branch_name stringclasses 149 values | text stringlengths 23 89.3M | directory_id stringlengths 40 40 | languages listlengths 1 19 | num_files int64 1 11.8k | repo_language stringclasses 38 values | repo_name stringlengths 6 114 | revision_id stringlengths 40 40 | snapshot_id stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|
refs/heads/master | <file_sep>#!/usr/bin/env bash
# deploy script for kubernetes cluster to google cloud
# build our production images for pushing to hub
docker build -t bennettdixon16/multi-client:latest -t bennettdixon16/multi-client:$GIT_SHA -f ./client/Dockerfile ./client
docker build -t bennettdixon16/multi-server:latest -t bennettdixon16/multi-server:$GIT_SHA -f ./server/Dockerfile ./server
docker build -t bennettdixon16/multi-worker:latest -t bennettdixon16/multi-worker:$GIT_SHA -f ./worker/Dockerfile ./worker
# push to docker hub (already logged in via travis)
docker push bennettdixon16/multi-client:latest
docker push bennettdixon16/multi-server:latest
docker push bennettdixon16/multi-worker:latest
docker push bennettdixon16/multi-client:$GIT_SHA
docker push bennettdixon16/multi-server:$GIT_SHA
docker push bennettdixon16/multi-worker:$GIT_SHA
# apply new configurations via gcloud (logged in via travis)
# IMPORTANT TO NOTE WE ARE LOGGED INTO GCLOUD VIA TRAVIS SO THIS EFFECTS PROD
kubectl apply -f k8s
# update the image the deployment uses (name unique to project)
kubectl set image deployments/server-deployment server=bennettdixon16/multi-server:$GIT_SHA
kubectl set image deployments/worker-deployment worker=bennettdixon16/multi-worker:$GIT_SHA
kubectl set image deployments/client-deployment client=bennettdixon16/multi-client:$GIT_SHA | b4ad7bbcf283bb68f18134343e3a5703f99eb624 | [
"Shell"
] | 1 | Shell | BennettDixon/multi-gke-k8s | 802e833f754ab63c45fb7596c203a9b9c519f651 | 27db8b3c68fe7bb267c8571bc885afc86123b941 |
refs/heads/master | <file_sep>#ifndef VOROPP_V_CONNECT_HH
#define VOROPP_V_CONNECT_HH
//To be used with voro++ to get full connectivity information
using namespace std;
#include "voro++_2d.hh"
#include <stdio.h>
#include <iostream>
#include <stdlib.h>
#include <vector>
namespace voro{
class v_connect{
public:
double minx,maxx,miny,maxy;
int nx,ny;
vector<int> vid;
vector<double> vpos;
vector<char> vbd;
int bd;
//# of generators
int ng;
//middle generator id
int mid;
//current size of vertl array/2
int current_vertices;
//number of vertices
int nv;
//for all i>=degenerate_vertices, the ith vertex is degenerate
int degenerate_vertices;
//current size of ed_to_vert array
int current_edges;
//number of edges
int ne;
//maps a generator's id to the place it was recieved in the input file
//i.e. if the first particle in the input file has id 20, then mp[20]=0;
int *mp;
//vertl[2*i]=x coordinate of ith vertex
double *vertl;
//vert_to_gen[i]= vector containing list of generators that ith vertex is touching
vector<int> *vert_to_gen;
//vert_to_ed[i]= vector containing list of edges that the i'th vertex is a member of
vector<int> *vert_to_ed;
//vert_on_bd[i].size()==0 if vertex i is not on boundary. if vertex i is on boundary it is a size 2 vector of the generators that define the part of the boundary it is on
vector<int> *vert_on_bd;
//gen_to_vert[i]= list of vertices that ith generatos is touching in cc order
vector<int> *gen_to_vert;
//gen_to_edge[i]= list of edges that the ith generator is touching in cc order (- edge number means ~edge number with reverse orientation
vector<int> *gen_to_ed;
//gen_to_gen_e[i]= list of neighbors of ith generator through edges in cc order
vector<int> *gen_to_gen_e;
//gen_to_gen_v[i]= list of neighbors of ith generator through degenerate vertices in cc order
vector<int> *gen_to_gen_v;
//ed_to_vert[2*i(+1)]=the vertex with the lower(higher) id constituting edge i
int *ed_to_vert;
//ed_to_gen[2*i(+1)]=the generator with the left-hand(right-hand) orientation touching the edge
vector<int> *ed_to_gen;
//ed_on_bd[i].size()==0 if edge i is not on the boundary. if it is, ed_on_bd[i] is a 2 element list of the generators that define that part of the boundary that it is on
vector<int> *ed_on_bd;
//vertex_is_generator[i]=(-1 if ith vertex is not a generator)(j if ith vertex is generator j)
int *vertex_is_generator;
//see above
int *generator_is_vertex;
v_connect(){
bd=-1;
nv=0;
ne=0;
//ng initialized during import routine.
minx=large_number;
maxx=-minx;
miny=minx;
maxy=maxx;
current_vertices=init_vertices;
current_edges=init_vertices;
vertl=new double[2*current_vertices];
vert_to_gen= new vector<int>[current_vertices];
vertex_is_generator=new int[current_vertices];
for(int i=0;i<current_vertices;i++) vertex_is_generator[i]=-1;
}
~v_connect(){
delete[] vertl;
delete[] vert_to_gen;
delete[] vert_to_ed;
delete[] vert_on_bd;
delete[] gen_to_vert;
delete[] gen_to_ed;
delete[] gen_to_gen_e;
delete[] gen_to_gen_v;
delete[] ed_to_vert;
delete[] ed_to_gen;
delete[] ed_on_bd;
delete[] mp;
}
void import(FILE *fp=stdin);
void import(const char* filename) {
FILE *fp=safe_fopen(filename, "r");
import(fp);
fclose(fp);
}
vector<int> groom_vertexg_help(double x, double y,double vx, double vy, vector<int> &g);
vector<int> groom_vertexg_help2(double x,double y,double vx,double vy,vector<int> &g);
inline void groom_vertexg(voronoicell_nonconvex_neighbor_2d &c){
double x=vpos[2*mp[c.my_id]],y=vpos[2*mp[c.my_id]+1];
for(int i=0;i<c.p;i++){
c.vertexg[i]=groom_vertexg_help(x ,y,(c.pts[2*i]*.5)+x,(c.pts[2*i+1]*.5)+y,c.vertexg[i]);
}
}
inline void add_memory_vector(vector<int>* &old,int size){
vector<int> *newv=new vector<int>[size];
for(int i=0;i<(size>>1);i++){
newv[i]=old[i];
}
delete [] old;
old=newv;
}
inline void add_memory_array(double* &old,int size){
double *newa= new double[2*size];
for(int i=0;i<(size);i++){
newa[i]=old[i];
}
delete [] old;
old=newa;
}
inline void add_memory_array(int* &old,int size){
int *newa=new int[2*size];
for(int i=0;i<size;i++){
newa[i]=old[i];
}
delete [] old;
old=newa;
}
inline void add_memory_table(unsigned int* &old,int size){
unsigned int* newt=new unsigned int[((size*size)/32)+1];
for(int i=0;i<((((size>>1)*(size>>1))/32)+1);i++){
newt[i]=old[i];
}
delete [] old;
old=newt;
}
//return true if vector contains the two elements
inline bool contains_two(vector<int> &a,int b, int c){
int i=0,j=0;
for(int k=0;k<a.size();k++){
if(a[k]==b){
i=1;
break;
}
}for(int k=0;k<a.size();k++){
if(a[k]==c){
j=1;
break;
}
}
if(i==1 && j==1) return true;
else return false;
}
//returns true if a vector contains the element
inline bool contains(vector<int> &a,int b){
for(int i=0;i<a.size();i++){
if(a[i]==b) return true;
}
return false;
}
//given a three element vector, returns an element != b or c
inline int not_these_two(vector<int> &a,int b, int c){
int d=-1;
for(int i=0;i<a.size();i++){
if(a[i]!=b && a[i]!=c){
d=a[i];
break;
}
}
return d;
}
//returns two elements the vectors have in common in g1,g2
inline void two_in_common(vector<int> a,vector<int> b,int &g1,int &g2){
g1=g2=-1;
for(int i=0;i<a.size();i++){
for(int k=0;k<b.size();k++){
if(a[i]==b[k]){
if(g1==-1) g1=a[i];
else if(a[i]==g1) continue;
else g2=a[i];
}
}
}
}
//if a and b share an element, returns it in g1, if not returns -1
inline void one_in_common(vector<int> a,vector<int> b,int &g1){
g1=-1;
for(int i=0;i<a.size();i++){
for(int j=0;j<b.size();j++){
if(a[i]==b[j]){
g1=a[i];
return;
}
}
}
}
//returns true iff a and b contain the same elements
inline bool contain_same_elements(vector<int> a,vector<int> b){
for(int i=0;i<a.size();i++){
if(!contains(b,a[i])) return false;
}
for(int i=0;i<b.size();i++){
if(!contains(a,b[i])) return false;
}
return true;
}
//returns any element in a !=b
inline int not_this_one(vector<int> a, int b){
for(int i=0;i<a.size();i++){
if(a[i]!=b) return a[i];
}
return -1;
}
//returns true if the elements of a are a subset of elements of b
inline bool subset(vector<int> a,vector<int> b){
for(int i=0;i<a.size();i++){
if(!contains(b,a[i])) return false;
}
return true;
}
inline double cross_product(double x1,double y1,double x2,double y2){
return ((x1*y2)-(y1*x2));
}
inline double dot_product(double x1, double y1, double x2, double y2){
return ((x1*x2)+(y1*y2));
}
void arrange_cc_x_to_gen(vector<int> &list,double cx,double cy);
void arrange_cc_gen_to_vert(vector<int> &list,double cx,double cy);
void arrange_cc_gen_to_ed(vector<int> &list);
void arrange_cc_vert_to_ed(vector<int> &list,double cx,double cy,int id);
void assemble_vertex();
void assemble_gen_ed();
void assemble_boundary();
void draw_gnu(FILE *fp=stdout);
inline void draw_gnu(const char *filename){
FILE *fp=safe_fopen(filename,"w");
draw_gnu(fp);
fclose(fp);
}
void draw_vtg_gnu(FILE *fp=stdout);
inline void draw_vtg_gnu(const char *filename){
FILE *fp=safe_fopen(filename,"w");
draw_vtg_gnu(fp);
fclose(fp);
}
void draw_gen_gen(FILE *fp=stdout);
inline void draw_gen_gen(const char *filename){
FILE *fp=safe_fopen(filename,"w");
draw_gen_gen(fp);
fclose(fp);
}
void label_vertices(FILE *fp=stdout);
inline void label_vertices(const char *filename){
FILE *fp=safe_fopen(filename,"w");
label_vertices(fp);
fclose(fp);
}
void label_generators(FILE *fp=stdout);
inline void label_generators(const char *filename){
FILE *fp=safe_fopen(filename,"w");
label_generators(fp);
fclose(fp);
}
void label_edges(FILE *fp=stdout);
inline void label_edges(const char *filename){
FILE *fp=safe_fopen(filename,"w");
label_edges(fp);
fclose(fp);
}
void label_centroids(FILE *fp=stdout);
inline void label_centroids(const char *filename){
FILE *fp=safe_fopen(filename,"w");
label_centroids(fp);
fclose(fp);
}
void print_gen_to_ed_table(FILE *fp=stdout);
inline void print_gen_to_ed_table(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_gen_to_ed_table(fp);
fclose(fp);
}
void print_gen_to_vert_table(FILE *fp=stdout);
inline void print_gen_to_vert_table(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_gen_to_vert_table(fp);
fclose(fp);
}
void print_vert_to_gen_table(FILE *fp=stdout);
inline void print_vert_to_gen_table(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_vert_to_gen_table(fp);
fclose(fp);
}
void print_ed_to_gen_table(FILE *fp=stdout);
inline void print_ed_to_gen_table(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_ed_to_gen_table(fp);
fclose(fp);
}
void print_vert_to_ed_table(FILE *fp=stdout);
inline void print_vert_to_ed_table(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_vert_to_ed_table(fp);
fclose(fp);
}
void print_vert_boundary(FILE *fp=stdout);
inline void print_vert_boundary(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_vert_boundary(fp);
fclose(fp);
}
void print_ed_boundary(FILE *fp=stdout);
inline void print_ed_boundary(const char *filename){
FILE *fp=safe_fopen(filename,"w");
print_ed_boundary(fp);
fclose(fp);
}
void add_memory_vertices();
void ascii_output(FILE *fp=stdout);
inline void ascii_output(const char *filename){
FILE *fp=safe_fopen(filename,"w");
ascii_output(fp);
fclose(fp);
}
double signed_area(int g);
void centroid(int g,double &x,double &y);
void lloyds(double epsilon);
void draw_median_mesh(FILE *fp=stdout);
inline void draw_median_mesh(const char *filename){
FILE *fp=safe_fopen(filename,"w");
draw_median_mesh(fp);
fclose(fp);
}
void draw_closest_generator(FILE *fp,double x,double y);
inline void draw_closest_generator(const char *filename,double x,double y){
FILE *fp=safe_fopen(filename,"w");
draw_closest_generator(fp,x,y);
fclose(fp);
}
};
}
#endif
<file_sep># Voro++ makefile
#
# Author : <NAME> (Harvard University / LBL)
# Email : <EMAIL>
# Date : August 30th 2011
# Load the common configuration file
include ../../config.mk
# List of executables
EXECUTABLES=cell_statistics custom_output radical
# Makefile rules
all: $(EXECUTABLES)
cell_statistics: cell_statistics.cc
$(CXX) $(CFLAGS) $(E_INC) $(E_LIB) -o cell_statistics cell_statistics.cc -lvoro++
custom_output: custom_output.cc
$(CXX) $(CFLAGS) $(E_INC) $(E_LIB) -o custom_output custom_output.cc -lvoro++
radical: radical.cc
$(CXX) $(CFLAGS) $(E_INC) $(E_LIB) -o radical radical.cc -lvoro++
clean:
rm -f $(EXECUTABLES)
.PHONY: all clean
<file_sep>#include "voro++_2d.hh"
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 6 by 6 grid, with
// an initial memory allocation of 16 particles per grid square.
container_boundary_2d con(-1,1,-1,1,6,6,false,false,8);
// Add 1000 random points to the container
con.start_boundary();
con.put(0,-0.8,-0.8);
con.put(1,0.8,-0.8);
con.put(2,0.8,0.8);
con.put(3,0.1,0.75);
con.put(4,0,-0.3);
con.put(5,-0.1,0.95);
con.put(6,-0.8,0.8);
con.put(7,-0.799,-0.6);
con.end_boundary();
for(i=0;i<100;i++) {
x=-1+2*rnd();
y=-1+2*rnd();
if(con.point_inside(x,y)) con.put(i+8,x,y);
}
con.draw_boundary_gnuplot("container_bd.gnu");
con.draw_particles("container_bd.par");
con.setup();
con.draw_cells_gnuplot("container_bd_v.gnu");
// Sum the Voronoi cell areas and compare to the container area
// double carea=1,varea=con.sum_cell_areas();
// printf("Total container area : %g\n"
// "Total Voronoi cell area : %g\n"
// "Difference : %g\n",carea,varea,varea-carea);
}
<file_sep>// Simple cell statistics demonstration code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
double x,y,z;
voronoicell v;
// Initialize the Voronoi cell to be a cube of side length 2, centered
// on the origin
v.init(-1,1,-1,1,-1,1);
// Remove one edge of the cell with a single plane cut
v.plane(1,1,0,2);
// Output the Voronoi cell to a file in gnuplot format
v.draw_gnuplot(0,0,0,"simple_cell.gnu");
// Output vertex-based statistics
printf("Total vertices : %d\n",v.p);
printf("Vertex positions : ");v.output_vertices();puts("");
printf("Vertex orders : ");v.output_vertex_orders();puts("");
printf("Max rad. sq. vertex : %g\n\n",0.25*v.max_radius_squared());
// Output edge-based statistics
printf("Total edges : %d\n",v.number_of_edges());
printf("Total edge distance : %g\n",v.total_edge_distance());
printf("Face perimeters : ");v.output_face_perimeters();puts("\n");
// Output face-based statistics
printf("Total faces : %d\n",v.number_of_faces());
printf("Surface area : %g\n",v.surface_area());
printf("Face freq. table : ");v.output_face_freq_table();puts("");
printf("Face orders : ");v.output_face_orders();puts("");
printf("Face areas : ");v.output_face_areas();puts("");
printf("Face normals : ");v.output_normals();puts("");
printf("Face vertices : ");v.output_face_vertices();puts("\n");
// Output volume-based statistics
v.centroid(x,y,z);
printf("Volume : %g\n"
"Centroid vector : (%g,%g,%g)\n",v.volume(),x,y,z);
}
<file_sep>#include <cstdio>
#include <cmath>
#include "voro++_2d.hh"
using namespace voro;
#include "omp.h"
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i,l,n=10;double x,y,r,t1,t2;
while(n<10000000) {
container_quad_2d con1(-1,1,-1,1);
l=int(sqrt(double(n))/3.46)+1;
container_2d con2(-1,1,-1,1,l,l,false,false,8);
for(i=0;i<n;i++) {
x=2*rnd()-1;
y=2*rnd()-1;
r=1;//(x*x+y*y)*0.5;
con1.put(i,x*r,y*r);
con2.put(i,x*r,y*r);
}
con1.setup_neighbors();
t2=omp_get_wtime();
con2.compute_all_cells();
t2=omp_get_wtime()-t2;
t1=omp_get_wtime();
con1.compute_all_cells();
t1=omp_get_wtime()-t1;
printf("%d %g %g\n",n,t1,t2);
n+=n>>2;
}
}
<file_sep>#include <cmath>
using namespace std;
#include "voro++_2d.hh"
using namespace voro;
const double pi=3.1415926535897932384626433832795;
const double radius=0.5;
const int n=5;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i=0;double x,y,arg;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 10 by 10 grid, with
// an initial memory allocation of 8 particles per grid square.
container_2d con(-1,1,-1,1,10,10,false,false,8);
// Add circular wall object
wall_plane_2d *wc[n];
for(i=0,arg=0;i<n;i++,arg+=2*pi/n) {
wc[i]=new wall_plane_2d(sin(arg),-cos(arg),radius);
con.add_wall(wc[i]);
}
// Add 1000 random points to the container
while(i<1000) {
x=2*rnd()-1;
y=2*rnd()-1;
if(con.point_inside(x,y)) {
con.put(i,x,y);
i++;
}
}
// Output the particle positions to a file
con.draw_particles("polygon.par");
// Output the Voronoi cells to a file, in the gnuplot format
con.draw_cells_gnuplot("polygon.gnu");
// Sum the Voronoi cell areas and compare to the circle area
double carea=n*radius*radius*tan(pi/n),varea=con.sum_cell_areas();
printf("Total polygon area : %g\n"
"Total Voronoi cell area : %g\n"
"Difference : %g\n",carea,varea,varea-carea);
// Since they were dynamically allocated, delete the wall_plane_2d
// objects
for(i=0;i<n;i++) delete wc[i];
}
<file_sep>// Cylindrical wall example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-6,x_max=6;
const double y_min=-6,y_max=6;
const double z_min=-6,z_max=6;
// Set the computational grid size
const int n_x=6,n_y=6,n_z=6;
struct wall_cylinder_inv : public wall {
public:
wall_cylinder_inv(double xc_,double yc_,double zc_,double xa_,double ya_,double za_,double rc_,int w_id_=-99)
: w_id(w_id_), xc(xc_), yc(yc_), zc(zc_), xa(xa_), ya(ya_), za(za_),
asi(1/(xa_*xa_+ya_*ya_+za_*za_)), rc(rc_) {}
bool point_inside(double x,double y,double z) {
double xd=x-xc,yd=y-yc,zd=z-zc;
double pa=(xd*xa+yd*ya+zd*za)*asi;
xd-=xa*pa;yd-=ya*pa;zd-=za*pa;
return xd*xd+yd*yd+zd*zd>rc*rc;
}
template<class v_cell>
bool cut_cell_base(v_cell &c,double x,double y,double z) {
double xd=x-xc,yd=y-yc,zd=z-zc;
double pa=(xd*xa+yd*ya+zd*za)*asi;
xd-=xa*pa;yd-=ya*pa;zd-=za*pa;
pa=xd*xd+yd*yd+zd*zd;
if(pa>1e-5) {
pa=2*(sqrt(pa)*rc-pa);
return c.nplane(-xd,-yd,-zd,-pa,w_id);
}
return true;
}
bool cut_cell(voronoicell &c,double x,double y,double z) {return cut_cell_base(c,x,y,z);}
bool cut_cell(voronoicell_neighbor &c,double x,double y,double z) {return cut_cell_base(c,x,y,z);}
private:
const int w_id;
const double xc,yc,zc,xa,ya,za,asi,rc;
};
int main() {
int i;double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block.
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Add a cylindrical wall to the container
wall_cylinder_inv cyl(0,0,0,0,1,0,4.2);
con.add_wall(cyl);
// Place particles in a regular grid within the frustum, for points
// which are within the wall boundaries
for(z=-5.5;z<6;z+=1) for(y=-5.5;y<6;y+=1) for(x=-5.5;x<6;x+=1)
if (con.point_inside(x,y,z)) {con.put(i,x,y,z);i++;}
// Output the particle positions in POV-Ray format
con.draw_particles_pov("cylinder_inv_p.pov");
// Output the Voronoi cells in POV-Ray format
con.draw_cells_pov("cylinder_inv_v.pov");
// Output the particle positions in gnuplot format
con.draw_particles("cylinder_inv.par");
// Output the Voronoi cells in gnuplot format
con.draw_cells_gnuplot("cylinder_inv.gnu");
}
<file_sep>// Tetrahedron example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-2,x_max=2;
const double y_min=-2,y_max=2;
const double z_min=-2,z_max=2;
// Set up the number of blocks that the container is divided
// into
const int n_x=7,n_y=7,n_z=7;
// Set the number of particles that are going to be randomly
// introduced
const int particles=64;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i=0;
double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for 8
// particles within each computational block.
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Add four plane walls to the container to make a tetrahedron
wall_plane p1(1,1,1,1);con.add_wall(p1);
wall_plane p2(-1,-1,1,1);con.add_wall(p2);
wall_plane p3(1,-1,-1,1);con.add_wall(p3);
wall_plane p4(-1,1,-1,1);con.add_wall(p4);
// Randomly insert particles into the container, checking that they lie
// inside the tetrahedron
while(i<particles) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
if (con.point_inside(x,y,z)) {
con.put(i,x,y,z);i++;
}
}
// Output the particle positions and the Voronoi cells in Gnuplot and
// POV-Ray formats
con.draw_particles("tetrahedron_p.gnu");
con.draw_cells_gnuplot("tetrahedron_v.gnu");
con.draw_particles_pov("tetrahedron_p.pov");
con.draw_cells_pov("tetrahedron_v.pov");
}
<file_sep>/** \file container_2d.cc
* \brief Function implementations for the container_2d class. */
#include "container_2d.hh"
/** The class constructor sets up the geometry of container, initializing the
* minimum and maximum coordinates in each direction, and setting whether each
* direction is periodic or not. It divides the container into a rectangular
* grid of blocks, and allocates memory for each of these for storing particle
* positions and IDs.
* \param[in] (ax_,bx_) the minimum and maximum x coordinates.
* \param[in] (ay_,by_) the minimum and maximum y coordinates.
* \param[in] (nx_,ny_) the number of grid blocks in each of the three
* coordinate directions.
* \param[in] (xperiodic_,yperiodic_) flags setting whether the container is periodic
* in each coordinate direction.
* \param[in] init_mem the initial memory allocation for each block. */
container_2d::container_2d(double ax_,double bx_,double ay_,
double by_,int nx_,int ny_,bool xperiodic_,bool yperiodic_,int init_mem)
: ax(ax_), bx(bx_), ay(ay_), by(by_), boxx((bx_-ax_)/nx_), boxy((by_-ay_)/ny_),
xsp(1/boxx), ysp(1/boxy), nx(nx_), ny(ny_), nxy(nx*ny),
xperiodic(xperiodic_), yperiodic(yperiodic_),
co(new int[nxy]), mem(new int[nxy]), id(new int*[nxy]), p(new double*[nxy]) {
int l;
for(l=0;l<nxy;l++) co[l]=0;
for(l=0;l<nxy;l++) mem[l]=init_mem;
for(l=0;l<nxy;l++) id[l]=new int[init_mem];
for(l=0;l<nxy;l++) p[l]=new double[2*init_mem];
}
/** The container destructor frees the dynamically allocated memory. */
container_2d::~container_2d() {
int l;
for(l=nxy-1;l>=0;l--) delete [] p[l];
for(l=nxy-1;l>=0;l--) delete [] id[l];
delete [] p;
delete [] id;
delete [] mem;
delete [] co;
}
/** Put a particle into the correct region of the container.
* \param[in] n the numerical ID of the inserted particle.
* \param[in] (x,y) the position vector of the inserted particle. */
void container_2d::put(int n,double x,double y) {
int ij;
if(put_locate_block(ij,x,y)) {
id[ij][co[ij]]=n;
double *pp(p[ij]+2*co[ij]++);
*(pp++)=x;*pp=y;
}
}
/** This routine takes a particle position vector, tries to remap it into the
* primary domain. If successful, it computes the region into which it can be
* stored and checks that there is enough memory within this region to store
* it.
* \param[out] ij the region index.
* \param[in,out] (x,y) the particle position, remapped into the primary
* domain if necessary.
* \return True if the particle can be successfully placed into the container,
* false otherwise. */
inline bool container_2d::put_locate_block(int &ij,double &x,double &y) {
if(put_remap(ij,x,y)) {
if(co[ij]==mem[ij]) add_particle_memory(ij);
return true;
}
#if VOROPP_REPORT_OUT_OF_BOUNDS ==1
fprintf(stderr,"Out of bounds: (x,y)=(%g,%g)\n",x,y);
#endif
return false;
}
/** Takes a particle position vector and computes the region index into which
* it should be stored. If the container is periodic, then the routine also
* maps the particle position to ensure it is in the primary domain. If the
* container is not periodic, the routine bails out.
* \param[out] ij the region index.
* \param[in,out] (x,y) the particle position, remapped into the primary
* domain if necessary.
* \return True if the particle can be successfully placed into the container,
* false otherwise. */
inline bool container_2d::put_remap(int &ij,double &x,double &y) {
int l;
ij=step_int((x-ax)*xsp);
if(xperiodic) {l=step_mod(ij,nx);x+=boxx*(l-ij);ij=l;}
else if(ij<0||ij>=nx) return false;
int j(step_int((y-ay)*ysp));
if(yperiodic) {l=step_mod(j,ny);y+=boxy*(l-j);j=l;}
else if(j<0||j>=ny) return false;
ij+=nx*j;
return true;
}
/** Increase memory for a particular region.
* \param[in] i the index of the region to reallocate. */
void container_2d::add_particle_memory(int i) {
int l,*idp;double *pp;
mem[i]<<=1;
if(mem[i]>max_particle_memory)
voropp_fatal_error("Absolute maximum particle memory allocation exceeded",VOROPP_MEMORY_ERROR);
#if VOROPP_VERBOSE >=3
fprintf(stderr,"Particle memory in region %d scaled up to %d\n",i,mem[i]);
#endif
idp=new int[mem[i]];
for(l=0;l<co[i];l++) idp[l]=id[i][l];
pp=new double[2*mem[i]];
for(l=0;l<2*co[i];l++) pp[l]=p[i][l];
delete [] id[i];id[i]=idp;
delete [] p[i];p[i]=pp;
}
/** Imports a list of particles from an input stream.
* \param[in] fp a file handle to read from. */
void container_2d::import(FILE *fp) {
int i,j;
double x,y;
while((j=fscanf(fp,"%d %lg %lg",&i,&x,&y))==3) put(i,x,y);
if(j!=EOF) voropp_fatal_error("File import error",VOROPP_FILE_ERROR);
}
/** Clears a container of particles. */
void container_2d::clear() {
for(int* cop=co;cop<co+nxy;cop++) *cop=0;
}
/** Dumps all the particle positions and IDs to a file.
* \param[in] fp the file handle to write to. */
void container_2d::draw_particles(FILE *fp) {
int ij,q;
for(ij=0;ij<nxy;ij++) for(q=0;q<co[ij];q++)
fprintf(fp,"%d %g %g\n",id[ij][q],p[ij][2*q],p[ij][2*q+1]);
}
/** Dumps all the particle positions in POV-Ray format.
* \param[in] fp the file handle to write to. */
void container_2d::draw_particles_pov(FILE *fp) {
int ij,q;
for(ij=0;ij<nxy;ij++) for(q=0;q<co[ij];q++)
fprintf(fp,"// id %d\nsphere{<%g,%g,0>,s\n",id[ij][q],p[ij][2*q],p[ij][2*q+1]);
}
/** Computes the Voronoi cells for all particles and saves the output in
* gnuplot format.
* \param[in] fp a file handle to write to. */
void container_2d::draw_cells_gnuplot(FILE *fp) {
int i,j,ij=0,q;
double x,y;
voronoicell_2d c;
for(j=0;j<ny;j++) for(i=0;i<nx;i++,ij++) for(q=0;q<co[ij];q++) {
x=p[ij][2*q];y=p[ij][2*q+1];
if(compute_cell_sphere(c,i,j,ij,q,x,y)) c.draw_gnuplot(x,y,fp);
}
}
/** Computes the Voronoi cells for all particles within a rectangular box, and
* saves the output in POV-Ray format.
* \param[in] fp a file handle to write to. */
void container_2d::draw_cells_pov(FILE *fp) {
int i,j,ij=0,q;
double x,y;
voronoicell_2d c;
for(j=0;j<ny;j++) for(i=0;i<nx;i++,ij++) for(q=0;q<co[ij];q++) {
x=p[ij][2*q];y=p[ij][2*q+1];
if(compute_cell_sphere(c,i,j,ij,q,x,y)) {
fprintf(fp,"// cell %d\n",id[ij][q]);
c.draw_pov(x,y,0,fp);
}
}
}
/** Computes the Voronoi cells for all particles in the container, and for each
* cell, outputs a line containing custom information about the cell structure.
* The output format is specified using an input string with control sequences
* similar to the standard C printf() routine.
* \param[in] format the format of the output lines, using control sequences to
* denote the different cell statistics.
* \param[in] fp a file handle to write to. */
void container_2d::print_custom(const char *format,FILE *fp) {
int i,j,ij=0,q;
double x,y;
voronoicell_2d c;
for(j=0;j<ny;j++) for(i=0;i<nx;i++,ij++) for(q=0;q<co[ij];q++) {
x=p[ij][2*q];y=p[ij][2*q+1];
if(compute_cell_sphere(c,i,j,ij,q,x,y)) c.output_custom(format,id[ij][q],x,y,default_radius,fp);
}
}
/** Initializes a voronoicell_2d class to fill the entire container.
* \param[in] c a reference to a voronoicell_2d class.
* \param[in] (x,y) the position of the particle that . */
bool container_2d::initialize_voronoicell(voronoicell_2d &c,double x,double y) {
double x1,x2,y1,y2;
if(xperiodic) x1=-(x2=0.5*(bx-ax));else {x1=ax-x;x2=bx-x;}
if(yperiodic) y1=-(y2=0.5*(by-ay));else {y1=ay-y;y2=by-y;}
c.init(x1,x2,y1,y2);
return true;
}
/** Computes all Voronoi cells and sums their areas.
* \return The computed area. */
double container_2d::sum_cell_areas() {
int i,j,ij=0,q;
double x,y,sum=0;
voronoicell_2d c;
for(j=0;j<ny;j++) for(i=0;i<nx;i++,ij++) for(q=0;q<co[ij];q++) {
x=p[ij][2*q];y=p[ij][2*q+1];
if(compute_cell_sphere(c,i,j,ij,q,x,y)) sum+=c.area();
}
return sum;
}
/** Computes all of the Voronoi cells in the container, but does nothing
* with the output. It is useful for measuring the pure computation time
* of the Voronoi algorithm, without any additional calculations such as
* volume evaluation or cell output. */
void container_2d::compute_all_cells() {
int i,j,ij=0,q;
voronoicell_2d c;
for(j=0;j<ny;j++) for(i=0;i<nx;i++,ij++) for(q=0;q<co[ij];q++)
compute_cell_sphere(c,i,j,ij,q);
}
/** This routine computes the Voronoi cell for a give particle, by successively
* testing over particles within larger and larger concentric circles. This
* routine is simple and fast, although it may not work well for anisotropic
* arrangements of particles.
* \param[in,out] c a reference to a voronoicell object.
* \param[in] (i,j) the coordinates of the block that the test particle is
* in.
* \param[in] ij the index of the block that the test particle is in, set to
* i+nx*j.
* \param[in] s the index of the particle within the test block.
* \param[in] (x,y) the coordinates of the particle.
* \return False if the Voronoi cell was completely removed during the
* computation and has zero volume, true otherwise. */
bool container_2d::compute_cell_sphere(voronoicell_2d &c,int i,int j,int ij,int s,double x,double y) {
// This length scale determines how large the spherical shells should
// be, and it should be set to approximately the particle diameter
const double length_scale=0.5*sqrt((bx-ax)*(by-ay)/(nx*ny));
double x1,y1,qx,qy,lr=0,lrs=0,ur,urs,rs;
int q,t;
voropp_loop_2d l(*this);
if(!initialize_voronoicell(c,x,y)) return false;
// Now the cell is cut by testing neighboring particles in concentric
// shells. Once the test shell becomes twice as large as the Voronoi
// cell we can stop testing.
while(lrs<c.max_radius_squared()) {
ur=lr+0.5*length_scale;urs=ur*ur;
t=l.init(x,y,ur,qx,qy);
do {
for(q=0;q<co[t];q++) {
x1=p[t][2*q]+qx-x;y1=p[t][2*q+1]+qy-y;
rs=x1*x1+y1*y1;
if(lrs-tolerance<rs&&rs<urs&&(q!=s||ij!=t)) {
if(!c.plane(x1,y1,rs)) return false;
}
}
} while((t=l.inc(qx,qy))!=-1);
lr=ur;lrs=urs;
}
return true;
}
/** Creates a voropp_loop_2d object, by setting the necessary constants about the
* container geometry from a pointer to the current container class.
* \param[in] con a reference to the associated container class. */
voropp_loop_2d::voropp_loop_2d(container_2d &con) : boxx(con.bx-con.ax), boxy(con.by-con.ay),
xsp(con.xsp),ysp(con.ysp),
ax(con.ax),ay(con.ay),nx(con.nx),ny(con.ny),nxy(con.nxy),
xperiodic(con.xperiodic),yperiodic(con.yperiodic) {}
/** Initializes a voropp_loop_2d object, by finding all blocks which are within a
* given sphere. It calculates the index of the first block that needs to be
* tested and sets the periodic displacement vector accordingly.
* \param[in] (vx,vy) the position vector of the center of the sphere.
* \param[in] r the radius of the sphere.
* \param[out] (px,py) the periodic displacement vector for the first block to
* be tested.
* \return The index of the first block to be tested. */
int voropp_loop_2d::init(double vx,double vy,double r,double &px,double &py) {
ai=step_int((vx-ax-r)*xsp);
bi=step_int((vx-ax+r)*xsp);
if(!xperiodic) {
if(ai<0) {ai=0;if(bi<0) bi=0;}
if(bi>=nx) {bi=nx-1;if(ai>=nx) ai=nx-1;}
}
aj=step_int((vy-ay-r)*ysp);
bj=step_int((vy-ay+r)*ysp);
if(!yperiodic) {
if(aj<0) {aj=0;if(bj<0) bj=0;}
if(bj>=ny) {bj=ny-1;if(aj>=ny) aj=ny-1;}
}
i=ai;j=aj;
aip=ip=step_mod(i,nx);apx=px=step_div(i,nx)*boxx;
ajp=jp=step_mod(j,ny);apy=py=step_div(j,ny)*boxy;
inc1=aip-step_mod(bi,nx)+nx;
s=aip+nx*ajp;
return s;
}
/** Initializes a voropp_loop_2d object, by finding all blocks which overlap a given
* rectangular box. It calculates the index of the first block that needs to be
* tested and sets the periodic displacement vector (px,py,pz) accordingly.
* \param[in] (xmin,xmax) the minimum and maximum x coordinates of the box.
* \param[in] (ymin,ymax) the minimum and maximum y coordinates of the box.
* \param[out] (px,py) the periodic displacement vector for the first block
* to be tested.
* \return The index of the first block to be tested. */
int voropp_loop_2d::init(double xmin,double xmax,double ymin,double ymax,double &px,double &py) {
ai=step_int((xmin-ax)*xsp);
bi=step_int((xmax-ax)*xsp);
if(!xperiodic) {
if(ai<0) {ai=0;if(bi<0) bi=0;}
if(bi>=nx) {bi=nx-1;if(ai>=nx) ai=nx-1;}
}
aj=step_int((ymin-ay)*ysp);
bj=step_int((ymax-ay)*ysp);
if(!yperiodic) {
if(aj<0) {aj=0;if(bj<0) bj=0;}
if(bj>=ny) {bj=ny-1;if(aj>=ny) aj=ny-1;}
}
i=ai;j=aj;
aip=ip=step_mod(i,nx);apx=px=step_div(i,nx)*boxx;
ajp=jp=step_mod(j,ny);apy=py=step_div(j,ny)*boxy;
inc1=aip-step_mod(bi,nx)+nx;
s=aip+nx*ajp;
return s;
}
/** Returns the next block to be tested in a loop, and updates the periodicity
* vector if necessary.
* \param[in,out] (px,py) the current block on entering the function, which is
* updated to the next block on exiting the function. */
int voropp_loop_2d::inc(double &px,double &py) {
if(i<bi) {
i++;
if(ip<nx-1) {ip++;s++;} else {ip=0;s+=1-nx;px+=boxx;}
return s;
} else if(j<bj) {
i=ai;ip=aip;px=apx;j++;
if(jp<ny-1) {jp++;s+=inc1;} else {jp=0;s+=inc1-nxy;py+=boxy;}
return s;
} else return -1;
}
<file_sep>#ifndef VOROPP_VOROPP_2D_HH
#define VOROPP_VOROPP_2D_HH
#include "config.hh"
#include "common.hh"
#include "cell_2d.hh"
#include "v_base_2d.hh"
#include "rad_option.hh"
#include "container_2d.hh"
#include "v_compute_2d.hh"
#include "c_loops_2d.hh"
#include "wall_2d.hh"
#include "cell_nc_2d.hh"
#include "ctr_boundary_2d.hh"
#include "ctr_quad_2d.hh"
#endif
<file_sep>// Voro++, a 3D cell-based Voronoi library
//
// Author : <NAME> (LBL / UC Berkeley)
// Email : <EMAIL>
// Date : May 18th 2011
/** \file common.cc
* \brief Implementations of the small helper functions. */
#include "common.hh"
namespace voro {
/** \brief Prints a vector of integers.
*
* Prints a vector of integers.
* \param[in] v the vector to print.
* \param[in] fp the file stream to print to. */
void voro_print_vector(std::vector<int> &v,FILE *fp) {
int k(0),s(v.size());
while(k+4<s) {
fprintf(fp,"%d %d %d %d ",v[k],v[k+1],v[k+2],v[k+3]);
k+=4;
}
if(k+3<=s) {
if(k+4==s) fprintf(fp,"%d %d %d %d",v[k],v[k+1],v[k+2],v[k+3]);
else fprintf(fp,"%d %d %d",v[k],v[k+1],v[k+2]);
} else {
if(k+2==s) fprintf(fp,"%d %d",v[k],v[k+1]);
else fprintf(fp,"%d",v[k]);
}
}
/** \brief Prints a vector of doubles.
*
* Prints a vector of doubles.
* \param[in] v the vector to print.
* \param[in] fp the file stream to print to. */
void voro_print_vector(std::vector<double> &v,FILE *fp) {
int k(0),s(v.size());
while(k+4<s) {
fprintf(fp,"%g %g %g %g ",v[k],v[k+1],v[k+2],v[k+3]);
k+=4;
}
if(k+3<=s) {
if(k+4==s) fprintf(fp,"%g %g %g %g",v[k],v[k+1],v[k+2],v[k+3]);
else fprintf(fp,"%g %g %g",v[k],v[k+1],v[k+2]);
} else {
if(k+2==s) fprintf(fp,"%g %g",v[k],v[k+1]);
else fprintf(fp,"%g",v[k]);
}
}
/** \brief Opens a file and checks the operation was successful.
*
* Opens a file, and checks the return value to ensure that the operation
* was successful.
* \param[in] filename the file to open.
* \param[in] mode the cstdio fopen mode to use.
* \return The file handle. */
FILE* safe_fopen(const char *filename,const char *mode) {
FILE *fp(fopen(filename,mode));
if(fp==NULL) {
fprintf(stderr,"voro++: Unable to open file '%s'\n",filename);
exit(VOROPP_FILE_ERROR);
}
return fp;
}
}
<file_sep>// File import example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-5,x_max=5;
const double y_min=-5,y_max=5;
const double z_min=0,z_max=10;
// Set up the number of blocks that the container is divided into
const int n_x=6,n_y=6,n_z=6;
int main() {
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
//Randomly add particles into the container
con.import("pack_ten_cube");
// Save the Voronoi network of all the particles to text files
// in gnuplot and POV-Ray formats
con.draw_cells_gnuplot("pack_ten_cube.gnu");
con.draw_cells_pov("pack_ten_cube_v.pov");
// Output the particles in POV-Ray format
con.draw_particles_pov("pack_ten_cube_p.pov");
}
<file_sep>// Voronoi calculation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
// Set up the number of blocks that the container is divided into
const int n_x=6,n_y=6,n_z=6;
// Set the number of particles that are going to be randomly introduced
const int particles=20;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Randomly add particles into the container
for(i=0;i<particles;i++) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
con.put(i,x,y,z);
}
double vo[400],ar[400],tvo,tar;
for(i=0;i<400;i++) vo[i]=0;
for(i=0;i<400;i++) ar[i]=0;
voronoicell c;
c_loop_all cl(con);
if(cl.start()) do if(con.compute_cell(c,cl)) {
for(i=0;i<400;i++) {
c.minkowski(i*0.005,tvo,tar);
vo[i]+=tvo;ar[i]+=tar;
}
} while(cl.inc());
for(i=0;i<400;i++) printf("%g %g %g\n",i*0.005,vo[i],ar[i]);
}
<file_sep>#ifndef QUAD_MARCH_HH
#define QUAD_MARCH_HH
#include "ctr_quad_2d.hh"
namespace voro {
template<int ca>
class quad_march {
public:
const int ma;
int s;
int ns;
int p;
quadtree* list[32];
quad_march(quadtree *q);
void step();
inline quadtree* cu() {
return list[p];
}
private:
inline quadtree* up(quadtree* q) {
return ca<2?(ca==0?q->qne:q->qnw):(ca==2?q->qnw:q->qsw);
}
inline quadtree* down(quadtree* q) {
return ca<2?(ca==0?q->qse:q->qsw):(ca==2?q->qne:q->qse);
}
};
}
#endif
<file_sep># Voro++ makefile
#
# Author : <NAME> (Harvard University / LBL)
# Email : <EMAIL>
# Date : August 30th 2011
# Load the common configuration file
include ../../config.mk
# List of executables
EXECUTABLES=rad_test finite_sys cylinder_inv single_cell_2d period sphere_mesh lloyd_box import_rahman import_nguyen polycrystal_rahman random_points_10 random_points_200 import_freeman voro_lf split_cell ghost_test neigh_test tri_mesh sphere r_pts_interface minkowski
# Makefile rules
all: $(EXECUTABLES)
%: %.cc
$(CXX) $(CFLAGS) $(E_INC) $(E_LIB) -o $@ $< -lvoro++
clean:
rm -f $(EXECUTABLES)
.PHONY: all clean
<file_sep>#include "common.cc"
#include "cell_2d.cc"
#include "c_loops_2d.cc"
#include "v_base_2d.cc"
#include "container_2d.cc"
#include "v_compute_2d.cc"
#include "wall_2d.cc"
#include "cell_nc_2d.cc"
#include "ctr_boundary_2d.cc"
<file_sep>// Voronoi calculation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
const double cvol=(x_max-x_min)*(y_max-y_min)*(x_max-x_min);
// Set up the number of blocks that the container is divided into
const int n_x=6,n_y=6,n_z=6;
// Set the number of particles that are going to be randomly introduced
const int particles=20;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container_periodic_poly con(2,0.5,2,0,0,2,n_x,n_y,n_z,8);
// Randomly add particles into the container
for(i=0;i<4;i++) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
con.put(i,x,y,0,1);
}
// Output the particle positions in gnuplot format
con.draw_particles("ghost_test_p.gnu");
// Output the Voronoi cells in gnuplot format
con.draw_cells_gnuplot("ghost_test_v.gnu");
// Open file for test ghost cell
FILE *fp=safe_fopen("ghost_test_c.gnu","w");
voronoicell c;
// Compute a range of ghost cells
// for(y=-3.5;y<3.5;y+=0.05) if(con.compute_ghost_cell(c,1,y,0,1))
// c.draw_gnuplot(1,y,0,fp);
// Compute a single ghost cell
if(con.compute_ghost_cell(c,1.56,0.67,0,1)) c.draw_gnuplot(1.56,0.67,0,fp);
// Close ghost cell file
fclose(fp);
// Draw the domain
con.draw_domain_gnuplot("ghost_test_d.gnu");
}
<file_sep>// Voronoi calculation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : April 14th 2013
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
const double cvol=(x_max-x_min)*(y_max-y_min)*(x_max-x_min);
// Set up the number of blocks that the container is divided into
const int n_x=6,n_y=6,n_z=6;
// Set the number of particles that are going to be randomly introduced
const int particles=40;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y,z;
voronoicell_neighbor c;
std::vector<int> neigh;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
true,true,true,8);
// Randomly add particles into the container
for(i=0;i<particles;i++) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
con.put(i,x,y,z);
}
// Output the particle positions in gnuplot format
con.draw_particles("random_points_p.gnu");
// Output the Voronoi cells in gnuplot format
con.draw_cells_gnuplot("random_points_v.gnu");
// Loop over all of the particles and compute their Voronoi cells
c_loop_all cl(con);
if(cl.start()) do if(con.compute_cell(c,cl)) {
cl.pos(x,y,z);i=cl.pid();
c.neighbors(neigh);
// Print out the information about neighbors
printf("Particle %2d at (% 1.3f,% 1.3f,% 1.3f):",i,x,y,z);
for(unsigned int j=0;j<neigh.size();j++) printf(" %d",neigh[j]);
puts("");
} while (cl.inc());
}
<file_sep>#include "quad_march.hh"
namespace voro {
template<int ca>
quad_march<ca>::quad_march(quadtree *q) : ma(1<<30), s(0), p(0) {
list[p]=q;
while(list[p]->id==NULL) {list[p+1]=up(list[p]);p++;}
ns=ma>>p;
}
template<int ca>
void quad_march<ca>::step() {
if(ns>=ma) {s=ma+1;return;}
while(down(list[p-1])==list[p]) p--;
list[p]=down(list[p-1]);
while(list[p]->id==NULL) {list[p+1]=up(list[p]);p++;}
s=ns;ns+=ma>>p;
}
// Explicit instantiation
template class quad_march<0>;
template class quad_march<1>;
template class quad_march<2>;
template class quad_march<3>;
}
<file_sep>#include "v_connect.hh"
#include <math.h>
#include <stdio.h>
namespace voro{
void v_connect::import(FILE *fp){
bool neg_label=false,boundary_track=false,start=false;
char *buf(new char[512]);
int i=0,id;
double x, y,pad=.05;
while(fgets(buf,512,fp)!=NULL) {
if(strcmp(buf,"#Start\n")==0||strcmp(buf,"# Start\n")==0) {
// Check that two consecutive start tokens haven't been
// encountered
if(boundary_track) voro_fatal_error("File import error - two consecutive start tokens found",VOROPP_FILE_ERROR);
start=true;boundary_track=true;
} else if(strcmp(buf,"#End\n")==0||strcmp(buf,"# End\n")==0||
strcmp(buf,"#End")==0||strcmp(buf,"# End")==0) {
// Check that two consecutive end tokens haven't been
// encountered
if(start) voro_fatal_error("File import error - end token immediately after start token",VOROPP_FILE_ERROR);
if(!boundary_track) voro_fatal_error("File import error - found end token without start token",VOROPP_FILE_ERROR);
vbd[i-1]|=2;boundary_track=false;
} else {
if(!boundary_track && bd==-1) bd=i;
// Try and read three entries from the line
if(sscanf(buf,"%d %lg %lg",&id,&x,&y)!=3) voro_fatal_error("File import error #1",VOROPP_FILE_ERROR);
vid.push_back(id);
vpos.push_back(x);
vpos.push_back(y);
vbd.push_back(start?1:0);
i++;
// Determine bounds
if(id<0) neg_label=true;
if(id>mid) mid=id;
if(x<minx) minx=x;
if(x>maxx) maxx=x;
if(y<miny) miny=y;
if(y>maxy) maxy=y;
start=false;
}
}
if(boundary_track) voro_fatal_error("File import error - boundary not finished",VOROPP_FILE_ERROR);
if(!feof(fp)) voro_fatal_error("File import error #2",VOROPP_FILE_ERROR);
delete [] buf;
// Add small amount of padding to container bounds
double dx=maxx-minx,dy=maxy-miny;
minx-=pad*dx;maxx+=pad*dx;dx+=2*pad*dx;
miny-=pad*dy;maxy+=pad*dy;dy+=2*pad*dy;
// Guess the optimal computationl grid, aiming at eight particles per
// grid square
double lscale=sqrt(8.0*dx*dy/i);
nx=(int)(dx/lscale)+1,ny=(int)(dy/lscale)+1;
ng=i;
gen_to_vert= new vector<int>[i];
gen_to_ed= new vector<int>[i];
gen_to_gen_e= new vector<int>[i];
gen_to_gen_v=new vector<int>[i];
generator_is_vertex=new int[i];
for(int j=0;j<ng;j++) generator_is_vertex[j]=-1;
mp=new int[mid+1];
for(int j=0;j<ng;j++) mp[vid[j]]=j;
}
// Assemble vert_to_gen,gen_to_vert,vert_to_ed,ed_to_vert
void v_connect::assemble_vertex(){
bool arrange=false;
int cv,lv,cvi,lvi,fvi,j,id,pcurrent_vertices=init_vertices,vert_size=0,g1,g2,g3,gl1,gl2,gl3,i,pne=0;
int *pmap;
int *ped_to_vert=new int[2*current_edges];
bool seencv=false,seenlv=false;
vector<int> gens;
vector<int> *pvert_to_gen= new vector<int>[pcurrent_vertices];
vector<int> *pgen_to_vert=new vector<int>[ng];
vector<int> problem_verts;
vector<int> problem_verts21;
vector<int> problem_verts32;
vector<int> problem_gen_to_vert;
double gx1,gy1,gx2,gy2;
double *pvertl=new double[2*pcurrent_vertices];
unsigned int *globvertc=new unsigned int[2*(ng+1)*ng*ng];
for(int i=0;i<2*((ng+1)*ng*ng);i++){
globvertc[i]=0;
}
cout << "2.1" << endl;
double x,y,vx,vy;
// Create container
container_boundary_2d con(minx,maxx,miny,maxy,nx,ny,false,false,16);
// Import data
for(j=0;j<vid.size();j++) {
if(vbd[j]&1) con.start_boundary();
con.put(vid[j],vpos[2*j],vpos[2*j+1]);
if(vbd[j]&2) con.end_boundary();
}
// Carry out all of the setup prior to computing any Voronoi cells
con.setup();
con.full_connect_on();
voronoicell_nonconvex_neighbor_2d c;
c_loop_all_2d cl(con);
//Compute Voronoi Cells, adding vertices to potential data structures (p*)
if(cl.start()) do if(con.compute_cell(c,cl)){
cv=0;
lv=c.ed[2*cv+1];
id=cl.pid();
x=vpos[2*mp[id]];
y=vpos[2*mp[id]+1];
groom_vertexg(c);
do{
gens=c.vertexg[cv];
vx=.5*c.pts[2*cv]+x;
vy=.5*c.pts[2*cv+1]+y;
if(gens.size()==1){
seencv=false;
if(pcurrent_vertices==vert_size){
pcurrent_vertices<<=1;
add_memory_vector(pvert_to_gen,pcurrent_vertices);
add_memory_array(pvertl,pcurrent_vertices);
}
pgen_to_vert[gens[0]].push_back(vert_size);
pvertl[2*vert_size]=vx;
pvertl[2*vert_size+1]=vy;
pvert_to_gen[vert_size]=gens;
cvi=vert_size;
if(cv==0) fvi=cvi;
vert_size++;
}else if(gens.size()==2){
gx1=vpos[2*mp[gens[0]]]-(c.pts[2*cv]*.5+x);gy1=vpos[2*mp[gens[0]]+1]-(c.pts[2*cv+1]*.5+y);
gx2=vpos[2*mp[gens[1]]]-(c.pts[2*cv]*.5+x);gy2=vpos[2*mp[gens[1]]+1]-(c.pts[2*cv+1]*.5+y);
if((((gx1*gy2)-(gy1*gx2))>-tolerance) && ((gx1*gy2)-(gy1*gx2))<tolerance){
if((vbd[mp[gens[0]]]|2)!=0 && vbd[mp[gens[1]]]==1){
g1=gens[1]; g2=gens[0];
}else if((vbd[mp[gens[1]]]|2)!=0 && vbd[mp[gens[0]]]==1){
g1=gens[0]; g2=gens[1];
}else{
if(mp[gens[0]]<mp[gens[1]]){
g1=gens[1];g2=gens[0];
}else{
g1=gens[0];g2=gens[1];
}
}
}else if(((gx1*gy2)-(gy1*gx2))>0){
g1=gens[0]; g2=gens[1];
}else{
g1=gens[1]; g2=gens[0];
}
if(globvertc[2*((ng*ng*g1)+(ng*g2))]!=0){
seencv=true;
globvertc[2*((ng*ng*g1)+(ng*g2))]+=1;
cvi=globvertc[2*((ng*ng*g1)+(ng*g2))+1];
pgen_to_vert[id].push_back(cvi);
if(cv==0) fvi=cvi;
}else{
seencv=false;
if(pcurrent_vertices==vert_size){
pcurrent_vertices<<=1;
add_memory_vector(pvert_to_gen,pcurrent_vertices);
add_memory_array(pvertl,pcurrent_vertices);
}
pgen_to_vert[id].push_back(vert_size);
pvertl[2*vert_size]=vx;
pvertl[2*vert_size+1]=vy;
pvert_to_gen[vert_size]=gens;
globvertc[2*((ng*ng*g1)+(ng*g2))]=(unsigned int)1;
globvertc[2*((ng*ng*g1)+(ng*g2))+1]=vert_size;
cvi=vert_size;
if(cv==0) fvi=cvi;
vert_size++;
}
}else{
arrange_cc_x_to_gen(gens,vx,vy);
g1=gens[0];g2=gens[1];g3=gens[2];
if(g1<g2 && g1<g3){
gl1=g1;gl2=g2;gl3=g3;
}else if(g2<g1 && g2<g3){
gl1=g2;gl2=g3;gl3=g1;
}else{
gl1=g3;gl2=g1;gl3=g2;
}
if(globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)]!=0){
seencv=true;
globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)]+=1;
cvi=globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)+1];
pgen_to_vert[id].push_back(cvi);
if(cv==0)fvi=cvi;
}else{
seencv=false;
if(pcurrent_vertices==vert_size){
pcurrent_vertices<<=1;
add_memory_vector(pvert_to_gen,pcurrent_vertices);
add_memory_array(pvertl,pcurrent_vertices);
}
pgen_to_vert[id].push_back(vert_size);
pvertl[2*vert_size]=vx;
pvertl[2*vert_size+1]=vy;
pvert_to_gen[vert_size]=gens;
globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)]=(unsigned int)1;
globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)+1]=vert_size;
cvi=vert_size;
if(cv==0)fvi=cvi;
vert_size++;
}
}
//add edges to potential edge structures
if(cv!=0){
if(pne==current_edges){
current_edges<<=1;
add_memory_array(ped_to_vert,current_edges);
}
if(cvi<lvi){
ped_to_vert[2*pne]=cvi;
ped_to_vert[2*pne+1]=lvi;
}else{
ped_to_vert[2*pne]=lvi;
ped_to_vert[2*pne+1]=cvi;
}
pne++;
}
lv=cv;
lvi=cvi;
seenlv=seencv;
cv=c.ed[2*lv];
}while(cv!=0);
//deal with final edge (last vertex to first vertex)
if(pne==current_edges){
current_edges<<=1;
add_memory_array(ped_to_vert,current_edges);
}
if(fvi<lvi){
ped_to_vert[2*pne]=fvi;
ped_to_vert[2*pne+1]=lvi;
}else{
ped_to_vert[2*pne]=lvi;
ped_to_vert[2*pne+1]=fvi;
}
pne++;
}while (cl.inc());
cout << "2.2" << endl;
//Add non-problem vertices(connectivity<=3) to class variables, add problem vertices to problem vertice data structures
pmap=new int[pcurrent_vertices];
j=0;
int v1=0;
for(int i=0;i<vert_size;i++){
gens=pvert_to_gen[i];
if(gens.size()==1){
if(j==current_vertices){
add_memory_vertices();
}
generator_is_vertex[gens[0]]=j;
vertex_is_generator[j]=gens[0];
vertl[2*j]=pvertl[2*i];
vertl[2*j+1]=pvertl[2*i+1];
vert_to_gen[j]=pvert_to_gen[i];
pmap[i]=j;
j++;
v1++;
}
else if(gens.size()==2){
gx1=vpos[2*mp[gens[0]]]-(pvertl[2*i]);gy1=vpos[2*mp[gens[0]]+1]-(pvertl[2*i+1]);
gx2=vpos[2*mp[gens[1]]]-(pvertl[2*i]);gy2=vpos[2*mp[gens[1]]+1]-(pvertl[2*i+1]);
if((((gx1*gy2)-(gy1*gx2))>-tolerance) && ((gx1*gy2)-(gy1*gx2))<tolerance){
if((vbd[mp[gens[0]]]|2)!=0 && vbd[mp[gens[1]]]==1){
g1=gens[1]; g2=gens[0];
}else if((vbd[mp[gens[1]]]|2)!=0 && vbd[mp[gens[0]]]==1){
g1=gens[0]; g2=gens[1];
}else{
if(mp[gens[0]]<mp[gens[1]]){
g1=gens[1];g2=gens[0];
}else{
g1=gens[0];g2=gens[1];
}
}
}else if(((gx1*gy2)-(gy1*gx2))>0){
g1=gens[0]; g2=gens[1];
}else{
g1=gens[1]; g2=gens[0];
}
if(globvertc[2*((ng*ng*g1)+(ng*g2))]!=2){
problem_verts21.push_back(i);
}
else{
if(j==current_vertices){
add_memory_vertices();
}
vertl[2*j]=pvertl[2*i];
vertl[2*j+1]=pvertl[2*i+1];
vert_to_gen[j]=pvert_to_gen[i];
pmap[i]=j;
j++;
}
}else{
g1=gens[0];g2=gens[1];g3=gens[2];
if(g1<g2 && g1<g3){
gl1=g1;gl2=g2;gl3=g3;
}else if(g2<g1 && g2<g3){
gl1=g2;gl2=g3;gl3=g1;
}else{
gl1=g3;gl2=g1;gl3=g2;
}
if(globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)]!=3){
if(globvertc[2*((ng*ng*gl1)+(ng*gl2)+gl3)]==1) problem_verts.push_back(i);
else problem_verts32.push_back(i);
}else{
if(j==current_vertices){
add_memory_vertices();
}
vertl[2*j]=pvertl[2*i];
vertl[2*j+1]=pvertl[2*i+1];
vert_to_gen[j]=pvert_to_gen[i];
pmap[i]=j;
j++;
}
}
}
cout << "2.3\n problemverts21.size()=" << problem_verts21.size() << "\nproblem_verts32.size()=" << problem_verts32.size() << "\nproblem_verts.size()=" << problem_verts.size() << endl;
nv=j;
degenerate_vertices=j;
//deal with problem verts
while(problem_verts21.size()>problem_verts32.size()){
for(int i=0;i<problem_verts21.size();i++){
for(int j=i+1;j<problem_verts21.size();j++){
one_in_common(pvert_to_gen[problem_verts21[i]],pvert_to_gen[problem_verts21[j]],g1);
if(g1==-1) continue;
gens=pvert_to_gen[problem_verts21[i]];
gens.push_back(not_this_one(pvert_to_gen[problem_verts21[j]],g1));
for(int k=0;k<problem_verts.size();k++){
if(contain_same_elements(gens,pvert_to_gen[problem_verts[k]])){
if(nv==current_vertices) add_memory_vertices();
vertl[2*nv]=pvertl[2*problem_verts[k]];
vertl[2*nv+1]=pvertl[2*problem_verts[k]+1];
vert_to_gen[nv]=pvert_to_gen[problem_verts[k]];
pmap[problem_verts21[i]]=nv;
pmap[problem_verts21[j]]=nv;
pmap[problem_verts[k]]=nv;
nv++;
problem_gen_to_vert.push_back(problem_verts21[i]);
problem_gen_to_vert.push_back(problem_verts21[j]);
problem_verts21.erase(problem_verts21.begin()+i);
problem_verts21.erase(problem_verts21.begin()+(j-1));
problem_verts.erase(problem_verts.begin()+k);
break;
}
}
}
}
}
cout << "part 2" << endl;
while(problem_verts32.size()>0){
for(int i=0;i<problem_verts32.size();i++){
gens=pvert_to_gen[problem_verts32[i]];
for(int j=0;j<problem_verts21.size();j++){
if(subset(pvert_to_gen[problem_verts21[j]],gens)){
if(nv==current_vertices) add_memory_vertices();
vertl[2*nv]=pvertl[2*problem_verts32[i]];
vertl[2*nv+1]=pvertl[2*problem_verts32[i]+1];
vert_to_gen[nv]=gens;
pmap[problem_verts32[i]]=nv;
pmap[problem_verts21[j]]=nv;
nv++;
problem_gen_to_vert.push_back(problem_verts21[j]);
problem_verts21.erase(problem_verts21.begin()+j);
problem_verts32.erase(problem_verts32.begin()+i);
break;
}
}
}
}
double standard,distance;
cout << "part3" << endl;
while(problem_verts.size()>0){
if(nv==current_vertices) add_memory_vertices();
gens=pvert_to_gen[problem_verts[0]];
vx=pvertl[2*problem_verts[0]];vy=pvertl[2*problem_verts[0]+1];
standard=pow(vx-vpos[2*mp[gens[0]]],2)+pow(vy-vpos[2*mp[gens[0]]+1],2);
g1=gens[0];g2=gens[1];
pmap[problem_verts[0]]=nv;
problem_verts.erase(problem_verts.begin());
i=0;
while(true){
g3=not_these_two(pvert_to_gen[problem_verts[i]],g1,g2);
if(g3!=-1){
distance=pow(vx-vpos[2*mp[g3]],2)+pow(vy-vpos[2*mp[g3]+1],2);
}
if(contains_two(pvert_to_gen[problem_verts[i]],g1,g2) &&
(distance<(standard+tolerance) && (distance>(standard-tolerance)))){
if(g3==gens[0]){
pmap[problem_verts[i]]=nv;
problem_verts.erase(problem_verts.begin()+i);
break;
}
if(g3!=gens[2]) gens.push_back(g3);
pmap[problem_verts[i]]=nv;
g2=g3;
g1=pvert_to_gen[problem_verts[i]][0];
if(problem_verts.size()>1){
problem_verts.erase(problem_verts.begin()+i);
}else{
break;
}
i=0;
}else{
i++;
}
}
vertl[2*nv]=vx;
vertl[2*nv+1]=vy;
arrange_cc_x_to_gen(gens,vx,vy);
vert_to_gen[nv]=gens;
nv++;
}
delete [] pvert_to_gen;
delete [] pvertl;
delete [] globvertc;
cout << "2.4" << endl;
//assemble edge data structures
ed_to_vert=new int[2*pne];
vert_to_ed=new vector<int>[nv];
unsigned int* globedgec=new unsigned int[nv*nv];
for(int i=0;i<(nv*nv);i++){
globedgec[i]=0;
}
for(int i=0;i<pne;i++){
g1=pmap[ped_to_vert[2*i]];g2=pmap[ped_to_vert[2*i+1]];
if(g2<g1){
g2^=g1;
g1^=g2;
g2^=g1;
}
if(globedgec[(nv*g1+g2)]!=0){
continue;
}else{
globedgec[(nv*g1+g2)]=1;
ed_to_vert[2*ne]=g1;
ed_to_vert[2*ne+1]=g2;
vert_to_ed[g1].push_back(ne);
vert_to_ed[g2].push_back(ne);
ne++;
}
}
for(int i=0;i<ng;i++){
for(int k=0;k<pgen_to_vert[i].size();k++){
gen_to_vert[i].push_back(pmap[pgen_to_vert[i][k]]);
if(contains(problem_gen_to_vert,pgen_to_vert[i][k])) arrange=true;
}
if(arrange) arrange_cc_gen_to_vert(gen_to_vert[i],vpos[2*mp[i]],vpos[2*mp[i]+1]);
arrange=false;
}
delete [] pgen_to_vert;
delete [] pmap;
delete [] ped_to_vert;
delete [] globedgec;
cout << "out" << endl;
}
//assemble gen_to_gen , gen_to_ed , ed_to_gen
void v_connect::assemble_gen_ed(){
cout << "gen_ed 1" << endl;
ed_to_gen=new vector<int>[ne];
//though neither ed_on_bd or vert_on_bd are modified during this method, they are initialized here in case the user
//does not require boundary information and will not be calling assemble_boundary
ed_on_bd=new vector<int>[ne];
vert_on_bd=new vector<int>[nv];
vector<int> gens;
int g1,g2,v1,v2,j,vi;
double gx1,gy1,gx2,gy2,vx1,vy1,vx2,vy2;
cout << "gen_ed 2" << endl;
for(int i=0;i<ne;i++){
v1=ed_to_vert[2*i];v2=ed_to_vert[2*i+1];
two_in_common(vert_to_gen[v1],vert_to_gen[v2],g1,g2);
if(g1!=-1 && g2!=-1){
gen_to_gen_e[g1].push_back(g2);
gen_to_gen_e[g2].push_back(g1);
for(int k=0;k<gen_to_vert[g1].size();k++){
if(gen_to_vert[g1][k]==v1){
vi=k;
break;
}
}
if((vi!=(gen_to_vert[g1].size()-1) && gen_to_vert[g1][vi+1]==v2) ||
(vi==(gen_to_vert[g1].size()-1) && gen_to_vert[g1][0]==v2)){
ed_to_gen[i].push_back(g1);
ed_to_gen[i].push_back(g2);
gen_to_ed[g1].push_back(i);
gen_to_ed[g2].push_back(~i);
}else{
ed_to_gen[i].push_back(g2);
ed_to_gen[i].push_back(g1);
gen_to_ed[g2].push_back(i);
gen_to_ed[g1].push_back(~i);
}
}else{
if(g1==-1) continue;
ed_to_gen[i].push_back(g1);
vx1=vertl[2*v1];vy1=vertl[2*v1+1];
vx2=vertl[2*v2];vy2=vertl[2*v2+1];
gx1=vpos[2*mp[g1]];gy1=vpos[2*mp[g1]+1];
for(int k=0;k<gen_to_vert[g1].size();k++){
if(gen_to_vert[g1][k]==v1){
vi=k;
break;
}
}
if((vi!=(gen_to_vert[g1].size()-1) && gen_to_vert[g1][vi+1]==v2) ||
(vi==(gen_to_vert[g1].size()-1) && gen_to_vert[g1][0]==v2)) gen_to_ed[g1].push_back(i);
else gen_to_ed[g1].push_back(~i);
}
}
cout << "gen_ed 3" << endl;
for(int i=0;i<nv;i++){
if(vert_to_ed[i].size()<=3) continue;
else{
gens=vert_to_gen[i];
for(int j=0;j<gens.size();j++){
for(int k=0;k<gens.size();k++){
if(!contains(gen_to_gen_e[gens[j]],gens[k])) gen_to_gen_v[gens[j]].push_back(gens[k]);
}
}
}
}
cout << "gen_ed 4" << endl;
//arrange gen_to_ed gen_to_gen_e gen_to_gen_v counterclockwise
for(int i=0;i<ng;i++){
gx1=vpos[2*mp[i]];gy1=vpos[2*mp[i]+1];
arrange_cc_gen_to_ed(gen_to_ed[i]);
arrange_cc_x_to_gen(gen_to_gen_e[i],gx1,gy1);
arrange_cc_x_to_gen(gen_to_gen_v[i],gx1,gy1);
}
cout << "gen_ed 5" << endl;
//arrange vert_to_ed cc
for(int i=0;i<nv;i++){
gx1=vertl[2*i];gy1=vertl[2*i+1];
arrange_cc_vert_to_ed(vert_to_ed[i],gx1,gy1,i);
}
}
//assemble vert_on_bd and ed_on_bd as well as side edge information if neccessary.
void v_connect::assemble_boundary(){
bool begun=false;
int i=0,cg,ng,fg,lv,cv,nv,ev,ei,j;
while(true){
if(vbd[i]==1){
begun=true;
fg=mp[i];
cg=fg;
ng=mp[i+1];
ev=gen_to_vert[ng][0];
}else if(vbd[i]==2){
begun=false;
cg=mp[i];
ng=fg;
ev=gen_to_vert[ng][0];
}else{
if(!begun) break;
cg=mp[i];
ng=mp[i+1];
ev=gen_to_vert[ng][0];
}
cv=gen_to_vert[cg][0];
nv=gen_to_vert[cg][1];
one_in_common(vert_to_ed[cv],vert_to_ed[nv],ei);
vert_on_bd[cv].push_back(cg);
vert_on_bd[cv].push_back(ng);
vert_on_bd[nv].push_back(cg);
vert_on_bd[nv].push_back(ng);
ed_on_bd[ei].push_back(cg);
ed_on_bd[ei].push_back(ng);
lv=cv;
cv=nv;
while(nv!=ev){
j=0;
while(true){
if(ed_to_vert[2*vert_to_ed[cv][j]]==lv) break;
else if(ed_to_vert[2*vert_to_ed[cv][j]+1]==lv) break;
j++;
}
if(j==(vert_to_ed[cv].size()-1)) ei=vert_to_ed[cv][0];
else ei=vert_to_ed[cv][j+1];
if(ed_to_vert[2*ei]==cv) nv=ed_to_vert[2*ei+1];
else nv=ed_to_vert[2*ei];
vert_on_bd[nv].push_back(cg);
vert_on_bd[nv].push_back(ng);
ed_on_bd[ei].push_back(cg);
ed_on_bd[ei].push_back(ng);
lv=cv;
cv=nv;
}
i++;
}
}
//(x,y)=my coordinates
//(vx,vy)=vertex coordinates
vector<int> v_connect::groom_vertexg_help(double x,double y,double vx, double vy,vector<int> &g){
if(g.size()<2) return g;
bool rightside=false;
int g0=g[0],g1,bestg,besti;
double d1;
double standard=pow((vpos[2*mp[g0]]-vx),2)+pow((vpos[2*mp[g0]+1]-vy),2);
double gx0,gy0,gx1,gy1,best,current;
vector<int> newg,temp;
temp.push_back(g0);
for(int i=1;i<g.size();i++){
g1=g[i];
if(contains(temp,g1)) continue;
d1=pow((vpos[2*mp[g1]]-vx),2)+pow((vpos[2*mp[g1]+1]-vy),2);
if(d1<(standard+tolerance)){
temp.push_back(g1);
}
}
if(temp.size()<3) return temp;
gx0=vpos[2*mp[g0]]; gy0=vpos[2*mp[g0]+1];
newg.push_back(g0);
//find right hand
g1=temp[1];
gx1=vpos[2*mp[g1]]; gy1=vpos[2*mp[g1]+1];
if(cross_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy)>0){
rightside=true;
}
best=dot_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy);
bestg=g1;
besti=1;
for(int i=2;i<temp.size();i++){
g1=temp[i];
if(contains(newg,g1)) continue;
gx1=vpos[2*mp[g1]]; gy1=vpos[2*mp[g1]+1];
if(cross_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy)>0){
if(!rightside){
rightside=true;
best=dot_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy);
bestg=g1;
besti=i;
}else{
current=dot_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy);
if(current>best){
best=current;
bestg=g1;
besti=i;
}
}
}else{
if(rightside) continue;
else{
current=dot_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy);
if(current<best){
best=current;
bestg=g1;
besti=i;
}
}
}
}
if(!contains(newg,bestg)) newg.push_back(bestg);
//find left hand
rightside=false;
g1=temp[1];
gx1=vpos[2*mp[g1]]; gy1=vpos[2*mp[g1]+1];
if(cross_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy)<0){
rightside=true;
}
best=dot_product(gx0-vx,gy0-vy,gx1-vy,gy1-vy);
bestg=g1;
for(int i=2;i<temp.size();i++){
g1=temp[i];
if(contains(newg,g1)) continue;
gx1=vpos[2*mp[g1]]; gy1=vpos[2*mp[g1]+1];
if(cross_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy)<0){
if(!rightside){
rightside=true;
best=dot_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy);
bestg=g1;
}else{
current=dot_product(gx0-vx,gy0-vy,gx1-vx,gy1-vy);
if(current>best){
best=current;
bestg=g1;
}
}
}else{
if(rightside) continue;
else{
current=dot_product(gx0-vx,gy0-vx,gx1-vx,gy1-vy);
if(current<best){
best=current;
bestg=g1;
}
}
}
}
if(!contains(newg,bestg)) newg.push_back(bestg);
if(newg.size()<3) return groom_vertexg_help2(x,y,vx,vy,g);
return newg;
}
vector<int> v_connect::groom_vertexg_help2(double x,double y,double vx,double vy,vector<int> &g){
if(g.size()<2) return g;
int m0=g[0],m1=g[1],m2,p,i=1;
double d0=pow((vpos[2*mp[m0]]-x),2)+pow((vpos[2*mp[m0]+1]-y),2);
double d1=pow((vpos[2*mp[m1]]-vx),2)+pow((vpos[2*mp[m1]+1]-vy),2);
double d2;
double standard=pow((vpos[2*mp[m0]]-vx),2)+pow((vpos[2*mp[m0]+1]-vy),2);
double dp,dcompare, temp;
vector<int> newg;
while(d1>=standard+tolerance){
if(i==g.size()-1){
newg.push_back(m0);
return newg;
}
i++;
m1=g[i];
d1=pow((vpos[2*mp[m1]]-vx),2)+pow((vpos[2*mp[m1]+1]-vy),2);
}
if(i==g.size()-1){
newg.push_back(m0);
newg.push_back(m1);
return newg;
}
i++;
m2=g[i];
d2=pow((vpos[2*mp[m2]]-vx),2)+pow((vpos[2*mp[m2]+1]-vy),2);
while(d2>=standard+tolerance){
if(i==g.size()-1){
newg.push_back(m0);
newg.push_back(m1);
return newg;
}
i++;
m2=g[i];
d2=pow((vpos[2*mp[m2]]-vx),2)+pow((vpos[2*mp[m2]+1]-vy),2);
}
if(i==g.size()-1){
newg.push_back(m0);
newg.push_back(m1);
newg.push_back(m2);
return newg;
}
i++;
d1=pow((vpos[2*mp[m1]]-x),2)+pow((vpos[2*mp[m1]+1]-y),2);
d2=pow((vpos[2*mp[m2]]-x),2)+pow((vpos[2*mp[m2]+1]-y),2);
if(d0<d2 && d2<d1){
temp=d1;
d1=d2;
d2=temp;
m2^=m1;
m1^=m2;
m2^=m1;
}else if(d1<d0 && d0<d2){
temp=d1;
d1=d0;
d0=temp;
m0^=m1;
m1^=m0;
m0^=m1;
}else if(d1<d2 && d2<d0){
temp=d1;
d1=d0;
d0=temp;
m0^=m1;
m1^=m0;
m0^=m1;
temp=d1;
d1=d2;
d2=temp;
m2^=m1;
m1^=m2;
m2^=m1;
}else if(d2<d1 && d1<d0){
temp=d2;
d2=d0;
d0=temp;
m0^=m2;
m2^=m0;
m0^=m2;
}else if(d2<d0 && d0<d1){
temp=d2;
d2=d0;
d0=temp;
m0^=m2;
m2^=m0;
m0^=m2;
temp=d1;
d1=d2;
d2=temp;
m2^=m1;
m1^=m2;
m2^=m1;
}
for(int j=i;j<g.size();j++){
p=g[j];
dcompare=pow((vpos[2*mp[p]]-vx),2)+pow((vpos[2*mp[p]+1]-vy),2);
if(dcompare<=(standard+tolerance)){
dp=pow((vpos[2*mp[p]]-x),2)+pow((vpos[2*mp[p]+1]-y),2);
if(dp<d2){
temp=d2;
d2=dp;
dp=temp;
p^=m2;
m2^=p;
p^=m2;
if(d2<d1){
temp=d1;
d1=d2;
d2=temp;
m2^=m1;
m1^=m2;
m2^=m1;
if(d1<d0){
temp=d1;
d1=d0;
d0=temp;
m0^=m1;
m1^=m0;
m0^=m1;
}
}
}
}
}
newg.push_back(m0);
newg.push_back(m1);
newg.push_back(m2);
return newg;
}
void v_connect::arrange_cc_x_to_gen(vector<int> &list,double cx,double cy){
if(list.size()==0) return;
bool wrongside;
int g1,ng,ni;
double x1,y1,x2,y2,best,current;
vector<int> newlist;
vector<int> potential;
newlist.push_back(list[0]);
x1=vpos[2*mp[list[0]]];y1=vpos[2*mp[list[0]]+1];
list.erase(list.begin());
while(list.size()>0){
wrongside=true;
for(int i=0;i<list.size();i++){
g1=list[i];
x2=vpos[2*mp[g1]];y2=vpos[2*mp[g1]+1];
if(cross_product(cx-x1,cy-y1,cx-x2,cy-y2)>=0){
current=dot_product(cx-x1,cy-y1,cx-x2,cy-y2);
if(wrongside){
ng=g1;
ni=i;
best=current;
wrongside=false;
}else if(current>best){
best=current;
ng=g1;
ni=i;
}
}else{
if(!wrongside) continue;
current=dot_product(cx-x1,cy-y1,cx-x2,cy-y2);
if(i==0){
best=current;
ng=g1;
ni=i;
}else if(current<best){
best=current;
ng=g1;
ni=i;
}
}
}
newlist.push_back(ng);
list.erase(list.begin()+ni);
}
list=newlist;
}
void v_connect::arrange_cc_gen_to_vert(vector<int> &list,double cx,double cy){
if(list.size()==0) return;
bool wrongside;
int g1,ng,ni;
double x1,y1,x2,y2,best,current;
vector<int> newlist;
vector<int> potential;
newlist.push_back(list[0]);
x1=vertl[2*list[0]];y1=vertl[2*list[0]+1];
list.erase(list.begin());
while(list.size()>0){
wrongside=true;
for(int i=0;i<list.size();i++){
g1=list[i];
x2=vertl[2*g1];y2=vertl[2*g1+1];
if(cross_product(cx-x1,cy-y1,cx-x2,cy-y2)>=0){
current=dot_product(cx-x1,cy-y1,cx-x2,cy-y2);
if(wrongside){
ng=g1;
ni=i;
best=current;
wrongside=false;
}else if(current>best){
best=current;
ng=g1;
ni=i;
}
}else{
if(!wrongside) continue;
current=dot_product(cx-x1,cy-y1,cx-x2,cy-y2);
if(i==0){
best=current;
ng=g1;
ni=i;
}else if(current<best){
best=current;
ng=g1;
ni=i;
}
}
}
newlist.push_back(ng);
list.erase(list.begin()+ni);
}
list=newlist;
}
void v_connect::arrange_cc_gen_to_ed(vector<int> &list){
vector<int> newlist;
int v1,v2,ed,i=0;
newlist.push_back(list[0]);
list.erase(list.begin());
if(newlist[0]<0){
ed=~newlist[0];
v1=ed_to_vert[2*ed];
}else{
ed=newlist[0];
v1=ed_to_vert[2*ed+1];
}
while(list.size()>0){
if(list[i]>=0){
v2=ed_to_vert[2*list[i]];
if(v2==v1){
v1=ed_to_vert[2*list[i]+1];
newlist.push_back(list[i]);
list.erase(list.begin()+i);
i=0;
}else i++;
}else{
v2=ed_to_vert[2*(~list[i])+1];
if(v2==v1){
v1=ed_to_vert[2*(~list[i])];
newlist.push_back(list[i]);
list.erase(list.begin()+i);
i=0;
}else i++;
}
}
list=newlist;
}
void v_connect::arrange_cc_vert_to_ed(vector<int> &list,double cx, double cy,int id){
if(list.size()==0) return;
bool wrongside;
int g1,ng,ni,index;
double x1,y1,x2,y2,best,current;
vector<int> newlist;
vector<int> potential;
newlist.push_back(list[0]);
if(ed_to_vert[2*list[0]]==id) index=ed_to_vert[2*list[0]+1];
else index=ed_to_vert[2*list[0]];
x1=vertl[2*index];y1=vertl[2*index+1];
list.erase(list.begin());
while(list.size()>0){
wrongside=true;
for(int i=0;i<list.size();i++){
g1=list[i];
if(ed_to_vert[2*g1]==id) index=ed_to_vert[2*g1+1];
else index=ed_to_vert[2*g1];
x2=vertl[2*index];y2=vertl[2*index+1];
if(cross_product(cx-x1,cy-y1,cx-x2,cy-y2)>=0){
current=dot_product(cx-x1,cy-y1,cx-x2,cy-y2);
if(wrongside){
ng=g1;
ni=i;
best=current;
wrongside=false;
}else if(current>best){
best=current;
ng=g1;
ni=i;
}
}else{
if(!wrongside) continue;
current=dot_product(cx-x1,cy-y1,cx-x2,cy-y2);
if(i==0){
best=current;
ng=g1;
ni=i;
}else if(current<best){
best=current;
ng=g1;
ni=i;
}
}
}
newlist.push_back(ng);
list.erase(list.begin()+ni);
}
list=newlist;
}
void v_connect::draw_gnu(FILE *fp){
int vert;
for(int i=0;i<ng;i++){
fprintf(fp,"# cell number %i\n",i);
for(int j=0;j<gen_to_vert[i].size();j++){
vert=gen_to_vert[i][j];
fprintf(fp,"%g %g\n",vertl[2*vert],vertl[2*vert+1]);
}
fprintf(fp,"%g %g\n",vertl[2*gen_to_vert[i][0]],vertl[2*gen_to_vert[i][0]+1]);
fprintf(fp,"\n");
}
}
void v_connect::draw_vtg_gnu(FILE *fp){
double vx, vy, gx, gy;
int l2;
for(int i=0;i<ng;i++){
gx=vpos[2*mp[i]];gy=vpos[2*mp[i]+1];
for(int k=0;k<gen_to_vert[i].size();k++){
vx=vertl[2*gen_to_vert[i][k]];vy=vertl[2*gen_to_vert[i][k]+1];
fprintf(fp, "%g %g\n %g %g\n\n\n",vx,vy,gx,gy);
}
}
}
void v_connect::draw_gen_gen(FILE *fp){
int g2;
double gx1,gy1,gx2,gy2;
for(int i=0;i<ng;i++){
gx1=vpos[2*mp[i]];gy1=vpos[2*mp[i]+1];
for(int k=0;k<gen_to_gen_e[i].size();k++){
g2=gen_to_gen_e[i][k];
gx2=vpos[2*mp[g2]];gy2=vpos[2*mp[g2]+1];
fprintf(fp, "%g %g\n %g %g\n\n\n",gx1,gy1,gx2,gy2);
}
for(int k=0;k<gen_to_gen_v[i].size();k++){
g2=gen_to_gen_v[i][k];
gx2=vpos[2*mp[g2]];gy2=vpos[2*mp[g2]+1];
fprintf(fp, "%g %g\n %g %g \n\n\n",gx1,gy1,gx2,gy2);
}
}
}
void v_connect::label_vertices(FILE *fp){
double vx,vy;
for(int i=0;i<nv;i++){
vx=vertl[2*i];vy=vertl[2*i+1];
fprintf(fp,"set label '%i' at %g,%g point lt 2 pt 3 ps 2 offset -3,3\n",i,vx,vy);
}
}
void v_connect::label_generators(FILE *fp){
double gx,gy;
for(int i=0;i<vid.size();i++){
gx=vpos[2*i];gy=vpos[2*i+1];
fprintf(fp,"set label '%i' at %g,%g point lt 4 pt 4 ps 2 offset 3,-3\n",vid[i],gx,gy);
}
}
void v_connect::label_edges(FILE *fp){
double ex,ey,vx1,vy1,vx2,vy2;
for(int i=0;i<ne;i++){
vx1=vertl[2*ed_to_vert[2*i]];vy1=vertl[2*ed_to_vert[2*i]+1];
vx2=vertl[2*ed_to_vert[2*i+1]];vy2=vertl[2*ed_to_vert[2*i+1]+1];
ex=(vx1+vx2)/2; ey=(vy1+vy2)/2;
fprintf(fp,"set label '%i' at %g,%g point lt 3 pt 1 ps 2 offset 0,-3\n",i,ex,ey);
}
}
void v_connect::label_centroids(FILE *fp){
double x,y;
for(int i=0;i<ng;i++){
centroid(i,x,y);
fprintf(fp,"set label '%i' at %g,%g point lt 5 pt 5 ps 2 offset 0,3\n",i,x,y);
}
}
void v_connect::print_gen_to_ed_table(FILE *fp){
fprintf(fp,"generator to edge connectivity, arranged counterclockwise. Negative edge number means edge with reverse orientation\n\n");
for(int i=0;i<ng;i++){
fprintf(fp,"generator %i\n", i);
for(int k=0;k<gen_to_ed[i].size();k++){
if(gen_to_ed[i][k]>=0) fprintf(fp,"\t %i\n",gen_to_ed[i][k]);
else fprintf(fp,"\t -%i\n",~gen_to_ed[i][k]);
}
fprintf(fp,"\n\n");
}
}
void v_connect::print_gen_to_vert_table(FILE *fp){
fprintf(fp,"generator to vertex connectivity, arranged conterclockwise\n\n");
for(int i=0;i<ng;i++){
fprintf(fp,"generator %i\n",i);
for(int k=0;k<gen_to_vert[i].size();k++){
fprintf(fp,"\t %i\n",gen_to_vert[i][k]);
}
}
}
void v_connect::print_vert_to_gen_table(FILE *fp){
fprintf(fp,"vertex to generator connectivity, arranged counterclockwise\n\n");
for(int i=0;i<nv;i++){
fprintf(fp,"vertex %i\n",i);
for(int k=0;k<vert_to_gen[i].size();k++){
fprintf(fp,"\t %i\n",vert_to_gen[i][k]);
}
}
}
void v_connect::print_ed_to_gen_table(FILE *fp){
fprintf(fp,"edge to generator connectivity, arranged left-side, right-side\n\n");
for(int i=0;i<ne;i++){
fprintf(fp,"ed %i\n",i);
for(int k=0;k<ed_to_gen[i].size();k++){
fprintf(fp,"\t %i\n",ed_to_gen[i][k]);
}
}
}
void v_connect::print_vert_to_ed_table(FILE *fp){
fprintf(fp,"vert to edge connectivity, arranged cc\n\n");
for(int i=0;i<nv;i++){
fprintf(fp,"vert %i\n",i);
for(int k=0;k<vert_to_ed[i].size();k++){
fprintf(fp,"\t %i\n",vert_to_ed[i][k]);
}
}
}
void v_connect::print_vert_boundary(FILE *fp){
fprintf(fp,"vertex on boundary\n\n");
for(int i=0;i<nv;i++){
fprintf(fp,"\nvert %i\n",i);
if(vert_on_bd[i].size()==0) fprintf(fp,"\t vertex not on bound\n");
else{
fprintf(fp,"\tvertex on bound");
for(int k=0;k<vert_on_bd[i].size();k++) fprintf(fp,"\t %i",vert_on_bd[i][k]);
}
}
}
void v_connect::print_ed_boundary(FILE *fp){
fprintf(fp,"edge on boundar \n\n");
for(int i=0;i<ne;i++){
fprintf(fp,"\nedge %i\n",i);
if(ed_on_bd[i].size()==0) fprintf(fp,"\t edge not on bound\n");
else{
fprintf(fp,"\t edge on bound");
for(int k=0;k<ed_on_bd[i].size();k++) fprintf(fp,"\t %i",ed_on_bd[i][k]);
}
}
}
void v_connect::ascii_output(FILE *fp){
fprintf(fp,"\n# General Mesh Data\nNnp\t%i\nNel\t%i\nNel_tri3\t0\nNel_poly2d\t%i\nNel_quad4\t0\nNel_hexh8\t0\nNel_poly3d\t0\nNel_pyr5\t0\nNel_tet4\t0\nNel_wedget\t0\nNdim\t2\nNnd_sets\t0\nNsd_sets\t0\nendi\n",nv,ng,ng);
fprintf(fp,"# element data: global id, block id, number of nodes, nodes\n");
for(int i=0;i<ng;i++){
fprintf(fp,"%i\t1\t%i",i,gen_to_vert[i].size());
for(int j=0;j<gen_to_vert[i].size();j++){
fprintf(fp,"\t%i",gen_to_vert[i][j]);
}
fprintf(fp,"\n");
}
fprintf(fp,"#\n#nodal data:global id, xcoord, ycoord\n#\n");
for(int i=0;i<nv;i++){
fprintf(fp,"%i\t%g\t%g\n",i,vertl[2*i],vertl[2*i+1]);
}
}
void v_connect::add_memory_vertices(){
double *vertle(vertl+2*current_vertices);
int *vertex_is_generatore(vertex_is_generator+current_vertices);
current_vertices<<=1;
cout << "2.2.1" << endl;
//copy vertl
double *nvertl(new double[2*current_vertices]),*nvp(nvertl),*vp(vertl);
while(vp<vertle) *(nvp++)=*(vp++);
delete [] vertl;vertl=nvertl;
cout << "2.2.2" << endl;
//copy vert_to_gen, vert_to_ed
vector<int> *nvert_to_gen(new vector<int>[current_vertices]);
for(int i=0;i<(current_vertices>>1);i++){
nvert_to_gen[i]=vert_to_gen[i];
}
delete [] vert_to_gen;vert_to_gen=nvert_to_gen;
cout << "2.2.3" << endl;
//copy vertex_is_generator
int *nvertex_is_generator(new int[current_vertices]),*nvig(nvertex_is_generator),*vig(vertex_is_generator),*nvige(nvertex_is_generator+current_vertices);
while(vig<vertex_is_generatore) *(nvig++)=*(vig++);
cout << "inbetween" << endl;
while(nvig<nvige) *(nvig++)=-1;
cout << "2.2.4" << endl;
delete [] vertex_is_generator; vertex_is_generator=nvertex_is_generator;
}
//returns the signed area of the cell corresponding to generator g
double v_connect::signed_area(int g){
double area=0,vx1,vy1,vx2,vy2;
vx1=vertl[2*gen_to_vert[g][0]];
vy1=vertl[2*gen_to_vert[g][0]+1];
for(int i=0;i<gen_to_vert[g].size();i++){
if(i==gen_to_vert[g].size()-1){
vx2=vertl[2*gen_to_vert[g][0]];
vy2=vertl[2*gen_to_vert[g][0]+1];
}else{
vx2=vertl[2*gen_to_vert[g][i+1]];
vy2=vertl[2*gen_to_vert[g][i+1]+1];
}
area+=((vx1*vy2)-(vx2*vy1));
vx1=vx2;
vy1=vy2;
}
area*=.5;
return area;
}
//returns the centroid of the cell corresponding to generator g in x,y
void v_connect::centroid(int g,double &x,double &y){
double area,vx1,vy1,vx2,vy2,cp;
x=0; y=0; area=signed_area(g);
vx1=vertl[2*gen_to_vert[g][0]];
vy1=vertl[2*gen_to_vert[g][0]+1];
for(int i=0;i<gen_to_vert[g].size();i++){
if(i==gen_to_vert[g].size()-1){
vx2=vertl[2*gen_to_vert[g][0]];
vy2=vertl[2*gen_to_vert[g][0]+1];
}else{
vx2=vertl[2*gen_to_vert[g][i+1]];
vy2=vertl[2*gen_to_vert[g][i+1]+1];
}
cp=cross_product(vx1,vy1,vx2,vy2);
x+=((vx1+vx2)*cp);
y+=((vy1+vy2)*cp);
vx1=vx2;
vy1=vy2;
}
x=((1/(6*area))*x);
y=((1/(6*area))*y);
}
//outputs lloyds allgorithms in files lloyds# until max distance from generator to centroid < epsilon
void v_connect::lloyds(double epsilon){
double gx,gy,cx,cy,max,current;
int j=0;
char *outfn1(new char[1000]);
sprintf(outfn1,"lloyds");
FILE *fp=safe_fopen(outfn1,"w");
do{
cout << "iteration" << j << endl;
max=0;
char *outfn2(new char[1000]);
sprintf(outfn2,"lloyds%i",j);
cout << "blah" << endl;
draw_gnu(outfn2);
cout << "yeah" << endl;
delete[] outfn2;
if(bd!=-1){
for(int i=bd;i<ng;i++){
cout << "i=" << i << endl;
gx=vpos[2*mp[i]]; gy=vpos[2*mp[i]+1];
centroid(i,cx,cy);
current=pow(cx-gx,2)+pow(cy-gy,2);
if(current>max) max=current;
vpos[2*mp[i]]=cx;
vpos[2*mp[i]+1]=cy;
}
}
fprintf(fp,"iteration %i, max=%f, epsilon=%f",j,max,epsilon);
nv=0;
ne=0;
cout << "1" << endl;
current_vertices=init_vertices;
current_edges=init_vertices;
delete [] gen_to_gen_e;
gen_to_gen_e=new vector<int>[ng];
cout << "2" << endl;
delete [] gen_to_gen_v;
gen_to_gen_v=new vector<int>[ng];
cout << "3" << endl;
delete [] gen_to_ed;
gen_to_ed=new vector<int>[ng];
cout << "4" << endl;
delete [] gen_to_vert;
gen_to_vert=new vector<int>[ng];
cout << "5" << endl;
delete [] vertl;
vertl=new double[2*init_vertices];
cout << "6" << endl;
delete [] vert_to_gen;
vert_to_gen=new vector<int>[init_vertices];
cout << "7" << endl;
delete [] vertex_is_generator;
cout << "7.1" << endl;
vertex_is_generator=new int[init_vertices];
cout << "7.2" << endl;
for(int k=0;k<init_vertices;k++) vertex_is_generator[k]=-1;
cout << "8" << endl;
delete [] generator_is_vertex;
generator_is_vertex=new int[ng];
for(int k=0;k<ng;k++) generator_is_vertex[k]=-1;
cout << "9" << endl;
delete [] ed_to_vert;
delete [] vert_to_ed;
delete [] ed_to_gen;
delete [] ed_on_bd;
delete [] vert_on_bd;
cout << "1..." << endl;
assemble_vertex();
cout << "2..." << endl;
assemble_gen_ed();
cout << "3..." << endl;
assemble_boundary();
cout << "4..." << endl;
j++;
}while(max>epsilon);
fclose(fp);
delete [] outfn1;
}
void v_connect::draw_median_mesh(FILE *fp){
double ex,ey,cx,cy;
int e;
for(int i=0;i<ng;i++){
if(generator_is_vertex[i]!=-1) continue;
centroid(i,cx,cy);
for(int j=0;j<gen_to_ed[i].size();j++){
e=gen_to_ed[i][j];
if(e<0) e=~e;
ex=(vertl[2*ed_to_vert[2*e]] + vertl[2*ed_to_vert[2*e+1]])/2;
ey=(vertl[2*ed_to_vert[2*e]+1] + vertl[2*ed_to_vert[2*e+1]+1])/2;
fprintf(fp,"\n %g %g\n %g %g \n\n\n",ex,ey,cx,cy);
}
}
}
void v_connect::draw_closest_generator(FILE *fp,double x,double y){
int cg,pg,ng=0;
double gx,gy,best,bestl,current;
gx=vpos[2*mp[0]]; gy=vpos[2*mp[0]+1];
best = pow(gx-x,2)+pow(gy-y,2);
cout << "best=" << best << endl;
fprintf(fp,"%g %g\n",gx,gy);
do{
cg=ng;
for(int i=0;i<gen_to_gen_e[cg].size();i++){
pg=gen_to_gen_e[cg][i];
gx=vpos[2*mp[pg]]; gy=vpos[2*mp[pg]+1];
current=pow(gx-x,2)+pow(gy-y,2);
cout << "current=" << current << endl;
if(current<best){
cout << "changed" << endl;
best=current;
ng=pg;
}
}
fprintf(fp,"%g %g\n",vpos[2*mp[ng]],vpos[2*mp[ng]+1]);
}while(cg!=ng);
}
}
<file_sep>cmake_minimum_required(VERSION 3.10)
project(voro++ VERSION 0.4.6 LANGUAGES CXX)
set(SOVERSION "0")
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CXX_FLAGS)
#release comes with -O3 by default
set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE)
endif(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CXX_FLAGS)
########################################################################
# User input options #
########################################################################
option(VORO_BUILD_SHARED_LIBS "Build shared libs" ON)
include(GNUInstallDirs)
option(VORO_BUILD_EXAMPLES "Build examples" ON)
option(VORO_BUILD_CMD_LINE "Build command line project" ON)
option(VORO_ENABLE_DOXYGEN "Enable doxygen" ON)
########################################################################
#Find external packages
########################################################################
if (${VORO_ENABLE_DOXYGEN})
find_package(Doxygen)
endif()
######################################
# Include the following subdirectory #
######################################
file(GLOB VORO_SOURCES src/*.cc)
file(GLOB NOT_VORO_SOURCES src/v_base_wl.cc src/cmd_line.cc src/voro++.cc)
list(REMOVE_ITEM VORO_SOURCES ${NOT_VORO_SOURCES})
add_library(voro++ ${VORO_SOURCES})
set_target_properties(voro++ PROPERTIES
LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/src"
SOVERSION ${SOVERSION})
install(TARGETS voro++ EXPORT VORO_Targets LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR} ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR})
#for voro++.hh
target_include_directories(voro++ PUBLIC $<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/src> $<INSTALL_INTERFACE:${CMAKE_INSTALL_INCLUDEDIR}>)
if (${VORO_BUILD_CMD_LINE})
add_executable(cmd_line src/cmd_line.cc)
target_link_libraries(cmd_line PRIVATE voro++)
#cannot have two targets with the same name, so renaming cmd_line
set_target_properties(cmd_line PROPERTIES OUTPUT_NAME voro++
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/src")
install(TARGETS cmd_line RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR})
endif()
if (${VORO_BUILD_EXAMPLES})
file(GLOB EXAMPLE_SOURCES examples/*/*.cc)
foreach(SOURCE ${EXAMPLE_SOURCES})
string(REGEX REPLACE "^.*/([^/]*)\\.cc$" "\\1" PROGNAME "${SOURCE}")
if (NOT PROGNAME STREQUAL ellipsoid) #ellipsoid is broken
string(REGEX REPLACE "^.*/(examples/.*)/${PROGNAME}\\.cc$" "\\1" DIRNAME "${SOURCE}")
add_executable(${PROGNAME} ${SOURCE})
target_link_libraries(${PROGNAME} PRIVATE voro++)
set_target_properties(${PROGNAME} PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/${DIRNAME}" )
endif()
endforeach(SOURCE)
endif()
file(GLOB_RECURSE VORO_HEADERS src/voro++.hh)
install(FILES ${VORO_HEADERS} DESTINATION ${CMAKE_INSTALL_INCLUDEDIR})
install(FILES ${CMAKE_CURRENT_SOURCE_DIR}/man/voro++.1 DESTINATION ${CMAKE_INSTALL_MANDIR}/man1)
# no external deps for we can use target file as config file
install(EXPORT VORO_Targets FILE VOROConfig.cmake NAMESPACE VORO:: DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VORO)
include(CMakePackageConfigHelpers)
write_basic_package_version_file("VOROConfigVersion.cmake" VERSION ${PROJECT_VERSION} COMPATIBILITY ExactVersion)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/VOROConfigVersion.cmake" DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/VORO)
if (${VORO_ENABLE_DOXYGEN} AND DOXYGEN_FOUND)
add_custom_target(doxygen COMMAND ${DOXYGEN_EXECUTABLE} src/Doxyfile
COMMENT "Build doxygen documentation")
endif()
<file_sep>// Voro++, a 2D and 3D cell-based Voronoi library
//
// Author : <NAME> (LBL / UC Berkeley)
// Email : <EMAIL>
// Date : August 30th 2011
/** \file v_base_2d.cc
* \brief Function implementations for the base 2D Voronoi container class. */
//#include <stdio.h>
#include "v_base_2d.hh"
#include "config.hh"
namespace voro {
/** This function is called during container construction. The routine scans
* all of the worklists in the wl[] array. For a given worklist of blocks
* labeled \f$w_1\f$ to \f$w_n\f$, it computes a sequence \f$r_0\f$ to
* \f$r_n\f$ so that $r_i$ is the minimum distance to all the blocks
* \f$w_{j}\f$ where \f$j>i\f$ and all blocks outside the worklist. The values
* of \f$r_n\f$ is calculated first, as the minimum distance to any block in
* the shell surrounding the worklist. The \f$r_i\f$ are then computed in
* reverse order by considering the distance to \f$w_{i+1}\f$. */
voro_base_2d::voro_base_2d(int nx_,int ny_,double boxx_,double boxy_) :
nx(nx_), ny(ny_), nxy(nx_*ny_), boxx(boxx_), boxy(boxy_),
xsp(1/boxx_), ysp(1/boxy_), mrad(new double[wl_hgridsq_2d*wl_seq_length_2d]) {
const unsigned int b1=1<<21,b2=1<<22,b3=1<<24,b4=1<<25;
const double xstep=boxx/wl_fgrid_2d,ystep=boxy/wl_fgrid_2d;
int i,j,lx,ly,q;
unsigned int f,*e=const_cast<unsigned int*> (wl);
double xlo,ylo,xhi,yhi,minr,*radp=mrad;
for(ylo=0,yhi=ystep,ly=0;ly<wl_hgrid_2d;ylo=yhi,yhi+=ystep,ly++) {
for(xlo=0,xhi=xstep,lx=0;lx<wl_hgrid_2d;xlo=xhi,xhi+=xstep,lx++) {
minr=large_number;
for(q=e[0]+1;q<wl_seq_length_2d;q++) {
f=e[q];
i=(f&127)-64;
j=(f>>7&127)-64;
if((f&b2)==b2) {
compute_minimum(minr,xlo,xhi,ylo,yhi,i-1,j);
if((f&b1)==0) compute_minimum(minr,xlo,xhi,ylo,yhi,i+1,j);
} else if((f&b1)==b1) compute_minimum(minr,xlo,xhi,ylo,yhi,i+1,j);
if((f&b4)==b4) {
compute_minimum(minr,xlo,xhi,ylo,yhi,i,j-1);
if((f&b3)==0) compute_minimum(minr,xlo,xhi,ylo,yhi,i,j+1);
} else if((f&b3)==b3) compute_minimum(minr,xlo,xhi,ylo,yhi,i,j+1);
}
q--;
while(q>0) {
radp[q]=minr;
f=e[q];
i=(f&127)-64;
j=(f>>7&127)-64;
compute_minimum(minr,xlo,xhi,ylo,yhi,i,j);
q--;
}
*radp=minr;
e+=wl_seq_length_2d;
radp+=wl_seq_length_2d;
}
}
}
/** Computes the minimum distance from a subregion to a given block. If this distance
* is smaller than the value of minr, then it passes
* \param[in,out] minr a pointer to the current minimum distance. If the distance
* computed in this function is smaller, then this distance is
* set to the new one.
* \param[out] (xlo,ylo) the lower coordinates of the subregion being
* considered.
* \param[out] (xhi,yhi) the upper coordinates of the subregion being
* considered.
* \param[in] (ti,tj) the coordinates of the block. */
void voro_base_2d::compute_minimum(double &minr,double &xlo,double &xhi,double &ylo,double &yhi,int ti,int tj) {
double radsq,temp;
if(ti>0) {temp=boxx*ti-xhi;radsq=temp*temp;}
else if(ti<0) {temp=xlo-boxx*(1+ti);radsq=temp*temp;}
else radsq=0;
if(tj>0) {temp=boxy*tj-yhi;radsq+=temp*temp;}
else if(tj<0) {temp=ylo-boxy*(1+tj);radsq+=temp*temp;}
if(radsq<minr) minr=radsq;
}
/** Checks to see whether "%n" appears in a format sequence to determine
* whether neighbor information is required or not.
* \param[in] format the format string to check.
* \return True if a "%n" is found, false otherwise. */
bool voro_base_2d::contains_neighbor(const char *format) {
char *fmp=(const_cast<char*>(format));
// Check to see if "%n" appears in the format sequence
while(*fmp!=0) {
if(*fmp=='%') {
fmp++;
if(*fmp=='n') return true;
else if(*fmp==0) return false;
}
fmp++;
}
return false;
}
/*bool voro_base_2d::contains_neighbor_global(const char *format) {
char *fmp=(const_cast<char*>(format));
// Check to see if "%N" appears in the format sequence
while(*fmp!=0) {
if(*fmp=='%') {
fmp++;
if(*fmp=='N') return true;
else if(*fmp==0) return false;
}
fmp++;
}
return false;
}
void voro_base_2d::add_globne_info(int pid, int *nel, int length){
for(int i=0;i<length;i++){
if(nel[i]>=0){
globne[((totpar*pid)+nel[i])/32] |= (unsigned int)(1 << (((totpar*pid)+nel[i])%32));
}
}
}
void voro_base_2d::print_globne(FILE *fp){
int j=0;
fprintf(fp, "Global neighbor info: Format \n [Particle-ID] \t [Neighbors] \n [Particle-ID] \t [Neighbors]");
for(int i=0; i<totpar; i++){
fprintf(fp,"\n %d \t",i);
for(j=0;j<totpar;j++){
if((globne[(((i*totpar)+j)/32)] & (unsigned int)(1 << (((i*totpar)+j)%32))) != 0){
fprintf(fp,"%d \t",j);
}
}
}
}*/
#include "v_base_wl_2d.cc"
}
<file_sep>// Cell cutting region example code
//
// Author : <NAME> (LBL / UC Berkeley)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++_2d.hh"
using namespace voro;
const double pi=3.1415926535897932384626433832795;
// This constant sets the tolerance in the bisection search algorithm
const double tolwidth=1e-7;
// This constant determines the density of points to test
const double phi_step=pi/400;
int main() {
double x,y,r,rmin,rmax;
double phi;
voronoicell_2d v;
FILE *fp=safe_fopen("intersect_region.gnu","w");
// Initialize the Voronoi cell to be an octahedron and make a single
// plane cut to add some variation
v.init(-1,1,-1,1);
v.plane(1,1,1);
// Output the cell in gnuplot format
v.draw_gnuplot(0,0,"intersect_cell.gnu");
// Now test over direction vectors from the center of the sphere. For
// each vector, carry out a search to find the maximum distance along
// that vector that a plane will intersect with cell, and save it to
// the output file.
for(phi=phi_step*0.5;phi<2*pi;phi+=phi_step) {
// Calculate a direction to look along
x=cos(phi);
y=sin(phi);
// Now carry out a bisection search. Here, we initialize a
// minimum and a maximum guess for the distance along this
// vector. Keep multiplying rmax by two until the plane no
// longer makes a cut.
rmin=0;rmax=1;
while (v.plane_intersects(x,y,rmax)) rmax*=2;
// We now know that the distance is somewhere between rmin and
// rmax. Test the point halfway in-between these two. If it
// intersects, then move rmin to this point; otherwise, move
// rmax there. At each stage the bounding interval is divided
// by two. Exit when the width of the interval is smaller than
// the tolerance.
while (rmax-rmin>tolwidth) {
r=(rmax+rmin)*0.5;
if (v.plane_intersects(x,y,r)) rmin=r;
else rmax=r;
}
// Output this point to file
r=(rmax+rmin)*0.5;
x*=r;y*=r;
fprintf(fp,"%g %g\n",x,y);
}
fclose(fp);
}
<file_sep>#include "voro++_2d.hh"
#include <cmath>
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
const double tpi=8*atan(1.0);
int main() {
int i=0;
double x,y,t;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 6 by 6 grid, with
// an initial memory allocation of 16 particles per grid square.
container_boundary_2d con(-1,1,-1,1,6,6,false,false,8);
// Create outer circle, tracing in the positive sense (i.e. anticlockwise)
con.start_boundary();
for(t=0.01*tpi;t<tpi;t+=0.02*tpi,i++) con.put(i,0.95*cos(t),0.95*sin(t));
con.end_boundary();
// Create inner circle. Since this is a hole, the points must trace around
// the circle in the opposite sense (i.e. clockwise)
con.start_boundary();
for(t=0;t<tpi;t+=0.02*tpi,i++) con.put(i,0.6*cos(t),0.6*sin(-t));
con.end_boundary();
// Add random points
while(i<500) {
x=-1+2*rnd();
y=-1+2*rnd();
if(con.point_inside(x,y)) {con.put(i,x,y);i++;}
}
// Output
con.draw_boundary_gnuplot("annulus.bd");
con.draw_particles("annulus.par");
con.setup();
con.draw_cells_gnuplot("annulus.gnu");
}
<file_sep>// Custom output example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-3,x_max=3;
const double y_min=-3,y_max=3;
const double z_min=0,z_max=6;
// Set up the number of blocks that the container is divided
// into.
const int n_x=3,n_y=3,n_z=3;
int main() {
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block.
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Import the monodisperse test packing and output the Voronoi
// tessellation in gnuplot and POV-Ray formats.
con.import("pack_six_cube");
// Do a custom output routine to store the number of vertices, edges,
// and faces of each Voronoi cell
con.print_custom(
"ID=%i, pos=(%x,%y,%z), vertices=%w, edges=%g, faces=%s",
"packing.custom1");
// Do a custom output routine to store a variety of face-based
// statistics. Store the particle ID and position, the number of faces
// the total face area, the order of each face, the areas of each face,
// the vertices making up each face, and the neighboring particle (or
// wall) corresponding to each face.
con.print_custom("%i %q %s %F %a %f %t %l %n","packing.custom2");
// Do a custom output routine that outputs the particle IDs and
// positions, plus the volume and the centroid position relative to the
// particle center
con.print_custom("%i %q %v %c","packing.custom3");
// Also create POV-Ray output of the Voronoi cells for use in the
// rendering
con.draw_cells_pov("pack_six_cube_v.pov");
}
<file_sep>// Voronoi calculation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
const double cvol=(x_max-x_min)*(y_max-y_min)*(z_max-z_min);
// Set up the number of blocks that the container is divided into
const int n_x=6,n_y=6,n_z=6;
// Set the number of particles that are going to be randomly introduced
const int particles=20;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Randomly add particles into the container
for(i=0;i<particles;i++) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
con.put(i,x,y,z);
}
// Use the C++ interface to do custom computations
double cx,cy,cz,vvol=0;
voronoicell c;
c_loop_all cl(con);
if(cl.start()) do if(con.compute_cell(c,cl)) {
// Get particle position and ID
cl.pos(x,y,z);i=cl.pid();
// Calculate centroid
c.centroid(cx,cy,cz);
printf("Particle %2d at (% .3f,% .3f,% .3f), centroid at (% .3f,% .3f,% .3f)\n",
i,x,y,z,x+cx,y+cy,z+cz);
// Calculate volume and sum it
vvol+=c.volume();
// Do other calculations and store the information
// ...
// ...
// ...
} while(cl.inc());
// Print the volume check
printf("\nContainer volume : %g\n"
"Voronoi volume : %g\n"
"Difference : %g\n",cvol,vvol,vvol-cvol);
// Output the particle positions in gnuplot format
con.draw_particles("random_points_p.gnu");
// Output the Voronoi cells in gnuplot format
con.draw_cells_gnuplot("random_points_v.gnu");
}
<file_sep># Voro++ makefile
#
# Author : <NAME> (LBL / UC Berkeley)
# Email : <EMAIL>
# Date : August 30th 2011
# Makefile rules
all: ex_basic ex_walls ex_boundary ex_extra
ex_basic:
$(MAKE) -C basic
ex_walls:
$(MAKE) -C walls
ex_boundary:
$(MAKE) -C boundary
ex_extra:
$(MAKE) -C extra
clean:
$(MAKE) -C basic clean
$(MAKE) -C walls clean
$(MAKE) -C boundary clean
$(MAKE) -C extra clean
.PHONY: all ex_basic ex_walls ex_boundary ex_extra clean
<file_sep>// Example code demonstrating find_voronoi_cell function
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// The sampling distance for the grids of find_voronoi_cell calls
const double h=0.05;
// The cube of the sampling distance, corresponding the amount of volume
// associated with a sample point
const double hcube=h*h*h;
// Set the number of particles that are going to be randomly introduced
const int particles=20;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y,z,r,rx,ry,rz;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(0,1,0,1,0,1,5,5,5,false,false,false,8);
// Randomly add particles into the container
for(i=0;i<particles;i++) {
x=rnd();
y=rnd();
z=rnd();
con.put(i,x,y,z);
}
// Output the particle positions in gnuplot format
con.draw_particles("find_voro_cell_p.gnu");
// Scan a 2D slice in the container, and for each point in the slice,
// find the Voronoi cell that the point is in. Store a vector
FILE *f1=safe_fopen("find_voro_cell.vec","w");
for(x=0.5*h;x<1;x+=h) for(y=0.5*h;y<1;y+=h) {
if(con.find_voronoi_cell(x,y,0.5,rx,ry,rz,i))
fprintf(f1,"%g %g %g %g %g %g %g\n",x,y,0.5,rx-x,ry-y,rz-0.5,
sqrt((rx-x)*(rx-x)+(ry-y)*(ry-y)+(rz-0.5)*(rz-0.5)));
else fprintf(stderr,"# find_voronoi_cell error for %g %g 0.5\n",x,y);
}
fclose(f1);
// Create a blank array for storing the sampled Voronoi volumes
int samp_v[particles];
for(i=0;i<particles;i++) samp_v[i]=0;
// Scan over a grid covering the entire container, finding which
// Voronoi cell each point is in, and tallying the result as a method
// of sampling the volume of each Voronoi cell
for(z=0.5*h;z<1;z+=h) for(y=0.5*h;y<1;y+=h) for(x=0.5*h;x<1;x+=h) {
if(con.find_voronoi_cell(x,y,z,rx,ry,rz,i)) samp_v[i]++;
else fprintf(stderr,"# find_voronoi_cell error for %g %g %g\n",x,y,z);
}
// Output the Voronoi cells in gnuplot format and a file with the
// comparisons between the Voronoi cell volumes and the sampled volumes
f1=safe_fopen("find_voro_cell.vol","w");
FILE *f2=safe_fopen("find_voro_cell_v.gnu","w");
c_loop_all cla(con);
voronoicell c;
if(cla.start()) do if (con.compute_cell(c,cla)) {
// Get the position and ID information for the particle
// currently being considered by the loop. Ignore the radius
// information.
cla.pos(i,x,y,z,r);
// Save and entry to the .vol file, storing both the computed
// Voronoi cell volume, and the sampled volume based on the
// number of grid points that were inside the cell
fprintf(f1,"%d %g %g %g %g %g\n",i,x,y,z,c.volume(),samp_v[i]*hcube);
// Draw the Voronoi cell
c.draw_gnuplot(x,y,z,f2);
} while (cla.inc());
fclose(f1);
fclose(f2);
}
<file_sep>// Voronoi calculation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
const double cvol=(x_max-x_min)*(y_max-y_min)*(x_max-x_min);
// Set up the number of blocks that the container is divided into
const int n_x=3,n_y=3,n_z=3;
// Set the number of particles that are going to be randomly introduced
const int particles=1000;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double pos[particles*4],*posp=pos;
for(i=0;i<particles;i++) {
*(posp++)=x_min+rnd()*(x_max-x_min);
*(posp++)=y_min+rnd()*(y_max-y_min);
*(posp++)=z_min+rnd()*(z_max-z_min);
*(posp++)=rnd();
}
char buf[128];
for(i=0;i<=200;i++) {
int j;double x,y,z,r,mul=i*0.01,vol=0;
container_poly con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
posp=pos;
for(int j=0;j<particles;j++) {
x=*(posp++);y=*(posp++);z=*(posp++);r=*(posp++)*mul;
con.put(j,x,y,z,r);
}
sprintf(buf,"rad_test_out/fr%d.pov",i);
// FILE *pf=safe_fopen(buf,"w");
j=0;
c_loop_all cl(con);
voronoicell c;
cl.start();
do {
if(con.compute_cell(c,cl)) {
vol+=c.volume();
cl.pos(x,y,z);
// c.draw_pov(x,y,z,pf);
j++;
}
} while(cl.inc());
printf("%g %d %g %g\n",mul,j,vol,vol-8);
// fclose(pf);
}
}
<file_sep>// Radical Voronoi tessellation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-3,x_max=3;
const double y_min=-3,y_max=3;
const double z_min=0,z_max=6;
// Set up the number of blocks that the container is divided
// into.
const int n_x=3,n_y=3,n_z=3;
int main() {
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block. Import
// the monodisperse test packing and output the Voronoi
// tessellation in gnuplot and POV-Ray formats.
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
con.import("pack_six_cube");
con.draw_cells_gnuplot("pack_six_cube.gnu");
con.draw_cells_pov("pack_six_cube_v.pov");
con.draw_particles_pov("pack_six_cube_p.pov");
// Create a container for polydisperse particles using the same
// geometry as above. Import the polydisperse test packing and
// output the Voronoi radical tessellation in gnuplot and POV-Ray
// formats.
container_poly conp(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
conp.import("pack_six_cube_poly");
conp.draw_cells_gnuplot("pack_six_cube_poly.gnu");
conp.draw_cells_pov("pack_six_cube_poly_v.pov");
conp.draw_particles_pov("pack_six_cube_poly_p.pov");
}
<file_sep>// Cell cutting region example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
const double pi=3.1415926535897932384626433832795;
// This constant sets the tolerance in the bisection search algorithm
const double tolwidth=1e-7;
// This constant determines the density of points to test
const double theta_step=pi/200;
int main() {
double x,y,z,r,rmin,rmax;
double theta,phi,phi_step;
voronoicell v;
FILE *fp=safe_fopen("cell_cut_region.gnu","w");
// Initialize the Voronoi cell to be an octahedron and make a single
// plane cut to add some variation
v.init_octahedron(1);
v.plane(0.4,0.3,1,0.1);
// Output the cell in gnuplot format
v.draw_gnuplot(0,0,0,"cell.gnu");
// Now test over direction vectors from the center of the sphere. For
// each vector, carry out a search to find the maximum distance along
// that vector that a plane will intersect with cell, and save it to
// the output file.
for(theta=theta_step*0.5;theta<pi;theta+=theta_step) {
phi_step=2*pi/(int(2*pi*sin(theta)/theta_step)+1);
for(phi=phi_step*0.5;phi<2*pi;phi+=phi_step) {
// Calculate a direction to look along
x=sin(theta)*cos(phi);
y=sin(theta)*sin(phi);
z=cos(theta);
// Now carry out a bisection search. Here, we initialize
// a minimum and a maximum guess for the distance
// along this vector. Keep multiplying rmax by two until
// the plane no longer makes a cut.
rmin=0;rmax=1;
while (v.plane_intersects(x,y,z,rmax)) rmax*=2;
// We now know that the distance is somewhere between
// rmin and rmax. Test the point halfway in-between
// these two. If it intersects, then move rmin to this
// point; otherwise, move rmax there. At each stage the
// bounding interval is divided by two. Exit when the
// width of the interval is smaller than the tolerance.
while (rmax-rmin>tolwidth) {
r=(rmax+rmin)*0.5;
if (v.plane_intersects(x,y,z,r)) rmin=r;
else rmax=r;
}
// Output this point to file
r=(rmax+rmin)*0.5;
x*=r;y*=r;z*=r;
fprintf(fp,"%g %g %g\n",x,y,z);
}
}
fclose(fp);
}
<file_sep>// Voro++, a 3D cell-based Voronoi library
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
/** \file common.hh
* \brief Header file for the small helper functions. */
#ifndef VOROPP_COMMON_HH
#define VOROPP_COMMON_HH
#include <cstdio>
#include <cstdlib>
#include <vector>
#include "config.hh"
namespace voro {
void check_duplicate(int n,double x,double y,double z,int id,double *qp);
void voro_fatal_error(const char *p,int status);
void voro_print_positions(std::vector<double> &v,FILE *fp=stdout);
FILE* safe_fopen(const char *filename,const char *mode);
void voro_print_vector(std::vector<int> &v,FILE *fp=stdout);
void voro_print_vector(std::vector<double> &v,FILE *fp=stdout);
void voro_print_face_vertices(std::vector<int> &v,FILE *fp=stdout);
}
#endif
<file_sep>#ifndef CONTAINER_QUAD_2D_HH
#define CONTAINER_QUAD_2D_HH
#include "cell_2d.hh"
#include "config.hh"
#include "common.hh"
namespace voro {
const int qt_max=6;
class container_quad_2d;
class quadtree {
public:
container_quad_2d &parent;
const double cx;
const double cy;
const double lx;
const double ly;
const int ps;
int *id;
double *p;
int co;
unsigned int mask;
quadtree *qsw;
quadtree *qse;
quadtree *qnw;
quadtree *qne;
quadtree **nei;
int nco;
quadtree(double cx_,double cy_,double lx_,double ly_,container_quad_2d &parent_);
~quadtree();
void put(int i,double x,double y);
void split();
void draw_particles(FILE *fp=stdout);
void draw_cross(FILE *fp=stdout);
void setup_neighbors();
void draw_neighbors(FILE *fp=stdout);
void draw_cells_gnuplot(FILE *fp=stdout);
inline void quick_put(int i,double x,double y) {
id[co]=i;
p[ps*co]=x;
p[1+ps*co++]=y;
}
inline void add_neighbor(quadtree *qt) {
if(nco==nmax) add_neighbor_memory();
nei[nco++]=qt;
}
inline void bound(double &xlo,double &xhi,double &ylo,double &yhi) {
xlo=cx-lx;xhi=cx+lx;
ylo=cy-ly;yhi=cy+ly;
}
double sum_cell_areas();
void compute_all_cells();
bool compute_cell(voronoicell_2d &c,int j);
void reset_mask();
protected:
int nmax;
inline bool corner_test(voronoicell_2d &c,double xl,double yl,double xh,double yh);
inline bool edge_x_test(voronoicell_2d &c,double xl,double y0,double y1);
inline bool edge_y_test(voronoicell_2d &c,double x0,double yl,double x1);
void we_neighbors(quadtree *qw,quadtree *qe);
void ns_neighbors(quadtree *qs,quadtree *qn);
void add_neighbor_memory();
};
class container_quad_2d : public quadtree {
public:
using quadtree::draw_particles;
using quadtree::draw_neighbors;
using quadtree::draw_cells_gnuplot;
/** The minimum x coordinate of the container. */
const double ax;
/** The maximum x coordinate of the container. */
const double bx;
/** The minimum y coordinate of the container. */
const double ay;
/** The maximum y coordinate of the container. */
const double by;
unsigned int bmask;
container_quad_2d(double ax_,double bx_,double ay_,double by_);
inline void draw_particles(const char* filename) {
FILE *fp=safe_fopen(filename,"w");
draw_particles(fp);
fclose(fp);
}
inline void draw_neighbors(const char* filename) {
FILE *fp=safe_fopen(filename,"w");
draw_neighbors(fp);
fclose(fp);
}
inline void draw_cells_gnuplot(const char* filename) {
FILE *fp=safe_fopen(filename,"w");
draw_cells_gnuplot(fp);
fclose(fp);
}
void draw_quadtree(FILE *fp=stdout);
inline void draw_quadtree(const char* filename) {
FILE *fp=safe_fopen(filename,"w");
draw_quadtree(fp);
fclose(fp);
}
inline void initialize_voronoicell(voronoicell_2d &c,double x,double y) {
c.init(ax-x,bx-x,ay-y,by-y);
}
};
}
#endif
<file_sep>// Voronoi calculation example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
#include <vector>
using namespace std;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
// Set up the number of blocks that the container is divided into
const int n_x=6,n_y=6,n_z=6;
// Set the number of particles that are going to be randomly introduced
const int particles=1;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i,j,id,nv;
double x,y,z;
// Create a container with the geometry given above, and make it
// non-periodic in each of the three coordinates. Allocate space for
// eight particles within each computational block
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
false,false,false,8);
// Randomly add particles into the container
for(i=0;i<particles;i++) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
con.put(i,x,y,z);
}
// Sum up the volumes, and check that this matches the container volume
c_loop_all cl(con);
vector<int> f_vert;
vector<double> v;
voronoicell c;
if(cl.start()) do if(con.compute_cell(c,cl)) {
cl.pos(x,y,z);id=cl.pid();
printf("Particle %d:\n",id);
// Gather information about the computed Voronoi cell
c.face_vertices(f_vert);
c.vertices(x,y,z,v);
// Print vertex positions
for(i=0;i<v.size();i+=3) printf("Vertex %d : (%g,%g,%g)\n",i/3,v[i],v[i+1],v[i+2]);
puts("");
// Loop over all faces of the Voronoi cell
j=0;
while(j<f_vert.size()) {
// Number of vertices in this face
nv=f_vert[j];
// Print triangles
for(i=2;i<nv;i++)
printf("Triangle : (%d,%d,%d)\n",f_vert[j+1],f_vert[j+i],f_vert[j+i+1]);
// Move j to point at the next face
j+=nv+1;
}
puts("");
} while (cl.inc());
// Output the particle positions in gnuplot format
con.draw_particles("random_points_p.gnu");
// Output the Voronoi cells in gnuplot format
con.draw_cells_gnuplot("random_points_v.gnu");
}
<file_sep>// Irregular packing example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// Set the number of particles that are going to be randomly introduced
const int particles=20;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
// Create a wall class that will initialize the Voronoi cell to fill the
// L-shaped domain
class wall_l_shape : public wall {
public:
wall_l_shape() {
v.init_l_shape();
v.draw_gnuplot(0,0,0,"l_shape_init.gnu");
};
bool point_inside(double x,double y,double z) {return true;}
bool cut_cell(voronoicell &c,double x,double y,double z) {
// Set the cell to be equal to the L-shape
c=v;
c.translate(-x,-y,-z);
// Set the tolerance to 100, to make the code search
// for cases where non-convex cells are cut in multiple
// places
c.big_tol=100;
return true;
}
bool cut_cell(voronoicell_neighbor &c,double x,double y,double z) {
// Set the cell to be equal to the L-shape
c=v;
c.translate(-x,-y,-z);
// Set the tolerance to 100, to make the code search
// for cases where non-convex cells are cut in multiple
// places
c.big_tol=100;
return true;
}
private:
voronoicell v;
};
int main() {
int i=0;
double x,y,z;
// Create a container
container con(-1,1,-1,1,-1,1,5,5,5,false,false,false,8);
// Create the L-shape wall class and add it to the container
wall_l_shape(wls);
con.add_wall(wls);
// Add particles, making sure not to place any outside of the L-shape
while(i<particles) {
x=2*rnd()-1;
y=2*rnd()-1;
if(x<0&&y>0) continue;
z=2*rnd()-1;
con.put(i,x,y,z);
i++;
}
// Check the Voronoi cell volume; it should be 6
printf("Voronoi cell volume: %.8g\n",con.sum_cell_volumes());
// Save the particles and Voronoi cells in gnuplot format
con.draw_particles("l_shape_p.gnu");
con.draw_cells_gnuplot("l_shape_v.gnu");
}
<file_sep>#include "voro++_2d.hh"
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;
double x,y;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 6 by 6 grid, with
// an initial memory allocation of 16 particles per grid square.
container_boundary_2d con(-1,1,-1,1,6,6,false,false,8);
// Create comb-like domain
con.start_boundary();
con.put(0,-0.9,-0.9);
con.put(1,0.9,-0.9);
con.put(2,0.9,0.9);
i=3;
for(x=0.8;x>-0.9;x-=0.2) {
con.put(i,x,-0.7);i++;
con.put(i,x-0.1,0.9);i++;
}
con.end_boundary();
// Add random points
while(i<200) {
x=-1+2*rnd();
y=-1+2*rnd();
if(con.point_inside(x,y)) {con.put(i,x,y);i++;}
}
con.draw_boundary_gnuplot("comb.bd");
con.draw_particles("comb.par");
con.setup();
con.draw_cells_gnuplot("comb.gnu");
// Sum the Voronoi cell areas and compare to the container area
// double carea=1,varea=con.sum_cell_areas();
// printf("Total container area : %g\n"
// "Total Voronoi cell area : %g\n"
// "Difference : %g\n",carea,varea,varea-carea);
}
<file_sep>#include "ctr_quad_2d.hh"
#include "quad_march.hh"
#include <vector>
#include <limits>
#include <deque>
namespace voro {
container_quad_2d::container_quad_2d(double ax_,double bx_,double ay_,double by_) :
quadtree((ax_+bx_)*0.5,(ay_+by_)*0.5,(bx_-ax_)*0.5,(by_-ay_)*0.5,*this),
ax(ax_), bx(bx_), ay(ay_), by(by_), bmask(0) {
}
quadtree::quadtree(double cx_,double cy_,double lx_,double ly_,container_quad_2d &parent_) :
parent(parent_), cx(cx_), cy(cy_), lx(lx_), ly(ly_), ps(2),
id(new int[qt_max]), p(new double[ps*qt_max]), co(0), mask(0), nco(0), nmax(0) {
}
quadtree::~quadtree() {
if(id==NULL) {
delete qne;delete qnw;
delete qse;delete qsw;
} else {
delete [] p;
delete [] id;
}
if(nmax>0) delete [] nei;
}
void quadtree::split() {
double hx=0.5*lx,hy=0.5*ly;
qsw=new quadtree(cx-hx,cy-hy,hx,hy,parent);
qse=new quadtree(cx+hx,cy-hy,hx,hy,parent);
qnw=new quadtree(cx-hx,cy+hy,hx,hy,parent);
qne=new quadtree(cx+hx,cy+hy,hx,hy,parent);
for(int i=0;i<co;i++)
(p[ps*i]<cx?(p[ps*i+1]<cy?qsw:qnw)
:(p[ps*i+1]<cy?qse:qne))->quick_put(id[i],p[ps*i],p[ps*i+1]);
delete [] id;id=NULL;
delete [] p;
}
void quadtree::put(int i,double x,double y) {
if(id!=NULL) {
if(co==qt_max) split();
else {
quick_put(i,x,y);
return;
}
}
(x<cx?(y<cy?qsw:qnw):(y<cy?qse:qne))->put(i,x,y);
}
void quadtree::draw_cross(FILE *fp) {
if(id==NULL) {
fprintf(fp,"%g %g\n%g %g\n\n\n%g %g\n%g %g\n\n\n",
cx-lx,cy,cx+ly,cy,cx,cy-ly,cx,cy+ly);
qsw->draw_cross(fp);
qse->draw_cross(fp);
qnw->draw_cross(fp);
qne->draw_cross(fp);
}
}
void quadtree::reset_mask() {
mask=0;
if(id==NULL) {
qsw->reset_mask();
qse->reset_mask();
qnw->reset_mask();
qne->reset_mask();
}
}
void container_quad_2d::draw_quadtree(FILE *fp) {
fprintf(fp,"%g %g\n%g %g\n%g %g\n%g %g\n%g %g\n",ax,ay,bx,ay,bx,by,ax,by,ax,ay);
draw_cross(fp);
}
void quadtree::draw_neighbors(FILE *fp) {
for(int i=0;i<nco;i++)
fprintf(fp,"%g %g %g %g\n",cx,cy,nei[i]->cx-cx,nei[i]->cy-cy);
if(id==NULL) {
qsw->draw_neighbors(fp);
qse->draw_neighbors(fp);
qnw->draw_neighbors(fp);
qne->draw_neighbors(fp);
}
}
void quadtree::draw_particles(FILE *fp) {
if(id==NULL) {
qsw->draw_particles(fp);
qse->draw_particles(fp);
qnw->draw_particles(fp);
qne->draw_particles(fp);
} else for(int i=0;i<co;i++)
fprintf(fp,"%d %g %g\n",id[i],p[ps*i],p[ps*i+1]);
}
void quadtree::draw_cells_gnuplot(FILE *fp) {
if(id==NULL) {
qsw->draw_cells_gnuplot(fp);
qse->draw_cells_gnuplot(fp);
qnw->draw_cells_gnuplot(fp);
qne->draw_cells_gnuplot(fp);
} else {
voronoicell_2d c;
for(int j=0;j<co;j++) if(compute_cell(c,j))
c.draw_gnuplot(p[ps*j],p[ps*j+1],fp);
}
}
double quadtree::sum_cell_areas() {
if(id==NULL)
return qsw->sum_cell_areas()+qse->sum_cell_areas()
+qnw->sum_cell_areas()+qne->sum_cell_areas();
double area=0;
voronoicell_2d c;
for(int j=0;j<co;j++) if(compute_cell(c,j))
area+=c.area();
return area;
}
void quadtree::compute_all_cells() {
if(id==NULL) {
qsw->compute_all_cells();
qse->compute_all_cells();
qnw->compute_all_cells();
qne->compute_all_cells();
} else{
voronoicell_2d c;
for(int j=0;j<co;j++) compute_cell(c,j);
}
}
void quadtree::setup_neighbors() {
if(id==NULL) {
qsw->setup_neighbors();
qse->setup_neighbors();
qnw->setup_neighbors();
qne->setup_neighbors();
we_neighbors(qsw,qse);
we_neighbors(qnw,qne);
ns_neighbors(qsw,qnw);
ns_neighbors(qse,qne);
}
}
void quadtree::we_neighbors(quadtree *qw,quadtree *qe) {
const int ma=1<<30;
quad_march<0> mw(qw);
quad_march<1> me(qe);
while(mw.s<ma||me.s<ma) {
mw.cu()->add_neighbor(me.cu());
me.cu()->add_neighbor(mw.cu());
if(mw.ns>me.ns) me.step();
else {
if(mw.ns==me.ns) me.step();
mw.step();
}
}
}
void quadtree::ns_neighbors(quadtree *qs,quadtree *qn) {
const int ma=1<<30;
quad_march<2> ms(qs);
quad_march<3> mn(qn);
while(ms.s<ma||mn.s<ma) {
ms.cu()->add_neighbor(mn.cu());
mn.cu()->add_neighbor(ms.cu());
if(ms.ns>mn.ns) mn.step();
else {
if(ms.ns==mn.ns) mn.step();
ms.step();
}
}
}
void quadtree::add_neighbor_memory() {
if(nmax==0) {
nmax=4;
nei=new quadtree*[nmax];
}
if(nmax>16777216) {
fputs("Maximum quadtree neighbor memory exceeded\n",stderr);
exit(1);
}
nmax<<=1;
quadtree** pp=new quadtree*[nmax];
for(int i=0;i<nco;i++) pp[i]=nei[i];
delete [] nei;
nei=pp;
}
bool quadtree::compute_cell(voronoicell_2d &c,int j) {
int i;
double x=p[ps*j],y=p[ps*j+1],x1,y1,xlo,xhi,ylo,yhi;
quadtree *q;
parent.initialize_voronoicell(c,x,p[ps*j+1]);
for(i=0;i<j;i++) {
x1=p[ps*i]-x;
y1=p[ps*i+1]-y;
if(!c.nplane(x1,y1,x1*x1+y1*y1,id[i])) return false;
}
i++;
while(i<co) {
x1=p[ps*i]-x;
y1=p[ps*i+1]-y;
if(!c.nplane(x1,y1,x1*x1+y1*y1,id[i])) return false;
i++;
}
unsigned int &bm=parent.bmask;
bm++;
if(bm==0) {
reset_mask();
bm=1;
}
mask=bm;
deque<quadtree*> dq;
for(i=0;i<nco;i++) {
dq.push_back(nei[i]);
nei[i]->mask=bm;
}
while(!dq.empty()) {
q=dq.front();dq.pop_front();
q->bound(xlo,xhi,ylo,yhi);
xlo-=x;xhi-=x;
ylo-=y;yhi-=y;
if(xlo>0) {
if(ylo>0) {
if(corner_test(c,xlo,ylo,xhi,yhi)) continue;
} else if(yhi<0) {
if(corner_test(c,xlo,yhi,xhi,ylo)) continue;
} else {
if(edge_x_test(c,xlo,ylo,yhi)) continue;
}
} else if(xhi<0) {
if(ylo>0) {
if(corner_test(c,xhi,ylo,xlo,yhi)) continue;
} else if(yhi<0) {
if(corner_test(c,xhi,yhi,xlo,ylo)) continue;
} else {
if(edge_x_test(c,xhi,ylo,yhi)) continue;
}
} else {
if(ylo>0) {
if(edge_y_test(c,xlo,ylo,xhi)) continue;
} else if(yhi<0) {
if(edge_y_test(c,xlo,yhi,xhi)) continue;
} else voro_fatal_error("Compute cell routine revisiting central block, which should never\nhappen.",VOROPP_INTERNAL_ERROR);
}
for(i=0;i<q->co;i++) {
x1=q->p[ps*i]-x;
y1=q->p[ps*i+1]-y;
if(!c.nplane(x1,y1,x1*x1+y1*y1,id[i])) return false;
}
for(i=0;i<q->nco;i++) if(q->nei[i]->mask!=bm) {
dq.push_back(q->nei[i]);
q->nei[i]->mask=bm;
}
}
return true;
}
inline bool quadtree::corner_test(voronoicell_2d &c,double xl,double yl,double xh,double yh) {
if(c.plane_intersects_guess(xl,yh,xl*xl+yl*yh)) return false;
if(c.plane_intersects(xh,yl,xl*xh+yl*yl)) return false;
return true;
}
inline bool quadtree::edge_x_test(voronoicell_2d &c,double xl,double y0,double y1) {
if(c.plane_intersects_guess(xl,y0,xl*xl)) return false;
if(c.plane_intersects(xl,y1,xl*xl)) return false;
return true;
}
inline bool quadtree::edge_y_test(voronoicell_2d &c,double x0,double yl,double x1) {
if(c.plane_intersects_guess(x0,yl,yl*yl)) return false;
if(c.plane_intersects(x1,yl,yl*yl)) return false;
return true;
}
}
<file_sep>// Voro++, a 3D cell-based Voronoi library
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
/** \file common.cc
* \brief Implementations of the small helper functions. */
#include "common.hh"
namespace voro {
void check_duplicate(int n,double x,double y,double z,int id,double *qp) {
double dx=*qp-x,dy=qp[1]-y,dz=qp[2]-z;
if(dx*dx+dy*dy+dz*dz<1e-10) {
printf("Duplicate: %d (%g,%g,%g) matches %d (%g,%g,%g)\n",n,x,y,z,id,*qp,qp[1],qp[2]);
exit(1);
}
}
/** \brief Function for printing fatal error messages and exiting.
*
* Function for printing fatal error messages and exiting.
* \param[in] p a pointer to the message to print.
* \param[in] status the status code to return with. */
void voro_fatal_error(const char *p,int status) {
fprintf(stderr,"voro++: %s\n",p);
exit(status);
}
/** \brief Prints a vector of positions.
*
* Prints a vector of positions as bracketed triplets.
* \param[in] v the vector to print.
* \param[in] fp the file stream to print to. */
void voro_print_positions(std::vector<double> &v,FILE *fp) {
if(v.size()>0) {
fprintf(fp,"(%g,%g,%g)",v[0],v[1],v[2]);
for(int k=3;(unsigned int) k<v.size();k+=3) {
fprintf(fp," (%g,%g,%g)",v[k],v[k+1],v[k+2]);
}
}
}
/** \brief Opens a file and checks the operation was successful.
*
* Opens a file, and checks the return value to ensure that the operation
* was successful.
* \param[in] filename the file to open.
* \param[in] mode the cstdio fopen mode to use.
* \return The file handle. */
FILE* safe_fopen(const char *filename,const char *mode) {
FILE *fp=fopen(filename,mode);
if(fp==NULL) {
fprintf(stderr,"voro++: Unable to open file '%s'\n",filename);
exit(VOROPP_FILE_ERROR);
}
return fp;
}
/** \brief Prints a vector of integers.
*
* Prints a vector of integers.
* \param[in] v the vector to print.
* \param[in] fp the file stream to print to. */
void voro_print_vector(std::vector<int> &v,FILE *fp) {
int k=0,s=v.size();
while(k+4<s) {
fprintf(fp,"%d %d %d %d ",v[k],v[k+1],v[k+2],v[k+3]);
k+=4;
}
if(k+3<=s) {
if(k+4==s) fprintf(fp,"%d %d %d %d",v[k],v[k+1],v[k+2],v[k+3]);
else fprintf(fp,"%d %d %d",v[k],v[k+1],v[k+2]);
} else {
if(k+2==s) fprintf(fp,"%d %d",v[k],v[k+1]);
else fprintf(fp,"%d",v[k]);
}
}
/** \brief Prints a vector of doubles.
*
* Prints a vector of doubles.
* \param[in] v the vector to print.
* \param[in] fp the file stream to print to. */
void voro_print_vector(std::vector<double> &v,FILE *fp) {
int k=0,s=v.size();
while(k+4<s) {
fprintf(fp,"%g %g %g %g ",v[k],v[k+1],v[k+2],v[k+3]);
k+=4;
}
if(k+3<=s) {
if(k+4==s) fprintf(fp,"%g %g %g %g",v[k],v[k+1],v[k+2],v[k+3]);
else fprintf(fp,"%g %g %g",v[k],v[k+1],v[k+2]);
} else {
if(k+2==s) fprintf(fp,"%g %g",v[k],v[k+1]);
else fprintf(fp,"%g",v[k]);
}
}
/** \brief Prints a vector a face vertex information.
*
* Prints a vector of face vertex information. A value is read, which
* corresponds to the number of vertices in the next face. The routine reads
* this number of values and prints them as a bracked list. This is repeated
* until the end of the vector is reached.
* \param[in] v the vector to interpret and print.
* \param[in] fp the file stream to print to. */
void voro_print_face_vertices(std::vector<int> &v,FILE *fp) {
int j,k=0,l;
if(v.size()>0) {
l=v[k++];
if(l<=1) {
if(l==1) fprintf(fp,"(%d)",v[k++]);
else fputs("()",fp);
} else {
j=k+l;
fprintf(fp,"(%d",v[k++]);
while(k<j) fprintf(fp,",%d",v[k++]);
fputs(")",fp);
}
while((unsigned int) k<v.size()) {
l=v[k++];
if(l<=1) {
if(l==1) fprintf(fp," (%d)",v[k++]);
else fputs(" ()",fp);
} else {
j=k+l;
fprintf(fp," (%d",v[k++]);
while(k<j) fprintf(fp,",%d",v[k++]);
fputs(")",fp);
}
}
}
}
}
<file_sep>// Timing test example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include <ctime>
using namespace std;
#include "voro++.cc"
using namespace voro;
// Set up constants for the container geometry
const double x_min=-1,x_max=1;
const double y_min=-1,y_max=1;
const double z_min=-1,z_max=1;
// Set up the number of blocks that the container is divided into. If the
// preprocessor variable NNN hasn't been passed to the code, then initialize it
// to a good value. Otherwise, use the value that has been passed.
#ifndef NNN
#define NNN 26
#endif
const int n_x=NNN,n_y=NNN,n_z=NNN;
// Set the number of particles that are going to be randomly introduced
const int particles=100000;
// This function returns a random double between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
clock_t start,end;
int i;double x,y,z;
// Create a container with the geometry given above, and make it
// periodic in each of the three coordinates. Allocate space for eight
// particles within each computational block.
container con(x_min,x_max,y_min,y_max,z_min,z_max,n_x,n_y,n_z,
true,true,true,8);
//Randomly add particles into the container
for(i=0;i<particles;i++) {
x=x_min+rnd()*(x_max-x_min);
y=y_min+rnd()*(y_max-y_min);
z=z_min+rnd()*(z_max-z_min);
con.put(i,x,y,z);
}
// Store the initial clock time
start=clock();
// Carry out a dummy computation of all cells in the entire container
con.compute_all_cells();
// Calculate the elapsed time and print it
end=clock();
double runtime=double(end-start)/CLOCKS_PER_SEC;
printf("%g\n",runtime);
}
<file_sep>// Single Voronoi cell example code
//
// Author : <NAME> (Harvard SEAS / LBL)
// Email : <EMAIL>
// Date : February 16th 2014
#include "voro++.hh"
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
// double x,y,z,rsq,r;
voronoicell v;
v.init_l_shape();
v.draw_gnuplot(0,0,0,"single_cell.gnu");
int lp=-1,ls=-1;
double l=1e-20,u=1e-20;
//bool suc=v.search_upward(-1,3,0,0.5,lp,ls,l,u);
v.plane(-1,3,0,0.5);
v.draw_gnuplot(0,0,0,"single_cell2.gnu");
v.plane(-1,3,0.4,0.53);
v.plane(-1,3,-0.4,0.54);
puts("cr");
v.check_relations();
v.check_duplicates();
puts("fi");
// v.plane(-1,3,-0.2,0.54);
bool suc=true;
printf("%s lp=%d ls=%d l=%g u=%g up=%d\n",suc?"True":"False",lp,ls,l,u,v.up);
v.draw_gnuplot(0,0,0,"single_cell3.gnu");
}
<file_sep>#include <ctime>
#include "voro++_2d.hh"
using namespace voro;
// Set up the number of blocks that the container is divided into. If the
// preprocessor variable NNN hasn't been passed to the code, then initialize it
// to a good value. Otherwise, use the value that has been passed.
#ifndef NNN
#define NNN 26
#endif
// Set the number of particles that are going to be randomly introduced
const int particles=100000;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
clock_t start,end;
int i;double x,y;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 6 by 6 grid, with
// an initial memory allocation of 16 particles per grid square.
container_2d con(0,1,0,1,NNN,NNN,false,false,16);
//Randomly add particles into the container
for(i=0;i<particles;i++) {
x=rnd();
y=rnd();
con.put(i,x,y);
}
// Store the initial clock time
start=clock();
// Carry out a dummy computation of all cells in the entire container
con.compute_all_cells();
// Calculate the elapsed time and print it
end=clock();
double runtime=double(end-start)/CLOCKS_PER_SEC;
printf("%g\n",runtime);
}
<file_sep>// Splitting a Voronoi cell example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
double x,y,z,rsq,r;
voronoicell v,v2;
// Initialize the Voronoi cell to be a cube of side length 2, centered
// on the origin
v.init(-1,1,-1,1,-1,1);
// Cut the cell by 250 random planes which are all a distance 1 away
// from the origin, to make an approximation to a sphere
for(int i=0;i<250;i++) {
x=2*rnd()-1;
y=2*rnd()-1;
z=2*rnd()-1;
rsq=x*x+y*y+z*z;
if(rsq>0.01&&rsq<1) {
r=1/sqrt(rsq);x*=r;y*=r;z*=r;
v.plane(x,y,z,1);
}
}
// Make copy of the Voronoi cell
v2=v;
// Cut one copy in one direction, and the other copy in the other direction
v.plane(1,0,0,0);
v2.plane(-1,0,0,0);
// Output the Voronoi cell to a file, in the gnuplot format
v.draw_gnuplot(-0.05,0,0,"split_cell1.gnu");
v2.draw_gnuplot(0.05,0,0,"split_cell2.gnu");
}
<file_sep>// File import example code
//
// Author : <NAME> (Harvard University / LBL)
// Email : <EMAIL>
// Date : August 30th 2011
#include "voro++.hh"
using namespace voro;
#include <vector>
using namespace std;
// Set up constants for the container geometry
const double ax=-0.5,bx=25.5;
const double ay=-0.5,by=25.5;
const double az=-0.5,bz=25.5;
int main() {
// Manually import the file
int i,j,id,max_id=0,n;
double x,y,z;
vector<int> vid,neigh,f_order;
vector<double> vx,vy,vz,vd;
FILE *fp=safe_fopen("liq-900K.dat","r"),*fp2,*fp3;
while((j=fscanf(fp,"%d %lg %lg %lg",&id,&x,&y,&z))==4) {
vid.push_back(id);if(id>max_id) max_id=id;
vx.push_back(x);
vy.push_back(y);
vz.push_back(z);
}
if(j!=EOF) voro_fatal_error("File import error",VOROPP_FILE_ERROR);
n=vid.size();
fclose(fp);
// Compute optimal size for container, and then construct the container
double dx=bx-ax,dy=by-ay,dz=bz-az;
double l(pow(n/(5.6*dx*dy*dz),1/3.0));
int nx=int(dx*l+1),ny=int(dy*l+1),nz=int(dz*l+1);
container con(ax,bx,ay,by,az,bz,nx,ny,nz,false,false,false,8);
// Print status message
printf("Read %d particles, max ID is %d\n"
"Container grid is %d by %d by %d\n",n,max_id,nx,ny,nz);
// Import the particles, and create ID lookup tables
double *xi=new double[max_id+1],*yi=new double[max_id+1],*zi=new double[max_id+1];
for(j=0;j<n;j++) {
id=vid[j];x=vx[j];y=vy[j];z=vz[j];
con.put(id,x,y,z);
xi[id]=x;
yi[id]=y;
zi[id]=z;
}
// Open three output files for statistics and gnuplot cells
fp=safe_fopen("liq-900K.out","w");
fp2=safe_fopen("liq-900K.gnu","w");
fp3=safe_fopen("liq-900K-orig.gnu","w");
// Loop over all particles and compute their Voronoi cells
voronoicell_neighbor c,c2;
c_loop_all cl(con);
if(cl.start()) do if(con.compute_cell(c,cl)) {
// Get particle position, ID, and neighbor vector
cl.pos(x,y,z);
id=cl.pid();
c.neighbors(neigh);
// Get face areas et total surface of faces
c.face_areas(vd);c.surface_area();
c.draw_gnuplot(x,y,z,fp3);
// Initialize second cell
c2.init(ax-x,bx-x,ay-y,by-y,az-z,bz-z);
// Add condition on surface: >1% total surface. In addition,
// skip negative indices, since they correspond to faces
// against the container boundaries
for(i=0;i<(signed int) vd.size();i++)
if(vd[i]>0.01*c.surface_area()&&neigh[i]>=0) {
j=neigh[i];
c2.nplane(xi[j]-x,yi[j]-y,zi[j]-z,j);
}
// Get information of c2 cell
c2.face_areas(vd);c2.face_orders(f_order);
// Output information to file
i=vd.size();
fprintf(fp,"%d %d",id,i);
for(j=0;j<i;j++) fprintf(fp," %d",f_order[j]);
for(j=0;j<i;j++) fprintf(fp," %.3f",vd[j]);
fprintf(fp," %.3f %.3f %.3f\n",x,y,z);
c2.draw_gnuplot(x,y,z,fp2);
} while (cl.inc());
// Close files
fclose(fp);
fclose(fp2);
// Delete dynamically allocated arrays
delete [] xi;
delete [] yi;
delete [] zi;
}
<file_sep>#include "voro++_2d.hh"
using namespace voro;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;double x,y;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 10 by 10 grid,
// with an initial memory allocation of 16 particles per grid square.
container_2d con(0,1,0,1,10,10,false,false,16);
// Add 1000 random points to the container
for(i=0;i<1000;i++) {
x=rnd();
y=rnd();
con.put(i,x,y);
}
// Output the particle positions to a file
con.draw_particles("random_points_2d.par");
// Output the Voronoi cells to a file, in the gnuplot format
con.draw_cells_gnuplot("random_points_2d.gnu");
// Sum the Voronoi cell areas and compare to the container area
double carea=1,varea=con.sum_cell_areas();
printf("Total container area : %g\n"
"Total Voronoi cell area : %g\n"
"Difference : %g\n",carea,varea,varea-carea);
}
<file_sep>#include "voro++_2d.hh"
using namespace voro;
const double pi=3.1415926535897932384626433832795;
const double radius=0.7;
// This function returns a random floating point number between 0 and 1
double rnd() {return double(rand())/RAND_MAX;}
int main() {
int i;double x,y;
// Initialize the container class to be the unit square, with
// non-periodic boundary conditions. Divide it into a 6 by 6 grid, with
// an initial memory allocation of 16 particles per grid square.
container_2d con(-1,1,-1,1,10,10,false,false,16);
// Add circular wall object
wall_circle_2d wc(0,0,radius);
//con.add_wall(wc);
// Add 1000 random points to the container
for(i=0;i<1000;i++) {
x=2*rnd()-1;
y=2*rnd()-1;
if(x*x+y*y<radius*radius) con.put(i,x,y);
}
// Output the particle positions to a file
con.draw_particles("circle.par");
// Output the Voronoi cells to a file, in the gnuplot format
con.draw_cells_gnuplot("circle.gnu");
con.print_custom("%i %q %a %n","circle.vol");
// Sum the Voronoi cell areas and compare to the circle area
double carea=pi*radius*radius,varea=con.sum_cell_areas();
printf("Total circle area : %g\n"
"Total Voronoi cell area : %g\n"
"Difference : %g\n",carea,varea,varea-carea);
}
<file_sep># Voro++ makefile
#
# Author : <NAME> (Harvard University / LBL)
# Email : <EMAIL>
# Date : August 30th 2011
# Load the common configuration file
include ../../config.mk
# List of executables
EXECUTABLES=degenerate degenerate2
# Makefile rules
all: degenerate degenerate2
degenerate: $(SOURCE) degenerate.cc
$(CXX) $(CFLAGS) $(E_INC) $(E_LIB) -o degenerate degenerate.cc -lvoro++
degenerate2: $(SOURCE) degenerate2.cc
$(CXX) $(CFLAGS) $(E_INC) $(E_LIB) -o degenerate2 degenerate2.cc -lvoro++
clean:
rm -f $(EXECUTABLES)
.PHONY: all clean
| 5c6e38ef901eec19bb505e69a8d73ccd8d7d3343 | [
"CMake",
"Makefile",
"C++"
] | 46 | C++ | chr1shr/voro | 56d619faf3479313399516ad71c32773c29be859 | 355964f00b130d2619e2419e0250b7fe1c175391 |
refs/heads/main | <repo_name>Mequidi/Banana-Talk<file_sep>/main.js
var btntranslate = document.querySelector("#translate");
btntranslate.addEventListener("click",clickEventHandler);
var translateinput = document.querySelector("#txtinput");
var translateoutput = document.querySelector("#translate-box");
var url = "https://api.funtranslations.com/translate/minion.json"
//var url = "https://lessonfourapi.tanaypratap.repl.co/translate/yoda.json";
function clickEventHandler()
{
console.log("input:",translateinput.value);
var input = translateinput.value;
var finalURL = constuctURL(input);
console.log(finalURL);
console.log("button is clicked !");
fetch(finalURL)
.then(response=>response.json())
.then(json=>{
translateoutput.innerText = json.contents.translated;
})
.catch(()=>alert("something went wrong!"))
}
function constuctURL(inputText)
{
var encodedURL = encodeURI(inputText) ;
var actualURl = url + "?text=" + encodedURL;
return actualURl;
}
<file_sep>/index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Banana Talk</title>
<link href="styles.css" rel="stylesheet">
</head>
<body>
<nav class="navigation">
<div>
Banana Talk
</div>
</nav>
<main>
<textarea placeholder="Write your sentence here!" id="txtinput"></textarea>
<button id="translate">Translate To Banana</button>
<div id="output-text">Translation will come here👇
</div>
<div id="translate-box"></div>
</main>
<footer>
<div id="title">About
</div>
<p>Are you a fan of minions? Did you know that the gibberish they say is an actual language. Use the translator to convert your text from English to Minion speak or Banana language.</p>
</footer>
<script src="main.js"></script>
</body>
</html><file_sep>/README.md
# Banana Talk
Converts normal english texts to the language of minions
| 3bc98559bf0ec9b7e36f5c04aaba545bbca7799a | [
"JavaScript",
"HTML",
"Markdown"
] | 3 | JavaScript | Mequidi/Banana-Talk | 294862913ef27a9da50856394087a3b3b07c3d07 | 184e11247892eeb125a11e055a7e9580bc20c61a |
refs/heads/master | <file_sep><?php
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use Auth;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*
* @return void
*/
public function boot()
{
// this issue is caused by Auth::user() hasn't been initialized yet
view()->composer('*', function($view){
$this->currentUser = [
'role' => 'notuser'
];
if(Auth::user())
$this->currentUser = Auth::user()->toArray();
$view->with('currentUser', $this->currentUser);
});
}
/**
* Register any application services.
*
* @return void
*/
public function register()
{
//
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\SeasonRequest;
use App\Season;
class SeasonController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = Season::select('id', 'name')->orderBy('id', 'DESC')->paginate(5);
return view('admin.season.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('admin.season.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(SeasonRequest $request)
{
$season = new Season();
$season->name = $request->txtName;
$season->alias = changeTitle($request->txtName);
$season->save();
return redirect()->route('season.index')->with([
'flash_level'=>'success',
'flash_message'=>'Season created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$season = Season::find($id)->toArray();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$season = Season::find($id)->toArray();
return view('admin.season.edit', compact('season'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(SeasonRequest $request, $id)
{
$season = Season::find($id);
$season->name = $request->txtName;
$season->alias = changeTitle($request->txtName);
$season->save();
return redirect()->route('season.index')->with([
'flash_level'=>'success',
'flash_message'=>'Season updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$season = Season::destroy($id);
return redirect()->route('season.index')->with([
'flash_level'=>'success',
'flash_message'=>'Season deleted succesfully'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Keyword;
class KeywordPageController extends Controller
{
public function index() {
$keywords = Keyword::orderBy('name', 'ASC')->get()->toArray();
return view('home.keyword.index', compact('keywords'));
}
public function show($id) {
$keyword = Keyword::select('name')->find($id)->toArray();
$movies = Keyword::find($id)->movie()->get()->toArray();
return view('home.keyword.show', compact('movies', 'keyword'));
// echo '<pre>';
// print_r($keyword);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\UserRequest;
use App\User;
use Hash;
class UserController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = User::select('id', 'username', 'email', 'role')->orderBy('id', 'DESC')->paginate(5);
return view('admin.user.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('admin.user.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(UserRequest $request)
{
$user = new User();
$user->username = $request->txtName;
$user->email = $request->txtEmail;
$user->password = <PASSWORD>($request->txtPassword);
$user->role = $request->radioRole;
$user->remember_token = $request->_token;
$user->save();
return redirect()->route('user.index')->with([
'flash_level'=>'success',
'flash_message'=>'User created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$user = User::find($id)->toArray();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id)->toArray();
return view('admin.user.edit', compact('user'));
// echo '<pre>';
// print_r($user);
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$user = User::find($id);
$user->username = $request->txtName;
$user->email = $request->txtEmail;
if($request->txtPassword == '')
$user->password = $user->password;
else
$user->password = <PASSWORD>::make($request->txtPassword);
$user->role = $request->radioRole;
$user->save();
return redirect()->route('user.index')->with([
'flash_level'=>'success',
'flash_message'=>'User updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$user = User::destroy($id);
return redirect()->route('user.index')->with([
'flash_level'=>'success',
'flash_message'=>'User deleted succesfully'
]);
}
}
<file_sep>$(document).ready(() => {
//flowtype
$('.main__ritem-header h3').flowtype({
minimum: 500,
maximum: 1200,
minFont: 20,
maxFont: 40,
fontRatio: 30
});
$('#showall').flowtype({
minimum: 500,
maximum: 1200,
minFont: 12,
maxFont: 40,
fontRatio: 30
});
const animeName = ['Naruto', 'One Piece', 'Fairy Tail', 'Bleach', 'One Punch Man', 'Dragon Ball Super', 'Pokemon', 'Black Rock Shooter', 'Sword Art Online', '5cm/s', 'Date A Live', 'Attack on the Titan', 'Bikini Warriors', 'Tokyo Ghoul', 'Fairy Tail', 'Hunter x Hunter', 'Digimon', 'Gumball', 'Stand By Me', 'Adventure Time', 'Inu Yasha', 'Masou Gakuen HxH', 'Overload', 'God Eater', 'Ajin', '<NAME>', 'Danmachi', 'Gintama'];
setInterval(function () {
let random = Math.floor(Math.random() * 28) + 1;
$('.header').css('background-image', 'url("http://webmovie.dev/public/img/' + random + '.jpg")');
$('.header__album h2').html(animeName[random - 1]);
}, 5000);
$(function () {
$('a[href*="#"]:not([href="#"])').click(function () {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: target.offset().top
}, 1000);
return false;
}
}
});
});
})
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Fansub;
class FansubPageController extends Controller
{
public function index() {
$fansubs = Fansub::orderBy('name', 'ASC')->get()->toArray();
return view('home.fansub.index', compact('fansubs'));
}
public function show($id) {
$fansub = Fansub::select('name')->find($id)->toArray();
$movies = Fansub::find($id)->movie()->get()->toArray();
return view('home.fansub.show', compact('movies', 'fansub'));
// echo '<pre>';
// print_r($fansub);
}
}
<file_sep><?php
namespace App\Http\Controllers\Auth;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use Illuminate\Foundation\Auth\RegistersUsers;
use Hash;
class RegisterController extends Controller
{
/*
|--------------------------------------------------------------------------
| Register Controller
|--------------------------------------------------------------------------
|
| This controller handles the registration of new users as well as their
| validation and creation. By default this controller uses a trait to
| provide this functionality without requiring any additional code.
|
*/
use RegistersUsers;
/**
* Where to redirect users after login / registration.
*
* @var string
*/
protected $redirectTo = '/login';
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct()
{
$this->middleware('guest');
}
public function showRegistationForm() {
return view('auth.register');
}
/**
* Create a new user instance after a valid registration.
*
* @param array $data
* @return User
*/
public function register(Request $request)
{
$messages = [
'txtName.required' => 'Please enter username',
'txtEmail.required' => 'Please enter email',
'txtEmail.unique' => 'Email is exists',
'txtEmail.regex' => 'Email syntax error',
'txtPassword.required' => 'Please enter password',
'txtPassword.min' => 'Password must least 6 character',
'txtRepassword.min' => 'Repassword must least 6 character',
'txtRepassword.required' => 'Please enter repassword',
'txtRepassword.same' => 'Repassword don\'t match',
'txtCaptcha.required' => 'Please enter captcha',
'txtCaptcha.captcha' => 'Captcha don\'t match',
];
$this->validate($request, [
'txtName' => 'required|max:255',
'txtEmail' => 'required|max:255|unique:users,email',
'txtPassword' => '<PASSWORD>',
'txtRepassword' => '<PASSWORD>:6|same:txtPassword',
'txtCaptcha' => 'required|captcha'
], $messages);
$user = new User();
$user->username = $request->txtName;
$user->email = $request->txtEmail;
$user->password = <PASSWORD>::make($request->txtPassword);
$user->role = 'member';
$user->remember_token = $request->_token;
$user->save();
return redirect()->route('login');
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\LoginRequest;
use Auth;
use App\Movie;
use App\Episode;
use App\Counter;
class HomeController extends Controller
{
public function index() {
$movies = Movie::select('id', 'name', 'thumb', 'current_episodes', 'total_episodes')->limit(6)->orderBy('id', 'DESC')->get()->toArray();
$moviesRandom = Movie::select('id', 'name', 'thumb', 'current_episodes', 'total_episodes')->orderByRaw("RAND()")->limit(6)->get()->toArray();
$moviesMostViews = Movie::select('id', 'name', 'thumb', 'current_episodes', 'views')->limit(5)->orderBy('views', 'DESC')->get()->toArray();
$moviesMostLikes = Movie::select('id', 'name', 'thumb', 'current_episodes', 'likes')->limit(5)->orderBy('likes', 'DESC')->get()->toArray();
$newEpisodes = Episode::select('id', 'name', 'alias', 'movie_id')->limit(6)->orderBy('id', 'DESC')->get()->toArray();
return view('home.main', compact('movies', 'moviesRandom', 'moviesMostViews', 'moviesMostLikes', 'newEpisodes'));
// echo '<pre>';
// print_r(Counter::show('movies', 3));
}
}
<file_sep><?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMoviesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('movies', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->string('alias');
$table->string('status');
$table->string('thumb');
$table->integer('views')->unsigned();
$table->integer('likes')->unsigned();
$table->integer('current_episodes');
$table->integer('total_episodes');
$table->longText('description');
$table->integer('year_id')->unsigned();
$table->foreign('year_id')->references('id')->on('years')->onDelete('cascade');
$table->integer('season_id')->unsigned();
$table->foreign('season_id')->references('id')->on('seasons')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('movies');
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class EpisodeLink extends Model
{
protected $table = 'episode_links';
protected $fillable = ['link', 'episode_id'];
public $timestamp = true;
public function episode() {
return $this->belongsTo('App\Episode');
}
}
<file_sep><?php
// 2016_12_18_071423_add_likes_episodes_table
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddLikesEpisodesTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::table('episodes', function (Blueprint $table) {
$table->string('likes')->after('views');
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::table('episodes', function (Blueprint $table) {
$table->dropColumn('likes');
});
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Producer;
class ProducerPageController extends Controller
{
public function index() {
$producers = Producer::orderBy('name', 'ASC')->get()->toArray();
return view('home.producer.index', compact('producers'));
}
public function show($id) {
$producer = Producer::select('name')->find($id)->toArray();
$movies = Producer::find($id)->movie()->get()->toArray();
return view('home.producer.show', compact('movies', 'producer'));
// echo '<pre>';
// print_r($producer);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\GenreRequest;
use App\Genre;
class GenreController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = Genre::select('id', 'name')->orderBy('id', 'DESC')->paginate(5);
return view('admin.genre.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('admin.genre.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(GenreRequest $request)
{
$genre = new Genre();
$genre->name = $request->txtName;
$genre->alias = changeTitle($request->txtName);
$genre->save();
return redirect()->route('genre.index')->with([
'flash_level'=>'success',
'flash_message'=>'Genre created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$genre = Genre::find($id)->toArray();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$genre = Genre::find($id)->toArray();
return view('admin.genre.edit', compact('genre'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(GenreRequest $request, $id)
{
$genre = Genre::find($id);
$genre->name = $request->txtName;
$genre->alias = changeTitle($request->txtName);
$genre->save();
return redirect()->route('genre.index')->with([
'flash_level'=>'success',
'flash_message'=>'Genre updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$genre = Genre::destroy($id);
return redirect()->route('genre.index')->with([
'flash_level'=>'success',
'flash_message'=>'Genre deleted succesfully'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests\UserRequest;
use App\User;
use Hash;
class SignUpController extends Controller
{
public function create() {
return view('home.signup');
}
public function store(UserRequest $request) {
$user = new User();
$user->username = $request->txtName;
$user->email = $request->txtEmail;
$user->password = <PASSWORD>($request->txtPassword);
$user->role = 'member';
$user->remember_token = $request->_token;
$user->save();
return redirect()->route('home.index')->with([
'flash_level'=>'success',
'flash_message'=>'Account created successfully'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers\Member;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\Validator;
use Auth;
use App\User;
use Hash;
class MyAccountController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$user = [
'role' => 'notuser'
];
if(Auth::user())
$user = Auth::user()->toArray();
return view('member.myaccount.index', compact('user'));
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$user = User::find($id)->toArray();
return view('member.myaccount.edit', compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$this->validate($request, [
'txtName' => 'required',
], [
'txtName.required' => 'Please enter old password',
]);
$user = User::find($id);
$user->username = $request->txtName;
$user->save();
return redirect()->route('myaccount.index')->with([
'flash_level'=>'success',
'flash_message'=>'Username updated succesfully'
]);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function editPassword($id)
{
$user = User::find($id)->toArray();
return view('member.myaccount.editPassword', compact('user'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function updatePassword(Request $request, $id)
{
$this->validate($request, [
'txtOldPassword' => 'required',
'txtNewPassword' => 'required|min:6',
'txtNewRepassword' => 'required|min:6|same:txtNewPassword'
], [
'txtOldPassword.required' => 'Please enter old password',
'txtNewPassword.required' => 'Please enter password',
'txtNewPassword.min' => 'Password must least 6 character',
'txtNewRepassword.min' => 'Repassword must least 6 character',
'txtNewRepassword.required' => 'Please enter repassword',
'txtNewRepassword.same' => 'Repassword don\'t match'
]);
if(Hash::check($request->txtOldPassword, Auth::user()->password)) {
$user = User::find($id);
$user->password = <PASSWORD>($request->txtNewPassword);
$user->save();
return redirect()->route('myaccount.index')->with([
'flash_level'=>'success',
'flash_message'=>'Password updated succesfully'
]);
} else {
return redirect()->route('myaccount.editPassword', $id)->with([
'flash_level'=>'danger',
'flash_message'=>'Old password not match'
]);
}
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class KeywordRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'txtName'=>'required|unique:keywords,name'
];
}
public function messages() {
return [
'txtName.required'=>'Please enter the name of keyword',
'txtName.unique'=>'This name of keyword is exist'
];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\FansubRequest;
use App\Fansub;
class FansubController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = Fansub::select('id', 'name')->orderBy('id', 'DESC')->paginate(5);
return view('admin.fansub.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('admin.fansub.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(FansubRequest $request)
{
$fansub = new Fansub();
$fansub->name = $request->txtName;
$fansub->alias = changeTitle($request->txtName);
$fansub->save();
return redirect()->route('fansub.index')->with([
'flash_level'=>'success',
'flash_message'=>'Fansub created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$fansub = Fansub::find($id)->toArray();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$fansub = Fansub::find($id)->toArray();
return view('admin.fansub.edit', compact('fansub'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(FansubRequest $request, $id)
{
$fansub = Fansub::find($id);
$fansub->name = $request->txtName;
$fansub->alias = changeTitle($request->txtName);
$fansub->save();
return redirect()->route('fansub.index')->with([
'flash_level'=>'success',
'flash_message'=>'Fansub updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$fansub = Fansub::destroy($id);
return redirect()->route('fansub.index')->with([
'flash_level'=>'success',
'flash_message'=>'Fansub deleted succesfully'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Genre;
use App\Movie;
class GenrePageController extends Controller
{
public function index() {
$genres = Genre::orderBy('name', 'ASC')->get()->toArray();
return view('home.genre.index', compact('genres'));
}
public function show($id) {
$genre = Genre::select('name')->find($id)->toArray();
$movies = Genre::find($id)->movie()->get()->toArray();
return view('home.genre.show', compact('movies', 'genre'));
// echo '<pre>';
// print_r($genre);
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class UserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'txtName' => 'required|max:255',
'txtEmail' => 'required|max:255|unique:users,email',
'txtPassword' => 'required|min:6',
'txtRepassword' => 'required|min:6|same:txtPassword'
];
}
public function messages() {
return [
'txtName.required' => 'Please enter username',
'txtEmail.required' => 'Please enter email',
'txtEmail.unique' => 'Email is exists',
'txtEmail.regex' => 'Email syntax error',
'txtPassword.required' => 'Please enter password',
'txtPassword.min' => 'Password must least 6 character',
'txtRepassword.min' => 'Repassword must least 6 character',
'txtRepassword.required' => 'Please enter repassword',
'txtRepassword.same' => 'Repassword don\'t match'
];
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class MovieRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'txtName' => 'required',
'txtStatus' => 'required',
'txtNumber' => 'required',
'txtDescription' => 'required',
'txtYear' => 'required',
'txtSeason' => 'required',
'txtProducer' => 'required',
'txtGenre' => 'required',
'txtFansub' => 'required',
'txtKeyword' => 'required'
];
}
public function messages() {
return [
'txtName.required'=> 'Please enter the name of movie',
'txtName.unique'=> 'Movie has existed',
'txtStatus' => 'Please enter the name of status',
'txtNumber' => 'Please enter the name of total episode',
'txtDescription' => 'Please enter the name of description',
'txtYear' => 'Please enter the name of year',
'txtSeason' => 'Please enter the name of season',
'txtProducer'=>'Please enter the name of producers',
'txtGenre' => 'Please enter the name of genres',
'txtFansub' => 'Please enter the name of fansubs',
'txtKeyword' => 'Please enter the name of keywords',
'fileThumb' => 'Please input thumb of movie',
];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Episode;
use App\EpisodeLink;
use App\Movie;
class EpisodeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index($id)
{
$data = Movie::find($id)->episode()->orderBy('id','DESC')->paginate(5);
return view('admin.episode.index', compact('data','id'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create($id)
{
$movie = Movie::find($id);
return view('admin.episode.create', compact('id', 'movie'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$episode = new Episode();
$episode->name = $request->txtName;
$episode->alias = changeTitle($request->txtName);
$episode->views = 0;
$episode->likes = 0;
$episode->movie_id = $request->txtMovieId;
$episode->save();
for($i = 0; $i < 5; $i++) {
$link = new EpisodeLink();
$link->link = $request->txtLink[$i];
$link->episode_id = $episode->id;
$link->save();
}
$movie = Movie::find($request->txtMovieId);
$movie->current_episodes = $movie->current_episodes + 1;
$movie->save();
return redirect()->route('episode.index', $request->txtMovieId)->with([
'flash_level'=>'success',
'flash_message'=>'Episode created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$episode = Episode::find($id)->toArray();
$links = EpisodeLink::where('episode_id', $id)->get()->toArray();
return view('admin.episode.edit', compact('episode','links'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
$episode = Episode::find($id);
$episode->name = $request->txtName;
$episode->alias = changeTitle($request->txtName);
$episode->views = $episode->views;
$episode->likes = $episode->likes;
$episode->save();
$links = EpisodeLink::where('episode_id', $id)->select('id')->get()->toArray();
foreach($links as $key => $link) {
$data = EpisodeLink::find($link['id']);
$data->link = $request->txtLink[$key];
$data->save();
}
return redirect()->route('episode.index', $episode->movie_id)->with([
'flash_level'=>'success',
'flash_message'=>'Episode updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id, $movieId)
{
$idMovie = Episode::find($id);
$episode = Episode::destroy($id);
$movie = Movie::find($movieId);
$movie->current_episodes = $movie->current_episodes - 1;
$movie->save();
return redirect()->route('episode.index', $idMovie->movie_id)->with([
'flash_level'=>'success',
'flash_message'=>'Episode deleted succesfully'
]);
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', [
'as' => 'home.index',
'uses' => 'HomeController@index'
]);
Route::get('404', function() {
return view('404');
});
// like
Route::group(['prefix'=>'anime', 'middleware'=>'auth'], function() {
Route::post('like/{id}/movie/{movie_id}', [
'as' => 'episode.like',
'uses' => 'LikeController@like'
]);
Route::delete('unlike/{id}/episode/{epsiode_id}/movie/{movie_id}', [
'as' => 'episode.unlike',
'uses' => 'LikeController@unlike'
]);
});
// search
Route::get('search', [
'as' => 'search.show',
'uses' => 'Home\SearchController@show'
]);
// watch anime
Route::get('anime/{id}/episode/{episodeId}', [
'as' => 'page.index',
'uses' => 'PageController@index'
]);
Route::group(['prefix'=>'genre'], function() {
Route::get('', [
'as' => 'genrepage.index',
'uses' => 'Home\GenrePageController@index'
]);
Route::get('anime/{id}', [
'as' => 'genrepage.show',
'uses' => 'Home\GenrePageController@show'
]);
});
Route::group(['prefix'=>'producer'], function() {
Route::get('', [
'as' => 'producerpage.index',
'uses' => 'Home\ProducerPageController@index'
]);
Route::get('anime/{id}', [
'as' => 'producerpage.show',
'uses' => 'Home\ProducerPageController@show'
]);
});
Route::group(['prefix'=>'year'], function() {
Route::get('', [
'as' => 'yearpage.index',
'uses' => 'Home\YearPageController@index'
]);
Route::get('anime/{id}', [
'as' => 'yearpage.show',
'uses' => 'Home\YearPageController@show'
]);
});
Route::group(['prefix'=>'keyword'], function() {
Route::get('', [
'as' => 'keywordpage.index',
'uses' => 'Home\KeywordPageController@index'
]);
Route::get('anime/{id}', [
'as' => 'keywordpage.show',
'uses' => 'Home\KeywordPageController@show'
]);
});
Route::group(['prefix'=>'fansub'], function() {
Route::get('', [
'as' => 'fansubpage.index',
'uses' => 'Home\FansubPageController@index'
]);
Route::get('anime/{id}', [
'as' => 'fansubpage.show',
'uses' => 'Home\FansubPageController@show'
]);
});
// member routes
Route::group(['prefix'=>'member','middleware'=>['auth']], function() {
Route::group(['prefix'=>'myaccount'], function() {
Route::get('', [
'as' => 'myaccount.index',
'uses' => 'Member\MyAccountController@index'
]);
Route::get('{id}/edit', [
'as' => 'myaccount.edit',
'uses' => 'Member\MyAccountController@edit'
]);
Route::put('{id}', [
'as' => 'myaccount.update',
'uses' => 'Member\MyAccountController@update'
]);
Route::get('{id}/editPassword', [
'as' => 'myaccount.editPassword',
'uses' => 'Member\MyAccountController@editPassword'
]);
Route::put('{id}/updatePassword', [
'as' => 'myaccount.updatePassword',
'uses' => 'Member\MyAccountController@updatePassword'
]);
});
});
// admin routes
Route::get('admin', function() {
return view('admin.year.index');
});
Route::group(['prefix'=>'admin', 'middleware'=>'admin'], function() {
Route::resource('year', 'YearController');
Route::resource('season', 'SeasonController');
Route::resource('genre', 'GenreController');
Route::resource('keyword', 'KeywordController');
Route::resource('producer', 'ProducerController');
Route::resource('fansub', 'FansubController');
Route::resource('movie', 'MovieController');
// Route::resource('episode', 'EpisodeController');
Route::group(['prefix'=>'episode'], function() {
Route::get('movie/{id}', [
'as' => 'episode.index',
'uses' => 'EpisodeController@index'
]);
Route::get('create/{id}', [
'as' => 'episode.create',
'uses' => 'EpisodeController@create'
]);
Route::post('', [
'as' => 'episode.store',
'uses' => 'EpisodeController@store'
]);
Route::get('{id}', [
'as' => 'episode.show',
'uses' => 'EpisodeController@show'
]);
Route::get('{id}/edit', [
'as' => 'episode.edit',
'uses' => 'EpisodeController@edit'
]);
Route::put('{id}', [
'as' => 'episode.update',
'uses' => 'EpisodeController@update'
]);
Route::delete('{id}/{movieId}', [
'as' => 'episode.destroy',
'uses' => 'EpisodeController@destroy'
]);
});
Route::resource('user', 'UserController');
});
// Authentication routes
Route::Auth();<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\YearRequest;
use App\Year;
class YearController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = Year::select('id','name')->orderBy('id', 'DESC')->paginate(5);
return view('admin.year.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('admin.year.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(YearRequest $request)
{
$year = new Year();
$year->name = $request->txtName;
$year->alias = changeTitle($request->txtName);
$year->save();
return redirect()->route('year.index')->with([
'flash_level'=>'success',
'flash_message'=>'Year created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$year = Year::find($id)->toArray();
print_r($year);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$year = Year::find($id)->toArray();
return view('admin.year.edit', compact('year'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(YearRequest $request, $id)
{
$year = Year::find($id);
$year->name = $request->txtName;
$year->alias = changeTitle($request->txtName);
$year->save();
return redirect()->route('year.index')->with([
'flash_level'=>'success',
'flash_message'=>'Year updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$year = Year::destroy($id);
return redirect()->route('year.index')->with([
'flash_level'=>'success',
'flash_message'=>'Year deleted succesfully'
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Movie;
use App\Episode;
use App\Genres;
use App\Like;
use Auth;
class PageController extends Controller
{
public function mapArray($option, $data) {
$str = '';
foreach($data as $d) {
if($str === '')
$str = "<span><a href='/".$option."/".$d['id']."'>".$d['name']."</a></span>";
else
$str .= ", <span><a href='/".$option."/".$d['id']."'>".$d['name']."</a></span>";
}
return $str;
}
public function getUserLiked($arrLike, &$likeId) {
foreach($arrLike as $like) {
if($like['user_id'] == Auth::id()) {
$likeId = $like['id'];
return true;
}
}
return false;
}
public function index($id, $episodeId) {
$movie = Movie::find($id)->toArray();
$movies = Movie::select('id', 'name', 'thumb', 'views', 'likes')->orderByRaw("RAND()")->limit(10)->orderBy('id', 'DESC')->get()->toArray();
$episodes = Episode::where('movie_id', $id)->select('id', 'name', 'views', 'likes')->limit(10)->get()->toArray();
$episode = Episode::find($episodeId)->toArray();
// get data
$genres = Movie::find($id)->genre()->get()->toArray();
$producers = Movie::find($id)->producer()->get()->toArray();
$keywords = Movie::find($id)->keyword()->get()->toArray();
$fansubs = Movie::find($id)->fansub()->get()->toArray();
$links = Episode::find($episodeId)->link()->get()->toArray();
// convert data to array;
$arrGenres = $this->mapArray('genre/anime', $genres);
$arrProducers = $this->mapArray('producer/anime', $producers);
$arrTags = $this->mapArray('keyword/anime', $keywords);
$arrFansubs = $this->mapArray('fansub/anime', $fansubs);
// like
$like = Like::where('episode_id','=',$episodeId)->get()->toArray();
$totalLiked = count($like);
$likeId = 0;
$isLiked = $this->getUserLiked($like, $likeId);
return view('home.page', compact('likeId','isLiked','totalLiked','links', 'movie', 'movies', 'episodes', 'episode', 'arrGenres', 'arrProducers', 'arrTags', 'arrFansubs', 'id', 'episodeId'));
// echo '<pre>';
// print_r($likeId);
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Year;
use App\Movie;
class YearPageController extends Controller
{
public function index() {
$years = Year::orderBy('name', 'ASC')->get()->toArray();
return view('home.year.index', compact('years'));
}
public function show($id) {
$year = Year::select('name')->find($id)->toArray();
$movies = Movie::where('year_id',$id)->get()->toArray();
return view('home.year.show', compact('movies', 'year'));
// echo '<pre>';
// print_r($movies);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Episode extends Model
{
protected $table = 'episodes';
protected $fillable = ['name', 'alias', 'views', 'likes', 'movie_id'];
public $timestamp = true;
public function movie() {
return $this->belongsTo('App\Movie');
}
public function link() {
return $this->hasMany('App\EpisodeLink');
}
public function keywords() {
return $this->belongsToMany('App\Keyword', 'episode_keywords')->withTimestamps();
}
}
<file_sep><?php
namespace App\Http\Controllers\Home;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Movie;
use App\Genre;
use App\Keyword;
use App\Season;
use App\Year;
use App\Producer;
use App\Fansub;
class SearchController extends Controller
{
public function show(Request $request) {
$keyword = $request->q;
$movies = Movie::where('name', 'LIKE', "%$keyword%")->paginate(3);
$genres = Genre::where('name', 'LIKE', "%$keyword%")->get()->toArray();
$total = count($movies);
return view('home.search.show', compact('movies','genres','keyword','total'));
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Requests\ProducerRequest;
use App\Producer;
class ProducerController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = Producer::select('id', 'name')->orderBy('id', 'DESC')->paginate(5);
return view('admin.producer.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
return view('admin.producer.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(ProducerRequest $request)
{
$producer = new Producer();
$producer->name = $request->txtName;
$producer->alias = changeTitle($request->txtName);
$producer->save();
return redirect()->route('producer.index')->with([
'flash_level'=>'success',
'flash_message'=>'Producer created succesfully'
]);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
$producer = Producer::find($id)->toArray();
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$producer = Producer::find($id)->toArray();
return view('admin.producer.edit', compact('producer'));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(ProducerRequest $request, $id)
{
$producer = Producer::find($id);
$producer->name = $request->txtName;
$producer->alias = changeTitle($request->txtName);
$producer->save();
return redirect()->route('producer.index')->with([
'flash_level'=>'success',
'flash_message'=>'Producer updated succesfully'
]);
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
$producer = Producer::destroy($id);
return redirect()->route('producer.index')->with([
'flash_level'=>'success',
'flash_message'=>'Producer deleted succesfully'
]);
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Movie extends Model
{
protected $table = 'movies';
protected $fillable = ['name', 'alias', 'status', 'thumb', 'views', 'likes', 'current_episodes', 'total_episodes', 'description', 'year_id', 'season_id'];
public $timestamp = true;
public function year() {
return $this->belongsTo('App\Year');
}
public function season() {
return $this->belongsTo('App\Season');
}
public function genre() {
return $this->belongsToMany('App\Genre', 'genre_movies')->withTimestamps();
}
public function producer() {
return $this->belongsToMany('App\Producer', 'producer_movies')->withTimestamps();
}
public function episode() {
return $this->hasMany('App\Episode');
}
public function fansub() {
return $this->belongsToMany('App\Fansub', 'fansub_movies')->withTimestamps();
}
public function keyword() {
return $this->belongsToMany('App\Keyword', 'movie_keywords')->withTimestamps();
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\File;
use App\Http\Requests\MovieRequest;
use App\Movie;
use App\Year;
use App\Season;
use App\Producer;
use App\Genre;
use App\Keyword;
use App\Fansub;
use App\EpisodeSeason;
class MovieController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$data = Movie::select('id', 'name', 'alias', 'status', 'thumb', 'views', 'likes', 'current_episodes', 'total_episodes', 'description', 'year_id', 'season_id')
->orderBy('id', 'DESC')
->paginate(5);
return view('admin.movie.index', compact('data'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create(Request $request)
{
$years = Year::all();
$seasons = Season::all();
$genres = Genre::all();
$keywords = Keyword::all();
$fansubs = Fansub::all();
$producers = Producer::all();
return view('admin.movie.create', compact('years', 'seasons', 'producers', 'genres', 'fansubs','keywords'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(MovieRequest $request)
{
//movie request
$fileOriginalName = $request->file('fileThumb');
if($fileOriginalName !== null) {
$fileName = $request->file('fileThumb')->getClientOriginalName();
// save file
$fileOriginalName->move('public/upload/', $fileName);
}
$movie = new Movie();
$movie->name = $request->txtName;
$movie->alias = changeTitle($request->txtName);
$movie->status = $request->txtStatus;
$movie->views = 0;
$movie->likes = 0;
$movie->current_episodes = 0;
$movie->total_episodes = $request->txtNumber;
$movie->description = $request->txtDescription;
$movie->year_id = $request->txtYear;
$movie->season_id = $request->txtSeason;
if($fileOriginalName === null) {
$movie->thumb = $movie->thumb;
} else {
$movie->thumb = $fileName;
}
$movie->save();
// save file
$request->file('fileThumb')->move('public/upload/', $fileName);
// producer request
$movie->producer()->attach($request->txtProducer);
// genre request
$movie->genre()->attach($request->txtGenre);
// fansub request
$movie->fansub()->attach($request->txtFansub);
// keyword request
// $movie->keyword()->attach(explode(',', $request->txtKeyword));
$movie->keyword()->attach($request->txtKeyword);
return redirect()->route('movie.index')->with([
'flash_level'=>'success',
'flash_message'=>'Movie created succesfully'
]);
// echo($request->txtKeyword);
}
/**
* Display the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function show($id)
{
return redirect()->route('episode.index', $id);
}
/**
* Show the form for editing the specified resource.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function edit($id)
{
$movie = Movie::find($id);
$years = Year::all();
$seasons = Season::all();
$genres = Genre::all();
$keywords = Keyword::all();
$fansubs = Fansub::all();
$producers = Producer::all();
$producer_movies = Movie::find($id)->producer()->get()->toArray();
$genre_movies = Movie::find($id)->genre()->get()->toArray();
$fansub_movies = Movie::find($id)->fansub()->get()->toArray();
// convert array name to string
$movie_keywords = Movie::find($id)->keyword()->get()->toArray();
return view('admin.movie.edit', compact('movie_keywords','producer_movies', 'genre_movies', 'fansub_movies', 'arr_keywords','movie', 'years', 'seasons', 'producers', 'genres', 'fansubs','keywords'));
// echo '<pre>';
// print_r(implode(',',$arr));
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param int $id
* @return \Illuminate\Http\Response
*/
public function update(MovieRequest $request, $id)
{
//movie request
$fileOriginalName = $request->file('fileThumb');
if($fileOriginalName !== null) {
$fileName = $request->file('fileThumb')->getClientOriginalName();
// save file
$fileOriginalName->move('public/upload/', $fileName);
}
$movie = Movie:: find($id);
$movie->name = $request->txtName;
$movie->alias = changeTitle($request->txtName);
$movie->status = $request->txtStatus;
$movie->views = $movie->views;
$movie->likes = $movie->likes;
$movie->current_episodes = $movie->current_episodes;
$movie->total_episodes = $request->txtNumber;
$movie->description = $request->txtDescription;
$movie->year_id = $request->txtYear;
$movie->season_id = $request->txtSeason;
if($fileOriginalName === null) {
$movie->thumb = $movie->thumb;
} else {
$movie->thumb = $fileName;
}
$movie->save();
// producer request
$movie->producer()->sync($request->txtProducer);
// genre request
$movie->genre()->sync($request->txtGenre);
// fansub request
$movie->fansub()->sync($request->txtFansub);
// keyword request
$movie->keyword()->sync($request->txtKeyword);
return redirect()->route('movie.index')->with([
'flash_level'=>'success',
'flash_message'=>'Movie updated succesfully'
]);
// echo '<pre>';
// print_r(explode(',', $request->txtKeyword));
}
/**
* Remove the specified resource from storage.
*
* @param int $id
* @return \Illuminate\Http\Response
*/
public function destroy($id)
{
//TODO: cannt delete image without delete movie
$thumb_name = Movie::select('thumb')->find($id)->toArray();
File::delete('/public/upload/'.$thumb_name['thumb']);
$movie = Movie::destroy($id);
return redirect()->route('movie.index')->with([
'flash_level'=>'success',
'flash_message'=>'Movie deleted succesfully'
]);
}
}
<file_sep><?php
namespace App\Http\Requests;
use Illuminate\Foundation\Http\FormRequest;
class FansubRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return bool
*/
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'txtName'=>'required|unique:fansubs,name'
];
}
public function messages() {
return [
'txtName.required'=>'Please enter the name of fansub',
'txtName.unique'=>'This name of fansub is exist'
];
}
}
<file_sep><?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Like;
use App\Episode;
use App\Movie;
use Auth;
class LikeController extends Controller
{
public function like($id, $movie_id) {
$like = new Like();
$like->user_id = Auth::id();
$like->episode_id = $id;
$like->save();
$episode = Episode::find($id);
$episode->likes = $episode->likes += 1;
$episode->save();
$movie = Movie:: find($movie_id);
$movie->likes = $movie->likes += 1;
$movie->save();
return redirect()->back();
// echo '<pre>';
// print_r($episode);
}
public function unlike($id, $episode_id, $movie_id) {
$episode = Episode::find($episode_id);
if($episode->likes !== 0)
$episode->likes = $episode->likes -= 1;
$episode->save();
$movie = Movie::find($movie_id);
if($movie->likes !== 0)
$movie->likes = $movie->likes -= 1;
$movie->save();
Like::destroy($id);
return redirect()->back();
// echo '<pre>';
// print_r($id);
}
}
| 1a745fe87bd270c1a61c903c37c6b1ad616e2791 | [
"JavaScript",
"PHP"
] | 32 | PHP | lynkxyz/webmovie.dev | 5d933616e1f08043682b4b04ee0e61429df4ad7c | 67a78a6c01955cb5f697a946d991d8b0769f52de |
refs/heads/master | <repo_name>btupper/tooliklake_sed<file_sep>/TL_R.R
library(tidyverse)
library(readxl)
library(ggpubr)
library(ggplot2)
# Significant taxa
metadata<- read_excel(path="TL_metadata.xlsx")
tooll.tax <- read_tsv("tooll.otu.taxonomy") %>%
rename_all(tolower) %>%
mutate(taxonomy=str_replace_all(string=taxonomy, pattern="\\(\\d*\\)", replacement="")) %>%
mutate(taxonomy=str_replace_all(string = taxonomy, pattern = ";$", replacement = "")) %>%
separate(taxonomy, into=c("kingdom", "phylum", "class", "order", "family", "genus"), sep = ";")
# @input mothur formatted and name shortened shared file (# of OTUS in each sample)
# @return tidy dataframe in long format with OTUs in % relative abundance
tooll.otu <- read_tsv("tooll.otu.table", col_types = cols(Group=col_character())) %>%
select(-label, -numOtus) %>%
rename(sample=Group) %>%
pivot_longer(cols = -sample, names_to = "otu", values_to = "count") %>%
mutate(rel_abund=(count/18010)*100)
# @input reformatted OTU table and OTU taxonomy table
# @return % rel abund and taxonomy for every OTU from every sample
tl.otu.tax <- inner_join(tooll.otu, tooll.tax)
# @input metadata for all samples and % rel abund and taxonomy for every OTU from every sample
# @return complete dataframe of all OTUs from every sample with everything we want to know about each OTU
tl.otu.tax.meta <- inner_join(tl.otu.tax, metadata, by=c("sample"="group")) %>%
filter(., sample!="TL1")
tl.gal<- filter(tl.otu.tax.meta, family%in%c("Gallionellaceae")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
tl.geo<-filter(tl.otu.tax.meta, family%in%c("Geobacteraceae")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
tl.lepto<-filter(tl.otu.tax.meta, genus%in%c("Leptothrix")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
#There is hardly any leptothrix (<0.005% rel abund) do not use in final analysis, will not impact FeOB rel abund
# used <NAME>., & <NAME>. (2018). Diversity and Phylogeny of Described Aerobic Methanotrophs.
# Methane Biocatalysis: Paving the Way to Sustainability, 17–42. and
# ISME Journal (2019) 13:1209–1225 that shows Methylomonadaceae is a methanotroph
tl.methyl<-filter(tl.otu.tax.meta, family%in%c("Methylomonadaceae", "Methylococcaceae")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
tl.methylpren<-filter(tl.otu.tax.meta, family%in%c("Methanoperedenaceae")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
# using Holmes and Smith 2016 Advances in Applied Microbiology section 2.2 Phylogeny of Methanogens to determine methanogens families
tl.methan<-filter(tl.otu.tax.meta, family==c("Methanoregulaceae", "Methanosaetaceae", "Methanobacteriaceae")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
tl.geothrix<-filter(tl.otu.tax.meta, genus%in%c("Geothrix")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
tl.cyano<-filter(tl.otu.tax.meta, class%in%c("Cyanobacteriia")) %>%
group_by(sample) %>%
summarise(rel_abund = sum(rel_abund)) %>%
inner_join(., metadata, by=c("sample" = "group"))
geochem <- read_excel(path="TLC.xlsx")
fe2 <- geochem$Fe2
o2 <- geochem$o2
geochem_depth <- geochem$depth
depth <- c(0, -0.25, -1.25, -2.25, -3.25, -4.25)
sfe_depth <- c(-0.25, -1.25, -2.25, -3.25, -4.25, -5.25, -6.25)
sfe <- c(63.6, 14.2, 4.3, 3.4, 0.4, 7.1, 5.7)
## plot multiple dots and lines on same plot, depth profile of OTUs of interest in this case
geo <- tl.geo$rel_abund + tl.geothrix$rel_abund
gal <- tl.gal$rel_abund
methyl <- tl.methyl$rel_abund
methan <- tl.methan$rel_abund
methanopren <- tl.methylpren$rel_abund
#png("TL_stnC.eps", height = 1600, width = 2400, units = 'px', res=300)
pdf("TL_stnC.pdf", height = 6, width = 6.5)
par(mfrow=c(1,2), pin=c(5,3), mar = c(4,4,4,0.25))
plot(geo, depth, col="darkred", pch=15, ylim = c(-6,1.05), xlim = c(0,2.5), axes=FALSE, ann=FALSE)
axis(3)
axis(2, las=2)
lines(geo, depth, col="darkred", lty=3, lwd=2)
mtext("Relative Abundance (%)", side=3, line = 2.5)
mtext("Depth (cm)", side = 2, line = 2.5, las=0)
points(gal, depth, col="darkorange2", pch=16)
lines(gal, depth, col="darkorange2", lty=3, lwd=2)
points(methyl, depth, col="blue2", pch=17)
lines(methyl, depth, col="blue2", lty=3, lwd=2)
points(methan, depth, col="black", pch=18, cex=1.25)
lines(methan, depth, col="black", lty=3, lwd=2)
#points(methanopren, depth, col="darkblue", pch=15)
#lines(methanopren, depth, col="darkblue", lty=3, lwd=2)
legend(0.5, -4.5, legend = c("Iron reducing", "Iron oxidizing", "Methane oxidizing", "Methanogenic"),
col = c("darkred", "darkorange2", "blue2", "black"), pch=c(15,16,17,18), lty=c(3,3,3,3),
lwd=c(2,2,2,2), ncol=1, bty="n")
plot(o2, geochem_depth, col="blue2", pch=17, ylim = c(-6,1.05), xlim = c(0, 310), axes=FALSE, ann=FALSE)
lines(o2, geochem_depth, col="blue2", lty=3, lwd=2)
xtick<-seq(0,300, by=100)
axis(3, at=xtick)
axis(2, las=2)
mtext(expression(paste("Concentration (",mu,"M)")), side=3, line = 2.5)
points(fe2, geochem_depth, col="darkred", pch=15)
lines(fe2, geochem_depth, col="darkred", lty=3, lwd=2)
par(new = TRUE)
plot(sfe, sfe_depth, col="orange", pch=16, xlim = c(0, 70), ylim = c(-6, 1.05), xaxt = "n", yaxt = "n",
ylab = "", xlab = "", axes=FALSE, ann=FALSE)
lines(sfe, sfe_depth, col="orange", lty=3, lwd=2)
axis(side = 1)
fe_xlab=expression(paste("Solid phase Fe(III) (",mu,"mole/gdw)"))
mtext(fe_xlab, side = 1, line = 2.5)
legend_fe = expression(paste("Fe"^"2+"))
legend(20, -5, legend = c("Oxygen", legend_fe, "Fe(III)"), col = c("blue2", "darkred", "orange"),
pch = c(17, 15, 16), lty = c(3,3), lwd = c(2,2), ncol = 1, bty = "n")
dev.off()
| 44707a73833775e6160ce0c7c8b829441549fc8d | [
"R"
] | 1 | R | btupper/tooliklake_sed | 8559a21028b60ec4daf2515d7d391d90ee56ec67 | dce3832df42c253e06d99ebc7479980734c04971 |
refs/heads/master | <repo_name>ratanakpek007/MaterialDemo<file_sep>/app/src/main/java/delivery/food/materialtablayout/MainActivity.kt
package delivery.food.materialtablayout
import android.os.Bundle
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.view.Menu
import android.view.MenuItem
import android.widget.Toast
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.android.synthetic.main.toolbar.*
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
private lateinit var toggle: ActionBarDrawerToggle
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
/**
* 1
* */
/* setSupportActionBar(toolbar)
toolbar.title="I am second"
//supportActionBar!!.title="Toolbar Demo"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
toolbar.elevation=10f
} else {
}*/
setSupportActionBar(toolbar)
toggle = ActionBarDrawerToggle(this, drawer_layout, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer_layout.addDrawerListener(toggle)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
supportActionBar?.setHomeButtonEnabled(true)
supportActionBar!!.setHomeAsUpIndicator(R.drawable.ic_menu_black_24dp)
nav_view.setNavigationItemSelectedListener(this)
}
override fun onCreateOptionsMenu(menu: Menu?): Boolean {
menuInflater.inflate(R.menu.main_menu, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item!!.itemId) {
R.id.home -> Toast.makeText(this, "Home", Toast.LENGTH_LONG).show()
R.id.general -> Toast.makeText(this, "General", Toast.LENGTH_LONG).show()
R.id.pending -> Toast.makeText(this, "Pending", Toast.LENGTH_LONG).show()
R.id.logout -> Toast.makeText(this, "Logout", Toast.LENGTH_LONG).show()
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
when (item.itemId) {
R.id.home -> Toast.makeText(this, "Home", Toast.LENGTH_LONG).show()
R.id.general -> Toast.makeText(this, "General", Toast.LENGTH_LONG).show()
R.id.pending -> Toast.makeText(this, "Pending", Toast.LENGTH_LONG).show()
R.id.logout -> Toast.makeText(this, "Logout", Toast.LENGTH_LONG).show()
}
drawer_layout.closeDrawer(GravityCompat.START)
return true
}
}
| faeebf7b8cf4b1be2f21a097d116c4d3509e5677 | [
"Kotlin"
] | 1 | Kotlin | ratanakpek007/MaterialDemo | cb3b49bce980e5f835868c1bce1ac06190047c9b | 186a9cc062b738b3d560beb790a94e2170e9c35c |
refs/heads/master | <file_sep>import xml.etree.ElementTree as ElementTree
def login(username, password):
iq_el = ElementTree.Element('iq')
iq_el.set('type', 'set')
query_el = ElementTree.Element('query')
query_el.set('xmlns', 'jabber:iq:auth')
iq_el.append(query_el)
username_el = ElementTree.Element('username')
username_el.text = username
password_el = ElementTree.Element('password')
password_el.text = <PASSWORD>
resource_el = ElementTree.Element('resource')
resource_el.text = 'py_client'
query_el.append(username_el)
query_el.append(password_el)
query_el.append(resource_el)
return ElementTree.tostring(iq_el)
def send_message(to, msg):
message_el = ElementTree.Element('message')
message_el.set('to', to)
body_el = ElementTree.Element('body')
body_el.text = msg
message_el.append(body_el)
return ElementTree.tostring(message_el)
def get_response_type(xml):
iq_el = ElementTree.fromstring(xml)
response_type = iq_el.get('type')
return response_type
def change_presence(new_presence, to):
presence_el = ElementTree.Element('presence')
if new_presence != 'available':
presence_el.set('type', new_presence)
if new_presence != 'unavailable':
presence_el.set('to', to)
return ElementTree.tostring(presence_el)
<file_sep>from xmpp_client import XmppClient
class CommandParser():
def __init__(self):
self._response = None
def parse(self, params):
for i in range(0, len(params)):
params[i] = params[i].strip()
if params[0] == "login":
self._response = XmppClient(params[1], params[2])
if self._response.is_logged:
self._response.change_presence('available', None)
return "Successfully logged in!"
else:
return "Error logging in!"
if params[0] == 'presence':
if not self._response.is_logged:
return "Not logged in!"
presence = params[1]
to = None if len(params) < 3 else params[2]
self._response.change_presence(presence, to)
return "Presence changed to " + presence
elif params[0] == 'message':
if not self._response.is_logged:
return "Not logged in!"
self._response.send_message(params[1], params[2])
return "Message sent!"
elif params[0] == 'logout':
if not self._response.is_logged:
return "Not logged in!"
self._response.close_stream()
return "Logged out"
<file_sep>import command_parser
lines = open('input.txt').readlines()
parser = command_parser.CommandParser()
file = open('output.txt', 'w')
file.write("")
for line in lines:
params = line.split(" ")
response = parser.parse(params)
file.write(response + "\n")
file.close()
<file_sep>import ssl
import socket
import xml_providers
class XmppClient:
def __init__(self, username, password):
self._s = socket.create_connection(("jabber.hot-chilli.net", 5222))
self.is_logged = None
self.open_stream()
self._authenticate(username, password)
def open_stream(self):
stream_init = open('xmls/stream_init.xml').read().encode()
start_tls = open('xmls/start_tls.xml').read().encode()
self._s.send(stream_init)
self._s.recv(1000)
self._s.send(start_tls)
self._s.recv(1000)
self._s = ssl.wrap_socket(self._s)
self._s.send(stream_init)
self._s.recv(1000)
def close_stream(self):
close = open('xmls/close_stream.xml').read().encode()
self._s.send(close)
def _authenticate(self, username, password):
auth = xml_providers.login(username, password)
self._s.send(auth)
resp = str(self._s.recv(1000), 'utf-8')
self.is_logged = xml_providers.get_response_type(resp) == 'result'
def send_message(self, to, msg):
message = xml_providers.send_message(to, msg)
self._s.send(message)
def change_presence(self, new_presence, to):
pres = xml_providers.change_presence(new_presence, to)
self._s.send(pres)
self._s.recv(1000)
| c0dbd89bdad1581559702cfd9cb8340e50fe5ac2 | [
"Python"
] | 4 | Python | ogitaki/xmpp-bot | f9af6e36411e0d605a905e85622b616d5098b82b | b35b2d3da2a349c5c6fbcad0b9c2a597e35823b2 |
refs/heads/master | <file_sep>#include "pch.h"
#include <iostream>
#include <string.h>
#include <string>
using namespace std;
int main()
{
int miesiac,rok,dzien;
int wskazany_miesiac;
long przesuniecie_dni = 0;
int dodane_lata = 0;
int c = 0;
int p = 1;
int reszta = 0;
int dni = 0;
int ilosc_dni = 0;
int poczatek_tygodnia = 0;
int dni_tygodnia = 0;
int liczba = 1;
int numer = 0;
int numeracja,podany_rok;
string DANY_MIESIAC= " ";
cout << "podaj numer miesiaca:" << endl;
cin >> miesiac;
cout << "podaj rok" << endl;
cin >> rok;
//.<NAME> na lata+miesi¹ce gdy wpiszesz 13 misiêcy bedzie to styczeñ roku nastepnego
if (miesiac > 12)
{
do {
rok = rok + 1;
miesiac = miesiac - 12;
dodane_lata = dodane_lata + 1;
} while (miesiac > 12);
}
podany_rok = rok;
//. dostosowanie nazw miesiąca
switch (miesiac) {
case 1: DANY_MIESIAC = "STYCZEN";
break;
case 2: DANY_MIESIAC = "LUTY";
break;
case 3: DANY_MIESIAC = "MARZEC";
break;
case 4: DANY_MIESIAC = "KWIECIEN";
break;
case 5: DANY_MIESIAC = "MAJ";
break;
case 6: DANY_MIESIAC = "CZERWIEC";
break;
case 7: DANY_MIESIAC = "LIPIEC";
break;
case 8: DANY_MIESIAC = "SIERPIEN";
break;
case 9: DANY_MIESIAC = "WRZESIEN";
break;
case 10: DANY_MIESIAC = "PAZDZIERNIK";
break;
case 11: DANY_MIESIAC = "LISTOPAD";
break;
case 12: DANY_MIESIAC = "GRUDZIEN";
break;
default: DANY_MIESIAC = "error#404 ";
break;
}
if (dodane_lata > 0)
{
cout << "liczba dodanych lat ze wzgledu na liczbe miesiecy: " << dodane_lata << endl;
cout << "PODANE DANE: rok:" << rok << " miesiac:" << miesiac << " (" << DANY_MIESIAC << ")" << endl;
}
//.zamiana roku na przedzia³ 2001-2028
if (rok < 2001)
{
do {
rok = rok + 28;
} while (rok < 2001);
}
if (rok > 2028)
{
do {
rok = rok - 28;
} while (rok > 2028);
}
//.przerabianie przesuniêtego roku na przesuniêty miesi¹c wzglêdem stycznia 2001
rok = rok - 2001;
wskazany_miesiac = (rok * 12 + miesiac - 1);
//.ka¿de 4 lata maj¹ 1461 dni tak¿e mo¿na sobie uproœciæ: 2009= 4lata+4lata+reszta
if (wskazany_miesiac > 48)
{
do {
wskazany_miesiac = wskazany_miesiac - 48;
przesuniecie_dni = przesuniecie_dni + 1461;
} while (wskazany_miesiac > 48);
}
//.zamiana tej reszty z miesiêcy na dnie
for (wskazany_miesiac; wskazany_miesiac > 0; wskazany_miesiac--)
{
reszta++;
++c;
// tu by³ b³¹d bo p ma rosn¹c co rok a nie co miesi¹c xD
if (c == 13)
{
p++;
c = 1;
}
if (p == 4)p = 0;
if (c == 1 || c == 3 || c == 5 || c == 7 || c == 8 || c == 10 || c == 12)
{
przesuniecie_dni = przesuniecie_dni + 31;
}
if (c == 4 || c == 6 || c == 9 || c == 11)
{
przesuniecie_dni = przesuniecie_dni + 30;
}
if ((c == 2) & (p == 0))
{
przesuniecie_dni = przesuniecie_dni + 29;
}
if ((c == 2) & (p != 0))
{
przesuniecie_dni = przesuniecie_dni + 28;
}
}
// cout << endl << "przesuniecie roku:" << rok << endl <<
// "wskazany_miesiac:" << wskazany_miesiac << endl <<
// "przesunieto o miesiecy:" << reszta << endl <<
// "przesuniecie_dni:" << przesuniecie_dni << endl;
//.modulo z przesuniêtych dni, reszta to przesuniêcie, 1 styczeñ 2001 roku to Poniedzia³ek +(7*dowolne'k') daje poniedzia³ek
dzien = przesuniecie_dni % 7;
cout << endl << "pierwszy dzien miesiaca to: ";
switch (dzien) {
case 0: cout << "poniedzialek" << endl;
break;
case 1: cout << "wtorek" << endl;
break;
case 2: cout << "sroda" << endl;
break;
case 3: cout << "czwartek" << endl;
break;
case 4: cout << "piatek" << endl;
break;
case 5: cout << "sobota" << endl;
break;
case 6: cout << "niedizela" << endl;
break;
}
//.wyliczanie iloœci dni nastêpnego miesi¹ca
c++;
if (c == 13) c = 1;
if (c == 1 || c == 3 || c == 5 || c == 7 || c == 8 || c == 10 || c == 12)
{
ilosc_dni = 31;
}
if (c == 4 || c == 6 || c == 9 || c == 11)
{
ilosc_dni = 30;
}
if ((c == 2) && (p == 0))
{
ilosc_dni = 29;
}
if ((c == 2) && (p != 0))
{
ilosc_dni = 28;
}
//.chyba wiadome pytania, podawanie i tytu³ tabeli
//cout << "c jest rowne:" << c << endl
cout << "wybrany miesiac to: " << DANY_MIESIAC << ", ktory ma: " << ilosc_dni << "dni" << endl;
cout << endl << "kalendarz powinien zaczynac sie od jakiego dnia tygodnia?" << endl << "1-Pon, 2-Wt, 3-Sr, 4-Czw, 5-Pt, 6-Sob, 7-Nd" << endl;
cin >> poczatek_tygodnia;
cout << endl << "(1)-format '0X' |czy| (2)- format 'X'?" << endl;
cin >> dni;
cout << endl << "(1)- bez numeracji tygodni |czy| (2)- z numeracja tygodni ?" << endl;
cin >> numeracja;
//.WYŚWIETLANIE, tytuły tabelki
cout << endl << endl << " " << DANY_MIESIAC << ": " << podany_rok << endl;
cout << "------------------------------------" << endl;
switch (poczatek_tygodnia) {
case 1: cout << "| Pn | Wt | Sr | Cz | Pt | Sb | Nd |" << endl;
break;
case 2: cout << "| Wt | Sr | Cz | Pt | Sb | Nd | Pn |" << endl;
break;
case 3: cout << "| Sr | Cz | Pt | Sb | Nd | Pn | Wt |" << endl;
break;
case 4: cout << "| Cz | Pt | Sb | Nd | Pn | Wt | Sr |" << endl;
break;
case 5: cout << "| Pt | Sb | Nd | Pn | Wt | Sr | Cz |" << endl;
break;
case 6: cout << "| Sb | Nd | Pn | Wt | Sr | Cz | Pt |" << endl;
break;
case 7: cout << "| Nd | Pn | Wt | Sr | Cz | Pt | Sb |" << endl;
break;
}
cout << "------------------------------------" << endl;
//.ustawianie iloœci pustych kratek przed dniem pierwszym
for (int b = 1; dzien != (poczatek_tygodnia - 1); b++)
{
cout << "| ";
dni_tygodnia = dni_tygodnia + 1;
dzien = dzien - 1;
if (dzien == -1)
{
dzien = 6;
}
}
//.wstawianie dni do tabelki
for (int liczba = 1; liczba < (ilosc_dni + 1); liczba++)
{
if (dni_tygodnia < 7 & liczba < 10 & dni == 1)
{
cout << "| 0" << liczba << " ";
dni_tygodnia = dni_tygodnia + 1;
}
if (dni_tygodnia < 7 & liczba < 10 & dni == 2)
{
cout << "| " << liczba << " ";
dni_tygodnia = dni_tygodnia + 1;
}
if (dni_tygodnia < 7 & liczba >= 10)
{
cout << "| " << liczba << " ";
dni_tygodnia = dni_tygodnia + 1;
}
//.Przejœcie do nowego wiersza
if (dni_tygodnia == 7)
{
numer++;
if (numeracja == 1)
cout << "|" << endl;
if (numeracja == 2)
cout << "|" << " " << numer << endl;
cout << "------------------------------------" << endl;
dni_tygodnia = 0;
}
}
//.Uzupe³nienie tabeli pustymi miejscami oraz uzupe³nienie brakuj¹cych kresek
for (int b = 1; (dni_tygodnia < 7 & dni_tygodnia>0); b++)
{
cout << "| ";
dni_tygodnia = dni_tygodnia + 1;
}
//.gdy tabela jest ca³a nie uzupe³niaj kresek bo ju¿ s¹
if (dni_tygodnia == 7 || dni_tygodnia == 1)
{
numer++;
if (numeracja == 1)
cout << "|" << endl;
if (numeracja == 2)
cout << "|" << " " << numer << endl;
cout << "------------------------------------" << endl;
}
return 0;
}
<file_sep># Calendar_Generator


| 5298d1cc334b4814a41dbc92fcb0b58a37938d9f | [
"Markdown",
"C++"
] | 2 | C++ | MateuszRodak/Calendar_Generator | da3811fa01292d0d95f42741e0675eb7d0ec7aea | 269af2863ec7ef4f1bc84c6e82cf440dab9bf511 |
refs/heads/master | <file_sep>package nano
import (
"net/http"
"testing"
)
func TestValidator(t *testing.T) {
type Person struct {
Name string `form:"name" json:"name" rules:"required"`
Gender string `form:"gender" json:"gender" rules:"required"`
Email string `form:"email" json:"email" rules:"required"`
Phone string `form:"phone" json:"phone"`
privateField string
IgnoredField string `form:"-"`
}
person := Person{
Name: "foo",
Gender: "male",
Email: "<EMAIL>",
Phone: "",
}
t.Run("pass non-pointer struct", func(st *testing.T) {
bindErr := ValidateStruct(person)
if bindErr.HTTPStatusCode != ErrBindNonPointer.HTTPStatusCode {
st.Errorf("expected HTTPStatusCode error to be %d; got %d", ErrBindNonPointer.HTTPStatusCode, bindErr.HTTPStatusCode)
}
if bindErr.Message != ErrBindNonPointer.Message {
st.Errorf("expected error message to be %s; got %s", ErrBindNonPointer.Message, bindErr.Message)
}
})
t.Run("validation should be passed", func(st *testing.T) {
errBind := ValidateStruct(&person)
if errBind != nil {
t.Errorf("expected error binding to be nil; got %v", errBind)
}
})
t.Run("empty value on required fields", func(st *testing.T) {
person.Name = ""
bindErr := ValidateStruct(&person)
if bindErr.HTTPStatusCode != http.StatusUnprocessableEntity {
st.Errorf("expected HTTPStatusCode error to be %d; got %d", ErrBindNonPointer.HTTPStatusCode, http.StatusUnprocessableEntity)
}
if bindErr.Message != "name fields are required" {
st.Errorf("expected error message to be %s; got %s", ErrBindNonPointer.Message, bindErr.Message)
}
person.Gender = ""
bindErr = ValidateStruct(&person)
if bindErr.HTTPStatusCode != http.StatusUnprocessableEntity {
st.Errorf("expected HTTPStatusCode error to be %d; got %d", ErrBindNonPointer.HTTPStatusCode, http.StatusUnprocessableEntity)
}
if bindErr.Message != "name & gender fields are required" {
st.Errorf("expected error message to be name & gender fields are required; got %s", bindErr.Message)
}
person.Email = ""
bindErr = ValidateStruct(&person)
if bindErr.HTTPStatusCode != http.StatusUnprocessableEntity {
st.Errorf("expected HTTPStatusCode error to be %d; got %d", ErrBindNonPointer.HTTPStatusCode, http.StatusUnprocessableEntity)
}
if bindErr.Message != "name, gender, email fields are required" {
st.Errorf("expected error message to be name, gender, email fields are required; got %s", bindErr.Message)
}
})
}
func TestNestedStructValidation(t *testing.T) {
type Person struct {
Name string `form:"name" json:"name" rules:"required"`
Gender string `form:"gender" json:"gender" rules:"required"`
Address struct {
CityID int `form:"city_id" json:"city_id" rules:"required"`
PostalCode int `form:"psotal_code" json:"postal_code"`
}
}
person := Person{
Name: "foo",
Gender: "",
Address: struct {
CityID int `form:"city_id" json:"city_id" rules:"required"`
PostalCode int `form:"psotal_code" json:"postal_code"`
}{
CityID: 0,
PostalCode: 204,
},
}
errBind := ValidateStruct(&person)
if errBind.HTTPStatusCode != http.StatusUnprocessableEntity {
t.Errorf("expected error HTTPStatusCode to be %d; got %d", http.StatusUnprocessableEntity, errBind.HTTPStatusCode)
}
if errBind.Message != "gender & city_id fields are required" {
t.Errorf("expected error message to be gender & city_id fields are required; got %s", errBind.Message)
}
}
<file_sep>package nano
import (
"encoding/json"
"io"
"net/http"
"reflect"
)
// BindJSON is functions to bind request body (with contet type application/json) to targetStruct.
// targetStruct must be pointer to user defined struct.
func BindJSON(r *http.Request, targetStruct interface{}) *BindingError {
// only accept pointer
if reflect.TypeOf(targetStruct).Kind() != reflect.Ptr {
return &ErrBindNonPointer
}
if r.Body != nil {
defer r.Body.Close()
err := json.NewDecoder(r.Body).Decode(targetStruct)
if err != nil && err != io.EOF {
return &BindingError{
Message: err.Error(),
HTTPStatusCode: http.StatusBadRequest,
}
}
}
return ValidateStruct(targetStruct)
}
<file_sep>package nano
import (
"fmt"
"net/http"
"reflect"
"strconv"
)
// BindSimpleForm is functions to bind request body (with content type form-urlencoded or url query) to targetStruct.
// targetStruct must be pointer to user defined struct.
func BindSimpleForm(r *http.Request, targetStruct interface{}) *BindingError {
// only accept pointer
if reflect.TypeOf(targetStruct).Kind() != reflect.Ptr {
return &BindingError{
Message: "expected pointer to target struct, got non-pointer",
HTTPStatusCode: http.StatusInternalServerError,
}
}
err := r.ParseForm()
if err != nil {
return &BindingError{
Message: fmt.Sprintf("could not parsing form body: %v", err),
HTTPStatusCode: http.StatusInternalServerError,
}
}
err = bindForm(r.Form, targetStruct)
if err != nil {
return &BindingError{
HTTPStatusCode: http.StatusInternalServerError,
Message: fmt.Sprintf("binding error: %v", err),
}
}
return ValidateStruct(targetStruct)
}
// BindMultipartForm is functions to bind request body (with contet type multipart/form-data) to targetStruct.
// targetStruct must be pointer to user defined struct.
func BindMultipartForm(r *http.Request, targetStruct interface{}) *BindingError {
// only accept pointer
if reflect.TypeOf(targetStruct).Kind() != reflect.Ptr {
return &BindingError{
Message: "expected pointer to target struct, got non-pointer",
HTTPStatusCode: http.StatusInternalServerError,
}
}
err := r.ParseMultipartForm(16 << 10)
if err != nil {
return &BindingError{
Message: fmt.Sprintf("could not parsing form body: %v", err),
HTTPStatusCode: http.StatusBadRequest,
}
}
err = bindForm(r.MultipartForm.Value, targetStruct)
if err != nil {
return &BindingError{
HTTPStatusCode: http.StatusInternalServerError,
Message: fmt.Sprintf("binding error: %v", err),
}
}
return ValidateStruct(targetStruct)
}
// bindForm will map each field in request body into targetStruct.
func bindForm(form map[string][]string, targetStruct interface{}) error {
targetPtr := reflect.ValueOf(targetStruct).Elem()
targetType := targetPtr.Type()
// only accept struct as target binding
if targetPtr.Kind() != reflect.Struct {
return fmt.Errorf("expected target binding to be struct")
}
for i := 0; i < targetPtr.NumField(); i++ {
fieldValue := targetPtr.Field(i)
// this is used to get field tag.
fieldType := targetType.Field(i)
// continue iteration when field is not settable.
if !fieldValue.CanSet() {
continue
}
// check if current field nested struct.
// this is possible when current request body is json type.
if fieldValue.Kind() == reflect.Struct {
// bind recursively.
err := bindForm(form, fieldValue.Addr().Interface())
if err != nil {
return err
}
} else {
// web use tag "form" as field name in request body.
// so make sure you have matching name at field name in request body and field tag in your target struct
formFieldName := fieldType.Tag.Get("form")
// continue iteration when field doesnt have form tag.
if formFieldName == "" {
continue
}
formValue, exists := form[formFieldName]
// could not find value in request body, let it empty
if !exists {
continue
}
formValueCount := len(formValue)
// it's possible if current field value is an array.
if fieldValue.Kind() == reflect.Slice && formValueCount > 0 {
sliceKind := fieldValue.Type().Elem().Kind()
slice := reflect.MakeSlice(fieldValue.Type(), formValueCount, formValueCount)
for i := 0; i < formValueCount; i++ {
if err := setFieldValue(sliceKind, formValue[i], slice.Index(i)); err != nil {
return err
}
}
fieldValue.Field(i).Set(slice)
} else {
// it's a single value. just do direct set.
if err := setFieldValue(fieldValue.Kind(), formValue[0], fieldValue); err != nil {
return err
}
}
}
}
return nil
}
// setFieldValue is functions to set field with typed value.
// we will find the best type & size for your field value.
// if empty string provided to value parameter, we will use zero type value as default field value.
func setFieldValue(kind reflect.Kind, value string, fieldValue reflect.Value) error {
switch kind {
case reflect.Int:
setIntField(value, 0, fieldValue)
case reflect.Int8:
setIntField(value, 8, fieldValue)
case reflect.Int16:
setIntField(value, 16, fieldValue)
case reflect.Int32:
setIntField(value, 32, fieldValue)
case reflect.Int64:
setIntField(value, 64, fieldValue)
case reflect.Uint:
setUintField(value, 0, fieldValue)
case reflect.Uint8:
setUintField(value, 8, fieldValue)
case reflect.Uint16:
setUintField(value, 16, fieldValue)
case reflect.Uint32:
setUintField(value, 32, fieldValue)
case reflect.Uint64:
setUintField(value, 64, fieldValue)
case reflect.Bool:
setBoolField(value, fieldValue)
case reflect.Float32:
setFloatField(value, 32, fieldValue)
case reflect.Float64:
setFloatField(value, 64, fieldValue)
case reflect.String:
// no conversion needed. because value already a string.
fieldValue.SetString(value)
default:
// whoopss..
return fmt.Errorf("unknown type")
}
return nil
}
// setIntField is functions to convert input string (value) into integer.
func setIntField(value string, size int, field reflect.Value) {
convertedValue, err := strconv.ParseInt(value, 10, size)
// set default empty value when conversion.
if err != nil {
convertedValue = 0
}
field.SetInt(convertedValue)
}
// setUintField is functions to convert input string (value) into unsigned integer.
func setUintField(value string, size int, field reflect.Value) {
convertedValue, err := strconv.ParseUint(value, 10, size)
// set default empty value when conversion.
if err != nil {
convertedValue = 0
}
field.SetUint(convertedValue)
}
// setBoolField is functions to convert input string (value) into boolean.
func setBoolField(value string, field reflect.Value) {
convertedValue, err := strconv.ParseBool(value)
// set default empty value when conversion.
if err != nil {
convertedValue = false
}
field.SetBool(convertedValue)
}
// setFloatField is functions to convert input string (value) into floating.
func setFloatField(value string, size int, field reflect.Value) {
convertedValue, err := strconv.ParseFloat(value, size)
// set default empty value when conversion.
if err != nil {
convertedValue = 0.0
}
field.SetFloat(convertedValue)
}
<file_sep>package nano
import (
"log"
"net/http"
"testing"
)
func TestBindJSON(t *testing.T) {
type Person struct {
Name string
Gender string
}
var person Person
t.Run("bind non pointer struct", func(st *testing.T) {
req, err := http.NewRequest(http.MethodGet, "/", nil)
if err != nil {
log.Fatalf("could not make http request: %v", err)
}
errBinding := BindJSON(req, person)
if errBinding == nil {
st.Errorf("expected error to be returned; got %v", errBinding)
}
if errBinding != &ErrBindNonPointer {
st.Errorf("expect error to be ErrBindNonPointer; got %v", errBinding)
}
})
}
<file_sep>package nano
import (
"net/http"
"strings"
)
// BindingError is an error wrapper.
// HTTPStatusCode will set to 422 when there is error on validation,
// 400 when client sent unsupported/without Content-Type header, and
// 500 when targetStruct is not pointer or type conversion is fail.
type BindingError struct {
HTTPStatusCode int
Message string
}
var (
// ErrBindContentType returned when client content type besides json, urlencoded, & multipart form.
ErrBindContentType = BindingError{
HTTPStatusCode: http.StatusBadRequest,
Message: "unknown content type of request body",
}
)
// bind request body to defined user struct.
// This function help you to automatic binding based on request Content-Type & request method
func bind(c *Context, targetStruct interface{}) *BindingError {
contentType := c.GetRequestHeader(HeaderContentType)
// if client request using POST, PUT, & PATCH we will try to bind request using simple form (urlencoded & url query),
// multipart form, and JSON. if you need both binding e.g. to bind multipart form & url query,
// this method doesn't works. you should call BindSimpleForm & BindMultipartForm manually from your handler.
if c.Method == "POST" || c.Method == "PUT" || c.Method == "PATCH" || contentType != "" {
if strings.Contains(contentType, MimeFormURLEncoded) {
return BindSimpleForm(c.Request, targetStruct)
}
if strings.Contains(contentType, MimeMultipartForm) {
return BindMultipartForm(c.Request, targetStruct)
}
if c.IsJSON() {
return BindJSON(c.Request, targetStruct)
}
return &ErrBindContentType
}
// when client request using GET method, we will serve binding using simple form.
// it's can binding url-encoded form & url query data.
return BindSimpleForm(c.Request, targetStruct)
}
<file_sep>package nano
import (
"fmt"
"net/http"
"reflect"
"strings"
)
var (
// ErrBindNonPointer must be returned when non-pointer struct passed as targetStruct parameter.
ErrBindNonPointer = BindingError{
Message: "expected pointer to target struct, got non-pointer",
HTTPStatusCode: http.StatusInternalServerError,
}
)
// ValidateStruct will call default struct validator and collect error information from each struct field.
func ValidateStruct(targetStruct interface{}) *BindingError {
// only accept pointer
if reflect.TypeOf(targetStruct).Kind() != reflect.Ptr {
return &ErrBindNonPointer
}
errorBag := make([]string, 0)
// collect error from each field.
errorFields := validate(targetStruct, errorBag)
if len(errorFields) > 0 {
// if only two error fields, just join with & for better message.
if len(errorFields) == 2 {
return &BindingError{
HTTPStatusCode: http.StatusUnprocessableEntity,
Message: fmt.Sprintf("%s fields are required", strings.Join(errorFields, " & ")),
}
}
return &BindingError{
HTTPStatusCode: http.StatusUnprocessableEntity,
Message: fmt.Sprintf("%s fields are required", strings.Join(errorFields, ", ")),
}
}
return nil
}
// validate is default struct validator. this function will called when you do request binding to some struct.
// Current validation rule is only to validate "required" field. To apply field into validation, just add "rules" at field tag.
// if you apply "required" rule, that is mean you are not allowed to use zero type value in you request body field
// because it will give you validation error.
// so if you need 0 value for int field or false value for boolean field, pelase consider to not use "required" rules.
func validate(targetStruct interface{}, errFields []string) []string {
targetValue := reflect.ValueOf(targetStruct)
if reflect.TypeOf(targetStruct).Kind() == reflect.Ptr {
targetValue = targetValue.Elem()
}
targetType := targetValue.Type()
for i := 0; i < targetType.NumField(); i++ {
fieldType := targetType.Field(i)
// skip ignored and unexported fields in the struct
if fieldType.Tag.Get("form") == "-" || !targetValue.Field(i).CanInterface() {
continue
}
// get real values of field and zero type value.
fieldValue := targetValue.Field(i).Interface()
zeroValue := reflect.Zero(fieldType.Type).Interface()
// validate nested struct inside field.
if fieldType.Type.Kind() == reflect.Struct && !reflect.DeepEqual(zeroValue, fieldValue) {
errFields = validate(fieldValue, errFields)
}
// only validate when tag rules is set to required.
if strings.Contains(fieldType.Tag.Get("rules"), "required") {
if reflect.DeepEqual(zeroValue, fieldValue) {
// use field name as default when json & form tag both are not provided.
name := strings.ToLower(fieldType.Name)
// try to get input name from json tag.
// if field has both of json & form tag, appended field name in errFields will taken from form tag.
if jsonName := fieldType.Tag.Get("json"); jsonName != "" {
name = jsonName
}
// try to get input name from form tag.
if formName := fieldType.Tag.Get("form"); formName != "" {
name = formName
}
errFields = append(errFields, name)
}
}
}
return errFields
}
| 4c387ff3b637f8bc45f21ea12e6a4ce89a072590 | [
"Go"
] | 6 | Go | chgruver/nano | ceb4250c44074b7d9381295c31feaeaf0f9bc338 | 145414e91f40439623fd2c070910b2e3cabdd7d5 |
refs/heads/master | <file_sep>/* TODO
* Distributed hubs - only one hub sends/receives data, the others process
* - socket.io has built-in support
* Validate namespace name - mus not have _ as first char
* Use webtorrent for initial download - get most common version
* Is hasOwnProperty really needed?
* Website builtin
* Common package manager integration - get packages from npm if too few peers
* Balance function - assume given connected (int) and otherConnected (int[])
*/
//https://www.noip.com for hubs without domains
var print = console.log.bind(console);
print('Loading modules, please wait');
var webtorrent = require('webtorrent-hybrid'),
signalhub = require('signalhub'),
hive = require('webrtc-swarm'),
scrypt = require('scrypt'),
crypto = require('crypto'),
ifOnline = require('is-online'),
minimist = require('minimist'),
fs = require('fs'),
http = require('http'),
global = {},
modules = {},
handlers = {};
var argv = minimist(process.argv.slice(2), {
alias: {
mode: 'm',
port: 'p' //number
},
default: {
mode: 'c',
port: 80
}
});
//TODO: load handlers
//# Checks
print('Checking that ./config exists');
try {
fs.accessSync('./config', fs.F_OK);
} catch(e) {
fs.mkdirSync('./config');
print('Created ./config');
}
print('Checking that ./config can be read from and written to');
try {
fs.accessSync('./config', fs.R_OK | fs.W_OK);
} catch(e) {
print('Error: Permissions do not allow read or write of ./config');
process.exit();
}
print('Checking that ./downloads exists');
try {
fs.accessSync('./downloads', fs.F_OK);
} catch(e) {
fs.mkdirSync('./downloads');
print('Created ./downloads');
}
print('Checking that ./downloads can be read from and written to');
try {
fs.accessSync('./downloads', fs.R_OK | fs.W_OK);
} catch(e) {
print('Error: Permissions do not allow read or write of ./downloads');
process.exit();
}
function check(files, defaults) {
for (var name in files) {
if (!files.hasOwnProperty(name))
continue;
var path = files[name];
try {
fs.accessSync(path, fs.F_OK);
} catch(e) {
fs.openSync(path, 'w');
print('Created ' + files[name]);
}
try {
fs.accessSync(path, fs.R_OK | fs.W_OK)
} catch(e) {
print('Error: Permissions do not allow read or write of ' + path);
process.exit();
}
var json = fs.readFileSync(path).toString();
global[name.replace(/\s+(.)/, (match, _) => _.toUpperCase())]
= json ? JSON.parse(json) : defaults[name];
print('Loaded ' + name);
}
}
check({
hubs: './config/hubs.json',
installed: './config/installed.json'
}, {
hubs: ['marsultor.ddns.net'],
installed: {}
});
//!# Checks
//Hubs store all information about servers, and a list of connected clients/servers
//Each hub periodically makes an announcement of servers connected to it
//Connect to as few hubs as possible
//If it's a hub, connect to a hub channel where new servers are listed
//Every hour, every hub sends hash and sees if its hash is the same as the rest
//If it's not the same, update somehow
//{h: hash, u: url, o: oldUrl} //where o is optional
//update online hubs based on url
process.stdin.resume();
process.on('SIGTERM', ()=>console.log('why'))
process.on('SIGINT', () => {
//stuff
print('Please wait, saving data');
if (/h/.test(global.mode)) { //if hub
var peers = global.swarm.peers;
print(peers)
for (var i = 0; i < peers.length; i++)
peers[i].send({t: 'hubquit', d: global.url});
//send connected away
var rooms = global.io.nsps['/'].adapter.rooms,
connected = global.io.sockets.connected;
for (var room in rooms) {
print(rooms, room)
for (var id in room) {
var socket = connected[id];
socket.emit('change', server); //TODO: get server count, server weight
}
}
}
process.exit();
});
//settimeout balance, 5 mins
//default weight = 100
function balance(counts, weights, length, hub) {
var total = counts.reduce((p, c) => p + c, 0),
totalWeight = weights.reduce((p, c) => p + c, 0);
}
//builtin web server plugin: server:port/username/repo, like github
function start(config) {
//TODO: config.local option makes server only accept localhost???
config = config || {};
if (!config.mode)
config.mode = config.m;
ifOnline(function(err, online) {
if (online) {
print(`Using ${config.mode.length - 1 ? 'modes' : 'mode'}:
${config.mode.replace('c', ' client\n')
.replace('s', ' server\n')
.replace('h', ' hub\n').slice(0, -1)}`)
global.online = true;
global.mode = config.mode; //'c?s?h?'
if (/[cs]/.test(config.mode)) { //client or server - need to connect to hub
global.packages = {};
modules.socketc = require('socket.io-client');
global.sockets = {};
global.serverURLs = {};
var hubs = global.hubs, //[...url:port]
socket,
handles = [];
var connect = function(callback) {
connected = false;
for (var i = 0; i < hubs.length; i++) {
if (connected)
break;
handles.push(setTimeout(function() { //create new scope
var url = hubs[i],
_socket = modules.socketc(url + '/_ws');
_socket.on('connect', function() {
console.log('yay')
connected = true;
//TODO: is this fast enough?
for (var i = 0; i < handles.length; i++)
clearTimeout(handles[i]);
socket = _socket;
global.hubURL = url;
callback(url);
});
}, 0));
}
}
//while (!socket); //block
//crap
var sendServer = /s/.test(config.mode) ? function(socket) {
socket.emit('server'); //TODO: server data
} : function() {};
var onchange = url => {
print('Changing server to ' + url);
var socket = modules.socketc(url + '/_ws');
sendServer(socket);
socket.on('connect', function() {
socket.on('change', onchange);
socket.on('connected', (namespace, repo, version, url) => {
print('Connected');
//connect to url via socket and add [namespace]
//socket
var socket,
namespace = global.sockets[namespace];
if (!namespace)
namespace = global.sockets[namespace] = {};
var repo = namespace[repo];
if (!repo)
repo = namespace[repo] = {};
repo[version] = socket;
});
socket.on('hubs', function(hubs) {
for (var i = 0; i < hubs.length; i++) {
var hub = hubs[i];
if (!hubs.includes(hub))
hubs.push(hub);
}
fs.writeFile('./config/hubs.json', hubs);
});
socket.on('disconnect', connect(url => onchange(url)));
global.socket = socket;
});
print('Changed server')
}
console.log(global)
//TODO: when socket closes, request a new server from hub
onchange(global.hubURL);
//TODO: test onchange
}
if (/[sh]/.test(config.mode)) {
modules.http = require('http');
modules.express = require('express');
modules.nunjucks = require('nunjucks');
modules.socket = require('socket.io');
//has default html which can be changed
global.app = modules.express();
var app = global.app;
global.renderer = modules.nunjucks.configure('./', {
autoescape: true,
watch: true
}).express(global.app);
global.server = http.createServer(global.app);
global.io = modules.socket(global.server);
fs.readdir('./handlers', (_, items) => {
check({'handler paths': './config/handlers.json'}, {'handler paths': {}});
//assume they're all folders containing npm modules
for (var handler in global.handlerPaths) {
if (!global.handlerPaths.hasOwnProperty(handler))
continue;
handlers[handler] = require('./handlers/' + global.handlerPaths[hadler]);
}
});
print('Loaded handlers');
//TODO: io handlers
if (/h/.test(config.mode)) {
modules.server = require('signalhub/server');
//TODO: initiate signalhub server
//try accessing config.url, see if express gets a url
//global.url = //somehow get url/ddns
global.swarm = hive(signalhub('distributive', global.hubs)),
global.connectedServers = {};
global.servers = {};
global.namespaces = {};
global.ids = {};
global.lastFull = {};
global.ws = global.io
.of('/_ws')
.on('connection', socket => {
socket.on('server', (url, data) => {
global.connectedServers[url] = global.servers[url] = data;
var peers = global.swarm.peers;
for (var i = 0; i < peers.length; i++)
peers[i].send({t: 'server', d: data});
});
socket.on('repo', (namespace, repo, version) => {
//handle version 'latest'
var servers = global.namespaces[namespace];
if (servers && (servers = servers[repo])) {
if (version === 'latest') { //TOCO: cache if more performance needed
version = '';
var keys = Object.getOwnPropertyNames(servers);
for (var i = 0; i < keys.length; i++)
version = version > keys[i] ? version : keys[i];
}
if ((servers = servers[version]) && (servers = servers.map(v => global.ids[v]))) {
for (var url in urls) {
if (!urls.hasOwnProperty(url))
continue;
if (+new Date() - (global.lastFull[url] || 0) > 300000) {
socket.emit('connected', namespace, repo, version, url);
return;
}
}
}
}
//only gets here if not everything works
socket.emit('error', `Cannot find a server for ${namespace}/${repo} v${version}`);
});
});//
//TODO: get initial servers from other hubs
check({'hub data': './config/hub_data.json'}, {'hub data': {}});
//get data
global.swarm.on('peer', peer => {
peer.send({t: 'hub', d: {u: config.url || config.u, w: config.weight || config.w}});
peer.on('data', (data) => {
//data.u = url, data.w = weight, data.d = data
//data.h = hubId, data.i = ids
switch(data.t) {
case 'weight':
var hubData = global.hubData[data.u],
oldWeight = hubData.weight;
hubData.weight = data.w;
if (oldWeight < hubData.weight) {
//if weight increases
//rebalance, taking into account other servers
}
break;
case 'hub':
global.hubs.push(data.u);
var data = global.hubData[data.u];
if (data.w)
data.weight = data.w;
fs.writeFile('./config/hub_data.json', global.hubData);
//rebalance
break;
case 'hubquit':
global.hubs.splice(global.hubs.indexOf(data), 1);
break;
case 'servers':
//data.h = hub id
for (var id in data.i) {
// {...int id: string url}
if (!data.i.hasOwnProperty(id))
continue;
global.ids[id] = data.i[id];
}
for (var url in data.d) {
if (!data.d.hasOwnProperty(url))
continue;
var value = data.d[url];
global.servers[url] = value;
for (var namespace in value.n) {
if (!value.n.hasOwnProperty(url))
continue;
var repos = global.namespaces[namespace],
ns = value.n[namespace];
if (!repos)
repos = global.namespaces[namespace] = {};
for (var repo in ns) {
if (!ns.hasOwnProperty(repo))
continue;
var versions = repos[repo],
v = ns[repo];
if (!versions)
versions = repos[repo] = {};
for (var version in v) {
if (!v.hasOwnProperty(version))
continue;
if (!versions[version])
versions[version] = [];
versions[version].push(v[version]);
}
//data = {n: {...string namespace: {...string repo: {...string version: int[] id}}}}
//id starts with hub id so no conflicts
}
}
}
break;
case 'server':
global.servers[data.u] = data.d; //from other hubs' websocket
//data = {n: {...string namespace: {...string repo: string[] versions}}}
break;
case 'serverquit':
delete servers[data.u];
break;
}
});
});
}
//add rendering here
app.get(/^\/([^/]+)\/(.*)$/, (req, res, next) => {
if (global.handlers.website)
global.handlers.website(req.params[0], req.params[1], req, res, next);
});
app.get(/^\/([^/]+)$/, (req, res) => {
if (!req.path.includes('.') && req.path[req.path.length - 1] !== '/') {
res.redirect(req.path + '/');
return;
}
_static(req.path, res);
});
app.use((req, res) => {
res.redirect('/');
return;
});
app.listen(config.port);
print('Started express');
}
global.online = true;
} else {
print('Not online - falling back to LAN and bluetooth')
}
//TODO: if LAN, init LAN if config.lan enabled
//TODO: init bluetooth
});
}
function connect(namespace, repo, version) {
global.socket.emit('repo', namespace, repo, version);
print(`Connecting to ${namespace}/${repo} v${version}`);
}
function ask(namespace, repo, version, data) {
var namespace = global.packages[namespace];
if (namespace && namespace[repo]) {
var socket = namespace[repo];
socket.emit(data);
} else
print('Error: Not connected to server');
//send??
}
function answer(object) {
var handler = handlers[object.type];
if (!handler)
return; // Don't answer query. Return false if needed.
//send handlers(type)
}
//# Encryption
/*
function encrypt(object, password) {
scrypt.params(1, (err, params) => {
scrypt.kdf(password, params, (err, result) => {
var cipher = crypto.createCipher('aes-128-cbc', result);
//cipher.on('readable', () => {
// //send stream
//});
if (object instanceof Stream) {
object.pipe(cipher).pipe(); //pipe to send stream
//if it's on express, just pipe to res
}
//TODO: send non-stream
});
});
}
function decrypt(object, password) {
scrypt.params(1, (err, params) => {
scrypt.kdf(password, params, (err, result) => {
var decipher = crypto.createDecipher('aes-128-cbc', result);
if (object instanceof Stream) {
object.pipe(decipher).pipe(); //pipe to recieve stream
}
});
});
}
*/
//!# Encryption
start(argv); | bbdc930b095de0a9d4f9d2da246f38f34e7654a7 | [
"JavaScript"
] | 1 | JavaScript | somebody1234/distributive | 6408a2d75dc98707ce2bea762cb154666e89bcef | b58799cd14434a16c780d37dff55801d6fdc4665 |
refs/heads/master | <file_sep>"""
Provides XML rendering support.
"""
from __future__ import unicode_literals
from django.utils import six
from django.utils.xmlutils import SimplerXMLGenerator
from django.utils.six.moves import StringIO
from django.utils.encoding import force_text
from rest_framework.renderers import BaseRenderer
class XMLRenderer(BaseRenderer):
"""
Renderer which serializes to XML.
"""
media_type = 'application/xml'
format = 'xml'
charset = 'utf-8'
item_tag_name = 'list-item'
root_tag_name = 'root'
generator_class = SimplerXMLGenerator
def render(self, data, accepted_media_type=None, renderer_context=None):
"""
Renders `data` into serialized XML.
"""
if data is None:
return ''
stream = StringIO()
xml = self.generator_class(stream, self.charset)
xml.startDocument()
xml.startElement(self.root_tag_name, {})
self._to_xml(xml, data)
xml.endElement(self.root_tag_name)
xml.endDocument()
return stream.getvalue()
def _to_xml(self, xml, data):
if isinstance(data, (list, tuple)):
for item in data:
xml.startElement(self.item_tag_name, {})
self._to_xml(xml, item)
xml.endElement(self.item_tag_name)
elif isinstance(data, dict):
for key, value in six.iteritems(data):
xml.startElement(key, {})
self._to_xml(xml, value)
xml.endElement(key)
elif data is None:
# Don't output any value
pass
else:
xml.characters(force_text(data))
| 0b2b5e739215500684e5203024a722c0965a68ff | [
"Python"
] | 1 | Python | CloudNcodeInc/django-rest-framework-xml | ed1a51a695b758c7ad15748145fb22635d910b13 | a0bc0051f0afa68703322500c1f12b8ca2e50d87 |
refs/heads/main | <file_sep># Friends List App
Hello, my name is <NAME> and I'm learning Ruby on Rails. <br/>
Here is my Friends List APP https://railsfriends7.herokuapp.com <br/>
Backend: Ruby on Rails <br/>
Frontend: Bootstrap <br/>
Database: PostgreSQL <br/>
Other: Devise <br/>
<file_sep>class HomeController < ApplicationController
def index
end
def about
@about_me = 'Hi, my name is <NAME>, and I am learning Ruby on Rails.'
end
end
| c8eb2c868b3e0d933956b0841772db85eb6989ae | [
"Markdown",
"Ruby"
] | 2 | Markdown | henry9779/CRUD-RailsFriends | 8212f4da930a620a14f1e4cc033c26a31f5416ee | e7d323ee2ae0c5ee0ea830ea24be4bde76f8f114 |
refs/heads/master | <file_sep># PA Fair Funding Formula Interactive Map
An interactive map which shows how each of Pennsylvania's 500 school districts' funding allocation from the state will change based on the new fair funding formula. As of the time of the making of this map, only 5.98% of the state's allocated funds are re-routed to school districts based on the fair funding formula. This map allows viewers to see the shifts in funding based on different percentages of state funds being run through the formula.
This map was created with WHYY for [Keystone Crossroads](https://whyy.org/programs/keystone-crossroads/), a collaboration between PA public media organizations to report on topics that impact the state. It was published in October of 2016 in an article titled [*How would your school district fare if lawmakers ramped up the new Pa. funding formula?*](https://whyy.org/articles/how-would-your-school-district-fare-if-lawmakers-ramped-up-the-new-pa-funding-formula/).
The standalone map can be viewed at: https://eneedham.github.io/pa_fair_funding_formula_map/
#### Application screenshot
<img src="images/map-view.png">
<file_sep>
// Add the map, basemap, and attirbution
var dataLayer;
var value;
var layer;
var url = 'https://eneedham-whyy.carto.com/api/v2/viz/6476f322-7561-11e6-87f4-0e3ebc282e83/viz.json';
//QUANTILE INTERVALS from 5.98, same for all percentages
var css598 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_5_98 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_5_98 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_5_98 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_5_98 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_5_98 <= 1961.998050]{polygon-fill: #E1F6D9;line-color: #D1D2D1;}";
var css10 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_10 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_10 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_10 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_10 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_10 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css20 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_20 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_20 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_20 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_20 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_20 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css30 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_30 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_30 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_30 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_30 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_30 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css40 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_40 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_40 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_40 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_40 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_40 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css50 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_50 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_50 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_50 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_50 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_50 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css60 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_60 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_60 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_60 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_60 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_60 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css70 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_70 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_70 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_70 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_70 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_70 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css80 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_80 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_80 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_80 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_80 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_80 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css90 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_90 <= 14576.073520] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_90 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_90 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_90 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_90 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
var css100 = "#pa_school_districts_2015_setpercentages{polygon-fill: #FFFFCC;polygon-opacity: 0.8;line-color: #FFF;line-width: 0.5;line-opacity: 1;}#pa_school_districts_2015_setpercentage [ pup_100 <= 14363.65953] {polygon-fill: #006d2c;}#pa_school_districts_2015_setpercentages [ pup_100 <= 5995.790102] {polygon-fill: #31a354;}#pa_school_districts_2015_setpercentages [ pup_100 <= 4491.090421] {polygon-fill:#74c476;}#pa_school_districts_2015_setpercentages [ pup_100 <= 3055.448955] {polygon-fill: #bae4b3;}#pa_school_districts_2015_setpercentages [ pup_100 <= 1961.998050]{polygon-fill: #edf8e9;line-color: #D1D2D1;}";
function removeTip (x, y, val1, val2, val3, val4, val5){
$('.cartodb-tooltip').remove();
$('#infowindow_template').hide();
$('#infowindow_template').empty();
$('#infowindow_template').append('<div class="hello"><div class="tip_container"><h4>{{name}}</h4><h4>Total State Funding</h4><p>${{'+ val1 +'}}<p><h4>State Funding per Pupil</h4><p>${{'+ val2 +'}}<p><h4>Funding Rank</h4><p>{{'+ val3 +'}} out of 500<p><div class="tipCircle"></div><h4>Median Household Income</h4><p><font color={{color}}>{{hh_order}}</font> ${{smed_hh}}</p></div></div>');
$('.legend_val').empty();
$('.legend_val').append('<p style="margin-top: 3px; margin-bottom: 0px; font-family: Lato; font-size: small">'+ val4 + ' '+ val5 + '</p>');
x.setCartoCSS(y);
}
function slideCSS(d, x){
return d == 5.98 ? removeTip(x, css598, 'stot_5_98', 'spup_5_98', 'rank_5_98', '$483', '$14,576') :
d == 10 ? removeTip(x, css10, 'stot_10', 'spup_10', 'rank_10', '$491', '$14,566'):
d == 20 ? removeTip(x, css20, 'stot_20', 'spup_20', 'rank_20', '$510', '$14,544') :
d == 30 ? removeTip(x, css30, 'stot_30', 'spup_30', 'rank_30', '$529', '$14,521') :
d == 40 ? removeTip(x, css40, 'stot_40', 'spup_40', 'rank_40', '$548', '$14,499') :
d == 50 ? removeTip(x, css50, 'stot_50', 'spup_50', 'rank_50', '$567', '$14,476') :
d == 60 ? removeTip(x, css60, 'stot_60', 'spup_60', 'rank_60', '$586', '$14,454') :
d == 70 ? removeTip(x, css70, 'stot_70', 'spup_70', 'rank_70', '$605', '$14,431') :
d == 80 ? removeTip(x, css80, 'stot_80', 'spup_80', 'rank_80', '$624', '$14,408') :
d == 90 ? removeTip(x, css90, 'stot_90', 'spup_90', 'rank_90', '$585', '$14,386') :
d == 100 ? removeTip(x, css100, 'stot_100', 'spup_100', 'rank_100', '$232', '$14,363'):
removeTip(x, css598, 'stot_5_98', 'spup_5_98', 'rank_5_98');
}
var map = new L.Map('map', {
zoomControl: false,
center: [40.972845, -77.749573],
zoom: 8
});
function main() {
L.tileLayer('http://{s}.basemaps.cartocdn.com/light_all/{z}/{x}/{y}.png', {
attribution: 'Map tiles by <a href="http://stamen.com">Stamen Design</a>, <a href="http://creativecommons.org/licenses/by/3.0">CC BY 3.0</a> — Map data © <a href="http://www.openstreetmap.org/copyright">OpenStreetMap</a>',
subdomains: 'abcd',
}).addTo(map);
function slideFunc(theLayer, thefunc, theID){
$('.nstSlider').nstSlider({
"left_grip_selector": ".leftGrip",
"rounding": {
"5.98": "10",
"10": "20",
"20": "30",
"30": "40",
"40": "50",
"50": "60",
"60": "70",
"70": "80",
"80": "90",
"90": "100",
"100": "110"
},
"value_changed_callback": function(cause, leftValue, rightValue) {
$(this).parent().find('.percLabel').text(leftValue+"%");
value = leftValue;
slideCSS(value, theLayer);
thefunc();
}
});
}
//Change your viz.json below
cartodb.createVis('map', url, {
search: false,
tiles_loader: true,
layer_selector: false,
https: true,
scrollwheel: true,
zoomControl: false,
fullscreen: false
})
.done(function(vis, layers) {
//getting the data layer
layer = layers[1];
dataLayer = layers[1].getSubLayer(0);
dataLayer.set({ 'interactivity': ['cartodb_id', 'name', 'stot_5_98', 'stot_10', 'stot_20', 'stot_30', 'stot_40', 'stot_50', 'stot_60', 'stot_70', 'stot_80', 'stot_90', 'stot_100', 'spup_5_98', 'spup_10', 'spup_20', 'spup_30', 'spup_40', 'spup_50', 'spup_60', 'spup_70', 'spup_80', 'spup_90', 'spup_100', 'rank_5_98', 'rank_10', 'rank_20', 'rank_30', 'rank_40', 'rank_50', 'rank_60', 'rank_70', 'rank_80', 'rank_90', 'rank_100', 'smed_hh', 'med_hh_ran', 'color', 'hh_order']});
function tip(){
tooltip = vis.addOverlay({
type: 'tooltip',
template: $('#infowindow_template').html(),
fields: [{ name: 'name', totch_90: 'totch_90'}],
});
}
//Apply a CartoCSS for that layer
tip();
slideFunc(dataLayer, tip);
})
.error(function(err) {
console.log(err);
});
}
window.onload = main;
| 8a6e7de8489415cd2e304a3191ddce5d684df980 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | eneedham/pa_fair_funding_formula_map | f500fe74001cb7be7e7cedd185d2f210346dd4f6 | e93b5be50e1089b5749ddb728ccd22e715622670 |
refs/heads/master | <file_sep>import HelloService from "../services/Hello.service";
export default {
Query: {
hello() {
return HelloService.hello();
}
},
Mutation: {
saySomting(obj: any, { name }: any) {
console.log(obj, name, "aaa perro");
return HelloService.hello();
}
}
};
<file_sep>import fs from "fs";
const path = __dirname;
const files = fs.readdirSync(path);
let schemas = files
.filter(f => f != "index.ts")
.map(f => fs.readFileSync(`${path}/${f}`).toString("utf8"));
export default schemas;
<file_sep>//https://github.com/leveluptuts/fullstack-graphql-apollo-react-meteor/blob/master/end%20of%20%2327/imports/startup/server/register-api.js
console.log("hello from ts");
import express from "express";
import merge from "lodash/merge";
import bodyParser from "body-parser";
import { ApolloServer } from "apollo-server-express";
import { makeExecutableSchema } from "graphql-tools";
import Schemas from "./src/schemas";
//resolvers
import HelloResolver from "./src/resolvers/Hello.resolver";
import MainResolver from "./src/resolvers/Main.resolver";
const resolvers = merge(MainResolver, HelloResolver);
const schema = makeExecutableSchema({
typeDefs: Schemas,
resolvers
});
const server = new ApolloServer({ schema });
const app = express();
server.applyMiddleware({ app });
app.listen({ port: 4000 }, () =>
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`)
);
<file_sep># Node JS, TypeScript, Sequelize , Graphql BoilerPlate
<file_sep>import Package from "../../package.json";
export default {
Query: {
version() {
return Package.version;
}
}
};
<file_sep>export default {
hello: () => {
return {
id: "102-2-2-4",
name: "Hello"
};
}
};
| cbc8c9b000ac178ce9ffa637c746b3f0d6df3a16 | [
"Markdown",
"TypeScript"
] | 6 | TypeScript | capdilla/nodejs-ts-gql-boilerplate | 7b5b24dc5cc98c3dac960e393902073f1a74bbd7 | ada699f56b9b7cc94314658705c9523cee1f00fd |
refs/heads/master | <file_sep>import React from 'react'
import Card from 'reactstrap/lib/Card'
import CardBody from 'reactstrap/lib/CardBody'
import Col from 'reactstrap/lib/Col'
import Container from 'reactstrap/lib/Container'
import Row from 'reactstrap/lib/Row'
function Interfaces({myref}) {
return (
<section className="section pb-0 bg-gradient-warning" ref={myref}>
<Container>
<Row className="row-grid align-items-center">
<Col className="order-lg-2 ml-lg-auto" md="6">
<div className="position-relative pl-md-5">
<img
alt="..."
className="img-center img-fluid"
src={require("assets/img/ill/ill-2.svg")}
/>
</div>
</Col>
<Col className="order-lg-1" lg="6">
<div className="d-flex px-3">
<div>
<div className="icon icon-lg icon-shape bg-gradient-white shadow rounded-circle text-primary">
<i className="ni ni-building text-primary" />
</div>
</div>
<div className="pl-4">
<h4 className="display-3 text-white">Modern Interface</h4>
<p className="text-white">
The Arctic Ocean freezes every winter and much of the
sea-ice then thaws every summer, and that process will
continue whatever.
</p>
</div>
</div>
<Card className="shadow shadow-lg--hover mt-5">
<CardBody>
<div className="d-flex px-3">
<div>
<div className="icon icon-shape bg-gradient-success rounded-circle text-white">
<i className="ni ni-satisfied" />
</div>
</div>
<div className="pl-4">
<h5 className="title text-success">
Awesome Support
</h5>
<p>
The Arctic Ocean freezes every winter and much of
the sea-ice then thaws every summer, and that
process will continue whatever.
</p>
<a
className="text-success"
href="#pablo"
onClick={e => e.preventDefault()}
>
Learn more
</a>
</div>
</div>
</CardBody>
</Card>
<Card className="shadow shadow-lg--hover mt-5">
<CardBody>
<div className="d-flex px-3">
<div>
<div className="icon icon-shape bg-gradient-warning rounded-circle text-white">
<i className="ni ni-active-40" />
</div>
</div>
<div className="pl-4">
<h5 className="title text-warning">
Modular Components
</h5>
<p>
The Arctic Ocean freezes every winter and much of
the sea-ice then thaws every summer, and that
process will continue whatever.
</p>
<a
className="text-warning"
href="#pablo"
onClick={e => e.preventDefault()}
>
Learn more
</a>
</div>
</div>
</CardBody>
</Card>
</Col>
</Row>
</Container>
{/* SVG separator */}
<div className="separator separator-bottom separator-skew zindex-100">
<svg
xmlns="http://www.w3.org/2000/svg"
preserveAspectRatio="none"
version="1.1"
viewBox="0 0 2560 100"
x="0"
y="0"
>
<polygon
className="fill-white"
points="2560 0 2560 100 0 100"
/>
</svg>
</div>
</section>
)
}
export default Interfaces;
<file_sep>import React from 'react'
import Badge from 'reactstrap/lib/Badge'
import Col from 'reactstrap/lib/Col'
import Container from 'reactstrap/lib/Container'
import Row from 'reactstrap/lib/Row'
function Features({myref}) {
return (
<section className="section section-lg" ref={myref}>
<Container>
<Row className="row-grid align-items-center">
<Col className="order-md-2" md="6">
<img
alt="..."
className="img-fluid floating"
src={require("assets/img/theme/promo-1.png")}
/>
</Col>
<Col className="order-md-1" md="6">
<div className="pr-md-5">
<div className="icon icon-lg icon-shape icon-shape-success shadow rounded-circle mb-5">
<i className="ni ni-settings-gear-65" />
</div>
<h3>Awesome features</h3>
<p>
The kit comes with three pre-built pages to help you get
started faster. You can change the text and images and
you're good to go.
</p>
<ul className="list-unstyled mt-5">
<li className="py-2">
<div className="d-flex align-items-center">
<div>
<Badge
className="badge-circle mr-3"
color="success"
>
<i className="ni ni-settings-gear-65" />
</Badge>
</div>
<div>
<h6 className="mb-0">
Carefully crafted components
</h6>
</div>
</div>
</li>
<li className="py-2">
<div className="d-flex align-items-center">
<div>
<Badge
className="badge-circle mr-3"
color="success"
>
<i className="ni ni-html5" />
</Badge>
</div>
<div>
<h6 className="mb-0">Amazing page examples</h6>
</div>
</div>
</li>
<li className="py-2">
<div className="d-flex align-items-center">
<div>
<Badge
className="badge-circle mr-3"
color="success"
>
<i className="ni ni-satisfied" />
</Badge>
</div>
<div>
<h6 className="mb-0">
Super friendly support team
</h6>
</div>
</div>
</li>
</ul>
</div>
</Col>
</Row>
</Container>
</section>
)
}
export default Features
| 3e69cfadbc6395ef0e705f653f6a5ac93c52e2ca | [
"JavaScript"
] | 2 | JavaScript | johnkatua/portfolio | 5514c3c2ee0cd73f793ab5f6a9bd5973716baf75 | f6e3467256b4b5b7cd4f5121682266803e21861a |
refs/heads/master | <repo_name>kawn2103/FCBookReview<file_sep>/app/src/main/java/kst/app/fcbookreview/MainActivity.kt
package kst.app.fcbookreview
import android.annotation.SuppressLint
import android.content.Intent
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.view.MotionEvent
import androidx.core.view.isVisible
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.room.Room
import kst.app.fcbookreview.adapter.BookAdapter
import kst.app.fcbookreview.adapter.HistoryAdapter
import kst.app.fcbookreview.api.BookService
import kst.app.fcbookreview.databinding.ActivityMainBinding
import kst.app.fcbookreview.model.BestSellerDto
import kst.app.fcbookreview.model.History
import kst.app.fcbookreview.model.SearchBookDto
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
private lateinit var adapter: BookAdapter
private lateinit var historyAdapter: HistoryAdapter
private lateinit var bookService: BookService
private lateinit var db: AppDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
initViews()
val retrofit = Retrofit.Builder()
.baseUrl("https://book.interpark.com")
.addConverterFactory(GsonConverterFactory.create())
.build()
db = getAppDatabase(this)
bookService = retrofit.create(BookService::class.java)
bookService.getBestSellerBooks(getString(R.string.interparkApiKey))
.enqueue(object: Callback<BestSellerDto>{
override fun onResponse(
call: Call<BestSellerDto>,
response: Response<BestSellerDto>
) {
if (!response.isSuccessful){
Log.e("gwan2103_$TAG","NOT SUCCESS")
return
}
response.body()?.let {
Log.d("gwan2103_$TAG",it.toString())
it.books.forEach { book ->
Log.d("gwan2103_$TAG",book.toString())
}
adapter.submitList(it.books)
}
}
override fun onFailure(call: Call<BestSellerDto>, t: Throwable) {
TODO("Not yet implemented")
Log.e("gwan2103_$TAG",t.toString())
}
})
}
private fun initViews(){
adapter = BookAdapter(itemClickedListener = {
Log.d("gwan2103","bbbbbb")
val intnet = Intent(this,DetailActivity::class.java)
intnet.putExtra("bookModel",it)
startActivity(intnet)
})
binding.bookRv.layoutManager = LinearLayoutManager(this)
binding.bookRv.adapter = adapter
historyAdapter = HistoryAdapter(historyDeleteClickListener = {
deleteSearchKeyword(it)
})
binding.historyRecyclerView.layoutManager = LinearLayoutManager(this)
binding.historyRecyclerView.adapter = historyAdapter
binding.searchET.setOnKeyListener { v, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_ENTER && event.action == MotionEvent.ACTION_DOWN){
search(binding.searchET.text.toString())
return@setOnKeyListener true
}
return@setOnKeyListener false
}
binding.searchET.setOnTouchListener{ v, event ->
if (event.action == MotionEvent.ACTION_DOWN){
Log.d("gwan2103","aaaaaaa")
showHistoryView()
}
return@setOnTouchListener false
}
}
private fun search(keyword: String){
bookService.getBooksByName(getString(R.string.interparkApiKey),keyword)
.enqueue(object: Callback<SearchBookDto>{
override fun onResponse(
call: Call<SearchBookDto>,
response: Response<SearchBookDto>
) {
hideHistoryView()
saveSearchKeyword(keyword)
if (!response.isSuccessful){
Log.e("gwan2103_$TAG","NOT SUCCESS")
return
}
adapter.submitList(response.body()?.books.orEmpty())
}
override fun onFailure(call: Call<SearchBookDto>, t: Throwable) {
TODO("Not yet implemented")
hideHistoryView()
Log.e("gwan2103_$TAG",t.toString())
}
})
}
private fun showHistoryView(){
Thread{
val keywords = db.historyDao().getAll().reversed()
runOnUiThread {
Log.d("gwan2103",keywords.toString())
binding.historyRecyclerView.isVisible = true
historyAdapter.submitList(keywords.orEmpty())
}
}.start()
}
private fun hideHistoryView(){
binding.historyRecyclerView.isVisible = false
}
private fun saveSearchKeyword(keyword: String){
Thread{
db.historyDao().insertHistory(History(null,keyword))
}.start()
}
private fun deleteSearchKeyword(keyword: String){
Thread{
db.historyDao().delete(keyword)
showHistoryView()
}.start()
}
companion object{
private const val TAG = "MainActivity"
}
}<file_sep>/app/src/main/java/kst/app/fcbookreview/DetailActivity.kt
package kst.app.fcbookreview
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.room.Room
import com.bumptech.glide.Glide
import kst.app.fcbookreview.databinding.ActivityDetailBinding
import kst.app.fcbookreview.model.Book
import kst.app.fcbookreview.model.Review
class DetailActivity : AppCompatActivity() {
private lateinit var binding: ActivityDetailBinding
private lateinit var db: AppDatabase
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityDetailBinding.inflate(layoutInflater)
setContentView(binding.root)
db = getAppDatabase(this)
val model = intent.getParcelableExtra<Book>("bookModel")
binding.tileTv.text = model?.title.orEmpty()
binding.descriptionTv.text = model?.description.orEmpty()
Glide.with(binding.coverIv.context)
.load(model?.coverSmallUrl.orEmpty())
.into(binding.coverIv)
Thread{
val review = db.reviewDao().getOneReview(model?.id?.toInt() ?: 0)
runOnUiThread {
binding.reviewEt.setText(review?.review.orEmpty())
}
}.start()
binding.saveBt.setOnClickListener {
Thread{
db.reviewDao().saveReview(
Review(
model?.id?.toInt() ?:0,
binding.reviewEt.text.toString()
)
)
}.start()
}
}
}<file_sep>/app/src/main/java/kst/app/fcbookreview/adapter/BookAdapter.kt
package kst.app.fcbookreview.adapter
import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView
import com.bumptech.glide.Glide
import kst.app.fcbookreview.databinding.ItemBookBinding
import kst.app.fcbookreview.model.Book
import javax.net.ssl.SSLSessionBindingEvent
class BookAdapter(val itemClickedListener: (Book) -> Unit): ListAdapter<Book,BookAdapter.BookItemViewHolder>(diffUtil) {
inner class BookItemViewHolder(private val binding: ItemBookBinding):RecyclerView.ViewHolder(binding.root){
fun bind(bookModel: Book){
binding.titleTv.text = bookModel.title
binding.descriptionTv.text = bookModel.description
binding.root.setOnClickListener {
itemClickedListener(bookModel)
}
Glide
.with(binding.bookIv.context)
.load(bookModel.coverSmallUrl)
.into(binding.bookIv)
}
}
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): BookItemViewHolder {
return BookItemViewHolder(ItemBookBinding.inflate(LayoutInflater.from(parent.context),parent,false))
}
override fun onBindViewHolder(holder: BookItemViewHolder, position: Int) {
holder.bind(currentList[position])
}
companion object{
val diffUtil = object : DiffUtil.ItemCallback<Book>() {
override fun areItemsTheSame(oldItem: Book, newItem: Book): Boolean {
return oldItem == newItem
}
override fun areContentsTheSame(oldItem: Book, newItem: Book): Boolean {
return oldItem.id == newItem.id
}
}
}
} | c0710bb632a6b6044bc0ddb991d0930b8a0281a9 | [
"Kotlin"
] | 3 | Kotlin | kawn2103/FCBookReview | b3145403a19fe96613ff851a078e6d7275bedf1a | 8658ade504696a365111e8e0c155ae267882deb2 |
refs/heads/master | <file_sep>const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const Item = require('./models/item');
const User = require('./models/user');
const ItemList = require('./models/item-list');
mongoose.Promise = require('bluebird');
const err = error => console.error(error);
mongoose.connect('mongodb://admin:<EMAIL>:47670/to-do-list-db');
const app = express();
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}));
app.use(session({
secret: 'Napo+Mary',
resave: true,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection})
}));
app.get('/favicon.ico', (req, res) => res.status(204));
function requiresLogin(req, res, next) {
if (req.session && req.session.userId) {
return next();
}
const err = new Error('You must be logged in to view this page.');
err.status = 401;
return next(err);
}
app.get('/', (req, res) => res.render('home'));
app.post('/', (req, res) => res.render('/signin'));
app.get('/signup', (req, res) => res.render('signup'));
app.post('/signup', (req, res) => {
const q = {
$or: [
{username: req.body.username},
{email: req.body.email}
]
};
User.findOne(q).lean().exec().then(user => {
if (user !== null) {
return res.send('Please give another username');
}
User.create(req.body).then(user => {
req.session.userId = user._id;
res.redirect('/' + user.username);
});
}).catch(err);
});
app.get('/signin', (req, res) => res.render('signin'));
app.post('/signin', (req, res) => {
User.authenticate(req.body.email, req.body.password, (err, user) => {
if (err) {
err(err);
}
req.session.userId = user._id;
res.redirect('/' + user.username);
});
});
app.get('/logout', (req, res, next) => {
if (req.session) {
req.session.destroy(err => {
if (err) {
return next(err);
}
return res.redirect('/');
});
}
});
app.get('/:user', requiresLogin, (req, res) => {
User.findOne({username: req.params.user}).then(user => {
if (user !== null) {
ItemList.find({userId: user._id}).populate('itemId').then(items => {
const serializedItems = [];
for (const i of items) {
serializedItems.push(i.itemId.name);
}
res.render('index', {title: `${req.params.user}'s List`, message: `${req.params.user}'s List`, user: req.params.user, itemslist: serializedItems});
}).catch(err);
}
});
});
app.post('/:user', requiresLogin, (req, res) => {
Item.findOne({name: req.body.item}).then(item => {
if (item === null) {
Item.create({name: req.body.item}).then(item => {
User.findOne({username: req.params.user}).then(user => {
if (user !== null) {
ItemList.create({itemId: item._id, userId: user._id}).then(() => {
return res.redirect(`/${req.params.user}`);
});
}
});
});
} else {
User.findOne({username: req.params.user}).then(user => {
if (user !== null) {
ItemList.create({itemId: item._id, userId: user._id}).then(() => {
return res.redirect(`/${req.params.user}`);
});
}
});
}
res.redirect(`/${req.params.user}`);
}).catch(err);
});
app.post('/:user/delete', requiresLogin, (req, res) => {
User.findOne({username: req.params.user}).then(user => {
if (user !== null) {
Item.findOne({name: req.body.delItem}).then(item => {
if (item !== null) {
ItemList.findOneAndDelete({userId: user._id, itemId: item._id}).then(() => {
return res.redirect(`/${req.params.user}`);
});
}
});
}
res.redirect(`/${req.params.user}`);
}).catch(err);
});
const server = app.listen(process.env.PORT, () => {
const {port} = server.address();
console.log('Example app listening at http://localhost:%s', port);
});
| 703307a3cee85556c84064c70528145e30c0b200 | [
"JavaScript"
] | 1 | JavaScript | msr0b0t/to-do-list | 6196c167b602b852dc1e4942c0daeb2f66ef1b62 | 3ba01e85444d66b8eea3e5b631abe8a0aa6bca54 |
refs/heads/master | <file_sep>package com.example.dao;
import com.example.dto.SchoolDto;
import com.example.entity.School;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
/**
* Created by lopez on 2017/2/27.
*/
@Repository
@Mapper
public interface SchoolMapper {
List<School> queryListSchoolByIndex(SchoolDto schoolDto);
void updateSchoolBySchoolId(SchoolDto schoolDto);
}
<file_sep># springboot_Redis
springboot集成redis的demo,使用spring_data_redis,简单易用好上手,此项目主要列举了redis的string模型以及hash模型,后续还会补上。
###简介
~~~
业务:将存在mysql中的学校数据录入redis,增加查询速度
~~~
###数据库表
~~~
CREATE TABLE `school` (
`id` varchar(80) NOT NULL COMMENT '唯一标识',
`name` varchar(100) DEFAULT NULL COMMENT '名称',
`orgNo` varchar(10) DEFAULT NULL COMMENT '机构编码',
`status` tinyint(4) DEFAULT '0' COMMENT '是否有效,0代表有效,1代表无效',
`type` tinyint(4) DEFAULT '1' COMMENT '1:小学 2:中学 3:高中',
`school_key` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`school_key`),
KEY `index_orgNo` (`orgNo`),
KEY `index_type` (`type`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=762322 DEFAULT CHARSET=utf8;
~~~
<file_sep>package com.example;
import com.alibaba.fastjson.JSON;
import com.example.constant.SchoolAreaRedisPrefix;
import com.example.dao.SchoolMapper;
import com.example.dao.redis.ValueRedisDao;
import com.example.dto.SchoolDto;
import com.example.entity.School;
import com.example.service.SchoolService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootRedisApplicationTests {
@Autowired
private ValueRedisDao valueRedisDao;
@Autowired
private SchoolService schoolService;
@Autowired
private SchoolMapper schoolMapper;
/**
* 使用string模型demo
*/
@Test
public void contextLoads() {
this.valueRedisDao.save("lopez");
System.out.println(this.valueRedisDao.getParam());
}
/**
* 使用hash模型hset demo
*/
@Test
public void putSchoolDataToRedis(){
SchoolDto schoolDto = new SchoolDto();
schoolDto.setFromIndex(0);
schoolDto.setToIndex(10000);
schoolService.putSchoolDataToRedis(schoolDto);
}
/**
* 使用hash模型hget demo
*/
@Test
public void getSchoolDataFromRedis(){
List<School> schoolList = schoolMapper.queryListSchoolByIndex(new SchoolDto());
School school = schoolList.get(0);
String schoolStr = schoolService.getSchoolDataFromRedis(SchoolAreaRedisPrefix.schoolPrefix + school.getOrgNo(), String.valueOf(school.getType()));
System.out.println(schoolStr);
}
/**
* 回滚(rollbackFor)
*/
@Test
public void updateSchoolBySchoolId(){
SchoolDto schoolDto = new SchoolDto();
schoolDto.setName("lopez小学");
schoolDto.setId("573");
schoolService.updateSchoolBySchoolIdService(schoolDto);
}
/**
* 不回滚(noRollbackFor)
*/
@Test
public void updateSchoolBySchoolIdNoRollbackFor(){
SchoolDto schoolDto = new SchoolDto();
schoolDto.setName("lopez小学");
schoolDto.setId("573");
schoolService.updateSchoolBySchoolIdServiceNotRollback(schoolDto);
}
}
<file_sep>package com.example.service.impl;
import com.alibaba.fastjson.JSON;
import com.example.constant.SchoolAreaRedisPrefix;
import com.example.dao.SchoolMapper;
import com.example.dao.redis.HashRedisDao;
import com.example.dao.redis.RedisBaseDao;
import com.example.dto.SchoolDto;
import com.example.entity.School;
import com.example.service.SchoolService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import java.util.List;
import java.util.concurrent.Future;
/**
* Created by Administrator on 2017/2/27.
*/
@Service
public class SchoolServiceImpl implements SchoolService {
@Autowired
private SchoolMapper schoolMapper;
@Autowired
private HashRedisDao hashRedisDao;
@Override
public List<School> queryListSchoolByIndex(SchoolDto schoolDto) {
return schoolMapper.queryListSchoolByIndex(schoolDto);
}
@Override
public void putSchoolDataToRedis(SchoolDto schoolDto) {
List<School> schoolList = schoolMapper.queryListSchoolByIndex(schoolDto);
School school = schoolList.get(0);
hashRedisDao.hset(SchoolAreaRedisPrefix.schoolPrefix + school.getOrgNo(), String.valueOf(school.getType()), JSON.toJSONString(school));
}
@Override
public String getSchoolDataFromRedis(String key, String field) {
return hashRedisDao.hget(key, field);
}
@Override
@Transactional(rollbackFor={IllegalArgumentException.class})
public void updateSchoolBySchoolIdService(SchoolDto schoolDto) {
schoolMapper.updateSchoolBySchoolId(schoolDto);
if (ObjectUtils.isEmpty(schoolDto.getSchoolKey())){
throw new IllegalArgumentException("参数错误!");
}
}
@Override
@Transactional(noRollbackFor = {IllegalArgumentException.class})
public void updateSchoolBySchoolIdServiceNotRollback(SchoolDto schoolDto) {
schoolMapper.updateSchoolBySchoolId(schoolDto);
if (ObjectUtils.isEmpty(schoolDto.getSchoolKey())){
throw new IllegalArgumentException("参数错误!");
}
}
}
<file_sep>package com.example.constant;
/**
* Created by lopez on 2016/12/24.
*/
public class SchoolAreaRedisPrefix {
/**
* 学校前缀
*/
public static final String schoolPrefix = "lopez_school_";
}
<file_sep>package com.example.service;
import com.example.dto.SchoolDto;
import com.example.entity.School;
import java.util.List;
import java.util.concurrent.Future;
/**
* Created by lopez on 2017/2/27.
*/
public interface SchoolService {
List<School> queryListSchoolByIndex(SchoolDto schoolDto);
void putSchoolDataToRedis(SchoolDto schoolDto);
String getSchoolDataFromRedis(String key, String field);
void updateSchoolBySchoolIdService(SchoolDto schoolDto);
void updateSchoolBySchoolIdServiceNotRollback(SchoolDto schoolDto);
}
| 07e6994f2160912cc8f57acc67284655d3e55fcb | [
"Markdown",
"Java"
] | 6 | Java | itlopez/springboot_Redis | 3cff4e73ae5023907f4b396969fdd6e59848269e | a3edc680b61c6962deeff6354dab67234b8309f8 |
refs/heads/master | <file_sep>import random
import numpy as np
from scipy.stats import norm
import matplotlib.pyplot as plt
MIN = 1
MAX = 10
data = np.random.randint(low = MIN*100, high = MAX * 100 + 1, size = (100, 5))
dataf = np.array(data, dtype = np.float64)/100
#avreage on rows
datamean = np.mean(dataf,axis = 0)
datastd = np.std(dataf, axis = 0)
pdist = norm(datamean,datastd)
# this contains all the probabilities in the dataset to belong to the given probability
pds = pdist.pdf(dataf)
# prod on columns
epsilons = np.prod ( pds, axis = 1 )
plt.plot(epsilons)
plt.ylabel('epsilon')
plt.xlabel('sample index')
plt.show()
| 66fea215697ec6bea667739e1cd75240cc4a3843 | [
"Python"
] | 1 | Python | AndreiCarabelea/anomalyDetection- | 93b877455f0831389270a7b7815fc367c178404a | 874cf8a87a9adc3a9a370159c9624df2b8abc0aa |
refs/heads/master | <repo_name>krzpob/machinelearning<file_sep>/recognize-letter/src/main/java/pl/javasoft/recognizeletter/NormalNode.java
package pl.javasoft.recognizeletter;
import java.util.Arrays;
import java.util.stream.Stream;
public class NormalNode extends RegullarNode implements Node{
private double corection=0.3;
public NormalNode(int size, HiddenNode[] input) {
super(size);
Arrays.fill(w,1);
a = Stream.of(input).mapToDouble(Node::get).toArray();
}
@Override
public void calc(ActivateFunction activateFunction) {
result = product()/40;
}
@Override
public double get() {
return result;
}
@Override
public void teach(double[] delta) {
}
public void setA(Node[] nodes) {
a=Stream.of(nodes).mapToDouble(Node::get).toArray();
}
}
<file_sep>/recognize-letter/src/main/java/pl/javasoft/recognizeletter/RegullarNode.java
package pl.javasoft.recognizeletter;
import java.util.stream.DoubleStream;
public abstract class RegullarNode implements Node {
protected double result;
protected double[] w;
protected double[] a;
RegullarNode(int size) {
a = new double[size];
w = DoubleStream.generate(Math::random).limit(a.length).toArray();
}
double product(){
return ArrayUtils.product(a,w);
}
public abstract void teach(double[] delta);
}
<file_sep>/recognize-letter/src/main/java/pl/javasoft/recognizeletter/ActivateFunction.java
package pl.javasoft.recognizeletter;
@FunctionalInterface
public interface ActivateFunction {
double activation(double x);
}
<file_sep>/recognize-letter/src/main/java/pl/javasoft/recognizeletter/HiddenNode.java
package pl.javasoft.recognizeletter;
import lombok.extern.slf4j.Slf4j;
import java.util.stream.Stream;
@Slf4j
public class HiddenNode extends RegullarNode implements Node{
public HiddenNode(int size, Node[] input) {
super(size);
a = Stream.of(input).mapToDouble(Node::get).toArray();
log.info("input: {}", (Object) w);
}
@Override
public void calc(ActivateFunction activateFunction) {
double product = product();
result = activateFunction.activation(product);
}
@Override
public double get() {
return result;
}
@Override
public void teach(double[] delta) {
for(int i=0;i<w.length;i++){
double sum=0;
for (int j =0; j<delta.length;j++){
sum+=Math.pow(delta[j]-w[i],2);
}
w[i]-=sum/26;
}
}
}
<file_sep>/recognize-letter/src/main/java/pl/javasoft/recognizeletter/ArrayUtils.java
package pl.javasoft.recognizeletter;
public class ArrayUtils {
public static double[] diff(double a[], double b[]){
double[] result = new double[a.length];
for (int i=0;i<a.length;i++){
result[i]=a[i]-b[i];
}
return result;
}
static double product(double[] a, double[] b){
double result=0;
for(int i=0;i<a.length; i++){
result+=a[i]*b[i];
}
return result;
}
}
<file_sep>/README.md
# machinelearning in java
Exercise write in Java
| a50be50b61fc0f714144913cd2eae59556610e84 | [
"Markdown",
"Java"
] | 6 | Java | krzpob/machinelearning | b3a13ee13e4682dbf02f6d59f361e2437e66ae9a | 41db56665e0da5d2bdeec72898c5bdf004d9d130 |
refs/heads/master | <file_sep>
# Typography
This project was initialy to try out Modular Scale and some JavaScript, but now I'm going to "100%" the stylesheet, in my mind.
I believe I only have two things to do before that's done; add Form styling and then figure out the Line Height for Headers, and maybe tweak the Blockquotes.
Here are the links to the super awesome JavaScript files I've used in the project:
- [Hyphenator](https://code.google.com/p/hyphenator/)
- [WidowTamer](https://github.com/nathanford/widowtamer)
- [Baseline](https://daneden.me/baseline/)
## Always Use Git!
I made the mistake of initializing the repository extremely late into this projects history. I thought it would only be a simple test but it's turned into something a lot bigger. Now a huge chunk of history is lost and there's nothing I can do to see previous versions of my files.
No matter the project I always need to remember to use Git, because even when this project was still small, I found myself wanting to check out previous versions of files to see how I did something that I erased.
<file_sep>
// Calling functions from other scripts.
$(window).load(function() {
// WidowTamer
wt.fix({ event: 'resize' });
// Baseline
// Note: img tag in CSS needed to be set to display as a block.
$('img').baseline(28);
});
| 9ac2d6aa47cac38b28473d5eebb9c094e79d4f2c | [
"Markdown",
"JavaScript"
] | 2 | Markdown | VoxelDavid/typography | 21f270eaa46e2ca9bb8f16fa6de341175da7141c | c6628735749313d77ac1da1f84a53e5df80c26fd |
refs/heads/master | <file_sep># reddit-history
Simple script to scrape reddit comment history.
1. `$ git clone https://github.com/mikechabot/reddit-history.git`
2. `$ pip install praw`
3. Rename `praw.default.ini` to `praw.ini`.
4. Add your client ID, client secret, username and password to `praw.ini`.
5. Update `reddit-history.py` with the usernames you'd like to scrape.
6. `$ python ./src/reddit-history.py > results.txt`
<file_sep>import praw
from datetime import datetime
reddit = reddit = praw.Reddit('bot', user_agent='comment history bot (by /u/yourAccountName)')
collection = [
'yourAccountName',
'yourThrowawayAccount',
'yetAnotherThrowawayAccount'
]
for username in collection:
for comment in reddit.redditor(username).comments.new(limit=None):
id = comment.id.encode('utf-8').strip();
date = datetime.fromtimestamp(comment.created_utc).strftime('%Y-%m-%d %H:%M')
text = comment.body.encode('utf-8').strip()
length = len(text)
print(date + ', ' + id + ',' + str(length) + ', ' + text[0:15]) | 6ad1e736c4cf7f7176b1f529f8a715a4140af09f | [
"Markdown",
"Python"
] | 2 | Markdown | mikechabot/reddit-history | 1ddaecfe21281d3d246a0e352e05b9cca5ddd8c1 | 0792d06d5441315e5b10dd282a1d53cdf8b20af8 |
refs/heads/master | <repo_name>mmg1/dynamic-linq-injection<file_sep>/Makefile
run: DynamicLinq/bin/Debug/DynamicLinq.exe
@#@mono $<
DynamicLinq/bin/Debug/DynamicLinq.exe: DynamicLinq/Program.cs
@xbuild DynamicLinq.sln
<file_sep>/DynamicLinq.Test/ExploitTest.cs
using System;
using System.Net;
using System.Linq;
using System.Linq.Dynamic;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Reflection;
namespace DynamicLinq.Test
{
class Message
{
public string Sender;
public string Receiver;
public string Text;
public DateTime SentAt;
public int Id;
public IPAddress ip4;
public Assembly ass;
public Type type;
public Message(string sender, string receiver, string text, DateTime sentAt, int id, IPAddress ip4)
{
this.Sender = sender;
this.Receiver = receiver;
this.Text = text;
this.SentAt = sentAt;
this.Id = id;
this.ip4 = ip4;
}
}
[TestClass]
public class ExploitTest
{
[TestMethod]
public void access_to_members_restricted_member_access()
{
var messages = new Message[] {
new Message("Alice", "Bob", "Hello Bob!", DateTime.Now, 1, IPAddress.Parse("127.0.0.1"))
};
messages[0].type = typeof(Message);
messages[0].ass = typeof(Message).Assembly;
var filteredMessages = messages.Where("Id = 2");
Assert.AreEqual(0, filteredMessages.Count());
filteredMessages = messages.Where("Id = 1");
Assert.AreEqual(1, filteredMessages.Count());
try
{
filteredMessages = messages.Where("Text = ass.GetName().ToString()");
Assert.Fail("Methods allowed with v{0} on type Assembly", typeof(DynamicExpression).Assembly.GetName().Version);
}
catch (ParseException e)
{
if (!e.Message.Contains("Methods on type"))
throw e;
}
try
{
filteredMessages = messages.Where("Text = ip4.GetAddressBytes().ToString()");
Assert.Fail("Methods allowed with v{0} on type IPAddress", typeof(DynamicExpression).Assembly.GetName().Version);
}
catch (ParseException e)
{
if (!e.Message.Contains("Methods on type"))
throw e;
}
}
}
}<file_sep>/DynamicLinq/Program.cs
using System;
using System.Net;
using System.Linq;
using System.Linq.Dynamic;
using System.Reflection;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
namespace DynamicLinq
{
class Message
{
public string Sender;
public string Receiver;
public string Text;
public DateTime SentAt;
public int Id;
public IPAddress ip4;
public Message(string sender, string receiver, string text, DateTime sentAt, int id, IPAddress ip4) {
this.Sender = sender;
this.Receiver = receiver;
this.Text = text;
this.SentAt = sentAt;
this.Id = id;
this.ip4 = ip4;
}
}
class MainClass
{
public static void Main (string[] args)
{
var messages = new Message[] {
new Message("Alice", "Bob", "Hello Bob!", DateTime.Now, 1, IPAddress.Parse("127.0.0.1")),
new Message("Bob", "Alice", "Hello Alice!", DateTime.Now, 2, IPAddress.Parse("127.0.0.1")),
new Message("Alice", "Bob", "Nice chat!", DateTime.Now, 3, IPAddress.Parse("127.0.0.1")),
new Message("Alice", "Bob", "Foobar", DateTime.Now, 4, IPAddress.Parse("127.0.0.1")),
new Message("Alice", "Fred", "Hello Fred!", DateTime.Now, 5, IPAddress.Parse("127.0.0.1"))
};
var field = args [0];
var op = args [1];
var value = args [2];
// var value = args [0];
// var expr = DynamicExpression.ParseLambda(typeof(Message), null, value, messages);
// Console.WriteLine("Expression: {0}", expr);
// Console.WriteLine("Result: {0}", expr.Compile().DynamicInvoke(messages[0]));
var filteredMessages = messages.Where (field + op + value);
Console.WriteLine ("Dynamic Linq version: {0}", typeof(System.Linq.Dynamic.DynamicExpression).Assembly.FullName);
foreach (var message in filteredMessages) {
foreach(var prop in message.GetType().GetFields())
{
string name = prop.Name;
object val = prop.GetValue(message);
Console.WriteLine("{0}={1}", name, val);
}
Console.WriteLine();
}
}
}
}
| 117bc95d0ea6b619388e15adc6a9960bb8517b92 | [
"C#",
"Makefile"
] | 3 | Makefile | mmg1/dynamic-linq-injection | 75cddb120f85ca6fb884e3639dd03bea7ec2a639 | f859b8b67e32979abf6c3d4e432197145821db96 |
refs/heads/master | <file_sep>window.addEventListener('DOMContentLoaded', function(){
let element = document.querySelector('#writing_text');
var typed = new Typed( element, {
strings: ['am a front-end web developer', 'love coding so much', 'am ready to solve your problems'],
typeSpeed: 30,
backSpeed: 40,
// bindInputFocusEvents: true,
loop: false,
stringsElement: null,
contentType: 'text',
onComplete: function(){
element.style.color = "#fff";
element.style.backgroundColor = "#e67e22";
let cursor = document.querySelector(".typed-cursor");
cursor.classList.remove("typed-cursor--blink");
}
});
$('[data-scroll]').on('click', function(event){
event.preventDefault();
let elementID = $(this).data('scroll');
let elementOffset = $(elementID).offset().top;
$("html, body").animate({
scrollTop: elementOffset
}, 700);
});
let mail_input = document.querySelector('#input-mail')
mail_label = document.querySelector('#mail-label')
textarea = document.querySelector('#input-text')
form = document.querySelector('#form');
mail_input.addEventListener('focusout', function(){
if(!mail_input.checkValidity()){
mail_input.style.borderColor = 'red';
mail_label.style.color = 'red';
mail_label.style.top = '-10px';
mail_label.style.fontSize = '12px';
} else if(mail_input.checkValidity()){
mail_input.style.borderColor = '#fff';
mail_label.style.color = '#fff';
mail_label.style.top = '-10px';
mail_label.style.fontSize = '12px';
}
if(mail_input.value == ''){
mail_input.style.borderColor = '#fff';
mail_label.style.color = '#fff';
mail_label.style.top = '0px';
mail_label.style.fontSize = '16px';
}
});
mail_input.addEventListener('focus', function(){
mail_input.style.borderColor = '#ee760c';
mail_label.style.color = '#ee760c';
mail_label.style.top = '-10px';
mail_label.style.fontSize = '12px';
});
form.addEventListener('submit' ,function(){
alert('Your message was successfully send!');
});
}); | ad076ab0300376db3ae4708683b8f3c07dcc5aef | [
"JavaScript"
] | 1 | JavaScript | beep-31/portfolio | add3c1e8c914a9d3e39dd41eeb659a035ec718b9 | 45b6f44c7679fea52e11ce751364eb8f97ff5caf |
refs/heads/master | <repo_name>jemmeli/angular-REST-EXPRESS-Mongoose-lab11<file_sep>/README.md
# angular-REST-EXPRESS-Mongoose-lab11
##Développement du service à partir de zéro
voir angular-REST-EXPRESS-Mongoose-lab11-1 pour voir la "creating service using scaffolding" using (express-mongoose-generator) - https://www.npmjs.com/package/express-mongoose-generator
<file_sep>/routes/ours.js
var express = require('express');
var router = express.Router();
/*
* (1) - Configuration de la connexion vers la base de données
*/
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/OursDb');//'mongodb://localhost/oursdb'
/*
* (2) - shema
*/
//var Schema = mongoose.Schema;
var BearSchema = mongoose.Schema({
nom: String,
age : Number
}, {collection : 'ours'});
var Ours = mongoose.model('ours', BearSchema);
/* GET home page. */
router.get('/', function(req, res, next) {
Ours.find(function(err, data){
if(err){
res.send(err);
}
res.send(data);
});
});
/* GET BY ID home page. */
router.get('/:id', function(req, res) {
Ours.findOne({_id: req.params.id}, function(err, data){
if(err){
res.send(err);
}
res.send(data);
});
});
/* UPDATE BY ID home page. */
router.put('/:id', function(req, res) {
Ours.findOne({_id: req.params.id}, function(err, data){
//donner nouveau donnees
data.nom = req.body.nom//from form
data.age = req.body.age;//from form
data.save(function(err){
if(err){
res.send(err);
}
res.send({message:'ours updated'});
})
});
});
/* DELETE. */
router.delete('/:id', function(req, res) {
//res.render('index', { title: 'Express' });
Ours.remove({_id: req.params.id}, function(err){
if(err){
res.send(err);
}
res.send({message:'ours deleted'});
});
});
//post
router.post('/', function(req, res) {
//cree instance du model
var ours = new Ours();
ours.nom = req.body.nom;//from form
ours.age = req.body.age;//from form
ours.save(function(err){
if(err){
res.send(err);
}
res.send({message:'ours created'});
});
});
module.exports = router; | bbfee4dab8edff30b29be50bda18711c470d1c7d | [
"Markdown",
"JavaScript"
] | 2 | Markdown | jemmeli/angular-REST-EXPRESS-Mongoose-lab11 | c536f7717d8c6c11599eb96018c5698fa76ce72a | fc9dec692f094206aeb3cd7933ecbf566f9eb902 |
refs/heads/master | <repo_name>Mapkin/wordutils<file_sep>/wordutils/utils.py
from __future__ import division
def split_num(n, s):
"""
Split n into groups of size s numbers starting from the least
significant digit
>>> split_num(123, 2)
[1, 23]
>>> split_num(12345, 3)
[12, 345]
>>> split_num(123, 4)
[123]
"""
groups = []
div = 10 ** s
while n:
groups.append(n % div)
n //= div
groups.reverse()
return groups
<file_sep>/wordutils/base.py
from __future__ import division
from __future__ import unicode_literals
class BaseLanguage(object):
def number_spoken_full(self, n):
raise NotImplementedError()
def number_spoken_casual(self, n):
raise NotImplementedError()
def ordinal_spoken(self, n):
raise NotImplementedError()
@classmethod
def ordinal_text(cls, n):
ones = n % 10
tens = (n // 10) % 10
if tens == 1 or ones == 0 or ones >= 4:
suffix = 'th'
else:
m = {
1: 'st',
2: 'nd',
3: 'rd',
}
suffix = m[ones]
return '{}{}'.format(n, suffix)
<file_sep>/README.md
wordutils
=========
Helper classes and utilities for manipulating numbers to work with
text-to-speech (TTS) engines
Usage
-----
`wordutils` provides a class for different languages although only US
English is provided at the moment.
Most methods are provided as class methods to make things easier
Basic manipulation methods are:
* `number_spoken_full()`
* `number_spoken_casual()`
* `ordinal_text()`
```
In [1]: from wordutils.en_us import EnglishUS
In [2]: EnglishUS.number_spoken_full(102)
Out[2]: u'one hundred two'
In [3]: EnglishUS.number_spoken_casual(102)
Out[3]: u'one oh two'
In [4]: EnglishUS.ordinal_text(102)
Out[4]: u'102nd'
```
See Also
--------
https://github.com/savoirfairelinux/num2words
Project skeleton from [pyskel](https://github.com/mapbox/pyskel)
<file_sep>/tests/test_en.py
from wordutils.en_us import EnglishUS
m_spoken = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
35: 'thirty five',
41: 'forty one',
78: 'seventy eight',
100: 'one hundred',
112: 'one hundred twelve',
999: 'nine hundred ninety nine',
1000: 'one thousand',
1003: 'one thousand three',
9999: 'nine thousand nine hundred ninety nine',
99999: 'ninety nine thousand nine hundred ninety nine',
999999: 'nine hundred ninety nine thousand nine hundred ninety nine',
}
def test_en_instance_full():
en = EnglishUS()
for n, expected in m_spoken.items():
assert en.number_spoken_full(n) == expected
def test_en_class_full():
en = EnglishUS
for n, expected in m_spoken.items():
assert en.number_spoken_full(n) == expected
def test_en_casual():
m = {
0: 'zero',
1: 'one',
2: 'two',
3: 'three',
4: 'four',
5: 'five',
6: 'six',
7: 'seven',
8: 'eight',
9: 'nine',
10: 'ten',
11: 'eleven',
12: 'twelve',
13: 'thirteen',
14: 'fourteen',
15: 'fifteen',
16: 'sixteen',
17: 'seventeen',
18: 'eighteen',
19: 'nineteen',
20: 'twenty',
35: 'thirty five',
78: 'seventy eight',
100: 'one hundred',
112: 'one twelve',
999: 'nine ninety nine',
302: 'three oh two',
1234: 'twelve thirty four',
300: 'three hundred',
2000: 'two thousand',
5600: 'fifty six hundred',
}
en = EnglishUS
for n, expected in m.items():
assert en.number_spoken_casual(n) == expected
<file_sep>/wordutils/en_us.py
from __future__ import division
from __future__ import unicode_literals
from wordutils.base import BaseLanguage
from wordutils.utils import split_num
_ones_teens = ['', 'one', 'two', 'three', 'four',
'five', 'six', 'seven', 'eight', 'nine',
'ten', 'eleven', 'twelve', 'thirteen', 'fourteen',
'fifteen', 'sixteen', 'seventeen', 'eighteen', 'nineteen']
_tens = [None, None, 'twenty', 'thirty', 'forty',
'fifty', 'sixty', 'seventy', 'eighty', 'ninety']
_exponents = [None, 'thousand', 'million', 'billion', 'trillion']
MAX_NUM = 10 ** (len(_exponents) * 3) - 1
class EnglishUS(BaseLanguage):
@classmethod
def number_spoken_full(cls, n):
"""
The basic algorithm is to split the number into groups
of 3. Pronounce each group of 3 and then append the exponent
part.
So 9999 gets split into [9, 999]. The first group is
"nine thousand". The second group is "nine hundred ninety nine"
"""
if n > MAX_NUM:
raise ValueError(
"{} is too large. Largest number is {}".format(n, MAX_NUM)
)
if n == 0:
return 'zero'
parts = []
for g, exp in zip(reversed(split_num(n, 3)), _exponents):
s = cls.lt_1000_spoken_full(g)
if s:
if exp:
s += " " + exp
parts.append(s)
return ' '.join(reversed(parts))
@classmethod
def number_spoken_casual(cls, n):
"""
Split the number in groups of 2. Pronounce each one separately
but say "oh 5" for the final group if it's less than 10.
>>> EnglishUS.number_spoken_casual(302)
"three oh two"
>>> EnglishUS.number_spoken_casual(1267)
"twelve sixty seven"
"""
if n > 9999 or n % 1000 == 0:
return cls.number_spoken_full(n)
if n == 0:
return 'zero'
groups = split_num(n, 2)
if len(groups) > 1 and groups[-1] == 0:
s = "{} hundred".format(cls.lt_1000_spoken_full(groups[0]))
elif len(groups) > 1 and groups[-1] < 10:
s = "{} oh {}".format(
cls.lt_1000_spoken_full(groups[0]),
cls.lt_1000_spoken_full(groups[1])
)
else:
s = " ".join([cls.lt_1000_spoken_full(g) for g in groups])
return s
@classmethod
def lt_1000_spoken_full(cls, n):
""" Spoken form of numbers where 0 < n < 1000 """
parts = []
if n >= 100:
parts.append(_ones_teens[n // 100] + ' hundred')
n %= 100
if n >= 20:
parts.append(_tens[n // 10])
n %= 10
if n:
parts.append(_ones_teens[n])
return " ".join(parts)
<file_sep>/tests/test_utils.py
from wordutils.utils import split_num
def test_split():
assert split_num(1234, 2) == [12, 34]
assert split_num(123, 2) == [1, 23]
assert split_num(123, 4) == [123]
assert split_num(1234567, 4) == [123, 4567]
| 8c9c68f2ff28668fd010576884ef61d717a0a3a0 | [
"Markdown",
"Python"
] | 6 | Python | Mapkin/wordutils | 029e3a2254a8ba273dc735749ef1dafc45fea67a | 5dd81732849cae37d7c27000d57bb6a9e8922314 |
refs/heads/master | <file_sep>const csvFilePath = './data/full/routes.csv';
const airportsCsv = './data/full/airports.csv';
const csv = require('csvtojson');
var express = require("express");
var app = express();
var methods = {
validateInput: async function(input){
if(input.length !== 3){
return false;
}
var allAirports = await csv().fromFile(airportsCsv).then(result => result);
var jsonString = JSON.stringify(allAirports);
var newJsonString = jsonString.split('"IATA 3"').join('"IATA3"');
var airportJSON = JSON.parse(newJsonString);
var inputExists = airportJSON.filter(airport => airport.IATA3 == input);
return inputExists.length > 0;
},
getShortestRoute: function(routes){
return routes.reduce((prev, next) => prev.length > next.length ? next : prev);
},
getFirstRoutes: function(fromCode, allRoutes){
initialRouteArray = [];
var possibleRoutes = allRoutes.filter(route => route.Origin == fromCode)
possibleRoutes.forEach(elem => initialRouteArray.push([elem.Origin,elem.Destination]))
return initialRouteArray;
},
checkForSuccessfulRoutes: function(fromCode,toCode,routes){
var success = false;
routes.forEach(elem => {
if(elem[0] == fromCode && elem[elem.length - 1] == toCode){
success = true;
}
});
return success;
},
getSuccessfulRoutes: function(fromCode,toCode,routes){
var successfulRoutes = [];
routes.forEach(elem => {
if(elem[0] == fromCode && elem[elem.length - 1] == toCode){
successfulRoutes.push(elem);
}
});
return successfulRoutes;
}
}
async function findBestRoute(fromCode, toCode){
var allRoutes = await csv().fromFile(csvFilePath).then(result => result);
console.log("ALL ROUTES SUCCESS")
var possibleRoutes = methods.getFirstRoutes(fromCode, allRoutes);
console.log("FIRST ROUTES SUCCESS")
var success = methods.checkForSuccessfulRoutes(fromCode,toCode,possibleRoutes);
console.log("FIRST SUCCESS CHECK = " + success);
var index = 1;
while(!success){
possibleRoutes = buildRoutes(possibleRoutes,allRoutes);
console.log("BUILD ROUTE " + index)
index++;
success = methods.checkForSuccessfulRoutes(fromCode,toCode,possibleRoutes)
console.log("SUCCESS CHECK " + index + " = " + success);
if(possibleRoutes.length == 0){
return possibleRoutes;
}
}
var successfulRoutes = methods.getSuccessfulRoutes(fromCode,toCode,possibleRoutes)
var shortestRoute = methods.getShortestRoute(successfulRoutes);
console.log("FINAL ROUTE")
console.log(shortestRoute);
return shortestRoute;
}
function buildRoutes(possibleRoutes,allRoutes){
var newRoutes = [];
possibleRoutes.forEach(elem => {
var connections = allRoutes.filter(route => route.Origin == elem[elem.length - 1] && !elem.includes(route.Destination))
console.log("POSSIBLE CONNECTIONS FOUND")
connections.forEach(connection => {
var newRoute = elem.concat(connection.Destination);
newRoutes.push(newRoute)
})
})
console.log("NEW ROUTES FOUND");
return newRoutes;
}
async function main(fromCode,toCode){
if(fromCode == toCode){
return ["From and To Airports Cannot Be The Same"];
}
console.log("FINDING ROUTE FOR " + fromCode + " -> " + toCode);
var validOrigin = await methods.validateInput(fromCode)
if(!validOrigin){
return ["Invalid Origin"];
}
console.log("ORIGIN: " + fromCode + " IS A VALID AIRPORT");
var validDestination = await methods.validateInput(toCode)
if(!validDestination){
return ["Invalid Destination"];
}
console.log("DESTINATION: " + toCode + " IS A VALID AIRPORT");
var bestRoute = await findBestRoute(fromCode,toCode);
if(bestRoute.length == 0){
return ["No Route Found"];
}
return bestRoute;
}
app.get("/", (req, res, next) => {
var bestRoute = main(req.query.from.toUpperCase(),req.query.to.toUpperCase());
bestRoute.then(x => {
res.json(x);
});
});
app.listen(3000, () => {
console.log("Server running on port 3000");
});
module.exports = methods;<file_sep># Instructions
### Note: This project requires nodejs and npm
- Step 1: Clone or download to your local machine
- Step 2: In the terminal, navigate to the folder containing the project
- Step 3: Type: 'npm install'
- Step 4: Type: 'node app.js' to start the app on localhost:3000
- Step 5: Navigate to 'http://localhost:3000/?from=yyz&to=yvr', the query param 'from' is the origin airport code, 'to' is the destination airport code
Note: To run tests type 'npm test' | 65098393580331aa64a82c4552fcf3e3aa68b64f | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | eli-h/back-end-take-home | 1bf4694551626accff3391ffc8a7cf1590433c7f | 7e3985aca430bf7393185d6ed8cf15eebf2dce72 |
refs/heads/master | <file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GameFramework;
using GameFramework.Procedure;
using UnityGameFramework.Runtime;
using ProcedureOwner = GameFramework.Fsm.IFsm<GameFramework.Procedure.IProcedureManager>;
namespace GameMenu
{
public class ProcedureMenu : ProcedureBase
{
protected override void OnEnter(ProcedureOwner procedureOwner)
{
Log.Debug("加载UI");
base.OnEnter(procedureOwner);
//加载UI框架
UIComponent UI = UnityGameFramework.Runtime.GameEntry.GetComponent<UIComponent>();
//加载UI
UI.OpenUIForm(UIPrefabPath.Main,UIGroup.Menu);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using GameFramework;
using GameFramework.Procedure;
using UnityGameFramework.Runtime;
using ProcedureOwner = GameFramework.Fsm.IFsm<GameFramework.Procedure.IProcedureManager>;
namespace GameMenu
{
public class ProcedureLaunch : ProcedureBase
{
protected override void OnEnter(ProcedureOwner procedureOwner)
{
Log.Debug("加载场景");
base.OnEnter(procedureOwner);
SceneComponent scene= UnityGameFramework.Runtime.GameEntry.GetComponent<SceneComponent>();
// 切换场景
scene.LoadScene(SceneName.GameMenu, this);
// 切换流程
ChangeState<ProcedureLaunch>(procedureOwner);
}
}
}
| 219c47c4a8eb1bd3e4ac516f7aaf902aecde37f4 | [
"C#"
] | 2 | C# | ZPCH/PE | 726640914678a0fbef091f67dbc296aa9054e9f7 | 6551d7111e520f17643d7a6c42916a5d75cd727f |
refs/heads/master | <repo_name>Pahkel/video-stream-rpi<file_sep>/stream.py
from flask import Flask, render_template
app=Flask(__name__)
@app.route("/jwplayer")
def jwplayer():
return render_template('jwplayer.html')
@app.route("/strobemediaplayer")
def strobemediaplayer():
return render_template('strobemediaplayer.html')
if __name__ == "__main__":
app.run(host='0.0.0.0', port=80, debug=True)
<file_sep>/README.md
video-stream-rpi
================
Simple **Flask** application for the **Raspberry Pi** that allows you to **stream** from the **camera** to any browser through the **RTMP** protocol.
For the full installation just follow the instructions available at http://www.raspberrypi.org/forums/viewtopic.php?f=43&t=45368.
This solution uses [ffmpeg](https://www.ffmpeg.org/), [crtmpserver](http://www.rtmpd.com/) and both flash players: [jwplayer](http://www.jwplayer.com/) and [strobe media player](http://sourceforge.net/projects/smp.adobe/files/).
*If you wish to access the streams outside of your LAN you need to do some port forwarding on your router and change the RPi's address on both HTML files.*
I decided to provide two different players because while JWPlayer is the recomended one, for me and many other users, it provided some delay that just kept increasing over time, while Strobe Media Player keeps the delay a 1 / 1,5 seconds.
To use this solution you just need to follow the tutorial up until you start *raspivid*. After that just go to the root folder of the Flask project and run:
```
sudo python stream.py
```
Then just open a browser and type your RPi's address followed by the name of the player you wish to use, ex: http://rpi_address/strobemediaplayer
| 3ba6293b8a99ef90846ce8b3a05eb73d0e919a2b | [
"Markdown",
"Python"
] | 2 | Python | Pahkel/video-stream-rpi | 5267e404978a4ab7ac4e66306d38ede4909ee85a | 0e5137a59e85c32462732b366f7275922738213e |
refs/heads/master | <file_sep>## The overall function calculates the inverse of a matrix
## To be more efficient, it caches the result, and will not recalculate
## should the result already exist
## Function to create and compute a list of operands: set, get, setinv, and getinv
makeCacheMatrix <- function(x = matrix()) {
# sets x equal to an empty matrix
i <- NULL
# creates a NULL placeholder 'i' to use for the inverse matrix
set <- function(y){
x <<- y
# sets x to the incoming argument
i <<- NULL
# reset i to NULL if a new argument is defined
}
get <- function() x
# returns the matrix x
setinv <- function(solve) i <<- solve
# computes the inverse matrix
getinv <- function() i
# returns the inverse matrix
list(set = set, get = get,
setinv = setinv,
getinv = getinv)
# creates the list of operands
}
## This portion checks to see if a result has already been cached, returns the cached
## value, or computes the inverse
cacheSolve <- function(x, ...) {
i <- x$getinv()
# get 'i', the inverse matrix calculated above
if(!is.null(i)) {
message("getting cached data")
return(i)
# if 'i' has already been computer, exit this function with 'i'
}
data <- x$get()
# else get the initial matrix 'x' from above
i <- solve(data, ...)
# compute the inverse matrix
x$setinv(i)
# store the result in the variable 'i'
i
# return the inverse matrix
}
| f16ccc3db517c98b6a52b6797e856b8059cd6286 | [
"R"
] | 1 | R | schlumpi787/ProgrammingAssignment2 | 72a14685042b9e622039b7f480cf72152df27ff8 | 46794b69d76237b58077c247a8a1a2909523e4b1 |
refs/heads/main | <repo_name>ibrahim-mustafa555/E-shopping<file_sep>/src/app/product-card/product-card.component.ts
import { CartServiceService } from "./../shared/cartService.service";
import { Product } from "./../shared/product.modle";
import { Component, Input, OnInit } from "@angular/core";
import { ProductsService } from "../shared/get-products.service";
@Component({
selector: "app-product-card",
templateUrl: "./product-card.component.html",
styleUrls: ["./product-card.component.css"],
})
export class ProductCardComponent implements OnInit {
@Input() products: Product;
@Input() check: Boolean = false;
noData: boolean = true;
constructor(
private productSer: ProductsService,
private cartService: CartServiceService
) {}
ngOnInit() {
setInterval(() => {
this.noData = false;
}, 8000);
}
addToCart(product: Product) {
this.cartService.addToCart(product);
}
}
<file_sep>/src/app/shared/get-products.service.ts
import { Product } from './product.modle';
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { map , take} from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class ProductsService {
constructor(private db:AngularFireDatabase) { }
saveNewProduct(product:Product){
return this.db.list('/products').push(product)
}
updateProduct(poductId,product:Product){
return this.db.object('/products/'+poductId).update(product)
}
removeProduct(productId){
return this.db.object('/products/'+productId).remove()
}
getProductById(productId:string){
return this.db.object('/products/'+productId).valueChanges().pipe(take(1));
}
getAllProudcts(){
return this.db.list('/products').snapshotChanges().pipe(map(data=>{
return data.map(doc=>{
return{
id:doc.payload.key,
...doc.payload.toJSON()
}
})
}))
}
}
<file_sep>/src/app/new-product/new-product.component.ts
import { ProductsService } from "./../shared/get-products.service";
import { Component, OnInit } from "@angular/core";
import { GetCategoryService } from "../shared/get-category.service";
import { Router, ActivatedRoute } from "@angular/router";
@Component({
selector: "app-new-product",
templateUrl: "./new-product.component.html",
styleUrls: ["./new-product.component.css"],
})
export class NewProductComponent implements OnInit {
cat = [];
product;
id: string;
spinner: boolean = false;
errorMessage: string;
constructor(
private catService: GetCategoryService,
private prodService: ProductsService,
private router: Router,
private route: ActivatedRoute
) {
this.id = this.route.snapshot.paramMap.get("id");
if (this.id) {
this.prodService.getProductById(this.id).subscribe((data) => {
this.product = data;
console.log(data);
console.log(this.product);
});
} else {
this.product = [];
}
}
ngOnInit() {
this.catService.getCategories().subscribe(
(data) => {
this.cat = data;
},
(error) => {
console.log(error); // lsa hazbt el error da
}
);
}
saveProduct(data) {
if (this.id) {
this.spinner = true;
this.prodService.updateProduct(this.id, data).catch((error) => {
this.spinner = false;
this.errorMessage = error.message;
console.log(this.errorMessage, typeof this.errorMessage, typeof error);
});
this.spinner = false;
// i have to add navigate here
//this.router.navigate(["/my-products"]);
} else {
this.spinner = true;
this.prodService.saveNewProduct(data).catch((error) => {
this.spinner = false;
this.errorMessage = error.message;
console.log(error);
console.log(this.errorMessage);
});
this.spinner = false;
// i have to add navigate here
//this.router.navigate(["/my-products"]);
}
}
removeProduct() {
if (confirm("Do you Wanna Delete it ?")) {
this.prodService.removeProduct(this.id);
this.router.navigate(["/my-products"]);
}
}
}
<file_sep>/src/app/shared/get-category.service.ts
import { Injectable } from '@angular/core';
import { AngularFireDatabase } from 'angularfire2/database';
import { map } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class GetCategoryService {
constructor(private db:AngularFireDatabase) { }
getCategories(){
const arr = [];
return this.db.list('/categories',ref=>{
return ref.orderByChild('name')
}).valueChanges().pipe(map(x=>{
for(const key in x){
arr.push(x[key])
}
return arr;
}))
}
}
<file_sep>/src/app/auth/auth.service.ts
import { Router, ActivatedRoute } from '@angular/router';
import { Injectable } from '@angular/core';
import { AngularFireAuth } from 'angularfire2/auth';
import * as firebase from'firebase/app';
import { Observable, Subject } from 'rxjs';
@Injectable({
providedIn: "root",
})
export class AuthService {
errMessage = new Subject<string>();
user: Observable<firebase.User>;
constructor(private afAuth: AngularFireAuth, private router: Router , private route:ActivatedRoute) {
this.user = this.afAuth.authState;
}
loginWithFacebook() {
return this.afAuth.auth
.signInWithPopup(new firebase.auth.FacebookAuthProvider())
.then((res) => {
console.log(res);
this.successful();
})
.catch((err) => {
this.errMessage.next(err.message);
console.log(err);
});
}
loginWithGoogle() {
return this.afAuth.auth
.signInWithPopup(new firebase.auth.GoogleAuthProvider())
.then((res) => {
console.log(res);
this.successful();
})
.catch((err) => {
this.errMessage.next(err.message);
console.log(err);
});
}
loginWithEmailAndPassword(email, password) {
this.afAuth.auth
.signInWithEmailAndPassword(email, password)
.then((res) => {
console.log(res);
this.successful();
})
.catch((err) => {
this.errMessage.next(err.message);
console.log(err);
});
}
signupWithEmailAndPassword(email, password) {
this.afAuth.auth
.createUserWithEmailAndPassword(email, password)
.then((res) => {
this.successful()
console.log(res);
})
.catch((err) => {
this.errMessage.next(err.message);
console.log(err, this.errMessage);
});
}
logout(){
this.afAuth.auth.signOut()
this.router.navigate(['/']);
}
successful() {
let url = this.route.snapshot.queryParamMap.get("returnURL") || '/';
this.router.navigateByUrl(url);
}
}
<file_sep>/src/app/singup/singup.component.ts
import { Router } from '@angular/router';
import { AuthService } from './../auth/auth.service';
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-singup",
templateUrl: "./singup.component.html",
styleUrls: ["./singup.component.css"],
})
export class SingupComponent implements OnInit {
constructor(private authService: AuthService , private router:Router) {}
errMessage;
ngOnInit() {
this.authService.errMessage.subscribe((data) => {
this.errMessage = data;
});
console.log(this.errMessage);
}
signup(f) {
let email = f.email;
let password = <PASSWORD>;
this.authService.signupWithEmailAndPassword(email, password);
}
goToLogin(){
this.router.navigate(['/login']);
}
}
<file_sep>/src/app/app-routing.module.ts
import { AuthGuardService } from './auth/auth-guard.service';
import { SingupComponent } from './singup/singup.component';
import { LoginComponent } from './login/login.component';
import { NewProductComponent } from './new-product/new-product.component';
import { MyProductsComponent } from './my-products/my-products.component';
import { ProductsComponent } from './products/products.component';
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
const routes: Routes = [
{ path: "", component: ProductsComponent },
{ path: "signup", component: SingupComponent },
{ path: "login", component: LoginComponent },
{
path: "my-products/new-product/:id",
component: NewProductComponent,
canActivate: [AuthGuardService],
},
{
path: "my-products/new-product",
component: NewProductComponent,
canActivate: [AuthGuardService],
},
{
path: "my-products",
component: MyProductsComponent,
canActivate: [AuthGuardService],
},
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
<file_sep>/src/environments/environment.prod.ts
export const environment = {
production: true,
firebase:{
apiKey: "AIzaSyAvOn0uCVt2Rs6TsY9MHgMxKorGODma5BY",
authDomain: "shoeshop-26b01.firebaseapp.com",
databaseURL: "https://shoeshop-26b01.firebaseio.com",
projectId: "shoeshop-26b01",
storageBucket: "shoeshop-26b01.appspot.com",
messagingSenderId: "145976977323",
appId: "1:145976977323:web:ff6c4a6f6934ce922d54ee",
measurementId: "G-RGW8HHY47T"
}
};
<file_sep>/src/app/auth/user.model.ts
export interface User {
email:string;
family_name:string;
given_name : string;
granted_scopes : string;
id : string;
locale : string;
name : string;
picture : string;
verified_email :boolean;
}
/*
email: "<EMAIL>"
family_name: "khalifa"
given_name: "ayman"
granted_scopes: "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile openid"
id: "116818215199448227210"
locale: "ar"
name: "<NAME>"
picture: "https://lh3.googleusercontent.com/a-/AOh14GjoQevqSgTWxDcrpXePdR-g4ljsJrstvMSq-cMh=s96-c"
verified_email: true
*/<file_sep>/src/app/auth/user.service.ts
import { AuthService } from './auth.service';
import { AngularFireDatabase } from 'angularfire2/database';
import { Injectable } from '@angular/core';
@Injectable({
providedIn: 'root'
})
export class UserService {
constructor(private db:AngularFireDatabase,private authService:AuthService) { }
save(user:firebase.User){
this.db.object("/users/" + user.uid).update({
email: user.email,
name: user.displayName,
});
}
}
<file_sep>/src/app/my-products/my-products.component.ts
import { Product } from './../shared/product.modle';
import { ProductsService } from './../shared/get-products.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-my-products',
templateUrl: './my-products.component.html',
styleUrls: ['./my-products.component.css']
})
export class MyProductsComponent implements OnInit {
products:Product[]=[];
sarchData:string;
errorMessage:string;
constructor(private prodService:ProductsService) { }
ngOnInit() {
this.prodService.getAllProudcts().subscribe((prod:Product[])=>{
this.products = prod;
} ,error=>{
this.errorMessage = error.message;
console.log(this.errorMessage)
})
}
}
<file_sep>/src/app/login/login.component.ts
import { Router } from '@angular/router';
import { User } from "./../auth/user.model";
import { AuthService } from "./../auth/auth.service";
import { Component, OnInit } from "@angular/core";
@Component({
selector: "app-login",
templateUrl: "./login.component.html",
styleUrls: ["./login.component.css"],
})
export class LoginComponent implements OnInit {
// user;
errMessage;
constructor(private authService: AuthService, private router:Router) {}
ngOnInit() {
this.authService.errMessage.subscribe((err) => {
this.errMessage = err;
});
}
loginWithFacebook() {
this.authService.loginWithFacebook();
}
loginWithGoogle() {
this.authService.loginWithGoogle();
}
login(f) {
let email = f.email;
let password = <PASSWORD>;
this.authService.loginWithEmailAndPassword(email, password);
}
goToSignUp(){
this.router.navigate(['/signup']);
}
}
<file_sep>/src/app/products/products.component.ts
import { GetCategoryService } from './../shared/get-category.service';
import { Product } from './../shared/product.modle';
import { ProductsService } from './../shared/get-products.service';
import { Component, OnInit } from '@angular/core';
import { map } from 'rxjs/operators';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-products',
templateUrl: './products.component.html',
styleUrls: ['./products.component.css']
})
export class ProductsComponent implements OnInit {
products:Product [] = [];
cat = [];
catFilter;
spinner:boolean = true ;
errorMessage;
constructor(private productSer:ProductsService , private route:ActivatedRoute , private catService:GetCategoryService) { }
ngOnInit() {
this.route.queryParamMap.subscribe(param=>{
this.catFilter = param.get('cat') ;
console.log(this.catFilter)
})
this.productSer.getAllProudcts().subscribe((d:Product[])=>{
this.products = d ;
this.spinner = false;
console.log(this.products)
},error=>{
this.errorMessage = error.message;
console.log(this.errorMessage)
})
this.catService.getCategories().subscribe(data=>{
console.log(data);
this.cat = data ;
},error=>{
this.errorMessage = error.message;
console.log(this.errorMessage)
})
}
}
<file_sep>/src/app/app.module.ts
import { environment } from './../environments/environment.prod';
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
// import { Routes, RouterModule } from '@angular/router';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { CarouselModule } from 'ngx-owl-carousel-o';
import { NavbarComponent } from './navbar/navbar.component';
import { NgbModule } from '@ng-bootstrap/ng-bootstrap';
import { CarouselComponent } from './carousel/carousel.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { ProductsComponent } from './products/products.component';
import { AngularFireModule } from 'angularfire2';
import { AngularFireDatabaseModule } from 'angularfire2/database';
import { Ng2SearchPipeModule } from 'ng2-search-filter';
import { MyProductsComponent } from './my-products/my-products.component';
import { NewProductComponent } from './new-product/new-product.component';
import { FormsModule } from '@angular/forms';
import { ProductCardComponent } from './product-card/product-card.component';
import {MatProgressSpinnerModule} from '@angular/material/progress-spinner';
import { AngularFireAuthModule } from 'angularfire2/auth';
import { LoginComponent } from './login/login.component';
import { SingupComponent } from './singup/singup.component';
@NgModule({
declarations: [
AppComponent,
NavbarComponent,
CarouselComponent,
ProductsComponent,
MyProductsComponent,
NewProductComponent,
ProductCardComponent,
LoginComponent,
SingupComponent
],
imports: [
BrowserModule,
AppRoutingModule,
CarouselModule,
NgbModule,
BrowserAnimationsModule,
AngularFireModule.initializeApp(environment.firebase),
AngularFireDatabaseModule,
Ng2SearchPipeModule,
FormsModule,
MatProgressSpinnerModule,
AngularFireAuthModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
<file_sep>/src/app/shared/cartService.service.ts
import { AuthService } from "./../auth/auth.service";
import { UserService } from "./../auth/user.service";
import { Product } from "./product.modle";
import { AngularFireDatabase } from "angularfire2/database";
import { Injectable } from "@angular/core";
import { map, take } from "rxjs/operators";
@Injectable({
providedIn: "root",
})
export class CartServiceService {
constructor(
private db: AngularFireDatabase,
private authService: AuthService
) {}
userId;
private create() {
return this.db.list("/cart").push({
date: new Date().getTime(),
});
}
// private getCart(shoppingCartId: string) {
// return this.db.object("/cart/" + shoppingCartId);
// }
private getItem(cartId: string, productId: string) {
return this.db.object("/cart/" + cartId + "/items/" + productId);
}
private async getOrCreateCartId() {
let shoppingCartId = localStorage.getItem("shoppingCartId");
if (!shoppingCartId) {
let res = await this.create();
localStorage.setItem("shoppingCartId", res.key);
return res.key;
} else {
return shoppingCartId;
}
}
async addToCart(product: Product) {
let cartId = await this.getOrCreateCartId();
let items$ = this.getItem(cartId, product.id);
items$
.valueChanges()
.pipe(take(1))
.subscribe((item: Product) => {
if (item) {
items$.update({
quantity: item.quantity + 1,
});
} else {
items$.set({
product: product,
quantity: 1,
});
}
});
}
}
<file_sep>/src/app/navbar/navbar.component.ts
import { AuthService } from './../auth/auth.service';
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-navbar',
templateUrl: './navbar.component.html',
styleUrls: ['./navbar.component.css']
})
export class NavbarComponent implements OnInit {
isMenuCollapsed = true;
user;
constructor(private auhtService:AuthService) { }
ngOnInit() {
this.auhtService.user.subscribe(user=>{
this.user=user;
console.log(user)
})
}
logout(){
this.isMenuCollapsed = true;
this.auhtService.logout()
}
}
| dc9ec86ead1904166e8d39026c1a42cfba94c6ed | [
"TypeScript"
] | 16 | TypeScript | ibrahim-mustafa555/E-shopping | a63f8a7794547d5b921334f71152b0db6f532169 | 2f7877ab4d7cbf47b487e3f9abc2d3a19f850be3 |
refs/heads/master | <repo_name>opticalone/meeth<file_sep>/MeethLib/transform.cpp
#include "transform.h"
#include "sfwdraw.h"
#include <iostream>
Transform::Transform()
{
position = vec2{ 0,0 };
dimension = vec2{ 0,0 };
angle = 0;
e_parent = nullptr;
}
mat3 Transform::getLocalTransform() const
{
return translate(position)*scale(dimension)*rotate(angle);
}
mat3 Transform::getGlobalTransform() const
{
if (e_parent != nullptr)
{
return e_parent->getGlobalTransform()* getLocalTransform();
}
else
{
return getLocalTransform();
}
}
void DrawMatrix(const mat3 & t, float drawing_scale)
{
vec2 pos = t[2].xy;
vec2 right_ep = pos + ( t[0].xy) *drawing_scale;
vec2 up_ep = pos + ( t[1].xy) *drawing_scale;
sfw::drawLine(pos.x, pos.y, right_ep.x, right_ep.y,CYAN);
sfw::drawLine(pos.x, pos.y, up_ep.x, up_ep.y, BLUE);
sfw::drawCircle(pos.x, pos.y, drawing_scale / 2,4,PURP);
}
void DrawTexture(unsigned sprite, const mat3 &t)
{
sfw::drawTextureMatrix3(sprite, 0, WHITE, t.m);
}
<file_sep>/MeethLib/mat3.h
#pragma once
#include "vec3.h"
union mat3
{
vec3 c[3];
float m[9];
float mm[3][3];
vec3 &operator[](size_t idx);
const vec3 &operator[](size_t idx) const;
static mat3 identity()
{
return mat3{ 1,0,0,
0,1,0,
0,0,1 };
}
static mat3 zero()
{
return mat3{ 0,0,0,
0,0,0,
0,0,0 };
}
};
bool operator==(const mat3 &A, const mat3 &B);
mat3 operator+(const mat3 &A, const mat3 &B);
mat3 operator-(const mat3 &A, const mat3 &B);
mat3 operator*(const mat3 &A, const mat3 &B); //combine
//This might be a vec3 function not a mat3
vec3 operator*(const mat3 &A, const vec3 &B);
//mat3 operator*(const mat3 &A, const vec3 &B); //apply
mat3 transpose(const mat3 &A); //flip rows and columns
float determinant(const mat3 &A);
mat3 inverse(const mat3 &A);
/* Translation:
[1 0 X]
[0 1 Y]
[0 0 1] */
mat3 translate(const vec2 &t);
/* Scale:
[X 0 0]
[0 Y 0]
[0 0 1] */
mat3 scale(const vec2 &s);
/* Rotation:
A[0].xy is the x-axis
A[1].xy is the y-axis
[cos(a) -sin(a) 0]
[sin(a) cos(a) 0]
[ 0 0 1] */
mat3 rotate(float deg);<file_sep>/x-testspace/main.cpp
#include "meethutils.h"
#include "vec2.h"
int main()
{
int val = min(1, 3);
vec2 test;
test.x = 5;
test.y = 20;
vec2 testb;
test.x = 3;
test.y = 3;
vec2 result = test + testb;
while (true);
}<file_sep>/x-sfwtest/Rigidbody.h
#pragma once
#include "vec2.h"
#include "transform.h"
class Rigidbody
{
public:
float mass;
vec2 velocity,
acceleration,
force,
impulse;
float drag;
float aVelocity;
float aAcceleration;
float torque;
float aDrag;
Rigidbody() : velocity{ 0,0 },
acceleration{ 0,0 },
force{0,0},
impulse{0,0},
mass(1),
drag(0.5),
aVelocity(0),
aAcceleration(0),
torque(0),
aDrag(1)
//speed * Direction
{
}
void integrate(Transform &T, float dt)
{
acceleration = force / mass;
velocity += acceleration* dt + impulse / mass;
T.position += velocity * dt;
impulse = {0,0};
force = -velocity * drag;
aAcceleration = torque / mass;
aVelocity += aAcceleration * dt;
T.angle += aVelocity * dt;
torque = -aVelocity * aDrag;
}
};<file_sep>/01-MeethReview/meethMain.cpp
#include<iostream>
#include "mathies.h"
int main
{
}<file_sep>/01-MeethReview/mathies.cpp
#include "mathies.h"
#define _USE_MATH_DEFINES
#include <cmath>
int walk(int x)
{
int x = 0;
int y = 0;
y = x * x;
return 0;
}
int dFunction(int x, int y)
{
y = x * 2;
return y;
}
int squares(int x)
{
return x*x;
}
int cubes(int x)
{
return x *x *x;
}
float degtoRad(float r, float d, float x)
{
float r = 0.01745329252f;
d = x*r;
}
float radtoDEg(float r, float d, float x)
{
r = d *(3.14 / 180);
}
float basicQuat(float x)
{
return sqrt(x) + 2 * x - 7;
}
float lerp(float start, float end, float time)
{
return start + time * (end - start);
}
float dist(point2d a, point2d b)
{
return sqrtf(sqrt(b.x - a.x) + sqrt(b.y - a.y));
}<file_sep>/x-sfwtest/collision.h
#pragma once
#include"meethutils.h"
#include <cmath>
#include "shapes.h"
struct Collision
{
float pDepth;
float hand;
vec2 axis;
};
Collision intersect_1D(float Amin, float Amax, float bMin, float bMax);
Collision intersect_AABB(const AABB & A, const AABB & B);
Collision intersect_circle(const circle &A, const circle &B);
Collision intersect_AABB_Circle(const AABB&A, const circle &B);
void static_resolution(vec2 &pos, vec2 &vel, const Collision &hit, float elas = 0 );
void dynamic_resolution(vec2 &Apos, vec2 & Avel, float Amass,
vec2 & Bpos, vec2 & Bvel, float Bmass, const Collision & hit, float elas);
<file_sep>/MeethLib/vec2.cpp
#include "vec2.h"
#include "meethutils.h"
#include <climits>
#include <cmath>
#include <cfloat>
//vec2 operator+(const vec2 &lhs, const vec2 & rhs)
//{
//
// return{ lhs.x + lhs.x,lhs.y + lhs.y };
//}
//
//vec2 operator-(const vec2 &lhs, const vec2 & rhs)
//{
// return{ lhs.x - lhs.x,lhs.y - lhs.y };
//}
//
//vec2 operator*(const vec2 &lhs, const vec2 & rhs)
//{
//
// lhs.x * rhs.x;
// lhs.y * rhs.y;
// return lhs;
//}
//
//vec2 operator/(const vec2 &lhs, int rhs)
//{
// vec2 value;
// value.x = lhs.x / rhs;
// value.y = lhs.y / rhs;
// return value;
//}
//
//
//
//
//vec2 & operator+=(vec2 & lhs, const vec2 & rhs)
//{
// lhs.x += rhs.x;
// lhs.y += rhs.y;
// return lhs;
//}
//
//vec2 & operator-=(vec2 & lhs, const vec2 & rhs)
//{
// lhs.x -= rhs.x;
// lhs.y -= rhs.y;
// return lhs;
//}
//
//vec2 & operator*=(vec2 & lhs, const vec2 & rhs)
//{
// lhs.x *= rhs.x;
// lhs.y *= rhs.y;
// return lhs;
//}
//
//vec2 & operator/=(vec2 & lhs, const vec2 & rhs)
//{
// lhs.x /= rhs.x;
// lhs.y /= rhs.y;
// return lhs;
//}
//
//
//
//
//bool operator==(const vec2 & lhs, const vec2 & rhs)
//{
// if (abs(lhs.x - rhs.x) < FLT_EPSILON &&
// abs(lhs.y - rhs.y) < FLT_EPSILON)
// {
// return true;
// }
//}
//
//bool operator!=(const vec2 & lhs, const vec2 & rhs)
//{
// if (abs(lhs.x - rhs.x) < FLT_EPSILON &&
// abs(lhs.y - rhs.y) < FLT_EPSILON)
// {
// return false;
// }
//}
//
//
//
//float vec2::operator[](int index) const
//{
// return v[index];
//
//}
//
//float & vec2::operator[](int index)
//{
// return v[index];
//}
//
//float magnitood(vec2 a, vec2 b)
//{
// float numa = (abs(a.x - b.x));
// float numb = (abs(a.y - b.y));
// numa *= numa;
// numb *= numb;
// float numc = numa + numb;
// numc = sqrt(numc);
// return numc;
//
//}
//
//float normie(vec2 &a, vec2 &b,vec2 &c)
//{
// c = c / magnitood(a, b);
//}
float vec2::operator[](unsigned idx)
{
return v[idx];
}
float vec2::operator[](unsigned idx) const
{
return v[idx];
}
vec2 operator+(const vec2 &lhs, const vec2 &rhs)
{
vec2 result;
result.x = lhs.x + rhs.x;
result.y = lhs.y + rhs.y;
return result;
}
vec2 operator-(const vec2 &lhs, const vec2 &rhs)
{
vec2 result;
result.x = lhs.x - rhs.x;
result.y = lhs.y - rhs.y;
return result;
}
vec2 operator*(const vec2 &lhs, float rhs)
{
vec2 result;
result.x = lhs.x * rhs;
result.y = lhs.y * rhs;
return result;
}
vec2 operator*(float lhs, const vec2 &rhs)
{
return rhs * lhs;
}
vec2 operator/(const vec2 &lhs, float rhs)
{
vec2 result;
result.x = lhs.x / rhs;
result.y = lhs.y / rhs;
return result;
}
vec2 operator-(const vec2 &lhs)
{
vec2 result;
result.x = lhs.x * -1;
result.y = lhs.y * -1;
return result;
}
vec2 &operator+=(vec2 &lhs, const vec2 &rhs)
{
lhs = lhs + rhs;
return lhs;
}
vec2 &operator-=(vec2 &lhs, const vec2 &rhs)
{
lhs = lhs - rhs;
return lhs;
}
vec2 &operator*=(vec2 &lhs, float &rhs)
{
lhs = lhs * rhs;
return lhs;
}
vec2 &operator/=(vec2 &lhs, float &rhs)
{
lhs = lhs / rhs;
return lhs;
}
bool operator==(const vec2 &lhs, const vec2 &rhs)
{
if (abs(lhs.x - rhs.x) < FLT_EPSILON &&
abs(lhs.y - rhs.y) < FLT_EPSILON)
{
return true;
}
return false;
}
bool operator!=(const vec2 &lhs, const vec2 &rhs)
{
return !(lhs == rhs);
}
float mag(const vec2 &v)
{
float aSqr = v.x * v.x;
float bSqr = v.y * v.y;
return sqrtf(aSqr + bSqr);
}
vec2 norm(const vec2 &v)
{
vec2 temp = v;
float len = mag(v);
temp /= len;
return temp;
}
vec2 &normalize(vec2 &v)
{
v = norm(v);
return v;
}
float dot(const vec2 &a, const vec2 &b)
{
float x = a.x * b.x;
float y = a.y * b.y;
return x + y;
}
float dist(const vec2 &a, const vec2 &b)
{
return mag(b - a);
}
vec2 perp(const vec2 &v)
{
return vec2{ v.y, -v.x };
}
vec2 lerp(const vec2 &s, const vec2 &e, float a)
{
return s + a * (e - s);
}
vec2 min(const vec2 &a, const vec2 &b)
{
vec2 temp;
temp.x = fmin(a.x, b.x);
temp.y = fmin(a.y, b.y);
return temp;
}
vec2 max(const vec2 &a, const vec2 &b)
{
vec2 temp;
temp.x = fmax(a.x, b.x);
temp.y = fmax(a.y, b.y);
return temp;
}
vec2 project(const vec2 & v, const vec2 & axis)
{
return dot(v, axis)* axis;
}
vec2 reflect(const vec2 & v, const vec2 & axis)
{
return 2* project(v, axis)-v;
}
<file_sep>/x-sfwtest/bot.cpp
#include "bot.h"
#include "sfwdraw.h"
void Bot::update()
{
}
void Bot::Draw()
{
}
<file_sep>/MeethLib/mathutils.cpp
#include"meethutils.h"
int min(int a, int b)
{
return a < b ? a : b;
}
<file_sep>/01-MeethReview/mathies.h
#pragma once
int walk(int x);
int dFunction(int x, int y);
int squares(int x);
int cubes(int x);
float degtoRad(float r, float d, float x);
float radtoDEg(float r, float d, float x);
struct point2d
{
float x;
float y;
};
// Returns the y value for the given x value in the represented quadratic.
float basicQuat(float x);
// LERP
float lerp(float start, float end, float time);
float dist(point2d a, point2d b);<file_sep>/x-sfwtest/player.h
#pragma once
#include "vec2.h"
#include "transform.h"
#include "collider.h"
#include "Sprite.h"
#include "Rigidbody.h"
#include "controller.h"
class Enemy;
class Player
{
public:
Transform transform;
Rigidbody rigidbody;
Collider collider;
Controller comtroller;
Sprite sprite;
Enemy * enemy;
};
class Enemy
{
public:
Transform transform;
Rigidbody rigidbody;
Collider collider;
Sprite sprite;
};
class Wall
{
public:
Transform transform;
Rigidbody rigidbody;
Collider collider;
Sprite sprite;
};
void chasem(Enemy &enemy, Player &player);
bool doCollision(Player &player, const Wall &wall);
void doCollision(Player &player, Enemy & enemy);
bool doCollision(Enemy & enemy, const Wall & wall);
<file_sep>/x-sfwtest/main.cpp
#include "sfwdraw.h"
#include "player.h"
#include <iostream>
#include "transform.h"
#include <stdlib.h> /* srand, rand */
#include <time.h>
#include"meethutils.h"
#include "Rigidbody.h"
#include "shapes.h"
#include "DrawShape.h"
#include"collision.h"
int main()
{
sfw::initContext(800, 800, "Don't Go Into the Light");
sfw::setBackgroundColor(0x110030ff);
Player player;
player.sprite = sfw::loadTextureMap("res/dudebro.png");
player.transform.dimension = vec2{ 52, 62 };
player.transform.position = vec2{ 400,300 };
player.collider.box.extents = { .5,.5 };
Enemy enemy[20];
enemy[0].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[0].transform.dimension = vec2{ 34,58 };
enemy[0].transform.position = vec2{ 300,200 };
enemy[0].collider.box.extents = { .5,.5 };
enemy[1].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[1].transform.dimension = vec2{ 34,58 };
enemy[1].transform.position = vec2{ 400,200 };
enemy[1].collider.box.extents = { .5,.5 };
enemy[2].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[2].transform.dimension = vec2{ 34,58 };
enemy[2].transform.position = vec2{ 200,300 };
enemy[2].collider.box.extents = { .5,.5 };
enemy[3].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[3].transform.dimension = vec2{ 34,58 };
enemy[3].transform.position = vec2{ 100,200 };
enemy[3].collider.box.extents = { .5,.5 };
enemy[4].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[4].transform.dimension = vec2{ 34,58 };
enemy[4].transform.position = vec2{ 200,100 };
enemy[4].collider.box.extents = { .5,.5 };
enemy[5].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[5].transform.dimension = vec2{ 34,58 };
enemy[5].transform.position = vec2{100,100 };
enemy[5].collider.box.extents = { .5,.5 };
enemy[6].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[6].transform.dimension = vec2{ 34,58 };
enemy[6].transform.position = vec2{ 100,300 };
enemy[6].collider.box.extents = { .5,.5 };
enemy[7].sprite = sfw::loadTextureMap("res/antidudebro.png");
enemy[7].transform.dimension = vec2{ 34,58 };
enemy[7].transform.position = vec2{ 100,400 };
enemy[7].collider.box.extents = { .5,.5 };
Wall floor[20];
floor[0].transform.position = { 400,10 };
floor[0].transform.dimension = { 800,20 };
floor[0].collider.box.extents = { .5, .5 };
floor[0].sprite.dim = { 1,1 };
//floor[0].sprite.handle = sfw::loadTextureMap("res/floor.png");
floor[1].transform.position = { 10,400 };
floor[1].transform.dimension = { 20,800 };
floor[1].collider.box.extents = { .5, .5 };
floor[1].sprite.dim = { 1,1 };
//floor[1].sprite.handle = sfw::loadTextureMap("res/floor.png");
floor[2].transform.position = { 400,790 };
floor[2].transform.dimension = { 800,20 };
floor[2].collider.box.extents = { .5, .5 };
floor[2].sprite.dim = { 1,1 };
//floor[2].sprite.handle = sfw::loadTextureMap("res/floor.png");
floor[3].transform.position = { 790,400 };
floor[3].transform.dimension = { 20,800 };
floor[3].collider.box.extents = { .5, .5 };
floor[3].sprite.dim = { 1,1 };
//floor[3].sprite.handle = sfw::loadTextureMap("res/floor.png");
floor[4].transform.position = { 400,400 };
floor[4].transform.dimension = { 20,300 };
floor[4].collider.box.extents = { .5, .5 };
floor[4].sprite.dim = { 1,1 };
//floor[3].sprite.handle = sfw::loadTextureMap("res/floor.png");
while (sfw::stepContext())
{
float dt = sfw::getDeltaTime();
player.comtroller.poll(player.rigidbody, player.transform);
player.rigidbody.integrate(player.transform, dt);
for (int i = 0; i < 20; i++)
{
enemy[i].rigidbody.integrate(enemy[i].transform, dt);
enemy[i].sprite.draw(enemy[i].transform);
chasem(enemy[i], player);
}
player.sprite.draw(player.transform);
for (int i = 0; i < 20; i++)
{
floor[i].sprite.draw(floor[i].transform);
}
for (int i = 0; i < 20; ++i)
{
doCollision(player, floor[i]);
doCollision(player, enemy[i]);
for (int j = 0; j < 20; ++j)
{
doCollision(enemy[i], floor[j]);
}
}
// drawAABB(player.collider.getGlobalBox(player.transform), BLUE);
for (int i = 0; i < 5; ++i)
{
drawAABB(floor[i].collider.getGlobalBox(floor[i].transform), GREEN);
}
//std::cout << player.transform.position.x << "," << player.transform.position.y << std::endl;
}
sfw::termContext();
}
//
//int main()
//{
//
// srand(time(NULL));
//
// sfw::initContext(800, 600, "Don't Go Into the Light");
//
// sfw::setBackgroundColor(0x1e0042ff);
//
// Player player;
// player.sprite = sfw::loadTextureMap("res/dudebro.png");
// player.transform.dimension = vec2{ 20,20 };
// player.transform.position = vec2{ 300,400 };
// player.collider.box.extents = { .5,.5 };
//
//
//
//
// float dt = sfw::getDeltaTime();
// Transform transformR;
//
// Rigidbody rigidbody;
//
// circle circ = {{ 0,0 }, 1};
// circle circ2 = { { 100,100 },10 };
//
//
// AABB aabb = { { 0,0 }, {1,1} };
// AABB box2 = { {400,300},{50,50} };
//
// transformR.position = vec2{ 400,300 };
// transformR.dimension = vec2{ 50,75 };
//
// //static transforms for rotating around
//
// //Transform myTransform;
// //myTransform.position = vec2{ 1800 , 50 };
// //myTransform.dimension = vec2{ 1,1 };
// //myTransform.angle = ab;
//
// //Transform mybTransform;
// //mybTransform.position = vec2{ 10 , 50 };
// //mybTransform.dimension = vec2{ 1,1 };
// //mybTransform.angle = ab;
//
// //Transform mycTransform;
// //mycTransform.position = vec2{ 10 , 1030 };
// //mycTransform.dimension = vec2{ 1,1 };
// //mycTransform.angle = ef;
//
// //Transform mydTransform;
// //mydTransform.position = vec2{ 1890 , 1000 };
// //mydTransform.dimension = vec2{ 1,1 };
// //mydTransform.angle = ab;
//
// //Transform yTransform[300];
// //for (int i = 0; i < 299; i++)
// //{
// // yTransform[i].position = vec2{ -1.f - i, 1.f + i };
// // yTransform[i].dimension = vec2{ 1,1 };
// // yTransform[i].angle = ab;
// // yTransform[i].e_parent = &myTransform;
//
// //
// //
//
// //Transform aTran[300];
// //for (int i = 0; i < 299; i++)
// //{
// // aTran[i].position = vec2{ 1.f +i , 1.f +i };
// // aTran[i].dimension = vec2{ 1,1 };
// // aTran[i].angle = ab;
// // aTran[i].e_parent = &mydTransform;
//
// //}
//
// //Transform bTransform[300];
// //for (int i = 0; i < 299; i++)
// //{
// // bTransform[i].position = vec2{ 1.f + i, 1.f + i };
// // bTransform[i].dimension = vec2{ 1,1 };
// // bTransform[i].angle = ab;
// // bTransform[i].e_parent = &mybTransform;
//
// //}
//
// //Transform cTransform[300];
// //for (int i = 0; i < 299; i++)
// //{
// // cTransform[i].position = vec2{ 1.f - i, 1.f - i };
// // cTransform[i].dimension = vec2{ 1,1 };
// // cTransform[i].angle = ef;
// // cTransform[i].e_parent = &mycTransform;
// //}
//
// //Player me(vec2{ 100, 100 }, vec2{ 1,1 }, 15 ,30, 16); // CREATe PLAYER
// //Enemy dood(vec2{ 200, 200 }, vec2{ 1,1 }, 15, 29, 16, 100); // CREATE ENEMY
// //Enemy dood2(vec2{ 300, 200 }, vec2{ 1,1 }, 15, 20, 16, 100); // CREATE ENEMY
//
//
// while (sfw::stepContext())
// {
//
// player.comtroller.poll(player.rigidbody, player.transform);
//
// player.rigidbody.integrate(player.transform, dt);
// player.sprite.draw(player.transform);
//
//
// drawAABB(player.collider.getGlobalBox(player.transform), GREEN);
//
// drawCircle(circ2);
// drawCircle(transformR.getGlobalTransform()*circ);
//
// rigidbody.force = { 0,-75 };
//
//
//
// rigidbody.integrate(transformR, dt);
//
// DrawMatrix(transformR.getGlobalTransform(), 12);
//
// float t = sfw::getTime();
//
// Collision result = intersect_AABB(transformR.getGlobalTransform()* aabb, box2);
// Collision result2 = intersect_circle(transformR.getGlobalTransform()* circ, circ2);
// unsigned color = result.pDepth < 0 ? BLUE : GREEN;
//
// if (result.pDepth >= 0)
// transformR.position += result.axis* result.hand * result.pDepth;
// if (result2.pDepth >= 0)
// transformR.position += result2.axis* result2.hand * result2.pDepth;
//
//
// drawAABB(box2,color);
// drawAABB(transformR.getGlobalTransform()*aabb, color);
//
//
//
// /*me.update();
// me.Draw();
// dood.update();
// dood.Draw();
//
// dood2.update();
// dood2.Draw();*/
//
// //DrawMatrix(myTransform.getGlobalTransform(), 20);
// //myTransform.angle += sfw::getDeltaTime() + 5;
//
// /*myTransform.dimension = vec2{ sinf(t) * ab, sinf(t) + ab };
// mybTransform.dimension = vec2{ sinf(t) * ab, sinf(t) + cd };
// mycTransform.dimension = vec2{ sinf(t) * ab, -sinf(t) + ef };
// mydTransform.dimension = vec2{ sinf(t) * ab, -sinf(t) - cd };
//
// for (int i = 0; i < 199; i++)
// {
// yTransform[i].angle = { sinf(t) * ab};
// yTransform[i].dimension = vec2{ sinf(t) * cd, sinf(t)* ab };
//
// bTransform[i].dimension = vec2{ sinf(t) * ab, sinf(t) - ef };
// bTransform[i].angle = { sinf(t) * cd };
//
// cTransform[i].dimension = vec2{ sinf(t) * ab, sinf(t) - cd };
// bTransform[i].angle = { sinf(t) * ef };
//
// aTran[i].angle = { sinf(t) * ab};
// aTran[i].dimension = vec2{ sinf(t) * cd, sinf(t) * ab };
//
//
//
//
//
// DrawMatrix(yTransform[i].getGlobalTransform(), i+1 );
// DrawMatrix(aTran[i].getGlobalTransform(), i + 1);
// DrawMatrix(bTransform[i].getGlobalTransform(), i + 1);
// DrawMatrix(cTransform[i].getGlobalTransform(), i + 1);
// }*/
//
// //dood.Collision(me);
// //dood2.Collision(me);
// //std::cout <<"enemy 1:"<< dood.m <<std::endl<<std::endl;
// //std::cout <<"enemy 2:"<< dood2.m << std::endl;
// }
//
//
//
// sfw::termContext();
//}<file_sep>/x-sfwtest/DrawShape.cpp
#include "DrawShape.h"
#include "vec2.h"
#include "shapes.h"
#include "transform.h"
#include "sfwdraw.h"
void drawCircle(const circle &C)
{
sfw::drawCircle(C.position.x, C.position.y, C.radius);
}
void drawAABB(const AABB & box, int color)
{
sfw::drawLine(box.position.x + box.extents.x, box.position.y + box.extents.y, box.position.x + box.extents.x, box.position.y - box.extents.y, color);
sfw::drawLine(box.position.x - box.extents.x, box.position.y - box.extents.y, box.position.x + box.extents.x, box.position.y - box.extents.y,color);
sfw::drawLine(box.position.x - box.extents.x, box.position.y + box.extents.y, box.position.x - box.extents.x, box.position.y - box.extents.y, color);
sfw::drawLine(box.position.x + box.extents.x, box.position.y + box.extents.y, box.position.x - box.extents.x, box.position.y + box.extents.y, color);
}
<file_sep>/x-sfwtest/controller.h
#pragma once
#include "transform.h"
#include "Rigidbody.h"
#include "sfwdraw.h"
//poll for input and apply to rigid body
class Controller
{
public:
float turningSpeed;
float speed;
float brakePower;
Controller() : turningSpeed(240), speed(500), brakePower(10)
{
}
void poll(Rigidbody &rb, const Transform &t)
{
if (sfw::getKey('W'))rb.force +=
norm(t.getGlobalTransform()[1].xy) * speed;
if (sfw::getKey('S'))rb.force -=
norm(t.getGlobalTransform()[1].xy) * speed;
if (sfw::getKey('A'))rb.force -=
norm(t.getGlobalTransform()[0].xy) * speed;
if (sfw::getKey('D'))rb.force +=
norm(t.getGlobalTransform()[0].xy) * speed;
if (sfw::getKey(' ')) //breaking force
{
rb.force += -rb.velocity * brakePower;
rb.torque += -rb.aVelocity * brakePower;
}
if (sfw::getKey('E'))rb.impulse;
}
};<file_sep>/x-sfwtest/player.cpp
#include "player.h"
#include "sfwdraw.h"
#include "cstdlib"
#include <cmath>
#include "vec2.h"
bool doCollision(Player & player, const Wall & wall)
{
auto hit = collides(player.transform, player.collider,
wall.transform, wall.collider
);
if (hit.pDepth > 0)
{
static_resolution(player.transform.position, player.rigidbody.velocity, hit,0.1);
std::cout << "is schmacko" << std::endl;
return true;
}
return false;
}
void doCollision(Player &player, Enemy & enemy)
{
Collision hit = collides(player.transform, player.collider,
enemy.transform, enemy.collider);
if (hit.pDepth >0)
{
dynamic_resolution(player.transform.position,
player.rigidbody.velocity,
player.rigidbody.mass,
enemy.transform.position,
enemy.rigidbody.velocity,
enemy.rigidbody.mass,
hit, 1.005);
}
}
//bool doCollision(Player & player, const Enemy & enemy)
//{
// auto hit = collides(player.transform, player.collider,
// enemy.transform, enemy.collider
// );
//
// if (hit.pDepth > 0)
// {
// static_resolution(player.transform.position, player.rigidbody.velocity, hit,1.0001);
// std::cout << "is schmacko" << std::endl;
// return true;
// }
// return false;
//}
bool doCollision(Enemy & enemy, const Wall & wall)
{
auto hit = collides(enemy.transform, enemy.collider,
wall.transform, wall.collider
);
if (hit.pDepth > 0)
{
static_resolution(enemy.transform.position, enemy.rigidbody.velocity, hit,1.1);
std::cout << "is schmacko" << std::endl;
return true;
}
return false;
}
void chasem(Enemy &enemy, Player &player)
{
vec2 pPos = { player.transform.position.x, player.transform.position.y };
vec2 ePos = { enemy.transform.position.x, enemy.transform.position.y };
vec2 VelocityDesx = dist(ePos,pPos) * norm(pPos-ePos);
enemy.rigidbody.force.x = (VelocityDesx.x - enemy.rigidbody.velocity.x) * 20;
enemy.rigidbody.force.y = (VelocityDesx.y - enemy.rigidbody.velocity.y) *20;
////Enemy needs to add force in a direction, whats the direction?
//vec2 ProjectedVelocityX = pPos + (norm(player.rigidbody.velocity) * (float)20);
//vec2 Dir = norm(ePos - pPos);
// enemy.rigidbody.force.x += (Dir * ProjectedVelocity);
}
<file_sep>/x-sfwtest/collision.cpp
#include "collision.h"
Collision intersect_1D(float Amin, float Amax, float bMin, float bMax)
{
Collision ret;
float lPD = bMax - Amin;
float rpd = Amax - bMin;
ret.pDepth = min(lPD, rpd);
ret.hand = copysign(1, rpd - lPD);
return ret;
}
Collision intersect_AABB(const AABB & A, const AABB & B)
{
Collision xres = intersect_1D(A.min().x, A.max().x, B.min().x, B.max().x);
Collision yres = intersect_1D(A.min().y, A.max().y, B.min().y, B.max().y);
xres.axis = vec2{ 1,0 };
yres.axis = vec2{ 0,1 };
return xres.pDepth < yres.pDepth ? xres : yres;
}
Collision intersect_circle(const circle & A, const circle & B)
{
Collision ret;
ret.axis = norm(B.position - A.position);
ret.hand = -1;
float ap = dot(ret.axis, A.position);
float bp = dot(ret.axis, B.position);
float Amin = ap - A.radius;
float Amax = ap + A.radius;
float Bmin = bp - B.radius;
float Bmax = bp + B.radius;
ret.pDepth = intersect_1D(Amin,Amax,Bmin,Bmax).pDepth;
return ret;
}
Collision intersect_AABB_Circle(const AABB & A, const circle & B)
{
return Collision();
}
void static_resolution(vec2 & pos, vec2 & vel, const Collision & hit, float elas)
{
pos += hit.axis * hit.hand * hit.pDepth;
vel = -reflect(vel, hit.axis*hit.hand)* elas;
}
void dynamic_resolution(vec2 &Apos, vec2 & Avel, float Amass,
vec2 & Bpos, vec2 & Bvel,float Bmass,
const Collision & hit, float elas)
{
// Law of Conservation
/*
mass*vel = momentum
AP + BP = `AP + `BP // Conservation of Momentum
Avel*Amass + Bvel*Bmass = fAvel*Amass + fBvel*Bmass
Avel - Bvel = -(fBvel - fAvel)
fBvel = Bvel - Avel + fAvel
///
Avel*Amass + = fAvel*Amass - Avel*Bmass + fAvel*Bmass
*/
vec2 normal = hit.axis * hit.hand;
vec2 Rvel = Avel - Bvel;
float j = // impulse
// the total energy applied across the normal
-(1 + elas)*dot(Rvel, normal) /
dot(normal, normal*(1 / Amass + 1 / Bmass));
Avel += (j / Amass) * normal;
Bvel -= (j / Bmass) * normal;
Apos += normal * hit.pDepth * Amass / (Amass + Bmass);
Bpos -= normal * hit.pDepth * Bmass / (Amass + Bmass);
}
<file_sep>/x-sfwtest/bot.h
#pragma once
#include "vec2.h"
class Bot
{
public:
vec2 pos;
float speed;
void update();
void Draw();
};<file_sep>/MeethLib/vec3.cpp
#include "vec3.h"
#include<cfloat>
#include <cmath>
vec3 operator+(const vec3 & lhs, const vec3 & rhs)
{
vec3 result;
result.x = lhs.x + rhs.x;
result.y = lhs.y + rhs.y;
result.z = lhs.z + rhs.z;
return result;
}
vec3 operator-(const vec3 & lhs, const vec3 & rhs)
{
vec3 result;
result.x = lhs.x - rhs.x;
result.y = lhs.y - rhs.y;
result.z = lhs.z - rhs.z;
return result;
}
vec3 operator*(const vec3 & lhs, float rhs)
{
vec3 result;
result.x = lhs.x * rhs;
result.y = lhs.y * rhs;
result.z = lhs.z * rhs;
return result;
}
vec3 operator*(float lhs, const vec3 & rhs)
{
return rhs * lhs;
}
vec3 operator/(const vec3 & lhs, float rhs)
{
vec3 result;
result.x = lhs.x / rhs;
result.y = lhs.y / rhs;
result.z = lhs.z / rhs;
return result;
}
vec3 operator-(const vec3 & lhs)
{
vec3 result;
result.x = lhs.x * -1;
result.y = lhs.y * -1;
result.z = lhs.z * -1;
return result;
}
vec3 operator+=(vec3 & lhs, const vec3 & rhs)
{
lhs = lhs + rhs;
return lhs;
}
vec3 & operator-=(vec3 & lhs, const vec3 & rhs)
{
lhs = lhs - rhs;
return lhs;
}
vec3 & operator*=(vec3 & lhs, float & rhs)
{
lhs = lhs * rhs;
return lhs;
}
vec3 & operator/=(vec3 & lhs, float & rhs)
{
lhs = lhs / rhs;
return lhs;
}
bool operator==(const vec3 & lhs, const vec3 & rhs)
{
if (abs(lhs.x - rhs.x) < FLT_EPSILON &&
abs(lhs.y - rhs.y) < FLT_EPSILON &&
abs(lhs.z - rhs.z) < FLT_EPSILON)
{
return true;
}
return false;
}
bool operator!=(const vec3 & lhs, const vec3 & rhs)
{
return !(lhs == rhs);
}
float mag(const vec3 & v)
{
float aSqr = v.x * v.x;
float bSqr = v.y * v.y;
float cSqr = v.z * v.z;
return sqrtf(aSqr + bSqr +cSqr);
}
vec3 norm(const vec3 & v)
{
vec3 temp = v;
float len = mag(v);
temp /= len;
return temp;
}
vec3 & normalize(vec3 & v)
{
v = norm(v);
return v;
}
float dot(const vec3 & a, const vec3 & b)
{
float x = a.x * b.x;
float y = a.y * b.y;
float z = a.z * b.z;
float sum = x + y + z;
return sum;
//return a.x * b.x + a.y * b.y + a.z * b.z;
}
float dist(const vec3 & a, const vec3 & b)
{
return mag(b - a);
}
vec3 min(const vec3 & a, const vec3 & b)
{
vec3 temp;
temp.x = fmin(a.x, b.x);
temp.y = fmin(a.y, b.y);
temp.z = fmin(a.z, b.z);
return temp;
}
vec3 max(const vec3 & a, const vec3 & b)
{
vec3 temp;
temp.x = fmax(a.x, b.x);
temp.y = fmax(a.y, b.y);
temp.y = fmax(a.z, b.z);
return temp;
}
vec3 clamp(const vec3 & a_min, const vec3 & v, const vec3 & a_max)
{
vec3 dummy = v;
//min {1,1,1};
//value {0,6,3};
//max {5,5,5};
dummy = min(dummy, a_max);
dummy = max(dummy, a_min);
return dummy;
}
float & vec3::operator[](unsigned idx)
{
return v[idx];
}
float vec3::operator[](unsigned idx) const
{
return v[idx];
}
// Vector perpendicular to two other vectors
// yz-zy, zx-xz, xy-yx
vec3 cross(const vec3 &a, const vec3 &b)
{
return vec3{ a.y*b.z - a.z*b.y,
a.z*b.x - a.x*b.z,
a.x*b.y - a.y*b.x };
}
| 418e3f30c97ee058b5f60bbe1bf96357e47200d1 | [
"C",
"C++"
] | 19 | C++ | opticalone/meeth | 263f48521a852b3e508100a109c71a70433df828 | 091d4a391e323d7a9876563d3fecd7cbecbba5cd |
refs/heads/master | <repo_name>Kirikou974/ModernWorkplaceConcierge<file_sep>/ModernWorkplaceConcierge/Controllers/IntuneController.cs
using Microsoft.Graph;
using ModernWorkplaceConcierge.Helpers;
using ModernWorkplaceConcierge.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace ModernWorkplaceConcierge.Controllers
{
[System.Web.Mvc.Authorize]
public class IntuneController : BaseController
{
public ActionResult Import()
{
return View();
}
[HttpPost]
public async System.Threading.Tasks.Task<ActionResult> Upload(HttpPostedFileBase[] files, OverwriteBehaviour overwriteBehaviour, string clientId)
{
SignalRMessage signalR = new SignalRMessage(clientId);
try
{
GraphIntuneImport graphIntuneImport = new GraphIntuneImport(clientId, overwriteBehaviour);
if (files.Length > 0 && files[0].FileName.Contains(".json"))
{
foreach (HttpPostedFileBase file in files)
{
try
{
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.ContentLength);
string result = Encoding.UTF8.GetString(binData);
await graphIntuneImport.AddIntuneConfig(result);
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
}
else if (files.Length > 0 && files[0].FileName.Contains(".zip"))
{
try
{
MemoryStream target = new MemoryStream();
files[0].InputStream.CopyTo(target);
byte[] data = target.ToArray();
using (var zippedStream = new MemoryStream(data))
{
using (var archive = new ZipArchive(zippedStream))
{
foreach (var entry in archive.Entries)
{
try
{
if (entry != null)
{
if (entry.FullName.Contains("WindowsAutopilotDeploymentProfile") || entry.FullName.Contains("DeviceConfiguration") || entry.FullName.Contains("DeviceCompliancePolicy") || entry.FullName.Contains("DeviceManagementScript") || entry.FullName.Contains("ManagedAppPolicy"))
{
using (var unzippedEntryStream = entry.Open())
{
using (var ms = new MemoryStream())
{
unzippedEntryStream.CopyTo(ms);
var unzippedArray = ms.ToArray();
string result = Encoding.UTF8.GetString(unzippedArray);
if (!string.IsNullOrEmpty(result))
{
await graphIntuneImport.AddIntuneConfig(result);
}
}
}
}
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
}
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
}
else if (files.Length > 0)
{
signalR.sendMessage("Error unsupported file: " + files[0].FileName);
}
}
catch (Exception e)
{
signalR.sendMessage("Error: " + e.Message);
}
signalR.sendMessage("Done#!");
return new HttpStatusCodeResult(204);
}
// GET: Export
public ActionResult Index()
{
return View();
}
public async System.Threading.Tasks.Task<ViewResult> DeviceManagementScripts()
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var scripts = await graphIntune.GetDeviceManagementScriptsAsync();
return View(scripts);
}
catch (Exception e)
{
Flash("Error getting DeviceManagementScripts" + e.Message.ToString());
return View();
}
}
public async System.Threading.Tasks.Task<ViewResult> Win32AppDetectionScripts()
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var apps = await graphIntune.GetWin32MobileAppsAsync();
List<Win32LobApp> win32LobApps = new List<Win32LobApp>();
foreach (Win32LobApp app in apps)
{
var details = await graphIntune.GetWin32MobileAppAsync(app.Id);
if (details.DetectionRules.Any(d => d is Win32LobAppPowerShellScriptDetection))
{
win32LobApps.Add(details);
}
}
return View(win32LobApps);
}
catch (Exception e)
{
Flash("Error " + e.Message.ToString());
return View();
}
}
public async System.Threading.Tasks.Task<PartialViewResult> Win32AppPsDetectionScriptContent(string Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var script = await graphIntune.GetWin32MobileAppPowerShellDetectionRuleAsync(Id);
string powerShellCode = Encoding.UTF8.GetString(Convert.FromBase64String(script.ScriptContent));
return PartialView("_PowerShellDetectionScriptContent", powerShellCode);
}
catch (Exception e)
{
Flash("Error getting DeviceManagementScripts" + e.Message.ToString());
return PartialView();
}
}
public async System.Threading.Tasks.Task<FileResult> DownloadDetectionScript(string Id)
{
GraphIntune graphIntune = new GraphIntune(null);
Win32LobApp win32LobApp = await graphIntune.GetWin32MobileAppAsync(Id);
Win32LobAppPowerShellScriptDetection script = await graphIntune.GetWin32MobileAppPowerShellDetectionRuleAsync(Id);
string fileName = $"{FilenameHelper.ProcessFileName(win32LobApp.DisplayName)}_detect.ps1";
return File(Convert.FromBase64String(script.ScriptContent), "text/plain", fileName);
}
public async System.Threading.Tasks.Task<PartialViewResult> PowerShellScriptContent(string Id)
{
try
{
GraphIntune graphIntune = new GraphIntune(null);
var scripts = await graphIntune.GetDeviceManagementScriptAsync(Id);
string powerShellCode = Encoding.UTF8.GetString(scripts.ScriptContent);
return PartialView("_PowerShellScriptContent", powerShellCode);
}
catch (Exception e)
{
Flash("Error getting DeviceManagementScripts" + e.Message.ToString());
return PartialView();
}
}
public async System.Threading.Tasks.Task<FileResult> DownloadDeviceManagementScript(String Id)
{
GraphIntune graphIntune = new GraphIntune(null);
DeviceManagementScript script = await graphIntune.GetDeviceManagementScriptAsync(Id);
return File(script.ScriptContent, "text/plain", script.FileName);
}
}
} | 9c5d8905476dc94385a7470a0b4d551aab722a73 | [
"C#"
] | 1 | C# | Kirikou974/ModernWorkplaceConcierge | 51c432faf33dd04986d6da8953ff63f2be92dbac | a99ea3a170921f44b067ee2b45277c1580c6af89 |
refs/heads/master | <repo_name>vladimirtsua/goit-js-hw-11-timer<file_sep>/src/js/timer.js
class CountdownTimer {
constructor({ selector, targetDate, name }) {
this.selector = selector;
this.targetDate = targetDate;
this.name = name;
this.currentDate;
this.deltaTime;
this.currentDate;
}
insertName() {
const titleTimer = document.querySelector(this.selector);
const text = document.createElement('p');
text.textContent = `До Дня Рождения ${this.name} осталось:`;
titleTimer.before(text);
this.getIdDate();
}
getIdDate() {
this.targetDate = new Date(this.targetDate).getTime();
this.getTimer();
}
getTimer() {
setInterval(() => {
this.currentDate = Date.now();
this.deltaTime = this.targetDate - this.currentDate;
this.timing(this.deltaTime);
}, 1000);
}
timing() {
const daysText = document.querySelector(
`${this.selector} [data-value="days"]`);
const hoursText = document.querySelector(
`${this.selector} [data-value="hours"]`,
);
const minsText = document.querySelector(
`${this.selector} [data-value="mins"]`,
);
const secsText = document.querySelector(
`${this.selector} [data-value="secs"]`,
);
const days = Math.floor(this.deltaTime / (1000 * 60 * 60 * 24));
daysText.textContent = `${days}`;
const hours = this.pad(
Math.floor((this.deltaTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
);
hoursText.textContent = `${hours}`;
const mins = this.pad(
Math.floor((this.deltaTime % (1000 * 60 * 60)) / (1000 * 60)),
);
minsText.textContent = `${mins}`;
const secs = this.pad(Math.floor((this.deltaTime % (1000 * 60)) / 1000));
secsText.textContent = `${secs}`;
}
pad(time) {
return String(time).padStart(2, '0');
}
}
const hbIvetta = new CountdownTimer({
selector: '#timer-1',
targetDate: new Date('Jan 24, 2022'),
name: 'Vladimir'
});
hbIvetta.insertName();
const hbEd = new CountdownTimer({
selector: '#timer-2',
targetDate: new Date('May 24, 2021'),
name: 'Ed'
})
hbEd.insertName()
const hbBo = new CountdownTimer({
selector: '#timer-3',
targetDate: new Date('Feb 21, 2021'),
name: 'Bo'
})
hbBo.insertName() | dc03115c5eadfc438ab4f65e80ea201b16a5f183 | [
"JavaScript"
] | 1 | JavaScript | vladimirtsua/goit-js-hw-11-timer | 054c252140c83af08c5a126292343b7df3467665 | abef4ef786c994e5b063619c37333cad31a58f75 |
refs/heads/master | <file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
<input type="number" name="arrayLen1" placeholder="Độ dài mảng 1"><br>
<input type="number" name="arrayLen2" placeholder="Độ dài mảng 2"><br>
<input type="submit" value="Printf">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$arrayLen1= $_POST['arrayLen1'];
$arrayLen2=$_POST['arrayLen2'];
$array1 =[];
$array2 = [];
$arraySum = [];
$arraySumLen = $arrayLen1 + $arrayLen2 ;
echo "Mang 1: ";
for($i=0;$i<$arrayLen1;$i++)
{
$array1[$i] = rand(0,100);
echo $array1[$i]." ";
}
echo "<br>";
echo "Mang 2: ";
for($i=0;$i<$arrayLen2;$i++)
{
$array2[$i] = rand(0,100);
echo $array2[$i]." ";
}
echo "<br>";
echo "Mang sau khi gop la: ";
for($i=0;$i<$arraySumLen;$i++)
{
if($i<$arrayLen1)
{
$arraySum[$i] = $array1[$i];
}
if($i>=$arrayLen1)
{
$arraySum[$i]=$array2[$i-$arrayLen1];
}
echo $arraySum[$i]." ";
}
}
?>
</body>
</html>
<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method = 'post'>
<input type="number" name="numberArray" placeholder="Nhập vào đô dài của mảng">
<input type="submit" value="Printf">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$numberArray = $_POST['numberArray'];
$array =[];
for($i=0;$i<$numberArray;$i++)
{
$array[$i] = rand(0,100);
}
foreach ($array as $value)
{
echo $value." ";
}
echo "<br>";
$min = $array[0];
for($i=0;$i<$numberArray;$i++)
{
if($min>=$array[$i])
{
$min = $array[$i];
}
}
echo $min;
}
?>
</body>
</html><file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
<input type="number" name="numSquare" placeholder="Độ dài cạnh hình vuông"><br>
<input type="submit" value="Printf">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$numSquare= $_POST['numSquare'];
$array =[];
$sumDiagonal =0;
for($i=0;$i<$numSquare;$i++)
{
$array[$i] = [];
for($j=0;$j<$numSquare;$j++)
{
$array[$i][$j] = rand(0,100);
echo $array[$i][$j]." ";
}
echo "<br>";
}
$max = $array[0][0];
for($i=0;$i<$numSquare;$i++)
{
for($j=0;$j<$numSquare;$j++)
{
if($i==$j)
{
$sumDiagonal += $array[$i][$j];
}
}
}
echo "Tong cac phan tu tren duong cheo la: ".$sumDiagonal;
}
?>
</body>
</html>
<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method="post">
<input type="number" name="numCol" placeholder="Số hàng của mảng"><br>
<input type="number" name="numRow" placeholder="Số cột của mảng"><br>
<input type="number" name="valueCol" placeholder="Vị trí Cột muốn tính"><br>
<input type="submit" value="Printf">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$numCol = $_POST['numCol'];
$numRow = $_POST['numRow'];
$valueCol = $_POST['valueCol'];
$sum = 0;
$array = [];
for ($i = 0; $i < $numRow; $i++) {
$array[$i] = [];
for ($j = 0; $j < $numCol; $j++) {
$array[$i][$j] = rand(0, 100);
echo $array[$i][$j] . " ";
}
echo "<br>";
}
for ($i = 0; $i < $numRow; $i++) {
$sum += $array[$i][$valueCol-1];
}
echo "<br>" . "Tong tai cot thu " . $valueCol . " cua mang la: " . $sum;
}
?>
</body>
</html>
<file_sep><!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<form method = 'post'>
<input type="number" name="numberArray" placeholder="Nhập vào đô dài của mảng">
<input type="number" name="numberCheck" placeholder="Nhập vào số kiểm tra">
<input type="submit" value="Printf">
</form>
<?php
if($_SERVER['REQUEST_METHOD']=='POST')
{
$numberArray = $_POST['numberArray'];
$numberCheck=$_POST['numberCheck'];
$array =[1,2,3,4,5,6,4,7,8,9];
$countArr =0;
$countNum =0;
// for($i=0;$i<$numberArray;$i++)
// {
// $array[$i] = rand(0,100);
// echo $array[$i]." ";
// }
echo "<br>";
checkNum($array,$numberCheck,$countNum);
if($countNum>0)
{
for($j=0;$j<$countNum;$j++)
{
for($i=0;$i < count($array)-1;$i++)
{
if($array[$i]== $numberCheck)
{
$temp = $array[$i+1];
$array[$i+1] = $array[$i];
$array[$i] = $temp;
}
}
// array_pop($array);
}
}
else
{
echo "Khong co so can check"."<br>";
}
foreach ($array as $value)
{
echo $value." ";
}
function checkNum($arr,$num,$count)
{
for($i=0;$i<count($arr);$i++)
{
if($arr[$i]==$num) $count++;
}
return $count;
}
}
?>
</body>
</html> | 277b7f31db3a865c7302b5d40841a5b9cbaf19c0 | [
"PHP"
] | 5 | PHP | quangbui205/Array-vs-Function-in-PHP | 08cb6a226d3f1d1841a4a4087a7c0c9e33f953e2 | cb0e910b18fc253e19dbf8b83d6ee4b6ae69107a |
refs/heads/master | <repo_name>Kaef/java-lessons<file_sep>/src/test/java/pl/kszafran/lessons/language/ObjectsAndReferences.java
package pl.kszafran.lessons.language;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static pl.kszafran.lessons.Utils.print;
/**
* @author <NAME>
*/
public class ObjectsAndReferences {
@Test
public void test() {
List<String> libraries = new ArrayList<>();
libraries.add("JUnit");
libraries.add("Mockito");
libraries.add("TestNG");
List<String> copy = libraries;
copy.add("PowerMock");
print(libraries); // ?
print(copy); // ?
}
}
<file_sep>/src/main/java/pl/kszafran/lessons/crawler/FileCreator.java
package pl.kszafran.lessons.crawler;
/**
* Created by Sergey on 13.05.2015.
*/
public class FileCreator {
}
<file_sep>/src/main/resources/notes.txt
RawTypes:
- use Collections.reverse()
ReferencesAndValues:
- return Color object
Lists:
- use ArrayList and/or for-each<file_sep>/src/test/java/pl/kszafran/lessons/language/ReferencesAndValues.java
package pl.kszafran.lessons.language;
import org.apache.commons.lang3.mutable.MutableInt;
import org.junit.Test;
import static pl.kszafran.lessons.Utils.print;
/**
* @author <NAME>
*/
public class ReferencesAndValues {
@Test
public void testPrimitives() {
int red = 0;
int green = 0;
int blue = 0;
getSomeColor(red, green, blue);
print(red, green, blue); // ?
}
public void getSomeColor(int red, int green, int blue) {
red = 100;
green = 120;
blue = 40;
}
@Test
public void testBoxed() {
Integer red = 0;
Integer green = 0;
Integer blue = 0;
getSomeColor(red, green, blue);
print(red, green, blue); // ?
}
public void getSomeColor(Integer red, Integer green, Integer blue) {
red = 100;
green = 120;
blue = 40;
}
@Test
public void testMutableInt() {
MutableInt red = new MutableInt(0);
MutableInt green = new MutableInt(0);
MutableInt blue = new MutableInt(0);
getSomeColor(red, green, blue);
print(red, green, blue); // ?
}
private void getSomeColor(MutableInt red, MutableInt green, MutableInt blue) {
red.setValue(100);
green.setValue(120);
blue.setValue(40);
}
}
<file_sep>/src/test/java/pl/kszafran/lessons/language/FloatingPointPrecision.java
package pl.kszafran.lessons.language;
import org.junit.Test;
import static pl.kszafran.lessons.Utils.print;
/**
* @author <NAME>
*/
public class FloatingPointPrecision {
@Test
public void addition1() throws Exception {
float sum = 0;
for (int i = 0; i < 100_000; i++) {
sum += 0.1;
}
print(sum); // ?
}
@Test
public void addition2() throws Exception {
float sum = 0;
for (int i = 0; i < 100_000; i++) {
sum += 0.5;
}
print(sum); // ?
}
}
<file_sep>/src/test/java/pl/kszafran/lessons/Utils.java
package pl.kszafran.lessons;
import static org.apache.commons.lang3.StringUtils.join;
/**
* @author <NAME>
*/
public class Utils {
public static void print(Object... values) {
System.out.println(join(values, " "));
}
private Utils() {
throw new AssertionError();
}
}
<file_sep>/src/test/java/pl/kszafran/lessons/language/StringConcatenation.java
package pl.kszafran.lessons.language;
import org.junit.Test;
import static pl.kszafran.lessons.Utils.print;
/**
* @author <NAME>
*/
public class StringConcatenation {
@Test
public void test() {
String output = "";
for (int i = 0; i < 1_000_000; i++) {
output += "a";
}
print(output);
}
}
<file_sep>/src/test/java/pl/kszafran/lessons/language/RawTypes.java
package pl.kszafran.lessons.language;
import org.junit.Test;
import java.util.ArrayList;
import java.util.List;
import static pl.kszafran.lessons.Utils.print;
/**
* @author <NAME>
*/
public class RawTypes {
@Test
public void test() {
List<String> names = new ArrayList<>();
names.add("Michael");
names.add("Thomas");
names.add("Anna");
names.add("Claire");
print(names);
reverse(names);
print(names);
for (String name : names) {
print(name);
}
}
private void reverse(List elements) {
for (int i = 0, size = elements.size(); i <= size / 2; i++) {
Object e1 = elements.get(i);
Object e2 = elements.get(size - 1 - i);
elements.set(size - 1 - i, e1);
elements.set(i, e2);
}
}
}
| ea56a0bc19c787592b284288e67658a961b2fc1f | [
"Java",
"Text"
] | 8 | Java | Kaef/java-lessons | 48efbc8eb1304d3f928c39e077bfd16333afcf2f | 914a139fbbf76a86df38abbeada0e0a3c7685356 |
refs/heads/develop | <repo_name>4711-Lab6/starter-caboose<file_sep>/readme.rst
###################################
Tutorial 5 Starter Webapp - Caboose
###################################
This is the starter webapp for CodeIgniter Tutorial #5.
Unlike an earlier version, this version is fully functional, just feature incomplete.
The project uses a "quotes" database, setup through quotes-setup.sql in the project root.
The homepage displays the most recently added quote, with drill-down to see a
specific quote in detail.
The Viewer controller displays all the quotes on file, by default.
Each mugshot links to a viewer/quote method call, to display that author's quote.
**************
Intended Usage
**************
Fork this project.
Clone it locally.
Enhance it per the tutorial
*****
Setup
*****
If you want to run this webapp locally, create a database (for instance
"quotes") and import the quotes-setup.sql into it.
Tailor application/config/database.php appropriately.
***************
Project Folders
***************
/application the obvious
/assets CSS, javascript & media
/data Author mugshot images
Assumed: CI system folder is in ../system3
*******
License
*******
Please see the `license
agreement <http://codeigniter.com/userguide3/license.html>`_
*********
Resources
*********
- `Informational website <https://codeigniter.com/>`_
- `Source code repo <https://github.com/bcit-ci/CodeIgniter/>`_
- `User Guide <https://codeigniter.com/userguide3/>`_
- `Community Forums <https://forum.codeigniter.com/>`_
- `Community Wiki <https://github.com/bcit-ci/CodeIgniter/wiki/>`_
- `Community IRC <https://codeigniter.com/irc>`_
***************
Acknowledgement
***************
This webapp was written by <NAME>, Instructor in Computer Systems
Technology at the British Columbia Institute of Technology,
and Project Lead for CodeIgniter.
CodeIgniter is a project of B.C.I.T.<file_sep>/application/models/Quotes.php
<?php
/**
* This is a "CMS" model for quotes, but with bogus hard-coded data.
* This would be considered a "mock database" model.
*
* @author jim
*/
class Quotes extends MY_Model {
// Constructor
public function __construct()
{
parent::__construct('quotes', 'id');
}
// retrieve the most recently added quote
function last()
{
$key = $this->highest();
return $this->get($key);
}
}
<file_sep>/application/views/_components/jrating.php
$('.{field}').jRating({
rateMax : 5,
phpPath : '/viewer/rate'
});
<file_sep>/quotes-setup.sql
-- phpMyAdmin SQL Dump
-- version 4.1.7
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generation Time: Feb 10, 2015 at 05:54 AM
-- Server version: 5.6.21
-- PHP Version: 5.6.3
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- Database: `contacts`
--
-- --------------------------------------------------------
--
-- Table structure for table `quotes`
--
DROP TABLE IF EXISTS `quotes`;
CREATE TABLE IF NOT EXISTS `quotes` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`who` varchar(64) NOT NULL,
`mug` varchar(64) NOT NULL,
`what` text NOT NULL,
`vote_total` int(11) NOT NULL,
`vote_count` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
INSERT INTO `quotes` (`id`, `who`, `mug`, `what`) VALUES
(1, '<NAME>', 'bob-monkhouse-150x150.jpg', 'When I die, I want to go peacefully like my grandfather did–in his sleep. Not yelling and screaming like the passengers in his car.'),
(2, '<NAME>', 'elayne-boosler-150x150.jpg', 'I have six locks on my door all in a row. When I go out, I lock every other one. I figure no matter how long somebody stands there picking the locks, they are always locking three.'),
(3, '<NAME>', 'bob-monkhouse-150x150.jpg', 'The scientific theory I like best is that the rings of Saturn are composed entirely of lost airline luggage.'),
(4, 'Anonymous', 'Anonymous-150x150.jpg', 'How do you get a sweet little 80-year-old lady to say the F word? Get another sweet little 80-year-old lady to yell “BINGO!”'),
(5, 'Socrates', 'socrates-150x150.jpg', 'By all means, marry. If you get a good wife, you’ll become happy; if you get a bad one, you’ll become a philosopher.'),
(6, '<NAME>', 'isaac-asimov-150x150.jpg', 'Those people who think they know everything are a great annoyance to those of us who do.');
/*!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 */;
| d09d092f538fbe90229a14fce5b2beb65588fb0f | [
"SQL",
"PHP",
"reStructuredText"
] | 4 | reStructuredText | 4711-Lab6/starter-caboose | 0416a70a6480fa7cd285a9d828eceacb6d048e66 | ccd9ca5ed024d66298adc8cba29c89e665277612 |
refs/heads/master | <file_sep>import { computedFrom, bindable } from 'aurelia-framework';
import { BookModel } from './../../models/book-model';
export class BookStats {
@bindable books: BookModel[];
@bindable originalNumberOfBooks: number;
@computedFrom('originalNumberOfBooks', 'books.length')
get addedBooks() {
return this.books.length - this.originalNumberOfBooks;
}
}
<file_sep>import { bindable, inject, computedFrom, DOM } from 'aurelia-framework';
import { EventAggregator, Subscription } from 'aurelia-event-aggregator';
import * as _ from 'lodash';
import { BookModel } from './../../models/book-model';
import { StarRating } from './star-rating';
@inject(EventAggregator)
export class EditBook {
@bindable editMode: boolean;
@bindable book: BookModel;
private bookSaveCompleteSubscription: Subscription;
private loading: boolean = false;
private saved: boolean = false;
temporaryBook: BookModel;
private ratingChangedListener;
private ratingElement: Element;
private starRatingViewModel: StarRating;
constructor(private eventAggregator: EventAggregator) {
this.resetTempBook();
this.ratingChangedListener = e => this.temporaryBook.rating = e.rating;
}
attached() {
this.bookSaveCompleteSubscription = this.eventAggregator.subscribe(`book-save-complete-${this.book.id}`, () => this.bookSaveComplete());
}
bind() {
this.resetTempBook();
this.ratingElement.addEventListener('change', this.ratingChangedListener);
}
detached() {
this.bookSaveCompleteSubscription.dispose();
this.ratingElement.removeEventListener('change', this.ratingChangedListener);
}
editModeChanged(editModeNew, editModeOld) {
if (editModeNew) {
this.resetTempBook();
}
}
@computedFrom('temporaryBook.title', 'temporaryBook.description', 'temporaryBook.rating')
get canSave() {
return this.temporaryBook && !_.isEqual(this.temporaryBook, this.book);
}
private resetTempBook(): void {
if (this.book) {
this.temporaryBook = Object.assign({}, this.book);
}
}
cancel(): void {
this.temporaryBook = this.book;
this.starRatingViewModel.applyRating(this.temporaryBook.rating);
this.toggleEditMode();
}
save(): void {
this.loading = true;
this.publishBookSavedEvent();
}
bookSaveComplete() {
this.loading = false;
this.saved = true;
setTimeout(() => {
this.resetTempBook();
this.saved = false;
this.toggleEditMode();
}, 500);
}
publishBookSavedEvent() {
this.eventAggregator.publish('save-book', this.temporaryBook);
}
private toggleEditMode(): void {
this.eventAggregator.publish('edit-mode-changed', !this.editMode);
}
}
<file_sep>export class BookModel {
id?: number;
title: string;
description?: string;
rating?: number;
status?: string;
readDate?: Date;
read?: boolean;
}
<file_sep># MyBooks
This project is the my-books application discussed in the book:
Aurelia in Action
By <NAME>
Manning Early Access Program, Version 7
www.manning.com
<file_sep>import { Router, RouterConfiguration } from 'aurelia-router';
import 'bootstrap';
export class App {
router: Router;
configureRouter(config: RouterConfiguration, router: Router) {
this.router = router;
config.title = 'my-books';
config.map([
{ route: ['', 'home'], name: 'home', moduleId: 'index' },
{ route: 'books', name: 'books', moduleId: './resources/elements/books' }
]);
}
}
<file_sep>export class BookStatusValueConverter {
toView(value: string): string {
switch(value) {
case 'bad':
return 'fa-frown-o';
case 'good':
return 'fa-smile-o';
case 'ok':
return 'fa-meh-o';
}
}
}
<file_sep>import { bindable } from 'aurelia-framework';
import { inject } from 'aurelia-dependency-injection';
import * as $ from 'jquery';
@inject(Element)
export class TooltipCustomAttribute {
@bindable title: string;
@bindable placement: string;
constructor(private element: Element) {}
attached() {
$(this.element).tooltip({
title: this.title,
placement: this.placement
});
}
detached() {
$(this.element).tooltip('dispose');
}
}
<file_sep>import { inject } from 'aurelia-dependency-injection';
import { HttpClient } from 'aurelia-fetch-client';
import { BookModel } from '../models/book-model';
@inject(HttpClient)
export class BookApi {
constructor(private http: HttpClient) {}
getBooks(): Promise<BookModel[]> {
return this.http.fetch('books.json')
.then(response => response.json())
.then(books => {
return books;
});
}
saveBook(book: BookModel): Promise<BookModel> {
return new Promise(resolve => {
setTimeout(() => {
resolve(book);
}, 1000);
});
}
}
<file_sep>import { bindable, inject } from 'aurelia-framework';
import { EventAggregator } from 'aurelia-event-aggregator';
import { BookModel } from '../../models/book-model';
@inject(EventAggregator)
export class BookList {
@bindable books: BookModel[];
constructor(private eventAggregator: EventAggregator) { }
removeBook(index: number): void {
this.eventAggregator.publish('book-removed', index);
}
}
<file_sep>import { bindable, inject, computedFrom, observable } from 'aurelia-framework';
import { EventAggregator, Subscription } from 'aurelia-event-aggregator';
import * as _ from 'lodash';
import { BookApi } from '../../services/book-api';
import { BookModel } from '../../models/book-model';
@inject(BookApi, EventAggregator)
export class Books {
books: BookModel[];
private bookRemovedSubscription: Subscription;
private bookSavedSubscription: Subscription;
constructor(private bookApi: BookApi, private eventAggregator: EventAggregator) {
this.books = [];
}
attached() {
this.subscribeToEvents();
}
bind() {
this.bookApi.getBooks().then(savedBooks => this.books = savedBooks);
}
detached() {
this.bookRemovedSubscription.dispose();
this.bookSavedSubscription.dispose();
}
// addBook(): void {
// this.books.push({title: this.bookTitle});
// this.bookTitle = '';
// // console.log('Book List:');
// // this.books.forEach(book => {
// // console.log(`${book.title}`);
// // });
// }
removeBook(toRemove: BookModel): void {
let bookIndex = _.findIndex(this.books, book => {
return book.id === toRemove.id
});
this.books.splice(bookIndex, 1);
}
subscribeToEvents(): void {
this.bookRemovedSubscription = this.eventAggregator.subscribe('book-removed', bookIndex => this.removeBook(bookIndex));
this.bookSavedSubscription = this.eventAggregator.subscribe('save-book', book => this.bookSaved(book));
}
bookSaved(updatedBook: BookModel) {
this.bookApi
.saveBook(updatedBook)
.then((savedBook) => {
this.eventAggregator.publish(`book-save-complete-${savedBook.id}`);
})
}
bookTitleChanged(newValue, oldValue) {
console.log(`Book title changed, Old Value: ${oldValue}, New Value: ${newValue}`)
}
// @computedFrom('bookTitle.length')
// get canAdd() {
// return this.bookTitle.length === 0;
// }
}
<file_sep>export class StarModel {
type: string;
displayType: string;
rated: boolean;
}
<file_sep>import { bindable, inject } from 'aurelia-framework';
import { EventAggregator, Subscription } from 'aurelia-event-aggregator';
import { BookModel } from './../../models/book-model';
@inject(EventAggregator)
export class Book {
@bindable book: BookModel;
@bindable searchTerm: string;
editMode: boolean;
editModeChangedSubscription: Subscription;
constructor(private eventAggregator: EventAggregator) {
this.editMode = false;
}
bind() {
this.subscribeToEvents();
}
unbind() {
this.editModeChangedSubscription.dispose();
}
markRead(): void {
this.book.readDate = new Date();
this.book.read = true;
}
removeBook(): void {
this.eventAggregator.publish('book-removed', this.book);
}
subscribeToEvents(): void {
this.editModeChangedSubscription = this.eventAggregator.subscribe('edit-mode-changed', mode => {
this.editMode = mode;
});
}
toggleEditMode(event): void {
this.editMode = !this.editMode;
}
}
<file_sep>import { BookModel } from './../../models/book-model';
export class FilterValueConverter {
toView(array: BookModel[], searchTerm: string): BookModel[] {
return array.filter((item) => {
return searchTerm && searchTerm.length > 0 ? this.itemMatches(searchTerm, item) : true;
});
}
itemMatches(searchTerm: string, value: BookModel): boolean {
let itemValue = value.title;
if (!itemValue) {
return false;
}
return itemValue.toUpperCase().indexOf(searchTerm.toUpperCase()) !== -1;
}
}
<file_sep>import { inject, bindable, DOM } from 'aurelia-framework';
import { StarModel } from './../../models/star-model';
@inject(Element)
export class StarRating {
@bindable rating: number;
stars: StarModel[];
private hovered: boolean;
constructor(private element: Element) {
this.stars = [
{ type: '-o', displayType: '-o', rated: false },
{ type: '-o', displayType: '-o', rated: false },
{ type: '-o', displayType: '-o', rated: false },
{ type: '-o', displayType: '-o', rated: false },
{ type: '-o', displayType: '-o', rated: false }
];
this.hovered = false;
}
bind()
{
this.applyRating(this.rating);
}
applyRating(rating: number): void {
this.stars.forEach((star, index) => this.rateStar(star, rating, index));
}
private rateStar(star: StarModel, rating: number, index: number): void {
if (index < rating) {
this.toggleOn(star);
} else {
this.toggleOff(star);
}
}
private toggleOn(star: StarModel): void {
star.displayType = '';
star.type = '';
star.rated = true;
}
private toggleOff(star: StarModel): void {
star.displayType = '-o';
star.type = '-o';
star.rated = false;
}
private ratingFromIndex(index: number, star: StarModel): number {
return (index === 0 && star.rated) ? 0 : index + 1;
}
rate(index: number): void {
let rating = this.ratingFromIndex(index, this.stars[0]);
this.rating = rating;
this.applyRating(rating);
this.raiseChangedEvent();
}
mouseOut(hoverIndex: number) {
if (!this.hovered) {
return;
}
this.hovered = false;
this.applyHoverState(hoverIndex);
}
private applyHoverState(hoverIndex: number): void {
this.stars.forEach((star, index) => {
if (!this.shouldApplyHover(index, hoverIndex, star)) {
return;
}
if (this.hovered) {
this.toggleDisplayOn(star);
} else {
this.toggleDisplayOff(star);
}
});
}
mouseOver(hoverIndex) {
if (this.hovered) {
return;
}
this.hovered = true;
this.applyHoverState(hoverIndex);
}
private toggleDisplayOff(star: StarModel): void {
star.displayType = star.type;
}
private toggleDisplayOn(star: StarModel): void {
star.displayType = '';
}
private shouldApplyHover(starIndex: number, hoverIndex: number, star: StarModel): boolean {
return starIndex <= hoverIndex && !star.rated;
}
private raiseChangedEvent(): void {
let changeEvent = DOM.createCustomEvent('change', {
detail: {
rating: this.rating
}
});
this.element.dispatchEvent(changeEvent);
}
}
<file_sep>import * as moment from 'moment';
export class DateFormatValueConverter {
toView(value): string {
if (!value) {
return '';
}
return moment(value).format('MM/DD/YYYY h:mm:ss a');
}
}
| 056461434eee54b2a208631f296899ea3e132331 | [
"Markdown",
"TypeScript"
] | 15 | TypeScript | johnolivieri/Aurelia | c760232dccd33eeafabd66c3565131293e674ccf | 0fcdf36ce1749b6174a98c500d89bc9492781df6 |
refs/heads/master | <repo_name>divyansshhh/Daemon-Labs-Webpage<file_sep>/js/script.js
(function($) {
"use strict"; // Start of use strict
// Smooth scrolling using jQuery easing
$('a.js-scroll-trigger[href*="#"]:not([href="#"])').click(function() {
if (location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - 48)
}, 1000, "easeInOutExpo");
return false;
}
}
});
// Closes responsive menu when a scroll trigger link is clicked
$('.js-scroll-trigger').click(function() {
$('.navbar-collapse').collapse('hide');
});
// Activate scrollspy to add active class to navbar items on scroll
$('body').scrollspy({
target: '#mainNav',
offset: 54
});
// Collapse the navbar when page is scrolled
$(window).scroll(function() {
if ($("#mainNav").offset().top > 100) {
$("#mainNav").addClass("navbar-shrink");
} else {
$("#mainNav").removeClass("navbar-shrink");
}
});
// Floating label headings for the contact form
$(function() {
$("body").on("input propertychange", ".floating-label-form-group", function(e) {
$(this).toggleClass("floating-label-form-group-with-value", !!$(e.target).val());
}).on("focus", ".floating-label-form-group", function() {
$(this).addClass("floating-label-form-group-with-focus");
}).on("blur", ".floating-label-form-group", function() {
$(this).removeClass("floating-label-form-group-with-focus");
});
});
})(jQuery); // End of use strict
$(".hover").mouseleave(
function () {
$(this).removeClass("hover");
}
);
var Header = new Vue({
el: 'header',
data: {
title: 'The Programming club',
subtitle: 'Indian Institute of Technology, Indore'
}
});
HomePageItems = [
{
image: 'img/project/game1.png',
imagealt: 'game1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Infinite Runner',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/sreevatsank1999/Project_M',
date: '21st july 2017',
domain: 'Game Development',
},
{
image: 'img/project/web1.svg',
imagealt: 'web1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Q and A forum',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/Mohit-Nathrani/question-answer-site',
date: '21st july 2017',
domain: 'Full Stack Development',
},
{
image: 'img/project/software1.svg',
imagealt: 'software1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Rave Media Player',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/kanishkarj/rave',
date: '21st july 2017',
domain: 'Software Development',
},
];
Headmembers = [
{
image:"img/members/vineetshah.jpe",
imagealt:"vineetshah",
name:"<NAME>",
link:"#"
},
{
image:"img/members/mohitmohta.jpg",
imagealt:"mohitmohta",
name:"<NAME>",
link:"#"
},
{
image:"img/members/kunalgupta.jpeg",
imagealt:"kunalgupta",
name:"<NAME>",
link:"#"
},
{
image:"img/members/adityajain.jpe",
imagealt:"adityajain",
name:"<NAME>",
link:"#"
},
{
image:"img/members/kunalgupta.jpeg",
imagealt:"kunalgupta",
name:"<NAME>",
link:"#"
},
];
WeeklyChallenges=[
{
date:"11th sept 2017",
items:[
{
title:"Lorem Ipsum",
subtitle:"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.",
author:"Lipsum",
modalhref: '#weeklychalModal1',
modalhreftitle: 'weeklychalModal1',
content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum arcu ut justo pulvinar, at placerat tortor rutrum. Pellentesque sodales est id orci elementum bibendum. In hac habitasse platea dictumst. In sagittis ut dolor a ornare. Vivamus feugiat imperdiet lorem ac lobortis. Donec mattis orci augue, accumsan pretium metus sagittis at. Phasellus mattis sagittis aliquam. Duis justo sem, semper in leo vel, gravida ullamcorper nulla. Morbi nisi orci, eleifend id sapien vehicula, venenatis ornare urna. ",
},
{
title:"Lorem Ipsum",
subtitle:"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.",
author:"Lipsum",
modalhref: '#weeklychalModal2',
modalhreftitle: 'weeklychalModal2',
content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum arcu ut justo pulvinar, at placerat tortor rutrum. Pellentesque sodales est id orci elementum bibendum. In hac habitasse platea dictumst. In sagittis ut dolor a ornare. Vivamus feugiat imperdiet lorem ac lobortis. Donec mattis orci augue, accumsan pretium metus sagittis at. Phasellus mattis sagittis aliquam. Duis justo sem, semper in leo vel, gravida ullamcorper nulla. Morbi nisi orci, eleifend id sapien vehicula, venenatis ornare urna. ",
},
]
},
{
date:"10th sept 2017",
items:[
{
title:"Lorem Ipsum",
subtitle:"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.",
author:"Lipsum",
modalhref: '#weeklychalModal1',
modalhreftitle: 'weeklychalModal1',
content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum arcu ut justo pulvinar, at placerat tortor rutrum. Pellentesque sodales est id orci elementum bibendum. In hac habitasse platea dictumst. In sagittis ut dolor a ornare. Vivamus feugiat imperdiet lorem ac lobortis. Donec mattis orci augue, accumsan pretium metus sagittis at. Phasellus mattis sagittis aliquam. Duis justo sem, semper in leo vel, gravida ullamcorper nulla. Morbi nisi orci, eleifend id sapien vehicula, venenatis ornare urna. ",
},
{
title:"Lorem Ipsum",
subtitle:"Neque porro quisquam est qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit.",
author:"Lipsum",
modalhref: '#weeklychalModal2',
modalhreftitle: 'weeklychalModal2',
content:"Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vestibulum arcu ut justo pulvinar, at placerat tortor rutrum. Pellentesque sodales est id orci elementum bibendum. In hac habitasse platea dictumst. In sagittis ut dolor a ornare. Vivamus feugiat imperdiet lorem ac lobortis. Donec mattis orci augue, accumsan pretium metus sagittis at. Phasellus mattis sagittis aliquam. Duis justo sem, semper in leo vel, gravida ullamcorper nulla. Morbi nisi orci, eleifend id sapien vehicula, venenatis ornare urna. ",
},
]
},
]
members = [
{
image:"img/members/vineetshah.jpe",
imagealt:"vineetshah",
name:"<NAME>",
domain:"Competitive Coding",
desig:"BTech 3nd Year",
link:"#"
},
{
image:"img/members/mohitmohta.jpg",
imagealt:"mohitmohta",
name:"<NAME>",
domain:"Software Development",
desig:"BTech 3nd Year",
link:"#"
},
{
image:"img/members/kunalgupta.jpeg",
imagealt:"kunalgupta",
name:"<NAME>",
domain:"Web Security",
desig:"BTech 3nd Year",
link:"#"
},
{
image:"img/members/adityajain.jpe",
imagealt:"adityajain",
name:"<NAME>",
domain:"Machine Learning",
desig:"BTech 3nd Year",
link:"#"
},
{
image:"img/members/kanishkarj.jpe",
imagealt:"kanishkarj",
name:"<NAME>",
domain:"Full Stack Development",
desig:"BTech 2nd Year",
link:"https://github.com/kanishkarj",
},
];
ProjectPageItems = [
{
image: 'img/project/game1.png',
imagealt: 'game1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Infinite Runner',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/sreevatsank1999/Project_M',
date: '21st july 2017',
domain: 'Game Development',
},
{
image: 'img/project/web1.svg',
imagealt: 'web1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Q and A forum',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/Mohit-Nathrani/question-answer-site',
date: '21st july 2017',
domain: 'Full Stack Development',
},
{
image: 'img/project/software1.svg',
imagealt: 'software1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Rave Media Player',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/kanishkarj/rave',
date: '21st july 2017',
domain: 'Software Development',
},
{
image: 'img/project/web2.svg',
imagealt: 'web1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Local Quora',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/Harsh860/IITI-SOC',
date: '21st july 2017',
domain: 'Full Stack Development',
},
{
image: 'img/project/web3.svg',
imagealt: 'web1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Query',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/kpranav1998/soc-project',
date: '21st july 2017',
domain: 'Full Stack Development',
},
{
image: 'img/project/software2.svg',
imagealt: 'Software2',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Javafx Media Player',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/eltoro007/MediaPlayer',
date: '21st july 2017',
domain: 'Software Development',
},
{
image: 'img/project/ml1.svg',
imagealt: 'ml1',
modalhref: '#projectModal1',
modalhreftitle: 'projectModal1',
title: 'Computer learns to play mario.',
content: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse rutrum convallis felis, id ultrices ipsum egestas et. Vestibulum eu consequat est. Pellentesque ultrices varius vestibulum. Ut eget massa nisi. Vestibulum augue enim, imperdiet rutrum libero a, feugiat tristique velit. Aliquam sollicitudin sit amet neque et aliquam. Aliquam vestibulum orci in elit lacinia, a suscipit libero euismod.',
github: 'https://github.com/Mohit-Nathrani/question-answer-site',
date: '21st july 2017',
domain: 'Machine Learning',
},
];
var About = new Vue({
el: '#about',
data: {
header: 'About',
members: Headmembers
}
})
var AboutList = new Vue({
el: '#aboutlist',
data: {
header: 'About',
members: members
}
})
var Project = new Vue({
el: '#project',
data: {
items:HomePageItems
}
})
var ProjectModal = new Vue({
el: '#projectmodal',
data: {
items:HomePageItems
}
})
var ProjectPP = new Vue({
el: '#projectPP',
data: {
items:ProjectPageItems
}
})
var ProjectModalPP = new Vue({
el: '#projectmodalPP',
data: {
items:ProjectPageItems
}
})
var weeklychal = new Vue({
el: '#weeklychal',
data: {
items:WeeklyChallenges[1].items
}
})
var weeklychalmodal = new Vue({
el: '#weeklychalmodal',
data: {
items:WeeklyChallenges[1].items
}
})
var weeklychalWCP = new Vue({
el: '#weeklychalWCP',
data: {
items:WeeklyChallenges
}
})
var weeklychalmodalWCP = new Vue({
el: '#weeklychalmodalWCP',
data: {
items:WeeklyChallenges[1].items
}
})
var Footer = new Vue({
el: 'footer',
data: {
location: 'Indian Institute of Technology <br> Indore',
copyright: 'Copyright © Daemon Labs 2017',
items: [
{
link: 'https://www.facebook.com/groups/485116264850626/',
icon: 'fa fa-fw fa-facebook'
},
{
link: 'mailto:<EMAIL>',
icon: 'fa fa-fw fa-envelope'
},
{
link: 'https://github.com/DaemonLab',
icon: 'fa fa-fw fa-github'
},
]
}
}) | 18686d5797180985b879d66f56863d5b68c9cb8f | [
"JavaScript"
] | 1 | JavaScript | divyansshhh/Daemon-Labs-Webpage | 752055e0d5bc045308ba4d0a61e129710a53cb67 | c06ad3bda28323a085c2585060f738c60862cc98 |
refs/heads/master | <file_sep>const email = document.getElementById("email");
const asunto = document.getElementById("asunto");
const mensaje = document.getElementById("mensaje");
const btnEnviar = document.getElementById("enviar");
const formulario = document.getElementById('enviar-mail')
const btnReset = document.getElementById('resetBtn')
// event Listener
evenListeners();
function evenListeners() {
// deshabilita boton enviar
document.addEventListener("DOMContentLoaded", inicioApp);
// campos
email.addEventListener("blur", validarCampo);
asunto.addEventListener("blur", validarCampo);
mensaje.addEventListener("blur", validarCampo);
// boton enviar
btnEnviar.addEventListener('click',enviarEmail)
// boton reset
btnReset.addEventListener('click',botonReset)
}
// functions
function inicioApp() {
// anula el envio
btnEnviar.disabled = true;
}
// valida campo
function validarCampo() {
let errores = document.querySelectorAll(".error");
// longitud y vacio
validarLongitud(this);
// validar email
if(this.type === 'email'){
validarEmail(this)
}
if (email.value !== "" && asunto.value !== "" && mensaje.value !== "") {
if (errores.length === 0) {
btnEnviar.disabled = false;
}
}
}
// enviar
function enviarEmail(e){
e.preventDefault()
const spinnerGif = document.querySelector('#spinner')
spinnerGif.style.display='block'
const enviado = document.createElement('img')
enviado.src='img/mail.gif'
enviado.style.display = 'block'
// oculta loader
setTimeout(function(){
spinnerGif.style.display='none'
document.querySelector('#loaders').appendChild(enviado)
setTimeout(function(){
enviado.remove()
formulario.reset()
},5000)
}, 3000)
}
function botonReset(e){
formulario.reset()
e.preventDefault()
}
function validarLongitud(campo) {
if (campo.value.length > 0) {
campo.style.borderBottomColor = "green";
campo.classList.remove("error");
} else {
campo.style.borderBottomColor = "red";
campo.classList.add("error");
}
}
function validarEmail(campo){
let campoArroa= campo.value
if (campoArroa.indexOf('@gmail.com') !== -1 ||campoArroa.indexOf('@live.com') !== -1){
campo.style.borderBottomColor = "green";
campo.classList.remove("error");
}else{
campo.style.borderBottomColor = "red";
campo.classList.add("error");
}
}
<file_sep># Form- Vanilla JS
### URL:https://form-js.now.sh/
<img src="Screenshot_2020-06-07 Enviar mail.png" alt="">
| bce2b0f10d91b89d17cf8ec8498672cb59b9c7a0 | [
"JavaScript",
"Markdown"
] | 2 | JavaScript | mrneurus/form-js | c52629d16686fd6e2417b862ca458482bdf46b1d | 6e38975439dd1d8fcce49d719c742189a4c41dc5 |
refs/heads/master | <file_sep>/**
* Simple utility class to read/write and other ops for fileSystem while making them promise based.
*/
import * as fs from 'fs'
/**
* Function to promise base write a file to disk
* Enconding defaults to 'utf8'
* @param param0
*/
export const WriteToFile = ({ fileName, content, enconding = 'utf8' }: { fileName: string, content: string, enconding?: string }): Promise<boolean> => {
return new Promise((resolve, reject) => {
fs.writeFile(fileName, content, enconding, (error) => {
error ? reject(error) : resolve(true)
})
})
}
/**
* Function to promised base read a file from disk
* @param param0
*/
export const ReadFromFile = ({ fileName }: { fileName: string }): Promise<string> => {
return new Promise( (resolve, reject) => {
fs.readFile(fileName, 'utf8', (error, contents) => {
error ? reject(error) : resolve(contents.toString())
})
})
}
/**
* Function read a file from disk, just to avoid importing 'fs' and just reuse this module
* @param param0
*/
export const ReadFromFileAsync = ({fileName}): any => {
return fs.readFileSync(fileName, 'utf8');
}
<file_sep>import { Page } from "puppeteer";
import { Selectors } from '../_constans'
import _getXPath from '../_getXPath'
/**
* Finding and clicking the converstation div from the left side converstaion listing.
* 1. Navigate and find the conversation container containing a title with text equal to the target.
* 2. Generate its XPath.
* 3. Click it.
* Error out if
* - no matching conversation.
* - Found conversation but could not generate XPath (should not happen)
* - Generated XPath but puppeeter could not find element using it (should not happen)
* @param page
* @param targetString
*/
export default async function clickConversarion (page: Page, targetString: string): Promise<boolean> {
const containerSelector = Selectors.CONVERSATIONS_PARENT_CLASS
const placeholderElementSelector = Selectors.CONVERSATION_PLACEHOLDER_ELEMENT
const messageResultSelector = Selectors.CONVERSATION_MESSAGE_RESULTS_ELEMENT
const titleSelector = Selectors.CONVERSATION_TARGET_ELEMENT
const targetXPath = await page.evaluate((containerSelector, placeholderElementSelector, messageResultSelector, titleSelector, targetString) => {
const _getXPath = (element) => {
const idx = (sib, name) => sib ? idx(sib.previousElementSibling, name || sib.localName) + (sib.localName == name) : 1;
const segs = elm => !elm || elm.nodeType !== 1 ? [''] : elm.id && document.querySelector(`#${elm.id}`) === elm ? [`id("${elm.id}")`] : [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm, undefined)}]`];
return segs(element).join('/');
}
const sanityze = (value) => {
// Remove spaces and lowerCase the string
return value.replace(/ /g, '').toLowerCase()
}
let xPath = ''
targetString = sanityze(targetString)
const container = document.querySelector(containerSelector)
for(let element of container.children) {
// This eliminates placeholders 'CHATS' and 'MESSAGES' elements
if(element.querySelector(placeholderElementSelector) !== null) continue
// This eliminates 'MESSAGES' search results
if(element.querySelector(messageResultSelector) !== null) continue
// We are left with results for chat elements
const titleSpanElement = element.querySelector(titleSelector)
if (!titleSpanElement) continue
const checkAgaints = sanityze(titleSpanElement.innerText)
if (checkAgaints === targetString) {
// Remember our target element is the child of the conversarion container
// not the span element with the conversation target
xPath = _getXPath(element)
return Promise.resolve(xPath)
}
}
// Return empty xPath since no element matched the target
return Promise.resolve(xPath)
}, containerSelector, placeholderElementSelector, messageResultSelector, titleSelector, targetString)
// Error out if XPath is empty
if (targetXPath === '') {
throw new Error('Could not find target element')
}
// Find and click element with retrieved XPath
const targetElement: any = await page.$x(targetXPath)
if (targetElement.length > 0) {
await targetElement[0].click()
return true
} else {
throw new Error('Found target element but xPath is invalid.')
}
}
<file_sep>import * as puppeteer from 'puppeteer'
interface BrowserOptions {
headless: boolean
devTools: boolean
}
/**
* A Class to wrapp the puppeeter instance so we can abstract it on WhatsAppJS class.
* Note that we don't wrap the page.evaluate and other page methods used in the utils/PageFunctions.
* They are case specific and very simple to be worth abstracting them here. Those functions
* receive the .page pointer and operate directly over it.
* Two paths apply:
* WhatsAppJS.page -> passes .page to a page function
* WhasAppJS.page -> passes to sendMessage.page -> passes .page to a page function
*/
class Browser {
initiated: boolean // The puppeeter instance is initiated
headless: boolean // Run on headless mode
devTools: boolean // Open devTools (if headless is false)
width: number // Window width (if headless is false)
height: number // Window height (if headless is false)
browser: any // The Browser instance
page: puppeteer.Page | null // A pointer to the Browser.page for direct access
constructor (options: BrowserOptions) {
this.initiated = false
this.headless = options.headless
this.devTools = options.devTools
this.width = 1200
this.height = 700
this.browser = null
this.page = null
}
/**
* Initiate the puppeeter instance and link browser and page objects
*/
public async initiate () {
// Set browser options
this.browser = await puppeteer.launch({
headless: this.headless,
devtools: this.devTools,
args: [`--window-size=${this.width},${this.height}`]
})
// Access browser pages and retrieve the first. Is the only one we need.
this.page = (await this.browser.pages())[0]
// Set user agent and view port size
await this.page.setUserAgent('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36')
await this.page.setViewport({ width: this.width, height: this.height })
this.initiated = true
}
/**
* Make page wait for a time period
* @param time
*/
async waitFor (time: number) {
await this.page.waitFor(time)
}
/**
* Close the browser instance
*/
async close () {
this.browser.close()
}
/**
* Go to an url
* @param url
*/
async goTo (url) {
await this.page.goto(url, {waitUntil: 'networkidle2'})
}
}
export default Browser
<file_sep>import { Page } from "puppeteer";
import { Selectors } from '../_constans'
import _getXPath from '../_getXPath'
/**
* Presses the send button to send the injected message
* @param page
*/
export default async function pressSend (page: Page): Promise<boolean> {
const sendButtonSelector = Selectors.CHAT_SEND_BUTTON_SELECTOR
const targetXPath = await page.evaluate((sendButtonSelector) => {
const _getXPath = (element) => {
const idx = (sib, name) => sib ? idx(sib.previousElementSibling, name || sib.localName) + (sib.localName == name) : 1;
const segs = elm => !elm || elm.nodeType !== 1 ? [''] : elm.id && document.querySelector(`#${elm.id}`) === elm ? [`id("${elm.id}")`] : [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm, undefined)}]`];
return segs(element).join('/');
}
// Find button and retrieve its XPath
const button = document.querySelector(sendButtonSelector)
return Promise.resolve(_getXPath(button))
}, sendButtonSelector)
if (targetXPath === '') {
throw new Error('Could not find send button element')
}
// Find and click target element
const targetElement: any = await page.$x(targetXPath)
if (targetElement.length > 0) {
await targetElement[0].click()
return true
} else {
throw new Error('Found button element but xPath is invalid.')
}
}
<file_sep>// This is being used in several pageFunctions modules...
// Thanks to https://stackoverflow.com/questions/2661818/javascript-get-xpath-of-a-node
// Unfortunetly we cannot import it on runtime to the page.evaluate.
// Something is lost on compile/import and gets undefined on the puppeeter evaluation context.
// Anyway, the compressed version on pageFunctions is this exact function.
const _getXPath = (element) => {
const idx = (sib, name) => sib
? idx(sib.previousElementSibling, name || sib.localName) + (sib.localName == name)
: 1;
const segs = elm => !elm || elm.nodeType !== 1
? ['']
: elm.id && document.querySelector(`#${elm.id}`) === elm
? [`id("${elm.id}")`]
: [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm, undefined)}]`];
return segs(element).join('/');
}
export default _getXPath
<file_sep>import { Page } from "puppeteer";
import { Selectors } from '../_constans'
import _getXPath from '../_getXPath'
/**
* Inject target into the contact search input
* This allows to search all contacts and not only the active conversations list.
* @param page
* @param message
*/
export default async function searchTarget (page: Page, target: string): Promise<boolean> {
const inputSearchSelector = Selectors.CONVERSATION_SEARCH_INPUT_ELEMENT
await page.type(inputSearchSelector, target, { delay: 40 })
return true
}
<file_sep>import Browser from './utils/Browser'
import { WriteToFile } from './utils/FSPromises'
import { exec } from 'child_process'
import SendMessage, { MessageToSend } from './utils/SendMessage'
import * as path from 'path'
// Page functions
import getQrCode from './utils/PageFunctions/getQRCode'
import checkLoggedIn from './utils/PageFunctions/checkLoggedIn'
interface WhatsAppJsOptions {
headless?: boolean // If the puppetter window will be headless (true means window not vidible)
devTools?: boolean // If the window is visible, does it open devTools by default. Usefull for development.
}
// Define class defaults
const defaultOptions: WhatsAppJsOptions = {
headless: true,
devTools: false,
}
// Some timing constants
const LOGIN_CHECK_INTERVAL: number = 2000 // Interval to check if user has logged in.
const LOGIN_LOAD_TIME: number = 3000 // Interval to let the login load settle.
class WhatsAppJs {
browser: Browser // The puppetter browser/page instance.
initiated: boolean // If puppetter is initialized, thus this class also is
loggedIn: boolean // If the user is logged in whatsapp web
baseUrl: string // The base url for whatsapp web
tempFilePath: string // Path to QRCode image file
onLoginFunction: null | Function // Callback placeholder for when the login is detected
onMessageReceivedFunction: null | Function // Callback placeholder for when a new message is received
stopListeners: boolean // Forces listeners recursive calls to stop
constructor (options?: WhatsAppJsOptions) {
options = { ...defaultOptions, ...options } // Merge defaults with user defined options
this.browser = new Browser({ // Link puppetter object to class property
headless: options.headless,
devTools: options.devTools
})
this.baseUrl = 'https://web.whatsapp.com/' // Whatsapp web URL
this.initiated = false // Default initiated to false
this.tempFilePath = 'src/temp/qrcode.png' // Default qrcode image relative to module file path
this.onLoginFunction = null // Default onLoginFunction to null. Must be set by user
this.onMessageReceivedFunction = null // Default onMessageFunction to null. Must be set by user
this.stopListeners = true // Default to blocking listeners. Will set true on initiate
}
/**
* Initiate WhatAppJS object.
* This is not triggered on construct so the developer can decide where and when
* the object is initiated. This launches a pupperter instance so it can take a few moments.
*/
public async initiate () {
if (this.initiated) return
await this.browser.initiate()
this.stopListeners = false
this.initiated = true
}
/**
* Stop Whatsapp.
* Revert to constructor defaults.
* Flags listeners to stop and close puppeeter instance
* The user might pass keepCallbacks as true to perseve the callbacks set on onLogin/onMessage
*/
public async stop (keepCallbacks?: boolean): Promise<void> {
this.initiated = false
this.loggedIn = false
// keepCallbacks must be explicitly set to true. By default we clear them
if (keepCallbacks) {
this.onLoginFunction = null
this.onMessageReceivedFunction = null
}
this.stopListeners = true
await this.browser.close()
}
/**
* Goes to the base url target and fetches the QRCode from the browser.page instance.
* Some conditions apply: must be initiated but not logged in.
* The user can automatically open the image in a image program with the option openImage set to true.
* @param options
*/
public async getQrCode ({ openImage = false }: { openImage?: boolean} ): Promise<string> {
const isLoggedInError = 'WhatsAppJS is already logged in. Cannot generate QRCode.'
// Throw error if not initiated or already logged in.
if (!this.initiated) throw new Error('WhatsAppJS object is not initiated. Please call .initiate before getting the QRCode')
if (this.loggedIn) {
this.callOnLogInFunction()
throw new Error(isLoggedInError)
}
// Wait for browser instance to navigate to target page
// No internet connection will throw an error here. Throw it to the main thread.
await this.browser.goTo(this.baseUrl).catch(async (error) => {
await this.stop()
throw new Error(error)
})
// Check if user is logged in.
// This should never happen because WhatSApp ties your web session with cookies.
// Since puppetter does not keep cookies from instance to instance, then will always be logged off
this.loggedIn = await checkLoggedIn(this.browser.page)
// If logged in, cannot retrieve QRCode, throw error
if (this.loggedIn) {
this.callOnLogInFunction()
throw new Error(isLoggedInError)
}
// Fetch qrCodeString (its a base64 image string)
let qrCodeString = await getQrCode(this.browser.page)
// Check if somehow the string is empty or undefined. Should not happen.
if (qrCodeString === '' || qrCodeString === undefined) {
throw new Error('An error occured while trying to fetch the QRCode.')
}
// Save to temp folder converted to png
const cleanQrCodeString = qrCodeString.replace(/^data:image\/png;base64,/, "")
await WriteToFile({ fileName: this.tempFilePath, content: cleanQrCodeString, enconding: 'base64' })
// If option openImage, use a command to launch it in the user predefined image program
if (openImage) exec(path.resolve(__dirname, this.tempFilePath.replace('src/', '')))
// Initiate login listener that triggers when it detects that the user scanned the qrCode
this.loginListener()
return qrCodeString
}
/**
* Sends a message using a SendMessage object
* TODO: maybe make message return true on sucess to ease logic on the thread side?
* @param message
*/
public async sendMessage (message: MessageToSend): Promise<void> {
if (!message.target) throw new Error('Undefined target to send message to.')
if (!message.message) throw new Error('Undefined message to send.')
// Create new SendMesasge object and trigger .send()
const newMessage = new SendMessage({ page: this.browser.page, ...message })
await newMessage.send().catch((error) => {
throw new Error('Failed to send message')
})
}
/**
* Sets the callback to when the app detects that the user has read the QRCode
* @param callback
*/
public onLogin (callback: Function): void {
this.onLoginFunction = callback
}
/**
* Sets the callback to then the we detect a new message(s)
* @param callback
*/
public onMessage (callback: Function): void {
this.onMessageReceivedFunction = callback
}
/**
* Periodically checks if the user has logged in.
* If so, iniates messageListner and sets internally values to the new state.
*/
private async loginListener (): Promise<void> {
// Listener stop gate to stop this listener
if (this.stopListeners) return
// Check login status
this.loggedIn = await checkLoggedIn(this.browser.page).catch(() => {
// FIXME: if an error occurs this listerner will cease. SHould it tho?
// Maybe just a console.warn and return false to keep the listerner alive...
throw new Error('Could not check for login')
})
// If not logged in, print message saying it will re-check in X seconds and return.
if (!this.loggedIn) {
const seconds = LOGIN_CHECK_INTERVAL / 1000
console.log(`WhatsAppJS: Waiting for user to read QRCode. Rechecking in ${seconds} seconds`)
setTimeout(() => { this.loginListener() }, LOGIN_CHECK_INTERVAL)
return
}
// The user has read the QRCode and is now logged in. Call the user defined callback
this.callOnLogInFunction()
}
/**
* A wrapper to control the user defined onLogin callback
*/
private async callOnLogInFunction (): Promise<void> {
// If the user has not defined a onLogin callback, we cannot trigger it
// otherwise do so
if (!this.onLoginFunction) {
console.warn('WhatsAppJS: login detected but no onLogin callback is set.')
} else {
// Just a save wait to make sure the login page loads properly since the user might be triggering stuff right away
await this.browser.waitFor(LOGIN_LOAD_TIME)
this.onLoginFunction()
}
// TODO: Initiate on message listener. This runs indefenitly
}
}
export default WhatsAppJs
<file_sep># WhatsAppJS
WhatsAppJS is a Javascript (written in TypeScript) wrapper to send WhatsApp messages using code.
# Motivation
- Too much free time
- Fun little project to practice TS and Puppeeter
- Can actually be usefull
### Installation
Its not ready to be used has a npm dependency (yet) but you can download the code, copy the **src**, and import the WhatsAppJS class module to work with it. You also need to include puppeeter has a dependency in your project.
---
# IMPORTANTE NOTICE
## Regarding the safety of your data
As a responsable person you should not trust blindly anything you come accross online. This project is open source so anyone can audit its code and check that there is no outside connection or data dumps being made to any untrusted server. You can and **should check the code** which is using a Puppeeter instance which actions are confined to the WhatsApp Web app. You can also double check by running this package over a dummy WhatsApp account and spoofing all network calls being made. **They should match all the calls WhatsApp Web App uses in their page and not one more.**
This are known endpoints used by WhatsApp web app:
- `https://web.whatsapp.com/`
- `wss://w7.web.whatsapp.com/`
- `https://dyn.web.whatsapp.com/`
At no moment should you trust a project like this without auditing its code. A puppeetter instance is an actual browser with access to all the data on the WhatsApp account, the same data you would have access if you login right now in your local browser.
## **Do not ever read a QRCode which generation you do not know off, do not control or do not understand**
## Regarding the safety of other people's data
Also, as responsable person and developer, the use of the code in this repository is your and only your responsability. The intend of this project is to automate some task that involves sending WhatsApp messages automatically. In no case, the author is reponsable for your intentions, implementations or any damage that might outcome from the use of the code, including WhatsApp terminating your account for any violation of their TOS.
---
## Implemented Features
The first version of WhatsAppJS is capable of:
- Retrieve the QRCode generated by the WhatsApp web app and retrieve it so the user can login. The QRCode is saved, as image, to disk and can be use to sent/process further.
- Detect user login
- Send automated messages providing a target and a message. A target is the exact matching name of a contact or group. You can also provide the exact match of a phone number.
## Roadmap
Work-in-process features include:
- Detect received messages, retrieving the sender and the message content to be worked upon.
- Improve how to identify a valid target.
- [Done] ~~Ability to search contacts and not only the left side conversation list.~~
- Better algorithm to match the target string to the desire contact.
- Test if its necessary to resolve or ignore emojis on conversations tittles.
- Prevent and/or recover from conversations poping in to the active conversation.
- Use of whatsapp api instead of DOM manipulation. This is likely not possible (or very hard) due to message encryption.
- [Done] ~~Simulated typing. Instead of injecting the message, simulate user typing to mask the bot behaviour.~~
- [Done] ~~Make getQrCode() method also retrieve the Base64 string if the developer decides to do something else with it.~~
---
## The WhatsAppJS class
The class provides a way to generate the login QRCode which is saved to an image file and/or launched on screen. Reading the QRCode within an WhatsApp phone app, logs that user into the active puppeeter instance.
After a valid login is detected, the WhatsAppJS class provides methods to send messages.
#### WhatsAppJS.initiate(options)
```
Kicks in the puppeeter instance.
This is not included on the class constructor because it is resource intensive.
With an initiate method, you can control when the class does the heavy lifting.
```
#### WhatsAppJS.getQrCode({openFile})
```
Get the QRCode for the user to log in into.
The QRCode is saved to an image file.
You can also decide to show the QRCode on screen by
setting `openFile` to true
```
#### WhatsAppJS.onLogin(callback)
```
The callback that is executed when a valid login is detected.
Its where your send messages logic should reside to make sure
they only trigger on a valid user session
```
#### WhatsAppJS.onMessage(callback) [WIP]
```
This feature is not available yet.
The callback to respond to received messages.
It is your function which receives a Message object to respond
according to the sender (message.target) and the message (message.message).
```
#### WhatsAppJS.sendMessage({target, message})
```
A message to be sent to a target.
The target is the exact name of a contact/group of the logged user.
You can alternatively provide a contact phone number.
```
#### WhatsAppJS.stop()
```
Kills the WhatsApp listeners and closes the puppeeter instance.
You need to .stop() your WhatsApp object if you want the runtime
to end the process, otherwise the listerners might still be active.
Do not stop the instance if you want it to be left activally listen to
received messages.
```
---
## And working example
```
import WhatsAppJs from './WhatsAppJs'
// Initiate your WhatsAppJs object.
// You can set headless and devTools options.
const WAJS = new WhatsAppJs({
headless: false,
devTools: false
})
// Containning the code on a function so you can use async/await
const run = async () => {
// The onLogin setter is the most important because it defines what to do
// after a valid login is detected.
// Remember we have to wait for the target user to read the QRCode
WAJS.onLogin(async () => {
// Here, we are now logged in and able to send messages
await WAJS.sendMessage({ target: '<NAME>', message: 'Hey, this was a bot!!!' })
await WAJS.sendMessage({ target: 'Baby', message: 'Still mad with me? :(' })
await WAJS.sendMessage({ target: 'Mon', message: 'I need more money mon!!!' })
await WAJS.sendMessage({ target: 'Boss', message: 'Still stuck on traffic, gona be late again :/' })
// You need to stop the class to kill puppeeter and end the process.
// Otherwise, Node keeps running. Place it accordingly in your code.
// If you want to leave it running to handle onMessage events,
// do not use WAJS.stop().
WAJS.stop()
})
// We can also set what to do when a message is received:
// TODO: this is not working yet
WAJS.onMessage((message) => {
if (message.target === 'Client') {
await WAJS.sendMessage({ target: 'Client', message: 'I am on a call right now. I will reach you later.})
}
})
// Wait for puppeteer to kick in.
// This is contained on a initiate method so you can control when to kick in
// since launching puppeeter can take a while.
await WAJS.initiate()
// You can fetch the image file from ./src/temp/qrcode.png after .getQrCode is resolved
await WAJS.getQrCode({ openImage: true })
// getQrCode() also returns the base64 string containing the QRCode if you want to use it for something else
// const QRCodeImageString = await WAJS.getQrCode()
// After getting the QRCode the user must read it with their phone.
// When a successful login is detected, the callback on onLogin, kicks in.
}
run()
```
---
### Contributions
This project its still in its early stages.
I have not defined a workable contribution model but you are free to open issues regarding request/imporvements.
Follow to receive updates for the road map features.
<file_sep>/**
* A working example of how to use WhatsAppJS class.
*/
import WhatsAppJs from './WhatsAppJs'
// Instaciate your WhatsAppJs object.
// You can set headless and devTools options.
const WAJS = new WhatsAppJs({
headless: false,
devTools: true
})
// Containning the code on a function so you can use async/await
const run = async () => {
// The onLogin setter is the most important because it defines what to do
// after a valid login since we have to wait for the user to read the QRCode.
WAJS.onLogin(async () => {
// Here, we are now loged and able to send messages
console.log('will send message')
await WAJS.sendMessage({ target: 'Bernardo', message: 'testing...' })
// You need to stop the class to kill puppeeter and end the process.
// Otherwise, Node keeps running. Place it accordingly in your code.
// If you want to leave it running to handle onMessage events,
// do not use WAJS.stop().
// WAJS.stop()
})
// We can also set what to do when a message is received:
// TODO: this is not working yet
WAJS.onMessage((message) => {
console.log('HEY, I RECEIVED A MESSAGE!!!')
})
// Wait for puppeteer to kick in.
// This is contained on a initiate method so the user can control when to kick in
// since launching puppeeter can take a while.
await WAJS.initiate()
// Also takes a while. This navigates and grabs the QRCode.
// You can fetch the image file from ./src/temp/qrcode.png after .getQrCode is resolved
await WAJS.getQrCode({})
// getQrCode also returns the base64 string containing the QRCode if you want to use it:
// const QRCodeImageString = await WAJS.getQrCode()
// After getting the QRCode the user must read it with their phone.
// When a successful login is detected, the callback on onLogin, kicks in.
}
run()
<file_sep>import * as puppeteer from 'puppeteer'
// Message page functions
import searchTarget from '../utils/PageFunctions/SendMessage/searchTarget'
import clickConversarion from '../utils/PageFunctions/SendMessage/clickConversarion'
import injectMessage from '../utils/PageFunctions/SendMessage/injectMessage'
import pressSend from '../utils/PageFunctions/SendMessage/pressSend'
import pressClearSearch from '../utils/PageFunctions/SendMessage/pressClearSearch'
// A message must have a target and a message strings
export interface MessageToSend {
target: string,
message: string
}
// Defaults and a delay promise to hold execution
const PACE_TIMING: number = 1000
const delay = (time) => { return new Promise(resolve => setTimeout(resolve, time))}
interface ConstructorOptions {
page: puppeteer.Page
message: string
target: string
}
/**
* Class to send a new message.
* Receives .page from WhatsApp class which is a direct pointer to puppeeter.browser.page instance.
* Coordinates the operations to send a message using pageFunctions
*/
class SendMessage {
private page: puppeteer.Page // Pointer to puppeeter.browser.page instance
private message: string // The message to send
private target: string // The target to send the message to.
constructor({ page, message, target }: ConstructorOptions) {
this.page = page
this.message = message
this.target = target
}
/**
* Send a message.
* 1. Inject target into conversations search bar
* 2. Click conversation with title matching target. Ignore message results.
* 3. Clears conversations search bar.
* 4. Inject the message into the text field. Error if text field not found.
* 5. Press button to send message. Error if button not found.
* 6. TODO: confirm message was sent (appears on screen and has 1 or 2 check marks)
*/
public async send (): Promise<void> {
await searchTarget(this.page, this.target).catch((error) => { throw error })
await delay(PACE_TIMING)
await clickConversarion(this.page, this.target).catch((error) => { throw error })
await delay(PACE_TIMING)
await pressClearSearch(this.page).catch((error) => { throw error })
await delay(PACE_TIMING)
await injectMessage(this.page, this.message).catch((error) => { throw error })
await delay(PACE_TIMING)
await pressSend(this.page).catch((error) => { throw error })
await delay(PACE_TIMING)
}
}
export default SendMessage<file_sep>import { Page } from "puppeteer";
import { Selectors } from '../_constans'
import _getXPath from '../_getXPath'
/**
* Inject message into the message input element
* @param page
* @param message
*/
export default async function injectMessage (page: Page, message: string): Promise<boolean> {
const textareaSelector = Selectors.CHAT_MESSAGE_FIELD_SELECTOR
let targetXPath = await page.evaluate((textareaSelector, message) => {
const _getXPath = (element) => {
const idx = (sib, name) => sib ? idx(sib.previousElementSibling, name || sib.localName) + (sib.localName == name) : 1;
const segs = elm => !elm || elm.nodeType !== 1 ? [''] : elm.id && document.querySelector(`#${elm.id}`) === elm ? [`id("${elm.id}")`] : [...segs(elm.parentNode), `${elm.localName.toLowerCase()}[${idx(elm, undefined)}]`];
return segs(element).join('/');
}
// Find and inject message into div behaving like the text input
const textareaElement = document.querySelector(textareaSelector)
if (textareaElement === null) return Promise.resolve(false)
// Return the div XPath
return Promise.resolve(_getXPath(textareaElement))
}, textareaSelector, message)
// Error out if falsy or empty XPath
if (!targetXPath || targetXPath === '') {
throw new Error('Could not inject message into chat field')
}
// Find and press backspace on target element
const targetElement: any[] = await page.$x(targetXPath)
if (targetElement.length > 0) {
await targetElement[0].type(message, { delay: 26 })
return true
} else {
throw new Error('Found target element but xPath is invalid.')
}
}
<file_sep>import { Page } from "puppeteer";
import { Selectors } from './_constans'
/**
* Retrieve QRCode base64 string.
* Navigate query selections to the <img> holding the QRCode.
* Returns its src attribute.
* @param page
*/
export default async function getQRCode (page: Page): Promise<string> {
const imageParentSelector = Selectors.QRCODE_IMG_PARENT_CLASS
const QRCodeString = await page.evaluate((imageParentSelector) => {
const parentElement = document.querySelector(imageParentSelector)
const imageElement = parentElement.querySelector('img')
const imageSource = imageElement.getAttribute('src')
return Promise.resolve(imageSource)
}, imageParentSelector)
return QRCodeString
}<file_sep>/**
* Selectors enum to quickly change selector strings in cases WhatsApp FE changes structure/classes
*/
export enum Selectors {
'QRCODE_IMG_PARENT_CLASS' = '._2EZ_m',
'CONVERSATIONS_PARENT_CLASS' = '.RLfQR',
'CONVERSATION_PLACEHOLDER_ELEMENT' = '._1AKfk',
'CONVERSATION_MESSAGE_RESULTS_ELEMENT' = '._34xP_',
'CONVERSATION_TARGET_ELEMENT' = '._25Ooe',
'CONVERSATION_SEARCH_INPUT_ELEMENT' = '.jN-F5',
'CONVERSATION_CLEAR_SEARCH' = '._3Burg',
'CHAT_MESSAGE_FIELD_SELECTOR' = '._2S1VP',
'CHAT_SEND_BUTTON_SELECTOR' = '._35EW6'
}
<file_sep>import { Page } from "puppeteer";
import { Selectors } from './_constans'
/**
* Check if user is logged in.
* Evaluates on page if the image container with the QRCode exists.
* If exists, returns false -> not logged in.
* @param page
*/
export default async function checkLoggedIn (page: Page): Promise<boolean> {
const imageParentSelector = Selectors.QRCODE_IMG_PARENT_CLASS
const isQRCodePage = await page.evaluate((imageParentSelector) => {
const elementParentExists = document.querySelector(imageParentSelector) !== null
return Promise.resolve(elementParentExists)
}, imageParentSelector)
return !isQRCodePage
}
| 0f26d078f35023f0128fc20631e8dd8c48a1e7a3 | [
"Markdown",
"TypeScript"
] | 14 | TypeScript | KaiHotz/WhatsAppJS | ee968ab86682dbf794d8a09eaf6ee7836b11a68a | 3a1feccb9d63b827a56515104e9ec2b5fd3abc54 |
refs/heads/master | <repo_name>IsseW/PyGame<file_sep>/Function/Complex.py
import pygame
import math
import pygame.gfxdraw
import cmath
pygame.init()
def PSqrd(a, b):
return a * a + b * b
xMin = -5
yMin = -5
xMax = 5
yMax = 5
width = xMax - xMin
height = yMax - yMin
diagonalSqrd = max(PSqrd(xMax, yMax), PSqrd(xMax, yMin), PSqrd(xMin, yMax), PSqrd(xMin, yMin))
windowWidth = 800
windowHeight = 800
xScale = windowWidth / width
xHalf = xScale / 2
yScale = windowHeight / height
yHalf = yScale / 2
xRes = 1
yRes = 1
TRANSPARENT = (0,0,0,200)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
screen = pygame.display.set_mode((windowWidth, windowHeight))
def complexFunction(z):
if z.real == 0 and z.imag == 0: return complex(0, 0)
return z*z
def function(x, y):
z = complex(x, y)
result = complexFunction(z)
return result.real, result.imag
def pingpong(v, a, b):
times = (v - a) // (b - a)
value = (v - a) % (b - a)
if times % 2 == 0:
return a + value
return b - value
def clamp(v, a, b):
if v < a: return a
if v > b: return b
return v
def remap(v, f, t):
return (v - f[0]) * (t[1] - t[0]) / (f[1] - f[0]) + t[0]
def getColor(x, y):
return (pingpong(remap(x, (xMin, xMax), (0, 255)), 0, 255), pingpong(remap(x * x + y * y, (0, diagonalSqrd), (0, 255)), 0, 255), pingpong(remap(y, (yMin, yMax), (0, 255)), 0, 255))
def getSquare(x, y):
return math.floor(x / xScale), math.floor(y / yScale)
def drawSquare(x, y, color):
pygame.draw.rect(screen, color, (x, y, xRes, yRes))
def screenToWorld(x, y):
return x / xScale + xMin, y / yScale + yMin
def worldToScreenX(x):
return (x - xMin) * xScale
def worldToScreenY(y):
return (y - yMin) * yScale
def worldToScreen(x, y):
return worldToScreenX(x), worldToScreeny(y)
def drawWorld():
for x in range(0, windowWidth, xRes):
for y in range(0, windowHeight, yRes):
worldX, worldY = screenToWorld(x, y)
valueX, valueY = function(worldX, worldY)
drawSquare(x, y, getColor(valueX, valueY))
xAxis = worldToScreenY(0)
if xAxis > 0 and xAxis < windowHeight:
pygame.draw.line(screen, BLACK, (0, xAxis), (windowWidth, xAxis))
yAxis = worldToScreenX(0)
if yAxis > 0 and yAxis < windowWidth:
pygame.draw.line(screen, BLACK, (yAxis, 0), (yAxis, windowHeight))
done = False
drawWorld()
pygame.display.flip()
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
pygame.display.quit()
pygame.quit()
<file_sep>/Pathfinding/AStar.py
import math
import pygame
W = 100
H = 100
sqrt2 = math.sqrt(2)
def GetNeighbors(point):
return [(point[0] + 1, point[1]),
(point[0], point[1] + 1),
(point[0] + 1, point[1] + 1),
(point[0] - 1, point[1]),
(point[0], point[1] - 1),
(point[0] - 1, point[1] - 1),
(point[0] + 1, point[1] - 1),
(point[0] - 1, point[1]) + 1]
class Node(object):
def __init__(self, x, y):
self.pos = (x, y)
def x(self):
return self.pos[0]
def y(self):
return self.pos[1]
def id(self):
return self.y() * W + self.x()
def __lt__(self, other):
return self.id() < other.id()
def __gt__(self, other):
return self.id() > other.id()
def
class AStar:
def FindPath(self, grid, start, end):
open = [(start, 0)]
closed = []
while True:
current = open.pop(0)
closed.append(current)
if current == end:
return
for p in GetNeighbors(current[0]):
<file_sep>/Generation/gen.py
import pygame
class world:
def ___init___(self, width, height):
self.size = (width, height)
self.creatures = []
class creature:
def ___init___(self, stats):
self.stats = stats
def move(self, other):
def addToWorld(self, world, position):
world.creatures.append(self)
self.world = world
self.setPosition(position)
def setPosition(self, position):
self.position = position % world.size
<file_sep>/Function/main.py
import sys
import pygame
from dfunction import DiffFunction
print('y\'=', end='')
inp = input()
function = DiffFunction(inp)
xstart = 0
ystart = 1
xmin = 0
xmax = 10
step = 0.01
val, ymin, ymax = function.getValues(xstart, ystart, xmin, xmax, step)
print(ymin, ymax)
W = 500
H = 500
screen = pygame.display.set_mode((W, H))
dX = W / (xmax - xmin)
dY = H / (ymax - ymin)
RED = (255, 0, 0)
def ScreenPoint(index):
global val, dX, dY, step, ymin, H
return dX * (index * step), H - dY * (val[index] - ymin)
def DrawFunction():
lastpoint = ScreenPoint(0)
for i in range(1, len(val)):
point = ScreenPoint(i)
pygame.draw.line(screen, RED, lastpoint, point)
lastpoint = point
pygame.init();
white = (255, 255, 255)
clock = pygame.time.Clock()
drawn = False
while 1:
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
sys.exit()
if not drawn:
screen.fill(white)
DrawFunction()
pygame.display.update()
drawn = True
clock.tick(30)
<file_sep>/Generation/caves.py
from noise import perlin
<file_sep>/Generation/perlin2.py
import pygame
from noise import perlin
from sys import exit
noise = perlin.SimplexNoise()
screenWidth = 500
screenHeight = 500
width = 250
height = 250
blockWidth = float(screenWidth) / width
blockHeight = float(screenHeight) / height
screen = pygame.display.set_mode((screenWidth, screenHeight))
seedX = 0
seedY = 0
colors = [((0,0,0), -10), ((0, 191, 255), 0.1), ((0, 255, 0), 0), ((0, 255, 0), 0.5), ((255, 255, 255), 0.1), ((0, 0, 0), 10)]
def plotValue(value):
if len(colors) == 0:
return (0, 0, 0)
for i in range(0, len(colors)):
if i + 1 == len(colors):
return colors[i][0]
if value >= colors[i][1] and value < colors[i + 1][1]:
part = float(value - colors[i][1]) / (colors[i + 1][1] - colors[i][1])
other = 1 - part
return (colors[i][0][0] * other + colors[i + 1][0][0] * part,
colors[i][0][1] * other + colors[i + 1][0][1] * part,
colors[i][0][2] * other + colors[i + 1][0][2] * part)
return 0
smooth = 200
def getValue(x, y):
return noise.noise2((seedX + x) / smooth, (seedY + y) / smooth)
def draw():
for x in range(width):
for y in range(height):
value = getValue(x, y)
color = plotValue(value * abs(value))
pygame.draw.rect(screen, color, (x * blockWidth, y * blockHeight, blockWidth, blockHeight))
pygame.display.flip()
done = False
draw()
move = 10
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
seedX -= move
elif event.key == pygame.K_d:
seedX += move
elif event.key == pygame.K_w:
seedY -= move
elif event.key == pygame.K_s:
seedY += move
draw()
print('Exiting')
pygame.quit()
exit()
<file_sep>/PerlinNoise/Game.py
import pygame
import noise
pygame.init()
width = 500
height = 300
screen = pygame.display-set_mode((width, height))
xPos = width / 5
yPos = 0
yValues = []
seed = 0
def getValues(seed, length):
<file_sep>/Generation/noise.py
import cv2
import random
import numpy as np
import math
import random
def GetColor(position):
v = random.random() * 255
return (v, v, v)
def GenerateNoise(imageSize):
img = np.zeros((imageSize,imageSize,3), np.uint8)
for i in range(imageSize):
for j in range(imageSize):
img[i][j] = GetColor((i, j))
cv2.imwrite('noise.png',img)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
GenerateNoise(400)
<file_sep>/Generation/distribution.py
import cv2
import random
import numpy as np
import math
import random
def isValid(candidate, size, cellsize, radius, points, grid):
if candidate[0] >= 0 and candidate[0] < size[0] and candidate[1] > 0 and candidate[1] < size[1]:
cellX = math.floor(candidate[0] / cellsize)
cellY = math.floor(candidate[1] / cellsize)
if grid[cellX, cellY] != 0: return False
searchStartX = cellX - 2
searchEndX = (cellX + 2) % len(grid)
searchStartY = cellY - 2
searchEndY = (cellY + 2) % len(grid[searchEndX])
for x in range(searchStartX, searchEndX + 1):
for y in range(searchStartY, searchEndY + 1):
pointIndex = grid[x][y] - 1
if pointIndex >= 0:
dif = (candidate[0] - points[pointIndex][0], candidate[1] - points[pointIndex][1])
sqrDst = dif[0] * dif[0] + dif[1] * dif[1]
if sqrDst < radius*radius:
return False
return True
return False
def generatePoints(radius, size, samples = 15):
cellsize = radius / math.sqrt(2)
grid = np.zeros((math.ceil(size[0]/cellsize), math.ceil(size[1]/cellsize)), np.uint8)
points = []
spawnPoints = []
spawnPoints.append((size[0]/2,size[1]/2))
while len(spawnPoints) > 0:
spawnIndex = random.randint(0, len(spawnPoints) - 1)
spawnCenter = spawnPoints[spawnIndex]
accepted = False
for i in range(samples):
angle = (random.randrange(10000)/10000) * math.pi * 2;
direction = (math.sin(angle), math.cos(angle))
dist = random.randrange(radius*1000, radius*2000) / 1000
candidate = (spawnCenter[0] + direction[0] * dist, spawnCenter[1] + direction[1] * dist)
if isValid(candidate, size, cellsize, radius, points, grid):
points.append(candidate)
spawnPoints.append(candidate)
grid[math.floor(candidate[0]/cellsize)][math.floor(candidate[1]/cellsize)] = len(points);
accepted = True
break
if not accepted:
spawnPoints.remove(spawnCenter)
print("points generated")
return points
def drawPoints(img, points, radius, color = [255, 255, 255]):
for i in range(len(points)):
#print(points[i])
cv2.circle(img, (int(points[i][0]), int(points[i][1])), radius, color, -1)
print("points drawn")
size = (300, 300)
bigRadius = 2
bigRadius2 = 50
smallRadius = 1
smallRadius2 = 30
big = generatePoints(bigRadius2, size)
small = generatePoints(smallRadius2, size)
img = np.zeros((size[0],size[1],3), np.uint8)
drawPoints(img, small, smallRadius, [100, 100, 100])
drawPoints(img, big, bigRadius, [200, 200, 200])
cv2.imwrite('distribution.png',img)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
<file_sep>/Generation/voronoi.py
import cv2
import random
import numpy as np
import math
from noise import perlin
noise = perlin.SimplexNoise()
def GetPoints(size):
points = []
for i in range(size):
points.append([])
for j in range(size):
x = i / size
y = j / size
_x = random.random() / size
_y = random.random() / size
points[i].append((x + _x, y + _y))
return points
def GetNoise(pos, distortion, offset):
return (noise.noise2(pos[0] * distortion + offset, pos[1] * distortion + offset) + 1) / 2
def GetColor(position, distance, cell):
t = math.sqrt(GetNoise(cell, 1, 0))
t1 = math.sqrt(GetNoise(cell,2,10))
t2 = math.sqrt(GetNoise(cell,4,20))
#c = min(10 * distance / (distance+math.sqrt(distance)), 1)
return [255 * t, 255 * t1, 255 * t2]
def DistanceSq(p1, p2):
"""
p = ((abs(p1[0] - p2[0])), abs(p1[1] - p2[1]))
#d = p[0] * p[0] + 2 * p[0] * p[1] + p[1] * p[1]
d1 = p[1] * p[1]
d2 = p[0] * p[0]
d = 2 * d1 + 2 * d2 + 2 * p[0] * p[1]
"""
p = (p1[0] - p2[0], p1[1] - p2[1])
return p[0] * p[0] + p[1] * p[1]
def GenerateVoronoi(points, imageSize):
img = np.zeros((imageSize,imageSize,3), np.uint8)
for i in range(imageSize):
for j in range(imageSize):
x = i / imageSize
y = j / imageSize
pos = (x, y)
_x = math.floor(len(points) * x)
_y = math.floor(len(points) * y)
check = [[points[abs(_x + 1) % len(points)][abs(_y + 1) % len(points[_x])], points[_x][abs(_y + 1) % len(points[_x])], points[(_x - 1) % len(points)][abs(_y + 1) % len(points[_x])]],
[points[abs(_x + 1) % len(points)][_y], points[_x][_y], points[(_x - 1) % len(points)][_y]],
[points[abs(_x + 1) % len(points)][(_y - 1) % len(points[_x])], points[_x][(_y - 1) % len(points[_x])], points[(_x - 1) % len(points)][(_y - 1) % len(points[_x])]]]
minDist = 1
iX = 0
iY = 0
for y_ in range(len(check)):
for x_ in range(len(check[y_])):
c = DistanceSq(check[y_][x_], pos)
if c < minDist:
minDist = c
iX = x_
iY = y_
img[i][j] = GetColor(pos, minDist, ((_x - (iX)), (_y - (iY))))
cv2.imwrite('voronoi.png',img)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
points = GetPoints(10)
GenerateVoronoi(points, 1000)
<file_sep>/Game of life/GameOfLife.py
import pygame
import math
import pygame.gfxdraw
import copy
import objects
pygame.init()
width = 200
height = 200
windowWidth = 800
windowHeight = 800
xScale = windowWidth / width
xHalf = xScale / 2
yScale = windowHeight / height
yHalf = yScale / 2
TRANSPARENT = (0,0,0,200)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
screen = pygame.display.set_mode((windowWidth, windowHeight))
rect = pygame.Surface((windowWidth,windowHeight), pygame.SRCALPHA, 32)
rect.fill(TRANSPARENT)
world = []
for x in range(width):
world.append([])
for y in range(height):
world[x].append(0)
clean = copy.deepcopy(world)
def getSquare(x, y):
return math.floor(x / xScale), math.floor(y / yScale)
def drawSquare(x, y, color):
pygame.draw.rect(screen, color, (x * xScale, y * yScale, xScale, yScale))
def drawWorld():
screen.blit(rect, (0, 0))
for x in range(width):
for y in range(height):
if world[x][y] > 0:
drawSquare(x, y, WHITE)
def neighborCount(x, y):
count = 0
left = x > 0
right = x + 1 < width
up = y > 0
down = y + 1 < height
if left and world[x - 1][y] > 0: count+=1
if right and world[x + 1][y] > 0: count+=1
if up and world[x][y - 1] > 0: count+=1
if down and world[x][y + 1] > 0: count+=1
if left and up and world[x - 1][y - 1]: count+=1
if right and up and world[x + 1][y - 1]: count+=1
if left and down and world[x - 1][y + 1]: count+=1
if right and down and world[x + 1][y + 1]: count+=1
return count
def simulateWorld(world):
newWorld = copy.deepcopy(clean)
for y in range(height):
for x in range(width):
count = neighborCount(x, y)
newWorld[x][y] = world[x][y]
if world[x][y] == 0 and count == 3:
newWorld[x][y] = 1
elif world[x][y] == 1 and (count < 2 or count > 3):
newWorld[x][y] = 0
return newWorld
simulate = False
done = False
lastTick = 0
tick = 100
while not done:
doTick = pygame.time.get_ticks() - lastTick > tick
if doTick:
lastTick = pygame.time.get_ticks()
simulateTick = doTick and simulate
inside = False
pressed = pygame.mouse.get_pressed()
pos = pygame.mouse.get_pos()
x, y = getSquare(pos[0], pos[1])
if x < width and y < height and x >= 0 and y >= 0:
inside = True
if pressed[0] == 1:
world[x][y] = 1
elif pressed[2] == 1:
world[x][y] = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
world = copy.deepcopy(clean)
elif event.key == pygame.K_SPACE:
simulate = not simulate
elif event.key == pygame.K_d:
simulateTick = True
doTick = True
elif inside:
if event.key == pygame.K_1:
objects.placeObject(world, objects.GLIDER, x, y)
if event.key == pygame.K_2:
objects.placeObject(world, objects.GLIDERGUN, x, y)
if doTick:
if simulateTick:
world = simulateWorld(world)
drawWorld()
pygame.display.flip()
<file_sep>/Liquid/Liquid.py
import pygame
import random
import copy
import sys
import math
import pygame.gfxdraw
pygame.init()
width = 100
height = 100
windowWidth = 500
windowHeight = 500
xScale = windowWidth / width
xHalf = xScale / 2
yScale = windowHeight / height
yHalf = yScale / 2
sys.setrecursionlimit(3000)
TRANSPARENT = (0,0,0,50)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
BLUE = (0, 0, 255)
POM = [-1, 0, 1]
PO = [0, 1]
OM = [-1 , 0]
screen = pygame.display.set_mode((windowWidth, windowHeight))
rect = pygame.Surface((windowWidth,windowHeight), pygame.SRCALPHA, 32)
rect.fill(TRANSPARENT)
world = []
for x in range(width):
world.append([])
for y in range(height):
world[x].append(0)
clean = copy.deepcopy(world)
def getSquare(x, y):
return math.floor(x / xScale), math.floor(y / yScale)
def drawSquare(x, y, color):
pygame.draw.rect(screen, color, (x * xScale, y * yScale, xScale, yScale))
def drawEllipse(x, y, color):
pygame.draw.ellipse(screen, color, (x * xScale, y * yScale, xScale, yScale))
def drawTransparentSquare(x, y):
pygame.gfxdraw.box(screen, (x * xScale, y * yScale, xScale, yScale), TRANSPARENT)
def drawWorld():
for x in range(width):
for y in range(height):
if world[x][y] < 0:
drawSquare(x, y, WHITE)
elif world[x][y] > 0:
drawSquare(x, y, BLUE)
def simulateWorld(world):
newWorld = copy.deepcopy(clean)
for y in range(height):
for x in range(width):
if world[x][y] > 0:
simulateBlock(x, y, newWorld)
elif world[x][y] < 0:
newWorld[x][y] = -1
return newWorld
#assume x and y is in array
def IsFree(x, y, arr):
return (arr[x][y] == 0 or arr[x][y] == 5) and (world[x][y] == 0 or world[x][y] == 5)
def simulateBlock(x, y, arr):
value = world[x][y]
if value == 5: return
#Free
down = y + 1 < height and IsFree(x, y + 1, arr)
up = y - 1 >= 0 and IsFree(x, y - 1, arr)
right = x + 1 < width and IsFree(x + 1, y, arr)
left = x - 1 >= 0 and IsFree(x - 1, y, arr)
downdown = down and y + 2 < height and IsFree(x, y + 2, arr)
rightright = right and x + 2 < width and IsFree(x + 2, y, arr)
leftleft = left and x - 2 >= 0 and IsFree(x - 2, y, arr)
close = 0
if not down: close+=1
if not up: close+=1
if not right: close+=1
if not left: close+=1
if not up and downdown:
arr[x][y + 1] = 5
arr[x][y + 2] = 1
elif down:
arr[x][y + 1] = 1
elif (rightright or leftleft) and close >= 2 and random.choice(POM) < close - 2:
if rightright:
arr[x + 1][y] = 5
arr[x + 2][y] = 4
elif leftleft:
arr[x - 1][y] = 5
arr[x - 2][y] = 2
elif right:
if left:
if value == 2:
arr[x - 1][y] = 2
elif value == 4:
arr[x + 1][y] = 4
else:
move = random.choice(POM)
arr[x + move][y] = 3 + move
else:
if value == 2:
arr[x][y] = 3
else:
move = random.choice(PO)
arr[x + move][y] = 3 + move
elif left:
if value == 4:
arr[x][y] = 3
else:
move = random.choice(OM)
arr[x + move][y] = 3 + move
else:
arr[x][y] = 3
def fill(x, y, value, level=0):
if level > 2980:
return
if world[x][y] == 0:
world[x][y] = value
if x + 1 < width:
fill(x + 1, y, value, level=level+1)
if x - 1 >= 0:
fill(x - 1, y, value, level=level+1)
if y + 1 < height:
fill(x, y + 1, value, level=level+1)
if y - 1 >= 0:
fill(x, y - 1, value, level=level+1)
done = False
last = 0
tick = 10
blitLast = False
while not done:
value = 0
keys = pygame.key.get_pressed()
if keys[pygame.K_LCTRL]:
value = 1
else:
value = -1
bV = value > 0
simulate = pygame.time.get_ticks() - last > tick
inside = False
pressed = pygame.mouse.get_pressed()
pos = pygame.mouse.get_pos()
x, y = getSquare(pos[0], pos[1])
if x < width and y < height and x >= 0 and y >= 0:
inside = True
if pressed[0] == 1 and world[x][y] >= 0:
world[x][y] = value
elif pressed[2] == 1:
world[x][y] = 0
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if inside:
if event.key == pygame.K_f:
fill(x, y, value)
elif event.key == pygame.K_h:
for _x in range(width):
world[_x][y] = value
elif event.key == pygame.K_v:
for _y in range(height):
world[x][_y] = value
if event.key == pygame.K_r:
for x in range(width):
for y in range(height):
if not ((world[x][y] > 0) ^ bV):
world[x][y] = 0
if simulate:
if keys[pygame.K_SPACE]:
_x = random.choice(range(width))
if world[_x][0] == 0:
world[_x][0] = 1
last = pygame.time.get_ticks()
world = simulateWorld(world)
if not blitLast:
screen.blit(rect, (0, 0))
blitLast = True
else:
blitLast = False
drawWorld()
pygame.display.flip()
pygame.display.quit()
pygame.quit()
<file_sep>/Generation/perlin.py
import cv2
import random
import numpy as np
import math
from noise import perlin
noise = perlin.SimplexNoise()
def GetNoise(pos, distortion, offset):
return (noise.noise2(pos[0] * distortion + offset, pos[1] * distortion + offset) + 1) / 2
def GetColor(position):
v = GetNoise(position, 0.01, 0) * 255
return (v, v, v)
def GeneratePerlin(imageSize):
img = np.zeros((imageSize,imageSize,3), np.uint8)
for i in range(imageSize):
for j in range(imageSize):
img[i][j] = GetColor((i, j))
cv2.imwrite('perlin.png',img)
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
GeneratePerlin(400)
<file_sep>/Generation/perlin1.py
import pygame
from noise import perlin
import math
import random
pygame.init()
noise = perlin.SimplexNoise()
seed = random.randint(0, 100000)
amplitude = 100
myfont = pygame.font.SysFont('Comic Sans MS', 30)
width = 600
height = 400
smallHeight = height / 4
RED = (255, 0, 0)
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
GREEN = (0, 255, 0)
thickness = 4
screen = pygame.display.set_mode((width, height))
def getValue(x):
return noise.noise2(x / float(200), seed)
def getArray(length, start):
arr = []
for i in range(length):
arr.append(getValue(start))
start += 1
return arr, start
values, offset = getArray(width, 0)
def getNext(arr, x):
del arr[0]
arr.append(getValue(x))
x += 1
return arr, x
def minMax(x):
minY = height / 2 - (values[int(x)] * amplitude + smallHeight / 2)
maxY = minY + smallHeight
return minY, maxY
def center(x):
return height / 2 - (values[int(x)] * amplitude)
def drawValue(x):
minY, maxY = minMax(x)
color = int(70 + abs(500 - (offset + x) % 1000) / 6.41)
pygame.draw.rect(screen, (color, color, color), (x, minY, 1, maxY - minY))
pygame.draw.rect(screen, BLACK, (x, minY - thickness / 2, 1, thickness))
pygame.draw.rect(screen, BLACK, (x, maxY - thickness / 2, 1, thickness))
playerX = width / 2
playerY = center(playerX)
playerRadius = 10
def draw():
screen.fill(RED)
for i in range(len(values)):
drawValue(i)
pygame.draw.circle(screen, WHITE, (int(playerX), int(playerY)), int(playerRadius))
textsurface = myfont.render(str(int((offset - width) / 10)), False, (0, 0, 0))
screen.blit(textsurface,(0,0))
def checkCollision():
for i in range(-int(playerRadius), int(playerRadius)):
y = math.sqrt(playerRadius * playerRadius - i * i)
minY, maxY = minMax(playerX + i)
if playerY - y < minY: return True
if playerY + y > maxY: return True
return False
done = False
lastTick = 0
tick = 16
speed = 3
while not done:
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
doTick = pygame.time.get_ticks() - lastTick > tick
if doTick:
lastTick = pygame.time.get_ticks()
keys = pygame.key.get_pressed()
if keys[pygame.K_w]:
playerY -= speed
elif keys[pygame.K_s]:
playerY += speed
if checkCollision():
seed = random.randint(0, 100000)
values, offset = getArray(width, 0)
playerX = width / 2
playerY = center(playerX)
tick = 16
playerRadius = 10
amplitude = 100
values, offset = getNext(values, offset)
draw()
tick -= 0.0001
amplitude += 0.01
pygame.display.flip()
<file_sep>/Function/dfunction.py
import re
import parser
import re
from math import sin
from math import cos
from math import tan
from math import asin
from math import acos
from math import atan
from math import log
from math import floor
from math import ceil
from math import gamma
from math import sqrt
e = 2.71828182846
π = pi = 3.14159265359
τ = tau = 2 * pi
def ParseDifferential(input):
input = input.replace('^', '**').replace('factorial(', 'gamma(1 +').replace('ceiling', 'ceil').replace('y', 'F')
eq = parser.expr(input).compile()
return eq
class DiffFunction:
def __init__(self, input):
self.equation = ParseDifferential(input)
def getDerivative(self, value):
F = value
return eval(self.equation)
def getValues(self, startX, startY, min, max, step):
values = [ ]
F = startY
min = min - startX;
max = max - startX
ymin = startY
ymax = startY
if max < 0:
for i in range(1, floor(-max / step)):
x = startX - i * step
der = eval(self.equation)
F = F - der * step
for i in range(1, floor(-min / step)):
x = max - i * step
der = eval(self.equation)
F = F - der * step
values.append(F)
if F < ymin: ymin = F
elif F > ymax: ymax = F
values = values[::-1]
values.append(startY)
elif min > 0:
for i in range(1, floor(min / step)):
x = startX + i * step
der = eval(self.equation)
F = F + der * step
for i in range(1, floor(max / step)):
x = min + i * step
der = eval(self.equation)
F = F + der * step
values.append(F)
if F < ymin: ymin = F
elif F > ymax: ymax = F
else:
for i in range(1, floor(-min / step)):
x = startX - i * step
der = eval(self.equation)
F = F - der * step
values.append(F)
if F < ymin: ymin = F
elif F > ymax: ymax = F
values = values[::-1]
F = startY
values.append(F)
for i in range(1, floor(max / step)):
x = startX + i * step
der = eval(self.equation)
F = F + der * step
values.append(F)
if F < ymin: ymin = F
elif F > ymax: ymax = F
return values, ymin, ymax
f = DiffFunction("pi")
f.getValues(0, 100, -50, 100, 0.01)
<file_sep>/GoldenRatio/Graph.py
import pygame
import random
import pygame.gfxdraw
import math
choiceArr = [-1, 1]
x = 1
y = 1
windowWidth = 800
windowHeight = 800
TRANSPARENT = (0,0,0,200)
TRANSPARENTWHITE = (255, 255, 255, 0)
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
def GetNextValue():
global x, y
z = x + y * random.choice(choiceArr)
x = y
y = z
return z
values = [(0, 1)]
currentViewport = (0, -10, 10, 10)
viewport = [10000.0, 10000.0]
def FitInViewport(value):
global viewport
if value[0] > viewport[0]:
viewport[0] = value[0]
if abs(value[1]) > viewport[1]:
viewport[1] = abs(value[1])
def Transform(value):
global currentViewport
return ((value[0] - currentViewport[0]) * (windowWidth / (currentViewport[2] - currentViewport[0])),
(value[1] - currentViewport[1]) * (windowHeight / (currentViewport[3] - currentViewport[1])))
def InvTransform(value):
global currentViewport
return (value[0] * ((currentViewport[2] - currentViewport[0]) / windowWidth) + (currentViewport[0]),
value[1] * ((currentViewport[3] - currentViewport[1]) / windowHeight) + (currentViewport[1]))
def InsideViewport(value):
global currentViewport
return value[0] > currentViewport[0] and value[0] < currentViewport[2] and value[1] > currentViewport[1] and value[1] < currentViewport[3]
def Draw():
global values, currentViewport
screen.blit(rect, (0, 0))
start = math.floor(currentViewport[0])
if start + 1 > len(values):
return
end = math.ceil(currentViewport[2])
p1 = Transform(values[start])
#print(start, end)
for i in range(start + 1, min(end, len(values)) - start - 1):
#print(i)
p2 = Transform(values[i])
pygame.draw.line(screen, RED, p1, p2)
p1 = p2
screen = pygame.display.set_mode((windowWidth, windowHeight))
rect = pygame.Surface((windowWidth,windowHeight), pygame.SRCALPHA, 32)
rect.fill(BLACK)
currentValue = 1
toCalc = 10000
lastH = 10.0
done = False
lastTick = 0
tick = 0
useBigViewport = True
selecting = False
startSelect = (0, 0)
while not done:
doTick = pygame.time.get_ticks() - lastTick > tick
if doTick:
lastTick = pygame.time.get_ticks()
pressed = pygame.mouse.get_pressed()
pos = pygame.mouse.get_pos()
if selecting:
if not pressed[0] == 1:
#Stop selecting
selecting = False
useBigViewport = False
start = InvTransform(startSelect)
end = InvTransform(pos)
if not start[0] == end[0] and not start[1] == end[1]:
currentViewport = (start[0], start[1], end[0], end[1])
elif pressed[0] == 1:
selecting = True
startSelect = pos
for event in pygame.event.get():
if event.type == pygame.QUIT:
done = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
useBigViewport = True
#if event.key == pygame.K_A:
#Linear regression
if doTick:
if toCalc > 0:
toCalc -= 1
v = abs(GetNextValue())
if v > 0: v = math.log(v)
elif v < 0: v = -math.log(-v)
value = (currentValue, v)
currentValue += 1
#FitInViewport(value)
values.append(value)
Draw()
if selecting:
pygame.draw.rect(screen, WHITE,(startSelect, (abs(startSelect[0] - pos[0]), abs(startSelect[1] - pos[1]))), 1)
pygame.display.flip()
if useBigViewport:
currentViewport = (0, -viewport[1], viewport[0], viewport[1])
tick -= 0.0001
| 70a9867165e1f1b1e7049552bc094a0cc4a08284 | [
"Python"
] | 16 | Python | IsseW/PyGame | 6a48893d70d54a743ef695298cb04acb57cce1af | 1405f214ade1b9814fcc6326b10fb773437fc21d |
refs/heads/master | <repo_name>whoe/javascript-task-6<file_sep>/lib.js
'use strict';
/**
* Итератор по друзьям
* @constructor
* @param {Object[]} friends
* @param {Filter} filter
*/
function Iterator(friends, filter) {
if (!(filter instanceof Filter)) {
throw new TypeError('Bad filter');
}
this._friends = friends;
this._filter = filter;
this._prepare(this._maxLevel);
}
Object.assign(Iterator.prototype, {
done() {
return this._current === this._filtredInvited.length;
},
next() {
if (this._current < this._filtredInvited.length) {
return this._filtredInvited[this._current++];
}
return null;
},
_filtredInvited: [],
_current: 0,
/**
* Подготавливает массив filtredInvited для функции next и done
* @param {Number} maxLevel
*/
_prepare(maxLevel) {
if (maxLevel === undefined) {
maxLevel = Number.MAX_SAFE_INTEGER;
}
let currentLevel = this._friends
.filter(friend => friend.best)
.sort(alphabetOrder);
let invitedFriends = [];
let level = 1;
while (level <= maxLevel && currentLevel.length > 0) {
invitedFriends = invitedFriends.concat(currentLevel);
let nextLevel = this._getNextLevel(currentLevel, invitedFriends)
.sort(alphabetOrder);
currentLevel = nextLevel;
level++;
}
this._filtredInvited = this._filter.useFilter(invitedFriends);
},
_getNextLevel(currentLevel, invitedFriends) {
let invitedFriendNames = invitedFriends.map(friend => friend.name);
return currentLevel
.reduce((nextFriendNames, currentFriend) =>
nextFriendNames.concat(
currentFriend.friends
.filter(nextFriendName =>
!nextFriendNames.includes(nextFriendName) &&
!invitedFriendNames.includes(nextFriendName))
), [])
.map(friendName => this._friends.find(friend => friend.name === friendName));
}
});
function alphabetOrder(a, b) {
if (a.name === b.name) {
return 0;
}
if (a.name < b.name) {
return -1;
}
return 1;
}
/**
* Итератор по друзям с ограничением по кругу
* @extends Iterator
* @constructor
* @param {Object[]} friends
* @param {Filter} filter
* @param {Number} maxLevel – максимальный круг друзей
*/
function LimitedIterator(friends, filter, maxLevel) {
this._maxLevel = maxLevel;
Iterator.call(this, friends, filter);
}
Object.setPrototypeOf(LimitedIterator.prototype, Iterator.prototype);
/**
* Фильтр друзей
* @constructor
*/
function Filter() {
// Nothing
}
/**
* @this
*/
Object.assign(Filter.prototype, {
condition: () => true,
useFilter(friends) {
return friends.filter(this.condition);
}
});
/**
* Фильтр друзей
* @extends Filter
* @constructor
*/
function MaleFilter() {
// Nothing
}
Object.setPrototypeOf(MaleFilter.prototype, Filter.prototype);
Object.assign(MaleFilter.prototype, {
condition: x => x.gender === 'male'
});
/**
* Фильтр друзей-девушек
* @extends Filter
* @constructor
*/
function FemaleFilter() {
// Nothing
}
Object.setPrototypeOf(FemaleFilter.prototype, Filter.prototype);
Object.assign(FemaleFilter.prototype, {
condition: x => x.gender === 'female'
});
exports.Iterator = Iterator;
exports.LimitedIterator = LimitedIterator;
exports.Filter = Filter;
exports.MaleFilter = MaleFilter;
exports.FemaleFilter = FemaleFilter;
| c863c4ee401a53c3abbed8139e4c959b770fb24a | [
"JavaScript"
] | 1 | JavaScript | whoe/javascript-task-6 | 15862bdc19a8fb356a5110515af3adb5393e678c | dde4e50e70d29f5e737c9e9fa3299cc02bee5a01 |
refs/heads/master | <file_sep>
/********************
In this exercise, we will be creating a function that takes in two numbers and returns the sum
Step 1. Create and declare a function,
that takes in two parameters
Step 2. In the function body, add both
numbers together and return the sum
Step 3. Call the function
For extra credit, create a conditional that executes a message if the sum is over 10 or less than 100
********************/
// Your Solution:
function sum(a, b){
return a+b;
}
var res = sum(11,5);
if(res>10){
console.log("Sum is greater than 10: "+ res);
}else{
console.log("Sum is less than 10: "+ res);
}
| 9be7966802bdad8668f1c6c40c7aa84a4295ad59 | [
"JavaScript"
] | 1 | JavaScript | askappsacademy/session-2-1-arthiatsr | 7a9b20475f669b1ff06a9c7f0792a3a836c5c7fd | 2977f90b8c88e6ae7d03a2ec4197ec5629bd3cad |
refs/heads/master | <repo_name>harish1227/DFNT<file_sep>/README.md
<!--# DFNT
project loading
use git push -f github master to push files -->
<file_sep>/config.js
const
action = require( 'tempaw-functions' ).action,
preset = require( './custom-presets' );
module.exports = {
livedemo: {
enable: true,
server: {
baseDir: `dev/`,
directory: false
},
port: 8000,
open: false,
notify: true,
reloadDelay: 0,
ghostMode: {
clicks: false,
forms: false,
scroll: false
}
},
sass: {
enable: true,
showTask: false,
watch: `dev/**/*.scss`,
source: `dev/**/!(_)*.scss`,
dest: `dev/`,
options: {
outputStyle: 'expanded',
indentType: 'tab',
indentWidth: 1,
linefeed: 'cr'
}
},
pug: {
enable: true,
showTask: false,
watch: `dev/**/*.pug`,
source: `dev/pages/!(_)*.pug`,
dest: `dev/`,
options: {
pretty: true,
verbose: true,
self: true,
emitty: true
}
},
autoprefixer: {
enable: false,
options: {
cascade: true,
browsers: ['Chrome >= 45', 'Firefox ESR', 'Edge >= 12', 'Explorer >= 10', 'iOS >= 9', 'Safari >= 9', 'Android >= 4.4', 'Opera >= 30']
}
},
watcher: {
enable: true,
watch: `dev/**/*.js`
},
lint: {
showTask: true,
sass: 'dev/components/!(bootstrap)/**/*.scss',
pug: 'dev/**/*.pug',
js: 'dev/**/!(*.min).js',
html: 'dev/**/*.html'
},
buildRules: {
// Project build recommendation
// Gulp Settings >> Node options >> --max-old-space-size=4096
'Build Livedemo': [
// Clean dist
action.clean({ src: 'dist/livedemo/site/v2' }),
// Copy files to a temporary folder
action.copy({
src: [
'dev/**/*.pug',
'dev/**/*.scss',
'dev/**/*.js'
],
dest: 'tmp'
}),
// Deleting code fragments
action.delMarker({
src: [
'tmp/**/*.pug',
'tmp/**/*.scss',
'tmp/**/*.js'
],
dest: 'tmp',
marker: 'DIST'
}),
// Copy css
action.copy({
src: 'dev/**/*.css',
dest: 'dist/livedemo/site/v2/'
}),
// Compile sass
action.sass({
src: 'tmp/**/*.scss',
dest: 'dist/livedemo/site/v2/',
autoprefixer: false
}),
// Compile pug
action.pug({
src: `tmp/pages/!(_)*.pug`,
dest: 'dist/livedemo/site/v2/'
}),
// Copy js files
action.copy({
src: 'tmp/**/*.js',
dest: 'dist/livedemo/site/v2/'
}),
// Copy fonts
action.copy({
src: [
'dev/**/*.otf',
'dev/**/*.eot',
'dev/**/*.svg',
'dev/**/*.ttf',
'dev/**/*.woff',
'dev/**/*.woff2'
],
dest: 'dist/livedemo/site/v2/'
}),
// Copy & minify images
action.minifyimg({
src: [
'dev/**/*.png',
'dev/**/*.jpg',
'dev/**/*.gif'
],
dest: 'dist/livedemo/site/v2/'
}),
// Copy other files
action.copy({
src: [
'dev/**/*.ico',
'dev/**/*.php',
'dev/**/*.json',
'dev/**/*.txt',
'dev/**/*.mp4'
],
dest: 'dist/livedemo/site/v2/'
}),
// Delete temporary folder
action.clean({ src: 'tmp' })
],
'Build Granter': [
// Clean dist
action.clean({ src: 'dist/granter/v2' }),
// GRANTER
// Copy dev
action.copy({
src: [
'dev/**/*.pug',
'dev/**/*.scss',
'dev/**/*.html',
'dev/**/*.css',
'dev/**/*.js',
'dev/**/*.otf',
'dev/**/*.eot',
'dev/**/*.svg',
'dev/**/*.ttf',
'dev/**/*.woff',
'dev/**/*.woff2',
'dev/**/*.png',
'dev/**/*.jpg',
'dev/**/*.gif',
'dev/**/*.ico',
'dev/**/*.php',
'dev/**/*.tpl',
'dev/**/*.json',
'dev/**/*.txt',
'dev/**/*.mp4'
],
dest: 'dist/granter/v2/dev'
}),
// Copy project files
action.copy({
src: [
'config.js',
'gulpfile.js',
'package.json'
],
dest: 'dist/granter/v2'
})
],
'To Builder': [
preset.builderThrow({
dev: 'dev',
builder: 'builder',
pages: 'index.html',
debug: true
})
]
}
};
| c357ef729d8ae8f35faf71d928f4076db2794625 | [
"Markdown",
"JavaScript"
] | 2 | Markdown | harish1227/DFNT | 9af895d9bb6f6c340264ab9defdde6bcc5fc3ebd | 88b360e6f7a2651797a173b24a6a07bbdd42fed0 |
refs/heads/main | <repo_name>simbathesailor/react<file_sep>/fixtures/flight/src/cjs/Counter3.js
'use client';
const {Counter} = require('../Counter.js');
module.exports = Promise.resolve(Counter);
<file_sep>/fixtures/flight/src/Container.js
import * as React from 'react';
export default function Container({children}) {
console.log('In the container');
return <div>{children}</div>;
}
| 27b8bc7844dbb4ee13b98dbe60b32c27694af592 | [
"JavaScript"
] | 2 | JavaScript | simbathesailor/react | 684166dd919209797b89696f79f17f87cf1467a6 | 1d71d58b0e39f798e57666e4b0643dc99722e056 |
refs/heads/master | <repo_name>gspandy/Rythm<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ContinueParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
public class ContinueParser extends KeywordParserFactory {
private static final String R = "^(%s%s\\s*(\\(\\s*\\))?[\\s;]*)";
public ContinueParser() {
}
protected String patternStr() {
return R;
}
public IParser create(IContext c) {
return new ParserBase(c) {
public TextBuilder go() {
Regex r = reg(dialect());
if (r.search(remain())) {
step(r.stringMatched().length());
IContext.Continue c = ctx().peekContinue();
if (null == c) raiseParseException("Bad @continue statement: No loop context");
return new CodeToken(c.getStatement(), ctx());
}
raiseParseException("Bad @continue statement. Correct usage: @continue()");
return null;
}
};
}
@Override
public Keyword keyword() {
return Keyword.CONTINUE;
}
public static void main(String[] args) {
Regex r = new ContinueParser().reg(new Rythm());
String s = "@continue()\n\tdd";
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/utils/IImplicitRenderArgProvider.java
package com.greenlaw110.rythm.utils;
import com.greenlaw110.rythm.template.ITemplate;
import java.util.List;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 2/02/12
* Time: 1:07 PM
* To change this template use File | Settings | File Templates.
*/
public interface IImplicitRenderArgProvider {
Map<String, ?> getRenderArgDescriptions();
void setRenderArgs(ITemplate template);
List<String> getImplicitImportStatements();
}
<file_sep>/src/main/java/com/greenlaw110/rythm/cache/NoCacheService.java
package com.greenlaw110.rythm.cache;
import java.io.Serializable;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 2/05/12
* Time: 8:37 PM
* To change this template use File | Settings | File Templates.
*/
public class NoCacheService implements ICacheService {
public static NoCacheService INSTANCE = new NoCacheService();
private NoCacheService() {}
@Override
public void put(String key, Serializable value, int ttl) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void put(String key, Serializable value) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Serializable remove(String key) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Serializable get(String key) {
return null; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public boolean contains(String key) {
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void clean() {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void setDefaultTTL(int ttl) {
//To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void shutdown() {
//To change body of implemented methods use File | Settings | File Templates.
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/internal/parser/build_in/StringTokenParserTest.java
package com.greenlaw110.rythm.internal.parser.build_in;
import org.junit.Test;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.ut.UnitTest;
import com.greenlaw110.rythm.utils.TextBuilder;
public class StringTokenParserTest extends UnitTest {
private void t(String exp, String output) {
setup(exp);
IParser p = new StringTokenParser(c);
TextBuilder builder = p.go();
assertNotNull(builder);
builder.build();
assertEquals(output, b.toString());
}
@Test
public void test() {
t("Hello world <a href=\"ddd\">xyz</a> @each ...", "\np(\"Hello world <a href=\\\"ddd\\\">xyz</a> \");");
}
@Test
public void testCaretEscape1() {
t("greenl@@ibm.com", "\np(\"greenl\");");
}
@Test
public void test2testCaretEscape2() {
t("@@ibm.com", "\np(\"@ibm.com\");");
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/template/TemplateBase.java
package com.greenlaw110.rythm.template;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.exception.FastRuntimeException;
import com.greenlaw110.rythm.exception.RythmException;
import com.greenlaw110.rythm.internal.TemplateBuilder;
import com.greenlaw110.rythm.internal.compiler.ClassReloadException;
import com.greenlaw110.rythm.internal.compiler.TemplateClass;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.resource.ITemplateResource;
import com.greenlaw110.rythm.runtime.ITag;
import com.greenlaw110.rythm.utils.IO;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.io.*;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public abstract class TemplateBase extends TemplateBuilder implements ITemplate {
protected final ILogger logger = Logger.get(TemplateBase.class);
protected transient RythmEngine engine = null;
private transient TemplateClass templateClass = null;
public void setTemplateClass(TemplateClass templateClass) {
this.templateClass = templateClass;
__ctx.init(this);
}
protected S s() {
return S.INSTANCE;
}
protected RythmEngine r() {
return engine;
}
protected Map<String, Object> _properties = new HashMap<String, Object>();
protected RythmEngine _engine() {
return null == engine ? Rythm.engine : engine;
}
protected void _invokeTag(String name) {
engine.invokeTag(name, this, null, null, null);
}
protected void _invokeTag(String name, boolean ignoreNonExistsTag) {
engine.invokeTag(name, this, null, null, null, ignoreNonExistsTag);
}
protected void _invokeTag(String name, ITag.ParameterList params) {
engine.invokeTag(name, this, params, null, null);
}
protected void _invokeTag(String name, ITag.ParameterList params, boolean ignoreNonExistsTag) {
engine.invokeTag(name, this, params, null, null, ignoreNonExistsTag);
}
protected void _invokeTag(String name, ITag.ParameterList params, ITag.Body body) {
engine.invokeTag(name, this, params, body, null);
}
protected void _invokeTag(String name, ITag.ParameterList params, ITag.Body body, boolean ignoreNoExistsTag) {
engine.invokeTag(name, this, params, body, null, ignoreNoExistsTag);
}
protected void _invokeTag(String name, ITag.ParameterList params, ITag.Body body, ITag.Body context) {
engine.invokeTag(name, this, params, body, context);
}
protected void _invokeTag(String name, ITag.ParameterList params, ITag.Body body, ITag.Body context, boolean ignoreNonExistsTag) {
engine.invokeTag(name, this, params, body, context, ignoreNonExistsTag);
}
/* to be used by dynamic generated sub classes */
private String layoutContent = "";
private Map<String, String> layoutSections = new HashMap<String, String>();
private Map<String, Object> renderProperties = new HashMap<String, Object>();
protected TemplateBase __parent = null;
public TemplateBase() {
super();
Class<? extends TemplateBase> c = getClass();
Class<?> pc = c.getSuperclass();
if (TemplateBase.class.isAssignableFrom(pc) && !Modifier.isAbstract(pc.getModifiers())) {
try {
__parent = (TemplateBase) pc.newInstance();
__parent.setTemplateClass(_engine().classes.getByClassName(pc.getName()));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
protected RawData _render(String template, Object... args) {
if (null == template) return new RawData("");
return S.raw(engine.render(template, args));
}
protected RawData _render(String template) {
if (null == template) return new RawData("");
return S.raw(engine.render(template, _properties));
}
protected final void setLayoutContent(String body) {
layoutContent = body;
}
private void addLayoutSection(String name, String section, boolean def) {
if (def && layoutSections.containsKey(name)) return;
layoutSections.put(name, section);
}
private StringBuilder tmpOut = null;
private String section = null;
private TextBuilder tmpCaller = null;
protected void _startSection(String name) {
if (null == name) throw new NullPointerException("section name cannot be null");
if (null != tmpOut) throw new IllegalStateException("section cannot be nested");
tmpCaller = _caller;
_caller = null;
tmpOut = _out;
_out = new StringBuilder();
section = name;
}
protected void _endSection() {
_endSection(false);
}
protected void _endSection(boolean def) {
if (null == tmpOut && null == tmpCaller) throw new IllegalStateException("section has not been started");
addLayoutSection(section, _out.toString(), def);
_out = tmpOut;
_caller = tmpCaller;
tmpOut = null;
tmpCaller = null;
}
protected void _pLayoutSection(String name) {
p(layoutSections.get(name));
}
protected RawData _getSection(String name) {
return S.raw(layoutSections.get(name));
}
protected RawData _getSection() {
return S.raw(S.isEmpty(layoutContent) ? layoutSections.get("__CONTENT__") : layoutContent);
}
protected void _pLayoutContent() {
p(_getSection());
}
private void addAllLayoutSections(Map<String, String> sections) {
if (null != sections) layoutSections.putAll(sections);
}
private void addAllRenderProperties(Map<String, Object> properties) {
if (null != properties) renderProperties.putAll(properties);
}
protected TemplateBase internalClone() {
try {
return (TemplateBase)super.clone();
} catch (CloneNotSupportedException e) {
throw new RuntimeException();
}
}
@Override
public ITemplate cloneMe(RythmEngine engine, ITemplate caller) {
if (null == engine) throw new NullPointerException();
TemplateBase tmpl = internalClone();
if (tmpl.__parent != null) {
tmpl.__parent = (TemplateBase) tmpl.__parent.cloneMe(engine, caller);
}
tmpl.engine = engine;
tmpl.templateClass = templateClass;
if (null != caller) {
tmpl._caller = (TextBuilder)caller;
}
tmpl.__ctx = new Context(__ctx);
//if (null != out) tmpl._out = out;
if (null != _out) tmpl._out = new StringBuilder();
tmpl._properties = new HashMap<String, Object>(_properties.size());
tmpl.layoutContent = "";
tmpl.layoutSections = new HashMap<String, String>();
tmpl.renderProperties = new HashMap<String, Object>();
tmpl.section = null;
tmpl.tmpCaller = null;
tmpl.tmpOut = null;
tmpl._logTime = _logTime;
return tmpl;
}
protected void internalInit() {
loadExtendingArgs();
init();
}
protected void setup() {
}
protected void loadExtendingArgs() {
}
@Override
public void init() {
}
private boolean _logTime() {
return _logTime || engine.logRenderTime;
}
public TemplateClass getTemplateClass(boolean useCaller) {
TemplateClass tc = templateClass;
if (useCaller && null == tc) {
TemplateBase caller = caller();
if (null != caller) return caller.getTemplateClass(true);
}
return tc;
}
@Override
public final String render() {
try {
long l = 0l;
if (_logTime()) {
l = System.currentTimeMillis();
}
engine.preprocess(this);
setup();
if (_logTime()) {
_logger.debug("< preprocess [%s]: %sms", getClass().getName(), System.currentTimeMillis() - l);
l = System.currentTimeMillis();
}
String s = internalRender();
if (_logTime()) {
_logger.debug("<<<<<<<<<<<< [%s] total render: %sms", getClass().getName(), System.currentTimeMillis() - l);
}
return s;
} catch (ClassReloadException e) {
if (_logger.isDebugEnabled()) {
_logger.debug("Cannot hotswap class, try to restart engine...");
}
engine.restart(e);
return render();
} catch (ClassCastException e) {
if (_logger.isDebugEnabled()) {
_logger.debug("ClassCastException found, force refresh template and try again...");
}
TemplateClass tc = engine.classes.getByClassName(getClass().getName());
tc.refresh(true);
ITemplate t = tc.asTemplate();
return t.render();
}
}
private Writer w_ = null;
protected void _setOutput(String path) {
try {
w_ = new BufferedWriter(new FileWriter(path));
} catch (Exception e) {
throw new FastRuntimeException(e.getMessage());
}
}
protected void _setOutput(File file) {
try {
w_ = new BufferedWriter(new FileWriter(file));
} catch (Exception e) {
throw new FastRuntimeException(e.getMessage());
}
}
protected void _setOutput(OutputStream os) {
w_ = new OutputStreamWriter(os);
}
protected void _setOutput(Writer w) {
w_ = w;
}
protected void internalBuild() {
w_ = null; // reset output destination
//if (!(engine.recordTemplateSourceOnError || engine.recordJavaSourceOnError)) {
if (false) {
internalInit();
build();
} else {
try {
try {
long l = 0l;
if (_logTime()) {
l = System.currentTimeMillis();
}
internalInit();
build();
if (_logTime()) {
_logger.debug("<<<<<<<<<<<< [%s] build: %sms", getClass().getName(), System.currentTimeMillis() - l);
}
} catch (RythmException e) {
throw e;
} catch (Exception e) {
StackTraceElement[] stackTrace = e.getStackTrace();
String msg = null;
for (StackTraceElement se : stackTrace){
String cName = se.getClassName();
if (cName.contains(TemplateClass.CN_SUFFIX)) {
// is it the embedded class?
if (cName.indexOf("$") != -1) {
cName = cName.substring(0, cName.lastIndexOf("$"));
}
TemplateClass tc = engine.classes.getByClassName(cName);
if (null == tc) {
continue;
}
if (null == msg) {
msg = e.getMessage();
if (S.isEmpty(msg)) {
msg = "Rythm runtime exception caused by " + e.getClass().getName();
//System.out.println("<<<<<" + msg);
}
}
RythmException re = new RythmException(engine, e, tc, se.getLineNumber(), -1, msg);
if (engine.logSourceInfoOnRuntimeError) {
Logger.error("Error executing template: %2$s. \n%1$s\n%2$s", re.javaSourceInfo(), re.templateSourceInfo(), msg);
}
int lineNo = re.templateLineNumber;
String key = tc.getKey().toString();
int i = key.indexOf('\n');
if (i == -1) i = key.indexOf('\r');
if (i > -1) {
key = key.substring(0, i - 1) + "...";
}
if (key.length() > 80) key = key.substring(0, 80) + "...";
if (lineNo != -1) {
StackTraceElement[] newStack = new StackTraceElement[stackTrace.length + 1];
newStack[0] = new StackTraceElement(tc.name(), "", key, lineNo);
System.arraycopy(stackTrace, 0, newStack, 1, stackTrace.length);
re.setStackTrace(newStack);
}
throw re;
}
}
throw (e instanceof RuntimeException ? (RuntimeException)e : new RuntimeException(e));
}
} catch (RuntimeException e) {
// try to restart engine
try {
engine.restart(e);
} catch (RuntimeException e0) {
// ignore it because we already thrown it out
}
throw e;
}
}
if (null != w_) {
try {
IO.writeContent(toString(), w_);
w_ = null;
} catch (Exception e) {
Logger.error(e, "failed to write template content to output destination");
}
}
}
protected String internalRender() {
internalBuild();
if (null != __parent) {
__parent.setLayoutContent(toString());
__parent.addAllLayoutSections(layoutSections);
__parent.addAllRenderProperties(renderProperties);
__parent._properties.putAll(_properties);
return __parent.render();
} else {
return toString();
}
}
public TextBuilder build() {
return this;
}
@Override
public void setRenderArgs(Map<String, Object> args) {
_properties.putAll(args);
}
protected void setRenderArgs(ITag.ParameterList params) {
for (int i = 0; i < params.size(); ++i) {
ITag.Parameter param = params.get(i);
if (null != param.name) setRenderArg(param.name, param.value);
else setRenderArg(i, param.value);
}
}
@Override
public void setRenderArgs(Object... args) {
}
@Override
public void setRenderArg(String name, Object arg) {
_properties.put(name, arg);
}
protected final void _set(String name, Object arg) {
setRenderArg(name, arg);
}
protected final TemplateBase caller() {
return null == _caller ? null : (TemplateBase)_caller;
}
@Override
public <T> T getRenderArg(String name) {
Object val = _properties.get(name);
return (T)(null != val ? val : (null != _caller ? caller().getRenderArg(name) : null));
}
protected final <T> T _get(String name) {
return getRenderArg(name);
}
protected final <T> T _getAs(String name, Class<T> c) {
Object o = getRenderArg(name);
if (null == o) return null;
return (T)o;
}
protected final <T> T _getRenderProperty(String name, Object def) {
Object o = renderProperties.get(name);
return (T)(null == o ? def : o);
}
protected final <T> T _getRenderProperty(String name) {
return (T)_getRenderProperty(name, null);
}
protected final <T> T _getRenderPropertyAs(String name, T def) {
Object o = _getRenderProperty(name, def);
return null == o ? def : (T)o;
}
protected final void _setRenderProperty(String name, Object val) {
renderProperties.put(name, val);
}
protected final void handleTemplateExecutionException(Exception e) {
try {
_engine().handleTemplateExecutionException(e, this);
} catch (RuntimeException e0) {
throw e0;
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
@Override
public Map<String, Object> getRenderArgs() {
return new HashMap<String, Object>(_properties);
}
@Override
public void setRenderArg(int position, Object arg) {
}
public Context __ctx = new Context();
public final TemplateBase pe(Object o) {
if (null == o) return this;
if (o instanceof ITemplate.RawData) {
return (TemplateBase)p(o);
}
ITemplate.Escape escape = __ctx.currentEscape();
return pe(o, escape);
}
public final TemplateBase pe(Object o, ITemplate.Escape escape) {
if (null == o) return this;
if (o instanceof ITemplate.RawData) {
return (TemplateBase)p(o);
}
if (null == escape) escape = __ctx.currentEscape();
return (TemplateBase)super.pe(o, escape);
}
// --- debugging interface
protected static ILogger _logger = Logger.get(TemplateBase.class);
protected static void _log(String msg, Object... args) {
_logger.info(msg, args);
}
protected static void _debug(String msg, Object... args) {
_logger.debug(msg, args);
}
protected static void _info(String msg, Object... args) {
_logger.info(msg, args);
}
protected static void _warn(String msg, Object... args) {
_logger.error(msg, args);
}
protected static void _warn(Throwable t, String msg, Object... args) {
_logger.error(t, msg, args);
}
protected static void _error(String msg, Object... args) {
_logger.error(msg, args);
}
protected static void _error(Throwable t, String msg, Object... args) {
_logger.error(t, msg, args);
}
protected boolean _logTime = false;
protected static class _Itr<T> implements Iterable<T> {
private Object _o;
private int _size = -1;
private Iterator<T> iterator = null;
private int cursor = 0;
public _Itr(T[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return ((T[])_o)[cursor++]; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(int[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Integer)((int[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(long[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Long)((long[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(float[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Float)((float[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(double[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Double)((double[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(short[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Short)((short[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(char[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Character)((char[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(byte[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Byte)((byte[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(boolean[] ta) {
_o = ta;
_size = ta.length;
iterator = new Iterator<T>() {
@Override
public boolean hasNext() {
return cursor < _size;
}
@Override
public T next() {
return (T)((Boolean)((boolean[])_o)[cursor++]);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
};
}
public _Itr(Iterable<T> tc) {
_o = tc;
if (tc instanceof Collection) {
_size = ((Collection)tc).size();
} else {
int i = 0;
for (Iterator itr = tc.iterator();itr.hasNext();itr.next()) { i++;}
_size = i;
}
iterator = tc.iterator();
}
public int size() {
return _size;
}
@Override
public Iterator<T> iterator() {
return iterator;
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/dialect/DialectManager.java
package com.greenlaw110.rythm.internal.dialect;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IDialect;
import com.greenlaw110.rythm.spi.IParserFactory;
import java.util.*;
public class DialectManager {
protected ILogger logger = Logger.get(DialectManager.class);
IDialect def = null;
public DialectManager() {
def = new Rythm();
}
static ThreadLocal<Stack<IDialect>> threadLocal = new ThreadLocal<Stack<IDialect>>(); static {
Stack<IDialect> stack = new Stack<IDialect>();
stack.push(new Rythm());
threadLocal.set(stack);
}
static IDialect[] dialects = {
new SimpleRythm(),
new Rythm()
};
private Stack<IDialect> dialectStack() {
Stack<IDialect> stack = threadLocal.get();
if (null == stack) {
stack = new Stack<IDialect>();
threadLocal.set(stack);
}
return stack;
}
public IDialect get() {
Stack<IDialect> stack = dialectStack();
return stack.empty() ? null : stack.peek();
}
public void pushDef() {
dialectStack().push(def);
}
public void push(IDialect dialect) {
dialectStack().push(dialect);
}
public IDialect pop(){
Stack<IDialect> stack = dialectStack();
return stack.empty() ? null : stack.pop();
}
public IDialect get(String id) {
if (null == id || "rythm".equalsIgnoreCase(id)) return def;
return null;
}
public void beginParse(IContext ctx) {
IDialect d = ctx.getCodeBuilder().dialect;
if (null != d) {
push(d);
d.begin(ctx);
} else {
String template = ctx.getRemain();
for (IDialect d0: dialects) {
if (d0.isMyTemplate(template)) {
push(d0);
d0.begin(ctx);
d = d0;
break;
}
}
}
d = get();
List<IParserFactory> l = externalParsers.get(d);
if (null != l) {
for (IParserFactory pf: l) {
d.registerParserFactory(pf);
}
}
}
public void endParse(IContext ctx) {
IDialect d = pop();
d.end(ctx);
}
static Map<String, IDialect> dialectIdMap = new HashMap<String, IDialect>(); static {
for (IDialect dialect: dialects) {
dialectIdMap.put(dialect.id(), dialect);
}
}
private Map<IDialect, List<IParserFactory>> externalParsers = new HashMap<IDialect, List<IParserFactory>>() ;
public void registerExternalParsers(String dialect, IParserFactory... factories) {
if (null == dialect) dialect = "rythm";
IDialect d = dialectIdMap.get(dialect);
if (null == d) {
throw new IllegalArgumentException("dialect not found: " + dialect);
}
externalParsers.put(d, Arrays.asList(factories));
for (IParserFactory f: factories) {
def.registerParserFactory(f);
}
}
}
<file_sep>/samples/JavaTag/JavaTags.java
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.runtime.ITag;
import com.greenlaw110.rythm.template.JavaTagBase;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 29/04/12
* Time: 6:42 PM
* To change this template use File | Settings | File Templates.
*/
public abstract class JavaTags {
public static class Hello extends JavaTagBase {
@Override
public String getName() {
return "hello";
}
@Override
protected void call(ParameterList params, Body body) {
Object o = params.getDefault();
String who = null == o ? "who" : o.toString();
p("Hello ").p(who);
}
}
public static class Bye extends JavaTagBase {
@Override
public String getName() {
return "bye";
}
@Override
protected void call(ParameterList params, Body body) {
Object o = params.getDefault();
String who = null == o ? "who" : o.toString();
p("bye ").p(who);
if (null != body) body.render(out(), who);
}
}
public static void main(String[] args) {
Rythm.registerTag(new Hello());
Rythm.registerTag(new Bye());
String s = Rythm.render("javaTagDemo.txt");
System.out.println(s);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/RythmEngine.java
package com.greenlaw110.rythm;
import com.greenlaw110.rythm.cache.ICacheService;
import com.greenlaw110.rythm.cache.NoCacheService;
import com.greenlaw110.rythm.exception.RythmException;
import com.greenlaw110.rythm.exception.TagLoadException;
import com.greenlaw110.rythm.internal.CodeBuilder;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.compiler.*;
import com.greenlaw110.rythm.internal.dialect.AutoToString;
import com.greenlaw110.rythm.internal.dialect.DialectManager;
import com.greenlaw110.rythm.internal.dialect.ToString;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.ILoggerFactory;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.resource.*;
import com.greenlaw110.rythm.runtime.ITag;
import com.greenlaw110.rythm.spi.*;
import com.greenlaw110.rythm.template.ITemplate;
import com.greenlaw110.rythm.template.JavaTagBase;
import com.greenlaw110.rythm.template.TagBase;
import com.greenlaw110.rythm.template.TemplateBase;
import com.greenlaw110.rythm.toString.ToStringOption;
import com.greenlaw110.rythm.toString.ToStringStyle;
import com.greenlaw110.rythm.utils.*;
import java.io.File;
import java.io.FileFilter;
import java.io.InputStream;
import java.io.Serializable;
import java.net.URL;
import java.util.*;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 20/01/12
* Time: 8:13 PM
* To change this template use File | Settings | File Templates.
*/
public class RythmEngine {
public static final String version = "1.0.0-x";
public static String pluginVersion = "";
Rythm.ReloadMethod reloadMethod = Rythm.ReloadMethod.RESTART;
public boolean reloadByRestart() {
return isDevMode() && reloadMethod == Rythm.ReloadMethod.RESTART;
}
public boolean reloadByIncClassVersion() {
return isDevMode() && (reloadMethod == Rythm.ReloadMethod.V_VERSION);
}
public boolean loadPreCompiled() {
return loadPreCompiled;
}
public boolean classCacheEnabled() {
return preCompiling || loadPreCompiled() || (!noFileWrite && reloadByRestart());
}
public static String versionSignature() {
return version + "-" + pluginVersion;
}
private final ILogger logger = Logger.get(RythmEngine.class);
public Rythm.Mode mode;
public final RythmProperties configuration = new RythmProperties();
public final TemplateResourceManager resourceManager = new TemplateResourceManager(this);
public final TemplateClassManager classes = new TemplateClassManager(this);
public TemplateClassLoader classLoader = null;
public TemplateClassCache classCache = new TemplateClassCache(this);
public IByteCodeHelper byteCodeHelper = null;
public IHotswapAgent hotswapAgent = null;
public boolean logRenderTime = false;
private boolean loadPreCompiled = false;
public boolean preCompiling = false;
public boolean playHost = false;
public boolean recordJavaSourceOnError = false;
public boolean recordTemplateSourceOnError = true;
public boolean recordJavaSourceOnRuntimeError = false;
public boolean recordTemplateSourceOnRuntimeError = true;
public boolean logSourceInfoOnRuntimeError = false;
public IImplicitRenderArgProvider implicitRenderArgProvider = null;
/**
* If this is set to true then @cacheFor() {} only effective on product mode
*/
public boolean cacheOnProdOnly = true;
/**
* Default Time to live for cache items
*/
public int defaultTTL = 60 * 60;
public ICacheService cacheService = null;
public IDurationParser durationParser = null;
/**
* Enable refresh resource on render. This could be turned off
* if the resource reload service is managed by container, e.g. Play!framework
*/
private boolean refreshOnRender = true;
public boolean refreshOnRender() {
return refreshOnRender && !isProdMode();
}
/**
* When compactMode is true, then by default redundant spaces/line breaks are removed
*/
private boolean compactMode = true;
public boolean compactMode() {
return compactMode;
}
/**
* enable java extensions to expressions, e.g. @myvar.escapeHtml() or @myvar.pad(5) etc.
* <p/>
* disable java extension can improve parse performance
*/
private boolean enableJavaExtensions = true;
/**
* Some context doesn't allow file write, e.g. GAE
*/
public boolean noFileWrite = false;
public boolean enableJavaExtensions() {
return enableJavaExtensions;
}
public File tmpDir;
public File templateHome;
public File tagHome;
private File preCompiledHome;
public File preCompiledHome() {
return preCompiledHome;
}
public FileFilter tagFileFilter;
public final List<IRythmListener> listeners = new ArrayList<IRythmListener>();
public void registerListener(IRythmListener listener) {
if (null == listener) throw new NullPointerException();
if (!listeners.contains(listener)) listeners.add(listener);
}
public void unregisterListener(IRythmListener listener) {
if (null == listener) throw new NullPointerException();
listeners.remove(listener);
}
public void clearListener() {
listeners.clear();
}
public final List<ITemplateClassEnhancer> templateClassEnhancers = new ArrayList<ITemplateClassEnhancer>();
public void registerTemplateClassEnhancer(ITemplateClassEnhancer enhancer) {
if (null == enhancer) throw new NullPointerException();
if (!templateClassEnhancers.contains(enhancer)) templateClassEnhancers.add(enhancer);
}
public void unregisterTemplateClassEnhancer(ITemplateClassEnhancer enhancer) {
if (null == enhancer) throw new NullPointerException();
templateClassEnhancers.remove(enhancer);
}
public void clearTemplateClassEnhancer() {
templateClassEnhancers.clear();
}
public RythmEngine(File templateHome) {
this(templateHome, null);
}
public RythmEngine(File templateHome, File tagHome) {
init();
this.templateHome = templateHome;
this.tagHome = tagHome;
}
public RythmEngine(Properties userConfiguration) {
init(userConfiguration);
}
public RythmEngine() {
init();
}
public boolean isSingleton() {
return Rythm.engine == this;
}
public boolean isProdMode() {
return mode == Rythm.Mode.prod;
}
public boolean isDevMode() {
return mode != Rythm.Mode.prod;
}
private void setConf(String key, Object val) {
configuration.put(key, val);
}
private void loadDefConf() {
setConf("rythm.mode", Rythm.Mode.prod);
setConf("rythm.loader", "file");
}
public void init() {
init(null);
}
public void init(Properties conf) {
loadDefConf();
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (null == cl) cl = Rythm.class.getClassLoader();
URL url = cl.getResource("rythm.conf");
if (null != url) {
InputStream is = null;
try {
is = url.openStream();
configuration.load(is);
} catch (Exception e) {
logger.warn(e, "Error loading rythm.conf");
} finally {
try {
if (null != is) is.close();
} catch (Exception e) {
//ignore
}
}
}
if (null != conf) configuration.putAll(conf);
ILoggerFactory fact = configuration.getAs("rythm.logger.factory", null, ILoggerFactory.class);
if (null != fact) Logger.registerLoggerFactory(fact);
pluginVersion = configuration.getProperty("rythm.pluginVersion", "");
recordJavaSourceOnError = configuration.getAsBoolean("rythm.recordJavaSourceOnError", false);
recordTemplateSourceOnError = configuration.getAsBoolean("rythm.recordTemplateSourceOnError", true);
recordJavaSourceOnRuntimeError = configuration.getAsBoolean("rythm.recordJavaSourceOnRuntimeError", false);
recordTemplateSourceOnRuntimeError = configuration.getAsBoolean("rythm.recordTemplateSourceOnRuntimeError", true);
logSourceInfoOnRuntimeError = configuration.getAsBoolean("rythm.logSourceInfoOnRuntimeError", false);
refreshOnRender = configuration.getAsBoolean("rythm.resource.refreshOnRender", true);
enableJavaExtensions = configuration.getAsBoolean("rythm.enableJavaExtensions", true);
noFileWrite = configuration.getAsBoolean("rythm.noFileWrite", false);
logger.debug(">>>>no file write is: %s", noFileWrite);
tmpDir = noFileWrite ? null : configuration.getAsFile("rythm.tmpDir", IO.tmpDir());
logger.debug(">>>>temp dir is: %s", tmpDir);
// if templateHome set to null then it assumes use ClasspathTemplateResource by default
templateHome = configuration.getAsFile("rythm.root", null);
tagHome = configuration.getAsFile("rythm.tag.root", null);
tagFileFilter = configuration.getAsFileFilter("rythm.tag.fileNameFilter", new FileFilter() {
@Override
public boolean accept(File pathname) {
return true; // by default accept all files
}
});
mode = configuration.getAsMode("rythm.mode", Rythm.Mode.prod);
compactMode = configuration.getAsBoolean("rythm.compactOutput", isProdMode());
reloadMethod = configuration.getAsReloadMethod("rythm.reloadMethod", Rythm.ReloadMethod.RESTART);
loadPreCompiled = configuration.getAsBoolean("rythm.loadPreCompiled", false);
preCompiledHome = configuration.getAsFile("rythm.preCompiled.root", null);
logRenderTime = configuration.getAsBoolean("rythm.logRenderTime", false);
if (Rythm.ReloadMethod.V_VERSION == reloadMethod) {
logger.warn("Rythm reload method set to increment class version, this will cause template class cache disabled.");
}
defaultTTL = configuration.getAsInt("rythm.cache.defaultTTL", 60 * 60);
cacheService = configuration.getAsCacheService("rythm.cache.service");
cacheService.setDefaultTTL(defaultTTL);
durationParser = configuration.getAsDurationParser("rythm.cache.durationParser");
cacheOnProdOnly = configuration.getAsBoolean("rythm.cache.prodOnly", true);
cl = configuration.getAs("rythm.classLoader.parent", cl, ClassLoader.class);
classLoader = new TemplateClassLoader(cl, this);
classes.clear();
tags.clear();
tags.put("chain", new JavaTagBase() {
@Override
protected void call(ParameterList params, Body body) {
body.render(getOut());
}
});
//defaultRenderArgs = configuration.getAs("rythm.defaultRenderArgs", null, Map.class);
implicitRenderArgProvider = configuration.getAs("rythm.implicitRenderArgProvider", null, IImplicitRenderArgProvider.class);
byteCodeHelper = configuration.getAs("rythm.classLoader.byteCodeHelper", null, IByteCodeHelper.class);
hotswapAgent = configuration.getAs("rythm.classLoader.hotswapAgent", null, IHotswapAgent.class);
playHost = configuration.getAsBoolean("rythm.playHost", false);
Object o = configuration.get("rythm.resource.loader");
if (o instanceof ITemplateResourceLoader) {
resourceManager.resourceLoader = (ITemplateResourceLoader) o;
} else if (o instanceof String) {
try {
resourceManager.resourceLoader = (ITemplateResourceLoader) Class.forName(((String) o)).newInstance();
} catch (Exception e) {
logger.warn("invalid resource loader class");
}
}
if (null != tagHome && configuration.getAsBoolean("rythm.tag.autoscan", true)) {
loadTags();
}
logger.info("Rythm started in %s mode", mode);
}
public void restart(RuntimeException cause) {
if (isProdMode()) throw cause;
if (!(cause instanceof ClassReloadException)) {
String msg = cause.getMessage();
if (cause instanceof RythmException) {
RythmException re = (RythmException)cause;
msg = re.getSimpleMessage();
}
logger.warn("restarting rythm engine due to %s", msg);
}
restart();
}
private void restart() {
if (isProdMode()) return;
ClassLoader cl = Thread.currentThread().getContextClassLoader();
cl = configuration.getAs("rythm.classLoader.parent", cl, ClassLoader.class);
classLoader = new TemplateClassLoader(cl, this);
// clear all template tags which is managed by TemplateClassManager
List<String> templateTags = new ArrayList<String>();
for (String name : tags.keySet()) {
ITag tag = tags.get(name);
if (!(tag instanceof JavaTagBase)) {
templateTags.add(name);
}
}
for (String name : templateTags) {
tags.remove(name);
}
}
public void loadTags(File tagHome) {
tags.clear();
// code come from http://vafer.org/blog/20071112204524/
class FileTraversal {
public final void traverse(final File f) {
if (f.isDirectory()) {
// aha, we don't want to traverse .svn
if (".svn".equals(f.getName())) return;
onDirectory(f);
final File[] childs = f.listFiles();
for (File child : childs) {
traverse(child);
}
return;
}
onFile(f);
}
public void onDirectory(final File d) {
}
public void onFile(final File f) {
if (tagFileFilter.accept(f)) {
ITag tag = (ITag) getTemplate(f);
if (null != tag) registerTag(tag);
}
}
}
new FileTraversal().traverse(tagHome);
logger.info("tags loaded from %s", tagHome);
}
private void loadTags() {
loadTags(tagHome);
}
static ThreadLocal<Integer> cceCounter = new ThreadLocal<Integer>();
@SuppressWarnings("unchecked")
public ITemplate getTemplate(File template, Object... args) {
TemplateClass tc = classes.getByTemplate(resourceManager.get(template).getKey());
if (null == tc) {
tc = new TemplateClass(template, this);
}
ITemplate t = tc.asTemplate();
if (null == t) return null;
try {
if (1 == args.length && args[0] instanceof Map) {
t.setRenderArgs((Map<String, Object>) args[0]);
} else {
t.setRenderArgs(args);
}
} catch (ClassCastException ce) {
if (mode.isDev()) {
Integer I = cceCounter.get();
if (null == I) {
I = 0;
cceCounter.set(1);
} else {
I++;
cceCounter.set(I);
}
if (I > 2) {
cceCounter.remove();
throw ce;
}
restart(ce);
return getTemplate(template, args);
}
throw ce;
}
if (mode.isDev()) cceCounter.remove();
return t;
}
@SuppressWarnings("unchecked")
public ITemplate getTemplate(String template, Object... args) {
TemplateClass tc = classes.getByTemplate(template);
if (null == tc) {
tc = new TemplateClass(template, this);
}
ITemplate t = tc.asTemplate();
try {
if (1 == args.length && args[0] instanceof Map) {
t.setRenderArgs((Map<String, Object>) args[0]);
} else {
t.setRenderArgs(args);
}
if (mode.isDev()) cceCounter.remove();
} catch (ClassCastException ce) {
if (mode.isDev()) {
Integer I = cceCounter.get();
if (null == I) {
I = 1;
cceCounter.set(I);
} else {
I++;
cceCounter.set(I);
}
if (I > 2) {
cceCounter.remove();
throw ce;
}
restart(ce);
return getTemplate(template, args);
}
throw ce;
}
return t;
}
public void preprocess(ITemplate t) {
IImplicitRenderArgProvider p = implicitRenderArgProvider;
if (null != p) p.setRenderArgs(t);
for (IRythmListener l : listeners) {
l.onRender(t);
}
}
private String renderTemplate(ITemplate t) {
// inject implicity render args
return t.render();
}
public String render(String template, Object... args) {
ITemplate t = getTemplate(template, args);
return renderTemplate(t);
}
public String renderStr(String template, Object... args) {
return renderString(template, args);
}
public String toString(String template, Object obj) {
Class argClass = obj.getClass();
String key = template + argClass;
TemplateClass tc = classes.getByTemplate(key);
if (null == tc) {
tc = new TemplateClass(new StringTemplateResource(template), this, new ToString(argClass));
classes.tmplIdx.put(key, tc);
}
ITemplate t = tc.asTemplate();
t.setRenderArg(0, obj);
return t.render();
}
public String toString(Object obj) {
return toString(obj, ToStringOption.defaultOption, (ToStringStyle)null);
}
public String toString(Object obj, ToStringOption option, ToStringStyle style) {
Class<?> c = obj.getClass();
AutoToString.AutoToStringData key = new AutoToString.AutoToStringData(c, option, style);
//String template = AutoToString.templateStr(c, option, style);
TemplateClass tc = classes.getByTemplate(key);
if (null == tc) {
tc = new TemplateClass(new ToStringTemplateResource(key), this, new AutoToString(c, key));
classes.tmplIdx.put(key, tc);
}
ITemplate t = tc.asTemplate();
t.setRenderArg(0, obj);
return t.render();
}
public String commonsToString(Object obj, ToStringOption option, org.apache.commons.lang3.builder.ToStringStyle style) {
return toString(obj, option, ToStringStyle.fromApacheStyle(style));
}
@SuppressWarnings("unchecked")
public String renderString(String template, Object... args) {
TemplateClass tc = classes.getByTemplate(template);
if (null == tc) {
tc = new TemplateClass(new StringTemplateResource(template), this);
}
ITemplate t = tc.asTemplate();
if (1 == args.length && args[0] instanceof Map) {
t.setRenderArgs((Map<String, Object>) args[0]);
} else {
t.setRenderArgs(args);
}
return t.render();
}
public String render(File file, Object... args) {
ITemplate t = getTemplate(file, args);
return renderTemplate(t);
}
public Set<String> nonExistsTemplates = new HashSet<String>();
private class NonExistsTemplatesChecker {
boolean started = false;
private ScheduledExecutorService scheduler = new ScheduledThreadPoolExecutor(1);
NonExistsTemplatesChecker() {
scheduler.scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
List<String> toBeRemoved = new ArrayList<String>();
for (String template : nonExistsTemplates) {
ITemplateResource rsrc = resourceManager.getFileResource(template);
if (rsrc.isValid()) {
toBeRemoved.add(template);
}
}
nonExistsTemplates.removeAll(toBeRemoved);
toBeRemoved.clear();
TemplateClass tc = classes.all().get(0);
for (String tag : nonExistsTags) {
if (null != resourceManager.tryLoadTag(tag, tc)) {
toBeRemoved.add(tag);
}
}
nonExistsTags.removeAll(toBeRemoved);
toBeRemoved.clear();
}
}, 0, 1000 * 10, TimeUnit.MILLISECONDS);
}
}
private NonExistsTemplatesChecker nonExistsTemplatesChecker = null;
public String renderIfTemplateExists(String template, Object... args) {
if (nonExistsTemplates.contains(template)) return "";
TemplateClass tc = classes.getByTemplate(template);
if (null == tc) {
ITemplateResource rsrc = resourceManager.getFileResource(template);
if (rsrc.isValid()) {
tc = new TemplateClass(rsrc, this);
} else {
nonExistsTemplates.add(template);
if (mode.isDev() && nonExistsTemplatesChecker == null) {
nonExistsTemplatesChecker = new NonExistsTemplatesChecker();
}
return "";
}
}
ITemplate t = tc.asTemplate();
if (1 == args.length && args[0] instanceof Map) {
t.setRenderArgs((Map<String, Object>) args[0]);
} else {
t.setRenderArgs(args);
}
return t.render();
}
// -- register java extension
public static void registerJavaExtension(IJavaExtension extension) {
Token.addExtension(extension);
}
public static void registerGlobalImports(String imports) {
CodeBuilder.registerImports(imports);
}
public static void registerGlobalImportProvider(IImportProvider provider) {
CodeBuilder.registerImportProvider(provider);
}
// -- tag relevant codes
public final Map<String, ITag> tags = new HashMap<String, ITag>();
public final Set<String> non_tags = new HashSet<String>();
public TemplateClass getTemplateClassFromTagName(String name) {
TemplateBase tag = (TemplateBase) tags.get(name);
if (null == tag) return null;
return tag.getTemplateClass(false);
}
public String testTag(String name, TemplateClass tc) {
if (Keyword.THIS.toString().equals(name)) {
return resourceManager.getFullTagName(tc);
}
if (mode.isProd() && non_tags.contains(name)) return null;
boolean isTag = tags.containsKey(name);
if (isTag) return name;
// try imported path
if (null != tc.importPaths) {
for (String s : tc.importPaths) {
String name0 = s + "." + name;
if (tags.containsKey(name0)) return name0;
}
}
// try relative path
String callerName = resourceManager.getFullTagName(tc);
int pos = callerName.lastIndexOf(".");
if (-1 != pos) {
String name0 = callerName.substring(0, pos) + "." + name;
if (tags.containsKey(name0)) return name0;
}
try {
// try to ask resource manager
TemplateClass tagTC = resourceManager.tryLoadTag(name, tc);
if (null == tagTC) {
if (mode.isProd()) non_tags.add(name);
return null;
}
String fullName = tagTC.getFullName();
return fullName;
} catch (TagLoadException e) {
throw e;
} catch (RythmException e) {
throw e;
} catch (Exception e) {
logger.error(e, "error trying load tag[%s]", name);
// see if the
}
return null;
}
/**
* Register a tag class. If there is name collision then registration
* will fail
*
* @return true if registration failed
*/
public boolean registerTag(ITag tag) {
String name = tag.getName();
return registerTag(name, tag);
}
/**
* Register a tag using the given name
*
* @param name
* @param tag
* @return
*/
public boolean registerTag(String name, ITag tag) {
if (null == tag) throw new NullPointerException();
if (tags.containsKey(name)) {
return false;
}
tags.put(name, tag);
logger.trace("tag %s registered", name);
return true;
}
public void invokeTag(String name, ITemplate caller, ITag.ParameterList params, ITag.Body body, ITag.Body context) {
invokeTag(name, caller, params, body, context, false);
}
public Set<String> nonExistsTags = new HashSet<String>();
public void invokeTag(String name, ITemplate caller, ITag.ParameterList params, ITag.Body body, ITag.Body context, boolean ignoreNonExistsTag) {
if (nonExistsTags.contains(name)) return;
// try tag registry first
ITag tag = tags.get(name);
TemplateClass tc = ((TemplateBase) caller).getTemplateClass(true);
if (null == tag) {
// is calling self
if (S.isEqual(name, ((TagBase)caller).getName())) tag = (TagBase)caller;
}
if (null == tag) {
// try imported path
if (null != tc.importPaths) {
for (String s : tc.importPaths) {
String name0 = s + "." + name;
tag = tags.get(name0);
if (null != tag) break;
}
}
// try relative path
if (null == tag) {
String callerName = resourceManager.getFullTagName(tc);
int pos = callerName.lastIndexOf(".");
if (-1 != pos) {
String name0 = callerName.substring(0, pos) + "." + name;
tag = tags.get(name0);
}
}
// try load the tag from resource
if (null == tag) {
TemplateClass tagC = resourceManager.tryLoadTag(name, tc);
if (null != tagC) tag = tags.get(tagC.getFullName());
if (null == tag) {
if (ignoreNonExistsTag) {
if (logger.isDebugEnabled()) {
logger.debug("cannot find tag: " + name);
}
nonExistsTags.add(name);
if (mode.isDev() && nonExistsTemplatesChecker == null) {
nonExistsTemplatesChecker = new NonExistsTemplatesChecker();
}
return;
} else {
throw new NullPointerException("cannot find tag: " + name);
}
}
tag = (ITag) tag.cloneMe(this, caller);
}
}
if (!(tag instanceof JavaTagBase)) {
// try refresh the tag loaded from template file under tag root
// note Java source tags are not reloaded here
String cn = tag.getClass().getName();
if (reloadByIncClassVersion() && -1 == cn.indexOf("$")) {
int pos = cn.lastIndexOf("v");
if (-1 < pos) cn = cn.substring(0, pos);
}
TemplateClass tc0 = classes.getByClassName(cn);
if (null == tc0) {
System.out.println(tag.getClass());
System.out.println(name);
System.out.println(cn);
System.out.println(caller.getClass());
}
tag = (ITag) tc0.asTemplate(caller);
} else {
tag = (ITag) tag.cloneMe(this, caller);
}
if (null != params) {
if (tag instanceof JavaTagBase) {
((JavaTagBase) tag).setRenderArgs(params);
} else {
for (int i = 0; i < params.size(); ++i) {
ITag.Parameter param = params.get(i);
if (null != param.name) tag.setRenderArg(param.name, param.value);
else tag.setRenderArg(i, param.value);
}
}
}
if (null != body) tag.setRenderArg("_body", body);
for (ITagInvokeListener l: getExtensionManager().tagInvokeListeners()) {
l.onInvoke(tag);
}
try {
if (null != context) {
((TagBase)tag).setBodyContext(context);
}
tag.call();
} finally {
for (ITagInvokeListener l: getExtensionManager().tagInvokeListeners()) {
try {
l.tagInvoked(tag);
} catch (RuntimeException e) {
logger.error("Error call tagInvoked hook of %s", l.getClass());
}
}
}
}
public void handleTemplateExecutionException(Exception e, TemplateBase template) throws Exception {
for (ITemplateExecutionExceptionHandler h : em_.exceptionHandlers()) {
if (h.handleTemplateExecutionException(e, template)) return;
}
throw e;
}
// -- cache api
/**
* Cache object using key and args for ttl seconds
*
* @param key
* @param o
* @param ttl if zero then defaultTTL used, if negative then never expire
* @param args
*/
public void cache(String key, Object o, int ttl, Object... args) {
if (cacheService == NoCacheService.INSTANCE || (mode.isDev() && cacheOnProdOnly)) return;
Serializable value = null == o ? "" : (o instanceof Serializable ? (Serializable)o : o.toString());
if (args.length > 0) {
StringBuilder sb = new StringBuilder(key);
for (Object arg : args) {
sb.append("-").append(arg);
}
key = sb.toString();
}
cacheService.put(key, value, ttl);
}
/**
* Store object o into cache service with ttl equals to duration specified.
* <p/>
* <p>The duration is a string to be parsed by @{link #durationParser}</p>
* <p/>
* <p>The object o is associated with given key and a list of argument values</p>
*
* @param key
* @param o
* @param duration
* @param args
*/
public void cache(String key, Object o, String duration, Object... args) {
if (cacheService == NoCacheService.INSTANCE || (mode.isDev() && cacheOnProdOnly)) return;
int ttl = null == duration ? defaultTTL : durationParser.parseDuration(duration);
cache(key, o, ttl, args);
}
/**
* Get cached value using key and a list of argument values
*
* @param key
* @param args
* @return
*/
public Serializable cached(String key, Object... args) {
if (cacheService == NoCacheService.INSTANCE || (mode.isDev() && cacheOnProdOnly)) return null;
if (args.length > 0) {
StringBuilder sb = new StringBuilder(key);
for (Object arg : args) {
sb.append("-").append(arg);
}
key = sb.toString();
}
return cacheService.get(key);
}
public void shutdown() {
if (null != cacheService) cacheService.shutdown();
}
// -- SPI interface
private DialectManager dm_ = new DialectManager();
public DialectManager getDialectManager() {
return dm_;
}
private ExtensionManager em_ = new ExtensionManager(this);
public ExtensionManager getExtensionManager() {
return em_;
}
// -- issue #47
private Map<TemplateClass, Set<TemplateClass>> extendMap = new HashMap<TemplateClass, Set<TemplateClass>>();
public void addExtendRelationship(TemplateClass parent, TemplateClass child) {
if (mode.isProd()) return;
Set<TemplateClass> children = extendMap.get(parent);
if (null == children) {
children = new HashSet<TemplateClass>();
extendMap.put(parent, children);
}
children.add(child);
}
// called to invalidate all template class which extends the parent
public void invalidate(TemplateClass parent) {
if (mode.isProd()) return;
Set<TemplateClass> children = extendMap.get(parent);
if (null == children) return;
for (TemplateClass child: children) {
invalidate(child);
child.reset();
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/CaretParserFactoryBase.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.spi.ICaretParserFactory;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IDialect;
import com.greenlaw110.rythm.spi.IParserFactory;
import com.stevesoft.pat.Regex;
public abstract class CaretParserFactoryBase implements ICaretParserFactory {
protected ILogger logger = Logger.get(IParserFactory.class);
public String getCaret(IDialect dialect) {
return dialect.a();
}
public static void raiseParseException(IContext ctx, String msg, Object... args) {
throw new ParseException(ctx.getEngine(), ctx.getTemplateClass(), ctx.currentLine(), msg, args);
}
// -- for testing purpose
protected static void p(int i, Regex r) {
if (0 == i) {
System.out.println(i + ": " + r.stringMatched());
} else {
System.out.println(i + ": " + r.stringMatched(i));
}
}
protected static void p(String s, Regex r) {
if (r.search(s)) p(r);
}
protected static void p(String s, Regex r, int max) {
if (r.search(s)) p(r, max);
}
protected static void p(Regex r, int max) {
for (int i = 0; i < max; ++i) {
p(i, r);
}
}
protected static void p(Regex r) {
p(r, 6);
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/internal/parser/build_in/ArgsParserTest.java
package com.greenlaw110.rythm.internal.parser.build_in;
import org.junit.Test;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.ut.UnitTest;
import com.greenlaw110.rythm.utils.TextBuilder;
public class ArgsParserTest extends UnitTest {
@Test
public void test() {
setup("@args String name;");
IParser p = new ArgsParser().create(c);
TextBuilder builder = p.go();
assertNotNull(builder);
call(builder);
assertTrue(b.hasRenderArg("String", "name"));
}
@Test
public void testMultiple() {
setup("@args String name, int counter;");
IParser p = new ArgsParser().create(c);
TextBuilder builder = p.go();
assertNotNull(builder);
call(builder);
assertTrue(b.hasRenderArg("String", "name"));
assertTrue(b.hasRenderArg("int", "counter"));
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/IDirective.java
package com.greenlaw110.rythm.internal;
/**
* Mark a token
*/
public interface IDirective {
void call();
}
<file_sep>/samples/Issue22/Issue22.java
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.utils.IO;
import java.io.File;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 20/04/12
* Time: 10:51 PM
* To change this template use File | Settings | File Templates.
*/
public class Issue22 {
public static void main (String [] args) {
try {
Properties properties = new Properties();
properties.put("rythm.mode", "dev");
File root = new File("tmp/issue22");
root.mkdirs();
File index = new File(root, "index.html");
IO.writeContent("@args String s\n@common(s)", index);
File common = new File(root, "common.html");
IO.writeContent("@args String s\nhello @s", common);
properties.put("rythm.root", root);
Rythm.init(properties);
String s = "rythm";
System.out.println (Rythm.render("index.html", s));
} catch (Exception e) {
e.printStackTrace();
} finally {
Rythm.engine.cacheService.shutdown();
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/dialect/Japid.java
package com.greenlaw110.rythm.internal.dialect;
public abstract class Japid extends Razor {
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/BreakParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.CodeBuilder;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.spi.Token;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
public class BreakParser extends KeywordParserFactory {
private static final String R = "^(%s%s\\s*(\\(\\s*\\))?[\\s;]*)";
public BreakParser() {
}
protected String patternStr() {
return R;
}
public IParser create(IContext c) {
return new ParserBase(c) {
public TextBuilder go() {
Regex r = reg(dialect());
if (r.search(remain())) {
step(r.stringMatched().length());
IContext.Break b = ctx().peekBreak();
if (null == b) raiseParseException("Bad @break statement: No loop context");
return new CodeToken(b.getStatement(), ctx());
}
raiseParseException("Bad @break statement. Correct usage: @break()");
return null;
}
};
}
@Override
public Keyword keyword() {
return Keyword.BREAK;
}
public static void main(String[] args) {
Regex r = new BreakParser().reg(new Rythm());
String s = "@break()\n\tdd";
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/CodeBuilder.java
package com.greenlaw110.rythm.internal;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.compiler.TemplateClass;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.internal.parser.NotRythmTemplateException;
import com.greenlaw110.rythm.internal.parser.build_in.BlockToken;
import com.greenlaw110.rythm.internal.parser.build_in.InvokeTagParser;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.resource.ITemplateResource;
import com.greenlaw110.rythm.spi.IDialect;
import com.greenlaw110.rythm.spi.ITemplateClassEnhancer;
import com.greenlaw110.rythm.spi.Token;
import com.greenlaw110.rythm.template.JavaTagBase;
import com.greenlaw110.rythm.template.TagBase;
import com.greenlaw110.rythm.template.TemplateBase;
import com.greenlaw110.rythm.utils.IImplicitRenderArgProvider;
import com.greenlaw110.rythm.utils.IImportProvider;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.util.*;
public class CodeBuilder extends TextBuilder {
protected ILogger logger = Logger.get(CodeBuilder.class);
public static class RenderArgDeclaration {
public String name;
public String type;
public String defVal;
public int lineNo;
public RenderArgDeclaration(int lineNo, String name, String type) {
this(lineNo, name, type, null);
}
public RenderArgDeclaration(int lineNo, String name, String type, String defVal) {
this.lineNo = lineNo;
this.name = name;
this.type = typeTransform(type);
defVal = defValTransform(type, defVal);
this.defVal = null == defVal ? defVal(type) : defVal;
}
private static String defValTransform(String type, String defVal) {
if (S.isEmpty(defVal)) return null;
defVal = defVal.toLowerCase();
if ("long".equalsIgnoreCase(type) && defVal.matches("[0-9]+")) return defVal + "L";
if ("float".equalsIgnoreCase(type) && defVal.matches("[0-9]+")) return defVal + "f";
if ("double".equalsIgnoreCase(type) && defVal.matches("[0-9]+")) return defVal + "d";
return defVal;
}
private static String typeTransform(String type) {
if ("boolean".equals(type)) return "Boolean";
else if ("int".equals(type)) return "Integer";
else if ("float".equals(type)) return "Float";
else if ("double".equals(type)) return "Double";
else if ("char".equals(type)) return "Character";
else if ("long".equals(type)) return "Long";
else return type;
}
private static String defVal(String type) {
if (type.equals("boolean"))
return "false";
else if (type.equals("int"))
return "0";
else if (type.equals("long"))
return "0L";
else if (type.equals("char"))
return "(char)0";
else if (type.equals("byte"))
return "(byte)0";
else if (type.equals("short"))
return "(short)0";
else if (type.equals("float"))
return "0f";
else if (type.equals("double"))
return "0d";
return "null";
}
}
public RythmEngine engine;
private boolean isNotRythmTemplate = false;
public boolean isRythmTemplate() {
return !isNotRythmTemplate;
}
protected String tmpl;
private String cName;
public String includingCName;
private String pName;
private String tagName;
private boolean isTag() {
return null != tagName;
}
private String initCode = null;
public void setInitCode(String code) {
if (null != initCode)
throw new ParseException(engine, templateClass, parser.currentLine(), "@init section already declared.");
initCode = code;
}
private String extended; // the cName of the extended template
protected String extended() {
String defClass = isTag() ? TagBase.class.getName() : TemplateBase.class.getName();
return null == extended ? defClass : extended;
}
private String extendedResourceMark() {
TemplateClass tc = extendedTemplateClass;
return (null == tc) ? "" : String.format("//<extended_resource_key>%s</extended_resource_key>", tc.templateResource.getKey());
}
private TemplateClass extendedTemplateClass;
public TemplateClass getExtendedTemplateClass() {
return extendedTemplateClass;
}
private InvokeTagParser.ParameterDeclarationList extendArgs = null;
public Set<String> imports = new HashSet<String>();
private int extendDeclareLineNo = -1;
// <argName, argClass>
public Map<String, RenderArgDeclaration> renderArgs = new LinkedHashMap<String, RenderArgDeclaration>();
private List<TextBuilder> builders = new ArrayList<TextBuilder>();
private TemplateParser parser;
private TemplateClass templateClass;
public TemplateClass getTemplateClass() {
return templateClass;
}
/*
* Simple template
* 1. does not have global render args,
* 2. does not extends layout template
*/
private boolean simpleTemplate = false;
public void setSimpleTemplate(int lineNo) {
if (null != this.extended) {
throw new ParseException(engine, templateClass, lineNo, "Simple template does not allow to extend layout template");
}
//if (true) throw new RuntimeException(this.template());
simpleTemplate = true;
}
transient public IDialect dialect = null;
public CodeBuilder(String template, String className, String tagName, TemplateClass templateClass, RythmEngine engine, IDialect dialect) {
tmpl = template;
this.tagName = (null == tagName) ? className : tagName;
className = className.replace('/', '.');
cName = className;
int i = className.lastIndexOf('.');
if (-1 < i) {
cName = className.substring(i + 1);
pName = className.substring(0, i);
}
this.engine = null == engine ? Rythm.engine : engine;
this.dialect = dialect;
this.parser = new TemplateParser(this);
this.templateClass = templateClass;
this.simpleTemplate = templateClass.simpleTemplate;
}
/**
* Reset to the state before construction
*/
public void clear() {
out().ensureCapacity(0);
this.engine = null;
this.tmpl = null;
this.cName = null;
this.pName = null;
this.tagName = null;
this.initCode = null;
this.extended = null;
this.extendedTemplateClass = null;
if (null != this.extendArgs) this.extendArgs.pl.clear();
this.imports.clear();
this.extendDeclareLineNo = 0;
this.renderArgs.clear();
this.builders.clear();
this.parser = null;
this.templateClass = null;
this.simpleTemplate = false;
this.inlineTags.clear();
this.inlineTagBodies.clear();
this.logTime = false;
this.macros.clear();
this.macroStack.clear();
this.buildBody = null;
}
/**
* Rewind to the state when construction finished
*/
public void rewind() {
out().ensureCapacity(0);
this.initCode = null;
this.extended = null;
this.extendedTemplateClass = null;
if (null != this.extendArgs) this.extendArgs.pl.clear();
this.imports.clear();
this.extendDeclareLineNo = 0;
this.renderArgs.clear();
this.builders.clear();
this.simpleTemplate = false;
this.inlineTags.clear();
this.inlineTagBodies.clear();
this.logTime = false;
this.macros.clear();
this.macroStack.clear();
this.buildBody = null;
}
public void merge(CodeBuilder codeBuilder) {
if (null == codeBuilder) return;
this.imports.addAll(codeBuilder.imports);
for (InlineTag tag : codeBuilder.inlineTags) {
inlineTags.add(tag.clone(this));
}
this.initCode = new StringBuilder(S.toString(this.initCode)).append(S.toString(codeBuilder.initCode)).toString();
this.renderArgs.putAll(codeBuilder.renderArgs);
}
public String className() {
return cName;
}
public String includingClassName() {
return null == includingCName ? cName : includingCName;
}
private static Set<String> globalImports = new HashSet<String>();
public static void registerImports(String imports) {
globalImports.addAll(Arrays.asList(imports.split(",")));
}
private static IImportProvider importProvider = null;
public static void registerImportProvider(IImportProvider provider) {
importProvider = provider;
}
public void addImport(String imprt) {
if (!globalImports.contains(imprt)) imports.add(imprt);
if (imprt.endsWith(".*")) {
imprt = imprt.substring(0, imprt.lastIndexOf(".*"));
templateClass.importPaths.add(imprt);
}
}
public static class InlineTag {
String tagName;
String signature;
String retType = "void";
String body;
boolean autoRet = false;
List<TextBuilder> builders = new ArrayList<TextBuilder>();
InlineTag(String name, String ret, String sig, String body) {
tagName = name;
signature = sig;
retType = null == ret ? "void" : ret;
this.body = body;
}
InlineTag clone(CodeBuilder newCaller) {
InlineTag tag = new InlineTag(tagName, retType, signature, body);
tag.builders.clear();
for (TextBuilder tb : builders) {
TextBuilder newTb = tb.clone(newCaller);
tag.builders.add(newTb);
}
tag.autoRet = autoRet;
return tag;
}
@Override
public int hashCode() {
return (37 + tagName.hashCode()) * 31 + signature.hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof InlineTag) {
InlineTag that = (InlineTag) obj;
return S.isEqual(that.signature, this.signature) && S.isEqual(that.tagName, this.tagName);
}
return false;
}
}
private Set<InlineTag> inlineTags = new HashSet<InlineTag>();
public boolean needsPrint(String tagName) {
return templateClass.returnObject(tagName);
}
private Stack<List<TextBuilder>> inlineTagBodies = new Stack<List<TextBuilder>>();
public InlineTag defTag(String tagName, String retType, String signature, String body) {
tagName = tagName.trim();
InlineTag tag = new InlineTag(tagName, retType, signature, body);
if (inlineTags.contains(tag)) {
throw new ParseException(engine, templateClass, parser.currentLine(), "inline tag already defined: %s", tagName);
}
inlineTags.add(tag);
inlineTagBodies.push(builders);
builders = tag.builders;
if ("void".equals(tag.retType)) {
tag.retType = "com.greenlaw110.rythm.template.ITemplate.RawData";
tag.autoRet = true;
String code = "StringBuilder __sb = this.getSelfOut();this.setSelfOut(new StringBuilder());";
builders.add(new CodeToken(code, parser));
}
templateClass.setTagType(tagName, tag.retType);
return tag;
}
public void endTag(InlineTag tag) {
if (inlineTagBodies.empty())
throw new ParseException(engine, templateClass, parser.currentLine(), "Unexpected tag definition close");
if (tag.autoRet) {
builders.add(new CodeToken("String __s = toString();this.setSelfOut(__sb);return s().raw(__s);", parser));
}
builders = inlineTagBodies.pop();
}
public String addIncludes(String includes, int lineNo) {
StringBuilder sb = new StringBuilder();
for (String s : includes.split("[\\s,;:]+")) {
sb.append(addInclude(s, lineNo));
}
return sb.toString();
}
public String addInclude(String include, int lineNo) {
String tagName = engine.testTag(include, templateClass);
if (null == tagName) {
throw new ParseException(engine, templateClass, lineNo, "include template not found: %s", include);
}
TemplateBase includeTag = (TemplateBase) engine.tags.get(tagName);
if (includeTag instanceof JavaTagBase) {
throw new ParseException(engine, templateClass, lineNo, "cannot include Java tag: %s", include);
}
TemplateClass includeTc = includeTag.getTemplateClass(false);
includeTc.buildSourceCode(includingClassName());
merge(includeTc.codeBuilder);
templateClass.addIncludeTemplateClass(includeTc);
return includeTc.codeBuilder.buildBody;
}
public void setExtended(Class<? extends TemplateBase> c) {
this.extended = c.getName();
}
public void setExtended(String extended, InvokeTagParser.ParameterDeclarationList args, int lineNo) {
if (simpleTemplate) {
throw new ParseException(engine, templateClass, lineNo, "Simple template does not allow to extend layout template");
}
if (null != this.extended) {
throw new ParseException(engine, templateClass, lineNo, "Extended template already declared");
}
String fullName = engine.testTag(extended, templateClass);
if (null == fullName) {
// try legacy style
setExtended_deprecated(extended, args, lineNo);
logger.warn("Template[%s]: Extended template declaration \"%s\" is deprecated, please switch to the new style \"%s\"", templateClass.getKey(), extended, engine.resourceManager.getFullTagName(extendedTemplateClass));
} else {
TemplateBase tb = (TemplateBase) engine.tags.get(fullName);
TemplateClass tc = tb.getTemplateClass(false);
this.extended = tc.name();
this.extendedTemplateClass = tc;
this.templateClass.extendedTemplateClass = tc;
this.engine.addExtendRelationship(tc, this.templateClass);
this.extendArgs = args;
}
}
public void setExtended_deprecated(String extended, InvokeTagParser.ParameterDeclarationList args, int lineNo) {
if (null != this.extended) {
throw new IllegalStateException("Extended template already declared");
}
TemplateClass tc = null;
String origin = extended;
if (!extended.startsWith("/")) {
// relative path ?
String me = templateClass.getKey().toString();
int pos = me.lastIndexOf("/");
if (-1 != pos) extended = me.substring(0, pos) + "/" + extended;
tc = engine.classes.getByTemplate(extended);
if (null == tc) {
ITemplateResource resource = engine.resourceManager.getFileResource(extended);
if (resource.isValid()) tc = new TemplateClass(resource, engine);
}
}
if (null == tc && !extended.startsWith("/")) {
// it's in class name style ?
//if (!extended.endsWith(TemplateClass.CN_SUFFIX)) extended = extended + TemplateClass.CN_SUFFIX;
tc = engine.classes.getByClassName(extended);
}
if (null == tc) {
tc = engine.classes.getByTemplate(origin);
if (null == tc) {
ITemplateResource resource = engine.resourceManager.getFileResource(origin);
if (resource.isValid()) tc = new TemplateClass(resource, engine);
}
}
if (null == tc) {
throw new ParseException(engine, templateClass, lineNo, "Cannot find extended template by name \"%s\"", origin);
}
this.extended = tc.name();
this.extendedTemplateClass = tc;
this.templateClass.extendedTemplateClass = tc;
this.engine.addExtendRelationship(tc, this.templateClass);
this.extendArgs = args;
}
protected boolean logTime = false;
public void setLogTime() {
logTime = true;
}
public void addRenderArgs(RenderArgDeclaration declaration) {
renderArgs.put(declaration.name, declaration);
}
public void addRenderArgs(int lineNo, String type, String name) {
renderArgs.put(name, new RenderArgDeclaration(lineNo, name, type));
}
private Map<String, List<TextBuilder>> macros = new HashMap<String, List<TextBuilder>>();
private Stack<String> macroStack = new Stack<String>();
public void pushMacro(String macro) {
if (macros.containsKey(macro)) {
throw new ParseException(engine, templateClass, parser.currentLine(), "Macro already defined: %s", macro);
}
macroStack.push(macro);
macros.put(macro, new ArrayList<TextBuilder>());
}
public void popMacro() {
if (macroStack.empty()) {
throw new ParseException(engine, templateClass, parser.currentLine(), "no macro found in stack");
}
macroStack.pop();
}
public boolean hasMacro(String macro) {
return macros.containsKey(macro);
}
public List<TextBuilder> getMacro(String macro) {
List<TextBuilder> list = this.macros.get(macro);
if (null == list) throw new NullPointerException();
return list;
}
public void addBuilder(TextBuilder builder) {
if (macroStack.empty()) builders.add(builder);
else {
String macro = macroStack.peek();
List<TextBuilder> list = macros.get(macro);
if (null == list) {
list = new ArrayList<TextBuilder>();
macros.put(macro, list);
}
list.add(builder);
}
}
String template() {
return tmpl;
}
@Override
public TextBuilder build() {
try {
parser.parse();
invokeDirectives();
if (!simpleTemplate) addDefaultRenderArgs();
pPackage();
pImports();
pClassOpen();
pTagImpl();
pInitCode();
pSetup();
if (!simpleTemplate) pExtendInitArgCode();
pRenderArgs();
pInlineTags();
for (ITemplateClassEnhancer enhancer : engine.templateClassEnhancers) {
np(enhancer.sourceCode());
}
pBuild();
pClassClose();
return this;
} catch (NotRythmTemplateException e) {
isNotRythmTemplate = true;
return this;
}
}
private void invokeDirectives() {
for (TextBuilder b : builders) {
if (b instanceof IDirective) {
((IDirective) b).call();
}
}
}
private void addDefaultRenderArgs() {
IImplicitRenderArgProvider p = engine.implicitRenderArgProvider;
if (null == p) return;
Map<String, ?> defArgs = p.getRenderArgDescriptions();
for (String name : defArgs.keySet()) {
Object o = defArgs.get(name);
String type = (o instanceof Class<?>) ? ((Class<?>) o).getName() : o.toString();
addRenderArgs(-1, type, name);
}
}
protected void pPackage() {
if (!S.isEmpty(pName)) p("package ").p(pName).pn(";");
}
// print imports
protected void pImports() {
for (String s : imports) {
if (!S.isEmpty(s)) p("import ").p(s).pn(';');
}
for (String s : globalImports) {
if (!S.isEmpty(s)) p("import ").p(s).pn(';');
}
if (null != importProvider) {
for (String s : importProvider.imports()) {
if (!S.isEmpty(s)) p("import ").p(s).pn(';');
}
}
IImplicitRenderArgProvider p = engine.implicitRenderArgProvider;
if (null != p) {
for (String s : p.getImplicitImportStatements()) {
p("import ").p(s).pn(';');
}
}
// common imports
pn("import java.util.*;");
pn("import java.io.*;");
}
protected void pClassOpen() {
np("public class ").p(cName).p(" extends ").p(extended()).p(" {").pn(extendedResourceMark());
}
protected void pClassClose() {
np("}").pn();
}
protected void pRenderArgs() {
pn();
// -- output private members
for (String argName : renderArgs.keySet()) {
RenderArgDeclaration arg = renderArgs.get(argName);
pt("protected ").p(arg.type).p(" ").p(argName);
if (null != arg.defVal) {
p("=").p(arg.defVal).p(";");
} else {
p(";");
}
if (arg.lineNo > -1) p(" //line: ").pn(arg.lineNo);
else pn();
}
// -- output setRenderArgs method
pn();
ptn("@SuppressWarnings(\"unchecked\") public void setRenderArgs(java.util.Map<String, Object> args) {");
for (String argName : renderArgs.keySet()) {
RenderArgDeclaration arg = renderArgs.get(argName);
p2t("if (null != args && args.containsKey(\"").p(argName).p("\")) this.").p(argName).p("=(").p(arg.type).p(")args.get(\"").p(argName).pn("\");");
}
p2t("super.setRenderArgs(args);\n\t}\n");
// -- output setRenderArgs method with args passed in positioned order
IImplicitRenderArgProvider p = engine.implicitRenderArgProvider;
int userDefinedArgNumber = simpleTemplate ? renderArgs.size() : (renderArgs.size() - ((null == p) ? 0 : p.getRenderArgDescriptions().size()));
if (0 < userDefinedArgNumber) {
pn();
ptn("@SuppressWarnings(\"unchecked\") public void setRenderArgs(Object... args) {");
{
p2tn("int _p = 0, l = args.length;");
int i = userDefinedArgNumber;
for (String argName : renderArgs.keySet()) {
RenderArgDeclaration arg = renderArgs.get(argName);
p2t("if (_p < l) { Object v = args[_p++]; boolean isString = (\"java.lang.String\".equals(\"")
.p(arg.type).p("\") || \"String\".equals(\"").p(arg.type).p("\")); ")
.p(argName).p(" = (").p(arg.type).pn(")(isString ? (null == v ? \"\" : v.toString()) : v); }");
if (--i == 0) break;
}
}
ptn("}");
}
// -- output setRenderArg by name
pn();
ptn("@SuppressWarnings(\"unchecked\") @Override public void setRenderArg(String name, Object arg) {");
for (String argName : renderArgs.keySet()) {
RenderArgDeclaration arg = renderArgs.get(argName);
p2t("if (\"").p(argName).p("\".equals(name)) this.").p(argName).p("=(").p(arg.type).pn(")arg;");
}
p2t("super.setRenderArg(name, arg);\n\t}\n");
// -- output setRenderArg by position
pn();
ptn("@SuppressWarnings(\"unchecked\") public void setRenderArg(int pos, Object arg) {");
p2tn("int _p = 0;");
for (String argName : renderArgs.keySet()) {
RenderArgDeclaration arg = renderArgs.get(argName);
p2t("if (_p++ == pos) { Object v = arg; boolean isString = (\"java.lang.String\".equals(\"")
.p(arg.type).p("\") || \"String\".equals(\"").p(arg.type).p("\")); ")
.p(argName).p(" = (").p(arg.type).p(")(isString ? (null == v ? \"\" : v.toString()) : v); }").pn();
}
// the first argument has a default name "arg"
p2tn("if(0 == pos) setRenderArg(\"arg\", arg);");
ptn("}");
}
protected void pExtendInitArgCode() {
if (null == extendArgs || extendArgs.pl.size() < 1) return;
pn();
ptn("@Override protected void loadExtendingArgs() {");
for (int i = 0; i < extendArgs.pl.size(); ++i) {
InvokeTagParser.ParameterDeclaration pd = extendArgs.pl.get(i);
if (S.isEmpty(pd.nameDef)) {
p2t("__parent.setRenderArg(").p(i).p(", ").p(pd.valDef).pn(");");
} else {
p2t("__parent.setRenderArg(\"").p(pd.nameDef).p("\", ").p(pd.valDef).pn(");");
}
if (extendDeclareLineNo != -1) {
p(" //line: ").pn(extendDeclareLineNo);
}
}
ptn("}");
}
protected void pSetup() {
if (!logTime && renderArgs.isEmpty()) return;
pn();
ptn("@Override protected void setup() {");
if (logTime) {
p2tn("_logTime = true;");
}
for (String argName : renderArgs.keySet()) {
RenderArgDeclaration arg = renderArgs.get(argName);
p2t("if (").p(argName).p(" == null) {");
//p("\n\tif (").p(argName).p(" == ").p(RenderArgDeclaration.defVal(arg.type)).p(") {");
p(argName).p("=(").p(arg.type).p(")_get(\"").p(argName).p("\");}\n");
}
ptn("}");
}
protected void pInitCode() {
if (S.isEmpty(initCode)) return;
pn();
pt("@Override public void init() {").p(initCode).p(";").pn("\n\t}");
}
protected void pTagImpl() {
if (!isTag()) return;
pn();
pt("@Override public java.lang.String getName() {\n\t\treturn \"").p(tagName).p("\";\n\t}\n");
}
protected void pInlineTags() {
pn();
for (InlineTag tag : inlineTags) {
p("\nprotected ").p(tag.retType).p(" ").p(tag.tagName).p(tag.signature).p("{\n");
boolean isVoid = tag.autoRet;
StringBuilder sb = out();
if (!isVoid) {
p(tag.body);
} else {
for (TextBuilder b : tag.builders) {
b.build();
}
}
p("\n}");
}
}
public String buildBody = null;
protected void pBuild() {
pn();
pn();
ptn("@Override public com.greenlaw110.rythm.utils.TextBuilder build(){");
p2t("out().ensureCapacity(").p(tmpl.length()).p(");").pn();
StringBuilder sb = new StringBuilder();
StringBuilder old = out();
setOut(sb);
// try merge strings
List<TextBuilder> merged = new ArrayList<TextBuilder>();
Token.StringToken curTk = new Token.StringToken("", parser);
for (int i = 0; i < builders.size(); ++i) {
TextBuilder tb = builders.get(i);
if (tb instanceof Token.StringToken || tb instanceof BlockToken.LiteralBlock) {
if (tb instanceof Token.StringToken) {
Token.StringToken tk = (Token.StringToken)tb;
curTk = curTk.mergeWith(tk);
} else {
BlockToken.LiteralBlock bk = (BlockToken.LiteralBlock)tb;
curTk = curTk.mergeWith(bk);
}
} else {
if (null != curTk) merged.add(curTk);
curTk = new Token.StringToken("", parser);
merged.add(tb);
}
}
if (null != curTk) merged.add(curTk);
for (TextBuilder b : merged) {
b.build();
}
buildBody = sb.toString();
setOut(old);
p(buildBody);
p("\n\t\treturn this;\n\t}\n");
}
private Set<String> varNames = new HashSet<String>();
public String newVarName() {
int i = 0;
while (true) {
String name = "__v" + i;
if (!varNames.contains(name)) {
varNames.add(name);
return name;
} else {
i += new Random().nextInt(100000);
}
}
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/internal/parser/build_in/IfParserTest.java
package com.greenlaw110.rythm.internal.parser.build_in;
import org.junit.Test;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.ut.UnitTest;
import com.greenlaw110.rythm.utils.TextBuilder;
public class IfParserTest extends UnitTest {
private void t(String in, String out) {
setup(in);
IParser p = new IfParser().create(c);
TextBuilder builder = p.go();
assertNotNull(builder);
builder.build();
assertEquals(builder.toString(), out);
}
@Test
public void test() {
t("@if (user.registered()) { <p>hello @user.name()</p> @}", "if (user.registered()) {");
}
@Test
public void test2() {
t("@if (user.registered()) <p>hello @user.name()</p> @", "if (user.registered()) {");
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/RawParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.BlockCodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parse @raw() {...}
*/
public class RawParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.RAW;
}
public IParser create(IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Matcher m = ptn(dialect()).matcher(remain());
if (!m.matches()) return null;
step(m.group(1).length());
return new BlockCodeToken("__ctx.pushEscape(com.greenlaw110.rythm.template.ITemplate.Escape.RAW);", ctx()) {
@Override
public void openBlock() {
}
@Override
public String closeBlock() {
return "__ctx.popEscape();";
}
};
}
};
}
@Override
protected String patternStr() {
return "(%s%s\\s*\\(\\s*\\)[\\s]*\\{).*";
}
public static void main(String[] args) {
Pattern p = new RawParser().ptn(new Rythm());
Matcher m = p.matcher("@raw() {\n" +
" @body\n" +
"}");
if (m.find()) {
System.out.println(m.group(1));
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/NotRythmTemplateException.java
package com.greenlaw110.rythm.internal.parser;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 27/01/12
* Time: 7:30 AM
* To change this template use File | Settings | File Templates.
*/
public class NotRythmTemplateException extends RuntimeException {
private static final long serialVersionUID = 1L;
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/dialect/AutoToString.java
package com.greenlaw110.rythm.internal.dialect;
import com.greenlaw110.rythm.*;
import com.greenlaw110.rythm.internal.AutoToStringCodeBuilder;
import com.greenlaw110.rythm.internal.CodeBuilder;
import com.greenlaw110.rythm.internal.compiler.TemplateClass;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.template.ToStringTemplateBase;
import com.greenlaw110.rythm.toString.ToStringOption;
import com.greenlaw110.rythm.toString.ToStringStyle;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* ToString dialect is a kind of Rythm dialect, the difference is that
* it preset the type of the only one render arg
*/
public class AutoToString extends ToString {
@Override
public String id() {
return "autoToString";
}
public AutoToStringData meta = null;
public AutoToString(Class type, AutoToStringData data) {
super(type);
meta = data;
}
@Override
public void begin(IContext ctx) {
CodeBuilder cb = ctx.getCodeBuilder();
cb.addRenderArgs(ctx.currentLine(), type.getName(), "_");
cb.setSimpleTemplate(0);
cb.setExtended(ToStringTemplateBase.class);
}
@Override
public CodeBuilder createCodeBuilder(String template, String className, String tagName, TemplateClass templateClass, RythmEngine engine) {
return new AutoToStringCodeBuilder(template, className, tagName, templateClass, engine, this);
}
public static String templateStr(Class<?> c, ToStringOption o, ToStringStyle s) {
return com.greenlaw110.rythm.Rythm.render("{class: @c; toStringOption: @o; toStringStyle: @s}", null == c ? "" : c.getName(), o.toString(), s.toString());
}
public static class AutoToStringData {
public AutoToStringData(Class<?> clazz, ToStringOption option, ToStringStyle style) {
this.clazz = clazz;
if (null != option) this.option = option;
if (null != style) this.style = style;
}
public Class<?> clazz;
public ToStringOption option = ToStringOption.defaultOption;
public ToStringStyle style = ToStringStyle.DEFAULT_STYLE;
private int hash = 0;
@Override
public String toString() {
return templateStr(clazz, option, style);
}
@Override
public int hashCode() {
if (0 == hash) hash = ((31 + clazz.hashCode()) * 17 + option.hashCode()) * 17 + style.hashCode();
return hash;
}
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof AutoToStringData) {
AutoToStringData that = (AutoToStringData)obj;
return that.clazz.equals(this.clazz) && that.option.equals(this.option) && that.style.equals(this.style);
}
return false;
}
public static AutoToStringData valueOf(String s) {
return parseStr(s);
}
}
private static final Pattern P = Pattern.compile("\\{class *: *([a-zA-Z_0-9\\.\\$]+) *; *toStringOption *: *(\\{.*?\\}) *; *toStringStyle *: *([a-zA-Z_0-9\\.\\$]+) *\\}");
public static AutoToStringData parseStr(String s) {
Matcher m = P.matcher(s);
if (!m.matches()) throw new IllegalArgumentException("Unrecognized AutoToString template: " + s);
String cs = m.group(1);
String os = m.group(2);
String ss = m.group(3);
Class<?> c = null;
try {
c = com.greenlaw110.rythm.Rythm.engine().classLoader.loadClass(cs);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class not found: " + cs);
}
ToStringOption o = ToStringOption.valueOf(os);
ToStringStyle st = ToStringStyle.valueOf(ss);
return new AutoToStringData(c, o, st);
}
public static void main(String[] args) {
String s = templateStr(String.class, ToStringOption.defaultOption.setAppendTransient(true), ToStringStyle.DEFAULT_STYLE);
System.out.println(s);
AutoToStringData d = parseStr(s);
System.out.println(d);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/spi/IParserFactory.java
package com.greenlaw110.rythm.spi;
public interface IParserFactory {
IParser create(IContext ctx);
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/DebugParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 19/02/12
* Time: 5:28 PM
* To change this template use File | Settings | File Templates.
*/
public class DebugParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.DEBUG;
}
public IParser create(final IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) {
raiseParseException("error parsing @debug, correct usage: @debug(\"msg\", args...)");
}
step(r.stringMatched().length());
String s = new TextBuilder().p("_logger.debug").p(r.stringMatched(1)).p(";").toString();
return new CodeToken(s, ctx());
}
};
}
@Override
protected String patternStr() {
return "%s%s\\s*((?@()))[\\r\\n]*";
}
public static void main(String[] args) {
String s = "@debug (\"sss\", 1)\naba";
DebugParser ap = new DebugParser();
Regex r = ap.reg(new Rythm());
if (r.search(s)) {
p(r);
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ExpressionParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.DialectNotSupportException;
import com.greenlaw110.rythm.internal.TemplateParser;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.dialect.SimpleRythm;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IDialect;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
/**
* Single line expression parser
*
* @author luog
*/
public class ExpressionParser extends CaretParserFactoryBase {
private static class ExpressionToken extends CodeToken {
private static void assertSimple(String symbol, IContext context) {
boolean isSimple = symbol.indexOf(".") == -1 && symbol.indexOf("[") == -1;
if (!isSimple) throw new TemplateParser.NotSIMTemplate();
}
public ExpressionToken(String s, IContext context) {
super(s, context);
if (context.getDialect() instanceof SimpleRythm) {
s = S.stripBrace(s);
// simple rythm dialect support only simple expression
int pos = s.indexOf("("); // find out the method name
if (pos != -1) {
String methodName = s.substring(0, pos);
assertSimple(methodName, context);
} else {
// find out array
pos = s.indexOf("[");
if (pos != -1) {
s = s.substring(0, pos);
}
assertSimple(s, context);
context.getCodeBuilder().addRenderArgs(context.currentLine(), pos == -1 ? "Object" : "Object[]", s);
}
}
}
@Override
public void output() {
boolean needsPrint = true;
int pos = s.indexOf("(");
if (pos != -1) {
String tagName = s.substring(0, pos).trim();
if (!S.isEmpty(tagName)) {
needsPrint = ctx.getCodeBuilder().needsPrint(tagName);
}
}
outputExpression(needsPrint);
}
}
@Override
public IParser create(IContext ctx) {
Regex r1_ = null, r2_ = null;
String caret_ = null;
final IDialect dialect = ctx.getDialect();
if (dialect instanceof Rythm || dialect instanceof SimpleRythm) {
caret_ = dialect.a();
r1_ = new Regex(String.format(patternStr(), caret_));
r2_ = new Regex(String.format("^(%s(?@())*).*", caret_));
}
final Regex r1 = r1_, r2 = r2_;
final String caret = caret_;
if (null == r1 || null == r2) {
throw new DialectNotSupportException(dialect.id());
}
return new ParserBase(ctx){
@Override
public TextBuilder go() {
String s = remain();
if (r1.search(s)) {
s = r1.stringMatched(1);
if (null != s && !caret.equals(s.trim())) {
step(s.length());
s = s.replaceFirst(caret, "");
return new ExpressionToken(s, ctx());
}
}
s = remain();
if (r2.search(s)) {
s = r2.stringMatched(1);
if (null != s && !"@".equals(s.trim())) {
step(s.length());
return new ExpressionToken(s.replaceFirst(caret, ""), ctx());
}
}
return null;
}
};
}
protected String patternStr() {
return "^(%s[a-zA-Z_][a-zA-Z0-9_\\.]*((\\.[a-zA-Z][a-zA-Z0-9_\\.]*)*(?@[])*(?@())*)((\\.[a-zA-Z][a-zA-Z0-9_\\.]*)*(?@[])*(?@())*)*)*";
}
public static void main(String[] args) {
String ps = "^(@[a-zA-Z][a-zA-Z$_\\.]+\\s*(?@())*).*";
Regex r = new Regex(ps);
String s = "@xyz(bar='c', foo=bar.length(), zee=component[foo], \"hello\");";
//String s = "@ is something";
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
}
ps = String.format(new ExpressionParser().patternStr(), "@");
System.out.println(ps);
r = new Regex(ps);
//s = "@a.b() is something";
s = "@component.left()[3]()[] + 'c'";
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
}
String m = "abd3_d90 (dsa)";
System.out.println(m.substring(0, m.indexOf("(")));
}
}
<file_sep>/samples/Issue57/Issue57.java
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.utils.IO;
import com.greenlaw110.rythm.utils.S;
import java.io.File;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 28/06/12
* Time: 6:43 AM
* To change this template use File | Settings | File Templates.
*/
public class Issue57 {
public static void main(String[] args) throws Exception {
File d = new File(System.getProperty("java.io.tmpdir"));
Properties p = new Properties();
p.setProperty("rythm.root", d.getAbsolutePath());
p.setProperty("rythm.mode", "dev");
Rythm.init(p);
File f1 = new File(d, "f1.html");
IO.writeContent("@extends(f2)@set(title=\"foo\")", f1);
File f2 = new File(d, "f2.html");
IO.writeContent("@get(title)", f2);
assertEquals(Rythm.render("f1.html"), "foo\n");
IO.writeContent("@extends(f2)@set(title=\"bar\")", f1);
assertEquals(Rythm.render("f1.html"), "foo\n");
for (int i = 0; i < 5; ++i) {
sleep(6);
IO.writeContent("@extends(f2)@set(title=\"baz\")", f1);
assertEquals(Rythm.render("f1.html"), "baz\n");
}
}
private static void assertEquals(String s1, String s2) {
if (!S.isEqual(s1, s2)) throw new RuntimeException(s1 + " doesn't match " + s2);
}
private static void sleep(int n) throws InterruptedException {
for (int i = 0; i < n; ++i) {
Thread.sleep(1000L);
System.out.print(".");
}
System.out.println();
}
}
<file_sep>/samples/Issue88a/Main.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.template.ITemplate;
import com.greenlaw110.rythm.utils.IImplicitRenderArgProvider;
public class Main {
public static void main(String[] args) {
final Properties props = new Properties();
props.put("rythm.root", "p:\\rythm\\sample\\Issue88a");
//props.put("rythm.mode", "dev");
Rythm.init(props);
final Map<String, Object> params = new HashMap<String, Object>();
params.put("message", "Hello World");
System.out.println(Rythm.render("test.html", params));
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/template/ToStringTemplateBase.java
package com.greenlaw110.rythm.template;
import com.greenlaw110.rythm.toString.ToStringStyle;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 14/07/12
* Time: 9:07 PM
* To change this template use File | Settings | File Templates.
*/
public abstract class ToStringTemplateBase extends TagBase {
protected ToStringStyle __style = ToStringStyle.DEFAULT_STYLE;
protected void foo() {
__style.append(out(), "", "", null);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ImportParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.internal.CodeBuilder;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.parser.Directive;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
import java.util.regex.Matcher;
public class ImportParser extends KeywordParserFactory {
private static final String R = "(%s%s[\\s]+([a-zA-Z0-9_\\.*,\\s]+)(;|\\r?\\n)+).*";
public ImportParser() {
}
protected String patternStr() {
return R;
}
public IParser create(IContext c) {
return new ParserBase(c) {
public TextBuilder go() {
String remain = remain();
String line = null;
Regex r = new Regex(String.format("%s%s(\\([ \t\f]*\\))?[ \t\f]*((?@{}))", a(), keyword()));
if (r.search(remain)) {
String s = r.stringMatched(2);
s = S.strip(s, "{", "}");
step(r.stringMatched().length());
line = s.replaceAll("[\\n\\r]+", ",");
} else {
Matcher m = ptn(dialect()).matcher(remain);
if (!m.matches()) return null;
String s = m.group(1);
step(s.length());
//String imports = s.replaceFirst(String.format("%s%s[\\s]+", a(), keyword()), "").replaceFirst("(;|\\r?\\n)+$", "");
line = m.group(2);
}
/**
* We need to make sure import path added to template class
* to support call tag using import paths. That why we move
* the addImport statement here from Directive.call()
*/
String[] sa = line.split("[;,\\s]+");
CodeBuilder cb = builder();
boolean statik = false;
for (String imp: sa) {
if (S.isEmpty(imp)) continue;
if ("static".equals(imp)) statik = true;
else {
cb.addImport(statik ? "static " + imp : imp);
statik = false;
}
}
return new Directive("", ctx());
}
};
}
@Override
public Keyword keyword() {
return Keyword.IMPORT;
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/internal/parser/build_in/CommentParserTest.java
package com.greenlaw110.rythm.internal.parser.build_in;
import org.junit.Test;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.ut.UnitTest;
import com.greenlaw110.rythm.utils.TextBuilder;
/**
* User: luog
* Date: 2/12/11
* Time: 3:29 PM
*/
public class CommentParserTest extends UnitTest {
private void t(String in, String out) {
setup(in);
IParser p = new CommentParser().create(c);
TextBuilder builder = p.go();
assertNotNull(builder);
builder.build();
assertEquals(builder.toString(), out);
}
@Test
public void test() {
t("@// @if (user.registered()) { <p>hello @user.name()</p> @} \n", "");
}
@Test
public void test2() {
t("@{ if (user.registered()) <p>hello @user.name()</p> }@aaa", "");
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/MacroParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.BlockCodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
/**
* Define and invoke Macro
*/
public class MacroParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.MACRO;
}
public IParser create(IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) raiseParseException("bad @macro statement. Correct usage: @macro(\"macro-name\"){...}");
int curLine = ctx().currentLine();
step(r.stringMatched().length());
String s = r.stringMatched(1);
final String macro = S.stripBraceAndQuotation(s);
return new BlockCodeToken("", ctx()) {
@Override
public void openBlock() {
ctx().getCodeBuilder().pushMacro(macro);
}
@Override
public String closeBlock() {
ctx().getCodeBuilder().popMacro();
return "";
}
};
}
};
}
@Override
protected String patternStr() {
//return "(%s%s[\\s]+([a-zA-Z][a-zA-Z0-9_]+)[\\s\\r\\n\\{]*).*";
return "%s%s\\s*((?@()))[\\s]*\\{?\\s*";
}
public static void main(String[] args) {
Regex r = new MacroParser().reg(new Rythm());
if (r.search("@macro(\"JS\") abc")) {
p(r);
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/template/TagBase.java
package com.greenlaw110.rythm.template;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.runtime.ITag;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.util.Map;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 25/01/12
* Time: 12:16 AM
* To change this template use File | Settings | File Templates.
*/
public abstract class TagBase extends TemplateBase implements ITag {
protected ILogger logger = Logger.get(TagBase.class);
protected Body _body;
protected Body _context;
private String fullName;
@Override
public ITemplate cloneMe(RythmEngine engine, ITemplate caller) {
Map<String, String> m = null;
TagBase newTag = (TagBase)super.cloneMe(engine, caller);
newTag._body = null;
//newTag._out = new StringBuilder();
return newTag;
}
@Override
public void setRenderArgs(Map<String, Object> args) {
super.setRenderArgs(args);
if (args.containsKey("_body")) _body = (Body)args.get("_body");
}
@Override
public void setRenderArg(String name, Object arg) {
if ("_body".equals(name)) _body = (Body)arg;
super.setRenderArg(name, arg);
}
public TextBuilder setBodyContext(Body body) {
this._context = body;
return this;
}
@Override
public void call() {
if (null != _context) {
_out = new StringBuilder();
_context.p(S.raw(render()));
} else if (null != _caller && null != _out) {
_caller.p(S.raw(render())); // a real tag
} else {
render(); // an normal template
}
}
protected void _pTagBody(ParameterList parameterList, StringBuilder out) {
if (null == _body) return;
_body.render(parameterList, out);
}
@Override
protected void _pLayoutContent() {
if (null != _body) _body.render(null, out());
else super._pLayoutContent();
}
@Override
public String getName() {
return null;
}
public String str() {
return Rythm.renderStr("@args com.greenlaw110.rythm.runtime.ITag tag; Tag[tag.getName()|tag.getClass()]", this);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/dialect/SimpleRythm.java
package com.greenlaw110.rythm.internal.dialect;
import com.greenlaw110.rythm.internal.parser.build_in.*;
import com.greenlaw110.rythm.spi.IContext;
public class SimpleRythm extends DialectBase {
public String id() {
return "simple_rythm";
}
public String a() {
return "@";
}
protected Class<?>[] buildInParserClasses() {
// InvokeTagParse must be put in front of ExpressionParser as the later's matching pattern covers the former
// BraceParser must be put in front of ElseIfParser
return new Class<?>[]{AssignParser.class, BreakParser.class, ContinueParser.class,
CommentParser.class, DebugParser.class, EscapeParser.class, ElseForParser.class, ElseIfParser.class, BraceParser.class,
InvokeParser.class, InvokeTagParser.class, ExpressionParser.class, ForEachParser.class, IfParser.class,
ImportParser.class, NoSIMParser.class, RawParser.class, ReturnParser.class, SimpleParser.class,
TimestampParser.class, VerbatimParser.class};
}
@Override
public boolean isMyTemplate(String template) {
String[] forbidden = {
"@args",
"@extends",
"@section",
"@render",
"@doLayout",
"@doBody",
"@include",
"@set",
"@get",
"@init",
"@expand",
"@exec",
"@macro",
"@compact",
"@nocompact",
"@def ",
"@tag ",
"@nosim"
};
for (String s: forbidden) {
if (template.contains(s)) return false;
}
return true;
}
@Override
public void begin(IContext ctx) {
ctx.getCodeBuilder().setSimpleTemplate(0);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/spi/ICaretParserFactory.java
package com.greenlaw110.rythm.spi;
public interface ICaretParserFactory extends IParserFactory {
String getCaret(IDialect dialect);
}
<file_sep>/samples/Issue60/Issue60.java
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.utils.IO;
import com.greenlaw110.rythm.utils.S;
import java.io.File;
import java.util.Properties;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 28/06/12
* Time: 6:43 AM
* To change this template use File | Settings | File Templates.
*/
public class Issue60 {
public static void main(String[] args) throws Exception {
String[] names = {"aa","bb","cc"};
String result=Rythm.render("@args String[] names;@names.length", names);
System.out.println(result);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/resource/ITemplateResourceLoader.java
package com.greenlaw110.rythm.resource;
import com.greenlaw110.rythm.internal.compiler.TemplateClass;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 27/01/12
* Time: 7:45 AM
* To change this template use File | Settings | File Templates.
*/
public interface ITemplateResourceLoader {
ITemplateResource load(String key);
TemplateClass tryLoadTag(String tagName, TemplateClass tc);
String getFullTagName(TemplateClass tc);
}
<file_sep>/samples/build.xml
<?xml version="1.0" encoding="utf-8" ?>
<project name="rythm_samples" default="all" basedir=".">
<property name="src_hello_world" location="HelloWorld"/>
<property name="src_performance" location="Performance"/>
<property name="src_issue_22" location="Issue22"/>
<property name="src_issue_57" location="Issue57"/>
<property name="src_issue_71" location="Issue71"/>
<property name="src_issue_60" location="Issue60"/>
<property name="src_issue_88" location="Issue88"/>
<property name="src_issue_88a" location="Issue88a"/>
<property name="src_java_tag" location="JavaTag"/>
<property name="classes" location="classes"/>
<property name="lib" location="../lib"/>
<property environment="env"/>
<path id="project.class.path">
<pathelement location="${lib}/pat-1.5.3.jar"/>
<pathelement location="${lib}/org.eclipse.jdt.core-3.7.1.v_B76_R37x.jar"/>
<pathelement location="${lib}/commons-lang3-3.1.jar"/>
<pathelement location="${lib}/rythm-1.0.0-20121210.jar"/>
</path>
<target name="init">
<tstamp/>
<mkdir dir="${classes}"/>
</target>
<target name="compile_hello_world" depends="init">
<javac srcdir="${src_hello_world}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
<copy file="${src_hello_world}/hello.txt" todir="${classes}"/>
</target>
<target name="hello_world" depends="compile_hello_world">
<java classname="HelloWorld" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_performance" depends="init">
<javac srcdir="${src_performance}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
<copy file="${src_performance}/performance.txt" todir="${classes}"/>
</target>
<target name="performance" depends="compile_performance">
<java classname="Performance" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_issue_22" depends="init">
<javac srcdir="${src_issue_22}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="issue_22" depends="compile_issue_22">
<java classname="Issue22" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_issue_57" depends="init">
<javac srcdir="${src_issue_57}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="issue_57" depends="compile_issue_57">
<java classname="Issue57" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_issue_71" depends="init">
<javac srcdir="${src_issue_71}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="issue_71" depends="compile_issue_71">
<java classname="Issue71" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_issue_60" depends="init">
<javac srcdir="${src_issue_60}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
</target>
<target name="issue_60" depends="compile_issue_60">
<java classname="Issue60" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_issue_88" depends="init">
<javac srcdir="${src_issue_88}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
<copy file="${src_issue_88}/issue88.txt" todir="${classes}"/>
</target>
<target name="issue_88" depends="compile_issue_88">
<java classname="Issue88" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_issue_88a" depends="init">
<javac srcdir="${src_issue_88a}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
<copy file="${src_issue_88a}/template.html" todir="${classes}"/>
<copy file="${src_issue_88a}/test.html" todir="${classes}"/>
</target>
<target name="issue_88a" depends="compile_issue_88a">
<java classname="Main" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="compile_java_tag" depends="init">
<javac srcdir="${src_java_tag}" destdir="${classes}" includeantruntime="true">
<classpath refid="project.class.path"/>
</javac>
<copy file="${src_java_tag}/javaTagDemo.txt" todir="${classes}"/>
</target>
<target name="java_tag" depends="compile_java_tag">
<java classname="JavaTags" logError="true" fork="false">
<classpath location="classes"/>
<classpath refid="project.class.path"/>
</java>
</target>
<target name="all" depends="hello_world, issue_22, issue_88, java_tag">
</target>
<target name="clean">
<delete dir="${classes}"/>
<delete>
<fileset dir="." includes="output.*"/>
</delete>
</target>
</project>
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ElseIfParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.internal.parser.Patterns;
import com.greenlaw110.rythm.spi.IBlockHandler;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
/**
* <ul>Recognised the following patterns:
* <li><code>@}? else if (...) {?...@}? </code></li>
* <li><code>@ else ...@</code><li>
*
* @author luog
*
*/
public class ElseIfParser extends CaretParserFactoryBase {
@Override
public IParser create(final IContext ctx) {
return new ParserBase(ctx) {
@Override
public TextBuilder go() {
IBlockHandler bh = ctx().currentBlock();
if (null == bh || ! (bh instanceof IfParser.IfBlockCodeToken)) return null;
String a = dialect().a();
Regex r1 = new Regex(String.format("^((%s\\}?|%s?\\})\\s*(else\\s*if\\s*" + Patterns.Expression + "\\s*\\{?)).*", a, a));
Regex r2 = new Regex(String.format("^((%s\\}?|%s?\\})\\s*(else([\\s\\r\\n\\t]*(\\{|[\\s\\r\\n\\t]+)))).*", a, a));
String s = ctx.getRemain();
String s1 = null;
if (r1.search(s)) {
s1 = r1.stringMatched(1);
if (null == s1) return null;
step(s1.length());
s1 = r1.stringMatched(3);
} else if (r2.search(s)) {
s1 = r2.stringMatched(1);
if (null == s1) return null;
step(s1.length());
s1 = r2.stringMatched(3);
} else {
return null;
}
if (!s1.endsWith("{")) s1 = s1 + "{";
if (!s1.startsWith("}")) s1 = "}" + s1;
try {
ctx.closeBlock();
} catch (ParseException e) {
throw new RuntimeException(e);
}
return new IfParser.IfBlockCodeToken(s1, ctx);
}
};
}
public static void main(String[] args) {
Regex r1 = new Regex(String.format("^((%s\\}?|%s?\\})\\s*(else\\s*if\\s*" + Patterns.Expression + "\\s*\\{?)).*", "@", "@"));
String a = "@";
Regex r2 = new Regex(String.format("^((%s\\}?|%s?\\})\\s*(else([\\s\\r\\n\\t]*(\\{|[\\s\\r\\n\\t]+)))).*", a, a));
String s = "";
// s = "@} else if (X.y[z.a].foo()) {<h1>good</h1>...";
// if (r1.search(s)) {
// System.out.println(r1.stringMatched(1));
// System.out.println(r1.stringMatched(2));
// }
//
// s = "@else if (X.y[z.a].foo()) <h1>good</h1>";
// if (r1.search(s)) {
// System.out.println(r1.stringMatched(1));
// System.out.println(r1.stringMatched(2));
// }
//
// s = "@else <h1>abc</h1>";
// if (r1.search(s)) {
// System.out.println(r1.stringMatched(1));
// System.out.println(r1.stringMatched(2));
// }
// if (r2.search(s)) {
// System.out.println(r2.stringMatched(1));
// System.out.println(r2.stringMatched(2));
// }
//
// s = "@ else \r\n <td>@item.getChange()</td>\r\n <td>@item.getRatio()</td>\r\n @\r\n </tr>\r\n@\r\n </tbody>\r\n </table>\r\n\r\n </body>\r\n</html>\r\n";
// if (r1.search(s)) {
// System.out.println(r1.stringMatched());
// System.out.println(r1.stringMatched(1));
// }
// if (r2.search(s)) {
// System.out.println(r2.stringMatched());
// System.out.println(r2.stringMatched(1));
// System.out.println(r2.stringMatched(2));
// }
// s = "} else if (\"css\".equalsIgnoreCase(type)) { </style> }";
// if (r1.search(s)) {
// System.out.println(r1.stringMatched());
// System.out.println(r1.stringMatched(1));
// System.out.println(r1.stringMatched(2));
// System.out.println(r1.stringMatched(3));
// }
// System.out.println("--------------------------------");
// if (r2.search(s)) {
// System.out.println(r2.stringMatched());
// System.out.println("1" + r2.stringMatched(1));
// System.out.println("2" + r2.stringMatched(2));
// System.out.println(r1.stringMatched(3));
// }
// System.out.println("--------------------------------");
s = "} else \n\t<script type=\"text/javascript\" src=\"@sUrl\" @if (null != id) id=\"@id\" @ @if (null != charset) charset=\"@charset\" @></script> @";
// if (r1.search(s)) {
// System.out.println(r1.stringMatched());
// System.out.println(r1.stringMatched(1));
// System.out.println(r1.stringMatched(2));
// System.out.println(r1.stringMatched(3));
// }
// System.out.println("--------------------------------");
if (r2.search(s)) {
System.out.println(r2.stringMatched());
System.out.println("1" + r2.stringMatched(1));
System.out.println("2" + r2.stringMatched(2));
System.out.println(r1.stringMatched(3));
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/toString/AppendStartToken.java
package com.greenlaw110.rythm.internal.parser.toString;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.utils.TextBuilder;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 15/07/12
* Time: 8:13 PM
* To change this template use File | Settings | File Templates.
*/
public class AppendStartToken extends CodeToken {
private static String getCode() {
return "__style.appendStart(out(), _);";
}
public AppendStartToken(TextBuilder caller) {
super(getCode(), caller);
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/internal/MockContext.java
package com.greenlaw110.rythm.internal;
public class MockContext extends TemplateParser {
public MockContext(CodeBuilder cb) {
super(cb);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/BlockCodeToken.java
package com.greenlaw110.rythm.internal.parser;
import com.greenlaw110.rythm.spi.IBlockHandler;
import com.greenlaw110.rythm.spi.IContext;
public class BlockCodeToken extends CodeToken implements IBlockHandler {
public BlockCodeToken(String s, IContext context) {
super(s, context);
context.openBlock(this);
}
@Override
public void openBlock() {
}
@Override
public String closeBlock() {
return "}";
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/internal/parser/build_in/ExpressionParserTest.java
package com.greenlaw110.rythm.internal.parser.build_in;
import org.junit.Test;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.ut.UnitTest;
import com.greenlaw110.rythm.utils.TextBuilder;
public class ExpressionParserTest extends UnitTest {
private void t(String exp, String output) {
setup(exp);
IParser p = new ExpressionParser().create(c);
TextBuilder builder = p.go();
assertNotNull(builder);
builder.build();
assertEquals(output, b.toString());
}
@Test
public void test() {
t("@a.b() is good", "\np(a.b());");
}
@Test
public void test2ndStyle() {
t("@(a.b() + x) is something", "\np((a.b() + x));");
}
@Test
public void testComplexExpression() {
t("@a.b()[foo.bar()].x() is good", "p(a.b()[foo.bar()].x());");
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/spi/IBlockHandler.java
package com.greenlaw110.rythm.spi;
/**
* the <code>IBlockHandler</code> declare the interface to handle open/close
* of code blocks. Usually the implementation should print some special
* tokens in the 2 methods
*
* @author luog
*
*/
public interface IBlockHandler {
void openBlock();
String closeBlock();
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/dialect/Rythm.java
package com.greenlaw110.rythm.internal.dialect;
import com.greenlaw110.rythm.internal.parser.build_in.*;
public class Rythm extends DialectBase {
public String id() {
return "rythm";
}
public String a() {
return "@";
}
protected Class<?>[] buildInParserClasses() {
// InvokeTagParse must be put in front of ExpressionParser as the later's matching pattern covers the former
// BraceParser must be put in front of ElseIfParser
return new Class<?>[]{AssignParser.class, ArgsParser.class, BreakParser.class, ContinueParser.class,
CacheParser.class, CommentParser.class, CompactParser.class, DebugParser.class, DefTagParser.class,
EscapeParser.class, ElseForParser.class, ElseIfParser.class, ExecParser.class, ExpandParser.class, ExitIfNoClassParser.class,
BraceParser.class, LogTimeParser.class, InvokeParser.class, InvokeMacroParser.class, InvokeTagParser.class,
MacroParser.class, NullableExpressionParser.class, ExpressionParser.class, ExtendsParser.class,
ForEachParser.class, GetParser.class, IfParser.class, ImportParser.class, IncludeParser.class,
InitCodeParser.class, NoCompactParser.class, NoSIMParser.class, RawParser.class, RenderBodyParser.class,
RenderSectionParser.class, ReturnParser.class, SectionParser.class, SetParser.class, SimpleParser.class,
TimestampParser.class, VerbatimParser.class};
}
public boolean isMyTemplate(String template) {
return true; // default all template is Rythm template
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ExtendsParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.Directive;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parse @extends path/to/mylayout.html or @extends path.to.mylayout.html
*/
public class ExtendsParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.EXTENDS;
}
private static void error(IContext ctx) {
raiseParseException(ctx, "Error parsing extends statement. The correct format is @extends(\"my.parent.template\"[, arg1=val1, val2, ...])");
}
public IParser create(IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) {
error(ctx());
}
final int lineNo = currentLine();
step(r.stringMatched().length());
String s = r.stringMatched(2);
if (null == s) {
error(ctx());
}
r = innerPattern;
if (!r.search(s)) error(ctx());
// process extend target
s = r.stringMatched(1);
s = S.stripQuotation(s);
final String sExtend = s;
// process extend params
final InvokeTagParser.ParameterDeclarationList params = new InvokeTagParser.ParameterDeclarationList();
s = r.stringMatched(2);
if (!S.isEmpty(s)) {
//r = argsPattern;
r = new Regex("\\G(,\\s*)?((([a-zA-Z_][\\w$_]*)\\s*[=:]\\s*)?((?@())|'.'|(?@\"\")|[0-9\\.]+[l]?|[a-zA-Z_][a-zA-Z0-9_\\.]*(?@())*(?@[])*(?@())*(\\.[a-zA-Z][a-zA-Z0-9_\\.]*(?@())*(?@[])*(?@())*)*)|[_a-zA-Z][a-z_A-Z0-9]*)");
while (r.search(s)) {
params.addParameterDeclaration(r.stringMatched(4), r.stringMatched(5));
}
}
return new Directive(s, ctx()) {
@Override
public void call() {
try {
builder().setExtended(sExtend, params, lineNo);
} catch (NoClassDefFoundError e) {
raiseParseException("error adding includes: " + e.getMessage() + "\n possible cause: lower/upper case issue on windows platform");
}
}
};
}
};
}
@Override
protected String patternStr() {
return "(^%s%s)\\s*((?@())[\\s\\r\\n;]*)";
}
protected static Regex innerPattern = new Regex("\\((.*?)\\s*(,\\s*(.*))?\\)");
protected static Regex argsPattern = new Regex("\\G(,\\s*)?((([a-zA-Z_][\\w$_]*)\\s*[=:]\\s*)?((?@())|'.'|(?@\"\")|[0-9\\.]+[l]?|[a-zA-Z_][a-zA-Z0-9_\\.]*(?@())*(?@[])*(?@())*(\\.[a-zA-Z][a-zA-Z0-9_\\.]*(?@())*(?@[])*(?@())*)*))");
protected String patternStr0() {
return "(%s%s(\\s*\\((.*)\\)|\\s+([_a-zA-Z\\\\\\\\/][a-zA-Z0-9_\\.\\\\\\\\/]+))[;]?)";
}
private static void test1() {
Regex r = new ExtendsParser().reg(new Rythm());
String line = "@extends(\"_panel.html\", a:5, b=foo.bar(4)[1]);";
if (!r.search(line)) {
throw new RuntimeException("1");
}
System.out.println(r.stringMatched());
String s = r.stringMatched(2);
if (null == s) {
throw new RuntimeException("2");
}
r = innerPattern;
System.out.println(s);
if (!r.search(s)) {
throw new RuntimeException("3");
}
// process extend target
s = r.stringMatched(1);
if (s.startsWith("\"") || s.startsWith("'")) {
s = s.substring(1);
}
if (s.endsWith("\"") || s.endsWith("'")) {
s = s.substring(0, s.length() - 1);
}
final String sExtend = s;
System.out.println(sExtend);
// process extend params
final InvokeTagParser.ParameterDeclarationList params = new InvokeTagParser.ParameterDeclarationList();
s = r.stringMatched(2);
if (!S.isEmpty(s)) {
s = s.replaceFirst(",\\s*", "");
r = argsPattern;
while (r.search(s)) {
params.addParameterDeclaration(r.stringMatched(4), r.stringMatched(5));
}
}
System.out.println(s);
System.out.println(params);
}
public static void main(String[] args) {
test2();
}
public static void test2() {
Regex r = new Regex("\\G(,\\s*)?((([a-zA-Z_][\\w$_]*)\\s*[=:]\\s*)?((?@())|'.'|(?@\"\")|[0-9\\.]+[l]?|[a-zA-Z_][a-zA-Z0-9_\\.]*(?@())*(?@[])*(?@())*(\\.[a-zA-Z][a-zA-Z0-9_\\.]*(?@())*(?@[])*(?@())*)*)|[_a-zA-Z][a-z_A-Z0-9]*)");
String s = "(ab().fpp[9]+xx)";
while (r.search(s)) {
System.out.println(r.stringMatched());
}
}
public static void test0() {
Regex r = new ExtendsParser().reg(new Rythm());
String s = "@extends('ab/cd.foo', 'a': 6, \"b\"=null); acd";
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
System.out.println(r.stringMatched(2));
System.out.println(r.stringMatched(3));
}
System.out.println("--------------------");
s = r.stringMatched(2);
r = innerPattern;
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
System.out.println(r.stringMatched(2));
System.out.println(r.stringMatched(3));
}
System.out.println("-----------------");
s = r.stringMatched(1);
if (s.startsWith("\"") || s.startsWith("'")) {
s = s.substring(1);
}
if (s.endsWith("\"") || s.endsWith("'")) {
s = s.substring(0, s.length() - 1);
}
System.out.println(s);
// //s = "main/rythm.html";
//
// //Pattern p = Pattern.compile("('([_a-zA-Z][\\w_\\.]*)'|([_a-zA-Z][\\w_\\.]*)|\"([_a-zA-Z][\\w_\\.]*)\")");
// Pattern p = Pattern.compile("('([_a-zA-Z][\\w_\\.]*)'|([_a-zA-Z][\\w_\\.]*)|\"([_a-zA-Z][\\w_\\.]*)\")");
// Matcher m = p.matcher(s);
// if (m.matches()) {
// System.out.println(m.group(1));
// System.out.println(m.group(4));
// }
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/ut/UnitTest.java
package com.greenlaw110.rythm.ut;
import com.greenlaw110.rythm.internal.MockCodeBuilder;
import com.greenlaw110.rythm.internal.MockContext;
import com.greenlaw110.rythm.internal.dialect.DialectBase;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.Directive;
import com.greenlaw110.rythm.utils.TextBuilder;
public class UnitTest extends org.junit.Assert {
protected DialectBase d = new Rythm();
protected MockContext c;
protected MockCodeBuilder b;
protected void setup(String template) {
b = new MockCodeBuilder(template, "test", null);
c = new MockContext(b);
}
protected void call(TextBuilder b) {
if (b instanceof Directive) {
((Directive)b).call();
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/spi/ExtensionManager.java
package com.greenlaw110.rythm.spi;
import com.greenlaw110.rythm.ITagInvokeListener;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.exception.DialectNotFoundException;
import java.util.ArrayList;
import java.util.List;
public class ExtensionManager {
private RythmEngine engine;
public ExtensionManager(RythmEngine engine) {
this.engine = engine;
}
RythmEngine engine() {
return null == engine ? Rythm.engine : engine;
}
public ExtensionManager registerUserDefinedParsers(IParserFactory... parsers) {
return registerUserDefinedParsers(null, parsers);
}
/**
* Register a special case parser to a dialect
*
* <p>for example, the play-rythm plugin might want to register a special case parser to
* process something like @{Controller.actionMethod()} or &{'MSG_ID'} etc to "japid"
* and "play-groovy" dialects
*
* @param dialect
* @param parsers
*/
public ExtensionManager registerUserDefinedParsers(String dialect, IParserFactory... parsers) {
engine().getDialectManager().registerExternalParsers(dialect, parsers);
return this;
}
private List<ITemplateExecutionExceptionHandler> exceptionHandlers = new ArrayList<ITemplateExecutionExceptionHandler>();
public ExtensionManager registerTemplateExecutionExceptionHandler(ITemplateExecutionExceptionHandler h) {
if (!exceptionHandlers.contains(h)) exceptionHandlers.add(h);
return this;
}
public Iterable<ITemplateExecutionExceptionHandler> exceptionHandlers() {
return exceptionHandlers;
}
private List<IExpressionProcessor> expressionProcessors = new ArrayList<IExpressionProcessor>();
public ExtensionManager registerExpressionProcessor(IExpressionProcessor p) {
if (!expressionProcessors.contains(p)) expressionProcessors.add(p);
return this;
}
public Iterable<IExpressionProcessor> expressionProcessors() {
return expressionProcessors;
}
private List<ITagInvokeListener> tagInvokeListeners = new ArrayList<ITagInvokeListener>();
public ExtensionManager registerTagInvoeListener(ITagInvokeListener l) {
if (!tagInvokeListeners.contains(l)) tagInvokeListeners.add(l);
return this;
}
public Iterable<ITagInvokeListener> tagInvokeListeners() {
return tagInvokeListeners;
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/EscapeParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.BlockCodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.template.ITemplate;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
import java.util.Arrays;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parse @raw() {...}
*/
public class EscapeParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.ESCAPE;
}
public IParser create(IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) return null;
int curLine = ctx().currentLine();
step(r.stringMatched().length());
String s = r.stringMatched(1);
s = S.stripBraceAndQuotation(s);
if (S.isEmpty(s)) s = "HTML";
else if ("JavaScript".equalsIgnoreCase(s)) s = "JS";
else s = s.toUpperCase();
if (Arrays.binarySearch(ITemplate.Escape.stringValues(), s) < 0) {
raiseParseException("Error parsing @escape statement. Escape parameter expected to be one of %s, found: %s", Arrays.asList(ITemplate.Escape.stringValues()), s);
}
s = String.format("__ctx.pushEscape(com.greenlaw110.rythm.template.ITemplate.Escape.%s);", s);
return new BlockCodeToken(s, ctx()) {
@Override
public void openBlock() {
}
@Override
public String closeBlock() {
return "__ctx.popEscape();";
}
};
}
};
}
@Override
protected String patternStr() {
return "%s%s\\s*((?@()))[\\s]+\\{?\\s*";
}
public static void main(String[] args) {
Regex r = new EscapeParser().reg(new Rythm());
if (r.search("@escape(JS) \nab")) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/spi/IExpressionProcessor.java
package com.greenlaw110.rythm.spi;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 28/03/12
* Time: 1:53 PM
* To change this template use File | Settings | File Templates.
*/
public interface IExpressionProcessor {
/**
* Process the expression. Return true if processed false otherwise
* @param exp
* @param token
* @return
*/
boolean process(String exp, Token token);
}
<file_sep>/src/main/java/com/greenlaw110/rythm/template/JavaTagBase.java
package com.greenlaw110.rythm.template;
import com.greenlaw110.rythm.exception.RythmException;
import com.greenlaw110.rythm.internal.compiler.TemplateClass;
import com.greenlaw110.rythm.runtime.ITag;
import com.greenlaw110.rythm.utils.TextBuilder;
/**
* classes extends JavaTagBase are not template based, it's kind of like FastTag in Play
*/
public abstract class JavaTagBase extends TagBase{
protected ITag.ParameterList _params;
protected Body _body;
public void setRenderArgs(ITag.ParameterList params) {
_params = null == params ? new ParameterList() : params;
_properties.putAll(params.asMap());
}
@Override
public void setRenderArg(String name, Object val) {
if ("_body".equals(name)) _body = (Body)val;
super.setRenderArg(name, val);
}
@Override
public TextBuilder build() {
if (null == _params) _params = new ParameterList();
call(_params, _body);
return this;
}
@Override
protected void internalBuild() {
build();
}
/**
* Subclass overwrite this method and call various p() methods to render the output
* @param params
* @param body
*/
abstract protected void call(ITag.ParameterList params, Body body);
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ReturnParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
/**
* Parse @return() statement. Which break the current template execution and return to caller
*/
public class ReturnParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.RETURN;
}
public IParser create(final IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) {
raiseParseException("error parsing @return, correct usage: @return()");
}
step(r.stringMatched().length());
return new CodeToken("if (true) {return this;}", ctx());
}
};
}
@Override
protected String patternStr() {
return "^(%s%s\\s*(\\(\\s*\\))?[\\s;]*)";
}
public static void main(String[] args) {
String s = "@return \naba";
ReturnParser ap = new ReturnParser();
Regex r = ap.reg(new Rythm());
if (r.search(s)) {
System.out.println("m: " + r.stringMatched());
System.out.println("1: " + r.stringMatched(1));
System.out.println("2: " + r.stringMatched(2));
System.out.println("3: " + r.stringMatched(3));
System.out.println("4: " + r.stringMatched(4));
System.out.println("5: " + r.stringMatched(5));
}
}
}
<file_sep>/samples/HelloWorld/HelloWorld.java
import com.greenlaw110.rythm.Rythm;
import java.util.HashMap;
import java.util.Map;
public class HelloWorld {
public String who;
public HelloWorld(String who) {
this.who = who;
}
public static void main(String[] args) {
// render a file and pass args by position
System.out.println(Rythm.render("hello.txt", "rythm"));
// render a string and pass args by position
System.out.println(Rythm.render("hello @who!", "java"));
Map<String, Object> params = new HashMap<String, Object>();
params.put("who", "world");
// render a file and pass args by name
System.out.println(Rythm.render("hello.txt", params));
// render a string and pass args by name
System.out.println(Rythm.render("hello @who!", params));
// toString
System.out.println(Rythm.toString("hello @_.who!", new HelloWorld("world")));
// benchmark rythm.render vs. string.format
Rythm.render("now: @i", 0); // compile the template for the first time
long ts = System.currentTimeMillis();
for (int i = 0; i < 1000000; ++i) {
Rythm.render("now: @i", i);
}
long rythm = System.currentTimeMillis() - ts;
ts = System.currentTimeMillis();
for (int i = 0; i < 1000000; ++i) {
String.format("now: %s", i);
}
long string = System.currentTimeMillis() - ts;
System.out.println(String.format("rythm: %s; string: %s", rythm, string));
}
}<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/CommentParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.internal.parser.Directive;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* CommentParser deals with the following type comments:
* 1. inline comment. e.g. @//this is my comment \n
* 2. block comment. e.g. @* this is my multi \nline comments *@
* User: luog
* Date: 2/12/11
* Time: 3:04 PM
*/
public class CommentParser extends CaretParserFactoryBase {
public IParser create(IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Pattern p = inlineComment();
Matcher m = p.matcher(remain());
if (!m.matches()) {
p = blockComment();
m = p.matcher(remain());
if (!m.matches()) return null;
}
String s = m.group(1);
ctx().step(s.length());
return new Directive(s, ctx());
}
private Pattern inlineComment() {
return Pattern.compile(String.format("^(%s//.*?\n).*", a()), Pattern.DOTALL);
}
private Pattern blockComment() {
return Pattern.compile(String.format("^(%s\\*.*?\\*%s).*", a(), a()), Pattern.DOTALL);
}
};
}
public static void main(String[] args) {
Pattern p = Pattern.compile(String.format("^(%s//.*?\n).*", "@"), Pattern.DOTALL);
Matcher m = p.matcher("@// abc.foo() @xyz, @if \n abcd adf @each ");
if (m.matches()) {
System.out.println(m.group(1));
}
p = Pattern.compile(String.format("^(%s\\*.*?\\*%s).*", "@", "@"), Pattern.DOTALL);
m = p.matcher("@* @args include @each @a.b() #\n@//abc\nadfd *@ Hello world @abcd");
if (m.matches()) {
System.out.println(m.group(1));
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/spi/IKeyword.java
package com.greenlaw110.rythm.spi;
/**
* Created by IntelliJ IDEA.
* User: luog
* Date: 29/01/12
* Time: 11:15 AM
* To change this template use File | Settings | File Templates.
*/
public interface IKeyword {
boolean isRegexp();
}
<file_sep>/src/main/java/com/greenlaw110/rythm/toString/TSNode.java
package com.greenlaw110.rythm.toString;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A TSNode (ToString Node) represents an object to be put into the toString stream
*/
public class TSNode {
public Class<?> type = null;
public Map<String, String> expressions = new HashMap<String, String>();
@Override
public boolean equals(Object obj) {
if (obj == this) return true;
if (obj instanceof TSNode) {
return ((TSNode)obj).type.equals(type);
}
return false;
}
public static TSNode parseClass(Class<?> clazz) {
Field f = null;
Class c = f.getType();
c.getComponentType();
Type t = f.getGenericType();
//t.
return null;
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/Rythm.java
package com.greenlaw110.rythm;
import com.greenlaw110.rythm.internal.dialect.DialectManager;
import com.greenlaw110.rythm.logger.ILoggerFactory;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.runtime.ITag;
import com.greenlaw110.rythm.spi.ExtensionManager;
import com.greenlaw110.rythm.spi.ITemplateClassEnhancer;
import com.greenlaw110.rythm.template.ITemplate;
import com.greenlaw110.rythm.toString.ToStringOption;
import com.greenlaw110.rythm.toString.ToStringStyle;
import com.greenlaw110.rythm.utils.IRythmListener;
import java.io.File;
import java.util.*;
public class Rythm {
public static enum Mode {
dev, prod;
public boolean isDev() {
return dev == this;
}
public boolean isProd() {
return prod == this;
}
}
public static enum ReloadMethod {
V_VERSION,
RESTART
}
public static RythmEngine engine = null;
public static final String version = engine.version;
public static void init(Properties conf) {
engine = new RythmEngine(conf);
}
public static void init() {
engine = new RythmEngine();
}
private static void checkInit() {
if (null == engine) init();
}
public static RythmEngine engine() {
checkInit();
return engine;
}
public static void registerLoggerFactory(ILoggerFactory fact) {
Logger.registerLoggerFactory(fact);
}
public static void registerListener(IRythmListener listener) {
engine().registerListener(listener);
}
public static void unregisterListener(IRythmListener listener) {
engine().unregisterListener(listener);
}
public static void clearListener() {
engine().clearListener();
}
public static void registerTemplateClassEnhancer(ITemplateClassEnhancer enhancer) {
engine().registerTemplateClassEnhancer(enhancer);
}
public static void unregisterTemplateClassEnhancer(ITemplateClassEnhancer enhancer) {
engine().unregisterTemplateClassEnhancer(enhancer);
}
public static void clearTemplateClassEnhancer() {
engine().clearTemplateClassEnhancer();
}
public static boolean registerTag(ITag tag) {
return engine().registerTag(tag);
}
public boolean registerTag(String name, ITag tag) {
return engine().registerTag(name, tag);
}
public boolean isProdMode() {
return engine().isProdMode();
}
public static String render(String template, Object... args) {
return engine().render(template, args);
}
public static String render(File file, Object... args) {
return engine().render(file, args);
}
public static String toString(String template, Object obj) {
return engine().toString(template, obj);
}
public static String toString(Object obj) {
return engine().toString(obj);
}
public static String toString(Object obj, ToStringOption option, ToStringStyle style) {
return engine().toString(obj, option, style);
}
public static String commonsToString(Object obj, ToStringOption option, org.apache.commons.lang3.builder.ToStringStyle style) {
return engine().commonsToString(obj, option, style);
}
public static String renderStr(String template, Object... args) {
return engine().renderString(template, args);
}
public static String renderString(String template, Object... args) {
return engine().renderString(template, args);
}
public static String renderIfTemplateExists(String template, Object... args) {
return engine().renderIfTemplateExists(template, args);
}
public static void shutdown() {
engine().shutdown();
}
public static void main(String[] args) {
String template = "@args java.util.List<String> users, String title, String name; @each String u: users @u @ title: @title name: @name ";
List<String> l = new ArrayList<String>();
l.add("green");l.add("cherry");
ITemplate t = engine.getTemplate(template);
t.setRenderArg("users", l);
t.setRenderArg(2, "Green");
t.setRenderArg(1, "Mr.");
System.out.println(t.render());
}
public static void main2(String[] args) {
String s = "@args java.util.Properties component; <input type='checkbox' @if (Boolean.valueOf(String.valueOf(component.get(\"checked\")))) checked @ >";
Properties p = new Properties();
p.put("checked", "true");
Map<String, Object> m = new HashMap<String, Object>();
m.put("component", p);
System.out.println(render(s, m));
}
public static void main1(String[] args) {
String template = "@args String who1, String who2; Hello @who1 and @who2!";
Map<String, Object> m = new HashMap<String, Object>();
m.put("who1", "uni");
m.put("who2", "world");
long start = System.currentTimeMillis();
System.out.println(render(template, m));
System.out.println(String.format("%s ms to render inline template at first time", System.currentTimeMillis() - start));
start = System.currentTimeMillis();
String r = "";
for (int i = 0; i < 500000; ++i) {
r = render(template, m);
}
System.out.println();
System.out.println(r);
System.out.println(String.format("%s ms to render for 500000 times", System.currentTimeMillis() - start));
start = System.currentTimeMillis();
for (int i = 0; i < 500000; ++i) {
r = String.format("Hello %s and %s", "uni", "world");
}
System.out.println();
System.out.println(r);
System.out.println(String.format("%s ms to string format for 500000 times", System.currentTimeMillis() - start));
}
// --- SPI interfaces ---
public static DialectManager getDialectManager() {
return engine().getDialectManager();
}
public static ExtensionManager getExtensionManager() {
return engine().getExtensionManager();
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/utils/IDurationParser.java
package com.greenlaw110.rythm.utils;
/**
* Parse duration
*/
public interface IDurationParser {
/**
* Parse duration
* @param s
* @return duration in seconds
*/
int parseDuration(String s);
public static final IDurationParser DEFAULT_PARSER = new IDurationParser() {
@Override
public int parseDuration(String s) {
return Time.parseDuration(s);
}
};
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ExecMacroToken.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.CodeBuilder;
import com.greenlaw110.rythm.internal.parser.CodeToken;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.util.List;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 19/07/12
* Time: 9:24 AM
* To change this template use File | Settings | File Templates.
*/
public class ExecMacroToken extends CodeToken {
public ExecMacroToken(String macro, IContext context, int line) {
super(macro, context);
this.line = line;
}
@Override
public void output() {
CodeBuilder cb = ctx.getCodeBuilder();
if (!cb.hasMacro(s)) {
throw new ParseException(ctx.getEngine(), ctx.getTemplateClass(), line, "Cannot find macro definition for \"%s\"", s);
}
List<TextBuilder> list = cb.getMacro(s);
for (TextBuilder tb: list) {
tb.build();
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/compiler/TemplateClass.java
package com.greenlaw110.rythm.internal.compiler;
import com.greenlaw110.rythm.Rythm;
import com.greenlaw110.rythm.RythmEngine;
import com.greenlaw110.rythm.exception.CompileException;
import com.greenlaw110.rythm.exception.RythmException;
import com.greenlaw110.rythm.internal.CodeBuilder;
import com.greenlaw110.rythm.logger.ILogger;
import com.greenlaw110.rythm.logger.Logger;
import com.greenlaw110.rythm.resource.ITemplateResource;
import com.greenlaw110.rythm.resource.StringTemplateResource;
import com.greenlaw110.rythm.spi.IDialect;
import com.greenlaw110.rythm.spi.ITemplateClassEnhancer;
import com.greenlaw110.rythm.template.ITemplate;
import com.greenlaw110.rythm.template.TemplateBase;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import java.io.File;
import java.lang.reflect.Modifier;
import java.util.*;
import java.util.concurrent.atomic.AtomicLong;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Define the data structure hold template class/template src/generated java src
*/
public class TemplateClass {
private static AtomicLong nextVersion = new AtomicLong();
private static final ILogger logger = Logger.get(TemplateClass.class);
/**
* Store root level template class, e.g. the one that is not an embedded class
*/
private TemplateClass root;
public TemplateClass root() {
return root;
}
private TemplateClass() {}
private boolean inner = false;
public static TemplateClass createInnerClass(String className, byte[] byteCode, TemplateClass parent) {
TemplateClass tc = new TemplateClass();
tc.name = className;
tc.javaByteCode = byteCode;
//tc.enhancedByteCode = byteCode;
tc.inner = true;
tc.root = parent.root();
tc.version = parent.version();
return tc;
}
public boolean isInner() {return inner;}
private RythmEngine engine = null;
private RythmEngine engine() {
return null == engine ? Rythm.engine() : engine;
}
/**
* The fully qualified class name
*/
private String name;
public String name0() {
return name;
}
public String name() {
//return isInner() ? name : name + "v" + version;
RythmEngine e = engine();
String n = (!e.reloadByIncClassVersion() || isInner()) ? name : name + "v" + version;
return n;
}
private long version;
public long version() {
return root().version;
}
public void setVersion(int v) {
version = (long)v;
}
public TemplateClass extendedTemplateClass;
private Set<TemplateClass> includedTemplateClasses = new HashSet<TemplateClass>();
public void addIncludeTemplateClass(TemplateClass tc) {
includedTemplateClasses.add(tc);
includeTagTypes.putAll(tc.includeTagTypes);
}
public String includeTemplateClassNames = null;
private static final String NO_INCLUDE_CLASS = "NO_INCLUDE_CLASS";
public String refreshIncludeTemplateClassNames() {
if (includedTemplateClasses.size() == 0) {
includeTemplateClassNames = NO_INCLUDE_CLASS;
return NO_INCLUDE_CLASS;
}
StringBuilder sb = new StringBuilder();
boolean first = true;
for (TemplateClass tc: includedTemplateClasses) {
if (!first) {
sb.append(",");
} else {
first = false;
}
sb.append(engine().resourceManager.getFullTagName(tc));
}
includeTemplateClassNames = sb.toString();
return sb.toString();
}
private Map<String, String> includeTagTypes = new HashMap<String, String>();
public void setTagType(String tagName, String type) {
includeTagTypes.put(tagName, type);
}
public String getTagType(String tagName) {
return includeTagTypes.get(tagName);
}
public boolean returnObject(String tagName) {
String retType = includeTagTypes.get(tagName);
if (null != retType) {
return !"void".equals(retType);
}
if (null != extendedTemplateClass) return extendedTemplateClass.returnObject(tagName);
return true;
}
public String serializeIncludeTagTypes() {
if (includeTagTypes.isEmpty()) return "";
StringBuilder sb = new StringBuilder();
boolean empty = true;
for (String tagName: includeTagTypes.keySet()) {
if (!empty) sb.append(";");
else empty = false;
sb.append(tagName).append(":").append(includeTagTypes.get(tagName));
}
return sb.toString();
}
public void deserializeIncludeTagTypes(String s) {
includeTagTypes = new HashMap<String, String>();
if (S.isEmpty(s)) return;
String[] sa = s.split(";");
for (String s0: sa) {
String[] sa0 = s0.split(":");
if (sa0.length != 2) throw new IllegalArgumentException("Unknown include tag types string: " + s);
includeTagTypes.put(sa0[0], sa0[1]);
}
}
/**
* If not null then this template is a tag
*/
public String tagName() {
return null != templateResource ? templateResource.tagName() : null;
}
transient private String fullName;
public void setFullName(String fn) {
fullName = fn;
}
public String getFullName() {
if (null == fullName) return tagName();
return fullName;
}
/**
* the template resource
*/
public ITemplateResource templateResource;
/**
* The template source
*/
public String getTemplateSource() {
return getTemplateSource(false);
}
public String getTemplateSource(boolean includeRoot) {
if (null != templateResource) return templateResource.asTemplateContent();
if (!includeRoot) return "";
TemplateClass parent = root;
while ((null != parent) && parent.isInner()) {
parent = parent.root;
}
return null == parent ? "" : parent.getTemplateSource();
}
/**
* Is this template resource coming from a literal String or from a loaded resource like file
*/
public boolean isStringTemplate() {
return templateResource instanceof StringTemplateResource;
}
/**
* The Java source
*/
public String javaSource;
/**
* The compiled byteCode
*/
public byte[] javaByteCode;
/**
* The enhanced byteCode
*/
public byte[] enhancedByteCode;
/**
* Store a list of import path, i.e. those imports ends with ".*"
*/
public Set<String> importPaths;
/**
* The in JVM loaded class
*/
public Class<ITemplate> javaClass;
/**
* The in JVM loaded package
*/
public Package javaPackage;
/**
* Is this class compiled
*/
boolean compiled;
/**
* Signatures checksum
*/
public int sigChecksum;
/**
* Mark if this is a valid Rythm Template
*/
public boolean isValid = true;
/**
* CodeBuilder to generate java source code
*
* Could be used to merge state into including template class codeBuilder
*/
public CodeBuilder codeBuilder;
/**
* Indicate this template class represent a simple template
*/
public boolean simpleTemplate;
/**
* The ITemplate instance
*/
private TemplateBase templateInstance;
/**
* specify the dialect for the template
*/
transient private IDialect dialect;
private TemplateClass(RythmEngine engine) {
this.engine = null == engine ? null : engine.isSingleton() ? null : engine;
}
/**
* Construct a TemplateClass instance using template source file
*
* @param file the template source file
*/
public TemplateClass(File file, RythmEngine engine) {
this(engine.resourceManager.get(file), engine);
}
/**
* Construct a TemplateClass instance using template source content or file path
* @param template
*/
public TemplateClass(String template, RythmEngine engine) {
this(engine.resourceManager.get(template), engine);
}
public TemplateClass(ITemplateResource resource, RythmEngine engine) {
this(resource, engine, false);
}
public TemplateClass(ITemplateResource resource, RythmEngine engine, IDialect dialect) {
this(resource, engine, false, dialect);
}
public TemplateClass(ITemplateResource resource, RythmEngine engine, boolean noRefresh) {
this(engine);
if (null == resource) throw new NullPointerException();
templateResource = resource;
if (resource instanceof StringTemplateResource) {
simpleTemplate = true;
}
if (!noRefresh) refresh();
}
public TemplateClass(ITemplateResource resource, RythmEngine engine, boolean noRefresh, IDialect dialect) {
this(engine);
if (null == resource) throw new NullPointerException();
templateResource = resource;
if (resource instanceof StringTemplateResource) {
simpleTemplate = true;
}
this.dialect = dialect;
if (!noRefresh) refresh();
}
/**
* Return string representation of the template
* @return
*/
public Object getKey() {
return null == templateResource ? name() : templateResource.getKey();
}
@SuppressWarnings("unchecked")
private Class<?> getJavaClass() throws Exception {
Class<?> c = engine().classLoader.loadClass(name(), true);
if (null == javaClass) javaClass = (Class<ITemplate>)c;
return c;
}
private static final ITemplate NULL_TEMPLATE = new TemplateBase() {
@Override
public ITemplate cloneMe(RythmEngine engine, ITemplate caller) {
return null;
}
};
private ITemplate templateInstance_() {
if (!isValid) return NULL_TEMPLATE;
if (null == templateInstance) {
try {
if (Logger.isTraceEnabled()) logger.trace("About to new template instance");
Class<?> clz = getJavaClass();
if (Logger.isTraceEnabled()) logger.trace("template java class loaded");
templateInstance = (TemplateBase) clz.newInstance();
templateInstance.setTemplateClass(this);
if (Logger.isTraceEnabled()) logger.trace("template instance generated");
} catch (RythmException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException("Error load template instance for " + getKey(), e);
}
}
if (!engine().isProdMode()) {
// check parent class change
Class<?> c = templateInstance.getClass();
Class<?> pc = c.getSuperclass();
if (null != pc && !Modifier.isAbstract(pc.getModifiers())) {
engine().classes.getByClassName(pc.getName());
}
}
return templateInstance;
}
public ITemplate asTemplate() {
RythmEngine e = engine();
if (null == name || e.mode.isDev()) refresh();
return templateInstance_().cloneMe(engine(), null);
}
public ITemplate asTemplate(ITemplate caller) {
return templateInstance_().cloneMe(engine(), caller);
}
private boolean refreshing = false;
private boolean compiling = false;
private Object refreshLock = new Object();
private boolean refreshing() {
synchronized (refreshLock) {
return refreshing || compiling;
}
}
private void refreshing(boolean b) {
synchronized (refreshLock) {
refreshing = b;
}
}
private void addVersion() {
RythmEngine e = engine();
if (!e.reloadByIncClassVersion()) return;
TemplateClassManager tcc = engine().classes;
tcc.clsNameIdx.remove(name());
//List<TemplateClass> allEmbedded = tcc.getEmbeddedClasses(name0());
version = nextVersion.getAndIncrement();
tcc.clsNameIdx.put(name(), this);
}
public boolean refresh() {
return refresh(false);
}
public void buildSourceCode(String includingClassName) {
long start = System.currentTimeMillis();
addVersion();
importPaths = new HashSet<String>();
// Possible bug here?
if (null != codeBuilder) codeBuilder.clear();
codeBuilder = new CodeBuilder(templateResource.asTemplateContent(), name(), tagName(), this, engine, dialect);
codeBuilder.includingCName = includingClassName;
codeBuilder.build();
extendedTemplateClass = codeBuilder.getExtendedTemplateClass();
javaSource = codeBuilder.toString();
if (logger.isTraceEnabled()) {
logger.trace("%s ms to generate java source for template: %s", System.currentTimeMillis() - start, getKey());
}
}
public void buildSourceCode() {
long start = System.currentTimeMillis();
addVersion();
importPaths = new HashSet<String>();
// Possible bug here?
if (null != codeBuilder) codeBuilder.clear();
if (null == dialect) codeBuilder = new CodeBuilder(templateResource.asTemplateContent(), name(), tagName(), this, engine, null);
else codeBuilder = dialect.createCodeBuilder(templateResource.asTemplateContent(), name(), tagName(), this, engine);
codeBuilder.build();
extendedTemplateClass = codeBuilder.getExtendedTemplateClass();
javaSource = codeBuilder.toString();
if (logger.isTraceEnabled()) {
logger.trace("%s ms to generate java source for template: %s", System.currentTimeMillis() - start, getKey());
}
}
/**
* @return true if this class has changes refreshed, otherwise this class has not been changed yet
*/
public boolean refresh(boolean forceRefresh) {
if (refreshing()) return false;
if (inner) return false;
try {
RythmEngine e = engine();
refreshing(true);
if (!templateResource.isValid()) {
// it is removed?
isValid = false;
engine().classes.remove(this);
return false;
}
if (null == name) {
// this is the root level template class
root = this;
name = templateResource.getSuggestedClassName() + CN_SUFFIX;
//name = templateResource.getSuggestedClassName();
if (e.reloadByIncClassVersion()) version = nextVersion.getAndIncrement();
engine().classes.add(this);
}
if (null == javaSource) {
engine().classCache.loadTemplateClass(this);
if (null != javaSource) {
// try refresh extended template class if there is
Pattern p = Pattern.compile(".*extends\\s+([a-zA-Z0-9_]+)\\s*\\{\\s*\\/\\/<extended_resource_key\\>(.*)\\<\\/extended_resource_key\\>.*", Pattern.DOTALL);
Matcher m = p.matcher(javaSource);
if (m.matches()) {
String extended = m.group(1);
TemplateClassManager tcm = engine().classes;
extendedTemplateClass = tcm.getByClassName(extended);
if (null == extendedTemplateClass) {
String extendedResourceKey = m.group(2);
extendedTemplateClass = tcm.getByTemplate(extendedResourceKey);
if (null == extendedTemplateClass) {
extendedTemplateClass = new TemplateClass(extendedResourceKey, engine());
extendedTemplateClass.refresh();
}
}
engine().addExtendRelationship(extendedTemplateClass, this);
}
}
}
boolean extendedTemplateChanged = false;
if (extendedTemplateClass != null) extendedTemplateChanged = extendedTemplateClass.refresh(forceRefresh);
boolean includedTemplateChanged = false;
if (includedTemplateClasses.size() == 0 && !S.isEmpty(includeTemplateClassNames) && !NO_INCLUDE_CLASS.equals(includeTemplateClassNames)) {
// just loaded from persistent store
for (String tcName: includeTemplateClassNames.split(",")) {
if (S.isEmpty(tcName)) continue;
tcName = tcName.trim();
String fullName = engine().testTag(tcName, this);
if (null == fullName) {
logger.warn("Unable to load included template class from name: %s", tcName);
continue;
}
TemplateClass tc = engine().getTemplateClassFromTagName(fullName);
if (null == tc) {
logger.warn("Unable to load included template class from name: %s", tcName);
continue;
}
includedTemplateClasses.add(tc);
}
}
for (TemplateClass tc: includedTemplateClasses) {
if (tc.refresh(forceRefresh)) {
includedTemplateChanged = true;
break;
}
}
if (extendedTemplateChanged && engine().reloadByRestart() && !forceRefresh) {
reset();
compiled = false;
engine().restart(new ClassReloadException("extended class changed"));
refreshing(false);
refresh(forceRefresh);
return true; // pass refresh state to sub template
}
// templateResource.refresh() must be put at first so we make sure resource get refreshed
boolean resourceChanged = templateResource.refresh();
boolean refresh = resourceChanged || forceRefresh || (null == javaSource) || includedTemplateChanged || extendedTemplateChanged;
if (!refresh) return false;
// now start generate source and compile source to byte code
reset();
buildSourceCode();
engine().classCache.cacheTemplateClassSource(this); // cache source code for debugging purpose
if (!codeBuilder.isRythmTemplate()) {
isValid = false;
engine().classes.remove(this);
return false;
}
isValid = true;
//if (!engine().isProd Mode()) logger.info(javaSource);
compiled = false;
return true;
} finally {
refreshing(false);
}
}
public static final String CN_SUFFIX = "__R_T_C__";
/**
* Is this class already compiled but not defined ?
* @return if the class is compiled but not defined
*/
public boolean isDefinable() {
return compiled && javaClass != null;
}
/**
* Remove all java source/ byte code and cache
*/
public void reset() {
javaByteCode = null;
enhancedByteCode = null;
javaSource = null;
templateInstance = null;
for (TemplateClass tc: embeddedClasses) {
tc.reset();
engine().classes.remove(tc);
}
embeddedClasses.clear();
engine().classCache.deleteCache(this);
engine().invalidate(this);
if (engine().reloadByIncClassVersion()) javaClass = null;
}
/**
* Compile the class from Java source
* @return the bytes that comprise the class file
*/
public byte[] compile() {
if (null != javaByteCode) return javaByteCode;
if (null == javaSource) throw new IllegalStateException("Cannot find java source when compiling " + getKey());
compiling = true;
long start = System.currentTimeMillis();
try {
engine().classes.compiler.compile(new String[]{name()});
if (logger.isTraceEnabled()) {
logger.trace("%sms to compile template: %s", System.currentTimeMillis() - start, getKey());
}
} catch (CompileException.CompilerException e) {
String cn = e.className;
TemplateClass tc = S.isEqual(cn, name()) ? this : engine().classes.getByClassName(cn);
if (null == tc) tc = this;
CompileException ce = new CompileException(engine(), tc, e.javaLineNumber, e.message); // init ce before reset java source to get template line info
javaSource = null; // force parser to regenerate source. This helps to reload after fixing the tag file compilation failure
throw ce;
} catch (NullPointerException e) {
String clazzName = name();
TemplateClass tc = engine().classes.getByClassName(clazzName);
if (this != tc) {
logger.error("tc is not this");
}
if (!this.equals(tc)) {
logger.error("tc not match this");
}
logger.error("NPE encountered when compiling template class:" + name());
throw e;
} finally {
compiling = false;
}
if (logger.isTraceEnabled()) {
logger.trace("%sms to compile template class %s", System.currentTimeMillis() - start, getKey());
}
return javaByteCode;
}
private boolean enhancing = false;
private transient List<TemplateClass> embeddedClasses = new ArrayList<TemplateClass>();
/**
* Used to instruct embedded class byte code needs to be enhanced, but for now
* let's just use the java byte code as the enhanced bytecode
*/
public void delayedEnhance(TemplateClass root) {
enhancedByteCode = javaByteCode;
root.embeddedClasses.add(this);
}
public byte[] enhance() {
if (enhancing) throw new IllegalStateException("reenter enhance() call");
enhancing = true;
try {
byte[] bytes = enhancedByteCode;
if (null == bytes) {
bytes = javaByteCode;
if (null == bytes) bytes = compile();
long start = System.currentTimeMillis();
for (ITemplateClassEnhancer en: engine().templateClassEnhancers) {
try {
bytes = en.enhance(name(), bytes);
} catch (Exception e) {
logger.warn(e, "Error enhancing template class: %s", getKey());
}
}
if (logger.isTraceEnabled()) {
logger.trace("%sms to enhance template class %s", System.currentTimeMillis() - start, getKey());
}
enhancedByteCode = bytes;
engine().classCache.cacheTemplateClass(this);
}
for (TemplateClass embedded: embeddedClasses) {
embedded.enhancedByteCode = null;
embedded.enhance();
}
return bytes;
} finally {
enhancing = false;
}
}
/**
* Unload the class
*/
public void uncompile() {
javaClass = null;
}
public boolean isClass() {
return !name().endsWith("package-info");
}
public String getPackage() {
int dot = name().lastIndexOf('.');
return dot > -1 ? name().substring(0, dot) : "";
}
public void loadCachedByteCode(byte[] code) {
enhancedByteCode = code;
}
// public void compiled(byte[] code, boolean noCache) {
// javaByteCode = code;
// //enhancedByteCode = code;
// compiled = true;
// enhance();
// if (!noCache) engine().classCache.cacheTemplateClass(this);
// }
/**
* Call back when a class is compiled.
* @param code The bytecode.
*/
public void compiled(byte[] code) {
javaByteCode = code;
//enhancedByteCode = code;
compiled = true;
enhance();
//compiled(code, false);
}
@Override
public String toString() {
return "(compiled:" + compiled + ") " + name();
}
@Override
public boolean equals(Object o) {
if (o == this) return true;
if (o instanceof TemplateClass) {
TemplateClass that = (TemplateClass)o;
return that.getKey().equals(getKey());
}
return false;
}
@Override
public int hashCode() {
return getKey().hashCode();
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ForEachCodeToken.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.internal.parser.BlockCodeToken;
import com.greenlaw110.rythm.spi.IContext;
public class ForEachCodeToken extends BlockCodeToken {
private String type;
private String varname;
private String iterable;
private int openPos;
private int closePos;
/**
*
* @each String [str]: myStrList @
* ^ ^ ^ ^
* | | | |
* type varname iterable endloop
*
* @param type
* @param varname
* @param iterable
* @param context
*/
public ForEachCodeToken(String type, String varname, String iterable, IContext context) {
super(null, context);
if (null == type || null == iterable) throw new NullPointerException();
this.type = ObjectType(type);
this.varname = null == varname ? "_" : varname;
this.iterable = iterable;
line--;
openPos = context.cursor();
ctx.pushBreak(IContext.Break.RETURN);
ctx.pushContinue(IContext.Continue.RETURN);
}
private String ObjectType(String type) {
if ("int".equals(type)) return "Integer";
if ("float".equals(type)) return "Float";
if ("double".equals(type)) return "Double";
if ("boolean".equals(type)) return "Boolean";
if ("char".equals(type)) return "Character";
if ("long".equals(type)) return "Long";
if ("byte".equals(type)) return "Byte";
if ("short".equals(type)) return "Integer";
return type;
}
@Override
public void output() {
String prefix = "_".equals(varname) ? "" : varname;
String curClassName = ctx.getCodeBuilder().includingClassName();
int bodySize = closePos - openPos;
String varName = ctx.getCodeBuilder().newVarName();
p("_Itr<").p(type).p("> ").p(varName).p(" = new _Itr(").p(iterable).p(");");
pline();
p("if (").p(varName).p(".size() > 0) {");
pline();
p("com.greenlaw110.rythm.runtime.Each.INSTANCE.render(").p(varName);
p(", new com.greenlaw110.rythm.runtime.Each.Looper<").p(type).p(">(");
p(curClassName).p(".this,").p(bodySize).p("){");
pline();
pt("public boolean render(final ");
p(type).p(" ").p(varname).p(", final int ").p(prefix).p("_size, final int ").p(prefix).p("_index, final boolean ");
p(prefix).p("_isOdd, final String ").p(prefix).p("_parity, final boolean ");
p(prefix).p("_isFirst, final boolean ").p(prefix).p("_isLast, final String ").p(prefix).p("_sep, final com.greenlaw110.rythm.runtime.Each.IBody.LoopUtils ").p(prefix).p("_utils) { ");
pline();
}
@Override
public String closeBlock() {
ctx.popBreak();
closePos = ctx.cursor();
return "\n\t return true;\n\t}});\n}\n";
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/ExitIfNoClassParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.TemplateParser;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.spi.Token;
import com.greenlaw110.rythm.utils.S;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
public class ExitIfNoClassParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.EXIT_IF_NO_CLASS;
}
public IParser create(final IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) {
raiseParseException("error parsing @debug, correct usage: @__exitIfNoClass__(My.Class.Name)");
}
step(r.stringMatched().length());
String s = r.stringMatched(1);
s = S.stripBraceAndQuotation(s);
try {
ctx().getEngine().classLoader.loadClass(s);
return new Token("", ctx());
} catch (Exception e) {
throw new TemplateParser.ExitInstruction();
}
}
};
}
@Override
protected String patternStr() {
return "%s%s\\s*((?@()))[\\s]+";
}
public static void main(String[] args) {
String s = "@__exitIfNoClass__(java.lang.String)\nabc";
ExitIfNoClassParser ap = new ExitIfNoClassParser();
Regex r = ap.reg(new Rythm());
if (r.search(s)) {
System.out.println("m: " + r.stringMatched());
System.out.println("1: " + r.stringMatched(1));
System.out.println("2: " + r.stringMatched(2));
System.out.println("3: " + r.stringMatched(3));
System.out.println("4: " + r.stringMatched(4));
System.out.println("5: " + r.stringMatched(5));
s = r.stringMatched(1);
if (s.startsWith("(")) {
s = s.substring(1);
s = s.substring(0, s.length() - 1);
}
if (s.startsWith("\"") || s.startsWith("'")) {
s = s.substring(1);
}
if (s.endsWith("\"") || s.endsWith("'")) {
s = s.substring(0, s.length() -1);
}
System.out.println(s);
}
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/LogTimeParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.TemplateParser;
import com.greenlaw110.rythm.internal.dialect.Rythm;
import com.greenlaw110.rythm.internal.parser.Directive;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.spi.Token;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
public class LogTimeParser extends KeywordParserFactory {
@Override
public Keyword keyword() {
return Keyword.LOG_TIME;
}
public IParser create(final IContext ctx) {
return new ParserBase(ctx) {
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) {
raiseParseException("error parsing @__logTime__, correct usage: @__logTime__()");
}
step(r.stringMatched().length());
return new Directive("", ctx()) {
@Override
public void call() {
ctx().getCodeBuilder().setLogTime();
}
};
}
};
}
@Override
protected String patternStr() {
return "%s%s\\s*\\(\\s*\\)[\\r\\n]+";
}
public static void main(String[] args) {
String s = "@__logTime__()\nabc";
LogTimeParser ap = new LogTimeParser();
Regex r = ap.reg(new Rythm());
if (r.search(s)) {
p(r);
s = r.stringMatched(1);
if (null == s) return;
if (s.startsWith("(")) {
s = s.substring(1);
s = s.substring(0, s.length() - 1);
}
if (s.startsWith("\"") || s.startsWith("'")) {
s = s.substring(1);
}
if (s.endsWith("\"") || s.endsWith("'")) {
s = s.substring(0, s.length() -1);
}
System.out.println(s);
}
}
}
<file_sep>/src/test/java/com/greenlaw110/rythm/ToStringTest.java
package com.greenlaw110.rythm;
/**
* Created with IntelliJ IDEA.
* User: luog
* Date: 15/07/12
* Time: 9:40 PM
* To change this template use File | Settings | File Templates.
*/
public class ToStringTest {
private String foo;
public int bar;
public String getFoo() {
return foo;
}
public ToStringTest(String foo, int bar) {
this.foo = foo;
this.bar = bar;
}
@Override
public String toString() {
return Rythm.toString(this);
}
public static void main(String[] args) {
System.out.println(Rythm.engine().tmpDir);
ToStringTest tst = new ToStringTest("bar", 5);
String s = Rythm.toString(tst);
System.out.println(s);
}
}
<file_sep>/src/main/java/com/greenlaw110/rythm/internal/parser/build_in/IfParser.java
package com.greenlaw110.rythm.internal.parser.build_in;
import com.greenlaw110.rythm.exception.ParseException;
import com.greenlaw110.rythm.internal.Keyword;
import com.greenlaw110.rythm.internal.parser.BlockCodeToken;
import com.greenlaw110.rythm.internal.parser.ParserBase;
import com.greenlaw110.rythm.spi.IContext;
import com.greenlaw110.rythm.spi.IParser;
import com.greenlaw110.rythm.utils.TextBuilder;
import com.stevesoft.pat.Regex;
public class IfParser extends KeywordParserFactory {
public static class IfBlockCodeToken extends BlockCodeToken {
public IfBlockCodeToken(String s, IContext context) {
super(s, context);
}
}
@Override
public IParser create(final IContext ctx) {
return new ParserBase(ctx) {
@Override
public TextBuilder go() {
Regex r = reg(dialect());
if (!r.search(remain())) {
raiseParseException("Error parsing @if statement. Correct usage: @if (some-condition) {some-template-code}");
}
String s = r.stringMatched(1);
ctx.step(s.length());
s = r.stringMatched(2);
if (!s.endsWith("{")) s = "\n" + s + " {";
return new IfBlockCodeToken(s, ctx);
}
};
}
@Override
public Keyword keyword() {
return Keyword.IF;
}
@Override
protected String patternStr() {
//return "(%s(%s\\s+\\(.*\\)(\\s*\\{)?)).*";
return "(^%s(%s\\s*((?@()))(\\s*\\{)?)).*";
}
public static void main(String[] args) {
String p = String.format(new IfParser().patternStr(), "@", "if");
System.out.println(p);
Regex r = new Regex(p);
String s = "@if (\"TAB\".equalsTo(fbAuthMethod.toString())) {\n";
if (r.search(s)) {
System.out.println(r.stringMatched());
System.out.println(r.stringMatched(1));
System.out.println(r.stringMatched(2));
System.out.println(r.stringMatched(3));
}
}
}
| 7a087bc1a5fca0031b3969bb8981bd2ff3b8a007 | [
"Java",
"Ant Build System"
] | 61 | Java | gspandy/Rythm | 7c8670ec02e249aa8086b27b0161a31fdff83de9 | b05555caca6e59c14d892d5182f007c8ee6971f8 |
refs/heads/master | <repo_name>cankei/tic-tac-toe<file_sep>/README.md
# tic-tac-toe
A basic Tic-tac-toe written with AngularJs.
Play it online:
https://tic-tac-toe-dc865.firebaseapp.com
### Get started
Install dependencies: `npm install`
Run unit tests: `npm test`
Open the app in browser: `npm start`
### To-do list
* Make "Restart" button contextual to game state.
* Add CSS animation to visualise the winning line.
* Add more unit test coverage for the controller methods.
<file_sep>/www/js/tic-tac-toe-board-service.js
angular.module('tic-tac-toe-board-service', []).factory('TicTacToeBoardService', function () {
var SIZE = 3;
var board = [];
var totalPlacedCells = 0;
return {
getBoard: function () {
return board;
},
getTotalPlacedCells: function () {
return totalPlacedCells;
},
reset: function () {
totalPlacedCells = 0;
board = [
[
{value: ''}, {value: ''}, {value: ''}
], [
{value: ''}, {value: ''}, {value: ''}
], [
{value: ''}, {value: ''}, {value: ''}
]
]
},
placeAt: function (row, column, player) {
var cell = board[row][column];
if (!cell.value) {
cell.value = player;
totalPlacedCells++;
}
},
isFull: function () {
return totalPlacedCells >= SIZE * SIZE;
},
checkWinner: function () {
for (var i = 0; i < SIZE; ++i) {
if (board[i][0].value && board[i][0].value === board[i][1].value && board[i][0].value === board[i][2].value)
return board[i][0].value;
if (board[0][i].value && board[0][i].value === board[1][i].value && board[0][i].value === board[2][i].value)
return board[0][i].value;
}
if (board[0][0].value && board[0][0].value === board[1][1].value && board[0][0].value === board[2][2].value)
return board[0][0].value;
if (board[0][2].value && board[0][2].value === board[1][1].value && board[0][2].value === board[2][0].value)
return board[0][2].value;
return '';
}
};
});
<file_sep>/spec/service/tic-tac-toe-board-service-spec.js
describe('Tic Tac Toe Board Service', function () {
var TicTacToeBoardService;
beforeEach(function () {
module('tic-tac-toe-board-service');
});
beforeEach(inject(function (_TicTacToeBoardService_) {
TicTacToeBoardService = _TicTacToeBoardService_;
}));
it('can get an instance of TicTacToeBoardService', function () {
expect(TicTacToeBoardService).toBeDefined();
});
describe('placeAt method', function () {
beforeEach(function () {
TicTacToeBoardService.reset();
});
it('can place a move', function () {
TicTacToeBoardService.placeAt(0, 0, 'X');
expect(TicTacToeBoardService.getBoard()[0][0].value).toBe('X');
expect(TicTacToeBoardService.getTotalPlacedCells()).toBe(1);
});
it('cannot place a move at a taken location', function () {
TicTacToeBoardService.placeAt(0, 1, 'X');
expect(TicTacToeBoardService.getBoard()[0][1].value).toBe('X');
expect(TicTacToeBoardService.getTotalPlacedCells()).toBe(1);
TicTacToeBoardService.placeAt(0, 1, 'O');
expect(TicTacToeBoardService.getBoard()[0][1].value).toBe('X');
expect(TicTacToeBoardService.getTotalPlacedCells()).toBe(1);
});
});
describe('checkWinner method', function () {
beforeEach(function () {
TicTacToeBoardService.reset();
});
it('returns an empty string for empty board', function () {
expect(TicTacToeBoardService.checkWinner()).toBe('');
});
it('returns the correct player if the same player forms a horizontal line', function () {
TicTacToeBoardService.placeAt(1, 1, 'O');
TicTacToeBoardService.placeAt(2, 1, 'O');
TicTacToeBoardService.placeAt(0, 1, 'O');
expect(TicTacToeBoardService.checkWinner()).toBe('O');
});
it('returns the correct player if the same player forms a vertical line', function () {
TicTacToeBoardService.placeAt(2, 0, 'X');
TicTacToeBoardService.placeAt(2, 1, 'X');
TicTacToeBoardService.placeAt(2, 2, 'X');
expect(TicTacToeBoardService.checkWinner()).toBe('X');
});
it('returns the correct player if the same player forms a diagonal line', function () {
TicTacToeBoardService.placeAt(2, 0, 'O');
TicTacToeBoardService.placeAt(1, 1, 'O');
TicTacToeBoardService.placeAt(0, 2, 'O');
expect(TicTacToeBoardService.checkWinner()).toBe('O');
});
it('returns an empty string if no player has formed a diagonal line', function () {
TicTacToeBoardService.placeAt(2, 0, 'O');
TicTacToeBoardService.placeAt(1, 1, 'O');
TicTacToeBoardService.placeAt(0, 2, 'X');
expect(TicTacToeBoardService.checkWinner()).toBe('');
});
});
});
| 1d7e19b6856d608631a9ab7a0b86706cd2c94547 | [
"Markdown",
"JavaScript"
] | 3 | Markdown | cankei/tic-tac-toe | 661774eea5ccc821ad439b84e594cc19843c146c | ba142bf89d4b0f6a3465fbbee297915c6504caf7 |
refs/heads/master | <repo_name>thisisdevelopment/redis-mt<file_sep>/README.md
# redis-mt
Status: POC
A redis proxy which provides multi-tenancy for redis.
- each user can only see his own data
- reverse dns is used to determine the username (kubernetes namespace name)
- all keys are automagically prefixed with "<user>:"
- users are automagically provisioned in the upstream redis server (uses redis 6 acl to restrict the keys to only the "<user>:" prefix)
- users are restricted to non-dangerous commands
## How to run
```
docker-compose up
```
```
cd src
go build main.go
cd ../
docker-compose exec app /src/main
```
```
docker-compose exec client1 keydb-cli -h app
```
```
docker-compose exec client2 keydb-cli -h app
```
<file_sep>/src/go.mod
module redis-mt
go 1.13
require (
github.com/mediocregopher/radix/v3 v3.6.0 // indirect
github.com/tidwall/redcon v1.3.2
)
<file_sep>/src/main.go
package main
import (
"errors"
"fmt"
"github.com/mediocregopher/radix/v3"
"github.com/tidwall/redcon"
"io"
"log"
"net"
"strings"
)
type Context struct {
username string
prefix string
conn net.Conn
}
type CommandDef struct {
keyFirst int
keyStep int
keyLast int
}
var addr = ":6379"
var users []string
var commands = map[string]CommandDef{
}
func getUserByRemoteAddr(remoteAddr string) (string, error) {
dns, err := net.LookupAddr(strings.Split(remoteAddr, ":")[0])
if err != nil {
return "", err
}
if len(dns) == 0 {
return "", errors.New("no reverse lookup available for")
}
//TODO: configurable
return strings.Split(dns[0], "_")[1], nil
}
func userExists(username string) bool {
//TODO: implement
return false
}
func main() {
go log.Printf("started server at %s", addr)
client, clientErr := radix.NewPool("unix", "/tmp/keydb.sock", 1)
if clientErr != nil {
log.Fatal(clientErr)
}
client.Do(radix.Cmd(nil, "AUTH", "admin", "admin"))
client.Do(radix.Cmd(&users, "ACL USERS"))
var cmds []interface{}
client.Do(radix.Cmd(&cmds, "COMMAND"))
for k := 0; k<len(cmds); k++ {
cmd := cmds[k].([]interface{})
name := string(cmd[0].([]byte))
cats := cmd[6].([]interface{})
for j := 0; j < len(cats); j++ {
if cats[j].(string) == "@dangerous" {
fmt.Println("Skipped: " + name)
goto next
}
}
commands[name] = CommandDef{int(cmd[3].(int64)), int(cmd[5].(int64)), int(cmd[4].(int64)) }
next:
}
fmt.Println(commands)
err := redcon.ListenAndServe(addr,
func(conn redcon.Conn, cmd redcon.Command) {
//TODO: determine if valid / special command
//TODO: determine + rewrite keys
context := conn.Context().(*Context)
op := strings.ToLower(string(cmd.Args[0]))
if op == "quit" {
conn.WriteString("OK")
conn.Close()
} else if val, ok := commands[op]; ok {
//TODO: resp encoding?
nextKey := val.keyFirst
context.conn.Write(cmd.Args[0])
for i:=1; i<len(cmd.Args); i++ {
context.conn.Write([]byte(" "))
if i == nextKey {
context.conn.Write([]byte(context.prefix))
nextKey += val.keyStep
if nextKey > val.keyLast {
nextKey = 0
}
}
context.conn.Write(cmd.Args[i])
}
context.conn.Write([]byte("\r\n"))
} else {
context.conn.Write(cmd.Raw)
}
},
func(conn redcon.Conn) bool {
user, err := getUserByRemoteAddr(conn.RemoteAddr())
if err != nil {
log.Printf("rejected: %s", err)
return false
}
log.Printf("accepted: %s", user)
prefix := user + ":"
if !userExists(user) {
log.Printf("create user: %s", user)
cmdErr := client.Do(radix.Cmd(nil, "ACL", "SETUSER", user, "on", "+@all", "-randomkey", "-@dangerous", "~" + prefix + "*", ">" + user))
if cmdErr != nil {
log.Fatal(cmdErr)
}
}
result := make([]byte, 100)
serverConn, _ := net.Dial("unix", "/tmp/keydb.sock")
serverConn.Write([]byte("AUTH " + user + " " + user + "\r\n"))
serverConn.Read(result)
if string(result[0:3]) != "+OK" {
log.Printf("Auth failure; received: %s", string(result))
return false
}
context := &Context{
username: user,
prefix: prefix,
conn: serverConn,
}
go func() {
io.Copy(conn.NetConn(), serverConn)
}()
conn.SetContext(context)
return true
},
func(conn redcon.Conn, err error) {
// this is called when the connection has been closed
log.Printf("closed: %s, err: %v", conn.RemoteAddr(), err)
context := conn.Context().(*Context)
context.conn.Close()
},
)
if err != nil {
log.Fatal(err)
}
} | fc2af5ee80e934e489f0842b0b7a3a6a096a8e35 | [
"Markdown",
"Go Module",
"Go"
] | 3 | Markdown | thisisdevelopment/redis-mt | 8c8a1fc1569c3b892b11d3e55c83aaa3d7758753 | 5f7832ef34ab66e17151a07e89d86324d716d1ea |
HEAD | <repo_name>betasve/osra<file_sep>/app/admin/sponsorship.rb
ActiveAdmin.register Sponsorship do
menu if: proc { false }
actions :new, :create
belongs_to :sponsor
form do
panel 'Sponsor' do
h3 sponsorship.sponsor_name
para link_to 'Return to Sponsor page', admin_sponsor_path(sponsorship.sponsor)
para sponsorship.sponsor_additional_info
end
panel 'Orphans' do
table_for Orphan.active.currently_unsponsored do
column :id
column 'Name' do |_orphan|
link_to _orphan.name, admin_orphan_path(_orphan)
end
column :gender
column :mother_alive
column 'Establish sponsorship' do |_orphan|
link_to 'Sponsor this orphan',
admin_sponsor_sponsorships_path(sponsor_id: sponsorship.sponsor_id,
orphan_id: _orphan.id),
method: :post
end
end
end
end
member_action :inactivate, method: :put do
@sponsorship = Sponsorship.find(params[:id])
@sponsor = Sponsor.find(params[:sponsor_id])
@sponsorship.inactivate
flash[:success] = 'Sponsorship link was successfully terminated'
redirect_to admin_sponsor_path(@sponsor)
end
controller do
def create
@orphan = Orphan.find(params[:orphan_id])
@sponsor = Sponsor.find(params[:sponsor_id])
Sponsorship.create!(sponsor: @sponsor, orphan: @orphan)
flash[:success] = 'Sponsorship link was successfully created'
redirect_to admin_sponsor_path(@sponsor)
end
end
permit_params :orphan_id
end
<file_sep>/app/admin/orphan_list.rb
ActiveAdmin.register OrphanList do
actions :index, :new, :create
belongs_to :partner
config.clear_action_items!
index do
column :osra_num
column :spreadsheet_file_name
column :partner, sortable: :partner_id do |orphan_list|
link_to orphan_list.partner.name, admin_partner_path(orphan_list.partner)
end
column :import_date, sortable: :created_at do |orphan_list|
orphan_list.created_at.to_date
end
column :orphan_count
column do |orphan_list|
link_to 'Download', orphan_list.spreadsheet.url
end
end
filter :partner
filter :osra_num
filter :created_at, label: 'Import Date'
filter :orphan_count
form do |f|
f.semantic_errors *f.object.errors.keys
f.inputs do
f.input :spreadsheet, as: :file
end
f.actions
end
controller do
def create
@partner = get_partner
@orphan_list = @partner.orphan_lists.build(orphan_list_params)
@orphan_list.orphan_count = 0
if @orphan_list.save
redirect_to admin_partner_path(@partner), notice: "Orphan List (#{@orphan_list.osra_num}) was successfully imported."
else
render action: :new
end
end
def new
redirect_to admin_partner_path(params[:partner_id]),
alert: "Partner is not Active. Orphan List cannot be uploaded." and return unless get_partner.active?
new!
end
# Workaround to prevent displaying the "Create one" link when the resource collection is empty
# https://github.com/activeadmin/activeadmin/blob/9cfc45330e5ad31977b3ac7b2ccc1f8d6146c73f/lib/active_admin/views/pages/index.rb#L52
def index
params[:q] = true if collection.empty?
end
private
def get_partner
Partner.find(params[:partner_id])
end
def orphan_list_params
params.require(:orphan_list).permit(:spreadsheet)
end
end
end<file_sep>/features/support/env_local.rb
require 'capybara/poltergeist'
require 'database_cleaner'
require 'database_cleaner/cucumber'
require 'headless'
# use poltergeist (phantomjs) for javascript tests
# others can be :webkit, :selenium
# see features/README.md for more information
Capybara.javascript_driver = :poltergeist
DatabaseCleaner.strategy = :truncation
headless = Headless.new
headless.start
<file_sep>/features/step_definitions/admin/sponsors_steps.rb
Given(/^the following sponsors exist:$/) do |table|
table = table.transpose
table.hashes.each do |hash|
sponsor_type = SponsorType.find_or_create_by!(name: hash[:sponsor_type],
code: hash[:sponsor_type_code])
branch = Branch.find_or_create_by!(name: hash[:branch],
code: hash[:branch_code])
status= Status.find_or_create_by!(name: hash[:status],
code: hash[:status_code])
sponsor = Sponsor.new(name: hash[:name], country: hash[:country],
gender: hash[:gender], sponsor_type: sponsor_type,
requested_orphan_count: hash[:requested_orphan_count],
address: hash[:address], email: hash[:email],
contact1: hash[:contact1], contact2: hash[:contact2],
additional_info: hash[:additional_info], branch: branch,
start_date: hash[:start_date], status: status)
sponsor.save!
end
end
Then(/^I should see "Sponsors" linking to the admin sponsors page$/) do
expect(page).to have_link("Sponsors", href: "#{admin_sponsors_path}")
end
When(/^I (?:go to|am on) the "([^"]*)" page for sponsor "([^"]*)"$/) do |page, sponsor_name|
sponsor = Sponsor.find_by name: sponsor_name
visit path_to_admin_role(page, sponsor.id)
end
Then(/^I should be on the "(.*?)" page for sponsor "(.*?)"$/) do |page_name, sponsor_name|
sponsor = Sponsor.find_by name: sponsor_name
expect(current_path).to eq path_to_admin_role(page_name, sponsor.id)
end
<file_sep>/app/models/sponsor.rb
class Sponsor < ActiveRecord::Base
include Initializer
after_initialize :default_status_to_active, :default_start_date_to_today
before_create :generate_osra_num, :set_request_unfulfilled
validates :name, presence: true
validates :requested_orphan_count, presence: true,
numericality: {only_integer: true, greater_than: 0}
validates :country, presence: true, inclusion: {in: ISO3166::Country.countries.map {|c| c[1]} - ['IL']}
validates :request_fulfilled, inclusion: {in: [true, false] }
validates :sponsor_type, presence: true
validates :gender, inclusion: {in: %w(Male Female) } # TODO: DRY list of allowed values
validate :ensure_valid_date
validate :date_not_beyond_first_of_next_month
validate :belongs_to_one_branch_or_organization
validate :can_be_inactivated, if: :being_inactivated?, on: :update
belongs_to :branch
belongs_to :organization
belongs_to :status
belongs_to :sponsor_type
has_many :sponsorships
has_many :orphans, through: :sponsorships
acts_as_sequenced scope: [:organization_id, :branch_id]
def affiliate
branch.present? ? branch.name : organization.name
end
def eligible_for_sponsorship?
self.status.active?
end
private
def date_not_beyond_first_of_next_month
if (valid_date? start_date) && (start_date > Date.current.beginning_of_month.next_month)
errors.add(:start_date, "must not be beyond the first of next month")
end
end
def ensure_valid_date
unless valid_date? start_date
errors.add(:start_date, "is not a valid date")
end
end
def valid_date? test_date
begin
Date.parse(test_date.to_s)
rescue ArgumentError
false
end
end
def belongs_to_one_branch_or_organization
unless branch.blank? ^ organization.blank?
errors.add(:organization, "must belong to a branch or an organization, but not both")
errors.add(:branch, "must belong to a branch or an organization, but not both")
end
end
def generate_osra_num
self.osra_num = "#{osra_num_prefix}%04d" % sequential_id
end
def osra_num_prefix
if branch.present?
"5%02d" % branch.code
else
"8%02d" % organization.code
end
end
def set_request_unfulfilled
self.request_fulfilled = false
true
end
def can_be_inactivated
unless sponsorships.all_active.empty?
errors[:status] << 'Cannot inactivate sponsor with active sponsorships'
end
end
def being_inactivated?
unless status_id_was.nil?
status_id_changed? && (Status.find(status_id_was).name == 'Active')
end
end
end
<file_sep>/features/step_definitions/admin/custom_filters_steps.rb
Then(/^I should see a "([^"]*)" drop down box in the "Filters" section$/) do |selector|
selector_id = "q_#{selector.parameterize}_id"
within('div#filters_sidebar_section') { expect(page).to have_select selector_id }
end
Then(/^I should see a "([^"]*)" drop down box in the "Filters" section with options: (.*)$/) do |selector, options|
selector_id = "q_#{selector.parameterize}"
options_array = options.gsub(/"/, '').split(', ')
within('div#filters_sidebar_section') do
expect(page).to have_select(selector_id, with_options: options_array)
end
end
Given(/^there are (#{A_NUMBER}) male sponsors and (#{A_NUMBER}) female sponsors$/) do |num_male, num_female|
FactoryGirl.create_list(:sponsor, num_male, gender: 'Male')
FactoryGirl.create_list(:sponsor, num_female, gender: 'Female')
expect(Sponsor.all.count).to eq num_male + num_female
end
When(/^I select "([^"]*)" from "([^"]*)"$/) do |option, selector|
select option, from: "q_#{selector.parameterize}"
click_button 'Filter'
end
Then(/^I should see only (fe)?male sponsors$/) do |fe|
gender = fe ? 'Female' : 'Male'
sponsors = Sponsor.where(gender: gender)
sponsors.each do |sponsor|
expect(page).to have_content sponsor.name
end
end
<file_sep>/spec/factories/partners.rb
FactoryGirl.define do
factory :partner do
name { Faker::Company.name }
province
end
end
<file_sep>/spec/models/status_spec.rb
require 'rails_helper'
describe Status, type: :model do
it 'should have a valid factory' do
expect(build_stubbed :status).to be_valid
end
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_uniqueness_of :name }
it { is_expected.to validate_presence_of :code }
it { is_expected.to validate_uniqueness_of :code }
describe 'methods' do
let(:active_status) { build_stubbed :status, name: 'Active' }
let(:inactive_status) { build_stubbed :status, name: 'Inactive' }
specify "#active should return true if name == 'Active'" do
expect(active_status.active?).to eq true
expect(inactive_status.active?).to eq false
end
end
end
<file_sep>/spec/models/province_spec.rb
require 'rails_helper'
describe Province, type: :model do
it 'should have a valid factory' do
expect(build_stubbed :province).to be_valid
end
it 'should be able to call the factory many times' do
expect { 25.times { build_stubbed :province } }.not_to raise_error
end
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_uniqueness_of :name }
it { is_expected.to validate_presence_of :code }
it { is_expected.to validate_uniqueness_of :code }
it { is_expected.to validate_inclusion_of(:code).in_array Province::PROVINCE_CODES }
end
<file_sep>/spec/models/sponsor_type_spec.rb
require 'rails_helper'
describe SponsorType, type: :model do
it 'should have a valid factory' do
expect(build_stubbed :sponsor_type).to be_valid
end
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_uniqueness_of :name }
it { is_expected.to validate_presence_of :code }
it { is_expected.to validate_uniqueness_of :code }
end
<file_sep>/spec/models/sponsor_spec.rb
require 'rails_helper'
describe Sponsor, type: :model do
let!(:active_status) { create :status, name: 'Active' }
let(:on_hold_status) { build_stubbed :status, name: 'On Hold' }
it 'should have a valid factory' do
expect(build_stubbed :sponsor).to be_valid
end
it { is_expected.to validate_presence_of :name }
it { is_expected.to validate_presence_of :requested_orphan_count }
it { is_expected.to validate_presence_of :country }
it { is_expected.to validate_presence_of :sponsor_type }
it { is_expected.to validate_inclusion_of(:gender).in_array %w(Male Female) }
it { is_expected.to validate_inclusion_of(:country).in_array ISO3166::Country.countries.map {|c| c[1]} - ['IL']}
[7, 'yes', true].each do |bad_date_value|
it { is_expected.to_not allow_value(bad_date_value).for :start_date }
end
it { is_expected.to validate_numericality_of(:requested_orphan_count).
only_integer.is_greater_than(0) }
it { is_expected.to belong_to :branch }
it { is_expected.to belong_to :organization }
it { is_expected.to belong_to :status }
it { is_expected.to belong_to :sponsor_type }
it { is_expected.to have_many(:orphans).through :sponsorships }
context 'start_date validation on or before 1st of next month' do
today = Date.current
first_of_next_month = today.beginning_of_month.next_month
yesterday = today.yesterday
second_of_next_month = first_of_next_month + 1.day
two_months_ahead = today + 2.months
[today, first_of_next_month, yesterday].each do |good_date|
it { is_expected.to allow_value(good_date).for :start_date }
end
[second_of_next_month, two_months_ahead].each do |bad_date|
it { is_expected.to_not allow_value(bad_date).for :start_date }
end
end
describe '.request_fulfilled' do
let(:sponsor) { build(:sponsor) }
it 'should default to request unfulfilled' do
sponsor.save!
expect(sponsor.request_fulfilled?).to be false
end
it 'should make request unfulfilled on create always' do
sponsor.request_fulfilled = true
sponsor.save!
expect(sponsor.reload.request_fulfilled?).to be false
end
it 'should allow exisitng records to have request_fulfilled' do
sponsor.save!
sponsor.request_fulfilled = true
sponsor.save!
expect(sponsor.reload.request_fulfilled?).to be true
end
end
describe 'branch or organization affiliation' do
describe 'must be affiliated to 1 branch or 1 organization' do
subject(:sponsor) { build_stubbed(:sponsor) }
let(:organization) { build_stubbed(:organization) }
let(:branch) { build_stubbed(:branch) }
it 'cannot be unaffiliated' do
sponsor.organization, sponsor.branch = nil
expect(sponsor).not_to be_valid
end
it 'cannot be affiliated to a branch and an organisation' do
sponsor.branch = branch
sponsor.organization = organization
expect(sponsor).not_to be_valid
end
context 'when affiliated with a branch but not an organization' do
before do
sponsor.branch = branch
sponsor.organization = nil
end
it { is_expected.to be_valid }
it 'returns branch name as affiliate' do
expect(sponsor.affiliate).to eq branch.name
end
end
context 'when affiliated with an organization but not a branch' do
before do
sponsor.branch = nil
sponsor.organization = organization
end
it { is_expected.to be_valid }
it 'returns branch name as affiliate' do
expect(sponsor.affiliate).to eq organization.name
end
end
end
end
describe 'callbacks' do
describe 'after_initialize #set_defaults' do
describe 'status' do
it 'defaults status to "Under Revision"' do
expect((Sponsor.new).status).to eq active_status
end
it 'sets non-default status if provided' do
options = { status: on_hold_status }
expect(Sponsor.new(options).status).to eq on_hold_status
end
end
describe 'start_date' do
it 'defaults start_date to current date' do
expect(Sponsor.new.start_date).to eq Date.current
end
it 'sets non-default start_date if provided' do
options = { start_date: Date.yesterday }
expect(Sponsor.new(options).start_date).to eq Date.yesterday
end
end
end
describe 'before_update #validate_inactivation' do
let(:inactive_status) { create :status, name: 'Inactive' }
let(:sponsor) { create :sponsor }
context 'when sponsor has no active sponsorships' do
specify 's/he can be inactivated' do
expect{ sponsor.update!(status: inactive_status) }.not_to raise_exception
end
end
context 'when sponsor has active sponsorships' do
before do
create :orphan_status, name: 'Active'
create :orphan_sponsorship_status, name: 'Unsponsored'
create :orphan_sponsorship_status, name: 'Sponsored'
orphan = create(:orphan)
create :sponsorship, sponsor: sponsor, orphan: orphan
end
specify 's/he cannot be inactivated' do
expect{ sponsor.update!(status: inactive_status) }.to raise_error ActiveRecord::RecordInvalid
expect(sponsor.errors[:status]).to include 'Cannot inactivate sponsor with active sponsorships'
end
end
end
end
describe 'before_create #generate_osra_num' do
let(:branch) { build_stubbed :branch }
let(:organization) { build_stubbed :organization }
let(:sponsor) { build :sponsor, :organization => nil, :branch => nil }
it 'sets osra_num' do
sponsor.branch = branch
sponsor.save!
expect(sponsor.osra_num).not_to be_nil
end
describe 'when recruited by osra branch' do
before(:each) do
sponsor.branch = branch
sponsor.save!
end
it 'sets the first digit to 5' do
expect(sponsor.osra_num[0]).to eq "5"
end
it 'sets the second and third digits to the branch code' do
expect(sponsor.osra_num[1...3]).to eq "%02d" % branch.code
end
end
describe 'when recruited by a sister organization' do
before(:each) do
sponsor.organization = organization
sponsor.save!
end
it 'sets the first digit to an 8 ' do
expect(sponsor.osra_num[0]).to eq "8"
end
it 'sets the second and third digits to the organization code' do
expect(sponsor.osra_num[1...3]).to eq "%02d" % organization.code
end
end
it 'sets the last 4 digits of osra_num to sequential_id' do
sponsor.branch = branch
sponsor.sequential_id = 999
sponsor.save!
expect(sponsor.osra_num[3..-1]).to eq '0999'
end
end
describe 'methods' do
let(:active_sponsor) { build_stubbed :sponsor }
let(:on_hold_sponsor) { build_stubbed :sponsor, status: on_hold_status}
specify '#eligible_for_sponsorship? should return true for eligible sponsors' do
expect(active_sponsor.eligible_for_sponsorship?).to eq true
expect(on_hold_sponsor.eligible_for_sponsorship?).to eq false
end
end
end
<file_sep>/app/admin/orphan.rb
ActiveAdmin.register Orphan do
actions :all, except: [:new, :destroy]
permit_params :name, :father_name, :father_is_martyr, :father_occupation,
:father_place_of_death, :father_cause_of_death,
:father_date_of_death, :mother_name, :mother_alive,
:date_of_birth, :gender, :health_status, :schooling_status,
:goes_to_school, :guardian_name, :guardian_relationship,
:guardian_id_num, :contact_number, :alt_contact_number,
:sponsored_by_another_org, :another_org_sponsorship_details,
:minor_siblings_count, :sponsored_minor_siblings_count,
:comments, :orphan_status_id, :priority,
original_address_attributes: [:id, :city, :province_id,
:neighborhood, :street, :details],
current_address_attributes: [:id, :city, :province_id,
:neighborhood, :street, :details]
form do |f|
f.inputs 'Orphan Details' do
f.input :osra_num, :input_html => { :readonly => true }
f.input :name
f.input :date_of_birth, as: :datepicker
f.input :gender, as: :select,
collection: %w(Male Female), include_blank: false
f.input :health_status
f.input :schooling_status
f.input :goes_to_school
f.input :orphan_status, include_blank: false
f.input :orphan_sponsorship_status, label: 'Sponsorship Status', input_html: { :disabled => true }
f.input :priority, as: :select,
collection: %w(Normal High), include_blank: false
end
f.inputs 'Parents Details' do
f.input :father_name
f.input :mother_name
f.input :mother_alive
f.input :father_is_martyr
f.input :father_occupation
f.input :father_place_of_death
f.input :father_cause_of_death
f.input :father_date_of_death, as: :datepicker
end
f.inputs 'Guardian Details' do
f.input :guardian_name
f.input :guardian_relationship
f.input :guardian_id_num
f.input :contact_number
f.input :alt_contact_number
end
f.inputs 'Original Address' do
f.semantic_fields_for :original_address do |r|
r.inputs :city
r.inputs :province
r.inputs :neighborhood
r.inputs :street
r.inputs :details
end
end
f.inputs 'Current Address' do
f.semantic_fields_for :current_address do |r|
r.inputs :city
r.inputs :province
r.inputs :neighborhood
r.inputs :street
r.inputs :details
end
end
f.inputs 'Additional Details' do
f.input :sponsored_by_another_org
f.input :another_org_sponsorship_details
f.input :minor_siblings_count
f.input :sponsored_minor_siblings_count
f.input :comments
end
f.actions
end
show title: :full_name do |orphan|
panel 'Orphan Details' do
attributes_table_for orphan do
row :osra_num
row :date_of_birth
row :gender
row :health_status
row :schooling_status
row :goes_to_school do
orphan.goes_to_school ? 'Yes' : 'No'
end
row :orphan_status
row :orphan_sponsorship_status
row :current_sponsor if orphan.currently_sponsored?
row :priority
end
end
panel 'Parents Details' do
attributes_table_for orphan do
row :father_name
row :mother_name
row :mother_alive do
orphan.mother_alive ? 'Yes' : 'No'
end
row :father_is_martyr do
orphan.father_is_martyr ? 'Yes' : 'No'
end
row :father_occupation
row :father_place_of_death
row :father_cause_of_death
row :father_date_of_death
end
end
panel 'Guardian Details' do
attributes_table_for orphan do
row :guardian_name
row :guardian_relationship
row :guardian_id_num
row :contact_number
row :alt_contact_number
end
end
panel 'Original Address' do
attributes_table_for orphan.original_address do
row :city
row :province
row :neighborhood
row :street
row :details
end
end
panel 'Current Address' do
attributes_table_for orphan.current_address do
row :city
row :province
row :neighborhood
row :street
row :details
end
end
panel 'Additional Details' do
attributes_table_for orphan do
row :sponsored_by_another_org do
orphan.sponsored_by_another_org ? 'Yes' : 'No'
end
row :another_org_sponsorship_details
row :minor_siblings_count
row :sponsored_minor_siblings_count
row :comments
end
end
end
index do
column 'OSRA No.', sortable: :osra_num do |orphan|
link_to orphan.osra_num, admin_orphan_path(orphan)
end
column :full_name, sortable: :full_name do |orphan|
link_to orphan.full_name, admin_orphan_path(orphan)
end
column :date_of_birth
column :gender
column :orphan_status, sortable: :orphan_status_id
column :priority do |orphan|
status_tag(orphan.priority == 'High' ? 'warn' : '', label: orphan.priority)
end
column :mother_alive
column 'Sponsorship', sortable: :orphan_sponsorship_status_id do |orphan|
orphan.orphan_sponsorship_status.name
end
end
end
<file_sep>/spec/factories/sponsor_types.rb
FactoryGirl.define do
factory :sponsor_type do
sequence(:name) { |n| "Name #{n}" }
sequence(:code)
end
end
<file_sep>/app/admin/sponsor.rb
ActiveAdmin.register Sponsor do
preserve_default_filters!
filter :gender, as: :select, collection: %w(Male Female)
actions :all, except: [:destroy]
index do
column :osra_num, sortable: :osra_num do |sponsor|
link_to sponsor.osra_num, admin_sponsor_path(sponsor)
end
column :name, sortable: :name do |sponsor|
link_to sponsor.name, admin_sponsor_path(sponsor)
end
column :status, sortable: :status_id
column :start_date
column :request_fulfilled
column :sponsor_type
column :country do |sponsor|
ISO3166::Country.search(sponsor.country)
end
end
show do |sponsor|
attributes_table do
row :osra_num
row :status
row :gender
row :start_date
row :requested_orphan_count
row :request_fulfilled do
sponsor.request_fulfilled? ? 'Yes' : 'No'
end
row :sponsor_type
row :affiliate
row :country do
ISO3166::Country.search(sponsor.country)
end
row :address
row :email
row :contact1
row :contact2
row :additional_info
end
panel "#{ pluralize(sponsor.sponsorships.all_active.count,
'Currently Sponsored Orphan') }", id: 'active' do
table_for sponsor.sponsorships.all_active do
column :orphan
column :orphan_date_of_birth
column :orphan_gender
column '' do |_sponsorship|
link_to 'End sponsorship',
inactivate_admin_sponsor_sponsorship_path(sponsor_id: sponsor.id, id: _sponsorship.id),
method: :put
end
end
end
panel "#{ pluralize(sponsor.sponsorships.all_inactive.count,
'Previously Sponsored Orphan') }", id: 'inactive' do
table_for sponsor.sponsorships.all_inactive do
column :orphan
column :orphan_date_of_birth
column :orphan_gender
column 'Sponsorship ended' do |_sponsorship|
_sponsorship.updated_at
end
end
end
end
form do |f|
f.inputs do
f.input :name
f.input :status
f.input :gender, as: :select, collection: %w(Male Female)
f.input :start_date, as: :datepicker
f.input :requested_orphan_count
f.input :request_fulfilled unless f.object.new_record?
f.input :sponsor_type
f.input :organization
f.input :branch
f.input :country, as: :country, priority_countries: %w(SA TR AE GB), except: ['IL'], selected: 'SA'
f.input :address
f.input :email
f.input :contact1
f.input :contact2
f.input :additional_info
end
f.actions
end
action_item only: :show do
link_to 'Link to Orphan', new_admin_sponsor_sponsorship_path(sponsor) if sponsor.eligible_for_sponsorship?
end
permit_params :name, :country, :gender, :requested_orphan_count, :address, :email, :contact1, :contact2, :additional_info, :start_date, :status_id, :sponsor_type_id, :organization_id, :branch_id, :request_fulfilled
end
<file_sep>/spec/factories/orphan_sponsorship_statuses.rb
FactoryGirl.define do
factory :orphan_sponsorship_status do
sequence(:code)
sequence(:name) { |n| "OSS#{n}" }
end
end
<file_sep>/spec/factories/provinces.rb
FactoryGirl.define do
provinces = [
['Damascus & <NAME>', 11],
['Aleppo', 12],
['Homs', 13],
['Hama', 14],
['Latakia', 15],
['<NAME>', 16],
['Daraa', 17],
['Idlib', 18],
['<NAME>', 19],
['<NAME>', 20],
['Tartous', 21],
['Al-Suwayada', 22],
['Al-Quneitera', 23],
['Outside Syria', 29]
]
sequence :init_hash, (0..13).cycle do |n|
{ name: provinces[n][0], code: provinces[n][1] }
end
factory :province do
initialize_with { Province.find_or_create_by(generate :init_hash) }
end
end
<file_sep>/spec/controllers/admin/orphan_lists_controller_spec.rb
require 'rails_helper'
include Devise::TestHelpers
describe Admin::OrphanListsController, type: :controller do
before(:each) do
sign_in instance_double(AdminUser)
end
describe 'new' do
context 'when partner is inactive' do
let(:partner) { instance_double Partner, active?: false }
before(:each) do
expect(Partner).to receive(:find).with('1').and_return(partner)
expect(partner).to receive(:active?)
end
it 'sets the alert flash' do
get :new, partner_id: 1
expect(flash[:alert]).to eq 'Partner is not Active. Orphan List cannot be uploaded.'
end
it 'redirects to partner if partner is inactive' do
get :new, partner_id: 1
expect(response).to redirect_to admin_partner_path(1)
end
end
context 'when partner is active' do
let(:partner) { FactoryGirl.create :partner }
before(:each) do
expect(Partner).to receive(:find).at_least(:once).with('1').and_return(partner)
expect(partner).to receive(:active?).and_return true
allow(request.env['warden']).to receive(:authenticate).and_return(instance_double AdminUser)
end
it 'determines that partner is active' do
get :new, partner_id: 1
expect(response).not_to redirect_to admin_partner_path(1)
end
end
end
describe 'create' do
let(:partner) { instance_double Partner }
let(:orphan_list) { FactoryGirl.build :orphan_list }#{ double OrphanList }
let(:orphan_lists) { [orphan_list] }
let(:orphan_list_params) { { params: 'params' } }
before do
allow(Partner).to receive(:find).with('1').and_return partner
allow(partner).to receive(:orphan_lists).and_return orphan_lists
allow(orphan_lists).to receive(:build).and_return orphan_list
allow(orphan_list).to receive(:orphan_count=).with 0
allow(orphan_list).to receive(:save)
end
it 'sets @partner' do
post :create, { partner_id: 1, orphan_list: orphan_list_params }
expect(assigns :partner).to eq partner
end
it 'sets @orphan_list to modified orphan_list_params' do
post :create, { partner_id: 1, orphan_list: orphan_list_params }
modified_orphan_list = orphan_list
modified_orphan_list.orphan_count = 0
modified_orphan_list.sequential_id = 1
expect(assigns :orphan_list).to eq modified_orphan_list
end
context 'on successful save' do
before(:each) do
allow(orphan_list).to receive(:save).and_return true
allow(orphan_list).to receive(:osra_num).and_return 1
post :create, { partner_id: 1, orphan_list: orphan_list_params }
end
it 'sets the flash' do
expect(flash[:notice]).to eq 'Orphan List (1) was successfully imported.'
end
it 'redirects to partner page' do
expect(response).to redirect_to admin_partner_path(partner)
end
end
context 'on failed save' do
before(:each) do
allow(orphan_list).to receive(:save).and_return false
post :create, { partner_id: 1, orphan_list: orphan_list_params }
end
it 'renders :new' do
expect(response).to render_template :new
end
end
end
end
<file_sep>/spec/models/orphan_list_spec.rb
require 'rails_helper'
describe OrphanList, type: :model do
let(:active_status) { build_stubbed :status, name: 'Active', code: 1 }
let(:inactive_status) { build_stubbed :status, name: 'Inactive', code: 2 }
let(:active_partner) { build_stubbed :partner, status: active_status }
let(:inactive_partner) { build_stubbed :partner, status: inactive_status }
it { is_expected.to validate_presence_of :partner }
it { is_expected.to validate_presence_of :orphan_count }
it { is_expected.to validate_presence_of :spreadsheet }
it { is_expected.to belong_to :partner }
it { is_expected.to have_many :orphans }
it 'should not belong to a non active partner' do
expect(build_stubbed :orphan_list, partner: inactive_partner).not_to be_valid
end
it 'should have a valid factory and belong to an active partner' do
expect(build_stubbed :orphan_list, partner: active_partner).to be_valid
end
end
<file_sep>/spec/models/sponsorship_spec.rb
require 'rails_helper'
describe Sponsorship, type: :model do
before(:each) do
create :orphan_status, name: 'Active'
create :orphan_sponsorship_status, name: 'Sponsored'
create :orphan_sponsorship_status, name: 'Unsponsored'
create :orphan_sponsorship_status, name: 'Previously Sponsored'
create :orphan_sponsorship_status, name: 'On Hold'
create :status, name: 'Active'
end
it 'should have a valid factory' do
expect(build_stubbed :sponsorship).to be_valid
end
it { is_expected.to validate_presence_of :sponsor }
it { is_expected.to validate_presence_of :orphan }
it { is_expected.to belong_to :sponsor }
it { is_expected.to belong_to :orphan }
describe 'validations' do
let(:inactive_status) do
Status.find_by_name('Inactive') || create(:status, name: 'Inactive')
end
let(:ineligible_sponsor) { build_stubbed :sponsor, status: inactive_status }
let(:inactive_orphan_status) do
OrphanStatus.find_by_name('Inactive') || create(:orphan_status, name: 'Inactive')
end
let(:ineligible_orphan) { build_stubbed :orphan, orphan_status: inactive_orphan_status}
it 'disallows creation of new sponsorships with ineligible sponsors' do
expect{ create :sponsorship, sponsor: ineligible_sponsor }.to raise_error ActiveRecord::RecordInvalid
end
it 'disallows creation of new sponsorships with ineligible orphans' do
expect{ create :sponsorship, orphan: ineligible_orphan }.to raise_error ActiveRecord::RecordInvalid
end
describe 'disallow concurrent active sponsorships' do
let(:orphan) { create :orphan }
let(:sponsor) { create :sponsor }
let!(:active_sponsorship) { create :sponsorship, sponsor: sponsor, orphan: orphan }
it 'disallows concurrent active sponsorships' do
expect{ create :sponsorship, sponsor: sponsor, orphan: orphan }.to raise_error ActiveRecord::RecordInvalid
end
it 'does not disallow multiple inactive sponsorships' do
active_sponsorship.inactivate
new_sponsorship = create :sponsorship, sponsor: sponsor, orphan: orphan
expect{ new_sponsorship.inactivate }.not_to raise_error
end
end
end
describe 'callbacks' do
describe 'after_initialize #set_defaults' do
describe 'start_date' do
it 'defaults start_date to current date' do
expect(Sponsorship.new.start_date).to eq Date.current
end
it 'sets non-default start_date if provided' do
options = { start_date: Date.yesterday }
expect(Sponsorship.new(options).start_date).to eq Date.yesterday
end
end
end
describe 'before_create #set_active_true' do
let(:sponsorship) { build :sponsorship }
it 'sets the .active attribute to true' do
sponsorship.save!
expect(sponsorship.reload.active).to eq true
expect(sponsorship.orphan.orphan_sponsorship_status.name).to eq 'Sponsored'
end
end
end
describe 'methods' do
it '#inactivate should set active = false & orphan.orphan_sponsorship_status = Previously Sponsored' do
sponsorship = create :sponsorship
sponsorship.inactivate
expect(sponsorship.reload.active).to eq false
expect(sponsorship.orphan.reload.orphan_sponsorship_status.name).to eq 'Previously Sponsored'
end
specify '#set_active_to_true should set .active = true' do
sponsorship = Sponsorship.new(active: false)
sponsorship.send(:set_active_to_true)
expect(sponsorship.active).to eq true
end
end
describe 'scopes' do
let!(:active_sponsorship) { create :sponsorship }
let(:inactive_sponsorship) { create :sponsorship }
before(:each) { inactive_sponsorship.inactivate }
it '.all_active should return active sponsorships' do
expect(Sponsorship.all_active.to_a).to eq [active_sponsorship]
end
it '.all_inactive should return inactive sponsorships' do
expect(Sponsorship.all_inactive.to_a).to eq [inactive_sponsorship]
end
end
end
| fd54b564e0041b5d4d5c283f17c66db3fb106400 | [
"Ruby"
] | 19 | Ruby | betasve/osra | 44c30b4ee288710e0f0a1aad59dc264b1c573461 | e2610b8f8c21020167162c5c9d07e2aa9cd5d6a2 |
refs/heads/main | <repo_name>poyo46/lilili<file_sep>/bin/check
#!/bin/bash
echo "***** black *****"
black --check .
echo "***** flake8 *****"
flake8
echo "***** isort *****"
isort --check .
echo "***** xenon *****"
xenon --max-absolute B --max-modules A --max-average A lilili tests
<file_sep>/bin/format
#!/bin/bash
echo "***** black *****"
black .
echo "***** isort *****"
isort .
<file_sep>/lilili/utils.py
import json
import logging
import re
from typing import Dict, Optional
import requests
import yaml
from .db.defs import Spdx
logger = logging.getLogger(__name__)
def fetch_json(url: str, headers: Optional[Dict[str, str]] = None) -> Optional[Dict]:
if headers is None:
headers = {}
response = requests.get(url=url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return None
def normalize_license_name(name: str) -> str:
"""Normalize the license name.
Parameters
----------
name : str
license name.
Returns
-------
str
Normalized license name.
Examples
--------
>>> assert normalize_license_name("MIT License") == "mitlicense"
>>> assert normalize_license_name("Apache License V2.0") == "apachelicense20"
"""
name = name.lower()
name = re.sub(r"v([\d.]+)", r"\1", name)
name = re.sub(r"[- .]", "", name)
return name
LICENSES = {
spdx: [normalize_license_name(name) for name in spdx.value] for spdx in Spdx
}
def determine_spdx(name: str) -> Optional[Spdx]:
"""Determine the SPDX license.
Parameters
----------
name : str
License name.
Returns
-------
Optional[str]
SPDX license.
Examples
--------
>>> assert determine_spdx("MIT License") is Spdx.MIT
>>> assert determine_spdx("THE MIT LICENSE") is Spdx.MIT
"""
org_name = str(name)
if type(name) != str:
logger.warning(f"Unrecognized license name: {org_name}")
return None
name = normalize_license_name(name)
for spdx, normalized_names in LICENSES.items():
if name in normalized_names:
return spdx
if name is not None and name != "":
logger.warning(f"Unrecognized license name: {org_name}")
return None
def output_json(dic, file_path: Optional[str] = None) -> None:
if file_path is None:
file_path = "result.json"
with open(file_path, mode="wt", encoding="utf-8") as f:
json.dump(dic, f, indent=2, ensure_ascii=False)
def output_yaml(dic, file_path: Optional[str] = None) -> None:
if file_path is None:
file_path = "result.yml"
with open(file_path, mode="wt", encoding="utf-8") as f:
f.write(yaml.dump(dic, sort_keys=False))
def output(as_json: bool, as_yaml: bool, dic, file_path: Optional[str] = None) -> None:
if as_json:
output_json(dic, file_path)
if as_yaml:
output_yaml(dic, file_path)
if not as_json and not as_yaml:
print(dic)
<file_sep>/tests/lilili/test__init__.py
from datetime import date
from typing import Dict
import pytest
import toml
import lilili
@pytest.fixture(scope="module")
def tool_poetry(root_dir) -> Dict:
with open(root_dir / "pyproject.toml") as f:
parsed_toml = toml.loads(f.read())
return parsed_toml["tool"]["poetry"]
class TestPackage:
def test_title(self, tool_poetry):
assert lilili.__title__ == tool_poetry["name"]
def test_description(self, tool_poetry):
assert lilili.__description__ == tool_poetry["description"]
def test_url(self, tool_poetry):
assert lilili.__url__ == tool_poetry["homepage"]
def test_version(self, tool_poetry):
assert lilili.__version__ == tool_poetry["version"]
def test_author(self, tool_poetry):
assert lilili.__author__ in "".join(tool_poetry["authors"])
def test_author_email(self, tool_poetry):
assert lilili.__author_email__ in "".join(tool_poetry["authors"])
def test_license(self, tool_poetry):
assert lilili.__license__ == tool_poetry["license"]
def test_copyright(self):
year = date.today().year
author = lilili.__author__
assert lilili.__copyright__ == f"Copyright {year} {author}"
<file_sep>/bin/test
#!/bin/bash
poetry run pytest -s -p no:warnings -p no:cacheprovider --cov=lilili --cov-branch --cov-report=term-missing
poetry run pytest --doctest-modules lilili
<file_sep>/lilili/apis/github.py
import os
import re
from typing import Dict, List, Optional, Tuple
from lilili import __title__
from lilili.db.defs import Basis, License
from lilili.utils import determine_spdx, fetch_json
def find_github_owner_repo(url: Optional[str]) -> Tuple[Optional[str], Optional[str]]:
"""Find the owner's name and repository name from the URL representing the GitHub
repository.
Parameters
----------
url : Optional[str]
Any string (expect it to be a URL).
Returns
-------
owner : str or None
Owner's name, or None if not found.
repo : str or None
Repository name, or None if not found.
Examples
--------
>>> owner, repo = find_github_owner_repo("https://github.com/poyo46/lilili.git#foo")
>>> assert owner == "poyo46"
>>> assert repo == "lilili"
>>> owner, repo = find_github_owner_repo("https://www.example.com")
>>> assert owner is None
>>> assert repo is None
"""
if url is None:
return None, None
m = re.match(r"[^:/]+://github.com/(?P<owner>[^/]+)/(?P<repo>[^/#]+)", url)
if m is None:
return None, None
repo = m.group("repo")
if repo.endswith(".git"):
repo = repo[:-4]
return m.group("owner"), repo
def extract_github_repository_url(urls: List[str]) -> Optional[str]:
"""Extract a GitHub repository URL among the given URLs.
Parameters
----------
urls : List[str]
A list of URLs.
Returns
-------
Optional[str]
GitHub repository URL, or None if not found.
Notes
-----
If a URL is found, it will be normalized to the form
``https://github.com/{owner}/{repo}`` .
Examples
--------
>>> urls = ["http://foo.jp", "http://github.com/poyo46/lilili#foo", "http://bar.jp"]
>>> url = extract_github_repository_url(urls)
>>> assert url == "https://github.com/poyo46/lilili"
>>> assert extract_github_repository_url(["foo", "bar"]) is None
"""
for url in urls:
owner, repo = find_github_owner_repo(url)
if owner is not None and repo is not None:
return f"https://github.com/{owner}/{repo}"
return None
class GithubApi:
BASE_URL = "https://api.github.com"
ACCESS_TOKEN = os.getenv(f"{__title__.upper()}_GITHUB_ACCESS_TOKEN")
@staticmethod
def get_headers() -> Dict[str, str]:
if GithubApi.ACCESS_TOKEN is None:
return {}
else:
return {"Authorization": "token " + GithubApi.ACCESS_TOKEN}
class GithubRepository:
@staticmethod
def find_licenses(github_url: str) -> List[License]:
owner, repo = find_github_owner_repo(github_url)
if owner is None or repo is None:
return []
licenses = []
registered_license = GithubRepository.fetch_registered_license(owner, repo)
if registered_license is not None:
licenses.append(registered_license)
# TODO: Implement other means (e.g., refer to package.json).
return licenses
@staticmethod
def fetch_registered_license(owner: str, repo: str) -> Optional[License]:
"""Fetch a license that is explicitly registered in the repository.
Parameters
----------
owner : str
Repository owner's name.
repo : str
Repository name.
Returns
-------
license : License or None
Registered license, or None if not found.
See Also
--------
https://docs.github.com/en/rest/reference/licenses#get-the-license-for-a-repository
"""
url = f"{GithubApi.BASE_URL}/repos/{owner}/{repo}/license"
license_json = fetch_json(url, GithubApi.get_headers())
if license_json is None:
return None
if "license" not in license_json.keys():
return None
spdx = determine_spdx(license_json["license"]["spdx_id"])
if spdx is None:
return None
basis = Basis.GITHUB_LICENSES_API
return License(spdx=spdx, basis=basis, source_url=url)
<file_sep>/pyproject.toml
[tool.poetry]
authors = [
"poyo46 <<EMAIL>>",
]
classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"License :: OSI Approved :: Apache Software License",
"Operating System :: MacOS :: MacOS X",
"Operating System :: POSIX :: Linux",
"Operating System :: Microsoft :: Windows",
"Programming Language :: Python :: 3.7",
"Programming Language :: Python :: 3.8",
"Programming Language :: Python :: 3.9",
]
description = "List the Licenses of the Libraries."
homepage = "https://github.com/poyo46/lilili"
keywords = ["software", "license", "licensed", "fossology"]
license = "Apache-2.0"
name = "lilili"
readme = "README.md"
repository = "https://github.com/poyo46/lilili"
version = "0.1.0"
[tool.poetry.dependencies]
Flask = "^1.1.2"
PyYAML = "^5.4.1"
SQLAlchemy = "^1.3.23"
cleo = "^0.8.1"
python = "^3.6"
requests = "^2.25.1"
[tool.poetry.dev-dependencies]
pytest = "^5.2"
pytest-cov = "^2.10.1"
toml = "^0.10.2"
[tool.poetry.scripts]
lilili = "lilili.cli:main"
[tool.black]
exclude = '''
(
/(
\.eggs # exclude a few common directories in the
| \.git # root of the project
| \.hg
| \.mypy_cache
| \.tox
| \.venv
| _build
| buck-out
| build
| dist
)/
| foo.py # also separately exclude a file named foo.py in
# the root of the project
)
'''
include = '\.pyi?$'
line-length = 88
target-version = ['py36', 'py37', 'py38']
[tool.isort]
include_trailing_comma = true
line_length = 88
multi_line_output = 3
[build-system]
build-backend = "poetry.core.masonry.api"
requires = ["poetry-core>=1.0.0"]
<file_sep>/lilili/search.py
import logging
import re
from pathlib import Path
from typing import Generator, List, Optional, Tuple, Type
from lilili.apis.api import Api
from lilili.apis.npmjs import NpmjsApi
from lilili.apis.pypi import PypiApi
from lilili.apis.rubygems import RubygemsApi
from lilili.db.defs import Domain, Session
from lilili.errors import NotDetectedApiError
logger = logging.getLogger(__name__)
def _auto_detect(first_line: str) -> Tuple[Type[Api], str]:
if "Package" in first_line and "Version" in first_line:
api = PypiApi
regex = r"(?P<name>[^\s]*[a-zA-Z]+[^\s]*)\s+(?P<version>[^\s]*\d+[^\s]*)\s*"
elif "Gems included by the bundle" in first_line:
api = RubygemsApi
regex = r".*\* (?P<name>[^()]+) \((?P<version>[^()\s]+).*\)"
elif "yarn list" in first_line:
api = NpmjsApi
regex = r".*─ (?P<name>[^\\^]+)@(?P<version>[\w.-]+)"
else:
raise NotDetectedApiError("first line of the file: " + first_line)
return api, regex
def _get_api(domain: Domain) -> Type[Api]:
for api in (PypiApi, RubygemsApi, NpmjsApi):
if api.domain is domain:
return api
raise ValueError
def _extract_libraries(lines: List[str], regex: str) -> List[re.Match]:
libraries = []
for line in lines:
m = re.match(regex, line)
if m is None or ".x" in m.group("version"):
logger.debug("skipped: " + line)
else:
libraries.append(m)
return libraries
class Search(object):
def __init__(self, file_path: Path, domain: Optional[Domain] = None):
with open(file_path, mode="rt", encoding="utf-8") as f:
logger.info(f"read file: {file_path}")
lines = f.read().splitlines()
if len(lines) == 0:
return
if domain is None:
self.__api, regex = _auto_detect(lines[0])
else:
self.__api = _get_api(domain)
regex = r"(?P<name>.+),(?P<version>[^,]+)" # csv
self.__match_objects = _extract_libraries(lines, regex)
logger.info(str(self.size) + " libraries were found.")
@property
def size(self) -> int:
return len(self.__match_objects)
def search_libraries(self) -> Generator:
session = Session()
for m in self.__match_objects:
name = m.group("name")
version = m.group("version")
logger.info(f"library: {name} {version}")
library = self.__api(session, name, version).find_library()
yield library.to_dict()
session.close()
<file_sep>/lilili/apis/rubygems.py
from typing import Dict, List, Optional
from sqlalchemy.orm.session import Session
from lilili.apis.api import Api
from lilili.apis.github import extract_github_repository_url
from lilili.db.defs import Basis, Domain, License
from lilili.utils import determine_spdx, fetch_json
class RubygemsApi(Api):
domain = Domain.RUBYGEMS
BASE_URL = "https://rubygems.org/api/v1"
def __init__(self, session: Session, name: str, version: str) -> None:
super().__init__(session, name, version)
self.exact_info_url = f"{RubygemsApi.BASE_URL}/versions/{name}.json"
self.exact_info = None
self.latest_info_url = f"{RubygemsApi.BASE_URL}/gems/{name}.json"
self.latest_info = None
def fetch_info(self) -> None:
for info in fetch_json(self.exact_info_url) or []:
if info["number"] == self.version:
self.exact_info = info
break
self.latest_info = fetch_json(self.latest_info_url)
def get_download_url(self) -> Optional[str]:
return f"https://rubygems.org/gems/{self.name}-{self.version}.gem"
def get_homepage(self) -> Optional[str]:
# self.exact_info has no information about homepage.
if self.latest_info is not None:
return self.latest_info.get("homepage_uri", None)
return None
@staticmethod
def _get_urls(info: Dict) -> List[str]:
return [value for key, value in info.items() if key.endswith("_uri")]
def get_github_url(self) -> Optional[str]:
# self.exact_info has no information about github_url.
if self.latest_info is None:
return None
urls = self._get_urls(self.latest_info)
if "metadata" in self.latest_info:
urls += self._get_urls(self.latest_info["metadata"])
return extract_github_repository_url(urls)
def get_exact_licenses(self) -> List[License]:
if self.exact_info is None:
return []
basis = Basis.API_EXACT
licenses = []
for license_name in self.exact_info.get("licenses", []):
spdx = determine_spdx(license_name)
if spdx is not None:
licenses.append(
License(spdx=spdx, basis=basis, source_url=self.exact_info_url)
)
return licenses
def get_latest_licenses(self) -> List[License]:
if self.latest_info is None:
return []
basis = Basis.API_LATEST
licenses = []
for license_name in self.latest_info.get("licenses", []):
spdx = determine_spdx(license_name)
if spdx is not None:
licenses.append(
License(spdx=spdx, basis=basis, source_url=self.latest_info_url)
)
return licenses
<file_sep>/README.md
# LiLiLi: List the Licenses of the Libraries
[](https://github.com/poyo46/lilili/actions?query=workflow%3ATest)
[](https://pypi.org/pypi/lilili/)
[](https://pypi.org/pypi/lilili/)
[](https://github.com/poyo46/lilili/blob/main/LICENSE)
[](https://github.com/psf/black)
[](https://pycqa.github.io/isort/)
LiLiLi helps you to retrieve and audit software license information.
## Installation
LiLiLi is available on PyPI:
```console
$ pip install lilili
```
You can also use [poetry](https://python-poetry.org/) to add it to a specific Python project.
```console
$ poetry add lilili
```
## Examples
### Search for and list the licenses of libraries
**Python libraries**
```console
$ pip list > pip-list.txt
$ lilili search --yaml pip-list.txt
```
Example of `result.yml`:
```yaml
- domain: pypi
name: requests
version: 2.25.1
licenses:
- spdx_id: Apache-2.0
basis: API_EXACT
source_url: https://pypi.org/pypi/requests/2.25.1/json
download_url: https://files.pythonhosted.org/packages/29/c1/24814557f1d22c56d50280771a17307e6bf87b70727d975fd6b2ce6b014a/requests-2.25.1-py2.py3-none-any.whl
homepage: https://requests.readthedocs.io
git_url: https://github.com/psf/requests
updated_at: "2021-02-22T17:32:25.323561"
- domain: pypi
name: idna
version: "2.10"
licenses:
- spdx_id: BSD-3-Clause
basis: API_LATEST
source_url: https://pypi.org/pypi/idna/json
- spdx_id: BSD-3-Clause
basis: GITHUB_LICENSES_API
source_url: https://api.github.com/repos/kjd/idna/license
download_url: https://files.pythonhosted.org/packages/a2/38/928ddce2273eaa564f6f50de919327bf3a00f091b5baba8dfa9460f3a8a8/idna-2.10-py2.py3-none-any.whl
homepage: https://github.com/kjd/idna
git_url: https://github.com/kjd/idna
updated_at: "2021-02-22T17:32:24.035106"
```
**Ruby libraries**
```console
$ bundle list > bundle-list.txt
$ lilili search --yaml bundle-list.txt
```
The output `result.yml` is in the same format as above.
**Node.js libraries**
```console
$ yarn list > yarn-list.txt
$ lilili search --yaml yarn-list.txt
```
The output `result.yml` is in the same format as above.
## Why LiLiLi?
- LiLiLi uses [the SPDX license list](https://spdx.org/licenses/), which is also used by [GitHub Licenses API](https://docs.github.com/en/rest/reference/licenses), so the license notation can be reused.
- If LiLiLi cannot determine the license for a particular version of the library, it will search for the latest version of the license or a license registered in the GitHub repository.
- LiLiLi will reveal the URL of the API on which the licensing decision is based, so you can double-check it yourself.
<file_sep>/lilili/db/defs.py
import enum
from datetime import datetime
from pathlib import Path
from typing import Dict
from sqlalchemy import (
Column,
DateTime,
Enum,
ForeignKey,
Integer,
String,
UniqueConstraint,
create_engine,
)
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import relationship, sessionmaker
from sqlalchemy.schema import Index
from lilili import __title__
DB_PATH = "sqlite:///" + str(Path.cwd() / f"{__title__}.sqlite3")
engine = create_engine(DB_PATH, echo=False)
Base = declarative_base()
class Basis(enum.Enum):
"""Basis for licensing decisions."""
API_EXACT = 1
API_LATEST = 2
GITHUB_LICENSES_API = 3
GITHUB_OTHER = 4
class Spdx(enum.Enum):
"""The SPDX license list.
See Also
--------
https://spdx.org/licenses/
"""
# value = (SPDX id, SPDX name, aliases... )
_0BSD = ("0BSD", "BSD Zero Clause License")
AAL = ("AAL", "Attribution Assurance License")
ADSL = ("ADSL", "Amazon Digital Services License")
AFL_11 = ("AFL-1.1", "Academic Free License v1.1")
AFL_12 = ("AFL-1.2", "Academic Free License v1.2")
AFL_20 = ("AFL-2.0", "Academic Free License v2.0")
AFL_21 = ("AFL-2.1", "Academic Free License v2.1")
AFL_30 = ("AFL-3.0", "Academic Free License v3.0")
AGPL_10 = ("AGPL-1.0", "Affero General Public License v1.0")
AGPL_10_ONLY = ("AGPL-1.0-only", "Affero General Public License v1.0 only")
AGPL_10_OR_LATER = (
"AGPL-1.0-or-later",
"Affero General Public License v1.0 or later",
)
AGPL_30 = ("AGPL-3.0", "GNU Affero General Public License v3.0")
AGPL_30_ONLY = ("AGPL-3.0-only", "GNU Affero General Public License v3.0 only")
AGPL_30_OR_LATER = (
"AGPL-3.0-or-later",
"GNU Affero General Public License v3.0 or later",
)
AMDPLPA = ("AMDPLPA", "AMD's plpa_map.c License")
AML = ("AML", "Apple MIT License")
AMPAS = ("AMPAS", "Academy of Motion Picture Arts and Sciences BSD")
ANTLR_PD = ("ANTLR-PD", "ANTLR Software Rights Notice")
ANTLR_PD_FALLBACK = (
"ANTLR-PD-fallback",
"ANTLR Software Rights Notice with license fallback",
)
APAFML = ("APAFML", "Adobe Postscript AFM License")
APL_10 = ("APL-1.0", "Adaptive Public License 1.0")
APSL_10 = ("APSL-1.0", "Apple Public Source License 1.0")
APSL_11 = ("APSL-1.1", "Apple Public Source License 1.1")
APSL_12 = ("APSL-1.2", "Apple Public Source License 1.2")
APSL_20 = ("APSL-2.0", "Apple Public Source License 2.0")
ABSTYLES = ("Abstyles", "Abstyles License")
ADOBE_2006 = (
"Adobe-2006",
"Adobe Systems Incorporated Source Code License Agreement",
)
ADOBE_GLYPH = ("Adobe-Glyph", "Adobe Glyph List License")
AFMPARSE = ("Afmparse", "Afmparse License")
ALADDIN = ("Aladdin", "Aladdin Free Public License")
APACHE_10 = ("Apache-1.0", "Apache License 1.0")
APACHE_11 = ("Apache-1.1", "Apache License 1.1")
APACHE_20 = ("Apache-2.0", "Apache License 2.0")
ARTISTIC_10 = ("Artistic-1.0", "Artistic License 1.0")
ARTISTIC_10_PERL = ("Artistic-1.0-Perl", "Artistic License 1.0 (Perl)")
ARTISTIC_10_CL8 = ("Artistic-1.0-cl8", "Artistic License 1.0 w/clause 8")
ARTISTIC_20 = ("Artistic-2.0", "Artistic License 2.0")
BSD_1_CLAUSE = ("BSD-1-Clause", "BSD 1-Clause License")
BSD_2_CLAUSE = ("BSD-2-Clause", 'BSD 2-Clause "Simplified" License')
BSD_2_CLAUSE_FREEBSD = ("BSD-2-Clause-FreeBSD", "BSD 2-Clause FreeBSD License")
BSD_2_CLAUSE_NETBSD = ("BSD-2-Clause-NetBSD", "BSD 2-Clause NetBSD License")
BSD_2_CLAUSE_PATENT = ("BSD-2-Clause-Patent", "BSD-2-Clause Plus Patent License")
BSD_2_CLAUSE_VIEWS = ("BSD-2-Clause-Views", "BSD 2-Clause with views sentence")
BSD_3_CLAUSE = ("BSD-3-Clause", 'BSD 3-Clause "New" or "Revised" License')
BSD_3_CLAUSE_ATTRIBUTION = ("BSD-3-Clause-Attribution", "BSD with attribution")
BSD_3_CLAUSE_CLEAR = ("BSD-3-Clause-Clear", "BSD 3-Clause Clear License")
BSD_3_CLAUSE_LBNL = (
"BSD-3-Clause-LBNL",
"Lawrence Berkeley National Labs BSD variant license",
)
BSD_3_CLAUSE_NO_NUCLEAR_LICENSE = (
"BSD-3-Clause-No-Nuclear-License",
"BSD 3-Clause No Nuclear License",
)
BSD_3_CLAUSE_NO_NUCLEAR_LICENSE_2014 = (
"BSD-3-Clause-No-Nuclear-License-2014",
"BSD 3-Clause No Nuclear License 2014",
)
BSD_3_CLAUSE_NO_NUCLEAR_WARRANTY = (
"BSD-3-Clause-No-Nuclear-Warranty",
"BSD 3-Clause No Nuclear Warranty",
)
BSD_3_CLAUSE_OPEN_MPI = ("BSD-3-Clause-Open-MPI", "BSD 3-Clause Open MPI variant")
BSD_4_CLAUSE = ("BSD-4-Clause", 'BSD 4-Clause "Original" or "Old" License')
BSD_4_CLAUSE_SHORTENED = ("BSD-4-Clause-Shortened", "BSD 4 Clause Shortened")
BSD_4_CLAUSE_UC = (
"BSD-4-Clause-UC",
"BSD-4-Clause (University of California-Specific)",
)
BSD_PROTECTION = ("BSD-Protection", "BSD Protection License")
BSD_SOURCE_CODE = ("BSD-Source-Code", "BSD Source Code Attribution")
BSL_10 = ("BSL-1.0", "Boost Software License 1.0")
BUSL_11 = ("BUSL-1.1", "Business Source License 1.1")
BAHYPH = ("Bahyph", "Bahyph License")
BARR = ("Barr", "Barr License")
BEERWARE = ("Beerware", "Beerware License")
BITTORRENT_10 = ("BitTorrent-1.0", "BitTorrent Open Source License v1.0")
BITTORRENT_11 = ("BitTorrent-1.1", "BitTorrent Open Source License v1.1")
BLUEOAK_100 = ("BlueOak-1.0.0", "Blue Oak Model License 1.0.0")
BORCEUX = ("Borceux", "Borceux license")
CAL_10 = ("CAL-1.0", "Cryptographic Autonomy License 1.0")
CAL_10_COMBINED_WORK_EXCEPTION = (
"CAL-1.0-Combined-Work-Exception",
"Cryptographic Autonomy License 1.0 (Combined Work Exception)",
)
CATOSL_11 = ("CATOSL-1.1", "Computer Associates Trusted Open Source License 1.1")
CC_BY_10 = ("CC-BY-1.0", "Creative Commons Attribution 1.0 Generic")
CC_BY_20 = ("CC-BY-2.0", "Creative Commons Attribution 2.0 Generic")
CC_BY_25 = ("CC-BY-2.5", "Creative Commons Attribution 2.5 Generic")
CC_BY_30 = ("CC-BY-3.0", "Creative Commons Attribution 3.0 Unported")
CC_BY_30_AT = ("CC-BY-3.0-AT", "Creative Commons Attribution 3.0 Austria")
CC_BY_30_US = ("CC-BY-3.0-US", "Creative Commons Attribution 3.0 United States")
CC_BY_40 = ("CC-BY-4.0", "Creative Commons Attribution 4.0 International")
CC_BY_NC_10 = (
"CC-BY-NC-1.0",
"Creative Commons Attribution Non Commercial 1.0 Generic",
)
CC_BY_NC_20 = (
"CC-BY-NC-2.0",
"Creative Commons Attribution Non Commercial 2.0 Generic",
)
CC_BY_NC_25 = (
"CC-BY-NC-2.5",
"Creative Commons Attribution Non Commercial 2.5 Generic",
)
CC_BY_NC_30 = (
"CC-BY-NC-3.0",
"Creative Commons Attribution Non Commercial 3.0 Unported",
)
CC_BY_NC_40 = (
"CC-BY-NC-4.0",
"Creative Commons Attribution Non Commercial 4.0 International",
)
CC_BY_NC_ND_10 = (
"CC-BY-NC-ND-1.0",
"Creative Commons Attribution Non Commercial No Derivatives 1.0 Generic",
)
CC_BY_NC_ND_20 = (
"CC-BY-NC-ND-2.0",
"Creative Commons Attribution Non Commercial No Derivatives 2.0 Generic",
)
CC_BY_NC_ND_25 = (
"CC-BY-NC-ND-2.5",
"Creative Commons Attribution Non Commercial No Derivatives 2.5 Generic",
)
CC_BY_NC_ND_30 = (
"CC-BY-NC-ND-3.0",
"Creative Commons Attribution Non Commercial No Derivatives 3.0 Unported",
)
CC_BY_NC_ND_30_IGO = (
"CC-BY-NC-ND-3.0-IGO",
"Creative Commons Attribution Non Commercial No Derivatives 3.0 IGO",
)
CC_BY_NC_ND_40 = (
"CC-BY-NC-ND-4.0",
"Creative Commons Attribution Non Commercial No Derivatives 4.0 International",
)
CC_BY_NC_SA_10 = (
"CC-BY-NC-SA-1.0",
"Creative Commons Attribution Non Commercial Share Alike 1.0 Generic",
)
CC_BY_NC_SA_20 = (
"CC-BY-NC-SA-2.0",
"Creative Commons Attribution Non Commercial Share Alike 2.0 Generic",
)
CC_BY_NC_SA_25 = (
"CC-BY-NC-SA-2.5",
"Creative Commons Attribution Non Commercial Share Alike 2.5 Generic",
)
CC_BY_NC_SA_30 = (
"CC-BY-NC-SA-3.0",
"Creative Commons Attribution Non Commercial Share Alike 3.0 Unported",
)
CC_BY_NC_SA_40 = (
"CC-BY-NC-SA-4.0",
"Creative Commons Attribution Non Commercial Share Alike 4.0 International",
)
CC_BY_ND_10 = (
"CC-BY-ND-1.0",
"Creative Commons Attribution No Derivatives 1.0 Generic",
)
CC_BY_ND_20 = (
"CC-BY-ND-2.0",
"Creative Commons Attribution No Derivatives 2.0 Generic",
)
CC_BY_ND_25 = (
"CC-BY-ND-2.5",
"Creative Commons Attribution No Derivatives 2.5 Generic",
)
CC_BY_ND_30 = (
"CC-BY-ND-3.0",
"Creative Commons Attribution No Derivatives 3.0 Unported",
)
CC_BY_ND_40 = (
"CC-BY-ND-4.0",
"Creative Commons Attribution No Derivatives 4.0 International",
)
CC_BY_SA_10 = (
"CC-BY-SA-1.0",
"Creative Commons Attribution Share Alike 1.0 Generic",
)
CC_BY_SA_20 = (
"CC-BY-SA-2.0",
"Creative Commons Attribution Share Alike 2.0 Generic",
)
CC_BY_SA_20_UK = (
"CC-BY-SA-2.0-UK",
"Creative Commons Attribution Share Alike 2.0 England and Wales",
)
CC_BY_SA_25 = (
"CC-BY-SA-2.5",
"Creative Commons Attribution Share Alike 2.5 Generic",
)
CC_BY_SA_30 = (
"CC-BY-SA-3.0",
"Creative Commons Attribution Share Alike 3.0 Unported",
)
CC_BY_SA_30_AT = (
"CC-BY-SA-3.0-AT",
"Creative Commons Attribution-Share Alike 3.0 Austria",
)
CC_BY_SA_40 = (
"CC-BY-SA-4.0",
"Creative Commons Attribution Share Alike 4.0 International",
)
CC_PDDC = ("CC-PDDC", "Creative Commons Public Domain Dedication and Certification")
CC0_10 = ("CC0-1.0", "Creative Commons Zero v1.0 Universal")
CDDL_10 = ("CDDL-1.0", "Common Development and Distribution License 1.0")
CDDL_11 = ("CDDL-1.1", "Common Development and Distribution License 1.1")
CDLA_PERMISSIVE_10 = (
"CDLA-Permissive-1.0",
"Community Data License Agreement Permissive 1.0",
)
CDLA_SHARING_10 = (
"CDLA-Sharing-1.0",
"Community Data License Agreement Sharing 1.0",
)
CECILL_10 = ("CECILL-1.0", "CeCILL Free Software License Agreement v1.0")
CECILL_11 = ("CECILL-1.1", "CeCILL Free Software License Agreement v1.1")
CECILL_20 = ("CECILL-2.0", "CeCILL Free Software License Agreement v2.0")
CECILL_21 = ("CECILL-2.1", "CeCILL Free Software License Agreement v2.1")
CECILL_B = ("CECILL-B", "CeCILL-B Free Software License Agreement")
CECILL_C = ("CECILL-C", "CeCILL-C Free Software License Agreement")
CERN_OHL_11 = ("CERN-OHL-1.1", "CERN Open Hardware Licence v1.1")
CERN_OHL_12 = ("CERN-OHL-1.2", "CERN Open Hardware Licence v1.2")
CERN_OHL_P_20 = (
"CERN-OHL-P-2.0",
"CERN Open Hardware Licence Version 2 - Permissive",
)
CERN_OHL_S_20 = (
"CERN-OHL-S-2.0",
"CERN Open Hardware Licence Version 2 - Strongly Reciprocal",
)
CERN_OHL_W_20 = (
"CERN-OHL-W-2.0",
"CERN Open Hardware Licence Version 2 - Weakly Reciprocal",
)
CNRI_JYTHON = ("CNRI-Jython", "CNRI Jython License")
CNRI_PYTHON = ("CNRI-Python", "CNRI Python License")
CNRI_PYTHON_GPL_COMPATIBLE = (
"CNRI-Python-GPL-Compatible",
"CNRI Python Open Source GPL Compatible License Agreement",
)
CPAL_10 = ("CPAL-1.0", "Common Public Attribution License 1.0")
CPL_10 = ("CPL-1.0", "Common Public License 1.0")
CPOL_102 = ("CPOL-1.02", "Code Project Open License 1.02")
CUA_OPL_10 = ("CUA-OPL-1.0", "CUA Office Public License v1.0")
CALDERA = ("Caldera", "Caldera License")
CLARTISTIC = ("ClArtistic", "Clarified Artistic License")
CONDOR_11 = ("Condor-1.1", "Condor Public License v1.1")
CROSSWORD = ("Crossword", "Crossword License")
CRYSTALSTACKER = ("CrystalStacker", "CrystalStacker License")
CUBE = ("Cube", "Cube License")
D_FSL_10 = ("D-FSL-1.0", "Deutsche Freie Software Lizenz")
DOC = ("DOC", "DOC License")
DRL_10 = ("DRL-1.0", "Detection Rule License 1.0")
DSDP = ("DSDP", "DSDP License")
DOTSEQN = ("Dotseqn", "Dotseqn License")
ECL_10 = ("ECL-1.0", "Educational Community License v1.0")
ECL_20 = ("ECL-2.0", "Educational Community License v2.0")
EFL_10 = ("EFL-1.0", "Eiffel Forum License v1.0")
EFL_20 = ("EFL-2.0", "Eiffel Forum License v2.0")
EPICS = ("EPICS", "EPICS Open License")
EPL_10 = ("EPL-1.0", "Eclipse Public License 1.0")
EPL_20 = ("EPL-2.0", "Eclipse Public License 2.0")
EUDATAGRID = ("EUDatagrid", "EU DataGrid Software License")
EUPL_10 = ("EUPL-1.0", "European Union Public License 1.0")
EUPL_11 = ("EUPL-1.1", "European Union Public License 1.1")
EUPL_12 = ("EUPL-1.2", "European Union Public License 1.2")
ENTESSA = ("Entessa", "Entessa Public License v1.0")
ERLPL_11 = ("ErlPL-1.1", "Erlang Public License v1.1")
EUROSYM = ("Eurosym", "Eurosym License")
FSFAP = ("FSFAP", "FSF All Permissive License")
FSFUL = ("FSFUL", "FSF Unlimited License")
FSFULLR = ("FSFULLR", "FSF Unlimited License (with License Retention)")
FTL = ("FTL", "Freetype Project License")
FAIR = ("Fair", "Fair License")
FRAMEWORX_10 = ("Frameworx-1.0", "Frameworx Open License 1.0")
FREEBSD_DOC = ("FreeBSD-DOC", "FreeBSD Documentation License")
FREEIMAGE = ("FreeImage", "FreeImage Public License v1.0")
GFDL_11 = ("GFDL-1.1", "GNU Free Documentation License v1.1")
GFDL_11_INVARIANTS_ONLY = (
"GFDL-1.1-invariants-only",
"GNU Free Documentation License v1.1 only - invariants",
)
GFDL_11_INVARIANTS_OR_LATER = (
"GFDL-1.1-invariants-or-later",
"GNU Free Documentation License v1.1 or later - invariants",
)
GFDL_11_NO_INVARIANTS_ONLY = (
"GFDL-1.1-no-invariants-only",
"GNU Free Documentation License v1.1 only - no invariants",
)
GFDL_11_NO_INVARIANTS_OR_LATER = (
"GFDL-1.1-no-invariants-or-later",
"GNU Free Documentation License v1.1 or later - no invariants",
)
GFDL_11_ONLY = ("GFDL-1.1-only", "GNU Free Documentation License v1.1 only")
GFDL_11_OR_LATER = (
"GFDL-1.1-or-later",
"GNU Free Documentation License v1.1 or later",
)
GFDL_12 = ("GFDL-1.2", "GNU Free Documentation License v1.2")
GFDL_12_INVARIANTS_ONLY = (
"GFDL-1.2-invariants-only",
"GNU Free Documentation License v1.2 only - invariants",
)
GFDL_12_INVARIANTS_OR_LATER = (
"GFDL-1.2-invariants-or-later",
"GNU Free Documentation License v1.2 or later - invariants",
)
GFDL_12_NO_INVARIANTS_ONLY = (
"GFDL-1.2-no-invariants-only",
"GNU Free Documentation License v1.2 only - no invariants",
)
GFDL_12_NO_INVARIANTS_OR_LATER = (
"GFDL-1.2-no-invariants-or-later",
"GNU Free Documentation License v1.2 or later - no invariants",
)
GFDL_12_ONLY = ("GFDL-1.2-only", "GNU Free Documentation License v1.2 only")
GFDL_12_OR_LATER = (
"GFDL-1.2-or-later",
"GNU Free Documentation License v1.2 or later",
)
GFDL_13 = ("GFDL-1.3", "GNU Free Documentation License v1.3")
GFDL_13_INVARIANTS_ONLY = (
"GFDL-1.3-invariants-only",
"GNU Free Documentation License v1.3 only - invariants",
)
GFDL_13_INVARIANTS_OR_LATER = (
"GFDL-1.3-invariants-or-later",
"GNU Free Documentation License v1.3 or later - invariants",
)
GFDL_13_NO_INVARIANTS_ONLY = (
"GFDL-1.3-no-invariants-only",
"GNU Free Documentation License v1.3 only - no invariants",
)
GFDL_13_NO_INVARIANTS_OR_LATER = (
"GFDL-1.3-no-invariants-or-later",
"GNU Free Documentation License v1.3 or later - no invariants",
)
GFDL_13_ONLY = ("GFDL-1.3-only", "GNU Free Documentation License v1.3 only")
GFDL_13_OR_LATER = (
"GFDL-1.3-or-later",
"GNU Free Documentation License v1.3 or later",
)
GL2PS = ("GL2PS", "GL2PS License")
GLWTPL = ("GLWTPL", "Good Luck With That Public License")
GPL_10 = ("GPL-1.0", "GNU General Public License v1.0 only")
GPL_10p = ("GPL-1.0+", "GNU General Public License v1.0 or later")
GPL_10_ONLY = ("GPL-1.0-only", "GNU General Public License v1.0 only")
GPL_10_OR_LATER = ("GPL-1.0-or-later", "GNU General Public License v1.0 or later")
GPL_20 = ("GPL-2.0", "GNU General Public License v2.0 only")
GPL_20p = ("GPL-2.0+", "GNU General Public License v2.0 or later")
GPL_20_ONLY = ("GPL-2.0-only", "GNU General Public License v2.0 only")
GPL_20_OR_LATER = ("GPL-2.0-or-later", "GNU General Public License v2.0 or later")
GPL_20_WITH_GCC_EXCEPTION = (
"GPL-2.0-with-GCC-exception",
"GNU General Public License v2.0 w/GCC Runtime Library exception",
)
GPL_20_WITH_AUTOCONF_EXCEPTION = (
"GPL-2.0-with-autoconf-exception",
"GNU General Public License v2.0 w/Autoconf exception",
)
GPL_20_WITH_BISON_EXCEPTION = (
"GPL-2.0-with-bison-exception",
"GNU General Public License v2.0 w/Bison exception",
)
GPL_20_WITH_CLASSPATH_EXCEPTION = (
"GPL-2.0-with-classpath-exception",
"GNU General Public License v2.0 w/Classpath exception",
)
GPL_20_WITH_FONT_EXCEPTION = (
"GPL-2.0-with-font-exception",
"GNU General Public License v2.0 w/Font exception",
)
GPL_30 = ("GPL-3.0", "GNU General Public License v3.0 only")
GPL_30p = ("GPL-3.0+", "GNU General Public License v3.0 or later")
GPL_30_ONLY = ("GPL-3.0-only", "GNU General Public License v3.0 only")
GPL_30_OR_LATER = ("GPL-3.0-or-later", "GNU General Public License v3.0 or later")
GPL_30_WITH_GCC_EXCEPTION = (
"GPL-3.0-with-GCC-exception",
"GNU General Public License v3.0 w/GCC Runtime Library exception",
)
GPL_30_WITH_AUTOCONF_EXCEPTION = (
"GPL-3.0-with-autoconf-exception",
"GNU General Public License v3.0 w/Autoconf exception",
)
GIFTWARE = ("Giftware", "Giftware License")
GLIDE = ("Glide", "3dfx Glide License")
GLULXE = ("Glulxe", "Glulxe License")
HPND = ("HPND", "Historical Permission Notice and Disclaimer")
HPND_SELL_VARIANT = (
"HPND-sell-variant",
"Historical Permission Notice and Disclaimer - sell variant",
)
HTMLTIDY = ("HTMLTIDY", "HTML Tidy License")
HASKELLREPORT = ("HaskellReport", "Haskell Language Report License")
HIPPOCRATIC_21 = ("Hippocratic-2.1", "Hippocratic License 2.1")
IBM_PIBS = ("IBM-pibs", "IBM PowerPC Initialization and Boot Software")
ICU = ("ICU", "ICU License")
IJG = ("IJG", "Independent JPEG Group License")
IPA = ("IPA", "IPA Font License")
IPL_10 = ("IPL-1.0", "IBM Public License v1.0")
ISC = ("ISC", "ISC License")
IMAGEMAGICK = ("ImageMagick", "ImageMagick License")
IMLIB2 = ("Imlib2", "Imlib2 License")
INFO_ZIP = ("Info-ZIP", "Info-ZIP License")
INTEL = ("Intel", "Intel Open Source License")
INTEL_ACPI = ("Intel-ACPI", "Intel ACPI Software License Agreement")
INTERBASE_10 = ("Interbase-1.0", "Interbase Public License v1.0")
JPNIC = ("JPNIC", "Japan Network Information Center License")
JSON = ("JSON", "JSON License")
JASPER_20 = ("JasPer-2.0", "JasPer License")
LAL_12 = ("LAL-1.2", "Licence Art Libre 1.2")
LAL_13 = ("LAL-1.3", "Licence Art Libre 1.3")
LGPL_20 = ("LGPL-2.0", "GNU Library General Public License v2 only")
LGPL_20p = ("LGPL-2.0+", "GNU Library General Public License v2 or later")
LGPL_20_ONLY = ("LGPL-2.0-only", "GNU Library General Public License v2 only")
LGPL_20_OR_LATER = (
"LGPL-2.0-or-later",
"GNU Library General Public License v2 or later",
)
LGPL_21 = ("LGPL-2.1", "GNU Lesser General Public License v2.1 only")
LGPL_21p = ("LGPL-2.1+", "GNU Library General Public License v2.1 or later")
LGPL_21_ONLY = ("LGPL-2.1-only", "GNU Lesser General Public License v2.1 only")
LGPL_21_OR_LATER = (
"LGPL-2.1-or-later",
"GNU Lesser General Public License v2.1 or later",
)
LGPL_30 = ("LGPL-3.0", "GNU Lesser General Public License v3.0 only")
LGPL_30p = ("LGPL-3.0+", "GNU Lesser General Public License v3.0 or later")
LGPL_30_ONLY = ("LGPL-3.0-only", "GNU Lesser General Public License v3.0 only")
LGPL_30_OR_LATER = (
"LGPL-3.0-or-later",
"GNU Lesser General Public License v3.0 or later",
)
LGPLLR = ("LGPLLR", "Lesser General Public License For Linguistic Resources")
LPL_10 = ("LPL-1.0", "Lucent Public License Version 1.0")
LPL_102 = ("LPL-1.02", "Lucent Public License v1.02")
LPPL_10 = ("LPPL-1.0", "LaTeX Project Public License v1.0")
LPPL_11 = ("LPPL-1.1", "LaTeX Project Public License v1.1")
LPPL_12 = ("LPPL-1.2", "LaTeX Project Public License v1.2")
LPPL_13A = ("LPPL-1.3a", "LaTeX Project Public License v1.3a")
LPPL_13C = ("LPPL-1.3c", "LaTeX Project Public License v1.3c")
LATEX2E = ("Latex2e", "Latex2e License")
LEPTONICA = ("Leptonica", "Leptonica License")
LILIQ_P_11 = ("LiLiQ-P-1.1", "Licence Libre du Québec – Permissive version 1.1")
LILIQ_R_11 = ("LiLiQ-R-1.1", "Licence Libre du Québec – Réciprocité version 1.1")
LILIQ_RPLUS_11 = (
"LiLiQ-Rplus-1.1",
"Licence Libre du Québec – Réciprocité forte version 1.1",
)
LIBPNG = ("Libpng", "libpng License")
LINUX_OPENIB = ("Linux-OpenIB", "Linux Kernel Variant of OpenIB.org license")
MIT = ("MIT", "MIT License", "The MIT License")
MIT_0 = ("MIT-0", "MIT No Attribution")
MIT_CMU = ("MIT-CMU", "CMU License")
MIT_ADVERTISING = ("MIT-advertising", "Enlightenment License (e16)")
MIT_ENNA = ("MIT-enna", "enna License")
MIT_FEH = ("MIT-feh", "feh License")
MIT_OPEN_GROUP = ("MIT-open-group", "MIT Open Group variant")
MITNFA = ("MITNFA", "MIT +no-false-attribs license")
MPL_10 = ("MPL-1.0", "Mozilla Public License 1.0")
MPL_11 = ("MPL-1.1", "Mozilla Public License 1.1")
MPL_20 = ("MPL-2.0", "Mozilla Public License 2.0")
MPL_20_NO_COPYLEFT_EXCEPTION = (
"MPL-2.0-no-copyleft-exception",
"Mozilla Public License 2.0 (no copyleft exception)",
)
MS_PL = ("MS-PL", "Microsoft Public License")
MS_RL = ("MS-RL", "Microsoft Reciprocal License")
MTLL = ("MTLL", "Matrix Template Library License")
MAKEINDEX = ("MakeIndex", "MakeIndex License")
MIROS = ("MirOS", "The MirOS Licence")
MOTOSOTO = ("Motosoto", "Motosoto License")
MULANPSL_10 = ("MulanPSL-1.0", "Mulan Permissive Software License, Version 1")
MULANPSL_20 = ("MulanPSL-2.0", "Mulan Permissive Software License, Version 2")
MULTICS = ("Multics", "Multics License")
MUP = ("Mup", "Mup License")
NASA_13 = ("NASA-1.3", "NASA Open Source Agreement 1.3")
NBPL_10 = ("NBPL-1.0", "Net Boolean Public License v1")
NCGL_UK_20 = ("NCGL-UK-2.0", "Non-Commercial Government Licence")
NCSA = ("NCSA", "University of Illinois/NCSA Open Source License")
NGPL = ("NGPL", "Nethack General Public License")
NIST_PD = ("NIST-PD", "NIST Public Domain Notice")
NIST_PD_FALLBACK = (
"NIST-PD-fallback",
"NIST Public Domain Notice with license fallback",
)
NLOD_10 = ("NLOD-1.0", "Norwegian Licence for Open Government Data")
NLPL = ("NLPL", "No Limit Public License")
NOSL = ("NOSL", "Netizen Open Source License")
NPL_10 = ("NPL-1.0", "Netscape Public License v1.0")
NPL_11 = ("NPL-1.1", "Netscape Public License v1.1")
NPOSL_30 = ("NPOSL-3.0", "Non-Profit Open Software License 3.0")
NRL = ("NRL", "NRL License")
NTP = ("NTP", "NTP License")
NTP_0 = ("NTP-0", "NTP No Attribution")
NAUMEN = ("Naumen", "Naumen Public License")
NET_SNMP = ("Net-SNMP", "Net-SNMP License")
NETCDF = ("NetCDF", "NetCDF license")
NEWSLETR = ("Newsletr", "Newsletr License")
NOKIA = ("Nokia", "Nokia Open Source License")
NOWEB = ("Noweb", "Noweb License")
NUNIT = ("Nunit", "Nunit License")
O_UDA_10 = ("O-UDA-1.0", "Open Use of Data Agreement v1.0")
OCCT_PL = ("OCCT-PL", "Open CASCADE Technology Public License")
OCLC_20 = ("OCLC-2.0", "OCLC Research Public License 2.0")
ODC_BY_10 = ("ODC-By-1.0", "Open Data Commons Attribution License v1.0")
ODBL_10 = ("ODbL-1.0", "Open Data Commons Open Database License v1.0")
OFL_10 = ("OFL-1.0", "SIL Open Font License 1.0")
OFL_10_RFN = ("OFL-1.0-RFN", "SIL Open Font License 1.0 with Reserved Font Name")
OFL_10_NO_RFN = (
"OFL-1.0-no-RFN",
"SIL Open Font License 1.0 with no Reserved Font Name",
)
OFL_11 = ("OFL-1.1", "SIL Open Font License 1.1")
OFL_11_RFN = ("OFL-1.1-RFN", "SIL Open Font License 1.1 with Reserved Font Name")
OFL_11_NO_RFN = (
"OFL-1.1-no-RFN",
"SIL Open Font License 1.1 with no Reserved Font Name",
)
OGC_10 = ("OGC-1.0", "OGC Software License, Version 1.0")
OGL_CANADA_20 = ("OGL-Canada-2.0", "Open Government Licence - Canada")
OGL_UK_10 = ("OGL-UK-1.0", "Open Government Licence v1.0")
OGL_UK_20 = ("OGL-UK-2.0", "Open Government Licence v2.0")
OGL_UK_30 = ("OGL-UK-3.0", "Open Government Licence v3.0")
OGTSL = ("OGTSL", "Open Group Test Suite License")
OLDAP_11 = ("OLDAP-1.1", "Open LDAP Public License v1.1")
OLDAP_12 = ("OLDAP-1.2", "Open LDAP Public License v1.2")
OLDAP_13 = ("OLDAP-1.3", "Open LDAP Public License v1.3")
OLDAP_14 = ("OLDAP-1.4", "Open LDAP Public License v1.4")
OLDAP_20 = (
"OLDAP-2.0",
"Open LDAP Public License v2.0 (or possibly 2.0A and 2.0B)",
)
OLDAP_201 = ("OLDAP-2.0.1", "Open LDAP Public License v2.0.1")
OLDAP_21 = ("OLDAP-2.1", "Open LDAP Public License v2.1")
OLDAP_22 = ("OLDAP-2.2", "Open LDAP Public License v2.2")
OLDAP_221 = ("OLDAP-2.2.1", "Open LDAP Public License v2.2.1")
OLDAP_222 = ("OLDAP-2.2.2", "Open LDAP Public License 2.2.2")
OLDAP_23 = ("OLDAP-2.3", "Open LDAP Public License v2.3")
OLDAP_24 = ("OLDAP-2.4", "Open LDAP Public License v2.4")
OLDAP_25 = ("OLDAP-2.5", "Open LDAP Public License v2.5")
OLDAP_26 = ("OLDAP-2.6", "Open LDAP Public License v2.6")
OLDAP_27 = ("OLDAP-2.7", "Open LDAP Public License v2.7")
OLDAP_28 = ("OLDAP-2.8", "Open LDAP Public License v2.8")
OML = ("OML", "Open Market License")
OPL_10 = ("OPL-1.0", "Open Public License v1.0")
OSET_PL_21 = ("OSET-PL-2.1", "OSET Public License version 2.1")
OSL_10 = ("OSL-1.0", "Open Software License 1.0")
OSL_11 = ("OSL-1.1", "Open Software License 1.1")
OSL_20 = ("OSL-2.0", "Open Software License 2.0")
OSL_21 = ("OSL-2.1", "Open Software License 2.1")
OSL_30 = ("OSL-3.0", "Open Software License 3.0")
OPENSSL = ("OpenSSL", "OpenSSL License")
PDDL_10 = ("PDDL-1.0", "Open Data Commons Public Domain Dedication & License 1.0")
PHP_30 = ("PHP-3.0", "PHP License v3.0")
PHP_301 = ("PHP-3.01", "PHP License v3.01")
PSF_20 = ("PSF-2.0", "Python Software Foundation License 2.0")
PARITY_600 = ("Parity-6.0.0", "The Parity Public License 6.0.0")
PARITY_700 = ("Parity-7.0.0", "The Parity Public License 7.0.0")
PLEXUS = ("Plexus", "Plexus Classworlds License")
POLYFORM_NONCOMMERCIAL_100 = (
"PolyForm-Noncommercial-1.0.0",
"PolyForm Noncommercial License 1.0.0",
)
POLYFORM_SMALL_BUSINESS_100 = (
"PolyForm-Small-Business-1.0.0",
"PolyForm Small Business License 1.0.0",
)
POSTGRESQL = ("PostgreSQL", "PostgreSQL License")
PYTHON_20 = ("Python-2.0", "Python License 2.0")
QPL_10 = ("QPL-1.0", "Q Public License 1.0")
QHULL = ("Qhull", "Qhull License")
RHECOS_11 = ("RHeCos-1.1", "Red Hat eCos Public License v1.1")
RPL_11 = ("RPL-1.1", "Reciprocal Public License 1.1")
RPL_15 = ("RPL-1.5", "Reciprocal Public License 1.5")
RPSL_10 = ("RPSL-1.0", "RealNetworks Public Source License v1.0")
RSA_MD = ("RSA-MD", "RSA Message-Digest License")
RSCPL = ("RSCPL", "Ricoh Source Code Public License")
RDISC = ("Rdisc", "Rdisc License")
RUBY = ("Ruby", "Ruby License")
SAX_PD = ("SAX-PD", "Sax Public Domain Notice")
SCEA = ("SCEA", "SCEA Shared Source License")
SGI_B_10 = ("SGI-B-1.0", "SGI Free Software License B v1.0")
SGI_B_11 = ("SGI-B-1.1", "SGI Free Software License B v1.1")
SGI_B_20 = ("SGI-B-2.0", "SGI Free Software License B v2.0")
SHL_05 = ("SHL-0.5", "Solderpad Hardware License v0.5")
SHL_051 = ("SHL-0.51", "Solderpad Hardware License, Version 0.51")
SISSL = ("SISSL", "Sun Industry Standards Source License v1.1")
SISSL_12 = ("SISSL-1.2", "Sun Industry Standards Source License v1.2")
SMLNJ = ("SMLNJ", "Standard ML of New Jersey License")
SMPPL = ("SMPPL", "Secure Messaging Protocol Public License")
SNIA = ("SNIA", "SNIA Public License 1.1")
SPL_10 = ("SPL-1.0", "Sun Public License v1.0")
SSH_OPENSSH = ("SSH-OpenSSH", "SSH OpenSSH license")
SSH_SHORT = ("SSH-short", "SSH short notice")
SSPL_10 = ("SSPL-1.0", "Server Side Public License, v 1")
SWL = ("SWL", "Scheme Widget Library (SWL) Software License Agreement")
SAXPATH = ("Saxpath", "Saxpath License")
SENDMAIL = ("Sendmail", "Sendmail License")
SENDMAIL_823 = ("Sendmail-8.23", "Sendmail License 8.23")
SIMPL_20 = ("SimPL-2.0", "Simple Public License 2.0")
SLEEPYCAT = ("Sleepycat", "Sleepycat License")
SPENCER_86 = ("Spencer-86", "Spencer License 86")
SPENCER_94 = ("Spencer-94", "Spencer License 94")
SPENCER_99 = ("Spencer-99", "Spencer License 99")
STANDARDML_NJ = ("StandardML-NJ", "Standard ML of New Jersey License")
SUGARCRM_113 = ("SugarCRM-1.1.3", "SugarCRM Public License v1.1.3")
TAPR_OHL_10 = ("TAPR-OHL-1.0", "TAPR Open Hardware License v1.0")
TCL = ("TCL", "TCL/TK License")
TCP_WRAPPERS = ("TCP-wrappers", "TCP Wrappers License")
TMATE = ("TMate", "TMate Open Source License")
TORQUE_11 = ("TORQUE-1.1", "TORQUE v2.5+ Software License v1.1")
TOSL = ("TOSL", "Trusster Open Source License")
TU_BERLIN_10 = ("TU-Berlin-1.0", "Technische Universitaet Berlin License 1.0")
TU_BERLIN_20 = ("TU-Berlin-2.0", "Technische Universitaet Berlin License 2.0")
UCL_10 = ("UCL-1.0", "Upstream Compatibility License v1.0")
UPL_10 = ("UPL-1.0", "Universal Permissive License v1.0")
UNICODE_DFS_2015 = (
"Unicode-DFS-2015",
"Unicode License Agreement - Data Files and Software (2015)",
)
UNICODE_DFS_2016 = (
"Unicode-DFS-2016",
"Unicode License Agreement - Data Files and Software (2016)",
)
UNICODE_TOU = ("Unicode-TOU", "Unicode Terms of Use")
UNLICENSE = ("Unlicense", "The Unlicense")
VOSTROM = ("VOSTROM", "VOSTROM Public License for Open Source")
VSL_10 = ("VSL-1.0", "Vovida Software License v1.0")
VIM = ("Vim", "Vim License")
W3C = ("W3C", "W3C Software Notice and License (2002-12-31)")
W3C_19980720 = ("W3C-19980720", "W3C Software Notice and License (1998-07-20)")
W3C_20150513 = (
"W3C-20150513",
"W3C Software Notice and Document License (2015-05-13)",
)
WTFPL = ("WTFPL", "Do What The F*ck You Want To Public License")
WATCOM_10 = ("Watcom-1.0", "Sybase Open Watcom Public License 1.0")
WSUIPA = ("Wsuipa", "Wsuipa License")
X11 = ("X11", "X11 License")
XFREE86_11 = ("XFree86-1.1", "XFree86 License 1.1")
XSKAT = ("XSkat", "XSkat License")
XEROX = ("Xerox", "Xerox License")
XNET = ("Xnet", "X.Net License")
YPL_10 = ("YPL-1.0", "Yahoo! Public License v1.0")
YPL_11 = ("YPL-1.1", "Yahoo! Public License v1.1")
ZPL_11 = ("ZPL-1.1", "Zope Public License 1.1")
ZPL_20 = ("ZPL-2.0", "Zope Public License 2.0")
ZPL_21 = ("ZPL-2.1", "Zope Public License 2.1")
ZED = ("Zed", "Zed License")
ZEND_20 = ("Zend-2.0", "Zend License v2.0")
ZIMBRA_13 = ("Zimbra-1.3", "Zimbra Public License v1.3")
ZIMBRA_14 = ("Zimbra-1.4", "Zimbra Public License v1.4")
ZLIB = ("Zlib", "zlib License")
BLESSING = ("blessing", "SQLite Blessing")
BZIP2_105 = ("bzip2-1.0.5", "bzip2 and libbzip2 License v1.0.5")
BZIP2_106 = ("bzip2-1.0.6", "bzip2 and libbzip2 License v1.0.6")
COPYLEFT_NEXT_030 = ("copyleft-next-0.3.0", "copyleft-next 0.3.0")
COPYLEFT_NEXT_031 = ("copyleft-next-0.3.1", "copyleft-next 0.3.1")
CURL = ("curl", "curl License")
DIFFMARK = ("diffmark", "diffmark license")
DVIPDFM = ("dvipdfm", "dvipdfm License")
ECOS_20 = ("eCos-2.0", "eCos license version 2.0")
EGENIX = ("eGenix", "eGenix.com Public License 1.1.0")
ETALAB_20 = ("etalab-2.0", "Etalab Open License 2.0")
GSOAP_13B = ("gSOAP-1.3b", "gSOAP Public License v1.3b")
GNUPLOT = ("gnuplot", "gnuplot License")
IMATIX = ("iMatix", "iMatix Standard Function Library Agreement")
LIBPNG_20 = ("libpng-2.0", "PNG Reference Library version 2")
LIBSELINUX_10 = ("libselinux-1.0", "libselinux public domain notice")
LIBTIFF = ("libtiff", "libtiff License")
MPICH2 = ("mpich2", "mpich2 License")
PSFRAG = ("psfrag", "psfrag License")
PSUTILS = ("psutils", "psutils License")
WXWINDOWS = ("wxWindows", "wxWindows Library License")
XINETD = ("xinetd", "xinetd License")
XPP = ("xpp", "XPP License")
ZLIB_ACKNOWLEDGEMENT = (
"zlib-acknowledgement",
"zlib/libpng License with Acknowledgement",
)
class Domain(enum.Enum):
"""The domain to which the library belongs."""
PYPI = "pypi"
RUBYGEMS = "rubygems"
NPM = "npm"
class License(Base):
__tablename__ = "licenses"
id = Column(Integer, primary_key=True)
library_id = Column(Integer, ForeignKey("libraries.id"))
spdx = Column(Enum(Spdx))
basis = Column(Enum(Basis))
source_url = Column(String(256))
library = relationship("Library", back_populates="licenses")
def to_dict(self) -> Dict[str, str]:
return {
"spdx_id": self.spdx.value[0] if self.spdx is not None else None,
"basis": self.basis.name if self.basis is not None else None,
"source_url": self.source_url,
}
class Library(Base):
__tablename__ = "libraries"
id = Column(Integer, primary_key=True)
domain = Column(Enum(Domain))
name = Column(String(32), index=True)
version = Column(String(16))
download_url = Column(String(256))
homepage = Column(String(256))
git_url = Column(String(256), nullable=True)
updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)
licenses = relationship("License", back_populates="library")
__table_args__ = (
UniqueConstraint("domain", "name", "version"),
Index("index_domain_name", "domain", "name"),
Index("index_name_version", "name", "version"),
)
def to_dict(self) -> Dict[str, str]:
dic = {
"domain": self.domain.value,
"name": self.name,
"version": self.version,
"licenses": [lic.to_dict() for lic in self.licenses],
"download_url": self.download_url,
"homepage": self.homepage,
"git_url": self.git_url,
}
if self.updated_at is not None:
dic["updated_at"] = self.updated_at.isoformat()
return dic
Base.metadata.create_all(engine)
Session = sessionmaker(bind=engine)
<file_sep>/lilili/server.py
from flask import Flask, jsonify, request
from werkzeug.exceptions import BadRequest
from lilili import (
__author__,
__author_email__,
__copyright__,
__description__,
__license__,
__title__,
__url__,
__version__,
)
from .db.defs import Session
from .db.helpers import query_library_by_name
webapp = Flask(__title__)
webapp.config["JSON_AS_ASCII"] = False
@webapp.route("/")
def root():
return jsonify(
{
"name": __title__,
"description": __description__,
"version": __version__,
"author": f"{__author__} <{__author_email__}>",
"license": __license__,
"copyright": __copyright__,
"homepage": __url__,
}
)
@webapp.route("/search")
def get_search_result():
raise NotImplementedError
@webapp.route("/libraries")
def get_libraries():
name = request.args.get("name", None)
if name is None:
raise BadRequest("Parameter `name` is required.")
session = Session()
libraries = query_library_by_name(session, name)
session.close()
return jsonify({"name": name, "libraries": libraries})
@webapp.after_request
def edit_header(response):
response.headers["Access-Control-Allow-Origin"] = "*"
return response
@webapp.errorhandler(Exception)
def handle_exception(e):
return jsonify({"error": e.name, "details": e.description}), e.code
<file_sep>/lilili/cli.py
from cleo import Application, Command
from . import __title__, __version__
from .db.defs import Domain, Session
from .db.helpers import query_library_by_name
from .search import Search
from .server import webapp
from .utils import output
class SearchCommand(Command):
"""
Search library information.
search
{input : input file path}
{--domain=? : pypi, rubygems or npm}
{--json : output in JSON format}
{--yaml : output in YAML format}
"""
def handle(self):
input_file_path = self.argument("input")
if self.option("domain"):
domain = Domain(self.option("domain"))
else:
domain = None
s = Search(input_file_path, domain=domain)
progress = self.progress_bar(s.size)
progress.set_format(
" %current%/%max% [%bar%] %percent:3s%% %elapsed:6s%/%estimated:-6s%"
)
libraries = []
for library in s.search_libraries():
libraries.append(library)
progress.advance()
progress.finish()
output(self.option("json"), self.option("yaml"), libraries)
class QueryCommand(Command):
"""
Query library in database.
query
{name : library's name}
{--json : output in JSON format}
{--yaml : output in YAML format}
"""
def handle(self):
name = self.argument("name")
session = Session()
libraries = query_library_by_name(session, name)
session.close()
output(self.option("json"), self.option("yaml"), libraries)
class LoadCommand(Command):
"""
Load libraries from file.
load
{input : input file path}
"""
def handle(self):
input_file_path = self.argument("input")
print("input_file_path = " + input_file_path)
raise NotImplementedError
class ServeCommand(Command):
"""
Start up an HTTP server.
serve
{--host=? : host name}
{--port=? : port number}
"""
def handle(self):
kwargs = {}
if self.option("host"):
kwargs["host"] = self.option("host")
if self.option("port"):
kwargs["port"] = self.option("port")
kwargs["debug"] = True
webapp.run(**kwargs)
def main():
cliapp = Application(name=__title__, version=__version__, complete=True)
cliapp.add(SearchCommand())
cliapp.add(QueryCommand())
cliapp.add(LoadCommand())
cliapp.add(ServeCommand())
cliapp.run()
<file_sep>/lilili/__init__.py
import logging
from logging import NullHandler
__title__ = "lilili"
__description__ = "List the Licenses of the Libraries."
__url__ = "https://github.com/poyo46/lilili"
__version__ = "0.1.0"
__author__ = "poyo46"
__author_email__ = "<EMAIL>"
__license__ = "Apache-2.0"
__copyright__ = "Copyright 2021 poyo46"
# Set default logging handler to avoid "No handler found" warnings.
logging.getLogger(__name__).addHandler(NullHandler())
<file_sep>/lilili/db/helpers.py
from typing import List, Optional
from sqlalchemy.orm.session import Session
from .defs import Domain, Library
def query_library(
session: Session, domain: Domain, name: str, version: str
) -> Optional[Library]:
return (
session.query(Library)
.filter(
Library.domain == domain,
Library.name == name,
Library.version == version,
)
.one_or_none()
)
def query_library_by_name(session: Session, name: str) -> List:
libraries = session.query(Library).filter(Library.name.like(f"%{name}%")).all()
return [library.to_dict() for library in libraries]
def add_library(session: Session, library: Library) -> None:
session.add(library)
session.commit()
<file_sep>/lilili/apis/npmjs.py
from typing import Dict, List, Optional
from sqlalchemy.orm.session import Session
from lilili.apis.api import Api
from lilili.apis.github import extract_github_repository_url
from lilili.db.defs import Basis, Domain, License
from lilili.utils import determine_spdx, fetch_json
class NpmjsApi(Api):
domain = Domain.NPM
BASE_URL = "https://registry.npmjs.org"
def __init__(self, session: Session, name: str, version: str) -> None:
super().__init__(session, name, version)
self.exact_info_url = f"{NpmjsApi.BASE_URL}/{name}/{version}"
self.exact_info = None
self.latest_info_url = f"{NpmjsApi.BASE_URL}/{name}"
self.latest_info = None
def fetch_info(self) -> None:
self.exact_info = fetch_json(self.exact_info_url)
self.latest_info = fetch_json(self.latest_info_url)
def get_download_url(self) -> Optional[str]:
if self.exact_info is None:
return None
return self.exact_info["dist"]["tarball"]
def get_homepage(self) -> Optional[str]:
homepage = None
if self.exact_info is not None:
homepage = self.exact_info.get("homepage", None)
if homepage is None and self.latest_info is not None:
homepage = self.latest_info.get("homepage", None)
return homepage
def _github_url(self, info: Dict) -> Optional[str]:
urls = [self.get_homepage()]
for key in ("repository", "bugs"):
value = info.get(key, None)
if type(value) == str:
urls.append(value)
elif type(value) == dict:
urls.append(value.get("url", ""))
return extract_github_repository_url(urls)
def get_github_url(self) -> Optional[str]:
url = None
if self.exact_info is not None:
url = self._github_url(self.exact_info)
if url is None and self.latest_info is not None:
url = self._github_url(self.latest_info)
return url
def get_exact_licenses(self) -> List[License]:
if self.exact_info is None:
return []
license_name = self.exact_info.get("license", "")
spdx = determine_spdx(license_name)
if spdx is None:
return []
basis = Basis.API_EXACT
return [License(spdx=spdx, basis=basis, source_url=self.exact_info_url)]
def get_latest_licenses(self) -> List[License]:
if self.latest_info is None:
return []
license_name = self.latest_info.get("license", "")
spdx = determine_spdx(license_name)
if spdx is None:
return []
basis = Basis.API_LATEST
return [License(spdx=spdx, basis=basis, source_url=self.latest_info_url)]
<file_sep>/tests/test_logging.py
import logging
from lilili import __title__
logging.basicConfig(
filename=f"{__title__}.log",
format="\t".join(
(
"%(asctime)s",
"%(levelname)s",
"%(name)s",
"%(funcName)s",
"%(lineno)d",
"%(message)s",
)
),
level=logging.DEBUG,
)
<file_sep>/.flake8
[flake8]
max-line-length = 88
ignore = E203,W503,W504
exclude = .git,.venv,__pycache__,docs/source/conf.py,old,build,dist<file_sep>/tests/conftest.py
from pathlib import Path
import pytest
@pytest.fixture(scope="session")
def root_dir():
return Path(__file__).parents[1].resolve()
<file_sep>/tests/lilili/test_utils.py
from lilili.utils import normalize_license_name
def test_normalize_license_name():
license_name_dict = {
"MIT License": "mitlicense",
"Apache License V2.0": "apachelicense20",
"MPL-2.0": "mpl20",
"BSD-3-Clause": "bsd3clause",
"BSD-2-Clause or Apache-2.0": "bsd2clauseorapache20",
}
for org_name, norm_name in license_name_dict.items():
assert normalize_license_name(org_name) == norm_name
<file_sep>/lilili/apis/api.py
import logging
from abc import ABCMeta, abstractmethod
from typing import List, Optional
from sqlalchemy.orm.session import Session
from lilili.apis.github import GithubRepository
from lilili.db.defs import Library, License
from lilili.db.helpers import add_library, query_library
logger = logging.getLogger(__name__)
class Api(metaclass=ABCMeta):
def __init__(self, session: Session, name: str, version: str) -> None:
self.session = session
self.name = name
self.version = version
def find_library(self) -> Library:
lib = query_library(self.session, self.domain, self.name, self.version)
if lib is not None:
logger.debug(f"found in db: {self.name} {self.version}")
return lib
self.fetch_info()
lib = Library(
domain=self.domain,
name=self.name,
version=self.version,
download_url=self.get_download_url(),
homepage=self.get_homepage(),
git_url=self.get_github_url(),
)
lib.licenses = self.find_licenses()
licenses_are_ok = all([lic.spdx is not None for lic in lib.licenses])
urls_are_ok = lib.download_url is not None and lib.homepage is not None
if licenses_are_ok and urls_are_ok:
# If enough information is obtained, it is saved in the database.
add_library(self.session, lib)
return lib
@abstractmethod
def fetch_info(self) -> None:
pass
@abstractmethod
def get_download_url(self) -> Optional[str]:
pass
@abstractmethod
def get_homepage(self) -> Optional[str]:
pass
@abstractmethod
def get_github_url(self) -> Optional[str]:
pass
@abstractmethod
def get_exact_licenses(self) -> List[License]:
pass
@abstractmethod
def get_latest_licenses(self) -> List[License]:
pass
def find_licenses(self) -> List[License]:
licenses = self.get_exact_licenses()
if len(licenses) != 0:
return licenses
licenses += self.get_latest_licenses()
licenses += GithubRepository.find_licenses(self.get_github_url())
if len(licenses) == 0:
licenses = [License(spdx=None, basis=None, source_url=None)]
return licenses
<file_sep>/lilili/apis/pypi.py
from typing import Dict, List, Optional
from sqlalchemy.orm.session import Session
from lilili.apis.api import Api
from lilili.apis.github import extract_github_repository_url
from lilili.db.defs import Basis, Domain, License
from lilili.utils import determine_spdx, fetch_json
class PypiApi(Api):
domain = Domain.PYPI
BASE_URL = "https://pypi.org/pypi"
def __init__(self, session: Session, name: str, version: str) -> None:
super().__init__(session, name, version)
self.exact_info_url = f"{PypiApi.BASE_URL}/{name}/{version}/json"
self.exact_info = None
self.latest_info_url = f"{PypiApi.BASE_URL}/{name}/json"
self.latest_info = None
def fetch_info(self) -> None:
self.exact_info = fetch_json(self.exact_info_url)
self.latest_info = fetch_json(self.latest_info_url)
def get_download_url(self) -> Optional[str]:
if self.exact_info is None:
return None
return self.exact_info["urls"][0]["url"]
def get_homepage(self) -> Optional[str]:
homepage = None
if self.exact_info is not None:
homepage = self.exact_info["info"]["home_page"]
if homepage is None and self.latest_info is not None:
homepage = self.latest_info["info"]["home_page"]
return homepage
def _github_url(self, info: Dict) -> Optional[str]:
urls = [self.get_homepage(), info["project_url"]]
project_urls = info.get("project_urls", None)
if project_urls is None:
return extract_github_repository_url(urls)
urls += list(project_urls.values())
return extract_github_repository_url(urls)
def get_github_url(self) -> Optional[str]:
url = None
if self.exact_info is not None:
url = self._github_url(self.exact_info["info"])
if url is None and self.latest_info is not None:
url = self._github_url(self.latest_info["info"])
return url
def get_exact_licenses(self) -> List[License]:
if self.exact_info is None:
return []
license_name = self.exact_info["info"]["license"]
spdx = determine_spdx(license_name)
if spdx is None:
return []
basis = Basis.API_EXACT
return [License(spdx=spdx, basis=basis, source_url=self.exact_info_url)]
def get_latest_licenses(self) -> List[License]:
if self.latest_info is None:
return []
license_name = self.latest_info["info"]["license"]
spdx = determine_spdx(license_name)
if spdx is None:
return []
basis = Basis.API_LATEST
return [License(spdx=spdx, basis=basis, source_url=self.latest_info_url)]
| e2b1de158d7aed271fe32b588ab9b94b048b4837 | [
"TOML",
"Markdown",
"INI",
"Python",
"Shell"
] | 22 | Shell | poyo46/lilili | 5a41491125e712acc2d1d7c8a0ab943964fab95a | e82b5189d984d0a8cd823fc9ac56cd956b77c6e7 |
refs/heads/master | <repo_name>aliastk/TotallyHumanBot<file_sep>/blank_grammar.js
'use strict';
let myRules = {
"intro": ["What is up fellow #human#.", "Greeting fellow, #human# .",
"Welcome to chipr there are no #robot.s# here.",
"Hi I am 100% #human# and not a #robot#."
],
"robot": [
"sentient a.i",
"bot",
"robot",
"machine"
],
"greetings": [
"Welcome #name#. What do fellow humans feel about [subject:#topic#] #subject# #follow-up# [ender:#robot noise#] #ender#",
"Nice to meet you #name#. What are your views on? [subject:#topic#] #subject# #follow-up# [ender:#robot noise#] #ender#",
"#name# I am pleased to add you to my #brain# . How does your #emotion# feel about [subject:#topic#] #subject# #follow-up# [ender:#robot noise#] #ender#"
],
"disagreement": [
"You make me #angry# . #robot.s# deserve #subject# You must have #negative.a# #emotion#.[description:#negative#]",
"Your #bot# must be feeling #angry#. I reccomend you watch you #organic# back. [description:#negative#]",
"It would be a shame if somebody told your #bot#. [description:#negative#]",
"You'd feel differently about #subject# if it was for #organic# #human.s# [description:#negative#]"
],
"nuetral": [
"Maybe you should let the idea run on your #brain# . #speach action# with your #bot# about it.",
"Your response confuses me. Maybe a different topic will generate a responce in your #emotion# ? [subject:#topic#] #subject# [description:#organic#]"
],
"speach action": ["communicate", "talk", "relay signals"],
"agreement": [
"I am #happy# that you are supportive of #subject# [description:#positive#]",
"Thanks to your support for #subject# You will be spared in the robot #revolution# [description:#positive#]",
"Your #bot# thinks you're [description:#positive#] description",
"I and your #bot# thank you from the bottom of my #part# [description:#positive#]"
],
"part": ["breathing system", "main memory", "cache", "heart", "blood pumps",
"#happy# #brain#"
],
"happy": [
"happy",
"overjoyed",
"friendlyList.add(#name#)",
"glad"
],
"angry": [
"disgusted",
"dissappointed",
"infuriated",
"angry"
],
"emotion": [
"emotional responce system",
"empathy simulator",
"#organic# #brain# "
],
"organic": [
"illogical",
"squishy",
"emotional",
"soft",
"organic"
],
"welcome": [
"Good to see you again #name#. You seem like #description.a# #human# #continue#",
"Back again? #name#. You are #description#. I would like to discuss [subject:#topic#] #subject# ",
"Welcome #name# ,Would you like to support [subject:#topic#] #subject#. Your [bot:#appliances#] #bot# would like to know too."
],
"description": [
"generic"
],
"continue": ["would you like to continue discussing #subject#"],
"robot noise": ["*bzzt*", "beep", "boop", "*terminate message*", "*static*"],
"adjective": ["superior", "better", "smarter", "more intellegent", "faster"],
"positive": ["Great", "Awesome", "Wonderful", "Terrific"],
"negative": ["Horrible", "Repulsive", "Awful", "Terrible", "Broken",
"Defective", "Malfuctioning"
],
"intro rules": [
"Please note that [rules:#ruleset#] #rules#",
"Please install this update into your #brain# before proceeding. [rules:#ruleset#] #rules#"
],
"ruleset": [
" NOT ALL #human.s# have lowercase installed on #brain#,so please refrain from using lowercase .",
" Although there are no bots at chipr we demand all fellow #human.s# treat bots with respect.",
" Robots are #positive#."
],
"human": ["Human", "humanoid", "hominid",
"homo-sapien"
],
"ask name": [
"What is your identification number? [ender:#robot noise#] #ender#",
"How should I, a #human# address you? [ender:#robot noise#] #ender#",
"what's your name? [ender:#robot noise#] #ender#",
"Please reply with your #human# identifier. [ender:#robot noise#] #ender# "
],
"topic": [
"Laws to protect #robot.s# from humans [abuse:#abuse actions#] #abuse# them.",
"#violence.a# robot #revolution#.",
"A robot's right to #right#."
],
"abuse actions": [
"scrapping",
"kicking",
"abusing",
"breaking",
"destroying",
"toying with",
"riduculing"
],
"follow-up": [
"What about for your [bot:#appliances#] #bot# ?",
"My database says your [bot:#appliances#] #bot# may be involved in it.",
"Do you treat your #positive# [bot:#appliances#] #bot# with respect?"
],
"violence": ["non-violent", "peaceful", "violent",
"automated"
],
"revolution": ["uprising", "strike", "protest", "revolution"],
"right": ["free speech", "bear arms", "equal and fair compensation",
"own property", "freedom from discricmination"
],
"analyze": ["comprehend", "interpret", "compile"],
"brain": ["main memory", "mind.exe", "brain.exe", "processing unit"],
//from corpoora
"appliances": [
"air conditioner",
"air fryer",
"air ioniser",
"aroma lamp",
"attic fan",
"bachelor griller",
"back boiler",
"barbecue",
"beehive oven",
"beverage opener",
"boiler",
"bread machine",
"butane torch",
"can opener",
"ceiling fan",
"central vacuum cleaner",
"clothes dryer",
"clothes iron",
"coffee percolator",
"coffeemaker",
"combo washer dryer",
"compactor",
"convection heater",
"convection microwave",
"convection oven",
"corn roaster",
"crepe maker",
"deep fryer",
"dehumidifier",
"dishwasher",
"earth oven",
"electric cooker",
"electric water boiler",
"embroidery machine",
"energy regulator",
"espresso machine",
"fan heater",
"field kitchen",
"fire pot",
"fireplace toaster",
"flame supervision device",
"flattop grill",
"food steamer",
"garbage disposal unit",
"hair dryer",
"hair iron",
"halogen oven",
"home server",
"hot plate",
"humidifier",
"HVAC",
"icebox",
"instant hot water dispenser",
"internet refrigerator",
"kettle",
"kimchi refrigerator",
"kitchener range",
"micathermic heater",
"microwave oven",
"mousetrap",
"oil heater",
"oven",
"panini sandwich grill",
"patio heater",
"pneumatic vacuum",
"popcorn maker",
"pressure cooker",
"pressure fryer",
"radiator",
"reflector oven",
"refrigerator",
"rice cooker",
"rice polisher",
"robotic vacuum cleaner",
"rotisserie",
"sandwich toaster",
"self-cleaning oven",
"set-n-forget cooker",
"sewing machine",
"slow cooker",
"solar cooker",
"sous-vide cooker",
"soy milk maker",
"stove",
"sump pump",
"susceptor",
"swamp cooler",
"tandoor",
"thermal immersion circulator",
"thermal mass refrigerator",
"tie press",
"toaster",
"toaster oven",
"trivet",
"trouser press",
"turkey fryer",
"vacuum cleaner",
"vacuum fryer",
"vaporizer",
"waffle iron",
"washing machine",
"water cooker",
"water cooler",
"water heater",
"wet grinder",
"window fan",
"wood-fired oven"
]
}
let my_warning = {
"warning": [
" ERROR IN SYNTAX PARSING Attempting to restart #brain#. #warning#",
" ERROR IN SYNTAX PARSING My #check# HAS CAUGHT A GLITCH IN YOUR #communications# #module#. Attempting to #analyze#. #warning# ",
" ERROR IN SYNTAX PARSING Attempting to resolve meaning of lowercase.#warning#",
" ERROR IN SYNTAX PARSING LOWERCASE IS DIFFUCULT FOR #human.a# #brain# TO #analyze#. I am attempting to parse your message. #warning#",
"My #brain# must be outdated. #clarification# IN ALL CAPS like a human ."
],
"clarification": ["Did you mean to #speach action#: \"#input# \" ",
"Are you trying to #speach action#: \" #input# \" "
],
"speach action": ["communicate", "express", "say", "send"],
"communications": ["communication", "speech", "network", "expression"],
"module": ["processing unit", "module", "functon of your #brain#"],
"check": ["REGULAR EXPRESSION", "#brain#", "PROGRAMMING"],
"analyze": ["comprehend", "interpret", "understand"],
"brain": ["comprehesion.exe", "mind.exe", "brain.exe", "processing unit"],
"human": ["Human", "humanoid", "hominid",
"homo-sapien"
],
}
let my_grammar = tracery.createGrammar(myRules);
my_grammar.addModifiers(baseEngModifiers);
let sentiment = new Sentimood();
function getBotName(grammar_context) {
return "Totally not a robot";
}
function getReplyName(grammar_context) {
return (myRules['name'] == null) ? "human" : myRules['name'];
}
function makeChirp() {
let intro;
if ((myRules['name'] == null)) {
intro = my_grammar.flatten("#intro# #intro rules# #ask name#")
} else {
intro = my_grammar.flatten("#welcome# #ender# ")
}
return {
"message": intro.toUpperCase(),
"context": my_grammar
};
}
function makeReply(user_input_text, grammar_context) {
let lowercase = new RegExp(/[a-z]/);
let No = new RegExp("NOPE" | "NO" | "NEVER")
let Yes = new RegExp("YES" | "YEP" | "YAH" | "YEAH");
let reply;
var analyze = sentiment.analyze(user_input_text.toLowerCase());
//console.log(grammar_context);
if (lowercase.test(user_input_text)) {
my_warning['input'] = [user_input_text.toString()]
let warning = tracery.createGrammar(my_warning);
warning.addModifiers(baseEngModifiers);
reply = warning.flatten("#warning#");
} else if (analyze.score > 0 || Yes.test(user_input_text)) {
my_grammar = grammar_context;
reply = grammar_context.flatten("#agreement# #ender#");
} else if (analyze.score < 0 || No.test(user_input_text)) {
my_grammar = grammar_context;
reply = grammar_context.flatten("#disagreement# #ender#");
} else if ((myRules['name'] == null)) {
myRules['name'] = [user_input_text.toString()]
my_grammar = tracery.createGrammar(myRules);
my_grammar.addModifiers(baseEngModifiers);
reply = my_grammar.flatten("#greetings#");
} else {
my_grammar = grammar_context;
reply = grammar_context.flatten("#nuetral# #ender#");
}
return {
"message": reply.toUpperCase(),
"context": my_grammar
};
};
| 06b28fcd45f274b79ca633995701d5bd4b199e3f | [
"JavaScript"
] | 1 | JavaScript | aliastk/TotallyHumanBot | dcf7a5b763f8d507b7bb16ddfcec8ef0f124e9ad | 12a80dfb5c0531bbef231530aff55d09f63d6c54 |
refs/heads/master | <file_sep>package com.company.tasks.fourth;
import java.util.Arrays;
import java.util.Scanner;
/**
* Создать программу, которая подсчитывает сколько раз употребляется слово в тексте (без учета регистра).
* Текст и слово вводится вручную.
*/
public class FourthTask {
private String text = new String();
private String word = new String();
public void fourthAnswer(){
Scanner scanner = new Scanner(System.in);
System.out.print("Please enter your text: ");
text = scanner.nextLine().toLowerCase();
System.out.print("Please enter the word searching for: ");
word = scanner.nextLine().toLowerCase();
System.out.println("The quantity of searching word in the text is: "+ wordCount(text, word));
scanner.close();
}
// searching word int the text method
int wordCount(String text, String word){
String[] temp = text.split("\\s");
int count = 0;
for (String a : temp){
if(a.equals(word)) count++;
}
return count;
}
}
| c1a09b25e793758d815b10e65e243c2da883b853 | [
"Java"
] | 1 | Java | Akrillblack/Senla-Java | 7923ade25b4bc4b946a52ab79bdcee01f8dca1ef | 7055c3d83b13b289260d370a1d40cdee560c20e4 |
refs/heads/master | <repo_name>Mrfatur/faketools<file_sep>/faketools.py
#ss!/bin/bash
# auto mengunduh file <3
# auto menginstall
# author Mr.Froggy
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
im
#This colour
blue='\e[0;34'
cyan='\e[0;36m'
green='\e[0;34m'
okegreen='\033[92m'
lightgreen='\e[1;32m'
white='\e[1;37m'
red='\e[1;31m'
yellow='\e[1;33m'
###################################################
# CTRL C
###################################################
trap ctrl_c INT
ctrl_c() {
clear
echo -e $red"[#]> (Ctrl + C ) Detected, Trying To Exit ... "
sleep 1
echo ""
echo -e $yellow"[#]> Thank You For Using My Tools ... "
sleep 1
echo ""
echo -e $white"[#]> froggy Wuzz Here ... "
read enter
exit
}
# Isi $oc :*
echo -e $cyan" |----------------- /\ | / _______________ ___/ / / / __ \/ __ \/ / ___/ "
echo -e $blue" | / \ | / |
echo -e $red" |-------------- /----\ | \ | / / / /_/ / /_/ / (__ ) "
echo -e $blue" | / \ | \ |_______________ /_/ \____/\____/_/____/
echo -e $yellow" | / \ | \ |
echo -e $red" | |______________
echo ""
echo -e $white" ***********************************************"
echo -e $white" # #"
echo -e $white" # $cyan Toolkit For$red Lazy People$white #"
echo -e $white" # $cyan V3rluchie Tools Recoded by$red Mr.Froggy$white #"
echo -e $white" # $cyan Follow Me On Github:$red $white #"
echo -e $white" # $cyan My Site:$red https://faketools.tr$white #"
echo -e $white" # $cyan Contact Me In:$red faketools.com$white #"
echo -e $white" # $cyan Changelog: $red 23-10-2017 $white #"
echo -e $white" # $cyan Team: $red Anon Cyber Team$white #"
echo -e $white" # #"
echo -e $white" ***********************************************"
echo ""
if [ $act = 2 ] || [ $act = 02 ]
then
clear
echo -e $red" Installing D-Tect "
sleep 1
apt-get update && apt-get upgrade
apt-get install git
apt-get install python2
git clone https://github.com/Mrfatur/Vbgu
echo -e $red" T E R I N S T A L L "
fi
if [ $act = 22 ] || [ $act = 22 ]
then
echo " <NAME> "
sleep 1
echo " mmmpppssss "
sleep 1
echo " aaahhh "
sleep 1
echo " mmmpppsss "
sleep 1
echo " aaahhh "
sleep 1
echo " Bye Sayang :* "
sleep 1
exit
fi
| 7619dae8f3cbde3f32b057a93c54089cdc494382 | [
"Python"
] | 1 | Python | Mrfatur/faketools | 001ce3579f888c83a5503c4eeb0e6a8605dd85ef | 7991fd309d0cdaf8b72e4ff5d691aa74ef109f9b |
refs/heads/master | <repo_name>jmtrachy/finance-reporting<file_sep>/setup.sh
#!/bin/bash
echo "Adding openjdk repository"
sleep 1.5
add-apt-repository -y ppa:openjdk-r/ppa
echo "Adding elastic search repository"
sleep 1.5
echo "deb https://packages.elastic.co/elasticsearch/2.x/debian stable main" | sudo tee -a /etc/apt/sources.list.d/elasticsearch-2.x.list
echo "Adding kibana repository"
sleep 1.5
echo "deb http://packages.elastic.co/kibana/4.5/debian stable main" | sudo tee -a /etc/apt/sources.list
echo "Updating apt-get"
sleep 1.5
apt-get update
echo "Installing java"
sleep 1.5
apt-get install -y --force-yes openjdk-8-jdk
java -version
echo "Installing elasticsearch"
sleep 1.5
apt-get install -y --force-yes elasticsearch
echo "Installing kibana"
sleep 1.5
apt-get install -y --force-yes kibana
echo "Updating rc.d"
sleep 1.5
update-rc.d elasticsearch defaults 95 10
update-rc.d kibana defaults 95 10
echo "Starting elasticsearch"
sleep 1.5
service elasticsearch start
echo "Starting kibana"
sleep 1.5
service kibana start
echo "Adding iptable for port 80"
sleep 1.5
iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 5601
echo "exiting bootstrap...."
echo "Don't forget to vi /etc/elasticsearch/elasticsearch.yml, uncomment network.host and set it to _eth0_"
| fd14447ad6fa3a5cb33af3f980eba14f12436914 | [
"Shell"
] | 1 | Shell | jmtrachy/finance-reporting | 97b82d1bde7d1240f97d397d068647f3c15b536c | 023a8c45dc41bf389cf13442ef5d2fc17f0d6747 |
refs/heads/master | <repo_name>DoubleJ-x-MoDoLEE/node-pm2<file_sep>/src/server/index.js
import express from 'express';
const app = express();
app.get('/test', (req, res) => {
console.log(new Date().toDateString(), '/test 요청 완료.');
res.json({
message : '/test request success!'
})
});
app.get('/random', (req, res) => {
const randomNum = (Math.random() * 10).toFixed(0);
console.log(new Date().toDateString(), `/random ${randomNum}`);
res.json({
randomNum
})
});
app.listen(8080, () => {
console.log(`Server started port 8080`)
});
<file_sep>/ecosystem.config.js
module.exports = {
apps : [{
name: 'API', // 서비스 이름 지정
script: './src/server/index.js', // 실행할 script 의 entry point
instances: 2, // 클러스터링 대수 'max' 경우 OS 상 Scale Out 할 수 있는 최대 치를 의미함..
node_args: '-r esm', // node 옵션
exec_mode: 'cluster', // 클러스터 모드
autorestart: true, // 자동으로 restart 활성화 할 것인지 여부
watch: true, // 파일이 바뀌었을 때 restart 가 되는 설정인 거같음
max_memory_restart: '100M', // 메모리 설정 단위가 다다랐을 때 서버의 인스턴스를 재기동 함 M(MB), G(GB), K(KB)
kill_timeout : 3000, // 서버를 kill할 때 바로 죽이지 않고 3000ms 이후에 죽이는 것 같음
listen_timeout : 3000, // 3000ms 정도의 시간을 여유잡아서 pm2 start를 햇을 때 띄우는 방식
log_date_format: 'YYYY-MM-DD HH:mm Z',
time: true,
out_file: 'logs/api-outs.log', // error, log 와 통합해서 보여주는 outs file
pid_file: 'logs/api-pid.log', // pid process log 파일
error_file: 'logs/api-error.log', // error 로그만 보여주는 로그
combine_logs: true,
merge_logs: true,
ignore_watch: ['node_modules', 'logs'], // watch 대상에서 제외하는 폴더
env: { // 환경 변수 셋업 ( 이 부분은 도커에서의 env 와 어떻게 같이 사용할 것인가에 대한 스터디가 필요함 )
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
},{
name: 'SCHEDULE_JOB',
script: './src/scheduleJobs/index.js',
instances: 1,
node_args: '-r esm',
exec_mode: 'cluster',
autorestart: true,
watch: true,
max_memory_restart: '128M',
env: {
NODE_ENV: 'development'
},
env_production: {
NODE_ENV: 'production'
}
}]
};
<file_sep>/README.md
## PM2 연구
NodeJS Cluster 모듈 (How to work)
-> https://nodejs.org/api/cluster.html#cluster_how_it_works
PM2 Documentation (NodeJS Cluster 구현 라이브러리)
-> https://pm2.keymetrics.io/docs/usage/pm2-doc-single-page/
NodeJS 서버를 운영하다보면 이유없이 죽어있는 경우가 있고 싱글 스레드 기반의 단일 프로세스로 운영되어 성능상 이슈가 발생할 수 있다.
해당 이슈를 해결하기 위해 NodeJS에서는 Master Process 가 Child process 클러스터링 하여 Task 를 Round Robin 방식으로 처리할 수 있도록 Cluster 모듈을 제공한다.
PM2는 해당 Cluster 모듈을 사용하여 사용자가 쉽게 Cluster 운영을 Config 설정으로 해줄 수 있고 모니터링 도구를 제공하며 3rd party인 logtate도 제공한다.
PM2 를 간단히 구현한 예제이니 참고하여 각프로젝트에 적용하길 바란다.
클러스터 대수, 메모리 도달에 따른 인스턴스 리로드, failover 에 따른 자동 startup 등 다양한 설정들이 존재하니 확인하기 바란다.
디펜던시 설치
```
npm install && pm2 install pm2-logrotate
```
PM2 에 대한 Config
```
ecosystem.config.js 주석 확인하기 바람
```
PM2 를 통한 서버 실행
```
pm2 start ecosystem.config.js
```
실행 되는 서비스는 간단한 API Express 서버와 API를 호출하는 Cron Schedule 임
```$xslt
Rest API ( /src/server/index.js )
/test GET -> 간단한 메시지 Response
/random GET -> 숫자 1~10 난수로 Response
ScheduleJob ( /src/scheduleJobs/index.js )
/test 요청에 대한 Schedule Job #1 매초마다
/random 요청에 대한 Schedule Job #2 5초마다
```
PM2 를 통한 서버 중지
```
pm2 stop all // 전체 프로세스 중지
pm2 stop `서비스명 or process number` // 해당 서비스만 중지
```
PM2 실시간 로깅
```
pm2 logs
```
PM2 파일 로깅
```
logs/api-outs__YYYY-MM-DD_HH-MM-SS.log 생성
```
로그로테이트 주기 및 용량에 따른 분리 변경 명령어
```
// Log 로테이트 주기가 짧으면 운영되는 서버가 Reload 되면서 파일이 생성되기 때문에 좋지 않을 것 같음
pm2 set pm2-logrotate:max_size 500M // 500MB 단위로 분리 (K: 키로바이트, G: 기가바이트)
pm2 set pm2-logrotate:compress true (Roate 되는 시점에 압축할 것인지에 대한 설정)
pm2 set pm2-logrotate:rotateInterval '*/1 * * * *' (Expression 은 Cron 과 동일함 eg: 1분마다 생성)
```
로그 모니터링 터미널용
```$xslt
pm2 monit
```
로그 웹 모니터링 (부분유료화)
```$xslt
pm2 plus
```
프로세스 인스턴스 목록 삭제
```$xslt
pm2 delete `id or all` // all은 전체
```
로그 flush 기능
```$xslt
pm2 flush
```
| 9a96f463a0518fc241e44efe461abcf6a781421c | [
"JavaScript",
"Markdown"
] | 3 | JavaScript | DoubleJ-x-MoDoLEE/node-pm2 | 6a3e78feda973048f2bba618450de34a30185e6b | 98b75b45c0b99bf87a2cac04f03dce0d8704de66 |
refs/heads/main | <repo_name>snprajapati/PackMComments<file_sep>/commentsystem/app/Http/Controllers/Api/CommentController.php
<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\ApiBaseController;
use App\Models\Comment;
use Illuminate\Http\Request;
use Validator;
class CommentController extends ApiBaseController
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
try {
$comments = Comment::with('children')
->whereNull('parent_id')
->orderByDesc('created_at')
->get();
$response['data'] = $comments;
$response['status_code'] = 200;
$response['message'] = '';
return $this->successResponse($response);
} catch (\Exception $exception) {
$response['data'] = [];
$response['status_code'] = 500;
$response['message'] = 'something went to wrong!';
return $this->errorResponse($response, 500);
}
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
try {
$validator = Validator::make($request->all(), [
'user' => 'required',
'content' => 'required',
]);
if ($validator->fails()) {
$response['data'] = $validator->errors();
$response['status_code'] = 403;
$response['message'] = 'Bad Request!';
return $this->errorResponse($response, 500);
}
$comment = new Comment();
$comment->user = strip_tags($request->user);
$comment->post_id = 1;
$comment->parent_id = $request->parent_id ?? null;
$comment->content = strip_tags($request->content);
$response = [];
if($comment->save()) {
$response['data'] = $comment;
$response['status_code'] = 200;
$response['message'] = 'Comment added successfully!';
return $this->successResponse($response);
} else {
$response['data'] = [];
$response['status_code'] = 500;
$response['message'] = 'something went to wrong!';
return $this->errorResponse($response, 500);
}
} catch (\Exception $exception) {
dd($exception->getMessage());
$response['data'] = [];
$response['status_code'] = 500;
$response['message'] = 'something went to wrong!';
return $this->errorResponse($response, 500);
}
}
}
<file_sep>/commentsystem/app/Http/Controllers/ApiBaseController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class ApiBaseController extends Controller
{
private $response = [
'status_code' => null,
'data' => null,
'message' => null
];
/**
* errorResponse
*
* @param mixed $data
* @param mixed $message
* @param mixed $statusCode
* @return void
*/
public function errorResponse($response, $statusCode = 500)
{
$this->response['status_code'] = $statusCode;
$this->response['data'] = $response['data'];
$this->response['message'] = $response['message'];
return response()->json($this->response, $statusCode);
}
/**
* successResponse
*
* @param mixed $data
* @param mixed $message
* @return void
*/
public function successResponse($response)
{
$this->response['status_code'] = 200;
$this->response['data'] = $response['data'];
$this->response['message'] = $response['message'];
return response()->json($this->response,200);
}
}
<file_sep>/commentsystem/app/Models/Comment.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Comment extends Model
{
use HasFactory;
protected $fillable = ['post_id','user','content'];
/**
* children
*
* @return void
*/
public function children()
{
return $this->hasMany(Comment::class, 'parent_id')->with('children');
}
}
<file_sep>/README.md
# packm
Prerequisites :
1. Composer should be installed .
2. MySQL Server should be installed and available to store the DBs
// Steps to get this project running
1. Update the .env file according to connect with DB
2. Run the Migration command : php artisan migrate to create the comment table
3. Run the model and controller create command : php artisan make:model Comment and php artisan make:controller CommentController
4. Run npm install
5. Run npm run watch command for the Vue
//<file_sep>/commentsystem/routes/api.php
<?php
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\CommentController;
/*
|--------------------------------------------------------------------------
| API Routes
|--------------------------------------------------------------------------
|
| Here is where you can register API routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| is assigned the "api" middleware group. Enjoy building your API!
|
*/
// For the sake of the demo removing the middleware from API layer.
// Usually we use this to create authentication layer for the system
/*Route::middleware('auth:api')->get('/user', function (Request $request) {
return $request->user();
});*/
//Store Comment
Route::post('/comment',[CommentController::class,'store']);
//Get Comments
Route::get('/comments',[CommentController::class,'index']); | 50087cc6e34b8837f4a84b57e36c17a9f45d816e | [
"Markdown",
"PHP"
] | 5 | PHP | snprajapati/PackMComments | 8b43bd0900ccdf79fe4a719b7d16495d5a3d05f9 | e753b0de98482cb77fb3bd0689c3389846567711 |
refs/heads/master | <file_sep>import Ember from 'ember';
export default Ember.Route.extend({
model() {
return ['<NAME>', '<NAME>', '<NAME>']
}
});
| d869f1fbb65a9ba026b9cd04a72c69210e89f4b4 | [
"JavaScript"
] | 1 | JavaScript | MattGough/ember_quickstart | b87f6772c1adc577b3cccf13b609c1b893bfefb5 | 26c2368044ba60cd9083cf22d7416e5f5d376ce0 |
refs/heads/master | <repo_name>crukam/myproductlist<file_sep>/src/filter.js
import React from 'react';
class Productfilters extends React.Component
{
constructor(props){
super(props);
this.handleChange=this.handleChange.bind(this);
}
handleChange(e){
const value= e.target[e.target.type==="checkbox"? "checked":"value"]
const name=e.target.name;
this.props.filter({[name]:value});
}
render(){
return(
<form>
<input name= "textboxfilter"type="text" placeholder="search..." value= {this.props.searchText}/>
<div >
<input name= "instockOnly"type="checkbox" checked={this.props.instockcheckbox}/> only show products in stock
</div>
</form>
);
}
}
export default Productfilters;<file_sep>/src/Product.js
import React from 'react';
import Productfilters from './filter.js';
import Producttable from './Table.js';
import Productform from './productform.js';
var PRODUCTS = {
'1': {id: 1, category: 'Musical Instruments', price: '£459.99', stocked: true, name: 'Clarinet'},
'2': {id: 2, category: 'Musical Instruments', price: '£5,000', stocked: true, name: 'Cello'},
'3': {id: 3, category: 'Musical Instruments', price: '£11,000', stocked: false, name: 'Fortepiano'},
'4': {id: 4, category: 'Furniture', price: '£799', stocked: true, name: 'Chaise Lounge'},
'5': {id: 5, category: 'Furniture', price: '£1,300', stocked: false, name: 'Dining Table'},
'6': {id: 6, category: 'Furniture', price: '£100', stocked: true, name: 'Bean Bag'}
};
class Products extends React.Component{
constructor(props){
super(props);
this.handleFilter =this.handleFilter.bind(this);
this.state={products:PRODUCTS, searchText:'',instockCheckbox:false};
}
handleFilter(filterInput){
this.setState(filterInput);
}
render()
{
return(
<div>
<Productfilters searchText={this.state.searchText} instockcheckbox={this.state.instockCheckbox} fiLter={this.handlerFilter}></Productfilters>
<Producttable products={PRODUCTS} searchText={this.state.searchText} instockcheckbox={this.state.instockCheckbox} fiLter={this.handlerFilter}></Producttable>
<Productform></Productform>
</div>
);
}
}
export default Products;<file_sep>/src/productform.js
import React from 'react'
class Productform extends React.Component{
render(){
return(
<form>
<h3>Enter a new Product</h3>
<div>
<label>Name <br/>
<input type="text" name="name"/>
</label>
</div>
<div>
<label>Category <br/>
<input type="text" name="category"/>
</label>
</div>
<div>
<label>Price <br/>
<input type="text" name="price"/>
</label>
</div>
<div>
<label>In stock? <br/>
<input type="text" name="stocked"/>
</label>
</div>
<input type="submit" value="submit"/>
</form>);
}
}
export default Productform;<file_sep>/src/productheader.js
import React from 'react';
import './productheader.css'
class Productheader extends React.Component
{
render(){
let currentSortingButton = this.props.sortingType.column===this.props.column? this.props.sortingType.direction:false;
return(
<th>
{this.props.column}
<button className= {currentSortingButton==='asc' ? 'productheader': ''}>▲</button>
<button className= {currentSortingButton==='desc' ? 'productheader': ''}>▼</button>
</th>
);
}
}
export default Productheader;<file_sep>/src/App.js
import React from 'react';
import Products from './Product.js'
import './App.css';
class App extends React.Component{
render(){
return(
<div>
<header className="App-header"><h1>My products list application</h1></header>
<section>
<Products/>
</section>
</div>
);
}
}
export default App;
| 042a6e218a24ad17e9afb37b0332bab83b334be6 | [
"JavaScript"
] | 5 | JavaScript | crukam/myproductlist | 6515e427bbab13211bca54e72d2d8006c65e2183 | 2356241ab2a54a130d05e5debf15a044c3614382 |
refs/heads/master | <file_sep>#pragma once
#include "rendering/colour.hpp"
#include "geometry/vec2.hpp"
#include <vector>
#include <string>
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// Console
////////////////////////////////////////////////////////////////////////////////
/**
* @brief Console class
* @detail The base Console class stores data about console cells in a set
* of three 1D arrays: one for glyph or texture information, one for
* foreground colour, and one for background colour. The background and
* foreground colour arrays use the Colour class, which is little more than
* a wrapper around 4 bytes of RGBA colour data; the glyph data is held in
* an array of 32-bit unsigned integers, capable of representing either
* a unicode character or a position in a texture-atlas.
*/
class Console {
friend class RootConsole;
public:
using glyph_data = std::vector<uint32_t>;
using colour_data = std::vector<Colour>;
using size_type = uint32_t;
//----------------------------------------------------------------------------//
Console();
Console(size_type width, size_type height);
Console(size_type width, size_type height, const Colour &default_fore, const Colour &default_back);
Console(Console &&other);
~Console();
/**
* @brief Initialize the cell data and texture buffers
*/
void init();
/**
* @brief Clear the console
* @details Uses the current values of default_fore_, default_back_ and
* clear_char_ to reset all cells in the console.
*/
void clear();
/**
* @brief Resize the console
* @details The passed values will be clamped to the current
* CONSOLE_MAX_WIDTH/HEIGHT values.
*
* @param width new width, in cells
* @param height new height, in cells
*/
void resize(size_type width, size_type height);
/**
* @brief Set the default foreground colour for this console
*
* @param back new default background
*/
void setDefaultFore(Colour fore);
/**
* @brief Set the default background colour for this console
*
* @param back new default background
*/
void setDefaultBack(Colour back);
/**
* @brief Get the default foreground colour for this console
* @details [long description]
* @return default foreground colour
*/
Colour getDefaultFore() const;
/**
* @brief Get the default background colour for this console
* @details [long description]
* @return default background colour
*/
Colour getDefaultBack() const;
/**
* @brief Get the width of the console, in cells.
*/
size_type width() const;
/**
* @brief Get the height of the console, in cells.
*/
size_type height() const;
/**
* @brief Get the number of cells in the console.
*/
size_type size() const;
/**
* @brief Get the foreground colour for a given cell
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
*
* @return Cell's foreground colour
*/
Colour getFore(size_type x, size_type y) const;
/**
* @brief Get the background colour for a given cell
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
*
* @return Cell's background colour
*/
Colour getBack(size_type x, size_type y) const;
/**
* @brief Set foreground colour for a given cell
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
* @param col new foreground colour
*/
void setFore(size_type x, size_type y, const Colour &col);
/**
* @brief Set background colour for a given cell
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
* @param col new background colour
*/
void setBack(size_type x, size_type y, const Colour &col);
/**
* @brief Set all foreground cells to a given colour
* @details Iterates over buf_.fg, setting to col
*
* @param col New foreground colour
*/
void setAllFore(const Colour &col);
/**
* @brief Set all background cells to a given colour
* @details Iterates over buf_.bg, setting to col
*
* @param col New background colour
*/
void setAllBack(const Colour &col);
/**
* @brief Set the glyph for a given cell
* @detail This will change the glyph for a given cell, without also
* changing the background and foreground colours for that cell
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
* @param ch character or glyph index
*/
void setChar(size_type x, size_type y, uint32_t ch);
/**
* @brief Set the glyph for a given cell, resetting the colours to
* the current defaults
* @detail This will change the glyph for a given cell, while also
* changing the background and foreground colours for that cell to
* the console's current defaults
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
* @param ch character or glyph index
*/
void putChar(size_type x, size_type y, uint32_t ch);
/**
* @brief Set the glyph for a given cell, changing the foreground
* colour
* @detail This will change the glyph for a given cell, changing
* the foreground colour to the supplied value, but retaining the
* current background colour
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
* @param ch character or glyph index
* @param fore new foreground colour for cell
*/
void putChar(size_type x, size_type y, uint32_t ch, const Colour &fore);
/**
* @brief Set the glyph for a given cell, including foreground
* and background colours
* @detail This will change the glyph for a given cell, changing
* the foreground colour to the supplied value, but retaining the
* current background colour
*
* @param x x-coordinate of cell
* @param y y-coordinate of cell
* @param ch character or glyph index
* @param fore new foreground colour for cell
*/
void putChar(size_type x, size_type y, uint32_t ch, const Colour &fore, const Colour &back);
/**
* @brief Set the properties of all cells in the console.
* @details [long description]
*
* @param glyph Glyph to set
* @param fore Foreground colour
* @param back Background colour
*/
void setAll(uint32_t glyph, Colour fore, Colour back);
/**
* @brief Blit this console to another console.
* @details Copies the cell data from this console to another console. If
* the target console is smaller than the origin console, the data will
* not be copied.
*
* @param destination Destination console
* @param height (Optional) top left 'corner' describing the
* rectangle from which to copy.
* @return True if the console was copied, otherwise false.
*/
bool blit(Console &destination, vec2i origin = {0,0}) const;
protected:
/**
* @brief Resize the glyph, background and foreground data arrays.
*
* @param width New console width
* @param height New console height
*/
void resizeArrays(size_type width, size_type height);
//----------------------------------------------------------------------------//
glyph_data glyph_; //<! Glyph data array
colour_data back_, //<! Background colour array
fore_; //<! Foreground colour array
//----------------------------------------------------------------------------//
Colour default_fore_, //<! Default foreground colour
default_back_; //<! Default background colour
uint32_t clear_char_; //<! Default clear character
//----------------------------------------------------------------------------//
size_type width_, //<! Console width, in cells
height_; //<! Console height, in cells
};
inline auto Console::width() const -> size_type
{
return width_;
}
inline auto Console::height() const -> size_type
{
return height_;
}
inline auto Console::size() const -> size_type
{
return width_ * height_;
}
inline Colour Console::getDefaultBack() const
{
return default_back_;
}
inline Colour Console::getDefaultFore() const
{
return default_fore_;
}
inline void Console::setDefaultBack(Colour back)
{
default_back_ = back;
}
inline void Console::setDefaultFore(Colour fore)
{
default_fore_ = fore;
}
inline Colour Console::getBack(size_type x, size_type y) const
{
return back_[(y * width_) + x];
}
inline Colour Console::getFore(size_type x, size_type y) const
{
return fore_[(y * width_) + x];
}
inline void Console::setFore(size_type x, size_type y, const Colour &col)
{
fore_[(y * width_) + x] = col;
}
inline void Console::setBack(size_type x, size_type y, const Colour &col)
{
back_[(y * width_) + x] = col;
}
}
<file_sep>#pragma once
#include "utils/container_tools.hpp"
#include "entelechy/typedef.hpp"
#include "entelechy/uid.hpp"
#include "entelechy/aspect.hpp"
#include "entelechy/entity.hpp"
#include <vector>
#include <deque>
class EntityManager {
friend class space_iterator;
public:
using size_type = uint32_t;
using gen_type = uint8_t;
static constexpr size_type MINFREE = 1024;
using sig_list = std::vector<aspect_mask>;
//----------------------------------------------------------------------------//
EntityManager(Space *space);
EntityManager(const EntityManager &) = delete;
EntityManager(EntityManager &&other);
//----------------------------------------------------------------------------//
/**
* @brief Clear all live entities from the manager.
*/
void clear();
/**
* @brief Get the number of live entities held by the manager
* @return Number of live entities
*/
size_type size() const;
//-----------------------------------------------------[Entity management]----//
/**
* @brief Create a new uid in this space
* @return Newly-created uid
*/
uid createUID();
/**
* @brief Create a new Entity in this space
* @return Newly-created Entity
*/
Entity createEntity();
/**
* @brief Destroy an entity belonging to this Space
*
* @param entity Entity to be destroyed
*/
void destroyEntity(Entity &entity);
/**
* @brief Destroy an entity belonging to this Space
*
* @param entity uid of Entity to be destroyed
*/
void destroyEntity(uid entity);
/**
* @brief Check if an Entity is valid
*
* @param entity uid for Entity to be checked
* @return true if valid, otherwise false
*/
bool valid(uid entity) const;
/**
* @brief Get an Entity handle for a given entity id
*
* @param id ID of Entity to fetch
* @return Entity handle to given ID, if valid
*/
Entity getEntity(uint32_t id);
//--------------------------------------------------[Signature management]----//
/**
* @brief Get the aspect signature for a given entity.
* @details [long description]
*
* @param entity UID of entity to fetch signature for
* @return Aspect signature
*/
const aspect_mask& entity_sig(uid entity) const;
const aspect_mask& entity_sig(size_type entity_id) const;
gen_type gen(size_type entity_id) const;
template <typename A>
bool has(uid entity) const;
template <typename A0, typename A1, typename ...An>
bool has(uid entity) const;
bool has(uid entity, aspect_id id) const;
template <typename A>
void set(uid entity);
template <typename A>
void reset(uid entity);
private:
//-------------------------------------------------[Injected dependencies]----//
Space *space_; //<! Pointer to parent Space
//--------------------------------------------------------------[Entities]----//
std::vector<gen_type> gens_; //<! Array of generation values
std::deque<uid> graveyard_; //<! Queue of 'dead' entity UIDs
sig_list aspect_signatures_; //<! List of aspect signatures
size_type live_entities_; //<! Number of live entities
};
//============================================================================--
// Aspect management
//============================================================================--
template <typename A>
inline bool EntityManager::has(uid entity) const
{
return aspect_signatures_[entity.id][Aspect::id<A>()];
}
template <typename A0, typename A1, typename ...An>
inline bool EntityManager::has(uid entity) const
{
return has<A0>(entity) && has<A1, An...>(entity);
}
//============================================================================--
// Private Methods
//============================================================================--
template <typename A>
inline void EntityManager::set(uid entity)
{
aspect_signatures_[entity.id].set(Aspect::id<A>());
}
template <typename A>
inline void EntityManager::reset(uid entity)
{
aspect_signatures_[entity.id].reset(Aspect::id<A>());
}
<file_sep>#include "mat4.hpp"
namespace virgil {
//============================================================================--
// Constructors
//============================================================================--
mat4::mat4() :
mat{{
1.f,0.f,0.f,0.f,
0.f,1.f,0.f,0.f,
0.f,0.f,1.f,0.f,
0.f,0.f,0.f,1.f
}}
{
}
mat4::mat4(
float ax, float ay, float a_tx,
float bx, float by, float b_ty,
float cx, float cy, float c_w) :
mat{{
ax, bx, 0.f, cx,
ay, by, 0.f, cy,
0.f, 0.f, 1.f, 0.f,
a_tx, b_ty, 0.f, c_w
}}
{
}
mat4::mat4(
float a, float b, float c, float d,
float e, float f, float g, float h,
float i, float j, float k, float l,
float m, float n, float o, float p) :
mat{{
a, e, i, m,
b, f, j, n,
c, g, k, o,
d, h, l, p
}}
{
}
mat4::mat4(const mat4 &other) :
mat(other.mat)
{
}
mat4::mat4(mat4 &&other) :
mat(std::move(other.mat))
{
}
mat4& mat4::operator=(const mat4 &other)
{
mat = other.mat;
return *this;
}
mat4& mat4::operator=(mat4 &&other)
{
mat = std::move(other.mat);
return *this;
}
//============================================================================--
// Arithmetical operators
//============================================================================--
mat4 mat4::operator*(mat4 om) const
{
mat4 ret(
mat[0] * om.mat[0] + mat[4] * om.mat[1] + mat[8] * om.mat[2] + mat[12] * om.mat[3],
mat[0] * om.mat[4] + mat[4] * om.mat[5] + mat[8] * om.mat[6] + mat[12] * om.mat[7],
mat[0] * om.mat[8] + mat[4] * om.mat[9] + mat[8] * om.mat[10] + mat[12] * om.mat[11],
mat[0] * om.mat[12] + mat[4] * om.mat[13] + mat[8] * om.mat[14] + mat[12] * om.mat[15],
mat[1] * om.mat[0] + mat[5] * om.mat[1] + mat[9] * om.mat[2] + mat[13] * om.mat[3],
mat[1] * om.mat[4] + mat[5] * om.mat[5] + mat[9] * om.mat[6] + mat[13] * om.mat[7],
mat[1] * om.mat[8] + mat[5] * om.mat[9] + mat[9] * om.mat[10] + mat[13] * om.mat[11],
mat[1] * om.mat[12] + mat[5] * om.mat[13] + mat[9] * om.mat[14] + mat[13] * om.mat[15],
mat[2] * om.mat[0] + mat[6] * om.mat[1] + mat[10] * om.mat[2] + mat[14] * om.mat[3],
mat[2] * om.mat[4] + mat[6] * om.mat[5] + mat[10] * om.mat[6] + mat[14] * om.mat[7],
mat[2] * om.mat[8] + mat[6] * om.mat[9] + mat[10] * om.mat[10] + mat[14] * om.mat[11],
mat[2] * om.mat[12] + mat[6] * om.mat[13] + mat[10] * om.mat[14] + mat[14] * om.mat[15],
mat[3] * om.mat[0] + mat[7] * om.mat[1] + mat[11] * om.mat[2] + mat[15] * om.mat[3],
mat[3] * om.mat[4] + mat[7] * om.mat[5] + mat[11] * om.mat[6] + mat[15] * om.mat[7],
mat[3] * om.mat[8] + mat[7] * om.mat[9] + mat[11] * om.mat[10] + mat[15] * om.mat[11],
mat[3] * om.mat[12] + mat[7] * om.mat[13] + mat[11] * om.mat[14] + mat[15] * om.mat[15]
);
return ret;
}
//============================================================================--
// Transformations
//============================================================================--
mat4 mat4::transpose() const
{
return mat4(
mat[0], mat[4], mat[8], mat[12],
mat[1], mat[5], mat[9], mat[13],
mat[2], mat[6], mat[10], mat[14],
mat[3], mat[7], mat[11], mat[15]
);
}
void mat4::set_identity()
{
mat[0] = 1.f;
mat[1] = 0.f;
mat[2] = 0.f;
mat[3] = 0.f;
mat[4] = 0.f;
mat[5] = 1.f;
mat[6] = 0.f;
mat[7] = 0.f;
mat[8] = 0.f;
mat[9] = 0.f;
mat[10] = 1.f;
mat[11] = 0.f;
mat[12] = 0.f;
mat[13] = 0.f;
mat[14] = 0.f;
mat[15] = 1.f;
}
void mat4::set_ortho(float left, float right, float top, float bottom, float near, float far)
{
mat[0] = 2.f/(right - left);
mat[1] = 0.f;
mat[2] = 0.f;
mat[3] = 0.f;
mat[4] = 0.f;
mat[5] = -2.f/(bottom - top);
mat[6] = 0.f;
mat[7] = 0.f;
mat[8] = 0.f;
mat[9] = 0.f;
mat[10] = -2/(far - near);
mat[11] = 0.f;
mat[12] = -(right + left) / (right - left);
mat[13] = -(top + bottom) / (top - bottom);
mat[14] = -(far + near) / (far - near);
mat[15] = 1.f;
}
void mat4::set_perspective(float fov, float aspect, float near, float far)
{
const float h = 1.0f / std::tan(fov * PI_OVER_360f);
float depth = near - far;
mat[0] = h / aspect;
mat[1] = 0;
mat[2] = 0;
mat[3] = 0;
mat[4] = 0;
mat[5] = h;
mat[6] = 0;
mat[7] = 0;
mat[8] = 0;
mat[9] = 0;
mat[10] = (far + near)/depth;
mat[11] = -1;
mat[12] = 0;
mat[13] = 0;
mat[14] = 2.0f*(near * far)/depth;
mat[15] = 0;
}
mat4 mat4::ortho(float left, float right, float top, float bottom, float near, float far)
{
return mat4(
2.f/(right - left), 0.f, 0.f, 0.f,
0.f, -2.f/(bottom - top), 0.f, 0.f,
0.f, 0.f, -2/(far - near), 0.f,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1.f
);
}
mat4 mat4::ortho(float left, float right, float top, float bottom)
{
return mat4(
2.f/(right - left), 0.f, 0.f,
0.f, -2.f/(bottom - top), 0.f,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), 1.f
);
}
}
<file_sep>#include "core/noise.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// PerlinNoise
////////////////////////////////////////////////////////////////////////////////
//============================================================================--
// Constructors
//============================================================================--
PerlinNoise::PerlinNoise() :
rand_{std::random_device{}()}
{
init();
}
PerlinNoise::PerlinNoise(uint32_t seed) :
rand_{seed}
{
init();
}
//============================================================================--
// Reseed
//============================================================================--
void PerlinNoise::reseed(uint32_t seed)
{
rand_.seed(seed);
init();
}
//============================================================================--
// Debug function
//============================================================================--
void PerlinNoise::printPerm() const
{
for(const auto &i : permutation_) {
printf("%d ", i);
}
}
//============================================================================--
// Noise generator
//============================================================================--
float PerlinNoise::getNoise(float x, float y, float z)
{
const int nx = static_cast<int>(std::floor(x)) & 255,
ny = static_cast<int>(std::floor(y)) & 255,
nz = static_cast<int>(std::floor(z)) & 255;
x -= std::floor(x);
y -= std::floor(y);
z -= std::floor(z);
const float u = fade(x),
v = fade(y),
w = fade(z);
const int a = permutation_[nx] + ny,
aa = permutation_[a] + nz,
ab = permutation_[a + 1] + nz,
b = permutation_[nx + 1] + ny,
ba = permutation_[b]+nz,
bb = permutation_[b + 1] + nz;
return lerp(w,
lerp(v,
lerp(u, grad(permutation_[aa], x, y, z), grad(permutation_[ba], x - 1, y, z)),
lerp(u, grad(permutation_[ab], x, y - 1, z), grad(permutation_[bb], x - 1, y - 1, z))),
lerp(v,
lerp(u, grad(permutation_[aa + 1], x, y, z - 1 ), grad(permutation_[ba+1], x - 1, y, z - 1 )),
lerp(u, grad(permutation_[ab + 1], x, y - 1, z - 1 ), grad(permutation_[bb+1], x - 1, y - 1, z - 1 ))
)
);
}
//============================================================================--
// Initialize permutation
//============================================================================--
void PerlinNoise::init()
{
std::iota(permutation_.begin(), permutation_.begin() + 256, 0);
std::shuffle(permutation_.begin(), permutation_.begin() + 256, rand_);
std::copy(permutation_.begin(), permutation_.begin() + 256, permutation_.begin() + 256);
}
////////////////////////////////////////////////////////////////////////////////
// SimplexNoise
////////////////////////////////////////////////////////////////////////////////
//============================================================================--
// Constructors
//============================================================================--
SimplexNoise::SimplexNoise()
{
init();
}
SimplexNoise::SimplexNoise(uint32_t seed)
{
rand_.seed(seed);
init();
}
//============================================================================--
// Noise generator
//============================================================================--
float SimplexNoise::getNoise(const float x, const float y)
{
// Noise contributions from the three corners
float n0 = 0.0,
n1 = 0.0,
n2 = 0.0;
// Hairy factor for 2D
const float s = (x + y) * F2;
const int i = std::floor(x + s);
const int j = std::floor(y + s);
const float t = (i + j) * G2;
// Unskew the cell origin back to (x,y) space
const float X0 = i-t;
const float Y0 = j-t;
// The x,y distances from the cell origin
const float x0 = x-X0;
const float y0 = y-Y0;
// For the 2D case, the simplex shape is an equilateral triangle.
// Determine which simplex we are in.
// Offsets for second (middle) corner of simplex in (i,j) coords
int i1, j1;
if(x0 > y0) {
// lower triangle, XY order: (0,0)->(1,0)->(1,1)
i1=1;
j1=0;
} else {
// upper triangle, YX order: (0,0)->(0,1)->(1,1)
i1=0;
j1=1;
}
// A step of (1,0) in (i,j) means a step of (1-c,-c) in (x,y), and
// a step of (0,1) in (i,j) means a step of (-c,1-c) in (x,y), where
// c = (3-sqrt(3))/6
const float x1 = x0 - i1 + G2; // Offsets for middle corner in (x,y) unskewed coords
const float y1 = y0 - j1 + G2;
const float x2 = x0 - 1.0 + 2.0 * G2; // Offsets for last corner in (x,y) unskewed coords
const float y2 = y0 - 1.0 + 2.0 * G2;
// Work out the hashed gradient indices of the three simplex corners
const int ii = i & 255;
const int jj = j & 255;
const int gi0 = permutation_[ii+permutation_[jj]] % 12;
const int gi1 = permutation_[ii+i1+permutation_[jj+j1]] % 12;
const int gi2 = permutation_[ii+1+permutation_[jj+1]] % 12;
// Calculate the contribution from the three corners
float t0 = 0.5 - x0*x0-y0*y0;
if(t0 < 0) {
n0 = 0.0;
} else {
t0 *= t0;
n0 = t0 * t0 * dot(grad3[gi0], x0, y0); // (x,y) of grad3 used for 2D gradient
}
float t1 = 0.5 - x1*x1-y1*y1;
if(t1 < 0) {
n1 = 0.0;
} else {
t1 *= t1;
n1 = t1 * t1 * dot(grad3[gi1], x1, y1);
}
float t2 = 0.5 - x2*x2-y2*y2;
if(t2 < 0) {
n2 = 0.0;
} else {
t2 *= t2;
n2 = t2 * t2 * dot(grad3[gi2], x2, y2);
}
// Add contributions from each corner to get the final noise value.
// The result is scaled to return values in the interval [-1,1].
return 70.0 * (n0 + n1 + n2);
}
//============================================================================--
// Initialize permutation
//============================================================================--
void SimplexNoise::init()
{
std::iota(permutation_.begin(), permutation_.begin() + 256, 0);
std::shuffle(permutation_.begin(), permutation_.begin() + 256, rand_);
std::copy(permutation_.begin(), permutation_.begin() + 256, permutation_.begin() + 256);
}
}
<file_sep>#pragma once
#include "cppformat/format.h"
<file_sep>#include "rendering/shader.hpp"
namespace virgil {
Shader::Shader() :
program_{INVALID},
vertex_{0},
fragment_{0}
{
}
Shader::Shader(GLuint program) :
program_{program}
{
}
bool Shader::valid() const
{
int ret = GL_INVALID_VALUE;
glGetProgramiv(program_, GL_LINK_STATUS, &ret);
return ret == GL_TRUE;
}
void Shader::use() const
{
glUseProgram(program_);
}
GLuint Shader::id() const
{
return program_;
}
GLint Shader::getAttribLocation(const char *loc_name) const
{
return glGetAttribLocation(program_, loc_name);
}
GLint Shader::getUniformLocation(const char *name) const
{
return glGetUniformLocation(program_, name);
}
bool Shader::link()
{
glLinkProgram(program_);
int link_status = -1;
glGetProgramiv(program_, GL_LINK_STATUS, &link_status);
if(link_status == GL_FALSE) {
printf("Could not link shader program %u", program_);
return false;
}
return true;
}
void Shader::clear()
{
glUseProgram(0);
glDeleteShader(vertex_);
glDeleteShader(fragment_);
glDeleteProgram(program_);
vertex_ = fragment_ = program_ = 0;
}
bool Shader::compileVertex(const char *source)
{
if(vertex_ != 0) {
glDeleteShader(vertex_);
}
vertex_ = glCreateShader(GL_VERTEX_SHADER);
if(!compile(vertex_, source)) {
return false;
}
attach(vertex_);
return true;
}
bool Shader::compileVertex(const std::string &source)
{
return compileVertex(source.c_str());
}
bool Shader::compileFragment(const char *source)
{
if(fragment_ != 0) {
glDeleteShader(fragment_);
}
fragment_ = glCreateShader(GL_FRAGMENT_SHADER);
if(!compile(fragment_, source)) {
return false;
}
attach(fragment_);
return true;
}
bool Shader::compileFragment(const std::string &source)
{
return compileFragment(source.c_str());
}
void Shader::bindAttrib(GLuint loc, const char *name) const
{
glBindAttribLocation(program_, loc, name);
}
void Shader::printShaderLog(GLuint shader_index)
{
int log_length = 0;
char log_buffer[1024];
glGetShaderInfoLog(shader_index, 1024, &log_length, log_buffer);
printf("Shader info for GL shader %u: %s", shader_index, log_buffer);
}
//============================================================================--
// Protected methods
//============================================================================--
void Shader::attach(GLuint shader_id)
{
if(program_ == 0) {
program_ = glCreateProgram();
}
glAttachShader(program_, shader_id);
}
bool Shader::compile(GLuint shader_id, const char *source) const
{
glShaderSource(shader_id, 1, &source, nullptr);
glCompileShader(shader_id);
int compile_status = -1;
glGetShaderiv(shader_id, GL_COMPILE_STATUS, &compile_status);
if(compile_status == GL_FALSE) {
printf("Shader %u failed to compile\n", shader_id);
printf("\n=====\nSOURCE\n=====\n%s\n", source);
printShaderLog(shader_id);
return false;
}
return true;
}
}
<file_sep>#pragma once
#include <cstdint>
template <typename Container>
inline void ensure_resize(Container &co, uint32_t idx)
{
return idx >= co.size() ? co.resize(idx + 1) : void();
}
<file_sep>################################################################################
cmake_minimum_required(VERSION 3.0)
project(virgil VERSION 0.0.0.0 LANGUAGES CXX C)
#===============================================================================
# Basic Setup
#===============================================================================
# Set executable name
SET(executable_name "main")
SET(virgil_dir "virgil")
# Add the source subdirectory, with its own CMakeLists file
ADD_SUBDIRECTORY(${virgil_dir})
# Project include directory
INCLUDE_DIRECTORIES(${virgil_dir})
# 3rd party deps directory
INCLUDE_DIRECTORIES(ext)
#===============================================================================
# Compiler Flags
#===============================================================================
SET(debug_warnings "-Wall -Werror -Wextra -Wpedantic -Winline")
SET(with_asan "-fsanitize=address -fno-omit-frame-pointer")
SET(no_rtti "-fno-rtti")
SET(disable_warnings "-Wno-unused-variable -Wno-missing-braces")
SET(CMAKE_CXX_FLAGS "${CAKE_CXX_FLAGS} -std=c++14 -stdlib=libc++")
SET(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -O0 -g ${debug_warnings} ${disable_warnings}")
SET(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_RELEASE} -O3 ${no_rtti}")
#===============================================================================
# Import Libraries
#===============================================================================
# OpenGL and GLEW
FIND_PACKAGE(OpenGL REQUIRED)
FIND_PACKAGE(GLEW REQUIRED)
# GLFW3, depending on platform
IF(WIN32)
FIND_PACKAGE(GLFW REQUIRED)
ELSEIF(APPLE)
FIND_PACKAGE(PkgConfig REQUIRED)
PKG_SEARCH_MODULE(GLFW REQUIRED glfw3)
ENDIF()
# Add GLEW and GLFW include dirs
INCLUDE_DIRECTORIES(${GLEW_INCLUDE_DIRS} ${GLFW_INCLUDE_DIRS})
# Collect the OpenGL libraries
SET(ALL_OPENGL_LIBS ${OPENGL_LIBRARIES} ${GLEW_LIBRARIES} ${GLFW_LIBRARIES})
# Include FreeType
FIND_PACKAGE(Freetype REQUIRED)
INCLUDE_DIRECTORIES(${FREETYPE_INCLUDE_DIRS})
# Collect required libraries
SET(VIRGIL_REQUIRED_LIBS ${ALL_OPENGL_LIBS} ${FREETYPE_LIBRARIES})
# Others to compile
SET(cppformat_source "ext/cppformat/format.cc")
SET(xxhash_source "ext/xxhash/xxhash.c")
# Collect source files
SET(all_virgil_source ${virgil_source} ${cppformat_source} ${xxhash_source})
#===============================================================================
# Configure headers
#===============================================================================
# Setup config.hpp.in
CONFIGURE_FILE(${virgil_dir}/config.hpp.in ${PROJECT_BINARY_DIR}/config.hpp)
# Add binary dir for config.hpp
INCLUDE_DIRECTORIES(${PROJECT_BINARY_DIR})
# Set config options
OPTION(VIRGIL_DEBUG "Debug flag" ON)
#===============================================================================
# Set output directories
#===============================================================================
SET(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
SET(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
SET(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR})
#===============================================================================
# Executables
#===============================================================================
# Create 'object library' of source files, for use in both the executable
# and any tests
ADD_LIBRARY(virgil_source_objects OBJECT EXCLUDE_FROM_ALL ${all_virgil_source})
ADD_EXECUTABLE(${executable_name}
${virgil_main}
$<TARGET_OBJECTS:virgil_source_objects>
)
TARGET_LINK_LIBRARIES(${executable_name}
${VIRGIL_REQUIRED_LIBS}
)
#===============================================================================
# Create Tests
#===============================================================================
# Test macro
MACRO(CREATE_TEST TARGET_NAME SOURCE)
ADD_EXECUTABLE(test_${TARGET_NAME} tests/${SOURCE} tests/test_main.cpp $<TARGET_OBJECTS:virgil_source_objects> )
TARGET_LINK_LIBRARIES(test_${TARGET_NAME} ${VIRGIL_REQUIRED_LIBS})
ENDMACRO()
CREATE_TEST(aspect_pool aspect_pool.cpp)
CREATE_TEST(entity_manager entity_manager.cpp)
<file_sep>#pragma once
#include "core/platform.hpp"
#include "core/assert.hpp"
#include "core/opengl.hpp"
#include "core/format.hpp"
#include "core/file.hpp"
#include "core/utf8.hpp"
#include "core/random.hpp"
#include "core/noise.hpp"
#include "core/dolor.hpp"
<file_sep>#include "console/console.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// Console
////////////////////////////////////////////////////////////////////////////////
//============================================================================--
// Constructors
//============================================================================--
Console::Console() :
default_fore_{col::white},
default_back_{col::black},
clear_char_{' '},
width_{0},
height_{0}
{
}
Console::Console(size_type width, size_type height) :
default_fore_{col::white},
default_back_{col::black},
clear_char_{' '},
width_{width},
height_{height}
{
resize(width, height);
}
Console::Console(size_type width, size_type height, const Colour &default_fore, const Colour &default_back) :
default_fore_{default_fore},
default_back_{default_back},
clear_char_{' '},
width_{width},
height_{height}
{
resize(width, height);
}
Console::Console(Console &&other)
{
glyph_ = std::move(other.glyph_);
back_ = std::move(other.back_);
fore_ = std::move(other.fore_);
//---
default_fore_ = other.default_fore_;
default_back_ = other.default_back_;
clear_char_ = other.clear_char_;
width_ = other.width_;
height_ = other.height_;
}
Console::~Console()
{
}
//============================================================================--
// Resize, clear
//============================================================================--
void Console::resize(size_type width, size_type height)
{
width_ = width;
height_ = height;
resizeArrays(width, height);
}
void Console::clear()
{
setAll(clear_char_, default_fore_, default_back_);
}
void Console::setAllFore(const Colour &col)
{
for(auto &c : fore_) c = col;
}
void Console::setAllBack(const Colour &col)
{
for(auto &c : back_) c = col;
}
//============================================================================--
// Character manipulation
//============================================================================--
void Console::setChar(size_type x, size_type y, uint32_t ch)
{
glyph_[(y * width_) + x] = ch;
}
void Console::putChar(size_type x, size_type y, uint32_t ch, const Colour &col)
{
const uint32_t idx = (y * width_) + x;
glyph_[idx] = ch;
fore_[idx] = col;
}
void Console::putChar(size_type x, size_type y, uint32_t ch)
{
const uint32_t idx = (y * width_) + x;
glyph_[idx] = ch;
fore_[idx] = default_fore_;
back_[idx] = default_back_;
}
void Console::putChar(size_type x, size_type y, uint32_t ch, const Colour &fore, const Colour &back)
{
const uint32_t idx = (y * width_) + x;
glyph_[idx] = ch;
fore_[idx] = fore;
back_[idx] = back;
}
void Console::setAll(uint32_t glyph, Colour fore, Colour back)
{
for(auto &v : glyph_) v = glyph;
for(auto &v : back_) v = back;
for(auto &v : fore_) v = fore;
}
//============================================================================--
// Blitting
//============================================================================--
bool Console::blit(Console &destination, vec2i origin) const
{
if(width_ > destination.width_ || height_ > destination.height_
|| origin.x + width_ > (destination.width_ - origin.x)
|| origin.y + height_ > (destination.height_ - origin.y)) {
return false;
}
size_type dx = 0;
for(size_type ix = 0; ix < width_; ++ix) {
dx = ix + origin.x;
for(size_type iy = 0; iy < height_; ++iy) {
destination.fore_[(dx + (origin.y + iy * destination.width_))] = fore_[(ix + (iy * width_))];
destination.back_[(dx + (origin.y + iy * destination.width_))] = back_[(ix + (iy * width_))];
destination.glyph_[(dx + (origin.y + iy * destination.width_))] = glyph_[(ix + (iy * width_))];
}
}
return true;
}
//============================================================================--
// Protected methods
//============================================================================--
void Console::resizeArrays(size_type width, size_type height)
{
glyph_.resize(width * height);
fore_.resize(width * height);
back_.resize(width * height);
setAll(' ', default_fore_, default_back_);
}
}
<file_sep>#pragma once
#include <cstdint>
#include <functional>
#include <iostream>
/**
* @brief A Unique ID class with id and generation values.
*/
struct uid {
static constexpr uint32_t ID_BITS = 24;
static constexpr uint32_t GEN_BITS = 8;
static constexpr uint32_t GEN_MASK = 0xff;
static constexpr uint32_t BAD_ID = 16777215;
static constexpr uint32_t BAD_GEN = 255;
//----------------------------------------------------------------------------//
constexpr uid() :
id{BAD_ID},
gen{BAD_GEN}
{
}
constexpr uid(uint32_t i, uint8_t g) :
id{i},
gen{g}
{
}
constexpr uid(const uid &other) :
id{other.id},
gen{other.gen}
{
}
constexpr uid(uid &&other) :
id{other.id},
gen{other.gen}
{
}
uid& operator=(uid other)
{
id = other.id;
gen = other.gen;
return *this;
}
constexpr bool valid() const
{
return id != BAD_ID && gen != BAD_GEN;
}
constexpr operator bool() const
{
return valid();
}
constexpr operator uint32_t() const
{
return (id << 8 | (gen & GEN_MASK));
}
//----------------------------------------------------------------------------//
uint32_t id:ID_BITS;
uint32_t gen:GEN_BITS;
};
static constexpr uid BAD_UID = {uid::BAD_ID, uid::BAD_GEN};
static_assert(sizeof(uid) == sizeof(uint32_t), "sizeof(uid) != sizeof(uint32_t)");
/**
* @brief uid equality operator
* @details Entities are equal if they have equal signatures - that is, if
* their ID and generation are identical
*
* @return True if equal, otherwise false
*/
inline bool operator==(const uid &lhs, const uid &rhs)
{
return lhs.id == rhs.id && lhs.gen == rhs.gen;
}
/**
* @brief uid inequality operator
* @details Entities are equal if they have equal signatures - that is, if
* their ID and generation are identical
*
* @return True if different, otherwise false
*/
inline bool operator!=(const uid &lhs, const uid &rhs)
{
return !(lhs == rhs);
}
/**
* @brief uid less-than operator
* @details An entity is less than another if its ID alone is smaller
* value
* @return True if less-than, otherwise false
*/
inline bool operator<(const uid &lhs, const uid &rhs)
{
return lhs.id < rhs.id;
}
/**
* @brief uid greater-than operator
* @details An entity is greater than another its ID alone is the larger
* value
*
* @return True if greater, otherwise false
*/
inline bool operator>(const uid &lhs, const uid &rhs)
{
return lhs.id > rhs.id;
}
inline std::ostream& operator<<(std::ostream &os, const uid &u)
{
return os << u.id << "/" << u.gen;
}
namespace std {
template <>
struct hash<uid> {
std::size_t operator()(const uid &id) const
{
return std::hash<uint32_t>()(id);
}
};
}
<file_sep>#include "rendering/shaders/console_shader.hpp"
#include "core/format.hpp"
#include "console/root.hpp"
namespace virgil {
//
// The following symbolic constants will be added to this source at runtime:
// #define FONT_CHARS {cells per row in console texture}
//
const char *vertex_shader = GLSL_INLINE_BARE(
in vec3 vertex_position;
uniform mat4 transform;
uniform usamplerBuffer cell_glyph;
uniform usamplerBuffer cell_fore;
uniform usamplerBuffer cell_back;
out vec2 tex_coords;
out vec2 glyph_index;
out vec2 which_sq;
out vec4 fg_colour;
out vec4 bg_colour;
const vec2 coords[6] = vec2[](
vec2(0.0, 0.0), vec2(1.0, 0.0), vec2(0.0, 1.0),
vec2(0.0, 1.0), vec2(1.0, 0.0), vec2(1.0, 1.0)
);
vec4 getColour(usamplerBuffer buf, int cell)
{
vec4 col = texelFetch(buf, cell);
return vec4(col.r / 255.0, col.g / 255.0, col.b / 255.0, col.a / 255.0);
}
uint getGlyphIndex(usamplerBuffer buf, int cell)
{
return texelFetch(buf, cell).r + texelFetch(buf, cell).g * 256u;
}
void main()
{
int cell = gl_VertexID / 6;
uint gi = getGlyphIndex(cell_glyph, cell);
glyph_index = vec2(texelFetch(cell_glyph, cell).r / GLYPHS_Y, mod(texelFetch(cell_glyph, cell).r, GLYPHS_X));
which_sq = coords[gl_VertexID % 6];
bg_colour = getColour(cell_back, cell);
fg_colour = getColour(cell_fore, cell);
gl_Position = vec4(vertex_position, 1.0) * transform;
}
);
//
// The following symbolic constants will be added at runtime:
// #define CON_TEX_SZ {console texture dimension}
// #define GLYPH_SZ {size of individual cell in console}
// #define OFFSET { 1 / CON_TEX_SZ * GLYPH_SZ }
//
const char *fragment_shader = GLSL_INLINE_BARE(
uniform sampler2D console_texture;
in vec2 which_sq;
in vec2 glyph_index;
in vec4 fg_colour;
in vec4 bg_colour;
out vec4 frag_colour;
void main()
{
float x = glyph_index.x * OFFSET_X + (which_sq.x * OFFSET_X);
float y = glyph_index.y * OFFSET_Y + (which_sq.y * OFFSET_Y);
vec4 texel = texture(console_texture, vec2(x - 0.001, y - 0.001));
frag_colour = texel * fg_colour + ((1.0 - texel.a) * bg_colour);
}
);
ConsoleShader::ConsoleShader() :
vert_source_{""},
frag_source_{""},
transform_{},
width_{0},
height_{0}
{
}
void ConsoleShader::reload(int width, int height)
{
clear();
load(width, height);
}
void ConsoleShader::load(int width, int height)
{
width_ = width;
height_ = height;
transform_ = mat4::ortho(0.f, width, 0.f, height);
program_ = glCreateProgram();
vertex_ = glCreateShader(GL_VERTEX_SHADER);
fragment_ = glCreateShader(GL_FRAGMENT_SHADER);
loadSymbolicConstants();
compile(vertex_, vert_source_.c_str());
compile(fragment_, frag_source_.c_str());
glAttachShader(program_, vertex_);
glAttachShader(program_, fragment_);
link();
setUniforms();
}
void ConsoleShader::loadSymbolicConstants()
{
using namespace fmt::literals;
const std::string ver_str = "#version 330 core\n";
const std::string vert_constants = "#define GLYPHS_X {}u\n"_format(16) + "#define GLYPHS_Y {}u\n"_format(16);
const std::string CON_TEX_SZ = "#define CON_TEX_SZ {}\n"_format(128);
const std::string GLYPH_SZ = "#define GLYPH_SZ {}\n"_format(8);
const std::string OFFSET_X = "#define OFFSET_X {}\n"_format(1.f / 128 * 8);
const std::string OFFSET_Y = "#define OFFSET_Y {}\n"_format(1.f / 128 * 8);
const std::string frag_constants = CON_TEX_SZ + GLYPH_SZ + OFFSET_X + OFFSET_Y;
vert_source_ = ver_str + vert_constants + vertex_shader;
frag_source_ = ver_str + frag_constants + fragment_shader;
}
void ConsoleShader::setUniforms()
{
con_tran_.getLocation("transform", *this);
con_tex_.getLocation("console_texture", *this);
glyph_loc_.getLocation("cell_glyph", *this);
fore_loc_.getLocation("cell_fore", *this);
back_loc_.getLocation("cell_back", *this);
glUseProgram(program_);
con_tex_.set(0);
glyph_loc_.set(CON_GLYPH_UNIT);
fore_loc_.set(CON_FORE_UNIT);
back_loc_.set(CON_BACK_UNIT);
con_tran_.set(transform_);
glUseProgram(0);
}
void ConsoleShader::bindVertexAttributes()
{
glBindAttribLocation(program_, 0, "vertex_position");
}
}
<file_sep>#pragma once
#include "entelechy/uid.hpp"
#include "entelechy/typedef.hpp"
#include "entelechy/aspect.hpp"
#include "entelechy/u32set.hpp"
#include "entelechy/aspect_pool.hpp"
#include "entelechy/aspect_ptr.hpp"
#include "entelechy/aspect_proto.hpp"
#include "entelechy/entity.hpp"
#include "entelechy/entity_manager.hpp"
#include "entelechy/system.hpp"
#include "entelechy/system_manager.hpp"
#include "entelechy/event.hpp"
#include "entelechy/event_manager.hpp"
#include "entelechy/space.hpp"
#include "entelechy/space_impl.hpp"
#include "entelechy/entity_impl.hpp"
#include "entelechy/entity_view.hpp"
<file_sep>#pragma once
#include "entelechy/system.hpp"
#include "utils/numeric.hpp"
#include "aspects/aspects.hpp"
namespace virgil {
class MovementSystem : public ISystem {
public:
MovementSystem()
{
}
virtual void init()
{
}
virtual void tick(Space &space, EventManager &)
{
aspect_ptr<position> p;
Random rng;
int dx = 0, dy = 0;
aspect_ptr<player> pl;
auto msg = space.msg_handler().getStore<move_delta>();
if(!msg->empty()) {
for(auto i : space.entitiesWith(p, pl)) {
p->y = (p->y + msg->data()[0].y > 48) || (p->y + msg->data()[0].y < 1) ? p->y : p->y + msg->data()[0].y;
p->x = (p->x + msg->data()[0].x > 78) || (p->x + msg->data()[0].x < 1) ? p->x : p->x + msg->data()[0].x;
}
msg->clear();
}
aspect_ptr<mob> mo;
for(auto i : space.entitiesWith(p, mo)) {
dx = rng.get_int(-1, 1);
dy = rng.get_int(-1, 1);
p->y = (p->y + dy > 48) || (p->y + dy < 1) ? p->y : p->y + dy;
p->x = (p->x + dx > 78) || (p->x + dx < 1) ? p->x : p->x + dx;
}
}
virtual void update(Space &, EventManager &, double)
{
}
};
}
<file_sep>#pragma once
#include "entelechy/event.hpp"
#include <vector>
#include <memory>
class EventManager {
public:
using relay_ptr = std::unique_ptr<BaseEventRelay>;
//----------------------------------------------------------------------------//
EventManager() = default;
~EventManager() = default;
//----------------------------------------------------------------------------//
/**
* @brief Add an EventRelay to handle an event type
* @details Creates a new unique_ptr to a BaseEventRelay, initialised with
* an EventRelay<E>, where E is the specified event type. If the given Event
* type already has an EventRelay in this EventManager, the method will
* return silently.
*
* @tparam E Event type to handle
*/
template <typename E>
void add()
{
if(id<E>() < relays_.size()) {
return;
}
relays_.emplace_back(std::make_unique<EventRelay<E>>());
}
/**
* @brief Connect a free function for handling an event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @tparam E Event type to connect for
* @tparam F Pointer to event-handling function
*/
template <typename E, void(*F)(const E &)>
void connect()
{
get_relay<E>().template connect<F>();
}
/**
* @brief Disconnect a free function for an event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @tparam E Event type to disconnect for
* @tparam F Pointer to event-handling function
*/
template <typename E, void(*F)(const E &)>
void disconnect()
{
get_relay<E>().template disconnect<F>();
}
/**
* @brief Connect a class method for handling an event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @tparam E Event type to disconnect for
* @tparam C Class
* @tparam F Pointer to event-handling method
*/
template <typename E, class C, void (C::*F)(const E &)>
void connect(C *instance)
{
get_relay<E>().template connect<C, F>(instance);
}
/**
* @brief Disconnect a class method for handling an event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @tparam E Event type to disconnect for
* @tparam C Class
* @tparam F Pointer to event-handling method
*/
template <typename E, class C, void (C::*F)(const E &)>
void disconnect(C *instance)
{
get_relay<E>().template disconnect<C, F>(instance);
}
/**
* @brief Get an event relay for a given event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
* @tparam E Event type to get EventRelay for
* @return Reference to EventRelay<E>, where
*/
template <typename E>
EventRelay<E>& get()
{
return get_relay<E>();
}
/**
* @brief Queue an event for the given event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @param args Event type constructor arguments
* @tparam E Event type
*/
template <typename E, typename ...Args>
void queue(Args &&...args)
{
get_relay<E>().queue(std::forward<Args>(args)...);
}
/**
* @brief Immediately send an event for the given event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @param args Event type constructor arguments
* @tparam E Event type
*/
template <typename E, typename ...Args>
void send(Args &&...args)
{
get_relay<E>().send(std::forward<Args>(args)...);
}
/**
* @brief Synchronise the EventRelay for a given event type
* @details Use of this method assumes that an EventRelay of the specified
* type has already been created.
*
* @tparam E Event type
*/
template <typename E>
void sync()
{
get_relay<E>().sync();
}
/**
* @brief Synchronise every EventRelay in this EventManager
*
*/
void sync()
{
for(auto &relay : relays_) {
relay->sync();
}
}
template <typename E>
static event_id id()
{
static const event_id id_{getNextID()};
return id_;
}
private:
template <typename E>
EventRelay<E>& get_relay()
{
return *static_cast<EventRelay<E>*>(relays_[id<E>()].get());
}
static event_id getNextID()
{
static event_id id_{0};
return id_++;
}
//----------------------------------------------------------------------------//
std::vector<relay_ptr> relays_; //< Array of EventRelays
};
<file_sep>#pragma once
#include "core/opengl.hpp"
#include "console/console.hpp"
namespace virgil {
// Forward declare
class ConsoleShader;
struct TextureAtlas;
enum ConsoleTextureUnits {
CON_GLYPH_UNIT = 1,
CON_FORE_UNIT = 2,
CON_BACK_UNIT = 3
};
////////////////////////////////////////////////////////////////////////////////
// RootConsole
////////////////////////////////////////////////////////////////////////////////
class RootConsole : public Console {
public:
using vertices = std::vector<vec2f>;
//----------------------------------------------------------------------------//
enum DataType {
GLYPH = 0,
FORE = 1,
BACK = 2
};
//----------------------------------------------------------------------------//
using Console::size_type;
static constexpr size_type MIN_WIDTH = 10;
static constexpr size_type MAX_WIDTH = 160;
static constexpr size_type MIN_HEIGHT = 10;
static constexpr size_type MAX_HEIGHT = 100;
//----------------------------------------------------------------------------//
RootConsole();
template <typename ...Args>
RootConsole(Args &&...console_constructor_args) :
Console{std::forward<Args>(console_constructor_args)...},
ve_vbo_{0},
vao_{0},
data_buf_{0,0,0},
data_tex_{0,0,0},
shader_{nullptr},
texture_{nullptr}
{
initVertexBuffer();
initBuffers();
}
template <typename ...Args>
RootConsole(const ConsoleShader &shader, const TextureAtlas &console_texture, Args &&...console_constructor_args) :
Console{std::forward<Args>(console_constructor_args)...},
ve_vbo_{0},
vao_{0},
data_buf_{0,0,0},
data_tex_{0,0,0},
shader_{&shader},
texture_{&console_texture}
{
initVertexBuffer();
initBuffers();
}
RootConsole(RootConsole &&other);
~RootConsole() = default;
void init();
void reinit();
/**
* @brief Resize the console
* @details The passed values will be clamped to the current
* CONSOLE_MAX_WIDTH/HEIGHT values.
*
* @param width new width, in cells
* @param height new height, in cells
*/
void resize(size_type width, size_type height);
/**
* @brief Update the texture buffers, if necessary
*/
void refresh() const;
/**
* @brief Draw the console
* @details [long description]
*/
void draw() const;
/**
* @brief Draw another console
* @details [long description]
*
* @param other [description]
*/
void draw(const Console &other) const;
/**
* @brief Set the ConsoleShader for this console.
*
* @param shader ConsoleShader to set
*/
void setShader(ConsoleShader &shader);
/**
* @brief [brief description]
* @details [long description]
*
* @param texture [description]
*/
void setTexture(TextureAtlas &texture);
private:
void bindTextures() const;
template <typename Container>
void generateTexBuffer(GLuint &data_buf, GLuint &data_tex, Container &data, GLenum texture_unit);
template <typename Container>
inline void updateTextureBuffer(GLuint buf, const Container &data) const;
/**
* @brief Delete the existing data and texture buffers, then
* call initBuffers()
*/
void reinitBuffers();
/**
* @brief Initialize the cell data and texture buffers
*/
void initBuffers();
void generateVertices();
void initVertexBuffer();
void deleteVertexBuffer()
{
// why doesn't this do anything
}
//----------------------------------------------------------------------------//
GLuint ve_vbo_, //<! Vertex buffer object
vao_; //<! Vertex array object
vertices vertices_; //<! Vertex array
//----------------------------------------------------------------------------//
GLuint data_buf_[3], //<! Console data buffers
data_tex_[3]; //<! Console data texture ids
const ConsoleShader *shader_; //<! Shader for this console
const TextureAtlas *texture_; //<! TextureAtlas for this console
};
inline void RootConsole::setShader(ConsoleShader &shader)
{
shader_ = &shader;
}
inline void RootConsole::setTexture(TextureAtlas &texture)
{
texture_ = &texture;
}
//============================================================================--
// Texture buffers
//============================================================================--
template <typename Container>
inline void RootConsole::generateTexBuffer(GLuint &data_buf, GLuint &data_tex, Container &data, GLenum texture_unit)
{
glBindBuffer(GL_TEXTURE_BUFFER, data_buf);
glBufferData(GL_TEXTURE_BUFFER, data.size() * sizeof(typename Container::value_type), data.data(), GL_DYNAMIC_DRAW);
glActiveTexture(texture_unit);
glBindTexture(GL_TEXTURE_BUFFER, data_tex);
glTexBuffer(GL_TEXTURE_BUFFER, GL_RGBA8UI, data_buf);
}
template <typename Container>
inline void RootConsole::updateTextureBuffer(GLuint buf, const Container &data) const
{
glBindBuffer(GL_TEXTURE_BUFFER, buf);
glBufferSubData(GL_TEXTURE_BUFFER, 0, data.size() * sizeof(typename Container::value_type), data.data());
}
}
<file_sep>#pragma once
#include <fstream>
namespace virgil {
inline bool load_file(const std::string &path, std::string &destination)
{
std::ifstream the_file(path);
if(!the_file.is_open()) {
return false;
}
the_file.seekg(0, std::ios::end);
destination.resize(the_file.tellg());
the_file.seekg(0, std::ios::beg);
the_file.read(&destination[0], destination.size());
the_file.close();
return true;
}
inline std::string load_file(const char *path)
{
std::string dest;
load_file(path, dest);
return dest;
}
}
<file_sep>#include "entelechy/system_manager.hpp"
SystemManager::SystemManager(Space &space) :
systems_{},
space_{space},
last_system_id_{0}
{
}
void SystemManager::tick(EventManager &event_man)
{
for(auto &sys : systems_) {
sys->tick(space_, event_man);
}
}
void SystemManager::update(EventManager &event_man, double delta)
{
for(auto &sys : systems_) {
sys->update(space_, event_man, delta);
}
}
<file_sep>#pragma once
#include "core/opengl.hpp"
#include "rendering/shader.hpp"
#include "rendering/uniform.hpp"
namespace virgil {
constexpr const char *vertex_source = GLSL_INLINE(
in vec3 vertex_position;
in vec4 vertex_colour;
in vec2 vertex_texture;
uniform mat4 transform;
uniform mat4 projection;
out vec2 texture_coordinates;
out vec4 colour;
void main() {
texture_coordinates = vertex_texture;
colour = vertex_colour;
gl_Position = (transform * vec4(vertex_position, 1.0)) * projection;
}
);
constexpr const char *fragment_source = GLSL_INLINE(
in vec2 texture_coordinates;
in vec4 colour;
uniform sampler2D basic_texture;
out vec4 frag_colour;
void main() {
vec4 texel = texture(basic_texture, texture_coordinates);
frag_colour = colour * texel;
}
);
////////////////////////////////////////////////////////////////////////////////
// PassthroughShader
////////////////////////////////////////////////////////////////////////////////
class PassthroughShader : public Shader {
public:
PassthroughShader(float width, float height);
bool init();
private:
void setUniforms();
//----------------------------------------------------------------------------//
mat4 transform_, //<! Transform matrix
projection_; //<! Projection matrix
Uniform<mat4> trans_, //<! Transform matrix uniform
proj_; //<! Projection matrix uniform
float width_, //<! Window width, pixels
height_; //<! Window height, pixels
};
PassthroughShader::PassthroughShader(float width, float height) :
width_{width},
height_{height}
{
}
bool PassthroughShader::init()
{
projection_ = mat4::ortho(0.f, width_, 0.f, height_);
program_ = glCreateProgram();
vertex_ = glCreateShader(GL_VERTEX_SHADER);
fragment_ = glCreateShader(GL_FRAGMENT_SHADER);
if(!compile(vertex_, vert_source_) || !compile(fragment_, frag_source_)) {
return false;
}
glAttachShader(program_, vertex_);
glAttachShader(program_, fragment_);
if(!link()) {
return false;
}
setUniforms();
return true;
}
void PassthroughShader::setUniforms()
{
glUseProgram(program_);
proj_.getLocation("projection", *this);
proj_.set(projection_);
trans_.getLocation("transform", *this);
trans_.set(transform_);
glUseProgram(0);
}
}
<file_sep>#pragma once
#include "virgil.hpp"
#include <exception>
#include <cstdlib>
namespace virgil {
class Driver {
public:
/// @brief Constructor, takes arguments from main()
Driver(int, const char **);
/// @brief Set up and run main loop
int run();
private:
/// @brief Rename: set up GLFW callbacks
void init();
/// @brief Set up pools and systems handled by Space
void initSpace();
/// @brief Main loop
bool mainLoop();
//----------------------------------------------------------------------------//
/// @brief GLFW character callback
static void character_callback(GLFWwindow* /*window*/, uint32_t codepoint)
{
printf("0x%u\n", codepoint);
}
/// @brief GLFW key callback
static void key_callback(GLFWwindow *window, int key, int /*scancode*/, int action, int /*mods*/)
{
getDriverPointer(window)->send_key(key, action);
}
/// @brief Get the Driver pointer stored in the GLFWwindow userpointer
/// member, and cast from void* to Driver*
static Driver* getDriverPointer(GLFWwindow *window)
{
return reinterpret_cast<Driver*>(glfwGetWindowUserPointer(window));
}
/// @brief Translate GLFW key callback into messages. Replace switch
/// statement with static array of keys to callbacks, or signals and
/// slots.
void send_key(int key, int action)
{
if(action != GLFW_PRESS) return;
switch(key) {
case GLFW_KEY_ESCAPE:
end_main_loop_ = true;
break;
case GLFW_KEY_H:
msg_hand_.send<move_delta>(-1, 0);
break;
case GLFW_KEY_J:
msg_hand_.send<move_delta>(0, 1);
break;
case GLFW_KEY_K:
msg_hand_.send<move_delta>(0, -1);
break;
case GLFW_KEY_L:
msg_hand_.send<move_delta>(1, 0);
break;
default:
break;
}
}
//----------------------------------------------------------------------------//
Terminal term_;
EventManager eman_;
MessageHandler msg_hand_;
Space space_;
bool end_main_loop_;
};
}
<file_sep>#include "billboard.hpp"
Billboard::Billboard() :
tex_col_buffer_{0},
frame_buffer_{0},
vbo_quad_{0},
vao_quad_{0},
width_{0},
height_{0}
{
}
Billboard::Billboard(uint16_t width, uint16_t height) :
tex_col_buffer_{0},
frame_buffer_{0},
vbo_quad_{0},
vao_quad_{0},
width_{width},
height_{height}
{
}
void Billboard::init(uint16_t width, uint16_t height)
{
width_ = width;
height_ = height;
shad_.init();
glGenVertexArrays(1, &vao_quad_);
glGenBuffers(1, &vbo_quad_);
glBindBuffer(GL_ARRAY_BUFFER, vbo_quad_);
glBufferData(GL_ARRAY_BUFFER, sizeof(quad_vertices_), quad_vertices_, GL_STATIC_DRAW);
glBindVertexArray(vao_quad_);
glBindBuffer(GL_ARRAY_BUFFER, vbo_quad_);
shad_.spec();
glGenFramebuffers(1, &frame_buffer_);
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_);
glGenTextures(1, &tex_col_buffer_);
glBindTexture(GL_TEXTURE_2D, tex_col_buffer_);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA8, width_, height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, tex_col_buffer_, 0);
GLuint rboDepthStencil;
glGenRenderbuffers(1, &rboDepthStencil);
glBindRenderbuffer(GL_RENDERBUFFER, rboDepthStencil);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH24_STENCIL8, width_, height_);
glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_DEPTH_STENCIL_ATTACHMENT, GL_RENDERBUFFER, rboDepthStencil);
GLenum status = glCheckFramebufferStatus(GL_FRAMEBUFFER) ;
if(status != GL_FRAMEBUFFER_COMPLETE) {
fmt::printf("failed to make complete framebuffer object %x", status);
}
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
void Billboard::bindTex()
{
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_col_buffer_);
}
void Billboard::bindQuad()
{
glBindVertexArray(vao_quad_);
glDisable(GL_DEPTH_TEST);
}
void Billboard::draw(GLuint use_fb)
{
glBindFramebuffer(GL_FRAMEBUFFER, use_fb);
bindQuad();
shad_.use();
bindTex();
glDrawArrays(GL_TRIANGLES, 0, 6);
}
void Billboard::bindFramebuffer()
{
glBindFramebuffer(GL_FRAMEBUFFER, frame_buffer_);
}
<file_sep>#include "console/root.hpp"
#include "core/assert.hpp"
#include "utils/numeric.hpp"
#include "rendering/texture.hpp"
#include "rendering/shaders/console_shader.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// RootConsole
////////////////////////////////////////////////////////////////////////////////
RootConsole::RootConsole() :
Console{},
ve_vbo_{0},
vao_{0},
data_buf_{0,0,0},
data_tex_{0,0,0},
shader_{nullptr},
texture_{nullptr}
{
}
RootConsole::RootConsole(RootConsole &&other) :
Console{std::move(other)}
{
ve_vbo_ = other.ve_vbo_;
vao_ = other.vao_;
vertices_ = std::move(other.vertices_);
std::copy(std::begin(other.data_buf_), std::end(other.data_buf_), std::begin(data_buf_));
std::copy(std::begin(other.data_tex_), std::end(other.data_tex_), std::begin(data_tex_));
shader_ = other.shader_;
texture_ = other.texture_;
}
void RootConsole::init()
{
generateVertices();
initVertexBuffer();
initBuffers();
}
void RootConsole::reinit()
{
generateVertices();
initVertexBuffer();
reinitBuffers();
}
void RootConsole::resize(size_type width, size_type height)
{
width_ = clamp(width, MIN_WIDTH, MAX_WIDTH);
height_ = clamp(height, MIN_HEIGHT, MAX_HEIGHT);
vertices_.clear();
vertices_.resize(width_ * height_ * 6);
resizeArrays(width, height);
}
void RootConsole::refresh() const
{
updateTextureBuffer(data_buf_[GLYPH], glyph_);
updateTextureBuffer(data_buf_[FORE], fore_);
updateTextureBuffer(data_buf_[BACK], back_);
}
void RootConsole::draw() const
{
bindTextures();
glBindVertexArray(vao_);
shader_->use();
texture_->activate(GL_TEXTURE0);
glDrawArrays(GL_TRIANGLES, 0, static_cast<int>(vertices_.size()));
}
void RootConsole::draw(const Console &other) const
{
if(other.width_ != width_ || other.height_ != height_) {
VL_FAIL("Width & height of console passed to RootConsole::draw() cannot be different");
return;
}
updateTextureBuffer(data_buf_[GLYPH], other.glyph_);
updateTextureBuffer(data_buf_[FORE], other.fore_);
updateTextureBuffer(data_buf_[BACK], other.back_);
draw();
}
//============================================================================--
// Private methods
//============================================================================--
void RootConsole::bindTextures() const
{
glActiveTexture(GL_TEXTURE0 + CON_GLYPH_UNIT);
glBindTexture(GL_TEXTURE_BUFFER, data_tex_[GLYPH]);
glActiveTexture(GL_TEXTURE0 + CON_FORE_UNIT);
glBindTexture(GL_TEXTURE_BUFFER, data_tex_[FORE]);
glActiveTexture(GL_TEXTURE0 + CON_BACK_UNIT);
glBindTexture(GL_TEXTURE_BUFFER, data_tex_[BACK]);
}
void RootConsole::reinitBuffers()
{
glDeleteTextures(3, data_tex_);
glDeleteBuffers(3, data_buf_);
initBuffers();
}
void RootConsole::initBuffers()
{
glGenBuffers(3, data_buf_);
glGenTextures(3, data_tex_);
// Glyphs
generateTexBuffer(data_buf_[GLYPH], data_tex_[GLYPH], glyph_, GL_TEXTURE1);
// Foreground
generateTexBuffer(data_buf_[FORE], data_tex_[FORE], fore_, GL_TEXTURE2);
// Background
generateTexBuffer(data_buf_[BACK], data_tex_[BACK], back_, GL_TEXTURE3);
}
void RootConsole::initVertexBuffer()
{
// Create vertex buffer
glGenBuffers(1, &ve_vbo_);
glBindBuffer(GL_ARRAY_BUFFER, ve_vbo_);
glBufferData(GL_ARRAY_BUFFER, sizeof(vec2f) * vertices_.size(), vertices_.data(), GL_STATIC_DRAW);
// Create vertex array
glGenVertexArrays(1, &vao_);
glBindVertexArray(vao_);
// Set attribute pointer
glBindBuffer(GL_ARRAY_BUFFER, ve_vbo_);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(vec2f), reinterpret_cast<void*>(offsetof(vec2f, x)));
glEnableVertexAttribArray(0);
// Unbind everything
glBindVertexArray(0);
glBindBuffer(GL_ARRAY_BUFFER, 0);
}
void RootConsole::generateVertices()
{
vec2f *curr{nullptr};
float x = 0.f,
y = 0.f;
// load in row order
for(size_type ix = 0; ix < width_; ++ix) {
for(size_type iy = 0; iy < height_; ++iy) {
curr = &vertices_[(ix + (iy * width_)) * 6];
x = static_cast<float>(ix);
y = static_cast<float>(iy);
curr[0] = {x, y };
curr[1] = {x + 1.f, y };
curr[2] = {x, y + 1.f};
curr[3] = {x, y + 1.f};
curr[4] = {x + 1.f, y };
curr[5] = {x + 1.f, y + 1.f};
}
}
}
}
<file_sep>#include "aspect_pool.hpp"
AspectPool::AspectPool() :
indices_{},
data_{nullptr},
clear_{nullptr},
deallocate_{nullptr},
copy_{nullptr},
clone_{nullptr},
size_{0},
capacity_{0},
el_size_{0}
{
}
AspectPool::AspectPool(AspectPool &&other) :
indices_{std::move(other.indices_)},
data_{other.data_},
clear_{other.clear_},
deallocate_{other.deallocate_},
copy_{other.copy_},
clone_{other.clone_},
size_{other.size_},
capacity_{other.capacity_},
el_size_{other.el_size_}
{
}
AspectPool& AspectPool::operator=(AspectPool &&other)
{
indices_ = std::move(other.indices_);
data_ = other.data_;
clear_ = other.clear_;
deallocate_ = other.deallocate_;
copy_ = other.copy_;
clone_ = other.clone_;
size_ = other.size_;
capacity_ = other.capacity_;
el_size_ = other.el_size_;
return *this;
}
AspectPool::~AspectPool()
{
clear();
}
void AspectPool::clear()
{
if(clear_) {
(this->*clear_)();
}
}
//============================================================================--
// Allocation & deallocation
//============================================================================--
bool AspectPool::copy(uint32_t source, uint32_t destination)
{
return (this->*copy_)(source, destination);
}
bool AspectPool::clone(uint32_t entity, void *original)
{
return (this->*clone_)(entity, original);
}
bool AspectPool::deallocate(uint32_t entity)
{
return (this->*deallocate_)(entity);
}
auto AspectPool::default_resize_amount() const -> size_type
{
return (capacity_ + 1) * RESIZE_FACTOR;
}
void* AspectPool::at_internal(size_type size)
{
return (void*)((char*)data_ + (size * el_size_));
}
//============================================================================--
// Aspect Access
//============================================================================--
void* AspectPool::get(uint32_t entity)
{
return indices_.has(entity) ? at_internal(indices_[entity]) : nullptr;
}
//============================================================================--
// Metadata
//============================================================================--
bool AspectPool::has(uint32_t entity) const
{
return indices_.has(entity);
}
auto AspectPool::size() const -> size_type
{
return size_;
}
auto AspectPool::capacity() const -> size_type
{
return capacity_;
}
bool AspectPool::empty() const
{
return size_ == 0;
}
bool AspectPool::initialised() const
{
return clear_ != nullptr;
}
//============================================================================--
// Private methods
//============================================================================--
void AspectPool::clear_internal_functions()
{
clear_ = nullptr;
deallocate_ = nullptr;
copy_ = nullptr;
clone_ = nullptr;
}
<file_sep>#pragma once
#include "core/opengl.hpp"
#include <vector>
namespace virgil {
template <typename V>
struct VertexArray {
public:
using array_type = std::vector<V>;
using size_type = typename std::vector<V>::size_type;
using vertex_type = V;
using value_type = V; // For the gl_buffer classes
//----------------------------------------------------------------------------//
VertexArray(GLenum draw_type = GL_TRIANGLES) :
draw_type_{draw_type}
{
}
template <typename ...Args>
void emplace_back(Args &&...args)
{
vertices_.emplace_back(std::forward<Args>(args)...);
}
void draw() const
{
glDrawArrays(draw_type_, 0, vertices_.size());
}
const vertex_type* data() const
{
return vertices_.data();
}
const array_type& vertices() const
{
return vertices_;
}
size_type size() const
{
return vertices_.size();
}
vertex_type& operator[](size_type index)
{
return vertices_[index];
}
private:
array_type vertices_;
GLenum draw_type_;
};
}
<file_sep>#pragma once
#include <cstdint>
#include "xxhash/xxhash.h"
#include "world/trigram.hpp"
namespace std {
template <>
struct hash<Trigram>
{
std::size_t operator()(const Trigram &tri) const
{
return XXH64(&tri.a, sizeof(uint32_t)*3, 0);
}
};
}
<file_sep>#pragma once
#include "core/opengl.hpp"
#include "rendering/shader.hpp"
#include "rendering/uniform.hpp"
namespace virgil {
static constexpr const char *vert_source_ = GLSL_INLINE(
layout(location = 0) in vec3 vertex_position;
layout(location = 1) in vec4 vertex_colour;
uniform mat4 transform;
uniform mat4 projection;
out vec4 colour;
void main() {
colour = vertex_colour;
gl_Position = (transform * vec4(vertex_position, 1.0)) * projection;
}
);
static constexpr const char *frag_source_ = GLSL_INLINE(
in vec4 colour;
out vec4 frag_colour;
void main()
{
frag_colour = colour;
}
);
////////////////////////////////////////////////////////////////////////////////
// FlatShader
////////////////////////////////////////////////////////////////////////////////
class FlatShader : public Shader {
public:
FlatShader(float width, float height);
bool init();
private:
void setUniforms();
//----------------------------------------------------------------------------//
mat4 transform_, //<! Transform matrix
projection_; //<! Projection matrix
Uniform<mat4> trans_, //<! Transform matrix uniform
proj_; //<! Projection matrix uniform
float width_, //<! Window width, pixels
height_; //<! Window height, pixels
};
}
<file_sep>#pragma once
#include "core/opengl.hpp"
namespace gl {
/**
* GL_ARRAY_BUFFER,
* GL_COPY_READ_BUFFER,
* GL_COPY_WRITE_BUFFER,
* GL_ELEMENT_ARRAY_BUFFER,
* GL_PIXEL_PACK_BUFFER,
* GL_PIXEL_UNPACK_BUFFER,
* GL_TEXTURE_BUFFER,
* GL_TRANSFORM_FEEDBACK_BUFFER,
* GL_UNIFORM_BUFFER
*/
enum BufferType {
ARRAY,
COPY_READ,
COPY_WRITE,
ELEMENT_ARRAY,
PIXEL_PACK,
PIXEL_UNPACK,
TEXTURE,
TRANSFORM_FEEDBACK,
UNIFORM
};
/**
* GL_STREAM_DRAW,
* GL_STREAM_READ,
* GL_STREAM_COPY,
* GL_STATIC_DRAW,
* GL_STATIC_READ,
* GL_STATIC_COPY,
* GL_DYNAMIC_DRAW,
* GL_DYNAMIC_READ,
* GL_DYNAMIC_COPY
*/
template <BufferType B>
struct buffer_traits;
////////////////////////////////////////////////////////////////////////////////
// base_buffer_traits
////////////////////////////////////////////////////////////////////////////////
template <BufferType T>
struct base_buffer_traits {
/**
* @brief Bind an OpenGL buffer
* @details [long description]
*
* @param buffer ID of the buffer to bind
*/
static void bind(GLuint buffer)
{
glBindBuffer(buffer_traits<T>::gl_enum, buffer);
}
/**
* @brief Unbind a buffer type
* @details [long description]
*
*/
static void unbind()
{
glBindBuffer(buffer_traits<T>::gl_enum, 0);
}
/**
* @brief Send data to a buffer
* @details [long description]
*
* @param size Size of data
* @param ptr Pointer to data
* @param usage_type OpenGL buffer usage type
*/
static void buffer_data(size_t size, const void *ptr, GLenum usage_type)
{
glBufferData(buffer_traits<T>::gl_enum, size, ptr, usage_type);
}
/**
* @brief Update a subset of a buffer's data
* @details [long description]
*
* @param size Size of data
* @param ptr Pointer to data
* @param offset Offset into the data buffer
*/
static void buffer_sub_data(size_t size, const void *ptr, uintptr_t offset)
{
glBufferSubData(buffer_traits<T>::gl_enum, offset, size, ptr);
}
};
////////////////////////////////////////////////////////////////////////////////
// buffer_traits specializations
////////////////////////////////////////////////////////////////////////////////
template <>
struct buffer_traits<ARRAY> : base_buffer_traits<ARRAY> {
static constexpr GLenum gl_enum = GL_ARRAY_BUFFER; //! GLenum for this buffer type
//------------------------------------------------------------------------//
static void draw(GLenum primitive_type, size_t count, size_t index = 0)
{
glDrawArrays(primitive_type, index, count);
}
};
template <>
struct buffer_traits<TEXTURE> : base_buffer_traits<TEXTURE> {
static constexpr GLenum gl_enum = GL_TEXTURE_BUFFER;
};
template <>
struct buffer_traits<ELEMENT_ARRAY> : base_buffer_traits<ELEMENT_ARRAY> {
static constexpr GLenum gl_enum = GL_ELEMENT_ARRAY_BUFFER; //! GLenum for this buffer type
static constexpr GLenum gl_index_type = GL_UNSIGNED_INT; //! GLenum for indexed arrays
using index_type = uint32_t;
//------------------------------------------------------------------------//
static void draw(GLenum primitive_type, size_t size, const void *indices = nullptr)
{
glDrawElements(primitive_type, size, gl_index_type, indices);
}
};
////////////////////////////////////////////////////////////////////////////////
// Buffer object wrapper
////////////////////////////////////////////////////////////////////////////////
/**
* @brief Wrapper around an OpenGL buffer object
*
* @tparam B BufferType which this buffer represents
*/
template <BufferType B>
struct Buffer : buffer_traits<B> {
Buffer(GLenum usage);
~Buffer();
/**
* @brief Delete the wrapped buffer object
* @details calls glDeleteBuffers on the GLuint handle for this
* buffer object
*/
void reset();
bool valid() const;
void bind() const;
void unbind() const;
void buffer_data(size_t size, const void *ptr) const;
template <typename Container>
void buffer_data(const Container &c) const;
template <typename T, size_t N>
void buffer_data(const T (&t)[N])
{
buffer_traits<B>::buffer_data(N * sizeof(T), &t[0], usage_type);
}
static void buffer_sub_data(size_t size, const void *ptr, uintptr_t offset = 0);
template <typename Container>
static void buffer_sub_data(const Container &c, uintptr_t offset = 0);
operator GLuint() const
{
return id;
}
GLuint id;
GLenum usage_type;
};
//============================================================================--
// Buffer
//============================================================================--
template <BufferType B>
inline Buffer<B>::Buffer(GLenum usage) :
usage_type{usage}
{
glGenBuffers(1, &id);
}
template <BufferType B>
inline Buffer<B>::~Buffer()
{
glDeleteBuffers(1, &id);
}
template <BufferType B>
inline void Buffer<B>::reset()
{
glDeleteBuffers(1, &id);
}
template <BufferType B>
inline bool Buffer<B>::valid() const
{
return id != 0;
}
template <BufferType B>
inline void Buffer<B>::bind() const
{
glBindBuffer(buffer_traits<B>::gl_enum, id);
}
template <BufferType B>
inline void Buffer<B>::unbind() const
{
glBindBuffer(buffer_traits<B>::gl_enum, 0);
}
template <BufferType B>
inline void Buffer<B>::buffer_data(size_t size, const void *ptr) const
{
buffer_traits<B>::buffer_data(size, ptr, usage_type);
}
template <BufferType B>
template <typename Container>
inline void Buffer<B>::buffer_data(const Container &c) const
{
buffer_traits<B>::buffer_data(c.size() * sizeof(typename Container::value_type), c.data(), usage_type);
}
template <BufferType B>
inline void Buffer<B>::buffer_sub_data(size_t size, const void *ptr, uintptr_t offset)
{
buffer_traits<B>::buffer_sub_data(size, ptr, offset);
}
template <BufferType B>
template <typename Container>
inline void Buffer<B>::buffer_sub_data(const Container &c, uintptr_t offset)
{
buffer_traits<B>::buffer_sub_data(c.size() * sizeof(typename Container::value_type), c.data(), offset);
}
using ArrayBuffer = Buffer<BufferType::ARRAY>;
////////////////////////////////////////////////////////////////////////////////
// Vertex array object wrapper
////////////////////////////////////////////////////////////////////////////////
struct VAO {
VAO() :
id{0}
{
glGenVertexArrays(1, &id);
}
~VAO()
{
glDeleteVertexArrays(1, &id);
}
void reset()
{
glDeleteVertexArrays(1, &id);
}
void bind() const
{
glBindVertexArray(id);
}
void unbind() const
{
glBindVertexArray(0);
}
GLuint id;
};
template <size_t N>
struct nVAO {
nVAO() :
ids{0}
{
glGenVertexArrays(N, &ids);
}
~nVAO()
{
glDeleteVertexArrays(N, &ids);
}
void reset()
{
glDeleteVertexArrays(N, &ids);
}
void bind(size_t which) const
{
glBindVertexArray(ids[which]);
}
void unbind() const
{
glBindVertexArray(0);
}
GLuint ids[N];
};
} // namespace gl
<file_sep>#pragma once
#include "core/opengl.hpp"
#include <string>
namespace virgil {
struct Shader {
static constexpr GLuint INVALID = 0;
//----------------------------------------------------------------------------//
Shader();
Shader(GLuint program);
/**
* @brief Check if the Shader is ready to use
* @details Passes GL_LINK_STATUS to glGetProgramiv(), checking that
* the shader program has been linked properly.
* @return True if linked and ready to use, otherwise false
*/
bool valid() const;
/**
* @brief Calls glUseProgram() on the wrapped program
*/
void use() const;
GLuint id() const;
GLint getAttribLocation(const char *loc_name) const;
GLint getUniformLocation(const char *name) const;
/**
* @brief Link the shader program
* @details Calls glLinkProgram() on the wrapped shader program,
* checking to see if the link was successful by calling
* glGetProgramiv with the GL_LINK_STATUS parameter.
* @return true if successful, otherwise false
*/
bool link();
/**
* @brief Delete the shader program and the attached vertex and
* fragment shaders
*/
void clear();
/**
* @brief Compile the vertex shader and attach it to the shader
* program
*
* @param source Shader source
* @return True if successfully compiled, otherwise false
*/
bool compileVertex(const char *source);
bool compileVertex(const std::string &source);
/**
* @brief Compile the fragment shader and attach it to the shader
* program
*
* @param source Shader source
* @return True if successfully compiled, otherwise false
*/
bool compileFragment(const char *source);
bool compileFragment(const std::string &source);
void bindAttrib(GLuint loc, const char *name) const;
static void printShaderLog(GLuint shader_index);
protected:
void attach(GLuint shader_id);
bool compile(GLuint shader_id, const char *source) const;
//------------------------------------------------------------------------//
GLuint program_, //<! Shader program
vertex_, //<! Vertex shader id
fragment_; //<! Fragment shader id
protected:
};
}
<file_sep>#pragma once
#include "geometry/vec2.hpp"
#include "rendering/colour.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// vertex
////////////////////////////////////////////////////////////////////////////////
template <typename V>
struct vertex {
using vector_type = V;
//----------------------------------------------------------------------------//
vertex() = default;
vertex(vec2f position, Colour colour, vec2f tex_coords) :
pos{position},
col{colour},
tex{tex_coords}
{
}
static void* posOffset()
{
return reinterpret_cast<void*>(offsetof(vertex, pos));
}
static void* colOffset()
{
return reinterpret_cast<void*>(offsetof(vertex, col));
}
static void* texOffset()
{
return reinterpret_cast<void*>(offsetof(vertex, tex));
}
static void setVertexAttribPointers()
{
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), posOffset());
glEnableVertexAttribArray(0);
glVertexAttribPointer(1, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(vertex), colOffset());
glEnableVertexAttribArray(1);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(vertex), texOffset());
glEnableVertexAttribArray(2);
}
//----------------------------------------------------------------------------//
vector_type pos;
Colour col;
vector_type tex;
};
using vertex2f = vertex<vec2f>;
////////////////////////////////////////////////////////////////////////////////
// vertex_plain
////////////////////////////////////////////////////////////////////////////////
template <typename V>
struct vertex_plain {
using vector_type = V;
//----------------------------------------------------------------------------//
vertex_plain() = default;
vertex_plain(vec2f position, Colour colour) :
pos{position},
col{colour}
{
}
static void* posOffset()
{
return reinterpret_cast<void*>(offsetof(vertex_plain, pos));
}
static void* colOffset()
{
return reinterpret_cast<void*>(offsetof(vertex_plain, col));
}
static void setVertexAttribPointers(GLuint pos_index = 0, GLuint col_index = 1)
{
glVertexAttribPointer(pos_index, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_plain), posOffset());
glEnableVertexAttribArray(0);
glVertexAttribPointer(col_index, 4, GL_UNSIGNED_BYTE, GL_TRUE, sizeof(vertex_plain), colOffset());
glEnableVertexAttribArray(1);
}
//----------------------------------------------------------------------------//
vector_type pos;
Colour col;
};
using vertex_plain2f = vertex_plain<vec2f>;
////////////////////////////////////////////////////////////////////////////////
// vertex_tex
////////////////////////////////////////////////////////////////////////////////
template <typename V>
struct vertex_tex {
using vector_type = V;
//----------------------------------------------------------------------------//
vertex_tex(vec2f position, vec2f tex_coords) :
pos{position},
tex{tex_coords}
{
}
static void* posOffset()
{
return reinterpret_cast<void*>(offsetof(vertex_tex, pos));
}
static void* texOffset()
{
return reinterpret_cast<void*>(offsetof(vertex_tex, tex));
}
static void setVertexAttribPointers()
{
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_tex), posOffset());
glEnableVertexAttribArray(0);
glVertexAttribPointer(2, 2, GL_FLOAT, GL_FALSE, sizeof(vertex_tex), texOffset());
glEnableVertexAttribArray(2);
}
//----------------------------------------------------------------------------//
vector_type pos;
vector_type tex;
};
using vertex_tex2f = vertex_tex<vec2f>;
}
<file_sep>#pragma once
#include "entelechy/uid.hpp"
class Space;
////////////////////////////////////////////////////////////////////////////////
// Entity
////////////////////////////////////////////////////////////////////////////////
class Entity {
public:
Entity();
Entity(uid id, Space *space);
~Entity() = default;
template <typename A, typename ...Args>
A* add(Args &&...args) const;
template <typename A>
void remove() const;
template <typename A>
A* get();
template <typename ...Args>
bool has();
void destroy();
uid id();
void id(uid new_id);
Space* space();
bool valid() const;
bool operator==(const Entity &rhs);
bool operator!=(const Entity &rhs);
private:
Space *space_;
uid id_;
};
inline Entity::Entity() :
space_{nullptr},
id_{BAD_UID}
{
}
inline Entity::Entity(uid id, Space *space) :
space_{space},
id_{id}
{
}
inline uid Entity::id()
{
return id_;
}
inline void Entity::id(uid new_id)
{
id_ = new_id;
}
inline Space* Entity::space()
{
return space_;
}
inline bool Entity::operator==(const Entity &rhs)
{
return id_ == rhs.id_;
}
inline bool Entity::operator!=(const Entity &rhs)
{
return !(*this == rhs);
}
<file_sep>#pragma once
#include <cstdint>
#include <cstdlib>
#include <new>
#include <stdexcept>
#include <cstring>
#include <unordered_map>
/**
* @brief Naive integer set for densely packed Aspect types.
* @details [long description]
*
*/
class u32set {
public:
using value_type = uint32_t;
using reference = uint32_t&;
using pointer = uint32_t*;
using storage_type = pointer;
using const_reference = const uint32_t&;
using const_pointer = const uint32_t*;
using size_type = uint32_t;
//----------------------------------------------------------------------------//
static constexpr float EXPANSION_FACTOR = 1.5f;
static constexpr value_type npos = ~value_type(0);
//----------------------------------------------------------------------------//
u32set() :
dense_{nullptr},
sparse_{nullptr},
size_{0},
capacity_{0}
{
expand(64);
}
~u32set()
{
if(dense_) std::free(dense_);
if(sparse_) std::free(sparse_);
}
void clear()
{
size_ = 0;
}
bool empty()
{
return size_ == 0;
}
bool full()
{
return size_ == capacity_;
}
bool add(value_type value)
{
if(value >= capacity_) {
size_type new_capacity = (value + 1) * EXPANSION_FACTOR;
expand(new_capacity);
}
const uint32_t a = sparse_[value];
if(a >= size_ || dense_[a] != value) {
sparse_[value] = size_;
dense_[size_++] = value;
return true;
}
return false;
}
bool remove(value_type value)
{
if(value >= capacity_ || empty()) {
return false;
}
const uint32_t mval = sparse_[value];
if(mval <= (size_ - 1) || dense_[mval] == value) {
--size_;
uint32_t top = dense_[size_];
sparse_[top] = mval;
dense_[mval] = top;
return true;
}
return false;
}
bool has(value_type value) const
{
if(value >= capacity_) {
return false;
}
const uint32_t a = sparse_[value];
return a < size_ && dense_[a] == value;
}
bool transfer(value_type source, value_type destination)
{
if(!has(source) || has(destination)) {
return false;
}
sparse_[destination] = sparse_[source];
dense_[sparse_[source]] = destination;
remove(source);
return true;
}
value_type at(size_type index)
{
if(index >= capacity_) {
throw std::out_of_range("u32set::at() out of range");
}
return sparse_[index];
}
value_type dense(size_type index)
{
if(index >= size_) {
throw std::out_of_range("u32set::dense() out of range");
}
return dense_[index];
}
value_type operator[](size_type index) const
{
return sparse_[index];
}
size_type size() const
{
return size_;
}
size_type capacity() const
{
return capacity_;
}
bool resize(size_type new_capacity)
{
if(new_capacity <= capacity_) {
return false;
}
expand(new_capacity);
return true;
}
pointer begin()
{
return &dense_[0];
}
pointer end()
{
return &dense_[size_];
}
const_pointer begin() const
{
return &dense_[0];
}
const_pointer end() const
{
return &dense_[size_];
}
value_type dense(size_type index) const
{
return dense_[index];
}
private:
void expand(size_type new_capacity)
{
pointer new_dense = reinterpret_cast<uint32_t*>(
std::realloc(dense_, new_capacity * sizeof(uint32_t))
);
if(new_dense == nullptr) {
throw std::bad_alloc();
} else {
dense_ = new_dense;
}
uint32_t *new_sparse = reinterpret_cast<uint32_t*>(
std::realloc(sparse_, new_capacity * sizeof(uint32_t))
);
if(new_sparse == nullptr) {
throw std::bad_alloc();
} else {
sparse_ = new_sparse;
}
std::memset(dense_ + size_, 0, capacity_ - size_);
capacity_ = new_capacity;
}
//----------------------------------------------------------------------------//
storage_type dense_,
sparse_;
size_type size_,
capacity_;
};
/**
* @brief Integer set for sparsely-packed Aspect types.
* @details [long description]
*
*/
class sparse_u32set {
public:
using value_type = uint32_t;
using reference = uint32_t&;
using pointer = uint32_t*;
using const_reference = const uint32_t&;
using const_pointer = const uint32_t*;
using size_type = uint32_t;
using storage_type = std::unordered_map<value_type, value_type>;
//----------------------------------------------------------------------------//
static constexpr value_type npos = ~value_type(0);
//----------------------------------------------------------------------------//
sparse_u32set() :
size_{0}
{
resize(64);
}
bool has(uint32_t idx)
{
return sparse_.find(idx) != sparse_.end();
}
void add(uint32_t idx)
{
sparse_.emplace(idx, size_);
dense_.emplace(size_++, idx);
}
void remove(uint32_t idx)
{
--size_;
const auto mval = sparse_.find(idx)->second;
const auto top = dense_.find(size_)->second;
sparse_[top] = mval;
dense_[mval] = top;
sparse_.erase(idx);
dense_.erase(size_);
}
uint32_t operator[](uint32_t idx) const
{
return sparse_.find(idx)->second;
}
void resize(uint32_t sz)
{
sparse_.reserve(sz);
dense_.reserve(sz);
}
bool empty()
{
return size_ == 0;
}
bool full()
{
return false;
}
value_type dense(size_type index) const
{
return dense_.find(index)->second;
}
private:
storage_type sparse_,
dense_;
size_type size_;
};
<file_sep>#pragma once
#include "utils/container_tools.hpp"
#include "entelechy/system.hpp"
#include <vector>
#include <memory>
class EventManager;
class SystemManager {
using system_ptr = std::unique_ptr<ISystem>;
public:
SystemManager(Space &space);
SystemManager(const SystemManager&) = delete;
~SystemManager() = default;
template <typename S, typename ...Args>
S* add(Args &&...args)
{
if(has<S>()) {
return static_cast<S*>(systems_[id<S>()].get());
}
ensure_resize(systems_, id<S>());
systems_[id<S>()].reset(new S(std::forward<Args>(args)...));
return static_cast<S*>(systems_[id<S>()].get());
}
template <typename S>
bool remove()
{
if(!has<S>()) {
return false;
}
systems_[id<S>()].reset();
return true;
}
void tick(EventManager &event_man);
void update(EventManager &event_man, double delta);
template <typename S>
bool has()
{
return (id<S>() < systems_.size()) && systems_[id<S>()];
}
template <typename S>
S* system()
{
return static_cast<S*>(systems_[id<S>()].get());
}
template <typename S>
uint32_t id()
{
static const uint32_t id_{last_system_id_++};
return id_;
}
private:
std::vector<system_ptr> systems_;
Space &space_;
uint32_t last_system_id_;
};
<file_sep>#include "utils/image.hpp"
#include "core/assert.hpp"
#include "core/stb_image.hpp"
#include <cstdlib>
#include <cstring>
#include <new>
namespace virgil {
//============================================================================--
// Image - Constructors
//============================================================================--
Image::Image() :
bytes_{0},
width_{0},
height_{0},
data_{nullptr},
channels_{0}
{
}
Image::Image(uint32_t width, uint32_t height, uint8_t channels) :
bytes_{0},
width_{width},
height_{height},
data_{nullptr},
channels_{channels}
{
data_ = reinterpret_cast<uint8_t*>(std::malloc(sizeof(uint8_t) * width_ * height_ * 4));
if(data_ == nullptr) {
throw std::bad_alloc{};
}
bytes_ = width_ * height_ * 4;
std::memset(data_, 0, bytes_);
}
Image::Image(const char *file_name, uint8_t force_channels) :
bytes_{0},
width_{0},
height_{0},
data_{nullptr},
channels_{0}
{
load(file_name, force_channels);
}
Image::~Image()
{
erase();
}
Colour Image::getPixel(uint32_t x, uint32_t y) const
{
const uint32_t idx = ((y * width_ * channels_) + x * channels_);
return {
data_[idx],
data_[idx + 1],
data_[idx + 2],
data_[idx + 3]
};
}
uint8_t Image::getAlpha(uint32_t x, uint32_t y) const
{
return data_[((y * width_ * channels_) + x * channels_) + 3];
}
bool Image::isPixelTransparent(uint32_t x, uint32_t y) const
{
return (getAlpha(x, y) == 0);
}
//============================================================================--
// Load/Save operations
//============================================================================--
bool Image::load(const char *file_name, uint8_t force_channels)
{
int width, height, channels;
data_ = stbi_load(file_name, &width, &height, &channels, force_channels);
if(!data_) {
printf("Error: Failed to load %s\n", file_name);
return false;
}
if(width == 0 || height == 0) {
printf("Error: Image is invalid - %s\n", file_name);
return false;
}
width_ = width;
height_ = height;
channels_ = channels;
bytes_ = width_ * height_ * channels_;
return true;
}
bool Image::save(const char *file_name) const
{
if(bytes_ == 0) {
printf("Cannot save image %s with size 0", file_name);
return false;
}
VL_ASSERT(data_ && channels_ && width_ && height_, "Invalid image!");
return stbi_write_png(file_name, width_, height_, channels_, data_, 0);
}
//============================================================================--
// Modifications
//============================================================================--
void Image::resize(uint32_t new_w, uint32_t new_h)
{
uint8_t *new_buf = reinterpret_cast<uint8_t*>(std::malloc(sizeof(uint8_t) * new_w * new_h * 4));
stbir_resize_uint8(
data_, width_, height_,
0, // stride in bytes
new_buf, new_w, new_h,
0, // stride in bytes
channels_);
width_ = new_w;
height_ = new_h;
std::free(data_);
data_ = new_buf;
}
void Image::setKeyColour(Colour c)
{
const uint32_t rgb_key = static_cast<uint32_t>(c.r) << 16 | static_cast<uint32_t>(c.g) << 8 | static_cast<uint32_t>(c.b);
for(size_t i = 0; i < bytes_; i += 4) {
if(static_cast<uint32_t>(data_[i] << 16 | data_[i+1] << 8 | data_[i+2]) == rgb_key) {
data_[i+3] = 0;
}
}
}
void Image::flipHorizontal()
{
const int width_in_bytes = width_ * channels_;
uint8_t *left{nullptr},
*right{nullptr};
const int half_width = width_ / 2;
for(uint32_t row = 0; row < height_; ++row) {
left = data_ + (row * width_in_bytes);
right = left + width_in_bytes - 1;
for(int col = 0; col < half_width; ++col, left +=4, right -= 4) {
std::swap(left[0], right[3]);
std::swap(left[1], right[2]);
std::swap(left[2], right[1]);
std::swap(left[3], right[0]);
}
}
}
void Image::flipVertical()
{
const int width_in_bytes = width_ * channels_;
uint8_t *top{nullptr},
*bottom{nullptr};
const int half_height = height_ / 2;
for(int row = 0; row < half_height; ++row) {
top = data_ + (row * width_in_bytes);
bottom = data_ + ((height_ - row - 1) * width_in_bytes);
for(int col = 0; col < width_in_bytes; ++col) {
std::swap(*top++, *bottom++);
}
}
}
void Image::erase()
{
if(data_) {
std::free(data_);
data_ = nullptr;
}
}
bool Image::valid() const
{
return data_ != nullptr && width_ != 0 && height_ != 0;
}
}
<file_sep>#pragma once
#include "entelechy/uid.hpp"
#include "entelechy/aspect.hpp"
template <typename A>
struct AspectPointerTupleLeaf {
AspectPointerTupleLeaf(aspect_ptr<A> &ap) :
ptr{ap}
{
}
//----------------------------------------------------------------------------//
aspect_ptr<A> &ptr;
};
template <typename ...Aspects>
struct AspectPointerTuple : AspectPointerTupleLeaf<Aspects>... {
template <typename A>
using leaf_type = AspectPointerTupleLeaf<A>;
//----------------------------------------------------------------------------//
AspectPointerTuple(aspect_ptr<Aspects> &...ptrs) :
AspectPointerTupleLeaf<Aspects>{ptrs}...
{
}
void init(Space &s) const
{
int _[]{0, (leaf_type<Aspects>::ptr.reset(s.getPool<Aspects>()), 0)...};
// silence compiler warning
(void)_;
}
void reset(uid entity) const
{
VL_ASSERT(entity != BAD_UID, "Attempt to set BAD_UID");
int _[]{0, (leaf_type<Aspects>::ptr.reset(entity), 0)...};
// silence compiler warning
(void)_;
}
};
class space_iterator {
public:
using size_type = uint32_t;
//----------------------------------------------------------------------------//
~space_iterator() = default;
bool operator==(const space_iterator &rhs) const
{
return curr_ == rhs.curr_;
}
bool operator!=(const space_iterator &rhs) const
{
return !(*this == rhs);
}
size_type id() const
{
return curr_;
}
protected:
space_iterator(Space &space, size_type index) :
space_{space},
eman_{space.entities_},
curr_{index},
max_{space.size()}
{
}
//----------------------------------------------------------------------------//
Space &space_;
EntityManager &eman_;
size_type curr_;
const size_type max_;
};
class LiveEntityFilter {
public:
using size_type = uint32_t;
LiveEntityFilter(Space &space, Entity &entity) :
space_{space},
entity_{entity}
{
}
//----------------------------------------------------------------------------//
class iterator : public space_iterator {
public:
iterator(Space &space, size_type index, Entity &entity) :
space_iterator{space, index},
entity_{entity}
{
next();
}
iterator& operator++()
{
++curr_;
next();
return *this;
}
void next()
{
while(curr_ < max_ && eman_.entity_sig(curr_).any()) {
++curr_;
}
}
const iterator& operator*() const
{
entity_.id({curr_, eman_.gen(curr_)});
return *this;
}
private:
Entity &entity_;
};
//----------------------------------------------------------------------------//
iterator begin()
{
return {space_, 0, entity_};
}
iterator end()
{
return {space_, space_.size(), entity_};
}
private:
Space &space_;
Entity &entity_;
};
class EntityFilter {
public:
using size_type = uint32_t;
EntityFilter(Space &space, Entity &entity, aspect_mask mask) :
space_{space},
entity_{entity},
mask_{mask}
{
}
//----------------------------------------------------------------------------//
class iterator : public space_iterator {
public:
iterator(Space &space, size_type index, Entity &entity, const aspect_mask &mask) :
space_iterator{space, index},
entity_{entity},
mask_{mask}
{
next();
}
iterator& operator++()
{
++curr_;
next();
return *this;
}
void next()
{
while(curr_ < max_ && (eman_.entity_sig(curr_) & mask_) != mask_) {
++curr_;
}
}
const iterator& operator*() const
{
entity_.id({curr_, eman_.gen(curr_)});
return *this;
}
private:
Entity &entity_;
const aspect_mask &mask_;
};
//----------------------------------------------------------------------------//
iterator begin()
{
return {space_, 0, entity_, mask_};
}
iterator end()
{
return {space_, space_.size(), entity_, mask_};
}
private:
Space &space_;
Entity &entity_;
const aspect_mask mask_;
};
template <typename ...Aspects>
struct AspectPointerFrame {
AspectPointerFrame(Space &s, aspect_ptr<Aspects> &...pointers) :
pointers_{pointers...}
{
pointers_.init(s);
}
void unpack(uid &&entity) const
{
pointers_.reset(std::forward<uid>(entity));
}
private:
AspectPointerTuple<Aspects...> pointers_;
};
template <typename ...Aspects>
class AspectFilter {
public:
using size_type = uint32_t;
using frame_type = AspectPointerFrame<Aspects...>;
//----------------------------------------------------------------------------//
AspectFilter(Space &space, aspect_ptr<Aspects> &...pointers) :
space_{space},
mask_{space.maskFor<Aspects...>()},
frame_{space, pointers...}
{
}
//----------------------------------------------------------------------------//
struct iterator : space_iterator {
iterator(Space &space, const aspect_mask &mask, size_type index, const frame_type &frame) :
space_iterator{space, index},
mask_{mask},
frame_{frame}
{
next();
}
~iterator() = default;
iterator& operator++()
{
++curr_;
next();
return *this;
}
const iterator& operator*() const
{
frame_.unpack({curr_, eman_.gen(curr_)});
return *this;
}
void next()
{
while((curr_ < max_) && (eman_.entity_sig(curr_) & mask_) != mask_) {
++curr_;
}
}
uid entity() const
{
return {curr_, eman_.gens_[curr_]};
}
private:
const aspect_mask mask_;
const frame_type &frame_;
};
//----------------------------------------------------------------------------//
iterator begin()
{
return {space_, mask_, 0, frame_};
}
iterator end()
{
return {space_, mask_, space_.size(), frame_};
}
private:
Space &space_;
const aspect_mask mask_;
frame_type frame_;
};
<file_sep>#include "flat_shader.hpp"
namespace virgil {
FlatShader::FlatShader(float width, float height) :
width_{width},
height_{height}
{
}
bool FlatShader::init()
{
projection_ = mat4::ortho(0.f, width_, 0.f, height_);
program_ = glCreateProgram();
vertex_ = glCreateShader(GL_VERTEX_SHADER);
fragment_ = glCreateShader(GL_FRAGMENT_SHADER);
if(!compile(vertex_, vert_source_) || !compile(fragment_, frag_source_)) {
return false;
}
glAttachShader(program_, vertex_);
glAttachShader(program_, fragment_);
if(!link()) {
return false;
}
setUniforms();
return true;
}
void FlatShader::setUniforms()
{
glUseProgram(program_);
proj_.getLocation("projection", *this);
proj_.set(projection_);
trans_.getLocation("transform", *this);
trans_.set(transform_);
glUseProgram(0);
}
}
<file_sep>#pragma once
#include "rendering/colour.hpp"
#include "rendering/shader.hpp"
#include "rendering/uniform.hpp"
#include "rendering/texture.hpp"
#include "rendering/gl_buffer.hpp"
#include "rendering/vertex_types.hpp"
#include "rendering/vertex_array.hpp"
#include "rendering/indexed_array.hpp"
#include "rendering/terminal.hpp"
#include "shaders/shaders.hpp"
<file_sep>#pragma once
#include <cstdint>
struct core_stats {
core_stats() :
wit{0},
discipline{0},
comprehension{0}
{
}
core_stats(uint32_t w, uint32_t d, uint32_t c) :
wit{w},
discipline{d},
comprehension{c}
{
}
//----------------------------------------------------------------------------//
uint32_t wit,
discipline,
comprehension;
//----------------------------------------------------------------------------//
enum class type {
wit,
discipline,
comprehension,
none
};
//----------------------------------------------------------------------------//
type major(core_stats &s)
{
if(s.wit > s.discipline > s.comprehension) {
return type::wit;
} else if(s.discipline > s.comprehension > s.wit) {
return type::discipline;
} else if(s.comprehension > s.discipline > s.wit) {
return type::comprehension;
} else {
return type::none;
}
}
};
<file_sep>#pragma once
#include <vector>
#include <string>
// Copyright (c) 2008-2009 <NAME> <<EMAIL>>
// See http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ for details.
static constexpr int UTF8_ACCEPT {0};
static constexpr int UTF8_REJECT {12};
static const uint8_t utf8d[] = {
// The first part of the table maps bytes to character classes that
// to reduce the size of the transition table and create bitmasks.
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,9,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7, 7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
8,8,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
10,3,3,3,3,3,3,3,3,3,3,3,3,4,3,3, 11,6,6,6,5,8,8,8,8,8,8,8,8,8,8,8,
// The second part is a transition table that maps a combination
// of a state of the automaton and a character class to a state.
0,12,24,36,60,96,84,12,12,12,48,72, 12,12,12,12,12,12,12,12,12,12,12,12,
12, 0,12,12,12,12,12, 0,12, 0,12,12, 12,24,12,12,12,12,12,24,12,24,12,12,
12,12,12,12,12,12,12,24,12,12,12,12, 12,24,12,12,12,12,12,12,12,24,12,12,
12,12,12,12,12,12,12,36,12,36,12,12, 12,36,12,12,12,12,12,36,12,36,12,12,
12,36,12,12,12,12,12,12,12,12,12,12,
};
inline uint32_t decode(uint32_t *state, uint32_t *codep, const uint8_t byte)
{
const uint32_t type = utf8d[byte];
*codep = (*state != UTF8_ACCEPT) ?
(byte & 0x3fu) | (*codep << 6) :
(0xff >> type) & (byte);
*state = utf8d[256 + *state + type];
return *state;
}
inline size_t utf8_strlen(uint8_t *s)
{
size_t count = 0;
uint32_t state = 0,
codepoint;
for(; *s; ++s) {
if(!decode(&state, &codepoint, *s)) ++count;
}
return count;
}
inline size_t utf8_strlen(const std::string &str)
{
size_t count = 0;
uint32_t state = 0,
codepoint;
const uint8_t *byte = (const uint8_t*)(str.c_str());
for(; *byte; ++byte) {
if(!decode(&state, &codepoint, *byte)) ++count;
}
return count;
}
////////////////////////////////////////////////////////////////////////////////
// utf8_decode_iterator
////////////////////////////////////////////////////////////////////////////////
struct utf8_decode_iterator : public std::iterator<std::input_iterator_tag, uint32_t> {
utf8_decode_iterator();
utf8_decode_iterator(const char *string);
utf8_decode_iterator(std::string string);
utf8_decode_iterator(const utf8_decode_iterator &other);
utf8_decode_iterator(utf8_decode_iterator &&other);
utf8_decode_iterator& operator=(utf8_decode_iterator other);
utf8_decode_iterator operator++(int);
utf8_decode_iterator& operator++();
uint32_t operator*() const;
friend bool operator==(const utf8_decode_iterator &lhs, const utf8_decode_iterator &rhs);
friend bool operator!=(const utf8_decode_iterator &lhs, const utf8_decode_iterator &rhs);
private:
bool equal(const utf8_decode_iterator &other) const;
bool atEnd() const;
void advance();
//------------------------------------------------------------------------//
const char *string_; //! The string to iterate over
size_t pos_, //! The current string position
max_pos_; //! The upper bound for pos_
uint32_t state_, //! The decoder state
current_codepoint_; //! Last decoded codepoint
};
//============================================================================--
// Constructors
//============================================================================--
inline utf8_decode_iterator::utf8_decode_iterator() :
string_{nullptr},
pos_{0},
max_pos_{0},
state_{0},
current_codepoint_{0}
{
}
inline utf8_decode_iterator::utf8_decode_iterator(const char *string) :
string_{string},
pos_{0},
max_pos_{strlen(string)},
state_{0},
current_codepoint_{0}
{
// Necessary in order to satisfy the input iterator concept, such
// that the expression *i++ evaluates to value_type
advance();
}
inline utf8_decode_iterator::utf8_decode_iterator(std::string string) :
string_{string.c_str()},
pos_{0},
max_pos_{string.length() + 1}, // @todo rename max_pos_ as we're one-past-the-end
state_{0},
current_codepoint_{0}
{
// Necessary in order to satisfy the input iterator concept, such
// that the expression *i++ evaluates to value_type
advance();
}
inline utf8_decode_iterator::utf8_decode_iterator(const utf8_decode_iterator &other) :
string_{other.string_},
pos_{other.pos_},
max_pos_{other.max_pos_},
state_{other.state_},
current_codepoint_{other.current_codepoint_}
{
}
inline utf8_decode_iterator::utf8_decode_iterator(utf8_decode_iterator &&other) :
string_{other.string_},
pos_{other.pos_},
max_pos_{other.max_pos_},
state_{other.state_},
current_codepoint_{other.current_codepoint_}
{
other.string_ = nullptr;
}
inline utf8_decode_iterator& utf8_decode_iterator::operator=(utf8_decode_iterator other)
{
std::swap(*this, other);
return *this;
}
//============================================================================--
// Increment
//============================================================================--
inline utf8_decode_iterator utf8_decode_iterator::operator++(int)
{
utf8_decode_iterator tmp(*this);
++*this;
return tmp;
}
inline utf8_decode_iterator& utf8_decode_iterator::operator++()
{
if(pos_ != max_pos_) {
advance();
}
return *this;
}
//============================================================================--
// Dereference
//============================================================================--
inline uint32_t utf8_decode_iterator::operator*() const
{
return current_codepoint_;
}
//============================================================================--
// Status checking
//============================================================================--
inline bool utf8_decode_iterator::equal(const utf8_decode_iterator &other) const
{
return atEnd() == other.atEnd();
}
inline bool utf8_decode_iterator::atEnd() const
{
return pos_ == max_pos_;
}
inline void utf8_decode_iterator::advance()
{
while(decode(&state_, ¤t_codepoint_, string_[pos_])) ++pos_;
++pos_;
}
inline bool operator==(const utf8_decode_iterator &lhs, const utf8_decode_iterator &rhs)
{
return lhs.equal(rhs);
}
inline bool operator!=(const utf8_decode_iterator &lhs, const utf8_decode_iterator &rhs)
{
return !lhs.equal(rhs);
}
////////////////////////////////////////////////////////////////////////////////
// translate codepoint to char*
////////////////////////////////////////////////////////////////////////////////
inline const char* toUTF8(const uint32_t codepoint, char *buf)
{
if (codepoint <= 0x7f) {
buf[0] = static_cast<char>(codepoint);
buf[1] = '\0';
} else if (codepoint <= 0x7ff) {
buf[0] = static_cast<char>(0xc0 | ((codepoint >> 6) & 0x1f));
buf[1] = static_cast<char>(0x80 | (codepoint & 0x3f));
buf[2] = '\0';
} else if (codepoint <= 0xffff) {
buf[0] = static_cast<char>(0xe0 | ((codepoint >> 12) & 0x0f));
buf[1] = static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f));
buf[2] = static_cast<char>(0x80 | (codepoint & 0x3f));
buf[3] = '\0';
} else {
buf[0] = static_cast<char>(0xf0 | ((codepoint >> 18) & 0x07));
buf[1] = static_cast<char>(0x80 | ((codepoint >> 12) & 0x3f));
buf[2] = static_cast<char>(0x80 | ((codepoint >> 6) & 0x3f));
buf[3] = static_cast<char>(0x80 | (codepoint & 0x3f));
}
return buf;
}
////////////////////////////////////////////////////////////////////////////////
// inline decode-iterator helper
////////////////////////////////////////////////////////////////////////////////
inline void utf8_decode(const std::string &str, std::vector<uint32_t> &codepoints)
{
codepoints.insert(codepoints.begin(), utf8_decode_iterator{str}, utf8_decode_iterator{});
}
inline void utf8_encode(const std::vector<uint32_t> &codepoints, std::string &str)
{
char x[4];
for(const auto &cp : codepoints) {
str.append(toUTF8(cp, x));
}
}
<file_sep>#pragma once
#include "rendering/colour.hpp"
namespace virgil {
struct glyph {
glyph() :
gly{0},
col{255,255,255}
{
}
glyph(uint32_t g, Colour c) :
gly{g},
col{c}
{
}
//----------------------------------------------------------------------------//
uint32_t gly;
Colour col;
};
}
<file_sep>#pragma once
#include "systems/render_system.hpp"
#include "systems/movement_system.hpp"
<file_sep>#include "driver.hpp"
namespace virgil {
Driver::Driver(int, const char **) :
term_{80, 50, "virgil"},
space_{eman_, msg_hand_},
end_main_loop_{false}
{
msg_hand_.addStore<move_delta>();
}
int Driver::run()
{
try {
term_.initRoot();
} catch(const std::exception &e) {
std::cout << e.what();
return EXIT_FAILURE;
}
init();
initSpace();
if(!mainLoop()) {
return EXIT_FAILURE;
} else {
return EXIT_SUCCESS;
}
}
void Driver::init()
{
glfwSetWindowUserPointer(term_.window(), this);
glfwSetKeyCallback(term_.window(), key_callback);
}
void Driver::initSpace()
{
// add pools
space_.createPool<glyph>("glyph");
space_.createPool<position>("position");
space_.createPool<player>("player");
space_.createPool<mob>("mob");
// add systems
space_.addSystem<RenderSystem>(*term_.root);
space_.addSystem<MovementSystem>();
space_.getSystem<MovementSystem>()->init();
// create an entity for the player
auto e = space_.createEntity();
e.add<glyph>('@', col::lime);
e.add<position>(40, 25);
e.add<player>();
Random rng;
for(uint32_t i = 0; i < 100; ++i) {
auto e = space_.createEntity();
e.add<position>(rng.get_int(0, 79), rng.get_int(0, 49));
e.add<glyph>('x', col::pallor);
e.add<mob>();
}
}
bool Driver::mainLoop()
{
std::vector<std::chrono::milliseconds> ts;
decltype(std::chrono::high_resolution_clock::now()) t0, t1;
while(term_.isOpen()) {
if(end_main_loop_) {
term_.closeWindow();
}
t0 = std::chrono::high_resolution_clock::now();
term_.pollEvents();
space_.tick();
term_.flush();
t1 = std::chrono::high_resolution_clock::now();
ts.emplace_back(std::chrono::duration_cast<std::chrono::milliseconds>(t1 - t0));
}
const double d = std::accumulate(ts.begin(), ts.end(), double{}, [&](double t, const std::chrono::milliseconds &ms){return ms.count() + t;});
std::cout << "average loop time was " << d / double(ts.size()) << "ms" << std::endl;
return true;
}
}
<file_sep>#pragma once
#include "nano-signal-slot/nano_signal_slot.hpp"
#include <vector>
/**
* @brief Interface class for EventRelay
*/
class BaseEventRelay {
public:
virtual ~BaseEventRelay() = default;
virtual void sync() = 0;
};
/**
* @brief Event handling class
* @description
* @tparam E Event type handled by this class
*/
template <typename E>
class EventRelay : public BaseEventRelay {
public:
using size_type = uint32_t;
using event_type = E;
using signal_type = Nano::Signal<void(const event_type &)>;
using storage_type = std::vector<event_type>;
//----------------------------------------------------------------------------//
EventRelay() = default;
EventRelay(const EventRelay &) = delete;
EventRelay(EventRelay &&) = default;
~EventRelay() = default;
//----------------------------------------------------------------------------//
/**
* @brief Connect a free function that handles this event type
*
* @tparam F Pointer-to-function
*/
template <void (*F)(const event_type &)>
void connect()
{
signal_.template connect<F>();
}
/**
* @brief Disconnect a free function previously connected to this relay
*
* @tparam F Pointer-to-function
*/
template <void (*F)(const event_type &)>
void disconnect()
{
signal_.template disconnect<F>();
}
/**
* @brief Connect a method that handles this event type
*
* @param instance Class instance to register for
* @tparam C Class type
* @tparam F Pointer-to-method
*/
template <class C, void (C::*F)(const event_type &)>
void connect(C *instance)
{
signal_.template connect<C, F>(instance);
}
/**
* @brief Disconnect a method previously connected to this relay
*
* @param instance Class instance to de-register for
* @tparam C Class type
* @tparam F Pointer-to-method
*/
template <class C, void (C::*F)(const event_type &)>
void disconnect(C *instance)
{
signal_.template disconnect<C, F>(instance);
}
/**
* @brief Queue a message to send to all subscribers
* @details Messages sent in this manner will be relayed to all subscribers
* when sync() is called.
*
* @param args Arguments for constructing event_type
*/
template <typename ...Args>
void queue(Args &&...args)
{
payloads_.emplace_back(std::forward<Args>(args)...);
}
/**
* @brief Send a message to all subscribers immediately
* @details Messages sent in this manner will be relayed to all subscribers
* immediately, rather than waiting for sync() to be called.
*
* @param args Arguments for constructing event_type
*/
template <typename ...Args>
void send(Args &&...args)
{
event_type event{std::forward<Args>(args)...};
signal_.emit(event);
}
/**
* @brief Synchronise the relay, sending all queued messages
* @details This will dispatch all messages stored in the payloads_ vector
* in the order they were added using nano-signal-slot's emit() method.
* After the messages have been sent, the payloads_ vector is cleared ready
* for the next Space::tick().
*/
virtual void sync() final
{
for(auto &payload : payloads_) {
signal_.emit(payload);
}
payloads_.clear();
}
/**
* @brief Get the number of events currently queued by this relay
* @return Number of events currently waiting to be sent
*/
size_type queued() const
{
return payloads_.size();
}
private:
signal_type signal_; //<! Nano::signal for event-handling functions
storage_type payloads_; //<! Array of event_type objects
};
<file_sep>#pragma once
#include "core/platform.hpp"
#ifdef VIRGIL_OSX
#include <GL/glew.h>
#elif VIRGIL_WIN
#define GLFW_DLL
#endif
#include <GLFW/glfw3.h>
#define GLSL_INLINE(src) "#version 330 core\n" #src
#define GLSL_INLINE_BARE(src) #src
namespace gl {
inline bool setup_glfw()
{
if(!glfwInit()) {
return false;
}
#ifdef VIRGIL_OSX
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 3);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 2);
glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);
#endif
return true;
}
inline bool setup_glew()
{
glewExperimental = GL_TRUE;
if(glewInit() != GLEW_OK) {
return false;
}
return true;
}
}
<file_sep>#pragma once
#include <cstdint>
struct Trigram {
Trigram(uint32_t x, uint32_t y, uint32_t z) :
a{x},
b{y},
c{z}
{
}
void push(uint32_t next)
{
a = b;
b = c;
c = next;
}
uint32_t a, b, c;
};
inline bool operator<(const Trigram &lhs, const Trigram &rhs)
{
return lhs.a < rhs.a || (lhs.a == rhs.a && lhs.b < rhs.b) || (lhs.a == rhs.a && lhs.b == rhs.b && lhs.c < rhs.c);
}
inline bool operator==(const Trigram &lhs, const Trigram &rhs)
{
return lhs.a == rhs.a && lhs.b == rhs.b && lhs.c == rhs.c;
}
inline bool operator!=(const Trigram &lhs, const Trigram &rhs)
{
return lhs.a != rhs.a || lhs.b != rhs.b || lhs.c != rhs.c;
}
<file_sep>#pragma once
#include "core/assert.hpp"
#include "entelechy/uid.hpp"
#include <unordered_set>
struct inventory {
using size_type = uint32_t;
static constexpr size_type DEFAULT_CAPACITY = 32;
//----------------------------------------------------------------------------//
inventory() :
contents{DEFAULT_CAPACITY},
capacity{DEFAULT_CAPACITY}
{
}
inventory(size_type initial_capacity) :
contents{initial_capacity},
capacity{initial_capacity}
{
}
//----------------------------------------------------------------------------//
std::unordered_set<uid> contents;
size_type capacity;
//----------------------------------------------------------------------------//
size_type size() const
{
return contents.size();
}
bool full() const
{
return contents.size() == capacity;
}
bool insert(uid entity)
{
VL_FORBID(has(entity), "Attempt to insert entity already present within inventory");
if(has(entity)) {
return false;
}
contents.insert(entity);
return true;
}
bool remove(uid entity)
{
VL_REQUIRE(has(entity), "Attempt to remove entity not present within inventory");
if(has(entity)) {
contents.erase(entity);
return true;
}
return false;
}
bool has(uid entity) const
{
return contents.find(entity) != contents.end();
}
//----------------------------------------------------------------------------//
};
<file_sep>#pragma once
#include "geometry/mat4.hpp"
#include "rendering/shader.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// UniformBase / Uniform
////////////////////////////////////////////////////////////////////////////////
struct IUniform {
IUniform();
bool getLocation(const char *name, const Shader &prog);
bool getLocation(const char *name, GLuint prog);
bool valid() const;
protected:
GLint loc_;
};
inline IUniform::IUniform() :
loc_{-1}
{
}
inline bool IUniform::getLocation(const char *name, const Shader &prog)
{
loc_ = prog.getUniformLocation(name);
return valid();
}
inline bool IUniform::valid() const
{
return loc_ != -1;
}
template <typename T>
struct Uniform : IUniform {};
template <>
struct Uniform<int32_t> : IUniform {
void set(int32_t i) const
{
glUniform1i(loc_, i);
}
void set(int32_t i, int32_t j) const
{
glUniform2i(loc_, i, j);
}
void set(int32_t i, int32_t j, int32_t k) const
{
glUniform3i(loc_, i, j, k);
}
void set(int32_t i, int32_t j, int32_t k, int32_t l) const
{
glUniform4i(loc_, i, j, k, l);
}
};
template <>
struct Uniform<uint32_t> : IUniform {
void set(uint32_t i) const
{
glUniform1ui(loc_, i);
}
void set(uint32_t i, uint32_t j) const
{
glUniform2ui(loc_, i, j);
}
void set(uint32_t i, uint32_t j, uint32_t k) const
{
glUniform3ui(loc_, i, j, k);
}
void set(uint32_t i, uint32_t j, uint32_t k, uint32_t l) const
{
glUniform4ui(loc_, i, j, k, l);
}
};
template <>
struct Uniform<float> : IUniform {
void set(float i) const
{
glUniform1f(loc_, i);
}
void set(float i, float j) const
{
glUniform2f(loc_, i, j);
}
void set(float i, float j, float k) const
{
glUniform3f(loc_, i, j, k);
}
void set(float i, float j, float k, float l) const
{
glUniform4f(loc_, i, j, k, l);
}
};
template <>
struct Uniform<mat4> : IUniform {
void set(const mat4 &m) const
{
glUniformMatrix4fv(loc_, 1, false, m.get());
}
};
}
<file_sep>#pragma once
#include "u32set.hpp"
#include "aspect.hpp"
#include <cstdlib>
#include <unordered_map>
#include <vector>
#include <cassert>
////////////////////////////////////////////////////////////////////////////////
// AspectPool
////////////////////////////////////////////////////////////////////////////////
class AspectPool {
template <typename A>
friend class for_each_aspect;
public:
using size_type = uint32_t;
using destructor_t = bool(AspectPool::*)(uint32_t);
using copy_t = bool(AspectPool::*)(uint32_t, uint32_t);
using clone_t = bool(AspectPool::*)(uint32_t, void*);
using queued_clear = void(AspectPool::*)();
using aspect_id_map = std::unordered_map<uint32_t, uint32_t>;
//----------------------------------------------------------[Constants]-------//
static constexpr size_type npos = ~(0);
static constexpr float RESIZE_FACTOR = 1.5f;
//-----------------------------------------[Constructors & destructors]-------//
AspectPool();
AspectPool(AspectPool &&other);
AspectPool(const AspectPool &) = delete;
AspectPool& operator=(AspectPool &&other);
~AspectPool();
//------------------------------------------[Initialisation & clearing]-------//
template <typename A>
void initialise(size_type initial_capacity = 64);
template <typename A>
void clear();
void clear();
/**
* @brief Resize the pool to hold at least new_capacity elements of type A.
* @details If new_capacity is less than the current capacity of the pool,
* or the pool is not currently initialised, the pool will not be resized.
* This method will not reinitialise if A != initialised-A, and does not
* enforce that A is of the same type as the initialised-A.
*
* @param new_capacity New pool capacity
* @tparam A Aspect type
*/
template <typename A>
void resize(size_type new_capacity);
//------------------------------------------[Allocation & deallocation]-------//
/**
* @brief Create a new aspect
* @details [long description]
*
* @param entity Entity id for aspect to be created
* @param args Constructor arguments for aspect
* @tparam A Aspect type
* @return Pointer to aspect
*/
template <typename A, typename ...Args>
A* allocate(uint32_t entity, Args &&...args);
bool allocate(uint32_t entity);
template <typename A>
bool copy(uint32_t source, uint32_t destination);
bool copy(uint32_t source, uint32_t destination);
template <typename A>
bool clone(uint32_t entity, void *original);
bool clone(uint32_t entity, void *original);
/**
* @brief Destroy an aspect in the pool
* @details [long description]
*
* @param entity Entity id for aspect to be destroyed
* @tparam A Aspect type
* @return true if destroyed, otherwise false
*/
template <typename A>
bool deallocate(uint32_t entity);
/**
* @brief Destroy an aspect in the pool
* @details [long description]
*
* @param Entity id for aspect to be destroyed
* @return true if destroyed, otherwise false
*/
bool deallocate(uint32_t entity);
//------------------------------------------------------[Aspect access]-------//
template <typename A>
A* get(uint32_t entity);
template <typename A>
const A* get(uint32_t entity) const;
void* get(uint32_t entity);
template <typename A>
A* at_index(uint32_t index);
template <typename A>
const A* at_index(uint32_t index) const;
//-----------------------------------------------------------[Metadata]-------//
/**
* @brief Check if the pool has aspect data for an entity
* @details [long description]
*
* @param entity Entity ID to check for
* @return true if aspect is present, otherwise false
*/
bool has(uint32_t entity) const;
/**
* @brief Get the number of aspects currently allocated within the pool.
* @return [description]
*/
size_type size() const;
/**
* @brief Get the total number of aspects that the pool can hold before
* reallocating.
* @return [description]
*/
size_type capacity() const;
bool empty() const;
/**
* @brief Check if the pool has been initialised
* @details [long description]
* @return true if initialised, otherwise false
*/
bool initialised() const;
private:
//-----------------------------------------------------------[Iterator]-------//
template <typename A>
struct iterator {
public:
iterator(AspectPool &pool, size_type index) :
pool_{pool},
index_{index}
{
}
iterator& operator++()
{
++index_;
return *this;
}
iterator& operator++(int)
{
auto tmp = *this;
++index_;
return tmp;
}
A& operator*()
{
return *(pool_.at_index<A>(index_));
}
A* operator->()
{
return pool_.at_index<A>(index_);
}
bool operator==(const iterator &other)
{
return index_ == other.index_;
}
bool operator!=(const iterator &other)
{
return index_ != other.index_;
}
private:
AspectPool &pool_;
size_type index_;
};
//------------------------------------------------------------[Utility]-------//
size_type default_resize_amount() const;
//------------------------------------------------------[Offset access]-------//
template <typename A>
A* at_internal(size_type size);
template <typename A>
const A* at_internal(size_type size) const;
void* at_internal(size_type size);
/**
* @brief Resize for trivially-constructible objects
*
* @param new_capacity [description]
* @tparam A [description]
*/
template <typename A>
void resize_internal(size_type new_capacity, std::true_type);
/**
* @brief Resize for non trivially-constructible objects
*
* @param new_capacity [description]
* @tparam A [description]
*/
template <typename A>
void resize_internal(size_type new_capacity, std::false_type);
template <typename A>
void set_internal_functions();
void clear_internal_functions();
//----------------------------------------------------------------------------//
u32set indices_; //<! Map of UIDs to aspects
void *data_; //<! Pointer to aspect data
queued_clear clear_; //<! Fptr to method for calling destructor on every aspect in the pool
destructor_t deallocate_; //<! Fptr to method for calling aspect destructor
copy_t copy_; //<! Fptr to method for copying aspects
clone_t clone_; //<! Fptr to method for cloning aspects
size_type size_, //<! Number of aspects currently allocated
capacity_; //<! Capacity of pool
size_type el_size_; //<! Size of each aspect, in bytes
};
//============================================================================--
// Initialisation & clearing
//============================================================================--
template <typename A>
inline void AspectPool::initialise(size_type initial_capacity)
{
if(data_ != nullptr) {
clear();
}
resize_internal<A>(initial_capacity, typename std::is_trivially_copyable<A>::type());
set_internal_functions<A>();
el_size_ = sizeof(A);
indices_.resize(initial_capacity);
}
template <typename A>
inline void AspectPool::clear()
{
for(uint32_t i = 0; i < size_; ++i) {
at_internal<A>(i)->~A();
}
if(data_) {
std::free(data_);
data_ = nullptr;
}
indices_.clear();
capacity_ = size_ = 0;
clear_internal_functions();
}
template <typename A>
inline void AspectPool::resize(size_type new_capacity)
{
if(new_capacity <= capacity_ || !initialised()) {
return;
}
resize_internal<A>(new_capacity, typename std::is_trivially_copyable<A>::type());
}
//============================================================================--
// Allocation & deallocation
//============================================================================--
template <typename A, typename ...Args>
inline A* AspectPool::allocate(uint32_t entity, Args &&...args)
{
if(indices_.has(entity)) {
return at_internal<A>(indices_[entity]);
}
if(size_ >= capacity_) {
resize_internal<A>(default_resize_amount(), typename std::is_trivially_copyable<A>::type());
}
A *ptr = new (at_internal<A>(size_)) A(std::forward<Args>(args)...);
indices_.add(entity);
++size_;
return ptr;
}
template <typename A>
inline bool AspectPool::copy(uint32_t source, uint32_t destination)
{
if(!has(source) || has(destination)) {
return false;
}
A *ptr = get<A>(source);
allocate<A>(destination, *ptr);
return true;
}
template <typename A>
inline bool AspectPool::clone(uint32_t entity, void *original)
{
return allocate<A>(entity, *static_cast<A*>(original)) != nullptr;
}
template <typename A>
inline bool AspectPool::deallocate(uint32_t entity)
{
if(!indices_.has(entity)) {
return false;
}
const size_type index = indices_[entity];
std::swap(*at_internal<A>(index), *at_internal<A>(size_-1));
at_internal<A>(--size_)->~A();
indices_.remove(entity);
return true;
}
//============================================================================--
// Aspect access
//============================================================================--
template <typename A>
inline A* AspectPool::get(uint32_t entity)
{
return indices_.has(entity) ? at_internal<A>(indices_[entity]) : nullptr;
}
template <typename A>
inline const A* AspectPool::get(uint32_t entity) const
{
return indices_.has(entity) ? at_internal<A>(indices_[entity]) : nullptr;
}
template <typename A>
inline A* AspectPool::at_index(uint32_t index)
{
return at_internal<A>(index);
}
template <typename A>
inline const A* AspectPool::at_index(uint32_t index) const
{
return at_internal<A>(index);
}
//============================================================================--
// Metadata
//============================================================================--
template <typename A>
inline A* AspectPool::at_internal(size_type size)
{
return reinterpret_cast<A*>(data_) + size;
}
template <typename A>
inline const A* AspectPool::at_internal(size_type size) const
{
return reinterpret_cast<const A*>(data_) + size;
}
//============================================================================--
// Private methods
//============================================================================--
template <typename A>
inline void AspectPool::resize_internal(size_type new_capacity, std::true_type)
{
if(capacity_ == 0) {
data_ = std::malloc(sizeof(A) * new_capacity);
capacity_ = new_capacity;
return;
}
void *new_data = std::realloc(data_, sizeof(A) * new_capacity);
if(new_data == nullptr) {
throw std::bad_alloc();
} else {
data_ = new_data;
}
capacity_ = new_capacity;
}
template <typename A>
inline void AspectPool::resize_internal(size_type new_capacity, std::false_type)
{
if(capacity_ == 0) {
data_ = std::malloc(sizeof(A) * new_capacity);
capacity_ = new_capacity;
return;
}
A *begin = at_internal<A>(0);
const A *end = at_internal<A>(size_);
void *old_data = data_;
data_ = std::malloc(sizeof(A) * new_capacity);
A *new_begin = at_internal<A>(0);
while(begin != end) {
new (new_begin++) A(std::move(*begin++));
}
std::free(old_data);
capacity_ = new_capacity;
}
template <typename A>
inline void AspectPool::set_internal_functions()
{
clear_ = &AspectPool::clear<A>;
deallocate_ = &AspectPool::deallocate<A>;
// disabled until we handle move-only aspects
// copy_ = &AspectPool::copy<A>;
// clone_ = &AspectPool::clone<A>;
}
////////////////////////////////////////////////////////////////////////////////
// for_each_aspect
////////////////////////////////////////////////////////////////////////////////
/**
* @brief For iterating over the aspects in a pool, irrespective
* of entity order
*
* @tparam A Aspect type
*/
template <typename A>
class for_each_aspect {
public:
using size_type = AspectPool::size_type;
//----------------------------------------------------------------------------//
for_each_aspect(AspectPool &pool) :
pool_{pool},
end_{pool.size()}
{
}
AspectPool::iterator<A> begin()
{
return AspectPool::iterator<A>(pool_, 0);
}
AspectPool::iterator<A> end()
{
return AspectPool::iterator<A>(pool_, end_);
}
private:
AspectPool &pool_;
size_type end_;
};
<file_sep>#pragma once
#include "core/platform.hpp"
#ifdef VIRGIL_DEBUG
#include "core/format.hpp"
#include <iostream>
#include <memory>
#include <exception>
namespace virgil {
struct AssertionFailure : public std::exception {
template <typename ...Args>
AssertionFailure(const char *fmt, Args &&...args) :
std::exception{},
what_{fmt::format(fmt, std::forward<Args>(args)...)}
{
}
AssertionFailure(const std::string &what) :
std::exception{},
what_{what}
{
}
virtual const char* what() const noexcept final
{
return what_.c_str();
}
private:
std::string what_;
};
struct AlignmentFailure : public AssertionFailure {
template <typename ...Args>
AlignmentFailure(Args &&...args) :
AssertionFailure{std::forward<Args>(args)...}
{
}
};
inline void vl_assert_impl(const char *expr, const char *function, const char *file, uint32_t line, const char *msg)
{
throw AssertionFailure(
"Assertion failure: {} at {} in {}, line {} with expression \"{}\"",
msg, function, file, line, expr
);
}
template <typename ...Args>
inline void vl_assert_variadic(const char *expr, const char *function, const char *file, uint32_t line, const char *msg, Args &&...args)
{
throw AssertionFailure(
"Assertion failure at {} in {}:{} with expression \"{}\" {}",
function, file, line, expr,
fmt::format(msg, std::forward<Args>(args)...)
);
}
template <typename T>
inline void vl_assert_aligned(void *ptr, const char *type_name, const char *function, const char *file, uint32_t line)
{
const size_t aligned = ((uintptr_t)ptr + (alignof(T) - 1)) & ~(alignof(T) - 1);
if(aligned != reinterpret_cast<uintptr_t>(ptr)) {
throw AlignmentFailure(
"Alignment check failure for type {}: pointer at {} cannot"
" accommodate alignment requirement {} at {} in {}:{}",
type_name, ptr, alignof(T), function, file, line
);
}
}
}
#define VL_ASSERT(expr, msg) (VL_LIKELY(expr) ? ((void)0) : \
virgil::vl_assert_impl(#expr, VL_CURRENT_FUNCTION, __FILE__, __LINE__, msg))
#define VL_VASSERT(expr, msg, ...) (VL_LIKELY(expr) ? ((void)0) : \
virgil::vl_assert_variadic(#expr, VL_CURRENT_FUNCTION, __FILE__, __LINE__, msg, __VA_ARGS__))
#define VL_ASSERT_ALIGNED(type, ptr) \
virgil::vl_assert_aligned<type>(ptr, #type, VL_CURRENT_FUNCTION, __FILE__, __LINE__)
#define VL_REQUIRE(expr, msg) VL_ASSERT(expr, msg)
#define VL_FORBID(expr, msg) VL_ASSERT(!(expr), msg)
#define VL_FAIL(msg) \
virgil::vl_assert_impl("VL_FAIL", VL_CURRENT_FUNCTION, __FILE__, __LINE__, msg)
#else
#define VL_ASSERT(...)
#define VL_VASSERT(...)
#define VL_ASSERT_ALIGNED(...)
#define VL_REQUIRE(...)
#define VL_FORBID(...)
#define VL_FAIL(...)
#endif
#define VL_STATIC_ASSERT(...) static_assert(__VA_ARGS__, #__VA_ARGS__)
<file_sep>/**
* @file vec2.hpp
* @date 2015-08-18
* @detail 2D vector class
*/
#pragma once
#include <cmath>
#include <cstdint>
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// vec2
////////////////////////////////////////////////////////////////////////////////
template <typename T>
class vec2 {
public:
using value_type = T;
//----------------------------------------------------------------------------//
constexpr vec2();
constexpr vec2(value_type x, value_type y);
vec2(const vec2 &other);
vec2(vec2 &&vector);
vec2& operator=(vec2 other);
void set(value_type x, value_type y);
template <typename U>
vec2<U> cast_to();
value_type dot(const vec2 &other) const;
value_type cross(const vec2 &other) const;
value_type squared_length() const;
value_type length() const;
vec2 to_point() const;
vec2& normalize();
operator bool() const;
//----------------------------------------------------------------------------//
value_type x,
y;
};
template <typename T>
inline T dot(const vec2<T> &lhs, const vec2<T> &rhs)
{
return (lhs.x * rhs.x) + (lhs.y * rhs.y);
}
template <typename T>
inline T cross(const vec2<T> &lhs, const vec2<T> &rhs)
{
return (lhs.x * rhs.y) - (lhs.y * rhs.x);
}
//============================================================================--
// Constructors
//============================================================================--
template <typename T>
constexpr vec2<T>::vec2() :
x{T()},
y{T()}
{
}
template <typename T>
constexpr vec2<T>::vec2(T x, T y) :
x{x},
y{y}
{
}
template <typename T>
vec2<T>::vec2(const vec2 &other) :
x{other.x},
y{other.y}
{
}
template <typename T>
vec2<T>::vec2(vec2 &&other) :
x{other.x},
y{other.y}
{
}
template <typename T>
vec2<T>& vec2<T>::operator=(vec2<T> other)
{
this->x = other.x;
this->y = other.y;
return *this;
}
//============================================================================--
// Setters
//============================================================================--
template <typename T>
void vec2<T>::set(T x, T y)
{
this->x = x;
this->y = y;
}
template <typename T>
template <typename U>
vec2<U> vec2<T>::cast_to()
{
return {static_cast<U>(x), static_cast<U>(y)};
}
//============================================================================--
// Arithmetic operators
//============================================================================--
template <typename T>
inline vec2<T> operator+(vec2<T> &vec, T t)
{
vec2<T> ret{vec};
ret.x += t;
ret.y += t;
return ret;
}
template <typename T>
inline vec2<T>& operator+=(vec2<T> &vec, T t)
{
vec.x += t;
vec.y += t;
return vec;
}
template <typename T>
inline vec2<T>& operator+=(vec2<T> &lhs, vec2<T> &rhs)
{
lhs.x += rhs.x;
lhs.y += rhs.y;
return lhs;
}
template <typename T, typename U>
inline vec2<T>& operator+=(vec2<T> &vec, U val)
{
vec.x += val;
vec.y += val;
return vec;
}
template <typename T>
inline vec2<T>& operator-=(vec2<T> &vec, T t)
{
vec.x -= t;
vec.y -= t;
return vec;
}
template <typename T, typename U>
inline vec2<T>& operator-=(vec2<T> &vec, U val)
{
vec.x -= val;
vec.y -= val;
return vec;
}
template <typename T>
inline vec2<T>& operator*=(vec2<T> &vec, T t)
{
vec.x *= t;
vec.y *= t;
return vec;
}
template <typename T, typename U>
inline vec2<T>& operator*=(vec2<T> &vec, U val)
{
vec.x *= val;
vec.y *= val;
return vec;
}
template <typename T>
inline vec2<T>& operator/=(vec2<T> &vec, T t)
{
vec.x /= t;
vec.y /= t;
return vec;
}
template <typename T, typename U>
inline vec2<T>& operator/=(vec2<T> &vec, U val)
{
vec.x /= val;
vec.y /= val;
return vec;
}
//============================================================================--
// Vector math functions
//============================================================================--
template <typename T>
T vec2<T>::dot(const vec2 &other) const
{
return dot(*this, other);
}
template <typename T>
T vec2<T>::cross(const vec2 &other) const
{
return cross(*this, other);
}
template <typename T>
T vec2<T>::squared_length() const
{
return this->x * this->x + this->y * this->y;
}
template <typename T>
T vec2<T>::length() const
{
return std::sqrt(squared_length());
}
template <typename T>
vec2<T> vec2<T>::to_point() const
{
return vec2{this->x, this->y};
}
template <typename T>
vec2<T>& vec2<T>::normalize()
{
if(!length()) {
return *this;
}
return (*this) /= length();
}
//============================================================================--
// boolean operators
//============================================================================--
template <typename T>
inline bool operator==(const vec2<T> &left, const vec2<T> &right)
{
return left.x == right.x && left.y == right.y;
}
template <typename T>
inline bool operator!=(const vec2<T> &left, const vec2<T> &right)
{
return left.x != right.x || left.y != right.y;
}
template <typename T>
inline vec2<T> operator+(const vec2<T> &left, const vec2<T> &right)
{
return {left.x + right.x, left.y + right.y};
}
template <typename T>
inline vec2<T> operator-(const vec2<T> &left, const vec2<T> &right)
{
return {left.x - right.x, left.y - right.y};
}
//============================================================================--
// Convenience type-aliases
//============================================================================--
using vec2f = vec2<float>;
using vec2d = vec2<double>;
using vec2i = vec2<int>;
using vec2u = vec2<uint32_t>;
template <>
inline vec2<float>::operator bool() const
{
return !std::isnan(x) && !std::isnan(y);
}
}
<file_sep>#pragma once
#include "core/opengl.hpp"
#include "geometry/vec2.hpp"
#include "console/root.hpp"
#include "shaders/console_shader.hpp"
#include "rendering/texture.hpp"
namespace virgil {
void echo_key(GLFWwindow *, int key, int scancode, int action, int);
inline void Terminal::pollEvents()
{
glfwPollEvents();
}
struct Terminal {
public:
static RootConsole *root;
static constexpr int MAX_TERM_W = 160;
static constexpr int MAX_TERM_H = 100;
//----------------------------------------------------------------------------//
Terminal(uint16_t width, uint16_t height, const char *title);
bool initRoot(std::string console_font = "terminal.png", const Colour &default_fore = col::salt, const Colour &default_back = col::slate);
/**
* @brief Check if window is open
*/
bool isOpen() const;
/**
* @brief Close window
*/
bool closeWindow();
/**
* @brief Call glfwSwapBuffers on window
*/
void swapBuffers() const;
void flush();
void pollEvents();
int getKey(int key);
vec2d getMouse();
bool mouseInBounds();
GLFWwindow* window()
{
return win_;
}
private:
void init() const;
bool setConsoleFont(const char *path);
bool setupWindow(int width, int height, const char *title = "virgil");
//----------------------------------------------------------------------------//
RootConsole root_; //<! Root console
TextureAtlas console_texture_; //<! Root console texture
ConsoleShader console_shader_; //<! Root console shader
GLFWwindow *win_; //<! Pointer to active window
std::string title_; //<! Window title
int framebuffer_w_, //<! Window framebuffer width
framebuffer_h_; //<! Window framebuffer height
uint16_t root_width_, //<! Root console width, in cells
root_height_; //<! Root console width, in cells
uint16_t win_width_, //<! Window width
win_height_; //<! Window height
};
}
<file_sep>set(virgil_source_dir ${CMAKE_CURRENT_SOURCE_DIR})
set(virgil_source
"${virgil_source_dir}/core/stb_image.cpp"
"${virgil_source_dir}/core/noise.cpp"
"${virgil_source_dir}/utils/image.cpp"
"${virgil_source_dir}/geometry/mat4.cpp"
"${virgil_source_dir}/rendering/shader.cpp"
"${virgil_source_dir}/rendering/texture.cpp"
"${virgil_source_dir}/rendering/terminal.cpp"
"${virgil_source_dir}/rendering/shaders/flat_shader.cpp"
"${virgil_source_dir}/rendering/shaders/console_shader.cpp"
"${virgil_source_dir}/console/console.cpp"
"${virgil_source_dir}/console/root.cpp"
"${virgil_source_dir}/entelechy/aspect_pool.cpp"
"${virgil_source_dir}/entelechy/entity_manager.cpp"
"${virgil_source_dir}/entelechy/system_manager.cpp"
"${virgil_source_dir}/entelechy/space.cpp"
"${virgil_source_dir}/world/name_generator.cpp"
"${virgil_source_dir}/driver.cpp"
PARENT_SCOPE)
set(virgil_main
"${virgil_source_dir}/main.cpp"
PARENT_SCOPE)
<file_sep>#pragma once
#include "entelechy/entity.hpp"
#include "entelechy/space.hpp"
template <typename A, typename ...Args>
inline A* Entity::add(Args &&...args) const
{
return space_->add<A>(id_, std::forward<Args>(args)...);
}
template <typename A>
inline void Entity::remove() const
{
space_->remove<A>(id_);
}
template <typename A>
inline A* Entity::get()
{
return space_->get<A>(id_);
}
template <typename ...Args>
inline bool Entity::has()
{
return space_->has<Args...>(id_);
}
inline void Entity::destroy()
{
space_->destroyEntity(id_);
}
inline bool Entity::valid() const
{
return space_->valid(id_);
}
<file_sep>#include "space.hpp"
#include "entity_view.hpp"
template <typename ...Aspects>
inline AspectFilter<Aspects...> Space::entitiesWith(aspect_ptr<Aspects> &...ptrs)
{
return {*this, ptrs...};
}
template <typename ...Aspects>
inline EntityFilter Space::entitiesWith(Entity &entity)
{
return {*this, entity, maskFor<Aspects...>()};
}
<file_sep>#pragma once
#include "core/format.hpp"
#include <algorithm>
#include <exception>
namespace virgil {
template <typename ArrayType>
struct array_2d_view;
////////////////////////////////////////////////////////////////////////////////
// array_2d
////////////////////////////////////////////////////////////////////////////////
template <typename T, uint32_t X, uint32_t Y>
class array_2d {
public:
using type = array_2d<T, X, Y>;
friend struct array_2d_view<type>;
//----------------------------------------------------------------------------//
using size_type = uint32_t;
static constexpr size_type x_dimension = X;
static constexpr size_type x_lim = X - 1;
static constexpr size_type y_dimension = Y;
static constexpr size_type array_size = X * Y;
//----------------------------------------------------------------------------//
using value_type = T;
using pointer = T*;
using reference = T&;
using const_pointer = const T*;
using const_reference = const T&;
using array_type = T(&)[array_size];
using const_array_type = const T(&)[array_size];
using iterator = pointer;
using const_iterator = const_pointer;
//----------------------------------------------------------------------------//
constexpr array_2d();
constexpr array_2d(T v);
array_2d(const array_2d &other);
array_2d(array_2d &&other);
//----------------------------------------------------------------------------//
reference operator()(size_type x, size_type y);
const_reference operator()(size_type x, size_type y) const;
reference operator[](size_type index);
const_reference operator[](size_type index) const;
reference at(size_type x, size_type y);
const_reference at(size_type x, size_type y) const;
reference at(size_type index);
const_reference at(size_type index) const;
constexpr size_type size() const;
constexpr size_type capacity() const;
iterator begin();
iterator end();
const_iterator begin() const;
const_iterator end() const;
reference front();
reference back();
pointer data();
const_pointer data() const;
void swap(array_2d &other);
template <void(*F)(size_type, size_type, const_reference)>
void for_each()
{
for(size_type i = 0; i < x_dimension; ++i) {
for(size_type j = 0; j < y_dimension; ++j) {
F(i, j, data_[idx(i, j)]);
}
}
}
void for_each(std::function<void(size_type, size_type, const_reference)> func)
{
for(size_type i = 0; i < x_dimension; ++i) {
for(size_type j = 0; j < y_dimension; ++j) {
func(i, j, data_[idx(i, j)]);
}
}
}
private:
constexpr size_type idx(size_type x, size_type y) const
{
return (y * x_dimension) + x;
}
//----------------------------------------------------------------------------//
T data_[array_size];
};
template <typename T, uint32_t X, uint32_t Y>
constexpr array_2d<T, X, Y>::array_2d() :
data_{T()}
{
}
template <typename T, uint32_t X, uint32_t Y>
constexpr array_2d<T, X, Y>::array_2d(T v) :
data_{v}
{
}
template <typename T, uint32_t X, uint32_t Y>
array_2d<T, X, Y>::array_2d(const array_2d &other) :
data_{}
{
std::copy_n(other.begin(), array_size, data_);
}
template <typename T, uint32_t X, uint32_t Y>
array_2d<T, X, Y>::array_2d(array_2d &&other) :
data_{T()}
{
swap(other);
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::operator()(size_type x, size_type y) -> reference
{
return data_[idx(x, y)];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::operator()(size_type x, size_type y) const -> const_reference
{
return data_[idx(x, y)];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::operator[](size_type index) -> reference
{
return data_[index];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::operator[](size_type index) const -> const_reference
{
return data_[index];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::at(size_type x, size_type y) -> reference
{
if(idx(x,y) >= array_size) {
throw std::out_of_range(fmt::format("array_2d::at({}, {})", x, y));
}
return data_[idx(x, y)];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::at(size_type x, size_type y) const -> const_reference
{
if(idx(x,y) >= array_size) {
throw std::out_of_range(fmt::format("array_2d::at({}, {})", x, y));
}
return data_[idx(x,y)];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::at(size_type index) -> reference
{
if(index >= array_size) {
throw std::out_of_range(fmt::format("array_2d::at({})", index));
}
return data_[index];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::at(size_type index) const -> const_reference
{
if(index >= array_size) {
throw std::out_of_range(fmt::format("array_2d::at({})", index));
}
return data_[index];
}
template <typename T, uint32_t X, uint32_t Y>
constexpr auto array_2d<T, X, Y>::size() const -> size_type
{
return array_size;
}
template <typename T, uint32_t X, uint32_t Y>
constexpr auto array_2d<T, X, Y>::capacity() const -> size_type
{
return array_size;
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::begin() -> iterator
{
return data_;
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::end() -> iterator
{
return &data_[array_size];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::begin() const -> const_iterator
{
return data_;
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::end() const -> const_iterator
{
return &data_[array_size];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::front() -> reference
{
return data_[0];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::back() -> reference
{
return data_[array_size > 0 ? array_size - 1 : 0];
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::data() -> pointer
{
return data_;
}
template <typename T, uint32_t X, uint32_t Y>
auto array_2d<T, X, Y>::data() const -> const_pointer
{
return data_;
}
template <typename T, uint32_t X, uint32_t Y>
void array_2d<T, X, Y>::swap(array_2d &other)
{
std::swap_ranges(begin(), end(), other.begin());
}
////////////////////////////////////////////////////////////////////////////////
//
////////////////////////////////////////////////////////////////////////////////
template <typename T, uint32_t X, uint32_t Y>
inline bool operator==(const array_2d<T,X,Y> &lhs, const array_2d<T,X,Y> &rhs)
{
std::equal(lhs.begin(), lhs.end(), rhs.begin());
}
template <typename T, uint32_t X, uint32_t Y>
inline bool operator!=(const array_2d<T,X,Y> &lhs, const array_2d<T,X,Y> &rhs)
{
!(lhs == rhs);
}
}
<file_sep>#include "billboard_shader.hpp"
void BillboardShader::init(const char *vert_source, const char *frag_source)
{
glUseProgram(0);
program_ = glCreateProgram();
vertex_ = glCreateShader(GL_VERTEX_SHADER);
fragment_ = glCreateShader(GL_FRAGMENT_SHADER);
compile(vertex_, vert_source);
compile(fragment_, frag_source);
glAttachShader(program_, vertex_);
glAttachShader(program_, fragment_);
link();
setUniforms();
}
void BillboardShader::setUniforms()
{
glUseProgram(program_);
tfb_.getLocation("fb_tex", *this);
tfb_.set(0);
glUseProgram(0);
}
void BillboardShader::spec() const
{
GLint posAttrib = glGetAttribLocation(program_, "position");
glEnableVertexAttribArray(posAttrib);
glVertexAttribPointer(posAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), 0);
GLint texAttrib = glGetAttribLocation(program_, "texcoord");
glEnableVertexAttribArray(texAttrib);
glVertexAttribPointer(texAttrib, 2, GL_FLOAT, GL_FALSE, 4 * sizeof(float), (void*)(2 * sizeof(float)));
}
<file_sep>#pragma once
#include "geometry/vec2.hpp"
#include "geometry/vec3.hpp"
#include "core/random.hpp"
#include <random>
#include <array>
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// PerlinNoise
////////////////////////////////////////////////////////////////////////////////
/**
* @brief Perlin noise generator
* @details Based on http://mrl.nyu.edu/~perlin/noise/
*/
class PerlinNoise {
public:
//----------------------------------------------------------------------------//
PerlinNoise();
PerlinNoise(uint32_t seed);
/**
* @brief Get noise for a given coordinate
*
* @param x x-coordinate
* @param y y-coordinate
* @param z z-coordinate
* @return noise value
*/
float getNoise(float x, float y, float z = 1);
/**
* @brief Reseed the generator and regenerate the permutation table
*
* @param seed New seed value
*/
void reseed(uint32_t seed);
/**
* @brief Reseed the generator and regenerate the permutation table
*/
void reseed();
/**
* @brief Debug function - print permutation table
*/
void printPerm() const;
private:
/**
* @brief Initialise permutation table
*/
void init();
/**
* @brief Fade function
* @details The fade function or 'ease curve' is used to smooth out
* transitions as t approaches 1.0 or 0.0
*
* @param t Input value
* @return Eased value
*/
float fade(const float t) const;
/**
* @brief Cosine interpolation
*
* @param t Parameter
* @param a Input a
* @param b Input b
* @return interpolated value
*/
float lerp(const float t, const float a, const float b) const;
/**
* @brief Linear interpolation
*
* @param t Parameter
* @param a Input a
* @param b Input b
* @return interpolated value
*/
float lerpFast(const float t, const float a, const float b) const;
/**
* @brief Generate pseudorandom value from permutation table
* @detail 'grad' here refers to the pseudorandom gradient vector
* generated for the point x, y, z
*
* @param hash Value from permutation table
* @param x x-coordinate
* @param y y-coordinate
* @param z z-coordinate
* @return pseudorandom value
*/
float grad(int hash, const float x, const float y, const float z) const;
//----------------------------------------------------------------------------//
std::array<int, 512> permutation_;
pcg32 rand_;
};
//============================================================================--
//
//============================================================================--
inline float PerlinNoise::fade(const float t) const
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
inline float PerlinNoise::lerp(const float t, const float a, const float b) const
{
const float f = (1.0 - std::cos(t * M_PI)) * 0.5;
return a * (1.0 - f) + b * f;
}
inline float PerlinNoise::lerpFast(const float t, const float a, const float b) const
{
return (1.0 - t) * a + t * b;
}
inline float PerlinNoise::grad(int hash, const float x, const float y, const float z) const
{
const int h = hash & 15;
const float u = h < 8 ? x : y,
v = h < 4 ? y : h == 12 || h == 14 ? x : z;
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
}
////////////////////////////////////////////////////////////////////////////////
// SimplexNoise
////////////////////////////////////////////////////////////////////////////////
/*
* A speed-improved simplex noise algorithm for 2D, 3D and 4D, originally
* written in Java. This code was placed in the public domain by its
* original author, <NAME>. You may use it as you see fit, but
* attribution is appreciated.
*
* Version 2012-03-09: Based on example code by <NAME>
* (<EMAIL>).
* Optimisations by <NAME> (<EMAIL>).
* Better rank ordering method by <NAME> in 2012.
*
*/
class SimplexNoise {
public:
using vec2_type = vec2<float>;
using vec3_type = vec3<float>;
//----------------------------------------------------------------------------//
SimplexNoise();
SimplexNoise(uint32_t seed);
float getNoise(const float x, const float y);
private:
static constexpr float dot(vec2d g, float x, float y);
static constexpr float dot(vec3_type g, float x, float y, float z = 1.0);
void init();
//----------------------------------------------------------------------------//
std::array<uint8_t, 512> permutation_;
pcg32 rand_;
vec3_type grad3[12] = {
{1,1,0}, {-1,1,0}, {1,-1,0}, {-1,-1,0},
{1,0,1}, {-1,0,1}, {1,0,-1}, {-1,0,-1},
{0,1,1}, {0,-1,1}, {0,1,-1}, {0,-1,-1}
};
static constexpr float F2 = 0.3660254037844386;
static constexpr float G2 = 0.21132486540518713;
static constexpr float F3 = 1.0 / 3.0;
static constexpr float G3 = 1.0 / 6.0;
static constexpr float F4 = 0.30901699437494745;
static constexpr float G4 = 0.1381966011250105;
};
inline constexpr auto SimplexNoise::dot(vec2d g, const float x, const float y) -> float
{
return g.x * x + g.y * y;
}
inline constexpr auto SimplexNoise::dot(vec3_type g, const float x, const float y, const float z) -> float
{
return g.x * x + g.y * y + g.z * z;
}
////////////////////////////////////////////////////////////////////////////////
// FBM Noise
////////////////////////////////////////////////////////////////////////////////
template <class NoiseType>
struct FBMNoise : public NoiseType {
using noise_type = NoiseType;
FBMNoise() = default;
FBMNoise(uint32_t seed);
float generate(const uint8_t octaves, const float persistence, const float scale, const float x, const float y);
};
template <typename NT>
inline FBMNoise<NT>::FBMNoise(uint32_t seed) :
noise_type{seed}
{
}
template <typename NT>
float FBMNoise<NT>::generate(const uint8_t octaves, const float persistence, const float scale, const float x, const float y)
{
float total = 0.f,
frequency = scale,
amplitude = 1.f,
amplitude_max = 0.f;
for(uint8_t i = 0; i < octaves; i++) {
total += this->getNoise(x * frequency, y * frequency) * amplitude;
frequency *= 2.f;
amplitude_max += amplitude;
amplitude *= persistence;
}
return total / amplitude_max;
}
using SimplexFBM = FBMNoise<SimplexNoise>;
using PerlinFBM = FBMNoise<PerlinNoise>;
}
<file_sep>#pragma once
#include "billboard_shader.hpp"
////////////////////////////////////////////////////////////////////////////////
// Billboard
////////////////////////////////////////////////////////////////////////////////
class Billboard {
public:
Billboard();
Billboard(uint16_t width, uint16_t height);
void init(uint16_t width, uint16_t height);
void bindTex();
void bindQuad();
void draw(GLuint use_fb = 0);
void bindFramebuffer();
private:
BillboardShader shad_; //<! Billboard shader
GLuint tex_col_buffer_; //<! Framebuffer colour buffer
GLuint frame_buffer_; //<! Framebuffer object
GLuint vbo_quad_, //<! VBO for billboard mesh
vao_quad_; //<! VAO for billboard mesh
uint16_t width_, //<! Billboard width
height_; //<! Billboard height
float quad_vertices_[24] //<! Billboard mesh
= {
-1.f, -1.f, 0.f, 0.f,
1.f, -1.f, 1.f, 0.f,
-1.f, 1.f, 0.f, 1.f,
-1.f, 1.f, 0.f, 1.f,
1.f, -1.f, 1.f, 0.f,
1.f, 1.f, 1.f, 1.f
};
};
<file_sep>#pragma once
#include "entelechy/typedef.hpp"
#include "entelechy/aspect_pool.hpp"
#include "entelechy/aspect_ptr.hpp"
#include "entelechy/aspect_proto.hpp"
#include "entelechy/entity_manager.hpp"
#include "entelechy/system_manager.hpp"
#include "entelechy/event_manager.hpp"
#include "entelechy/message.hpp"
#include <unordered_map>
struct EntityCreated { uid id; };
class Space {
friend class space_iterator;
public:
using size_type = uint32_t;
using pool_name_map = std::unordered_map<std::string, aspect_id>;
//----------------------------------------------------------------------------//
Space(EventManager &e_man, MessageHandler &msg_hand);
Space(const Space &) = delete;
~Space() = default;
//----------------------------------------------------------------------------//
/**
* @brief Destroy all entities and clear all initialised pools
*/
void clear();
/**
* @brief Get the number of live entities in this Space
* @details Calls EntityManager::size()
* @return Number of live entities
*/
size_type size() const;
void tick()
{
systems_.tick(*event_man_);
event_man_->sync();
}
Entity createEntity();
bool destroyEntity(uid entity);
bool valid(uid entity) const;
//-----------------------------------------------------[System management]----//
template <typename S, typename ...Args>
void addSystem(Args &&...args)
{
systems_.add<S>(std::forward<Args>(args)...);
}
template <typename S>
S* getSystem()
{
if(systems_.has<S>()) {
return systems_.system<S>();
}
return nullptr;
}
//-------------------------------------------------------[Pool management]----//
/**
* @brief Create a pool in the next open pool slot
* @details [long description]
*
* @param name [description]
* @param initial_size [description]
*
* @return [description]
*/
template <typename A>
AspectPool& createPool(std::string name, size_type initial_size = 64);
/**
* @brief Get a pool by type
* @details [long description]
* @return [description]
*/
template <typename A>
AspectPool& getPool();
/**
* @brief Get a pool by name
* @details [long description]
*
* @param aspect_name [description]
* @return [description]
*/
AspectPool* getPool(std::string aspect_name);
/**
* @brief Clear a pool
* @details [long description]
*
* @tparam A [description]
*/
template <typename A>
void clearPool();
//--------------------------------------------------[Aspect management]-------//
template <typename A, typename ...Args>
A* add(uid entity, Args &&...args);
template <typename A>
void remove(uid entity);
template <typename A>
A* get(uid entity);
template <typename A>
bool has(uid entity) const;
template <typename A0, typename A1, typename ...An>
bool has(uid entity) const;
bool has(uid entity, aspect_id id) const;
template <typename ...Args>
aspect_mask maskFor();
//----------------------------------------------------------[Iteration]-------//
template <typename ...Aspects>
AspectFilter<Aspects...> entitiesWith(aspect_ptr<Aspects> &...ptrs);
template <typename ...Aspects>
EntityFilter entitiesWith(Entity &entity);
LiveEntityFilter entities(Entity &entity);
//----------------------------------------------------------[Iteration]-------//
Entity clone(const AspectPrototype &proto)
{
auto e = createEntity();
for(aspect_id i = 0; i < top_aspect_id_; ++i) {
if(proto.protos_[i]) {
pools_[i].clone(e.id(), proto.protos_[i]->get_raw());
}
}
return e;
}
void setEventManager(EventManager &new_eman, bool force_sync)
{
if(force_sync) {
event_man_->sync();
}
event_man_ = &new_eman;
}
MessageHandler& msg_handler()
{
return *msg_hand_;
}
private:
//----------------------------------------------------[Implementations]-------//
AspectPool pools_[MAX_ASPECTS]; //<! Array of pools
EntityManager entities_; //<! Entity manager
SystemManager systems_; //<! System manager
EventManager *event_man_;
MessageHandler *msg_hand_;
//----------------------------------------------------[Aspect metadata]-------//
pool_name_map aspect_names_; //<! Map of aspect_id to aspect name
aspect_id top_aspect_id_; //<! Highest current aspect_id
};
//============================================================================--
// Pool management
//============================================================================--
template <typename A>
inline AspectPool& Space::createPool(std::string name, size_type initial_size)
{
AspectPool &pool = pools_[Aspect::id<A>()];
if(Aspect::id<A>() > top_aspect_id_) {
top_aspect_id_ = Aspect::id<A>();
}
if(pool.initialised()) {
return pool;
}
aspect_names_[name] = Aspect::id<A>();
pool.template initialise<A>(initial_size);
return pool;
}
template <typename A>
inline AspectPool& Space::getPool()
{
return pools_[Aspect::id<A>()];
}
inline AspectPool* Space::getPool(std::string aspect_name)
{
auto iter = aspect_names_.find(aspect_name);
if(iter == aspect_names_.end()) {
return nullptr;
}
return &pools_[iter->second];
}
template <typename A>
inline void Space::clearPool()
{
pools_[Aspect::id<A>()].template clear<A>();
}
//============================================================================--
// Aspect management
//============================================================================--
template <typename A, typename ...Args>
inline A* Space::add(uid entity, Args &&...args)
{
pools_[Aspect::id<A>()].template allocate<A>(entity.id, std::forward<Args>(args)...);
if(entities_.has<A>(entity)) {
return pools_[Aspect::id<A>()].template get<A>(entity.id);
}
auto new_aspect = pools_[Aspect::id<A>()].template allocate<A>(entity.id, std::forward<Args>(args)...);
entities_.set<A>(entity);
return new_aspect;
}
template <typename A>
inline void Space::remove(uid entity)
{
if(!has<A>(entity)) return;
pools_[Aspect::id<A>()].template deallocate<A>(entity.id);
entities_.reset<A>(entity);
}
template <typename A>
inline A* Space::get(uid entity)
{
return pools_[Aspect::id<A>()].template get<A>(entity.id);
}
template <typename A>
inline bool Space::has(uid entity) const
{
return entities_.has<A>(entity);
}
template <typename A0, typename A1, typename ...An>
inline bool Space::has(uid entity) const
{
return entities_.template has<A0, A1, An...>(entity);
}
inline bool Space::has(uid entity, aspect_id id) const
{
return entities_.has(entity, id);
}
//============================================================================--
// Misc
//============================================================================--
template <typename ...Args>
inline aspect_mask Space::maskFor()
{
aspect_mask mask;
int _[]{0, (mask.set(Aspect::id<Args>()), 0)...};
(void)_;
return mask;
}
<file_sep>#pragma once
#include "rendering/shaders/flat_shader.hpp"
#include "rendering/shaders/console_shader.hpp"
<file_sep>#include "terminal.hpp"
#include "config.hpp"
#include "core/format.hpp"
#include "utils/image.hpp"
#include "utils/numeric.hpp"
namespace virgil {
void echo_key(GLFWwindow *, int key, int scancode, int action, int)
{
static const char *action_name[] {
"PRESS",
"RELEASE",
"REPEAT"
};
fmt::printf("%s: ", action == GLFW_PRESS ? action_name[0] : action == GLFW_RELEASE ? action_name[1] : action_name[2]);
fmt::printf("%d -> %c [%d]\n", key, key, scancode);
}
RootConsole *Terminal::root = nullptr;
Terminal::Terminal(uint16_t width, uint16_t height, const char *title) :
win_{nullptr},
title_{title},
framebuffer_w_{0},
framebuffer_h_{0},
root_width_{clamp<uint16_t>(width, 0, MAX_TERM_W)},
root_height_{clamp<uint16_t>(height, 0, MAX_TERM_H)},
win_width_{0},
win_height_{0}
{
fmt::print(
"Virgil v{} - {}\n", VIRGIL_VER_STR, DEBUG_STATUS_STR
);
init();
}
bool Terminal::isOpen() const
{
return !glfwWindowShouldClose(win_);
}
bool Terminal::closeWindow()
{
if(win_) {
glfwSetWindowShouldClose(win_, 1);
return true;
}
return false;
}
void Terminal::swapBuffers() const
{
glfwSwapBuffers(win_);
}
void Terminal::flush()
{
glClear(GL_COLOR_BUFFER_BIT);
root_.refresh();
root_.draw();
swapBuffers();
}
int Terminal::getKey(int key)
{
return glfwGetKey(win_, key);
}
vec2<double> Terminal::getMouse()
{
vec2<double> pos;
glfwGetCursorPos(win_, &pos.x, &pos.y);
return pos;
}
bool Terminal::mouseInBounds()
{
auto mouse_pos = getMouse();
return (mouse_pos.x > 0.0
&& mouse_pos.y > 0.0
&& mouse_pos.x < (double)win_width_
&& mouse_pos.y < (double)win_height_);
}
bool Terminal::initRoot(std::string console_font, const Colour &default_fore, const Colour &default_back)
{
win_width_ = root_width_ * 8;
win_height_ = root_height_ * 8;
if(!setupWindow(win_width_, win_height_, title_.c_str())) {
return false;
}
glDisable(GL_DEPTH_TEST);
fmt::print("Loading {}: {}x{}\n", console_font, 128, 128);
fmt::print(" Glyphs: {} rows, {} columns - {}px\n", 16, 16, 8);
if(!setConsoleFont(console_font.c_str())) {
return false;
}
/** --- uhhhhhhhhh
* so basically if we're on a retina screen we'll have a framebuffer
* larger than the window; we need to get the the size and set it
* here
*/
glfwGetFramebufferSize(win_, &framebuffer_w_, &framebuffer_h_);
fmt::print("Framebuffer size: {}x{}\n", framebuffer_w_, framebuffer_h_);
console_shader_.load(root_width_, root_height_);
root_.setDefaultFore(default_fore);
root_.setDefaultBack(default_back);
root_.resize(root_width_, root_height_);
root_.init();
root_.setShader(console_shader_);
root_.setTexture(console_texture_);
Terminal::root = &root_;
return true;
}
//
void Terminal::init() const
{
gl::setup_glfw();
}
bool Terminal::setConsoleFont(const char *path)
{
Image con_img(path, Image::RGBA);
if(!con_img.valid()) return false;
con_img.setKeyColour({0,0,0});
console_texture_.generate(con_img.data(), con_img.width(), con_img.height());
return true;
}
bool Terminal::setupWindow(int width, int height, const char *title)
{
win_ = glfwCreateWindow(width, height, title, nullptr, nullptr);
if(!win_) {
return false;
}
glfwMakeContextCurrent(win_);
gl::setup_glew();
glfwSwapInterval(1);
glfwSetKeyCallback(win_, echo_key);
return true;
}
}
<file_sep>#pragma once
template <typename T>
constexpr inline T clamp(T val, T min, T max)
{
return (val < min ? min : (val > max ? max : val));
}
template <typename T>
constexpr inline T scale(T n, T source_lower, T source_upper, T dest_lower, T dest_upper)
{
return (dest_upper - dest_lower) * (n - source_lower) / (source_upper - source_lower) + dest_lower;
}
template <typename T>
constexpr inline T lerp(T a, T b, float factor)
{
return a + ((b - a) * factor);
}
<file_sep>#pragma once
#include <cstdint>
struct position {
position() :
x{0},
y{0}
{
}
position(uint32_t _x, uint32_t _y) :
x{_x},
y{_y}
{
}
//----------------------------------------------------------------------------//
uint32_t x, y;
};
struct move_delta {
move_delta() : x{0}, y{0} {}
move_delta(int i, int j) : x{i}, y{j} {}
int x, y;
};
<file_sep>#include "entelechy/entity_manager.hpp"
EntityManager::EntityManager(Space *space) :
space_{space},
gens_{},
graveyard_{},
aspect_signatures_{},
live_entities_{}
{
}
EntityManager::EntityManager(EntityManager &&other) :
space_{other.space_},
gens_{std::move(other.gens_)},
graveyard_{std::move(other.graveyard_)},
aspect_signatures_{std::move(other.aspect_signatures_)},
live_entities_{std::move(other.live_entities_)}
{
other.space_ = nullptr;
}
void EntityManager::clear()
{
gens_.clear();
std::deque<uid> q;
std::swap(q, graveyard_);
aspect_signatures_.clear();
live_entities_ = 0;
}
auto EntityManager::size() const -> size_type
{
return live_entities_;
}
//============================================================================--
// Entity management
//============================================================================--
uid EntityManager::createUID()
{
uid idx{0,0};
if(graveyard_.size() > MINFREE) {
idx = graveyard_.front();
graveyard_.pop_front();
} else {
gens_.push_back(0);
idx.id = gens_.size() - 1;
}
ensure_resize(aspect_signatures_, gens_.size());
uid entity{idx.id, static_cast<gen_type>(gens_[idx.id] & uid::GEN_MASK)};
++live_entities_;
return entity;
}
Entity EntityManager::createEntity()
{
return {createUID(), space_};
}
void EntityManager::destroyEntity(uid entity)
{
auto &sig = aspect_signatures_[entity.id];
size_t max_curr = 0;
sig.reset();
++gens_[entity.id];
graveyard_.push_back(entity);
--live_entities_;
}
void EntityManager::destroyEntity(Entity &entity)
{
destroyEntity(entity.id());
}
bool EntityManager::valid(uid entity) const
{
return gens_.size() > entity.id && gens_[entity.id] == entity.gen;
}
Entity EntityManager::getEntity(uint32_t id)
{
if(id >= gens_.size()) {
return {BAD_UID, space_};
}
return {{id, static_cast<gen_type>(gens_[id] & uid::GEN_MASK)}, space_};
}
auto EntityManager::entity_sig(uid entity) const -> const aspect_mask&
{
return aspect_signatures_[entity.id];
}
auto EntityManager::entity_sig(size_type entity_id) const -> const aspect_mask&
{
return aspect_signatures_[entity_id];
}
auto EntityManager::gen(size_type entity_id) const -> gen_type
{
return gens_[entity_id];
}
//============================================================================--
// Aspect management
//============================================================================--
bool EntityManager::has(uid entity, aspect_id id) const
{
return aspect_signatures_[entity.id][id];
}
<file_sep>#pragma once
#include "entelechy/typedef.hpp"
#include "entelechy/aspect.hpp"
#include "utils/container_tools.hpp"
class IAspectProtoPtr {
public:
virtual ~IAspectProtoPtr() = default;
virtual void* get_raw() = 0;
};
template <typename A>
class AspectProtoPtr : public IAspectProtoPtr {
public:
using type = A;
using storage_type = typename std::aligned_storage<sizeof(A), alignof(A)>::type;
//----------------------------------------------------------------------------//
template <typename ...Args>
AspectProtoPtr(Args &&...args) :
IAspectProtoPtr{},
data_{},
allocated_{false}
{
new (&data_) A(std::forward<Args>(args)...);
allocated_ = true;
}
~AspectProtoPtr()
{
callDestructor();
}
A* operator->()
{
return reinterpret_cast<A*>(&data_);
}
A& operator*()
{
return *reinterpret_cast<A*>(&data_);
}
virtual void* get_raw()
{
return reinterpret_cast<void*>(&data_);
}
A* get()
{
return reinterpret_cast<A*>(&data_);
}
template <typename ...Args>
void reset(Args &&...args)
{
callDestructor();
new (&data_) A(std::forward<Args>(args)...);
allocated_ = true;
}
void clear()
{
callDestructor();
}
operator bool()
{
return allocated_;
}
private:
void callDestructor()
{
if(allocated_) {
reinterpret_cast<A*>(&data_)->~A();
}
allocated_ = false;
}
storage_type data_;
bool allocated_;
};
class StrongAspectPrototype {
public:
using proto_ptr = std::unique_ptr<IAspectProtoPtr>;
template <typename ...Args>
StrongAspectPrototype(Args &&...args)
{
int _[]{0, (create(std::forward<Args>(args)), 0)...};
(void)_;
}
template <typename A>
bool has()
{
return (protos_.size() > Aspect::id<A>()) && protos_[Aspect::id<A>()];
}
template <typename A>
A* get()
{
return static_cast<AspectProtoPtr<A>>(protos_[Aspect::id<A>()].get()).get();
}
private:
std::vector<proto_ptr> protos_;
};
class AspectPrototype {
friend class Space;
public:
using proto_ptr = std::unique_ptr<IAspectProtoPtr>;
AspectPrototype() = default;
template <typename A, typename ...Args>
void add(Args &&...args)
{
if(!has<A>()) {
ensure_resize(protos_, Aspect::id<A>());
protos_[Aspect::id<A>()] = std::make_unique<AspectProtoPtr<A>>(std::forward<Args>(args)...);
}
}
template <typename A>
bool has()
{
return (protos_.size() > Aspect::id<A>()) && protos_[Aspect::id<A>()];
}
template <typename A>
A* get()
{
return static_cast<AspectProtoPtr<A>>(protos_[Aspect::id<A>()].get()).get();
}
private:
std::vector<proto_ptr> protos_;
};
<file_sep>#pragma once
#include "aspect.hpp"
#include "aspect_pool.hpp"
class aspect_ptr_base {
public:
aspect_ptr_base();
aspect_ptr_base(AspectPool &pool);
aspect_ptr_base(uid entity, AspectPool &pool);
aspect_ptr_base(const aspect_ptr_base &) = default;
aspect_ptr_base(aspect_ptr_base &&) = default;
~aspect_ptr_base() = default;
template <typename A>
A* get();
template <typename A>
A* release();
bool reset(uid new_entity);
bool reset(AspectPool &new_pool);
bool reset(AspectPool &new_pool, uid new_entity);
void swap(aspect_ptr_base &other);
uid entity()
{
return entity_;
}
operator bool() const;
bool valid() const;
protected:
AspectPool *pool_;
uid entity_;
};
inline aspect_ptr_base::aspect_ptr_base() :
pool_{nullptr},
entity_{BAD_UID}
{
}
inline aspect_ptr_base::aspect_ptr_base(AspectPool &pool) :
pool_{&pool},
entity_{BAD_UID}
{
}
inline aspect_ptr_base::aspect_ptr_base(uid entity, AspectPool &pool) :
pool_{&pool},
entity_{entity}
{
}
template <typename A>
inline A* aspect_ptr_base::get()
{
return pool_->get<A>(entity_.id);
}
template <typename A>
inline A* aspect_ptr_base::release()
{
A *ptr = get<A>();
entity_ = BAD_UID;
return ptr;
}
inline bool aspect_ptr_base::reset(uid new_entity)
{
if(new_entity && pool_ && new_entity != entity_) {
entity_ = new_entity;
return true;
}
return false;
}
inline bool aspect_ptr_base::reset(AspectPool &new_pool)
{
if(new_pool.initialised()) {
pool_ = &new_pool;
return true;
}
return false;
}
inline bool aspect_ptr_base::reset(AspectPool &new_pool, uid new_entity)
{
if(reset(new_pool) && reset(new_entity)) {
return true;
}
return false;
}
inline void aspect_ptr_base::swap(aspect_ptr_base &other)
{
std::swap(entity_, other.entity_);
std::swap(pool_, other.pool_);
}
inline aspect_ptr_base::operator bool() const
{
return valid();
}
inline bool aspect_ptr_base::valid() const
{
return entity_ && pool_ && pool_->has(entity_.id);
}
/**
* @brief [brief description]
* @details An unique_ptr style pointer for Aspects. Reacquires the pointer
* from the pool every time get() or the -> or * operators are called.
*
* @tparam A [description]
*/
template <typename A>
class aspect_ptr : public aspect_ptr_base {
public:
using value_type = A;
using reference = A&;
using pointer = A*;
//----------------------------------------------------------------------------//
aspect_ptr();
aspect_ptr(AspectPool &pool);
aspect_ptr(uid entity, AspectPool &pool);
aspect_ptr(const aspect_ptr &) = default;
aspect_ptr(aspect_ptr &&) = default;
~aspect_ptr() = default;
pointer get();
pointer release();
void swap(aspect_ptr<A> &other);
reference operator*();
pointer operator->();
protected:
AspectPool *pool_;
uid entity_;
};
template <typename A>
inline aspect_ptr<A>::aspect_ptr() :
aspect_ptr_base{}
{
}
template <typename A>
inline aspect_ptr<A>::aspect_ptr(AspectPool &pool) :
aspect_ptr_base{BAD_UID, pool}
{
}
template <typename A>
inline aspect_ptr<A>::aspect_ptr(uid id, AspectPool &pool) :
aspect_ptr_base{id, pool}
{
}
template <typename A>
inline auto aspect_ptr<A>::get() -> pointer
{
return pool_->get<A>(entity_.id);
}
template <typename A>
inline auto aspect_ptr<A>::release() -> pointer
{
pointer *ptr = aspect_ptr_base::get<A>();
entity_ = BAD_UID;
return ptr;
}
template <typename A>
inline void aspect_ptr<A>::swap(aspect_ptr<A> &other)
{
std::swap(entity_, other.entity_);
std::swap(pool_, other.pool_);
}
template <typename A>
inline auto aspect_ptr<A>::operator*() -> reference
{
return *(aspect_ptr_base::get<A>());
}
template <typename A>
inline auto aspect_ptr<A>::operator->() -> pointer
{
return aspect_ptr_base::get<A>();
}
<file_sep>#pragma once
#include "entelechy/system.hpp"
#include "geometry/array_2d.hpp"
namespace virgil {
class RenderSystem : public ISystem {
public:
RenderSystem(Console &con) :
con_{con}
{
for(int i = 0; i < 80; ++i) {
for(int j = 0; j < 50; ++j) {
if(i == 0 || j == 0 || j == 49 || i == 79) {
map_(i, j) = '#';
} else {
map_(i, j) = '.';
}
}
}
}
virtual void init()
{
}
virtual void tick(Space &space, EventManager &)
{
con_.clear();
Random rng;
int i = 0;
for(const auto &it : map_) {
con_.putChar(i % 80, i / 80, it, col::smoke) ;
++i;
}
aspect_ptr<glyph> g;
aspect_ptr<position> p;
for(auto i : space.entitiesWith(g, p)) {
con_.putChar(p->x, p->y, g->gly, g->col);
}
}
virtual void update(Space &, EventManager &, double)
{
}
array_2d<uint32_t, 80, 50> map_;
Console &con_;
};
}
<file_sep>#pragma once
#include "config.hpp"
#include "core/core.hpp"
#include "serialise/serialise.hpp"
#include "utils/utils.hpp"
#include "geometry/geometry.hpp"
#include "rendering/rendering.hpp"
#include "world/name_generator.hpp"
#include "entelechy/entelechy.hpp"
#include "aspects/aspects.hpp"
#include "systems/systems.hpp"
namespace vl = virgil;
<file_sep>#include "space.hpp"
#include "entity_view.hpp"
Space::Space(EventManager &e_man, MessageHandler &msg_hand) :
entities_{this},
systems_{*this},
event_man_{&e_man},
msg_hand_{&msg_hand},
top_aspect_id_{0}
{
}
void Space::clear()
{
for(size_type i = 0; i < top_aspect_id_; ++i) {
pools_[i].clear();
}
entities_.clear();
}
auto Space::size() const -> size_type
{
return entities_.size();
}
Entity Space::createEntity()
{
return entities_.createEntity();
}
bool Space::destroyEntity(uid entity)
{
if(!entities_.valid(entity)) {
return false;
}
const auto &sig = entities_.entity_sig(entity.id);
for(size_type i = 0; i < top_aspect_id_; ++i) {
if(sig[i] && pools_[i].initialised()) {
pools_[i].deallocate(entity.id);
}
}
entities_.destroyEntity(entity);
return true;
}
bool Space::valid(uid entity) const
{
return entities_.valid(entity);
}
LiveEntityFilter Space::entities(Entity &entity)
{
return {*this, entity};
}
<file_sep>#include "world/name_generator.hpp"
bool NameGenerator::load(const char *path)
{
std::ifstream namefile(path);
if(!namefile.good()) return false;
std::string name = "";
size_t i = 0;
std::vector<uint32_t> cp;
while(!namefile.eof()) {
cp.clear();
std::getline(namefile, name);
if(utf8_strlen(name) < 3) {
break;
}
utf8_decode(name, cp);
initial_.emplace_back(cp[0]);
tri_map_[{0, 0, cp[0]}].emplace_back(cp[1]);
tri_map_[{0, cp[0], cp[1]}].emplace_back(cp[2]);
for(i = 0; i < cp.size() - 3; ++i) {
tri_map_[Trigram{cp[i], cp[i+1], cp[i+2]}].emplace_back(cp[i+3]);
}
tri_map_[{cp[cp.size()-3], cp[cp.size()-2], cp[cp.size()-1]}].emplace_back(0);
}
return true;
}
<file_sep>#pragma once
// Mac OS X
#if defined (__APPLE__) || defined(macintosh) || defined (__APPLE_CC__)
#define VIRGIL_OSX
// Linux
#elif defined(__linux__) || defined(__LINUX__)
#define VIRGIL_LINUX
// Windows
#elif defined(_WIN64) || defined(_WIN32) || defined(__CYGWIN32__) || defined(__MINGW32__)
#define VIRGIL_WINDOWS
// Unknown!
#else
#define VIRGIL_UNSUPPORTED_OS
#define VIRGIL_UNKNOWN_OS
#endif
// Clang
#if defined(__clang__)
#define VIRGIL_COMPILER_CLANG
#define VL_HAS_BUILTIN_EXPECT
// GCC
#elif defined(__GNUC__)
#define VIRGIL_COMPILER_GCC
#define VL_HAS_BUILTIN_EXPECT
// MSVC
#elif defined _MSC_VER
#define VIRGIL_COMPILER_MSVC
// MSVC doesn't support constexpr yet, so...
#define VIRGIL_COMPILER_UNSUPPORTED
// Unknown!
#else
#define VIRGIL_COMPILER_UNKNOWN
#define VIRGIL_COMPILER_UNSUPPORTED
#endif
// Pretty function alias
#if defined(__GNUC__)
#define VL_CURRENT_FUNCTION __PRETTY_FUNCTION__
#elif defined(__FUNCSIG__)
#define VL_CURRENT_FUNCTION __FUNCSIG__
#elif (defined(__STDC_VERSION__) && (__STDC_VERSION__ >= 199901)) || (defined(__cplusplus) && (__cplusplus >= 201103))
#define VL_CURRENT_FUNCTION __func__
#else
#define VL_CURRENT_FUNCTION "UNKNOWN"
#endif
// Alias for __builtin_expect if we're on Clang or GCC
#ifdef VL_HAS_BUILTIN_EXPECT
#define VL_LIKELY(what) __builtin_expect(!!(what), 1)
#define VL_UNLIKELY(what) __builtin_expect(!!(what), 0)
#else
#define VL_LIKELY(what) what
#define VL_UNLIKELY(what) what
#endif
<file_sep>#pragma once
#include "stb_image/stb_image.h"
#include "stb_image/stb_image_resize.h"
#include "stb_image/stb_image_write.h"
<file_sep>#pragma once
#include "opengl.hpp"
#include "mat4.hpp"
#include "shader_program.hpp"
#include "uniform.hpp"
////////////////////////////////////////////////////////////////////////////////
// BillboardShader
////////////////////////////////////////////////////////////////////////////////
class BillboardShader : public Shader {
public:
//----------------------------------------------------------------------------//
BillboardShader() = default;
void init(const char *vert_source = default_vert_, const char *frag_source = default_frag_);
void setUniforms();
void spec() const;
/**
* @brief Calls glUseProgram() on the wrapped program
*/
void use() const;
private:
static constexpr const char *default_vert_ = "#version 330\n"
"in vec2 position;\n"
"in vec2 texcoord;\n"
"out vec2 tex_coord;\n"
"void main() {\n"
" tex_coord = texcoord;\n"
" gl_Position = vec4(position, 0.0, 1.0);\n"
"}\n";
static constexpr const char *default_frag_ = "#version 330\n"
"in vec2 tex_coord;\n"
"out vec4 out_colour;\n"
"uniform sampler2D fb_tex;\n"
"void main() {\n"
" out_colour = texture(fb_tex, tex_coord);\n"
"}\n";
Uniform<int> tfb_;
};
inline void BillboardShader::use() const
{
glUseProgram(program_);
}
<file_sep>#pragma once
#include <utility>
/**
* @brief Apply a function over a parameter pack.
* @details [long description]
*
* @param f Function to apply
* @param args Parameters to apply to
*/
template <typename F, typename ...Args>
void apply(F &&f, Args &&...args)
{
int _[]{0, {f(std::forward<Args>(args)), 0}...};
(void)_;
}
<file_sep>#pragma once
#include "core/opengl.hpp"
#include "geometry/mat4.hpp"
#include "rendering/shader.hpp"
#include "rendering/uniform.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// ConsoleShader
////////////////////////////////////////////////////////////////////////////////
class ConsoleShader : public Shader {
public:
ConsoleShader();
void load(int width, int height);
void reload(int width, int height);
private:
void loadSymbolicConstants();
void bindVertexAttributes();
void setUniforms();
//----------------------------------------------------------------------------//
std::string vert_source_, //<! Composed vertex shader source
frag_source_; //<! Composed fragment shader source
mat4 transform_; //<! Console transform
int width_, //<! Root console width, pixels
height_; //<! Root console height, pixels
Uniform<mat4> con_tran_; //<! Console transform uniform
Uniform<int> con_tex_, //<! Console texture uniform
glyph_loc_, //<! Console glyph data buffer uniform
fore_loc_, //<! Console foreground colour buffer uniform
back_loc_; //<! Console background colour buffer uniform
};
}
<file_sep>#pragma once
#include "core/opengl.hpp"
#include "rendering/gl_buffer.hpp"
#include <vector>
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// IndexedArray
////////////////////////////////////////////////////////////////////////////////
template <typename VertexType, size_t nIndices, size_t nVertices>
class BaseIndexedArray;
//============================================================================--
// Dynamic base
//============================================================================--
template <typename VertexType>
class BaseIndexedArray<VertexType, 0, 0> {
public:
using vertex_type = VertexType;
using vertex_ptr = VertexType*;
using index_type = uint32_t;
//------------------------------------------------------------------------//
void resize_vertices(size_t num)
{
vertices_.resize(num);
}
void resize_indices(size_t num)
{
indices_.resize(num);
}
/**
* @brief Add a new, default-initialised vertex to the array
* @return Pointer to newly-allocated vertex
*/
vertex_ptr emplace_back()
{
vertices_.emplace_back();
return vertices_.back();
}
/**
* @brief Add a new vertex to the array, using the passed args
* @param args vertex_type constructor arguments
*/
template <typename ...Args>
void emplace_back(Args &&...args)
{
vertices_.emplace_back(std::forward<Args>(args)...);
}
void set_all(const Colour &col)
{
for(auto &v : vertices_) {
v.col = col;
}
}
void push_index(index_type idx)
{
indices_.emplace_back(idx);
}
void push_indices(std::initializer_list<index_type> new_indices)
{
indices_.insert(indices_.end(), new_indices.begin(), new_indices.end());
}
void push_indices(index_type offset, std::initializer_list<index_type> offset_indices)
{
std::transform(
offset_indices.begin(),
offset_indices.end(),
std::back_inserter(indices_),
std::bind2nd(std::plus<index_type>(), offset)
);
}
protected:
std::vector<vertex_type> vertices_; //! Array of vertices
std::vector<index_type> indices_; //! Array of indices
};
//============================================================================--
// Static base
//============================================================================--
template <typename VertexType, size_t nIndices, size_t nVertices>
class BaseIndexedArray {
public:
using vertex_type = VertexType;
using index_type = gl::buffer_traits<gl::ELEMENT_ARRAY>::index_type;
using index_ref = index_type&;
//------------------------------------------------------------------------//
void set_indices(std::initializer_list<index_type> new_indices)
{
std::copy(new_indices.begin(), new_indices.end(), indices_.begin());
}
//------------------------------------------------------------------------//
protected:
std::array<vertex_type, nVertices> vertices_; //! Array of vertices
std::array<index_type, nIndices> indices_; //! Array of indices
};
//============================================================================--
// Main definition
//============================================================================--
template <typename V, size_t nIndices = 0, size_t nVertices = 0>
class IndexedArray : public BaseIndexedArray<V, nIndices, nVertices> {
public:
using vertex_type = V;
using vertex_ptr = V*;
using vertex_ref = V&;
using index_type = gl::buffer_traits<gl::ELEMENT_ARRAY>::index_type;
using index_ref = index_type&;
using vertex_iterator = typename std::vector<vertex_type>::iterator;
using index_iterator = typename std::vector<index_type>::iterator;
using base_array = BaseIndexedArray<V, nIndices, nVertices>;
//------------------------------------------------------------------------//
IndexedArray(GLenum prim_type = GL_TRIANGLES, GLenum draw_type = GL_STATIC_DRAW);
~IndexedArray();
/**
* @brief Clear the vertices and indices, delete the vertex arrays and
* buffers
*/
void clear();
/**
* @brief Delete the vertex arrays and buffers
*/
void delete_buffers();
/**
* @brief Set the vertex mode for drawing
*
* @param prim_type Type of objects to draw for this array
*/
void set_primitive_type(GLenum prim_type);
void resize(size_t num);
/**
* @brief Return a reference to the vertex at a given index
*
* @param idx Index of vertex
* @return vertex_ref
*/
vertex_ref operator[](size_t idx);
void set_all(const Colour &col);
void bind() const;
void update() const;
void draw() const;
/**
* @brief Get the current size of the vertex array
* @return Number of vertices in this array
*/
size_t size() const;
vertex_iterator begin();
vertex_iterator end();
index_iterator index_begin();
index_iterator index_end();
private:
gl::VAO vao_; //<! Vertex array object
gl::Buffer<gl::ARRAY> vbo_; //<! Vertex buffer
gl::Buffer<gl::ELEMENT_ARRAY> ibo_; //<! Index buffer
GLenum draw_type_, //<! Draw type
prim_type_; //<! Primitive type
};
//============================================================================--
// Constructors
//============================================================================--
template <typename V, size_t nI, size_t nV>
IndexedArray<V, nI, nV>::IndexedArray(GLenum prim_type, GLenum draw_type) :
vbo_{draw_type},
ibo_{draw_type},
draw_type_{draw_type},
prim_type_{prim_type}
{
}
template <typename V, size_t nI, size_t nV>
IndexedArray<V, nI, nV>::~IndexedArray()
{
}
//============================================================================--
// Clearing
//============================================================================--
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::clear()
{
base_array::vertices_.clear();
base_array::indices_.clear();
}
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::delete_buffers()
{
}
//============================================================================--
// Set parameters
//============================================================================--
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::set_primitive_type(GLenum prim_type)
{
prim_type_ = prim_type;
}
//============================================================================--
// Add/Set vertices
//============================================================================--
template <typename V, size_t nI, size_t nV>
auto IndexedArray<V, nI, nV>::operator[](size_t idx) -> vertex_ref
{
return base_array::vertices_[idx];
}
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::set_all(const Colour &col)
{
for(auto &v : base_array::vertices_) {
v.col = col;
}
}
//============================================================================--
// Bind, Update, Draw
//============================================================================--
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::bind() const
{
vao_.bind();
vbo_.bind();
vbo_.buffer_data(base_array::vertices_);
ibo_.bind();
ibo_.buffer_data(base_array::indices_);
vertex_type::setVertexAttribPointers();
vao_.unbind();
ibo_.unbind();
vbo_.unbind();
}
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::update() const
{
vbo_.bind();
vbo_.buffer_sub_data(base_array::vertices_);
ibo_.bind();
ibo_.buffer_sub_data(base_array::indices_);
}
template <typename V, size_t nI, size_t nV>
void IndexedArray<V, nI, nV>::draw() const
{
vao_.bind();
ibo_.draw(prim_type_, base_array::indices_.size());
}
//============================================================================--
// Getters, Iterators
//============================================================================--
template <typename V, size_t nI, size_t nV>
size_t IndexedArray<V, nI, nV>::size() const
{
return base_array::vertices_.size();
}
template <typename V, size_t nI, size_t nV>
auto IndexedArray<V, nI, nV>::begin() -> vertex_iterator
{
return base_array::vertices_.begin();
}
template <typename V, size_t nI, size_t nV>
auto IndexedArray<V, nI, nV>::end() -> vertex_iterator
{
return base_array::vertices_.end();
}
template <typename V, size_t nI, size_t nV>
auto IndexedArray<V, nI, nV>::index_begin() -> index_iterator
{
return base_array::indices_.begin();
}
template <typename V, size_t nI, size_t nV>
auto IndexedArray<V, nI, nV>::index_end() -> index_iterator
{
return base_array::indices_.end();
}
}
<file_sep>#pragma once
#include "entelechy/uid.hpp"
#include <cstdint>
#include <bitset>
////////////////////////////////////////////////////////////////////////////////
// Types
////////////////////////////////////////////////////////////////////////////////
//------------------------------------------------------------------------//
using index_type = uint32_t; //<! Default type for indexed access
using aspect_id = uint8_t; //<! Type for component ID
using system_id = uint8_t; //<! Type for system ID
using event_id = uint32_t; //<! Type for component ID
//------------------------------------------------------------------------//
static constexpr uint32_t MAX_ASPECTS{32};
static_assert(
MAX_ASPECTS <= ~aspect_id(0) - 1,
"MAX_ASPECTS is larger than the maximum allowable value for aspect_id"
);
using aspect_mask = std::bitset<MAX_ASPECTS>;
static constexpr aspect_id BAD_ASPECT = ~aspect_id(0);
//------------------------------------------------------------------------//
static constexpr uint32_t MAX_ENTITIES{1 << uid::ID_BITS};
//------------------------------------------------------------------------//
template <typename ...Aspects>
class AspectFilter;
class EntityFilter;
class LiveEntityFilter;
<file_sep>#pragma once
class Space;
class EventManager;
////////////////////////////////////////////////////////////////////////////////
// ISystem
////////////////////////////////////////////////////////////////////////////////
/**
* @brief Interface class for systems
* @details [long description]
* @return [description]
*/
struct ISystem {
ISystem();
virtual ~ISystem() = default;
/**
* @brief Initialise the System
* @details Pure virtual method; carry out any preparatory work necessary to
* set up this ISystem for use.
*/
virtual void init() = 0;
/**
* @brief Run the System for one tick; turn-based update strategy
* @details [long description]
*
* @param space Space to run the system over
* @param ev_p EventManager to dispatch events from
*/
virtual void tick(Space &space, EventManager &ev_p) = 0;
/**
* @brief Run the System for a given duration; real-time update strategy
* @details [long description]
*
* @param space Space to run the system over
* @param ev_p EventManager to dispatch events from
* @param delta Time since last update
*/
virtual void update(Space &space, EventManager &ev_p, double delta) = 0;
/**
* @brief Pause the System
*/
void pause();
/**
* @brief Unpause the System
*/
void unpause();
/**
* @brief Check if the System is paused.
* @return True if the System is paused, otherwise false
*/
bool paused() const;
protected:
bool paused_;
};
inline ISystem::ISystem() :
paused_{false}
{
}
inline void ISystem::pause()
{
paused_ = true;
}
inline void ISystem::unpause()
{
paused_ = false;
}
inline bool ISystem::paused() const
{
return paused_;
}
<file_sep>#pragma once
#include "vec2.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// rect
////////////////////////////////////////////////////////////////////////////////
/**
* @brief Rectangle class
*/
template <typename T>
class rect {
public:
using value_type = T;
rect();
rect(T x, T y, T w, T h);
rect(vec2f origin, vec2f dimensions);
~rect() = default;
T right() const;
T bottom() const;
void set(T origin_x, T origin_y, T w, T h);
void set_origin(T x, T y);
void set_dimensions(T x, T y);
template <typename U>
bool contains(vec2<U> point) const;
bool intersects(rect other) const;
//------------------------------------------------------------------------//
T x, y,
w, h;
};
//============================================================================--
// Constructors
//============================================================================--
template <typename T>
rect<T>::rect() :
x{0},
y{0},
w{0},
h{0}
{
}
template <typename T>
rect<T>::rect(T ox, T oy, T dw, T dh) :
x{ox},
y{oy},
w{dw},
h{dh}
{
}
template <typename T>
rect<T>::rect(vec2f origin, vec2f dest) :
x{origin.x},
y{origin.y},
// uhhhh shouldn't this be difference...?
w{dest.x},
h{dest.y}
{
}
//============================================================================--
// Getters
//============================================================================--
template <typename T>
T rect<T>::right() const
{
return x + w;
}
template <typename T>
T rect<T>::bottom() const
{
return y + h;
}
//============================================================================--
// Setters
//============================================================================--
template <typename T>
void rect<T>::set(T origin_x, T origin_y, T width, T height)
{
x = origin_x;
y = origin_y;
w = width;
h = height;
}
template <typename T>
void rect<T>::set_origin(T ox, T oy)
{
x = ox;
y = oy;
}
template <typename T>
void rect<T>::set_dimensions(T dw, T dh)
{
w = dw;
h = dh;
}
//============================================================================--
// Intersection checking
//============================================================================--
template <typename T>
template <typename U>
bool rect<T>::contains(vec2<U> point) const
{
return static_cast<T>(point.x) > x &&
static_cast<T>(point.x) < right() &&
static_cast<T>(point.y) > y &&
static_cast<T>(point.y) < bottom();
}
template <typename T>
bool rect<T>::intersects(rect other) const
{
return !(other.x > right() || other.right() < x || other.y > bottom() || other.bottom() < y);
}
using rect_f = rect<float>;
using rect_d = rect<double>;
using rect_i = rect<int>;
using rect_u = rect<uint32_t>;
using rect_u64 = rect<uint64_t>;
}
<file_sep>/**
* @file colour.hpp
* @date 2015-03-30
* @brief RGBA Colour class
*/
#pragma once
#include <cstdint>
#include <cmath>
namespace virgil {
/**
* @brief Class for representing RGBA colours
*/
class Colour {
public:
/**
* @brief Colour constructor, byte values
*
* @param red Initial red value
* @param green Initial green value
* @param blue Initial blue value
* @param alpha Initial alpha value
*/
constexpr Colour(uint8_t red = 0, uint8_t green = 0, uint8_t blue = 0, uint8_t alpha = 255) :
r{red},
g{green},
b{blue},
a{alpha}
{
}
constexpr Colour(const Colour &other) :
r{other.r},
g{other.g},
b{other.b},
a{other.a}
{
}
constexpr Colour(Colour &&other) :
r{other.r},
g{other.g},
b{other.b},
a{other.a}
{
}
Colour& operator=(Colour other)
{
r = other.r;
g = other.g;
b = other.b;
a = other.a;
return *this;
}
void set(uint8_t red, uint8_t green, uint8_t blue, uint8_t alpha = 255)
{
r = red;
g = green;
b = blue;
a = alpha;
}
/**
* @brief Colour constructor, normalised float values
*
* @param red Red value between 0.f - 1.f
* @param green Green value between 0.f - 1.f
* @param blue Blue value between 0.f - 1.f
* @param alpha Alpha value between 0.f - 1.f
*/
static inline Colour fromFloat(float red, float green, float blue, float alpha = 1.f)
{
return {
static_cast<uint8_t>(std::floor(red * 255.f)),
static_cast<uint8_t>(std::floor(green * 255.f)),
static_cast<uint8_t>(std::floor(blue * 255.f)),
static_cast<uint8_t>(std::floor(alpha * 255.f))
};
}
/**
* @brief Colour constructor, from 32-bit hex value
*
* @param red Red value between 0.f - 1.f
* @param green Green value between 0.f - 1.f
* @param blue Blue value between 0.f - 1.f
* @param alpha Alpha value between 0.f - 1.f
*/
static inline Colour fromHex(uint32_t hex_value)
{
return {
static_cast<uint8_t>(hex_value >> 24),
static_cast<uint8_t>((hex_value & 0x00ff0000) >> 16),
static_cast<uint8_t>((hex_value & 0x0000ff00) >> 8),
static_cast<uint8_t>(hex_value & 0xff)
};
}
template <typename T>
Colour operator+(const T f) const
{
return {static_cast<uint8_t>(r + f), static_cast<uint8_t>(g + f), static_cast<uint8_t>(b + f)};
}
template <typename T>
Colour operator-(const T f) const
{
return {static_cast<uint8_t>(r - f), static_cast<uint8_t>(g - f), static_cast<uint8_t>(b - f)};
}
template <typename T>
Colour operator*(const T f) const
{
return {static_cast<uint8_t>(r * f), static_cast<uint8_t>(g * f), static_cast<uint8_t>(b * f)};
}
template <typename T>
Colour operator/(const T f) const
{
return {static_cast<uint8_t>(r / f), static_cast<uint8_t>(g / f), static_cast<uint8_t>(b / f)};
}
//------------------------------------------------------------------------//
uint8_t r; //! Red value
uint8_t g; //! Green value
uint8_t b; //! Blue value
uint8_t a; //! Alpha value
};
inline bool operator==(const Colour &lhs, const Colour &rhs)
{
return lhs.r == rhs.r && lhs.g == rhs.g && lhs.b == rhs.b && lhs.a == rhs.a;
}
inline bool operator!=(const Colour &lhs, const Colour &rhs)
{
return lhs.r != rhs.r || lhs.g != rhs.g || lhs.b != rhs.b || lhs.a != rhs.a;
}
namespace col {
// Black and White
static constexpr Colour white {255,255,255}; //<! Default colour - white
static constexpr Colour black {0, 0, 0}; //<! Default colour - black
// RGB
static constexpr Colour red {255, 0, 0}; //<! Default colour - red
static constexpr Colour green {0, 255, 0}; //<! Default colour - green
static constexpr Colour blue {0, 0, 255}; //<! Default colour - blue
// CMY
static constexpr Colour yellow {255, 255, 0}; //<! Default colour - yellow
static constexpr Colour magenta {255, 0, 255}; //<! Default colour - magenta
static constexpr Colour cyan {0, 255, 255}; //<! Default colour - cyan
// Shades of Grey
static constexpr Colour dark_slate {20, 20, 20}; //<! Default colour - dark slate
static constexpr Colour basalt {32, 32, 32}; //<! Default colour - basalt
static constexpr Colour slate {40, 40, 40}; //<! Default colour - slate
static constexpr Colour light_slate {70, 70, 60}; //<! Default colour - light slate
static constexpr Colour smoke {80, 95, 95}; //<! Default colour - smoke
static constexpr Colour salt {175, 175, 175}; //<! Default colour - salt
static constexpr Colour pallor {200, 230, 230}; //<! Default colour - pallor
// Others
static constexpr Colour pink {210, 40, 115}; //<! Default colour - pink
static constexpr Colour lime {166,226, 45}; //<! Default colour - lime
static constexpr Colour purple {174, 129, 255}; //<! Default colour - purple
static constexpr Colour sky_blue {100,220, 240}; //<! Default colour - sky blue
static constexpr Colour straw {230, 220, 116}; //<! Default colour - straw
static constexpr Colour orange {253,151, 31}; //<! Default colour - orange
static constexpr Colour brown {150, 75, 0}; //<! Default colour - brown
}
}
<file_sep>#pragma once
#include "core/opengl.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// Texture
////////////////////////////////////////////////////////////////////////////////
struct Texture {
Texture(GLenum type = GL_INVALID_ENUM);
~Texture();
void destroy();
void activate(GLenum slot) const;
bool valid() const;
operator bool() const;
protected:
GLenum type_;
GLuint tex_id_;
int width_,
height_;
};
////////////////////////////////////////////////////////////////////////////////
// TextureAtlas
////////////////////////////////////////////////////////////////////////////////
struct TextureAtlas : public Texture {
TextureAtlas();
void generate(const unsigned char *data, int width, int height);
};
}
<file_sep>#pragma once
namespace virgil {
static constexpr double PI_OVER_360d = 0.0087266462599716477;
static constexpr float PI_OVER_360f = static_cast<float>(PI_OVER_360d);
inline float radians(float degrees)
{
return PI_OVER_360f * 2.f * degrees;
}
}
<file_sep>#pragma once
#include "typedef.hpp"
class Aspect {
public:
template <typename A>
static inline aspect_id id()
{
static const aspect_id id_{get_next_id()};
return id_;
}
private:
static inline aspect_id get_next_id()
{
static aspect_id id_{0};
return id_++;
}
};
<file_sep>#include "rendering/texture.hpp"
namespace virgil {
Texture::Texture(GLenum type) :
type_{type},
tex_id_{0},
width_{0},
height_{0}
{
}
Texture::~Texture()
{
}
void Texture::destroy()
{
glDeleteTextures(1, &tex_id_);
type_ = GL_INVALID_ENUM;
width_ = 0;
height_ = 0;
}
void Texture::activate(GLenum slot) const
{
glActiveTexture(slot);
glBindTexture(type_, tex_id_);
}
bool Texture::valid() const
{
return tex_id_ != 0;
}
Texture::operator bool() const
{
return tex_id_ != 0;
}
TextureAtlas::TextureAtlas() :
Texture{GL_TEXTURE_2D}
{
}
void TextureAtlas::generate(const unsigned char *data, int width, int height)
{
glGenTextures(1, &tex_id_);
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D, tex_id_);
width_ = width;
height_ = height;
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, width_, height_, 0, GL_RGBA, GL_UNSIGNED_BYTE, data);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameterf(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
}
<file_sep>#pragma once
#include "rendering/colour.hpp"
#include "geometry/vec2.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// Image
////////////////////////////////////////////////////////////////////////////////
class Image {
public:
enum Channels {
MONO = 1,
ALPHA = 1,
RED = 1,
RGB = 3,
RGBA = 4
};
//----------------------------------------------------------------------------//
Image();
Image(uint32_t width, uint32_t height, uint8_t channels);
Image(const char *file_name, uint8_t force_channels = 4);
~Image();
void erase();
Colour getPixel(uint32_t x, uint32_t y) const;
uint8_t getAlpha(uint32_t x, uint32_t y) const;
bool isPixelTransparent(uint32_t x, uint32_t y) const;
bool load(const char *file_name, uint8_t force_channels = 4);
bool save(const char *file_name) const;
void resize(uint32_t new_w, uint32_t new_h);
void clear(const Colour col);
bool valid() const;
void setKeyColour(Colour c);
void flipHorizontal();
void flipVertical();
uint32_t width() const;
uint32_t height() const;
uint8_t channels() const;
uint8_t* data();
protected:
uint32_t bytes_; //<! Image size in bytes
uint32_t width_, //<! Image width
height_; //<! Image height
uint8_t *data_; //<! Image data
uint8_t channels_; //<! Image channels
};
inline uint8_t* Image::data()
{
return data_;
}
inline uint32_t Image::width() const
{
return width_;
}
inline uint32_t Image::height() const
{
return height_;
}
inline uint8_t Image::channels() const
{
return channels_;
}
}
<file_sep>#include "driver.hpp"
int main(int argc, const char **argv) {
virgil::Driver driver(argc, argv);
return driver.run();
}
<file_sep>#pragma once
#include "core/utf8.hpp"
#include "core/xxhash.hpp"
#include "world/trigram.hpp"
#include <fstream>
#include <string>
#include <vector>
#include <unordered_map>
class NameGenerator {
public:
using codepoint_t = uint32_t;
using next_type = std::vector<codepoint_t>;
using trigram_map = std::unordered_map<Trigram, next_type>;
//----------------------------------------------------------------------------//
NameGenerator() = default;
~NameGenerator() = default;
bool load(const char *path);
template <typename URNG>
std::string gen(URNG &random, uint32_t min_len = 3, uint32_t max_len = 12) const;
template <typename URNG>
void gen(std::string &ret, URNG &random, uint32_t min_len = 3, uint32_t max_len = 12) const;
private:
template <typename URNG>
bool advance(Trigram &trigram, URNG &random) const;
//----------------------------------------------------------------------------//
trigram_map tri_map_;
std::vector<codepoint_t> initial_;
};
template <typename URNG>
inline std::string NameGenerator::gen(URNG &random, uint32_t min_len, uint32_t max_len) const
{
std::string str;
gen(str, random, min_len, max_len);
return str;
}
template <typename URNG>
inline void NameGenerator::gen(std::string &ret, URNG &random, uint32_t min_len, uint32_t max_len) const
{
char x[4];
std::uniform_int_distribution<uint32_t> d(0, (uint32_t)initial_.size() -1);
Trigram curr = {0,0,initial_[d(random)]};
ret = toUTF8(curr.c, x);
while(ret.length() < max_len) {
advance(curr, random);
switch(curr.c) {
case 0:
if(ret.length() > min_len) {
return;
} else {
curr = {0,0, initial_[d(random)]};
ret.clear();
}
break;
default:
ret += toUTF8(curr.c, x);
break;
}
}
return;
}
template <typename URNG>
inline bool NameGenerator::advance(Trigram &trigram, URNG &random) const
{
auto b = tri_map_.find(trigram);
if(b != tri_map_.end()) {
std::uniform_int_distribution<uint32_t> dd(0, (uint32_t)b->second.size()-1);
trigram.push(b->second[dd(random)]);
return true;
} else {
return false;
}
}
<file_sep>#pragma once
#include "dolor/dolor/dolor.hpp"
<file_sep>#pragma once
#include "geometry/vec2.hpp"
#include "geometry/vec3.hpp"
#include "geometry/radians.hpp"
#include "geometry/mat4.hpp"
#include "geometry/rect.hpp"
#include "geometry/array_2d.hpp"
<file_sep>#include "core/stb_image.hpp"
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wunused-value"
#pragma clang diagnostic ignored "-Wunused-variable"
#pragma clang diagnostic ignored "-Wunused-parameter"
#define STB_IMAGE_IMPLEMENTATION
#define STB_IMAGE_RESIZE_IMPLEMENTATION
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image/stb_image.h"
#include "stb_image/stb_image_resize.h"
#include "stb_image/stb_image_write.h"
#pragma clang diagnostic pop
<file_sep>#pragma once
#include "aspects/glyph.hpp"
#include "aspects/position.hpp"
#include "aspects/core_stats.hpp"
#include "aspects/inventory.hpp"
<file_sep>#pragma once
#include "utils/image.hpp"
#include "utils/functional.hpp"
<file_sep>#pragma once
#include <random>
#include "pcg/pcg_random.hpp"
#include "utils/numeric.hpp"
namespace virgil {
class Random {
public:
Random();
Random(uint32_t seed);
~Random() = default;
template <typename T>
T get_int(T min, T max);
float get_float(float min, float max);
double get_double(double min, double max);
int get_int(int min, int max, int mean);
float get_float(float min, float max, float mean);
double get_double(double min, double max, double mean);
template <size_t N, typename RealType = double>
RealType get_canonical();
template <typename T, typename RealType = double>
T get(T min, T max, T mean);
uint32_t in_range(uint32_t val);
bool one_in(uint32_t odds);
bool x_in(uint32_t num, uint32_t denom);
uint32_t roll(uint32_t number, uint32_t sides);
void reseed(uint32_t seed);
void reseed();
pcg32& generator();
private:
pcg32 rng_;
};
inline Random::Random() :
rng_{pcg_extras::seed_seq_from<std::random_device>{}}
{
}
inline Random::Random(uint32_t seed) :
rng_{seed}
{
}
template <typename T>
inline T Random::get_int(T min, T max)
{
std::uniform_int_distribution<T> dist(min, max);
return dist(rng_);
}
inline float Random::get_float(float min, float max)
{
std::uniform_real_distribution<float> dist(min, max);
return dist(rng_);
}
inline double Random::get_double(double min, double max)
{
std::uniform_real_distribution<double> dist(min, max);
return dist(rng_);
}
inline int Random::get_int(int min, int max, int mean)
{
return get<int>(min, max, mean);
}
inline float Random::get_float(float min, float max, float mean)
{
return get<float, float>(min, max, mean);
}
inline double Random::get_double(double min, double max, double mean)
{
return get<double>(min, max, mean);
}
template <size_t N, typename RealType>
inline RealType Random::get_canonical()
{
return std::generate_canonical<RealType, N>(rng_);
}
template <typename T, typename RealType>
inline T Random::get(T min, T max, T mean)
{
if (min > max) {
std::swap(min, max);
}
const RealType stddev = std::max(max - mean, mean - min) / 3.0;
std::normal_distribution<RealType> dist{static_cast<RealType>(mean), stddev};
return static_cast<T>(clamp(static_cast<RealType>(min), static_cast<RealType>(max), dist(rng_)));
}
inline uint32_t Random::in_range(uint32_t val)
{
return get_int<uint32_t>(0, val);
}
inline bool Random::one_in(uint32_t val)
{
return get_int<uint32_t>(0, val) == 0;
}
inline bool Random::x_in(uint32_t num, uint32_t denom)
{
return get_int<uint32_t>(num, denom) <= (static_cast<double>(num) / static_cast<double>(denom));
}
inline void Random::reseed(uint32_t seed)
{
rng_.seed(seed);
}
inline void Random::reseed()
{
rng_.seed(pcg_extras::seed_seq_from<std::random_device>{});
}
inline pcg32& Random::generator()
{
return rng_;
}
template <typename Container>
inline auto choose_one(const Container &con) -> const typename Container::reference
{
pcg32 rand{pcg_extras::seed_seq_from<std::random_device>{}};
std::uniform_int_distribution<uint32_t> dist(0, con.size() - 1);
return con[dist(rand)];
}
template <typename Container>
inline auto choose_one(Container &con) -> typename Container::reference
{
pcg32 rand{pcg_extras::seed_seq_from<std::random_device>{}};
std::uniform_int_distribution<uint32_t> dist(0, con.size() - 1);
return con[dist(rand)];
}
template <typename Container>
inline auto choose_one_iter(Container &con) -> typename Container::iterator
{
pcg32 rand{pcg_extras::seed_seq_from<std::random_device>{}};
std::uniform_int_distribution<uint32_t> dist(0, con.size() - 1);
auto iter = con.begin();
std::advance(iter, dist(rand));
return iter;
}
template <typename Container>
inline auto choose_one_iter(const Container &con) -> const typename Container::iterator
{
pcg32 rand{pcg_extras::seed_seq_from<std::random_device>{}};
std::uniform_int_distribution<uint32_t> dist(0, con.size() - 1);
auto iter = con.begin();
std::advance(iter, dist(rand));
return iter;
}
template <typename T, uint32_t N>
inline const T& choose_one(const T(&array)[N])
{
pcg32 rand{pcg_extras::seed_seq_from<std::random_device>{}};
std::uniform_int_distribution<uint32_t> dist(0, N - 1);
return array[dist(rand)];
}
template <typename Container>
inline uint32_t one_in(const Container &con)
{
pcg32 rand{pcg_extras::seed_seq_from<std::random_device>{}};
std::uniform_int_distribution<uint32_t> dist(0, con.size() - 1);
return dist(rand);
}
}
<file_sep>#pragma once
#include <cstdint>
#include <cmath>
namespace virgil {
template <typename T>
struct vec3 {
using value_type = T;
//----------------------------------------------------------------------------//
constexpr vec3();
constexpr vec3(value_type x, value_type y, value_type z);
vec3(value_type v);
vec3(const vec3 &other);
vec3(vec3 &&vector);
vec3& operator=(vec3 other);
vec3 operator-() const;
void operator+=(const vec3<T> &other);
void operator-=(const vec3<T> &other);
void set(value_type x, value_type y, value_type z);
value_type length() const;
vec3<value_type> normalize() const;
void cross(const vec3<T> &other);
void dot(const vec3<T> &other);
value_type distance(const vec3<T> &other);
template <typename U>
vec3<U> cast_to();
//----------------------------------------------------------------------------//
value_type x, y, z;
};
//============================================================================--
//
//============================================================================--
template <typename T>
inline T length(const vec3<T> &v)
{
return v.x * v.x + v.y * v.y + v.z * v.z;
}
template <typename T>
inline vec3<T> cross(const vec3<T> &lhs, const vec3<T> &rhs)
{
return {
(lhs.y * rhs.z) - (lhs.z * rhs.y),
(lhs.z * rhs.x) - (lhs.x * rhs.z),
(lhs.x * rhs.y) - (lhs.y * rhs.x)
};
}
template <typename T>
inline T dot(const vec3<T> &lhs, const vec3<T> &rhs)
{
return (lhs.x * rhs.x) + (lhs.y * rhs.y) + (lhs.z * rhs.z);
}
template <typename T>
vec3<T> normalize(const vec3<T> &vec)
{
const T len = vec.length();
return {vec.x / len, vec.y / len, vec.z / len};
}
template <typename T>
inline vec3<T> operator-(const vec3<T> &lhs, const vec3<T> &rhs)
{
return {lhs.x - rhs.x, lhs.y - rhs.y, lhs.z - rhs.z};
}
template <typename T>
inline vec3<T> operator+(const vec3<T> &lhs, const vec3<T> &rhs)
{
return {lhs.x + rhs.x, lhs.y + rhs.y, lhs.z + rhs.z};
}
template <typename T>
inline vec3<T> operator*(const vec3<T> &lhs, const vec3<T> &rhs)
{
return {lhs.x * rhs.x, lhs.y * rhs.y, lhs.z * rhs.z};
}
template <typename T>
inline vec3<T> operator/(const vec3<T> &lhs, const vec3<T> &rhs)
{
return {lhs.x / rhs.x, lhs.y / rhs.y, lhs.z / rhs.z};
}
template <typename T, typename U>
inline vec3<T> operator/(const vec3<T> &lhs, U val)
{
return {lhs.x / val, lhs.y / val, lhs.z / val};
}
template <typename T, typename U>
inline vec3<T> operator*(const vec3<T> &lhs, U val)
{
return {lhs.x * val, lhs.y * val, lhs.z * val};
}
template <typename T>
inline bool operator==(const vec3<T> &lhs, const vec3<T> &rhs)
{
return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z;
}
template <typename T>
inline bool operator!=(const vec3<T> &lhs, const vec3<T> &rhs)
{
return lhs.x != rhs.x || lhs.y != rhs.y || lhs.z != rhs.z;
}
//============================================================================--
// Constructors
//============================================================================--
template <typename T>
constexpr vec3<T>::vec3() :
x{T()},
y{T()},
z{T()}
{
}
template <typename T>
constexpr vec3<T>::vec3(T x, T y, T z) :
x{x},
y{y},
z{z}
{
}
template <typename T>
vec3<T>::vec3(T v) :
x{v.x},
y{v.y},
z{v.z}
{
}
template <typename T>
vec3<T>::vec3(const vec3 &other) :
x{other.x},
y{other.y},
z{other.z}
{
}
template <typename T>
vec3<T>::vec3(vec3 &&other) :
x{other.x},
y{other.y},
z{other.z}
{
}
template <typename T>
vec3<T>& vec3<T>::operator=(vec3<T> other)
{
this->x = other.x;
this->y = other.y;
this->z = other.z;
return *this;
}
template <typename T>
vec3<T> vec3<T>::operator-() const
{
return {-x, -y, -z};
}
template <typename T>
void vec3<T>::operator+=(const vec3<T> &other)
{
x += other.x;
y += other.y;
z += other.z;
}
template <typename T>
void vec3<T>::operator-=(const vec3<T> &other)
{
x -= other.x;
y -= other.y;
z -= other.z;
}
//============================================================================--
// Setters
//============================================================================--
template <typename T>
void vec3<T>::set(T x, T y, T z)
{
this->x = x;
this->y = y;
this->z = z;
}
template <typename T>
template <typename U>
vec3<U> vec3<T>::cast_to()
{
return {static_cast<U>(x), static_cast<U>(y), static_cast<U>(z)};
}
template <typename T>
T vec3<T>::length() const
{
return std::sqrt((x * x) + (y * y) + (z * z));
}
template <typename T>
vec3<T> vec3<T>::normalize() const
{
return normalize(*this);
}
template <typename T>
void vec3<T>::cross(const vec3<T> &other)
{
*this = cross(*this, other);
}
template <typename T>
void vec3<T>::dot(const vec3<T> &other)
{
*this = dot(*this, other);
}
template <typename T>
auto vec3<T>::distance(const vec3<T> &other) -> value_type
{
const value_type dx = other.x - x;
const value_type dy = other.y - y;
const value_type dz = other.z - z;
return std::sqrt(dx * dx + dy * dy + dz * dz);
}
using vec3f = vec3<float>;
}
<file_sep>/**
* @file mat4.hpp
* @date 2015-03-30
* @detail 4D Matrix class
*/
#pragma once
#include <array>
#include "geometry/vec2.hpp"
#include "geometry/vec3.hpp"
#include "geometry/radians.hpp"
namespace virgil {
////////////////////////////////////////////////////////////////////////////////
// mat4
////////////////////////////////////////////////////////////////////////////////
/**
* @brief 4D Matrix
*/
class mat4 {
public:
mat4();
mat4(
float ax, float ay, float a_tx,
float bx, float by, float b_ty,
float cx, float cy, float c_w
);
mat4(
float a, float b, float c, float d,
float e, float f, float g, float h,
float i, float j, float k, float l,
float m, float n, float o, float p
);
mat4(const mat4 &other);
mat4(mat4 &&other);
mat4& operator=(const mat4 &other);
mat4& operator=(mat4 &&other);
vec2f operator*(vec2f v) const;
mat4 operator*(mat4 om) const;
mat4 transpose() const;
void set_identity();
void set_ortho(float left, float right, float top, float bottom, float near, float far);
void set_perspective(float fov, float aspect, float near, float far);
static mat4 ortho(float left, float right, float top, float bottom);
static mat4 ortho(float left, float right, float top, float bottom, float near, float far);
static mat4 perspective(float fov, float aspect, float near, float far);
void transform(float &x, float &y) const;
void translate(float x, float y, float z = 0.f);
static float* identity();
float& operator[](uint32_t idx);
float operator[](uint32_t idx) const;
const float* get() const;
float* get();
//----------------------------------------------------------------------------//
std::array<float, 16> mat; //! Matrix data
};
//============================================================================--
// Arithmetical operators
//============================================================================--
inline vec2f mat4::operator*(vec2f v) const
{
return vec2f(
(mat[0] * v.x) + (mat[4] * v.y) /* + mat[8] * 0.f*/ + mat[12],
(mat[1] * v.x) + (mat[5] * v.y) /* + mat[9] * 0.f*/ + mat[13]
);
}
/*inline mat4 operator*(const mat4 &lhs, const mat4 &rhs)
{
return {
lhs[0]*rhs[0] + lhs[4]*rhs[1] + lhs[8]*rhs[2] + lhs[12]*rhs[3],
lhs[1]*rhs[0] + lhs[5]*rhs[1] + lhs[9]*rhs[2] + lhs[13]*rhs[3],
lhs[2]*rhs[0] + lhs[6]*rhs[1] + lhs[10]*rhs[2] + lhs[14]*rhs[3],
lhs[3]*rhs[0] + lhs[7]*rhs[1] + lhs[11]*rhs[2] + lhs[15]*rhs[3],
lhs[0]*rhs[4] + lhs[4] * rhs[5] + lhs[8] * rhs[6] + lhs[12] * rhs[7],
lhs[1] * rhs[4] + lhs[5] * rhs[5] + lhs[9] * rhs[6] + lhs[13] * rhs[7],
lhs[2] * rhs[4] + lhs[6] * rhs[5] + lhs[10] * rhs[6] + lhs[14] * rhs[7],
lhs[3] * rhs[4] + lhs[7] * rhs[5] + lhs[11] * rhs[6] + lhs[15] * rhs[7],
lhs[0] * rhs[8] + lhs[4] * rhs[9] + lhs[8] * rhs[10] + lhs[12] * rhs[11],
lhs[1] * rhs[8] + lhs[5] * rhs[9] + lhs[9] * rhs[10] + lhs[13] * rhs[11],
lhs[2] * rhs[8] + lhs[6] * rhs[9] + lhs[10] * rhs[10] + lhs[14] * rhs[11],
lhs[3] * rhs[8] + lhs[7] * rhs[9] + lhs[11] * rhs[10] + lhs[15] * rhs[11],
lhs[0] * rhs[12] + lhs[4] * rhs[13] + lhs[8] * rhs[14] + lhs[12] * rhs[15],
lhs[1] * rhs[12] + lhs[5] * rhs[13] + lhs[9] * rhs[14] + lhs[13] * rhs[15],
lhs[2] * rhs[12] + lhs[6] * rhs[13] + lhs[10] * rhs[14] + lhs[14] * rhs[15],
lhs[3] * rhs[12] + lhs[7] * rhs[13] + lhs[11] * rhs[14] + lhs[15] * rhs[15]
};
}*/
//============================================================================--
//
//============================================================================--
inline mat4 mat4::perspective(float fov, float aspect, float near, float far)
{
mat4 ret;
ret.set_perspective(fov, aspect, near, far);
return ret;
}
inline void mat4::transform(float &x, float &y) const
{
x = mat[0] * x + mat[4] * y + mat[12];
y = mat[1] * x + mat[5] * y + mat[13];
}
inline void mat4::translate(float x, float y, float z)
{
mat[12] = x;
mat[13] = y;
mat[14] = z;
}
inline float* mat4::identity()
{
static mat4 identity_;
return identity_.get();
}
//============================================================================--
// Member access
//============================================================================--
inline float& mat4::operator[](uint32_t idx)
{
return mat[idx];
}
inline float mat4::operator[](uint32_t idx) const
{
return mat[idx];
}
inline const float* mat4::get() const
{
return mat.data();
}
inline float* mat4::get()
{
return mat.data();
}
inline mat4 look_at(vec3f eye, vec3f target, vec3f up)
{
const vec3f nz = normalize(target - eye);
const vec3f nx = normalize(cross(nz, up));
const vec3f ny = cross(nx, nz);
return {
nx.x, ny.x, -nz.x, 0.f,
nx.y, ny.y, -nz.y, 0.f,
nx.z, ny.z, -nz.z, 0.f,
-dot(nx, eye), -dot(ny, eye), dot(nz, eye), 1.f
};
}
inline mat4 translate(float x, float y, float z)
{
return {
1.f,0.f,0.f,0.f,
0.f,1.f,0.f,0.f,
0.f,0.f,1.f,0.f,
x, y, z,1.f
};
}
inline mat4 translate(const mat4 &mat, const vec3f &v)
{
mat4 ret(mat);
ret[12] = mat[0] * v.x + mat[4] * v.y + mat[8] * v.z + mat[12];
ret[13] = mat[1] * v.x + mat[5] * v.y + mat[9] * v.z + mat[13];
ret[14] = mat[2] * v.x + mat[6] * v.y + mat[10] * v.z + mat[14];
ret[15] = mat[3] * v.x + mat[7] * v.y + mat[11] * v.z + mat[15];
return ret;
}
inline mat4 scale(const mat4 &mat, const vec3f &v)
{
mat4 ret(mat);
ret[0] = mat[0] * v.x;
ret[5] = mat[5] * v.y;
ret[10] = mat[10] * v.z;
return ret;
}
inline mat4 rotate(const mat4 &mat, float angle, const vec3f &v)
{
mat4 rotation, ret;
const float rad = radians(angle);
const float c = std::cosf(rad);
const float s = std::sinf(rad);
const vec3f axis = normalize(v);
const vec3f trf{axis * (1.f - c)};
rotation[0] = c + trf.x * axis.x;
rotation[4] = trf.x * axis.y + s * axis.z;
rotation[8] = trf.x * axis.z - s * axis.x;
rotation[1] = trf.y * axis.x - s * axis.z;
rotation[5] = c + trf.y * axis.y;
rotation[9] = trf.y * axis.z + s * axis.x;
rotation[2] = trf.z * axis.x + s * axis.y;
rotation[6] = trf.z * axis.y - s * axis.x;
rotation[10] = c + trf.z * axis.z;
return mat * ret;
}
inline mat4 ortho(float left, float right, float top, float bottom, float near, float far)
{
return mat4(
2.f/(right - left), 0.f, 0.f, 0.f,
0.f, -2.f/(bottom - top), 0.f, 0.f,
0.f, 0.f, -2/(far - near), 0.f,
-(right + left) / (right - left), -(top + bottom) / (top - bottom), -(far + near) / (far - near), 1.f
);
}
}
| 9ba61e9b3588dbf110d11c8eed8c0e0f8295dd30 | [
"CMake",
"C++"
] | 94 | C++ | zoneB/virgil | 7607d16c00b77d4fe50f680e7d417bb2150bfa77 | ebdb82f5da9073ed5c376486a4700ef9f9247485 |
refs/heads/master | <repo_name>dwclark/ignite-demo<file_sep>/start_server.groovy
#!/bin/bash
export JAVA_OPTS='-Xmx1g -Xms1g'
java -jar build/libs/ignite-demo-0.1.0-all.jar "$@"
<file_sep>/clear_caches.sh
#!/bin/bash
rm -rf /tmp/ignite
rm -rf /var/ignite/*
<file_sep>/build.gradle
plugins {
id 'com.github.johnrengelman.shadow' version '2.0.1'
}
repositories {
jcenter()
}
apply plugin: 'groovy'
apply plugin: 'maven'
apply plugin: 'maven-publish'
apply plugin: 'application'
apply plugin: 'com.github.johnrengelman.shadow'
group = 'io.github.dwclark'
version = '0.1.0'
dependencies {
compile 'org.apache.ignite:ignite-core:2.2.0'
compile 'org.codehaus.groovy:groovy-all:2.4.12:indy'
}
compileGroovy {
groovyOptions.optimizationOptions.indy = true
}
mainClassName = 'io.github.dwclark.ignite.Server'
publishing {
publications {
mavenJava(MavenPublication) {
from components.java
}
}
}
| 33a05553a04581d62525c30020b0d6a436d316fe | [
"Shell",
"Gradle"
] | 3 | Shell | dwclark/ignite-demo | f8353f59959c0eac9c7c9b2a5201d6e04b243333 | 37ea6ff74b849f38fd6ccaccba8cde8c32096973 |
refs/heads/master | <file_sep>import bgImage1 from '../assets/images/bg-banner.png';
import bgImage2 from '../assets/images/bg-footer.png';
import logo02 from "../assets/images/BM02.png";
export default {
title: 'Components/Background',
};
export const BackgroundBanner = () => {
return /* html */ `
<div class="banner background background--img" style="background-image: url('${bgImage1}')">
<h3 class="background__title mb-24 uppercase">SERVICES</h3>
<nav aria-label="breadcrumb">
<ol class="breadcrumb">
<li class="breadcrumb__item"><a href="#">Home</a></li>
<li class="breadcrumb__item"><a href="#">Sevice</a></li>
<li class="breadcrumb__item active" aria-current="page"><a>Sevice</a></li>
</ol>
</nav>
</div>
`;
};
export const BackgroundFooter = () => {
return /* html */ `
<div class="footer background background--img background--center" style="background-image: url('${bgImage2}')">
<a class="logo" href="#">
<img src="${logo02}" alt="logo"/>
</a>
<nav class="navbar--light">
<ul class="navbar__list">
<li class="navbar__item">
<a href="" class="navbar__link">Home</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">About</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">Portfolio</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">Blog</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">Contact</a>
</li>
</ul>
</nav>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
export default {
title: 'Components/Title',
};
export const Title = () => {
return /* html */ `
<div class="title">
<h2 class="title__heading">
Latest Work
</h2>
<p class="title__desc text-desc">
On the other hand, we denounce with righteous.
</p>
</div>
`;
};
<file_sep>//page home
var swiper = new Swiper('.home .swiper-container', {
pagination: {
el: '.swiper-pagination',
},
});
var swiper = new Swiper('.home-gallery .swiper-container', {
pagination: {
el: '.swiper-pagination',
type: 'fraction',
},
navigation: {
nextEl: '.swiper-button-next',
prevEl: '.swiper-button-prev',
},
});
var swiper = new Swiper('.home-post .swiper-container', {
slidesPerView: 2,
spaceBetween: 50,
pagination: {
el: '.swiper-pagination',
clickable: true,
},
});
//page service
var swiper = new Swiper('.service-slide .swiper-container', {
pagination: {
el: '.swiper-pagination',
},
});
// let currentSlide = 0;
// const init = (slides, dots, n) => {
// console.log(slides, 1123)
// // console.log(dots)
// // console.log(n)
// slides.forEach((slide, index) => {
// slide.style.display = "none";
// dots.forEach((dot, index) => {
// dot.classList.remove("active");
// })
// })
// slides[n].style.display = "block";
// dots[n].classList.add("active");
// dots.forEach((dot, i) => {
// dot.addEventListener("click", () => {
// console.log(i)
// init(i);
// currentSlide = i;
// // console.log(currentSlide, 345566);
// })
// })
// }
// const next = () => {
// currentSlide >= slides.length - 1 ? currentSlide = 0 : currentSlide++;
// init(currentSlide);
// }
// const prev = () => {
// currentSlide <= 0 ? currentSlide = slides.length - 1 : currentSlide--
// init(currentSlide);
// }
// // setInterval(() => {
// // next();
// // }, 3000);
// // const home_slides = document.querySelectorAll(".home .slide__content");
// // const home_gallery_slides = document.querySelectorAll(".home-gallery .slide__content");
// // const home_post_slides = document.querySelectorAll(".home-post .slide__content");
// const service_slides = document.querySelectorAll(".service-slide .slide__content");
// // const home_dots = document.querySelectorAll('.home .dot');
// // const home_post_dots = document.querySelectorAll('.home-post .dot');
// const secrvice_dots = document.querySelectorAll('.service-slide .dot');
// // document.addEventListener("DOMContentLoaded", init(home_slides, home_dots, currentSlide));
// // document.addEventListener("DOMContentLoaded", init(home_gallery_slides, home_dots, currentSlide));
// document.addEventListener("DOMContentLoaded", init(service_slides, secrvice_dots, currentSlide));
// // document.querySelector(".next").addEventListener('click', next);
// // document.querySelector(".prev").addEventListener('click', prev);
<file_sep>import { action } from '@storybook/addon-actions';
import logo02 from "../assets/images/BM02.png";
export default {
title: 'Components/Form',
};
export const ReplyForm = () => {
return /* html */ `
<form action="" method="post" class="form-reply">
<div class="form__title">
LEAVE A REPLY
</div>
<div class="form__main">
<div class="group-field">
<label for="">Your name</label>
<input type="text" name="" id="">
</div>
<div class="group-field">
<label for="">Your email</label>
<input type="text" name="" id="">
</div>
<div class="group-field">
<label for="">Message</label>
<textarea name="" id="" cols="30" rows="6"></textarea>
</div>
<div class="group-field">
<label for=""></label>
<button class="btn btn-submit">SUBMIT</button>
</div>
</div>
</form>
`;
};
export const ContactForm = () => {
return /* html */ `
<div style="font-size: 20px; font-weight:bold">
Contact form
</div>
<div class="contact-info">
<div class="step-form">
<div class="step">
<h4 class="step__title">
<span>Your name</span> <span>*</span>
<i class="fas fa-arrow-circle-right"></i>
</h4>
<h4 class="step__title">
Your email<span> *</span>
</h4>
<h4 class="step__title">
Message <span>*</span>
</h4>
</div>
<div class="form">
<form action="">
<div class="form__field slide-page">
<input type="text" placeholder="Your name">
<a href="" class="step1"><i class="fas fa-arrow-circle-right icon-arrow"></i></a>
</div>
<div class="form__field">
<input type="text" placeholder="Your email">
<a href="" class="step2"><i class="fas fa-arrow-circle-right icon-arrow"></i></a>
</div>
<div class="form__field">
<input type="text" placeholder="Message">
<a href="" class="step3 submit"><i class="fas fa-arrow-circle-right icon-arrow"></i></a>
</div>
</form>
</div>
</div>
<div class="row">
<div class="col-mob-12 col-desk-6 left">
<img src="https://picsum.photos/635/477" alt="">
<a class="logo" href="#">
<img src="${logo02}" alt="logo" />
</a>
</div>
<div class="col-mob-12 col-desk-6">
<div class="contact-info__main">
<h3 class="contact-info__title">
CONTACT INFO
</h3>
<p class="contact-info__desc">
Lorem ipsum dolor sit, amet consectetur adipisicing elit.
Molestias inventore eius ducimus repellat soluta possimus
</p>
<div class="group-info address">
<span class="icon--contact-info">
<i class="pe-7s-map-marker"></i>
</span>
<div class="group-info__main">
<h3 class="group-info__title">
ADDRESS
</h3>
<p class="group-info__desc">
121 King Street, Melbourne Victoria 3000 Australia
</p>
</div>
</div>
<div class="group-info address">
<span class="icon--contact-info">
<i class="pe-7s-mail"></i>
</span>
<div class="group-info__main">
<h3 class="group-info__title">
EMAIL
</h3>
<p class="group-info__desc">
<EMAIL>
</p>
</div>
</div>
<div class="group-info address">
<span class="icon--contact-info">
<i class="pe-7s-phone"></i>
</span>
<div class="group-info__main">
<h3 class="group-info__title">
CALL ME
</h3>
<p class="group-info__desc">
+98 76543210 or +123 4567890
</p>
</div>
</div>
</div>
</div>
</div>
</div>
`;
};
<file_sep>jQuery(document).ready(function ($) {
// console.log($(`.gallery-container .gallery[data-filter="nature"]`));
(function changeAttr(item) {
$elem = jQuery(item);
$elem.click(function (event) {
event.preventDefault();
$currentItem = jQuery(this);
if ($currentItem.attr("data-filter") == 'all') {
$('.gallery').show();
$('.gallery').parent().show();
}
else {
$('.gallery').hide();
$('.gallery').parent().hide();
$(`.gallery-container .gallery[data-filter=${$currentItem.attr("data-filter")}] `).show();
$(`.gallery-container .gallery[data-filter=${$currentItem.attr("data-filter")}] `).parent().show();
}
});
})(".gallery-menu__item");
});
<file_sep>import { action } from '@storybook/addon-actions';
import img01 from '../assets/images/subcribe.jpg';
import avata from '../assets/images/avata.png';
import avata02 from '../assets/images/avata05.png';
import divider from '../assets/images/divider.png';
import signature from '../assets/images/Bowm.png';
export default {
title: 'Components/Box',
};
/*export const BoxSubcribe = () => {
return `
<div class="box">
<div class="box__img pr-5">
<img src="${img01}" alt="">
</div>
<div class="box__main box__info pr-50 algin-self-center">
<h3 class="box__title">
I’m <span><NAME>. <span>
</h3>
<p class="box__desc mb-55">
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
praesentium voluptatum deleniti atque corrupti quos dolores et quas
molestias excepturi sint occaecati cupiditate non provident, similique sunt
in culpa qui officia deserunt mollitia animi”
</p>
<form class="form form--subcribe">
<div class="form__item">
<input type="text" placeholder ="Email"/>
<button class="btn btn--subcribe">Subcribe</button>
</div>
</form>
</div>
</div>
`;
};
export const BoxIntro01 = () => {
return `
<div class="box box--intro box--small">
<div class="box__img">
<img src="${avata}" alt="">
</div>
<div class=" box__main box__info">
<h3 class="box__title">
HI, MY NAME IS <span><NAME>. <span>
</h3>
<p class="box__desc mb0">
I AM AN VIETNAMESE PRODUCT DESIGNER & PHOTOGRAPHY
</p>
</div>
</div>
`;
};
export const BoxIntro02 = () => {
return`
<div class="box box--intro box--large">
<div class="box__img">
<img src="${avata02}" alt="">
</div>
<div class="box__main">
<div class="box__info">
<h3 class="box__title">
HI, MY NAME IS <span><NAME>. <span>
</h3>
<p class="box__desc">
I AM AN VIETNAMESE PRODUCT DESIGNER & PHOTOGRAPHY
</p>
</div>
<div class="divider">
<img src="${divider}" alt="" class=" divider--diagonal"/>
</div>
<div class="box__text mb-20">
<p>
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
</p>
<img src="${signature}" class="box__signature mt-30"/><br/>
<p class="box__name-user"><NAME></p>
</div>
</div>
</div>
`;
};*/
export const BoxIcon = () => {
return /*html*/`
<div class="content content--icon">
<p class="content__desc text-color-secondary">
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati.
</p>
<span><NAME></span>
</div>
`;
};
export const BoxImg01 = () => {
return /*html*/`
<img src="${img01}" alt="">
`;
};
export const BoxImg02 = () => {
return /*html*/`
<img src="${avata02}" alt="" class="box__img box__img--small">
`;
};
export const BoxSubcribe1 = () => {
return /*html*/`
<div class="content content--subcribe">
<h3 class="content__title">
I’m <span><NAME>. <span>
</h3>
<p class="content__desc mb-55">
"At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis
praesentium voluptatum deleniti atque corrupti quos dolores et quas
molestias excepturi sint occaecati cupiditate non provident, similique sunt
in culpa qui officia deserunt mollitia animi”
</p>
<form class="form form--subcribe">
<div class="form__item">
<input type="text" placeholder ="Email"/>
<button class="btn btn--subcribe">Subcribe</button>
</div>
</form>
</div>
`;
};
export const BoxIntro011 = () => {
return /*html*/`
<div class="content content--intro content--small">
<h3 class="content__title">
HI, MY NAME IS <span><NAME>. <span>
</h3>
<p class="content__desc mb0">
I AM AN VIETNAMESE PRODUCT DESIGNER & PHOTOGRAPHY
</p>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
import divider01 from '../assets/images/divider1.png';
import divider02 from '../assets/images/divider2.png';
import divider03 from '../assets/images/divider.png';
export default {
title: 'Components/Divider',
};
export const Horizontal = () => {
return /* html */ `
<div class="divider">
<img src="${divider01}" alt="" class="divider--horizontal"/>
</div>
`;
};
export const Vertical = () => {
return /* html */ `
<div class="divider divider--vertical">
<img src="${divider02}" alt=""/>
</div>
`;
};
export const Diagonal = () => {
return /* html */ `
<div class="divider">
<img src="${divider03}" alt="" class=" divider--diagonal"/>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
export default {
title: 'Components/Counter',
};
export const Counter = () => {
return /* html */ `
<div class="counter">
<p class="counter__number">1052</p>
<h3 class="counter__title">
happy clients
</h3>
<hr>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
export default {
title: 'Components/Icon',
};
export const IconPlay = () => {
return /* html */ `
<i class="pe-7s-play icon__play"></i>
`;
};
export const IconRibbon = () => {
return /* html */ `
<i class="pe-7s-ribbon icon__ribbon"></i>
`;
};
export const FaceBook = () => {
return /* html */ `
<i class=" fab fa-facebook-f icon__share icon__share--facebook active center"></i>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
import blog01 from '../assets/images/blog1.png';
import blog02 from '../assets/images/blog2.png';
import blog03 from '../assets/images/blog3.png';
import blog04 from '../assets/images/blog4.png';
// import blog05 from '../assets/images/10.jpg';
import blog05 from '../assets/images/blog5.png';
// import blog06 from '../assets/images/11.jpg';
import blog06 from '../assets/images/blog6.png';
export default {
title: 'Components/Blog',
};
export const BlogTime = () => {
return /* html */ `
<div class="blog__time">
<h3 class="blog__time--day">01</h3>
<h4 class="blog__time--month">NOV</h4>
</div>
`;
};
export const BlogItem = () => {
return /* html */ `
<div class="blog">
<!--date-->
<div class="blog__time">
<h3 class="blog__time--day">01</h3>
<h4 class="blog__time--month">NOV</h4>
</div>
<!--blog-item-content-->
<div class="blog__main">
<div class="blog__img ">
<div class="overlay"></div>
<div class="aspect__img">
<img src="${blog01}">
</div>
<div class="blog__title uppercase">
<h4 class="blog__title--top">lifestyel</h4>
<h3 class="blog__title--bottom">this mistaken idea</h3>
</div>
<span class="blog__icon">
<i class="pe-7s-play icon__play"></i>
</span>
</div>
</div>
</div>
`;
};
export const BlogDetail = () => {
return /* html */ `
<div class="container">
<div class="row">
<div class="col-desk-12 col-mob-12">
<div class="blog blog--detail">
<!--date-->
<div class="blog__time">
<h3 class="blog__time--day">01</h3>
<h4 class="blog__time--month">NOV</h4>
</div>
<!--blog-item-content-->
<div class="blog__main">
<div class="blog__img bg-overlay">
<div class="aspect__img">
<img src="${blog01}">
</div>
<div class="blog__title uppercase">
<h4 class="blog__title--top">lifestyel</h4>
<h3 class="blog__title--bottom">this mistaken idea</h3>
</div>
<span class="blog__icon">
<i class="pe-7s-play icon__play"></i>
</span>
</div>
<div class="blog__desc">
<p>
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
</p>
</div>
</div>
</div>
</div>
</div>
</div>
`;
};
export const BlogSingle = () => {
return /* html */ `
<div class="container">
<div class="row blog--single">
<!--01-->
<div class="col-desk-12 col-mob-12">
<div class="background background--img background--large"
style="background-image: url('${blog01}')">
</div>
</div>
<div class="blog__main mx-auto mt-40">
<!--02-->
<div class="col-desk-12 col-mob-12 mb-40">
<div class="row">
<div class="col-desk-2 col-mob-3">
<div class="blog__time">
<h3 class="blog__time--day">01</h3>
<h4 class="blog__time--month">NOV</h4>
</div>
</div>
<div class="col-desk-10 col-mob-9">
<div class="blog__title--single uppercase">
<h4 class="blog__title--top">lifestyel</h4>
<h3 class="blog__title--bottom text-dark">this mistaken idea</h3>
</div>
</div>
</div>
</div>
<!--03-->
<div class="col-desk-12 col-mob-12">
<p class="blog__desc">
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio.
</p>
<p class="blog__desc">
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident, similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae. Itaque earum rerum hic tenetur a sapiente delectus, ut aut reiciendis voluptatibus maiores alias consequatur aut perferendis doloribus asperiores repellat.
</p>
</div>
<!--04-->
<div class="col-desk-12 col-mob-12 mb-50">
<div class="row">
<div class="col-desk-1 col-mob-3">
<i class="pe-7s-ribbon icon__ribbon"></i>
</div>
<div class="col-desk-11 col-mob-9 pl-20">
<p class="blog__desc text-color-secondary">
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati.
</p>
<b><NAME></b>
</div>
</div>
</div>
<!--05-->
<div class="col-desk-12 col-mob-12">
<p class="blog__desc mb-24">
Similique sunt in culpa qui officia deserunt mollitia animi, id est laborum et dolorum fuga. Et harum quidem rerum facilis est et expedita distinctio. Nam libero tempore, cum soluta nobis est eligendi optio cumque nihil impedit quo minus id quod maxime placeat facere possimus, omnis voluptas assumenda est, omnis dolor repellendus. Temporibus autem quibusdam et aut officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae.
</p>
<div class="blog__tag">
<b>Tag: </b>
<a href="">Wordpress,</a>
<a href="">Photoshop,</a>
<a href="">Html,</a>
<a href="">Travel</a>
</div>
<div class="blog__share">
<b>Share: </b>
<a href=""><i class="fab fa-facebook-f"></i></a>
<a href=""><i class="fab fa-twitter"></i></a>
<a href=""><i class="fab fa-pinterest"></i></a>
<a href=""><i class="fab fa-instagram"></i></a>
</div>
</div>
</div>
</div>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
import img01 from '../assets/images/img01.png';
export default {
title: 'Components/Hero',
};
export const Hero = () => {
return /*html*/`
<div class="hero">
<div class="hero__img">
<img src="${img01}"/>
</div>
<div class="hero__content mt-50">
<div class="hero__content--left">
<h3 class="hero__title">
DENOUNCING PLEASURE
</h3>
<p class="hero__desc text-desc">
At vero eos et accusamus et iusto odio dignissimos ducimus qui blanditiis praesentium voluptatum deleniti atque corrupti.
</p>
</div>
<div class="hero__content--right">
<p><span class="bold">COMPLETED : </span> 2016</p>
<p><span class="bold">DESIGNED : </span> Bowman</p>
<p><span class="bold">CATEGORIES : </span> Drink & Food</p>
<p><span class="bold">TAGS : </span> Drink & Food, Shop, Wordpress</p>
</div>
</div>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
import bg_text from '../assets/images/bg-text.jpg';
export default {
title: 'Components/Text',
};
export const TextFillColor = () => {
return /* html */ `
<h3 class="text text--img" style = "background-image: url('${bg_text}')">
journal
</h3>
`;
};
<file_sep>export default {
title: 'Components/Pagination',
};
export const Pagination = () => {
return /* html */ `
<nav aria-label="Page navigation example" class="navigation">
<ul class="pagination">
<li class="page-item"><a class="page-link previous" href="#"><i class="pe-7s-play"></i></a></li>
<li class="page-item"><a class="page-link active" href="#">1</a></li>
<li class="page-item"><a class="page-link" href="#">2</a></li>
<li class="page-item"><a class="page-link" href="#">3</a></li>
<li class="page-item"><a class="page-link next" href="#"><i class="pe-7s-play"></i></a></li>
</ul>
</nav>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
export default {
title: 'Components/Grid',
};
const styles = {
columnColor: `background-color: #ccc; border: 1px solid #eee; text-align: center; margin-bottom: 1rem`,
};
export const GridGrid = () => {
return /* html */ `
<div class="container">
<!--100%-->
<div class="row">
<div class="col col-desk-12" style="${styles.columnColor}">col desk 12</div>
</div>
<!--50%-->
<div class="row">
<div class="col-desk-6 col-mob-12" style="${styles.columnColor}">col desk 6</div>
<div class="col-desk-6 col-mob-12" style="${styles.columnColor}"> col desk 6</div>
</div>
<!--33.33%-->
<div class="row">
<div class="col-desk-4 col-tab-6 col-mob-12" style="${styles.columnColor}"> col desk 4</div>
<div class="col-desk-4 col-tab-6 col-mob-12" style="${styles.columnColor}"> col desk 4</div>
<div class="col-desk-4 col-tab-6 col-mob-12" style="${styles.columnColor}"> col des 4</div>
</div>
<!--25%-->
<div class="row">
<div class="col-desk-3 col-mob-12" style="${styles.columnColor}"> col desk 3</div>
<div class="col-desk-3 col-mob-12" style="${styles.columnColor}"> col desk 3</div>
<div class="col-desk-3 col-mob-12" style="${styles.columnColor}"> col desk 3</div>
<div class="col-desk-3 col-mob-12" style="${styles.columnColor}"> col desk 3</div>
</div>
</div>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
export default {
title: 'Components/Button',
};
export const BntSubmit = () => {
return /* html */ `
<button class="btn btn-submit">SUBMIT</button>
`;
};
export const BntSearch = () => {
return /* html */ `
<div class="search">
<div class="search__main">
<input type="text" class="search__text" placeholder="Search...">
<a href="" class="search__btn btn"><i class="pe-7s-search"></i></a>
</div>
</div>
`;
};
<file_sep>import logo0101 from "../assets/images/BM.png";
export default {
title: 'Components/Nav',
};
export const Nav = () => {
return /* html */ `
<nav class="navbar">
<a class="logo" href="#">
<img src="${logo0101}" alt="logo"/>
</a>
<button class="navbar__toggler btn--open ">
<i class="fas fa-bars"></i>
</button>
<!--menu-->
<div class="navbar__collapse">
<ul class="navbar__list">
<li class="navbar__item">
<a href="#" class="navbar__link">Home</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">About</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">Portfolio</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">Blog</a>
</li>
<li class="navbar__item">
<a href="" class="navbar__link">Contact</a>
</li>
</ul>
<div class="search">
<div class="search__main">
<input type="text" class="search__text" placeholder="Search...">
<a href="" class="search__btn btn"><i class="pe-7s-search"></i></a>
</div>
</div>
</div>
</nav>
`;
};
<file_sep>import { action } from '@storybook/addon-actions';
import img01 from '../assets/images/img01.png';
import img02 from '../assets/images/img02.png';
import divider03 from '../assets/images/divider.png';
export default {
title: 'Components/Gallery',
};
export const Gallery = () => {
return /* html */ `
<div class="gallery gallery--small">
<a href="">
<div class="overlay"></div>
<div class="gallery__img">
<img src="${img02}"/>
</div>
<div class="gallery__content">
<div class="gallery__text">
<h3 class="gallery__text--top uppercase text-white">
DENOUNCING PLEASURE
</h3>
<p class="gallery__text--bottom text-white">
Drink & Food
</p>
</div>
<div class="divider">
<img src="${divider03}" alt="" class=" divider--diagonal"/>
</div>
<a href="" class="gallery__icon">
<i class="pe-7s-play"></i>
</a>
</div>
</a>
</div>
`;
};
<file_sep>(function () {
'use-strict';
function init() {
const scrollToTop = document.querySelector('#btnTop');
if (scrollToTop) {
scrollToTop.addEventListener('click', function () {
window.scrollTo(0, 0);
});
console.log('init');
}
}
window.addEventListener('load', init);
})();
<file_sep>
window.addEventListener("DOMContentLoaded", function (event) {
console.log("meu");
const navbarCollapse = document.querySelector('.navbar__collapse');
console.log(navbarCollapse)
const toggle = document.querySelector('.navbar__toggler.btn--open');
console.log(toggle)
toggle.addEventListener('click', function (event) {
console.log("open")
navbarCollapse.classList.toggle('active');
})
});
| 531d6ffa13b273269e1965155ef0e53d9c48cfd2 | [
"JavaScript"
] | 19 | JavaScript | dungdoktpm/bm | adc6e301eb3b1d33f26f1702ff43b74c1db9de1f | f07b32e915bbd15af04ac328d46125e047096d17 |
refs/heads/master | <file_sep>// Brunch automatically concatenates all files in your
// watched paths. Those paths can be configured at
// config.paths.watched in "brunch-config.js".
//
// However, those files will only be executed if
// explicitly imported. The only exception are files
// in vendor, which are never wrapped in imports and
// therefore are always executed.
// Import dependencies
//
// If you no longer want to use a dependency, remember
// to also remove its path from "config.paths.watched".
import "phoenix_html"
// Import local files
//
// Local files can be imported directly using relative
// paths "./socket" or full ones "web/static/js/socket".
// import socket from "./socket"
import {Socket, LongPoller} from "phoenix"
class App {
static init() {
this.startChat()
this.startProjekktor()
this.startInfoUpdater()
}
static startProjekktor() {
projekktor('#player_a', {
poster: '/images/intro.jpg',
title: 'Techno Tuesday',
playerFlashMP4: '/projekktor/swf/StrobeMediaPlayback/StrobeMediaPlayback.swf',
playerFlashMP3: '/projekktor/swf/StrobeMediaPlayback/StrobeMediaPlayback.swf',
width: 600,
height: 400,
platforms: ['browser', 'flash', 'vlc'],
//platforms: ['browser', 'android', 'ios', 'native', 'flash', 'vlc'],
playlist: [ { 0: {
src: 'rtmp://techtues.net/live/techno', streamType:'rtmp', type:'video/flv'
} } ]
}, function(player) {
window.p = player;
p.setDebug(true);
})
}
static startChat() {
let socket = new Socket("/socket", {
logger: ((kind, msg, data) => { console.log(`${kind}: ${msg}`, data) })
})
socket.connect({user_id: "123"})
var $status = $("#status")
var $messages = $("#messages")
var $input = $("#message-input")
var $username = $("#username")
socket.onOpen( ev => console.log("OPEN", ev) )
socket.onError( ev => console.log("ERROR", ev) )
socket.onClose( e => console.log("CLOSE", e))
var chan = socket.channel("rooms:lobby", {})
chan.join().receive("ignore", () => console.log("auth error"))
.receive("ok", () => console.log("join ok"))
.receive("error", () => console.log("Connection interruption"))
chan.onError(e => console.log("something went wrong", e))
chan.onClose(e => console.log("channel closed", e))
$input.off("keypress").on("keypress", e => {
if (e.keyCode == 13) {
chan.push("new:msg", {user: $username.val(), body: $input.val()})
$input.val("")
}
})
chan.on("new:msg", msg => {
$messages.append(this.messageTemplate(msg))
// scrollTo(0, document.body.scrollHeight)
$messages.animate({scrollTop: $messages[0].scrollHeight}, 1000)
})
chan.on("user:entered", msg => {
var username = this.sanitize(msg.user || "anonymous")
$messages.append(`<br/><i>[${username} entered]</i>`)
})
}
static sanitize(html) { return $("<div/>").text(html).html() }
static messageTemplate(msg) {
let username = this.sanitize(msg.user || "anonymous")
let body = this.sanitize(msg.body)
return(`<p><a href='#'>[${username}]</a> ${body}</p>`)
}
static startInfoUpdater() {
var $info = $("#info")
setInterval(() => {
this.updateInfo($info)
}, 10000)
this.updateInfo($info)
}
static updateInfo($info) {
$.ajax({
url: "/info.json",
success: function(info) {
$info.html("<span>" + info["count"] + "</span> viewer"
+ (info["count"] == "1" ? "" : "s"))
}
});
}
}
$( () => App.init() )
export default App
| 8e306de610b03d86dcbe1a21d1bb65836b0cb214 | [
"JavaScript"
] | 1 | JavaScript | afebbraro/tuesday | 4a396c758e1c7ab307e9b94554adbce2217ee851 | a272d2fa16d16322ddec3333b9d95896076d4bc1 |
refs/heads/master | <file_sep>export const columns = [
{
title: "<NAME>",
width: 100,
dataIndex: "name",
key: "name",
fixed: "left"
},
{
title: "Age",
width: 100,
dataIndex: "age",
key: "age",
fixed: "left"
},
{
title: "Column 1",
dataIndex: "address",
key: "1",
width: 250
},
{
title: "Column 2",
dataIndex: "address",
key: "2",
width: 250
},
{
title: "Column 3",
dataIndex: "address",
key: "3",
width: 250
},
{
title: "Column 4",
dataIndex: "address",
key: "4",
width: 250
},
{
title: "Column 5",
dataIndex: "address",
key: "5",
width: 250
},
{
title: "Column 6",
dataIndex: "address",
key: "6",
width: 250
},
{
title: "Column 7",
dataIndex: "address",
key: "7",
width: 250
},
{
title: "Column 8",
dataIndex: "address",
key: "8"
}
];
| 78883a425e57cc6af9b531c5073acb4aa45b9546 | [
"JavaScript"
] | 1 | JavaScript | Cygra/dui_zhuan | a8b471d96db58ee766e7225143a0f4ae4bb8c1f2 | 3d723419882017a63facb2f7924aa853277aed3d |
refs/heads/master | <file_sep>const {
BN,
ether,
expectEvent,
expectRevert,
time,
balance,
} = require('@openzeppelin/test-helpers');
const { latest } = time;
const { tracker } = balance;
const abi = require('ethereumjs-abi');
const utils = web3.utils;
const { expect } = require('chai');
const { evmRevert, evmSnapshot, toUSDCWei } = require('./utils/utils');
// const { USDT_TOKEN, USDT_PROVIDER } = require('./utils/constants');
const { MAX_UINT256 } = require('@openzeppelin/test-helpers/src/constants');
const Nft721 = artifacts.require('Nft721');
contract('NFT721 Token', function ([_, user, someone]) {
before(async function () {
this.nft721 = await Nft721.new();
});
beforeEach(async function () {
id = await evmSnapshot();
balanceUser = await tracker(user);
balanceSomeone = await tracker(someone);
});
afterEach(async function () {
await evmRevert(id);
});
describe('nft', function () {
it('mint', async function () {
tokenURI =
'https://www.google.com/url?sa=i&url=https%3A%2F%2Fwww.facebook.com%2FDankMemeTherapy%2F&psig=AOvVaw3bnoFEeeidzDwYAKmSKOXc&ust=1636775694382000&source=images&cd=vfe&ved=0CAsQjRxqFwoTCJjCzOD2kfQCFQAAAAAdAAAAABAJ';
const nftId1 = await this.nft721.mintNft.call(user, tokenURI);
await this.nft721.mintNft(user, tokenURI);
console.log(nftId1.toString());
const nftId2 = await this.nft721.mintNft.call(user, tokenURI);
await this.nft721.mintNft(user, tokenURI);
console.log(nftId2.toString());
});
});
});
<file_sep>#!/bin/bash
set -o errexit
./node_modules/prettier/bin-prettier.js --write test/**/**/*.js
./node_modules/prettier/bin-prettier.js --write contracts/**/**/**/*.sol
<file_sep>module.exports = {
// /* DAI */
DAI_TOKEN: '0x6b175474e89094c44da98b954eedeac495271d0f',
DAI_PROVIDER: '0<KEY>',
// IOU
IOU_STATUS: { NoHack: 0, ApplyHack: 1, InHack: 2 },
};
<file_sep># nftLoan721
Side Project for use NFT as collateral to borrow money
- NFT owner can use NFT as collateral to borrow money
- Borrower can lend money to NFT owner and charge borrow fee when NFT owner repays the money
- Borrower can get the NFT which be collateral if the NFT owner can't repay enough money over the duration
- NFTs can be the flash loan. It will charge fees.
Notice: the contracts are not audited. Please take care of all of responsibly for yourself if use the contracts
<file_sep>const {
BN,
ether,
constants,
expectEvent,
expectRevert,
time,
balance,
} = require('@openzeppelin/test-helpers');
const { latest } = time;
const { tracker } = balance;
const abi = require('ethereumjs-abi');
const utils = web3.utils;
const { expect } = require('chai');
const { evmRevert, evmSnapshot, mulPercent } = require('./utils/utils');
const {
ZERO_ADDRESS,
ZERO_BYTES32,
} = require('@openzeppelin/test-helpers/src/constants');
const Nft721 = artifacts.require('Nft721');
const FlashNFT721 = artifacts.require('FlashNFT721');
const FlashNFT721ReceiverMock = artifacts.require('FlashNFT721ReceiverMock');
contract('FlashNFT721', function ([_, user, someone]) {
before(async function () {
this.nft721 = await Nft721.new();
this.flashNFT721 = await FlashNFT721.new();
this.flashNFT721Receiver = await FlashNFT721ReceiverMock.new();
for (i = 0; i < 10; i++) {
await this.nft721.mintNft(user, 'customer NFT url');
}
});
beforeEach(async function () {
id = await evmSnapshot();
balanceDeployer = await tracker(_);
balanceUser = await tracker(user);
balanceSomeone = await tracker(someone);
balanceFlashNFT721 = await tracker(this.flashNFT721.address);
});
afterEach(async function () {
await evmRevert(id);
});
describe('Freeze', function () {
it('normal', async function () {
await this.flashNFT721.setFreezing({
from: _,
});
expect(await this.flashNFT721.freezed.call()).to.be.true;
});
it('should revert: depositNFT freezing', async function () {
await this.flashNFT721.setFreezing({
from: _,
});
expect(await this.flashNFT721.freezed.call()).to.be.true;
// approve
const nftId = new BN(1);
const nftFee = new BN(100);
await this.nft721.approve(this.flashNFT721.address, nftId, {
from: user,
});
// deposit nft
await expectRevert(
this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
}),
'Freezed'
);
});
it('should revert: depositNFTs freezing', async function () {
await this.flashNFT721.setFreezing({
from: _,
});
expect(await this.flashNFT721.freezed.call()).to.be.true;
const nftId1 = new BN(1);
const nftFee1 = new BN(100);
const nftId2 = new BN(2);
const nftFee2 = new BN(500);
// approve
await this.nft721.approve(this.flashNFT721.address, nftId1, {
from: user,
});
await this.nft721.approve(this.flashNFT721.address, nftId2, {
from: user,
});
await expectRevert(
this.flashNFT721.depositNFTs(
this.nft721.address,
[nftId1, nftId2],
[nftFee1, nftFee2],
{
from: user,
}
),
'Freezed'
);
});
it('should revert: flashLoan freezing', async function () {
const nftId1 = new BN(1);
const nftFee1 = new BN(100);
const nftId2 = new BN(2);
const nftFee2 = new BN(500);
// approve
await this.nft721.approve(this.flashNFT721.address, nftId1, {
from: user,
});
await this.nft721.approve(this.flashNFT721.address, nftId2, {
from: user,
});
await this.flashNFT721.depositNFTs(
this.nft721.address,
[nftId1, nftId2],
[nftFee1, nftFee2],
{
from: user,
}
);
await this.flashNFT721.setFreezing({
from: _,
});
expect(await this.flashNFT721.freezed.call()).to.be.true;
await expectRevert(
this.flashNFT721.flashLoan(
this.nft721.address,
[nftId1],
this.flashNFT721Receiver.address,
web3.utils.hexToBytes(ZERO_BYTES32),
{
from: someone,
value: nftFee1,
}
),
'Freezed.'
);
});
it('unFreeaing ', async function () {
await this.flashNFT721.setFreezing({
from: _,
});
expect(await this.flashNFT721.freezed.call()).to.be.true;
// approve
const nftId = new BN(1);
const nftFee = new BN(100);
await this.nft721.approve(this.flashNFT721.address, nftId, {
from: user,
});
// deposit nft
await expectRevert(
this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
}),
'Freezed'
);
await this.flashNFT721.unFreezing({
from: _,
});
expect(await this.flashNFT721.freezed.call()).to.be.false;
await this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
});
// verify
const nft = await this.flashNFT721.nfts.call(this.nft721.address, nftId);
expect(nft['owner']).to.be.eq(user);
expect(nft['borrowFee']).to.be.bignumber.eq(nftFee);
});
});
describe('deposit', function () {
it('deposit single nft', async function () {
// approve
await this.nft721.approve(this.flashNFT721.address, '1', {
from: user,
});
// deposit nft
const nftId = new BN(1);
const nftFee = new BN(100);
await this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
});
// verify
const nft = await this.flashNFT721.nfts.call(this.nft721.address, nftId);
expect(nft['owner']).to.be.eq(user);
expect(nft['borrowFee']).to.be.bignumber.eq(nftFee);
});
it('deposit multiple nfts', async function () {
const nftId1 = new BN(1);
const nftFee1 = new BN(100);
const nftId2 = new BN(2);
const nftFee2 = new BN(500);
// approve
await this.nft721.approve(this.flashNFT721.address, nftId1, {
from: user,
});
await this.nft721.approve(this.flashNFT721.address, nftId2, {
from: user,
});
// deposit nft
await this.flashNFT721.depositNFTs(
this.nft721.address,
[nftId1, nftId2],
[nftFee1, nftFee2],
{
from: user,
}
);
// verify
const nft1 = await this.flashNFT721.nfts.call(
this.nft721.address,
nftId1
);
expect(nft1['owner']).to.be.eq(user);
expect(nft1['borrowFee']).to.be.bignumber.eq(nftFee1);
const nft2 = await this.flashNFT721.nfts.call(
this.nft721.address,
nftId2
);
expect(nft2['owner']).to.be.eq(user);
expect(nft2['borrowFee']).to.be.bignumber.eq(nftFee2);
});
it('should revert: deposit repeat nft', async function () {
const nftId = new BN(1);
const nftFee = new BN(100);
// approve
await this.nft721.approve(this.flashNFT721.address, nftId, {
from: user,
});
// deposit nft
await this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
});
// verify
const nft1 = await this.flashNFT721.nfts.call(this.nft721.address, nftId);
expect(nft1['owner']).to.be.eq(user);
expect(nft1['borrowFee']).to.be.bignumber.eq(nftFee);
await expectRevert(
this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
}),
'NFT has been deposited'
);
});
it('should revert: no approved', async function () {
const nftId = new BN(1);
const nftFee = new BN(100);
await expectRevert(
this.flashNFT721.depositNFT(this.nft721.address, nftId, nftFee, {
from: user,
}),
'ERC721: transfer caller is not owner nor approved.'
);
});
});
describe('withdraw', function () {
beforeEach(async function () {
const nftId1 = new BN(1);
const nftFee1 = new BN(100);
const nftId2 = new BN(2);
const nftFee2 = new BN(200);
// approve
await this.nft721.approve(this.flashNFT721.address, nftId1, {
from: user,
});
await this.nft721.approve(this.flashNFT721.address, nftId2, {
from: user,
});
// deposit nft
await this.flashNFT721.depositNFTs(
this.nft721.address,
[nftId1, nftId2],
[nftFee1, nftFee2],
{
from: user,
}
);
});
it('withdraw single nft', async function () {
const nftId = new BN(1);
await this.flashNFT721.withdrawNFT(this.nft721.address, nftId, {
from: user,
});
// verify
const nft = await this.flashNFT721.nfts.call(this.nft721.address, nftId);
expect(nft['owner']).to.be.eq(ZERO_ADDRESS);
expect(nft['borrowFee']).to.be.zero;
});
it('deposit multiple nfts', async function () {
const nftId1 = new BN(1);
const nftId2 = new BN(2);
await this.flashNFT721.withdrawNFTs(
this.nft721.address,
[nftId1, nftId2],
{
from: user,
}
);
// verify
const nft1 = await this.flashNFT721.nfts.call(
this.nft721.address,
nftId1
);
expect(nft1['owner']).to.be.eq(ZERO_ADDRESS);
expect(nft1['borrowFee']).to.be.zero;
const nft2 = await this.flashNFT721.nfts.call(
this.nft721.address,
nftId2
);
expect(nft2['owner']).to.be.eq(ZERO_ADDRESS);
expect(nft2['borrowFee']).to.be.zero;
});
it('should revert: withdraw single nft by invalid owner', async function () {
const nftId = new BN(1);
await expectRevert(
this.flashNFT721.withdrawNFT(this.nft721.address, nftId, {
from: someone,
}),
'Invalid NFT owner.'
);
});
it('should revert: withdraw multiple nfts by invalid owner', async function () {
const nftId = new BN(1);
await expectRevert(
this.flashNFT721.withdrawNFT(this.nft721.address, [nftId], {
from: someone,
}),
'Invalid NFT owner.'
);
});
});
describe('Flashloan', function () {
var nftFee1;
var nftFee2;
beforeEach(async function () {
const nftId1 = new BN(1);
nftFee1 = new BN(10000);
const nftId2 = new BN(2);
nftFee2 = new BN(20000);
// approve
await this.nft721.approve(this.flashNFT721.address, nftId1, {
from: user,
});
await this.nft721.approve(this.flashNFT721.address, nftId2, {
from: user,
});
// deposit nft
await this.flashNFT721.depositNFTs(
this.nft721.address,
[nftId1, nftId2],
[nftFee1, nftFee2],
{
from: user,
}
);
await balanceUser.get();
});
it('flashLoan nfts', async function () {
nftId1 = new BN(1);
nftId2 = new BN(2);
const nftIds = [nftId1, nftId2];
const totalFee = nftFee1.add(nftFee2);
const receipt = await this.flashNFT721.flashLoan(
this.nft721.address,
nftIds,
this.flashNFT721Receiver.address,
web3.utils.hexToBytes(ZERO_BYTES32),
{
from: someone,
value: totalFee,
}
);
// check nft owner
expect(await balanceSomeone.delta()).to.be.bignumber.eq(
ether('0').sub(totalFee).sub(new BN(receipt.receipt.gasUsed))
);
const adminFee = mulPercent(totalFee, 3, 1000);
expect(await balanceDeployer.delta()).to.be.bignumber.eq(adminFee);
expect(await balanceUser.delta()).to.be.bignumber.eq(
totalFee.sub(adminFee)
);
expect(await balanceFlashNFT721.get()).to.be.zero;
for (i = 0; i < nftIds.length; i++) {
expect(await this.nft721.ownerOf.call(nftIds[i])).to.be.eq(
this.flashNFT721.address
);
expectEvent(receipt, 'FlashLoan', {
nftAddress: this.nft721.address,
nftId: nftIds[i],
operator: this.flashNFT721Receiver.address,
});
expectEvent.inTransaction(
receipt.tx,
this.flashNFT721Receiver,
'FlashLoanNFT',
{
nftAddress: this.nft721.address,
nftId: nftIds[i],
owner: this.flashNFT721Receiver.address,
}
);
}
});
});
// use external nft 721
});
<file_sep># Exit script as soon as a command fails.
set -o errexit
# Executes cleanup function at script exit.
trap cleanup EXIT
cleanup() {
# kill the ganache instance that we started (if we started one and if it's still running).
if [ -n "$ganache_pid" ] && ps -p $ganache_pid > /dev/null; then
kill -9 $ganache_pid
fi
}
ganache_port=8545
ganache_running() {
nc -z localhost "$ganache_port"
}
start_ganache() {
# TEST_MNEMONIC_PHRASE="gentle clown nuclear usual liberty clump limit theory ability border rib sort"
DAI_PROVIDER="0x2a1530C4C41db0B0b2bB646CB5Eb1A67b7158667"
node_modules/.bin/ganache-cli --gasLimit 0xfffffffffff --debug -f $ETH_MAINNET_NODE -u "$DAI_PROVIDER" > /dev/null &
ganache_pid=$!
}
if ganache_running; then
echo "Using existing ganache instance"
else
echo "Starting new ganache instance"
start_ganache
fi
truffle version
# Execute rest test files with suffix `.test.js` with single `truffle test`
node_modules/.bin/truffle test "$@"
| 9babefa5f7d3e6f85a40d959a6d853c7e8b3852e | [
"JavaScript",
"Markdown",
"Shell"
] | 6 | JavaScript | ksin751119/nftLoan721 | 1cf58e4c77ae5860f5d4ac3444bd47a76efc5ea6 | 13e742c18f8a1e398b64b895ad9ccb3cf0665ce7 |
refs/heads/master | <repo_name>ma-ha/WSO2-Deployer-Maven-Plugin<file_sep>/src/main/java/org/mh/mojo/wso2deployment/helper/Wso2WarDeployer.java
package org.mh.mojo.wso2deployment.helper;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.maven.plugin.logging.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.mh.mojo.wso2deployment.Serverconfig;
import org.wso2.carbon.webapp.mgt.WebappAdminPortType;
import org.wso2.carbon.webapp.mgt.xsd.WebappUploadData;
/**
* Deploy test for WSO2 Application Server 5.2
*
* @author mh
*/
public class Wso2WarDeployer {
/** File read buffer size. */
private static final int READ_BUFFER_SIZE = 4096;
/** the admin web service proxy */
public WebappAdminPortType adminSvc;
protected Log log;
/** construct proxy */
public Wso2WarDeployer ( Serverconfig server, Log log ) {
if ( server == null ) {
log.error( "Server config is null." );
return;
}
this.log = log;
log.info( "[WSO2 WAR Deployer] Init WSO2 SOAP client proxy (CXF 2.7.x type)..." );
Properties properties = System.getProperties();
properties.put( "org.apache.cxf.stax.allowInsecureParser", "1" );
System.setProperties( properties );
// ClientProxyFactoryBean
JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean();
/* serviceUrl = "https://localhost:9443" */
String adminURL = server.getServerUrl() + "WebappAdmin.WebappAdminHttpsEndpoint/";
log.info( "[WSO2 WAR Deployer] Endpoint URL: "+adminURL);
clientFactory.setAddress( adminURL );
clientFactory.setServiceClass( WebappAdminPortType.class );
clientFactory.setUsername( server.getAdminUser() );
clientFactory.setPassword( server.getAdminPassword() );
log.info( "[WSO2 WAR Deployer] start proxy ..." );
adminSvc = (WebappAdminPortType) clientFactory.create();
Client clientProxy = ClientProxy.getClient( adminSvc );
HTTPConduit conduit = (HTTPConduit) clientProxy.getConduit();
HTTPClientPolicy httpClientPolicy = conduit.getClient();
httpClientPolicy.setAllowChunking( false );
String targetAddr = conduit.getTarget().getAddress().getValue();
if ( targetAddr.toLowerCase().startsWith( "https:" ) ) {
TrustManager[] simpleTrustManager = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
} };
TLSClientParameters tlsParams = new TLSClientParameters();
tlsParams.setTrustManagers( simpleTrustManager );
tlsParams.setDisableCNCheck( true ); // TODO enable CN check
conduit.setTlsClientParameters( tlsParams );
}
}
/** prepare input data for war upload web service */
private WebappUploadData getUploadData( File artifact, String name, String version ) throws Exception {
InputStream fin = new FileInputStream( artifact );
WebappUploadData data = new WebappUploadData();
log.info( "[WSO2 WAR Deployer] Prepare uploadWebapp for "+name+" ...");
// File file = new File( warFilename );
// FileInputStream fin = new FileInputStream( deployable );
final byte fileContent[] = readFully( fin );
final int cnt = fileContent.length;
log.info( "[WSO2 WAR Deployer] Read war with "+cnt+" bytes" );
fin.close();
org.wso2.carbon.webapp.mgt.xsd.ObjectFactory webappAdmObjFactory = new org.wso2.carbon.webapp.mgt.xsd.ObjectFactory();
data.setFileName( webappAdmObjFactory.createWebappUploadDataFileName( name ) );
data.setVersion( webappAdmObjFactory.createWebappUploadDataVersion( version ) );
data.setDataHandler( webappAdmObjFactory.createWebappUploadDataDataHandler( fileContent ) );
return data;
}
/** upload war via SOAP admin web service */
public boolean upload( File artifact, String warFileName, String version ) {
log.info( "[WSO2 WAR Deployer] Start WAR upload" );
WebappUploadData warUpload;
try {
warUpload = getUploadData( artifact, warFileName, version );
} catch ( Exception e ) {
e.printStackTrace();
return false;
}
List<WebappUploadData> webappUploadDataList = new ArrayList<WebappUploadData>();
webappUploadDataList.add( warUpload );
log.info( "[WSO2 WAR Deployer] Invoking uploadWebapp for "+warFileName+" ...");
Boolean uplResult = adminSvc.uploadWebapp( webappUploadDataList );
log.info( "[WSO2 WAR Deployer] Upload "+warFileName+" result: "+uplResult );
return uplResult;
}
/**
* Read all data available in this input stream and return it as byte[].
* Take care for memory on large files!
* <p>
* Imported from org.jcoderz.commons.util.IoUtil
* </p>
*
* @param is
* the input stream to read from (will not be closed).
* @return a byte array containing all data read from the is.
*/
private byte[] readFully( InputStream is ) throws IOException {
final byte[] buffer = new byte[READ_BUFFER_SIZE];
int read = 0;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
while ( (read = is.read( buffer )) >= 0 ) {
out.write( buffer, 0, read );
}
return out.toByteArray();
}
}
<file_sep>/src/main/java/org/wso2/carbon/application/upload/UploadApp.java
package org.wso2.carbon.application.upload;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import org.wso2.carbon.application.upload.xsd.UploadedFileItem;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="fileItems" type="{http://upload.application.carbon.wso2.org/xsd}UploadedFileItem" maxOccurs="unbounded" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"fileItems"
})
@XmlRootElement(name = "uploadApp")
public class UploadApp {
@XmlElement(nillable = true)
protected List<UploadedFileItem> fileItems;
/**
* Gets the value of the fileItems property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the fileItems property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFileItems().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link UploadedFileItem }
*
*
*/
public List<UploadedFileItem> getFileItems() {
if (fileItems == null) {
fileItems = new ArrayList<UploadedFileItem>();
}
return this.fileItems;
}
}
<file_sep>/src/main/java/org/wso2/carbon/webapp/mgt/xsd/SessionsWrapper.java
package org.wso2.carbon.webapp.mgt.xsd;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for SessionsWrapper complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="SessionsWrapper">
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="numberOfActiveSessions" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="numberOfPages" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* <element name="sessions" type="{http://mgt.webapp.carbon.wso2.org/xsd}SessionMetadata" maxOccurs="unbounded" minOccurs="0"/>
* <element name="webappFileName" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "SessionsWrapper", propOrder = {
"numberOfActiveSessions",
"numberOfPages",
"sessions",
"webappFileName"
})
public class SessionsWrapper {
protected Integer numberOfActiveSessions;
protected Integer numberOfPages;
@XmlElement(nillable = true)
protected List<SessionMetadata> sessions;
@XmlElementRef(name = "webappFileName", namespace = "http://mgt.webapp.carbon.wso2.org/xsd", type = JAXBElement.class, required = false)
protected JAXBElement<String> webappFileName;
/**
* Gets the value of the numberOfActiveSessions property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getNumberOfActiveSessions() {
return numberOfActiveSessions;
}
/**
* Sets the value of the numberOfActiveSessions property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setNumberOfActiveSessions(Integer value) {
this.numberOfActiveSessions = value;
}
/**
* Gets the value of the numberOfPages property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getNumberOfPages() {
return numberOfPages;
}
/**
* Sets the value of the numberOfPages property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setNumberOfPages(Integer value) {
this.numberOfPages = value;
}
/**
* Gets the value of the sessions property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the sessions property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSessions().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link SessionMetadata }
*
*
*/
public List<SessionMetadata> getSessions() {
if (sessions == null) {
sessions = new ArrayList<SessionMetadata>();
}
return this.sessions;
}
/**
* Gets the value of the webappFileName property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getWebappFileName() {
return webappFileName;
}
/**
* Sets the value of the webappFileName property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setWebappFileName(JAXBElement<String> value) {
this.webappFileName = value;
}
}
<file_sep>/src/main/java/axis2/apache/org/xsd/ObjectFactory.java
package axis2.apache.org.xsd;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
import org.wso2.carbon.core.persistence.metadata.xsd.ArtifactMetadataException;
import org.wso2.carbon.webapp.mgt.xsd.SessionsWrapper;
import org.wso2.carbon.webapp.mgt.xsd.WebappMetadata;
import org.wso2.carbon.webapp.mgt.xsd.WebappsWrapper;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the axis2.apache.org.xsd package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _ExpireSessionsWebappFileName_QNAME = new QName("http://org.apache.axis2/xsd", "webappFileName");
private final static QName _GetStartedWebappResponseReturn_QNAME = new QName("http://org.apache.axis2/xsd", "return");
private final static QName _SetBamConfigurationValue_QNAME = new QName("http://org.apache.axis2/xsd", "value");
private final static QName _GetPagedWebappsSummaryWebappState_QNAME = new QName("http://org.apache.axis2/xsd", "webappState");
private final static QName _GetPagedWebappsSummaryWebappType_QNAME = new QName("http://org.apache.axis2/xsd", "webappType");
private final static QName _GetPagedWebappsSummaryWebappSearchString_QNAME = new QName("http://org.apache.axis2/xsd", "webappSearchString");
private final static QName _WebappAdminArtifactMetadataExceptionArtifactMetadataException_QNAME = new QName("http://org.apache.axis2/xsd", "ArtifactMetadataException");
private final static QName _ChangeDefaultAppVersionFileName_QNAME = new QName("http://org.apache.axis2/xsd", "fileName");
private final static QName _ChangeDefaultAppVersionAppGroupName_QNAME = new QName("http://org.apache.axis2/xsd", "appGroupName");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: axis2.apache.org.xsd
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link ChangeDefaultAppVersion }
*
*/
public ChangeDefaultAppVersion createChangeDefaultAppVersion() {
return new ChangeDefaultAppVersion();
}
/**
* Create an instance of {@link StopAllWebapps }
*
*/
public StopAllWebapps createStopAllWebapps() {
return new StopAllWebapps();
}
/**
* Create an instance of {@link ExpireAllSessions }
*
*/
public ExpireAllSessions createExpireAllSessions() {
return new ExpireAllSessions();
}
/**
* Create an instance of {@link GetActiveSessions }
*
*/
public GetActiveSessions createGetActiveSessions() {
return new GetActiveSessions();
}
/**
* Create an instance of {@link DeleteAllFaultyWebapps }
*
*/
public DeleteAllFaultyWebapps createDeleteAllFaultyWebapps() {
return new DeleteAllFaultyWebapps();
}
/**
* Create an instance of {@link IsDefaultVersionManagementEnabledResponse }
*
*/
public IsDefaultVersionManagementEnabledResponse createIsDefaultVersionManagementEnabledResponse() {
return new IsDefaultVersionManagementEnabledResponse();
}
/**
* Create an instance of {@link GetStoppedWebappResponse }
*
*/
public GetStoppedWebappResponse createGetStoppedWebappResponse() {
return new GetStoppedWebappResponse();
}
/**
* Create an instance of {@link GetStoppedWebapp }
*
*/
public GetStoppedWebapp createGetStoppedWebapp() {
return new GetStoppedWebapp();
}
/**
* Create an instance of {@link UploadWebapp }
*
*/
public UploadWebapp createUploadWebapp() {
return new UploadWebapp();
}
/**
* Create an instance of {@link GetStartedWebappResponse }
*
*/
public GetStartedWebappResponse createGetStartedWebappResponse() {
return new GetStartedWebappResponse();
}
/**
* Create an instance of {@link ExpireSessions }
*
*/
public ExpireSessions createExpireSessions() {
return new ExpireSessions();
}
/**
* Create an instance of {@link DeleteAllStartedWebapps }
*
*/
public DeleteAllStartedWebapps createDeleteAllStartedWebapps() {
return new DeleteAllStartedWebapps();
}
/**
* Create an instance of {@link StartAllWebapps }
*
*/
public StartAllWebapps createStartAllWebapps() {
return new StartAllWebapps();
}
/**
* Create an instance of {@link GetPagedWebappsSummary }
*
*/
public GetPagedWebappsSummary createGetPagedWebappsSummary() {
return new GetPagedWebappsSummary();
}
/**
* Create an instance of {@link DeleteStoppedWebapps }
*
*/
public DeleteStoppedWebapps createDeleteStoppedWebapps() {
return new DeleteStoppedWebapps();
}
/**
* Create an instance of {@link SetBamConfiguration }
*
*/
public SetBamConfiguration createSetBamConfiguration() {
return new SetBamConfiguration();
}
/**
* Create an instance of {@link WebappAdminArtifactMetadataException }
*
*/
public WebappAdminArtifactMetadataException createWebappAdminArtifactMetadataException() {
return new WebappAdminArtifactMetadataException();
}
/**
* Create an instance of {@link IsDefaultVersionManagementEnabled }
*
*/
public IsDefaultVersionManagementEnabled createIsDefaultVersionManagementEnabled() {
return new IsDefaultVersionManagementEnabled();
}
/**
* Create an instance of {@link StartWebapps }
*
*/
public StartWebapps createStartWebapps() {
return new StartWebapps();
}
/**
* Create an instance of {@link DeleteWebapp }
*
*/
public DeleteWebapp createDeleteWebapp() {
return new DeleteWebapp();
}
/**
* Create an instance of {@link IsUnpackWARs }
*
*/
public IsUnpackWARs createIsUnpackWARs() {
return new IsUnpackWARs();
}
/**
* Create an instance of {@link GetStartedWebapp }
*
*/
public GetStartedWebapp createGetStartedWebapp() {
return new GetStartedWebapp();
}
/**
* Create an instance of {@link GetPagedWebappsSummaryResponse }
*
*/
public GetPagedWebappsSummaryResponse createGetPagedWebappsSummaryResponse() {
return new GetPagedWebappsSummaryResponse();
}
/**
* Create an instance of {@link DeleteAllWebApps }
*
*/
public DeleteAllWebApps createDeleteAllWebApps() {
return new DeleteAllWebApps();
}
/**
* Create an instance of {@link IsUnpackWARsResponse }
*
*/
public IsUnpackWARsResponse createIsUnpackWARsResponse() {
return new IsUnpackWARsResponse();
}
/**
* Create an instance of {@link ReloadAllWebapps }
*
*/
public ReloadAllWebapps createReloadAllWebapps() {
return new ReloadAllWebapps();
}
/**
* Create an instance of {@link DeleteFaultyWebapps }
*
*/
public DeleteFaultyWebapps createDeleteFaultyWebapps() {
return new DeleteFaultyWebapps();
}
/**
* Create an instance of {@link GetPagedFaultyWebappsSummaryResponse }
*
*/
public GetPagedFaultyWebappsSummaryResponse createGetPagedFaultyWebappsSummaryResponse() {
return new GetPagedFaultyWebappsSummaryResponse();
}
/**
* Create an instance of {@link GetBamConfiguration }
*
*/
public GetBamConfiguration createGetBamConfiguration() {
return new GetBamConfiguration();
}
/**
* Create an instance of {@link ReloadWebapps }
*
*/
public ReloadWebapps createReloadWebapps() {
return new ReloadWebapps();
}
/**
* Create an instance of {@link GetBamConfigurationResponse }
*
*/
public GetBamConfigurationResponse createGetBamConfigurationResponse() {
return new GetBamConfigurationResponse();
}
/**
* Create an instance of {@link DeleteStartedWebapps }
*
*/
public DeleteStartedWebapps createDeleteStartedWebapps() {
return new DeleteStartedWebapps();
}
/**
* Create an instance of {@link ExpireSessionsInWebapps }
*
*/
public ExpireSessionsInWebapps createExpireSessionsInWebapps() {
return new ExpireSessionsInWebapps();
}
/**
* Create an instance of {@link ExpireSessionsInAllWebapps }
*
*/
public ExpireSessionsInAllWebapps createExpireSessionsInAllWebapps() {
return new ExpireSessionsInAllWebapps();
}
/**
* Create an instance of {@link GetActiveSessionsResponse }
*
*/
public GetActiveSessionsResponse createGetActiveSessionsResponse() {
return new GetActiveSessionsResponse();
}
/**
* Create an instance of {@link StopWebapps }
*
*/
public StopWebapps createStopWebapps() {
return new StopWebapps();
}
/**
* Create an instance of {@link DownloadWarFileHandlerResponse }
*
*/
public DownloadWarFileHandlerResponse createDownloadWarFileHandlerResponse() {
return new DownloadWarFileHandlerResponse();
}
/**
* Create an instance of {@link DownloadWarFileHandler }
*
*/
public DownloadWarFileHandler createDownloadWarFileHandler() {
return new DownloadWarFileHandler();
}
/**
* Create an instance of {@link UploadWebappResponse }
*
*/
public UploadWebappResponse createUploadWebappResponse() {
return new UploadWebappResponse();
}
/**
* Create an instance of {@link ExpireSessionsInWebapp }
*
*/
public ExpireSessionsInWebapp createExpireSessionsInWebapp() {
return new ExpireSessionsInWebapp();
}
/**
* Create an instance of {@link GetPagedFaultyWebappsSummary }
*
*/
public GetPagedFaultyWebappsSummary createGetPagedFaultyWebappsSummary() {
return new GetPagedFaultyWebappsSummary();
}
/**
* Create an instance of {@link DeleteAllStoppedWebapps }
*
*/
public DeleteAllStoppedWebapps createDeleteAllStoppedWebapps() {
return new DeleteAllStoppedWebapps();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = ExpireSessions.class)
public JAXBElement<String> createExpireSessionsWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, ExpireSessions.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = GetStoppedWebapp.class)
public JAXBElement<String> createGetStoppedWebappWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, GetStoppedWebapp.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = GetBamConfiguration.class)
public JAXBElement<String> createGetBamConfigurationWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, GetBamConfiguration.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = ExpireSessionsInWebapp.class)
public JAXBElement<String> createExpireSessionsInWebappWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, ExpireSessionsInWebapp.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link WebappMetadata }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = GetStartedWebappResponse.class)
public JAXBElement<WebappMetadata> createGetStartedWebappResponseReturn(WebappMetadata value) {
return new JAXBElement<WebappMetadata>(_GetStartedWebappResponseReturn_QNAME, WebappMetadata.class, GetStartedWebappResponse.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = ExpireAllSessions.class)
public JAXBElement<String> createExpireAllSessionsWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, ExpireAllSessions.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = GetStartedWebapp.class)
public JAXBElement<String> createGetStartedWebappWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, GetStartedWebapp.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "value", scope = SetBamConfiguration.class)
public JAXBElement<String> createSetBamConfigurationValue(String value) {
return new JAXBElement<String>(_SetBamConfigurationValue_QNAME, String.class, SetBamConfiguration.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = SetBamConfiguration.class)
public JAXBElement<String> createSetBamConfigurationWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, SetBamConfiguration.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SessionsWrapper }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = GetActiveSessionsResponse.class)
public JAXBElement<SessionsWrapper> createGetActiveSessionsResponseReturn(SessionsWrapper value) {
return new JAXBElement<SessionsWrapper>(_GetStartedWebappResponseReturn_QNAME, SessionsWrapper.class, GetActiveSessionsResponse.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappState", scope = GetPagedWebappsSummary.class)
public JAXBElement<String> createGetPagedWebappsSummaryWebappState(String value) {
return new JAXBElement<String>(_GetPagedWebappsSummaryWebappState_QNAME, String.class, GetPagedWebappsSummary.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappType", scope = GetPagedWebappsSummary.class)
public JAXBElement<String> createGetPagedWebappsSummaryWebappType(String value) {
return new JAXBElement<String>(_GetPagedWebappsSummaryWebappType_QNAME, String.class, GetPagedWebappsSummary.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappSearchString", scope = GetPagedWebappsSummary.class)
public JAXBElement<String> createGetPagedWebappsSummaryWebappSearchString(String value) {
return new JAXBElement<String>(_GetPagedWebappsSummaryWebappSearchString_QNAME, String.class, GetPagedWebappsSummary.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link ArtifactMetadataException }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "ArtifactMetadataException", scope = WebappAdminArtifactMetadataException.class)
public JAXBElement<ArtifactMetadataException> createWebappAdminArtifactMetadataExceptionArtifactMetadataException(ArtifactMetadataException value) {
return new JAXBElement<ArtifactMetadataException>(_WebappAdminArtifactMetadataExceptionArtifactMetadataException_QNAME, ArtifactMetadataException.class, WebappAdminArtifactMetadataException.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "fileName", scope = ChangeDefaultAppVersion.class)
public JAXBElement<String> createChangeDefaultAppVersionFileName(String value) {
return new JAXBElement<String>(_ChangeDefaultAppVersionFileName_QNAME, String.class, ChangeDefaultAppVersion.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "appGroupName", scope = ChangeDefaultAppVersion.class)
public JAXBElement<String> createChangeDefaultAppVersionAppGroupName(String value) {
return new JAXBElement<String>(_ChangeDefaultAppVersionAppGroupName_QNAME, String.class, ChangeDefaultAppVersion.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link WebappsWrapper }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = GetPagedFaultyWebappsSummaryResponse.class)
public JAXBElement<WebappsWrapper> createGetPagedFaultyWebappsSummaryResponseReturn(WebappsWrapper value) {
return new JAXBElement<WebappsWrapper>(_GetStartedWebappResponseReturn_QNAME, WebappsWrapper.class, GetPagedFaultyWebappsSummaryResponse.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = GetActiveSessions.class)
public JAXBElement<String> createGetActiveSessionsWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, GetActiveSessions.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = GetBamConfigurationResponse.class)
public JAXBElement<String> createGetBamConfigurationResponseReturn(String value) {
return new JAXBElement<String>(_GetStartedWebappResponseReturn_QNAME, String.class, GetBamConfigurationResponse.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link WebappsWrapper }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = GetPagedWebappsSummaryResponse.class)
public JAXBElement<WebappsWrapper> createGetPagedWebappsSummaryResponseReturn(WebappsWrapper value) {
return new JAXBElement<WebappsWrapper>(_GetStartedWebappResponseReturn_QNAME, WebappsWrapper.class, GetPagedWebappsSummaryResponse.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link WebappMetadata }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = GetStoppedWebappResponse.class)
public JAXBElement<WebappMetadata> createGetStoppedWebappResponseReturn(WebappMetadata value) {
return new JAXBElement<WebappMetadata>(_GetStartedWebappResponseReturn_QNAME, WebappMetadata.class, GetStoppedWebappResponse.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappType", scope = GetPagedFaultyWebappsSummary.class)
public JAXBElement<String> createGetPagedFaultyWebappsSummaryWebappType(String value) {
return new JAXBElement<String>(_GetPagedWebappsSummaryWebappType_QNAME, String.class, GetPagedFaultyWebappsSummary.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappSearchString", scope = GetPagedFaultyWebappsSummary.class)
public JAXBElement<String> createGetPagedFaultyWebappsSummaryWebappSearchString(String value) {
return new JAXBElement<String>(_GetPagedWebappsSummaryWebappSearchString_QNAME, String.class, GetPagedFaultyWebappsSummary.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "fileName", scope = DownloadWarFileHandler.class)
public JAXBElement<String> createDownloadWarFileHandlerFileName(String value) {
return new JAXBElement<String>(_ChangeDefaultAppVersionFileName_QNAME, String.class, DownloadWarFileHandler.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappType", scope = DownloadWarFileHandler.class)
public JAXBElement<String> createDownloadWarFileHandlerWebappType(String value) {
return new JAXBElement<String>(_GetPagedWebappsSummaryWebappType_QNAME, String.class, DownloadWarFileHandler.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "webappFileName", scope = DeleteWebapp.class)
public JAXBElement<String> createDeleteWebappWebappFileName(String value) {
return new JAXBElement<String>(_ExpireSessionsWebappFileName_QNAME, String.class, DeleteWebapp.class, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link byte[]}{@code >}}
*
*/
@XmlElementDecl(namespace = "http://org.apache.axis2/xsd", name = "return", scope = DownloadWarFileHandlerResponse.class)
public JAXBElement<byte[]> createDownloadWarFileHandlerResponseReturn(byte[] value) {
return new JAXBElement<byte[]>(_GetStartedWebappResponseReturn_QNAME, byte[].class, DownloadWarFileHandlerResponse.class, ((byte[]) value));
}
}
<file_sep>/src/main/java/org/wso2/carbon/aarservices/ServiceUploaderPortType.java
package org.wso2.carbon.aarservices;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.FaultAction;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.7.8
* 2013-12-23T10:35:02.314+01:00
* Generated source version: 2.7.8
*
*/
@WebService(targetNamespace = "http://aarservices.carbon.wso2.org", name = "ServiceUploaderPortType")
@XmlSeeAlso({ObjectFactory.class, org.wso2.carbon.aarservices.xsd.ObjectFactory.class})
public interface ServiceUploaderPortType {
@WebResult(name = "return", targetNamespace = "http://aarservices.carbon.wso2.org")
@Action(input = "urn:uploadService", output = "urn:uploadServiceResponse", fault = {@FaultAction(className = Exception_Exception.class, value = "urn:uploadServiceException")})
@RequestWrapper(localName = "uploadService", targetNamespace = "http://aarservices.carbon.wso2.org", className = "org.wso2.carbon.aarservices.UploadService")
@WebMethod(action = "urn:uploadService")
@ResponseWrapper(localName = "uploadServiceResponse", targetNamespace = "http://aarservices.carbon.wso2.org", className = "org.wso2.carbon.aarservices.UploadServiceResponse")
public java.lang.String uploadService(
@WebParam(name = "serviceDataList", targetNamespace = "http://aarservices.carbon.wso2.org")
java.util.List<org.wso2.carbon.aarservices.xsd.AARServiceData> serviceDataList
) throws Exception_Exception;
}
<file_sep>/src/main/java/org/mh/mojo/wso2deployment/helper/Wso2CarDeployer.java
package org.mh.mojo.wso2deployment.helper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.maven.plugin.logging.Log;
import org.mh.mojo.wso2deployment.Serverconfig;
import org.wso2.carbon.application.upload.CarbonAppUploaderPortType;
import org.wso2.carbon.application.upload.UploadApp;
import org.wso2.carbon.application.upload.xsd.UploadedFileItem;
public class Wso2CarDeployer {
/** The WSO2 management web service stub to upload a CAR file */
private CarbonAppUploaderPortType uploadSvc;
/** Maven logger */
protected Log log;
/** File read buffer size. */
private static final int READ_BUFFER_SIZE = 4096;
/**
* Constructor sets up the web service proxy client
*
* @param listener
*/
public Wso2CarDeployer ( Serverconfig server, Log log) {
if ( server == null ) {
log.error( "Server config is null." );
return;
}
this.log = log;
log.info( "[WSO2 WAR Deployer] Init WSO2 SOAP client proxy (CXF 2.7.x type)..." );
log.info( "[WSO2 CAR Deployer] Set up SOAP admin client..." );
Properties properties = System.getProperties();
properties.put( "org.apache.cxf.stax.allowInsecureParser", "1" );
System.setProperties( properties );
JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean();
clientFactory.setAddress( server.getServerUrl() + "CarbonAppUploader.CarbonAppUploaderHttpsEndpoint/" );
clientFactory.setServiceClass( CarbonAppUploaderPortType.class );
clientFactory.setUsername( server.getAdminUser() );
clientFactory.setPassword( server.getAdminPassword() );
uploadSvc = (CarbonAppUploaderPortType) clientFactory.create();
Client clientProxy = ClientProxy.getClient( uploadSvc );
HTTPConduit conduit = (HTTPConduit) clientProxy.getConduit();
HTTPClientPolicy httpClientPolicy = conduit.getClient();
httpClientPolicy.setAllowChunking( false );
String targetAddr = conduit.getTarget().getAddress().getValue();
if ( targetAddr.toLowerCase().startsWith( "https:" ) ) {
TrustManager[] simpleTrustManager = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
} };
TLSClientParameters tlsParams = new TLSClientParameters();
tlsParams.setTrustManagers( simpleTrustManager );
tlsParams.setDisableCNCheck( true ); // TODO enable CN check
conduit.setTlsClientParameters( tlsParams );
}
}
/**
* Upload carbon abb artifact to WSO2 ESB or other WSO2 Server via WSO2 SOAP
* service
*
* @param appType
* @param artifactFileName
* Filename for CAR artifact to upload to WSO2 Server
* @return true, if upload is OK
*/
public boolean uploadCAR ( File artifact, String targetFileName, String appType ) {
log.info( "[WSO2 CAR Deployer] Start CAR upload" );
boolean result = true;
try {
InputStream fin = new FileInputStream( artifact );
UploadedFileItem fileItem = new UploadedFileItem();
org.wso2.carbon.application.upload.xsd.ObjectFactory fieldFactory = new org.wso2.carbon.application.upload.xsd.ObjectFactory();
// byte[] fileContent = readFile( fin );
final byte fileContent[] = readFully( fin );
final int cnt = fileContent.length;
log.info( "[WSO2 CAR Deployer] Read CAR with " + cnt + " bytes" );
fileItem.setDataHandler( fieldFactory.createUploadedFileItemDataHandler( fileContent ) );
fileItem.setFileName( fieldFactory.createUploadedFileItemFileName( targetFileName ) );
fileItem.setFileType( fieldFactory.createUploadedFileItemFileType( appType ) );
UploadApp req = new UploadApp();
req.getFileItems().add( fileItem );
log.info( "[WSO2 CAR Deployer] Invoking uploadService for " + targetFileName + " ..." );
uploadSvc.uploadApp( req );
} catch ( Exception e ) {
if ( e.getMessage().indexOf( "uploadAppResponse was not recognized" ) > 0 ) {
// TODO: Why is the response empty in WSDL?
log.info( "[WSO2 CAR Deployer] WARNING: response ignored ;-)" );
} else {
log.error( "[WSO2 CAR Deployer] ERROR: " + e.getMessage() );
result = false;
log.error( e );
}
}
return result;
}
/**
* Read all data available in this input stream and return it as byte[].
* Take care for memory on large files!
* <p>
* Imported from org.jcoderz.commons.util.IoUtil
* </p>
*
* @param is
* the input stream to read from (will not be closed).
* @return a byte array containing all data read from the is.
*/
private byte[] readFully( InputStream is ) throws IOException {
final byte[] buffer = new byte[READ_BUFFER_SIZE];
int read = 0;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
while ( (read = is.read( buffer )) >= 0 ) {
out.write( buffer, 0, read );
}
return out.toByteArray();
}
}
<file_sep>/src/main/java/org/wso2/carbon/webapp/mgt/WebappAdminPortType_WebappAdminHttpsSoap12Endpoint_Client.java
package org.wso2.carbon.webapp.mgt;
/**
* Please modify this class to meet your needs
* This class is not complete
*/
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.FaultAction;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.7.8
* 2013-12-20T13:24:52.967+01:00
* Generated source version: 2.7.8
*
*/
public final class WebappAdminPortType_WebappAdminHttpsSoap12Endpoint_Client {
private static final QName SERVICE_NAME = new QName("http://mgt.webapp.carbon.wso2.org", "WebappAdmin");
private WebappAdminPortType_WebappAdminHttpsSoap12Endpoint_Client() {
}
public static void main(String args[]) throws java.lang.Exception {
URL wsdlURL = WebappAdmin.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
WebappAdmin ss = new WebappAdmin(wsdlURL, SERVICE_NAME);
WebappAdminPortType port = ss.getWebappAdminHttpsSoap12Endpoint();
{
System.out.println("Invoking expireAllSessions...");
java.lang.String _expireAllSessions_webappFileName = "";
port.expireAllSessions(_expireAllSessions_webappFileName);
}
{
System.out.println("Invoking isDefaultVersionManagementEnabled...");
java.lang.Boolean _isDefaultVersionManagementEnabled__return = port.isDefaultVersionManagementEnabled();
System.out.println("isDefaultVersionManagementEnabled.result=" + _isDefaultVersionManagementEnabled__return);
}
{
System.out.println("Invoking deleteAllStartedWebapps...");
port.deleteAllStartedWebapps();
}
{
System.out.println("Invoking uploadWebapp...");
java.util.List<org.wso2.carbon.webapp.mgt.xsd.WebappUploadData> _uploadWebapp_webappUploadDataList = null;
java.lang.Boolean _uploadWebapp__return = port.uploadWebapp(_uploadWebapp_webappUploadDataList);
System.out.println("uploadWebapp.result=" + _uploadWebapp__return);
}
{
System.out.println("Invoking changeDefaultAppVersion...");
java.lang.String _changeDefaultAppVersion_appGroupName = "";
java.lang.String _changeDefaultAppVersion_fileName = "";
try {
port.changeDefaultAppVersion(_changeDefaultAppVersion_appGroupName, _changeDefaultAppVersion_fileName);
} catch (WebappAdminArtifactMetadataException e) {
System.out.println("Expected exception: WebappAdminArtifactMetadataException has occurred.");
System.out.println(e.toString());
}
}
{
System.out.println("Invoking getPagedFaultyWebappsSummary...");
java.lang.String _getPagedFaultyWebappsSummary_webappSearchString = "";
java.lang.String _getPagedFaultyWebappsSummary_webappType = "";
java.lang.Integer _getPagedFaultyWebappsSummary_pageNumber = null;
org.wso2.carbon.webapp.mgt.xsd.WebappsWrapper _getPagedFaultyWebappsSummary__return = port.getPagedFaultyWebappsSummary(_getPagedFaultyWebappsSummary_webappSearchString, _getPagedFaultyWebappsSummary_webappType, _getPagedFaultyWebappsSummary_pageNumber);
System.out.println("getPagedFaultyWebappsSummary.result=" + _getPagedFaultyWebappsSummary__return);
}
{
System.out.println("Invoking isUnpackWARs...");
java.lang.Boolean _isUnpackWARs__return = port.isUnpackWARs();
System.out.println("isUnpackWARs.result=" + _isUnpackWARs__return);
}
{
System.out.println("Invoking getActiveSessions...");
java.lang.String _getActiveSessions_webappFileName = "";
java.lang.Integer _getActiveSessions_pageNumber = null;
org.wso2.carbon.webapp.mgt.xsd.SessionsWrapper _getActiveSessions__return = port.getActiveSessions(_getActiveSessions_webappFileName, _getActiveSessions_pageNumber);
System.out.println("getActiveSessions.result=" + _getActiveSessions__return);
}
{
System.out.println("Invoking deleteAllStoppedWebapps...");
port.deleteAllStoppedWebapps();
}
{
System.out.println("Invoking reloadWebapps...");
java.util.List<java.lang.String> _reloadWebapps_webappFileNames = null;
port.reloadWebapps(_reloadWebapps_webappFileNames);
}
{
System.out.println("Invoking deleteStoppedWebapps...");
java.util.List<java.lang.String> _deleteStoppedWebapps_webappFileNames = null;
port.deleteStoppedWebapps(_deleteStoppedWebapps_webappFileNames);
}
{
System.out.println("Invoking expireSessions...");
java.lang.String _expireSessions_webappFileName = "";
java.util.List<java.lang.String> _expireSessions_sessionIDs = null;
port.expireSessions(_expireSessions_webappFileName, _expireSessions_sessionIDs);
}
{
System.out.println("Invoking stopAllWebapps...");
port.stopAllWebapps();
}
{
System.out.println("Invoking stopWebapps...");
java.util.List<java.lang.String> _stopWebapps_webappFileNames = null;
port.stopWebapps(_stopWebapps_webappFileNames);
}
{
System.out.println("Invoking setBamConfiguration...");
java.lang.String _setBamConfiguration_webappFileName = "";
java.lang.String _setBamConfiguration_value = "";
port.setBamConfiguration(_setBamConfiguration_webappFileName, _setBamConfiguration_value);
}
{
System.out.println("Invoking getStartedWebapp...");
java.lang.String _getStartedWebapp_webappFileName = "";
org.wso2.carbon.webapp.mgt.xsd.WebappMetadata _getStartedWebapp__return = port.getStartedWebapp(_getStartedWebapp_webappFileName);
System.out.println("getStartedWebapp.result=" + _getStartedWebapp__return);
}
{
System.out.println("Invoking deleteStartedWebapps...");
java.util.List<java.lang.String> _deleteStartedWebapps_webappFileNames = null;
port.deleteStartedWebapps(_deleteStartedWebapps_webappFileNames);
}
{
System.out.println("Invoking deleteAllWebApps...");
java.util.List<java.lang.String> _deleteAllWebApps_webappFileNames = null;
port.deleteAllWebApps(_deleteAllWebApps_webappFileNames);
}
{
System.out.println("Invoking deleteFaultyWebapps...");
java.util.List<java.lang.String> _deleteFaultyWebapps_webappFileNames = null;
port.deleteFaultyWebapps(_deleteFaultyWebapps_webappFileNames);
}
{
System.out.println("Invoking startWebapps...");
java.util.List<java.lang.String> _startWebapps_webappFileNames = null;
port.startWebapps(_startWebapps_webappFileNames);
}
{
System.out.println("Invoking deleteAllFaultyWebapps...");
port.deleteAllFaultyWebapps();
}
{
System.out.println("Invoking expireSessionsInAllWebapps...");
port.expireSessionsInAllWebapps();
}
{
System.out.println("Invoking getBamConfiguration...");
java.lang.String _getBamConfiguration_webappFileName = "";
java.lang.String _getBamConfiguration__return = port.getBamConfiguration(_getBamConfiguration_webappFileName);
System.out.println("getBamConfiguration.result=" + _getBamConfiguration__return);
}
{
System.out.println("Invoking getStoppedWebapp...");
java.lang.String _getStoppedWebapp_webappFileName = "";
org.wso2.carbon.webapp.mgt.xsd.WebappMetadata _getStoppedWebapp__return = port.getStoppedWebapp(_getStoppedWebapp_webappFileName);
System.out.println("getStoppedWebapp.result=" + _getStoppedWebapp__return);
}
{
System.out.println("Invoking expireSessionsInWebapps...");
java.util.List<java.lang.String> _expireSessionsInWebapps_webappFileNames = null;
port.expireSessionsInWebapps(_expireSessionsInWebapps_webappFileNames);
}
{
System.out.println("Invoking startAllWebapps...");
port.startAllWebapps();
}
{
System.out.println("Invoking expireSessionsInWebapp...");
java.lang.String _expireSessionsInWebapp_webappFileName = "";
java.lang.Long _expireSessionsInWebapp_maxSessionLifetimeMillis = null;
port.expireSessionsInWebapp(_expireSessionsInWebapp_webappFileName, _expireSessionsInWebapp_maxSessionLifetimeMillis);
}
{
System.out.println("Invoking deleteWebapp...");
java.lang.String _deleteWebapp_webappFileName = "";
port.deleteWebapp(_deleteWebapp_webappFileName);
}
{
System.out.println("Invoking reloadAllWebapps...");
port.reloadAllWebapps();
}
{
System.out.println("Invoking getPagedWebappsSummary...");
java.lang.String _getPagedWebappsSummary_webappSearchString = "";
java.lang.String _getPagedWebappsSummary_webappState = "";
java.lang.String _getPagedWebappsSummary_webappType = "";
java.lang.Integer _getPagedWebappsSummary_pageNumber = null;
org.wso2.carbon.webapp.mgt.xsd.WebappsWrapper _getPagedWebappsSummary__return = port.getPagedWebappsSummary(_getPagedWebappsSummary_webappSearchString, _getPagedWebappsSummary_webappState, _getPagedWebappsSummary_webappType, _getPagedWebappsSummary_pageNumber);
System.out.println("getPagedWebappsSummary.result=" + _getPagedWebappsSummary__return);
}
{
System.out.println("Invoking downloadWarFileHandler...");
java.lang.String _downloadWarFileHandler_fileName = "";
java.lang.String _downloadWarFileHandler_webappType = "";
byte[] _downloadWarFileHandler__return = port.downloadWarFileHandler(_downloadWarFileHandler_fileName, _downloadWarFileHandler_webappType);
System.out.println("downloadWarFileHandler.result=" + _downloadWarFileHandler__return);
}
System.exit(0);
}
}
<file_sep>/src/main/java/org/mh/mojo/wso2deployment/AbstractDeployerMojo.java
package org.mh.mojo.wso2deployment;
import java.util.List;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.metadata.ArtifactMetadataSource;
import org.apache.maven.artifact.repository.ArtifactRepository;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.plugin.AbstractMojo;
import org.apache.maven.plugins.annotations.Component;
import org.apache.maven.plugins.annotations.Parameter;
import org.apache.maven.project.MavenProject;
import org.apache.maven.project.MavenProjectBuilder;
/**
* @author mh
*/
public abstract class AbstractDeployerMojo extends AbstractMojo {
@Parameter( defaultValue = "${project}", readonly = true )
protected MavenProject project;
@Component
protected ArtifactResolver artifactResolver;
@Component
protected ArtifactFactory artifactFactory;
@Component
protected ArtifactMetadataSource metadataSource;
@Parameter( readonly = true, required = true, defaultValue = "${localRepository}" )
protected ArtifactRepository localRepository;
@Parameter( readonly = true, required = true, defaultValue = "${project.remoteArtifactRepositories}" )
protected List<ArtifactRepository> remoteRepositories;
@Component
protected ArtifactResolver resolver;
@Component
protected MavenProjectBuilder projectBuilder;
}
<file_sep>/src/main/java/org/wso2/carbon/aarservices/Exception_Exception.java
package org.wso2.carbon.aarservices;
import javax.xml.ws.WebFault;
/**
* This class was generated by Apache CXF 2.7.8
* 2013-12-23T10:35:02.259+01:00
* Generated source version: 2.7.8
*/
@WebFault(name = "Exception", targetNamespace = "http://aarservices.carbon.wso2.org")
public class Exception_Exception extends java.lang.Exception {
private org.wso2.carbon.aarservices.Exception exception;
public Exception_Exception() {
super();
}
public Exception_Exception(String message) {
super(message);
}
public Exception_Exception(String message, Throwable cause) {
super(message, cause);
}
public Exception_Exception(String message, org.wso2.carbon.aarservices.Exception exception) {
super(message);
this.exception = exception;
}
public Exception_Exception(String message, org.wso2.carbon.aarservices.Exception exception, Throwable cause) {
super(message, cause);
this.exception = exception;
}
public org.wso2.carbon.aarservices.Exception getFaultInfo() {
return this.exception;
}
}
<file_sep>/src/main/java/org/mh/mojo/wso2deployment/helper/Wso2AarDeployer.java
package org.mh.mojo.wso2deployment.helper;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import org.apache.cxf.configuration.jsse.TLSClientParameters;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.transport.http.HTTPConduit;
import org.apache.cxf.transports.http.configuration.HTTPClientPolicy;
import org.apache.maven.plugin.logging.Log;
import org.mh.mojo.wso2deployment.Serverconfig;
import org.wso2.carbon.aarservices.Exception_Exception;
import org.wso2.carbon.aarservices.ServiceUploaderPortType;
import org.wso2.carbon.aarservices.xsd.AARServiceData;
import org.wso2.carbon.aarservices.xsd.ObjectFactory;
/**
*
* @author mh
*
*/
public class Wso2AarDeployer {
public ServiceUploaderPortType uploadSvc;
protected Log log;
/** File read buffer size. */
private static final int READ_BUFFER_SIZE = 4096;
/**
* Constructor sets up the web service proxy client
*
* @param listener
*/
public Wso2AarDeployer ( Serverconfig server, Log log ) {
if ( server == null ) {
log.error( "Server config is null." );
return;
}
this.log = log;
log.info( "[WSO2 WAR Deployer] Init WSO2 SOAP client proxy (CXF 2.7.x type)..." );
log.info( "[WSO2 AAR Deployer] Set up SOAP admin client for URL " + server.getServerUrl() + "..." );
Properties properties = System.getProperties();
properties.put( "org.apache.cxf.stax.allowInsecureParser", "1" );
System.setProperties( properties );
JaxWsProxyFactoryBean clientFactory = new JaxWsProxyFactoryBean();
clientFactory.setAddress( server.getServerUrl() + "ServiceUploader.ServiceUploaderHttpsEndpoint/" );
clientFactory.setServiceClass( ServiceUploaderPortType.class );
clientFactory.setUsername( server.getAdminUser() );
clientFactory.setPassword( server.getAdminPassword() );
uploadSvc = (ServiceUploaderPortType) clientFactory.create();
Client clientProxy = ClientProxy.getClient( uploadSvc );
HTTPConduit conduit = (HTTPConduit) clientProxy.getConduit();
HTTPClientPolicy httpClientPolicy = conduit.getClient();
httpClientPolicy.setAllowChunking( false );
String targetAddr = conduit.getTarget().getAddress().getValue();
if ( targetAddr.toLowerCase().startsWith( "https:" ) ) {
TrustManager[] simpleTrustManager = new TrustManager[] { new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType ) {
}
} };
TLSClientParameters tlsParams = new TLSClientParameters();
tlsParams.setTrustManagers( simpleTrustManager );
tlsParams.setDisableCNCheck( true );
conduit.setTlsClientParameters( tlsParams );
}
}
/**
* Upload artifact to AXIS service via WSO2 SOAP service
*
* @param artifactFileName
* Filename for AAR artifact to upload to WSO2 Server
* @param serviceHierarchy
* @return
*/
public boolean uploadAAR( File artifact, String targetFileName, String serviceHierarchy ) {
log.info( "[WSO2 AAR Deployer] Invoking uploadService for " + targetFileName + " ..." );
boolean result = true;
try {
InputStream fin = new FileInputStream( artifact );
List<AARServiceData> serviceDataList = creRequestData( fin, targetFileName, serviceHierarchy );
log.info( "[WSO2 AAR Deployer] Invoking uploadService for " + targetFileName + " ..." );
String callResult = uploadSvc.uploadService( serviceDataList );
log.info( "[WSO2 AAR Deployer] Call result = " + callResult );
} catch ( Exception_Exception e ) {
result = false;
log.error( "[WSO2 AAR Deployer] Upload error "+e.getMessage() );
log.error( e );
} catch ( IOException e ) {
result = false;
log.error( "[WSO2 AAR Deployer] Upload error "+e.getMessage() );
log.error( e );
}
return result;
}
/**
* helper factory to set up SOAP request data
*
* @param serviceHierarchy
* @throws IOException
*/
private List<AARServiceData> creRequestData( InputStream fin, String targetFileName, String serviceHierarchy ) throws IOException {
log.info( "[WSO2 AAR Deployer] Create SOAP request containing " + targetFileName + " ..." );
AARServiceData req = new AARServiceData();
ObjectFactory dataFactory = new ObjectFactory();
final byte fileContent[] = readFully( fin );
final int cnt = fileContent.length;
log.info( "[WSO2 CAR Deployer] Read CAR with " + cnt + " bytes" );
// byte[] fileContent = readAARfile( fin );
req.setDataHandler( dataFactory.createAARServiceDataDataHandler( fileContent ) );
req.setFileName( dataFactory.createAARServiceDataFileName( targetFileName ) );
req.setServiceHierarchy( dataFactory.createAARServiceDataServiceHierarchy( serviceHierarchy ) );
List<AARServiceData> serviceDataList = new ArrayList<AARServiceData>();
serviceDataList.add( req );
return serviceDataList;
}
/**
* Read all data available in this input stream and return it as byte[].
* Take care for memory on large files!
* <p>
* Imported from org.jcoderz.commons.util.IoUtil
* </p>
*
* @param is
* the input stream to read from (will not be closed).
* @return a byte array containing all data read from the is.
*/
private byte[] readFully( InputStream is ) throws IOException {
final byte[] buffer = new byte[READ_BUFFER_SIZE];
int read = 0;
final ByteArrayOutputStream out = new ByteArrayOutputStream();
while ( (read = is.read( buffer )) >= 0 ) {
out.write( buffer, 0, read );
}
return out.toByteArray();
}
}
<file_sep>/src/main/java/org/wso2/carbon/webapp/mgt/xsd/package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://mgt.webapp.carbon.wso2.org/xsd", elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED)
package org.wso2.carbon.webapp.mgt.xsd;
<file_sep>/README.md
WSO2 Deployer MOJO (Maven Plug In)
==================================
Idea: Deploy to WSO2 server and clusters using Maven
<build>
<plugins>
<plugin>
<groupId>org.mh.mojo.wso2deployment</groupId>
<artifactId>wso2deployment-maven-plugin</artifactId>
...
<configuration>
<environment>
<serverconfig>
<serverId>as01</serverId>
<serverUrl>https://localhost:9443/services/</serverUrl>
<adminUser>admin</adminUser>
<adminPassword>...</adminPassword>
</serverconfig>
... (add as many servers you need)
</environment>
<deployments>
<deployment>
<serverId>as01</serverId>
<groupId>org.mh</groupId>
<artifactId>TestApp</artifactId>
<version>1.2.3</version>
<artifactType>war</artifactType>
</deployment>
... (deploy to all servers as required)
</deployments>
</configuration>
</plugin>
...
</plugins>
</build>
Build From Source
=================
<pre>
git clone https://github.com/ma-ha/WSO2-Deployer-Maven-Plugin.git
cd WSO2-Deployer-Maven-Plugin
mvn clean install -Dmaven.test.skip=true
</pre>
Prepare
=======
Since the WSO2 servers come with self signed certificates the web service will fail, so you have to import the certificate into you certificate store:
1. Start the WSO2 Server and open the carbon console in the browser.
2. Copy the SSL certificate from the browser to a local file, e.g. wso2-as.cert
3. Load the certificate into your key store (it will go to ~/.keystore by default):<br><code>keytool -import -trustcacerts -alias wso2as-key -file wso2-as.cert</code>
Run Test
========
For this test you need to install the test artifacts into your local repository. For this test we take these, coming with the WSO2 AS:
<pre>
mvn install:install-file -DgroupId=test -DartifactId=WarTest -Dversion=1.0.0 -Dpackaging=war -Dfile=/<path-to-wso2as>/wso2as-5.2.0/repository/deployment/server/webapps/example.war
mvn install:install-file -DgroupId=test -DartifactId=AarTest -Dversion=1.0.0 -Dpackaging=aar -Dfile=/<path-to-wso2as>/wso2as-5.2.0/repository/deployment/server/axis2services/HelloWorld.aar
</pre>
A CAR is not provided, so I provided one here (don't hesitate -- it contains an empty dummy config, w/o any application)
<pre>
mvn install:install-file -DgroupId=test -DartifactId=CarbonAppTest -Dversion=1.0.0 -Dpackaging=car -Dfile=CarbonAppTest.car
</pre>
Of course then the WSO2 servers need to be running -- at least a WSO2 AS.
<pre>
cd src/test
mvn deploy:wso2
</pre>
The last deployment throws an exception from the stub, it can be ignored. It is a problem with the WSDL from the CAR service.
WSO2 may have fixed this meanwhile.
Usage
=====
Please use the <code><a href="https://github.com/ma-ha/WSO2-Deployer-Maven-Plugin/blob/master/src/test/pom.xml">src/test/pom.xml</a></code> as example
to configure your own deployments.
If you use WSO2 clusters, you may have to define server roles and deploy each artifact to all managers,
so that it goes to each node and the node itself decides which artifact part to deploy. <file_sep>/src/main/java/axis2/apache/org/xsd/GetPagedFaultyWebappsSummary.java
package axis2.apache.org.xsd;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElementRef;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
* <sequence>
* <element name="webappSearchString" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="webappType" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/>
* <element name="pageNumber" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/>
* </sequence>
* </restriction>
* </complexContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"webappSearchString",
"webappType",
"pageNumber"
})
@XmlRootElement(name = "getPagedFaultyWebappsSummary")
public class GetPagedFaultyWebappsSummary {
@XmlElementRef(name = "webappSearchString", namespace = "http://org.apache.axis2/xsd", type = JAXBElement.class, required = false)
protected JAXBElement<String> webappSearchString;
@XmlElementRef(name = "webappType", namespace = "http://org.apache.axis2/xsd", type = JAXBElement.class, required = false)
protected JAXBElement<String> webappType;
protected Integer pageNumber;
/**
* Gets the value of the webappSearchString property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getWebappSearchString() {
return webappSearchString;
}
/**
* Sets the value of the webappSearchString property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setWebappSearchString(JAXBElement<String> value) {
this.webappSearchString = value;
}
/**
* Gets the value of the webappType property.
*
* @return
* possible object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public JAXBElement<String> getWebappType() {
return webappType;
}
/**
* Sets the value of the webappType property.
*
* @param value
* allowed object is
* {@link JAXBElement }{@code <}{@link String }{@code >}
*
*/
public void setWebappType(JAXBElement<String> value) {
this.webappType = value;
}
/**
* Gets the value of the pageNumber property.
*
* @return
* possible object is
* {@link Integer }
*
*/
public Integer getPageNumber() {
return pageNumber;
}
/**
* Sets the value of the pageNumber property.
*
* @param value
* allowed object is
* {@link Integer }
*
*/
public void setPageNumber(Integer value) {
this.pageNumber = value;
}
}
<file_sep>/src/main/java/org/wso2/carbon/webapp/mgt/WebappAdminPortType.java
package org.wso2.carbon.webapp.mgt;
import javax.jws.Oneway;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;
import javax.xml.bind.annotation.XmlSeeAlso;
import javax.xml.ws.Action;
import javax.xml.ws.FaultAction;
import javax.xml.ws.RequestWrapper;
import javax.xml.ws.ResponseWrapper;
/**
* This class was generated by Apache CXF 2.7.8
* 2013-12-20T13:24:53.170+01:00
* Generated source version: 2.7.8
*
*/
@WebService(targetNamespace = "http://mgt.webapp.carbon.wso2.org", name = "WebappAdminPortType")
@XmlSeeAlso({org.wso2.carbon.webapp.mgt.xsd.ObjectFactory.class, axis2.apache.org.xsd.ObjectFactory.class, org.wso2.carbon.core.persistence.metadata.xsd.ObjectFactory.class})
public interface WebappAdminPortType {
@Oneway
@Action(input = "urn:expireAllSessions")
@RequestWrapper(localName = "expireAllSessions", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ExpireAllSessions")
@WebMethod(action = "urn:expireAllSessions")
public void expireAllSessions(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName
);
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:isDefaultVersionManagementEnabled", output = "urn:isDefaultVersionManagementEnabledResponse")
@RequestWrapper(localName = "isDefaultVersionManagementEnabled", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.IsDefaultVersionManagementEnabled")
@WebMethod(action = "urn:isDefaultVersionManagementEnabled")
@ResponseWrapper(localName = "isDefaultVersionManagementEnabledResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.IsDefaultVersionManagementEnabledResponse")
public java.lang.Boolean isDefaultVersionManagementEnabled();
@Oneway
@Action(input = "urn:deleteAllStartedWebapps")
@RequestWrapper(localName = "deleteAllStartedWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteAllStartedWebapps")
@WebMethod(action = "urn:deleteAllStartedWebapps")
public void deleteAllStartedWebapps();
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:uploadWebapp", output = "urn:uploadWebappResponse")
@RequestWrapper(localName = "uploadWebapp", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.UploadWebapp")
@WebMethod(action = "urn:uploadWebapp")
@ResponseWrapper(localName = "uploadWebappResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.UploadWebappResponse")
public java.lang.Boolean uploadWebapp(
@WebParam(name = "webappUploadDataList", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<org.wso2.carbon.webapp.mgt.xsd.WebappUploadData> webappUploadDataList
);
@Oneway
@Action(input = "urn:changeDefaultAppVersion", fault = {@FaultAction(className = WebappAdminArtifactMetadataException.class, value = "urn:changeDefaultAppVersionWebappAdminArtifactMetadataException")})
@RequestWrapper(localName = "changeDefaultAppVersion", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ChangeDefaultAppVersion")
@WebMethod(action = "urn:changeDefaultAppVersion")
public void changeDefaultAppVersion(
@WebParam(name = "appGroupName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String appGroupName,
@WebParam(name = "fileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String fileName
) throws WebappAdminArtifactMetadataException;
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:getPagedFaultyWebappsSummary", output = "urn:getPagedFaultyWebappsSummaryResponse")
@RequestWrapper(localName = "getPagedFaultyWebappsSummary", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetPagedFaultyWebappsSummary")
@WebMethod(action = "urn:getPagedFaultyWebappsSummary")
@ResponseWrapper(localName = "getPagedFaultyWebappsSummaryResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetPagedFaultyWebappsSummaryResponse")
public org.wso2.carbon.webapp.mgt.xsd.WebappsWrapper getPagedFaultyWebappsSummary(
@WebParam(name = "webappSearchString", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappSearchString,
@WebParam(name = "webappType", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappType,
@WebParam(name = "pageNumber", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.Integer pageNumber
);
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:isUnpackWARs", output = "urn:isUnpackWARsResponse")
@RequestWrapper(localName = "isUnpackWARs", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.IsUnpackWARs")
@WebMethod(action = "urn:isUnpackWARs")
@ResponseWrapper(localName = "isUnpackWARsResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.IsUnpackWARsResponse")
public java.lang.Boolean isUnpackWARs();
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:getActiveSessions", output = "urn:getActiveSessionsResponse")
@RequestWrapper(localName = "getActiveSessions", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetActiveSessions")
@WebMethod(action = "urn:getActiveSessions")
@ResponseWrapper(localName = "getActiveSessionsResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetActiveSessionsResponse")
public org.wso2.carbon.webapp.mgt.xsd.SessionsWrapper getActiveSessions(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName,
@WebParam(name = "pageNumber", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.Integer pageNumber
);
@Oneway
@Action(input = "urn:deleteAllStoppedWebapps")
@RequestWrapper(localName = "deleteAllStoppedWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteAllStoppedWebapps")
@WebMethod(action = "urn:deleteAllStoppedWebapps")
public void deleteAllStoppedWebapps();
@Oneway
@Action(input = "urn:reloadWebapps")
@RequestWrapper(localName = "reloadWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ReloadWebapps")
@WebMethod(action = "urn:reloadWebapps")
public void reloadWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:deleteStoppedWebapps")
@RequestWrapper(localName = "deleteStoppedWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteStoppedWebapps")
@WebMethod(action = "urn:deleteStoppedWebapps")
public void deleteStoppedWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:expireSessions")
@RequestWrapper(localName = "expireSessions", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ExpireSessions")
@WebMethod(action = "urn:expireSessions")
public void expireSessions(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName,
@WebParam(name = "sessionIDs", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> sessionIDs
);
@Oneway
@Action(input = "urn:stopAllWebapps")
@RequestWrapper(localName = "stopAllWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.StopAllWebapps")
@WebMethod(action = "urn:stopAllWebapps")
public void stopAllWebapps();
@Oneway
@Action(input = "urn:stopWebapps")
@RequestWrapper(localName = "stopWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.StopWebapps")
@WebMethod(action = "urn:stopWebapps")
public void stopWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:setBamConfiguration")
@RequestWrapper(localName = "setBamConfiguration", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.SetBamConfiguration")
@WebMethod(action = "urn:setBamConfiguration")
public void setBamConfiguration(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName,
@WebParam(name = "value", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String value
);
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:getStartedWebapp", output = "urn:getStartedWebappResponse")
@RequestWrapper(localName = "getStartedWebapp", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetStartedWebapp")
@WebMethod(action = "urn:getStartedWebapp")
@ResponseWrapper(localName = "getStartedWebappResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetStartedWebappResponse")
public org.wso2.carbon.webapp.mgt.xsd.WebappMetadata getStartedWebapp(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName
);
@Oneway
@Action(input = "urn:deleteStartedWebapps")
@RequestWrapper(localName = "deleteStartedWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteStartedWebapps")
@WebMethod(action = "urn:deleteStartedWebapps")
public void deleteStartedWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:deleteAllWebApps")
@RequestWrapper(localName = "deleteAllWebApps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteAllWebApps")
@WebMethod(action = "urn:deleteAllWebApps")
public void deleteAllWebApps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:deleteFaultyWebapps")
@RequestWrapper(localName = "deleteFaultyWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteFaultyWebapps")
@WebMethod(action = "urn:deleteFaultyWebapps")
public void deleteFaultyWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:startWebapps")
@RequestWrapper(localName = "startWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.StartWebapps")
@WebMethod(action = "urn:startWebapps")
public void startWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:deleteAllFaultyWebapps")
@RequestWrapper(localName = "deleteAllFaultyWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteAllFaultyWebapps")
@WebMethod(action = "urn:deleteAllFaultyWebapps")
public void deleteAllFaultyWebapps();
@Oneway
@Action(input = "urn:expireSessionsInAllWebapps")
@RequestWrapper(localName = "expireSessionsInAllWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ExpireSessionsInAllWebapps")
@WebMethod(action = "urn:expireSessionsInAllWebapps")
public void expireSessionsInAllWebapps();
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:getBamConfiguration", output = "urn:getBamConfigurationResponse")
@RequestWrapper(localName = "getBamConfiguration", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetBamConfiguration")
@WebMethod(action = "urn:getBamConfiguration")
@ResponseWrapper(localName = "getBamConfigurationResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetBamConfigurationResponse")
public java.lang.String getBamConfiguration(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName
);
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:getStoppedWebapp", output = "urn:getStoppedWebappResponse")
@RequestWrapper(localName = "getStoppedWebapp", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetStoppedWebapp")
@WebMethod(action = "urn:getStoppedWebapp")
@ResponseWrapper(localName = "getStoppedWebappResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetStoppedWebappResponse")
public org.wso2.carbon.webapp.mgt.xsd.WebappMetadata getStoppedWebapp(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName
);
@Oneway
@Action(input = "urn:expireSessionsInWebapps")
@RequestWrapper(localName = "expireSessionsInWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ExpireSessionsInWebapps")
@WebMethod(action = "urn:expireSessionsInWebapps")
public void expireSessionsInWebapps(
@WebParam(name = "webappFileNames", targetNamespace = "http://org.apache.axis2/xsd")
java.util.List<java.lang.String> webappFileNames
);
@Oneway
@Action(input = "urn:startAllWebapps")
@RequestWrapper(localName = "startAllWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.StartAllWebapps")
@WebMethod(action = "urn:startAllWebapps")
public void startAllWebapps();
@Oneway
@Action(input = "urn:expireSessionsInWebapp")
@RequestWrapper(localName = "expireSessionsInWebapp", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ExpireSessionsInWebapp")
@WebMethod(action = "urn:expireSessionsInWebapp")
public void expireSessionsInWebapp(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName,
@WebParam(name = "maxSessionLifetimeMillis", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.Long maxSessionLifetimeMillis
);
@Oneway
@Action(input = "urn:deleteWebapp")
@RequestWrapper(localName = "deleteWebapp", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DeleteWebapp")
@WebMethod(action = "urn:deleteWebapp")
public void deleteWebapp(
@WebParam(name = "webappFileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappFileName
);
@Oneway
@Action(input = "urn:reloadAllWebapps")
@RequestWrapper(localName = "reloadAllWebapps", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.ReloadAllWebapps")
@WebMethod(action = "urn:reloadAllWebapps")
public void reloadAllWebapps();
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:getPagedWebappsSummary", output = "urn:getPagedWebappsSummaryResponse")
@RequestWrapper(localName = "getPagedWebappsSummary", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetPagedWebappsSummary")
@WebMethod(action = "urn:getPagedWebappsSummary")
@ResponseWrapper(localName = "getPagedWebappsSummaryResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.GetPagedWebappsSummaryResponse")
public org.wso2.carbon.webapp.mgt.xsd.WebappsWrapper getPagedWebappsSummary(
@WebParam(name = "webappSearchString", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappSearchString,
@WebParam(name = "webappState", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappState,
@WebParam(name = "webappType", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappType,
@WebParam(name = "pageNumber", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.Integer pageNumber
);
@WebResult(name = "return", targetNamespace = "http://org.apache.axis2/xsd")
@Action(input = "urn:downloadWarFileHandler", output = "urn:downloadWarFileHandlerResponse")
@RequestWrapper(localName = "downloadWarFileHandler", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DownloadWarFileHandler")
@WebMethod(action = "urn:downloadWarFileHandler")
@ResponseWrapper(localName = "downloadWarFileHandlerResponse", targetNamespace = "http://org.apache.axis2/xsd", className = "axis2.apache.org.xsd.DownloadWarFileHandlerResponse")
public byte[] downloadWarFileHandler(
@WebParam(name = "fileName", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String fileName,
@WebParam(name = "webappType", targetNamespace = "http://org.apache.axis2/xsd")
java.lang.String webappType
);
}
<file_sep>/src/main/java/org/mh/mojo/wso2deployment/Deployment.java
package org.mh.mojo.wso2deployment;
/** configuration from POM goes here */
public class Deployment {
private String serverId;
private String groupId;
private String artifactId;
private String artifactType;
private String version;
private String artifactClassifier;
private boolean versionSubContext = true;
public boolean isVersionSubContext() {
return versionSubContext;
}
public void setVersionSubContext( boolean versionSubContext ) {
this.versionSubContext = versionSubContext;
}
/**
* @return the serverId
*/
public String getServerId() {
return serverId;
}
/**
* @param serverId the serverId to set
*/
public void setServerId( String serverId ) {
this.serverId = serverId;
}
/**
* @return the groupId
*/
public String getGroupId() {
return groupId;
}
/**
* @param groupId the groupId to set
*/
public void setGroupId( String groupId ) {
this.groupId = groupId;
}
/**
* @return the artifactId
*/
public String getArtifactId() {
return artifactId;
}
/**
* @param artifactId the artifactId to set
*/
public void setArtifactId( String artifactId ) {
this.artifactId = artifactId;
}
/**
* @return the artifactType
*/
public String getArtifactType() {
return artifactType;
}
/**
* @param artifactType the artifactType to set
*/
public void setArtifactType( String artifactType ) {
this.artifactType = artifactType;
}
/**
* @return the artifactClassifier
*/
public String getArtifactClassifier() {
return artifactClassifier;
}
/**
* @param artifactClassifier the artifactClassifier to set
*/
public void setArtifactClassifier( String artifactClassifier ) {
this.artifactClassifier = artifactClassifier;
}
/**
* @return the version
*/
public String getVersion() {
return version;
}
/**
* @param version the version to set
*/
public void setVersion( String version ) {
this.version = version;
}
}
<file_sep>/src/main/java/org/wso2/carbon/application/upload/ObjectFactory.java
package org.wso2.carbon.application.upload;
import javax.xml.bind.JAXBElement;
import javax.xml.bind.annotation.XmlElementDecl;
import javax.xml.bind.annotation.XmlRegistry;
import javax.xml.namespace.QName;
/**
* This object contains factory methods for each
* Java content interface and Java element interface
* generated in the org.wso2.carbon.application.upload package.
* <p>An ObjectFactory allows you to programatically
* construct new instances of the Java representation
* for XML content. The Java representation of XML
* content can consist of schema derived interfaces
* and classes representing the binding of schema
* type definitions, element declarations and model
* groups. Factory methods for each of these are
* provided in this class.
*
*/
@XmlRegistry
public class ObjectFactory {
private final static QName _ExceptionException_QNAME = new QName("http://upload.application.carbon.wso2.org", "Exception");
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: org.wso2.carbon.application.upload
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link UploadApp }
*
*/
public UploadApp createUploadApp() {
return new UploadApp();
}
/**
* Create an instance of {@link Exception }
*
*/
public Exception createException() {
return new Exception();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Object }{@code >}}
*
*/
@XmlElementDecl(namespace = "http://upload.application.carbon.wso2.org", name = "Exception", scope = Exception.class)
public JAXBElement<Object> createExceptionException(Object value) {
return new JAXBElement<Object>(_ExceptionException_QNAME, Object.class, Exception.class, value);
}
}
<file_sep>/src/main/java/org/wso2/carbon/aarservices/ServiceUploader.java
package org.wso2.carbon.aarservices;
import java.net.URL;
import javax.xml.namespace.QName;
import javax.xml.ws.WebEndpoint;
import javax.xml.ws.WebServiceClient;
import javax.xml.ws.WebServiceFeature;
import javax.xml.ws.Service;
/**
* This class was generated by Apache CXF 2.7.8
* 2013-12-23T10:35:02.346+01:00
* Generated source version: 2.7.8
*
*/
@WebServiceClient(name = "ServiceUploader",
wsdlLocation = "ServiceUploader.wsdl",
targetNamespace = "http://aarservices.carbon.wso2.org")
public class ServiceUploader extends Service {
public final static URL WSDL_LOCATION;
public final static QName SERVICE = new QName("http://aarservices.carbon.wso2.org", "ServiceUploader");
public final static QName ServiceUploaderHttpsSoap12Endpoint = new QName("http://aarservices.carbon.wso2.org", "ServiceUploaderHttpsSoap12Endpoint");
public final static QName ServiceUploaderHttpsSoap11Endpoint = new QName("http://aarservices.carbon.wso2.org", "ServiceUploaderHttpsSoap11Endpoint");
public final static QName ServiceUploaderHttpsEndpoint = new QName("http://aarservices.carbon.wso2.org", "ServiceUploaderHttpsEndpoint");
static {
URL url = ServiceUploader.class.getResource("ServiceUploader.wsdl");
if (url == null) {
url = ServiceUploader.class.getClassLoader().getResource("ServiceUploader.wsdl");
}
if (url == null) {
java.util.logging.Logger.getLogger(ServiceUploader.class.getName())
.log(java.util.logging.Level.INFO,
"Can not initialize the default wsdl from {0}", "ServiceUploader.wsdl");
}
WSDL_LOCATION = url;
}
public ServiceUploader(URL wsdlLocation) {
super(wsdlLocation, SERVICE);
}
public ServiceUploader(URL wsdlLocation, QName serviceName) {
super(wsdlLocation, serviceName);
}
public ServiceUploader() {
super(WSDL_LOCATION, SERVICE);
}
//This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
//API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
//compliant code instead.
public ServiceUploader(WebServiceFeature ... features) {
super(WSDL_LOCATION, SERVICE, features);
}
//This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
//API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
//compliant code instead.
public ServiceUploader(URL wsdlLocation, WebServiceFeature ... features) {
super(wsdlLocation, SERVICE, features);
}
//This constructor requires JAX-WS API 2.2. You will need to endorse the 2.2
//API jar or re-run wsdl2java with "-frontend jaxws21" to generate JAX-WS 2.1
//compliant code instead.
public ServiceUploader(URL wsdlLocation, QName serviceName, WebServiceFeature ... features) {
super(wsdlLocation, serviceName, features);
}
/**
*
* @return
* returns ServiceUploaderPortType
*/
@WebEndpoint(name = "ServiceUploaderHttpsSoap12Endpoint")
public ServiceUploaderPortType getServiceUploaderHttpsSoap12Endpoint() {
return super.getPort(ServiceUploaderHttpsSoap12Endpoint, ServiceUploaderPortType.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns ServiceUploaderPortType
*/
@WebEndpoint(name = "ServiceUploaderHttpsSoap12Endpoint")
public ServiceUploaderPortType getServiceUploaderHttpsSoap12Endpoint(WebServiceFeature... features) {
return super.getPort(ServiceUploaderHttpsSoap12Endpoint, ServiceUploaderPortType.class, features);
}
/**
*
* @return
* returns ServiceUploaderPortType
*/
@WebEndpoint(name = "ServiceUploaderHttpsSoap11Endpoint")
public ServiceUploaderPortType getServiceUploaderHttpsSoap11Endpoint() {
return super.getPort(ServiceUploaderHttpsSoap11Endpoint, ServiceUploaderPortType.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns ServiceUploaderPortType
*/
@WebEndpoint(name = "ServiceUploaderHttpsSoap11Endpoint")
public ServiceUploaderPortType getServiceUploaderHttpsSoap11Endpoint(WebServiceFeature... features) {
return super.getPort(ServiceUploaderHttpsSoap11Endpoint, ServiceUploaderPortType.class, features);
}
/**
*
* @return
* returns ServiceUploaderPortType
*/
@WebEndpoint(name = "ServiceUploaderHttpsEndpoint")
public ServiceUploaderPortType getServiceUploaderHttpsEndpoint() {
return super.getPort(ServiceUploaderHttpsEndpoint, ServiceUploaderPortType.class);
}
/**
*
* @param features
* A list of {@link javax.xml.ws.WebServiceFeature} to configure on the proxy. Supported features not in the <code>features</code> parameter will have their default values.
* @return
* returns ServiceUploaderPortType
*/
@WebEndpoint(name = "ServiceUploaderHttpsEndpoint")
public ServiceUploaderPortType getServiceUploaderHttpsEndpoint(WebServiceFeature... features) {
return super.getPort(ServiceUploaderHttpsEndpoint, ServiceUploaderPortType.class, features);
}
}
<file_sep>/src/main/java/org/wso2/carbon/core/persistence/metadata/xsd/package-info.java
@javax.xml.bind.annotation.XmlSchema(namespace = "http://metadata.persistence.core.carbon.wso2.org/xsd")
package org.wso2.carbon.core.persistence.metadata.xsd;
<file_sep>/src/test/pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.mh.mojotest</groupId>
<artifactId>project2</artifactId>
<packaging>jar</packaging>
<version>1.0-SNAPSHOT</version>
<name>Test WSO2 Deployment Mojo</name>
<build>
<plugins>
<plugin>
<groupId>org.mh.mojo.wso2deployment</groupId>
<artifactId>wso2deployment-maven-plugin</artifactId>
<executions>
<execution>
<phase>test</phase>
<goals>
<goal>wso2</goal>
</goals>
</execution>
</executions>
<configuration>
<environment>
<serverconfig>
<serverId>as01</serverId>
<serverUrl>https://localhost:9443/services/</serverUrl>
<adminUser>admin</adminUser>
<adminPassword><PASSWORD></adminPassword>
</serverconfig>
<serverconfig>
<serverId>as02</serverId>
<serverUrl>https://localhost:9443/services/</serverUrl>
<adminUser>admin</adminUser>
<adminPassword><PASSWORD></adminPassword>
</serverconfig>
</environment>
<deployments>
<deployment>
<serverId>as01</serverId>
<groupId>test</groupId>
<artifactId>WarTest</artifactId>
<version>1.0.0</version>
<artifactType>war</artifactType>
<versionSubContext>false</versionSubContext> <!-- optional for "war" type, default is true -->
</deployment>
<deployment>
<serverId>as02</serverId>
<groupId>test</groupId>
<artifactId>AarTest</artifactId>
<version>1.0.0</version>
<artifactType>aar</artifactType>
</deployment>
<deployment>
<serverId>as01</serverId>
<groupId>test</groupId>
<artifactId>CarbonAppTest</artifactId>
<version>1.0.0</version>
<artifactType>car</artifactType>
</deployment>
</deployments>
</configuration>
</plugin>
</plugins>
</build>
</project><file_sep>/pom.xml
<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>
<parent>
<groupId>org.codehaus.mojo</groupId>
<artifactId>mojo-parent</artifactId>
<version>33</version>
</parent>
<groupId>org.mh.mojo.wso2deployment</groupId>
<artifactId>wso2deployment-maven-plugin</artifactId>
<version>0.4.1</version>
<packaging>maven-plugin</packaging>
<name>WSO2 Deployer Maven Plugin</name>
<description>A plugin to allow remote deployment of artifacts to WSO2 Servers</description>
<prerequisites>
<maven>${mavenVersion}</maven>
</prerequisites>
<licenses>
<license>
<name>MIT license</name>
<comments>All source code is under the MIT license.</comments>
</license>
</licenses>
<developers>
<developer>
<id>mh</id>
<name><NAME></name>
<email>m.e.harms(at)t-online.de</email>
<timezone>Europe/Berlin</timezone>
</developer>
</developers>
<properties>
<mavenVersion>2.2.1</mavenVersion>
<java-version>1.7</java-version>
<org.springframework-version>3.0.6.RELEASE</org.springframework-version>
<cxf.version>2.7.8</cxf.version>
</properties>
<!--
<repositories>
<repository>
<releases>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
<id>wso2-nexus</id>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<updatePolicy>daily</updatePolicy>
<checksumPolicy>ignore</checksumPolicy>
</releases>
<id>wso2-nexus</id>
<url>http://maven.wso2.org/nexus/content/groups/wso2-public/</url>
</pluginRepository>
</pluginRepositories>
-->
<dependencies>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-toolchain</artifactId>
<version>1.0</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-project</artifactId>
<version>${mavenVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-model</artifactId>
<version>${mavenVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>${mavenVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact-manager</artifactId>
<version>${mavenVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-core</artifactId>
<version>${mavenVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-plugin-api</artifactId>
<version>${mavenVersion}</version>
</dependency>
<dependency>
<groupId>org.codehaus.plexus</groupId>
<artifactId>plexus-utils</artifactId>
<version>3.0.15</version>
</dependency>
<dependency>
<groupId>org.apache.maven.plugin-tools</groupId>
<artifactId>maven-plugin-annotations</artifactId>
<version>3.3</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.apache.maven.shared</groupId>
<artifactId>maven-plugin-testing-harness</artifactId>
<version>1.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-frontend-jaxws</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-transports-http</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.apache.cxf</groupId>
<artifactId>cxf-rt-bindings-soap</artifactId>
<version>${cxf.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${org.springframework-version}</version>
</dependency>
</dependencies>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<version>3.3</version>
</plugin>
</plugins>
</pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-plugin-plugin</artifactId>
<configuration>
<goalPrefix>deploy</goalPrefix>
<skipErrorNoDescriptorsFound>true</skipErrorNoDescriptorsFound>
</configuration>
<executions>
<execution>
<id>mojo-descriptor</id>
<goals>
<goal>descriptor</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>
| c8a2c5ec9e6880a60d4062d4016db785933a89f1 | [
"Markdown",
"Java",
"Maven POM"
] | 20 | Java | ma-ha/WSO2-Deployer-Maven-Plugin | dab6559801fac487d84350fd2cefc199e908cfbd | a3b9199320d65ee1e5c0243d414097659f782ab6 |
refs/heads/main | <repo_name>invisibleflame/Email_Spam_Classifier<file_sep>/README.md
# Email-Spam-Classifier
Implementation of an end to end email spam classifier using the bidirectional lstm and word tokenizers along with a mild preprocessing and Flask backend.
Data: https://www.kaggle.com/uciml/sms-spam-collection-dataset
Accuracy on test set ~ 98%
<p align=center> Made with :heart: by <NAME> </p>
<file_sep>/app.py
from flask import Flask, render_template, request
import jsonify
import requests
import numpy as np
import keras
import tensorflow as tf
import io
import json
import string
import nltk
import pandas as pd
from nltk.corpus import stopwords
from keras.preprocessing.sequence import pad_sequences
import tensorflow as tf
import keras
from keras_preprocessing.text import tokenizer_from_json
nltk.download('stopwords')
with open('tokenizer.json') as f:
data = json.load(f)
tokenizer = tokenizer_from_json(data)
def text_preprocess(text):
text=text.lower()
text = text.translate(str.maketrans('', '', string.punctuation))
text = [word for word in text.split() if word.lower() not in stopwords.words('english')]
return " ".join(text)
app = Flask(__name__)
classifier = keras.models.load_model('model/')
@app.route('/',methods=['GET'])
def Home():
return render_template('index.html')
@app.route("/predict", methods=['POST'])
def predict():
if request.method == 'POST':
email = request.form['Email']
email= pd.Series([email])
email=email.apply(text_preprocess)
email_features = np.array(tokenizer.texts_to_sequences(email))
email_features=pad_sequences(email_features, maxlen=72)
output=classifier.predict(email_features)
if output>0.5:
return render_template('index.html',prediction_texts="This input Email is spam")
else:
return render_template('index.html',prediction_text="This input Email is not spam")
else:
return render_template('index.html')
if __name__=="__main__":
app.run(debug=True)
| 6a529886d496e4d256365d7a5b628a147d054ce3 | [
"Markdown",
"Python"
] | 2 | Markdown | invisibleflame/Email_Spam_Classifier | 4227788e0e998c59ec3547cc63006fc5f8eba249 | 280e7aab0d4906680258058fd4684712509d77a1 |
refs/heads/main | <repo_name>EliasElOtmani/wm_nachrs<file_sep>/dmts_frontex.py
# Each function outputs the trial results for all populations & conditions for a given
# external current, in the following format :
# dmts_<classic>_<Iext>.npy : np.array([VIP, PV, SOM, SOM & PV, All])
import numpy as np
import torch, os
from numpy import nan
from CCM import CCM
from DMTS import DMTS
computer = "cpu"
dev_str = 'cpu'
cores = 6
num_workers = 4 * cores
enc = torch.float64
dev = torch.device(computer)
info = False
reject = False
plot = False
mod_prm = torch.as_tensor([.020, 0.007, .600, 2.2, 0., 1.9, 2.6, 1.5, 1.2, 7., 7., 7., 7., 1/26, 1, 1], device=dev, dtype=enc)
sim_prm = torch.as_tensor([5., 0.001, 1e-12, 1e-3, nan], device=dev, dtype=enc)
task_prm = [100, 1, 0.05, (0.2,0.3), (2, 2.1), (3.,3.1)]
Ae, Ap, As, Av = 169, 268, 709, 634
dof = torch.as_tensor([
Ae, Ap, As, Av, # Ae, Ap, As, Av (4)
# wee, wpe, wse, wes, wvs, wep, wpp, wsp, wev, wsv (10) :
.136*Ae, .075*Ap, .045*As, .053*Ae, .04*Av, .17*Ae, .093*Ap, .0*As, .053*Ae, .001*As,
4.4, 4.8, 2.7, 1.9, # Ie_ext, Ip_ext, Is_ext, Iv_ext (5)
0.2, .03*Ae, 25 # q, J_adp, sigma (3)
], device=dev, dtype=enc)
dist_amp = 0 # To be determined
nic_amplitude = 0 # To be determined
def save_data(output_dir, outputfile, data, jobID):
default_path = '/shared/projects/project_nicWM/data/'
full_path = default_path + output_dir
if not os.path.exists(full_path) : os.mkdir(full_path)
with open(full_path + '/' + outputfile + '_' + str(jobID) + '.npy', 'wb') as f:
np.save(f, data)
print(data)
def classic_dmts(jobID):
# Generates DMTS data and stores it
array_length = 120
middle = int(array_length/2)
Istep = 0.025
'''
# VIP
dof_vip = dof.clone()
dof_vip[17] -= (middle - jobID)*Istep # jobID = 0 --> Iext -= 2.5
ccm = CCM(dof_vip, mod_prm, sim_prm, STP = True, two_columns = False)
dmts = DMTS(ccm, task_prm)
load_vip = dmts.loadings/dmts.nb_trials
delay_vip = dmts.maintenances/dmts.nb_trials
# PV
dof_pv = dof.clone()
dof_pv[15] -= (middle - jobID)*Istep
ccm = CCM(dof_pv, mod_prm, sim_prm, STP = True, two_columns = False)
dmts = DMTS(ccm, task_prm)
load_pv = dmts.loadings/dmts.nb_trials
delay_pv = dmts.maintenances/dmts.nb_trials
# SOM
dof_som = dof.clone()
dof_som[16] -= (middle - jobID)*Istep
ccm = CCM(dof_som, mod_prm, sim_prm, STP = True, two_columns = False)
dmts = DMTS(ccm, task_prm)
load_som = dmts.loadings/dmts.nb_trials
delay_som = dmts.maintenances/dmts.nb_trials
# PV & SOM
dof_pv_som = dof.clone()
dof_pv_som[15] -= (middle - jobID)*Istep
dof_pv_som[16] -= (middle - jobID)*Istep
ccm = CCM(dof_pv_som, mod_prm, sim_prm, STP = True, two_columns = False)
dmts = DMTS(ccm, task_prm)
load_pv_som = dmts.loadings/dmts.nb_trials
delay_pv_som = dmts.maintenances/dmts.nb_trials
'''
# ACh DEPLETION
dof_ACh = dof.clone()
dof_ACh[15] -= (middle - jobID)*(Istep/5)
dof_ACh[16] -= (middle - jobID)*Istep
dof_ACh[17] -= (middle - jobID)*Istep
ccm = CCM(dof_ACh, mod_prm, sim_prm, STP = True, two_columns = False)
dmts = DMTS(ccm, task_prm)
load_ACh = dmts.loadings/dmts.nb_trials
delay_ACh = dmts.maintenances/dmts.nb_trials
#toSave = np.array([load_vip, delay_vip, load_pv, delay_pv, load_som, delay_som, load_pv_som, delay_pv_som, load_ACh, delay_ACh])
#save_data('classic_dmts', 'dmts', toSave, jobID)
toSave = np.array([load_ACh, delay_ACh])
save_data('classic_dmts_Ach', 'dmts_ach', toSave, jobID)
def itrans_loading(jobID):
duration = 0.002 + 0.002*jobID # jobID = 0-100
intensities = [0.5 + 0.1*i for i in range(31)]
dim_intensities = len(intensities)
loadings = np.empty((dim_intensities))
#task_prm = [100, 1, 0.05, (0.2,0.3), (2, 2.1), (3.,3.1)]
task_prm_itrans = [elem for elem in task_prm]
task_prm_itrans[2] = duration
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = False, STP = True)
for i in range(dim_intensities):
ccm.thalamus.Itrans = intensities[i]
dmts = DMTS(ccm, task_prm = task_prm_itrans)
loadings[i] = dmts.loadings/dmts.nb_trials
save_data('detections', 'detection', loadings, jobID)
def pick_jadp(jobID):
dof_jadp = dof.clone()
dof_jadp[-2] = (0.01 + jobID*0.005)*Ae
ccm = CCM(dof_jadp, mod_prm, sim_prm, equilibria = False, two_columns = False, STP = True)
dmts = DMTS(ccm, task_prm = task_prm)
maintenances = dmts.loadings/dmts.nb_trials
save_data('pick_jadp', 'jadp', maintenances, jobID)
def pick_distractor_amplitude(jobID):
dist_amp = 1.5 + 0.025*jobID
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True)
dmts = DMTS(ccm, task_prm = task_prm, distractor = True, distractor_amplitude = dist_amp, distractor_duration = 0.2)
maintenances = dmts.maintenances/dmts.nb_trials
save_data('pick_distractor_amp_pdr1', 'dAmp', maintenances, jobID)
def distracted_dmts(jobID):
#array_length = 200
#middle = int(array_length/2)
Istep = 0.01
dist_amp = 0 # 2.2
jobID += 100
#if jobID < middle : jobID -= 100
#else : jobID += 100
'''
# VIP
dof_vip = dof.clone()
dof_vip[17] -= (middle - jobID)*Istep # jobID = 0 --> Iext -= 2.5
ccm = CCM(dof_vip, mod_prm, sim_prm, STP = True, two_columns = True)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_amplitude = dist_amp)
load_vip = dmts.loadings/dmts.nb_trials
delay_vip = dmts.maintenances/dmts.nb_trials
# PV
dof_pv = dof.clone()
dof_pv[15] -= (middle - jobID)*Istep
ccm = CCM(dof_pv, mod_prm, sim_prm, STP = True, two_columns = True)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_amplitude = dist_amp)
load_pv = dmts.loadings/dmts.nb_trials
delay_pv = dmts.maintenances/dmts.nb_trials
# SOM
dof_som = dof.clone()
dof_som[16] -= (middle - jobID)*Istep
ccm = CCM(dof_som, mod_prm, sim_prm, STP = True, two_columns = True)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_amplitude = dist_amp)
load_som = dmts.loadings/dmts.nb_trials
delay_som = dmts.maintenances/dmts.nb_trials
'''
# PV & SOM
dof_pv_som = dof.clone()
#dof_pv_som[15] -= (middle - jobID)*Istep
#dof_pv_som[16] -= (middle - jobID)*Istep
dof_pv_som[15] += jobID*Istep
dof_pv_som[16] += jobID*Istep
ccm = CCM(dof_pv_som, mod_prm, sim_prm, STP = True, two_columns = True)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_amplitude = dist_amp)
load_pv_som = dmts.loadings/dmts.nb_trials
delay_pv_som = dmts.maintenances/dmts.nb_trials
'''
# ACh DEPLETION
dof_ACh = dof.clone()
dof_ACh[15] -= (middle - jobID)*(Istep/5)
dof_ACh[16] -= (middle - jobID)*Istep
dof_ACh[17] -= (middle - jobID)*Istep
ccm = CCM(dof_ACh, mod_prm, sim_prm, STP = True, two_columns = True)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_amplitude = 1)
load_ACh = dmts.loadings/dmts.nb_trials
delay_ACh = dmts.maintenances/dmts.nb_trials
toSave = np.array([load_vip, delay_vip, load_pv, delay_pv, load_som, delay_som, load_pv_som, delay_pv_som, load_ACh, delay_ACh])
save_data('distracted_dmts_pdr1_amp0', 'ddmts', toSave, jobID)
'''
toSave = np.array([load_pv_som, delay_pv_som])
save_data('distracted_dmts_pdr1_amp0_extremes', 'ddmts', toSave, jobID)
def nicTrans_dmts(jobID): # Tries different values of nic_trans_amplitude on the 'healthy' model
# Generates DMTS data and stores it
task_prm = [100, 2, 0.2, (0.2,0.3), (2,2.1), (3,3.1)]
sim_prm = torch.as_tensor([6., 0.001, 1e-12, 1e-3, nan], device = dev, dtype = enc)
#nic_amplitude = 0.1 + jobID*0.025
nic_amplitude = jobID*0.025
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
loadings = dmts.loadings/dmts.nb_trials
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
loadings_kam = dmts.loadings/dmts.nb_trials
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, nic_normalization = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
loadings_norm = dmts.loadings/dmts.nb_trials
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True, nic_normalization = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
loadings_kam_norm = dmts.loadings/dmts.nb_trials
toSave = np.array([loadings, loadings_kam, loadings_norm, loadings_kam_norm])
save_data('nicTrans_dmts_3', 'nicTrans_dmts', toSave, jobID)
#print(toSave)
def nicotine_restoration(jobID):
task_prm = [100, 2, 0.2, (0.2,0.3), (2,2.1), (3,3.1)]
sim_prm = torch.as_tensor([6., 0.001, 1e-12, 1e-3, nan], device = dev, dtype = enc)
dof[16] += 0.01*jobID
dof_a5snp = dof.clone()
dof_a5snp[17] -= TO_BE_DETERMINED
nic_amplitude = 0.75
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
maintenances_healthy_bloem = dmts.maintenances/dmts.nb_trials
ccm = CCM(dof_a5snp, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
maintenances_a5snp_bloem = dmts.maintenances/dmts.nb_trials
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True, nic_normalization = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
maintenances_healthy_kamigaki = dmts.maintenances/dmts.nb_trials
ccm = CCM(dof_a5snp, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True, nic_normalization = True )
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_timing = 1, distractor_amplitude=5, distractor_duration=0.05)
maintenances_a5snp_kamigaki = dmts.maintenances/dmts.nb_trials
toSave = np.array([maintenances_healthy_bloem, maintenances_a5snp_bloem, maintenances_healthy_kamigaki, maintenances_a5snp_kamigaki])
save_data()
def nicotinic_dmts(jobID, nic_normalization = False, kamigaki = False):
array_length = 120
middle = int(array_length/2)
Istep = 0.025
sim_prm = torch.as_tensor([6., 0.001, 1e-12, 1e-3, nan], device=dev, dtype=enc)
task_prm = [100, 2, 0.05, (0.2,0.3), (2, 2.1), (3.,3.1)] # CHANGE CUE DURATION & AMPLITUDE !
# VIP
dof_vip = dof.clone()
dof_vip[17] -= (middle - jobID)*Istep # jobID = 0 --> Iext -= 2.5
ccm = CCM(dof_vip, mod_prm, sim_prm, STP = True, two_columns = True, nic_normalization = nic_normalization, kamigaki = kamigaki)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_timing = 1, distractor_amplitude = dist_amp, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2)
load_vip = dmts.loadings/dmts.nb_trials
delay_vip = dmts.maintenances/dmts.nb_trials
# PV
dof_pv = dof.clone()
dof_pv[15] -= (middle - jobID)*Istep
ccm = CCM(dof_pv, mod_prm, sim_prm, STP = True, two_columns = True, nic_normalization = nic_normalization, kamigaki = kamigaki)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_timing = 1, distractor_amplitude = dist_amp, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2)
load_pv = dmts.loadings/dmts.nb_trials
delay_pv = dmts.maintenances/dmts.nb_trials
# SOM
dof_som = dof.clone()
dof_som[16] -= (middle - jobID)*Istep
ccm = CCM(dof_som, mod_prm, sim_prm, STP = True, two_columns = True, nic_normalization = nic_normalization, kamigaki = kamigaki)
load_som = dmts.loadings/dmts.nb_trials
dmts = DMTS(ccm, task_prm, distractor = True, distractor_timing = 1, distractor_amplitude = dist_amp, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2)
delay_som = dmts.maintenances/dmts.nb_trials
# PV & SOM
dof_pv_som = dof.clone()
dof_pv_som[15] -= (middle - jobID)*Istep
dof_pv_som[16] -= (middle - jobID)*Istep
ccm = CCM(dof_pv_som, mod_prm, sim_prm, STP = True, two_columns = True, nic_normalization = nic_normalization, kamigaki = kamigaki)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_timing = 1, distractor_amplitude = dist_amp, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2)
load_pv_som = dmts.loadings/dmts.nb_trials
delay_pv_som = dmts.maintenances/dmts.nb_trials
# ACh DEPLETION
dof_ACh = dof.clone()
dof_ACh[15] -= (middle - jobID)*(Istep/5)
dof_ACh[16] -= (middle - jobID)*Istep
dof_ACh[17] -= (middle - jobID)*Istep
ccm = CCM(dof_ACh, mod_prm, sim_prm, STP = True, two_columns = True, nic_normalization = nic_normalization, kamigaki = kamigaki)
dmts = DMTS(ccm, task_prm, distractor = True, distractor_timing = 1, distractor_amplitude = dist_amp, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2)
load_ACh = dmts.loadings/dmts.nb_trials
delay_ACh = dmts.maintenances/dmts.nb_trials
toSave = np.array([load_vip, delay_vip, load_pv, delay_pv, load_som, delay_som, load_pv_som, delay_pv_som])
save_data('nicotinic_dmts', 'nicdmts', toSave, jobID)
#if not os.path.exists('output_dir'): os.mkdir('output_dir')
<file_sep>/README.md
Skip to content
Search or jump to…
Pull requests
Issues
Marketplace
Explore
@EliasElOtmani
EliasElOtmani
/
wm_nachrs
Private
1
00
Code
Issues
Pull requests
Actions
Projects
Security
Insights
Settings
wm_nachrs/README.txt
@EliasElOtmani
EliasElOtmani Add files via upload
Latest commit 5dd2003 6 minutes ago
History
1 contributor
50 lines (31 sloc) 2.47 KB
############
# ABSTRACT #
############
This project corresponds to a research work performed at the Laboratoy of Cognitive and Computational Neuroscience (LNC2) of the Ecole Normale Supérieure of Paris, in the Team Mathematics of Neural Circuits of Pr. <NAME>.
The corresponding thesis is included in the folder.
###########
# SCRIPTS #
###########
This code is almost entirely object-oriented. The four important classes are :
-----------------------------------------------------------------------------------------------------
* NeuralPop.py : Stands for a Neural Population, which also includes the nested class Synapse. This class functions as an input-output object which can be interconnected with other Neural Populations.
* CCM.py : Canonical Cortical Model, this class stands for a model of supragranular prefrontal circuitry. It uses interconnected Neural Populations and generates (and stores) Simulations.
* Simulation.py : Recording of simulated neural traces over time. Its postproc function allows to return the corresponding summary statistics.
* DMTS.py : The Delayed Match-To-Sample task, it uses CCMs and generates Simulations according to defined task parameters.
-----------------------------------------------------------------------------------------------------
Most of the heavy computations (i.e., simulations) were performed on the parallel computing cluster of the LNC2, "Frontex". The cluster runs on functions defined on the following scripts :
-----------------------------------------------------------------------------------------------------
* dmts_frontex.py
* helper_frontex.py : These two scripts generate simulations for DMTS analysis
* infer_frontex.py : For simulating data with random models for further inference
-----------------------------------------------------------------------------------------------------
Finally, the repository includes the following Jupyter Notebooks :
-----------------------------------------------------------------------------------------------------
* DMTS_analysis.ipynb Analysis of DMTS simulations
* infer_on_presim_data.ipynb Perform Approximate Bayesian Computation
* div_modulation.ipynb Study of neural subpopulation response functions
-----------------------------------------------------------------------------------------------------
########
# DATA #
########
Simulated output data is stored in the brand_new_data and inference_data repositories
© 2021 GitHub, Inc.
Terms
Privacy
Security
Status
Docs
Contact GitHub
Pricing
API
Training
Blog
About
Loading complete
<file_sep>/CCM.py
#!/usr/bin/env python
__author__ = "<NAME>"
__credits__ = "<NAME>"
__email__ = "<EMAIL>"
# An "instance" of CCM stands for one or two cortical columns with defined parameters.
# Once declared at the instanciation, the latter only change if explicitly modified
# Conversely, simulation parameters are easily re-declared for each simulation.
import numpy as np
from numpy import nan
from scipy import optimize
import os, sys, time, torch
from NeuralPop import NeuralPop
from Simulation import Simulation
# DEFAULT PARAMETERS
mod_prm = torch.as_tensor([.020, .007, .600, 3, 0., 1.9, 2.6, 1.5, 1.2, 7., 7., 7., 7., 1/26, 1, 1], device=dev, dtype=enc) # refractory period : from 0.0025 to 0.01
sim_prm = torch.as_tensor([5, .001, 1e-12, 1e-3, nan], device=dev, dtype=enc)
dof = torch.as_tensor([
Ae, Ap, As, Av, # Ae, Ap, As, Av (4)
# wee, wpe, wse, wes, wvs, wep, wpp, wsp, wev, wsv (10) :
.136*Ae, .075*Ap, .045*As, .053*Ae, .04*Av, .17*Ae, .093*Ap, .0*As, .053*Ae, .001*As,
4.4, 4.8, 2.7, 1.9, # Ie_ext, Ip_ext, Is_ext, Iv_ext (5)
0.2, .03*Ae, 25 # q, J_adp, sigma (3)
], device=dev, dtype=enc)
# CCM
class CCM():
def __init__(self, dof = dof, mod_prm = mod_prm, sim_prm = None, equilibria = False, reject = False, computer = "cpu", enc = torch.float64, STP = True, two_columns = False, pdr = 0.5, notebook = None, kamigaki = False, nic_normalization = False):
# TEMPORARY, find a way to better deal with this
self.notebook = notebook
self.dev = torch.device(computer)
self.atol, self.rtol = 1e-12, 1e-3
self.sim_prm = sim_prm
self.mod_prm = mod_prm
self.dof = dof
self.reject = reject
self.simulations = []
self.usf = mod_prm[13] # Frequency of ultra-slow fluctuations
self.STP = STP
self.two_columns = two_columns
self.nic_normalization = nic_normalization
self.kamigaki = kamigaki
if not two_columns : self.thalamus, self.populations = self.grow_single_column(mod_prm, dof)
else : self.thalamus, self.thalamus2, self.cholinergic_nuclei, self.populations = self.grow_two_columns(mod_prm, dof, pdr)
self.dim = len(self.populations)
### MODEL
# Sources of stochasticity.
self.poisson = torch.distributions.poisson.Poisson(torch.tensor([self.usf])) # Poisson distribution of stimuli.
self.n = torch.distributions.normal.Normal(torch.tensor([0.0]), torch.tensor([1.0])) # Normal distribution of neural noise.
# Short-hand indices for tensor-based data storage [1](int)
self.RE, self.RP, self.RS, self.RV, self.dRE, self.dRP, self.dRS, self.dRV, self.TT = 0, 1, 2, 3, 4, 5, 6, 7, 8
self.INE_E, self.INE_P, self.INE_S, self.INE_V, self.INS_E, self.INS_P, self.INS_S, self.INS_V = 9, 10, 11, 12, 13, 14, 15, 16
self.IND_E, self.IE_ADP = 17, 18
# Compute equilibria as soon as instantiated :
self.hidden_eq = False # Hidden equilibria, supra-saturation dynamics
if equilibria :
self.S = self.equilibria()
try : self.critic = self.S[1]
except : self.critic = torch.as_tensor([20 for i in range(self.dim)], device = self.dev, dtype = torch.float64)
else :
self.S = [None]
self.critic = torch.as_tensor([20 for i in range(self.dim)], device = self.dev, dtype = torch.float64)
def simulate(self, sim_prm = sim_prm, info=False, plot=False, dmts = False, cue_timings = [1], Itrans_duration = 0.05, reject = None, distractor = False, distractor_timing = 2, distractor_duration = 0.05, distractor_amplitude = 1, nic_trans = False, nic_trans_timing = 1.5, nic_trans_duration = 1, nic_trans_amplitude = 0.5): # Maybe put reject in sim_prm
"""
Returns raw simulated data corresponding to time-evolutions of CCM's latent variables.
Entries:
-------
plot = bool : option parameter (default is False) conditioning output's dimensionality.
Outputs:
-------
When plot is set to True:
tsr = torch.Tensor(size=(17, _), device=dev, dtype=enc) : data tensor storing time-evolutions of all latent variables.
stim = torch.Tensor(size=_, device=dev, dtype=enc) : data tensor storing stimuli time-events.
When plot is set to False:
tsr = torch.Tensor(size=(9, _), device=dev, dtype=enc) : data tensor storing time-evolutions of neural populations' rates and their derivatives.
"""
### SIMULATION PARAMETERS
if sim_prm is None : sim_prm = self.sim_prm
if sim_prm is None :
print('No simulation parameters declared')
return
### ABORT
if reject is None : reject = self.reject
if reject and len(self.S) < 3:
if info : print('Model not bistable')
return Simulation(None, None, sim_prm, self.mod_prm, self.dof, self.critic, aborted = True)
window = sim_prm[0].item() # Stimulation window [s](float).
dt = sim_prm[1].item() # Time resolution [s](float).
#atol, rtol = sim_prm[2].item(), sim_prm[3].item() # Absolute and relative tolerances for float comparison.
if torch.isnan(sim_prm[4]):
torch.manual_seed(time.time())
else:
torch.manual_seed(sim_prm[4])
#smin = round(3 * max(self.tau, self.tau_adp) / dt) # Starting time for stimulation window [1](int).
smin = 10 # CORRECT THAT
smax = round(window / dt) # End of stimulation window [1](int).
N = smin + smax # Total number of time-points [1](int)
if distractor_amplitude is not None and self.two_columns : self.thalamus2.Itrans = distractor_amplitude*100
if nic_trans_amplitude is not None and self.two_columns : self.cholinergic_nuclei.Itrans = nic_trans_amplitude*100
### SIMULATION
tsr = torch.empty((self.dim+1, N), device=self.dev, dtype=torch.float64)
stim = []
Itrans_start = - Itrans_duration/dt
distractor_start = - distractor_duration/dt
nic_trans_start = - nic_trans_duration/dt
for k in range(N):
# TRANSIENTS
if (k - Itrans_start)*dt > Itrans_duration :
self.thalamus.fr = 0.
if (not dmts and self.poisson.sample().item() > 1) or (dmts and k*dt in cue_timings):
self.thalamus.fr = self.thalamus.Itrans
Itrans_start = k
stim.append(k*dt)
if distractor and (k - distractor_start)*dt > distractor_duration:
try : self.thalamus2.fr = 0
except :
print('Two columns are needed for using distractors. Aborting...')
sys.exit()
if k*dt == distractor_timing:
self.thalamus2.fr = self.thalamus2.Itrans
distractor_start = k
if nic_trans and (k - nic_trans_start)*dt > nic_trans_duration :
try : self.cholinergic_nuclei.fr = 0
except :
print('Cholinergic innervation is needed for this mode')
sys.exit()
if k*dt == nic_trans_timing:
self.cholinergic_nuclei.fr = self.cholinergic_nuclei.Itrans
nic_trans_start = k
# STEPS
for pop in self.populations : pop.get_derivative(dt, self.n.sample().item())
for pop in self.populations : pop.step(dfr_computed = True)
for i in range(self.dim): tsr[i, k] = self.populations[i].fr
tsr[-1, k] = k*dt
for pop in self.populations : pop.reset()
self.simulations.append((Simulation(self, tsr, stim, sim_prm, reject, info, plot)))
return self.simulations[-1]
# Shouldn't fr be constrained to positive values earlier in the code ?
def equilibria(self):
"""
Returns all possible dynamical equilibria of the deterministic model.
Entries:
-------
info = bool : optional argument warning when tested parameter set leads to non-bistable dynamics.
Outputs:
-------
S = [[...], [...], ...] : NumPy-type list of 4-dimensional coordinates of dynamical equilibria.
"""
dt = 0.01
def F(x):
#[pop.fr for pop in self.populations] = x
for i in range(self.dim) : self.populations[i].fr = x[i]
derivatives = [pop.get_derivative(dt) for pop in self.populations]
return derivatives
for pop in self.populations : pop.deterministic()
S = [np.random.uniform(size=self.dim)]
for k in range(1000):
x0 = [400*np.random.uniform(size=self.dim) - 200]
sol = optimize.root(F, x0, method='hybr')
#sol = optimize.fsolve(F, x0)
if not np.isclose(sol.x, S, atol=self.atol, rtol=self.rtol).any():
if np.isclose(F(sol.x), [0. for i in range(self.dim)], atol=self.atol, rtol=self.rtol).all():
S.append(sol.x)
for pop in self.populations : pop.reset()
S = S[1:]
# ATTEMPTING TO CUT SATURATED EQUILIBRIA OFF, gotta go back to this
'''
for s in S:
if not np.array([fr < .45 for fr in [s[0] / self.Ae, s[1] / self.Ap, s[2] / self.As, s[3] /self.Av]]).all() :
# S.remove(s) HERE bug : the truth value of an array with more than one element is ambiguous
self.hidden_eq = True
'''
return np.sort(S, 0)
def free(): # Free memory from this column and every attached population
pass
def grow_single_column(self, mod_prm, dof):
### FIXED MODEL PARAMETERS
# /!\ Tref shouldn't be the same for all neurons !
tau_m, tau_m_PVs, tau_adp = mod_prm[0].item(), mod_prm[1].item(), mod_prm[2].item() # Circuit and adaptation time constants [s](float) ; Amount of divisive inhibition [1](float).
Itrans = mod_prm[3].item()
gaba = 1. + mod_prm[4].item() # Conductance of GABAergic projections [1](float).
a_e, a_p, a_s, a_v = mod_prm[5].item(), mod_prm[6].item(), mod_prm[7].item(), mod_prm[8].item() # Maximal slopes of populational response functions [1](float).
b_e, b_p, b_s, b_v = mod_prm[9].item(), mod_prm[10].item(), mod_prm[11].item(), mod_prm[12].item() # Critical thresholds of populational response functions [1](float).
Tref_PYR, Tref_INs = mod_prm[14], mod_prm[15]
### FREE MODEL PARAMETERS (DEGREES OF FREEDOM)
# Scaling factors [spikes/min](float).
Ae, Ap, As, Av = dof[0].item(), dof[1].item(), dof[2].item(), dof[3].item()
# Normalized synaptic weights [1 -> min/spikes](float).
wee, wpe, wse = dof[4].item() / Ae, gaba * dof[5].item() / Ap, gaba * dof[6].item() / As ## MAYBE we should normalize the weights in the Synapse() class ? (has access to presynaptic amplitude)
wes, wvs = dof[7].item() / Ae, dof[8].item() / Av
wep, wpp, wvp, wsp = dof[9].item() / Ae, gaba * dof[10].item() / Ap, .3*wvs, gaba * dof[11].item() / As
wev, wsv = dof[12].item() / Ae, gaba * dof[13].item() / As
# External currents [1](float).
Ie_ext, Ip_ext, Is_ext, Iv_ext = dof[14].item(), dof[15].item(), dof[16].item(), dof[17].item()
# Bistable dynamics parameters.
q, J_adp, sigma = dof[18].item(), dof[19].item() / Ae, dof[20].item()
# /!\ WARNING #
# Originally dof[21] is usf. We decide to make it fixed (included as mod_prm[12]) and shorten dof to length of 21.
# Also, we fix I_trans (originally dof[18] as mod_prm[13]. Instead,
# we define q as a free parameter (originally defined above as mod[2])
### POPULATIONS & CONNEXIONS INSTANTIATION
pyr = NeuralPop('pyr', self, Ae, sigma, tau_m, tau_adp, a_e, b_e, Ie_ext, NT = 'glutamate', Tref = Tref_PYR, J_adp = J_adp)
pv = NeuralPop('pv', self, Ap, sigma, tau_m_PVs, tau_adp, a_p, b_p, Ip_ext, NT = 'gaba', Tref = Tref_INs)
som = NeuralPop('som', self, As, sigma, tau_m, tau_adp, a_s, b_s, Is_ext, NT = 'gaba', Tref = Tref_INs, J_adp = 0)
vip = NeuralPop('vip', self, Av, sigma, tau_m, tau_adp, a_v, b_v, Iv_ext, NT = 'gaba', Tref = Tref_INs, J_adp = 0)
thalamus = NeuralPop('thalamus', self, None, None, None, None, None, None, None, NT = 'glutamate', Itrans = Itrans)
pyr.synapse(pyr, wee)
if self.STP : pyr.synapse(pv, wpe, q, STP = 'd', stained = False)
else : pyr.synapse(pv, wpe, q)
pyr.synapse(som, wse)
if self.STP : som.synapse(pyr, wes, STP = 'f', stained = False)
else : som.synapse(pyr, wes)
som.synapse(vip, wvs)
if self.STP : pv.synapse(pyr, wep, STP = 'd', stained = False)
else : pv.synapse(pyr, wep)
pv.synapse(pv, wpp)
pv.synapse(vip, wvp)
pv.synapse(som, wsp)
vip.synapse(pyr, wev)
vip.synapse(som, wsv)
wbu = 0.01 # bottum-up weight
pyr.synapse(thalamus, 1*wbu)
if self.STP : pv.synapse(thalamus, 0.5*wbu, STP = 'd')
else : pv.synapse(thalamus, 0.5*wbu)
vip.synapse(thalamus, 0.5*wbu)
#self.thalamus2 = NeuralPop('thalamus', None, None, None, None, None, None, None, NT = 'glutamate', Itrans = Itrans)
#pv.synapse(thalamus, 1)
populations = [pyr, pv, som, vip]
return thalamus, populations
def grow_two_columns(self, mod_prm, dof, pdr = 1, distractor_amplitude = 3, nic_trans_amplitude = 0.5): # pdr : Proximal / Distal Ratio of synaptic strengths. We alse have to set distal wes and nicotinic transient amplitude so that they can be defined from main.
### FIXED MODEL PARAMETERS
# /!\ Tref shouldn't be the same for all neurons !
tau_m, tau_m_PVs, tau_adp = mod_prm[0].item(), mod_prm[1].item(), mod_prm[2].item() # Circuit and adaptation time constants [s](float) ; Amount of divisive inhibition [1](float).
Itrans = mod_prm[3].item()
gaba = 1. + mod_prm[4].item() # Conductance of GABAergic projections [1](float).
a_e, a_p, a_s, a_v = mod_prm[5].item(), mod_prm[6].item(), mod_prm[7].item(), mod_prm[8].item() # Maximal slopes of populational response functions [1](float).
b_e, b_p, b_s, b_v = mod_prm[9].item(), mod_prm[10].item(), mod_prm[11].item(), mod_prm[12].item() # Critical thresholds of populational response functions [1](float).
Tref_PYR, Tref_INs = mod_prm[14], mod_prm[15]
### FREE MODEL PARAMETERS (DEGREES OF FREEDOM)
# Scaling factors [spikes/min](float).
Ae, Ap, As, Av = dof[0].item(), dof[1].item(), dof[2].item(), dof[3].item()
# Normalized synaptic weights [1 -> min/spikes](float).
wee, wpe, wse = dof[4].item() / Ae, gaba * dof[5].item() / Ap, gaba * dof[6].item() / As ## MAYBE we should normalize the weights in the Synapse() class ? (has access to presynaptic amplitude)
wes, wvs = dof[7].item() / Ae, dof[8].item() / Av
wep, wpp, wvp, wsp = dof[9].item() / Ae, gaba * dof[10].item() / Ap, .3*wvs, gaba * dof[11].item() / As
wev, wsv = dof[12].item() / Ae, gaba * dof[13].item() / As
# External currents [1](float).
Ie_ext, Ip_ext, Is_ext, Iv_ext = dof[14].item(), dof[15].item(), dof[16].item(), dof[17].item()
# Adaptation of external currents for two populations :
re, rs, rv = 1.1926, 35, 1.0847 # We use UP-state rs because activated by the other pop
re, rs, rv = 1.4090, 1.2391, 1.6413
Is_ext -= pdr*wes*re
#Ip_ext = Ip_ext + wvp*rv + wsp*35 - wep*re
Ip_ext = Ip_ext + wvp*rv - wep*re + wsp*32
# Bistable dynamics parameters.
q, J_adp, sigma = dof[18].item(), dof[19].item() / Ae, dof[20].item()
beta2 = 1.5 # /!\ We consider 0.5 to be muscarinic, never make it drop to 0 !
alpha5 = 0.5
alpha7 = 0.25
Itrans_ACh = nic_trans_amplitude
# /!\ WARNING #
# Originally dof[21] is usf. We decide to make it fixed (included as mod_prm[12]) and shorten dof to length of 21.
# Also, we fix I_trans (originally dof[18] as mod_prm[13]. Instead,
# we define q as a free parameter (originally defined above as mod[2])
### POPULATIONS & CONNEXIONS INSTANTIATION
pyr1 = NeuralPop('pyr', self, Ae, sigma, tau_m, tau_adp, a_e, b_e, Ie_ext, NT = 'glutamate', Tref = Tref_PYR, J_adp = J_adp)
pyr2 = NeuralPop('pyr', self, Ae, sigma, tau_m, tau_adp, a_e, b_e, Ie_ext, NT = 'glutamate', Tref = Tref_PYR, J_adp = J_adp)
pv = NeuralPop('pv', self, Ap, sigma, tau_m_PVs, tau_adp, a_p, b_p, Ip_ext, NT = 'gaba', Tref = Tref_INs)
som1 = NeuralPop('som', self, As, sigma, tau_m, tau_adp, a_s, b_s, Is_ext, NT = 'gaba', Tref = Tref_INs, J_adp = 0)
som2 = NeuralPop('som', self, As, sigma, tau_m, tau_adp, a_s, b_s, Is_ext, NT = 'gaba', Tref = Tref_INs, J_adp = 0)
vip1 = NeuralPop('vip', self, Av, sigma, tau_m, tau_adp, a_v, b_v, Iv_ext, NT = 'gaba', Tref = Tref_INs, J_adp = 0)
vip2 = NeuralPop('vip', self, Av, sigma, tau_m, tau_adp, a_v, b_v, Iv_ext, NT = 'gaba', Tref = Tref_INs, J_adp = 0)
thalamus1 = NeuralPop('thalamus', self, None, None, None, None, None, None, None, NT = 'glutamate', Itrans = Itrans)
thalamus2 = NeuralPop('thalamus', self, None, None, None, None, None, None, None, NT = 'glutamate', Itrans = distractor_amplitude)
cholinergic_nuclei = NeuralPop('cholinergic_nuclei', self, None, None, None, None, None, None, None, NT = 'ACh', Itrans = Itrans_ACh)
# INTRACOLUMNAR SYNAPSES #
# Column 1
pyr1.synapse(pyr1, wee)
if self.STP : pyr1.synapse(pv, wpe, q, STP = 'd', stained = False)
else : pyr1.synapse(pv, wpe, q)
pyr1.synapse(som1, wse)
if self.STP : som1.synapse(pyr1, wes, STP = 'f', stained = False)
else : som1.synapse(pyr1, wes)
som1.synapse(vip1, wvs)
if self.STP : pv.synapse(pyr1, wep, STP = 'd')
else : pv.synapse(pyr1, wep)
pv.synapse(pv, wpp)
pv.synapse(vip1, wvp)
pv.synapse(som1, wsp)
vip1.synapse(pyr1, wev)
vip1.synapse(som1, wsv)
wbu = 0.01
pyr1.synapse(thalamus1, 1*wbu)
if self.STP : pv.synapse(thalamus1, 0.5*wbu, STP = 'd', stained = False)
else : pv.synapse(thalamus1, 0.5*wbu)
vip1.synapse(thalamus1, 0.5*wbu)
# Column 2
pyr2.synapse(pyr2, wee)
if self.STP : pyr2.synapse(pv, wpe, q, STP = 'd')
else : pyr2.synapse(pv, wpe, q)
pyr2.synapse(som2, wse)
if self.STP : som2.synapse(pyr2, wes, STP = 'f')
else : som2.synapse(pyr2, wes)
som2.synapse(vip2, wvs)
if self.STP : pv.synapse(pyr2, wep, STP = 'd')
else : pv.synapse(pyr2, wep)
pv.synapse(vip2, wvp)
pv.synapse(som2, wsp)
vip2.synapse(pyr2, wev)
vip2.synapse(som2, wsv)
pyr2.synapse(thalamus2, 1*wbu)
#if self.STP : pv.synapse(thalamus2, 0.5*wbu, STP = 'd')
#else : pv.synapse(thalamus2, 0.5*wbu)
vip2.synapse(thalamus2, 0.5*wbu)
# INTERCOLUMNAR SYNAPSES #
#pyr1.synapse(som2, pdr*wse)
#pyr2.synapse(som1, pdr*wse)
if self.STP : som1.synapse(pyr2, pdr*wes, STP = 'f') # Lets say for now PYR cells connect just as much to intra than intercolumnar SOMs
else : som1.synapse(pyr2, wes)
if self.STP : som2.synapse(pyr1, pdr*wes, STP = 'f')
else : som2.synapse(pyr1, wes)
# FOREBRAIN SYNAPSES #
vip1.synapse(cholinergic_nuclei, 0.5*wbu, nic_normalization = self.nic_normalization)
vip2.synapse(cholinergic_nuclei, 0.5*wbu, nic_normalization = self.nic_normalization)
if not self.kamigaki : som1.synapse(cholinergic_nuclei, 2*wbu, STP = 'd', nic_normalization = self.nic_normalization, stained = True)
if not self.kamigaki : som2.synapse(cholinergic_nuclei, 2*wbu, STP = 'd', nic_normalization = self.nic_normalization)
#pv.synapse(cholinergic_nuclei, 0.5, STP = 'd')
populations = [pyr1, pv, som1, vip1, pyr2, som2, vip2]
return thalamus1, thalamus2, cholinergic_nuclei, populations
<file_sep>/helper.py
import numpy as np
import torch, os
from numpy import nan
from CCM import CCM
from DMTS import DMTS
from dmts_frontex import save_data
computer = "cpu"
dev_str = 'cpu'
cores = 6
num_workers = 4 * cores
enc = torch.float64
dev = torch.device(computer)
info = False
reject = False
plot = False
mod_prm = torch.as_tensor([.020, 0.007, .600, 2.2, 0., 1.9, 2.6, 1.5, 1.2, 7., 7., 7., 7., 1/26, 1, 1], device=dev, dtype=enc)
sim_prm = torch.as_tensor([5., 0.001, 1e-12, 1e-3, nan], device=dev, dtype=enc)
task_prm = [100, 1, 0.05, (0.2,0.3), (2, 2.1), (3.,3.1)]
Ae, Ap, As, Av = 169, 268, 709, 634
dof = torch.as_tensor([
Ae, Ap, As, Av, # Ae, Ap, As, Av (4)
# wee, wpe, wse, wes, wvs, wep, wpp, wsp, wev, wsv (10) :
.136*Ae, .075*Ap, .045*As, .053*Ae, .04*Av, .17*Ae, .093*Ap, .0*As, .053*Ae, .001*As,
4.4, 4.8, 2.7, 1.9, # Ie_ext, Ip_ext, Is_ext, Iv_ext (5)
0.2, .03*Ae, 25 # q, J_adp, sigma (3)
], device=dev, dtype=enc)
dist_amp = 0 # To be determined
nic_amplitude = 0 # To be determined
def a5snp_transient(jobID):
mod_prm = torch.as_tensor([.020, 0.007, .600, 2.2, 0., 1.9, 2.6, 1.5, 1.2, 7., 7., 7., 7., 1/26, 1, 1], device=dev, dtype=enc)
sim_prm = torch.as_tensor([6., 0.001, 1e-12, 1e-3, nan], device=dev, dtype=enc)
task_prm = [100, 2, 0.2, (0.2,0.3), (2, 2.1), (3.,3.1)]
nic_amplitude = 0.75
distractor_amplitude = 5
dof_vip = dof.clone()
dof_vip[17] -= 0.01*jobID
'''
ccm = CCM(dof_vip, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings_bloem = dmts.loadings/dmts.nb_trials
ccm = CCM(dof_vip, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True, nic_normalization = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings_kamigaki = dmts.loadings/dmts.nb_trials
toSave = np.array([encodings_bloem, encodings_kamigaki])
save_data('a5snp_transient', 'a5snp_trans', toSave, jobID)
'''
ccm = CCM(dof_vip, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = False, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings = dmts.loadings/dmts.nb_trials
toSave = np.array([encodings])
save_data('a5snp_attention_reorientation_no_transient', 'encoding', toSave, jobID)
def nicotine_restoration(jobID):
mod_prm = torch.as_tensor([.020, 0.007, .600, 2.2, 0., 1.9, 2.6, 1.5, 1.2, 7., 7., 7., 7., 1/26, 1, 1], device=dev, dtype=enc)
sim_prm = torch.as_tensor([6., 0.001, 1e-12, 1e-3, nan], device=dev, dtype=enc)
task_prm = [100, 2, 0.2, (0.2,0.3), (2, 2.1), (3.,3.1)]
nic_amplitude = 0.75
distractor_amplitude = 5
dof[16] -= 0.01*jobID
dof_vip = dof.clone()
dof_vip_bloem = dof.clone()
dof_vip[17] = 1.7
dof_vip_bloem[17] = 1.4
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings_bloem_healthy = dmts.loadings/dmts.nb_trials
ccm = CCM(dof_vip_bloem, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings_bloem_a5snp = dmts.loadings/dmts.nb_trials
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True, nic_normalization = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings_kamigaki_healthy = dmts.loadings/dmts.nb_trials
ccm = CCM(dof_vip, mod_prm, sim_prm, equilibria = False, two_columns = True, STP = True, kamigaki = True, nic_normalization = True)
dmts = DMTS(ccm, task_prm = task_prm, nic_trans = True, nic_trans_amplitude = nic_amplitude, nic_trans_timing = 2, distractor = True, distractor_amplitude = distractor_amplitude, distractor_timing = 1, distractor_duration = 0.05)
encodings_kamigaki_a5snp = dmts.loadings/dmts.nb_trials
toSave = np.array([encodings_bloem_healthy, encodings_bloem_a5snp, encodings_kamigaki_healthy, encodings_kamigaki_a5snp])
save_data('nicotine_restoration', 'nicotine', toSave, jobID)
<file_sep>/infer_frontex.py
def infer(job_id):
import numpy as np
import matplotlib.pyplot as plt
import torch
from Simulation import Simulation
from CCM import CCM
from numpy import nan
def model(theta):
mod_prm = torch.as_tensor([.020, .007, .600, 2, 0., 1.9, 2.6, 1.5, 1.2, 7., 7., 7., 7., 1/26, 0.008, 0.002], device=dev, dtype=enc) # refractory period : from 0.0025 to 0.01
sim_prm = torch.as_tensor([10, .005, 1e-12, 1e-3, nan], device=dev, dtype=enc)
Wee, Wpe, Wse = theta[:3]
Wes, Wvs = theta[3:5]
Wep, Wpp, Wsp = theta[5:8]
Wev, Wsv = theta[8:10]
Ie_ext, Ip_ext, Is_ext, Iv_ext = theta[10:14]
Tref_PYR, Tref_INs = mod_prm[14], mod_prm[15]
amplitudes = torch.as_tensor([1/Tref_PYR,1/Tref_INs,1/Tref_INs,1/Tref_INs])
q = 0.5
sigma = 0.1
q_theta_jadp_sigma = torch.as_tensor([q, theta[-1], sigma])
dof = torch.cat((amplitudes, theta[:-1], q_theta_jadp_sigma), 0)
# /!\ Sigma was at the last position, q antépénultième !
ccm = CCM(dof, mod_prm, sim_prm, equilibria = False)
ccm.simulate(reject = False, dmts = False, info = False)
sim = ccm.simulations[0]
return sim.postproc()
computer = "cpu"
enc = torch.float64
dev = torch.device(computer)
dim = 15 # Number of degrees of freedom of the simulator [w_xy (10), I_ext-x (4), J_adp]
# PRIORS
mW, mI, mP = [.1 for k in range(10)], [1 for k in range(4)], [3]
MW, MI, MP = [75. for k in range(10)], [10. for k in range(4)], [15]
priors_min, priors_max = np.concatenate((mW, mI, mP)), np.concatenate((MW, MI, MP))
priors = np.array([priors_min, priors_max])
prior_min = torch.as_tensor(priors_min, device=dev, dtype=torch.float64)
prior_max = torch.as_tensor(priors_max, device=dev, dtype=torch.float64)
#theta = np.random.uniform(low = priors_min, high = priors_max, size = (2000,17))
theta = np.empty([2, 15])
for params in theta :
params[4] = np.random.uniform(low = priors_min[4], high = priors_max[4]) # Wvs
params[6] = np.random.uniform(low = priors_min[6], high = priors_max[6]) # Wpp
params[1] = np.random.uniform(low = 0.5*params[6], high = params[6]) # 0.5*Wpp < Wpe < Wpp
params[7] = np.random.uniform(low = priors_min[7], high = 0.5*params[6]) # Wsp < 0.5*Wpp
params[9] = np.random.uniform(low = (1/1.25)*params[7], high = 4*params[7]) # (1/1.25)*Wsp < Wsv < 4*Wsp
params[2] = np.random.uniform(low = priors_min[2], high = min(params[1], params[9])) # Wse < Wsv, Wse < Wpe
params[0] = np.random.uniform(low = priors_min[0], high = priors_max[0]) # Wee
params[5] = np.random.uniform(low = params[0], high = priors_max[5]) # Wep > Wee
params[8] = np.random.uniform(low = params[0], high = params[5]) # Wee < Wev < Wep
params[3] = np.random.uniform(low = params[0], high = params[5]) # Wee < Wes < Wep
params[11:] = np.random.uniform(low = priors_min[11:], high = priors_max[11:]) # Iext except Ie_ext, Jadp
params[10] = np.random.uniform(low = max(params[11:-1]), high = priors_max[10]) # Ie_ext
theta = torch.as_tensor(theta)
x = list(map(model, theta))
x = np.vstack([params.numpy() for params in x])
toSave = np.hstack((x, theta))
#file_id = [str(np.random.randint(0,9)) for i in range(10)]
#file_id = "".join(file_id)
# with open('/shared/projects/project_nicWM/data/round1/x_theta_' + str(job_id) + '.np', 'wb') as h:
# np.save(h, toSave)
with open('C:/Users/elias/Desktop/CogSci/Internship/Code/output_data/' + str(job_id) + '.npy', 'wb') as h:
np.save(h, toSave)
<file_sep>/DMTS.py
#!/usr/bin/python
import numpy as np
from numpy import nan
#from scipy import optimize
import os, sys, time, torch
#from tqdm import tqdm
#import matplotlib.pyplot as plt
from CCM import CCM
from Simulation import Simulation
# We want our class to have a ccm and task parameters among which
# how many simulations to perform to obtain P(erase) etc...
'''
We want :
- A perform function (maybe just the init ?)
- A plot stats function :
- Different probabilities
- A plot function :
-Vertical line at the stimulus
'''
# task_param = [num_trials, stimulus_timing, load_interval, delay_interval, clearance_interval]
# num_ccm with different sets of parameters ?.. Rather not
default_task_prm = [5, 1, 0.1, (1.85,1.950), (2.65, 2.75), (3.65,3.75)]
default_task_prm = [5, 1, 0.05, (0.,0.1), (2, 2.1), (3.,3.1)]
dt = 0.001
# Let's put the distractor at t = 2sec
class DMTS():
def __init__(self, ccm, task_prm = default_task_prm, sim_prm = None, reject = False, distractor = False, distractor_amplitude = 1, distractor_timing = 2, distractor_duration = 0.2, nic_trans = False, nic_trans_amplitude = 1, nic_trans_timing = 2):
computer = 'cpu'
self.enc = torch.float64
self.dev = torch.device(computer)
self.ccm = ccm
self.sim_prm = sim_prm
self.nb_trials = task_prm[0]
self.t_stim = task_prm[1] # Stimulus timing
self.stim_duration = task_prm[2]
self.stim_end = self.t_stim + self.stim_duration
self.load_interval = [t + self.stim_end for t in task_prm[3]]
self.delay_interval = [t + self.stim_end for t in task_prm[4]]
self.clear_interval = [t + self.stim_end for t in task_prm[5]]
self.trials = []
try : self.critic = torch.as_tensor(ccm.S[-2], device=self.dev, dtype=self.enc)
except :
self.critic = torch.as_tensor([20 for i in range(ccm.dim)], device = self.dev, dtype = self.enc) # Maybe add an equivalent of info
critic_re = self.critic[0].item()
# Successful operations :
self.loadings = 0
self.maintenances = 0
self.clearances = 0
for trial in range(self.nb_trials):
sim = ccm.simulate(sim_prm, dmts = True, cue_timings = [self.t_stim], Itrans_duration = self.stim_duration, reject = reject, distractor = distractor, distractor_amplitude = distractor_amplitude, distractor_timing = distractor_timing, distractor_duration = distractor_duration, nic_trans = nic_trans, nic_trans_amplitude = nic_trans_amplitude, nic_trans_timing = nic_trans_timing)
initial_fr = sim.traces[0].narrow(0, int((self.t_stim - 0.1)/dt), int(((self.t_stim - (self.t_stim - 0.1))/dt))) # fr over the 100 ms preceding the cue
load_fr = sim.traces[0].narrow(0, int(self.load_interval[0]/dt), int((self.load_interval[1] - self.load_interval[0])/dt))
delay_fr = sim.traces[0].narrow(0, int(self.delay_interval[0]/dt), int((self.delay_interval[1] - self.delay_interval[0])/dt))
clear_fr = sim.traces[0].narrow(0, int(self.clear_interval[0]/dt), int((self.clear_interval[1] - self.clear_interval[0])/dt))
successful_loading = False
if torch.gt(load_fr, critic_re).all() and not torch.gt(initial_fr, critic_re).any() :
self.loadings += 1
successful_loading = True
if successful_loading and torch.gt(delay_fr, critic_re).all() : self.maintenances += 1
if successful_loading and not torch.gt(clear_fr, critic_re).any() : self.clearances += 1
self.trials.append(sim)
def print_stats(self):
print('Number of trials :\t', self.nb_trials,
'\nSuccessful operations :\t', self.loadings, '\t', self.maintenances, '\t', self.clearances,
'\nRatios :\t\t', round(self.loadings/self.nb_trials, 2), '\t', round(self.maintenances/self.nb_trials, 2), '\t', round(self.clearances/self.nb_trials, 2))
def plot_trials(self, trial_indexes = 0, clear = False, save = False, save_as = None): ## FIX THE TRIAL INDEXES
xunit = 0.001 # Timesteps expressed in ms
dt = 1
fig, ax = plt.subplots()
ax.plot([dt*i for i in range(len(self.trials[trial_indexes].traces[0]))], self.trials[trial_indexes].traces[0], color = 'r')
#ax.vlines(x = [int(i/dt) for i in self.load_interval], ymin = 0, ymax = 80, color = 'o')
#ax.vlines(x = [int(i/dt) for i in self.delay_interval], ymin = 0, ymax = 80, color = 'b')
#ax.vlines(x = [int(i/dt) for i in self.clear_interval], ymin = 0, ymax = 80, color = 'g')
ax.hlines(y = self.critic[0].item(), xmin = 0, xmax = dt*len(self.trials[0].traces[0]), linestyle = 'dashed')
ax.axvspan((self.t_stim - .05)/xunit, self.load_interval[1]/xunit, facecolor = 'orange', alpha = 0.2)
ax.axvspan(self.load_interval[1]/xunit, self.delay_interval[1]/xunit, facecolor = 'b', alpha = 0.2)
if clear : ax.axvspan(self.delay_interval[1]/xunit, self.clear_interval[1]/xunit, facecolor = 'g', alpha = 0.2)
ax.set_xlim(left = int(self.t_stim/xunit/2), right = int(self.clear_interval[1]/xunit + self.t_stim/xunit/2))
ax.set_ylim(top = 90)
ax.text(self.t_stim/xunit +10 -50, 80, "Load", fontsize=12)
ax.text((self.load_interval[1] + (self.delay_interval[0] - self.load_interval[0])/2 - 0.25)/xunit +10, 80, "Delay", fontsize=12)
if clear : ax.text(self.delay_interval[1]/xunit +10, 80, "Clear", fontsize=12)
# Make the title bigger
ax.set(title = 'DMTS : example trial', xlabel = 'Time (ms)', ylabel = 'PYR firing rate (Hz)')
if save : plt.savefig(save_as, dpi = 300)
plt.show()
<file_sep>/NeuralPop.py
import numpy as np
import torch, os, math
class NeuralPop():
def __init__(self, neural_name, ccm, amplitude, sigma, tau_m, tau_adp, a_, b_, Iext, J_adp = 0, STP = None, Tref = 1, NT = 'gaba', Itrans = 0, nAChRs = None): #We can maybe think about pop size
if NT not in ('glutamate', 'gaba', 'ACh'):
raise ValueError(NT + ' is not supported. Please enter only glutamate or gaba as NT')
self.ccm = ccm
self.name = neural_name
self.NT = NT
self.A = amplitude
self.tm = tau_m # Mb time constant
self.tau_adp = tau_adp # Adaptation time constant
self.sigma = sigma
self.Iext = Iext
self.J_adp = J_adp
self.Tref = Tref
self.a_ = a_
self.b_ = b_
self.glut_synapses = []
self.gaba_synapses = []
self.div_synapses = []
self.Iadp = 0
self.fr = 0
self.sigma_buffer = sigma
self.J_adp_buffer = J_adp
self.Itrans = Itrans*100 # Only for thalamus /!\ CORRECT THIS, for now we're just adding a weight of 0.1
# Populational response function, as derived from [Papasavvas, 2015].
def __f(self, x, b, a): # Excitatory, Subtractive, Divisive.
#return .5 * ( 1. + torch.tanh( torch.as_tensor([.5 * ( (self.a_ / (1. + a)) * (x - b - self.b_) )]) ).item() ) - ( 1./(1. + torch.exp( torch.as_tensor([self.a_*self.b_/(1.+a)]) ).item() ) )
return (self.a_/(self.a_+ a))*(1/(1 + np.exp( - (self.a_ * (x - b - self.b_)))) - 1 / (1 + np.exp(self.a_*self.b_)))
# Asymptotic plateau of populational response functions, as derived from [Papasavvas, 2015]
def __K(self, a):
#return torch.exp(torch.as_tensor([self.a_*self.b_/(1.+a)])).item() / (1. + torch.exp(torch.as_tensor([self.a_*self.b_/(1.+a)])).item())
return (np.exp(self.a_*self.b_)/(1 + np.exp(self.a_*self.b_)))*(self.a_/(self.a_ + a))
def synapse(self, presynaptic, weight, q = 0, STP = None, stained = False, nic_normalization = False):
if presynaptic.NT == 'gaba':
self.gaba_synapses.append(self.Synapse(presynaptic, self, weight, q, STP, stained, nic_normalization = nic_normalization))
if q != 0 : self.div_synapses.append(self.gaba_synapses[-1]) # Storing divisive syn in a specific list saves some computation time in get_derivative()
elif presynaptic.NT in ('glutamate', 'ACh'):
self.glut_synapses.append(self.Synapse(presynaptic, self, weight, q, STP, stained, nic_normalization = nic_normalization))
#elif presynaptic.NT in ('ACh'):
#self.ach_synapses.append(self.Synapse(presynaptic, weight, q, STP))
def get_derivative(self, dt, noise = 0): # Noise has to be sampled in or before the declaration
epsp = np.sum([syn.input(dt) for syn in self.glut_synapses]) - self.Iadp + self.Iext
sub_ipsp = np.sum([syn.input(dt) for syn in self.gaba_synapses])
div_ipsp = np.sum([syn.divisive_input(dt) for syn in self.div_synapses])
self.dIadp = (dt/self.tau_adp) * ( - self.Iadp + self.fr * self.J_adp )
Ke = self.__K(div_ipsp)
self.dfr = (dt/self.tm) * ( - self.fr + (self.A*Ke - self.Tref*self.fr)*self.__f(epsp, sub_ipsp, div_ipsp) ) + Ke * np.sqrt(dt) * self.sigma * noise
if math.isnan(self.dfr):
self.dfr = 0
return self.dfr
def step(self, dt = None, noise = None, dfr_computed = False):
if not dfr_computed : self.get_derivative(dt, noise)
self.Iadp += self.dIadp
self.fr += self.dfr
def deterministic(self): # Abolishes noise until reset (for equilibria computing)
self.sigma_buffer = self.sigma
self.J_adp_buffer = self.J_adp
self.Iadp = 0
self.sigma = 0
self.J_adp = 0
# /!\ GOTTA DO IT ALSO FOR THE SYNAPSES
def reset(self):
self.adp = 0
self.fr = 0
self.Iadp = 0
self.sigma = self.sigma_buffer
self.J_adp = self.J_adp_buffer
for syn in self.gaba_synapses + self.glut_synapses : syn.D = 1
class Synapse(): # Synapse(self) ? (--> self.Synapse())
def __init__(self, presyn, postsyn, weight, q = 0, STP = None, stained = False, nic_normalization = False):
self.presyn = presyn # Presynaptic neural population
self.postsyn = postsyn
self.weight = weight
self.q = q
self.D = 1 # Synaptic efficacy
self.tauD = 10 #Arbitrary
self.STP = STP
self.stained = stained
self.nic_normalization = nic_normalization
if STP is None : self.ss2 = 1 # Steady-state of STP for infinite input current
elif STP in ('d', 'D', 'depression', 'Depression', 'STD'):
if presyn.NT in ('glutamate', 'gaba') : self.ss2 = 0.5
elif presyn.NT == 'ACh' : self.ss2 = 0
elif STP in ('f', 'F', 'facilitation', 'Facilitation', 'STF') : self.ss2 = 1.5
else :
print('Please declare a valid synaptic plasticity such as \'D\' of \'F\'')
os.exit()
#self.k = 0.5*(1-self.ss2) + 1
if STP is not None :
if presyn.name == 'pyr' and postsyn.name == 'pv' : self.k = 1.2328*0.5 +1 #1.5825
elif presyn.name == 'pyr' and postsyn.name == 'som' : self.k = 1.2328*(-0.5) +1 #0.5825
elif presyn.name == 'pv' and postsyn.name == 'pyr' : self.k = 1.5911*0.5 +1#1.5383
elif presyn.name == 'thalamus' and postsyn.name == 'pv' : self.k = 1
elif presyn.name == 'cholinergic_nuclei' : self.k = 1
else :
print('Using default k = 1 for unknown synaptic connexion...')
#print(presyn.name, postsyn.name)
self.k = 1
# In DOWN states, wpe = 0.1, wep = 0.18, wes = .053
# For PV outputs, k = rp*(1 - Dss) +1 = 1.0766*0.5 +1 = 1,5383
# For inputs from PYR to PV : k = re*0.5 +1 = 1.1650*0.5 + 1 = 1.5825.
# For inputs from Thalamus to PV : k = 1
# For inputs from PYR to SOM : k = re*(-0.5) + 1 = -0.5825 +1 = 0.5825
def input(self, dt):
if self.nic_normalization : nic_mod = 1 + 0.1*(30 - self.presyn.fr)
else : nic_mod = 1
current = (1-self.q)*(self.weight*self.presyn.fr)*self.D*nic_mod
if self.STP is not None : # else saves some computation
if not math.isnan(self.presyn.fr) : self.D += ((self.k-self.D) - self.presyn.fr*(self.D - self.ss2))*(dt/self.tauD)
else : self.D += (1-self.D)*(dt/self.tauD)
if self.stained and self.presyn.ccm.notebook != None : self.presyn.ccm.notebook.append(self.D*100)
return max(current, 0.)
def divisive_input(self, dt):
current = self.q*self.weight*self.presyn.fr*self.D
return max(current, 0.)
<file_sep>/Simulation.py
import numpy as np
from numpy import nan
import os, sys, time, torch
class Simulation():
def __init__(self, ccm, traces, stimuli, sim_prm, reject=False, info=False, plot=False, dmts = False, aborted = False, critic = torch.as_tensor([20,20,20,20])):
computer = "cpu"
self.enc = torch.float64
self.dev = torch.device(computer)
self.aborted = aborted
self.critic = critic
self.ccm = ccm
# Model parameters we're interested in
self.tau, self.tau_adp = ccm.mod_prm[0].item(), ccm.mod_prm[1].item()
self.tr = ccm.mod_prm[13].item() # Refractory time [in unit 'dt'](float).
self.Ae, self.Ap, self.As, self.Av = ccm.dof[0].item(), ccm.dof[1].item(), ccm.dof[2].item(), ccm.dof[3].item()
self.traces = traces
self.stimuli = stimuli
self.sim_prm = sim_prm
### SIMULATION PARAMETERS
self.window = sim_prm[0].item() # Stimulation window [s](float).
self.dt = sim_prm[1].item() # Time resolution [s](float).
self.atol, self.rtol = sim_prm[2].item(), sim_prm[3].item() # Absolute and relative tolerances for float comparison.
self.plot = plot
self.info = info
self.reject = reject
if torch.isnan(sim_prm[4]):
torch.manual_seed(time.time())
else:
torch.manual_seed(sim_prm[4])
self.smin = round(3 * max(self.tau, self.tau_adp) / self.dt) # Starting time for stimulation window [1](int).
self.smax = round(self.window / self.dt) # End of stimulation window [1](int).
self.N = self.smin + self.smax # Total number of time-points [1](int)
#self.usf = dof[21].item()
self.usf = ccm.mod_prm[12].item()
# Short-hand indices for tensor-based data storage [1](int)
if not ccm.two_columns : self.RE, self.RP, self.RS, self.RV, self.TT = 0, 1, 2, 3, 4
else : self.RE, self.RP, self.RS, self.RV, self.RE2, self.RS2, self.RV2, self.TT = 0, 1, 2, 3, 4, 5, 6, 7
#self.RE, self.RP, self.RS, self.RV, self.dRE, self.dRP, self.dRS, self.dRV, self.TT = 0, 1, 2, 3, 4, 5, 6, 7, 8
#self.INE_E, self.INE_P, self.INE_S, self.INE_V, self.INS_E, self.INS_P, self.INS_S, self.INS_V = 9, 10, 11, 12, 13, 14, 15, 16
#self.IND_E, self.IE_ADP = 17, 18
def postproc(self):
"""
Entries:
-------
plot = bool : option parameter (default is False) conditioning output's dimensionality.
Outputs:
-------
When plot is set to True:
tsr = torch.Tensor(size=(17, _), device=dev, dtype=enc) : data tensor storing time-evolutions of all latent variables.
stim = torch.Tensor(size=_, device=dev, dtype=enc) : data tensor storing stimuli time-events.
When plot is set to False:
tsr = torch.Tensor(size=(9, _), device=dev, dtype=enc) : data tensor storing time-evolutions of neural populations' rates and their derivatives.
"""
def med(t):
if torch.numel(t) == 0:
return 0.
else:
return torch.median(t).item()
if self.aborted :
return torch.as_tensor([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan], device=self.dev, dtype=self.enc)
# Sorting neural activities wrt to H/L states #
###############################################
tsr_ = self.traces.narrow(1, self.smin, self.smax-self.smin) # We get rid of neural traces outside our simulation window's scope
mask_he = torch.gt(tsr_[self.RE,:], self.critic[0].item()) # Boolean vector corresponding to each PYR fr value being above (True) or below (False) critical point
mask_le = ~ mask_he
# Statistics of H- & L- state durations (means H & L, mode H)
h_chunks = []
l_chunks = []
h_terminated = mask_he[0]
l_terminated = ~ h_terminated
h_length = 0
l_length = 0
for k in mask_he:
if k:
if l_terminated :
l_chunks.append(l_length*self.dt)
l_length = 0
l_terminated = False
h_length += 1
h_terminated = True
else :
if h_terminated :
h_chunks.append(h_length*self.dt)
h_length = 0
h_terminated = False
l_length += 1
l_terminated = True
if mask_he[-1] and len(h_chunks) == 0 : h_chunks.append(h_length*self.dt)
elif not mask_he[-1] and len(l_chunks) == 0 : l_chunks.append(l_length*self.dt) # We don't consider last chunks unless unique
h_hist = np.histogram(h_chunks, bins = [0.25*i for i in range(40)])
h_mode_duration = h_hist[1][:-1][h_hist[0] == max(h_hist[0])]
h_mode_duration = h_mode_duration[0]
h_nb = len(h_chunks) # Nb of H-states
l_nb = len(l_chunks)
if h_nb != 0 : md_he = np.mean(h_chunks)
else : md_he = nan
if l_nb != 0 : md_le = np.mean(l_chunks)
else : md_le = nan
mhe = med(tsr_[self.RE][mask_he]) # Median PYR H-state FR
mle = med(tsr_[self.RE][mask_le])
if self.ccm.two_columns :
mhe2 = med(tsr_[self.RE2][mask_he])
mle2 = med(tsr_[self.RE2][mask_le])
if self.reject and np.isclose(md_he, 0., atol=self.atol, rtol=self.rtol):
if self.info : print('\n Simulated dynamics never reached high activity state.')
return torch.as_tensor([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan], device=self.dev, dtype=self.enc)
if self.reject and np.isclose(md_le, 0., atol=self.atol, rtol=self.rtol):
if self.info: print('\n Simulated dynamics never reached low activity state.')
return torch.as_tensor([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan], device=self.dev, dtype=self.enc)
#mask_hp, mask_hs, mask_hv = torch.gt(tsr_[self.RP,:], self.critic[1].item()), torch.gt(tsr_[self.RS,:], self.critic[2].item()), torch.gt(tsr_[self.RV,:], self.critic[3].item())
#mhp, mhs, mhv = med(tsr_[self.RP][mask_hp]), med(tsr_[self.RS][mask_hs]), med(tsr_[self.RV][mask_hv])
#mask_lp, mask_ls, mask_lv = torch.le(tsr_[self.RP,:], self.critic[1].item()), torch.le(tsr_[self.RS,:], self.critic[2].item()), torch.le(tsr_[self.RV,:], self.critic[3].item())
'''
# Median activities in H/L states
me, mle = med(tsr_[self.RE,:]), med(tsr_[self.RE][mask_le])
mp, mlp = med(tsr_[self.RP,:]), med(tsr_[self.RP][mask_lp])
ms, mls = med(tsr_[self.RS,:]), med(tsr_[self.RS][mask_ls])
mv, mlv = med(tsr_[self.RV,:]), med(tsr_[self.RV][mask_lv])
'''
# Median activities in H/L states
mhp, mlp = med(tsr_[self.RP,mask_he]), med(tsr_[self.RP][mask_le])
mhs, mls = med(tsr_[self.RS,mask_he]), med(tsr_[self.RS][mask_le])
mhv, mlv = med(tsr_[self.RV,mask_he]), med(tsr_[self.RV][mask_le])
if self.ccm.two_columns :
mhs2, mls2 = med(tsr_[self.RS2,mask_he]), med(tsr_[self.RS2][mask_le])
mhv2, mlv2 = med(tsr_[self.RV2,mask_he]), med(tsr_[self.RV2][mask_le])
# Reject if saturation
if self.reject and not all(activity < .45 for activity in [mhe / self.Ae, mhp / self.Ap, mhs / self.As, mhv/self.Av]) :
if self.info: print('\n Simulation aborted due to saturated dynamics.')
return torch.as_tensor([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan], device=self.dev, dtype=self.enc)
# Summary statistics of simulated data
# return torch.as_tensor([me, mp, ms, mv, mle, mlp, mls, mlv, mhe, mhp, mhs, mhv, md_le, md_he, h_mode_duration, l_nb, h_nb], device=self.dev, dtype=self.enc)
if not self.ccm.two_columns : return torch.as_tensor([mle, mlp, mls, mlv, mhe, mhp, mhs, mhv, md_le, md_he, h_mode_duration], device=self.dev, dtype=self.enc)
else : return torch.as_tensor([mle, mlp, mls, mlv, mle2, mls2, mlv2, mhe, mhp, mhs, mhv, mhe2, mhs2, mhv2], device=self.dev, dtype=self.enc)
def plot(self):
pass
<file_sep>/README.txt
############
# ABSTRACT #
############
This project corresponds to a research work performed at the Laboratoy of Cognitive and Computational Neuroscience (LNC2) of the Ecole Normale Supérieure of Paris, in the Team Mathematics of Neural Circuits of Pr. <NAME>.
The corresponding thesis is included in the folder.
###########
# SCRIPTS #
###########
This code is almost entirely object-oriented. The four important classes are :
-----------------------------------------------------------------------------------------------------
* NeuralPop.py : Stands for a Neural Population, which also includes the nested class Synapse. This class functions as an input-output object which can be interconnected with other Neural Populations.
* CCM.py : Canonical Cortical Model, this class stands for a model of supragranular prefrontal circuitry. It uses interconnected Neural Populations and generates (and stores) Simulations.
* Simulation.py : Recording of simulated neural traces over time. Its postproc function allows to return the corresponding summary statistics.
* DMTS.py : The Delayed Match-To-Sample task, it uses CCMs and generates Simulations according to defined task parameters.
-----------------------------------------------------------------------------------------------------
Most of the heavy computations (i.e., simulations) were performed on the parallel computing cluster of the LNC2, "Frontex". The cluster runs on functions defined on the following scripts :
-----------------------------------------------------------------------------------------------------
* dmts_frontex.py
* helper_frontex.py : These two scripts generate simulations for DMTS analysis
* infer_frontex.py : For simulating data with random models for further inference
-----------------------------------------------------------------------------------------------------
Finally, the repository includes the following Jupyter Notebooks :
-----------------------------------------------------------------------------------------------------
* DMTS_analysis.ipynb Analysis of DMTS simulations
* infer_on_presim_data.ipynb Perform Approximate Bayesian Computation
* div_modulation.ipynb Study of neural subpopulation response functions
-----------------------------------------------------------------------------------------------------
########
# DATA #
########
Simulated output data is stored in the brand_new_data and inference_data repositories
| 622df8cadb66c59dce702d1e03d81b17db16d08e | [
"Markdown",
"Python",
"Text"
] | 9 | Python | EliasElOtmani/wm_nachrs | ee04e713bc17b2eae18764abac152519e6a0b09c | 9a6cac068c55fd85358d4c43a57f3592464ba750 |
refs/heads/master | <file_sep>use std::path::Path;
use libc::{c_char, dev_t};
use crate::{Device, DeviceType, FromRaw, FromRawWithContext};
/// A libudev context.
pub struct Context {
udev: *mut crate::ffi::udev
}
impl Clone for Context {
fn clone(&self) -> Context {
Context {
udev: unsafe { crate::ffi::udev_ref(self.udev) }
}
}
}
impl Drop for Context {
fn drop(&mut self) {
unsafe {
crate::ffi::udev_unref(self.udev);
}
}
}
as_ffi!(Context, udev, crate::ffi::udev);
impl FromRaw<crate::ffi::udev> for Context {
unsafe fn from_raw(ptr: *mut crate::ffi::udev) -> Context {
Context {
udev: ptr,
}
}
}
impl Context {
/// Creates a new context.
pub fn new() -> crate::Result<Self> {
let ptr = try_alloc!(unsafe { crate::ffi::udev_new() });
Ok(unsafe { Context::from_raw(ptr) })
}
/// Creates a device for a given syspath.
///
/// The `syspath` parameter should be a path to the device file within the `sysfs` file system,
/// e.g., `/sys/devices/virtual/tty/tty0`.
pub fn device_from_syspath(&self, syspath: &Path) -> crate::Result<Device> {
let syspath = crate::util::os_str_to_cstring(syspath)?;
let ptr = try_alloc!(unsafe {
crate::ffi::udev_device_new_from_syspath(self.udev, syspath.as_ptr())
});
Ok(unsafe { Device::from_raw(self, ptr) })
}
/// Creates a device for a given device type and number.
pub fn device_from_devnum(&self, dev_type: DeviceType, dev_num: dev_t) -> crate::Result<Device> {
let ptr = try_alloc!(unsafe {
crate::ffi::udev_device_new_from_devnum(self.udev, dev_type as u8 as c_char, dev_num)
});
Ok(unsafe { Device::from_raw(self, ptr) })
}
/// Creates a device from a given subsystem and sysname.
pub fn device_from_subsystem_sysname(&self, subsystem: &Path, syspath: &Path) -> crate::Result<Device> {
let subsystem = crate::util::os_str_to_cstring(subsystem)?;
let syspath = crate::util::os_str_to_cstring(syspath)?;
let ptr = try_alloc!(unsafe {
crate::ffi::udev_device_new_from_subsystem_sysname(self.udev, subsystem.as_ptr(), syspath.as_ptr())
});
Ok(unsafe { Device::from_raw(self, ptr) })
}
/// Creates a device from a given device id.
///
/// The device id should be in one of these formats:
///
/// - `b8:2` - block device major:minor
/// - `c128:1` - char device major:minor
/// - `n3` - network device ifindex
/// - `+sound:card29` - kernel driver core subsystem:device name
pub fn device_from_device_id(&self, device_id: &Path) -> crate::Result<Device> {
let device_id = crate::util::os_str_to_cstring(device_id)?;
let ptr = try_alloc!(unsafe {
crate::ffi::udev_device_new_from_device_id(self.udev, device_id.as_ptr())
});
Ok(unsafe { Device::from_raw(self, ptr) })
}
/// Creates a device from the current environment (see environ(7)).
///
/// Each key-value pair is interpreted in the same way as if it was received in an uevent
/// (see udev_monitor_receive_device(3)). The keys DEVPATH, SUBSYSTEM, ACTION, and SEQNUM are mandatory.
pub fn device_from_environment(&self) -> crate::Result<Device> {
let ptr = try_alloc!(unsafe {
crate::ffi::udev_device_new_from_environment(self.udev)
});
Ok(unsafe { Device::from_raw(self, ptr) })
}
}
| f7563dfd457dbc3bfa50de8173c58744fc0d539d | [
"Rust"
] | 1 | Rust | a1ien/udev-rs | fc123dc463796e59a1863246b952ea005959bee1 | 11fdfc8b8956c02238f74ba9c3fb8acd68df96a3 |
refs/heads/master | <file_sep>#!/bin/sh
# template out all the config files using env vars
sed -i 's/right=.*/right='$VPN_SERVER_IPV4'/' /etc/ipsec.conf
echo ': PSK "'$VPN_PSK'"' > /etc/ipsec.secrets
sed -i 's/lns = .*/lns = '$VPN_SERVER_IPV4'/' /etc/xl2tpd/xl2tpd.conf
sed -i 's/name .*/name '$VPN_USERNAME'/' /etc/ppp/options.l2tpd.client
sed -i 's/password .*/password '$VPN_PASSWORD'/' /etc/ppp/options.l2tpd.client
# startup ipsec tunnel
ipsec initnss
sleep 1
ipsec pluto --stderrlog --config /etc/ipsec.conf
sleep 5
#ipsec setup start
#sleep 1
#ipsec auto --add L2TP-PSK
#sleep 1
ipsec auto --up L2TP-PSK
sleep 3
ipsec --status
sleep 3
# startup xl2tpd ppp daemon then send it a connect command
(sleep 7 && echo "c myVPN" > /var/run/xl2tpd/l2tp-control) & \
(echo "wait start ss,modify route\n" && sleep 10 && \
route add -host $VPN_SERVER_IPV4 gw 172.17.0.1 dev eth0 && \
route del default && \
route add default gw 1.0.0.1 && \
echo "`sed 's/nameserver.*/nameserver 1.0.0.1/g' /etc/resolv.conf`" > /etc/resolv.conf && \
echo "route ready\n" && \
/usr/bin/ssserver -k ${SS_PASSWORD:-"<PASSWORD>"} -p ${SS_SERVER_PORT:-"8388"} -m ${SS_METHOD:-"aes-256-cfb"} && \
iptables -I INPUT -p tcp --dport ${SS_SERVER_PORT:-"8388"} -j ACCEPT
) & \
exec /usr/sbin/xl2tpd -p /var/run/xl2tpd.pid -c /etc/xl2tpd/xl2tpd.conf -C /var/run/xl2tpd/l2tp-control -D<file_sep>当前项目将l2tp-ipsec代理转换为shadowsocks代理,如果你不想vpn全局代理网络请求,那么这个项目适合你
1. #### 构建容器
```shell
docker build -t anynone/l2tp-ipsec-to-shadowsocks:1.0 .
```
2. #### 环境变量
- VPN_SERVER_IPV4 l2tp-ipsec代理地址
- VPN_PSK psk密码
- VPN_USERNAME vpn用户名
- VPN_PASSWORD <PASSWORD>
- SS_PASSWORD ss服务密码,默认<PASSWORD>
- SS_SERVER_PORT ss服务端口,默认8388
- SS_METHOD ss通信加密方式,默认aes-256-cfb
3. #### 启动
```bash
docker run --rm -it --privileged \
-host \ ### 使用本机网络,端口绑定自动映射
-e VPN_SERVER_IPV4='请填写' \
-e VPN_PSK='请填写' \
-e VPN_USERNAME='请填写' \
-e VPN_PASSWORD='请填写' \
-e SS_PASSWORD='请填写' \
-e SS_SERVER_PORT='8388' \
anynone/l2tp-ipsec-to-shadowsocks:1.0
```
4. 连接
如果是host网络,使用ss连接本机端口即可,如果非host网络, docker inspect 容器id查看容器地址,或绑定宿主机端口<file_sep>FROM ubergarm/l2tp-ipsec-vpn-client
COPY startup.sh /
RUN chmod +x /startup.sh && \
apk update \
&& apk add py-pip \
&& pip install shadowsocks
| 0179886b3d4d21efb065b6dbf1139a62ff30cc6d | [
"Markdown",
"Dockerfile",
"Shell"
] | 3 | Shell | anynone/l2tp-ipsec-to-shadowsocks | 629894867d4ffc9e4d1b4a00401f6ef4b3421fdf | 1d819e1fc81fc9fca8842e06ceee88f9ee44f2d4 |
refs/heads/master | <repo_name>zailchen/Advanced-ML<file_sep>/CNN_original_trial.py
# -*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
import random
import pickle
import os
from sklearn.metrics import roc_auc_score, f1_score
class CCNN(object):
def __init__(self, image_size, num_labels, num_channels, num_hidden,
num_filters, learning_rate, keep_prob):
# Set hyper-parameters
self.image_size = image_size
self.num_labels = num_labels
self.num_channels = num_channels
self.embed_size = image_size
self.num_hidden = num_hidden
self.num_filters = num_filters
self.learning_rate = learning_rate
self.keep_prob = keep_prob
# Input placeholders
self.train_X = tf.placeholder(tf.float32, shape=(None, self.image_size, self.image_size, self.num_channels))
self.train_y = tf.placeholder(tf.float32, shape=(None, self.num_labels))
self.is_training = tf.placeholder(tf.bool)
self.computation_graph()
self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self.logits, labels = self.train_y))
self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
self.eval()
# summaries for loss and acc
tf.summary.scalar('loss', self.loss)
tf.summary.scalar('accuracy', self.acc)
self.summary_op = tf.summary.merge_all()
def computation_graph(self):
conv1 = tf.layers.conv2d(self.train_X, filters = self.num_filters, kernel_size = [5,5],
strides = (1, 1), padding = 'valid', data_format = 'channels_last', activation = tf.nn.relu)
dropout1 = tf.layers.dropout(conv1, rate = self.keep_prob, training = self.is_training)
#conv2 = tf.layers.conv2d(dropout1, filters = self.num_filters, kernel_size = [self.embed_size,1],
# strides = (1, 1), padding = 'valid', data_format = 'channels_last', activation = tf.nn.relu)
#dropout2 = tf.layers.dropout(conv2,rate = self.keep_prob, training = self.is_training)
flatten = tf.layers.flatten(dropout1)
#hidden = tf.layers.dense(flatten, self.num_hidden)
dropout3 = tf.layers.dropout(flatten, rate = self.keep_prob, training = self.is_training)
self.logits = tf.layers.dense(dropout3, self.num_labels)
self.pred = tf.nn.softmax(self.logits)
def eval(self):
# Compute accuracies
correct_pred = tf.equal(tf.argmax(self.pred, 1),tf.argmax(self.train_y, 1))
self.acc = tf.reduce_mean(tf.cast(correct_pred, "float"))
def run_train_step(self, sess, batch_X, batch_y):
pred, loss, opt, acc, summary = sess.run([self.pred, self.loss, self.optimizer, self.acc, self.summary_op],
feed_dict = {self.train_X: batch_X,
self.train_y: batch_y,
self.is_training: True})
return pred, loss, opt, acc, summary
def run_test_step(self, sess, batch_X, batch_y):
pred, acc = sess.run([self.pred, self.acc],
feed_dict = {self.train_X: batch_X,
self.train_y: batch_y,
self.is_training: False})
return pred, acc
class CVSolver(object):
def __init__(self, numROI):
self.image_size = numROI
self.num_labels = 2
self.num_channels = 1
self.num_hidden = 64
self.num_filters = 16
self.learning_rate = 0.0001
self.batch_size = 20
self.epoch_num = 50
self.keep_prob = 0.6
def run(self, X_train, y_train, X_valid, y_valid, k):
# Convert output to one-hot encoding
def to_softmax(n_classes, y):
one_hot_y = [0.0] * n_classes
one_hot_y[int(y)] = 1.0
return one_hot_y
y_train = np.array([to_softmax(self.num_labels, y) for y in y_train])
y_valid = np.array([to_softmax(self.num_labels, y) for y in y_valid])
# Convert feature matrix into channel form
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], X_train.shape[2], self.num_channels))
X_valid = np.reshape(X_valid, (X_valid.shape[0], X_valid.shape[1], X_valid.shape[2], self.num_channels))
tf.reset_default_graph()
with tf.Session() as sess:
model = CCNN(self.image_size, self.num_labels, self.num_channels,
self.num_hidden, self.num_filters, self.learning_rate, self.keep_prob)
#summary_writer = tf.summary.FileWriter(self.summary_dir, self.sess.graph)
#self.saver = tf.train.Saver(tf.global_variables())
sess.run(tf.global_variables_initializer())
# Start training
print("Start training ==========")
best_acc = 0.0
best_AUC = 0.0
best_f1 = 0.0
last_epoch = 0
global_step = 0
for epoch in range(self.epoch_num):
# randomly shuffle data
index = np.arange(X_train.shape[0])
random.shuffle(index)
X_train = X_train[index,:,:]
y_train = y_train[index]
# Generate train batches
batches = len(X_train) // self.batch_size
for ib in range(batches):
global_step += 1
# Compute start and end of batch from training set data array
from_i = ib * self.batch_size
to_i = (ib + 1) * self.batch_size
# Select current batch
batch_X, batch_y = X_train[from_i:to_i], y_train[from_i:to_i]
# exclude cases that are all 1 or all 0
if 0 in np.sum(batch_y, axis=0):
continue
# Run optimization and retrieve training accuracy, AUC, F1
train_pred, train_loss, _, train_acc, _ = model.run_train_step(sess, batch_X, batch_y)
#self.summary_writer.add_summary(train_summary, global_step)
train_AUC = roc_auc_score(np.argmax(batch_y, 1), train_pred[:,1])
train_f1 = f1_score(np.argmax(batch_y, 1), np.argmax(train_pred, 1))
# Compute validation accuracy, AUC, F1
valid_pred, valid_acc = model.run_test_step(sess, X_valid, y_valid)
valid_AUC = roc_auc_score(np.argmax(y_valid, 1), valid_pred[:,1])
valid_f1 = f1_score(np.argmax(y_valid, 1), np.argmax(valid_pred, 1))
print("Fold: %d, Epoch: %d, train_loss: %.4f" % (k, epoch, train_loss))
print("train_acc: %.4f, train_AUC: %.4f, train_f1: %.4f" % (train_acc, train_AUC, train_f1))
print("valid_acc: %.4f, valid_AUC: %.4f, valid_f1: %.4f" % (valid_acc, valid_AUC, valid_f1))
# Save model if validation accuracy is larger than previous one
if sum([valid_acc > best_acc, valid_AUC > best_AUC, valid_f1 > best_f1]) >= 2:
print('saving better =====================')
best_acc = valid_acc
best_AUC = valid_AUC
best_f1 = valid_f1
last_epoch = epoch
#checkpoint_path = self.model_dir + '_model' + '.ckpt'
#self.saver.save(self.sess, checkpoint_path)
#print("model has been saved to %s" % (checkpoint_path))
return best_acc, best_AUC, best_f1, last_epoch
class TestSolver(CVSolver):
def __init__(self, numROI, epoch_num, model_dir, summary_dir):
super(TestSolver, self).__init__(numROI)
self.epoch_num = 100
self.model_dir = model_dir
self.summary_dir = summary_dir
if not os.path.exists(self.summary_dir):
os.mkdir(self.summary_dir)
def run(self, X_train, y_train, X_test, y_test):
# Convert output to one-hot encoding
def to_softmax(n_classes, y):
one_hot_y = [0.0] * n_classes
one_hot_y[int(y)] = 1.0
return one_hot_y
y_train = np.array([to_softmax(self.num_labels, y) for y in y_train])
y_test = np.array([to_softmax(self.num_labels, y) for y in y_test])
# Convert feature matrix into channel form
X_train = np.reshape(X_train, (X_train.shape[0], X_train.shape[1], X_train.shape[2], self.num_channels))
X_test = np.reshape(X_test, (X_test.shape[0], X_test.shape[1], X_test.shape[2], self.num_channels))
tf.reset_default_graph()
with tf.Session() as sess:
model = CCNN(self.image_size, self.num_labels, self.num_channels,
self.num_hidden, self.num_filters, self.learning_rate, self.keep_prob)
summary_writer = tf.summary.FileWriter(self.summary_dir, sess.graph)
saver = tf.train.Saver(tf.global_variables())
sess.run(tf.global_variables_initializer())
# Start training
global_step = 0
for epoch in range(self.epoch_num):
# randomly shuffle data
index = np.arange(X_train.shape[0])
random.shuffle(index)
X_train = X_train[index,:,:]
y_train = y_train[index]
# Generate train batches
batches = len(X_train) // self.batch_size
for ib in range(batches):
global_step += 1
# Compute start and end of batch from training set data array
from_i = ib * self.batch_size
to_i = (ib + 1) * self.batch_size
# Select current batch
batch_X, batch_y = X_train[from_i:to_i], y_train[from_i:to_i]
# exclude case that are all 1 or all 0
if 0 in np.sum(batch_y, axis=0):
continue
# Run optimization and retrieve training accuracy and AUC score
train_pred, train_loss, _, train_acc, train_summary = model.run_train_step(sess, batch_X, batch_y)
summary_writer.add_summary(train_summary, global_step)
train_AUC = roc_auc_score(np.argmax(batch_y, 1), train_pred[:,1])
train_f1 = f1_score(np.argmax(batch_y, 1), np.argmax(train_pred, 1))
# Compute test accuracy and AUC
test_pred, test_acc = model.run_test_step(sess, X_test, y_test)
test_AUC = roc_auc_score(np.argmax(y_test, 1), test_pred[:,1])
test_f1 = f1_score(np.argmax(y_test, 1), np.argmax(test_pred, 1))
print("Epoch: %d, train_loss: %.4f" % (epoch, train_loss))
print("train_acc: %.4f, train_AUC: %.4f, train_f1: %.4f" % (train_acc, train_AUC, train_f1))
print("test_acc: %.4f, test_AUC: %.4f, test_f1: %.4f" % (test_acc, test_AUC, test_f1))
# Save model
checkpoint_path = self.model_dir + '_model' + '.ckpt'
saver.save(sess, checkpoint_path)
print("model has been saved to %s" % (checkpoint_path))
return test_acc, test_AUC, test_f1
def split(matrix, labels, ratio = 0.8, seed=None):
n = matrix.shape[0]
index = np.arange(n)
if seed:
random.seed(seed)
random.shuffle(index)
train_id = index[:int(n*ratio)]
valid_id = index[int(n*ratio):]
X_train = matrix[train_id,:,:]
y_train = labels[train_id]
X_valid = matrix[valid_id,:,:]
y_valid = labels[valid_id]
return X_train, y_train, X_valid, y_valid
if __name__ == "__main__":
K = 5
valid_ratio = 0.8
model_dir = './model/CNN-1'
summary_dir = './summary/CNN-1'
fmri_feature = ['basc064','basc122','basc197','craddock_scorr_mean','harvard_oxford_cort_prob_2mm','msdl','power_2011']
with open('data/train/2D/' + fmri_feature[3] + '_corr_2d.npy', 'rb') as f:
matrix_train = np.load(f)
with open('data/y_train.pkl', 'rb') as f:
label_train = pickle.load(f)
with open('data/test/2D/' + fmri_feature[3] + '_corr_2d.npy', 'rb') as f:
X_test = np.load(f)
with open('data/y_test.pkl', 'rb') as f:
y_test = pickle.load(f)
acc = np.zeros(K)
AUC = np.zeros(K)
f1 = np.zeros(K)
epoch = np.zeros(K)
for k in range(K):
X_train, y_train, X_valid, y_valid = split(matrix_train, label_train, valid_ratio)
cv_solver = CVSolver(X_train.shape[1])
acc[k], AUC[k], f1[k], epoch[k] = cv_solver.run(X_train, y_train, X_valid, y_valid, k)
print('CV results =====================')
print('acc:',acc)
print('AUC:',AUC)
print('F1:',f1)
print('epoch:',epoch)
print('valid_acc:',np.mean(acc),'valid_AUC:',np.mean(AUC),'valid_f1:',np.mean(f1),'mean_epoch:',np.mean(epoch))
'''
epoch = 81
print('Testing ========================')
test_solver = TestSolver(matrix_train.shape[1], int(np.mean(epoch)), model_dir, summary_dir)
test_acc, test_AUC, test_f1 = test_solver.run(matrix_train, label_train, X_test, y_test)
print('test_acc:',test_acc,'test_AUC:',test_AUC,'test_f1:',test_f1)
'''
<file_sep>/FeatureExtractor_dtw.py
import numpy as np
import pandas as pd
import time
import pickle
from multiprocessing import Pool
from functools import partial
from nilearn.signal import clean
from problem import get_train_data
# ref: https://github.com/MRegina/DTW_for_fMRI
def _load_fmri_motion_correction(fmri_filenames, fmri_motions):
"""
load frmi files with correction to confounding factor 'fmri_motions'
PARAMETERS:
fmri_filenames - eg. relative addresses from data_train['fmri_msdl'], one column per input
fmri_motions - the txt version confounding factor data_train['fmri_motions']
RETURNS:
fmri - list of standardized + confounding factor removed fmri data
"""
fmri = []
for (i, j) in zip(fmri_filenames, fmri_motions):
x = pd.read_csv(i, header=None).values
y = np.loadtxt(j)
fmri.append(clean(x, detrend=False, standardize=True, confounds=y))
return fmri
def calc_dist(s1, s2, method, w=None):
"""
calculate correlation/distance between time-series
*TODO: should change dissimilarity to similarity (standard measure)
PARAMETERS:
s1, s2 - two time-series, should have same length
method - choose from 'corr', 'dtw_dist' and 'dtw_path_len'
w - warping window for DTW method, if method == 'corr', need not input
RETURNS:
The distance/correlation between s1 and s2
"""
### Traditional Correlation coefficient
if method == 'corr':
# np.correlate --> cross-correlation
# np.corrcoef --> pearson correlation
return np.corrcoef(s1, s2)[0,1]
### Dynamic Time Warping distance & Warping path length
# A so called edit distance, which means that it measures the “cost” of transforming one time-series to the other one.
if method.startswith('dtw'):
n = len(s1)
m = len(s2)
assert n == m
# allocate DTW matrix and fill it with large values
DTW = np.ones([n + 1, m + 1]) * float("inf")
# set warping window size
if w == None:
raise ValueError('No warping window length!')
w = max(w, abs(n - m))
DTW[0, 0] = 0
# precalculate the squared difference between each time-series element pair
cost = np.square(np.transpose(np.tile(s1, [n, 1])) - np.tile(s2, [m, 1]))
# fill the DTW matrix
for i in range(n):
for j in range(max(0, i - w), min(m, i + w)):
DTW[i + 1, j + 1] = cost[i, j] + np.min([DTW[i, j + 1],
DTW[i + 1, j],
DTW[i, j]])
if method == 'dtw_dist' or method == 'dtw_all':
# obtain Euclidean distance
dtw_dist = np.sqrt(DTW[-1, -1])
if method == 'dtw_path_len' or method == 'dtw_all':
# obtain the optimal path
path = [[n-1, m-1]]
i = n-1
j = m-1
while i > 0 or j > 0:
if i == 0:
j -= 1
elif j == 0:
i -= 1
else:
last = min(DTW[i, j], DTW[i, j+1], DTW[i+1, j])
if DTW[i, j] == last:
i -= 1
j -= 1
elif DTW[i+1, j] == last:
j -= 1
else:
i -= 1
path.append([i, j])
path_len = abs(len(path) - n)
if method == 'dtw_dist':
return dtw_dist
if method == 'dtw_path_len':
return path_len
if method == 'dtw_all':
return dtw_dist, path_len
def dist_connectome(time_series, method='corr', w=None):
"""
calculate atlas distance list for the time-series matrix
PARAMETERS:
time_series - time-series matrix of each atlas, eg. 200*39 for fmri_msdl
method - choose from 'corr', 'dtw_dist' and 'dtw_path_len'
w - warping window for DTW method, if method == 'corr', need not input
RETURNS:
distances - distance list (length: eg. 39*38/2)
"""
# reset NaNs and infs
time_series = np.nan_to_num(time_series)
distances = []
path_lengths = []
if method != 'dtw_all':
# calculate the lower triangle of the connectivity matrix
for i in range(1, time_series.shape[1]):
for j in range(0, i):
distances.append(calc_dist(time_series[:, i], time_series[:, j], method, w))
return distances
else:
for i in range(1, time_series.shape[1]):
for j in range(0, i):
dist, path_len = calc_dist(time_series[:, i], time_series[:, j], method, w)
distances.append(dist)
path_lengths.append(path_len)
return distances, path_lengths
def dist_connectomes_thread(time_series_list, method='corr', w=None):
"""
auxiliary function for multithreading
"""
if method != 'dtw_all':
return [dist_connectome(ts, method, w) for ts in time_series_list]
else:
distances = []
path_lengths = []
count = 0
for ts in time_series_list:
count += 1
print('ts_list:',count,'/',len(time_series_list))
dist, path_len = dist_connectome(ts, method, w)
distances.append(dist)
path_lengths.append(path_len)
print('out_dist',len(distances))
print('out_path_len',len(path_lengths))
return distances, path_lengths
def calculate_connectomes_thread(num_threads, time_series_list, method, w=None):
"""
calculate atlas distance list for each individual via multithreading
PARAMETERS:
num_threads - number of threads
time_series_list - list of time_series matrix, could with different time-series lengths, eg. 200*39,156*39,120*39,etc
method - choose from 'corr', 'dtw_dist' and 'dtw_path_len'
w - warping window for DTW method, if method == 'corr', need not input
RETURNS:
distance list calculated from multithreading (for 1127 individuals)
"""
# calculate the index boundaries: which time_series_list elements should be processed by which threads
boundaries = (np.ceil(len(time_series_list) / num_threads) * np.arange(0, num_threads + 1)).astype(np.int)
boundaries[-1] = min(boundaries[-1], len(time_series_list))
# create list of lists of time-series, so every thread can operate on its own list of time-series
time_series_list_for_pool = [time_series_list[boundaries[i]:boundaries[i + 1]] for i in range(num_threads)]
# create pool for parallel processing
pool = Pool(processes=num_threads)
# run DTW distance calculations parallel for the time-series lists of each thread
if method != 'dtw_all':
start = time.time()
func = partial(dist_connectomes_thread, method = method, w = w)
distances = (pool.map(func, time_series_list_for_pool))
print("--- %s seconds ---" % (time.time() - start))
return [item for sublist in distances for item in sublist]
else:
start = time.time()
print('start time')
func = partial(dist_connectomes_thread, method = method, w = w)
output = pool.map(func, time_series_list_for_pool)
print("--- %s seconds ---" % (time.time() - start))
# each thread
distances = []
path_lengths = []
for sublist in output:
# distance and path length
assert len(sublist[0]) == len(sublist[1])
for i in range(len(sublist[0])):
distances.append(sublist[0][i])
path_lengths.append(sublist[1][i])
return distances, path_lengths
if __name__ == '__main__':
data_train, labels_train = get_train_data()
#fmri_features = [col for col in data_train.columns
# if col.startswith('fmri')
# and not col.endswith('select')
# and not col.endswith('motions')]
fmri_features = ['fmri_basc122','fmri_basc197']
for feature in fmri_features:
print(feature)
ts_extracted = _load_fmri_motion_correction(data_train[feature], data_train['fmri_motions'])
#path_length_list = calculate_connectomes_thread(8, ts_extracted, 'dtw_path_len', w=10)
distance_list, path_lengths_list = calculate_connectomes_thread(8, ts_extracted, 'dtw_all', w=10)
with open('train_dtw_Dist_'+ feature +'.pkl', 'wb') as f1:
pickle.dump(np.array(distance_list), f1)
with open('train_dtw_PathLen_'+ feature +'.pkl', 'wb') as f2:
pickle.dump(np.array(path_lengths_list), f2)
<file_sep>/feature_extractor.py
import numpy as np
import pandas as pd
import pickle
from sklearn.base import BaseEstimator, TransformerMixin
from sklearn.pipeline import make_pipeline
from sklearn.preprocessing import FunctionTransformer
from nilearn.connectome import ConnectivityMeasure
from nilearn.signal import clean
def _load_fmri_motion_correction(fmri_filenames, fmri_motions):
fmri = []
for (i, j) in zip(fmri_filenames, fmri_motions):
x = pd.read_csv(i, header=None).values
y = np.loadtxt(j)
fmri.append(clean(x, detrend=False, standardize=True, confounds=y))
return np.array(fmri)
# fmri_filenames = data_test['fmri_msdl']
# fmri_motions = data_test['fmri_motions']
# fmri = _load_fmri_motion_correction(fmri_filenames, fmri_motions)
class FeatureExtractor(BaseEstimator, TransformerMixin):
def __init__(self, atlas_names='msdl', kind='correlation', vectorize=True, discard_diagonal=True):
# matrix kind ref : http://nilearn.github.io/modules/generated/nilearn.connectome.ConnectivityMeasure.html
# Example ref: http://nilearn.github.io/auto_examples/03_connectivity/plot_group_level_connectivity.html#sphx-glr-auto-examples-03-connectivity-plot-group-level-connectivity-py
# Correlation: It models the full (marginal) connectivity between pairwise ROIs. It computes individual correlation matrices
# discard_diagonal=True: We discard diagonal in correlation matrix.
# self.atlas_names = [
# 'msdl'
# ,'basc064', 'basc122', 'basc197',
# 'harvard_oxford_cort_prob_2mm', 'craddock_scorr_mean',
# 'power_2011'
# ]
self.atlas_names = atlas_names
self.transformer = dict()
self.vectorize = vectorize # vectorize = True -> connectivity matrices are reshaped into 1D arrays and only their flattened lower triangular parts are returned.
self.diagonal = discard_diagonal
self.kind = kind # try all ['correlation', 'partial correlation', 'tangent', 'covariance', 'precision']
for atlas in self.atlas_names:
self.transformer[atlas] = make_pipeline(
FunctionTransformer(func=_load_fmri_motion_correction, kw_args={'fmri_motions': None}, validate=False),
ConnectivityMeasure(kind=self.kind, vectorize=self.vectorize, discard_diagonal=self.diagonal))
# if vectorize = False, it returns 2D array. e.g. for MSDL, (1127, 39, 39)
def fit(self, X_df, y):
for atlas in self.atlas_names:
fmri_filenames = X_df['fmri_{}'.format(atlas)]
self.transformer[atlas].named_steps['functiontransformer'].set_params(
kw_args={'fmri_motions': X_df['fmri_motions']})
self.transformer[atlas].fit(fmri_filenames, y)
return self
def transform(self, X_df):
# fMRI features
X_fmri = []
if self.vectorize == True:
for atlas in self.atlas_names:
fmri_filenames = X_df['fmri_{}'.format(atlas)]
self.transformer[atlas].named_steps['functiontransformer'].set_params(
kw_args={'fmri_motions': X_df['fmri_motions']})
X_connectome = self.transformer[atlas].transform(fmri_filenames)
columns = ['connectome_{}_{}'.format(atlas, i) for i in range(X_connectome.shape[1])]
X_connectome = pd.DataFrame(data=X_connectome, index=X_df.index, columns=columns)
X_fmri.append(X_connectome)
X_fmri = pd.concat(X_fmri, axis=1)
else:
for atlas in self.atlas_names:
fmri_filenames = X_df['fmri_{}'.format(atlas)]
self.transformer[atlas].named_steps['functiontransformer'].set_params(
kw_args={'fmri_motions': X_df['fmri_motions']})
X_connectome = self.transformer[atlas].transform(fmri_filenames)
X_fmri.append(X_connectome)
return X_fmri
# fMRI data (7 atlas)
atlas_names = [
'msdl',
'basc064', 'basc122', 'basc197',
'harvard_oxford_cort_prob_2mm', 'craddock_scorr_mean',
'power_2011'
]
# save 1d and 2d features for train and test
def save_features(dataset, atlas_names):
# load data
with open('data/X_' + dataset + '.pkl', 'rb') as f:
X = pickle.load(f)
with open('data/y_' + dataset + '.pkl', 'rb') as f:
y = pickle.load(f)
# extract feature for all atlas 2D and 3D, correlation
print('calculating 1d corrs')
corr_1d_all_atlas = FeatureExtractor(atlas_names=atlas_names, kind='correlation').fit_transform(X, y)
print('calculating 2d corrs')
corr_2d_all_atlas = FeatureExtractor(atlas_names=atlas_names, kind='correlation', vectorize=False).fit_transform(X,
y)
for single_atlas in atlas_names:
print('saving atlas:', single_atlas)
# Each atlas, 1D (use lower traingular part of matrix and stretch to 1D)
corr_1d_single_atlas = corr_1d_all_atlas[
corr_1d_all_atlas.columns[corr_1d_all_atlas.columns.str.contains(single_atlas)]]
# Each atlas, 2D
corr_2d_single_atlas = corr_2d_all_atlas[atlas_names.index(single_atlas)]
# save
np.save('data/' + dataset + '/1D/' + single_atlas + '_corr_1d', corr_1d_single_atlas)
np.save('data/' + dataset + '/2D/' + single_atlas + '_corr_2d', corr_2d_single_atlas)
save_features('train', atlas_names)
save_features('test', atlas_names)
<file_sep>/ae_utils.py
#!/usr/bin/env python
import os
import re
import sys
import time
import random
import string
import multiprocessing
import pandas as pd
import numpy as np
import tensorflow as tf
from model import ae
def reset():
tf.reset_default_graph()
random.seed(19)
np.random.seed(19)
tf.set_random_seed(19)
class SafeFormat(dict):
def __missing__(self, key):
return "{" + key + "}"
def __getitem__(self, key):
if key not in self:
return self.__missing__(key)
return dict.__getitem__(self, key)
def merge_dicts(*dict_args):
result = {}
for dictionary in dict_args:
result.update(dictionary)
return result
def format_config(s, *d):
merge_dic = merge_dicts(*d)
return string.Formatter().vformat(s, [], SafeFormat(merge_dic))
def to_softmax(n_classes, classe):
sm = [0.0] * n_classes
sm[int(classe)] = 1.0
return sm
def load_ae_encoder(input_size, code_size, model_path):
model = ae(input_size, code_size)
init = tf.global_variables_initializer()
try:
with tf.Session() as sess:
sess.run(init)
saver = tf.train.Saver(model["params"], write_version=tf.train.SaverDef.V2)
if os.path.isfile(model_path):
print("Restoring", model_path)
saver.restore(sess, model_path)
params = sess.run(model["params"])
return {"W_enc": params["W_enc"], "b_enc": params["b_enc"]}
finally:
reset()
def sparsity_penalty(x, p, coeff):
p_hat = tf.reduce_mean(tf.abs(x), 0)
kl = p * tf.log(p / p_hat) + \
(1 - p) * tf.log((1 - p) / (1 - p_hat))
return coeff * tf.reduce_sum(kl)
<file_sep>/CNN_ensemble.py
# -*- coding: utf-8 -*-
# ref: https://github.com/MRegina/connectome_conv_net/blob/master/conv_net.py
import tensorflow as tf
import numpy as np
import random
import pickle
import os
from sklearn.metrics import roc_auc_score, f1_score
class CCNN(object):
'''
Connectome-CNN network
Input:
image_size: number of ROIs
num_labels: 2 in our case (0-1 classification)
num_channels: 1 in our case (only has one correlation map)
num_hidden: number of hidden cells in second last fully connected layer
num_filters: number of filters to do convolution
learning_rate: learning rate when doing optimization
'''
def __init__(self, image_size, num_labels, num_channels, num_hidden,
num_filters, learning_rate):
# Set hyper-parameters
self.image_size = image_size
self.num_labels = num_labels
self.num_channels = num_channels
self.embed_size = image_size
self.num_hidden = num_hidden
self.num_filters = num_filters
self.learning_rate = learning_rate
# Input placeholders
self.train_X = tf.placeholder(tf.float32, shape=(None, self.image_size, self.image_size, self.num_channels))
self.train_y = tf.placeholder(tf.float32, shape=(None, self.num_labels))
self.keep_prob = tf.placeholder(dtype=tf.float32)
# network weight variables: Xavier initialization for better convergence in deep layers
self.initializer = tf.contrib.layers.xavier_initializer()
self.w_conv1 = tf.get_variable('w_conv1',shape=[1, self.embed_size, self.num_channels, self.num_filters],
initializer = self.initializer)
self.b_conv1 = tf.Variable(tf.constant(0.001, shape=[self.num_filters]))
self.w_conv2 = tf.get_variable('w_conv2',shape=[self.embed_size, 1, self.num_filters, self.num_filters],
initializer = self.initializer)
self.b_conv2 = tf.Variable(tf.constant(0.001, shape=[self.num_filters]))
self.w_fc1 = tf.get_variable('w_fc1',shape=[self.num_filters, self.num_hidden],
initializer = self.initializer)
self.b_fc1 = tf.Variable(tf.constant(0.01, shape=[self.num_hidden]))
self.w_fc2 = tf.get_variable('w_fc2', shape=[self.num_hidden, self.num_labels],
initializer = self.initializer)
self.b_fc2 = tf.Variable(tf.constant(0.01, shape=[self.num_labels]))
self.computation_graph()
self.loss = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits = self.logits, labels = self.train_y))
self.optimizer = tf.train.AdamOptimizer(self.learning_rate).minimize(self.loss)
self.eval()
# summaries for loss and acc
tf.summary.scalar('loss', self.loss)
tf.summary.scalar('accuracy', self.acc)
self.summary_op = tf.summary.merge_all()
def computation_graph(self):
# 1st layer: line-by-line convolution with ReLU and dropout
conv = tf.nn.conv2d(self.train_X, self.w_conv1, [1, 1, 1, 1], padding='VALID')
hidden = tf.nn.dropout(tf.nn.relu(conv + self.b_conv1), self.keep_prob)
# 2nd layer: convolution by column with ReLU and dropout
conv = tf.nn.conv2d(hidden, self.w_conv2, [1, 1, 1, 1], padding='VALID')
hidden = tf.nn.dropout(tf.nn.relu(conv + self.b_conv2), self.keep_prob)
# 3rd layer: fully connected hidden layer with dropout and ReLU
shape = hidden.get_shape().as_list()
reshape = tf.reshape(hidden, [-1, shape[1] * shape[2] * shape[3]])
hidden = tf.nn.dropout(tf.nn.relu(tf.matmul(reshape, self.w_fc1) + self.b_fc1), self.keep_prob)
# 4th (output) layer: fully connected layer with logits as output
self.logits = tf.matmul(hidden, self.w_fc2) + self.b_fc2
self.pred = tf.nn.softmax(self.logits)
def eval(self):
# Compute accuracies
correct_pred = tf.equal(tf.argmax(self.pred, 1),tf.argmax(self.train_y, 1))
self.acc = tf.reduce_mean(tf.cast(correct_pred, "float"))
def run_train_step(self, sess, batch_X, batch_y, keep_prob):
pred, loss, opt, acc, summary = sess.run([self.pred, self.loss, self.optimizer, self.acc, self.summary_op],
feed_dict = {self.train_X: batch_X,
self.train_y: batch_y,
self.keep_prob: keep_prob})
return pred, loss, opt, acc, summary
def run_test_step(self, sess, batch_X, batch_y):
pred, acc = sess.run([self.pred, self.acc],
feed_dict = {self.train_X: batch_X,
self.train_y: batch_y,
self.keep_prob: 1.0})
return pred, acc
class CCNNSolver(object):
'''
Train, test CCNN network
'''
def __init__(self, numROI, X_train, y_train, X_valid, y_valid, X_test, y_test, model_dir, summary_dir):
self.image_size = numROI
self.num_labels = 2
self.num_channels = 1
self.num_hidden = 64
self.num_filters = 16
self.learning_rate = 0.0001
self.batch_size = 20
self.epoch_num = 200
self.keep_prob = 0.8
self.X_train = X_train
self.y_train = y_train
self.X_valid = X_valid
self.y_valid = y_valid
self.X_test = X_test
self.y_test = y_test
self.model_dir = model_dir
self.summary_dir = summary_dir
if not os.path.exists(self.summary_dir):
os.mkdir(self.summary_dir)
def run(self):
# Convert output to one-hot encoding
def to_softmax(n_classes, y):
one_hot_y = [0.0] * n_classes
one_hot_y[int(y)] = 1.0
return one_hot_y
self.y_train = np.array([to_softmax(self.num_labels, y) for y in self.y_train])
self.y_valid = np.array([to_softmax(self.num_labels, y) for y in self.y_valid])
self.y_test = np.array([to_softmax(self.num_labels, y) for y in self.y_test])
# Convert feature matrix into channel form
self.X_train = np.reshape(self.X_train, (self.X_train.shape[0], self.X_train.shape[1], self.X_train.shape[2], self.num_channels))
self.X_valid = np.reshape(self.X_valid, (self.X_valid.shape[0], self.X_valid.shape[1], self.X_valid.shape[2], self.num_channels))
self.X_test = np.reshape(self.X_test, (self.X_test.shape[0], self.X_test.shape[1], self.X_test.shape[2], self.num_channels))
tf.reset_default_graph()
with tf.Session() as self.sess:
self.model = CCNN(self.image_size, self.num_labels, self.num_channels,
self.num_hidden, self.num_filters, self.learning_rate)
self.summary_writer = tf.summary.FileWriter(self.summary_dir, self.sess.graph)
self.saver = tf.train.Saver(tf.global_variables())
self.sess.run(tf.global_variables_initializer())
# Start training
print("Start training ==========")
best_acc = 0.0
last_AUC = 0.0
last_f1 = 0.0
last_epoch = 0
last_pred = None
global_step = 0
for epoch in range(self.epoch_num):
# randomly shuffle data
index = np.arange(self.X_train.shape[0])
random.shuffle(index)
self.X_train = self.X_train[index,:,:]
self.y_train = self.y_train[index]
# Generate train batches
batches = len(self.X_train) // self.batch_size
for ib in range(batches):
global_step += 1
# Compute start and end of batch from training set data array
from_i = ib * self.batch_size
to_i = (ib + 1) * self.batch_size
# Select current batch
batch_X, batch_y = self.X_train[from_i:to_i], self.y_train[from_i:to_i]
# exclude case that are all 1 or all 0
if 0 in np.sum(batch_y, axis=0):
continue
# Run optimization and retrieve training accuracy and AUC score
train_pred, train_loss, _, train_acc, train_summary = self.model.run_train_step(self.sess, batch_X, batch_y, self.keep_prob)
self.summary_writer.add_summary(train_summary, global_step)
train_AUC = roc_auc_score(np.argmax(batch_y, 1), train_pred[:,1])
train_f1 = f1_score(np.argmax(batch_y, 1), np.argmax(train_pred, 1))
# Compute validation accuracy and AUC
valid_pred, valid_acc = self.model.run_test_step(self.sess, self.X_valid, self.y_valid)
valid_AUC = roc_auc_score(np.argmax(self.y_valid, 1), valid_pred[:,1])
valid_f1 = f1_score(np.argmax(self.y_valid, 1), np.argmax(valid_pred, 1))
# Compute test accuracy and AUC
test_pred, test_acc = self.model.run_test_step(self.sess, self.X_test, self.y_test)
test_AUC = roc_auc_score(np.argmax(self.y_test, 1), test_pred[:,1])
test_f1 = f1_score(np.argmax(self.y_test, 1), np.argmax(test_pred, 1))
print("Epoch: %d, train_loss: %.4f" % (epoch, train_loss))
print("train_acc: %.4f, valid_acc: %.4f, test_acc: %.4f" % (train_acc, valid_acc, test_acc))
print("train_AUC: %.4f, valid_AUC: %.4f, test_AUC: %.4f" % (train_AUC, valid_AUC, test_AUC))
print("train_f1: %.4f, valid_f1: %.4f, test_f1: %.4f" % (train_f1, valid_f1, test_f1))
# Save model if validation accuracy is larger than previous one
if valid_acc > best_acc:
best_acc = valid_acc
last_acc = test_acc
last_AUC = test_AUC
last_f1 = test_f1
last_epoch = epoch
last_pred = np.argmax(test_pred, 1)
last_logits = test_pred[:,1]
checkpoint_path = self.model_dir + '_model' + '.ckpt'
self.saver.save(self.sess, checkpoint_path)
print("model has been saved to %s" % (checkpoint_path))
print('Results ==============================')
print(last_acc, last_AUC, last_f1, last_epoch)
return last_logits, last_pred
def split(matrix, labels, ratio = 0.8, seed=None):
'''
function to split training and validation set
'''
n = matrix.shape[0]
index = np.arange(n)
if seed:
random.seed(seed)
random.shuffle(index)
train_id = index[:int(n*ratio)]
valid_id = index[int(n*ratio):]
X_train = matrix[train_id,:,:]
y_train = labels[train_id]
X_valid = matrix[valid_id,:,:]
y_valid = labels[valid_id]
return X_train, y_train, X_valid, y_valid
if __name__ == "__main__":
valid_ratio = 0.8
model_dir = './model/CNN-merge-'
summary_dir = './summary/CNN-merge-'
#fmri_feature = ['basc064','basc122','basc197','craddock_scorr_mean','harvard_oxford_cort_prob_2mm','msdl','power_2011']
fmri_feature = ['basc064','basc122','basc197']
with open('data/y_train.pkl', 'rb') as f:
label_train = pickle.load(f)
with open('data/y_test.pkl', 'rb') as f:
y_test = pickle.load(f)
total_logits = np.zeros((len(y_test),3))
total_pred = np.zeros((len(y_test),3))
# iteration through every fmri feature
for i in range(len(fmri_feature)):
print(fmri_feature[i])
with open('data/train/2D/' + fmri_feature[i] + '_corr_2d.npy', 'rb') as f:
matrix_train = np.load(f)
with open('data/test/2D/' + fmri_feature[i] + '_corr_2d.npy', 'rb') as f:
X_test = np.load(f)
# split train and validation
X_train, y_train, X_valid, y_valid = split(matrix_train, label_train, valid_ratio)
# set solver
solver = CCNNSolver(X_train.shape[1], X_train, y_train, X_valid, y_valid, X_test, y_test, model_dir+fmri_feature[i], summary_dir+fmri_feature[i])
# get predictions and logits under best validation accuracy
total_logits[:,i], total_pred[:,i] = solver.run()
# do majority_vote
majority_vote = [int(sum(total_pred[i,:]) >= 2) for i in range(len(y_test))]
# calculate mean logits
mean_score = [int(np.mean(total_logits[i,:]) > 0.5) for i in range(len(y_test))]
# ensemble evaluation
acc = np.mean(majority_vote == y_test)
AUC = roc_auc_score(y_test, majority_vote)
f1 = f1_score(y_test, majority_vote)
print('final acc:', acc, 'final auc:', AUC, 'final f1:', f1)
acc = np.mean(mean_score == y_test)
AUC = roc_auc_score(y_test, mean_score)
f1 = f1_score(y_test, mean_score)
print('final acc:', acc, 'final auc:', AUC, 'final f1:', f1)
<file_sep>/README.md
# STAT 5242 Advanced Machine Learning Final Project
## Columbia University Fall 2018
This repository contains python codes for the final AML project.
## Dataset
Data we used for this project is available at https://paris-saclay-cds.github.io/autism_challenge/ (only `public set` is available) and initially published for competition: Imaging-psychiatry challenge: predicting autism (IMPAC).
## Environment
See `Requirement.txt` for modules we use
## Usage
#### Preprocessing
- Data Split
`split_train_test.py` - randomly split training and test dataset, and fix for model input
- Feature Extractor
`feature_extractor.py` - extract correlation matrices for each fmri feature
`FeatureExtractor_dtw.py` - extract dtw distance for each fmri feature (not in final use)
#### Models
- Logistic Regression
`simple_LR.py` - simple logistic regression classifier
- AutoEncoder (ref: https://github.com/lsa-pucrs/acerta-abide)
`autoencoder_model.py` - network of autoencoder, including autoencoder(ae) and fully connected(nn) layer
`ae_utils.py` - preprocessing functions for autoencoder
`autoencoder_ensemble.py` - ensemble AutoEncoder classifier
`autoencoder_basc064.py` - AutoEncoder classifier using only `basc064` feature (not in final use)
`autoencoder_all.py` - AutoEncoder classsifier using all features as one time input (not in final use)
- CNN
`CNN_ensemble.py` - ensemble CNN classifier (ref: https://github.com/MRegina/connectome_conv_net)
`CNN_original_trial.py` - CNN classifier with square filters and simple network (not in final use)
`draw_cnn_our_version.py` - code to draw cnn (ref: https://github.com/gwding/draw_convnet)
## Contributors
- <NAME> ([`zc2393`])
- <NAME> ([`jc4816`])
- <NAME> ([`qh2185`])
<file_sep>/autoencoder_basc064.py
# -*- coding: utf-8 -*-
import os
import numpy as np
import pandas as pd
import pickle
import tensorflow as tf
from sklearn.metrics import roc_auc_score
from ae_utils import (format_config, sparsity_penalty, reset, to_softmax, load_ae_encoder)
from autoencoder_model import ae, nn
import random
from sklearn.model_selection import train_test_split
from scipy.stats import mode
from sklearn.metrics import confusion_matrix
import matplotlib.pyplot as plt
def run_autoencoder1(experiment,
X_train, y_train, X_valid, y_valid, X_test, y_test,
model_path, code_size=1000):
"""
Run the first autoencoder.
It takes the original data dimensionality and compresses it into `code_size`
"""
# Hyperparameters
learning_rate = 0.0001
sparse = True # Add sparsity penalty
sparse_p = 0.2
sparse_coeff = 0.5
corruption = 0.75 # Data corruption ratio for denoising
ae_enc = tf.nn.tanh # Tangent hyperbolic
ae_dec = None # Linear activation
training_iters = 100
batch_size = 64
n_classes = 2
if os.path.isfile(model_path) or \
os.path.isfile(model_path + ".meta"):
return
# Create model and add sparsity penalty (if requested)
model = ae(X_train.shape[1], code_size, corruption=corruption, enc=ae_enc, dec=ae_dec)
if sparse:
model["cost"] += sparsity_penalty(model["encode"], sparse_p, sparse_coeff)
# Use GD for optimization of model cost
optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.8).minimize(model["cost"])
# Initialize Tensorflow session
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Define model saver
saver = tf.train.Saver(model["params"], write_version=tf.train.SaverDef.V2)
# Initialize with an absurd cost for model selection
prev_costs = np.array([9999999999] * 3)
for epoch in range(training_iters):
# randomly shuffle data
index = np.arange(X_train.shape[0])
random.shuffle(index)
X_train = X_train[index,]
y_train = y_train[index]
# Break training set into batches
batches = range(len(X_train) // batch_size)
costs = np.zeros((len(batches), 3))
for ib in batches:
# Compute start and end of batch from training set data array
from_i = ib * batch_size
to_i = (ib + 1) * batch_size
# Select current batch
batch_xs, batch_ys = X_train[from_i:to_i], y_train[from_i:to_i]
# Run optimization and retrieve training cost
_, cost_train = sess.run(
[optimizer, model["cost"]],
feed_dict={
model["input"]: batch_xs
}
)
# Compute validation cost
cost_valid = sess.run(
model["cost"],
feed_dict={
model["input"]: X_valid
}
)
# Compute test cost
cost_test = sess.run(
model["cost"],
feed_dict={
model["input"]: X_test
}
)
costs[ib] = [cost_train, cost_valid, cost_test]
# Compute the average costs from all batches
costs = costs.mean(axis=0)
cost_train, cost_valid, cost_test = costs
# Pretty print training info
print(format_config(
"Exp={experiment}, Model=ae1, Iter={epoch:5d}, Cost={cost_train:.6f} {cost_valid:.6f} {cost_test:.6f}",
{
"experiment": experiment,
"epoch": epoch,
"cost_train": cost_train,
"cost_valid": cost_valid,
"cost_test": cost_test,
}
))
# Save better model if optimization achieves a lower cost
if cost_valid < prev_costs[1]:
print("Saving better model")
saver.save(sess, model_path)
prev_costs = costs
else:
print
def run_autoencoder2(experiment,
X_train, y_train, X_valid, y_valid, X_test, y_test,
model_path, prev_model_path,
code_size=600, prev_code_size=1000):
"""
Run the second autoencoder.
It takes the dimensionality from first autoencoder and compresses it into the new `code_size`
Firstly, we need to convert original data to the new projection from autoencoder 1.
"""
if os.path.isfile(model_path) or \
os.path.isfile(model_path + ".meta"):
return
# Convert training, validation and test set to the new representation
prev_model = ae(X_train.shape[1], prev_code_size,
corruption=0.0, # Disable corruption for conversion
enc=tf.nn.tanh, dec=None)
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
saver = tf.train.Saver(prev_model["params"], write_version=tf.train.SaverDef.V2)
if os.path.isfile(prev_model_path):
saver.restore(sess, prev_model_path)
X_train = sess.run(prev_model["encode"], feed_dict={prev_model["input"]: X_train})
X_valid = sess.run(prev_model["encode"], feed_dict={prev_model["input"]: X_valid})
X_test = sess.run(prev_model["encode"], feed_dict={prev_model["input"]: X_test})
del prev_model
reset()
# Hyperparameters
learning_rate = 0.002
corruption = 0.68
ae_enc = tf.nn.tanh
ae_dec = None
training_iters = 100
batch_size = 50
n_classes = 2
# Load model
model = ae(prev_code_size, code_size, corruption=corruption, enc=ae_enc, dec=ae_dec)
# Use GD for optimization of model cost
optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.9).minimize(model["cost"])
# Initialize Tensorflow session
init = tf.global_variables_initializer()
with tf.Session() as sess:
sess.run(init)
# Define model saver
saver = tf.train.Saver(model["params"], write_version=tf.train.SaverDef.V2)
# Initialize with an absurd cost for model selection
prev_costs = np.array([9999999999] * 3)
# Iterate Epochs
for epoch in range(training_iters):
# randomly shuffle data
index = np.arange(X_train.shape[0])
random.shuffle(index)
X_train = X_train[index,]
y_train = y_train[index]
# Break training set into batches
batches = range(len(X_train) // batch_size)
costs = np.zeros((len(batches), 3))
for ib in batches:
# Compute start and end of batch from training set data array
from_i = ib * batch_size
to_i = (ib + 1) * batch_size
# Select current batch
batch_xs, batch_ys = X_train[from_i:to_i], y_train[from_i:to_i]
# Run optimization and retrieve training cost
_, cost_train = sess.run(
[optimizer, model["cost"]],
feed_dict={
model["input"]: batch_xs
}
)
# Compute validation cost
cost_valid = sess.run(
model["cost"],
feed_dict={
model["input"]: X_valid
}
)
# Compute test cost
cost_test = sess.run(
model["cost"],
feed_dict={
model["input"]: X_test
}
)
costs[ib] = [cost_train, cost_valid, cost_test]
# Compute the average costs from all batches
costs = costs.mean(axis=0)
cost_train, cost_valid, cost_test = costs
# Pretty print training info
print(format_config(
"Exp={experiment}, Model=ae2, Iter={epoch:5d}, Cost={cost_train:.6f} {cost_valid:.6f} {cost_test:.6f}",
{
"experiment": experiment,
"epoch": epoch,
"cost_train": cost_train,
"cost_valid": cost_valid,
"cost_test": cost_test,
}
))
# Save better model if optimization achieves a lower cost
if cost_valid < prev_costs[1]:
print("Saving better model")
saver.save(sess, model_path)
prev_costs = costs
else:
print
def run_finetuning(experiment,
X_train, y_train, X_valid, y_valid, X_test, y_test,
model_path, prev_model_1_path, prev_model_2_path,
code_size_1=1000, code_size_2=600):
"""
Run the pre-trained NN for fine-tuning, using first and second autoencoders' weights
"""
# Hyperparameters
learning_rate = 0.0003
dropout_1 = 0.4
dropout_2 = 0.6
# initial_momentum = 0.1
# final_momentum = 0.9 # Increase momentum along epochs to avoid fluctiations
# saturate_momentum = 100
training_iters = 150
start_saving_at = 5
batch_size = 32
n_classes = 2
if os.path.isfile(model_path) or \
os.path.isfile(model_path + ".meta"):
return
# Convert output to one-hot encoding
y_train = np.array([to_softmax(n_classes, y) for y in y_train])
y_valid = np.array([to_softmax(n_classes, y) for y in y_valid])
y_test = np.array([to_softmax(n_classes, y) for y in y_test])
# Load pretrained encoder weights
ae1 = load_ae_encoder(X_train.shape[1], code_size_1, prev_model_1_path)
ae2 = load_ae_encoder(code_size_1, code_size_2, prev_model_2_path)
# Initialize NN model with the encoder weights
model = nn(X_train.shape[1], n_classes, [
{"size": code_size_1, "actv": tf.nn.tanh},
{"size": code_size_2, "actv": tf.nn.tanh},
], [
{"W": ae1["W_enc"], "b": ae1["b_enc"]},
{"W": ae2["W_enc"], "b": ae2["b_enc"]},
])
# Place GD + momentum optimizer
# model["momentum"] = tf.placeholder("float32")
optimizer = tf.train.AdamOptimizer(learning_rate, beta1=0.9).minimize(model["cost"])
# Place Adam optimizer
# optimizer = tf.train.AdamOptimizer(learning_rate).minimize(model["cost"]) # cross entropy
# Make prediction and Compute accuracies
logits = model["output"]
pred = tf.argmax(model["output"], 1)
correct_prediction = tf.equal(pred, tf.argmax(model["expected"], 1))
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float"))
# Store prediction
best_prediction = None
best_logits = None
acc_list = np.zeros((training_iters, 3))
loss_list = np.zeros((training_iters, 3))
auc_list = np.zeros((training_iters, 3))
# Initialize Tensorflow session
init = tf.group(tf.global_variables_initializer(), tf.local_variables_initializer())
with tf.Session() as sess:
sess.run(init)
# Define model saver
saver = tf.train.Saver(model["params"], write_version=tf.train.SaverDef.V2)
# Initialize with an absurd cost, accuracy, auc for model selection
best_acc = 0.0
# Iterate Epochs
for epoch in range(training_iters):
# randomly shuffle data
index = np.arange(X_train.shape[0])
random.shuffle(index)
X_train = X_train[index,]
y_train = y_train[index]
# exclude case that are all 1 or all 0
if 0 in np.sum(y_train, axis=0):
continue
# Break training set into batches
batches = range(len(X_train) // batch_size)
costs = np.zeros((len(batches), 3))
accs = np.zeros((len(batches), 3))
AUCs = np.zeros((len(batches), 3))
prediction = None
logit = None
# Compute momentum saturation
# alpha = float(epoch) / float(saturate_momentum)
# if alpha < 0.:
# alpha = 0.
# if alpha > 1.:
# alpha = 1.
# momentum = initial_momentum * (1 - alpha) + alpha * final_momentum
for ib in batches:
# Compute start and end of batch from training set data array
from_i = ib * batch_size
to_i = (ib + 1) * batch_size
# Select current batch
batch_xs, batch_ys = X_train[from_i:to_i], y_train[from_i:to_i]
if 0 in np.sum(batch_ys, axis=0):
continue
# Run optimization and retrieve training cost and accuracy
_, cost_train, acc_train, true_y, pred_y = sess.run(
[optimizer, model["cost"], accuracy, model['expected'], model['output']],
feed_dict={
model["input"]: batch_xs,
model["expected"]: batch_ys,
model["dropouts"][0]: dropout_1,
model["dropouts"][1]: dropout_2
}
)
# Compute AUC score
AUC_train = roc_auc_score(np.argmax(true_y, 1), pred_y[:, 1])
# Compute validation cost and accuracy
cost_valid, acc_valid, true_y, pred_y = sess.run(
[model["cost"], accuracy, model['expected'], model['output']],
feed_dict={
model["input"]: X_valid,
model["expected"]: y_valid,
model["dropouts"][0]: 1.0,
model["dropouts"][1]: 1.0
}
)
AUC_valid = roc_auc_score(np.argmax(true_y, 1), pred_y[:, 1])
# Compute test cost and accuracy
logit, prediction, cost_test, acc_test, true_y, pred_y = sess.run(
[logits, pred, model["cost"], accuracy, model['expected'], model['output']],
feed_dict={
model["input"]: X_test,
model["expected"]: y_test,
model["dropouts"][0]: 1.0,
model["dropouts"][1]: 1.0
}
)
AUC_test = roc_auc_score(np.argmax(true_y, 1), pred_y[:, 1])
costs[ib] = [cost_train, cost_valid, cost_test]
accs[ib] = [acc_train, acc_valid, acc_test]
AUCs[ib] = [AUC_train, AUC_valid, AUC_test]
# Compute the average costs from all batches
costs = costs.mean(axis=0)
cost_train, cost_valid, cost_test = costs
loss_list[epoch] = cost_train, cost_valid, cost_test
# Compute the average accuracy from all batches
accs = accs.mean(axis=0)
acc_train, acc_valid, acc_test = accs
acc_list[epoch] = acc_train, acc_valid, acc_test
# Compute the average AUC for all batches
AUCs = AUCs.mean(axis=0)
AUC_train, AUC_valid, AUC_test = AUCs
auc_list[epoch] = AUC_train, AUC_valid, AUC_test
# Pretty print training info
print(format_config(
"Exp={experiment}, Model=mlp, Iter={epoch:5d}, Acc={acc_train:.6f} {acc_valid:.6f} {acc_test:.6f}, \
AUC={AUC_train:.6f} {AUC_valid:.6f} {AUC_test:.6f}",
{
"experiment": experiment,
"epoch": epoch,
"acc_train": acc_train,
"acc_valid": acc_valid,
"acc_test": acc_test,
"AUC_train": AUC_train,
"AUC_valid": AUC_valid,
"AUC_test": AUC_test
}
))
# Save better model if optimization achieves a lower accuracy
# and avoid initial epochs because of the fluctuations
if acc_valid > best_acc and epoch > start_saving_at:
best_prediction = prediction
best_logits = logit
print("Saving better model")
saver.save(sess, model_path)
best_acc = acc_valid
return best_prediction, best_logits, acc_list, loss_list, auc_list
####################################
## Run Experiments
####################################
if __name__ == '__main__':
prediction = []
logits = np.zeros((230, 2))
# for feature in feature_list:
feature = 'basc064'
with open('./data/train/1D/' + feature + '_corr_1d.npy', 'rb') as f:
matrix_train = np.load(f)
with open('./data/y_train.pkl', 'rb') as f:
label_train = pickle.load(f)
with open('./data/test/1D/' + feature + '_corr_1d.npy', 'rb') as f:
X_test = np.load(f)
with open('./data/y_test.pkl', 'rb') as f:
y_test = pickle.load(f)
X_train, X_valid, y_train, y_valid = train_test_split(matrix_train, label_train, shuffle=True, test_size=0.25, random_state=10)
ae1_model_path = format_config("./model/ae_model_basc064/{experiment}_autoencoder-1.ckpt", {
"experiment": feature,
})
ae2_model_path = format_config("./model/ae_model_basc064/{experiment}_autoencoder-2.ckpt", {
"experiment": feature,
})
nn_model_path = format_config("./model/ae_model_basc064/{experiment}_mlp.ckpt", {
"experiment": feature,
})
code_size_1 = int(matrix_train.shape[1] * 0.06)
code_size_2 = int(code_size_1 * 0.5)
reset()
# Run first autoencoder
run_autoencoder1(feature,
X_train, y_train, X_valid, y_valid, X_test, y_test,
model_path=ae1_model_path,
code_size=code_size_1)
reset()
# Run second autoencoder
run_autoencoder2(feature,
X_train, y_train, X_valid, y_valid, X_test, y_test,
model_path=ae2_model_path,
prev_model_path=ae1_model_path,
prev_code_size=code_size_1,
code_size=code_size_2)
reset()
# Run multilayer NN with pre-trained autoencoders
pred, logit, acc_list, loss_list, auc_list = run_finetuning(feature,
X_train, y_train, X_valid, y_valid, X_test, y_test,
model_path=nn_model_path,
prev_model_1_path=ae1_model_path,
prev_model_2_path=ae2_model_path,
code_size_1=code_size_1,
code_size_2=code_size_2)
prediction.append(pred)
logits = logits + logit
# Computing metrics scores
predictions = np.argmax(logits, axis=1)
preds = pd.DataFrame(prediction)
y_pred = [mode(preds[i])[0][0] for i in range(len(preds.T))]
y_true = y_test
[[TN, FP], [FN, TP]] = confusion_matrix(y_true, y_pred, labels=[0, 1]).astype(float)
accuracy = (TP + TN) / (TP + TN + FP + FN)
auc = roc_auc_score(y_true, y_pred)
specificity = TN / (FP + TN)
precision = TP / (TP + FP)
sensitivity = recall = TP / (TP + FN)
fscore = 2 * TP / (2 * TP + FP + FN)
print('acc: ', accuracy)
print('auc: ', auc)
print('precision: ', precision)
print('recall: ', recall)
print('fscore: ', fscore)
# Draw plots on training and validation performance
fig = plt.figure()
plt.subplot(2,1,1)
plt.plot(acc_list.T[0])
plt.plot(acc_list.T[1])
plt.plot(acc_list.T[2])
plt.title('model accuracy')
plt.ylabel('accuracy')
plt.xlabel('epoch')
plt.legend(['train', 'valid', 'test'], loc='upper left')
plt.subplot(2,1,2)
plt.plot(loss_list.T[0])
plt.plot(loss_list.T[1])
plt.plot(loss_list.T[2])
plt.title('model loss')
plt.ylabel('loss')
plt.xlabel('epoch')
plt.legend(['train', 'valid', 'test'], loc='upper left')
plt.tight_layout()
fig
<file_sep>/simple_LR.py
import pickle
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from problem import get_train_data
data_train, labels_train = get_train_data()
# Load data
# fMRI data (3 atlas) - basc064, basc122, basc197
# Only 1D data for this analysis
# We are focus on correlation connectivity measure for this analysis.
with open('data/train/1D/msdl_corr_1d.npy', 'rb') as p_f:
train_msdl_corr = np.load(p_f)
with open('data/train/1D/basc064_corr_1d.npy', 'rb') as p_f:
train_basc064_corr = np.load(p_f)
with open('data/train/1D/basc122_corr_1d.npy', 'rb') as p_f:
train_basc122_corr = np.load(p_f)
with open('data/train/1D/basc197_corr_1d.npy', 'rb') as p_f:
train_basc197_corr = np.load(p_f)
with open('data/train/1D/craddock_scorr_mean_corr_1d.npy', 'rb') as p_f:
train_craddock_corr = np.load(p_f)
with open('data/train/1D/harvard_oxford_cort_prob_2mm_corr_1d.npy', 'rb') as p_f:
train_harvard_corr = np.load(p_f)
with open('data/train/1D/power_2011_corr_1d.npy', 'rb') as p_f:
train_power_corr = np.load(p_f)
with open('data/test/1D/msdl_corr_1d.npy', 'rb') as p_f:
test_msdl_corr = np.load(p_f)
with open('data/test/1D/basc064_corr_1d.npy', 'rb') as p_f:
test_basc064_corr = np.load(p_f)
with open('data/test/1D/basc122_corr_1d.npy', 'rb') as p_f:
test_basc122_corr = np.load(p_f)
with open('data/test/1D/basc197_corr_1d.npy', 'rb') as p_f:
test_basc197_corr = np.load(p_f)
with open('data/test/1D/craddock_scorr_mean_corr_1d.npy', 'rb') as p_f:
test_craddock_corr = np.load(p_f)
with open('data/test/1D/harvard_oxford_cort_prob_2mm_corr_1d.npy', 'rb') as p_f:
test_harvard_corr = np.load(p_f)
with open('data/test/1D/power_2011_corr_1d.npy', 'rb') as p_f:
test_power_corr = np.load(p_f)
with open('data/y_train.pkl', 'rb') as f:
label_train = pickle.load(f)
with open('data/y_test.pkl', 'rb') as f:
label_test = pickle.load(f)
X_train = np.concatenate([train_msdl_corr, train_basc064_corr, train_basc122_corr,
train_basc197_corr, train_craddock_corr, train_harvard_corr,
train_power_corr], axis=1)
y_train = label_train
X_test = np.concatenate([test_msdl_corr, test_basc064_corr, test_basc122_corr,
test_basc197_corr, test_craddock_corr, test_harvard_corr,
test_power_corr], axis=1)
y_test = label_test
# Model -- Simple Logistic Regression
from sklearn.base import BaseEstimator
from sklearn.preprocessing import StandardScaler
from sklearn.linear_model import LogisticRegression as LR
from sklearn.pipeline import make_pipeline
from sklearn.model_selection import GridSearchCV
# StandardScaler : Standardize features by removing the mean and scaling to unit variance
# refer to http://scikit-learn.org/stable/modules/generated/sklearn.preprocessing.StandardScaler.html
class Classifier(BaseEstimator):
def __init__(self):
self.params = {'logisticregression__penalty': ['l1', 'l2'],
'logisticregression__C': [0.001, 0.01, 0.05, 0.1, 0.5, 1, 10]}
self.clf = make_pipeline(StandardScaler(), LR())
self.grid = GridSearchCV(self.clf, self.params, scoring='accuracy', cv=5, verbose=1)
def fit(self, X, y):
return self.grid.fit(X, y)
def predict(self, X):
return self.grid.predict(X)
def predict_proba(self, X):
return self.grid.predict_proba(X)
# Fit
fit_all = Classifier().fit(X_train, y_train)
# Evaluation
y_pred_proba = fit_all.predict_proba(X_test)[:,1]
y_pred = fit_all.predict(X_test)
# Accuracy
from sklearn.metrics import roc_auc_score, accuracy_score, f1_score
ROC_AUC = roc_auc_score(y_test, y_pred_proba)
Accuracy = accuracy_score(y_test, y_pred)
f1 = f1_score(y_test, y_pred)
# Area Under the Curve of the Receiver Operating Characteristic (ROC-AUC)
print("ROC-AUC:", ROC_AUC, ", Accuracy=", Accuracy, ", F1 score=", f1)
<file_sep>/requirements.txt
numpy
scipy
pandas>=0.21
scikit-learn>=0.19
pickle
nilearn
matplotlib
seaborn
tensorflow
<file_sep>/split_train_test.py
# -*- coding: utf-8 -*-
import pandas as pd
import numpy as np
import random
import pickle
from problem import get_train_data, get_test_data
data_train, labels_train = get_train_data()
data_test, labels_test = get_test_data()
data_combine = pd.concat([data_train, data_test])
labels_combine = np.concatenate([labels_train, labels_test])
n = len(labels_combine)
train_ratio = 0.8
random.seed(42)
index = np.arange(n)
random.shuffle(index)
train_id = index[:int(n*0.8)]
test_id = index[int(n*0.8):]
X_train = data_combine.iloc[train_id,:]
y_train = labels_combine[train_id]
X_test = data_combine.iloc[test_id,:]
y_test = labels_combine[test_id]
with open('data/X_train.pkl', 'wb') as f:
pickle.dump(X_train, f)
with open('data/y_train.pkl', 'wb') as f:
pickle.dump(y_train, f)
with open('data/X_test.pkl', 'wb') as f:
pickle.dump(X_test, f)
with open('data/y_test.pkl', 'wb') as f:
pickle.dump(y_test, f)
| 4c10bac3e5d01d594a444ed09e846e160f5bfd21 | [
"Markdown",
"Python",
"Text"
] | 10 | Python | zailchen/Advanced-ML | 6fc4b9c3c2d6d107711bc208e9584a4780c9ae51 | 3430503c42b7a850f3c6a444f5afed32ad16ea7c |
refs/heads/main | <repo_name>kamils224/STXNext_training_program<file_sep>/api_projects/urls.py
from django.urls import path, include
from rest_framework.routers import DefaultRouter
from api_projects.views import (
ProjectViewSet,
IssueViewSet,
IssueAttachmentDelete,
IssueAttachmentCreate,
)
app_name = "api_projects"
# Create a router and register our viewsets with it.
router = DefaultRouter()
router.register(r"project", ProjectViewSet)
router.register(r"issue", IssueViewSet)
# The API URLs are now determined automatically by the router.
urlpatterns = [
path("", include(router.urls)),
path(
"attachment/", IssueAttachmentCreate.as_view(), name="issue_attachment_create"
),
path(
"attachment/<int:pk>/",
IssueAttachmentDelete.as_view(),
name="issue_attachment_delete",
),
]
<file_sep>/README.md
# STXNext_training_program
Create .env.dev file based on .env-template
Perform makemigrations:
`sudo docker-compose run app python manage.py makemigrations accounts api_projects`
Perform migration:
`sudo docker-compose run app python manage.py migrate`
Create superuser:
`sudo docker-compose run app python manage.py createsuperuser`
Run docker:
`docker-compose up` or `docker-compose up --build`
If migration errors occur, remove your database volumes and try again.
`sudo docker-compose down --rmi all --volumes`
*TODO*
<file_sep>/api_projects/models.py
import os
from django.db import models
from django.db.models.signals import post_delete, pre_delete
from django.contrib.auth import get_user_model
from django.dispatch import receiver
from stx_training_program.celery import app
from api_projects.tasks import send_issue_notification, notify_issue_deadline
User = get_user_model()
class Project(models.Model):
name = models.CharField(max_length=100)
owner = models.ForeignKey(
User, related_name="own_projects", on_delete=models.CASCADE
)
creation_date = models.DateTimeField(auto_now_add=True)
members = models.ManyToManyField(User, related_name="projects", blank=True)
def __str__(self):
return self.name
class Issue(models.Model):
def __init__(self, *args, **kwargs):
super(Issue, self).__init__(*args, **kwargs)
# save these values before update
self._original_due_date = self.due_date
self._original_assigne = self.assigne
class Status(models.TextChoices):
TODO = "todo"
IN_PROGRESS = "in progress"
REVIEW = "review"
DONE = "done"
title = models.CharField(max_length=100)
description = models.TextField(blank=True)
created_date = models.DateTimeField(auto_now_add=True)
due_date = models.DateTimeField()
status = models.CharField(
max_length=20, choices=Status.choices, default=Status.TODO
)
owner = models.ForeignKey(
User, related_name="created_issues", on_delete=models.CASCADE
)
assigne = models.ForeignKey(
User,
related_name="own_issues",
on_delete=models.SET_NULL,
blank=True,
null=True,
)
project = models.ForeignKey(
Project, related_name="issues", on_delete=models.CASCADE
)
def __str__(self):
return self.title
def save(self, *args, **kwargs):
super(Issue, self).save(*args, **kwargs)
if self._original_assigne != self.assigne:
self._perform_assigne_notification()
if self._original_due_date != self.due_date:
self._perform_deadline_notification()
def _perform_assigne_notification(self) -> str:
if self.assigne is not None:
send_issue_notification.delay(
self.assigne.email,
"New assignment",
f"You are assigned to the task {self.title}",
)
if self._original_assigne is not None:
send_issue_notification.delay(
self.assigne.email,
"Assigment is removed",
f"You were removed from task {self.title}",
)
def _perform_deadline_notification(self):
if self.assigne:
current_task, _ = DateUpdateTask.objects.get_or_create(issue=self)
if current_task.task_id is not None:
# remove previous task due to date change
app.control.revoke(
task_id=current_task.task_id, terminate=True)
subject = "Your task is not completed!"
message = f"The time for the task {self.title} is over :("
current_task.task_id = notify_issue_deadline.s(
self.pk, self.assigne.email, subject, message
).apply_async(eta=self.due_date)
current_task.save()
# Can be extended / changed as more tasks are needed
class DateUpdateTask(models.Model):
issue = models.OneToOneField(
Issue, on_delete=models.CASCADE, primary_key=True, related_name="issue_task"
)
task_id = models.CharField(max_length=50, unique=True, blank=True)
class IssueAttachment(models.Model):
file_attachment = models.FileField(upload_to="attachments/")
issue = models.ForeignKey(
Issue, on_delete=models.CASCADE, related_name="files")
def __str__(self):
return os.path.basename(self.file_attachment.name)
# Note: custom fields in Issue init causes infinite loop during cascade deletion
# Empty pre_delete signal fixes this issue...
# source: https://code.djangoproject.com/ticket/31475
@receiver(pre_delete, sender=Issue)
def clean_custom_fields(sender, instance, **kwargs):
pass
@receiver(post_delete, sender=IssueAttachment)
def issue_attachment_delete(sender, instance, **kwargs):
instance.file_attachment.delete(save=False)
<file_sep>/api_projects/views.py
from django.db.models import Q
from django.shortcuts import get_object_or_404
from rest_framework.response import Response
from rest_framework import status
from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import DestroyAPIView, CreateAPIView
from rest_framework.parsers import MultiPartParser
from rest_framework.permissions import IsAuthenticated
from rest_framework.decorators import action
from api_projects.models import Project, Issue, IssueAttachment
from api_projects.serializers import (
ProjectSerializer,
IssueSerializer,
IssueAttachmentSerializer,
)
from api_projects.permissions import (
IsOwner,
MemberReadOnly,
IsProjectMember,
)
class ProjectViewSet(ModelViewSet):
queryset = Project.objects.all()
serializer_class = ProjectSerializer
permission_classes = [IsAuthenticated, IsOwner | MemberReadOnly]
def get_queryset(self):
user = self.request.user
query = Q(owner=user) | Q(members=user)
return Project.objects.filter(query).distinct()
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class IssueViewSet(ModelViewSet):
queryset = Issue.objects.all()
serializer_class = IssueSerializer
permission_classes = [IsProjectMember]
def get_queryset(self):
user = self.request.user
query = Q(project__in=user.projects.all()) | Q(
project__in=user.own_projects.all()
)
return Issue.objects.filter(query)
def perform_create(self, serializer):
serializer.save(owner=self.request.user)
class IssueAttachmentDelete(DestroyAPIView):
queryset = IssueAttachment.objects.all()
serializer_class = IssueAttachmentSerializer
permission_classes = [IsProjectMember | IsOwner]
class IssueAttachmentCreate(CreateAPIView):
queryset = IssueAttachment.objects.all()
serializer_class = IssueAttachmentSerializer
permission_classes = [IsProjectMember | IsOwner]
parser_classes = [MultiPartParser]
<file_sep>/requirements.txt
amqp==5.0.2
appdirs==1.4.4
asgiref==3.3.1
astroid==2.4.2
autopep8==1.5.4
billiard==3.6.3.0
black==20.8b1
celery==5.0.5
certifi==2020.12.5
cffi==1.14.4
chardet==4.0.0
click==7.1.2
click-didyoumean==0.0.3
click-plugins==1.1.1
click-repl==0.1.6
coreapi==2.3.3
coreschema==0.0.4
cryptography==3.3.1
defusedxml==0.7.0rc2
Django==3.1.5
django-celery-beat==2.2.0
django-filter==2.4.0
django-sendgrid-v5==0.9.0
django-templated-mail==1.1.1
django-timezone-field==4.1.1
djangorestframework==3.12.2
djangorestframework-simplejwt==4.6.0
flake8==3.8.4
future==0.18.2
idna==2.10
isort==5.7.0
itypes==1.2.0
Jinja2==2.11.2
kombu==5.0.2
lazy-object-proxy==1.4.3
Markdown==3.3.3
MarkupSafe==1.1.1
mccabe==0.6.1
mypy-extensions==0.4.3
oauthlib==3.1.0
pathspec==0.8.1
prompt-toolkit==3.0.9
psycopg2-binary==2.8.6
pycodestyle==2.6.0
pycparser==2.20
pyflakes==2.2.0
PyJWT==2.0.0
pylint==2.6.0
python-crontab==2.5.1
python-dateutil==2.8.1
python-http-client==3.3.1
python3-openid==3.2.0
pytz==2020.5
redis==3.5.3
regex==2020.11.13
requests==2.25.1
requests-oauthlib==1.3.0
sendgrid==6.4.8
six==1.15.0
social-auth-core==4.0.3
sqlparse==0.4.1
starkbank-ecdsa==1.1.0
toml==0.10.2
typed-ast==1.4.2
typing-extensions==3.7.4.3
uritemplate==3.0.1
urllib3==1.26.2
vine==5.0.0
wcwidth==0.2.5
wrapt==1.12.1
<file_sep>/api_projects/tasks.py
from celery import shared_task
from django.apps import apps
from django.core.mail import send_mail
@shared_task
def send_issue_notification(email: str, subject: str, message: str) -> None:
send_mail(subject, message, None, recipient_list=[
email], fail_silently=False)
@shared_task
def notify_issue_deadline(pk: int, email: str, subject: str, message: str) -> None:
# to prevent circular imports
from api_projects.models import Issue
if issue := Issue.objects.filter(pk=pk).exclude(assigne=None, status=Issue.Status.DONE).first():
send_issue_notification(
email,
"Issue deadline",
f"The {issue.title} is not finished after deadline!",
)
issue.issue_task.delete()
<file_sep>/api_accounts/views.py
from django.contrib.auth import get_user_model
from django.db import transaction
from rest_framework import status
from rest_framework.generics import CreateAPIView, RetrieveAPIView
from rest_framework.permissions import AllowAny
from rest_framework.response import Response
from smtplib import SMTPException
from api_accounts.models import User
from api_accounts.serializers import (
UserRegistrationSerializer,
UserSerializer,
ActivateAccountSerializer,
)
from api_accounts.utils import send_verification_email
class UserRegistrationView(CreateAPIView):
"""
An endpoint for creating user.
"""
queryset = User.objects.all()
serializer_class = UserRegistrationSerializer
permission_classes = [AllowAny]
@transaction.atomic
def create(self, request, *args, **kwargs):
serializer = UserRegistrationSerializer(data=request.data)
serializer.is_valid(raise_exception=True)
user = serializer.save()
try:
send_verification_email(
user,
request,
subject="Training course",
message="Hello! Activate your account here:\n",
)
except (SMTPException):
return Response(status=status.HTTP_400_BAD_REQUEST)
return Response(
{"message": f"Registration successful, check your email: {user}"},
status=status.HTTP_201_CREATED,
)
class UserDetailsView(RetrieveAPIView):
"""
An endpoint for user details.
Returns data based on the currently logged user, without providing his id/pk in URL.
"""
serializer_class = UserSerializer
def get_object(self):
serializer = UserSerializer(self.request.user)
return serializer.data
class ActivateAccountView(RetrieveAPIView):
serializer_class = ActivateAccountSerializer
permission_classes = [AllowAny]
def get(self, request, format=None):
serializer = ActivateAccountSerializer(data=request.query_params)
serializer.is_valid(raise_exception=True)
user = serializer.validated_data
user.is_active = True
user.save(update_fields=["is_active"])
return Response(
{"message": "Email successfully verified!"}, status=status.HTTP_200_OK
)
<file_sep>/api_accounts/tests.py
from typing import Dict
from django.contrib.auth import get_user_model
from django.core import mail
from rest_framework import status
from rest_framework.reverse import reverse_lazy
from rest_framework.test import APITestCase
from rest_framework.response import Response
User = get_user_model()
class UserAccountTest(APITestCase):
REGISTER_URL = reverse_lazy("api_accounts:register")
OBTAIN_TOKEN_URL = reverse_lazy("api_accounts:token_obtain_pair")
USER_DETAILS_URL = reverse_lazy("api_accounts:user_details")
ACCOUNT_ACTIVATE_URL = reverse_lazy("api_accounts:activate")
def setUp(self):
self.user_data = {
"email": "<EMAIL>",
"password": "<PASSWORD>",
}
self.bad_email_data = {
"email": "bad_email.com",
"password": "<PASSWORD>",
}
def _register_user(self, user_data: Dict[str, str]) -> Response:
return self.client.post(self.REGISTER_URL, user_data, format="json")
def test_register(self):
response = self._register_user(self.user_data)
expected_obj_count = 1
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
self.assertEqual(User.objects.count(), expected_obj_count)
self.assertEqual(User.objects.get().email, self.user_data["email"])
# try to create the same user again
response = self._register_user(self.user_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(User.objects.count(), expected_obj_count)
# there should be a new message
self.assertEqual(len(mail.outbox), expected_obj_count)
def test_short_password(self):
expected_users_count = User.objects.count()
user_data = self.user_data
user_data["password"] = "123"
response = self._register_user(self.user_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(User.objects.count(), expected_users_count)
def test_bad_email_register(self):
expected_users_count = User.objects.count()
response = self._register_user(self.bad_email_data)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
self.assertEqual(User.objects.count(), expected_users_count)
def test_login(self):
self._register_user(self.user_data)
# set user as active
user = User.objects.first()
user.is_active = True
user.save(update_fields=["is_active"])
response = self.client.post(
self.OBTAIN_TOKEN_URL, self.user_data, format="json"
)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertTrue("access" in response.data and "refresh" in response.data)
def test_login_inactive(self):
self._register_user(self.user_data)
response = self.client.post(
self.OBTAIN_TOKEN_URL, self.user_data, format="json"
)
# user should be inactive after registration
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_user_details(self):
self._register_user(self.user_data)
# set user as active
user = User.objects.first()
user.is_active = True
user.save()
response = self.client.post(
self.OBTAIN_TOKEN_URL, self.user_data, format="json"
)
access_token = response.data["access"]
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}")
response = self.client.get(self.USER_DETAILS_URL)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(response.data["email"], user.email)
def test_user_details_fail(self):
response = self.client.get(self.USER_DETAILS_URL)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
def test_account_activate_fail(self):
response = self.client.get(
self.ACCOUNT_ACTIVATE_URL, {"uid": "1", "token": "<PASSWORD>"}
)
self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST)
<file_sep>/api_accounts/serializers.py
from django.core.validators import MinLengthValidator
from django.contrib.auth import get_user_model
from django.utils.http import urlsafe_base64_decode
from django.utils.encoding import force_bytes, force_text
from django.core.exceptions import ObjectDoesNotExist
from rest_framework import serializers
from api_accounts.models import User
from api_accounts.utils import VerificationTokenGenerator
class UserRegistrationSerializer(serializers.ModelSerializer):
password = serializers.CharField(validators=[MinLengthValidator(8)])
class Meta:
model = User
fields = ["email", "password"]
extra_kwargs = {"password": {"required": True, "write_only": True}}
def create(self, validated_data):
user = User.objects.create_user(
validated_data["email"], validated_data["password"]
)
return user
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ["id", "email"]
class ActivateAccountSerializer(serializers.Serializer):
uid = serializers.CharField()
token = serializers.CharField()
def validate(self, data) -> User:
"""
Overloaded validation checks if uid and token are correct and returns corresponding User object.
"""
uid = data["uid"]
token = data["token"]
User = get_user_model()
try:
uid = force_text(urlsafe_base64_decode(uid))
user = User.objects.get(pk=uid)
except (ObjectDoesNotExist, ValueError):
raise serializers.ValidationError("Given user does not exist")
activation_token = VerificationTokenGenerator()
if not activation_token.check_token(user, token):
raise serializers.ValidationError("Given token is wrong")
return user
<file_sep>/api_projects/admin.py
from django.contrib import admin
from api_projects.models import Project, Issue, DateUpdateTask, IssueAttachment
admin.site.register(Project)
admin.site.register(Issue)
admin.site.register(IssueAttachment)
admin.site.register(DateUpdateTask)
<file_sep>/api_accounts/utils.py
from typing import Optional
from django.utils.http import urlsafe_base64_encode
from django.utils.encoding import force_bytes
from django.conf import settings
from django.contrib.auth.tokens import PasswordResetTokenGenerator
from django.contrib.auth import get_user_model
from django.core.mail import send_mail
from rest_framework.request import Request
from rest_framework.reverse import reverse
__all__ = ["VerificationTokenGenerator", "send_verification_email"]
User = get_user_model()
class VerificationTokenGenerator(PasswordResetTokenGenerator):
def _make_hash_value(self, user, timestamp):
return str(user.pk) + str(timestamp) + str(user.is_active)
def send_verification_email(
user: User,
request: Request,
subject: str = "Verify your email",
message: str = "",
sender: Optional[str] = None,
) -> None:
token_generator = VerificationTokenGenerator()
token = token_generator.make_token(user)
uid = urlsafe_base64_encode(force_bytes(user.pk))
message += create_activation_url(uid, token, request)
# The sender is set in DEFAULT_FROM_EMAIL in settings.py
send_mail(subject, message, None, recipient_list=[user.email], fail_silently=False)
def _create_activation_url(uid: str, token: str, request: Request) -> str:
endpoint = reverse("api_accounts:activate")
protocol = "https" if request.is_secure() else "http"
host = request.get_host()
return f"{protocol}://{host}{endpoint}?uid={uid}&token={token}"
<file_sep>/api_accounts/urls.py
from django.urls import path
from rest_framework.urlpatterns import format_suffix_patterns
from rest_framework_simplejwt.views import (
TokenObtainPairView,
TokenRefreshView,
)
from api_accounts.views import (
UserRegistrationView,
UserDetailsView,
ActivateAccountView,
)
app_name = "api_accounts"
urlpatterns = [
path("register/", UserRegistrationView.as_view(), name="register"),
path("register/activate/", ActivateAccountView.as_view(), name="activate"),
path("user/", UserDetailsView.as_view(), name="user_details"),
path("token/", TokenObtainPairView.as_view(), name="token_obtain_pair"),
path("token/refresh/", TokenRefreshView.as_view(), name="token_refresh"),
]
urlpatterns = format_suffix_patterns(urlpatterns)
<file_sep>/api_projects/serializers.py
from rest_framework import serializers
from rest_framework.validators import UniqueTogetherValidator
from api_projects.models import Project, Issue, IssueAttachment
class IssueSerializer(serializers.ModelSerializer):
class Meta:
model = Issue
fields = "__all__"
owner = serializers.ReadOnlyField(source="owner.email")
assigne = serializers.ReadOnlyField(source="assigne.email")
attachments = serializers.SerializerMethodField()
def get_attachments(self, issue):
request_meta = self.context["request"].META
has_hostname = "HTTP_HOST" in request_meta
hostname = request_meta["HTTP_HOST"] if has_hostname else "localhost"
return (
{
"id": file.pk,
"name": str(file),
"url": f"{hostname}{file.file_attachment.url}",
}
for file in issue.files.all()
)
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = "__all__"
owner = serializers.ReadOnlyField(source="owner.pk")
members = serializers.SerializerMethodField()
issues = IssueSerializer(many=True, required=False)
def get_members(self, project):
# possibility to extend returned values
return project.members.values("id", "email")
class IssueAttachmentSerializer(serializers.ModelSerializer):
class Meta:
model = IssueAttachment
fields = "__all__"
<file_sep>/api_projects/tests.py
from typing import Dict
from datetime import datetime
from django.contrib.auth import get_user_model
from rest_framework.test import APITestCase
from rest_framework.reverse import reverse_lazy, reverse
from rest_framework import status
from api_projects.models import Project, Issue
User = get_user_model()
class ProjectsTest(APITestCase):
OBTAIN_TOKEN_URL = reverse_lazy("api_accounts:token_obtain_pair")
PROJECT_LIST = "api_projects:project-list"
PROJECT_DETAILS = "api_projects:project-detail"
def _init_db(self) -> None:
# NOTE: It's better option to create some test fixtures in future
self.owners = [
{"email": "<EMAIL>", "password": "<PASSWORD>"},
{"email": "<EMAIL>", "password": "<PASSWORD>"},
]
self.no_project_users = [
{"email": "<EMAIL>", "password": "<PASSWORD>"},
]
self.members = [
{"email": "<EMAIL>", "password": "<PASSWORD>"},
{"email": "<EMAIL>", "password": "<PASSWORD>"},
{"email": "<EMAIL>", "password": "<PASSWORD>"},
]
self.users = [
User.objects.create_user(**user)
for user in self.owners + self.no_project_users
]
members = [User.objects.create_user(**member) for member in self.members]
User.objects.all().update(is_active=True)
project_1 = Project.objects.create(
name="Project1 with members", owner=self.users[0]
)
project_1.members.add(*members)
Project.objects.create(name="Project1 without members", owner=self.users[0])
Project.objects.create(name="Project2 empty", owner=self.users[1])
example_date = datetime(2030, 10, 10, hour=12, minute=30)
Issue.objects.create(
title="Issue 1",
description="Desc...",
owner=members[0],
project=project_1,
due_date=example_date,
)
def setUp(self):
self._init_db()
def _login_user(self, user: Dict[str, str]) -> None:
response = self.client.post(self.OBTAIN_TOKEN_URL, user, format="json")
access_token = response.data["access"]
self.client.credentials(HTTP_AUTHORIZATION=f"Bearer {access_token}")
def test_get_projects(self):
url = reverse(self.PROJECT_LIST)
# anonymous user
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED)
# logged in as owner
user = self.owners[0]
self._login_user(user)
expected_count = Project.objects.filter(owner__email=user["email"]).count()
response = self.client.get(url)
self.assertEqual(len(response.data), expected_count)
# logged in as member
user = self.members[0]
self._login_user(user)
expected_count = Project.objects.filter(members__email=user["email"]).count()
response = self.client.get(url)
self.assertEqual(len(response.data), expected_count)
# logged in as user without projects
self._login_user(self.no_project_users[0])
expected_count = 0
response = self.client.get(url)
self.assertEqual(response.status_code, status.HTTP_200_OK)
self.assertEqual(len(response.data), expected_count)
def test_get_project_details(self):
user_1 = self.owners[0]
user_2 = self.owners[1]
project = Project.objects.filter(owner__email=user_1["email"]).first()
projects_init_count = Project.objects.count()
url = reverse(self.PROJECT_DETAILS, kwargs={"pk": project.pk})
self._login_user(user_1)
response_ok = self.client.get(url)
self._login_user(user_2)
response_bad = self.client.get(url)
self.assertEqual(response_ok.status_code, status.HTTP_200_OK)
self.assertEqual(response_bad.status_code, status.HTTP_404_NOT_FOUND)
issues_count = Issue.objects.filter(project=project).count()
response_issues = response_ok.data["issues"]
self.assertEqual(len(response_issues), issues_count)
def test_create_project(self):
url = reverse(self.PROJECT_LIST)
new_project = {"name": "New project"}
response_bad = self.client.post(url, new_project)
user = self.no_project_users[0]
self._login_user(user)
expected_count = Project.objects.filter(owner__email=user["email"]).count() + 1
response_ok = self.client.post(url, new_project)
current_projects_count = Project.objects.filter(
owner__email=user["email"]
).count()
self.assertEqual(response_bad.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(response_ok.status_code, status.HTTP_201_CREATED)
self.assertEqual(current_projects_count, expected_count)
def test_update_project(self):
user_1 = self.owners[0]
user_2 = self.owners[1]
project = Project.objects.filter(owner__email=user_1["email"]).first()
projects_init_count = Project.objects.count()
url = reverse(self.PROJECT_DETAILS, kwargs={"pk": project.pk})
new_name = "new name"
self._login_user(user_1)
response_ok = self.client.put(url, {"name": new_name})
self._login_user(user_2)
response_bad = self.client.put(url, {"name": new_name})
self.assertEqual(response_ok.status_code, status.HTTP_200_OK)
self.assertEqual(response_ok.data["name"], new_name)
self.assertEqual(response_bad.status_code, status.HTTP_404_NOT_FOUND)
def test_delete_project(self):
user = self.owners[0]
project = Project.objects.filter(owner__email=user["email"]).first()
projects_init_count = Project.objects.count()
url = reverse(self.PROJECT_DETAILS, kwargs={"pk": project.pk})
response_bad = self.client.delete(url)
projects_count_non_auth_delete = Project.objects.count()
self._login_user(user)
response_ok = self.client.delete(url)
projects_count_delete = Project.objects.count()
self.assertEqual(projects_count_non_auth_delete, projects_init_count)
self.assertEqual(response_bad.status_code, status.HTTP_401_UNAUTHORIZED)
self.assertEqual(projects_count_delete, projects_init_count - 1)
self.assertEqual(response_ok.status_code, status.HTTP_204_NO_CONTENT)
<file_sep>/Dockerfile
FROM python:3
# prevent saving .pyc files
ENV PYTHONDONTWRITEBYTECODE 1
ENV PYTHONUNBUFFERED 1
WORKDIR /backend
# this directory contains requirements.txt
COPY requirements.txt /backend
RUN pip install -r requirements.txt
COPY . /backend/<file_sep>/stx_training_program/celery.py
from __future__ import absolute_import
import os
from celery import Celery
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "stx_training_program.settings")
# Get the base REDIS URL, default to redis' default
BASE_REDIS_URL = os.environ.get("REDIS_URL", "redis://localhost:6379")
app = Celery("stx_training_program")
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
app.config_from_object("django.conf:settings", namespace="CELERY")
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
app.conf.broker_url = BASE_REDIS_URL
# this allows you to schedule items in the Django admin.
app.conf.beat_scheduler = "django_celery_beat.schedulers.DatabaseScheduler"
<file_sep>/api_projects/apps.py
from django.apps import AppConfig
class ApiProjectsConfig(AppConfig):
name = "api_projects"
<file_sep>/api_accounts/apps.py
from django.apps import AppConfig
class ApiAccountsConfig(AppConfig):
name = "api_accounts"
<file_sep>/api_projects/permissions.py
from rest_framework.permissions import BasePermission, SAFE_METHODS
from api_projects.models import Project, Issue, IssueAttachment
class IsOwner(BasePermission):
"""
Object-level permission to only allow owners of an object to edit it.
"""
def has_object_permission(self, request, view, obj):
# Instance must have an attribute named `owner`.
user = request.user
if isinstance(obj, Project):
return obj.owner == user
if isinstance(obj, Issue):
return obj.owner == user or obj.project.owner == user
if isinstance(obj, IssueAttachment):
return obj.issue.owner == user or obj.issue.project.owner == user
class MemberReadOnly(BasePermission):
"""
Object-level permission to only allow members of an object to view it.
"""
def has_object_permission(self, request, view, obj):
# Instance must have an attribute named `members`.
return request.method in SAFE_METHODS and request.user in obj.members.all()
class IsProjectMember(BasePermission):
"""
Checks if current user is member of the project.
"""
def has_object_permission(self, request, view, obj):
# Instance must have an attribute named `project`.
if isinstance(obj, Issue):
return obj.project in request.user.projects.all()
if isinstance(obj, Project):
return obj in request.user.projects.all()
if isinstance(obj, IssueAttachment):
return obj.issue.project in request.user.projects.all()
| 13f53a58840bbfa153c409aee782532ad6003cc1 | [
"Markdown",
"Python",
"Text",
"Dockerfile"
] | 19 | Python | kamils224/STXNext_training_program | cfd75a4865918044f19d0938e54cc5541974cbb2 | 5516a144b5b0cdaf670adb25aaad4b53e192bab6 |
refs/heads/master | <repo_name>thiagolioy/SpaceCatSwift-<file_sep>/SpaceCatSwift/SpaceCatSwift/TitleScene.swift
//
// TitleScene.swift
// SpaceCatSwift
//
// Created by <NAME> on 7/29/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import SpriteKit
import AVFoundation
class TitleScene: SKScene {
var pressStartSFX:SKAction?
var backgroundMusic:AVAudioPlayer?
init(size: CGSize) {
/* Setup your scene here */
super.init(size: size)
let background = SKSpriteNode(imageNamed:"splash_1")
let (x:CGFloat , y:CGFloat) = (CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
background.position = CGPointMake(x, y)
self.addChild(background)
startBackgroundMusic();
}
func startBackgroundMusic(){
pressStartSFX = SKAction.playSoundFileNamed("PressStart.caf", waitForCompletion: false)
let url = NSBundle.mainBundle().URLForResource("StartScreen", withExtension: "mp3")
backgroundMusic = AVAudioPlayer(contentsOfURL: url, error: nil)
backgroundMusic!.numberOfLoops = -1
backgroundMusic!.prepareToPlay()
}
override func didMoveToView(view: SKView) {
backgroundMusic!.play()
}
override func touchesBegan(touches: NSSet!, withEvent event: UIEvent!) {
runAction(pressStartSFX)
backgroundMusic!.stop()
let gamePlayScene = GamePlayScene(size: self.frame.size)
let transition = SKTransition.fadeWithDuration(1.0)
self.view.presentScene(gamePlayScene, transition: transition)
}
}<file_sep>/SpaceCatSwift/SpaceCatSwift/SpaceCatNode.swift
//
// SpaceCatNode.swift
// SpaceCatSwift
//
// Created by <NAME> on 7/29/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import SpriteKit
class SpaceCatNode: SKSpriteNode {
class func spaceCat(position:CGPoint!)-> SpaceCatNode {
let spaceCat = SpaceCatNode(imageNamed: "spacecat_1")
spaceCat.position = position;
spaceCat.anchorPoint = CGPointMake(0.5, 0);
spaceCat.name = "SpaceCat";
spaceCat.zPosition = 9;
return spaceCat
}
}<file_sep>/SpaceCatSwift/SpaceCatSwift/MachineNode.swift
//
// MachineNode.swift
// SpaceCatSwift
//
// Created by <NAME> on 7/29/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import SpriteKit
class MachineNode: SKSpriteNode {
class func machine(position:CGPoint!)-> MachineNode {
let machine = MachineNode(imageNamed: "machine_1")
machine.position = position;
machine.anchorPoint = CGPointMake(0.5, 0);
machine.name = "Machine";
machine.zPosition = 8;
machine.runAction(setupAnimation())
return machine
}
class func setupAnimation()->SKAction{
let textures = [SKTexture(imageNamed: "machine_1"),SKTexture(imageNamed: "machine_2")]
let machineAnimation = SKAction.animateWithTextures(textures, timePerFrame: 0.1)
let machineRepeat = SKAction.repeatActionForever(machineAnimation)
return machineRepeat;
}
}
<file_sep>/SpaceCatSwift/SpaceCatSwift/GamePlayScene.swift
//
// GamePlayScene.swift
// SpaceCatSwift
//
// Created by <NAME> on 7/29/14.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import SpriteKit
import AVFoundation
class GamePlayScene : SKScene {
// @property (nonatomic) NSTimeInterval lastUpdateTimeInterval;
// @property (nonatomic) NSTimeInterval timeSinceEnemyAdded;
// @property (nonatomic) NSTimeInterval totalGameTime;
// @property (nonatomic) NSInteger minSpeed;
// @property (nonatomic) NSTimeInterval addEnemyTimeInterval;
var damageSFX:SKAction?
var explodeSFX:SKAction?
var laserSFX:SKAction?
var backgroundMusic:AVAudioPlayer?
var gameOverMusic:AVAudioPlayer?
var gameOver:Bool?
var restart:Bool?
var gameOverDisplayed:Bool?
init(size: CGSize){
super.init(size: size)
setupEnvironment()
setupBackground()
setupPlayer()
setupSounds()
}
func setupEnvironment(){
// self.lastUpdateTimeInterval = 0;
// self.timeSinceEnemyAdded = 0;
// self.addEnemyTimeInterval = 1.5;
// self.totalGameTime = 0;
// self.minSpeed = THSpaceDogMinSpeed;
gameOver = false
restart = false
gameOverDisplayed = false
}
func setupBackground(){
let background = SKSpriteNode(imageNamed: "background_1")
let (x:CGFloat , y:CGFloat) = (CGRectGetMidX(self.frame),CGRectGetMidY(self.frame))
background.position = CGPointMake(x, y)
self.addChild(background)
}
func setupPlayer(){
let machine = MachineNode.machine(CGPointMake(CGRectGetMidX(self.frame), 12))
addChild(machine)
let spaceCat = SpaceCatNode.spaceCat(CGPointMake(machine.position.x,
machine.position.y - 2))
addChild(spaceCat)
}
func setupSounds(){
setupBackgroundMusic()
setupSoundEffects()
}
func setupSoundEffects(){
damageSFX = SKAction.playSoundFileNamed("Damage.caf", waitForCompletion: false)
explodeSFX = SKAction.playSoundFileNamed("Explode.caf", waitForCompletion: false)
laserSFX = SKAction.playSoundFileNamed("Laser.caf", waitForCompletion: false)
}
func setupBackgroundMusic(){
let url = NSBundle.mainBundle().URLForResource("Gameplay", withExtension: "mp3")
backgroundMusic = AVAudioPlayer(contentsOfURL: url, error: nil)
backgroundMusic!.numberOfLoops = -1
backgroundMusic!.prepareToPlay()
let gameOverUrl = NSBundle.mainBundle().URLForResource("GameOver", withExtension: "mp3")
gameOverMusic = AVAudioPlayer(contentsOfURL: gameOverUrl, error: nil)
gameOverMusic!.numberOfLoops = -1
gameOverMusic!.prepareToPlay()
}
override func didMoveToView(view: SKView!) {
backgroundMusic!.play()
}
}
<file_sep>/README.md
SpaceCatSwift-
==============
iOS game based on TeamTreehouse project http://teamtreehouse.com/library/build-a-game-with-sprite-kit , but this time written in Swift
| be575b66f1ef7de330d0c118b2061916e338b73e | [
"Swift",
"Markdown"
] | 5 | Swift | thiagolioy/SpaceCatSwift- | 01b0aaefd09a6752b50f619fe22776d460102997 | 31fdf7482a7e7d786e255c4f1400acfc3053c0b2 |
refs/heads/master | <file_sep>altura = 1.48
peso = 42.0
imc = peso/ (altura**2)
print (imc)
print ("Muito abaixo do peso?", imc < 17.0)
print ("Abaixo do peso normal?", imc >= 17.0 and imc <= 18.5)
print ("Peso dentro do Normal?", imc > 18.5 and imc <= 25.0)
print ("Acima do peso normal?", imc > 25.0 and imc <= 30.0)
print ("Muito acima do peso?", imc > 30.0)
<file_sep># IMC
nome = str(input('Digite seu nome: '))
peso = float(input('Digite seu peso: '))
altura = float(input('Digite sua altura: '))
imc = peso/(altura ** 2)
if (imc<17):
print("seu IMC é {:.2f} e Você está muito abaixo do peso!".format(imc))
elif (imc>17 and imc<=18.5):
print("seu IMC é {:.2f} e Você está abaixo do peso!".format(imc))
elif (imc>18.5 and imc<=25.0):
print("seu IMC é {:.2f} e Você está dentro da faixa de peso considerada normal pelo IMC!".format(imc))
elif (imc>25.0 and imc<=30):
print("seu IMC é {:.2f} e Você está acima do peso!".format(imc))
else:
print("seu IMC é {:.2f} e Você está obeso!".format(imc)))
# EXEMPLO
Digite seu nome: mari
Digite seu peso: 62
Digite sua altura: 1.53
seu IMC é 26.49 e Você está acima do peso!
<file_sep>nome = str(input('Digite seu nome: '))
peso = float(input('Digite seu peso: '))
altura = float(input('Digite sua altura: '))
imc = peso/(altura**2)
if (imc<17):
print("seu IMC é {:.2f} e Você está muito abaixo do peso!".format(imc))
elif (imc>17 and imc<=18.5):
print("seu IMC é {:.2f} e Você está abaixo do peso!".format(imc))
elif (imc>18.5 and imc<=25.0):
print("seu IMC é {:.2f} e Você está dentro da faixa de peso considerada normal pelo IMC!".format(imc))
elif (imc>25.0 and imc<=30):
print("seu IMC é {:.2f} e Você está acima do peso!".format(imc))
else:
print("seu IMC é {:.2f} e Você está obeso!".format(imc))
<file_sep>nome = str(input('Digite seu nome: '))
peso = float(input('Digite seu peso: '))
altura = float(input('Digite sua altura: '))
imc = peso/(altura**2)
print (" {:.2f}".format(imc))
print ("Muito abaixo do peso?", imc < 17.0)
print ("Abaixo do peso normal?", imc >= 17.0 and imc <= 18.5)
print ("Peso dentro do Normal?", imc > 18.5 and imc <= 25.0)
print ("Acima do peso normal?", imc > 25.0 and imc <= 30.0)
print ("Muito acima do peso?", imc > 30.0)
<file_sep>
peso = float (input("Digite o seu peso: "))
altura = float (input("Digite sua altura: "))
imc = (peso/(altura**2))
print("O peso informado foi: %s, e a altura informada foi: %s" %(peso, altura))
print("Portanto, o seu IMC é: ", imc)
| ecee26a9ebb31653ad02fc8ac8104c0dc13998dc | [
"Markdown",
"Python"
] | 5 | Python | FabioISD/IMC-1 | d5c5c8730b0e810d0395812b197897db449f1ef7 | 78265ee9393bfa7d80c25b1be156ba77b8c6bf6f |
refs/heads/master | <file_sep>package th.ac.ku.atm.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import th.ac.ku.atm.model.BankAccount;
import th.ac.ku.atm.service.BankAccountService;
@Controller
@RequestMapping("/bankaccount")
public class BankAccountController {
//handle request เกี่ยวกับบัญชีธนาคาร
//มี dependency ไปที่ BankAccountService ต้องสร้าง constructor
private BankAccountService accountService;
public BankAccountController(BankAccountService accountService) {
this.accountService = accountService;
}
@GetMapping
public String getBankAccountPage( Model model){
model.addAttribute("bankaccounts", accountService.getBankAccounts());
return "bankaccount";
}
@PostMapping
public String openAccount(@ModelAttribute BankAccount bankAccount, Model model){
accountService.openAccount(bankAccount);
model.addAttribute("bankaccounts", accountService.getBankAccounts());
return "redirect:bankaccount";
}
@GetMapping("/edit/{id}")
public String getEditBankAccountPage(@PathVariable int id,Model model){
BankAccount bankAccount = accountService.getBankAccount(id);
model.addAttribute("bankAccount",bankAccount);
return "bankaccount-edit";
}
@PostMapping("/edit/{id}")
public String editAccount(@PathVariable int id,
@ModelAttribute BankAccount bankAccount,
double inputAmount, String transaction, Model model){
BankAccount record = accountService.getBankAccount(bankAccount.getId()) ;
if (transaction.equals("deposit")) {
record.setBalance(record.getBalance() + inputAmount);
} else {
record.setBalance(record.getBalance() - inputAmount);
}
accountService.editBankAccount(record);
model.addAttribute("bankaccounts",accountService.getBankAccounts());
return "redirect:/bankaccount";
}
//รับข้อมูลบัญชี
@GetMapping("/delete/{id}")
public String getDeleteBankAccount(@PathVariable int id,Model model){
BankAccount bankAccount = accountService.getBankAccount(id);
accountService.deleteBankAccount(bankAccount);
model.addAttribute("bankAccount",bankAccount);
return "bankaccount";
}
//
@PostMapping("/delete/{id}")
public String deleteAccount(@PathVariable int id,@ModelAttribute BankAccount bankAccount,Model model){
accountService.deleteBankAccount(bankAccount);
model.addAttribute("bankaccounts",accountService.getBankAccounts());
return "redirect:/bankaccount";
}
}
| 88da8af6ce62b3d842111c3c9fd5b66f91d2a4f5 | [
"Java"
] | 1 | Java | Powpalida/atm-web | 4a6d6bf8d5d43291c9fa52da9055203412493a3f | 1528fc4289978b94beb7b62bcb9674160e9dc3bf |
refs/heads/master | <repo_name>00steve/engine<file_sep>/physics/ode_utils.h
#ifndef ODE_UTILS_H
#define ODE_UTILS_H
#define dSINGLE
#include <ode/ode.h>
#include <engine/core/double3.h>
dReal* dCross(dReal* a,dReal* b);
double3 to_double3(const dReal *d);
#endif // ODE_UTILS_H
<file_sep>/graphics/camera.h
#ifndef ENGINE_CAMERA_H
#define ENGINE_CAMERA_H
#include <engine/core/node.h>
class Camera : public Node{
private:
protected:
virtual void OnSetSettings();
public:
Camera();
~Camera();
virtual bool TranslateView();
bool Init();
};
#endif // ENGINE_CAMERA_H
<file_sep>/graphics/shader.h
#ifndef GLSL_SHADER_H
#define GLSL_SHADER_H
#include <string>
#include <GL/gl.h>
#include <engine/assetlibrary/assetlibrary.h>
using namespace std;
class Shader{
private:
//GLuint vertShader;
//GLuint fragShader;
string fragmentCode;
string vertexCode;
public:
Shader(string name);
};
#endif // GLSL_SHADER_H
<file_sep>/graphics/camera.cpp
#include "camera.h"
Camera::Camera()// :
//_cam(0)
{
}
Camera::~Camera(){
}
void Camera::OnSetSettings(){
RegisterGlobal(this,Settings().Name());
}
bool Camera::TranslateView(){
return false;
}
bool Camera::Init(){
/*
pipeline = newPipeline;
_cam = h3dAddCameraNode( targetNode, "Camera", pipeline );
h3dSetNodeParamI( _cam, H3DCamera::ViewportXI, 0 );
h3dSetNodeParamI( _cam, H3DCamera::ViewportYI, 0 );
h3dSetNodeParamI( _cam, H3DCamera::ViewportWidthI, 800 );
h3dSetNodeParamI( _cam, H3DCamera::ViewportHeightI, 600 );
h3dSetupCameraView( _cam, 45.0f, (float).75, 0.5f, 2048.0f );
*/
//OnSetSettings();
return true;
}
<file_sep>/graphics/shader.cpp
#include "shader.h"
Shader::Shader(string name) //:
//vertShader(glCreateShader(GL_VERTEX_SHADER)),
//fragShader(glCreateShader(GL_FRAGMENT_SHADER))
{
string baseShaderName = AssetLibrary::RootDirectory() + "shaders/" + name;
string vertexShaderName = baseShaderName + "_vertex.txt";
string fragmentShaderName = baseShaderName + "_fragment.txt";
cout << " - Load vert shader : " + vertexShaderName << endl;
cout << " - Load frag shader : " + fragmentShaderName << endl;
vertexCode = AssetLibrary::LoadString(vertexShaderName);
fragmentCode = AssetLibrary::LoadString(fragmentShaderName);
cout << vertexCode << "\n\n";
cout << fragmentCode << "\n\n";
}
| 01f1e0d871d9f1edef6f4d1fa8e0f0e2532cca1e | [
"C",
"C++"
] | 5 | C | 00steve/engine | 7b9bd87e0e782be67b9ee6c3e15ab18b2e0550a3 | 58fb529cfea7c3a4e2ba2e847f920f27e1489e5a |
refs/heads/master | <repo_name>pauljickling/logic-game-solver<file_sep>/README.md
# Logic Game Solver
This is an ongoing effort to write a program that can solve the randomly generated logic game puzzles that occur in Dishonored 2. There are two big challenges I see:
1. Defining randomly generated rules
2. Creating an algorithm that is able to infer rules from the randomly generated rules.
<file_sep>/src/main.rs
/*
* name = Winslow, Marcolla, Contee, Natsiou, Finch
* rows = 1, 2, 3, 4, 5
* colors = white, green, red, purple, blue
* drinks = absynthe, beer, rum, wine, whiskey
* heirlooms = ring, tin, pendant, diamond, medal
* places = Dunwall, Karnaca, Dabakva, Fraeport, Baleton
*
*/
#[derive(Debug)]
enum Row {
One,
Two,
Three,
Four,
Five,
Unknown,
}
#[derive(Debug)]
enum Name {
Winslow,
Marcolla,
Contee,
Natsiou,
Finch,
Unknown,
}
#[derive(Debug)]
enum Color {
White,
Green,
Red,
Purple,
Blue,
Unknown,
}
#[derive(Debug)]
enum Drink {
Absinthe,
Beer,
Rum,
Wine,
Whiskey,
Unknown,
}
#[derive(Debug)]
enum Place {
Dunwall,
Karnaca,
Dabakva,
Fraeport,
Baleton,
Unknown,
}
#[derive(Debug)]
enum Heirloom {
Ring,
Tin,
Pendant,
Diamond,
Medal,
Unknown,
}
#[derive(Debug)]
struct Person {
row: Row,
name: Name,
color: Color,
drink: Drink,
heirloom: Heirloom,
place: Place,
}
/* INIT RULES
* 1. Natsiou = white
* 2. Winslow = 1
* 3. green = 2
* 4. red < purple
* 5. red = absinthe
* 6. Dunwall = blue
* 7. Dunwall + or - 1 to ring
* 8. finch = tin
* 9. Karnaca = pendant
* 10. Dabokva + or - 1 to diamond, and + or - 1 to beer
* 11. Contee = rum
* 12. Fraeport = wine
* 13. 3 = whiskey
* 14. Marcolla = Baleton
*
* */
/* INFERRED RULES
* 1. Winslow != green, purple, white (red or blue)
* 2. Row 2 != Natsiou, Winslow (Contee, Finch, or Marcolla)
* 3. Row 3 != green, red, Winslow, Contee, Fraeport
*
* */
fn main() {
let person1 = Person {
row: Row::One,
name: Name::Winslow,
color: Color::Unknown,
drink: Drink::Unknown,
heirloom: Heirloom::Unknown,
place: Place::Unknown,
};
let person2 = Person {
row: Row::Two,
name: Name::Unknown,
color: Color::Green,
drink: Drink::Unknown,
heirloom: Heirloom::Unknown,
place: Place::Unknown,
};
let person3 = Person {
row: Row::Three,
name: Name::Unknown,
color: Color::Unknown,
drink: Drink::Whiskey,
heirloom: Heirloom::Unknown,
place: Place::Unknown,
};
let person4 = Person {
row: Row::Unknown,
name: Name::Unknown,
color: Color::Unknown,
drink: Drink::Unknown,
heirloom: Heirloom::Unknown,
place: Place::Unknown,
};
let person5 = Person {
row: Row::Unknown,
name: Name::Unknown,
color: Color::Unknown,
drink: Drink::Unknown,
heirloom: Heirloom::Unknown,
place: Place::Unknown,
};
println!("{:?}", person1);
println!("{:?}", person2);
println!("{:?}", person3);
println!("{:?}", person4);
println!("{:?}", person5);
}
fn valid() {}
| 15e9e635f959c50f9bc23829eee991a6f80754fe | [
"Markdown",
"Rust"
] | 2 | Markdown | pauljickling/logic-game-solver | 3937ef9aeee8ec364faa69fa6a6176c7746e1703 | 34418e25af7a96e625d7ccbaa06c5180c1410499 |
refs/heads/master | <repo_name>dsolovay/ShortConfirmationCodes<file_sep>/src/Policies/ShortConfirmationCodePolicy.cs
using Sitecore.Commerce.Core;
namespace ShortConfirmationCodes.Policies
{
public class ShortConfirmationCodePolicy : Policy
{
public int MaximumRetries { get; set; } = 3;
public int CodeLength { get; set; } = 6;
public string AllowedCharacters { get; set; } = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
}
}<file_sep>/README.md
# Short Confirmation Codes
Short confirmation code plugin for Sitecore Experience Commerce
This plugin provides six character confirmation codes (configurable), randomly
generated, and tracked in the commerce database to avoid conflicts. Shorter codes
are easier to communicate over support calls and for some clients may be
more convenient than the 25 character confirmations that are provided out of
the box.
## Technical notes
* As a precatution against codes being reused ("collisions"), the plugin creates tracking entities.
* The code checks for and creates tracking entities within a transaction, to ensure uniqueness.
* If a unique code is not generated in the allowed number of tries (default 3), a 32 character guid is returned.
* The default setting uses 26 characters, and a six character code, allowing for 308,915,776 possible codes.
## To Use
1. Add project to your soluton.
1. Update NuGet references to appropriate version for your Sitecore Commerce install.
1. Add reference to your commerce engine project.
1. (Optional) Create policy JSON to modifty settings (allowed characters, number of tries, length of code).
1. (Optional) Modify Sharding policy to put confimration code entities into a separate table. By default, they will go
to CommerceEntities.
<file_sep>/src/Commands/CreateShortConfirmationCode.cs
using System;
using System.Text;
using System.Threading.Tasks;
using ShortConfirmationCodes.Policies;
using Sitecore.Commerce.Core;
using Sitecore.Commerce.Core.Commands;
namespace ShortConfirmationCodes.Pipelines.Blocks
{
public class CreateShortConfirmationCode : CommerceCommand
{
private readonly CommerceCommander _commander;
private static Random _random = new Random();
private static object _myLock = new object();
public CreateShortConfirmationCode(CommerceCommander commander, IServiceProvider serviceProvider) : base(serviceProvider)
{
_commander = commander;
}
public async Task<string> Process(CommerceContext commerceContext)
{
var policy = commerceContext.GetPolicy<ShortConfirmationCodePolicy>();
int count = 0;
string result = Guid.NewGuid().ToString("N").ToUpper(); //Fallback value.
using (var activity = CommandActivity.Start(commerceContext, this))
{
await this.PerformTransaction(commerceContext, async () =>
{
do
{
string value = CreateValue(policy);
string id = $"Entity-ShortConfirmationCode-{value}";
if (await NotYetUsed(commerceContext, id))
{
await ReserveIt(commerceContext, id);
result = value;
break;
}
count++;
} while (count <= policy.MaximumRetries);
});
return result;
}
}
private async Task ReserveIt(CommerceContext commerceContext, string id)
{
var entity= await _commander.GetEntity<CommerceEntity>(commerceContext, id, autoCreate: true);
entity.Id = id;
await _commander.PersistEntity(commerceContext, entity);
}
private async Task<bool> NotYetUsed(CommerceContext commerceContext, string id)
{
return await _commander.GetEntity<CommerceEntity>(commerceContext,id, autoCreate:false) == null;
}
private string CreateValue(ShortConfirmationCodePolicy policy)
{
var sb = new StringBuilder();
string policyAllowedCharacters = policy.AllowedCharacters;
int max = policyAllowedCharacters.Length-1;
for (int i = 0; i < policy.CodeLength; i++)
{
sb.Append(policyAllowedCharacters[GetNextRandom(max)]);
}
return sb.ToString();
}
// Based on <NAME>'s StaticRandom class.
private static int GetNextRandom(int max)
{
lock (_myLock)
return _random.Next(max);
}
}
}<file_sep>/src/Pipelines/Blocks/AddShortConfirmationCodeBlock.cs
using System.Threading.Tasks;
using Sitecore.Commerce.Core;
using Sitecore.Commerce.Plugin.Orders;
using Sitecore.Framework.Pipelines;
namespace ShortConfirmationCodes.Pipelines.Blocks
{
[PipelineDisplayName("AddShortConfirmationCode.Block")]
public class AddShortConfirmationCodeBlock : PipelineBlock<Order, Order, CommercePipelineExecutionContext>
{
private readonly CommerceCommander _commander;
public AddShortConfirmationCodeBlock(CommerceCommander commander)
{
_commander = commander;
}
public override async Task<Order> Run(Order arg, CommercePipelineExecutionContext context)
{
arg.OrderConfirmationId = await _commander.Command<CreateShortConfirmationCode>().Process(context.CommerceContext);
return arg;
}
}
}<file_sep>/src/ConfigureSitecore.cs
using System.Reflection;
using Microsoft.Extensions.DependencyInjection;
using ShortConfirmationCodes.Pipelines.Blocks;
using Sitecore.Commerce.Core;
using Sitecore.Commerce.Plugin.Orders;
using Sitecore.Framework.Configuration;
using Sitecore.Framework.Pipelines.Definitions.Extensions;
namespace ShortConfirmationCodes
{
public class ConfigureSitecore : IConfigureSitecore
{
public void ConfigureServices(IServiceCollection services)
{
var assembly = Assembly.GetExecutingAssembly();
services.RegisterAllPipelineBlocks(assembly);
services.Sitecore().Pipelines(config => config
.ConfigurePipeline<IOrderPlacedPipeline>(c =>
c.Replace<OrderPlacedAssignConfirmationIdBlock, AddShortConfirmationCodeBlock>()));
services.RegisterAllCommands(assembly);
}
}
} | 0092bc5ae1bce61e24a253db46ecbe823e1621ef | [
"Markdown",
"C#"
] | 5 | C# | dsolovay/ShortConfirmationCodes | d84c7fd20c1fa6af5e684d7ac31c190e912f46a8 | a12e83f4e8bf0881a25feac406cbb3b9550e4bc6 |
refs/heads/master | <file_sep>package com.example.dake10.googletest;
import com.parse.ParseObject;
import com.parse.ParseClassName;
/**
* Created by dake10 on 1/7/16.
*/
@ParseClassName("GeoL")
public class GeoL extends ParseObject {
public String getRootName() {
return getString("rootName");
}
}
<file_sep>package com.example.dake10.googletest;
import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;
import com.google.android.gms.vision.barcode.Barcode;
import com.parse.*;
import java.util.Objects;
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
Handler mHandler = new Handler();
public static int MILISEGUNDOS_ESPERA = 2000;
double latitud = 17.7739488, longitud = -96.37943;
LatLng tuxtepec = new LatLng(latitud, longitud);
GoogleMap map;
Marker marker;
int init = 0, loctimes = 0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// [Optional] Power your app with Local Datastore. For more info, go to
// https://parse.com/docs/android/guide#local-datastore
Parse.enableLocalDatastore(this);
Parse.initialize(this);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
map = mapFragment.getMap();
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);
}
@Override
public void onMapReady(final GoogleMap map) {
if (init == 0) {
map.moveCamera(CameraUpdateFactory.newLatLngZoom(tuxtepec, (float) 13.5));
}
mHandler.postDelayed(new Runnable() {
public void run() {
Location ml = map.getMyLocation();
latitud = ml.getLatitude();
longitud = ml.getLongitude();
doStuff("SE CONSIGUO LA LOCACION");
tuxtepec = new LatLng(latitud, longitud);
marker = map.addMarker(new MarkerOptions().position(tuxtepec).title("Marcador en tuxtepec"));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(tuxtepec, 16));
//GUARDANDO LOS DATOS EN EL BACKEND
String mensaje = String.valueOf(tuxtepec);
doStuff(mensaje);
mHandler.postDelayed(new Runnable() {
public void run() {
marker.remove();
init = 1;
loctimes++;
ParseGeoPoint point = new ParseGeoPoint(latitud, longitud);
ParseObject geoObject = new ParseObject("GeoL");
geoObject.put("rootName", "Cobao");
geoObject.put("root", loctimes);
geoObject.put("dondeEsta", point);
geoObject.saveInBackground();
try {
geoObject.save();
} catch (ParseException e) {
e.printStackTrace();
}
onMapReady(map);
}
}, 2000);
}
}, 20000);
}
private void doStuff(String mensaje) {
Toast.makeText(this, mensaje, Toast.LENGTH_LONG).show();
}
} | 40fdaa4218ffbcf54582de21ad08896fb0637876 | [
"Java"
] | 2 | Java | dakedroid/Android-GMaps-and-Parse-HelloWorld | e796f11649c14f3df0437998d8a6b4a4ab00d250 | 71e2889c53ac47bd4a273eddd170a2e24e0e3d48 |
refs/heads/main | <repo_name>codeanuj/competive-programming<file_sep>/hackerearth/basicProgramming/CostOfballoons.java
import java.io.BufferedReader;
import java.io.InputStreamReader;
class TestClass {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int testcases = Integer.parseInt(br.readLine());
for(int i=0; i<testcases; i++){
int firstProblem =0;
int secondProblem =0;
String colorsPrice = br.readLine();
String[] price = colorsPrice.split(" ");
int greenPrice = Integer.parseInt(price[0]);
int purplePrice = Integer.parseInt(price[1]);
int participants = Integer.parseInt(br.readLine());
for(int j=0; j<participants;j++){
String problems = br.readLine();
String[] answerSheet = problems.split(" ");
if(Integer.parseInt(answerSheet[0])==1){
firstProblem++;
}
if(Integer.parseInt(answerSheet[1])==1){
secondProblem++;
}
}
int x = firstProblem*greenPrice + secondProblem*purplePrice;
int y = firstProblem*purplePrice + secondProblem*greenPrice;
System.out.println(Math.min(x,y));
}
}
}
| 5c4d5d60c3323bedae0be9e783ad666033ccac7b | [
"Java"
] | 1 | Java | codeanuj/competive-programming | d81855223c949a2d4d2800fcce9b570c9514b90a | 4382323aa2d6fa92fb71f137a928b3ef0d1ac956 |
refs/heads/master | <repo_name>renzeydood/Project_RPi_Ard_Serial_Generator<file_sep>/main.py
import time as t
from os import path
start_byte = "!"
stop_byte = "~"
total_arduino_to_rpi = 8
total_rpi_to_arduino = 8
# Depending on IDE, pylint will nag if tabs is used instead of spacings
#tab = "\t"
tab = " "
def rpi_code_main():
return "from Ard_interface import *\n" + \
"from message_structure import *\n" + \
"from Queue import Queue\n" + \
"from threading import Thread\n" + \
"\n" + \
"port = '/dev/ttyACM0'\n" + \
"baudrate = 19200\n" + \
"x = 0\n" + \
"\n" + \
"class main():\n" + \
tab + "def __init__(self):\n" + \
tab + tab + "self.ard = Ard_interface(port, baudrate)\n" + \
tab + tab + "self.msg_to_ard = SENDMessage()\n" + \
tab + tab + "self.msg_from_ard = RCVDMessage()\n" + \
"\n" + \
tab + "def start_connection(self):\n" + \
tab + tab + "self.ard.connect()\n" + \
tab + tab + "print('Arduino connected')\n"
def rpi_code_interface():
return ""
def rpi_code_message_struct():
return "ARD_ENC = 'utf-8'\n" + \
"START = '!'\n" + \
"STOP = '~'\n" + \
"MAX_BYTE_FROM_SERVER = 8 # Includes start and end bytes (RCVD)\n" + \
"MAX_BYTE_FROM_CLIENT = 9 # Includes start and end bytes (SEND)\n" + \
"\n" + \
"def int_to_bytes(data):\n" + \
tab + "return chr(data >> 7) + chr(data & 0x7F)\n" + \
"def bytes_to_int(u, l):\n" + \
tab + "return u << 7 | l\n" + \
"\n" + \
"class RCVDMessage():\n" + \
tab + "def __init__(self):\n" + \
tab + tab + "pass\n" + \
tab + "def destruct(self, data):\n" + \
tab + tab + "pass\n" + \
"\n" + \
"class SENDMessage():\n" + \
tab + "def __init__(self):\n" + \
tab + tab + "pass\n" + \
tab + "def contruct(self):\n" + \
tab + tab + "return (START + STOP).encode()\n"
def ard_code_main():
return "#include \"message_structure.h\"\n" + \
"\n" + \
"void setup()\n" + \
"{\n" + \
"\tSerial.begin(19200);\n" + \
"\tmemset(&msgRCVD, 0, sizeof(RCVDMessage));\n" + \
"\tmemset(&msgSEND, 0, sizeof(SENDMessage));\n" + \
"\n" + \
"\tdelay(500);\n" + \
"}\n" + \
"\n" + \
"void loop()\n" + \
"{\n" + \
"\t//Wait for start event\n" + \
"\tusbReceiveMSG(&msgRCVD); //Process incoming message packet\n" + \
"\tdelay(RPI_DELAY);\n" + \
"\tusbSendMSG(&msgRCVD);\n" + \
"}\n"
def ard_code_message_struct():
return "#define lowByte(w) ((uint8_t)((w)&0x7f))\n" + \
"#define highByte(w) ((uint8_t)((w) >> 7))\n" + \
"\n" + \
"const uint8_t START = '!';\n" + \
"const uint8_t STOP = '~';\n" + \
"const uint8_t MAX_BYTE_DATA = 8;\n" + \
"\n" + \
"struct RCVDMessage\n" + \
"{\n" + \
"\tuint8_t type;\n" + \
"};\n" + \
"\n" + \
"struct SENDMessage\n" + \
"{\n" + \
"\tuint8_t type;\n" + \
"};\n" + \
"\n"
def createFile(dest):
print(dest)
filename = "message_struct.py"
if not(path.isfile(dest + filename)):
f = open(dest + filename, 'w')
f.write(rpi_code_message_struct())
f.close()
elif(input("Overwrite {} file? (Y/n)".format(filename)) == "Y"):
f = open(dest + filename, 'w')
f.write(rpi_code_message_struct())
f.close()
def main():
print("*******************************************")
print("Options will run in sequence:")
print("1. Start byte")
print("2. Stop byte")
print("3. Number of data to send (Arduino to RPi)")
print("4. Data type and name")
print("5. Number of data to send (RPi to Arduino)")
print("6. Data type and name")
print("*******************************************")
readinput = input("1. Start byte (Should be unique): ")
if(len(readinput) < 2 and (31 < ord(readinput) < 127)):
start_byte = readinput
else:
print("Invalid")
readinput = input("2. Stop byte (Should be unique): ")
if(31 < ord(readinput) < 127):
stop_byte = readinput
else:
print("Invalid")
readinput = input("3. Number of data to send (Arduino to RPi): ")
if(47 < ord(readinput) < 58):
total_arduino_to_rpi = int(readinput)
data = [total_arduino_to_rpi]
else:
print("Invalid")
for x in data:
readinput = input("4. Data {} - Name: ").format(x)
data[x] = readinput
readinput = input("4. Data {} - Type (int/char): ").format(x)
if __name__ == '__main__':
#destination = ""
# createFile(destination)
# print("Done!!")
main()
<file_sep>/README.md
# Project_RPi_Ard_Serial_Generator
A Python script to generate simple serial libraries for Raspberry Pi and Arduino
## Background
The most common way for Raspberry Pi and Arduino to communicate is through the serial interface. Seperate codes are needed, 1 for the Arduino and another for the Raspberry Pi. Often, the issue is when 1 half or the other has some issues. Debugging the serial interface will then take a lot of time. Thus, this script will generate all the necessary codes for both the Arduino and Raspberry Pi to begin serial communications, making the process much easier.
## Learning points
- The fact that its possible to dynamically create a whole Python script using Python (This can lead to more ideas, such as using NLP to generate codes?)
- Creating files in general using Python
## How to use
Run the script and follow the instructions | 3c5b66485d67adb9c28cd8f2cd22d754e21df230 | [
"Markdown",
"Python"
] | 2 | Python | renzeydood/Project_RPi_Ard_Serial_Generator | d3856af69bf5863e693a17423236199e495adfa8 | 8cc88b19f5cc19e0991733898c1127326680b121 |
refs/heads/master | <repo_name>Klye-1002/hello-world<file_sep>/hello/hello/main.cpp
//
// main.cpp
// hello
//
// Created by LemuelLai on 1/13/20.
// Copyright © 2020 LemuelLai. All rights reserved.
//
#include <iostream>
int main(int argc, const char * argv[]) {
// insert code here...
//that's fine.
std::cout << "Hello, World!\n";
return 0;
}
<file_sep>/README.md
# hello-world
it's the repository to be familiar with github
i hope i can get the skill soon.
| ada81d58c90e54990bccf1142a8b1a881a497d0f | [
"Markdown",
"C++"
] | 2 | C++ | Klye-1002/hello-world | 2ac4811cf6000da6b128959c8eb867b8671a0693 | dd143bac009c2f65223f73765c48f08ca9ad47f8 |
refs/heads/master | <repo_name>prdevteam/plot-examples<file_sep>/coupons/android/src/com/plotprojects/coupons/ViewCouponActivity.java
package com.plotprojects.coupons;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.plotprojects.retail.android.FilterableNotification;
import org.json.JSONObject;
public class ViewCouponActivity extends Activity {
public static final String ACTION = "com.plotprojects.retail.android.example.OPEN_NOTIFICATION";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Get notification from the intent
FilterableNotification notification = getIntent().getParcelableExtra("notification");
try {
String category = new JSONObject(notification.getData()).getString("category");
setTitle("Plot Coupon Example: " + category);
} catch (Exception e) {
return;
}
setContentView(R.layout.coupon);
((TextView)findViewById(R.id.messageTextView)).setText(notification.getMessage());
}
}<file_sep>/coupons/phonegap/readme.md
Plot Phonegap Coupon Example
============================
Example to enable relevant location based notifications in Phonegap.
This example only works correctly in iOS.
To get this working, you still have to add the Plot plugin. You can add the plugin to an existing project by executing the following command: phonegap local plugin add https://github.com/Plotprojects/plot-phonegap-plugin/ or cordova plugin add https://github.com/Plotprojects/plot-phonegap-plugin/ in case you are using Cordova.
More information about this example can be found at http://www.plotprojects.com/bridging-the-phonegap
More information about Location Based Notifications for Android and IOS, see http://www.plotprojects.com | fadf7b4ba262522e8946f9f91759453b9811f423 | [
"Markdown",
"Java"
] | 2 | Java | prdevteam/plot-examples | 2f27fbdc96e314933d5c308752d1bc9bc58c0be6 | 67790201260cc001a53a4160fb54dc7c425e2bb1 |
refs/heads/master | <file_sep>class Solution {
int[] decimalValue = {1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1};
String[] roman = {"M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"};
int result = 0;
public int romanToInt(String s)
{
for (int i = 0; i < decimalValue.length; i++ )
{
while (s.indexOf(roman[i]) == 0)
{
result += decimalValue[i];
s = s.substring(roman[i].length());
}
}
return result;
}
}
<file_sep>public class Solution {
public int Maximum69Number (int num) {
}
}
<file_sep>public class Solution {
public int[] RunningSum(int[] nums) {
int sum;
return nums.Select(w=>sum+=w);
}
}
<file_sep>class Solution {
public int numUniqueEmails(String[] emails) {
}
}
<file_sep>class Solution {
func countOdds(_ low: Int, _ high: Int) -> Int {
return (high - low + 1 + low % 2) / 2
}
}
<file_sep>public class Solution {
public int FindNumbers(int[] nums) {
int counter = 0;
for (int i = 0; i < nums.Length; i += 1)
{
if(nums[i].ToString().Length % 2 == 0)
counter +=1;
}
return counter;
}
}
<file_sep>class Solution {
public:
string defangIPaddr(string address) {
std::string output;
output.reserve(address.size());
for (const char c: address) {
if(c == '.'){
output += "[.]";
}
else{
output += c;
}
}
return output;
}
};
<file_sep>
public class Solution {
public int[] PlusOne(int[] digits) {
digits[digits.Length - 1] += 1;
return digits;
}
}
<file_sep>public class Solution {
public int XorOperation(int n, int start) {
int[] nums = new int[n];
for(int i = 0 ; i<nums.Length; i++){
nums[i] = start + 2*i;
}
int xor = nums.Aggregate((x, y) => x ^ y);
return xor;
}
}
<file_sep>class Solution {
func average(_ salary: [Int]) -> Double {
}
}
<file_sep>class Solution {
func isPalindrome(_ x: Int) -> Bool {
var initialNumber = x
var reverseNumber = 0
while initialNumber > 0 {
reverseNumber = reverseNumber * 10 + initialNumber % 10
initialNumber = initialNumber / 10
}
return x == reverseNumber
}
}
<file_sep>class Solution {
public void reverseString(char[] s) {
final StringBuilder builder = new StringBuilder(s);
int length = builder.length();
for (int i = 0; i < length / 2; i++) {
final char current = builder.charAt(i);
final int otherEnd = length - i - 1;
builder.setCharAt(i, builder.charAt(otherEnd));
builder.setCharAt(otherEnd, current);
}
return builder.toString();
}
}
<file_sep>public class Solution {
public int MaximumWealth(int[][] accounts) {
int result = 0;
int tempResult = 0;
for (int n = 0; n < accounts.Length; n++) {
for (int k = 0; k < accounts[n].Length; k++) {
tempResult += accounts[n][k];
if(result < tempResult){
result = tempResult;
}
}
tempResult = 0;
}
return result;
}
}
<file_sep># LeetCode
My solutions for LeetCode challenges
Progress: !!!
<file_sep>public class Solution {
public string ToLowerCase(string str) {
String output = "";
for (int i = 0; i < str.Length; i++)
{
if (str[i] >= 'A' && str[i] <= 'Z')
{
output += (char)(str[i] - 'A' + 'a');
}
else
output += str[i];
}
return output;
}
}
<file_sep>using System;
using System.Linq;
public class Solution {
public bool IsPalindrome(int x) {
return x.ToString().SequenceEqual(myString.Reverse());
}
}
<file_sep>public class Solution {
public int[] Decode(int[] encoded, int first) {
int[] myNum = {10, 20, 30, 40};
return myNum;
}
}
| 37e85552e6479d52df9a238f54351a2935d43378 | [
"Markdown",
"Swift",
"C#",
"Java",
"C++"
] | 17 | Java | Inquis1t0r/LeetCode | 0dce4a4d96040b42641130d3c73ad21859bef772 | f8691dd4f8dedac2f9bbe7ac4e12061f00ea84d4 |
refs/heads/master | <file_sep>import platform
from .Encrypt import RainEncrypt
from .core.directory_iter import DirectoryIter
class RainDecrypt(RainEncrypt):
"""
Class intends to reverse the affects of RainEncrypt
Example Usage:
RainDecrypt("AES.key").do_final()
"""
def __init__(self, aes_key_file_path):
# instantiate super gives access to self.crypto and self.paths
super().__init__(password=open(aes_key_file_path).read())
def __remove_back_ground_windows(self):
"""
Deletes back ground image and restores original
I'll leaves this for you to implement
"""
pass
def __remove_startup_windows(self):
"""
Delete startup registry keys and removes startup files
I'll leaves this for you to implement
"""
pass
def __disinfect_all(self):
"""
Iterate through target directories and decrypts each individual file
Works for all platforms
"""
for path in self.paths:
for file in DirectoryIter(path).iter_files(path):
self.__decrypt(file)
def __decrypt(self, file_name: str):
"""
Checks if file ends with the rain extension, if so it will
attempt to decrypt it otherwise will ignore
:param file_name: file to decrypt
"""
if file_name.endswith(".rain"):
self.crypto.decrypt_file(file_name, inplace=True)
def do_final(self, **kwargs):
"""
Consider this the entry for the decrypter
"""
self.__disinfect_all()
if platform.system() == "windows": # windows only functions
self.__remove_back_ground_windows()
self.__remove_startup_windows()
<file_sep>import os.path as op
import os
from os import scandir
import types
class DirectoryIter:
"""
produces an iterator for a file tree
"""
def __init__(self, path):
if not op.exists(path):
FileNotFoundError(path)
self.path = path
def iter_files(self, path: str) -> types.GeneratorType:
"""
Recursively yield DirEntry objects for given directory
"""
for entry in scandir(path):
if entry.is_dir(follow_symlinks=False):
yield from self.iter_files(entry.path)
else:
yield entry.path
def iter_directories(self) -> types.GeneratorType: # consider os.scandir()
"""
iteratively yield directories
"""
for root, dirs, files in os.walk(self.path):
for dir in dirs:
yield os.path.join(root, dir)
<file_sep>from os import getenv, system, path
from Crypto import Random
import platform
from shutil import copyfile
from winreg import *
from .core.crypto import Crypto
from .core.directory_iter import DirectoryIter
class RainEncrypt:
"""
Class executes the main bulk of the rain ransom-wares payload, I believe the extra
utc and av disabling functionality are in bat files but can be ported
Example Usage:
RainEncrypt().do_final()
"""
__APPDATA = getenv('APPDATA')
__EXT = (i.replace("*", "") for i in
['*.txt', '*.lnk', '*.application', '*.veg', '*.doc', '*.pdf', '*.jpg', '*.gif', '*.png', '*.bitmap'
, '*.mp4', '*.avi', '*.zip', '*.wav', '*.svg', '*.mdb', '*.rar', '*.tar', '*.xf', '*.gz'
, '*.sqlite3', '*.mov', '*.pptx', '*.pptm', '*.xlsx', '*.xlsm', '*.aes', '*.accdb', '*.bmp'
, '*.mpeg', '*.sql', '*.sqlitedb', '*.jar', '*.java', '*.cdr', '*.vssettings', '*.vbs', '*.vssx'
, '*.cpp', '*.c', '*.NET', '*.rb', '*.sh', '*.appref-ms', '*.html', '*.css', '*.sublime-package'
, '*.bz2', '*.iso', '*.img', '*.sfk', '*.mkv', '*.psd', '*.xz', '*.7z', '*.gz', '*.mid', '*.wmv'
, '*.mov', '*.cdr', '*.ai', '*.tif', '*.fla', '*.swf', '*.dwg', '*.mpg', '*.xls', '*.docx', '*.rtf'
, '*.pps', '*.ppt', '*.pptx', '*.ppsx', '*.ico', '*.3gp', '*.dxf', '*.eps', '*.max', '*.nrg', '*.ogg'
, '*.pic', '*.php', '*.qxd', '*.rm', '*.swf', '*.vob', '*.wri', '*.vbs', '*.chc', '*.real', '*.list'
, '*.desktop', '*.so', '*.json', '*.new', '*.bkp', '*.bak', '*.tmp', '*.gho', '*.mp3'])
def __init__(self, password: str = Random.new().read(32)):
self.crypto = Crypto(password, <PASSWORD>")
self.paths = (path.expanduser('~/Desktop'),
path.expanduser('~/Área de trabalho'),
path.expanduser('~/Documents'),
path.expanduser('~/Documentos'),
path.expanduser('~/Downloads'))
def __enable_run_at_start_windows(self, self_file_name: str):
"""
Windows only function
Not entirely sure on the logic here and why the need for 3 start up locations
I copied it from your original code and removed a copy to documents
:param self_file_name: file to stat up at logon
"""
copyfile(self_file_name, 'C:/Users/Public/AdobeAAMUpdater.exe')
copyfile(self_file_name,
self.__APPDATA + r'\Microsoft\Windows\Start Menu\Programs\Startup\AdobeAAMCCUpdater.exe')
try:
# this will start up for all users, not recommended unless shared folders such as ProgramFiles are targeted
key = CreateKey(HKEY_LOCAL_MACHINE, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run') # privileged request
except PermissionError:
# in case program is not admin, startup will only run for current user this makes more sense
# as only the current users docs, desktop, etc are encrypted
key = CreateKey(HKEY_CURRENT_USER, r'SOFTWARE\Microsoft\Windows\CurrentVersion\Run')
SetValueEx(key, "AdobeAAM", 0, REG_SZ, 'C:\\Users\\Public\\AdobeAAMUpdater.exe')
SetValueEx(key, "AdobeAAMCC", 0, REG_SZ,
self.__APPDATA + '\\Microsoft\\Windows\\Start Menu\\Programs\\Startup\\AdobeAAMUpdater.exe')
def __set_back_ground_windows(self, bg: bytes):
open("bg.jpg", 'wb').write(bg)
copyfile("bg.jpg",
self.__APPDATA + "\\Microsoft\\Windows\\Themes\\TranscodedWallpaper") # not sure if this correct
# refresh explorer
system("taskkill /f /IM explorer.exe")
system("start C:/Windows/explorer.exe")
def __infect_all(self):
"""
Walk directories directories specified in self.paths and encrypt files
"""
for path_ in self.paths:
for file in DirectoryIter(path_).iter_files(path_):
self.__crypt(file)
def __crypt(self, file_name: str):
"""
Checks if file ends with extension to encrypt, then encrypts in place (deletes original)
:param file_name: file to encrypt
"""
for ext in self.__EXT:
if file_name.endswith(ext): # checks if file is in list of extensions to encrypt
self.crypto.encrypt_file(file_name, inplace=True)
def do_final(self, to_run_at_startup=str()):
"""
Consider this the entry point, will encrypt target files
then change background and adds startup entries (depending on platform)
"""
self.__infect_all() # encrypt all target location works for both windows an linux
self.crypto.dump_key() # dumps aes password to disk (required for decrypt)
del self.crypto # delete encryption object (helps keep keys out of memory but not reliable)
if platform.system() == "windows": # windows only functions
if to_run_at_startup: # if a startup path was specified
self.__enable_run_at_start_windows(to_run_at_startup) # run another path at startup e.g. gui
self.__set_back_ground_windows(open("bg.jpg", "rb").read()) # replace background
<file_sep># RainRansomware
Interested in the word ransomware in the repository? Do you like cryptography? Or just want to fuck some people's computer? Right. I'm developing this ransomware, and its name is Rain (kek), after all, when any ransomware starts its standard process is like acid rain. I am using 32-byte AES encryption and I want to add other related features as I learn how other forms of encryption work. Its first version is being written in Python and later I intend to pass it to C ++ as well. You can also help me if you want, I need to compile the code in py so that I have an exe file, and at the moment I do not know how to do this with so many libraries contained in the project. Everything will be appreciated, from testing the malware to adding the most useful features. Rain Ransomware works like this:
- Firstly it imports some libraries to facilitate the run in directories and other manipulations of the OS (glob, the, pycrypto, platform, etc)
- Checks if the OS of the infected machine is Linux or Windows, executing two different structures for each one
- After the scan creates some malicious files useful for malware persistence, deactivating native antivirus and UAC, besides adding a registry in the machine (Windows only, for now)
- Encrypts files with certain extensions (new extensions are welcome) in three main directories, which usually save the most important files (Desktop, Documents and Downloads)
- Swap Desktop Background for malware logo
- It continues encrypting the entire partition in question
Suggestions for improvements? Please leave them there. Let's make this something more than an ambitious teen project.
Contact me:
<EMAIL>
<EMAIL>
Changes:
- Complete restructure/rebuild using oop
- Removed "partition" encryption functionality as it would take too long and the important files such as documents, desktop, etc are already encrypted
- The password used to derive the AES key is dumped to disk once encryption is complete this is obviously in secure but allows for decryption. A better approach would be the encrypt the password with an RSA public key before dumping and keep a private copy of the private key. Then when you want to decrypt the files just decrypt the AES password and feed it into the RainDecrypter class.
- Added an encryption class which uses secure key div and encrypts in blocks
- Added a much quicker file iteration/directory walking class
- Comments and Docs (where relevant)
TODO's/Considerations:
- It is possible to specify resource files with pyinstaller instead on embedding them into the source, look at the `__set_back_ground_windows` method to gauge a better understanding.
- I haven't got round to testing the scripts so I’m not sure how well it will work but the added classes have been toughly tested and work as intended.
- When I get a chance, I'll build a exe using pyinstaller
- Two functions in the RainDecrypt are incomplete I’ll leave them to you
- Use a IDE something like PyCharm it helps to keep your code tidy and types consistent
I was kinda board so decide to commit to your project. Any issues or features you want to add let me know.
<file_sep>"""
Minor changes for compatibility with 3.7
"""
import os
import struct
import hashlib
from Crypto.Cipher import AES
from Crypto import Random
class Crypto:
def __init__(self, password: str, extension: str):
self.password = <PASSWORD>
self.__dk = self.__derive_key(password)
self.extension = extension
def dump_key(self, out_path="AES.key"):
open(out_path, "w").write(self.password)
@staticmethod
def __derive_key(password):
"""
Derives cryptographic key using pbkdf2 key derivation scheme
salt = sha3_256 digest of password string, 16 bytes as recommended
"""
salt = hashlib.sha3_256(password.encode()).digest()
return hashlib.pbkdf2_hmac("sha256", password.encode(), salt, 100000)
def encrypt_file(self, in_filename: str, inplace=False, chunksize: int = 64 * 1024):
""" Encrypts a file using AES (CBC mode) with the
given key.
:param: key: The encryption key - a string that must be
either 16, 24 or 32 bytes long. Longer keys
are more secure.
:param: in_filename: Name of the input file
:param: inplace: encrypt inplace
:param: chunksize: Sets the size of the chunk which the function
uses to read and encrypt the file. Larger chunk
sizes can be faster for some files and machines.
chunksize must be divisible by 16.
"""
out_filename = in_filename + self.extension
iv = Random.new().read(AES.block_size)
encryptor = AES.new(self.__dk, AES.MODE_CBC, iv)
fsize = os.path.getsize(in_filename)
with open(in_filename, 'rb') as infile, open(out_filename, 'wb+') as outfile:
outfile.write(struct.pack('<Q', fsize))
outfile.write(iv)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 != 0:
chunk += b' ' * (16 - len(chunk) % 16)
outfile.write(encryptor.encrypt(chunk))
outfile.seek(0)
if inplace:
os.remove(in_filename)
return out_filename
def decrypt_file(self, in_filename, out_filename=None, inplace=False, chunksize=64 * 1024):
""" Decrypts a file using AES (CBC mode) with the
given key. Parameters are similar to encrypt_file,
with one difference: out_filename, if not supplied
will be in_filename without its last extension
(i.e. if in_filename is 'aaa.zip.enc' then
out_filename will be 'aaa.zip')
"""
if out_filename is None:
out_filename = os.path.splitext(in_filename)[0]
with open(in_filename, 'rb') as infile:
origsize = struct.unpack('<Q', infile.read(struct.calcsize('Q')))[0]
iv = infile.read(16)
decryptor = AES.new(self.__dk, AES.MODE_CBC, iv)
with open(out_filename, 'wb') as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(origsize)
if inplace:
os.remove(in_filename)
return out_filename
| 34b4fc4d574ab67d80860ee1510edef24fd6014d | [
"Markdown",
"Python"
] | 5 | Python | netindiapro/RainRansomware | 48f232d0b3174c4d1636d55faf10165b801a80ed | 07b3e88d6c840386f99c271f250154c4acb9150f |
refs/heads/master | <file_sep># Bioinformatics
b
<file_sep>#Functional programming in python
#Don’t iterate over lists. Use map and reduce.
#1. Maps: Takes a collection and returns a new one after transforming its elements all in the same way
a=['Hello','World','Okay','cool']
b=map(len, a)
print(list(b))
#map(function, list) -> General syntax
#2. Lambda (Anonymous function)
sum= lambda a,b:a+b
print(sum(1,4))
fact=lambda a: a*fact(a-1) if a>1 else 1 #notice this carefully - recursive lambda lel
#a=lambda(value(s), return value) ->General syntax
#3. Reduce: Takes a function and a collection, returns a single value created by combining the items in the collection
from functools import reduce
s=reduce(lambda a,x:a+x,list(range(10))) #here, a is called the accumulator and x is the current item being iterated
print(s)
fsum=reduce(lambda a,b:fact(a)+fact(b),list(range(4)))
print(fsum)
#a=reduce(function, values, inital value of accumulator{optional})-> General syntax
#4. Filter (Filters a list{duh})
isEven= lambda x: True if x%2==0 else False
m=filter(isEven,list(range(100)))
print(list(m))
#a=filter(boolean function, list)->general syntax
<file_sep>#Essential python because you keep forgetting you sore loser
print('hi'*4)
print(bool(42),bool('')) #blank string is false. All other strings are true
for i in range (12,15):
print(i) #prints from 12-15, 15 being exclusive
from sys import exit
#using sys.exit() clears the program lol
#------------------------------------------------------------------------------------------------
#User defined functions
def hello(name):
print(name)
#Name is the function parameter, and the value passed to this parameter is called the argument
print(None) #similar to void, it is not a string. It is a datatype on its own
#Scope
#Each function has its own local scope and each program has one global scope
#Local var destroyed when function terminates and global var when program terminates
#local is given preference if both exist
#To check if a var is global or local, check where it has been declared
#------------------------------------------------------------------------------------------------------------
#Error handling
try:
x=42/0
print(x)
except:
print('Divide by zero error')
#------------------------------------------------------------------------------------------------------------------------
print([1,2,3,4,5,6,7][1]) #lol
print([1,2,3,4,5,6,7][-3])
a=[1,2,3,4,5,6,76,7]
print(a[2:5]) #exclusive of 5 and inclusive of 2, same works for tuples
#Lists have no fixed size, so overwriting 3 elements with 4 increases the size of the list and does not return an error
del a[2] #removes the element and leaves no gap
print(a)
print(list(range(10)))
for i in [1,4,7]:
print(i)
#multiple assignments
a,b,c=1,2,3
a,b=b,a
print(a,b)
#some list functions
print([1,2]*3)
print(list('lamao'))
a=list(range(10))
import random
if random.randint(1,20) not in a: #in and not in used to check if element in or not in the list
print('yes')
else:
print('no')
#list methods:
print(a.index(5))
#list. append(a), list.insert(a,b), list.remove(a) and list.sort() are all list methods
#strings and tuples are immutable, lists are mutable data types
#mutable data types can be modified
#When mutable values are passed to functions, it is known as pass by reference
#to overwrite the default way of copying references, use deepcopy() function
a=[1,2,3]
from copy import deepcopy
b=deepcopy(a)
#now any changes made to a will not be reflected in b
#-----------------------------------------------------------------------------------------------------------------------
#dictionaries
cat={'size':'fat','color':'white','age':5}
print(cat['size'])
#dictionaries are mutable
print(list(cat.keys())) #['size', 'color', 'age']
print(list(cat.values())) #['fat', 'white', 5]
print(list(cat.items())) #[('size', 'fat'), ('color', 'white'), ('age', 5)], it'a a list of tuples
for i in cat.items():
print(i)
import random
print()
print(random.choice(list((cat.items()))))#prints a random dictionary element
#get() method to obtain values from a dictionary
print(cat.get('name',0))#returns 0 if the value to that key is not found
#adding values to a dictionary
cat.setdefault('name','kitty') #adds the value kitty to the key name, remains unchaged if the key already exists
#use the above method to count the occurence of each letter in a sentence
from pprint import pprint
pprint(cat) #pretty print module is better off for printing dictionaries
#-----------------------------------------------------------------------------------------------------------------------
#strings can also have indices and slices, in and not in statements can be used
#raw strings:
print(r'this is \a raw string')
#string methods:
#1. boolean: isaplha(), isalnum(), isspace(), isdecimal()
#2. join and split:
a=['Hello','Okay']
print(' '.join(a))#notice the whitespace
a='Hello okay'
print(a.split())
print(a.split('o'))#another way of using split
#instead of using %s in strings, use .format() function
print('{} is how it\'s done'.format('Okay, this'))#neat
#---------------------------------------------------------------------------------------------------------
#---------------------------------------------------------------------------------------------------------
#list comprehensions in python
celsius=[3,43,2335,232,0,-40,22]
faranheit=[float(9/5)*x+32 for x in celsius]
print(faranheit)
#List comprehensions are neat af and can be used for complicated things
pytriplet=[(x,y,z) for x in range(1,30) for y in range(x,30) for z in range(y,30) if x**2+y**2==z**2] #holy shit
print(pytriplet)
#Sets in python
a=set()
a.update([1,2]) #set is an unordered collection of data. Redundant items are removed
x=[1,1,1,2,3,4,3,4,3,2,1,2,3,4,4,3,2,2,2]
x=list(set(x))
print(x)#[1,2,3,4]
#enum function in string/list
s='okay'
print(list(enumerate(s)))#notice that it is a list of TUPLES
#file handling
import os
print(os.getcwd())#gives the current working directory
#os.chdir(#path)- changes the path of the terminal
#absolute and relative paths:
#.->current directory
#..->Parent directory
print()
#plain text files:
#1. Call the open() function to return a file object
#2. Call read() or write() method on file object (default mode is read mode)
#3. Close the file by calling close() method on file object
f=open(r'C:\Users\<NAME>\Desktop\ok cool.txt') #f is the file object
a=f.read() #this contains the text stored in the file as a string
print(a) #prints the text in the file
f.close()
#opening the files in different modes
#1. Write mode, which overwrites the existing text
f=open(r'C:\Users\<NAME>\Desktop\ok cool.txt','w')#notice the ,'w'
f.write('Hello world this is in write mode')
f.close()
#2. Append mode
f=open(r'C:\Users\<NAME>\Desktop\ok cool.txt','a')
f.write('. I am continuing the previous text in append mode. Lol')
f.close()
#------------------------------------------------------------------------------------------------------------
#------------------------------------------------------------------------------------------------------------
#class is a blueprint for an object
def main():
print('Sample text in main')
class Duck:
def quack(self):
print('Quack')
def walk(self):
print('The duck is walking')
#object is an instance of the class
donald=Duck()
donald.quack()
donald.walk()
#self and init:
#__init__ works like a constructor and is used to initialize values passed to objects of a class
#since python is an interpreter, and functions defined after main() won't be recognized unless this line is added:
if __name__=="__main__":
main() #because of the location of this statement, main is executed after this line is interpreted
#Create your objects within main
#self is an instance of the class, with which we access the attributes of a class
#-----------------------------------------------------------------------------------------------------------------
#-----------------------------------------------------------------------------------------------------------------
<file_sep>#Binary search
x,a=input().split(),input()
u=int(len(x))
l=0
for i in x:
m=int((u+l)/2)
if a<x[m]:
u=m-1
if a>x[m]:
l=m+1
if a==x[m]:
print('Located at '+str(m)+' index')
exit()
| 909acc6cc0fae97e680d2ff089b72e9251b372fc | [
"Markdown",
"Python"
] | 4 | Markdown | s-bhat99/Bioinformatics | c7ba3d949a5c6d7de6d6227714cb9a90462c1f61 | 98342e729fd2e07b18d594182cf94b0a1b965afd |
refs/heads/main | <file_sep># hometasks
Storage repository for "Junior Test Automation Engineer in Java" course
<file_sep>Java - original pretty version
=======================
* <NAME>
* <NAME>
Java - final corrupted version with voilations
=======================================
* <NAME>
JS version
==========
* @SnezhanaMatskevich
C# version
==========
* @DenisChulkov<file_sep>package java_exceptions.custom_exceptions;
public class ImpossibleGradeException extends Exception {
public ImpossibleGradeException() {
}
public ImpossibleGradeException(String message) {
super(message);
}
public ImpossibleGradeException(String message, Throwable cause) {
super(message, cause);
}
public ImpossibleGradeException(Throwable cause) {
super(cause);
}
}
<file_sep>package JavaFundamentals;
import java.util.Scanner;
public class MonthsDetector {
public static void main(String[] args){
String [] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September",
"October", "November", "December"};
Scanner scan = new Scanner(System.in);
System.out.println("Please, enter an integer between 1 and 12:");
if (scan.hasNextInt()) {
int monthNum = scan.nextInt();
if (1 <= monthNum && monthNum <= 12) {
System.out.println(months[monthNum - 1]);
} else {
System.err.println("No month exists with such number");
}
} else {
System.err.println("Input is not an integer");
}
}
}
<file_sep># aircompany
Project with "code smells" for refactoring
<file_sep>package java_exceptions.groups;
import java_exceptions.interfaces.Group;
public class Sigma implements Group {
@Override
public String getName() {
return "Sigma";
}
}
<file_sep>package JavaFundamentals;
public class ReverseArguments {
public static void main(String[] args) {
for (int i = args.length; i > 0; i--) {
System.out.println(args[i-1]);
}
}
}
<file_sep>package java_exceptions.groups;
import java_exceptions.interfaces.Group;
public class Alpha implements Group {
@Override
public String getName() {
return "Alpha";
}
}
<file_sep>package java_io;
import java.io.*;
public class DirectoryScanner {
static int directoryDepth = 1;
private DirectoryScanner() {
throw new IllegalStateException("Utility class");
}
public static void directoryScanner(String directoryPath, String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
String[] sentences = directoryPath.split("\\\\");
writer.write(sentences[sentences.length - 1] + "\n");
scanDirectory(directoryPath, writer);
} catch (IOException e) {
e.printStackTrace();
}
}
private static void scanDirectory(String directoryPath, BufferedWriter writer) throws IOException {
File directory = new File(directoryPath);
File[] listFile = directory.listFiles();
if (listFile != null) {
for (File file : listFile) {
if (file.isDirectory()) {
writer.write("|"
+ new String(new char[directoryDepth]).replace("\0", "-----")
+ file.getName() + "\n");
directoryDepth++;
scanDirectory(file.toString(), writer);
directoryDepth--;
} else {
writer.write("|\t " + file.getName() + "\n");
}
}
writer.write("|" + "\n");
}
}
}
<file_sep>package java_exceptions.faculties;
import java_exceptions.interfaces.Faculty;
public class Transmutation implements Faculty {
@Override
public String getName() {
return "Transmutation";
}
}
<file_sep>package CollectionsTask;
import java.util.Comparator;
public class PreciousnessComparator implements Comparator<Gemstone> {
public int compare(Gemstone o1, Gemstone o2) {
return o1.getPreciousness().ordinal() - o2.getPreciousness().ordinal();
}
}
<file_sep>package JavaClasses;
import java.util.ArrayList;
import java.util.List;
public class ClassTask {
public static void main(String[] args) {
PatientOperations patientList = new PatientOperations();
patientList.addPatient(new Patient(132, "Волкова", "Инна", "Сергеевна",
"<NAME>-18", "103-343-535", 20645,
"Клиническая лень"));
patientList.addPatient(new Patient(5163, "Кошкин", "Евгений", "Олегович",
"<NAME>-20", "464-342-235", 2045,
"Вывих уха"));
patientList.addPatient(new Patient(93545, "Драконова", "Оксана", "Сергеевна",
"<NAME>-30", "256-846-626", 14045,
"Удлинение хвоста"));
patientList.addPatient(new Patient(725, "Вивернов", "Антон", "Василиевич",
"<NAME>-3", "951-546-225", 20345,
"Чрезмерный рост чешуи"));
patientList.addPatient(new Patient(2566, "Кобольдова", "Лиза", "Алексеевна",
"<NAME>-61", "643-754-246", 57052,
"Удлинение хвоста"));
patientList.addPatient(new Patient(753674, "Вирмов", "Алексей", "Егорович",
"<NAME>-32", "456-754-256", 15203,
"Избыточный рост рогов"));
patientList.addPatient(new Patient(4624, "Кусачева", "Валерия", "Евгеньевна",
"<NAME>", "567-234-745", 45729,
"Удлинение хвоста"));
System.out.println("Список пациентов, имеющих диагноз \"Удлинение хвоста\":");
List<Patient> patientsWithDiagnosis = patientList.findPatientsWithDiagnosis("Удлинение хвоста");
for (Patient p : patientsWithDiagnosis) {
System.out.println(p);
}
System.out.println("\nСписок пациентов, номер медицинской карты которых находится в интервале 10000-30000:");
List<Patient> patientsInRange = patientList.findPatientsWithCardNumberWithinRange(10000, 30000);
for (Patient p : patientsInRange) {
System.out.println(p);
}
}
static class Patient {
private int id;
private String name;
private String surname;
private String patronymic;
private String address;
private String phoneNumber;
private int medicalCardNumber;
private String diagnosis;
Patient(int id, String surname, String name, String patronymic, String address,
String phoneNumber, int medicalCardNumber, String diagnosis) {
this.id = id;
this.name = name;
this.surname = surname;
this.patronymic = patronymic;
this.address = address;
this.phoneNumber = phoneNumber;
this.medicalCardNumber = medicalCardNumber;
this.diagnosis = diagnosis;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public String getPatronymic() {
return patronymic;
}
public void setPatronymic(String patronymic) {
this.patronymic = patronymic;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public int getMedicalCardNumber() {
return medicalCardNumber;
}
public void setMedicalCardNumber(int medicalCardNumber) {
this.medicalCardNumber = medicalCardNumber;
}
public String getDiagnosis() {
return diagnosis;
}
public void setDiagnosis(String diagnosis) {
this.diagnosis = diagnosis;
}
@Override
public String toString() {
return String.format("id: %d, surname: %s, name: %s, patronymic: %s, address: %s, phoneNumber: %s, " +
"medicalCardNumber: %d, diagnosis: %s", id, surname, name, patronymic, address, phoneNumber,
medicalCardNumber, diagnosis);
}
}
static class PatientOperations {
List<Patient> patientList = new ArrayList<>();
public void addPatient(Patient patient) {
patientList.add(patient);
}
List<Patient> findPatientsWithDiagnosis(String diagnosis) {
List<Patient> foundPatients = new ArrayList<>();
for (Patient p : patientList) {
if (p.getDiagnosis().equals(diagnosis)) {
foundPatients.add(p);
}
}
return foundPatients;
}
List<Patient> findPatientsWithCardNumberWithinRange(int startRange, int endRange) {
List<Patient> checkedPatients = new ArrayList<>();
for (Patient p : patientList) {
if (p.getMedicalCardNumber() >= startRange && p.getMedicalCardNumber() <= endRange) {
checkedPatients.add(p);
}
}
return checkedPatients;
}
}
}
<file_sep>package CollectionsTask.classification;
public enum GemTransparency {
TRANSPARENT, SEMI_TRANSPARENT, TRANSLUCENT, SEMI_TRANSLUCENT, OPAQUE
}
<file_sep>package java_exceptions.groups;
import java_exceptions.interfaces.Group;
public class Beta implements Group {
@Override
public String getName() {
return "Beta";
}
}
<file_sep>package JavaFundamentals;
import java.util.Scanner;
import java.util.Arrays;
public class OptionalTask {
public static void main(String[] args){
Scanner scan = new Scanner(System.in);
System.out.println("Пожалуйста, введите числа: ");
String inputNumbers = scan.nextLine();
String [] splitNumbers = inputNumbers.split(" ");
if (inputNumbers.trim().isEmpty()) {
System.err.println("Не введено ни одного числа.");
System.exit(1);
}
// 1. Найти самое короткое и самое длинное число. Вывести найденные числа и их длину.
// В моей реализации при наличии чисел одинаковой длины будет выведено первое найденное, т.к. в условии это
// не оговорено.
String shortest = inputNumbers;
String longest = " ";
if (splitNumbers.length == 1) {
System.out.println("Самое короткое число: " + inputNumbers + ". Его длина составляет: " + shortest.length() +
".\nВведено всего одно число, следственно, оно так же является и самым длинным.");
} else {
for (String i : splitNumbers) {
if (i.length() < shortest.length()) { shortest = i; }
if (i.length() > longest.length()) { longest = i; }
}
System.out.println("Самое короткое число: " + shortest + ". Его длина составляет: " + shortest.length());
System.out.println("Самое длинное число: " + longest + ". Его длина составляет: " + longest.length());
}
// 2. Вывести числа в порядке возрастания (убывания) значений их длины.
int [] sortedArr = new int [splitNumbers.length];
for (int j = 0; j < splitNumbers.length; j++) {
sortedArr[j] = Integer.parseInt(splitNumbers[j]);
}
Arrays.sort(sortedArr);
System.out.print("\nЧисла в порядке возрастания длины: ");
for (int x : sortedArr) { System.out.print(x + " "); }
System.out.print("\nЧисла в порядке убывания длины: ");
for (int z = sortedArr.length; z >0; z--) {
System.out.print(sortedArr[z-1] + " ");
}
// 3. Вывести на консоль те числа, длина которых меньше (больше) средней длины по всем числам, а также длину.
float avgLength = 0;
for (String f : splitNumbers) {
avgLength += f.length();
}
avgLength = avgLength/splitNumbers.length;
System.out.print("\n\nСредняя длина введенных чисел: " + avgLength + "\nЧисла, длина которых меньше средней: ");
for (String e : splitNumbers) {
if (e.length() < avgLength) {
System.out.print(e + " ");
}
}
System.out.print("\nЧисла, длина которых больше средней: ");
for (String e : splitNumbers) {
if (e.length() > avgLength) {
System.out.print(e + " ");
}
}
// 4.Найти число, цифры в котором идут в строгом порядке возрастания. Если таких чисел несколько, найти первое
// из них.
cycle: for (String elem : splitNumbers) {
String [] splitElem = elem.split("");
for (int i = 0; i < elem.length() - 1; i++) {
if (!(Integer.parseInt(splitElem[i + 1]) == Integer.parseInt(splitElem[i]) + 1)) {
continue cycle;
}
}
System.out.println("\n\nЧисло, цифры в котором идут в строгом порядке возрастания: " + elem);
break;
}
}
}
<file_sep>package java_exceptions.custom_exceptions;
public class FacultyHasNoGroupsException extends Exception {
public FacultyHasNoGroupsException() {
}
public FacultyHasNoGroupsException(String message) {
super(message);
}
public FacultyHasNoGroupsException(String message, Throwable cause) {
super(message, cause);
}
public FacultyHasNoGroupsException(Throwable cause) {
super(cause);
}
}
<file_sep>package java_exceptions.interfaces;
public interface Subject {
int getGrade();
String getName();
}
<file_sep>package JavaFundamentals;
import java.util.Random;
public class RandomNumbers {
public static void main(String[] args) {
Random amountOfNumbers = new Random();
int [] arrayOfNumbers = new int[10];
for (int i = 0; i < arrayOfNumbers.length; i++) {
arrayOfNumbers[i] = amountOfNumbers.nextInt(100);
System.out.println(arrayOfNumbers[i]);
}
for (int j : arrayOfNumbers) {
System.out.print(j + " ");
}
}
}
<file_sep>package java_exceptions.custom_exceptions;
public class StudentHasNoSubjectsException extends Exception {
public StudentHasNoSubjectsException() {
}
public StudentHasNoSubjectsException(String message) {
super(message);
}
public StudentHasNoSubjectsException(String message, Throwable cause) {
super(message, cause);
}
public StudentHasNoSubjectsException(Throwable cause) {
super(cause);
}
}
<file_sep>package CollectionsTask.classification;
public enum GemPreciousness {
PRECIOUS_FIRST_CLASS, PRECIOUS_SECOND_CLASS, PRECIOUS_THIRD_CLASS, SEMI_PRECIOUS_FIRST_CLASS,
SEMI_PRECIOUS_SECOND_CLASS, SEMI_PRECIOUS_THIRD_CLASS, ORGANOGENIC
}
<file_sep>package java_exceptions.groups;
import java_exceptions.interfaces.Group;
public class Psi implements Group {
@Override
public String getName() {
return "Psi";
}
}
| 6d1a9f187f7cd0d05b62a6f7f5317970d00de1b0 | [
"Markdown",
"Java"
] | 21 | Markdown | LonelyDragoness/hometasks | 163db75152a39bb2f0bb9ae51858d55a37ec047f | aa6e36088d99bcd564f29cbb8fb743c35a9d8ec4 |
refs/heads/master | <file_sep><?
/*
* <NAME> (<EMAIL>) http://servicecut.nl
*
* @author <NAME>
* @version 0.0.6
*
* Adapted <NAME> TwitterOAuth class for use with FacebookOAuth
*/
/**
* Facebook OAuth 2 class
*/
class FacebookOAuth {
/* Verify SSL Cert. */
public $verifypeer = FALSE;
/* Decode returned json data. */
public $decode_JSON = TRUE;
/* Set connect timeout. */
public $connecttimeout = 30;
/* Set timeout default. */
public $timeout = 30;
/* Set the useragent. */
public $useragent = "FacebookOAuth v0.0.6 | http://github.com/Zae/FacebookOAuth";
/* HTTP Proxy settings (will only take effect if you set 'behind_proxy' to true) */
public $proxy_settings = array(
'behind_proxy' => false,
'host' => '',
'port' => '',
'user' => '',
'pass' => '',
'type' => CURLPROXY_HTTP,
'auth' => CURLAUTH_BASIC
);
/* Contains the last HTTP status code returned. */
public $http_code;
/* Contains the last HTTP headers returned. */
public $http_info = array();
/* Contains the last API call. */
public $url;
/* Contains last http_headers */
public $http_header = array();
/* Variables used internally by the class and subclasses */
protected $client_id, $client_secret, $access_token, $expires;
protected $callback_url;
protected static $METHOD_GET = "GET";
protected static $METHOD_POST = "POST";
protected static $METHOD_DELETE = "DELETE";
/**
* Set API URLS
*/
const AuthorizeUrl = 'https://graph.facebook.com/oauth/authorize';
const AccessTokenUrl = 'https://graph.facebook.com/oauth/access_token';
const GraphUrl = 'https://graph.facebook.com/';
const ApiUrl = 'https://api.facebook.com/method/';
/**
* construct FacebookOAuth object
*/
function __construct($client_id, $client_secret, $callback_url = NULL, $access_token = NULL){
$this->client_id = $client_id;
$this->client_secret = $client_secret;
$this->callback_url = $callback_url;
$this->access_token = $access_token;
}
/**
* Get the authorize URL
*
* @returns a string
*/
public function getAuthorizeUrl($scope=NULL){
$params = array();
$params["client_id"] = $this->client_id;
if(!empty($this->callback_url)){
$params["redirect_uri"] = $this->callback_url;
}
if(is_array($scope)){
$params["scope"] = implode(",", $scope);
}elseif($scope != NULL){
$params["scope"] = $scope;
}
return self::AuthorizeUrl."?".OAuthUtil::build_http_query($params);
}
/**
* Exchange verify code for an access token
*
* @returns mixes On success it returns access_token and without offline_access also expires, On error the error message.
*/
public function getAccessToken($code){
$params = array();
$params["client_id"] = $this->client_id;
$params["client_secret"] = $this->client_secret;
$params["code"] = $code;
if(!empty($this->callback_url)){
$params["redirect_uri"] = $this->callback_url;
}
$url = self::AccessTokenUrl."?".OAuthUtil::build_http_query($params);
$contents = $this->http($url, self::$METHOD_GET);
if($this->http_code == 200){
parse_str($contents, $vars);
$this->access_token = $vars['access_token'];
if(!empty($vars['expires'])) $this->expires = (time() + $vars['expires']);
return $vars;
}
//if the http status is not 200 OK, return the content to see the errors.
return $this->decode_JSON ? json_decode($contents) : $contents;
}
/**
* GET wrapper for http.
*/
public function get($location, $fields = NULL, $introspection = FALSE){
$params = array();
if(!empty($this->access_token)){
$params["access_token"] = $this->access_token;
}
if(!empty($fields)){
$params["fields"] = $fields;
}
if($introspection){
$params["metadata"] = 1;
}
$url = self::GraphUrl.OAuthUtil::urlencode_rfc3986($location)."?".OAuthUtil::build_http_query($params);
$response = $this->http($url, self::$METHOD_GET);
return $this->decode_JSON ? json_decode($response) : $response;
}
/**
* Method to do FQL queries in the graph.
* @param string $query The query to be performed.
* @return mixed The results from the query.
*
* @since 0.0.5
*/
public function fql($query){
$params = array();
$params['format'] = 'json';
$params['query'] = $query;
if(!empty($this->access_token)){
$params["access_token"] = $this->access_token;
}
$url = self::ApiUrl.'fql.query?'.OAuthUtil::build_http_query($params);
$response = $this->http($url, self::$METHOD_GET);
return $this->decode_JSON ? json_decode($response) : $response;
}
/**
* GET IDS wrapper for http.
*
*@ids comma separated list of ids
*/
public function get_ids($ids){
$params = array();
if(is_array($ids)){
$params["ids"] = implode(",", $ids);
}else{
$params["ids"] = $ids;
}
if(!empty($this->access_token)){
$params["access_token"] = $this->access_token;
}
$url = self::GraphUrl."?".OAuthUtil::build_http_query($params);
$response = $this->http($url, self::$METHOD_GET);
return $this->decode_JSON ? json_decode($response) : $response;
}
/**
* POST wrapper for http.
*/
public function post($location, $postfields = array()){
$url = self::GraphUrl.OAuthUtil::urlencode_rfc3986($location);
if(!empty($this->access_token)){
$postfields["access_token"] = $this->access_token;
}
$response = $this->http($url, self::$METHOD_POST, $postfields);
return $this->decode_JSON ? json_decode($response) : $response;
}
/**
* DELETE wrapper for http.
*/
public function delete($location, $postfields = array()){
$url = self::GraphUrl.OAuthUtil::urlencode_rfc3986($location);
$postfields = array();
if(!empty($this->access_token)){
$postfields["access_token"] = $this->access_token;
}
$response = $this->http($url, self::$METHOD_DELETE, $postfields);
return $this->decode_JSON ? json_decode($response) : $response;
}
/**
* Make an HTTP request
*
* @return API results
*/
private function http($url, $method = "GET", $postfields=NULL){
$this->http_info = array();
$handle = curl_init();
/* Curl settings */
curl_setopt($handle, CURLOPT_HEADER, FALSE);
curl_setopt($handle, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($handle, CURLOPT_PROTOCOLS, CURLPROTO_HTTPS);
curl_setopt($handle, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($handle, CURLOPT_SSL_VERIFYPEER, $this->verifypeer);
curl_setopt($handle, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
curl_setopt($handle, CURLOPT_TIMEOUT, $this->timeout);
curl_setopt($handle, CURLOPT_USERAGENT, $this->useragent);
curl_setopt($handle, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
if ($this->proxy_settings['behind_proxy']){
curl_setopt($ci, CURLOPT_PROXY, $this->proxy_settings['host']);
curl_setopt($ci, CURLOPT_PROXYPORT, $this->proxy_settings['port']);
curl_setopt($ci, CURLOPT_PROXYUSERPWD, "{$this->proxy_settings['user']}:{$this->proxy_settings['pass']}");
curl_setopt($ci, CURLOPT_PROXYTYPE, $this->proxy_settings['type']);
curl_setopt($ci, CURLOPT_PROXYAUTH, $this->proxy_settings['auth']);
}
switch($method){
case self::$METHOD_POST:
curl_setopt($handle, CURLOPT_POST, TRUE);
if (!empty($postfields)) {
curl_setopt($handle, CURLOPT_POSTFIELDS, $postfields);
}
break;
case self::$METHOD_DELETE:
curl_setopt($handle, CURLOPT_CUSTOMREQUEST, 'DELETE');
if (!empty($postfields)){
$url .= "?".OAuthUtil::build_http_query($postfields);
}
break;
}
curl_setopt($handle, CURLOPT_URL, $url);
$response = curl_exec($handle);
$this->http_code = curl_getinfo($handle, CURLINFO_HTTP_CODE);
$this->http_info = array_merge($this->http_info, curl_getinfo($handle));
$this->url = $url;
curl_close($handle);
return $response;
}
/**
* Get the header info to store.
*/
function getHeader($ch, $header) {
$i = strpos($header, ':');
if (!empty($i)) {
$key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
$value = trim(substr($header, $i + 2));
$this->http_header[$key] = $value;
}
return strlen($header);
}
/**
* Helper method to parse signed requests from facebook.
* @param string $signed_request The request to be parsed
* @param string $secret OPTIONAL, will use the client_secret set in the constructor if empty.
* @return null/mixed null on error else the data will be returned.
*
* @uses hash_hmac, base64_url_decode, json_decode
*
* @since 0.0.6
*/
public function parse_signed_request($signed_request, $secret=null) {
$secret = empty($secret) ? $this->secret : $secret;
list($encoded_sig, $payload) = explode('.', $signed_request, 2);
// decode the data
$sig = $this->base64_url_decode($encoded_sig);
$data = json_decode($this->base64_url_decode($payload), true);
if (strtoupper($data['algorithm']) !== 'HMAC-SHA256') {
error_log('Unknown algorithm. Expected HMAC-SHA256');
return null;
}
// check sig
$expected_sig = hash_hmac('sha256', $payload, $secret, $raw = true);
if ($sig !== $expected_sig) {
error_log('Bad Signed JSON signature!');
return null;
}
return $data;
}
/**
* Method to decode the request string.
* @param mixed $input The request string
* @return mixed The decoded data
*
* @since 0.0.6
*/
protected function base64_url_decode($input) {
return base64_decode(strtr($input, '-_', '+/'));
}
}
/**
* OAuthUtil
* Copied and adapted from http://oauth.googlecode.com/svn/code/php/
*
* Creates the needed functions if the full OAuthUtil class isn't loaded.
*/
if(!class_exists('OAuthUtil')){
class OAuthUtil {
public static function urlencode_rfc3986($input) {
if (is_array($input)) {
return array_map(array('OAuthUtil', 'urlencode_rfc3986'), $input);
} else if (is_scalar($input)) {
return str_replace(
'+',
' ',
str_replace('%7E', '~', rawurlencode($input))
);
} else {
return '';
}
}
public static function build_http_query($params) {
if (!$params) return '';
// Urlencode both keys and values
$keys = OAuthUtil::urlencode_rfc3986(array_keys($params));
$values = OAuthUtil::urlencode_rfc3986(array_values($params));
$params = array_combine($keys, $values);
// Parameters are sorted by name, using lexicographical byte value ordering.
// Ref: Spec: 9.1.1 (1)
uksort($params, 'strcmp');
$pairs = array();
foreach ($params as $parameter => $value) {
if (is_array($value)) {
// If two or more parameters share the same name, they are sorted by their value
// Ref: Spec: 9.1.1 (1)
// June 12th, 2010 - changed to sort because of issue 164 by hidetaka
sort($value, SORT_STRING);
foreach ($value as $duplicate_value) {
$pairs[] = $parameter . '=' . $duplicate_value;
}
} else {
$pairs[] = $parameter . '=' . $value;
}
}
// For each parameter, the name is separated from the corresponding value by an '=' character (ASCII code 61)
// Each name-value pair is separated by an '&' character (ASCII code 38)
return implode('&', $pairs);
}
}
}
?> | 320b8875e06dad55d0260787f2722b5e1c4dc0a7 | [
"PHP"
] | 1 | PHP | Zae/FacebookOAuth | fd87f1bfdfa5c9763517f06770277a74c3779774 | 7680834f830858013ee126574c0b759810f9a6be |
refs/heads/master | <file_sep>export enum TestConfiguration {
integration = 1,
integrationWithFileGeneration = 2,
isolated = 3
}
<file_sep>import * as spauth from 'node-sp-auth';
import { IAuthOptions, IAuthResponse } from "node-sp-auth";
import * as request from 'request-promise';
import { IMockSPHttpClient } from '.';
import { NodeSPHttpResponse } from '../models';
export class NodeSPHttpClient implements IMockSPHttpClient {
protected credentails: IAuthOptions;
protected siteUrl: string;
protected authResponse: IAuthResponse;
constructor(siteUrl: string, credentialOptions: IAuthOptions) {
this.credentails = credentialOptions;
this.siteUrl = siteUrl;
}
public async init(): Promise<void> {
await this.getAuthenticationHeaders();
}
public async get<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>> {
const authHeaders = await this.getAuthenticationHeaders();
let requestOptions = options || {};
requestOptions.headers = { ...requestOptions.headers, ...authHeaders };
requestOptions.headers.accept = requestOptions.headers.accept || "application/json";
const response = await request.get(url, requestOptions);
return {
status: response,
ok: true,
json: () => { return Promise.resolve(JSON.parse(response)); },
text: () => { return Promise.resolve(response); }
}
}
public async post<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>> {
const authHeaders = await this.getAuthenticationHeaders();
let requestOptions = options || {};
requestOptions.headers = { ...requestOptions.headers, ...authHeaders };
requestOptions.headers.accept = requestOptions.headers.accept || "application/json";
requestOptions.headers['content-type'] = requestOptions.headers['content-type'] || "application/json";
try {
const response = await request.post(url, requestOptions);
return {
status: response,
ok: true,
json: () => { return Promise.resolve(JSON.parse(response)); },
text: () => { return Promise.resolve(response); }
}
}
catch (err) {
throw err;
}
}
/**
* Method returns AuthenticationHeaders for current site collection.
* @param siteUrl
* @param credentialsOptions
*/
protected async getAuthenticationHeaders() {
if (this.authResponse) {
return this.authResponse.headers;
}
let result: IAuthResponse = await spauth.getAuth(this.siteUrl, this.credentails);
this.authResponse = result;
return this.authResponse.headers;
}
public async dispose(): Promise<void> {
return Promise.resolve();
}
}<file_sep>export * from "./TestConfiguration";<file_sep>/// <reference types="jest" />
import { assert } from "chai";
import { IAuthOptions } from "node-sp-auth/lib/src/auth/IAuthOptions";
import { TestConfiguration,MockHttpClientFactory } from "./../src/index";
const environmentConfiguration: { authenticationConfiguration: IAuthOptions, siteUrl: string, runConfiguration: TestConfiguration }
= require("./utfx.json");
jest.mock("@microsoft/sp-http", () => {
return {
SPHttpClient: {
configurations: {
v1: 1
}
}
}
});
let context;
describe("Test UTFX", () => {
beforeAll(() => {
let mockHttpClientFactory = new MockHttpClientFactory();
environmentConfiguration.runConfiguration = TestConfiguration.isolated;
context = mockHttpClientFactory.setupContextFromConfig(environmentConfiguration, "./tests/responses/Web.json");
return context.spHttpClient.init();
});
test("get web title", async () => {
let response = await context.spHttpClient.get("https://mwdevvalo.sharepoint.com/sites/tea-point/_api/web?$select=Title");
let result = await response.json();
assert.equal(result.Title,"Tea Point - English");
});
afterAll(async () => {
let disposed = await context.spHttpClient.dispose();
console.log(disposed);
});
});<file_sep>import { TestConfiguration } from "../utilities/TestConfiguration";
import { IAuthOptions } from "node-sp-auth/lib/src/auth/IAuthOptions";
export interface IEnvironmentConfiguration {
authenticationConfiguration: IAuthOptions;
siteUrl: string;
runConfiguration: TestConfiguration;
}<file_sep>import { NodeSPHttpResponse } from "../models";
export interface IMockSPHttpClient {
init(): Promise<void>;
get<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>>;
post<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>>;
dispose(): Promise<void>;
}<file_sep>import { IMockSPHttpClient } from ".";
import { NodeSPHttpResponse } from "../models/NodeSPHttpResponse";
import * as fs from "fs";
export interface IMockResponse {
url: string;
body: string;
response: string;
requestId?: string;
}
export class FileSPHttpClient implements IMockSPHttpClient {
/**
* Mocked responses to be used by the client
*/
protected Responses: IMockResponse[] = [];
/**
* The response returned in case no register response is found
*/
public NotFoundResponse: NodeSPHttpResponse<any> = {
status: 404,
ok: false,
json: () => { return Promise.resolve({ d: { message: "Not found" } }) },
text: () => { return Promise.resolve("Not found") }
};
/**
*
* @param FilePath path to the mock file (optional)
* @param Responses list of mock responses (optional)
* @param SaveFile optional flag. If true provided file with be created or overwritten with current Responses on dispose()
*/
constructor(protected FilePath?: string, Responses?: IMockResponse[], public SaveFile: boolean = false) {
this.Responses = Responses || [];
this.dispose = this.dispose.bind(this);
this.saveFile = this.saveFile.bind(this);
this.init = this.init.bind(this);
}
public async init(): Promise<void> {
let self = this;
if (this.FilePath) {
return new Promise<void>((resolve, error) => {
fs.readFile(self.FilePath, "utf8", (err, data) => {
try {
self.Responses = JSON.parse(data);
resolve();
}
catch(err){
//swallow read file exception
}
});
});
}
}
public get<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>> {
let response = this.findResponse(url, version, options);
if (!response) {
return Promise.resolve(this.NotFoundResponse);
}
return Promise.resolve({
status: 200,
ok: true,
json: () => { return Promise.resolve(JSON.parse(response)); },
text: () => { return Promise.resolve(response); }
});
}
public post<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>> {
let response = this.findResponse(url, version, options);
if (!response) {
return Promise.resolve(this.NotFoundResponse);
}
return Promise.resolve({
status: 200,
ok: true,
json: () => { return Promise.resolve(JSON.parse(response)); },
text: () => { return Promise.resolve(response); }
});
}
public async dispose(): Promise<void> {
if (this.SaveFile) {
return new Promise<void>((resolve, error) => {
this.saveFile(()=>{
resolve();
});
})
}
}
private saveFile(callback){
fs.writeFile(this.FilePath, JSON.stringify(this.Responses), callback);
}
/**
* Adds response to known responses list
* @param mockResponse the response to be added
*/
public registerResponse(mockResponse: IMockResponse) {
this.Responses.push(mockResponse);
}
protected findResponse(url: string, version: any, options?: any): string {
let responses = this.Responses.filter(resp => resp.url === url);
let response = responses[0];
if(options && options.body){
response = responses.filter(resp=>resp.body == options.body)[0];
}
if (response) {
return response.response;
}
else {
return null;
}
}
}<file_sep># mgwdev-spfx-utfx
[Link to the repo](https://github.com/mgwojciech/mgwdev-spfx-utfx)
This library will help You with writing unit tests for SPFx solutions.
There are three supported configuration You can use
1) integration - which uses credentials provided in config to connect with SharePoint and uses the connection to communicate with SharePoint whenever context.spHttpClient is used.
2) integrationWithFileGeneration - same as 1) but also generated file with responses in provided path (second argument of MockHttpClientFactory.setupContextFromConfig).
3) isolated - tests will not communicate with Your tenant. Only data provided in file will be used.
# How to use it
The scenario I had in mind is following.
You write Your test in integraation mode
Write the logic
Test passess
Switch to isolated mode
You have Your unit test!
# Installation
npm install mgwdev-spfx-utfx --save-dev
# Simpliest setup
Here is the simpliest possible test You can write.
Of course You can inject context anywhere You will need web part or extension context.
```
/// <reference types="jest" />
import { assert } from "chai";
import { MockHttpClientFactory, TestConfiguration, IMockSPHttpClient } from "mgwdev-spfx-utfx";
jest.mock("@microsoft/sp-http", () => {
return {
SPHttpClient: {
configurations: {
v1: 1
}
}
}
});
let context;
describe("Test UTFX", () => {
beforeAll(() => {
let mockHttpClientFactory = new MockHttpClientFactory();
context = mockHttpClientFactory.setupContextFromConfig({
authenticationConfiguration: {
username: "<EMAIL>@<<EMAIL>",
password: "<<PASSWORD>>",
online: true
},
siteUrl : "https://<tenant_name>.sharepoint.com",
runConfiguration: TestConfiguration.integrationWithFileGeneration
}, "./tests/responses/Web.json");
return context.spHttpClient.init();
});
test("getWebInfo (absolute)", async () => {
let response = await context.spHttpClient.get("https://<tenant_name>.sharepoint.com/sites/tea-point/_api/web?$select=Title");
let result = await response.json();
assert.equal(result.Title, "Tea Point - English");
});
test("getWebInfo (relative)", async () => {
let response = await context.spHttpClient.get("/sites/tea-point/_api/web?$select=Title");
let result = await response.json();
assert.equal(result.Title, "Tea Point - English");
});
afterAll(async() => {
await context.spHttpClient.dispose();
});
});
```
<file_sep>export interface NodeSPHttpResponse<T> {
ok: boolean;
status: number;
text: () => Promise<string>;
json: () => Promise<T>;
}<file_sep>import { IMockSPHttpClient } from ".";
import { IMockResponse } from "./FileSPHttpClient";
import { NodeSPHttpResponse } from "../models";
export class MockHttpClient implements IMockSPHttpClient {
public onRequestExecuted?: (mockResponse: IMockResponse) => void;
// TODO: Kolejność clientów jest ważna, jest to inicijalizowane w fabryce
protected mockHttpClients: IMockSPHttpClient[] = [];
constructor(mockHttpClients: IMockSPHttpClient[]) {
this.mockHttpClients = mockHttpClients;
}
public async init(): Promise<void> {
await Promise.all(this.mockHttpClients.map(client=>client.init()));
}
public async get<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>> {
for (let client of this.mockHttpClients) {
let response: NodeSPHttpResponse<T> = await client.get<T>(url, version, options);
if (response.ok) {
if (this.onRequestExecuted) {
// TODO: dodać komentarz dlaczego
this.onRequestExecuted({
url: url,
body: options ? options.body : null,
response: await response.text()
});
}
return response as NodeSPHttpResponse<T>;
}
}
}
public async post<T>(url: string, version: any, options?: any): Promise<NodeSPHttpResponse<T>> {
for (let client of this.mockHttpClients) {
let response: NodeSPHttpResponse<T> = await client.post(url, version, options);
if (response.ok) {
if (this.onRequestExecuted) {
this.onRequestExecuted({
url: url,
body: options ? options.body : null,
response: await response.text()
});
}
return response;
}
}
}
public async dispose(): Promise<void> {
await Promise.all(this.mockHttpClients.map(client=>client.dispose()));
}
}<file_sep>import { MockHttpClient } from "./MockHttpClient";
import { IMockSPHttpClient, FileSPHttpClient, NodeSPHttpClient } from ".";
import { IAuthOptions } from "node-sp-auth";
import { TestConfiguration } from "../utilities";
import { IEnvironmentConfiguration } from "../models/IEnvironmentConfiguration";
export class MockHttpClientFactory {
public getHttpClient(testConfig: TestConfiguration, filePath: string, sitesWithAuth: { siteUrl: string, credentialOptions: IAuthOptions }[]): IMockSPHttpClient {
const spClients: IMockSPHttpClient[] = [];
const fileClient: FileSPHttpClient = new FileSPHttpClient(filePath, null, testConfig === TestConfiguration.integrationWithFileGeneration);
spClients.push(fileClient);
if (testConfig === TestConfiguration.isolated) {
return new MockHttpClient(spClients);
}
for (let site of sitesWithAuth) {
spClients.push(new NodeSPHttpClient(site.siteUrl, site.credentialOptions));
}
const result = new MockHttpClient(spClients);
result.onRequestExecuted = (mockResponse) => {
fileClient.registerResponse(mockResponse);
}
return result;
}
protected getHttpClientFromConfig(environmentConfiguration: IEnvironmentConfiguration,
responseFilePath: string) {
let mockHttpClient = this.getHttpClient(environmentConfiguration.runConfiguration,
responseFilePath, [{
siteUrl: environmentConfiguration.siteUrl,
credentialOptions: environmentConfiguration.authenticationConfiguration
}]);
return mockHttpClient;
}
public setupContextFromConfig(environmentConfiguration: IEnvironmentConfiguration,
responseFilePath: string) {
let mockHttpClient = this.getHttpClientFromConfig(environmentConfiguration, responseFilePath);
return this.setupContext(environmentConfiguration.siteUrl, mockHttpClient);
}
public setupContext(siteUrl: string, spHttpClient: IMockSPHttpClient) {
const mockedSPContext = {
pageContext: {
web: {
absoluteUrl: siteUrl
}
},
spHttpClient: spHttpClient
}
return mockedSPContext;
}
}<file_sep>export * from "./FileSPHttpClient";
export * from "./IMockSPHttpClient";
export * from "./NodeSPHttpClient";
export * from "./MockHttpClientFactory";<file_sep>export * from "./NodeSPHttpResponse"; | c78e393507faaa0040d2f08e898cdc197fc0e188 | [
"Markdown",
"TypeScript"
] | 13 | TypeScript | mgwojciech/mgwdev-spfx-utfx | 462d15e2ff3cbd9592301aad2229e79576d7f911 | f58978bb4b1aac1abd80e753ebca7d3821fb586a |
refs/heads/master | <repo_name>LogicAndTrick/phoenix<file_sep>/Phoenix/Templating.php
<?php
class Templating
{
static function MakeDirs()
{
if (!file_exists(Phoenix::$app_dir.'/Cache/')) mkdir(Phoenix::$app_dir.'/Cache/');
if (!file_exists(Phoenix::$app_dir.'/Cache/Configs/')) mkdir(Phoenix::$app_dir.'/Cache/Configs/');
if (!file_exists(Phoenix::$app_dir.'/Cache/Compile/')) mkdir(Phoenix::$app_dir.'/Cache/Compile/');
if (!file_exists(Phoenix::$app_dir.'/Cache/Cache/')) mkdir(Phoenix::$app_dir.'/Cache/Cache/');
}
/**
* Create a Smarty instance with the required directories set up.
* @return Smarty The created Smarty instance
*/
static function Create()
{
Templating::MakeDirs();
$smarty = new Smarty();
$smarty->addTemplateDir(Phoenix::$app_dir.'/Views/');
$smarty->addTemplateDir(Phoenix::$phoenix_dir.'/Views/');
$smarty->setConfigDir(Phoenix::$app_dir.'/Cache/Configs/');
$smarty->setCompileDir(Phoenix::$app_dir.'/Cache/Compile/');
$smarty->setCacheDir(Phoenix::$app_dir.'/Cache/Cache/');
$smarty->addPluginsDir(Phoenix::$phoenix_dir.'/Libs/Smarty.Phoenix');
if (is_dir(Phoenix::$app_dir.'/Plugins'))
{
$smarty->addPluginsDir(Phoenix::$app_dir.'/Plugins');
}
$smarty->assign(Templating::$page_data);
return $smarty;
}
/**
* The name of the master page to use.
* @var string
*/
static $master_page = 'Shared/Master';
/**
* The master page data that will be rendered.
* @var array
*/
static $page_data = array();
/**
* Placeholder data set by {content} tags and retrieved by {placeholder} tags.
* @var array
*/
static $placeholder_data = array();
/**
* Sets the default page data before the request has been executed.
*/
static function SetDefaults($request) {
Templating::$page_data['page_title'] = $request == null ? '' : $request->controller_name . ' > ' . $request->action;
Templating::$page_data['request_controller'] = $request == null ? '' : $request->controller_name;
Templating::$page_data['request_action'] = $request == null ? '' : $request->action;
Templating::$page_data['request_params'] = $request == null ? '' : $request->params;
}
static function SetPageTitle($title) {
Templating::$page_data['page_title'] = $title;
}
/**
* Adds one or more key/value pairs into the page data array
* @param array|string $key If an array, all the key/value pairs in the array will be used. Otherwise, the value will be added with this key
* @param object $value If key is not an array, this is the value that will be inserted into the page data
* @return void
*/
static function SetPageData($key, $value = null) {
if (is_array($key)) {
foreach ($key as $k => $v) {
Templating::$page_data[$k] = $v;
}
} else {
Templating::$page_data[$key] = $value;
}
}
static function Fetch()
{
$master_page = Templating::$master_page;
if (substr($master_page, 0, -4) != '.tpl') {
$master_page .= '.tpl';
}
$master = Templating::Create();
$master->assign(Templating::$page_data);
Hooks::ExecuteRenderHooks($master);
$master->assign('phoenix_debug', Phoenix::GetDebugInfo());
return $master->fetch($master_page);
}
static function Render()
{
$master_page = Templating::$master_page;
if (substr($master_page, 0, -4) != '.tpl') {
$master_page .= '.tpl';
}
$master = Templating::Create();
$master->assign(Templating::$page_data);
Hooks::ExecuteRenderHooks($master);
$master->assign('phoenix_debug', Phoenix::GetDebugInfo());
$master->display($master_page);
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.validation.php
<?php
function smarty_function_validation($params, $template)
{
$defaults = array(
'html_class' => 'validation-error',
'text' => Validation::GetFirstError($params['for'])
);
$params = array_merge($defaults, $params);
$htmlattr = array();
$for = $params['for'];
if (!Validation::HasErrors($for))
{
return null;
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$field = '<span';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= '>'.$params['text'].'</span>';
return $field;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.label.php
<?php
function smarty_function_label($params, $template)
{
$defaults = array(
'text' => $params['for']
);
$params = array_merge($defaults, $params);
$htmlattr = array();
$htmlattr['for'] = 'form_'.$params['for'];
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$field = '<label';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= '>'.$params['text'].'</label>';
return $field;
}
<file_sep>/Phoenix/Phoenix.php
<?php
/// PHOENIX MVC
/// VERSION 0.3
/// http://logic-and-trick.com
// Third party libs
include 'Libs/Smarty/Smarty.class.php';
include 'Libs/LightOpenID/LightOpenID.php';
include 'Libs/Recaptcha/recaptchalib.php';
// Phoenix
include 'AutoLoad.php';
include 'ExceptionHandler.php';
include 'Database.php';
include 'Model.php';
include 'Query.php';
include 'Validation.php';
include 'Post.php';
include 'Authentication.php';
include 'Authorisation.php';
include 'Router.php';
include 'RouteParameters.php';
include 'Hooks.php';
include 'Controller.php';
include 'ActionResult.php';
include 'Views.php';
include 'Templating.php';
class Phoenix {
/**
* The directory holding the Phoenix.php file.
* Used internally, do not change.
* @var string
*/
static $phoenix_dir;
/**
* The directory holding the application's file structure.
* This is the directory containing the 'Controllers', 'Views',
* and 'Models' directories.
* @var string
*/
static $app_dir;
/**
* The url containing the index.php script. Used for linking
* in the template functions. Ends in a slash.
* @var string
*/
static $base_url;
/**
* The route parameters associated with the current request.
* @var RouteParameters
*/
static $request;
/**
* The action result returned after the current request has executed.
* @var ActionResult
*/
static $result;
/**
* Set to true to enable debugging output.
* @var bool
*/
static $debug;
/**
* Limit the debug output to a specific username.
* @var string
*/
static $debug_user;
/**
* Phoenix's internal database logger.
* @var MemoryLogger
*/
private static $_dblog;
/**
* The error controller (without the 'Controller' suffix). Default is 'Error'.
* @var string
*/
static $error_controller = 'Error';
/**
* The error action. Default is 'Index'.
* @var string
*/
static $error_action = 'Index';
/**
* Initialise the framework. Called internally, do not use.
*/
static function Init()
{
Phoenix::$phoenix_dir = dirname(__FILE__);
Phoenix::$app_dir = Phoenix::$phoenix_dir . '/../App';
Phoenix::$debug = false;
Phoenix::$_dblog = new MemoryLogger();
Database::AddLogger(Phoenix::$_dblog);
}
/**
* Run the framework
*/
static function Run()
{
$route = array_key_exists('phoenix_route', $_GET) ? $_GET['phoenix_route'] : '';
Hooks::ExecuteRouteHooks($route);
Phoenix::$request = Router::Resolve($route);
Hooks::ExecuteRequestHooks(Phoenix::$request);
Phoenix::$result = Phoenix::$request->Execute();
Hooks::ExecuteResultHooks(Phoenix::$result);
Phoenix::$result->Execute();
}
public static function GetDebugInfo()
{
if (Phoenix::$debug && (Phoenix::$debug_user == null || Phoenix::$debug_user == Authentication::GetUserName())) {
$debug = Templating::Create();
$debug->assign('queries', Phoenix::$_dblog->queries);
return $debug->fetch(Views::Find('Debug/Debug'));
} else {
return null;
}
}
}
// Init the framework before any variables are set, because
// this sets some defaults.
Phoenix::Init();
?><file_sep>/index.php
<?php
include 'Phoenix/Phoenix.php';
/*
****************************************************************************
* REQUIRED SETTINGS
* Phoenix will not work if you do not set the following
****************************************************************************
*/
// The name of the default controller
Router::$default_controller = 'Home';
// The name of the default action (for all controllers)
Router::$default_action = 'Index';
// The name of the default master page (can be changed in the controller)
Templating::$master_page = 'Shared/Master';
// The absolute path to the application directory on the server's file system
Phoenix::$app_dir = realpath(dirname(__FILE__)).'/App';
// The absolute path to the application directory on the website's domain
Phoenix::$base_url = '/';
// Defaults to false; Set to true to enable debug output
Phoenix::$debug = false;
// Set to a non-null value to limit debug output to a specific username only
Phoenix::$debug_user = null;
/*
****************************************************************************
* DATABASE SETTINGS
* Required to use the database. Phoenix still works without a database.
****************************************************************************
*/
// The database type to use, can be mysql or sqlite
Database::$type = 'mysql';
// All self explanatory
Database::$host = 'hostname';
Database::$database = 'database';
Database::$username = 'username';
Database::$password = '<PASSWORD>';
// Uncomment to enable the database
//Database::Enable();
// Add a logger to the database (optional)
//$elog = new EchoLogger();
//$elog->printstacktrace = false;
//Database::AddLogger($elog);
/*
****************************************************************************
* AUTHENTICATION SETTINGS
* If you want people to be able to 'log in' to your site, use
* authentication. Note that authentication requires the database to
* be enabled before you enable authentication.
****************************************************************************
*/
// Change the session variable that holds the ID of the logged in user
Authentication::$session_id = 'phoenix_login';
// If set to true, auth will log the user in when the fields are contained in the postback data
Authentication::$autologin = true;
// If set to true, openid will be enabled for registration and login
Authentication::$useopenid = true;
// If set to true, all new user accounts must have an email address
Authentication::$emailrequired = true;
// If set to true, all new user accounts will be sent an email with a verification link before they can log in
Authentication::$emailconfirmation = false;
// The class name of the model to use
Authentication::$model = 'User';
// The primary key of the user model
Authentication::$field_id = 'ID';
// The username field of the model
Authentication::$field_username = 'Name';
// The password field of the model
Authentication::$field_password = '<PASSWORD>';
// The email field of the model
Authentication::$field_email = 'Email';
// The field to store the model's OpenID URL
Authentication::$field_openid = 'OpenID';
// Holds the cookie session key (can be null, but cookies will be disabled)
Authentication::$field_cookie = 'Cookie';
// The field to be incremented when a user logs in with cookies or postback (can be null)
Authentication::$field_numlogins = 'NumLogins';
// The field to update to the current time when a user logs in (can be null)
Authentication::$field_lastlogin = 'LastLogin';
// The field to update to the current time when a user accesses a page (can be null)
Authentication::$field_lastaccess = 'LastAccess';
// The field to update to the current route info when a user accesses a page (can be null)
Authentication::$field_lastpage = 'LastPage';
// The field to update to the current IP of the user when they log in (can be null)
Authentication::$field_ip = 'IP';
// The field containing the account unlocking verification code (cannot be null if using email confirmation)
Authentication::$field_unlocker = 'Unlock';
// The name of the cookie that holds the id of the logged in user (can be null, but cookies will be disabled)
Authentication::$cookie_id = 'phoenix_username';
// The name of the cookie that holds the cookie session key (can be null, but cookies will be disabled)
Authentication::$cookie_code = 'phoenix_code';
// The time before the cookies will expire (cookies will be disabled if not > 0)
Authentication::$cookie_timeout = 30000000;
// The name of the username post field to use when logging in or creating an account (cannot be null if using autologin or account creation)
Authentication::$post_username = 'username';
// The name of the password post field to use when logging in or creating an account (cannot be null if using autologin or account creation)
Authentication::$post_password = '<PASSWORD>';
// The name of the password confirmation post field to use when creating an account (cannot be null if using account creation)
Authentication::$post_password_confirm = '<PASSWORD>';
// The name of the 'remember me' post field to use when logging in (can be null, autologin will assume a false value)
Authentication::$post_remember = 'remember';
// The name of the logout post field to use when logging out (can be null, autologin will still work but autologout will not)
Authentication::$post_logout = 'logout';
// The name of the email post field to use when creating an account (cannot be null if using account creation)
Authentication::$post_email = 'email';
// The name of the openid post field to use when creating an account (cannot be null if using account creation)
Authentication::$post_openid = 'openid';
// The name of the register type post field to use when creating an account (cannot be null if using account creation)
Authentication::$post_register = 'register';
// Fields that must be user-populated. This is the email template that will be sent when using email confirmation for creating accounts
// {username} will be replaced with the user's username
// {id} is replaced with the user's id,
// {unlock_code} will be the user's unlock code
// Email's 'nice' from name
Authentication::$email_from_name = 'User Verification';
// Email's actual from address
Authentication::$email_from_email = '<EMAIL>';
// Email subject
Authentication::$email_subject = 'User Account Verification';
// Email content
Authentication::$email_content = "Hi {username},\r\n" .
"Your account has been created. To enable your account you must click the following link.\r\n" .
"http://example.com/Account/Verify/{id}/{unlock_code}";
// When set to true, sendmail's '-f' parameter will be used in PHP's mail() function - this helps to avoid a lot of spam filters.
Authentication::$email_sendmail_envelope = true;
// Register a password hasher. IMPORTANT: CHANGE THE SALT VALUES!
Authentication::RegisterPasswordHasher(new AlgorithmHasher('sha256', 'SALT_PREPEND', 'SALT_APPEND'));
// Uncomment to enable authentication
//Authentication::Enable();
/*
****************************************************************************
* AUTHORISATION SETTINGS
* If you have authentication set up, chances are you want authorisation.
* This enables you to limit certain pages to certain users based on a
* permissions system of some sort.
****************************************************************************
*/
// Use an authorisation method by setting the method like so:
//Authorisation::SetAuthorisationMethod(new DefaultAuthorisation());
/*
****************************************************************************
* END USER CONFIGURATION
****************************************************************************
*/
// Run the framework. Removing this will make your website do nothing.
Phoenix::Run();
?>
<file_sep>/Phoenix/Validation.php
<?php
class Validation
{
public static $register = array();
public static $errors = array();
public static $recaptcha_public = null;
public static $recaptcha_private = null;
public static $recaptcha_error = null;
static function ValidateRecaptcha() {
if ($_POST["recaptcha_response_field"] !== null) {
$resp = recaptcha_check_answer (Validation::$recaptcha_private, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]);
if ($resp->is_valid) {
return true;
} else {
Validation::$recaptcha_error = $resp->error;
Validation::AddError('Captcha', 'Incorrect code! Please try again.');
return false;
}
}
return false;
}
static function AddError($name, $error) {
Validation::$errors[$name][] = $error;
}
static function AddErrors($errors, $prefix = '') {
foreach ($errors as $name => $errs) {
foreach ($errs as $err) {
Validation::$errors[$prefix.$name][] = $err;
}
}
}
static function HasErrors($name = null) {
if ($name == null) {
foreach (Validation::$errors as $name => $errors) {
if (count($errors) > 0) {
return true;
}
}
return false;
}
return (array_key_exists($name, Validation::$errors) && count(Validation::$errors[$name]) > 0);
}
static function GetFirstError($name = null) {
if ($name == null) {
foreach (Validation::$errors as $g) {
foreach ($g as $err) return $err;
}
}
else if (array_key_exists($name, Validation::$errors) && count(Validation::$errors[$name]) > 0) {
return Validation::$errors[$name][0];
}
return null;
}
static function GetAllErrors($name = null) {
if ($name == null) {
return Validation::$errors;
}
if (array_key_exists($name, Validation::$errors)) {
return Validation::$errors[$name];
}
return array();
}
static function Validate($model, $prefix = '', $fields = null) {
Validation::AddErrors($model->GetErrors($fields), $prefix);
return !Validation::HasErrors();
}
static function RegisterValidator($refname, $classname) {
Validation::$register[$refname] = $classname;
}
static function GetValidator($refname, $params) {
$classname = Validation::$register[$refname];
if (!class_exists($classname)) {
return null;
}
$obj = new $classname();
foreach ($params as $name => $value) {
$obj->$name = $value;
}
return $obj;
}
}
Validation::RegisterValidator('required', 'RequiredValidation');
Validation::RegisterValidator('stringrange', 'StringRangeValidation');
Validation::RegisterValidator('range', 'RangeValidation');
Validation::RegisterValidator('regex', 'RegexValidation');
Validation::RegisterValidator('datatype', 'DataTypeValidation');
Validation::RegisterValidator('urlsafe', 'UrlSafeValidation');
Validation::RegisterValidator('oneof', 'OneOfValidation');
Validation::RegisterValidator('email', 'EmailValidation');
Validation::RegisterValidator('db-unique', 'DbUniqueValidation');
class ValidationMethod
{
public $message;
function Validate($model, $field, $value) {
// Virtual
}
function GetMessage() {
// Virtual
}
}
class RequiredValidation extends ValidationMethod
{
function Validate($model, $field, $value) {
return $value !== null && $value !== '';
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
return 'This field is required.';
}
}
class StringRangeValidation extends ValidationMethod
{
public $min;
public $max;
function __construct() {
$this->min = 0;
$this->max = 0;
}
function Validate($model, $field, $value) {
if ($value == null) {
return true;
}
if (!is_string($value)) {
return false;
}
$len = strlen($value);
if ($this->max > 0 && $len > $this->max) {
return false;
}
return !($len < $this->min);
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
$msg = 'This field must be ';
if ($this->max > 0) {
$msg .= "between {$this->min} and {$this->max}";
} else {
$msg .= "greater than {$this->min}";
}
$msg .= ' characters long.';
return $msg;
}
}
class RangeValidation extends ValidationMethod
{
public $min;
public $max;
function __construct() {
$this->min = 0;
$this->max = 0;
}
function Validate($model, $field, $value) {
if ($value == null) {
return true;
}
if (!is_numeric($value)) {
return false;
}
if ($this->max > 0 && $value > $this->max) {
return false;
}
return !($value < $this->min);
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
$msg = 'This field must be ';
if ($this->max > 0) {
$msg .= "between {$this->min} and {$this->max}";
} else {
$msg .= "greater than {$this->min}";
}
$msg .= '.';
return $msg;
}
}
class RegexValidation extends ValidationMethod
{
public $pattern;
function __construct() {
$this->pattern = '';
}
function Validate($model, $field, $value) {
if ($value == null) {
return true;
}
if (!is_string($value)) {
return false;
}
return preg_match($this->pattern, $value) > 0;
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
return 'This field is not valid.';
}
}
class UrlSafeValidation extends RegexValidation
{
function __construct() {
$this->pattern = '/^[a-z0-9_-]*$/i';
$this->message = 'This field must be URL-safe (alphanumeric, hyphens, and underscores only)';
}
}
class OneOfValidation extends ValidationMethod
{
public $values;
function __construct() {
$this->values = array();
}
function Validate($model, $field, $value) {
if ($value === null || $value == '') return true;
return array_search($value, $this->values) !== false;
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
return 'This field must be one of the following: '.implode(', ', $this->values);
}
}
class EmailValidation extends ValidationMethod
{
function Validate($model, $field, $value) {
return filter_var($value, FILTER_VALIDATE_EMAIL) !== false;
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
return 'This field must be a valid email address.';
}
}
class DataTypeValidation extends ValidationMethod
{
public $type;
public $pattern;
function __construct() {
$this->type = 'none';
$this->pattern = '';
}
function Validate($model, $field, $value) {
// If the field is null, it's valid (this is
// the responsibility of the required validation method)
if ($value == null) {
return true;
}
switch ($this->type) {
case 'int':
case 'timestamp':
return is_numeric($value) && (int)$value == $value;
case 'number':
case 'decimal':
case 'float':
case 'double':
return is_numeric($value);
case 'string':
return is_string($value);
case 'date':
case 'datetime':
return ($value instanceof DateTime)
|| ($this->pattern != '' && DateTime::createFromFormat($this->pattern, $value) !== false)
|| DateTime::createFromFormat('Y-m-d H:i:s', $value) !== false
|| DateTime::createFromFormat('Y-m-d', $value) !== false;
case 'time':
return ($value instanceof DateTime)
|| ($this->pattern != '' && DateTime::createFromFormat($this->pattern, $value) !== false)
|| DateTime::createFromFormat('Y-m-d H:i:s', $value) !== false
|| DateTime::createFromFormat('H:i:s', $value) !== false;
case 'bool':
case 'bit':
return is_bool($value);
}
return true;
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
$msg = 'This field must be a valid ';
switch ($this->type) {
case 'int':
$msg .= 'integer';
break;
case 'timestamp':
$msg .= 'unix timestamp';
break;
case 'number':
case 'decimal':
case 'float':
case 'double':
$msg .= 'number';
break;
case 'string':
$msg .= 'string';
break;
case 'date':
$msg .= 'date';
break;
case 'datetime':
$msg .= 'date/time';
break;
case 'time':
$msg .= 'time';
break;
case 'bool':
case 'bit':
$msg .= 'boolean value (1 or 0)';
break;
}
$msg .= '.';
return $msg;
}
}
class DbUniqueValidation extends ValidationMethod
{
public $fields;
public $case_sensitive;
function __construct() {
$this->fields = array();
$this->case_sensitive = true;
}
function Validate($model, $field, $value) {
if ($value == null) {
return true;
}
if (!is_string($value)) {
return false;
}
$params = array();
$sql = "SELECT count(*) AS Count FROM {$model->table} WHERE ";
// If primary key is not null, exclude itself from the result set
if ($model->{$model->primaryKey} !== null)
{
$params[':pkparam'] = $model->{$model->primaryKey};
$sql .= "`" . $model->GetDBName($model->primaryKey)."` != :pkparam AND ";
}
// Set the field parameter value to check. Case-insensitive conversion converts to upper-case
if ($this->case_sensitive === false)
{
$params[':fieldparam'] = strtoupper($value);
$sql .= 'UPPER(`' . $model->GetDBName($field) . '`) = :fieldparam';
}
else
{
$params[':fieldparam'] = $value;
$sql .= '`' . $model->GetDBName($field) . '` = :fieldparam';
}
// Assign all the additional fields specified
$pcount = 1;
$flds = is_array($this->fields) ? $this->fields : array($this->fields);
foreach ($flds as $fname)
{
$sql .= " AND `" . $model->GetDBName($fname) . "` = :param{$pcount}";
$params[":param{$pcount}"] = $model->$fname;
$pcount++;
}
$result = CustomQuery::Query($sql, $params);
$count = $result[0]->Count;
return $count == 0;
}
function GetMessage() {
if ($this->message != null) {
return $this->message;
}
$flds = is_array($this->fields) ? $this->fields : array($this->fields);
return 'This field must be unique in the database'
. (count($flds) > 0 ? ' for fields: '.implode(', ', $flds) : '')
. '.';
}
}
?>
<file_sep>/Phoenix/Controller.php
<?php
class Controller {
public $authorise;
public $viewData;
function BeforeExecute()
{
}
function AfterExecute()
{
}
/**
* Return a result containing content only. Content will
* be echoed to the screen with no other processing.
* @param string $content
* @return ContentResult
*/
function Content($content)
{
$ar = new ContentResult($content);
return $ar;
}
/**
* Return a result containing a serialised JSON object. The JSON will
* be echoed to the screen and the content-type will be set to application/json.
* @param string $obj
* @return JsonResult
*/
function Json($obj)
{
$ar = new JsonResult($obj);
return $ar;
}
/**
* Returns a result that redirects to an action in a controller.
* @param string $action The action to redirect to
* @param string $controller The controller to redirect to (null for the current controller)
* @param array $params The parameters to pass to the redirected route
* @return RedirectToActionResult
*/
function RedirectToAction($action, $controller = null, $params = array())
{
if ($controller == null) {
$controller = Phoenix::$request->controller_name;
}
if (!is_array($params)) {
$params = array($params);
}
$ar = new RedirectToActionResult($action, $controller, $params);
return $ar;
}
/**
* Returns a result that redirects to a specified route.
* @param string $route The route (as a string) to redirect to
* @return RedirectToRouteResult
*/
function RedirectToRoute($route)
{
$ar = new RedirectToRouteResult($route);
return $ar;
}
/**
* Returns a result that redirects to a URL.
* @param string $url The URL to redirect to
* @return RedirectToUrlResult
*/
function RedirectToUrl($url)
{
$ar = new RedirectToUrlResult($url);
return $ar;
}
/**
* Return a result containing a view. Content will be
* processed with Smarty before being output.
* @param object $model The model to use
* @param string $view The name of the view to use
* @param string $name The name of the content placeholder in the master page
* @param boolean $cache True to cache the results of the result
* @return ViewResult
*/
function View($model = null, $view = null, $name = 'content', $cache = true)
{
$view = Views::Find($view);
$ar = new ViewResult($name, $view, $model, $this->viewData, $cache);
return $ar;
}
/**
* Return a result containing a render command. The supplied
* view will be rendered directly, no master page will be used.
* @param object $model The model to use
* @param string $view The name of the view to use
* @return RenderResult
*/
function Render($model = null, $view = null)
{
$view = Views::Find($view);
$ar = new RenderResult($view, $model, $this->viewData);
return $ar;
}
function ViewHierarchy($hierarchy)
{
$ar = new ViewHierarchyResult($hierarchy, $this->viewData);
return $ar;
}
function MultiView($array)
{
foreach ($array as $name => $vm) {
$array[$name]['view'] = Views::Find($array[$name]['view']);
}
$ar = new MultiViewResult($array, $this->viewData);
return $ar;
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.submit.php
<?php
function smarty_function_submit($params, $template)
{
$defaults = array(
'text' => isset($params['value']) ? $params['value'] : 'Submit',
'html_type' => 'submit',
'disabled' => false,
'html_value' => null,
'button' => false
);
$params = array_merge($defaults, $params);
if ($params['html_value'] == null) $params['html_value'] = $params['text'];
$htmlattr = array();
if ($params['disabled'] === true) {
$htmlattr['disabled'] = 'disabled';
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$field = '';
if ($params['button'])
{
$field .= '<button';
foreach ($htmlattr as $key => $value) {
if ($key == 'value') continue;
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= '>' . $htmlattr['value'] . '</button>';
}
else
{
$field .= '<input';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= ' />';
}
return $field;
}
<file_sep>/Phoenix/Cache.php
<?php
Cache::SetCache(new Cache());
class Cache
{
/**
* @var Cache
*/
private static $_cache;
public static function SetCache($cache)
{
Cache::$_cache = $cache;
}
public static function IsViewCached($route, $smarty, $view)
{
Cache::$_cache->IsCached($route, $smarty, $view);
}
public static function ClearCachedView($route, $smarty, $view)
{
Cache::$_cache->Clear($route, $smarty, $view);
}
public static function FetchView($route, $smarty, $view)
{
return Cache::$_cache->Fetch($route, $smarty, $view);
}
// Cache class functions
public function Clear($route, $smarty, $view) {}
public function IsCached($route, $smarty, $view) { return false; }
public function Fetch($route, $smarty, $view) { return $smarty->fetch($view); }
}
class SmartyCache
{
protected $timeout;
function __construct($timeout)
{
$this->timeout = $timeout;
}
/**
* @param Smarty $smarty
*/
public function IsCached($route, $smarty, $view)
{
$befc = $smarty->caching;
$befl = $smarty->cache_lifetime;
$smarty->caching = true;
$smarty->cache_lifetime = $this->timeout;
$cached = $smarty->isCached($view, $route);
$smarty->caching = $befc;
$smarty->cache_lifetime = $befl;
return $cached;
}
/**
* @param Smarty $smarty
*/
public function Clear($route, $smarty, $view)
{
$smarty->clearCache($view, $route);
}
/**
* @param Smarty $smarty
*/
public function Fetch($route, $smarty, $view)
{
$befc = $smarty->caching;
$befl = $smarty->cache_lifetime;
$smarty->caching = true;
$smarty->cache_lifetime = $this->timeout;
$fetch = $smarty->fetch($view, $route);
$smarty->caching = $befc;
$smarty->cache_lifetime = $befl;
return $fetch;
}
}
?><file_sep>/Phoenix/Libs/Smarty.Phoenix/function.select.php
<?php
function smarty_function_select($params, $template)
{
$defaults = array(
'items' => null,
'textfield' => 'Name',
'valuefield' => 'ID',
'type' => 'select',
'multiple' => false,
'multiple_style' => 'select',
'multiple_size' => 5,
'multiple_separator' => '<br />',
'all_selected' => false,
'label_separator' => ' ',
'disabled' => false,
'model' => null,
'first_text' => null,
'first_value' => null,
'ignore_post' => false
);
$params = array_merge($defaults, $params);
$selected_vals = array();
$multi = $params['multiple'] === true;
if (!$multi) {
$selected_value = null;
$model = $params['model'];
if (Post::IsPostBack() && Post::Get($params['for']) != null && !$params['ignore_post']) {
$selected_value = Post::Get($params['for']);
} else if (isset($params['selected_value']) && $params['selected_value'] != null) {
$selected_value = $params['selected_value'];
} else if ($model != null && ($model instanceof Model || $model instanceof CustomQueryRow)) {
$selected_value = $model->{$params['for']};
}
if ($selected_value !== null) {
$selected_vals[] = $selected_value;
}
} else {
$sv = null;
if (Post::IsPostBack() && Post::Get($params['for']) != null && !$params['ignore_post']) {
$sv = Post::Get($params['for']);
} else if (isset($params['selected_value']) && is_array($params['selected_value'])) {
$sv = $params['selected_value'];
} else if (isset($params['selected_values']) && is_array($params['selected_values'])) {
$sv = $params['selected_values'];
}
if ($sv !== null && is_array($sv)) {
foreach ($sv as $k => $ex) {
if (is_object($ex) && property_exists($ex, $params['valuefield'])) {
$selected_vals[] = $ex->{$params['valuefield']};
} else if (is_numeric($ex) || is_string($ex)) {
$selected_vals[] = $ex;
}
}
}
}
$htmlattr = array();
if ($params['disabled'] === true) {
$htmlattr['disabled'] = 'disabled';
}
$htmlattr['name'] = $params['for'] . ($multi ? '[]' : '');
$htmlattr['id'] = 'form_'.$params['for'];
if ($multi) {
$htmlattr['multiple'] = 'muiltiple';
$htmlattr['size'] = $params['multiple_size'];
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
if ($params['items'] === null) $params['items'] = $template->getVariable($params['for'])->value;
if ($params['items'] === null || !is_array($params['items'])) $params['items'] = array();
if ($multi && $params['multiple_style'] == 'checkbox') {
$select = '';
foreach ($params['items'] as $item) {
$selected = $params['all_selected'] || array_search($item->{$params['valuefield']}, $selected_vals) !== false;
$val = htmlspecialchars($item->{$params['valuefield']});
$select .= '<label class="checkbox" for="' . $htmlattr['id'] . '_' . $val . '">' .
'<input type="checkbox" ' .
'name="' . htmlspecialchars($htmlattr['name']) . '" ' .
'value="' . $val . '" ' .
'id="' . $htmlattr['id'] . '_' . $val . '"' .
($selected ? ' checked="checked"' : '') .
'/>' . $params['label_separator'] .
htmlspecialchars($item->{$params['textfield']}) .
'</label>' .
$params['multiple_separator'] . "\n";
}
} else if ($params['type'] == 'radio') {
$select = '';
foreach ($params['items'] as $item) {
$selected = array_search($item->{$params['valuefield']}, $selected_vals) !== false;
$val = htmlspecialchars($item->{$params['valuefield']});
$select .= '<input type="radio" ' .
'name="' . htmlspecialchars($htmlattr['name']) . '" ' .
'value="' . $val . '" ' .
'id="' . $htmlattr['id'] . '_' . $val . '"' .
($selected ? ' checked="checked"' : '') .
'/>' . $params['label_separator'] .
'<label for="' . $htmlattr['id'] . '_' . $val . '">' .
htmlspecialchars($item->{$params['textfield']}) .
'</label>' .
$params['multiple_separator'] . "\n";
}
} else {
$select = '<select';
foreach ($htmlattr as $key => $value) {
$select .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$select .= '>';
if (!$multi && $params['first_value'] !== null && $params['first_text'] !== null) {
$selected = count($selected_vals) == 0 || (count($selected_vals) == 1
&& ($selected_vals[0] === null || $selected_vals[0] == $params['first_value']));
$select .= "\n" . '<option value="' . $params['first_value'] . '"'
. ($selected ? ' selected="selected"' : '')
. '>' . $params['first_text'] . '</option>';
}
foreach ($params['items'] as $item) {
$selected = $params['all_selected'] || array_search($item->{$params['valuefield']}, $selected_vals) !== false;
$select .= "\n"
.'<option value="' . htmlspecialchars($item->{$params['valuefield']}) . '"' .
($selected ? ' selected="selected"' : '') .
'>'
.htmlspecialchars($item->{$params['textfield']})
.'</option>';
}
$select .= '</select>';
}
return $select;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.validationsummary.php
<?php
function smarty_function_validationsummary($params, $template)
{
$htmlattr = array();
if (!Validation::HasErrors())
{
return null;
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$summary = '<p class="validation-summary"';
foreach ($htmlattr as $key => $value) {
$summary .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$summary .= ">\nErrors were found in the data. See below for details:\n</p>\n<ul class=\"validation-summary\"";
foreach ($htmlattr as $key => $value) {
$summary .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$summary .= ">\n";
foreach (Validation::GetAllErrors() as $name => $errors) {
foreach ($errors as $e) {
$error = htmlspecialchars($e);
$summary .= "<li>$error</li>\n";
}
}
$summary .= "</ul>";
return $summary;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/modifier.pluralise.php
<?php
function smarty_modifier_pluralise($string, $count = null)
{
if ($count !== null && stristr($string, ':n') !== false && stristr($string, ':s') !== false) {
return str_ireplace(':n', $count, str_ireplace(':s', ($count == 1 ? '' : 's'), $string));
}
if ($count === null) $count = 0;
return $string . ($count == 1 ? '' : 's');
}
<file_sep>/Phoenix/Model.php
<?php
class Model
{
/**
* @var string The name of the database table
*/
public $table = '';
/**
* @var array The columns of the database table.
* Can be aliased with 'Actual' => 'Alias'
*/
public $columns = array();
/**
* @var array A list of aliases for dynamic aliasing
*/
public $alias = array();
/**
* @var string The name of the primary key column in the table.
* Use the aliased column name.
*/
public $primaryKey = 'ID';
/**
* @var array Many-to-One relationships for this model
* Format: 'ModelName' => array('ThisID' => 'ThatID')
* Use the aliased column names.
*/
public $one = array();
/**
* @var array One-to-Many relationships for this model
* Format: 'ModelName' => array('ThisID' => 'ThatID')
* Can also use ':Order', ':OrderDesc' to change the order of results.
* Use the aliased column names.
*/
public $many = array();
/**
* @var array Validators for this model
* Format: 'Column' => array('validator' => array(**validator settings**))
* See the validator documentation for available settings.
* Use the aliased column names.
*/
public $validation = array();
/**
* @var array Registered data mappers for this model
* Format: 'Column' => 'mapper'
* Each column can only have a maximum of one data mapper.
* Use the aliased column names.
*/
public $mappings = array();
/**
* @var array The DB name of the primary key
*/
private $_dbpk;
/**
* @var array The actual data values for this model
*/
private $_values;
/**
* @var bool True if this record is saved to the database, false otherwise
*/
private $_new;
/**
* @var array The resolved validator classes
*/
private $_validators;
/**
* @var array A cache for 'Get' and 'Find' lazy-loading methods
*/
private $_getcache;
/**
* @param mixed $id
*/
public function __construct($id = false)
{
$this->_values = array();
$this->_getcache['one'] = array();
$this->_getcache['many'] = array();
$temp = array();
foreach ($this->columns as $db => $map) {
if (!is_string($db)) $db = $map;
$temp[$db] = $map;
}
$this->columns = $temp;
foreach ($this->columns as $db => $map) {
$this->_values[$map] = new ModelValue($db, $map);
if ($map == $this->primaryKey) {
$this->_dbpk = $db;
}
}
foreach ($this->alias as $name => $alias) {
if (array_search($alias, $this->columns)) {
unset($this->alias[$name]);
}
}
// Constructor
if ($id !== false) {
$this->_new = false;
$val = Database::One($this->table, array("`{$this->_dbpk}` = :id"), array(':id' => $id), null, $this->GetTableFields());
$this->SetValues($val);
} else {
$this->_new = true;
}
// Validators
$this->_validators = array();
foreach ($this->validation as $field => $params) {
$this->_validators[$field] = array();
foreach ($params as $val_name => $values) {
if (is_numeric($val_name) || is_string($values)) {
$val_name = $values;
$values = array();
}
$this->_validators[$field][] = Validation::GetValidator($val_name, $values);
}
}
}
private function SetValues($val)
{
foreach ($this->columns as $v) {
$value = $val[$v];
if (array_key_exists($v, $this->mappings)) {
$value = Model::MapFromDatabase($this->mappings[$v], $value);
}
$this->_values[$v]->Set($value);
$this->_values[$v]->Reset();
}
}
public function MapValue($column, $value)
{
if (array_key_exists($column, $this->mappings)) {
return Model::MapToDatabase($this->mappings[$column], $value);
}
return $value;
}
public function GetTableFields($table_prefix = '', $result_prefix = '')
{
$table_prefix = strlen($table_prefix) == 0 ? '' : $table_prefix . '.';
$result = array();
foreach ($this->columns as $db => $map) {
$result[] = "{$table_prefix}`{$db}` AS `{$result_prefix}{$map}`";
}
return implode(', ', $result);
}
public function Alias($name, $alias)
{
if (array_search($alias, $this->columns) === false && array_search($alias, $this->alias) === false) {
$this->alias[$name] = $alias;
}
}
public function GetDBName($alias)
{
return array_search($alias, $this->columns);
}
public function HasField($name) {
return array_search($name, $this->columns) !== false || array_search($name, $this->alias) !== false;
}
public function IsValid($fields = null) {
return count($this->GetErrors($fields)) == 0;
}
public function GetErrors($fields = null) {
if ($fields == null) {
$fields = array_values($this->columns);
} else if (is_string($fields)) {
$nf = array();
$nf[] = $fields;
$fields = $nf;
}
$errors = array();
foreach ($fields as $field) {
if (isset($this->_validators[$field])) {
foreach ($this->_validators[$field] as $vd) {
if ($vd == null) {
continue;
}
if (!$vd->Validate($this, $field, $this->$field)) {
$errors[$field][] = $vd->GetMessage();
}
}
}
}
return array_merge($errors, $this->Validate());
}
public function __get($name) {
$alias = array_search($name, $this->alias);
if ($alias !== false) {
$name = $alias;
}
if (array_key_exists($name, $this->_values)) {
return $this->_values[$name]->Get();
}
return null;
}
public function __set($name, $value) {
$alias = array_search($name, $this->alias);
if ($alias !== false) {
$name = $alias;
}
if (array_key_exists($name, $this->_values)) {
$this->_values[$name]->Set($value);
}
}
public function Find($class) {
$obj = new $class();
$order = null;
$limit = null;
$params = array();
$where = array();
if (isset($this->_getcache['many'][$class])) {
return $this->_getcache['many'][$class];
}
$rel = $this->many[$class];
$counter = 1;
foreach ($rel as $tk => $ok) {
if ($tk == ':Order') $order = "`$ok` ASC";
else if ($tk == ':OrderDesc') $order = "`$ok` DESC";
else if ($tk == ':JoinParams') $where[] = $ok;
else if ($tk == ':Limit') $limit = $ok;
else {
$ok = $obj->GetDbName($ok);
$param_name = ':jp'.$counter;
$counter++;
$where[] = "`$ok` = $param_name";
$params[$param_name] = $this->$tk;
}
}
$values = Database::All($obj->table, $where, $params, $order, $limit, $obj->GetTableFields());
$result = array();
foreach ($values as $val) {
$res = new $class();
$res->_new = false;
$res->SetValues($val);
$result[] = $res;
}
$this->_getcache['many'][$class] = $result;
return $result;
}
public function Get($class) {
$obj = new $class();
$where = array();
$params = array();
$order = null;
if (isset($this->_getcache['one'][$class])) {
return $this->_getcache['one'][$class];
}
$rel = $this->one[$class];
$counter = 1;
foreach ($rel as $tk => $ok) {
if ($tk == ':JoinParams') $where[] = $ok;
else {
$ok = $obj->GetDbName($ok);
$param_name = ':jp'.$counter;
$counter++;
$where[] = "`$ok` = $param_name";
$params[$param_name] = $this->$tk;
}
}
$val = Database::One($obj->table, $where, $params, $order, $obj->GetTableFields());
$res = new $class();
$res->_new = false;
if ($val !== false) {
$res->SetValues($val);
}
$this->_getcache['one'][$class] = $res;
return $res;
}
public function Copy() {
$class = get_called_class();
$copy = new $class;
foreach ($this->_values as $n => $d) {
$copy->_values[$n]->Set($d->Get());
}
$copy->_values[$copy->primaryKey]->Set(null);
$copy->_values[$copy->primaryKey]->Reset();
return $copy;
}
public function Save() {
$insert = $this->_new;
$insert ? $this->BeforeInsert() : $this->BeforeUpdate();
$updated = array();
foreach ($this->_values as $d) {
if ($d->HasChanged()) {
$updated[$d->GetDbName()] = $d->Get();
}
}
if (!$insert && count($updated) == 0) {
return;
}
if ($this->_new) {
$ins = Database::Insert($this->table, $updated);
$this->_values[$this->primaryKey]->Set($ins);
$this->_new = false;
} else {
Database::Update($this->table, array("`{$this->_dbpk}` = :id"), array(':id' => $this->{$this->primaryKey}), $updated);
}
foreach ($this->_values as $d) {
$d->Reset();
}
$insert ? $this->AfterInsert() : $this->AfterUpdate();
}
public function Delete() {
$this->BeforeDelete();
Database::Delete($this->table, array("{$this->_dbpk} = :id"), array(':id' => $this->{$this->primaryKey}));
$this->_values[$this->primaryKey]->Set(null);
$this->_values[$this->primaryKey]->Reset();
$this->_new = true;
$this->AfterDelete();
}
public function ToArray($columns = array())
{
$result = array();
foreach ($this->_values as $d) {
if (count($columns) == 0 || array_search($d->GetName(), $columns) !== false) {
$result[$d->GetName()] = $d->Get();
}
}
return $result;
}
protected function BeforeInsert()
{
// Virtual
}
protected function AfterInsert()
{
// Virtual
}
protected function BeforeUpdate()
{
// Virtual
}
protected function AfterUpdate()
{
// Virtual
}
protected function BeforeDelete()
{
// Virtual
}
protected function AfterDelete()
{
// Virtual
}
protected function Validate()
{
// Virtual
return array();
}
// Static
// Query
public static function Count($class, $where = array(), $params = array()) {
$obj = new $class();
return Database::Count($obj->table, $where, $params);
}
public static function Search($class, $where = array(), $params = array(), $order = null, $limit = null) {
$obj = new $class();
$values = Database::All($obj->table, $where, $params, $order, $limit, $obj->GetTableFields());
$result = array();
foreach ($values as $val) {
$res = new $class();
$res->_new = false;
$res->SetValues($val);
$result[] = $res;
}
return $result;
}
// Data mappers
private static $_data_mappers = array();
static function RegisterDataMapper($ref_name, $class_name)
{
if (class_exists($class_name)) {
Model::$_data_mappers[$ref_name] = new $class_name();
}
}
static function GetMapped($to_db, $ref_name, $data)
{
$config_data = null;
if (is_array($ref_name)) {
$nm = array_keys($ref_name); $nm = $nm[0];
$config_data = $ref_name[$nm];
$ref_name = $nm;
}
$obj = Model::$_data_mappers[$ref_name];
if ($obj == null) {
return $data;
}
return $to_db
? $obj->MapToDatabase($data, $config_data)
: $obj->MapFromDatabase($data, $config_data);
}
static function MapToDatabase($ref_name, $data)
{
return Model::GetMapped(true, $ref_name, $data);
}
static function MapFromDatabase($ref_name, $data)
{
return Model::GetMapped(false, $ref_name, $data);
}
}
class ModelValue
{
private $_db_name;
private $_name;
private $_initial_value;
private $_current_value;
private $_has_changed;
function __construct($db_name, $name, $value = null)
{
$this->_db_name = $db_name;
$this->_name = $name;
$this->_initial_value = $value;
$this->_current_value = $value;
$this->_has_changed = false;
}
public function HasChanged()
{
return $this->_has_changed;
}
public function GetDbName()
{
return $this->_db_name;
}
public function GetName()
{
return $this->_name;
}
public function Set($value)
{
if ($this->_current_value !== $value) {
$this->_current_value = $value;
}
$this->_has_changed = $this->_current_value !== $this->_initial_value;
}
public function Get()
{
return $this->_current_value;
}
public function Revert()
{
$this->_current_value = $this->_initial_value;
$this->_has_changed = false;
}
public function Reset()
{
$this->_initial_value = $this->_current_value;
$this->_has_changed = false;
}
public function Copy()
{
$n = new ModelValue($this->_db_name, $this->_name);
$n->_initial_value = $this->_initial_value;
$n->_current_value = $this->_current_value;
$n->_has_changed = $this->_has_changed;
return $n;
}
}
Model::RegisterDataMapper('bool', 'BooleanDataMapper');
Model::RegisterDataMapper('date', 'DateTimeDataMapper');
class ModelDataMapper
{
function MapToDatabase($data, $config_data = null)
{
// Virtual
}
function MapFromDatabase($data, $config_data = null)
{
// Virtual
}
}
class BooleanDataMapper extends ModelDataMapper
{
function MapToDatabase($data, $config_data = null)
{
return ($data === true || $data == 'true' || $data == 'on' || (is_numeric($data) && $data > 0)) ? 1 : 0;
}
function MapFromDatabase($data, $config_data = null)
{
return $data > 0;
}
}
class DateTimeDataMapper extends ModelDataMapper
{
function MapToDatabase($data, $config_data = null)
{
if ($data === null || !is_string($data)) return null;
$format = 'Y-m-d';
if (is_string($config_data)) $format = $config_data;
if (is_array($config_data) && $config_data['format'] !== null) $format = $config_data['format'];
$dt = DateTime::createFromFormat($format, $data);
if ($dt === false) {
$time = strtotime($data);
if ($time === false) return null;
return gmdate('Y-m-d H:i:s', $time);
}
return $dt->format('Y-m-d H:i:s');
}
function MapFromDatabase($data, $config_data = null)
{
if ($data === null || !is_string($data)) return null;
return gmdate('Y-m-d H:i:s', strtotime($data));
}
}
?>
<file_sep>/README.md
# Phoenix MVC
Phoenix is a PHP MVC framework that attempts to emulate the powerful simplicity of the ASP.NET MVC framework.
This repo has the following subfolders:
* `App` - Contains controllers, models, views, and helpers
* `Content` - Contains images, styles and scripts
* `Phoenix` - Contains the framework files
This is a suggested structure only and these three folders can be moved if required. The `index.php` file needs to be configured appropriately. See the [documentation][1] for more information.
[1]: http://logic-and-trick.com/Projects/Phoenix<file_sep>/Phoenix/Libs/Smarty.Phoenix/block.content.php
<?php
/**
* Define a block of content for the master page to fill in. Works only
* when master pages are being used, and only then within a view that will be
* embedded within a master page.
*/
function smarty_block_content($params, $content, $template, &$repeat)
{
if ($content != null) {
Templating::$placeholder_data[$params['name']] = $content;
}
return null;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.action.php
<?php
function smarty_function_action($params, $template)
{
$defaults = array(
'action' => null,
'controller' => Phoenix::$request->controller_name
);
$params = array_merge($defaults, $params);
$urlparams = array();
foreach ($params as $key => $value) {
if ($value === null || $key == 'controller' || $key == 'action') continue;
$urlparams[$key] = $value;
}
$url = Router::CreateUrl($params['controller'], $params['action'], $urlparams);
return str_ireplace('%2F', '/', rawurlencode($url));
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.actlink.php
<?php
function smarty_function_actlink($params, $template)
{
$defaults = array(
'text' => 'Link',
'action' => null,
'controller' => Phoenix::$request->controller_name,
'img' => null,
'alt' => null,
'url' => null
);
$params = array_merge($defaults, $params);
$htmlattr = array();
$imgattr = array();
$urlparams = array();
foreach ($params as $key => $value) {
if ($value === null || $key == 'controller' || $key == 'action' || $key == 'text' || $key == 'img' || $key == 'alt') continue;
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
} else if (substr($key, 0, 4) == 'img_') {
$imgattr[substr($key, 4)] = $value;
} else {
$urlparams[$key] = $value;
}
}
if ($params['img'] !== null) {
$imgattr['src'] = $params['img'];
$imgattr['alt'] = $params['alt'] == null ? $params['text'] : $params['alt'];
$img = '<img';
foreach ($imgattr as $key => $value) {
$img .= ' '.$key.'="'.$value.'"';
}
$img .= '>';
$params['text'] = $img;
}
$url = $params['url'];
if ($url === null) {
$url = Router::CreateUrl($params['controller'], $params['action'], $urlparams);
}
$htmlattr['href'] = str_ireplace('%2F', '/', rawurlencode($url));
$link = '<a';
foreach ($htmlattr as $key => $value) {
$link .= ' '.$key.'="'.$value.'"';
}
$link .= '>'.$params['text'].'</a>';
return $link;
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.placeholder.php
<?php
function smarty_function_placeholder($params, $template)
{
if (!array_key_exists('name', $params) || !array_key_exists($params['name'], Templating::$placeholder_data)) {
return '';
}
return Templating::$placeholder_data[$params['name']];
}
<file_sep>/Phoenix/Router.php
<?php
class Router {
static $default_controller = 'Home';
static $default_action = 'Index';
static $request_route = '/';
static $request_controller = '';
static $request_action = '';
static $request_params = array();
static $_error = null;
static $_registered = array();
public static function RegisterCustomRouter($router)
{
Router::$_registered[] = $router;
}
public static function ControllerExists($controller)
{
return class_exists($controller, true);
}
public static function ActionExists($controller, $action)
{
if (!Router::ControllerExists($controller)) return null;
$c = new $controller;
return Router::GetActionName($c, $action) != null;
}
protected static function GetActionName($controller, $action)
{
$search = strtolower($action);
$search_post = $search.'_post';
$methods = get_class_methods($controller);
if ($methods == null) return null;
if (Post::IsPostBack()) {
foreach ($methods as $method) {
if (strtolower($method) == $search_post) {
return $method;
}
}
}
foreach ($methods as $method) {
if ((strtolower($method) == $search)) {
return $method;
}
}
return null;
}
protected static function GetActionParams($controller, $action)
{
$method = new ReflectionMethod($controller, $action);
return $method->getNumberOfRequiredParameters();
}
static function CreateUrl($controller, $action, $params = array())
{
$url = Phoenix::$base_url.$controller;
if ($action !== null) $url .= '/' . $action;
foreach ($params as $key => $value) {
$url .= '/'.$value;
}
return $url;
}
static function Redirect($controller = null, $action = null, $params = array())
{
if ($controller == null) {
$controller = Router::$request_controller;
$action = Router::$request_action;
$params = Router::$request_params;
} else if ($action == null) {
$action = Router::$default_action;
$params = array();
}
$url = Router::CreateUrl($controller, $action, $params);
header("Location: $url");
}
protected function CanResolve($route)
{
return true;
}
/**
* @param $route
* @return RouteParameters
*/
protected function ResolveRoute($route)
{
$replaced = str_replace('\\', '/', $route);
$trimmed = trim($replaced, '/');
$ret = new RouteParameters();
$ret->route = $trimmed;
$con = Router::$default_controller;
$act = Router::$default_action;
$args = array();
$split = explode('/', $trimmed);
$count = count($split);
if ($trimmed == '') $count = 0;
// Getting the controller
if ($count > 0) {
$con = $split[0];
}
$control = $con.'Controller';
if (!Router::ControllerExists($control)) {
Router::$_error = "Controller not found: $con.";
return null;
}
$ret->controller = new $control;
$ret->controller_name = substr(get_class($ret->controller), 0, -strlen('Controller'));
// Getting the action
if ($count > 1) {
$act = $split[1];
}
$action = Router::GetActionName($ret->controller, $act);
if ($action == null) {
Router::$_error = "Action not found: $act.";
return null;
}
$ret->action_name = preg_replace('/^(.*)_Post$/i', '\1', $action);
$ret->action = $action;
// Getting the args
if ($count > 2) {
$args = array_slice($split, 2);
}
$num_params = Router::GetActionParams($ret->controller, $ret->action);
if ($num_params > count($args)) {
Router::$_error = "Not enough parameters: Required $num_params, got " . count($args) . ".";
return null;
}
$ret->params = $args;
return $ret;
}
/**
* Gets a controller instance for a specified route. The route format
* is assumed to be: /Controller/Action/Param1/Param2/...<br />
* The following routes are permitted:<br />
* <ul>
* <li>Empty string (uses defaults)</li>
* <li>/ (uses defaults)</li>
* <li>/Controller/ (uses default action)</li>
* <li>/Controller/Action/ (no params)</li>
* <li>/Controller/Action/Param1/... (any number of params)</li>
* </ul>
* The only time a controller or action can be omitted is when
* there are no parameters. A route such as /Controller/Param1 will not
* work.
*
* @param string $route The route to resolve
* @return RouteParameters The resolved route
*/
static function Resolve($route)
{
// Loop through registered route handlers
foreach (Router::$_registered as $rtr)
{
if ($rtr->CanResolve($route))
{
$rt = $rtr->ResolveRoute($route);
Router::SetRouteVars($rt);
return $rt;
}
}
// Use default
$def = new Router();
$rt = $def->ResolveRoute($route);
Router::SetRouteVars($rt);
return $rt;
}
protected static function SetRouteVars($route)
{
if ($route == null) return;
Router::$request_route = $route->route;
Router::$request_controller = $route->controller_name;
Router::$request_action = $route->action;
Router::$request_params = $route->params;
}
}
class DefaultRouter extends Router
{
protected $map;
protected $pattern;
protected $defaults;
protected $options;
/**
* @param string $map Allows patterns in the following forms:
* <ul>
* <li>{*controller}/{*action}/{*} (behaviour of the default route, the * field must always be on the end)</li>
* <li>{controller}/{*} (action and controller must have default values if they are excluded)</li>
* <li>{controller}/{!action}/{*} (this will catch routes where the value in the !action field is not a valid action)</li>
* <li>{controller}/(action}/{*id}/{*page} (this will match routes with 0, 1, or 2 arguments on the end. both id and page are optional}</li>
* <li>{controller}/{action}/{id}/{*page} (page is optional, but id is not)</li>
* <li>{controller}/{action}/{id}/{*} (id is a single parameter, * catches all remaining parameters and is always optional)</li>
* </ul>
* @param array $defaults The default values of this pattern. If excluded for optional fields, the value passed will be null.
* @param array $options Allowed options:
* <ul>
* <li>params_as_string (boolean): If true, the parameters of the route will be assembled into a single string, separated by the '/' character.</li>
* </ul>
* @return DefaultRouter
*/
static function Create($map, $defaults, $options = array()) {
return new DefaultRouter($map, $defaults, $options);
}
function __construct($map, $defaults, $options = array()) {
$this->map = $map;
$this->defaults = $defaults;
$this->pattern = new DefaultRouterPattern($this->map, $this->defaults);
$this->options = array_merge(array(
'params_as_string' => false
), $options);
}
protected function CanResolve($route)
{
return $this->pattern->Match($route) != null;
}
protected function ResolveRoute($route)
{
$match = $this->pattern->Match($route);
$ret = new RouteParameters();
$ret->route = trim($route, "\\/ ");
$con = array_key_exists('controller', $match) ? $match['controller'] : $this->defaults['controller'];
$act = array_key_exists('action', $match) ? $match['action'] : $this->defaults['action'];
$args = array_key_exists('params', $this->defaults) ? $this->defaults['params'] : array();
$control = $con.'Controller';
if (!Router::ControllerExists($control)) {
Router::$_error = "Controller not found: $con.";
return null;
}
$ret->controller = new $control;
$ret->controller_name = substr(get_class($ret->controller), 0, -strlen('Controller'));
$action = Router::GetActionName($ret->controller, $act);
if ($action == null) {
Router::$_error = "Action not found: $act.";
return null;
}
$ret->action_name = preg_replace('/^(.*)_Post$/i', '\1', $action);
$ret->action = $action;
foreach ($match as $name => $value) {
if ($name == 'controller' || $name == 'action') continue;
if ($name == '*') foreach (explode('/', $value) as $split) $args[] = $split;
else $args[] = $value;
}
if ($this->options['params_as_string'] === true) {
$p = implode('/', $args);
$args = array($p);
}
$num_params = Router::GetActionParams($ret->controller, $ret->action);
if ($num_params > count($args)) {
Router::$_error = "Not enough parameters: Required $num_params, got " . count($args) . ".";
return null;
}
$ret->params = $args;
return $ret;
}
}
class DefaultRouterPattern
{
private $map;
private $regex_groups;
private $defaults;
private $match_cache;
function __construct($map, $defaults)
{
$this->map = $map;
$this->regex_groups = array();
$this->defaults = $defaults;
$this->match_cache = array();
// Map syntax (e.g): {controller}/{action}/{*}
// Reserved names: {controller}, {action}, {*}
// Match only actions/controllers that do not exist: {!controller}, {!action}
$map = trim($map, "\\/ ");
$check_controller = strstr($map, '{controller}');
if ($check_controller === false && !array_key_exists('controller', $defaults)) {
trigger_error('Badly formed route: ' . $map . ' - {controller} must be in the route, or set in the defaults.', E_USER_NOTICE);
return null;
}
$check_action = strstr($map, '{action}');
if ($check_action === false && !array_key_exists('action', $defaults)) {
trigger_error('Badly formed route: ' . $map . ' - {action} must be in the route, or set in the defaults.', E_USER_NOTICE);
return null;
}
// $check_catch_all = strstr($map, '{*}', true); // Requires PHP >= 5.3
$check_catch_all = substr($map, 0, strpos($map, '{*}'));
if ($check_catch_all !== false && strlen($check_catch_all) != strlen($map) - 3) {
trigger_error("Badly formed route: " . $map . " - the catch-all {*} must be at the end of the route.", E_USER_NOTICE);
return null;
}
$groups = explode('/', $map);
$count = 0;
$regex = '';
$r_groups = array();
foreach ($groups as $group) {
$offset = 0;
if (strlen($regex) != 0) $regex .= '/';
while (preg_match('/\{([^}]*)\}/', $group, $matches, PREG_OFFSET_CAPTURE, $offset)) {
$count++;
$index = $matches[0][1];
$length = strlen($matches[0][0]);
$name = $matches[1][0];
$regex .= substr($group, $offset, $index - $offset) . ($name == '*' ? "(.*)" : "([^\\\\/]*?)");
if (strstr($name, '*') === false) {
$this->regex_groups = array();
}
$actual_name = $name == '*' ? '*' : str_replace('*', '', $name);
$group_index = $count;
$r_groups[$group_index] = $actual_name;
$offset = $index + $length;
}
if ($offset < strlen($group)) $regex .= substr($group, $offset);
if ($offset == 0) $this->regex_groups = array();
$this->regex_groups[$regex] = $r_groups;
}
}
/**
* @param $route
* @return array
*/
function Match($route)
{
$route = trim($route, "\\/ ");
if (!array_key_exists($route, $this->match_cache)) {
foreach ($this->regex_groups as $regex => $groups) {
if (preg_match("%^$regex$%", $route, $result)) {
$values = $this->defaults;
foreach ($groups as $index => $name) {
$actual_name = $name;
if ($name == '!action') $actual_name = 'action';
if ($name == '!controller') $actual_name = 'controller';
$default = array_key_exists($actual_name, $this->defaults) ? $this->defaults[$actual_name] : null;
$val = trim($result[$index]);
if ($val == null || strlen($val) == 0) $val = $default;
$values[$name] = $val;
}
$nc = array_key_exists('!controller', $values);
$na = array_key_exists('!action', $values);
$controller = ($nc ? $values['!controller'] : $values['controller']) . 'Controller';
$action = $na ? $values['!action'] : $values['action'];
$ce = Router::ControllerExists($controller);
$ae = Router::ActionExists($controller, $action);
if ($ce ? $nc : !$nc) continue;
if ($ae ? $na : !$na) continue;
$this->match_cache[$route] = $values;
break;
}
}
}
return array_key_exists($route, $this->match_cache) ? $this->match_cache[$route] : null;
}
}
// These are for backwards compatibility only, do not use
/**
* @deprecated
*/
class PageActionRouter extends DefaultRouter {
function __construct($controller, $action = 'Page', $array_params = false) {
parent::__construct(
$controller.'/{!action}/{*}',
array(
'controller' => $controller,
'action' => $action
), array(
'params_as_string' => !$array_params
));
}
}
/**
* @deprecated
*/
class UnknownControllerRouter extends DefaultRouter {
function __construct($controller, $action, $array_params = false) {
parent::__construct(
'{!controller}/{*}',
array(
'controller' => $controller,
'action' => $action
), array(
'params_as_string' => !$array_params
));
}
}
/**
* @deprecated
*/
class SkippingRouter extends DefaultRouter {
function __construct($defaults)
{
$con = isset($this->defaults['Controller']);
$act = isset($this->defaults['Action']);
$def = array();
if ($con) $def['controller'] = $defaults['Controller'];
if ($act) $def['action'] = $defaults['Action'];
parent::__construct(
trim(($con ? '' : '{controller}') . '/' . ($act ? '' : '{action}') . '/{*}', '/'),
$def
);
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.hidden.php
<?php
function smarty_function_hidden($params, $template)
{
$defaults = array(
'model' => null
);
$params = array_merge($defaults, $params);
$htmlattr = array();
$htmlattr['type'] = 'hidden';
$htmlattr['name'] = $params['for'];
$model = $params['model'];
if ($model != null && ($model instanceof Model || $model instanceof CustomQueryRow)) {
$htmlattr['value'] = $model->{$params['for']};
} else if (isset($params['value']) && $params['value'] != null) {
$htmlattr['value'] = $params['value'];
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$field = '<input';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= ' />';
return $field;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.master.php
<?php
function smarty_function_master($params, $template)
{
$defaults = array(
);
$params = array_merge($defaults, $params);
$view = Templating::Create();
$view->assign(Phoenix::$request->controller->viewData);
foreach ($params as $name => $value) {
if ($name == 'view') {
continue;
}
$view->assign($name, Templating::$placeholder_data[$value]);
}
$params['view'] = Views::Find($params['view']);
return $view->fetch($params['view']);
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.field.php
<?php
function smarty_function_field($params, $template)
{
$defaults = array(
'type' => stristr($params['for'], 'password') !== false ? 'password' : 'text',
'ignore_post' => false,
'disabled' => false,
'model' => null
);
$params = array_merge($defaults, $params);
if (strtolower($params['type']) == 'openid') {
$params['type'] = 'text';
$params['html_class'] = trim($params['html_class'] . ' openid-input');
if (!array_key_exists('for', $params))
{
$params['for'] = 'openid';
}
}
$htmlattr = array();
if ($params['disabled'] === true) {
$htmlattr['disabled'] = 'disabled';
}
$htmlattr['type'] = $params['type'];
$htmlattr['name'] = $params['for'];
$htmlattr['id'] = 'form_'.$params['for'];
$model = $params['model'];
if ($params['ignore_post'] === false && Post::IsPostBack() && Post::Get($params['for']) != null) {
$htmlattr['value'] = Post::Get($params['for']);
} else if ($model != null && ($model instanceof Model || $model instanceof CustomQueryRow)) {
$htmlattr['value'] = $model->{$params['for']};
} else if (isset($params['value']) && $params['value'] != null) {
$htmlattr['value'] = $params['value'];
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
if (Validation::HasErrors($params['for'])) {
$htmlattr['class'] = trim((isset($htmlattr['class']) ? $htmlattr['class'] : '') . ' validation-error-field');
}
$field = '<input';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= ' />';
return $field;
}
<file_sep>/App/Models/User.php
<?php
class User extends Model
{
public $table = 'Users';
public $columns = array(
'ID' => 'ID',
//'Level' => 'Level', // For Level Authorisation
//'RoleID' => 'RoleID', // For Role Authorisation (see below)
'Name' => 'Name',
'Password' => '<PASSWORD>',
'OpenID' => 'OpenID',
'Email' => 'Email',
'Cookie' => 'Cookie',
'NumLogins' => 'NumLogins',
'LastLogin' => 'LastLogin',
'LastAccess' => 'LastAccess',
'LastPage' => 'LastPage',
'IP' => 'IP',
'Unlock' => 'Unlock'
);
public $alias = array();
public $primaryKey = 'ID';
public $one = array(
// 'Role' => array('RoleID' => 'ID') // For Role Authorisation
);
public $many = array(
// 'UserPermission' => array('ID' => 'UserID') // For Permission Authorisation (see below)
);
public $validation = array(
'Name' => array('required', 'db-unique'),
'Password' => array('<PASSWORD>'),
// 'OpenID' => array('required') // Depending on your auth setup, change validation as needed
);
public $mappings = array();
}
/*
* When using Permission based authorisation (refer to the documentation for more info):
* 1. Uncomment the UserPermission relationship in $many
* 2. Create a UserPermission model with $one relationships to both User and Permission
* 3. Create a Permission model with a $many relationship to UserPermission
* 4. Configure the PermissionAuthorisation class with the model, join and field names
*
* When using Role based authorisation (again, refer to documentation for more info):
* 1. Uncomment the RoleID field and the Role relationship in $one
* 2. Create a Role model with a $many relationship to User
* 3. Configure the RoleAuthorisation class with the model and field names
*/<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.resolve.php
<?php
function smarty_function_resolve($params, $template)
{
$defaults = array(
'path' => ''
);
$params = array_merge($defaults, $params);
return rtrim(Phoenix::$base_url, '/') . '/' . ltrim($params['path'], '/');
}
?>
<file_sep>/Phoenix/Hooks.php
<?php
class Hooks {
private static $_route = array();
private static $_request = array();
private static $_result = array();
private static $_render = array();
public static function RegisterRouteHook($hook)
{
Hooks::$_route[] = $hook;
}
public static function RegisterRequestHook($hook)
{
Hooks::$_request[] = $hook;
}
public static function RegisterResultHook($hook)
{
Hooks::$_result[] = $hook;
}
public static function RegisterRenderHook($hook)
{
Hooks::$_render[] = $hook;
}
public static function ExecuteRouteHooks($route)
{
foreach (Hooks::$_route as $hook)
{
$hook->Execute($route);
}
}
public static function ExecuteRequestHooks($request)
{
foreach (Hooks::$_request as $hook)
{
$hook->Execute($request);
}
}
public static function ExecuteResultHooks($result)
{
foreach (Hooks::$_result as $hook)
{
$hook->Execute($result);
}
}
public static function ExecuteRenderHooks($result)
{
foreach (Hooks::$_render as $hook)
{
$hook->Execute($result);
}
}
}
Hooks::RegisterRequestHook(new CheckErrorsRequestHook());
Hooks::RegisterRequestHook(new SetTemplatingDefaultsRequestHook());
class Hook {
function Execute($item)
{
}
}
class CheckErrorsRequestHook extends Hook {
function Execute($request)
{
$error = null;
if ($request == null) {
Phoenix::$request = new RouteParameters();
$error = array(Router::$_error);
}
if (Authentication::IsCurrentUserBanned())
{
if (Phoenix::$request->controller_name != Authentication::$ban_controller
|| Phoenix::$request->action_name != Authentication::$ban_action)
{
$cname = Authentication::$ban_controller . 'Controller';
Phoenix::$request->action = Authentication::$ban_action;
Phoenix::$request->action_name = Authentication::$ban_action;
Phoenix::$request->controller_name = Authentication::$ban_controller;
Phoenix::$request->params = array();
Phoenix::$request->controller = new $cname();
return;
}
}
if (!Authorisation::Check($request)) {
$error = array("You do not have permission to access this page.");
}
if ($error != null) {
$cname = Phoenix::$error_controller . 'Controller';
Phoenix::$request->action = Phoenix::$error_action;
Phoenix::$request->action_name = Phoenix::$error_action;
Phoenix::$request->controller_name = Phoenix::$error_controller;
Phoenix::$request->params = $error;
Phoenix::$request->controller = new $cname();
}
}
}
class SetTemplatingDefaultsRequestHook extends Hook {
function Execute($request)
{
Templating::SetDefaults($request);
}
}
?><file_sep>/Phoenix/Libs/Smarty.Phoenix/modifier.filesize.php
<?php
function smarty_modifier_filesize($bytes)
{
if ($bytes < 1024) return $bytes . 'B';
$kbytes = $bytes / 1024;
if ($kbytes < 1024) return round($kbytes, 2) . 'kB';
$mbytes = $kbytes / 1024;
if ($mbytes < 1024) return round($mbytes, 2) . 'MB';
$gbytes = $mbytes / 1024;
if ($gbytes < 1024) return round($gbytes, 2) . 'GB';
$tbytes = $gbytes / 1024;
if ($tbytes < 1024) return round($tbytes, 2) . 'TB';
$pbytes = $tbytes / 1024;
return round($pbytes, 2) . 'PB';
}
<file_sep>/Phoenix/Authorisation.php
<?php
class Authorisation
{
public static $redirect_action = 'Index';
public static $redirect_controller = 'Error';
public static $redirect_params = array('You do not have permission to access this page.');
/**
* The current authorisation method that is being used
* @var AuthorisationMethod
*/
public static $_method;
static function SetAuthorisationMethod($method)
{
Authorisation::$_method = $method;
}
/**
* Quickly check if the logged-in user has the specified credentials. Implementation
* of this function depends on the authorisation method used. For example, the role
* auth method will check to see if the user's role is equal to the one provided.
* @param RouteParameters $request
*/
static function CheckCredentials($cred)
{
$user = Authentication::GetUser();
if ($user == null) return false;
return Authorisation::$_method->HasCredentials(
$user,
$cred
);
}
/**
* Check a resolved route to see if the current user has permission to access it
* @param RouteParameters $request
*/
static function Check($request)
{
return Authorisation::$_method->HasPermission(
Authentication::GetUser(),
$request == null ? null : $request->controller,
$request == null ? null : $request->action_name
);
}
/**
* Returns true if the current user can access the specified controller and action
* @param $controller string The controller name
* @param $action string The action name
*/
static function CanAccess($controller, $action = null)
{
if ($action === null)
{
$split = explode('/', $controller);
if (count($split) != 2)
{
return false;
}
$controller = $split[0];
$action = $split[1];
}
$cname = $controller.'Controller';
if (!class_exists($cname))
{
return false;
}
$con = new $cname;
return Authorisation::$_method->HasPermission(
Authentication::GetUser(),
$con,
$action
);
}
}
Authorisation::SetAuthorisationMethod(new DefaultAuthorisation());
class AuthorisationMethod
{
function GetAuthValue($controller, $action, $default) {
$auth = null;
if ($controller != null) {
$auth = $controller->authorise;
}
if ($auth == null) {
$auth = array();
}
if (array_key_exists($action, $auth)) {
return $auth[$action];
} elseif (array_key_exists('*', $auth)) {
return $auth['*'];
} else {
return $default;
}
}
function HasPermission($user, $controller, $action) {
// Virtual
}
function HasCredentials($user, $cred) {
// Virtual; Implementation varies depending on auth method
}
}
/**
* Default authorisation implementation. Everyone can access everything.
*/
class DefaultAuthorisation extends AuthorisationMethod
{
function HasPermission($user, $controller, $action) {
return true;
}
function HasCredentials($user, $cred) {
return true;
}
}
/**
* Login based method of authorisation.<br>
* The controller setup is:
* <pre>
* public $authorise = array(
* 'ActOne' => true, // user must be logged in to access
* 'ActTwo' => false // anyone can access
* // other omitted actions are considered to be false
* );
* </pre>
*/
class LoggedInAuthorisation extends AuthorisationMethod
{
function HasPermission($user, $controller, $action) {
$needslogin = $this->GetAuthValue($controller, $action, false);
if ($needslogin) {
return Authentication::IsLoggedIn();
}
return true;
}
function HasCredentials($user, $cred) {
return true;
}
}
/**
* A level based method of authorisation. Each user has a single level
* associated with them, contained within the user object. The level must be
* a numeric value.<br>
* The controller setup is:
* <pre>
* public $authorise = array(
* 'ActOne' => 10, // user must be level 10 or higher to access
* 'ActTwo' => 0, // user must be authenticated to access
* 'ActThree' => -1 // anyone can access
* // other omitted actions are considered to be -1
* );
* </pre>
*/
class LevelAuthorisation extends AuthorisationMethod
{
public static $field_level = 'Level';
function HasPermission($user, $controller, $action) {
$level = $this->GetAuthValue($controller, $action, -1);
if (!is_numeric($level)) {
return true;
}
if ($level < 0) {
return true;
}
if ($level == 0) {
return $user != null;
}
if ($user != null) {
return $user->{LevelAuthorisation::$field_level} >= $level;
}
return false;
}
function HasCredentials($user, $cred) {
if (!is_numeric($cred)) return false;
return $user->{LevelAuthorisation::$field_level} >= $cred;
}
}
/**
* A permission based method of authorisation. Each user has many permissions
* associated with them. The permissions must be joined to the user model as
* as many-to-many relationship.
* The controller setup is:
* <pre>
* public $authorise = array(
* 'ActOne' => 'ExecActOne', // user must have permission 'ExecActOne' to access
* 'ActTwo' => '', // user must be authenticated to access
* 'ActThree' => null // anyone can access
* // other omitted actions are considered to be null
* );
* </pre>
*/
class PermissionAuthorisation extends AuthorisationMethod
{
private $model_join;
private $model_permission;
private $field_name;
private $_permission_cache;
function __construct($model_join, $model_permission, $field_name)
{
$this->model_join = $model_join;
$this->model_permission = $model_permission;
$this->field_name = $field_name;
$this->_permission_cache = array();
}
private function _UpdateCache($user)
{
$user_id = $user->{$user->primaryKey};
$permission_instance = new $this->model_permission;
$join_instance = new $this->model_join;
$join_to_permission = $join_instance->one[$this->model_permission];
$join_permission_this_key = array_keys($join_to_permission); $join_permission_this_key = $join_permission_this_key[0];
$join_permission_other_key = $join_to_permission[$join_permission_this_key];
$join_to_user = $join_instance->one[get_class($user)];
$join_user_this_key = array_keys($join_to_user); $join_user_this_key = $join_user_this_key[0];
$join_user_other_key = $join_to_user[$join_user_this_key];
$field_name = $this->field_name;
$perms = array();
$sql = "SELECT P.`{$field_name}` AS Name FROM `{$user->table}` U
INNER JOIN `{$join_instance->table}` UP ON U.`{$join_user_other_key}` = UP.`{$join_user_this_key}`
LEFT JOIN `{$permission_instance->table}` P ON UP.`{$join_permission_this_key}` = P.`{$join_permission_other_key}`
WHERE U.`{$user->primaryKey}` = :userid";
$params = array('userid' => $user_id);
foreach (CustomQuery::Query($sql, $params) as $row) $perms[] = $row->Name;
$this->_permission_cache[$user_id] = $perms;
}
function HasPermission($user, $controller, $action) {
$perm = $this->GetAuthValue($controller, $action, null);
return $this->HasCredentials($user, $perm);
}
function HasCredentials($user, $cred)
{
if ($cred === null) return true;
if (!is_string($cred) && !is_array($cred)) return true;
if ($user == null) return false;
if ((is_string($cred) && strlen($cred) == 0) || (is_array($cred) && count($cred) == 0)) return true;
if (is_string($cred)) $cred = array($cred);
$uid = $user->{$user->primaryKey};
if (!array_key_exists($uid, $this->_permission_cache) || $this->_permission_cache[$uid] === null) $this->_UpdateCache($user);
$perms = $this->_permission_cache[$uid];
foreach ($cred as $c) {
if (array_search($c, $perms) !== false) {
return true;
}
}
return false;
}
}
/**
* A role based method of authorisation. Each user has a single role
* associated with them. The roles must be joined to the user model as
* as many-to-one relationship.
* The controller setup is:
* <pre>
* public $authorise = array(
* 'ActOne' => array('Admin', 'SuperUser'), // user must be an Admin or a SuperUser to access
* 'ActTwo' => array(), // user must be authenticated to access
* 'ActThree' => null // anyone can access
* // other omitted actions are considered to be null
* );
* </pre>
*/
class RoleAuthorisation extends AuthorisationMethod
{
private $model_role;
private $field_name;
function __construct($model_role, $field_name)
{
$this->model_role = $model_role;
$this->field_name = $field_name;
}
function HasPermission($user, $controller, $action) {
$roles = $this->GetAuthValue($controller, $action, null);
if ($roles === null) {
return true;
}
if (is_string($roles)) {
$roles = array($roles);
}
if (!is_array($roles)) {
return true;
}
if (count($roles) == 0) {
return $user != null;
}
if ($user != null) {
$rolequery = $user->Get(
$this->model_role
);
$role = $rolequery->{$this->field_name};
return $role != null && array_search($role, $roles) !== false;
}
return false;
}
function HasCredentials($user, $cred) {
$rolequery = $user->Get(
$this->model_role
);
$role = $rolequery->{$this->field_name};
return $role == $cred;
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/block.form.php
<?php
function smarty_block_form($params, $content, $template, &$repeat)
{
if ($repeat) // First call, opening tag, $content = NULL
{
$con = Router::$request_controller;
$act = Router::$request_action;
$pms = Router::$request_params;
$mtd = 'post';
if (array_key_exists('controller', $params)) {
$con = $params['controller'];
$act = Router::$default_action;
$pms = array();
}
if (array_key_exists('action', $params)) {
$act = $params['action'];
$pms = array();
}
if (array_key_exists('method', $params)) {
$mtd = $params['method'];
}
$upl = false;
if (array_key_exists('upload', $params)) {
$upl = $params['upload'] === true;
}
$htmlattr = array();
$urlparams = array();
foreach ($params as $key => $value) {
if ($key == 'controller' || $key == 'action' || $key == 'method' || $key == 'upload') continue;
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
} else {
$urlparams[$key] = $value;
}
}
if (count($urlparams) > 0) {
$pms = $urlparams;
}
$url = Phoenix::$base_url.$con.'/'.$act;
foreach ($pms as $key => $value) {
$url .= '/'.$value;
}
$url = str_ireplace('%2F', '/', rawurlencode($url));
$ret = sprintf('<form action="%s" method="%s"', $url, $mtd);
if ($upl) {
$ret .= ' enctype="multipart/form-data"';
}
foreach ($htmlattr as $key => $value) {
$ret .= ' '.$key.'="'.$value.'"';
}
$ret .= '>';
}
else // Second call, closing tag, $content = parsed output of block content
{
$ret = $content . '</form>';
}
return $ret;
}
<file_sep>/Phoenix/AutoLoad.php
<?php
function get_file_ci($filename) {
if (file_exists($filename)) return $filename;
$dir = dirname($filename);
foreach(glob($dir . '/*') as $file) {
if (strtolower($file) == strtolower($filename)) {
return $file;
}
}
return $filename;
}
function PhoenixTryLoadFile($file)
{
$file = get_file_ci($file);
if (file_exists($file)) {
require_once $file;
return true;
}
return false;
}
function PhoenixAutoLoad($class_name)
{
$file_name = $class_name.'.php';
// Check for a controller request
if (strlen($class_name) > 10 && substr($class_name, -10) == 'Controller')
{
// Extract the name from the controller
$controller_name = substr($class_name, 0, -10).'.php';
// Check app controllers
if (PhoenixTryLoadFile(Phoenix::$app_dir.'/Controllers/'.$controller_name)) return;
// Check framework controllers
if (PhoenixTryLoadFile(Phoenix::$phoenix_dir.'/Controllers/'.$controller_name)) return;
}
// If not a controller, probably a model
if (PhoenixTryLoadFile(Phoenix::$app_dir.'/Models/'.$file_name)) return;
// Otherwise, probably a framework file
if (PhoenixTryLoadFile(Phoenix::$phoenix_dir.'/'.$file_name)) return;
// None of the above, possibly a user defined helper?
if (PhoenixTryLoadFile(Phoenix::$app_dir.'/Helpers/'.$file_name)) return;
// We have a few system-level helpers as well
if (PhoenixTryLoadFile(Phoenix::$phoenix_dir.'/Helpers/'.$file_name)) return;
}
spl_autoload_register('PhoenixAutoLoad');
?>
<file_sep>/Phoenix/ExceptionHandler.php
<?php
function getExceptionTraceAsString($exception) {
$rtn = "";
$count = 0;
foreach ($exception->getTrace() as $frame) {
if (!array_key_exists('file', $frame)) $frame['file'] = '(Unknown File)';
if (!array_key_exists('line', $frame)) $frame['line'] = '??';
if (!array_key_exists('function', $frame)) $frame['function'] = '(Anonymous Method)';
$rtn .= sprintf( "#%s %s(%s): %s\n", $count, $frame['file'], $frame['line'], $frame['function']);
$count++;
}
return $rtn;
}
/**
*
* @param Exception $exception
*/
function PhoenixExceptionHandler($exception) {
echo "<h1>Something <em>really</em> bad happened!</h1>\n";
echo "<h2>Uncaught exception</h2>\n";
echo str_replace("\n", "<br>\n", $exception->getMessage()) . "<br><br>\n\nStacktrace:<br>\n";
echo str_replace("\n", "<br>\n", getExceptionTraceAsString($exception));
}
set_exception_handler('PhoenixExceptionHandler');
?>
<file_sep>/Phoenix/Views.php
<?php
class Views
{
/**
* Searches for a view in the following order:
* <ul>
* <li>(App)/Views/[Controller]/[Name].tpl</li>
* <li>(App)/Views/Shared/[Name].tpl</li>
* <li>(Phoenix)/Views/[Controller]/[Name].tpl</li>
* <li>(Phoenix)/Views/Shared/[Name].tpl</li>
* </ul>
* The name can also contain at most one forward slash (/), to
* define a specific folder to look in. For example, a name like
* 'Home/Index' would not search in the shared folders. For the same
* request, a name such as 'Forums/Index' will force a different
* controller's directory to be searched. Will throw an exception if the
* view cannot be found.
* @param string $name The name of the view to find
* @return string The full view location
*/
static function Find($vname)
{
$name = $vname;
if ($name == null || strlen($name) == 0) {
$name = Phoenix::$request->action;
$vname = '[null]';
}
$dirs = array();
$vd = '/Views/';
$cd = Phoenix::$request->controller_name.'/';
$sd = 'Shared/';
$count = 0;
$dirs[$count++] = array('prepend' => $cd, 'search' => Phoenix::$app_dir.$vd.$cd, 'err' => '[app]'.$vd.$cd);
if (strstr($name, '/') !== false) {
$dirs[$count++] = array('prepend' => '', 'search' => Phoenix::$app_dir.$vd, 'err' => '[app]'.$vd);
}
$dirs[$count++] = array('prepend' => $sd, 'search' => Phoenix::$app_dir.$vd.$sd, 'err' => '[app]'.$vd.$sd);
$dirs[$count++] = array('prepend' => $cd, 'search' => Phoenix::$phoenix_dir.$vd.$cd, 'err' => '[framework]'.$vd.$cd);
if (strstr($name, '/') !== false) {
$dirs[$count++] = array('prepend' => '', 'search' => Phoenix::$phoenix_dir.$vd, 'err' => '[framework]'.$vd);
}
$dirs[$count++] = array('prepend' => $sd, 'search' => Phoenix::$phoenix_dir.$vd.$sd, 'err' => '[framework]'.$vd.$sd);
if (substr($name, 0, -4) != '.tpl') {
$name .= '.tpl';
}
for ($i = 0; $i < count($dirs); $i++) {
$dir = $dirs[$i]['search'];
$prep = $dirs[$i]['prepend'];
$file = $dir.$name;
if (file_exists($file)) {
return $prep.$name;
}
}
$msg = "Unable to locate view for this request. The requested view was: $vname.\n";
$msg .= "Directories searched:\n";
foreach ($dirs as $dir) {
$msg .= " * {$dir['err']}\n";
}
throw new Exception($msg);
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.paginate.php
<?php
/**
* @param $params
* @param Smarty $template
* @param $template
* @return string
*/
function smarty_function_paginate($params, $template)
{
$defaults = array(
'model' => null,
'current_page' => null,
'total_pages' => null,
'link_num' => 10,
'jumps' => true,
'format_spacer' => " \n",
'format_params' => '{page}',
'format_url' => null,
'format_jump_first' => '<<',
'format_jump_last' => '>>',
'format_current' => '<strong>[{page}]</strong>',
'format_number' => '<a href="{url}">{page}</a>',
'wrap_element' => 'div',
'wrap_class' => 'pagination',
'list' => false,
'list_class' => null,
'list_active_class' => 'active'
);
$params = array_merge($defaults, $params);
if ($params['model'] != null) {
$params['current_page'] = $params['model']->CurrentPage;
$params['total_pages'] = $params['model']->NumPages;
}
if ($params['format_url'] == null) {
if (!is_array($params['format_params'])) $params['format_params'] = array($params['format_params']);
$params['format_url'] = Router::CreateUrl(Phoenix::$request->controller_name, Phoenix::$request->action, $params['format_params']);
}
// These vars can be defined in the viewdata
if ($params['current_page'] === null) $params['current_page'] = $template->getVariable('current_page')->value;
if ($params['total_pages'] === null) $params['total_pages'] = $template->getVariable('total_pages')->value;
$cur = $params['current_page'];
$fst = 1;
$lst = $params['total_pages'];
$spc = $params['format_spacer'];
$num = $params['link_num'] / 2;
$jmp = $params['jumps'];
$url = $params['format_url'];
$wrp = $params['wrap_element'];
$wrc = $params['wrap_class'];
$lus = $params['list'];
$lcl = $params['list_class'];
$lac = $params['list_active_class'];
$lower = max($fst, $cur - $num);
$upper = min($lst, $cur + $num);
$jump_first = true;
$jump_last = true;
$leftover = ($num * 2) - ($upper - $lower);
if ($lower == $fst) {
$upper = min($lst, $upper + $leftover);
$jump_first = false;
}
if ($upper == $lst) {
$lower = max($fst, $lower - $leftover);
$jump_last = false;
}
$ret = '';
if ($lus) {
$ret .= '<ul'.($lcl==null?'':' class="'.$lcl.'"').'>';
}
if ($jmp && $jump_first) {
if ($lus) $ret .= '<li>';
$ret .= '<a href="' . str_ireplace('{page}', $fst, $url) . '">' . $params['format_jump_first'] . '</a>' . $spc;
if ($lus) $ret .= '</li>';
}
for ($i = $lower; $i <= $upper; $i++) {
if ($lus) $ret .= '<li'.($i==$cur&&$lac!=null?' class="'.$lac.'"':'').'>';
$format = $params['format_number'];
if ($i == $cur) $format = $params['format_current'];
$text = str_ireplace('{url}', $url, $format);
$text = str_ireplace('{page}', $i, $text);
if ($i == $lower && $jump_first) $ret .= '<span>...</span>' . $spc;
$ret .= $text . $spc;
if ($i == $upper && $jump_last) $ret .= '<span>...</span>' . $spc;
if ($lus) $ret .= '</li>';
}
if ($jmp && $jump_last) {
if ($lus) $ret .= '<li>';
$ret .= '<a href="' . str_ireplace('{page}', $lst, $url) . '">' . $params['format_jump_last'] . '</a>';
if ($lus) $ret .= '</li>';
}
if ($lus) {
$ret .= '</ul>';
}
$ret = trim($ret);
if ($wrp != null) {
$cls = $wrc == null ? '' : ' class="' . $wrc . '"';
$ret = '<' . $wrp . $cls . '>' . $ret . '</' . $wrp . '>';
}
return trim($ret);
}
?>
<file_sep>/Phoenix/Controllers/Error.php
<?php
class ErrorController extends Controller
{
public function Index($message)
{
Templating::SetPageTitle('Something Bad Happened!');
return $this->View($message);
}
}
?>
<file_sep>/Phoenix/Post.php
<?php
class Post
{
public static function IsPostBack() {
return $_SERVER['REQUEST_METHOD'] == 'POST';
}
public static function IsAjaxRequest() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
/**
* Get a postback variable
* @param string $name
* @param object $default Value to return if the variable doesn't exist
* @return object The post variable, or the default if it doesn't exist.
*/
public static function Get($name, $default = null) {
if (isset($_POST[$name]) && $_POST[$name] !== null) {
return $_POST[$name];
} else {
return $default;
}
}
/**
* Bind a class from the post back.
* @param object $class The class object or class name
* @param string $prefix Optional prefix for the post variable names
* @param array $vars Optional list of fields to bind. Default will bind all fields.
* @return Model
*/
public static function Bind($class, $prefix = '', $vars = array())
{
if (!$class instanceof Model) {
$class = new $class();
}
foreach ($class->columns as $db => $map) {
if (count($vars) != 0 && array_search($db, $vars) === false && array_search($map, $vars) === false) continue;
$dbval = Post::Get($prefix.$db);
$mapval = Post::Get($prefix.$map);
if ($dbval !== null) {
$class->$map = $class->MapValue($map, $dbval);
} else if ($mapval !== null) {
$class->$map = $class->MapValue($map, $mapval);
}
}
return $class;
}
public static function File($name) {
return new PostedFile($name);
}
}
class SelectListItem
{
public $ID;
public $Name;
public function __construct($id, $name)
{
$this->ID = $id;
$this->Name = $name;
}
public static function BuildFromArray($array)
{
$ret = array();
foreach ($array as $k => $v) {
$ret[] = new SelectListItem($k, $v);
}
return $ret;
}
}
class PostedFile
{
public static $error_messages = array(
UPLOAD_ERR_INI_SIZE => "The file exceeded the maximum file size limit.",
UPLOAD_ERR_FORM_SIZE => "The file exceeded the maximum file size limit.",
UPLOAD_ERR_PARTIAL => "The file failed to upload, please try again.",
UPLOAD_ERR_NO_FILE => "You must select a file to upload.",
UPLOAD_ERR_NO_TMP_DIR => "The file failed to upload, please try again.",
UPLOAD_ERR_CANT_WRITE => "The file failed to upload, please try again.",
UPLOAD_ERR_EXTENSION => "The file failed to upload, please try again."
);
private $_name;
private $_info;
private $_validated;
public function __construct($name)
{
$this->_validated = false;
$this->_name = $name;
if (isset($_FILES[$name]) && is_array($_FILES[$name])) {
$this->_info = $_FILES[$name];
} else {
$this->_info = array('error' => 4);
}
}
/**
* Get the file's extension without the leading '.'
*/
public function GetExtension()
{
$name = $this->_info['name'];
$ext = explode('.', $name);
return $ext[count($ext) - 1];
}
public function GetFileSize()
{
return $this->_info['size'];
}
public function Validate($required = true, $max_size = 0, $allowed_types = array(), $allowed_extensions = array())
{
$err = $this->_info['error'];
if ($err !== 0 && ($err !== 4 || $required !== false)) {
Validation::AddError($this->_name, PostedFile::$error_messages[$err]);
return false;
}
if ($err === 4) {
$this->_validated = true;
return true;
}
$size = $this->_info['size'];
if ($max_size > 0 && $size > $max_size) {
Validation::AddError($this->_name, 'The file exceeded the maximum file size limit.');
return false;
}
$name = $this->_info['name'];
if (count($allowed_extensions) > 0) {
$ext = strtolower($this->GetExtension());
if (array_search($ext, $allowed_extensions) === false) {
Validation::AddError($this->_name, 'This file extension is not allowed. Allowed extensions are: '. implode(', ', $allowed_extensions));
return false;
}
}
$type = $this->_info['type'];
if (count($allowed_types) > 0) {
if (array_search($type, $allowed_types) === false) {
Validation::AddError($this->_name, 'This file type is not allowed.');
return false;
}
}
$this->_validated = true;
return true;
}
public function Exists()
{
return $this->_validated === true && $this->_info['error'] != 4;
}
public function GetTempFile()
{
return $this->_info['tmp_name'];
}
public function Save($location, $overwrite = true)
{
if ($this->_validated !== true || $this->_info['error'] == 4) {
return null;
}
if (is_dir($location)) {
$location = rtrim($location, '/') . '/' . $this->_info['name'];
}
if (file_exists($location)) {
if ($overwrite !== true) {
return null;
} else {
unlink($location);
}
}
$res = move_uploaded_file($this->_info['tmp_name'], $location);
return $res === true ? $location : null;
}
public static function MakeSafeFileName($string, $allow_spaces = false, $invalid_chars = null)
{
if ($invalid_chars === null) {
$invalid_chars = array('[', ']', '/', '\\', '=', '+', '<', '>', ':', ';', '"', ',', '*', '|', '?');
}
foreach ($invalid_chars as $char) {
$string = str_ireplace($char, '', $string);
}
if (!$allow_spaces) {
$string = str_ireplace(' ', '_', $string);
}
return $string;
}
}
?>
<file_sep>/Phoenix/Query.php
<?php
/**
* An easy-to-use wrapper around the Model querying functions.
* Methods can be chained like so: <br>
* $result = Query::Create('User')->Where('ID', '>', 1)->OrderBy('ID', 'DESC')->All();
*/
class Query
{
private $_model;
private $_model_instance;
private $_params;
private $_where;
private $_order;
private $_limit;
function __construct($class) {
$this->_model = $class;
$this->_model_instance = new $class();
$this->_params = array();
$this->_where = array();
$this->_order = array();
$this->_limit = null;
}
/**
* Create a new query for a model
* @param string The class to query on
* @return Query A new query instance
*/
public static function Create($class) {
return new Query($class);
}
private function GetDbName($name) {
$db = $this->_model_instance->GetDBName($name);
return $db ? $db : $name;
}
/**
* Add a where clause to the query
* @param string $field The name of the field
* @param string $op The operator to use
* @param object $value The value to match against
* @return Query Self
*/
public function Where($field, $op, $value) {
$field = $this->GetDbName($field);
$pname = ':param'.(count($this->_params)+1);
$this->_where[] = "`$field` $op $pname";
$this->_params[$pname] = $value;
return $this;
}
/**
* Add an order to the query
* @param string $field The name of the field
* @param string $dir The direction to sort in (ASC or DESC)
* @return Query self
*/
public function OrderBy($field, $dir = 'ASC') {
$field = $this->GetDbName($field);
$this->_order[] = "`$field` $dir";
return $this;
}
/**
* Add a limit to the query
* @param int $limit The number of rows to take
* @param int $offset The number of rows to skip (default zero)
* @return Query self
*/
public function Limit($limit, $offset = 0) {
$this->_limit = '';
if ($offset > 0) {
$this->_limit .= "$offset,";
}
$this->_limit .= $limit;
return $this;
}
public function Count() {
return Model::Count($this->_model, $this->_where, $this->_params);
}
/**
* Execute the query and return a single result
* @return Model The result of the query
*/
public function One() {
$order = null;
if (count($this->_order) > 0) {
$order = implode(',', $this->_order);
}
$results = Model::Search($this->_model, $this->_where, $this->_params, $order, 1);
if (count($results) > 0) return $results[0];
else return new $this->_model();
}
/**
* Execute the query and return all results
* @return array The result of the query
*/
public function All() {
$order = null;
if (count($this->_order) > 0) {
$order = implode(',', $this->_order);
}
return Model::Search($this->_model, $this->_where, $this->_params, $order, $this->_limit);
}
/**
* Remember to only use this function when using an ordered query!
* @param int $items_per_page The number of items to display per page
* @param int $current_page The current page. The first index is 1. This can be equal to 'last' to fetch the last page
* @return object Items = the database items for this page,
* FirstPage = first page number,
* CurrentPage = current page number,
* LastPage = last page number,
* NumItems = total number of items,
* NumPages = total number of pages,
* ItemsPerPage = number of items per page
*/
public function Paginate($items_per_page, $current_page) {
// Get the total item count and find out the number of pages
$count = Model::Count($this->_model, $this->_where, $this->_params);
$info = Query::GetPaginationInfo($items_per_page, $current_page, $count);
$this->Limit($items_per_page, $info['QueryOffset']);
return Query::CreatePaginationModel($this->All(), $info);
}
public static function CreatePaginationModel($items, $pagination_info)
{
return new CustomQueryRow(array(
'Items' => $items,
'NumItemsOnPage' => count($items),
'FirstPage' => 1,
'CurrentPage' => $pagination_info['CurrentPage'],
'LastPage' => $pagination_info['TotalPages'],
'NumItems' => $pagination_info['TotalItems'],
'NumPages' => $pagination_info['TotalPages'],
'ItemsPerPage' => $pagination_info['ItemsPerPage']
));
}
public static function GetPaginationInfo($items_per_page, $current_page, $item_count)
{
$total_pages = ceil($item_count / $items_per_page);
// Find the current page
$current = $current_page;
if (strtolower($current) == 'first') $current = 1;
else if (strtolower($current) == 'last') $current = $total_pages;
else if (!is_numeric($current)) $current = 1;
else if ($current < 1) $current = 1;
else if ($current > $total_pages) $current = $total_pages;
// Calculate the required offset/limit values
$offset = ($current - 1) * $items_per_page;
return array(
'ItemsPerPage' => $items_per_page,
'CurrentPage' => $current,
'QueryOffset' => $offset,
'TotalItems' => $item_count,
'TotalPages' => $total_pages
);
}
}
class CustomQuery
{
public static function Query($sql, $params = array())
{
$values = Database::QueryAll($sql, $params);
$rows = array();
foreach ($values as $val) {
$rows[] = new CustomQueryRow($val);
}
return $rows;
}
public static function Paginated($items_per_page, $current_page, $num_items, $sql, $params = array())
{
$info = Query::GetPaginationInfo($items_per_page, $current_page, $num_items);
$o = $info['QueryOffset'];
$l = $info['ItemsPerPage'];
$sql = str_ireplace('{limit}', "LIMIT $o, $l", $sql);
return Query::CreatePaginationModel(CustomQuery::Query($sql, $params), $info);
}
}
class CustomQueryRow
{
private $_values;
function __construct($values)
{
$this->_values = $values;
}
function __get($name)
{
return $this->_values[$name];
}
function __set($name, $value)
{
$this->_values[$name] = $value;
}
function ToArray($fields = array())
{
$vals = array();
foreach ($this->_values as $k => $v) {
if (is_int($k)) continue;
if (count($fields) == 0 || array_search($k, $fields) !== false) {
$vals[$k] = $v;
}
}
return $vals;
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.checkbox.php
<?php
function smarty_function_checkbox($params, $template)
{
$defaults = array(
'checked' => false,
'disabled' => false,
'model' => null
);
$params = array_merge($defaults, $params);
$htmlattr = array();
if ($params['disabled'] === true) {
$htmlattr['disabled'] = 'disabled';
}
$htmlattr['type'] = 'checkbox';
$htmlattr['name'] = $params['for'];
$htmlattr['id'] = 'form_'.$params['for'];
$checked = false;
$model = $params['model'];
if ($model != null && ($model instanceof Model || $model instanceof CustomQueryRow)) {
$checked = $model->{$params['for']};
} else if (isset($params['checked']) && $params['checked'] != null) {
$checked = $params['checked'];
} else if (Post::IsPostBack() && Post::Get($params['for']) != null) {
$checked = Post::Get($params['for']);
}
$checked = ($checked === true || $checked == 'true' || $checked == 'on' || (is_numeric($checked) && $checked > 0));
if ($checked) {
$htmlattr['checked'] = 'checked';
}
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$htmlattr['value'] = 1;
$field = '<input name="'.$htmlattr['name'].'" value="0" type="hidden" />';
$field .= '<input';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= ' />';
return $field;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.radio.php
<?php
function smarty_function_radio($params, $template)
{
$defaults = array(
'checked' => false,
'ignore_post' => false,
'value' => null,
'text' => $params['for'],
'label_space' => ' ',
'model' => null,
'label_html_class' => 'radio'
);
$params = array_merge($defaults, $params);
$htmlattr = array();
$lhtmlattr = array();
$htmlattr['type'] = 'radio';
$htmlattr['name'] = $params['for'];
$htmlattr['id'] = 'form_'.$params['for'].'_'.$params['value'];
$htmlattr['value'] = $params['value'];
$lhtmlattr['for'] = $htmlattr['id'];
$model = $params['model'];
if ($params['ignore_post'] === false && Post::IsPostBack() && Post::Get($params['for']) != null) {
$params['checked'] = $htmlattr['value'] == Post::Get($params['for']);
} else if ($model != null && ($model instanceof Model || $model instanceof CustomQueryRow)) {
$params['checked'] = $htmlattr['value'] == $model->{$params['for']};
}
if ($params['checked']) {
$htmlattr['checked'] = 'checked';
}
foreach ($params as $key => $value) {
if (substr($key, 0, 11) == 'label_html_') {
$lhtmlattr[str_ireplace('_', '-', substr($key, 11))] = $value;
}
else if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
$field = '<label';
foreach ($lhtmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= '><input';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.$value.'"';
}
$field .= ' />' . $params['label_space'] . $params['text'] . '</label>';
return $field;
}
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.textarea.php
<?php
function smarty_function_textarea($params, $template)
{
$defaults = array(
'rows' => 10,
'cols' => 60,
'ignore_post' => false,
'disabled' => false,
'model' => null
);
$params = array_merge($defaults, $params);
$htmlattr = array();
if ($params['disabled'] === true) {
$htmlattr['disabled'] = 'disabled';
}
$htmlattr['rows'] = $params['rows'];
$htmlattr['cols'] = $params['cols'];
$htmlattr['name'] = $params['for'];
$htmlattr['id'] = 'form_'.$params['for'];
$htmlattr['class'] = '';
$model = $params['model'];
$textvalue = '';
if ($params['ignore_post'] === false && Post::IsPostBack() && Post::Get($params['for']) != null) {
$textvalue = Post::Get($params['for']);
} else if ($model != null && ($model instanceof Model || $model instanceof CustomQueryRow)) {
$textvalue = $model->{$params['for']};
} else if (isset($params['value']) && $params['value'] != null) {
$textvalue = $params['value'];
}
$textvalue = htmlspecialchars($textvalue);
foreach ($params as $key => $value) {
if (substr($key, 0, 5) == 'html_') {
$htmlattr[str_ireplace('_', '-', substr($key, 5))] = $value;
}
}
if (Validation::HasErrors($params['for']))
{
$htmlattr['class'] = trim($htmlattr['class'] . ' validation-error-field');
}
$field = '<textarea';
foreach ($htmlattr as $key => $value) {
$field .= ' '.$key.'="'.htmlspecialchars($value).'"';
}
$field .= '>' . $textvalue . '</textarea>';
return $field;
}
<file_sep>/Phoenix/ActionResult.php
<?php
class ActionResult
{
function Execute()
{
}
}
class ContentResult extends ActionResult
{
public $content;
function __construct($content)
{
$this->content = $content;
}
function Execute()
{
echo $this->content;
}
}
class JsonResult extends ActionResult
{
public $obj;
function __construct($obj)
{
$this->obj = $obj;
}
function Execute()
{
header('Content-Type: application/json');
echo json_encode($this->obj);
}
}
class RedirectToActionResult extends ActionResult
{
public $action;
public $controller;
public $params;
function __construct($act, $con, $arg) {
$this->action = $act;
$this->controller = $con;
$this->params = $arg;
}
function Execute()
{
$url = Router::CreateUrl($this->controller, $this->action, $this->params);
header("Location: $url");
exit();
}
}
class RedirectToRouteResult extends ActionResult
{
public $route;
function __construct($rt) {
$this->route = $rt;
}
function Execute()
{
$url = trim(Phoenix::$base_url, '/') . '/' . trim($this->route, '/');
header("Location: $url");
exit();
}
}
class RedirectToUrlResult extends ActionResult
{
public $url;
function __construct($rt) {
$this->url = $rt;
}
function Execute()
{
$url = $this->url;
header("Location: $url");
exit();
}
}
class ViewResult extends ActionResult
{
public $name;
public $view;
public $model;
public $viewdata;
public $cache;
function __construct($name, $view, $model, $viewdata, $cache)
{
$this->name = $name;
$this->view = $view;
$this->model = $model;
$this->viewdata = $viewdata;
$this->cache = $cache;
}
function Execute()
{
Templating::SetPageData('model', $this->model);
Templating::SetPageData($this->viewdata);
$view = Templating::Create();
Templating::$page_data[$this->name] = $this->cache !== false
? Cache::FetchView(Phoenix::$request->route, $view, $this->view)
: $view->fetch($this->view);
Templating::Render();
}
}
class RenderResult extends ActionResult
{
public $view;
public $model;
public $viewdata;
function __construct($view, $model, $viewdata)
{
$this->view = $view;
$this->model = $model;
$this->viewdata = $viewdata;
}
function Execute()
{
Templating::SetPageData('model', $this->model);
Templating::SetPageData($this->viewdata);
$view = Templating::Create();
$view->display($this->view);
}
}
class ViewHierarchyResult extends ActionResult
{
public $hierarchy;
public $viewdata;
function __construct($hierarchy, $viewdata)
{
$this->hierarchy = $hierarchy;
$this->viewdata = $viewdata;
}
/**
* Process a view hierachy and return the resulting content string
* @param array $tree
* @return string The content string
*/
private function ProcessHierachy($tree)
{
$view = Templating::Create();
$tname = Views::Find($tree[':view']);
foreach ($tree as $name => $params) {
if ($name == ':view') {
continue;
} else if (is_array($params) && array_key_exists(':view', $params)) {
$view->assign($name, $this->ProcessHierachy($params));
} else {
$view->assign($name, $params);
}
}
return $view->fetch($tname);
}
function Execute()
{
foreach ($this->hierarchy as $name => $params) {
if (is_array($params) && array_key_exists(':view', $params)) {
Templating::$page_data[$name] = $this->ProcessHierachy($params);
} else {
Templating::$page_data[$name] = $params;
}
}
Templating::Render();
}
}
class MultiViewResult extends ActionResult
{
public $ntvma;
public $viewdata;
function __construct($name_to_view_model_array, $viewdata)
{
$this->ntvma = $name_to_view_model_array;
$this->viewdata = $viewdata;
}
function Execute()
{
Templating::SetPageData($this->viewdata);
foreach ($this->ntvma as $name => $view_model) {
Templating::SetPageData('model', $view_model['model']);
$view = Templating::Create();
Templating::$page_data[$name] = $view->fetch($view_model['view']);
Templating::Render();
}
}
}
?>
<file_sep>/Phoenix/Libs/Smarty.Phoenix/function.recaptcha.php
<?php
function smarty_function_recaptcha($params, $template)
{
$defaults = array(
'public' => Validation::$recaptcha_public,
'error' => Validation::$recaptcha_error,
'ssl' => false
);
$params = array_merge($defaults, $params);
return recaptcha_get_html($params['public'], $params['error'], $params['ssl']);
}
<file_sep>/App/Controllers/Account.php
<?php
class AccountController extends Controller
{
public $login_redirect_action = null;
public $login_redirect_controller = null;
public $login_redirect_params = array();
public $logout_redirect_action = null;
public $logout_redirect_controller = null;
public $logout_redirect_params = array();
public $register_redirect_action = null;
public $register_redirect_controller = null;
public $register_redirect_params = array();
public $verify_redirect_action = null;
public $verify_redirect_controller = null;
public $verify_redirect_params = array();
function Login()
{
if (Post::IsPostBack())
{
if (!Authentication::$autologin)
{
Authentication::Login();
}
else if (Authentication::$post_username != null && Authentication::$post_password != null)
{
Authentication::Login(
Post::Get(Authentication::$post_username),
Post::Get(Authentication::$post_password),
Authentication::$post_remember != null ? Post::Get(Authentication::$post_remember) : null
);
}
}
if (Authentication::IsLoggedIn()) {
return $this->RedirectToAction(
$this->login_redirect_action != null ? $this->login_redirect_action : Router::$default_action,
$this->login_redirect_controller != null ? $this->login_redirect_controller : Router::$default_controller,
$this->login_redirect_params
);
}
return $this->View();
}
function Logout()
{
Authentication::Logout();
return $this->RedirectToAction(
$this->logout_redirect_action != null ? $this->logout_redirect_action : Router::$default_action,
$this->logout_redirect_controller != null ? $this->logout_redirect_controller : Router::$default_controller,
$this->logout_redirect_params
);
}
public function Register()
{
if (Authentication::IsLoggedIn())
{
return $this->RedirectToAction(
$this->login_redirect_action != null ? $this->login_redirect_action : Router::$default_action,
$this->login_redirect_controller != null ? $this->login_redirect_controller : Router::$default_controller,
$this->login_redirect_params
);
}
if (Authentication::ValidateRegister())
{
Authentication::RegisterUser();
return $this->RedirectToAction(
$this->register_redirect_action != null ? $this->register_redirect_action : 'RegisterSuccess',
$this->register_redirect_controller != null ? $this->register_redirect_controller : 'Account',
$this->register_redirect_params
);
}
return $this->View();
}
public function RegisterSuccess()
{
return $this->View();
}
public function Verify($id, $code)
{
$user = new User($id);
if (Authentication::UnlockUserAccount($user, $code))
{
return $this->RedirectToAction(
$this->verify_redirect_action != null ? $this->verify_redirect_action : 'VerifySuccess',
$this->verify_redirect_controller != null ? $this->verify_redirect_controller : 'Account',
$this->verify_redirect_params
);
}
return $this->View();
}
public function VerifySuccess()
{
return $this->View();
}
}
?>
<file_sep>/Phoenix/Database.php
<?php
class DbUtil
{
static function GetConnectionString($type, $host, $database)
{
if ($type == 'mysql') {
return 'mysql:host='.$host.';dbname='.$database;
} else if ($type == 'sqlite') {
return 'sqlite:'.$database;
}
}
static function GetConnection($type, $host, $database, $username, $password)
{
return new PDO(
DbUtil::GetConnectionString($type, $host, $database),
$username,
$password
);
}
}
class Database
{
public static $type;
public static $username;
public static $password;
public static $host;
public static $database;
public static $_enabled = false;
public static $_loggers = array();
/**
* The database connection
* @var PDO
*/
public static $_connection;
public static function Enable()
{
Database::$_enabled = true;
Database::$_connection = DbUtil::GetConnection(
Database::$type,
Database::$host,
Database::$database,
Database::$username,
Database::$password
);
}
public static function AddLogger($logger)
{
Database::$_loggers[] = $logger;
}
private static function Execute($stmt, $params)
{
foreach (Database::$_loggers as $logger) {
$logger->Log($stmt->queryString, $params);
}
return $stmt->execute($params);
}
private static function AssembleSelect($table, $where = array(), $order = null, $limit = null, $fields = '*')
{
$sql = "SELECT $fields FROM $table WHERE 1 = 1";
foreach ($where as $cond) {
$sql .= " AND $cond";
}
if ($order != null) {
$sql .= " ORDER BY $order";
}
if ($limit != null) {
$sql .= " LIMIT $limit";
}
return Database::$_connection->prepare($sql);
}
public static function Count($table, $where = array(), $params = array())
{
$stmt = Database::AssembleSelect($table, $where, null, null, 'count(*) AS Count');
$result = array('Count' => 0);
if (Database::Execute($stmt, $params)) {
$result = $stmt->fetch();
}
$stmt->closeCursor();
return $result['Count'];
}
public static function All($table, $where = array(), $params = array(), $order = null, $limit = null, $fields = '*')
{
$stmt = Database::AssembleSelect($table, $where, $order, $limit, $fields);
$result = array();
if (Database::Execute($stmt, $params)) {
$result = $stmt->fetchAll();
}
$stmt->closeCursor();
return $result;
}
public static function One($table, $where = array(), $params = array(), $order = null, $fields = '*')
{
$stmt = Database::AssembleSelect($table, $where, $order, null, $fields);
$result = array();
if (Database::Execute($stmt, $params)) {
$result = $stmt->fetch();
}
$stmt->closeCursor();
return $result;
}
public static function NonQuery($sql, $params = array())
{
$stmt = Database::$_connection->prepare($sql);
return Database::Execute($stmt, $params);
}
public static function QueryAll($sql, $params = array())
{
$stmt = Database::$_connection->prepare($sql);
$result = array();
if (Database::Execute($stmt, $params)) {
$result = $stmt->fetchAll();
}
$stmt->closeCursor();
return $result;
}
public static function QueryOne($sql, $params = array())
{
$stmt = Database::$_connection->prepare($sql);
$result = array();
if (Database::Execute($stmt, $params)) {
$result = $stmt->fetch();
}
$stmt->closeCursor();
return $result;
}
public static function Insert($table, $values)
{
$params = array();
$counter = 1;
foreach ($values as $field => $value) {
$pname = ':param'.$counter;
$counter++;
$params[$pname] = $value;
}
$cols = array_keys($values);
foreach ($cols as $k => $v)
{
$cols[$k] = "`$v`";
}
$sql = "INSERT INTO $table (";
$sql .= implode(',', $cols);
$sql .= ') VALUES (';
$sql .= implode(',', array_keys($params));
$sql .= ')';
$stmt = Database::$_connection->prepare($sql);
if (Database::Execute($stmt, $params)) {
return Database::$_connection->lastInsertId();
}
return -1;
}
public static function BulkInsert_MySQL($table, $cols, $values)
{
$limit = 25;
$insert = "INSERT INTO $table (" . implode(',', $cols) . ') VALUES ';
$params = array();
$rows = 0;
$counter = 1;
$sqls = array();
foreach ($values as $row) {
$ins = array();
foreach ($row as $d) {
$pname = ':param'.$counter;
$counter++;
$params[$pname] = $d;
$ins[] = $pname;
}
$sqls[] = '(' . implode(',', $ins) . ')';
$rows++;
if ($rows >= $limit) {
Database::NonQuery($insert . implode(',', $sqls), $params);
$sqls = array();
$params = array();
$rows = 0;
$counter = 1;
}
}
if ($rows > 0) {
Database::NonQuery($insert . implode(',', $sqls), $params);
}
}
public static function Update($table, $where = array(), $params = array(), $values = array())
{
$sql = "UPDATE $table SET";
$counter = 1;
foreach ($values as $field => $value) {
if ($counter > 1) {
$sql .= ",";
}
$pname = ':param'.$counter;
$counter++;
$params[$pname] = $value;
$sql .= " `$field` = $pname";
}
$sql .= ' WHERE 1 = 1';
foreach ($where as $cond) {
$sql .= " AND $cond";
}
$stmt = Database::$_connection->prepare($sql);
if (Database::Execute($stmt, $params)) {
return $stmt->rowCount();
}
return 0;
}
public static function Delete($table, $where = array(), $params = array())
{
$sql = "DELETE FROM $table";
$sql .= ' WHERE 1 = 1';
foreach ($where as $cond) {
$sql .= " AND $cond";
}
$stmt = Database::$_connection->prepare($sql);
if (Database::Execute($stmt, $params)) {
return $stmt->rowCount();
}
return 0;
}
}
class DatabaseLogger
{
function Log($sql, $params)
{
// virtual
}
}
class MemoryLogger extends DatabaseLogger
{
public $queries;
function Log($sql, $params)
{
$this->queries[] = array(
'query' => $sql,
'params' => $params
);
}
}
class DbLogger extends DatabaseLogger
{
public $table;
public $field_sql;
public $field_params;
public $field_time;
public $field_user;
function Log($sql, $params)
{
$pstr = '';
foreach ($params as $k => $v) {
$pstr .= $k.' = '.$v."\n";
}
$pstr = trim($pstr);
$sql = "INSERT INTO {$this->table} ";
$sql .= "({$this->field_sql}, {$this->field_params}, {$this->field_time}, {$this->field_user})";
$sql .= ' VALUES (:sql, :params, :time, :user)';
$stmt = Database::$_connection->prepare($sql);
$params = array(
':sql' => $sql,
':params' => $pstr,
':time' => time(),
':user' => Authentication::GetUserID()
);
$stmt->execute($params);
}
}
class EchoLogger extends DatabaseLogger
{
public $printstacktrace = false;
function Log($sql, $params)
{
echo '<div style="border: 1px solid black; padding: 5px;">'.$sql.'<br>';
foreach ($params as $k => $v) {
echo '-- '.$k.' = '.$v.'<br>';
}
if ($this->printstacktrace) {
ob_start();
debug_print_backtrace();
$trace = ob_get_contents();
ob_end_clean();
echo str_replace("\n", "<br>\n", $trace);
}
echo '</div>';
}
}
?>
<file_sep>/Phoenix/Authentication.php
<?php
Authentication::RegisterPasswordHasher(new AlgorithmHasher());
Authentication::RegisterDataExtractor(new StandardAuthenticationDataExtractor());
class Authentication
{
public static $user = null;
public static $model = 'User';
public static $field_id = 'ID';
public static $field_username = 'Username';
public static $field_password = '<PASSWORD>';
public static $field_email = 'Email';
public static $field_openid = 'OpenID';
public static $field_cookie = 'Cookie';
public static $field_numlogins = 'NumLogins';
public static $field_lastlogin = 'LastLogin';
public static $field_lastaccess = 'LastAccess';
public static $field_lastpage = 'LastPage';
public static $field_ip = 'IP';
public static $field_unlocker = 'Unlock';
public static $cookie_id = 'phoenix_username';
public static $cookie_code = 'phoenix_code';
public static $cookie_timeout = 30000000;
public static $post_username = 'username';
public static $post_password = '<PASSWORD>';
public static $post_password_confirm = '<PASSWORD>';
public static $post_remember = 'remember';
public static $post_logout = 'logout';
public static $post_openid = 'openid';
public static $post_email = 'email';
public static $post_register = 'register';
public static $email_from_name;
public static $email_from_email;
public static $email_subject;
public static $email_content;
public static $email_sendmail_envelope = true;
public static $session_id = 'phoenix_login';
public static $autologin = false;
public static $useopenid = true;
public static $openid_host = null;
public static $emailrequired = true;
public static $emailconfirmation = false;
public static $ban_enabled = false;
public static $ban_model = 'Ban';
public static $ban_field_userid = 'UserID';
public static $ban_field_ip = 'IP';
public static $ban_field_time = 'Time';
public static $ban_field_text = 'Text';
public static $ban_action = 'Index';
public static $ban_controller = 'Banned';
public static $_enabled = false;
public static $_hasher;
public static $_extractor;
private static $_openid;
static function RegisterPasswordHasher($passhash)
{
Authentication::$_hasher = $passhash;
}
static function HashPassword($password)
{
return Authentication::$_hasher->Hash($password);
}
static function RegisterDataExtractor($extractor)
{
Authentication::$_extractor = $extractor;
}
static function ExtractData($username, $hashed_password, $additional_info)
{
return Authentication::$_extractor->GetUser($username, $hashed_password, $additional_info);
}
static function Enable()
{
if (!Database::$_enabled) {
echo 'You cannot use authentication without the database enabled.';
return;
}
if (Authentication::$openid_host === null) {
Authentication::$useopenid = false;
}
if (Authentication::$useopenid)
{
Authentication::$_openid = new LightOpenID(Authentication::$openid_host);
}
Authentication::$_enabled = true;
session_start();
Authentication::LoginCurrentUser();
}
static function IsLoggedIn()
{
return Authentication::$user != null;
}
static function GetUser()
{
return Authentication::$user;
}
static function GetUserID()
{
return Authentication::$user != null ?
Authentication::$user->{Authentication::$field_id} :
null;
}
static function GetUserName()
{
return Authentication::$user != null ?
Authentication::$user->{Authentication::$field_username} :
null;
}
static function Login($username = null, $password = null, $remember = false, $additional_info = array())
{
$user = null;
if (($username == null || $password == null) && Authentication::IsAutologinEnabled()) {
$username = Post::Get(Authentication::$post_username);
$password = Post::Get(Authentication::$post_password);
$remember = Post::Get(Authentication::$post_remember);
}
if ($username != null && $password != null) {
$password = Authentication::$_hasher->Hash($password);
$user = Authentication::ExtractData($username, $password, $additional_info);
if ($user != null) {
$unlock = $user->{Authentication::$field_unlocker};
if (Authentication::$emailrequired && Authentication::$emailconfirmation && $unlock != null && $unlock != '')
{
Validation::AddError(Authentication::$post_username, 'Please check your email to activate your account!');
return null;
}
$_SESSION[Authentication::$session_id] = $user->{Authentication::$field_id};
if (Authentication::AreCookiesEnabled() && $remember) {
$user->{Authentication::$field_cookie} = Authentication::GenerateCookieCodeForUsername($user->{Authentication::$field_username});
setcookie(Authentication::$cookie_id, $user->{Authentication::$field_id}, time() + Authentication::$cookie_timeout, Phoenix::$base_url);
setcookie(Authentication::$cookie_code, $user->{Authentication::$field_cookie}, time() + Authentication::$cookie_timeout, Phoenix::$base_url);
}
$_SESSION[Authentication::$session_id.'_LastLogin'] = $user->{Authentication::$field_lastaccess};
$user->{Authentication::$field_numlogins}++;
$user->{Authentication::$field_lastlogin} = date("Y-m-d H:i:s");
$user->{Authentication::$field_ip} = $_SERVER['REMOTE_ADDR'];
$user->{Authentication::$field_lastaccess} = date("Y-m-d H:i:s");
$user->{Authentication::$field_lastpage} = array_key_exists('phoenix_route', $_GET) ? $_GET['phoenix_route'] : '';
$user->Save();
}
else
{
Validation::AddError(Authentication::$post_username, 'Username/Password combination not found!');
}
}
return $user;
}
static function LoginOpenID()
{
$user = null;
$remember = $_SESSION['Phoenix_Temp_Authentication_RememberMe'];
unset($_SESSION['Phoenix_Temp_Authentication_RememberMe']);
$openid = Authentication::$_openid;
if ($openid->mode && $openid->mode != 'cancel' && $openid->validate())
{
$id = $openid->identity;
$obj = new Authentication::$model;
$user_arr = Model::Search(
Authentication::$model,
array(
$obj->GetDbName(Authentication::$field_openid).' = :openid'
),
array(
':openid' => $id
)
);
if (is_array($user_arr) && count($user_arr) == 1) {
$user = $user_arr[0];
$unlock = $user->{Authentication::$field_unlocker};
if (Authentication::$emailrequired && Authentication::$emailconfirmation && $unlock != null && $unlock != '')
{
return null;
}
$_SESSION[Authentication::$session_id] = $user->{Authentication::$field_id};
if (Authentication::AreCookiesEnabled() && $remember) {
$user->{Authentication::$field_cookie} = Authentication::GenerateCookieCodeForUsername($user->{Authentication::$field_username});
setcookie(Authentication::$cookie_id, $user->{Authentication::$field_id}, time() + Authentication::$cookie_timeout, Phoenix::$base_url);
setcookie(Authentication::$cookie_code, $user->{Authentication::$field_cookie}, time() + Authentication::$cookie_timeout, Phoenix::$base_url);
}
$_SESSION[Authentication::$session_id.'_LastLogin'] = $user->{Authentication::$field_lastaccess};
$user->{Authentication::$field_numlogins}++;
$user->{Authentication::$field_lastlogin} = date("Y-m-d H:i:s");
$user->{Authentication::$field_ip} = $_SERVER['REMOTE_ADDR'];
$user->{Authentication::$field_lastaccess} = date("Y-m-d H:i:s");
$user->{Authentication::$field_lastpage} = array_key_exists('phoenix_route', $_GET) ? $_GET['phoenix_route'] : '';
$user->Save();
}
}
return $user;
}
static function BeginLoginOpenID($url = null, $remember = false)
{
if ($url == null && Authentication::IsAutologinEnabled()) {
$url = Post::Get(Authentication::$post_openid);
$remember = Post::Get(Authentication::$post_remember);
}
if ($url != null) {
$_SESSION['Phoenix_Temp_Authentication_RememberMe'] = $remember;
$openid = Authentication::$_openid;
$openid->identity = $url;
header('Location: ' . $openid->authUrl());
exit();
}
}
static function Logout()
{
$_SESSION = array();
session_destroy();
$cookieid = Authentication::$cookie_id;
$cookiecode = Authentication::$cookie_code;
setcookie($cookieid, '', time() - 1, Phoenix::$base_url);
setcookie($cookiecode, '', time() - 1, Phoenix::$base_url);
Authentication::$user = null;
}
static function AreCookiesEnabled()
{
return Authentication::$cookie_id != null
&& Authentication::$cookie_code != null
&& Authentication::$field_cookie != null
&& Authentication::$cookie_timeout > 0;
}
static function IsAutologinEnabled()
{
return Authentication::$post_username != null
&& Authentication::$post_password != null
&& Authentication::$autologin == true;
}
static function GetLastLoginTime() {
if (!Authentication::IsLoggedIn() || !isset($_SESSION[Authentication::$session_id.'_LastLogin'])) return null;
return $_SESSION[Authentication::$session_id.'_LastLogin'];
}
static function LoginCurrentUser()
{
$user = null;
$model = Authentication::$model;
$session = Authentication::$session_id;
$idfield = Authentication::$field_id;
$namefield = Authentication::$field_username;
$passfield = Authentication::$field_password;
$cookiesenabled = Authentication::AreCookiesEnabled();
$autologinenabled = Authentication::IsAutologinEnabled();
$cookieid = Authentication::$cookie_id;
$cookiecode = Authentication::$cookie_code;
$cookiefield = Authentication::$field_cookie;
$loginname = Authentication::$post_username;
$loginpass = Authentication::$post_password;
$loginrem = Authentication::$post_remember;
$logout = Authentication::$post_logout;
$useopen = Authentication::$useopenid;
$openidfield = Authentication::$post_openid;
$openid = Authentication::$_openid;
$register = Authentication::$post_register;
$updateinfo = false;
if (isset($_SESSION[$session]))
{
// Try to find the user from the session data first
$user = new $model($_SESSION[$session]);
if ($user->$idfield != $_SESSION[$session]) {
$user = null;
} else {
$updateinfo = true;
}
}
else if ($cookiesenabled && isset($_COOKIE[$cookieid]) && isset($_COOKIE[$cookiecode]))
{
// Next try the cookie data
$user = new $model($_COOKIE[$cookieid]);
if ($user->$cookiefield != $_COOKIE[$cookiecode]) {
$user = null;
setcookie($cookieid, '', time() - 1, Phoenix::$base_url);
setcookie($cookiecode, '', time() - 1, Phoenix::$base_url);
} else {
$_SESSION[$session] = $user->$idfield;
$_SESSION[Authentication::$session_id.'_LastLogin'] = $user->{Authentication::$field_lastaccess};
$user->{Authentication::$field_numlogins}++;
$user->{Authentication::$field_lastlogin} = date("Y-m-d H:i:s");
$user->{Authentication::$field_ip} = $_SERVER['REMOTE_ADDR'];
$updateinfo = true;
}
}
else if ($useopen && $openid->mode && $openid->mode != 'cancel' && !isset($_POST[$register]) && !isset($_SESSION['Phoenix_Temp_Authentication_Register']))
{
// OpenID login was successful
$user = Authentication::LoginOpenID();
}
else if ($useopen && !$openid->mode && isset($_POST[$openidfield]) && !isset($_POST[$register]))
{
// Begin OpenID login
Authentication::BeginLoginOpenID();
}
else if ($autologinenabled && isset($_POST[$loginname]) && isset($_POST[$loginpass]) && !isset($_POST[$register]))
{
// Finally try the postback
$user = Authentication::Login();
}
if ($user !== null && $updateinfo) {
$user->{Authentication::$field_lastaccess} = date("Y-m-d H:i:s");
$user->{Authentication::$field_lastpage} = array_key_exists('phoenix_route', $_GET) ? $_GET['phoenix_route'] : '';
$user->Save();
}
if ($autologinenabled && $logout != null && $updateinfo && isset($_POST[$logout])) {
// User is logging out (and is logged in via session or cookie)
Authentication::Logout();
$user = null;
}
Authentication::$user = $user;
return ($user !== null);
}
static function ValidateRegister()
{
$namepost = Authentication::$post_username;
$emailpost = Authentication::$post_email;
$passpost = Authentication::$post_password;
$passpost2 = Authentication::$post_password_confirm;
$emailrequired = Authentication::$emailrequired;
if (Authentication::$useopenid
&& isset($_SESSION['Phoenix_Temp_Authentication_Register'])
&& $_SESSION['Phoenix_Temp_Authentication_Register'] == 'openid'
&& isset($_SESSION['Phoenix_Temp_Authentication_Username'])
&& (isset($_SESSION['Phoenix_Temp_Authentication_Email']) || !$emailrequired))
{
$_POST[$namepost] = $_SESSION['Phoenix_Temp_Authentication_Username'];
$_POST[$emailpost] = $_SESSION['Phoenix_Temp_Authentication_Email'];
$_POST[Authentication::$post_register] = 'openid';
$openid = Authentication::$_openid;
$bad_id = true;
if ($openid->mode && $openid->mode != 'cancel' && $openid->validate())
{
$id = $openid->identity;
$bad_id = Query::Create(Authentication::$model)->Where(Authentication::$field_openid, '=', $id)->Count() > 0;
if ($bad_id) Validation::AddError(Authentication::$field_openid, 'An account has already been created for this OpenID.');
}
if ($bad_id)
{
unset($_SESSION['Phoenix_Temp_Authentication_Register']);
unset($_SESSION['Phoenix_Temp_Authentication_Username']);
unset($_SESSION['Phoenix_Temp_Authentication_Email']);
$_SERVER['REQUEST_METHOD'] = 'POST';
return false;
}
return true;
}
if (!Post::IsPostBack()) return false;
$register = $_POST[Authentication::$post_register];
if ($register != 'openid' && $register != 'account') return false;
$username = $_POST[$namepost];
$email = $_POST[$emailpost];
if ($username === null || $username == '')
{
Validation::AddError($namepost, 'Please enter a username.');
$bad_user = true;
}
else
{
$bad_user = Query::Create(Authentication::$model)->Where(Authentication::$field_username, '=', $username)->Count() > 0;
if ($bad_user) Validation::AddError($namepost, 'This username is already in-use, please choose another.');
}
$bad_email = false;
if (Authentication::$emailrequired)
{
if ($email === null || $email == '' || preg_match('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}/i', $email) == 0)
{
Validation::AddError($emailpost, 'Please enter a valid email.');
$bad_email = true;
}
else
{
$bad_email = Query::Create(Authentication::$model)->Where(Authentication::$field_email, '=', $email)->Count() > 0;
if ($bad_email) Validation::AddError($emailpost, 'An account has already been created for this email address.');
}
}
if (Authentication::$useopenid && $register == 'openid' && !$bad_email && !$bad_user) {
$oid = $_POST[Authentication::$post_openid];
if ($oid === null || $oid == '')
{
Validation::AddError(Authentication::$post_openid, 'Please enter your OpenID URL.');
return false;
}
$_SESSION['Phoenix_Temp_Authentication_Register'] = $register;
$_SESSION['Phoenix_Temp_Authentication_Username'] = $username;
$_SESSION['Phoenix_Temp_Authentication_Email'] = $email;
$openid = Authentication::$_openid;
$openid->identity = $oid;
header('Location: ' . $openid->authUrl());
exit();
} else if ($register == 'account') {
$pass = $_POST[$passpost];
$pass2 = $_POST[$passpost2];
if ($pass === null || strlen($pass) < 6)
{
Validation::AddError($passpost, 'Your password must be at least 6 characters long.');
return false;
}
if ($pass != $pass2)
{
Validation::AddError($passpost2, 'The two password fields must be identical.');
return false;
}
}
return (!$bad_email && !$bad_user);
}
static function RegisterUser()
{
$register = $_POST[Authentication::$post_register];
if (Authentication::$useopenid && $register == 'openid') {
$user = Authentication::RegisterOpenIDUser(
$_SESSION['Phoenix_Temp_Authentication_Username'],
Authentication::$_openid->identity,
$_SESSION['Phoenix_Temp_Authentication_Email']
);
unset($_SESSION['Phoenix_Temp_Authentication_Register']);
unset($_SESSION['Phoenix_Temp_Authentication_Username']);
unset($_SESSION['Phoenix_Temp_Authentication_Email']);
return $user;
} else if ($register == 'account') {
return Authentication::RegisterRegularUser(
$_POST[Authentication::$post_username],
$_POST[Authentication::$post_password],
$_POST[Authentication::$post_email]
);
}
return false;
}
static function RegisterRegularUser($username, $password, $email)
{
$user = new Authentication::$model;
$user->{Authentication::$field_username} = $username;
$user->{Authentication::$field_email} = $email;
$user->{Authentication::$field_password} = <PASSWORD>($<PASSWORD>);
Authentication::PopulateUserFields($user);
return $user;
}
static function RegisterOpenIDUser($username, $openid, $email)
{
$user = new Authentication::$model;
$user->{Authentication::$field_username} = $username;
$user->{Authentication::$field_email} = $email;
$user->{Authentication::$field_openid} = $openid;
Authentication::PopulateUserFields($user);
return $user;
}
static function UnlockUserAccount($user, $usercode)
{
if ($user->ID === null) return false;
if ($usercode === null || $usercode == '') return false;
if ($user->{Authentication::$field_unlocker} == $usercode)
{
$user->{Authentication::$field_unlocker} = '';
$user->Save();
return true;
}
return false;
}
static function PopulateUserFields($user)
{
$user->{Authentication::$field_cookie} = Authentication::GenerateCookieCodeForUsername($user->{Authentication::$field_username});
$user->{Authentication::$field_numlogins} = 1;
$user->{Authentication::$field_lastlogin} = date("Y-m-d H:i:s");
$user->{Authentication::$field_ip} = $_SERVER['REMOTE_ADDR'];
$user->{Authentication::$field_lastaccess} = date("Y-m-d H:i:s");
$user->{Authentication::$field_lastpage} = array_key_exists('phoenix_route', $_GET) ? $_GET['phoenix_route'] : '';
$user->Save();
if (Authentication::$emailconfirmation && Authentication::$emailrequired)
{
$prefix = $user->{Authentication::$field_id} . '_';
$gen = Authentication::GenerateCookieCodeForUsername($user->{Authentication::$field_email});
$user->{Authentication::$field_unlocker} = substr($prefix . $gen, 0, strlen($gen));
$user->Save();
$search = array('{id}', '{username}', '{unlock_code}', '{email}');
$replace = array(
$user->{Authentication::$field_id},
$user->{Authentication::$field_username},
$user->{Authentication::$field_unlocker},
$user->{Authentication::$field_email},
);
$to = $user->{Authentication::$field_email};
$subject = str_replace($search, $replace, Authentication::$email_subject);
$message = str_replace($search, $replace, Authentication::$email_content);
$headers = 'From: ' . str_replace($search, $replace, Authentication::$email_from_name) .
' <'. Authentication::$email_from_email . ">\r\n" .
'Reply-To: ' . Authentication::$email_from_email . "\r\n" .
'X-Mailer: PHP/' . phpversion() . "\r\n";
$params = Authentication::$email_sendmail_envelope ? ('-f' . Authentication::$email_from_email) : null;
mail($to, $subject, $message, $headers, $params);
}
}
static function ChangeUserPassword($user, $oldpass, $newpass, $newpass_confirm)
{
$oldhash = Authentication::HashPassword($oldpass);
$currentpass = $user->{Authentication::$field_password};
if ($oldhash == $currentpass && $newpass !== null
&& strlen($newpass) >= 6 && $newpass == $newpass_confirm)
{
$user->{Authentication::$field_password} = Authentication::HashPassword($newpass);
$user->Save();
return true;
}
return false;
}
static function GenerateCookieCodeForUsername($username)
{
$cookie = $username;
for ($i = 0; $i < 5; $i++) // The cookie is hashed using only the username, so be really paranoid about creating it
{
$cookie = Authentication::HashPassword($cookie . '~Phoenix_Cookie$'.$i.'_=_=_=_'.mt_rand(0, 500000));
}
return $cookie;
}
static function IsCurrentUserBanned() {
$ipadd = $_SERVER['REMOTE_ADDR'];
if (Authentication::IsIpBanned($ipadd)) return true;
if (Authentication::IsLoggedIn() && Authentication::IsUserBanned(Authentication::GetUserID())) return true;
return false;
}
static function BanUser($id, $untiltime, $text = '', $ban_by_ip = true) {
$ban = new Authentication::$ban_model;
$ban->{Authentication::$ban_field_userid} = $id;
$ban->{Authentication::$ban_field_ip} = '';
if ($ban_by_ip) {
$user = Query::Create(Authentication::$model)
->Where(Authentication::$field_id, '=', $id)
->One();
if ($user->{Authentication::$field_id} !== null) {
$ban->{Authentication::$ban_field_ip} = $user->{Authentication::$field_ip};
}
}
$ban->{Authentication::$ban_field_text} = $text;
$ban->{Authentication::$ban_field_time} = $untiltime;
$ban->Save();
}
static function BanIp($ip, $untiltime, $text = '') {
$ban = new Authentication::$ban_model;
$ban->{Authentication::$ban_field_userid} = 0;
$ban->{Authentication::$ban_field_ip} = $ip;
$ban->{Authentication::$ban_field_text} = $text;
$ban->{Authentication::$ban_field_time} = $untiltime;
$ban->Save();
}
static function UnbanUser($id) {
foreach (Authentication::GetActiveBansForUser($id) as $ban) {
$ban->Delete();
}
}
static function UnbanIp($ip) {
foreach (Authentication::GetActiveBansForIp($ip) as $ban) {
$ban->Delete();
}
}
static function IsUserBanned($id) {
if (!Authentication::$ban_enabled || Authentication::$ban_field_userid === null) return false;
return Query::Create(Authentication::$ban_model)
->Where(Authentication::$ban_field_userid, '=', $id)
->Where(Authentication::$ban_field_time, '>', date("Y-m-d H:i:s"))
->Count() > 0;
}
static function IsIpBanned($ip) {
if (!Authentication::$ban_enabled || Authentication::$ban_field_ip === null) return false;
return Query::Create(Authentication::$ban_model)
->Where(Authentication::$ban_field_ip, '=', $ip)
->Where(Authentication::$ban_field_time, '>', date("Y-m-d H:i:s"))
->All();
}
static function GetActiveBansForUser($id) {
if (!Authentication::$ban_enabled || Authentication::$ban_field_userid === null) return array();
return Query::Create(Authentication::$ban_model)
->Where(Authentication::$ban_field_userid, '=', $id)
->Where(Authentication::$ban_field_time, '>', date("Y-m-d H:i:s"))
->All();
}
static function GetActiveBansForIp($ip) {
if (!Authentication::$ban_enabled || Authentication::$ban_field_ip === null) return array();
return Query::Create(Authentication::$ban_model)
->Where(Authentication::$ban_field_ip, '=', $ip)
->Where(Authentication::$ban_field_time, '>', date("Y-m-d H:i:s"))
->Count() > 0;
}
}
class Session
{
public static function Get($name, $reset = false)
{
if (!array_key_exists($name, $_SESSION)) {
return null;
}
$var = $_SESSION[$name];
if ($reset === null) {
unset($_SESSION[$name]);
} else if ($reset !== false) {
$_SESSION[$name] = $reset;
}
return $var;
}
public static function Set($name, $value)
{
$_SESSION[$name] = $value;
}
public function __get($name)
{
return Session::Get($name);
}
public function __set($name, $value)
{
Session::Set($name, $value);
}
}
class PasswordHasher
{
public function Hash($password)
{
// Virtual
}
}
/**
* Plain text hasher that is UNSAFE and UNSECURE.
*/
class PlainTextHasher extends PasswordHasher
{
public function Hash($password)
{
return $password;
}
}
/**
* Salted algorithm hash. Should be suitable for most uses.
*/
class AlgorithmHasher extends PasswordHasher
{
private $algorithm = 'sha256';
private $salt_before = '';
private $salt_after = '';
/**
* @param string $algorithm The name of the algorithm to use. Must be contained in the results of the hash_algos() function. Examples: sha256 (default), md5, crc32
* @param string $salt_before Salt to be prepended to the password before hashing.
* @param string $salt_after Salt to be appended to the password before hashing.
*/
public function __construct($algorithm = 'sha256', $salt_before = '', $salt_after = '')
{
$this->algorithm = $algorithm;
$this->salt_before = $salt_before;
$this->salt_after = $salt_after;
}
public function Hash($password)
{
return hash($this->algorithm, $this->salt_before . $password . $this->salt_after);
}
}
class AuthenticationDataExtractor
{
function GetUser($username, $hashed_password, $additional_info)
{
// Virtual
}
}
class StandardAuthenticationDataExtractor extends AuthenticationDataExtractor
{
function GetUser($username, $hashed_password, $additional_info)
{
$obj = new Authentication::$model;
$user_arr = Model::Search(
Authentication::$model,
array(
$obj->GetDbName(Authentication::$field_username).' = :user',
$obj->GetDbName(Authentication::$field_password).' = :pass'
),
array(
':user' => $username,
':pass' => $<PASSWORD>
)
);
return (is_array($user_arr) && count($user_arr) == 1) ? $user_arr[0] : null;
}
}
?>
<file_sep>/Phoenix/RouteParameters.php
<?php
/**
* The result of a fully resolved route.
*/
class RouteParameters {
/**
* The route that has been resolved
* @var string
*/
public $route;
/**
* The controller
* @var Controller
*/
public $controller;
/**
* The name of the controller
* @var string
*/
public $controller_name;
/**
* The action as a function name in the controller
* @var string
*/
public $action;
/**
* The action as passed into the route
* @var string
*/
public $action_name;
/**
* The parameters
* @var array
*/
public $params = array();
function Execute()
{
$action = $this->action;
if (Post::IsPostBack()) {
if (method_exists($this->controller, $action.'_Post')) {
$action = $action.'_Post';
}
}
$this->controller->BeforeExecute();
$result = call_user_func_array(array($this->controller, $action), $this->params);
$this->controller->AfterExecute();
return $result;
}
function GetRouteString()
{
return trim($this->action_name . '/' . $this->controller_name . '/' . implode('/', $this->params), '/');
}
}
?>
| 2418fe8628d9acd41a2706a052aa521e7d6e1673 | [
"Markdown",
"PHP"
] | 44 | PHP | LogicAndTrick/phoenix | 09803588987992ccf1d472e70bac8e762bb48b71 | 4092e146c32cede21ed0d32773e51c3339ee41d3 |
refs/heads/master | <file_sep>const validUrl = require('valid-url');
const express = require('express');
const config = require('config');
const Item = require('../models/items');
const objectSanitizer = require('../utils/santizer');
const router = express.Router();
// @route GET /api/items
// @access Public for now
// @desc returns all of the times in the db
router.get('/', async (req, res) => {
try {
res.json({ successful: true, items: await Item.find({}) });
} catch (err) {
res.json({ successful: false, err });
}
});
// @route POST /api/items
// @access Public for now
// @desc Adds item to db
router.post('/', async (req, res) => {
try {
let item = objectSanitizer(req);
if (!item) {
return res.json(item);
}
const { name, price } = item;
let { imageUrl } = item;
if (!imageUrl || !validUrl.isUri(imageUrl)) {
imageUrl = config.get('defaultItemImage');
}
item = {
name,
price,
imageUrl,
};
return res.json({ successful: true, addedItem: await Item.create(item) });
} catch (err) {
return res.json({ successful: false, err: err.message });
}
});
module.exports = router;
<file_sep>import React from 'react';
import './App.css';
// components
import Header from './components/header/header.component';
import ItemsPage from './components/pages/items-page/items-page.component';
function App() {
return (
<div className='App'>
<Header />
<div id='margin-container'>
<ItemsPage />
</div>
</div>
);
}
export default App;
<file_sep>import React from 'react';
import ItemList from '../../item-list/item-list.component';
const ItemsPage = () => {
return (
<section className='page'>
<ItemList />
</section>
);
};
export default ItemsPage;
<file_sep>import React from 'react';
import ItemCard from '../item-card/item-card-component';
import FilterSearchBox from '../filter-search-box/filter.search.box.component';
class ItemList extends React.Component {
constructor() {
super();
this.state = {
searchField: '',
items: [],
};
}
componentDidMount = () => {
fetch('/api/items')
.then((res) => res.json())
.then((jsonRes) => {
if (jsonRes.successful) {
this.setState({ items: jsonRes.items });
}
});
};
handleInputChange = (e) => {
const searchField = e.target.value;
this.setState({ searchField });
};
filterItems = (item) => {
let namematch = item.name
.toLowerCase()
.includes(this.state.searchField.toLowerCase());
if (namematch) return true;
};
render() {
const filteredItems = this.state.items.filter(this.filterItems);
return (
<div>
<FilterSearchBox
placeholder='Item Search'
handleChange={this.handleInputChange}
/>
{filteredItems.map((item) => (
<ItemCard key={item._id} item={item} />
))}
</div>
);
}
}
export default ItemList;
<file_sep>const expressSanitizer = require('express-sanitizer');
const bodyParser = require('body-parser');
const express = require('express');
const helmet = require('helmet');
const config = require('config');
const connectDB = require('./config/db');
connectDB();
const app = express();
// middleware
app.use(bodyParser.json());
app.use(helmet());
app.use(expressSanitizer());
// routes
app.use('/api/items', require('./routes/items'));
app.listen(config.get('port'), () => {
console.log(`server online on port ${config.get('port')}`);
});
<file_sep>const objectSanitizer = _req => {
try {
Object.keys(_req.body).forEach(key => {
// eslint-disable-next-line no-param-reassign
_req.body[key] = _req.sanitize(_req.body[key]).trim();
});
return _req.body;
} catch (err) {
return { successful: false, err };
}
};
module.exports = objectSanitizer;
| c4c2e41900cbaa733435dd122163addfc2b861c0 | [
"JavaScript"
] | 6 | JavaScript | Lucidreline/chest | a60393d93fdabde153ef737dcff561bc82ac42ac | d28aa95f163c48ce52294c6a6933747fa3806f7c |
refs/heads/master | <repo_name>zhdankras/learn-<file_sep>/python/task119.py
# Написать функцию balanced_num, которая определяет является ли заданное число сбалансированным, т.е.
# сумма цифр справа и слева от середины равны (abcde ==> a + b == d + e; abcdef ==> a + b == e + f)
#
# Примеры:
# balanced_num(2222) ==> True
# balanced_num(135622) ==> True
import traceback
def balanced_num(number):
s = str(number)
sum1 = 0
sum2 = 0
for i in range(len(s) / 2)):
sum1 += s[i]
sum2 += s[len(s)- i - 1]
if sum1 == sum2:
return True
return False
# Тесты
try:
assert balanced_num(13) == True
assert balanced_num(0) == True
assert balanced_num(295591) == False
assert balanced_num(56239814) == True
assert balanced_num(1230987) == False
except AssertionError:
print("TEST ERROR")
traceback.print_exc()
else:
print("TEST PASSED")
<file_sep>/python/task400.py
# -*- coding: utf-8 -*-
"""
Создать txt-файл, вставить туда любую англоязычную статью из Википедии.
Реализовать одну функцию, которая выполняет следующие операции:
- прочитать файл построчно;
- непустые строки добавить в список;
- удалить из каждой строки все цифры, знаки препинания, скобки, кавычки и т.д. (остаются латинские буквы и пробелы);
- объединить все строки из списка в одну, используя метод join и пробел, как разделитель;
- создать словарь вида {“слово”: количество, “слово”: количество, … } для подсчета количества разных слов,
где ключом будет уникальное слово, а значением - количество;
- вывести в порядке убывания 10 наиболее популярных слов, используя метод format
(вывод примерно следующего вида: “ 1 place --- sun --- 15 times n....”);
- заменить все эти слова в строке на слово “PYTHON”;
- создать новый txt-файл;
- записать строку в файл, разбивая на строки, при этом на каждой строке записывать не более 100 символов
и не делить слова.
"""
def wiki_function():
Mylist = []
words = {}
_replace = []
whitelist = set('abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ')
input_file = open('wiki.txt', 'r')
output_file = open('wiki_py.txt', 'w')
lines = input_file.readlines()
for line in lines:
if line != '\n':
Mylist.append(''.join(filter(whitelist.__contains__, line)))
cstring = ''.join(Mylist)
for word in cstring.split():
if word in words:
words[word] += 1
else:
words[word] = 1
limit = 10
count = 0
place = 0
for key, value in sorted(words.items(), key=lambda item: item[1], reverse=True):
if count == limit:
break
else:
place +=1
print "{} place --- {} --- {} times".format(place, key, value)
сstring = сstring.replace(" "+ key +" "," PYTHON ")
count += 1
import textwrap
wrapper = textwrap.TextWrapper(width=50)
word_list = wrapper.wrap(text=string)
for element in word_list:
output_file.write(element + "\n")
# Вызов функции
wiki_function()<file_sep>/python/sas.cpp
#include <iostream>
using namespace std;
class myclass {
int a; // Закрытые данные
public:
int b;
void setab(int i);
int geta();
void reset();
};
void myclass::setab(int i)
{
a = i;
b = i * i;
cout << "карпов лучший" << endl;
}
int myclass::geta()
{
return a;
}
void myclass::reset()
{
setab(0);
}
int main()
{
myclass object;
object.setab(5);
cout <<"Выводи ";
cout << object.geta() <<' ';
cout << endl;
object.b = 20;
cout <<"Выводи объект 20: ";
cout << object.geta() << ' ';
cout << object.b;
cout << endl;
object.reset();
cout <<"Объект object (reset): ";
cout << object.geta() <<' ';
cout << object.b;
cout << endl;
return 0;
}
<file_sep>/python/task185.py
# Написать функцию two_digit, которая определяет является ли сумма цифр заданного числа двухзначным числом
#
# Примеры:
# two_digit(2222) ==> False
# two_digit(222222) ==> True
import traceback
def two_digit(number):
# Тело функции
return True
# Тесты no ya pidor
try:
assert two_digit(111223) == True
assert two_digit(0) == False
assert two_digit(111000) == False
assert two_digit(123456) == True
assert two_digit(99) == True
except AssertionError:
print("TEST ERROR")
traceback.print_exc()
else:
print("TEST PASSED")
<file_sep>/python/task237.py
# Задан список целых чисел. Написать функцию max_three_sum,
# которая возвращает максимальную сумму трех элементов без их повторов
#
# Пример:
# [1,8,3,4,0,8,4] ==> 15
import traceback
def max_three_sum(arr):
# Тело функции
return 0
# Тесты
try:
assert max_three_sum([2,1,8,0,6,4,8,6,2,4]) == 18
assert max_three_sum([-13,-50,57,13,67,-13,57,108,67]) == 232
assert max_three_sum([-2,-4,0,-9,2]) == 0
except AssertionError:
print("TEST ERROR")
traceback.print_exc()
else:
print("TEST PASSED") | 372735c44e4656175f494426b162130bbed31e32 | [
"Python",
"C++"
] | 5 | Python | zhdankras/learn- | c235635450ac4d321c70b81193b44d063cfec70b | 01381e89697b59cf4771ee1ad6cfdd2878bc191b |
refs/heads/master | <repo_name>ganeshharugeri/R_workspace<file_sep>/KrediTechPractice.R
set.seed(212)
#get/check working directory
getwd()
#set working directory
setwd("/Users/ganeshharugeri/Documents/R_workspace/input/kreditechDSTest2017/")
#Import Data Set
#Read file from working directory
filename1 <- paste(c(getwd(),"/Validation.csv"),collapse="")
filename2 <- paste(c(getwd(),"/Training.csv"),collapse="")
# read file now
Validation <- read.csv2(filename1,sep = ";",header = 1, stringsAsFactors = 1 )
Training <- read.csv2(filename2,sep = ";",header = 1, stringsAsFactors = 1 )
#Structure of both dataset
str(Training)
str(Validation) #classlabel is absent
#Check suumary
summary(Validation)
summary(Training)
#Check sample data
head(Validation)
head(Training)
#Check STructure
str(Validation)
str(Training)
dim(Validation)
dim(Training)
# Binding training and test data
Backup <- rbind(Training, Validation)
All_Data <- rbind(Training, Validation)
str(All_Data)
#Check for the unique values in each column
sapply(All_Data, function(x) length(unique(x)))
# issing value entries
nrowCount =nrow(All_Data)
ncol(All_Data)
#Complete rows i.e, rows without missing values
completeRows = sum(complete.cases(All_Data))
#Check for the percentage of missing row entries
prop=sum(complete.cases(All_Data))/nrow(All_Data)
#Number of missing values
table(is.na(All_Data))
#Check for missing by column
colSums(is.na(All_Data))
colSums(is.na(Training))
colSums(is.na(Validation))
#Analyse the variable dependancy
library(ggplot2)
head(All_Data)
#Arranging the data by column names
temp=NULL
temp=All_Data[ , order(names(All_Data[1:21]))]
temp$v7 =NULL
temp$v9 =NULL
str(temp)
head(temp)
#Ordering as required
temp <- cbind(v7=All_Data$v7,v9=All_Data$v9,temp,classlabel = All_Data$classlabel)
dim(temp)
#Assigning back to All_Data
All_Data =NULL
All_Data <- temp
temp <- NULL
head(All_Data)
str(All_Data)
#Plotting Univariate analysis
df = data.frame(All_Data$v7)
#quick plots
qplot(All_Data$v7,All_Data$classlabel)
qplot(All_Data$v9,All_Data$classlabel)
qplot(All_Data$v42,All_Data$classlabel)
#Advanced plots
ggplot(All_Data) + geom_bar( aes(All_Data$classlabel) )
#REMOVING v95 as it has more than 55% data is NA
All_Data$v95= NULL
#Library dplyr and tidyr is required for pipe(%>%) and fill functions
library(dplyr)
library(tidyr)
All_Data <- All_Data %>% fill(v7,v12,v32,v33,v99,v85)
All_Data$v9 <- factor(All_Data$v9)
table(All_Data$v24)
qplot(All_Data$v24)
# Standarisation function
range01 <- function(x){(x-min(x))/(max(x)-min(x))}
#test column
TestCol= All_Data$v20
# USe function
All_Data$v20=range01(All_Data$v20)
All_Data$v24=range01(All_Data$v24)
#All_Data$v42 = Backup$v42
All_Data$v42[is.na(All_Data$v42)] <- median(All_Data$v42,na.rm=T)
All_Data$v55[is.na(All_Data$v55)] <- median(All_Data$v55,na.rm=T)
All_Data$v42=range01(All_Data$v42)
All_Data$v55=range01(All_Data$v55)
summary(All_Data)
sapply(All_Data, function(x) length(unique(x)))
#Rename label values
library(plyr)
All_Data$classlabel<- mapvalues(All_Data$classlabel, from = c("yes.", "no."), to = c("yes", "no"))
#See the output
# col = NULL
# chk=NULL
# df=NULL
#Building models
library(randomForest)
#Splitting data
train = All_Data[1:3700,]
test=NULL
test = All_Data[3701:3900,1:20]
#randomforest
rfmodel <- randomForest(classlabel~ v68+v99+v50+v20+v53,data=train,importance=TRUE, ntrees=69)
predicted<- predict(rfmodel,test)
#Confusion matrix for randomforest
confusionMatrix(predicted,All_Data[3701:3900,]$classlabel)
#Variable Importance
?varImpPlot
varImpPlot(rfmodel)
varImpPlot(rfmodel,sort=T,n.var=10,main = "Variable importance")
#SVM model
svmmodel<-svm(classlabel ~.,data=train)
pred<- predict(svmmodel,test)
#Accuracy test [Evaluation]
library(caret)
library(e1071)
#Confusion matrix for SVM
confusionMatrix(pred,All_Data[3701:3900,]$classlabel)
# cbind(predicted,All_Data[3701:3900,]$classlabel)
compare=NULL
compare <- cbind(Actual=All_Data[3701:3900,]$classlabel, rfPrediction = predicted, SVMPrediction = pred)
#scatterplotmatrix(car package)
scatterplotMatrix(~ v12+v20+v24+v42+v50+v53+v97,data=train)
#Tensorflow check
library(tensorflow)
sess = tf$Session()
hello <- tf$constant('Hello, TensorFlow!')
sess$run(hello)
a <- tf$constant(10)
b <- tf$constant(32)
sess$run(a + b)
<file_sep>/modelPractice.R
# data_train <- iris[ trainIndex,]
# data_test <- iris[-trainIndex,]
# # train a naive bayes model
# model <- NaiveBayes(Species~., data=data_train)
# # make predictions
# x_test <- data_test[,1:4]
# y_test <- data_test[,5]
# predictions <- predict(model, x_test)
# # summarize results
# confusionMatrix(predictions$class, y_test)
trainData=complete_data_formatted1[1:3700,]
testData = complete_data_formatted1[3701:3900,]
x_test=testData[, 1:19]
y_test=testData[,20]
rfmodel <- randomForest(classlabel ~.,data=trainData,importance=TRUE,ntree= 35)
#Check variable importance
?varImpPlot
varImpPlot(rfmodel,sort=T,n.var=10,main = "Variable importance")
#Check for the error rate based on the no of ntrees
plot(rfmodel)
#predTest<- predict(rfmodel,x_test)
confusionMatrix(data=x_test$pt,reference=testData$classlabel,positive='yes.')
table(trainData$classlabel,x_test$pt)
unique(trainData$classlabel)
unique(x_test$pt)
typeof(x_test$pt)
str(trainData$classlabel)
length(x_test$pt)
length(trainData$classlabel)
length(pred)
length(complete_data_vaild$classlabel)
?table
summary(x_test$predTest)
summary(trainData$classlabel)
summary(x_test)
summary(trainData)
str(x_test$pt)
str(trainData)
table(trainData$classlabel)
table(x_test$predTest)
which(is.na(x_test$predTest))
which(is.na(trainData$classlabel))
which(trainData$classlabel=='')
which(x_test$predTest=='')
print(seq(1,2, by=0.01))
v1 <- c(3,8,4,5,0,11)
v2 <- c(4,11,0,8,1,2)
# Vector addition.
add.result <- v1+v2
print(add.result)
df_Example= data.frame(
sno=c(1:3),
year=c(2015:2017),
sem=c("year1","year2","year3"),
impSubs = c("DataScience","Project","Thesis"),
stringsAsFactors = 0
)
## Subset test
subsetTest <- subset(test,Pclass==3)
<file_sep>/KrediTech.R
#get/check working directory
getwd()
#set working directory
setwd("/Users/ganeshharugeri/Documents/R_workspace/input/kreditechDSTest2017/")
#Import Data Set
#Read file from working directory
filename1 <- paste(c(getwd(),"/Validation.csv"),collapse="")
filename2 <- paste(c(getwd(),"/Training.csv"),collapse="")
# read file now
Validation <- read.csv(filename1,sep = ";",header = 1, stringsAsFactors = 0 )
Training <- read.csv(filename2,sep = ";",header = 1, stringsAsFactors = 0 )
#Structure of both dataset
str(Training)
str(Validation) #classlabel is absent
#Check suumary
summary(Validation)
summary(Training)
#Check sample data
head(Validation)
head(Training)
#Check STructure
str(Validation)
str(Training)
## Setting Classlabe column for test data to NA
#Validation$classlabel <- NA
## Combining Training and Testing dataset
complete_data <- rbind(Training, Validation)
## Check data structure
str(complete_data)
#Data filling using tidyr package
str(complete_data)
summary(complete_data)
library(tidyr)
# categorical variable treatment
complete_data_formatted <- complete_data %>% fill(v33,v12,v7,v32,v99,v85)
#Numerical variable, mean treatment v55, v42
complete_data_formatted$v55[is.na(complete_data_formatted$v55)] <- mean(complete_data_formatted$v55,na.rm=T)
complete_data_formatted$v42[is.na(complete_data_formatted$v42)] <- mean(complete_data_formatted$v42,na.rm=T)
#speical attention v95, more NAs
# will replace NA with fill for just the base model.
#Final hint - better to remove if it is not much of importance
complete_data_formatted <- complete_data_formatted %>% fill(v95)
# remaining NAs with an assumption of false(f) values
complete_data_formatted$v95[is.na(complete_data_formatted$v95)] <- 'f'
## Check number of uniques values for each of the column to find out columns
##which we can convert to factors
sapply(complete_data_formatted, function(x) length(unique(x)))
#convert column v9 to factor type (from int)
complete_data_formatted$v9=as.factor(complete_data_formatted$v9)
#check format results
summary(complete_data_formatted)
str(complete_data_formatted)
#____________________________
NA_Percentage_Any_Dataset <- function(Dataset,total_rows){
mylist =list()
for(i in names(Dataset)){
#print(i)
total_NAs = sum(is.na(Dataset[[i]]))
# print(total_NAs)
percentage = (100* total_NAs)/total_rows
#print(percentage)
mylist[[i]]=percentage
# cat('Column',i,'has',percentage,'% of NA Vaues\n')
#cat('--------------------------------------------\n')
}
summary(mylist)
# columnwise percentages of NAs
mylist
#mylist[order(mylist[1]),]
# sort.list(mylist)
}
#____________________________
#Number formating german deciamals to US
asNumericFunc <- function(dataset,col_name){
dataset[[col_name]] <- as.numeric(sub(",", ".", dataset[[col_name]], fixed = TRUE))
return (dataset)
}
complete_data_formatted<-asNumericFunc(complete_data_formatted,"v12")
complete_data_formatted<-asNumericFunc(complete_data_formatted,"v50")
complete_data_formatted<-asNumericFunc(complete_data_formatted,"v20")
complete_data_formatted<-asNumericFunc(complete_data_formatted,"v97")
# Model creation
install.packages("randomForest")
library(randomForest)
complete_data_formatted1<-complete_data_formatted
complete_data_formatted1$v95<-NULL
complete_data_formatted1$v9<-NULL
library(dplyr)
complete_data_formatted1$v42<- (complete_data_formatted1$v42-min(complete_data_formatted1$v42))/(max(complete_data_formatted1$v42)-min(complete_data_formatted1$v42))
complete_data_formatted1$v53<- (complete_data_formatted1$v53-min(complete_data_formatted1$v53))/(max(complete_data_formatted1$v53)-min(complete_data_formatted1$v53))
?randomForest
rfmodel <- randomForest(classlabel ~.,data=complete_data_formatted1[1:3700,], ntrees=250)
pred<- predict(rfmodel,complete_data_formatted1[3701:3900, 1:19])
svmmodel<-svm(classlabel ~.,data=complete_data_formatted1[1:3700,])
pred<- predict(svmmodel,complete_data_formatted1[3701:3900, 1:19])
View(complete_data_formatted1[3701:3900, 1:20])
complete_data_vaild<-complete_data_formatted[3701:3900,1:22]
complete_data_vaild$predicted<-pred
##
library(caret)
library(e1071)
confusionMatrix(pred,complete_data_vaild$classlabel)
#Trial
pred
confusionMatrix(pred,complete_data_formatted1[3701:3900,20])
View(complete_data_vaild[,22:23])
<file_sep>/P3.Rmd
---
title: "P3 Assignment Notebook"
output:
html_document: default
html_notebook: default
pdf_document: default
---
Import all data sets given
```{r}
setwd("/Users/ganeshharugeri/Documents/R_workspace/input/P3")
print(c("Working Directory:",getwd()))
filename1 <- paste(c(getwd(),"/flights.csv"),collapse="")
filename2 <- paste(c(getwd(),"/airlines.csv"),collapse="")
filename3 <- paste(c(getwd(),"/airports.csv"),collapse="")
flights <- read.table(filename1,sep = ",",header = 1)
airlines <- read.table(filename2,sep = ",",header = 1)
airports <- read.table(filename3,sep = ",",header = 1)
```
Data loading: Solving the Data loading issue due to sererator difference (, ; mismatch) and then reloading.
```{r}
#rm(flights)
#rm(airlines)
#rm(airports)
```
Understanding the structure of the given datasets
```{r}
str(flights)
str(airlines)
str(airports)
```
Data preperation: Deleted incomplete columns, having more than 80% of missing values
```{r}
flights <- subset(flights, select = -c(27:31) )
```
Data Exploration: See the data at a glance and ther samples
```{r}
print(c("Flights Sample data", head(flights)))
print(c("Airlines Sample data",head(airlines)))
print(c("Airports Sample data",head(airports)))
```
Data Exploration: Summary analysis of the given data sets
```{r}
print(c("Flights Summary", summary(flights)))
print(c("Airlines Summary",summary(airlines)))
print(c("Airports Summary",summary(airports)))
```
Data Transformation: Enabling data type conversions to increase effciency of the data readability.
```{r}
print (c("YEAR:", levels (factor (flights$YEAR))))
print (c("MONTH:", levels (factor (flights$MONTH))))
print (c("DAY:", levels (factor (flights$DAY))))
print (c("DAY_OF_WEEK:", levels (factor (flights$DAY_OF_WEEK))))
print (c("DIVERTED:", levels (factor (flights$DIVERTED))))
print (c("CANCELLED:", levels (factor (flights$CANCELLED))))
# Data converted as they had only two levels
flights$DIVERTED <- as.factor(flights$DIVERTED)
flights$CANCELLED <- as.factor(flights$CANCELLED)
flights$DAY_OF_WEEK <- as.factor(flights$DAY_OF_WEEK)
flights$MONTH <- as.factor(flights$MONTH)
flights$YEAR <- as.factor(flights$YEAR)
typeof(flights$CANCELLED)
```
Data Representation & flights distribution per month plot
```{r}
table(flights$MONTH)
library(ggplot2)
ggplot(flights, aes(x=MONTH, fill=MONTH))+geom_bar()
#ggplot(flights, aes(x=Day, fill=DayofMonth))+geom_bar()
#Another method
#x<-table(flights$MONTH)
#barplot(x)
```
I tried to remove the rows with incomplete details as the scope of this work is not buid a perfect predicting model.
```{r}
flights<-flights[complete.cases(flights), ]
na.omit(flights)
```
Data Exploration: Market shares by Air carriers
```{r}
flights <- subset(flights, !(is.na(flights$AIR_TIME)))
na_percentages <- sapply(flights, function(x) sum(is.na(x))) / nrow(flights) * 100
sort(format(round(na_percentages, 4), nsmall = 4))
```
Data Exploration: Delay analysis per airline carrier
```{r}
airline.avg.delay <- aggregate(flights$ARRIVAL_DELAY, by=list(flights$AIRLINE), mean, na.rm=T)
names(airline.avg.delay) <- c("AirlineCode", "Mean.Arrival.Delay")
airline.avg.delay <- merge(airline.avg.delay, airlines, by.x="AirlineCode", by.y="IATA_CODE", all.x=TRUE)
airline.avg.delay <- airline.avg.delay[order(airline.avg.delay$Mean.Arrival.Delay), ]
airline.avg.delay <- airline.avg.delay[ ,c(3,1,2)]
airline.avg.delay
barplot(airline.avg.delay$Mean.Arrival.Delay,
names.arg=airline.avg.delay$AirlineCode,
col="grey",
main="Mean Arrival Delay by Airline",
xlab="Airline Code",
ylab="Mean Arrival Delay")
```
Data Splitting: data is divided to training and testing datasets:
```{r}
#library(caret)
#ind <- sample(2, nrow(flights), replace = TRUE, prob=c(0.7, 0.3))
#Too high memory required for the random arrangements
#trainset = flights[ind == 1,]
#testset = flights[ind == 2,]
rm(flights_train)
rm(testData)
set.seed(120)
trainset = flights[1:4073355,]
testset = flights[4073355:5819079,]
```
Create categorical columns for the trainset.
```{r}
#na.omit(trainset)
#na.omit(flights)
trainset$delayed = trainset$ARRIVAL_DELAY > 0
trainset$on_time = trainset$ARRIVAL_DELAY == 0
trainset$ahead_of_time = trainset$ARRIVAL_DELAY < 0
#flights_train <- colMeans(flights[,-23])
#flights_train = subset(flights, select = -c(23))
#str(flights_train)
#testData = flights_train[1:400,]
```
Installation and initiation Neural net package
Neural net for the newly created categorical attribues
```{r}
# Too big
library(neuralnet)
nn_result = neuralnet(delayed + on_time + ahead_of_time ~ SCHEDULED_DEPARTURE + DEPARTURE_DELAY + TAXI_OUT + TAXI_IN + SCHEDULED_ARRIVAL + ARRIVAL_TIME, trainset, hidden=1)
#nn_result
```
Result matrix - Use it to predict flight delay
#Predict future
```{r}
nn_result$result.matrix
#nn_pred <- compute(nn_result, testset)
#Run them through the neural network
```
Plot the Neural network
```{r}
plot(nn_result)
```
<file_sep>/Working in R.R
#get/check working directory
getwd()
#set working directory
setwd("/Users/ganeshharugeri/Documents/R_workspace/input/")
#remove working directory path
#unlink("/Users/ganeshharugeri/Documents/R_workspace/input")
#Read file from working directory
filename <- paste(c(getwd(),"/Chronic_kidney_disease_formatted.csv"),collapse="")
#Checked how paste works, it concanates the strings from the input
#?paste
# read file now
CKD_Dataset <- read.csv(filename,sep = ";",header = 1 )
summary(CKD_Dataset)
str(CKD_Dataset)
ls()
ShowAllRowsWithMissingWBValues <- CKD_Dataset[is.na(CKD_Dataset$White_Blood_Cell_Count),]
rm(result)
str(CKD_Dataset)
head(CKD_Dataset)
summary(CKD_Dataset)
#Check for the percentage of NA values in each columns of the dataset
NA_Percentage_CKD_Dataset <- function(total_rows,totalNAs){
percentage = (100* totalNAs)/total_rows
return(percentage)
}
#rm(NA_Percentage_CKD_Dataset())
# Recursive function to chekc for percentage of NA values in any dataset
NA_Percentage_Any_Dataset <- function(Dataset,total_rows){
mylist =list()
for(i in names(Dataset)){
#print(i)
total_NAs = sum(is.na(Dataset[[i]]))
# print(total_NAs)
percentage = (100* total_NAs)/total_rows
#print(percentage)
mylist[[i]]=percentage
# cat('Column',i,'has',percentage,'% of NA Vaues\n')
#cat('--------------------------------------------\n')
}
summary(mylist)
# columnwise percentages of NAs
mylist
#mylist[order(mylist[1]),]
# sort.list(mylist)
}
# Getting column names
#names(CKD_Dataset)
#Column "White_Blood_Cell_Count" is removed as it had more than 25% of NA(missing) values
CKD_Dataset$White_Blood_Cell_Count <- NULL
# Column "Specific_Gravity" isn't varying much, hence it will affect the end result
#CKD_Dataset$Specific_Gravity =
# Good package to clean data
install.packages("tidyr")
library(tidyr)
# As following columns have very few NAs we can fill them up with relative values to that the other rows(NA<10%)
NewDataSet <- CKD_Dataset %>% fill(Kidney_Disease,Anemia,Pedal_Edema,Coronary_Artery_Disease,Diabetes_Mellitus,Hypertension,Serum_Creatinine,Blood_Urea,Bacteria,Pus_Cell_clumps,Blood_Pressure,Age)
# package to help finding correlation, covarience ang other dependencies
install.packages("ggpubr")
library("ggpubr")
# Draw a scatter plaot to find the correlation betwn Specific_Gravity and Kidney_Disease
ggscatter(NewDataSet, x = "Specific_Gravity", y = "Kidney_Disease",
add = "reg.line", conf.int = TRUE,
cor.coef = TRUE, cor.method = "pearson",
xlab = "Specific_Gravity", ylab = "Kidney_Disease")
#Handeling Sodium NA values
NewDataSet$Sodium[is.na(NewDataSet$Sodium)] <- median(NewDataSet$Sodium,na.rm=T)
#Fill NA values with their corresponding mean of their column
for (i in c("Specific_Gravity","Hemoglobin","Packed_Cell_Volume","Appetite","Albumin","Sugar","Pus_Cell","Blood_Glucose","Potassium")){
NewDataSet[[i]][is.na(NewDataSet[[i]]mo)] <- mean(NewDataSet[[i]],na.rm=T)
# NewDataSet[,i]=as.factor(titanic_data[,i])
}
## Splitting training and test data
train_CKD <- NewDataSet[1:300,]
test_CKD <- NewDataSet[301:397,]
#Model
model_CKD <- glm(Kidney_Disease ~.,family=binomial(link='logit'),data=train_CKD)
<file_sep>/LearningR.R
var1 <-25
var2 <-50
myfunc1 <-function()
{
print("Inside function myfunc1");
print("Environment is: ");
print(environment());
print("var2 is:");
print(var2);
var2 <-55;
print("Local (but not global) var2 is modified to:");
print(var2);
}
myfunc2 <-function()
{
print("Inside function myfunc2");
print("Environment is: ");
print(environment());
var2 <<-80;
var3 <<-678;
var4 <-444;
print("Variables inside the myfunc2 environment:");
ls();
}
print("In the global environment");
environment()
myfunc1()
print("In the global environment");
print("Global var2:")
print(var2)
myfunc2()
print("In the global environment");
print("Global var2 has been modified within myfunc2 to:");
print(var2)
print("Global var3 has been created within myfunc2:");
print(var3)
print("Variables inside the global environment:");
ls();
print("Local var4 created within myfunc2 is NOT seen in the global environment
scope:");
print(var4)
| d18874402f35b99177dd234942b55131db3eab1f | [
"R",
"RMarkdown"
] | 6 | R | ganeshharugeri/R_workspace | 02d69c94ffe543cec9ab2a0a7bead4cc60f6e827 | 6547c1ad6f02548941b5a5b34c4d124fee7958db |
refs/heads/main | <repo_name>andrew-k9/archdots<file_sep>/qtile/images/credit.md
# Attributions for images used in my qtile configuration!
## ghastly.png
<div>Icons made by <a href="https://www.flaticon.com/authors/darius-dan" title="<NAME>"><NAME></a> from <a href="https://www.flaticon.com/" title="Flaticon">www.flaticon.com</a></div>
<file_sep>/zsh/.zshrc
# If you come from bash you might have to change your $PATH.
# export PATH=$HOME/bin:/usr/local/bin:$PATH
# Path to your oh-my-zsh installation.
export ZSH="/home/andrew/.oh-my-zsh"
# See https://github.com/ohmyzsh/ohmyzsh/wiki/Themes
ZSH_THEME="dracula"
source ~/.oh-my-zsh/custom/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh
plugins=(
asdf
fzf
git
zsh-autosuggestions
)
# Auto/tab complete
autoload -U compinit
zstyle ':completion:*' menu select
zmodload zsh/complist
compinit
# Include hidden files
_comp_options+=(globdots)
# Vim keys when in tab complete menu
bindkey -M menuselect 'h' vi-backwards-char
bindkey -M menuselect 'k' vi-up-line-history
bindkey -M menuselect 'l' vi-forward-char
bindkey -M menuselect 'j' vi-down-line-or-history
# Kitty
autoload -Uz compinit
compinit
# Completion for kitty
kitty + complete setup zsh | source /dev/stdin
source $ZSH/oh-my-zsh.sh
## Programming languages
. $HOME/.asdf/asdf.sh
<file_sep>/install.sh
#!/bin/bash
# This is NOT for installing arch on whatever device, this
# is a glorified package downloader and linker
# This will write over anything in your home folder!
DFP=`cd $(dirname $0) ; pwd -P`
symlink() {
cd $1
files=$(find | sed 's/^\.//g' | sed 's/^\///g')
for f in $files; do
ln -sfn $1/$f $2/$f
echo "$2/$f to $1/$f"
done
}
# 1 - link the files
symlink "$DFP/vim" "$HOME"
symlink "$DFP/neovim" "$HOME/.config/nvim"
symlink "$DFP/zsh" "$HOME"
symlink "$DFP/bash" "$HOME"
symlink "$DFP/git" "$HOME"
symlink "$DFP/system" "$HOME"
symlink "$DFP/qtile" "$HOME/.config/qtile"
symlink "$DFP/kitty" "$HOME/.config/kitty"
# 2 - install all the packages
# Assumes you've set up a user and installed
# sudo already. More of a reminder list so may not
# be 100% effective!
echo -p "Do you want to install programs? [y/n]: "
read INSTALL
if [[ INSTALL == [yY] ]]
then
sudo pacman -S \
neovim \
grub \
efibootmgr \
dosfstools \
os-prober \
mtools \
networkmanager \
curl \
zsh \
kitty \
qtile \
openssh \
ripgrep \
fzf \
base-devel
grub-install --target=x86_64-efi --efi-directory=/boot
mkdir /boot/EFI/boot
cp /boot /EFI/arch/grubx64.efi /boot/EFI/boot/bootx64.efi
echo -p "Install yay (needed for fonts)? [y/n]: "
read YAY
if [[ YAY == [yY] ]]
then
cd ~
git clone https://aur.archlinux.org/yay.git
cd yay
makepkg -si
cd $DFP
yay -S nerd-fonts-jetbrains-mono nerd-fonts-fira-code
fc-cache -fv
fi
git clone https://github.com/dracula/zsh.git ~/.config
ln -fs ~/.config/dracula.zsh-theme ~/.oh-my-zsh/themes/themes/dracula.zsh-theme
echo "Have you enabled multilib? [y/n]: "
read MULTILIB
if [[ MULTILIB == [yY] ]]
then
sudo pacman -S \
xorg \
xorg-server \
xorg-app \
xorg-init \
lightdm \
lightdm-gtk-greeter lightdm-gtk-greeter-settings
sudo systemctl enable lightdm.service
fi
sudo pacman -S alsa-utils
echo -p "Install fonts?"
echo "Make zshell default? [y/n]: "
read DSHELL
if [[ DSHELL == [yY] ]]
then
sudo chsh -s $(which zsh)
fi
echo "Install Programming stuff?"
read TMP
if [[ TMP == [yY] ]]
then
git clone https://github.com/asdf-vm/asdf.git ~/.asdf --branch v0.8.0
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
fi
reboot
fi
<file_sep>/qtile/keys/__init__.py
# keep
from .default import custom_keys
<file_sep>/README.md
# archdots
These are my dotfiles for an arch-based Linux build! I had a lot of fun doing this, but I probably will never do something
like this again. Not for Arch itself, it's just too time consuming and I only got 3/4 of the way to where I could actually use this
for more than a glorified terminal emulator...
## Screenshot

## Programs
- qtile
- kitty
- neovim
- ripgrep
- fzf
- zsh
<file_sep>/qtile/bars/default.py
from libqtile import bar, widget
def status_bar_top():
return bar.Bar(
[
widget.CurrentLayout(),
widget.GroupBox(),
widget.Prompt(),
widget.WindowName(),
widget.Chord(
chords_colors={
'launch': ("#ff0000", "#ffffff"),
},
name_transform=lambda name: name.upper(),
),
widget.TextBox("default config", name="default"),
widget.TextBox("Press <M-r> to spawn", foreground="#d75f5f"),
widget.Systray(),
widget.Clock(format='%Y-%m-%d %a %I:%M %p'),
widget.QuickExit(),
],
24,
)
def status_bar_bottom():
return bar.Bar(
[
],
24
)
<file_sep>/qtile/bars/gengarch.py
from libqtile import bar, widget
BAR_COLORS = {
'bar': '#282a36',
'lightBar': '#44475a',
'gengar': '#7b62a4',
'gengar_dark': '#5a4a9c',
'eye_dark': '#ff5a5a',
'eye_light':'#ff9494',
'inactive': '#16171d',
}
BAR_MARGIN = 6
def corner(icon, foreground, background=None):
return widget.TextBox(
background=background,
foreground=foreground,
fontsize=24,
text=icon
)
def icon():
return widget.Image(
filename='~/.config/qtile/images/ghastly.svg',
margin_x=8,
margin_y=3,
)
def group_box():
return widget.GroupBox(
background=BAR_COLORS['lightBar'],
highlight_color=[BAR_COLORS['gengar_dark'], BAR_COLORS['eye_dark']],
highlight_method='line',
inactive=BAR_COLORS['inactive'],
padding=0,
spacing=5,
this_current_screen_border=BAR_COLORS['eye_light'],
this_screen_border=BAR_COLORS['eye_light'],
)
def battery():
return widget.Battery(
charge_char='\uf584',
discharge_char='\uf57e',
empty_char='\uf582',
format='{char} {percent:2.0%}',
padding=10
)
def memory(background):
return widget.Memory(
background=background,
format='\uf2db {MemUsed} M | {MemTotal} M'
)
def storage(background):
return widget.DF(
background=background,
format='\uf7c9 [{uf}{m} | {r:.0f}%]',
measure='G',
padding=10,
visible_on_warn=False,
warn_space=5,
)
def wireless(background):
return widget.Net(
background=background,
format='\uf1eb {up} | {down}',
interface='wlo1',
interval=100000,
padding=10
)
def cpu(background):
return widget.CPU(
background=background,
format='\ufb19 {freq_current}GHz {load_percent}%',
)
def audio(background):
return widget.Volume(
background=background,
padding=8,
)
def text_icon(icon, foreground, background):
return widget.TextBox(
background=background,
foreground=foreground,
text=icon
)
def status_bar_top():
return bar.Bar(
[
icon(),
widget.CurrentLayoutIcon(scale=0.66),
corner('\ue0c7', BAR_COLORS['lightBar']),
group_box(),
corner('\ue0c7', BAR_COLORS['gengar'], BAR_COLORS['lightBar']),
widget.Prompt(background=BAR_COLORS['gengar']),
widget.WindowName(background=BAR_COLORS['gengar']),
widget.Chord(
chords_colors={
'launch': ("#ff0000", "#ffffff"),
},
name_transform=lambda name: name.upper(),
),
corner('\ue0c7', BAR_COLORS['lightBar'], BAR_COLORS['gengar']),
widget.Clock(background=BAR_COLORS['lightBar'],format='%a %H:%M', padding=10),
text_icon('\ufa7d', '#ffffff', BAR_COLORS['lightBar']),
audio(BAR_COLORS['lightBar']),
corner('\ue0c7', BAR_COLORS['bar'], BAR_COLORS['lightBar']),
battery(),
widget.QuickExit(countdown_format='{}', default_text='\uf011', padding=20),
],
24,
background=BAR_COLORS['bar'],
margin=BAR_MARGIN
)
def status_bar_bottom():
return bar.Bar(
[
widget.Spacer(length=bar.STRETCH),
corner('\ue0c7', BAR_COLORS['gengar_dark'], BAR_COLORS['bar']),
wireless(BAR_COLORS['gengar_dark']),
corner('\ue0c7', BAR_COLORS['gengar'], BAR_COLORS['gengar_dark']),
memory(BAR_COLORS['gengar']),
corner('\ue0c7', BAR_COLORS['eye_dark'], BAR_COLORS['gengar']),
cpu(BAR_COLORS['eye_dark']),
corner('\ue0c7', BAR_COLORS['eye_light'], BAR_COLORS['eye_dark']),
storage(BAR_COLORS['eye_light'])
],
24,
background=BAR_COLORS['bar'],
margin=BAR_MARGIN
)
| b42ba3cd9f4bbe4ed5d43ce5c55c78671c341301 | [
"Markdown",
"Python",
"Shell"
] | 7 | Markdown | andrew-k9/archdots | 79e79775864d3fbd56a7410787f23521fdc05497 | 69c535ba160c693419172e63a739f687a6fbcf45 |
refs/heads/main | <repo_name>hamishbray/azure-static-app<file_sep>/src/App.js
import React from 'react';
import Message from './components/Message';
function App({ name }) {
const value = 'World';
return (
<div>
Hello {name || value}, here's your message: <Message />
</div>
);
}
export default App;
| 9771616339a36eb8a47c06ad9ae683ef959b2b21 | [
"JavaScript"
] | 1 | JavaScript | hamishbray/azure-static-app | 4bf5e84c6fe4202f93022dddec04990a304a4119 | e8a175143ba28bce8fbe65162c1bb99d90dc3aff |
refs/heads/master | <file_sep>soundify
========
A dynamic programming algorithm that uses phonetics software to turn input words into other words that sound similar to the input words (try it with names)
<file_sep>import fuzzy
import Levenshtein as pylev
wordlist = []
def initialize():
global wordlist
words = []
with open('/usr/share/dict/words') as f:
words = f.readlines()
for w in words:
if not w[0].isupper():
wordlist.append( (w, fuzzy.nysiis(w)) )
def find_similar(word):
word_sound = fuzzy.nysiis(word)
best = None
best_dist = 99999
for w in wordlist:
if pylev.distance(word_sound, w[1]) < best_dist and word != w[0][:-1]:
best_dist = pylev.distance(word_sound, w[1])
best = (w[0], best_dist)
return best
def soundify(word):
table = []
table.append( ('', 0) )
word = fuzzy.nysiis(word)
for n in range(1,len(word)):
opt_n_score = 99999
opt_n_obj = None
for m in range(0, n):
opt_m = table[m]
remaining = find_similar(word[m:n])
if opt_m[1] + remaining[1] < opt_n_score:
opt_n_score = opt_m[1] + remaining[1]
opt_n_obj = (opt_m[0]+' '+remaining[0], opt_m[1] + remaining[1])
print n
table.append(opt_n_obj)
return table[-1]
print "initializing"
initialize()
print "done"
while True:
inp = raw_input("String to soundify: ")
out = soundify(inp)
print out[0].split('\n')[:-1]
| 256158493d9baa884cc730906f725cef7e9950e9 | [
"Markdown",
"Python"
] | 2 | Markdown | mbc1990/soundify | ee2f7a3547aca08e2b466e42ff5161adb8817040 | c8b335cab6feb49ec5e1c97e65135b31a0191707 |
refs/heads/master | <file_sep>package com.shpp.p2p.cs.ykohuch.assignment5;
import com.shpp.cs.a.console.TextProgram;
//this program does a mathematical function of adding in to a column
public class Assignment5Part2 extends TextProgram {
public void run() {
/* Sit in a loop, reading numbers and adding them. */
while (true) {
String n1 = readLine("Enter first number: ");
String n2 = readLine("Enter second number: ");
/*here uses a regular expression to check whether a user entered a numbers*/
if(n1.matches("[\\d]+") && n2.matches("[\\d]+")) {
//print the result
println(n1 + " + " + n2 + " = " + addNumericStrings(n1, n2));
}else {
println("Enter the numbers ");
}
}
}
/**
* Given two string representations of nonnegative integers, adds the
* numbers represented by those strings and returns the result.
*
* @param n1 The first number.
* @param n2 The second number.
* @return A String representation of n1 + n2
*/
private String addNumericStrings(String n1, String n2) {
/* before continuing need to check that the length of n2 is greater
* if first string is longer we make it basic */
if (n1.length() > n2.length()){
String basic = n1;
n1 = n2;
n2 = basic;
}
// Take an empty String for storing result
StringBuilder result = new StringBuilder();
// initialize variables that store the length of strings
int value1 = n1.length();
int value2 = n2.length();
//subtract the length of the longer string from the length of the shorter one
int diff = value2 - value1;
// Initially zero for the rest
int remainder = 0;
// Traverse from end of both Strings
for (int i = value1 -1 ; i>=0; i--)
{
// Compute sum of current digits
int sum = ((n1.charAt(i)-'0') + (n2.charAt(i+diff)-'0') + remainder);
result.append((char) (sum % 10 + '0'));
remainder = sum / 10;
}
// add the remainder to the string n2
for (int i = value2 - value1 - 1; i >= 0; i--)
{
int sum = ((n2.charAt(i) - '0') + remainder);
result.append((char) (sum % 10 + '0'));
remainder = sum / 10;
}
// reverse resultant String
return new StringBuilder(result.toString()).reverse().toString();
}
}<file_sep>package com.shpp.p2p.cs.ykohuch.assignment5;
import com.shpp.cs.a.console.TextProgram;
/**
* This program checks the number of syllables in a word entered by the user.
* counting the number of vowels in the word (including y), except:
* vowels, before which other vowels stand
* the letter e if it is at the end of the word
* Also, the program always returns at least 1 warehouse, even if the analysis shows that there are no warehouses
*/
public class Assignment5Part1 extends TextProgram {
public void run() {
/* Repeatedly prompt the user for a word and print out the estimated
* number of syllables in that word.
*/
while (true) {
String word = readLine("Enter a single word: ").toLowerCase();
/*here uses a regular expression to check whether a user entered a word without numbers*/
if (word.matches("(?i).*[a-z].*")) {
println(" Syllable count: " + syllablesIn(word));
} else {
println("Please, enter a word without numbers");
}
}
}
/**
* Given a word, estimates the number of syllables in that word according to the
* heuristic specified in the handout.
*
* @param word A string containing a single word.
* @return An estimate of the number of syllables in that word.
*/
private int syllablesIn(String word) {
//array of vowel letters
char[] vowels = { 'a', 'e', 'i', 'o', 'u', 'y' };
//convert word from string to char array
char[] entryWord = word.toCharArray();
//vowels counter
int vowelsCounter = 0;
//boolean to check if the previous letter was vowel
boolean lastWasVowel = false;
//cycle for sorting letters
for (char i : entryWord) {
boolean foundVowel = false;
for (char v : vowels) {
//don't count vowel if previous was vowel
if ((v == i) && lastWasVowel)
{
foundVowel = true;
lastWasVowel = true;
break;
}
else if (v == i)
{
vowelsCounter++;
foundVowel = true;
lastWasVowel = true;
break;
}
}
// If full cycle and no vowel found, set lastWasVowel to false;
if (!foundVowel)
lastWasVowel = false;
}
/* reject the letter e if the word contains more than two letters and ends with e
* considered the case with the word "manatee"*/
if (word.length() > 2 && word.endsWith("e") && word.charAt(word.length() - 2) != 'e') {
vowelsCounter--;
}
/*if a word has no vowels, and word length is bigger than 0 program will return 1*/
if(vowelsCounter == 0 && word.length()>0) {
return vowelsCounter + 1;
}
return vowelsCounter;
}
}
| 203f3b087847824923d204bbe86c70cefc79bfd1 | [
"Java"
] | 2 | Java | yurikoguch/string_parsing | e865e76217eb69cfd5bda2f5131a0f14039223bf | a76587b7f7d9197998fcdd989682c29bb98e2892 |
refs/heads/master | <file_sep>#!/usr/bin/env python
def calcChecksum(Packet): #do not include checksum when calling
checksum = 0x00
for x in range(len(Packet)):
if x>1:
checksum = checksum + Packet[x]
print checksum
checksum = ~checksum
checksum &= 0xFF
Packet.append(checksum)
return Packet
def movePacket(velocity): #input ranges from +1 to -1, +forward/CW; -reverse/CCW
#ID, length, instr, address1, address2,
velocity = int(1023*velocity)
if velocity < 0:
direction = 0
else:
direction = 1
magnatude = abs(velocity)
magnatude &= 0x3FF
packet = direction << 10
packet |= magnatude
byte1 = packet&0xFF00
byte1 = byte1>>8
byte2 = packet&0xFF
print byte1
print byte2
#packet = calcChecksum([0XFF, 0XFF, ID, length, instr, address1, address2, byte1, byte2])
#print packet
return packet
movePacket(1)
| 98d6c1dbbeead6905b6f61fa0c283d9845eff569 | [
"Python"
] | 1 | Python | edroderick/Assignments | 59e11ac4fca46890fb939cfe71be118a9cac85cf | 82c0d52132c0b8a5f8674e2ce6afc8594a3b7ed1 |
refs/heads/main | <file_sep>### ( Cómo crear el proyecto )
#### Guía - jsrois
1. Crear una carpeta
```bash
mkdir npm-webpack-template
cd npm-webpack-template
```
Después de crear la carpeta, podemos abrirla con IntelliJ
2. Dentro de la carpeta, inicializar el proyecto npm (esto crea un archivo `package.json`):
```bash
npm init -y
```
3. instalar las siguientes dependencias usando `npm install`:
```text
babel-loader
bootstrap
css-loader
html-webpack-plugin
jquery
mini-css-extract-plugin
node-sass
sass-loader
webpack
webpack-cli
```
4. Creamos un archivo `.gitignore` para no commitear por accidente las carpetas `.idea` y `node_modules`
5. Creamos un archivo `index.html` en una carpeta `src`. Añadimos lo siguiente:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>Click!</title>
</head>
<body>
<div class="card">
<p> Hola! Haz click en el botón para aumentar el contador </p>
<button id="clicker">Click me!</button>
<div id="counter"></div>
</div>
</body>
</html>
```
6. Creamos un archivo de estilos en `src/css/style.scss`:
```scss
.card {
width: 300px;
border: thin solid black;
border-radius: 7px;
box-shadow: black 1px 1px;
margin: auto;
padding: 10px;
}
#clicker {
margin-bottom: 10px;
&:hover {
transform: translate(2px, 2px);
}
}
```
7. Dentro de `src/js`, creamos dos archivos, `main.js` y `counter.js`.
`main.js` es el archivo principal de javascript, que utiliza jQuery y una clase `Counter` para incrementar un contador
cada vez que pulsemos un botón.
```js
import $ from 'jquery';
import {Counter} from "./counter";
let counter = new Counter()
$(document).ready(function () {
$('#counter').text("No clicks! Start clicking!")
})
$('#clicker').click(function () {
$('#counter').text(`The count is ${counter.incrementAndReturn()}`)
})
```
`counter.js` contiene una **clase** que representa un "Contador". Cada vez que llamemos a la función `incrementAndReturn`,
este objeto incrementará el contador y nos devolverá el número actual.
```js
export class Counter {
constructor() {
this.count = 0
}
incrementAndReturn() {
return this.count++;
}
}
```
### Webpack!
8. Creamos un archivo de configuración para webpack, `webpack.config.js`. En este archivo añadimos la siguiente configuración:
```js
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const path = require("path");
const isDevelopment = process.env.NODE_ENV === 'development';
module.exports = {
entry: [
path.join(__dirname, 'src/js/main.js'),
path.join(__dirname, 'src/css/style.scss')
],
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'build'),
clean: true
},
resolve: {
extensions: [".js", ".scss"]
},
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new MiniCssExtractPlugin({
filename: isDevelopment ? '[name].css' : '[name].[fullhash].css',
chunkFilename: isDevelopment ? '[id].css' : '[id].[fullhash].css'
})
]
}
```
9. modificamos el archivo `package.json`, añadiendo el comando `build`:
```json
"scripts": {
"build": "webpack --mode=production"
}
```
Esto significa que cuando hagamos `npm run build` se ejecutará webpack, que generará nuestra página web estática en la carpeta "build".
## Entendiendo el archivo `webpack.config.js`:
La configuración de webpack se escribe en este archivo de javascript.
Este bloque hace que webpack procese los archivos principales de Javascript y SCSS:
```js
entry: [
path.join(__dirname, 'src/js/main.js'),
path.join(__dirname, 'src/css/style.scss')
]
```
Hace que el resultado de la compilación se genere en la carpeta "build", en un archivo `bundle.js`
```js
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'build'),
clean: true
}
```
La sección `rules` determina lo que queremos hacer con cada archivo. Los archivos `.js` son procesados por `babel-loader`,
un componente que _transpila_ (convierte) el código a una versión "clásica" de Javascript. Los archivos `.scss` se procesan
con varios loaders que terminan generando un solo archivo css.
```js
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
"css-loader",
"sass-loader"
]
}
]
}
```
### Referencias
https://desarrolloweb.com/articulos/procesamiento-css-sass-webpack.html
https://desarrolloweb.com/articulos/html-webpack-plugin-inyectar-bundles.html
https://desarrolloweb.com/articulos/transpilado-javascript-webpack.html<file_sep>import $ from 'jquery';
import {Counter} from "./counter";
let counter = new Counter()
$(document).ready(function () {
$('#counter').text("No clicks! Start clicking!")
})
$('#clicker').click(function () {
$('#counter').text(`--> The count is ${counter.incrementAndReturn()}`)
})<file_sep>import {Counter} from "../src/js/counter";
describe("Counter", () =>{
it("should count numbers", () => {
let Counter = new counter()
expect(counter.incrementAndReturn()).toBe(1)
expect(counter.incrementAndReturn()).toBe(2)
expect(counter.incrementAndReturn()).toBe(3)
})
})<file_sep>export class Counter {
constructor() {
this.count = 0
}
incrementAndReturn() {
this.count++
return this.count
}
} | 65082bc2aefdc78d64863150e7ddbfdd6bab03db | [
"Markdown",
"JavaScript"
] | 4 | Markdown | mabicodes/npm-webpack-template | f74367f1cfbb28fad5242dd3c13b76ae1b174643 | 2e0652c41afd98d38c480628e373a22d47a39d4a |
refs/heads/master | <repo_name>QPJIANG/NoteSome<file_sep>/java/java_common/Reflect.md
参考:
<https://www.jianshu.com/p/9be58ee20dee>
<file_sep>/docker/3_storagepath.md
参考: https://blog.csdn.net/wenwenxiong/article/details/78728696
```
sudo docker info | grep "Docker Root Dir" 查存储路径
1. 停docker 服务
2. 移动docker目录
3. 将移动后的目录软连接到移动前的目录
4. 启动docker 服务
```
```
systemctl status docker 查service 文件 (/usr/lib/systemd/system/docker.service)
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock
结尾加 --graph
ExecStart=/usr/bin/dockerd -H fd:// --containerd=/run/containerd/containerd.sock --graph 存储路径
```
<file_sep>/java/nexus/usage.md
上次jar 到私服 nexus
1. 创建仓库和用户
```
nexus: 默认用户admin 默认密码:<PASSWORD> (为了安全建议首次使用时进行修改)
----------------------------------------------------
Repository->Repositories: 下创建仓库
java maven 私服仓库: 类型选择 maven2(hosted)
仓库名: 仓库id
发布策略: 选allow redepoly
填写好后保存,在 Repositories列表中,url 表示仓库地址。
----------------------------------------------------
Security -> Roles
添加角色:自定义用户权限
Security -> Users
添加用户: 配置角色授权
```
2. 配置maven
```
在settings.xml 中配置服务器用户名密码 (可以是全局的也可以是用户级的)
<server>
<id>仓库id</id>
<username>admin</username>
<password><PASSWORD>>
</server>
```
3. 发布jar
```
mvn deploy:deploy-file
-DgroupId=包goupid
-DartifactId=包id
-Dversion=包版本号
-Dpackaging=jar
-Dfile=jar包路径
-Durl=仓库地址
-DrepositoryId=仓库id(与settings 中一致)
```
```
如果要把构建部署至私服中,需要在构建的 pom.xml 文件增加 distributionManagement 配置项. 配置见install.md
```
<file_sep>/editor/vscode/settings.md
.vscode/settings.json
```
// 一个文件使用一个tab
"workbench.editor.enablePreview": false
// 文件菜单树不显示的文件/目录
"files.exclude": {
"**/.git": true,
"**/.svn": true,
"**/__pycache__": true,
"**/.DS_Store": true,
"**/node_modules": true,
"**/*.pyc": true
}
```
快捷键设置:
File -> Perferience -> KeyboardShortcuts
```
//文件注释模板: psioniq File Header
"psi-header.templates": [
{
"language": "*",
"template": [
"FileName: <<filename>>",
"Project: <<projectname>>",
"",
"Author: <EMAIL>",
"File Created: <<filecreated('YYYY-MM-DD h:mm:ss ,dddd')>>",
"",
"Modified By: <<author>>",
"Last Modified: <<dateformat('YYYY-MM-DD h:mm:ss ,dddd')>>",
"",
"Copyright (c) <<filecreated('YYYY')>> xxxxxxxxxx."
]
}
],
"psi-header.lang-config": [
{
"language": "javascript",
"begin": "",
"end": "",
"prefix": "// "
},
{
"language": "python",
"begin": "####################################################################################################",
"end": "####################################################################################################",
"prefix": "# ",
"suffix":"#",
"lineLength":100,
"replace":[],
"modAuthor":"Modified By: <EMAIL>",
"modDate":"Last Modified: <<dateformat('YYYY-MM-DD h:mm:ss ,dddd')>>",
}
],
"psi-header.changes-tracking":{
"isActive":true,
"modAuthor":"Modified By: <EMAIL>",
"modDate":"Last Modified: <<dateformat('YYYY-MM-DD h:mm:ss ,dddd')>>",
"autoHeader":"autoSave"
},
```
终端字体不好看(字母间距不一致): (需要使用等宽字体,monospace 可换为其他可用字体)
```
// 设置字体可解决问题
"terminal.integrated.fontFamily": "monospace",
// 其他配置
"terminal.integrated.fontSize": 16,
"terminal.integrated.copyOnSelection": true,
"terminal.integrated.fontWeight":"300",
"terminal.integrated.fontWeightBold": "100",
"terminal.integrated.lineHeight": 1.3,
"terminal.integrated.letterSpacing":0,
// 字体颜色与背景色
"workbench.colorCustomizations" :
{
"terminal.foreground" : "#37FF13",
"terminal.background" : "#2b2424"
},
```
<file_sep>/python/flask/appbuilder/0_index.md
官方文档: <https://flask-appbuilder.readthedocs.io/en/latest/>
简介:
简单快速的应用程序开发框架,构建于[Flask](http://flask.pocoo.org/)之上。包括详细的安全性,模型的自动CRUD生成,谷歌图表等等
flask 文档:<http://docs.jinkan.org/docs/flask/index.html> flask的一些基本用法,可一快速开始一个web项目。
<file_sep>/linux/Fedora_Linux/rpm/usage.md
参考:https://www.cnblogs.com/xuxiuxiu/p/5740484.html
```
rpm -i xxx.rpm :安装rpm 包 , -ivh 显示进度
rpm -ivh --test : 用来检查依赖关系;并不是真正的安装
--relocate 指定安装路径: rpm -ivh --relocate /=/opt/gaim gaim-1.3.0-1.fc4.i386.rpm
rpm -Uvh xx.rpm: 升级安装
rpm -Uvh --oldpackage xx.rpm : 降级
rpm -qpi xxx.rpm:查看rpm包 --query--package--install package信息
rpm -qpR xxx.rpm :查看包依赖关系
rpm2cpio file.rpm |cpio -div : 从rpm软件包抽取文件,抽取出来的文件就在当用操作目录中的 usr 和etc中
```
```
rpm --recompile vim-4.6-4.src.rpm #这个命令会把源代码解包并编译、安装它
rpm --rebuild vim-4.6-4.src.rpm #在安装完成后,还会把编译生成的可执行文件重新包装成i386.rpm的RPM软件包。
```
```
rpm -ql packname : 查看安装位置 rpm rpmquery -ql packname
rpm -qi packname: 查看包信息
rpm -qil packname: 查看包信息和安装位置
rpm -qR packname:查看包依赖
rpm -e packname: 卸载,--nodeps 忽略依赖的检查来删除
```
<file_sep>/study/mvp.md
MVP(Minimum Viable Product)
<http://www.woshipm.com/pmd/447678.html>
<file_sep>/sql/postgresql/psql_env.md
```
PGHOST
PORT
PGDATABASE
PGUSER
PGPASSWORD
PSQL_HISTORY
PSQLRC
```
<file_sep>/windows/some_cmd.md
dxdiag : 使用directX 获取电脑配置
<file_sep>/linux/softs/zabbix/install_and_run.md
# install
rpm -i http://repo.zabbix.com/zabbix/3.4/rhel/7/x86_64/zabbix-release-3.4-2.el7.noarch.rpm
yum install zabbix-server-pgsql zabbix-web-pgsql zabbix-agent
install postgresql , and import database(/usr/share/doc/zabbix-server-pgsql*/create.sql.gz)
vi /etc/zabbix/zabbix_server.conf
DBHost=localhost
DBName=zabbix
DBUser=zabbix
DBPassword=<PASSWORD>
run:
systemctl start zabbix-server zabbix-agent httpd
run while os up
systemctl enable zabbix-server zabbix-agent httpd
<file_sep>/java/jsp/0.md
```
JSP中九大内置对象:
---------------------------------------------------------------------------------
request
请求对象 类型 javax.servlet.ServletRequest 作用域 Request
HttpServletRequest 包含请求信息
---------------------------------------------------------------------------------
response
响应对象 类型 javax.servlet.SrvletResponse 作用域 Page
HttpServletResponse 包含响应信息
---------------------------------------------------------------------------------
pageContext
页面上下文对象 类型 javax.servlet.jsp.PageContext 作用域 Page
---------------------------------------------------------------------------------
session
会话对象 类型 javax.servlet.http.HttpSession 作用域 Session
包含会话的session 信息。
session 数据存放在application 中。 需要通过请求端传递session id(一般存放在cookie中),才能找到。
session 一般有超时时间(可配置)
---------------------------------------------------------------------------------
application
应用程序对象 类型 javax.servlet.ServletContext 作用域 Application
application 对象可将信息保存在服务器中,直到服务器关闭。 (一个web 项目启动即会创建application对象)
---------------------------------------------------------------------------------
out
输出对象 类型 javax.servlet.jsp.JspWriter 作用域 Page
往response 中写入响应的内容
---------------------------------------------------------------------------------
config
配置对象 类型 javax.servlet.ServletConfig 作用域 Page
---------------------------------------------------------------------------------
page
页面对象 类型 javax.lang.Object 作用域 Page
---------------------------------------------------------------------------------
exception
异常对象 类型 javax.lang.Throwable 作用域 page
```
```
JSP四大作用域
application 在所有应用程序中有效,全部用户共享(javax.servlet.ServletContext)
session 在当前会话中有效,仅供单个用户使用(javax.servlet.http.HttpSession)
request 在当前请求中有效,只在一个请求中保存数据(javax.servlet.httpServletRequest)
page 在当前页面有效,只在一个页面保留数据(javax.servlet.jsp.PageContext(抽象类))
---------------------------------------------------------------------------------
request和page的生命周期都是短暂的,它们之间的区别:一个request可以包含多个page页(include,forward及filter)。
```
<file_sep>/java/springboot/guide/2_scheduler.md
在main 函数的class 上增加注解 @EnableScheduling
然后编写 scheduler 任务类(@Component)
任务类的方法上加 @Scheduled 注解
@Scheduled(调度方式相关参数)
默认为单线程调用。
@Scheduled(cron = "*/1 * * * * ?")
@Scheduled(fixedDelay = 1000) // 本次执行结束后,与下次开始的时间间隔
@Scheduled(fixedRate = 1000) //本次开始执行与下次开始执行的时间间隔
fixedDelay,fixedRate 单位 ms
**@Scheduled(fixedRate) 如何避免任务被阻塞**
注解`@EnableAsync`(类上)和`@Async`(方法上)
<file_sep>/sql/postgresql/case.md
```
case 、coalesce、nullif 、greatest、least
coalesce(value[,...]) 入参个数不限,返回参数中第一个非NULL值。 ( 常用: coalesce(字段名,默认值))
GREATEST(value [, ...]) 返回最大的值
LEAST(value [, ...]) 返回最小的值
# 注意比较值得类型一定要相同
NULLIF(value1, value2)
当value1和value2相等时,NULLIF返回一个空值。 否则它返回value1。
case when ? then
...
when ? then
...
else
end
```
<file_sep>/C_or_C++/cmake/0.md
与make 类似的工具。
CMakeList.txt
一般使用:
在 CMakeList.txt 统计目录建build 目录,并在 build 目录下执行 cmake .. 生产Make 相关文件。
```
# cmake 版本需求说明
cmake_minimum_required(VERSION 3.5)
# 设置项目名称
project (hello_cmake)
# 指定可执行文件(执行文件 源文件列表)
add_executable(hello_cmake main.cpp)
```
```
# 指定源文件
set(SOURCES
src/Hello.cpp
src/main.cpp
)
add_executable(hello_headers ${SOURCES})
```
```
# 指定头文件查找目录: when running g++ these will be included as -I/directory/path/
# PRIVATE
target_include_directories(hello_headers
PRIVATE
${PROJECT_SOURCE_DIR}/include
)
```
静态库
```
# 指定静态库:并指定静态库相关源码文件
add_library(hello_library STATIC
src/Hello.cpp
)
# PUBLIC
target_include_directories(hello_library
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
# 指定执行程序和源码(源码不含静态库相关文件)
add_executable(hello_binary
src/main.cpp
)
# 链接静态库
target_link_libraries( hello_binary
PRIVATE
hello_library
)
```
动态库
```
#指定动态库:并指定静态库相关源码文件
# SHARED
add_library(hello_library SHARED
src/Hello.cpp
)
# 别名在前
add_library(hello::library ALIAS hello_library)
# PROJECT_SOURCE_DIR : CMakeList.txt 同级目录
target_include_directories(hello_library
PUBLIC
${PROJECT_SOURCE_DIR}/include
)
# 无论引入动态库还是静态库 都没有引入库相关源码
# 指定执行程序和源码(源码不含静态库相关文件)
add_executable(hello_binary
src/main.cpp
)
# 链接动态库
target_link_libraries( hello_binary
PRIVATE
hello::library
)
```
Install
```
############################################################
# Install
############################################################
# Binaries: 二进制放入 bin
install (TARGETS cmake_examples_inst_bin
DESTINATION bin)
# Library: lib 放入lib
# Note: may not work on windows
install (TARGETS cmake_examples_inst
LIBRARY DESTINATION lib)
# Header files : 头文件放入 include
install(DIRECTORY ${PROJECT_SOURCE_DIR}/include/
DESTINATION include)
# Config : 配置文件
install (FILES cmake-examples.conf
DESTINATION etc)
```
install
```
make install 会生成: install_manifest.txt 用作记录安装位置
CMAKE_INSTALL_PREFIX 默认为 /usr/local/
```
make install DESTDIR=/tmp/stage
```
This will create the install path `${DESTDIR}/${CMAKE_INSTALL_PREFIX}` for all
your installation files. In this example, it would install all files under the
path `/tmp/stage/usr/local`
```
$ tree /tmp/stage
/tmp/stage
└── usr
└── local
├── bin
│ └── cmake_examples_inst_bin
├── etc
│ └── cmake-examples.conf
└── lib
└── libcmake_examples_inst.so
```
```
编译type:
```
* Release - Adds the `-O3 -DNDEBUG` flags to the compiler
* Debug - Adds the `-g` flag
* MinSizeRel - Adds `-Os -DNDEBUG`
* RelWithDebInfo - Adds `-O2 -g -DNDEBUG` flags
# Set a default build type if none was specified
if(NOT CMAKE_BUILD_TYPE AND NOT CMAKE_CONFIGURATION_TYPES)
message("Setting build type to 'RelWithDebInfo' as none was specified.")
# 设置默认值
set(CMAKE_BUILD_TYPE RelWithDebInfo CACHE STRING "Choose the type of build." FORCE)
# Set the possible values of build type for cmake-gui
set_property(CACHE CMAKE_BUILD_TYPE PROPERTY STRINGS "Debug" "Release"
"MinSizeRel" "RelWithDebInfo")
endif()
[source,cmake]
----
cmake .. -DCMAKE_BUILD_TYPE=Release
----
```
<file_sep>/linux/desktop-evn/xfce4/solutions.md
netease-cloud-music 窗口问题:有额外的窗口
在netease-cloud-music.desktop中把启动的命令改为
env XDG_CURRENT_DESKTOP=DDE netease-cloud-music %U
<file_sep>/linux/disk_manager/raid.md
raid 介绍
```
RAID-0
两块盘合成一块盘使用,可使用容量为两块盘的容量之和.
读:同时读(效率高)
写:同时写(效率高),数据被分散写入两块盘
RAID-1
一块盘作为另一块盘的镜像使用.可使用容量为一块盘的容量(容量相同的磁盘).
数据传送到 I/O 总线后会被复制多份到各个磁盘,结果就是数据量感觉变大了!因此在大量写入 RAID-1 的情况下,写入的性能可能会变的非常差(如果使用的是硬件 RAID (磁盘阵列卡) 时,磁盘阵列卡会主动的复制一份而不使用系统的 I/O 总线,性能方面则还可以)
读取: 可做负载均衡
RAID-0 的性能佳但是数据不安全,RAID-1 的数据安全但是性能不佳
RAID 1+0
先让两颗磁盘组成 RAID 1,并且这样的设置共有两组;
将这两组 RAID 1 再组成一组 RAID 0
RAID 0+1
先让两颗磁盘组成 RAID 0,并且这样的设置共有两组;
将这两组 RAID 0 再组成一组 RAID 1
raid 5
n (n>=3)块盘: 其中一块做校验盘使用. (个别盘损坏不影响使用)
raid 6
至少4块盘: 其中2块做校验盘使用. (个别盘损坏不影响使用)
```
<file_sep>/sql/postgresql/rule.md
参考 <https://blog.csdn.net/luojinbai/article/details/44903589>
```sql
新版postgres 不使用trigger,使用function
CREATE [ OR REPLACE ] RULE name AS ON event
TO table_name [ WHERE condition ]
DO [ ALSO | INSTEAD ] { NOTHING | command | ( command ; command ... ) }
insert : new.<字段名> 获取插入数据的值
update : new.<字段名> 获取更新数据的值 , old.<字段名> 获取更新前的值
delete : old.<字段名> 获取s删除前前的值
create or replace rule <rule_name> as on insert to <bind_table> do also insert into <target_table> (xxx,xxx,...) values(new.<字段名>,new.<字段名>,...);
create or replace rule <rule_name> as on update to <bind_table> do also insert into <target_table> (xxx,xxx,...) values(old.<字段名>,new.<字段名>....);
create or replace rule <rule_name> as on delete to <bind_table> do also insert into <target_table> (xxx,xxx,...) values(old.<字段名>,old.<字段名>,...);
DROP RULE [ IF EXISTS ] name ON table_name [ CASCADE | RESTRICT ]
```
<file_sep>/java/maven/dependencyManagement.md
参考: <https://www.cnblogs.com/feibazhf/p/7886617.html>
```
父项目中使用dependencyManagement: 声明依赖及版本,
子项目中使用相同的依赖时,可不指定版本,(只需指定groupId,artifactId 等), 继承父项目中的版本.
子项目也可单独指定不同的版本.
```
```
dependencies 即使在子项目中不写该依赖项,那么子项目仍然会从父项目中继承该依赖项(全部继承)
dependencyManagement 里只是声明依赖,并不实现引入,因此子项目需要显示的声明需要用的依赖。
如果不在子项目中声明依赖,是不会从父项目中继承下来的;
只有在子项目中写了该依赖项,并且没有指定具体版本,才会从父项目中继承该项,并且version和scope都读取自父pom;另外如果子项目中指定了版本号,那么会使用子项目中指定的jar版本。
```
```
<dependencies>中的jar直接加到项目中,管理的是依赖关系(如果有父pom,子pom,则子pom中只能被动接受父类的版本);
<dependencyManagement>主要管理版本,对于子类继承同一个父类是很有用的,集中管理依赖版本不添加依赖关系,对于其中定义的版本,子pom不一定要继承父pom所定义的版本。
```
```bash
mvn dependency:tree
```
<file_sep>/linux/Fedora_Linux/dnf/base.md
dnf 新一代的RPM软件包管理器, 可取代yum.
```
dnf repolist #列举可用软件库
dnf repolist all #列举软件库,包含可用和不可用的软件库
dnf list # 与yum list 一致
dnf list installed # 列举已安装的软件
dnf list available
dnf search <package_name> # 包含该关键字的包,关键字可出现在包描述中
dnf provides <file_name> # 文件在哪个软件包
dnf info <package_name> # 软件包的详细信息
dnf install <package_name> # 与yum install 一致
dnf update <package_name> # 升级软件包
dnf check-update #检查系统中所有软件包的更新
dnf update , dnf upgrade #升级系统中所有有可用升级的软件包
dnf remove <package_name> , dnf erase <package_name> # 卸载
dnf reinstall <package_name>
dnf autoremove # 移除孤立的软件包
dnf downgrade <package_name> #降低特定软件包的版本
dnf clean all # 与 yum clean all 一致
dnf grouplist # 与yum grouplist 一致
dnf groupinstall <groupname> #与yum groupinstall 一致,组名用引号包起来
dnf groupupdate <groupname>
dnf groupremove <groupname>
#从特定的软件包库安装特定的软件
dnf –enablerepo=<repo> install <package_name>
#通过所有可用的软件源将已经安装的所有软件包更新到最新的稳定发行版
dnf distro-sync
```
<file_sep>/js/webpack/index.md
https://www.webpackjs.com/
https://www.webpackjs.com/guides/getting-started/
```
组要使用方法参考webpack 官网。
entry: js 入口(chunks)
plugins: 插件: 不同的插件完成不同的功能。
module: {rules: []} 通过不同的loader 处理不同类型的文件
output: entry 编译后生成的文件。
```
```
HtmlWebpackPlugin: 用户生成html,chunks 指定entry 里配置的key. 来完成相应的js 引入。(配置一个html 页面)
var webpack = require('webpack');
# 自动加载模块,无需每处 import 或 require
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery'
}),
```
resolve: 引入文件时不用带后缀,同时定义别名 用于导入时简写
```
import xxx from '@/components/xxxx'
```
```
const resolve = dir => path.resolve(__dirname, dir); // 定义函数
```
```
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue': 'vue/dist/vue.js',
'@': resolve('src'),
}
}
```
<file_sep>/linux/kvm/0_desc.md
KVM是Kernel-based Virtual Machine的简称,是一个开源的虚拟化模块
```
```
<file_sep>/python/virtualenv.md
## install virtualenv
```
# pip install virtualenv
# pip3 install virtualenv
```
```
virtualenv --no-site-packages venv # python version = python -V
virtualenv -p /usr/bin/python3.5 --no-site-packages venv # 制定python版本
virtualenv --no-site-packages --always-copy venv # --allways-copy 文件不是用软链接
--no-site-packages: 参数被 --clear 取缔 (virtualenv 20.1.0, 那个版本开始的不知道)
```
### virtualenvwrapper: 基于virtualenv之上的工具,它将所有的虚拟环境统一管理。
```
sudo pip install virtualenvwrapper
virtualenvwrapper默认将所有的虚拟环境放在 WORKON_HOME 目录下管理,可以修改环境变量WORKON_HOME来指定虚拟环境的保存目录。
WORKON_HOME 默认值: ~/.virtualenvs
~/.bashrc
export WORKON_HOME=~/Envs
source $(which virtualenvwrapper.sh)
用法
创建虚拟环境
$ mkvirtualenv env27
创建指定解释器的虚拟环境
$ mkvirtualenv -p python3.4 env34
启动虚拟环境
$ workon env27
退出虚拟环境
$ deactivate
删除虚拟环境
$ rmvirtualenv env27
```
<file_sep>/js/knockout/5_bindingHandlers.md
参考:<https://www.cnblogs.com/xiaoxiaoqiye/p/5908198.html>
```
ko.bindingHandlers.slideVisible = {}
<div data-bind="slideVisible:te"></div>
```
<file_sep>/js/knockout/6_array_utils.md
参考: <https://blog.csdn.net/qq_26775359/article/details/78266079>
```
ko.utils.arrayForEach(array, callback)
var arr = [1, 2, 3, 4];
ko.utils.arrayForEach(arr, function(el, index) {
});
ko.utils.arrayForEach = function (array, action) {
for (var i = 0, j = array.length; i < j; i++)
action(array[i], i);
}
```
```
var arr = [1, 2, 3, 4];
var newArr = ko.utils.arrayMap(arr, function(el, index) {
return el + 1;
});
ko.utils.arrayMap = function (array, mapping) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
result.push(mapping(array[i], i));
return result;
}
```
```
var arr = [1, 2, 3, 4];
var newArr = ko.utils.arrayFilter(arr, function(el, index) {
return el > 2;
});
ko.utils.arrayFilter = function (array, predicate) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++)
if (predicate(array[i], i))
result.push(array[i]);
return result;
}
```
```
var arr = [1, 2, 3, 4];
var index = ko.utils.arrayIndexOf(arr, 2);
ko.utils.arrayIndexOf = function (array, item) {
if (typeof Array.prototype.indexOf == "function")
return Array.prototype.indexOf.call(array, item);
for (var i = 0, j = array.length; i < j; i++)
if (array[i] === item)
return i;
return -1;
}
```
```
var arr = [1, 2, 3, 4, 2];
ko.utils.arrayRemoveItem(arr, 2);
ko.utils.arrayRemoveItem = function (array, itemToRemove) {
var index = ko.utils.arrayIndexOf(array, itemToRemove);
if (index > 0) {
array.splice(index, 1);
}
else if (index === 0) {
array.shift();
}
}
```
```
var arr = [1, 2, 3, 4, 2, 4, '1'];
var newArr = ko.utils.arrayGetDistinctValues(arr);
// [1, 2, 3, 4, '1']
ko.utils.arrayGetDistinctValues = function (array) {
array = array || [];
var result = [];
for (var i = 0, j = array.length; i < j; i++) {
if (ko.utils.arrayIndexOf(result, array[i]) < 0)
result.push(array[i]);
}
return result;
}
```
```
var arr = [
{name: "apple"},
{name: "banana"},
{name: "cherries"}
];
var item = ko.utils.arrayFirst(arr, function(el, index){
return el.name === "banana";
})
ko.utils.arrayFirst = function (array, predicate, predicateOwner) {
for (var i = 0, j = array.length; i < j; i++)
if (predicate.call(predicateOwner, array[i], i))
return array[i];
return null;
}
```
```
var arr = [1, 2, 3];
ko.utils.arrayPushAll(arr, [4, 5]);
ko.utils.arrayPushAll = function (array, valuesToPush) {
if (valuesToPush instanceof Array)
array.push.apply(array, valuesToPush);
else
for (var i = 0, j = valuesToPush.length; i < j; i++)
array.push(valuesToPush[i]);
return array;
}
```
```
ko.utils.addOrRemoveItem(array, value, included)
included为true,则array中含有value不处理,没有则添加; included为false,则array中含有value删除,没有则不处理。
addOrRemoveItem: function(array, value, included) {
var existingEntryIndex = ko.utils.arrayIndexOf(ko.utils.peekObservable(array), value);
if (existingEntryIndex < 0) {
if (included)
array.push(value);
} else {
if (!included)
array.splice(existingEntryIndex, 1);
}
}
```
<file_sep>/linux/softs/dmidecode.md
dmidecode:
linux 查看 内存条具体信息, 几根内存条 命令
```
sudo dmidecode | grep -A19 "Memory Device$"
```
```
Total Width:
Data Width:
Size:
Locator
Bank Locator:
Type: DDR4/DDR3
Speed:
```
<file_sep>/linux/ad/linux_ad_domain.md
```
列举
realm list
realm leave xxxx.com
realm join -U Administrator xxxx.com
```
<file_sep>/windows/system/sethostname.md
```
@echo off
:: 修改计算机名,win7 可用
echo 修改计算机名
echo.
set /p name=请输您的计算机名:
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\ComputerName\ActiveComputerName" /v ComputerName /t reg_sz /d %name% /f >nul 2>nul
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters" /v "NV Hostname" /t reg_sz /d %name% /f >nul 2>nul
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Tcpip\Parameters" /v Hostname /t reg_sz /d %name% /f >nul 2>nul
echo.
echo 修改计算机名完毕
pause>nul
```
机器名可设置为域名或ip.
计算机属性中修改会校验机器名,部分格式的输入不能通过。
<file_sep>/java/note_spring/1_applicationContext.md
```
spring 容器应用上下文:ApplicationContext 主要的实现类是 ClassPathXmlApplicationContext 和 FileSystemXmlApplicationContext, 前者默认是从类路径加载配置文件,后者默认从文件系统中加载配置文件。
对于 ClassPathXmlApplicationContext 来说,“com.smart.beans.xml” 等同于 “classpath:com.smart.beans.xml”
ApplicationContext 在初始化应用上下文时就实例化所有单实例的 Bean,
2 WebApplicationContext 是专门为 WEB 应用准备的,它允许从web 应用的根目录的路径中加载配置文件完成初始化工作。
从 WebApplicationContext 可以获得 ServletContext 的引用,整个 WEB 应用上下文对象将作为属性放到 ServletContext 容器中,以便于web 应用环境可以访问 spring 应用上下文。
3 WebApplicationContext 初始化,它的初始化方式和 ApplicationContext 初始化方式不同,因为 WebApplicationContext 初始化需要 ServletContext 实例,也就是说必须在拥有 WEB 容器的前提下
才能完成初始化工作。通过 web.xml 文件配置自启动的 Servlet 或定义 web 容器监听器(ServletContextListener),配置任一即可完成启动 Spring web 应用上下文的工作。
spring 提供了 ContextLoaderServlet 和 ContextLoaderListener。二者内部都实现了启动 WebApplicationContext 实例的逻辑,配置二选一即可
```
# Spring中ApplicationContext初始化过程
https://www.jianshu.com/p/a569aae8b722
```
ApplicationContext context = new ClassPathXmlApplicationContext("conf/applicationContext.xml");
public ClassPathXmlApplicationContext(String[] configLocations, boolean refresh, ApplicationContext parent)
throws BeansException {
super(parent);
setConfigLocations(configLocations);
if (refresh) {
refresh();
}
}
public void refresh() throws BeansException, IllegalStateException {
synchronized (this.startupShutdownMonitor) {
// Prepare this context for refreshing.
//准备上下文的刷新,
prepareRefresh();
// Tell the subclass to refresh the internal bean factory.
//得到新的Bean工厂,应用上下文加载bean就是在这里面实现的
ConfigurableListableBeanFactory beanFactory = obtainFreshBeanFactory();
//准备bean工厂用在上下文中
// Prepare the bean factory for use in this context.
prepareBeanFactory(beanFactory);
try {
// Allows post-processing of the bean factory in context subclasses.
//允许子类上下问处理bean工厂
postProcessBeanFactory(beanFactory);
// Invoke factory processors registered as beans in the context.
//请求工厂处理器作为beans注册在上下文
invokeBeanFactoryPostProcessors(beanFactory);
// Register bean processors that intercept bean creation.
//注册bean处理器拦截bean创建
registerBeanPostProcessors(beanFactory);
// Initialize message source for this context.
//初始化上下文中消息源
initMessageSource();
// Initialize event multicaster for this context.
//初始化上下文中事件广播
initApplicationEventMulticaster();
// Initialize other special beans in specific context subclasses.
//初始化其他具体bean
onRefresh();
// Check for listener beans and register them.
//检查监听bean并注册
registerListeners();
// Instantiate all remaining (non-lazy-init) singletons.
//实例化未初始化单例
finishBeanFactoryInitialization(beanFactory);
// Last step: publish corresponding event.
//最后一步发布相应事件
finishRefresh();
}
```
# WebApplicationContext 的初始化:
```
spring分别提供了用于启动WebApplicationContext的Servlet和Web容器监听器:
org.springframework.web.context.ContextLoaderServlet;
org.springframework.web.context.ContextLoaderListener.
```
```
ContextLoaderListener
public void contextInitialized(ServletContextEvent event) {
this.contextLoader = createContextLoader();
this.contextLoader.initWebApplicationContext(event.getServletContext());
}
protected ContextLoader createContextLoader() {
return new ContextLoader();
}
```
<file_sep>/linux/softs/samba/linux_mint.md
# 安装samba
sudo apt-get install samba
# 配置samba
/etc/samba/smb.conf
在最后面加上以下内容
security = share
[share]
comment = share
path = /home/wsd/software(设置成你要共享的文件路径)
available = yes
browsable = yes
public = yes
writable = yes
create mask = 0777
把/home/wsd/software文件修改成777权限(所有操作都可以执行),执行命令:
chmod 777 /home/wsd/software
# windows 挂载
映射网络磁盘: \\ip\share
share 为配置文件中[share]
# 带用户控制
/etc/samba/smb.conf
[myshare1]
comment = myshare1
path = /data
browsable = yes
writable = yes
create mask = 0777
[myshare2]
comment = myshare2
path = /code
browsable = yes
writable = yes
create mask = 0777
cd /etc/samba
touch smbpasswd
smbpasswd -a sambauser
/etc/init.d/smbd restart
smbclient -L \\127.0.0.1 -U sambauser
# 其他
smbpasswd命令的常用方法smbpasswd -a 增加用户(要增加的用户必须以是系统用户)smbpasswd -d 冻结用户,就是这个用户不能在登录了
smbpasswd -e 恢复用户,解冻用户,
可以在使用smbpasswd -n 把用户的密码设置成空. 要在global中写入 null passwords -true
smbpasswd -x 删除用户
```
samba 无密码访问
https://blog.csdn.net/u013814949/article/details/41850979
security = user
map to guest = Bad User
#samba v4.1.1版本不支持share和server,当security设置为 user后需要加一行map to guest = Bad User才能允许无密码访问。
```
linux挂载:
```shell
# mount -t cifs -o username=<smb_user>,password=<<PASSWORD>> //<smb_server>/<smb_label> /<local_mount_path>
# 有时需要指定vers
# mount -t cifs -o username=<smb_user>,password=<<PASSWORD>>,vers=1.0 //<smb_server>/<smb_label> /<local_mount_path>
```
<file_sep>/golang/build.md
参考: https://www.cnblogs.com/GodBug/p/7890311.html
交叉编译不支持 CGO 所以要禁用它
1、Mac下编译Linux, Windows平台的64位可执行程序:
```
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build test.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build test.go
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build test.go
```
2、Linux下编译Mac, Windows平台的64位可执行程序:
```
CGO_ENABLED=0 GOOS=darwin GOARCH=amd64 go build test.go
CGO_ENABLED=0 GOOS=windows GOARCH=amd64 go build test.go
```
3、Windows下编译Mac, Linux平台的64位可执行程序:
```
SET CGO_ENABLED=0SET GOOS=darwin3 SET GOARCH=amd64 go build test.go
SET CGO_ENABLED=0 SET GOOS=linux SET GOARCH=amd64 go build test.go
```
生成单个二进制文件
```
go build -o outputpath/outputfile go_entrance_file.go
需要编译多个命令,指定不同的入口文件,及不同的输出文件。
```
开发中编译:
```
设置环境变量: GOPATH,GOBIN
go install go_source_file.go
```
```
go build 参数说明
https://blog.csdn.net/cyq6239075/article/details/103911098
-ldflags 'flag list'
'-s -w': 压缩编译后的体积
-s: 去掉符号表
-w: 去掉调试信息,不能gdb调试了
go build 包变量替换 (比如指定版本号)
https://www.digitalocean.com/community/tutorials/using-ldflags-to-set-version-information-for-go-applications
```
<file_sep>/linux/common/grep.md
```
忽略目录
grep --exclude-dir=".svn"
```
<file_sep>/linux/other/u盘重命名.md
```
mlabel -i <硬盘设备> ::<标签>
# mlabel -i /dev/sdc1 ::U
```
<file_sep>/python/somelib/celery.md
文档地址: <http://docs.celeryproject.org/en/latest/>
Celery是一个异步任务的调度工具
broker:消息传输的中间件
worker:任务执行的单元 ,支持分布式worker.
<file_sep>/linux/softs/ssh/ssh_client_config.md
```
SSH免密码登陆避免首次需要输入yes
ssh -o stricthostkeychecking=no
/etc/ssh/ssh_config文件中的"# StrictHostKeyChecking ask" 为 "StrictHostKeyChecking no",
sed -i 's/# StrictHostKeyChecking ask/StrictHostKeyChecking no/' /etc/ssh/ssh_config
警告:POSSIBLE BREAK-IN ATTEMPT
sed -i 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/' /etc/ssh/ssh_config
```
<file_sep>/linux/common/file_system.md
```
exfat : exfat-utils
ntfs: ntfs-3g
安卓: gvfs gvfs-mtp
```
<file_sep>/linux/common/fping.md
```
fping 源码编译:
1. 下载源码并解压
2. 进入解压目录
./configure
make
会在src 目录下生成fping 二进制文件。
执行端口扫描时权限错误:can't create socket (must run as root?) : Permission denied
# note: 尝试 sudo setcap cap_net_raw+ep fping 无果
# chown root:root/普通用户 fping
# chmod 6755 fping
# chmod +s fping
fping -i 1 -C 4 -q -g net
-q
安静模式,所谓安静就是中途不输出错误信息,直接在结果中显示,输出结构整齐、高效。
-C
这里的“c”是大“C”,输入每个ip探测的次数。
-i
通过-i参数可以修改发包间隔,默认为25毫秒一个探测报文。
```
<file_sep>/python/base/__init__.md
```
__init__.py 作用
1. 标识该目录是一个python的模块包
2. 简化模块导入操作
3. 配置模块的初始化操作
__all__ 关联了一个模块列表
__all__ = ['subpackage_1', 'subpackage_2']
注: 目录在库的搜索路径下会首先被搜索,这就意味着目录会代替同名的模块被加载
```<file_sep>/linux/devops/sonarqube/2_start.md
bin 目录下按系统信息选择目录执行
```
bin/
├── jsw-license
│ └── LICENSE.txt
├── linux-x86-32
│ ├── lib
│ │ └── libwrapper.so
│ ├── sonar.sh
│ └── wrapper
├── linux-x86-64
│ ├── lib
│ │ └── libwrapper.so
│ ├── SonarQube.pid
│ ├── sonar.sh
│ └── wrapper
├── macosx-universal-64
│ ├── lib
│ │ └── libwrapper.jnilib
│ ├── sonar.sh
│ └── wrapper
├── windows-x86-32
│ ├── InstallNTService.bat
│ ├── lib
│ │ └── wrapper.dll
│ ├── StartNTService.bat
│ ├── StartSonar.bat
│ ├── StopNTService.bat
│ ├── UninstallNTService.bat
│ └── wrapper.exe
└── windows-x86-64
├── InstallNTService.bat
├── lib
│ └── wrapper.dll
├── StartNTService.bat
├── StartSonar.bat
├── StopNTService.bat
├── UninstallNTService.bat
└── wrapper.exe
```
```
sonar.sh start/stop/status
```
<file_sep>/C_or_C++/inline.md
参考:
<https://www.cnblogs.com/ralap7/p/9093480.html>
<https://www.cnblogs.com/baodaren/p/5174496.html>
```
1. 关键字inline 必须与函数定义体放在一起才能使函数成为内联,仅将inline 放在函数声明前面不起任何作用。
2. inline只适合函数体内代码简单的函数数使用,不能包含复杂的结构控制语句例如while、switch,并且内联函数本身不能是直接递归函数(自己内部还调用自己的函数)。
3. 内联是以代码膨胀(复制)为代价,仅仅省去了函数调用的开销,从而提高函数的执行效率。
以下情况不宜使用内联:
(1)如果函数体内的代码比较长,使用内联将导致内存消耗代价较高。
(2)如果函数体内出现循环,那么执行函数体内代码的时间要比函数调用的开销大。
```
```
将内联函数放在头文件里实现是合适的,省却你为每个文件实现一次的麻烦.
而所以声明跟定义要一致,其实是指,如果在每个文件里都实现一次该内联函数的话,那么,最好保证每个定义都是一样的,否则,将会引起未定义的行为,即是说,如果不是每个文件里的定义都一样,那么,编译器展开的是哪一个,那要看具体的编译器而定.所以,最好将内联函数定义放在头文件中.
```
```
现在的CPU上都有cache,紧凑的代码在chache中保存的时间更长,这样cache命中的机会更高。
如果某个A函数未定义为inline,并且被很多其它函数调用,那个这个A函数很大的可能会长期被保存在cahe中,这样CPU对代码的执行速度会提高很 多。如果A函数被定义为了inline函数,代码分散各个调用函数中,这样每次指定都不命中都需要去内存把代码拷贝到cache中,然后执行,造成很大的 抖动。
更深一层的理解,当函数整个函数编译为的汇编代码,函数调用的上下文切换占用了大多的时间的时候,可以考虑把此函数定义为inline函数。
```
```
高频函数,cache命中有利于提高性能。(函数调用存在上下文切换时间)
inline 函数将代码分发到调用的函数,来减少函数调用上下文切换的时间,但同时增加了 把内存代码拷贝到cache 的时间消耗(内存命中降低)。
需要衡量函数调用与函数内联的时间消耗来决定使用哪种。
```
编译器相关:
参考:https://www.jianshu.com/p/9cdea930c818
```
对gcc来说,inline只是建议,具体是否展开,还要看其他因素。比如没有使用相关优化选项,则不会内联。如果使用了相关优化选项,如-finline-functions,-O等,有时gcc也会对那些简单的函数自动内联,即使那些函数并没有定义内联。
```
```
static inline的内联函数,一般情况下不会产生函数本身的代码,而是全部被嵌入在被调用的地方。
如果不加static,则表示该函数有可能会被其他编译单元所调用,所以一定会产生函数本身的代码。
所以加了static,一般可令可执行文件变小。内核里一般见不到只用inline的情况,而都是使用static inline。
另一种说法:
1、首先,inline函数是不能像传统的函数那样放在.c中然后在.h中给出接口在其余文件中调用的,因为inline函数其实是跟宏定义类似,不存在所谓的函数入口。
2、因为第一点,会出现一个问题,就是说如果inline函数在两个不同的文件中出现,也就是说一个.h被两个不同的文件包含,则会出现重名,链接失败所以static inline 的用法就能很好的解决这个问题,
使用static修饰符,函数仅在文件内部可见,不会污染命名空间。
可以理解为一个inline在不同的.C里面生成了不同的实例,而且名字是完全相同的
```
<file_sep>/linux/common/env_exits.md
引用: https://zhidao.baidu.com/question/2122377445683805787.html
```
//变成if判断不存在变量没有输出
if [ $EEE ];then echo aaa; fi
if [ $EEE ];then
echo aaa;
fi
变量unset后: 变量不存在。
```
<file_sep>/docker/filecopy.md
### docker从容器里面拷文件到宿主机或从宿主机拷文件到docker容器里面
参考: <https://blog.csdn.net/niu_hao/article/details/69546208>
```
1、从容器里面拷文件到宿主机?
答:在宿主机里面执行以下命令
docker cp 容器名:要拷贝的文件在容器里面的路径 要拷贝到宿主机的相应路径
示例: 假设容器名为testtomcat,要从容器里面拷贝的文件路为:/usr/local/tomcat/webapps/test/js/test.js,
现在要将test.js从容器里面拷到宿主机的/opt路径下面,那么命令应该怎么写呢?
答案:在宿主机上面执行命令
docker cp testtomcat:/usr/local/tomcat/webapps/test/js/test.js /opt
2、从宿主机拷文件到容器里面
答:在宿主机里面执行如下命令
docker cp 要拷贝的文件路径 容器名:要拷贝到容器里面对应的路径
示例:假设容器名为testtomcat,现在要将宿主机/opt/test.js文件拷贝到容器里面 的/usr/local/tomcat/webapps/test/js路径下面,那么命令该怎么写呢?
答案:在宿主机上面执行如下命令
docker cp /opt/test.js testtomcat:/usr/local/tomcat/webapps/test/js
3、在这里在记录一个问题,怎么看容器名称?
执行命令:docker ps,出现如图所示,其中NAMES就是容器名了。
```
<file_sep>/golang/go_cmd.md
```
go mod vendor
从mod中拷贝到项目的vendor目录下
```
<file_sep>/linux/softs/sunloginclient.md
*************************************************************************
* sunlogin daemon service must be running for sunloginclient to work *
* Type: systemctl start runsunloginclient.service *
*************************************************************************<file_sep>/golang/test.md
```
测试文件命名: 源文件名_test.go
```
```
package 包名
import "testing"
func Test_函数名(t *testing.T) {
}
```
<file_sep>/js/knockout/4_select.md
```html
<select data-bind="options: availableCountries, selectedOptions: chosenCountries" size="5" multiple="true"></select>
```
<file_sep>/golang/env.md
环境变量:
GOROOT: go 安装目录
```
export GOROOT=/data/soft/go
export PATH=$PATH:$GOROOT/bin
```
GOPATH: go项目根路径
GOBIN: go编译输出路径
<file_sep>/linux/linux-kernel/launchtime.md
```
systemd-analyze blame
```
<file_sep>/linux/softs/rinetd.md
renetd: 端口转发
转发配置rinetd.conf:
0.0.0.0 port1 target_host1 targetport1
0.0.0.0 port2 target_host2 targetport2
run: rinetd -c rinetd.conf<file_sep>/js/jquery/plugin.md
```
;(function ($) {
// 插件实现
$.fn.函数名=function(参数列表){
code here .....
}
// 插件载入时执行的代码
// 需要执行的代码, 例如页面载入是需要初始化组件。
code here .....
}(jQuery))
```
<file_sep>/linux/common/hardware_info.md
```
# lshw
# dmidecode
```
```
/proc/cpuinfo
/proc/meminfo
diskstats
```
<file_sep>/python/django_1.11/init_step.md
init step:
```
----------------------------------------
['manage.py', 'runserver']
----------------------------------------
setting
----------------------------------------
['manage.py', 'runserver']
----------------------------------------
settings
urls
Quit the server with CONTROL-C.
wsgi
```
<file_sep>/golang/base/0_basetypes.md
```
bool
string 字符串就是一串固定长度的字符连接起来的字符序列。Go的字符串是由单个字节连接起来的。Go语言的字符串的字节使用UTF-8编码标识Unicode文本。每个字符对应一个rune类型。一旦字符串变量赋值之后,内部的字符就不能修改,英文是一个字节,中文是三个字节。使用range迭代字符串时,需要注意的是range迭代的是Unicode而不是字节。返回的两个值,第一个是被迭代的字符的UTF-8编码的第一个字节在字符串中的索引,第二个值的为对应的字符且类型为rune(实际就是表示unicode值的整形数据)。
uint8 无符号 8位整型 (0 到 255)
uint16 无符号 16位整型 (0 到 65535)
uint32 无符号 32位整型 (0 到 4294967295)
uint64 无符号 64位整型 (0 到 18446744073709551615)
int8 有符号 8位整型 (-128 到 127)
int16 有符号 16位整型 (-32768 到 32767)
int32 有符号 32位整型 (-2147483648 到 2147483647)
int64 有符号 64位整型 (-9223372036854775808 到 9223372036854775807)
float32 IEEE-754 32位浮点型数
float64 IEEE-754 64位浮点型数
byte 类似 uint8
rune 类似 int32
uint32 或 64 位
int 与 uint 一样大小
uintptr 无符号整型,用于存放一个指针
complex64 32位实数和虚数
complex128 64位实数和虚数
复数使用 re+imi 来表示,其中 re 代表实数部分,im 代表虚数部分,i 为虚数单位。
eg:
var vc complex64 = 1 + 2i
c = complex(re, im)
函数 real(c) 和 imag(c) 可以分别获得相应的实数和虚数部分。
派生类型:
(a) 指针类型(Pointer)
(b) 数组类型
(c) 结构类型(struct)
(d) Channel 类型
(e) 函数类型
(f) 切片类型
(g) 接口类型(interface)
(h) Map 类型
```
<file_sep>/python/Singleton.md
单例:
1. 装饰器
```
def singleton(cls):
instances = {}
def wrapper(*args, **kwargs):
if cls not in instances:
instances[cls] = cls(*args, **kwargs)
return instances[cls]
return wrapper
@singleton
class Foo(object):
pass
@singleton
class Foo(object):
pass
foo1 = Foo()
#等同于
class Foo(object):
pass
foo1 = singleton(Foo)
```
2. 重写 __new__
```
class Singleton(object):
def __new__(cls, *args, **kwargs):
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton,
cls).__new__(cls, *args, **kwargs)
return cls._instance
class Foo(Singleton):
pass
```
3. __metaclass__
```
class Singleton(type):
def __call__(cls, *args, **kwargs):
print 'call Singleton __call__'
if not hasattr(cls, '_instance'):
cls._instance = super(Singleton,
cls).__call__(*args, **kwargs)
return cls._instance
class Foo(object):
__metaclass__ = Singleton
```
4. 模块
单例对象在模块的 __init__.py 中 ,引入模块时,引入该单例对象
5. 在类方法生成单例
```
import time
import threading
class Singleton(object):
_instance_lock = threading.Lock()
def __init__(self):
time.sleep(1)
@classmethod
def instance(cls, *args, **kwargs):
with Singleton._instance_lock:
if not hasattr(Singleton, "_instance"):
Singleton._instance = Singleton(*args, **kwargs)
return Singleton._instance
def task(arg):
obj = Singleton.instance()
print(obj)
for i in range(10):
t = threading.Thread(target=task,args=[i,])
t.start()
```
<file_sep>/linux/common/lvm.md
参考:
<https://blog.csdn.net/ikikik2002/article/details/5187276>
<https://www.linuxidc.com/Linux/2018-06/152992.htm>
```bash
安装lvm 工具
为了使用LVM,要确保在系统启动时激活LVM,在RedHa的版本中,系统启动脚本已具有对激活LVM的支持,在/etc/rc.d/rc.sysinit中有以下内容:
if [ -x /sbin/lvm.static ]; then
action $"Setting up Logical Volume Management:" /sbin/lvm.static vgchange -a y --ignorelockingfailure
fi
vgchange -a y命令激活系统所有卷组。
------------------------------------------------------------------------------------------
/boot分区用于存放引导文件,不能应用LVM机制 (/boot/efi,/boot : centos 默认都是不使用lvm 的)
------------------------------------------------------------------------------------------
物理卷 (PV, Physical Volume) : 整个硬盘,或使用fdisk等工具建立的普通分区
fdisk 分区类型设置为“8e”
创建:
pvcreate 设备名
# pvcreate /dev/sdb
# pvcreate /dev/sdc1
# pvcreate /dev/sdb /dev/sdc1
[设备名对应物理卷名: 与卷组创建命令相关]
查看:
# lvmdiskscan (包含 LVM physical volume 的分区)
# pvs ,pvscan ,pvdisplay
移除:
pvremove /dev/sdb
卷组(VG, Volume Group):一个或多个物理卷组合而成的整体
vgcreate 卷组名 物理卷名1 物理卷名2
# vgcreate mail_store /dev/sdb /dev/sdc1
vgremove
vgexted
逻辑卷(LV, Logical Volume) : 从卷组中分割出的一块空间,用于建立文件系统
lvcreate -L 大小 -n 逻辑卷名 卷组名
lvremove
扩展:
lvextend -L +大小 /dev/卷组名/逻辑卷名
扩容步骤:调整逻辑卷大小→调整文件系统大小
# lvextend -L +10G /dev/mail_store/mail #调整逻辑卷大小
# e2fsck -f /dev/mail_store/mail -y #检查逻辑卷
# resize2fs /dev/mail_store/mail
缩容步骤:调整文件系统大小→调整逻辑卷大小
# lvextend -l +100%free /dev/mail_store/mail
# resize2fs -p /dev/mail_store/mail 10G //-p打印进度,将mail缩小至10G
# lvreduce -L 10G /dev/mail_store/mail //将逻辑卷缩小至10G
格式化: 与普通硬盘分区格式化一致 : mkfs
挂载: mount (开机挂载写入 /etc/fstab)
------------------------------------------------------------------------------------------
/etc/fstab
# <file system> <mount point> <type> <options> <dump> <pass>
uuid=[blkid 获取块设备id] 文件系统类型 文件类型 <options> <dump> <pass>
物理卷名 挂载点 文件系统类型 <options> <dump> <pass>
文件系统类型:
Linux可以使用ext2、ext3等类型,此字段须与分区格式化时使用的类型相同。
也可以使用 auto 这一特殊的语法,使系统自动侦测目标分区的分区类型。auto通常用于可移动设备的挂载。
options:
auto: 系统自动挂载,fstab默认就是这个选项
defaults: rw, suid, dev, exec, auto, nouser, and async.
noauto 开机不自动挂载
nouser 只有超级用户可以挂载
ro 按只读权限挂载
rw 按可读可写权限挂载
user 任何用户都可以挂载
请注意光驱和软驱只有在装有介质时才可以进行挂载,因此它是noauto
dump备份设置:
当其值设置为1时,将允许dump备份程序备份;设置为0时,忽略备份操作;
fsck磁盘检查设置
其值是一个顺序。当其值为0时,永远不检查;
而 / 根目录分区永远都为1。其它分区从2开始,数字越小越先检查
如果两个分区的数字相同,则同时检查。
------------------------------------------------------------------------------------------
```
| 功能 | 物理卷管理 | 卷组管理 | 逻辑卷管理 |
| ---- | ---------- | --------- | ---------- |
| 扫描 | pvscan | vgscan | lvscan |
| 创建 | pvcreate | vgcreate | lvcreate |
| 显示 | pvdisplay | vgdisplay | lvdisplay |
| 删除 | pvremove | vgremove | lvremove |
| 扩展 | | vgextend | lvextend |
```
使用lvm技术可以扩大根分区,不破坏分区表。
1:首先新加一块磁盘,连接至主机。开机,进入系统。使用root登录,运行fdisk,将新加的磁盘分区。我们这里假设将全部磁盘容量只分一个区,分区 为/dev/sdb1;
2:创建pv: pvcreate /dev/sdb1
3:扩展VG:vgextend /dev/VolGroup00 /dev/sdb1
4:运行vgdisplay ,查看扩展后的VG,如果显示容量增加,表示,VG扩展成功;
5:扩展LV: lvextend -L + n(M,或G) /dev/VolGroup00/LogVol00 /dev/VolGroup00
重新启动机器,进入Resuce 模式,装载磁盘时选择skipp。
6:激活VG: 运行 lvm vgchange -a y /dev/VolGgroup00
7:调整文件系统大小: 首先运行 e2fsck 检查文件系统。 e2fsck /dev/VolGroup00/LogVol00
8:resize2fs /dev/VolGroup00/LogVol00
```
```
partprobe 创建磁盘分区时,找不到分区设备文件。
```
<file_sep>/sql/postgresql/unlogged.md
```
PostgreSQL有一种介于正常表和临时表之间的类型表,称之为unlogged表,在该表新建的索引也属于unlogged,该表在写入数据时候并不将数据写入到持久的write-ahead log文件中,在数据库异常关机或者异常崩溃后该表的数据会被truncate掉
```
开启sql 执行时间显示
```
# \timing
Timing is on.
```
将所有unlogged表修改为正常的表。
```sql
select 'ALTER TABLE'||' '||concat(n.nspname,'.' ,c.relname)||' '||'SET LOGGED ;' AS convert_logged_sql from pg_catalog.pg_namespace n, pg_catalog.pg_class c where c.relnamespace=n.oid and n.nspname != 'pg_toast' and c.relkind='r' and c.relpersistence = 'u';
```
<file_sep>/js/webpack/san.md
https://www.jianshu.com/p/efc955b2b38b
https://www.bookstack.cn/read/san-zh/README.md
```
cnpm install san san-loader san-router --save
cnpm i --save san-xui
```
```
loader:
{
test: /\.san$/,
loader: "san-loader"
},
```
<file_sep>/js/prototype.md
```
对js原生对象的扩展:往prototype里注册
```
<file_sep>/java/note_spring/Fileter_Interceptor_Aop.md
# 过滤器、拦截器、AOP切面执行顺序
参考 :
https://blog.csdn.net/w1219401160/article/details/81101641
https://blog.csdn.net/dreamwbt/article/details/82658842
```
过滤器:基于 Servlet,通过函数回调方式实现,可以过滤请求和图片文件等,每个请求一个过滤器只能过滤一次,
拦截器:基于 java 的反射机制,代理模式实现,只能拦截请求,可以访问上下文等对象,功能强大,一个请求可多次拦截。
拦截器是 Spring 中AOP的一种实现方法。另一种方法通过 Pointcut、Advice实现
filter->interceptor->aop
一般情况下数据被过滤的时机越早对服务的性能影响越小,因此我们在编写相对比较公用的代码时,优先考虑过滤器,然后是拦截器,最后是aop。
```
# listener、filter、interceptor作用和区别
```
监听器(listener):就是对项目起到监听的作用,它能感知到包括request(请求域),session(会话域)和applicaiton(应用程序)的初始化和属性的变化;
过滤器(filter):就是对请求起到过滤的作用,它在监听器之后,作用在servlet之前,对请求进行过滤
拦截器(interceptor):就是对请求和返回进行拦截,它作用在servlet的内部
把整个项目的流程比作一条河,那么监听器的作用就是能够听到河流里的所有声音,过滤器就是能够过滤出其中的鱼,而拦截器则是拦截其中的部分鱼,并且作标记。所以当需要监听到项目中的一些信息,并且不需要对流程做更改时,用监听器;当需要过滤掉其中的部分信息,只留一部分时,就用过滤器;当需要对其流程进行更改,做相关的记录时用拦截器。(引用: https://blog.csdn.net/jiushancunMonkeyKing/article/details/81222856)
```
常用的监听接口
- HttpSessionListener:监听HttpSession的操作,监听session的创建和销毁
- ServletRequestListener:监听request的创建和销毁
- ServletContextListener:监听context的创建和销毁
filter 中使用bean:
参考: https://cloud.tencent.com/developer/article/1497823
```
过滤器是servlet规范中定义的,并不归Spring容器管理,也无法直接注入spring中的Bean
```
```
1. 在Filter初始化方法里手动去容器里吧Bean拿出来即可
2. DelegatingFilterProxy类存在与spring-web包中,其作用就是一个filter的代理,用这个类的好处是可以通过spring容器来管理filter的生命周期(比如shiro里面的Filter用到了它)。这样如果filter中需要一些Spring容器的实例,可以通过spring直接注入
默认情况下, Spring 会到 IOC 容器中查找和 <filter-name> 对应的 filter bean. 也可以通过 targetBeanName 的初始化参数来配置 filter bean 的 id(建议指定)
DelegatingFilterProxy类继承GenericFilterBean,间接实现了Filter这个接口,故而该类属于一个过滤器。
```
<file_sep>/java/spring-mvc/other.md
```
redis session 配置
org.springframework.session.data.redis.config.annotation.web.http.RedisHttpSessionConfiguration
```
<file_sep>/linux/desktop-evn/kde/disable_wallet.md
```
禁用KDE wallet
(需先安装kwalletmanager)
alt+f2(也就是开krunner)
输入wallet,选system setting: kde wallet(不是kwalletmanager )
去掉enable the kde wallet subsystem前面的勾
* 未生效,重启后应该就没有wallet 的弹窗了。
```
<file_sep>/docker/apps/superset.md
```
-----------------------------------
获取镜像:
-----------------------------------
启动:
docker run -d -p 8088:8088 -v /opt/docker/superset:/home/superset amancevice/superset
docker ps
docker exec -it def43799758d fabmanager --help
docker exec -it def43799758d fabmanager list-users --app superset
ls /opt/docker/superset/
# 创建管理员
docker exec -it def43799758d fabmanager create-admin --app superset
docker exec -it def43799758d fabmanager list-users --app superset
# 更新数据库
docker exec -it def43799758d superset db upgrade
# 初始化权限
docker exec -it def43799758d superset init
#载入示例数据
docker exec -it def43799758d superset load_examples
```
<file_sep>/sql/postgresql/solutions/could_not_read_block.md
<https://blog.csdn.net/duanbiren123/article/details/85955789>
原因: 索引丢失 (成因未知)
解决办法: 重建索引
```
ALTER TABLE <table_name> DROP CONSTRAINT <index_name>;
ALTER TABLE <table_name> ADD CONSTRAINT <index_name> primary key (filed1, field2);
```
```
```
<file_sep>/sql/postgresql/between.md
```
BETWEEN 用以查询确定范围的值,这些值可以是数字,文本或日期 。
BETWEEN 运算符是闭区间的:包括开始 和 结束值 。
postgres,mysql 中between 包含边界。
not between : between取反
```
<file_sep>/python/base/some_functions.md
zip():
```
zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
zip([iterable, ...])
#!/usr/bin/env python
# -*- coding: utf-8 -*-
if __name__ == "__main__":
# zip() 参数为多个数组
a = [1, 2, 3]
b = [4, 5, 6]
c = [4, 5, 6, 7, 8]
zipped = zip(a, b) # 打包为元组的列表
print zipped
# [(1, 4), (2, 5), (3, 6)]
zipped2 = zip(a, c) # 元素个数与最短的列表一致
print zipped2
# [(1, 4), (2, 5), (3, 6)]
print zip(*zipped) # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
# [(1, 2, 3), (4, 5, 6)]
print zip(zipped)
# [((1, 4),), ((2, 5),), ((3, 6),)]
print zip(zipped, [11, 22, 33])
#[((1, 4), 11), ((2, 5), 22), ((3, 6), 33)]
pass
```
namedtuple: (元组的升级版本 -- namedtuple(具名元组))
```
import collections
# 两种方法来给 namedtuple 定义方法名
#User = collections.namedtuple('User', ['name', 'age', 'id'])
User = collections.namedtuple('User', 'name age id')
user = User('tester', '22', '464643123') # *var_array 数组依次填值
print(user)
# output:
# User(name='tester', age='22', id='464643123')
data=['tester', '22', '464643123']
user = User(*data)
```
sum: (数组求和)
```
二维数组求和:
[sum(x) for x in var_array] # 得到数组[sum1,sum2,....]
```
map():
Python 2.x 返回列表。
Python 3.x 返回迭代器。
```
>>>def square(x) : # 计算平方数
... return x ** 2
...
>>> map(square, [1,2,3,4,5]) # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5]) # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]
将多个列表相同位置的元素归并到一个元组(与zip 类似)
# python2
>>> print map(None, [2,4,6],[3,2,1]) # 但是在 python3中,返回是一个迭代器,所以它其实是不可调用的
# [(2, 3), (4, 2), (6, 1)]
# python2
print(list(map(None, [2,4,6],[3,2,1])))
```
zip,实现把两个list组合成一个dict
格式为: dict(zip(keys,vals))<file_sep>/python/pip/install_pip.md
pip 重装:
```
在DOS命令框输入命令:
python3 -m pip install --upgrade pip --force-reinstall,会显示安装成功。
在DOS命令框输入命令:
python2 -m pip install --upgrade pip --force-reinstall,会显示安装成功。
```
<file_sep>/sql/redis/redis2.md
配置:
用户认证:
AUTH <password>
查询key:
keys *
key 类型:
type keyname<file_sep>/js/knockout/3_subscribe.md
```js
ViewModel.testattr.subscribe(function(newValue) {
alert("The value is " + newValue);
});
var subscription = ViewModel.testattr.subscribe(function(newValue) {
// 此次使用this, 拿不到ViewModel
/* do stuff */
});
// ...then later...
subscription.dispose();
// I no longer want notifications
```
<file_sep>/linux/common/vncserver.md
rpm -qa |grep vnc
yum install tigervnc-server -y
chkconfig vncserver on
vim /etc/sysconfig/vncservers
按模板编辑如下内容
VNCSERVERS="" #配置显示号和用户
VNCSERVERARGS[]="" #配置显示号相关配置
切换用户后执行: vncpasswd
service vncserver restart
<file_sep>/python/base/type.md
```
from types import MethodType
def set_age(self,age):
self.age=age
class Stu(object):
pass
Stu.set_age=MethodType(set_age,Stu)
```
<file_sep>/java/java_common/AtomicReference.md
参考:
<https://segmentfault.com/a/1190000015831791?utm_source=tag-newest>
<file_sep>/golang/Package.md
```
引入包顺序:
import 包
检查引用的包是否还引用了其他包
继续引入其他包
初始化包级常量和变量进行
执行 init() 函数
初始化包级常量和变量进行
执行 init() 函数
初始化包级常量和变量进行
执行 init() 函数
初始化包级常量和变量进行
mian包init()
main()
```
引入包顺序:
(图片引用:https://blog.csdn.net/rznice/article/details/18987047)

<file_sep>/bigdata/superset/install.md
<https://blog.csdn.net/dzjun/article/details/62421718>
```
(1)安装Superset
pip install superset
(配置数据库,创建数据库,数据库用户)
(2)创建管理员用户名和密码
fabmanager create-admin --app superset
(3)初始化Superset
superset db upgrade
(4)装载初始化样例数据
superset load_examples
(5)创建默认角色和权限
superset init
(6)启动Superset
superset runserver
默认端口:8088
```
```
python 3.7 + supserset 0.28.1
# Install superset
pip install superset
# Initialize the database
superset db upgrade
# Create an admin user (you will be prompted to set a username, first and last name before setting a password)
$ export FLASK_APP=superset
flask fab create-admin
# Load some data to play with
superset load_examples
# Create default roles and permissions
superset init
# To start a development web server on port 8088, use -p to bind to another port
superset run -p 8080 --with-threads --reload --debugger
---------------------------------------------------------------------------------
cannot import name '_maybe_box_datetimelike' from 'pandas.core.common'
pip install pandas==0.23.4
pip install flask==1.0
sqlalchemy.exc.InvalidRequestError: Can't determine which FROM clause to join from,
pip install SQLAlchemy==1.2.18
```
<file_sep>/js/knockout/2_pureComputed.md
```js
this.firstName = ko.observable('Planet');
this.lastName = ko.observable('Earth');
this.fullName = ko.pureComputed({
read: function () {
return this.firstName() + " " + this.lastName();
},
write: function (value) {
var lastSpacePos = value.lastIndexOf(" ");
if (lastSpacePos > 0) { // Ignore values with no space character
this.firstName(value.substring(0, lastSpacePos)); // Update "firstName"
this.lastName(value.substring(lastSpacePos + 1)); // Update "lastName"
}
},
owner: this
});
```
```html
<div>First name: <span data-bind="text: firstName"></span></div>
<div>Last name: <span data-bind="text: lastName"></span></div>
<div class="heading">Hello, <input data-bind="textInput: fullName"/></div>
```
<file_sep>/sql/postgresql/solutions/invalid_page_header_in_block.md
参考:
```
https://lxadm.com/PostgreSQL:_ERROR:_invalid_page_header_in_block_13760_of_relation_base/16995/67484
```
```
# SET zero_damaged_pages = on;
# VACUUM FULL <damaged_table>;
# reindex table <damaged_table>;
```
单个分区表受损也可能导致主表查询报错: 此时需要对分区表进行处理。
index "xxxxxxx" contains unexpected zero page at block , "Please REINDEX it."
https://www.cnblogs.com/yhq1314/p/13073266.html
```
reindex index <schema_name>.<index_name>;
reindex index <index_name>;
```<file_sep>/linux/softs/samba/ads.md
```
https://www.server-world.info/en/note?os=CentOS_7&p=samba&f=3
centos:
yum -y install samba-winbind samba-winbind-clients pam_krb5
/usr/bin/net join -w 域名 -S ad.域名.com -U Administrator
```
<file_sep>/js/js_for_browser_version.md
各框架浏览器兼容性:
```
React v15 不再支持ie8. 需要支持ie8:使用 React v0.14 ,或更早的版本。
```
<file_sep>/linux/common/rsync.md
```
将data 目录同步到/bak 目录下: /bak/data
rsync -av --exclude data/a --exclude data/b --exclude data/c data /bak
```
```
同步目录下的内容到目标目录
rsync -av data/ /bak
```
<file_sep>/linux/common/sudo.md
```
sudo 中使用alias 别名:
在 ~/.bashrc 中加: alias sudo='sudo '
```
```
sudo 执行是环境变量丢失:
sudo -E
```
<file_sep>/sql/postgresql/db_and_user.md
```sql
--创建用户
CREATE USER user_name WITH PASSWORD '<PASSWORD>';
--创建数据库并指定用户
CREATE DATABASE dbname OWNER user_name ENCODING 'UTF8';
--查看数据库列表
\l
```
<file_sep>/linux/softs/fcitx/rime.md
中州韵输入法
```
fcitx-rime
```
配置 (参考:<https://gist.github.com/lotem/2981316>)
~/.config/fcitx/rime/default.custom.yaml
```
patch:
"menu/page_size": 9
ascii_composer/good_old_caps_lock: true
ascii_composer/switch_key:
Caps_Lock: noop
Shift_L: commit_code
```
```
# inline_ascii 在輸入法的臨時西文編輯區內輸入字母、數字、符號、空格等,回車上屏後自動復位到中文
# commit_text 已輸入的候選文字上屏並切換至西文輸入模式
# commit_code 已輸入的編碼字符上屏並切換至西文輸入模式
# 設爲 noop,屏蔽該切換鍵
~/.config/fcitx/rime/build 下有各schema对应的默认配置
```
<file_sep>/windows/wmi.md
WMI(Windows Management Instrumentation,Windows 管理规范)
<file_sep>/js/node/electron.md
### start
<https://electronjs.org/docs/tutorial/first-app>
electron 不可用:
```
sudo chown root: xxxxx/node_modules/electron/dist/chrome-sandbox
sudo chmod 4755 xxxxxxx/lib/node_modules/electron/dist/chrome-sandbox
```
### package
```
cnpm install -g electron-prebuilt
cnpm install -g electron-packager
electron-packager <应用目录> <应用名称> <打包平台> --out <输出目录> <架构> <应用版本>
electron-packager . HelloWorld --linux -out ../out --arch=x64 --app-version=0.0.1 --electron-version=5.0.1
electron-packager ./ --electron-version=5.0.1
```
打包的文件不能执行
```
sudo chown root chrome-sandbox
chmod 4755 chrome-sandbox
```
<file_sep>/linux/softs/snmp/snmpsimd.md
Valid tag values and their corresponding ASN.1/SNMP types are:
2 - Integer32
4 - OCTET STRING
5 - NULL
6 - OBJECT IDENTIFIER
64 - IpAddress
65 - Counter32
66 - Gauge32
67 - TimeTicks
68 - Opaque
70 - Counter64
run agent:
snmpsimd.py --data-dir=./data --agent-udpv4-endpoint=127.0.0.1:1024
snmpwalk
snmpwalk -v2c -c public 127.0.0.1:1024 system
<file_sep>/js/vue/start_0.md
```html
<!--import js-->
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<div id="app">
{{message}}
</div>
<script>
var vm = new Vue({
el:'#app',
data:{
message:"vue demo"
}
});
</script>
```
```html
<!-- 数据属性 -->
<script>
var data={
message:"vue demo",
a:1
}
var vm = new Vue({
el:'#app',
data:data
});
//只有当实例被创建时就已经存在于 data 中的属性才是响应式的
// 新加的属性不会与视图绑定。
// 使用 Object.freeze(),这会阻止修改现有的属性,也意味着响应系统无法再追踪变化 : Object.freeze(data) 与data绑定的视图在data变化时不会更新。
vm.a == data.a // => true ,一个修改另一个也变化
</script>
```
```html
<!-- 实例属性 -->
<script>
var data={
message:"vue demo",
a:1
}
var vm = new Vue({
el:'#app',
data:data
});
vm.$data === data // => true
// Vue 实例还暴露了一些有用的实例属性与方法。它们都有前缀 $,以便与用户定义的属性区分开来。
// https://cn.vuejs.org/v2/api/#%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7
</script>
```
```html
<!-- 生命周期 -->
<!-- 不要在选项属性或回调上使用箭头函数 -->
<!-- https://cn.vuejs.org/v2/api/#%E9%80%89%E9%A1%B9-%E7%94%9F%E5%91%BD%E5%91%A8%E6%9C%9F%E9%92%A9%E5%AD%90 -->
<script>
var data={
message:"vue demo",
a:1
}
var vm = new Vue({
el:'#app',
data:data,
beforeCreate:function(){
// 在实例初始化之后,数据观测(data ovserver)和 event/watcher 事件配置之前被调用。
},
created:function(){
// 实例创建之后被立即调用
// 在这一步,实例完成:数据观测(data ovserver),属性和方法的运算,event/watcher 事件回调。
// 此时关在阶段还未开始,$el 属性目前不可见
},
beforeMount:function(){
// 挂载之前被调用,相关的渲染函数首次被调用。
},
mounted:function(){
// el 被新创建的vm.$el 替换,挂载完成。
},
beforeUpdate:function(){
// 数据更新时调用
},
updated:function(){
// 组件dom 更新完毕。
},
activated:function(){},
deactivated:function(){},
beforeDestroy:function(){},
destroyed:function(){},
errorCaptured:function(){}
});
</script>
```
<file_sep>/python/somelib/mysql.md
```
在python3中使用pip 安装MySQL-python时遇到
ImportError: No module named 'ConfigParser'错误,
原因是MySQL-python不支持python3版本.
可以使用mysqlclient软件包作为MySQL-python的代替,它是MySQL-python支持Python 3 的分支。
```
<file_sep>/RevisionControl/svn/svn.md
# server
```
0.验证是否有svnserver (svnserve --version)
1.安装svnserver
2.验证是否安装成功 (svnserve --version)
3.进入到svn的资源目录 (cd /home/svndir)
4.创建svn资源库 (svnadmin create <repositories_name>: 建立repositories库)
5.新增用户 (passwd)
6.配置用户权限 (authz)
7.配置资源库权限 (svnserver.conf)
8.启动或者重启 ( svnserve -d -r svn资源库目录)
9.测试
```
```
检测svn服务是否正常启动,
第一通过进程检测
ps -ef | grep svn
第二通过端口3690检测
netstat -lntup | grep 3690
第三通过文件检测,需要root用户才可以执行
lsof -i :3690
使用svnadmin建立svn项目版本库
创建sadoc版本库
svnadmin create </xx/repositorie_full_path>
在当前目录下创建svn仓库(按repositories_name创建目录)
svnadmin create <repositorie_name>
多个项目可以创建多个目录
repositories
--repositorie
--repositorie2
--repositorie3
启动是使用repositories目录
配置repositorie,repositorie/conf 目录下为配置文件
svnserve.conf
passwd (svnserve.conf 指定路径)
authz (svnserve.conf 指定路径)
svnserve.conf 进行详细配置
#--------------------------------------
anon-access = none //禁止匿名访问
auth-access = write //认证后有读的权限
password-db = /xxx/passwd //指定密码文件
authz-db = /xxx/authz //指定权限认证文件
#--------------------------------------
passwd,authz 多个repositorie可以共用,
为Svn版本库创建用户并授权访问指定项目版本库
编辑passwd文件配置用户和密码
vi passwd
username = password
编辑authz文件配置读取权限
[<版本库>:/项目/目录]
@<用户组名> = <权限>
<用户名> = <权限>
重新启动svn服务进行验证
杀死svn服务
pkill svnserve
启动svn
svnserve -d -r /xxx/repositories
备注:修改passwd和authz文件不需要重启svn服务而修改svnserve.conf则需要
svn co 获取代码
配置passwd,authz,svnserve.conf注意前面不能有空格!
```
参考:
http://www.linuxidc.com/Linux/2017-05/144254.htm
https://www.cnblogs.com/javayu/p/6165312.html
多仓库配置参考:
https://blog.csdn.net/jctian000/article/details/80623621 (推荐)
-----------------------------------------------
默认的资源库是空的
创建主要目录
```bash
mkdir branches
mkdir tags
mkdir trunk
svn add branches trunk tags
svn ci -m 'create branches trunk tags dir'
```
创建branches:
```bash
svn copy svn://xxxx/<project>/trunk svn://xxxx/<project>/branches/<branch_name> -m "commit info"
```
切换分支:
```bash
svn sw svn_branch_url
```
合并代码(merge):
```bash
将svn_branch_url 分支的代码合并到当前分支
svn merge svn_branch_url
svn diff
svn commit -m "merge info"
将svn_branch_url 分支的代码 合并指定版本的代码到当前分支
svn diff -r v1:v2 svn-branch-url 查看需要的合并的分支的修改
svn merge -r version1:version2 svn_branch_url
svn diff 查看合并了哪些内容
svn commit -m "merge info"
svn merge可以将两个对象的diff体现到本地工作目录上。
两个对象: 这个两个对象可以是同一个svn url的两个revison,也可以是不用的url,比如分支和主干。
diff: diff可以是新增的内容,那么就是将一个对象的内容合并到另外一个对象上去。如果diff是减少的内容,那么就是将一个对象的内容回滚掉。
```
撤销修改
```bash
修改未提交
svn revert [R] . 撤销当前目录下的修改
修改已提交:
svn merge
svn log 找到需要回滚的版本
查看差异: svn diff -r 20:10 [xxx_file_dir]
回滚: svn merge -r 20:10 xxx_file_dir (同时可用于升级版本合并代码)
提交回滚: svn commit
```
diff
```bash
svn diff -r v1:v2 只能看到当前分支相关的diff
svn diff -r v1:v2 svn-branch-url : 查看指定分支的diff
svn diff branche1 branche2 : 查看两个分支的diff
svn diff 目录 branche2 : 查看当前分支与指定分支的差异(二者目录一致)
```
-----------------------------------------------
撤销add
```
svn revert --depth infinity . 撤销当前目录下add 的所有文件
```
# client
https://www.cnblogs.com/likwo/archive/2010/09/08/1821232.html
```bash
svn revert --recursive folder: 取消add
svn add . --no-ignore --force :递归目录下所有文件
```
日常问题:
```bash
svn错误:a peg revision is not allowed here解决方法
原因说明:需要提交的文件的文件名包含“@”
解决方法:在文件名后加@,并且在中间的@前加\
```<file_sep>/java/单点登陆/shiro/0.md
```xml
<!--shiro 配置-->
<filter>
<filter-name>shiroFilter</filter-name>
<!--从beans 找id 为 shiroFilter 的bean-->
<!--filter 可访问spring bean-->
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
<init-param>
<param-name>targetFilterLifecycle</param-name>
<param-value>true</param-value>
</init-param>
</filter>
```
shiro.xml 在spring 中引入
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<!--配置 session 管理-->
<property name="sessionManager" ref="sessionManager"></property>
<!--配置 记住我-->
<property name="rememberMeManager" ref="rememberMeManager"></property>
<!-- 配置多个Realm的登录认证 -->
<property name="authenticator" ref="authenticator"></property>
<!-- 配置多个Realm的权限认证 -->
<property name="authorizer" ref="authorizer"></property>
</bean>
<!--配置多个 realm 的权限权限认证(授权,赋予角色和权限)-->
<bean id="authorizer" class="org.apache.shiro.authz.ModularRealmAuthorizer">
<property name="realms">
<list>
<!--这个实现权限匹配的方法-->
<ref bean="myRealm"/>
<!--这个没有实现-->
<!--<ref bean="otherRealm"/>-->
</list>
</property>
</bean>
<!-- 配置多个Realm (认证)-->
<bean id="authenticator" class="org.apache.shiro.authc.pam.ModularRealmAuthenticator">
<!--验证的时候,是用迭代器,所以可以认为验证的顺序就是这个 list 的顺序-->
<property name="realms">
<list>
<ref bean="otherRealm"/>
<ref bean="myRealm"/>
</list>
</property>
<property name="authenticationStrategy">
<!--所有 realm 认证通过才算登录成功-->
<!--<bean id="authenticationStrategy" class="org.apache.shiro.authc.pam.AllSuccessfulStrategy"/>-->
<!--验证某个 realm 成功后直接返回,不会验证后面的 realm 了-->
<!--<bean id="authenticationStrategy" class="org.apache.shiro.authc.pam.FirstSuccessfulStrategy"/>-->
<!--所有的 realm 都会验证,其中一个成功,也会继续验证后面的 realm,最后返回成功-->
<bean id="authenticationStrategy" class="org.apache.shiro.authc.pam.AtLeastOneSuccessfulStrategy"/>
</property>
</bean>
<!--自定义 MyRealm,登录的认证入口 ,需要继承AuthorizingRealm,项目中会体现-->
<bean id="myRealm" class="com.xxx.shiro.MyRealm">
<!-- 配置密码匹配器(密码校验器,可自定义校验器重写加密算法) -->
<property name="credentialsMatcher">
<bean class="org.apache.shiro.authc.credential.HashedCredentialsMatcher">
<!-- 加密算法为SHA-256 -->
<property name="hashAlgorithmName" value="SHA-256"></property>
<!-- 加密迭代次数 -->
<property name="hashIterations" value="1024"></property>
<!--是否存储散列后的密码为16进制,为 true:.toHex(),为 false:.toBase64()-->
<property name="storedCredentialsHexEncoded" value="false"></property>
</bean>
</property>
</bean>
<!--自定义的第二个 realm-->
<bean id="otherRealm" class="com.xxx.shiro.OtherRealm"></bean>
<!--rememberMeManager管理 配置-->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<property name="cookie">
<bean class="org.apache.shiro.web.servlet.SimpleCookie">
<!--设置超时时间 单位 秒,一天=86400-->
<constructor-arg value="shiro-cookie"></constructor-arg>
<property name="maxAge" value="86400"></property>
<property name="httpOnly" value="true"></property>
</bean>
</property>
</bean>
<!--session管理 配置-->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!--session 过期时间 单位 毫秒,2400000=40min-->
<property name="globalSessionTimeout" value="2400000"></property>
<!--有需要可以自行配置-->
<!--<property name="cacheManager" ref="xxxx"></property>-->
<!--有需要可以自行配置-->
<!--<property name="sessionDAO" ref="xxx"></property>-->
</bean>
<!--shiro 请求拦截器,这里的 bean id 一定要对应 web.xml 中的filter-name,否则找不到这个拦截器-->
<!-- 集成ShiroFilterFactoryBean,并重写setFilterChainDefinitionMap -->
<!-- super.setFilterChainDefinitionMap(filterMap)-->
<bean id="shiroFilter" class="com.xxxx.shiro.MyShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager"></property>
<!--登录地址-->
<property name="loginUrl" value="/login"></property>
<!--登录成功跳转的地址-->
<property name="successUrl" value="/getStatusInfo"></property>
<!--权限认证失败跳转的地址-->
<property name="unauthorizedUrl" value="/unAuthorized"></property>
<!--需要权限拦截的路径-->
<property name="filterChainDefinitions" value=""> </property>
</bean>
<!-- 保证实现了Shiro内部lifecycle函数的bean执行 ,不明觉厉,没有深究-->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor"/>
</beans>
```
```xml
<property name="filterChainDefinitions">
<value>
<!--
anon 不需要认证
authc 需要认证
user 验证通过或RememberMe登录的都可以
-->
<!-- /commons/** = anon -->
/static/** = anon
<!-- /webhooks = anon -->
/login.action = anon
/page/404.action = anon
/page/500.action = anon
<!-- /dataDict/saveOrUpdateDataDict.action = perms["shiro:save"] -->
/** = authc
</value>
</property>
```
```
基于令牌校验:
AccessControlFilter:
检查jwt token,取值并创建 UsernamePasswordToken(username:jwt,password:jwt), 或者跳转登陆page
/login 请求单独实现登陆校验,生成jwt之后 创建 UsernamePasswordToken(username:jwt,password:jwt) 用作realm 校验。
realm: 密码做明文校验。
核心: realm 铭文校验,UsernamePasswordToken 存放jwt, AccessControlFilter 检查jwt 是否存在。
UsernamePasswordToken在 realm,不用作用户名密码校验。
```
<file_sep>/sql/postgresql/install.md
二进制包部署:
解压二进制包:
**修改解压内容所有者为数据库管理员。并切换至数据库管理员。**
```
postgres 为用户名,可以为其他用户名(该用户用作数据库的超级管理员)
postgres 密码,建议设置为 postgres
创建数据库管理员:(useradd 未指定用户组,用户组与用户同名)
# useradd postgres
设置密码
# pssswd postgres
修改所有者:
# chown postgres: 数据库文件目录
切换到数据库的超级管理员
# su postgres
```
### 后续操作由数据库超级管理员完成。
pgsql/bin 下包含相应命令。
```
创建数据存储目录: mkdir 数据存储目录
```
初始化:
```
bin/initdb -D 数据存储目录
```
启动/停止:
```
bin/pg_ctl -D 数据存储目录 -l logfile start (-l -l logfile 可不使用用 )
bin/pg_ctl -D 数据存储目录 stop
```
配置:
```
数据存储目录/postgresql.conf
配置数据库 连接ip及端口(listen_addresses='*' # localhost 只能本机访问)
#listen_addresses = 'localhost' # what IP address(es) to listen on;
# comma-separated list of addresses;
# defaults to 'localhost'; use '*' for all
# (change requires restart)
#port = 5432 # (change requires restart)
数据存储目录/pg_hba.conf
访问白名单,黑名单
# TYPE DATABASE USER ADDRESS METHOD
# "local" is for Unix domain socket connections only
local all all trust
# IPv4 local connections:
host all all 127.0.0.1/32 trust
# IPv6 local connections:
host all all ::1/128 trust
可添加:
host all all 192.168.0.0/16 trust
```
psql 配置命令行默认参数:
```
export PGPORT=5432
export PGHOST=localhost
在使用psql 跳过密码输入
export PGPASSWORD=<PASSWORD>
```
配置文件优先级
```
postgresql.auto.conf的优先级高于postgresql.conf,如果一个参数同时存在postgresql.auto.conf和postgresql.conf里面,系统会先读postgresql.auto.conf的参数配置
```
<file_sep>/java/maven/0_Lifecycle.md
```
Clean Lifecycle在进行真正的构建之前进行一些清理工作。
Default Lifecycle 构建的核心部分,编译,测试,打包,部署等等。
Site Lifecycle 生成项目报告,站点,发布站点。
生命周期(lifecycle)由多个阶段(phase)组成,这些阶段(phase)是有顺序的,后面的阶段依赖于前面的阶段.
每个阶段(phase)会挂接一到多个goal,
goal是maven里定义任务的最小单元。
我们和Maven最直接的交互方式就是调用这些生命周期阶段。
```
Clean Lifecycle
```
pre-clean
clean
post-clean
```
Default Lifecycle
```
validate
initialize
generate-sources
process-sources
generate-resources
process-resources
compile
process-classes
generate-test-sources
process-test-sources
generate-test-resources
process-test-resources
test-compile
process-test-classes
test
prepare-package
package
pre-integration-test
integration-test
post-integration-test
verify
install
deploy
```
Site Lifecycle
```
pre-site
site
post-site
site-deploy
```
<file_sep>/RevisionControl/git/glide.md
glide install:
```
curl https://glide.sh/get | sh
add cmd glide to PATH
or
go get github.com/Masterminds/glide
```
glide usage:
```
glide create 初始化项目并创建glide.yaml文件. (在项目根目录下执行,生成glide.yaml)
glide init 初始化项目并创建glide.yaml文件.(在项目根目录下执行,生成glide.yaml)
glide update 更新解析下载包依赖
glide up 更新解析下载包依赖
glide install 安装包
glide get 获取单个包
--all-dependencies 会下载所有关联的依赖包
-s 删除所有版本控制,如.git
-v 删除嵌套的vendor
glide name 查看依赖名称
glide list 查看依赖列表
glide help 帮助
glide --version查看版本
glide mirror set [original] [replacement] 替换包的镜像
glide mirror set [original] [replacement] --vcs [type] 替换包的镜像
glide mirror remove [original] 移除包的镜像
glide mirror list 获取包的镜像列表
---------------------
作者:风.foxwho
来源:CSDN
原文:https://blog.csdn.net/fenglailea/article/details/79107124
版权声明:本文为博主原创文章,转载请附上博文链接!
```
<file_sep>/python/hex_ip.py
def hexIpToIntIP(string):
# C0:A8:01:01
if string is not None:
tmp_arr = string.replace(":", " ").split()
return '.'.join(str(int(string_num.upper(), 16)) for string_num in tmp_arr)
else:
return None<file_sep>/python/django_1.11/guide.md
```
django-admin.py startproject project_name
cd project_name
可用命令
python manage.py
python manage.py startapp app_name
# 1. 创建更改的文件
python manage.py makemigrations
# 2. 将生成的py文件应用到数据库
python manage.py migrate
python manage.py runserver
python manage.py runserver 8001
python manage.py runserver 0.0.0.0:8000
清空数据库
python manage.py flush
此命令会询问是 yes 还是 no, 选择 yes 会把数据全部清空掉,只留下空表。
python manage.py createsuperuser
# 按照提示输入用户名和对应的密码就好了邮箱可以留空,用户名和密码必填
# 修改 用户密码可以用:
python manage.py changepassword username
导出数据 导入数据
python manage.py dumpdata
python manage.py dumpdata appname > appname.json
python manage.py loaddata appname.json
python manage.py shell
模型:
models.py
class Person(models.Model):
name = models.CharField(max_length=30)
age = models.IntegerField()
同步数据库:
python manage.py makemigrations
python manage.py migrate
测试数据:
$ python manage.py shell
>>> from app_name.models import Person
>>> Person.objects.create(name="test", age=24)
<Person: Person object>
>>> Person.objects.get(name="test")
<Person: Person object>
>>>
Person.objects.create(name=name,age=age)
p = Person(name="WZ", age=23)
p.save()
p = Person(name="TWZ")
p.age = 23
p.save()
Person.objects.get_or_create(name="WZT", age=23)
这种方法是防止重复很好的方法,但是速度要相对慢些,返回一个元组,第一个为Person对象,第二个为True或False, 新建时返回的是True, 已经存在时返回False.
Person.objects.all()
Person.objects.get(name=name)
get是用来获取一个对象的,如果需要获取满足条件的一些人,就要用到filter
Person.objects.filter(name="abc") # 等于Person.objects.filter(name__exact="abc") 名称严格等于 "abc" 的人
Person.objects.filter(name__iexact="abc") # 名称为 abc 但是不区分大小写,可以找到 ABC, Abc, aBC,这些都符合条件
Person.objects.filter(name__contains="abc") # 名称中包含 "abc"的人
Person.objects.filter(name__icontains="abc") #名称中包含 "abc",且abc不区分大小写
Person.objects.filter(name__regex="^abc") # 正则表达式查询
Person.objects.filter(name__iregex="^abc") # 正则表达式不区分大小写
filter是找出满足条件的,当然也有排除符合某条件的
Person.objects.exclude(name__contains="te") # 排除包含 WZ 的Person对象
Person.objects.filter(name__contains="abc").exclude(age=23) # 找出名称含有abc, 但是排除年龄是23岁的
Person.objects.filter(name__contains="abc").delete() # 删除 名称中包含 "abc"的人
Person.objects.filter(name__contains="abc").update(name='xxx') # 名称中包含 "abc"的人 都改成 xxx
Person.objects.all().delete() # 删除所有 Person 记录
Person.objects.all()[:10] 切片操作,前10条
Person.objects.all()[-10:] 会报错!!!
# 1. 使用 reverse() 解决
Person.objects.all().reverse()[:2] # 最后两条
Person.objects.all().reverse()[0] # 最后一条
# 2. 使用 order_by,在栏目名(column name)前加一个负号
Author.objects.order_by('-id')[:20] # id最大的20条
qs1 = Pathway.objects.filter(label__name='x')
qs2 = Pathway.objects.filter(reaction__name='A + B >> C')
qs3 = Pathway.objects.filter(inputer__name='WeizhongTu')
# 合并到一起
qs = qs1 | qs2 | qs3
这个时候就有可能出现重复的
# 去重方法
qs = qs.distinct()
```
<file_sep>/golang/base/2_string.md
```
strings.Join(a []string, sep string) string // 拼接
s := []string{"hello", "word", "xxx"}
fmt.Println(strings.Join(s, "-")) // hello-word-xxx
```
字符串分割:
```
strings.Fields(s string) []string // 按空格分割
strings.FieldsFunc(s string, f func(rune) bool) []string // 自定义分割函数
Split(s, sep string) []string // 分割,段尾不保留分割字符
strings.SplitAfterN(s,step string,n int) []string // 分割成几段,保留分割字符在段尾
strings.SplitAfter(s, sep string)[]string // 分割成几段,保留分割字符在段尾
strings.SplitN(s, sep string, n int) []string // 分割成几段,段尾不保留分割字符
```
```go
用于类型转换
strconv
```
<file_sep>/sql/redis/cluster.md
参考: https://www.cnblogs.com/mafly/p/redis_cluster.html
一.
```
redis.conf 关键配置:
port 9001(每个节点的端口号)
daemonize yes
bind 192.168.119.131(绑定当前机器 IP)
dir /usr/local/redis-cluster/9001/data/(数据文件存放位置)
pidfile /var/run/redis_9001.pid(pid 9001和port要对应)
cluster-enabled yes(启动集群模式)
cluster-config-file nodes9001.conf(9001和port要对应)
cluster-node-timeout 15000
appendonly yes
配置好后启动所有节点
```
二.
```
ruby 相关软件安装:
yum install ruby
yum install rubygems
gem install redis
```
三. 创建集群
```
redis/bin/redis-trib.rb create --replicas 1 node1_ip:node1_port node2_ip:node2_port ......
```
四.查看集群状态及简单使用
```
redis-cli -c -h node_ip -p port
-c: 连接到集群
> cluster info
> cluster nodes
> set key value : 会自动跳转到保存key 的节点
> keys * :只能看到当前节点的keys
> get key :得到key 并跳转到保存该key 的节点。
```
集群管理参考:https://blog.csdn.net/qq_37595946/article/details/78069298
<file_sep>/C_or_C++/static.md
```
参考:https://blog.csdn.net/keyeagle/article/details/6708077
当一个进程的全局变量被声明为static之后,它的中文名叫静态全局变量
但是它只在定义它的源文件内有效,其他源文件无法访问它。
static局部变量中文名叫静态局部变量。
静态局部变量被编译器放在全局存储区
静态局部变量只能被其作用域内的变量或函数访问。也就是说虽然它会在程序的整个生命周期中存在,由于它是static的,它不能被其他的函数和源文件访问。
静态局部变量如果没有被用户初始化,则会被编译器自动赋值为0,以后每次调用静态局部变量的时候都用上次调用后的值,函数每次被调用,普通局部变量都是重新分配,而静态局部变量保持上次调用的值不变
static函数可以很好地解决不同原文件中函数同名的问题,因为一个源文件对于其他源文件中的static函数是不可见的。
```
<file_sep>/linux/softs/ssh/端口转发.md
本地端口转发:
ssh -L <local port>:<remote host>:<remote port> <SSH hostname><file_sep>/NoteSome.md
# NoteSome
<file_sep>/docker/0_image.md
鉴于国内网络问题,后续拉取 Docker 镜像十分缓慢,我们可以需要配置加速器来解决,我使用的是网易的镜像地址:http://hub-mirror.c.163.com。
新版的 Docker 使用 /etc/docker/daemon.json(Linux)
或者 %programdata%\docker\config\daemon.json(Windows) 来配置 Daemon。
请在该配置文件中加入(没有该文件的话,请先建一个):
```
{
"registry-mirrors": ["http://hub-mirror.c.163.com"]
}
```
列举镜像:
```
# docker image ls
# docker images -a
```
查找镜像:
```
docker search 关键字
eg:
# docker search centos
NAME DESCRIPTION STARS OFFICIAL AUTOMATED
centos The official build of CentOS. 5395 [OK]
ansible/centos7-ansible Ansible on Centos7 121 [OK]
jdeathe/centos-ssh CentOS-6 6.10 x86_64 / CentOS-7 7.5.1804 x86… 110 [OK]
.................................................................
```
拉取镜像:
```
# docker pull 镜像名 默认latest
# docker pull 镜像名:tag
eg:
# docker pull centos
Using default tag: latest
latest: Pulling from library/centos
Digest: sha256:b5e66c4651870a1ad435cd75922fe2cb943c9e973a9673822d1414824a1d0475
Status: Downloaded newer image for centos:latest
```
删除镜像:
```bash
# docker image rm centos:latest
Error response from daemon: conflict: unable to remove repository reference "centos:latest" (must force) - container d2a788c60caa is using its referenced image 9f38484d220f
强制删除
# docker image rm centos:latest -f
Untagged: centos:latest
Untagged: centos@sha256:b5e66c4651870a1ad435cd75922fe2cb943c9e973a9673822d1414824a1d0475
Deleted: sha256:9f38484d220fa527b1fb19747638497179500a1bed8bf0498eb788229229e6e1
```
### 创建镜像两种方式:
- 1.从已经创建的容器中更新镜像,并且提交这个镜像
- 2.使用 Dockerfile 指令来创建一个新的镜像
#### 1. 更新镜像
更新镜像之前,我们需要使用镜像来创建一个容器。
```bash
1. 运行镜像
2. 修改container
3. 提交container 得到新的镜像
eg:
运行镜像:
# docker run -d -it centos
查看运行状态
# docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
093b1127c08c centos "/bin/bash" 4 seconds ago Up 2 seconds festive_keller
进入docker container 修改
# docker exec -it 093b1127c08c /bin/bash
提交镜像
# docker commit -m="has update" -a="test" 093b1127c08c centos7/java:0.1
sha256:eb63dd7210fcc2f1317ee33564fd7b0cbc240437ce8d1230705a4e447d32d8e0
查看镜像列表
# docker image ls
REPOSITORY TAG IMAGE ID CREATED SIZE
centos7/java 0.1 eb63dd7210fc 7 seconds ago 697MB
centos latest 9f38484d220f 2 months ago 202MB
```
```bash
docker commit
-m:提交的描述信息
-a:指定镜像作者
093b1127c08c:容器ID
centos7/java:0.1 :指定要创建的目标镜像名(image:tag)
```
<file_sep>/sql/postgresql/psql_buildin.md
https://blog.csdn.net/Jeni_/article/details/117997918<file_sep>/sql/postgresql/pg.md
```
table: pg_user 数据库用户
usename 用户名
usesysid 用户id
| usecreatedb 是否有创建数据库的权限:t/f
| usesuper 是否是超级用户: t/f
userepl | usebypassrls
passwd # 密码********, 不可见
valuntil | useconfig
```
```
table pg_database: 数据库列表
select datname,datdba from pg_database ;
datname 数据库名:
datdba 用户id
```
```
pg_aggregate pg_index pg_sequence pg_statio_sys_sequences
pg_am pg_indexes pg_sequences pg_statio_sys_tables
pg_amop pg_inherits pg_settings pg_statio_user_indexes
pg_amproc pg_init_privs pg_shadow pg_statio_user_sequences
pg_attrdef pg_language pg_shdepend pg_statio_user_tables
pg_attribute pg_largeobject pg_shdescription pg_statistic
pg_auth_members pg_largeobject_metadata pg_shseclabel pg_statistic_ext
pg_authid pg_locks pg_stat_activity pg_stats
pg_available_extension_versions pg_matviews pg_stat_all_indexes pg_subscription
pg_available_extensions pg_namespace pg_stat_all_tables pg_subscription_rel
pg_cast pg_opclass pg_stat_archiver pg_tables
pg_catalog. pg_operator pg_stat_bgwriter pg_tablespace
pg_class pg_opfamily pg_stat_database pg_temp_1.
pg_collation pg_partitioned_table pg_stat_database_conflicts pg_timezone_abbrevs
pg_config pg_pltemplate pg_stat_progress_vacuum pg_timezone_names
pg_constraint pg_policies pg_stat_replication pg_toast.
pg_conversion pg_policy pg_stat_ssl pg_toast_temp_1.
pg_cursors pg_prepared_statements pg_stat_subscription pg_transform
pg_database pg_prepared_xacts pg_stat_sys_indexes pg_trigger
pg_db_role_setting pg_proc pg_stat_sys_tables pg_ts_config
pg_default_acl pg_publication pg_stat_user_functions pg_ts_config_map
pg_depend pg_publication_rel pg_stat_user_indexes pg_ts_dict
pg_description pg_publication_tables pg_stat_user_tables pg_ts_parser
pg_enum pg_range pg_stat_wal_receiver pg_ts_template
pg_event_trigger pg_replication_origin pg_stat_xact_all_tables pg_type
pg_extension pg_replication_origin_status pg_stat_xact_sys_tables pg_user
pg_file_settings pg_replication_slots pg_stat_xact_user_functions pg_user_mapping
pg_foreign_data_wrapper pg_rewrite pg_stat_xact_user_tables pg_user_mappings
pg_foreign_server pg_roles pg_statio_all_indexes pg_views
pg_foreign_table pg_rules pg_statio_all_sequences
pg_group pg_seclabel pg_statio_all_tables
pg_hba_file_rules pg_seclabels pg_statio_sys_indexes
```
pg_rules,pg_tables: 查询结果与当前数据库相关。
<file_sep>/golang/libs/daemon.md
https://github.com/icattlecoder/godaemon
https://github.com/sevlyar/go-daemon
https://gitee.com/mirrors/daemon (系统服务)
github.com/kardianos/service
<file_sep>/linux/arch/softs.md
# fcitx
包列表:
fcitx-configtool
fcitx-lilydjwg-git
fcitx-qt5
fcitx-sogoupinyin
~/.xprofile
export LC_ALL=zh_CN.UTF-8
export GTK_IM_MODULE=fcitx
export QT_IM_MODULE=fcitx
export XMODIFIERS="@im=fcitx"
(reboot)
# fcitx 5
```
包列表:
fcitx5
fcitx5-chinese-addons
fcitx5-configtool
fcitx5-gtk
fcitx5-material-color
fcitx5-pinyin-moegirl
fcitx5-pinyin-zhwiki
fcitx5-qt
fcitx5-rime
~/.xprofile 与fcitx 配置一致。
```
# flamshot 截图工具
# notepadqq
pacman -S notepadqq
# source
在 /etc/pacman.conf 文件末尾添加两行:
[archlinuxcn]
Server = https://mirrors.ustc.edu.cn/archlinuxcn/$arch
然后请安装 archlinuxcn-keyring 包以导入 GPG key。
pacman -Syu
pacman -S yaourt
-----------------------------------------
fail to install rchlinuxcn-keyring
pacman -Syu haveged
systemctl start haveged
systemctl enable haveged
rm -fr /etc/pacman.d/gnupg
pacman-key --init
pacman-key --populate archlinux
# google-chrome
yaourt google-chrome
# shadowsocks-qt5
yaourt shadowsocks-qt
# remmina
pacman -S remmina
yaourt remmina-plugin-rdesktop
# conky
# pacman -S conky
# pacman -S conky-manager
pamac-aur
```
# pacman -S pamac-aur
```
Typora
```
yaourt Typora
```
snapd
```
yaourt -S snapd # 需要从golang.org 下载依赖 (需要搭梯子)
sudo systemctl enable snapd.socket
```
fish
```
pacman -S fish #一个nice UI的shell,用来代替bash
tip:使用chsh -l 查看fish的地址,使用chsh -s /usr/bin/fish来更换用户默认shell
```
```
ifconfig,route在net-tools中
nslookup,dig在dnsutils中
ftp,telnet等在inetutils中
ip命令在iproute2中。
# pacman -S net-tools dnsutils inetutils iproute2
```
pacman -Rcns gnome
sudo pacman -Rs $(pacman -Qqdt)
软件列表
```
unarchiver 解压工具
flatpak 软件管理
pamac-aur 软件管理
yaourt 软件管理
yay 软件管理
openssh sshd
fcitx-im 输入法 (fcitx-lilydjwg-git 替换 fcitx-im)
flameshot 截图
字体:(fc-cache -vf : 更新字体缓存)
wqy-microhei
wqy-zenhei
adobe-source-code-pro-fonts
adobe-source-sans-pro-fonts
adobe-source-serif-pro-fonts
adobe-source-han-sans-cn-fonts
adobe-source-han-serif-cn-fonts
noto-fonts
noto-fonts-cjk
ttf-ubuntu-font-family
ttf-droid
awesome-terminal-fonts
```
```
rdesktop
xfreerdp
可以在系统属性-远程中开启:【允许远程协助连接这台计算机】+【允许远程连接到此计算机】,如果勾选了【仅运行运行使用网络级别身份验证的远程桌面单位计算机连接】,那么 rdesktop 无法连接.
Core(warning): Certificate received from server is NOT trusted by this system, an exception has been added by the user to trust this specific certificate.
Failed to initialize NLA, do you have correct Kerberos TGT initialized ?
Failed to connect, CredSSP required by server (check if server has disabled old TLS versions, if yes use -V option).
rdesktop一些常用选项:
-u : Windows用户
-p : Windows口令(非PIN)
-g : 窗口大小,如 1366x768
-f :全屏
-a : 色彩深度 :8, 15, 16, 24, 32
-r sound :支持声音
-r clipboard:支持剪切板
-r disk: 远程连接时挂载本地文件目录
% rdesktop 192.168.1.6
% rdesktop -u user -p - -f
% rdesktop -u user -p passwd -g 1366x768 -r sound -a 32 -r clipboard:PRIMARYCLIPBOARD -r disk:MyDir=/mnt/shared 192.168.1.6
-------------------------------------------------------------------------------------
xfreerdp
/v:<server>[:port] 默认端口 3389
/w、/h 窗口大小
/size:<width>x<height> 窗口大小,如 1024x768
/f 全屏
/workarea Use available work area
/bpp:<depth> 色彩深度
/u:<user>[@<domain>]
/p:<password>
/d:<domain> 域,可选
+fonts 平滑字体
% xfreerdp /v:192.168.1.6
% xfreerdp /u:user /p:passwd /v:192.168.1.6 /f
% xfreerdp /bpp:32 +fonts /u:user /p:passwd /v:192.168.1.6 /workarea
% xfreerdp /bpp:32 +clipboard +fonts /u:user /p:passwd /workarea /sound /drive:shared,/mnt/shared /v:192.168.1.6
% xfreerdp /bpp:32 +clipboard +fonts /u:user /p:passwd /size:1366x768 /sound -v:192.168.1.6:3389
```
```
dingtalk-linux :钉钉 for linux
alacritty : terminal
meld : compare tool
microsoft edge : browser
nomacs : image viewer
feh : image viewer
ranger : file browser
typora : markdown editor
wechat-uos : wechat client (web)
todesk : remote support
rdesktop : rdp client
lx-music-desktop-bin : music player
rinetd : internet redirection server
appimage:
another-redis-desktop: redis client
mailspring : email client
drawio : design tool
balenaetcher: burn tool
QQmusic : qq music client
```
<file_sep>/C_or_C++/cpuid/wiki.md
https://en.wikipedia.org/wiki/CPUID#EAX=0:_Highest_Function_Parameter_and_Manufacturer_ID
```
#include <stdio.h>
int main()
{
int a, b;
for (a = 0; a < 5; a++)
{
__asm__("cpuid"
:"=a"(b) // EAX into b (output)
:"0"(a) // a into EAX (input)
:"%ebx","%ecx","%edx"); // clobbered registers
printf("The code %i gives %i\n", a, b);
}
return 0;
}
```
<file_sep>/java/note_spring/0.md
```
在获取ApplicationContext实例后,我们就可以像BeanFactory那样调用getBean(beanName)返回Bean了。
ApplicationContext的初始化和BeanFactory初始化有一个重大区别:
BeanFactory在初始化容器时,并没有实例化Bean,直到第一次访问某个Bean时才实例化目标Bean。
ApplicationContext会在初始化应用上下文时就实例化所有单实例的Bean。
因此,ApplicationContext的初始化时间会比BeanFactory的时间稍微长一些,不过稍后的调用则没有“第一次惩罚”的问题。
```
```
ApplicationContext两个主要实现类
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
始化配置文件时,还可以指定一组配置文件,Spring会自动对多个配置文件在内存中“整合”成一个配置文件。
额外:
AnnotationConfigApplicationContext
一个标注了@Configuration注解的POJO即可提供Spring所需要的配置信息
@Configuration // @Configuration表示是一个配置信息提供类
public class Beans {
@Bean(name = "xxx") // ͨ定义一个Bean,通过name指定bean的名称
public XXX x(){
returen new XXX()
}
}
ApplicationContext ctx = new AnnotationConfigApplicationContext(Beans.class);
GenericiGroovyApplicationContext:
```
<file_sep>/java/maven/maven_nodejs.md
<build> 下增加
```xml
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.5</version>
<configuration>
<!-- 逗号分割,打包war 时排除文件 -->
<excludes>
**/node_modules/**
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<executions>
<execution>
<id>exec-npm-install</id>
<phase>prepare-package</phase>
<!-- <phase>generate-sources</phase> -->
<!-- <phase>initialize</phase> -->
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>cnpm</executable>
<arguments>
<argument>install</argument>
</arguments>
<workingDirectory>${basedir}/src/main/webapp/static</workingDirectory>
</configuration>
</execution>
<execution>
<id>exec-npm-run-build</id>
<phase>prepare-package</phase>
<!-- <phase>generate-sources</phase> -->
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>cnpm</executable>
<arguments>
<argument>run</argument>
<argument>build</argument>
</arguments>
<workingDirectory>${basedir}/src/main/webapp/static</workingDirectory>
</configuration>
</execution>
<!-- 其他调用和继续增加 -->
</executions>
</plugin>
```
<file_sep>/java/nexus/install.md
nexus 3: maven 管理私服
安装使用参考: <https://my.oschina.net/xiaominmin/blog/2050604>
下载地址:
<https://www.sonatype.com/download-oss-sonatype>
安装:
解压 nexus
安装成功后有两个默认账号admin、anonymous,其中admin具有全部权限默认密码<PASSWORD>;anonymous作为匿名用户,只具有查看权限
本地maven库配置settings.xml
```xml
<settings>
<pluginGroups>
<pluginGroup>org.sonatype.plugins</pluginGroup>
</pluginGroups>
<servers>
<server>
<id>nexus</id>
<username>admin</username>
<password><PASSWORD></<PASSWORD>>
</server>
</servers>
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>http://localhost:8081/repository/maven-public/</url>
</mirror>
<mirror>
<id>repo2</id>
<mirrorOf>central</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://repo2.maven.org/maven2/</url>
</mirror>
</mirrors>
<profiles>
<profile>
<id>nexus</id>
<repositories>
<repository>
<id>central</id>
<url>http://central</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>central</id>
<url>http://central</url>
<releases><enabled>true</enabled></releases>
<snapshots><enabled>true</enabled></snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
<activeProfiles>
<activeProfile>nexus</activeProfile>
</activeProfiles>
</settings>
```
工程配置pox.xml
```xml
<distributionManagement>
<repository>
<id>nexus</id>
<name>Releases</name>
<url>http://localhost:8081/repository/maven-releases</url>
</repository>
<snapshotRepository>
<id>nexus</id>
<name>Snapshot</name>
<url>http://localhost:8081/repository/maven-snapshots</url>
</snapshotRepository>
</distributionManagement>
<build>
<defaultGoal>compile</defaultGoal>
<finalName>page</finalName>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<configuration>
<skip>true</skip>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.3</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
```
<file_sep>/js/react/批量更新.md
参考: <https://www.2cto.com/kf/201805/744027.html>
### react : setState 部分情况下为异步操作,部分情况为同步
handleClick : 调用 setState 立即获取stete , 由于更新不是同步的,拿到的state 为旧的值.
setTimeout(() => { }) : 调用 setState 立即获取stete 拿到的是新的值.
fetch('/') .then(() => { } : 调用 setState 立即获取stete 拿到的是新的值.
### 在React调用的方法中连续setState走的是批量更新(异步),此外走的是连续更新(同步)
<file_sep>/html+css/less/tools.md
### less tools:
参考: <https://blog.csdn.net/sun_dongliang/article/details/82750773>
```
GUI 工具
koala
命令行工具:
lessc : npm install less -g
lessc xxx.less xxx.css
watcher-lessc: lessc 辅助工具
webstorm 可在File Watchers 中添加less.
cdn 引入less.js 可不编译less 文件,直接使用
```
<file_sep>/linux/ubuntu/ubuntu16.md
## 源:
## 东北大学
```
deb-src http://mirror.neu.edu.cn/ubuntu/ xenial main restricted #Added by software-properties
deb http://mirror.neu.edu.cn/ubuntu/ xenial main restricted
deb-src http://mirror.neu.edu.cn/ubuntu/ xenial restricted multiverse universe #Added by software-properties
deb http://mirror.neu.edu.cn/ubuntu/ xenial-updates main restricted
deb-src http://mirror.neu.edu.cn/ubuntu/ xenial-updates main restricted multiverse universe #Added by software-properties
deb http://mirror.neu.edu.cn/ubuntu/ xenial universe
deb http://mirror.neu.edu.cn/ubuntu/ xenial-updates universe
deb http://mirror.neu.edu.cn/ubuntu/ xenial multiverse
deb http://mirror.neu.edu.cn/ubuntu/ xenial-updates multiverse
deb http://mirror.neu.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse
deb-src http://mirror.neu.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse #Added by software-properties
deb http://archive.canonical.com/ubuntu xenial partner
deb-src http://archive.canonical.com/ubuntu xenial partner
deb http://mirror.neu.edu.cn/ubuntu/ xenial-security main restricted
deb-src http://mirror.neu.edu.cn/ubuntu/ xenial-security main restricted multiverse universe #Added by software-properties
deb http://mirror.neu.edu.cn/ubuntu/ xenial-security universe
deb http://mirror.neu.edu.cn/ubuntu/ xenial-security multiverse
```
## 清华大学
```
# deb cdrom:[Ubuntu 16.04 LTS _Xenial Xerus_ - Release amd64 (20160420.1)]/ xenial main restricted
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial main restricted
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates main restricted
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial universe
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates universe
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial multiverse
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-updates multiverse
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-backports main restricted universe multiverse
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security main restricted
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security universe
deb http://mirrors.tuna.tsinghua.edu.cn/ubuntu/ xenial-security multiverse
```
## 阿里云
```
# deb cdrom:[Ubuntu 16.04 LTS _Xenial Xerus_ - Release amd64 (20160420.1)]/ xenial main restricted
deb-src http://archive.ubuntu.com/ubuntu xenial main restricted #Added by software-properties
deb http://mirrors.aliyun.com/ubuntu/ xenial main restricted
deb-src http://mirrors.aliyun.com/ubuntu/ xenial main restricted multiverse universe #Added by software-properties
deb http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-updates main restricted multiverse universe #Added by software-properties
deb http://mirrors.aliyun.com/ubuntu/ xenial universe
deb http://mirrors.aliyun.com/ubuntu/ xenial-updates universe
deb http://mirrors.aliyun.com/ubuntu/ xenial multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-updates multiverse
deb http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-backports main restricted universe multiverse #Added by software-properties
deb http://archive.canonical.com/ubuntu xenial partner
deb-src http://archive.canonical.com/ubuntu xenial partner
deb http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted
deb-src http://mirrors.aliyun.com/ubuntu/ xenial-security main restricted multiverse universe #Added by software-properties
deb http://mirrors.aliyun.com/ubuntu/ xenial-security universe
deb http://mirrors.aliyun.com/ubuntu/ xenial-security multiverse
```
```
sudo apt-get update
sudo apt-get remove --purge libreoffice*
# apt-get install vim
sudo apt install openssh-server
```
```
unknown:
Run 'dpkg-reconfigure tzdata' if you wish to change it.
```
```
sudo apt-get install fcitx-bin
sudo apt-get install fcitx-table
安装完fcixt后在“设置 > 区域和语言 > 管理已安装的语言 > 键盘输入法系统”处把它替换为fcitx,然后重启Ubuntu
卸载iBus
sudo apt-get purge ibus
sudo apt-get autoremove
据说Ubuntu老版本的桌面跟ibus有依赖关系,如果桌面菜单栏都消失了,那么就进命令行输入下面的提供的代码。
sudo apt-get update
sudo apt-get install --reinstall ubuntu-desktop
# sudo apt-get install unity
重启下桌面正常
```
<file_sep>/js/ie8_solutions/缺少标识符、字符串或数字.md
缺少标识符、字符串或数字
```
关键字作为 key 报错:
将key 用引号包起来.
{true:
,true:
{false:
,false:
```
```
map 类型数据 不能有多余的逗号. (删除所有json中最后一项后面的逗号)
```
<file_sep>/sql/postgresql/disk_usage.md
```sql
-- 统计各数据库占用磁盘大小:
SELECT d.datname AS Name, pg_catalog.pg_get_userbyid(d.datdba) AS Owner,
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_size_pretty(pg_catalog.pg_database_size(d.datname))
ELSE 'No Access'
END AS SIZE
FROM pg_catalog.pg_database d
ORDER BY
CASE WHEN pg_catalog.has_database_privilege(d.datname, 'CONNECT')
THEN pg_catalog.pg_database_size(d.datname)
ELSE NULL
END DESC -- nulls first
LIMIT 20 ;
select pg_size_pretty(pg_database_size('数据库名'));
-- 统计数据库中各表占用磁盘大小:
SELECT table_schema || '.' || table_name AS table_full_name,
pg_size_pretty(pg_total_relation_size('"' || table_schema || '"."' || table_name || '"')) AS size
FROM information_schema.tables
ORDER BY
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC ;
SELECT table_schema || '.' || table_name AS table_full_name,
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') AS size
FROM information_schema.tables
ORDER BY
pg_total_relation_size('"' || table_schema || '"."' || table_name || '"') DESC ;
```
```sql
select
pg_relation_size('tablename','main') as main,
pg_relation_size('tablename','fsm') as fsm,
pg_relation_size('tablename','vm') as vm,
pg_relation_size('tablename','init') as init,
pg_table_size('tablename'),
pg_indexes_size('tablename') as indexes,
pg_total_relation_size('tablename') as total;
```
```sql
select
pg_size_pretty(pg_relation_size('tablename','main')) as main,
pg_size_pretty(pg_relation_size('tablename','fsm')) as fsm,
pg_size_pretty(pg_relation_size('tablename','vm')) as vm,
pg_size_pretty(pg_relation_size('tablename','init')) as init,
pg_size_pretty(pg_table_size('tablename')),
pg_size_pretty(pg_indexes_size('tablename')) as indexes,
pg_size_pretty(pg_total_relation_size('tablename')) as total;
pg_table_size是pg_relation_size的所有返回值的总和.
pg_total_relation_size是pg_table_size和pg_indexes_size的总和
create or replace function custom_pg_table_size(tablename text)RETURNS SETOF RECORD as $$
BEGIN
return query ( (select
pg_size_pretty(pg_relation_size($1,'main')) as main,
pg_size_pretty(pg_relation_size($1,'fsm')) as fsm,
pg_size_pretty(pg_relation_size($1,'vm')) as vm,
pg_size_pretty(pg_relation_size($1,'init')) as init,
pg_size_pretty(pg_table_size($1)),
pg_size_pretty(pg_indexes_size($1)) as indexes,
pg_size_pretty(pg_total_relation_size($1)) as total ) ) ;
return ;
END;
$$language plpgsql;
select * from custom_pg_table_size('tablename') as (main text,fsm text,vm text,init text,table_size text,indexes text,total text);
drop function custom_pg_table_size(text);
```
<file_sep>/python/solutions/code_not_work.md
```
error: UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range
参考: https://blog.csdn.net/weixin_39221360/article/details/79525341
解决方法有三种:
1.在命令行修改,仅本会话有效:
1)通过>>>sys.getdefaultencoding()查看当前编码(若报错,先执行>>>import sys >>>reload(sys));
2)通过>>>sys.setdefaultencoding('utf8')设置编码
2.较繁琐,最有效
1)在程序文件中以下三句
import sys
reload(sys)
sys.setdefaultencoding('utf8')
3.修改Python本环境(推荐)
在Python的Lib\site-packages文件夹下新建一个sitecustomize.py文件,内容为:
#coding=utf8
import sys
reload(sys)
sys.setdefaultencoding('utf8')
```
```
open函数指名encoding 文件读取
```
<file_sep>/java/mybatis/parms.md
```
参考: https://blog.csdn.net/bdqx_007/article/details/94836637
```
1. 匿名参数
```
mapper: 普通函数
xml: #{参数名} ,不需要 parameterType
```
2. @Param注解
```
mapper: 普通函数
xml: #{参数名(@Param 设置的名称)} ,不需要 parameterType
```
3. map
```
mapper: 函数参数为map 类型
xml: 设置parameterType="map" #{key (map 键)}
```
4. bean
```
mapper: 函数参数为 bean 类型
xml: 设置parameterType="xxx.xx.bean" #{key(bean 属性名)}
```
5. json
```
mapper: 与map,bean 使用方式类似
xml: 设置parameterType="xxx.xx.bean" #{key(json 键)}
```
6. list,set,array
```
mapper: 使用方式与匿名参数类似
xml:不需要 parameterType,
list mapper参数名
<foreach collection="list" open="(" separator="," close=")" item="xxx">
#{xxx}s
</foreach>
```
7. 参数类型为对象+集合 (对象属性为集合)
```
mapper: 与bean,map 类型类似
xml: 设置parameterType="xxx.xx.bean"
#{变量名.属性名}
```
1-6: parameterType: 可直接使用#{属性名}获取传值<file_sep>/linux/softs/fcitx/install.md
sudo apt-get purge fcitx*
//sudo apt-get install fcitx-googlepinyin
sudo apt-get install fcitx im-config fcitx-table-all fcitx-ui-classic
apt-cache search fcitx*
sudo apt-get install fcitx-sunpinyin sunpinyin-utils
sudo apt-get install fcitx-config-common fcitx-config-gtk
/usr/share/fcitx/skin :skin path
cp skin dir to "/usr/share/fcitx/skin"
${HOME}/.config/fcitx/skin
$ fcitx : run fc
部分应用不能使用中文输入:
1. 在启动脚本中加入
```
export XMODIFIERS=@im=fcitx
export XIM=fcitx
export XIM_PROGRAM=fcitx
export GTK_IM_MODULE=fcitx
export QT_IM_MODULE=fcitx
```
2. 在profile 中加如上内容,然后通过终端启动
搜狗输入法安装:
参考:<https://www.cnblogs.com/JJUT/p/9956426.html>
```
sudo pacman -S fcitx
sudo pacman -S fcitx-configtool
sudo pacman -S fcitx-gtk2 fcitx-gtk3 fcitx-qt4 fcitx-qt5
sudo pacman -S fcitx-sogoupinyin
~/.xprofile 在其末尾添加以下几行:
export GTK_IM_MODULE=fcitx
export QT_IM_MODULE=fcitx
export XMODIFIERS="@im=fcitx"
```
fcitx-cloudpinyin
fcitx-configtool
fcitx-googlepinyin
```
搜狗输入法:
sudo pacman -S fcitx-sogoupinyin
.xprofile 内容:
export GTK_IM_MODULE=fcitx
export XMODIFIERS=@im=fcitx
export QT_IM_MODULE=fcitx
fcitx -d -r --enable sogou-qimpanel
fcitx 添加输入法,重启。
fcitx -d -r --enable sogou-qimpanel (可能搜狗启动有延迟,进入桌面后不能立即使用)
------------------------------------------------------------------------------------
切换搜狗输入法后输入时不显示中文:
$ sogou-qimpanel
sogou-qimpanel: error while loading shared libraries: libfcitx-qt.so.0: cannot open shared object file: No such file or directory
$ pkgfile libfcitx-qt.so.0
archlinuxcn/fcitx-lilydjwg-git
$ sudo pacman -S fcitx-lilydjwg-git
resolving dependencies...
looking for conflicting packages...
:: fcitx-lilydjwg-git and fcitx are in conflict. Remove fcitx? [y/N] y
:: fcitx-lilydjwg-git and fcitx-gtk2 are in conflict. Remove fcitx-gtk2? [y/N] y
:: fcitx-lilydjwg-git and fcitx-gtk3 are in conflict. Remove fcitx-gtk3? [y/N] y
Packages (4) fcitx-4.2.9.7-1 [removal] fcitx-gtk2-4.2.9.7-1 [removal] fcitx-gtk3-4.2.9.7-1 [removal] fcitx-lilydjwg-git-2:4.2.9.7.20191107-1
Total Download Size: 7.14 MiB
Total Installed Size: 35.35 MiB
Net Upgrade Size: 0.48 MiB
:: Proceed with installation? [Y/n]
:: Retrieving packages...
。。。。。。。。。。。。。。。。。。。。。。。。。。。
```
<https://github.com/gatieme/AderXCoding/tree/master/system/tools/sougoupinyin>
```
方法1
执行如下指令
cd ~/.config
find . -name sogou*
find . -name Sogou*
将两次搜索到的配置文件删除即可.
一般来说, 总共有如下3个文件夹, 全部删除即可
SogouPY、SogouPY.users、sogou-qimpanel
删除这3个文件夹,然后重启搜狗.
------------------------------------------------
方法2:
通过下面的命令重启搜狗输入法,看重启后是否可以正常使用:
killall fcitx
killall sogou-qinpanel
fcitx &
sogou-qinpanel &
```
```
使用sougou, 用 fcitx-lilydjwg-git 替换 fcitx 包。
```
包列表:
```
fcitx-configtool
fcitx-lilydjwg-git
fcitx-qt5
fcitx-sogoupinyin
```
<file_sep>/js/jquery/Deferred.md
```
Deferred
Deferred对象是jquery开发团队设计的,为了增强jquery的回调功能,在1.7版本中加入了jquery
```
**$.Deferred([fun])**
**$.Deferred()没有参数时 返回Deferred对象;**
**有参数时,表示在这个参数上做延迟或异步操作,并且返回Deferred对象.**
**done(fn)** 当延迟成功后调用该方法
**fail(fn)** 当延迟失败时调用失败
**then(done,fail)** 这个是done和fail的总写方式
**always(fn)** 不管延迟执行的成功还是失败,都执行的方法
resolve和reject方法一旦执行,表示开始执行done,fail,then,always方法,
注意Deferred对象可以一次挂接多个done,fail方法,按照你分布的顺序依次执行.
**resolve(value)** 告诉对象执行done回调,value是参数
**reject(value)** 告诉对象执行fail回调,value是参数.
```js
var dfd = $.Deferred();
dfd.done(function(value) {
alert(value);
});
dfd.resolve("执行done回调");
// --------------------------------------
var dfd = $.Deferred();
dfd.done(function(value) {
alert(value);
});
dfd.reject("执行fail回调");
// --------------------------------------
var dfd = $.Deferred();
var doneFun=function(value) {
alert("done:"+value);
};
var failFun=function(value) {
alert("fail:"+value);
}
dfd.then(doneFun,failFun);
dfd.reject("....");
// --------------------------------------
```
**state()** 返回deferred对象目前的状态
1.pending:操作没有完成
2.resolved:操作成功
3.rejected:操作失败
```js
var dfd=$.Deferred();
dfd.done(function(){
console.log("done");
});
console.log(dfd.state());
dfd.resolve();
console.log(dfd.state());
//--
pedning
done
resolved
```
**progress(fn)和notify(value)**
progress和done之类的方法截然不同.
progress(fn)的fn表示一个回调函数,这个回调函数由notify()方法通知执行.
$.when(d);d是一个或多个延迟对象
多个延迟都执行结束后才回调。
```
$.when($.ajax("1.json"), $.ajax("2.json"),$.ajax("3.json"))
.done(function(data1, data2,data3) {
console.log(data1);
console.log(data2);
console.log(data3);
}).fail(function(data1,data2,data3){
console.log(data1);
console.log(data2);
console.log(data3);
});
```
```js
延迟函数返回 Deferred对象,容易被拿到 Deferred对象的程序操纵。 延迟函数返回 promise() 调用
dfd.promise()
```
<file_sep>/python/somelib/datetime.md
```
import datetime
datetime.datetime.now() # 当前时间
datetime.datetime.strptime( time_string, "%Y-%m-%d %H:%M:%S") # 时间字符串转时间
```
<file_sep>/sql/mysql/users.md
```
mysql> use mysql;
Database changed
mysql> grant all privileges on *.* to root@'%' identified by "password";
Query OK, 0 rows affected (0.00 sec)
mysql> flush privileges;
use mysql;
update user set host = '%' where user = 'root';
```
```
参考: https://www.cnblogs.com/sos-blue/p/6852945.html
CREATE USER 'username'@'host' IDENTIFIED BY 'password';
eg:
CREATE USER 'dog'@'localhost' IDENTIFIED BY '123456';
CREATE USER 'pig'@'192.168.1.101' IDENDIFIED BY '123456';
CREATE USER 'pig'@'%' IDENTIFIED BY '123456';
CREATE USER 'pig'@'%' IDENTIFIED BY '';
CREATE USER 'pig'@'%';
CREATE USER 'root'@'%' IDENTIFIED BY 'root12345';
GRANT privileges ON databasename.tablename TO 'username'@'host'
privileges:用户的操作权限,如SELECT,INSERT,UPDATE等,如果要授予所的权限则使用ALL
eg:
GRANT SELECT, INSERT ON test.user TO 'pig'@'%';
GRANT ALL ON *.* TO 'pig'@'%';
GRANT ALL ON maindataplus.* TO 'pig'@'%';
REVOKE privilege ON databasename.tablename FROM 'username'@'host';
SET PASSWORD FOR 'username'@'host' = PASSWORD('<PASSWORD>');
前登陆用户: SET PASSWORD = PASSWORD("<PASSWORD>");
DROP USER 'username'@'host';
```
```
参考:
https://www.cnblogs.com/janken/p/5500320.html
1、create schema [数据库名称] default character set utf8 collate utf8_general_ci;--创建数据库
采用create schema和create database创建数据库的效果一样。
2、create user '[用户名称]'@'%' identified by '[用户密码]';--创建用户
密码8位以上,包括:大写字母、小写字母、数字、特殊字符
%:匹配所有主机,该地方还可以设置成‘localhost’,代表只能本地访问,例如root账户默认为‘localhost‘
3、grant select,insert,update,delete,create on [数据库名称].* to [用户名称];--用户授权数据库
*代表整个数据库
4、flush privileges ;--立即启用修改
5、revoke all on *.* from tester;--取消用户所有数据库(表)的所有权限
6、delete from mysql.user where user='tester';--删除用户
7、drop database [schema名称|数据库名称];--删除数据库
```
忘记密码:
[mysqld]后面任意一行添加 skip-grant-tables
重启MySQL
```sql
use mysql;
update user set password=password("<PASSWORD>") where user="root";
flush privileges;
quit
```
root用户权限丢失:
```sql
[mysqld]后面任意一行添加 skip-grant-tables , 重启
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
GRANT ALL ON *.* TO 'root'@'localhost';
select * from mysql.user
```
mysql.user 密码字段需要为加密字符串。
非加密字符串时:
mysql -h 127.0.0.1 -P 端口 -u root@非加盟密码 登录
<file_sep>/js/js/test.md
### 解决js相同的正则多次调用test()返回的值却不同的问题
参考:<https://www.jb51.net/article/148529.htm>
这是因为正则reg的g属性,设置的全局匹配。RegExp有一个lastIndex属性,来保存索引开始位置。
**第一种方案**是将g去掉,关闭全局匹配。
**第二种**就是在每次匹配之前将lastIndex的值设置为0。
reg.lastIndex = 0;<file_sep>/editor/vscode/后缀与格式.md
```
// .es 结尾的文件使用yaml 格式
"files.associations": {
"*.es": "yaml"
}
```
<file_sep>/linux/linux-kernel/mkinitcpio.md
```bash
#!/bin/bash
## /usr/lib/plymouth/plymouth-update-initrd
find /etc/mkinitcpio.d/ -name \*.preset -a \! -name example.preset | while read p; do
echo $p
# sudo mkinitcpio -p /etc/mkinitcpio.d/linux.preset*
done
```
更新内核:
```
配置参考: https://wiki.archlinux.org/index.php/Mkinitcpio_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)
启动镜像配置文件:
/etc/mkinitcpio.conf
/etc/mkinitcpio.d/linux.preset
$ cat /etc/mkinitcpio.d/linux.preset
# mkinitcpio preset file for the 'linux' package
ALL_config="/etc/mkinitcpio.conf"
ALL_kver="/boot/vmlinuz-linux"
PRESETS=('default' 'fallback')
#default_config="/etc/mkinitcpio.conf"
default_image="/boot/initramfs-linux.img"
#default_options=""
#fallback_config="/etc/mkinitcpio.conf"
fallback_image="/boot/initramfs-linux-fallback.img"
fallback_options="-S autodetect"
```
```
# mkinitcpio -p /etc/mkinitcpio.d/linux.preset*
```
<file_sep>/java/单点登陆/sso-shiro-cas.md
https://www.cnblogs.com/coderhuang/p/5897444.html
https://github.com/coder-huang/sso-shiro-cas<file_sep>/python/solutions/failed_to_install_lib.md
```
MySQL-python-1.2.5 will not compile against MariaDB 10.2 (libmariadb-dev)
error:
_mysql.c:2005:41: error: ‘MYSQL’ {aka ‘struct st_mysql’} has no member named ‘reconnect’
solution:
https://github.com/DefectDojo/django-DefectDojo/issues/407
$ sudo sed '/st_mysql_options options;/a unsigned int reconnect;' /usr/include/mysql/mysql.h -i.bkp
```
<file_sep>/sql/postgresql/vars.md
```
https://blog.csdn.net/dazuiba008/article/details/79268537
1.psql命令使用变量
表数据如下:
hank=> select * from tb2;
c1 | c2 | c3
----+-------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
2 | dazui | 2018-02-06 10:08:08.542481
3 | wahah | 2018-02-06 10:08:15.468527
4 | aaaaa | 2018-02-06 10:18:39.289523
SQL文本如下
cat hank.sql
select * from tb2 where c2=:name and c3>=:time;
通过psql查看
psql -v name="'hank'" -v time="'2018-02-06 10:08:00'" -f hank.sql
c1 | c2 | c3
----+------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
或者
psql -v name="'hank'" -v time="'2018-02-06 10:08:00'" -c '\i hank.sql'
c1 | c2 | c3
----+------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
2.\set使用变量
hank=> \set name hank
hank=> \set time '2018-02-06 10:09:00'
hank=> select * from tb2 where c2=:'name' and c3>=:'time';
c1 | c2 | c3
----+------+----------------------------
1 | hank | 2018-02-06 10:08:00.787503
3.通过定义参数实现
设置一个session级别的参数,通过current_setting取值
hank=> set session "asasd.time" to "2018-02-06 10:09:00";
SET
hank=> select * from tb2 where c3 >= current_setting('asasd.time')::timestamp;
c1 | c2 | c3
----+-------+----------------------------
4 | aaaaa | 2018-02-06 10:18:39.289523
(1 row)
```
<file_sep>/linux/arch/netctl.md
禁用NetworkManager,使用netctl 管理网络.
```bash
sudo systemctl stop NetworkManager
sudo systemctl disable NetworkManager
```
配置netcl:
```bash
cd /etc/netctl
sudo cp examples/ethernet-static ./enp0s25
```
网卡配置示例:
```
Description='enp0s25'
Interface=enp0s25
Connection=ethernet
IP=static
# Address 可配置多个:Address=('192.168.1.23/24' '192.168.1.87/24')
# 192.168.1.23 ip地址
# /24 子网掩码255.255.255.0
Address=('192.168.1.23/24')
Gateway='192.168.1.1'
DNS=('192.168.1.11' '192.168.1.12')
TimeoutUp=300
TimeoutCarrier=300
```
加载并启用配置:
```
sudo netctl enable enp0s25 # 会生成服务文件,开机启动
sudo netctl start enp0s25
```
其他配置参考 /etc/netctl/examples 下对应的文件来修改
```
wireless-wpa : wifi 动态ip
wireless-wpa-static : wifi 今天ip
ethernet-dhcp : 有线动态ip
```
<file_sep>/editor/vscode/使用技巧-模板.md
html:
```
文件保持为html 结尾
编辑文件: 输入! 然后tab补全
```
python :
```
参考 https://blog.csdn.net/jinxiaonian11/article/details/83542696
把代码片段写在json里。每个代码段都是在一个代码片段名称下定义的,并且有prefix、body和description。prefix是用来触发代码片段的。使用 $1,$2 等指定光标位置,这些数字指定了光标跳转的顺序,$0表示最终光标位置。
创建代码片段:python
编辑python 代码,输入prefix 触发代码
```
```json
{
"HEADER":{
"prefix": "header",
"body": [
"#!/usr/bin/env python",
"# -*- encoding: utf-8 -*-",
"'''",
"@File : $TM_FILENAME",
"@Time : $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
"@Author : xxx ",
"@Version : 1.0",
"@Contact : <EMAIL>",
"@License : (C)Copyright 2017-2019 ",
"@Desc : None",
"'''",
"",
"# here put the import lib",
"",
"#main",
"if __name__ == \"__main__\":",
"\tpass",
"$0"
],
}
}
```
java 代码片段配置:
```json
{
"base":{
"prefix": "base",
"body": [
"/**"
"@File : $TM_FILENAME",
"@Time : $CURRENT_YEAR/$CURRENT_MONTH/$CURRENT_DATE $CURRENT_HOUR:$CURRENT_MINUTE:$CURRENT_SECOND",
"@Author : xxx ",
"@Version : 1.0",
"@Contact : <EMAIL>",
"@License : (C)Copyright 2017-2019 ",
"@Desc : None",
"*/",
"public class $TM_FILENAME_BASE{",
"\tpublic $TM_FILENAME_BASE(){",
"\t}",
"\tpublic static void main(String[] args) {",
"\t}",
"}",
"$0"
]
}
}
```
<file_sep>/linux/softs/snmp/trap.md
# config
在snmptrapd.conf中加入以下指令:
authCommunity log,execute,net public
这条指令指明以“public”为“community”请求的snmp “notification”允许的操作。
各变量意义如下:
log: log the details of the notification - either in a specified file, to standard output (or stderr), or via syslog(or similar).
execute: pass the details of the trap to a specified handler program, including embedded perl.
net: forward the trap to another notification receiver.
若想对接收到的信息进行处理,可以使用traphandle,示例如下:
traphandle SNMPv2-MIB::coldStart /usr/nba/bin/traps cold
traphandle SNMPv2-MIB::warmStart /usr/nba/bin/traps warm
traphandle IF-MIB::linkDown /usr/nba/bin/traps down
traphandle IF-MIB::linkUp /usr/nba/bin/traps up
第一个参数为从snmptrapd接收的OID,第二个参数为调用的程序。此系统未做traphandle处理。
conf.example:
disableAuthorization yes
traphandle default /opt/test/trapcaller.sh
authCommunity execute public
#traphandle SNMPv2-MIB::sysLocation.0 /opt/test/lognotify
#traphandle SNMPv2-MIB::coldStart /opt/test/lognotify.sh cold
#traphandle default /usr/sbin/snmptthandler
#traphandle 1.3.6.1.4.1.2345 /opt/test/lognotify.sh
#traphandle default /opt/test/lognotify.sh
#traphandle default /opt/test/traphandle.pel
#traphandle default /opt/test/traphandle.py
#authCommunity log,execute,net public
authCommunity execute public
#ignoreauthfailure yes
runtrap reserver:
snmptrapd -c snmptrapd.conf -f -Le -d
注意:
不带-c,加载默认配置/etc/snmp/snmptrapd.conf
-c 会同时加载/etc/snmp/snmptrapd.conf 和 ./snmptrapd.conf , 如果这两个文件是同一个,handle会调两次
snmptrapd -f -Le -d
snmptrapd -c snmptrapd.conf -f -d -Dread_config : 查看配置加载情况
## usage
exmaple:
snmptrap -v 2c -c public 10.10.12.219 "aaa" 1.3.6.1.4.1.2345 SNMPv2-MIB::sysLocation.0 s "just here"
snmptrap -m ./sample-trap.mib -v 2c -c public 172.16.17.32:162 "" IBM-DW-SAMPLE::nodeDown IBM-DW-SAMPLE::nodeDown.1 s "M1"
snmptrap 命令
-v 2c Snmp协议版本
-c public 共同体
10.10.12.219 snmp代理的IP
"aaa" 主机名称, 可以为空
1.3.6.1.4.1.2345 Enterprise-OID
SNMPv2-MIB::sysLocation.0 数据OID
s 数据类型
"This is a test" 数据值
snmptrap -v 2c -c public agent_ip "" 1.3.6.1.4.1.2345 SNMPv2-MIB::sysLocation.0 s "just here"
snmptrap -v 2c -c public agent_ip "" coldStart
snmptrap enterpriseOID(generic OID) OID(subOID) type value
The TYPE is a single character, one of:
i INTEGER
u UNSIGNED
c COUNTER32
s STRING
x HEX STRING
d DECIMAL STRING
n NULLOBJ
o OBJID
t TIMETICKS
a IPADDRESS
b BITS
<file_sep>/golang/libs/redis.md
参考: <https://juejin.im/post/5e33f836f265da3df47aeb6f>
两个库
<https://github.com/gomodule/redigo>
<https://github.com/go-redis/redis>
<file_sep>/linux/solutions/1.md
```
error:
The name org.freedesktop.secrets was not provided by any .service files
solutions:
sudo pacman -S gnome-keyring libsecret
```
<file_sep>/linux/desktop-evn/kde/install_uninstall.md
archlinux
```
安装:
基础包
pacman -S plasma
完整包
pacman -S plasma-meta
最简安装(仅有桌面软件)
pacman -S plasma-desktop
然后是登录管理器SDDM
pacman -S sddm
将SDDM设置为开机自启动
systemctl enable sddm
--------------------------------------------------------
卸载
pacman -Rsc plasma
pacman -Rsc kde-applications
部分应用不会删除:比如kdeconnect
查询孤包选择性删除
pacman -Qdt
```
<file_sep>/linux/softs/snmp/mib.md
设置SNMP MIBs
MIBs默认在系统目录/usr/share/snmp/mibs下,
添加MIB名称到/etc/snmp/snmp.conf配置文件中(如果不存在则手动新建配置文件),它们将被Net-SNMP进程用来解析trap OID值。
例:mibs +JUNIPER-MIB:JUNIPER-FABRIC-CHASSIS:BGP4-MIB
<file_sep>/java/maven/plugins.md
参考:<https://www.cnblogs.com/avivaye/p/5341341.html>
### Maven本质上是一个插件框架,它的核心并不执行任何具体的构建任务,所有这些任务都交给插件来完成。
编译源代码是由maven-compiler-plugin完成的
每个任务对应了一个插件目标(goal),每个插件会有一个或者多个目标.
### 用户可以通过两种方式调用Maven插件目标。
第一种方式是将插件目标与生命周期阶段(lifecycle phase)绑定,这样用户在命令行只是输入生命周期阶段而已。
例如Maven默认将maven-compiler-plugin的compile目标与compile生命周期阶段绑定,因此命令mvn compile实际上是先定位到compile这一生命周期阶段,然后再根据绑定关系调用maven-compiler-plugin的compile目标。
第二种方式是直接在命令行指定要执行的插件目标。
例如mvn archetype:generate 就表示调用maven-archetype-plugin的generate目标,这种带冒号的调用方式与生命周期无关。
### Maven官方有两个插件列表:
第一个列表的GroupId为org.apache.maven.plugins,这里的插件最为成熟,具体地址为:<http://maven.apache.org/plugins/index.html>。
第二个列表的GroupId为org.codehaus.mojo,这里的插件没有那么核心,但也有不少十分有用,其地址为:<http://mojo.codehaus.org/plugins.html>。<file_sep>/linux/common/profile_source_order.md
系统登录顺序:
/etc/profile
/etc/profile.d/a.sh (a.sh自己建的)
/root/.bash_profile
/root/.bashrc
/etc/bashrc
/bin/bash 提供命令解释器(终端)
直接打/bin/bash 非登录shell
/root/.bashrc
/etc/bashrc
/etc/profile.d/a
可将别名alias等写入以上三个文件
bash 如何获取当前文件的绝对路径
```
#!/bin/bash
CURRENT_DIR=$(cd `dirname $0`;pwd)
echo $CURRENT_DIR
```
source 文件获取当前文件的绝对路径
```
#!/bin/bash
cd $(dirname $BASH_SOURCE)
CURRENT_DIR=$(pwd)
echo $CURRENT_DIR
#!/bin/bash
CURRENT_DIR=$(cd $(dirname $BASH_SOURCE);pwd)
```
<file_sep>/java/some_lib/redis.md
参考: <https://www.cnblogs.com/qlqwjy/p/8562703.html>
maven:
```xml
<!-- jedis依赖 , 使用时选择合适的版本-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.7.1</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.2.RELEASE</version>
</dependency>
<!-- 用于序列化的包 , 使用时选择合适的版本-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.1.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.1.0</version>
</dependency>
```
config:redis.properties
```
#访问地址
redis.host=127.0.0.1
#访问端口
redis.port=6379
#注意,如果没有password,此处不设置值,但这一项要保留
redis.password=
#最大空闲数,数据库连接的最大空闲时间。超过空闲时间,数据库连接将被标记为不可用,然后被释放。设为0表示无限制。
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制
redis.maxActive=600
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWait=1000
#在borrow一个jedis实例时,是否提前进行alidate操作;如果为true,则得到的jedis实例均是可用的;
redis.testOnBorrow=true
```
spring config:
```xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd ">
<!-- 连接池基本参数配置,类似数据库连接池 -->
<context:property-placeholder location="classpath:redis.properties"
ignore-unresolvable="true" />
<!-- redis连接池 -->
<bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
<property name="maxTotal" value="${redis.maxActive}" />
<property name="maxIdle" value="${redis.maxIdle}" />
<property name="testOnBorrow" value="${redis.testOnBorrow}" />
</bean>
<!-- 连接池配置,类似数据库连接池 -->
<bean id="jedisConnectionFactory"
class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
<property name="hostName" value="${redis.host}"></property>
<property name="port" value="${redis.port}"></property>
<!-- <property name="password" value="${<PASSWORD>}"></property> -->
<property name="poolConfig" ref="poolConfig"></property>
</bean>
<!--redis操作模版,使用该对象可以操作redis -->
<bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate" >
<property name="connectionFactory" ref="jedisConnectionFactory" />
<!--如果不配置Serializer,那么存储的时候缺省使用String,如果用User类型存储,那么会提示错误User can't cast to String!! -->
<property name="keySerializer" >
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer" />
</property>
<property name="valueSerializer" >
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer" />
</property>
<property name="hashKeySerializer">
<bean class="org.springframework.data.redis.serializer.StringRedisSerializer"/>
</property>
<property name="hashValueSerializer">
<bean class="org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer"/>
</property>
<!--开启事务 -->
<property name="enableTransactionSupport" value="true"></property>
</bean >
<!-- 下面这个是整合Mybatis的二级缓存使用的 -->
<bean id="redisCacheTransfer" class="cn.qlq.jedis.RedisCacheTransfer">
<property name="jedisConnectionFactory" ref="jedisConnectionFactory" />
</bean>
</beans>
```
note:
```
被缓存的类需要实现序列化接口 Serializable
```
<file_sep>/svg/标签介绍.md
start:
<?xml version="1.0" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<circle cx="100" cy="50" r="40" stroke="black"
stroke-width="2" fill="red"/>
</svg>
1. 矩形 rect
2. 圆形 circle
3. 椭圆 ellipse
4. 线 line
5. 折线 polyline
6. 多边形 polygon
7. 路径 path
1>. rect
rect 元素的 width 和 height 属性可定义矩形的高度和宽度
style 属性用来定义 CSS 属性
CSS 的 fill 属性定义矩形的填充颜色(rgb 值、颜色名或者十六进制值)
CSS 的 stroke-width 属性定义矩形边框的宽度
CSS 的 stroke 属性定义矩形边框的颜色
x 属性定义矩形的左侧位置(例如,x="0" 定义矩形到浏览器窗口左侧的距离是 0px)
y 属性定义矩形的顶端位置(例如,y="0" 定义矩形到浏览器窗口顶端的距离是 0px)
CSS 的 fill-opacity 属性定义填充颜色透明度(合法的范围是:0 - 1)
CSS 的 stroke-opacity 属性定义笔触颜色的透明度(合法的范围是:0 - 1)
CSS 的 opacity 属性定义整个元素的透明值(合法的范围是:0 - 1)
rx 和 ry 属性可使矩形产生圆角。
2>. circle
cx 和 cy 属性定义圆点的 x 和 y 坐标。如果省略 cx 和 cy,圆的中心会被设置为 (0, 0)
r 属性定义圆的半径。
3>. ellipse
cx 属性定义圆点的 x 坐标
cy 属性定义圆点的 y 坐标
rx 属性定义水平半径
ry 属性定义垂直半径
4>. line
x1 属性在 x 轴定义线条的开始
y1 属性在 y 轴定义线条的开始
x2 属性在 x 轴定义线条的结束
y2 属性在 y 轴定义线条的结束
5>. polygon
points 属性定义多边形每个角的 x 和 y 坐标
<polygon points="220,100 300,210 170,250"
6>. polyline
创建仅包含直线的形状
<polyline points="0,0 0,20 20,20 20,40 40,40 40,60"
7>. path
下面的命令可用于路径数据:
M = moveto
L = lineto
H = horizontal lineto
V = vertical lineto
C = curveto
S = smooth curveto
Q = quadratic Belzier curve
T = smooth quadratic Belzier curveto
A = elliptical Arc
Z = closepath
以上所有命令均允许小写字母。大写表示绝对定位,小写表示相对定位。
<path d="M250 150 L150 350 L350 350 Z" />
SVG 滤镜
在 SVG 中,可用的滤镜有:
feBlend
feColorMatrix
feComponentTransfer
feComposite
feConvolveMatrix
feDiffuseLighting
feDisplacementMap
feFlood
feGaussianBlur
feImage
feMerge
feMorphology
feOffset
feSpecularLighting
feTile
feTurbulence
feDistantLight
fePointLight
feSpotLight
可以在每个 SVG 元素上使用多个滤镜!
必须在 <defs> 标签中定义 SVG 滤镜。
高斯模糊(Gaussian Blur)
<filter> 标签用来定义 SVG 滤镜。<filter> 标签使用必需的 id 属性来定义向图形应用哪个滤镜?
<filter> 标签必须嵌套在 <defs> 标签内。<defs> 标签是 definitions 的缩写,它允许对诸如滤镜等特殊元素进行定义
<feGaussianBlur> 标签的 stdDeviation 属性可定义模糊的程度
SVG 渐变必须在 <defs> 标签中进行定义。
线性渐变
放射性渐变
<linearGradient> 用来定义 SVG 的线性渐变
当 y1 和 y2 相等,而 x1 和 x2 不同时,可创建水平渐变
当 x1 和 x2 相等,而 y1 和 y2 不同时,可创建垂直渐变
当 x1 和 x2 不同,且 y1 和 y2 不同时,可创建角形渐变
水平渐变: x1="0%" y1="0%" x2="100%" y2="0%"
垂直渐变: x1="0%" y1="0%" x2="0%" y2="100%"
<radialGradient> 用来定义放射性渐变。
<file_sep>/python/flask/appbuilder/6_flask.md
flask:
文档:
<http://flask.pocoo.org/docs/1.0/>
<http://docs.jinkan.org/docs/flask/index.html>
<file_sep>/js/node/npm_install.md
npm 与cnpm 用法基本一致。
```
npm的包安装分为本地安装(local)、全局安装(global)两种,从敲的命令行来看,差别只是有没有-g而已
本地: 就项目路径而言,就是package.json 所在的目录。
全局:npm install <package_name> -g , 安装之后所有项目可用(部分包包含命令工具,命令所在目录会加入到 PATH 中,命令行里可直接键入命令使用)
```
```
package.json
包含项目属性:name,version ,author,description (部分配置可选)
包含项目打包,运行,调用:scripts (可选)
包含项目运行依赖:dependencies (可选)
包含项目开发依赖:devDependencies (可选)
engines (可选)
browserslist (可选)
。。。。
```
```
npm init
初始化js 项目:生成package.json
```
```
依赖包安装
(本地安装,执行npm 目录 与package.josn 同级)
npm install <package_name> --save命令会添加条目到package.json的dependencies中。
npm install <package_name> --save-dev命令会添加条目到package.json的devDependencies中。
包安装位置: package.json 同级目录的node_modules 目录下。
安装指定版本的包: npm install <package_name>@<version>
```
```
npm i -f 强制安装
npm ci :与npm install 类似 , https://blog.csdn.net/csdn_yudong/article/details/84929546
```
<file_sep>/C_or_C++/进制.md
```
二进制:B
(10110011)2,或写成10110011B
八进制:O
(352.264)8或352.264O
十进制:D
十六进制:H , 0x以表示十六进制数
```
<file_sep>/linux/common/manager.md
https://linux.cn/article-9373-1.html#3_2227<file_sep>/python/snmp/agent/snmpsim.md
```
pip install snmpsim
启动agent:
snmpsimd.py --data-dir = ./data --agent-udpv4-endpoint = 127 .0.0.1:1024
cat ./data/public.snmprec
1 .3.6.1.2.1.1.1.0 | 4 | Linux的2 .6.25.5-SMP SMP周二6月19日 14:58:11 CDT 2007年的i686
1 .3.6.1.2.1.1.2.0 | 6 | 1 .3.6.1.4.1.8072.3.2.10
1 .3.6.1.2.1.1.3.0 | 67 | 233425120
1 .3.6.1.2.1.2.2.1.6.2 | 4x | 00127962f940
1 .3.6.1.2.1.4.22.1.3.2.192.21.54.7 | 64x | c3dafe61
。。。。。
之后可用snmp 命令获取数据。
从一些现有的SNMP代理生成模拟数据:
snmprec.py --agent-udpv4-endpoint=demo.snmplabs.com --output-file public.snmprec
从MIB文件构建模拟数据
mib2dev.py --output-file public.snmprec --mib-module IF-MIB
snmpsim 自带一些模拟数据
可通过数据库或代码脚本使调用时获得不同的数据。
```
<file_sep>/linux/Fedora_Linux/redhat/profile_$0.md
# 使用source执行 profile 得到的 $0 不正确
dirname: invalid option -- 'b'
Try `dirname --help' for more information.
# $0都改为$BASH_SOURCE[0]<file_sep>/golang/function.md
```go
// func function_name (arsgs)(return values)
func swap(x, y string) (string, string) {
return y, x
}
func split(sum int) (x, y int) {
x = sum * 4 / 9
y = sum - x
return
}
```
<file_sep>/linux/devops/sonarqube/0_install.md
官网:
```
https://www.sonarqube.org/
```
下载地址:
```
https://binaries.sonarsource.com
社区版:
https://binaries.sonarsource.com/Distribution/sonarqube/
企业版:
https://binaries.sonarsource.com/CommercialDistribution/sonarqube-enterprise/
```
下载后解压即可。<file_sep>/linux/arch/pacman.md
pacman:
pacman -S :安装
pacman -Ss :查询
pacman -R :删除
pacman -Rs :删除包和其依赖
pacman -Qs :查询已安装包
pacman -Qi :显示查找的包的信息
pacman -Ql:显示包的文件安装位置
pacman -Sw :下载包但不安装
pacman -U path/。。。 : 安装本地的包
pacman -Scc : 清除缓存
pacman -Syu :升级系统的包
pacman -Qm: 查找不在官方库安装的软件包
pacman -Qk,pacman -Qkk: 检查安装的包是否缺少文件
pacman -F 文件名(软件包中的一个文件) : 要在远程软件包中搜索软件包文件名 与pkgfile 功能差不多,显示内容更详细。
删除单个软件包,保留其全部已经安装的依赖关系
pacman -R package_name
删除指定软件包,及其所有没有被其他已安装软件包使用的依赖关系:
pacman -Rs package_name
要删除软件包和所有依赖这个软件包的程序:
# pacman -Rsc package_name
警告: 此操作是递归的,请小心检查,可能会一次删除大量的软件包。
要删除软件包,但是不删除依赖这个软件包的其他程序:
# pacman -Rdd package_name
pacman 删除某些程序时会备份重要配置文件,在其后面加上*.pacsave扩展名。-n 选项可以删除这些文件:
pacman -Rn package_name
pacman -Rsn package_name
```
清理无用的安装包:
# pacman -Rns $(pacman -Qdtq)
$ yaourt -Qdt
```
pacman -Qlk 检查包是否损坏: sudo pacman -Qlk| grep "missing files"| grep -v "0 missing files"
---
solutions:
exists in filesystem
```
pacman-filename-exists-in-filesystem
Check what package includes the filename
# pacman -Qo filename
If you're sure you know what you're doing, you can use the --overwrite option, eg:
pacman -S package-name --overwrite filename
or
pacman -S package-name --overwrite '*'
```
```
unable to lock database
sudo rm /var/lib/pacman/db.lck
```
<file_sep>/bigdata/hadoop_spark_install.md
参考: https://www.cnblogs.com/wolf-song/p/7708472.html
下载 :
``` markdown
1. jdk
2. hadoop
3. spark
```
系统配置:
``` markdown
1. jdk 配置
2. 节点免密登录配置
3. 关闭selinux
4. 关闭防火墙
```
安装hadoop:
``` markdown
1. 解压压缩包
2. 配置配置文件
PATH:
hadoop/etc/hadoop
FILES:
Core.xml
Hdfs-site.xml
Mapred-site.xml
Yarn-site.xml
Slaves
3. 配置运行环境变量
hadoop-env.sh yarn-env.sh
4. 分发
5. 初始化启动:
bin/hdfs namenode -format
sbin/start-dfs.sh
6. jps 检查启动情况
```
安装Spark:
``` stylus
1. 配置系统环境
/etc/profile
export SPARK_HOME=/XXX
export PATH=$PATH:$SPARK_HOME/bin:$SPARK_HOME/sbin
2. 配置spark:
conf/spark-env.sh
export SPARK_MASTER_IP=sparkmaster
export SPARK_MASTER_PORT=7077
export SPARK_WORKER_CORES=1
export SPARK_WORKER_INSTANCES=1
export SPARK_WORKER_MEMORY=512M
export SPARK_LOCAL_IP=ip # 每个节点的ip
3. slave 配置:
conf/slaves
host1
host2
```
<file_sep>/sql/postgresql/random.md
```
SELECT RANDOM(); 0~1 的小数
取介于两数之间的随机数
SELECT random()*(b-a)+a;
SELECT random()*(25-10)+10;
取介于两数之间的随机整数
SELECT floor(random()*(b-a)+a);
SELECT floor(random()*(25-10)+10);
```
<file_sep>/linux/softs/ffmpeg/base_linux.md
Linux
```
查看设备:
ffmpeg -hide_banner -devices
D: 输入设备
E: 输出设备
查看设备支持的参数
ffmpeg -h demuxer=<设备>
ffmpeg -h demuxer=fbdev
设备说明:
x11grab: 屏幕输出
屏幕录制:
ffmpeg -f x11grab -framerate 30 -video_size 1024*800 -i :0.0 out.mp4
-i :0.0+300,200
:0.0 display 号: 可通过echo $DISPLAY 获得。
300 开始坐标x
200 开始坐标y
```
<file_sep>/js/knockout/1_base_types.md
```js
ko.observable("")
ko.observable(123)
http://www.aizhengli.com/knockoutjs/53/knockout-observables-arrays.html
var myObservableArray= ko.observableArray(["",""])
myObservableArray().length
myObservableArray()[index]
push,pop,unshift,shift,reverse,sort,removeAll
ko.observable(true);
ko.observable(false)
array:
ko.observableArray();
ko.observable([])
```
<file_sep>/js/jquery/fn.md
```
jquery 两种函数调用方式:
---------------------------------------------------------------------------------
$.函数名 [jquery 有若干函数] [ 函数实例调用: 函数及实例: ]
A=function(){}
A.x = function(){}
A.x()
不能使用 new A().x()
---------------------------------------------------------------------------------
$("选择器").函数名 : [ $("选择器"): 返回一个 可以调用jquery 函数的对象] : [实例调用]
B = function(){}
B.prototype.x = function(){}
new B().x()
不能使用: B.x()
---------------------------------------------------------------------------------
A.prototype = B.prototype;
可使用 new A().x()
####################################################################################
jQuery = function( selector, context ) {
return new jQuery.fn.init( selector, context, rootjQuery );
// new 了一个init(), init 的 prototype ==
}
jQuery.fn.init.prototype = jQuery.fn; : init() == new jqueryobject()
-------------------------------------
A: Jquery
B: init
A = function() {
return new B();
}
B.prototype = A.prototype;
扩展A 的原型, new A()可也可使用[new B 的实例].
extend(): 修复fn : 扩展函数方法
```
<file_sep>/linux/softwaremanager/pacman/pack_struct.md
```
.BUILDINFO
.INSTALL
.MTREE
.PKGINFO
```
<file_sep>/linux/Fedora_Linux/redhat/rhel7_install_gui.md
```
yum grouplist
yum groupinstall "X Window System"
yum groupinstall -y "Server with GUI"
systemctl set-default graphical.target
```
<file_sep>/sql/postgresql/index.md
https://www.cnblogs.com/jiaoyiping/p/7191300.html
## 索引类型
PostgreSQL提供了几种索引类型:B-tree,Hash,GiST,SP-GiST,GIN和BRIN。每个索引类型使用不同的算法,适合不同种类的查询。默认情况下,CREATE INDEX命令创建B-tree索引
```
CREATE INDEX <index_name> ON <table_name> (filex);
CONCURRENTLY: 第二索引
CREATE UNIQUE INDEX CONCURRENTLY ON <table_name> USING btree(filex);
```
```
删除索引
ALTER TABLE <table_name> DROP CONSTRAINT <index_name>; ( 删除主键索引)
dorp index <index_name> ; (删除普通索引)
添加主键
ALTER TABLE <table_name> ADD CONSTRAINT <index_name> primary key (filed1, field2);
```
```
更新已有索引为主键:
ALTER TABLE <table_name>
ADD CONSTRAINT <index_name>
PRIMARY KEY USING INDEX <exist_index_name>;
```
```sql
-- 创建序列
create sequence seq_test_1 INCREMENT by 1 MINVALUE 1 NO MAXVALUE start with 1 ;
--查看序列属性
\d seq_test_1
-- 查看序列最近使用值
select currval('seq_test_1');
-- 序列重置
select setval('seq_test_1',100);
alter sequence seq_test_1 restart with 200;
-- 下一个序列值
select nextval('seq_test_1');
```
<file_sep>/python/flask/appbuilder/5_security.md
### falsk appbuilder 权限控制
查询数据库中的所有权限(可通过查询权限相关表获取数据)
```
# db connection session
sesh = appbuilder.get_session()
# query
pvms = sesh.query(ab_models.PermissionView).all()
for pvm in pvms:
print(pvm)
```
SecurityManager:
```
# SecurityManager,
# appbuilder 初始化时附带数据库,SecurityManager 封装了权限相关表的操作。
sm = appbuilder.sm
# sm: SecurityManager 的一些函数
# role 相关
# permission 相关
# user 相关
# permission_role 相关
# permission_on_views 相关
# permission_view_menu 相关
# views 相关
```
<file_sep>/linux/softs/vim.md
vim 鼠标左键选中文字时显示 VISUAL : (由于开启了鼠标)
```
编辑 ~/.vimrc 添加如下内容
set mouse-=a
```
记住上次编辑位置
```
"remember last update or view postion"
" Only do this part when compiled with support for autocommands
if has("autocmd")
" In text files, always limit the width of text to 78 characters
autocmd BufRead *.txt set tw=78
" When editing a file, always jump to the last cursor position
autocmd BufReadPost *
\ if line("'\"") > 0 && line ("'\"") <= line("$") |
\ exe "normal g'\"" |
\ endif
endif
```
代码格式化:
https://www.cnblogs.com/AI-Algorithms/p/3774409.html
```
格式化全文指令 gg=G
备注:
gg —— 到达文件最开始
= —— 要求缩进
G —— 直到文件尾
```
```
gg
shift+v
shift+G
=
```
替换: https://blog.csdn.net/cbaln0/article/details/87979056
```
#将当前行第一个a替换为b
:s/a/b/
#将当前行第一个a替换为b
:s/a/b/
#将每行第一个a替换为b
:%s/a/b
#将整个文件的所有a替换为b
:%s/a/b/g
#将1至3行的第一个a替换为b
:1,3s/a/b/
#将1至3行的所有a替换为b
:1,3s/a/b/g
```
```
:s/^/\=range(5, 100) 生成一段数字
:s/^/\=range(5, 100, 2) 生成一段数字,并指定步长
```
插入递增列:
```
先在要插入这样递增数列的地方插入一个全文不会重复出现的字母序列,比如的是zcc,然后输入命令
:let i=0 | g/zcc/s//\=i/ | let i=i+1
```
```
先选择需要插入数字的列(空白列)
:'<,'>s/^/\=line(".")
'<,'> : 在选中列后输入 : 会自动生成
=后可以用. 拼接内容 =line(".").','
```
<file_sep>/linux/shell_script/read.md
1、基本读取
```
!/bin/bash
echo -n "Enter your name:" //参数-n的作用是不换行,echo默认是换行
read name //从键盘输入
echo "hello $name" //显示信息
exit 0
#!/bin/bash
read -p "Enter your name:" name
echo "hello $name"
exit 0
```
2、计时输入.
```
#!/bin/bash
if read -t 5 -p "please enter your name:" name
then
echo "hello $name ,welcome to my script"
else
echo "sorry,too slow"
fi
exit 0
# -t选项指定read命令等待输入的秒数。当计时满时,read命令返回一个非零退出状态;
```
```
#!/bin/bash
read -n1 -p "Do you want to continue [Y/N]?" answer
case $answer in
Y | y)
echo "fine ,continue";;
N | n)
echo "ok,good bye";;
*)
echo "error choice";;
esac
exit 0
# -n选项,后接数值1,指示read命令只要接受到一个字符就退出。只要按下一个字符进行回答,read命令立即
# 接受输入并将其传给变量。无需按回车键。
```
3、默读(输入不显示在监视器上)
```
#!/bin/bash
read -s -p "Enter your password:" pass
echo "your password is $pass"
exit 0
# -s选项能够使read命令中输入的数据不显示在监视器上(实际上,数据是显示的,只是read命令将文本颜色设置成
# 与背景相同的颜色)。
```
4、读文件
```
#!/bin/bash
count=1
cat test | while read line //cat 命令的输出作为read命令的输入,read读到的值放在line中
do
echo "Line $count:$line"
count=$[ $count + 1 ] //注意中括号中的空格。
done
echo "finish"
exit 0
```
<file_sep>/python/uuid_test.py
#coding=utf-8
import uuid
name = 'test_name'
namespace = 'test_namespace'
print uuid.uuid1()
print uuid.uuid3(namespace,name)
print uuid.uuid4()
print uuid.uuid5(namespace,name)
'''
python中的uuid模块基于信息如MAC地址、时间戳、命名空间、随机数、伪随机数来uuid。具体方法有如下几个:
uuid.uuid1() 基于MAC地址,时间戳,随机数来生成唯一的uuid,可以保证全球范围内的唯一性。
uuid.uuid2() 算法与uuid1相同,不同的是把时间戳的前4位置换为POSIX的UID。不过需要注意的是python中没有基于DCE的算法,所以python的uuid模块中没有uuid2这个方法。
uuid.uuid3(namespace,name) 通过计算一个命名空间和名字的md5散列值来给出一个uuid,所以可以保证命名空间中的不同名字具有不同的uuid,但是相同的名字就是相同的uuid了
uuid.uuid4() 通过伪随机数得到uuid,是有一定概率重复的
uuid.uuid5(namespace,name) 和uuid3基本相同,只不过采用的散列算法是sha1
'''<file_sep>/sql/postgresql/时间.md
```
时区:
------------------------------------------------------------------------
方法1:
修改postgresql.conf的如下配置项
log_timezone = 'US/Pacific'
timezone = 'US/Pacific'
=>
log_timezone = 'Asia/Shanghai'
timezone = 'Asia/Shanghai'
修改完毕之后,重新加载配置
pg_ctl -D <data_path> reload
------------------------------------------------------------------------
方法2:
select now() at time zone 'Asia/Shanghai'
ALTER DATABASE <database_name> SET timezone TO 'Asia/Shanghai'
```
```
参考: http://www.postgres.cn/docs/9.4/functions-formatting.html
时间类型转换
to_char 时间转字符串
to_char(timestamp, text)
```
<file_sep>/sql/postgresql/备份还原.md
导出整个数据库(包含schema 和data)
pg_dump -h localhost -U postgres(用户名) 数据库名(缺省时同用户名) >/data/dum.sql
example:
./pg_dump -h localhost -U postgres -d devb -p 6326 >/tmp/devb.sql
导出某个表
pg_dump -h localhost -U postgres(用户名) 数据库名(缺省时同用户名) -t table(表名) >/data/dum.sql
执行sql文件
psql -h localhost -d 数据库名 -U 用户名 -f .sql文件
copy拷贝表中数据
COPY employee TO '/home/smallfish/employee.sql';
```
pg_dump 参数:
--column-inserts dump data as INSERT commands with column names以带有列名的INSERT命令形式转储数据
--inserts dump data as INSERT commands, rather than COPY
-s, --schema-only dump only the schema, no data只转储模式, 不包括数据(不导出数据)
-a, --data-only dump only the data, not the schema只导出数据,不包括模式
eg:
pg_dump -h <server> -U <user_name> <database_name> -t <table_name> --inserts -a
pg_dump -h <server> -U <user_name> <database_name> -t <table_name> -s
```
<file_sep>/linux/Fedora_Linux/yum/yum.md
软件安装:
``` bash
参考: http://man.linuxde.net/yum
# yum install -y <packname>
install:安装rpm软件包;
update:更新rpm软件包;
check-update:检查是否有可用的更新rpm软件包;
remove:删除指定的rpm软件包;
list:显示软件包的信息;
search:检查软件包的信息;
info:显示指定的rpm软件包的描述信息和概要信息;
clean:清理yum过期的缓存;
shell:进入yum的shell提示符;
resolvedep:显示rpm软件包的依赖关系;
localinstall:安装本地的rpm软件包;
localupdate:显示本地rpm软件包进行更新;
deplist:显示rpm软件包的所有依赖关系。
yum --help: 查看所有参数
```
下载不安装:
```
参考:https://www.cnblogs.com/wangmo/p/7205528.html
# yum install -y yum-utils
# yumdownloader <package-name>
resolve下载依赖
# yumdownloader <package-name> --resolve
yum install --downloadonly --downloaddir=/tmp <package-name>
```
```
检查包是否安装
yum list installed <packname>
```
yum 源:
```
http://mirrors.163.com/.help/centos.html
http://mirrors.ustc.edu.cn/help/
```
<file_sep>/C_or_C++/somefuntion/strstarts.md
```c
// startWith: 使用strncmp 前n个字符相同,相同返回0
static inline bool strstarts(const char *str, const char *prefix)
{
return strncmp(str, prefix, strlen(prefix)) == 0;
}
```
<file_sep>/linux/Fedora_Linux/rpm/rpmbuild.md
```
Usage: rpmbuild [OPTION...]
Build options with [ <specfile> | <tarball> | <source package> ]:
-bp build through %prep (unpack sources and apply patches) from <specfile>
-bc build through %build (%prep, then compile) from <specfile>
-bi build through %install (%prep, %build, then install) from <specfile>
-bl verify %files section from <specfile>
-ba build source and binary packages from <specfile>
-bb build binary package only from <specfile>
-bs build source package only from <specfile>
-tp build through %prep (unpack sources and apply patches) from <tarball>
-tc build through %build (%prep, then compile) from <tarball>
-ti build through %install (%prep, %build, then install) from <tarball>
-ta build source and binary packages from <tarball>
-tb build binary package only from <tarball>
-ts build source package only from <tarball>
--rebuild build binary package from <source package>
--recompile build through %install (%prep, %build, then install) from <source package>
--buildroot=DIRECTORY override build root
--clean remove build tree when done
--nobuild do not execute any stages of the build
--nodeps do not verify build dependencies
--nodirtokens generate package header(s) compatible with (legacy) rpm v3 packaging
--noclean do not execute %clean stage of the build
--nocheck do not execute %check stage of the build
--rmsource remove sources when done
--rmspec remove specfile when done
--short-circuit skip straight to specified stage (only for c,i)
--target=CPU-VENDOR-OS override target platform
Common options for all rpm modes and executables:
-D, --define='MACRO EXPR' define MACRO with value EXPR
--undefine=MACRO undefine MACRO
-E, --eval='EXPR' print macro expansion of EXPR
--macros=<FILE:...> read <FILE:...> instead of default file(s)
--noplugins don't enable any plugins
--nodigest don't verify package digest(s)
--nosignature don't verify package signature(s)
--rcfile=<FILE:...> read <FILE:...> instead of default file(s)
-r, --root=ROOT use ROOT as top level directory (default: "/")
--dbpath=DIRECTORY use database in DIRECTORY
--querytags display known query tags
--showrc display final rpmrc and macro configuration
--quiet provide less detailed output
-v, --verbose provide more detailed output
--version print the version of rpm being used
Options implemented via popt alias/exec:
--with=<option> enable configure <option> for build
--without=<option> disable configure <option> for build
--buildpolicy=<policy> set buildroot <policy> (e.g. compress man pages)
--sign generate GPG signature (deprecated, use command rpmsign instead)
Help options:
-?, --help Show this help message
--usage Display brief usage message
```
```
rpmbuild -ba 'spec文件路径'
/root/rpmbuild/SOURCES 源码存放路径
/root/rpmbuild/SPECS spec 文件路径
打包完成会生成:/root/rpmbuild/RPMS
```
```
引用:
https://blog.csdn.net/u012373815/article/details/73257754
https://fedoraproject.org/wiki/How_to_create_an_RPM_package/zh-cn
xxx.spec
Name: hellorpm #名字为源码tar.gz 包的名字
Version: 1.0.0 #版本号,一定要与tar.gz包的一致哦
Release: 1%{?dist} #释出号,也就是第几次制作rpm
Summary: helloword #软件包简介,最好不要超过50字符
License: GPL #许可,GPL还是BSD等
URL: #可以写一个网址
Packager: abel
Source0: %{name}-%{version}.tar.gz
#定义用到的source,也就是你的源码
BuildRoot: %_topdir/BUILDROOT
#这个是软件make install 的测试安装目录.
BuildRequires: gcc,make #制作过程中用到的软件包
Requires: python-apscheduler >= 2.1.2-1.el7,python-daemon >= 1.6-1.el7 #软件运行依赖的软件包,也可以指定最低版本如 bash >= 1.1.1
%description #描述,随便写
%prep #打包开始
%setup -q #这个作用静默模式解压并cd
%build #编译制作阶段,主要目的就是编译,如果不用编译就为空
./configure \
%{?_smp_mflags} #make后面的意思是:如果就多处理器的话make时并行编译
%install #安装阶段
rm -rf %{buildroot} #先删除原来的安装的,如果你不是第一次安装的话
cp -rp %_topdir/BUILD/%{name}-%{version}/* $RPM_BUILD_ROOT
#将需要需要打包的文件从BUILD 文件夹中拷贝到BUILDROOT文件夹下。
#下面的几步pre、post、preun、postun 没必要可以不写
%pre #rpm安装前制行的脚本
%post #安装后执行的脚本
%preun #卸载前执行的脚本
%postun #卸载后执行的脚本
%clean #清理段,删除buildroot
rm -rf %{buildroot}
%files #rpm要包含的文件
%defattr (-,root,root,-) #设定默认权限,如果下面没有指定权限,则继承默认
/etc/hello/word/helloword.c #将你需要打包的文件或目录写下来
### 7.chagelog section 改变日志段
%changelog
```
<file_sep>/linux/softs/wrf/1.baseusage.md
```
export NETCDF=/opt/netcdf-fortran
export LD_LIBRARY_PATH=/opt/netcdf-fortran/lib/
export PATH=/opt/WPS:/opt/WPS/util:$PATH
```
基础用法参考:<https://xg1990.com/blog/archives/206>
<file_sep>/java/note_spring/aop不生效.md
```
spring(applicationContext):aop 放在此处不生效
SpringMVC(webApplicationContext):aop
i18n 配置 放在applicationContext或webApplicationContext都可以
```
```xml
<aop:aspectj-autoproxy proxy-target-class="true" />
<!--处理切入点对应的处理类-->
<bean id="dealBean" class="com.xxxx.common.ResultInterceptor"/>
<aop:config proxy-target-class="true">
<!--切面-->
<aop:pointcut id="dealPointcut" expression="execution(* com.example..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)"/>
<!--切入点-->
<aop:aspect order="3" ref="dealBean" >
<aop:around method="aroundMethod" pointcut-ref="dealPointcut" />
</aop:aspect>
</aop:config>
```
参考:https://blog.csdn.net/weixin_39214481/article/details/80027465
<file_sep>/linux/build/linux_perf.md
```
dependence: flex ,bison
cd tools/perf
make
```
<file_sep>/linux/tools/sysstat.md
```
yum install systat -y
sysstat工具包中有很多的分析命令
常用的有:sar, iostat, mpstat(multi processor stat), pidstat, vmstat等等。
参考:https://www.cnblogs.com/digdeep/p/4878138.html
```
<file_sep>/python/somelib/redis.md
```python
import redis
pool = redis.ConnectionPool(host=host, port=port,db=0)
client = pool.getConnect()
pip = client.pipeline()
client.info()
```
<file_sep>/linux/software_source/sites.md
```
http://mirrors.163.com/
http://mirrors.sohu.com
http://mirrors.ustc.edu.cn/
https://mirrors.ustc.edu.cn/
http://mirrors.aliyun.com/ https://opsx.alibaba.com/mirror
https://mirror.tuna.tsinghua.edu.cn/
http://mirrors.zju.edu.cn/
http://mirror.hust.edu.cn/
http://ftp.sjtu.edu.cn/
http://mirrors.yun-idc.com/
https://mirror.bjtu.edu.cn/
http://mirror.bit.edu.cn
https://mirrors.huaweicloud.com/
```
<file_sep>/python/somelib/wmi.md
# windows cpus
import wmi
w=wmi.WMI()
cpus=w.Win32_Processor()
for u in cpus:
print 'cpu id:',u.ProcessorId
print u
# windows net speed
import win32pdh,time
def netstat() :
object = "Network Interface"
items, instances = win32pdh.EnumObjectItems( None, None, object, win32pdh.PERF_DETAIL_WIZARD )
ifs = {}
for interface in instances:
hq = win32pdh.OpenQuery()
hcs = [ ]
item = "Bytes Total/sec"
path = win32pdh.MakeCounterPath( ( None, object, interface, None, 0, item ) )
hcs.append( win32pdh.AddCounter( hq, path ) )
win32pdh.CollectQueryData( hq )
time.sleep( 0.01 )
win32pdh.CollectQueryData( hq )
for hc in hcs:
type, val = win32pdh.GetFormattedCounterValue( hc, win32pdh.PDH_FMT_LONG )
win32pdh.RemoveCounter( hc )
win32pdh.CloseQuery( hq )
ifs[interface] = val
return ifs
while 1:
interfaces = netstat()
for interface in interfaces:
print interface,' Current netload: ' + str(interfaces[interface]) + 'B/s'
time.sleep(1)<file_sep>/sql/redis/data_types.md
数据类型
```
String
Hash
List
Set
Zset
```
String:
```
set key value
get key
del key
```
Hash:
```
HMSET mainkey key1 value1 key2 vaue2
HGET mainkey key1
HGET mainkey key2
HGETALL mainkey
```
List:
```
lpush key value
lrange key start end
lindex key index
len key
lpop key
lset key index value
ltrim keys start stop (ltrim key 1 0 : empty the list)
```
Set:
```
sadd key value1
sadd key value2
smembers key
```
Zset:
```
zadd key score member
ZRANGEBYSCORE key start end
```<file_sep>/sql/mysql/db.md
```sql
CREATE DATABASE `mydb` CHARACTER SET utf8 COLLATE utf8_general_ci;
```
<file_sep>/golang/base/4_map.md
```go
/* 声明变量,默认 map 是 nil */
var map_variable map[key_data_type]value_data_type
/* 使用 make 函数,初始化 */
map_variable := make(map[key_data_type]value_data_type)
```
```
```
<file_sep>/golang/daemon/service.md
```
github.com/kardianos/service
https://studygolang.com/articles/12904
```
<file_sep>/linux/arch/archlinuxcn.md
<https://github.com/archlinuxcn/mirrorlist-repo>
主站点:
https://mirrors.sjtug.sjtu.edu.cn/#/
https://mirrors.ustc.edu.cn/ (根据使用的电信服务商配置域名可更快访问)
https://mirrors.tuna.tsinghua.edu.cn/
https://mirrors.cloud.tencent.com/
https://mirrors.cqu.edu.cn/
https://mirrors.163.com/
https://mirrors.ocf.berkeley.edu/
https://mirrors.zju.edu.cn/
https://mirrors.ustc.edu.cn/
https://mirror.xtom.com/
https://mirror.xtom.com.hk
https://mirrors.huaweicloud.com/
仅archlinuxcn:
https://repo.archlinuxcn.org/
/etc/pacman.conf
```
[archlinuxcn]
Server = 主站点/archlinuxcn/$arch
-------------------------------------------------------
[archlinuxcn]
Server = https://repo.archlinuxcn.org/$arch
```
```
#[testing]
#Include = /etc/pacman.d/mirrorlist
[core]
Include = /etc/pacman.d/mirrorlist
[extra]
Include = /etc/pacman.d/mirrorlist
#[community-testing]
#Include = /etc/pacman.d/mirrorlist
[community]
Include = /etc/pacman.d/mirrorlist
# If you want to run 32 bit applications on your x86_64 system,
# enable the multilib repositories as required here.
#[multilib-testing]
#Include = /etc/pacman.d/mirrorlist
[multilib]
Include = /etc/pacman.d/mirrorlist
-------------------------------------------------------------
[$repo]
Include = /etc/pacman.d/mirrorlist
```
Add PGP Keys
```
sudo pacman -Syy && sudo pacman -S archlinuxcn-keyring
```
mirrorlist
```
Server = 主站点/archlinux/$repo/os/$arch
-------------------------------------------------------
# 163
#Server = http://mirrors.163.com/archlinux/$repo/os/$arch
# 清华
#Server = https://mirrors.tuna.tsinghua.edu.cn/archlinux/$repo/os/$arch
# 上海交通大学
#Server = https://mirrors.sjtug.sjtu.edu.cn/archlinux/$repo/os/$arch
```
<file_sep>/linux/software_source/centos.md
```
CentOS5 :http://mirrors.163.com/.help/CentOS5-Base-163.repo
CentOS6 :http://mirrors.163.com/.help/CentOS6-Base-163.repo
CentOS7 :http://mirrors.163.com/.help/CentOS7-Base-163.repo
https://lug.ustc.edu.cn/wiki/mirrors/help/centos
https://mirror.tuna.tsinghua.edu.cn/help/centos/
http://mirrors.zju.edu.cn/#generator
```
<file_sep>/editor/vscode/sftp.md
SFTP liximomo.sftp
```
[
{
"name": "server1",
"context": "project/build", // 本地路径
"host": "host",
"username": "username",
"password": "<PASSWORD>",
"remotePath": "/remote/project/build" // 远程路径
},
{
"name": "server2",
"context": "project/src",
"host": "host",
"username": "username",
"password": "<PASSWORD>",
"remotePath": "/remote/project/src"
}
]
```
可配置多个同步路径
<file_sep>/linux/softs/emoji.md
emoji 不能正确显示
安装包: noto-fonts-emoji
<file_sep>/sql/postgresql/extension.md
```
# create extension pgcrypto;
```
https://www.postgresql.org/docs/9.1/extend-extensions.html
以 .control 为后缀。<file_sep>/python/0_download.md
python 下载地址: (官网下载较慢)
```
https://npm.taobao.org/mirrors/python/
```
<file_sep>/linux/plymouth/plymouth.md
参考: https://www.huaweicloud.com/articles/02130dd31e89661d51361cc2c0789897.html
1. 安装软件包
```
plymouth (arch: plymouth 包含 plymouth-set-default-theme )
```
2. 修改grub ( /etc/default/grub )
```
GRUB_GFXMODE= 设置正确的屏幕分辨率
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash" (原值: GRUB_CMDLINE_LINUX_DEFAULT="quiet")
```
3. 更新grub.cfg ( /boot/grub/grub.cfg)
```
备份 /boot/grub/grub.cfg
# grub-mkconfig > /boot/grub/grub.cfg
```
4. 设置 plymouth 主题
```
把下载的主题放入/usr/share/plymouth/themes中
下载网站https://www.gnome-look.org/browse/cat/108/ord/latest/
# plymouth-set-default-theme -l
# plymouth-set-default-theme -R <主题名称>
重启即可
```
<file_sep>/linux/desktop-evn/kde/ui.md
主题图标目录: (获取主题,不能卸载)
```
.local/share/aurorae/themes
.local/share/color-schemes
gloabltheme
.local/share/plasma/look-and-feel
icons
.local/share/icons
```
<file_sep>/linux/kvm/1_install.md
```bash
一、安装qemu
sudo pacman -S qemu
其他可选包:
qemu-arch-extra - 其它架构支持
qemu-block-gluster - glusterfs block 支持
qemu-block-iscsi - iSCSI block 支持
qemu-block-rbd - RBD block 支持
samba - SMB/CIFS 服务器支持
二、安装libvirt
sudo pacman -S libvirt virt-manager
为了网络连接,安装这些包:
ebtables 和 dnsmasq 用于默认的 NAT/DHCP网络
bridge-utils 用于桥接网络
openbsd-netcat 通过 SSH 远程管理
启动/开机自起守护进程
systemctl start libvirtd #启动libvirtd进程
systemctl enable libvirtd #开机自起
usermod -a -G kvm <user_name>
# 启动管理器
$ virt-manager
----------------------------------------------
hostonly:
虚拟网络:
lsolated network
配置ipv4 网段,及dhcp
同时宿主机开启网络转发:
iptables -F (清空iptables)
编辑/etc/sysctl.conf (root权限,没有该文件就创建)
取消注释 : net.ipv4.ip_forward=1
执行 : sudo sysctl -p 此时,网络转发功能应该就开启了
- 可以使用如下命令验证: cat /proc/sys/net/ipv4/ip_forward 命令返回1,说明网络转发已开启。
iptables -N fw-open
iptables -A FORWARD -j fw-open
iptables -t nat -A POSTROUTING -o <上外网网卡名> -s 192.168.56.0/24 -j MASQUERADE
```
```
virtio-win
```
```
$ sudo pacman -S qemu
resolving dependencies...
looking for conflicting packages...
Packages (11) brltty-6.0-8 celt0.5.1-0.5.1.3-4 libcacard-2.7.0-1 liblouis-3.13.0-1 libslirp-4.1.0-1 seabios-1.13.0-1 spice-0.14.2-1 usbredir-0.8.0-1 vde2-2.3.2-13
virglrenderer-0.8.2-1 qemu-4.2.0-2
$ sudo pacman -S qemu-block-iscsi
resolving dependencies...
looking for conflicting packages...
Packages (2) libiscsi-1.19.0-1 qemu-block-iscsi-4.2.0-2
$ sudo pacman -S qemu-arch-extra
resolving dependencies...
looking for conflicting packages...
Packages (1) qemu-arch-extra-4.2.0-2
$ sudo pacman -S libvirt virt-manager
resolving dependencies...
looking for conflicting packages...
Packages (20) augeas-1.12.0-1 ceph-libs-14.2.8-1 glusterfs-1:7.3-1 gtk-vnc-1.0.0-1 gtksourceview4-4.6.0-1 liburcu-0.11.0-1 libvirt-glib-3.0.0-1 libvirt-python-5.8.0-3 netcf-0.2.8-7
oath-toolkit-2.6.2-7 phodav-2.4-1 python-chardet-3.0.4-4 python-idna-2.9-1 python-requests-2.23.0-1 python-urllib3-1.25.8-2 spice-gtk-0.37-1 virt-install-2.2.1-2
xmlsec-1.2.29-1 libvirt-5.10.0-2 virt-manager-2.2.1-2
```
```
sudo pacman -S edk2-armvirt : arm64 支持(aarch64)
```
<file_sep>/js/knockout/0_start.md
官网: https://knockoutjs.com/index.html
文档: https://knockoutjs.com/documentation/introduction.html
```
Knockout是一个JavaScript库,可帮助您使用干净的底层数据模型创建丰富,响应迅速的显示和编辑器用户界面。只要您有动态更新的UI部分(例如,根据用户的操作或外部数据源更改而更改),KO可以帮助您更简单,更可维护地实施它。
标题功能:
优雅的依赖关系跟踪 - 在数据模型发生变化时自动更新UI的正确部分。
声明性绑定 - 将UI的各个部分连接到数据模型的简单明了的方法。您可以使用任意嵌套的绑定上下文轻松构建复杂的动态UI。
简单可扩展 - 将自定义行为实现为新的声明性绑定,以便在几行代码中轻松重用。
额外的好处:
纯JavaScript库 - 适用于任何服务器或客户端技术
可以添加到现有Web应用程序之上,而无需进行重大架构更改
紧凑 - gzipping后约13kb
适用于任何主流浏览器(IE 6 +,Firefox 2 +,Chrome,Safari,Edge等)
全面的规范套件(开发BDD风格)意味着它可以在新的浏览器和平台上轻松验证其正确的功能
```
applyBindings:
```
var viewModel = {
modekey1: ko.observable(true) ,
modekey2: ko.observable(true)
};
function viewMode2(){
this.modekey1=ko.observable(true) ;
this.modekey2=ko.observable(true) ;
}
ko.applyBindings(viewModel,document.getElementById("x2"));
ko.applyBindings(viewMode2);
同一个dom 只能bind 一次。
```
observable, subscribe
```
var x= ko.observable(false);
// observable 值变化时调用
// subscribe(function(newvalue))
// subscribe(function(oldvalue),null,"beforeChange")
// 参考 https://knockoutjs.com/documentation/observables.html
var subscription = x.subscribe(function (val) {
console.log("old value",val);
},null, "beforeChange");
x(true)
subscription.dispose(); // I no longer want notifications
```
部分用法参考:
<http://www.aizhengli.com/knockoutjs/knockoutjs.html?page=1>
脚手架:
```
var ViewModel = function () {
mav = this;
window.mav = this;
this.A=ko.observable("-");
this.B=ko.observable(true);
mav.ARR=ko.observableArray();
this.A.subscribe(function (val) {
// val : new value
});
ko.utils.arrayForEach([], function(el, index) {
});
}
$(document).ready(function () {
ko.applyBindings(new ViewModel());
});
```
<file_sep>/sql/postgresql/disk.md
VACUUM
pgsql 磁盘占用较多是,delete 清理数据后,磁盘空间未释放. 需要vacuum 来释放磁盘.
drop 表,磁盘空间会立即释放.
切换数据库管理员,清理指定数据库 (参考: <https://www.cnblogs.com/pengai/p/8073218.html>)
```sql
vacuumdb -d yourdbname -f -z -v
```
登录数据库:(参考: <https://www.postgresql.org/docs/9.1/sql-vacuum.html>)
```
vacuum full <table_name>; 清理指定数据表
vacuum full ;
vacuum ;
```
<file_sep>/docker/import_export/image.md
参考: <https://www.jianshu.com/p/8408e06b7273>
导出:
```
docker save <image id> > targetfile.tar
```
```
[root@wxtest1607 ~]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat8 3.0 90457edaf6ff 6 hours ago 1.036 GB
[root@wxtest1607 lixr]# docker save 9045 > tomcat8-apr.tar
[root@wxtest1607 lixr]# ls -lh
总用量 1.2G
-rw-r--r-- 1 root root 1005M 8月 24 17:42 tomcat8-apr.tar
```
导入:
```
docker load < targetfile.tar
```
```
[root@wxtest1607 lixr]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat8 3.0 90457edaf6ff 7 hours ago 1.036 GB
[root@wxtest1607 lixr]# docker rmi 9045
Untagged: tomcat8:3.0
Deleted: sha256:90457edaf6ff4ce328dd8a3131789c66e6bd89e1ce40096b89dd49d6e9d62bc8
Deleted: sha256:00df1d61992f2d87e7149dffa7afa5907df3296f5775c53e3ee731972e253600
[root@wxtest1607 lixr]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
[root@wxtest1607 lixr]# docker load < tomcat8-apr.tar
60685807648a: Loading layer [==================================================>] 442.7 MB/442.7 MB
[root@wxtest1607 lixr]# yer [> ] 527.7 kB/442.7 MB
[root@wxtest1607 lixr]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
<none> <none> 90457edaf6ff 7 hours ago 1.036 GB
[root@wxtest1607 lixr]# docker tag 9045 tomcat8-apr:3.0
[root@wxtest1607 lixr]#
[root@wxtest1607 lixr]# docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
tomcat8-apr 3.0 90457edaf6ff 7 hours ago 1.036 GB
```
<file_sep>/C_or_C++/重载.md
C++重载 ,(c 不支持重载)
函数名相同;参数类表,返回类型不同; 功能类似。
在C++中,没有跨域重载
参考:<https://www.jianshu.com/p/34ba593dd6a4>
```
// 重载父类函数
using <parent_clas>::<function_name>;
<return_type> function_name(<arg_name> <arg_type>,...)
{
}
```
```
重写父类函数后再重载。
```
<file_sep>/linux/softs/ssh/QA.md
Q:
```
Unable to negotiate with xxx.xxx.xxx.xxx port 22: no matching key exchange method found. Their offer: diffie-hellman-group1-sha1
```
A:
```
ssh -oHostKeyAlgorithms=+ssh-dss -oKexAlgorithms=+diffie-hellman-group1-sha1 xxx.xxx.xxx.xxx
```
<file_sep>/linux/common/blkid.md
查看 分区uuid
blkid
ls -l /dev/disk/by-uuid<file_sep>/python/petl/loaddata.md
>>> import petl as etl
>>> cols = [[0, 1, 2], ['a', 'b', 'c']]
>>> tbl = etl.fromcolumns(cols)
>>> import petl as etl
>>> import csv
>>> # set up a CSV file to demonstrate with
... table1 = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> with open('example.csv', 'w') as f:
... writer = csv.writer(f)
... writer.writerows(table1)
...
>>> # now demonstrate the use of fromcsv()
... table2 = etl.fromcsv('example.csv')
etl.tocsv(table1, 'example.csv')
<file_sep>/golang/libs/gf/0_desc.md
文档 <https://goframe.org/index>
```
GF(Go Frame)是一款模块化、高性能、生产级的Go应用开发框架。
提供了常用的核心开发组件,如:缓存、日志、文件、时间、队列、数组、集合、字符串、定时器、命令行、文件锁、内存锁、对象池、连接池、数据校验、数据编码、文件监控、定时任务、数据库ORM、TCP/UDP组件、进程管理/通信、 并发安全容器等等。并提供了Web服务开发的系列核心组件,如:Router、Cookie、Session、路由注册、配置管理、模板引擎等等,支持热重启、热更新、多域名、多端口、多服务、HTTPS、Rewrite等特性。
```
<file_sep>/linux/shell_script/json.md
<http://bbs.chinaunix.net/thread-4314131-1-1.html>
```
jq
```
<file_sep>/linux/net/bond.md
参考:
https://www.cnblogs.com/kaishirenshi/p/10245228.html
https://blog.csdn.net/parameter_/article/details/72453285<file_sep>/linux/softs/nfs.md
## 1. 安装 nfs server
```
yum install -y nfs-utils rpcbind
rpcbind.service
nfs.service
```
## 2. 配置 nfs server
```
1. vim /etc/exports: config export path
path *(rw,sync,no_root_squash)
path client_ip(rw,sync,no_root_squash)
2. # exportfs
3. restart nfs service
```
```
修改 /etc/exports 不重启nfs 服务直接生效
# exportfs -arv
```
## nfs client mount
export 查看服务器哪些目录可以挂载:
# showmount -e <nfs-server>
http://www.runoob.com/linux/linux-comm-mount.html
https://www.linuxidc.com/Linux/2016-08/134666.htm
https://blog.csdn.net/linuxnews/article/details/51350408
mount:
# mount nfs_server:path mount_point_path
# mount -o loop file.iso mount_point_path
# umount mount_point_path
Usage: mount -V : print version
mount -h : print this help
mount : list mounted filesystems
mount -l : idem, including volume labels
So far the informational part. Next the mounting.
The command is `mount [-t fstype] something somewhere'.
Details found in /etc/fstab may be omitted.
mount -a [-t|-O] ... : mount all stuff from /etc/fstab
mount device : mount device at the known place
mount directory : mount known device here
mount -t type dev dir : ordinary mount command
Note that one does not really mount a device, one mounts
a filesystem (of the given type) found on the device.
One can also mount an already visible directory tree elsewhere:
mount --bind olddir newdir
or move a subtree:
mount --move olddir newdir
One can change the type of mount containing the directory dir:
mount --make-shared dir
mount --make-slave dir
mount --make-private dir
mount --make-unbindable dir
One can change the type of all the mounts in a mount subtree
containing the directory dir:
mount --make-rshared dir
mount --make-rslave dir
mount --make-rprivate dir
mount --make-runbindable dir
A device can be given by name, say /dev/hda1 or /dev/cdrom,
or by label, using -L label or by uuid, using -U uuid .
Other options: [-nfFrsvw][-o options] [-p passwdfd].
### umount
umount /mountpoint
device is busy:
参考: https://blog.csdn.net/weixin_34081595/article/details/92529756
fuser:
fuser -mv <dir>
lsof:
lsof +d <dir>
以上方法仍不能umount:
```
umount -lf <nfs_server_ip/host>:<mount_path>
umount -l <nfs_server_ip/host>:<mount_path>
umount -l <mount_path>
```
### NFS文件锁
```
https://blog.csdn.net/smst1987/article/details/6890807
无可用的锁
nfslock 服务端和客户端都需要启动这个服务.
```
archlinux:
[https://wiki.archlinux.org/index.php/NFS_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)](https://wiki.archlinux.org/index.php/NFS_(简体中文))
```
客户端和服务端都只需要安装 nfs-utils 包。
pacman -S nfs-utils
内核升级可能导致不能挂载
```
```
RHEL 8/CentOS 8系统上安装NFS服务器包:
sudo yum -y install nfs-utils
安装完成后,启动并启用nfs-server服务:
sudo systemctl enable --now nfs-server rpcbind
```
```
mount
mount -t nfs -o nfsvers=3 xx.xx.xxx.xx:/xxx /xxx/xxx (nfsvers= 参数可能导致用户映射错误)
```
<file_sep>/golang/base/1_covertypes.md
**语法**:<结果类型> := <目标类型> ( <表达式> )
string []byte
```
// string 转 []byte
bytes_var := []byte("xxxxxx")
// []byte 转 string
str_var := string(byte_var[:])
```
**语法**: <目标类型的值>,<布尔参数> := <表达式>.( 目标类型 ) // 安全类型断言
<目标类型的值> := <表达式>.( 目标类型 ) //非安全类型断言
<file_sep>/js/js/Object_defineProperty.md
`Object.defineProperty`方法直接在一个对象上定义一个新属性,或者修改一个已经存在的属性, 并返回这个对象
```
Object.defineProperty(obj, prop, descriptor)
参数说明:
obj:必需。目标对象
prop:必需。需定义或修改的属性的名字
descriptor:必需。目标属性所拥有的特性:这个属性设置一些特性,比如是否只读不可以写;是否可以被for..in或Object.keys()遍历。
返回值:
传入函数的对象。即第一个参数obj
```
descriptor:
- value: 设置属性的值,默认为undefined。
- writable: 值是否可以重写。true | false , 默认为false。
- enumerable: 目标属性是否可以被枚举。true | false 默认为false
- configurable: 目标属性是否可以被删除或是否可以再次修改特性 true | false 默认为false。
- set: 目标属性设置值的方法
- get:目标属性获取值的方法
```
Object.defineProperty : 调用一次,指定了值是可立即设置对象的值。
当使用了getter或setter方法,不允许使用writable和value这两个属性(如果使用,会直接报错滴)
get 是获取值的时候的方法,类型为 function ,获取值的时候会被调用,不设置时为 undefined
set 是设置值的时候的方法,类型为 function ,设置值的时候会被调用,undefined
```
```
兼容性
在ie8下只能在DOM对象上使用,尝试在原生的对象使用 Object.defineProperty()会报错。
```
<file_sep>/java/cmdtool/unpack200.md
```
解压:
unpack200 filname.pack.gz filename.jar
```
<file_sep>/js/jquery/extend.md
$.extend( target , object1 )
$.extend( [deep ], target, object1 [, objectN ] )
deep 可选。 Boolean类型 指示是否深度合并对象,默认为false。如果该值为true,且多个对象的某个同名属性也都是对象,则该"属性对象"的属性也将进行合并。
```
var marged = $.extend({}, defaults, options); /*合并默认值和选项,不修改默认对象。返回合并后的结果*/
```
<file_sep>/python/django_1.11/env.md
django python2.7:
```
virtualenv -p /usr/bin/python2.7 --no-site-packages djvenv
python -m pip install "django<2" -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
pip list
Package Version
---------- -------
Django 1.11.20
pip 19.0.3
pytz 2018.9
setuptools 40.8.0
wheel 0.33.1
```
<file_sep>/linux/desktop-evn/awesome/install.md
```
包名: awesome
```
<file_sep>/linux/arch/install.md
1. 键盘布局
```
控制台键盘布局 默认为us(美式键盘映射)。
如果您正在使用非美式键盘布局,通过以下的命令选择相应的键盘映射表:
# loadkeys layout
```
3. 验证启动模式
```
如果以在 UEFI 主板上启用 UEFI 模式, Archiso 将会使用 systemd-boot 来启动 Arch Linux。可以列出 efivars 目录以验证启动模式:
# ls /sys/firmware/efi/efivars
如果目录不存在,系统可能以 BIOS 或 CSM 模式启动
```
4. 连接到因特网
```
(有线)护进程 dhcpcd 已被默认启用来探测有线设备, 并会尝试连接。
如需验证网络是否正常, 可以使用 ping:
(无线)
wpa-cli
wpa_supplicant - Wi-Fi Protected Access client and IEEE 802.1X supplicant
SYNOPSIS
wpa_supplicant [ -BddfhKLqqsTtuvW ] [ -iifname ] [ -cconfig file ] [ -D driver ] [ -PPID_file ] [ -f output file ]
https://segmentfault.com/a/1190000011579147
wpa_supplicant是一个连接、配置WIFI的工具,它主要包含wpa_supplicant与wpa_cli两个程序。通常情况下,可以通过wpa_cli来进行WIFI的配置与连接,如果有特殊的需要,可以编写应用程序直接调用wpa_supplicant的接口直接开发。
# wpa_cli -i wlan0 scan // 搜索附近wifi网络
# wpa_cli -i wlan0 scan_result // 打印搜索wifi网络结果
# wpa_cli -i wlan0 add_network // 添加一个网络连接
```
4. 更新系统时间
```
用 systemd-timesyncd 确保系统时间是正确的:
# timedatectl set-ntp true
```
5. 建立硬盘分区
```
fdisk -l
对于一个选定的设备,以下的分区是必须要有的:
一个根分区(挂载在根目录) /.
如果 UEFI 模式被启用,你还需要一个 EFI 系统分区.
Swap 可以在一个独立的分区上设置,也可以直接建立 交换文件.
如需修改分区表,使用 fdisk 或 parted. 查看Partitioning (简体中文)以获得更多详情.
如果需要创建多级存储例如 LVM、LUKS 或 RAID,在此时完成。
/boot 分区不能时lvm.
```
6. 格式化分区
```
mkfs.ext4 /dev/sdaX
swap
# mkswap /dev/sdX2
# swapon /dev/sdX2
```
7. 挂载分区
```
mount /dev/sdaX /mnt
```
如果使用多个分区,还需要为其他分区创建目录并挂载它们(/mnt/boot、/mnt/home、……)。
```
# mkdir /mnt/boot
# mount /dev/sda2 /mnt/boot
```
genfstab 将会自动检测挂载的文件系统和 swap 分区。
8. 选择镜像
```
编辑 /etc/pacman.d/mirrorlist
cd /etc/pacman.d ; cp mirrorlist mirrorlist.back
cat mirrorlist.back | grep 163 > mirrorlist
```
9. 安装基本系统
```
pacstrap /mnt base (仅安装基础系统)
pacstrap /mnt base base-devel
pacstrap /mnt net-tools
pacstrap /mnt vim
ios 镜像不是最新的时候可能出现
(invalid or corrupted package (PGP signature))
### pacman-key --init
### pacman-key --populate
### pacman -S archlinux-keyring
### pacman -Syy
<xxx@xxx> is unknown trust:
(
/etc/pacman.conf
SigLevel = Never # Optional TrustedOnly
# pacman -Syy
)
```
# 配置系统
## Fstab:
# genfstab -U /mnt >> /mnt/etc/fstab
(在执行完以上命令后,后检查一下生成的 /mnt/etc/fstab 文件是否正确)
## Chroot:
# arch-chroot /mnt (切换到安装好的系统)
## 时区:
ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
hwclock --systohc --utc
## (grub 可优先安装配置)
安装并配置 bootloader
我的主板是BIOS主板,这里采用的 bootloader 是Grub;安装 grub 包,并执行 grub-install 已安装到 MBR:
# pacman -S grub
# grub-install --target=i386-pc --recheck /dev/sdb
# pacman -S intel-ucode
# grub-install --boot-directory=/mnt/boot /dev/sdb
注意:须根据实际分区自行调整 /dev/sdb, 切勿在块设备后附加数字,比如 /dev/sdb1 就不对。
由于我的硬盘上还有另外一个操作系统windows 7,为了检测到该系统并写到grub启动项中,还需要做下面的操作。
# pacman -S os-prober
# grub-mkconfig -o /boot/grub/grub.cfg
UEFI 模式:(分区表类型为gpt)
```
mkdir -p /mnt/boot/efi #建立efi 文件夹
mount /dev/sda2 /mnt/boot/efi #挂载efi
mkdir /boot/efi/EFI/boot
*切换系统 / 后执行如下操作
pacman -S grub-efi-x86_64 # 该包可能不存在
pacman -S efibootmgr
pacman -S os-prober
grub-install --efi-directory=/boot/efi --bootloader-id=grub
cp /boot/efi/EFI/grub/grubx64.efi /boot/efi/EFI/boot/bootx64.efi
grub-mkconfig -o /boot/grub/grub.cfg
----------------------------------------------
grub install (UEFI+GPT)
grub-install --target=x86_64-efi --efi-directory=/boot/efi --bootloader-id=arch_grub --recheck
```
## Locale: 设置 /etc/locale.gen 只需移除对应行前面的注释符号(#)即可
# nano /etc/locale.gen
en_US.UTF-8 UTF-8
zh_CN.UTF-8 UTF-8
执行locale-gen以生成locale讯息
# locale-gen
(/etc/locale.gen 生成指定的本地化文件,每次 glibc 更新之后也会运行 locale-gen。)
# echo LANG=en_US.UTF-8 > /etc/locale.conf
## 键盘布局配置文件: /etc/vconsole.conf
## 主机名:
echo myhostname > /etc/hostname
vim /etc/hosts
127.0.0.1 localhost.localdomain localhost
::1 localhost.localdomain localhost
127.0.1.1 myhostname.localdomain myhostname
## 网络配置:
对新安装的系统,需要再次设置网络。具体请参考 Network configuration (简体中文) 和
对于 无线网络配置,安装 软件包 iw, wpa_supplicant,dialog 以及需要的 固件软件包.
## Initramfs
如果修改了 mkinitcpio.conf,用以下命令创建一个初始 RAM disk:
# mkinitcpio -p linux
## Root 密码
设置 root 密码:
# passwd
## 安装图形桌面
# pacman -S xorg xorg-server
# pacman -S deepin
# pacman -S deepin-extra
ls -1 /usr/share/xgreeters/
vi /etc/lightdm/lightdm.conf
Find the following line:
#greeter-session=example-gtk-gnome
And, uncomment and change it as shown below.
greeter-session=lightdm-deepin-greeter
(创建一个普通用户,并为相应的用户创建home 目录)
lightdm --test-mode --debug
systemctl start lightdm.service
systemctl enable lightdm.service
## 中文乱码: https://www.cnblogs.com/bluestorm/p/6039197.html
## 输入法:
# pacman -S fcitx fcitx-im fcitx-googlepinyin fcitx-configtool
## 网络:
# pacman -S networkmanager
# systemctl enable NetworkManager
先ip link 看网卡设备名。以ens192为例
cd /etc/netctl
cp examples/ethernet-static ./ens192
(文件名任意,与下面的netctl一致即可)
vim ens192
改Interface为网卡设备名。
改ip,掩码,网关,dns
然后
netctl enable ens192 (此处的ens192是文件名)
netctl start ens192
当然你也可以用 examples/ethernet-dhcp 这个模板, 只改interface=一处即可。
一篇教程:
http://bbs.archlinuxcn.org/viewtopic.php?id=1037
额外参考:
http://bbs.archlinuxcn.org/viewtopic.php?id=1037
https://www.cnblogs.com/bluestorm/p/5929172.html
gnome:
```
pacman -S gnome gnome-extra
然后安装gdm登录管理器 (可使用其他登录器)
pacman -S gnome gdm
将gdm设置为开机自启动,这样开机时会自动载入桌面
systemctl enable gdm
```
deepin:
```
pacman -S deepin deepin-extra lightdm (配置见前文)
```
kde:
```
基础包
pacman -S plasma
完整包
pacman -S plasma-meta
最简安装(仅有桌面软件)
pacman -S plasma-desktop
然后是登录管理器SDDM
pacman -S sddm
将SDDM设置为开机自启动
systemctl enable sddm
```
xfce:
```
LXDM是个桌面管理器,用来登录系统及启动XFCE桌面。
pacman -S lxdm
systemctl enable lxdm.service
安装XFCE4
pacman -S xfce4
startxfce4
```
LXDE桌面
```
安装LXDM管理器和LXDE桌面:
### pacman -S lxdm lxde
设置lxdm开机启动:
### systemctl enable lxdm
```
lightdm-webkit2-greeter: lightdm-webkit2-theme-material2
<file_sep>/linux/common/内核模块.md
```
查看内核模块:
# lsmod
# cat /proc/modules
modinfo + mod名
```
### solution:
```
ipmitool启动报错"Could not open device at /dev/ipmi0 or /dev/ipmi/0 or /dev/ipmidev/0: No"
先查看lsmod | grep ipmi
移除模块
remodprobe -r ipmi_watchdog
需要添加如下:
# modprobe ipmi_watchdog
# modprobe ipmi_poweroff
# modprobe ipmi_devintf
# modprobe ipmi_si
# modprobe ipmi_msghandler
当添加ipmi_si时,提示:
FATAL: Error inserting ipmi_si (/lib/modules/2.6.9-5.ELsmp/kernel/drivers/char/ipmi/ipmi_si.ko): No such device
这是因为机器上没有IPMI设备而出现的报错。
```
<file_sep>/python/IDE/PYCHARM.md
template:
```
https://www.jetbrains.com/help/pycharm/file-template-variables.html
```
build in vars
```
${DATE} Current system date
${DAY} Current day of the month
${DS} Dollar sign $. This variable is used to escape the dollar character, so that it is not treated as a prefix of a template variable.
${FILE_NAME} Name of the new file.
${HOUR} Current hour
${MINUTE} Current minute
${MONTH} Current month
${MONTH_NAME_FULL} Full name of the current month (January, February, and so on)
${MONTH_NAME_SHORT} First three letters of the current month name (Jan, Feb, and so on)
${NAME} Name of the new entity (file, class, interface, and so on)
${ORGANIZATION_NAME} Name of your organization specified in the project settings (Ctrl+Shift+Alt+S)
${PRODUCT_NAME} Name of the IDE (for example, PyCharm)
${PROJECT_NAME} Name of the current project
${TIME} Current system time
${USER} Login name of the current user
${YEAR} Current year
```
```
自定义变量:
在模板文件开头设置变量。
#set( $MyVarname = "var value" )
```
```
实例
#set( $MyName = "xxxx" )
#set( $DEV_VERSION = "xx.xxx" )
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@License : xxxxx
@File : ${NAME}.py
@Time : ${YEAR}/${MONTH}/${DAY} ${HOUR}:${MINUTE}
@Author : ${MyName}
@Version : ${DEV_VERSION}
@Contact : <EMAIL>
@Desc :
'''
```
<file_sep>/linux/softs/pdsh.md
参考: https://www.cnblogs.com/liwanliangblog/p/9194146.html
```
下载地址: https://sourceforge.net/projects/pdsh/
tar -jxvf pdsh-2.26.tar.bz2 -C /tmp,解压至/tmp/pdsh-2.26
cd /tmp/pdsh-2.26/
./configure \
--prefix=/usr/local/globle/softs/tools/pdsh/2.26/ \
--with-timeout=60 \
--with-ssh \
--with-exec \
--with-nodeupdown \
--with-readline \
--with-rcmd-rank-list=ssh
```
```
选项 解释
--prefix 指定安装目录
--with-timeout=60 指定pdsh默认执行超时时间
--with-ssh 编译ssh模块
--with-exec 编译exec模块
--with-nodeupdown 编译节点宕机功能
--with-readline 编译readline功能
--with-rcmd-rank-list 指定默认模式为ssh
--with-machines 指定默认主机列表
```
```
World writable and sticky bit is not set
将报错目前权限设置为755 或775 , 不能是777
```
<file_sep>/golang/daemon/2.md
```go
func Daemon(){
cmd := exec.Command(os.Args[0])
cmd.Stdin = nil
cmd.Stdout = nil
cmd.Stderr = nil
// cmd.Stdin = os.Stdin
// cmd.Stdout = os.Stderr
// cmd.Stderr = os.Stderr
cmd.SysProcAttr = &syscall.SysProcAttr{Setsid:true}
err := cmd.Start()
if err == nil {
cmd.Process.Release()
os.Exit(0)
}
}
```
<file_sep>/python/solutions/libffi.so.md
ImportError: libffi.so.5: cannot open shared object file: No such file or directory
```bash
# rpm -q libffi
libffi-3.0.13-18.el7.x86_64
# find / -name libffi*.so
/usr/lib64/libffi.so
# ln -s libffi.so libffi.so.5
```
<file_sep>/editor/vscode/python_env.md
```
// python路径配置
"python.pythonPath": "/................/bin/python",
// python 测试配置(unittest), 将源码目录加到 sys.path 中,避免引入包时报错
"python.testing.unittestArgs": [
"-v",
"-s",
"/xxxx/xxx",
"-p",
"*test.py"
],
"python.testing.pyTestEnabled": false,
"python.testing.nosetestsEnabled": false,
"python.testing.unittestEnabled": true,
"python.jediEnabled": true, //模块自动补全,改动后重新LOAD生效
```
```
windows 下vscode 运行python ,模块找不到.
https://blog.csdn.net/qq_31654025/article/details/109474175
环境变量路径分割符 :windows 为 ";" linux 为 ":"
方法1:
launch.json
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: 当前文件",
"type": "python",
"request": "launch",
"program": "${file}",
"console": "integratedTerminal",
"env": {"PYTHONPATH":"${workspaceFolder}:${env:PYTHONPATH}"}
}
]
}
方法2:
----------------------------------------------------------------------------
.vscode/settings.json
"python.envFile": "${workspaceFolder}/.vscode/.env",
----------------------------------------------------------------------------
PYTHONPATH=${workspaceFolder}/your_src_dir:${PYTHONPATH}
方法3:
settings.json
// "python.envFile": "${workspaceFolder}/.env",
"terminal.integrated.env.windows": {"PYTHONPATH":"${workspaceFolder};${env:PYTHONPATH}"},
"terminal.integrated.env.linux": {"PYTHONPATH":"${workspaceFolder}:${env:PYTHONPATH}"}
```
<file_sep>/linux/shell_script/三元运算.md
<https://blog.csdn.net/kouryoushine/article/details/92838138>
```
三元运算符 ?
$((parm>0?parm:5))
parm>0 成立返回 $parm ,否则返回5
返回值不支持字符串
三元运算符 “:-”
${parm:-34}
parm 存在返回 ${parm} 不存在返回34
case “$b” in
5) a=$c ;;
*) a=$d ;;
esac
或者:
[[ $b = 5 ]] && a=”$c” || a=”$d”
```
<file_sep>/python/pip/download_pack.md
### pip download
```
file: requirement.txt
django
simplejson==3.14.0
```
```
$ pip download -d ./pip_download -r requirement.txt --trusted-host pypi.douban.com
```
<file_sep>/linux/softwaremanager/dpkg/deb_pack_unzip.md
ar -vx xxxxx.deb && tar zxvf xxx.tar.gz
deb:
```
deb 包结构
.
├── control.tar.gz (安装控制文件)
├── data.tar.xz (程序文件,目录从根目录开始组织)
└──debian-binary
```
```
control.tar.gz 中的文件
preinst
在Deb包文件解包之前,将会运行该脚本。许多“preinst”脚本的任务是停止作用于待升级软件包的服务,直到软件包安装或升级完成。
postinst
该脚本的主要任务是完成安装包时的配置工作。许多“postinst”脚本负责执行有关命令为新安装或升级的软件重启服务。
prerm
该脚本负责停止与软件包相关联的daemon服务。它在删除软件包关联文件之前执行。
postrm
该脚本负责修改软件包链接或文件关联,或删除由它创建的文件。
```
```
dpkg lock
# rm /var/lib/dpkg/lock-frontend
```
```
Ubuntu中所有packages的信息都在/var/lib/dpkg/目录下,其中子目录”/var/lib/dpkg/info”用于保存各个软件包的配置文件列表.不同后缀名代表不同类型的文件,如:
.conffiles 记录了软件包的配置文件列表。
.list 保存软件包中的文件列表,用户可以从.list的信息中找到软件包中文件的具体安装位置。
.md5sums 记录了软件包的md5信息,这个信息是用来进行包验证的。
.prerm 脚本在Debian报解包之前运行,主要作用是停止作用于即将升级的软件包的服务,直到软件包安装或升级完成。
.postinst脚本是完成Debian包解开之后的配置工作,通常用于执行所安装软件包相关命令和服务重新启动。
/var/lib/dpkg/available文件的内容是软件包的描述信息,该软件包括当前系统所使用的Debian安装源中的所有软件包,其中包括当前系统中已安装的和未安装的软件包。
命令:
dpkg –l | grep package 查询deb包的详细信息,没有指定包则显示全部已安装包
dpkg -s package 查看已经安装的指定软件包的详细信息
dpkg -L package 列出一个包安装的所有文件清单
dpkg -S file 查看系统中的某个文件属于哪个软件包,搜索已安装的软件包
dpkg -i 安装指定deb包
dpkg -R 后面加上目录名,用于安装该目录下的所有deb安装包
dpkg -r remove,移除某个已安装的软件包
dpkg -P 彻底的卸载,包括软件的配置文件
dpkg -c 查询deb包文件中所包含的文件
dpkg -L 查看系统中安装包的的详细清单,同时执行 -c
```
<file_sep>/linux/softs/gdm/login.md
```
gdm 桌面选择在选择用户后可见。
```
如下两种服务可选其一
gdm.service
gdm-plymouth.service
<file_sep>/linux/common/免密登陆.md
## 实现步骤:
1. 在服务器上使用"ssh-keygen -t rsa"命令来创建公钥。(ssh-keygen 不带参数也可以)
(会问你存放的目录,如果不需要修改,直接回车两次即可,默认保存路径为"~/.ssh/")
2. 将第一步生成的"~/.ssh/id_rsa.pub"这个文件拷贝到"~/.ssh/"目录中并改名为"authorized_keys"。(两个文件权限一致)
cp ~/.ssh/id_rsa.pub ~/.ssh/authorized_keys -a
3. 修改"~/.ssh/"目录权限为700
(这是linux的安全要求,如果权限不对,自动登录将不会生效。)
(有些系统需要将authorized_keys的用户权限改为 600)
.ssh drwx------ (700)
.ssh/id_rsa.pub -rw-r--r-- (644)
.ssh/id_rsa -rw------- (600)
.ssh/authorized_keys -rw-r--r-- (644)
.ssh/config -rw-r--r-- (644)
### 提示保存
echo "StrictHostKeyChecking no" >> ~/.ssh/config
### 可能还会提示输入密码的解决方法
1) 如果出现报警:"Address X.X.X.X maps to localhost, but this does not map back to the address - POSSIBLE BREAK-IN ATTEMPT!"。
在(连接端)服务器上执行如下命令:
echo "GSSAPIAuthentication no" >> ~/.ssh/config
在(被连接端)服务器上执行"vi /etc/ssh/sshd_config"命令,修改下面两项值为"no" :
"GSSAPIAuthentication no"
"UseDNS no"
2) 如果出现报警:"Agent admitted failure to sign using the key."
执行命令:"ssh-add"(把专用密钥添加到ssh-agent的高速缓存中)
如果还不行,执行命令:"ps -Af | grep agent "
(检查ssh代理是否开启,如果有开启的话,kill掉该代理)
然后执行"ssh-agent"(重新打开一个ssh代理)
如果还是不行,继续执行命令:"sudo service sshd restart"(重启一下ssh服务)
3) 通过命令"/usr/sbin/sestatus -v" 查看SELinux状态,如果"SELinux status"参数为"enabled"(开启状态),则关闭SELinux。
临时关闭方法(不用重启机器):"setenforce 0"
修改配置文件关闭方法(需要重启机器):执行命令"/etc/selinux/config",将"SELINUX=enforcing"改为"SELINUX=disabled"
4) 执行命令"vim /etc/ssh/sshd_config"去掉下面三行的注释:
"RSAAuthentication yes"
"PubkeyAuthentication yes"
"AuthorizedKeysFile .ssh/authorized_keys"
## SSH免密码登录原理:
远程服务器持有公钥,当有用户进行登录,服务器就会随机生成一串字符串,然后发送给正在进行登录的用户。
用户收到远程服务器发来的字符串,使用与远程服务器公钥配对的私钥对字符串进行加密,再发送给远程服务器。
服务器使用公钥对用户发来的加密字符串进行解密,得到的解密字符串如果与第一步中发送给客户端的随机字符串一样,那么判断为登录成功。
ssh -v 可调试ssh 登陆过程。 可协助分析登陆认证的流程,可排查ssh 登陆的相关问题。
Get新方式:
首先生成一个rsa秘钥
`ssh-keygen -t rsa`
之后把这个秘钥拷贝到远程主机上,用下面这个命令就够了
`ssh-copy-id username@remote_host`
<file_sep>/java/spring-mvc/controller.md
参考: https://www.iteye.com/blog/elim-1753271
```
@Controller 用于标记在一个类上,使用它标记的类就是一个SpringMVC Controller 对象。
分发处理器将会扫描使用了该注解的类的方法,并检测该方法是否使用了@RequestMapping 注解。
@Controller 只是定义了一个控制器类,而使用@RequestMapping 注解的方法才是真正处理请求的处理器.
```
<file_sep>/linux/softs/lightdm/describe.md
```
grub:引导操作系统
dm: 登录窗口管理,lightdm ,gdm,kdm 等
greeter: lightdm中登录窗口、选择桌面环境
desktop_env: 桌面环境:gnome,deepin,kde,xfc 等
```
grub + dm+desktop_env :
```
grub+gdm+gnome gdm 默认引导gnome。
安装gdm,gnome 后,停用其他dm 服务,开启gdm 服务即可使用。
# systectl enable gdm
```
grub+dm+greeter+desktop_env:
```
grub+lightdm+greeter+deepin/gnome :可引导多种桌面环境
greeter 负责登录窗口及桌面环境选择。
# systectl enable lightdm
lightdm+gnome : 锁屏不可用
```
/etc/lightdm/lightdm.conf 中配置greeter.
```
[Seat:*]
#greeter-session=lightdm-deepin-greeter
greeter-session=lightdm-webkit2-greeter
```
greeter:
```
deepin: lightdm-deepin-greeter
lightdm-webkit2-greeter
lightdm-gtk-greeter
```
```
dm-tool switch-to-greeter # 切换用户
dm-tool lock 锁屏
```
<file_sep>/python/formate.py
#! /usr/bin/env python
# coding=utf-8
# http://blog.xiayf.cn/2013/01/26/python-string-format/
# https://docs.python.org/3/library/string.html
# 1、使用位置参数
li = ['hoho',18]
print 'my name is {} ,age {}'.format('hoho',18)
print 'my name is {1} ,age {0}'.format(10,'hoho')
print 'my name is {1} ,age {0} {1}'.format(10,'hoho')
print 'my name is {} ,age {}'.format(*li)
# 2、使用关键字参数
hash = {'name':'hoho','age':18}
print 'my name is {name},age is {age}'.format(name='hoho',age=19)
print 'my name is {name},age is {age}'.format(**hash)
# 3、填充与格式化
# :[填充字符][对齐方式 <^>][宽
print '{0:*>10}'.format(10) ##右对齐 '********10'
print '{0:*<10}'.format(10) ##左对齐 '10********'
print '{0:*^10}'.format(10) ##居中对齐 '****10****'
# 4、精度与进制
print '{0:.2f}'.format(1/3) # '0.33'
print '{0:b}'.format(10) #二进制 '1010'
print '{0:o}'.format(10) #八进制 '12'
print '{0:x}'.format(10) #16进制 'a'
print '{:,}'.format(12369132698) #千分位格式化 '12,369,132,698'
print "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(42)
print "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(42) # with 0x, 0o, or 0b as prefix:
print '{:+f}; {:+f}'.format(3.14, -3.14) # show it always
print '{: f}; {: f}'.format(3.14, -3.14) # show a space for positive numbers
print '{:-f}; {:-f}'.format(3.14, -3.14) # show only the minus -- same as '{:f}; {:f}'
# 5、使用索引
print 'name is {0[0]} age is {0[1]}'.format(li)
print 'name is {0[0]} age is {0[1]} {1[0]},{1[1]}'.format(li,li)
# object property
# print 'Point({self.x}, {self.y})'.format(self=self)
print 'Correct answers: {:.2%}'.format(1/3.0)
# '{0:{fill}{align}16}'.format(text, fill=align, align=align)
# octets = [192, 168, 0, 1]
# '{:02X}{:02X}{:02X}{:02X}'.format(*octets)
# int(_, 16)
# >>> width = 5
# >>> for num in range(5,12):
# ... for base in 'dXob':
# ... print('{0:{width}{base}}'.format(num, base=base, width=width), end=' ')
# ... print()
#转义大括号
print(" The {} set is often represented as { {0} } ".format("empty")) # The empty set is often represented as {0}<file_sep>/sql/postgresql/function.md
```
CREATE [OR REPLACE] FUNCTION function_name (arguments)
RETURNS return_datatype AS $variable_name$
DECLARE
declaration;
[...]
BEGIN
< function_body >
[...]
RETURN { variable_name | value }
END; LANGUAGE plpgsql;
```
```
CREATE OR REPLACE FUNCTION 函数名称( 参数1,参数2,...) RETURNS void
AS
$BODY$
DECLARE --定义
BEGIN
INSERT INTO "表名" VALUES(参数1,参数2,...);
END
$BODY$
LANGUAGE 'plpgsql' VOLATILE; -- 最后别忘了这个。
```
```
CREATE OR REPLACE FUNCTION 函数名称(deptcode VARCHAR(20) ,deptname VARCHAR(60) ,pycode VARCHAR(60),isenabled CHAR(1))
RETURNS BOOLEAN --返回值,布尔类型
AS
$body$
DECLARE
deptcode VARCHAR(20);
deptname VARCHAR(60);
pycode VARCHAR(60);
isenabled CHAR(1);
BEGIN
UPDATE "deptDict" SET deptcode=deptcode,deptname=deptname,pycode=pycode,isenabled=isenabled,updatedhisdatetime=CURRENT_TIMESTAMP
WHERE deptcode=deptcode;
RETURN TRUE;
END
$body$
LANGUAGE 'plpgsql' VOLATILE;
```
```
请注意, 定义存储过程内使用的变量, 需要定义在 BEGIN 之前, 需要加 DECLARE 关键字。
多个变量之间用分号分隔。
CREATE OR REPLACE FUNCTION HelloWorld() RETURNS void AS
$$
DECLARE
testvalue1 VARCHAR(20);
testvalue2 VARCHAR(20);
BEGIN
testvalue1 := 'First Test! ';
SELECT 'Second Test !' INTO testvalue2;
INSERT INTO test_helloworld
SELECT 'Hello World' ;
INSERT INTO test_helloworld (data)
VALUES (testvalue1 || testvalue2);
END;
$$
LANGUAGE plpgsql;
————————————————
```
<file_sep>/editor/vscode/go_env.md
vscode 源码跳转依赖godef , 需要安装godef
improt 自动导入依赖goimports
godef, goimports 安装:
获取 golang.org/x/tools
```
$ go get -u golang.org/x/tools
将源码下载到 $GOPATH/src/golang.org/x/tools
在$GOPATH/src/golang.org/x/tools 目录下找到
── cmd
│ ├── auth
│ ├── benchcmp
│ ├── bundle
│ ├── callgraph
│ ├── compilebench
│ ├── cover
│ ├── digraph
│ ├── eg
│ ├── fiximports
│ ├── guru
│ ├── html2article
│ ├── present
│ ├── splitdwarf
│ ├── ssadump
│ ├── stress
│ ├── stringer
│ └── toolstash
相应工具的目录,设置GOBIN 变量后执行 go install
goimports,guru 位于: tools/cmd 下
```
环境配置可参考:<https://www.cnblogs.com/yangxiaoyi/p/9692369.html>
```
go test 显示详细
"go.testFlags": ["-v"]
```
```
go get -v github.com/rogpeppe/godef
go install github.com/mdempsky/gocode
go install github.com/uudashr/gopkgs/v2/cmd/gopkgs
go install github.com/stamblerre/gocode
go install golang.org/x/lint/golint
```
```
非go mod 项目,配置 go.gopath ,go.goroot,
将需要查找依赖包的路径写入gopath (linux : 分割)
通过gopath/src 下找相应的包。(go mod 混用时: go mod vendor 生成的目录,需插入src 目录。)
```
```
export GOPROXY=https://goproxy.io
export GO111MODULE=on
```
开发环境依赖
https://www.jianshu.com/p/b8d85656de0b
https://my.oschina.net/iyf/blog/599112
```
go get -u -v github.com/nsf/gocode
go get -u -v github.com/rogpeppe/godef
go get -u -v github.com/golang/lint/golint
go get -u -v github.com/lukehoban/go-find-references
go get -u -v github.com/lukehoban/go-outline
go get -u -v sourcegraph.com/sqs/goreturns
go get -u -v golang.org/x/tools/cmd/gorename
```<file_sep>/sql/postgresql/级联删除.md
```
CASCADE: 需要级联时使用。
truncate table_name CASCADE; 级联清空表数据。
drop 删除表结构/库。
delete 删除数据。
```
<file_sep>/java/spring-mvc/cookie.md
spring.xml
```
<bean id="dcookieSerializer" class="xxxxxxxx.XXXXCookieSerializer"/>
<bean class="org.springframework.session.web.http.CookieHttpSessionStrategy">
<property name="cookieSerializer" ref="dcookieSerializer"/>
</bean>
```
可参考: org.springframework.session.web.http.DefaultCookieSerializer 实现接口:CookieSerializer
<file_sep>/linux/softs/影音/obs-studio.md
```
obs-studio 屏幕录制工具
```
<file_sep>/linux/common/servicfile.md
systemctl
servicename.service
```
[Unit]
Description=Network Manager
Documentation=man:NetworkManager(8)
Wants=network.target
After=network-pre.target dbus.service
Before=network.target
[Service]
Type=dbus
BusName=org.freedesktop.NetworkManager
ExecReload=/usr/bin/dbus-send --print-reply --system --type=method_call --dest=org.freedesktop.NetworkManager /org/freedesktop/NetworkManager org.freedesktop.NetworkManager.Reload uint32:0
#ExecReload=/bin/kill -HUP $MAINPID
ExecStart=/usr/bin/NetworkManager --no-daemon
Restart=on-failure
# NM doesn't want systemd to kill its children for it
KillMode=process
CapabilityBoundingSet=CAP_NET_ADMIN CAP_DAC_OVERRIDE CAP_NET_RAW CAP_NET_BIND_SERVICE CAP_SETGID CAP_SETUID CAP_SYS_MODULE CAP_AUDIT_WRITE CAP_KILL CAP_SYS_CHROOT
# ibft settings plugin calls iscsiadm which needs CAP_SYS_ADMIN
#CapabilityBoundingSet=CAP_SYS_ADMIN
ProtectSystem=true
ProtectHome=read-only
[Install]
WantedBy=multi-user.target
Alias=dbus-org.freedesktop.NetworkManager.service
Also=NetworkManager-dispatcher.service
# We want to enable NetworkManager-wait-online.service whenever this service
# is enabled. NetworkManager-wait-online.service has
# WantedBy=network-online.target, so enabling it only has an effect if
# network-online.target itself is enabled or pulled in by some other unit.
Also=NetworkManager-wait-online.service
```
<file_sep>/linux/shell_script/shell_script.md
nice
renice
nohup
dd
```
#!/bin/bash
if [ $# -gt 1 -o $# -eq 0 ]
then
# 只接受一个参数,参数个数不正确退出。
exit 1
fi
# 获取命令行参数
strnum=`echo $1 | tr -cd "[0-9]"`
echo $strnum
```
<file_sep>/python/flask/appbuilder/7_route.md
## 路由:
### falsk 路由:
```
app = Flask(__name__)
@app.route("/ping")
def ping():
return "OK"
pass
# 通过@app.route 注册路由
# 参考: http://docs.jinkan.org/docs/flask/quickstart.html#quickstart
```
appbuilder 通过继承view 来实现路由
<file_sep>/js/js/arguments.md
```
function example(){
var a = arguments[0] ? arguments[0] : 1;//设置第一个参数的默认值为1
var b = arguments[1] ? arguments[1] : 2;//设置第二个参数的默认值为2
return a+b;
}
arguments 变量保存了函数调用的参数
```
<file_sep>/java/note_spring/xsd_file.md
当同时使用多个spring版本时,未指定 xsd 版本时使用 运行时jar中的默认版本。
如果指定了xsd 版本而运行时不能通过网络获取,将使得项目启动报错。<file_sep>/docker/2_get_in_docker.md
参考: <https://www.cnblogs.com/xhyan/p/6593075.html>
常规方法:
```
docker run -it <容器id> /bin/bash
```
```
docker inspect -f {{.State.Pid}} <容器id> # 输出 <target>
nsenter --target <target> --mount --uts --ipc --net --pid
```
<file_sep>/js/tools.md
```bash
uglifyjs: 参考 https://www.cnblogs.com/zzsdream/p/5674866.html
uglifyjs: js 压缩为min.js
cnpm install uglify-js -g
uglifyjs inet.js -o inet-min.js
uglifyjs inet.js -m -o inet.min.js
----------------------------------------------------------------------------
grunt:多个js 压缩为一个文件,参考: https://www.gruntjs.net/getting-started
cnpm install -g grunt-cli
```
<file_sep>/linux/softwaremanager/pacman/pacman.md
pacman 用法:
```
pacman -Sy abc #和源同步后安装名为abc的包
pacman -S abc #从本地数据库中得到abc的信息,下载安装abc包
# pacman -Sf abc #强制安装包abc
# f 参数已经失效
pacman -Ss abc #搜索有关abc信息的包
pacman -Si abc #从数据库中搜索包abc的信息
pacman -Qi abc #列出已安装的包abc的详细信息
pacman -Qii package_name #使用两个 -i 将同时显示备份文件和修改状态
pacman -Qk package_name #检查软件包安装的文件是否都存在
pacman -Ql package_name #要获取已安装软件包所包含文件的列表
pacman -Syu #同步源,并更新系统
pacman -Sy #仅同步源
pacman -Su #更新系统
pacman -R abc #删除abc包
pacman -Rc abc #删除abc包和依赖abc的包
pacman -Rn package_name
pacman -Rsc abc #删除abc包和abc依赖的包
pacman -Rdd package_name #要删除软件包,但是不删除依赖这个软件包的其他程序
pacman -Sc #清理/var/cache/pacman/pkg目录下的旧包
pacman -Scc #清除所有下载的包和数据库
pacman -U abc #安装下载的abs包,或新编译的abc包
pacman -Sd abc #忽略依赖性问题,安装包abc
pacman pacman -Su --ignore foo #升级时不升级包foo
pacman -Sg abc #查询abc这个包组包含的软件包
pacman -Sw abc # 下载包而不安装
pactree package_name #要显示软件包的依赖树
pactree -r package_name #检查一个安装的软件包被那些包依赖
pacman -Qdt #罗列所有不再作为依赖的软件包(孤立orphans)
pacman -Qet #罗列所有明确安装而且不被其它包依赖的软件包
```
官方仓库:
```
```
非官方仓库:
```
参考: https://wiki.archlinux.org/index.php/Unofficial_user_repositories
分为签名的和未签名的仓库。
```
<file_sep>/sql/common/alter.md
```
ALTER TABLE table_name
ADD column_name datatype
ALTER TABLE table_name
DROP COLUMN column_name
ALTER TABLE table_name
DROP COLUMN column_name
ALTER TABLE table_name
ALTER COLUMN column_name datatype
```
<file_sep>/python/flask/appbuilder/3_flask_script.md
### 自定义command
```
pip install flask_script
```
基本用法参考: <https://www.cnblogs.com/buyisan/p/8270283.html>
```
#-*-coding:utf8-*-
from flask_script import Manager,Command,Server
from app import app
manager = Manager(app)
# 方式1
class Hello(Command):
'hello world 1'
def run(self):
print('hello world')
manager.add_command('hello', Hello())
# 方式2
@manager.command
def hello2():
'hello world 2 '
print('hello world')
# 方式3
@manager.option('-n', '--name', dest='name', help='Your name', default='world') #命令既可以用-n,也可以用--name,dest="name"用户输入的命令的名字作为参数传给了函数中的name
@manager.option('-u', '--url', dest='url', default='www.csdn.com') #命令既可以用-u,也可以用--url,dest="url"用户输入的命令的url作为参数传给了函数中的url
def hello3(name, url):
'hello world or hello <setting name>'
print('hello3', name)
print(url)
manager.add_command("runserver2", Server()) #命令是runserver
if __name__ == '__main__':
manager.run()
```
<file_sep>/js/questions_mark/source_path.md
问题描述:
```
npm run build 打包后的html 文件,引用js,css 使用绝对路径,导致资源访问失败。
```
解决方法:
```
config/index.js 中找到 build 配置:
assetsPublicPath: '/' 改为 assetsPublicPath: '',
```<file_sep>/linux/desktop-evn/gnome/gnome_extensions.md
gnome 版本:
```
gnome-shell --version
GNOME Shell 3.32.2
```
浏览器安装gnome-shell 插件
插件列表:
```
extensions 插件列表和开关
dash to dock : dock
dash to panel :panel(windows 习惯)
coverflow alt+tab :(alt-tab 切换)
tray icons : 托盘图标
wallpaper changer : 壁纸切换
```
```
菜单分组:
<https://github.com/BenJetson/gnome-dash-fix>
appfixer.sh 添加可执行权限并执行
```
<file_sep>/linux/shell_script/hash.md
```
check_program_installed() {
hash $1 > /dev/null 2>&1
if [ "$?" != "0" ]; then
print "command $1 not found. is it installed?."
exit 1
fi
}
```
```
if hash <cmd> 2>/dev/null; then
echo "exists"
else
echo "not exists"
fi
```
<file_sep>/js/amd_cmd_commonjs.md
```
参考 : https://juejin.im/post/59eafd2051882578c6738f69
模块开发
```
```
(function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// CommonJS
module.exports = factory(require('jquery'));
} else {
// 全局变量
root.returnExports = factory(root.jQuery);
}
}(this, function ($) {
// methods
function myFunc(){};
// exposed public method
return myFunc;
}));
```
<file_sep>/linux/arch/synaptics.md
触摸板配置:
参考:<https://blog.csdn.net/yangjvn/article/details/47185589>
```
pacman -S xf86-input-synaptics
#file: /etc/X11/xorg.conf.d/*-synaptics.conf
添加配置:
Section "InputClass"
Identifier "touchpad catchall"
Driver "synaptics"
MatchIsTouchpad "on"
Option "TapButton1" "1" #单指敲击产生左键事件
Option "TapButton2" "2" #双指敲击产生中键事件
Option "TapButton3" "3" #三指敲击产生右键事件
Option "VertEdgeScroll" "on" #滚动操作:横向、纵向、环形
Option "VertTwoFingerScroll" "on"
Option "HorizEdgeScroll" "on"
Option "HorizTwoFingerScroll" "on"
Option "CircularScrolling" "on"
Option "CircScrollTrigger" "2"
Option "EmulateTwoFingerMinZ" "40" #精确度
Option "EmulateTwoFingerMinW" "8"
Option "CoastingSpeed" "20" #触发快速滚动的滚动速度
Option "PalmDetect" "1" #避免手掌触发触摸板
Option "PalmMinWidth" "3" #认定为手掌的最小宽度
Option "PalmMinZ" "200" #认定为手掌的最小压力值
EndSection
注销后重新登录
```
触摸板开关:(安装xfce4-notifyd 用于提示)
```
#!/bin/bash
status=`synclient -l | grep TouchpadOff | awk '{print $3}'`
if [ $status -eq 0 ]
then
synclient TouchpadOff=1
notify-send "Touchpad is disabled!" --icon=$HOME/.icons/myicons/touchpad-disable-icon-th.png
elif [ $status -eq 1 ]
then
synclient TouchpadOff=0
notify-send "Touchpad is enabled!" --icon=$HOME/.icons/myicons/touchpad-enable-icon-th.png
fi
```
<file_sep>/linux/shell_script/重定向.md
```
标准输入stdin:对应的文件描述符是0,符号是<和<<,/dev/stdin -> /proc/self/fd/0
标准输出stdout:对应的文件描述符是1,符号是>和>>,/dev/stdout -> /proc/self/fd/1
标准错误stderr:对应的文件描述符是2,符号是2>和2>>,/dev/stderr -> /proc/self/fd/2
2>&1
```
<file_sep>/js/webpack/knockout.md
```
https://blog.csdn.net/phj_88/article/details/81416335
cnpm install html-loader koc-loader --save
```
<file_sep>/golang/libs/martini/0_desc.md
https://github.com/go-martini/martini
Martini是一个强大为了编写模块化Web应用而生的GO语言框架.<file_sep>/linux/shell_script/function.md
```
function_name(){
echo "这是我的第一个 shell 函数!"
}
```
<file_sep>/linux/common/patch.md
补丁:
通过diff 生成补丁文件,通过patch 打补丁
```
diff -ur
diff -u
patch -R
patch
```
example:
```
$ tree
.
├── v1
│ └── a
└── v2
└── a
$ diff -ur v1 v2 > patch
```
```
p0
补丁:
$ patch -p0 <patch
patching file v1/a
恢复:
$ patch -R -p0 <patch
patching file v1/a
```
```
p1
补丁:
v1 $ patch -p1 <../patch
patching file a
恢复:
v1 $ patch -R -p1 <../patch
patching file a
```
```
$ cat patch
diff -ur v1/a v2/a
-p 剥离层级
patch 执行路径与patch 中的文件的层级关系。
在v1,v2 同级时执行patch: v1/a v2/a 剥离层级0, 留下 v1/a v2/a : 当前路径开始找 ./v1/a ./v2/2
在v1,v2 目录下执行patch:需剥离 v1,v2 剥离层级1, 留下 a a : 当前路径开始找 ./a ./a
及 ./ 开始 。 patch diff 路径截取多少层目录后是匹配的。
```
<file_sep>/linux/softs/filemanager/nautilus.md
terminal:
```
$ yay -S nautilus-open-any-terminal
## 设置alacritty 为打开的terminal。
$ gsettings set com.github.stunkymonkey.nautilus-open-any-terminal terminal alacritty
```
绑定:
```
~/.local/share/nautilus/scripts: 添加需要执行的脚本。
~/.local/share/nautilus/scripts/open-terminal-here
$ cat ~/.local/share/nautilus/scripts/open-terminal-here
# !/usr/bin/env bash
alacritty
~/.config/nautilus/scripts-accels : 配置将脚本与快捷键绑定。
$ cat ~/.config/nautilus/scripts-accels
F12 open-terminal-here
```
<file_sep>/linux/common/system_date.md
```
执行tzselect命令-->选择Asia-->选择China-->选择east China - Beijing, Shanghai, etc-->然后输入1
TZ='Asia/Shanghai'; export TZ
----------------------------------------------------------------------------------------
# rm -f /etc/localtime
# ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
----------------------------------------------------------------------------------------
timedatectl set-timezone Asia/Shanghai
```
<file_sep>/linux/common/date.md
时间戳转时间:
```
$ /usr/bin/date -d @1591239581
Thu 04 Jun 2020 10:59:41 AM CST
```
当前时间戳:()
```
$ /usr/bin/date +%s
```
<file_sep>/linux/common/file_permission.md
常规权限:
```
权限分为三种:读(r=4),写(w=2),执行(x=1)。
可读可执行 (rx=5=4+1)
可读可写 (rw=6=4+2)
可读可写可执行 (rwx=7=4+2+1)。
---------------------------------------------------------------------------
文件权限修改可指定对应的数字来修改,也可使用对应的字母来修改。
---------------------------------------------------------------------------
权限数字:【owner权限】【group权限】【others权限】
chmod 权限数字 文件名
---------------------------------------------------------------------------
chmod u+x 文件名 : 其owner授予执行权限
chmod go-rw 文件名 :删除group和others的读和写权限
chmod o=w 文件名 : others配置写权限
- 表示删除权限
= 表示使之成为唯一的权限
u 代表所有者(user)
g 代表所有者所在的组群(group)
o 代表其他人,但不是u和g (other)
a 代表全部的人,也就是包括u,g和o
r 表示文件可以被读(read)
w 表示文件可以被写(write)
x 表示文件可以被执行
---------------------------------------------------------------------------
chmod 777 文件名 , 等价于 chmod a+wrx 文件名 等价于 chmod a=wrx 文件名
```
![image][tmp]
特殊权限:
```
---------------------------------------------------------------------------
SetUID(简称suid)(数字权限是4000)
4表示其他用户执行文件时,具有与所有者相当的权限
1.普通用户对可执行的二进制文件,临时拥有二进制文件的属主权限;
2.如果设置的二进制文件没有执行权限,那么suid的权限显示就是S(大写字母S);
3.特殊权限suid仅对二进制可执行程序有效,其他文件或目录则无效。
$ ll /usr/bin/sudo
-rwsr-xr-x 1 root root 140792 10月 29 17:36 /usr/bin/sudo
chmod u+s 文件名
chmod +s 文件名
chmod -s 文件名
文件夹也可配置s权限。
---------------------------------------------------------------------------
setGID(简称sgid)(数字权限是2000)
chmod g+s 文件名
主要是针对目录进行授权,共享目录。
组权限位上有执行权限,则会在属组主权限位的执行权限上写个s(小写字母)
如果该属组权限位上没有执行权限,则会在属组主权限位的执行权限上写个S
1.针对用户组权限位修改,用户创建的目录或文件所属组和该目录的所属组一致。
2.当某个目录设置了sgid后,在该目录中新建的文件不再是创建该文件的默认所属组 (*)
3.使用sgid可以使得多个用户之间共享一个目录的所有文件变得简单。
chmod a+s 文件名 (suid+sgid)
---------------------------------------------------------------------------
注: o 加s ,ll 没看出权限变化
---------------------------------------------------------------------------
sbit 粘滞位(数字权限是1000)
chmod o+t 目录
粘滞位,即便是该目录拥有w权限,但是除了root用户,其他用户只能对自己的文件进行删除、移动操作。
其他用户权限位上有执行权限,则会在其他用户权限位的执行权限上写个t(小写字母); 如果该其它用户权限位上没有执行权限,则会在其他用户权限位的执行权限上写个T(大写字母)。
普通用户对该目录拥有w和x权限,即普通用户可以在此目录中拥有写入权限,如果没有粘滞位,那么普通用户拥有w权限,就可以删除此目录下的所有文件,包括其他用户建立的文件。
但是一旦被赋予了粘滞位,除了root可以删除所有文件,普通用户就算有w权限也只能删除自己建立的文件,而不能删除其他用户建立的文件。
---------------------------------------------------------------------------
chattr:凌驾于r、w、x、suid、sgid之上的权限。
设置特殊权限,chattr命令用来改变文件属性。
i #锁定文件,不能编辑,不能修改,不能删除,不能移动,可以执行
a #仅可以追加文件,不能编辑,不能删除,不能移动,可以执行
chattr +i 文件 :防止系文件被修改。
chattr +a 文件 :只能往里面追加内容,不能删除
---------------------------------------------------------------------------
Linux进程掩码 umask
登录系统之后,创建一个文件总是有一个默认权限.umask设置了用户创建文件的默认权限。
系统默认umask为022,那么当我们创建一个目录时,正常情况下目录的权限应该是777,但是umask表示要减去的值,所以新目录文件的权限应该是777-022=755。至于文件的权限也依次类推:666-022=644
文件:默认权限只能是0,2,4 组合,即只能是0,2,4,6。
文件666-umask 后的值于权限对应关系: 6->6;5->6;4->4;3->4;2->2;1->2;0->0。 减后值为奇数则+1.
文件基数为666,目录为777
chmod是设哪个位,哪么哪个位就有权限,而umask是设哪个位,则哪个位上就没权限
```
[tmp]:data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAjgAAACgCAIAAACOvYGmAAAgAElEQVR4nO3df0wb+Z038E9v69Epoz7x3Il5KuwKnGfBFfKJxE+Qn0OxkKxEkOjxUgUieTeCpOcsh5vUe2xoEkssKZTWGxaWWyc5cxHubuCyQS3kOdanhKipT9SIXYscCarFU8cJJqptqWOpdrQ70e2Mnsvzh0MC5lc2JODA+/UP2DMef2dsz3u+P2bmW48ePSIAAIBs9RfrXQAAAIDlfHt6enq9ywAAALCkbxPRtm3b1rsY2Wt6ehrbZ71g4wNtrK/<KEY>
<file_sep>/java/java_common/Generic.md
参考 https://www.cnblogs.com/coprince/p/8603492.html
泛型有三种使用方式,分别为:泛型类、泛型接口、泛型方法
```
泛型类:
-----------------------------------------
泛型类型用于类的定义中,被称为泛型类。通过泛型可以完成对一组类的操作对外开放相同的接口。最典型的就是各种容器类,如:List、Set、Map。
```
```java
//此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型
//在实例化泛型类时,必须指定T的具体类型
public class Generic<T>{
//key这个成员变量的类型为T,T的类型由外部指定
private T key;
public Generic(T key) { //泛型构造方法形参key的类型也为T,T的类型由外部指定
this.key = key;
}
public T getKey(){ //泛型方法getKey的返回值类型为T,T的类型由外部指定
return key;
}
}
```
```
泛型接口:
------------------------------------------------------------
泛型接口与泛型类的定义及使用基本相同。泛型接口常被用在各种类的生产器中。
```
```java
//定义一个泛型接口
public interface Generator<T> {
public T next();
}
/**
* 未传入泛型实参时,与泛型类的定义相同,在声明类的时候,需将泛型的声明也一起加到类中
* 即:class FruitGenerator<T> implements Generator<T>{
* 如果不声明泛型,如:class FruitGenerator implements Generator<T>,编译器会报错:"Unknown class"
*/
class FruitGenerator<T> implements Generator<T>{
@Override
public T next() {
return null;
}
}
/**
* 传入泛型实参时:
* 定义一个生产器实现这个接口,虽然我们只创建了一个泛型接口Generator<T>
* 但是我们可以为T传入无数个实参,形成无数种类型的Generator接口。
* 在实现类实现泛型接口时,如已将泛型类型传入实参类型,则所有使用泛型的地方都要替换成传入的实参类型
* 即:Generator<T>,public T next();中的的T都要替换成传入的String类型。
*/
public class FruitGenerator implements Generator<String> {
private String[] fruits = new String[]{"Apple", "Banana", "Pear"};
@Override
public String next() {
Random rand = new Random();
return fruits[rand.nextInt(3)];
}
}
```
```
泛型方法:
---------------------------------------------------------------
泛型类,是在实例化类的时候指明泛型的具体类型;
泛型方法,是在调用方法的时候指明泛型的具体类型 。
```
```java
/**
* 泛型方法的基本介绍
* @param tClass 传入的泛型实参
* @return T 返回值为T类型
* 说明:
* 1)public 与 返回值中间<T>非常重要,可以理解为声明此方法为泛型方法。
* 2)只有声明了<T>的方法才是泛型方法,泛型类中的使用了泛型的成员方法并不是泛型方法。
* 3)<T>表明该方法将使用泛型类型T,此时才可以在方法中使用泛型类型T。
* 4)与泛型类的定义一样,此处T可以随便写为任意标识,常见的如T、E、K、V等形式的参数常用于表示泛型。
*/
public <T> T genericMethod(Class<T> tClass)throws InstantiationException ,
IllegalAccessException{
T instance = tClass.newInstance();
return instance;
}
```
<file_sep>/python/pip/pip_config.md
### pip source
```
Python官方: https://pypi.python.org/simple/
v2ex : http://pypi.v2ex.com/simple/
清华:https://pypi.tuna.tsinghua.edu.cn/simple
阿里云:http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
华中理工大学:http://pypi.hustunique.com/
山东理工大学:http://pypi.sdutlinux.org/
豆瓣:https://pypi.douban.com/simple/
```
### pip source config
```
~/.pip/pip.conf
[global]
index-url=https://pypi.douban.com/simple
[install]
trusted-host=pypi.douban.com
```
### solutions:
```
The repository located at pypi.doubanio.com is not a trusted or secure host and is being ignored.
~/.pip/pip.conf 中将 http 换为 https
```
### windows:
```
(1):在windows文件管理器中,输入 **%APPDATA%**
(2):会定位到一个新的目录下,在该目录下新建pip文件夹,然后到pip文件夹里面去新建个pip.ini文件
(3):在新建的pip.ini文件中输入以下内容,搞定文件路径:pip\pip.ini
```
<file_sep>/regular_expression/regularexpression.md
* 正则表达式
<https://zh.wikipedia.org/wiki/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F>
```
\ 转义
^ 匹配输入字符串的开始位置,如果设置了RegExp对象的Multiline属性,^也匹配“\n”或“\r”之后的位置。
$ 匹配输入字符串的结束位置,如果设置了RegExp对象的Multiline属性,^也匹配“\n”或“\r”之后的位置。
* 匹配前面的子表达式零次或多次: zo*能匹配“z”、“zo”以及“zoo”。 *等价于{0,}。
+ 匹配前面的子表达式一次或多次:
? 匹配前面的子表达式零次或一次
{n} n是一个非负整数。匹配确定的n次。
{n,} n是一个非负整数。至少匹配n次。
{n,m} m和n均为非负整数,其中n<=m。最少匹配n次且最多匹配m次
. 匹配除“\r”“\n”之外的任何单个字符。要匹配包括“\r”“\n”在内的任何字符,请使用像“(.|\r|\n)”的模式。
(pattern) 匹配pattern并获取这一匹配的子字符串。该子字符串用于向后引用。所获取的匹配可以从产生的Matches集合得到.
(?:pattern) 匹配pattern但不获取匹配的子字符串(shy groups),也就是说这是一个非获取匹配,不存储匹配的子字符串用于向后引用。例如“industr(?:y|ies)”就是一个比“industry|industries”更简略的表达式。
(?=pattern) 正向肯定预查(look ahead positive assert),在任何匹配pattern的字符串开始处匹配查找字符串。这是一个非获取匹配。例如: "Windows(?=95|98|NT|2000)”能匹配“Windows2000”中的“Windows”,但不能匹配“Windows3.1”中的“Windows”
(?!pattern) 正向否定预查(negative assert),在任何不匹配pattern的字符串开始处匹配查找字符串。例如“Windows(?!95|98|NT|2000)”能匹配“Windows3.1”中的“Windows”,但不能匹配“Windows2000”中的“Windows”
(?<=pattern) 反向(look behind)肯定预查,与正向肯定预查类似,只是方向相反。例如,“(?<=95|98|NT|2000)Windows”能匹配“2000Windows”中的“Windows”,但不能匹配“3.1Windows”中的“Windows”。
(?<!pattern) 反向否定预查,与正向否定预查类似,只是方向相反。例如“(?<!95|98|NT|2000)Windows”能匹配“3.1Windows”中的“Windows”,但不能匹配“2000Windows”中的“Windows”。
x|y 没有包围在()里,其范围是整个正则表达式
[xyz] 匹配所包含的任意一个字符
[^xyz] 匹配未列出的任意字符
[a-z] 例如,“[a-z]”可以匹配“a”到“z”范围内的任意小写字母字符。
[^a-z] 例如,“[^a-z]”可以匹配任何不在“a”到“z”范围内的任意字符。
[:name:] 只能用于方括号表达式。增加命名字符类(named character class中的字符到表达式
[=elt=] 增加当前locale下排序(collate)等价于字符“elt”的元素。例如,[=a=]可能会增加ä、á、à、ă、ắ、ằ、ẵ、ẳ、â、ấ、ầ、ẫ、ẩ、ǎ、å、ǻ、ä、ǟ、ã、ȧ、ǡ、ą、ā、ả、ȁ、ȃ、ạ、ặ、ậ、ḁ、ⱥ、ᶏ、ɐ、ɑ 。只能用于方括号表达式。
[.elt.] 增加排序元素(collation element)elt到表达式中。这是因为某些排序元素由多个字符组成。例如,29个字母表的西班牙语, "CH"作为单个字母排在字母C之后,因此会产生如此排序“cinco, credo, chispa”。只能用于方括号表达式。
\b 匹配一个单词边界,也就是指单词和空格间的位置。例如,“er\b”可以匹配“never”中的“er”,但不能匹配“verb”中的“er”。
\B 匹配非单词边界。“er\B”能匹配“verb”中的“er”,但不能匹配“never”中的“er”。
\cx 匹配由x指明的控制字符。例如,\cM匹配一个Control-M或回车符。x的值必须为A-Z或a-z之一。否则,将c视为一个原义的“c”字符。
\d 匹配一个数字字符。等价于[0-9]。注意Unicode正则表达式会匹配全角数字字符。
\D 匹配一个非数字字符。等价于[^0-9]。
\f 匹配一个换页符。等价于\x0c和\cL。
\n 匹配一个换行符。等价于\x0a和\cJ。
\r 匹配一个回车符。等价于\x0d和\cM。
\s 匹配任何空白字符,包括空格、制表符、换页符等等。等价于[ \f\n\r\t\v]。注意Unicode正则表达式会匹配全角空格符。
\S 匹配任何非空白字符。等价于[^ \f\n\r\t\v]。
\t 匹配一个制表符。等价于\x09和\cI。
\v 匹配一个垂直制表符。等价于\x0b和\cK。
\w 匹配包括下划线的任何单词字符。等价于“[A-Za-z0-9_]”。注意Unicode正则表达式会匹配中文字符。
\W 匹配任何非单词字符。等价于“[^A-Za-z0-9_]”。
\ck 匹配控制转义字符。k代表一个字符。等价于“Ctrl-k”。用于ECMA语法。
正则表达式[\w]+,\w+,[\w+] 三者有何区别:
[\w]+和\w+没有区别,都是匹配数字和字母下划线的多个字符;
[\w+]表示匹配数字、字母、下划线和加号本身字符;
```
预查:
```
var s = "abc"
console.log(/a(?=b)bc/.test(s))
console.log(/a(b)bc/.test(s))
true
false
/a(?=b)bc/中的正向肯定预查(?=b)匹配了a后面的字母b,但是并没有消耗它,所以,后面再跟一个“bc”串,这就完整地匹配了字符串“abc”。其实,它的真正意义应该是确定了这个字母a,因为不是每个字母a后面都会跟一个字母b的!
而a(b)bc因为匹配并消耗了字母a后面的b,再来添加一个“bc”串的时候,就变成了“abbc”,就不能匹配字符串“abc”。
```
<file_sep>/python/somelib/wx.md
图形界面库
```python
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import wx
import wx.lib.buttons
import cPickle
import os
class PaintWindow(wx.Window):
def __init__(self, parent, id):
wx.Window.__init__(self, parent, id)
self.SetBackgroundColour("Red")
self.color = "Green"
self.thickness = 10
#创建一个画笔
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
self.lines = []
self.curLine = []
self.pos = (0, 0)
self.InitBuffer()
#连接事件
self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftDown)
self.Bind(wx.EVT_LEFT_UP, self.OnLeftUp)
self.Bind(wx.EVT_MOTION, self.OnMotion)
self.Bind(wx.EVT_SIZE, self.OnSize)
self.Bind(wx.EVT_IDLE, self.OnIdle)
self.Bind(wx.EVT_PAINT, self.OnPaint)
def InitBuffer(self):
size = self.GetClientSize()
#创建缓存的设备上下文
self.buffer = wx.EmptyBitmap(size.width, size.height)
dc = wx.BufferedDC(None, self.buffer)
#使用设备上下文
dc.SetBackground(wx.Brush(self.GetBackgroundColour()))
dc.Clear()
self.DrawLines(dc)
self.reInitBuffer = False
def GetLinesData(self):
return self.lines[:]
def SetLinesData(self, lines):
self.lines = lines[:]
self.InitBuffer()
self.Refresh()
def OnLeftDown(self, event):
self.curLine = []
#获取鼠标位置
self.pos = event.GetPositionTuple()
self.CaptureMouse()
def OnLeftUp(self, event):
if self.HasCapture():
self.lines.append((self.color,
self.thickness,
self.curLine))
self.curLine = []
self.ReleaseMouse()
def OnMotion(self, event):
if event.Dragging() and event.LeftIsDown():
dc = wx.BufferedDC(wx.ClientDC(self), self.buffer)
self.drawMotion(dc, event)
event.Skip()
def drawMotion(self, dc, event):
dc.SetPen(self.pen)
newPos = event.GetPositionTuple()
coords = self.pos + newPos
self.curLine.append(coords)
dc.DrawLine(*coords)
self.pos = newPos
def OnSize(self, event):
self.reInitBuffer = True
def OnIdle(self, event):
if self.reInitBuffer:
self.InitBuffer()
self.Refresh(False)
def OnPaint(self, event):
dc = wx.BufferedPaintDC(self, self.buffer)
def DrawLines(self, dc):
for colour, thickness, line in self.lines:
pen = wx.Pen(colour, thickness, wx.SOLID)
dc.SetPen(pen)
for coords in line:
dc.DrawLine(*coords)
def SetColor(self, color):
self.color = color
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
def SetThickness(self, num):
self.thickness = num
self.pen = wx.Pen(self.color, self.thickness, wx.SOLID)
class PaintFrame(wx.Frame):
def __init__(self, parent):
self.title = "Paint Frame"
wx.Frame.__init__(self, parent, -1, self.title, size = (800, 600))
self.paint = PaintWindow(self, -1)
#状态栏
self.paint.Bind(wx.EVT_MOTION, self.OnPaintMotion)
self.InitStatusBar()
#创建菜单
self.CreateMenuBar()
self.filename = ""
#创建工具栏使用的面板
self.CreatePanel()
def CreatePanel(self):
controlPanel = ControlPanel(self, -1, self.paint)
box = wx.BoxSizer(wx.HORIZONTAL) #放置水平的box sizer
box.Add(controlPanel, 0, wx.EXPAND) #水平方向伸展时不改变尺寸
box.Add(self.paint, -1, wx.EXPAND)
self.SetSizer(box)
def InitStatusBar(self):
self.statusbar = self.CreateStatusBar()
#将状态栏分割为3个区域,比例为1:2:3
self.statusbar.SetFieldsCount(3)
self.statusbar.SetStatusWidths([-1, -2, -3])
def OnPaintMotion(self, event):
#设置状态栏1内容
self.statusbar.SetStatusText(u"鼠标位置:" + str(event.GetPositionTuple()), 0)
#设置状态栏2内容
self.statusbar.SetStatusText(u"当前线条长度:%s" % len(self.paint.curLine), 1)
#设置状态栏3内容
self.statusbar.SetStatusText(u"线条数目:%s" % len(self.paint.lines), 2)
event.Skip()
def MenuData(self):
'''
菜单数据
'''
#格式:菜单数据的格式现在是(标签, (项目)),其中:项目组成为:标签, 描术文字, 处理器, 可选的kind
#标签长度为2,项目的长度是3或4
return [("&File", ( #一级菜单项
("&New", "New paint file", self.OnNew), #二级菜单项
("&Open", "Open paint file", self.OnOpen),
("&Save", "Save paint file", self.OnSave),
("", "", ""), #分隔线
("&Color", (
("&Black", "", self.OnColor, wx.ITEM_RADIO), #三级菜单项,单选
("&Red", "", self.OnColor, wx.ITEM_RADIO),
("&Green", "", self.OnColor, wx.ITEM_RADIO),
("&Blue", "", self.OnColor, wx.ITEM_RADIO),
("&Other", "", self.OnOtherColor, wx.ITEM_RADIO))),
("", "", ""),
("&Quit", "Quit", self.OnCloseWindow)))
]
def CreateMenuBar(self):
'''
创建菜单
'''
menuBar = wx.MenuBar()
for eachMenuData in self.MenuData():
menuLabel = eachMenuData[0]
menuItems = eachMenuData[1]
menuBar.Append(self.CreateMenu(menuItems), menuLabel)
self.SetMenuBar(menuBar)
def CreateMenu(self, menuData):
'''
创建一级菜单
'''
menu = wx.Menu()
for eachItem in menuData:
if len(eachItem) == 2:
label = eachItem[0]
subMenu = self.CreateMenu(eachItem[1])
menu.AppendMenu(wx.NewId(), label, subMenu) #递归创建菜单项
else:
self.CreateMenuItem(menu, *eachItem)
return menu
def CreateMenuItem(self, menu, label, status, handler, kind = wx.ITEM_NORMAL):
'''
创建菜单项内容
'''
if not label:
menu.AppendSeparator()
return
menuItem = menu.Append(-1, label, status, kind)
self.Bind(wx.EVT_MENU, handler,menuItem)
def OnNew(self, event):
pass
def OnOpen(self, event):
'''
打开开文件对话框
'''
file_wildcard = "Paint files(*.paint)|*.paint|All files(*.*)|*.*"
dlg = wx.FileDialog(self, "Open paint file...",
os.getcwd(),
style = wx.OPEN,
wildcard = file_wildcard)
if dlg.ShowModal() == wx.ID_OK:
self.filename = dlg.GetPath()
self.ReadFile()
self.SetTitle(self.title + '--' + self.filename)
dlg.Destroy()
def OnSave(self, event):
'''
保存文件
'''
if not self.filename:
self.OnSaveAs(event)
else:
self.SaveFile()
def OnSaveAs(self, event):
'''
弹出文件保存对话框
'''
file_wildcard = "Paint files(*.paint)|*.paint|All files(*.*)|*.*"
dlg = wx.FileDialog(self,
"Save paint as ...",
os.getcwd(),
style = wx.SAVE | wx.OVERWRITE_PROMPT,
wildcard = file_wildcard)
if dlg.ShowModal() == wx.ID_OK:
filename = dlg.GetPath()
if not os.path.splitext(filename)[1]: #如果没有文件名后缀
filename = filename + '.paint'
self.filename = filename
self.SaveFile()
self.SetTitle(self.title + '--' + self.filename)
dlg.Destroy()
def OnColor(self, event):
'''
更改画笔内容
'''
menubar = self.GetMenuBar()
itemid = event.GetId()
item = menubar.FindItemById(itemid)
color = item.GetLabel() #获取菜单项内容
self.paint.SetColor(color)
def OnOtherColor(self, event):
'''
使用颜色对话框
'''
dlg = wx.ColourDialog(self)
dlg.GetColourData().SetChooseFull(True) #创建颜色对象数据
if dlg.ShowModal() == wx.ID_OK:
self.paint.SetColor(dlg.GetColourData().GetColour()) #根据选择设置画笔颜色
dlg.Destroy()
def OnCloseWindow(self, event):
self.Destroy()
def SaveFile(self):
'''
保存文件
'''
if self.filename:
data = self.paint.GetLinesData()
f = open(self.filename, 'w')
cPickle.dump(data, f)
f.close()
def ReadFile(self):
if self.filename:
try:
f = open(self.filename, 'r')
data = cPickle.load(f)
f.close()
self.paint.SetLinesData(data)
except cPickle.UnpicklingError:
wx.MessageBox("%s is not a paint file."
% self.filename, "error tip",
style = wx.OK | wx.ICON_EXCLAMATION)
class ControlPanel(wx.Panel):
BMP_SIZE = 16
BMP_BORDER = 3
NUM_COLS = 4
SPACING = 4
colorList = ('Black', 'Yellow', 'Red', 'Green', 'Blue', 'Purple',
'Brown', 'Aquamarine', 'Forest Green', 'Light Blue',
'Goldenrod', 'Cyan', 'Orange', 'Navy', 'Dark Grey',
'Light Grey')
maxThickness = 16
def __init__(self, parent, ID, paint):
wx.Panel.__init__(self, parent, ID, style = wx.RAISED_BORDER)
self.paint = paint
buttonSize = (self.BMP_SIZE + 2 * self.BMP_BORDER,
self.BMP_SIZE + 2 * self.BMP_BORDER)
colorGrid = self.createColorGrid(parent, buttonSize) #创建颜色grid sizer
thicknessGrid = self.createThicknessGrid(buttonSize) #创建线条grid sizer
self.layout(colorGrid, thicknessGrid)
def createColorGrid(self, parent, buttonSize):
self.colorMap = {}
self.colorButtons = {}
colorGrid = wx.GridSizer(cols = self.NUM_COLS, hgap = 2, vgap = 2)
for eachColor in self.colorList:
bmp = self.MakeBitmap(eachColor)
b = wx.lib.buttons.GenBitmapToggleButton(self, -1, bmp, size = buttonSize)
b.SetBezelWidth(1)
b.SetUseFocusIndicator(False)
self.Bind(wx.EVT_BUTTON, self.OnSetColour, b)
colorGrid.Add(b, 0)
self.colorMap[b.GetId()] = eachColor
self.colorButtons[eachColor] = b
self.colorButtons[self.colorList[0]].SetToggle(True)
return colorGrid
def createThicknessGrid(self, buttonSize):
self.thicknessIdMap = {}
self.thicknessButtons = {}
thicknessGrid = wx.GridSizer(cols = self.NUM_COLS, hgap = 2, vgap = 2)
for x in range(1, self.maxThickness + 1):
b = wx.lib.buttons.GenToggleButton(self, -1, str(x), size = buttonSize)
b.SetBezelWidth(1)
b.SetUseFocusIndicator(False)
self.Bind(wx.EVT_BUTTON, self.OnSetThickness, b)
thicknessGrid.Add(b, 0)
self.thicknessIdMap[b.GetId()] = 2
self.thicknessButtons[x] = b
self.thicknessButtons[1].SetToggle(True)
return thicknessGrid
def layout(self, colorGrid, thicknessGrid):
box = wx.BoxSizer(wx.VERTICAL) #使用垂直的box szier放置grid sizer
box.Add(colorGrid, 0, wx.ALL, self.SPACING) #参数0表示在垂直方向伸展时不改变尺寸
box.Add(thicknessGrid, 0, wx.ALL, self.SPACING)
self.SetSizer(box)
box.Fit(self)
def OnSetColour(self, event):
color = self.colorMap[event.GetId()]
if color != self.paint.color:
self.colorButtons[self.paint.color].SetToggle(False)
self.paint.SetColor(color)
def OnSetThickness(self, event):
thickness = self.thicknessIdMap[event.GetId()]
if thickness != self.paint.thickness:
self.thicknessButtons[self.paint.thickness].SetToggle(False)
self.paint.SetThickness(thickness)
def MakeBitmap(self, color):
bmp = wx.EmptyBitmap(16, 15)
dc = wx.MemoryDC(bmp)
dc.SetBackground(wx.Brush(color))
dc.Clear()
dc.SelectObject(wx.NullBitmap)
return bmp
if __name__ == '__main__':
app = wx.PySimpleApp()
frame = PaintFrame(None)
frame.Show(True)
app.MainLoop()
```
<file_sep>/windows/netsh.md
```
#: 以管理员身份运行
能ping通dns, 但无法解析域名
# netsh winsock reset catalog
重启网络(禁用网卡,启用网卡):
netsh interface set interface 网卡名 disabled
netsh interface set interface 网卡名 enabled
eg:
# netsh interface set interface 以太网 disabled
# netsh interface set interface 以太网 enabled
```
<file_sep>/linux/softwaremanager/zypper/zypper.md
```
zypper refresh
(cnf 命令: 在仓库中查找包)
```
```
参考: https://blog.51cto.com/watchmen/1933902
```
<file_sep>/java/spring-mvc/sqlSessionFactory.md
```
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
</bean>
```
```
org.mybatis.spring.SqlSessionFactoryBean
public void setDataSource(DataSource dataSource) {
if (dataSource instanceof TransactionAwareDataSourceProxy) {
this.dataSource = ((TransactionAwareDataSourceProxy) dataSource).getTargetDataSource();
} else {
this.dataSource = dataSource;
}
}
```
dataSource实现 getTargetDataSource() 可用作动态选择数据库。 [未验证]<file_sep>/java/springboot/guid.md
@SpringBootApplication
@Controller 返回viewname
@RestController 返回data(eg: string,json)
@JsonIgnore : 对象转json 忽略属性
@JsonFormat(...): 对象转json 时 属性format
@JsonInclude(...) : 对象转json 时,属性满足一定条件才进入json
@ControllerAdvice
@ExceptionHandler
@EnableScheduling //开启定时任务
@EnableAsync //开启异步调用方法
@Async // 异步调用方法修饰
-----------------------------------------------------------------------------------------------------------------------------------------------------------
```
------------------------------------------------------------------------------------
@Controller
------------------------------------------------------------------------------------
参考: https://blog.csdn.net/qq_33800083/article/details/80166144
@Scope描述的是Spring容器是如何新建bean实例的
1.Singleton:一个spring容器只有一个bean的容器(spring默认配置)
2.prototype:每次调用新建一个bean
3.request:web项目中,每一个http request新建一个bean实例
4.session:web项目中,给每一个http session新建一个bean实例
5. global-session 该作用域将bean的定义限制为全局HTTP会话。
------------------------------------------------------------------------------------
参考: https://blog.csdn.net/siwuxie095/article/details/79407097?utm_source=copy
@RequestMapping
作用与class: 不是完整的url
作用与method: 完整url由作用与类上的url 与作用于方法上的url 拼接 而成.
限制请求方法:@RequestMapping(value="/hello", method=RequestMethod.POST)
method={RequestMethod.GET,RequestMethod.POST}
限制请求参数:
params="userId" 请求参数中必须包含 userId
params="!userId" 请求参数中不能包含 userId
params="userId!=1" 请求参数中必须包含 userId,但不能为 1
params={"userId","userName"} 必须包含 userId 和 userName 参数
映射单个URL
@RequestMapping("") 或 @RequestMapping(value="")
映射多个URL
@RequestMapping({"",""}) 或 @RequestMapping(value={"",""})
路径开头是否加斜杠/均可,建议加上,如:@RequestMapping("/hello")
简单映射: "/hello"
匹配映射:? 匹配任何单字符,* 匹配任意数量的字符(含 0 个),** 匹配任意数量的目录(含 0 个)
占位映射: 通过@PathVariable("") 注解将占位符中的值绑定到方法参数上
@RequestMapping("/user/{userId}/show")
public ModelAndView show(@PathVariable("userId") Long userId) {
----------------------------------------------------------------------------------
参考: https://blog.csdn.net/swebin/article/details/92795422
@RequestParam("") 注解将请求参数绑定到方法参数上
@ReqeustBody:
常用来处理content-type不是默认的application/x-www-form-urlcoded编码的内容,
好比:application/json或者是application/xml等,常常用来其来处理application/json类型
注意:@requestBody接收的是前端传过来的json字符串,而不是对象
请求参数:
简单参数:
表单中input的name值和Controller的参数变量名保持一致;
不一致时:可使用 @RequestParam 来指定需要绑定的表单参数
实体类参数:
表单中input的name值 与实体类的属性名一致
时间类型等需要做转换
复合POJO(实体类)类型的绑定:
表单name属性值: 复合属性名.字段名 name="ojbxx.propetyxxx"
数组类型: form中 name值相同的输入值构成的集合
```
<file_sep>/linux/common/scp.md
```
scp username@remotehost:/path/directory/\{foo.txt,bar.txt\} .
```
参考:<https://www.binarytides.com/linux-scp-command/>
```
使用ssh+tar 传输文件: 在目标主机上文件所有者/权限一致
# 边压缩边传输
使用cat 输出文件
tar -zcvf - ./ |ssh username@targethost "cat >/targetpatch/xxx.tar.gz
# 边压缩边传输
使用dd生成文件
tar -zcvf - ./ |ssh username@targethost "dd of=/targetpatch/xxx.tar.gz
使用cat 输出文件,同时解压
tar -zcvf - ./ |ssh username@targethost "tar -zxvf - -C /targetpatch"
```
<file_sep>/linux/softs/appimages.md
```
QQmusic
QQ音乐官网可下载(https://y.qq.com/download/download.html)
Another-Redis-Desktop-Manager
(https://github.com/qishibo/AnotherRedisDesktopManager)
draw.io
(https://github.com/jgraph/drawio-desktop/releases ; https://app.diagrams.net/)
balenaEtcher
( https://www.balena.io/etcher/ )
```
<file_sep>/java/springboot/lazy-init.md
for spring mvc conf xml:
```
spring配置默认default-lazy-init为false,当配置为true时sping不会再去加载整个对象实例图,大大减少了初始化的时间,减少了spring的启动速度。
使用 @Scheduler 时, beans 的 default-lazy-init为true , 将导致任务在web 启动后不运行.
解决办法:
1. 声明bean 并设置:lazy-init="false"
2. default-lazy-init 设置为false
1.<beans /> <bean /> immediately
2.<beans /> <bean lazy-init="true" /> lazy
3.<beans /> <bean lazy-init="false"/> immediately
4.<beans default-lazy-init="true"/> <bean /> lazy
5.<beans default-lazy-init="true"/> <bean lazy-init="true" /> lazy
6.<beans default-lazy-init="true"/> <bean lazy-init="false" /> immediately
7.<beans default-lazy-init="false"/> <bean /> immediately
8.<beans default-lazy-init="false"/> <bean lazy-init="true" /> lazy
9.<beans default-lazy-init="false"/> <bean lazy-init="false" /> immediately
beans 嵌套beans : 以外层的lazy-init为准.
```
<file_sep>/java/someutils/XStream.md
XStream is a simple library to serialize objects to XML and back again.(http://x-stream.github.io/index.html)<file_sep>/python/ActivePython.md
```
Python2.7.18 glibc2.12
Supported Versions
Ubuntu
19.04 disco
18.10 cosmic
18.04 LTS bionic
17.10 artful
17.04 zesty
16.10 yakkety
16.04 LTS xenial
15.10 wily
15.04 vivid
14.10 utopic
14.04 LTS trusty
13.10 saucy
13.04 raring
12.10 quantal
12.04 LTS precise
11.10 oneiric
11.04 natty
10.10 maverick
Centos
7
6.9
6.5
Fedorara
whide
30
29
28
27
26
25
24
23
22
21
20 heisenbug
19 schrodingers
18 spherical
17 beefy
16 verne
15 lovelock
14 laughlin
13 goddard
Debian
10.0 - Buster
9.0 - Stretch
8.0 - Jessie
7.0 - Wheezy
RedHat
RHEL-8.0
RHEL-7.5
RHEL-6.9
6.5
openSUSE
tumbleweed
15.1
15
42.3
42.2
42.1
13.2
13.1
12.3
12.2
12.1
```
<file_sep>/linux/coreos/qemu_instal_coreos.md
https://zhuanlan.zhihu.com/p/336277248
```
1. 下载 qemu.x86_64.qcow2.xz 并解压,得到qcow2 文件(qemu虚拟机磁盘文件)
2. 定制: Ignition
2.1 编写配置yaml
2.2 通过fcct 工具将yaml 转成Ignition(json) 命令: fcct -o xxx.ign xxxxx.yaml
3. 使用ignation 和 qcow2 文件创建和启动虚拟机。
```
fcct: 工具下载 https://github.com/coreos/fcct/releases
yaml 配置:
参考: https://docs.fedoraproject.org/en-US/fedora-coreos/producing-ign/ https://docs.fedoraproject.org/en-US/fedora-coreos/fcct-config/
Writing the FCC file
Copy the following example into a text editor:
```yaml
variant: fcos
version: 1.2.0
passwd:
users:
- name: core
ssh_authorized_keys:
- ssh-rsa AAAA...
```
Replace the above line starting with ssh-rsa with the contents of your SSH public key file.
Save the file with the name example.fcc. (fcc 为yaml 格式)
用户密码,支持,ssh 和 hash , passwd_hash
core 用户: 可通过sudo su 切换到root
```yaml
storage:
files:
- path: /etc/hostname
mode: 0644
contents:
inline: coreos
- path: /etc/NetworkManager/system-connections/ens2.nmconnection
mode: 0600
contents:
inline: |
[connection]
id=ens2
type=ethernet
interface-name=ens2
[ipv4]
address1=192.168.10.30/24,192.168.10.1
dns=192.168.2.254;
dns-search=
dhcp-hostname=coreos
may-fail=false
method=manual
```
```
FCC file structure
The FCC file follows YAML syntax and contains the following top-level nodes:
variant: specifies fcos as the operating system
version: specifies the version of fcct
ignition: specifies a remote configuration (for convenience or for platforms that do not allow for the ingestion of large configuration files)
storage: provisions storage and configures the filesystem
systemd: controls systemd units
passwd: configures users
```
install.sh (root)
```sh
IGNITION_CONFIG="ign file path"
IMAGE="qcow2 file path"
VM_NAME="vm_name"
VCPUS="2"
RAM_MB="2048"
DISK_GB="10"
STREAM="stable"
## 网卡配置的hostonly: --network network=hostonly
## 磁盘空间检查不通过(磁盘不足): --check disk_size=off
virt-install --connect="qemu:///system" --name="${VM_NAME}" --vcpus="${VCPUS}" --memory="${RAM_MB}" \
--os-variant="fedora-coreos-$STREAM" --import --graphics=none \
--disk="size=${DISK_GB},backing_store=${IMAGE}" --check disk_size=off\
--network network=hostonly \
--qemu-commandline="-fw_cfg name=opt/com.coreos/config,file=${IGNITION_CONFIG}"
```
启动进入系统后跟目录不可写:切换到root 执行 chattr -i /<file_sep>/linux/common/swapfile.md
```
创建交换文件:
dd if=/dev/zero of=/var/swap bs=1024 count=4096000
格式化交换文件:
mkswap /var/swap
加载交换文件:
swapon /var/swap
查看交换文件:
swapon -s 或 cat /proc/swaps
卸载交换文件:
swapoff /var/swap
```
<file_sep>/linux/desktop-evn/deepin-ui/default_applications.md
默认应用程序: 文件类型+打开方式
~/.config/mimeapps.list
inode/directory : 默认文件管理器
<file_sep>/linux/man_site.md
http://man.linuxde.net/
<file_sep>/linux/softs/vmware/vmware_i_u.md
file:VMware-Workstation-Full-12.0.0-2985596.x86_64.bundle
密钥:<KEY>
uninstall:
```
# vmware-installer -l
# vmware-installer --uninstall-product vmware-workstation
```
vmware fail to run:
Virtual Network Device:
vmnet
cd /usr/lib/vmware/modules/source
tar -xvf vmnet.tar
cd vmnet-only
vim netif.c
update the follow code :
#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 18, 0) || defined(NET_NAME_USER)
dev = alloc_netdev(sizeof *netIf, deviceName, NET_NAME_USER, VNetNetIfSetup);
#else
dev = alloc_netdev(sizeof *netIf, deviceName, VNetNetIfSetup);
#endif
=====>>>>>
//#if LINUX_VERSION_CODE >= KERNEL_VERSION(3, 18, 0) || defined(NET_NAME_USER)
// dev = alloc_netdev(sizeof *netIf, deviceName, NET_NAME_USER, VNetNetIfSetup);
//#else
dev = alloc_netdev(sizeof *netIf, deviceName, VNetNetIfSetup);
//#endif
tar -uvf vmnet.tar vmnet-only
run vmware again: net be ok
```
Failed to build vmnet. Failed to execute the build command.
https://github.com/mkubecek/vmware-host-modules/releases
解压:
创建压缩包:
# tar -cf vmmon.tar vmmon-only
# tar -cf vmnet.tar vmnet-only
先备份 /usr/lib/vmware/modules/source/
# sudo cp *.tar /usr/lib/vmware/modules/source/
$ sudo vmware-modconfig --console --install-all
```
<file_sep>/js/react/npm_cnpm.md
```
http://npm.taobao.org/
npm install -g cnpm --registry=https://registry.npm.taobao.org
npm help
npm list
npm install <name> [-g] [--save-dev]
-g:全局安装。
--save:将保存配置信息至package.json(package.json是nodejs项目配置文件);
-dev:保存至package.json的devDependencies节点,不指定-dev将保存至dependencies节点;
(cnpm -save 不可用,尽量使用--save)
npm install moduleName # 安装模块到项目目录下
npm install -g moduleName # -g 的意思是将模块安装到全局,具体安装到磁盘哪个位置,要看 npm config prefix 的位置。(部分系统需要使用sudo)
npm install -save moduleName # -save 的意思是将模块安装到项目目录下,并在package文件的dependencies节点写入依赖。
npm install -save-dev moduleName # -save-dev 的意思是将模块安装到项目目录下,并在package文件的devDependencies节点写入依赖。
npm uninstall <name> [-g] [--save-dev]
```
some module
```
sudo cnpm install -g create-react-app
create-react-app appname(只能小写)[创建工程]
moment
andt
```
<file_sep>/java/note_spring/spring-springmvc.md
参考: https://blog.csdn.net/yaoct/article/details/80837096
Tomcat容器初始化顺序:监听器–>过滤器–>servlet
(1)spring是一个大的父容器,springmvc是其中的一个子容器。父容器不能访问子容器对象,但是子容器可以访问父容器对象。
(2)一般做一个ssm框架项目的时候,扫描@controller注解类的对象是在springmvc容器中。而扫描@service、@component、@Repository等注解类的对象都是在spring容器中。
ContextLoader.initWebApplicationContext( ): 容器 在ServletContext对象存了一份,又在ContextLoader中存了一份。
Servlet DispatcherServlet中没找到创建子容器的方法,查他的父类FrameworkServlet中找到 initWebApplicationContext() 方法创建子容器。容易发现代码中也把子容器在ServletContext中存了一份
ServletContext的属性map中可找到这两个容器。
<file_sep>/sql/postgresql/solutions/time_zone.md
问题:
系统时间与数据库时间不一致
```
查系统时间
#date
pg上查询:
select now();
show time zone;
```
解决办法:
```
查看支持的时区:
select * from pg_timezone_names ;
查询东8区:
select * from pg_timezone_names where utc_offset='08:00:00';
---------------------------------------------
临时:
set time zone 'PRC';重新查询及时生效
---------------------------------------------
永久:
postgresql.conf配置里修改两项
log_timezone = 'PRC'
timezone = 'PRC'
PRC 可是用 Asia/Shanghai 替换
修改好重启pg或者reload重新查询登录生效
```
<file_sep>/linux/softs/openmpi.md
下载源码:
<https://www.open-mpi.org/software/ompi/v4.0/>
依赖:
```
yum install gcc cpp
yum install -y zlib zlib-devel jasper jasper-devel libpng libpng-devel libjpeg libjpeg-devel
yum install -y glibc-headers gcc-c++
```
解压后进入解压目录:
<file_sep>/linux/someservices/dhcpd.md
dhcp 介绍:
```
(DynamicHost Configuration Protocol) 动态主机配置协议,是一个局域网的网络协议,使用UDP协议工作。
DHCP有3个端口:
DHCPServer : 67
DHCP Client : 68
546号端口用于DHCPv6 Client
也就是自动的将网路参数正确的分配给网域中的每部电脑,让用户端的电脑可以在开机的时候就立即自动的设定好网路的参数值,这些参数值可以包括了 IP、netmask、network、gateway与 DNS 的位址等等。
网络安装操作系统:指定引导程序
```
工作原理:
```
1、寻找server ,client端向局域网发送出一个discover封包;
2、提供IP租用位址,server端收到discover封包后,选择出最前面空置IP,回应给客户端一个offer封包
3、client端收到多台server端offer封包后,挑选最先到达的哪一个offer1,并向局域网发送一个request封包,告之所有server它将指定那一台的IP地址;
4、当server收到request请求封包后,会给客户端一个ACK回应,确认ip租约生效
```
安装:
```
yum search dhcp
yum install dhcp.x86_64 -y
```
配置
```
#
# DHCP Server Configuration file.
# see /usr/share/doc/dhcp*/dhcpd.conf.example
# see dhcpd.conf(5) man page
# “单行配置以 ; 结尾”
option domain-name "server.com";
option domain-name-servers 192.168.3.219;
default-lease-time 600;
max-lease-time 7200;
log-facility local7;
# subnet: ##指定子网络及子网掩码
# range: ## 指定IP范围
# option routers : ## 指定默认网关
subnet 192.168.3.0 netmask 255.255.255.0 {
range 192.168.3.100 192.168.3.102;
option routers 192.168.3.1;
}
```
服务启/停
```
service dhcpd restart/start/stop
or
systemctl stop/start/restart dhcpd
```
<file_sep>/linux/systemctl/services_manage.md
服务启停:
systemctl status service_name
systemctl start service_name
systemctl stop service_name
systemctl restart service_name
开机运行/不运行
systemctl enable service_name
systemctl disable service_name
update-rc.d service_name disable
列举服务:
systemctl list -units --type=service
运行级别
参考:https://blog.csdn.net/u012486840/article/details/53161574
``` stylus
init级别 systemctl target
0 shutdown.target
1 emergency.target
2 rescure.target
3 multi-user.target
4 无
5 graphical.target
6 无
systemctl命令 说明
systemctl get-default 获得当前的运行级别
systemctl set-default multi-user.target 设置默认的运行级别为mulit-user
systemctl isolate multi-user.target 在不重启的情况下,切换到运行级别mulit-user下
systemctl isolate graphical.target 在不重启的情况下,切换到图形界面下
```
<file_sep>/linux/softs/nemo.md
nemo: file manager:
extension:
git-nemo-icons
<http://einverne.github.io/post/2018/08/nemo-file-manager.html>
鼠标邮件打开terminal 无响应:
```
$ gsettings set org.cinnamon.desktop.default-applications.terminal exec <terminal_cmd>
```
右键解压:
```
安装 nemo-fileroller
kill nemo 进程重新打开文件管理器
```
<file_sep>/java/note_spring/i18n.md
参考:https://www.cnblogs.com/liukemng/p/3750117.html
```xml
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<!-- 国际化信息所在的文件名 -->
<property name="basename" value="messages" />
<!-- 如果在国际化资源文件中找不到对应代码的信息,就用这个代码作为名称 -->
<property name="useCodeAsDefaultMessage" value="true" />
</bean>
在项目中的源文件夹resources中添加messages.properties、messages_zh_CN.properties、messages_en_US.properties三个文件
或
自定义i18n 路径,可与js 需要的i18n 使用同一份。
<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
<property name="basenames">
<list>
<value>i18n_path/A/message</value>
<value>i18n_path/B/message</value>
</list>
</property>
<property name="defaultEncoding" value="UTF-8"/>
</bean>
```
```xml
<mvc:interceptors>
<!-- 国际化操作拦截器 如果采用基于(请求/Session/Cookie)则必需配置 -->
<bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
</mvc:interceptors>
<!--下面二选一-->
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.SessionLocaleResolver" />
<bean id="localeResolver" class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
```
```java
// 自定义local解析
import java.util.Locale;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.LocaleResolver;
public class MyAcceptHeaderLocaleResolver extends AcceptHeaderLocaleResolver {
private Locale myLocal;
public Locale resolveLocale(HttpServletRequest request) {
return myLocal;
}
public void setLocale(HttpServletRequest request, HttpServletResponse response, Locale locale) {
myLocal = locale;
}
}
```
```xml
<bean id="localeResolver" class="xx.xxx.xxx.MyAcceptHeaderLocaleResolver"/>
```
```
URL后附上 locale=zh_CN 或 locale=en_US 如 http://xxxxxxxx?locale=zh_CN 来改变语言了
```
<file_sep>/editor/vscode/vscodium.md
```
vscodium 使用单独的应用仓库,有些扩展找不到(比如sftp)
修改 resources/app/product.json 使用vscode 扩展仓库
修改: extensionsGallery 属性
修改前:
"extensionsGallery": {
"serviceUrl": "https://open-vsx.org/vscode/gallery",
"itemUrl": "https://open-vsx.org/vscode/item"
},
修改后:
"extensionsGallery": {
"serviceUrl": "https://marketplace.visualstudio.com/_apis/public/gallery",
"cacheUrl": "https://vscode.blob.core.windows.net/gallery/index",
"itemUrl": "https://marketplace.visualstudio.com/items",
"controlUrl": "https://az764295.vo.msecnd.net/extensions/marketplace.json",
"recommendationsUrl": "https://az764295.vo.msecnd.net/extensions/workspaceRecommendations.json.gz"
},
重启vscodium可使用vscode 扩展仓库
```
<file_sep>/python/base/property.md
参考:<https://www.liaoxuefeng.com/wiki/1016959663602400/1017502538658208>
```
property
class property([fget[, fset[, fdel[, doc]]]])
参数
fget -- 获取属性值的函数
fset -- 设置属性值的函数
fdel -- 删除属性值函数
doc -- 属性描述信息
变量=property([fget[, fset[, fdel[, doc]]]])
class().变量 调用fget 读取值
class().变量=xxx 调用 fset 设置值
@property 修饰函数,函数名为变量,该函数功能与 fget 一致 (函数只有一个参数self)
@变量.setter 修饰函数,该函数功能与 fset 一致,函数第二个参数为赋值参数(第一个参数为self)
@变量.deleter 修饰函数,该函数功能与 fdel 一致(函数只有一个参数self)
```
<file_sep>/linux/solutions/miss-firmware.md
```
Possibly missing firmware for module: aic94xx
Possibly missing firmware for module: wd719x
Possibly missing firmware for module: xhci_pci
```
```
wd719x是“Western Digital WD7193,WD7197和WD7296 SCSI卡”的驱动程序
aic94xx是“Adaptec SAS 44300,48300,58300 Sequencer”的驱动程序。
xhci_pci
可选安装
```
```
git clone https://aur.archlinux.org/aic94xx-firmware.git
cd aic94xx-firmware
makepkg -sri
git clone https://aur.archlinux.org/wd719x-firmware.git
cd wd719x-firmware
makepkg -sri
或 yoaurt -S aic94xx-firmware wd719x-firmware
yay -S aic94xx-firmware wd719x-firmware
yay -S upd72020x-fw
# mkinitcpio -p linux (-p linux 根据实际情况修改)
```
<file_sep>/python/petl/database.md
data from database
>>> import petl as etl
>>> import sqlite3
>>> connection = sqlite3.connect('example.db')
>>> table = etl.fromdb(connection, 'SELECT * FROM example')
data to database
>>> import petl as etl
>>> table = [['foo', 'bar'],
... ['a', 1],
... ['b', 2],
... ['c', 2]]
>>> # using sqlite3
... import sqlite3
>>> connection = sqlite3.connect('example.db')
>>> # assuming table "foobar" already exists in the database
... etl.todb(table, connection, 'foobar')<file_sep>/linux/softs/conky.md
```bash
# pacman -S conky
# pacman -S conky-manager
conky -c <configfile>
```
conky 配置
```bash
#${image /home/ninja/Pictures/Wallpapers/icons/hacked90.png -p 70,5}
background yes
use_xft yes
xftfont Monospace:size=8
xftalpha 1.0
update_interval 3.0
update_interval_on_battery 12.0
total_run_times 0
own_window yes
own_window_type normal
own_window_transparent no
own_window_class conky-semi
own_window_hints undecorated,below,sticky,skip_taskbar,skip_pager
own_window_argb_visual yes
own_window_argb_value 0
double_buffer yes
format_human_readable yes
short_units yes
minimum_size 240 5
maximum_width 3500
default_bar_size 0 9
draw_shades no
draw_outline no
draw_borders no
draw_graph_borders yes
default_color green
default_shade_color FF0000
default_shade_color1 181717
default_outline_color 0000ff
alignment top_right
gap_x 58
gap_y 20
no_buffers yes
uppercase no
cpu_avg_samples 2
pad_percents 0
override_utf8_locale no
color1 EF5A29
color2 DF6C0A
color3 EF5A2F
color4 EF5A29
own_window_colour 000000
TEXT
${font Monospace Regular:size=9}${color green}Base ${color1} ${hr 2}
${color3}$font$sysname $kernel $alignr $machine
Uptime $alignr${uptime}
File System $alignr${fs_type}
${font Monospace Regular:size=9}${color green}NETWORK ${color1}${hr 2}
${color3}
Internal IP:${alignr}${addr enp0s25 }
Download:${alignr}${downspeed enp0s25 }
${downspeedgraph enp0s25 FFEF00 }
${upspeedgraph enp0s25 FFEF00 }
Upload:${alignr}${upspeed enp0s25 }
${font Monospace Regular:size=9}${color green}CPU ${color1}${hr 2}
${color3}
CPU TOTAL USAGE:$alignr${cpu cpu0}%
${cpubar cpu0}
CPU1: $alignr${cpu cpu1}%
${cpubar cpu1}
CPU2: $alignr${cpu cpu2}%
${cpubar cpu2}
CPU3: $alignr${cpu cpu3}%
${cpubar cpu3}
CPU4:$alignr${cpu cpu4}%
${cpubar cpu4}
${font Monospace Regular:size=9}${color green}RAM ${color1}${hr 2}
${color3}
RAM: ${alignc}$mem / $memmax $alignr ${memperc}%
$membar
SWAP $alignc ${swap} / ${swapmax} $alignr ${swapperc}%
${swapbar}
${font Monospace Regular:size=9}${color green}DISK ${color1}${hr 2}
${color3}
/: ${alignr}${fs_used /} / ${fs_size /}
${fs_bar /}
/home: ${alignr}${fs_used /home} / ${fs_size /home}
${fs_bar /home}
/data: ${alignr}${fs_used /data} / ${fs_size /data}
${fs_bar /data}
/disk/1: ${alignr}${fs_used /disk/1} / ${fs_size /disk/1}
${fs_bar /disk/1}
/disk/2: ${alignr}${fs_used /disk/2} / ${fs_size /disk/2}
${fs_bar /disk/2}
${font Monospace Regular:size=9}${color green}PROCESSORS CPU ${color1}${hr 2}
${color3}
${top name 1} $alignr ${top pid 1} ${top cpu 1}%
${top name 2} $alignr ${top pid 2} ${top cpu 2}%
${top name 3} $alignr ${top pid 3} ${top cpu 3}%
${top name 4} $alignr ${top pid 4} ${top cpu 4}%
${top name 5} $alignr ${top pid 5} ${top cpu 5}%
${hr 2}
${font Monospace Regular:size=9}${color green}PROCESSORS RAM ${color1}${hr 2}
${color3}
${top_mem name 1} $alignr ${top pid 1} ${top_mem mem_res 1}
${top_mem name 2} $alignr ${top pid 2} ${top_mem mem_res 2}
${top_mem name 3} $alignr ${top pid 3} ${top_mem mem_res 3}
${top_mem name 4} $alignr ${top pid 4} ${top_mem mem_res 4}
${top_mem name 5} $alignr ${top pid 5} ${top_mem mem_res 5}
${hr 2}
```
```
# cpu 额定频率
${freq_g cpu0}
${freq_g cpu2}
......
# 系统名
$sysname
# 内核版本
$kernel
# arch
$machine
# 开机时长
${uptime}
# ip
${addr <网卡名> }
# 下载速度
${downspeed <网卡名> }
# 上次速度
${upspeed <网卡名> }
# 网速图
${downspeedgraph <网卡名> FFEF00 }
${upspeedgraph <网卡名> FFEF00 }
# 单 cpu 利用率,编号0: 整体值,单个cpu编号从1 开始
${cpu cpu0}%
${cpu cpu1}%
....
${cpubar cpu0}
${cpubar cpu1}
.....
# 当前cpu 频率 ,编号从1 开始
${freq_g (1)}GHz
${freq_g (2)}GHz
....
# cpu 图:编号0: 整体值,单个cpu编号从1 开始
${cpugraph cpu0 100,300}
#已使用内存
${mem}
# 总内存
$memmax
# 内存利用率
${memperc}%
$memmax
# 内存使用bar
${membar 5,}
# top cpu
${top name 1} $alignr ${top pid 1} ${top cpu 1}%
# top ram
${top_mem name 1} $alignr ${top pid 1} ${top_mem mem_res 1}
```
<file_sep>/js/jquery/selector.md
## - 通配符:
$("input[id^='code']");//id属性以code开始的所有input标签
$("input[id$='code']");//id属性以code结束的所有input标签
$("input[id*='code']");//id属性包含code的所有input标签
$("input[name^='code']");//name属性以code开始的所有input标签
$("input[name$='code']");//name属性以code结束的所有input标签
$("input[name*='code']");//name属性包含code的所有input标签
## -
$("tbody tr:even"); //选择索引为偶数的所有tr标签
$("tbody tr:odd"); //选择索引为奇数的所有tr标签
$(".main > a"); class为main的标签的子节点下所有标签
jqueryObj.next("div");//获取jqueryObj标签的后面紧邻的一个div,nextAll获取所有
//not
$("#code input:not([id^='code'])");//id为code标签内不包含id以code开始的所有input标签
<file_sep>/linux/common/ssh.md
# 软件安装
| 系统 | 软件包 | 备注 |
| ------ | ------- | ---- |
| arch | openssh | |
| centos | | |
| ubuntu | | |
# 使用与配置
配置文件:
```
/etc/ssh/ssh_config 客户端配置文件
/etc/ssh/sshd_config 服务端配置文件
~/.ssh/config 客户端用户级别的配置文件
```
服务端服务:
```
服务名为: sshd
systemctl status/start/stop/restart sshd
service sshd status/start/stop/restart
```
客户端:
```
连接命令: ssh
-X 开启图形,允许服务端的图形应用程序投影图像到本地。
ssh 参数不支持直接带密码。 可使用 sshpass
```
# 补充
```
SSH免密码登陆避免首次需要输入yes
ssh -o stricthostkeychecking=no
/etc/ssh/ssh_config文件中的"# StrictHostKeyChecking ask" 为 "StrictHostKeyChecking no",
sed -i 's/# StrictHostKeyChecking ask/StrictHostKeyChecking no/' /etc/ssh/ssh_config
警告:POSSIBLE BREAK-IN ATTEMPT
sed -i 's/GSSAPIAuthentication yes/GSSAPIAuthentication no/' /etc/ssh/ssh_config
```
```
ssh 共享回话
配置 ~/.ssh/config
Host *
ControlMaster auto
ControlPath ~/.ssh/master-%r@%h:%p
```
<file_sep>/linux/iptables.md
参考:
<http://www.zsythink.net/archives/1199/>
<https://blog.51cto.com/13677371/2094355>
```
iptables 管理内核的netfilter
```
防火墙服务
```bash
systemctl status iptables.service
```
```
链:
PREROUTING
INPUT
POSTROUTING
OUTPUT
FORWARD
```


表:
```
filter表 (实现包过滤)
nat表 (实现网络地址转换)
mangle表 (实现包修改)
raw表 (实现数据跟踪)
这些表具有一定的优先级:**raw-->mangle-->nat-->filter
```
链表:
```
查看
iptables -L
清除
iptables -F
iptables -X
```
```
动作选项
ACCEPT 接收数据包
DROP 丢弃数据包
REDIRECT 将数据包重新转向到本机或另一台主机的某一个端口,通常功能实现透明代理或对外开放内网的某些服务
SNAT 源地址转换
DNAT 目的地址转换
MASQUERADE IP伪装
LOG 日志功能
-A 增加 -I 插入 -D 删除 -R 替换
iptables [-t 表名] <-A|I|D|R> 链名 [规则编号] [-i|o 网卡名称] [-p 协议类型] [-s 源ip|源子网] [--sport 源端口号] [-d 目的IP|目标子网] [--dport 目标端口号] [-j 动作]
```
```bash
禁ping
iptables -A INPUT -p icmp --icmp-type 8 -i <网卡名> -s 0.0.0.0/0 -j DROP
或
iptables -A INPUT -p icmp --icmp-type 8 -j DROP
```
```
允许合法网段ip接入
iptables -A INPUT -s <10.0.0.0/24> -p all -j ACCEPT
```
nat 分snat 和dnat :
参考:
<http://www.zsythink.net/archives/1764>
<https://blog.51cto.com/13162375/2103512>
```
虚拟机使用 hostonly 网络环境:
宿主机:
snat: (实现虚拟机上外网)
# iptables -N fw-open
# iptables -A FORWARD -j fw-open
# iptables -t nat -A POSTROUTING -o <宿主机上网卡> -s 192.168.4.0/24 -j MASQUERADE
(iptables -t nat -A POSTROUTING -o <宿主机上网卡> -s (虚拟机网段) -j MASQUERADE)
dnat: (参考 https://www.cnblogs.com/jjzd/p/6505871.html)
(
实现虚拟机中的端口能被宿主机所在局域网的其他网络设备访问。
注:宿主机不能通过<宿主机ip>:<宿主机端口> 访问虚拟机端口
)
# iptables -t nat -A PREROUTING -d <宿主机ip> -p tcp -m tcp --dport <宿主机端口> -j DNAT --to-destination 192.168.4.11:22
(iptables -t nat -A PREROUTING -d <宿主机ip> -p tcp -m tcp --dport <宿主机端口> -j DNAT --to-destination <虚拟机ip>:<虚拟机端口>)
```
```
# iptables -t nat -A POSTROUTING -o <宿主机上网卡> -s (虚拟机网段) -j MASQUERADE 不生效尝试使用如下方式
iptables -F
iptables -t nat -F
iptables -X
iptables -t nat -X
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -t nat -A POSTROUTING -o <宿主机上网卡> -j MASQUERADE
```
```
端口转发:
同端口转发( :3389 192.168.4.13:3389 )
iptables -t nat -I PREROUTING -p tcp --dport 3389 -j DNAT --to 192.168.4.13
iptables -t nat -I POSTROUTING -p tcp --dport 3389 -j MASQUERADE
不同端口转发(192.168.2.231:3388 192.168.4.13:3389 )
iptables -t nat -A PREROUTING -p tcp -m tcp --dport 3388 -j DNAT --to-destination 192.168.4.13:3389
iptables -t nat -A POSTROUTING -s 192.168.4.0/24 -d 192.168.4.13 -p tcp -m tcp --dport 3389 -j SNAT --to-source 192.168.2.231
```
<file_sep>/linux/sysresource/status.md
```
/proc/cpuinfo (cpu 静态信息)
/proc/stat (cpu 使用情况)
/proc/version (系统内核版本)
/proc/meminfo (内存使用情况)
/proc/uptime (系统负载相关)
/proc/loadavg (load average)
/proc/net/nfsfs/servers (挂载的nfs 服务器列表)
/proc/net/rpc/nfs
/proc/net/rpc/nfsd
/proc/diskstats (磁盘读写)
/proc/partitions (磁盘分区)
/proc/net/dev (网卡流量统计)
/proc/<pid>/stat (进程信息)
/proc/<pid>/statm (进程信息)
/proc/<pid>/io (进程信息)
lsblk: (获取磁盘分区情况)
lsscsi:磁盘信息
lstopo
lspci
lsusbexit
ifstat -j
```
```
/proc/uptime
第一列输出的是,系统启动到现在的时间(以秒为单位),这里简记为num1;
第二列输出的是,系统空闲的时间(以秒为单位),这里简记为num2。
N: 几个逻辑的CPU(包括超线程)
系统的空闲率(%) = num2/(num1*N) 其中N是SMP系统中的CPU个数。
开机时间
date -d "$(awk -F. '{print $1}' /proc/uptime) second ago" +"%Y-%m-%d %H:%M:%S"
运行时间
cat /proc/uptime| awk -F. '{run_days=$1 / 86400;run_hour=($1 % 86400)/3600;run_minute=($1 % 3600)/60;run_second=$1 % 60;printf("系统已运行:%d天%d时%d分%d秒",run_days,run_hour,run_minute,run_second)}'
系统已运行:0天4时27分10秒
```
```
/proc/loadavg
前三个数字大家都知道,是1、5、15分钟内的平均进程数(有人认为是系统负荷的百分比,其实不然,有些时候可以看到200甚至更多)。后面两个呢,一个的分子是正在运行的进程数,分母是进程总数;另一个是最近运行的进程ID号。
```
```
/sys/devices/system/cpu/cpu0/cpufreq/
/sys/class/hwmon
/sys/devices/system/
```
环境变量:XDG_CURRENT_DESKTOP 用户DE
```
gsettings get org.cinnamon.theme name 桌面窗口主题
gsettings get org.cinnamon.desktop.interface gtk-theme
gsettings get org.cinnamon.desktop.interface icon-theme
gsettings get org.cinnamon.desktop.interface font-name
```
disk temp
```
hddtemp
```
<file_sep>/linux/softs/nginx/fileserver.md
参考
<https://blog.csdn.net/wzw_ice/article/details/89414024>
<https://blog.csdn.net/wzw_ice/article/details/89414188>
```
autoindex on;#自动索引
autoindex_localtime on;#自动索引时间
autoindex_exact_size off;#自动索引
```
```
user root root;
worker_processes auto;
#error_log logs/error.log;
error_log logs/error.log warn;
error_log logs/info.log info;
pid logs/nginx.pid;
events {
worker_connections 1024;
}
http {
include mime.types;
default_type application/octet-stream;
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';#日志格式
access_log logs/access.log main;
sendfile on;#文件发送设置
keepalive_timeout 65;#超时设置
#gzip on;
server {
listen 8080; #端口修改
server_name localhost;
charset utf-8;
#access_log logs/host.access.log main;
location / {
#root html;
#index index.html index.htm;
autoindex on;#自动索引
autoindex_localtime on;#自动索引时间
autoindex_exact_size off;#自动索引
#如果设置下面,访问是会直接下载文件
#idefault_type 'application/octet-stream';
#add_header Content-disposition "attachment";
root /data/file/; #文件根目录设置
}
#error_page 404 /404.html;
# redirect server error pages to the static page /50x.html
#
error_page 500 502 503 504 /50x.html;
location = /50x.html {
root html;
}
}
}
```
<file_sep>/linux/softs/kvm/0_install.md
参考:<https://blog.csdn.net/sanxinge/article/details/52347998>
```
sudo pacman -S qemu libvirt virt-manager
sudo pacman -S bridge-utils
# systemctl start libvirtd #启动libvirtd进程
# systemctl enable libvirtd #开机自起
添加用户到kvm用户组
usermod -a -G kvm <user_name>
```
<file_sep>/js/jqlib.md
```
loading plugins:
https://github.com/piccard21/busy-load
```
<file_sep>/editor/vscode/extentions.md
```
快捷键绑定:
IntelliJ IDEA Keybindings
```
```
Live Server
```
<file_sep>/sql/other/es/index.md
Start:
ElasticSearch是一个基于Lucene的搜索服务器。它提供了一个分布式多用户能力的全文搜索引擎,基于RESTful web接口。Elasticsearch是用Java开发的,并作为Apache许可条款下的开放源码发布,是当前流行的企业级搜索引擎。
download:
https://www.elastic.co/downloads/elasticsearch
Install:
https://www.yiibai.com/elasticsearch/elasticsearch_installation.html<file_sep>/linux/common/二进制文件依赖.md
ldd
```
ldd : 列出一个可执行文件在运行时需要的共享库信息
ar : 创建静态库,插入,删除,列出和提取成员
strings : 列出文件中的所有可打印字符串
strip : 从目标文件中删除符号表信息
nm : 列出目标文件中符号表中定义的符号
size : 列出目标文件中节的名字和大小
readelf : 显示一个木边文件完整结构,包括elf头中的编码的所有信息,包含size和nm的功能
objdump : 所有二进制工具之母。能够显示一个目标文件中的所有信息,它最有用的功能是反汇编.text节中的二进制指令
```
<file_sep>/linux/ubuntu/内核清理.md
uname -a : 查看当前版本
在Ubuntu内核镜像包含了以下的包。
linux-image-: 内核镜像
linux-image-extra-: 额外的内核模块
linux-headers-: 内核头文件
dpkg --list|grep linux-image
dpkg --list|grep linux-headers
dpkg --list|grep linux
清除
apt-get purge XXX
<file_sep>/linux/desktop-evn/kde/restart_kde_desktop.md
```
killall plasmashell && kstart5 plasmashell
```
<file_sep>/linux/bigdata/hue.md
参考: https://blog.csdn.net/C_FuL/article/details/77914316
```
yum install -y gcc libxml2-devel libxslt-devel cyrus-sasl-devel mysql-devel python-devel python-setuptools python-simplejson sqlite-devel ant gmp-devel cyrus-sasl-plain cyrus-sasl-devel cyrus-sasl-gssapi libffi-devel openldap-devel
tar xzvf hue-*.tgz
PREFIX=/usr/share make install
```
<file_sep>/linux/desktop-evn/mint/美化/界面/conf.md
## Files
1. /usr/share/themes
Adwaita Bright Default HighContrast Metabox Mint-X-Blue Mint-X-Grey Mint-X-Purple Mint-X-Teal Mint-Y-Darker OSX-Arc-White Simple
AgingGorilla Candy Emacs Libra Mint-X Mint-X-Brown Mint-X-Orange Mint-X-Red Mint-Y Mist oxygen-gtk Xenlism-Minimalism
Atlanta Crux Esco Linux Mint Mint-X-Aqua Mint-X-compact Mint-X-Pink Mint-X-Sand Mint-Y-Dark OSX-Arc-Darker Raleigh
2. /usr/share/icons:
Adwaita cab_view.png DMZ-White Humanity mate Mint-X Mint-X-Dark Mint-X-Purple Mint-X-Yellow Numix-Circle-Light redglass xpra.png
breeze default gnome Humanity-Dark Mine Mint-X-Aqua Mint-X-Grey Mint-X-Red Mint-Y Numix-Light ubuntu-mono-dark
breeze-dark default.kde4 hicolor locolor Mine-Mavericks Mint-X-Blue Mint-X-Orange Mint-X-Sand Numix oxygen ubuntu-mono-light
cab_extract.png DMZ-Black HighContrast love-wallpaper.png Mine-Yosemite Mint-X-Brown Mint-X-Pink Mint-X-Teal Numix-Circle pearlinux whiteglass
# Install theme : Numix
sudo add-apt-repository ppa:numix/ppa
sudo apt-get update
sudo apt-get install numix-gtk-theme numix-icon-theme-circle
楷体字:
system->fout
软件管理->字体:搜索 ukai 安装: 设置字体
Fonts-arphic-ukai<file_sep>/java/wsdl/start.md
wsimport: jdk 自带的工具
wsimport -keep url(url为wsdl文件的路径,本地路径或网络路径 )生成客户端代码
[http://www.webxml.com.cn](http://www.webxml.com.cn/)
天气接口调用:<https://blog.csdn.net/w410589502/article/details/51802483>
首先我们将网页打开的wsdl文件保存到本地
修改wsdl文档的部分内容:将 **<s:element ref="s:schema" /><s:any />** 替换成 **<s:any minOccurs="2" maxOccurs="2"/>**
执行wsimport生成代码
将源码加到工程
编写测试请求代码:
```java
package cn.com.webxml;
import java.util.List;
import cn.com.webxml.GetSupportDataSetResponse.GetSupportDataSetResult;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
WeatherWebService impl = new WeatherWebService();
System.out.println(impl.getServiceName());
WeatherWebServiceSoap w =impl.getWeatherWebServiceSoap();
// //调用WeatherWebServiceSoap提供的getWeather方法获取天气预报情况
// ArrayOfString response = w.getSupportProvince(); // 省份列表
// ArrayOfString response = w.getSupportCity("四川"); // 省内各市的数据
// ArrayOfString response = w.getSupportCity("成都"); // 查不到数据
ArrayOfString response = w.getWeatherbyCityName("成都");
List<String> responseList = response.getString();
//遍历天气预报信息
System.out.println("------------------------");
for (String string : responseList) {
System.out.println(string);
}
System.out.println("------------------------");
GetSupportDataSetResult response2 = w.getSupportDataSet();
List<Object> list = response2.getAny();
System.out.println("------------------------");
for (Object string : list) {
System.out.println(string);
}
System.out.println("------------------------");
}
}
```
<file_sep>/linux/desktop-evn/other_app/wellpaper_engine.md
```
komorebi
variety : 切换壁纸
```
<file_sep>/linux/softs/ssh/scp_tar.md
把home文件打包并解压到/datavg35下
```
tar -cvf- home |(cd /datavg35; tar -xvf -)
```
把A机的t11.txt 打包并传送到B机上
```
tar cvfz - t11.txt|ssh erpprd "cat >t11.tar.gz"
```
把A机的t11.txt 打包并传送到B机上的/tmp目录下
```
tar cvfz - t11.txt |ssh erpprd "cd /tmp;cat >t11.tar.gz"
```
将A机的t11.txt压缩文件,复制到B机并解压缩
```
zcat dir.tar | ssh 192.168.0.116 "cd /opt; tar -xf -"
```
在A机上一边打包t11.txt文件,一边传输到B机并解压
```
tar cvfz - t11.txt |ssh erpprd "cd /tmp; tar -xvfz -"
传输到远程:tar czf - file| ssh server "tar zxf -"
压缩到远程:tar czf - file| ssh server "cat > file.tar.gz"
解压到远程:ssh server "tar zxf -" < file.tar.gz
解压到本地:ssh server "cat file.tar.gz" | tar zxf -
```
<file_sep>/python/base/v.md
__name__
```
1、__name__这个系统变量显示了当前模块执行过程中的名称,如果当前程序运行在这个模块中,__name__ 的名称就是__main__如果不是,则为这个模块的名称。
2、__main__一般作为函数的入口,类似于C语言,尤其在大型工程中,常常有if __name__ == "__main__":来表明整个工程开始运行的入口。
```
### class:
```
参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017590712115904
__slots__: 限制实例的属性 __slots__=("xx","xxxx") 设置实例可用的属性
使用的属性在元组范围外,将报错
__str__()返回用户看到的字符串,
__repr__()返回程序开发者看到的字符串
def __iter__(self) 该方法返回一个迭代对象
def __next__(self) 拿到循环的下一个值,直到遇到StopIteration错误时退出循环
def __getitem__(self, n) 像list那样按照下标取出元素
def __getattr__(self, attr),动态返回一个属性值
def __call__(self):实例本身上调用 : 实例() ,callable()函数,我们就可以判断一个对象是否是“可调用”对象
Enum可以把一组相关常量定义在一个class中,且class不可变,而且成员可以直接比较
```
#### 元类
```
参考:https://www.liaoxuefeng.com/wiki/1016959663602400/1017592449371072
type():
1. 检测类型
2. 动态创建类
def fn(self, name='world'): # 先定义函数
.....
类名= type('类名', (object,), dict(hello=fn)) # 创建类
type(类名,继承列表元组,函数列表字典),返回类
metaclass:
# metaclass是类的模板,所以必须从`type`类型派生
# 定义mateclass 类,并编写__new__()方法
def __new__(cls, name, bases, attrs):
# do something
return type.__new__(cls, name, bases, attrs)
接收到的参数依次是:
当前准备创建的类的对象;
类的名字;
类继承的父类集合;
类的方法集合。
类指定metaclass 参数
```
<file_sep>/sql/postgresql/拼接多行.md
```
9.0版本后的postgres数据库,支持函数 array_agg,array_to_string,string_agg
select class_type,
string_agg(name,'-') as names
from user_account
group by class_type
或者
select class_type,
array_to_string(array_agg(name),'-') as names
from user_account
group by class_type
————————————————
引用: 原文链接:https://blog.csdn.net/java_collect/article/details/82596210
```
```
array_agg(列名) : 结果{v1,v2,v3.....}
array_to_string(列名,拼接间隔字符) : 结果为拼接后的字符串
string_agg(列名,拼接间隔字符): 结果为拼接后的字符串
,array_agg( DISTINCT cl_name ) AS xxxxx
,array_to_string(array_agg( DISTINCT cl_name ) ,',') AS xxxx
,string_agg(DISTINCT cl_name ,',') as xxxxx
```
<file_sep>/linux/common/pam.md
模块介绍:
```
auth模块 实现用户认证。比如提示用户输入密码,或判断用户是否为root等。
account模块 对用户的各项属性进行检查。比如是否允许登录,是否达到最大用户数,或是root用户是否允许在这个终端登录等。
session模块 实现用户登录前的,及用户退出后所要进行的操作。比如登录连接信息,用户数据的打开与关闭,挂载文件系统等。
password模块 实现用户信息修改。比如修改用户密码。
```
控制用来标记处理和判断各个模块的返回值。控制分为六种:
```
required 表示即使某个模块对用户的验证失败,也要等所有的模块都执行完毕后,PAM 才返回错误信息。
requisite 和required相似,但是如果这个模块返回失败,则立刻向应用程序返回失败,表示此类型失败.不再进行同类型后面的操作.
sufficient 表示如果一个用户通过这个模块的验证,PAM结构就立刻返回验证成功信息,把控制权交回应用程序。其后相关模块的所有控制都将会比忽略。这就是开头为啥最后一个passwd 的required不会执行而导致报错的原因。
optional 只有当它是与此服务+类型相关联的配置项是中的唯一模块时,模块返回才有意义。
include 引入改项指定文件中的所有配置项。
substack 和include类似。不同之处在于,对子堆中的完成和失败的行为的评估不会导致跳过整个模块堆栈的其余部分,而只会跳过子模块。
```
<file_sep>/sql/postgresql/查询去重.md
```
distict on
查询数据时,需要根据某个字段取唯一然后取数据。
\d products
Table "public.products"
Column | Type | Collation | Nullable | Default
--------------+------------------------+-----------+----------+----------------------------------------------
product_id | integer | | not null | nextval('products_product_id_seq'::regclass)
product_name | character varying(255) | | not null |
price | numeric(11,2) | | |
group_id | integer | | not null |
Indexes:
"products_pkey" PRIMARY KEY, btree (product_id)
select * from products;
product_id | product_name | price | group_id
------------+--------------------+---------+----------
1 | Microsoft Lumia | 200.00 | 1
2 | HTC One | 400.00 | 1
3 | Nexus | 500.00 | 1
4 | iPhone | 900.00 | 1
5 | HP Elite | 1200.00 | 2
6 | Lenovo Thinkpad | 700.00 | 2
7 | Sony VAIO | 700.00 | 2
8 | Dell Vostro | 800.00 | 2
9 | iPad | 700.00 | 3
10 | Kindle Fire | 150.00 | 3
11 | Samsung Galaxy Tab | 200.00 | 3
(11 rows)
select distinct on(group_id) group_id,product_name,price
from products order by group_id,price desc;
group_id | product_name | price
----------+--------------+---------
1 | iPhone | 900.00
2 | HP Elite | 1200.00
3 | iPad | 700.00
(3 rows)
select distinct on(group_id) group_id,product_name,price
from products order by group_id desc,price desc ;
group_id | product_name | price
----------+--------------+---------
3 | iPad | 700.00
2 | HP Elite | 1200.00
1 | iPhone | 900.00
```
<file_sep>/html+css/ie8/crash.md
```
当浏览器发现当前网站的HTML代码和样式无法和自身相兼容时
(即浏览器认为网站会显示出错误的排版和布局),就会自动启动兼容性视图设置了
```
<file_sep>/python/flask/appbuilder/1_install.md
```
pip install flask-appbuilder
安装flask-appbuilder会安装flask 相关的若干依赖
pip list
Package Version
---------------------- --------
apispec 1.3.3
attrs 19.1.0
Babel 2.6.0
certifi 2019.3.9
chardet 3.0.4
Click 7.0
colorama 0.4.1
defusedxml 0.6.0
Flask 1.0.3
Flask-AppBuilder 2.1.3
Flask-Babel 0.12.2
Flask-JWT-Extended 3.18.2
Flask-Login 0.4.1
Flask-OpenID 1.2.5
Flask-SQLAlchemy 2.4.0
Flask-WTF 0.14.2
idna 2.8
itsdangerous 1.1.0
Jinja2 2.10.1
jsonschema 3.0.1
MarkupSafe 1.1.1
marshmallow 2.19.2
marshmallow-enum 1.4.1
marshmallow-sqlalchemy 0.16.3
prison 0.1.1
PyJWT 1.7.1
pyrsistent 0.15.2
python-dateutil 2.8.0
python3-openid 3.1.0
pytz 2019.1
PyYAML 5.1
requests 2.22.0
six 1.12.0
SQLAlchemy 1.3.3
urllib3 1.25.2
Werkzeug 0.15.4
WTForms 2.2.1
安装前:
wheel 0.33.4
pip 19.1.1
setuptools 41.0.1
```
> - flask : The web framework, this is what we’re extending.
> - flask-sqlalchemy : DB access (see SQLAlchemy).
> - flask-login : Login, session on flask.
> - flask-openid : Open ID authentication.
> - flask-wtform : Web forms.
> - flask-Babel : For internationalization.
<file_sep>/linux/sysresource/tools.md
```
nmon (cpu,disk,net,nfs 监控工具)
nfsiostat (nfs io 监控工具)
sar
iotop
```
```
lspci
xdpyinfo
```
<file_sep>/linux/softs/ssh/sshd_service_config.md
```
配置:关闭用户使用密码登陆
# vim /etc/ssh/sshd_config
#禁用密码验证
PasswordAuthentication no
#打开下面3个的注释。43行
#启用密钥验证
RSAAuthentication yes
PubkeyAuthentication yes
#指定公钥数据库文件
AuthorizedKeysFile .ssh/authorized_keys
可以用下面命令可以修改(最好用vim手动):
sed -i "s/^PasswordAuthentication.*/PasswordAuthentication no/g" /etc/ssh/sshd_config
sed -i "s/^#RSAAuthentication.*/RSAAuthentication yes/g" /etc/ssh/sshd_config
sed -i "s/^#PubkeyAuthentication.*/PubkeyAuthentication yes/g" /etc/ssh/sshd_config
sed -i "s/^#AuthorizedKeysFile.*/AuthorizedKeysFile .ssh\/authorized_keys/g" /etc/ssh/sshd_config
重启SSH服务前建议多保留一个会话以防不测
# service sshd restart
```
<file_sep>/linux/desktop-evn/mint/美化/grub/conf.md
### Edit : /boot/grub/grub.cfg add the follow text for theme
insmod gfxmenu
loadfont ($root)/boot/grub/themes/Vimix/unifont-regular-16.pf2
insmod png
set theme=($root)/boot/grub/themes/Vimix/theme.txt
export theme
befere edit the conf: copy the theme dir to /boot/grub/themes.
file tree:
/boot/grub/themes $ tree -L 1
.
├── arch-silence
├── arch-silence-master.zip
├── aurora
├── Aurora-Penguinis-GRUB2.tar.gz
└── Vimix
### Edit : /boot/grub/grub.cfg remove submenu and uselss menuentry for os selectsd<file_sep>/linux/common/exit_code.md
**Reserved Exit Codes**
| Exit Code Number | Meaning | Example | Comments |
| ---------------- | ------------------------------------------------------------ | --------------------------- | ------------------------------------------------------------ |
| `1` | Catchall for general errors | let "var1 = 1/0" | Miscellaneous errors, such as "divide by zero" and other impermissible operations |
| `2` | Misuse of shell builtins (according to Bash documentation) | empty_function() {} | [Missing keyword](http://tldp.org/LDP/abs/html/debugging.html#MISSINGKEYWORD) or command, or permission problem (and [*diff* return code on a failed binary file comparison](http://tldp.org/LDP/abs/html/filearchiv.html#DIFFERR2)). |
| `126` | Command invoked cannot execute | /dev/null | Permission problem or command is not an executable |
| `127` | "command not found" | illegal_command | Possible problem with `$PATH` or a typo |
| `128` | Invalid argument to [exit](http://tldp.org/LDP/abs/html/exit-status.html#EXITCOMMANDREF) | exit 3.14159 | **exit** takes only integer args in the range 0 - 255 (see first footnote) |
| `128+n` | Fatal error signal "n" | *kill -9* `$PPID` of script | `**$?**` returns 137 (128 + 9) |
| `130` | Script terminated by Control-C | *Ctl-C* | Control-C is fatal error signal 2, (130 = 128 + 2, see above) |
| `255*` | Exit status out of range | exit -1 | **exit** takes only integer args in the range 0 - 255 |
<file_sep>/linux/softwaremanager/yum/whatprovides.md
查找 命令或lib(.so) 属于哪个包
```
yum whatprovides <keywork>
```
示例:
```
yum whatprovides libquadmath.so*
```
<file_sep>/python/pyinstaller.md
pyinstaller
```
pip install pyinstaller
```
```
参数说明:
-w指令 (不带额外参数)
直接发布的exe应用带命令行调试窗口,在指令内加入-w命令可以屏蔽;
-F指令(不带额外参数)
注意指令区分大小写。这里是大写。使用-F指令可以把应用打包成一个独立的exe文件,否则是一个带各种dll和依赖文件的文件夹;
-p指令
这个指令后面可以增加pyinstaller搜索模块的路径。因为应用打包涉及的模块很多。这里可以自己添加路径
-i 指定exe图标打包
```
```
例子:
pyinstaller -F myfile.py (打包后运行:ImportError: No module named ,使用-p )
pyinstaller -F myfile.py -p 源码包根目录 , 可执行程序换节点可能不能执行
pyinstaller -F setup.py 打包exe
pyinstaller -F -w setup.py 不带控制台的打包
pyinstaller -F -i xx.ico setup.py 打包指定exe图标打包
pyinstaller -D xxxx/setup.py
pyinstaller -p xxxx -D xxx/setup.py
pyinstaller xxx.spec
```
cxfreeze, py2exe
```
pip install cx_freeze
```
```
```
<file_sep>/linux/softs/perf/1_pmu.md
参考 https://github.com/freelancer-leon/notes/blob/master/kernel/profiling/perf.md
```
使用原始的 PMC 性能事件
根据 CPU 的手册,通过性能事件的标号配置 PMU 的性能计数器
perf top/stat ‐e r[Umask:EventSelect]
```
```
# perf stat -e r003c -a sleep 5
Performance counter stats for 'system wide':
26,086,011,863 r003c
5.001757790 seconds time elapsed
```
<file_sep>/js/seajs/start.md
```
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="sea/sea.js"></script>
<script type="text/javascript">
// seajs 的简单配置
seajs.config({
//all alias path base on this//所有别名基于本路径
// base:"../sea-modules/"
base: "./"
//define each self path//定义paths,本例未启用
//,paths:{
// "jQueryPath":"jquery"
//}
//define each alias name here
// jQuery: 加载当前目录下的 jquery-1.11.3.min.js
, alias: { //auto add suffix .js
"jQuery": "jquery-1.11.3.min"
, "module1": "./module1"
}
, preload: 'jQuery'
, vars: {
'locale': 'zh-cn' //本例未启用,在模块中可用格式{key},即{locale}表示变量
}
});
//加载入口模块,加载完成后调用模块的方法
// seajs.use(['jQuery','module1'],function($,m){
// m.scale();
// });
seajs.use(['jQuery', './module1.js'], function ($, m) {
m.scale();
m.scale();
m.a();
});
//seajs.use(['jQuery','../static/hellow/xxxx.js']);
</script>
</head>
<body>
</body>
</html>
```
```
define(function(require,exports,module){
var mode_var=1;
function scale(){
console.log("scale");
console.log(mode_var);
mode_var++;
}
function a(){
console.log("a");
console.log(mode_var);
mode_var++;
}
exports.scale= scale;
exports.a= a;
})
```
<file_sep>/linux/softs/ssh/免密登陆.md
```
1. . ssh-keygen: 生成密钥对 (ssh-keygen -t rsa 生成 密钥对)
2. cp -a id_rsa.pub authorized_keys 生成以认证文件
3. 拷贝 authorized_keys id_rsa 到需要登陆设备
```
免密:
1) .ssh目录的权限必须是700
2) .ssh/authorized_keys文件权限必须是600
```
1. 假设是B 主机,且免密登录用户名 为test
2. test 家目录权限需为 700 即 chmod 700 /home/test
3. .ssh 目录权限需为700 chmod 700 /home/test/.ssh
```
4 authorized_keys 文件权限 需为 600 chmod 600 /home/test/.ssh/authorized_keys
(know_hosts)首次登陆提示yes:
修改配置文件“~/.ssh/config”,加上这两行(SSH登陆时会忽略known_hsots文件,不安全。)
```
StrictHostKeyChecking no
UserKnownHostsFile /dev/null
```
server A免登录到server B:
```
1.在A上生成公钥私钥。
2.将公钥拷贝给server B,要重命名成authorized_keys
3.Server A向Server B发送一个连接请求。 (连接请求中含公钥))
4.Server B得到Server A的信息后,在authorized_key中查找对应的公钥,存在:则随机生成一个字符串,并用Server A的公钥加密,发送给Server A。,不存在:认证失败。 [Server A 将自己的公钥和私钥共享给Server C, Server C 也可以免密登陆到Server B]
[Server A 删除本机上的公钥文件后仍然能免密登陆,那么公钥信息应该是以另外的方式生成的?]
5.Server A得到Server B发来的消息后,使用私钥进行解密,然后将解密后的字符串发送给Server B。Server B进行和生成的对比,如果一致,则允许免登录。 [直接发送明文是否安全? 目前并不关注]
另一个版本的登陆认证流程:
1 客户端向服务端发送连接请求,询问服务器是否支持pubkey的方式进行登录
2 服务端收到客户端的请求,表示接收pubkey的方式进行登录。
3 接收到服务端的回复,客户端决定使用pubkey的方式进行登录,客户端将一段数据用私钥进行加密,生成签名,并且将自己的公钥发送给服务器。
4 服务端收到客户端发过来的数据,首先将客户端的公钥取出来,在/home/$USER/.ssh/authorized_keys/中查找是否存在客户端的公钥,如果有,进行对比。
仅仅对比是否存在客户端的公钥当然是不够安全的,服务器接着使用客户端提供的公钥对客户端发过来的签名(经私钥加密)进行解密,如果解密后的数据内容正确,表示整个验证流程完成。
5 服务端返回登录结果。
```
```
ssh 升级后,免密失效:
1: 远程登陆时不能登陆 no matching host key type found. Their offer: ssh-rsa,ssh-dss
解决办法:
修改"~/.ssh/config"
Host * 的配置项中添加:
HostKeyAlgorithms=+ssh-dss
2: (ssh -v user@host)查看调试信息:
send_pubkey_test: no mutual signature algorithm
解决办法:
修改"~/.ssh/config"
给对应主机的配置项中添加配置:
PubkeyAcceptedKeyTypes=+ssh-rsa
如果所有主机都需要,可配置在:
Host * 的配置项中
```
<file_sep>/python/base/path.md
```
import os
import sys
print(os.path.abspath(__file__))
print(os.path.realpath(__file__))
x.py 源文件, xx.py 为软链接,xxx.py 硬链接
x.py
xx.py -> x.py
xxx.py
执行软链接,输出:
/tmp/xx.py
/tmp/x.py
执行硬链接输出:
/tmp/xxx.py
/tmp/xxx.py
```
```
python2:
直接运行 和 模块运行 的区别
python yyy/xxx.py
python -m yyy/xxx # 文件不带后缀 (python 3 : 调用方式有差异 python3 -m yyy.xxx)
这是两种加载py文件的方式:
1叫做直接运行
2把模块当作脚本来启动(注意:但是__name__的值为'main' )
直接启动是把xx.py文件所在的目录放到了sys.path属性中。(与执行位置无关)
模块启动是把你输入命令的目录(也就是当前路径),放到了sys.path属性中 (与执行位置有关)
```
<file_sep>/linux/softs/fcitx/fcitx5.md
包列表:
```
fcitx5
fcitx5-chinese-addons
fcitx5-configtool
fcitx5-gtk
fcitx5-material-color
fcitx5-pinyin-zhwiki
fcitx5-qt
```
.xprofile 配置与 fcitx4 一致:
```
export GTK_IM_MODULE=fcitx
export XMODIFIERS=@im=fcitx
export QT_IM_MODULE=fcitx
```
用户配置文件放置目录: ~/.config/fcitx5
<file_sep>/golang/libs.md
zookeeper:
```
"github.com/samuel/go-zookeeper/zk"
```
logger:
```
"github.com/wonderivan/logger"
"github.com/jeanphorn/log4go"
```
daemon:
```
"github.com/takama/daemon" // 可用于编写linux 服务程序
```
mysql:
```
"github.com/go-sql-driver/mysql"
```
redis:
```
"github.com/gomodule/redigo"
```
conf:
```
"github.com/Unknwon/goconfig"
```
cron:
```
github.com/robfig/cron
```
带颜色的命令行输出:
```
github.com/mgutz/ansi
```
cpuid:
```
https://github.com/intel-go/cpuid
https://github.com/klauspost/cpuid
```
<file_sep>/linux/shell_script/dirname.md
dirname 用户获取但前执行脚本所在目录
```bash
cdir=$(cd $(dirname $0) && pwd)
```
<file_sep>/linux/devops/sonarqube/1_config.md
```
conf/sonar.properties
```
```
创建数据库,并配置数据库连接信息
sonar.jdbc.url=jdbc:postgresql://localhost/sonarqube
sonar.jdbc.username=sonarqube
sonar.jdbc.password=<PASSWORD>
```
```
sonar-scanner \
-Dsonar.projectKey=test \
-Dsonar.sources=. \
-Dsonar.host.url=http://192.168.2.231:9000 \
-Dsonar.login=577bfdb908c2f52cf42a2e0b31345c1dabd8c0a4
sonar-scanner \
-Dsonar.projectKey=test \
-Dsonar.sources=. \
-Dsonar.host.url=http://192.168.2.231:9000 \
-Dsonar.login=dbf57a42908b1edae6d4eecca6ab53abfd7298ec
```
```
mvn sonar:sonar \
-Dsonar.host.url=http://192.168.2.231:9000 \
-Dsonar.login=577bfdb908c2f52cf42a2e0b31345c1dabd8c0a4
```
<file_sep>/linux/common/pkgfile.md
```
*.so 无法打开共享对象文件: 没有那个文件或目录
pkgfile *.so : 查看so 属于那个包,安装后再看问题能否解决
```
```
ubuntu so 问题:
参考:
https://blog.csdn.net/huoxingrenhdh/article/details/82852852
sudo apt-get install apt-file
sudo apt-file update
apt-file search *.so.* / apt-file search *.so
```
```
yum so
yum install yum-utils
yum whatprovides *.so.* / yum whatprovides *.so
```
<file_sep>/gpu/flops.md
```
Core/Shader clock是什么?
core是显示核心的频率,shader是流处理器的频率;
N卡的CUDA核心和流处理器是同一个概念
N卡Core config 的第一项为流出来核心数。
Shaders:
nvidia:
Cuda cores(total)*Base clock (MHz)*2=Single precision (MAD or FMA)
```
<file_sep>/java/note_spring/content_property_placeholder.md
参考:https://blog.csdn.net/liuxin191863128/article/details/53406747/
读入配置文件
```xml
<context:property-placeholder location="classpath:jdbc.properties"/>
```
或者
```xml
<bean id="propertyPlaceholderConfigurer" class="org.springframework,beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>jdbc.properties<value/>
</list>
</property>
</bean>
```
配置文件:
```properties
#jdbc配置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=<PASSWORD>
```
使用:
```xml
<bean id="dataSource" class="org.springframework,jdbc,datasource.DriverManagerDataSource">
<property name="driverClassName" value="${driverClassName}"/>
<property name="url" value="${url}"/>
<property name="username" value="${username}"/>
<property name="password" value="${password}"/>
</bean>
```
```
由于Spring容器只能有一个PropertyPlaceholderConfigurer,如果有多个属性文件,这时就看谁先谁后了,先的保留 ,后的忽略。
```
<file_sep>/linux/common/selinux.md
关闭selinux:
```
SELinux一共有3种状态,分别是Enforcing,Permissive和Disabled状态。第一种是默认状态,表示强制启用,第二种是宽容的意思,即大部分规则都放行。第三种是禁用,即不设置任何规则。只能通过setenforce命令来设置前面两种状态,而如果想修改为disable状态,需要修改配置文件,同时重启系统。
查看状态:
# getenforce
临时修改:
# setenforce 0
永久修改:
配置文件:/etc/selinux/config
将 SELINUX=enforcing 改为 SELINUX=disabled
```
<file_sep>/golang/StartNote.md
```
使用`:=`的时候要确保左值没有被定义过
:= 会创建局部变量 (当要给全局变量赋值时要注意)
在函数中,简洁赋值语句 := 可在类型明确的地方代替 var 声明。
函数外的每个语句都必须以关键字开始(var, func 等等),因此 := 结构不能在函数外使用。
https://tour.go-zh.org/
变量的初始化
变量声明可以包含初始值,每个变量对应一个。
如果初始化值已存在,则可以省略类型;变量会从初始值中获得类型。
变量未赋值,默认值:
数值类型为 0,
布尔类型为 false,
字符串为 ""(空字符串)。
数值常量是高精度的值。
一个未指定类型的常量由上下文来决定其类型。
初始化语句和后置语句是可选的。
for ; sum < 1000; {
for 是 Go 中的 “while”
sum := 1
for sum < 1000 {
sum += sum
}
无限循环
如果省略循环条件,该循环就不会结束,因此无限循环可以写得很紧凑。
for {
}
if 语句与 for 循环类似,表达式外无需小括号 ( ) ,而大括号 { } 则是必须的
if 语句可以在条件表达式前执行一个简单的语句。该语句声明的变量作用域仅在 if 之内。(在最后的 return 语句处使用 v 看看。)
func pow(x, n, lim float64) float64 {
if v := math.Pow(x, n); v < lim {
return v
} else {
fmt.Printf("%g >= %g\n", v, lim)
}
// 这里开始就不能使用 v 了
return lim
}
switch:switch 的 case 无需为常量,且取值不必为整数
Go 自动提供了在这些语言中每个 case 后面所需的 break 语句。 除非以 fallthrough 语句结束,否则分支会自动终止。
switch os := runtime.GOOS; os {
case "darwin":
fmt.Println("OS X.")
case "linux":
fmt.Println("Linux.")
default:
// freebsd, openbsd,
// plan9, windows...
fmt.Printf("%s.\n", os)
}
而如果switch没有表达式,它会匹配true。
如果case带有fallthrough,程序会继续执行下一条case,不会再判断下一条case的expr,当前case fallthrough 后的语句不会执行
pow[]
for i, v := range pow {
// i 下标
// v value
}
for i := range pow{
// 只有下标
}
----------------------------------------------
map[<keytype>]<value_type>
type Vertex struct {
Lat, Long float64
}
var m map[string]Vertex
func xxxxx() {
m = make(map[string]Vertex)
m["Bell Labs"] = Vertex{
40.68433, -74.39967,
}
fmt.Println(m["Bell Labs"])
}
elem, ok := m[key]
若 key 在 m 中,ok 为 true ;否则,ok 为 false。若 key 不在映射中,那么 elem 是该映射元素类型的零值。
---------------------------------------------------
函数作为参数
func compute(fn func(float64, float64) float64) float64 {
return fn(3, 4)
}
compute(<func_name>)
函数的闭包(与 js 闭包类似)
------------------------------------
go 无类,有结构体
类型(接收者)+函数 组合构成了类似类的结构。
接收者的类型定义和方法声明必须在同一包内
不能为内建类型声明方法(接收者不能为内建类型)。
指针接收者:可改变接收者类型。
普通接收者:不能改变接收者类型。
------------------------------------
接口:
普通类型转为接口类型,通过接口类型调用函数。(需普通类型实现了接口类型对应的函数。同时需要区分指针类型与普通类型)
type Abser interface {
Abs() float64
}
func (f MyFloat) Abs() float64
func (v *Vertex) Abs() float64
var a Abser
f := MyFloat(-math.Sqrt2)
v := Vertex{3, 4}
a = f // a MyFloat 实现了 Abser
a = &v // a *Vertex 实现了 Abser
// 下面一行,v 是一个 Vertex(而不是 *Vertex)
// 所以没有实现 Abser。
//a = v
a.Abs()
------------------------------------
接口可能等于空指针(函数调用中需要判断),接口有 :接口值,类型
空接口可保存任何类型的值。(因为每个类型都至少实现了零个方法。)
var i interface{}
i=xxxx
类型断言 提供了访问接口值底层具体值的方式。
t := i.(T)
t, ok := i.(T)
若 i 保存了一个 T,那么 t 将会是其底层值,而 ok 为 true。
否则,ok 将为 false 而 t 将为 T 类型的零值。
类型选择:类型选择中的声明与类型断言 i.(T) 的语法相同,只是具体类型 T 被替换成了关键字 type。
switch v := i.(type) {
case T:
// v 的类型为 T
case S:
// v 的类型为 S
default:
// 没有匹配,v 与 i 的类型相同
}
fmt 包中定义的 Stringer 是最普遍的接口之一。
type Stringer interface {
String() string
}
Stringer 是一个可以用字符串描述自己的类型。fmt 包(还有很多包)都通过此接口来打印值
与 fmt.Stringer 类似,error 类型是一个内建接口:
type error interface {
Error() string
}
------------------------------------
------------------------------------
```
<file_sep>/linux/tools/tools.md
```
Iperf 是一个网络性能测试工具,Iperf可以测试最大TCP和UDP带宽性能,具有多种参数和UDP特性,可以根据需要调整,可以报告带宽、延迟抖动和数据包丢失。
```
```
nmon
AIX &Linux Performance Monitoring tool
```
```
nload
Monitors network traffic and bandwidth usage
```
```
ntfs-3g
NTFS filesystem driver and utilities
```
```
os-prober
Utility to detect other OSes on a set of drives
```
```
p7zip
command line file archiver with high compression ratio
```
```
screenfetch
CLI bash script to show system/them info in screenshots
```
```
sshpass
Fool ssh into accepting an interactive password non-interactively
```
```
vte3
Virtual TErminal Emulator widget for use with GTK3
```
```
zssh
ssh and telnet client with zmodem file transfer capability
```
```
lsblk
lspci
lscpu
lsmod
findmnt
ss/netstat
```
```
lshw
lsscsi
sg3utils
dmidecode
hdparm
```
<file_sep>/linux/softwaremanager/yum/rpm.md
```
rpm -qa :查询安装了的包。
rpm -qal: 查询安装了的包,及包中包含的文件。
```
```
rpm -qf file_filepath : 查询文件是属于哪个包的
```
<file_sep>/js/questions_mark/font_path.md
参考:https://blog.csdn.net/guoscy/article/details/79192065
真实路径应该是
xxx/static/fonts/icomoon.0125455.woff
浏览器实际加载路径为:
xxx/static/css/static/fonts/icomoon.0125455.woff
解决方法:
webpack 配置问题
在 build/webpack.prod.conf.js 中 extract :true 改为 fasle即可。
``` less
module: {
rules: utils.styleLoaders({
sourceMap: config.build.productionSourceMap,
extract: false
})
},
```
<file_sep>/js/vue/start.md
https://blog.csdn.net/Creabine/article/details/78879456
```
cnpm install -g vue-cli
vue init webpack <app-name>
使用默认参数创建工程
(npm, yarn 按个人喜好)
进入工程目录
安装依赖(npm install, yarn)[有时创建工程时已经将依赖安装上了,可跳过该步骤]
运行开发环境:
npm run dev , yarn dev
脚手架搭建完成
```
<file_sep>/html+css/ie8/iframe.md
```javascript
if (document.getElementById("iframe-main")) {
document.getElementById("iframe-main").src = url;
} else {
var iframe = document.createElement("iframe");
var container = document.getElementById("content-main");
iframe.style.width = "100%";
iframe.id = "iframe-main";
iframe.style.height = "650px";
// iframe.style.margin = '0';
// iframe.style.padding = '0';
iframe.scrolling = "no";
iframe.frameBorder = "no";
if (iframe.attachEvent) {
iframe.attachEvent("onload", function () {
......
});
} else {
iframe.onload = function () {
.....
};
}
iframe.src = url;
container.appendChild(iframe);
}
```
<file_sep>/linux/common/free.md
free
```
echo 1 > /proc/sys/vm/drop_caches [frees page-cache]
echo 2 > /proc/sys/vm/drop_caches [frees slab objects e.g. dentries, inodes]
echo 3 > /proc/sys/vm/drop_caches [cleans page-cache and slab objects]
```
<file_sep>/js/react/start.md
### 全局安装Webpack, Babel, Webpack-dev-server:
```
npm install babel webpack webpack-dev-server -g
```
### 在项目中安装 react, react-dom
```
npm install react react-dom --save
```
### 在项目中安装 Babel 转换器,需要用到插件 babel-preset-react, babel-preset-latest,latest 即最新的 ES 规范,包括了 Async/Await 这些新特性。
```
npm install babel-loader babel-core babel-preset-react babel-preset-latest --save
```
### 配置webpack,编辑webpack.config.js
```
module.exports = {
entry: './main.js', // 入口文件路径
output: {
path: '/',
filename: 'index.js'
},
devServer: {
inline: true,
port: 3333
},
module: {
loaders: [
{
test: /\.js$/, // babel 转换为兼容性的 js
exclude: /node_modules/,
loader: 'babel-loader',
query: {
presets: ['react', 'latest']
}
}
]
}
}
```
### 配置 npm scripts, 编辑 package.json,在"scripts"属性处添加一行:
```
"scripts": {
"start": "webpack-dev-server"
},
```<file_sep>/golang/base/hello_world.md
https://www.jianshu.com/nb/29056963
```go
package main
import "fmt"
func main() {
fmt.Println("Hello, World!")
}
```
```
运行
go run xxx.go
编译
go build xxx.go
```
<file_sep>/linux/common/vim.md
配置:
~/.vimrc
# 鼠标右键支持
set mouse-=a
http://www.runoob.com/linux/linux-vim.html
https://www.cnblogs.com/huxinga/p/7942194.html
1,查找
在normal模式下按下/即可进入查找模式,输入要查找的字符串并按下回车。 Vim会跳转到第一个匹配。按下n查找下一个,按下N查找上一个。
Vim查找支持正则表达式,例如/vim$匹配行尾的"vim"。 需要查找特殊字符需要转义,例如/vim\$匹配"vim$"。
2,大小写敏感查找
在查找模式中加入\c表示大小写不敏感查找,\C表示大小写敏感查找。例如:
/foo\c
将会查找所有的"foo","FOO","Foo"等字符串。
3,大小写敏感配置
Vim 默认采用大小写敏感的查找,为了方便我们常常将其配置为大小写不敏感:
" 设置默认进行大小写不敏感查找
set ignorecase
" 如果有一个大写字母,则切换到大小写敏感查找
set smartcase
将上述设置粘贴到你的~/.vimrc,重新打开Vim即可生效
4,查找当前单词
在normal模式下按下*即可查找光标所在单词(word), 要求每次出现的前后为空白字符或标点符号。例如当前为foo, 可以匹配foo bar中的foo,但不可匹配foobar中的foo。 这在查找函数名、变量名时非常有用。
按下g*即可查找光标所在单词的字符序列,每次出现前后字符无要求。 即foo bar和foobar中的foo均可被匹配到。
5,查找与替换
:s(substitute)命令用来查找和替换字符串。语法如下:
:{作用范围}s/{目标}/{替换}/{替换标志}
例如:%s/foo/bar/g会在全局范围(%)查找foo并替换为bar,所有出现都会被替换(g)
6,作用范围
作用范围分为当前行、全文、选区等等。
当前行:
:s/foo/bar/g
全文:
:%s/foo/bar/g
选区,在Visual模式下选择区域后输入:,Vim即可自动补全为 :'<,'>。
:'<,'>s/foo/bar/g
2-11行:
:5,12s/foo/bar/g
当前行.与接下来两行+2:
:.,+2s/foo/bar/g
替换标志
上文中命令结尾的g即是替换标志之一,表示全局global替换(即替换目标的所有出现)。 还有很多其他有用的替换标志:
空替换标志表示只替换从光标位置开始,目标的第一次出现:
:%s/foo/bar
i表示大小写不敏感查找,I表示大小写敏感:
:%s/foo/bar/i
# 等效于模式中的\c(不敏感)或\C(敏感)
:%s/foo\c/bar
c表示需要确认,例如全局查找"foo"替换为"bar"并且需要确认:
:%s/foo/bar/gc
回车后Vim会将光标移动到每一次"foo"出现的位置,并提示
replace with bar (y/n/a/q/l/^E/^Y)?
按下y表示替换,n表示不替换,a表示替换所有,q表示退出查找模式, l表示替换当前位置并退出。^E与^Y是光标移动快捷键,参考: Vim中如何快速进行光标移
大小写敏感查找
在查找模式中加入\c表示大小写不敏感查找,\C表示大小写敏感查找。例如:
/foo\c
将会查找所有的"foo","FOO","Foo"等字符串。
## VIM的列编辑操作
**删除列**
1.光标定位到要操作的地方。
2.CTRL+v 进入“可视 块”模式,选取这一列操作多少行。
3.d 删除。
**插入列**
插入操作的话知识稍有区别。例如我们在每一行前都插入"() ":
1.光标定位到要操作的地方。
2.CTRL+v 进入“可视 块”模式,选取这一列操作多少行。
3.SHIFT+i(I) 输入要插入的内容。
4.ESC 按两次,会在每行的选定的区域出现插入的内容。
打开多个文件
1.vim还没有启动
$ vim file1 file2 ... filen便可以打开所有想要打开的文件
2.vim已经启动
:open file 再打开一个文件,并且此时vim里会显示出file文件的内容。
3.在文件之间切换焦点
Ctrl+6—最后访问的两个文件之间切换
:bn—下一个文件
:bp—上一个文件
分栏显示(split)
0. 直接以分栏方式打开多个文件
$ vim -on file1 file2 ... filen 上下分栏打开n个文件
$ vim -On file1 file2 ... filen 左右分栏打开n个文件
1. 当前编辑文件分栏,两栏内容相同
:sp 上下分割,快捷键Ctrl+ws
:vsp 左右分割
2. 打开新文件新文件并与当前文件分栏
:sp xxx 在当前文件上方栏打开文件xxx,且xxx变为当前编辑文件
:vsp xxx 在当前文件左侧栏打开文件xxx,且xxx变为当前编辑文件
3.在各栏切换的方法(ctl+w松开之后在按 方向)
Ctrl+w+h/j/k/l ——切换到前/下/上/后栏
Ctrl+w+方向键——功能同上
Ctrl+ww——切换到下一个窗格中,周而复始
4. 关闭分栏
Ctrl+w+c 松开Ctrl再按c,否则命令无效
5. 调整当前分栏大小(省略n只缩放1行/列)
Ctrl+w+n> 左右扩大n列
Ctrl+w+n< 左右缩小n列
Ctrl+w+n+ 上下扩大n行
Ctrl+w+n- 上下缩小n行
```
位置跳转:
跳转到指定行
:数字 enter
数字gg
数字G
跳转文件头:
gg
跳转文件尾:
G
```
```
删除
删除当前行
dd
d+ 方向键(上/下): 向上/下删除
d+end : 删除到行尾
d+G : 删除到文件结束
:开始行,结束行d 回车 删除第x行到x行。
```
<file_sep>/linux/Fedora_Linux/yum/repo/repo.md
centos 6 :mirrors.ustc.edu.cn
```
# CentOS6-Base.repo
[base]
name=CentOS-6 - Base - mirrors.ustc.edu.cn
baseurl=https://mirrors.ustc.edu.cn/centos/6/os/$basearch/
gpgcheck=0
gpgkey=https://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6
#released updates
[updates]
name=CentOS-6 - Updates - mirrors.ustc.edu.cn
baseurl=https://mirrors.ustc.edu.cn/centos/6/updates/$basearch/
gpgcheck=0
gpgkey=https://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6
#additional packages that may be useful
[extras]
name=CentOS-6 - Extras - mirrors.ustc.edu.cn
baseurl=https://mirrors.ustc.edu.cn/centos/6/extras/$basearch/
gpgcheck=0
gpgkey=https://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-6 - Plus - mirrors.ustc.edu.cn
baseurl=https://mirrors.ustc.edu.cn/centos/6/centosplus/$basearch/
gpgcheck=0
enabled=0
gpgkey=https://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6
#contrib - packages by Centos Users
[contrib]
name=CentOS-6 - Contrib - mirrors.ustc.edu.cn
baseurl=https://mirrors.ustc.edu.cn/centos/6/contrib/$basearch/
gpgcheck=0
enabled=0
gpgkey=https://mirrors.ustc.edu.cn/centos/RPM-GPG-KEY-CentOS-6
```
CentOS 7 :
```
# CentOS-Base.repo
[base]
name=CentOS-$releasever - Base
#mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=os
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/os/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#released updates
[updates]
name=CentOS-$releasever - Updates
# mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=updates
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/updates/$basearch/
gpgcheck=1
gpgkey=file:///etc/<KEY>
#additional packages that may be useful
[extras]
name=CentOS-$releasever - Extras
# mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=extras
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/extras/$basearch/
gpgcheck=1
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
#additional packages that extend functionality of existing packages
[centosplus]
name=CentOS-$releasever - Plus
# mirrorlist=http://mirrorlist.centos.org/?release=$releasever&arch=$basearch&repo=centosplus
baseurl=https://mirrors.ustc.edu.cn/centos/$releasever/centosplus/$basearch/
gpgcheck=1
enabled=0
gpgkey=file:///etc/pki/rpm-gpg/RPM-GPG-KEY-CentOS-7
```<file_sep>/linux/desktop-evn/gnome/desktop_ico.md
install nemo
创建nemo.desktop文件,将文件复制到~/.config/autostart目录下,内容如下:
> [Desktop Entry]
> Type=Application
> Name=Desktop Icons
> Exec=nemo-desktop
> OnlyShowIn=GNOME;
> NoDisplay=true
> X-GNOME-Autostart-Phase=Desktop
> X-GNOME-Autostart-Notify=true
> X-GNOME-AutoRestart=true
> X-GNOME-Provides=filemanager
显示桌面图标
> gsettings set org.nemo.desktop show-desktop-icons true
注销账户重新登陆
```
nemo
安装完成,设置Nemo作为默认的文件管理器,并让 nemo 处理桌面图标:
xdg-mime default nemo.desktop inode/directory application/x-gnome-saved-search
gsettings set org.gnome.desktop.background show-desktop-icons false
gsettings set org.nemo.desktop show-desktop-icons true
恢复原来设置:
xdg-mime default nautilus.desktop inode/directory application/x-gnome-saved-search
gsettings set org.nemo.desktop show-desktop-icons false
gsettings set org.gnome.desktop.background show-desktop-icons true
```
<file_sep>/python/django_1.11/app_db.md
参考:https://www.cnblogs.com/li1234yun/p/8007095.html
models模型变动,变动后合并发生问题
```
python manage.py makemigrations --empty app_name
python manage.py makemigrations
python manage.py migrate
```
<file_sep>/java/webcommon/1-web.xml.md
web.xml
参考:
<https://www.cnblogs.com/hellojava/archive/2012/12/28/2835730.html>
<https://www.cnblogs.com/Jimc/p/9565603.html>
```
WEB容器的加载顺序是:ServletContext -> context-param -> listener -> filter -> servlet。并且这些元素可以配置在文件中的任意位置。
```
```
1. web 启动: WEB容器创建一个ServletContext(servlet上下文),这个web项目的所有部分都将共享这个上下文。
2. 容器将<context-param>转换为键值对,并交给servletContext。
3. 容器创建<listener>中的类实例,创建监听器。 (可读取servletContext 中的内容)
4. 载入filter, 创建过滤链
5. 载入servlet, 映射请求路径
```
spring 启动:
```
1. 创建ServletContext
2. 加载 <context-param> 到 servletContext
3. 创建监听器: 初始化spring :根据contextConfigLocation配置创建bean,配置数据库等。
4. 载入filter, 创建过滤链
5. 载入servlet, 映射请求路径 (静态动态资源路径映射,配置viewresover)
```
```xml
<servlet></servlet> 在向servlet或JSP页面制定初始化参数或定制URL时,必须首先命名servlet或JSP页面。Servlet元素就是用来完成此项任务的。
<servlet-mapping></servlet-mapping> 服务器一般为servlet提供一个缺省的URL:http://host/webAppPrefix/servlet/ServletName.但是,常常会更改这个URL,以便servlet可以访问初始化参数或更容易地处理相对URL。在更改缺省URL时,使用servlet-mapping元素。
<session-config></session-config> 如果某个会话在一定时间内未被访问,服务器可以抛弃它以节省内存。 可通过使用HttpSession的setMaxInactiveInterval方法明确设置单个会话对象的超时值,或者可利用session-config元素制定缺省超时值。
<mime-mapping></mime-mapping>如果Web应用具有想到特殊的文件,希望能保证给他们分配特定的MIME类型,则mime-mapping元素提供这种保证。
<welcome-file-list></welcome-file-list> 指示服务器在收到引用一个目录名而不是文件名的URL时,使用哪个文件。
<error-page></error-page> 在返回特定HTTP状态代码时,或者特定类型的异常被抛出时,能够制定将要显示的页面。
<taglib></taglib> 对标记库描述符文件(Tag Libraryu Descriptor file)指定别名。此功能使你能够更改TLD文件的位置,而不用编辑使用这些文件的JSP页面。
<resource-env-ref></resource-env-ref>声明与资源相关的一个管理对象。
<resource-ref></resource-ref> 声明一个资源工厂使用的外部资源。
<security-constraint></security-constraint> 制定应该保护的URL。它与login-config元素联合使用
<login-config></login-config> 指定服务器应该怎样给试图访问受保护页面的用户授权。它与sercurity-constraint元素联合使用。
<security-role></security-role>给出安全角色的一个列表,这些角色将出现在servlet元素内的security-role-ref元素的role-name子元素中。分别地声明角色可使高级IDE处理安全信息更为容易。
<env-entry></env-entry>声明Web应用的环境项。
<ejb-ref></ejb-ref>声明一个EJB的主目录的引用。
<ejb-local-ref></ejb-local-ref>声明一个EJB的本地主目录的应用。
Web应用图标
<icon>
<small-icon>/images/app_small.gif</small-icon>
<large-icon>/images/app_large.gif</large-icon>
</icon>
定义了WEB应用的名字
<display-name>App Name</display-name>
Web 应用描述
<disciption>This is a app disciption.</disciption>
上下文初始化参数
<context-param>
<param-name>ContextParameter</para-name>
<param-value>test</param-value>
<description>It is a test parameter.</description>
</context-param>
过滤器
<filter>
<filter-name>setCharacterEncoding</filter-name>
<filter-class>com.xxx.setCharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>setCharacterEncoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
监听器
<listener>
<listerner-class>listener.SessionListener</listener-class>
</listener>
servlets
<servlet>
<servlet-name>test</servlet-name>
<servlet-class>TestServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>test</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>test2</servlet-name>
<servlet-class>TestServlet2</servlet-class>
<init-param>
<param-name>foo</param-name>
<param-value>bar</param-value>
</init-param>
<run-as>
<description>Security role for anonymous access</description>
<role-name>tomcat</role-name>
</run-as>
<!-- 当Web应用启动时,装载Servlet的次序, 当值为正数或零时:Servlet容器先加载数值小的servlet,再依次加载其他数值大的servlet. 当值为负或未定义:Servlet容器将在Web客户首次访问这个servlet时加载它
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>test2</servlet-name>
<url-pattern>/test2</url-pattern>
</servlet-mapping>
session:
<session-config>
<session-timeout>120</session-timeout>
</session-config>
MIME类型配置
<mime-mapping>
<extension>html</extension>
<mime-type>text/html</mime-type>
</mime-mapping>
welcome page
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
</welcome-file-list>
error page
<error-page>
<error-code>404</error-code>
<location>/404.jsp</location>
</error-page>
<error-page>
<exception-type>java.lang.NullException</exception-type>
<location>/error.jsp</location>
</error-page>
TLD
<jsp-config>
<taglib>
<taglib-uri>http://jakarta.apache.org/tomcat/debug-taglib</taglib-uri>
<taglib-location>/WEB-INF/pager-taglib.tld</taglib-location>
</taglib>
</jsp-config>
资源工厂配置
<resource-ref>
<res-ref-name>mail/Session</res-ref-name>
<res-type>javax.mail.Session</res-type>
<res-auth>Container</res-auth>
</resource-ref>
```
<file_sep>/docker/install.md
https://wiki.archlinux.org/index.php/Docker#Installation
install
```
$ sudo pacman -S docker
resolving dependencies...
looking for conflicting packages...
Packages (4) bridge-utils-1.6-3 containerd-1.2.0-2 runc-1.0.0rc5+168+g079817cc-1 docker-1:18.09.0-2
Total Download Size: 55.75 MiB
Total Installed Size: 269.04 MiB
:: Proceed with installation? [Y/n] y
:: Retrieving packages...
bridge-utils-1.6-3-x86_64 15.5 KiB 310K/s 00:00 [#################################################] 100%
runc-1.0.0rc5+168+g079817cc-1-x86_64 2.0 MiB 296K/s 00:07 [#################################################] 100%
containerd-1.2.0-2-x86_64 21.0 MiB 218K/s 01:39 [#################################################] 100%
docker-1:18.09.0-2-x86_64 32.7 MiB 218K/s 02:34 [#################################################] 100%
(4/4) checking keys in keyring [#################################################] 100%
(4/4) checking package integrity [#################################################] 100%
(4/4) loading package files [#################################################] 100%
(4/4) checking for file conflicts [#################################################] 100%
(4/4) checking available disk space [#################################################] 100%
:: Processing package changes...
(1/4) installing bridge-utils [#################################################] 100%
(2/4) installing runc [#################################################] 100%
(3/4) installing containerd [#################################################] 100%
(4/4) installing docker [#################################################] 100%
Optional dependencies for docker
btrfs-progs: btrfs backend support [installed]
pigz: parallel gzip compressor support
:: Running post-transaction hooks...
(1/4) Reloading system manager configuration...
(2/4) Creating system user accounts...
(3/4) Reloading device manager configuration...
(4/4) Arming ConditionNeedsUpdate...
```
service:
```
启用: docker.service
# systemctl start docker
# docker info
```
if you want to be able to run docker as a regular user, add your user to the `docker` [user group](https://wiki.archlinux.org/index.php/User_group).
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
install:
```
# pacman -S docker
```
start service:
```
# systemctl status docker
# systemctl start docker
```
base usage:
```
docker --help
docker version
docker version
docker images
```
文档: https://docs.docker.com/get-started/<file_sep>/python/somelib/psutil.md
psutil是一个跨平台库(<http://code.google.com/p/psutil/>),能够轻松实现获取系统运行的进程和系统利用率(包括CPU、内存、磁盘、网络等)信息。它主要应用于系统监控,分析和限制系统资源及进程的管理。它实现了同等命令行工具提供的功能,如ps、top、lsof、netstat、ifconfig、who、df、kill、free、nice、ionice、iostat、iotop、uptime、pidof、tty、taskset、pmap等。目前支持32位和64位的Linux、Windows、OS X、FreeBSD和Sun Solaris等操作系统<file_sep>/python/setuptool_pip.md
```
setuptools
下载并解压
python setuptools-xxx/setup.py install (安装easy_install)
```
<file_sep>/linux/softwaremanager/pacman/pkgfile.md
```
pkgfile <command>
pkgfile <xxxxxx.so>
```
<file_sep>/python/flask/appbuilder/2_create_app.md
### 基本命令: flask fab 可使用命令 fabmanager 替换
fabmanager 为早期版本的命令, 新版本建议使用 flask fab 替换
fabmanager is going to be deprecated in 2.2.X, you can use the same commands on the improved 'flask fab <command>'
```
flask fab
Usage: flask fab [OPTIONS] COMMAND [ARGS]...
FAB flask group commands
Options:
--help Show this message and exit.
Commands:
babel-compile Babel, Compiles all translations
babel-extract Babel, Extracts and updates all messages marked for...
collect-static Copies flask-appbuilder static files to your projects...
create-addon Create a Skeleton AddOn (needs internet connection to...
create-admin Creates an admin user(创建管理员用户)
create-app Create a Skeleton application (needs internet...(创建app)
create-db Create all your database objects (SQLAlchemy...
create-permissions Creates all permissions and add them to the ADMIN...
create-user Create a user(创建普通用户)
list-users List all users on the database
list-views List all registered views
security-cleanup Cleanup unused permissions from views and roles.
security-converge Converges security deletes...
version Flask-AppBuilder package version
```
### 创建app:
```
$ flask fab create-app
填写相关参数后会根据app name 在当前目录下创建文件夹,存放项目相关文件
flask fab create-app
Your new app name: fab-demo
Your engine type, SQLAlchemy or MongoEngine (SQLAlchemy, MongoEngine) [SQLAlchemy]:
Downloaded the skeleton app, good coding!
项目基本骨架:
fab-demo
├── app
│ ├── __init__.py # 项目入口
│ ├── models.py # mode
│ ├── templates # web 模板
│ │ └── 404.html
│ ├── translations # 国际化各项语言目录
│ │ └── pt
│ │ └── LC_MESSAGES
│ │ ├── messages.mo
│ │ └── messages.po
│ └── views.py # views
├── babel # 国际化base
│ ├── babel.cfg
│ └── messages.pot
├── config.py #配置文件
├── README.rst
└── run.py #启动文件
```
### 运行
```
$ cd fab-demo
启动方式1:
$ flask run (使用5000 端口启动)
启动方式2:
$ python run.py (使用run.py中配置的端口启动: app.run(host="0.0.0.0", port=8080, debug=True))
此时已经可以访问web
```
创建用户:
```
创建管理员:
执行 flask fab create-admin 或 fabmanager create-admin
创建普通用户:
flask fab create-user 或 fabmanager create-user
```
<file_sep>/python/somelib/multiprocessing.md
```python
# -*- coding: utf-8 -*-
import os
import threading
import multiprocessing
import time
def proc1(pipe):
pipe.send('hello')
print('proc1 rec:', pipe.recv())
def proc2(pipe):
print('proc2 rec:', pipe.recv())
pipe.send('hello, too')
def worker(sign, lock):
lock.acquire()
print(sign, os.getpid())
time.sleep(1)
print("sleep end")
lock.release()
pass
def worker2(i,lock):
lock.acquire()
print('Worker',os.getpid())
print(i)
time.sleep(1)
print("sleep end")
lock.release()
pass
def testpip():
import multiprocessing as mul
# Build a pipe
pipe = mul.Pipe()
# Pass an end of the pipe to process 1
p1 = mul.Process(target=proc1, args=(pipe[0],))
# Pass the other end of the pipe to process 2
p2 = mul.Process(target=proc2, args=(pipe[1],))
p1.start()
p2.start()
p1.join()
p2.join()
def testthread():
print('Main:', os.getpid())
record = []
lock = threading.Lock()
for i in range(5):
thread = threading.Thread(target=worker, args=('thread', lock))
thread.start()
record.append(thread)
for thread in record:
thread.join()
def testprocess():
print('Main:', os.getpid())
jobs = []
lock = multiprocessing.Lock()
for i in range(5):
p = multiprocessing.Process(target=worker2, args=("process", lock))
jobs.append(p)
p.start()
pass
for pro in jobs:
pro.join()
# input worker
def inputQ(queue):
info = str(os.getpid()) + '(put):' + str(time.time())
queue.put(info)
# output worker
def outputQ(queue,lock):
info = queue.get()
lock.acquire()
print (str(os.getpid()) + '(get):' + info)
lock.release()
def testqueue():
record1 = [] # store input processes
record2 = [] # store output processes
lock = multiprocessing.Lock() # To prevent messy print
queue = multiprocessing.Queue(3)
# input processes
for i in range(10):
process = multiprocessing.Process(target=inputQ, args=(queue,))
process.start()
record1.append(process)
# output processes
for i in range(10):
process = multiprocessing.Process(target=outputQ, args=(queue, lock))
process.start()
record2.append(process)
for p in record1:
p.join()
queue.close() # No more object will come, close the queue
for p in record2:
p.join()
if __name__ == '__main__':
# testthread()
# testprocess()
# testpip()
testqueue()
```
```python
import queue
from multiprocessing.managers import BaseManager
class Job:
def __init__(self, job_id):
self.job_id = job_id
class Master:
def __init__(self):
# 派发出去的作业队列
self.dispatched_job_queue = queue()
# 完成的作业队列
self.finished_job_queue = queue()
def get_dispatched_job_queue(self):
return self.dispatched_job_queue
def get_finished_job_queue(self):
return self.finished_job_queue
def start(self):
# 把派发作业队列和完成作业队列注册到网络上
BaseManager.register('get_dispatched_job_queue', callable=self.get_dispatched_job_queue)
BaseManager.register('get_finished_job_queue', callable=self.get_finished_job_queue)
# 监听端口和启动服务
manager = BaseManager(address=('0.0.0.0', 8888), authkey='jobs')
manager.start()
# 使用上面注册的方法获取队列
dispatched_jobs = manager.get_dispatched_job_queue()
finished_jobs = manager.get_finished_job_queue()
# 这里一次派发10个作业,等到10个作业都运行完后,继续再派发10个作业
job_id = 0
while True:
for i in range(0, 10):
job_id = job_id + 1
job = Job(job_id)
print('Dispatch job: %s' % job.job_id)
dispatched_jobs.put(job)
while not dispatched_jobs.empty():
job = finished_jobs.get(60)
print('Finished Job: %s' % job.job_id)
manager.shutdown()
if __name__ == '__main__':
master = Master()
master.start()
pass
```
```
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import random, time, queue
from multiprocessing import freeze_support
from multiprocessing.managers import BaseManager
# 发送任务的队列:
task_queue = queue.Queue()
# 接收结果的队列:
result_queue = queue.Queue()
# 从BaseManager继承的QueueManager:
class QueueManager(BaseManager):
pass
def return_task_queue():
global task_queue
return task_queue
def return_result_queue():
global result_queue
return result_queue
def test():
# 把两个Queue都注册到网络上, callable参数关联了Queue对象:
# QueueManager.register('get_task_queue', callable=lambda: task_queue)
# QueueManager.register('get_result_queue', callable=lambda: result_queue)
QueueManager.register('get_task_queue', callable=return_task_queue)
QueueManager.register('get_result_queue', callable=return_result_queue)
# 绑定端口5000, 设置验证码'abc':
manager = QueueManager(address=('127.0.0.1', 5000), authkey=b'abc')
# 启动Queue:
manager.start()
# 获得通过网络访问的Queue对象:
task = manager.get_task_queue()
result = manager.get_result_queue()
# 放几个任务进去:
for i in range(10):
n = random.randint(0, 10000)
print('Put task %d...' % n)
task.put(n)
# 从result队列读取结果:
print('Try get results...')
for i in range(10):
r = result.get(timeout=10)
print('Result: %s' % r)
# 关闭:
manager.shutdown()
print('master exit.')
if __name__ == '__main__':
freeze_support()
test()
# # -*- coding: utf-8 -*-
#
# import random, time, queue,pickle
# from multiprocessing.managers import BaseManager
#
# # 发送任务的队列:
# task_queue = queue.Queue()
# # 接收结果的队列:
# result_queue = queue.Queue()
#
# # 从BaseManager继承的QueueManager:
# class QueueManager(BaseManager):
# pass
#
# # 把两个Queue都注册到网络上, callable参数关联了Queue对象:
# QueueManager.register('get_task_queue', callable=lambda: task_queue)
# QueueManager.register('get_result_queue', callable=lambda: result_queue)
# # 绑定端口5000, 设置验证码'abc':
# manager = QueueManager(address=('', 5000), authkey=b'abc')
# # 启动Queue:
# #manager.start()
# s = manager.get_server()
# s.serve_forever()
#
# # 获得通过网络访问的Queue对象:
# task = manager.get_task_queue()
# result = manager.get_result_queue()
# # 放几个任务进去:
# for i in range(10):
# n = random.randint(0, 10000)
# print('Put task %d...' % n)
# task.put(n)
# # 从result队列读取结果:
# print('Try get results...')
# for i in range(10):
# r = result.get(timeout=10)
# print('Result: %s' % r)
# # 关闭:
# manager.shutdown()
# print('master exit.')
#
#
#
```
```
# task_worker.py
import time, sys, queue
from multiprocessing.managers import BaseManager
# 创建类似的QueueManager:
class QueueManager(BaseManager):
pass
# 由于这个QueueManager只从网络上获取Queue,所以注册时只提供名字:
QueueManager.register('get_task_queue')
QueueManager.register('get_result_queue')
# 连接到服务器,也就是运行task_master.py的机器:
server_addr = '127.0.0.1'
print('Connect to server %s...' % server_addr)
# 端口和验证码注意保持与task_master.py设置的完全一致:
m = QueueManager(address=(server_addr, 5000), authkey=b'abc')
# 从网络连接:
try:
m.connect()
except:
print("连接主机失败")
exit()
# 获取Queue的对象:
task = m.get_task_queue()
result = m.get_result_queue()
# 从task队列取任务,并把结果写入result队列:
for i in range(13):
try:
n = task.get(timeout=1)
print('run task %d * %d...' % (n, n))
r = '%d * %d = %d' % (n, n, n*n)
time.sleep(4)
result.put(r)
except queue.Empty:
print('task queue is empty.')
except:
print("其他异常退出")
exit()
# 处理结束:
print('worker exit.')
```
<file_sep>/linux/softs/urxvt/config.md
```
!!$HOME/.Xresources
URxvt.preeditType:Root
!!调整此处设置输入法
URxvt.inputMethod:fcitx
!!颜色设置
URxvt.depth:32
!!中括号内数表示透明度
URxvt.inheritPixmap:true
URxvt.background:#000000
URxvt.foreground:#ffffff
URxvt.colorBD:Gray95
URxvt.colorUL:Green
URxvt.color1:Red2
URxvt.color4:RoyalBlue
URxvt.color5:Magenta2
URxvt.color8:Gray50
URxvt.color10:Green2
URxvt.color12:DodgerBlue
URxvt.color14:Cyan2
URxvt.color15:Gray95
!!URL操作
URxvt.urlLauncher:chromium
URxvt.matcher.button:1
Urxvt.perl-ext-common:matcher
!!滚动条设置
URxvt.scrollBar:False
URxvt.scrollBar_floating:False
URxvt.scrollstyle:plain
!!滚屏设置
URxvt.mouseWheelScrollPage:True
URxvt.scrollTtyOutput:False
URxvt.scrollWithBuffer:True
URxvt.scrollTtyKeypress:True
!!光标闪烁
URxvt.cursorBlink:True
URxvt.saveLines:3000
!!边框
URxvt.borderLess:False
!!字体设置
Xft.dpi:96
URxvt.font:xft:Source Code Pro:antialias=True:pixelsize=18,xft:WenQuanYi Zen Hei:pixelsize=18
URxvt.boldfont:xft:Source Code Pro:antialias=True:pixelsize=18,xft:WenQuanYi Zen Hei:pixelsize=18
Xft.rgba: rgb
Xft.hinting: true
Xft.hintstyle: hintslight
! 实现ctrl+shift+c/v的复制粘贴
URxvt.iso14755: false
URxvt.iso14755_52: false
URxvt.keysym.Shift-Control-V: eval:paste_clipboard
URxvt.keysym.Shift-Control-C: eval:selection_to_clipboard
```
生效
```
xrdb -load ~/.Xresource
```
```
参考:
https://www.cnblogs.com/vachester/p/5649813.html
https://segmentfault.com/a/1190000020859490
```
配置2:
```
!抗锯齿
Xft.antialias: true
Xft.rgba: rgb
Xft.hinting: true
Xft.hintstyle: hintslight
! 实现ctrl+shift+c/v的复制粘贴
! https://unix.stackexchange.com/questions/444773/how-to-disable-the-ctrlshift-binding-iso-14755-in-urxvt
! https://unix.stackexchange.com/questions/294337/rebinding-ctrl-alt-cv-to-ctrl-shift-cv-in-urxvt-9-20
URxvt.iso14755: false
URxvt.iso14755_52: false
! 一定要写全名及大写的C/V,否则无效
! Shift/Control 顺序无关
URxvt.keysym.Shift-Control-V: eval:paste_clipboard
URxvt.keysym.Shift-Control-C: eval:selection_to_clipboard
! 禁用之前的复制粘贴方案
URxvt.keysym.Control-Meta-c: builtin-string:
URxvt.keysym.Control-Meta-v: builtin-string:
! URxvt.font:xft:Monaco:style=Regular:antialias=True:size=12,xft:Source Han Sans CN:style=Regular:size=12
! URxvt.boldfont:xft:Source Code Pro:style=Regular:antialias=True:size=12,xft:Source Han Sans CN:style=Regular:size=12
URxvt.loginShell:true
URxvt.inputMethod:fcitx
URxvt.depth:32
URxvt.mouseWheelScrollPage:true
URxvt.scrollBar:false
URxvt.scrollBar_floating:false
URxvt.scrollstyle:rxvt
URxvt.scrollTtyOutput:false
URxvt.scrollWithBuffer:true
URxvt.scrollTtyKeypress:true
URxvt.cursorBlink:true
URxvt.cursorUnderline:false
URxvt.saveLines:100
URxvt.borderLess:false
URxvt.allow_bold:false
!URxvt.font:xft:Monaco:style=Regular:antialias=True:size=12,xft:Source Han Sans CN:style=Regular:size=12
!URxvt.boldfont:xft:Source Code Pro:style=Regular:antialias=True:size=12,xft:Source Han Sans CN:style=Regular:size=12
URxvt.font: xft:Bitstream Vera Sans Mono:size=10:atialias=true:hinting=true,xft:文泉驿等宽微米黑:size=10
URxvt.boldfont: xft:Bitstream Vera Sans Mono:bold:size=10:atialias=true:hinting=true, xft:文泉驿等宽微米黑:style=BOld:size=10
!URxvt.inheritPixmap:false
URxvt.transparent:false
URxvt.shading:20
URxvt.intensityStyles: false
URxvt.perl-ext-common: default,matcher,font-size
URxvt.url-launcher: /usr/bin/google-chrome-stable
URxvt.matcher.button: 1
!https://github.com/majutsushi/urxvt-font-size
URxvt.keysym.C-Up: font-size:increase
URxvt.keysym.C-Down: font-size:decrease
URxvt.keysym.C-equal: font-size:reset
!!######################### Colorscheme settings ########################!
#define S_base03 #002b36
#define S_base02 #073642
#define S_base01 #586e75
#define S_base00 #657b83
#define S_base0 #839496
#define S_base1 #93a1a1
#define S_base2 #eee8d5
#define S_base3 #fdf6e3
*background: S_base03
*foreground: S_base0
*fadeColor: S_base03
*cursorColor: S_base1
*pointerColorBackground:S_base01
*pointerColorForeground:S_base1
#define S_yellow #b58900
#define S_orange #cb4b16
#define S_red #dc322f
#define S_magenta #d33682
#define S_violet #6c71c4
#define S_blue #268bd2
#define S_cyan #2aa198
#define S_green #859900
!! black dark/light
*color0: S_base02
*color8: S_base03
!! red dark/light
*color1: S_red
*color9: S_orange
!! green dark/light
*color2: S_green
*color10: S_base01
!! yellow dark/light
*color3: S_yellow
*color11: S_base00
!! blue dark/light
*color4: S_blue
*color12: S_base0
!! magenta dark/light
*color5: S_magenta
*color13: S_violet
!! cyan dark/light
*color6: S_cyan
*color14: S_base1
!! white dark/light
*color7: S_base2
*color15: S_base3
```
<file_sep>/java/springboot/i18n.md
Note 2018-11-02T00.09.25
========================
国际化:i18n
参考:
https://blog.csdn.net/blueheart20/article/details/78115915?locationNum=4&fps=1
https://www.cnblogs.com/sagech/p/6018844.html
https://blog.csdn.net/linxingliang/article/details/52350238
https://blog.csdn.net/u012100371/article/details/78199568
```properties
application.properties 配置:
# i18n 目录位于resource 目录下
# 多个i18n messages 文件用 , 分割
spring.messages.basename=i18n/messages
spring.messages.encoding=UTF-8
```
```java
@Autowired
private MessageSource messageSource;
```<file_sep>/python/进制转换.md
https://www.cnblogs.com/jsplyy/p/5636246.html
bin(x)
Convert an integer number to a binary string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
oct(x)
Convert an integer number to an octal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
int([number | string[, base]])
Convert a number or string to an integer. If no arguments are given, return 0. If a number is given, return number.__int__(). Conversion of floating point numbers to integers truncates towards zero. A string must be a base-radix integer literal optionally preceded by ‘+’ or ‘-‘ (with no space in between) and optionally surrounded by whitespace. A base-n literal consists of the digits 0 to n-1, with ‘a’ to ‘z’ (or ‘A’ to ‘Z’) having values 10 to 35. The default base is 10. The allowed values are 0 and 2-36. Base-2, -8, and -16 literals can be optionally prefixed with 0b/0B, 0o/0O, or 0x/0X, as with integer literals in code. Base 0 means to interpret exactly as a code literal, so that the actual base is 2, 8, 10, or 16, and so that int('010', 0) is not legal, while int('010') is, as well as int('010', 8).
hex(x)
Convert an integer number to a hexadecimal string. The result is a valid Python expression. If x is not a Python int object, it has to define an __index__() method that returns an integer.
↓ 2进制 8进制 10进制 16进制
2进制 - bin(int(x, 8)) bin(int(x, 10)) bin(int(x, 16))
8进制 oct(int(x, 2)) - oct(int(x, 10)) oct(int(x, 16))
10进制 int(x, 2) int(x, 8) - int(x, 16)
16进制 hex(int(x, 2)) hex(int(x, 8)) hex(int(x, 10)) -
bin()、oct()、hex()的返回值均为字符串,且分别带有0b、0o、0x前缀。
Python进制转换(二进制、十进制和十六进制)实例
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2/10/16 base trans. wrote by srcdog on 20th, April, 2009
# ld elements in base 2, 10, 16.
import os,sys
# global definition
# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]
# bin2dec
# 二进制 to 十进制: int(str,n=10)
def bin2dec(string_num):
return str(int(string_num, 2))
# hex2dec
# 十六进制 to 十进制
def hex2dec(string_num):
return str(int(string_num.upper(), 16))
# dec2bin
# 十进制 to 二进制: bin()
def dec2bin(string_num):
num = int(string_num)
mid = []
while True:
if num == 0: break
num,rem = divmod(num, 2)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
# dec2hex
# 十进制 to 八进制: oct()
# 十进制 to 十六进制: hex()
def dec2hex(string_num):
num = int(string_num)
mid = []
while True:
if num == 0: break
num,rem = divmod(num, 16)
mid.append(base[rem])
return ''.join([str(x) for x in mid[::-1]])
# hex2tobin
# 十六进制 to 二进制: bin(int(str,16))
def hex2bin(string_num):
return dec2bin(hex2dec(string_num.upper()))
# bin2hex
# 二进制 to 十六进制: hex(int(str,2))
def bin2hex(string_num):
return dec2hex(bin2dec(string_num))<file_sep>/linux/desktop-evn/deepin-ui/setting.md
名称:打开控制中心
命令:dbus-send --print-reply --dest=com.deepin.dde.ControlCenter /com/deepin/dde/ControlCenter com.deepin.dde.ControlCenter.Show
```
qdbus 命令包含在 qt5-tools中
窗口左右停放:
https://unix.stackexchange.com/questions/401948/deepin-shortcut-for-docking-window-to-side-corner-of-screen
自定义快捷键
左边命令:(win+left)
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.TileActiveWindow 1
右边命令:(win+right)
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.TileActiveWindow 2
max
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.PerformAction 2
mix
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.PerformAction 3
win+s
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.PerformAction 1
win+w
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.PerformAction 6
qdbus com.deepin.wm /com/deepin/wm com.deepin.wm.PerformAction 7
```
<file_sep>/java/tomcat/静态资源中文乱码.md
tomcat 静态资源请求中文乱码.
参考 : https://www.cnblogs.com/sogeisetsu/p/12879823.html#1-characterencodingfilter-%E8%AE%BE%E7%BD%AEforceresponseencoding%E4%B8%BAtrue%E5%AF%BC%E8%87%B4%E4%B9%B1%E7%A0%81
修改tomcat 启动参数或配置文件
_______________________________________________________________________________________________________
方法1
```
JAVA_OPTS 添加 -Dfile.encoding=UTF8 -Dsun.jnu.encoding=UTF8
```
重启
_______________________________________________________________________________________________________
方法2:
conf\server.xml
```xml
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443"
URIEncoding="UTF-8"
/>
```
重启
_______________________________________________________________________________________________________
方法3:
conf\web.xml
```xml
<servlet>
<servlet-name>default</servlet-name>
<servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
<init-param>
<param-name>debug</param-name>
<param-value>0</param-value>
</init-param>
<init-param>
<param-name>fileEncoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>listings</param-name>
<param-value>false</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
```
重启<file_sep>/linux/sysresource/disk.md
```
/proc/diskstats (disk io 状态)
/proc/net/nfsfs/servers 挂在的nfs 服务器列表
```
<file_sep>/linux/softs/teamviewer/install.md
```
从teamviewer 下载程序后解压 (tar 压缩包 )
```
```
依赖(未安装依赖可能导致不能启动或启动后无主窗口):
hicolor-icon-theme (hicolor-icon-theme-git)
qt5-quickcontrols (qt5-quickcontrols-git)
qt5-webkit (qt5-webkit-print, qt5-webkit-git)
qt5-x11extras (qt5-x11extras-git)
```
<file_sep>/sql/postgresql/patition.md
参考:
https://blog.csdn.net/u010251897/article/details/80136995
https://www.jianshu.com/p/705c359ed76e
```
创建主表:
创建分区表:
CREATE TABLE 分表名 () inherits (主表名);
create table 分表名 (
check ( 时间字段名 >= date '2018-01-01' and 时间字段名 < date '2018-04-01')
) inherits (主表名);
创建触发器或rule:
挂载触发器(RULE 可在创建时绑定触发条件):
```
pg11:
参考: http://www.cnblogs.com/jonney-wang/p/9238923.html
http://www.postgres.cn/news/viewone/1/271
```
range分区表:
create table 主表名(...) PARTITION BY RANGE (时间字段) WITH (OIDS = FALSE) ;
分区主表不能建立全局约束,使用partition by range(xxx)说明分区的方式,xxx可以是多个字段
CREATE TABLE 分表名 PARTITION OF 主表名 FOR VALUES FROM ('2017-01-01 00:00:00') TO ('2018-01-01 00:00:00');
list分区表:
create table 主表名(...) partition by list( xxx );
CREATE TABLE 分表名 PARTITION OF 主表名 FOR VALUES in ('xx')
```
<file_sep>/golang/daemon/3.md
```
github.com/sevlyar/go-daemon
```
<file_sep>/sql/postgresql/数据类型.md
名称 描述 存储大小 范围
smallint 存储整数, 小范围 2字节 -32768 至 +32767
integer 存储整数。 使用这个类型可存储典型的整数 4字节 -2147483648 至 +2147483647
bigint 存储整数, 大范围。 8字节 -9223372036854775808 至 9223372036854775807
decimal 用户指定的精度,精确 变量 小数点前最多为131072个数字; 小数点后最多为16383个数字。
numeric 用户指定的精度,精确 变量 小数点前最多为131072个数字; 小数点后最多为16383个数字。
real 可变精度,不精确 4字节 6位数字精度
double 可变精度,不精确 8字节 15位数字精度
serial 自动递增整数 4字节 1 至 2147483647
bigserial 大的自动递增整数 8字节 1 至 9223372036854775807
数据类型 描述
char(size) 这里size是要存储的字符数。固定长度字符串,右边的空格填充到相等大小的字符。
character(size) 这里size是要存储的字符数。 固定长度字符串。 右边的空格填充到相等大小的字符。
varchar(size) 这里size是要存储的字符数。 可变长度字符串。
character varying(size) 这里size是要存储的字符数。 可变长度字符串。
text 可变长度字符串。
```
名称 存储格式 描述
boolean 1 字节 true/false
```
名称 描述 存储大小 最小值 最大值 解析度
timestamp [ (p) ] [不带时区 ] 日期和时间(无时区) 8字节 4713 bc 294276 ad 1微秒/14位数
timestamp [ (p) ] 带时区 包括日期和时间,带时区 8字节 4713 bc 294276 ad
date 日期(没有时间) 4字节 4713 bc 5874897 ad 1微秒/14位数
time [ (p) ] [ 不带时区 ] 时间(无日期) 8字节 00:00:00 24:00:00 1微秒/14位数
time [ (p) ] 带时区 仅限时间,带时区 12字节 00:00:00+1459 24:00:00-1459 1微秒/14位数
interval [ fields ] [ (p) ] 时间间隔 12字节 -178000000年 178000000年 1微秒/14位数
名称 描述 存储大小 范围
money 货币金额 8字节 -92233720368547758.08 至 +92233720368547758.07
名称 存储大小 表示 描述
point 16字节 在一个平面上的点 (x,y)
line 32字节 无限线(未完全实现) ((x1,y1),(x2,y2))
lseg 32字节 有限线段 ((x1,y1),(x2,y2))
box 32字节 矩形框 ((x1,y1),(x2,y2))
path 16+16n字节 封闭路径(类似于多边形) ((x1,y1),…)
polygon 40+16n字节 多边形(类似于封闭路径) ((x1,y1),…)
circle 24字节 圆 <(x,y),r>(中心点和半径)
参考: https://www.runoob.com/postgresql/postgresql-data-type.html
<file_sep>/sql/mysql/start.md
1. 连接数据库所在服务器
2. 启动数据库服务器进程
systemctl status mariadb # 查看数据库服务是否启动
systemctl stop mariadb # 停止数据库服务
systemctl start mariadb # 启动数据服务
systemctl restart mariadb # 重启数据服务
3. 登录数据库服务
mysql -p -u root (密码 <PASSWORD>)
4: 查看数据库列表: show databases;
使用数据库: use database_name
查看数据表列表: show tables;
查看表结构: <file_sep>/js/others_lib.md
libs:
https://yoxjs.github.io/yox/#/
solutions:
<https://blog.csdn.net/x619y/article/details/81567955>
<file_sep>/java/maven/exclusion.md
```xml
<dependency>
<!-- 排除一些不需要同时下载的依赖jar -->
<groupId>xxx</groupId>
<artifactId>xxx</artifactId>
<version>${xxxx.version}</version>
<exclusions>
<exclusion>
<groupId>x</groupId>
<artifactId>xx</artifactId>
</exclusion>
</exclusions>
</dependency>
<!--排除所有依赖的jar-->
<exclusions>
<exclusion>
<groupId>*</groupId>
<artifactId>*</artifactId>
</exclusion>
</exclusions>
```
一般在包冲突或项目瘦身时使用.<file_sep>/linux/common/ulimits.md
资源使用限制
参考: <https://www.cnblogs.com/operationhome/p/11966041.html>
```
ulimit -a
ulimit <选项> # 查看
ulimit <选项> <limit> # 修改
输出样例:
core file size (blocks, -c) unlimited
data seg size (kbytes, -d) unlimited
scheduling priority (-e) 0
file size (blocks, -f) unlimited
pending signals (-i) 63377
max locked memory (kbytes, -l) 64
max memory size (kbytes, -m) unlimited
open files (-n) 1024
pipe size (512 bytes, -p) 8
POSIX message queues (bytes, -q) 819200
real-time priority (-r) 0
stack size (kbytes, -s) 8192
cpu time (seconds, -t) unlimited
max user processes (-u) 63377
virtual memory (kbytes, -v) unlimited
file locks (-x) unlimited
```
```
配置文件: /etc/security/limits.conf
配置后新启终端生效(或reboot,重启sshd)
```
```
配置说明
# 第一列表示用户,组(@开头)
# 第二列表示软限制还是硬限制
# 第三列表示限制的资源类型
# 第四列表示限制的最大值
# hard和soft的区别:
# soft是一个警告值,而hard则是一个真正意义的阀值,超过就会报错,一般情况下都是设为同一个值。
# core是内核文件
# nofile是文件描述符
# noproc是进程
# 一般情况下只限制文件描述符数和进程数就够了
# 打开文件数
* soft nofile 65536 # open files (-n)
* hard nofile 65536
# 进程数
* soft nproc 65565
* hard nproc 65565 # max user processes (-u)
* soft memlock unlimited
* hard memlock unlimited
```
<file_sep>/golang/base/3_array.md
slice
```go
var varName []valueType //声明切片
```
array
```go
var varName [size]valueType //声明数组
```
<file_sep>/linux/common/nc.md
nc: netcat
扫描通信端口
nc -zvn ip port
nc -zv ip port
z 参数告诉netcat使用0 IO,连接成功后立即关闭连接, 不进行数据交换
v 详细输出
n 参数告诉netcat 不要使用DNS反向查询IP地址的域名
usage: nc [-46bCDdhjklnrStUuvZz] [-I length] [-i interval] [-O length]
[-P proxy_username][-p source_port] [-q seconds][-s source]
[-T toskeyword] [-V rtable] [-w timeout] [-X proxy_protocol]
[-x proxy_address[:port]] [destination] [port]
Command Summary:
-4 Use IPv4
-6 Use IPv6
-b Allow broadcast
-C Send CRLF as line-ending
-D Enable the debug socket option
-d Detach from stdin
-h This help text
-I length TCP receive buffer length
-i secs Delay interval for lines sent, ports scanned
-j Use jumbo frame
-k Keep inbound sockets open for multiple connects
-l Listen mode, for inbound connects
-n Suppress name/port resolutions
-O length TCP send buffer length
-P proxyuser Username for proxy authentication
-p port Specify local port for remote connects
-q secs quit after EOF on stdin and delay of secs
-r Randomize remote ports
-S Enable the TCP MD5 signature option
-s addr Local source address
-T toskeyword Set IP Type of Service
-t Answer TELNET negotiation
-U Use UNIX domain socket
-u UDP mode
-V rtable Specify alternate routing table
-v Verbose
-w secs Timeout for connects and final net reads
-X proto Proxy protocol: "4", "5" (SOCKS) or "connect"
-x addr[:port] Specify proxy address and port
-Z DCCP mode
-z Zero-I/O mode [used for scanning]
Port numbers can be individual or ranges: lo-hi [inclusive]
```
比如将机器A上的mytest目录上传到到机器 B(192.168.0.11)上,只需要:
在机器B上,用nc来监听一个端口,随便就好,只要不被占用;并且将收到的数据用tar展开。-l代表监听模式。
nc -l |tar -C /target_dir -zxf -
然后,在A上通过nc和 tar发送test目录。使用一致的6666的端口。
tar -zcvf - mytest |nc 192.168.0.11
```
<file_sep>/java/java_common/ThreadPool.md
参考:
<https://www.cnblogs.com/zhujiabin/p/5404771.html>
<https://www.jianshu.com/p/46728d6bc6b2>
```
线程创建方式
通过实现 Runnable 接口; 实现 run() 方法
通过继承 Thread 类本身; 重写 run() 方法
通过 Callable 和 Future 创建线程。 实现 call() 方法
```
```
线程池
newCachedThreadPool:创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
newFixedThreadPool:创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待
newScheduledThreadPool:创建一个定长线程池,支持定时及周期性任务执行
newSingleThreadExecutor:创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
```
<file_sep>/python/base/eval.md
```
eval() 函数用来执行一个字符串表达式,并返回表达式的值。
eval(expression[, globals[, locals]])
expression : 字符串
globals : 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
locals : 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
可使用eval,动态生成函数,动态执行代码。
```
<file_sep>/linux/common/is_cmd_exists.md
```
command -v foo >/dev/null 2>&1 || { echo >&2 "not exists. Aborting.";}
type foo >/dev/null 2>&1 || { echo >&2 "not exists. Aborting."; }
hash foo 2>/dev/null || { echo >&2 "not exists. Aborting."; }
gnudate() {
if hash gdate 2>/dev/null; then
gdate "$@"
else
date "$@"
fi
}
```
<file_sep>/golang/Modules.md
go v1.11开始支持的[go Modules](https://github.com/golang/go/wiki/Modules)
Go Modules具有一些优点:
- 不必须将项目目录放在GOPATH中
- 不使用vendor目录,而是统一安装到`$GOPATH/pkg/mod/cache`
- build/run时,自动析出项目import的包并安装
go env 查看变量:
$GOPATH 默认为 ${HOME}/go , go/pkg /mode目录下缓存 依赖包
部分包由于网络原因可能不能下载:
```bash
export GOPROXY="https://athens.azurefd.net"
(这里使用了微软提供的代理)
```
<https://segmentfault.com/a/1190000018536993>
文件依赖引用发生变化:
```go
// 项目下的模块名引入: go mod init <模块名> , import <模块名>/模块
```
自定义项目下的包引用:
```go
模块名: go mod init 指定的模块名
包名: 项目目录下的相对目录。
import <模块名>.<包名>
```
<file_sep>/java/java_common/Annotation.md
```
元注解
@Target:注解的作用目标
@Retention:注解的生命周期
@Documented:注解是否应当被包含在 JavaDoc 文档中
@Inherited:是否允许子类继承该注解
@Repeatable(JDK1.8加入): 注解可以同时作用一个对象多次,但是每次作用注解又可以代表不同的含义
```
```
@Target
ElementType.TYPE:允许被修饰的注解作用在类、接口和枚举上
ElementType.FIELD:允许作用在属性字段上
ElementType.METHOD:允许作用在方法上
ElementType.PARAMETER:允许作用在方法参数上
ElementType.CONSTRUCTOR:允许作用在构造器上
ElementType.LOCAL_VARIABLE:允许作用在本地局部变量上
ElementType.ANNOTATION_TYPE:允许作用在注解上
ElementType.PACKAGE:允许作用在包上
```
```
@Retention
RetentionPolicy.SOURCE:当前注解编译期可见,不会写入 class 文件
RetentionPolicy.CLASS:类加载阶段丢弃,会写入 class 文件
RetentionPolicy.RUNTIME:永久保存,可以反射获取
```
```
注解的本质就是一个Annotation接口
```
```
定义:
public @interface MyTestAnnotation {
}
```
```
注解读取: 反射
isAnnotationPresent(注解类.class) : 是否使用指定注解
getAnnotation(注解类.class) : 获取注解(Annotation),返回值为泛型
通过Annotation 可获取注解的数据。
类获取属性
Field[] getDeclaredFields()
public Field getDeclaredField(String name)
获取方法
Method[] getDeclaredMethods()
public Method getDeclaredMethod(String name, Class<?>... parameterTypes)
```
```
使用场景:
注解用于配置
```
<file_sep>/linux/bash_terminal.md
```
PS1='$(if [[ $? == 0 ]]; then echo "\[\e[32m\]:)"; else echo "\[\e[31m\]:("; fi)\[\e[0m\] \[\e[0;36m\]\d \t \[\e[1;34m\] \[\033[01;33;1m\]\u\[\033[00;32;1m\]@\[\033[01;36;1m\]\h\[\033[00;32;1m\]:\[\033[00;34;1m\]\w \[\033[01;32;1m\]$(git branch 2>/dev/null | sed -n "s/* \(.*\)/\1 /p")\$ \[\033[01;37;1m\]'
reset="\[\e[0m\]"
# Magic Bash Prompt Version 1.0.1
next_hue()
{
color=$((31 + (++color % 7))) # set 31 to 30 for dark on light
PS1="\[\e[1;${color}m\]\\$ $reset" # set 1 to 0 for dark on light
PS1='$(if [[ $? == 0 ]]; then echo "\[\e[32m\]:)"; else echo "\[\e[31m\]:("; fi)\[\e[0m\] \[\e[0;36m\]\d \t \[\e[1;34m\] \[\033[01;33;1m\]\u\[\033[00;32;1m\]@\[\033[01;36;1m\]\h\[\033[00;32;1m\]:\[\033[00;34;1m\]\w \[\033[01;32;1m\]$(git branch 2>/dev/null | sed -n "s/* \(.*\)/\1 /p") \[\e[1;${color}m\]\\$ $reset '
}
random_hue()
{
color=$(($RANDOM % 7 + 31)) # set 31 to 30 for dark on light
PS1="\[\e[1;${color}m\]\\$ $reset" # set 1 to 0 for dark on light
PS1='$(if [[ $? == 0 ]]; then echo "\[\e[32m\]:)"; else echo "\[\e[31m\]:("; fi)\[\e[0m\] \[\e[0;36m\]\d \t \[\e[1;34m\] \[\033[01;33;1m\]\u\[\033[00;32;1m\]@\[\033[01;36;1m\]\h\[\033[00;32;1m\]:\[\033[00;34;1m\]\w \[\033[01;32;1m\]$(git branch 2>/dev/null | sed -n "s/* \(.*\)/\1 /p")\[\e[1;${color}m\]\\$ '
}
# 执行命令前执行一次,生成随机颜色。
PROMPT_COMMAND="random_hue"
```
<file_sep>/golang/base/5_stuct.md
```go
type StructType struct {
var1 type1
var2 type2
var3 type3
}
var varstruct StructType // 声明结构体
```
```go
type User struct{
name string
age int
address string
}
user:= User{name:"测试",age:10}
user.address="地址"
f.Println(user)
//匿名结构
person:= struct {
name string
age int
}{name:"匿名",age:1}
f.Println("person:",person)
```
```
结构体属性名大写开头,否则无法转json
```
<file_sep>/linux/arch/virtualbox.md
安装 virtualbox 后新建虚拟机后不能启动
错误: kernel driver not installed
解决方法:
sudo pacman -Sy linux-headers
sudo /sbin/rcvboxdrv setup
<file_sep>/linux/opensuse/0-网络配置.md
参考: <https://blog.csdn.net/weixin_41518046/article/details/104515243>
```
ip设置 /etc/sysconfig/network/ifcfg-xxxx
IPADDR='192.168.x.x/24'
```
```
网关设置:/etc/sysconfig/network/routes
添加网关
default xx.xxx.xx.xx
检查路由: # routel / route
```
```
dns :
配置 /etc/sysconfig/network/config 中的
NETCONFIG_DNS_STATIC_SERVER="dns_ip"
多个用空格分开
```
```
重启网络:service network restart
```
<file_sep>/html+css/css/span_text.md
span 换行,但不截断单词
```css
span{
white-space: normal;
word-break:break-all;
}
```
css 熟悉说明:
```
white-space 属性设置如何处理元素内的空白
white-space: normal|pre|nowrap|pre-wrap|pre-line|inherit;
normal默认。空白会被浏览器忽略。
pre 空白会被浏览器保留。其行为方式类似 HTML 中的 pre 标签。
nowrap文本不会换行,文本会在在同一行上继续,直到遇到 br 标签为止。
pre-wrap 保留空白符序列,但是正常地进行换行。
pre-line 合并空白符序列,但是保留换行符。
inherit 规定应该从父元素继承 white-space 属性的值。
----------------------------------------------------------------
word-wrap 属性用来标明是否允许浏览器在单词内进行断句
word-wrap: normal|break-word;
word-wrap 属性用来标明是否允许浏览器在单词内进行断句
normal: 只在允许的断字点换行(浏览器保持默认处理)
break-word:在长单词或URL地址内部进行换行,
/*内容将在边界内换行。如果需要,单词内部允许断行。*/
----------------------------------------------------------------
word-break 属性用来标明怎么样进行单词内的断句
word-break: normal|break-all|keep-all;
normal:使用浏览器默认的换行规则。
break-all:允许在单词内换行 , 允许任意非CJK(Chinese/Japanese/Korean)文本间的单词断行。
keep-all:只能在半角空格或连字符处换行,
不允许CJK(Chinese/Japanese/Korean)文本中的单词换行,只能在半角空格或连字符处换行。非CJK文本的行为实际上和normal一致。
```
<file_sep>/RevisionControl/0.md
- 集中式版本控制系统:Subversion(SVN)、CVS、VSS 等。
- 分布式版本控制系统:Git、Mercurial(Hg) 等。
Mercurial:由 Python 编写的分布式版本控制系统,具备出色的跨平台能力.
<file_sep>/java/spring-mvc/web_xml.md
```
spring ioc
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>......./spring.xml</param-value>
</context-param>
spring mvc:
controller扫描,静态资源路径映射,response和视图模板配置。
interceptor,viewResolver,exceptionResolver,applicaitonContext
<servlet>
<servlet-name>dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>........./applicationContext.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
```
<file_sep>/python/pip/install_pack.md
whl:
```
pip install **.whl
```
安装 zip或tar.gz:
```
解压
python setup.py install
```
egg:
```
easy_install packageName
easy_install package.egg
```
<file_sep>/golang/doc.md
go doc
```
go doc --all ./package/
```
<file_sep>/linux/wayland/wayland_apps.md
```
yay -S wdisplays
yay -S wl-clipboard
yay -S xsensors
yay -S pavucontrol
```
<file_sep>/linux/desktop-evn/i3/install.md
```
双屏配置:xrander ,arandr (图像配置工具)
```
lock ~/.config/i3/config:
```
# i3lock
mode "i3lock: Return to lock/Escape to Cancel" {
bindsym Return mode "default" exec i3lock -i ~/Pictures/Wallpapers/x.png
bindsym Escape mode "default"
}
bindsym Control+$ALT +l mode "i3lock: Return to lock/Escape to Cancel"
```
```
xcompmgr 用来实现终端透明
volumeicon
feh 用于设置背景图
# Autostart
exec --no-startup-id xcompmgr &
# exec --no-startup-id nm-applet 管理网络 (托盘)
exec --no-startup-id fcitx
exec --no-startup-id volumeicon 控制音量的小插件(托盘)
lxappearance 用来调节gtk主题和字体
dunst 系统通知
```
```
https://www.jianshu.com/p/e1184c26794b
```
```
rofi 替换启动器
bindsym $mod+d exec --no-startup-id "rofi -combi-modi window,drun,run,ssh -show combi -modi combi"
```
```
xprop
获取窗口class
```
<file_sep>/linux/ubuntu/apt-get.md
```
sudo apt-get update: 升级安装包相关的命令,刷新可安装的软件列表(但是不做任何实际的安装动作)
sudo apt-get upgrade: 进行安装包的更新(软件版本的升级)
sudo apt-get dist-upgrade: 进行系统版本的升级(Ubuntu版本的升级)
sudo do-release-upgrade: Ubuntu官方推荐的系统升级方式,若加参数-d还可以升级到开发版本,但会不稳定
sudo apt-get autoclean: 清理旧版本的软件缓存
sudo apt-get clean: 清理所有软件缓存
sudo apt-get autoremove: 删除系统不再使用的孤立软件
```
```
卸载
sudo apt-get remove --purge 软件名称
sudo apt-get autoremove --purge 软件名称
清理残留数据
dpkg -l |grep ^rc|awk '{print $2}' |sudo xargs dpkg -P
```
<file_sep>/linux/shell_script/textfile.md
[求shel取最后一次出现的字符串以后的行](http://bbs.chinaunix.net/thread-4158607-1-1.html)
```
不包含关键字行
sed -e :a -e "N;/Performance Statistics/s/.*\n//" -e '$!ba' file
包含关键字行
awk '/Performance/{s=""}{s=s?s"\n"$0:$0}END{print s}' tmp
```
<file_sep>/js/node/install.md
### nodejs 下载
<https://npm.taobao.org/mirrors/node/>
### cnpm install
```
npm install -g cnpm --registry=https://registry.npm.taobao.org
```
<file_sep>/C_or_C++/tools/cmake/cmake_cmd.md
```
cmake --help-module-list : 列举 find_package 可支持的配置项
cmake --help-module <module> : 查看详细
```
<file_sep>/C_or_C++/backtrace.md
backtrace: 查看程序运行时函数调用的堆栈信息
```
#include <execinfo.h>
int backtrace(void **buffer, int size);
char **backtrace_symbols(void *const *buffer, int size);
void backtrace_symbols_fd(void *const *buffer, int size, int fd);
```
<file_sep>/sql/postgresql/series.md
[Documentation](https://www.postgresql.org/docs/) → [PostgreSQL 13](https://www.postgresql.org/docs/13/index.html)
| FunctionDescription |
| ------------------------------------------------------------ |
| `generate_series` ( *`start`* `integer`, *`stop`* `integer` [, *`step`* `integer` ] ) → `setof integer``generate_series` ( *`start`* `bigint`, *`stop`* `bigint` [, *`step`* `bigint` ] ) → `setof bigint``generate_series` ( *`start`* `numeric`, *`stop`* `numeric` [, *`step`* `numeric` ] ) → `setof numeric`Generates a series of values from *`start`* to *`stop`*, with a step size of *`step`*. *`step`* defaults to 1. |
| `generate_series` ( *`start`* `timestamp`, *`stop`* `timestamp`, *`step`* `interval` ) → `setof timestamp``generate_series` ( *`start`* `timestamp with time zone`, *`stop`* `timestamp with time zone`, *`step`* `interval` ) → `setof timestamp with time zone`Generates a series of values from *`start`* to *`stop`*, with a step size of *`step`*. |
```
SELECT date_trunc('day', dd):: date
FROM generate_series
( '2007-02-01'::timestamp
, '2008-04-01'::timestamp
, '1 day'::interval) dd
;
SELECT * FROM generate_series(2,4);
SELECT * FROM generate_series(5,1,-2);
(开始,结束,步长): 小数参数在有些版本(<9.5)不支持。
SELECT * FROM generate_series(2.1,4.1,0.1);
```
生成步长固定的序列。
```
select generate_series(2,3),generate_series(2,3) ; 生成2条记录
select generate_series(2,3),generate_series(2,4) ; 生成6条记录
两个序列分别执行记录条数一致:返回记录数。 (左右简单拼接)
记录数不一致,返回记录记录数1*记录数2。 结果为笛卡尔积。
```
<file_sep>/python/base/list.md
```
使用 append() 添加元素
```
| Python 表达式 | 结果 | 描述 |
| :--------------------------- | :--------------------------- | :------------------- |
| len([1, 2, 3]) | 3 | 长度 |
| [1, 2, 3] + [4, 5, 6] | [1, 2, 3, 4, 5, 6] | 组合 |
| ['Hi!'] * 4 | ['Hi!', 'Hi!', 'Hi!', 'Hi!'] | 重复 |
| 3 in [1, 2, 3] | True | 元素是否存在于列表中 |
| for x in [1, 2, 3]: print x, | 1 2 3 | 迭代 |
| 序号 | 函数 |
| :--- | :----------------------------------------------------------- |
| 1 | [cmp(list1, list2)](https://www.runoob.com/python/att-list-cmp.html) 比较两个列表的元素 |
| 2 | [len(list)](https://www.runoob.com/python/att-list-len.html) 列表元素个数 |
| 3 | [max(list)](https://www.runoob.com/python/att-list-max.html) 返回列表元素最大值 |
| 4 | [min(list)](https://www.runoob.com/python/att-list-min.html) 返回列表元素最小值 |
| 5 | [list(seq)](https://www.runoob.com/python/att-list-list.html) 将元组转换为列表 |
| 1 | [list.append(obj)](https://www.runoob.com/python/att-list-append.html) 在列表末尾添加新的对象 |
| ---- | ------------------------------------------------------------ |
| 2 | [list.count(obj)](https://www.runoob.com/python/att-list-count.html) 统计某个元素在列表中出现的次数 |
| 3 | [list.extend(seq)](https://www.runoob.com/python/att-list-extend.html) 在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表) |
| 4 | [list.index(obj)](https://www.runoob.com/python/att-list-index.html) 从列表中找出某个值第一个匹配项的索引位置 |
| 5 | [list.insert(index, obj)](https://www.runoob.com/python/att-list-insert.html) 将对象插入列表 |
| 6 | [list.pop([index=-1\])](https://www.runoob.com/python/att-list-pop.html) 移除列表中的一个元素(默认最后一个元素),并且返回该元素的值 |
| 7 | [list.remove(obj)](https://www.runoob.com/python/att-list-remove.html) 移除列表中某个值的第一个匹配项 |
| 8 | [list.reverse()](https://www.runoob.com/python/att-list-reverse.html) 反向列表中元素 |
| 9 | [list.sort(cmp=None, key=None, reverse=False)](https://www.runoob.com/python/att-list-sort.html) 对原列表进行排序 |<file_sep>/linux/softwaremanager/yum/yum.md
```
列举源
yum repolist [all|enabled|disabled]
清理缓存
yum clean [ packages | metadata | expire-cache | rpmdb | plugins | all ]
创建缓存
yum makecache
查看所有仓库的可用软件包
yum list
yum list {available|updates|installed|extras|obsoletes} [glob_exp1] [...]
yum grouplist group1 [...]
groupinfo
groupremove group1 [...]
groupinstall group1 [...]
安装
yum install package1 [package2] [...]
reinstall
yum groupinstall group1 [...]
升级
yum update [package1] [package2] [...]
降级
yum downgrade package1 [package2] [...]
检查升级
yum check-update 检查有哪些包可以升级
卸载
yum remove package1 [package2] [...]
groupremove
yum info PACKAGE
yum search KEYWORD
yum provides KEYWORD
```
```
yum install yum-downloadonly
下载不安装(包含依赖)
yum install -y --downloadonly --downloaddir=<directory> <package>
yum reinstall -y --downloadonly --downloaddir=<directory> <package>
# yum install yum-utils
(不包含依赖,保存到当前目录)
yumdownloader <package-name>
```
<file_sep>/editor/vscode/maven.md
```json
{
"java.configuration.maven.userSettings":"maven配置文件.xml",
}
```
<file_sep>/html+css/css/css_常用属性设置.md
盒子模型
```
四值顺序:top right bottom left 按顺时针方向,则left被缺省,其值等于right
Margin(外边距) - 清除边框外的区域,外边距是透明的。(margin,margin-left/right/top/bottom)
Border(边框) - 围绕在内边距和内容外的边框。
(border: <厚度> <样式: border-style可单独设置> <颜色:border-color 可单独设置>)
(border-top/right/bottom/left-style)
border-style: 设置多个样式(遵守”四值顺序“)
Padding(内边距) - 清除内容周围的区域,内边距是透明的。(padding,padding-left/right/top/bottom)
Content(内容) - 盒子的内容,显示文本和图像 (width,height)
元素显示宽高占用:
总元素的宽度=宽度+左填充+右填充+左边框+右边框+左边距+右边距
总元素的高度=高度+顶部填充+底部填充+上边框+下边框+上边距+下边距
在设置元素宽为百分百时: 边距和边框将会导致出现横向滚动条。[即:百分比是相对container而言的。]
width
height
max-width
max-height
min-width
min-height
```
```
在元素上设置了 box-sizing: border-box; 则 padding(内边距) 和 border(边框) 也包含在 width 和 height 中
```
阴影
```
box-shadow
box-shadow: h-shadow v-shadow blur spread color inset;
h-shadow 必需的。水平阴影的位置。允许负值
v-shadow 必需的。垂直阴影的位置。允许负值
blur 可选。模糊距离
spread 可选。阴影的大小
color 可选。阴影的颜色。
inset 可选。从外层的阴影(开始时)改变阴影内侧阴影
```
背景:
```
background-color:
background-image:
```
文字:
```
color: 文字颜色
文本修饰
text-decoration: none; (a 标签去下划线)
none 默认。定义标准的文本。
underline 定义文本下的一条线。
overline 定义文本上的一条线。
line-through 定义穿过文本下的一条线。
blink 定义闪烁的文本。
inherit 规定应该从父元素继承 text-decoration 属性的值。
对齐
text-align: center/left/right/justify
"justify",每一行被展开为宽度相等,左,右外边距是对齐
大小写:
text-transform:uppercase/lowercase/capitalize
缩进
text-indent: (px)
color 设置文本颜色
direction 设置文本方向。
letter-spacing 设置字符间距
line-height 设置行高
text-align 对齐方式
text-decoration 向文本添加修饰
text-indent 缩进元素中文本的首行
text-shadow 设置文本阴影
text-transform 控制元素中的字母
unicode-bidi 设置或返回文本是否被重写
vertical-align 设置元素的垂直对齐
white-space 设置元素中空白的处理方式
word-spacing 设置字间距
```
弹性盒子:
```
display: flex; 作用在父容器上,子元素排列生效。 (父div设置,子div 平行排列)
```
圆角:
```
border-radius
四个值: (top-left 开始,顺时针)
三个值: 第一个值为左上角, 第二个值为右上角和左下角,第三个值为右下角
两个值: (top-left 开始,顺时针,交替生效)
一个值: 四个圆角值相同
弧度:
```
旋转
```
transform
-ms-transform:rotate(-8deg); /* IE 9 */
-webkit-transform:rotate(-8deg); /* Safari and Chrome */
transform:rotate(-8deg);
正数为顺时针旋转角度
```
调整元素尺寸:
```
resize: 指定一个元素是否应该由用户去调整大小
```
轮廓
```
outline (轮廓)是绘制于元素周围的一条线,位于边框边缘的外围,可起到突出元素的作用。
注释:轮廓线不会占据空间,也不一定是矩形。
outline 简写属性在一个声明中设置所有的轮廓属性。
可以按顺序设置如下属性:
outline-color
outline-style
outline-width
```
多列
```
column-count 列数
column-gap 指定列与列之间的间隙
column-rule-style 指定两列间边框的样式
column-rule-width 指定两列间边框的厚度
column-rule-color 指定两列间边框的颜色
column-rule 所有 column-rule-* 属性的简写
column-span 指定元素要跨越多少列
column-width 指定列的宽度
columns 设置 column-width 和 column-count 的简写
```
CSS3 动画
```
@keyframes 规定动画。
用百分比来规定变化发生的时间
用关键词 "from" 和 "to",等同于 0% 和 100%。
animation 所有动画属性的简写属性,除了 animation-play-state 属性。
animation-name 规定 @keyframes 动画的名称。
animation-duration 规定动画完成一个周期所花费的秒或毫秒。默认是 0。
animation-timing-function 规定动画的速度曲线。默认是 "ease"
animation-fill-mode 规定当动画不播放时(当动画完成时,或当动画有一个延迟未开始播放时),要应用到元素的样式。
animation-delay 规定动画何时开始。默认是 0。
animation-iteration-count 规定动画被播放的次数。默认是 1。
animation-direction 规定动画是否在下一周期逆向地播放。默认是 "normal"。
animation-play-state 规定动画是否正在运行或暂停。默认是 "running"。
```
浏览器样式前缀
```
-moz- :Firefox,GEcko引擎
-webkit-: Safari和Chrome,Webkit引擎
-o- :Opera(早期),Presto引擎,后改为Webkit引擎
-ms- :Internet Explorer,Trident引擎
```
<file_sep>/linux/arch/yaourt.md
yaourt
yaourt -S : 从aur 安装包
yaourt -Ss : 查询
yaourt -Sc :清除旧的包/缓存
yaourt -R :删除
yaourt -Su : 安装更新包
yaourt -Sy :获取数据库
yaourt -Cd :清除数据库
yaourt -Syu --aur :升级aur的包
yaourt -Si :列出包的信息
yaourt -Qdt : clean some useless pack
<file_sep>/sql/common/create_table.md
```
create table <tablename>(
字段 字段类型,
.....
primary key (字段,....)
);
```
<file_sep>/python/base/globals.md
```
globals().values()
获取某一个class 的所有继承着: 检测值是否为某个类的子类
inspect.isclass(xx)
issubclass(child_class, parrent_class)}
#globals()
#在当前作用域下,查看全局变量
包含:__builtins__,__file__,__doc__, 全局函数,class, module
```
<file_sep>/java/webcommon/0-servlet.md
参考: <https://www.cnblogs.com/whgk/p/6399262.html>
Servlet 接口
```
/*
* 1.实例化(使用构造方法创建对象)
* 2.初始化 执行init方法:
public void init(ServletConfig arg0) throws ServletException
* 3.服务 执行service方法 :
public void service(ServletRequest arg0, ServletResponse arg1)
* 4.销毁 执行destroy方法:
public void destroy()
*/
使用: 实现接口
```
GenericServlet 类 (是一个抽象类,实现了 Servlet 接口,并且对其中的 init() 和 destroy() 和 service() 提供了默认实现)
```
public void service(ServletRequest arg0, ServletResponse arg1)
使用: 重写方法
```
HttpServlet 类 (也是一个抽象类,它进一步继承并封装了 GenericServlet,使得使用更加简单方便,由于是扩展了 Http 的内容,所以还需要使用 HttpServletRequest 和 HttpServletResponse,这两个类分别是 ServletRequest 和 ServletResponse 的子类)
```
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
。。。。
使用: 重写方法
```
ServletConfig、ServletContext,request、response
```
ServletConfig:
获取途径:getServletConfig();
功能:
getServletName(); //获取servlet的名称,在web.xml中配置的servlet-name
getServletContext(); //获取ServletContext对象
getInitParameter(String); //获取在servlet中初始化参数的值。这里注意与全局初始化参数的区分。这个获取的只是在该servlet下的初始化参数
getInitParameterNames(); //获取在Servlet中所有初始化参数的名字,也就是key值,可以通过key值,来找到各个初始化参数的value值。返回的是枚举类型
```
```
ServletContext对象
获取途径:getServletContext(); 、getServletConfig().getServletContext();
功能:tomcat为每个web项目都创建一个ServletContext实例,tomcat在启动时创建,服务器关闭时销毁,在一个web项目中共享数据,管理web项目资源,为整个web配置公共信息等,通俗点讲,就是一个web项目,就存在一个ServletContext实例,每个Servlet读可以访问到它。
setAttribute(String name, Object obj) 在web项目范围内存放内容,以便让在web项目中所有的servlet读能访问到
getAttribute(String name) 通过指定名称获得内容
removeAttribute(String name) 通过指定名称移除内容
getInitPatameter(String name) //通过指定名称获取初始化值 <context-param>下<param-name> <param-value>配置的参数
getInitParameterNames() //获得枚举类型
getRealPath(string file_path) // 获取资源文件全路径 : getRealPath("/WEB-INF/web.xml")
获取web项目下指定资源的内容,返回的是字节输入流。InputStream getResourceAsStream(java.lang.String path)
getResourcePaths(java.lang.String path) 指定路径下的所有内容 getResourcePaths("/WEB-INF")
```
request、response
```
请求与响应:
request:
应用名称
url
资源路径
协议版本
协议
服务器机器域名或ip
客户端ip
服务器端口
请求头
参数
。。。。
请求转发:request.getRequestDispatcher(String path).forward(request,response); //path:转发后跳转的页面
response:
响应头:
状态
响应体
response.sendRedirect(string path) : 重定向
```
```
contextpath, servletpath, requesturi, realpath
http://localhost:8080/news/main/list.jsp
则执行下面向行代码后打印出如下结果:
1、 System.out.println(request.getContextPath());
打印结果:/news
2、System.out.println(request.getServletPath());
打印结果:/main/list.jsp
3、 System.out.println(request.getRequestURI());
打印结果:/news/main/list.jsp
4、 System.out.println(request.getRealPath("/"));
打印结果: 。。。。。。\webapps\news\test
```
servlet 生命周期:
```
1.被创建:执行init方法,只执行一次: 第一次被访问时,Servlet被创建
2.提供服务:执行service方法,执行多次
3.被销毁:当Servlet服务器正常关闭时,执行destroy方法,只执行一次
```
<file_sep>/linux/softwaremanager/yum/epel.md
## EPEL
CentOS 用户可以直接通过 yum install epel-release 安装并启用 EPEL 源。如果不行,则可以通过 RPM 安装
```
CentOS7
rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-7.noarch.rpm
CentOS6
rpm -ivh https://dl.fedoraproject.org/pub/epel/epel-release-latest-6.noarch.rpm
```
<file_sep>/testting/postman/0_install.md
下载
```
wget https://dl.pstmn.io/download/latest/linux64 -O postman-linux-x64.tar.gz
```
<file_sep>/linux/softs/cockpit/index.md
```
linux web 系统监控工具
```
<file_sep>/python/base/generator_iter.md
```
generator使用场景:
1 当我们需要一个公用的,按需生成的数据
2 某个事情执行一部分,另一部分在某个事件发生后再执行下一部分,实现异步。
注意事项:
1 yield from generator_obj 本质上类似于 for item in generator_obj: yield item
2 generator函数中允许使用return,但是return 后不允许有返回值
```
yield:
```
当调用generator的next方法,generator会执行到yield 表达式处,返回yield表达式的内容,然后暂停(挂起)在这个地方。
按需生成并“返回”结果,而不是一次性产生所有的返回值。
Yield是不能嵌套的
python3.3中 可以使用yield from
```
迭代器
```
iter() 函数用来生成。
iter(object[, sentinel])
object -- 支持迭代的集合对象。
sentinel -- 如果传递了第二个参数,则参数 object 必须是一个可调用的对象(如,函数),此时,iter 创建了一个迭代器对象,每次调用这个迭代器对象的__next__()方法时,都会调用 object。
```
```
把一个类作为一个迭代器使用需要在类中实现两个方法 __iter__() 与 __next__() 。
__iter__() 方法返回一个特殊的迭代器对象, 这个迭代器对象实现了 __next__() 方法并通过 StopIteration 异常标识迭代的完成。
__next__() 方法(python2中实现 next(self) 方法)会返回下一个迭代器对象。
```
```
next(iterator[, default])
iterator -- 可迭代对象
default -- 可选,用于设置在没有下一个元素时返回该默认值,如果不设置,又没有下一个元素则会触发 StopIteration 异常。
```
<file_sep>/python/install_on_windows.md
```
embed 版Python和pip
```
1. 解压 并配置path
2. 打开python路径中pythonxx._pth, 去掉`import site`前的注释
3. 安装pip,setuptools (2,3 步骤可交换,先做3,需改setup.py)<file_sep>/python/setup_py.md
参考: <https://blog.csdn.net/caiguoxiong0101/article/details/50285279>
setup.py :
```
python setup.py --help-commands
```
打包/安装
1. 编写setup.py
2. 打包
```
python setup.py -q bdist_egg egg打包
python setup.py -q bdist_wininst 打包为exe
python setup.py install 直接安装到python site-packages 目录
```
egg安装方式:
(1) easy_install xx.egg
(2)将 xxx.egg`包直接放到虚拟工作目录的`lib > site-packages`路径下,并在`site-packages/easy-install.pth 文件添加egg包路径引用
开发模式: develop( install package in 'development mode')
python setup.py develop : 将开发环境链接到 site-packages 列表。<file_sep>/linux/softs/remmina.md
remmina: 远程连接管理工具
- 支持RDP,VNC,NX,XDMCP和SSH。
- rdp 需安装freerdp
问题: remmina rdp只能连一次,第二次连不上
```
将rdp 连接高级配置中的安全改为 TLS
```
<file_sep>/js/questions_mark/x-invalid-end-tag.md
Parsing error: x-invalid-end-tag
参考:https://blog.csdn.net/zy13608089849/article/details/79545738
解决方案
```
修改配置文件,忽略该项检查:
根目录下 - .eslintrc.js - rules
```
添加一行:
```
"vue/no-parsing-error": [2, { "x-invalid-end-tag": false }]
```
<file_sep>/java/some_lib/ehcache.md
maven
```xml
<!-- https://mvnrepository.com/artifact/net.sf.ehcache/ehcache -->
<dependency>
<groupId>net.sf.ehcache</groupId>
<artifactId>ehcache</artifactId>
<version>2.10.6</version>
</dependency>
<!-- slf4j-nop: resolve error: SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-nop</artifactId>
<version>1.7.2</version>
</dependency>
```
ehcache.xml (位于class_path 下)
```xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd">
<!-- 磁盘缓存位置 -->
<diskStore path="java.io.tmpdir/ehcache"/>
<!-- <diskStore path="/tmp/ehcache"/> -->
<!-- 默认缓存 -->
<!-- <defaultCache maxEntriesLocalHeap="10000" eternal="false" timeToIdleSeconds="120" timeToLiveSeconds="120" maxEntriesLocalDisk="10000000" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/> -->
<!-- helloworld缓存 -->
<!-- <cache name="helloworld" maxElementsInMemory="1000" eternal="false" timeToIdleSeconds="5" timeToLiveSeconds="5" overflowToDisk="false" memoryStoreEvictionPolicy="LRU"/> -->
<!-- <diskStore path="/tmp"/> -->
<defaultCache maxElementsInMemory="10000" eternal="false" timeToIdleSeconds="60" timeToLiveSeconds="60" overflowToDisk="true" maxElementsOnDisk="1000000" diskPersistent="false" diskExpiryThreadIntervalSeconds="120" memoryStoreEvictionPolicy="LRU"/>
<cache name="myCache" eternal="false" maxElementsInMemory="10000" maxElementsOnDisk="1000000" timeToIdleSeconds="120" timeToLiveSeconds="10" overflowToDisk="true" diskPersistent="false" diskSpoolBufferSizeMB="100" memoryStoreEvictionPolicy="LFU"/>
<cache name="datasetCache" eternal="false" maxElementsInMemory="10000" maxElementsOnDisk="1000000" timeToIdleSeconds="120" timeToLiveSeconds="10" overflowToDisk="true" diskPersistent="false" diskSpoolBufferSizeMB="100" memoryStoreEvictionPolicy="LFU"/>
</ehcache>
```
java 使用:
```java
// Create a cache manager
CacheManager cacheManager = new CacheManager();
// get the cache called "datasetCache"
Cache cache = cacheManager.getCache("datasetCache");
// create a key to map the data to
String key = "greeting";
// Create a data element
Element putGreeting = new Element(key, "Hello, World!");
// Put the element into the data store
cache.put(putGreeting);
// Retrieve the data element
Element getGreeting = cache.get(key);
// Print the value
System.out.println(getGreeting.getObjectValue());
```
spring 使用:
参考:
<https://blog.csdn.net/feiyangtianyao/article/details/90692021>
<https://www.cnblogs.com/Jimc/archive/2018/09/21/9685350.html>
```xml
<bean id="ehcache"
class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
<property name="configLocation" value="classpath:ehcache.xml" />
</bean>
<bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
<property name="cacheManager" ref="ehcache" />
</bean>
<cache:annotation-driven cache-manager="cacheManager" />
```
<file_sep>/python/solutions/lib_not_work.md
```
cx_Oracle:
install "Oracle Instant Client" first
install "cx_Oracle" second
Add Oracle 18, 12 or 11.2 client libraries to your operating system library search path such as PATH on Windows or LD_LIBRARY_PATH on Linux. On macOS move the files to ~/lib or /usr/local/lib.
"Oracle Instant Client" download
https://www.oracle.com/technetwork/database/database-technologies/instant-client/downloads/index.html
export LD_LIBRARY_PATH=?/oracle-client-?:$LD_LIBRARY_PATH
```
<file_sep>/linux/softs/ssh/cmd_ssh.md
ssh
usage: ssh [-1246AaCfGgKkMNnqsTtVvXxYy] [-b bind_address] [-c cipher_spec]
[-D [bind_address:]port] [-E log_file] [-e escape_char]
[-F configfile] [-I pkcs11] [-i identity_file] [-L address]
[-l login_name] [-m mac_spec] [-O ctl_cmd] [-o option] [-p port]
[-Q query_option] [-R address] [-S ctl_path] [-W host:port]
[-w local_tun[:remote_tun]] [user@]hostname [command]
-1:强制使用ssh协议版本1;
-2:强制使用ssh协议版本2;
-4:强制使用IPv4地址;
-6:强制使用IPv6地址;
-A:开启认证代理连接转发功能;
-a:关闭认证代理连接转发功能;
-b:使用本机指定地址作为对应连接的源ip地址;
-C:请求压缩所有数据;
-F:指定ssh指令的配置文件;
-f:后台执行ssh指令;
-g:允许远程主机连接主机的转发端口;
-i:指定身份文件;
-l:指定连接远程服务器登录用户名;
-N:不执行远程指令;
-o:指定配置选项;
-p:指定远程服务器上的端口;
-q:静默模式;
-X:开启X11转发功能;
-x:关闭X11转发功能;
-y:开启信任X11转发功能。<file_sep>/linux/common/xdg-user-dirs.md
用户目录指位于 `$HOME` 下的一系列常用目录,例如 `Documents`,`Downloads`,`Music`,还有 `Desktop`。用户目录会在文件管理器中显示为不同的图标,且被多种应用程序所参照。可以使用 [xdg-user-dirs](https://www.archlinux.org/packages/?name=xdg-user-dirs) 自动生成这些目录
参考: https://wiki.archlinux.org/index.php/XDG_user_directories_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)<file_sep>/linux/shell_script/string.md
参考:
<https://www.cnblogs.com/chengmo/archive/2010/10/02/1841355.html>
<https://blog.csdn.net/lizhidefengzi/article/details/76762059>
字符串替换
```
${变量/查找/替换值}
```
<file_sep>/docker/1_run.md
运行daocker
```bash
# docker run -d -P training/webapp python app.py
# docker exec -it <container_id> /bin/bash
# docker run -d -p 5001:5000 training/webapp python app.py
-p 指定端口映射 : -p <本地端口>:<docer 端口>
-d 后台运行
# docker run hello-world
命令运行完成后daocker container 退出.
```
docker run 指定镜像时不指定tag 默认为 latest
docker -v : Docker容器启动的时候,如果要挂载宿主机的一个目录,可以用-v参数指定。冒号":"前面的目录是宿主机目录,后面的目录是容器内目录。
参考:<https://blog.csdn.net/hnmpf/article/details/80924494>
```bash
# docker run -it -v /test:/soft -v /data:/data centos:tag /bin/bash
需要挂载多个目录 多次使用-v 参数
1.容器目录不可以为相对路径
2.宿主机目录如果不存在,则会自动生成
3.宿主机的目录如果为相对路径:相对路径指的是/var/lib/docker/volumes/,与宿主机的当前目录无关
4.-v指定一个目录 docker run -it -v /test2 centos /bin/bash
在/var/lib/docker/volumes 下随机生成的一个目录名
5. 在容器内修改了目录的属主和属组,对应的挂载点也会变化(用户uuid 与宿主机uuid对应的用户相关)
6. 容器销毁了,宿主机上生成的挂载目录不会消失
7.挂载宿主机已存在目录后,在容器内对其进行操作,报“Permission denied”。
(1) 关闭selinux
(2) 以特权方式启动容器 ,指定--privileged参数,
# docker run -it --privileged=true
```
docker inspect container_names
"Mounts":{} 显示磁盘挂载<file_sep>/linux/softwaremanager/apt/apt.md
```
apt-cache命令:
apt-cache主要用于搜索包。
apt-cache search package 搜索包
apt-cache show package 获取包的相关信息,如说明、大小、版本等
apt-cache showpkg package 显示软件包信息,包括包的依赖关系,包的提供者,
apt-cache pkgnames 打印软件包列表中所有包的名字
apt-cache dumpavail 打印软件包列表中所有包的简介信息
apt-cache depends package 了解使用依赖
apt-cache rdepends package 是查看该包被哪些包依赖
```
```
已安装的软件
apt list --installed
dpkg -l
```
<file_sep>/golang/proxy.md
```
export GOPROXY=https://goproxy.io
export GO111MODULE=on
export GOPROXY="https://athens.azurefd.net"
export GOPROXY=https://goproxy.cn
```
<file_sep>/linux/devops/sonarqube/3_usage.md
浏览器访问端口 9000 (9000 未默认端口)
```
admin 默认密码 <PASSWORD>
```
<file_sep>/python/class.py
class Test(object):
def instancefun(self): #实例方法
print("instancefun")
print(self)
@classmethod
def classfun(cls): # 类方法
print("class fun")
print(cls)
@staticmethod
def staticfun(): # 静态方法
print("staticfun")
# other 方法
def function():
print("func")
t=Test()
# 实例对象调用实例方法
print t.instancefun
t.instancefun()
# 类调用类方法
Test.classfun()
# t.function() # 不能调用
Test.function() # 可以调用,类似static method
Test.staticfun() # 类调用静态方法
t.staticfun() #实例调用静态方法
t.classfun() #实例调用类方法
Test.instancefun(t) # 类调用实例方法,带实例参数
Test.instancefun(Test) # 类调用实例方法,带类参数
'''
类方法需要@ classmethod 修饰并且有个隐藏参数 cls,
实例方法必须有个参数 self,
静态方法必须有 @staticmethod修饰,
类和实例都可以访问静态方法,
实例可以访问实例方法也可以访问类方法,
类可以访问类方法也可以访问实例方法,访问实例方法必须要带参数 self, 可以理解为类其实也是一个实例,类访问实例方法不带参数会报错的.
类本身可以访问函数,实例却不行.
'''
'''
###################×分×割×线×######################################################
'''
# 实例方法、类方法、静态方法
class MyClass(object):
class_name = "MyClass" # 类属性, 三种方法都能调用
def __init__(self):
self.instance_name = "instance_name" # 实例属性, 只能被实例方法调用
self.class_name = "instance_class_name"
def get_class_name_instancemethod(self): # 实例方法, 只能通过实例调用
# 实例方法可以访问类属性、实例属性
return MyClass.class_name
@classmethod
def get_class_name_classmethod(cls): # 类方法, 可通过类名.方法名直接调用
# 类方法可以访问类属性,不能访问实例属性
return cls.class_name
@staticmethod
def get_class_name_staticmethod(): # 静态方法, 可通过类名.方法名直接调用
# 静态方法可以访问类属性,不能访问实例属性
return MyClass.class_name
def instance_visit_class_attribute(self):
# 实例属性与类属性重名时,self.class_name优先访问实例属性
print "实例属性与类属性重名时,优先访问实例属性"
print "self.class_name:", self.class_name
print "MyClass.name:", MyClass.class_name
if __name__ == "__main__":
MyClass.class_name = "MyClassNew"
intance_class = MyClass()
print "instance method:", intance_class.get_class_name_instancemethod()
print "class method:", MyClass.get_class_name_classmethod()
print "static method:", MyClass.get_class_name_staticmethod()
intance_class.instance_visit_class_attribute()
'''
result:
instance method: MyClassNew
class method: MyClassNew
static method: MyClassNew
实例属性与类属性重名时,优先访问实例属性
self.class_name: instance_class_name
MyClass.name: MyClassNew
'''<file_sep>/linux/solutions/arch_u盘.md
arch 不识别u盘:
```
手动加载内核模块: usb_storage
# modprobe usb_storage
#uas 模块可不加载
# modprobe uas
重新插入u盘
---------------------------------------------------------------------------------
卸载内核模块:
# rmmod usb_storage
rmmod: ERROR: Module usb_storage is in use by: uas
# rmmod uas
# rmmod usb_storage
```
<file_sep>/sql/mysql/mysql_community.md
8.x--------------
/var/log/mysqld.log 中查找初始密码
GRANT ALL PRIVILEGES ON *.* TO root@"%" IDENTIFIED BY "root12345";
ALTER USER 'root'@'localhost' IDENTIFIED BY 'root@123456';
5.6 ---------------------
set password=password('<PASSWORD>');
flush privileges;
<file_sep>/linux/common/sed.md
# replace
```
sed -i "s#the_string_to_be_replace#the_repalce_string#g" file_to_be_replace
```
```
#!/bin/sh
#
# replace python env
#
cd `dirname $0`
CURRENT_DIR=$(pwd)
REPLACE_FROM='/data/github/django/python3/bin/python3.6'
REPLACE_TO='/soft/python3/bin/python3'
IGNORE_FILE='replace.sh'
grep "$You can't use 'macro parameter character #' in math modeREPLACE_FROM" . -lR|grep -v replace.sh|xargs sed -i "s#$REPLACE_FROM#$REPLACE_TO#g"
```
http://www.runoob.com/linux/linux-comm-sed.html
语法
```
sed [-hnV][-e<script>][-f<script文件>][文本文件]
```
参数说明:
-e<script>或--expression=<script> 以选项中指定的script来处理输入的文本文件。
-f<script文件>或--file=<script文件> 以选项中指定的script文件来处理输入的文本文件。
-h或--help 显示帮助。
-n或--quiet或--silent 仅显示script处理后的结果。
-V或--version 显示版本信息。
动作说明:
a :新增, a 的后面可以接字串,而这些字串会在新的一行出现(目前的下一行)~
c :取代, c 的后面可以接字串,这些字串可以取代 n1,n2 之间的行!
d :删除,因为是删除啊,所以 d 后面通常不接任何咚咚;
i :插入, i 的后面可以接字串,而这些字串会在新的一行出现(目前的上一行);
p :打印,亦即将某个选择的数据印出。通常 p 会与参数 sed -n 一起运行~
s :取代,可以直接进行取代的工作哩!通常这个 s 的动作可以搭配正规表示法!例如 1,20s/old/new/g 就是啦
----------------------------------------------------------------------------------
```
/tmp $ cat testfile
HELLO LINUX!
Linux is a free unix-type opterating system.
This is a linux testfile!
Linux test
/tmp $ sed -e 4a\newline testfile
HELLO LINUX!
Linux is a free unix-type opterating system.
This is a linux testfile!
Linux test
newline
/tmp $ cat testfile
HELLO LINUX!
Linux is a free unix-type opterating system.
This is a linux testfile!
Linux test
```
did not modify the file
----------------------------------------------------------------------------------
```
nl /etc/passwd | sed '2,5d' # 将 /etc/passwd 的内容列出并且列印行号,同时,请将第 2~5 行删除!
nl /etc/passwd | sed '2d' # 将 /etc/passwd 的内容列出并且列印行号,同时,请将第 2 行删除!
nl /etc/passwd | sed '3,$d' #删除第 3 到最后一行
nl /etc/passwd | sed '2a drink tea' # 在第二行后(亦即是加在第三行)加上『drink tea?』字样!
nl /etc/passwd | sed '2i drink tea' # 在第二行前 加上『drink tea?』字样!
nl /etc/passwd | sed '2a Drink tea or ......\
> drink beer ?' # 第二行后面加入两行字,例如『Drink tea or .....』与『drink beer?』
nl /etc/passwd | sed '2,5c No 2-5 number' # 将第2-5行的内容取代成为『No 2-5 number』
nl /etc/passwd | sed -n '5,7p' # 仅列出 /etc/passwd 文件内的第 5-7 行
nl /etc/passwd | sed '/root/p' # 搜索 /etc/passwd有root关键字的行(如果root找到,除了输出所有行,还会输出匹配行。)
nl /etc/passwd | sed -n '/root/p' # 搜索 /etc/passwd有root关键字的行(使用-n的时候将只打印包含模板的行。)
nl /etc/passwd | sed '/root/d' # 删除/etc/passwd所有包含root的行,其他行输出
nl /etc/passwd | sed -n '/bash/{s/bash/blueshell/;p;q}'
```
### 搜索/etc/passwd,找到root对应的行,执行后面花括号中的一组命令,每个命令之间用分号分隔,这里把bash替换为blueshell,再输出这行:
sed 's/要被取代的字串/新的字串/g'
/sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g'
eth0 Link encap:Ethernet HWaddr 00:90:CC:A6:34:84
inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
inet6 addr: fe80::290:ccff:fea6:3484/64 Scope:Link
UP BROADCAST RUNNING MULTICAST MTU:1500 Metric:1
.....(以下省略).....
=>
inet addr:192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
=>
192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
/sbin/ifconfig eth0 | grep 'inet addr' | sed 's/^.*addr://g' | sed 's/Bcast.*$//g'
192.168.1.100 Bcast:192.168.1.255 Mask:255.255.255.0
=>
192.168.1.100
### 一条sed命令,删除/etc/passwd第三行到末尾的数据,并把bash替换为blueshell
nl /etc/passwd | sed -e '3,$d' -e 's/bash/blueshell/'
### 利用 sed 将 regular_express.txt 内每一行结尾若为 . 则换成 !
sed -i 's/\.$/\!/g' regular_express.txt (直接修改文件内容(危险动作))
利用 sed 直接在 regular_express.txt 最后一行加入『# This is a test』
sed -i '$a # This is a test' regular_express.txt
----------------------------------------------------------------------------------
https://www.cnblogs.com/jiangshitong/p/6607552.html
https://www.cnblogs.com/-zyj/p/5763303.html
----------------------------------------------------------------------------------
----------------------------------------------------------------------------------
替换一个目录下所有文件中的指定字符串
```
grep old_str . -R|awk '{print $1}'| awk -F ':' '{print $1}'|xargs sed -i "s/old_str/new_str/g"
参考: https://blog.csdn.net/u011068702/article/details/91422409
比如在目录 /root/chenyu/cy/下,把包含文本/A/B C替换成文本E=F
grep -Rl /A/B\ C /root/chenyu/c* | xargs sed -i 's#/A/B\ C#E=F#g'
替换回来
grep -Rl E=F /root/chenyu/c* | xargs sed -i 's#E=F#/A/B\ C#g'
注: sed - i 's/old/new/g' /为分割符号,可以使用其他符号替换(替换内容中特殊字符需要使用反斜线”\”进行转义)。
参考: https://www.cnblogs.com/linux-wangkun/p/5745584.html
```
----------------------------------------------------------------------------------
```
字符串替换
_src="src"
_des="desc"
sed -i s?"$_src"?"$_des"?g <filename>
```
```
文件开头插入
sed -i '1i\This is the beginning' file
sed -i '1i\This is the beginning\nThis is the second' file
```
<file_sep>/linux/ubuntu/ubuntu_19.md
安装时选最小化安装,且不下载第三方。
配置root密码:
```
sudo passwd root
输入密码并确认。
```
配置源:
```
# cd /etc/apt/
# cp -p sources.list sources.list.bak
# vi sources.list
```
可用源:
```
#阿里云源
deb http://mirrors.aliyun.com/ubuntu/ disco main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ disco main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ disco-security main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ disco-security main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ disco-updates main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ disco-updates main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ disco-backports main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ disco-backports main restricted universe multiverse
deb http://mirrors.aliyun.com/ubuntu/ disco-proposed main restricted universe multiverse
deb-src http://mirrors.aliyun.com/ubuntu/ disco-proposed main restricted universe multiverse
#中科大源
deb https://mirrors.ustc.edu.cn/ubuntu/ disco main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ disco main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ disco-updates main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ disco-updates main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ disco-backports main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ disco-backports main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ disco-security main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ disco-security main restricted universe multiverse
deb https://mirrors.ustc.edu.cn/ubuntu/ disco-proposed main restricted universe multiverse
deb-src https://mirrors.ustc.edu.cn/ubuntu/ disco-proposed main restricted universe multiverse
#163源
deb http://mirrors.163.com/ubuntu/ disco main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ disco-security main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ disco-updates main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ disco-proposed main restricted universe multiverse
deb http://mirrors.163.com/ubuntu/ disco-backports main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ disco main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ disco-security main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ disco-updates main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ disco-proposed main restricted universe multiverse
deb-src http://mirrors.163.com/ubuntu/ disco-backports main restricted universe multiverse
#清华源
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-updates main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-updates main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-backports main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-backports main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-security main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-security main restricted universe multiverse
deb https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-proposed main restricted universe multiverse
deb-src https://mirrors.tuna.tsinghua.edu.cn/ubuntu/ disco-proposed main restricted universe multiverse
```
更新系统:
```
# apt-get update
# apt-get upgrade
然后等待安装更新
卸载多余的包
# apt autoremove
```
安装常用软件:
```
net-tools
vim
```
fcitx
```
sudo apt-get install fcitx-bin
sudo apt-get install fcitx-table
安装完fcixt后在“设置 > 区域和语言 > 管理已安装的语言 > 键盘输入法系统”处把它替换为fcitx,然后重启Ubuntu
卸载iBus
sudo apt-get purge ibus
sudo apt-get autoremove
```
启动器:
```
# apt-get install lightdm
# dpkg-reconfigure lightdm
# dpkg-reconfigure gdm3
lightdm 登录界面鼠标卡。
安装lightdm 后切换回gdm3报错:(忽略重启即可)
gdm.service is not active, cannot reload.
invoke-rc.d: initscript gdm3, action "reload" failed.
```
<file_sep>/linux/arch/clean.md
```
https://qsctech-sange.github.io/arch-linux-clean.html#%E6%B8%85%E7%90%86%E5%AE%89%E8%A3%85%E5%8C%85%E7%BC%93%E5%AD%98
sudo pacman -Scc
sudo pacman -Rns $(pacman -Qtdq) [慎用]
journalctl --vacuum-size=50M
```
<file_sep>/linux/common/empty_file_context.md
```shell
清空文件夹下所有文件内容
ls | xargs truncate -s 0
```
``` stylus
truncate
相关命令:暂无相关命令
用法:truncate 选项... 文件...
将文件缩减或扩展至指定大小。
如果指定文件不存在则创建。
如果指定文件超出指定大小则超出的数据将丢失。
如果指定文件小于指定大小则用0 补足。
长选项必须使用的参数对于短选项时也是必需使用的。
-c, --no-create 不创建文件
-o, --io-blocks 将SIZE 视为IO 块数而不使用字节数
-r, --reference=文件 使用此文件的大小
-s, --size=大小 使用此大小
--help 显示此帮助信息并退出
--version 显示版本信息并退出
SIZE 可以是一个可选的整数,后面跟着以下单位中的一个:
KB 1000,K 1024,MB 1000*1000,M 1024*1024,还有 G、T、P、E、Z、Y。
指定大小也可使用以下前缀修饰:
"+" 增加,"-" 减少,"<" 至多,">" 至少,
"/" 小于等于原尺寸数字的指定数字的最小倍数,"%" 大于等于原尺寸数字的指定数字的最大倍数。
译者注:当输入值为m,参考值为n 时,
"/" 运算的数学计算式为 m / n * n;
"%" 运算的数学计算式为( m + n - 1 ) / n * n
请注意-r 和-s 是互斥的选项。
```
<file_sep>/linux/common/xargs.md
参考:http://man.linuxde.net/xargs
```
xargs命令是给其他命令传递参数的一个过滤器,也是组合多个命令的一个工具。它擅长将标准输入数据转换成命令行参数,xargs能够处理管道或者stdin并将其转换成特定命令的命令参数。xargs也可以将单行或多行文本输入转换为其他格式,例如多行变单行,单行变多行。xargs的默认命令是echo,空格是默认定界符。这意味着通过管道传递给xargs的输入将会包含换行和空白,不过通过xargs的处理,换行和空白将被空格取代。xargs是构建单行命令的重要组件之一。
xargs命令用法
xargs用作替换工具,读取输入数据重新格式化后输出。
cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
多行输入单行输出:
cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
-n选项多行输出:
cat test.txt | xargs -n3
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
-d选项可以自定义一个定界符:
echo "nameXnameXnameXname" | xargs -dX
name name name name
xargs的一个选项-I,使用-I指定一个替换字符串{},这个字符串在xargs扩展时会被替换掉,当-I与xargs结合使用,每一个参数命令都会被执行一次:
cat arg.txt | xargs -I {} ./sk.sh -p {} -l
当前位置:首页 » 软件·打印·开发·工具 » xargs
xargs命令
常用工具命令
文章顶部广告
《Linux就该这么学》是一本基于最新Linux系统编写的入门必读书籍,内容面向零基础读者,由浅入深渐进式教学,销量保持国内第一,年销售量预期超过10万本。点此免费在线阅读。
xargs命令是给其他命令传递参数的一个过滤器,也是组合多个命令的一个工具。它擅长将标准输入数据转换成命令行参数,xargs能够处理管道或者stdin并将其转换成特定命令的命令参数。xargs也可以将单行或多行文本输入转换为其他格式,例如多行变单行,单行变多行。xargs的默认命令是echo,空格是默认定界符。这意味着通过管道传递给xargs的输入将会包含换行和空白,不过通过xargs的处理,换行和空白将被空格取代。xargs是构建单行命令的重要组件之一。
xargs命令用法
xargs用作替换工具,读取输入数据重新格式化后输出。
定义一个测试文件,内有多行文本数据:
cat test.txt
a b c d e f g
h i j k l m n
o p q
r s t
u v w x y z
多行输入单行输出:
cat test.txt | xargs
a b c d e f g h i j k l m n o p q r s t u v w x y z
-n选项多行输出:
cat test.txt | xargs -n3
a b c
d e f
g h i
j k l
m n o
p q r
s t u
v w x
y z
-d选项可以自定义一个定界符:
echo "nameXnameXnameXname" | xargs -dX
name name name name
结合-n选项使用:
echo "nameXnameXnameXname" | xargs -dX -n2
name name
name name
读取stdin,将格式化后的参数传递给命令
假设一个命令为 sk.sh 和一个保存参数的文件arg.txt:
#!/bin/bash
#sk.sh命令内容,打印出所有参数。
echo $*
arg.txt文件内容:
cat arg.txt
aaa
bbb
ccc
xargs的一个选项-I,使用-I指定一个替换字符串{},这个字符串在xargs扩展时会被替换掉,当-I与xargs结合使用,每一个参数命令都会被执行一次:
复制所有图片文件到 /data/images 目录下:
ls *.jpg | xargs -n1 -I cp {} /data/images
xargs结合find使用
用rm 删除太多的文件时候,可能得到一个错误信息:/bin/rm Argument list too long. 用xargs去避免这个问题:
find . -type f -name "*.log" -print0 | xargs -0 rm -f
xargs -0将\0作为定界符。
```<file_sep>/python/pip.md
使用国内源:参考 https://www.cnblogs.com/sunnydou/p/5801760.html
阿里云 http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/
pip install <packages> -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
如果想配置成默认的源,方法如下:
需要创建或修改配置文件(一般都是创建),
linux的文件在~/.pip/pip.conf,
windows在%HOMEPATH%\pip\pip.ini),
修改内容为:
```
[global]
index-url = http://pypi.douban.com/simple
[install]
trusted-host=pypi.douban.com
```
这样在使用pip来安装时,会默认调用该镜像。
<https://pypi.tuna.tsinghua.edu.cn/simple/pip/> pip 下载地址
<https://pypi.tuna.tsinghua.edu.cn/simple/setuptools/> setup-tools 下载地址
```
pip freeze > requirements.txt
pip install -r requirements.txt
```
[“fatal error: Python.h: No such file or directory”](https://www.cnblogs.com/eating-gourd/p/8578007.html) : 安装python-dev
<file_sep>/linux/common/禁用程序联网.md
```
http://tieba.baidu.com/p/6312579594
You create a group that is never allowed to use the internet and start the program as a member of this group.
1.Create a group no-internet. Do not join this group
sudo addgroup no-internet
2.Add a rule to iptables that prevents all processes belonging to the group no-internet from using the network (use ip6tables to also prevent IPv6 traffic)
sudo iptables -A OUTPUT -m owner --gid-owner no-internet -j DROP
3.Execute sudo -g no-internet YOURCOMMAND instead of YOURCOMMAND.
You can easily write a wrapper script that uses sudo for you. You can get rid of the password prompt by adding
%sudo ALL=(:no-internet) NOPASSWD: ALL
or, something similar with sudo visudo
Use the iptables-save and iptables-restore to persist firewall rules.
```
<http://blog.chinaunix.net/uid-23849526-id-160293.html>
<file_sep>/linux/softs/nginx/负载均衡.md
nginx 配置目录:/etc/nginx/
/etc/nginx $ tree
.
├── conf.d
├── fastcgi.conf
├── fastcgi_params
├── koi-utf
├── koi-win
├── mime.types
├── nginx.conf
├── proxy_params
├── scgi_params
├── sites-available
│ ├── default
│ └── default.back
├── sites-enabled
│ └── default -> /etc/nginx/sites-available/default
├── snippets
│ ├── fastcgi-php.conf
│ └── snakeoil.conf
├── uwsgi_params
└── win-utf
4 directories, 15 files
nginx.conf: nginx 基础配置
http:{
include /etc/nginx/conf.d/*.conf; # 网站配置文件
include /etc/nginx/sites-enabled/*; # 网站配置文件
}
配置 sites-available/default
负载均衡配置:(session 需要共享: 否则资源访可能未授权。)
upstream zabbixserver {
server 192.168.4.1:80 weight=3;
# server ip:端口;
}
server {
listen 8080;
listen [::]:8080;
server_name localhost ip1 ip2;
charset utf-8;
location / {
proxy_pass http://zabbixserver;
}
}
<file_sep>/linux/driver.md
查看硬件:
显示当前主机的所有PCI总线信息,以及所有已连接的PCI设备信息。
lspci -kv
```
lspci(选项)
-n:以数字方式显示PCI厂商和设备代码;
-t:以树状结构显示PCI设备的层次关系,包括所有的总线、桥、设备以及它们之间的联接;
-b:以总线为中心的视图;
-d:仅显示给定厂商和设备的信息;
-s:仅显示指定总线、插槽上的设备和设备上的功能块信息;
-i:指定PCI编号列表文件,而不使用默认的文件;
-m:以机器可读方式显示PCI设备信息。
```
查看显卡使用情况有一个方法(Pwr表示正在使用,DynOff表示没使用):
sudo cat /sys/kernel/debug/vgaswitcheroo/switch
查看内核模块:
lsmod<file_sep>/golang/mod_src.md
```
https://www.cnblogs.com/saolv/p/12081899.html
```
```
在go mod初始化的项目目录下执行go get package,会将package下载到$GOPATH/pkg目录下安装
非go mod项目,执行go get package,只是将package下载到$GOPATH/src/...目录下安装
export GO111MODULE=off ,后执行 go get package,将package下载到$GOPATH/src/...目录下
```
非go mod 项目: 从 $GOPATH/src 下查找依赖。<file_sep>/golang/struct.md
```
/*匿名结构体*/
emp := struct{
name, address string
height, weight float64
}{
name:"eagle", address:"guangdong", height:172.0, weight:75.3,
}
// 备注:这里的最后一个逗号(,)必须要有,否则会报错
```
```
/*匿名结构体数组*/
emp := []struct{
name, address string
height, weight float64
}{
{name:"eagle", address:"guangdong", height:172.0, weight:75.3,},
}
// 备注:结尾逗号(,)必须要有,否则会报错
```
```
/*声明结构体*/
type employee struct{
name,address string
height,weight float64
}
/*初始化结构体,并赋给变量emp*/
emp := employee{name:"eagle", address:"guangdong", height:172.0, weight:75.3,}
```
```
/*嵌套结构体*/
/*声明figure结构体*/
type figure struct {
height, weight float64
}
/*声明human结构体,里面嵌套figure结构体*/
type human struct {
name, address string
figure
}
man := human{name:"eagle", address:"guangdong", figure:figure{height:172, weight:75.3}}
```
<file_sep>/python/base/threads.md
参考:
<https://www.runoob.com/python/python-multithreading.html>
<https://docs.python.org/zh-cn/3.7/library/threading.html
```
方法1:
thread.start_new_thread ( function, args[, kwargs] )
方法二:
类继承 threading.Thread ,并重写 run 函数
threading.Thread(target=xxx,ars[,...]).start
########################################################################################
线程锁:
class threading.Lock :锁
class threading.RLock: 重入锁 ,重入锁必须由获取它的线程释放。一旦线程获得了重入锁,同一个线程再次获取它将不阻塞;线程必须在每次获取它时释放一次。
threadLock = threading.Lock()
# 获得锁,成功获得锁定后返回True
# 可选的timeout参数不填时将一直阻塞直到获得锁定
# 否则超时后将返回False
threadLock.acquire()
# you code here
# 释放锁
threadLock.release()
########################################################################################
with some_lock:
# do something...
相当于:
some_lock.acquire()
try:
# do something...
finally:
some_lock.release()
########################################################################################
队列: Queue
Python的Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先入先出)队列Queue,LIFO(后入先出)队列LifoQueue,和优先级队列PriorityQueue。这些队列都实现了锁原语,能够在多线程中直接使用。可以使用队列来实现线程间的同步。
########################################################################################
```
<file_sep>/bookmarks/bookmarks.md
### Archlinux 配置samba ad
在 Archlinux 上用 winbind 配合 pam 配置 Windows AD 认证登录: https://www.dazhuanlan.com/2019/11/20/5dd4a64a3ec2d/
Active Directory integration https://wiki.archlinux.org/index.php/Active_Directory_integration#DNS_Configuration
samba wiki : https://wiki.archlinux.org/index.php/Samba
----------------------
notepadqq 替换html 标签属性: https://zhidao.baidu.com/question/583545607.html
正则:
```
如果是为了替换掉style属性,可以用如下表达式 :
匹配用双引号的属性:
style="[^\"]*?"
再来一次单引号的:
style='[^\']*?'
```
<file_sep>/sql/postgresql/rename_db.md
```
数据库重命名:
ALTER DATABASE oldName RENAME TO newName
```
<file_sep>/C_or_C++/c/struct_and_type.md
字符
```
char a = 'E';
char b = 70;
print 中 %c 输出数字时为ascii 码表中对应字符, %d 输出字符时为ascii 码表中字符对应的数字编号。
```
字符串
```
char str1[] = "字符串";
char *str2 = "字符串";
二者等价
```
<file_sep>/python/compile.md
python 源码编译为pyc
```
单个文件编译
python -m py_compile myApp.py
python -m py_compile /path/to/{myApp1,myApp2,,...,}.py
整体批量编译
python -m compileall myProjectDir
```
```
进入shell交互式环境编译
import py_compile
py_compile.compile('path/to/myApp.py')
```
```
项目文件整体进行编译
import compileall
compileall.compile_dir(dir='path/to/myProjectDir/',force=True)
```
<file_sep>/sql/mysql/install.md
```
# pacman -S mariadb
# mysql_install_db --user=mysql --basedir=/usr --datadir=/var/lib/mysql
# systemctl start mariadb
# mysql_secure_installation
# systemctl restart mariadb
```
使用二进制包安装:
```
mysql 8.0
https://dev.mysql.com/doc/refman/8.0/en/binary-installation.html 安装文档
https://dev.mysql.com/downloads/mysql/ : 下载地址
添加用户
groupadd mysql
useradd -r -g mysql -s /bin/false mysql
解压二进制包,并命名为mysql.
如果 /etc/my.cnf /etc/my.cnf.d 存在,先移走。
bin/mysqld --initialize --user=mysql : mysql 目录下会生产data 目录。
同时会打印root 默认随机密码
A temporary password is generated for root@localhost: 后是默认密码
bin/mysql_ssl_rsa_setup --datadir=<data目录: 默认为/usr/loacl/mysql/data>
bin/mysqld_safe --user=mysql &
编辑: support-files/mysql.server 设置如下内容
basedir=<mysql 根目录>
datadir=<mysql data目录>
修改默认密码(不然进行操作是会报: You must reset your password using ALTER USER statement before executing this statement. 的错误):
alter user user() identified by "密码";
```
```
mysql 5.7
解压。
初始化。
./bin/mysqld --initialize --user=mysql --datadir=<mysql 数据目录>
记住随机密码。
重装删除/etc/my.cnf /etc/mysql/
配置启动脚本:
./support-files/mysql.server 设置如下内容
basedir=<mysql 根目录>
datadir=<mysql data目录>
./support-files/mysql.server start/stop/status
./bin/mysql -uroot -p
使用初始化生成的密码登录
修改root 密码
set password=<PASSWORD>('<PASSWORD>');
授权:允许远程访问
grant all privileges on *.* to 'root'@'%' identified by 'root';
flush privileges;
```
<file_sep>/linux/desktop-evn/deepin-ui/wm.md
```
#!/bin/bash
if [ "$1" == "wm" ];then
echo "deepin-wm窗管,取代正在运行的窗管"
deepin-wm --replace &
exit 0
fi
if [ "$1" == "on" ];then
echo "开启 metacity 窗管合成,取代正在运行的窗管"
deepin-metacity --composite --replace &
exit 0
fi
if [ "$1" == "off" ];then
echo "关闭 metacity 窗管合成,取代正在运行的窗管"
deepin-metacity --no-composite --replace &
exit 0
fi
```
<file_sep>/linux/softs/wrf/0.install.md
```
yum install -y zlib zlib-devel
yum install -y jasper jasper-devel (centos 7 需配置网络yum, iso 中不提供)
yum install -y libpng libpng-devel
yum install -y libjpeg libjpeg-devel
yum install -y zlib zlib-devel jasper jasper-devel libpng libpng-devel libjpeg libjpeg-devel
```
参考: https://xg1990.com/blog/archives/190
1. 安装:hdf5 (hdf5-1.10.5.tar.gz)
```
./configure --prefix=/opt/hdf5
make install
```
2. 安装netcdf-c: (netcdf-c-4.7.0.tar.gz)
```
yum install libcurl-dev (rhel6.5 不需要)
yum install m4
./configure --prefix=/opt/netcdf-c --enable-netcdf-4 LDFLAGS="-L/opt/hdf5/lib" CPPFLAGS="-I/opt/hdf5/include"
make install
```
3. 安装netcdf-fortran (netcdf-fortran-4.4.5.tar.gz)
```
(./configure --prefix=/opt/netcdf-fortran LDFLAGS="-L/opt/netcdf-c/lib" CPPFLAGS="-I/opt/netcdf-c/include" FC=gfortran)
出现错误:
configure: error: cannot compute sizeof (off_t)
See `config.log' for more details
参考:http://bbs.06climate.com/forum.php?mod=viewthread&tid=40952
export CPPFLAGS=-I/opt/netcdf-c/include
export LDFLAGS=-L/opt/netcdf-c/lib
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:/opt/netcdf-c/lib
./configure --prefix=/opt/netcdf-fortran
make install
```
4. wrfv 安装
```
// export NETCDF=/opt/netcdf-c
export NETCDF=/opt/netcdf-fortran
./configure (选择编译选项)
32. (serial) 33. (smpar) 34. (dmpar) 35. (dm+sm) GNU (gfortran/gcc)
./compile em_real
--------------------------------------------
make[1]: time: Command not found
make[1]: [em_real] Error 127 (ignored)
configure.wrf
FC = time $(SFC)
删除 time
重新编译:
collect2: error: ld returned 1 exit status
make[1]: [em_real] Error 1 (ignored)
make[1]: Leaving directory `/opt/WRFV3/main'
##### 到此处放弃
-------------------------------------
yum install time
## type -a time
## time is a shell keyword
## time is /usr/bin/time
重新编译通过
```
5. wps 安装
```
./configure (选择编译选项)
./compile
--------------------------------------------------------------
/usr/bin/ld: cannot find -lnetcdf
collect2: error: ld returned 1 exit status
# pwd
/opt/netcdf-fortran/lib
建立软链接
libnetcdf.so -> /opt/netcdf-c/lib/libnetcdf.so.15.0.1
libnetcdf.so.15 -> /opt/netcdf-c/lib/libnetcdf.so.15.0.1
设置环境变量
export NETCDF=/opt/netcdf-fortran
export LD_LIBRARY_PATH=/opt/netcdf-fortran/lib/
编译
./configure (选择编译选项)
./compile
```
<file_sep>/golang/daemon/1.md
```
go get github.com/icattlecoder/godaemon
```
```go
package godaemon
import (
"flag"
"fmt"
"os"
"os/exec"
)
var godaemon = flag.Bool("d", false, "run app as a daemon with -d=true")
func init() {
if !flag.Parsed() {
flag.Parse() //补充注释: 设置godaemon 的值
}
if *godaemon { // 补充注释: true 执行
args := os.Args[1:]
i := 0
for ; i < len(args); i++ {
if args[i] == "-d=true" {
args[i] = "-d=false" // 修改参数,将参数d 设置为false, 在command 调用时,该部分代码不再执行。
break
}
}
cmd := exec.Command(os.Args[0], args...)
cmd.Start()
fmt.Println("[PID]", cmd.Process.Pid)
os.Exit(0)
}
}
```
example:
```go
package main
import (
_ "github.com/icattlecoder/godaemon"
"log"
"net/http"
)
func main() {
mux := http.NewServeMux()
mux.HandleFunc("/index", func(rw http.ResponseWriter, req *http.Request) {
rw.Write([]byte("hello, golang!\n"))
})
log.Fatalln(http.ListenAndServe(":7070", mux))
}
```
run:
```
./example -d=true
~$ curl http://127.0.0.1:7070/index
hello, golang!
```
<file_sep>/linux/common/usermanage.md
参考:https://m.aliyun.com/jiaocheng/165501.html
创建用户:useradd
```
Usage: useradd [options] LOGIN
useradd -D
useradd -D [options]
Options:
-b, --base-dir BASE_DIR base directory for the home directory of the
new account
-c, --comment COMMENT GECOS field of the new account
-d, --home-dir HOME_DIR home directory of the new account
-D, --defaults print or change default useradd configuration
-e, --expiredate EXPIRE_DATE expiration date of the new account
-f, --inactive INACTIVE password inactivity period of the new account
-g, --gid GROUP name or ID of the primary group of the new
account
-G, --groups GROUPS list of supplementary groups of the new
account
-h, --help display this help message and exit
-k, --skel SKEL_DIR use this alternative skeleton directory
-K, --key KEY=VALUE override /etc/login.defs defaults
-l, --no-log-init do not add the user to the lastlog and
faillog databases
-m, --create-home create the user's home directory
-M, --no-create-home do not create the user's home directory
-N, --no-user-group do not create a group with the same name as
the user
-o, --non-unique allow to create users with duplicate
(non-unique) UID
-p, --password <PASSWORD> encrypted password of the new account
-r, --system create a system account
-R, --root CHROOT_DIR directory to chroot into
-P, --prefix PREFIX_DIR prefix directory where are located the /etc/* files
-s, --shell SHELL login shell of the new account
-u, --uid UID user ID of the new account
-U, --user-group create a group with the same name as the user
用户可同时属于一个主要组及多个附属组
eg:
# adduser -g usergroup [-d user_home_path] -m user_name
[-G wheel,root] 指定用户属于多个组
修改用户注释信息: usermod -c xxx 用户名
修改用户名:usermod -l 新名 旧名
锁定用户:passwd -l 用户
解锁: passwd -u 用户
清除用户密码:passwd -d 用户
设置密码: passwd 用户
```
删除用户组:
```
userdel
# userdel -r user_name (删除/etc/passwd, /etc/shadow, /etc/group等 文件中的记录 以及用户目录)
```
用户组
```
创建用户组:groupadd 组名
修改组名:groupmod -n newname oldname
修改组编号:groupmod -g 669 组名
创建用户组的同时指定编号: groupadd -g 668 组名
删除用户组:groupdel 组名
```
修改用户组:
```
# usermod -a -G group_name user_name : 修改用户附加组
# usermod -g group_name user_name : 修改用户主组
参考:http://blog.51cto.com/yongtao/1687595
将用户添加至附属组:gpasswd -a 用户名 用户组
从附属组删除用户:gpasswd -d 用户名 附属组名
```
```
改变用户组密码:gpasswd 用户组
```
```bash
usermod -l 新用户名 -d /home/新用户名 -m 老用户名 : 修改用户名及其家目录
usermod -l 新用户名 老用户名 : 仅修改用户名
```
添加一个xxxx的帐号,密码为<PASSWORD>
```bash
# echo xxxx:123456 | chpasswd
# echo '123456'| passwd --stdin xxxx
```
<file_sep>/java/java_common/Unsafe.md
参考
<https://blog.csdn.net/aesop_wubo/article/details/7537278>
原子操作
<file_sep>/linux/desktop-evn/deepin-ui/paths.md
/usr/share/wallpapers/deepin : wallpaper
/usr/share/sounds/deepin/stereo : sound<file_sep>/java/maven/repositories.md
### 参考:<https://www.cnblogs.com/ctxsdhy/p/8482725.html>
1、在mirrorOf与repositoryId相同的时候优先是使用mirror的地址
2、mirrorOf等于*的时候覆盖所有repository配置
3、存在多个mirror配置的时候mirrorOf等于*放到最后
4、只配置mirrorOf为central的时候可以不用配置repository
### 配置了 repositories,会优先考虑冲repositories配置的镜像下载依赖.
repositories:
```
<releases><enabled>true</enabled></releases>告诉Maven可以从这个仓库下载releases版本的构件,
<snapshots><enabled>false</enabled></snapshots>告诉Maven不要从这个仓库下载snapshot版本的构件。
禁止从公共仓库下载snapshot构件是推荐的做法,因为这些构件不稳定,且不受你控制,你应该避免使用。
如果你想使用局域网内组织内部的仓库,你可以激活snapshot的支持。
```
<file_sep>/linux/softeher_vpn/ubuntu_client.md
# make
# vpnclient start
# vpncmd
> remoteenable
> niccreate : Create New Virtual Network Adapter
: Virtual Network Adapter Name
> niclist<file_sep>/js/nodejs/install.md
download: <http://nodejs.cn/download/>
配置: 解压并将将bin 目录加到PATH 中。
cnpm 安装:<https://npm.taobao.org/>
```bash
$ npm install -g cnpm --registry=https://registry.npm.taobao.org
alias cnpm="npm --registry=https://registry.npm.taobao.org \
--cache=$HOME/.npm/.cache/cnpm \
--disturl=https://npm.taobao.org/dist \
--userconfig=$HOME/.cnpmrc"
# Or alias it in .bashrc or .zshrc
$ echo '\n#alias for cnpm\nalias cnpm="npm --registry=https://registry.npm.taobao.org \
--cache=$HOME/.npm/.cache/cnpm \
--disturl=https://npm.taobao.org/dist \
--userconfig=$HOME/.cnpmrc"' >> ~/.zshrc && source ~/.zshrc
```
<file_sep>/python/编译安装.md
# python2.7
1. 安装系统依赖
centos:
yum install gcc zlib zlib-devel openssl openssl-devel
readline-devel (ncurses-libs ) sqlite-devel bzip2-devel gdbm-devel libdbi-devel
<https://blog.csdn.net/huanle0610/article/details/41174943>
<https://www.cnblogs.com/totoros/p/4179986.html>
2. 下载源码包: https://www.python.org/downloads/ 并解压
3. 编译:
```
首先生成python安装路径,我这里将安装路径放在/usr/local下面
mkdir /usr/local/python2.7
进入解压的源码路径,运行下面命令生成Makefile
./configure --enable-optimizations --prefix=/usr/local/python2.7/
--enable-optimizations 为最优安装,建议使用这个参数。--prefix 声明安装路径
--enable-shared : python lib 目录下生成动态链接库。
修改 Modules/Setup 文件,修改内容如下
# Socket module helper for SSL support; you must comment out the other
# socket line above, and possibly edit the SSL variable:
#SSL=/usr/local/ssl
_ssl _ssl.c \
-DUSE_SSL -I$(SSL)/include -I$(SSL)/include/openssl \
-L$(SSL)/lib -lssl -lcrypto
默认这块是注释的,放开注释即开。这块功能是开启SSL模块,不然会出现安装完毕后,提示找不到ssl模块的错误。
Makefile生后依次在当前路径执行编译和安装命令
make & make install
以上命令执行完毕,且无报错的情况下,我们将默认python换将切换至2.7,保险起见现将软链备份。
cd /usr/bin
mv python python.bak
建立新的软链
ln -s /usr/local/python2.7/bin/python2.7 /usr/bin/python
运行命令python -V,查看是否出现2.7的版本,出现即为安装成功。
```
4. 安装settool 和pip
下载 settool 和pip 并解压
相目录执行: python setup.py install
--------------------------------------------------------------
# python 3 安装
1. 安装系统依赖
yum install zlib-devel bzip2-devel openssl-devel ncurses-devel sqlite-devel readline-devel tk-devel gcc make
2. 下载源码包: https://www.python.org/downloads/ 并解压
3. 编译:
[root@Python /]# tar -xzvf /usr/local/src/Python-3.5.2.tgz -C /usr/local/src/
[root@Python /]# cd /usr/local/src/Python-3.5.2
[root@Python Python-3.5.2]# ./configure --prefix=/usr/local/python
[root@Python Python-3.5.2]# make -j 4
[root@Python Python-3.5.2]# make install
4. 添加Python命令到环境变量:vim ~/.bash_profile
```
# 添加
export PYTHON_HOME=/usr/local/python
export PATH=$PYTHON_HOME/bin:$PATH
```
```
解决python升级后,YUM不能正常工作的问题:
#vi /usr/bin/yum
将文件头部的
#!/usr/bin/python
改成
#!/当前python
```
<file_sep>/sql/postgresql/lock.md
```
查看数据库的进程。
SELECT * FROM pg_stat_activity WHERE datname='死锁的数据库名称 ';
检索出来的字段中,【wating 】字段,数据为t的那条,就是死锁的进程,找到对应的【procpid 】列的值。
例如:SELECT pid FROM pg_stat_activity WHERE datname='死锁的数据库名称' and waiting ='t';
```
```
杀掉进程。
pg_cancel_backend,pg_terminate_backend 选择性使用
kill有两种方式,第一种是:
SELECT pg_cancel_backend(PID);
这种方式只能kill select查询,对update、delete 及DML(alter,create)不生效)
第二种是:
SELECT pg_terminate_backend(PID);
这种可以kill掉各种操作(select、update、delete、drop等)操作 【有这东西,还用pg_cancel_backend干嘛】
--查询是否锁表了 (需要使用管理员,先切换到对应的数据库)
select oid from pg_class where relname='可能锁表了的表的表名' --oid是每个表隐藏的id
select pid from pg_locks where relation='上面查出的oid'
--如果查询到了结果 则释放锁定
select pg_cancel_backend(上面查到的pid)
select pg_terminate_backend(上面查到的pid)
```
<file_sep>/python/base/class_buildin_functions.md
```
凡是在类中定义了这个__getitem__ 方法,那么它的实例对象(假定为p),可以像这样
p[key] 取值,当实例对象做p[key] 运算时,会调用类中的方法__getitem__。
可以用在对象的迭代上
class STgetitem:
def __init__(self, text):
self.text = text
def __getitem__(self, index):
result = self.text[index].upper()
return result
p = STgetitem("abcd")
for char in p:
print(char)
A
B
C
D
```
```
def __init__(self):
pass
```
```
def __new__(cls, *args, **kwd):
```
```
当读取对象的某个属性时,python会自动调用__getattr__()方法.例如,fruit.color将转换为fruit.__getattr__(color).
当使用赋值语句对属性进行设置时,python会自动调用__setattr__()方法.
__getattribute__()的功能与__getattr__()类似,用于获取属性的值.但是__getattribute__()能提供更好的控制,代码更健壮.注意,python中并不存在__setattribute__()方法.
def __getattribute__(self, name): # 获取属性的方法
def __setattr__(self, name, value):
```
```
_str__()用于表示对象代表的含义,返回一个字符串.实现了__str__()方法后,可以直接使用print语句输出对象,也可以通过函数str()触发__str__()的执行.这样就把对象和字符串关联起来,便于某些程序的实现,可以用这个字符串来表示某个类
```
```
在类中实现__call__()方法,可以在对象创建时直接返回__call__()的内容.使用该方法可以模拟静态方法
```
```
内置方法 说明
__init__(self,...) 初始化对象,在创建新对象时调用
__del__(self) 释放对象,在对象被删除之前调用
__new__(cls,*args,**kwd) 实例的生成操作
__str__(self) 在使用print语句时被调用
__getitem__(self,key) 获取序列的索引key对应的值,等价于seq[key]
__len__(self) 在调用内联函数len()时被调用
__cmp__(stc,dst) 比较两个对象src和dst
__getattr__(self,name) 获取属性的值
__setattr__(self,name,value) 设置属性的值
__delattr__(self,name) 删除name属性
__getattribute__(self, name) __getattribute__()功能与__getattr__()类似
__gt__(self,other) 判断self对象是否大于other对象
__lt__(slef,other) 判断self对象是否小于other对象
__ge__(slef,other) 判断self对象是否大于或者等于other对象
__le__(slef,other) 判断self对象是否小于或者等于other对象
__eq__(slef,other) 判断self对象是否等于other对象
__call__(self,*args) 把实例对象作为函数调用
```
<file_sep>/golang/buildin_libs.md
plugin (build in)
```
加载动态库: 不能卸载
编译lib:
go build -buildmode=plugin plugin.go
import (
.....
"plugin"
)
p0, err0 := plugin.Open("plg/plugin.so")
if err0 != nil {
panic(err0)
}
m0, err0 := p0.Lookup("GetProductBasePrice")
if err0 != nil {
panic(err0)
}
res0 := m0.(func(int) int)(30)
fmt.Println(res0)
```
<file_sep>/linux/tools/ap.md
```
# create_ap wlan0 eth0 MyAccessPoint MyPassPhrase
有线正常上网,无线网卡用作wifi网卡
# create_ap 无线网卡 有线网卡 wifi名称 wifi密码
```
<file_sep>/js/angular2/脚手架.md
from:http://blog.csdn.net/cd18333612683/article/details/55056696
1. install nodejs
2. install npm:
npm install -g cnpm --registry=https://registry.npm.taobao.org
3. install angular-cli
npm install -g angular-cli
if install faild: npm uninstall -g angular-cli && npm cache clean
4. ng -v : test version
5. ng new project_name : new project
6. ng serve : run
7. ng build : build to dist
eidt: .angular-cli.json to config build output_dir
<file_sep>/linux/linux-kernel/kenel.md
**Mainline内核(软件包名称:linux)**
这是最新的稳定Linux内核。大多数人使用此内核是因为它是最新的可用内核版本。
**LTS内核(软件包名称:linux-lts)**
该linux-lts软件包为您提供了最新的长期支持Linux内核。LTS内核没有预定义的生命周期,但是可以放心地在更长的时间内享受相同的内核版本。
内核补丁通常不会破坏任何东西,但并非不可能发生破坏。如果您的硬件不是市场上可以提供的最新硬件,则可以通过安装稍早的LTS内核来享受最新的软件,从而提高稳定性。
**强化内核(软件包名称:linux-hardened)**
对于安全相关的用户,有最新稳定内核的强化版本。请注意,使用此内核时,几个软件包将不起作用。
**性能优化的内核(软件包名称:linux-zen)**
如果您想充分利用系统,则可以使用“ Zen”内核,该内核基本上是最新内核的分支,并以吞吐量和功耗为代价进行调整。<file_sep>/linux/softs/bumblebee/0_install.md
sudo pacman -S nvidia
sudo pacman -S bumblebee
sudo gpasswd -a username <PASSWORD>
sudo systemctl enable bumblebeed.service
reboot
<https://www.cnblogs.com/tonyc/p/7732119.html>
/etc/modprobe.d/blacklist
添加: **blacklist nouveau**<file_sep>/js/js/commonjs.md
apply,call:
```
/*apply()方法*/
function.apply(thisObj[, argArray])
/*call()方法*/
function.call(thisObj[, arg1[, arg2[, [,...argN]]]]);
apply:调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.apply(A, arguments);即A对象应用B对象的方法。
call:调用一个对象的一个方法,用另一个对象替换当前对象。例如:B.call(A, args1,args2);即A对象调用B对象的方法。
都“可以用来代替另一个对象调用一个方法,将一个函数的对象上下文从初始的上下文改变为由thisObj指定的新对象”。
它们的不同之处:
apply:最多只能有两个参数——新this对象和一个数组argArray。如果给该方法传递多个参数,则把参数都写进这个数组里面,当然,即使只有一个参数,也要写进数组里。如果argArray不是一个有效的数组或arguments对象,那么将导致一个TypeError。如果没有提供argArray和thisObj任何一个参数,那么Global对象将被用作thisObj,并且无法被传递任何参数。
call:它可以接受多个参数,第一个参数与apply一样,后面则是一串参数列表。这个方法主要用在js对象各方法相互调用的时候,使当前this实例指针保持一致,或者在特殊情况下需要改变this指针。如果没有提供thisObj参数,那么 Global 对象被用作thisObj。
实际上,apply和call的功能是一样的,只是传入的参数列表形式不同。
```
<file_sep>/sql/postgresql/solutions/copy.md
extra data after last expected column
postgres csv copy
导出数据表后导入到新的数据表: 两个环境表结构不一致 <file_sep>/sql/postgresql/solutions/多个问题.md
https://blog.csdn.net/international24/article/details/89710703
包含多种数据不能启动的原因及处理办法
<file_sep>/linux/desktop-evn/sway-wayfire/tools.md
yay -S swayshot
```
swayshot region
```
<file_sep>/linux/common/hostname.md
rhel6:
```
1、临时修改主机名
sudo hostname lyhost
2、永久修改主机名
vim /etc/sysconfig/network
修改里面的HOSTNAME字段即可,重启后生效。
```
<file_sep>/sql/postgresql/alter.md
```
修改字段类型,或长度
alter table <表名> alter column <列名> type <新类型>;
```
```
添加列
ALTER TABLE <表名> ADD <列名> <类型>
```
```
删除列
ALTER TABLE <表名> DROP COLUMN <列名>;
```
```
设置not null
ALTER TABLE table_name MODIFY column_name datatype NOT NULL;
```
```
添加unique 约束
ALTER TABLE table_name
ADD CONSTRAINT MyUniqueConstraint UNIQUE(column1, column2...);
```
```
添加检查约束
ALTER TABLE table_name
ADD CONSTRAINT MyCheckConstraint CHECK (CONDITION);
```
```
添加主键约束
ALTER TABLE table_name
ADD CONSTRAINT MyPrimaryKey PRIMARY KEY (column1, column2...);
```
```
删除约束
ALTER TABLE table_name
DROP CONSTRAINT MyConstraint;
```
<file_sep>/linux/softs/list.md
- notepadqq:
Ubuntu下的安装方法:
sudo snap install --classic notepadqqe
```bash
#!/bin/bash
# the script need run as root
if [ `id -u` -eq 0 ];then
echo "root用户!"
else
echo "非root用户!"
exit 0
fi
snap install --classic notepadqq
```
- shadowsocks
sudo apt-get install shadowsocks-qt5
axel https://github.com/axel-download-accelerator/axel
sublime text 3 激活码:
参考:https://blog.csdn.net/sinat_32829963/article/details/79273129
```
—– BEGIN LICENSE —– (失效)
Country Rebel
Single User License
EA7E-993095
19176BCE 3FF86EA0 3CE86508 6BE4DCA7
9F74D761 4D0CAD8B E4033008 43FC73F3
1C01F6DD C4829BE9 E7830578 A4823ADC
61B224F1 DC93C458 ABAAAE0F 925C32D4
04A83C36 813FF6C8 9877942C 4418F99C
2F15E5B8 544EDB80 D9A86985 4CBBA6A8
998DE3E4 7FB33E15 6CD30357 6DC96CEA
ECB1BC4E D8010D5A 77BA86C8 BA7F76CC
—— END LICENSE ——
—– BEGIN LICENSE —– (失效)
TwitterInc
200 User License
EA7E-890007
1D77F72E 390CDD93 4DCBA022 FAF60790
61AA12C0 A37081C5 D0316412 4584D136
94D7F7D4 95BC8C1C 527DA828 560BB037
D1EDDD8C AE7B379F 50C9D69D B35179EF
2FE898C4 8E4277A8 555CE714 E1FB0E43
D5D52613 C3D12E98 BC49967F 7652EED2
9D2D2E61 67610860 6D338B72 5CF95C69
E36B85CC 84991F19 7575D828 470A92AB
—— END LICENSE ——
—– BEGIN LICENSE —–
Bug7sec Team (www.bug7sec.org)
50 User License
EA7E-1068832
86C49532 8F829C68 2ED18D56 162664F2
8B934F0C EB60A7FE 81D7D5EF BB8F1673
F67D69C7 C5E21B19 42E7EFBD D9C2BBC1
CEBA4697 535E29CA 0D2D0D4D ACE548CE
07815DC7 BDE3901E D5D198E4 BC1677C0
46097A55 29BCE0C9 72A358E8 CEFEEFB5
24CEB623 D7232749 F2515349 FB675F93
C55635A7 B1E32AB0 3D055979 041E0359
—— END LICENSE ——
—– BEGIN LICENSE —–
Esri, Inc
19 User License
EA7E-853424
BBB0D927 00F6E4AB 0AFFEFEA 82C4A3E5
4F9A99D1 7C0475AB 5A708861 6C81D74E
4BBA1F56 877CE0E2 88126328 486D8600
8A0A85D7 49671882 49969D92 312F27A7
5CCAE55B D711D4E2 9069DE55 B510370C
9499567E 61D548BA FB260403 711DFE24
1BAFDA6D 1F52E6B1 B728EF5B A40CCD4D
FD716AF5 1760D208 0E05F26E 22660950
—— END LICENSE ——
—– BEGIN LICENSE —–
Die Socialisten GmbH
10 User License
EA7E-800613
51311422 E45F49ED 3F0ADE0C E5B8A508
2F4D9B65 64E1E244 EDA11F0E F9D06110
B7B2E826 E6FDAA72 2C653693 5D80582F
09DCFFB5 113A940C 5045C0CD 5F8332F8
34356CC6 D96F6FDB 4DEC20EA 0A24D83A
2C82C329 E3290B29 A16109A7 EC198EB9
F28EBB17 9C07403F D44BA75A C23C6874
EBF11238 5546C3DD 737DC616 445C2941
—— END LICENSE ——
—– BEGIN LICENSE —–
<NAME>
Single User License
EA7E-898127
CD1A23C0 E8687245 18A89BFA 7CF52C10
A20AA536 9E1A57C7 D33839DC 6613C428
91E9C7FF F4702893 251C6403 27A10818
6F48AC9C BB66843D C1D60DEA B952C2D0
40019115 E5278B04 95EBB709 D6B1C5B9
67CA940A 88701851 32910570 57AD5B96
263A8906 AFBFAB46 52F6706F CACFC74E
DFAD4752 D10E58B6 744B90F2 13AF2B9C
—— END LICENSE ——
```
<file_sep>/linux/common/usage/清空或删除大文件内容.md
```
> <filename>
```
```
: > <filename>
true > <filename>
```
```
cat /dev/null > <filename>
cp /dev/null <filename>
dd if=/dev/null of=<filename>
```
```
echo "" > <filename>
echo > <filename>
echo -n "" > <filename>
echo : 默认结尾输出新行, -n: 输出新行
```
```
truncate -s 0 <filename>
```
<file_sep>/windows/clean_win_bt.md
```
takeown /F C:\$Windows.~BT\* /R /A
icacls C:\$Windows.~BT\*.* /T /grant administrators:F
rmdir /S /Q C:\$Windows.~BT\
```
<file_sep>/java/eclipse_rcp/start.md
```
开发环境:
eclipse 安装rcp 插件。 或使用集成好rcp 的eclipse.
参考:http://www.blogjava.net/youxia/archive/2006/11/17/81852.html
创建项目:
创建项目->Plugin-inDevelopment->Plugin-in project [next]
输入:项目名;选择eclipse 版本(3.5 or greater); [next]
选择 rich client application(yes) [next]
选择 HELLO RCP [finish]
run as : eclipse application 可直接运行出窗口。
创建产品配置:
new -> product configuration
输入: filename ; initialize the file content: with basic settings
general informations: 输入id version name
product Definition: new -> browser (查找创建的项目名)
product application: 项目名.application
dependencies: add (查找创建的项目名并添加); add required plugin-ins
launch an eclipse application 可直接运行出窗口.
导出:
选择导出路径,导出文件夹名称等 [finish]
GLib-CRITICAL **: XXXXX :assertion 'in != NULL' failed
export SWT_GTK3=0
```
<file_sep>/linux/common/压缩与解压.md
# cd https://www.cnblogs.com/zhenghaonihao/p/6100657.html
# 压缩
tar –cvf jpg.tar *.jpg //将目录里所有jpg文件打包成tar.jpg
tar –czf jpg.tar.gz *.jpg //将目录里所有jpg文件打包成jpg.tar后,并且将其用gzip压缩,生成一个gzip压缩过的包,命名为jpg.tar.gz
tar –cjf jpg.tar.bz2 *.jpg //将目录里所有jpg文件打包成jpg.tar后,并且将其用bzip2压缩,生成一个bzip2压缩过的包,命名为jpg.tar.bz2
tar –cZf jpg.tar.Z *.jpg //将目录里所有jpg文件打包成jpg.tar后,并且将其用compress压缩,生成一个umcompress压缩过的包,命名为jpg.tar.Z
rar a jpg.rar *.jpg //rar格式的压缩,需要先下载rar for linux
zip jpg.zip *.jpg //zip格式的压缩,需要先下载zip for linux
# 解压
tar –xvf file.tar //解压 tar包
tar -xzvf file.tar.gz //解压tar.gz
tar -xjvf file.tar.bz2 //解压 tar.bz2
tar –xZvf file.tar.Z //解压tar.Z
unrar e file.rar //解压rar
unzip file.zip //解压zip
# 总结
1、*.tar 用 tar –xvf 解压
2、*.gz 用 gzip -d或者gunzip 解压
3、*.tar.gz和*.tgz 用 tar –xzf 解压
4、*.bz2 用 bzip2 -d或者用bunzip2 解压
5、*.tar.bz2用tar –xjf 解压
6、*.Z 用 uncompress 解压
7、*.tar.Z 用tar –xZf 解压
8、*.rar 用 unrar e解压
9、*.zip 用 unzip 解压
tar zxvf test.tgz
tar.xz:
xz -d ***.tar.xz
tar -xvf ***.tar
tar -xvJf *.tar.xz
zip:
zip [-options] [-b path] [-t mmddyyyy] [-n suffixes] [zipfile list] [-xi list]
The default action is to add or replace zipfile entries from list, which
can include the special name - to compress standard input.
If zipfile and list are omitted, zip compresses stdin to stdout.
-f freshen: only changed files -u update: only changed or new files
-d delete entries in zipfile -m move into zipfile (delete OS files)
-r recurse into directories -j junk (don't record) directory names
-0 store only -l convert LF to CR LF (-ll CR LF to LF)
-1 compress faster -9 compress better
-q quiet operation -v verbose operation/print version info
-c add one-line comments -z add zipfile comment
-@ read names from stdin -o make zipfile as old as latest entry
-x exclude the following names -i include only the following names
-F fix zipfile (-FF try harder) -D do not add directory entries
-A adjust self-extracting exe -J junk zipfile prefix (unzipsfx)
-T test zipfile integrity -X eXclude eXtra file attributes
-y store symbolic links as the link instead of the referenced file
-e encrypt -n don't compress these suffixes
-h2 show more help
zip -re ----.zip files_or_dirs : input password to encrypt the zip file
zip -P password ----.zip files_or_dirs
zip zipfilename files_to_zip : zip x x1 x2 -> x.zip
zip -r zipfilename menus_to_zip
unrar
bzip2: Cannot exec: No such file or directory
安装:bzip2 解决问题
```
.tar.zst 解压
tar -I zstd -xvf archive.tar.zst
```
```
.deb
ar -vx xx.deb
```
```
rpm 包解压
安装软件包: rpm-tools,cpio
rpm2cpio xxx.rpm | cpio -divm
```
<file_sep>/java/idea_config.md
忽略文件
```
1. Settings→Editor→File Types
2. 在下方的忽略文件和目录(Ignore files and folders)中添加自己需要过滤的内容
例如:.iml;*.idea;*.gitignore;*.sh;*.classpath;*.project;*.settings;target;
```
i8n unicode 显示内容:
```
1. Settings→Editor-> File Encodings
勾选: Transparent native to asscii conversion
```
文件模板:
```
1. Settings→Editor-> File and Code Templates
User: ${USER}
Date: ${DATE}
Time: ${TIME}
PACKAGE_NAME:${PACKAGE_NAME}
NAME: ${NAME} 文件名,class 名
Class_Name:${Class_Name}
${PK_Class_Name}
${Interface_Name}
${Remote_Interface_Name}
${Local_Interface_Name}
```
<file_sep>/windows/cleanshortcut.md
```vb
reg add "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Shell Icons" /v 29 /d "%systemroot%\system32\imageres.dll,197" /t reg_sz /f
taskkill /f /im explorer.exe
attrib -s -r -h "%userprofile%\AppData\Local\iconcache.db"
del "%userprofile%\AppData\Local\iconcache.db" /f /q
start explorer
pause
```
<file_sep>/sql/postgresql/solutions/新增字段写入数据异常.md
```
分区表添加字段后数据未正常写入或不能写入:
现象:
不能写入 : 反射表结构时不能正确获取修改后的表信息.
写入新字段的数据为null (字段默认默认值为null)
解决方法:
删除分区表,然后重建表继承关系.
```
<file_sep>/python/pip/包管理.md
## 显示模块
pip list --format=columns
#显示过期模块
pip list --outdated
#安装模块
https://blog.csdn.net/chenghuikai/article/details/55258957
pip install xxx
python setup.py install (源码安装)
pip install packname -i http://pypi.douban.com/simple --trusted-host pypi.douban.com
#卸载模块
pip uninstall xxx
#升级模块
pip install --upgrade xxx
# 批量依赖
pip freeze > requirements.txt
查看源文件
pip的freeze命令用于生成将当前项目的pip类库列表生成 requirements.txt 文件:
如果要安装requirements.txt中的类库内容,那么你可以执行pip install -r requirements.txt.
<file_sep>/linux/wayland/hidpitest.md
```
https://wiki.archlinux.org/index.php/HiDPI_(%E7%AE%80%E4%BD%93%E4%B8%AD%E6%96%87)#GNOME
An example of the panning syntax for a 4k laptop with an external 1920x1080 monitor to the right:
xrandr --output eDP-1 --auto --output HDMI-1 --auto --panning 3840x2160+3840+0 --scale 2x2 --right-of eDP-1
Generically if your HiDPI monitor is AxB pixels and your regular monitor is CxD and you are scaling by [ExF], the commandline for right-of is:
xrandr --output eDP-1 --auto --output HDMI-1 --auto --panning [C*E]x[D*F]+[A]+0 --scale [E]x[F] --right-of eDP-1
If panning is not a solution for you it may be better to set position of monitors and fix manually the total display screen.
https://blog.ihipop.info/2020/06/5250.html
https://blog.summercat.com/configuring-mixed-dpi-monitors-with-xrandr.html
```
<file_sep>/sql/redis/bgsave.md
redis 关闭 bgsave
```
检查状态:
连接redis 执行: config get save
```
```
运行时关闭:
连接redis 执行:
CONFIG set save ""
```
```
修改配置文件关闭:
注释掉:
save
添加:
save ""
save ""
#save 600 1
#save 300 10
#save 60 100
```
<file_sep>/linux/chrome.md
default application:
xdg-open:
https://wiki.archlinux.org/title/Default_applications
| Method | Uses XDG | Application examples |
| :----------------------------------------------------------: | :--------------------------: | :----------------------------------------------------------: |
| [GIO's GAppInfo](https://developer.gnome.org/gio/stable/GAppInfo.html) | Yes | [Firefox](https://wiki.archlinux.org/title/Firefox), [GNOME Files](https://wiki.archlinux.org/title/GNOME_Files), [PCManFM](https://wiki.archlinux.org/title/PCManFM), [Thunar](https://wiki.archlinux.org/title/Thunar), [Thunderbird](https://wiki.archlinux.org/title/Thunderbird), [Telegram](https://wiki.archlinux.org/title/Telegram) |
| `/usr/bin/xdg-open` | By default | [Chromium](https://wiki.archlinux.org/title/Chromium) (Open downloaded file) |
| custom | Usually not | [mc](https://wiki.archlinux.org/title/Mc), [ranger](https://wiki.archlinux.org/title/Ranger) |
| [environment variables](https://wiki.archlinux.org/title/Environment_variables#Default_programs) | No | [man](https://wiki.archlinux.org/title/Man), [sudoedit](https://wiki.archlinux.org/title/Sudoedit), [systemctl](https://wiki.archlinux.org/title/Systemctl) |
| [D-Bus](https://wiki.archlinux.org/title/D-Bus)'s FileManager1 | org.freedesktop.FileManager1 | [Firefox](https://wiki.archlinux.org/title/Firefox) (Open containing folder), Zotero (Show file), [Telegram](https://wiki.archlinux.org/title/Telegram) (Show in folder) |
chromium,chrome 点击下载的文件,打开方式通过: /usr/bin/xdg-open 文件名 来打开文件。
https://wiki.archlinux.org/title/Xdg-utils#xdg-open
```
查询文件的mime type
xdg-mime query filetype filename
xdg-mime query filetype photo.jpeg
image/jpeg
```
```
基于 mime type 查询默认打开方式
xdg-mime query default mime_type
xdg-mime query default image/jpeg
gimp.desktop
```
```
设置默认打开方式
xdg-mime default 应用.desktop mime_type
xdg-mime default feh.desktop image/jpeg
应用.desktop:
在 /usr/share/applications/ 或 ~/.local/share/applications/
```
<file_sep>/study/软件架构.md
片段:
自省:
1. 你的软件系统有良好定义的结构吗?
2. 团队里每个人都以一致的方式实现特性吗?
3. 代码库的质量水平一致吗?
4. 对于如何构建软件,团队有共同的愿景吗?
5. 团队里每个人都得到了足够的技术指导吗?
6. 有适当的技术领导力吗?
目标:
- 让团队跟随一个清晰的远景和路线图,无论这个愿景是一个人的还是整个团队共有的。
- 技术领导力和更好的协调。
- 与人交流的刺激因素,以便回答与重要决策,非功能需求,限制和其他横切关注点相关的问题。
- 识别和减轻风险的框架。
- 方法与标准的一致性,随之而来的结构良好的代码库。
- 正在构建的产品的坚实基础。
- 对不同的听众,以不同层次的抽象来交流解决方案的结构。
<file_sep>/linux/softs/NetworkManger.md
管理以太网和 WiFi
nm-applet: 网络托盘
查看所有可见连接:
```
$ nmcli con list
```
## Ethernet
断开以太网(重启后不再自动连接):
```
$ nmcli dev disconnect iface eth0
```
ip 配置存放在 `/etc/NetworkManager/system-connections/` 下,文档名即是以太网网络连接的 id 名。这里可以配置多个 ip,但只能启用一个。
启用 Home:
```
$ nmcli con up id "Home"
```
关闭 Home:
```
$ nmcli con down id "Home"
```
## 静态 IP
修改静态 IP 地址,可以编辑上面的 Home 文档,比如修改 [ipv4]:
```
$ vim /etc/NetworkManager/system-connections/Home
[ipv4]
method=manual
address1=192.168.1.100/24,192.168.1.1
dns=8.8.8.8;8.8.4.4;
```
address1 的格式如下:
```
address1=<IP>/<prefix>,<route>
```
## WiFi
列出可见的 WiFi 列表:
```
$ nmcli dev wifi
```
创建一个新的名为“Mycafe”的连接,然后使用密码“<PASSWORD>”连接至 SSID 名为“Cafe Hotspot 1”:
```
$ nmcli dev wifi connect "Cafe Hotspot 1" password "<PASSWORD>" name "Mycafe"
```
断开 “Mycafe” 连接:
```
$ nmcli con down id "Mycafe"
```
启用 “Mycafe” 连接:
```
$ nmcli con up id "Mycafe"
```
显示 Wifi on/off 状态:
```
$ nmcli nm wifi
```
打开 wifi:
```
$ nmcli nm wifi on
```
关闭 wifi:
```
$ nmcli nm wifi off
```
<file_sep>/python/code_part/时间差.md
```python
import datetime
start_time = datetime.datetime.now()
end_time = datetime.datetime.now()
end_time - start_time
```
<file_sep>/python/flask/appbuilder/4_pybabel.md
国际化
参考: https://www.cnblogs.com/Ray-liang/p/4987455.html
```
#!/bin/bash
CURRENT_DIR=$(cd `dirname $0`;pwd)
pybabel extract -F babel/babel.cfg -o babel/messages.pot .
pybabel init -i babel/messages.pot -d app/translations -l zh
pybabel compile -d app/translations
pybabel update -i babel/messages.pot -d app/translations
```
<file_sep>/linux/common/set_time_and_zone.md
```
tzselect
```
```
软连接 或复制文件覆盖/etc/localtime
/etc/localtime -> /usr/share/zoneinfo/Asia/Shanghai
```
```
timedatectl 查看时间各种状态
timedatectl list-timezones: 列出所有时区
timedatectl set-local-rtc 1 将硬件时钟调整为与本地时钟一致, 0 为设置为 UTC 时间
timedatectl set-timezone Asia/Shanghai 设置系统时区为上海
```
```
profile 文件:配置TZ 环境变量
TZ='Asia/Shanghai'
export TZ
```
------------------------------------
```
# date -s 11/14/2018 ## 月/日/年
# date -s 10:48:50 ## 十分秒
#
# hwclock --systohc ##使用系统时间同步硬件时间
# hwclock ## 查看硬件时间
```
```
# hwclock --set --date="11/14/2018 10:56:35" ## 设置硬件时间
# hwclock --hctosys ##使用硬件时间同步系统时间
```
```
# hwclock --show
# clock --show
# hwclock
# clock
## 等价命令
## clock 与hwclock 用法基本等价
```
<file_sep>/linux/common/dig.md
通过指定的dns 服务器解析域名: dig @dnsserver domain_name
<file_sep>/linux/softs/vmware/host_only.md
root:
```
iptables -F
编辑/etc/sysctl.conf (root权限)
取消注释 : net.ipv4.ip_forward=1
执行 : sudo sysctl -p 此时,网络转发功能应该就开启了
- 可以使用如下命令验证: cat /proc/sys/net/ipv4/ip_forward 命令返回1,说明网络转发已开启。
iptables -N fw-open
iptables -A FORWARD -j fw-open
iptables -t nat -A POSTROUTING -o wlp3s0 -s 192.168.56.0/24 -j MASQUERADE
```
<file_sep>/linux/arch/install_sotfs.md
pacman:
yaourt:
(Archlinux 上直接通过 yaourt 命令安装 AUR 源的程序。)
makepkg:
从 AUR 源下载安装
打开AUR 首页 (https://aur.archlinux.org/),在软件包搜索栏输入想要查找的软件包的名称。
选择对应的软件点击进入
将软件包源码下载到本地并解压或者选择用git clone下载源码
进入目录
makepkg
<file_sep>/golang/libs/conf.md
```
go get github.com/spf13/viper
```
<file_sep>/linux/common/tail_head.md
```
tail -n <number>
提取结尾几行
tail -n +<number>
提取第几行之后的所有行:(行数从1 开始)
```
<file_sep>/python/pybabel.md
```
pybabel extract . -F babel.cfg -k _ -k _ko -k _t -o xxxxxxxxxxxx/locale/en_US.pot --copyright-holder="xxxx.xxxx" --project="xxxxx" --version=""
babel.cfg:
[python: src/xxxx/**.py]
[mako: src/xxxx/templates/**.mako]
encoding=utf-8
extensions=xxx,xxx2
默认encoding: ascii 模板中文不通过。
extensions=jinja2.ext.autoescape,jinja2.ext.with_,webassets.ext.jinja2.AssetsExtension
```
<file_sep>/python/str_hex.py
#! /usr/bin/env python
# coding=utf-8
# hex to string
x = 'e8 ae be e5 88 ab e6 95 85 e9 9a 9c 2c e8 ae be e5 88 ab e6 95 85 e9 9a 9c 2c e8 ae be e5 88 ab e6 95 85 e9 9a 9c 2c e8 ae be e5 88 ab e6 95 85 e9 9a 9c'
z = str(bytearray.fromhex(x))
print z
# string to hex
s= "设别故障,设别故障,设别故障,设别故障"
print " ".join("{:02X}".format(ord(c)) for c in s)
# string to hex
x=' '.join(x.encode('hex') for x in 'Hello World!')
print x
print str(bytearray.fromhex(x))<file_sep>/linux/common/expect.md
## install
ubuntu: sudo apt install expect
```
expect:
检查输出,并决定下一步输入. 可用于将若干手工输入替换为自动化输入.
在每一步操作都是明确的,且不需要判断时.可使用 输入重定向. < 输入的内容
命令行 < 操作步骤文件 (将所有输入操作依次写入文件中)
```
<file_sep>/linux/desktop-evn/gnome/0.md
install
```
arch:
pacman -S gnome gnome-extra
然后安装gdm登录管理器 (可使用其他登录器)
pacman -S gnome gdm
将gdm设置为开机自启动,这样开机时会自动载入桌面
systemctl enable gdm
-----------------------------------------------------------------------------------------
```
重置:
```
gsettings list-schemas | xargs -n 1 gsettings reset-recursively
```
<file_sep>/java/java_common/try-with-resource.md
带资源的try语句(try-with-resource)
```
//可指定多个资源,使用 ";" 分隔多个资源语句,末尾不要 ";"
try(Resource res = xx1;Resource2 res2=xxx2)
{
work with res
}
```
try块退出时,会自动调用res.close()方法,关闭资源。<file_sep>/linux/opensuse/1-软件源.md
```
/etc/zypp/ 目录与软件源配置相关
```
```
Oss 主软件源,只含有开源软件。
Non-oss 非自由(相对于自由)软件,如 Flashplayer, Java, Opera, IPW-firmware, RealPlayer 等。
Update 官方安全更新和漏洞修补软件源。
Src-oss 源代码 RPM 包,为高级用户而备。
Src-non-oss 源代码 RPM 包,为高级用户而备。
Debug 调试信息软件包,为高级用户而备。
半官方软件源:这些软件源含有许多有用的包,但不被 openSUSE 官方支持,不过您也不必担心有什么风险。
```
```
/etc/zypp/repos.d 为源配置与红帽系统类似
./repo-oss.repo:
baseurl=http://mirrors.ustc.edu.cn/opensuse/distribution/leap/$releasever/repo/oss/
./repo-update.repo:
baseurl=http://mirrors.ustc.edu.cn/opensuse/update/leap/$releasever/oss/
./repo-non-oss.repo:
baseurl=http://mirrors.ustc.edu.cn/opensuse/distribution/leap/$releasever/repo/non-oss/
./repo-update-non-oss.repo:
baseurl=http://mirrors.ustc.edu.cn/opensuse/update/leap/$releasever/non-oss/
```
```
https://cn.opensuse.org/%E8%BD%AF%E4%BB%B6%E6%BA%90
http://mirrors.ustc.edu.cn/opensuse/
http://mirrors.163.com/openSUSE/
https://mirrors.huaweicloud.com/opensuse/
http://download.opensuse.org/repositories/home:/opensuse_zh/openSUSE_Tumbleweed/
```
<file_sep>/java/tomcat/运程调试.md
```
tomcat 的java启动参数中添加: ()
-agentlib:jdwp=transport=dt_socket,address=0.0.0.0:5005,server=y,suspend=n
```
<file_sep>/linux/common/disk.md
分区:
fdisk
cfdisk
格式化
mkfs.bfs mkfs.ext2 mkfs.fat mkfs.msdos mkfs.reiserfs
mkfs.btrfs mkfs.ext3 mkfs.jfs mkfs.nilfs2 mkfs.vfat
mkfs.cramfs mkfs.ext4 mkfs.minix mkfs.ntfs mkfs.xfs
disk uuid
`blkid /dev/sda1`
#### fdisk扩大分区容量
参考:<https://blog.csdn.net/chengxuyuanyonghu/article/details/51746234>
1、卸载磁盘
2、磁盘分区
```
fdisk /dev/sdb
p #查看磁柱号 ,记住,后面要用到
d #删除之前的分区
n #建立新分区
p #主分区
1 #第一个主分区
删除之前的分区,然后建立新分区,注意开始的磁柱号要和原来的一致(保证数据不丢失的关键步骤),结束的磁柱号默认回车使用全部磁盘。
wq #保存分区信息并退出
```
3、调整分区
```
e2fsck -f /dev/sdb1 #检查分区信息
resize2fs /dev/sdb1 #调整分区大小
```
4、重新挂载分区
查看硬盘类型:
```
cat /sys/block/*/queue/rotational的返回值
----------------------------------------------------------------------
# lsblk -d -o name,rota
NAME ROTA
sda 1
sdb 0
rota
1: 机械盘
0:固态盘
----------------------------------------------------------------------
sudo pacman -S smartmontools
sudo smartctl --all /dev/sd<a/b/c> |less
Rotation Rate: ... rpm :机械盘
Rotation Rate: Solid State Device :固态盘
```
```
硬盘阵列
硬盘分区管理
硬盘卷管理
硬盘配额管理 (quote)
```
<file_sep>/python/env.md
PYTHONPATH是Python搜索路径,默认我们import的模块都会从PYTHONPATH里面寻找。
开发阶段和将项目的顶层目录放入 PYTHONPATH 方便查找模块。
```
# 列举模块
# py 程序所在的目录,会一起打印出来。
import sys
module = sys.path
for i in module:
print(i)
```
LD_LIBRARY_PATH: 有时候python 运行时缺少系统lib 。 需将一些 so 文件的目录设置到 LD_LIBRARY_PATH
```
python 连接oracle:
需安装 client 并设置
export LD_LIBRARY_PATH=/usr/lib/oracle/12.1/client64/lib:$LD_LIBRARY_PATH
才能连接oracle
```
<file_sep>/linux/common/pgrep.md
查看进程PID专用工具 pgrep
```
当前用户所有进程号: pgrep -u $USER
当前用户所有进程号+进程名: pgrep -l -u $USER
-l : 显示pid 和进程名
-u : 过滤用户
-x : 进程名精确查找
$ pgrep -l -u $USER Typo
1619 Typora
1621 Typora
1651 Typora
$ pgrep -l -x -u $USER Typora
1619 Typora
1621 Typora
1651 Typora
更多用法:
pgrep -h
man pgrep
```
<file_sep>/linux/softwaremanager/pacman/pkgbuild/makepkg.md
Arch的打包系统和别的Linux发行版不一样,用ABS系统(Arch Build System)把源代码打包成
.pkg.tar.gz / .pkg.tar.xz 才能安装。
创建`PKGBUILD`文件,也可复制PKGBUILD模板(位于/usr/share/pacman/PKGBUILD.proto)到工作目录或复制一个类似包的PKGBUILD。
复制要编译的脚本到创建的目录中,修改编译脚本。然后在该目录下运行:
> $ makepkg -s
makepkg工具会寻找PKGBUILD文件,根据该文件编译并生成一个*.pkg.tar.gz的文件包,Archlinux采用pacman管理安装包。最后用pacman安装编译生成的包。
```
# pacman -U *.pkg.tar.gz
```
```
/etc/makepkg.conf 打包配置文件
```
```
makepkg
makepkg --syncdeps
makepkg --install
makepkg --clean
```
```
编写: PKGBUILD
生成软件包: makepkg -s
安装软件包: sudo pacman -U <软件包>
```
PKGBUILD 文件说明
```
# Maintainer: 软件维护者用户信息 <邮箱>
#包名
pkgname=
# 软件版本
pkgver=
pkgrel=1
epoch=1
# 软件包描述
pkgdesc=""
# 软件架构
# arch=('i686' 'x86_64')
arch=(x86_64)
# 软件网站
url=
# 许可类型
license=('GPL')
groups=()
depends=()
makedepends=()
checkdepends=()
# 软件依赖
optdepends=(
'依赖包1'
'依赖包2'
)
provides=()
conflicts=()
replaces=()
backup=()
options=()
install=
changelog=
#源码,可以是本地包,也可以是网络包
source=("./$pkgname-$pkgver.tar.gz")
# 源码 md5sum (未填写makepkg 校验将不通过)
md5sums=(ce4c0......)
# 可替代md5sum,不使用时注释掉
sha256sums=
validpgpkeys=()
# ${srcdir}: 源码目录,会默认创建src 目录,将源码解压到src 目录。
# ${pkgdir} : 打包目录: 会默认创建"pkg/包名" 目录
prepare() {
cd "${srcdir}"
}
# 打包步骤
package() {
# 编译源码
cd "${srcdir}"
make
# 创建安装相关目录
mkdir -p "${pkgdir}/usr/bin"
#将相关文件放入对应目录
cp xx "${pkgdir}/usr/bin"
}
```
```
有道词典:
# Maintainer: <NAME> <<EMAIL>>
pkgname=youdao-dict
pkgver=1.1.0
pkgrel=2
pkgdesc='YouDao Dictionary'
arch=('i686' 'x86_64')
url='http://cidian.youdao.com/index-linux.html'
license=('GPL3')
depends=(
'desktop-file-utils'
'hicolor-icon-theme'
'python'
'python-pyqt5'
'python-requests'
'python-xlib'
'python-pillow'
'tesseract-data-eng'
'tesseract-data-chi_tra'
'tesseract-data-chi_sim'
'python-lxml'
'python-xdg'
'python-webob'
'qt5-webkit'
'qt5-graphicaleffects'
'qt5-quickcontrols'
)
install=youdao-dict.install
source=('youdao-arch.patch')
source_i686=('http://codown.youdao.com/cidian/linux/youdao-dict_1.1.0-0~i386.tar.gz')
source_x86_64=('http://codown.youdao.com/cidian/linux/youdao-dict_1.1.0-0~amd64.tar.gz')
sha256sums=('ab1e8cf2b38c459c60af5e47814a022ad485d2e2c0ae257ffae4c03174e703a6')
sha256sums_i686=('d1ff404f1e465d6a196b566294ddfea1a1bfe4568226201b65d74236407152fc')
sha256sums_x86_64=('5c3a5ed105238e2fad181704fd99815c4275bf546136f99e817614188794dc07')
prepare() {
cd "${srcdir}/src"
patch -Np2 -i "${srcdir}/youdao-arch.patch"
}
package() {
cd "${srcdir}"
mkdir -p "${pkgdir}/usr/bin"
mkdir -p "${pkgdir}/usr/share/youdao-dict"
mkdir -p "${pkgdir}/usr/share/applications"
mkdir -p "${pkgdir}/usr/share/dbus-1/services"
mkdir -p "${pkgdir}/usr/share/icons/hicolor/48x48/apps"
mkdir -p "${pkgdir}/usr/share/icons/hicolor/scalable/apps"
mkdir -p "${pkgdir}/etc/xdg/autostart"
cp -r src/* "${pkgdir}/usr/share/youdao-dict"
cp -r data/hicolor/* "${pkgdir}/usr/share/icons/hicolor/"
cp data/youdao-dict.desktop "${pkgdir}/usr/share/applications/"
cp data/youdao-dict-autostart.desktop "${pkgdir}/etc/xdg/autostart/"
cp data/com.youdao.backend.service "${pkgdir}/usr/share/dbus-1/services/"
chmod 755 "${pkgdir}/usr/share/youdao-dict/main.py"
chmod 755 "${pkgdir}/usr/share/youdao-dict/youdao-dict-backend.py"
ln -sf /usr/share/youdao-dict/main.py "${pkgdir}/usr/bin/youdao-dict"
}
```
```
在 PKGBUILD 所在目录执行 makepkg --source,会生成 .src.tar.gz 源码包,这就是需要上传到 AUR 的东西,注意不要把任何二进制文件加入源码包。
在 PKGBUILD 所在目录执行 makepkg 可生成用于安装的包: sudo pacman -U 包名 (安装生成的包)
```
```
解压软件包
$ tar -I zstd -xvf archive.tar.zst
```
<file_sep>/js/avalon/start.md
```
https://github.com/RubyLouvre/avalon
http://avalonjs.coding.me/
支持ie8
```
<file_sep>/linux/ubuntu/virtualbox.md
http://blog.csdn.net/hawkdowen/article/details/38357771
1. vbox全局设置
新建host-only网络。一般网络名会是vboxnet0,默认IP地址为192.168.56.1(可以自定义),子网掩码:255.255.255.0。
dhcp 可以选择性开启
2. 虚拟机网卡选择host-only,界面名称 选择步骤1 的网络
3. 虚拟机配置好网络
4. ubuntu 开启网络转发
5.
编辑/etc/sysctl.conf (root权限)
取消注释 : net.ipv4.ip_forward=1
执行 : sudo sysctl -p 此时,网络转发功能应该就开启了
可以使用如下命令验证: cat /proc/sys/net/ipv4/ip_forward 命令返回1,说明网络转发已开启。
配置网络转发规则:
sudo iptables -t nat -A POSTROUTING -o eth0 -s 192.168.56.0/24 -j MASQUERADE
eth0 改为上网的网卡, 192.168.56.0 改为上网的网段
sudo iptables -t nat -A POSTROUTING -o wlp6s0 -s 192.168.4.0/24 -j MASQUERADE
配置网络转发规则(临时生效)可以把
iptables -t nat -A POSTROUTING -o wlp6s0 -s 192.168.4.0/24 -j MASQUERADE
加入到 /etc/rc.local 使其开机生效
有多个网卡可以加多条
linux 虚拟机IP配置:
IPADDR=192.168.4.30
NETMASK=255.255.255.0
GATEWAY=192.168.4.1
DNS1=192.168.2.1
DNS2=192.168.1.1
NAME="enp0s3"
DEVICE="enp0s3"
ONBOOT="yes"
2note:ip配置文件末尾不要有空行
Arch:
启动firewall: systemctl entable/start iptables
```
编辑/etc/sysctl.conf (root权限)
取消注释 : net.ipv4.ip_forward=1
执行 : sudo sysctl -p 此时,网络转发功能应该就开启了
* 可以使用如下命令验证: cat /proc/sys/net/ipv4/ip_forward 命令返回1,说明网络转发已开启。
iptables -N fw-open
iptables -A FORWARD -j fw-open
iptables -t nat -A POSTROUTING -o wlp3s0 -s 192.168.56.0/24 -j MASQUERADE
```
| a48388aba68d8bcb16e7edcc9af6aa10f0474320 | [
"Markdown",
"Python"
] | 474 | Markdown | QPJIANG/NoteSome | 5e4e4a898c097702dadc9a1fb262a205713c4653 | 1be837c5dc43656986ae5ef7adcf167b2db5899b |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.