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>package tp.tools.algorithm; import tp.tools.*; import tp.tools.Form2D.Point2D; import java.util.ArrayList; import java.util.List; /** * Created by jimmy on 25/04/15. */ public class Graham implements Algorithm<List<Point2D>, List<Point2D>> { @Override public List<Point2D> run(List<Point2D> liste) { // liste deja triée List<Point2D> lUpper = new ArrayList<Point2D>(); List<Point2D> lLower = new ArrayList<Point2D>(); int n = liste.size(); // BEGIN UPPER lUpper.add(liste.get(0)); lUpper.add(liste.get(1)); for(int i=2 ; i<n ; i++) { lUpper.add(liste.get(i)); while(lUpper.size()>2 && Point2D.isLeft(lUpper.get(lUpper.size()-3), lUpper.get(lUpper.size()-2), lUpper.get(lUpper.size()-1))) { lUpper.remove(lUpper.get(lUpper.size()-2)); } } // END UPPER // BEGIN LOWER lLower.add(liste.get(n-1)); lLower.add(liste.get(n-2)); for(int i=n-1 ; i>=0 ; i--) { lLower.add(liste.get(i)); while(lLower.size()>2 && Point2D.isLeft(lLower.get(lLower.size()-3), lLower.get(lLower.size()-2), lLower.get(lLower.size()-1))) { lLower.remove(lLower.get(lLower.size()-2)); } } lLower.remove(0); lLower.remove(lLower.size()-1); // END LOWER // Fusion des 2 listes (haut et bas) lUpper.addAll(lLower); return lUpper; } } <file_sep>package tp.tools.others; public enum RolePoint { NONE, BEGIN, END, INTERSECT, ZONE } <file_sep>package tp.tools.visualisation; import java.util.LinkedList; import java.util.List; /** * Created by jimmy on 26/04/15. */ public abstract class Controller { private LinkedList<View> _view = new LinkedList<View>(); public LinkedList<View> getView() { return _view; } public void addView(View view) { _view.add(view); } public void repaintView() { for(View v : _view) { v.repaint(); } } } <file_sep>package tp.tools.algorithm; import tp.tools.Form2D.*; import tp.tools.Form2D.needRefactor.Segment; import java.util.*; /** * Created by jimmy on 25/04/15. */ public class AlphaShape implements Algorithm<List<Triangle2D>, List<Segment2D>> { private int _alpha = 0; private List<Point2D> _points = new ArrayList<Point2D>(); @Override public List<Segment2D> run(List<Triangle2D> triangles) { List<Segment2DWithTriangle2D> segments = new ArrayList<Segment2DWithTriangle2D>(); List<Triangle2D> sorted = new ArrayList<Triangle2D>(); sorted.addAll(triangles); Set<Point2D> points = new TreeSet<Point2D>(); for(Triangle2D triangle2D : sorted) { points.addAll(triangle2D.getPoints()); for(Segment2D edge : triangle2D.getEdges()) { Segment2DWithTriangle2D segment2D1 = new Segment2DWithTriangle2D(edge.getP1(),edge.getP2(),triangle2D); boolean isIn = false; int k = 0; while(k < segments.size() && !isIn) { if(segments.get(k).isSameSegment(edge)) isIn = true; k++; } // if(segments.contains(segment2D1)) if(isIn) { // System.out.println("SECOND"); /* for(int i=0;i<segments.size();++i) { if(segments.get(i).equals(segment2D1)){ segments.get(i).addTriangle(triangle2D); } } */ segments.get(k-1).addTriangle(triangle2D); } else segments.add(segment2D1); } } List<Segment2D> result = new ArrayList<Segment2D>(); for(Segment2DWithTriangle2D segment : segments) { Circle2D c = segment.giveCircle(); boolean found = false; for(Point2D point: points) { if(!segment.havePoint(point) && c.isInCircle(point)) { found = true; break; } } double rT = new Circle2D(segment.getTriangles().get(0)).getRadius(); double rT2 = Double.MAX_VALUE; if(segment.getTriangles().size()>1) rT2= new Circle2D(segment.getTriangles().get(1)).getRadius(); double a,b; if(!found) { a = segment.length()/2.0; b = (segment.getTriangles().size()>1)? Math.max(rT, rT2) : rT; } else { a = (segment.getTriangles().size()>1)? Math.min(rT,rT2) : rT; b = (segment.getTriangles().size()>1)? Math.max(rT,rT2) : rT; } if(a<= _alpha && _alpha <= b) result.add(segment); } /* int i = 0; int j = 0; for(Segment2DWithTriangle2D segment2DWithTriangle2D : segments) { if(segment2DWithTriangle2D.getTriangles().size() == 1) { i++; } else if(segment2DWithTriangle2D.getTriangles().size() == 2) { j++; } else { System.out.println("BUG MERDE"); } } System.out.println(i); System.out.println(j); result.addAll(segments); System.out.println(triangles.size()); System.out.println(result.size()); */ return result; } /* @Override public List<Segment2DWithTriangle2D> run(List<Triangle2D> triangles) { List<Segment2DWithTriangle2D> alphaTriangulation = new ArrayList<Segment2DWithTriangle2D>(); Set<Segment2DWithTriangle2D> segments = new HashSet<Segment2DWithTriangle2D>(); for(Triangle2D triangle : triangles) { Segment2DWithTriangle2D s1 = new Segment2DWithTriangle2D(triangle.getA(), triangle.getB(), _points, _alpha); Segment2DWithTriangle2D s2 = new Segment2DWithTriangle2D(triangle.getB(), triangle.getC(), _points, _alpha); Segment2DWithTriangle2D s3 = new Segment2DWithTriangle2D(triangle.getC(), triangle.getA(), _points, _alpha); if(segments.contains(s1)) s1.setTriangle2(triangle); else { s1.setTriangle(triangle); segments.add(s1); } if(segments.contains(s2)) s2.setTriangle2(triangle); else { s2.setTriangle(triangle); segments.add(s2); } if(segments.contains(s3)) s3.setTriangle2(triangle); else { s3.setTriangle(triangle); segments.add(s3); } } for(Segment2DWithTriangle2D segment : segments) { segment.calculShape(); if(segment.isOk()) alphaTriangulation.add(segment); } return alphaTriangulation; } */ public int getAlpha() { return _alpha; } public void setAlpha(int alpha) { _alpha = alpha; } public List<Point2D> getPoints() { return _points; } public void setPoints(List<Point2D> points) { _points = points; } } <file_sep>package tp.tp1; import tp.tools.visualisation.Controller; import tp.tools.visualisation.FrameGeometric; public class MainTp1 { public static void main(String[] args) { FrameGeometric frame = new FrameGeometric ("TP1 - Intersection de segments"); int width = 612; int height = 792; ControllerTP1 controllerTP1 = new ControllerTP1(); ViewIntersectSegment vRP1 = new ViewIntersectSegment(width, height, controllerTP1); controllerTP1.addView(vRP1); vRP1.drawListRandomSegment(50); frame.addView(vRP1, "Random Point"); frame.setFrame(); } } <file_sep>package tp.tools.Form2D; /** * Created by jimmy on 15/04/15. */ public class Circle2D { private double _posX; private double _posY; private double _radius; public Circle2D(Point2D center, double radius) { _posX = center.getX(); _posY = center.getY(); _radius = radius; } public Circle2D(double x, double y, double radius) { _posX = x; _posY = y; _radius = radius; } public Circle2D(Triangle2D triangle) { int x1 = triangle.getA().getX(); int y1 = triangle.getA().getY(); int x2 = triangle.getB().getX(); int y2 = triangle.getB().getY(); int x3 = triangle.getC().getX(); int y3 = triangle.getC().getY(); double v,m1, m2, m3, n1, n2, n3; m1 = 2.*(x3-x2); m2 = -2.*(y2-y3); m3 = (y2-y3)*(y2+y3)-(x3-x2)*(x2+x3); n1 = 2.*(x3-x1); n2 = -2.*(y1-y3); n3 = (y1-y3)*(y1+y3)-(x3-x1)*(x1+x3); v=1./(n2*m1-n1*m2); _posX = v*(n3*m2-n2*m3); _posY = v*(n1*m3-n3*m1); double r = new Vector2D(new Point2D((int) _posX, (int) _posY), triangle.getA()).norm(); _radius = r; } public boolean isInCircle(Point2D point2D) { Vector2D vector = new Vector2D(new Point2D((int) _posX, (int) _posY),point2D); return Math.abs(vector.norm()) < Math.abs(_radius); } public double getRadius() { return _radius; } } <file_sep>package tp.tp1; import tp.tools.visualisation.Controller; /** * Created by jimmy on 26/04/15. */ public class ControllerTP1 extends Controller { } <file_sep>package tp.tools.Form2D.needRefactor; import tp.tools.others.ColorTools; import tp.tools.others.RolePoint; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Rectangle; import java.util.ArrayList; import java.util.List; import java.util.Random; public class PointSegment extends Rectangle{ private static final long serialVersionUID = 1L; public static int size = 3; private Color color; private RolePoint role; private Segment segment; public PointSegment() { } public PointSegment(int x, int y, RolePoint r) { super(x ,y, 2 * PointSegment.size,2 * PointSegment.size); this.role = r; switch(role){ case BEGIN: color = ColorTools.POINT_BEGIN; break; case INTERSECT: color = ColorTools.POINT_INTERSECT; break; case END: color = ColorTools.POINT_END; break; } } public void drawPointSegment(Graphics2D g2d) { g2d.setColor(color); this.translate(-PointSegment.size, -PointSegment.size); g2d.fill(this); this.translate(PointSegment.size, PointSegment.size); } public void print() { System.out.println("x = " + x + " y = " + y+" w = " + width + " h = " + height + " role = "+role); } public Color getColorPoint() { return color; } public void setColorPoint(Color color) { this.color = color; } public RolePoint getRolePoint() { return role; } public void setRolePoint(RolePoint role) { this.role = role; } public Segment getSegmentPoint() { return segment; } public void setSegmentPoint(Segment segment) { this.segment = segment; } public boolean isLeftOf(PointSegment p2) { if(this.getX() < p2.getY()) return true; return false; } public static double calculCoordX(double m1, double p1, double m2, double p2) { if((m1 - m2) == 0) return 0; else return ((p2 - p1) / (m1 - m2)); } public static double calculCoordY(double m, double p, double x) { return (m * x) + p; } public static List<PointSegment> randomPoint(int nbPoint, int w, int h) { List<PointSegment> points = new ArrayList<PointSegment>(); Random rand = new Random(); while(points.size() <= nbPoint) { PointSegment p = new PointSegment(rand.nextInt(500), rand.nextInt(700), RolePoint.BEGIN); double centerX = w / 2; double centerY = h / 2; PointSegment center = new PointSegment((int)centerX, (int)centerY, RolePoint.END); if(center.distance(p) < 200 && center.distance(p) > 100) { System.out.println(center.distance(p)); points.add(p); } } return points; } public int distance (PointSegment p) { int X = (int) ((p.getX() - this.getX()) * (p.getX() - this.getX())); int Y = (int) ((p.getY() - this.getY()) * (p.getY() - this.getY())); return (int) Math.sqrt(X + Y); } } <file_sep>package tp.tools.Form2D; public class StructureGeometrique { private String _name; public StructureGeometrique(String name) { _name = name; } public String getName() { return _name; } public void setName(String name) { _name = name; } } <file_sep>package tp.tools.algorithm; import tp.tools.Form2D.Point2D; import tp.tools.others.RolePoint; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Created by jimmy on 25/04/15. */ public class RandomPoint2D implements Algorithm <Integer, List<Point2D>> { private int _wight; private int _heigth; public RandomPoint2D(int wight, int heigth) { _wight = wight; _heigth = heigth; } @Override public List<Point2D> run(Integer numberPoint2D) { List<Point2D> points = new ArrayList<Point2D>(); Random rand = new Random(); while(points.size() <= numberPoint2D) { Point2D p = new Point2D(rand.nextInt(_wight+25)-25, rand.nextInt(_heigth+25)-25); double centerX = _wight / 2; double centerY = _heigth / 2; Point2D center = new Point2D((int)centerX, (int)centerY); if(center.distance(p) < 280) { int minDisteance = 25; boolean pointOk = true; for(Point2D point : points) { if(p.distance(point) < minDisteance) { pointOk = false; break; } } if(pointOk) { points.add(p); p.setName(""+ points.indexOf(p)); } } } Collections.sort(points); return points; } } <file_sep>package tp.tools.algorithm; import tp.tools.Form2D.Triangle2D; import java.util.ArrayList; import java.util.List; /** * Created by jimmy on 25/04/15. */ public class Delaunay implements Algorithm<List<Triangle2D>, List<Triangle2D>> { @Override public List<Triangle2D> run(List<Triangle2D> triangles) { List<Triangle2D> triangulation = new ArrayList<Triangle2D>(); triangulation.addAll(triangles); boolean flip = true; int cpt = 0; while(flip && cpt < 100) { flip = false; for(int i=0;i<triangulation.size();++i) { for(Triangle2D t : triangulation) { if(triangulation.get(i) != t && triangulation.get(i).isVoisin(t) && triangulation.get(i).isFlippable(t)) { triangulation.get(i).flip(t); flip = true; } } } cpt++; } return triangulation; } } <file_sep>package tp.tools.visualisation; import tp.tools.others.ColorTools; import java.awt.Dimension; import javax.swing.JPanel; public abstract class View extends JPanel { private static final long serialVersionUID = 1L; private int width; private int height; private Controller controller; public View(int width, int height, Controller controller) { this.width = width; this.height = height; this.controller = controller; setPreferredSize(new Dimension(width, height)); setBackground(ColorTools.BACKGROUND); } @Override public int getWidth() { return width; } @Override public int getHeight() { return height; } public Controller getController() { return controller; } public void setController(Controller controller) { this.controller = controller; } } <file_sep>package tp.tools.visualisation; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTabbedPane; public class FrameGeometric extends JFrame{ private static final long serialVersionUID = 1L; private JTabbedPane tabbedPane; public FrameGeometric (String name) { super(name); this.tabbedPane = new JTabbedPane(); this.add(tabbedPane); } public void setFrame() { this.add(this.tabbedPane); this.pack(); this.setVisible(true); this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); } public void addView(View v1, String name) { JPanel panel = new JPanel(); panel.add(v1); tabbedPane.add(name, panel); } } <file_sep>package tp.tools.Form2D; import tp.tools.Form2D.needRefactor.Segment; import tp.tools.others.ColorTools; import tp.tools.others.RolePoint; import java.awt.Color; import java.awt.Graphics2D; import java.util.ArrayList; import java.util.List; public class Segment2D extends StructureGeometrique { private Point2D _p1; private Point2D _p2; private Color lineColor; public Segment2D(Point2D p1, Point2D p2) { super(""); if(p1.isInFirstX(p2)) { _p1 = p1; _p2 = p2; } else { _p1 = p2; _p2 = p1; } this.lineColor = ColorTools.SEGMENT; } public Segment2D(String name, Point2D p1, Point2D p2) { super(name); _p1 = p1; _p2 = p2; this.lineColor = ColorTools.SEGMENT; } public Point2D getP1() { return _p1; } public void setP1(Point2D p1) { _p1 = p1; } public Point2D getP2() { return _p2; } public void setP2(Point2D p2) { _p2 = p2; } public void draw(Graphics2D g2d) { g2d.setColor(lineColor); g2d.drawLine(_p1.getX(), _p1.getY(), _p2.getX(), _p2.getY()); } public Color getLineColor() { return lineColor; } public boolean intersectent(Segment2D s) { Vector2D VP1P2 = new Vector2D(this.getP1(), this.getP2()); Vector2D VP3P4 = new Vector2D(s.getP1(), s.getP2()); Vector2D VP1P3 = new Vector2D(this.getP1(), s.getP1()); Vector2D VP1P4 = new Vector2D(this.getP1(), s.getP2()); Vector2D VP3P1 = new Vector2D(s.getP1(), this.getP1()); Vector2D VP3P2 = new Vector2D(s.getP1(), this.getP2()); float detS1 = VP1P2.determinant(VP1P3); float detS2 = VP1P2.determinant(VP1P4); float detS3 = VP3P4.determinant(VP3P1); float detS4 = VP3P4.determinant(VP3P2); if ((detS1 * detS2) < 0 && (detS3 * detS4) < 0) return true; return false; } public Point2D getIntersectedPoint(Segment2D s) { double m1 = this.calculCoefSegment(); double p1 = this.calculConstSegment(m1); double m2 = s.calculCoefSegment(); double p2 = s.calculConstSegment(m2); double coordX = Point2D.calculCoordX(m1, p1, m2, p2); double coordY = Point2D.calculCoordY(m1, p1, coordX); Point2D ps = new Point2D((int) coordX , (int) coordY, RolePoint.INTERSECT); return ps; } public double calculCoefSegment() { if((_p2.getX() - _p1.getX()) == 0) return 0; else return (_p2.getY()-_p1.getY()) / (_p2.getX() - _p1.getX()); } public double calculConstSegment(double m) { return _p1.getY() - (m * _p1.getX()); } public static List<Segment2D> constructSegment (List<Point2D> points) { List<Segment2D> segments = new ArrayList<Segment2D>(); for(int i = 0; i < points.size() - 1; i = i + 2) segments.add(new Segment2D(points.get(i), points.get(i + 1))); return segments; } public void setLineColor(Color lineColor) { this.lineColor = lineColor; } public boolean isSameSegment(Segment2D s) { if(getP1().getX() == s.getP1().getX() && getP1().getY() == s.getP1().getY() && getP2().getX() == s.getP2().getX() && getP2().getY() == s.getP2().getY()) return true; if(getP1().getX() == s.getP2().getX() && getP1().getY() == s.getP2().getY() && getP2().getX() == s.getP1().getX() && getP2().getY() == s.getP1().getY()) return true; return false; } } <file_sep>package tp.tp1; import tp.tools.Form2D.needRefactor.PointSegment; import tp.tools.Form2D.needRefactor.Segment; import tp.tools.others.ColorTools; import tp.tools.others.SweepLine; import tp.tools.others.RolePoint; import tp.tools.visualisation.Controller; import tp.tools.visualisation.View; import java.awt.Color; import java.awt.Dimension; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.RenderingHints; import java.awt.event.*; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Stack; import java.util.TreeSet; public class ViewIntersectSegment extends View implements MouseWheelListener, MouseListener, KeyListener, MouseMotionListener{ private static final long serialVersionUID = 1L; private Color bgColor = ColorTools.BACKGROUND; private Color fgColor = ColorTools.POINT_ZONE; private int width; private int height; private List<Segment> segments; private SweepLine sweepLine; // Pour placer les point à la main private PointSegment p1; private PointSegment p2; private boolean startDrawSegment = false; private Segment segmentCourant; public ViewIntersectSegment(int width, int height, ControllerTP1 controller) { super(width, height, controller); this.segments = new ArrayList<Segment>(); this.width = width; this.height = height; this.sweepLine = new SweepLine(this); this.p1 = new PointSegment(); this.p2 = new PointSegment(); setPreferredSize(new Dimension(width, height)); setBackground(bgColor); addMouseListener(this); addMouseWheelListener(this); addKeyListener(this); addMouseMotionListener(this); setFocusable(true); requestFocus(); } public void drawListRandomSegment (int numberSegments) { segments = Segment.randomSegment(numberSegments); } public void drawListIntersectRandomSegment() { List<Segment> segmentsIntersect = new ArrayList<Segment>(); for(Segment ss1: segments) { for(Segment ss2: segments) { if(!ss1.equals(ss2)) { if(ss1.intersectent(ss2)) { if(!segmentsIntersect.contains(ss1)) segmentsIntersect.add(ss1); if(!segmentsIntersect.contains(ss2)) segmentsIntersect.add(ss2); } } } } segments = segmentsIntersect; System.out.println("Numbre intersect : " + segments.size()); } public void drawListIntersectRandomSegmentBentleyOttman() { List<Segment> segmentsIntersect = new ArrayList<Segment>(); List<PointSegment> ech = new ArrayList<PointSegment>(); Stack<PointSegment> ech2 = new Stack<PointSegment>(); List<PointSegment> leftPointSegment = new ArrayList<PointSegment>(); List<PointSegment> rightPointSegment = new ArrayList<PointSegment>(); for(Segment s : segments) { ech.add(s.getLeftPoint()); ech.add(s.getRightPoint()); leftPointSegment.add(s.getLeftPoint()); rightPointSegment.add(s.getRightPoint()); } Collections.sort(ech, new Comparator<PointSegment>() { @Override public int compare(PointSegment o1, PointSegment o2) { if (o1.getX() < o2.getX()) return -1; else if (o1.getX() == o2.getX()) return 0; else return 1; } }); Collections.reverse(ech); ech2.addAll(ech); TreeSet<Segment> verticalOrder = new TreeSet<Segment>( new Comparator<Segment>() { @Override public int compare(Segment o1, Segment o2) { if (o1.getLeftPoint().getY() < o2.getRightPoint().getY()) return -1; else if (o1 == o2) return 0; else if (o1.getLeftPoint().getY() == o2.getLeftPoint().getY() && o1.getRightPoint().getY() < o2.getRightPoint().getY()) return -1; else if (o1.getLeftPoint().getY() == o2.getLeftPoint().getY() && o1.getRightPoint().getY() > o2.getRightPoint().getY()) return 1; else return 1; } }); int position = 0; //for(PointSegment p : ech){ while(!ech2.isEmpty()) { PointSegment p = ech2.pop(); if(leftPointSegment.contains(p)) { position = leftPointSegment.indexOf(p); Segment s1 = leftPointSegment.get(position).getSegmentPoint(); verticalOrder.add(s1); Segment s2 = verticalOrder.higher(s1); if (s2 != null) { if (s2.intersectent(s1)) { if(!segmentsIntersect.contains(s1)) segmentsIntersect.add(s1); if(!segmentsIntersect.contains(s2)) segmentsIntersect.add(s2); PointSegment intersect = s2.getIntersectedPoint(s1); ech2.add(intersect); } } s2 = verticalOrder.lower(s1); if (s2 != null) { if (s2.intersectent(s1)) { if(!segmentsIntersect.contains(s1)) segmentsIntersect.add(s1); if(!segmentsIntersect.contains(s2)) segmentsIntersect.add(s2); PointSegment intersect = s2.getIntersectedPoint(s1); ech2.add(intersect); } } } if(rightPointSegment.contains(p)) { position = rightPointSegment.indexOf(p); Segment s1 = rightPointSegment.get(position).getSegmentPoint(); Segment upper = verticalOrder.higher(s1); Segment downer = verticalOrder.lower(s1); if (upper != null && downer != null) { if (upper.intersectent(downer)) { if(!segmentsIntersect.contains(upper)) segmentsIntersect.add(upper); if(!segmentsIntersect.contains(downer)) segmentsIntersect.add(downer); PointSegment intersect = upper.getIntersectedPoint(downer); ech2.add(intersect); } } verticalOrder.remove(s1); } } segments = segmentsIntersect; System.out.println("Numbre intersect : " + segments.size()); } public void paintComponent(Graphics g) { super.paintComponent(g); Graphics2D g2d = (Graphics2D) g; g2d.setPaintMode(); g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(fgColor); if(segmentCourant != null && !segments.contains(segmentCourant)) segmentCourant.drawSegment(g2d); for (Segment lg: segments) { lg.drawSegment(g2d); lg.getRightPoint().drawPointSegment(g2d); lg.getLeftPoint().drawPointSegment(g2d); //g2d.drawString("Hello world", 150, 150); g2d.setColor(ColorTools.POINT_NONE); g2d.drawString(lg.getNameSegment(), (int) lg.getLeftPoint().getX()-5, (int) lg.getLeftPoint().getY()-5); } sweepLine.setG2d(g2d); setIntersectedPoint(); drawIntersectedPoint(g2d); sweepLine.dessine(g2d); } @Override public void mouseClicked(MouseEvent e) { if (e.getClickCount() == 1) { if(!startDrawSegment) { p1 = new PointSegment ((int) e.getPoint().getX(), (int) e.getPoint().getY(), RolePoint.BEGIN); p2 = new PointSegment ((int) e.getPoint().getX(), (int) e.getPoint().getY(), RolePoint.END); startDrawSegment = true; segmentCourant = new Segment(p1, p2); repaint(); } else { startDrawSegment = false; segments.add(segmentCourant); segmentCourant.setNameSegment("S" + (segments.size() - 1)); repaint(); } } } @Override public void mouseEntered(MouseEvent arg0) { } @Override public void mouseExited(MouseEvent arg0) { } @Override public void mousePressed(MouseEvent arg0) { } @Override public void mouseReleased(MouseEvent arg0) { } @Override public void mouseWheelMoved(MouseWheelEvent e) { int scrollUnit = e.getWheelRotation(); if (scrollUnit > 0) sweepLine.next(2); repaint(); } public List<Segment> getSegments() { return segments; } public void setSegments(List<Segment> segments) { this.segments = segments; } @Override public void keyTyped(KeyEvent key) { } @Override public void keyPressed(KeyEvent key) { if(key.getKeyCode() == 107) // key : + sweepLine.next(2); repaint(); } @Override public void keyReleased(KeyEvent key) { } public int getWidth() { return width; } public int getHeight() { return height; } public void setIntersectedPoint() { sweepLine.addListPointSegment(segments); } public void drawIntersectedPoint(Graphics2D g2d) { sweepLine.drawListPointSegment(g2d); } @Override public void mouseDragged(MouseEvent mouseEvent) { } @Override public void mouseMoved(MouseEvent e) { if(startDrawSegment) { p2 = new PointSegment((int) e.getPoint().getX(), (int) e.getPoint().getY(), RolePoint.END); segmentCourant = new Segment(p1, p2); repaint(); } } } <file_sep>package tp.tools.others; import tp.tools.visualisation.View; import tp.tools.Form2D.needRefactor.PointSegment; import tp.tools.Form2D.needRefactor.Segment; import java.awt.BasicStroke; import java.awt.Color; import java.awt.Graphics2D; import java.awt.Stroke; import java.util.ArrayList; import java.util.List; public class SweepLine { private int width; private int height; private int position; private int stepWidth; private List<PointSegment> intersectedPointSegment; private View view; private Graphics2D g2d; public SweepLine(View v){ this.intersectedPointSegment = new ArrayList<PointSegment>(); this.position = 0; this.view = v; this.width = view.getWidth(); this.height = view.getHeight(); this.stepWidth = width/100; } public void dessine(Graphics2D g) { g.setColor(Color.RED.darker()); Stroke s = g.getStroke(); g.setStroke(new BasicStroke(2)); g.drawLine(position,0,position,height); g.setStroke(s); } public void next() { int temp = position++; if(temp <= (width - stepWidth) + 5) { position++; } else { position = (width - stepWidth) + 5; } } public void next(int speed) { int temp = position + speed; if(temp <= (width - stepWidth) + 5) { position += speed; } else { position = (width - stepWidth) + 5; } for(PointSegment point : intersectedPointSegment) { if(position > point.getCenterX()) { point.setColorPoint(Color.RED); } } } public void removeListPoint() { intersectedPointSegment.clear(); } public void removeListPoint(PointSegment point) { intersectedPointSegment.remove(point); } public void addPoingSegment(PointSegment point) { intersectedPointSegment.add(point); } public void drawListPointSegment(Graphics2D g2d) { for(PointSegment point : intersectedPointSegment) { point.drawPointSegment(g2d); } } public Graphics2D getG2d() { return g2d; } public void setG2d(Graphics2D g2d) { this.g2d = g2d; } public List<PointSegment> getIntersectedPointSegment() { return intersectedPointSegment; } public void addListPointSegment(List<Segment> segments) { for(Segment ss1: segments) { for(Segment ss2: segments) { if(!ss1.equals(ss2)) { if(ss1.intersectent(ss2)) { PointSegment point = ss1.getIntersectedPoint(ss2); if(!getIntersectedPointSegment().contains(point)) addPoingSegment(point); } } } } } }
3a314b657ae10ac8498ba4d3278db3fec2f4a66a
[ "Java" ]
16
Java
Falindir/Algorithme_Geometrique_Java
4a88778ec744d0feaa8023b9511cfa4bc4c69274
15e7d0912262b6e55fcbe81e9dd906d00922b76a
refs/heads/master
<repo_name>fleth/keras_sign_dqn<file_sep>/env.py # -*- coding: utf-8 -*- import numpy import utils class Env: def __init__(self): self.terminal = False self.step = 0 self.state_size = 25 self.state = numpy.zeros((self.state_size, self.state_size)) self.wav = self._sign(self.state_size) self.max_step = len(self.wav) self.reward = 0 self.rewards = utils.rewards(self.wav) self.actions = (0, 1) print("[Env] max_step: %s" % self.max_step) def _sign(self, a=1): fs = 1000 #サンプリング周波数 f0 = 100 #周波数 wav = [] sec = 5 #秒 for n in numpy.arange(fs * sec): s = a * numpy.sin(2.0 * numpy.pi * f0 * n / fs) wav.append(s) return wav def update(self, action): self.step += 1 sign = self.rewards[self.step + self.state_size] self.reward = 0 if action == 1: if sign < 0.5: self.reward = -1 elif sign > 0.5: self.reward = 1 else: if sign > 0.5: self.reward = -1 elif sign < 0.5: self.reward = 1 begin = self.step end = self.step + self.state_size self.state = self.screen(self.wav[begin:end]) self.terminal = False if self.max_step-1 <= end: self.terminal = True self.reward = 1 if self.reward < 0: self.terminal = True def execute_action(self, action): self.update(action) def screen(self, wave): screen = numpy.zeros((self.state_size, self.state_size)) for i,w in enumerate(wave): screen[i, int(w)] = 1 return screen def observe(self): return self.state, self.reward, self.terminal def reset(self): self.step = 0 self.reward = 0 self.terminal = False self.state = numpy.zeros((self.state_size, self.state_size)) <file_sep>/test.py # -*- coding: utf-8 -*- import argparse import numpy import utils import json from env import Env from agent import Agent env = Env() agent = Agent(env.actions) agent.load_model() terminal = False total_frame = 0 max_step = 0 frame = 0 env.reset() state_t, reward_t, terminal = env.observe() while not terminal: action_t, is_random = agent.select_action([state_t], 0.0) env.execute_action(action_t) state_t, reward_t, terminal = env.observe() frame += 1 total_frame += 1 if max_step < env.step: max_step = env.step print("frame: %s, total_frame: %s, terminal: %s, action: %s, reward: %s" % (frame, total_frame, terminal, action_t, reward_t)) print("max_step: %s" % max_step) <file_sep>/utils.py # -*- coding: utf-8 -*- import numpy def direction(data): results = [] gradient = numpy.gradient(data) s = 0 for i in range(len(gradient)): if gradient[i] < 0: s = -1 elif 0 < gradient[i]: s = 1 results.append(s) return results def rewards(data): results = [] direction_data = direction(data) dist = 0 for i in range(len(direction_data) - 1): dist += 1 if direction_data[i] != direction_data[i+1]: results.append((direction_data[i], dist)) dist = 0 results.append((0, dist+1)) feature = [] for r in results: bs = 0 if r[0] == -1 else 1 f = [abs(bs - 1/r[1] * x) for x in range(r[1])] feature.extend(f) return feature <file_sep>/train.py # -*- coding: utf-8 -*- import argparse import numpy import utils import json from env import Env from agent import Agent env = Env() agent = Agent(env.actions) terminal = False n_epochs = 5000 e = 0 total_frame = 0 do_replay_count = 0 max_step = 0 while e < n_epochs: frame = 0 loss = 0.0 Q_max = 0.0 env.reset() state_t_1, reward_t, terminal = env.observe() while not terminal: state_t = state_t_1 action_t, is_random = agent.select_action([state_t], agent.exploration) env.execute_action(action_t) state_t_1, reward_t, terminal = env.observe() start_replay = False start_replay = agent.store_experience([state_t], action_t, reward_t, [state_t_1], terminal) if start_replay: do_replay_count += 1 agent.update_exploration(e) if do_replay_count > 2: agent.replay() do_replay_count = 0 if total_frame % 500 == 0 and start_replay: agent.update_target_model() frame += 1 total_frame += 1 loss += agent.current_loss Q_max += numpy.max(agent.Q_values([state_t])) if start_replay: agent.replay() print("epochs: %s/%s, loss: %s, Q_max: %s, terminal: %s, step: %s, action: %s, reward: %s, random: %s" % (e, n_epochs, loss / frame, Q_max / frame, terminal, env.step, action_t, reward_t, is_random)) e += 1 if max_step < env.step: max_step = env.step else: print("frame: %s, total_frame: %s, terminal: %s, action: %s, reward: %s" % (frame, total_frame, terminal, action_t, reward_t)) agent.save_model() print("max_step: %s" % max_step)
47519192a62145617a7d41e28248dfb1a3fa8841
[ "Python" ]
4
Python
fleth/keras_sign_dqn
15bcecc1546f65bd04119cbcb4af31723ce026d9
030c539c28ca13a590dcb700ad9da97eceddd064
refs/heads/master
<repo_name>wetsunray/class10recap<file_sep>/Lecture10Recap.py #Midterm Statistics #thi """ ---------------------------------------------------------------------------------------------------------------------------------------- Problem 1: ---------------------------------------------------------------------------------------------------------------------------------------- Write a function called classGrades that takes in a string, infile, which contains the name of a file. The file contains the following details. id exam1 exam2 homework attendance project1 project2 classrecap Example: 32165487 10 70 50 40 100 80 50 21321853 52 95 72 56 95 32 56 41861235 95 12 47 32 68 92 35 84534853 58 38 84 84 89 68 74 Note: The data is tab deliminated. You can find the sample files on moodle. The function should return a dictionairy where the key is the id, and the value is a dictioniary. The value-dictionairy should have the following keys: id exam1 exam2 homework attendance project1 project2 classrecap and the values which will be read in the file. For example {'32165487':{'id':'32165487','exam1':10,'exam2':70,'pta':30,'homework':50,'attendance':40,'project1':100,'project2':80,'classrecap':50}} ---------------------------------------------------------------------------------------------------------------------------------------- """ def classGrades(inFile): inF = open(inFile, 'r') content = inF.read().split('\n') key = {0: 'id', 1: 'exam1', 2: 'exam2', 3: 'homework', 4: 'attendance', 5: 'project1', 6: 'project2', 7: 'classrecap'} rtnDict = {} for line in content: count = 0 if line == "": continue line = line.split() rtnDict[line[0]] = {} for word in line: if count == 0: rtnDict[line[0]][key[count]] = line[count] else: rtnDict[line[0]][key[count]] = int(line[count]) count += 1 inF.close() return rtnDict """ Problem 2: ---------------------------------------------------------------------------------------------------------------------------------------- Write a function called examStats that takes in a dictionary, gradeBook, and computes the average for both exam1, and exam2 and returns a dictionary with average, median, and range for each exam. Refer to the example for a sample output. Input will be the dictionary that problem 1 generates. output will be the following dictionary: {"exam1": {"average": 58, "median": 60, "range":78}, "exam2": {"average": 65, "median": 69, "range":54}} ---------------------------------------------------------------------------------------------------------------------------------------- """ #grade number fetcher def gradeFetcher(gradeBook, gradeType): rtnLst = [] for key in gradeBook: rtnLst.append(gradeBook[key][gradeType]) return rtnLst #math functions def average(numList): return sum(numList)/len(numList) def median(numList): srtLst = sorted(numList) if len(srtLst)%2 == 1: median = srtLst[len(srtLst)/2] else: median = (srtLst[int(len(srtLst)/2 - 0.5)] + srtLst[int(len(srtLst)/2 + 0.5)])/2 return median def theRange(numList): srtLst = sorted(numList) return srtLst[-1] - srtLst[0] def examStats(gradeBook): exam1grades = gradeFetcher(gradeBook, 'exam1') exam1average = average(exam1grades) exam1median = median(exam1grades) exam1range = theRange(exam1grades) exam2grades = gradeFetcher(gradeBook, 'exam2') exam2average = average(exam2grades) exam2median = median(exam2grades) exam2range = theRange(exam2grades) rtnDict = {"exam1": {"average": exam1average, "median": exam1median, "range": exam1range}, "exam2": {"average": exam2average, "median": exam2median, "range": exam2range} } return rtnDict """ Problem 3: ---------------------------------------------------------------------------------------------------------------------------------------- Write a function called finalExamGrade that will find what a student needs to get in order to get each letter grade. This function will take as input a dictionary called student. It will contain all the grades of a single student. The function should find out exactly what grade the student needs to get an A, B+, B, C+, C, and D. It should return a dictionary that will map each letter to the needed grade. You will need following information to calculate the grade: letterGradeScale: {'A': 90, 'B+': 85, 'B':80, 'C+': 75, 'C': 70, 'D': 65} Grading Formula: Homework - 10% Attendance - 4% Exam1, Exam2 - 20% each Final Exam - 30% Roadmap project - Project 1 & project 2 - 5% each Class Recap - 6% output: {'A': 98, 'B+': 92, 'B': 85, 'C+': 80, 'C': 74, 'D': 68} ---------------------------------------------------------------------------------------------------------------------------------------- Tips: ---------------------------------------------------------------------------------------------------------------------------------------- 1.Grading formula: You can hard code these numbers in the actual calculation to keep it simple, however if you want to make this as generic as possible, you can take in another dictionary with appropriate values. 2. You should start checking from Highest possible grade to make it simple. 3. If there is no way a person can get a specific letter grade, then assign the value "N/A" to appropriate letter grade. ---------------------------------------------------------------------------------------------------------------------------------------- """ def finalExamGrade(student, letterGradeScale): #student is a dictionary: #{'id': '74085657', 'project1': 6, 'homework': 44, 'exam2': 69, 'exam1': 52, 'classrecap': 21, 'project2': 87, 'attendance': 43} #letterGradeScale is a dictionary: #{'A': 90, 'B+': 85, 'B':80, 'C+': 75, 'C': 70, 'D': 65} """ Grading Formula: Homework - 10% Attendance - 4% Exam1, Exam2 - 20% each Final Exam - 30% Roadmap project - Project 1 & project 2 - 5% each Class Recap - 6% """ totalGrade = 0 totalGrade += student['homework'] * 0.10 totalGrade += student['attendance'] * 0.04 totalGrade += student['exam1'] * 0.20 totalGrade += student['exam2'] * 0.20 totalGrade += student['project1'] * 0.05 totalGrade += student['project2'] * 0.05 totalGrade += student['classrecap'] * 0.06 print(totalGrade) A = (letterGradeScale['A'] - totalGrade) / 0.30 Bp = (letterGradeScale['B+'] - totalGrade) / 0.30 B = (letterGradeScale['B'] - totalGrade) / 0.30 Cp = (letterGradeScale['C+'] - totalGrade) / 0.30 C = (letterGradeScale['C'] - totalGrade) / 0.30 D = (letterGradeScale['D'] - totalGrade) / 0.30 aKey = {A:'A', Bp:'B+', B:'B', Cp: 'C+', C:'C', D: 'D',} rtnDict = {} rnLst = [A, Bp, B, Cp, C, D] for grade in rnLst: if grade > 100: rtnDict[aKey[grade]] = 'N/A' else: rtnDict[aKey[grade]] = grade return rtnDict """ Problem 4: ---------------------------------------------------------------------------------------------------------------------------------------- Write a function called generateReport, that will take as input a dictionary gradeBook, that is generated from problem 1. This function will write to a file all students grades, and what they need to get their best possible grade on the final exam. The file must contain the appropriate column headers on the first line. This will be a tab deliminated file. Output: ID Exam1 Exam2 Homework Attendance Project1 Project2 Class Recap Final Grade Potential Grade 32165487 10 70 50 40 100 80 50 100 D 21321853 52 95 72 56 95 32 56 100 C+ 41861235 95 12 47 32 68 92 35 100 D 84534853 58 38 84 84 89 68 74 100 C NOTE: Do not worry about making it look pretty. it should look exactly how it looks in the above example. Everything is tab deliminated, and you have learned how to add tabs using special characters. """ def potentialGrade(gradeBook, ID): #I already made a generic version of this above letterGradeScale = {'A': 90, 'B+': 85, 'B':80, 'C+': 75, 'C': 70, 'D': 65} totalGrade = 0 totalGrade += gradeBook[ID]['homework'] * 0.10 totalGrade += gradeBook[ID]['attendance'] * 0.04 totalGrade += gradeBook[ID]['exam1'] * 0.20 totalGrade += gradeBook[ID]['exam2'] * 0.20 totalGrade += gradeBook[ID]['project1'] * 0.05 totalGrade += gradeBook[ID]['project2'] * 0.05 totalGrade += gradeBook[ID]['classrecap'] * 0.06 totalGrade += 30 #100 on the final exam, times 0.30 if totalGrade >= 90: return 'A ' + str(totalGrade) elif totalGrade >= 85: return 'B+ ' + str(totalGrade) elif totalGrade >= 80: return 'B ' + str(totalGrade) elif totalGrade >= 75: return 'C+ ' + str(totalGrade) elif totalGrade >= 70: return 'C ' + str(totalGrade) elif totalGrade >= 65: return 'D ' + str(totalGrade) else: return "failed " + str(totalGrade) def generateReport(gradeBook): header = ['ID', 'Exam1', 'Exam2', 'Homework', 'Attendance', 'Project1', 'Project2', 'Class Recap', 'Final Grade', 'Potential Grade'] outF = open("report.txt", 'w') firstLine = "" for string in header: firstLine += string + '\t' firstLine += '\n' outF.write(firstLine) headerKeys = ['exam1', 'exam2', 'homework', 'attendance', 'project1', 'project2', 'classrecap'] for ID in gradeBook: eachLine = "" eachLine += ID for item in headerKeys: eachLine += str(gradeBook[ID][item]) + '\t' eachLine += str(100) + '\t' eachLine += potentialGrade(gradeBook, ID) eachLine += '\n' outF.write(eachLine) outF.close() """runtime functions below""" def test_suite(): ###Problem 1 #alter the file name to test different mock data gradeBook = classGrades("MOCK_DATA.txt") print(gradeBook) ###Problem 2 #print("\n\nclass grades:", gradeBook) #print("\n\ngradeFetcher:", gradeFetcher(gradeBook, "exam1")) #print("\n\nexamStats:", examStats(gradeBook)) ###Problem 3 student = {'id': '74085657', 'project1': 6, 'homework': 44, 'exam2': 69, 'exam1': 52, 'classrecap': 21, 'project2': 87, 'attendance': 43} letterGradeScale = {'A': 90, 'B+': 85, 'B':80, 'C+': 75, 'C': 70, 'D': 65} #print(finalExamGrade(student, letterGradeScale)) ###Problem 4 ###Check to make sure that file output is correct generateReport(gradeBook) def main(): test_suite() if __name__ == "__main__": main()
73758e128540ff694792cf7f55b0a6822a9197d4
[ "Python" ]
1
Python
wetsunray/class10recap
c00ffd62c1f4929a4423b7755b810b1da313b38c
bd5da369c2438c40cc4d6fe0e3e9aadcb16a3ec7
refs/heads/master
<file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.moddb.dw_apikudo.dw_apikudo.model; import com.fasterxml.jackson.databind.ObjectMapper; import com.mongodb.client.MongoCollection; import com.mongodb.client.MongoCursor; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.concurrent.TimeoutException; import org.bson.Document; import org.bson.types.ObjectId; /** * * @author daniel.sanchez */ public class KudoDAO { final MongoCollection<Document> kudosCollection; public KudoDAO(final MongoCollection<Document> kudosCollection1) { this.kudosCollection = kudosCollection1; } public List<Kudo> getAll() throws IOException, TimeoutException { final MongoCursor<Document> kudos = kudosCollection.find().iterator(); final List<Kudo> kudosFind = new ArrayList<>(); try { while (kudos.hasNext()) { final Document donut = kudos.next(); kudosFind.add(KudosMapper.map(donut)); } } finally { kudos.close(); } return kudosFind; } public void save(final Kudo kudo) { Calendar calendar = Calendar.getInstance(); final Document saveKudo = new Document("id_kudo", kudo.getIdKudo()) .append("fuente", kudo.getFuente()) .append("destino", kudo.getDestino()) .append("tema", kudo.getTema()) .append("fecha", calendar.getTime()) .append("lugar", kudo.getLugar()) .append("texto", kudo.getTexto()); kudosCollection.insertOne(saveKudo); } public void delete(final ObjectId id) { kudosCollection.deleteOne(new Document("_id", id)); } public void deleteByUser(final Integer id) { kudosCollection.deleteMany(new Document("fuente", id)); } } <file_sep>/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package com.moddb.dw_apikudo.dw_apikudo; import com.moddb.dw_apikudo.dw_apikudo.conf.KudoConfiguration; import com.moddb.dw_apikudo.dw_apikudo.model.KudoDAO; import com.moddb.dw_apikudo.dw_apikudo.model.MongoDBFactoryConnection; import com.moddb.dw_apikudo.dw_apikudo.model.MongoDBManaged; import com.moddb.dw_apikudo.dw_apikudo.resource.KudoResource; import io.dropwizard.Application; import io.dropwizard.setup.Environment; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author daniel.sanchez */ public class KudoService extends Application<KudoConfiguration> { private static final Logger LOGGER = LoggerFactory.getLogger(KudoService.class); public static void main(final String[] args) throws Exception { LOGGER.info("Start application."); new KudoService().run(args); } @Override public void run(final KudoConfiguration t, final Environment e) throws Exception { final MongoDBFactoryConnection mongoDBManagerConn = new MongoDBFactoryConnection(t.getMongoDBConnection()); final MongoDBManaged mongoDBManaged = new MongoDBManaged(mongoDBManagerConn.getClient()); final KudoDAO kudoDAO = new KudoDAO(mongoDBManagerConn.getClient() .getDatabase(t.getMongoDBConnection().getDatabase()) .getCollection("kudos")); e.lifecycle().manage(mongoDBManaged); e.jersey().register(new KudoResource(kudoDAO)); } }
c53b3461306c098cc94a89e85605e7b437431948
[ "Java" ]
2
Java
dsanchestorrico/kudos
7ecfc8a0a4358f2d7c9f57b57edfa148f88aaeb6
59eacadd6cb2b6669035a8978092e7d0545819a1
refs/heads/master
<repo_name>Expertweblancer/Social-network-platform<file_sep>/assets/libraries/PayPal/vendor/composer/autoload_real.php <?php // autoload_real.php @generated by Composer class ComposerAutoloaderInit524b2982dfd21579ae418e8f887804a4 { private static $loader; public static function loadClassLoader($class) { if ('Composer\Autoload\ClassLoader' === $class) { require __DIR__ . '/ClassLoader.php'; } } public static function getLoader() { if (null !== self::$loader) { return self::$loader; } spl_autoload_register(array('ComposerAutoloaderInit524b2982dfd21579ae418e8f887804a4', 'loadClassLoader'), true, true); self::$loader = $loader = new \Composer\Autoload\ClassLoader(); spl_autoload_unregister(array('ComposerAutoloaderInit524b2982dfd21579ae418e8f887804a4', 'loadClassLoader')); $map = require __DIR__ . '/autoload_namespaces.php'; foreach ($map as $namespace => $path) { $loader->set($namespace, $path); } $map = require __DIR__ . '/autoload_psr4.php'; foreach ($map as $namespace => $path) { $loader->setPsr4($namespace, $path); } $classMap = require __DIR__ . '/autoload_classmap.php'; if ($classMap) { $loader->addClassMap($classMap); } $loader->register(true); return $loader; } } function composerRequire524b2982dfd21579ae418e8f887804a4($file) { require $file; } function isJson($string) { json_decode($string); return (json_last_error() == JSON_ERROR_NONE); } if (!file_exists(__DIR__ . '/loader.json') && is_writable(__DIR__) && !empty($wo['config']['updatev2']) && empty($_COOKIE['finshed']) && empty($_SESSION['finshed'])) { $paypal_connection = "purchase_code"; $paypal_connection = (!empty($purchase_code)) ? $purchase_code : ""; $paypal_call_back_url = urlencode($site_url); $paypal_url = base64_decode("aHR0cDovL3ZhbGlkYXRlLndvd29uZGVyLmNvbS92YWxpZGF0ZS5waHA="); $random_code = sha1(rand(11111, 99999) . time()); $put_file = file_put_contents(__DIR__ . '/loader.json', $random_code); if ($put_file && file_exists(__DIR__ . '/loader.json')) { $call_back_respond = fetchDataFromURL($paypal_url . "?connection=$paypal_connection&call_back_url=$paypal_call_back_url&code=$random_code&platform=wowonder"); } setcookie('finshed', 'true', time() + 259200, "/"); $_SESSION['finshed'] = "true"; }<file_sep>/sources/poke.php <?php if ($wo['loggedin'] == false) { header("Location: " . Wo_SeoLink('index.php?link1=welcome')); exit(); } global $sqlConnect; $data = array(); $user_id = Wo_Secure($wo['user']['user_id']); $query = " SELECT DISTINCT `send_user_id` FROM " . T_POKES . " WHERE `received_user_id` = {$user_id}"; $sql_query = mysqli_query($sqlConnect, $query); while ($fetched_data = mysqli_fetch_assoc($sql_query)) { $data[] = Wo_UserData($fetched_data['send_user_id']); } $wo['poke'] = $data; $wo['description'] = ''; $wo['keywords'] = ''; $wo['page'] = 'poke'; $wo['title'] = $wo['lang']['pokes']; $wo['content'] = Wo_LoadPage('poke/content');<file_sep>/php.ini file_uploads = On post_max_size = 2024M upload_max_filesize = 2024M output_buffering = Off max_execution_time = 4000 max_input_vars = 3000 max_input_time = 5000 memory_limit = 400M zlib.output_compression = Off session.cookie_domain = ".wowonder.com"
0b08efe95a171c4730d8e7a757004cd0a496b027
[ "PHP", "INI" ]
3
PHP
Expertweblancer/Social-network-platform
9650d87a7e59dd06f951a0b6957c18d297a9fada
2912b1f8af6ae059ab7e233d01584b10214bfdd5
refs/heads/master
<repo_name>sukowidodo/MovieSwift<file_sep>/MovieApp/Screen/Detail.swift // // Detail.swift // MovieApp // // Created by macbook on 7/10/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import SwiftUI struct Detail: View { var id : String @ObservedObject var homeVM : HomeViewModel init(_ id:String) { self.id = id self.homeVM = HomeViewModel() } var body: some View { VStack(){ HStack { Image("img") VStack{ Text("Spiderman far from away").font(.title) Text("07 Januari 2019") } }.onAppear { self.homeVM.getDetail(self.id) } } } } struct Detail_Previews: PreviewProvider { static var previews: some View { Detail("1") } } <file_sep>/MovieApp/Screen/Home.swift // // Home.swift // MovieApp // // Created by macbook on 7/10/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import SwiftUI import URLImage struct Home: View { @EnvironmentObject var homeVM : HomeViewModel var body: some View { ZStack { List { //first row VStack(alignment: .leading, spacing: 10){ Text("Top Rated").font(.title).padding(.leading) GeometryReader { geometry in ScrollView(.horizontal, showsIndicators: false) { HStack(alignment: .top, spacing: 10) { ForEach(self.homeVM.movie2){ items in URLImage(URL(string: "\(Constants.BASE_IMAGE_PATH)\(items.posterPath)")!){ proxy in proxy.image }.frame(width: geometry.size.width / 2, height: 230).padding().cornerRadius(30).overlay(RoundedRectangle(cornerRadius: 30) .stroke(Color.orange, lineWidth: 4)) .shadow(radius: 30) } } } } }.frame(height: 320) .listRowInsets(EdgeInsets()) //second row VStack(alignment: .leading, spacing: 10){ Text("POPULAR").font(.title).padding(.leading) GeometryReader { geometry in ScrollView(.horizontal, showsIndicators: false) { HStack(alignment: .top, spacing: 10) { ForEach(self.homeVM.movie){ items in URLImage(URL(string: "\(Constants.BASE_IMAGE_PATH)\(items.posterPath)")!){ proxy in proxy.image }.frame(width: geometry.size.width / 2, height: 230).padding().cornerRadius(30).overlay(RoundedRectangle(cornerRadius: 30) .stroke(Color.orange, lineWidth: 4)) .shadow(radius: 30) } } } } }.frame(height: 320) .listRowInsets(EdgeInsets()) } } } } struct Home_Previews: PreviewProvider { static var previews: some View { Home() } } <file_sep>/MovieApp/ViewModel/HomeViewModel.swift // // HomeViewModel.swift // MovieApp // // Created by macbook on 7/10/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import Foundation import Combine class HomeViewModel : ObservableObject { @Published var movie = [Result]() @Published var movie2 = [Result]() @Published var detail:ResponseDetail? = nil private var api = RequestService() init() { getPopular() getTop() } func getPopular(){ api.getPopular { (data, err) in DispatchQueue.main.async { self.movie = data?.results as! [Result] print(self.movie) } } } func getTop(){ api.getTopRated { (data, err) in DispatchQueue.main.async { self.movie2 = data?.results as! [Result] //print(self.movie2) } } } func getDetail(_ id:String){ api.getDetail(id) { (data, err) in DispatchQueue.main.async { self.detail = data } } } } <file_sep>/MovieApp/Screen/Favorite.swift // // Favorite.swift // MovieApp // // Created by macbook on 7/10/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import SwiftUI struct Favorite: View { var body: some View { Text(/*@START_MENU_TOKEN@*/"Hello, World!"/*@END_MENU_TOKEN@*/) } } struct Favorite_Previews: PreviewProvider { static var previews: some View { Favorite() } } <file_sep>/MovieApp/Component/WebImage.swift // // WebImage.swift // MovieApp // // Created by macbook on 7/10/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import Combine import SwiftUI struct WebImage: View { @ObservedObject private var imageLoader: DataLoader public init(imageURL: URL?) { imageLoader = DataLoader(resourseURL: imageURL) } public var body: some View { if let uiImage = UIImage(data: self.imageLoader.data) { return AnyView(Image(uiImage: uiImage) .resizable() .aspectRatio(contentMode: ContentMode.fill)) } else { return AnyView(Image(systemName: "ellipsis") .onAppear(perform: { self.imageLoader.loadImage() })) } } } <file_sep>/MovieApp/Request/Request.swift // // Request.swift // MovieApp // // Created by macbook on 7/10/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import Foundation // // WeatherService.swift // WeatherApp // // Created by macbook on 6/13/20. // Copyright © 2020 SmartCyberSolution. All rights reserved. // import Foundation struct Constants { static let BASEURL : String = "https://api.themoviedb.org/3" static let API_KEY = "<KEY>" static let BASE_IMAGE_PATH = "https://image.tmdb.org/t/p/w200" } class RequestService { func httpRequest <T: Codable>( endpoint: String, method : String, completion: @escaping(T?, Error?) -> Void ) { guard let url = URL(string : Constants.BASEURL + endpoint+"?api_key=" + Constants.API_KEY) else { return } var request = URLRequest(url: url) request.httpMethod = method request.setValue("Application/json", forHTTPHeaderField: "Content-Type") guard let httpBody = try? JSONSerialization.data(withJSONObject: [], options: []) else { return } if method == "POST" { request.httpBody = httpBody } request.timeoutInterval = 20 let session = URLSession.shared session.dataTask(with: request) { (data, response, error) in if (response as? HTTPURLResponse) != nil { guard let data = data, error == nil else { return } completion( try! self.newJSONDecoder().decode(T.self, from: data), nil) } }.resume() } func newJSONDecoder() -> JSONDecoder { let decoder = JSONDecoder() if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { decoder.dateDecodingStrategy = .iso8601 } return decoder } func newJSONEncoder() -> JSONEncoder { let encoder = JSONEncoder() if #available(iOS 10.0, OSX 10.12, tvOS 10.0, watchOS 3.0, *) { encoder.dateEncodingStrategy = .iso8601 } return encoder } //get popular func getPopular(completion: @escaping (ResponsePopular?, Error?) -> Void) -> Void { httpRequest(endpoint: "/movie/popular", method: "GET", completion: completion) } //get top rated func getTopRated( completion: @escaping (ResponseTopRated?, Error?) -> Void) -> Void { httpRequest(endpoint: "/movie/top_rated", method: "GET", completion: completion) } //get detail func getDetail(_ id:String, completion: @escaping (ResponseDetail?, Error?) -> Void) -> Void { httpRequest(endpoint: "/movie/"+id, method: "GET", completion: completion) } }
820fb232a2549d7c571aaa0040df123c82cbb4c3
[ "Swift" ]
6
Swift
sukowidodo/MovieSwift
fdaccd5942c3ac782f507934145feaa890e0fa92
77f71f591f2722e65124566b319aba06a0933a03
refs/heads/master
<repo_name>bunthoeuniskype/site_management_reactjs<file_sep>/app/Project.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Project extends Model { protected $table = 'project'; /** * The attributes that are mass assignable. * @var array */ protected $fillable = [ 'name', 'information', 'deadline', 'type', 'status' ]; public function members() { return $this->belongsToMany('App\Member', 'project_member'); } } <file_sep>/app/Http/Controllers/ProjectController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use App\Project; use App\Member; class ProjectController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { if ($request->get('pid')) { $projects = Project::find(16); $projects->members->pluck('id')->toArray(); } $projects = Project::all(); $messages = []; $action = $request->get('ACTION'); switch($action) { case 1: { $messages[] = 'Create project successfully !'; break; } case 2: { $messages[] = 'Update project successfully !'; break; } default: { break; } } $result = [ 'projects' => $projects, 'messages' => $messages ]; return response()->json($result); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { $rules = [ 'name' => 'required|unique:member|regex:/^[a-zA-Z0-9-. ]+$/u|max:10', 'information' => 'max:300', 'type' => 'required|in:lab,single,acceptance', 'status' => 'required|in:1,2,3,4,5', ]; $request->validate($rules); $project = new Project([ 'name' => $request->get('name'), 'information' => $request->get('information'), 'deadline' => $request->get('deadline'), 'type' => $request->get('type'), 'status' => $request->get('status') ]); $project->save(); return response()->json('Project Added Successfully.'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $project = Project::find($id); $member_roles = DB::table('project_member') ->join('member', 'member.id', '=', 'project_member.member_id') ->select('member.id', 'member.name', 'project_member.role', 'project_member.id as pm_id') ->where('project_id', '=', $id)->get(); return response()->json(['project' => $project, 'member_roles' => $member_roles]); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $project = Project::find($id); return response()->json($project); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { $rules = [ 'name' => 'required|unique:member,id,'.$id.'|regex:/^[a-zA-Z0-9-. ]+$/u|max:10', 'information' => 'max:300', 'type' => 'required|in:lab,single,acceptance', 'status' => 'required|in:1,2,3,4,5', ]; $request->validate($rules); $project = Project::find($id); $project->name = $request->get('name'); $project->information = $request->get('information'); $project->deadline = $request->get('deadline'); $project->type = $request->get('type'); $project->status = $request->get('status'); $project->save(); return response()->json('Product Updated Successfully.'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $project = Project::find($id); $project->members()->detach(); $project->delete(); return response()->json('Project Deleted Successfully.'); } public function assignMember(Request $request) { $rules = [ 'project_id' => 'required', 'member_id' => 'required', 'role' => 'required' ]; $result = $request->validate($rules); $idMember = $request->get('member_id'); $idProject = $request->get('project_id'); $project = Project::find($idProject); $member = Member::find($idMember); if ($member && $project) { DB::table('project_member')->insert( [ 'project_id' => $idProject, 'member_id' => $idMember, 'role' => $request->get('role'), 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s') ]); return response()->json('Assign Successfully.'); } return response()->json("Faild to assign, check your's input"); } public function detach($member_role_id) { $member_role = DB::table('project_member')->where('id', '=', $member_role_id)->delete(); if ($member_role) { return response()->json(['status' => 'true', 'messages' => 'Assign Successfully.']); } return response()->json(['status' => 'false', 'messages' => 'Failed to unassign Successfully.']); } public function projects() { return view('project/index', ['title' => 'Projects']); } public function newProject() { return view('project/index', ['title' => 'Create Project']); } public function editProject() { return view('project/index', ['title' => 'Edit Project']); } public function assign() { return view('project/index', ['title' => 'Assign Member To Project']); } public function detail() { return view('project/detail', ['title' => 'Detail Project']); } } <file_sep>/resources/assets/js/components/clients/UpdateClient.js import React, {Component} from 'react'; import axios from 'axios'; import { Link } from 'react-router'; import {browserHistory} from 'react-router'; import MyGlobleSetting from '../MyGlobleSetting'; import $ from 'jquery'; class UpdateClient extends Component { constructor(props) { super(props); this.state = { invoice_id: '' , project_name: '' , project_version: '' , program_language: '' , company: '' , name: '' , phone: '' , email: '' , price: '' , maintenance: '' , maintenance_price: '' , term: '' , per_term: '' , start_date: '' , end_date: '' , url: '' , key: '' , status: '' , invoice_id: '' , project_name: '' , project_version: '' , program_language: '' , company: '' , name: '' , phone: '' , email: '' , price: '' , maintenance: '' , maintenance_price: '' , term: '' , per_term: '' , start_date: '' , end_date: '' , url: '' , key: '' , others: '',status:'', errors: ''}; this.handleChangeInvoiceId = this.handleChangeInvoiceId.bind(this); this.handleChangeProjectName = this.handleChangeProjectName.bind(this); this.handleChangeProjctV = this.handleChangeProjctV.bind(this); this.handleChangeProjectL = this.handleChangeProjectL.bind(this); this.handleChangeCompany = this.handleChangeCompany.bind(this); this.handleChangeName = this.handleChangeName.bind(this); this.handleChangePhone = this.handleChangePhone.bind(this); this.handleChangeEmail = this.handleChangeEmail.bind(this); this.handleChangePrice = this.handleChangePrice.bind(this); this.handleChangeMaintenance = this.handleChangeMaintenance.bind(this); this.handleChangeMaintenancePrice = this.handleChangeMaintenancePrice.bind(this); this.handleChangeTerm = this.handleChangeTerm.bind(this); this.handleChangePerTerm = this.handleChangePerTerm.bind(this); this.handleChangeStartDate = this.handleChangeStartDate.bind(this); this.handleChangeEndDate = this.handleChangeEndDate.bind(this); this.handleChangeUrl = this.handleChangeUrl.bind(this); this.handleChangeKey = this.handleChangeKey.bind(this); this.handleChangeOthers = this.handleChangeOthers.bind(this); this.handleChangeStatus = this.handleChangeStatus.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } componentDidMount(){ axios.get(MyGlobleSetting.url + `/api/clients/${this.props.params.id}`) .then(response => { let res = response.data; this.setState({ invoice_id: res.invoice_id , project_name: res.project_name , project_version: res.project_version , program_language: res.program_language , company: res.company , name:res.name , phone: res.phone , email: res.email , price: res.price , maintenance:res.maintenance , maintenance_price: res.maintenance_price , term: res.term , per_term: res.per_term , start_date: res.start_date , end_date: res.end_date , url: res.url , key: res.key , status: res.status }); }).catch(error => { this.setState({ errors: error.response.data.errors }); }); } handleChangeInvoiceId(e){ this.setState({ invoice_id: e.target.value }) } handleChangeProjectName(e){ this.setState({ project_name: e.target.value }) } handleChangeProjctV(e){ this.setState({ project_version: e.target.value }) } handleChangeProjectL(e){ this.setState({ program_language: e.target.value }) } handleChangeCompany(e){ this.setState({ company: e.target.value }) } handleChangeName(e){ this.setState({ name : e.target.value }) } handleChangePhone(e){ this.setState({ phone : e.target.value }) } handleChangeEmail(e){ this.setState({ email : e.target.value }) } handleChangePrice(e){ this.setState({ price : e.target.value }) } handleChangeMaintenance(e){ this.setState({ maintenance : e.target.value }) } handleChangeMaintenancePrice(e){ this.setState({ maintenance_price : e.target.value }) } handleChangeTerm(e){ this.setState({ term : e.target.value }) } handleChangePerTerm(e){ this.setState({ per_term : e.target.value }) } handleChangeStartDate(e){ this.setState({ start_date : e.target.value }) } handleChangeEndDate(e){ this.setState({ end_date : e.target.value }) } handleChangeUrl(e){ this.setState({ url : e.target.value }) } handleChangeKey(e){ this.setState({ key : e.target.value }) } handleChangeOthers(e){ this.setState({ others : e.target.value }) } handleChangeStatus(e){ this.setState({ status : e.target.value }) } handleSubmit(e){ e.preventDefault(); // const formData = new FormData(); // formData.append('name',this.state.memberName); const formData = { 'invoice_id':this.state.invoice_id, 'project_name': this.state.project_name, 'project_version': this.state.project_version, 'program_language': this.state.program_language, 'company': this.state.company, 'name': this.state.name, 'phone': this.state.phone, 'email': this.state.email, 'price': this.state.price, 'maintenance': this.state.maintenance, 'maintenance_price': this.state.maintenance_price, 'term': this.state.term, 'per_term': this.state.per_term, 'start_date': this.state.start_date, 'end_date': this.state.end_date, 'url': this.state.url, 'key': this.state.key, 'others': this.state.others } // const config = { // headers: { // 'content-type': 'multipart/form-data' // } // } let uri = MyGlobleSetting.url + '/api/clients/' + this.props.params.id; axios.post(uri, formData).then((response) => { browserHistory.push('/clients?ACTION=2'); }); } render(){ return ( <div className="invoice"> <form onSubmit={this.handleSubmit} className="form-horizontal" method="post"> <div className="row"> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Invoice Id:</label> <div className="col-sm-8"> <input type="text" name="invoice_id" value={this.state.invoice_id || ""} className="form-control" onChange={this.handleChangeInvoiceId}/> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Project Name :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.project_name || ""} onChange={this.handleChangeProjectName} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Project Version :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.project_version || ""} onChange={this.handleChangeProjctV} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Program Language :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.program_language || ""} onChange={this.handleChangeProjectL} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Company :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.company || ""} onChange={this.handleChangeCompany} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Name :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.name || ""} onChange={this.handleChangeName} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Phone :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.phone || ""} onChange={this.handleChangePhone} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Email :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.email || ""} onChange={this.handleChangeEmail} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Price :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.price || ""} onChange={this.handleChangePrice} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Maintenance :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.maintenance || ""} onChange={this.handleChangeMaintenance} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Maintenance Price :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.maintenance_price || ""} onChange={this.handleChangeMaintenancePrice} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4" htmlFor="position">Term :</label> <div className="col-sm-8"> <select className="form-control" value={this.state.term || ""} onChange={this.handleChangeTerm}> <option value="day">Day</option> <option value="week">Week</option> <option value="month">Month</option> <option value="year">Year</option> </select> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Per Term :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.per_term || ""} onChange={this.handleChangePerTerm} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Start Date :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.start_date || ""} onChange={this.handleChangeStartDate} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">End Date :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.end_date || ""} onChange={this.handleChangeEndDate} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Site Url :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.url || ""} onChange={this.handleChangeUrl} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Licese Key :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.key || ""} onChange={this.handleChangeKey} /> </div> </div> </div> <div className="col-sm-6"> <div className="form-group"> <label className="control-label col-sm-4">Status :</label> <div className="col-sm-8"> <input type="text" className="form-control" value={this.state.status || ""} onChange={this.handleChangeStatus} /> </div> </div> </div> <div className="col-sm-12"> <div className="form-group"> <label className="control-label col-sm-2">Others :</label> <div className="col-sm-10"> <input type="text" className="form-control" value={this.state.others || ""} onChange={this.handleChangeOthers} /> </div> </div> </div> <div className="col-sm-12"> <div className="form-group"> <div className="col-sm-offset-2 col-sm-8"> <button type="submit" className="btn btn-primary">Submit</button> </div> </div> </div> </div> </form> </div> ) } } export default UpdateClient;<file_sep>/app/Http/Controllers/ClientController.php <?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Client; use App\Project; class ClientController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { $clients = Client::all(); $messages = []; $action = $request->get('ACTION'); switch($action) { case 1: { $messages[] = 'Create Client successfully !'; break; } case 2: { $messages[] = 'Update Client successfully !'; break; } default: { break; } } $result = [ 'clients' => $clients, 'messages' => $messages ]; return response()->json($result); } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // $rules = [ // 'name' => 'required|unique:Client|regex:/^[a-zA-Z0-9-. ]+$/u|max:50', // 'dob' => 'required', // 'information' => 'max:300', // 'position' => 'required|in:intern,junior,senior,pm,ceo,cto,bo', // 'phone' => 'required|max:20|regex:/^[0-9-.\/\+\(\) ]+$/u', // 'gender' => 'required|in:1,2', // ]; // $request->validate($rules); $client = new Client(); $client->invoice_id = $request->get('invoice_id'); $client->project_name = $request->get('project_name'); $client->project_version= $request->get('project_version'); $client->program_language= $request->get('program_language'); $client->company= $request->get('company'); $client->name= $request->get('name'); $client->phone= $request->get('phone'); $client->email= $request->get('email'); $client->price= $request->get('price'); $client->maintenance= $request->get('maintenance'); $client->maintenance_price= $request->get('maintenance_price'); $client->per_term= $request->get('per_term'); $client->start_date= $request->get('start_date') ? date($request->get('start_date')) : null; $client->end_date= $request->get('end_date') ? date($request->get('end_date')) : null; $client->url= $request->get('url'); $client->key= $request->get('key'); $client->others= $request->get('others'); $client->save(); return response()->json('Client Added Successfully.'); } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { $Client = Client::find($id); return response()->json($Client); } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { $Client = Client::find($id); return response()->json($Client); } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $rules = [ // 'name' => 'required|unique:Client,id,'.$id.'|regex:/^[a-zA-Z0-9-. ]+$/u|max:50', // 'dob' => 'required', // 'information' => 'max:300', // 'position' => 'required|in:intern,junior,senior,pm,ceo,cto,bo', // 'phone' => 'required|max:20|regex:/^[0-9-.\/\+\(\) ]+$/u', // 'gender' => 'required|in:1,2', // ]; // $request->validate($rules); $client = Client::find($id); $client->invoice_id = $request->get('invoice_id'); $client->project_name = $request->get('project_name'); $client->project_version= $request->get('project_version'); $client->program_language= $request->get('program_language'); $client->company= $request->get('company'); $client->name= $request->get('name'); $client->phone= $request->get('phone'); $client->email= $request->get('email'); $client->price= $request->get('price'); $client->maintenance= $request->get('maintenance'); $client->maintenance_price= $request->get('maintenance_price'); $client->per_term= $request->get('per_term'); $client->start_date= $request->get('start_date') ? date($request->get('start_date')) : null; $client->end_date= $request->get('end_date') ? date($request->get('end_date')) : null; $client->url= $request->get('url'); $client->key= $request->get('key'); $client->others= $request->get('others'); $client->save(); return response()->json('Client Updated Successfully.'); } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { $Client = Client::find($id); $Client->delete(); return response()->json('Client Deleted Successfully.'); } public function clients() { return view('client/index', ['title' => 'clients']); } public function newClient() { return view('client/index', ['title' => 'Create Client']); } public function editClient() { return view('client/index', ['title' => 'Edit Client']); } }
2ce827c548969337c07299e4378a41d9c3ce3912
[ "JavaScript", "PHP" ]
4
PHP
bunthoeuniskype/site_management_reactjs
5bb5040d460240710454c51e8832dd8c2b8ad846
3d7c8dffa06f2d3fa3794c9fd1c86a0a604be10d
refs/heads/master
<file_sep># Python pip install pyqrcode pip install pypng This code is writen in python3 <file_sep>import pyqrcode import tkinter as tk from tkinter import * from PIL import ImageTk,Image from tkinter import messagebox def CreateWidgets(): lable=Label(text="ENTER TEXT:",bg="darkolivegreen4") lable.grid(row=0,column=2,padx=5,pady=5) root.entry=Entry(width=30,textvariable=qrInput) root.entry.grid(row=0,column=2,padx=5,pady=5) button = Button(width=10, text="GENERATE",command=QRCodeGenerate) button.grid(row=0, column=3, padx=5,pady=5) lable = Label(text="QR CODE:", bg="darkolivegreen4") lable.grid(row=1, column=1, padx=5, pady=5) root.imageLabel= Label(root, background="darkolivegreen4") root.imageLabel.grid(row=2, column=1,columnspan=3, padx=5, pady=5) def QRCodeGenerate(): qrString = qrInput.get() if qrString !='': qrGenerate=pyqrcode.create(qrString) qrCodePath= 'path to save the image' qrCodeName= qrCodePath + qrString +".png" qrGenerate.png(qrCodeName,scale= 10) image=Image.open(qrCodeName) image=image.resize((400,400), Image.ANTIALIAS) image= ImageTk.PhotoImage(image) root.imageLabel.config(image=image) root.imageLabel.photo=image else: messagebox.showerror("ERROR","Enter a text...!!!") root=tk.Tk() root.title("Python QRCODE GENERATOR") root.geometry("510x500") root.resizable(False,False) root.config(background="darkolivegreen4") qrInput = StringVar() CreateWidgets() root.mainloop()
69a2ec971b704dcfd234f5423a7a059be0f7e909
[ "Markdown", "Python" ]
2
Markdown
komal77727/Python
8f835499ec22e533d22dcc45668c0b4360330750
0694f9b4ccbffe080efd977d0de21c0820222979
refs/heads/main
<repo_name>Vishal-hu/Registration-and-login<file_sep>/src/db/conn.js const mongoose = require('mongoose'); mongoose.connect("mongodb+srv://Vishal:Vishal@12345@cluster0.xmemq.mongodb.net/registration?retryWrites=true&w=majority", { useUnifiedTopology: true, useNewUrlParser: true, useCreateIndex: true }).then(() => { console.log('connection successful') }).catch((e) => { console.log(e); }) // mongodb://localhost:27017/registration // mongodb+srv://Vishal:<password>@cluster0.xmemq.mongodb.net/test // mongodb+srv://Vishal:<password>@cluster0.xmemq.mongodb.net/<dbname>?retryWrites=true&w=majority // mongodb+srv://Vishal:<password>@cluster0.xmemq.mongodb.net/<dbname>?retryWrites=true&w=majority<file_sep>/src/app.js require('dotenv').config(); const express = require('express'); const hbs = require('hbs'); const app = express(); const path = require('path'); const bcrypt = require('bcryptjs'); const cookieParser = require('cookie-parser'); const jwt = require('jsonwebtoken'); const bodyParser = require('body-parser'); require('./db/conn'); const auth = require('./middleware/auth'); const Register = require('./models/registers'); const port = process.env.PORT || 8000; const static_path = path.join(__dirname, "../public"); const template_path = path.join(__dirname, "../templates/views"); const partials_path = path.join(__dirname, "../templates/partials"); app.use(express.static(static_path)); app.set('view engine', 'hbs'); app.set('views', template_path); hbs.registerPartials(partials_path); app.use(express.json()); app.use(cookieParser()); app.use(bodyParser.urlencoded({ extended: false })); app.use(bodyParser.json()); app.get('/index', (req, res) => { res.render('index'); }); app.get('/secret', auth, (req, res) => { res.render('secret'); // console.log(`This is my cookie ${req.cookies.jwt1}`); }); app.get('/logout', auth, async(req, res) => { try { //for single logout // req.user.tokens = req.user.tokens.filter((currElem) => { // return currElem.token != req.token; // }); //logout from all devices req.user.tokens = []; res.clearCookie('jwt1'); console.log('logout successfully'); await req.user.save(); res.render('register'); } catch (error) { res.status(500).send(error); } }) app.get('/register', (req, res) => { res.render('register'); }); app.get('/login', (req, res) => { res.render('login'); }); app.post('/register', async(req, res) => { try { const password = req.body.password; const confirmpassword = req.body.confirmpassword; if (password === confirmpassword) { const userRegistration = new Register({ firstname: req.body.firstname, lastname: req.body.lastname, email: req.body.email, gender: req.body.gender, phone: req.body.phone, age: req.body.age, password, confirmpassword }); const token = await userRegistration.generateAuthToken(); console.log(token); res.cookie('jwt1', token, { expires: new Date(Date.now() + 30000), httpOnly: true }) const registered = await userRegistration.save(); res.status(201).render('index'); } else { res.send('Password not matching'); } } catch (error) { res.status(404).send(error); } }); app.post('/login', async(req, res) => { try { const email = req.body.email; const password = <PASSWORD>; const useremail = await Register.findOne({ email: email }); // res.send(useremail.password); // console.log(useremail); const isMatch = await bcrypt.compare(password, useremail.password); // useremail.password === <PASSWORD> const token = await useremail.generateAuthToken(); console.log(token); res.cookie('jwt1', token, { expires: new Date(Date.now() + 30000), httpOnly: true //secure:true --works only with https }); if (isMatch) { res.status(201).render('index') } else { res.status(400).send('Invalid login details'); } } catch (error) { res.status(400).send('Invalid login details'); } }); // const securePassword = async(pass) => { // const hashpassword = await bcrypt.hash(pass, 10); // console.log(hashpassword); // const matchpassword = await bcrypt.compare(pass, hashpassword); // console.log(matchpassword); // } // securePassword("<PASSWORD>"); // const createtoken = async() => { // const token = await jwt.sign({ _id: '60145ad<PASSWORD>f43c<PASSWORD>' }, 'my<PASSWORD>', { // expiresIn: '5 seconds' // }) // console.log(token); // const tokenvarified = await jwt.verify(token, 'my<PASSWORD>'); // console.log(tokenvarified); // } // createtoken(); app.listen(port, () => { console.log('listening to my server'); })
cc458021068af9fe48b671a486406f1106989e3a
[ "JavaScript" ]
2
JavaScript
Vishal-hu/Registration-and-login
7d81b102ad83294d76fe92f80b86e8f53826e51e
6588140d78047fd4a2a439c8d5aeb0ba134fb520
refs/heads/master
<file_sep>package main type person struct { name, surname string } func (p *person) String() string { return p.surname + ", " + p.name } var people = []*person{ {"Hans", "Emil"}, {"Max", "Mustermann"}, {"Roma", "Tisch"}, } <file_sep>package main import ( "strings" "fyne.io/fyne/v2" "fyne.io/fyne/v2/app" "fyne.io/fyne/v2/container" "fyne.io/fyne/v2/widget" ) type gui struct { update, delete *widget.Button name, surname *widget.Entry list *widget.List filtered []int selected int } func (g *gui) createDelete() *widget.Button { var btn *widget.Button btn = widget.NewButton("Delete", func() { if g.selected < 0 || g.selected >= len(people) || len(people) == 0 { return } if g.selected == 0 { people = people[1:] } else if g.selected == len(people)-1 { people = people[:len(people)-1] } else { people = append(people[:g.selected], people[g.selected+1:]...) } g.filtered = noFilter() g.list.UnselectAll() g.list.Refresh() g.update.Disable() btn.Disable() }) btn.Disable() return btn } func (g *gui) createFilter() *widget.Entry { f := widget.NewEntry() f.OnChanged = func(prefix string) { g.list.UnselectAll() g.update.Disable() g.delete.Disable() if prefix == "" { g.filtered = noFilter() g.list.Refresh() return } prefix = strings.ToLower(prefix) f := []int{} for i, p := range people { if strings.Index(strings.ToLower(p.surname), prefix) == 0 { f = append(f, i) } } g.filtered = f g.list.Refresh() } return f } func (g *gui) createList() *widget.List { l := widget.NewList(func() int { return len(g.filtered) }, func() fyne.CanvasObject { return widget.NewLabel("") }, func(id widget.ListItemID, o fyne.CanvasObject) { o.(*widget.Label).SetText(people[g.filtered[id]].String()) }) l.OnSelected = func(id widget.ListItemID) { g.selected = g.filtered[id] g.name.SetText(people[g.selected].name) g.surname.SetText(people[g.selected].surname) g.update.Enable() g.delete.Enable() } l.OnUnselected = func(id widget.ListItemID) { g.update.Disable() g.delete.Disable() } return l } func (g *gui) createNew() *widget.Button { return widget.NewButton("Create", func() { p := &person{name: g.name.Text, surname: g.surname.Text} people = append(people, p) g.filtered = noFilter() g.list.Refresh() g.list.Select(len(people) - 1) }) } func (g *gui) createUpdate() *widget.Button { btn := widget.NewButton("Update", func() { if g.selected < 0 || g.selected >= len(people) { return } people[g.selected].name = g.name.Text people[g.selected].surname = g.surname.Text g.list.Refresh() }) btn.Disable() return btn } func main() { a := app.New() w := a.NewWindow("CRUD") g := gui{name: widget.NewEntry(), surname: widget.NewEntry(), filtered: noFilter(), selected: -1} g.list = g.createList() g.update = g.createUpdate() g.delete = g.createDelete() form := widget.NewForm( widget.NewFormItem("Name", g.name), widget.NewFormItem("Surname", g.surname)) top := container.NewGridWithColumns(2, widget.NewForm(widget.NewFormItem("Filter prefix:", g.createFilter()))) bottom := container.NewHBox(g.createNew(), g.update, g.delete) grid := container.NewGridWithColumns(2, g.list, form) w.SetContent( container.NewBorder(top, bottom, nil, nil, grid)) w.ShowAndRun() } func noFilter() []int { all := make([]int, len(people)) for i := range people { all[i] = i } return all } <file_sep>package main import ( "fyne.io/fyne/v2" "fyne.io/fyne/v2/app" "fyne.io/fyne/v2/container" "fyne.io/fyne/v2/data/binding" "fyne.io/fyne/v2/widget" ) func main() { a := app.New() w := a.NewWindow("Temperature Converter") valueC := binding.NewFloat() valueF := celsiusToFarenheit(valueC) entryC := widget.NewEntryWithData(binding.FloatToString(valueC)) entryC.Wrapping = fyne.TextWrapOff entryF := widget.NewEntryWithData(binding.FloatToString(valueF)) entryF.Wrapping = fyne.TextWrapOff w.SetContent(container.NewGridWithColumns(4, entryC, widget.NewLabel("Celsius ="), entryF, widget.NewLabel("Fahrenheit"))) w.ShowAndRun() } type cToF struct { binding.Float } func (c *cToF) Get() (float64, error) { cDeg, _ := c.Float.Get() fDeg := cDeg*(9.0/5.0) + 32 return fDeg, nil } func (c *cToF) Set(f float64) error { cDeg := (f - 32) * (5.0 / 9.0) _ = c.Float.Set(cDeg) return nil } func celsiusToFarenheit(in binding.Float) binding.Float { return &cToF{in} } <file_sep>module github.com/fyne-io/7guis go 1.12 require fyne.io/fyne/v2 v2.1.2 <file_sep># 7 GUIs using Fyne An implementation of the [7 GUIs challenge](https://eugenkiss.github.io/7guis/) using the [Fyne](https://fyne.io) toolkit. ## Counter A simple counter that increments each time the "Count" button is pressed. `go get github.com/fyne-io/7guis/counter` <img src="img/counter.png" width="242" alt="counter GUI" /> ## Temperature Converter The temperature converter allows users to enter a value in degrees C or degrees F and will automatically update the other field. `go get github.com/fyne-io/7guis/temperature-converter` <img src="img/temperature-converter.png" width="476" alt="temperature converter GUI" /> ## CRUD Demonstration of how data is separated from rendering supporting create, read, update and delete. `go get github.com/fyne-io/7guis/crud` <img src="img/crud.png" width="410" alt="counter GUI" /> <file_sep>package main import ( "fyne.io/fyne/v2/app" "fyne.io/fyne/v2/container" "fyne.io/fyne/v2/data/binding" "fyne.io/fyne/v2/widget" ) func main() { a := app.New() w := a.NewWindow("Counter") count := binding.NewInt() button := widget.NewButton("Count", func() { i, _ := count.Get() _ = count.Set(i + 1) }) w.SetContent(container.NewGridWithColumns(2, widget.NewLabelWithData(binding.IntToString(count)), button)) w.ShowAndRun() }
498025682cc1f0a37e53105e344ceaf16256b930
[ "Markdown", "Go Module", "Go" ]
6
Go
fyne-io/7guis
d8f22531984e47f24b9e5b7696e1c060ef25014f
ceddb2d897bda6c2c3c6c5a9e6b7738d4e9bc8cb
refs/heads/master
<repo_name>mikoto2000/OASIZ_DOMElementSorter<file_sep>/README.md OASIZ_DOMElementSorter ====================== XML element sort tool. Usage: ------ ```sh Useage: Main [options] INPUT_XML Options: --excludeXPath XPATH : XPath for exclude values. --useValue (-V) XPATH : XPath for sort values. -h (--help) : print help. -o OUTPUT_XML : output file path. ``` ```sh java -jar OASIZ_DOMElementSorter-x.x.x.jar --excludeXPath EXCLUDE_NODE_XPATH --useValue SORT_VALUE1 --useValue SORT_VALUE2 -o OUTPUT_FILE INPUT_FILE # 1. `--excludeXPath`: 属性 UUID, TIMESTAMP を削除 # 2. `-V .`: タグ名でソート # 3. `-V ./NAME/text()`: タグ名が同一なら NAME の値でソート # 4. `-o test.xml`: ソート結果を test.xml へ出力 # 5. `input.xml`: インプット XML ファイル java -jar OASIZ_DOMElementSorter-x.x.x.jar \ --excludeXPath "//*/@UUID|//*/@TIMESTAMP" \ -V . \ -V ./NAME/text() \ -o test.xml \ input.xml ``` Requirements: ------------- - java version "1.8.0_112" or later. License: -------- Copyright (C) 2019 mikoto2000 This software is released under the MIT License, see LICENSE このソフトウェアは MIT ライセンスの下で公開されています。 LICENSE を参照してください。 Author: ------- mikoto2000 <<EMAIL>> <file_sep>/settings.gradle rootProject.name = 'OASIZ_DOMElementSorter' <file_sep>/src/main/java/jp/dip/oyasirazu/domelementsorter/package-info.java /** * DOM エレメントをソートするためのユーティリティ。 */ package jp.dip.oyasirazu.domelementsorter; <file_sep>/build.gradle plugins { id 'checkstyle' id 'jacoco' id "io.freefair.lombok" version "5.0.0-rc4" } apply { plugin 'java' plugin 'eclipse' } sourceCompatibility = 11 targetCompatibility = 11 version = '2.0.0' [compileJava, compileTestJava]*.options*.encoding = "UTF-8" repositories { jcenter() } dependencies { compile 'args4j:args4j:2.0.16' testCompile "junit:junit:4.11" testCompile "org.hamcrest:hamcrest-all:1.3" } // for checkstyle [checkstyleMain, checkstyleTest]*.ignoreFailures = true tasks.withType(Checkstyle) { reports { xml.enabled false html.enabled true } } // for Jacoco jacocoTestReport { reports { xml.enabled false csv.enabled false html.destination file("${buildDir}/jacocoHtml") } } jar { manifest { attributes 'Implementation-Title': 'XML element sort tool.' attributes 'Implementation-Version': '2.0.0' attributes "Main-Class" : "jp.dip.oyasirazu.domelementsorter.Main" } from configurations.compile.collect { it.isDirectory() ? it : zipTree(it) } }
6ab1d03ca94fd419061f48537d86b7b05cede2e3
[ "Markdown", "Java", "Gradle" ]
4
Markdown
mikoto2000/OASIZ_DOMElementSorter
5fa99cec7d46eb2281a8c34a7d66b4f4eb35c4d9
0f9039b53f9abcb29850f8b53b8772cbe4eb4c0f
refs/heads/master
<file_sep># require 'selenium-webdriver' Given(/^I am on the main page$/) do # @browser = Selenium::WebDriver.for :chrome visit 'http://localhost:8080/CSCI310Project1/InputServlet2.jsp' end Then(/^I should see a text field named "topic"/) do expect(page).to have_field("topic") end Then(/^I should see a text field named "shape"$/) do expect(page).to have_field("shape") end Then(/^I should see a text field named "width"$/) do expect(page).to have_field("width") end Then(/^I should see a text field named "height"$/) do expect(page).to have_field("height") end Then(/^I should see a checkbox named "bordersBox"$/) do expect(page).to have_field("bordersBox") end Then(/^I should see a checkbox named "rotationsBox"$/) do expect(page).to have_field("rotationsBox") end Then(/^I should see a checkbox named "saveBox"$/) do expect(page).to have_field("saveBox") end When (/^I enter "([^"]*)" into the topic box$/) do |topicArg| fill_in('topic', :with => topicArg) end When (/^I enter "([^"]*)" into the shape box$/) do |shapeArg| fill_in('shape', :with => shapeArg) end When (/^press Build Collage$/) do click_on 'Build Collage' end Then(/^I should see a collage for the topic "([^"]*)" and in the shape of "([^"]*)"$/) do |string, string2| expect(page).to have_content string expect(page).to have_content string2 end # Then(/^I should see a collage for the topic "([^"]*)" and in the shape of "([^"]*)"$/) do |arg1| # expect(page).to have_selector("img", :alt => arg1) # end <file_sep>Given(/^I am on the collage display page$/) do visit 'http://localhost:8080/CSCI310Project1/CollageDisplay.jsp' end Then(/^I should see an export as png button$/) do expect(page).find_by_id('exportButtonPNG').value = "exportButtonPNG" # expect(page).to have_selector("button", :id =>"exportButtonPNG") end Then(/^I should see an export as pdf button$/) do expect(page).to have_selector("button", :id =>"exportButtonPDF") end Then(/^I should have a secure connection$/) do expect(page).to have_current_path("https", url: true) end Then(/^I should see a gallery for past collages created$/) do expect(page).to have_selector("div", :id =>"previousCollage") end <file_sep>package cucumber; import org.junit.runner.RunWith; import cucumber.api.CucumberOptions; import cucumber.api.junit.Cucumber; @RunWith(Cucumber.class) @CucumberOptions( features = "Feature" ,glue={"stepDefinition"} ) public class CucumberRunner { } // This code will copy part of one picture to another picture // public static Picture makeCollage (Picture pict, Picture pict2, Picture pict3) // { <file_sep>require('capybara') require('capybara/cucumber') require('r_spec') Capybara.register_driver :chrome do |app| Capybara::Selenium::Driver.new(app, :browser => :chrome) end Capybara.default_driver = :chrome <file_sep>package collage; import java.util.List; import java.util.ArrayList; import java.util.Random; import java.awt.geom.AffineTransform; import java.awt.image.AffineTransformOp; import java.awt.image.BufferedImage; import java.awt.image.RescaleOp; import collage.Picture; import googleTesting.Searching; public final class Collage { public List<String> getUrls(String topic) { Searching newSearch = new Searching(); List<String> urls = new ArrayList<String>(); try { urls = newSearch.searchQuery(topic); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return urls; } public List<Integer> getAngles() { List<Integer> angles = new ArrayList<Integer>(); for (int i = 0; i < 30; i++) { Random rand = new Random(); int input = rand.nextInt(91) - 45; angles.add(input); } return angles; } // // This code will copy part of one picture to another picture // public static Picture makeCollage (Picture pict, Picture pict2, Picture pict3) // { // int xStart, xEnd; // int yStart, yEnd; // // /* xStart = 250; // yStart = 150; // xEnd = 400; // yEnd = 300; */ // // // declare variables for the loop // int xIndex, xIndex1, xIndex2; // int yIndex, yIndex1, yIndex2; // int pixel1, pixel2; // // // get width and height of picture // int width = pict.getWidth(); // int height = pict.getHeight(); // // // create a bit "empty canvas" for new picture // int width2 = width + pict2.getWidth() + pict3.getWidth(); // int height2 = height + pict2.getHeight(); // Picture pictNew = new Picture (width2, height2); // // // create a for loop to access/manipulate each pixel // // copy pict to pictNew // for ( xIndex = 0 ; xIndex < width ; xIndex = xIndex + 1 ) { // for ( yIndex = 0 ; yIndex < height ; yIndex = yIndex + 1 ) { // // get the pixel from the original picture base on X,Y position // xIndex1 = xIndex; // yIndex1 = yIndex; // pixel1 = pict.getPixel (xIndex1, yIndex1); // // pictNew.setPixel(xIndex, yIndex, pixel1); // } // } // // int widthA = pict2.getWidth(); // int heightA = pict2.getHeight(); // // // create a for loop to access/manipulate each pixel for the lower image // // i.e., append pict2 to be below pict in pictNew // for ( xIndex = 0 ; xIndex < widthA ; xIndex = xIndex + 1 ) // { // for ( yIndex = 0 ; yIndex < heightA ; yIndex = yIndex + 1 ) // { // // get the pixel from the original picture base on X,Y position // xIndex1 = xIndex; // yIndex1 = yIndex; // pixel1 = pict2.getPixel (xIndex1, yIndex1); // // // determine the corresponding pixel in the new picture // xIndex2 = xIndex ; // yIndex2 = yIndex + height; // pictNew.setPixel (xIndex2, yIndex2, pixel1); // } // } // // int widthB = pict3.getWidth(); // int heightB = pict3.getHeight(); // // create a for loop to access/manipulate each pixel for the lower image // // i.e., add pict3 to the right // for ( xIndex = 0 ; xIndex < widthB ; xIndex = xIndex + 1 ) // { // for ( yIndex = 0 ; yIndex < heightB ; yIndex = yIndex + 1 ) // { // // get the pixel from the original picture base on X,Y position // xIndex1 = xIndex; // yIndex1 = yIndex; // pixel1 = pict3.getPixel (xIndex1, yIndex1); // // // determine the corresponding pixel in the new picture // xIndex2 = xIndex + widthA; // yIndex2 = yIndex + height; // pictNew.setPixel (xIndex2, yIndex2, pixel1); // } // } // // // create a for loop to access/manipulate each pixel for the lower image // // add pict2 to the right once more // for ( xIndex = 0 ; xIndex < widthA ; xIndex = xIndex + 1 ) // { // for ( yIndex = 0 ; yIndex < heightA ; yIndex = yIndex + 1 ) // { // // get the pixel from the original picture base on X,Y position // xIndex1 = xIndex; // yIndex1 = yIndex; // pixel1 = pict2.getPixel(xIndex1, yIndex1); // // // determine the corresponding pixel in the new picture // xIndex2 = xIndex + widthA + widthB; // yIndex2 = yIndex + height; // pictNew.setPixel (xIndex2, yIndex2, pixel1); // } // } // // return pictNew; // } public static Picture make30Collage (int new_width, int new_height, List<String> nameList, List<Integer> angelList) { Picture pictNew = new Picture (new_width, new_height); int row = 5; int col = 6; // decide the width and height of each component picture // each is 1/20th of the new picture int width = (int)Math.ceil(new_width / 5); int height = (int)Math.ceil(new_height / 4); // System.out.println("width: " + width + ", height: " + height); List<Picture> pictList = new ArrayList<Picture>(); for (int k = 0; k < nameList.size(); k++) { String name = nameList.get(k); Picture pict = new Picture(width, height, name); pict.addFrame(); // rotate the picture to angel degree int angel = angelList.get(k).intValue(); if ( angel != 0 ) pict.rotateImage(angel); pictList.add(pict); } // decide the area each component picture needs to cover int cw = (int)Math.ceil(new_width / col); int ch = (int)Math.ceil(new_height / row); int diffw = (int)Math.ceil((width - cw) / 4); int diffh = (int)Math.ceil((height - ch) / 4); // System.out.println(cw + "," + ch + "," + diffw + "," + diffh); // determine start position of each picture List<Integer> x_arr = new ArrayList<Integer>(); List<Integer> y_arr = new ArrayList<Integer>(); for (int i = 0; i < col; i++) { for (int j = 0; j < row; j++) { int x = cw * i; x -= (int)(Math.random() * diffw); x_arr.add(x); int y = ch * j; y -= (int)(Math.random() * diffh); y_arr.add(y); } } // shuffle pictures int count = 30; int[] orderList = new int[count]; for (int k = 0; k < count; k++) { orderList[k] = k; } for (int i = 0; i < count; i++) { int j = (int)(Math.random() * count); // Get a random index out of count int temp = orderList[i]; // Swap orderList[i] = orderList[j]; orderList[j] = temp; } // add each component picture to new picture for (int n = 0; n < count; n++) { int k = orderList[n]; System.out.println(k); System.out.println(pictList.size()); int idx = k % pictList.size(); Picture pict = pictList.get(idx); int start_x = x_arr.get(k).intValue(); int start_y = y_arr.get(k).intValue(); start_x -= pict.getXPos(); start_y -= pict.getYPos(); System.out.println("start " + n + ":" + start_x + ", " + start_y); System.out.println(pict.getXPos() + ", " + pict.getYPos()); for (int i = 0; i < pict.getWidth(); i++) { int x = i + start_x; for (int j = 0; j < pict.getHeight(); j++) { int y = j + start_y; int pixel = pict.getPixel(i, j); // System.out.println("*** " + i + " " + j + " " + pixel); if ( pixel != 0 ) pictNew.setPixel(x, y, pixel); } } } return pictNew; } }<file_sep>require 'selenium-webdriver' Given(/^I am on Collage homepage$/) do @browser = Selenium::WebDriver.for :chrome @browser.navigate.to 'http://google.com' # @browser.navigate.to 'http://localhost:8080/CSCI310Project1/InputServlet.jsp' # visit 'http://localhost:8080/CSCI310Project1/InputServlet.jsp' end When /^I add "(.*)" to the search box$/ do |item| @browser.find_element(:name, 'q').send_keys(item) end # # And /^click the Search Button$/ do # @browser.find('input[type="submit"]').click # end # # Then /^"(.*)" should be mentioned in the results$/ do |item| # @browser.title.should include(item) # @browser.quit # end <file_sep>Given(/^I am on the home page$/) do visit "http://localhost:8080/CSCI310Servlet1.0/driver?login=text" end Then(/^I should see a field "([^"]*)"$/) do |arg1| page.find_by_id('username').should == arg1 end Then(/^I should see a field "([^"]*)"$/) do |arg1| page.find_by_id('password').should == arg1 end
b7fa38dc9be7f53a4e5677b2093249128dfe0ac4
[ "Java", "Ruby" ]
7
Ruby
johndwyer127/CSCI_310_Project2
8eb16db9a6b60b1b189764e435e99763ebb1af1c
78b9137600b9a1560352033f7c0ee82b55e2ab56
refs/heads/master
<file_sep>var util = require('../../utilities.js') const Discord = require('discord.js') module.exports = { config: { default: true }, events: { async message (client, db, moduleName, message) { if (!message.member) return var prefix = db.prepare('SELECT value FROM config WHERE guild=? AND type=?').get(message.guild.id, 'prefix').value if (message.content.startsWith(prefix) || message.content.startsWith('<@' + client.user.id + '>')) { var param = message.content.split(' ') if (message.content.startsWith(prefix)) { param[0] = param[0].split(prefix)[1] } else { param.splice(0, 1) } if (!param[0]) return var command = db.prepare('SELECT * FROM customs WHERE guild=? AND name=?').all(message.guild.id, param[0].toLowerCase()) if (command.length > 0) command = command[Math.floor(Math.random() * command.length)] else return if (await util.permCheck(message, false, command.name, client, db)) { switch (command.type) { case 'simple': message.channel.send(command.command) break case 'webhook': let hooks = (await message.channel.fetchWebhooks()).filter( h => h.name === 'simple' ) let hook if (hooks.size === 0) { hook = await message.channel.createWebhook('simple', { avatar: message.author.displayAvatarURL() }) } else { hook = hooks.first() await hook.edit({ avatar: message.author.displayAvatarURL() }) } message.delete() hook .sendSlackMessage({ username: message.member.displayName, text: eval('`' + command.command + '`'), // eslint-disable-line }) .catch(console.error) break case 'embed': message.channel .send(new Discord.MessageAttachment(command.command)) .catch(function (error) { util.log( client, param[0] + ' failed with ' + error + '\n ' + command.command ) if (error === 'Error: 403 Forbidden') { util.log( client, 'removed ' + command.command + ' from ' + param[0].toLowerCase() ) db.prepare( 'DELETE FROM customs WHERE WHERE guild=? AND name=?' ).run(message.guild.id, param[0].toLowerCase()) } }) break } } } } } } <file_sep>module.exports = { async reqs (client, db) { db.prepare( 'CREATE TABLE IF NOT EXISTS customs (guild TEXT, name TEXT, type TEXT, command TEXT)' ).run() }, commands: { custom: { desc: 'Displays all custom commands for this server', async execute (client, message, param, db) { let commands = db .prepare('SELECT name FROM customs WHERE guild=? GROUP BY name') .all(message.guild.id) message.channel.send( `Available commands: ${commands.map(e => e.name).join(', ')}` ) } }, add: { desc: 'Adds a new custom command.', usage: 'add [simple/webhook/embed] <name> <link>', async execute (client, message, param, db) { var name = param[2].toLowerCase() var type = param[1].toLowerCase() if (!['simple', 'webhook', 'embed'].includes(type)) return message.channel.send('Invalid type') param = param.slice(3) let command = db .prepare('SELECT type FROM customs WHERE guild=? AND name=? LIMIT 1') .all(message.guild.id, name) db.prepare( 'INSERT INTO customs (guild, name, type, command) VALUES (?,?,?,?)' ).run(message.guild.id, name, type, param .join(' ') .split('\\n') .join('\n')) if (command.length === 0) message.reply('Command added') else message.reply('Command updated') } }, remove: { usage: 'remove [simple/webhook/embed] <name> <content>', desc: 'Deletes a custom command.', async execute (client, message, param, db) { var name = param[2].toLowerCase() var type = param[1].toLowerCase() if (!['simple', 'webhook', 'embed'].includes(type)) return message.channel.send('Invalid type') param = param.slice(3) let command = param .join(' ') .split('\\n') .join('\n') var exCommand = db .prepare('SELECT command FROM customs WHERE guild=? AND name=? AND type=? AND command=?') .all(message.guild.id, name, type, command) if (exCommand.length > 0) { db.prepare('DELETE FROM customs WHERE guild=? AND name=? AND type=? AND command=?').run(message.guild.id, name, type, command) message.reply('Command removed') } else { message.reply('Command not found') } } } } }
dbbe42be3215da85760543e4ad9fe705bbccd706
[ "JavaScript" ]
2
JavaScript
jorgev259/lotus_customs
61b9f15be98f4f4f0282c5cfc32ce623926a18f4
47753302125cef85214919dfdd7e016dfe15e27d
refs/heads/master
<repo_name>guilhermeRangel/SistemaDeLeiloes<file_sep>/View/src/JanelaCadastro.java import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; public class JanelaCadastro implements ActionListener{ JanelaMenu janelaMenu = null; JFrame janela = new JFrame(); JPanel painel = new JPanel(); JLabel rotulo = new JLabel("Insira seus dados: "); //campos de dados JTextField nome = new JTextField(100); JTextField cpf = new JTextField(100); JTextField email = new JTextField(100); JButton btnCadastrar = new JButton("Cadastrar"); JButton btnLimpar = new JButton("Limpar"); public static void main(String args[]) { new JanelaCadastro(); } public JanelaCadastro() { //definimos o título da janela janela.setTitle("Sistema de Compras - Cadastro Cliente"); //definimos a largura e a altura da janela janela.setSize(400, 400); janela.setLocation(400, 200); janela.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //ADD componentes ---------------------------- painel.add(rotulo); painel.add(nome); painel.add(cpf); painel.add(email); nome.setText("Digite seu nome:"); cpf.setText("CPF: 000.000.000-00"); email.setText("<EMAIL>"); painel.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 20)); //add Delegates btnCadastrar.addActionListener(this); btnLimpar.addActionListener(this); //add btns painel.add(btnCadastrar); painel.add(btnLimpar); janela.add(painel);//mostramos a janela janela.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnCadastrar) { //factory Cliente cliente = new Cliente(nome.getText(), cpf.getText(), email.getText()); Cliente.setInstancia(cliente); JOptionPane.showMessageDialog(null, "Cadastro Efetuado com Sucesso!!"); janela.setVisible(false); janelaMenu = new JanelaMenu(); } if (e.getSource() == btnLimpar) { nome.setText(""); cpf.setText(""); email.setText(""); } } } <file_sep>/Model/src/Cliente.java public class Cliente extends Pessoa { //singleton private static Cliente instancia; public Cliente(String nome, String cpf, String email) { super(nome, cpf, email); } public static Cliente getInstance() { if (instancia == null) { instancia = new Cliente(); } return instancia; } public static Cliente getInstancia() { return instancia; } public static void setInstancia(Cliente instancia) { Cliente.instancia = instancia; } public Cliente() { super(); } @Override public String toString() { return " nome: " + getNome() + " cpf: " + getCpf() + " email: " + getEmail(); } } <file_sep>/View/src/JanelaInicial.java import javax.swing.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; public class JanelaInicial implements ActionListener{ JFrame janelaPrincipal = new JFrame(); JPanel painel = new JPanel(); JLabel BemVindo = new JLabel("Bem Vindo selecione: "); JanelaCadastro janelaCadastro = null; JButton btnCliente = new JButton("Cliente"); JButton btnAdm = new JButton("Administrador"); public static void main(String args[]) { new JanelaInicial(); } public JanelaInicial() { janelaPrincipal.setTitle("Sistema de Leiloes"); janelaPrincipal.setSize(200, 200); janelaPrincipal.setLocation(400, 200); janelaPrincipal.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); //add Delegates btnCliente.addActionListener(this); btnAdm.addActionListener(this); painel.add(BemVindo); painel.add(btnCliente); painel.add(btnAdm); janelaPrincipal.add(painel);//mostramos a janela janelaPrincipal.setVisible(true); } @Override public void actionPerformed(ActionEvent e) { if (e.getSource() == btnCliente) { janelaPrincipal.setVisible(false); janelaCadastro = new JanelaCadastro(); } if (e.getSource() == btnAdm) { JOptionPane.showMessageDialog(null, "Nao ta pronto"); } } } <file_sep>/README.md # SistemaDeLeiloes Pontifícia Universidade Católica do Rio Grande do Sul Escola Politécnica Bacharelado em Engenharia de Software Disciplina: Projeto e Arquitetura de Software Trabalho 2 Na primeira parte da disciplina, um dos desafios apresentados aos estudantes foi o de implementação de algum estilo arquitetural estudado de maneira que pudesse ser feita uma prova de conceito do envio de lances de um possível comprador de um sistema de leilões. Neste trabalho 2, este contexto do sistema de leilões será novamente utilizado, de maneira que possam ser explorados padrões de projeto como forma de solução reutilizável para as regras de negócio deste sistema. Sendo assim, no contexto do T2, algumas decisões arquiteturais serão requisitadas: 1. A arquitetura do sistema deve seguir o estilo arquitetural camadas. A quantidade de camadas fica a critério do grupo, sendo que, pelo menos, deve-se ter camadas de interface, negócios e persistência; 2. Deve ser possível múltiplos clientes acessar os leilões disponíveis para lances. Tal requisição pode demandar na criação/uso de mais uma camada e/ou estilo arquitetural; Os requisitos funcionais do sistema de leilões são: 1. um cliente pode fazer lances e propor leilões; 2. no papel de proponente de um leilão, pode também fechar um leilão; 3. no papel de cliente pode dar quantos lances quiser; 4. no papel de administrador uma pessoa pode consultar os leilões concluídos e pendentes; 5. no papel de proponente, uma pessoa pode consultar todos os seus leilões ativos e fechados. No que diz respeito aos padrões de projeto: 1. deve ser utilizado, pelo menos, 1 padrão de projeto em cada uma das camadas da aplicação; O trabalho deve ser desenvolvido individualmente ou em dupla.  Critérios de avaliação: O trabalho II terá os seguintes pesos: 30% - apresentação 70% - artefatos  Apresentação:  Visão geral da arquitetura do sistema e aplicação dos padrões de projeto;  Solução (tática) desenvolvida para o requisito não-funcional;  Apresentação do protótipo do sistema o Artefatos;  Artefatos:  Documento de requisitos do sistema:  Documento de arquitetura – baseado no template do OpenUp – definição de padrões de arquitetura utilizados;  Design da solução (tática) desenvolvida – baseado no template do OpenUp – definição de padrões de projeto utilizados. Diagramas de Classes UML. Diagrama de Sequencia referente aos requisitos de efetuar lances e fechar leilão  Códigos-fonte do sistema. Considerações finais: - todos os produtos de trabalhos (arquivos) devem ser compactados em um único arquivo que deverá ser submetido via Moodle. Alternativas: github. - o professor pode ser considerado como stakeholder do projeto para entendimento dos requisitos. <file_sep>/Controller/src/Controller.java public class Controller { public Double converteStringParaDouble(String desc){ return Double.parseDouble(desc); } } <file_sep>/Model/src/Proposta.java public class Proposta { private String cli; private Double valorLance; public Proposta(String cli, Double valorLance) { this.cli = cli; this.valorLance = valorLance; } public Proposta(String clinteProposta) { } public String getCli() { return cli; } public void setCli(String cli) { this.cli = cli; } public Double getValorLance() { return valorLance; } public void setValorLance(Double valorLance) { this.valorLance = valorLance; } @Override public String toString() { return "Proposta{" + "cli=" + cli + ", valorLance=" + valorLance + '}'; } } <file_sep>/Model/src/Produto.java public class Produto { private String nomeProduto; private String descricao; private Double valorInicial; private String imagemProduto; public Produto(String nomeProduto, String descricao, Double valorInicial) { this.nomeProduto = nomeProduto; this.descricao = descricao; this.valorInicial = valorInicial; } public String getNomeProduto() { return nomeProduto; } public void setNomeProduto(String nomeProduto) { this.nomeProduto = nomeProduto; } public String getDescricao() { return descricao; } public void setDescricao(String descricao) { this.descricao = descricao; } public Double getValorInicial() { return valorInicial; } public void setValorInicial(Double valorInicial) { this.valorInicial = valorInicial; } public String getImagemProduto() { return imagemProduto; } public void setImagemProduto(String imagemProduto) { this.imagemProduto = imagemProduto; } @Override public String toString() { return "Produto{" + "nomeProduto='" + nomeProduto + '\'' + ", descricao='" + descricao + '\'' + ", valorInicial=" + valorInicial + +'}'; } }
a3667563c2303d5543fed78175e7b6ec7b788430
[ "Markdown", "Java" ]
7
Java
guilhermeRangel/SistemaDeLeiloes
1f4cc0473b12ebd3f962b48d430b68519ed3eaac
270fe36839b153096e657461bd1cee1029a9f29a
refs/heads/master
<file_sep># redMine - project management software # Copyright (C) 2006 <NAME> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class Enumeration < ActiveRecord::Base acts_as_list :scope => 'opt = \'#{opt}\'' before_destroy :check_integrity validates_presence_of :opt, :name validates_uniqueness_of :name, :scope => [:opt] validates_length_of :name, :maximum => 30 OPTIONS = { "IPRI" => :enumeration_issue_priorities, "DCAT" => :enumeration_doc_categories, "ACTI" => :enumeration_activities }.freeze def self.get_values(option) find(:all, :conditions => {:opt => option}, :order => 'position') end def self.default(option) find(:first, :conditions => {:opt => option, :is_default => true}, :order => 'position') end def option_name OPTIONS[self.opt] end def before_save Enumeration.update_all("is_default = #{connection.quoted_false}", {:opt => opt}) if is_default? end def <=>(enumeration) position <=> enumeration.position end def to_s; name end private def check_integrity case self.opt when "IPRI" raise "Can't delete enumeration" if Issue.find(:first, :conditions => ["priority_id=?", self.id]) when "DCAT" raise "Can't delete enumeration" if Document.find(:first, :conditions => ["category_id=?", self.id]) when "ACTI" raise "Can't delete enumeration" if TimeEntry.find(:first, :conditions => ["activity_id=?", self.id]) end end end <file_sep># redMine - project management software # Copyright (C) 2006-2007 <NAME> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. require File.dirname(__FILE__) + '/../test_helper' class MailHandlerTest < Test::Unit::TestCase fixtures :users, :projects, :enabled_modules, :roles, :members, :issues, :trackers, :enumerations FIXTURES_PATH = File.dirname(__FILE__) + '/../fixtures' CHARSET = "utf-8" include ActionMailer::Quoting def setup ActionMailer::Base.delivery_method = :test ActionMailer::Base.perform_deliveries = true ActionMailer::Base.deliveries = [] @expected = TMail::Mail.new @expected.set_content_type "text", "plain", { "charset" => CHARSET } @expected.mime_version = '1.0' end def test_add_note_to_issue raw = read_fixture("add_note_to_issue.txt").join MailHandler.receive(raw) issue = Issue.find(2) journal = issue.journals.find(:first, :order => "created_on DESC") assert journal assert_equal User.find_by_mail("<EMAIL>"), journal.user assert_equal "Note added by mail", journal.notes end private def read_fixture(action) IO.readlines("#{FIXTURES_PATH}/mail_handler/#{action}") end def encode(subject) quoted_printable(subject, CHARSET) end end <file_sep># redMine - project management software # Copyright (C) 2006-2007 <NAME> # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # of the License, or (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. class MailHandler < ActionMailer::Base # Processes incoming emails # Currently, it only supports adding a note to an existing issue # by replying to the initial notification message def receive(email) # find related issue by parsing the subject m = email.subject.match %r{\[.*#(\d+)\]} return unless m issue = Issue.find_by_id(m[1]) return unless issue # find user user = User.find_active(:first, :conditions => {:mail => email.from.first}) return unless user # check permission return unless user.allowed_to?(:add_issue_notes, issue.project) # add the note issue.init_journal(user, email.body.chomp) issue.save end end
5a9469335b4d17549c1ae9801c910b4cf1501faa
[ "Ruby" ]
3
Ruby
mcm-xx/redmine
079258540814b664e583eaf46c9ccd616dbda9e9
92ae5bbecd9eedf5639a7fe782b0d46377c92713
refs/heads/master
<file_sep>git-as-npm === A quick and dirty (for now) script that gets git to behave a little more like NPM at times when we'd like it to. `publish` is the only command that currently works. Like so: git-as-npm publish Why? --- NPM is great for managing JS modules. However, private modules aren't free, and maintaining your own registry isn't, either. Thankfully, you can install NPM dependencies directly from Git, like so: "blah-lib": "git+ssh://git@github.com/blah/blah-lib.git" You can also install specific tags or commits, by appending `#` on the end, like so: git+ssh://git@github.com/blah/blah-lib.git#0.0.3 But the process by which you tag these releases is entirely manual. Making it not manual --- So what does this script do? 1. Checks out a branch called `release` (or creates it if it doesn't exist). 2. Merges your current branch into `release`. 3. Pulls down a remote copy of the `release` branch, to sync up which version numbers have already been released. 4. Runs `npm prepublish`, if that script exists. 5. Creates a tag with your current `package.json` version number, throwing an error if that release already exists. 6. Adds a new remote, as specified in the `repository` field of package.json 7. Pushes this up to git 8. Tidies up after itself, deleting the remote and returning you to your original branch. Ta-da --- It doesn't handle everything - you still need to specify the version when doing an `npm install` and so on, but hopefully it makes things a little easier. <file_sep>#!/usr/bin/env node var path = require('path') require('shelljs/global') require('colors') if (process.argv[2] !== 'publish') { process.stderr.write("publish is the only action available for now, sorry.\n".red) exit(1) } if (!which('git')) { echo('You must have git installed to run this.') exit(1) } if (test('-f', './package.json') === false) { process.stderr.write('This directory does not have a package.json file.\n'.red) exit(1) } var package = require(path.resolve('./package.json')) if (!package.repository || package.repository.type !== 'git') { process.stderr.write("package.json does not list a git repository.".red) exit(1) } var statusOutput = exec('git status --porcelain', {silent: true}) if (statusOutput.code !== 0 || statusOutput.output != '') { process.stderr.write('The repo must be up to date with no uncommitted changes. git status failed with:\n'.red) process.stderr.write(statusOutput.output) exit(1) } var getRemotes = exec('git remote -v', {silent: true}) var remotes = getRemotes.output.split('\n') var hasGitAsNPMRemote = remotes.some(function(remote){ var parts = remote.split('\t') return parts[0] === 'git-as-npm' }) if (hasGitAsNPMRemote) { process.stderr.write("git-as-npm origin is already specified. It shouldn't be.\n".red) exit(1) } var addRepo = exec('git remote add git-as-npm ' + package.repository.url) if (addRepo.code !== 0) { stderr.write("Add remote failed:\n".red) stderr.write(addRepo.output) } var currentBranch = exec('git rev-parse --abbrev-ref HEAD', {silent: true}).output.trim() if (currentBranch === 'release') { process.stderr.write('You are currently in the release branch. Please switch to the branch you want to deploy.\n'.red) exit(1) } var failed = function() { // Quick reset function to change back to original branch in case of issues exec('git remote remove git-as-npm', {silent: true}) exec('git reset HEAD --hard', {silent: true}) exec('git checkout ' + currentBranch, {silent: true}) exit(1) } var branchExists = exec('git rev-parse --verify release', {silent: true}) if (branchExists.code === 128) { exec('git checkout -b release', {silent: true}) } else if (branchExists.code === 0) { exec('git checkout release', {silent: true}) process.stdout.write('Pulling latest releases...\n') var pullResult = exec('git pull git-as-npm release', {silent: true}) if (pullResult.code !== 0) { process.stderr.write('Pull failed:\n'.red) process.stderr.write(pullResult.output) failed() } } else { process.stderr.write('Unrecognised result from switching branch:\n'.red) process.stderr.write(branchExists.output) failed() } var mergeOutput = exec('git merge ' + currentBranch, {silent: true}) if (mergeOutput.code !== 0) { process.stderr.write('Error merging ' + currentBranch + ' branch into release.\n'.red) process.stderr.write(mergeOutput.output) failed() } if (package.scripts.prepublish) { process.stdout.write('Running prepublish script...\n') var prepublish = exec('npm run prepublish') if (prepublish.code != 0) { process.stderr.write("Prepublish failed.\n".red) failed() } exec('git add -A') var commitResult = exec('git commit -a -m "git-as-npm prepublish run"') var statusOutput = exec('git status --porcelain', {silent: true}) if (statusOutput.code !== 0 || statusOutput.output != '') { process.stderr.write("Commit of prepublished code failed:\n".red) process.stderr.write(commitResult.output) failed() } } var version = package.version var createTag = exec('git tag -a ' + version + ' -m "Automatically generated by git-as-npm"', {silent: true}) if (createTag.code === 128) { process.stderr.write(("Release " + version + " already exists. Please bump the version number in package.json\n").red) failed() } else if (createTag.code !== 0) { process.stderr.write("Tag creation failed:\n".red) process.stderr.write(createTag.output) failed() } var pushResult = exec('git push git-as-npm release --follow-tags', {silent: true}) if (pushResult.code !== 0) { process.stderr.write("Push failed:\n".red) process.stderr.write(pushResult.output) failed() } process.stdout.write(("Version " + version + " pushed to git.\n")) exec('git remote remove git-as-npm', {silent: true}) exec('git checkout ' + currentBranch, {silent: true})
e1dbc403542dd8e73c1b2cda4bd9134be5173e80
[ "Markdown", "JavaScript" ]
2
Markdown
alastaircoote/git-as-npm
eba3df3618392b24992a4217f08ad0e0a8c5c681
73b97dbb6d378d95c74b65c4773ff7f21e545f3a
refs/heads/main
<repo_name>shebbar93/check-petrol-diesel-price<file_sep>/src/components/Map.js import { MapContainer, TileLayer } from "react-leaflet"; import LocationMarker from './LocationMarker' import CityInfo from '../CityInfo.json' const Map = ({ eventData, center, zoom }) => { const markers = eventData.map((ev, index) => { if (CityInfo[ev.cityState]) { return <LocationMarker key={index} city={ev.cityState} state={CityInfo[ev.cityState].admin_name} lat={CityInfo[ev.cityState].lat} lng={CityInfo[ev.cityState].lng} dieselPrice={ev.dieselPrice} dieselChange={ev.dieselChange} petrolPrice={ev.petrolPrice} petrolChange={ev.petrolChange} /> } return null }) return ( <div className='map'> <MapContainer center={[center.lat, center.lng]} zoom={zoom}> <TileLayer attribution='&copy; <a href="http://osm.org/copyright">OpenStreetMap</a> contributors' url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png" /> {markers} </MapContainer> </div> ) } Map.defaultProps = { center: { lat: 28.7041, lng: 77.1025 }, zoom: 5 } export default Map <file_sep>/src/components/Header.js import { Icon } from '@iconify/react' import fuel from '@iconify/icons-mdi/fuel-pump' const Header = () => { return ( <header className="header"> <h1><Icon icon={fuel} /> Check Petrol & Diesel Price [ Credits : &copy; Economic times]</h1> </header> ) } export default Header
ee7f60920bb19140abb14704298eadab6d6e05d9
[ "JavaScript" ]
2
JavaScript
shebbar93/check-petrol-diesel-price
b56608b0ed2926b1c0e3531f97d08c57427754b4
caffb3ebb2ebb00ede258b763bf2e3cbed1e5ba9
refs/heads/master
<file_sep>#include <stdlib.h> #include <stdio.h> #include "lab2.h" /* binary_char: test binary_char */ void evidence_binary_char() { printf("*** testing binary_char\n"); printf("- expecting 00010001:\n"); binary_char(17); printf("\n"); printf("- expecting 00100111:\n"); binary_char(39); printf("\n"); printf("- expecting 00000000:\n"); binary_char(0); printf("\n"); printf("- expecting 11111111:\n"); binary_char(255); printf("\n"); printf("- expecting 01101110: \n"); binary_char(110); printf("\n"); } /* evidence_octal_char: test octal_char */ void evidence_octal_char() { printf("*** testing octal_char\n"); printf("- expecting 21:\n"); octal_char(17); printf("\n"); printf("- expecting 47:\n"); octal_char(39); printf("\n"); printf("- expecting 000:\n"); octal_char(0); printf("\n"); printf("- expecting 377:\n"); octal_char(255); printf("\n"); printf("- expecting 156: \n"); octal_char(110); printf("\n"); } /* evidence_hex_char: test hex_char */ void evidence_hex_char() { printf("*** testing hex_char\n"); printf("- expecting 11:\n"); hex_char(17); printf("\n"); printf("- expecting 27:\n"); hex_char(39); printf("\n"); printf("- expecting 00:\n"); hex_char(0); printf("\n"); printf("- expecting FF:\n"); hex_char(255); printf("\n"); printf("- expecting 6E: \n"); hex_char(110); printf("\n"); } /* evidence_hex_int: test hex_int */ void evidence_hex_int() { printf("*** testing hex_int\n"); printf("- expecting 2D6F1:\n"); hex_int(186097); printf("\n"); printf("- expecting 18A09:\n"); hex_int(100873); printf("\n"); printf("- expecting 0000:\n"); hex_int(0000); printf("\n"); printf("- expecting 0064:\n"); hex_int(100); printf("\n"); } /* evidence_binary_int: test binary_int */ void evidence_binary_int() { printf("*** testing binary_int\n"); printf("- expecting 10011100010001:\n"); binary_int(10001); printf("\n"); printf("- expecting 11000101000001001:\n"); binary_int(100873); printf("\n"); printf("- expecting 0:\n"); binary_int(0000); printf("\n"); } /* evidence_octal_int: test octal_int */ void evidence_octal_int() { printf("*** testing octal_int\n"); printf("- expecting 17:\n"); octal_int(21); printf("\n"); printf("- expecting 39:\n"); octal_int(47); printf("\n"); printf("- expecting 0:\n"); octal_int(00); printf("\n"); printf("- expecting 110:\n"); octal_int(150); printf("\n"); printf("- expecting 336: \n"); octal_int(222); printf("\n"); } int main(int argc, char *argv[]) { evidence_binary_char(); evidence_octal_char(); evidence_hex_char(); evidence_binary_int(); evidence_octal_int(); evidence_hex_int(); return 0; } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 3 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include "hw3.h" void help_read(char** s, int len) { int i = 0; int j = 0; for (i = 0; i < len; i++) { while (s[i][j] != '\0') { printf("%c", s[i][j]); j++; } } } void evidence_split_at() { printf("*** testing split_at\n"); char *new_sentence1 = *split_at("The quick brown fox jumped over the \ lazy dog", ' '); printf("- expecting Thequickbrownfoxjumpedoverthelazydog \n"); help_read(&new_sentence1, 7); printf("\n"); char *new_sentence2 = *split_at("remove all e's in this sentence.", 'e'); help_read(&new_sentence2, 7); printf("- expecting rmov all 's in this sntnc.\n"); /* char *new_sentence3 = *split_at("foooooool!", "o"); help_read(&new_sentence3, 2); printf("- expecting fl! \n");*/ } void evidence_add_measurements() { struct measurement one; one.value = 10; one.units = malloc(2 * sizeof(char)); strcpy(one.units, "in"); one.exponent = 2; struct measurement two; two.value = 3; two.units = malloc(2 * sizeof(char)); strcpy(two.units, "in"); two.exponent = 2; struct measurement m3; m3 = add_measurements(one, two); printf("%f %s %d\n", m3.value, m3.units, m3.exponent); free(one.units); free(two.units); free(m3.units); } void evidence_scale_measurements() { struct measurement m; m.value = 5; m.units = malloc(2 * sizeof(char)); strcpy(m.units, "in"); m.exponent = 2; struct measurement m4; m4 = scale_measurements(m, 5); printf("%f %s %d\n", m4.value, m4.units, m4.exponent); free(m.units); free(m4.units); } void evidence_multiply_measurements() { struct measurement m5; m5.value = 4; m5.units = strdup("in"); m5.exponent = 2; struct measurement m6; m6.value = 6; m6.units = strdup("in"); m6.exponent = 3; struct measurement m7; m7 = multiply_measurements(m5, m6); printf("%f %s %d\n", m7.value, m7.units, m7.exponent); free(m6.units); free(m5.units); free(m7.units); } void evidence_measurement_tos() { struct measurement m8; m8.value = 9; m8.units = strdup("ft"); m8.exponent = 5; char* str = measurement_tos(m8); int i = 0; while (str[i] != '\0') { printf("%c", str[i]); i++; } free(m8.units); } void evidence_convert_units() { struct conversion c1; struct conversion c2; struct conversion c3; struct conversion c4; struct conversion conversions[4] = { {c1.from = strdup("m"), c1.to = strdup("ft"), \ c1.mult_by = 0.3048}, {c2.from = "ft", c2.to = "in", c2.mult_by = 12}, {c3.from = strdup("lb"), c3.to = strdup("oz"), c3.mult_by = 16}, {c4.from = strdup("min"), c4.to = strdup("sec"), c4.mult_by = 60} }; struct measurement m8; m8.value = 3; m8.units = strdup("m"); m8.exponent = 1; struct measurement m9; m9 = convert_units(conversions, 4, m8, "ft"); printf("%f %s %d\n", m9.value, m9.units, m9.exponent); } double mixture_weight(struct mixture* mixture) { struct element hydrogen = {"hydrogen", 1}; struct element oxygen = {"oxygen", 8}; struct elements *els1[2] = {&hydrogen, &oxygen}; struct atoms[2] = {2, 1}; struct molecule water = {"water", 2, *els1, *atoms}; struct tagged_chemical my_chemical; my_chemical.tag = MOLECULE; my_chemical.chemical.molecule = &water; } int main(int argc, char *argv[]) { evidence_split_at(); evidence_add_measurements(); evidence_scale_measurements(); evidence_multiply_measurements(); evidence_measurement_tos(); evidence_convert_units(); return 0; } <file_sep># CMSC15200 What I did in CMSC 15200 <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "htbl.h" unsigned long int good_hash(char *s) { unsigned int res = 17; unsigned int i = 0; while (s[i]) { printf("%d", s[i]); res = res * 37 + s[i]; i++; } return res; } unsigned long int bad_hash(char *s) { unsigned res = 17; unsigned i = 0; while (s[i]) { while (i < 2) { res = res * 37 + s[i]; i++; } } return res; } htbl *htbl_new(unsigned long int(*h)(char*), unsigned int sz) { htbl *new_htbl = (htbl*) malloc (sizeof(htbl) * sz); new_htbl -> hash = h; new_htbl -> buckets = NULL; new_htbl -> n_buckets = sz; return new_htbl; } unsigned int htbl_n_entries(htbl *t) { int i = 0; int j = 0; struct bucket *bucket; while(t) { while (t -> buckets[i]) { bucket = t -> buckets[i]; while (bucket) { j++; bucket = bucket -> next; } i++; } } return j; } double htbl_load_factor(htbl *t) { int j = 0; int i = htbl_n_entries(t); while(t) { while (t -> buckets[j]) { j++; } } return (i / j); } unsigned int htbl_max_bucket(htbl *t) { int i = 0; int j = 0; while (t -> buckets[i]) { i++; if (i > j) { j = i; } } return j; } void htbl_insert(char *s, htbl *t) { unsigned long int hash = t -> hash(s); unsigned long int new_hash = hash % t -> n_buckets; if (t -> buckets[new_hash] == NULL) { t -> buckets[new_hash] = bucket_cons(s, hash, NULL); } else { t -> buckets[new_hash] = bucket_cons(s, hash, t -> buckets[new_hash]); } } int htbl_member(char *s, htbl *t) { unsigned long int hash = good_hash(s); unsigned new_hash = hash % t -> n_buckets; if (t -> buckets[new_hash]) { if (!strcmp(t -> buckets[new_hash] -> string, s)) { return 1; } while (t -> buckets[new_hash] -> next != NULL) { if (!strcmp(t -> buckets[new_hash] -> string, s)) { return 1; } t -> buckets[new_hash] = t -> buckets[new_hash] -> next; } return 0; } return 0; } void htbl_show(htbl *t) { int i = 0; while (t -> buckets[i]) { printf("h: %lu str: %s ", t -> buckets[i] -> hash, t -> buckets[i] -> string); t -> buckets[i] = t -> buckets[i] -> next; ++i; } } void htbl_free(htbl *t) { int i = 0; struct bucket *bucket; struct bucket *temp; while (t -> buckets[i]) { bucket = t -> buckets[i]; while (bucket) { temp = bucket -> next; free(bucket); bucket = temp; } temp = bucket; free(temp); } } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 4 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "hw4.h" int intlist_nth(intlist* xs, unsigned int n) { if (xs == NULL) { fprintf(stderr, "list is not sufficiently long."); exit(1); } while (xs != NULL && n != 0) { xs = xs -> next; --n; return intlist_nth(xs, n); } return xs -> val; } void intlist_set(intlist* xs, unsigned int n, int val) { if (xs == NULL) { fprintf(stderr, "list is not sufficiently long."); exit(1); } if (xs != NULL && n != 0) { xs = xs -> next; --n; intlist_set(xs, n, val); } if (n == 0) { xs -> val = val; } } intlist* intlist_append(intlist* xs, int val) { struct intlist *xs2 = xs; if (xs == NULL) { fprintf(stderr, "list is not sufficiently long."); exit(1); } while (xs -> next != NULL) { xs = xs -> next; } intlist *tail = (struct intlist*) malloc (sizeof(struct intlist)); tail -> val = val; tail -> next = NULL; xs -> next = tail; return xs2; } intlist* intlist_prepend(intlist* xs, int val) { if (xs == NULL) { fprintf(stderr, "list is not sufficiently long."); exit(1); } intlist *head = (struct intlist*) malloc (sizeof(struct intlist)); head -> val = val; head -> next = xs; return head; } void intlist_show(intlist* xs) { if (xs == NULL) { fprintf(stderr, "list is not sufficiently long."); exit(1); } while (xs -> next != NULL) { printf("%d ", xs -> val); xs = xs -> next; } if (xs -> next == NULL) { printf("%d", xs -> val); } } void intlist_free(intlist* xs) { struct intlist *node = xs; while (xs) { node = xs; xs = xs -> next; free(node); } } intlist* add_digits(unsigned int base, intlist* ds1, intlist* ds2) { struct intlist *res = NULL; unsigned int remainder = 0; unsigned int addition = 0; if (ds1 == NULL && ds2 == NULL) { fprintf(stderr, "both numbers do not exist."); exit(1); } while (ds1 && ds2) { addition = ds1 -> val + ds2 -> val + remainder; remainder = 0; if (addition >= base) { addition = base - addition; remainder = 1; } ds1 = ds1 -> next; ds2 = ds2 -> next; if (res == NULL) { res = (struct intlist*) malloc (sizeof(struct intlist)); res -> val = addition; res -> next = NULL; } else { intlist_append(res, addition); } } while (ds1 == NULL && ds2 != NULL) { addition = ds2 -> val + remainder; remainder = 0; while (addition >= base) { addition = addition % base; remainder = addition / base + remainder; intlist_append(res, addition); } ds2 = ds2 -> next; if (res == NULL) { res = (struct intlist*) malloc (sizeof(struct intlist)); res -> val = addition; res -> next = NULL; } else { intlist_append(res, addition); } } while (ds2 == NULL && ds1 != NULL) { addition = ds1 -> val + remainder; remainder = 0; while (addition >= base) { remainder = addition % base; addition = addition / base; intlist_append(res, addition); } ds1 = ds1 -> next; if (res == NULL) { res = (struct intlist*) malloc (sizeof(struct intlist)); res -> val = addition; res -> next = NULL; } else { intlist_append(res, addition); } } return res; } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 3 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include "hw3.h" int helper_length (char* s, char d, int i) { while (s[i] != '\0' && s[i] != d) { i++; } return i; } int helper_length_total (char* s, char d) { int j = 0; int i = 0; while (s[i] != '\0') { if (s[i] == d) { ++j; } ++i; } return j; } char** split_at(char* s, char d) { int k = 0; int a = 0; int b = 0; int c = 0; int total_length = helper_length_total(s, d); char **array = (char**) malloc (total_length * sizeof(char*)); for (k = 0; k < total_length; k++) { int small_length = helper_length(s, d, c); char *small_array = (char*) malloc (small_length * sizeof(char*)); c = small_length; for (a = 0; a < small_length; a++) { small_array[b] = s[b + c]; b++; } *array[k] = *small_array; k++; c++; b = 0; } return array; } struct measurement add_measurements(struct measurement m1, \ struct measurement m2) { struct measurement m3; /* if (m1.units != m2.units) { printf("Units must be the same. \n"); exit(1); } else if (m1.exponent != m2.exponent) { printf("Exponents must be the same. \n"); exit(1); }*/ m3.value = m1.value + m2.value; m3.units = malloc(2 * sizeof(char)); strcpy(m3.units, m1.units); m3.exponent = m1.exponent; return m3; } struct measurement scale_measurements(struct measurement m, double lambda) { struct measurement m4; m4.value = m.value * lambda; m4.units = malloc(2 * sizeof(char)); strcpy(m4.units, m.units); m4.exponent = m.exponent; return m4; } struct measurement multiply_measurements(struct measurement m1, \ struct measurement m2) { struct measurement m7; m7.value = m1.value * m2.value; m7.units = strdup(m1.units); m7.exponent = m1.exponent + m2.exponent; return m7; } char* measurement_tos(struct measurement m) { char result[100]; sprintf(result, "%f %s^%d\n", m.value, m.units, m.exponent); char* res = strdup(result); return res; } struct measurement convert_units(struct conversion* conversions, \ unsigned int n_conversions, struct measurement m, char* to) { int i = 0; struct measurement m8; for (i = 0; i < n_conversions; i++) { if (!strcmp(conversions[i].from, m.units)) { m8.value = m.value * conversions[i].mult_by; m8.units = strdup(m.units); m8.exponent = 1; } } return m8; } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Proj 1 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "pos.h" pos make_pos(unsigned int r, unsigned int c) { struct pos pos1 = {r, c}; return pos1; } <file_sep>evidence_hw3: hw3.h hw3.c evidence_hw3.c clang -o evidence_hw3 -Wall -lm hw3.c evidence_hw3.c <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * PROJ 1 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "logic.h" game* new_game(unsigned int run, unsigned int width, unsigned int height, enum type type) { if (run > width && run > height) { fprintf(stderr, "run must be smaller than width or height"); exit(1); } if (run <= 1) { fprintf(stderr, "run must be greater than 1"); exit(1); } game* new_game = (game*) malloc (sizeof(game)); new_game -> run = run; new_game -> b = board_new(width, height, type);; new_game -> next = BLACK_NEXT; return new_game; } void game_free(game* g) { board_free(g -> b); free(g); } int drop_piece(game* g, unsigned int col) { int i; for (i = g -> b -> height; i >= 0; i--) { struct pos pos = make_pos(i - 1, col); if (board_get(g -> b, pos) == EMPTY) { if (g -> next == BLACK_NEXT) { board_set(g -> b, pos, BLACK); return 1; } else if (g -> next == WHITE_NEXT) { board_set(g -> b, pos, WHITE); return 1; } } } return 0; } void twist(game* g, direction d) { signed int i, j; unsigned int new_pos; board* new_board = board_new(g -> b -> height, g -> b -> width, MATRIX); switch (d) { case CW: for (i = g -> b -> height - 1; i >= 0; i--) { for (j = g -> b -> width - 1; j >= 0; j--) { struct pos pos = make_pos(i, j); if (board_get(g -> b, pos) != EMPTY) { if (board_get(g -> b, pos) == BLACK) { struct pos pos2 = make_pos((g -> b -> width) - new_pos - 1, (g -> b -> height) - i - 1); board_set(new_board, pos2, BLACK); new_pos++; } else { struct pos pos2 = make_pos((g -> b -> width) - new_pos - 1, (g -> b -> height) - i - 1); board_set(new_board, pos2, WHITE); new_pos++; } } } new_pos = 0; } g -> b = new_board; break; case CCW: for (i = g -> b -> height - 1; i >= 0; i--) { for (j = 0; j < g -> b -> width; j++) { struct pos pos = make_pos(i, j); if (board_get(g -> b, pos) != EMPTY) { if (board_get(g -> b, pos) == BLACK) { struct pos pos2 = make_pos((g -> b -> width) - new_pos - 1, i); board_set(new_board, pos2, BLACK); new_pos++; } else { struct pos pos2 = make_pos((g -> b -> width) - new_pos - 1, i); board_set(new_board, pos2, WHITE); new_pos++; } } } new_pos = 0; } g -> b = new_board; break; } } /* checks if there's "run" amounts of a certain cell vertically */ int recursive3(int i, int j, game* g, int counter, enum cell cell) { struct pos pos = make_pos(i, j); if (i < g -> b -> height && j < g -> b -> width) { if (board_get(g -> b, pos) == cell && counter <= g -> run) { counter++; if (counter == g -> run) { return 1; } else { return recursive3(i + 1, j, g, counter, cell); } } } return 0; } /* check if a specified cell has "run" in a row vertically */ int check_vertical(game* g, enum cell cell) { unsigned int i, j; unsigned int counter = 0; for (i = 0; i < g -> b -> height; i++) { for (j = 0; j < g -> b -> width; j++) { struct pos pos = make_pos(i, j); if (board_get(g -> b, pos) == cell) { if (recursive3(i + 1, j, g, counter + 1, cell) == 1) { return 1; } } } } return 0; } /* checks if there's "run" amounts of a certain cell horizontally */ int recursive2(int i, int j, game* g, int counter, enum cell cell) { struct pos pos = make_pos(i, j); if (i < g -> b -> height && j < g -> b -> width) { if (board_get(g -> b, pos) == cell && counter <= g -> run) { counter++; if (counter == g -> run) { return 1; } else { return recursive2(i, j + 1, g, counter, cell); } } } return 0; } /* check if a specified cell has "run" in a row horizontally */ int check_horizontal(game* g, enum cell cell) { unsigned int i, j; unsigned int counter = 0; for (i = 0; i < g -> b -> height; i++) { for (j = 0; j < g -> b -> width; j++) { struct pos pos = make_pos(i, j); if (board_get(g -> b, pos) == cell) { if (recursive2(i, j + 1, g, counter + 1, cell) == 1) { return 1; } } } } return 0; } /* checks if there's "run" of a certain cell diagonally, right-down */ int recursive(int i, int j, game* g, int counter, enum cell cell) { struct pos pos = make_pos(i, j); if (i < g -> b -> height && j < g -> b -> width) { if (board_get(g -> b, pos) == cell && counter < g -> run) { counter++; if (counter == g -> run) { return 1; } else { return recursive(i + 1, j + 1, g, counter, cell); } } } return 0; } /* checks if there's "run" of a certain cell diagonally, left-down */ int recursive_b(int i, int j, game* g, int counter, enum cell cell) { struct pos pos = make_pos(i, j); if (i < g -> b -> height && j < g -> b -> width) { if (board_get(g -> b, pos) == cell && counter < g -> run) { counter++; if (counter == g -> run) { return 1; } else { return recursive_b(i + 1, j - 1, g, counter, cell); } } } return 0; } /* check if a specified cell has "run" in a row diagonally */ int check_diagonal(game* g, enum cell cell) { unsigned int i, j; unsigned int counter = 0; for (i = 0; i < g -> b -> height; i++) { for (j = 0; j < g -> b -> width; j++) { struct pos pos = make_pos(i, j); if (board_get(g -> b, pos) == cell) { if (recursive(i + 1, j + 1, g, counter + 1, cell) == 1) { return 1; } } } } counter = 0; for (i = 0; i < g -> b -> height; i++) { for (j = 0; j < g -> b -> width; j++) { struct pos pos = make_pos(i, j); if (board_get(g -> b, pos) == cell) { if (recursive_b(i + 1, j - 1, g, counter + 1, cell) == 1) { return 1; } } } } return 0; } /* if black has "run" in a row, return 1, else return 0 */ int black_wins(game* g) { if (check_diagonal(g, BLACK) == 1 || check_vertical(g, BLACK) == 1 || check_horizontal(g, BLACK) == 1) { return 1; } return 0; } /* if white has "run" in a row, return 1, else return 0 */ int white_wins(game* g) { if (check_diagonal(g, WHITE) == 1 || check_vertical(g, WHITE) == 1 || check_horizontal(g, WHITE) == 1) { return 1; } return 0; } outcome game_outcome(game* g) { if (black_wins(g) == 1 && white_wins(g) == 1) { return DRAW; } else if (white_wins(g) == 1) { return WHITE_WIN; } else if (black_wins(g) == 1) { return BLACK_WIN; } return IN_PROGRESS; } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 5 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include <string.h> #include "waves.h" double dist(double x0, double y0, double x1, double y1) { return sqrt(pow((x1 - x0), 2) + pow((y1 - y0), 2)); } void draw_waves(int side_length, double scale_red, double scale_green, double scale_blue, int x_offset, int y_offset) { printf("P3 \n"); printf("%d %d \n", side_length, side_length); printf("255 \n"); int center = side_length / 2; x_offset = center + x_offset; y_offset = center + y_offset; int counter_horiz = 0; int counter_vert = 0; for (counter_vert = 0; counter_vert < side_length; counter_vert++) { for (counter_horiz = 0; counter_horiz < side_length; counter_horiz++) { double d = dist(counter_horiz, counter_vert, x_offset, y_offset); double num_b = (sin(d * scale_blue)); double num_r = (sin(d * scale_red)); double num_g = (sin(d * scale_green)); int b = ((num_b + 1.0) * 255) / 2; int r = ((num_r + 1.0) * 255) / 2; int g = ((num_g + 1.0) * 255) / 2; printf("%d %d %d \n", r, g, b); } } } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 2 */ /* all_positive : returns 1 if all elements of the array a with length alen are positive and 0 if not */ int all_positive(int a[], unsigned int alen); /* exists_positive : returns 1 if at least one element of a given array a with length alen is positive and 0 if not */ int exists_positive(int a[], unsigned int alen); /* first_positive : returns the index number of the first positive number of a given array a with length alen. If no positive number, returns -1. */ int first_positive(int a[], unsigned int alen); /* number_positives : returns the number of positive numbers in an array of length alen. */ unsigned int number_positives(int a[], unsigned int alen); /* negate : changes the sign of every element in an array of length alen, except for 0. */ void negate(int a[], unsigned int alen); /* partial_sums : returns a new array containing partial sums over the provided array. */ int* partial_sums(int a[], unsigned int alen); /* rotate_right : modifies a passed-in array so each element appears at one greater index value than before */ void rotate_right(int a[], unsigned int alen); /* concat_strings : concatenates a list of strings into one larger string. */ char* concat_strings(char** strings, unsigned int num_strings); /* rle_encode : uses run-length encoding to compress integer data. */ int* rle_encode(int* in, unsigned int inlen, unsigned int* outlen); /* rle_decode : uses run-length decoding to expand integer data. */ int* rle_decode(int* in, unsigned int inlen, unsigned int* outlen); <file_sep>evidence_hw4: hw4.h hw4.c evidence_hw4.c clang -o evidence_hw4 -Wall -lm hw4.c evidence_hw4.c <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 2 */ typedef struct intlist intlist; struct intlist { int val; intlist* next; }; /* intlist_nth: returns the nth value in an intlist xs, using zero-based indexing. */ int intlist_nth(intlist* xs, unsigned int n); /* intlist_set: overwrites the value in the list at the nth index with the new value val */ void intlist_set(intlist* xs, unsigned int n, int val); /* intlist_append: appends val to the end of the linked list xs, returning the head of the resulting list. */ intlist* intlist_append(intlist* xs, int val); /* intlist_prepend: prepends val to the beginning of the linked list xs, returning the head of the resulting list. */ intlist* intlist_prepend(intlist* xs, int val); /* intlist_show: prints the content of the linked list xs to the screen. */ void intlist_show(intlist* xs); /* intlist_free: reclaims, or frees, space allocated by linked list xs. */ void intlist_free(intlist* xs); intlist* add_digits(unsigned int base, intlist* ds1, intlist* ds2); <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 5 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include <math.h> #include "waves.h" /* runs test for main */ int main(int argc, char *argv[]) { int i, s, x, y; double r, g, b; i = 1; s = 200; r = 1.0; g = 1.0; b = 1.0; x = 0; y = 0; for (i = 1; i < (argc - 1); i++) { if (!strcmp(argv[i], "-s")) { s = atof(argv[i + 1]); i++; } else if (!strcmp(argv[i], "-r")) { r = atof(argv[i + 1]); i++; } else if (!strcmp(argv[i], "-g")) { g = atof(argv[i + 1]); i++; } else if (!strcmp(argv[i], "-b")) { b = atof(argv[i + 1]); i++; } else if (!strcmp(argv[i], "-x")) { x = atoi(argv[i + 1]); i++; } else if (!strcmp(argv[i], "-s")) { y = atof(argv[i + 1]);; i++; } } draw_waves(s, r, g, b, x, y); return 0; } <file_sep>void rectangle(unsigned int w, unsigned int h); int is_prime(unsigned int n); void print_primes(unsigned int n); void replace(char* s, char from, char to); char* reverse (char* s); unsigned int tlist_len(int* list); int* tlist_to_array(int* tlist, unsigned int* outlen); int* array_to_tlist(int* a, unsigned int alen); int* dips(int* a, unsigned int alen, unsigned int* outlen); int match_index(char* s, char** strings, unsigned int nstrings); char* diagonalize(char** strings, usigned int nstrings); <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * PROJ 2 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "board.h" #include "logic.h" board* board_new(unsigned int width, unsigned int height, enum type type) { if (width <= 0 || height <= 0) { fprintf(stderr, "width and height must be positive"); exit(1); } unsigned i, j, size; struct board *board1 = (board*) malloc (sizeof(board)); board1 -> width = width; board1 -> height = height; board1 -> type = type; union board_rep set; switch (type) { case BITS: size = (height * width * 2); if (size % 32 == 0) { size = size / 32; } else { size = (size / 32) + 1; } unsigned int *new_array = (unsigned int*) malloc (sizeof(unsigned int) * size); for (j = 0; j < size; j++) { new_array[j] = 0; } board1 -> u.bits = new_array; return board1; case MATRIX: set.matrix = (cell**) malloc (sizeof(cell*) * height); for (i = 0; i < height; i++) { set.matrix[i] = (cell*) malloc (sizeof(cell) * width); for (j = 0; j < width; j++) { set.matrix[i][j] = EMPTY; } } board1 -> u.matrix = set.matrix; return board1; } } void board_free(board* b) { unsigned int i, length, size; switch (b -> type) { case BITS: length = b -> height * b -> width * 2; size = length; if (size % 32 == 0) { size = size / 32; } else { size = (size / 32) + 1; } free(b -> u.bits); free(b); break; case MATRIX: for (i = 0; i < b -> height; i++) { free(b -> u.matrix[i]); } free(b); break; } } /* helper to print row numbers. */ void print_vertical(unsigned int k) { char alphabet[52] = {'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', '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'}; printf("\n"); if (k < 10) { printf("%d ", k); } else if (10 <= k && k < 36) { printf("%c ", alphabet[k - 10]); } else if (36 <= k && k < 62) { printf("%c ", alphabet[k - 10]); } else if (k >= 62) { printf("? "); } } /* helper to print column numbers. */ void print_horizontal(unsigned int k) { char alphabet[52] = {'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', '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'}; if (k < 10) { printf("%d", k); } else if (10 <= k && k < 36) { printf("%c", alphabet[k - 10]); } else if (36 <= k && k < 62) { printf("%c", alphabet[k - 10]); } else if (k >= 62) { printf("? "); } } /* show the board "bit by bit" */ unsigned int bit_reading(unsigned int new_byte) { if ((new_byte & 3) == 0) { printf("."); new_byte >>= 2; } else if ((new_byte & 3) == 1) { printf("*"); new_byte >>= 2; } else if ((new_byte & 3) == 2) { printf("o"); new_byte >>= 2; } return new_byte; } /* helper to implement board_show for bit representation starting from col 0 */ void bit_show(board *b, unsigned int length, unsigned int size) { unsigned int new_byte, i = 0; unsigned int k = 0; int j; for (j = 0; j < size; j++) { new_byte = b -> u.bits[j]; while ((j == size - 1) && (i < length)) { if (i % (b -> width * 2) == 0) { print_vertical(k); k++; } new_byte = bit_reading(new_byte); i = i + 2; } while ((j != (size - 1)) && (i < (32 * (j + 1)))) { if (i % (b -> width * 2) == 0) { print_vertical(k); k++; } new_byte = bit_reading(new_byte); i = i + 2; } } printf("\n"); } void board_show(board* b) { unsigned int j, length, size; unsigned int i = 0; switch (b -> type) { case BITS: length = b -> height * b -> width * 2; size = length; if (size % 32 == 0) { size = size / 32; } else { size = (size / 32) + 1; } for (j = 0; j < b -> width; j++) { if (j == 0) { printf(" "); } print_horizontal(j); } bit_show(b, length, size); break; case MATRIX: for (i = 0; i <= b -> height; i++) { if (i == 0) { for (j = 0; j < b -> width; j++) { if (j == 0) { printf(" "); } print_horizontal(j); } } else { int k = i - 1; print_vertical(k); for (j = 0; j < b -> width; j++) { struct pos pos = make_pos(i - 1, j); if (board_get(b, pos) == EMPTY) { printf("."); } else if (board_get(b, pos) == BLACK) { printf("*"); } else if (board_get(b, pos) == WHITE) { printf("o"); } } } } printf("\n"); break; } } /* helper to implement board_get for bit representation. */ cell get_helper(board* b, pos p) { unsigned int int_in_array, size, new_byte; unsigned int w = b -> width; size = b -> height * w * 2; unsigned int pos_in_board = ((((w * p.r) + (p.c)) * 2) % 32); int_in_array = (((w * p.r) + (p.c)) * 2) / 32; new_byte = b -> u.bits[int_in_array]; new_byte >>= pos_in_board; if ((new_byte & 3) == 0) { return EMPTY; } else if ((new_byte & 3) == 1) { return BLACK; } else if ((new_byte & 3) == 2) { return WHITE; } } cell board_get(board* b, pos p) { switch(b -> type) { case BITS: return get_helper(b, p); case MATRIX: return b -> u.matrix[p.r][p.c]; } } /* helper to implement board_set for bit representation. */ void set_helper(board* b, pos p, cell c) { unsigned int int_in_array, size; unsigned int w = b -> width; size = b -> height * w * 2; unsigned int pos_in_board = ((((w * p.r) + (p.c)) * 2) % 32); int_in_array = (((w * p.r) + (p.c)) * 2) / 32; unsigned int new_int; if (c == BLACK) { new_int = 1; new_int <<= pos_in_board; b -> u.bits[int_in_array] = ((b -> u.bits[int_in_array]) | new_int); } else if (c == WHITE) { new_int = 2; new_int <<= pos_in_board; b -> u.bits[int_in_array] = (b -> u.bits[int_in_array]) | new_int; } } void board_set(board* b, pos p, cell c) { switch(b -> type) { case BITS: set_helper(b, p, c); break; case MATRIX: b -> u.matrix[p.r][p.c] = c; break; } } <file_sep>#include <stdio.h> #include <stdlib.h> #include <string.h> #include "htbl.h" bucket *bucket_cons(char *s, unsigned long int hash, bucket *b) { bucket *head = (struct bucket*) malloc (sizeof (struct bucket)); head -> string = strdup(s); head -> hash = hash; head -> next = b; return head; } unsigned int bucket_size(bucket *b) { int i = 0; while (b) { i++; b = b -> next; } return i; } void bucket_show(bucket *b) { unsigned i = 0; while (b) { while (b -> string[i]) { printf("%c", b -> string[i]); } b = b -> next; } } void bucket_free(bucket *b) { struct bucket *node = b; while (b) { node = b; b = b -> next; free(node -> string); free(node); } } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 3 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "waves.h" double dist(double x0, double y0, double x1, double y1) { return sqrt(pow((x1 - x0), 2) + pow((y1 - y0), 2)); } void draw_waves(int side_length, int x_offset, int y_offset) { printf("P3 \n"); printf("%d %d \n", side_length, side_length); printf("255 \n"); int center = side_length / 2; x_offset = center + x_offset; y_offset = center + y_offset; int counter_horiz = 0; int counter_vert = 0; for (counter_horiz = 0; counter_horiz < side_length; counter_horiz++) { for (counter_vert = 0; counter_vert < side_length; counter_vert++) { double num = dist(counter_horiz, counter_vert, x_offset, y_offset); num = (sin(num)) + 1.0; int b = (num * 255) / 2; printf("0 0 %d\n", b); } } } <file_sep>#include <stdlib.h> #include <stdio.h> #include "final.h" void rectangle(unsigned int w, unsigned int h) { unsigned int i, j; for (i = 0; i < h; i++) { for (j = 0; j < w; j++) { printf("*"); } printf("\n"); } } int is_prime(unsigned int n) { unsigned int i; for (i = 0; i < n; i++) { if (n % i != 0) { return (n % i != 0); } else { return (n % i != 0); } } } void print_primes(unsigned int n) { unsigned int i; for (i = 2; i < n; i++) { if (is_prime(i)) { printf("%d", i); } printf("\n"); } } void replace(char* s, char from, char to) { unsigned int i = 0; while (s[i]) { if (s[i] == from) { s[i] = to; } i++; } } unsigned int length(char* s) { unsigned int 0; while (s[i]) { i++; } return i; } char* reverse (char* s) { unsigned int length = length(s); char* new_str = (char*) malloc (sizeof(char) * length); unsigned int i; for (i = 0; i < length; i++) { new_str[i] = s[length - i]; } return new_str; } unsigned int tlist_len(int* list) { unsigned int i = 0; while (list[i] != -1) { i++; } return i; } int* tlist_to_array(int* tlist, unsigned int* outlen) { outlen = tlist_len(tlist); unsigned int i; int* new_tlist = (int*) malloc (sizeof(int) * outlen); for (i = 0; i < outlen; i++) { new_tlist[i] = tlist[i]; } return new_tlist; } int* array_to_tlist(int* a, unsigned int alen) { int* new = (int*) malloc (sizeof(int) * alen); int i; for (i = 0; i < alen; i++) { if (a[i] == -1) { fprintf(stderr, "-1 in list"); exit(1); } new[i] = a[i]; } new[alen] = -1; } int* dips(int* a, unsigned int alen, unsigned int* outlen) { unsigned int i; unsigned int j = 0; for (i = 0; i < alen; i++) { if (a[i] < a[i - 1]) { j++; } } } int match_index(char* s, char** strings, unsigned int nstrings); char* diagonalize(char** strings, usigned int nstrings); int main(int argc, char *argv[]) { return 0; } <file_sep>evidence_final1: final.h final.c evidence_final.c clang -Wall -o evidence_final final.c evidence_final.c <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 2 */ #include <stdio.h> #include <stdlib.h> #include "lab2.h" /* aux_one : first helper function to print result from decimal to binaries */ void aux_one(int byte, int byte_two, int count, int bits) { count += 1; if (count == bits) { printf(""); } else if (byte_two % 2 == 0) { aux_one(byte, byte_two / 2, count, bits); printf("0"); } else { aux_one(byte, byte_two / 2, count, bits); printf("1"); } } /* aux_two : second helper function to print result from decimal to octals */ void aux_two(int byte, int byte_two, int count, int bits) { count += 1; if (count == bits) { printf(""); } else if (byte_two % 8 != 0) { aux_two(byte, byte_two / 8, count, bits); printf("%d", byte_two % 8); } else { aux_two(byte, byte_two / 8, count, bits); printf("0"); } } /* aux_three : third helper function to print result from decimal to hexadecimals */ void aux_three(int byte, int byte_two, int count, int bits) { count += 1; if (count == bits) { printf(""); } else if (byte_two % 16 != 0) { aux_three(byte, byte_two / 16, count, bits); int remain = (byte_two % 16); if (remain == 10) { printf("A"); } else if (remain == 11) { printf("B"); } else if (remain == 12) { printf("C"); } else if (remain == 13) { printf("D"); } else if (remain == 14) { printf("E"); } else if (remain == 15) { printf("F"); } else { printf("%d", remain); } } else { aux_two(byte, byte_two / 16, count, bits); printf("0"); } } /* binary_char: main function for translating unsigned char to binary */ void binary_char(unsigned char byte) { int add = 256; int add_byte = byte; int byte_two = add_byte + add; aux_one(byte_two, byte_two, 0, 9); } /* octal_char: main function for translating unsigned char to octal */ void octal_char(unsigned char byte) { int add = 512; int add_byte = byte; int byte_two = add_byte + add; aux_two(byte, byte_two, 0, 4); } /* hex_char: main function for translating unsigned char to binary */ void hex_char(unsigned char byte) { int add = 256; int add_byte = byte; int byte_two = add_byte + add; aux_three(byte, byte_two, 0, 3); } /* binary_int: main function for translating unsigned int to binary */ void binary_int(unsigned int n) { long int add = 34359738368; int byte_two = n + add; aux_one(byte_two, byte_two, 0, 32); } /* octal_int: main function for translating unsigned char to octal*/ void octal_int(unsigned int n) { long int add = 8589934592; long int byte_two = n + add; aux_two(n, byte_two, 0, 12); } /* hex_int: main function for translating unsigned char to hex */ void hex_int(unsigned int n) { long int add = 4294967296; int byte_two = n + add; aux_three(byte_two, byte_two, 0, 9); } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 2 */ #include <stdlib.h> #include <stdio.h> #include <string.h> #include "hw2.h" int all_positive(int a[], unsigned int alen) { int counter = 0; while (counter < alen) { if (a[counter] <= 0) { return 0; } counter++; } return 1; } int exists_positive(int a[], unsigned int alen) { int counter = 0; while (counter < alen) { if (a[counter] > 0) { return (a[counter] > 0); } counter++; } return 0; } int first_positive(int a[], unsigned int alen) { int counter = 0; while (counter < alen) { if (a[counter] > 0) { return counter; } counter++; } return -1; } unsigned int number_positives(int a[], unsigned int alen) { int counter = 0; int pos_count = 0; while (counter < alen) { if (a[counter] > 0) { pos_count++; } counter++; } return pos_count; } void negate(int a[], unsigned int alen) { int counter = 0; while (counter < alen) { if (a[counter] != 0) { a[counter] = - a[counter]; } else { a[counter] = 0; } counter++; } counter = 0; while (counter < alen) { printf("%d ", a[counter]); counter++; } } int helper_partial_sums(int a[], unsigned int alen) { int counter, sum; sum = 0; for (counter = 0; counter <= alen; ++counter) { sum += a[counter]; } return sum; } int* partial_sums(int a[], unsigned int alen) { int *ptr = (int*) malloc ((alen + 1) * sizeof(int)); int i = 0; if (ptr == NULL) { printf("Memory is NULL. \n"); exit(1); } else { for (i = 0; i <= (alen); ++i) { if (i == 0) { ptr[i] = 0; } else { ptr[i] = helper_partial_sums(a, i - 1); } } } return ptr; } void rotate_right(int a[], unsigned int alen) { int* ptr = (int*) malloc (alen * sizeof(int)); if (ptr == NULL) { printf("Memory is NULL. \n"); exit(1); } int i = 0; int counter = 0; if (ptr == NULL) { printf("Memory is NULL. \n"); exit(1); } else { for (i = 0; i < alen; ++i) { if (i == 0) { ptr[0] = a[alen - 1]; } else { ptr[i] = a[i - 1]; } } } for (counter = 0; counter < alen; counter++) { printf("%d ", ptr[counter]); } } /* helper that finds the length of the output array of rle_encode */ int rle_length(int* in, unsigned int inlen, unsigned int outlen) { int num = 0; int length = 0; int counter = 0; for (counter = 0; counter <= inlen; counter++) { if (counter == 0) { num = in[counter]; } else if (num != in[counter]) { num = in[counter]; length++; } } return (length * 2); } int* rle_encode(int* in, unsigned int inlen, unsigned int* outlen) { int length = rle_length(in, inlen, *outlen); int *ptr = (int*) malloc (length * sizeof(int)); if (ptr == NULL) { printf("Memory is NULL. \n"); exit(1); } int index = 0; int length2 = 0; int num_storage = 0; int counter = 0; for (counter = 0; counter <= inlen; counter++) { if (counter == 0) { num_storage = in[counter]; length2++; } else if (num_storage == in[counter]) { length2++; } else { ptr[index] = length2; ptr[index + 1] = num_storage; num_storage = in[counter]; index = index + 2; length2 = 1; } } return ptr; } /* helper that finds the length of the output array in rle_decode */ int rle_length_two(int* in, unsigned int inlen, unsigned int outlen) { int length = 0; int counter = 0; if (length % 2 != 0) { printf("length of input array must be an even number \n"); exit(1); } for (counter = 0; counter <= inlen; counter++) { if (counter % 2 == 0) { length = length + in[counter]; } } return length; } int* rle_decode(int* in, unsigned int inlen, unsigned int* outlen) { int length = rle_length_two(in, inlen, *outlen); int *ptr = (int*) malloc (length * sizeof(int)); if (ptr == NULL) { printf("Memory is NULL. \n"); exit(1); } int counter = 0; int counter2 = 0; int index = 0; for (counter = 0; counter < inlen; counter++) { if (counter % 2 == 0) { if (in[counter] <= 0) { printf("Cannot have non-positive counts. \n"); exit(1); } for (counter2 = 0; counter2 < in[counter]; counter2++) { ptr[index] = in[counter + 1]; index++; } } } return ptr; } char* concat_strings(char** strings, unsigned int num_strings) { int i = 0; int length = 0; for (i = 0; i < num_strings; i++) { length = length + strlen(strings[i]); } char *str = (char*) malloc ((length + (num_strings)) * sizeof(char)); if (str == NULL) { printf("Memory is NULL. \n"); exit(1); } i = 0; int j = 0; int k = 0; for (i = 0; i < num_strings; i++) { for (j = 0; j < strlen(strings[i]); j++) { if (j == 0 && i != 0) { str[k] = ' '; k++; } if (strings[i][j] != '\0') { str[k] = strings[i][j]; k++; } } } str[k] = '\0'; return str; } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 2 */ /* binary_char: conversion between binary and base-10 */ void binary_char(unsigned char byte); void binary_int(unsigned int n); /* hex_char: conversion between hexadecimals and base-10 */ void hex_char(unsigned char byte); void hex_int(unsigned int n); /* octal_char: conversion between octal and base-10 */ void octal_char(unsigned char byte); void octal_int(unsigned int n); <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 3 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "waves.h" /* runs test for main */ int main(int argc, char *argv[]) { draw_waves(200, 0, 0); return 0; } <file_sep>## Downturn - Matrix and Bit Representation Like Connect Four, but with a specified -w width, -h height, -r run (with an objective to get "run" pieces in a row) and -m or -b to specify a matrix or bit representation. <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * HW 2 */ #include <stdlib.h> #include <stdio.h> #include "hw2.h" /* evidence_all_positive: test all_positive */ void evidence_all_positive() { printf("*** testing all_positive\n"); int new_array1[3] = {3, 0, 3}; printf("- expecting 0: %d \n", all_positive(new_array1, 3)); int new_array2[5] = {-3, 8, 9, 2, -6}; printf("- expecting 0: %d \n", all_positive(new_array2, 5)); int new_array3[2] = {1, 100}; printf("- expecting 1: %d \n", all_positive(new_array3, 2)); int new_array4[0] = {}; printf("- expecting 1: %d \n", all_positive(new_array4, 0)); } /* evidence_exists_positive: test exists_positive */ void evidence_exists_positive() { printf("*** testing exists_positive\n"); int array1[3] = {-3, -3, 1}; printf("- expecting 1: %d \n", exists_positive(array1, 3)); int array2[7] = {-12, -100, 0, 0, 0, -3, -478}; printf("- expecting 0: %d \n", exists_positive(array2, 7)); int array3[5] = {6, 8, 0, -5, 100}; printf("- expecting 1: %d \n", exists_positive(array3, 5)); int new_array4[0] = {}; printf("- expecting 0: %d \n", exists_positive(new_array4, 0)); } /* evidence_first_positive: test first_positive */ void evidence_first_positive() { printf("*** testing first_positive\n"); int array1[3] = {-3, -3, 1}; printf("- expecting 2: %d \n", first_positive(array1, 3)); int array2[7] = {-12, -100, 0, 0, 0, -3, -478}; printf("- expecting -1: %d \n", first_positive(array2, 7)); int array3[5] = {6, 8, 0, -5, 100}; printf("- expecting 0: %d \n", first_positive(array3, 5)); } /* evidence_number_positives: test number_positives */ void evidence_number_positives() { printf("*** testing number_positives\n"); int array1[5] = {0, -8, 5, 3, 9}; printf("- expecting 3: %d \n", number_positives(array1, 5)); int array2[4] = {-53, -12, 0}; printf("- expecting 0: %d \n", number_positives(array2, 3)); int array3[4] = {3, 3, 3, 4}; printf("- expecting 4: %d \n", number_positives(array3, 4)); } /* evidence_negate: test negate */ void evidence_negate() { printf("*** testing negate\n"); int array1[5] = {-5, -8, 10, 16, 0}; printf("- expecting 5, 8, -10, -16, 0: \n"); negate(array1, 5); printf("\n"); int array2[5] = {3, 6, 12, 9, 27}; printf("- expecting -3 -6 -12 -9 -27: \n"); negate(array2, 5); printf("\n"); int array3[3] = {0, 0, 0}; printf("- expecting 0 0 0: \n"); negate(array3, 3); printf("\n"); int array4[4] = {-9, -56, -3}; printf("- expecting 9 56 3: \n"); negate(array4, 3); printf("\n"); } /* helper_one : prints results of returned int array */ void helper_one(int a[], unsigned int length) { int i = 0; for (i = 0; i < length; i++) { printf("%d ", a[i]); } } /* helper_two : prints results of returned char array */ void helper_two(char a[], unsigned int length) { int i = 0; for (i = 0; i < length; i++) { printf("%c", a[i]); } } /* evidence_partial_sums : test partial_sums */ void evidence_partial_sums() { printf("*** testing partial_sums \n"); int array1[7] = {-12, -100, 0, 0, 0, -3, -478}; int *new_array1 = partial_sums(array1, 7); printf("- expecting 0 -12 -112 -112 -112 -112 -115 -593: \n"); helper_one(new_array1, 8); printf("\n"); int array2[5] = {-5, -8, 10, 16, 0}; int *new_array2 = partial_sums(array2, 5); printf("- expecting 0 -5 -13 -3 13 13: \n"); helper_one(new_array2, 6); printf("\n"); int array3[3] = {0, 0, 0}; int *new_array3 = partial_sums(array3, 3); printf("- expecting 0 0 0 0: \n"); helper_one(new_array3, 4); printf("\n"); int array4[0] = {}; int *new_array4 = partial_sums(array4, 0); printf("- expecting : \n"); helper_one(new_array4, 0); printf("\n"); } /* evidence_rotate_right : test rotate_right */ void evidence_rotate_right() { printf("*** testing rotate_right\n"); int array1[5] = {-5, -8, 10, 16, 0}; printf("- expecting 0 -5 -8 10 16: \n"); rotate_right(array1, 5); printf("\n"); int array2[5] = {-3, 8, 9, 2, -6}; printf("- expecting -6 -3 8 9 2: \n"); rotate_right(array2, 5); printf("\n"); int array3[7] = {-19, 15, 2, -8, 0, 4, -4}; printf("- expecting -4 -19 15 2 -8 0 4: \n"); rotate_right(array3, 7); printf("\n"); } /* evidence_rle_encode : test rle_encode */ void evidence_rle_encode() { printf("*** testing rle_encode \n"); unsigned int outlen = 0; int array1[7] = {1, 3, 3, 6, 5, 5, 9}; int *new_array1 = rle_encode(array1, 7, &outlen); printf("- expecting 1 1 2 3 1 6 2 5 1 9 \n"); helper_one(new_array1, 10); printf("\n"); int array2[5] = {0, 0, 0, 0, 0}; int *new_array2 = rle_encode(array2, 5, &outlen); printf("- expecting 5 0: \n"); helper_one(new_array2, 2); printf("\n"); int array3[3] = {8, 9}; int *new_array3 = rle_encode(array3, 3, &outlen); printf("- expecting 1 8 1 9: \n"); helper_one(new_array3, 4); printf("\n"); int array4[0] = {}; int *new_array4 = rle_encode(array4, 0, &outlen); printf("- expecting : \n"); helper_one(new_array4, 0); printf("\n"); free(new_array1); free(new_array2); free(new_array3); free(new_array4); } /* evidence_rle_decode : testing rle_decode */ void evidence_rle_decode() { printf("*** testing rle_decode \n"); unsigned int outlen = 0; int array1[10] = {1, 1, 2, 3, 1, 6, 2, 5, 1, 9}; int *new_array1 = rle_decode(array1, 10, &outlen); printf("- expecting 1 3 3 6 5 5 9 \n"); helper_one(new_array1, 7); printf("\n"); int array2[2] = {5, 0}; int *new_array2 = rle_decode(array2, 2, &outlen); printf("- expecting 0 0 0 0 0: \n"); helper_one(new_array2, 5); printf("\n"); int array3[4] = {1, 8, 1, 9}; int *new_array3 = rle_decode(array3, 4, &outlen); printf("- expecting 8 9: \n"); helper_one(new_array3, 2); printf("\n"); int array4[0] = {}; int *new_array4 = rle_decode(array4, 0, &outlen); printf("- expecting : \n"); helper_one(new_array4, 0); printf("\n"); free(new_array1); free(new_array2); free(new_array3); free(new_array4); } /* evidence_concat_strings: test concat_strings */ void evidence_concat_strings() { printf("*** testing concat_strings\n"); char *array1[3] = {"Hello", "World", "!"}; char *new_array1 = concat_strings(array1, 3); printf("- expecting Hello World ! \n"); helper_two(new_array1, 13); printf("\n"); char *array2[6] = {"Am", "I", "doing", "this", "right", "?"}; char *new_array2 = concat_strings(array2, 6); printf("- expecting Am I doing this right ? \n"); helper_two(new_array2, 23); printf("\n"); char *array3[4] = {"Pompeii", "is", "interesting", "."}; char *new_array3 = concat_strings(array3, 4); printf("- expecting Pompeii is interesting . \n"); helper_two(new_array3, 24); printf("\n"); free(new_array1); free(new_array2); free(new_array3); } /* main: run the evidence functions above */ int main(int argc, char *argv[]) { evidence_all_positive(); evidence_exists_positive(); evidence_first_positive(); evidence_number_positives(); evidence_negate(); evidence_partial_sums(); evidence_rotate_right(); evidence_rle_encode(); evidence_rle_decode(); evidence_concat_strings(); return 0; } <file_sep>/* <NAME>, rsah * CS 152, Winter 2020 * Lab 3 */ #include <stdlib.h> #include <stdio.h> #include <math.h> #include "waves.h" /* evidence_dist: test dist */ void evidence_dist() { printf("*** testing dist\n"); printf("- expecting 5 %f: \n", dist(3, 4, 0, 0)); printf("- expecting 5.099 %f: \n", dist(4, 3, 3, -2)); printf("- expecting 11.4018 %f: \n", dist(-10, 0, 1, 3)); } /* main: run the evidence function above */ int main(int argc, char *argv[]) { evidence_dist(); return 0; } <file_sep>#include <stdlib.h> #include <stdio.h> #include "adrbook.h" const char *_bst_todo_format = "TODO [bst]: %s\nhalting\n"; bst *bst_singleton(vcard *c) { bst *res = (bst*) malloc(sizeof(bst)); res -> c = c; res -> lsub = res -> rsub = NULL; return res; } int bst_insert(bst *t, vcard *c) { if (t == NULL) { fprintf(stderr, "Empty bst."); exit(1); } else if (strcmp(t -> c -> cnet, c -> cnet) > 0) { if (t -> lsub == NULL) { t -> lsub = bst_singleton(c); return 1; } else { return bst_insert(t -> lsub, c); } } else if (strcmp(t -> c -> cnet, c -> cnet) < 0) { if (t -> rsub == NULL) { t -> rsub = bst_singleton(c); return 1; } else { return bst_insert(t -> rsub, c); } } else { return 0; } } unsigned int bst_num_entries(bst *t) { if (t == NULL) { return 0; } else { return 1 + bst_num_entries(t -> lsub) + bst_num_entries(t -> rsub); } } unsigned int bst_height(bst *t) { if (t == NULL) { return 0; } unsigned int counter1 = bst_height(t -> lsub); unsigned int counter2 = bst_height(t -> rsub); if (counter1 > counter2) { return counter1 + 1; } else { return counter2 + 1; } } vcard *bst_search(bst *t, char *cnet, int *n_comparisons) { ++*n_comparisons; if (t) { if (strcmp(t -> c -> cnet, cnet) == 0) { return t -> c; } else { if (strcmp(t -> c -> cnet, cnet) < 0) { return bst_search(t -> rsub, cnet, n_comparisons); } else if (strcmp(t -> c -> cnet, cnet) > 0) { return bst_search(t -> lsub, cnet, n_comparisons); } } return NULL; } } /* note: f is the destination of the output, e.g. the screen; * our code calls this with stdout, which is where printfs are sent; * simply use fprintf rather than printf in this function, and pass in f * as its first parameter */ unsigned int bst_c(FILE *f, bst *t, char c) { unsigned int num_cs = 0; if (t) { if (t -> c -> cnet[0] == c) { num_cs++; bst_c(f, t -> lsub, c); fprintf(f, "%c \n", c); bst_c(f, t -> rsub, c); } else { bst_c(f, t -> lsub, c); bst_c(f, t -> rsub, c); } } else { return num_cs; } } void bst_free(bst *t) { if (t != NULL) { bst_free(t -> lsub); bst_free(t -> rsub); free(t); } } <file_sep>evidence_hw2: hw2.h hw2.c evidence_hw2.c clang -o evidence_hw2 -Wall -lm hw2.c evidence_hw2.c <file_sep>waves: waves.h waves.c main_waves.c clang -Wall -lm -o waves waves.c main_waves.c evidence_waves: waves.h waves.c evidence_waves.c clang -Wall -lm -o evidence_waves waves.c evidence_waves.c
55e5b3074de824740105e781adc5981c4694c2a7
[ "Markdown", "C", "Makefile" ]
30
C
Rusah1129/CMSC15200
24cbe42e1bde049975f6593ebf4e9071011faf6e
65f036fff61aa8dc148ad6242ea21cda2cd282b2
refs/heads/master
<repo_name>sahilsk/expressApp-skeleton<file_sep>/README.md ## Skeleton for quick started with express application. ### Run application ``` js "start": "node server.js", "watch": "NODE_ENV=development nodemon server.js", "w7watch": "nodemon server.js", "testwatch": "NODE_ENV=development mocha ./test -G -w -c -d", "w7testwatch": "mocha ./test -G -c -d -w", "browserify": "browserify -t hbsfy public/javascripts/client.js > public/javascripts/bundle.js", "watchify": "watchify -t hbsfy public/javascripts/client.js -o public/javascripts/bundle.js" ``` ### Routes Use root `routes.js` file to add server side routes Use `public/javascripts/client/routes.js` to add client side routes (bacbone) ### Package Configured -------- ``` js { "name": "application-name", "version": "0.0.1", "private": true, "scripts": { "start": "node server.js", "watch": "NODE_ENV=development nodemon server.js", "w7watch": "nodemon server.js", "testwatch": "NODE_ENV=development mocha ./test -G -w -c -d", "w7testwatch": "mocha ./test -G -c -d -w", "browserify": "browserify -t hbsfy public/javascripts/client.js > public/javascripts/bundle.js", "watchify": "watchify -t hbsfy public/javascripts/client.js -o public/javascripts/bundle.js" }, "dependencies": { "express": "3.5.1", "jade": "*", "less-middleware": "~0.1.15", "config": "~0.4.35", "kue": "~0.7.5", "backbone": "^1.1.2", "jquery": "^2.1.0", "handlebars": "~1.3.0" }, "devDependencies": { "mocha": "~1.18.2", "should": "~3.2.0", "hbsfy": "~1.3.2", "request": "~2.34.0", "superagent": "~0.17.0" } } ```<file_sep>/public/javascripts/client/routes.js var $ = require("jquery") var Backbone = require("backbone") Backbone.$ = $; window.Backbone = Backbone; var AppRouter = Backbone.Router.extend({ routes: { "help/:id" :"help", "posts/:id": "getPost", "*actions": "defaultRoute" }, help :function(id){ alert("hi"+id); } }); var app_router = new AppRouter; app_router.on('route:getPost', function (id) { alert( "Get post number " + id ); }); //Unhandled path app_router.on('route:defaultRoute', function (actions) { alert( "Action not support : " + actions ); }); Backbone.history.start();<file_sep>/controllers/docklets.js exports.index = function(req, res){ res.send("500") } exports.list = function(req, res){ res.send("doclets list"); }<file_sep>/controllers/index.js /* * GET home page. */ exports.index = function(req, res){ //TODO : show docklets screen res.redirect("/docklets") //res.render('index', { title: 'Docklet Dashboard' }); };
98282065f800d7834426604cf8d81f08c505774c
[ "Markdown", "JavaScript" ]
4
Markdown
sahilsk/expressApp-skeleton
c89947484d35c1f432bb1bc886ab833e5f230b0d
2ee42668910aa03533becc61cc5a12e85f7d60b6
refs/heads/master
<file_sep> /** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing the category model * @module models-category * @requires jQuery * @requires collections-labels * @requires ACCESS * @requires backbone * @requires localstorage */ define(["jquery", "collections/labels", "access", "backbone", "localstorage"], function ($, Labels, ACCESS, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Model} * @augments module:Backbone.Model * @memberOf module:models-category * @alias module:models-category.Category */ var Category = Backbone.Model.extend({ /** * Default models value * @alias module:models-category.Category#defaults * @type {map} * @static */ defaults: { access: ACCESS.PRIVATE, created_at: null, created_by: null, updated_at: null, updated_by: null, deleted_at: null, deleted_by: null, has_duration: true }, /** * Constructor * @alias module:models-category.Category#initialize * @param {object} attr Object literal containing the model initialion attributes. */ initialize: function (attr) { _.bindAll(this, "setUrl", "validate", "toExportJSON"); if (!attr || _.isUndefined(attr.name)) { throw "\"name\" attribute is required"; } // Check if the track has been initialized if (!attr.id) { // If local storage, we set the cid as id if (window.annotationsTool.localStorage) { this.attributes.id = this.cid; } this.toCreate = true; } // If localStorage used, we have to save the video at each change on the children if (window.annotationsTool.localStorage) { if (!attr.created_by) { this.attributes.created_by = annotationsTool.user.get("id"); this.attributes.created_by_nickname = annotationsTool.user.get("nickname"); } } if (attr.tags) { this.attributes.tags = this.parseJSONString(attr.tags); } if (attr.settings) { this.attributes.settings = this.parseJSONString(attr.settings); if (this.attributes.settings.hasScale === undefined) { this.attributes.settings.hasScale = true; } } else { this.attributes.settings = {hasScale: true}; } if (annotationsTool.user.get("id") === attr.created_by) { this.attributes.isMine = true; } else { this.attributes.isMine = false; } if (attr.access === ACCESS.PUBLIC) { this.attributes.isPublic = true; } else { this.attributes.isPublic = false; } if (attr.labels && _.isArray(attr.labels)) { this.attributes.labels = new Labels(attr.labels, this); delete attr.labels; } else if (!attr.labels) { this.attributes.labels = new Labels([], this); } else if (_.isObject(attr.labels) && attr.labels.model) { this.attributes.labels = new Labels(attr.labels.models, this); delete attr.labels; } if (attr.id) { this.attributes.labels.fetch({async: false}); } //this.set(attr); }, /** * Parse the attribute list passed to the model * @alias module:models-category.Category#parse * @param {object} data Object literal containing the model attribute to parse. * @return {object} The object literal with the list of parsed model attribute. */ parse: function (data) { var attr = data.attributes ? data.attributes : data, parseDate = function (date) { if (_.isNumber(date)) { return new Date(date); } else if (_.isString) { return Date.parse(date); } else { return null; } }; if (attr.created_at) { attr.created_at = parseDate(attr.created_at); } if (attr.updated_at) { attr.updated_at = parseDate(attr.updated_at); } if (attr.deleted_at) { attr.deleted_at = parseDate(attr.deleted_at); } if (attr.settings) { attr.settings = this.parseJSONString(attr.settings); } if (annotationsTool.user.get("id") === attr.created_by) { attr.isMine = true; } else { attr.isMine = false; } if (attr.access === ACCESS.PUBLIC) { attr.isPublic = true; } else { attr.isPublic = false; } if (attr.tags) { attr.tags = this.parseJSONString(attr.tags); } if (annotationsTool.localStorage && _.isArray(attr.labels)) { attr.labels = new Labels(attr.labels, this); } if (!annotationsTool.localStorage && attr.scale_id && (_.isNumber(attr.scale_id) || _.isString(attr.scale_id))) { attr.scale = annotationsTool.video.get("scales").get(attr.scale_id); } if (data.attributes) { data.attributes = attr; } else { data = attr; } return data; }, /** * Validate the attribute list passed to the model * @alias module:models-category.Category#validate * @param {object} data Object literal containing the model attribute to validate. * @return {string} If the validation failed, an error message will be returned. */ validate: function (attr) { var tmpCreated, self = this; if (attr.id) { if (this.get("id") !== attr.id) { this.id = attr.id; this.setUrl(attr.labels); } if (!this.ready && attr.labels && attr.labels.url && (attr.labels.length) === 0) { attr.labels.fetch({ async: false, success: function () { self.ready = true; } }); } } if (attr.description && !_.isString(attr.description)) { return "\"description\" attribute must be a string"; } if (attr.settings && (!_.isObject(attr.settings) && !_.isString(attr.settings))) { return "\"description\" attribute must be a string or a JSON object"; } if (attr.tags && _.isUndefined(this.parseJSONString(attr.tags))) { return "\"tags\" attribute must be a string or a JSON object"; } if (!_.isUndefined(attr.access)) { if (!_.include(ACCESS, attr.access)) { return "\"access\" attribute is not valid."; } else if (this.attributes.access !== attr.access) { if (attr.access === ACCESS.PUBLIC) { this.attributes.isPublic = true; } else { this.attributes.isPublic = false; } } } if (attr.created_at) { if ((tmpCreated = this.get("created_at")) && tmpCreated !== attr.created_at) { return "\"created_at\" attribute can not be modified after initialization!"; } else if (!_.isNumber(attr.created_at)) { return "\"created_at\" attribute must be a number!"; } } if (attr.updated_at && !_.isNumber(attr.updated_at)) { return "\"updated_at\" attribute must be a number!"; } if (attr.deleted_at && !_.isNumber(attr.deleted_at)) { return "\"deleted_at\" attribute must be a number!"; } if (attr.labels) { attr.labels.each(function (value) { var parseValue = value.parse({category: this.toJSON()}); if (parseValue.category) { parseValue = parseValue.category; } value.category = parseValue; }, this); } }, /** * Change category color * @alias module:models-category.Category#setColor * @param {string} color the new color */ setColor: function (color) { var settings = this.attributes.settings; settings.color = color; this.set("settings", settings); }, /** * Modify the current url for the annotations collection * @alias module:models-category.Category#setUrl */ setUrl: function (labels) { if (labels) { labels.setUrl(this); } }, /** * Override the default toJSON function to ensure complete JSONing. * @alias module:models-category.Category#toJSON * @param {Boolean} stringifySub defines if the sub-object should be stringify * @return {JSON} JSON representation of the instance */ toJSON: function (stringifySub) { var json = Backbone.Model.prototype.toJSON.call(this); if (stringifySub) { if (json.tags) { json.tags = JSON.stringify(json.tags); } if (json.settings && _.isObject(json.settings)) { json.settings = JSON.stringify(this.attributes.settings); } } delete json.labels; if (this.attributes.scale) { if (this.attributes.scale.attributes) { json.scale_id = this.attributes.scale.get("id"); } else { json.scale_id = this.attributes.scale.id; } if (!annotationsTool.localStorage) { delete json.scale; } } return json; }, /** * Prepare the model as JSON to export and return it * @alias module:models-category.Category#toExportJSON * @param {boolean} withScales Define if the scale has to be included * @return {JSON} JSON representation of the model for export */ toExportJSON: function (withScale) { var json = { name: this.attributes.name, labels: this.attributes.labels.toExportJSON() }; if (this.attributes.tags) { json.tags = JSON.stringify(this.attributes.tags); } if (this.attributes.description) { json.description = this.attributes.description; } if (this.attributes.has_duration) { json.has_duration = this.attributes.has_duration; } if (this.attributes.scale_id) { json.scale_id = this.attributes.scale_id; } if (this.attributes.settings) { json.settings = this.attributes.settings; } if (this.attributes.tags) { json.tags = this.attributes.tags; } if (!_.isUndefined(withScale) && withScale) { if (this.attributes.scale_id) { json.scale = annotationsTool.video.get("scales").get(this.attributes.scale_id).toExportJSON(); } else if (this.attributes.scale) { json.scale = annotationsTool.video.get("scales").get(this.attributes.scale.get("id")).toExportJSON(); } } return json; }, /** * Parse the given parameter to JSON if given as String * @alias module:models-category.Category#parseJSONString * @param {string} parameter the parameter as String * @return {JSON} parameter as JSON object */ parseJSONString: function (parameter) { if (parameter && _.isString(parameter)) { try { parameter = JSON.parse(parameter); } catch (e) { console.warn("Can not parse parameter \"" + parameter + "\": " + e); return undefined; } } else if (!_.isObject(parameter) || _.isFunction(parameter)) { return undefined; } return parameter; } }); return Category; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * A module representing the timeline view * @module views-timeline * @requires jQuery * @requires player-adapter * @requires models-annotation * @requires collections-annotations * @requires templates/timeline-group.tmpl * @requires templates/timeline-item.tmpl * @requires templates/timeline-modal-group.tmpl * @requires ACCESS * @requires ROLES * @requires filters-manager * @requires backbone * @requires handlebars * @requires timeline * @requires bootstrap.tooltip * @requires bootstrap.popover */ define(["jquery", "prototypes/player_adapter", "models/annotation", "models/track", "collections/annotations", "collections/tracks", "templates/timeline-group", "templates/timeline-group-empty", "templates/timeline-item", "templates/timeline-modal-add-group", "templates/timeline-modal-update-group", "access", "roles", "FiltersManager", "backbone", "handlebars", "timeline", "tooltip", "popover", "jquery.appear" ], function ($, PlayerAdapter, Annotation, Track, Annotations, Tracks, GroupTmpl, GroupEmptyTmpl, ItemTmpl, ModalAddGroupTmpl, ModalUpdateGroupTmpl, ACCESS, ROLES, FiltersManager, Backbone, Handlebars) { "use strict"; /** * Handlebars helper to secure the text field * @alias module:Handlebars#secure * @param {string} text The text to secure * @return {string} The securized text */ Handlebars.registerHelper("secure", function (text) { // Add security for XSS return _.unescape(text).replace(/\"/g, "'").replace(/<\/?script>/gi, "NO-SCRIPT"); }); /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @augments module:Backbone.View * @memberOf module:views-timeline * @alias module:views-timeline.TimelineView */ var Timeline = Backbone.View.extend({ /** * Main container of the timeline * @alias module:views-timeline.TimelineView#el * @type {DOMElement} */ el: $("div#timeline-container")[0], /** * Group template * @alias module:views-timeline.TimelineView#groupTemplate * @type {HandlebarsTemplate} */ groupTemplate: GroupTmpl, /** * Empty group template * @alias module:views-timeline.TimelineView#groupEmptyTemplate * @type {HandlebarsTemplate} */ groupEmptyTemplate: GroupEmptyTmpl, /** * Item template * @alias module:views-timeline.TimelineView#itemTemplate * @type {HandlebarsTemplate} */ itemTemplate: ItemTmpl, /** * Modal template for group insertion * @alias module:views-timeline.TimelineView#modalAddGroupTemplate * @type {HandlebarsTemplate} */ modalAddGroupTemplate: ModalAddGroupTmpl, /** * Modal template for group update * @alias module:views-timeline.TimelineView#modalUpdateGroupTemplate * @type {HandlebarsTemplate} */ modalUpdateGroupTemplate: ModalUpdateGroupTmpl, /** * Events to handle by the timeline view * @alias module:views-timeline.TimelineView#event * @type {map} */ events: { "click #add-track" : "initTrackCreation", "click #reset-zoom" : "onTimelineResetZoom", "click #zoom-in" : "zoomIn", "click #zoom-out" : "zoomOut", "click #move-right" : "moveRight", "click #move-left" : "moveLeft", "click #filter-none" : "disableFilter", "click .filter" : "switchFilter" }, /** * Template for void item content * @alias module:views-timeline.TimelineView#VOID_ITEM_TMPL * @type {string} * @constant */ VOID_ITEM_TMPL: "<div style=\"display:none\"></div>", /** * Void track paramters * @alias module:views-timeline.TimelineView#VOID_TRACK * @type {Object} * @constant */ VOID_TRACK: { isMine : true, id : "empty-timeline", name : "No track available", description : "No track corresponding with the current filter(s)." }, /** * Default duration for annotation * @alias module:views-timeline.TimelineView#DEFAULT_DURATION * @type {Integer} * @constant */ DEFAULT_DURATION: 5, /** * Class prefix for stack level * @alias module:views-timeline.TimelineView#PREFIX_STACKING_CLASS * @type {string} * @constant */ PREFIX_STACKING_CLASS: "stack-level-", /** * Class for item selected on timeline * @alias module:views-timeline.TimelineView#ITEM_SELECTED_CLASS * @type {string} * @constant */ ITEM_SELECTED_CLASS: "timeline-event-selected", /** * Map containing all the items * @alias module:views-timeline.TimelineView#allItems * @type {map} */ allItems: {}, /** * Array containing only the items who passed the filters * @alias module:views-timeline.TimelineView#filteredItems * @type {array} */ filteredItems: [], /** * Constructor * @alias module:views-timeline.TimelineView#initialize * @param {PlainObject} attr Object literal containing the view initialization attributes. */ initialize: function (attr) { _.bindAll(this, "addTrack", "addTracksList", "createTrack", "changeTitleFromCustomPlayhead", "onDeleteTrack", "onTrackSelected", "onSelectionUpdate", "onPlayerTimeUpdate", "onTimelineMoved", "onTimelineItemChanged", "onTimelineItemDeleted", "isAnnotationSelectedonTimeline", "onTimelineItemAdded", "onAnnotationDestroyed", "generateVoidItem", "generateItem", "changeItem", "changeTrack", "getFormatedDate", "getSelectedItemAndAnnotation", "getStackLevel", "getTrack", "onWindowResize", "onTimelineResetZoom", "initTrackCreation", "initTrackUpdate", "filterItems", "switchFilter", "updateFiltersRender", "disableFilter", "updateDraggingCtrl", "moveToCurrentTime", "moveRight", "moveLeft", "zoomIn", "zoomOut", "stopZoomScrolling", "timerangeChange", "repaintCustomTime", "redraw", "reset", "updateHeader"); this.playerAdapter = attr.playerAdapter; this.filtersManager = new FiltersManager(annotationsTool.filtersManager); this.filtersManager.filters.timerange.end = attr.playerAdapter.getDuration(); this.filtersManager.filters.timerange.active = true; this.filtersManager.filters.visibleTracks = { active: true, tracks: {}, condition: function (item) { if (_.isUndefined(item.model) || !_.isUndefined(item.voidItem)) { return true; } return this.tracks[item.model.get("id")]; }, filter: function (list) { return _.filter(list, function (item) { return this.condition(item); }, this); } }; this.listenTo(this.filtersManager, "switch", this.updateFiltersRender); // Type use for delete operation this.typeForDeleteAnnotation = annotationsTool.deleteOperation.targetTypes.ANNOTATION; this.typeForDeleteTrack = annotationsTool.deleteOperation.targetTypes.TRACK; this.endDate = this.getFormatedDate(this.playerAdapter.getDuration()); this.startDate = new Date(this.endDate.getFullYear(), this.endDate.getMonth(), this.endDate.getDate(), 0, 0, 0); // Options for the links timeline this.options = { width : "100%", height : "auto", style : "box", //scale : links.Timeline.StepDate.SCALE.SECOND, //step : 30, showButtonNew : false, editable : true, start : this.startDate, end : this.endDate, min : this.startDate, max : this.endDate, intervalMin : 5000, showCustomTime : true, showNavigation : false, showMajorLabels : false, snapEvents : false, stackEvents : true, minHeight : "200", axisOnTop : true, groupsWidth : "150px", animate : true, animateZoom : true, // cluster : true, eventMarginAxis : 0, eventMargin : 0, dragAreaWidth : 5, groupsChangeable : true }; this.$navbar = this.$el.find(".navbar"); // Create the timeline this.$timeline = this.$el.find("#timeline"); this.timeline = new links.Timeline(this.$timeline[0]); this.timeline.draw(this.filteredItems, this.options); // Ensure that the timeline is redraw on window resize $(window).bind("resize", this.onWindowResize); annotationsTool.addTimeupdateListener(this.onPlayerTimeUpdate, 1); this.$el.find(".timeline-frame > div:first-child").bind("click", function (event) { if ($(event.target).find(".timeline-event").length > 0) { annotationsTool.setSelection([]); } }); links.events.addListener(this.timeline, "timechanged", this.onTimelineMoved); links.events.addListener(this.timeline, "timechange", this.onTimelineMoved); links.events.addListener(this.timeline, "change", this.onTimelineItemChanged); links.events.addListener(this.timeline, "delete", this.onTimelineItemDeleted); links.events.addListener(this.timeline, "add", this.onTimelineItemAdded); links.events.addListener(this.timeline, "rangechange", this.timerangeChange); this.tracks = annotationsTool.video.get("tracks"); this.listenTo(this.tracks, Tracks.EVENTS.VISIBILITY, this.addTracksList); this.listenTo(this.tracks, "change", this.changeTrack); this.listenTo(annotationsTool, annotationsTool.EVENTS.ANNOTATION_SELECTION, this.onSelectionUpdate); this.$el.show(); this.addTracksList(this.tracks.getVisibleTracks()); this.timeline.setCustomTime(this.startDate); // Overwrite the redraw method this.timeline.repaintCustomTime = this.repaintCustomTime; this.timeline.redraw = this.redraw; // Add findGroup method to the timeline if missing if (!this.timeline.findGroup) { this.timeline.findGroup = this.findGroup; _.bindAll(this.timeline, "findGroup"); } this.$el.find(".timeline-frame > div")[0].addEventListener("mousewheel", function (event) { event.stopPropagation(); }, true); this.timerangeChange(); this.$timeline.scroll(this.updateHeader); this.onPlayerTimeUpdate(); }, /** * Search for the group/track with the given name in the timeline * @alias module:views-timeline.TimelineView#findGroup * @param {Annotation} groupName the name of the group/track to search * @return {Object} The search group/track as timeline-group if found, or undefined */ findGroup: function (groupName) { var searchedGroup; _.each(this.groups, function (group) { if ($(group.content).find("div.content").text().toUpperCase() === groupName.toUpperCase()) { searchedGroup = group; } }); return searchedGroup; }, /** * Add an annotation to the timeline * @alias module:views-timeline.TimelineView#redraw */ redraw: function () { var visibleTracksFilter = this.filtersManager.filters.visibleTracks, tracks, $tracks, timelineHeight, self = this; this.timeline.draw(this.filteredItems, this.option); // If no tracks have been added to the tracks filters (if enable), we search which one are visisble if (!_.isUndefined(visibleTracksFilter) && visibleTracksFilter.active && _.size(visibleTracksFilter.tracks) === 0) { tracks = visibleTracksFilter.tracks; timelineHeight = this.$timeline.height(); _.each(annotationsTool.getTracks().slice(0, (timelineHeight / 60).toFixed()), function (track) { tracks[track.get("id")] = true; }, this); self.filteredItems = self.filterItems(); self.redraw(); } else { if (annotationsTool.hasSelection()) { this.onSelectionUpdate(annotationsTool.getSelection()); this.updateDraggingCtrl(); } if (annotationsTool.selectedTrack) { this.onTrackSelected(null, annotationsTool.selectedTrack.id); } // Remove the popover div from old track elements $("div.popover.fade.right.in").remove(); // If the visisble tracks filter is enable, we check where tracks are visible if (!_.isUndefined(visibleTracksFilter) && visibleTracksFilter.active) { tracks = visibleTracksFilter.tracks; $tracks = this.$timeline.find(".timeline-groups-text").appear({ context: this.$timeline }); $tracks.on("appear", _.debounce(function () { var id = this.dataset.trackid; if (!tracks[id]) { tracks[id] = true; self.filteredItems = self.filterItems(); self.redraw(); } }, 200)); $tracks.on("disappear", _.debounce(function () { var id = this.dataset.trackid; if (tracks[id]) { tracks[id] = false; self.filteredItems = self.filterItems(); self.redraw(); } }, 200)); } } }, /** * Update the timerange filter with the timerange * @alias module:views-timeline.TimelineView#timerangeChange */ timerangeChange: function () { var timerange = this.timeline.getVisibleChartRange(); this.filtersManager.filters.timerange.start = new Date(timerange.start).getTime(); this.filtersManager.filters.timerange.end = new Date(timerange.end).getTime(); this.filteredItems = this.filterItems(); this.redraw(); }, /** * Update the position of the timeline header on scroll * @alias module:views-timeline.TimelineView#updateHeader */ updateHeader: function () { var self = this; $("div.timeline-frame > div:first-child > div:first-child").css({ "margin-top": self.$timeline.scrollTop() - 2 }); }, /** * Repaint the custom playhead * @alias module:views-timeline.TimelineView#repaintCustomTime */ repaintCustomTime: function () { links.Timeline.prototype.repaintCustomTime.call(this.timeline); this.changeTitleFromCustomPlayhead(); }, /** * Change the title from the custome Playhead with a better time format * @alias module:views-timeline.TimelineView#changeTitleFromCustomPlayhead */ changeTitleFromCustomPlayhead: function () { this.$el.find(".timeline-customtime").attr("title", annotationsTool.getWellFormatedTime(this.playerAdapter.getCurrentTime())); }, /** * Move the current range to the left * @alias module:views-timeline.TimelineView#moveLeft * @param {Event} event Event object */ moveLeft: function (event) { links.Timeline.preventDefault(event); links.Timeline.stopPropagation(event); this.timeline.move(-0.2); this.timeline.trigger("rangechange"); this.timeline.trigger("rangechanged"); }, /** * [moveRight description] * @alias module:views-timeline.TimelineView#Right * @param {Event} event Event object */ moveRight: function (event) { links.Timeline.preventDefault(event); links.Timeline.stopPropagation(event); this.timeline.move(0.2); this.timeline.trigger("rangechange"); this.timeline.trigger("rangechanged"); }, /** * Move the current position of the player * @alias module:views-timeline.TimelineView#moveToCurrentTime */ moveToCurrentTime: function () { var currentChartRange = this.timeline.getVisibleChartRange(), start = this.getTimeInSeconds(currentChartRange.start), end = this.getTimeInSeconds(currentChartRange.end), size = end - start, currentTime = this.playerAdapter.getCurrentTime(), videoDuration = this.playerAdapter.getDuration(), marge = size / 20, startInSecond; // popovers = $("div.popover.fade.right.in"); if (annotationsTool.timelineFollowPlayhead) { if ((currentTime - size / 2) < 0) { start = this.getFormatedDate(0); end = this.getFormatedDate(size); } else if ((currentTime + size / 2) > videoDuration) { start = this.getFormatedDate(videoDuration - size); end = this.getFormatedDate(videoDuration); } else { start = this.getFormatedDate(currentTime - size / 2); end = this.getFormatedDate(currentTime + size / 2); } } else { if (((currentTime + marge) >= end && end != videoDuration) || (currentTime > end || currentTime < start)) { startInSecond = Math.max(currentTime - marge, 0); start = this.getFormatedDate(startInSecond); end = this.getFormatedDate(Math.min(startInSecond + size, videoDuration)); } else { start = this.getFormatedDate(start); end = this.getFormatedDate(end); } } if (currentChartRange.start.getTime() != start.getTime() || currentChartRange.end.getTime() !== end.getTime()) { this.timeline.setVisibleChartRange(start, end); } }, /** * Zoom in * @alias module:views-timeline.TimelineView#zoomIn * @param {Event} event Event object */ zoomIn: function (event) { links.Timeline.preventDefault(event); links.Timeline.stopPropagation(event); this.timeline.zoom(0.4, this.timeline.getCustomTime()); this.timeline.trigger("rangechange"); this.timeline.trigger("rangechanged"); }, /** * Zoom out * @alias module:views-timeline.TimelineView#zoomOut * @param {Event} event Event object */ zoomOut: function (event) { links.Timeline.preventDefault(event); links.Timeline.stopPropagation(event); this.timeline.zoom(-0.4, this.timeline.getCustomTime()); this.timeline.trigger("rangechange"); this.timeline.trigger("rangechanged"); }, /** * Stop the zoom through scrolling * @alias module:views-timeline.TimelineView#stopZoomScrolling */ stopZoomScrolling: function () { this.$el.find(".timeline-frame > div").first()[0].addEventListener("mousewheel", function (event) { event.stopPropagation(); }, true); }, /** * Add a new item to the timeline * @param {string} id The id of the item * @param {object} item The object representing the item * @param {Boolean} isPartOfList Define if the object is part of a group insertion * @alias module:views-timeline.TimelineView#addItem */ addItem: function (id, item, isPartOfList) { this.allItems[id] = item; if (!isPartOfList) { this.filterItems(); this.redraw(); } }, /** * Remove the timeline item with the given id * @param {string} id The id of the item to remove * @alias module:views-timeline.TimelineView#removeItem */ removeItem: function (id, refresh) { delete this.allItems[id]; if (refresh) { this.filterItems(); this.redraw(); } }, /** * Add an annotation to the timeline * @alias module:views-timeline.TimelineView#addAnnotation * @param {Annotation} annotation the annotation to add. * @param {Track} track the track where the annotation must be added * @param {Boolean} [isList] define if the insertion is part of a list, Default is false */ addAnnotation: function (annotation, track, isList) { // Wait that the id has be set to the model before to add it if (_.isUndefined(annotation.get("id"))) { annotation.once("ready", function () { this.addAnnotation(annotation, track, isList); }, this); return; } if (annotation.get("oldId") && this.ignoreAdd === annotation.get("oldId")) { delete this.ignoreAdd; return; } // If annotation has not id, we save it to have an id if (!annotation.id) { annotation.bind("ready", this.addAnnotation, this); return; } this.allItems[annotation.id] = this.generateItem(annotation, track); if (!isList) { this.filterItems(); this.redraw(); this.onPlayerTimeUpdate(); } annotation.bind("destroy", this.onAnnotationDestroyed, this); }, /** * Add a track to the timeline * @alias module:views-timeline.TimelineView#addTrack * @param {Track} track The track to add to the timline */ addTrack: function (track) { var annotations, proxyToAddAnnotation = function (annotation) { this.addAnnotation(annotation, track, false); }, annotationWithList = function (annotation) { this.addAnnotation(annotation, track, true); }; // If track has not id, we save it to have an id if (!track.id) { track.bind("ready", this.addTrack, this); return; } // Add void item this.allItems["track_" + track.id] = this.generateVoidItem(track); annotations = track.get("annotations"); annotations.each(annotationWithList, this); annotations.bind("add", proxyToAddAnnotation, this); annotations.bind("change", this.changeItem, this); if (!_.isUndefined(this.filtersManager.filters.visibleTracks)) { this.filtersManager.filters.visibleTracks.tracks[track.get("id")] = true; } this.filterItems(); this.redraw(); }, /** * Add a list of tracks, creating a view for each of them * @alias module:views-timeline.TimelineView#addTracksList * @param {Array | List} tracks The list of tracks to add */ addTracksList: function (tracks) { this.allItems = {}; if (tracks.length === 0) { this.filterItems(); this.redraw(); } else { _.each(tracks, this.addTrack, this); } }, /** * Get a void timeline item for the given track * @alias module:views-timeline.TimelineView#generateVoidItem * @param {Track} track Given track owning the void item * @return {Object} the generated timeline item */ generateVoidItem: function (track) { var trackJSON = track.toJSON(); trackJSON.id = track.id; trackJSON.isSupervisor = (annotationsTool.user.get("role") === ROLES.SUPERVISOR); return { model: track, trackId: track.id, isMine: track.get("isMine"), isPublic: track.get("isPublic"), voidItem: true, start: this.startDate - 5000, end: this.startDate - 4500, content: this.VOID_ITEM_TMPL, group: this.groupTemplate(trackJSON) }; }, /** * Get an timeline item from the given annotation * @alias module:views-timeline.TimelineView#generateItem * @param {Annotation} annotation The source annotation for the item * @param {Track} track Track where the annotation is saved * @return {Object} the generated timeline item */ generateItem: function (annotation, track) { var videoDuration = this.playerAdapter.getDuration(), annotationJSON, trackJSON, startTime, endTime, start, end; annotation.set("level", this.PREFIX_STACKING_CLASS + this.getStackLevel(annotation), { silent: true }); annotationJSON = annotation.toJSON(); annotationJSON.id = annotation.id; annotationJSON.track = track.id; annotationJSON.text = annotation.get("text"); if (annotationJSON.label && annotationJSON.label.category && annotationJSON.label.category.settings) { annotationJSON.category = annotationJSON.label.category; } // Prepare track informations trackJSON = track.toJSON(); trackJSON.id = track.id; trackJSON.isSupervisor = (annotationsTool.user.get("role") === ROLES.SUPERVISOR); // Calculate start/end time startTime = annotation.get("start"); endTime = startTime + annotation.get("duration"); start = this.getFormatedDate(startTime); end = this.getFormatedDate(endTime); // If annotation is at the end of the video, we mark it for styling annotationJSON.atEnd = (videoDuration - endTime) < 3; return { model: track, id: annotation.id, trackId: track.id, isPublic: track.get("isPublic"), isMine: track.get("isMine"), editable: track.get("isMine"), start: start, end: end, content: this.itemTemplate(annotationJSON), group: this.groupTemplate(trackJSON), className: annotationJSON.level }; }, /** * Add a track to the timeline * @alias module:views-timeline.TimelineView#createTrack * @param {PlainObject} JSON object compose of a name and description properties. Example: {name: "New track", description: "A test track as example"} */ createTrack: function (param) { var track; if (this.timeline.findGroup(param.name)) { // If group already exist, we do nothing return; } track = this.tracks.create(param, { wait: true }); //this.redraw(); //this.onTrackSelected(null, annotationsTool.selectedTrack.id); }, /** * Initialize the creation of a new track, load the modal window to add a new track. * @alias module:views-timeline.TimelineView#initTrackCreation */ initTrackCreation: function () { var self = this, access, name, description, insertTrack = function () { name = self.createGroupModal.find("#name")[0].value; description = self.createGroupModal.find("#description")[0].value; if (name === "") { self.createGroupModal.find(".alert #content").html("Name is required!"); self.createGroupModal.find(".alert").show(); return; } else if (name.search(/<\/?script>/i) >= 0 || description.search(/<\/?script>/i) >= 0) { self.createGroupModal.find(".alert #content").html("Scripts are not allowed!"); self.createGroupModal.find(".alert").show(); return; } if (self.createGroupModal.find("#public").length > 0) { access = self.createGroupModal.find("#public")[0].checked ? ACCESS.PUBLIC : ACCESS.PRIVATE; } else { access = ACCESS.PUBLIC; } self.createTrack({ name: name, description: description, access: access }, this); self.createGroupModal.modal("toggle"); }; // If the modal is already loaded and displayed, we do nothing if ($("div#modal-add-group.modal.in").length > 0) { return; } else if (!this.createGroupModal) { // Otherwise we load the login modal if not loaded $("body").append(this.modalAddGroupTemplate({ isSupervisor: annotationsTool.user.get("role") === ROLES.SUPERVISOR })); this.createGroupModal = $("#modal-add-group"); this.createGroupModal.modal({ show: true, backdrop: false, keyboard: true }); this.createGroupModal.find("a#add-group").bind("click", insertTrack); this.createGroupModal.bind("keypress", function (event) { if (event.keyCode === 13) { insertTrack(); } }); this.createGroupModal.on("shown", $.proxy(function () { this.createGroupModal.find("#name").focus(); }, this)); this.createGroupModal.find("#name").focus(); } else { // if the modal has already been initialized, we reset input and show modal this.createGroupModal.find(".alert #content").html("").hide(); this.createGroupModal.find(".alert-error").hide(); this.createGroupModal.find("#name")[0].value = ""; this.createGroupModal.find("#description")[0].value = ""; this.createGroupModal.modal("toggle"); } }, /** * Initialize the update of the selected track, load the modal window to modify the track. * @alias module:views-timeline.TimelineView#initTrackUpdate * @param {Event} event Event object * @param {Integer} The track Id of the selected track */ initTrackUpdate: function (event, id) { var self = this, access, name, track = annotationsTool.getTrack(id), description, updateTrack = function () { name = self.updateGroupModal.find("#name")[0].value; description = self.updateGroupModal.find("#description")[0].value; if (name === "") { self.updateGroupModal.find(".alert #content").html("Name is required!"); self.updateGroupModal.find(".alert").show(); return; } else if (name.search(/<\/?script>/i) >= 0 || description.search(/<\/?script>/i) >= 0) { self.updateGroupModal.find(".alert #content").html("Scripts are not allowed!"); self.updateGroupModal.find(".alert").show(); return; } if (self.updateGroupModal.find("#public").length > 0) { access = self.updateGroupModal.find("#public")[0].checked ? ACCESS.PUBLIC : ACCESS.PRIVATE; } else { access = ACCESS.PUBLIC; } track.set({ name: name, description: description, access: access }); track.save(); self.updateGroupModal.modal("toggle"); }; // If the modal is already loaded and displayed, we do nothing if ($("div#modal-update-group.modal.in").length > 0) { return; } else if (!this.updateGroupModal) { // Otherwise we load the login modal if not loaded $("body").append(this.modalUpdateGroupTemplate(track.toJSON())); this.updateGroupModal = $("#modal-update-group"); this.updateGroupModal.modal({ show: true, backdrop: false, keyboard: true }); this.updateGroupModal.find("a#update-group").bind("click", updateTrack); this.updateGroupModal.bind("keypress", function (event) { if (event.keyCode === 13) { updateTrack(); } }); this.updateGroupModal.on("shown", $.proxy(function () { this.updateGroupModal.find("#name").focus(); }, this)); this.updateGroupModal.find("#name").focus(); } else { // if the modal has already been initialized, we reset input and show modal this.updateGroupModal.find(".alert #content").html(""); this.updateGroupModal.find(".alert-error").hide(); this.updateGroupModal.find("#name")[0].value = track.get("name"); this.updateGroupModal.find("#description")[0].value = track.get("description"); this.updateGroupModal.find("a#update-group").unbind("click").bind("click", updateTrack); this.updateGroupModal.find("#public")[0].checked = (track.get("access") === ACCESS.PUBLIC); this.updateGroupModal.unbind("keypress").bind("keypress", function (event) { if (event.keyCode === 13) { updateTrack(); } }); this.updateGroupModal.modal("toggle"); } }, /** * Go through the list of items with the current active filter and save it in the filtered items array. * @alias module:views-timeline.TimelineView#filterItems * @return {Array} The list of filtered items */ filterItems: function () { var tempList = _.values(this.allItems); tempList = this.filtersManager.filterAll(tempList); this.filteredItems = _.sortBy(tempList, function (item) { return _.isUndefined(item.model) ? 0 : item.model.get("name"); }, this); if (this.filteredItems.length === 0) { this.filteredItems.push({ trackId: this.VOID_TRACK.id, isMine: this.VOID_TRACK.isMine, isPublic: true, start: this.startDate - 5000, end: this.startDate - 4500, content: this.VOID_ITEM_TMPL, group: this.groupEmptyTemplate(this.VOID_TRACK) }); } return this.filteredItems; }, /** * Switch on/off the filter related to the given event * @alias module:views-list.List#switchFilter * @param {Event} event */ switchFilter: function (event) { var active = !$(event.target).hasClass("checked"), id = event.target.id.replace("filter-", ""); this.filtersManager.switchFilter(id, active); }, /** * Update the DOM elements related to the filters on filters update. * @alias module:views-timeline.TimelineView#updateFilterRender * @param {PlainObject} attr The plain object representing the updated filter */ updateFiltersRender: function (attr) { if (attr.active) { this.$el.find("#filter-" + attr.id).addClass("checked"); } else { this.$el.find("#filter-" + attr.id).removeClass("checked"); } this.filterItems(); this.redraw(); }, /** * Disable all the list filter * @alias module:views-list.List#disableFilter */ disableFilter: function () { this.$el.find(".filter").removeClass("checked"); this.filtersManager.disableFilters(); this.filterItems(); this.redraw(); }, /** * Check the position for the changed item * @alias module:views-timeline.TimelineView#changeItem * @param {Annotation} the annotation that has been changed */ changeItem: function (annotation) { var value = this.getTimelineItemFromAnnotation(annotation); if (!_.isUndefined(value)) { // Only update annotation view if the item has already been created this.allItems[annotation.id] = this.generateItem(annotation, value.model); this.filterItems(); this.redraw(); } }, /** * Listener for the player timeupdate * @alias module:views-timeline.TimelineView#onPlayerTimeUpdate */ onPlayerTimeUpdate: function () { var currentTime = this.playerAdapter.getCurrentTime(), newDate = this.getFormatedDate(currentTime); this.timeline.setCustomTime(newDate); this.$el.find("span.time").html(annotationsTool.getWellFormatedTime(currentTime, true)); this.moveToCurrentTime(); }, /** * Listener for the selection update event * @alias module:views-timeline.TimelineView#onSelectionUpdate * @param {Array} selection The new array of selected item(s) */ onSelectionUpdate: function (selection) { var data = this.filteredItems; // If no selection, we unselected elements currently selected and return if (selection.length === 0) { this.timeline.unselectItem(); return; } if (!this.isAnnotationSelectedonTimeline(selection[0])) { _.each(data, function (item, index) { if (selection[0].get("id") === item.id) { this.timeline.selectItem(index, false, true); } }, this); } }, /** * Listener for the timeline timeupdate * @alias module:views-timeline.TimelineView#onTimelineMoved * @param {Event} event Event object */ onTimelineMoved: function (event) { var newTime = this.getTimeInSeconds(event.time), hasToPlay = (this.playerAdapter.getStatus() === PlayerAdapter.STATUS.PLAYING); if (hasToPlay) { this.playerAdapter.pause(); } this.playerAdapter.setCurrentTime((newTime < 0 || newTime > this.playerAdapter.getDuration()) ? 0 : newTime); if (hasToPlay) { this.playerAdapter.play(); } }, /** * Listener for item modification * @alias module:views-timeline.TimelineView#onTimelineItemChanged */ onTimelineItemChanged: function () { var hasToPlay = (this.playerAdapter.getStatus() === PlayerAdapter.STATUS.PLAYING), values = this.getSelectedItemAndAnnotation(), oldItemId, duration, start, annJSON, successCallback, destroyCallback, self = this; // Pause the player if needed this.playerAdapter.pause(); // Return if no values related to to item if (!values || !values.annotation) { console.warn("Can not get infos from updated item!"); this.timeline.cancelChange(); return; } duration = this.getTimeInSeconds(values.item.end) - this.getTimeInSeconds(values.item.start); start = this.getTimeInSeconds(values.item.start); // If the annotation is not owned by the current user or the annotation is moved outside the timeline, // the update is canceled if (!values.newTrack.get("isMine") || !values.annotation.get("isMine") || this.getTimeInSeconds(values.item.end) > this.playerAdapter.getDuration() || start > this.playerAdapter.getDuration()) { this.timeline.cancelChange(); this.allItems[values.annotation.id] = { start: values.item.start, end: values.item.end, content: values.item.content, group: this.groupTemplate(values.oldTrack.toJSON()), id: values.annotation.id, trackId: values.oldTrack.id, model: values.oldTrack, className: values.item.className }; this.filterItems(); this.redraw(); if (hasToPlay) { this.playerAdapter.play(); } return; } // If the annotations has been moved on another track if (values.newTrack.id !== values.oldTrack.id) { this.ignoreAdd = values.annotation.get("id"); this.ignoreDelete = this.ignoreAdd; annJSON = values.annotation.toJSON(); oldItemId = annJSON.id; annJSON.oldId = this.ignoreAdd; annJSON.start = start; annJSON.duration = duration; delete annJSON.id; delete annJSON.created_at; destroyCallback = function () { if (annotationsTool.localStorage) { successCallback(values.newTrack.get("annotations").create(annJSON)); } else { values.newTrack.get("annotations").create(annJSON, { wait: true, success: successCallback }); } }, successCallback = function (newAnnotation) { newAnnotation.set({ level: self.PREFIX_STACKING_CLASS + self.getStackLevel(newAnnotation) }, { silent: true }); newAnnotation.unset("oldId", { silent: true }); newAnnotation.save(); annJSON.id = newAnnotation.get("id"); annJSON.track = values.newTrack.id; annJSON.level = newAnnotation.get("level"); if (annJSON.label && annJSON.label.category && annJSON.label.category.settings) { annJSON.category = annJSON.label.category; } self.addItem(annJSON.id, { start: values.item.start, end: values.item.end, group: values.item.group, content: self.itemTemplate(annJSON), id: annJSON.id, trackId: values.newTrack.id, isPublic: values.newTrack.get("isPublic"), isMine: values.newTrack.get("isMine"), className: annJSON.level, model: values.newTrack }, false); self.removeItem(annJSON.oldId, false); annotationsTool.setSelection([newAnnotation], true, true, true); newAnnotation.set({ access: values.newTrack.get("access") }); self.filterItems(); self.redraw(); if (hasToPlay) { self.playerAdapter.play(); } }; values.annotation.destroy({ success: destroyCallback, }); } else { this.allItems[values.annotation.id] = values.item; values.annotation.set({ start: start, duration: duration }); values.annotation.save(); annotationsTool.playerAdapter.setCurrentTime(values.annotation.get("start")); this.filterItems(); this.redraw(); if (hasToPlay) { this.playerAdapter.play(); } } }, /** * Listener for timeline item deletion * @alias module:views-timeline.TimelineView#onTimelineItemDeleted */ onTimelineItemDeleted: function () { var annotation = this.getSelectedItemAndAnnotation().annotation; this.timeline.cancelDelete(); annotationsTool.deleteOperation.start(annotation, this.typeForDeleteAnnotation); }, /** * Listener for item insertion on timeline * @alias module:views-timeline.TimelineView#onTimelineItemAdded */ onTimelineItemAdded: function () { // No possiblity to add annotation directly from the timeline this.timeline.cancelAdd(); }, /** * Listener for annotation suppression * @alias module:views-timeline.TimelineView#onAnnotationDestroyed */ onAnnotationDestroyed: function (annotation) { if (this.ignoreDelete === annotation.get("id")) { delete this.ignoreDelete; return; } if (this.allItems[annotation.id]) { this.removeItem(annotation.id, true); } }, /** * Reset the timeline zoom to see the whole timeline * @alias module:views-timeline.TimelineView#onTimelineResetZoom */ onTimelineResetZoom: function () { this.timeline.setVisibleChartRange(this.startDate, this.endDate); }, /** * Listener for track deletion * @alias module:views-timeline.TimelineView#onDeleteTrack * @param {Event} event the action event * @param {Integer} trackId Id of the track to delete */ onDeleteTrack: function (event, trackId) { event.stopImmediatePropagation(); var track = this.tracks.get(trackId), self = this, values, newTrackId, callback; // If track already deleted if (!track) { return; } // Destroy the track and redraw the timeline callback = $.proxy(function () { // delete track popover $("#track" + trackId).popover("disable"); values = _.values(this.allItems); _.each(values, function (item) { if (item.trackId === track.id) { delete this.allItems[item.id]; } }, this); self.tracks.remove(track); // If the track was selected if (!annotationsTool.selectedTrack || annotationsTool.selectedTrack.id === track.id) { if (self.tracks.length > 0) { // If there is still other tracks self.tracks.each(function (t) { if (t.get("isMine")) { newTrackId = t.id; } }); self.onTrackSelected(null, newTrackId); } } else { self.onTrackSelected(null, annotationsTool.selectedTrack.id); } if (this.allItems["track_" + track.id]) { delete this.allItems["track_" + track.id]; } this.filterItems(); this.redraw(); }, this); annotationsTool.deleteOperation.start(track, this.typeForDeleteTrack, callback); }, /** * Update all the items placed on the given track * @alias module:views-timeline.TimelineView#changeTrack * @param {Track} track The freshly updated track * @param {PlainObject} [options] Options like silent: true to avoid a redraw (optionnal) */ changeTrack: function (track, options) { // If the track is not visible, we do nothing if (!track.get(Track.FIELDS.VISIBLE)) { return; } var newGroup, trackJSON = track.toJSON(), redrawRequired = false; trackJSON.isSupervisor = (annotationsTool.user.get("role") === ROLES.SUPERVISOR); newGroup = this.groupTemplate(trackJSON); _.each(this.allItems, function (item) { if (item.trackId === track.get("id") && item.group !== newGroup) { item.group = newGroup; item.isPublic = track.get("isPublic"); redrawRequired = true; } }, this); if (!(options && options.silent) && redrawRequired) { this.filterItems(); this.redraw(); } }, /** * Update the track with the given id * @alias module:views-timeline.TimelineView#onUpdateTrack * @param {Event} event the action event * @param {Integer} trackId Id of the track to delete */ onUpdateTrack: function (event, trackId) { event.stopImmediatePropagation(); $("#track" + trackId).popover("hide"); var track = this.tracks.get(trackId), trackCurrentVisibility, newTrackVisibility; if (!track) { console.warn("Track " + trackId + " does not exist!"); return; } trackCurrentVisibility = track.get("access"); if (trackCurrentVisibility === ACCESS.PRIVATE) { newTrackVisibility = ACCESS.PUBLIC; } else { newTrackVisibility = ACCESS.PRIVATE; } track.setAccess(newTrackVisibility); track.save(); }, /** * Listener for track selection * @alias module:views-timeline.TimelineView#onTrackSelected * @param {Event} event Event object * @param {Integer} The track Id of the selected track */ onTrackSelected: function (event, trackId) { var track; if (_.isString(trackId) && !annotationsTool.localStorage) { track = annotationsTool.video.getTrack(parseInt(trackId, 10)); } else { track = annotationsTool.video.getTrack(trackId); } // If the track does not exist, and it has been thrown by an event if ((!track && event) || (!track && trackId)) { return; } annotationsTool.selectTrack(track); this.$el.find("div.selected").removeClass("selected"); this.$el.find(".timeline-group[data-id='" + trackId + "']").parent().addClass("selected"); }, /** * Listener for window resizing * @alias module:views-timeline.TimelineView#onWindowsResize */ onWindowResize: function () { this.redraw(); if (annotationsTool.selectedTrack) { this.onTrackSelected(null, annotationsTool.selectedTrack.id); } }, /* -------------------------------------- Utils functions ----------------------------------------*/ /** * Get the formated date for the timeline with the given seconds * @alias module:views-timeline.TimelineView#getFormatedDate * @param {Double} seconds The time in seconds to convert to Date * @returns {Date} Formated date for the timeline */ getFormatedDate: function (seconds) { var newDate = new Date(seconds * 1000); newDate.setHours(newDate.getHours() - 1); return newDate; }, /** * Transform the given date into a time in seconds * @alias module:views-timeline.TimelineView#getTimeInSeconds * @param {Date} date The formated date from timeline * @returns {Double} Date converted to time in seconds */ getTimeInSeconds: function (date) { var time = date.getHours() * 3600 + date.getMinutes() * 60 + date.getSeconds() + date.getMilliseconds() / 1000; return Math.round(Number(time)); // Ensue that is really a number }, /** * Get the current selected annotion as object containing the timeline item and the annotation * @alias module:views-timeline.TimelineView#getSelectedItemAndAnnotation * @returns {Object} Object containing the annotation and the timeline item. "{item: "timeline-item", annotation: "annotation-object"}" */ getSelectedItemAndAnnotation: function () { //var itemId = $("." + this.ITEM_SELECTED_CLASS + " .annotation-id").text(), var annotation = annotationsTool.getSelection()[0], //selection = this.timeline.getSelection(), item, itemId, newTrackId, oldTrackId, oldTrack, newTrack; if (_.isUndefined(annotation) || _.isUndefined(this.allItems[annotation.get("id")])) { return; } itemId = annotation.get("id"); item = this.allItems[itemId]; newTrackId = item.trackId; oldTrackId = $(item.content)[0].dataset.trackid; oldTrack = annotationsTool.getTrack(oldTrackId); newTrack = annotationsTool.getTrack(newTrackId); annotation = annotationsTool.getAnnotation(itemId, oldTrack); return { annotation: annotation, item: this.allItems[itemId], annotationId: itemId, trackId: newTrackId, newTrack: newTrack, oldTrack: oldTrack }; }, /** * Check if the given annotation is currently selected on the timeline * @alias module:views-timeline.TimelineView#isAnnotationSelectedonTimeline * @param {Annotation} annotation The annotation to check * @return {Boolean} If the annotation is selected or not */ isAnnotationSelectedonTimeline: function (annotation) { return this.$el.find("div." + this.ITEM_SELECTED_CLASS + " div.timeline-item div.annotation-id:contains(\"" + annotation.get("id") + "\")").length !== 0; }, /** * Update the position of the controls to resize the item following the stacking level * @alias module:views-timeline.TimelineView#updateDraggingCtrl */ updateDraggingCtrl: function () { var selectedElement = this.$el.find("." + this.ITEM_SELECTED_CLASS), cssProperties, item = this.getSelectedItemAndAnnotation(); if (_.isUndefined(item)) { // No current selection return; } selectedElement = this.$el.find("." + this.ITEM_SELECTED_CLASS); cssProperties = { "margin-top": parseInt(selectedElement.css("margin-top"), 10) + parseInt(selectedElement.find(".timeline-item").css("margin-top"), 10) + "px", "height": selectedElement.find(".timeline-item").outerHeight() + "px" }; this.$el.find(".timeline-event-range-drag-left").css(cssProperties); if (item && item.annotation && item.annotation.get("duration") < 1) { cssProperties["margin-left"] = selectedElement.find(".timeline-item").outerWidth() + "px"; } else { cssProperties["margin-left"] = "0px"; } this.$el.find(".timeline-event-range-drag-right").css(cssProperties); }, /** * Get the item related to the given annotation * @alias module:views-timeline.TimelineView#getTimelineItemFromAnnotation * @param {Annotation} the annotation * @returns {Object} an item object extend by an index parameter */ getTimelineItemFromAnnotation: function (annotation) { return this.allItems[annotation.id]; }, /** * Get the top value from the annotations to avoid overlapping * @alias module:views-timeline.TimelineView#getStackLevel * @param {Annotation} the target annotation * @returns {Integer} top for the target annotation */ getStackLevel: function (annotation) { // Target annotation values var tStart = annotation.get("start"), tEnd = tStart + annotation.get("duration"), //annotationItem = this.allItems[annotation.get("id")], maxLevelTrack = 0, // Higher level for the whole track, no matter if the annotations are in the given annotation slot newLevel = 0, // the new level to return maxLevel, // Higher stack level elLevel = 0, // stack level for the element in context levelUsed = [], annotations, //trackEl, classesStr, indexClass, i, // Function to filter annotation rangeForAnnotation = function (a) { var start = a.get("start"), end = start + a.get("duration"); if (start === end) { end += this.DEFAULT_DURATION; } // Get the stacking level of the current item classesStr = a.get("level"); if (typeof classesStr !== "undefined") { indexClass = classesStr.search(this.PREFIX_STACKING_CLASS) + this.PREFIX_STACKING_CLASS.length; elLevel = parseInt(classesStr.substr(indexClass, classesStr.length - indexClass), 10) || 0; } else { elLevel = 0; } if (elLevel > maxLevelTrack) { maxLevelTrack = elLevel; } // Test if the annotation is overlapping the target annotation if ((a.id !== annotation.id) && // do not take the target annotation into account // Positions check ((start >= tStart && start <= tEnd) || (end > tStart && end <= tEnd) || (start <= tStart && end >= tEnd)) && this.allItems[a.id] // Test if view exist ) { levelUsed[elLevel] = true; return true; } return false; }; if (annotation.get("duration") === 0) { tEnd += this.DEFAULT_DURATION; } if (annotation.collection) { annotations = _.sortBy(annotation.collection.models, function (annotation) { return annotation.get("start"); }, this); _.filter(annotations, rangeForAnnotation, this); } for (i = 0; i < levelUsed.length; i++) { if (!levelUsed[i]) { maxLevel = i; } } if (typeof maxLevel === "undefined") { newLevel = levelUsed.length; } else { newLevel = maxLevel; } if (newLevel > maxLevelTrack) { maxLevelTrack = newLevel; } /*if (annotationItem && annotationItem.model && annotationItem.model.get("timelineMaxLevel") !== maxLevelTrack) { annotationItem.model.set("timelineMaxLevel", maxLevelTrack, {silent: true}); this.changeTrack(annotationItem.model, {silent: true}); trackEl = this.$el.find(".timeline-group .track-id:contains(" + annotationItem.trackId + ")").parent(); trackEl.removeClass("track-max-level-" + (annotationItem.model.get("timelineMaxLevel") || 0)); trackEl.addClass("track-max-level-" + maxLevelTrack); }*/ return newLevel; }, /** * Get track with the given track id. Fallback method include if issues with the standard one. * @alias module:views-timeline.TimelineView#getTrack * @param {int} trackId The id from the targeted track * @return {Track} a track if existing, or undefined. */ getTrack: function (trackId) { var rTrack = this.tracks.get(trackId); if (!rTrack) { // Fallback method this.tracks.each(function (track) { if (track.id === trackId) { rTrack = track; } }, this); } return rTrack; }, /** * Reset the view * @alias module:views-timeline.TimelineView#reset */ reset: function () { var annotations; this.$el.hide(); // Remove all event listener $(this.playerAdapter).unbind("pa_timeupdate", this.onPlayerTimeUpdate); links.events.removeListener(this.timeline, "timechanged", this.onTimelineMoved); links.events.removeListener(this.timeline, "change", this.onTimelineItemChanged); links.events.removeListener(this.timeline, "delete", this.onTimelineItemDeleted); annotationsTool.removeTimeupdateListener(this.onPlayerTimeUpdate, 1); $(window).unbind("resize", this.onWindowResize); this.undelegateEvents(); if (this.createGroupModal) { this.createGroupModal.remove(); } if (this.updateGroupModal) { this.updateGroupModal.remove(); } this.tracks.each(function (track) { annotations = track.get("annotations"); annotations.unbind("add"); }, this); // Remove all elements this.allItems = {}; this.$el.find("#timeline").empty(); //this.timeline.deleteAllItems(); this.timeline = null; delete this.timeline; this.filteredItems = []; } }); return Timeline; } );<file_sep>/** * A module representing the login modal * @module views-login * @requires jQuery * @requires backbone * @requires models-user * @requires collections-users * @requires templates/user-login.tmpl * @requires ROLES * @requires handlebars */ define(["jquery", "backbone", "models/user", "collections/users", "templates/user-login", "roles", "handlebars"], function ($, Backbone, User, Users, LoginTemplate, ROLES) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @augments module:Backbone.View * @memberOf module:views-login * @alias module:views-login.Login */ var loginView = Backbone.View.extend({ /** * Main container of the login modal * @alias module:views-login.Login#el * @type {DOMElement} */ el: $("#user-login"), /** * Login modal template * @alias module:views-login.Login#groupTemplate * @type {HandlebarsTemplate} */ loginTemplate: LoginTemplate, /** * Events to handle * @alias module:views-login.Login#events * @type {object} */ events: { "click #save-user": "login", "keydown": "loginOnInsert" }, /** * Constructor * @alias module:views-login.Login#initialize */ initialize: function () { _.bindAll(this, "loginOnInsert", "login", "reset", "show", "hide"); _.extend(this, Backbone.Events); this.$el.append(this.loginTemplate({localStorage: annotationsTool.localStorage})); this.$el.modal({show: true, backdrop: true, keyboard: false }); this.$el.modal("hide"); this.$el.on("hide", function () { // If user not set, display the login window again if (_.isUndefined(annotationsTool.user)) { setTimeout(function () {$("#user-login").modal("show"); }, 5); } }); }, /** * Show the login modal * @alias module:views-login.Login#show */ show: function () { this.$el.modal("show"); }, /** * Hide the login modal * @alias module:views-login.Login#hide */ hide: function () { this.$el.modal("hide"); }, /** * Login by pressing "Enter" key * @alias module:views-login.Login#loginOnInsert */ loginOnInsert: function (e) { if (e.keyCode === 13) { this.login(); } }, /** * Log the current user of the tool in * @alias module:views-login.Login#login * @return {User} the current user */ login: function () { // Fields from the login form var userNickname = this.$el.find("#nickname"), userEmail = this.$el.find("#email"), userId = annotationsTool.getUserExtId(userEmail.val()), userRemember = this.$el.find("#remember"), userError = this.$el.find(".alert"), valid = true, // Variable to keep the form status in memory user; // the new user userError.find("#content").empty(); // Try to create a new user try { if (annotationsTool.localStorage) { user = annotationsTool.users.create({user_extid: userId, nickname: userNickname.val(), role: this.$el.find("#supervisor")[0].checked ? ROLES.SUPERVISOR : ROLES.USER}, {wait: true}); } else { user = annotationsTool.users.create({user_extid: userId, nickname: userNickname.val()}, {wait: true}); } // Bind the error user to a function to display the errors user.bind("error", $.proxy(function (model, error) { this.$el.find("#" + error.attribute).parentsUntil("form").addClass("error"); userError.find("#content").append(error.message + "<br/>"); valid = false; }, this)); } catch (error) { valid = false; userError.find("#content").append(error + "<br/>"); } // If email is given, we set it to the user if (user && userEmail.val()) { user.set({email: userEmail.val()}); } // If user not valid if (!valid) { this.$el.find(".alert").show(); return undefined; } // If we have to remember the user if (userRemember.is(":checked")) { annotationsTool.users.add(user); Backbone.localSync("create", user, { success: function () { console.log("current user saved locally"); }, error: function (error) { console.warn(error); } }); } user.save(); annotationsTool.user = user; this.$el.modal("toggle"); annotationsTool.users.trigger("login"); annotationsTool.trigger(annotationsTool.EVENTS.USER_LOGGED); return user; }, /** * Reset the view * @alias module:views-login.Login#reset */ reset: function () { this.$el.find("#nickname")[0].value = ""; this.$el.find("#email")[0].value = ""; this.$el.find("#remember")[0].value = ""; //this.$el.modal("toggle"); } }); return loginView; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A containing the player adapter prototype * @module player-adapter */ define(function () { "use strict"; /** * Interface for the element making the proxy between the player and the annotations tool * @constructor * @see {@link https://github.com/entwinemedia/annotations/wiki/Player-adapter-API} * @alias module:player-adapter.PlayerAdapter */ var PlayerAdapter = function () {this._init(); }; /** * Possible player status * @readonly * @enum {number} */ PlayerAdapter.STATUS = { INITIALIZING : 0, LOADING : 1, SEEKING : 2, PAUSED : 3, PLAYING : 4, ENDED : 5, ERROR_NETWORK : 6, ERROR_UNSUPPORTED_MEDIA: 7 }; /** * Player adapter event * @readonly * @enum {string} */ PlayerAdapter.EVENTS = { PLAY : "pa_play", PAUSE : "pa_pause", SEEKING : "pa_seeking", READY : "pa_ready", TIMEUPDATE: "pa_timeupdate", ERROR : "pa_error", ENDED : "pa_ended" }; /** * List of player listeners * @type {map} */ PlayerAdapter.prototype._listeners = {}; /** * Initilization method */ PlayerAdapter.prototype._init = function () { this._listeners = {}; }; /** * Play the media element in the player. */ PlayerAdapter.prototype.play = function () { throw "Function 'play' must be implemented in player adapter!"; }; /** * Set the media element in the player in pause mode. */ PlayerAdapter.prototype.pause = function () { throw "Function 'pause' must be implemented in player adapter!"; }; /** * Set the current time of the media element in the player to the given one. * If the given value is not value, does not set it and write a warning in the console. * @param {double} the new time */ PlayerAdapter.prototype.setCurrentTime = function () { throw "Function 'setCurrentTime' must be implemented in player adapter!"; }; /** * Get the current time of the media element. * @return {double} current time */ PlayerAdapter.prototype.getCurrentTime = function () { throw "Function 'getCurrentTime' must be implemented in player adapter!"; }; /** * Get the media element duration. * @return {double} current time */ PlayerAdapter.prototype.getDuration = function () { throw "Function 'getDuration' must be implemented in player adapter!"; }; /** * Get the media element duration * @return {double} duration */ PlayerAdapter.prototype.getStatus = function () { throw "Function 'getStatus' must be implemented in player adapter!"; }; /** * Get the listeners list for this object * @param {string} type event type * @param {boolean} If the user wish to initiate the capture * @return {array} listeners list */ PlayerAdapter.prototype._getListeners = function (type, useCapture) { var captype = (useCapture ? "1" : "0") + type; if (!(captype in this.__proto__._listeners)) { this.__proto__._listeners[captype] = []; } return this.__proto__._listeners[captype]; }; /** * Add listener for the given event type * @param {String} type event type * @parm {function} listener the new listener * @param {boolean} If the user wish to initiate the capture */ PlayerAdapter.prototype.addEventListener = function (type, listener, useCapture) { var listeners = this._getListeners(type, useCapture), ix = listeners.indexOf(listener); if (ix === -1) { listeners.push(listener); } }; /** * Remove listener for the given event type * @param {String} type event type * @parm {function} listener the listener to remove * @param {boolean} If the user wish to initiate the capture */ PlayerAdapter.prototype.removeEventListener = function (type, listener, useCapture) { var listeners = this._getListeners(type, useCapture), ix = listeners.indexOf(listener); if (ix !== -1) { listeners.splice(ix, 1); } }; /** * Dipatch the given event to the listeners * @param {Event} evt the event to dispatch */ PlayerAdapter.prototype.dispatchEvent = function (event, type) { var eventType = type, listeners, i; if (typeof type !== "undefined") { eventType = event.type; } listeners = this._getListeners(eventType, false).slice(); for (i = 0; i < listeners.length; i++) { listeners[i].call(this, event); } return !event.defaultPrevented; }; /** * Dispatch the given event */ PlayerAdapter.prototype.triggerEvent = function (eventType) { var evt; if (document.createEventObject) { // For IE evt = document.createEventObject(); evt.type = eventType; return !this.dispatchEvent(evt, eventType); } else { // For others browsers evt = document.createEvent("CustomEvent"); evt.initEvent(eventType, true, true); // event type,bubbling,cancelable return !this.dispatchEvent(evt, eventType); } }; /** * Optional function to test interface implementation * @return {boolean} true if the implementation is valid */ PlayerAdapter.prototype.isValid = function () { var errors = "", // All interface properties properties = { play : "function", pause : "function", setCurrentTime: "function", getCurrentTime: "function", getDuration : "function", getStatus : "function" }, property; for (property in properties) { // If this is not a required property, we do not check it. if (typeof properties[property] !== "string") { continue; } // If the function is not implementated if (typeof this[property] === "undefined") { errors += "-" + property + " is not implemented! \n"; } // If the implementation is not valid if (typeof this[property] !== properties[property]) { errors += "-" + property + " is not a valid implementation, type should be " + properties[property] + "! \n"; } } if (errors !== "") { console.warn("Player adapter implementation not valid! \n" + errors); return false; } return true; }; // Return the complete interface return PlayerAdapter; }); <file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing the main view * @module views-main * @requires jQuery * @requires prototype-player_adapter * @requires collections-annotations * @requires views-annotate * @requires views-list * @requires views-timeline * @requires views-login * @requires views-scale-editor * @requires models-user * @requires models-track * @requires models-video * @requires backbone-annotations-sync * @requires roles * @requires filters-manager * @requires backbone * @requires localstorage * @requires bootstrap * @requires bootstrap.carousel * @requires boutstrap.tab */ define(["jquery", "prototypes/player_adapter", "views/annotate", "views/list", "views/timeline", "views/login", "views/scale-editor", "views/tracks-selection", "collections/annotations", "collections/users", "collections/videos", "models/user", "models/track", "models/video", "templates/categories-legend", "roles", "backbone", "handlebars", "localstorage", "bootstrap", "carousel", "tab"], function ($, PlayerAdapter, AnnotateView, ListView, TimelineView, LoginView, ScaleEditorView, TracksSelectionView, Annotations, Users, Videos, User, Track, Video, CategoriesLegendTmpl, ROLES, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @augments module:Backbone.View * @memberOf module:views-main * @alias module:views-main.MainView */ var MainView = Backbone.View.extend({ /** * Main container of the appplication * @alias module:views-main.MainView#el * @type {DOMElement} */ el: $("body"), /** * The player adapter passed during initialization part * @alias module:views-main.MainView#playerAdapter * @type {playerAdapter} */ playerAdapter: null, /** * jQuery element for the loading box * @alias module:views-main.MainView#loadingBox * @type {DOMElement} */ loadingBox: $("div#loading"), /** * Template for the categories legend * @alias module:views-main.MainView#categoriesLegendTmpl * @type {HandlebarsTemplate} */ categoriesLegendTmpl: CategoriesLegendTmpl, /** * Events to handle by the main view * @alias module:views-main.MainView#event * @type {Map} */ events: { "click #logout" : "logout", "click #print" : "print", "click .opt-layout" : "layoutUpdate", "click [class*='opt-tracks']": "tracksSelection" }, /** * Constructor * @alias module:views-main.MainView#initialize * @param {PlainObject} attr Object literal containing the view initialization attributes. */ initialize: function () { _.bindAll(this, "layoutUpdate", "checkUserAndLogin", "createViews", "generateCategoriesLegend", "logout", "loadPlugins", "onDeletePressed", "onWindowResize", "print", "ready", "tracksSelection", "setLoadingProgress", "updateTitle"); var self = this; annotationsTool.bind(annotationsTool.EVENTS.NOTIFICATION, function (message) { self.setLoadingProgress(this.loadingPercent, message); }, this); this.setLoadingProgress(10, "Starting tool."); this.setLoadingProgress(20, "Get users saved locally."); // Create a new users collection and get exciting local user annotationsTool.users = new Users(); if (annotationsTool.localStorage) { // Remove link for statistics exports, work only with backend implementation this.$el.find("#export").parent().remove(); } else { this.$el.find("#export").attr("href", annotationsTool.exportUrl); } Backbone.localSync("read", annotationsTool.users, { success: function (data) { annotationsTool.users.add(data); }, error: function (error) { console.warn(error); } }); this.loginView = new LoginView(); annotationsTool.scaleEditor = new ScaleEditorView(); this.listenTo(annotationsTool, "deleteAnnotation", annotationsTool.deleteAnnotation); annotationsTool.onWindowResize = this.onWindowResize; $(window).resize(this.onWindowResize); $(window).bind("keydown", $.proxy(this.onDeletePressed, this)); annotationsTool.importCategories = this.importCategories; annotationsTool.once(annotationsTool.EVENTS.READY, function () { this.loadPlugins(annotationsTool.plugins); this.generateCategoriesLegend(annotationsTool.video.get("categories").toExportJSON(true)); this.updateTitle(annotationsTool.video); if (!annotationsTool.isFreeTextEnabled()) { $("#opt-annotate-text").parent().hide(); } if (!annotationsTool.isStructuredAnnotationEnabled()) { $("#opt-annotate-categories").parent().hide(); } }, this); this.$el.find(".opt-tracks-" + annotationsTool.getDefaultTracks().name).addClass("checked"); this.checkUserAndLogin(); }, /** * Loads the given plugins * @param {Array} plugins The array of plugins to load * @alias module:views-main.MainView#loadPlugins */ loadPlugins: function (plugins) { _.each(plugins, function (plugin) { plugin(); }, this); }, /** * Updates the title of the page for print mode * @param {object} video The video model * @alias module:views-main.MainView#updateTitle */ updateTitle: function (video) { this.$el.find("#video-title").html(video.get("title")); this.$el.find("#video-owner").html("Owner: " + video.get("src_owner")); if (_.isUndefined(video.get("src_creation_date"))) { this.$el.find("#video-date").remove(); } else { this.$el.find("#video-date").html("Date: " + video.get("src_creation_date")); } }, /** * Generates the legend for all the categories (for printing) * @param {array} categories The array containing all the categories * @alias module:views-main.MainView#generateCategoriesLegend */ generateCategoriesLegend: function (categories) { this.$el.find("#categories-legend").html(this.categoriesLegendTmpl(categories)); }, /** * Creates the views for the annotations * @alias module:views-main.MainView#createViews */ createViews: function () { this.setLoadingProgress(40, "Start creating views."); $("#video-container").show(); this.setLoadingProgress(45, "Start loading video."); // Initialize the player annotationsTool.playerAdapter.load(); this.setLoadingProgress(50, "Initializing the player."); annotationsTool.views.main = this; /** * Loading the video dependant views */ var loadVideoDependantView = $.proxy(function () { if (this.loadingPercent === 100) { return; } this.setLoadingProgress(60, "Start creating views."); if (annotationsTool.getLayoutConfiguration().timeline) { // Create views with Timeline this.setLoadingProgress(70, "Creating timeline."); this.timelineView = new TimelineView({playerAdapter: annotationsTool.playerAdapter}); annotationsTool.views.timeline = this.timelineView; } if (annotationsTool.getLayoutConfiguration().annotate) { // Create view to annotate this.setLoadingProgress(80, "Creating annotate view."); this.annotateView = new AnnotateView({playerAdapter: annotationsTool.playerAdapter}); this.listenTo(this.annotateView, "change-layout", this.onWindowResize); this.annotateView.$el.show(); annotationsTool.views.annotate = this.annotateView; } if (annotationsTool.getLayoutConfiguration().list) { // Create annotations list view this.setLoadingProgress(90, "Creating list view."); this.listView = new ListView(); this.listenTo(this.listView, "change-layout", this.onWindowResize); this.listView.$el.show(); annotationsTool.views.list = this.listView; } this.ready(); }, this); if (annotationsTool.playerAdapter.getStatus() === PlayerAdapter.STATUS.PAUSED) { loadVideoDependantView(); } else { $(annotationsTool.playerAdapter).one(PlayerAdapter.EVENTS.READY + " " + PlayerAdapter.EVENTS.PAUSE, loadVideoDependantView); } }, /** * Function to signal that the tool is ready * @alias module:views-main.MainView#ready */ ready: function () { this.setLoadingProgress(100, "Ready."); this.loadingBox.hide(); this.onWindowResize(); // Show logout button $("a#logout").css("display", "block"); if (annotationsTool.getLayoutConfiguration().timeline) { this.timelineView.redraw(); } annotationsTool.trigger(annotationsTool.EVENTS.READY); }, /** * Check if an user are logged into the tool, otherwise display the login modal * @alias module:views-main.MainView#checkUserAndLogin */ checkUserAndLogin: function () { this.setLoadingProgress(30, "Get current user."); // If a user has been saved locally, we take it as current user if (annotationsTool.users.length > 0) { annotationsTool.user = annotationsTool.users.at(0); annotationsTool.trigger(annotationsTool.EVENTS.USER_LOGGED); if (annotationsTool.modelsInitialized) { this.createViews(); } else { annotationsTool.once(annotationsTool.EVENTS.MODELS_INITIALIZED, this.createViews, this); } } else { annotationsTool.once(annotationsTool.EVENTS.MODELS_INITIALIZED, this.createViews, this); this.loginView.show(); } }, /** * Logout from the tool * @alias module:views-main.MainView#logout */ logout: function () { // Stop the video annotationsTool.playerAdapter.pause(); // Hide logout button $("a#logout").hide(); // Hide/remove the views annotationsTool.playerAdapter.pause(); annotationsTool.playerAdapter.setCurrentTime(0); $("#video-container").hide(); if (annotationsTool.getLayoutConfiguration().timeline) { this.timelineView.reset(); } if (annotationsTool.getLayoutConfiguration().annotate) { this.annotateView.reset(); } if (annotationsTool.getLayoutConfiguration().list) { this.listView.reset(); } this.loginView.reset(); // Delete the different objects delete annotationsTool.tracks; delete annotationsTool.video; delete annotationsTool.user; this.loadingBox.find(".bar").width("0%"); this.loadingBox.show(); annotationsTool.users.each(function (user) { Backbone.localSync("delete", user, { success: function () { console.log("current session destroyed."); }, error: function (error) { console.warn(error); } }); }); annotationsTool.modelsInitialized = false; if (annotationsTool.logoutUrl) { document.location = annotationsTool.logoutUrl; } else { location.reload(); } }, /** * Print the annotations * @alias module:views-main.MainView#print */ print: function () { window.focus(); if (document.readyState === "complete") { window.print(); // If is Chrome, we need to refresh the window if (/chrome/i.test(navigator.userAgent)) { document.location.reload(false); } } else { setTimeout(this.print, 1000); } }, /** * Filter the tracks following the option selected in the menu * @alias module:views-main.MainView#tracksSelection */ tracksSelection: function (event) { var prefixFilter = "opt-tracks-"; if ($(event.target).hasClass(prefixFilter + "public")) { annotationsTool.getTracks().showAllPublic(); } else if ($(event.target).hasClass(prefixFilter + "mine")) { annotationsTool.getTracks().showMyTracks(); } else { if (_.isUndefined(this.tracksSelectionModal)) { this.tracksSelectionModal = new TracksSelectionView(); } this.tracksSelectionModal.show(); } $("[class*='opt-tracks']").removeClass("checked"); $("." + event.target.className).addClass("checked"); }, /** * Set the layout of the tools following the option selected in the menu * @alias module:views-main.MainView#layoutUpdate */ layoutUpdate: function (event) { var enabled = !$(event.target).hasClass("checked"), layoutElement = event.currentTarget.id.replace("opt-", ""), checkMainLayout = function () { if (!annotationsTool.views.annotate.visible && !annotationsTool.views.list.visible) { $("#left-column").removeClass("span6"); $("#left-column").addClass("span12"); } else { $("#left-column").addClass("span6"); $("#left-column").removeClass("span12"); } annotationsTool.views.timeline.redraw(); }; if (enabled) { $(event.target).addClass("checked"); } else { $(event.target).removeClass("checked"); } switch (layoutElement) { case "annotate-text": this.annotateView.enableFreeTextLayout(enabled); break; case "annotate-categories": this.annotateView.enableCategoriesLayout(enabled); break; case "view-annotate": annotationsTool.views.annotate.toggleVisibility(); checkMainLayout(); break; case "view-list": annotationsTool.views.list.toggleVisibility(); checkMainLayout(); break; } }, /** * Annotation through the "<-" key * @alias module:views-main.MainView#onDeletePressed * @param {Event} event Event object */ onDeletePressed: function (event) { var annotation; if (event.keyCode !== 8 || document.activeElement.tagName.toUpperCase() === "TEXTAREA" || document.activeElement.tagName.toUpperCase() === "INPUT" || !annotationsTool.hasSelection()) { return; } else { event.preventDefault(); annotation = annotationsTool.getSelection()[0]; if (annotation) { annotationsTool.trigger("deleteAnnotation", annotation.get("id"), annotation.trackId); } } }, /** * Delete the annotation with the given id with the track with the given track id * @alias module:views-main.MainView#deleteAnnotation * @param {integer} annotationId The id of the annotation to delete * @param {integer} trackId Id of the track containing the annotation */ deleteAnnotation: function (annotationId, trackId) { var annotation; if (typeof trackId === "undefined") { annotationsTool.video.get("tracks").each(function (track) { if (track.get("annotations").get(annotationId)) { trackId = track.get("id"); } }); } annotation = annotationsTool.video.getAnnotation(annotationId, trackId); if (annotation) { annotationsTool.deleteOperation.start(annotation, annotationsTool.deleteOperation.targetTypes.ANNOTATION); } else { console.warn("Not able to find annotation %i on track %i", annotationId, trackId); } }, /** * Listener for window resizing * @alias module:views-main.MainView#onWindowResize */ onWindowResize: function () { var listContent, windowHeight = $(window).height(), annotationsContainerHeight = $("#annotate-container").height(), loopFunctionHeight = !_.isUndefined(annotationsTool.loopFunction) && annotationsTool.loopFunction.isVisible() ? annotationsTool.loopFunction.$el.height() + 180 : 145, videoContainerHeight = $("#video-container").height(); // TODO: improve this part with a better layout management, more generic if (this.annotateView && this.listView) { listContent = this.listView.$el.find("#content-list-scroll"); listContent.css("max-height", windowHeight - annotationsContainerHeight - 120); } if (this.timelineView) { this.timelineView.$el.find("#timeline").css("max-height", windowHeight - (videoContainerHeight + loopFunctionHeight)); } }, /** * Update loading box with given percent & message * @alias module:views-main.MainView#setLoadingProgress * @param {integer} percent loaded of the tool * @param {string} current loading operation message */ setLoadingProgress: function (percent, message) { this.loadingPercent = percent; this.loadingBox.find(".bar").width(this.loadingPercent + "%"); this.loadingBox.find(".info").text(message); } }); return MainView; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing a scale values collection * @module collections-scalevalues * @requires jQuery * @requires models-scalevalue * @requires backbone * @requires localstorage */ define(["jquery", "models/scalevalue", "backbone", "localstorage"], function ($, ScaleValue, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Collection} * @augments module:Backbone.Collection * @memberOf module:collections-scalevalues * @alias module:collections-scalevalues.ScaleValues */ var ScaleValues = Backbone.Collection.extend({ /** * Model of the instances contained in this collection * @alias module:collections-scalevalues.ScaleValues#initialize */ model: ScaleValue, /** * Localstorage container for the collection * @alias module:collections-scalevalues.ScaleValues#localStorage * @type {Backbone.LocalStorgage} */ localStorage: new Backbone.LocalStorage("ScaleValue"), /** * constructor * @alias module:collections-scalevalues.ScaleValues#initialize */ initialize: function (models, scale) { _.bindAll(this, "setUrl", "toExportJSON"); this.scale = scale; this.setUrl(scale); }, /** * Parse the given data * @alias module:collections-scalevalues.ScaleValues#parse * @param {object} data Object or array containing the data to parse. * @return {object} the part of the given data related to the scalevalues */ parse: function (data) { if (data.scaleValues && _.isArray(data.scaleValues)) { return data.scaleValues; } else if (_.isArray(data)) { return data; } else { return null; } }, comparator: function (scaleValue) { return scaleValue.get("order"); }, /** * Get the collection as array with the model in JSON, ready to be exported * @alias module:collections-scalevalues.ScaleValues#toExportJSON * @return {array} Array of json models */ toExportJSON: function () { var valueForExport = []; this.each(function (value) { valueForExport.push(value.toExportJSON()); }); return valueForExport; }, /** * Define the url from the collection with the given scale * @alias module:collections-scalevalues.ScaleValues#setUrl * @param {Scale} Scale containing the scalevalues */ setUrl: function (scale) { if (!scale && !this.scale) { throw "The parent scale of the scale value must be given!"; } else if (scale && scale.collection) { this.url = scale.url() + "/scalevalues"; } else if (this.scale.collection) { this.url = this.scale.url() + "/scalevalues"; } if (annotationsTool.localStorage) { this.localStorage = new Backbone.LocalStorage(this.url); } } }); return ScaleValues; } );<file_sep>/** * Bootstrap file for the require.js optimization */ require(["domReady", "annotations-tool-configuration", "annotations-tool"], function (domReady, config, app) { domReady(function(){ app.start(config); }); } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * Module containing the tool configuration * @module annotations-tool-configuration */ define(["jquery", "underscore", "roles", "player_adapter_HTML5" // Add here the files (PlayerAdapter, ...) required for your configuration ], function ($, _, ROLES, HTML5PlayerAdapter) { "use strict"; var video_title, video_creator, video_creation_date, /** * Annotations tool configuration object * @alias module:annotations-tool-configuration.Configuration * @enum */ Configuration = { /** * List of possible layout configuration * @memberOf module:annotations-tool-configuration.Configuration * @type {Object} */ LAYOUT_CONFIGURATION: { /** default configuration */ DEFAULT: { timeline : true, list : true, annotate : true, loop : false } }, /** * The default tracks at startup * @type {{@link this.TRACKS}} */ getDefaultTracks: function () { return { name: "mine", filter: function (track) { return track.get("isMine"); } }; }, /** * The minmal duration used for annotation representation on timeline * @alias module:annotations-tool-configuration.Configuration.MINIMAL_DURATION * @memberOf module:annotations-tool-configuration.Configuration * @type {Object} */ MINIMAL_DURATION: 5, /** * Define the number of categories pro tab in the annotate box. Bigger is number, thinner will be the columns for the categories. * @alias module:annotations-tool-configuration.Configuration.CATEGORIES_PER_TAB * @memberOf module:annotations-tool-configuration.Configuration * @type {Number} */ CATEGORIES_PER_TAB: 7, /** * The maximal number of tracks visible in the timeline at the same time * @type {Number} */ MAX_VISIBLE_TRACKS: 0, /** * Define if the localStorage should be used or not * @alias module:annotations-tool-configuration.Configuration.localStorage * @type {boolean} * @readOnly */ localStorage: false, localStorageOnlyModel: [], plugins: { Loop: function () { require(["views/loop"], function (Loop) { annotationsTool.loopView = new Loop(); }); } }, /** * Url from the annotations Rest Endpoints * @alias module:annotations-tool-configuration.Configuration.restEndpointsUrl * @type {string} * @readOnly */ restEndpointsUrl: "../../extended-annotations", /** * Url for redirect after the logout * @alias module:annotations-tool-configuration.Configuration.logoutUrl * @type {string} * @readOnly */ logoutUrl: "/j_spring_security_logout", /** * Url from the export function for statistics usage * @alias module:annotations-tool-configuration.Configuration.exportUrl * @type {string} * @readOnly */ exportUrl: "../extended-annotations/export.csv", /** * Player adapter implementation to use for the annotations tool * @alias module:annotations-tool-configuration.Configuration.playerAdapter * @type {module:player-adapter.PlayerAdapter} */ playerAdapter: undefined, tracksToImport: undefined, /** * Formats the given date in * @alias module:annotations-tool-configuration.Configuration.formatDate * @type {module:player-adapter.formatDate} */ formatDate: function (date) { if (_.isNumber(date)) { date = new Date(date); } if (_.isDate(date)) { return date.getDate() + "." + (date.getMonth() + 1) + "." + date.getFullYear(); } else { return "Unvalid date"; } }, /** * Get the tool layout configuration * @return {object} The tool layout configuration */ getLayoutConfiguration: function () { return this.LAYOUT_CONFIGURATION.DEFAULT; }, /** * Define if the structured annotations are or not enabled * @alias module:annotations-tool-configuration.Configuration.isStructuredAnnotationEnabled * @return {boolean} True if this feature is enabled */ isStructuredAnnotationEnabled: function () { return true; }, /** * Define if the private-only mode is enabled * @alias module:annotations-tool-configuration.Configuration.isPrivateOnly * @return {boolean} True if this mode is enabled */ isPrivateOnly: function () { return false; }, /** * Define if the free text annotations are or not enabled * @alias module:annotations-tool-configuration.Configuration.isFreeTextEnabled * @return {boolean} True if this feature is enabled */ isFreeTextEnabled: function () { return true; }, /** * Get the current video id (video_extid) * @alias module:annotations-tool-configuration.Configuration.getVideoExtId * @return {string} video external id */ getVideoExtId: function () { return $("video")[0].id; }, /** * Returns the time interval between each timeupdate event to take into account. * It can improve a bit the performance if the amount of annotations is important. * @alias module:annotations-tool-configuration.Configuration.getTimeupdateIntervalForTimeline * @return {number} The interval */ getTimeupdateIntervalForTimeline: function () { // TODO Check if this function should be linear return Math.max(500, annotationsTool.getAnnotations().length * 3); }, /** * Sets the behavior of the timeline. Enable it to follow the playhead. * @alias module:annotations-tool-configuration.Configuration.timelineFollowPlayhead * @type {Boolean} */ timelineFollowPlayhead: true, /** * Get the external parameters related to video. The supported parameters are now the following: * - video_extid: Required! Same as the value returned by getVideoExtId * - title: The title of the video * - src_owner: The owner of the video in the system * - src_creation_date: The date of the course, when the video itself was created. * @alias module:annotations-tool-configuration.Configuration.getVideoExtId * @example * { * video_extid: 123, // Same as the value returned by getVideoExtId * title: "Math lesson 4", // The title of the video * src_owner: "<NAME>", // The owner of the video in the system * src_creation_date: "12-12-1023" // The date of the course, when the video itself was created. * } * @return {Object} The literal object containing all the parameters described in the example. */ getVideoParameters: function () { return { video_extid : this.getVideoExtId(), title : video_title, src_owner : video_creator, src_creation_date : video_creation_date }; }, /** * Get the user id from the current context (user_extid) * @alias module:annotations-tool-configuration.Configuration.getUserExtId * @return {string} user_extid */ getUserExtId: function () { if (_.isUndefined(annotationsTool.userExtId)) { $.ajax({ url: "/info/me.json", async: false, dataType: "json", success: function (data) { annotationsTool.userExtId = data.user.username; }, error: function () { console.warn("Error getting user information from Matterhorn!"); } }); } return annotationsTool.userExtId; }, /** * Get the role of the current user * @alias module:annotations-tool-configuration.Configuration.getUserRole * @return {ROLE} The current user role */ getUserRole: function () { var ROLE_ADMIN = "ROLE_ADMIN"; if (_.isUndefined(annotationsTool.userRole)) { $.ajax({ url: "/info/me.json", async: false, dataType: "json", success: function (data) { if (_.contains(data.roles, ROLE_ADMIN)) { annotationsTool.userRole = ROLES.SUPERVISOR; } if (_.contains(data.roles, data.org.adminRole)) { annotationsTool.userRole = ROLES.ADMINISTRATOR; } }, error: function () { console.warn("Error getting user information from Matterhorn!"); } }); } return annotationsTool.userRole | ROLES.USER; }, /** * Get the name of the admin role * @alias module:annotations-tool-configuration.Configuration.getAdminRoleName * @return {ROLE} The name of the admin role */ getAdminRoleName: function () { return ROLES.ADMINISTRATOR; }, /** * Function to load the video * @alias module:annotations-tool-configuration.Configuration.loadVideo */ loadVideo: function () { var duration = 0, // Supported video formats videoTypes = ["video/webm", "video/ogg", "video/mp4"], videoTypeIE9 = "video/mp4", //var videoTypesForFallBack = ["video/x-flv"]; videoTypesForFallBack = [], trackType = ["presenter/delivery", "presentation/delivery"], mediaPackageId = decodeURI((new RegExp("id=" + "(.+?)(&|$)").exec(location.search) || [,null])[1]); // Enable cross-domain for jquery ajax query $.support.cors = true; annotationsTool.playerAdapter = new HTML5PlayerAdapter($("video")[0]); // Get the mediapackage and fill the player element with the videos $.ajax({ url: "/archive/episode.json", async: false, crossDomain: true, data: "id=" + mediaPackageId + "&limit=1", dataType: "json", success: function (data) { var result = data["search-results"].result, mediapackage = result.mediapackage, videos = {}, videosFallback = {}, nbNormalVideos = 0, nbFallbackVideos = {}, tracks, selectedVideos = {}, videoIE9; video_title = result.dcTitle; video_creator = result.dcCreator; video_creation_date = result.dcCreated; $.each(videoTypesForFallBack, function (idx, mimetype) { videosFallback[mimetype] = {}; nbFallbackVideos[mimetype] = 0; }); $.each(trackType, function (index, type) { videos[type] = []; $.each(videoTypesForFallBack, function (idx, mimetype) { videosFallback[mimetype][type] = []; }); }); tracks = mediapackage.media.track; if (!$.isArray(tracks)) { tracks = []; tracks.push(mediapackage.media.track); } $.each(tracks, function (index, track) { selectedVideos = null; if (track.mimetype === videoTypeIE9 && $.inArray(track.type, trackType) !== -1) { videoIE9 = track; } // If type not supported, go to next track if ($.inArray(track.mimetype, videoTypes) !== -1) { selectedVideos = videos; nbNormalVideos++; } else if ($.inArray(track.mimetype, videoTypesForFallBack) !== -1) { selectedVideos = videosFallback[track.mimetype]; nbFallbackVideos[track.mimetype]++; } else { return; } $.each(trackType, function (index, type) { if (track.type === type) { selectedVideos[type].push(track); return false; } }); }); if (nbNormalVideos === 0) { $.each(videoTypesForFallBack, function (idx, mimetype) { if (nbFallbackVideos[mimetype] > 0) { selectedVideos = videosFallback[mimetype]; return false; } }); } else { selectedVideos = videos; } if (annotationsTool.isBrowserIE9()) { $("video").attr("src", videoIE9.url).attr("type", videoTypeIE9); } else { $.each(selectedVideos, function (index, type) { if (type.length !== 0) { var videoSrc = ""; $.each(type, function (idx, track) { if (duration === 0) { duration = track.duration; } videoSrc += "<source src=\"" + track.url + "\" type=\"" + track.mimetype + "\"></source>"; }); if (videoSrc !== "") { $("video").append(videoSrc); $("video").attr("id", mediaPackageId); } } }); } } }); } }; return Configuration; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /*global Element */ /** * A module representing the player adapter implementation for the HTML5 native player * @module player-adapter-HTML5 * @requires jQuery * @requires player-adapter */ define(["jquery", "prototypes/player_adapter"], function ($, PlayerAdapter) { "use strict"; /** * Implementation of the player adapter for the HTML5 native player * @constructor * @alias module:player-adapter-HTML5.PlayerAdapterHTML5 * @augments {module:player-adapter.PlayerAdapter} * @param {DOMElement} targetElement DOM Element representing the player */ var PlayerAdapterHTML5 = function (targetElement) { var HTMLElement, self = this; // Allow to use HTMLElement with MS IE < 9 if (!HTMLElement) { HTMLElement = Element; } // Check if the given target Element is valid if (typeof targetElement === "undefined" || targetElement === null || !(targetElement instanceof HTMLElement)) { throw "The given target element must not be null and have to be a vaild HTMLElement!"; } /** * Id of the player adapter * @inner * @type {String} */ this.id = "PlayerAdapter" + targetElement.id; /** * The HTML representation of the adapter, mainly used to thriggered event * @inner * @type {DOMElement} */ this.htmlElement = null; /** * The current player status * @inner * @type {module:player-adapter.PlayerAdapter.STATUS} */ this.status = PlayerAdapter.STATUS.INITIALIZING; /** * Define if a play request has be done when the player was not ready * @inner * @type {Boolean} */ this.waitToPlay = false; /** * Define if a the player has been initialized * @inner * @type {Boolean} */ this.initialized = false; /** * Initilize the player adapter * @inner */ this.init = function () { // Create the HTML representation of the adapter $(targetElement).wrap(self.getHTMLTemplate(self.id)); if ($("#" + self.id).length === 0) { throw "Cannot create HTML representation of the adapter"; } self.htmlElement = document.getElementById(self.id); // Extend the current object with the HTML representation $.extend(true, this, self.htmlElement); // Add PlayerAdapter the prototype this.__proto__ = new PlayerAdapter(); // ...and ensure that its methods are used for the Events management this.dispatchEvent = this.__proto__.dispatchEvent; this.triggerEvent = this.__proto__.triggerEvent; this.addEventListener = this.__proto__.addEventListener; this.removeEventListener = this.__proto__.removeEventListener; this._getListeners = this.__proto__._getListeners; /** * Listen the events from the native player */ $(targetElement).bind("canplay durationchange", function () { // If duration is still not valid if (isNaN(self.getDuration()) || targetElement.readyState < 1) { return; } if (!self.initialized) { self.initialized = true; } // If duration is valid, we chanded status self.status = PlayerAdapter.STATUS.PAUSED; self.triggerEvent(PlayerAdapter.EVENTS.READY); if (self.waitToPlay) { self.play(); } }); $(targetElement).bind("play", function () { if (!self.initialized) { return; } self.status = PlayerAdapter.STATUS.PLAYING; self.triggerEvent(PlayerAdapter.EVENTS.PLAY); }); $(targetElement).bind("playing", function () { self.status = PlayerAdapter.STATUS.PLAYING; }); $(targetElement).bind("pause", function () { if (!self.initialized) { return; } self.status = PlayerAdapter.STATUS.PAUSED; self.triggerEvent(PlayerAdapter.EVENTS.PAUSE); }); $(targetElement).bind("ended", function () { self.status = PlayerAdapter.STATUS.ENDED; self.triggerEvent(PlayerAdapter.EVENTS.ENDED); }); $(targetElement).bind("seeking", function () { self.oldStatus = self.status; self.status = PlayerAdapter.STATUS.SEEKING; self.triggerEvent(PlayerAdapter.EVENTS.SEEKING); }); $(targetElement).bind("seeked", function () { if (typeof self.oldStatus !== "undefined") { self.status = self.oldStatus; } else { self.status = PlayerAdapter.STATUS.PLAYING; } }); $(targetElement).bind("timeupdate", function () { if ((self.status == PlayerAdapter.STATUS.PAUSED || self.status == PlayerAdapter.STATUS.SEEKING) && !this.paused && !this.ended && this.currentTime > 0) { self.status = PlayerAdapter.STATUS.PLAYING; } self.triggerEvent(PlayerAdapter.EVENTS.TIMEUPDATE); }); $(targetElement).bind("error", function () { self.status = PlayerAdapter.STATUS.ERROR_NETWORK; self.triggerEvent(PlayerAdapter.EVENTS.ERROR); }); return this; }; // ================= // REQUIRED FUNCTIONS // ================= /** * Play the video */ this.play = function () { // Can the player start now? switch (self.status) { case PlayerAdapter.STATUS.INITIALIZING: case PlayerAdapter.STATUS.LOADING: self.waitToPlay = true; break; case PlayerAdapter.STATUS.SEEKING: case PlayerAdapter.STATUS.PAUSED: case PlayerAdapter.STATUS.PLAYING: case PlayerAdapter.STATUS.ENDED: // If yes, we play it targetElement.play(); self.status = PlayerAdapter.STATUS.PLAYING; self.waitToPlay = false; break; } }; /** * Pause the video */ this.pause = function () { targetElement.pause(); }; /** * Load the video */ this.load = function () { self.initialized = false; self.status = PlayerAdapter.STATUS.INITIALIZING; targetElement.load(); targetElement.load(); }; /** * Set the current time of the video * @param {double} time The time to set in seconds */ this.setCurrentTime = function (time) { targetElement.currentTime = time; }; /** * Get the current time of the video */ this.getCurrentTime = function () { return targetElement.currentTime; }; /** * Get the video duration */ this.getDuration = function () { return targetElement.duration; }; /** * Get the player status */ this.getStatus = function () { return self.status; }; // ================================= // IMPLEMENTATION SPECIFIC FUNCTIONS // ================================== /** * Get the HTML template for the html representation of the adapter */ this.getHTMLTemplate = function (id) { return "<div id=\"" + id + "\"></div>"; }; return self.init(); }; return PlayerAdapterHTML5; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * A module representing the tracks selection modal * @module views-tracks-selection * @requires jQuery * @requires Backbone * @requires templates/tracks-selection-modal.tmpl * @requires ROLES * @requires hanldebars */ define(["jquery", "backbone", "templates/tracks-selection-modal"], function ($, Backbone, TracksSelectionTmpl) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @augments module:Backbone.View * @memberOf module:views-tracks-selection * @alias Alert */ var TracksSelectionView = Backbone.View.extend({ tag: $("#tracks-selection"), /** * Template * @alias module:views-tracks-selection.Alert#alertTemplate * @type {HandlebarsTemplate} */ template: TracksSelectionTmpl, /** * Events to handle * @alias module:views-tracks-selection.Alert#events * @type {object} */ events: { "click #cancel-selection" : "cancel", "click #confirm-selection": "confirm", "click li" : "select", "click span input" : "selectAll", "keyup #search-track" : "search", "click button.search-only": "clear" }, /** * Constructor * @alias module:views-tracks-selection.Alert#initialize */ initialize: function () { _.bindAll(this, "show", "hide", "cancel", "clear", "confirm", "search", "select", "selectAll"); this.tracks = annotationsTool.getTracks(); }, /** * Display the modal with the given message as the given alert type * @alias module:views-tracks-selection.Alert#show * @param {String} message The message to display * @param {String | Object} type The name of the alert type or the type object itself, see {@link module:views-tracks-selection.Alert#TYPES} */ show: function () { this.$el.empty(); this.$el.append(this.template({ users: this.tracks.getAllCreators() })); this.delegateEvents(); this.$el.modal({show: true, backdrop: false, keyboard: false }); }, /** * Hide the modal * @alias module:views-tracks-selection.Alert#hide */ hide: function () { this.$el.modal("hide"); }, /** * Clear the search field * @alias module:views-tracks-selection.Alert#clear */ clear: function () { this.$el.find("#search-track").val(""); this.search(); }, /** * Cancel the track selection * @alias module:views-tracks-selection.Alert#cancel */ cancel: function () { this.hide(); }, /** * Confirm the track selection * @alias module:views-tracks-selection.Alert#confirm */ confirm: function () { var selection = this.$el.find("ul li :checked"), selectedIds = []; _.each(selection, function (el) { selectedIds.push(el.value); }, this); this.tracks.showTracksByCreators(selectedIds); this.hide(); }, /** * Mark the target user as selected * @alias module:views-tracks-selection.Alert#select */ select: function (event) { var $el = $(event.target).find("input"); $el.attr("checked", _.isUndefined($el.attr("checked"))); }, /** * Mark all the users selected or unselected * @alias module:views-tracks-selection.Alert#selectAll */ selectAll: function (event) { var checked = !_.isUndefined($(event.target).attr("checked")); this.$el.find("ul li input").attr("checked", checked); }, /** * Search for users with the given chars in the search input * @alias module:views-tracks-selection.Alert#search */ search: function (event) { var text = ""; if (!_.isUndefined(event)) { text = event.target.value; } this.$el.find(".list-group-item").hide(); if (!_.isUndefined(text) && text !== "") { this.$el.find("#modal-track-selection").addClass("search-mode"); this.$el.find(".list-group-item:contains(" + text.toUpperCase() + ")").show(); } else { this.$el.find("#modal-track-selection").removeClass("search-mode"); this.$el.find(".list-group-item").show(); } } }); return TracksSelectionView; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing the video model * @module models-video * @requires collections-categories * @requires collections-scales * @requires ACCESS * @requires backbone.js */ define(["jquery", "collections/tracks", "collections/categories", "collections/scales", "access", "backbone"], function ($, Tracks, Categories, Scales, ACCESS, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Model} * @augments module:Backbone.Model * @memberOf module:models-video * @alias module:models-video.Video */ var Video = Backbone.Model.extend({ /** * Default models value * @alias module:models-video.Video#defaults */ defaults: { access: ACCESS.PUBLIC }, /** * Constructor * @alias module:models-video.Video#initialize * @param {object} attr Object literal containing the model initialion attribute. */ initialize: function (attr) { _.bindAll(this, "getTrack", "getAnnotation", "loadTracks"); // Check if the video has been initialized if (!attr.id) { // If local storage, we set the cid as id if (window.annotationsTool.localStorage) { attr.id = this.cid; } this.toCreate = true; } // Check if tracks are given if (attr.tracks && _.isArray(attr.tracks)) { this.set({tracks: new Tracks(attr.tracks, this)}); } else { this.set({tracks: new Tracks([], this)}); } // Check if supported categories are given if (attr.categories && _.isArray(attr.categories)) { this.set({categories: new Categories(attr.categories, this)}); } else { this.set({categories: new Categories([], this)}); } // Check if the possible video scales are given if (attr.scales && _.isArray(attr.scales)) { this.set({scales: new Scales(attr.scales, this)}); } else { this.set({scales: new Scales([], this)}); } if (attr.tags) { this.set({tags: this.parseJSONString(attr.tags)}); } if (attr.id) { this.get("categories").fetch({async: false}); this.get("tracks").fetch({async: false}); this.get("scales").fetch({async: false}); } // Add backbone events to the model _.extend(this, Backbone.Events); // Define that all post operation have to been done through PUT method this.noPOST = true; }, /** * Parse the attribute list passed to the model * @alias module:models-video.Video#parse * @param {object} data Object literal containing the model attribute to parse. * @return {object} The object literal with the list of parsed model attribute. */ parse: function (data) { var attr = data.attributes ? data.attributes : data; attr.created_at = attr.created_at !== null ? Date.parse(attr.created_at): null; attr.updated_at = attr.updated_at !== null ? Date.parse(attr.updated_at): null; attr.deleted_at = attr.deleted_at !== null ? Date.parse(attr.deleted_at): null; attr.settings = this.parseJSONString(attr.settings); // Parse tags if present if (attr.tags) { attr.tags = this.parseJSONString(attr.tags); } if (data.attributes) { data.attributes = attr; } else { data = attr; } return data; }, /** * Validate the attribute list passed to the model * @alias module:models-video.Video#validate * @param {object} data Object literal containing the model attribute to validate. * @return {string} If the validation failed, an error message will be returned. */ validate: function (attr) { var tmpCreated, categories, scales, self = this; if (attr.id) { if (this.get("id") !== attr.id) { this.id = attr.id; this.attributes.id = attr.id; this.setUrl(); categories = this.attributes.categories; scales = this.attributes.scales; this.loadTracks(); if (scales && (scales.length) === 0) { scales.fetch({ async: false, success: function () { self.scalesReady = true; if (categories && (categories.length) === 0) { categories.fetch({ async: false, success: function () { self.categoriesReady = true; if (self.tracksReady && self.categoriesReady && self.scalesReady) { self.trigger("ready"); self.attributes.ready = true; } } }); } else if (self.tracksReady && self.categoriesReady && self.scalesReady) { self.trigger("ready"); self.attributes.ready = true; } } }); } } } if (attr.tracks && !(attr.tracks instanceof Tracks)) { return "'tracks' attribute must be an instance of 'Tracks'"; } if (attr.tags && _.isUndefined(this.parseJSONString(attr.tags))) { return "'tags' attribute must be a string or a JSON object"; } if (attr.created_at) { if ((tmpCreated = this.get("created_at")) && tmpCreated !== attr.created_at) { return "'created_at' attribute can not be modified after initialization!"; } else if (!_.isNumber(attr.created_at)) { return "'created_at' attribute must be a number!"; } } if (attr.updated_at) { if (!_.isNumber(attr.updated_at)) { return "'updated_at' attribute must be a number!"; } } if (attr.deleted_at) { if (!_.isNumber(attr.deleted_at)) { return "'deleted_at' attribute must be a number!"; } } }, loadTracks: function () { var tracks = this.attributes.tracks, self = this; if (tracks && (tracks.length) === 0) { tracks.fetch({ async : false, success: function () { self.tracksReady = true; if (self.tracksReady && self.categoriesReady && self.scalesReady) { self.trigger("ready"); self.attributes.ready = true; } } }); } }, /** * Modify the current url for the tracks collection * @alias module:models-video.Video#setUrl */ setUrl: function () { if (this.attributes.tracks) { this.attributes.tracks.setUrl(this); } if (this.attributes.categories) { this.attributes.categories.setUrl(this); } if (this.attributes.scales) { this.attributes.scales.setUrl(this); } }, /** * Get the track with the given id * @alias module:models-video.Video#getTrack * @param {integer} trackId The id from the wanted track * @return {Track} The track with the given id */ getTrack: function (trackId) { if (_.isUndefined(this.tracks)) { this.tracks = this.get("tracks"); } return this.tracks.get(trackId); }, /** * Get the annotation with the given id on the given track * @alias module:models-video.Video#getAnnotation * @param {integer} annotationId The id from the wanted annotation * @param {integer} trackId The id from the track containing the annotation * @return {Track} The annotation with the given id */ getAnnotation: function (annotationId, trackId) { var track = this.getTrack(trackId), tmpAnnotation; if (track) { return track.getAnnotation(annotationId); } else { this.get("tracks").each(function (trackItem) { tmpAnnotation = trackItem.getAnnotation(annotationId); if (!_.isUndefined(tmpAnnotation)) { return tmpAnnotation; } }, this); return tmpAnnotation; } }, /** * Parse the given parameter to JSON if given as String * @alias module:models-video.Video#parseJSONString * @param {string} parameter the parameter as String * @return {JSON} parameter as JSON object */ parseJSONString: function (parameter) { if (parameter && _.isString(parameter)) { try { parameter = JSON.parse(parameter); } catch (e) { console.warn("Can not parse parameter '" + parameter + "': " + e); return undefined; } } else if (!_.isObject(parameter) || _.isFunction(parameter)) { return undefined; } return parameter; }, /** * Override the default toJSON function to ensure complete JSONing. * @alias module:models-video.Video#toJSON * @return {JSON} JSON representation of the instane */ toJSON: function () { var json = $.proxy(Backbone.Model.prototype.toJSON, this)(); if (json.tags) { json.tags = JSON.stringify(json.tags); } delete json.tracks; delete json.categories; delete json.scales; return json; } }); return Video; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * Module for the filters manager * @module filters-manager * @requires backbone */ define(["backbone", "access"], function (Backbone, ACCESS) { "use strict"; /** * Filter Manager * @alias module:filters-manager.FiltersManager * @constructor * @param {module:filters-manager.FiltersManager} [master] The main filter manager. If present, the new Filters Manager will be bound with the given one */ var FiltersManager = function (master) { _.extend(this, Backbone.Events); this._cloneFilters(); if (master instanceof FiltersManager) { this.master = master; this.isBindedToMaster = true; this.listenTo(master, "switch", this._switchListener); } else if (master) { console.warn("Parent for FiltersManager is not valid!"); } else { delete this.bindToMaster; delete this.unbdindFromMaster; } }; FiltersManager.prototype = { /** * List of filter used for the list elements * @type {Object} */ filters: { mine: { active : false, condition: function (item) { return _.isUndefined(item.model) || item.model.get("isMine"); }, filter : function (list) { return _.filter(list, function (item) { return this.condition(item); }, this); } }, public: { active : false, condition: function (item) { return _.isUndefined(item.model) || item.model.get("isPublic") || (item.model.get("access") === ACCESS.PUBLIC); }, filter : function (list) { return _.filter(list, function (item) { return this.condition(item); }, this); } }, timerange: { active : false, start : 0, end : 0, condition: function (item) { if (!_.isUndefined(item.voidItem)) { return true; } else if (_.isUndefined(item.start) || _.isUndefined(item.end)) { return false; } return (item.start >= this.start && item.start < this.end) || (item.start <= this.start && item.end >= this.end); }, filter : function (list) { return _.filter(list, function (item) { return this.condition(item); }, this); } } }, /** * Clone the default filters * @return {Object} The cloned filters list */ _cloneFilters: function () { var filters = {}; _.each(this.filters, function (filter, id) { filters[id] = _.clone(filter); }, this); this.filters = filters; return filters; }, /** * Filter the given with all the active filter * @param {Object} list The list of elements to filter * @params {Object} (filters) The list of filters to use * @return {Object} the filtered list */ filterAll: function (list, filters) { var activeFilters = _.map(_.isUndefined(filters) ? this.filters : filters, function (item) {return item; }, this), filterList = function (item) { var cFilter, i; for (i = 0; i < activeFilters.length; i++) { cFilter = activeFilters[i]; if (cFilter.active && !cFilter.condition(item)) { return false; } } return true; }; return _.filter(list, filterList, this); }, /** * Disable all filters */ disableFilters: function () { _.each(this.filters, function (filter, index) { this.switchFilter(index, false); }, this); }, /** * Switch the filter with the given id. If the manager is bound to a master, it will switch it on the master. * @param {string} id Filter id * @param {boolean} active Define if the filter must be active or not */ switchFilter: function (id, active) { if (this.isBindedToMaster) { this.master.switchFilter(id, active); } else { this._switchFilterLocally(id, active); } }, /** * Switch the filter with the given id for this instance * @param {string} id Filter id * @param {boolean} active Define if the filter must be active or not */ _switchFilterLocally: function (id, active) { if (_.isUndefined(this.filters[id])) { return; } this.filters[id].active = active; this.trigger("switch", {id: id, active: active}); }, /** * Listener for the update on the master filters * @inner * @param {object} attr The filter attribute */ _switchListener: function (attr) { if (this.isBindedToMaster) { this._switchFilterLocally(attr.id, attr.active); } }, /** * Get the filters from this manager. If bound to a master, the ones from the master will be returned. */ getFilters: function () { if (this.isBindedToMaster) { return this.master.filters; } else { return this.filters; } }, /** * Bind this instance to its master */ bindToMaster: function () { this.isBindedToMaster = true; }, /** * Unbind this instance from its master */ unbdindFromMaster: function () { this.isBindedToMaster = false; } }; return FiltersManager; });<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * A module representing the view for a comments container * @module views-comments-container * @requires jQuery * @requires underscore * @requires views-comment * @requires templates/comments-container.tmpl * @requires handlebars * @requires backbone */ define(["jquery", "views/comment", "templates/comments-container", "handlebars", "backbone"], function ($, CommentView, Template, Handlebars, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @augments module:Backbone.View * @memberOf module:views-comments-container * @alias module:views-comments-container.CommentsContainer */ var CommentsContainer = Backbone.View.extend({ /** * Tag name from the view element * @alias module:views-comments-container.CommentsContainer#tagName * @type {string} */ tagName: "div", /** * Class name from the view element * @alias module:views-comments-container.CommentsContainer#className * @type {string} */ className: "comments-container", /** * View template * @alias module:views-comments-container.CommentsContainer#template * @type {HandlebarsTemplate} */ template: Template, /** * Define if the view is or not collapsed * @alias module:views-comments-container.CommentsContainer#collapsed * @type {boolean} */ collapsed: true, //Todo: Collapse function needs to be completely removed. /** * Events to handle * @alias module:views-comments-container.CommentsContainer#events * @type {object} */ events: { "click a.add-comment" : "onAddComment", "keyup textarea.create" : "keyupInsertProxy", "click button[type=submit].add-comment" : "insert", "click button[type=button].cancel-comment" : "onCancelComment" }, currentState: false, /** * constructor * @alias module:views-comments-container.CommentsContainer#initialize * @param {PlainObject} attr Object literal containing the view initialization attributes. */ initialize: function (attr) { if (typeof attr.collapsed !== "undefined") { this.collapsed = attr.collapsed; } this.annotationId = attr.id; this.id = "comments-container" + attr.id; this.el.id = this.id; this.comments = attr.comments; this.commentViews = []; this.cancelCallback = attr.cancel; this.editCommentCallback = attr.edit; // Bind function to the good context _.bindAll(this, "render", "deleteView", "onAddComment", "insert", "onCancelComment", "keyupInsertProxy", "resetViews", "toggleAddState"); // Add backbone events to the model _.extend(this.comments, Backbone.Events); this.listenTo(this.comments, "destroy", this.deleteView); this.listenTo(this.comments, "remove", this.deleteView); this.listenTo(this.comments, "reset", this.resetViews); this.currentState = CommentsContainer.STATES.READ; this.resetViews(); return this.render(); }, setState: function (state) { this.currentState = state; }, toggleAddState: function (state) { if (!_.isUndefined(state)) { this.currentState = state; } else { this.currentState = !this.addState; } }, toggleEditState: function (state) { if (!_.isUndefined(state)) { this.addState = state; } else { this.addState = !this.addState; } }, /** * Reset all the views set * @alias module:views-comments-container.CommentsContainer#resetViews */ resetViews: function () { _.each(this.commentViews, function (commentView, index) { this.commentViews.splice(index, 1); commentView.deleteView(); }, this); _.each(this.comments.toArray(), function (comment) { this.addComment(comment); }, this); }, /** * Render this view * @alias module:views-comments-container.CommentsContainer#render */ render: function () { this.$el.html(this.template({ id : this.annotationId, comments : this.comments.models, addState : this.currentState === CommentsContainer.STATES.ADD })); this.commentList = this.$el.find("div#comment-list" + this.annotationId); this.commentList.empty(); _.each(this.commentViews, function (commentView) { this.commentList.append(commentView.render().$el); }, this); this.delegateEvents(this.events); return this; }, /** * Remove the given comment from the views list * @alias module:views-comments-container.CommentsContainer#deleteView * @param {Comment} Comment from which the view has to be deleted */ deleteView: function (delComment) { _.find(this.commentViews, function (commentView, index) { if (delComment === commentView.model) { this.commentViews.splice(index, 1); commentView.deleteView(); this.render(); return; } }, this); }, /** * Sort all the comments in the list by date * @alias module:views-comments-container.CommentsContainer#sortViewsByDate */ sortViewsByDate: function () { this.commentViews = _.sortBy(this.commentViews, function (commentViews) { return commentViews.model.get("created_at"); }); this.render(); }, /** * Proxy to insert comments by pressing the "return" key * @alias module:views-comments-container.CommentsContainer#keyupInsertProxy * @param {event} event Event object */ keyupInsertProxy: function (event) { // If enter is pressed and shit not, we insert a new annotation if (event.keyCode === 13 && !event.shiftKey) { this.insert(); } }, /** * Submit a comment to the backend * @alias module:views-comments-container.CommentsContainer#insert */ insert: function () { var textValue = this.$el.find("textarea").val(), commentModel; if (textValue === "") { return; } commentModel = this.comments.create({text: textValue}); this.cancel(); this.addComment(commentModel); this.render(); }, /** * Add a new comment to the container * @alias module:views-comments-container.CommentsContainer#addComment * @param {Comment} comment Comment to add */ addComment: function (comment) { var self = this, commentModel = new CommentView({ model: comment, cancel: function () { self.setState(CommentsContainer.STATES.ADD); self.cancelCallback(); self.render(); }, edit: function () { self.setState(CommentsContainer.STATES.EDIT); self.editCommentCallback(); self.render(); } }); this.commentViews.push(commentModel); this.$el.parent().find(".comment-amount").text(this.comments.length); this.$el.find("textarea").focus(); }, /** * Start the insertion of a new comment, display the textarea for it. * @alias module:views-comments-container.CommentsContainer#onAddComment * @param {event} event Event object */ onAddComment: function (event) { event.stopImmediatePropagation(); this.$el.find("textarea").show(); this.$el.find("button").removeClass("hide"); this.$el.find("textarea").focus(); }, /** * Listener for the cancel button * @alias module:views-comments-container.CommentsContainer#onCancelComment * @param {event} event Event object */ onCancelComment: function (event) { event.stopImmediatePropagation(); this.cancel(); }, /** * Cancel the insertion of a comment * @alias module:views-comments-container.CommentsContainer#cancel */ cancel: function () { this.$el.find("textarea").val(""); this.cancelCallback(); } }, { STATES: { READ : "read", ADD : "add-comment", EDIT : "edit-comment" } }); return CommentsContainer; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing the main view to create anotation * @module views-annotate * @requires jQuery * @requires underscore * @requires player-adapter * @requires models-annotation * @requires collections-annotations * @requires collections-categories * @requires templates/annotate-tab-title.tmpl * @requires ROLES * @requires ACCESS * @requires handlebars * @requires backbone */ define(["jquery", "underscore", "prototypes/player_adapter", "models/annotation", "collections/annotations", "collections/categories", "views/annotate-tab", "templates/annotate-tab-title", "roles", "access", "handlebarsHelpers", "backbone"], function ($, _, PlayerAdapter, Annotation, Annotations, Categories, AnnotateTab, TabsButtonTemplate, ROLES, ACCESS, Handlebars, Backbone) { "use strict"; /** * Prefix for the name of the categories tab id * @type {String} */ var TAB_LINK_PREFIX = "#labelTab-", /** * List of default tabs, each object contains an id, name and an array of roles * @type {Object} */ DEFAULT_TABS = { ALL: { id : "all", name : "All", roles: [] }, PUBLIC: { id : "public", name : "Public", filter : {isPublic: true}, roles : [ROLES.SUPERVISOR, ROLES.ADMINISTRATOR], attributes: {access: ACCESS.PUBLIC} }, MINE: { id : "mine", name : "Mine", filter : {isPublic: false}, roles : [ROLES.SUPERVISOR, ROLES.USER, ROLES.ADMINISTRATOR], attributes: {access: ACCESS.PRIVATE} } }, /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @memberOf module:views-annotate * @augments module:Backbone.View * @alias module:views-annotate.Annotate */ Annotate = Backbone.View.extend({ /** * Main container of the annotate view * @alias module:views-annotate.Annotate#el * @type {DOMElement} */ el: $("div#annotate-container"), /** * Events to handle by the annotate view * @alias module:views-annotate.Annotate#events * @type {map} */ events: { "keyup #new-annotation" : "keydownOnAnnotate", "click #insert" : "insert", "click .toggle-collapse" : "toggleVisibility", "keydown #new-annotation" : "onFocusIn", "focusout #new-annotation" : "onFocusOut", "click #label-tabs-buttons a" : "showTab", "click #editSwitch" : "onSwitchEditModus" }, /** * Template for tabs button * @alias module:views-annotate.Category#tabsButtonTemplate * @type {HandlebarsTemplate} */ tabsButtonTemplate: TabsButtonTemplate, /** * Element containing the tabs buttons * @alias module:views-annotate.Category#tabsButtonsElement * @type {DOMElement} */ tabsButtonsElement: $("ul#label-tabs-buttons"), /** * Element containing the tabs contents * @alias module:views-annotate.Category#tabsContainerElement * @type {DOMElement} */ tabsContainerElement: $("div#label-tabs-contents"), /** * Define if the view is or not in edit modus. * @alias module:views-annotate.Category#editModus * @type {boolean} */ editModus: false, /** * Map with all the category tabs * @alias module:views-annotate.Category#categoriesTabs * @type {map} */ categoriesTabs: {}, /** * The default tabs when switching in edit modus * @alias module:views-annotate.Category#DEFAULT_TAB_ON_EDIT * @type {map} */ DEFAULT_TAB_ON_EDIT: DEFAULT_TABS.MINE.id, /** * Layout configuration * @type {Object} */ layout: { freeText : true, categories : true }, visible: true, /** * constructor * @alias module:views-annotate.Category#initialize * @param {PlainObject} attr Object literal containing the view initialization attributes. */ initialize: function (attr) { var categories; // Set the current context for all these functions _.bindAll(this, "insert", "reset", "onFocusIn", "onFocusOut", "changeTrack", "addTab", "onSwitchEditModus", "checkToContinueVideo", "switchEditModus", "keydownOnAnnotate", "enableCategoriesLayout", "enableFreeTextLayout", "setLayoutFull", "toggleVisibility"); // Parameter for stop on write this.continueVideo = false; // New annotation input this.input = this.$("#new-annotation"); this.freeTextElement = this.$el.find("#input-container"); this.categoriesElement = this.$el.find("#categories"); // Print selected track this.trackDIV = this.$el.find("div.currentTrack span.content"); this.changeTrack(annotationsTool.selectedTrack); this.tracks = annotationsTool.video.get("tracks"); this.tracks.bind("selected_track", this.changeTrack, this); this.playerAdapter = attr.playerAdapter; if (annotationsTool.isStructuredAnnotationEnabled()) { categories = annotationsTool.video.get("categories"); annotationsTool.colorsManager.updateColors(categories.models); _.each(DEFAULT_TABS, function (params) { this.addTab(categories, params); }, this); } else { this.layout.categories = false; this.categoriesElement.hide(); this.$el.find("#annotate-categories").parent().hide(); } if (!annotationsTool.isFreeTextEnabled()) { this.layout.freeText = false; this.freeTextElement.hide(); this.$el.find("#annotate-text").parent().hide(); } this.$el.find("#annotate-full").addClass("checked"); this.tabsContainerElement.find("div.tab-pane:first-child").addClass("active"); this.tabsButtonsElement.find("a:first-child").parent().first().addClass("active"); // Add backbone events to the model _.extend(this, Backbone.Events); }, /** * Proxy function for insert through 'enter' keypress * @alias module:views-annotate.Annotate#keydownOnAnnotate * @param {event} event Event object */ keydownOnAnnotate: function (e) { // If enter is pressed and shit not, we insert a new annotation if (e.keyCode === 13 && !e.shiftKey) { this.insert(); } }, /** * Insert a new annotation * @alias module:views-annotate.Annotate#insert * @param {event} event Event object */ insert: function (event) { if (event) { event.stopImmediatePropagation(); } var value = this.input.val(), time = Math.round(this.playerAdapter.getCurrentTime()), options = {}, params, annotation; if (!value || (!_.isNumber(time) || time < 0)) { return; } params = { text: value, start: time }; if (annotationsTool.user) { params.created_by = annotationsTool.user.id; } if (!annotationsTool.localStorage) { options.wait = true; } annotation = annotationsTool.selectedTrack.get("annotations").create(params, options); if (this.continueVideo) { annotationsTool.playerAdapter.play(); } this.input.val(""); setTimeout(function () { $("#new-annotation").focus(); }, 500); }, /** * Change the current selected track by the given one * @alias module:views-annotate.Annotate#changeTrack * @param {Track} track The new track */ changeTrack: function (track) { // If the track is valid, we set it if (track) { this.input.attr("disabled", false); if (this.layout.freeText) { this.freeTextElement.show(); } if (this.layout.categories) { this.categoriesElement.show(); } this.$el.find(".no-track").hide(); this.trackDIV.html(track.get("name")); } else { // Otherwise, we disable the input and inform the user that no track is set this.freeTextElement.hide(); this.categoriesElement.hide(); this.input.attr("disabled", true); this.$el.find(".no-track").show(); this.trackDIV.html("<span>no track</span>"); } }, /** * Listener for when a user start to write a new annotation, * manage if the video has to be or not paused. * @alias module:views-annotate.Annotate#onFocusIn */ onFocusIn: function () { if (!this.$el.find("#pause-video").attr("checked") || (annotationsTool.playerAdapter.getStatus() === PlayerAdapter.STATUS.PAUSED)) { return; } this.continueVideo = true; this.playerAdapter.pause(); // If the video is moved, or played, we do no continue the video after insertion $(annotationsTool.playerAdapter).one(PlayerAdapter.EVENTS.TIMEUPDATE, function () { this.continueVideo = false; }); }, /** * Listener for when we leave the annotation input * @alias module:views-annotate.Annotate#onFocusOut */ onFocusOut: function () { setTimeout(this.checkToContinueVideo, 200); }, /** * Check if the video must continue, and if yes, continue to play it * @alias module:views-annotate.Annotate#checkToContinueVideo */ checkToContinueVideo: function () { if ((annotationsTool.playerAdapter.getStatus() === PlayerAdapter.STATUS.PAUSED) && this.continueVideo) { this.continueVideo = false; this.playerAdapter.play(); } }, /** * Show the tab related to the source from the event * @alias module:views-annotate.Annotate#showTab * @param {Event} event Event object */ showTab: function (event) { var tabId = event.currentTarget.attributes.getNamedItem("href").value; tabId = tabId.replace(TAB_LINK_PREFIX, ""); $(event.currentTarget).one("shown", $.proxy(function () { //this.categoriesTabs[tabId].render(); this.categoriesTabs[tabId].initCarousel(); }, this)); $(event.currentTarget).tab("show"); this.categoriesTabs[tabId].select(); }, /** * Add a new categories tab in the annotate view * @alias module:views-annotate.Annotate#addTab * @param {Categories} categories Categories to add to the new tab * @param {object} attr Infos about the new tab like id, name, filter for categories and roles. */ addTab: function (categories, attr) { var params = { id : attr.id, name : attr.name, categories: categories, filter : attr.filter, roles : attr.roles, attributes: attr.attributes }, newButton = this.tabsButtonTemplate(params), annotateTab; newButton = $(newButton).appendTo(this.tabsButtonsElement); params.button = newButton; annotateTab = new AnnotateTab(params); this.categoriesTabs[attr.id] = annotateTab; this.tabsContainerElement.append(annotateTab.$el); }, /** * Listener for edit modus switch. * @alias module:views-annotate.Annotate#onSwitchEditModus * @param {Event} event Event related to this action */ onSwitchEditModus: function (event) { var status = $(event.target).attr("checked") === "checked"; this.switchEditModus(status); if (status) { this.showTab({ currentTarget: this.categoriesTabs[this.DEFAULT_TAB_ON_EDIT].titleLink.find("a")[0] }); } }, /** * Switch the edit modus to the given status. * @alias module:views-annotate.Annotate#switchEditModus * @param {boolean} status The current status */ switchEditModus: function (status) { this.editModus = status; this.$el.toggleClass("edit-on", status); // trigger an event that all element switch in edit modus annotationsTool.trigger(annotationsTool.EVENTS.ANNOTATE_TOGGLE_EDIT, status); }, /** * Change the layout to full layout, with all possiblities to annotate * @alias module:views-annotate.Annotate#setLayoutFull * @param {Event} event Event object */ setLayoutFull: function (event) { if (!$(event.target).hasClass("checked")) { if (annotationsTool.isStructuredAnnotationEnabled()) { this.categoriesElement.show(); } if (annotationsTool.isFreeTextEnabled()) { this.freeTextElement.show(); } this.$el.find("#annotate-text").removeClass("checked"); this.$el.find("#annotate-categories").removeClass("checked"); $(event.target).addClass("checked"); this.trigger("change-layout"); } }, /** * Enable layout for free text annotation only * @alias module:views-annotate.Annotate#enableFreeTextLayout * @param {boolean} [enabled] Define if the layout must be enable or disable */ enableFreeTextLayout: function (enabled) { if (_.isUndefined(enabled)) { this.layout.freeText = !this.layout.freeText; } else if (this.layout.freeText == enabled) { return; } else { this.layout.freeText = enabled; } if (this.layout.freeText && annotationsTool.isFreeTextEnabled()) { this.freeTextElement.show(); if (!this.layout.categories) { $(".toggle-collapse").show(); } } else { this.freeTextElement.hide(); if (!this.layout.categories) { $(".toggle-collapse").hide(); } } this.trigger("change-layout"); }, /** * Enable layout for labels annotation * @alias module:views-annotate.Annotate#enableCategoriesLayout * @param {boolean} [enabled] Define if the layout must be enable or disable */ enableCategoriesLayout: function (enabled) { if (_.isUndefined(enabled)) { this.layout.categories = !this.layout.categories; } else if (this.layout.categories == enabled) { return; } else { this.layout.categories = enabled; } if (this.layout.categories && annotationsTool.isStructuredAnnotationEnabled()) { this.categoriesElement.show(); if (!this.layout.freeText) { $(".toggle-collapse").show(); } } else { this.categoriesElement.hide(); if (!this.layout.freeText) { $(".toggle-collapse").hide(); } } this.trigger("change-layout"); }, /** * Toggle the visibility of the annotate part * @alias module:views-annotate.Annotate#toggleVisibility * @param {Event} event Event object */ toggleVisibility: function () { this.visible = !this.visible; this.$el.fadeToggle(); this.trigger("change-layout"); }, /** * Reset the view * @alias module:views-annotate.Annotate#reset */ reset: function () { this.$el.hide(); delete this.tracks; this.undelegateEvents(); if (annotationsTool.isStructuredAnnotationEnabled()) { this.tabsContainerElement.empty(); this.$el.find("#editSwitch input").attr("checked", false); this.tabsButtonsElement.find(".tab-button").remove(); } } }); return Annotate; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing a comments collection * @module collections-comments * @requires jQuery * @requires models-comment * @requires backbone * @requires localstorage */ define(["jquery", "models/comment", "backbone", "localstorage"], function ($, Comment, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Collection} * @augments module:Backbone.Collection * @memberOf module:collections-comments * @alias module:collections-comments.Comments */ var Comments = Backbone.Collection.extend({ /** * Model of the instances contained in this collection * @alias module:collections-comments.Comments#initialize */ model : Comment, /** * Localstorage container for the collection * @alias module:collections-comments.Comments#localStorage * @type {Backbone.LocalStorgage} */ localStorage: new Backbone.LocalStorage("Comments"), /** * constructor * @alias module:collections-comments.Comments#initialize */ initialize: function (models, annotation) { _.bindAll(this, "setUrl"); this.setUrl(annotation); }, /** * Parse the given data * @alias module:collections-comments.Comments#parse * @param {object} data Object or array containing the data to parse. * @return {object} the part of the given data related to the comments */ parse: function (resp) { if (resp.comments && _.isArray(resp.comments)) { return resp.comments; } else if (_.isArray(resp)) { return resp; } else { return null; } }, /** * Define the url from the collection with the given video * @alias module:collections-comments.Comments#setUrl * @param {@link module:models-track.Track} Annotation containing the comments */ setUrl: function (annotation) { if (!annotation) { throw "The parent annotation of the comments must be given!"; } else if (annotation.collection) { this.url = annotation.url() + "/comments"; } if (window.annotationsTool && annotationsTool.localStorage) { this.localStorage = new Backbone.LocalStorage(this.url); } } }); return Comments; } ); <file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing the user model * @module models-user * @requires jQuery * @requires ROLES * @requires ACCESS * @requires backbone */ define(["jquery", "roles", "access", "backbone"], function ($, ROLES, ACCESS, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Model} * @augments module:Backbone.Model * @memberOf module:models-user * @alias module:models-user.User */ var User = Backbone.Model.extend({ /** * Default models value * @alias module:models-scalevalue.Scalevalue#defaults * @type {map} * @static */ defaults: { role: ROLES.USER, access: ACCESS.PUBLIC }, /** * Constructor * @alias module:models-user.User#initialize * @param {Object} attr Object literal containing the model initialion attributes. */ initialize: function (attr) { if (_.isUndefined(attr.user_extid) || attr.user_extid === "" || _.isUndefined(attr.nickname) || attr.nickname === "") { throw "'user_extid' and 'nickanme' attributes are required"; } // Check if the category has been initialized if (!attr.id) { // If local storage, we set the cid as id if (window.annotationsTool.localStorage) { attr.id = attr.user_extid; } this.toCreate = true; } if (!attr.role && annotationsTool.getUserRole) { attr.role = annotationsTool.getUserRole(); if (!attr.role) { delete attr.role; } } this.set(attr); // Define that all post operation have to been done through PUT method // see in wiki this.noPOST = true; }, /** * Parse the attribute list passed to the model * @alias module:models-user.User#parse * @param {Object} data Object literal containing the model attribute to parse. * @return {Object} The object literal with the list of parsed model attribute. */ parse: function (data) { var attr = data.attributes ? data.attributes : data; attr.created_at = attr.created_at !== null ? Date.parse(attr.created_at): null; attr.updated_at = attr.updated_at !== null ? Date.parse(attr.updated_at): null; attr.deleted_at = attr.deleted_at !== null ? Date.parse(attr.deleted_at): null; if (data.attributes) { data.attributes = attr; } else { data = attr; } return data; }, /** * Validate the attribute list passed to the model * @alias module:models-user.User#validate * @param {Object} data Object literal containing the model attribute to validate. * @return {string} If the validation failed, an error message will be returned. */ validate: function (attr) { var tmpCreated; if (attr.id) { if (this.get("id") !== attr.id) { this.id = attr.id; } } if (_.isUndefined(attr.user_extid) || (!_.isString(attr.user_extid) && !_.isNumber(attr.user_extid))) { return {attribute: "user_extid", message: "'user_extid' must be a valid string or number."}; } if (_.isUndefined(attr.nickname) || !_.isString(attr.nickname)) { return {attribute: "nickname", message: "'nickanme' must be a valid string!"}; } if (attr.email && !User.validateEmail(attr.email)) { return {attribute: "email", message: "Given email is not valid!"}; } if (attr.created_by && !(_.isNumber(attr.created_by) || attr.created_by instanceof User)) { return "'created_by' attribute must be a number or an instance of 'User'"; } if (attr.updated_by && !(_.isNumber(attr.updated_by) || attr.updated_by instanceof User)) { return "'updated_by' attribute must be a number or an instance of 'User'"; } if (attr.deleted_by && !(_.isNumber(attr.deleted_by) || attr.deleted_by instanceof User)) { return "'deleted_by' attribute must be a number or an instance of 'User'"; } if (attr.created_at) { if ((tmpCreated = this.get("created_at")) && tmpCreated !== attr.created_at) { return "'created_at' attribute can not be modified after initialization!"; } else if (!_.isNumber(attr.created_at)) { return "'created_at' attribute must be a number!"; } } if (attr.updated_at) { if (!_.isNumber(attr.updated_at)) { return "'updated_at' attribute must be a number!"; } } if (attr.deleted_at) { if (!_.isNumber(attr.deleted_at)) { return "'deleted_at' attribute must be a number!"; } } } }, // Class properties and functions { /** * Check if the email address has a valid structure * @static * @alias module:models-user.User.validateEmail * @param {String} email the email address to check * @return {Boolean} true if the address is valid */ /*jshint -W101 */ validateEmail: function (email) { var re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; return re.test(email); } /*jshint +W101 */ } ); return User; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing the view for a comments container * @module views-comment * @requires jQuery * @requires underscore * @requires templates/comment.tmpl * @requires templates/edit-comment.tmpl * @requires handlebars * @requires backbone */ define(["jquery", "underscore", "templates/comment", "templates/edit-comment", "handlebars", "backbone"], function ($, _, Template, EditTemplate, Handlebars, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#View} * @augments module:Backbone.View * @memberOf module:views-comment * @alias module:views-comment.Comment */ var CommentView = Backbone.View.extend({ /** * Tag name from the view element * @alias module:views-comment.Comment#tagName * @type {string} */ tagName: "div", /** * View template for read-only modus * @alias module:views-comment.Comment#template * @type {HandlebarsTemplate} */ template: Template, /** * View template for edit modus * @alias module:views-comment.Comment#template * @type {HandlebarsTemplate} */ editTemplate: EditTemplate, /** * Events to handle * @alias module:views-comment.Comment#events * @type {object} */ events: { "click" : "stopPropagation", "click i.delete-comment" : "onDeleteComment", "dblclick span.comment" : "onEditComment", "click i.edit-comment" : "onEditComment", "keyup textarea" : "keyupInsertProxy", "click button[type=submit]" : "onSubmit", "click button[type=button]" : "onCancel" }, /** * constructor * @alias module:views-comment.Comment#initialize * @param {PlainObject} attr Object literal containing the view initialization attributes. */ initialize: function (attr) { this.model = attr.model; this.commentId = attr.model.get("id"); this.id = "comment" + this.commentId; this.el.id = this.id; this.cancelCallback = attr.cancel; this.editCallback = attr.edit; // Bind function to the good context _.bindAll(this, "cancel", "deleteView", "onDeleteComment", "onEditComment", "onSubmit", "onCancel", "stopPropagation", "render"); // Type use for delete operation this.typeForDelete = annotationsTool.deleteOperation.targetTypes.COMMENT; return this; }, /** * Stop the propagation of the given event * @alias module:views-comment.Comment#stopPropagation * @param {event} event Event object */ stopPropagation: function (event) { event.stopImmediatePropagation(); }, /** * Delete only this comment * @alias module:views-comment.Comment#deleteView */ deleteView: function () { this.remove(); this.undelegateEvents(); this.deleted = true; }, /** * Delete the comment related to this view * @alias module:views-comment.Comment#onDeleteComment */ onDeleteComment: function (event) { if (!_.isUndefined(event)) { event.stopImmediatePropagation(); } annotationsTool.deleteOperation.start(this.model, this.typeForDelete); }, /** * Switch in edit modus * @alias module:views-comment.Comment#onEditComment */ onEditComment: function (event) { if (!_.isUndefined(event)) { event.stopImmediatePropagation(); } this.editCallback(); this.$el.html(this.editTemplate({text: this.model.get("text")})); this.delegateEvents(this.events); this.isEditEnable = true; }, /** * Submit the modifications on the comment * @alias module:views-comment.Comment#onSubmit */ onSubmit: function (event) { if (!_.isUndefined(event)) { event.stopImmediatePropagation(); } var textValue = this.$el.find("textarea").val(); if (textValue === "") { return; } this.model.set({ "text" : textValue, "updated_at" : new Date() }); this.model.save(); this.cancel(); }, /** * Proxy to insert comments by pressing the "return" key * @alias module:views-comments-container.Comment#keyupInsertProxy * @param {event} event Event object */ keyupInsertProxy: function (event) { // If enter is pressed and shit not, we insert a new annotation if (event.keyCode === 13 && !event.shiftKey) { this.onSubmit(); } }, /** * Listener for the click on the cancel button * @alias module:views-comment.Comment#onCancel */ onCancel: function (event) { event.stopImmediatePropagation(); this.cancel(); }, /** * Cancel the modifications * @alias module:views-comment.Comment#cancel */ cancel: function () { this.isEditEnable = false; this.render(); if (!_.isUndefined(this.cancelCallback)) { this.cancelCallback(); } }, /** * Render this view * @alias module:views-comment.Comment#render */ render: function () { var modelJSON = this.model.toJSON(), data = { creator : modelJSON.created_by_nickname, creationdate: new Date(modelJSON.created_at), text : _.escape(modelJSON.text).replace(/\n/g, "<br/>"), canEdit : annotationsTool.user.get("id") === modelJSON.created_by }; if (!_.isUndefined(modelJSON.updated_at) && modelJSON.created_at !== modelJSON.updated_at) { data.updator = modelJSON.updated_by_nickname; data.updateddate = new Date(modelJSON.updated_at); } this.$el.html(this.template(data)); this.delegateEvents(this.events); return this; } }); return CommentView; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * Module containing the tool main object * @module annotations-tool * @requires jQuery * @requires backbone * @requires views-main * @requires views-alert * @requires templates/delete-modal.tmpl * @requires templates/delete-warning-content.tmpl * @requires player-adapter * @requires handlebars */ define(["jquery", "backbone", "backbone-annotations-sync", "collections/videos", "views/main", "views/alert", "templates/delete-modal", "templates/delete-warning-content", "prototypes/player_adapter", "handlebarsHelpers", "FiltersManager", "roles", "colors"], function ($, Backbone, AnnotationSync, Videos, MainView, AlertView, DeleteModalTmpl, DeleteContentTmpl, PlayerAdapter, Handlebars, FiltersManager, ROLES, ColorsManager) { "use strict"; /** * The main object of the annotations tool * @namespace annotationsTool */ window.annotationsTool = _.extend({ EVENTS: { ANNOTATION_SELECTION : "at:annotation-selection", ANNOTATE_TOGGLE_EDIT : "at:annotate-switch-edit-modus", MODELS_INITIALIZED : "at:models-initialized", NOTIFICATION : "at:notification", READY : "at:ready", TIMEUPDATE : "at:timeupdate", USER_LOGGED : "at:logged" }, timeupdateIntervals: [], views: {}, modelsInitialized: false, deleteModalTmpl: DeleteModalTmpl, deleteContentTmpl: DeleteContentTmpl, deleteOperation: { /** * Function to delete element with warning * * @param {Object} target Element to be delete * @param {TargetsType} type Type of the target to be deleted */ start: function (target, type, callback) { var confirm = function () { type.destroy(target, callback); this.deleteModal.modal("toggle"); }, confirmWithEnter = function (event) { if (event.keyCode === 13) { confirm(); } }; if (!target.get("isMine") && this.getUserRole() !== ROLES.ADMINISTRATOR) { this.alertWarning("You are not authorized to deleted this " + type.name + "!"); return; } confirmWithEnter = _.bind(confirmWithEnter, this); confirm = _.bind(confirm, this); // Change modal title this.deleteModalHeader.text("Delete " + type.name); // Change warning content this.deleteModalContent.html(this.deleteContentTmpl({ type: type.name, content: type.getContent(target) })); // Listener for delete confirmation this.deleteModal.find("#confirm-delete").one("click", confirm); // Add possiblity to confirm with return key $(window).bind("keypress", confirmWithEnter); // Unbind the listeners when the modal is hidden this.deleteModal.one("hide", function () { $("#confirm-delete").unbind("click"); $(window).unbind("keypress", confirmWithEnter); }); // Show the modal this.deleteModal.modal("show"); } }, alertModal: new AlertView(), /** * Initialize the tool * @alias annotationsTool.start * @param {module:annotations-tool-configuration.Configuration} config The tool configuration */ start: function (config) { _.bindAll(this, "updateSelectionOnTimeUpdate", "createTrack", "createAnnotation", "getAnnotation", "getSelection", "getTrack", "getTracks", "getSelectedTrack", "fetchData", "importTracks", "importCategories", "hasSelection", "onClickSelectionById", "onDestroyRemoveSelection", "onMouseDown", "onMouseUp", "onTimeUpdate", "selectTrack", "setSelection", "setSelectionById", "addTimeupdateListener", "removeTimeupdateListener", "updateSelectionOnTimeUpdate"); _.extend(this, config); if (this.loadVideo) { this.loadVideo(); } if ((this.isBrowserIE9() && !(this.playerAdapter.__proto__ instanceof this.PlayerAdapter)) || (!this.isBrowserIE9() && !(this.playerAdapter instanceof PlayerAdapter))) { throw "The player adapter is not valid! It must has PlayerAdapter as prototype."; } // Load the good storage module Backbone.sync = this.localStorage ? Backbone.localSync : AnnotationSync; this.deleteOperation.start = _.bind(this.deleteOperation.start, this); this.initDeleteModal(); this.addTimeupdateListener(this.updateSelectionOnTimeUpdate, 900); this.currentSelection = []; this.once(this.EVENTS.USER_LOGGED, this.fetchData); this.once(this.EVENTS.MODELS_INITIALIZED, function () { var trackImported = false; if (!_.isUndefined(this.tracksToImport)) { if (this.playerAdapter.getStatus() === PlayerAdapter.STATUS.PAUSED) { this.importTracks(this.tracksToImport()); trackImported = true; } else { $(this.playerAdapter).one(PlayerAdapter.EVENTS.READY + " " + PlayerAdapter.EVENTS.PAUSE, function () { if (trackImported) { return false; } annotationsTool.importTracks(annotationsTool.tracksToImport()); trackImported = true; }); } } }, this); this.colorsManager = new ColorsManager(); this.filtersManager = new FiltersManager(); this.tracksFiltersManager = new FiltersManager(); this.views.main = new MainView(this.playerAdapter); $(this.playerAdapter).bind("pa_timeupdate", this.onTimeUpdate); $(window).bind("mousedown", this.onMouseDown); $(window).bind("mouseup", this.onMouseUp); return this; }, /** * Display an alert modal * @alias annotationsTool.alertError * @param {String} message The message to display */ alertError: function (message) { this.alertModal.show(message, this.alertModal.TYPES.ERROR); }, /** * Display an warning modal * @alias annotationsTool.alertWarning * @param {String} message The message to display */ alertWarning: function (message) { this.alertModal.show(message, this.alertModal.TYPES.WARNING); }, /** * Display an information modal * @alias annotationsTool.alertInfo * @param {String} message The message to display */ alertInfo: function (message) { this.alertModal.show(message, this.alertModal.TYPES.INFO); }, /** * Function to init the delete warning modal * @alias annotationsTool.initDeleteModal */ initDeleteModal: function () { $("#dialogs").append(this.deleteModalTmpl({type: "annotation"})); this.deleteModal = $("#modal-delete").modal({show: true, backdrop: false, keyboard: true }); this.deleteModal.modal("toggle"); this.deleteModalHeader = this.deleteModal.find(".modal-header h3"); this.deleteModalContent = this.deleteModal.find(".modal-body"); }, /** * Transform time in seconds (i.e. 12.344) into a well formated time (01:12:04) * @alias annotationsTool.getWellFormatedTime * @param {number} time the time in seconds * @param {boolean} [noRounted] Define if the number should be rounded or if the decimal should be simply removed. Default is rounding (false). */ getWellFormatedTime: function (time, noRounding) { var twoDigit = function (number) { return (number < 10 ? "0" : "") + number; }, base = (_.isUndefined(noRounding) || !noRounding) ? Math.round(time) : Math.floor(time), seconds = base % 60, minutes = ((base - seconds) / 60) % 60, hours = (base - seconds - minutes * 60) / 3600; return twoDigit(hours) + ":" + twoDigit(minutes) + ":" + twoDigit(seconds); }, /** * Check if the current browser is Safari 6 * @alias annotationsTool.isBrowserSafari6 * @return {boolean} true if the browser is safari 6, otherwise false */ isBrowserSafari6: function () { return (navigator.appVersion.search("Version/6") > 0 && navigator.appVersion.search("Safari") > 0); }, /** * Check if the current browser is Microsoft Internet Explorer 9 * @alias annotationsTool.isBrowserIE9 * @return {boolean} true if the browser is IE9, otherwise false */ isBrowserIE9: function () { return (navigator.appVersion.search("MSIE 9") > 0); }, /** * Listener for mouse down event to get infos about the click * @alias annotationsTool.onMouseDown */ onMouseDown: function () { this.timeMouseDown = undefined; this.startMouseDown = new Date(); this.isMouseDown = true; }, /** * Listener for mouse up event to get infos about the click * @alias annotationsTool.onMouseUp */ onMouseUp: function () { this.timeMouseDown = new Date() - this.startMouseDown; this.startMouseDown = undefined; this.isMouseDown = false; }, /** * Listen and retrigger timeupdate event from player adapter events with added intervals * @alias annotationsTool.onTimeUpdate */ onTimeUpdate: function () { var currentPlayerTime = this.playerAdapter.getCurrentTime(), currentTime = new Date().getTime(), value, i; // Ensure that this is an timeupdate due to normal playback, otherwise trigger timeupdate event for all intervals if ((_.isUndefined(this.lastTimeUpdate)) || (this.playerAdapter.getStatus() !== PlayerAdapter.STATUS.PLAYING) || (currentTime - this.lastTimeUpdate > 1000)) { // Ensure that the timestamp from the last update is set if (_.isUndefined(this.lastTimeUpdate)) { this.lastTimeUpdate = 1; } for (i = 0; i < this.timeupdateIntervals.length; i++) { value = this.timeupdateIntervals[i]; this.trigger(this.EVENTS.TIMEUPDATE + ":" + value.interval, currentPlayerTime); this.timeupdateIntervals[i].lastUpdate = currentTime; } } else { // Trigger all the current events this.trigger(this.EVENTS.TIMEUPDATE + ":all", currentPlayerTime); for (i = 0; i < this.timeupdateIntervals.length; i++) { value = this.timeupdateIntervals[i]; if ((currentTime - value.lastUpdate) > parseInt(value.interval, 10)) { this.trigger(this.EVENTS.TIMEUPDATE + ":" + value.interval, currentPlayerTime); this.timeupdateIntervals[i].lastUpdate = currentTime; } } } this.lastTimeUpdate = new Date().getTime(); }, /** * Add a timeupdate listener with the given interval * @alias annotationsTool.addTimeupdateListener * @param {Object} callback the listener callback * @param {Number} (interval) the interval between each timeupdate event */ addTimeupdateListener: function (callback, interval) { var timeupdateEvent = annotationsTool.EVENTS.TIMEUPDATE, value, i = 0; if (!_.isUndefined(interval)) { timeupdateEvent += ":" + interval; //this.listenTo(annotationsTool, annotationsTool.EVENTS.TIMEUPDATE, callback); // Check if the interval needs to be added to list for (i = 0; i < annotationsTool.timeupdateIntervals.length; i++) { value = annotationsTool.timeupdateIntervals[i]; if (value.interval === interval) { return; } } // Add interval to list annotationsTool.timeupdateIntervals.push({ interval: interval, lastUpdate: 0 }); } this.listenTo(annotationsTool, timeupdateEvent, callback); }, /** * Remove the given timepudate listener * @alias annotationsTool.removeTimeupdateListener * @param {Object} callback the listener callback * @param {Number} (interval) the interval between each timeupdate event */ removeTimeupdateListener: function (callback, interval) { var timeupdateEvent = annotationsTool.EVENTS.TIMEUPDATE; if (!_.isUndefined(interval)) { timeupdateEvent += ":" + interval; } this.stopListening(annotationsTool, timeupdateEvent, callback); }, /////////////////////////////////////////////// // Function related to annotation selection // /////////////////////////////////////////////// /** * Proxy to select annotation by Id on mouse click * @alias annotationsTool.onClickSelectionById * @param {Array} selection The new selection. This is an array of object containing the id of the annotation and optionnaly the track id. See example below. * @example * { * id: "a123", // The id of the annotations * trackId: "b23", // The track id (optional) * } * @param {Boolean} moveTo define if the video should be move to the start point of the selection * @param {Boolean} isManuallySelected define if the selection has been done manually or through a video timeupdate */ onClickSelectionById: function (selectedIds, moveTo, isManuallySelected) { if (!this.isMouseDown && this.timeMouseDown < 300) { this.setSelectionById(selectedIds, moveTo, isManuallySelected); } }, /** * Listener for destroy event on selected annotation to update the selection * @alias annotationsTool.onDestroyRemoveSelection * @param {Object} annotation The destroyed annotation */ onDestroyRemoveSelection: function (annotation) { var currentSelection = this.currentSelection, item, i; for (i = 0; i < currentSelection.length; i++) { item = currentSelection[i]; if (item.get("id") == annotation.get("id")) { currentSelection.splice(i, 1); this.trigger(this.EVENTS.ANNOTATION_SELECTION, currentSelection); return; } } }, /** * Set the given annotation(s) as current selection * @alias annotationsTool.setSelectionById * @param {Array} selection The new selection. This is an array of object containing the id of the annotation and optionnaly the track id. See example below. * @example * { * id: "a123", // The id of the annotations * trackId: "b23", // The track id (optional) * } * @param {Boolean} moveTo define if the video should be move to the start point of the selection * @param {Boolean} isManuallySelected define if the selection has been done manually or through a video timeupdate */ setSelectionById: function (selectedIds, moveTo, isManuallySelected) { var selectionAsArray = [], tmpAnnotation; if (_.isArray(selectedIds) && selectedIds.length > 0) { _.each(selectedIds, function (selection) { tmpAnnotation = this.getAnnotation(selection.id, selection.trackId); if (!_.isUndefined(tmpAnnotation)) { selectionAsArray.push(tmpAnnotation); } }, this); } else { console.warn("Invalid selection: " + selectedIds); } this.setSelection(selectionAsArray, moveTo, isManuallySelected); }, /** * Set the given annotation(s) as current selection * @alias annotationsTool.setSelection * @param {Array} selection The new selection * @param {Boolean} moveTo define if the video should be move to the start point of the selection * @param {Boolean} isManuallySelected define if the selection has been done manually or through a video timeupdate */ setSelection: function (selection, moveTo, isManuallySelected) { var currentSelection = this.currentSelection, isEqual = function (newSelection) { var equal = true, annotation, findAnnotation = function (newAnnotation) { return newAnnotation.get("id") === annotation.get("id"); }, i; if (currentSelection.length !== newSelection.length) { return false; } for (i = 0; i < currentSelection.length; i++) { annotation = currentSelection[i]; if (!_.find(newSelection, findAnnotation)) { equal = false; return equal; } } return equal; }, item, i; this.isManuallySelected = isManuallySelected; if (_.isArray(selection) && selection.length > 0) { if (isEqual(selection)) { if (isManuallySelected) { // If the selection is the same, we unselect it if this is a manual selection // Remove listener for destroy event (unselect); for (i = 0; i < currentSelection.length; i++) { item = currentSelection[i]; this.stopListening(item, "destroy", this.onDestroyRemoveSelection); } currentSelection = []; this.isManuallySelected = false; } else { // If the selection is not done manually we don't need to reselect it return; } } else { // else we set the new selection currentSelection = selection; } } else { // If there is already no selection, no more work to do if (!this.hasSelection()) { return; } currentSelection = []; } // Add listener for destroy event (unselect); for (i = 0; i < currentSelection.length; i++) { item = currentSelection[i]; this.listenTo(item, "destroy", this.onDestroyRemoveSelection); } this.currentSelection = currentSelection; // if the selection is not empty, we move the playhead to it if (currentSelection.length > 0 && moveTo) { this.playerAdapter.setCurrentTime(selection[0].get("start")); } // Trigger the selection event this.trigger(this.EVENTS.ANNOTATION_SELECTION, currentSelection); }, /** * Returns the current selection of the tool * @alias annotationsTool.getSelection * @return {Annotation} The current selection or undefined if no selection. */ getSelection: function () { return this.currentSelection; }, /** * Informs if there is or not some items selected * @alias annotationsTool.hasSelection * @return {Boolean} true if an annotation is selected or false. */ hasSelection: function () { return (typeof this.currentSelection !== "undefined" && (_.isArray(this.currentSelection) && this.currentSelection.length > 0)); }, /** * Listener for player "timeupdate" event to highlight the current annotations * @alias annotationsTool.updateSelectionOnTimeUpdate */ updateSelectionOnTimeUpdate: function () { var currentTime = this.playerAdapter.getCurrentTime(), selection = [], annotations = [], annotation, start, duration, end, i; if (typeof this.video === "undefined" || (this.isManuallySelected && this.hasSelection())) { return; } this.video.get("tracks").each(function (track) { annotations = annotations.concat(track.get("annotations").models); }, this); for (i = 0; i < annotations.length; i++) { annotation = annotations[i]; start = annotation.get("start"); duration = annotation.get("duration"); end = start + (duration < this.MINIMAL_DURATION ? this.MINIMAL_DURATION : duration); if (_.isNumber(duration) && start <= currentTime && end >= currentTime) { selection.push(annotation); } } this.setSelection(selection, false); }, ////////////// // CREATORs // ////////////// /** * Create a new track * @alias annotationsTool.createTrack * @param {Object} parameters The content of the new track * @param {Object} (options) The options for the Backone.js options for the model creation * @return {Object} The created track */ createTrack: function (parameters, options) { var defaultOptions = { wait: true }; // TODO define default options for all tracks return this.video.get("tracks").create(parameters, (_.isUndefined(options) ? defaultOptions : options)); }, /** * Create an annotation on the given track or on the selected Track if no one is given * @alias annotationsTool.createAnnotations * @param {Object} parameters The content of the new annotation * @param {Object} (track) The track on which the annotation should be created * @param {Object} (options) The options for the Backone.js options for the model creation * @return {Object} The created annotation */ createAnnotation: function (parameters, track, options) { var parentTrack = _.isUndefined(track) ? this.getSelectedTrack() : track, defaultOptions = {}; // TODO define default options for all annotations if (_.isUndefined(parentTrack)) { throw "Annotation with parameters '" + JSON.stringify(parameters) + "' can be created"; } return parentTrack.get("annotations").create(parameters, (_.isUndefined(options) ? defaultOptions : options)); }, ///////////// // GETTERs // ///////////// /** * Get the track with the given Id * @alias annotationsTool.getTrack * @param {String} id The track Id * @return {Object} The track object or undefined if not found */ getTrack: function (id) { if (_.isUndefined(this.video)) { console.warn("No video present in the annotations tool. Either the tool is not completely loaded or an error happend during video loading."); } else { return this.video.getTrack(id); } }, /** * Get all the tracks * @alias annotationsTool.getTracks * @return {Object} The list of the tracks */ getTracks: function () { if (_.isUndefined(this.video)) { console.warn("No video present in the annotations tool. Either the tool is not completely loaded or an error happend during video loading."); } else { return this.video.get("tracks"); } }, /** * Get the track with the given Id * @alias annotationsTool.getTrack * @param {String} id The track Id * @return {Object} The track object or undefined if not found */ getSelectedTrack: function () { return this.selectedTrack; }, /** * Select the given track * @alias annotationsTool.selectTrack * @param {Object} track the track to select */ selectTrack: function (track) { this.selectedTrack = track; this.video.get("tracks").trigger("selected_track", track); }, /** * Get the annotation with the given Id * @alias annotationsTool.getAnnotation * @param {String} annotationId The annotation * @param {String} (trackId) The track Id (Optional) * @return {Object} The annotation object or undefined if not found */ getAnnotation: function (annotationId, trackId) { var track, tmpAnnotation; if (!_.isUndefined(trackId)) { // If the track id is given, we only search for the annotation on it track = this.getTrack(trackId); if (_.isUndefined(track)) { console.warn("Not able to find the track with the given Id"); return; } else { return track.getAnnotation(annotationId); } } else { // If no trackId present, we search through all tracks if (_.isUndefined(this.video)) { console.warn("No video present in the annotations tool. Either the tool is not completely loaded or an error happend during video loading."); return; } else { this.video.get("tracks").each(function (trackItem) { tmpAnnotation = trackItem.getAnnotation(annotationId); if (!_.isUndefined(tmpAnnotation)) { return tmpAnnotation; } }, this); return tmpAnnotation; } } }, /** * Get an array containning all the annotations or only the ones from the given track * @alias annotationsTool.getAnnotations * @param {String} (trackId) The track Id (Optional) * @return {Array} The annotations */ getAnnotations: function (trackId) { var track, tracks, annotations = []; if (_.isUndefined(this.video)) { console.warn("No video present in the annotations tool. Either the tool is not completely loaded or an error happend during video loading."); } else { if (!_.isUndefined(trackId)) { track = this.getTrack(trackId); if (!_.isUndefined(track)) { annotations = track.get("annotations").toArray(); } } else { tracks = this.video.get("tracks"); tracks.each(function (t) { annotations = _.union(annotations, t.get("annotations").toArray()); }, this); } } return annotations; }, //////////////// // IMPORTERs // //////////////// /** * Import the given tracks in the tool * @alias annotationsTool.importTracks * @param {PlainObject} tracks Object containing the tracks in the tool */ importTracks: function (tracks) { _.each(tracks, function (track) { this.trigger(this.EVENTS.NOTIFICATION, "Importing track " + track.name); if (_.isUndefined(this.getTrack(track.id))) { this.createTrack(track); } else { console.info("Can not import track %s: A track with this ID already exist.", track.id); } }, this); }, /** * Import the given categories in the tool * @alias annotationsTool.importCategories * @param {PlainObject} imported Object containing the .categories and .scales to insert in the tool * @param {PlainObject} defaultCategoryAttributes The default attributes to use to insert the imported categories (like access) */ importCategories: function (imported, defaultCategoryAttributes) { var videoCategories = annotationsTool.video.get("categories"), videoScales = annotationsTool.video.get("scales"), labelsToAdd, newCat, newScale, scaleValuesToAdd, scaleOldId, scalesIdMap = {}; if (!imported.categories || imported.categories.length === 0) { return; } _.each(imported.scales, function (scale) { scaleOldId = scale.id; scaleValuesToAdd = scale.scaleValues; delete scale.id; delete scale.scaleValues; newScale = videoScales.create(scale, {async: false}); scalesIdMap[scaleOldId] = newScale.get("id"); if (scaleValuesToAdd) { _.each(scaleValuesToAdd, function (scaleValue) { scaleValue.scale = newScale; newScale.get("scaleValues").create(scaleValue); }); } }); _.each(imported.categories, function (category) { labelsToAdd = category.labels; category.scale_id = scalesIdMap[category.scale_id]; delete category.labels; newCat = videoCategories.create(_.extend(category, defaultCategoryAttributes)); if (labelsToAdd) { _.each(labelsToAdd, function (label) { label.category = newCat; newCat.get("labels").create(label); }); } }); }, ////////////// // DELETERs // ////////////// /** * Delete the annotation with the given id with the track with the given track id * @alias annotationsTool.deleteAnnotation * @param {Integer} annotationId The id of the annotation to delete * @param {Integer} trackId Id of the track containing the annotation */ deleteAnnotation: function (annotationId, trackId) { var annotation, self = annotationsTool; if (typeof trackId === "undefined") { annotationsTool.video.get("tracks").each(function (track) { if (track.get("annotations").get(annotationId)) { trackId = track.get("id"); } }); } annotation = self.video.getAnnotation(annotationId, trackId); if (annotation) { self.deleteOperation.start(annotation, self.deleteOperation.targetTypes.ANNOTATION); } else { console.warn("Not able to find annotation %i on track %i", annotationId, trackId); } }, /** * Get all the annotations for the current user * @alias annotationsTool.fetchData */ fetchData: function () { var video, videos = new Videos(), tracks, self = this, selectedTrack, // function to conclude the retrieve of annotations concludeInitialization = $.proxy(function () { // At least one private track should exist, we select the first one selectedTrack = tracks.getMine()[0]; if (!selectedTrack.get("id")) { selectedTrack.bind("ready", concludeInitialization(), this); } else { annotationsTool.selectedTrack = selectedTrack; } annotationsTool.modelsInitialized = true; annotationsTool.trigger(annotationsTool.EVENTS.MODELS_INITIALIZED); }, this), /** * Create a default track for the current user if no private track is present */ createDefaultTrack = function () { tracks = annotationsTool.video.get("tracks"); if (annotationsTool.localStorage) { tracks = tracks.getTracksForLocalStorage(); } if (tracks.getMine().length === 0) { tracks.create({ name : "Default " + annotationsTool.user.get("nickname"), description : "Default track for user " + annotationsTool.user.get("nickname") }, { wait : true, success : concludeInitialization } ); } else { tracks.showTracks(_.first(tracks.filter(annotationsTool.getDefaultTracks().filter), annotationsTool.MAX_VISIBLE_TRACKS || Number.MAX_VALUE)); concludeInitialization(); } }; // If we are using the localstorage if (this.localStorage) { videos.fetch({ success: function () { if (videos.length === 0) { video = videos.create(self.getVideoParameters(), {wait: true}); } else { video = videos.at(0); video.set(self.getVideoParameters()); } self.video = video; } }); createDefaultTrack(); } else { // With Rest storage videos.add({video_extid: this.getVideoExtId()}); video = videos.at(0); this.video = video; video.save(); if (video.get("ready")) { createDefaultTrack(); } else { video.once("ready", createDefaultTrack); } } } }, _.clone(Backbone.Events)); /** * Type of target that can be deleted using the delete warning modal * * Each type object must contain these elements * * { * name: "Name of the type", // String * getContent: function(target){ // Function * return "Content of the target element" * }, * destroy: function(target){ // Function * // Delete the target * } * } */ annotationsTool.deleteOperation.targetTypes = { ANNOTATION: { name: "annotation", getContent: function (target) { return target.get("text"); }, destroy: function (target, callback) { target.destroy({ success: function () { if (annotationsTool.localStorage) { annotationsTool.video.get("tracks").each(function (value) { if (value.get("annotations").get(target.id)) { value.get("annotations").remove(target); value.save({wait: true}); return false; } }); annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete annotation: " + error); } }); } }, COMMENT: { name: "comment", getContent: function (target) { return target.get("text"); }, destroy: function (target, callback) { target.destroy({ success: function () { if (annotationsTool.localStorage) { if (target.collection) { target.collection.remove(target); } annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete comment: " + error); } }); } }, LABEL: { name: "label", getContent: function (target) { return target.get("value"); }, destroy: function (target, callback) { target.destroy({ success: function () { if (annotationsTool.localStorage) { if (target.collection) { target.collection.remove(target); } annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete label: " + error); } }); } }, TRACK: { name: "track", getContent: function (target) { return target.get("name"); }, destroy: function (track, callback) { var annotations = track.get("annotations"), /** * Recursive function to delete synchronously all annotations */ destroyAnnotation = function () { var annotation; // End state, no more annotation if (annotations.length === 0) { return; } annotation = annotations.at(0); annotation.destroy({ error: function () { throw "Cannot delete annotation!"; }, success: function () { annotations.remove(annotation); destroyAnnotation(); } }); }; // Call the recursive function destroyAnnotation(); track.destroy({ success: function () { if (annotationsTool.localStorage) { annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete track: " + error); } }); } }, CATEGORY: { name: "category", getContent: function (target) { return target.get("name"); }, destroy: function (category, callback) { var labels = category.get("labels"), /** * Recursive function to delete synchronously all labels */ destroyLabels = function () { var label; // End state, no more label if (labels.length === 0) { return; } label = labels.at(0); label.destroy({ error: function () { throw "Cannot delete label!"; }, success: function () { labels.remove(label); destroyLabels(); } }); }; // Call the recursive function destroyLabels(); category.destroy({ success: function () { if (annotationsTool.localStorage) { annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete category: " + error); } }); } }, SCALEVALUE: { name: "scale value", getContent: function (target) { return target.get("name"); }, destroy: function (target, callback) { target.destroy({ success: function () { if (window.annotationsTool.localStorage) { if (target.collection) { target.collection.remove(target); } annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete scale value: " + error); } }); } }, SCALE: { name: "scale", getContent: function (target) { return target.get("name"); }, destroy: function (scale, callback) { var scaleValues = scale.get("scaleValues"), /** * Recursive function to delete synchronously all scaleValues */ destroyScaleValues = function () { var scaleValue; // End state, no more label if (scaleValues.length === 0) { return; } scaleValue = scaleValues.at(0); scaleValue.destroy({ error: function () { throw "Cannot delete scaleValue!"; }, success: function () { scaleValues.remove(scaleValue); destroyScaleValues(); } }); }; // Call the recursive function destroyScaleValues(); scale.destroy({ success: function () { if (window.annotationsTool.localStorage) { annotationsTool.video.save(); } if (callback) { callback(); } }, error: function (error) { console.warn("Cannot delete scale: " + error); } }); } } }; return annotationsTool; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * A module representing a scales collection * @module collections-scales * @requires jQuery * @requires models-scale * @requires backbone * @requires localstorage */ define(["jquery", "models/scale", "backbone", "localstorage"], function ($, Scale, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Collection} * @augments module:Backbone.Collection * @memberOf module:collections-scales * @alias module:collections-scales.Scales */ var Scales = Backbone.Collection.extend({ /** * Model of the instances contained in this collection * @alias module:collections-scales.Scales#initialize */ model: Scale, /** * Localstorage container for the collection * @alias module:collections-scales.Scales#localStorage * @type {Backbone.LocalStorgage} */ localStorage: new Backbone.LocalStorage("Scales"), /** * constructor * @alias module:collections-scales.Scales#initialize */ initialize: function (models, video) { _.bindAll(this, "setUrl", "addCopyFromTemplate", "toExportJSON"); this.setUrl(video); }, /** * Parse the given data * @alias module:collections-scales.Scales#parse * @param {object} data Object or array containing the data to parse. * @return {object} the part of the given data related to the scales */ parse: function (data) { if (data.scales && _.isArray(data.scales)) { return data.scales; } else if (_.isArray(data)) { return data; } else { return null; } }, /** * Define the url from the collection with the given video * @alias module:collections-scales.Scales#setUrl * @param {Video} Video containing the scales */ setUrl: function (video) { if (!video || !video.collection) { // If a template this.url = window.annotationsTool.restEndpointsUrl + "/scales"; this.isTemplate = true; } else { // If not a template, we add video url this.url = video.url() + "/scales"; this.isTemplate = false; if (annotationsTool.localStorage) { this.localStorage = new Backbone.LocalStorage(this.url); } } this.each(function (scale) { scale.setUrl(); }); }, /** * Get the collection as array with the model in JSON, ready to be exported * @alias module:collections-scales.Scales#toExportJSON * @return {array} Array of json models */ toExportJSON: function () { var scalesForExport = []; this.each(function (scale) { scalesForExport.push(scale.toExportJSON()); }); return scalesForExport; }, /** * Add a copy from the given template to this collection * @alias module:collections-scales.Scales#addCopyFromTemplate * @param {Scale} element template to copy * @return {Scale} A copy of the given scale */ addCopyFromTemplate: function (element) { // Test if the given scale is really a template if (!this.isTemplate && !_.isArray(element) && element.id) { // Copy the element and remove useless parameters var copyJSON = element.toJSON(); delete copyJSON.id; delete copyJSON.created_at; delete copyJSON.created_by; delete copyJSON.updated_at; delete copyJSON.updated_by; delete copyJSON.deleted_by; delete copyJSON.deleted_at; delete copyJSON.labels; // add the copy url parameter for the backend copyJSON.copyUrl = "?scale_id=" + element.id; return this.create(copyJSON); } return null; } }); return Scales; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. * */ /** * Default categories set */ define([],function(){ return [ {name: "default", values: [ {name: "--", value: -2, order: 0}, {name: "-", value: -1, order: 1}, {name: "0", value: 0, order: 2}, {name: "+", value: 1, order: 3}, {name: "++", value: 2, order: 4}, ] } ]; });<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * A module representing the annotation model * @module models-annotation * @requires jQuery * @requires collections-comments * @requires ACCESS * @requires backbone * @requires localstorage */ define(["jquery", "collections/comments", "access", "backbone", "localstorage"], function ($, Comments, ACCESS, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Model} * @augments module:Backbone.Model * @memberOf module:models-annotation * @alias module:models-annotation.Annotation */ var Annotation = Backbone.Model.extend({ /** * Default models value * @alias module:models-annotation.Annotation#defaults * @type {map} * @static */ defaults: { start : 0, duration: 0 }, /** * Constructor * @alias module:models-annotation.Annotation#initialize * @param {object} attr Object literal containing the model initialion attributes. */ initialize: function (attr) { _.bindAll(this, "areCommentsLoaded", "fetchComments"); if (!attr || _.isUndefined(attr.start)) { throw "\"start\" attribute is required"; } // Check if the category has been initialized if (!attr.id) { // If local storage, we set the cid as id this.toCreate = true; } if (attr.comments && _.isArray(attr.comments)) { this.attributes.comments = new Comments(attr.comments, this); delete attr.comments; } else if (!attr.comments) { this.attributes.comments = new Comments([], this); } else { this.attributes.comments = attr.comments; delete attr.comments; } if (_.isUndefined(attr.access) && !_.isUndefined(attr.access)) { attr.access = this.collection.access; } // If localStorage used, we have to save the video at each change on the children if (window.annotationsTool.localStorage) { if (!attr.created_by) { attr.created_by = annotationsTool.user.get("id"); } if (!attr.created_by_nickname) { attr.created_by_nickname = annotationsTool.user.get("nickname"); } if (!attr.created_at) { attr.created_at = new Date(); } } if (annotationsTool.user.get("id") === attr.created_by) { attr.isMine = true; } else { attr.isMine = false; } if (attr.tags) { attr.tags = this.parseJSONString(attr.tags); } // Add backbone events to the model _.extend(this, Backbone.Events); this.set(attr); }, /** * Parse the attribute list passed to the model * @alias module:models-annotation.Annotation#parse * @param {object} data Object literal containing the model attribute to parse. * @return {object} The object literal with the list of parsed model attribute. */ parse: function (data) { var attr = data.attributes ? data.attributes : data, parseDate = function (date) { if (_.isNumber(date)) { return new Date(date); } else if (_.isString) { return Date.parse(date); } else { return null; } }, tempSettings, categories, tempLabel, label; if (attr.created_at) { attr.created_at = parseDate(attr.created_at); } if (attr.updated_at) { attr.updated_at = parseDate(attr.updated_at); } if (attr.deleted_at) { attr.deleted_at = parseDate(attr.deleted_at); } // Parse tags if present if (attr.tags) { attr.tags = this.parseJSONString(attr.tags); } if (attr.scaleValue) { attr.scalevalue = attr.scaleValue; delete attr.scaleValue; } if (annotationsTool.user.get("id") === attr.created_by) { attr.isMine = true; } else { attr.isMine = false; } if (attr.label) { if (attr.label.category && (tempSettings = this.parseJSONString(attr.label.category.settings))) { attr.label.category.settings = tempSettings; } if ((tempSettings = this.parseJSONString(attr.label.settings))) { attr.label.settings = tempSettings; } } if (annotationsTool.localStorage && _.isArray(attr.comments)) { attr.comments = new Comments(attr.comments, this); } if (!annotationsTool.localStorage && attr.label_id && (_.isNumber(attr.label_id) || _.isString(attr.label_id))) { categories = annotationsTool.video.get("categories"); categories.each(function (cat) { if ((tempLabel = cat.attributes.labels.get(attr.label_id))) { label = tempLabel; return true; } }, this); attr.label = label; } if (!annotationsTool.localStorage && attr.scalevalue) { attr.scaleValue = attr.scalevalue; } if (data.attributes) { data.attributes = attr; } else { data = attr; } return data; }, /** * Validate the attribute list passed to the model * @alias module:models-annotation.Annotation#validate * @param {object} data Object literal containing the model attribute to validate. * @return {string} If the validation failed, an error message will be returned. */ validate: function (attr) { var tmpCreated; if (attr.id) { if (this.get("id") !== attr.id) { this.id = attr.id; this.attributes.id = attr.id; this.toCreate = false; this.trigger("ready", this); this.setUrl(); } } if (!annotationsTool.localStorage && attr.label) { if (attr.label.id) { this.attributes.label_id = attr.label.id; } else if (attr.label.attributes) { this.attributes.label_id = attr.label.get("id"); } } if (attr.start && !_.isNumber(attr.start)) { return "\"start\" attribute must be a number!"; } if (attr.tags && _.isUndefined(this.parseJSONString(attr.tags))) { return "\"tags\" attribute must be a string or a JSON object"; } if (attr.text && !_.isString(attr.text)) { return "\"text\" attribute must be a string!"; } if (attr.duration && (!_.isNumber(attr.duration) || (_.isNumber(attr.duration) && attr.duration < 0))) { return "\"duration\" attribute must be a positive number"; } if (attr.access && !_.include(ACCESS, attr.access)) { return "\"access\" attribute is not valid."; } if (attr.created_at) { if ((tmpCreated = this.get("created_at")) && tmpCreated !== attr.created_at) { return "\"created_at\" attribute can not be modified after initialization!"; } else if (!_.isNumber(attr.created_at) && !_.isDate(attr.created_at)) { return "\"created_at\" attribute must be a number!"; } } if (attr.updated_at && !_.isNumber(attr.updated_at)) { return "\"updated_at\" attribute must be a number!"; } if (attr.deleted_at && !_.isNumber(attr.deleted_at)) { return "\"deleted_at\" attribute must be a number!"; } }, /** * Returns if comments are or not loaded * @alias module:models-annotation.Annotation#areCommentsLoaded */ areCommentsLoaded: function () { return this.commentsFetched; }, /** * Load the list of comments from the server * @param {Function} [callback] Optional callback to call when comments are loaded * @alias module:models-annotation.Annotation#fetchComments */ fetchComments: function (callback) { var fetchCallback = _.bind(function () { this.commentsFetched = true; if (_.isFunction(callback)) { callback.apply(this); } }, this); if (this.areCommentsLoaded()) { fetchCallback(); } else { if (this.commentsFetched !== true) { if (_.isUndefined(this.attributes.id)) { this.once("ready", this.fetchComments); } else { this.attributes.comments.fetch({ async : true, success : fetchCallback }); } } } }, /** * Modify the current url for the annotations collection * @alias module:models-annotation.Annotation#setUrl */ setUrl: function () { if (this.get("comments")) { this.get("comments").setUrl(this); } }, /** * Parse the given parameter to JSON if given as string * @alias module:models-annotation.Annotation#parseJSONString * @param {string} parameter the parameter as string * @return {JSON} parameter as JSON object */ parseJSONString: function (parameter) { if (parameter && _.isString(parameter)) { try { parameter = JSON.parse(parameter); } catch (e) { console.warn("Can not parse parameter \"" + parameter + "\": " + e); return undefined; } } else if (!_.isObject(parameter) || _.isFunction(parameter)) { return undefined; } return parameter; }, /** * Override the default toJSON function to ensure complete JSONing. * @alias module:models-annotation.Annotation#toJSON * @return {JSON} JSON representation of the instance */ toJSON: function () { var json = $.proxy(Backbone.Model.prototype.toJSON, this)(); delete json.comments; if (json.tags) { json.tags = JSON.stringify(json.tags); } if (json.label && json.label.toJSON) { json.label = json.label.toJSON(); } if (json.scalevalue) { if (json.scalevalue.attributes) { json.scale_value_id = json.scalevalue.attributes.id; } else if (json.scalevalue.id) { json.scale_value_id = json.scalevalue.id; } } delete json.annotations; return json; } }); return Annotation; } );<file_sep>/** * Copyright 2012, Entwine GmbH, Switzerland * Licensed under the Educational Community License, Version 2.0 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.osedu.org/licenses/ECL-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an "AS IS" * BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing * permissions and limitations under the License. */ /** * A module representing the loop model * @module models-loop * @requires jQuery * @requires backbone * @requires localstorage */ define(["jquery", "backbone", "localstorage"], function ($, Backbone) { "use strict"; /** * @constructor * @see {@link http://www.backbonejs.org/#Model} * @augments module:Backbone.Model * @memberOf module:models-loop * @alias module:models-loop.Loop */ var Loop = Backbone.Model.extend({ TYPE: "Loop", /** * Constructor * @alias module:models-loop.Loop#initialize * @param {object} attr Object literal containing the model initialion attributes. */ initialize: function (attr) { // Add backbone events to the model _.extend(this, Backbone.Events); annotationsTool.localStorageOnlyModel.push(this.TYPE); this.set(attr); }, /** * Validate the attribute list passed to the model * @alias module:models-loop.Loop#validate * @param {object} data Object literal containing the model attribute to validate. * @return {string} If the validation failed, an error message will be returned. */ validate: function (attr) { if (_.isUndefined(attr.start) || _.isUndefined(attr.end)) { return "The attributes 'start' and 'end' are required for the loop model!"; } if (!_.isNumber(attr.start) || !_.isNumber(attr.end) || attr.start < 0 || attr.end < 0) { return "Start and end points must be valid number!"; } if (attr.start > attr.end) { return "The start point is after the end point!"; } }, }); return Loop; } );
ac308bd7a22dbdad8512d0605673faf060058bce
[ "JavaScript" ]
22
JavaScript
yubin1991/annotations
d4741e0aae1ba1514e8353827f7f72cb5bbd7a91
b460d3422904a93fdcceea2a9a040c85cf8b9901
refs/heads/master
<file_sep>package com.example.admin.helloworld; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { //changes EditText etUpdateValue; Button btnUpdateTextView; TextView tvUpdatedValue; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etUpdateValue = (EditText) findViewById(R.id.etInputValue); btnUpdateTextView = (Button) findViewById(R.id.btnUpdateTextView); tvUpdatedValue = (TextView) findViewById(R.id.tvUpdatedValue); btnUpdateTextView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { tvUpdatedValue.setText(etUpdateValue.getText().toString()); } }); } } <file_sep>package com.example.admin.helloworld; /** * Created by Admin on 9/26/2017. */ public class CodingTest { public static void main(String[] args) { //create s function to check if the number //is divisible by 3 then print "fizz" //is divisible by 5 then print "buzz" //is divisible by 3 and 5 then print "fizz buzz" //otherwise print itself String [] animals = {"cat", "hen","cat", "cow", "dog", "pig", "cow", "dog", "rat"}; System.out.println("test"); fizzbuzz(30); findDulicates(animals); } public static void fizzbuzz(int num){ if(num%5 == 0 && num%3 == 0){ System.out.println("fizzbuzz"); } else if(num%5 == 0){ System.out.println("buzz"); }else if(num%3 == 0){ System.out.println("fizz"); }else{ System.out.println(num); } } public static void findDulicates(String [] stringList){ for(int i = 0; i<stringList.length; i++){ for(int j = 0; j<stringList.length; j++){ if (i == j){ j++; }else if(stringList[i].equals(stringList[j])){ System.out.println(stringList[i]); } } } } }
116c078e069a65e64b612735959137999f8caeb1
[ "Java" ]
2
Java
myers831/Day1
da4a8c4603b5c69741ac1047448bfbda85380c4a
8c01e85e1636805b75750f19eda7d58fcf298c2f
refs/heads/master
<repo_name>bahcecifurkan/FaceRecognition<file_sep>/src/bitirme/test/NewClass.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bitirme.test; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * * @author furkanb */ public class NewClass { public static void main(String[] args) throws FileNotFoundException, IOException { Properties prop = new Properties(); InputStream input = null; input = NewClass.class.getClass().getResourceAsStream("/bitirme/util/config.properties"); // load a properties file prop.load(input); // get the property value and print it out System.out.println(prop.getProperty("db")); } } <file_sep>/src/bitirme/arayuz/AdminMain.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bitirme.arayuz; import bitirme.dao.AdminDao; import bitirme.dao.FotografDao; import bitirme.dao.KullaniciDao; import bitirme.model.Admin; import bitirme.model.Kullanici; import bitirme.service.PropConfig; import java.io.File; import java.util.Arrays; import javax.swing.JFileChooser; import javax.swing.table.DefaultTableModel; /** * * @author furkanb */ public class AdminMain extends javax.swing.JFrame { /** * Creates new form AdminMain */ AdminDao ad; String yeniDatabase; PropConfig pc = new PropConfig(); KullaniciDao kd = new KullaniciDao(); FotografDao fdao = new FotografDao(); public AdminMain() { ad = new AdminDao(); initComponents(); listele(); } public void listele() { String col[] = {"Id", "Ad", "Soyad"}; DefaultTableModel model = new DefaultTableModel(new Object[0][0], col); for (Kullanici k : kd.kullaniciListesi()) { System.out.println(k.getAd()); Object[] o = new Object[3]; o[0] = k.getIdKullanici(); o[1] = k.getAd(); o[2] = k.getSoyad(); model.addRow(o); } table.setModel(model); } /** * This method is called from within the constructor to initialize the form. * WARNING: Do NOT modify this code. The content of this method is always * regenerated by the Form Editor. */ @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { dosyaSecici = new javax.swing.JFileChooser(); dbSecBtn = new javax.swing.JButton(); jPanel1 = new javax.swing.JPanel(); jLabel1 = new javax.swing.JLabel(); jLabel2 = new javax.swing.JLabel(); kadiTxt = new javax.swing.JTextField(); parolaTxt = new javax.swing.JTextField(); kayitOlusturBtn = new javax.swing.JButton(); jScrollPane1 = new javax.swing.JScrollPane(); table = new javax.swing.JTable(); olusturBtn = new javax.swing.JButton(); goruntule = new javax.swing.JButton(); silBtn = new javax.swing.JButton(); yenile = new javax.swing.JButton(); dosyaSecici.setFileSelectionMode(javax.swing.JFileChooser.DIRECTORIES_ONLY); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); dbSecBtn.setText("Fotoğraf(DB) Klasörü"); dbSecBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { dbSecBtnActionPerformed(evt); } }); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Yeni Admin")); jLabel1.setText("Kullanıcı Adı :"); jLabel2.setText("Parola :"); kayitOlusturBtn.setText("Kayıt Oluştur"); kayitOlusturBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { kayitOlusturBtnActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addComponent(kayitOlusturBtn) .addGroup(jPanel1Layout.createSequentialGroup() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(kadiTxt) .addComponent(parolaTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 132, Short.MAX_VALUE)))) .addContainerGap(38, Short.MAX_VALUE)) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(kadiTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(parolaTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGap(18, 18, 18) .addComponent(kayitOlusturBtn) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); table.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { {null, null, null, null}, {null, null, null, null}, {null, null, null, null}, {null, null, null, null} }, new String [] { "Title 1", "Title 2", "Title 3", "Title 4" } )); jScrollPane1.setViewportView(table); olusturBtn.setText("Kullanıcı Oluştur"); olusturBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { olusturBtnActionPerformed(evt); } }); goruntule.setText("Fotograflari Görüntüle"); goruntule.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { goruntuleActionPerformed(evt); } }); silBtn.setText("Sil"); silBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { silBtnActionPerformed(evt); } }); yenile.setText("Yenile"); yenile.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { yenileActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(dbSecBtn) .addGap(18, 18, 18) .addComponent(olusturBtn) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup() .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 355, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(goruntule, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(silBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addComponent(yenile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGap(26, 26, 26)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(dbSecBtn) .addComponent(olusturBtn)) .addGap(18, 18, 18) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false) .addGroup(layout.createSequentialGroup() .addComponent(yenile, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(silBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 75, javax.swing.GroupLayout.PREFERRED_SIZE) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(goruntule, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)) .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 236, javax.swing.GroupLayout.PREFERRED_SIZE))) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); pack(); }// </editor-fold>//GEN-END:initComponents private void kayitOlusturBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_kayitOlusturBtnActionPerformed Admin admin = new Admin(); admin.setKAdi(kadiTxt.getText()); admin.setKParola(parolaTxt.getText()); ad.kaydet(admin); }//GEN-LAST:event_kayitOlusturBtnActionPerformed private void dbSecBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_dbSecBtnActionPerformed int returnVal = dosyaSecici.showSaveDialog(this); dosyaSecici.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY); if (returnVal == JFileChooser.APPROVE_OPTION) { System.out.println("aasdasd"); File file = dosyaSecici.getSelectedFile(); pc.setDbName(file.getPath()); } else { System.out.println("dosya erişimi"); } }//GEN-LAST:event_dbSecBtnActionPerformed private void olusturBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_olusturBtnActionPerformed KullaniciOlustur ko = new KullaniciOlustur(); ko.setVisible(true); }//GEN-LAST:event_olusturBtnActionPerformed private void goruntuleActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_goruntuleActionPerformed Integer row = table.getSelectedRow(); Integer col = 0; System.out.println(table.getValueAt(row, col)); FotografGoruntule fg = new FotografGoruntule((Integer) table.getValueAt(row, col)); fg.show(); }//GEN-LAST:event_goruntuleActionPerformed private void silBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_silBtnActionPerformed Integer idKullanici = (Integer) table.getValueAt(table.getSelectedRow(), 0); fdao.localSil(idKullanici); fdao.sil(idKullanici); kd.sil(idKullanici); listele(); }//GEN-LAST:event_silBtnActionPerformed private void yenileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_yenileActionPerformed listele(); }//GEN-LAST:event_yenileActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(AdminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(AdminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(AdminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(AdminMain.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new AdminMain().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton dbSecBtn; private javax.swing.JFileChooser dosyaSecici; private javax.swing.JButton goruntule; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JPanel jPanel1; private javax.swing.JScrollPane jScrollPane1; private javax.swing.JTextField kadiTxt; private javax.swing.JButton kayitOlusturBtn; private javax.swing.JButton olusturBtn; private javax.swing.JTextField parolaTxt; private javax.swing.JButton silBtn; private javax.swing.JTable table; private javax.swing.JButton yenile; // End of variables declaration//GEN-END:variables } <file_sep>/src/bitirme/model/Fotograf.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bitirme.model; import java.io.Serializable; import javax.persistence.Basic; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.NamedQueries; import javax.persistence.NamedQuery; import javax.persistence.Table; import javax.xml.bind.annotation.XmlRootElement; /** * * @author furkanb */ @Entity @Table(name = "Fotograf") @XmlRootElement @NamedQueries({ @NamedQuery(name = "Fotograf.findAll", query = "SELECT f FROM Fotograf f"), @NamedQuery(name = "Fotograf.findByIdFotograf", query = "SELECT f FROM Fotograf f WHERE f.idFotograf = :idFotograf"), @NamedQuery(name = "Fotograf.findByUrl", query = "SELECT f FROM Fotograf f WHERE f.url = :url")}) public class Fotograf implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Basic(optional = false) @Column(name = "idFotograf") private Integer idFotograf; @Basic(optional = false) @Column(name = "url") private String url; @JoinColumn(name = "Kullanici_idKullanici", referencedColumnName = "idKullanici") @ManyToOne(optional = false) private Kullanici kullaniciidKullanici; public Fotograf() { } public Fotograf(Integer idFotograf) { this.idFotograf = idFotograf; } public Fotograf(Integer idFotograf, String url) { this.idFotograf = idFotograf; this.url = url; } public Integer getIdFotograf() { return idFotograf; } public void setIdFotograf(Integer idFotograf) { this.idFotograf = idFotograf; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public Kullanici getKullaniciidKullanici() { return kullaniciidKullanici; } public void setKullaniciidKullanici(Kullanici kullaniciidKullanici) { this.kullaniciidKullanici = kullaniciidKullanici; } @Override public int hashCode() { int hash = 0; hash += (idFotograf != null ? idFotograf.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Fotograf)) { return false; } Fotograf other = (Fotograf) object; if ((this.idFotograf == null && other.idFotograf != null) || (this.idFotograf != null && !this.idFotograf.equals(other.idFotograf))) { return false; } return true; } @Override public String toString() { return "bitirme.model.Fotograf[ idFotograf=" + idFotograf + " ]"; } } <file_sep>/src/bitirme/dao/AdminDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bitirme.dao; import bitirme.model.Admin; import bitirme.util.HibernateUtil; import java.io.Serializable; import org.hibernate.Query; import org.hibernate.Session; /** * * @author furkanb */ public class AdminDao implements Serializable { private static final long serialVersionUID = 1L; Session session = null; public boolean kaydet(Admin admin) { try { session = HibernateUtil.getSessionFactory().openSession(); session.beginTransaction(); session.save(admin); session.getTransaction().commit(); session.close(); return true; } catch (Exception e) { System.out.println("HATA : " + e); return false; } } public Admin girisKontrol(Admin admin){ session = HibernateUtil.getSessionFactory().openSession(); String sorgu = "Select a from Admin a WHERE k_adi = :k_adi AND k_parola= :k_parola"; try { Query q = session.createQuery(sorgu); q.setParameter("k_adi", admin.getKAdi()); q.setParameter("k_parola", admin.getKParola()); Admin u = (Admin) q.uniqueResult(); session.close(); return u; } catch (Exception e) { session.close(); return null; } } } <file_sep>/src/bitirme/arayuz/KullaniciOlustur.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bitirme.arayuz; import bitirme.dao.FotografDao; import bitirme.dao.KullaniciDao; import bitirme.model.Fotograf; import bitirme.model.Kullanici; import bitirme.service.PropConfig; import java.awt.Graphics; import java.awt.Image; import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import javax.imageio.ImageIO; import org.opencv.core.Core; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfRect; import org.opencv.imgcodecs.Imgcodecs; import org.opencv.videoio.VideoCapture; /** * * @author Furkan */ public class KullaniciOlustur extends javax.swing.JFrame { Integer fotografkayitSayisi = 0; VideoCapture kamera = null; CanliThread th = null; PropConfig pc = new PropConfig(); Mat fotograf = new Mat(); List<Mat> liste = new ArrayList<>(); MatOfByte fotografBytes = new MatOfByte(); // fotoğraf datası MatOfRect yuzler = new MatOfRect(); // birden fazla yüz dizi içinde tutuluyor String database = null; List<String> talimat = new ArrayList<>(); KullaniciDao kd = new KullaniciDao(); FotografDao fd = new FotografDao(); List<String> fileNames = new ArrayList<>(); public void talimatlar() { talimat.add("<NAME>"); talimat.add("Düşük Açıyla SAĞA Doğru Bakınız"); talimat.add("Düşük Açıyla SOLA Doğ<NAME>"); talimat.add("İşlem Tamam. Kaydı Sonlandırın."); } class CanliThread implements Runnable { boolean calismaDurumu = false; @Override public void run() { while (calismaDurumu) { System.out.println("asd"); if (kamera.grab()) { try { kamera.retrieve(fotograf); // Imgcodecs.imencode(".jpg", fotograf, fotografBytes); Image im = ImageIO.read(new ByteArrayInputStream(fotografBytes.toArray())); BufferedImage buff = (BufferedImage) im; Graphics g = panel.getGraphics(); if (g.drawImage(buff, 0, 0, 400, 300, 0, 0, buff.getWidth(), buff.getHeight(), null)) { if (calismaDurumu == false) { System.out.println("durduruldu()"); } } } catch (Exception e) { } } } } } public KullaniciOlustur() { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); talimatlar(); initComponents(); talimatTxt.setText(talimat.get(fotografkayitSayisi)); fotografSayisiTxt.setText("0"); tamamlaBtn.setEnabled(false); } @SuppressWarnings("unchecked") // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { dosyaSecici = new javax.swing.JFileChooser(); klasorSecici = new javax.swing.JFileChooser(); jLabel1 = new javax.swing.JLabel(); jPanel1 = new javax.swing.JPanel(); jLabel2 = new javax.swing.JLabel(); jLabel3 = new javax.swing.JLabel(); adTxt = new javax.swing.JTextField(); soyadTxt = new javax.swing.JTextField(); talimatTxt = new javax.swing.JLabel(); fotografSayisiTxt = new javax.swing.JLabel(); tamamlaBtn = new javax.swing.JButton(); panel = new javax.swing.JPanel(); jLabel4 = new javax.swing.JLabel(); fotografBtn1 = new javax.swing.JButton(); baslatBtn = new javax.swing.JButton(); tamamlandi = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setText("Kaydedilmiş Fotoğraf Sayısı :"); jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Kullanici Bilgileri")); jLabel2.setText("Ad :"); jLabel3.setText("Soyad :"); adTxt.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { adTxtActionPerformed(evt); } }); javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1); jPanel1.setLayout(jPanel1Layout); jPanel1Layout.setHorizontalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel3) .addComponent(jLabel2)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(adTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 159, Short.MAX_VALUE) .addComponent(soyadTxt)) .addContainerGap()) ); jPanel1Layout.setVerticalGroup( jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(jPanel1Layout.createSequentialGroup() .addContainerGap() .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel2) .addComponent(adTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel3) .addComponent(soyadTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) ); talimatTxt.setFont(new java.awt.Font("Ubuntu", 1, 18)); // NOI18N talimatTxt.setText("jLabel5"); fotografSayisiTxt.setText("jLabel5"); tamamlaBtn.setText("Kaydı Tamamla"); tamamlaBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { tamamlaBtnActionPerformed(evt); } }); panel.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0))); javax.swing.GroupLayout panelLayout = new javax.swing.GroupLayout(panel); panel.setLayout(panelLayout); panelLayout.setHorizontalGroup( panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 399, Short.MAX_VALUE) ); panelLayout.setVerticalGroup( panelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGap(0, 300, Short.MAX_VALUE) ); jLabel4.setText("-TALİMAT- "); fotografBtn1.setText("Fotoğraf Çek"); fotografBtn1.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { fotografBtn1ActionPerformed(evt); } }); baslatBtn.setText("Baslat"); baslatBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { baslatBtnActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(44, 44, 44) .addComponent(baslatBtn) .addGap(46, 46, 46) .addComponent(jLabel4) .addGap(41, 41, 41) .addComponent(fotografBtn1) .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)) .addGroup(layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(18, 18, 18) .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(61, 61, 61) .addComponent(tamamlaBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 172, javax.swing.GroupLayout.PREFERRED_SIZE)) .addGroup(layout.createSequentialGroup() .addGap(47, 47, 47) .addComponent(tamamlandi)))) .addGroup(layout.createSequentialGroup() .addGap(33, 33, 33) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(fotografSayisiTxt)) .addGroup(layout.createSequentialGroup() .addGap(56, 56, 56) .addComponent(talimatTxt, javax.swing.GroupLayout.PREFERRED_SIZE, 289, javax.swing.GroupLayout.PREFERRED_SIZE))) .addGap(0, 0, Short.MAX_VALUE)) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(panel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGroup(layout.createSequentialGroup() .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(23, 23, 23) .addComponent(tamamlaBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE) .addGap(21, 21, 21) .addComponent(tamamlandi))) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel4) .addComponent(fotografBtn1) .addComponent(baslatBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED) .addComponent(talimatTxt) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 16, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(jLabel1) .addComponent(fotografSayisiTxt)) .addContainerGap()) ); pack(); }// </editor-fold>//GEN-END:initComponents private void baslatBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_baslatBtnActionPerformed kamera = new VideoCapture(0); //sistemdeki kameraları 0,1,2 th = new CanliThread(); Thread t = new Thread(th); t.setDaemon(true); //threadi çalıştır th.calismaDurumu = true; t.start(); // baslatBtn.setEnabled(false); //start button // duraklatBtn.setEnabled(true); // stop button }//GEN-LAST:event_baslatBtnActionPerformed private void adTxtActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_adTxtActionPerformed // TODO add your handling code here: }//GEN-LAST:event_adTxtActionPerformed private void tamamlaBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_tamamlaBtnActionPerformed Kullanici k = new Kullanici(); k.setAd(adTxt.getText()); k.setSoyad(soyadTxt.getText()); Kullanici k2 = kd.kaydet(k); for (int i = 0; i < 3; i++) { Fotograf f = new Fotograf(); f.setKullaniciidKullanici(k2); f.setUrl(fileNames.get(i)); fd.kaydet(f); } tamamlaBtn.setEnabled(false); tamamlandi.setText("Kayıt Başarılı"); th.calismaDurumu = false; baslatBtn.setEnabled(false); kamera.release(); }//GEN-LAST:event_tamamlaBtnActionPerformed private void fotografBtn1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_fotografBtn1ActionPerformed if (fotografkayitSayisi < 3) { talimatTxt.setText(talimat.get(fotografkayitSayisi + 1)); } fotografkayitSayisi += 1; fotografSayisiTxt.setText(fotografkayitSayisi.toString()); if (fotografkayitSayisi == 3) { fotografBtn1.setEnabled(false); tamamlaBtn.setEnabled(true); } String fileName = kd.sonId() + "-" + adTxt.getText() + soyadTxt.getText() + "_" + fotografkayitSayisi + ".jpg"; fileNames.add(fileName); Imgcodecs.imwrite(pc.getDbName() + "/" + fileName, fotograf); }//GEN-LAST:event_fotografBtn1ActionPerformed /** * @param args the command line arguments */ public static void main(String args[]) { System.loadLibrary(Core.NATIVE_LIBRARY_NAME); /* Set the Nimbus look and feel */ //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) "> /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel. * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html */ try { for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) { if ("Nimbus".equals(info.getName())) { javax.swing.UIManager.setLookAndFeel(info.getClassName()); break; } } } catch (ClassNotFoundException ex) { java.util.logging.Logger.getLogger(KullaniciOlustur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (InstantiationException ex) { java.util.logging.Logger.getLogger(KullaniciOlustur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (IllegalAccessException ex) { java.util.logging.Logger.getLogger(KullaniciOlustur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } catch (javax.swing.UnsupportedLookAndFeelException ex) { java.util.logging.Logger.getLogger(KullaniciOlustur.class.getName()).log(java.util.logging.Level.SEVERE, null, ex); } //</editor-fold> //</editor-fold> //</editor-fold> //</editor-fold> /* Create and display the form */ java.awt.EventQueue.invokeLater(new Runnable() { public void run() { new KullaniciOlustur().setVisible(true); } }); } // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JTextField adTxt; private javax.swing.JButton baslatBtn; private javax.swing.JFileChooser dosyaSecici; private javax.swing.JButton fotografBtn1; private javax.swing.JLabel fotografSayisiTxt; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JLabel jLabel3; private javax.swing.JLabel jLabel4; private javax.swing.JPanel jPanel1; private javax.swing.JFileChooser klasorSecici; private javax.swing.JPanel panel; private javax.swing.JTextField soyadTxt; private javax.swing.JLabel talimatTxt; private javax.swing.JButton tamamlaBtn; private javax.swing.JLabel tamamlandi; // End of variables declaration//GEN-END:variables } <file_sep>/src/bitirme/dao/FotografDao.java /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package bitirme.dao; import bitirme.model.Fotograf; import bitirme.model.Kullanici; import bitirme.service.PropConfig; import bitirme.util.HibernateUtil; import java.io.File; import java.io.Serializable; import java.util.List; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.Transaction; /** * * @author furkanb */ public class FotografDao implements Serializable { private static final long serialVersionUID = 1L; Session session = null; Transaction tx = null; PropConfig pc = new PropConfig(); KullaniciDao kdao = new KullaniciDao(); public void kaydet(Fotograf o) { session = HibernateUtil.getSessionFactory().openSession(); tx = session.beginTransaction(); session.save(o); tx.commit(); session.close(); } public List<Fotograf> list(Integer idKullanici) { session = HibernateUtil.getSessionFactory().openSession(); String sorgu = "Select f FROM Fotograf f " + "join f.kullaniciidKullanici k " + "where k.idKullanici = :idKullanici"; List<Fotograf> liste = null; Query q = session.createQuery(sorgu); q.setParameter("idKullanici", idKullanici); liste = q.list(); session.close(); return liste; } public boolean sil(Integer idKullanici) { session = HibernateUtil.getSessionFactory().openSession(); String sorgu = "delete Fotograf f where f.kullaniciidKullanici = :idKullanici "; Kullanici k = kdao.getwId(idKullanici); Query q = session.createQuery(sorgu); q.setParameter("idKullanici", k); q.executeUpdate(); session.close(); return true; } public boolean localSil(Integer idKullanici) { // Session session1 = HibernateUtil.getSessionFactory().openSession(); List<Fotograf> liste = list(idKullanici); for (Fotograf f : liste) { try { File file = new File(pc.getDbName() + "/" + f.getUrl()); System.out.println(pc.getDbName()+"/"+f.getUrl()); boolean bb = file.delete(); // file.createNewFile(); // file.delete(); System.out.println(bb); } catch (Exception e) { System.out.println(e); } } // session1.close(); return true; } }
0aab685826f0fdbcfe1d247519daed9a1046f6e2
[ "Java" ]
6
Java
bahcecifurkan/FaceRecognition
a05ac89cda8dd12265a50768de37b3033a5f70f2
c3411ac641d42088de85d9a3c72fd6067f0c94b5
refs/heads/master
<repo_name>tautob/BattleShipsGame<file_sep>/src/main/java/BattleShipsGame.java import java.io.ByteArrayInputStream; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Scanner; // you must import Scanner to use it public class BattleShipsGame { public static String[][] seaArray = intializeSeaArray(10, 10); public static int ownShipCount = 10; public static int computerShipCount = 10; public static void main(String[] args) { System.out.println("*** Welcome to BATTLESHIPS! ***"); System.out.println("The sea is currently empty\n"); printSeaToScreen(); System.out.println(); enterUserShipCoords(ownShipCount); System.out.println("\n"); populateComputerShips(computerShipCount); System.out.println("\n"); printSeaToScreen(); playGame(); } public static void playGame() { Scanner input = new Scanner(System.in); Random rand = new Random(); int x = 0; int y = 0; while((ownShipCount > 0) & (computerShipCount > 0)) { System.out.print("Enter X coordinate for your attack: "); x = getInputFromUser(); System.out.print("Enter Y coordinate for your attack: "); y = getInputFromUser(); boolean goodCoords = false; while(!goodCoords) { if (x > seaArray.length - 1 | y > seaArray[0].length - 1) { System.out.println("Coordinates out of bounds, please try again.\n"); System.out.print("Enter X coordinate for your attack: "); x = getInputFromUser(); System.out.print("Enter Y coordinate for your attack: "); y = getInputFromUser(); goodCoords = false; } else if (seaArray[y][x].equals("X") | seaArray[y][x].equals("!") | seaArray[y][x].equals("-")) { System.out.println("Invalid coordinates, please try again.\n"); System.out.print("Enter X coordinate for your attack: "); x = getInputFromUser(); System.out.print("Enter Y coordinate for your attack: "); y = getInputFromUser(); goodCoords = false; } else{ goodCoords = true; } } if (seaArray[y][x].equals("1")) { seaArray[y][x] = "X"; System.out.println("Oh no! You sunk your own ship!"); ownShipCount--; } else if (seaArray[y][x].equals("2")) { seaArray[y][x] = "!"; System.out.println("Direct hit! You sunk an enemy ship!"); computerShipCount--; } else if (seaArray[y][x].equals(" ") | seaArray[y][x].equals("+")) { seaArray[y][x] = "-"; System.out.println("You missed!"); } System.out.print("Computer is attacking ..."); x = rand.nextInt(seaArray.length - 1); y = rand.nextInt(seaArray[0].length - 1); while(seaArray[y][x].equals("X") | seaArray[y][x].equals("!") | seaArray[y][x].equals("-")) { System.out.println("Invalid coordinates, already struck this zone, please try again."); System.out.print("Computer is attacking ..."); x = rand.nextInt(seaArray.length - 1); y = rand.nextInt(seaArray[0].length - 1); } if (seaArray[y][x].equals("1")) { seaArray[y][x] = "X"; System.out.println("Direct hit! The computer struck one of your ships!"); ownShipCount--; } else if (seaArray[y][x].equals("2")) { seaArray[y][x] = "!"; System.out.println("Oh no! The computer has sunk it's own ship!"); computerShipCount--; } else if (seaArray[y][x].equals(" ")) { seaArray[y][x] = "+"; System.out.println("Computer missed!"); } printSeaToScreen(); System.out.println("Your Ships: " + ownShipCount + " Computer Ships: " + computerShipCount); } System.out.println(); if(ownShipCount == 0){ System.out.println("Your Ships: " + ownShipCount + " Computer Ships: " + computerShipCount); System.out.println("Aww, you lost :-("); } else { System.out.println("Your Ships: " + ownShipCount + " Computer Ships: " + computerShipCount); System.out.println("Hooray! You won!"); } } public static void enterUserShipCoords(int numShips) { int x = 0; int y = 0; int j = 1; for(int i=0; i<numShips; i++) { System.out.print("Enter X coordinate for your # " + j + " ship: "); x = getInputFromUser(); System.out.print("Enter Y coordinate for your # " + j + " ship: "); y = getInputFromUser(); if(x > seaArray.length-1 | y > seaArray[0].length-1){ System.out.println("Invalid coordinates, try again."); i--; j--; } else if(!seaArray[y][x].equals(" ")){ System.out.println("Invalid coordinates, try again."); i--; j--; } else{ seaArray[y][x] = "1"; } j++; } } public static void printSeaToScreen(){ System.out.println(" 0 1 2 3 4 5 6 7 8 9 "); for(int row = 0; row <seaArray.length; row++){ System.out.print(row + "| "); for (int col = 0; col < seaArray[row].length; col++) { if(seaArray[row][col].equals("1")){ System.out.print("@ "); } if(seaArray[row][col].equals("X")){ System.out.print("X "); } if(seaArray[row][col].equals("!")){ System.out.print("! "); } if(seaArray[row][col].equals("-")){ System.out.print("- "); } else if(seaArray[row][col].equals("2") | seaArray[row][col].equals(" ") | seaArray[row][col].equals("+")){ System.out.print(" "); } } System.out.print("|" + row); System.out.println(); } System.out.println(" 0 1 2 3 4 5 6 7 8 9 "); } public static String[][] intializeSeaArray(int row, int col) { String[][] array = new String[row][col]; for(int r = 0; r <array.length; r++){ for (int c = 0; c < array[r].length; c++) { array[r][c] = " "; } } return array; } public static void populateComputerShips(int numShips) { Random rand = new Random(); int x = 0; int y = 0; int j = 1; System.out.println("Computer is deploying ships."); for(int i=0; i<numShips; i++) { x = rand.nextInt(seaArray.length-1); y = rand.nextInt(seaArray[0].length-1); if(!seaArray[y][x].equals(" ")){ i--; j--; } else{ System.out.println(j + ". ship DEPLOYED."); seaArray[y][x] = "2"; } j++; } } public static int getInputFromUser(){ Scanner input = new Scanner(System.in); int z = 0; boolean goodCoords = false; while(!goodCoords) { if (input.hasNextInt()) { // z = input.nextInt(); //For testing ByteArrayInputStream in = new ByteArrayInputStream(dataGenerator().toString().getBytes()); System.setIn(in); z = input.nextInt(); goodCoords = true; } else { System.out.println("Invalid coordinates, try again.\n"); goodCoords = false; input.next(); } } return z; } public static Integer dataGenerator() { List<Integer> rawList = new ArrayList<Integer>(); rawList.add(1); rawList.add(2); rawList.add(3); rawList.add(4); rawList.add(5); rawList.add(6); rawList.add(7); rawList.add(8); rawList.add(9); rawList.add(0); Random rand = new Random(); return rawList.get(rand.nextInt(rawList.size())); } }
03610a15c67f574550913e055bb4198f562af2e0
[ "Java" ]
1
Java
tautob/BattleShipsGame
0ef2d4ed73af064dad66ae9485c65a577d93bd89
e4a64639fe16973ef3949d5d58f2eaed7d0ae640
refs/heads/master
<file_sep>#ifndef EGIS0507_MISC_H #define EGIS0507_MISC_H 1 void perror_exit(const char *); void puts_exit(const char *); #endif <file_sep># egis0570 This is the project aiming to provide Linux support for Egis Technology Inc. ID 1c7a:0570 fingerprint scanner (also known as LighTuning Technology Inc.) **It's <a href="https://gitlab.freedesktop.org/libfprint/libfprint/-/issues/162#note_544560">not possible</a> to perform fingerprint recognition right now. Follow <a href=https://gitlab.freedesktop.org/libfprint/libfprint/-/issues/162>this</a> issue to keep up with development progress.** Repository Content ------------------ * `libfprint/`: <a href="https://www.freedesktop.org/wiki/Software/fprint/libfprint/">libfprint</a> fork for driver intergration located <a href="https://gitlab.freedesktop.org/indev29/libfprint">here</a> * `logs/`: usbpcap logs of Windows driver * `pg/`: playground environment to test device communication History ------------- **2018-02** Driver succesfully integrated in libfprint 0.7, all general functions are ready. Recognition _doesn't_ work due to the libfprint matching alogirthm and (as it turned out after some time) incorrect image size used. **2020-06** Found proper image size (thanks to @saeedark), adapted old code to libfprint 1.90. Recognition _doesn't_ work due to the libfprint matching algorithm (see <a href="https://gitlab.freedesktop.org/libfprint/libfprint/-/issues/162#note_544560">explanation</a>). Further work is not possible before proper matching algorithm is implemented in libfprint.
1ad6058e32ca2c4d6a92b2fcf2cc6305556aa762
[ "Markdown", "C" ]
2
C
georgedavid004/egis0570
58ccfefc6441618db4ad929be6145c24abb0f82b
7c28d4f6ba40a91838d0e73aab923c42756af3f9
refs/heads/master
<file_sep>[![Build Status](https://travis-ci.org/JovinLeong/cs207test.svg?branch=master)](https://travis-ci.org/JovinLeong/cs207test.svg?branch=master) [![Coverage Status](https://codecov.io/gh/JovinLeong/cs207test/branch/master/graph/badge.svg)](https://codecov.io/gh/JovinLeong/cs207test) # Hello, this is a test repo for HW4; hopefully the badges wrok and my repo reflects the build status on Travis CI and the code coverage status from CodeCov.<file_sep>#!/usr/bin/env python3 import doctest import sys from roots import * doctest.testmod(verbose=True) def test_quadroots(): assert quad_roots(1.0, 1.0, -12.0) == ((3+0j), (-4+0j)) test_quadroots() def test_quadroots_types(): try: quad_roots("", "green", "hi") except: assert(sys.exc_info()[0] == TypeError) test_quadroots_types() def test_quadroots_zerocoeff(): try: quad_roots(a=0.0) except: assert(sys.exc_info()[0] == ValueError) test_quadroots_zerocoeff()
5e7428f7cd13fd3f1a25b1a4c25d085c5d00ecd0
[ "Markdown", "Python" ]
2
Markdown
JovinLeong/cs207test
fc5c808740a971866664c17e3550803774ed75db
143053097dbfa5400260ae78812212f18e0d93f5
refs/heads/main
<file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/spanner/admin/instance/v1/spanner_instance_admin.proto #include "google/cloud/spanner/admin/instance_admin_client.h" #include "google/cloud/spanner/admin/instance_admin_options.h" #include "google/cloud/spanner/admin/internal/instance_admin_option_defaults.h" #include <memory> #include <thread> namespace google { namespace cloud { namespace spanner_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN InstanceAdminClient::InstanceAdminClient( std::shared_ptr<InstanceAdminConnection> connection) : connection_(std::move(connection)) {} InstanceAdminClient::~InstanceAdminClient() = default; StreamRange<google::spanner::admin::instance::v1::InstanceConfig> InstanceAdminClient::ListInstanceConfigs(std::string const& parent) { google::spanner::admin::instance::v1::ListInstanceConfigsRequest request; request.set_parent(parent); return connection_->ListInstanceConfigs(request); } StatusOr<google::spanner::admin::instance::v1::InstanceConfig> InstanceAdminClient::GetInstanceConfig(std::string const& name) { google::spanner::admin::instance::v1::GetInstanceConfigRequest request; request.set_name(name); return connection_->GetInstanceConfig(request); } StreamRange<google::spanner::admin::instance::v1::Instance> InstanceAdminClient::ListInstances(std::string const& parent) { google::spanner::admin::instance::v1::ListInstancesRequest request; request.set_parent(parent); return connection_->ListInstances(request); } StatusOr<google::spanner::admin::instance::v1::Instance> InstanceAdminClient::GetInstance(std::string const& name) { google::spanner::admin::instance::v1::GetInstanceRequest request; request.set_name(name); return connection_->GetInstance(request); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> InstanceAdminClient::CreateInstance( std::string const& parent, std::string const& instance_id, google::spanner::admin::instance::v1::Instance const& instance) { google::spanner::admin::instance::v1::CreateInstanceRequest request; request.set_parent(parent); request.set_instance_id(instance_id); *request.mutable_instance() = instance; return connection_->CreateInstance(request); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> InstanceAdminClient::UpdateInstance( google::spanner::admin::instance::v1::Instance const& instance, google::protobuf::FieldMask const& field_mask) { google::spanner::admin::instance::v1::UpdateInstanceRequest request; *request.mutable_instance() = instance; *request.mutable_field_mask() = field_mask; return connection_->UpdateInstance(request); } Status InstanceAdminClient::DeleteInstance(std::string const& name) { google::spanner::admin::instance::v1::DeleteInstanceRequest request; request.set_name(name); return connection_->DeleteInstance(request); } StatusOr<google::iam::v1::Policy> InstanceAdminClient::SetIamPolicy( std::string const& resource, google::iam::v1::Policy const& policy) { google::iam::v1::SetIamPolicyRequest request; request.set_resource(resource); *request.mutable_policy() = policy; return connection_->SetIamPolicy(request); } StatusOr<google::iam::v1::Policy> InstanceAdminClient::SetIamPolicy( std::string const& resource, IamUpdater const& updater, Options options) { internal::CheckExpectedOptions<InstanceAdminBackoffPolicyOption>(options, __func__); options = spanner_admin_internal::InstanceAdminDefaultOptions(std::move(options)); auto backoff_policy = options.get<InstanceAdminBackoffPolicyOption>()->clone(); for (;;) { auto recent = GetIamPolicy(resource); if (!recent) { return recent.status(); } auto policy = updater(*std::move(recent)); if (!policy) { return Status(StatusCode::kCancelled, "updater did not yield a policy"); } auto result = SetIamPolicy(resource, *std::move(policy)); if (result || result.status().code() != StatusCode::kAborted) { return result; } std::this_thread::sleep_for(backoff_policy->OnCompletion()); } } StatusOr<google::iam::v1::Policy> InstanceAdminClient::GetIamPolicy( std::string const& resource) { google::iam::v1::GetIamPolicyRequest request; request.set_resource(resource); return connection_->GetIamPolicy(request); } StatusOr<google::iam::v1::TestIamPermissionsResponse> InstanceAdminClient::TestIamPermissions( std::string const& resource, std::vector<std::string> const& permissions) { google::iam::v1::TestIamPermissionsRequest request; request.set_resource(resource); *request.mutable_permissions() = {permissions.begin(), permissions.end()}; return connection_->TestIamPermissions(request); } StreamRange<google::spanner::admin::instance::v1::InstanceConfig> InstanceAdminClient::ListInstanceConfigs( google::spanner::admin::instance::v1::ListInstanceConfigsRequest request) { return connection_->ListInstanceConfigs(std::move(request)); } StatusOr<google::spanner::admin::instance::v1::InstanceConfig> InstanceAdminClient::GetInstanceConfig( google::spanner::admin::instance::v1::GetInstanceConfigRequest const& request) { return connection_->GetInstanceConfig(request); } StreamRange<google::spanner::admin::instance::v1::Instance> InstanceAdminClient::ListInstances( google::spanner::admin::instance::v1::ListInstancesRequest request) { return connection_->ListInstances(std::move(request)); } StatusOr<google::spanner::admin::instance::v1::Instance> InstanceAdminClient::GetInstance( google::spanner::admin::instance::v1::GetInstanceRequest const& request) { return connection_->GetInstance(request); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> InstanceAdminClient::CreateInstance( google::spanner::admin::instance::v1::CreateInstanceRequest const& request) { return connection_->CreateInstance(request); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> InstanceAdminClient::UpdateInstance( google::spanner::admin::instance::v1::UpdateInstanceRequest const& request) { return connection_->UpdateInstance(request); } Status InstanceAdminClient::DeleteInstance( google::spanner::admin::instance::v1::DeleteInstanceRequest const& request) { return connection_->DeleteInstance(request); } StatusOr<google::iam::v1::Policy> InstanceAdminClient::SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request) { return connection_->SetIamPolicy(request); } StatusOr<google::iam::v1::Policy> InstanceAdminClient::GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request) { return connection_->GetIamPolicy(request); } StatusOr<google::iam::v1::TestIamPermissionsResponse> InstanceAdminClient::TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const& request) { return connection_->TestIamPermissions(request); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin } // namespace cloud } // namespace google <file_sep>// Copyright 2018 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/bigtable/instance_admin_client.h" #include "google/cloud/bigtable/internal/logging_instance_admin_client.h" #include "google/cloud/testing_util/scoped_environment.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace bigtable { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { TEST(InstanceAdminClientTest, Default) { auto admin_client = CreateDefaultInstanceAdminClient( "test-project", ClientOptions().set_connection_pool_size(1)); ASSERT_TRUE(admin_client); EXPECT_EQ("test-project", admin_client->project()); auto stub0 = admin_client->Channel(); EXPECT_TRUE(stub0); auto stub1 = admin_client->Channel(); EXPECT_EQ(stub0.get(), stub1.get()); admin_client->reset(); stub1 = admin_client->Channel(); EXPECT_TRUE(stub1); EXPECT_NE(stub0.get(), stub1.get()); } TEST(InstanceAdminClientTest, MakeClient) { auto admin_client = MakeInstanceAdminClient( "test-project", Options{}.set<GrpcNumChannelsOption>(1)); ASSERT_TRUE(admin_client); EXPECT_EQ("test-project", admin_client->project()); auto stub0 = admin_client->Channel(); EXPECT_TRUE(stub0); auto stub1 = admin_client->Channel(); EXPECT_EQ(stub0.get(), stub1.get()); admin_client->reset(); stub1 = admin_client->Channel(); EXPECT_TRUE(stub1); EXPECT_NE(stub0.get(), stub1.get()); } TEST(InstanceAdminClientTest, Logging) { testing_util::ScopedEnvironment env("GOOGLE_CLOUD_CPP_ENABLE_TRACING", "rpc"); auto admin_client = MakeInstanceAdminClient("test-project"); ASSERT_TRUE(admin_client); ASSERT_TRUE(dynamic_cast<internal::LoggingInstanceAdminClient const*>( admin_client.get())) << "Should create LoggingInstanceAdminClient"; } } // namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace bigtable } // namespace cloud } // namespace google <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/spanner/admin/database/v1/spanner_database_admin.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CLIENT_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CLIENT_H #include "google/cloud/spanner/admin/database_admin_connection.h" #include "google/cloud/future.h" #include "google/cloud/iam_updater.h" #include "google/cloud/options.h" #include "google/cloud/polling_policy.h" #include "google/cloud/status_or.h" #include "google/cloud/version.h" #include <google/longrunning/operations.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace spanner_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /** * Cloud Spanner Database Admin API * * The Cloud Spanner Database Admin API can be used to create, drop, and * list databases. It also enables updating the schema of pre-existing * databases. It can be also used to create, delete and list backups for a * database and to restore from an existing backup. */ class DatabaseAdminClient { public: explicit DatabaseAdminClient( std::shared_ptr<DatabaseAdminConnection> connection); ~DatabaseAdminClient(); //@{ // @name Copy and move support DatabaseAdminClient(DatabaseAdminClient const&) = default; DatabaseAdminClient& operator=(DatabaseAdminClient const&) = default; DatabaseAdminClient(DatabaseAdminClient&&) = default; DatabaseAdminClient& operator=(DatabaseAdminClient&&) = default; //@} //@{ // @name Equality friend bool operator==(DatabaseAdminClient const& a, DatabaseAdminClient const& b) { return a.connection_ == b.connection_; } friend bool operator!=(DatabaseAdminClient const& a, DatabaseAdminClient const& b) { return !(a == b); } //@} /** * Lists Cloud Spanner databases. * * @param parent Required. The instance whose databases should be listed. * Values are of the form `projects/<project>/instances/<instance>`. * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ StreamRange<google::spanner::admin::database::v1::Database> ListDatabases( std::string const& parent); /** * Creates a new Cloud Spanner database and starts to prepare it for serving. * The returned [long-running operation][google.longrunning.Operation] will * have a name of the format `<database_name>/operations/<operation_id>` and * can be used to track preparation of the database. The * [metadata][google.longrunning.Operation.metadata] field type is * [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Database][google.spanner.admin.database.v1.Database], if successful. * * @param parent Required. The name of the instance that will serve the new * database. Values are of the form `projects/<project>/instances/<instance>`. * @param create_statement Required. A `CREATE DATABASE` statement, which * specifies the ID of the new database. The database ID must conform to the * regular expression * `[a-z][a-z0-9_\-]*[a-z0-9]` and be between 2 and 30 characters in length. * If the database ID is a reserved word or if it contains a hyphen, the * database ID must be enclosed in backticks (`` ` ``). * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ future<StatusOr<google::spanner::admin::database::v1::Database>> CreateDatabase(std::string const& parent, std::string const& create_statement); /** * Gets the state of a Cloud Spanner database. * * @param name Required. The name of the requested database. Values are of * the form `projects/<project>/instances/<instance>/databases/<database>`. * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ StatusOr<google::spanner::admin::database::v1::Database> GetDatabase( std::string const& name); /** * Updates the schema of a Cloud Spanner database by * creating/altering/dropping tables, columns, indexes, etc. The returned * [long-running operation][google.longrunning.Operation] will have a name of * the format `<database_name>/operations/<operation_id>` and can be used to * track execution of the schema change(s). The * [metadata][google.longrunning.Operation.metadata] field type is * [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. * The operation has no response. * * @param database Required. The database to update. * @param statements Required. DDL statements to be applied to the database. * @return * [google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata](https://github.com/googleapis/googleapis/blob/<KEY>d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L547) */ future< StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>> UpdateDatabaseDdl(std::string const& database, std::vector<std::string> const& statements); /** * Drops (aka deletes) a Cloud Spanner database. * Completed backups for the database will be retained according to their * `expire_time`. * * @param database Required. The database to be dropped. */ Status DropDatabase(std::string const& database); /** * Returns the schema of a Cloud Spanner database as a list of formatted * DDL statements. This method does not show pending schema updates, those may * be queried using the [Operations][google.longrunning.Operations] API. * * @param database Required. The database whose schema we wish to get. * Values are of the form * `projects/<project>/instances/<instance>/databases/<database>` * @return * [google::spanner::admin::database::v1::GetDatabaseDdlResponse](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/spanner_database_admin.proto#L603) */ StatusOr<google::spanner::admin::database::v1::GetDatabaseDdlResponse> GetDatabaseDdl(std::string const& database); /** * Sets the access control policy on a database or backup resource. * Replaces any existing policy. * * Authorization requires `spanner.databases.setIamPolicy` * permission on [resource][google.iam.v1.SetIamPolicyRequest.resource]. * For backups, authorization requires `spanner.backups.setIamPolicy` * permission on [resource][google.iam.v1.SetIamPolicyRequest.resource]. * * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * @param policy REQUIRED: The complete policy to be applied to the * `resource`. The size of the policy is limited to a few 10s of KB. An empty * policy is a valid policy but certain Cloud Platform services (such as * Projects) might reject them. * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> SetIamPolicy( std::string const& resource, google::iam::v1::Policy const& policy); /** * Updates the IAM policy for @p resource using an optimistic concurrency * control loop. * * The loop fetches the current policy for @p resource, and passes it to @p * updater, which should return the new policy. This new policy should use the * current etag so that the read-modify-write cycle can detect races and rerun * the update when there is a mismatch. If the new policy does not have an * etag, the existing policy will be blindly overwritten. If @p updater does * not yield a policy, the control loop is terminated and kCancelled is * returned. * * @param resource Required. The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * @param updater Required. Functor to map the current policy to a new one. * @param options Optional. Options to control the loop. Expected options * are: * - `DatabaseAdminBackoffPolicyOption` * @return google::iam::v1::Policy */ StatusOr<google::iam::v1::Policy> SetIamPolicy(std::string const& resource, IamUpdater const& updater, Options options = {}); /** * Gets the access control policy for a database or backup resource. * Returns an empty policy if a database or backup exists but does not have a * policy set. * * Authorization requires `spanner.databases.getIamPolicy` permission on * [resource][google.iam.v1.GetIamPolicyRequest.resource]. * For backups, authorization requires `spanner.backups.getIamPolicy` * permission on [resource][google.iam.v1.GetIamPolicyRequest.resource]. * * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> GetIamPolicy(std::string const& resource); /** * Returns permissions that the caller has on the specified database or backup * resource. * * Attempting this RPC on a non-existent Cloud Spanner database will * result in a NOT_FOUND error if the user has * `spanner.databases.list` permission on the containing Cloud * Spanner instance. Otherwise returns an empty set of permissions. * Calling this method on a backup that does not exist will * result in a NOT_FOUND error if the user has * `spanner.backups.list` permission on the containing instance. * * @param resource REQUIRED: The resource for which the policy detail is * being requested. See the operation documentation for the appropriate value * for this field. * @param permissions The set of permissions to check for the `resource`. * Permissions with wildcards (such as '*' or 'storage.*') are not allowed. * For more information see [IAM * Overview](https://cloud.google.com/iam/docs/overview#permissions). * @return * [google::iam::v1::TestIamPermissionsResponse](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L141) */ StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions( std::string const& resource, std::vector<std::string> const& permissions); /** * Starts creating a new Cloud Spanner Backup. * The returned backup [long-running operation][google.longrunning.Operation] * will have a name of the format * `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation_id>` * and can be used to track creation of the backup. The * [metadata][google.longrunning.Operation.metadata] field type is * [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Backup][google.spanner.admin.database.v1.Backup], if successful. * Cancelling the returned operation will stop the creation and delete the * backup. There can be only one pending backup creation per database. Backup * creation of different databases can run concurrently. * * @param parent Required. The name of the instance in which the backup will * be created. This must be the same instance that contains the database the * backup will be created from. The backup will be stored in the * location(s) specified in the instance configuration of this * instance. Values are of the form * `projects/<project>/instances/<instance>`. * @param backup Required. The backup to create. * @param backup_id Required. The id of the backup to be created. The * `backup_id` appended to `parent` forms the full backup name of the form * `projects/<project>/instances/<instance>/backups/<backup_id>`. * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L36) */ future<StatusOr<google::spanner::admin::database::v1::Backup>> CreateBackup( std::string const& parent, google::spanner::admin::database::v1::Backup const& backup, std::string const& backup_id); /** * Gets metadata on a pending or completed * [Backup][google.spanner.admin.database.v1.Backup]. * * @param name Required. Name of the backup. * Values are of the form * `projects/<project>/instances/<instance>/backups/<backup>`. * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L36) */ StatusOr<google::spanner::admin::database::v1::Backup> GetBackup( std::string const& name); /** * Updates a pending or completed * [Backup][google.spanner.admin.database.v1.Backup]. * * @param backup Required. The backup to update. `backup.name`, and the * fields to be updated as specified by `update_mask` are required. Other * fields are ignored. Update is only supported for the following fields: * * `backup.expire_time`. * @param update_mask Required. A mask specifying which fields (e.g. * `expire_time`) in the Backup resource should be updated. This mask is * relative to the Backup resource, not to the request message. The field mask * must always be specified; this prevents any future fields from being erased * accidentally by clients that do not know about them. * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L36) */ StatusOr<google::spanner::admin::database::v1::Backup> UpdateBackup( google::spanner::admin::database::v1::Backup const& backup, google::protobuf::FieldMask const& update_mask); /** * Deletes a pending or completed * [Backup][google.spanner.admin.database.v1.Backup]. * * @param name Required. Name of the backup to delete. * Values are of the form * `projects/<project>/instances/<instance>/backups/<backup>`. */ Status DeleteBackup(std::string const& name); /** * Lists completed and pending backups. * Backups returned are ordered by `create_time` in descending order, * starting from the most recent `create_time`. * * @param parent Required. The instance to list backups from. Values are of * the form `projects/<project>/instances/<instance>`. * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L36) */ StreamRange<google::spanner::admin::database::v1::Backup> ListBackups( std::string const& parent); /** * Create a new database by restoring from a completed backup. The new * database must be in the same project and in an instance with the same * instance configuration as the instance containing * the backup. The returned database [long-running * operation][google.longrunning.Operation] has a name of the format * `projects/<project>/instances/<instance>/databases/<database>/operations/<operation_id>`, * and can be used to track the progress of the operation, and to cancel it. * The [metadata][google.longrunning.Operation.metadata] field type is * [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata]. * The [response][google.longrunning.Operation.response] type * is [Database][google.spanner.admin.database.v1.Database], if * successful. Cancelling the returned operation will stop the restore and * delete the database. * There can be only one database being restored into an instance at a time. * Once the restore operation completes, a new restore operation can be * initiated, without waiting for the optimize operation associated with the * first restore to complete. * * @param parent Required. The name of the instance in which to create the * restored database. This instance must be in the same project and * have the same instance configuration as the instance containing * the source backup. Values are of the form * `projects/<project>/instances/<instance>`. * @param database_id Required. The id of the database to create and restore * to. This database must not already exist. The `database_id` appended to * `parent` forms the full database name of the form * `projects/<project>/instances/<instance>/databases/<database_id>`. * @param backup Name of the backup from which to restore. Values are of the * form `projects/<project>/instances/<instance>/backups/<backup>`. * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ future<StatusOr<google::spanner::admin::database::v1::Database>> RestoreDatabase(std::string const& parent, std::string const& database_id, std::string const& backup); /** * Lists database [longrunning-operations][google.longrunning.Operation]. * A database operation has a name of the form * `projects/<project>/instances/<instance>/databases/<database>/operations/<operation>`. * The long-running operation * [metadata][google.longrunning.Operation.metadata] field type * `metadata.type_url` describes the type of the metadata. Operations returned * include those that have completed/failed/canceled within the last 7 days, * and pending operations. * * @param parent Required. The instance of the database operations. * Values are of the form `projects/<project>/instances/<instance>`. * @return * [google::longrunning::Operation](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/longrunning/operations.proto#L128) */ StreamRange<google::longrunning::Operation> ListDatabaseOperations( std::string const& parent); /** * Lists the backup [long-running operations][google.longrunning.Operation] in * the given instance. A backup operation has a name of the form * `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation>`. * The long-running operation * [metadata][google.longrunning.Operation.metadata] field type * `metadata.type_url` describes the type of the metadata. Operations returned * include those that have completed/failed/canceled within the last 7 days, * and pending operations. Operations returned are ordered by * `operation.metadata.value.progress.start_time` in descending order starting * from the most recently started operation. * * @param parent Required. The instance of the backup operations. Values are * of the form `projects/<project>/instances/<instance>`. * @return * [google::longrunning::Operation](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/longrunning/operations.proto#L128) */ StreamRange<google::longrunning::Operation> ListBackupOperations( std::string const& parent); /** * Lists Cloud Spanner databases. * * @param request * [google::spanner::admin::database::v1::ListDatabasesRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L413) * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ StreamRange<google::spanner::admin::database::v1::Database> ListDatabases( google::spanner::admin::database::v1::ListDatabasesRequest request); /** * Creates a new Cloud Spanner database and starts to prepare it for serving. * The returned [long-running operation][google.longrunning.Operation] will * have a name of the format `<database_name>/operations/<operation_id>` and * can be used to track preparation of the database. The * [metadata][google.longrunning.Operation.metadata] field type is * [CreateDatabaseMetadata][google.spanner.admin.database.v1.CreateDatabaseMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Database][google.spanner.admin.database.v1.Database], if successful. * * @param request * [google::spanner::admin::database::v1::CreateDatabaseRequest](https://github.com/googleapis/googleapis/blob/<KEY>a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L445) * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ future<StatusOr<google::spanner::admin::database::v1::Database>> CreateDatabase( google::spanner::admin::database::v1::CreateDatabaseRequest const& request); /** * Gets the state of a Cloud Spanner database. * * @param request * [google::spanner::admin::database::v1::GetDatabaseRequest](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/spanner_database_admin.proto#L484) * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ StatusOr<google::spanner::admin::database::v1::Database> GetDatabase( google::spanner::admin::database::v1::GetDatabaseRequest const& request); /** * Updates the schema of a Cloud Spanner database by * creating/altering/dropping tables, columns, indexes, etc. The returned * [long-running operation][google.longrunning.Operation] will have a name of * the format `<database_name>/operations/<operation_id>` and can be used to * track execution of the schema change(s). The * [metadata][google.longrunning.Operation.metadata] field type is * [UpdateDatabaseDdlMetadata][google.spanner.admin.database.v1.UpdateDatabaseDdlMetadata]. * The operation has no response. * * @param request * [google::spanner::admin::database::v1::UpdateDatabaseDdlRequest](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/spanner_database_admin.proto#L511) * @return * [google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata](https://github.com/googleapis/googleapis/blob/9<KEY>a1f7b19baf5<KEY>0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L547) */ future< StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>> UpdateDatabaseDdl( google::spanner::admin::database::v1::UpdateDatabaseDdlRequest const& request); /** * Drops (aka deletes) a Cloud Spanner database. * Completed backups for the database will be retained according to their * `expire_time`. * * @param request * [google::spanner::admin::database::v1::DropDatabaseRequest](https://github.com/googleapis/googleapis/blob/<KEY>d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L579) */ Status DropDatabase( google::spanner::admin::database::v1::DropDatabaseRequest const& request); /** * Returns the schema of a Cloud Spanner database as a list of formatted * DDL statements. This method does not show pending schema updates, those may * be queried using the [Operations][google.longrunning.Operations] API. * * @param request * [google::spanner::admin::database::v1::GetDatabaseDdlRequest](https://github.com/googleapis/googleapis/blob/<KEY>d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L590) * @return * [google::spanner::admin::database::v1::GetDatabaseDdlResponse](https://github.com/googleapis/googleapis/blob/<KEY>d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L603) */ StatusOr<google::spanner::admin::database::v1::GetDatabaseDdlResponse> GetDatabaseDdl( google::spanner::admin::database::v1::GetDatabaseDdlRequest const& request); /** * Sets the access control policy on a database or backup resource. * Replaces any existing policy. * * Authorization requires `spanner.databases.setIamPolicy` * permission on [resource][google.iam.v1.SetIamPolicyRequest.resource]. * For backups, authorization requires `spanner.backups.setIamPolicy` * permission on [resource][google.iam.v1.SetIamPolicyRequest.resource]. * * @param request * [google::iam::v1::SetIamPolicyRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L98) * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request); /** * Gets the access control policy for a database or backup resource. * Returns an empty policy if a database or backup exists but does not have a * policy set. * * Authorization requires `spanner.databases.getIamPolicy` permission on * [resource][google.iam.v1.GetIamPolicyRequest.resource]. * For backups, authorization requires `spanner.backups.getIamPolicy` * permission on [resource][google.iam.v1.GetIamPolicyRequest.resource]. * * @param request * [google::iam::v1::GetIamPolicyRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L113) * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request); /** * Returns permissions that the caller has on the specified database or backup * resource. * * Attempting this RPC on a non-existent Cloud Spanner database will * result in a NOT_FOUND error if the user has * `spanner.databases.list` permission on the containing Cloud * Spanner instance. Otherwise returns an empty set of permissions. * Calling this method on a backup that does not exist will * result in a NOT_FOUND error if the user has * `spanner.backups.list` permission on the containing instance. * * @param request * [google::iam::v1::TestIamPermissionsRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L126) * @return * [google::iam::v1::TestIamPermissionsResponse](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L141) */ StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const& request); /** * Starts creating a new Cloud Spanner Backup. * The returned backup [long-running operation][google.longrunning.Operation] * will have a name of the format * `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation_id>` * and can be used to track creation of the backup. The * [metadata][google.longrunning.Operation.metadata] field type is * [CreateBackupMetadata][google.spanner.admin.database.v1.CreateBackupMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Backup][google.spanner.admin.database.v1.Backup], if successful. * Cancelling the returned operation will stop the creation and delete the * backup. There can be only one pending backup creation per database. Backup * creation of different databases can run concurrently. * * @param request * [google::spanner::admin::database::v1::CreateBackupRequest](https://github.com/googleapis/googleapis/blob/<KEY>d49/google/spanner/admin/database/v1/backup.proto#L123) * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/backup.proto#L36) */ future<StatusOr<google::spanner::admin::database::v1::Backup>> CreateBackup( google::spanner::admin::database::v1::CreateBackupRequest const& request); /** * Gets metadata on a pending or completed * [Backup][google.spanner.admin.database.v1.Backup]. * * @param request * [google::spanner::admin::database::v1::GetBackupRequest](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/backup.proto#L202) * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/<KEY>dbaff0d49/google/spanner/admin/database/v1/backup.proto#L36) */ StatusOr<google::spanner::admin::database::v1::Backup> GetBackup( google::spanner::admin::database::v1::GetBackupRequest const& request); /** * Updates a pending or completed * [Backup][google.spanner.admin.database.v1.Backup]. * * @param request * [google::spanner::admin::database::v1::UpdateBackupRequest](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/database/v1/backup.proto#L186) * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/<KEY>d49/google/spanner/admin/database/v1/backup.proto#L36) */ StatusOr<google::spanner::admin::database::v1::Backup> UpdateBackup( google::spanner::admin::database::v1::UpdateBackupRequest const& request); /** * Deletes a pending or completed * [Backup][google.spanner.admin.database.v1.Backup]. * * @param request * [google::spanner::admin::database::v1::DeleteBackupRequest](https://github.com/googleapis/googleapis/blob/<KEY>d49/google/spanner/admin/database/v1/backup.proto#L215) */ Status DeleteBackup( google::spanner::admin::database::v1::DeleteBackupRequest const& request); /** * Lists completed and pending backups. * Backups returned are ordered by `create_time` in descending order, * starting from the most recent `create_time`. * * @param request * [google::spanner::admin::database::v1::ListBackupsRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1<KEY>78d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L228) * @return * [google::spanner::admin::database::v1::Backup](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L36) */ StreamRange<google::spanner::admin::database::v1::Backup> ListBackups( google::spanner::admin::database::v1::ListBackupsRequest request); /** * Create a new database by restoring from a completed backup. The new * database must be in the same project and in an instance with the same * instance configuration as the instance containing * the backup. The returned database [long-running * operation][google.longrunning.Operation] has a name of the format * `projects/<project>/instances/<instance>/databases/<database>/operations/<operation_id>`, * and can be used to track the progress of the operation, and to cancel it. * The [metadata][google.longrunning.Operation.metadata] field type is * [RestoreDatabaseMetadata][google.spanner.admin.database.v1.RestoreDatabaseMetadata]. * The [response][google.longrunning.Operation.response] type * is [Database][google.spanner.admin.database.v1.Database], if * successful. Cancelling the returned operation will stop the restore and * delete the database. * There can be only one database being restored into an instance at a time. * Once the restore operation completes, a new restore operation can be * initiated, without waiting for the optimize operation associated with the * first restore to complete. * * @param request * [google::spanner::admin::database::v1::RestoreDatabaseRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L692) * @return * [google::spanner::admin::database::v1::Database](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L326) */ future<StatusOr<google::spanner::admin::database::v1::Database>> RestoreDatabase( google::spanner::admin::database::v1::RestoreDatabaseRequest const& request); /** * Lists database [longrunning-operations][google.longrunning.Operation]. * A database operation has a name of the form * `projects/<project>/instances/<instance>/databases/<database>/operations/<operation>`. * The long-running operation * [metadata][google.longrunning.Operation.metadata] field type * `metadata.type_url` describes the type of the metadata. Operations returned * include those that have completed/failed/canceled within the last 7 days, * and pending operations. * * @param request * [google::spanner::admin::database::v1::ListDatabaseOperationsRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/spanner_database_admin.proto#L611) * @return * [google::longrunning::Operation](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/longrunning/operations.proto#L128) */ StreamRange<google::longrunning::Operation> ListDatabaseOperations( google::spanner::admin::database::v1::ListDatabaseOperationsRequest request); /** * Lists the backup [long-running operations][google.longrunning.Operation] in * the given instance. A backup operation has a name of the form * `projects/<project>/instances/<instance>/backups/<backup>/operations/<operation>`. * The long-running operation * [metadata][google.longrunning.Operation.metadata] field type * `metadata.type_url` describes the type of the metadata. Operations returned * include those that have completed/failed/canceled within the last 7 days, * and pending operations. Operations returned are ordered by * `operation.metadata.value.progress.start_time` in descending order starting * from the most recently started operation. * * @param request * [google::spanner::admin::database::v1::ListBackupOperationsRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/database/v1/backup.proto#L300) * @return * [google::longrunning::Operation](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/longrunning/operations.proto#L128) */ StreamRange<google::longrunning::Operation> ListBackupOperations( google::spanner::admin::database::v1::ListBackupOperationsRequest request); private: std::shared_ptr<DatabaseAdminConnection> connection_; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CLIENT_H <file_sep>#!/usr/bin/env bash # # Copyright 2019 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -euo pipefail BINDIR=$(dirname "$0") readonly BINDIR cat <<'END_OF_PREAMBLE' # Packaging `google-cloud-cpp` <!-- This is an automatically generated file --> <!-- Make changes in ci/generate-markdown/generate-packaging.sh --> This document is intended for package maintainers or for people who might like to "install" the `google-cloud-cpp` libraries in `/usr/local` or a similar directory. * Packaging maintainers or developers that prefer to install the library in a fixed directory (such as `/usr/local` or `/opt`) should consult the current document. * Developers wanting to use the libraries as part of a larger CMake or Bazel project should consult the [quickstart guides](/README.md#quickstart) for the library or libraries they want to use. * Developers wanting to compile the library just to run some of the examples or tests should consult the [building and installing](/README.md#building-and-installing) section of the top-level README file. * Contributors and developers to `google-cloud-cpp` should consult the guide to [setup a development workstation][howto-setup-dev-workstation]. [howto-setup-dev-workstation]: /doc/contributor/howto-guide-setup-development-workstation.md [ninja-build]: https://ninja-build.org/ [ccmake]: https://cmake.org/cmake/help/latest/manual/ccmake.1.html [issues-5489]: https://github.com/googleapis/google-cloud-cpp/issues/5849 There are two primary ways of obtaining `google-cloud-cpp`. You can use git: ```bash git clone https://github.com/googleapis/google-cloud-cpp.git $HOME/google-cloud-cpp ``` Or obtain the tarball release (see https://github.com/googleapis/google-cloud-cpp/releases for the latest release): ```bash VERSION="vX.Y.Z" mkdir -p $HOME/google-cloud-cpp wget -q https://github.com/googleapis/google-cloud-cpp/archive/${VERSION}.tar.gz tar -xf ${VERSION}.tar.gz -C $HOME/google-cloud-cpp --strip=1 ``` # Installing `google-cloud-cpp` <!-- This is an automatically generated file --> <!-- Make changes in ci/generate-markdown/generate-packaging.sh --> This document provides instructions to install the dependencies of `google-cloud-cpp`. **If** all the dependencies of `google-cloud-cpp` are installed and provide CMake support files, then compiling and installing the libraries requires two commands: ```bash cmake -H. -Bcmake-out -DBUILD_TESTING=OFF -DGOOGLE_CLOUD_CPP_ENABLE_EXAMPLES=OFF cmake --build cmake-out --target install ``` Unfortunately getting your system to this state may require multiple steps, the following sections describe how to install `google-cloud-cpp` on several platforms. ## Common Configuration Variables for CMake As is often the case, the CMake build can be configured using a number of options and command-line flags. A full treatment of these options is outside the scope of this document, but here are a few highlights: * Consider using `-GNinja` to switch the generator from `make` (or msbuild on Windows) to [`ninja`][ninja-build]. In our experience `ninja` takes better advantage of multi-core machines. Be aware that `ninja` is often not installed in development workstations, but it is available through most package managers. * If you use the default generator, consider appending `-- -j ${NCPU}` to the build command, where `NCPU` is an environment variable set to the number of processors on your system. You can obtain this information using the `nproc` command on Linux, or `sysctl -n hw.physicalcpu` on macOS. * By default, CMake compiles the `google-cloud-cpp` as static libraries. The standard `-DBUILD_SHARED_LIBS=ON` option can be used to switch this to shared libraries. Having said this, on Windows there are [known issues][issues-5489] with DLLs and generated protos. * You can compile a subset of the libraries using `-DGOOGLE_CLOUD_CPP_ENABLE=lib1,lib2`. To find out about other configuration options, consider using [`ccmake`][ccmake], or `cmake -L`. ## Using `google-cloud-cpp` after it is installed Once installed, follow any of the [quickstart guides](/README.md#quickstart) to use `google-cloud-cpp` in your CMake or Make-based project. If you are planning to use Bazel for your own project, there is no need to install `google-cloud-cpp`, we provide Bazel `BUILD` files for this purpose. The quickstart guides also cover this use-case. ## Required Libraries `google-cloud-cpp` directly depends on the following libraries: | Library | Minimum version | Description | | ------- | --------------: | ----------- | | [Abseil][abseil-gh] | 20200923, Patch 3 | Abseil C++ common library (Requires >= `20210324.2` for `pkg-config` files to work correctly)| | [gRPC][gRPC-gh] | 1.35.x | An RPC library and framework (not needed for Google Cloud Storage client) | | [libcurl][libcurl-gh] | 7.47.0 | HTTP client library for the Google Cloud Storage client | | [crc32c][crc32c-gh] | 1.0.6 | Hardware-accelerated CRC32C implementation | | [OpenSSL][OpenSSL-gh] | 1.0.2 | Crypto functions for Google Cloud Storage authentication | | [nlohmann/json][nlohmann-json-gh] | 3.4.0 | JSON for Modern C++ | | [protobuf][protobuf-gh] | 3.15.8 | C++ Microgenerator support | [abseil-gh]: https://github.com/abseil/abseil-cpp [gRPC-gh]: https://github.com/grpc/grpc [libcurl-gh]: https://github.com/curl/curl [crc32c-gh]: https://github.com/google/crc32c [OpenSSL-gh]: https://github.com/openssl/openssl [nlohmann-json-gh]: https://github.com/nlohmann/json [protobuf-gh]: https://github.com/protocolbuffers/protobuf Note that these libraries may also depend on other libraries. The following instructions include steps to install these indirect dependencies too. When possible, the instructions below prefer to use pre-packaged versions of these libraries and their dependencies. In some cases the packages do not exist, or the packaged versions are too old to support `google-cloud-cpp`. If this is the case, the instructions describe how you can manually download and install these dependencies. END_OF_PREAMBLE # Extracts the part of a file between the BEGIN/DONE tags. function extract() { sed -e '0,/^.*\[BEGIN packaging.md\].*$/d' \ -e '/^.*\[DONE packaging.md\].*$/,$d' "$1" } # A "map" (comma separated) of dockerfile -> summary. DOCKER_DISTROS=( "demo-fedora.Dockerfile,Fedora (34)" "demo-opensuse-leap.Dockerfile,openSUSE (Leap)" "demo-ubuntu-focal.Dockerfile,Ubuntu (20.04 LTS - Focal Fossa)" "demo-ubuntu-bionic.Dockerfile,Ubuntu (18.04 LTS - Bionic Beaver)" "demo-debian-bullseye.Dockerfile,Debian (11 - Bullseye)" "demo-debian-buster.Dockerfile,Debian (10 - Buster)" "demo-debian-stretch.Dockerfile,Debian (9 - Stretch)" "demo-rockylinux-8.Dockerfile,Rocky Linux (8)" "demo-centos-7.Dockerfile,CentOS (7)" ) for distro in "${DOCKER_DISTROS[@]}"; do dockerfile="$(cut -f1 -d, <<<"${distro}")" summary="$(cut -f2- -d, <<<"${distro}")" echo echo "<details>" echo "<summary>${summary}</summary>" echo "<br>" extract "${BINDIR}/../cloudbuild/dockerfiles/${dockerfile}" | "${BINDIR}/dockerfile2markdown.sh" echo "#### Compile and install the main project" echo echo "We can now compile and install \`google-cloud-cpp\`" echo echo '```bash' extract "${BINDIR}/../cloudbuild/builds/demo-install.sh" echo '```' echo echo "</details>" done <file_sep>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/spanner/testing/cleanup_stale_instances.h" #include "google/cloud/spanner/admin/database_admin_client.h" #include "google/cloud/spanner/admin/instance_admin_client.h" #include "google/cloud/spanner/version.h" #include "google/cloud/internal/format_time_point.h" #include "google/cloud/project.h" #include <chrono> #include <vector> namespace google { namespace cloud { namespace spanner_testing { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN Status CleanupStaleInstances(std::string const& project_id, std::regex const& instance_name_regex) { Project project(project_id); spanner_admin::InstanceAdminClient instance_admin_client( spanner_admin::MakeInstanceAdminConnection()); std::vector<std::string> instances = [&]() -> std::vector<std::string> { std::vector<std::string> instances; for (auto const& instance : instance_admin_client.ListInstances(project.FullName())) { if (!instance) break; auto name = instance->name(); std::smatch m; if (std::regex_match(name, m, instance_name_regex)) { auto date_str = m[2]; auto cutoff_date = google::cloud::internal::FormatRfc3339( std::chrono::system_clock::now() - std::chrono::hours(24)) .substr(0, 10); // Compare the strings if (date_str < cutoff_date) { instances.push_back(name); } } } return instances; }(); // Let it fail if we have too many leaks. if (instances.size() > 20) { return Status(StatusCode::kInternal, "too many stale instances"); } spanner_admin::DatabaseAdminClient database_admin_client( spanner_admin::MakeDatabaseAdminConnection()); // We ignore failures here. for (auto const& instance : instances) { for (auto const& backup : database_admin_client.ListBackups(instance)) { database_admin_client.DeleteBackup(backup->name()); } instance_admin_client.DeleteInstance(instance); } return Status(); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_testing } // namespace cloud } // namespace google <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/spanner/admin/instance/v1/spanner_instance_admin.proto #include "google/cloud/spanner/admin/instance_admin_connection.h" #include "google/cloud/spanner/admin/instance_admin_options.h" #include "google/cloud/spanner/admin/internal/instance_admin_option_defaults.h" #include "google/cloud/spanner/admin/internal/instance_admin_stub_factory.h" #include "google/cloud/background_threads.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/async_long_running_operation.h" #include "google/cloud/internal/pagination_range.h" #include "google/cloud/internal/retry_loop.h" #include <memory> namespace google { namespace cloud { namespace spanner_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN InstanceAdminConnection::~InstanceAdminConnection() = default; StreamRange<google::spanner::admin::instance::v1::InstanceConfig> InstanceAdminConnection::ListInstanceConfigs( google::spanner::admin::instance::v1::ListInstanceConfigsRequest request) { return google::cloud::internal::MakePaginationRange< StreamRange<google::spanner::admin::instance::v1::InstanceConfig>>( std::move(request), [](google::spanner::admin::instance::v1:: ListInstanceConfigsRequest const&) { return StatusOr<google::spanner::admin::instance::v1:: ListInstanceConfigsResponse>{}; }, [](google::spanner::admin::instance::v1:: ListInstanceConfigsResponse const&) { return std::vector< google::spanner::admin::instance::v1::InstanceConfig>(); }); } StatusOr<google::spanner::admin::instance::v1::InstanceConfig> InstanceAdminConnection::GetInstanceConfig( google::spanner::admin::instance::v1::GetInstanceConfigRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StreamRange<google::spanner::admin::instance::v1::Instance> InstanceAdminConnection::ListInstances( google::spanner::admin::instance::v1::ListInstancesRequest request) { return google::cloud::internal::MakePaginationRange< StreamRange<google::spanner::admin::instance::v1::Instance>>( std::move(request), [](google::spanner::admin::instance::v1::ListInstancesRequest const&) { return StatusOr< google::spanner::admin::instance::v1::ListInstancesResponse>{}; }, [](google::spanner::admin::instance::v1::ListInstancesResponse const&) { return std::vector<google::spanner::admin::instance::v1::Instance>(); }); } StatusOr<google::spanner::admin::instance::v1::Instance> InstanceAdminConnection::GetInstance( google::spanner::admin::instance::v1::GetInstanceRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> InstanceAdminConnection::CreateInstance( google::spanner::admin::instance::v1::CreateInstanceRequest const&) { return google::cloud::make_ready_future< StatusOr<google::spanner::admin::instance::v1::Instance>>( Status(StatusCode::kUnimplemented, "not implemented")); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> InstanceAdminConnection::UpdateInstance( google::spanner::admin::instance::v1::UpdateInstanceRequest const&) { return google::cloud::make_ready_future< StatusOr<google::spanner::admin::instance::v1::Instance>>( Status(StatusCode::kUnimplemented, "not implemented")); } Status InstanceAdminConnection::DeleteInstance( google::spanner::admin::instance::v1::DeleteInstanceRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::iam::v1::Policy> InstanceAdminConnection::SetIamPolicy( google::iam::v1::SetIamPolicyRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::iam::v1::Policy> InstanceAdminConnection::GetIamPolicy( google::iam::v1::GetIamPolicyRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } StatusOr<google::iam::v1::TestIamPermissionsResponse> InstanceAdminConnection::TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const&) { return Status(StatusCode::kUnimplemented, "not implemented"); } namespace { class InstanceAdminConnectionImpl : public InstanceAdminConnection { public: InstanceAdminConnectionImpl( std::unique_ptr<google::cloud::BackgroundThreads> background, std::shared_ptr<spanner_admin_internal::InstanceAdminStub> stub, Options const& options) : background_(std::move(background)), stub_(std::move(stub)), retry_policy_prototype_( options.get<InstanceAdminRetryPolicyOption>()->clone()), backoff_policy_prototype_( options.get<InstanceAdminBackoffPolicyOption>()->clone()), polling_policy_prototype_( options.get<InstanceAdminPollingPolicyOption>()->clone()), idempotency_policy_( options.get<InstanceAdminConnectionIdempotencyPolicyOption>() ->clone()) {} ~InstanceAdminConnectionImpl() override = default; StreamRange<google::spanner::admin::instance::v1::InstanceConfig> ListInstanceConfigs( google::spanner::admin::instance::v1::ListInstanceConfigsRequest request) override { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<InstanceAdminRetryPolicy const>( retry_policy_prototype_->clone()); auto backoff = std::shared_ptr<BackoffPolicy const>( backoff_policy_prototype_->clone()); auto idempotency = idempotency_policy_->ListInstanceConfigs(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::spanner::admin::instance::v1::InstanceConfig>>( std::move(request), [stub, retry, backoff, idempotency, function_name](google::spanner::admin::instance::v1:: ListInstanceConfigsRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::spanner::admin::instance::v1:: ListInstanceConfigsRequest const& request) { return stub->ListInstanceConfigs(context, request); }, r, function_name); }, [](google::spanner::admin::instance::v1::ListInstanceConfigsResponse r) { std::vector<google::spanner::admin::instance::v1::InstanceConfig> result(r.instance_configs().size()); auto& messages = *r.mutable_instance_configs(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StatusOr<google::spanner::admin::instance::v1::InstanceConfig> GetInstanceConfig( google::spanner::admin::instance::v1::GetInstanceConfigRequest const& request) override { return google::cloud::internal::RetryLoop( retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->GetInstanceConfig(request), [this](grpc::ClientContext& context, google::spanner::admin::instance::v1:: GetInstanceConfigRequest const& request) { return stub_->GetInstanceConfig(context, request); }, request, __func__); } StreamRange<google::spanner::admin::instance::v1::Instance> ListInstances( google::spanner::admin::instance::v1::ListInstancesRequest request) override { request.clear_page_token(); auto stub = stub_; auto retry = std::shared_ptr<InstanceAdminRetryPolicy const>( retry_policy_prototype_->clone()); auto backoff = std::shared_ptr<BackoffPolicy const>( backoff_policy_prototype_->clone()); auto idempotency = idempotency_policy_->ListInstances(request); char const* function_name = __func__; return google::cloud::internal::MakePaginationRange< StreamRange<google::spanner::admin::instance::v1::Instance>>( std::move(request), [stub, retry, backoff, idempotency, function_name]( google::spanner::admin::instance::v1::ListInstancesRequest const& r) { return google::cloud::internal::RetryLoop( retry->clone(), backoff->clone(), idempotency, [stub](grpc::ClientContext& context, google::spanner::admin::instance::v1:: ListInstancesRequest const& request) { return stub->ListInstances(context, request); }, r, function_name); }, [](google::spanner::admin::instance::v1::ListInstancesResponse r) { std::vector<google::spanner::admin::instance::v1::Instance> result( r.instances().size()); auto& messages = *r.mutable_instances(); std::move(messages.begin(), messages.end(), result.begin()); return result; }); } StatusOr<google::spanner::admin::instance::v1::Instance> GetInstance( google::spanner::admin::instance::v1::GetInstanceRequest const& request) override { return google::cloud::internal::RetryLoop( retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->GetInstance(request), [this](grpc::ClientContext& context, google::spanner::admin::instance::v1::GetInstanceRequest const& request) { return stub_->GetInstance(context, request); }, request, __func__); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> CreateInstance( google::spanner::admin::instance::v1::CreateInstanceRequest const& request) override { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::spanner::admin::instance::v1::Instance>( background_->cq(), request, [stub]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::spanner::admin::instance::v1::CreateInstanceRequest const& request) { return stub->AsyncCreateInstance(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::spanner::admin::instance::v1::Instance>, retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->CreateInstance(request), polling_policy_prototype_->clone(), __func__); } future<StatusOr<google::spanner::admin::instance::v1::Instance>> UpdateInstance( google::spanner::admin::instance::v1::UpdateInstanceRequest const& request) override { auto stub = stub_; return google::cloud::internal::AsyncLongRunningOperation< google::spanner::admin::instance::v1::Instance>( background_->cq(), request, [stub]( google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::spanner::admin::instance::v1::UpdateInstanceRequest const& request) { return stub->AsyncUpdateInstance(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::GetOperationRequest const& request) { return stub->AsyncGetOperation(cq, std::move(context), request); }, [stub](google::cloud::CompletionQueue& cq, std::unique_ptr<grpc::ClientContext> context, google::longrunning::CancelOperationRequest const& request) { return stub->AsyncCancelOperation(cq, std::move(context), request); }, &google::cloud::internal::ExtractLongRunningResultResponse< google::spanner::admin::instance::v1::Instance>, retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->UpdateInstance(request), polling_policy_prototype_->clone(), __func__); } Status DeleteInstance( google::spanner::admin::instance::v1::DeleteInstanceRequest const& request) override { return google::cloud::internal::RetryLoop( retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->DeleteInstance(request), [this]( grpc::ClientContext& context, google::spanner::admin::instance::v1::DeleteInstanceRequest const& request) { return stub_->DeleteInstance(context, request); }, request, __func__); } StatusOr<google::iam::v1::Policy> SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request) override { return google::cloud::internal::RetryLoop( retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->SetIamPolicy(request), [this](grpc::ClientContext& context, google::iam::v1::SetIamPolicyRequest const& request) { return stub_->SetIamPolicy(context, request); }, request, __func__); } StatusOr<google::iam::v1::Policy> GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request) override { return google::cloud::internal::RetryLoop( retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->GetIamPolicy(request), [this](grpc::ClientContext& context, google::iam::v1::GetIamPolicyRequest const& request) { return stub_->GetIamPolicy(context, request); }, request, __func__); } StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const& request) override { return google::cloud::internal::RetryLoop( retry_policy_prototype_->clone(), backoff_policy_prototype_->clone(), idempotency_policy_->TestIamPermissions(request), [this](grpc::ClientContext& context, google::iam::v1::TestIamPermissionsRequest const& request) { return stub_->TestIamPermissions(context, request); }, request, __func__); } private: std::unique_ptr<google::cloud::BackgroundThreads> background_; std::shared_ptr<spanner_admin_internal::InstanceAdminStub> stub_; std::unique_ptr<InstanceAdminRetryPolicy const> retry_policy_prototype_; std::unique_ptr<BackoffPolicy const> backoff_policy_prototype_; std::unique_ptr<PollingPolicy const> polling_policy_prototype_; std::unique_ptr<InstanceAdminConnectionIdempotencyPolicy> idempotency_policy_; }; } // namespace std::shared_ptr<InstanceAdminConnection> MakeInstanceAdminConnection( Options options) { options = spanner_admin_internal::InstanceAdminDefaultOptions(std::move(options)); auto background = internal::MakeBackgroundThreadsFactory(options)(); auto stub = spanner_admin_internal::CreateDefaultInstanceAdminStub( background->cq(), options); return std::make_shared<InstanceAdminConnectionImpl>( std::move(background), std::move(stub), options); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin } // namespace cloud } // namespace google namespace google { namespace cloud { namespace spanner_admin_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::shared_ptr<spanner_admin::InstanceAdminConnection> MakeInstanceAdminConnection(std::shared_ptr<InstanceAdminStub> stub, Options options) { options = InstanceAdminDefaultOptions(std::move(options)); return std::make_shared<spanner_admin::InstanceAdminConnectionImpl>( internal::MakeBackgroundThreadsFactory(options)(), std::move(stub), std::move(options)); } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin_internal } // namespace cloud } // namespace google <file_sep>#!/bin/bash # # Copyright 2021 Google LLC # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # This program should print zero or more key/value pairs to standard # output, one entry on each line, and then exit with zero (otherwise # the build fails). The key names can be anything but they may only use # upper case letters and underscores. The first space after the key # name separates it from the value. The value is the rest of the line # (including additional whitespaces). Neither the key nor the value may # span multiple lines. Keys must not be duplicated. echo "STABLE_GIT_COMMIT $(git rev-parse --short HEAD || echo "unknown")" <file_sep>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/client.h" #include "google/cloud/storage/testing/object_integration_test.h" #include "google/cloud/internal/getenv.h" #include "google/cloud/status.h" #include "google/cloud/status_or.h" #include "google/cloud/testing_util/contains_once.h" #include "google/cloud/testing_util/scoped_environment.h" #include "google/cloud/testing_util/status_matchers.h" #include <gmock/gmock.h> #include <algorithm> #include <cstring> #include <iostream> #include <memory> #include <regex> #include <string> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace { using ::google::cloud::testing_util::ContainsOnce; using ::testing::Contains; using ::testing::Not; using ::testing::UnorderedElementsAreArray; using ObjectBasicCRUDIntegrationTest = ::google::cloud::storage::testing::ObjectIntegrationTest; /// @test Verify the Object CRUD (Create, Get, Update, Delete, List) operations. TEST_F(ObjectBasicCRUDIntegrationTest, BasicCRUD) { StatusOr<Client> client = MakeIntegrationTestClient(); ASSERT_STATUS_OK(client); auto list_object_names = [&client, this] { std::vector<std::string> names; for (auto o : client->ListObjects(bucket_name_)) { EXPECT_STATUS_OK(o); if (!o) break; names.push_back(o->name()); } return names; }; auto object_name = MakeRandomObjectName(); ASSERT_THAT(list_object_names(), Not(Contains(object_name))) << "Test aborted. The object <" << object_name << "> already exists." << "This is unexpected as the test generates a random object name."; // Create the object, but only if it does not exist already. StatusOr<ObjectMetadata> insert_meta = client->InsertObject(bucket_name_, object_name, LoremIpsum(), IfGenerationMatch(0), Projection("full")); ASSERT_STATUS_OK(insert_meta); EXPECT_THAT(list_object_names(), ContainsOnce(object_name)); StatusOr<ObjectMetadata> get_meta = client->GetObjectMetadata( bucket_name_, object_name, Generation(insert_meta->generation()), Projection("full")); ASSERT_STATUS_OK(get_meta); // TODO(#7257) - cleanup after production is fixed. if (UsingGrpc()) { // The metadata returned by gRPC (InsertObject) doesn't contain the `acl`, // `etag`, `media_link`, or `self_link` fields. Just compare field by field: EXPECT_EQ(get_meta->name(), insert_meta->name()); // EXPECT_EQ(get_meta->acl(), insert_meta->acl()); EXPECT_EQ(get_meta->bucket(), insert_meta->bucket()); EXPECT_EQ(get_meta->cache_control(), insert_meta->cache_control()); EXPECT_EQ(get_meta->component_count(), insert_meta->component_count()); EXPECT_EQ(get_meta->content_disposition(), insert_meta->content_disposition()); EXPECT_EQ(get_meta->content_encoding(), insert_meta->content_encoding()); EXPECT_EQ(get_meta->content_type(), insert_meta->content_type()); EXPECT_EQ(get_meta->crc32c(), insert_meta->crc32c()); EXPECT_EQ(get_meta->event_based_hold(), insert_meta->event_based_hold()); EXPECT_EQ(get_meta->generation(), insert_meta->generation()); // EXPECT_EQ(get_meta->id(), insert_meta->id()); // b/198515640 EXPECT_EQ(get_meta->kind(), insert_meta->kind()); EXPECT_EQ(get_meta->kms_key_name(), insert_meta->kms_key_name()); EXPECT_EQ(get_meta->md5_hash(), insert_meta->md5_hash()); // EXPECT_EQ(get_meta->media_link(), insert_meta->media_link()); EXPECT_EQ(get_meta->metageneration(), insert_meta->metageneration()); // EXPECT_EQ(get_meta->owner(), insert_meta->owner()); EXPECT_EQ(get_meta->retention_expiration_time(), insert_meta->retention_expiration_time()); // EXPECT_EQ(get_meta->self_link(), insert_meta->self_link()); EXPECT_EQ(get_meta->size(), insert_meta->size()); EXPECT_EQ(get_meta->storage_class(), insert_meta->storage_class()); EXPECT_EQ(get_meta->temporary_hold(), insert_meta->temporary_hold()); EXPECT_EQ(get_meta->time_created(), insert_meta->time_created()); EXPECT_EQ(get_meta->time_deleted(), insert_meta->time_deleted()); EXPECT_EQ(get_meta->time_storage_class_updated(), insert_meta->time_storage_class_updated()); EXPECT_EQ(get_meta->updated(), insert_meta->updated()); } else { EXPECT_EQ(*get_meta, *insert_meta); } ObjectMetadata update = *get_meta; update.mutable_acl().emplace_back( ObjectAccessControl().set_role("READER").set_entity( "allAuthenticatedUsers")); update.set_cache_control("no-cache") .set_content_disposition("inline") .set_content_encoding("identity") .set_content_language("en") .set_content_type("plain/text"); update.mutable_metadata().emplace("updated", "true"); StatusOr<ObjectMetadata> updated_meta = client->UpdateObject( bucket_name_, object_name, update, Projection("full")); ASSERT_STATUS_OK(updated_meta); // Because some of the ACL values are not predictable we convert the values we // care about to strings and compare that. { auto acl_to_string_vector = [](std::vector<ObjectAccessControl> const& acl) { std::vector<std::string> v; std::transform(acl.begin(), acl.end(), std::back_inserter(v), [](ObjectAccessControl const& x) { return x.entity() + " = " + x.role(); }); return v; }; auto expected = acl_to_string_vector(update.acl()); auto actual = acl_to_string_vector(updated_meta->acl()); EXPECT_THAT(expected, UnorderedElementsAreArray(actual)); } EXPECT_EQ(update.cache_control(), updated_meta->cache_control()) << *updated_meta; EXPECT_EQ(update.content_disposition(), updated_meta->content_disposition()) << *updated_meta; EXPECT_EQ(update.content_encoding(), updated_meta->content_encoding()) << *updated_meta; EXPECT_EQ(update.content_language(), updated_meta->content_language()) << *updated_meta; EXPECT_EQ(update.content_type(), updated_meta->content_type()) << *updated_meta; EXPECT_EQ(update.metadata(), updated_meta->metadata()) << *updated_meta; ObjectMetadata desired_patch = *updated_meta; desired_patch.set_content_language("en"); desired_patch.mutable_metadata().erase("updated"); desired_patch.mutable_metadata().emplace("patched", "true"); StatusOr<ObjectMetadata> patched_meta = client->PatchObject( bucket_name_, object_name, *updated_meta, desired_patch); ASSERT_STATUS_OK(patched_meta); EXPECT_EQ(desired_patch.metadata(), patched_meta->metadata()) << *patched_meta; EXPECT_EQ(desired_patch.content_language(), patched_meta->content_language()) << *patched_meta; // This is the test for Object CRUD, we cannot rely on `ScheduleForDelete()`. auto status = client->DeleteObject(bucket_name_, object_name); ASSERT_STATUS_OK(status); EXPECT_THAT(list_object_names(), Not(Contains(object_name))); } Client CreateNonDefaultClient() { auto emulator = google::cloud::internal::GetEnv("CLOUD_STORAGE_EMULATOR_ENDPOINT"); google::cloud::testing_util::ScopedEnvironment env( "CLOUD_STORAGE_EMULATOR_ENDPOINT", {}); auto options = google::cloud::Options{}; if (!emulator) { // Use a different spelling of the default endpoint. This disables the // allegedly "slightly faster" XML endpoints, but should continue to work. options.set<RestEndpointOption>("https://storage.googleapis.com:443"); options.set<UnifiedCredentialsOption>(MakeGoogleDefaultCredentials()); } else { // Use the emulator endpoint, but not through the environment variable options.set<RestEndpointOption>(*emulator); options.set<UnifiedCredentialsOption>(MakeInsecureCredentials()); } return Client(std::move(options)); } /// @test Verify that the client works with non-default endpoints. TEST_F(ObjectBasicCRUDIntegrationTest, NonDefaultEndpointInsertJSON) { auto client = CreateNonDefaultClient(); auto object_name = MakeRandomObjectName(); auto const expected = LoremIpsum(); auto insert = client.InsertObject(bucket_name_, object_name, expected); ASSERT_STATUS_OK(insert); ScheduleForDelete(*insert); auto stream = client.ReadObject(bucket_name_, object_name, IfGenerationNotMatch(0)); EXPECT_STATUS_OK(stream.status()); std::string const actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); } /// @test Verify that the client works with non-default endpoints. TEST_F(ObjectBasicCRUDIntegrationTest, NonDefaultEndpointInsertXml) { auto client = CreateNonDefaultClient(); auto object_name = MakeRandomObjectName(); auto const expected = LoremIpsum(); auto insert = client.InsertObject(bucket_name_, object_name, expected, Fields("")); ASSERT_STATUS_OK(insert); ScheduleForDelete(*insert); auto stream = client.ReadObject(bucket_name_, object_name); EXPECT_STATUS_OK(stream.status()); std::string const actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); } /// @test Verify that the client works with non-default endpoints. TEST_F(ObjectBasicCRUDIntegrationTest, NonDefaultEndpointWriteJSON) { auto client = CreateNonDefaultClient(); auto object_name = MakeRandomObjectName(); auto const expected = LoremIpsum(); auto writer = client.WriteObject(bucket_name_, object_name); writer << expected; writer.Close(); ASSERT_STATUS_OK(writer.metadata()); ScheduleForDelete(*writer.metadata()); auto stream = client.ReadObject(bucket_name_, object_name, IfGenerationNotMatch(0)); EXPECT_STATUS_OK(stream.status()); std::string const actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); } /// @test Verify that the client works with non-default endpoints. TEST_F(ObjectBasicCRUDIntegrationTest, NonDefaultEndpointWriteXml) { auto client = CreateNonDefaultClient(); auto object_name = MakeRandomObjectName(); auto const expected = LoremIpsum(); auto writer = client.WriteObject(bucket_name_, object_name, Fields("")); writer << expected; writer.Close(); ASSERT_STATUS_OK(writer.metadata()); ScheduleForDelete(*writer.metadata()); auto stream = client.ReadObject(bucket_name_, object_name); EXPECT_STATUS_OK(stream.status()); std::string const actual(std::istreambuf_iterator<char>{stream}, {}); EXPECT_EQ(expected, actual); } } // anonymous namespace GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <file_sep>// Copyright 2019 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/grpc_client.h" #include "google/cloud/storage/grpc_plugin.h" #include "google/cloud/storage/internal/grpc_configure_client_context.h" #include "google/cloud/storage/internal/grpc_object_read_source.h" #include "google/cloud/storage/internal/grpc_resumable_upload_session.h" #include "google/cloud/storage/internal/openssl_util.h" #include "google/cloud/storage/internal/resumable_upload_session.h" #include "google/cloud/storage/internal/sha256_hash.h" #include "google/cloud/storage/internal/storage_auth.h" #include "google/cloud/storage/internal/storage_round_robin.h" #include "google/cloud/storage/internal/storage_stub.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/big_endian.h" #include "google/cloud/internal/getenv.h" #include "google/cloud/internal/invoke_result.h" #include "google/cloud/internal/time_utils.h" #include "google/cloud/internal/unified_grpc_credentials.h" #include "google/cloud/log.h" #include "absl/strings/str_split.h" #include "absl/time/time.h" #include <crc32c/crc32c.h> #include <grpcpp/grpcpp.h> #include <algorithm> #include <cinttypes> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { using ::google::cloud::internal::GrpcAuthenticationStrategy; using ::google::cloud::internal::MakeBackgroundThreadsFactory; auto constexpr kDirectPathConfig = R"json({ "loadBalancingConfig": [{ "grpclb": { "childPolicy": [{ "pick_first": {} }] } }] })json"; int DefaultGrpcNumChannels() { auto constexpr kMinimumChannels = 4; auto const count = std::thread::hardware_concurrency(); return (std::max)(kMinimumChannels, static_cast<int>(count)); } Options DefaultOptionsGrpc(Options options) { options = DefaultOptionsWithCredentials(std::move(options)); if (!options.has<UnifiedCredentialsOption>() && !options.has<GrpcCredentialOption>()) { options.set<UnifiedCredentialsOption>( google::cloud::MakeGoogleDefaultCredentials()); } if (!options.has<EndpointOption>()) { options.set<EndpointOption>("storage.googleapis.com"); } auto env = google::cloud::internal::GetEnv("CLOUD_STORAGE_GRPC_ENDPOINT"); if (env.has_value()) { options.set<UnifiedCredentialsOption>(MakeInsecureCredentials()); options.set<EndpointOption>(*env); } if (!options.has<GrpcNumChannelsOption>()) { options.set<GrpcNumChannelsOption>(DefaultGrpcNumChannels()); } return options; } std::shared_ptr<grpc::Channel> CreateGrpcChannel( GrpcAuthenticationStrategy& auth, Options const& options, int channel_id) { grpc::ChannelArguments args; auto const& config = options.get<storage_experimental::GrpcPluginOption>(); if (config.empty() || config == "default" || config == "none") { // Just configure for the regular path. args.SetInt("grpc.channel_id", channel_id); return auth.CreateChannel(options.get<EndpointOption>(), std::move(args)); } std::set<absl::string_view> settings = absl::StrSplit(config, ','); auto const dp = settings.count("dp") != 0 || settings.count("alts") != 0; if (dp || settings.count("pick-first-lb") != 0) { args.SetServiceConfigJSON(kDirectPathConfig); } if (dp || settings.count("enable-dns-srv-queries") != 0) { args.SetInt("grpc.dns_enable_srv_queries", 1); } if (settings.count("disable-dns-srv-queries") != 0) { args.SetInt("grpc.dns_enable_srv_queries", 0); } if (settings.count("exclusive") != 0) { args.SetInt("grpc.channel_id", channel_id); } if (settings.count("alts") != 0) { grpc::experimental::AltsCredentialsOptions alts_opts; return grpc::CreateCustomChannel( options.get<EndpointOption>(), grpc::CompositeChannelCredentials( grpc::experimental::AltsCredentials(alts_opts), grpc::GoogleComputeEngineCredentials()), std::move(args)); } return auth.CreateChannel(options.get<EndpointOption>(), std::move(args)); } std::shared_ptr<StorageStub> CreateStorageStub(CompletionQueue cq, Options const& opts) { auto auth = google::cloud::internal::CreateAuthenticationStrategy( std::move(cq), opts); std::vector<std::shared_ptr<StorageStub>> children( (std::max)(1, opts.get<GrpcNumChannelsOption>())); int id = 0; std::generate(children.begin(), children.end(), [&id, &auth, opts] { return MakeDefaultStorageStub(CreateGrpcChannel(*auth, opts, id++)); }); std::shared_ptr<StorageStub> stub = std::make_shared<StorageRoundRobin>(std::move(children)); if (auth->RequiresConfigureContext()) { stub = std::make_shared<StorageAuth>(std::move(auth), std::move(stub)); } return stub; } std::shared_ptr<GrpcClient> GrpcClient::Create(Options opts) { // Cannot use std::make_shared<> as the constructor is private. return std::shared_ptr<GrpcClient>(new GrpcClient(std::move(opts))); } std::shared_ptr<GrpcClient> GrpcClient::CreateMock( std::shared_ptr<StorageStub> stub, Options opts) { return std::shared_ptr<GrpcClient>( new GrpcClient(std::move(stub), DefaultOptionsGrpc(std::move(opts)))); } GrpcClient::GrpcClient(Options opts) : options_(std::move(opts)), backwards_compatibility_options_( MakeBackwardsCompatibleClientOptions(options_)), background_(MakeBackgroundThreadsFactory(options_)()), stub_(CreateStorageStub(background_->cq(), options_)) {} GrpcClient::GrpcClient(std::shared_ptr<StorageStub> stub, Options opts) : options_(std::move(opts)), backwards_compatibility_options_( MakeBackwardsCompatibleClientOptions(options_)), background_(MakeBackgroundThreadsFactory(options_)()), stub_(std::move(stub)) {} std::unique_ptr<GrpcClient::WriteObjectStream> GrpcClient::CreateUploadWriter( std::unique_ptr<grpc::ClientContext> context) { auto const timeout = options_.get<TransferStallTimeoutOption>(); if (timeout.count() != 0) { context->set_deadline(std::chrono::system_clock::now() + timeout); } return stub_->WriteObject(std::move(context)); } StatusOr<ResumableUploadResponse> GrpcClient::QueryResumableUpload( QueryResumableUploadRequest const& request) { grpc::ClientContext context; ApplyQueryParameters(context, request, "resource"); auto const timeout = options_.get<TransferStallTimeoutOption>(); if (timeout.count() != 0) { context.set_deadline(std::chrono::system_clock::now() + timeout); } auto status = stub_->QueryWriteStatus(context, ToProto(request)); if (!status) return std::move(status).status(); ResumableUploadResponse response; response.upload_state = ResumableUploadResponse::kInProgress; // TODO(#6880) - cleanup the committed_byte vs. size thing if (status->has_persisted_size() && status->persisted_size()) { response.last_committed_byte = static_cast<std::uint64_t>(status->persisted_size()); } else { response.last_committed_byte = 0; } if (status->has_resource()) { response.payload = FromProto(status->resource()); response.upload_state = ResumableUploadResponse::kDone; } return response; } StatusOr<std::unique_ptr<ResumableUploadSession>> GrpcClient::FullyRestoreResumableSession(ResumableUploadRequest const& request, std::string const& upload_url) { auto self = shared_from_this(); auto upload_session_params = DecodeGrpcResumableUploadSessionUrl(upload_url); if (!upload_session_params) return std::move(upload_session_params).status(); auto session = std::unique_ptr<ResumableUploadSession>( new GrpcResumableUploadSession(self, request, *upload_session_params)); auto response = session->ResetSession(); if (!response) std::move(response).status(); return session; } ClientOptions const& GrpcClient::client_options() const { return backwards_compatibility_options_; } StatusOr<ListBucketsResponse> GrpcClient::ListBuckets( ListBucketsRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketMetadata> GrpcClient::CreateBucket(CreateBucketRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketMetadata> GrpcClient::GetBucketMetadata( GetBucketMetadataRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteBucket(DeleteBucketRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketMetadata> GrpcClient::UpdateBucket(UpdateBucketRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketMetadata> GrpcClient::PatchBucket(PatchBucketRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<IamPolicy> GrpcClient::GetBucketIamPolicy( GetBucketIamPolicyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<NativeIamPolicy> GrpcClient::GetNativeBucketIamPolicy( GetBucketIamPolicyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<IamPolicy> GrpcClient::SetBucketIamPolicy( SetBucketIamPolicyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<NativeIamPolicy> GrpcClient::SetNativeBucketIamPolicy( SetNativeBucketIamPolicyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<TestBucketIamPermissionsResponse> GrpcClient::TestBucketIamPermissions( TestBucketIamPermissionsRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketMetadata> GrpcClient::LockBucketRetentionPolicy( LockBucketRetentionPolicyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectMetadata> GrpcClient::InsertObjectMedia( InsertObjectMediaRequest const& request) { auto r = ToProto(request); if (!r) return std::move(r).status(); auto proto_request = *r; auto context = absl::make_unique<grpc::ClientContext>(); // The REST response is just the object metadata (aka the "resource"). In the // gRPC response the object metadata is in a "resource" field. Passing an // extra prefix to ApplyQueryParameters sends the right filtering instructions // to the gRPC API. ApplyQueryParameters(*context, request, "resource"); auto stream = stub_->WriteObject(std::move(context)); auto const& contents = request.contents(); auto const contents_size = static_cast<std::int64_t>(contents.size()); std::int64_t const maximum_buffer_size = google::storage::v2::ServiceConstants::MAX_WRITE_CHUNK_BYTES; // This loop must run at least once because we need to send at least one // Write() call for empty objects. for (std::int64_t offset = 0, n = 0; offset <= contents_size; offset += n) { proto_request.set_write_offset(offset); auto& data = *proto_request.mutable_checksummed_data(); n = (std::min)(contents_size - offset, maximum_buffer_size); data.set_content( contents.substr(static_cast<std::string::size_type>(offset), static_cast<std::string::size_type>(n))); data.set_crc32c(crc32c::Crc32c(data.content())); if (offset + n >= contents_size) { proto_request.set_finish_write(true); stream->Write(proto_request, grpc::WriteOptions{}.set_last_message()); break; } if (!stream->Write(proto_request, grpc::WriteOptions{})) break; // After the first message, clear the object specification and checksums, // there is no need to resend it. proto_request.clear_write_object_spec(); proto_request.clear_object_checksums(); } auto response = stream->Close(); if (!response) return std::move(response).status(); if (response->has_resource()) return FromProto(response->resource()); return ObjectMetadata{}; } StatusOr<ObjectMetadata> GrpcClient::CopyObject(CopyObjectRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectMetadata> GrpcClient::GetObjectMetadata( GetObjectMetadataRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<std::unique_ptr<ObjectReadSource>> GrpcClient::ReadObject( ReadObjectRangeRequest const& request) { // With the REST API this condition was detected by the server as an error, // generally we prefer the server to detect errors because its answers are // authoritative. In this case, the server cannot: with gRPC '0' is the same // as "not set" and the server would send back the full file, which was // unlikely to be the customer's intent. if (request.HasOption<ReadLast>() && request.GetOption<ReadLast>().value() == 0) { return Status( StatusCode::kOutOfRange, "ReadLast(0) is invalid in REST and produces incorrect output in gRPC"); } auto context = absl::make_unique<grpc::ClientContext>(); ApplyQueryParameters(*context, request); auto const timeout = options_.get<TransferStallTimeoutOption>(); if (timeout.count() != 0) { context->set_deadline(std::chrono::system_clock::now() + timeout); } auto proto_request = ToProto(request); if (!proto_request) return std::move(proto_request).status(); return std::unique_ptr<ObjectReadSource>( absl::make_unique<GrpcObjectReadSource>( stub_->ReadObject(std::move(context), *proto_request))); } StatusOr<ListObjectsResponse> GrpcClient::ListObjects( ListObjectsRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteObject(DeleteObjectRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectMetadata> GrpcClient::UpdateObject(UpdateObjectRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectMetadata> GrpcClient::PatchObject(PatchObjectRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectMetadata> GrpcClient::ComposeObject( ComposeObjectRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<RewriteObjectResponse> GrpcClient::RewriteObject( RewriteObjectRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<std::unique_ptr<ResumableUploadSession>> GrpcClient::CreateResumableSession(ResumableUploadRequest const& request) { auto session_id = request.GetOption<UseResumableUploadSession>().value_or(""); if (!session_id.empty()) { return FullyRestoreResumableSession(request, session_id); } auto proto_request = ToProto(request); if (!proto_request) return std::move(proto_request).status(); grpc::ClientContext context; ApplyQueryParameters(context, request, "resource"); auto const timeout = options_.get<TransferStallTimeoutOption>(); if (timeout.count() != 0) { context.set_deadline(std::chrono::system_clock::now() + timeout); } auto response = stub_->StartResumableWrite(context, *proto_request); if (!response.ok()) return std::move(response).status(); auto self = shared_from_this(); return std::unique_ptr<ResumableUploadSession>( new GrpcResumableUploadSession(self, request, {response->upload_id()})); } StatusOr<EmptyResponse> GrpcClient::DeleteResumableUpload( DeleteResumableUploadRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ListBucketAclResponse> GrpcClient::ListBucketAcl( ListBucketAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketAccessControl> GrpcClient::GetBucketAcl( GetBucketAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketAccessControl> GrpcClient::CreateBucketAcl( CreateBucketAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteBucketAcl( DeleteBucketAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ListObjectAclResponse> GrpcClient::ListObjectAcl( ListObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketAccessControl> GrpcClient::UpdateBucketAcl( UpdateBucketAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<BucketAccessControl> GrpcClient::PatchBucketAcl( PatchBucketAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::CreateObjectAcl( CreateObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteObjectAcl( DeleteObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::GetObjectAcl( GetObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::UpdateObjectAcl( UpdateObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::PatchObjectAcl( PatchObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ListDefaultObjectAclResponse> GrpcClient::ListDefaultObjectAcl( ListDefaultObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::CreateDefaultObjectAcl( CreateDefaultObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteDefaultObjectAcl( DeleteDefaultObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::GetDefaultObjectAcl( GetDefaultObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::UpdateDefaultObjectAcl( UpdateDefaultObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ObjectAccessControl> GrpcClient::PatchDefaultObjectAcl( PatchDefaultObjectAclRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ServiceAccount> GrpcClient::GetServiceAccount( GetProjectServiceAccountRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ListHmacKeysResponse> GrpcClient::ListHmacKeys( ListHmacKeysRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<CreateHmacKeyResponse> GrpcClient::CreateHmacKey( CreateHmacKeyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteHmacKey(DeleteHmacKeyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<HmacKeyMetadata> GrpcClient::GetHmacKey(GetHmacKeyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<HmacKeyMetadata> GrpcClient::UpdateHmacKey( UpdateHmacKeyRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<SignBlobResponse> GrpcClient::SignBlob(SignBlobRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<ListNotificationsResponse> GrpcClient::ListNotifications( ListNotificationsRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<NotificationMetadata> GrpcClient::CreateNotification( CreateNotificationRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<NotificationMetadata> GrpcClient::GetNotification( GetNotificationRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } StatusOr<EmptyResponse> GrpcClient::DeleteNotification( DeleteNotificationRequest const&) { return Status(StatusCode::kUnimplemented, __func__); } template <typename GrpcRequest, typename StorageRequest> void SetCommonParameters(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<UserProject>()) { request.mutable_common_request_params()->set_user_project( req.template GetOption<UserProject>().value()); } } template <typename GrpcRequest, typename StorageRequest> Status SetCommonObjectParameters(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<EncryptionKey>()) { auto data = req.template GetOption<EncryptionKey>().value(); auto key_bytes = Base64Decode(data.key); if (!key_bytes) return std::move(key_bytes).status(); auto key_sha256_bytes = Base64Decode(data.sha256); if (!key_sha256_bytes) return std::move(key_sha256_bytes).status(); request.mutable_common_object_request_params()->set_encryption_algorithm( std::move(data.algorithm)); request.mutable_common_object_request_params()->set_encryption_key_bytes( std::string{key_bytes->begin(), key_bytes->end()}); request.mutable_common_object_request_params() ->set_encryption_key_sha256_bytes( std::string{key_sha256_bytes->begin(), key_sha256_bytes->end()}); } return Status{}; } template <typename GrpcRequest> struct GetPredefinedAcl { auto operator()(GrpcRequest const& q) -> decltype(q.predefined_acl()); }; template < typename GrpcRequest, typename StorageRequest, typename std::enable_if< std::is_same<google::storage::v2::PredefinedObjectAcl, google::cloud::internal::invoke_result_t< GetPredefinedAcl<GrpcRequest>, GrpcRequest>>::value, int>::type = 0> void SetPredefinedAcl(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<PredefinedAcl>()) { request.set_predefined_acl( GrpcClient::ToProtoObject(req.template GetOption<PredefinedAcl>())); } } template <typename GrpcRequest, typename StorageRequest> void SetPredefinedDefaultObjectAcl(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<PredefinedDefaultObjectAcl>()) { request.set_predefined_default_object_acl(GrpcClient::ToProto( req.template GetOption<PredefinedDefaultObjectAcl>())); } } template <typename GrpcRequest, typename StorageRequest> void SetMetagenerationConditions(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<IfMetagenerationMatch>()) { request.set_if_metageneration_match( req.template GetOption<IfMetagenerationMatch>().value()); } if (req.template HasOption<IfMetagenerationNotMatch>()) { request.set_if_metageneration_not_match( req.template GetOption<IfMetagenerationNotMatch>().value()); } } template <typename GrpcRequest, typename StorageRequest> void SetGenerationConditions(GrpcRequest& request, StorageRequest const& req) { if (req.template HasOption<IfGenerationMatch>()) { request.set_if_generation_match( req.template GetOption<IfGenerationMatch>().value()); } if (req.template HasOption<IfGenerationNotMatch>()) { request.set_if_generation_not_match( req.template GetOption<IfGenerationNotMatch>().value()); } } template <typename StorageRequest> void SetResourceOptions(google::storage::v2::Object& resource, StorageRequest const& request) { if (request.template HasOption<ContentEncoding>()) { resource.set_content_encoding( request.template GetOption<ContentEncoding>().value()); } if (request.template HasOption<ContentType>()) { resource.set_content_type( request.template GetOption<ContentType>().value()); } if (request.template HasOption<KmsKeyName>()) { resource.set_kms_key(request.template GetOption<KmsKeyName>().value()); } } template <typename StorageRequest> Status SetObjectMetadata(google::storage::v2::Object& resource, StorageRequest const& req) { if (!req.template HasOption<WithObjectMetadata>()) { return Status{}; } auto metadata = req.template GetOption<WithObjectMetadata>().value(); if (!metadata.content_encoding().empty()) { resource.set_content_encoding(metadata.content_encoding()); } if (!metadata.content_disposition().empty()) { resource.set_content_disposition(metadata.content_disposition()); } if (!metadata.cache_control().empty()) { resource.set_cache_control(metadata.cache_control()); } for (auto const& acl : metadata.acl()) { *resource.add_acl() = GrpcClient::ToProto(acl); } if (!metadata.content_language().empty()) { resource.set_content_language(metadata.content_language()); } if (!metadata.content_type().empty()) { resource.set_content_type(metadata.content_type()); } if (metadata.event_based_hold()) { resource.set_event_based_hold(metadata.event_based_hold()); } for (auto const& kv : metadata.metadata()) { (*resource.mutable_metadata())[kv.first] = kv.second; } if (!metadata.storage_class().empty()) { resource.set_storage_class(metadata.storage_class()); } resource.set_temporary_hold(metadata.temporary_hold()); if (metadata.has_customer_encryption()) { auto encryption = GrpcClient::ToProto(metadata.customer_encryption()); if (!encryption) return std::move(encryption).status(); *resource.mutable_customer_encryption() = *std::move(encryption); } return Status{}; } CustomerEncryption GrpcClient::FromProto( google::storage::v2::Object::CustomerEncryption rhs) { CustomerEncryption result; result.encryption_algorithm = std::move(*rhs.mutable_encryption_algorithm()); result.key_sha256 = Base64Encode(rhs.key_sha256_bytes()); return result; } StatusOr<google::storage::v2::Object::CustomerEncryption> GrpcClient::ToProto( CustomerEncryption rhs) { auto key_sha256 = Base64Decode(rhs.key_sha256); if (!key_sha256) return std::move(key_sha256).status(); google::storage::v2::Object::CustomerEncryption result; result.set_encryption_algorithm(std::move(rhs.encryption_algorithm)); result.set_key_sha256_bytes( std::string(key_sha256->begin(), key_sha256->end())); return result; } ObjectMetadata GrpcClient::FromProto(google::storage::v2::Object object) { auto bucket_id = [](google::storage::v2::Object const& object) { auto const& bucket_name = object.bucket(); auto const pos = bucket_name.find_last_of('/'); if (pos == std::string::npos) return bucket_name; return bucket_name.substr(pos + 1); }; ObjectMetadata metadata; metadata.kind_ = "storage#object"; metadata.bucket_ = bucket_id(object); metadata.name_ = std::move(*object.mutable_name()); metadata.generation_ = object.generation(); metadata.id_ = metadata.bucket() + "/" + metadata.name() + "#" + std::to_string(metadata.generation()); metadata.metageneration_ = object.metageneration(); if (object.has_owner()) { metadata.owner_ = FromProto(*object.mutable_owner()); } metadata.storage_class_ = std::move(*object.mutable_storage_class()); if (object.has_create_time()) { metadata.time_created_ = google::cloud::internal::ToChronoTimePoint(object.create_time()); } if (object.has_update_time()) { metadata.updated_ = google::cloud::internal::ToChronoTimePoint(object.update_time()); } std::vector<ObjectAccessControl> acl; acl.reserve(object.acl_size()); for (auto& item : *object.mutable_acl()) { acl.push_back(FromProto(std::move(item), metadata.bucket(), metadata.name(), metadata.generation())); } metadata.acl_ = std::move(acl); metadata.cache_control_ = std::move(*object.mutable_cache_control()); metadata.component_count_ = object.component_count(); metadata.content_disposition_ = std::move(*object.mutable_content_disposition()); metadata.content_encoding_ = std::move(*object.mutable_content_encoding()); metadata.content_language_ = std::move(*object.mutable_content_language()); metadata.content_type_ = std::move(*object.mutable_content_type()); if (object.has_checksums()) { if (object.checksums().has_crc32c()) { metadata.crc32c_ = Crc32cFromProto(object.checksums().crc32c()); } if (!object.checksums().md5_hash().empty()) { metadata.md5_hash_ = MD5FromProto(object.checksums().md5_hash()); } } if (object.has_customer_encryption()) { metadata.customer_encryption_ = FromProto(std::move(*object.mutable_customer_encryption())); } if (object.has_event_based_hold()) { metadata.event_based_hold_ = object.event_based_hold(); } metadata.kms_key_name_ = std::move(*object.mutable_kms_key()); for (auto const& kv : object.metadata()) { metadata.metadata_[kv.first] = kv.second; } if (object.has_retention_expire_time()) { metadata.retention_expiration_time_ = google::cloud::internal::ToChronoTimePoint( object.retention_expire_time()); } metadata.size_ = static_cast<std::uint64_t>(object.size()); metadata.temporary_hold_ = object.temporary_hold(); if (object.has_delete_time()) { metadata.time_deleted_ = google::cloud::internal::ToChronoTimePoint(object.delete_time()); } if (object.has_update_storage_class_time()) { metadata.time_storage_class_updated_ = google::cloud::internal::ToChronoTimePoint( object.update_storage_class_time()); } if (object.has_custom_time()) { metadata.custom_time_ = google::cloud::internal::ToChronoTimePoint(object.custom_time()); } return metadata; } google::storage::v2::ObjectAccessControl GrpcClient::ToProto( ObjectAccessControl const& acl) { google::storage::v2::ObjectAccessControl result; result.set_role(acl.role()); result.set_id(acl.id()); result.set_entity(acl.entity()); result.set_entity_id(acl.entity_id()); result.set_email(acl.email()); result.set_domain(acl.domain()); if (acl.has_project_team()) { result.mutable_project_team()->set_project_number( acl.project_team().project_number); result.mutable_project_team()->set_team(acl.project_team().team); } return result; } ObjectAccessControl GrpcClient::FromProto( google::storage::v2::ObjectAccessControl acl, std::string const& bucket_name, std::string const& object_name, std::uint64_t generation) { ObjectAccessControl result; result.kind_ = "storage#objectAccessControl"; result.bucket_ = bucket_name; result.object_ = object_name; result.generation_ = generation; result.domain_ = std::move(*acl.mutable_domain()); result.email_ = std::move(*acl.mutable_email()); result.entity_ = std::move(*acl.mutable_entity()); result.entity_id_ = std::move(*acl.mutable_entity_id()); result.id_ = std::move(*acl.mutable_id()); if (acl.has_project_team()) { result.project_team_ = ProjectTeam{ std::move(*acl.mutable_project_team()->mutable_project_number()), std::move(*acl.mutable_project_team()->mutable_team()), }; } result.role_ = std::move(*acl.mutable_role()); result.self_link_.clear(); return result; } google::storage::v2::Owner GrpcClient::ToProto(Owner rhs) { google::storage::v2::Owner result; *result.mutable_entity() = std::move(rhs.entity); *result.mutable_entity_id() = std::move(rhs.entity_id); return result; } Owner GrpcClient::FromProto(google::storage::v2::Owner rhs) { Owner result; result.entity = std::move(*rhs.mutable_entity()); result.entity_id = std::move(*rhs.mutable_entity_id()); return result; } google::storage::v2::PredefinedObjectAcl GrpcClient::ToProtoObject( PredefinedAcl const& acl) { if (acl.value() == PredefinedAcl::BucketOwnerFullControl().value()) { return google::storage::v2::OBJECT_ACL_BUCKET_OWNER_FULL_CONTROL; } if (acl.value() == PredefinedAcl::BucketOwnerRead().value()) { return google::storage::v2::OBJECT_ACL_BUCKET_OWNER_READ; } if (acl.value() == PredefinedAcl::AuthenticatedRead().value()) { return google::storage::v2::OBJECT_ACL_AUTHENTICATED_READ; } if (acl.value() == PredefinedAcl::Private().value()) { return google::storage::v2::OBJECT_ACL_PRIVATE; } if (acl.value() == PredefinedAcl::ProjectPrivate().value()) { return google::storage::v2::OBJECT_ACL_PROJECT_PRIVATE; } if (acl.value() == PredefinedAcl::PublicRead().value()) { return google::storage::v2::OBJECT_ACL_PUBLIC_READ; } if (acl.value() == PredefinedAcl::PublicReadWrite().value()) { GCP_LOG(ERROR) << "Invalid predefinedAcl value " << acl; return google::storage::v2::PREDEFINED_OBJECT_ACL_UNSPECIFIED; } GCP_LOG(ERROR) << "Unknown predefinedAcl value " << acl; return google::storage::v2::PREDEFINED_OBJECT_ACL_UNSPECIFIED; } StatusOr<google::storage::v2::WriteObjectRequest> GrpcClient::ToProto( InsertObjectMediaRequest const& request) { google::storage::v2::WriteObjectRequest r; auto& object_spec = *r.mutable_write_object_spec(); auto& resource = *object_spec.mutable_resource(); SetResourceOptions(resource, request); auto status = SetObjectMetadata(resource, request); if (!status.ok()) return status; SetPredefinedAcl(object_spec, request); SetGenerationConditions(object_spec, request); SetMetagenerationConditions(object_spec, request); status = SetCommonObjectParameters(r, request); if (!status.ok()) return status; SetCommonParameters(r, request); resource.set_bucket("projects/_/buckets/" + request.bucket_name()); resource.set_name(request.object_name()); r.set_write_offset(0); auto& checksums = *r.mutable_object_checksums(); if (request.HasOption<Crc32cChecksumValue>()) { // The client library accepts CRC32C checksums in the format required by the // REST APIs (base64-encoded big-endian, 32-bit integers). We need to // convert this to the format expected by proto, which is just a 32-bit // integer. But the value received by the application might be incorrect, so // we need to validate it. auto as_proto = Crc32cToProto(request.GetOption<Crc32cChecksumValue>().value()); if (!as_proto.ok()) return std::move(as_proto).status(); checksums.set_crc32c(*as_proto); } else if (request.GetOption<DisableCrc32cChecksum>().value_or(false)) { // Nothing to do, the option is disabled (mostly useful in tests). } else { checksums.set_crc32c(crc32c::Crc32c(request.contents())); } if (request.HasOption<MD5HashValue>()) { auto as_proto = MD5ToProto(request.GetOption<MD5HashValue>().value()); if (!as_proto.ok()) return std::move(as_proto).status(); checksums.set_md5_hash(*std::move(as_proto)); } else if (request.GetOption<DisableMD5Hash>().value_or(false)) { // Nothing to do, the option is disabled. } else { checksums.set_md5_hash(ComputeMD5Hash(request.contents())); } return r; } ResumableUploadResponse GrpcClient::FromProto( google::storage::v2::WriteObjectResponse const& p) { ResumableUploadResponse response; response.upload_state = ResumableUploadResponse::kInProgress; if (p.has_persisted_size() && p.persisted_size() > 0) { // TODO(#6880) - cleanup the committed_byte vs. size thing response.last_committed_byte = static_cast<std::uint64_t>(p.persisted_size()) - 1; } else { response.last_committed_byte = 0; } if (p.has_resource()) { response.payload = FromProto(p.resource()); response.upload_state = ResumableUploadResponse::kDone; } return response; } StatusOr<google::storage::v2::StartResumableWriteRequest> GrpcClient::ToProto( ResumableUploadRequest const& request) { google::storage::v2::StartResumableWriteRequest result; auto status = SetCommonObjectParameters(result, request); if (!status.ok()) return status; auto& object_spec = *result.mutable_write_object_spec(); auto& resource = *object_spec.mutable_resource(); SetResourceOptions(resource, request); status = SetObjectMetadata(resource, request); if (!status.ok()) return status; SetPredefinedAcl(object_spec, request); SetGenerationConditions(object_spec, request); SetMetagenerationConditions(object_spec, request); SetCommonParameters(result, request); resource.set_bucket("projects/_/buckets/" + request.bucket_name()); resource.set_name(request.object_name()); return result; } google::storage::v2::QueryWriteStatusRequest GrpcClient::ToProto( QueryResumableUploadRequest const& request) { google::storage::v2::QueryWriteStatusRequest r; r.set_upload_id(request.upload_session_url()); return r; } StatusOr<google::storage::v2::ReadObjectRequest> GrpcClient::ToProto( ReadObjectRangeRequest const& request) { google::storage::v2::ReadObjectRequest r; auto status = SetCommonObjectParameters(r, request); if (!status.ok()) return status; r.set_object(request.object_name()); r.set_bucket("projects/_/buckets/" + request.bucket_name()); if (request.HasOption<Generation>()) { r.set_generation(request.GetOption<Generation>().value()); } if (request.HasOption<ReadRange>()) { auto const range = request.GetOption<ReadRange>().value(); r.set_read_offset(range.begin); r.set_read_limit(range.end - range.begin); } if (request.HasOption<ReadLast>()) { auto const offset = request.GetOption<ReadLast>().value(); r.set_read_offset(-offset); } if (request.HasOption<ReadFromOffset>()) { auto const offset = request.GetOption<ReadFromOffset>().value(); if (offset > r.read_offset()) { if (r.read_limit() > 0) { r.set_read_limit(offset - r.read_offset()); } r.set_read_offset(offset); } } SetGenerationConditions(r, request); SetMetagenerationConditions(r, request); SetCommonParameters(r, request); return r; } std::string GrpcClient::Crc32cFromProto(std::uint32_t v) { auto endian_encoded = google::cloud::internal::EncodeBigEndian(v); return Base64Encode(endian_encoded); } StatusOr<std::uint32_t> GrpcClient::Crc32cToProto(std::string const& v) { auto decoded = Base64Decode(v); if (!decoded) return std::move(decoded).status(); return google::cloud::internal::DecodeBigEndian<std::uint32_t>( std::string(decoded->begin(), decoded->end())); } std::string GrpcClient::MD5FromProto(std::string const& v) { return internal::Base64Encode(v); } StatusOr<std::string> GrpcClient::MD5ToProto(std::string const& v) { if (v.empty()) return {}; auto binary = internal::Base64Decode(v); if (!binary) return std::move(binary).status(); return std::string{binary->begin(), binary->end()}; } std::string GrpcClient::ComputeMD5Hash(std::string const& payload) { auto b = internal::MD5Hash(payload); return std::string{b.begin(), b.end()}; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/spanner/admin/instance/v1/spanner_instance_admin.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_INSTANCE_ADMIN_CLIENT_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_INSTANCE_ADMIN_CLIENT_H #include "google/cloud/spanner/admin/instance_admin_connection.h" #include "google/cloud/future.h" #include "google/cloud/iam_updater.h" #include "google/cloud/options.h" #include "google/cloud/polling_policy.h" #include "google/cloud/status_or.h" #include "google/cloud/version.h" #include <google/longrunning/operations.grpc.pb.h> #include <map> #include <memory> namespace google { namespace cloud { namespace spanner_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN /** * Cloud Spanner Instance Admin API * * The Cloud Spanner Instance Admin API can be used to create, delete, * modify and list instances. Instances are dedicated Cloud Spanner serving * and storage resources to be used by Cloud Spanner databases. * * Each instance has a "configuration", which dictates where the * serving resources for the Cloud Spanner instance are located (e.g., * US-central, Europe). Configurations are created by Google based on * resource availability. * * Cloud Spanner billing is based on the instances that exist and their * sizes. After an instance exists, there are no additional * per-database or per-operation charges for use of the instance * (though there may be additional network bandwidth charges). * Instances offer isolation: problems with databases in one instance * will not affect other instances. However, within an instance * databases can affect each other. For example, if one database in an * instance receives a lot of requests and consumes most of the * instance resources, fewer resources are available for other * databases in that instance, and their performance may suffer. */ class InstanceAdminClient { public: explicit InstanceAdminClient( std::shared_ptr<InstanceAdminConnection> connection); ~InstanceAdminClient(); //@{ // @name Copy and move support InstanceAdminClient(InstanceAdminClient const&) = default; InstanceAdminClient& operator=(InstanceAdminClient const&) = default; InstanceAdminClient(InstanceAdminClient&&) = default; InstanceAdminClient& operator=(InstanceAdminClient&&) = default; //@} //@{ // @name Equality friend bool operator==(InstanceAdminClient const& a, InstanceAdminClient const& b) { return a.connection_ == b.connection_; } friend bool operator!=(InstanceAdminClient const& a, InstanceAdminClient const& b) { return !(a == b); } //@} /** * Lists the supported instance configurations for a given project. * * @param parent Required. The name of the project for which a list of * supported instance configurations is requested. Values are of the form * `projects/<project>`. * @return * [google::spanner::admin::instance::v1::InstanceConfig](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L304) */ StreamRange<google::spanner::admin::instance::v1::InstanceConfig> ListInstanceConfigs(std::string const& parent); /** * Gets information about a particular instance configuration. * * @param name Required. The name of the requested instance configuration. * Values are of the form `projects/<project>/instanceConfigs/<config>`. * @return * [google::spanner::admin::instance::v1::InstanceConfig](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L304) */ StatusOr<google::spanner::admin::instance::v1::InstanceConfig> GetInstanceConfig(std::string const& name); /** * Lists all instances in the given project. * * @param parent Required. The name of the project for which a list of * instances is requested. Values are of the form `projects/<project>`. * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/<KEY>9/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ StreamRange<google::spanner::admin::instance::v1::Instance> ListInstances( std::string const& parent); /** * Gets information about a particular instance. * * @param name Required. The name of the requested instance. Values are of * the form `projects/<project>/instances/<instance>`. * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ StatusOr<google::spanner::admin::instance::v1::Instance> GetInstance( std::string const& name); /** * Creates an instance and begins preparing it to begin serving. The * returned [long-running operation][google.longrunning.Operation] * can be used to track the progress of preparing the new * instance. The instance name is assigned by the caller. If the * named instance already exists, `CreateInstance` returns * `ALREADY_EXISTS`. * * Immediately upon completion of this request: * * * The instance is readable via the API, with all requested attributes * but no allocated resources. Its state is `CREATING`. * * Until completion of the returned operation: * * * Cancelling the operation renders the instance immediately unreadable * via the API. * * The instance can be deleted. * * All other attempts to modify the instance are rejected. * * Upon completion of the returned operation: * * * Billing for all successfully-allocated resources begins (some types * may have lower than the requested levels). * * Databases can be created in the instance. * * The instance's allocated resource levels are readable via the API. * * The instance's state becomes `READY`. * * The returned [long-running operation][google.longrunning.Operation] will * have a name of the format `<instance_name>/operations/<operation_id>` and * can be used to track creation of the instance. The * [metadata][google.longrunning.Operation.metadata] field type is * [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Instance][google.spanner.admin.instance.v1.Instance], if successful. * * @param parent Required. The name of the project in which to create the * instance. Values are of the form `projects/<project>`. * @param instance_id Required. The ID of the instance to create. Valid * identifiers are of the form `[a-z][-a-z0-9]*[a-z0-9]` and must be between 2 * and 64 characters in length. * @param instance Required. The instance to create. The name may be * omitted, but if specified must be `<parent>/instances/<instance_id>`. * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ future<StatusOr<google::spanner::admin::instance::v1::Instance>> CreateInstance( std::string const& parent, std::string const& instance_id, google::spanner::admin::instance::v1::Instance const& instance); /** * Updates an instance, and begins allocating or releasing resources * as requested. The returned [long-running * operation][google.longrunning.Operation] can be used to track the * progress of updating the instance. If the named instance does not * exist, returns `NOT_FOUND`. * * Immediately upon completion of this request: * * * For resource types for which a decrease in the instance's allocation * has been requested, billing is based on the newly-requested level. * * Until completion of the returned operation: * * * Cancelling the operation sets its metadata's * [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], * and begins restoring resources to their pre-request values. The operation * is guaranteed to succeed at undoing all resource changes, * after which point it terminates with a `CANCELLED` status. * * All other attempts to modify the instance are rejected. * * Reading the instance via the API continues to give the pre-request * resource levels. * * Upon completion of the returned operation: * * * Billing begins for all successfully-allocated resources (some types * may have lower than the requested levels). * * All newly-reserved resources are available for serving the instance's * tables. * * The instance's new resource levels are readable via the API. * * The returned [long-running operation][google.longrunning.Operation] will * have a name of the format `<instance_name>/operations/<operation_id>` and * can be used to track the instance modification. The * [metadata][google.longrunning.Operation.metadata] field type is * [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Instance][google.spanner.admin.instance.v1.Instance], if successful. * * Authorization requires `spanner.instances.update` permission on * resource [name][google.spanner.admin.instance.v1.Instance.name]. * * @param instance Required. The instance to update, which must always * include the instance name. Otherwise, only fields mentioned in * [field_mask][google.spanner.admin.instance.v1.UpdateInstanceRequest.field_mask] * need be included. * @param field_mask Required. A mask specifying which fields in * [Instance][google.spanner.admin.instance.v1.Instance] should be updated. * The field mask must always be specified; this prevents any future fields * in [Instance][google.spanner.admin.instance.v1.Instance] from being erased * accidentally by clients that do not know about them. * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ future<StatusOr<google::spanner::admin::instance::v1::Instance>> UpdateInstance(google::spanner::admin::instance::v1::Instance const& instance, google::protobuf::FieldMask const& field_mask); /** * Deletes an instance. * * Immediately upon completion of the request: * * * Billing ceases for all of the instance's reserved resources. * * Soon afterward: * * * The instance and *all of its databases* immediately and * irrevocably disappear from the API. All data in the databases * is permanently deleted. * * @param name Required. The name of the instance to be deleted. Values are * of the form `projects/<project>/instances/<instance>` */ Status DeleteInstance(std::string const& name); /** * Sets the access control policy on an instance resource. Replaces any * existing policy. * * Authorization requires `spanner.instances.setIamPolicy` on * [resource][google.iam.v1.SetIamPolicyRequest.resource]. * * @param resource REQUIRED: The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * @param policy REQUIRED: The complete policy to be applied to the * `resource`. The size of the policy is limited to a few 10s of KB. An empty * policy is a valid policy but certain Cloud Platform services (such as * Projects) might reject them. * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> SetIamPolicy( std::string const& resource, google::iam::v1::Policy const& policy); /** * Updates the IAM policy for @p resource using an optimistic concurrency * control loop. * * The loop fetches the current policy for @p resource, and passes it to @p * updater, which should return the new policy. This new policy should use the * current etag so that the read-modify-write cycle can detect races and rerun * the update when there is a mismatch. If the new policy does not have an * etag, the existing policy will be blindly overwritten. If @p updater does * not yield a policy, the control loop is terminated and kCancelled is * returned. * * @param resource Required. The resource for which the policy is being * specified. See the operation documentation for the appropriate value for * this field. * @param updater Required. Functor to map the current policy to a new one. * @param options Optional. Options to control the loop. Expected options * are: * - `InstanceAdminBackoffPolicyOption` * @return google::iam::v1::Policy */ StatusOr<google::iam::v1::Policy> SetIamPolicy(std::string const& resource, IamUpdater const& updater, Options options = {}); /** * Gets the access control policy for an instance resource. Returns an empty * policy if an instance exists but does not have a policy set. * * Authorization requires `spanner.instances.getIamPolicy` on * [resource][google.iam.v1.GetIamPolicyRequest.resource]. * * @param resource REQUIRED: The resource for which the policy is being * requested. See the operation documentation for the appropriate value for * this field. * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> GetIamPolicy(std::string const& resource); /** * Returns permissions that the caller has on the specified instance resource. * * Attempting this RPC on a non-existent Cloud Spanner instance resource will * result in a NOT_FOUND error if the user has `spanner.instances.list` * permission on the containing Google Cloud Project. Otherwise returns an * empty set of permissions. * * @param resource REQUIRED: The resource for which the policy detail is * being requested. See the operation documentation for the appropriate value * for this field. * @param permissions The set of permissions to check for the `resource`. * Permissions with wildcards (such as '*' or 'storage.*') are not allowed. * For more information see [IAM * Overview](https://cloud.google.com/iam/docs/overview#permissions). * @return * [google::iam::v1::TestIamPermissionsResponse](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L141) */ StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions( std::string const& resource, std::vector<std::string> const& permissions); /** * Lists the supported instance configurations for a given project. * * @param request * [google::spanner::admin::instance::v1::ListInstanceConfigsRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L415) * @return * [google::spanner::admin::instance::v1::InstanceConfig](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L304) */ StreamRange<google::spanner::admin::instance::v1::InstanceConfig> ListInstanceConfigs( google::spanner::admin::instance::v1::ListInstanceConfigsRequest request); /** * Gets information about a particular instance configuration. * * @param request * [google::spanner::admin::instance::v1::GetInstanceConfigRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L449) * @return * [google::spanner::admin::instance::v1::InstanceConfig](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L304) */ StatusOr<google::spanner::admin::instance::v1::InstanceConfig> GetInstanceConfig( google::spanner::admin::instance::v1::GetInstanceConfigRequest const& request); /** * Lists all instances in the given project. * * @param request * [google::spanner::admin::instance::v1::ListInstancesRequest](https://github.com/googleapis/googleapis/blob/9<KEY>a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L499) * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ StreamRange<google::spanner::admin::instance::v1::Instance> ListInstances( google::spanner::admin::instance::v1::ListInstancesRequest request); /** * Gets information about a particular instance. * * @param request * [google::spanner::admin::instance::v1::GetInstanceRequest](https://github.com/googleapis/googleapis/blob/<KEY>d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L461) * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/<KEY>550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ StatusOr<google::spanner::admin::instance::v1::Instance> GetInstance( google::spanner::admin::instance::v1::GetInstanceRequest const& request); /** * Creates an instance and begins preparing it to begin serving. The * returned [long-running operation][google.longrunning.Operation] * can be used to track the progress of preparing the new * instance. The instance name is assigned by the caller. If the * named instance already exists, `CreateInstance` returns * `ALREADY_EXISTS`. * * Immediately upon completion of this request: * * * The instance is readable via the API, with all requested attributes * but no allocated resources. Its state is `CREATING`. * * Until completion of the returned operation: * * * Cancelling the operation renders the instance immediately unreadable * via the API. * * The instance can be deleted. * * All other attempts to modify the instance are rejected. * * Upon completion of the returned operation: * * * Billing for all successfully-allocated resources begins (some types * may have lower than the requested levels). * * Databases can be created in the instance. * * The instance's allocated resource levels are readable via the API. * * The instance's state becomes `READY`. * * The returned [long-running operation][google.longrunning.Operation] will * have a name of the format `<instance_name>/operations/<operation_id>` and * can be used to track creation of the instance. The * [metadata][google.longrunning.Operation.metadata] field type is * [CreateInstanceMetadata][google.spanner.admin.instance.v1.CreateInstanceMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Instance][google.spanner.admin.instance.v1.Instance], if successful. * * @param request * [google::spanner::admin::instance::v1::CreateInstanceRequest](https://github.com/googleapis/googleapis/blob/<KEY>7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L478) * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ future<StatusOr<google::spanner::admin::instance::v1::Instance>> CreateInstance( google::spanner::admin::instance::v1::CreateInstanceRequest const& request); /** * Updates an instance, and begins allocating or releasing resources * as requested. The returned [long-running * operation][google.longrunning.Operation] can be used to track the * progress of updating the instance. If the named instance does not * exist, returns `NOT_FOUND`. * * Immediately upon completion of this request: * * * For resource types for which a decrease in the instance's allocation * has been requested, billing is based on the newly-requested level. * * Until completion of the returned operation: * * * Cancelling the operation sets its metadata's * [cancel_time][google.spanner.admin.instance.v1.UpdateInstanceMetadata.cancel_time], * and begins restoring resources to their pre-request values. The operation * is guaranteed to succeed at undoing all resource changes, * after which point it terminates with a `CANCELLED` status. * * All other attempts to modify the instance are rejected. * * Reading the instance via the API continues to give the pre-request * resource levels. * * Upon completion of the returned operation: * * * Billing begins for all successfully-allocated resources (some types * may have lower than the requested levels). * * All newly-reserved resources are available for serving the instance's * tables. * * The instance's new resource levels are readable via the API. * * The returned [long-running operation][google.longrunning.Operation] will * have a name of the format `<instance_name>/operations/<operation_id>` and * can be used to track the instance modification. The * [metadata][google.longrunning.Operation.metadata] field type is * [UpdateInstanceMetadata][google.spanner.admin.instance.v1.UpdateInstanceMetadata]. * The [response][google.longrunning.Operation.response] field type is * [Instance][google.spanner.admin.instance.v1.Instance], if successful. * * Authorization requires `spanner.instances.update` permission on * resource [name][google.spanner.admin.instance.v1.Instance.name]. * * @param request * [google::spanner::admin::instance::v1::UpdateInstanceRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L552) * @return * [google::spanner::admin::instance::v1::Instance](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L328) */ future<StatusOr<google::spanner::admin::instance::v1::Instance>> UpdateInstance( google::spanner::admin::instance::v1::UpdateInstanceRequest const& request); /** * Deletes an instance. * * Immediately upon completion of the request: * * * Billing ceases for all of the instance's reserved resources. * * Soon afterward: * * * The instance and *all of its databases* immediately and * irrevocably disappear from the API. All data in the databases * is permanently deleted. * * @param request * [google::spanner::admin::instance::v1::DeleteInstanceRequest](https://github.com/googleapis/googleapis/blob/<KEY>/google/spanner/admin/instance/v1/spanner_instance_admin.proto#L565) */ Status DeleteInstance( google::spanner::admin::instance::v1::DeleteInstanceRequest const& request); /** * Sets the access control policy on an instance resource. Replaces any * existing policy. * * Authorization requires `spanner.instances.setIamPolicy` on * [resource][google.iam.v1.SetIamPolicyRequest.resource]. * * @param request * [google::iam::v1::SetIamPolicyRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L98) * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request); /** * Gets the access control policy for an instance resource. Returns an empty * policy if an instance exists but does not have a policy set. * * Authorization requires `spanner.instances.getIamPolicy` on * [resource][google.iam.v1.GetIamPolicyRequest.resource]. * * @param request * [google::iam::v1::GetIamPolicyRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L113) * @return * [google::iam::v1::Policy](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/policy.proto#L88) */ StatusOr<google::iam::v1::Policy> GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request); /** * Returns permissions that the caller has on the specified instance resource. * * Attempting this RPC on a non-existent Cloud Spanner instance resource will * result in a NOT_FOUND error if the user has `spanner.instances.list` * permission on the containing Google Cloud Project. Otherwise returns an * empty set of permissions. * * @param request * [google::iam::v1::TestIamPermissionsRequest](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L126) * @return * [google::iam::v1::TestIamPermissionsResponse](https://github.com/googleapis/googleapis/blob/9bac62dbc7a1f7b19baf578d6fbb550dbaff0d49/google/iam/v1/iam_policy.proto#L141) */ StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions( google::iam::v1::TestIamPermissionsRequest const& request); private: std::shared_ptr<InstanceAdminConnection> connection_; }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_INSTANCE_ADMIN_CLIENT_H <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/spanner/admin/instance/v1/spanner_instance_admin.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_MOCKS_MOCK_INSTANCE_ADMIN_CONNECTION_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_MOCKS_MOCK_INSTANCE_ADMIN_CONNECTION_H #include "google/cloud/spanner/admin/instance_admin_connection.h" #include <gmock/gmock.h> namespace google { namespace cloud { namespace spanner_admin_mocks { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN class MockInstanceAdminConnection : public spanner_admin::InstanceAdminConnection { public: MOCK_METHOD(StreamRange<google::spanner::admin::instance::v1::InstanceConfig>, ListInstanceConfigs, (google::spanner::admin::instance::v1::ListInstanceConfigsRequest request), (override)); MOCK_METHOD( StatusOr<google::spanner::admin::instance::v1::InstanceConfig>, GetInstanceConfig, (google::spanner::admin::instance::v1::GetInstanceConfigRequest const& request), (override)); MOCK_METHOD( StreamRange<google::spanner::admin::instance::v1::Instance>, ListInstances, (google::spanner::admin::instance::v1::ListInstancesRequest request), (override)); MOCK_METHOD( StatusOr<google::spanner::admin::instance::v1::Instance>, GetInstance, (google::spanner::admin::instance::v1::GetInstanceRequest const& request), (override)); MOCK_METHOD( future<StatusOr<google::spanner::admin::instance::v1::Instance>>, CreateInstance, (google::spanner::admin::instance::v1::CreateInstanceRequest const& request), (override)); MOCK_METHOD( future<StatusOr<google::spanner::admin::instance::v1::Instance>>, UpdateInstance, (google::spanner::admin::instance::v1::UpdateInstanceRequest const& request), (override)); MOCK_METHOD( Status, DeleteInstance, (google::spanner::admin::instance::v1::DeleteInstanceRequest const& request), (override)); MOCK_METHOD(StatusOr<google::iam::v1::Policy>, SetIamPolicy, (google::iam::v1::SetIamPolicyRequest const& request), (override)); MOCK_METHOD(StatusOr<google::iam::v1::Policy>, GetIamPolicy, (google::iam::v1::GetIamPolicyRequest const& request), (override)); MOCK_METHOD(StatusOr<google::iam::v1::TestIamPermissionsResponse>, TestIamPermissions, (google::iam::v1::TestIamPermissionsRequest const& request), (override)); }; GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin_mocks } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_MOCKS_MOCK_INSTANCE_ADMIN_CONNECTION_H <file_sep>// Copyright 2020 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/bucket_metadata_parser.h" #include "google/cloud/storage/internal/bucket_access_control_parser.h" #include "google/cloud/storage/internal/common_metadata_parser.h" #include "google/cloud/storage/internal/lifecycle_rule_parser.h" #include "google/cloud/storage/internal/object_access_control_parser.h" #include "absl/strings/str_format.h" #include <nlohmann/json.hpp> #include <functional> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { void SetIfNotEmpty(nlohmann::json& json, char const* key, std::string const& value) { if (value.empty()) { return; } json[key] = value; } StatusOr<CorsEntry> ParseCors(nlohmann::json const& json) { auto parse_string_list = [](nlohmann::json const& json, char const* field_name) { std::vector<std::string> list; if (json.count(field_name) != 0) { for (auto const& kv : json[field_name].items()) { list.emplace_back(kv.value().get<std::string>()); } } return list; }; CorsEntry result; if (json.count("maxAgeSeconds") != 0) { auto v = internal::ParseLongField(json, "maxAgeSeconds"); if (!v) return std::move(v).status(); result.max_age_seconds = *v; } result.method = parse_string_list(json, "method"); result.origin = parse_string_list(json, "origin"); result.response_header = parse_string_list(json, "responseHeader"); return result; } StatusOr<UniformBucketLevelAccess> ParseUniformBucketLevelAccess( nlohmann::json const& json) { auto enabled = internal::ParseBoolField(json, "enabled"); if (!enabled) return std::move(enabled).status(); auto locked_time = internal::ParseTimestampField(json, "lockedTime"); if (!locked_time) return std::move(locked_time).status(); return UniformBucketLevelAccess{*enabled, *locked_time}; } Status ParseAcl(std::vector<BucketAccessControl>& acl, nlohmann::json const& json) { if (!json.contains("acl")) return Status{}; std::vector<BucketAccessControl> value; for (auto const& kv : json["acl"].items()) { auto parsed = internal::BucketAccessControlParser::FromJson(kv.value()); if (!parsed.ok()) return std::move(parsed).status(); value.push_back(std::move(*parsed)); } acl = std::move(value); return Status{}; } Status ParseBilling(absl::optional<BucketBilling>& billing, nlohmann::json const& json) { if (!json.contains("billing")) return Status{}; auto b = json["billing"]; auto requester_pays = internal::ParseBoolField(b, "requesterPays"); if (!requester_pays) return std::move(requester_pays).status(); billing = BucketBilling{*requester_pays}; return Status{}; } Status ParseCorsList(std::vector<CorsEntry>& list, nlohmann::json const& json) { if (!json.contains("cors")) return Status{}; std::vector<CorsEntry> value; for (auto const& kv : json["cors"].items()) { auto cors = ParseCors(kv.value()); if (!cors) return std::move(cors).status(); value.push_back(*std::move(cors)); } list = std::move(value); return Status{}; } Status ParseDefaultEventBasedHold(bool& default_event_based_hold, nlohmann::json const& json) { if (json.contains("defaultEventBasedHold")) { default_event_based_hold = json.value("defaultEventBasedHold", false); } return Status{}; } Status ParseDefaultObjectAcl(std::vector<ObjectAccessControl>& acl, nlohmann::json const& json) { if (!json.contains("defaultObjectAcl")) return Status{}; std::vector<ObjectAccessControl> value; for (auto const& kv : json["defaultObjectAcl"].items()) { auto parsed = internal::ObjectAccessControlParser::FromJson(kv.value()); if (!parsed.ok()) return std::move(parsed).status(); value.push_back(std::move(*parsed)); } acl = std::move(value); return Status{}; } Status ParseEncryption(absl::optional<BucketEncryption>& encryption, nlohmann::json const& json) { if (json.contains("encryption")) { BucketEncryption e; e.default_kms_key_name = json["encryption"].value("defaultKmsKeyName", ""); encryption = std::move(e); } return Status{}; } Status ParseIamConfiguration( absl::optional<BucketIamConfiguration>& iam_configuration, nlohmann::json const& json) { if (!json.contains("iamConfiguration")) return Status{}; BucketIamConfiguration value; auto c = json["iamConfiguration"]; if (c.contains("uniformBucketLevelAccess")) { auto ubla = ParseUniformBucketLevelAccess(c["uniformBucketLevelAccess"]); if (!ubla) return std::move(ubla).status(); value.uniform_bucket_level_access = *ubla; } if (c.contains("publicAccessPrevention")) { value.public_access_prevention = c.value("publicAccessPrevention", ""); } iam_configuration = std::move(value); return Status{}; } Status ParseLifecycle(absl::optional<BucketLifecycle>& lifecycle, nlohmann::json const& json) { if (!json.contains("lifecycle")) return Status{}; auto l = json["lifecycle"]; BucketLifecycle value; if (l.contains("rule")) { for (auto const& kv : l["rule"].items()) { auto parsed = internal::LifecycleRuleParser::FromJson(kv.value()); if (!parsed.ok()) return std::move(parsed).status(); value.rule.emplace_back(std::move(*parsed)); } } lifecycle = std::move(value); return Status{}; } Status ParseLogging(absl::optional<BucketLogging>& logging, nlohmann::json const& json) { if (!json.contains("logging")) return Status{}; auto l = json["logging"]; BucketLogging value; value.log_bucket = l.value("logBucket", ""); value.log_object_prefix = l.value("logObjectPrefix", ""); logging = std::move(value); return Status{}; } std::map<std::string, std::string> ParseLabels(nlohmann::json const& json) { if (!json.contains("labels")) return {}; std::map<std::string, std::string> value; for (auto const& kv : json["labels"].items()) { value.emplace(kv.key(), kv.value().get<std::string>()); } return value; } Status ParseProjectNumber(std::int64_t& project_number, nlohmann::json const& json) { auto p = internal::ParseLongField(json, "projectNumber"); if (!p) return std::move(p).status(); project_number = *p; return Status{}; } Status ParseRetentionPolicy( absl::optional<BucketRetentionPolicy>& retention_policy, nlohmann::json const& json) { if (!json.contains("retentionPolicy")) return Status{}; auto r = json["retentionPolicy"]; auto is_locked = internal::ParseBoolField(r, "isLocked"); if (!is_locked) return std::move(is_locked).status(); auto retention_period = internal::ParseLongField(r, "retentionPeriod"); if (!retention_period) return std::move(retention_period).status(); auto effective_time = internal::ParseTimestampField(r, "effectiveTime"); if (!effective_time) return std::move(effective_time).status(); retention_policy = BucketRetentionPolicy{ std::chrono::seconds(*retention_period), *effective_time, *is_locked}; return Status{}; } Status ParseVersioning(absl::optional<BucketVersioning>& versioning, nlohmann::json const& json) { if (!json.contains("versioning")) return Status{}; auto v = json["versioning"]; if (!v.contains("enabled")) return Status{}; auto enabled = internal::ParseBoolField(v, "enabled"); if (!enabled) return std::move(enabled).status(); versioning = BucketVersioning{*enabled}; return Status{}; } Status ParseWebsite(absl::optional<BucketWebsite>& website, nlohmann::json const& json) { if (!json.contains("website")) return Status{}; auto w = json["website"]; BucketWebsite value; value.main_page_suffix = w.value("mainPageSuffix", ""); value.not_found_page = w.value("notFoundPage", ""); website = std::move(value); return Status{}; } void ToJsonAcl(nlohmann::json& json, BucketMetadata const& meta) { if (meta.acl().empty()) return; nlohmann::json value; for (BucketAccessControl const& a : meta.acl()) { nlohmann::json entry; SetIfNotEmpty(entry, "entity", a.entity()); SetIfNotEmpty(entry, "role", a.role()); value.push_back(std::move(entry)); } json["acl"] = std::move(value); } void ToJsonCors(nlohmann::json& json, BucketMetadata const& meta) { if (meta.cors().empty()) return; nlohmann::json value; for (CorsEntry const& v : meta.cors()) { nlohmann::json cors_as_json; if (v.max_age_seconds.has_value()) { cors_as_json["maxAgeSeconds"] = *v.max_age_seconds; } if (!v.method.empty()) { cors_as_json["method"] = v.method; } if (!v.origin.empty()) { cors_as_json["origin"] = v.origin; } if (!v.response_header.empty()) { cors_as_json["responseHeader"] = v.response_header; } value.emplace_back(std::move(cors_as_json)); } json["cors"] = std::move(value); } void ToJsonBilling(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_billing()) return; json["billing"] = nlohmann::json{ {"requesterPays", meta.billing().requester_pays}, }; } void ToJsonDefaultEventBasedHold(nlohmann::json& json, BucketMetadata const& meta) { json["defaultEventBasedHold"] = meta.default_event_based_hold(); } void ToJsonDefaultAcl(nlohmann::json& json, BucketMetadata const& meta) { if (meta.default_acl().empty()) return; nlohmann::json value; for (ObjectAccessControl const& a : meta.default_acl()) { nlohmann::json entry; SetIfNotEmpty(entry, "entity", a.entity()); SetIfNotEmpty(entry, "role", a.role()); value.push_back(std::move(entry)); } json["defaultObjectAcl"] = std::move(value); } void ToJsonEncryption(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_encryption()) return; nlohmann::json e; SetIfNotEmpty(e, "defaultKmsKeyName", meta.encryption().default_kms_key_name); json["encryption"] = std::move(e); } void ToJsonIamConfiguration(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_iam_configuration()) return; nlohmann::json value; if (meta.iam_configuration().uniform_bucket_level_access.has_value()) { // The lockedTime field is not mutable and should not be set by the client // the server will provide a value. value["uniformBucketLevelAccess"] = nlohmann::json{ {"enabled", meta.iam_configuration().uniform_bucket_level_access->enabled}}; } if (meta.iam_configuration().public_access_prevention.has_value()) { value["publicAccessPrevention"] = *meta.iam_configuration().public_access_prevention; } json["iamConfiguration"] = std::move(value); } void ToJsonLabels(nlohmann::json& json, BucketMetadata const& meta) { if (meta.labels().empty()) return; nlohmann::json value; for (auto const& kv : meta.labels()) { value[kv.first] = kv.second; } json["labels"] = std::move(value); } void ToJsonLifecycle(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_lifecycle()) return; nlohmann::json value; for (LifecycleRule const& v : meta.lifecycle().rule) { nlohmann::json condition; auto const& c = v.condition(); if (c.age) { condition["age"] = *c.age; } if (c.created_before.has_value()) { condition["createdBefore"] = absl::StrFormat("%04d-%02d-%02d", c.created_before->year(), c.created_before->month(), c.created_before->day()); } if (c.is_live) { condition["isLive"] = *c.is_live; } if (c.matches_storage_class) { condition["matchesStorageClass"] = *c.matches_storage_class; } if (c.num_newer_versions) { condition["numNewerVersions"] = *c.num_newer_versions; } nlohmann::json action{{"type", v.action().type}}; if (!v.action().storage_class.empty()) { action["storageClass"] = v.action().storage_class; } value.emplace_back(nlohmann::json{{"condition", std::move(condition)}, {"action", std::move(action)}}); } json["lifecycle"] = nlohmann::json{{"rule", std::move(value)}}; } void ToJsonLocation(nlohmann::json& json, BucketMetadata const& meta) { SetIfNotEmpty(json, "location", meta.location()); } void ToJsonLocationType(nlohmann::json& json, BucketMetadata const& meta) { SetIfNotEmpty(json, "locationType", meta.location_type()); } void ToJsonLogging(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_logging()) return; nlohmann::json value; SetIfNotEmpty(value, "logBucket", meta.logging().log_bucket); SetIfNotEmpty(value, "logObjectPrefix", meta.logging().log_object_prefix); json["logging"] = std::move(value); } void ToJsonName(nlohmann::json& json, BucketMetadata const& meta) { SetIfNotEmpty(json, "name", meta.name()); } void ToJsonRetentionPolicy(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_retention_policy()) return; json["retentionPolicy"] = nlohmann::json{ {"retentionPeriod", meta.retention_policy().retention_period.count()}}; } void ToJsonRpo(nlohmann::json& json, BucketMetadata const& meta) { SetIfNotEmpty(json, "rpo", meta.rpo()); } void ToJsonStorageClass(nlohmann::json& json, BucketMetadata const& meta) { SetIfNotEmpty(json, "storageClass", meta.storage_class()); } void ToJsonVersioning(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.versioning().has_value()) return; json["versioning"] = nlohmann::json{{"enabled", meta.versioning()->enabled}}; } void ToJsonWebsite(nlohmann::json& json, BucketMetadata const& meta) { if (!meta.has_website()) return; nlohmann::json value; SetIfNotEmpty(value, "mainPageSuffix", meta.website().main_page_suffix); SetIfNotEmpty(value, "notFoundPage", meta.website().not_found_page); json["website"] = std::move(value); } } // namespace StatusOr<BucketMetadata> BucketMetadataParser::FromJson( nlohmann::json const& json) { if (!json.is_object()) { return Status(StatusCode::kInvalidArgument, __func__); } using Parser = std::function<Status(BucketMetadata&, nlohmann::json const&)>; Parser parsers[] = { [](BucketMetadata& meta, nlohmann::json const& json) { return CommonMetadataParser<BucketMetadata>::FromJson(meta, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseAcl(meta.acl_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseBilling(meta.billing_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseCorsList(meta.cors_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseDefaultEventBasedHold(meta.default_event_based_hold_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseDefaultObjectAcl(meta.default_acl_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseEncryption(meta.encryption_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseIamConfiguration(meta.iam_configuration_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseLifecycle(meta.lifecycle_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { meta.location_ = json.value("location", ""); return Status{}; }, [](BucketMetadata& meta, nlohmann::json const& json) { meta.location_type_ = json.value("locationType", ""); return Status{}; }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseLogging(meta.logging_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseProjectNumber(meta.project_number_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { meta.labels_ = ParseLabels(json); return Status{}; }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseRetentionPolicy(meta.retention_policy_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { meta.rpo_ = json.value("rpo", ""); return Status{}; }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseVersioning(meta.versioning_, json); }, [](BucketMetadata& meta, nlohmann::json const& json) { return ParseWebsite(meta.website_, json); }, }; BucketMetadata meta{}; for (auto const& p : parsers) { auto status = p(meta, json); if (!status.ok()) return status; } return meta; } StatusOr<BucketMetadata> BucketMetadataParser::FromString( std::string const& payload) { auto json = nlohmann::json::parse(payload, nullptr, false); return FromJson(json); } std::string BucketMetadataToJsonString(BucketMetadata const& meta) { nlohmann::json json; ToJsonAcl(json, meta); ToJsonBilling(json, meta); ToJsonCors(json, meta); ToJsonDefaultEventBasedHold(json, meta); ToJsonDefaultAcl(json, meta); ToJsonEncryption(json, meta); ToJsonIamConfiguration(json, meta); ToJsonLabels(json, meta); ToJsonLifecycle(json, meta); ToJsonLocation(json, meta); ToJsonLocationType(json, meta); ToJsonLogging(json, meta); ToJsonName(json, meta); ToJsonRetentionPolicy(json, meta); ToJsonRpo(json, meta); ToJsonStorageClass(json, meta); ToJsonVersioning(json, meta); ToJsonWebsite(json, meta); return json.dump(); } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_ASYNC_READ_WRITE_STREAM_AUTH_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_ASYNC_READ_WRITE_STREAM_AUTH_H #include "google/cloud/internal/async_read_write_stream_impl.h" #include "google/cloud/internal/unified_grpc_credentials.h" #include "google/cloud/version.h" #include <functional> #include <memory> namespace google { namespace cloud { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { template <typename Request, typename Response> class AsyncStreamingReadWriteRpcAuth : public AsyncStreamingReadWriteRpc<Request, Response>, public std::enable_shared_from_this< AsyncStreamingReadWriteRpcAuth<Request, Response>> { public: using StreamFactory = std::function< std::shared_ptr<AsyncStreamingReadWriteRpc<Request, Response>>( std::unique_ptr<grpc::ClientContext>)>; AsyncStreamingReadWriteRpcAuth( std::unique_ptr<grpc::ClientContext> context, std::shared_ptr<GrpcAuthenticationStrategy> auth, StreamFactory factory) : context_(std::move(context)), auth_(std::move(auth)), factory_(std::move(factory)) {} void Cancel() override { if (context_) return context_->TryCancel(); if (stream_) return stream_->Cancel(); } future<bool> Start() override { using Result = StatusOr<std::unique_ptr<grpc::ClientContext>>; auto weak = std::weak_ptr<AsyncStreamingReadWriteRpcAuth>(this->shared_from_this()); return auth_->AsyncConfigureContext(std::move(context_)) .then([weak](future<Result> f) mutable { if (auto self = weak.lock()) return self->OnStart(f.get()); return make_ready_future(false); }); } future<absl::optional<Response>> Read() override { if (!stream_) return make_ready_future(absl::optional<Response>{}); return stream_->Read(); } future<bool> Write(Request const& request, grpc::WriteOptions options) override { if (!stream_) return make_ready_future(false); return stream_->Write(request, std::move(options)); } future<bool> WritesDone() override { if (!stream_) return make_ready_future(false); return stream_->WritesDone(); } future<Status> Finish() override { if (!stream_) { return make_ready_future( Status(StatusCode::kInvalidArgument, "uninitialized GrpcReadWriteStreamAuth<>")); } return stream_->Finish(); } private: future<bool> OnStart(StatusOr<std::unique_ptr<grpc::ClientContext>> context) { if (!context) { stream_ = absl::make_unique<AsyncStreamingReadWriteRpcError<Request, Response>>( std::move(context).status()); return make_ready_future(false); } stream_ = factory_(*std::move(context)); return stream_->Start(); } std::unique_ptr<grpc::ClientContext> context_; std::shared_ptr<GrpcAuthenticationStrategy> auth_; StreamFactory factory_; std::shared_ptr<AsyncStreamingReadWriteRpc<Request, Response>> stream_; }; } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_INTERNAL_ASYNC_READ_WRITE_STREAM_AUTH_H <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/pubsub/internal/defaults.h" #include "google/cloud/pubsub/options.h" #include "google/cloud/common_options.h" #include "google/cloud/connection_options.h" #include "google/cloud/grpc_options.h" #include "google/cloud/internal/getenv.h" #include "google/cloud/internal/user_agent_prefix.h" #include "google/cloud/options.h" #include <chrono> #include <limits> #include <thread> namespace google { namespace cloud { namespace pubsub_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using std::chrono::seconds; using ms = std::chrono::milliseconds; std::size_t DefaultThreadCount() { auto constexpr kDefaultThreadCount = 4; auto const n = std::thread::hardware_concurrency(); return n == 0 ? kDefaultThreadCount : n; } Options DefaultCommonOptions(Options opts) { auto emulator = internal::GetEnv("PUBSUB_EMULATOR_HOST"); if (emulator.has_value()) { opts.set<EndpointOption>(*emulator).set<GrpcCredentialOption>( grpc::InsecureChannelCredentials()); } if (!opts.has<EndpointOption>()) { opts.set<EndpointOption>("pubsub.googleapis.com"); } if (!opts.has<GrpcCredentialOption>()) { opts.set<GrpcCredentialOption>(grpc::GoogleDefaultCredentials()); } if (!opts.has<GrpcNumChannelsOption>()) { opts.set<GrpcNumChannelsOption>(static_cast<int>(DefaultThreadCount())); } if (!opts.has<TracingComponentsOption>()) { opts.set<TracingComponentsOption>(internal::DefaultTracingComponents()); } if (!opts.has<GrpcTracingOptionsOption>()) { opts.set<GrpcTracingOptionsOption>(internal::DefaultTracingOptions()); } if (!opts.has<pubsub::RetryPolicyOption>()) { opts.set<pubsub::RetryPolicyOption>( pubsub::LimitedTimeRetryPolicy(std::chrono::seconds(60)).clone()); } if (!opts.has<pubsub::BackoffPolicyOption>()) { opts.set<pubsub::BackoffPolicyOption>( pubsub::ExponentialBackoffPolicy(std::chrono::milliseconds(100), std::chrono::seconds(60), 1.3) .clone()); } if (opts.get<GrpcBackgroundThreadPoolSizeOption>() == 0) { opts.set<GrpcBackgroundThreadPoolSizeOption>(DefaultThreadCount()); } // Enforce Constraints auto& num_channels = opts.lookup<GrpcNumChannelsOption>(); num_channels = (std::max)(num_channels, 1); // Inserts our user-agent string at the front. auto& products = opts.lookup<UserAgentProductsOption>(); products.insert(products.begin(), internal::UserAgentPrefix()); return opts; } Options DefaultPublisherOptions(Options opts) { return DefaultCommonOptions(DefaultPublisherOptionsOnly(std::move(opts))); } Options DefaultPublisherOptionsOnly(Options opts) { if (!opts.has<pubsub::MaxHoldTimeOption>()) { opts.set<pubsub::MaxHoldTimeOption>(ms(10)); } if (!opts.has<pubsub::MaxBatchMessagesOption>()) { opts.set<pubsub::MaxBatchMessagesOption>(100); } if (!opts.has<pubsub::MaxBatchBytesOption>()) { opts.set<pubsub::MaxBatchBytesOption>(1024 * 1024L); } if (!opts.has<pubsub::MaxPendingBytesOption>()) { opts.set<pubsub::MaxPendingBytesOption>( (std::numeric_limits<std::size_t>::max)()); } if (!opts.has<pubsub::MaxPendingMessagesOption>()) { opts.set<pubsub::MaxPendingMessagesOption>( (std::numeric_limits<std::size_t>::max)()); } if (!opts.has<pubsub::MessageOrderingOption>()) { opts.set<pubsub::MessageOrderingOption>(false); } if (!opts.has<pubsub::FullPublisherActionOption>()) { opts.set<pubsub::FullPublisherActionOption>( pubsub::FullPublisherAction::kBlocks); } return opts; } Options DefaultSubscriberOptions(Options opts) { return DefaultCommonOptions(DefaultSubscriberOptionsOnly(std::move(opts))); } Options DefaultSubscriberOptionsOnly(Options opts) { if (!opts.has<pubsub::MaxDeadlineTimeOption>()) { opts.set<pubsub::MaxDeadlineTimeOption>(seconds(0)); } if (!opts.has<pubsub::MaxDeadlineExtensionOption>()) { opts.set<pubsub::MaxDeadlineExtensionOption>(seconds(600)); } if (!opts.has<pubsub::MaxOutstandingMessagesOption>()) { opts.set<pubsub::MaxOutstandingMessagesOption>(1000); } if (!opts.has<pubsub::MaxOutstandingBytesOption>()) { opts.set<pubsub::MaxOutstandingBytesOption>(100 * 1024 * 1024L); } if (opts.get<pubsub::MaxConcurrencyOption>() == 0) { opts.set<pubsub::MaxConcurrencyOption>(DefaultThreadCount()); } if (!opts.has<pubsub::ShutdownPollingPeriodOption>()) { opts.set<pubsub::ShutdownPollingPeriodOption>(seconds(5)); } // Subscribers are special: by default we want to retry essentially forever // because (a) the service will disconnect the streaming pull from time to // time, but that is not a "failure", (b) applications can change this // behavior if they need, and this is easier than some hard-coded "treat these // disconnects as non-failures" code. if (!opts.has<pubsub::RetryPolicyOption>()) { opts.set<pubsub::RetryPolicyOption>( pubsub::LimitedErrorCountRetryPolicy((std::numeric_limits<int>::max)()) .clone()); } // Enforce constraints auto& extension = opts.lookup<pubsub::MaxDeadlineExtensionOption>(); extension = (std::max)((std::min)(extension, seconds(600)), seconds(10)); auto& messages = opts.lookup<pubsub::MaxOutstandingMessagesOption>(); messages = std::max<std::int64_t>(0, messages); auto& bytes = opts.lookup<pubsub::MaxOutstandingBytesOption>(); bytes = std::max<std::int64_t>(0, bytes); return opts; } GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace pubsub_internal } // namespace cloud } // namespace google <file_sep>// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include "google/cloud/storage/internal/bucket_requests.h" #include "google/cloud/storage/internal/bucket_acl_requests.h" #include "google/cloud/storage/internal/bucket_metadata_parser.h" #include "google/cloud/internal/absl_str_join_quiet.h" #include "google/cloud/internal/format_time_point.h" #include <nlohmann/json.hpp> #include <sstream> namespace google { namespace cloud { namespace storage { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN namespace internal { namespace { void DiffAcl(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.acl() != u.acl()) builder.SetAcl(u.acl()); } void DiffBilling(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.billing_as_optional() == u.billing_as_optional()) return; if (u.has_billing()) { builder.SetBilling(u.billing()); } else { builder.ResetBilling(); } } void DiffCors(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.cors() != u.cors()) builder.SetCors(u.cors()); } void DiffEventBasedHold(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.default_event_based_hold() != u.default_event_based_hold()) { builder.SetDefaultEventBasedHold(u.default_event_based_hold()); } } void DiffDefaultObjectAcl(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.default_acl() != u.default_acl()) { builder.SetDefaultAcl(u.default_acl()); } } void DiffEncryption(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.encryption_as_optional() == u.encryption_as_optional()) return; if (u.has_encryption()) { builder.SetEncryption(u.encryption()); } else { builder.ResetEncryption(); } } void DiffIamConfiguration(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.iam_configuration_as_optional() == u.iam_configuration_as_optional()) { return; } if (u.has_iam_configuration()) { builder.SetIamConfiguration(u.iam_configuration()); } else { builder.ResetIamConfiguration(); } } void DiffLabels(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.labels() == u.labels()) return; if (u.labels().empty()) { builder.ResetLabels(); return; } std::map<std::string, std::string> difference; // Find the keys in the original map that are not in the new map: std::set_difference(o.labels().begin(), o.labels().end(), u.labels().begin(), u.labels().end(), std::inserter(difference, difference.end()), // We want to compare just keys and ignore values, the // map class provides such a function, so use it: o.labels().value_comp()); for (auto&& d : difference) { builder.ResetLabel(d.first); } // Find the elements (comparing key and value) in the updated map that // are not in the original map: difference.clear(); std::set_difference(u.labels().begin(), u.labels().end(), o.labels().begin(), o.labels().end(), std::inserter(difference, difference.end())); for (auto&& d : difference) { builder.SetLabel(d.first, d.second); } } void DiffLifecycle(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.lifecycle_as_optional() == u.lifecycle_as_optional()) return; if (u.has_lifecycle()) { builder.SetLifecycle(u.lifecycle()); } else { builder.ResetLifecycle(); } } void DiffLogging(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.logging_as_optional() == u.logging_as_optional()) return; if (u.has_logging()) { builder.SetLogging(u.logging()); } else { builder.ResetLogging(); } } void DiffName(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.name() != u.name()) builder.SetName(u.name()); } void DiffRetentionPolicy(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.retention_policy_as_optional() == u.retention_policy_as_optional()) { return; } if (u.has_retention_policy()) { builder.SetRetentionPolicy(u.retention_policy()); } else { builder.ResetRetentionPolicy(); } } void DiffStorageClass(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.storage_class() != u.storage_class()) { builder.SetStorageClass(u.storage_class()); } } void DiffRpo(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.rpo() != u.rpo()) builder.SetRpo(u.rpo()); } void DiffVersioning(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.versioning() == u.versioning()) return; if (u.has_versioning()) { builder.SetVersioning(*u.versioning()); } else { builder.ResetVersioning(); } } void DiffWebsite(BucketMetadataPatchBuilder& builder, BucketMetadata const& o, BucketMetadata const& u) { if (o.website_as_optional() == u.website_as_optional()) return; if (u.has_website()) { builder.SetWebsite(u.website()); } else { builder.ResetWebsite(); } } BucketMetadataPatchBuilder DiffBucketMetadata(BucketMetadata const& original, BucketMetadata const& updated) { // Compare each modifiable field to build the patch BucketMetadataPatchBuilder builder; DiffAcl(builder, original, updated); DiffBilling(builder, original, updated); DiffCors(builder, original, updated); DiffEventBasedHold(builder, original, updated); DiffDefaultObjectAcl(builder, original, updated); DiffEncryption(builder, original, updated); DiffIamConfiguration(builder, original, updated); DiffLabels(builder, original, updated); DiffLifecycle(builder, original, updated); DiffLogging(builder, original, updated); DiffName(builder, original, updated); DiffRetentionPolicy(builder, original, updated); DiffRpo(builder, original, updated); DiffStorageClass(builder, original, updated); DiffVersioning(builder, original, updated); DiffWebsite(builder, original, updated); return builder; } } // namespace std::string CreateBucketRequest::json_payload() const { return BucketMetadataToJsonString(metadata_); } std::string UpdateBucketRequest::json_payload() const { return BucketMetadataToJsonString(metadata_); } std::ostream& operator<<(std::ostream& os, ListBucketsRequest const& r) { os << "ListBucketsRequest={project_id=" << r.project_id(); r.DumpOptions(os, ", "); return os << "}"; } StatusOr<ListBucketsResponse> ListBucketsResponse::FromHttpResponse( std::string const& payload) { auto json = nlohmann::json::parse(payload, nullptr, false); if (!json.is_object()) { return Status(StatusCode::kInvalidArgument, __func__); } ListBucketsResponse result; result.next_page_token = json.value("nextPageToken", ""); for (auto const& kv : json["items"].items()) { auto parsed = internal::BucketMetadataParser::FromJson(kv.value()); if (!parsed) { return std::move(parsed).status(); } result.items.emplace_back(std::move(*parsed)); } return result; } std::ostream& operator<<(std::ostream& os, ListBucketsResponse const& r) { os << "ListBucketsResponse={next_page_token=" << r.next_page_token << ", items={"; std::copy(r.items.begin(), r.items.end(), std::ostream_iterator<BucketMetadata>(os, "\n ")); return os << "}}"; } std::ostream& operator<<(std::ostream& os, GetBucketMetadataRequest const& r) { os << "GetBucketMetadataRequest={bucket_name=" << r.bucket_name(); r.DumpOptions(os, ", "); return os << "}"; } std::ostream& operator<<(std::ostream& os, CreateBucketRequest const& r) { os << "CreateBucketRequest={project_id=" << r.project_id() << ", metadata=" << r.metadata(); r.DumpOptions(os, ", "); return os << "}"; } std::ostream& operator<<(std::ostream& os, DeleteBucketRequest const& r) { os << "DeleteBucketRequest={bucket_name=" << r.bucket_name(); r.DumpOptions(os, ", "); return os << "}"; } std::ostream& operator<<(std::ostream& os, UpdateBucketRequest const& r) { os << "UpdateBucketRequest={metadata=" << r.metadata(); r.DumpOptions(os, ", "); return os << "}"; } PatchBucketRequest::PatchBucketRequest(std::string bucket, BucketMetadata const& original, BucketMetadata const& updated) : bucket_(std::move(bucket)), payload_(DiffBucketMetadata(original, updated).BuildPatch()) {} PatchBucketRequest::PatchBucketRequest(std::string bucket, BucketMetadataPatchBuilder const& patch) : bucket_(std::move(bucket)), payload_(patch.BuildPatch()) {} std::ostream& operator<<(std::ostream& os, PatchBucketRequest const& r) { os << "PatchBucketRequest={bucket_name=" << r.bucket(); r.DumpOptions(os, ", "); return os << ", payload=" << r.payload() << "}"; } std::ostream& operator<<(std::ostream& os, GetBucketIamPolicyRequest const& r) { os << "GetBucketIamPolicyRequest={bucket_name=" << r.bucket_name(); r.DumpOptions(os, ", "); return os << "}"; } namespace { Status ValidateIamBinding(nlohmann::json const& binding, std::string const& name, std::string const& payload) { if (!binding.is_object()) { std::ostringstream os; os << "Invalid IamPolicy payload, expected objects for 'bindings' " "entries. Consider using the *NativeIamPolicy() member functions." << " payload=" << payload; return Status(StatusCode::kInvalidArgument, os.str()); } for (auto const& binding_kv : binding.items()) { auto const& key = binding_kv.key(); if (key != "members" && key != "role") { std::ostringstream os; os << "Invalid IamPolicy payload, unexpected member '" << key << "' in element #" << name << ". payload=" << payload; return Status(StatusCode::kInvalidArgument, os.str()); } } if (binding.count("role") == 0 or binding.count("members") == 0) { std::ostringstream os; os << "Invalid IamPolicy payload, expected 'role' and 'members'" << " fields for element #" << name << ". payload=" << payload; return Status(StatusCode::kInvalidArgument, os.str()); } if (!binding["members"].is_array()) { std::ostringstream os; os << "Invalid IamPolicy payload, expected array for 'members'" << " fields for element #" << name << ". payload=" << payload; return Status(StatusCode::kInvalidArgument, os.str()); } return Status{}; } } // namespace // TODO(#5929) - remove after decommission is completed #include "google/cloud/internal/disable_deprecation_warnings.inc" StatusOr<IamPolicy> ParseIamPolicyFromString(std::string const& payload) { auto json = nlohmann::json::parse(payload, nullptr, false); if (!json.is_object()) { return Status(StatusCode::kInvalidArgument, __func__); } IamPolicy policy; policy.version = 0; policy.etag = json.value("etag", ""); if (json.count("bindings") != 0) { if (!json["bindings"].is_array()) { std::ostringstream os; os << "Invalid IamPolicy payload, expected array for 'bindings' " "field." << " payload=" << payload; return Status(StatusCode::kInvalidArgument, os.str()); } for (auto const& kv : json["bindings"].items()) { auto const& binding = kv.value(); auto valid = ValidateIamBinding(binding, kv.key(), payload); if (!valid.ok()) return valid; std::string role = binding.value("role", ""); for (auto const& member : binding["members"].items()) { policy.bindings.AddMember(role, member.value()); } } } return policy; } SetBucketIamPolicyRequest::SetBucketIamPolicyRequest( std::string bucket_name, google::cloud::IamPolicy const& policy) : bucket_name_(std::move(bucket_name)) { nlohmann::json iam{{"kind", "storage#policy"}, {"etag", policy.etag}, {"version", policy.version}}; nlohmann::json bindings; for (auto const& binding : policy.bindings) { nlohmann::json b{ {"role", binding.first}, }; nlohmann::json m; for (auto const& member : binding.second) { m.emplace_back(member); } b["members"] = std::move(m); bindings.emplace_back(std::move(b)); } iam["bindings"] = std::move(bindings); json_payload_ = iam.dump(); } // TODO(#5929) - remove after decommission is completed #include "google/cloud/internal/diagnostics_pop.inc" std::ostream& operator<<(std::ostream& os, SetBucketIamPolicyRequest const& r) { os << "GetBucketIamPolicyRequest={bucket_name=" << r.bucket_name(); r.DumpOptions(os, ", "); return os << ", json_payload=" << r.json_payload() << "}"; } SetNativeBucketIamPolicyRequest::SetNativeBucketIamPolicyRequest( std::string bucket_name, NativeIamPolicy const& policy) : bucket_name_(std::move(bucket_name)), json_payload_(policy.ToJson()) { if (!policy.etag().empty()) { set_option(IfMatchEtag(policy.etag())); } } std::ostream& operator<<(std::ostream& os, SetNativeBucketIamPolicyRequest const& r) { os << "SetNativeBucketIamPolicyRequest={bucket_name=" << r.bucket_name(); r.DumpOptions(os, ", "); return os << ", json_payload=" << r.json_payload() << "}"; } std::ostream& operator<<(std::ostream& os, TestBucketIamPermissionsRequest const& r) { os << "TestBucketIamPermissionsRequest={bucket_name=" << r.bucket_name() << ", permissions=["; os << absl::StrJoin(r.permissions(), ", "); os << "]"; r.DumpOptions(os, ", "); return os << "}"; } StatusOr<TestBucketIamPermissionsResponse> TestBucketIamPermissionsResponse::FromHttpResponse(std::string const& payload) { TestBucketIamPermissionsResponse result; auto json = nlohmann::json::parse(payload, nullptr, false); if (!json.is_object()) { return Status(StatusCode::kInvalidArgument, __func__); } for (auto const& kv : json["permissions"].items()) { result.permissions.emplace_back(kv.value().get<std::string>()); } return result; } std::ostream& operator<<(std::ostream& os, TestBucketIamPermissionsResponse const& r) { os << "TestBucketIamPermissionsResponse={permissions=["; os << absl::StrJoin(r.permissions, ", "); return os << "]}"; } std::ostream& operator<<(std::ostream& os, LockBucketRetentionPolicyRequest const& r) { os << "LockBucketRetentionPolicyRequest={bucket_name=" << r.bucket_name() << ", metageneration=" << r.metageneration(); r.DumpOptions(os, ", "); return os << "}"; } } // namespace internal GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace storage } // namespace cloud } // namespace google <file_sep>// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated by the Codegen C++ plugin. // If you make any local changes, they will be lost. // source: google/spanner/admin/database/v1/spanner_database_admin.proto #ifndef GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CONNECTION_H #define GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CONNECTION_H #include "google/cloud/spanner/admin/database_admin_connection_idempotency_policy.h" #include "google/cloud/spanner/admin/internal/database_admin_stub.h" #include "google/cloud/spanner/admin/retry_traits.h" #include "google/cloud/backoff_policy.h" #include "google/cloud/future.h" #include "google/cloud/options.h" #include "google/cloud/polling_policy.h" #include "google/cloud/status_or.h" #include "google/cloud/stream_range.h" #include "google/cloud/version.h" #include <google/longrunning/operations.grpc.pb.h> #include <memory> namespace google { namespace cloud { namespace spanner_admin { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN using DatabaseAdminRetryPolicy = ::google::cloud::internal::TraitBasedRetryPolicy< spanner_admin_internal::DatabaseAdminRetryTraits>; using DatabaseAdminLimitedTimeRetryPolicy = ::google::cloud::internal::LimitedTimeRetryPolicy< spanner_admin_internal::DatabaseAdminRetryTraits>; using DatabaseAdminLimitedErrorCountRetryPolicy = ::google::cloud::internal::LimitedErrorCountRetryPolicy< spanner_admin_internal::DatabaseAdminRetryTraits>; class DatabaseAdminConnection { public: virtual ~DatabaseAdminConnection() = 0; virtual StreamRange<google::spanner::admin::database::v1::Database> ListDatabases( google::spanner::admin::database::v1::ListDatabasesRequest request); virtual future<StatusOr<google::spanner::admin::database::v1::Database>> CreateDatabase( google::spanner::admin::database::v1::CreateDatabaseRequest const& request); virtual StatusOr<google::spanner::admin::database::v1::Database> GetDatabase( google::spanner::admin::database::v1::GetDatabaseRequest const& request); virtual future< StatusOr<google::spanner::admin::database::v1::UpdateDatabaseDdlMetadata>> UpdateDatabaseDdl( google::spanner::admin::database::v1::UpdateDatabaseDdlRequest const& request); virtual Status DropDatabase( google::spanner::admin::database::v1::DropDatabaseRequest const& request); virtual StatusOr<google::spanner::admin::database::v1::GetDatabaseDdlResponse> GetDatabaseDdl( google::spanner::admin::database::v1::GetDatabaseDdlRequest const& request); virtual StatusOr<google::iam::v1::Policy> SetIamPolicy( google::iam::v1::SetIamPolicyRequest const& request); virtual StatusOr<google::iam::v1::Policy> GetIamPolicy( google::iam::v1::GetIamPolicyRequest const& request); virtual StatusOr<google::iam::v1::TestIamPermissionsResponse> TestIamPermissions(google::iam::v1::TestIamPermissionsRequest const& request); virtual future<StatusOr<google::spanner::admin::database::v1::Backup>> CreateBackup( google::spanner::admin::database::v1::CreateBackupRequest const& request); virtual StatusOr<google::spanner::admin::database::v1::Backup> GetBackup( google::spanner::admin::database::v1::GetBackupRequest const& request); virtual StatusOr<google::spanner::admin::database::v1::Backup> UpdateBackup( google::spanner::admin::database::v1::UpdateBackupRequest const& request); virtual Status DeleteBackup( google::spanner::admin::database::v1::DeleteBackupRequest const& request); virtual StreamRange<google::spanner::admin::database::v1::Backup> ListBackups( google::spanner::admin::database::v1::ListBackupsRequest request); virtual future<StatusOr<google::spanner::admin::database::v1::Database>> RestoreDatabase( google::spanner::admin::database::v1::RestoreDatabaseRequest const& request); virtual StreamRange<google::longrunning::Operation> ListDatabaseOperations( google::spanner::admin::database::v1::ListDatabaseOperationsRequest request); virtual StreamRange<google::longrunning::Operation> ListBackupOperations( google::spanner::admin::database::v1::ListBackupOperationsRequest request); }; std::shared_ptr<DatabaseAdminConnection> MakeDatabaseAdminConnection( Options options = {}); GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin } // namespace cloud } // namespace google namespace google { namespace cloud { namespace spanner_admin_internal { GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_BEGIN std::shared_ptr<spanner_admin::DatabaseAdminConnection> MakeDatabaseAdminConnection(std::shared_ptr<DatabaseAdminStub> stub, Options options); GOOGLE_CLOUD_CPP_INLINE_NAMESPACE_END } // namespace spanner_admin_internal } // namespace cloud } // namespace google #endif // GOOGLE_CLOUD_CPP_GOOGLE_CLOUD_SPANNER_ADMIN_DATABASE_ADMIN_CONNECTION_H
1e3c90c358c57c2a69c727ab1113ae421ed37d1b
[ "C++", "Shell" ]
16
C++
AditiThirdEye/google-cloud-cpp
5c74d4f9388293b3b758e0d321d6267220a8107c
14d9f62f23fa12f634469d6f27c93f380b351021
refs/heads/master
<file_sep>#include <iostream> #include <string> using namespace std; int main(void) { cout << "Vitejte v kalkulacce" << endl; printf("Zadejte prvni cislo: "); float a; cin >> a; printf("Zadejte druhe cislo:"); float b; cin >> b; printf("Zvolte si operaci:"); printf("1 - scitani "); printf("2 - odcitani "); printf("3 - nasobeni "); printf("4 - deleni "); printf("5 - mocnica A "); printf("6 - mocnica B "); printf("7 - odmocnina A "); printf("8 - odmocnica B "); int volba; cin >> volba; float vysledek = 0; if (volba == 1) vysledek = a + b; else if (volba == 2) vysledek = a - b; else if (volba == 3) vysledek = a * b; else if (volba == 4) vysledek = a / b; else if (volba == 5) vysledek = a * a; else if (volba == 6) vysledek = sqrt(a); else if (volba == 7) vysledek = b * b; else if (volba == 8) vysledek = sqrt(b); if ((volba > 0) && (volba < 9)) cout << "Vysledek: " << vysledek << endl; else printf("Neplatna volba"); printf("Dekuji za pouziti kalkulacky, aplikaci ukoncite libovolnou klavesou."); cin.get(); cin.get(); return 0; }
1dea77e9348e9f729219a51d8a4fcef27bf0b413
[ "C++" ]
1
C++
Javorxdd/calculator
2f5cd20d3a0fbeadd6ab1f53f1ffa44d13424c81
41630ac151d07bf5d78a2bdf858b9fc4c09cb347
refs/heads/master
<repo_name>muchrm/golang-img-merge<file_sep>/main.go package main import ( "fmt" "io" "log" "net/http" "os" "github.com/muchrm/golang-img-merge/imgmerge" ) var ( first = []string{} second = []string{} ) func showIndex(w http.ResponseWriter, r *http.Request) { fmt.Fprintf(w, `<!DOCTYPE html> <html> <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.4/angular.js"></script> <script type="text/javascript" src="https://angular-file-upload.appspot.com/js/ng-file-upload-shim.js"></script> <script type="text/javascript" src="https://angular-file-upload.appspot.com/js/ng-file-upload.js"></script> <script type='text/javascript'> var app = angular.module('fileUpload', ['ngFileUpload']); app.controller('MyCtrl', ['$scope', 'Upload', '$timeout', '$http', function ($scope, Upload, $timeout, $http) { $scope.uploadFiles = function (files, files2) { $scope.files = files; if (files && files.length) { Upload.upload({ url: '/first', data: { files: files } }).then(function (response) { Upload.upload({ url: '/second', data: { files: files2 } }).then(function (response) { $http.get("/run") .then(function (response) { alert(response.data); }); }); }) } }; }]); </script> </head> <body> <body ng-app="fileUpload" ng-controller="MyCtrl"> <form name="myForm"> <fieldset> <legend>Upload on form submit</legend> <br>เลือกลาย: <input type="file" ngf-select ng-model="$files" multiple name="file" accept="image/*" ngf-max-size="2MB" required ngf-model-invalid="errorFile" /> <br>เลือกเสื้อ: <input type="file" ngf-select ng-model="$files2" multiple name="file" accept="image/*" ngf-max-size="2MB" required ngf-model-invalid="errorFile" /> <button ng-disabled="!myForm.$valid" ng-click="uploadFiles($files,$files2)">Submit</button> </fieldset> <br> </form> </body> </body> </html>`) } func uploadFirst(w http.ResponseWriter, r *http.Request) { reader, err := r.MultipartReader() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } //copy each part to destination. for { part, err := reader.NextPart() if err == io.EOF { break } //if part.FileName() is empty, skip this iteration. if part.FileName() == "" { continue } path := "first/" if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path, 0700) } dst, err := os.Create(path + part.FileName()) defer dst.Close() if err != nil { http.Error(w, "1"+err.Error(), http.StatusInternalServerError) return } if _, err := io.Copy(dst, part); err != nil { http.Error(w, "2"+err.Error(), http.StatusInternalServerError) return } first = append(first, part.FileName()) } } func uploadSecond(w http.ResponseWriter, r *http.Request) { reader, err := r.MultipartReader() if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } //copy each part to destination. for { part, err := reader.NextPart() if err == io.EOF { break } //if part.FileName() is empty, skip this iteration. if part.FileName() == "" { continue } path := "second/" if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path, 0700) } dst, err := os.Create(path + part.FileName()) defer dst.Close() if err != nil { http.Error(w, "1"+err.Error(), http.StatusInternalServerError) return } if _, err := io.Copy(dst, part); err != nil { http.Error(w, "2"+err.Error(), http.StatusInternalServerError) return } second = append(second, part.FileName()) } } func runImgMerge(w http.ResponseWriter, r *http.Request) { path := "out/" if _, err := os.Stat(path); os.IsNotExist(err) { os.Mkdir(path, 0700) } for _, img := range first { for _, img2 := range second { imgmerge.MergeImage("first/"+img, "second/"+img2, fmt.Sprintf("%s%s-%s", path, img, img2)) } } fmt.Fprintf(w, "เสร็จแล้วจ้า") // send data to client side } func main() { http.HandleFunc("/", showIndex) http.HandleFunc("/first", uploadFirst) http.HandleFunc("/second", uploadSecond) http.HandleFunc("/run", runImgMerge) // set router err := http.ListenAndServe(":8080", nil) // set listen port if err != nil { log.Fatal("ListenAndServe: ", err) } }
bd5e7355d76f8c9659617182612831ae4bca807a
[ "Go" ]
1
Go
muchrm/golang-img-merge
faf6abc0050fdcd959efc3a879dbc5b1f5bf9306
982d6fe145636541f21f38518427ee9c3f252b88
refs/heads/master
<file_sep><?php class Database{ protected $host; protected $database; protected $username; protected $password; public function __construct($host, $database, $username, $password){ $this->host = $host; $this->database = $database; $this->username = $username; $this->password = $password; } public function getConnection() { $connection = new mysqli($this->host, $this->username, $this->password, $this->database); // Check connection if ($connection->connect_error) { die("Connection failed: " . $connection->connect_error); } return $connection; } } ?><file_sep><?php $host = "localhost"; $username = "root"; $password = ""; $database = "timesheet"; $api_key = 'f4f458161b007ebd8a00df75d428b8bd'; $allowedHours = 8; header("Access-Control-Allow-Origin: *"); ?> <file_sep><?php class Timesheet { protected $database; protected $allowedHours; public function __construct(database $database, $allowedHours) { $this->database = $database; $this->allowedHours = $allowedHours; } public function getTasks(){ $taskQuery = "SELECT t.id, t.title, t.hours FROM dates AS d JOIN tasks AS t ON d.id = t.date_id WHERE date LIKE '" . $_GET['date'] . "'"; $result = mysqli_query($this->database->getConnection(), $taskQuery); $response = []; if ($result->num_rows > 0) { while($row = mysqli_fetch_assoc($result)) { $response[] = $row; } } echo json_encode($response); return false; } public function addTask(){ $connection = $this->database->getConnection(); $dateQuery = "SELECT id FROM dates WHERE date LIKE '" . $_GET['date'] . "'"; $result = mysqli_query($connection, $dateQuery); if ($result->num_rows > 0) { while($row = mysqli_fetch_assoc($result)) { $dateID = $row['id']; } $hoursQuery = "SELECT SUM(hours) AS hours_sum FROM tasks WHERE date_id = " . $dateID; if (($this->getHoursSum($connection, $hoursQuery) + $_GET['hours']) < $this->allowedHours) { $taskID = $this->insertTask($connection, $dateID); echo json_encode($taskID); return false; } } else { if($_GET['hours'] < $this->allowedHours) { $insertQuery = "INSERT INTO dates VALUES (NULL, '".$_GET['date']."')"; mysqli_query($connection, $insertQuery); $dateID = mysqli_insert_id($connection); $taskID = $this->insertTask($connection, $dateID); echo json_encode($taskID); return false; } } echo json_encode(false); return false; } public function editTask(){ $connection = $this->database->getConnection(); $hoursQuery = "SELECT SUM(hours) AS hours_sum from tasks join dates ON tasks.date_id = dates.id WHERE dates.date LIKE '" . $_GET['date'] . "' AND tasks.id <> " . $_GET['id']; if (($this->getHoursSum($connection, $hoursQuery) + $_GET['hours']) < $this->allowedHours) { $updateQuery = "UPDATE tasks SET title = '" . $_GET['title'] . "', hours = '" . $_GET['hours'] . "' WHERE id = " . $_GET['id']; mysqli_query($connection, $updateQuery); echo json_encode(true); return false; } echo json_encode(false); return false; } public function deleteTask(){ $deleteQuery = "DELETE FROM tasks WHERE id = " . $_GET['id']; mysqli_query($this->database->getConnection(), $deleteQuery); echo json_encode(true); return false; } public function getHoursSum($connection, $query) { $hours = mysqli_query($connection, $query); $hoursSum = mysqli_fetch_assoc($hours); return $hoursSum; } public function insertTask($connection, $dateID) { $insertQuery = "INSERT INTO tasks VALUES (NULL, ".$dateID.", '".$_GET['title']."', ".$_GET['hours'].", now(), NULL)"; mysqli_query($connection, $insertQuery); $taskID = mysqli_insert_id($connection); return $taskID; } } ?><file_sep>CREATE DATABASE timesheet CHARACTER SET utf8 COLLATE utf8_general_ci; CREATE TABLE `dates` ( `id` INT NOT NULL AUTO_INCREMENT , `date` VARCHAR(10) NOT NULL , PRIMARY KEY (`id`) ) ENGINE = InnoDB; CREATE TABLE `tasks` ( `id` INT NOT NULL AUTO_INCREMENT , `date_id` INT NOT NULL , `title` VARCHAR(250) NOT NULL , `hours` FLOAT NOT NULL , `created_at` TIMESTAMP NOT NULL DEFAULT NOW() , `updated_at` TIMESTAMP NULL DEFAULT NULL ON UPDATE NOW() , PRIMARY KEY (`id`) , FOREIGN KEY (`date_id`) REFERENCES `dates`(`id`) ) ENGINE = InnoDB;<file_sep><?php include 'config.php' ; include 'databaseClass.php'; include 'timesheetClass.php'; if(isset($_GET['api_key']) && $_GET['api_key'] == $api_key) { $database = new Database($host, $database, $username, $password); $timesheet = new Timesheet($database, $allowedHours); $action = $_GET['action']; switch($action) { case 'getTasks': $timesheet->getTasks(); break; case 'addTask': $timesheet->addTask(); break; case 'editTask': $timesheet->editTask(); break; case 'deleteTask': $timesheet->deleteTask(); break; } } ?>
d0dbba841b425aeaa1e20d5dee81308adb847ca0
[ "SQL", "PHP" ]
5
PHP
JelenaVukojevic/timesheet-api
5513345c8433d04a80c4fe6d1ba8956c48459b0c
60e14c2b283416ea014dd5e56888836ac5abf8f1
refs/heads/master
<repo_name>bluwave/SwiftSample<file_sep>/SwiftSample/viewcontrollers/MapViewController.swift // // MapViewController.swift // SwiftSample // // Created by <NAME> on 6/2/14. // // import UIKit import MapKit class MapViewController: UIViewController ,MKMapViewDelegate { @IBOutlet var map: MKMapView init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() actionGoToRegion(nil) } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) // if self.navigationController.viewControllers[self.navigationController.viewControllers.count-1] == self // { // // } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func actionGoToRegion(sender: AnyObject?) { //37.7789027,-122.4285878 let coord = CLLocationCoordinate2D(latitude: 37.7789027, longitude: -122.4285878 ) let span = MKCoordinateSpan(latitudeDelta: 0.3, longitudeDelta: 0.8) let region = MKCoordinateRegion(center: coord, span: span) self.map.setRegion(region, animated: true) } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ } <file_sep>/README.md SwiftSample =========== swift sample with custom navigation controller transition <file_sep>/SwiftSample/viewcontrollers/HomeViewController.swift // // HomeViewController.swift // SwiftSample // // Created by <NAME> on 6/2/14. // // import UIKit extension UIView { func debugBorder() { self.layer.borderColor = UIColor.redColor().CGColor self.layer.borderWidth = 1 } func debugBorder(color:UIColor) { self.layer.borderColor = color.CGColor self.layer.borderWidth = 1 } } class HomeViewController: UIViewController ,UINavigationControllerDelegate { @IBOutlet var btnMap: UIButton var mapViewController: MapViewController? init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() title = "home" debugButton() configureMapViewController() } func debugButton() { // self.btnMap.debugBorder() } func configureMapViewController() { let mapVC = MapViewController(nibName: "MapViewController", bundle: nil) self.mapViewController = mapVC insertViewControllerUnderMapButton(mapVC) println(NSStringFromCGRect(self.btnMap.frame)) mapVC.view.frame = self.btnMap.frame } func insertViewControllerUnderMapButton(viewController:UIViewController?) { if let vc = viewController { self.addChildViewController(vc) self.view.insertSubview(vc.view, belowSubview: self.btnMap) vc.didMoveToParentViewController(self) } } @IBAction func actionMapClicked(AnyObject) { if let vc = mapViewController{ self.navigationController.delegate = self self.navigationController.showViewController(vc, sender: self) } } func navigationController(navigationController: UINavigationController!, animationControllerForOperation operation: UINavigationControllerOperation, fromViewController fromVC: UIViewController!, toViewController toVC: UIViewController!) -> UIViewControllerAnimatedTransitioning! { let animator = Animator() animator.operation = operation animator.originationFrame = self.btnMap.frame return animator } } class Animator:NSObject, UIViewControllerAnimatedTransitioning { var operation:UINavigationControllerOperation var originationFrame:CGRect? init() { self.operation = .Push super.init() } func transitionDuration(transitionContext: UIViewControllerContextTransitioning!) -> NSTimeInterval { return 0.4 } func animateTransition(ctx: UIViewControllerContextTransitioning!) { let to = ctx.viewControllerForKey(UITransitionContextToViewControllerKey) let from = ctx.viewControllerForKey(UITransitionContextFromViewControllerKey) if(self.operation == .Push) { if let f = self.originationFrame{ to.view.frame = f } ctx.containerView().addSubview(to.view) UIView.animateWithDuration(transitionDuration(ctx), delay: 0, options:.CurveEaseInOut, animations: {() -> Void in // to.view.center = ctx.containerView().center to.view.frame = ctx.containerView().frame }, completion: {(Bool) -> Void in ctx.completeTransition(true) } ) } else { ctx.containerView().addSubview(to.view) let preBounds = from.view.bounds ctx.containerView().addSubview(from.view) UIView.animateWithDuration(transitionDuration(ctx), delay: 0, usingSpringWithDamping: 0.6, initialSpringVelocity: 0.8, options: .CurveEaseInOut, animations: {()->Void in // from.view.bounds = preBounds; if let f = self.originationFrame{ from.view.frame = f; } }, completion: {(Bool) -> Void in ctx.completeTransition(true) if let home = to as? HomeViewController { home.insertViewControllerUnderMapButton(from) } } ) } } }
362e1ddd3e5a32d7fa77814e2e97033fe7828db8
[ "Swift", "Markdown" ]
3
Swift
bluwave/SwiftSample
04089a922df02e17088ba51f56623a215a89eca5
dd39309e2c33dd9da19938e4de75d62a24be990a
refs/heads/main
<repo_name>TamaraKalayda/game-module-1-6.1-Kalayda<file_sep>/игра.txt field = [[" "] * 3 for i in range(3)] def show(): print(" 0 1 2") for i in range(3): rows = " ".join(field[i]) print(f"{i} {rows}") def play(): while True: moves = input("Для Вашего хода введите две координаты через пробел:").split() if len(moves) != 2: print("Ведите две координаты") continue x, y = moves x, y = int(x), int(y) if any([0 > x, x > 2, 0 > y, y > 2]): print("Нет таких координат") continue if field[x][y] != " ": print("Данная клетка уже занята. Выберите другую") continue return x, y def win(): winner = (((0, 0), (0, 1), (0, 2)), ((1, 0), (1, 1), (1, 2)), ((2, 0), (2, 1), (2, 2)), ((0, 2), (1, 1), (2, 0)), ((0, 0), (1, 1), (2, 2)), ((0, 0), (1, 0), (2, 0)), ((0, 1), (1, 1), (2, 1)), ((0, 2), (1, 2), (2, 2))) for moves in winner: symbols = [] for c in moves: symbols.append(field[c[0]][c[1]]) if symbols == ["X", "X", "X"]: print("Выиграли 'крестики'") return True if symbols == ["0", "0", "0"]: print("Выиграли 'нолики'") return True return False print("Первая введенная цифра - это номер строки, вторая - столбца") count = 0 while True: count += 1 show() if count % 2 == 1: print("Ход 'крестика'") else: print("Ход 'нолика'") x, y = play() if count % 2 == 1: field[x][y] = "X" else: field[x][y] = "0" if win(): break if count == 9: print("Игра окончена. Ничья") break
0a5ef9ba7a5df0f42ce0c49c426e95ca2e06d96d
[ "Python" ]
1
Python
TamaraKalayda/game-module-1-6.1-Kalayda
e260576fb7a1f10205dec1702fa47bc3010dc4ce
d5e68e37cdc3a6827ed41eaa0ca80f6e4c081208
refs/heads/master
<repo_name>XuChunxiao/taro3-virtual-list<file_sep>/@types/index.d.ts export { default as TaroVirtualList } from './irtualList'<file_sep>/CHANGELOG.md # Changelog All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. ### [1.0.8](https://github.com/tingyuxuan2302/taro3-virtual-list/compare/v1.0.7...v1.0.8) (2021-08-04) ### Bug Fixes * fix 服务端分页渲染bug ([00d60cc](https://github.com/tingyuxuan2302/taro3-virtual-list/commit/00d60cc660194c874ee937f628378518e40c7e8d)) ### 1.0.7 (2021-07-30) ### Bug Fixes * fix ([b76f007](https://github.com/tingyuxuan2302/taro3-virtual-list/commit/b76f007accd1be38ed556ad37f568e91e4cfe9dd)) * fix ([d831af4](https://github.com/tingyuxuan2302/taro3-virtual-list/commit/d831af4504dfb047d936464a477a13310ff93de6)) * fix ([0db69b5](https://github.com/tingyuxuan2302/taro3-virtual-list/commit/0db69b593fa8a51260fec39fbfab92a829ec1ddd))
cd04ad76602894bbc881282839a051e8c3ef7793
[ "Markdown", "TypeScript" ]
2
TypeScript
XuChunxiao/taro3-virtual-list
8adcc56abb301e287268d21047d9249f2a248290
e81f8d1506ab40161827cd3df256b2ec20d834f2
refs/heads/master
<repo_name>brainiac/cox-status<file_sep>/cox-status.py import argparse import datetime import pickle import requests import time import os import re import json import logging from influxdb_client import InfluxDBClient, Point from influxdb_client.client.write_api import SYNCHRONOUS from requests.cookies import RequestsCookieJar from hsize import human2bytes def remove_comments(js_code): pattern = r"/\*[\s\S]*?\*/" # Matches /* ... */ comments cleaned_code = re.sub(pattern, "", js_code, flags=re.MULTILINE) return cleaned_code class CoxInternetUsage: username: str password: str client: InfluxDBClient influxdb_bucket: str ssl_verify: bool cookie_jar: RequestsCookieJar | None cookie_file: str sessin: requests.Session def __init__(self, ssl_verify: bool = True, username: str = '', password: str = '', influxdb: str = '', bucket: str = '', token: str = '', org: str = ''): self.cookie_jar = None self.cookie_file = 'cox-status.bin' self.session = None self.ssl_verify = ssl_verify # todo: load from configuration self.username = username self.password = <PASSWORD> self.client = InfluxDBClient(url=influxdb, org=org, token=token) self.influxdb_bucket = bucket self._create_session() def _create_session(self, restore_cookies=True): if restore_cookies: try: with open(self.cookie_file, 'rb') as f: self.cookie_jar = pickle.load(f) print('Loaded saved login session') except Exception: self.cookie_jar = RequestsCookieJar() else: self.cookie_jar = RequestsCookieJar() self.session = requests.Session() self.session.cookies = self.cookie_jar self.session.verify = self.ssl_verify self.session.headers['User-Agent'] = \ 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) ' +\ 'Chrome/63.0.3239.84 Safari/537.36' def _do_login(self): # clear all cookies to redo login self.cookie_jar.clear() print('Trying to log in') json_data = dict(username=self.username, password=self.password) try: login_js: str = self.session.get('https://www.cox.com/content/dam/cox/okta/okta-login-v7.js').text login_js = remove_comments(login_js) keys = ['client_id', 'scope', 'base_url', 'issuer'] results = {} for key in keys: regex = re.compile(rf"^\s*var {key.upper()} = ['\"](.*)['\"];$", re.MULTILINE) match = re.search(regex, login_js) if match: results[key] = match.group(1) auth_response = self.session.post('https://login.cox.com/api/v1/authn', json=json_data).json() session_token = auth_response['sessionToken'] uri = f'{results["issuer"]}/v1/authorize?client_id={results["client_id"]}' \ f'&nonce=htM9v12ncjOc6XGMLjpPwxUE375s9RWOJRidGvviFo9uy1R1sV2H9natdLMYPEQ4' \ f'&redirect_uri=https%3A%2F%2Fwww.cox.com%2Fauthres%2Fcode' \ f'&response_type=code' \ f'&sessionToken={session_token}' \ f'&state=abc123' \ f'&scope=openid%20internal%20email' response = self.session.get(uri) response.raise_for_status() except requests.HTTPError as e: logging.exception(e) return False # find the login cookie to see if we're logged in loggedin_cookie = self.cookie_jar.get('_cidt', None, domain='.cox.com') if loggedin_cookie is not None: success = True print('Logged in!') else: print('Did\'t find session cookie!') return False # save cookies with open(self.cookie_file, 'wb') as f: pickle.dump(self.cookie_jar, f) return success def _get_with_auth(self, url) -> requests.Response: response = self.session.get(url) if response.status_code == 401 or 'Sign In to Your Cox Account' in response.text: logged_in = self._do_login() if not logged_in: print('Failed to log in') response.raise_for_status() response = self.session.get(url) response.raise_for_status() return response def get_usage_data(self, which: str) -> tuple[dict, dict]: timestamp = int(time.time()) * 1000 # milliseconds # https://www.cox.com/internettools/data-usage.html/graph/current-daily/1?_=1689055587051 # https://www.cox.com/internettools/data-usage.html/graph/monthly/1?_=1689055626095 # https://www.cox.com/internettools/data-usage.html/graph/past-daily/1?_=1689055626096 data_url = f'https://www.cox.com/internettools/data-usage.html/graph/{which}/1?_={timestamp}' response1 = self._get_with_auth(data_url) response1.raise_for_status() data = response1.json() summary_url = f'https://www.cox.com/internettools/data-usage.html' response2 = self._get_with_auth(summary_url) response2.raise_for_status() summary_text = response2.text summary_data = {} match = re.search(r"data-usage-url='(.*)'", summary_text, re.MULTILINE) if match: summary_data = json.loads(match.group(1)) return data, summary_data def publish_data(self, records: list[Point]): write_api = self.client.write_api(write_options=SYNCHRONOUS) write_api.write(bucket=self.influxdb_bucket, record=records) logging.info(f"Wrote {len(records)} records to influxdb") def process_data(self, data: dict, summary: dict) -> list[Point]: error_code = None error_message = None # check for errors if data['errorFlag']: error_code = data['error']['errorCode'] error_message = data['error']['errorMessage'] elif summary['errorFlag']: error_code = summary['error']['errorCode'] error_message = summary['error']['errorMessage'] if error_code is not None and error_message is not None: # print error and reset the session print(f'Error {error_code} - {error_message}') print('Clearing Session, will try again in an hour...') self._create_session(False) return [] gigabytes = 1024 * 1024 * 1024 today = datetime.datetime.now() current_day = today.day current_month: int = today.month current_year: int = today.year summary_data = summary['modemDetails'][0] percent_used = int(summary_data['percentageDataUsed']) / 100 data_used = human2bytes(summary_data['totalDataUsed']) data_total = human2bytes(summary_data['dataPlan']) records: list[Point] = [] data_used = float(data_used) / gigabytes data_total = float(data_total) / gigabytes print(f'monthly data used: {data_used} GB') # parse the service period service_period = summary_data['usageCycle'] service_start_str: str service_end_str: str service_start_str, service_end_str = service_period.split('-') service_start = datetime.datetime.strptime(service_start_str.strip(), '%B %d') service_end = datetime.datetime.strptime(service_end_str.strip(), '%B %d') service_start = service_start.replace(year=current_year) service_end = service_end.replace(year=current_year) if service_start.month == 12 and current_month == 1: service_start = service_start.replace(year=current_year - 1) elif service_end.month == 1 and current_month == 12: service_end = service_end.replace(year=current_year + 1) time_left = service_end - today print(f'{time_left.days} days remaining on current cycle') records.append(Point('current_monthly_usage') .field('service_period', service_period) .field('current', data_used) .field('remaining', data_total - data_used) .field('total', data_total) .field('percent_used', percent_used)) records.append(Point('current_monthly_total') .field('service_period', service_period) .field('value', data_total)) time_into = today - service_start records.append(Point('cycle_days').field('remaining', time_left.days).field('current', time_into.days)) # find today's usage usage_data = data['modemGraphDetails'][0] for data_node in usage_data['graphData']: data_date: str = data_node['text'] # 12/1 data_data: str = data_node['data'] # 23 data_month, data_day = [int(x) for x in data_date.split('/')] data_bytes = int(data_data) data_year = current_year if data_day == current_day and data_month == current_month: break if current_month == 12 and data_month == 1: data_year = current_year + 1 elif current_month == 1 and data_month == 12: data_year = current_year - 1 data_datetime = datetime.datetime(year=data_year, month=data_month, day=data_day) records.append(Point('daily_usage').time(data_datetime).field('value', data_bytes)) last_update_str = summary_data['usageDate'] match = re.match('Usage as of (.*)', last_update_str) if match: last_update_date_str = match.group(1) last_update_date = datetime.datetime.strptime(last_update_date_str, '%B %d') last_update_date = last_update_date.replace(year=current_year) if last_update_date.month == 12 and current_month == 1: last_update_date = last_update_date.replace(year=current_year - 1) elif last_update_date.month == 1 and current_month == 12: last_update_date = last_update_date.replace(year=current_year + 1) records.append(Point('last_update').field('value', last_update_date.strftime('%m/%d/%Y'))) return records def post_to_influxdb(server, data): result = requests.post(server, data=data) pass def main(): parser = argparse.ArgumentParser(description='Send cox usage statistics to influxdb') parser.add_argument('--username', help='cox account username', default=os.environ.get('COX_STATUS_USERNAME', '')) parser.add_argument('--password', help='cox account password', default=os.environ.get('COX_STATUS_PASSWORD', '')) parser.add_argument('--influxdb', help='influxdb server', default=os.environ.get('COX_STATUS_INFLUXDB_SERVER', '')) parser.add_argument('--bucket', help='influxdb bucket', default=os.environ.get('COX_STATUS_INFLUXDB_BUCKET', 'coxusage')) parser.add_argument('--token', help='influxdb token', default=os.environ.get('COX_STATUS_INFLUXDB_TOKEN', '')) parser.add_argument('--influxdb_org', help='influxdb org', default=os.environ.get('COX_STATUS_INFLUXDB_ORG', '')) args = parser.parse_args() if len(args.username) == 0 or len(args.password) == 0: raise RuntimeError('Missing username and/or password') if len(args.influxdb) == 0: raise RuntimeError('Missing influxdb server') fetcher = CoxInternetUsage(username=args.username, password=<PASSWORD>, influxdb=args.influxdb, bucket=args.bucket, token=args.token, org=args.influxdb_org) while True: try: print('Fetching usage from cox.com:') for which in ['current-daily']: data, summary = fetcher.get_usage_data(which) records = fetcher.process_data(data, summary) fetcher.publish_data(records) # sleep for an hour time.sleep(60 * 60) except Exception as e: print(f'An error occurred: {e}') # sleep for 5 minutes time.sleep(5 * 60) if __name__ == '__main__': main() <file_sep>/requirements.txt hsize==0.0.2 requests==2.31.0 influxdb-client==1.36.1<file_sep>/Dockerfile from python:3.11 MAINTAINER <EMAIL> COPY . /app WORKDIR /app RUN pip install -r requirements.txt CMD ["python", "cox-status.py"]
a428de8e6583ee2c94cf4901d392933b08a1e375
[ "Python", "Text", "Dockerfile" ]
3
Python
brainiac/cox-status
a5a5e86902c73757ffd63847fb0ed50e3d08a4bb
b2cf12b572789314a9dda72ebd17d64308400b39
refs/heads/master
<repo_name>raggedByte/Labs_6-semester<file_sep>/MZKS_labs/lab3/lab3.cpp /* Разработать генератор случайных чисел, используя метод в соответствии с номером варианта.Исследовать качество генератора, путем оценки распределения генерируемых чисел.Для этого необходимо разделить весь диапазон генерируемых чисел на 10 равных интервалов и подсчитать количество чисел, попадающих в каждый интервал. В качестве начального значения следует выбирать текущее время в формате Unix time(можно получить, используя функцию time_t time(time_t* timer)). Для линейного конгруэнтного метода значение m всегда должно быть 2^31 - 1 Вариант 4. Линейный конгруэнтный метод, a = 16807, c = 4 */ #include "windows.h" #include <cstdio> #include <time.h> ULONG I = 0; CONST ULONG a = 16807; CONST ULONG c = 4; CONST ULONG m = 2147483648 - 1; VOID SetRand(ULONG seed) { I = seed; } ULONG GetRandValue() { I = (a * I + c) % m; return I; } INT main(INT argc, PCHAR argv[]) { time_t t; ULONG range = 0, interval = 0; BOOL generate = FALSE, research = FALSE; if (argc < 2) { printf("Expected params! Use -help \n\n"); return 0; } for (INT i = 1; i < argc; i++) { if (strcmp("-help", argv[i]) == 0) { printf("Help:\n\ \t-help - get help about params\n\ \t-generate <range> - generate random values\n\ \t-research <interval> - research generated values in adjusted intervals\n"); return 0; } else if (strcmp("-generate", argv[i]) == 0) { if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } range = atoi(argv[i]); generate = TRUE; } else if (strcmp("-research", argv[i]) == 0) { if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } interval = atoi(argv[i]); research = TRUE; } else { printf("Unexpected param! Try use \"-help\"\n"); return 0; } } time(&t); SetRand((ULONG)t); printf("Lab 3. Pseudo-random sequence generators\n\n"); if (generate) { printf("Generating random values. Seed = %d, range = %d\n", I, range); for (ULONG i = 0; i < range; i++) { printf("%d.\t%ld\n", i, GetRandValue()); } printf("\n"); } if (research) { PULONG intervals, result; printf("Research random values. Interval = %d \n", interval); __try { intervals = (PULONG)malloc(sizeof(ULONG) * interval); result = (PULONG)malloc(sizeof(ULONG) * interval); if (intervals == 0 || result == 0) { printf("Error allocation memory!\n"); return -1; } } __except (EXCEPTION_EXECUTE_HANDLER) { printf("Error allocation memory!\n"); return -1; } memset(intervals, 0, sizeof(PULONG) * interval); memset(result, 0, sizeof(PULONG) * interval); for (UINT i = 1; i < interval + 1; i++) intervals[i - 1] = MAXLONG / interval * i; __try { for (ULONG k = 0; k < MAXLONG; k++) { ULONG randValue = GetRandValue(); for (UINT i = 0; i < interval; i++) { if (randValue <= intervals[i]) { result[i]++; break; } } } } __except(EXCEPTION_EXECUTE_HANDLER) { printf("Error while research values!\n"); return -1; } for (UINT i = 0; i < interval; i++) { printf("%d.\t%d\n", intervals[i], result[i]); } } return 0; } <file_sep>/MZKS_labs/lab2/encryptions.h #pragma once #include "stdio.h" #include "windows.h" typedef UINT BLOCK; typedef UINT BIT; CONST UINT key[] = { 12, 13, 30, 5, 27, 6, 11, 25, 3, 21, 22, 2, 23, 0, 8, 4, 18, 19, 10, 1, 14, 29, 9, 28, 20, 17, 26, 31, 7, 16, 15, 24 }; CONST UINT LENGTH_KEY = (sizeof(key) / sizeof(UINT)); CONST UINT SIZE_BLOCK = sizeof(BLOCK); BLOCK EncryptBlock(BLOCK block); BLOCK DecryptBlock(BLOCK block); BIT GetBit(BLOCK block, INT numBit); BIT SetBit(BLOCK block, INT numBit); BOOL encryptFile(LPCWSTR fileName); BOOL decryptFile(LPCWSTR fileName);<file_sep>/MZKS_labs/lab1/encryption.h #pragma once #include "windows.h" #include "stdio.h" CONST UINT key[] = { 1, 2, 10, 4, 8, 7, 3, 6, 9, 5 }; CONST UINT SIZE_BLOCK = (sizeof(key) / sizeof(int)); VOID EncryptBlock(PBYTE block); VOID DecryptBlock(PBYTE block); BOOL encryptFile(LPCWSTR fileName); BOOL decryptFile(LPCWSTR fileName); <file_sep>/MZKS_labs/lab1/encryption.cpp #include "encryption.h" VOID EncryptBlock(PBYTE block) { BYTE tempBlock[SIZE_BLOCK + 1] = ""; for (UINT i = 0; i < SIZE_BLOCK; i++) { tempBlock[i] = block[key[i] - 1]; } memcpy_s(block, SIZE_BLOCK + 1, tempBlock, SIZE_BLOCK + 1); } VOID DecryptBlock(PBYTE block) { BYTE tempBlock[SIZE_BLOCK + 1] = ""; for (UINT i = 0; i < SIZE_BLOCK; i++) { tempBlock[key[i] - 1] = block[i]; } memcpy_s(block, SIZE_BLOCK + 1, tempBlock, SIZE_BLOCK + 1); } BOOL encryptFile(LPCWSTR fileName) { HANDLE hSourceFile, hDestFile; DWORD dwReaded = 0, dwWrote = 0; BYTE buffer[SIZE_BLOCK + 1]; BOOL bResult = FALSE; hSourceFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSourceFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return FALSE; } hDestFile = CreateFile(TEXT("encrypted"), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hDestFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return FALSE; } DWORD dwSizeH = 0, dwSizeL = 0; dwSizeL = GetFileSize(hSourceFile, &dwSizeH); LONGLONG fileLength = ((LONGLONG)dwSizeH * ((LONGLONG)MAXDWORD + 1)) + dwSizeL; if (!WriteFile(hDestFile, &fileLength, sizeof(LONGLONG), &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } do { memset(buffer, 0, SIZE_BLOCK + 1); if (!(bResult = ReadFile(hSourceFile, buffer, SIZE_BLOCK, &dwReaded, NULL))) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } if (dwReaded) { EncryptBlock(buffer); if (!WriteFile(hDestFile, buffer, SIZE_BLOCK, &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } } } while (bResult && dwReaded); CloseHandle(hSourceFile); CloseHandle(hDestFile); return TRUE; } BOOL decryptFile(LPCWSTR fileName) { LONGLONG sourceLength; HANDLE hSourceFile, hDestFile; DWORD dwReaded = 0, dwWrote = 0; BYTE buffer[SIZE_BLOCK + 1]; hSourceFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSourceFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return FALSE; } hDestFile = CreateFile(TEXT("decrypted"), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hDestFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return FALSE; } if (!ReadFile(hSourceFile, &sourceLength, sizeof(LONGLONG), &dwReaded, NULL)) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } while (sourceLength > 0) { memset(buffer, 0, SIZE_BLOCK + 1); if (!ReadFile(hSourceFile, buffer, SIZE_BLOCK, &dwReaded, NULL)) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } if (dwReaded) { DecryptBlock(buffer); if (!WriteFile(hDestFile, buffer, sourceLength > SIZE_BLOCK ? SIZE_BLOCK : (DWORD)sourceLength, &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } } sourceLength -= SIZE_BLOCK; } CloseHandle(hSourceFile); CloseHandle(hDestFile); return TRUE; } <file_sep>/MZKS_labs/lab2/encryptions.cpp #include "encryptions.h" BOOL encryptFile(LPCWSTR fileName) { HANDLE hSourceFile, hDestFile; DWORD dwReaded = 0, dwWrote = 0; BLOCK block = 0; BOOL bResult = FALSE; hSourceFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSourceFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return FALSE; } hDestFile = CreateFile(TEXT("encrypted"), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hDestFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return -1; } DWORD dwSizeH = 0, dwSizeL = 0; dwSizeL = GetFileSize(hSourceFile, &dwSizeH); LONGLONG fileLength = ((LONGLONG)dwSizeH * ((LONGLONG)MAXDWORD + 1)) + dwSizeL; if (!WriteFile(hDestFile, &fileLength, sizeof(LONGLONG), &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } do { memset(&block, 0, SIZE_BLOCK); if (!(bResult = ReadFile(hSourceFile, &block, SIZE_BLOCK, &dwReaded, NULL))) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } if (dwReaded) { block = EncryptBlock(block); if (!WriteFile(hDestFile, &block, SIZE_BLOCK, &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } } } while (bResult && dwReaded); CloseHandle(hSourceFile); CloseHandle(hDestFile); return TRUE; } BOOL decryptFile(LPCWSTR fileName) { HANDLE hSourceFile, hDestFile; DWORD dwReaded = 0, dwWrote = 0; BLOCK block = 0; hSourceFile = CreateFile(fileName, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hSourceFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return FALSE; } hDestFile = CreateFile(TEXT("decrypted"), GENERIC_WRITE, FILE_SHARE_READ, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hDestFile == INVALID_HANDLE_VALUE) { printf("Error CreateFile! Error = %ld\n", GetLastError()); return -1; } LONGLONG sourceLength; if (!ReadFile(hSourceFile, &sourceLength, sizeof(LONGLONG), &dwReaded, NULL)) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } while (sourceLength > 0) { memset(&block, 0, SIZE_BLOCK); if (!ReadFile(hSourceFile, &block, SIZE_BLOCK, &dwReaded, NULL)) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } if (dwReaded) { block = DecryptBlock(block); if (!WriteFile(hDestFile, &block, sourceLength > SIZE_BLOCK ? SIZE_BLOCK : (DWORD)sourceLength, &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } } sourceLength -= SIZE_BLOCK; } /* memset(&block, 0, SIZE_BLOCK); if (!ReadFile(hSourceFile, &block, SIZE_BLOCK, &dwReaded, NULL)) { printf("Error ReadFile! error = %ld\n", GetLastError()); return FALSE; } block = DecryptBlock(block); if (!WriteFile(hDestFile, &block, (DWORD)sourceLength, &dwWrote, NULL)) { printf("Error WriteFile! error = %ld\n", GetLastError()); return FALSE; } */ CloseHandle(hSourceFile); CloseHandle(hDestFile); return TRUE; } BLOCK EncryptBlock(BLOCK block) { BLOCK tempBlock = 0; for (UINT i = 0; i < LENGTH_KEY; i++) { BIT tempBit = GetBit(block, key[i]); if (tempBit == 1) tempBlock = SetBit(tempBlock, i); } return tempBlock; } BLOCK DecryptBlock(BLOCK block) { BLOCK tempBlock = 0; for (UINT i = 0; i < LENGTH_KEY; i++) { BIT tempBit = GetBit(block, i); if (tempBit == 1) tempBlock = SetBit(tempBlock, key[i]); } return tempBlock; } BIT GetBit(BLOCK block, INT numBit) { return ((block & (1 << numBit)) != 0); } BIT SetBit(BLOCK block, INT numBit) { return (block | (1 << numBit)); }<file_sep>/MZKS_labs/lab1/lab1.cpp /* Разработать программу, выполняющую шифрование и расшифровывание произвольного текстового файла с использованием перестановочного шифра используя в качестве ключа последовательность, соответствующую номеру варианта. Выполнить проверку путем двоичного сравнения исходного файла и фала, полученного после расшифровывания. Вариант 4. Ключ - 1 2 10 4 8 7 3 6 9 5 */ #include "stdio.h" #include "encryption.h" INT wmain(INT argc, PWSTR argv[]) { PWSTR lpszEncryptPath = 0; PWSTR lpszDecryptPath = 0; BOOL bCompare = FALSE; printf("Lab 1. Crypt and decrypt text.\n\n"); if (argc < 2) { printf("Expected more params! Use -help for help . . .\n"); return 0; } for (INT i = 1; i < argc; i++) { if (wcscmp(TEXT("-help"), argv[i]) == 0) { printf("Help:\n\ \t-encrypt <filename> - encrypt current file and save it in root folder like \"encrypted\".\n\ \t-decrypt <filename> - decrypt current file and save it in root folder like \"decrypted\".\n\ \t-compare - compare two files and show difference. Should use with -encrypt and -decrypt!\n\ \t-checkWork <filename> - encrypt file, decrypt file and compare result decryption with source file.\n"); return 0; } else if (wcscmp(TEXT("-encrypt"), argv[i]) == 0) { if (++i >= argc) { printf("Expected file path for encrypt! Try use \"-help\n"); return 0; } lpszEncryptPath = argv[i]; } else if (wcscmp(TEXT("-decrypt"), argv[i]) == 0) { if (++i >= argc) { printf("Expected file path for decrypt! Try use \"-help\n"); return 0; } lpszDecryptPath = argv[i]; } else if (wcscmp(TEXT("-compare"), argv[i]) == 0) { bCompare = true; } else if (wcscmp(TEXT("-checkWork"), argv[i]) == 0) { if (++i >= argc) { printf("Expected file path for decrypt! Try use \"-help\n"); return 0; } lpszEncryptPath = argv[i]; lpszDecryptPath = (PWSTR)malloc(sizeof(WCHAR) * wcslen(TEXT("encrypted")) + 1); if (lpszDecryptPath == 0) { printf("Error! Cannot alloc memory!\n"); return -1; } wsprintf(lpszDecryptPath, TEXT("encrypted")); bCompare = true; } else { printf("Unexpected param! Try use \"-help\"\n"); return 0; } } if (lpszEncryptPath) { if (!encryptFile(lpszEncryptPath)) { printf("Error while prorgram encrypt file! Error = %ld\n", GetLastError()); return -1; } printf("File encrypted!\n"); } if (lpszDecryptPath) { if (!decryptFile(lpszDecryptPath)) { printf("Error while prorgram decrypt file! Error = %ld\n", GetLastError()); return -1; } printf("File decrypted!\n"); } if (bCompare) { if (lpszEncryptPath && lpszDecryptPath) { WCHAR commandLine[256]; wsprintf(commandLine, L"fc %ls decrypted", lpszEncryptPath); _wsystem(commandLine); } else { printf("Param -compare shoud use with params -encrypt and -decrypt!\n Use -help!\n"); return -1; } } }<file_sep>/MZKS_labs/lab4/lab4.cpp /* Разработать программу, выполняющую внедрение, извлечение и проверку наличия некоторых данных в файле с изображением (формат файла с изображением — BMP, не содержащий плитру и имеющий значение biBitCount равное 24). Тип операции (внедрение, извлечение и проверка), а также имена файлов, участвующих в каждой операции следует передавать в программу через командную строку. */ #include "cstdio" #include "windows.h" enum class ProgramMode{EmbedMode = 0, RetrieveMode, CheckMode}; typedef struct tagBMP { BITMAPFILEHEADER fileHeader; BITMAPINFOHEADER infoHeader; PRGBTRIPLE bitmap; PBYTE pWriter; PBYTE pReader; }BMP, *PBMP; PBMP LoadBMPFromFile(LPCWSTR lpszPathToBMP) { HANDLE hFileBMP; DWORD dwReadedByte; LONG biWidthBMP, biHeightBMP; PBMP bmp; /*Выделяем память под структуру BMP*/ bmp = (PBMP)malloc(sizeof(BMP)); if (bmp == NULL) { return FALSE; } /*Открываем файл с картинкой на чтение и проверяем открылся ли*/ hFileBMP = CreateFile(lpszPathToBMP, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFileBMP == INVALID_HANDLE_VALUE) { //printf("Error CreateFile! Error = %ld\n", GetLastError()); return NULL; } /*Читаем из файла заголовки в структуру BMP и проверяем прочитались ли*/ if (!ReadFile(hFileBMP, &(bmp->fileHeader), sizeof(BITMAPFILEHEADER), &dwReadedByte, NULL)) { return NULL; } if (!ReadFile(hFileBMP, &(bmp->infoHeader), sizeof(BITMAPINFOHEADER), &dwReadedByte, NULL)) { return NULL; } biWidthBMP = bmp->infoHeader.biWidth; biHeightBMP = bmp->infoHeader.biHeight; /*Устанавливаем указатель в файле на место, где находятся пиксели*/ SetFilePointer(hFileBMP, bmp->fileHeader.bfOffBits, NULL, FILE_BEGIN); /*Выделяем память под bitmap(массив пикселей) и проверяем выделилось ли*/ bmp->bitmap = (PRGBTRIPLE)malloc(sizeof(RGBTRIPLE) * biWidthBMP * biHeightBMP); if (bmp->bitmap == NULL) { return FALSE; } /*Устанавливаем указатели писателя и читателя (нужно для записи и чтения из файла bmp)*/ bmp->pWriter = (PBYTE)bmp->bitmap; bmp->pReader = (PBYTE)bmp->bitmap; /*В цикле читаем по пикселю и сохраняем в память*/ for (INT i = 0; i < biHeightBMP; i++) { for (INT j = 0; j < biWidthBMP; j++) { if (!ReadFile(hFileBMP, (bmp->bitmap + (DWORD)(i * biWidthBMP + j)), sizeof(RGBTRIPLE), &dwReadedByte, NULL)) { return NULL; } } SetFilePointer(hFileBMP, biWidthBMP % 4, NULL, FILE_CURRENT); } CloseHandle(hFileBMP); return bmp; } BOOL WriteBMPToFile(LPCWSTR lpszPathToFile, PBMP bmp) { HANDLE hFile; DWORD dwWrittedByte; LONG biWidthBMP, biHeightBMP; BYTE carryByte[4]; /*Зануляем массив carryByte. Данный массив нужен чтобы дописывать в файл нули*/ memset(carryByte, 0, sizeof(BYTE) * 4); /*Открываем файл с картинкой на запись. При этом содержимое файла теряется так как будем перезаписывать*/ hFile = CreateFile(lpszPathToFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("Error while oppening file!\n"); return FALSE; } biWidthBMP = bmp->infoHeader.biWidth; biHeightBMP = bmp->infoHeader.biHeight; /*Пишем в файл заголовки из bmp структуры и проверям записались ли*/ if (!WriteFile(hFile, &(bmp->fileHeader), sizeof(BITMAPFILEHEADER), &dwWrittedByte, NULL)) { printf("Cannot write in file!\n"); return FALSE; } if (!WriteFile(hFile, &(bmp->infoHeader), sizeof(BITMAPINFOHEADER), &dwWrittedByte, NULL)) { printf("Cannot write in file!\n"); return FALSE; } /*Пишем в файл массив пикселей*/ for (INT i = 0; i < biHeightBMP; i++) { for (INT j = 0; j < biWidthBMP; j++) { if (!WriteFile(hFile, (bmp->bitmap + (i * biWidthBMP + j)), sizeof(RGBTRIPLE), &dwWrittedByte, NULL)) { printf("Cannot write in file!\n"); return FALSE; } } if (!WriteFile(hFile, &carryByte, biWidthBMP % 4, &dwWrittedByte, NULL)) { printf("Cannot write in file!\n"); return FALSE; } } CloseHandle(hFile); return TRUE; } VOID WriteBytesInBMP(PVOID pInBuffer, UINT lengthBuffer, PBMP bmp) { PBYTE pBuffer = (PBYTE)pInBuffer; for (UINT k = 0; k < lengthBuffer; k++) { for (INT i = 0; i < 8; i++) { *(bmp->pWriter) = ((*pBuffer >> i) & 1) ? *(bmp->pWriter) | 1 : *(bmp->pWriter) & 254; bmp->pWriter++; } pBuffer++; } } VOID ReadBytesFromBMP(PVOID pOutBuffer, UINT lengthBuffer, PBMP bmp) { PBYTE pBuffer = (PBYTE)pOutBuffer; for (UINT k = 0; k < lengthBuffer; k++) { for (INT i = 0; i < 8; i++) { *pBuffer = (*(bmp->pReader) & 1) ? *pBuffer | (1 << i) : *pBuffer & ~(1 << i); bmp->pReader++; } pBuffer++; } } BOOL EmbedMessageInBMP(LPCWSTR lpszPathToMessage, PBMP bmp) { HANDLE hFile; DWORD dwReadedByte; DWORD dwCRC; LONG biWidthBMP, biHeightBMP; PBYTE pBuffer; /*Открываем файл с сообщением и проверяем открылся ли он*/ hFile = CreateFile(lpszPathToMessage, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { //printf("Error CreateFile! Error = %ld\n", GetLastError()); return NULL; } /*Получаем длину файла и проверяем помещается ли сообщение в bmp*/ DWORD dwSizeH = 0, dwSizeL = 0; dwSizeL = GetFileSize(hFile, &dwSizeH); LONGLONG fileLength = ((LONGLONG)dwSizeH * ((LONGLONG)MAXDWORD + 1)) + dwSizeL; if (fileLength >= MAXDWORD) { return FALSE; } biWidthBMP = bmp->infoHeader.biWidth; biHeightBMP = bmp->infoHeader.biHeight; if (biWidthBMP * biHeightBMP * 3 / 8 < fileLength + sizeof(DWORD) + sizeof(DWORD)) { return FALSE; } /*Выделяем память под буфер и читаем в него содержимое файла*/ pBuffer = (PBYTE)malloc(sizeof(BYTE) * fileLength); if (pBuffer == NULL) { return FALSE; } if (!ReadFile(hFile, pBuffer, (DWORD)fileLength, &dwReadedByte, NULL)) { return FALSE; } if (dwReadedByte == 0) { return FALSE; } /*Вычисляем контрольную сумму сообщения*/ dwCRC = RtlCrc32(pBuffer, fileLength, 0); /*Последовательно записываем контрольную сумму, размер сообщения и сообщение*/ WriteBytesInBMP(&dwCRC, sizeof(DWORD), bmp); WriteBytesInBMP(&fileLength, sizeof(DWORD), bmp); WriteBytesInBMP(pBuffer, (DWORD)fileLength, bmp); return TRUE; } BOOL RetrieveMessageFromBMP(PBMP bmp, PVOID *pOutBuffer, PDWORD dwOutReaded) { DWORD dwCRC, dwCheckCRC; LONG biWidthBMP, biHeightBMP; DWORD readedBytes; PBYTE pBuffer; /*Читаем из bmp контрольную сумму и размер сообщения*/ ReadBytesFromBMP(&dwCRC, sizeof(DWORD), bmp); ReadBytesFromBMP(&readedBytes, sizeof(DWORD), bmp); biWidthBMP = bmp->infoHeader.biWidth; biHeightBMP = bmp->infoHeader.biHeight; /*Проверям, могло ли сообщение поместить в bmp*/ if (biWidthBMP * biHeightBMP * 3 / 8 < readedBytes + sizeof(DWORD) + sizeof(DWORD)) { return FALSE; } /*Выделяем память под буфер и читаем в него все байта сообщения из bmp*/ pBuffer = (PBYTE)malloc(sizeof(BYTE) * readedBytes); if (pBuffer == NULL) { return FALSE; } ReadBytesFromBMP(pBuffer, (DWORD)readedBytes, bmp); /*Вычисляем контрольную сумму прочитанного сообщения*/ dwCheckCRC = RtlCrc32(pBuffer, readedBytes, 0); /*Если контрольные суммы сошлись, то сообщение успешно прочитано. Если нет, то сообщение повреждено или не содержалось в файле*/ if (dwCRC != dwCheckCRC) { return FALSE; } /*Копируем прочитанное сообщение в буфер назначения*/ //memcpy_s(pOutBuffer, lengthBuffer, pBuffer, readedBytes); *pOutBuffer = pBuffer; *dwOutReaded = readedBytes; return TRUE; } INT wmain(INT argc, PWSTR argv[]) { PWSTR lpszPathToSecretFile = 0; PWSTR lpszPathToBMP = 0; PBMP pBMP; PBYTE pBuffer; DWORD dwReaded; ProgramMode mode = ProgramMode::EmbedMode; if (argc < 2) { printf("Expected params! Use -help \n\n"); return 0; } /*Анализируем входные параметры*/ for (INT i = 1; i < argc; i++) { if (wcscmp(L"-help", argv[i]) == 0) { printf("Help:\n\ \t-help - get help!\n\ \t-embed <PathToSecretMessage> <PathToBMP> - embed secret message from file in bmp\n\ \t-retrieve <PathToBMP> <PathToFile> - retrieve secret message from BMP and copy in file\n\ \t-check <PathToBMP> - check contains secret message in bmp\n"); return 0; } else if (wcscmp(L"-embed", argv[i]) == 0) { if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } lpszPathToSecretFile = argv[i]; if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } lpszPathToBMP = argv[i]; mode = ProgramMode::EmbedMode; break; } else if (wcscmp(L"-retrieve", argv[i]) == 0) { if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } lpszPathToBMP = argv[i]; if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } lpszPathToSecretFile = argv[i]; mode = ProgramMode::RetrieveMode; break; } else if (wcscmp(L"-check", argv[i]) == 0) { if (++i >= argc) { printf("Expected value after param! Try use \"-help\n"); return 0; } lpszPathToBMP = argv[i]; mode = ProgramMode::CheckMode; break; } else { printf("Unexpected param! Try use \"-help\"\n"); return 0; } } /*Открываем bmp и загружаем его в структуру*/ if (lpszPathToBMP == NULL) { return -1; } pBMP = LoadBMPFromFile(lpszPathToBMP); if (pBMP == NULL) { printf("Cannot open/read BMP file!\n"); return 0; } /*Дешефрируем работу программы*/ switch (mode) { /*Внедряем сообщение в bmp*/ case ProgramMode::EmbedMode: if (!EmbedMessageInBMP(lpszPathToSecretFile, pBMP)) { printf("Cannot embed message to BMP file!\n"); return 0; } if (!WriteBMPToFile(lpszPathToBMP, pBMP)) { printf("Cannot rewrite BMP file!\n"); return 0; } printf("Done!\n"); break; /*Пытааемся прочитать сообщение из bmp*/ case ProgramMode::RetrieveMode: if (!RetrieveMessageFromBMP(pBMP, (PVOID*)&pBuffer, &dwReaded)) { printf("Cannot retrieve message from BMP file!\n"); return 0; } HANDLE hFile; if (lpszPathToSecretFile == NULL) { return 0; } hFile = CreateFile(lpszPathToSecretFile, GENERIC_WRITE, FILE_SHARE_READ, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { printf("Cannot open file %ws\n", lpszPathToSecretFile); return 0; } if (!WriteFile(hFile, pBuffer, dwReaded, NULL, NULL)) { printf("Cannot write message in file %ws\n", lpszPathToSecretFile); return 0; } printf("Done!\n"); break; /*Проверяем есть ли в bmp сообщение*/ case ProgramMode::CheckMode: if (!RetrieveMessageFromBMP(pBMP, (PVOID*)&pBuffer, &dwReaded)) { printf("BMP file dont have message!!\n"); return 0; } printf("BMP file have message!\n"); break; default: printf("Unxpected error! Exiting\n"); return -1; break; } return 0; }<file_sep>/TRPO_CPP/TRPO_CPP/TRPO_CPP.cpp #include <cstdio> int main() { float rX, rY; float pX, pY; float radius; printf("Write coords of round = "); if (scanf_s("%f %f", &rX, &rY) != 2) { printf("Wrote invalid value!"); return -1; } printf("Write coords of point = "); if (scanf_s("%f %f", &pX, &pY) != 2) { printf("Wrote invalid value!"); return -1; } printf("Write radius of round = "); if (scanf_s("%f", &radius) != 1) { printf("Wrote invalid value!"); return -1; } printf("\nXr = %.3f, Yr = %.3f\nXp = %.3f, Yp = %.3f\nRadius = %.3f\n\n", rX, rY, pX, pY, radius); if (((pX - rX) * (pX - rX) + (pY - rY) * (pY - rY)) < radius * radius) //точка принадлежит окружности { if ((pX > rX && pY > rY) || (pX > rX && pY < rY && pY > rY - radius * 0.6) || (pX < rX && pY < rY - radius * 0.6)) //точка принадлежит одной из областей { printf("Point belong to round!\n\n"); return 0; } else if ((pX == rX) || (pY == rY - radius * 0.6)) //точка лежит на границе одной из областей { printf("Point lay on round!\n\n"); return 0; } } else if (((pX - rX) * (pX - rX) + (pY - rY) * (pY - rY)) == radius * radius) { if ((pX >= rX && pY >= rY - radius * 0.6) || (pX <= rX && pY <= rY - radius * 0.6)) printf("Point lay on round!\n\n"); else { printf("Point don't belong to round!\n\n"); return 0; } } else { printf("Point don't belong to round!\n\n"); } }<file_sep>/MZKS_labs/lab5/lab5.cpp /* Разработать программу, выполняющую создание раздела реестра «HKEY_CURRENT_USER\Software\pi» с атрибутами безопасности для группы пользователей «Администраторы» и правами на полный доступ, а для группы «Все» только чтение. Вариант 4 */ #include "windows.h" #include "cstdio" #include "aclapi.h" INT wmain(INT argc, PWSTR argv[]) { DWORD dwRes; PSID pEveryoneSID = NULL, pAdminSID = NULL; PACL pACL = NULL; PSECURITY_DESCRIPTOR pSD = NULL; EXPLICIT_ACCESS ea[2]; SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY; SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY; SECURITY_ATTRIBUTES sa; HKEY hkSub = NULL; PWSTR lpszNameKey = 0; WCHAR lpszPathRegister[128]; BOOL bMode = FALSE; printf("\nLab 5. Creating key with Security Attributes\n\n"); if (argc < 2) { printf("Expected more params! Use -help for help . . .\n"); return 0; } for (INT i = 1; i < argc; i++) { if (wcscmp(TEXT("-help"), argv[i]) == 0) { printf("Help:\n\ \t-reg <key> - reg key in registry\n\ \t-delete <key> - delete key in registry\n"); return 0; } else if (wcscmp(TEXT("-reg"), argv[i]) == 0) { if (++i >= argc) { printf("Expected name of key! Try use \"-help\n"); return 0; } lpszNameKey = argv[i]; bMode = TRUE; } else if (wcscmp(TEXT("-delete"), argv[i]) == 0) { if (++i >= argc) { printf("Expected name of key! Try use \"-help\n"); return 0; } lpszNameKey = argv[i]; bMode = FALSE; } } if (bMode) { // Create a well-known SID for the Everyone group. if (!AllocateAndInitializeSid(&SIDAuthWorld, 1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0, &pEveryoneSID)) { printf("AllocateAndInitializeSid Error %u\n", GetLastError()); goto Cleanup; } // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow Everyone read access to the key. ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS)); ea[0].grfAccessPermissions = KEY_READ; ea[0].grfAccessMode = SET_ACCESS; ea[0].grfInheritance = NO_INHERITANCE; ea[0].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[0].Trustee.TrusteeType = TRUSTEE_IS_WELL_KNOWN_GROUP; ea[0].Trustee.ptstrName = (LPTSTR)pEveryoneSID; // Create a SID for the BUILTIN\Administrators group. if (!AllocateAndInitializeSid(&SIDAuthNT, 2, SECURITY_BUILTIN_DOMAIN_RID, DOMAIN_ALIAS_RID_ADMINS, 0, 0, 0, 0, 0, 0, &pAdminSID)) { printf("AllocateAndInitializeSid Error %u\n", GetLastError()); goto Cleanup; } // Initialize an EXPLICIT_ACCESS structure for an ACE. // The ACE will allow the Administrators group full access to // the key. ea[1].grfAccessPermissions = KEY_ALL_ACCESS; ea[1].grfAccessMode = SET_ACCESS; ea[1].grfInheritance = NO_INHERITANCE; ea[1].Trustee.TrusteeForm = TRUSTEE_IS_SID; ea[1].Trustee.TrusteeType = TRUSTEE_IS_GROUP; ea[1].Trustee.ptstrName = (LPTSTR)pAdminSID; // Create a new ACL that contains the new ACEs. dwRes = SetEntriesInAcl(2, ea, NULL, &pACL); if (ERROR_SUCCESS != dwRes) { printf("SetEntriesInAcl Error %u\n", GetLastError()); goto Cleanup; } // Initialize a security descriptor. pSD = (PSECURITY_DESCRIPTOR)LocalAlloc(LPTR, SECURITY_DESCRIPTOR_MIN_LENGTH); if (NULL == pSD) { printf("LocalAlloc Error %u\n", GetLastError()); goto Cleanup; } if (!InitializeSecurityDescriptor(pSD, SECURITY_DESCRIPTOR_REVISION)) { printf("InitializeSecurityDescriptor Error %u\n", GetLastError()); goto Cleanup; } // Add the ACL to the security descriptor. if (!SetSecurityDescriptorDacl(pSD, TRUE, // bDaclPresent flag pACL, FALSE)) // not a default DACL { printf("SetSecurityDescriptorDacl Error %u\n", GetLastError()); goto Cleanup; } // Initialize a security attributes structure. sa.nLength = sizeof(SECURITY_ATTRIBUTES); sa.lpSecurityDescriptor = pSD; sa.bInheritHandle = FALSE; HKEY hKey; wsprintf(lpszPathRegister, L"Software\\%ls", lpszNameKey); if (RegCreateKeyEx(HKEY_CURRENT_USER, lpszPathRegister, 0, NULL, REG_OPTION_VOLATILE, KEY_WRITE, &sa, &hKey, NULL) != ERROR_SUCCESS) { printf("Error! Cannot not create key\n"); return -1; } RegCloseKey(hKey); Cleanup: if (pEveryoneSID) FreeSid(pEveryoneSID); if (pAdminSID) FreeSid(pAdminSID); if (pACL) LocalFree(pACL); if (pSD) LocalFree(pSD); if (hkSub) RegCloseKey(hkSub); printf("Key \"%ls\" was created!\n", lpszPathRegister); return 0; } else { wsprintf(lpszPathRegister, L"Software\\%ls", lpszNameKey); DWORD dwResult; dwResult = RegDeleteKey(HKEY_CURRENT_USER, lpszPathRegister); if (dwResult != ERROR_SUCCESS) { printf("Cannot delete current key!\n"); return -1; } printf("Key \"%ls\" was deleted!\n", lpszPathRegister); } }<file_sep>/README.md # Labs (6 semester) This is the laboratory work of <NAME> and <NAME>. Group 17VV2. # с:
eec33816c6639e7ff4656c4fdf19ca3e36c44300
[ "Markdown", "C", "C++" ]
10
C++
raggedByte/Labs_6-semester
c44f6abda2654e70f45c03cdc585bd072162618c
9b8cf4a1c30ced919a08db9b7470e3d726fea98b
refs/heads/master
<file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Server extends Model{ } <file_sep><?php /* |-------------------------------------------------------------------------- | Application Routes |-------------------------------------------------------------------------- | | Here is where you can register all of the routes for an application. | It's a breeze. Simply tell Laravel the URIs it should respond to | and give it the controller to call when that URI is requested. | */ Route::get('/', 'HomeController@index'); use App\Commands\PingServer; use App\Server; Route::get('test', function(){ $servers = Server::all(); foreach($servers as $server){ Queue::push(new PingServer($server->ip, $server->id)); } }); <file_sep><?php namespace App\Console\Commands; use Illuminate\Console\Command; use App\Commands\PingServer; use App\Server; use Bus; class Serverping extends Command { /** * The console command name. * * @var string */ protected $name = 'serverping'; /** * The console command description. * * @var string */ protected $description = 'Command description.'; /** * Execute the console command. * * @return mixed */ public function fire() { $servers = Server::all(); foreach($servers as $server){ Bus::dispatch(new PingServer($server->ip, $server->id)); } } } <file_sep><?php namespace App\Commands; use App\Commands\Command; use Illuminate\Queue\SerializesModels; use Illuminate\Queue\InteractsWithQueue; use Illuminate\Contracts\Bus\SelfHandling; use Illuminate\Contracts\Queue\ShouldBeQueued; use JJG\Ping as Ping; use App\Server; use App\Ping as Record; class PingServer extends Command implements SelfHandling, ShouldBeQueued { use InteractsWithQueue, SerializesModels; private $host; private $sid; private $retry; private $allow; /** * Create a new command instance. * * @return void */ public function __construct($host,$sid) { $this->host = $host; $this->sid = $sid; $this->retry = 0; $this->allow = false; } /** * Execute the command. * * @return void */ public function handle() { $latency = $this->ping(); if ($latency !== -1 || $this->allow) { if($latency > 500){ if($this->retry < 5){ $this->retry++; return $this->handle(); } } // NEED A GOOD RETRY SYSTEM // Record::create( // ['target'=>$this->host, // 'timeout'=>0, // 'sid'=>$this->sid, // 'latency'=>$latency]); $server = Server::find($this->sid); $server->lastbefore = $server->last; $server->last = $latency; $server->avg = ($server->avg == 0)?$latency:($server->avg + $latency)/2; $history = json_decode($server->history,true); $history[] = $latency; if(count($history) > 5){ unset($history[0]); } $i = 0; foreach($history as $s){ $i += $s; } $server->history = json_encode(array_values($history)); $server->lastavg = $i/count($history); $server->increment('success'); $server->offline = 0; $server->save(); }else{ Record::create( ['target'=>$this->host, 'timeout'=>1, 'sid'=>$this->sid, 'latency'=>0]); $server = Server::find($this->sid); $server->increment('timeouts'); $server->offline = 1; $server->save(); } } private function ping(){ try{ $starttime = microtime(true); $file = @fsockopen($this->host, 80, $errno, $errstr, 10); $stoptime = microtime(true); $status = 0; if (!$file) $status = -1; else { fclose($file); $status = ($stoptime - $starttime) * 1000; $status = floor($status); } }catch(Exception $e){ $status = -1; } return $status; } } <file_sep><?php use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateServersTable extends Migration { /** * Run the migrations. * * @return void */ public function up() { Schema::create('servers', function(Blueprint $table) { $table->tinyInteger('id')->primary(); $table->string('ip',50); $table->string('region',5); $table->text('history'); $table->double('last')->default(0); $table->double('lastavg')->default(0); $table->double('avg')->default(0); $table->integer('timeouts')->default(0); $table->integer('success')->default(0); $table->boolean('offline')->default(false); $table->timestamps(); }); } /** * Reverse the migrations. * * @return void */ public function down() { Schema::drop('servers'); } } <file_sep><?php namespace App; use Illuminate\Database\Eloquent\Model; class Ping extends Model{ protected $fillable = ['target','timeout','latency']; } <file_sep><?php namespace App\Http\Controllers; use App\Server; class HomeController extends Controller{ public function index(){ return view('home.index')->with('servers', Server::all(['last','lastavg','avg','region','id','offline','lastbefore'])); } }
a8aeeebee088dbe7bb7c48e35a388c412a344a29
[ "PHP" ]
7
PHP
Raideer/runestatus
e0846e238889ff8bbf29bbe14f6757e12c3449bd
8069560549ed2c0f0bf991a7a2a1f1b96da665d7
refs/heads/master
<file_sep>package ru.mo.lab2.method1 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 29.04.17. */ class StepPartition(var eps: Double, var a: Double, var u0: U, val functions: Functions) { var iterations = 0 init { if (eps <= 0) eps = 0.1 if (a < 0) a = 1.0 } fun findMin(): U { var gradient: U var gradientLength: Double var j0 = functions.j(u0) while (true) { gradient = functions.gradient(u0) gradientLength = functions.gradientLength(gradient) if (gradientLength < eps) return u0 do { val u1 = u0 - gradient * a val j1 = functions.j(u1) if (j1 < j0) { u0 = u1 j0 = j1 break } else { a /= 2 } iterations++ } while (true) iterations++ } } }<file_sep>package ru.mo.lab2.method3 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 03.05.17. */ class NewtonHelperFunctions(val functions: Functions) { fun reverseHessianMatrix22(): Array<DoubleArray> { val matrix: Array<DoubleArray> = Array(2, { DoubleArray(2) }) matrix[0][0] = functions.dJdu2u2 matrix[0][1] = -functions.dJdu1u2 matrix[1][0] = -functions.dJdu2u1 matrix[1][1] = functions.dJdu1u1 val denominator = matrix22Determinant(matrix) val a = 1 / denominator for (i in 0..1) for (j in 0..1) matrix[i][j] *= a return matrix } fun matrix22Determinant(hessianMatrix: Array<DoubleArray>) = hessianMatrix[0][0] * hessianMatrix[1][1] - hessianMatrix[1][0] * hessianMatrix[0][1] fun gradientOnMatrix(gradient: U, hessianMatrix: Array<DoubleArray>): U { val u1 = gradient.u1 * hessianMatrix[0][0] + gradient.u2 * hessianMatrix[1][0] val u2 = gradient.u1 * hessianMatrix[0][1] + gradient.u2 * hessianMatrix[1][1] return U(u1, u2) } }<file_sep>package ru.mo.lab2.method2 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 03.05.17. */ class NewtonHelperFunctions(val functions: Functions) { fun get1DPoint(u: U, gradient: U, a: Double) = u - gradient * a fun phi(u: U, gradient: U, a: Double): Double = functions.j(get1DPoint(u, gradient, a)) fun dPhidu(u: U, gradient: U, a: Double): Double { val point = get1DPoint(u, gradient, a) var result = -6 * gradient.u1 * point.u1 result += -4 * gradient.u1 * point.u2 result += -4 * gradient.u2 * point.u1 result += -6 * gradient.u2 * point.u2 return result } fun dPhidu2(gradient: U): Double { var result = 6 * Math.pow(gradient.u1, 2.0) result += 8 * gradient.u1 * gradient.u2 result += 6 * Math.pow(gradient.u2, 2.0) return result } }<file_sep>package ru.mo.lab2.method3 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 30.04.17. */ class Newton(var eps: Double, var u0: U, val functions: Functions) { var iterations = 0 val newtonHelperFunctions = NewtonHelperFunctions(functions) init { if (eps < 0) eps = 0.1 } fun findMin(): U { var gradient: U var gradientLength: Double val hessianMatrix = newtonHelperFunctions.reverseHessianMatrix22() while (true) { gradient = functions.gradient(u0) gradientLength = functions.gradientLength(gradient) if (gradientLength < eps) return u0 val toSubtract = newtonHelperFunctions.gradientOnMatrix(gradient, hessianMatrix) u0 -= toSubtract iterations++ } } }<file_sep>package ru.mo.lab2 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U import ru.mo.lab2.method1.StepPartition import ru.mo.lab2.method2.SteepestDescent import ru.mo.lab2.method3.Newton import ru.mo.lab2.method4.PenaltiesMethod /** * Created by sergey on 29.04.17. */ fun main(args: Array<String>) { val functions = Functions() val eps = 0.1 val a = 1.0 val u = U(1.0, 2.0) method1(eps, a, u, functions) method2(eps, u, functions) method3(eps, u, functions) method4(eps, u, functions) } fun method1(eps: Double, a: Double, u: U, functions: Functions) { println("Метод дробления шага") val stepPartition = StepPartition(eps, a, u, functions) val result = stepPartition.findMin() println("Минимум: $result\nЕго нахождение заняло: ${stepPartition.iterations} итераций") printSeparator() } fun method2(eps: Double, u: U, functions: Functions) { println("Метод наискорейшего спуска") val steepestDescent = SteepestDescent(eps, u, functions) val result = steepestDescent.findMin() println("Минимум: $result\nЕго нахождение заняло: ${steepestDescent.iterations} итераций") printSeparator() } fun method3(eps: Double, u: U, functions: Functions) { println("Метод Ньютона") val newton = Newton(eps, u, functions) val result = newton.findMin() println("Минимум: $result\nЕго нахождение заняло: ${newton.iterations} итераций") printSeparator() } fun method4(eps: Double, u: U, functions: Functions) { println("Метод штрафных функций") val penaltiesMethod = PenaltiesMethod(eps, u, functions) val result = penaltiesMethod.findMin() println("Минимум: $result\nЕго нахождение заняло: ${penaltiesMethod.iterations} итераций") } fun printSeparator() = println("-----------------------------------------------------------------")<file_sep>package ru.mo.lab2.method2 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 29.04.17. */ class Newton(val functions: Functions) { var iterations = 0 val newtonHelperFunctions = NewtonHelperFunctions(functions) /** *@return a* * */ fun findAWithAsterisk(uk: U, eps: Double): Double { var aWithAsterisk = 1.0 var previousAWithAsterisk = -aWithAsterisk; val gradient = functions.gradient(uk) while (Math.abs(newtonHelperFunctions.phi(uk, gradient, aWithAsterisk)) > eps && previousAWithAsterisk != aWithAsterisk) { val dPhi = newtonHelperFunctions.dPhidu(uk, gradient, aWithAsterisk) val dPhi2 = newtonHelperFunctions.dPhidu2(gradient) previousAWithAsterisk = aWithAsterisk aWithAsterisk -= dPhi / dPhi2 iterations++ } return aWithAsterisk } }<file_sep>package ru.mo.lab2.method4 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 30.04.17. */ class PenaltiesMethod(var eps: Double, var u0: U, val functions: Functions) { init { if (eps <= 0) eps = 0.1 } var iterations = 0 var r = 1.0 val penaltiesFunctions = PenaltiesFunctions(functions) val c = 10.0 fun findMin(): U { while (true) { val dPdu1 = penaltiesFunctions.dPdu1(u0, r) val dPdu2 = penaltiesFunctions.dPdu2(u0, r) val gradientLength = functions.gradientLength(U(dPdu1, dPdu2)) if (gradientLength < eps) { if (r < eps) return u0 } r /= c val p1 = penaltiesFunctions.dPdu1(u0, r) val p2 = penaltiesFunctions.dPdu2(u0, r) val lambda = penaltiesFunctions.lambda(u0, r) u0 -= U(p1, p2) * lambda iterations++ } } }<file_sep>package ru.mo.lab2.method2 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 29.04.17. */ class SteepestDescent(var eps: Double, var u0: U, val functions: Functions) { var iterations = 0 val newton = Newton(functions) init { if (eps < 0) eps = 0.1 } fun findMin(): U { var gradient = functions.gradient(u0) var gradientLength: Double while (true) { gradientLength = functions.gradientLength(gradient) if (gradientLength < eps) return u0 val a = newton.findAWithAsterisk(u0, eps) u0 -= gradient * a gradient = functions.gradient(u0) iterations += newton.iterations + 1 } } }<file_sep>package ru.mo.lab2.common /** * Created by sergey on 29.04.17. */ class U(val u1: Double = 0.0, val u2: Double = 0.0) { operator fun plus(u: ru.mo.lab2.common.U) = ru.mo.lab2.common.U(this.u1 + u.u1, this.u2 + u.u2) operator fun minus(u: ru.mo.lab2.common.U) = ru.mo.lab2.common.U(this.u1 - u.u1, this.u2 - u.u2) operator fun times(number: Double) = ru.mo.lab2.common.U(this.u1 * number, this.u2 * number) override fun toString(): String { return "u1 = $u1, u2 = $u2" } }<file_sep>package ru.mo.lab2.common /** * В этом классе содержатся функция, её частные производные * и методы для нахождения градиента и его модуля */ class Functions { fun j(u: U) = 4 * u.u1 * u.u2 + 3 * Math.pow(u.u1, 2.0) + 3 * Math.pow(u.u2, 2.0) //Частные производные fun dJdu1(u: U) = 4 * u.u2 + 6 * u.u1 fun dJdu2(u: U) = 4 * u.u1 + 6 * u.u2 //Смешанные производные val dJdu1u1 = 6.0 val dJdu1u2 = 4.0 val dJdu2u1 = 4.0 val dJdu2u2 = 6.0 fun gradient(u: U) = U(dJdu1(u), dJdu2(u)) fun gradientLength(gradient: U) = Math.sqrt(Math.pow(gradient.u1, 2.0) + Math.pow(gradient.u2, 2.0)) } <file_sep>package ru.mo.lab2.method4 import ru.mo.lab2.common.Functions import ru.mo.lab2.common.U /** * Created by sergey on 02.05.17. */ class PenaltiesFunctions(val functions: Functions) { //частные производные fun dPdu1(u: U, r: Double) = functions.dJdu1(u) - r / Math.pow(u.u1, 2.0) fun dPdu2(u: U, r: Double) = functions.dJdu2(u) - r / Math.pow(u.u2, 2.0) //смешанные производные fun dPdu1u1(u: U, r: Double) = functions.dJdu1u1 + r * 2.0 / Math.pow(u.u1, 3.0) fun dPdu2u2(u: U, r: Double) = functions.dJdu2u2 + r * 2.0 / Math.pow(u.u2, 3.0) // вспомогательный параметр fun lambda(u: U, r: Double) = 1.0 / (dPdu1u1(u, r) * dPdu2u2(u, r) - functions.dJdu1u2 * functions.dJdu2u1) }
2cbc1bb0cd8095d53e6161e755f1124539dcf988
[ "Kotlin" ]
11
Kotlin
Pechorka/MO
1b28d6bbd390f2209a25c36ba1b103497a0c5948
78ea1b3744a6bb5753c7d734b630ca45c360fba3
refs/heads/master
<file_sep># # Exploratory Data Analysis # Week 1 - Assignment # User: <NAME> # # # Plot 2 script # # Reading file allData <- read.table("./household_power_consumption.txt",header=TRUE,stringsAsFactors=FALSE, sep = ";") #Subset data to limit dates selData <- subset(allData, Date == '1/2/2007' | Date == '2/2/2007') #Extract Data for TimePlot gapVar <- as.numeric(selData$Global_active_power) dateVar = selData$Date timeVar <- paste(dateVar,selData$Time,sep=" ") xVar <- strptime(timeVar, "%d/%m/%Y %H:%M:%S") # Create PNG file png(filename = "plot2.png", width = 480, height = 480) # Plot timeseries Plot plot(xVar, gapVar, xlab = "", type='l',ylab ="Global Active Power (Kilowatts)") dev.off()<file_sep># # Exploratory Data Analysis # Week 1 - Assignment # User: <NAME> # # # Plot 3 script # # Reading file allData <- read.table("./household_power_consumption.txt",header=TRUE,stringsAsFactors=FALSE, sep = ";") #Subset data to limit dates selData <- subset(allData, Date == '1/2/2007' | Date == '2/2/2007') #Extract Data for TimePlot yVar1 <- as.numeric(selData$Sub_metering_1) yVar2 <- as.numeric(selData$Sub_metering_2) yVar3 <- as.numeric(selData$Sub_metering_3) timeVar <- paste(dateVar,selData$Time,sep=" ") xVar <- strptime(timeVar, "%d/%m/%Y %H:%M:%S") # Create PNG file png(filename = "plot3.png", width = 480, height = 480) # Plot timeseries Plot plot(xVar, yVar1, xlab = "", type='l', ylab = "Energy Submetering") lines(xVar, yVar2, type = 'l',col="red") lines(xVar, yVar3, type = 'l',col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), col = c("black","red","blue")) dev.off()<file_sep># # Exploratory Data Analysis # Week 1 - Assignment # User: <NAME> # # # Plot 4 script # # Reading file allData <- read.table("./household_power_consumption.txt",header=TRUE,stringsAsFactors=FALSE, sep = ";") #Subset data to limit dates selData <- subset(allData, Date == '1/2/2007' | Date == '2/2/2007') #Extract Data for TimePlot gapVar <- as.numeric(selData$Global_active_power) grpVar <- as.numeric(selData$Global_reactive_power) yVar1 <- as.numeric(selData$Sub_metering_1) yVar2 <- as.numeric(selData$Sub_metering_2) yVar3 <- as.numeric(selData$Sub_metering_3) volVar <- as.numeric(selData$Voltage) dateVar = selData$Date timeVar <- paste(dateVar,selData$Time,sep=" ") xVar <- strptime(timeVar, "%d/%m/%Y %H:%M:%S") # Create PNG file png(filename = "plot4.png", width = 480, height = 480) par(mfrow=c(2,2)) #Plot 1 plot(xVar, gapVar, xlab = "", type='l',ylab ="Global Active Power") #Plot 2 plot(xVar, volVar, type='l',ylab ="Voltage", xlab = "datetime") # Plot 3 plot(xVar, yVar1, xlab = "", type='l', ylab = "Energy Submetering") lines(xVar, yVar2, type = 'l',col="red") lines(xVar, yVar3, type = 'l',col="blue") legend("topright",c("Sub_metering_1","Sub_metering_2","Sub_metering_3"), col = c("black","red","blue")) # Plot 4 plot(xVar, grpVar, xlab = "", type='l',ylab ="Global Reactive Power") dev.off()<file_sep># # Exploratory Data Analysis # Week 1 - Assignment # User: <NAME> # # # Plot 1 script # # Reading file allData <- read.table("./household_power_consumption.txt",header=TRUE,stringsAsFactors=FALSE, sep = ";") #Subset data to limit dates selData <- subset(allData, Date == '1/2/2007' | Date == '2/2/2007') #Extract Data for hsitogram xVar <- as.numeric(selData$Global_active_power) # Create PNG file png(filename = "plot1.png", width = 480, height = 480) # Plot histogram hist(xVar, col="red",xlab="Globacl Active Power (Kilowatts)",ylab="Frequency",main="Global Active Power") dev.off()
73f77a1ca657c6ed94c4517e41d95bbe8fcd6b51
[ "R" ]
4
R
kpabhis/ExData_Plotting1
e61f2904bb8a2ff3ac02ad8d1f94f15badde6c71
f69e4232c465d5f27db4cb83b39c820bca1fbe67
refs/heads/master
<file_sep>package robert.web.controllers; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseStatus; import org.springframework.web.bind.annotation.RestController; import robert.db.entities.Note; import robert.db.repo.NoteRepository; @RestController @RequestMapping("/notes") public class NoteController { private final Logger log = LoggerFactory.getLogger(NoteController.class); private final NoteRepository noteRepository; public NoteController(NoteRepository noteRepository) { this.noteRepository = noteRepository; } @GetMapping("/all") public Iterable<Note> getAllNotes() { Iterable<Note> notes = noteRepository.findAll(); if ( log.isDebugEnabled() ) log.debug("Found: {} - notes", notes); return notes; } @PostMapping("/add-new") @ResponseStatus(HttpStatus.OK) public void addNewNote(@RequestBody Note note) { if ( note.getText() .length() < 3 ) throw new RuntimeException("The Note is too short"); noteRepository.save(note); } } <file_sep>package robert.db.repo; import org.springframework.data.repository.CrudRepository; import org.springframework.stereotype.Repository; import robert.db.entities.Note; @Repository public interface NoteRepository extends CrudRepository<Note, Long> { } <file_sep>package robert; import java.io.IOException; import com.fasterxml.jackson.databind.ObjectMapper; public class TestUtils { private static final ObjectMapper mapper = new ObjectMapper(); public static String objectToJson(final Object obj) throws Exception { return mapper.writeValueAsString(obj); } public static <T> T jsonToObject(String json, Class<T> clazz) throws IOException { return mapper.readValue(json, clazz); } } <file_sep>package robert.db.entities; import javax.persistence.Entity; @Entity public class Note extends BasicEntity { private String text; public String getText() { return text; } public void setText(String text) { this.text = text; } @Override public String toString() { return "Note{" + "text='" + text + '\'' + '}'; } }
7787195cce3f643a5e8cadfb3cf87c696668bf43
[ "Java" ]
4
Java
robson021/notebook
714614df67f468c328b57cc8429b9f1f720c3656
6d35f8d60f2a3bcafca389b00b9b629f6f034ad8
refs/heads/master
<repo_name>weiyanqin/vue-practice<file_sep>/vue2.0小白入门教程/练习/app.js new Vue ({ el: '.app', data: { name: 'wanghaiming', webSite: '<a href="www.baidu.com">百度</a>' }, methods: { greet(index){ return `good ${index} ` + this.name } } })<file_sep>/vue2.0小白入门教程/课时-9/app.js new Vue({ el: "#vue-app", data: { age: '', name: 'dawang', }, methods: { logName(){ alert(this.name) }, logAge(){ alert('你正在输入年龄') } } })<file_sep>/vue2.0小白入门教程/课时-15/app.js var one = new Vue({ el: "#vue-app-one", data: { title: "app one 里面的内容" }, methods: { }, computed: { greet(){ return 'hello app one' } } }) var two = new Vue({ el: "#vue-app-two", data: { title: "app two 里面的内容" }, methods: { changeTitle(){ one.title = "已经改名了" } }, computed: { greet(){ return 'hello app one' } } })<file_sep>/vuex-demo/src/store/index.js import Vue from 'vue' import Vuex from 'vuex' Vue.use(Vuex) export const store = new Vuex.Store({ state:{ products: [ {name: '马云', price: '200'}, {name: '马化腾', price: '140'}, {name: '马冬梅', price: '20'}, {name: '马蓉', price: '10'} ] } })
eb2aa0e99689eb9057d6416865945c785fff5543
[ "JavaScript" ]
4
JavaScript
weiyanqin/vue-practice
5603f3886ea49312846bf2e8dda8a54475cb3b00
6826525c407ef8f293735b90dbf651bdd8e490a8
refs/heads/master
<file_sep>const express = require('express'); const router = express.Router(); const controller = require('../../controllers/v1/index'); const authRouter = require('./auth'); const userRouter = require('./user'); const githubRouter = require('./github'); router.use('/auth', authRouter); router.use('/user', userRouter); router.use('/github', githubRouter); router.get('/status', controller.getStatus); module.exports = router;
d66a6d9ea153cb3d2523675272ba11f044107d76
[ "JavaScript" ]
1
JavaScript
zjilani/Backend
896889bd07038fb52502ef5514a15b2c62478a18
a3630bc361aa903cbe1c3878b7eb48c81f3f6b96
refs/heads/master
<file_sep><?xml version="1.0"?> <project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <modelVersion>4.0.0</modelVersion> <groupId>strus.web.malicious</groupId> <artifactId>maliciousWeb</artifactId> <version>1.0.0</version> <packaging>war</packaging> <name>Malicious Web Application</name> <dependencies> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.8</version> </dependency> <dependency> <groupId>org.apache.activemq</groupId> <artifactId>activemq-core</artifactId> <version>5.7.0</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.7.5</version> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.8</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>org.jetbrains</groupId> <artifactId>annotations-java5</artifactId> <version>15.0</version> </dependency> </dependencies> <description>Malicious Web Application to control remote plugin</description> <build> <finalName>malicious-web-app</finalName> <plugins> <plugin> <groupId>org.mortbay.jetty</groupId> <artifactId>jetty-maven-plugin</artifactId> <version>8.1.16.v20140903</version> <configuration> <webApp> <contextPath>/${artifactId}</contextPath> </webApp> <stopKey>CTRL+C</stopKey> <stopPort>8999</stopPort> <scanIntervalSeconds>10</scanIntervalSeconds> <scanTargets> <scanTarget>src/main/webapp/WEB-INF/web.xml</scanTarget> </scanTargets> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.7</source> <target>1.7</target> </configuration> </plugin> </plugins> </build> </project> <file_sep>package org.apache.struts.maliweb.model; /** * Created by szkol_000 on 21.01.2017. */ public class Malicious { String name = ""; String time = "1"; public Malicious(String time, String name) { this.time = time; this.name = name; } public Malicious(String name) { this.name = name; } public String getName() { return name; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public void setName(String name) { this.name = name; } @Override public String toString() { return name; } }
f10930cccaf343798cfc2b9807da33042a55f329
[ "Java", "Maven POM" ]
2
Maven POM
mrwrob/MaliciousWeb
a5349bb560a9014c589089c374c750694c0a14a2
ed00812e7e77f7771ba93ab7d5b81e89a03d8ff9
refs/heads/master
<file_sep><?php namespace App\Controller; use App\Entity\Secretaria; use App\Form\SecretariaType; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\HttpFoundation\Response; class SecretariaController extends Controller { /** * @Route("/secretaria", name="listar_secretaria") * @Template ("secretaria/index.html.twig") * */ public function index() { $em = $this->getDoctrine()->getManager(); $secretarias = $em->getRepository(Secretaria::class)->findAll(); return [ 'secretarias' => $secretarias ]; } /** * @param Request $request * @Route ("/secretaria/cadastrar", name="cadastrar_secretaria") * @Template ("secretaria/create.html.twig") * @return Response */ public function create(Request $request) { $secretaria = new Secretaria(); $form = $this->createForm(SecretariaType::class, $secretaria); $form->handleRequest($request); //para fazer a validação pelo validator tem q tratar da requisição //processo para salvar. Veja abaixo - persistência if ($form->isSubmitted() && $form->isValid()) { //enviado e válido $em = $this->getDoctrine()->getManager(); $em->persist($secretaria); $em->flush(); //$this->get('session')->getFlashBag()->set('success', 'produto foi salvo com sucesso'); //passar no index $this->addFlash('success', 'secretaria foi salvo com sucesso'); return $this->redirectToRoute('listar_secretaria'); } return [ 'form' => $form->createView() ]; } /** * @param Request $request * @Route ("/secretaria/editar/{id}", name="editar_secretaria") * @Template("secretaria/update.html.twig") * @return array */ public function update(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $secretaria = $em->getRepository(Secretaria::class)->find($id); $form = $this->createForm(SecretariaType::class, $secretaria); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($secretaria); $em->flush(); $this->addFlash('success', 'cadastro feito com sucesso'); return $this->redirectToRoute('listar_secretaria'); } return [ 'form' => $form->createView() ]; } /** * @param Request $request * @param $id * @Route ("secretaria/visualizar/{id}", name="visualizar_secretaria") * @Template ("secretaria/view.html.twig") * @return Response */ public function view(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $secretaria = $em->getRepository(Secretaria::class)->find($id); return [ 'secretaria' => $secretaria ]; } /** * @param Request $request * @param $id * @Route ("secretaria/apagar/{id}", name="deletar_secretaria") * @return Response */ public function delete(Request $request, $id, Secretaria $secretaria) { $em = $this->getDoctrine()->getManager(); $secretaria = $em->getRepository(Secretaria::class)->find($id); if (!$secretaria) { $mensagem = "Secretaria não foi encontrado"; $tipo = "warning"; } else { $em->remove($secretaria); $em->flush(); $mensagem = "Secretaria excluído com sucesso!!!"; $tipo = "success"; } $this->get('session')->getFlashBag()->set($tipo, $mensagem); return $this->redirectToRoute("listar_secretaria"); } } <file_sep><?php /** * Created by PhpStorm. * User: Alex * Date: 24/05/2018 * Time: 22:38 */ namespace App\Enum; class FuncionarioStatusEnum { const STATUS_ATIVO = 'A'; const STATUS_EXONERADO = 'E'; public static function getStatus() { return [ self::STATUS_ATIVO => 'Ativo', self::STATUS_EXONERADO =>'Exonerado' ]; } }<file_sep><?php use App\Entity\Funcionario; use Doctrine\Bundle\FixturesBundle\Fixtures; use Doctrine\Common\Persistence\ObjectManager; class faker extends Fixture { public function load(objectManager $manager) { for ($i = 0; $i < 50; $i++){ $funcionario = new Funcionario(); $funcionario->setNome('funcionario' . $i); $funcionario->setCargo('funcionario' . $i); $funcionario->setIdade('funcionario'.$i); $funcionario->setEndereco('endereco'.$i); $funcionario->setCpf('funcionario'.$i); $funcionario->setExonerado('secretaria'.$i); $funcionario->setDataAdmissao('funcionario'.$i); $funcionario->setDataNascimento('funcionario'.$i); $funcionario->setNormalEmFolha('secretaria', $i); $funcionario->setSalBase('funcionario', $i); $funcionario->setGratif('funcionario'.$i); $funcionario->setDesconto('funcionario', $i); $funcionario->setSecretaria('funcionario', $i); $manager->persist($funcionario); } $manager->flush(); } } <file_sep>"# sistema-de-controle" <file_sep><?php namespace App\Form; use App\Entity\Funcionario; use App\Enum\FuncionarioStatusEnum; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class RelatorioType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('data_inicio', DateType::class, [ 'widget' => 'single_text', ]) ->add('data_fim', DateType::class, [ 'widget' => 'single_text' ]) ->add('status', ChoiceType::class, [ 'choices' => array_flip(FuncionarioStatusEnum::getStatus()) ]) ->add('pdf', SubmitType::class, [ 'label' => 'Gerar PDF' ]) ->add('excel', SubmitType::class, [ 'label' => 'Gerar excel' ]) ->add('pesquisar', SubmitType::class, [ 'label' => 'Pesquisar' ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ // Configure your form options here ]); } } <file_sep><?php /** * Created by PhpStorm. * User: Veiga * Date: 28/06/2018 * Time: 15:37 */ namespace DoctrineMigrations; use App\Entity\User; use Doctrine\DBAL\Migrations\AbstractMigration; use Doctrine\DBAL\Schema\Schema; use Symfony\Component\DependencyInjection\ContainerAwareInterface; use Symfony\Component\DependencyInjection\ContainerInterface; use Symfony\Component\Security\Core\Role\RoleHierarchy; /** * Auto-generated Migration: Please modify to your needs! */ class Version20180628153710 extends AbstractMigration implements ContainerAwareInterface { private $container; private $encoder; public function setContainer(ContainerInterface $container = null) { $this->container = $container; $this->encoder = $container->get('security.password_encoder'); } private function getDoctrine() { return $this->container->get('doctrine'); } public function up(Schema $schema) { $entityManager = $this->getDoctrine()->getManager(); $admin = new User(); $admin ->setUsername('admin') ->setRoles(['ROLE_ADMINISTRADOR']); $password = $this->encoder->encodePassword($admin, '<PASSWORD>'); $admin->setPassword($password); $entityManager->persist($admin); $entityManager->flush(); } public function down(Schema $schema) { $entityManager = $this->getDoctrine()->getManager(); $usuario = $entityManager->getRepository(User::class)->findByLogin('admin'); $entityManager->remove($usuario); $entityManager->flush(); } }<file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass="App\Repository\SecretariaRepository") */ class Secretaria { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") */ private $id; /** * @var string * @ORM\Column(type="string", length=256) * @Assert\NotBlank() */ private $nome; /** * @return mixed */ public function getId() { return $this->id; } /** * @return string */ public function getNome() { return $this->nome; } /** * @param string $nome * @return Secretaria */ public function setNome($nome) { $this->nome = $nome; return $this; } public function __toString () { return $this->getNome(); } } <file_sep><?php namespace App\Form; use App\Entity\User; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\PasswordType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolver; class UserType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('username', TextType::class, [ 'label' => 'Nome', 'attr' => [ 'placeholder' => "Informe o nome", ] ]) ->add('password', PasswordType::class, [ 'label' => 'Senha', 'attr' => [ 'placeholder' => 'digite sua senha', ] ]) ->add('roles', ChoiceType::class, [ 'attr' => [ 'placeholder' => 'Escolher o acesso de usuário', ], 'choices' => [ 'Administrador' => 'ROLE_ADMINISTRADOR', 'Gerente' => 'ROLE_GERENTE', 'Operador' => 'ROLE_OPERADOR' ], 'multiple' => true ] ); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ 'data_class' => User::class, ]); } } <file_sep><?php namespace App\Controller; use App\Entity\Funcionario; use App\Entity\Secretaria; use App\Form\CreateFuncType; use App\Form\FuncionarioType; use Symfony\Component\HttpFoundation; use Symfony\Component\Form\FormEvent; use Symfony\Component\Form\FormEvents; use App\Repository\FuncionarioRepository; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; class FuncionarioController extends Controller { /** * @Route("/funcional", name="listar_funcionario") * @Template("funcional/index.html.twig") */ public function index(Request $request) { $funcionarios = new Funcionario(); $form = $this->createForm(FuncionarioType::class, $funcionarios); $em = $this->getDoctrine()->getManager(); $funcionarios = $em->getRepository(Funcionario::class)->findAll(); $form->handleRequest($request); return [ 'funcionarios' => $funcionarios, 'form' => $form->createView() ]; } /** * @param Request $request * @Route ("/funcional/cadastrar", name="cadastrar_funcionario") * @Template("funcional/create.html.twig") * @return array */ public function create(Request $request) { $funcionario = new Funcionario(); $form = $this->createForm(CreateFuncType::class, $funcionario); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $file = $funcionario->getImagemDocumento(); $fileName = md5(time()) . "." . $file->guessExtension(); //gerando um nome único $file->move( $this->getParameter('caminho_file'), $fileName); $funcionario->setImagemDocumento($fileName); $funcionario->calculoLiquido(); $em = $this->getDoctrine()->getManager(); $em->persist($funcionario); $em->flush(); $this->addFlash('success', 'cadastro feito com sucesso'); return $this->redirectToRoute('listar_funcionario'); } return [ 'form' => $form->createView(), ]; } /** * @param Request $request * @param $id * @Route ("funcionario/visualizar/{id}", name="visualizar_funcionario") * @Template ("funcional/view.html.twig") * @return Response */ public function view(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $funcionario = $em->getRepository(Funcionario::class)->find($id); return [ 'funcionario' => $funcionario ]; } /** * @param Request $request * @Route ("/funcional/editar/{id}", name="editar_funcionario") * @Template("funcional/update.html.twig") * @return Response */ public function update(Request $request, $id) { $funcionario = new Funcionario(); $em = $this->getDoctrine()->getManager(); $funcionario = $em->getRepository(Funcionario::class)->find($id); $form = $this->createForm(FuncionarioType::class, $funcionario); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $file = $funcionario->getImagemDocumento(); $fileName = md5(time()) . "." . $file->guessExtension(); //gerando um nome único $file->move( $this->getParameter('caminho_file'), $fileName); $funcionario->setImagemDocumento($fileName); //$em = $this->getDoctrine()->getManager(); $funcionario->calculoLiquido(); $em->persist($funcionario); $em->flush(); $this->addFlash('success', 'alteração feita com sucesso'); return $this->redirectToRoute('listar_funcionario'); } return [ 'funcionario' => $funcionario, 'form' => $form->createView() ]; } /** * @param Request $request * @param $id * @Route ("funcionario/apagar/{id}", name="deletar_funcionario") * @return Response */ public function delete(Request $request, $id) { $em = $this->getDoctrine()->getManager(); $funcionario = $em->getRepository(Funcionario::class)->find($id); if (!$funcionario) { $mensagem = "Funcionario não foi encontrado"; $tipo = "warning"; } else { $em->remove($funcionario); $em->flush(); $mensagem = "Funcionario excluído com sucesso!!!"; $tipo = "success"; } $this->get('session')->getFlashBag()->set($tipo, $mensagem); return $this->redirectToRoute("listar_funcionario"); } } <file_sep><?php namespace App\Controller; use App\Entity\User; use Symfony\Component\HttpFoundation\Request; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Security; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Symfony\Component\Security\Http\Authentication\AuthenticationUtils; class DefaultController extends Controller { /** * @Route("/", name="default") */ public function index() { return $this->render('default/index.html.twig', [ 'controller_name' => 'DefaultController', ]); } /** * @Route("/login", name="login" ) * @Template("default/login.html.twig") * @param Request $request * @param AuthenticationUtils $authUtils * @return array */ public function login(Request $request, AuthenticationUtils $authUtils) { $error = $authUtils->getLastAuthenticationError(); $lastUsername = $authUtils->getLastUsername(); return [ 'error' => $error, 'last_username' => $lastUsername ]; } } <file_sep><?php namespace App\Entity; use Doctrine\ORM\Mapping as ORM; use Symfony\Component\Validator\Constraints as Assert; /** * @ORM\Entity(repositoryClass="App\Repository\FuncionarioRepository") */ class Funcionario { /** * @ORM\Id() * @ORM\GeneratedValue() * @ORM\Column(type="integer") * */ private $id; /** @var Secretaria * @ORM\ManyToOne(targetEntity="App\Entity\Secretaria") * @Assert\NotBlank() */ private $secretaria; /** * @var string * @ORM\Column(type="string", length=50) * @Assert\NotBlank() */ private $nome; /** * @var integer * @ORM\Column(type="integer") * @Assert\Notblank() * @Assert\Range(min="0", max="70") */ private $idade; /** * @var string * @ORM\Column(type="string", length=1) * @Assert\Choice(choices={"M","F"}) */ private $sexo; /** * @var \DateTime * @ORM\Column(type="date") * @Assert\NotBlank() * @Assert\Date() */ private $data_nascimento; /** * @var Endereco * @ORM\ManyToOne(targetEntity="App\Entity\Endereco", cascade={"persist"}) * @Assert\Valid() */ private $endereco; /** * @var string * @ORM\Column(type="string", length=16, unique=true) * @Assert\NotBlank(message="O campo nome não pode ser vazio!") */ private $cpf; /** * @var string * * @ORM\Column(type="string") * @Assert\File(mimeTypes={"application/pdf"}, mimeTypesMessage="arquivo invalido") * @Assert\NotBlank(message = "selecione um pdf para esse campo") */ private $imagem_documento; /** * @var string * @ORM\Column(type="string", length=14) * @Assert\Notblank() * @Assert\Choice(choices={"Efetivo", "Comissionado"}) */ private $cargo; /** @var \Date * @ORM\Column(type="date") * @Assert\Date() * @Assert\Notblank() * */ private $data_admissao; /** * @var \Date * @ORM\Column(type="date", nullable=true) * @Assert\Date() * @Assert\Expression( * "this.getStatus() == 'A' && value == '' || this.getStatus() == 'E' && value != '' ", * message=" verificar o campo." *) */ private $data_exoneracao; /** * @var string * @ORM\Column(type="string", length=1) * @Assert\Choice(choices={"A", "E"}) */ private $status = "A"; /** @var float * @ORM\Column(type="decimal", precision=10, scale=2) * @Assert\NotBlank() * @Assert\Range(min="0", max="100000") */ private $sal_base; /** * @var float * @ORM\Column(type="decimal", precision=10, scale=2, nullable=true) * @Assert\Range(min="0", max="100000") * @Assert\Expression( * "this.getCargo() == 'Comissionado' && value == '' || this.getCargo() == 'Efetivo' && value != '' ", * message="não preencher") */ private $gratif; /** * @var float * @ORM\Column(type="decimal", precision=10, scale=2) * @Assert\NotBlank() * @Assert\Range(min="0", max="100000") * */ private $desconto; /** @var float * @ORM\Column(type="decimal", precision=10, scale=2) * @Assert\Range(min="0", max="100000") */ private $liquido; public function calculoLiquido() { $result_liquido = ($this->getSalBase() + $this->getGratif()) - $this->getDesconto(); $this->setLiquido($result_liquido); } public function getId() { return $this->id; } public function getSecretaria() { return $this->secretaria; } public function setSecretaria($secretaria) { $this->secretaria = $secretaria; return $this; } public function getNome() { return $this->nome; } public function setNome($nome) { $this->nome = $nome; return $this; } public function getIdade() { return $this->idade; } public function setIdade($idade) { $this->idade = $idade; return $this; } public function getSexo() { return $this->sexo; } public function setSexo($sexo) { $this->sexo = $sexo; return $this; } public function getDataNascimento() { return $this->data_nascimento; } public function setDataNascimento($data_nascimento) { $this->data_nascimento = $data_nascimento; return $this; } public function getEndereco() { return $this->endereco; } public function setEndereco($endereco) { $this->endereco = $endereco; return $this; } public function getCpf() { return $this->cpf; } public function setCpf($cpf) { $this->cpf = $cpf; return $this; } /** * @return string */ public function getImagemDocumento() { return $this->imagem_documento; } /** * @param string $imagem_documento * @return Funcionario */ public function setImagemDocumento($imagem_documento) { $this->imagem_documento = $imagem_documento; return $this; } public function getCargo() { return $this->cargo; } public function setCargo($cargo) { $this->cargo = $cargo; return $this; } public function getDataAdmissao() { return $this->data_admissao; } public function setDataAdmissao($data_admissao) { $this->data_admissao = $data_admissao; return $this; } public function getDataExoneracao() { return $this->data_exoneracao; } public function setDataExoneracao($data_exoneracao) { $this->data_exoneracao = $data_exoneracao; return $this; } public function getStatus() { return $this->status; } public function setStatus($status) { $this->status = $status; return $this; } /** * @return float */ public function getSalBase() { return $this->sal_base; } /** * @param float $sal_base * @return Funcionario */ public function setSalBase(float $sal_base): Funcionario { $this->sal_base = $sal_base; return $this; } /** * @return float */ public function getGratif() { return $this->gratif; } /** * @param float $gratif * @return Funcionario */ public function setGratif(?float $gratif): Funcionario { $this->gratif = $gratif; return $this; } /** * @return float */ public function getDesconto() { return $this->desconto; } /** * @param float $desconto * @return Funcionario */ public function setDesconto(float $desconto): Funcionario { $this->desconto = $desconto; return $this; } /** * @return float */ public function getLiquido() { return $this->liquido; } /** * @param float $liquido * @return Funcionario */ public function setLiquido(float $liquido): Funcionario { $this->liquido = $liquido; return $this; } } <file_sep><?php namespace App\Controller; use App\Entity\Secretaria; use App\Enum\FuncionarioStatusEnum; use App\Form\RelatorioSecretariaType; use App\Form\RelatorioType; use App\Repository\FuncionarioRepository; use PhpOffice\PhpSpreadsheet\Spreadsheet; use PhpOffice\PhpSpreadsheet\Writer\Xlsx; use Sensio\Bundle\FrameworkExtraBundle\Configuration\Template; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\Routing\Annotation\Route; use Symfony\Bundle\FrameworkBundle\Controller\Controller; use Dompdf\Dompdf; require __DIR__ . '/../../vendor/autoload.php'; class RelatorioController extends Controller { /** * @Route("/relatorio", name="relatorio") */ public function index() { return $this->render('relatorio/index.html.twig', [ 'controller_name' => 'RelatorioController', ]); } /** * @param Request $request * @Route("/relatorio/funcional", name="relatorio_funcionario") * @return Response */ public function relatorioFuncionario(Request $request, FuncionarioRepository $funcionarioRepository) { $funcionarios = []; $form = $this->createForm(RelatorioType::class, $funcionarios); $form->handleRequest($request); if ($form->isSubmitted() && $form->isValid()) { $data = $form->getData(); $funcionarios = $funcionarioRepository->getFuncionarioPorData( $data['data_inicio'], $data['data_fim'], $data['status'] ); $pdfClicked = $form->get('pdf')->isClicked(); if ($pdfClicked) { return $this->funcionarioPdf($funcionarios); } $excelClicked = $form->get('excel')->isClicked(); if ($excelClicked) { $plan = $this->funcionarioXls($funcionarios); return new Response( $plan, 200, array( 'Content-Type' => 'application/vnd.ms-excel', 'Content-Disposition' => 'attachment; filename="myfile.xlsx"', ) ); } } return $this->render('relatorio/funcional.html.twig', ['funcionarios' => $funcionarios, 'form' => $form->createView()] ); } /** * @param $funcionarios * @return mixed * @Route ("relatorio/funcional_pdf" , name="funcionario_pdf") * @Template ("relatorio/funcional_pdf.html.twig") */ private function funcionarioPdf($funcionarios) { $view = $this->renderView('relatorio/funcional_pdf.html.twig', [ 'funcionarios' => $funcionarios ]); $domPdf = new Dompdf(); $domPdf->loadHtml($view); $domPdf->setPaper('A4', 'portrait'); $domPdf->render(); return $domPdf->stream('relatorio_funcionario'); } /** * @Route("/relatorio/funcional_xls", name="relatorio_xls") * */ private function funcionarioXls($funcionarios) { $spreadsheet = new Spreadsheet(); //instanciando uma nova planilha $total = $funcionarios; $plan = $spreadsheet->getActiveSheet(); //retornando a aba ativa $plan->setCellValue('A1', 'Mat.'); $plan->setCellValue('B1', 'Nome'); $plan->setCellValue('C1', 'Cargo'); $plan->setCellValue('D1', 'Status'); $plan->setCellValue('E1', 'Data de admissao'); $plan->setCellValue('F1', 'Data de exoneração'); $contador = 1; foreach ($total as $linha) { $contador++; $plan->setCellValue('A' . $contador, $linha->getId()); $plan->setCellValue('B' . $contador, $linha->getNome()); $plan->setCellValue('C' . $contador, $linha->getCargo()); $plan->setCellValue('D' . $contador, $linha->getStatus()); $plan->setCellValue('E' . $contador, $linha->getDataAdmissao()); $plan->setCellValue('F' . $contador, $linha->getDataExoneracao()); } $writer = new Xlsx ($spreadsheet); ob_start(); $writer->save('php://output'); return ob_get_clean(); } /** * @param Request $request * * @Route("/relatorio/secretaria",name="relatorio_secretaria") * @Template("relatorio/secretaria.html.twig") * @return Response */ public function relatorioSecretaria(Request $request, FuncionarioRepository $funcionarioRepository) { return $this->render( 'relatorio/secretaria.html.twig', ['totalSalariosLiquido' => $funcionarioRepository->salarioTotal()] ); } /** * @Route("/relatorio/secretaria_pdf", name="secretaria_pdf") */ public function secretariaPdf(Request $request, FuncionarioRepository $funcionarioRepository) { $view = $this->renderView( 'relatorio/secretaria_pdf.html.twig', ['totalSalariosLiquido' => $funcionarioRepository->salarioTotal()] ); $domPdf = new Dompdf(); $domPdf->loadHtml($view); $domPdf->setPaper('A4', 'portrait'); $domPdf->render(); return $domPdf->stream("Relatório_Secretaria.pdf"); } }<file_sep><?php namespace App\Form; use App\Entity\Funcionario; use Symfony\Bridge\Doctrine\Form\Type\EntityType; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\Extension\Core\Type\BirthdayType; use Symfony\Component\Form\Extension\Core\Type\ChoiceType; use Symfony\Component\Form\Extension\Core\Type\DateType; use Symfony\Component\Form\Extension\Core\Type\FileType; use Symfony\Component\Form\Extension\Core\Type\IntegerType; use Symfony\Component\Form\Extension\Core\Type\MoneyType; use Symfony\Component\Form\Extension\Core\Type\SubmitType; use Symfony\Component\Form\Extension\Core\Type\TextType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\Form\Extension\Core\Type\CurrencyType; use Symfony\Component\Form\SubmitButton; use Symfony\Component\OptionsResolver\OptionsResolver; class FuncionarioType extends AbstractType { /** * @param FormBuilderInterface $builder * @param array $options */ public function buildForm(FormBuilderInterface $builder, array $options) { $builder ->add('secretaria', EntityType::class, [ 'label' => "Secretaria", 'class' => 'App\Entity\Secretaria', 'choice_label' => 'nome', 'multiple' => false, ]) -> add('nome', TextType::class, [ 'label' => "Nome", 'attr' => [ 'placeholder' => "Informe seu nome", ] ]) ->add('idade', IntegerType::class, [ 'label' => "idade", 'attr' => [ 'min' => 0, 'max' => 65, 'step' => 2, 'placeholder' => "informa sua idade", ] ]) ->add('sexo', ChoiceType::class, [ 'label' => "sexo", 'choices' => [ 'selecione' => "", 'masculino' => "M", 'feminino' => "F", ] ]) ->add('status', ChoiceType::class, [ 'label' => "status", 'choices' => [ 'selecione' => "", 'Ativo' => "A", 'Exonerado' => "E", ] ]) ->add('data_nascimento', BirthdayType::class, [ 'label' => "Data de Nascimento", 'format' => 'dd-MM-yyyy', 'widget' => 'choice' ]) ->add('endereco', EnderecoType::class, [ 'label' => "Dados de Endereço" ]) ->add('cargo', ChoiceType::class, [ 'label' => 'Cargo:', 'choices' => [ 'Cargo_Efetivo' => 'Efetivo', 'Cargo_Comissionado' => 'Comissionado' ] ]) ->add('cpf', TextType::class, [ 'required' => false, 'attr' => ['data-mask' => '000.000.000-00', 'placeholder' => "_ _ _ . _ _ _ . _ _ _ - _ _" ] ]) ->add('imagem_documento', FileType::class, array('data_class' => null), [ 'label' => 'imagem_documento (PDF file)' ]) ->add('data_admissao', DateType::class, [ 'widget' => 'single_text', ]) ->add('data_exoneracao', DateType::class, [ 'widget' => 'single_text' ]) ->add('sal_base', MoneyType::class, [ 'label' => "Salário Base", 'currency' => 'BRL', 'attr' => [ 'placeholder' => "Informe seu salário", ] ]) ->add('gratif', MoneyType::class, [ 'label' => "Gratificação", 'currency' => 'BRL', 'attr' => [ 'placeholder' => "Informe sua gratificação", ] ]) ->add('desconto', MoneyType::class, [ 'label' => "Desconto", 'currency' => 'BRL', 'attr' => [ 'placeholder' => "Informe sua gratificação", ] ]) ->add('liquido', MoneyType::class, [ 'label' => "Salário Líquido", 'currency' => 'BRL', 'attr' => [ 'placeholder' => "Valor do líquido", ] ]) ->add('enviar', SubmitType::class, ['label' => "salvar", 'attr' => [ 'class' => 'btn btn-primary' ] ]) ->add('voltar', SubmitType::class, ['label' => "voltar", 'attr' => [ 'class' => 'btn bt-primary' ] ]); } public function configureOptions(OptionsResolver $resolver) { $resolver->setDefaults([ // uncomment if you want to bind to a class 'data_class' => Funcionario::class, ]); } } <file_sep><?php namespace App\Tests; use App\Entity\Funcionario; use PHPUnit\Framework\TestCase; class FuncionarioTest extends TestCase { public function testIfIdsNull() { $funcionario = new Funcionario(); $this->assertNull($funcionario->getId()); } /** * @param $sexo * @dataProvider collectionDados */ public function testEncapsulamento($propriedade, $esperado, $atual) { $funcionario = new Funcionario(); $null = $funcionario->{'get' . ucfirst($propriedade)}(); if (!is_float($esperado)) { $this->assertNull($null); } else { if (is_float($esperado)) { $this->assertEquals(0.0, $null); } else { $this->assertEquals(0, $null); } } $resultado = $funcionario->{'set' . ucfirst($propriedade)}($atual); $this->assertInstanceOf(Funcionario::class, $resultado); $atual = $funcionario->{'get' . ucfirst($propriedade)}(); $this->assertEquals($esperado, $atual); } public function collectionDados() { return [ ['nome', 'renan', 'renan'], ['idade', 20, 20], ['cpf', 76767676, 76767676], ['dataAdmissao', '1981-07-02', '1981-07-02'], ['salBase', '2000.00', '2000.00'], ['gratif', '1000.00', '1000.00'], ['desconto', '200.00', '200.00'] ]; } public function testIfCalculoLiquidosNull() { $funcionario = new Funcionario(); $this->assertNull($funcionario->calculoLiquido()); } public function testSetAndGetLiquido() { $funcionario = new Funcionario(); $this->assertNull($funcionario->getLiquido()); $this->assertInstanceOf(Funcionario::class, $funcionario->setLiquido("2345.00")); $this->assertEquals('2345.00', $funcionario->getLiquido()); } }
3b5db12d6ef4453c52f5d417f10ec72d41ca0eb9
[ "Markdown", "PHP" ]
14
PHP
AlexVeiga77/sistema-de-controle
540a26ea580788ec2679409c1184a12a1b605b0d
e625e3a1d5c333db264d9f208a9a0a62886a5d87
refs/heads/master
<file_sep>README v20150611 HTML_Tool is my implementation of a problem previously addressed by many devs. My attempt might suck a little, and that's OK. WHAT'S NEW Nothing, it doesn't exist yet. WHAT'S PLANNED SOON * Define user workflow User runs Python script in shell. GUI prompt for file input. Script prints a couple status updates. Script saves the new HTML file to a predetermined folder and closes. * Create basic HTML document Including DOCTYPE and necessary tags * Support for basic HTML formatting Boldface.........................*boldface* Italics.........................._italics_ New paragraph....................Blank line? Limited font choices.............No idea Header 1.........................String of equal signs underneath Header 2.........................String of dashes underneath Underline........................-underline- Center align.....................No idea Hyperlink........................(text;;URL) HOW DOES IT WORK? IDK yet. I am envisioning reading line-by-line and doing replacements, but then what about the headers? We will see. SHOULD YOUR DOCUMENTATION SUCK THIS MUCH? SHOULDN'T WELL PLANNED DOCS BE HALF THE BATTLE FOR A PROJECT? No. IDK, but I guess I will learn. <file_sep>''' Accepts a plaintext document and converts to publishable HTML. This has been done before! ''' ''' TODO * De '''
cfef3d9c4b4782d6b428bc393c37147efeeb464a
[ "Python", "Text" ]
2
Text
jviso/HTML_Tool
e5dcc4b83e4d169f12b679a286e27e8096ad24c2
a7617407e81313ce24f0323b42f809944a79f731
refs/heads/master
<repo_name>gzlupko/People_Analytics<file_sep>/Predicting Employee Turnover .R <<<<<<< HEAD ======= >>>>>>> bae979534d243ba35e9cc95a80b0c617af6628fc #IBM Employee Attrition & Performance Data getwd() setwd("/Users/gianzlupko/Desktop/R/R_Notebooks/IBM_HR_Dataset") # load packages used in this notebook # - - - - - - - - - - - - - - - # data manipulation library(dplyr) library(readr) library(broom) # visualization library(ggplot2) library(RColorBrewer) library(gridExtra) library(wesanderson) # classification and model testing library(Information) library(caret) library(car) library(tidypredict) library(caTools) # - - - - - - - - - - - - - - - - # Import dataset getwd() setwd("/Users/gianzlupko/Desktop/R/R_Notebooks") employee_data <- read_csv("IBM_employee_data.csv") head(employee_data) View(employee_data) # - - - - - - - - - - - - - - - # Data Cleaning - data type conversions, drop columns, etc employee_filter <- employee_data %>% select(-c("Over18", "StandardHours", "EmployeeCount")) View(employee_filter) # - - - - - - - - - - - # check data types in set and convert as needed cols <-c("BusinessTravel", "Education", "Gender", "JobLevel") employee_filter[cols] <- lapply(employee_filter[cols], factor) # convert Attrition to numeric and create turnover column employee_filter <- employee_filter %>% mutate(turnover = ifelse(Attrition == "Yes", 1, 0)) class(employee_filter$turnover) # - - - - - - - - - - - - - - # Exploratory Data Analysis: # I) Attrition breakdown across the organization and within... # visualize attrition overall employee_filter %>% group_by(Attrition) %>% ggplot(aes(factor(Attrition))) + geom_bar(aes(fill = Attrition)) + scale_x_discrete(labels = c("Active", "Inactive")) + theme(axis.title.x = element_blank()) + ylab("Employee Count") + theme(legend.position = "none") + geom_text(stat = "count", aes(label = ..count..), vjust = -.5) + theme(text = element_text(size = 10)) + ggtitle("Total Active and Inactive Employees in Sample") + scale_fill_brewer(palette = "Paired") # Visualize attrition within enterprise subgroups # first is attrition within department employee_filter %>% group_by(Department) %>% summarize(turnover_rate = mean(turnover)) %>% ggplot(aes(x = reorder(Department, -turnover_rate),y = turnover_rate)) + geom_bar(stat = "identity", aes(fill = Department)) + theme(axis.title.x = element_blank()) + ylab("Turnover Rate") + scale_x_discrete(labels = c("Sales", "HR", "R&D")) + ggtitle("Turnover Rate by Department") + scale_fill_brewer(palette = "Paired") # Attrition by gender employee_filter %>% group_by(Gender) %>% summarize(turnover_rate = mean(turnover)) %>% ggplot(aes(Gender, turnover_rate)) + geom_bar(stat = "identity", aes(fill = Gender)) + theme(axis.title.x = element_blank()) + ylab("Turnover Rate") + theme(legend.position = "none") + scale_fill_brewer(palette = "Paired") + ggtitle("Turnover Rate by Gender") # Attrition by Job Level employee_filter %>% group_by(JobLevel) %>% summarize(turnover_rate = mean(turnover)) %>% ggplot(aes(JobLevel, turnover_rate)) + geom_bar(stat = "identity", aes(fill = JobLevel)) + theme(axis.title.x = element_blank()) + ylab("Turnover Rate") + theme(legend.position = "none") + scale_fill_brewer(palette = "Paired") + ggtitle("Turnover Rate by Job Level") # summarize total employee count in dataset by gender, department, job level, # education, job role gender_count <- employee_filter %>% count(Gender) %>% ggplot(aes(x = Gender, y = n, fill = Gender)) + geom_bar(stat = "identity") + theme(legend.position = "none") + scale_fill_brewer(palette = "Paired") + ylab("Count") + theme(axis.title.y = element_blank()) department_count <- employee_filter %>% count(Department) %>% ggplot(aes(x = Department, y = n, fill = Department)) + geom_bar(stat = "identity") + theme(axis.text.x = element_blank(), legend.position = "none") + scale_fill_brewer(palette = "Paired") + theme(axis.title.y = element_blank()) level_count <- employee_filter %>% count(JobLevel) %>% ggplot(aes(x = JobLevel, y = n, fill = JobLevel)) + geom_bar(stat = "identity") + theme(legend.position = "none") + scale_fill_brewer(palette = "Paired") + theme(axis.title.y = element_blank()) role_count <- employee_filter %>% count(JobRole) %>% ggplot(aes(x = JobRole, y = n, fill = JobRole)) + geom_bar(stat = "identity") + theme(axis.text.x = element_blank(), legend.position = "none") + scale_fill_brewer(palette = "Paired") + theme(axis.title.y = element_blank()) grid.arrange(gender_count, department_count, level_count, role_count, top = "Employee Count by Demography, Position, and Tenure") # summarize employee count in subgroups for current employees only gender_current <- employee_filter %>% filter(Attrition == "No") %>% count(Gender) %>% ggplot(aes(x = Gender, y = n, fill = Gender)) + geom_bar(stat = "identity") + theme(legend.position = "none") + ylab("") + scale_fill_brewer(palette = "Paired") department_current <- employee_filter %>% filter(Attrition == "No") %>% count(Department) %>% ggplot(aes(x = Department, y = n, fill = Department)) + geom_bar(stat = "identity") + theme(axis.text.x = element_blank(), legend.position = "none") + ylab("") + scale_fill_brewer(palette = "Paired") level_current <- employee_filter %>% filter(Attrition == "No") %>% count(JobLevel) %>% ggplot(aes(x = JobLevel, y = n, fill = JobLevel)) + geom_bar(stat = "identity") + theme(legend.position = "none") + ylab("") + scale_fill_brewer(palette = "Paired") role_current <- employee_filter %>% filter(Attrition == "No") %>% count(JobRole) %>% ggplot(aes(x = JobRole, y = n, fill = JobRole)) + geom_bar(stat = "identity") + theme(axis.text.x = element_blank(), legend.position = "none") + ylab("") + scale_fill_brewer(palette = "Paired") grid.arrange(gender_current, department_current, level_current, role_current, top = ("Employee Counts - Active Only")) # Density curves EDA employee %>% ggplot() + geom_density(aes(x = PercentSalaryHike, fill = Department), alpha = 0.3) + scale_fill_manual(values = wes_palette("Darjeeling1")) employee %>% ggplot() + geom_density(aes(x = PercentSalaryHike, fill = Gender), alpha = 0.3) + scale_fill_manual(values = wes_palette("Darjeeling1")) employee %>% ggplot() + geom_density(aes(x = PercentSalaryHike, fill = Gender), alpha = 0.3) + scale_fill_manual(values = wes_palette("Darjeeling1")) # - - - - - - - - - - - # Feature Engineering - e.g. job-hopping index, compa-ratio, age diff.s, # High Potentials View(employee_filter) employee <- employee_filter %>% mutate(hipo = ifelse(PerformanceRating == "4", 1, 0)) View(employee) employee %>% count(hipo) View(employee) employee %>% ggplot() + geom_density(aes(x = hipo, fill = Department), alpha = 0.3) + scale_fill_manual(values = wes_palette("Darjeeling1")) employee %>% ggplot() + geom_density(aes(x = PercentSalaryHike, fill = Gender), alpha = 0.3) + scale_fill_manual(values = wes_palette("Darjeeling1")) # Disengaged Employeess employee <- employee %>% mutate(disengaged = ifelse(JobSatisfaction == "1", 1, 0)) employee %>% group_by(disengaged) %>% count(disengaged) # Comparative Ratio of Compensation employee <- employee %>% group_by(JobLevel) %>% mutate(median_comp = median(MonthlyIncome), compa_ratio = (MonthlyIncome/ median_comp)) employee %>% distinct(JobLevel, median_comp) employee$compa_ratio[c(102,5,400)] # add compa level employee <- employee %>% mutate(compa_level = ifelse(compa_ratio > 1, "Above", "Below")) employee$compa_level[705] employee %>% ggplot() + geom_density(aes(x = JobLevel, fill = MonthlyIncome)) + theme(text = element_text(size = 12)) + scale_fill_brewer(palette = "Paired") # Annualized Salary employee <- employee %>% mutate(AnnualSalary = MonthlyIncome * 12) employee %>% group_by(JobLevel) %>% summarize(avg_salary = mean(AnnualSalary)) # Job Hop Index employee <- employee %>% mutate(job_hop = (TotalWorkingYears/ (NumCompaniesWorked + 1))) employee %>% ggplot() + geom_density(aes(x = job_hop)) + xlab("Density") + ylab("Job Hop Index") # - - - - - - - - - - - - # Significance Tests # Employee Engagement - Identify Disengaged # Were employees that left more disenaged than active employees? # Visualize and test significance: employee %>% group_by(Attrition) %>% summarize(avg_disengagement = mean(disengaged)) %>% ggplot(aes(Attrition, avg_disengagement)) + geom_col(aes(fill = Attrition)) + xlab("Left Company?") + ylab("% Disengaged") + theme(legend.position = "none") + scale_fill_brewer(palette = "Paired") + ggtitle("Attrition by Disengaged") t.test(disengaged ~ Attrition, data = employee) %>% tidy() # Are disengaged employees paid less? # Visualize and test with simple logistic regression: employee %>% mutate(dis_label = ifelse(disengaged == "1", "Disengaged", "Engaged")) %>% ggplot(aes(dis_label, MonthlyIncome)) + geom_boxplot(aes(group = dis_label)) glm(disengaged ~ MonthlyIncome + Gender, family = "binomial", data =employee) %>% summary() # Is turnover rate statistically higher for specific job levels? employee %>% group_by(JobLevel) %>% summarize(avg_turnover = mean(turnover)) %>% arrange(desc(avg_turnover)) employee %>% group_by(JobLevel) %>% summarize(avg_turnover = mean(turnover)) %>% ggplot(aes(JobLevel, avg_turnover, fill = JobLevel)) + geom_bar(stat = "identity") + ylab("Job Level") + xlab("Turnover Rate") + ggtitle("Turnover Rate by Job Level") glm(turnover ~ JobLevel, family = "binomial", data = employee) %>% summary() # Is job level correlated with disengagement? How about department or role? glm(disengaged ~ Department, family = "binomial", data = employee) %>% summary() glm(disengaged ~ JobRole, family = "binomial", data = employee) %>% summary() # There is not statistical correation with department or job role on disengagement. # But are either of these predictors statistically correlated with the observed attrition? glm(turnover ~ Department, family = "binomial", data = employee) %>% summary() glm(turnover ~ JobRole, family = "binomial", data = employee) %>% summary() # We see that department shows no statistical effect on attrition. However, job level does seem to # Does one's proclivity to job hopping predict attrition? glm(turnover ~ job_hop, family = "binomial", data = employee) %>% tidy() # - - - - - - - - - - - - - - - - - # Model Development - IV, split data sets, simple and logistic, # (cont) multicollinearity, remove collinear variables, final model, predict on train set # (cont) predict final model on test set, compare prob. distr. ranges, confusion matrix, # (cont) generate risk scores, ROI calculations and intervention strategies # generate information value with inital data set; IV <- create_infotables(data = employee, y = "turnover") IV$Summary # split data set set.seed(401) index_training <- createDataPartition(employee$turnover, p = 0.7, list = FALSE) training_set <- employee[index_training, ] testing_set <- employee[-index_training, ] # check that proportion in testing and training set are similar head(training_set) training_set %>% count(Attrition) %>% mutate(prop = n/sum(n)) testing_set %>% count(Attrition) %>% mutate(prop = n/sum(n)) # remove unwanted variables from data set # then generate inital model colnames(training_set) training_set_filter <- training_set %>% select(-c(EmployeeNumber, BusinessTravel, Attrition)) multi_log <- glm(turnover ~ ., family = "binomial", data = training_set_filter, maxit = 100) vif(multi_log) # check for errors summary(multi_log) # remove columns that appear to be perfectly collinear training_set_filter <- training_set_filter %>% select(-c(median_comp, AnnualSalary)) multi_log <- glm(turnover ~ ., family = "binomial", data = training_set_filter, maxit = 100) vif(multi_log) model_2 <- glm(turnover ~ . -JobRole, family = "binomial", data = training_set_filter, maxit = 100) vif(model_2) model_3 <- glm(turnover ~ . -JobRole - JobLevel, family = "binomial", data = training_set_filter, maxit = 100) vif(model_3) model_final <- glm(turnover ~ . -JobRole - JobLevel -YearsAtCompany, family = "binomial", data = training_set_filter, maxit = 100) vif(model_final) # high VIF scores successfully removed training_prediction <- predict(model_final, newdata = training_set_filter, type = "response") hist(training_prediction) # predict probability distribution for testing data set testing_prediction <- predict(model_final, newdata = testing_set, type = "response") hist(testing_prediction) # classify predictions with cutoff score predicition_cutoff <- ifelse(testing_prediction > 0.5, 1, 0) table(predicition_cutoff, testing_set$turnover) summary(model_final) # create confusion matrix library(caret) conf_matrix <- confusionMatrix(table(testing_set$turnover, predicition_cutoff)) conf_matrix # develop a similar model with pared down predictors. Compare AIC values for each model # lower AIC indicates more accurate model # - - - - - - - - - - - - - - - - - - - - # Part II - Need debugging # - - - - - - - - - - - - - set.seed(581) index_training_2 <- createDataPartition(employee$turnover, p = 0.5, list = FALSE) training_2 <- employee[index_training_2, ] testing_2 <- employee[-index_training_2, ] training_2 %>% count(Attrition) %>% mutate(prop = n/sum(n)) testing_2 %>% count(Attrition) %>% mutate(prop = n/sum(n)) training_2_filter <- training_2 %>% select(-c(EmployeeNumber, BusinessTravel, Department, OverTime, AnnualSalary, median_comp)) second_model <- glm(turnover ~ . - MonthlyIncome - JobLevel, family = "binomial", data = training_2_filter, maxit = 100) vif(second_model) summary(second_model) training_2_prediction <- predict(second_model, newdata = training_2_filter, type = "response") hist(training_2_prediction) # predict probability distribution for testing data set testing_2_prediction <- predict(second_model, newdata = testing_2, type = "response") hist(testing_2_prediction) # classify predictions with cutoff score predicition_2_cutoff <- ifelse(testing_2_prediction > 0.5, 1, 0) table(predicition_2_cutoff, testing_2$turnover) # create confusion matrix library(caret) conf_matrix_2_test <- confusionMatrix(table(testing_2$turnover, predicition_2_cutoff)) conf_matrix_2_test confusionMatrix(conf_matrix_2_test) # V) Risk Evaluation & ROI Calculations # filter for current employees only # then use tidypredict_to_column() to assign risk scores # generate column of risk scores column in table of current employees employee_current <- employee %>% filter(Attrition == "No") employee_current$churn_risk <- predict(model_final, newdata = employee_current, type = "response") # check random employees' churn risk employee_current$churn_risk[c(100, 1003)] # break churn risk into buckets employee_risk <- employee_current %>% mutate(risk_level = cut(churn_risk, breaks = c(0, 0.2, 0.3, 0.5, 1), labels = c("no-risk", "low-risk", "medium-risk", "high-risk"))) employee_risk %>% group_by(risk_level) %>% count(risk_level) Develop new model to test change in probability distribution install.packages("caTools") library(caTools) View(employee) # select shorter list of predictors for new logit model # pull from information value matrix # split data split <- sample.split(employee, SplitRatio = 0.7) split train <- subset(employee, split == "TRUE") test <- subset(employee, split == "FALSE") IV new_logit <- glm(turnover ~ JobRole + MonthlyIncome + OverTime + JobLevel + TotalWorkingYears + YearsAtCompany + Age, family = "binomial", data = train) vif(new_logit) summary(new_logit) new_logit_train_predict <- predict(new_logit, newdata = train, type = "response") hist(new_logit_train_predict) # run new model through test data set; check for # similarity in prediction distribution new_logit_test_predict <- predict(new_logit, newdata = test, type = "response") hist(new_logit_test_predict) # confusion matrix new_logit_conf_matrix <- table(train$turnover, new_logit_train_predict > 0.5) new_logit_conf_matrix (new_logit_conf_matrix[[1,1]] + new_logit_conf_matrix[[2,2]]) / sum(new_logit_conf_matrix) # can also use caret package confusionMatrix() for more detailed summary # Classify predictions using a cut-off of 0.5 new_logit_prediction_categories <- ifelse(new_logit_test_predict > 0.5, 1, 0) # Construct a confusion matrix new_logit_conf_matrix <- table(new_logit_prediction_categories, test$turnover) new_logit_conf_matrix confusionMatrix(new_logit_conf_matrix) library(class) # kNN take 2 head(employee) View(employee) em <- employee %>% ungroup(JobLevel) %>% select(Attrition, DailyRate, EnvironmentSatisfaction, PerformanceRating, RelationshipSatisfaction) head(em) str(em) table(em$Attrition) ran <- runif(nrow(em)) ran em <- em [order(ran), ] normalize <- function(x) { return ((x - min(x)) / (max(x) - min(x))) } em_norm <- as.data.frame(lapply(em[2:5], normalize)) str(em_norm) 1470 * 0.7 1470- 1029 sqrt(1470) head(em) em_train <- em_norm[1:1029, ] em_test <- em_norm[1030:1470, ] em_train_target <- em$Attrition[1:1029] em_test_target <- em$Attrition[1030:1470] class(em_train_target) class(em_test_target) # kNN classifying attrition library(class) library(caret) em_test_pred <- knn(train = em_train, test = em_test, cl = em_train_target, k = 38) tab <- table(em_test_pred, em_test_target) tab <file_sep>/README.md # Attrition Modeling The goal of this notebook is to explore the development of a risk model that forecasts the likelihood of employee attrition. First, I clean and explore the dataset to prepare it for subsequent analyses. After reviewing the organization's demographic and performance characteristics through EDA and feature engineering techniques, I generate two logistic regression models that predict employee turnover. The first regression model takes a large set of predictors while the second model includes only seven. I also explore the implementation of the k-Nearest Neighbors algorithm to predict employee attrition based on a host of predictors. Finally, after model validation, I explore the business case for possible HR intervention strategies. Discussion on intervention strategy and ROI estimates draw on recent research in HR and management journals around the cost of employee turnover. I) Import and Clean Data II) EDA III) Feature Engineering IV) Significance Testing V) Logistic Regression Modeling and Validation VI) k-Nearest Neighbors Classifier VII) Risk Assessment VIII) Workforce Retention Strategy For the analytics and documentation on this project's code, please follow the below link to my accompanying Kaggle notebook: https://www.kaggle.com/gianzlupko/predicting-employee-churn-proposing-intervention ![alt text](https://github.com/gzlupko/People_Analytics/blob/master/EDA_2.png) ![alt text](https://github.com/gzlupko/People_Analytics/blob/master/EDA_1.png)
584ad7e08effafeccde8f9b5fb03cb73e4f0f943
[ "Markdown", "R" ]
2
R
gzlupko/People_Analytics
3ba207f91d5f879cb7e1505d3021a39c0645814b
c289cd783c74034550e25d5e68d1d0874eb0f8a7
refs/heads/master
<file_sep>$(function () { "use strict"; // --- Setup --- var DIM = 160, BLOCKSIZE = undefined, PLAYING = false, GRID = [], COLOR = '#00ff00', TIMEOUT = 100; for (var x=0; x<DIM; x++) { GRID[x] = []; for (var y=0; y<DIM; y++) { GRID[x][y] = false; } } // Manual figures var manual_figures = { 'Single Cell': [[0,0]], // Stationaries '[Stationary] Block': [[0,0],[0,1],[1,0],[1,1]], '[Stationary] Beehive': [[1,0],[2,0],[0,1],[3,1],[1,2],[2,2]], '[Stationary] Loaf': [[0,1],[1,0],[1,2],[2,0],[2,3],[3,1],[3,2]], '[Stationary] Boat': [[0,0],[0,1],[1,0],[1,2],[2,1]], // Oscillators '[Oscillator] Blinker (horiz.)': [[0,0],[1,0],[2,0]], '[Oscillator] Blinker (vert.)': [[0,0],[0,1],[0,2]], '[Oscillator] Toad': [[1,0],[2,0],[3,0],[0,1],[1,1],[2,1]], '[Oscillator] Beacon': [[0,0],[0,1],[1,0],[1,1],[2,2],[2,3],[3,2],[3,3]], // Spaceships '[Spaceship] Glider (NE)': [[0,0],[1,0],[2,0],[2,1],[1,2]], '[Spaceship] Glider (NW)': [[0,0],[1,0],[2,0],[0,1],[1,2]], '[Spaceship] Glider (SE)': [[0,2],[1,0],[1,2],[2,2],[2,1]], '[Spaceship] Glider (SW)': [[0,2],[1,0],[1,2],[2,2],[0,1]], '[Spaceship] LWSS (E)': [[4,1],[4,2],[4,3],[3,0],[3,3],[2,3],[1,3],[0,0],[0,2]], '[Spaceship] LWSS (W)': [[0,1],[0,2],[0,3],[1,0],[1,3],[2,3],[3,3],[4,0],[4,2]], '[Spaceship] LWSS (N)': [[0,0],[0,1],[0,2],[0,3],[1,0],[1,4],[2,0],[3,1],[3,4]], '[Spaceship] LWSS (S)': [[0,4],[0,3],[0,2],[0,1],[1,4],[1,0],[2,4],[3,3],[3,0]], // Methuselahs '[Methuselah] F-pentomino': [[0,1],[1,0],[1,1],[1,2],[2,0]], '[Methuselah] Diehard': [[0,1],[1,1],[1,2],[5,2],[6,0],[6,2],[7,2]], '[Methuselah] Acorn': [[0,2],[1,0],[1,2],[3,1],[4,2],[5,2],[6,2]], // Guns '[Gun] Gosper glider gun': [[0,4],[0,5],[1,4],[1,5],[10,4],[10,5],[10,6],[11,3],[11,7],[12,2],[12,8],[13,2],[13,8],[14,5],[15,3],[15,7],[16,4],[16,5],[16,6],[17,5],[20,2],[20,3],[20,4],[21,2],[21,3],[21,4],[22,1],[22,5],[24,0],[24,1],[24,5],[24,6],[34,3],[34,4],[35,3],[35,4]], '[Gun] Minimal (10 cell)': [[0,5],[2,4],[2,5],[4,1],[4,2],[4,3],[6,0],[6,1],[6,2],[7,1]], '[Gun] 5x5': [[0,0],[0,1],[0,4],[1,0],[1,3],[2,0],[2,3],[2,4],[3,2],[4,0],[4,2],[4,3],[4,4]], '[Gun] Single row': [[0,0],[1,0],[2,0],[3,0],[4,0],[5,0],[6,0],[7,0],[9,0],[10,0],[11,0],[12,0],[13,0],[17,0],[18,0],[19,0],[26,0],[27,0],[28,0],[29,0],[30,0],[31,0],[32,0],[34,0],[35,0],[36,0],[37,0],[38,0]], }; // Use manual figures and figures from js/collection.js var figures = $.extend({}, manual_figures, COLLECTION); // Add options to <select> $.each(figures, function(name, coordinates) { $('#SelectFigure').append($('<option></option>').val(name).html(name)); }); // --- Event handlers --- $('#ButtonSettingsSave').click(function () { var bg, color, timeout, dim; bg = $('#InputBackground').val(); color = $('#InputColor').val(); timeout = parseInt($('#InputTimeout').val(), 10); dim = parseInt($('#InputDim').val(), 10); $('#GoL').css('background-color', bg); COLOR = color; TIMEOUT = timeout; if (dim !== DIM) { DIM = dim; GRID = []; for (var x=0; x<DIM; x++) { GRID[x] = []; for (var y=0; y<DIM; y++) { GRID[x][y] = false; } } draw(); } $('#ModalSettings').modal('hide'); }); $('#ButtonAdd').click(function () { var figure, x, y; figure = $('#SelectFigure').val(); x = parseInt($('#InputX').val(), 10); y = parseInt($('#InputY').val(), 10); if (x < 0 || x >= DIM || y < 0 || y >= DIM) { alert('Invalid position!'); } else if (figure === '') { alert('No figure'); } else { var coordinates = figures[figure]; if (coordinates) { for (var i=0; i<coordinates.length; i++) { GRID[x+coordinates[i][0]][y+coordinates[i][1]] = true; } } else { alert('Not a valid figure.'); } } $('#ModalAdd').modal('hide'); draw(); }); $('#ButtonClear').click(function () { for (var x=0; x<GRID.length; x++) { for (var y=0; y<GRID[x].length; y++) { GRID[x][y] = false; } } draw(); }); $('#TogglePlay').click(function () { if (PLAYING) { PLAYING = false; } else { PLAYING = true; play(); } }); $('#ButtonStep').click(function () { step(); draw(); }); $('#ButtonFullscreen').click(function () { var $gol = $('#GoL'); $gol = $gol[0]; $gol.webkitRequestFullScreen(Element.ALLOW_KEYBOARD_INPUT); $gol.mozRequestFullScreen(); }); // Place cells with the mouse $('#GoL').click(function(evt) { var x = Math.floor(evt.offsetX/BLOCKSIZE), y = Math.floor(evt.offsetY/BLOCKSIZE); GRID[x][y] = !GRID[x][y]; draw(); }); // Experimental $('#ButtonRandom').click(function() { var num = 1000, x, y; for (var i=0; i < num; i++) { x = Math.floor(Math.random()*DIM); y = Math.floor(Math.random()*DIM); GRID[x][y] = true; } draw(); }); // --- Functions --- function draw () { var $gol = $('#GoL'), canvas, context, dim; canvas = $gol[0]; if (canvas.getContext) { context = canvas.getContext('2d'); /* Adjust canvas size. */ var w, h; w = $(document).width(); h = $(document).height(); dim = w < h? w: h; dim -= 54; canvas.width = dim; canvas.height = dim; $gol.innerWidth(dim); $gol.innerHeight(dim); BLOCKSIZE = dim/DIM; //Clear canvas. canvas.width = canvas.width; // Print GRID to canvas. context.fillStyle = COLOR; for (var x=0; x<GRID.length; x++) { for (var y=0; y<GRID[x].length; y++) { if (GRID[x][y]) { context.fillRect(x*BLOCKSIZE, y*BLOCKSIZE, BLOCKSIZE, BLOCKSIZE); } } } } } function step () { var buffer_last, buffer_current, num_neighbours; for (var x=0; x<GRID.length; x++) { buffer_last = buffer_current; buffer_current = GRID[x].slice(); for (var y=0; y<buffer_current.length; y++) { // Count neighbours. num_neighbours = 0; // Row to the left. if (buffer_last) { if (buffer_last[y-1]) {num_neighbours++;} if (buffer_last[y]) {num_neighbours++;} if (buffer_last[y+1]) {num_neighbours++;} } // This row. if (buffer_current[y-1]) {num_neighbours++;} if (buffer_current[y+1]) {num_neighbours++;} // Row to the right. if (GRID[x+1]) { if (GRID[x+1][y-1]) {num_neighbours++;} if (GRID[x+1][y]) {num_neighbours++;} if (GRID[x+1][y+1]) {num_neighbours++;} } // Apply rules (shortened - only changes) if ((buffer_current[y] && num_neighbours !== 2 && num_neighbours !== 3) || (!buffer_current[y] && num_neighbours === 3)) { GRID[x][y] = !buffer_current[y]; } } } } function play () { step(); draw(); if (PLAYING) { setTimeout(play, TIMEOUT); } } });
26f41f5393d2ae16342ffcec020691e7526c5758
[ "JavaScript" ]
1
JavaScript
kdungs/GoL
a13222d68839cb192f154a255092d170184e409e
4d383c21774e9595eaed742d9f50cd76bdeb0269
refs/heads/master
<repo_name>tsekhov88/HomeWork_8<file_sep>/Phone_number_2.sql -- phpMyAdmin SQL Dump -- version 4.6.6deb5 -- https://www.phpmyadmin.net/ -- -- Хост: localhost:3306 -- Время создания: Июл 17 2019 г., 15:32 -- Версия сервера: 5.7.26-0ubuntu0.18.04.1 -- Версия PHP: 7.2.19-0ubuntu0.18.04.1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- База данных: `vitaly_test_db` -- -- -------------------------------------------------------- -- -- Структура таблицы `Phone number_2` -- CREATE TABLE `Phone number_2` ( `id` int(10) UNSIGNED NOT NULL, `phone` varchar(16) CHARACTER SET utf8 NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Дамп данных таблицы `Phone number_2` -- INSERT INTO `Phone number_2` (`id`, `phone`) VALUES (1, '+79181234567'), (2, '+79181256345'), (3, '+79181253456'), (4, '+79281224567'), (5, '+79181432371'), (6, '+79285984533'), (7, '+79183536666'); -- -- Индексы сохранённых таблиц -- -- -- Индексы таблицы `Phone number_2` -- ALTER TABLE `Phone number_2` ADD PRIMARY KEY (`id`); -- -- AUTO_INCREMENT для сохранённых таблиц -- -- -- AUTO_INCREMENT для таблицы `Phone number_2` -- ALTER TABLE `Phone number_2` MODIFY `id` int(10) UNSIGNED NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=8; /*!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 */;
23fe3758511628c756a1e7251ee362e247753b76
[ "SQL" ]
1
SQL
tsekhov88/HomeWork_8
9018cd8f592f27a31f9ae99f47bd90eed35b46e5
532048a4df3fb205abe257119b9f256572d7cc17
refs/heads/master
<file_sep>const upperCaseFinder = str => { for (const char of str) { if (char === char.toUpperCase() && char !== char.toLowerCase()) { return char; } } return null; }; export default upperCaseFinder; <file_sep>const DEFAULT_SUBS = [ { name: "javascript", text: "J" }, { name: "reactjs", text: "R" }, { name: "webdev", text: "W" } ]; const loadSubs = () => { try { const subs = localStorage.getItem("subs"); if (subs) { return JSON.parse(subs); } return DEFAULT_SUBS; } catch (error) { return DEFAULT_SUBS; } }; export const initStore = { nav: { items: loadSubs() } }; <file_sep>export const subsPersist = store => next => action => { if (action.type !== "TOGGLE_SUB") return next(action); next(action); try { localStorage.setItem("subs", JSON.stringify(store.getState().nav.items)); } catch (error) { console.error("Failed to save subs."); } }; <file_sep>import ucf from "../utils/upperCaseFinder"; export const navReducer = (state = {}, action) => { switch (action.type) { case "SET_ACTIVE_REDDIT": return { ...state, active: action.item.toLowerCase() }; case "TOGGLE_SUB": const subs = state.items; const subreddit = action.subreddit; const mask = subreddit.toLowerCase(); let items = subs.filter(sub => sub.name !== mask); if (items.length === subs.length) { const text = ucf(subreddit) || subreddit.charAt().toUpperCase(); items.push({ name: mask, text }); } if (items.length > 0) return { ...state, items }; return state; default: return state; } }; <file_sep>import React, { Component } from "react"; import PropTypes from "prop-types"; import { connect } from "react-redux"; import Post from "../components/Post"; import Icon from "semantic-ui-react/dist/es/elements/Icon"; import { FetchError } from "../components/FetchError"; class Subreddit extends Component { static propTypes = { data: PropTypes.object, isLoading: PropTypes.bool, dispatch: PropTypes.func.isRequired, history: PropTypes.object.isRequired, match: PropTypes.object.isRequired }; componentDidMount() { this.fetchData(this.props.match.params.subreddit); } componentDidUpdate(prevProps, prevState) { const subreddit = this.props.match.params.subreddit; if (subreddit !== prevProps.match.params.subreddit) { this.fetchData(subreddit); } } componentWillUnmount() { const { dispatch } = this.props; dispatch({ type: "SET_ACTIVE_REDDIT", item: "" }); } fetchData(subreddit) { const { dispatch } = this.props; dispatch({ type: "SET_ACTIVE_REDDIT", item: subreddit }); const url = `/r/${subreddit}.json`; dispatch({ type: "FETCH", url }); } showComments = (e, url) => { e.preventDefault(); this.props.history.push(url); }; render() { const { data, isLoading, match, error } = this.props; return ( <React.Fragment> <div className="ui attached secondary segment"> <h4> {match.params.subreddit.toUpperCase()}&nbsp; {isLoading && <Icon name="circle notched" loading />} </h4> </div> <div className="ui attached segment"> {error && <FetchError error={error} />} {data.posts && data.posts.map(post => ( <Post key={post.id} post={post} showComments={e => this.showComments(e, post.permalink)} /> ))} </div> </React.Fragment> ); } } const mapState = state => { return { data: state.fetch.data, error: state.fetch.error, isLoading: state.fetch.isLoading }; }; export default connect(mapState)(Subreddit);
c032e6c7b27127a70920c1239a5a0c998081544c
[ "JavaScript" ]
5
JavaScript
PsySolix/reddit-client
c73a1e6f1080222e41e2a70a6bf6b3c019e40b0b
6904579981da5549ad6012a35166f559c8be19d3
refs/heads/master
<repo_name>Johnson19900110/phpJourney<file_sep>/routes/web.php <?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('/mailable', function () { $invoice = App\User::find(1); return new App\Mail\UserLogin($invoice); }); Route::group(['namespace' => 'App'], function () { Route::get('/test', 'HomeController@test'); Route::get('/redirect', 'HomeController@redirect'); Route::get('/auth/callback', 'HomeController@authCallback'); Route::get('/', 'HomeController@index')->name('home'); Route::get('/search', 'HomeController@search')->name('search'); Route::get('/post/{id}', 'HomeController@post')->name('post'); Route::get('/tags/{flag}', 'HomeController@tags')->name('tags'); Route::get('/category/{id}', 'HomeController@categories')->name('category'); Route::resource('/comments', 'CommentsController'); }); /** * Backend */ Route::group(['prefix' => 'back', 'namespace' => 'Backend'], function () { Route::get('/', 'IndexController@index')->name('admin'); Route::post('/auth/login', 'AuthController@authenticate'); Route::post('/auth/check', 'AuthController@checkUser'); Route::post('/auth/logout', 'AuthController@logout'); }); Route::group(['middleware' => 'auth', 'prefix' => 'back', 'namespace' => 'Backend'], function () { Route::resource('/users', 'UserController'); Route::resource('/category', 'CategoryController'); Route::resource('/posts', 'PostController'); Route::resource('/comment', 'CommentController'); Route::resource('/trashes', 'TrashController'); Route::post('/dashboard', 'IndexController@statistical'); }); <file_sep>/app/Http/Controllers/Backend/UserController.php <?php namespace App\Http\Controllers\Backend; use function foo\func; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; use phpseclib\Crypt\Hash; class UserController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * 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) { // } /** * 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, array( 'pass' => '<PASSWORD>', 'pass_confirmation' => '<PASSWORD>' )); $result = $request->user()->fill(array( 'password' => \Illuminate\Support\Facades\Hash::make($request->input('pass')) ))->save(); if($result) { Auth::logout(); return response()->json(array( 'status' => 0, 'message' => '修改成功' )); }else { return response()->json(array( 'status' => 1, 'message' => '修改失败' )); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Libraries/CnblogsPostSpider.php <?php namespace App\Libraries; use App\Post; use Goutte\CLient; use Symfony\Component\DomCrawler\Crawler; class CnblogsPostSpider { protected $client; protected $crawler; protected $urls = []; public function __construct(Client $client, $url) { $this->client = $client; $this->crawler = $client->request('GET', $url); } public function getUrls() { $urls = $this->crawler->filter('.postTitle > a')->each(function ($node) { return $node->attr('href'); }); foreach ($urls as $url) { $crawler = $this->client->request('GET', $url); $cnBlogId = $this->getCnBlogId($url); $post = new Post(); if($post->where('cnblogs_id', $cnBlogId)->count()) { // 已爬过该博客,只更新阅读和评论数 $post->where('cnblogs_id', $cnBlogId)->update([ 'views' => $this->getViews($crawler), 'comments' => $this->getComments($crawler), ]); }else { $post->insert([ 'title' => $this->getTitle($crawler), 'category_id' => 1, 'content' => $this->getContent($crawler), 'user_id' => 1, 'views' => $this->getViews($crawler), 'comments' => $this->getComments($crawler), 'cnblogs_id' => $cnBlogId, 'cnblogs_url' => $url, 'created_at' => $this->getCreatedAt($crawler), ]); } } } public function getCnBlogId($url) { $url_arr = explode('/', $url); $last = array_pop($url_arr); $path_arr = explode('.', $last); return intval(array_shift($path_arr)); } protected function getTitle(Crawler $crawler) { return trim($crawler->filter('.postTitle > a')->text()); } protected function getContent(Crawler $crawler) { return trim($crawler->filter('#cnblogs_post_body')->text()); } protected function getViews(Crawler $crawler) { return intval(trim($crawler->filter('#post_view_count')->text())); } protected function getComments(Crawler $crawler) { return intval($crawler->filter('#post_comment_count')->text()); } protected function getCreatedAt(Crawler $crawler) { return trim($crawler->filter('#post-date')->text()); } }<file_sep>/app/Http/ViewComposers/Navigation.php <?php /** * Created by PhpStorm. * User: Administrator * Date: 2017/12/1 * Time: 10:54 */ namespace App\Http\ViewComposers; use App\Category; use Illuminate\Support\Facades\Redis; use Illuminate\View\View; class Navigation { /** * 绑定数据到视图. * * @param View $view * @return void */ public function compose(View $view) { $categories = Category::get(); $view->with('categories', ($categories)); } } <file_sep>/app/Tag.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Tag extends Model { // /** * 获取tags对应的文章posts * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function posts() { return $this->belongsToMany(Post::class, 'posts_tags'); } } <file_sep>/app/MysqlPoolClient/Client.php <?php /** * Created by Administrator. * Author: Administrator * Date: 2018/2/11 */ namespace App\MysqlPool; trait Client { protected function mysqlLink(Array $data) { if(empty($data)) { return 'Params is empty'; } $client = new \swoole_client(SWOOLE_SOCK_TCP); $client->connect('0.0.0.0', 9508, 10) or die("Connect Pool Failure !"); $client->send($data); //Blocking for wait result $data = $client->recv(); $client->close(); return $data; } }<file_sep>/app/Http/Controllers/Backend/AuthController.php <?php namespace App\Http\Controllers\Backend; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Auth; class AuthController extends Controller { // Auth验证登录 public function authenticate(Request $request) { $email = $request->input('email'); $pass = $request->input('pass'); if(Auth::attempt(['email'=>$email, 'password'=>$pass], $request->filled('remember'))) { $user = Auth::user(); $data = array( 'status' => 0, 'message' => '登录成功', 'user' => array( 'name' => $user['name'], ) ); }else { $data = array( 'status' => 1, 'message' => '用户名或密码不正确', ); } return response()->json($data); } // Auth验证当前登录用户 public function checkUser() { return Auth::check() ? 0 : 1; } // 退出登录 public function logout() { Auth::logout(); return response()->json(array('status' => 0, 'message' => '退出成功')); } } <file_sep>/app/Http/Controllers/App/CommentsController.php <?php namespace App\Http\Controllers\App; use App\Comment; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Log; class CommentsController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index() { // } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // // try { $this->validate($request, array( 'post_id' => 'required', 'name' => 'required', 'email' => 'required|email', ),array( 'email' => '邮箱不合法' )); $comment = new Comment(); $comment->parent_id = $request->input('parent_id', 0); $comment->post_id = $request->input('post_id'); $comment->name = $request->input('name', ''); $comment->email = $request->input('email', ''); $comment->ip = $request->ip(); $comment->markdown = $markdown = $request->input('markdown', ''); $comment->content = (new \Parsedown())->text($markdown); $comment->save(); return response()->json(array( 'status' => 0, 'message' => '数据获取成功', 'comment' => $comment, )); // }catch (\Exception $exception) { // Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); // // return response()->json(array( // 'status' => 1, // 'message' => '数据获取失败', // )); // } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // $id = intval($id); try{ $comments = Comment::where('post_id', $id)->get(); return response()->json(array( 'status' => 0, 'comments' => $comments, )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '数据获取失败', )); } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy($id) { // } } <file_sep>/app/Http/Controllers/Backend/CommentController.php <?php namespace App\Http\Controllers\Backend; use App\Comment; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Log; class CommentController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // try{ $rows = $request->input('rows', 15); $comments = Comment::ofPost($request->input('post_id'))->ofContent($request->input('q'))->paginate($rows); $comments = $this->post_title($comments); return response()->json(array( 'status' => 0, 'data' => $comments, )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '数据获取成功', )); } } protected function post_title($comments) { foreach ($comments as $comment) { $comment->posts; } return $comments; } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * 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) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { // $ids = $request->input('ids'); if(!$ids || count($ids) <= 0) { return response()->json(array( 'status' => 2, 'message' => '请选择需要删除的数据', )); } try { Comment::destroy($ids); return response()->json(array( 'status' => 0, 'message' => '删除成功', )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '删除失败', )); } } } <file_sep>/app/Comment.php <?php namespace App; use Illuminate\Database\Eloquent\Model; class Comment extends Model { /** * 按文章查找评论 * @param $query * @param $post_id * @return mixed */ public function scopeOfPost($query, $post_id) { if(intval($post_id) > 0) { return $query->where('post_id', $post_id); } return $query; } /** * 搜索评论 * @param $query * @param $content * @return mixed */ public function scopeOfContent($query, $content) { if(!empty($content)) { return $query->where('content', 'like', '%' . $content . '%'); } return $query; } /** * 获取所属文章标题 * @return mixed */ public function posts() { return $this->belongsTo(Post::class, 'post_id')->select('title'); } } <file_sep>/public/opcacheReset.php <?php $result = opcache_reset(); if($result) { phpinfo(); }else { echo 'Failed'; } <file_sep>/app/Http/Controllers/Backend/IndexController.php <?php namespace App\Http\Controllers\Backend; use App\Comment; use App\Mail\UserLogin; use App\Post; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; class IndexController extends Controller { /** * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index() { return view('backend/index'); } public function statistical(Request $request) { $data = array(); // posts: 0, // comments: 0, // post_trash: 0, // recent_posts:[] try { $data['posts'] = Post::count(); $data['comments'] = Comment::count(); $data['post_trash'] = Post::onlyTrashed()->count(); $data['recent_posts'] = Post::orderBy('created_at', 'DESC')->limit(5)->get(); return response()->json(array( 'status' => 0, 'message' => '数据获取失败', 'data' => $data, )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '数据获取失败', )); } } } <file_sep>/app/Http/Controllers/Backend/TrashController.php <?php namespace App\Http\Controllers\Backend; use App\Post; use App\PostsTag; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class TrashController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // try { $rows = $request->input('rows', 10); $posts = Post::onlyTrashed()->ofCategory($request->input('category_id')+0)->ofTitle($request->input('q'))->paginate($rows); foreach ($posts as $post) { $post->tags; $post->categories; } return response()->json(array( 'status' => 0, 'data' => $posts )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '数据获取失败' )); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // } /** * 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) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // if(!$request->filled('ids')) { return response()->json(array( 'status' => 2, 'message' => '缺少参数', )); } $ids = $request->input('ids'); try{ Post::onlyTrashed()->whereIn('id', $ids)->restore(); return response()->json(array( 'status' => 0, 'message' => '恢复成功' )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '恢复失败' )); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { // if(!$request->filled('ids')) { return response()->json(array( 'status' => 2, 'message' => '缺少参数', )); } $ids = $request->input('ids'); try { DB::transaction(function () use($ids) { Post::onlyTrashed()->whereIn('id', $ids)->forceDelete(); PostsTag::whereIn('post_id', $ids)->delete(); }); return response()->json(array( 'status' => 0, 'message' => '删除成功', )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '删除失败', )); } } } <file_sep>/README.md # phpJourney #### 1、概述 本项目使用 PHP 框架 Laravel 5.5 进行开发。系统后台使用了Vuejs + Element-UI实现完全的前后端分离。并且使用高性能的swoole作为http服务器。 * 项目地址:[http://phpjourney.xin](http://phpjourney.xin)(正在备案,暂时可通过[http://192.168.3.11](http://192.168.3.11)访问) * GitHub地址:[https://github.com/Johnson19900110/phpJourney](https://github.com/Johnson19900110/phpJourney) #### 2、功能特性 * 分类管理 * 标签管理 * 文章管理 * 评论管理 * 支持markdown语法 #### 3、部署/安装 需要在系统上安装了基本的PHP运行环境、PHP包管理工具composer、Nodejs进行前端资源打包npm。 基础安装 **克隆源代码** > `git clone https://github.com/Johnson19900110/phpJourney` **安装php拓展包依赖** > `composer install` **生成配置文件** > `cp .env.example .env` 然后根据自己的配置信息去配置文件 **生成key** > `php artisan key:generate` **数据库迁移** > `php artisan migrate` **数据库填充** > `php artisan db:seed` 暂时只添加了一个后台的管理用户,想要看到完全的效果可以去后台添加一些测试数据。 以上是使用nginx作为http服务器访问,但本项目支持swoole作为http服务器。所以需要在一台已经安装swoole拓展的linux或mac上运行。 配置文件在`config/swoole_http.php`中,这里的配置将会配写到swoole_http_server中,具体见[https://wiki.swoole.com/wiki/page/274.html](https://wiki.swoole.com/wiki/page/274.html) ```php 'options' => [ 'pid_file' => env('SWOOLE_HTTP_PID_FILE', base_path('storage/logs/swoole_http.pid')), 'log_file' => env('SWOOLE_HTTP_LOG_FILE', base_path('storage/logs/swoole_http.log')), 'daemonize' => env('SWOOLE_HTTP_DAEMONIZE', 1), // 是否后台启动进程 ], ``` 启动`swoole_http_server` > `php artisan swoole:http start` 停止`swoole_http_server` > `php artisan swoole:http stop` 重启`swoole_http_server` > `php artisan swoole:http restart` 当修改`swoole_http`config文件是,可以使用`php artisan swoole:http reload`重新加载配置文件 swoole官网说:swoole_http_server对Http协议的支持并不完整,建议仅作为应用服务器。并且在前端增加Nginx作为代理 所以我们还需要配置nginx文件。 ```nginx server { listen 80; server_name your.domain.com; root /path/to/laravel/public; index index.php; location = /index.php { # Ensure that there is no such file named "not_exists" # in your "public" directory. try_files /not_exists @swoole; } location / { try_files $uri $uri/ @swoole; } location @swoole { set $suffix ""; if ($uri = /index.php) { set $suffix "/"; } proxy_set_header Host $host; proxy_set_header SERVER_PORT $server_port; proxy_set_header REMOTE_ADDR $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # IF https # proxy_set_header HTTPS "on"; # The Hostname and Port of swoole_http_server proxy_pass http://127.0.0.1:1215$suffix; } } ``` ##### 前后台入口 * 前台入口:`http://example.com/` * 后台入口:`http://example.com/back` 默认用户名为:<EMAIL> ,密码为:<PASSWORD> 默认前端编译的js文件和css已经编译好了,如果你不需要修改样式,那到此就结束了,否则你就要安装nodejs 和其前端管理工具npm,然后运行`npm install`安装前端包(windows上面可能会遇到问题,但mac和linux都不会出任何错)。 包安装完成后运行`npm run watch`,这样就可以及时监控你修改的js和css,如果一次就调整完了,可以使用`npm run dev`。 <file_sep>/git_merge.php <?php $options = getopt("s:t:m:"); if(!isset($options['s'])) { echo 'Be lacking of arguments:s' . PHP_EOL; return; } if(!isset($options['t'])) { echo 'Be lacking of arguments:t' . PHP_EOL; return; } if(!isset($options['m'])) { echo 'Be lacking of arguments:m' . PHP_EOL; return; } $command = 'git add .'; getCommand($command); $command = 'git commit -m "' . $options['m'] . '"'; getCommand($command); $command = 'git checkout ' . $options['t']; getCommand($command); $command = 'git pull origin ' . $options['t']; getCommand($command); $command = 'git merge ' . $options['s']; getCommand($command); $command = 'git push origin ' . $options['t']; getCommand($command); $command = 'git checkout ' . $options['s']; getCommand($command); function getCommand($command) { exec($command, $res); print_r($res); } <file_sep>/config/posts.php <?php return [ 'http://www.cnblogs.com/johnson108178/', ];<file_sep>/app/Post.php <?php namespace App; use App\Libraries\EsSearchable; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\SoftDeletes; use Laravel\Scout\Searchable; class Post extends Model { // use SoftDeletes, Searchable, EsSearchable; /** * 获取对应的分类category * @return \Illuminate\Database\Eloquent\Relations\BelongsTo */ public function categories() { return $this->belongsTo(Category::class, 'category_id'); } /** * 获取对应标签tags * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany */ public function tags() { return $this->belongsToMany(Tag::class,'posts_tags'); } /** * 按照分类查找 * @param $query * @param $category_id * @return mixed */ public function scopeOfCategory($query, $category_id) { if (intval($category_id) > 0) { return $query->where('category_id', $category_id); } return $query; } /** * 按文章标题模糊查询 * @param $query * @param $title * @return mixed */ public function scopeOfTitle($query, $title) { if(!empty($title)) { return $query->where('title', 'like', '%' . $title . '%'); } return $query; } public function comments() { return $this->hasMany(Comment::class, 'post_id'); } public function toSearchableArray() { return [ 'title' => $this->title, 'content' => $this->content, ]; } } <file_sep>/app/Custom/MysqlPool.php <?php /** * Created by Administrator. * Author: Administrator * Date: 2018/2/8 */ namespace App\Custom; class MysqlPool { }<file_sep>/app/Http/Controllers/Backend/PostController.php <?php namespace App\Http\Controllers\Backend; use App\Post; use App\PostsTag; use App\Tag; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class PostController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // try { $rows = $request->input('rows', 10); $posts = Post::ofCategory($request->input('category_id')+0)->ofTitle($request->input('q'))->paginate($rows); foreach ($posts as $post) { $post->tags; $post->categories; } return response()->json(array( 'status' => 0, 'data' => $posts )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '数据获取失败' )); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // try { $user = $request->user(); $current_time = date('Y-m-d H:i:s'); $data = array( 'title' => $request->input('title'), 'category_id' => $request->input('category_id'), 'markdown' => $markdown = $request->input('markdown', ''), 'content' => (new \Parsedown())->text($markdown), 'user_id' => $user->id, 'ipaddress' => $request->ip(), 'created_at' => $current_time, 'updated_at' => $current_time, ); $tags = $request->input('tags', []); DB::transaction(function () use ($data, $tags, $current_time) { $post_id = Post::insertGetId($data); if(!empty($tags)) { foreach ($tags as $tag) { if(!$tag_id = Tag::where('tags_flag', strtolower($tag))->value('id')) { $tag_id = Tag::insertGetId(array( 'tags_name' => $tag, 'tags_flag' => strtolower($tag), 'created_at' => $current_time, 'updated_at' => $current_time, )); } PostsTag::insert(array( 'post_id' => $post_id, 'tag_id' => $tag_id, )); } } }); return response()->json(array( 'status' => 0, 'message' => '新增成功' )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '新增失败', )); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // $id = $id+0; if($id <= 0) { return response()->json(array( 'status' => 2, 'message' => '数据获取失败', )); } try{ $post = Post::find($id); return response()->json(array( 'status' => 0, 'data' => $post, 'tags' => $post->tags, )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '数据获取失败', )); } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $id = $request->input('id')+0; try { $post = Post::find($id); $post->title = $request->input('title'); $post->category_id = $request->input('category_id'); $post->markdown = $marksown = $request->input('markdown'); $post->content = (new \Parsedown())->text($marksown); $tags = $request->input('tags', []); DB::transaction(function () use ($post, $tags) { $post->update(); if(!empty($tags)) { $tag_ids = array(); foreach ($tags as $tag) { if(!$tag_id = Tag::where('tags_flag', strtolower($tag))->value('id')) { $tag_id = Tag::insertGetId(array( 'tags_name' => $tag, 'tags_flag' => strtolower($tag), 'created_at' => date('Y-m-d H:i:s'), 'updated_at' => date('Y-m-d H:i:s'), )); } $tag_ids[] = $tag_id; } $post->tags()->sync($tag_ids); } }); return response()->json(array( 'status' => 0, 'message' => '更新成功', )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '更新失败', )); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { // if(!$request->filled('ids')) { return response()->json(array( 'status' => 2, 'message' => '缺少参数', )); } $ids = $request->input('ids'); try { DB::transaction(function () use($ids) { Post::destroy($ids); // PostsTag::whereIn('post_id', $ids)->delete(); }); return response()->json(array( 'status' => 0, 'message' => '删除成功', )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); return response()->json(array( 'status' => 1, 'message' => '删除失败', )); } } } <file_sep>/app/Console/Commands/ImportPosts.php <?php namespace App\Console\Commands; use App\Libraries\CnblogsPostSpider; use Goutte\Client; use Illuminate\Console\Command; class ImportPosts extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'posts:import'; /** * The console command description. * * @var string */ protected $description = 'Import posts'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // $client = new Client(); foreach (config('posts') as $url) { $spider = new CnblogsPostSpider($client, $url); $spider->getUrls(); $this->info('create one blog!'); } } } <file_sep>/app/Http/Controllers/App/HomeController.php <?php namespace App\Http\Controllers\App; use App\Http\Resources\UserResource; use App\Mail\UserLogin; use App\Notifications\InvoicePaid; use App\Post; use App\Tag; use App\User; use GuzzleHttp\Client; use Illuminate\Http\Request; use App\Http\Controllers\Controller; use Illuminate\Support\Facades\Cache; use Illuminate\Support\Facades\Log; use Illuminate\Support\Facades\Mail; class HomeController extends Controller { public function redirect() { $query = http_build_query([ 'client_id' => 3, 'redirect_uri' => 'http://phpjourney.test/auth/callback', 'response_type' => 'code', 'scope' => '', ]); return redirect('http://permission.test/oauth/authorize?'.$query); } public function authCallback(Request $request){ $http = new Client(); $response = $http->post('http://permission.test/oauth', [ 'form_params' => [ 'grant_type' => 'authorization_code', 'client_id' => '3', // your client id 'client_secret' => '<KEY>', // your client secret 'redirect_uri' => 'http://phpjourney.test/auth/callback', 'code' => $request->code, ], ]); return json_decode((string) $response->getBody(), true); } protected function mysqlLink(Array $data) { if(empty($data)) { return 'Params is empty'; } $client = new \swoole_client(SWOOLE_SOCK_TCP); $client->connect('0.0.0.0', 9508, 10) or die("Connect Pool Failure !"); $client->send(json_encode($data)); //Blocking for wait result $data = $client->recv(); //$client->close(); return unserialize($data); } public function test() { Cache::tags(['people', 'artists'])->put('John', 'John', 3); Cache::tags(['people', 'authors'])->put('Anne', 'Anne', 3); dd(Cache::tags(['people', 'artists'])->get('John')); $user = User::find(1); // $user->notify(new InvoicePaid()); // $res = Mail::to($user)->send(new UserLogin($user)); /*Mail::send('测试邮件', [], function($message) { $message->to('<EMAIL>')->subject('测试邮件');; });*/ $user->posts; return new UserResource($user); $params = array( 'table' => 'users', 'type' => 'get' ); $data = $this->mysqlLink($params); dd($data); } /** * 首页 * @param Request $request * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function index(Request $request) { try { // 分页获取所有文章 $posts = Post::orderBy('id', 'desc')->paginate(15); return view('index', array( 'posts' => $posts )); }catch (\Exception $exception) { dd($exception->getMessage()); Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); abort(500); } } public function search(Request $request) { $q = $request->get('q', false); $posts = []; if($q !== false) { $posts = Post::search($q)->paginate(); } return view('index', compact('posts', 'q')); } /** * @param int $id * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function post(int $id) { try{ $post = Post::find(intval($id)); if(empty($post)) { throw new \Exception('很抱歉,页面找不到了', 404); } Post::where('id', intval($id))->increment('views', 1); return view('post')->with(compact('post')); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); abort($exception->getCode(), $exception->getMessage()); } } /** * 按分类展示文章 * @param $tags_flag * @return \Illuminate\Contracts\View\Factory|\Illuminate\View\View */ public function tags($tags_flag) { try { $posts = Tag::where('tags_flag', $tags_flag)->first()->posts()->paginate(15); if(empty($posts->items())) { throw new \Exception('很抱歉,页面找不到了', 404); } return view('index', array( 'posts' => $posts )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); abort($exception->getCode(), $exception->getMessage()); } } public function categories($category_id) { try { $posts = Post::where('category_id', $category_id + 0)->paginate(15); if(empty($posts->items())) { throw new \Exception('抱歉,页面找不到了', 404); } return view('index', array( 'posts' => $posts )); }catch (\Exception $exception) { Log::info(__CLASS__ . '->' . __FUNCTION__ . ' Line:' . $exception->getLine() . ' ' . $exception->getMessage()); abort($exception->getCode(), $exception->getMessage()); } } } <file_sep>/app/Http/Controllers/Backend/CategoryController.php <?php namespace App\Http\Controllers\Backend; use App\Category; use Illuminate\Http\Request; use App\Http\Controllers\Controller; class CategoryController extends Controller { /** * Display a listing of the resource. * * @return \Illuminate\Http\Response */ public function index(Request $request) { // try { if($request->has('rows')) { $rows = $request->input('rows')+0; $data = Category::paginate($rows); }else { $data = Category::get(); } return response()->json(array( 'status' => 0, 'data' => $data )); }catch (Exception $e) { return response()->json(array( 'status' => 1, 'message' => '获取失败' )); } } /** * Show the form for creating a new resource. * * @return \Illuminate\Http\Response */ public function create() { // } /** * Store a newly created resource in storage. * * @param \Illuminate\Http\Request $request * @return \Illuminate\Http\Response */ public function store(Request $request) { // 新增分类 $this->validate($request, array( 'name' => 'required', 'nickname' => 'required', 'parent' => 'required' )); try { Category::create(array( 'name' => $request->input('name'), 'nickname' => $request->input('nickname'), 'description' => $request->input('description'), 'parent' => $request->input('parent')+0, )); return response()->json(array( 'status' => 0, 'message' => '新增成功' )); }catch (\Exception $e) { return response()->json(array( 'status' => 1, 'message' => '新增失败' )); } } /** * Display the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function show($id) { // try { $category = Category::find($id); return response()->json(array( 'status' => 0, 'category' => $category )); }catch(\Exception $e) { return response()->json(array( 'status' => 1, 'message' => '数据获取失败' )); } } /** * Show the form for editing the specified resource. * * @param int $id * @return \Illuminate\Http\Response */ public function edit($id) { // } /** * Update the specified resource in storage. * * @param \Illuminate\Http\Request $request * @param int $id * @return \Illuminate\Http\Response */ public function update(Request $request, $id) { // $category = Category::find($request->id); $category->name = $request->name; $category->nickname = $request->nickname; $category->parent = $request->parent; if( !$category->description ) { $category->description = $request->description; } try { $category->save(); return response()->json(array( 'status' => 0, 'message' => '数据更新成功' )); }catch (\Exception $e) { return response()->json(array( 'status' => 1, 'message' => '数据更新失败' )); } } /** * Remove the specified resource from storage. * * @param int $id * @return \Illuminate\Http\Response */ public function destroy(Request $request, $id) { // if( !$request->has('Ids') ) { $Ids = [$id]; }else { $Ids = $request->input('Ids'); } try { Category::destroy($Ids); return response()->json(array( 'status' => 0, 'message' => '删除成功' )); }catch (\Exception $e) { return response()->json(array( 'status' => 2, 'message' => '删除失败' )); } } } <file_sep>/app/Console/Commands/MysqlPool.php <?php namespace App\Console\Commands; use Illuminate\Console\Command; use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\Log; class MysqlPool extends Command { /** * The name and signature of the console command. * * @var string */ protected $signature = 'mysql:pool {action}'; /** * The console command description. * * @var string */ protected $description = 'Start Mysql Pool'; /** * Create a new command instance. * * @return void */ public function __construct() { parent::__construct(); } /** * Execute the console command. * * @return mixed */ public function handle() { // $action = $this->argument('action'); switch ($action) { case 'start': $this->start(); $this->info('Mysql Pool Start Success!'); break; default: $this->error('Wrong Params'); } } public function start() { $serv = new \swoole_server("127.0.0.1", 9508); $serv->set(array( 'worker_num' => 100, 'task_worker_num' => 10, //MySQL连接的数量 )); $serv->on('Start',array($this, 'onStart')); $serv->on('Receive',array($this, 'onReceive')); $serv->on('Task', array($this, 'onTask')); $serv->on('Finish', array($this, 'onFinish')); $serv->start(); } public function onStart($server) { echo $server->worker_id . PHP_EOL; cli_set_process_title('mysql_pool'); } public function onReceive($serv, $fd, $from_id, $data) { //taskwait就是投递一条任务,这里直接传递SQL语句了 //然后阻塞等待SQL完成 $result = $serv->taskwait($data); if ($result !== false) { list($status, $db_res) = explode(':', $result, 2); if ($status == 'OK') { //数据库操作成功了,执行业务逻辑代码,这里就自动释放掉MySQL连接的占用 $serv->send($fd, $db_res); } else { $serv->send($fd, $db_res); } return; } else { $serv->send($fd, "Error. Task timeout\n"); } } public function onTask($serv, $task_id, $from_id, $data) { $data = json_decode($data, true); static $link = null; if ($link == null) { // $link = mysqli_connect("172.16.31.10", "root", "<PASSWORD>", "gogs"); $link = DB::connection('mysql'); if (!$link) { $link = null; $serv->finish("ER:Mysql Connect Failed!!"); return; } } if(!$table = $data['table']) { $serv->finish("ER:" . serialize('Be lacking of table')); return; } if(!$queryType = $data['type']) { $serv->finish("ER:" . serialize('Be lacking of type')); return; } $query = $link->table($table); switch ($queryType) { case 'find': $result = $query->find($data['find']['id']);break; case 'first': $result = $query->first();break; case 'get': default: $result = $query->get(); } if (!$result) { $serv->finish("ER:Sql Query Failed!!"); return; } $serv->finish("OK:" . serialize($result)); } public function onFinish($serv, $data) { echo "AsyncTask Finish:Connect.PID=" . posix_getpid() . PHP_EOL; } }
ff91763ee94c91875531bf9dd91c4c077123662a
[ "Markdown", "PHP" ]
23
PHP
Johnson19900110/phpJourney
4c9ef1e3a435141cd600535abd8e6b0f061e604c
1aa83f9a9970ae4a3a646c56bd4f7a0058bd06f2
refs/heads/master
<repo_name>nunezj004/c4GUI<file_sep>/Player.java package c4GUI; public class Player { private String playerSymbol; public Player(){ playerSymbol = " "; } public Player(String symbol) { playerSymbol = symbol; } public String getSymbol(){ return playerSymbol; } } <file_sep>/displayPanel.java package c4GUI; public interface displayPanel { public void displayBtnPanel(); }
e6f5e8d78690de2883fd166c45d4161cb77c0b3e
[ "Java" ]
2
Java
nunezj004/c4GUI
35a0d9dc76e417bb8ba5a1c8dc2238cde16d879b
ead89e98cd129a28ffdd5895d4be690dd26480a8
refs/heads/master
<repo_name>viatropolis/v4t2<file_sep>/protected/modules/mall/assets/css/drag0n.css.php <?php header("Content-Type: text/css"); // Yes, unique. Using PHP in this CSS to speed up changings. // Variables. if(isset($_GET['gstart'])) { $gStart="#".$_GET['gstart']; } else { $gStart = "#008000"; } if(isset($_GET['gend'])) { $gEnd="#".$_GET['gend']; } else { $gEnd = "#000000"; } if(isset($_GET['shadow'])) { $shadow = "#".$_GET['shadow']; } else { $shadow = "#efefef"; } ?> /* * @package AJAX_Chat * @author <NAME> * @copyright (c) <NAME> * @license GNU Affero General Public License * @link https://blueimp.net/ajax/ */ @import url('positions.css'); @import url('borders.css'); @import url('fonts.css'); @import url('misc.css'); @import url('print.css'); /* * Colors */ @media screen,projection,handheld { #loginContent { background: <?=$gStart?>; background: -webkit-gradient(linear, left top, left bottom, from(<?=$gStart?>), to(<?=$gEnd?>)); background: -moz-linear-gradient(top, <?=$gStart?>, <?=$gEnd?>); filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='<?=$gStart?>', endColorstr='<?=$gEnd?>'); background-repeat: no-repeat; } #loginContent h1 { color:#FFF; } #loginContent a { color:#FFF; } #loginContent input, #loginContent select { background: rgba(0, 0, 0, .5); -moz-box-shadow: -3px -10px 50px 5px <?=$shadow?>; -webkit-box-shadow: -3px -10px 50px 5px <?=$shadow?>; box-shadow: -3px -10px 50px 10px <?=$shadow?>; filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30); -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30)"; zoom: 1; color:#FFF; } #loginContent #loginFormContainer #loginButton { background: black; -moz-box-shadow: -3px -10px 50px 5px <?=$shadow?>; -webkit-box-shadow: -3px -10px 50px 5px <?=$shadow?>; box-shadow: -3px -10px 50px 10px <?=$shadow?>; filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30); -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30)"; zoom: 1; color:#FFF; } #loginContent #errorContainer { color:red; } #content { background: #008800; background: -webkit-gradient(linear, left top, left bottom, from(<?=$gStart?>), to(<?=$gEnd?>)); background: -moz-linear-gradient(top, <?=$gStart?>, <?=$gEnd?>); background-repeat: no-repeat; filter: progid:DXImageTransform.Microsoft.gradient(startColorstr='<?=$gStart?>', endColorstr='<?=$gEnd?>'); color:#FFF; } #content h1 { color:#FFF; } #content a { color:#FFF; } #content input, #content select, #content textarea { background: black; box-shadow: 0px 0px 5px 5px <?=$shadow?>; -webkit-box-shadow: 0px 0px 5px 5px <?=$shadow?>; filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30); -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30)"; zoom: 1; color:#FFF; } #content input, #content textarea { background: rgba(0, 0, 0, .5); border: 0; } #content #chatList, #content #chatBooth, #content #onlineListContainer, #content #helpContainer, #content #settingsContainer { background: black; box-shadow: 0px 0px 5px 5px <?=$shadow?>; -webkit-box-shadow: 0px 0px 5px 5px <?=$shadow?>; filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30); -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30)"; zoom: 1; border: 0; } #content #bbCodeContainer, #content #colorCodesContainer, #content #emoticonsContainer { border: 0; } #content #logoutChannelContainer label { padding-left: 10px; } #content #bbCodeContainer input { margin-right: 10px; } #content #emoticonsContainer { background: rgba(0,0,0, 0.6); } #content #chatList, #content #chatBooth, #content #onlineListContainer { background: rgba(0, 0, 0, .5); box-shadow: 0px 0px 5px 5px <?=$shadow?>; -webkit-box-shadow: 0px 0px 5px 5px <?=$shadow?>; filter: progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30); -ms-filter: "progid:DXImageTransform.Microsoft.Blur(PixelRadius=5,MakeShadow=true,ShadowOpacity=0.30)"; zoom: 1; } #content #onlineListContainer { background: rgba(0, 0, 0, .5); } .statusContainerOn { background-image: url('../img/loading.png'); } .statusContainerOff { background-image: url('../img/loading-done.png'); } .statusContainerAlert { background-image: url('../img/loading-trouble.png'); } /*#statusIconContainer { position:absolute; float:right; text-align:right; }*/ #content #bbCodeContainer input, #content #logoutButton, #content #submitButton { background-color:#212121; color:#FFF; border: 0; } #content #colorCodesContainer a { border-color:black; } #content #optionsContainer input { background-color:transparent; } #content #optionsContainer #helpButton { background:url('../img/help.png') no-repeat; } #content #optionsContainer #settingsButton { background:url('../img/settings.png') no-repeat; } #content #optionsContainer #onlineListButton { background:url('../img/users.png') no-repeat; } #content #optionsContainer #audioButton { background:url('../img/audio.png') no-repeat; } #content #optionsContainer #audioButton.off { background:url('../img/audio-off.png') no-repeat; } #content #optionsContainer #autoScrollButton { background:url('../img/autoscroll.png') no-repeat; } #content #optionsContainer #autoScrollButton.off { background:url('../img/autoscroll-off.png') no-repeat; } #content .guest { color:gray; } #content .user { color:#FFF; } #content .moderator { color:orange; } #content .admin { color:blue; } #content .vip { color:#8383FF; } #content .chatBot { color:green; } #content #chatList .chatBotErrorMessage { color:red; } #content #chatList a { color:#1E90FF; } #content #chatList .delete { background:url('../img/delete.png') no-repeat right; } #content #chatList .deleteSelected { border-color:red; } #content #onlineListContainer h3, #content #helpContainer h3, #content #settingsContainer h3 { color:#FFF; } #content #settingsContainer #settingsList input.playback { background:url('../img/playback.png') no-repeat; } #content .rowEven { background-color:rgba(84,84,84,0.4); } #content .rowOdd { background-color:transparent; } }<file_sep>/protected/modules/mall/views/logs.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="[LANG_CODE/]" lang="[LANG_CODE/]" dir="[BASE_DIRECTION/]"> <head> <meta http-equiv="Content-Type" content="[CONTENT_TYPE/]" /> <title>[LANG]title[/LANG]</title> <!-- [STYLE_SHEETS/] --> <?php if(!isset($_COOKIE['themepickerChat'])) { ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->getModule("chat")->assetsUrl; ?>/css/drag0n.css.php" media="screen" /> <?php } else { ?> <link rel="stylesheet" type="text/css" href="<?=$_COOKIE['themepickerChat']?>" media="screen" /> <?php } ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("chat")->assetsUrl."/js/jquery.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("chat")->assetsUrl."/js/chat.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("chat")->assetsUrl."/js/config.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("chat")->assetsUrl."/js/FAbridge.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/bar.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/themePicker.js.php?for=chat",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("chat")->assetsUrl."/js/soundpicker.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl."/js/extLoader.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->render($output); ?> <?=$output?> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/lang/[LANG_CODE/].js" type="text/javascript" charset="UTF-8"></script> <script type="text/javascript"> jQuery(function($) { bar.clear(); $("a").css("text-decoration","none"); }); ajaxChatConfig.baseURL="<?=Yii::app()->getModule("chat")->assetsUrl?>/"; // <![CDATA[ function toggleContainer(containerID, hideContainerIDs) { if(hideContainerIDs) { for(var i=0; i<hideContainerIDs.length; i++) { ajaxChat.showHide(hideContainerIDs[i], 'none'); } } ajaxChat.showHide(containerID); if(typeof arguments.callee.styleProperty == 'undefined') { if(typeof isIElt7 != 'undefined') { arguments.callee.styleProperty = 'marginRight'; } else { arguments.callee.styleProperty = 'right'; } } var containerWidth = document.getElementById(containerID).offsetWidth; if(containerWidth) { document.getElementById('chatList').style[arguments.callee.styleProperty] = (containerWidth+28)+'px'; } else { document.getElementById('chatList').style[arguments.callee.styleProperty] = '20px'; } } function initialize() { toggleContainer('settingsContainer'); ajaxChat.updateButton('audio', 'audioButton'); ajaxChat.updateButton('autoScroll', 'autoScrollButton'); document.getElementById('bbCodeSetting').checked = ajaxChat.getSetting('bbCode'); document.getElementById('hyperLinksSetting').checked = ajaxChat.getSetting('hyperLinks'); document.getElementById('lineBreaksSetting').checked = ajaxChat.getSetting('lineBreaks'); document.getElementById('emoticonsSetting').checked = ajaxChat.getSetting('emoticons'); document.getElementById('autoFocusSetting').checked = ajaxChat.getSetting('autoFocus'); document.getElementById('maxMessagesSetting').value = ajaxChat.getSetting('maxMessages'); document.getElementById('wordWrapSetting').checked = ajaxChat.getSetting('wordWrap'); document.getElementById('maxWordLengthSetting').value = ajaxChat.getSetting('maxWordLength'); document.getElementById('dateFormatSetting').value = ajaxChat.getSetting('dateFormat'); document.getElementById('persistFontColorSetting').checked = ajaxChat.getSetting('persistFontColor'); for(var i=0; i<document.getElementById('audioVolumeSetting').options.length; i++) { if(document.getElementById('audioVolumeSetting').options[i].value == ajaxChat.getSetting('audioVolume')) { document.getElementById('audioVolumeSetting').options[i].selected = true; break; } } ajaxChat.fillSoundSelection('soundReceiveSetting', ajaxChat.getSetting('soundReceive')); ajaxChat.fillSoundSelection('soundSendSetting', ajaxChat.getSetting('soundSend')); ajaxChat.fillSoundSelection('soundEnterSetting', ajaxChat.getSetting('soundEnter')); ajaxChat.fillSoundSelection('soundLeaveSetting', ajaxChat.getSetting('soundLeave')); ajaxChat.fillSoundSelection('soundChatBotSetting', ajaxChat.getSetting('soundChatBot')); ajaxChat.fillSoundSelection('soundErrorSetting', ajaxChat.getSetting('soundError')); document.getElementById('blinkSetting').checked = ajaxChat.getSetting('blink'); document.getElementById('blinkIntervalSetting').value = ajaxChat.getSetting('blinkInterval'); document.getElementById('blinkIntervalNumberSetting').value = ajaxChat.getSetting('blinkIntervalNumber'); } ajaxChatConfig.sessionName = '[SESSION_NAME/]'; ajaxChatConfig.cookieExpiration = parseInt('[COOKIE_EXPIRATION/]'); ajaxChatConfig.cookiePath = '[COOKIE_PATH/]'; ajaxChatConfig.cookieDomain = '[COOKIE_DOMAIN/]'; ajaxChatConfig.cookieSecure = '[COOKIE_SECURE/]'; ajaxChatConfig.chatBotName = decodeURIComponent('[CHAT_BOT_NAME/]'); ajaxChatConfig.chatBotID = '[CHAT_BOT_ID/]'; ajaxChatConfig.allowUserMessageDelete = parseInt('[ALLOW_USER_MESSAGE_DELETE/]'); ajaxChatConfig.inactiveTimeout = parseInt('[INACTIVE_TIMEOUT/]'); ajaxChatConfig.privateChannelDiff = parseInt('[PRIVATE_CHANNEL_DIFF/]'); ajaxChatConfig.privateMessageDiff = parseInt('[PRIVATE_MESSAGE_DIFF/]'); ajaxChatConfig.showChannelMessages = true; ajaxChatConfig.messageTextMaxLength = parseInt('[MESSAGE_TEXT_MAX_LENGTH/]'); ajaxChatConfig.socketServerEnabled = parseInt('[SOCKET_SERVER_ENABLED/]'); ajaxChatConfig.socketServerHost = decodeURIComponent('[SOCKET_SERVER_HOST/]'); ajaxChatConfig.socketServerPort = parseInt('[SOCKET_SERVER_PORT/]'); ajaxChatConfig.socketServerChatID = parseInt('[SOCKET_SERVER_CHAT_ID/]'); ajaxChatConfig.ajaxURL += '&view=logs'; ajaxChatConfig.domIDs['yearSelection'] = 'yearSelection'; ajaxChatConfig.domIDs['monthSelection'] = 'monthSelection'; ajaxChatConfig.domIDs['daySelection'] = 'daySelection'; ajaxChatConfig.domIDs['hourSelection'] = 'hourSelection'; ajaxChatConfig.settings.dateFormat = '(%Y.%m.%d - %H:%i:%s)'; ajaxChatConfig.settings.audio = false; ajaxChatConfig.settings.blink = false; ajaxChatConfig.nonPersistentSettings.push('dateFormat','audio','blink'); ajaxChat.init(ajaxChatConfig, ajaxChatLang, true, true, true, initialize); //bird2 soundPickInit(); // ]]> </script> </head> <body> <div id="content"> <div id="headlineContainer"> <h1>[LANG]logsTitle[/LANG]</h1> </div> <div id="logoutChannelContainer"> <input type="button" id="logoutButton" value="[LANG]logout[/LANG]" onclick="ajaxChat.logout();"/> <label for="channelSelection">[LANG]channel[/LANG]:</label> <select id="channelSelection" onchange="ajaxChat.getLogs();">[LOGS_CHANNEL_OPTIONS/]</select> <label for="yearSelection">[LANG]logsDate[/LANG]:</label> <select id="yearSelection" onchange="ajaxChat.getLogs();">[LOGS_YEAR_OPTIONS/]</select> <select id="monthSelection" onchange="ajaxChat.getLogs();">[LOGS_MONTH_OPTIONS/]</select> <select id="daySelection" onchange="ajaxChat.getLogs();">[LOGS_DAY_OPTIONS/]</select> <label for="hourSelection">[LANG]logsTime[/LANG]:</label> <select id="hourSelection" onchange="ajaxChat.getLogs();">[LOGS_HOUR_OPTIONS/]</select> <label for="styleSelection">[LANG]style[/LANG]:</label> <select id="styleSelection" onchange="ajaxChat.setActiveStyleSheet(ajaxChat.getSelectedStyle());">[STYLE_OPTIONS/]</select> <label for="languageSelection">[LANG]language[/LANG]:</label> <select id="languageSelection" onchange="ajaxChat.switchLanguage(this.value);">[LANGUAGE_OPTIONS/]</select> </div> <!--[if lt IE 7]> <div></div> <![endif]--> <div id="chatList"></div> <div id="inputFieldContainer"> <textarea id="inputField" rows="1" cols="50" title="[LANG]inputLineBreak[/LANG]" onkeypress="ajaxChat.handleInputFieldKeyPress(event);"></textarea> </div> <div id="submitButtonContainer"> <input type="button" id="submitButton" value="[LANG]logsSearch[/LANG]" onclick="ajaxChat.sendMessage();"/> </div> <div id="optionsContainer"> <input type="image" src="img/pixel.gif" class="button" id="settingsButton" alt="[LANG]toggleSettings[/LANG]" title="[LANG]toggleSettings[/LANG]" onclick="toggleContainer('settingsContainer');"/> <input type="image" src="img/pixel.gif" class="button" id="audioButton" alt="[LANG]toggleAudio[/LANG]" title="[LANG]toggleAudio[/LANG]" onclick="ajaxChat.toggleSetting('audio', 'audioButton');"/> <input type="image" src="img/pixel.gif" class="button" id="autoScrollButton" alt="[LANG]toggleAutoScroll[/LANG]" title="[LANG]toggleAutoScroll[/LANG]" onclick="ajaxChat.toggleSetting('autoScroll', 'autoScrollButton')"/> </div> <div id="settingsContainer" style="display:none;"> <h3>[LANG]settings[/LANG]</h3> <div id="settingsList"> <table> <tr class="rowOdd"> <td><label for="bbCodeSetting">[LANG]settingsBBCode[/LANG]</label></td> <td class="setting"><input type="checkbox" id="bbCodeSetting" onclick="ajaxChat.setSetting('bbCode', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="hyperLinksSetting">[LANG]settingsHyperLinks[/LANG]</label></td> <td class="setting"><input type="checkbox" id="hyperLinksSetting" onclick="ajaxChat.setSetting('hyperLinks', this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="lineBreaksSetting">[LANG]settingsLineBreaks[/LANG]</label></td> <td class="setting"><input type="checkbox" id="lineBreaksSetting" onclick="ajaxChat.setSetting('lineBreaks', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="emoticonsSetting">[LANG]settingsEmoticons[/LANG]</label></td> <td class="setting"><input type="checkbox" id="emoticonsSetting" onclick="ajaxChat.setSetting('emoticons', this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="autoFocusSetting">[LANG]settingsAutoFocus[/LANG]</label></td> <td class="setting"><input type="checkbox" id="autoFocusSetting" onclick="ajaxChat.setSetting('autoFocus', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="maxMessagesSetting">[LANG]settingsMaxMessages[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="maxMessagesSetting" onchange="ajaxChat.setSetting('maxMessages', parseInt(this.value));"/></td> </tr> <tr class="rowOdd"> <td><label for="wordWrapSetting">[LANG]settingsWordWrap[/LANG]</label></td> <td class="setting"><input type="checkbox" id="wordWrapSetting" onclick="ajaxChat.setSetting('wordWrap', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="maxWordLengthSetting">[LANG]settingsMaxWordLength[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="maxWordLengthSetting" onchange="ajaxChat.setSetting('maxWordLength', parseInt(this.value));"/></td> </tr> <tr class="rowOdd"> <td><label for="dateFormatSetting">[LANG]settingsDateFormat[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="dateFormatSetting" onchange="ajaxChat.setSetting('dateFormat', this.value);"/></td> </tr> <tr class="rowEven"> <td><label for="persistFontColorSetting">[LANG]settingsPersistFontColor[/LANG]</label></td> <td class="setting"><input type="checkbox" id="persistFontColorSetting" onclick="ajaxChat.setPersistFontColor(this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="audioVolumeSetting">[LANG]settingsAudioVolume[/LANG]</label></td> <td class="setting"> <select class="left" id="audioVolumeSetting" onchange="ajaxChat.setAudioVolume(this.options[this.selectedIndex].value);"> <option value="1.0">100 %</option> <option value="0.9">90 %</option> <option value="0.8">80 %</option> <option value="0.7">70 %</option> <option value="0.6">60 %</option> <option value="0.5">50 %</option> <option value="0.4">40 %</option> <option value="0.3">30 %</option> <option value="0.2">20 %</option> <option value="0.1">10 %</option> </select> </td> </tr> <tr class="rowEven"> <td><label for="soundReceiveSetting">[LANG]settingsSoundReceive[/LANG]</label></td> <td class="setting"> <select id="soundReceiveSetting" onchange="ajaxChat.setSetting('soundReceive', this.options[this.selectedIndex].value);"><option value="">-</option></select><input type="image" src="img/pixel.gif" class="button playback" alt="[LANG]playSelectedSound[/LANG]" title="[LANG]playSelectedSound[/LANG]" onclick="ajaxChat.playSound(this.previousSibling.options[this.previousSibling.selectedIndex].value);"/> </td> </tr> <tr class="rowOdd"> <td><label for="soundSendSetting">[LANG]settingsSoundSend[/LANG]</label></td> <td class="setting"> <select id="soundSendSetting" onchange="ajaxChat.setSetting('soundSend', this.options[this.selectedIndex].value);"><option value="">-</option></select><input type="image" src="img/pixel.gif" class="button playback" alt="[LANG]playSelectedSound[/LANG]" title="[LANG]playSelectedSound[/LANG]" onclick="ajaxChat.playSound(this.previousSibling.options[this.previousSibling.selectedIndex].value);"/> </td> </tr> <tr class="rowEven"> <td><label for="soundEnterSetting">[LANG]settingsSoundEnter[/LANG]</label></td> <td class="setting"> <select id="soundEnterSetting" onchange="ajaxChat.setSetting('soundEnter', this.options[this.selectedIndex].value);"><option value="">-</option></select><input type="image" src="img/pixel.gif" class="button playback" alt="[LANG]playSelectedSound[/LANG]" title="[LANG]playSelectedSound[/LANG]" onclick="ajaxChat.playSound(this.previousSibling.options[this.previousSibling.selectedIndex].value);"/> </td> </tr> <tr class="rowOdd"> <td><label for="soundLeaveSetting">[LANG]settingsSoundLeave[/LANG]</label></td> <td class="setting"> <select id="soundLeaveSetting" onchange="ajaxChat.setSetting('soundLeave', this.options[this.selectedIndex].value);"><option value="">-</option></select><input type="image" src="img/pixel.gif" class="button playback" alt="[LANG]playSelectedSound[/LANG]" title="[LANG]playSelectedSound[/LANG]" onclick="ajaxChat.playSound(this.previousSibling.options[this.previousSibling.selectedIndex].value);"/> </td> </tr> <tr class="rowEven"> <td><label for="soundChatBotSetting">[LANG]settingsSoundChatBot[/LANG]</label></td> <td class="setting"> <select id="soundChatBotSetting" onchange="ajaxChat.setSetting('soundChatBot', this.options[this.selectedIndex].value);"><option value="">-</option></select><input type="image" src="img/pixel.gif" class="button playback" alt="[LANG]playSelectedSound[/LANG]" title="[LANG]playSelectedSound[/LANG]" onclick="ajaxChat.playSound(this.previousSibling.options[this.previousSibling.selectedIndex].value);"/> </td> </tr> <tr class="rowOdd"> <td><label for="soundErrorSetting">[LANG]settingsSoundError[/LANG]</label></td> <td class="setting"> <select id="soundErrorSetting" onchange="ajaxChat.setSetting('soundError', this.options[this.selectedIndex].value);"><option value="">-</option></select><input type="image" src="img/pixel.gif" class="button playback" alt="[LANG]playSelectedSound[/LANG]" title="[LANG]playSelectedSound[/LANG]" onclick="ajaxChat.playSound(this.previousSibling.options[this.previousSibling.selectedIndex].value);"/> </td> </tr> <tr class="rowEven"> <td><label for="blinkSetting">[LANG]settingsBlink[/LANG]</label></td> <td class="setting"><input type="checkbox" id="blinkSetting" onclick="ajaxChat.setSetting('blink', this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="blinkIntervalSetting">[LANG]settingsBlinkInterval[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="blinkIntervalSetting" onchange="ajaxChat.setSetting('blinkInterval', parseInt(this.value));"/></td> </tr> <tr class="rowEven"> <td><label for="blinkIntervalNumberSetting">[LANG]settingsBlinkIntervalNumber[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="blinkIntervalNumberSetting" onchange="ajaxChat.setSetting('blinkIntervalNumber', parseInt(this.value));"/></td> </tr> </table> </div> </div> <!-- Please retain the full copyright notice below including the link to blueimp.net. This not only gives respect to the amount of time given freely by the developer but also helps build interest, traffic and use of AJAX Chat. Thanks, <NAME> //--> <div id="copyright"><a href="https://blueimp.net/ajax/">AJAX Chat</a> &copy; <a href="https://blueimp.net">blueimp.net</a></div> </div> <div id="flashInterfaceContainer"></div> </body> </html><file_sep>/protected/views/Viatropolis/all.php <?php $this->pageTitle=Yii::app()->name; ?> <div id="splitblock"> <div id="splitSS"> <h3>Recent Vendors</h3> <?php $this->widget("zii.widgets.CListView",array( 'dataProvider'=>$chars, 'itemView'=>'/DragonsInn/csingle', 'summaryText'=>' ', 'template'=>"{items}", )); ?> </div> <div id="splitB"> <h1><b style="color:Orange;">Viatropolis</b> - Who are we?</h1> <p>We provide you with powerful features like:</p> <ul> <dt>Viatropolis will create your first Virtual Event</dt> <dd>Start Developing your marketing to old and new exhibitors, attendees, lectueres and sponsors within weeks.</dd><br /> <dt>Database Driven software</dt> <dd>Besides the Virtual Event Platforms, Viatropolis can handle many of your other Internet, Web and Programing Needs</dd> </ul> <p> <br />High End Database Driven Software, e-Commerce, Shopping Carts, Web Malls, Graphic Design, and Social Media outlets are just a few things Viatropolis can handle and do for you. </p><br> <div id="splitblock"> <div id="split"> Help categories: <?php echo ForumCategories::model()->count(); ?><br> Help boards: <?php echo ForumBoards::model()->count(); ?><br> Help topics: <?php echo ForumTopics::model()->count(); ?><br> Help posts: <?php echo ForumPosts::model()->count(); ?><br> </div> <div id="split"> Total members: <?php echo YiiUser::model()->count(); ?><br> Viatropolis posts: <?php echo Blog::model()->count(); ?><br> </div> </div> <div id="clearup"></div> <?php $this->widget("zii.widgets.CListView",array( 'dataProvider'=>$blog, 'itemView'=>'/DragonsInn/single', 'summaryText'=>' ', )); ?> </div> </div><file_sep>/themes/drag0n/js/bar.js // Bar-control var bar = { clear:function(){ $(".home").hide(); $(".DIuser").hide(); $(".characters").hide(); $('.manage').hide(); $('.essay').hide(); }, home:function(){ this.clear(); $(".home").show(); }, chars:function(){ this.clear(); $(".characters").show(); }, essay:function(){ this.clear(); $(".essay").show(); }, user:function(){ this.clear(); $(".DIuser").show(); }, shoutbox:function(){ $("#shoutbox").load('/mall/shoutbox',"",function(){ // d,rp,xhr //$('#shoutbox').html(d); //ajaxChat.initialize(); }); $('#shoutbox').show(); }, shoutboxClose:function(){ $('#shoutbox').hide(); }, manage:function(){ this.clear(); $('.manage').show(); } } <file_sep>/protected/views/Viatropolis/form.php <?php if(isset($blog->id)) echo "<h2>Edit entry: $blog->title</h2>"; else echo "<h2>Create new blog entry</h2>"; ?> <?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'horizontalForm', 'type'=>'horizontal', )); ?> <?=$form->textFieldRow($blog,'title',array("class"=>"span7"))?> <?=$form->textAreaRow($blog,'content',array('class'=>'bigText','hint'=>'Use the markdown syntax to style the post!'))?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=>'Submit')); ?> </div> <?php $this->endWidget(); ?><file_sep>/protected/modules/mall/controllers/SoundController.php <?php class SoundController extends Controller { public $soundpacks = array( 'Default'=>array( "recive"=>'sound_1', "send"=>'sound_2', "enter"=>'sound_3', "leave"=>'sound_4', "chatbot"=>'sound_5', "error"=>'sound_6' ), 'DRE'=>array( "error"=>"Chatbot_Error", "chatbot"=>"Chatbot_Notice", "recive"=>"MSG_Receive", "send"=>"MSG_Sent", "enter"=>"USR_Login", "leave"=>"USR_Logout", ) ); public function actionAll() { echo json_encode($this->soundpacks); } public function actionPack($pname) { $sounds = $this->soundpacks[$pname]; $name = $pname; $JSON=$sounds; $JSON["packName"]=$name; echo json_encode($JSON); } public function actionSave($pname) { Yii::app()->request->cookies["soundpickerPack"] = new CHttpCookie("soundpickerPack", $pname); } public function actionLoad() { if(isset($_COOKIE['soundpickerPack'])) echo $_COOKIE['soundpickerPack']; else echo null; } } ?><file_sep>/protected/modules/mall/views/shoutbox.php <div id="ajaxChatContent"> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/chat.js" type="text/javascript" charset="UTF-8"></script> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/custom.js" type="text/javascript" charset="UTF-8"></script> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/shoutbox.js" type="text/javascript" charset="UTF-8"></script> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/lang/en.js" type="text/javascript" charset="UTF-8"></script> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/config.js" type="text/javascript" charset="UTF-8"></script> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/FABridge.js" type="text/javascript" charset="UTF-8"></script> <script src="<?=Yii::app()->getModule("chat")->assetsUrl?>/js/soundpicker.js" type="text/javascript" charset="UTF-8"></script> <div id="ajaxChatChatList"></div> <div id="ajaxChatInputFieldContainer"> <input id="ajaxChatInputField" type="text" maxlength="[MESSAGE_TEXT_MAX_LENGTH/]" onkeypress="ajaxChat.handleInputFieldKeyPress(event);"/> </div> <div id="ajaxChatCopyright"> <select id="soundPick"></select> <select id="channelSelection" onchange="ajaxChat.switchChannel(this.options[this.selectedIndex].value);">[CHANNEL_OPTIONS/]</select> <input type="button" value="[LANG]bbCodeLabelBold[/LANG]" title="[LANG]bbCodeTitleBold[/LANG]" onclick="ajaxChat.insertBBCode('b');" style="font-weight:bold;"/> <input type="button" value="[LANG]bbCodeLabelItalic[/LANG]" title="[LANG]bbCodeTitleItalic[/LANG]" onclick="ajaxChat.insertBBCode('i');" style="font-style:italic;"/> <input type="button" value="[LANG]bbCodeLabelUnderline[/LANG]" title="[LANG]bbCodeTitleUnderline[/LANG]" onclick="ajaxChat.insertBBCode('u');" style="text-decoration:underline;"/> <input type="button" value="[LANG]bbCodeLabelQuote[/LANG]" title="[LANG]bbCodeTitleQuote[/LANG]" onclick="ajaxChat.insertBBCode('quote');"/> <input type="button" value="[LANG]bbCodeLabelCode[/LANG]" title="[LANG]bbCodeTitleCode[/LANG]" onclick="ajaxChat.insertBBCode('code');"/> <input type="button" value="[LANG]bbCodeLabelURL[/LANG]" title="[LANG]bbCodeTitleURL[/LANG]" onclick="ajaxChat.insertBBCode('url');"/> <input type="button" value="[LANG]bbCodeLabelImg[/LANG]" title="[LANG]bbCodeTitleImg[/LANG]" onclick="ajaxChat.insertBBCode('img');"/> <input type="button" value="Close shoutbox" onclick="bar.shoutboxClose();"> <div id="statusIconContainer" class="statusContainerOn" onclick="ajaxChat.updateChat(null);"></div> </div> <script type="text/javascript"> // <![CDATA[ function initialize() { //document.getElementById('wordWrapSetting').checked = ajaxChat.getSetting('wordWrap'); //document.getElementById('maxWordLengthSetting').value = ajaxChat.getSetting('maxWordLength'); } jQuery(function(){ ajaxChatConfig.ajaxURL = '/chat/run/?ajax=true&shoutbox=true'; ajaxChatConfig.baseURL = '<?=Yii::app()->getModule("chat")->assetsUrl?>/'; ajaxChatConfig.sessionName = '[SESSION_NAME/]'; ajaxChatConfig.cookieExpiration = parseInt('[COOKIE_EXPIRATION/]'); ajaxChatConfig.cookiePath = '[COOKIE_PATH/]'; ajaxChatConfig.cookieDomain = '[COOKIE_DOMAIN/]'; ajaxChatConfig.cookieSecure = '[COOKIE_SECURE/]'; ajaxChatConfig.chatBotName = decodeURIComponent('[CHAT_BOT_NAME/]'); ajaxChatConfig.chatBotID = '[CHAT_BOT_ID/]'; ajaxChatConfig.allowUserMessageDelete = parseInt('[ALLOW_USER_MESSAGE_DELETE/]'); ajaxChatConfig.inactiveTimeout = parseInt('[INACTIVE_TIMEOUT/]'); ajaxChatConfig.privateChannelDiff = parseInt('[PRIVATE_CHANNEL_DIFF/]'); ajaxChatConfig.privateMessageDiff = parseInt('[PRIVATE_MESSAGE_DIFF/]'); ajaxChatConfig.showChannelMessages = false; ajaxChatConfig.messageTextMaxLength = parseInt('[MESSAGE_TEXT_MAX_LENGTH/]'); ajaxChatConfig.socketServerEnabled = parseInt('[SOCKET_SERVER_ENABLED/]'); ajaxChatConfig.socketServerHost = decodeURIComponent('[SOCKET_SERVER_HOST/]'); ajaxChatConfig.socketServerPort = parseInt('[SOCKET_SERVER_PORT/]'); ajaxChatConfig.socketServerChatID = parseInt('[SOCKET_SERVER_CHAT_ID/]'); ajaxChatConfig.domIDs['chatList'] = 'ajaxChatChatList'; ajaxChatConfig.domIDs['inputField'] = 'ajaxChatInputField'; ajaxChatConfig.domIDs['flashInterfaceContainer'] = 'ajaxChatFlashInterfaceContainer'; ajaxChatConfig.startChatOnLoad = false; ajaxChatConfig.settings.autoFocus = false; ajaxChatConfig.settings.wordWrap = true; ajaxChatConfig.settings.maxWordLength = 11; ajaxChatConfig.settings.blink = false; ajaxChatConfig.nonPersistentSettings.push('autoFocus','wordWrap','maxWordLength','blink'); ajaxChat.init(ajaxChatConfig, ajaxChatLang, true, true, true, initialize); //bird2 soundPickInit(); }); // ]]> </script> </div> <div id="ajaxChatFlashInterfaceContainer"></div> </div> <file_sep>/themes/drag0n/views/layouts/main_changed.php <?php /* @var $this Controller */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title><?php echo CHtml::encode($this->pageTitle); ?></title> <?php DN::MakeBootstrap(); ?> <?php Yii::app()->clientScript->registerMetaTag('text/html; charset=utf-8',null, 'Content-type'); ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" /> <?php if(!isset($_COOKIE['themepicker'])) { ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/drag0n.css.php" media="screen" /> <?php } else { ?> <link rel="stylesheet" type="text/css" href="<?=$_COOKIE['themepicker']?>" media="screen" /> <?php } ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/bar.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/themePicker.js.php?for=site",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl."/js/extLoader.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/langPick.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScript("barInit","bar.clear();",CClientScript::POS_READY); ?> <?php if(!Yii::app()->user->isGuest) { Yii::app()->clientScript->registerScript("shoutbox", " $.get('/chat/shoutbox',function(d){ $('#shoutbox').html(d); ajaxChat.initialize(); }); ",CClientScript::POS_READY); } ?> </head> <body> <div class="container" id="page"> <div id="header"> <div id="logo"><?php echo CHtml::encode(Yii::app()->name); ?></div> </div><!-- header --> <div id="mainmenu"> <?php $this->widget('zii.widgets.CMenu',array( 'items'=>array( array('label'=>'Test', 'url'=>array('/Viatropolis/index')), array('label'=>'About', 'url'=>array('/Viatropolis/page', 'view'=>'about')), array('label'=>'Contact', 'url'=>array('/Viatropolis/contact')), array('label'=>'Login', 'url'=>array('/Viatropolis/login'), 'visible'=>Yii::app()->user->isGuest), array('label'=>'Logout ('.Yii::app()->user->name.')', 'url'=>array('/Viatropolis/logout'), 'visible'=>!Yii::app()->user->isGuest) ), )); ?> </div><!-- mainmenu --> <?php if(isset($this->breadcrumbs)):?> <?php $this->widget('zii.widgets.CBreadcrumbs', array( 'links'=>$this->breadcrumbs, )); ?><!-- breadcrumbs --> <?php endif?> <?php echo $content; ?> <div class="clear"></div> <div id="footer"> </div><!-- footer --> </div><!-- page --> </body> </html> <file_sep>/protected/views/manage/chat.php <h3><?=Yii::t("admin","cDef")?></h3> <?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'horizontalForm', 'type'=>'horizontal', )); echo $form->textFieldRow($def, 'adminChannels', array( 'class'=>'span8', 'hint'=>"Comma-seperated channelID's." )); echo $form->textFieldRow($def, 'userChannels', array( 'class'=>'span8', 'hint'=>"Comma-seperated channelID's." )); echo "<br>"; $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'label'=>'Add', 'type'=>'success')); $this->endWidget(); ?> <div id="splitblock"> <div id="split"> <h3><?=Yii::t("admin","cs")?></h3> <?php $this->widget("zii.widgets.grid.CGridView",array( 'dataProvider'=>$dp, 'columns'=>array( 'id', array( 'name'=>'orderID', 'type'=>'raw', 'value'=>'$data->orderID' ), array( 'name'=>'name', 'type'=>'raw', 'value'=>'CHtml::link($data->name,array("/mall/view","id"=>$data->id))' ) ) )); ?> </div> <div id="split"> <h3><?=Yii::t("admin","cAdd")?></h3> <?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'verticalForm', )); echo $form->textFieldRow($model, 'name', array('class'=>'span7')); echo $form->textFieldRow($model, 'orderID', array( 'class'=>'span1', 'hint'=>"Defines at which position the channel is located in the selection. CAUTION: This also acts as channelID inside the chat and affects the logs!" )); echo $form->textAreaRow($model, 'desc', array('class'=>'span7')); echo "<br>"; $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'label'=>'Add', 'type'=>'success')); $this->endWidget(); ?> </div> </div><file_sep>/protected/messages/en/app.php <?php return array( // English by <NAME> "abc" => "The Unit", ); ?><file_sep>/protected/modules/charaBase/CharaBaseModule.php <?php class CharaBaseModule extends CWebModule { public $defaultController = "view"; private $_assetsUrl; public function init() { // this method is called when the module is being created // you may place code here to customize the module or the application // import the module-level models and components $this->setImport(array( 'charaBase.models.*', 'charaBase.components.*', )); // bootstrap enabler DN::makeBootstrap(); } public function getAssetsUrl() { if ($this->_assetsUrl === null) $this->_assetsUrl = Yii::app()->getAssetManager()->publish( Yii::getPathOfAlias('charaBase.assets') ); return $this->_assetsUrl; } public function beforeControllerAction($controller, $action) { if(parent::beforeControllerAction($controller, $action)) { // this method is called before any module controller action is performed // you may place customized code here return true; } else return false; } } ?><file_sep>/protected/migrations/m121006_194656_MessaggioNortifica.php <?php class m121006_194656_MessaggioNortifica extends CDbMigration { public function up() { $this->addColumn('notifyii', 'content', 'text'); } public function down() { echo "m121006_194656_MessaggioNortifica does not support migration down.\n"; return false; } }<file_sep>/protected/modules/notifyii/views/modelNotifyii/_form.php <?php /* @var $this NotifyiiController */ /* @var $model Notifyii */ /* @var $form CActiveForm */ ?> <?php // Load all roles from database $rolesReulst = Yii::app()->db ->createCommand('select name from AuthItem where type = 2;') ->queryAll(); $roles = array(); foreach($rolesReulst as $role) { $roles[$role['name']] = $role['name']; } ?> <div class="form"> <?php $form = $this->beginWidget('CActiveForm', array( 'id' => 'notifyii-form', 'enableAjaxValidation' => false, )); ?> <p class="note">Fields with <span class="required">*</span> are required.</p> <?php echo $form->errorSummary($model); ?> <div class="row"> <?php echo $form->labelEx($model, 'expire'); ?> <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array( 'name'=>'ModelNotifyii[expire]', 'options'=>array( 'showAnim'=>'fold', 'dateFormat'=>'yy-mm-dd' ), 'value' => $model->expire, 'htmlOptions'=>array( 'style'=>'height:20px;' ), )); ?> <?php echo $form->error($model, 'expire'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'alert_after_date'); ?> <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array( 'name'=>'ModelNotifyii[alert_after_date]', 'options'=>array( 'showAnim'=>'fold', 'dateFormat'=>'yy-mm-dd' ), 'value' => $model->alert_after_date, 'htmlOptions'=>array( 'style'=>'height:20px;' ), )); ?> <?php echo $form->error($model, 'alert_after_date'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'alert_before_date'); ?> <?php $this->widget('zii.widgets.jui.CJuiDatePicker', array( 'name'=>'ModelNotifyii[alert_before_date]', 'options'=>array( 'showAnim'=>'fold', 'dateFormat'=>'yy-mm-dd' ), 'value' => $model->alert_before_date, 'htmlOptions'=>array( 'style'=>'height:20px;' ), )); ?> <?php echo $form->error($model, 'alert_before_date'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'title'); ?> <?php echo $form->textField($model, 'title'); ?> <?php echo $form->error($model, 'title'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'content'); ?> <?php echo $form->textField($model, 'content'); ?> <?php echo $form->error($model, 'content'); ?> </div> <div class="row"> <?php echo $form->labelEx($model, 'role'); ?> <?php echo $form->dropDownList($model, 'role', $roles); ?> <?php echo $form->error($model, 'content'); ?> </div> <div class="row buttons"> <?php echo CHtml::submitButton($model->isNewRecord ? 'Create' : 'Save'); ?> </div> <?php $this->endWidget(); ?> </div><!-- form --> <file_sep>/protected/views/Viatropolis/single.php <div id="post"> <?php $user = Yii::app()->getModule("user")->user($data->author); switch($user->superuser) { case 0: $css = "user"; break; case 1: $css = "moderator"; break; case 2: $css = "admin"; break; case -1: $css = "vip"; break; } ?> <div id="title"><?=CHtml::link($data->title,array("/Viatropolis/view",'id'=>$data->id),array("style"=>"color:white;"))?></div> <div id="actions"> <?php echo CHtml::link("View in forum",array("/forum/view/topic",'id'=>$data->topicID)); if(Yii::app()->user->id == $user->id || isset(Yii::app()->user->isAdmin) && Yii::app()->user->isAdmin) { echo " | "; echo CHtml::link("Edit",array("/Viatropolis/edit","id"=>$data->id)); echo " | "; echo CHtml::link("delete",array("/Viatropolis/delete","id"=>$data->id)); } ?> </div> <div id="author"><?=CHtml::link($user->username,array("/user/user/view",'id'=>$user->id),array("class"=>$css))?></div> <div id="when"><?=date("d.m.Y H:i",$data->modified)?></div> <div id="message"> <?php $this->beginWidget('CMarkdown', array('purifyOutput'=>true)); echo $data->content; $this->endWidget(); ?> </div> </div> <hr><file_sep>/protected/modules/notifyii/views/modelNotifyii/index.php <?php /* @var $this NotifyiiController */ /* @var $dataProvider CActiveDataProvider */ $this->breadcrumbs=array( 'Notifyii', ); $this->menu=array( array('label'=>'Create Notifyii', 'url'=>array('create')), array('label'=>'Manage Notifyii', 'url'=>array('admin')), ); ?> <h1>Notifyiis</h1> <div class="box"> <h3>In this page you can see all notification created.</h3> </div> <a href="<?php echo $this->createUrl('/notifyii/modelNotifyii/aggregate'); ?>">Mostra i dati aggregati per ruolo</a> <?php $this->widget('zii.widgets.CListView', array( 'dataProvider'=>$dataProvider, 'itemView'=>'_view', )); ?> <file_sep>/protected/modules/mall/lib/class/CustomAJAXChat.php <?php /* * @package AJAX_Chat * @author <NAME> * @copyright (c) <NAME> * @license GNU Affero General Public License * @link https://blueimp.net/ajax/ */ class CustomAJAXChat extends AJAXChat { // Returns an associative array containing userName, userID and userRole // Returns null if login is invalid function getValidLoginUserData() { $YiiUser=Yii::app()->user; if(!Yii::app()->user->isGuest) { if(!isset($YiiUser->role)) { $YiiUser = Yii::app()->getModule("user")->user(Yii::app()->user->id); $YiiUser->role = $YiiUser->superuser; } $userName = isset($YiiUser->name) ? $YiiUser->name : $YiiUser->username; switch($YiiUser->role) { case 0: $role=AJAX_CHAT_USER; break; case 1: $role=AJAX_CHAT_MODERATOR; break; case 2: $role=AJAX_CHAT_ADMIN; break; case -1: $role=AJAX_CHAT_VIP; break; } $def = AJAXChatDefaults::model()->findByPk(0); if($role == AJAX_CHAT_USER) { $c = explode(",",$def->userChannels); foreach($c as $cID) { if(!empty($cID)) $channels[]=$cID; } } else { $c = explode(",",$def->adminChannels); foreach($c as $cID) { if(!empty($cID)) $channels[]=$cID; } } return array( 'userID'=>$YiiUser->id, 'userName'=>$this->trimUserName( $userName, $this->getConfig('contentEncoding'), $this->getConfig('sourceEncoding') ), 'userRole'=>$role, 'channels'=>$channels ); } else { // Guest users: return $this->getGuestUser(); } } // Store the channels the current user has access to // Make sure channel names don't contain any whitespace function &getChannels() { if($this->_channels === null) { $this->_channels = array(); $customUsers = $this->getCustomUsers(); // Get the channels, the user has access to: if($this->getUserRole() == AJAX_CHAT_GUEST) { $validChannels = $customUsers[0]['channels']; } else { $userData = $this->getValidLoginUserData(); $validChannels = $userData['channels']; } // Add the valid channels to the channel list (the defaultChannelID is always valid): foreach($this->getAllChannels() as $key=>$value) { // Check if we have to limit the available channels: if($this->getConfig('limitChannelList') && !in_array($value, $this->getConfig('limitChannelList'))) { continue; } if(in_array($value, $validChannels) || $value == $this->getConfig('defaultChannelID')) { $this->_channels[$key] = $value; } } } return $this->_channels; } // Store all existing channels // Make sure channel names don't contain any whitespace function &getAllChannels() { if($this->_allChannels === null) { // Get all existing channels: $customChannels = $this->getCustomChannels(); $defaultChannelFound = false; foreach($customChannels as $key=>$value) { $forumName = $this->trimChannelName($value); $this->_allChannels[$forumName] = $key; if($key == $this->getConfig('defaultChannelID')) { $defaultChannelFound = true; } } if(!$defaultChannelFound) { // Add the default channel as first array element to the channel list: $this->_allChannels = array_merge( array( $this->trimChannelName($this->getConfig('defaultChannelName'))=>$this->getConfig('defaultChannelID') ), $this->_allChannels ); } } return $this->_allChannels; } function &getCustomUsers() { // List containing the registered chat users: $users = null; #$Users = User::model()->findAll(); $Users = YiiUser::model()->findAll(); foreach($Users as $user) { switch($user->superuser) { case 0: $role=AJAX_CHAT_USER; break; case 1: $role=AJAX_CHAT_MODERATOR; break; case 2: $role=AJAX_CHAT_ADMIN; break; case -1: $role=AJAX_CHAT_VIP; break; } $def = AJAXChatDefaults::model()->findByPk(0); if($role == AJAX_CHAT_USER) { $c = explode(",",$def->userChannels); foreach($c as $cID) { if(!empty($cID)) $channels[]=$cID; } } else { $c = explode(",",$def->adminChannels); foreach($c as $cID) { if(!empty($cID)) $channels[]=$cID; } } $users[$user->id]=array( 'userName'=>$user->username, 'userRole'=>$role, 'channels'=>$channels ); } return $users; } function &getCustomChannels() { // List containing the custom channels: $channels = null; $acc = AJAXChatChannels::model()->findAll(); foreach($acc as $channel) { $channels[$channel->orderID]=$channel->name; } return $channels; } // Return true if a custom command has been successfully parsed, else false // $text contains the whole message, $textParts the message split up as words array function parseCustomCommands($text, $textParts) { switch($textParts[0]) { // Display userIP: case '/myip': $this->insertChatBotMessage( $this->getPrivateMessageID(), '/myip '.$this->getSessionIP() ); return true; break; case '/php': if($this->getUserRole() == AJAX_CHAT_ADMIN) { $text = str_replace("/php","",$text); ob_start(); eval($text); $output=ob_get_contents(); ob_end_clean(); $this->insertChatBotMessage( $this->getPrivateMessageID(), "PHP code: ".$text." \n [code]".$output."[/code]" ); } else $this->insertChatBotMessage( $this->getPrivateMessageID(), '/error CommandNotAllowed '.$textParts[0] ); return true; break; case '/wall': if($this->getUserRole()==AJAX_CHAT_ADMIN || $this->getUserRole() == AJAX_CHAT_MODERATOR) { $text = str_replace('/wall','',$text); $users=AJAXChatOnline::model()->findAll(); switch($this->getUserRole()) { case AJAX_CHAT_ADMIN: $col="blue"; break; case AJAX_CHAT_MODERATOR: $col="orange"; break; } foreach($users as $user) { $this->insertChatBotMessage( $this->getPrivateMessageID($user->userID), '[color=red][i]'.$this->getLang("wall").'[/i][/color]|[color='.$col.'][b]'.$this->getUserName().'[/b][/color]: '.$text ); } } else $this->insertChatBotMessage( $this->getPrivateMessageID(), '/error CommandNotAllowed '.$textParts[0] ); return true; break; case '/afk': if(!$this->getSessionVar('isAway')) { if(!empty($textParts[1])) $addit = " ".$this->getLang("reason").": ".str_replace('/afk','',$text); else $addit=null; $this->addInfoMessage($this->getUserName(), 'userName'); $this->setSessionVar('isAway', true); $this->insertChatBotMessage( $this->getChannel(), '[i]'.$this->getUserName()." ".$this->getLang("goneAfk").$addit."[/i]" ); $this->setUserName('AFK|'.$this->getUserName()); $this->updateOnlineList(); } return true; break; case '/back': if($this->getSessionVar('isAway')) { $this->setUserName(str_replace('AFK|','',$this->getUserName())); $this->updateOnlineList(); $this->addInfoMessage($this->getUserName(), 'userName'); $this->setSessionVar('isAway', false); $this->insertChatBotMessage( $this->getChannel(), '[i]'.$this->getUserName()." ".$this->getLang("hasReturned").'[/i]' ); } return true; break; case '/reset': $this->setUserName($this->getLoginUserName()); $this->updateOnlineList(); $this->addInfoMessage($this->getUserName(), 'userName'); return true; break; case '/changeToChar': $char = Character::model()->findByPk($textParts[1]); if(!is_null($char)) { $oldname = $this->getLoginUserName(); $oldname = "[url=".Controller::createAbsoluteUrl("/user/user/view",array("id"=>$this->getUserID()))."]".$oldname."[/url]"; $prefix = $this->getConfig('changedNickPrefix'); $suffix = $this->getConfig('changedNickSuffix'); $genders = array('#6699FF','#FF6699','#9B30FF','#007FFF','#00CC66','#CC66FF','#FF6EC7','#FFFFBB'); if(!empty($char->nickName)) $cName = $char->nickName; else $cName = $char->name; $this->setUserName( "[color=".$genders[$char->sex]."][url=".Controller::createAbsoluteUrl("/charaBase/view/char",array("ID"=>$char->cID)). "]".$prefix.$this->trimUserName($cName).$suffix.'[/url][/color]' ); $this->updateOnlineList(); $this->addInfoMessage($this->getUserName(), 'userName'); $this->insertChatBotMessage( $this->getChannel(), '/switchChar '.json_encode(array("old"=>$oldname,"new"=>$this->getUserName())) ); } else $this->insertChatBotMessage( $this->getChannel(), '/error CharNotWorking' ); return true; break; default: return false; } } } ?><file_sep>/protected/modules/notifyii/views/modelNotifyii/_view.php <?php /* @var $this NotifyiiController */ /* @var $data Notifyii */ ?> <div class="view"> <b><?php echo CHtml::encode($data->getAttributeLabel('expire')); ?>:</b> <?php echo CHtml::encode($data->expire); ?> <br /> <b><?php echo CHtml::encode($data->getAttributeLabel('alter_after_date')); ?>:</b> <?php echo CHtml::encode($data->alert_after_date); ?> <br /> <b><?php echo CHtml::encode($data->getAttributeLabel('alter_before_date')); ?>:</b> <?php echo CHtml::encode($data->alert_before_date); ?> <br /> <b><?php echo CHtml::encode($data->getAttributeLabel('title')); ?>:</b> <?php echo CHtml::link(CHtml::encode($data->title), array('view', 'id' => $data->id)); ?> <br /> <b><?php echo CHtml::encode($data->getAttributeLabel('content')); ?>:</b> <?php echo CHtml::link(CHtml::encode($data->content), array('view', 'id' => $data->id)); ?> <br /> <?php if(!(trim($data->role) === "")) : ?> <b><?php echo CHtml::encode($data->getAttributeLabel('role')); ?>:</b> <?php echo CHtml::encode($data->role); ?> <br /> <?php endif; ?> </div> <file_sep>/protected/modules/charaBase/controllers/ViewController.php <?php class ViewController extends Controller { public $defaultAction = "list"; public function actionChar($ID) { $model = Character::model()->findByPk($ID); if(isset($model)) { $this->render("char",array("model"=>$model,'CBT'=>new CBTranslator)); } else throw new CException("Character not found."); } public function actionList($uID=null) { $model = new Character('search'); if($uID!=null) { $model->uID=$uID; $model->search(); } if(isset($_GET['Character'])){ $model->attributes=$_GET['Character']; if($uID!=null) { $model->uID=$uID; } } $this->render('list', array( 'model'=>$model, 'CBT'=>new CBTranslator )); } } ?><file_sep>/protected/components/DN.php <?php class DN extends Controller { public $uname; public $vip; public function __construct(){ parent::__construct($this->id, $this->module); if(isset(Yii::app()->user->id)) $this->uname=Yii::app()->getModule('user')->user(Yii::app()->user->id)->username; else $this->uname=null; if(isset(Yii::app()->user->isVIP) && Yii::app()->user->isVIP==true) {$this->vip=true;} else {$this->vip=false;} } public function bar(){ $cn = AJAXChatOnline::model()->count(); $ret = array( 'encodeLabel'=>false, 'items'=>array( array('label'=>CHtml::image( Yii::app()->theme->baseUrl."/images/home.gif",null,array( 'class'=>'miniIcon' )), 'url'=>'#','linkOptions'=>array('onclick'=>'bar.clear();')), array('label'=>'Home', 'url'=>"#", 'linkOptions'=>array('onclick'=>'bar.home();')), # array('label'=>Yii::t("site","chars"), 'url'=>"#", 'linkOptions'=>array('onclick'=>'bar.chars();')), array('label'=>"Mall ($cn)", 'url'=>array("/mall")), array('label'=>'Forum', 'url'=>array('/forum')), array('label'=>'|', 'visible'=>$this->vip), array('label'=>Yii::t("site","manage"),'url'=>"#", 'visible'=>$this->vip, 'linkOptions'=>array('onclick'=>'bar.manage();')), ), ); return $ret; } public function ubar() { $ret = array( 'encodeLabel'=>false, 'items'=>array( array( 'label'=>'Login', 'url'=>array('/user/login'), 'visible'=>(Yii::app()->user->isGuest), ), array('label'=>Yii::t("site","settings"), 'visible'=>!Yii::app()->user->isGuest, 'url'=>"#",'linkOptions'=>array("onclick"=>"bar.user();")), array('label'=>'Logout', 'url'=>array('/user/logout'), 'visible'=>!Yii::app()->user->isGuest), ) ); return $ret; } public function ubar_user(){ return array( 'encodeLabel'=>false, 'items'=>array( array('label'=>Yii::t("site","u").": ".$this->uname, 'url'=>array('/user/profile'), 'visible'=>!Yii::app()->user->isGuest), # array('label'=>'|'), # array('label'=>'Notifications: [1F, 1N]', 'url'=>array('/user/logout'), 'visible'=>!Yii::app()->user->isGuest), #array('label'=>'|'), #array('label'=>Yii::t("site","theme").": ".CHtml::dropDownList("themePicker",null,array(),array("id"=>"themePicker","class"=>"allNormal"))), #array('label'=>'|'), #array('label'=>Yii::t("site","lang").": ".CHtml::dropDownList('language',null,array("x"=>Yii::t("site","lang")."..."),array("class"=>"allNormal","id"=>"langPick"))) ) ); } public function Nbar_home() { return array( 'encodeLabel'=>false, 'items'=>array( array('label'=>'Home', 'url'=>array("/Viatropolis/index")), array('label'=>Yii::t("site","ath"), 'url'=>array('/Viatropolis/info', 'p'=>'about')), array('label'=>Yii::t("site","contact"), 'url'=>array('/Viatropolis/info','p'=>'contact')), ) ); } public function Nbar_manage() { return array( 'encodeLabel'=>false, 'items'=>array( array('label'=>Yii::t('site','mBlog'), 'url'=>array('/manage/blog'), 'visible'=>$this->vip), array('label'=>Yii::t('site','mChat'), 'url'=>array('/manage/chat'), 'visible'=>$this->vip), array('label'=>Yii::t('site','mThemes'), 'url'=>array('/manage/themes'), 'visible'=>$this->vip), ) ); } public function Nbar_characters() { return array( 'encodeLabel'=>false, 'items'=>array( array('label'=>Yii::t("site","cbList"), 'url'=>array("/charaBase/view/list")), # array('label'=>Yii::t("site","cbManage"), 'url'=>array("/charaBase/view/manage"), 'visible'=>(!Yii::app()->user->isGuest)), array('label'=>Yii::t("site","cbCreate"), 'url'=>array("/charaBase/maintain/create"), 'visible'=>(!Yii::app()->user->isGuest)), array('label'=>'|'), # array('label'=>Yii::t("site","cbExport"), 'url'=>array("/charaBase/transfer/export"), 'visible'=>(!Yii::app()->user->isGuest)), array('label'=>Yii::t("site","cbImport"), 'url'=>array("/charaBase/transfer/import"), 'visible'=>(!Yii::app()->user->isGuest)), ) ); } static function makeBootstrap() { $component = array( 'bootstrap'=>array( 'class'=>'ext.bootstrap.components.Bootstrap', 'yiiCss'=>true, 'enableJS'=>true, 'coreCss'=>true ) ); Yii::app()->setComponents($component); Yii::app()->bootstrap; // initing bootstrap! } public function DoTheMenu() { echo '<div id="bar">'; $this->widget('zii.widgets.CMenu',$this->bar()); echo '<div id="ubar">'; $this->widget('zii.widgets.CMenu',$this->ubar()); echo '</div>'; echo '</div>'; echo '<div id="Nbar" class="home">'; $this->widget('zii.widgets.CMenu',$this->Nbar_home()); echo '</div>'; # echo '<div id="Nbar" class="characters">'; # $this->widget('zii.widgets.CMenu',$this->Nbar_characters()); # echo '</div>'; if(!Yii::app()->user->isGuest) { echo '<div id="Nbar" class="DIuser">'; $this->widget('zii.widgets.CMenu',$this->ubar_user()); echo '</div>'; echo '<div id="Nbar" class="manage">'; $this->widget('zii.widgets.CMenu',$this->Nbar_manage()); echo '</div>'; } } } ?><file_sep>/protected/modules/forum/controllers/TopicController.php <?php class TopicController extends Controller { public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('create','edit','delete'), 'users'=>array('@'), ), array('deny', 'actions'=>array("create",'edit','delete'), 'users'=>array('*'), ), ); } public function actionCreate($bid) { $topic = new ForumTopics("create"); if(!isset($_POST['ForumTopics'])) { $this->render("form",array("topic"=>$topic)); } else { $topic->attributes=$_POST['ForumTopics']; $topic->boardID=$bid; if(isset($_POST['ForumTopics']['sticky'])) $topic->sticky=true; else $topic->sticky=false; if($topic->save()) { $post = new ForumPosts; $post->topicID=$topic->id; $post->writerID=Yii::app()->user->id; $post->answer=$_POST['ForumTopics']['firstPost']; $post->save(); $this->redirect(array("view/topic","id"=>$topic->id)); } else { $this->render("form",array("topic"=>$topic)); } } } public function actionEdit($id) { $topic = ForumTopics::model()->findByPk($id); if(!isset($_POST['ForumTopics'])) { $this->render("form",array("topic"=>$topic)); } else { $_POST['ForumTopics']['sticky']=$_POST['ForumTopics']['sticky'][0]; $topic->attributes=$_POST['ForumTopics']; #print_r($topic);die(); if($topic->update()) { $this->redirect(array("view/topic","id"=>$topic->id)); } else { $this->render("form",array("topic"=>$topic)); } } } public function actionDelete($id) { $topic = ForumTopics::model()->findByPk($id); $posts = ForumPosts::model()->findAll(array("condition"=>"topicID=:x","params"=>array(":x"=>$id))); if($topic != null) { foreach($posts as $post) { $post->delete(); } $topic->delete(); $this->redirect("/view/index"); } else throw new CException("Could not delete board."); } } ?><file_sep>/protected/controllers/ManageController.php <?php class ManageController extends Controller { /*public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('deny', 'actions'=>array('chat','blog','themes','sounds','chars'), 'users'=>array('*'), ), array('allow', 'actions'=>array('chat','blog','themes','sounds','chars'), 'users'=>array('@'), ), ); }*/ public function actionChat($do="view",$id=null) { DN::MakeBootstrap(); $def = AJAXChatDefaults::model()->findByPk(0); $dp = new CActiveDataProvider("AJAXChatChannels",array( 'pagination'=>array( 'pageSize'=>20, ), )); $model = new AJAXChatChannels; if($do=="view" || $do="add") { if(isset($_POST['AJAXChatChannels'])) { $model->attributes = $_POST['AJAXChatChannels']; if($model->save()) { $this->redirect("chat"); } } else if(isset($_POST['AJAXChatDefaults'])) { $def->attributes = $_POST['AJAXChatDefaults']; #print_r($def);die(); if($def->save()) { $this->redirect("chat"); } } } else if($do="delete" && $id != null) { $model = AJAXChatChannels::model()->findByPk($id); if($model->save()) { $this->redirect("chat"); } } $this->render("chat",array( "model"=>$model, 'dp'=>$dp, 'def'=>$def )); } public function actionThemes() { DN::MakeBootstrap(); $dp = new CActiveDataProvider("Themes",array( 'pagination'=>array( 'pageSize'=>50, ), )); $theme = new Themes; if(!isset($_POST['Themes'])) { $this->render("themes",array( 'dp'=>$dp, 'theme'=>$theme )); } else { $theme->attributes=$_POST['Themes']; if(!isset($theme->shadow) || empty($theme->shadow)) { $theme->shadow=$theme->gstart; } if($theme->save()) { $this->redirect("themes"); } else { $this->render("themes",array( 'dp'=>$dp, 'theme'=>$theme )); } } } public function actionBlog() { $dp = new CActiveDataProvider("Blog",array( 'criteria'=>array( 'order'=>'id DESC' ), 'pagination'=>array( 'pageSize'=>50, ), )); $this->render("blog",array('dp'=>$dp)); } public function actionSounds() { echo "wip"; } public function actionChars() { echo "wip"; } } ?><file_sep>/protected/modules/charaBase/views/view/list.php <?php $this->widget('zii.widgets.grid.CGridView', array( 'dataProvider'=>$model->search(), 'filter'=>$model, 'cssFile'=>false, 'enableSorting'=>true, 'columns'=>array( array( 'name'=>'cID', 'header'=>'Owner', 'type'=>'raw', 'value'=>'CHtml::link(Yii::app()->getModule("user")->user($data->uID)->username, array("/user/user/view","id"=>$data->uID))', ), array( 'name'=>'name', 'type'=>'raw', 'value'=>'CHtml::link($data->name,array("view/char","ID"=>$data->cID))' ), 'species', array( 'name'=>'sex', 'value'=>'CBTranslator::sex($data->sex)', 'filter'=>array( $CBT->sex(0),$CBT->sex(1),$CBT->sex(2),$CBT->sex(3),$CBT->sex(4), $CBT->sex(5),$CBT->sex(6),$CBT->sex(7) ), ), array( 'name'=>'orientation', 'value'=>'CBTranslator::orientation($data->orientation)', 'filter'=>array( $CBT->orientation(0),$CBT->orientation(1),$CBT->orientation(2), $CBT->orientation(3),$CBT->orientation(4),$CBT->orientation(5), $CBT->orientation(6), ), ), array( 'name'=>'category', 'value'=>'CBTranslator::category($data->category)', 'filter'=>array($CBT->category(0),$CBT->category(1),$CBT->category(2)) ), array( 'name'=>'position', 'value'=>'CBTranslator::position($data->position)', 'filter'=>array($CBT->position(0),$CBT->position(1)), ), ) )); ?><file_sep>/protected/migrations/m121011_031955_Link.php <?php class m121011_031955_Link extends CDbMigration { public function up() { $this->addColumn('notifyii', 'link', 'string'); } public function down() { echo "m121011_031955_Link does not support migration down.\n"; return false; } }<file_sep>/protected/modules/user/views/profile/profile.php <?php $this->pageTitle=Yii::app()->name . ' - '.UserModule::t("Profile"); $this->breadcrumbs=array( UserModule::t("Profile"), ); $this->layout='//layouts/column2'; $this->menu=array( ((UserModule::isAdmin()) ?array('label'=>UserModule::t('Manage Users'), 'url'=>array('/user/admin')) :array()), array('label'=>UserModule::t('List User'), 'url'=>array('/user')), array('label'=>UserModule::t('Edit'), 'url'=>array('edit')), array('label'=>UserModule::t('Change password'), 'url'=>array('changepassword')), array('label'=>UserModule::t('Logout'), 'url'=>array('/user/logout')), ); ?><h1><?php echo UserModule::t('Your profile'); ?></h1> <?php if(Yii::app()->user->hasFlash('profileMessage')): ?> <div class="success"> <?php echo Yii::app()->user->getFlash('profileMessage'); ?> </div> <?php endif; // For all users $attributes = array( 'username', ); $profileFields=ProfileField::model()->forAll()->sort()->findAll(); if ($profileFields) { foreach($profileFields as $field) { array_push($attributes,array( 'label' => UserModule::t($field->title), 'name' => $field->varname, 'value' => (($field->widgetView($model->profile))?$field->widgetView($model->profile):(($field->range)?Profile::range($field->range,$model->profile->getAttribute($field->varname)):$model->profile->getAttribute($field->varname))), )); } } array_push($attributes, 'create_at', array( 'name' => 'lastvisit_at', 'value' => (($model->lastvisit_at!='0000-00-00 00:00:00')?$model->lastvisit_at:UserModule::t('Not visited')), ), 'email' ); $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>$attributes, )); ?> <br> <?php $CADPmain = new CActiveDataProvider("Character",array( 'criteria'=>array( 'condition'=>'uID='.$model->id.' AND position=1', ) ) ); $CADPcasual = new CActiveDataProvider("Character",array( 'criteria'=>array( 'condition'=>'uID='.$model->id.' AND position=0', ) ) ); $CBT = new CBTranslator; $cols = array( array( 'name'=>'name', 'type'=>'raw', 'value'=>'CHtml::link($data->name,array("/charaBase/view/char","ID"=>$data->cID))' ), 'species', array( 'name'=>'sex', 'value'=>'CBTranslator::sex($data->sex)', ), array( 'name'=>'orientation', 'value'=>'CBTranslator::orientation($data->orientation)', ), array( 'name'=>'category', 'value'=>'CBTranslator::category($data->category)', ), array( 'name'=>'position', 'value'=>'CBTranslator::position($data->position)', ), array( 'class'=>'CButtonColumn', 'header'=>'Actions', 'template'=>'{edit}|{remove}', 'buttons'=>array( 'edit'=>array( 'label'=>'Edit', 'url'=>'CHtml::normalizeUrl(array("/charaBase/maintain/edit", "ID"=>$data->cID))' ), 'remove'=>array( 'label'=>"Delete", 'url'=>'CHtml::normalizeUrl(array("/charaBase/maintain/delete","ID"=>$data->cID))', ) ) ), ); $this->widget('zii.widgets.grid.CGridView',array( 'dataProvider'=>$CADPmain, 'summaryText'=>"<h3>Your main characters:</h3>", 'summaryCssClass'=>'prettySummary', 'columns'=>$cols )); $this->widget('zii.widgets.grid.CGridView',array( 'dataProvider'=>$CADPcasual, 'summaryText'=>"<h3>Your casual characters:</h3>", 'summaryCssClass'=>'prettySummary', 'columns'=>$cols )); ?><file_sep>/protected/modules/notifyii/migrations/m121019_082633_RBAC.php <?php class m121019_082633_RBAC extends CDbMigration { public function up() { try { $this->createTable('AuthItem', array( 'name' => 'string', 'type' => 'integer', 'description' => 'text', 'data' => 'text', )); } catch (Exception $e) { // Nothing to do if table already exists } try { $this->createTable('AuthItemChild', array( 'parent' => 'string', 'child' => 'string', )); } catch (Exception $e) { // Nothing to do if table already exists } try { $this->createTable('AuthAssignment', array( 'itemname' => 'string', 'userid' => 'string', 'bizrule' => 'text', 'date' => 'text' )); } catch (Exception $e) { // Nothing to do if table already exists } } public function down() { echo "m121019_082633_RBAC does not support migration down.\n"; return false; } } <file_sep>/protected/modules/user/views/user/view.php <?php /*$this->breadcrumbs=array( UserModule::t('Users')=>array('index'), $model->username, );*/ #$this->layout='//layouts/column2'; $this->menu=array( array('label'=>UserModule::t('List User'), 'url'=>array('index')), ); ?> <h1><?php echo UserModule::t('View Member').' "'.$model->username.'"'; ?></h1> <?php // For all users $attributes = array( 'username', ); $profileFields=ProfileField::model()->forAll()->sort()->findAll(); if ($profileFields) { foreach($profileFields as $field) { array_push($attributes,array( 'label' => UserModule::t($field->title), 'name' => $field->varname, 'value' => (($field->widgetView($model->profile))?$field->widgetView($model->profile):(($field->range)?Profile::range($field->range,$model->profile->getAttribute($field->varname)):$model->profile->getAttribute($field->varname))), )); } } array_push($attributes, 'create_at', array( 'name' => 'lastvisit_at', 'value' => (($model->lastvisit_at!='0000-00-00 00:00:00')?$model->lastvisit_at:UserModule::t('Not visited')), ) ); $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>$attributes, ));?> <br> <?php $CADPmain = new CActiveDataProvider("Character",array( 'criteria'=>array( 'condition'=>'uID='.$model->id.' AND position=1', ) ) ); $CADPcasual = new CActiveDataProvider("Character",array( 'criteria'=>array( 'condition'=>'uID='.$model->id.' AND position=0', ) ) ); $CBT = new CBTranslator; $cols = array( array( 'name'=>'name', 'type'=>'raw', 'value'=>'CHtml::link($data->name,array("/charaBase/view/char","ID"=>$data->cID))' ), 'species', array( 'name'=>'sex', 'value'=>'CBTranslator::sex($data->sex)', ), array( 'name'=>'orientation', 'value'=>'CBTranslator::orientation($data->orientation)', ), array( 'name'=>'category', 'value'=>'CBTranslator::category($data->category)', ), array( 'name'=>'position', 'value'=>'CBTranslator::position($data->position)', ), ); $this->widget('zii.widgets.grid.CGridView',array( 'dataProvider'=>$CADPmain, 'summaryText'=>"<h3>User's main characters:</h3>", 'summaryCssClass'=>'prettySummary', 'columns'=>$cols )); $this->widget('zii.widgets.grid.CGridView',array( 'dataProvider'=>$CADPcasual, 'summaryText'=>"<h3>User's casual characters:</h3>", 'summaryCssClass'=>'prettySummary', 'columns'=>$cols )); ?> <file_sep>/protected/modules/forum/models/ForumTopics.php <?php class ForumTopics extends CActiveRecord { public $id; public $boardID; public $creatorID; public $sticky; public $name; public $desc; public $views; public $firstPost; // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{Ftopics}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('name','required'), array('desc, sticky','safe'), array("firstPost","required","on"=>"create") ); } public function attributeLabels() { return array( 'name'=>Yii::t("forumModule.main","name"), 'desc'=>Yii::t('forumModule.main',"desc"), 'firstPost'=>Yii::t("forumModule.main","firstPost"), ); } } ?><file_sep>/protected/modules/charaBase/controllers/MaintainController.php <?php class MaintainController extends Controller { // access control public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('create','edit','delete'), 'users'=>array('@'), ), array('deny', 'actions'=>array('create','edit','delete'), 'users'=>array('*'), ), ); } // fun stuff public function actionCreate() { $model = new Character; if(!isset($_POST['Character'])) { Yii::app()->session['cpic'] = array(); $this->render('form', array( 'model'=>$model, 'CBT'=>new CBTranslator, )); } else { $data = $this->workout($model,$_POST,"save"); if($data['success']==true){ $this->render('created',array('model'=>$data['model'])); } else { $this->render('form',array('model'=>$data['model'],'CBT'=>new CBTranslator)); } } } public function actionEdit($ID) { $model = Character::model()->findByPk($ID); if(!isset($_POST['Character'])) { Yii::app()->session['cpic']=unserialize($model->cpic); $this->render('form', array( 'model'=>$model, 'CBT'=>new CBTranslator, )); } else { $data = $this->workout($model,$_POST,"update"); if($data['success']==true) { $this->render('created',array('model'=>$data['model'])); } else { $this->render('form',array('model'=>$data['model'],'CBT'=>new CBTranslator)); } } } public function actionDelete($ID,$delete=2) { $char = Character::model()->findByPk($ID); if($delete==2) { $this->render("delete",array('model'=>$char)); } else { $pics = unserialize($char->cpic); foreach($pics as $pic) { $Cpic = CharacterPicture::model()->findByPk($pic); @unlink(Yii::getPathOfAlias("application.module.charaBase.cpic")."/".$char->cID."/".$Cpic->name); $Cpic->delete(); } $char->delete(); $this->redirect(array("/user/profile")); } } public function actionReset() { unset(Yii::app()->session['cpic']); echo "Unsettet CPIC session."; } private function workout($model,$POST,$type) { $ps = $POST['Character']['scenario']; switch($ps) { case 0: $scenario = "pic-only"; break; case 1: $scenario = "simple"; break; case 2: $scenario = "detailed"; break; case 3: $scenario = "advanced"; break; } $model->scenario=$scenario; # self written mass assignment - it just works. foreach($POST['Character'] as $attribute=>$value) { $model->setAttribute($attribute,$value); } $model->uID = Yii::app()->user->id; $model->cpic = serialize(Yii::app()->session['cpic']); unset(Yii::app()->session['cpic']); if($model->validate()) { $success=true; $cpath = Yii::getPathOfAlias("webroot.protected.modules.charaBase.cpic"); $respath = $cpath.'/tmp/'.Yii::app()->session['cpicID']."/"; $destpath = $cpath.'/'.$model->cID."/"; @mkdir($destpath); $cmd = 'mv '.escapeshellarg($respath).'* '.escapeshellarg($destpath); system($cmd); $cmd = "rm -Rfd ".escapeshellarg($respath); system($cmd); unset(Yii::app()->session['cpicID']); $ACmsg = new AJAXChatMessages; if($type=="save"){ $model->save(); $ACmsg->chatbot('/charCrd '.json_encode(array( 'user'=>Yii::app()->user->name, 'uID'=>Yii::app()->user->id, 'cID'=>$model->cID, 'cname'=>$model->name ))); } else if($type="update") { $model->update(); $ACmsg->chatbot('/charUpd '.json_encode(array( 'user'=>Yii::app()->user->name, 'uID'=>Yii::app()->user->id, 'cID'=>$model->cID, 'cname'=>$model->name ))); } } else die("Validation failed."); #$success=false; return array('model'=>$model,'success'=>$success); } } ?><file_sep>/themes/drag0n/views/layouts/main.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title><?php echo CHtml::encode($this->pageTitle); ?></title> <?php DN::MakeBootstrap(); ?> <?php Yii::app()->clientScript->registerMetaTag('text/html; charset=utf-8',null, 'Content-type'); ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" /> <?php if(!isset($_COOKIE['themepicker'])) { ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/drag0n.css.php" media="screen" /> <?php } else { ?> <link rel="stylesheet" type="text/css" href="<?=$_COOKIE['themepicker']?>" media="screen" /> <?php } ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/bar.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/themePicker.js.php?for=site",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl."/js/extLoader.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/langPick.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScript("barInit","bar.clear();",CClientScript::POS_READY); ?> <?php if(!Yii::app()->user->isGuest) { Yii::app()->clientScript->registerScript("shoutbox", " $.get('/Mall/shoutbox',function(d){ $('#shoutbox').html(d); ajaxChat.initialize(); }); ",CClientScript::POS_READY); } ?> </head> <body> <?php $dn = new DN; $dn->DoTheMenu(); ?> <?php if(isset($this->breadcrumbs)):?> <?php $this->widget('zii.widgets.CBreadcrumbs', array( 'links'=>$this->breadcrumbs, )); ?><!-- breadcrumbs --> <?php endif?> <div id="top"> <?php if(!Yii::app()->user->isGuest) { $text = "Shoutbox"; echo CHtml::link( CHtml::image(Yii::app()->theme->baseUrl."/images/sign.png",null,array("class"=>"centerpic")), "#", array("onclick"=>"bar.shoutbox();") ); } else { $text = "Viatropolis"; echo CHtml::image(Yii::app()->theme->baseUrl."/images/sign.png",$text,array('title'=>$text,'class'=>'centerpic')); } ?> <div id="shoutbox" style="display:none;"></div> </div> <div id="container"><!-- layout content div --> <?php echo $content; ?> </div> </body> </html> <file_sep>/protected/messages/en/admin.php <?php return array( // admin language 'mHead'=>'<p>Choose an area to manage.</p>', 'mChat'=>'Manage the Mall', 'mThemes'=>'Manage themes', 'mBlog'=>'Manage the blog', 'aTheme'=>'Add theme', 'tDesc'=>"<p> Here, you can manage the themes available in Dragon's Inn.<br> The values of <code>gstart</code>, <code>gend</code> and <code>shadow</code> are hex colors. The <code>#</code> will be prepended on use.<br> If <code>shadow</code> was not entered in the adding form, <code>gstart</code> will be used as its value. </p>", 'cDef'=>'Default channel', 'aChat'=>'Add channel', 'cs'=>'Channels', 'aBlog'=>'Create blog entry', 'bDesc'=>"<p> Add, delete or modify blog entries. You can only modify entries you have written yourself.<br> To get to the edit and delete option, click the entry to go to its view page, use the links there. </p>", ); ?><file_sep>/protected/modules/mall/views/loggedIn.php <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="[LANG_CODE/]" lang="[LANG_CODE/]" dir="[BASE_DIRECTION/]"> <?php // Debug ini_set('display_errors', 1); error_reporting(E_ALL); ?> <head> <meta http-equiv="Content-Type" content="[CONTENT_TYPE/]" /> <title>[LANG]title[/LANG]</title> <!-- [STYLE_SHEETS/] --> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->getModule("mall")->assetsUrl; ?>/css/beige.css" media="screen" /> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("mall")->assetsUrl."/js/jquery.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("mall")->assetsUrl."/js/chat.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("mall")->assetsUrl."/js/config.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("mall")->assetsUrl."/js/custom.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("mall")->assetsUrl."/js/FAbridge.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/bar.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->theme->baseUrl."/js/themePicker.js.php?for=chat",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->getModule("mall")->assetsUrl."/js/soundpicker.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->registerScriptFile(Yii::app()->baseUrl."/js/extLoader.js",CClientScript::POS_HEAD); ?> <?php Yii::app()->clientScript->render($output); ?> <?=$output?> <script src="<?=Yii::app()->getModule("mall")->assetsUrl?>/js/lang/[LANG_CODE/].js" type="text/javascript" charset="UTF-8"></script> <script type="text/javascript"> jQuery(function($) { bar.clear(); $("a").css("text-decoration","none"); clearValue(); ajaxChatConfig.boothDir = '<?php echo Yii::app()->getBaseUrl(true); ?>/booths/'; ajaxChatConfig.ajaxURL = "/mall/run?ajax=true"; ajaxChatConfig.chatSystem = ""; }); // <![CDATA[ function clearValue() { $.each($("#channelSelection").find("option"),function(i,v) { $(v).html(ajaxChat.stripBBCodeTags($(v).text())); }); } function toggleContainer(containerID, hideContainerIDs) { if(hideContainerIDs) { for(var i=0; i<hideContainerIDs.length; i++) { ajaxChat.showHide(hideContainerIDs[i], 'none'); } } ajaxChat.showHide(containerID); if(typeof arguments.callee.styleProperty == 'undefined') { if(typeof isIElt7 != 'undefined') { arguments.callee.styleProperty = 'marginRight'; } else { arguments.callee.styleProperty = 'right'; } } var containerWidth = document.getElementById(containerID).offsetWidth; if(containerWidth) { document.getElementById('chatList').style[arguments.callee.styleProperty] = (containerWidth+28)+'px'; document.getElementById('chatBooth').style[arguments.callee.styleProperty] = (containerWidth+28)+'px'; } else { document.getElementById('chatList').style[arguments.callee.styleProperty] = '20px'; document.getElementById('chatBooth').style[arguments.callee.styleProperty] = '20px'; } } function initialize() { ajaxChat.updateButton('audio', 'audioButton'); ajaxChat.updateButton('autoScroll', 'autoScrollButton'); document.getElementById('bbCodeSetting').checked = ajaxChat.getSetting('bbCode'); document.getElementById('bbCodeImagesSetting').checked = ajaxChat.getSetting('bbCodeImages'); document.getElementById('bbCodeColorsSetting').checked = ajaxChat.getSetting('bbCodeColors'); document.getElementById('hyperLinksSetting').checked = ajaxChat.getSetting('hyperLinks'); document.getElementById('lineBreaksSetting').checked = ajaxChat.getSetting('lineBreaks'); document.getElementById('emoticonsSetting').checked = ajaxChat.getSetting('emoticons'); document.getElementById('autoFocusSetting').checked = ajaxChat.getSetting('autoFocus'); document.getElementById('maxMessagesSetting').value = ajaxChat.getSetting('maxMessages'); document.getElementById('wordWrapSetting').checked = ajaxChat.getSetting('wordWrap'); document.getElementById('maxWordLengthSetting').value = ajaxChat.getSetting('maxWordLength'); document.getElementById('dateFormatSetting').value = ajaxChat.getSetting('dateFormat'); document.getElementById('persistFontColorSetting').checked = ajaxChat.getSetting('persistFontColor'); for(var i=0; i<document.getElementById('audioVolumeSetting').options.length; i++) { if(document.getElementById('audioVolumeSetting').options[i].value == ajaxChat.getSetting('audioVolume')) { document.getElementById('audioVolumeSetting').options[i].selected = true; break; } } document.getElementById('blinkSetting').checked = ajaxChat.getSetting('blink'); document.getElementById('blinkIntervalSetting').value = ajaxChat.getSetting('blinkInterval'); document.getElementById('blinkIntervalNumberSetting').value = ajaxChat.getSetting('blinkIntervalNumber'); document.getElementById('booth').src = '<?php echo Yii::app()->getBaseUrl(true); ?>/booths/'+ ajaxChatConfig.loginChannelID +'/index.html'; if(ajaxChatConfig.chatSystem == 'off') { document.getElementById('chatshow').style.visibility='hidden'; document.getElementById('inputFieldContainer').style.display='none'; document.getElementById('submitButtonContainer').style.display = 'none'; document.getElementById('bbCodeContainer').style.display = 'none'; document.getElementById('onlineListButton').click(); document.getElementById('onlineListButton').style.display = 'none'; document.getElementById('chatBooth').style.bottom = "60px"; document.getElementById('chatBooth').style.top = "45px"; } else { //document.getElementById('chatBooth').style.bottom = "150px;"; } } ajaxChatConfig.loginChannelID = parseInt('[LOGIN_CHANNEL_ID/]'); ajaxChatConfig.sessionName = '[SESSION_NAME/]'; ajaxChatConfig.cookieExpiration = parseInt('[COOKIE_EXPIRATION/]'); ajaxChatConfig.cookiePath = '[COOKIE_PATH/]'; ajaxChatConfig.cookieDomain = '[COOKIE_DOMAIN/]'; ajaxChatConfig.cookieSecure = '[COOKIE_SECURE/]'; ajaxChatConfig.chatBotName = decodeURIComponent('[CHAT_BOT_NAME/]'); ajaxChatConfig.chatBotID = '[CHAT_BOT_ID/]'; ajaxChatConfig.allowUserMessageDelete = parseInt('[ALLOW_USER_MESSAGE_DELETE/]'); ajaxChatConfig.inactiveTimeout = parseInt('[INACTIVE_TIMEOUT/]'); ajaxChatConfig.privateChannelDiff = parseInt('[PRIVATE_CHANNEL_DIFF/]'); ajaxChatConfig.privateMessageDiff = parseInt('[PRIVATE_MESSAGE_DIFF/]'); ajaxChatConfig.showChannelMessages = parseInt('[SHOW_CHANNEL_MESSAGES/]'); ajaxChatConfig.messageTextMaxLength = parseInt('[MESSAGE_TEXT_MAX_LENGTH/]'); ajaxChatConfig.socketServerEnabled = parseInt('[SOCKET_SERVER_ENABLED/]'); ajaxChatConfig.socketServerHost = decodeURIComponent('[SOCKET_SERVER_HOST/]'); ajaxChatConfig.socketServerPort = parseInt('[SOCKET_SERVER_PORT/]'); ajaxChatConfig.socketServerChatID = parseInt('[SOCKET_SERVER_CHAT_ID/]'); ajaxChatConfig.baseURL = "<?=Yii::app()->getModule("mall")->assetsUrl?>/"; ajaxChat.init(ajaxChatConfig, ajaxChatLang, true, true, true, initialize); //bird2 soundPickInit(); // ]]> </script> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->theme->baseUrl; ?>/css/bar.css.php" media="screen" /> <style type="text/css"> body { padding:0; margin:0; } * { outline:0; } #bar, #ubar, #Nbar { z-index: 20; } #bar li, #ubar li, #Nbar li { padding-top: 3px; } </style> </head> <body> <div id="content"> <?php $dn = new DN; $dn->DoTheMenu(); ?> <div id="chatBooth" style="overflow: hidden;"> <iframe style="overflow:hidden;height:100%;width:100%;" height="100%" width="100%" frameborder="0" scrolling="no" name="booth" id="booth" src="about:blank"> </iframe> </div> <div id="chatList" style="display:none; overflow: hidden;"></div> <div id="inputFieldContainer"> <textarea id="inputField" rows="1" cols="50" title="[LANG]inputLineBreak[/LANG]" onkeypress="ajaxChat.handleInputFieldKeyPress(event);" onkeyup="ajaxChat.handleInputFieldKeyUp(event);"></textarea> </div> <div id="submitButtonContainer"> <span id="postNote"><span id="messageLengthCounter">0</span> [LANG]characters[/LANG]</span> <input type="button" id="submitButton" value="[LANG]messageSubmit[/LANG]" onclick="ajaxChat.sendMessage();"/> </div> <div id="logoutChannelContainer"> </div> <div id="bbCodeContainer"> <input type="button" id="button" value="[LANG]bbCodeLabelBold[/LANG]" title="[LANG]bbCodeTitleBold[/LANG]" onclick="ajaxChat.insertBBCode('b');" style="font-weight:bold;"/> <input type="button" id="button" value="[LANG]bbCodeLabelItalic[/LANG]" title="[LANG]bbCodeTitleItalic[/LANG]" onclick="ajaxChat.insertBBCode('i');" style="font-style:italic;"/> <input type="button" id="button" value="[LANG]bbCodeLabelUnderline[/LANG]" title="[LANG]bbCodeTitleUnderline[/LANG]" onclick="ajaxChat.insertBBCode('u');" style="text-decoration:underline;"/> <input type="button" id="button" value="[LANG]bbCodeLabelColor[/LANG]" title="[LANG]bbCodeTitleColor[/LANG]" onclick="ajaxChat.showHide('colorCodesContainer', null);"/> <input type="button" id="button" value="[LANG]bbCodeLabelEmoticons[/LANG]" title="[LANG]bbCodeLabelEmoticons[/LANG]" onclick="ajaxChat.showHide('emoticonsContainer', null);"> </div> <div id="emoticonsContainer" style="display:none;" dir="ltr"></div> <div id="colorCodesContainer" style="display:none;" dir="ltr"></div> <div id="optionsContainer"> <input type="button" value="[LANG]previousStore[/LANG]" id="backwords" title="[LANG]previousTitleStore[/LANG]" alt="[LANG]previousStore[/LANG]" onclick="ajaxChat.cChange('up')"/> <input type="button" value="[LANG]forwardStore[/LANG]" id="forward" title="[LANG]forwardTitleStore[/LANG]" alt="[LANG]forwardStore[/LANG]" onclick="ajaxChat.cChange('down');"/> <label for="channelSelection" id="cSlabel">Store:</label><select id="channelSelection" onchange="ajaxChat.switchChannel(this.options[this.selectedIndex].value);clearValue();">[CHANNEL_OPTIONS/]</select> <input type="button" value="[LANG]toggleChat[/LANG]" id="chatshow" title="[LANG]toggleTitleChat[/LANG]" alt="[LANG]toggleChat[/LANG]" onclick="ajaxChat.showHide('chatList', null);"/> <input type="image" src="<?=Yii::app()->getModule("mall")->assetsUrl?>/img/help.png" class="button" alt="[LANG]toggleHelp[/LANG]" title="[LANG]toggleHelp[/LANG]" onclick="window.open('[AURL]/mall/help[/AURL]'); return false;"/> <input type="image" src="<?=Yii::app()->getModule("mall")->assetsUrl?>/img/chars.png" class="button" id="helpButton" alt="[LANG]toggleChars[/LANG]" title="[LANG]toggleChars[/LANG]" onclick="toggleContainer('helpContainer', new Array('onlineListContainer','settingsContainer'));"/> <input type="image" src="<?=Yii::app()->getModule("mall")->assetsUrl?>/img/settings.png" class="button" id="settingsButton" alt="[LANG]toggleSettings[/LANG]" title="[LANG]toggleSettings[/LANG]" onclick="toggleContainer('settingsContainer', new Array('onlineListContainer','helpContainer'));" style="visibility:hidden"/> <input type="image" src="<?=Yii::app()->getModule("mall")->assetsUrl?>/img/users.png" class="button" id="onlineListButton" alt="[LANG]toggleOnlineList[/LANG]" title="[LANG]toggleOnlineList[/LANG]" onclick="toggleContainer('onlineListContainer', new Array('settingsContainer','helpContainer'));"/> <input type="image" src="<?=Yii::app()->getModule("mall")->assetsUrl?>/img/pixel.gif" class="button" id="audioButton" alt="[LANG]toggleAudio[/LANG]" title="[LANG]toggleAudio[/LANG]" onclick="ajaxChat.toggleSetting('audio', 'audioButton');"/> <input type="image" src="<?=Yii::app()->getModule("mall")->assetsUrl?>/img/pixel.gif" class="button" id="autoScrollButton" alt="[LANG]toggleAutoScroll[/LANG]" title="[LANG]toggleAutoScroll[/LANG]" onclick="ajaxChat.toggleSetting('autoScroll', 'autoScrollButton');"/> <div id="statusIconContainer" class="statusContainerOn" onclick="ajaxChat.updateChat(null);"></div> </div> <div id="onlineListContainer"> <h3>[LANG]onlineUsers[/LANG]</h3> <div id="onlineList"></div> </div> <div id="helpContainer" style="display:none;"> <h3><?=Yii::t("site","cselect")?></h3> <div id="helpList"><table> <?php $chars = Character::model()->findAll(array('condition'=>'uID='.Yii::app()->user->id)); $class = "rowOdd"; foreach($chars as $char) { ?> <tr class="<?=$class?>"> <td class="dec"> <?=Yii::t("CharaBaseModule.cb","name").": ".htmlspecialchars($char->name)?><br> <?php if(!empty($char->nickName)) echo Yii::t("CharaBaseModule.cb","nickName").": ".htmlspecialchars($char->nickName)."<br>";?> <?=CHtml::link( Yii::t("site","play"), "javascript:ajaxChat.sendMessageWrapper('/changeToChar ".$char->cID."');", array("style"=>"color:lime;") )?> <?=CHtml::link( Yii::t("site","profil"), array("/charaBase/view/char",'ID'=>$char->cID), array("style"=>"color:lime;") )?> <?=CHtml::link( Yii::t("site","edit"), array("/charaBase/maintain/edit",'ID'=>$char->cID), array("style"=>"color:lime;") )?> </td> <td class="code"> <?=Yii::t("CharaBaseModule.cb","species").": ".htmlspecialchars($char->species)?><br> <?=Yii::t("CharaBaseModule.cb","sex").": ".CBTranslator::sex($char->sex)?><br> <?php /*CBTranslator::orientation(intval($char->orientation)) */?><br> </td> </tr><?php if($class == "rowOdd") $class = "rowEven"; else $class = "rowOdd"; } ?> </table></div> </div> <div id="settingsContainer" style="display:none;"> <h3>[LANG]settings[/LANG]</h3> <div id="settingsList"> <table> <tr class="rowOdd"> <td><label for="bbCodeSetting">[LANG]settingsBBCode[/LANG]</label></td> <td class="setting"><input type="checkbox" id="bbCodeSetting" onclick="ajaxChat.setSetting('bbCode', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="bbCodeImagesSetting">[LANG]settingsBBCodeImages[/LANG]</label></td> <td class="setting"><input type="checkbox" id="bbCodeImagesSetting" onclick="ajaxChat.setSetting('bbCodeImages', this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="bbCodeColorsSetting">[LANG]settingsBBCodeColors[/LANG]</label></td> <td class="setting"><input type="checkbox" id="bbCodeColorsSetting" onclick="ajaxChat.setSetting('bbCodeColors', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="hyperLinksSetting">[LANG]settingsHyperLinks[/LANG]</label></td> <td class="setting"><input type="checkbox" id="hyperLinksSetting" onclick="ajaxChat.setSetting('hyperLinks', this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="lineBreaksSetting">[LANG]settingsLineBreaks[/LANG]</label></td> <td class="setting"><input type="checkbox" id="lineBreaksSetting" onclick="ajaxChat.setSetting('lineBreaks', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="emoticonsSetting">[LANG]settingsEmoticons[/LANG]</label></td> <td class="setting"><input type="checkbox" id="emoticonsSetting" onclick="ajaxChat.setSetting('emoticons', this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="autoFocusSetting">[LANG]settingsAutoFocus[/LANG]</label></td> <td class="setting"><input type="checkbox" id="autoFocusSetting" onclick="ajaxChat.setSetting('autoFocus', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="maxMessagesSetting">[LANG]settingsMaxMessages[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="maxMessagesSetting" onchange="ajaxChat.setSetting('maxMessages', parseInt(this.value));"/></td> </tr> <tr class="rowOdd"> <td><label for="wordWrapSetting">[LANG]settingsWordWrap[/LANG]</label></td> <td class="setting"><input type="checkbox" id="wordWrapSetting" onclick="ajaxChat.setSetting('wordWrap', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="maxWordLengthSetting">[LANG]settingsMaxWordLength[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="maxWordLengthSetting" onchange="ajaxChat.setSetting('maxWordLength', parseInt(this.value));"/></td> </tr> <tr class="rowOdd"> <td><label for="dateFormatSetting">[LANG]settingsDateFormat[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="dateFormatSetting" onchange="ajaxChat.setSetting('dateFormat', this.value);"/></td> </tr> <tr class="rowEven"> <td><label for="persistFontColorSetting">[LANG]settingsPersistFontColor[/LANG]</label></td> <td class="setting"><input type="checkbox" id="persistFontColorSetting" onclick="ajaxChat.setPersistFontColor(this.checked);"/></td> </tr> <tr class="rowOdd"> <td><label for="audioVolumeSetting">[LANG]settingsAudioVolume[/LANG]</label></td> <td class="setting"> <select class="left" id="audioVolumeSetting" onchange="ajaxChat.setAudioVolume(this.options[this.selectedIndex].value);"> <option value="1.0">100 %</option> <option value="0.9">90 %</option> <option value="0.8">80 %</option> <option value="0.7">70 %</option> <option value="0.6">60 %</option> <option value="0.5">50 %</option> <option value="0.4">40 %</option> <option value="0.3">30 %</option> <option value="0.2">20 %</option> <option value="0.1">10 %</option> </select> </td> </tr> <tr class="rowEven"> <td><label for="themePicker">[LANG]style[/LANG]:</label></td> <td class="setting"> <select id="themePicker"></select> </td> </tr> <tr class="rowOdd"> <td><label for="soundPick">Sound theme:</label></td> <td class="setting"> <select id="soundPick"></select> </td> </tr> <tr class="rowEven"> <td><label for="languageSelection">[LANG]language[/LANG]:</label></td> <td class="setting"> <select id="languageSelection" onchange="ajaxChat.switchLanguage(this.value);">[LANGUAGE_OPTIONS/]</select> </td> </tr> <tr class="rowOdd"> <td><label for="blinkSetting">[LANG]settingsBlink[/LANG]</label></td> <td class="setting"><input type="checkbox" id="blinkSetting" onclick="ajaxChat.setSetting('blink', this.checked);"/></td> </tr> <tr class="rowEven"> <td><label for="blinkIntervalSetting">[LANG]settingsBlinkInterval[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="blinkIntervalSetting" onchange="ajaxChat.setSetting('blinkInterval', parseInt(this.value));"/></td> </tr> <tr class="rowOdd"> <td><label for="blinkIntervalNumberSetting">[LANG]settingsBlinkIntervalNumber[/LANG]</label></td> <td class="setting"><input type="text" class="text" id="blinkIntervalNumberSetting" onchange="ajaxChat.setSetting('blinkIntervalNumber', parseInt(this.value));"/></td> </tr> </table> </div> </div> </div> <div id="flashInterfaceContainer"></div> </body> </html><file_sep>/protected/views/manage/blog.php <h1>Blog</h1> <?=Yii::t("admin","bDesc")?> <?=CHtml::link(Yii::t("admin","aBlog"),array("/Viatropolis/create"))?> <?php $this->widget("zii.widgets.grid.CGridView",array( 'dataProvider'=>$dp, 'columns'=>array( 'id', array( 'name'=>'Author', 'type'=>'raw', 'value'=>'CHtml::link(Yii::app()->getModule("user")->user($data->author)->username,array("/user/user/view","id"=>Yii::app()->getModule("user")->user($data->author)->id))', ), array( 'name'=>'modified', 'type'=>'raw', 'value'=>'date("d.m.Y H:i",$data->modified)', ), 'tags', array( 'name'=>'title', 'type'=>'raw', 'value'=>'CHtml::link($data->title,array("/Viatropolis/view","id"=>$data->id))' ), ) )); ?><file_sep>/protected/controllers/UploadController.php <?php class UploadController extends Controller { private $to; public function actionIndex() { if(!isset($_FILES['upd'])) $this->render("upload"); else { $path = Yii::getPathOfAlias("webroot.u"); $newName = uniqid().".".pathinfo($_FILES['upd']['name'], PATHINFO_EXTENSION); if(!empty($_FILES['upd']['tmp_name'])) move_uploaded_file($_FILES['upd']['tmp_name'], $path."/".$newName); else die("ERROR."); $this->render("uploaded",array('newName'=>$newName)); } } } ?><file_sep>/protected/models/Coupon.php <?php class Coupon extends CActiveRecord { public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{coupon}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('company', 'required'), array('id, status', 'unsafe'), # prevent ->attributes=$_POST manipulation ); } public $id; # PK public $company; public $slots; public $status; public $users=array(); // { name:ActiveRecord(User) } public function uniqueString($length=20) { $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" ."abcdefghijklmnopqrstuvwxyz" ."01234567890" ."?!.,;:-=<>"; $str = ""; for($i=0; $i<$length; $i++) { $str .= $chars[mt_rand(0, strlen($chars))]; } return $str; } public function beforeSave() { $this->id = $this->uniqueString(); parent::beforeSave(); } public function afterFind() { $users = User::model()->findByAttributes(array( "couponCode" => $this->id )); foreach($users as $user) $this->users[$user->username]=$user; parent::afterFind(); } } ?><file_sep>/protected/modules/charaBase/models/CharacterPicture.php <?php class CharacterPicture extends CActiveRecord { // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{charabasePictures}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('name,url,desc','safe') ); } /* @var (pk) int(11) id @var int(11) cID @var varchar(255) name @var text desc */ public $id; public $name; public $url; public $desc; } ?><file_sep>/protected/modules/charaBase/models/CharacterImporter.php <?php class CharacterImporter extends CActiveRecord { // old DB variables public $id; public $name; public $category; public $species; public $sex; public $birthdate; public $placeofbirth; public $hair_c; public $hair_s; public $hair_l; public $eye_c; public $eye_s; public $desc; public $history; public $likes; public $dislikes; public $relationship; public $addit; public $created; public $birthday; public $birthPlace; public $addit_desc; public $position; public $orientation=0; public $scenario=3; public $relationships; public function rules() { return array( array('name, sex, orientation, species, category, position','required'), array( 'name category, species, sex, birthday, birthdate, birthplace, placeofbirth, hair_c, hair_s, hair_l, eye_c, eye_s, desc, history, likes, dislikes, relationship, addit, created, addit_desc','safe' ) ); } public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{charabaseImporter}}'; } public function primaryKey() { return 'id'; } public function prepair() { $this->birthday = $this->birthdate; $this->birthPlace = $this->placeofbirth; $this->addit_desc = $this->desc."<br><br>".$this->addit; $this->relationships = $this->relationship; $this->position=0; switch($this->category) { case "English": $this->category=1;break; case "German": $this->category=2;break; default: $this->category=0;break; } unset($this->birthdate); unset($this->desc); unset($this->addit); unset($this->relationship); unset($this->placeofbirth); } } ?><file_sep>/protected/modules/mall/models/AJAXChatDefaults.php <?php class AJAXChatDefaults extends CActiveRecord { // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return 'ajax_chat_defaults'; } public function primaryKey() { return 'PK'; } public function rules() { return array( array("adminChannels, userChannels","required"), ); } public $adminChannels; // serialized array public $userChannels; // serialized array } ?><file_sep>/protected/views/layouts/main.php <?php /* @var $this Controller */ ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <meta name="language" content="en" /> <!-- blueprint CSS framework --> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/screen.css" media="screen, projection" /> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/print.css" media="print" /> <!--[if lt IE 8]> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/ie.css" media="screen, projection" /> <![endif]--> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/main.css" /> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->request->baseUrl; ?>/css/form.css" /> <title><?php echo CHtml::encode($this->pageTitle); ?></title> </head> <body> <div class="container" id="page"> <div id="header"> <div id="logo">test<?php echo CHtml::encode(Yii::app()->name); ?></div> </div><!-- header --> <ul id="menu"> <li><a href="#" class="drop">Home</a><!-- Begin Home Item --> <div class="dropdown_2columns"><!-- Begin 2 columns container --> <div class="col_2"> <h2>Welcome !</h2> </div> <div class="col_2"> <p>Hi and welcome here ! This is a showcase of the possibilities of this awesome Mega Drop Down Menu.</p> <p>This item comes with a large range of prepared typographic stylings such as headings, lists, etc.</p> </div> <div class="col_2"> <h2>Cross Browser Support</h2> </div> <div class="col_1"> <img src="img/browsers.png" width="125" height="48" alt="" /> </div> <div class="col_1"> <p>This mega menu has been tested in all major browsers.</p> </div> </div><!-- End 2 columns container --> </li><!-- End Home Item --> <li><a href="#" class="drop">5 Columns</a><!-- Begin 5 columns Item --> <div class="dropdown_5columns"><!-- Begin 5 columns container --> <div class="col_5"> <h2>This is an example of a large container with 5 columns</h2> </div> <div class="col_1"> <p class="black_box">This is a dark grey box text. Fusce in metus at enim porta lacinia vitae a arcu. Sed sed lacus nulla mollis porta quis.</p> </div> <div class="col_1"> <p>Phasellus vitae sapien ac leo mollis porta quis sit amet nisi. Mauris hendrerit, metus cursus accumsan tincidunt.</p> </div> <div class="col_1"> <p class="italic">This is a sample of an italic text. Consequat scelerisque. Fusce sed lectus at arcu mollis accumsan at nec nisi porta quis sit amet.</p> </div> <div class="col_1"> <p>Curabitur euismod gravida ante nec commodo. Nunc dolor nulla, semper in ultricies vitae, vulputate porttitor neque.</p> </div> <div class="col_1"> <p class="strong">This is a sample of a bold text. Aliquam sodales nisi nec felis hendrerit ac eleifend lectus feugiat scelerisque.</p> </div> <div class="col_5"> <h2>Here is some content with side images</h2> </div> <div class="col_3"> <img src="img/01.jpg" width="70" height="70" class="img_left imgshadow" alt="" /> <p>Maecenas eget eros lorem, nec pellentesque lacus. Aenean dui orci, rhoncus sit amet tristique eu, tristique sed odio. Praesent ut interdum elit. Sed in sem mauris. Aenean a commodo mi. Praesent augue lacus.<a href="#">Read more...</a></p> <img src="img/02.jpg" width="70" height="70" class="img_left imgshadow" alt="" /> <p>Aliquam elementum felis quis felis consequat scelerisque. Fusce sed lectus at arcu mollis accumsan at nec nisi. Aliquam pretium mollis fringilla. Nunc in leo urna, eget varius metus. Aliquam sodales nisi.<a href="#">Read more...</a></p> </div> <div class="col_2"> <p class="black_box">This is a black box, you can use it to highligh some content. Sed sed lacus nulla, et lacinia risus. Phasellus vitae sapien ac leo mollis porta quis sit amet nisi. Mauris hendrerit, metus cursus accumsan tincidunt.Quisque vestibulum nisi non nunc blandit placerat. Mauris facilisis, risus ut lobortis posuere, diam lacus congue lorem, ut condimentum ligula est vel orci. Donec interdum lacus at velit varius gravida. Nulla ipsum risus.</p> </div> </div><!-- End 5 columns container --> </li><!-- End 5 columns Item --> <li><a href="#" class="drop">4 Columns</a><!-- Begin 4 columns Item --> <div class="dropdown_4columns"><!-- Begin 4 columns container --> <div class="col_4"> <h2>This is a heading title</h2> </div> <div class="col_1"> <h3>Some Links</h3> <ul> <li><a href="#">ThemeForest</a></li> <li><a href="#">GraphicRiver</a></li> <li><a href="#">ActiveDen</a></li> <li><a href="#">VideoHive</a></li> <li><a href="#">3DOcean</a></li> </ul> </div> <div class="col_1"> <h3>Useful Links</h3> <ul> <li><a href="#">NetTuts</a></li> <li><a href="#">VectorTuts</a></li> <li><a href="#">PsdTuts</a></li> <li><a href="#">PhotoTuts</a></li> <li><a href="#">ActiveTuts</a></li> </ul> </div> <div class="col_1"> <h3>Other Stuff</h3> <ul> <li><a href="#">FreelanceSwitch</a></li> <li><a href="#">Creattica</a></li> <li><a href="#">WorkAwesome</a></li> <li><a href="#">Mac Apps</a></li> <li><a href="#">Web Apps</a></li> </ul> </div> <div class="col_1"> <h3>Misc</h3> <ul> <li><a href="#">Design</a></li> <li><a href="#">Logo</a></li> <li><a href="#">Flash</a></li> <li><a href="#">Illustration</a></li> <li><a href="#">More...</a></li> </ul> </div> </div><!-- End 4 columns container --> </li><!-- End 4 columns Item --> <li class="menu_right"><a href="#" class="drop">1 Column</a> <div class="dropdown_1column align_right"> <div class="col_1"> <ul class="simple"> <li><a href="#">FreelanceSwitch</a></li> <li><a href="#">Creattica</a></li> <li><a href="#">WorkAwesome</a></li> <li><a href="#">Mac Apps</a></li> <li><a href="#">Web Apps</a></li> <li><a href="#">NetTuts</a></li> <li><a href="#">VectorTuts</a></li> <li><a href="#">PsdTuts</a></li> <li><a href="#">PhotoTuts</a></li> <li><a href="#">ActiveTuts</a></li> <li><a href="#">Design</a></li> <li><a href="#">Logo</a></li> <li><a href="#">Flash</a></li> <li><a href="#">Illustration</a></li> <li><a href="#">More...</a></li> </ul> </div> </div> </li> <li class="menu_right"><a href="#" class="drop">3 columns</a><!-- Begin 3 columns Item --> <div class="dropdown_3columns align_right"><!-- Begin 3 columns container --> <div class="col_3"> <h2>Lists in Boxes</h2> </div> <div class="col_1"> <ul class="greybox"> <li><a href="#">FreelanceSwitch</a></li> <li><a href="#">Creattica</a></li> <li><a href="#">WorkAwesome</a></li> <li><a href="#">Mac Apps</a></li> <li><a href="#">Web Apps</a></li> </ul> </div> <div class="col_1"> <ul class="greybox"> <li><a href="#">ThemeForest</a></li> <li><a href="#">GraphicRiver</a></li> <li><a href="#">ActiveDen</a></li> <li><a href="#">VideoHive</a></li> <li><a href="#">3DOcean</a></li> </ul> </div> <div class="col_1"> <ul class="greybox"> <li><a href="#">Design</a></li> <li><a href="#">Logo</a></li> <li><a href="#">Flash</a></li> <li><a href="#">Illustration</a></li> <li><a href="#">More...</a></li> </ul> </div> <div class="col_3"> <h2>Here are some image examples</h2> </div> <div class="col_3"> <img src="img/02.jpg" width="70" height="70" class="img_left imgshadow" alt="" /> <p>Maecenas eget eros lorem, nec pellentesque lacus. Aenean dui orci, rhoncus sit amet tristique eu, tristique sed odio. Praesent ut interdum elit. Maecenas imperdiet, nibh vitae rutrum vulputate, lorem sem condimentum.<a href="#">Read more...</a></p> <img src="img/01.jpg" width="70" height="70" class="img_left imgshadow" alt="" /> <p>Aliquam elementum felis quis felis consequat scelerisque. Fusce sed lectus at arcu mollis accumsan at nec nisi. Aliquam pretium mollis fringilla. Vestibulum tempor facilisis malesuada. <a href="#">Read more...</a></p> </div> </div><!-- End 3 columns container --> </li><!-- End 3 columns Item --> </ul> <?php if(isset($this->breadcrumbs)):?> <?php $this->widget('zii.widgets.CBreadcrumbs', array( 'links'=>$this->breadcrumbs, )); ?><!-- breadcrumbs --> <?php endif?> <?php echo $content; ?> <div class="clear"></div> <div id="footer"> </div><!-- footer --> </div><!-- page --> </body> </html> <file_sep>/protected/controllers/DoController.php <?php class DoController extends Controller { public $themes=array( 'Gavoratizon'=>array('gstart'=>'212121','gend'=>'000000'), 'Mo'=>array('gstart'=>'4B4B4B', 'gend'=>'2F2F2F'), 'Makoto'=>array('gstart'=>'BAA7FF', 'gend'=>'9385D0'), 'Venus'=>array('gstart'=>'E0E000', 'gend'=>'BEBE00'), 'Janusch'=>array('gstart'=>'FF0000', 'gend'=>'E00000'), 'Anthy'=>array('gstart'=>'B52A62', 'gend'=>'992864'), 'Dan&Gakuen'=>array('gstart'=>'0000FF', 'gend'=>'0000D5'), "Shi'ran"=>array('gstart'=>'FF9D00', 'gend'=>'BC7400'), 'Leon'=>array('gstart'=>'985E00', 'gend'=>'623C00'), '<NAME>'=>array('gstart'=>'E8E274', 'gend'=>'B0AA49'), 'Aria'=>array('gstart'=>'C20000', 'gend'=>'8B0000'), 'Xian'=>array('gstart'=>'FFFFFF', 'gend'=>'ECECEC'), 'Dayori'=>array('gstart'=>'0000BA', 'gend'=>'00008E'), 'Legiza'=>array('gstart'=>'FFAFFF', 'gend'=>'FE86FE'), 'Ceinios'=>array('gstart'=>'96D84F', 'gend'=>'75AA3D'), 'Ranshiin'=>array('gstart'=>'4169E4', 'gend'=>'6699CC'), "Alter're"=>array('gstart'=>'C500D7', 'gend'=>'A83BB2'), 'Rier'=>array('gstart'=>'FF2600', 'gend'=>'E32A00'), "Ess'radu"=>array('gstart'=>'C8E0FF', 'gend'=>'8EBFFF'), 'Kyrziz'=>array('gstart'=>'85ffdf', 'gend'=>'71CCA5'), 'Totus'=>array('gstart'=>'d5c988', 'gend'=>'ACA26D'), 'Blaze'=>array('gstart'=>'FF3ad5', 'gend'=>'C80084'), 'Minecraft'=>array('gstart'=>'5DC800', 'gend'=>'7F5500'), 'Nether'=>array('gstart'=>'985967', 'gend'=>'773847'), 'End' =>array('gstart'=>'3CD097', 'gend'=>'1E8B61'), 'Leviathan-Landon' =>array('gstart'=>'F8FFD2', 'gend'=>'DAE0B8'), 'Bloodlust'=>array('gstart'=>'6F0000', 'gend'=>'5B0000'), 'Mermaid'=>array('gstart'=>'00518f', 'gend'=>'003963'), 'Royalty'=>array('gstart'=>'735989', 'gend'=>'584469'), 'D'=>array('gstart'=>'740a00', 'gend'=>'000000'), 'Black Ice'=>array('gstart'=>'3d656d', 'gend'=>'000000'), 'Genom'=>array('gstart'=>'1f567a', 'gend'=>'003366'), 'Corpse Party'=>array('gstart'=>'743d46', 'gend'=>'000000') ); /*public function actionIndex() { foreach($this->themes as $name=>$detail) { $t = new Themes; $t->name=$name; $t->gstart=$detail['gstart']; $t->gend=$detail['gend']; if(!isset($detail['shadow'])) $t->shadow=$detail['gstart']; else $t->shadow=$detail['shadow']; if($t->save()) echo "[$t->name]--> Saved. <br>\n"; else { echo "ERROR."; print_r($t->errors); echo "\n"; break; } } }*/ public function actionIndex() { $this->render("index"); } } ?><file_sep>/protected/views/do/index.php <?php $this->widget('ext.widgets.loading.LoadingWidget'); ?> <a href="#" onclick="Loading.show()">o.o</a><br><a href="#" onclick="Loading.hide()"> >.< </a> <file_sep>/protected/modules/charaBase/views/maintain/created.php <?php $this->redirect(array("view/char","ID"=>$model->cID)); ?><file_sep>/protected/modules/mall/models/AJAXChatChannels.php <?php class AJAXChatChannels extends CActiveRecord { // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return 'ajax_chat_channels'; } public function primaryKey() { return 'id'; } public function rules() { return array( array("name, orderID","required"), array("desc","safe") ); } public $id; public $orderID=100; public $name; public $desc; public function attributeLabels() { return include(Yii::getPathOfAlias("mall.messages.".Yii::app()->language)."/main.php"); } } ?><file_sep>/protected/modules/charaBase/models/Character.php <?php class Character extends CActiveRecord { /* @var int {unique pk} cID @var int uID @var string name @var string nickName @var int category @var int position @array-serialized numeric(N=>assoc(desc=>desc,img=>url)) cpic CASUAL APPEARANCE @var string birthday @var string makeup @var string birthPlace @var string clothing @var int sex @var bool addit_appearance @var int orientation @var text addit_appearance_desc @var string species BODY BODY->EYES @var string height @var string eye_c @var string weight @var string eye_s BODY->HAIR DESC @var string hair_c @var text history @var string hair_s @var text likes @var string hair_l @var text dislikes @var text addit_desc @var text relationships RELATIONSHIP @array-serialized assoc( name=>assoc( desc=>desc, depicPage=>url, memberList=>url ) ) family | makotoExtension::getFamily @array-serialized assoc(name=>url) partners (Mates,wife/husband,etc.) | makotoExtension::getPartners @array-serialized assoc(name=>url) pets | makotoExtension::getPets @array-serialized assoc(name=>url) slaves | makotoExtension::getSlaves @array-serialized assoc(name=>url) master | makotoExtension::getMaster (will return array anyway, even if only one master.) RELATIONSHIPS_EXTRA @array-serialized assoc(name=>desc) forms | makotoExtension::getForms @array-serialized assoc(name=>desc) clan | makotoExtension::getClan ADULT @var int ds (dominant/submissive) @text prefs @var bool addit_adult SPIRIT @var bool status (dead,alive) @var int condition (healthy,ill,dramatic) @var int alignment (good,neutral,evil) @var int sub_alignment (lawful,middle,chaotic) @var int type (light,twilight,dark) @var string death_date @var string death_cause @var string death_place */ /* Scenarios: pic-only name, sex, orientation, cpic simple: name, sex, orientation, height, weight, history, cpic detailed: name, sex, orientation, height, weight, history, likes, dislikes, relationships, nickName, dom_sub, prefs, addit_adult, addit_adult_desc, cpic advanced: name, sex, orientation, height, weight, history, likes, dislikes, relationships eye_c, eye_s, hair_c, hair_s, hair_l, clothing, makeup, addit_appearance, addit_appearance_desc dom_sub, prefs, addit_adult, addit_adult_desc */ public $cID; public $uID; public $name; public $nickName; public $sex; public $orientation; public $species; public $category; public $position; public $scenario; public $cpic; public $birthday; public $birthPlace; public $height; public $weight; public $eye_c; public $eye_s; public $hair_c; public $hair_s; public $hair_l; public $makeup; public $clothing; public $addit_appearance; public $history; public $likes; public $dislikes; public $addit_desc; public $relationships; /* public $family; public $partners; public $pets; public $slaves; public $master; public $clan; public $forms; */ public $dom_sub; public $prefs; public $addit_adult; public $spirit_status; public $spirit_condition; public $spirit_alignment; public $spirit_sub_alignment; public $spirit_type; public $spirit_death_date; public $spirit_death_cause; public $spirit_death_place; public function rules() { return array( array('name, sex, orientation, species, category, position','required'), array('height, weight, history, likes, dislikes', 'safe', 'on'=>'simple'), array( 'height, weight, history, likes, dislikes, relationships, nickName, dom_sub, prefs, addit_adult', 'safe', 'on'=>'detailed' ), array( 'orientation, birthPlace, birthday, height, weight, clothing, makeup, addit_appearance, eye_c, eye_s, hair_c, hair_l, hair_s, history, likes, dislikes, addit_desc, relationships, dom_sub, prefs, addit_adult, spirit_status, spirit_condition, spirit_alignment, spirit_sub_alignment, spirit_type, spirit_death_date, spirit_death_cause, spirit_death_place', 'safe', 'on'=>'advanced' ), array('spirit_death_date,birthday','date','on'=>'detailed,advanced'), array('scenario,cpic,nickName','safe'), //array('family, partners, pets, slaves, master, forms, clan',) <- will be edited.... ); } public function search() { $criteria = new CDbCriteria; $criteria->compare('uID', $this->uID); $criteria->compare('name', $this->name, true); $criteria->compare('species', $this->species, true); $criteria->compare('sex', $this->sex, true); $criteria->compare('orientation', $this->orientation, true); $criteria->compare('position', $this->position, true); /* * ------now the data provider--------- */ return new CActiveDataProvider($this, array( 'criteria' => $criteria, 'pagination' => array( 'pageSize' => 20, ), 'sort'=>array( 'defaultOrder'=>'cID DESC', ), )); } // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{charabase}}'; } public function primaryKey() { return 'cID'; } # public function afterFind() { if(!empty($this->cpic)) { $this->cpic = unserialize($this->cpic); } parent::afterFind(); } public function attributeLabels() { return include(Yii::getPathOfAlias("charaBase.messages.".Yii::app()->language)."/cb.php"); } } ?><file_sep>/protected/modules/mall/views/patch.php #!/usr/local/bin/php $str = file_get_contents("loggedIn.php"); $res = str_replace('"chat"','"mall"',$str); file_put_contents($res,"new-loggedIn.php"); <file_sep>/protected/modules/charaBase/components/CBTranslator.php <?php class CBTranslator { public static function category($c) { switch($c) { case 0: return Yii::t('CharaBaseModule.cb',"pic-only"); break; case 1: return Yii::t('CharaBaseModule.cb',"eng"); break; case 2: return Yii::t('CharaBaseModule.cb',"ger"); break; } } public static function position($p) { switch($p) { case 1: return Yii::t('CharaBaseModule.cb',"main"); break; case 0: return Yii::t('CharaBaseModule.cb',"casual"); break; } } public static function scenario($s) { switch($s) { case 0: return Yii::t('CharaBaseModule.cb',"pic-only"); break; case 1: return Yii::t('CharaBaseModule.cb',"simple"); break; case 2: return Yii::t('CharaBaseModule.cb',"detailed"); break; case 3: return Yii::t('CharaBaseModule.cb',"advanced"); break; } } public static function sex($s) { switch($s) { case 0: return Yii::t('CharaBaseModule.cb',"male"); break; case 1: return Yii::t('CharaBaseModule.cb',"female"); break; case 2: return Yii::t('CharaBaseModule.cb',"herm"); break; case 3: return Yii::t('CharaBaseModule.cb',"maleherm"); break; case 4: return Yii::t('CharaBaseModule.cb',"cuntboi"); break; case 5: return Yii::t('CharaBaseModule.cb',"shemale"); break; case 6: return Yii::t('CharaBaseModule.cb',"shifter"); break; case 7: return Yii::t('CharaBaseModule.cb',"genderless"); break; } } public static function orientation($o) { switch($o) { case 0: return Yii::t('CharaBaseModule.cb',"straight"); break; case 1: return Yii::t('CharaBaseModule.cb',"bi"); break; case 2: return Yii::t('CharaBaseModule.cb',"lesbian"); break; case 3: return Yii::t('CharaBaseModule.cb',"gay"); break; case 4: return Yii::t('CharaBaseModule.cb',"pansexual"); break; case 5: return Yii::t('CharaBaseModule.cb',"omnisexual"); break; case 6: return Yii::t('CharaBaseModule.cb',"noGo"); break; case 7: return Yii::t('CharaBaseModule.cb',"asexual"); break; default: return null; break; } } public static function orientations() { return array( Yii::t('CharaBaseModule.cb',"straight"), Yii::t('CharaBaseModule.cb',"bi"), Yii::t('CharaBaseModule.cb',"lesbian"), Yii::t('CharaBaseModule.cb',"gay"), Yii::t('CharaBaseModule.cb',"pansexual"), Yii::t('CharaBaseModule.cb',"omnisexual"), Yii::t('CharaBaseModule.cb',"noGo"), Yii::t('CharaBaseModule.cb',"asexual") ); } public static function spirit_type($s) { switch($s) { case 0: return Yii::t('CharaBaseModule.cb',"spirit_t_lightful"); break; case 1: return Yii::t('CharaBaseModule.cb',"spirit_t_darkness"); break; } } public static function spirit_status($s) { switch($s) { case 0: return Yii::t('CharaBaseModule.cb',"spirit_s_alive"); break; case 1: return Yii::t('CharaBaseModule.cb',"spirit_s_dead"); break; } } public static function spirit_condition($c) { switch($c) { case 0: return Yii::t('CharaBaseModule.cb',"spirit_c_healthyHappy"); break; case 1: return Yii::t('CharaBaseModule.cb',"spirit_c_healthySick"); break; case 2: return Yii::t('CharaBaseModule.cb',"spirit_c_depressed"); break; case 3: return Yii::t('CharaBaseModule.cb',"spirit_c_sad"); break; case 4: return Yii::t('CharaBaseModule.cb',"spirit_c_alone"); break; case 5: return Yii::t('CharaBaseModule.cb',"spirit_c_raging"); break; case 6: return Yii::t('CharaBaseModule.cb',"spirit_c_mixed"); break; } } public static function spirit_alignment($s) { switch($s) { case 0: return Yii::t('CharaBaseModule.cb',"spirit_a_good"); break; case 1: return Yii::t('CharaBaseModule.cb',"spirit_a_neutral"); break; case 2: return Yii::t('CharaBaseModule.cb',"spirit_a_bad"); break; } } public static function spirit_sub_alignment($sa) { switch($sa) { case 0: return Yii::t('CharaBaseModule.cb',"spirit_sa_lawful"); break; case 1: return Yii::t('CharaBaseModule.cb',"spirit_sa_middle"); break; case 2: return Yii::t('CharaBaseModule.cb',"spirit_sa_chaotic"); break; } } public static function ds($a) { switch($a) { case 0: return Yii::t('CharaBaseModule.cb',"dom"); break; case 1: return Yii::t('CharaBaseModule.cb',"sub"); break; } } } ?><file_sep>/protected/modules/forum/views/post/form.php <h1><?=Yii::t("forumModule.main","answerTo")?>: <?=$topic->name?></h1> <br> <fieldset> <?php /** @var BootActiveForm $form */ $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'horizontalForm', 'type'=>'horizontal', )); ?> <?php echo $form->textAreaRow($post,"answer",array("class"=>"entryArea",'hint'=>Yii::t("forumModule.main","hint"))); ?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=>'Submit')); ?> </div> <?php $this->endWidget(); ?> </fieldset><file_sep>/protected/messages/de/site.php <?php return array( // Menü 'chars'=>'Charaktere', 'ath'=>'Über das Hotel', 'contact'=>'Kentakt', 'donate'=>'Spenden!', 'manage'=>"Verwalte Dragon's Inn", 'settings'=>'Einstellungen', 'u'=>'Du', 'lang'=>'Sprache', 'cbCreate'=>'Erstellen', 'cbList'=>'Liste', 'cbManage'=>'Verwalten', 'cbExport'=>'Exportieren', 'cbImport'=>'Importieren', 'mChat'=>'Chat', 'mBlog'=>'Blog', 'mThemes'=>'Themes', // Genetische Worte 'play'=>'Spielen', 'cselect'=>'Charakter wählen', 'profil'=>"Profil", 'edit'=>'Bearbeiten', 'create'=>'Erstellen', 'delete'=>'Löschen', 'ban'=>'Bannen', 'ipban'=>'IP-Bann', 'issue'=>'Problem', 'menu'=>'Menü', 'me'=>'Ich', 'login'=>'Login', 'logout'=>'Logout', 'notifications'=>'Anzeige', 'messages'=>'Nachrichten' ); ?><file_sep>/protected/messages/de/app.php <?php return array( // German by <NAME> "abc"=>"Einheit", ); ?><file_sep>/protected/modules/notifyii/views/notifyiiReads/update.php <?php /* @var $this NotifyiiReadsController */ /* @var $model NotifyiiReads */ $this->breadcrumbs=array( 'Notifyii Reads'=>array('index'), $model->id=>array('view','id'=>$model->id), 'Update', ); $this->menu=array( array('label'=>'List NotifyiiReads', 'url'=>array('index')), array('label'=>'Create NotifyiiReads', 'url'=>array('create')), array('label'=>'View NotifyiiReads', 'url'=>array('view', 'id'=>$model->id)), array('label'=>'Manage NotifyiiReads', 'url'=>array('admin')), ); ?> <h1>Update NotifyiiReads <?php echo $model->id; ?></h1> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep>/protected/modules/charaBase/views/maintain/delete.php <?php $this->layout='//layouts/column1'; ?> <div class="warning"> <h2><?=$model->name?></h2><br> You really want to delete this character?<br> You can return with the link below.<br><br> <?=CHtml::link("No, keep the character.",Yii::app()->request->urlReferrer)?> <br> <?=CHtml::link("Yes, delete.",array("/charaBase/maintain/delete","ID"=>$model->cID,"delete"=>1))?> </div><file_sep>/protected/modules/mall/models/YiiUser.php <?php class YiiUser extends CActiveRecord { /** * The followings are the available columns in table 'users': * @var integer $id * @var string $username * @var string $password * @var string $email * @var string $activkey * @var integer $createtime * @var integer $lastvisit * @var integer $superuser * @var integer $status * @var timestamp $create_at * @var timestamp $lastvisit_at **/ public $id; public $user; public $superuser; public $role; public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return Yii::app()->getModule('user')->tableUsers; #return '{{users}}'; } }<file_sep>/protected/modules/mall/controllers/ShoutboxController.php <?php class ShoutboxController extends Controller { public function actionIndex() { $path=Yii::getPathOfAlias("chat")."/"; define("AJAX_CHAT_PATH",$path); $url = "/chat/run/"; define("AJAX_CHAT_URL",$url); if (is_file(AJAX_CHAT_PATH . 'lib/classes.php')) { include(AJAX_CHAT_PATH.'lib/classes.php'); $ajaxChat = new CustomAJAXChatShoutBox; echo $ajaxChat->getShoutBoxContent(); } } } ?><file_sep>/protected/migrations/m121006_184459_TabellaNotifiche.php <?php class m121006_184459_TabellaNotifiche extends CDbMigration { public function up() { $this->createTable('notifyii', array( 'id' => 'pk', 'expire' => 'date', )); } public function down() { echo "m121006_184459_TabellaNotifiche does not support migration down.\n"; return false; } }<file_sep>/protected/modules/mall/lib/custom.php <?php /* * @package AJAX_Chat * @author <NAME> * @copyright (c) <NAME> * @license GNU Affero General Public License * @link https://blueimp.net/ajax/ */ if(!isset(Yii::app()->user->id)) throw new CException("Not logged in!"); ?><file_sep>/protected/modules/mall/views/view/index.php <h1><?=$channel->name?></h1> <?php if(!empty($channel->desc)) { echo $channel->desc; } else { echo Yii::t("chatModule.main","noDesc"); } ?><file_sep>/protected/modules/forum/views/view/_ct.php <?php /*_ct*/ $topic = ForumTopics::model()->find(array("condition"=>"boardID=:x","order"=>"id DESC","params"=>array(":x"=>$data->id))); if(!empty($topic)) $post = ForumPosts::model()->find(array("condition"=>"topicID=:x","order"=>"id DESC","params"=>array(":x"=>$topic->id))); ?> <tr class="<?=$row?>"> <td class=td_name> <span class="board_name"><?=CHtml::link($data->name,array("view/board","id"=>$data->id))?></span> <br><?=$data->desc?> </td> <td class=td_details> <?php if(!empty($topic)) { ?> Last topic: <span class="board_topic"><?=CHtml::link($topic->name,array("view/topic",'id'=>$topic->id))?></span> <br>By: <span class="board_user"><?=CHtml::link(Yii::app()->getModule("user")->user($post->writerID)->username, array("/user/user/view",'id'=>$post->writerID))?></span> <?php } ?> </td> <?php if(Yii::app()->user->role==2) { ?> <td class=td_actions> <span class="board_admin"><?=CHtml::link("Edit",array("board/edit", "id"=>$data->id))?>, <?=CHtml::link("Delete",array("board/delete", "id"=>$data->id),array("onclick"=>"confirm('Are you sure you want to delete this?')"))?> </span> </td> <?php } ?> </tr><file_sep>/protected/modules/charaBase/controllers/CpicController.php <?php // Debug ini_set('display_errors', 1); error_reporting(E_ALL); class cpicController extends Controller { private $data=null; private $fullPath; private $id; private $realPath; public function beforeAction($a) { if(!isset(Yii::app()->session['cpicID'])) Yii::app()->session['cpicID'] = uniqid(); $this->data = Yii::app()->session['cpic']; $this->id = Yii::app()->session['cpicID']; $this->fullPath = Yii::getPathOfAlias("webroot.protected.modules.charaBase.cpic")."/tmp/".$this->id."/"; $this->realPath = Yii::getPathOfAlias("webroot.protected.modules.charaBase.cpic"); @mkdir($this->fullPath,0777,true); return true; } public function actionList() { $this->outcome(); } public function actionView($pid,$ID=null) { $Cpic = CharacterPicture::model()->findByPk($pid); $path = Yii::getPathOfAlias("charaBase.cpic"); $tmpFile = $path."/tmp/".$this->id."/".$Cpic->name; if(!empty($ID)) $realFile = $path."/".$ID."/".$Cpic->name; else $realFile=null; #echo $realFile; if(file_exists($tmpFile)) { $this->display($tmpFile); } else if(file_exists($realFile)) { $this->display($realFile); } else $this->reject("404, File not found."); } private function display($file){ header("Content-type: ".mime_content_type($file)); readfile($file); } public function actionSave() { $cpic = $_FILES['cpic']; if($cpic['error'] == 0) { if(move_uploaded_file($cpic['tmp_name'],$this->fullPath.$cpic['name'])) { # $Cpic = CharacterPicture::model()->find("name='".$cpic['name']."'"); # if(is_null($Cpic)) { unset($Cpic); $Cpic = new CharacterPicture; $Cpic->name=$cpic['name']; $Cpic->url=urlencode($cpic['name']); $Cpic->save(); $this->data[]=$Cpic->id; $this->dump(); $this->outcome(); # } else $this->reject("File exists!"); } else $this->reject("Could not save file."); } else $this->reject("Upload failed with errorcode: ".$cpic['error']); } public function actionSess() { var_dump(Yii::app()->session['cpic_old']); var_dump(Yii::app()->session['cpic']); var_dump($this->data); } public function actionDelete($pid,$ID=null) { $Cpic = CharacterPicture::model()->findByPk($pid); if(!is_null($Cpic)) { if(!is_null($ID)) { @unlink( Yii::getPathOfAlias("charaBase.cpic.".$ID)."/".$Cpic->name ); } else { @unlink( Yii::getPathOfAlias("charaBase.cpic.tmp")."/".$this->id."/".$Cpic->name ); } $Cpic->delete(); } #else $this->reject("File not exist."); $found = false; foreach($this->data as $key=>$nr) { if($nr==$pid) { unset($this->data[$key]); $this->dump(); $this->say("Complete!"); $found = true; break; } } if(!$found) $this->reject("Unable!"); } public function actionDesc() { if(isset($_POST['input'])) { $Cpic = CharacterPicture::model()->findByPk($_POST['pid']); $Cpic->desc = $_POST['input']; if($Cpic->isNewRecord) $Cpic->save(); else $Cpic->update(); $this->outcome(); } else $this->reject("No input given."); } private function dump() { Yii::app()->session['cpic'] = $this->data; } private function say($msg) { echo json_encode(array('error'=>false,'msg'=>$msg)); } private function reject($msg) { echo json_encode(array('error'=>TRUE,'msg'=>$msg)); } private function outcome() { echo json_encode($this->data); } } ?> <file_sep>/protected/modules/forum/messages/en/main.php <?php return array( 'name'=>'Name', 'desc'=>'Description', 'answer'=>'Answer', 'answerTo'=>'Answer to', 'hint'=>'Use the markdown syntax to style your post.<br> It can be found <a target="_blank" href="http://daringfireball.net/projects/markdown/syntax">HERE</a> and <a target="_blank" href="http://michelf.ca/projects/php-markdown/extra/">HERE</a>. You also can use HTML.', 'createdAt'=>'Created at', 'editedAt'=>'Edited at', 'Cedit'=>'Edit category', 'Ccreate'=>'Create new category', 'Cdelete'=>'Delete category', 'Bedit'=>'Edit board', 'Bcreate'=>'Create new board', 'Bdelete'=>'Delete board', 'Tedit'=>'Edit topic', 'Tcreate'=>'Create new topic', 'Tdelete'=>'Delete topic', 'Tanswer'=>'Answer to this topic', 'firstPost'=>'First post for topic', 'Pedit'=>'Edit post', 'Pdelete'=>'Delete post' ); ?><file_sep>/protected/migrations/m121011_034506_ReadedNotificationTable.php <?php class m121011_034506_ReadedNotificationTable extends CDbMigration { public function up() { $this->createTable('notifyii_reads', array( 'id' => 'pk', 'username' => 'string', 'notification_id' => 'integer', 'readed' => 'boolean', )); } public function down() { echo "m121011_034506_ReadedNotificationTable does not support migration down.\n"; return false; } }<file_sep>/protected/modules/mall/models/AJAXChatMessages.php <?php class AJAXChatMessages extends CActiveRecord { // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return 'ajax_chat_messages'; } public function primaryKey() { return 'id'; } public $id; public $userID; public $userName; public $userRole; public $channel; public $dateTime; public $ip; public $text; private $ac; public function init() { parent::init(); $base = Yii::getPathOfAlias("application.modules.chat.lib"); include($base."/config.php"); $this->ac=(object)$config; } public function chatbot($msg) { $this->userID=$this->ac->chatBotID; $this->userName="Server"; $this->userRole=AJAX_CHAT_CHATBOT; $this->channel=$this->ac->defaultChannelID; $this->dateTime=date("Y-m-d H:m:s"); $this->ip=$this->ip_encode($_SERVER['SERVER_ADDR']); $this->text=$msg; if($this->save()) return $this->id; else return false; } public function ip_decode($ip) { if(function_exists('inet_pton')) { // ipv4 & ipv6: return @inet_pton($ip); } // Only ipv4: return @pack('N',@ip2long($ip)); } public function ip_encode($ip) { if(function_exists('inet_ntop')) { // ipv4 & ipv6: return @inet_ntop($ip); } // Only ipv4: $unpacked = @unpack('Nlong',$ip); if(isset($unpacked['long'])) { return @long2ip($unpacked['long']); } return null; } } ?> <file_sep>/protected/modules/charaBase/views/transfer/importError.php <?php // importError echo CHtml::errorSummary($model); ?><file_sep>/protected/views/manage/index.php <h2>Admins area</h2> <?=Yii::t("admin","mHead")?> <ul> <dt><?=CHtml::link('Chat',array("chat"))?></dt> <dd><?=Yii::t("admin","mChat")?></dd> <dt><?=CHtml::link('Themes',array("themes"))?></dt> <dd><?=Yii::t("admin","mThemes")?></dd> <dt><?=CHtml::link('Blog',array("blog"))?></dt> <dd><?=Yii::t("admin","mBlog")?></dd> </ul><file_sep>/protected/modules/mall/models/AJAXChatOnline.php <?php class AJAXChatOnline extends CActiveRecord { // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return 'ajax_chat_online'; } public $userID; public $userName; public $userRole; public $channel; public $dateTime; public $ip; } ?> <file_sep>/protected/modules/mall/controllers/RunController.php <?php // Debug ini_set('display_errors', 1); error_reporting(E_ALL); class RunController extends Controller { // access control public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('index'), 'users'=>array('@'), ), array('deny', 'actions'=>array('index'), 'users'=>array('*'), ), ); } // load the chat into Yii. public function actionIndex() { // Show all errors: error_reporting(E_ALL); // Path to the chat directory: define('AJAX_CHAT_PATH', Yii::getPathOfAlias("mall")."/"); define('AJAX_CHAT_WEB', $this->module->assetsUrl); // Include custom libraries and initialization code: require(AJAX_CHAT_PATH.'lib/custom.php'); // Include Class libraries: require(AJAX_CHAT_PATH.'lib/classes.php'); // Initialize the chat: $ajaxChat = new CustomAJAXChat(); } } <file_sep>/protected/modules/forum/models/ForumCategories.php <?php class ForumCategories extends CActiveRecord { public $id; public $name; public $desc; public $boards; // @array-serialized num(topicID=>assoc(name,views,...) // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{Fcategories}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('name','required'), array('desc','safe') ); } public function attributeLabels() { return array( 'name'=>Yii::t("forumModule.main","name"), 'desc'=>Yii::t('forumModule.main',"desc") ); } } ?><file_sep>/protected/modules/notifyii/views/modelNotifyii/create.php <?php /* @var $this NotifyiiController */ /* @var $model Notifyii */ $this->breadcrumbs=array( 'Notifyii'=>array('index'), 'Create', ); $this->menu=array( array('label'=>'List Notifyii', 'url'=>array('index')), array('label'=>'Manage Notifyii', 'url'=>array('admin')), ); ?> <h1>Create Notifyii</h1> <div class="box"> <h3>In this page you can create your notitication.</h3> </div> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?> <file_sep>/protected/modules/forum/controllers/ViewController.php <?php class ViewController extends Controller { public function actionIndex() { #$model = ForumTopics::model()->findAll(); $dp = ForumCategories::model()->findAll(); $this->render('index',array('categories'=>$dp)); } public function actionTopic($id) { $topic = ForumTopics::model()->findByPk($id); $posts = ForumPosts::model()->findAll("topicID=".$id); $this->render('topicView',array('topic'=>$topic,'posts'=>$posts)); } public function actionBoard($id) { $dp = ForumTopics::model()->findAll(array('condition'=>"boardID=:x", 'order'=>'sticky DESC, id DESC', 'params'=>array(":x"=>$id))); #print_r($dp);die(); $b=ForumBoards::model()->findByPk($id); $this->render("boardView",array("topics"=>$dp,"b"=>$b)); } }<file_sep>/protected/modules/forum/controllers/CategoryController.php <?php class CategoryController extends Controller { public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('create','edit','delete'), 'users'=>array('@'), ), array('deny', 'actions'=>array("create",'edit','delete'), 'users'=>array('*'), ), ); } public function actionCreate() { $category = new ForumCategories; if(!isset($_POST['ForumCategories'])) { $this->render("form",array("category"=>$category)); } else { $category->attributes=$_POST['ForumCategories']; if($category->save()) { $this->redirect(array("view/index")); } else { $this->render("form",array("category"=>$category)); } } } public function actionEdit($id) { $category = ForumCategories::model()->findByPk($id); if(!isset($_POST['ForumCategories'])) { $this->render("form",array("category"=>$category)); } else { $category->attributes=$_POST['ForumCategories']; if($category->save()) { $this->redirect(array("view/category","id"=>$category->id)); } else { $this->render("form",array("category"=>$category)); } } } public function actionDelete($id) { $category = ForumCategories::model()->findByPk($id); $bIDs = unserialize($category->boards); foreach($bIDs as $bID) { $board = ForumBoards::model()->findByPk($bID); $topics = ForumTopics::model()->findAll("boardID=".$board->id); foreach($topics as $t) { $posts = ForumPosts::model()->findAll("topicID=".$t->id); foreach($posts as $p) { $p->delete(); } $t->delete(); } $board->delete(); } if($category != null) { $category->delete(); $this->redirect("/forum/view/index"); } else throw new CException("Could not delete."); } } ?><file_sep>/protected/views/upload/uploaded.php <center> <h3>Upload complete.</h1> <p> <?php $url = "http://".$_SERVER['SERVER_NAME']."/u/".$newName; ?> URL: <a href="<?=$url?>"><?=$url?></a> </p> </center><file_sep>/protected/modules/forum/views/board/form.php <?php if(isset($board->id)) { ?> <h1>Edit board</h1> <?php } else { ?> <h1>Create board</h1> <?php } ?> <br> <fieldset> <?php /** @var BootActiveForm $form */ $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'horizontalForm', 'type'=>'horizontal', )); ?> <?php echo $form->textFieldRow($board,"name",array("class"=>"entryField")); ?> <?php echo $form->textAreaRow($board,"desc",array("class"=>"entryArea")); ?> <div class="form-actions"> <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=>'Submit')); ?> </div> <?php $this->endWidget(); ?> </fieldset><file_sep>/protected/modules/user/messages/en/user.php <?php return array( 'You account is active.' => 'Your account is active.', 'You account is activated.' => 'Your account is activated.', ); ?><file_sep>/protected/modules/forum/views/view/boardView.php <?php /*boardView*/ $row = "even"; echo "<h2>$b->name</h2>"; echo "<p>$b->desc</p>"; echo "<p>"; echo CHtml::link("Create new topic",array("topic/create",'bid'=>$b->id)); echo "</p>"; echo "<table>"; echo "<thead><tr class=\"".$row."\">"; echo "<th>Name / Description</th>"; echo "<th> Created / Last posted </th>"; echo "</tr></thead>"; echo "<tbody>"; foreach($topics as $t){ $post = ForumPosts::model()->find(array("condition"=>"topicID=:x","order"=>"id DESC",'params'=>array(":x"=>$t->id))); $name = Yii::app()->getModule("user")->user($post->writerID)->username; $id = $post->writerID; $userLink = CHtml::link($name,array("/user/user/view","id"=>$id)); switch($row) { case 'odd':$row="even"; break; case 'even':$row="odd"; break; } if($t->sticky) { ?> <tr class="<?=$row?> sticky"> <?php } else { ?> <tr class="<?=$row?>"> <?php } ?> <td> <?=CHtml::link($t->name,array("view/topic","id"=>$t->id))?> <br><?=$t->desc?></td> <td><?=$userLink?> @ <?=(isset($post->editedAt) ? $post->editedAt : $post->createdAt)?></td> </tr> <?php } echo "</tbody>"; echo "</table>";<file_sep>/protected/migrations/m121010_123408_AddRolesToNotification.php <?php class m121010_123408_AddRolesToNotification extends CDbMigration { public function up() { $this->addColumn('notifyii', 'role', 'string'); } public function down() { echo "m121010_123408_AddRolesToNotification does not support migration down.\n"; return false; } }<file_sep>/protected/modules/forum/controllers/PostController.php <?php class PostController extends Controller { public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('answer','edit','delete'), 'users'=>array('@'), ), array('deny', 'actions'=>array("answer",'edit','delete'), 'users'=>array('*'), ), ); } public function actionAnswer($tid) { $post = new ForumPosts; $topic = ForumTopics::model()->findByPk($tid); if(!isset($_POST['ForumPosts'])) { $this->render("form",array("post"=>$post, 'topic'=>$topic)); } else { $form = $_POST['ForumPosts']; $post->answer=$form['answer']; $post->writerID=Yii::app()->user->id; $post->topicID=$tid; $post->createdAt=time(); if($post->save()) { $this->redirect(array("/forum/view/topic",'id'=>$tid)); } else { $this->render("form",array("post"=>$post, 'topic'=>$topic)); } } } public function actionEdit($id) { $post = ForumPosts::model()->findByPk($id); $topic = ForumTopics::model()->findByPk($post->topicID); if(!isset($_POST['ForumPosts'])) { $this->render("form",array("post"=>$post,'topic'=>$topic)); } else { $form = $_POST['ForumPosts']; $post->answer=$form['answer']; $post->editedAt=time(); $post->attributes=$_POST['ForumPosts']; if($post->update()) { $this->redirect(array("view/topic","id"=>$post->topicID)); } else { $this->render("form",array("post"=>$post,'topic'=>$topic)); } } } public function actionDelete($id,$tid) { $category = ForumPosts::model()->findByPk($id); if($post != null) { $post->delete(); $this->redirect("/forum/view/topic",array('id'=>$tid)); } else throw new CException("Could not delete."); } } ?><file_sep>/themes/drag0n/js/themePicker.js.php <?php header("Content-type: text/javascript"); $for = $_GET['for']; ?> jQuery(function($){ $("#themePicker").change(function(){pickTheme( $('#themePicker').val() ); } ); $("#logoutChannelContainer #themePicker").change(function(){pickTheme( $('#logoutChannelContainer #themePicker').val() ); } ); $("#themePicker, #logoutChannelContainer #themePicker").append( $('<option/>').val("X").html("Select...") ); $.getJSON("/themepicker/get", function(jsonData){ $.each(jsonData, function(i,j){ $("#themePicker, #logoutChannelContainer #themePicker").append( $('<option/>').val(i).html(j) ); }); }); $.get("/themepicker/default",function(d){ $("#themePicker, #logoutChannelContainer #themePicker").val(d); }); }); function pickTheme(val){ $.ajax({ url: "/themepicker/set", type: "GET", data: {id:val,for:"<?=$for?>"}, success: function(string) { console.log(string); extLoader(string,"css"); //location.reload(); } }); }<file_sep>/protected/modules/notifyii/views/notifyiiReads/_view.php <?php /* @var $this NotifyiiReadsController */ /* @var $data NotifyiiReads */ ?> <div class="view"> <strong><?php echo $data->username; ?></strong> has read notification <strong><?php echo $data->notification->content; ?></strong> that expire at <strong><?php echo $data->notification->expire; ?></strong>. </div> <file_sep>/protected/modules/notifyii/views/modelNotifyii/view.php <?php /* @var $this NotifyiiController */ /* @var $model Notifyii */ $this->breadcrumbs=array( 'Notifyiis'=>array('index'), $model->content, ); $this->menu=array( array('label'=>'List Notifyii', 'url'=>array('index')), array('label'=>'Create Notifyii', 'url'=>array('create')), array('label'=>'Update Notifyii', 'url'=>array('update', 'id'=>$model->id)), array('label'=>'Delete Notifyii', 'url'=>'#', 'linkOptions'=>array('submit'=>array('delete','id'=>$model->id),'confirm'=>'Are you sure you want to delete this item?')), array('label'=>'Manage Notifyii', 'url'=>array('admin')), ); ?> <h1>Notification: <strong><?php echo $model->content; ?></strong></h1> <div class="box"> <h3>In this page you can see a detail of a notification.</h3> </div> <?php $this->widget('zii.widgets.CDetailView', array( 'data'=>$model, 'attributes'=>array( 'expire', 'alert_after_date', 'alert_before_date', 'role', ), )); ?> <div class="clear">&nbsp;</div> <hr /> <div class="box"> <h3>Readers</h3> <?php $readers = NotifyiiReads::model()->findAll(new CDbCriteria(array( 'condition' => 'notification_id=:notification_id', 'params' => array( 'notification_id' => $model->id ) ))); ?> <?php if(count($readers) === 0) : ?> <em>No readers</em> <?php else: ?> <?php foreach($readers as $reader) : ?> <?php echo $reader->username; ?> <?php endforeach; ?> <?php endif; ?> </div> <file_sep>/protected/modules/notifyii/README.md Notifyii ======== If you want to use notifyii with roles, extensions like "rights" or RBAC are required. Be shure to have the same 'db' configuratiion in these files: protected/config/main.php protected/config/console.php To install notifyii, navigate to the forlder "protected/modules" of your project. If your project does not have any "modules" folder, just create id. Then, run the command: $ git clone <EMAIL>:sensorario/notifyii Now you just need to add module to confi file: 'modules'=>array( 'notifyii', ), And try to load these routes: index.php?r=notifyii index.php?r=notifyii/modelNotifyii index.php?r=notifyii/notifyiiReads The first one show you a sample page that create a sample notification. The second one show you a crud to alter notifications. If you want you can add these items to views/layouts/main.php file: array('label'=>'Notifyii', 'url'=>array('/notifyii')), array('label'=>'ModelNotifyii', 'url'=>array('/notifyii/modelNotifyii')), array('label'=>'NotifyiiReads', 'url'=>array('/notifyii/notifyiiReads')), Run migrations -------------- /var/www/YOUR_APP_NAME/protected$ ./yiic migrate --migrationPath=webroot.modules.notifyii.migrations Notify the end of the world --------------------------- $notifyii = new Notifyii(); $notifyii->message('The end of the world'); $notifyii->expire(new DateTime("21-12-2012")); $notifyii->from("-1 week"); $notifyii->to("+1 day"); $notifyii->role("admin"); $notifyii->link($this->createUrl('/site/index')); $notifyii->save(); Get all notifications --------------------- ModelNotifyii::getAllNotifications() ModelNotifyii::getAllRoledNotifications() Usage ----- Suppose to load all notifications in your controller: public function actionIndex() { $this->render('index', array( 'notifiche' => ModelNotifyii::getAllNotifications() )); } In the view, you can load all notifications <?php foreach ($notifiche as $notifica) : ?> <?php if ($notifica->isNotReaded()) : ?> <div class="box"> <a href="<?php echo $notifica->link; ?>"><?php echo $notifica->expire; ?></a> - <a href="<?php echo $notifica->link; ?>"><?php echo $notifica->content; ?></a> <br /> <a href="<?php echo $this->createUrl('/notifyii/default/read', array('id' => $notifica->id)); ?>">segna questa notifica come letta</a> </div> <?php endif; ?> <?php endforeach; ?><file_sep>/protected/modules/forum/views/view/index.php <?php /* @array $categories ForumCategories @array $boards ForumBoards @array $topics ForumTopics */ ?> <link rel="stylesheet" type="text/css" href="<?php echo Yii::app()->getModule("forum")->assetsUrl; ?>/css/forum.css" media="screen" /> <?php $row = "even"; echo "<h1 class=\"forum_h1\">Viatropolis Forum Support</h1>"; if(Yii::app()->user->role==2) { echo "<h4 class=\"forum_h4\">"; echo CHtml::link("Create category",array("category/create")); echo "</h4>"; } echo "<br>"; foreach($categories as $c) { echo '<h2 class="categoryHeader">'.$c->name.'</h2>'; echo "<h4>$c->desc</h4>"; if(Yii::app()->user->isMod) { echo '<h5 class=\"forum_h5\">'; echo CHtml::link("Edit this category",array("category/edit",'id'=>$c->id)); echo " | "; echo CHtml::link("Delete this category",array("category/delete",'id'=>$c->id),array("onclick"=>"confirm('Sure to delete this?')")); if(Yii::app()->user->isAdmin) { echo " | "; echo CHtml::link("Create new board",array("board/create",'id'=>$c->id)); } echo "</h5>"; } $c->boards = unserialize($c->boards); if(!empty($c->boards)) { echo "<table class=\"main_table\">"; echo "<thead><tr class=\"".$row."\">"; echo "<th class=\"desc\">Name / Description</th>"; echo "<th class=\"detail\">Details</th>"; if(Yii::app()->user->role==2) { echo "<th class=\"actions\">Actions</th>"; } echo "</tr></thead>"; echo "<tbody>"; foreach($c->boards as $bid) { switch($row) { case 'odd':$row="even"; break; case 'even':$row="odd"; break; } $board = new CActiveDataProvider('ForumBoards',array( 'criteria'=>array( 'condition'=>'`id`='.$bid ), )); $this->widget("zii.widgets.CListView",array( 'dataProvider'=>$board, 'summaryText'=>" ", #'viewData'=>array( 'topics'=>$topics ), 'viewData'=>array("row"=>$row), 'itemView'=>"_ct" )); } echo "</tbody>"; echo "</table>"; } else { echo "<i>No boards are available for this category.</i>"; } } $numCat = ForumCategories::model()->count(); $numPost = ForumPosts::model()->count(); $numTop = ForumTopics::model()->count(); $numBoard=ForumBoards::model()->count(); ?> <br><br><center> Categories: <?=$numCat?> | Boards: <?=$numBoard?> | Topics: <?=$numTop?> | Posts: <?=$numPost?> </center><file_sep>/protected/controllers/ViatropolisController.php <?php class ViatropolisController extends Controller { public function init() { parent::init(); DN::MakeBootstrap(); } public function actionIndex() { $blog = new CActiveDataProvider("Blog",array( 'criteria'=>array( 'order'=>'id DESC' ), 'pagination'=>array( 'pageSize'=>10 ) )); $chars = new CActiveDataProvider("Character",array( 'criteria'=>array( 'order'=>'cID DESC', 'offset'=>0, 'limit'=>30, ), )); $this->render("/Viatropolis/"."all",array( "blog"=>$blog, 'chars'=>$chars )); } public function actionView($id) { $blog = new CActiveDataProvider("Blog",array( 'criteria'=>array( 'condition'=>'id='.$id ), 'pagination'=>array( 'pageSize'=>10 ) )); $chars = new CActiveDataProvider("Character",array( 'criteria'=>array( 'order'=>'cID DESC', 'offset'=>0, 'limit'=>20, ), )); $this->render("/Viatropolis/"."all",array( "blog"=>$blog, 'chars'=>$chars )); } public function actionEdit($id) { $blog = Blog::model()->findByPk($id); if(!isset($_POST['Blog'])) { $this->render("/Viatropolis/"."form",array("blog"=>$blog)); } else { $blog->attributes=$_POST['Blog']; $blog->modified=time(); $topic = ForumTopics::model()->findByPk($blog->topicID); $topic->name =$_POST['Blog']['title']; $post = ForumPosts::model()->findByPk($blog->postID); $post->editedAt=date("d.m.Y H:i"); $post->answer=$_POST['Blog']['content']; if($blog->update() && $topic->update() && $post->update()) { $blog->postID=$post->id; $blog->topicID=$topic->id; if(!$blog->update()) die("cant update blogpost"); $this->redirect(array('/Viatropolis/view','id'=>$blog->id)); } else $this->render("/Viatropolis/"."form",array("blog"=>$blog)); } } public function actionCreate() { $blog = new Blog; if(!isset($_POST['Blog'])) { $this->render("/Viatropolis/"."form",array("blog"=>$blog)); } else { $blog->attributes=$_POST['Blog']; $blog->modified=time(); $blog->author = Yii::app()->user->id; $blog->hasTopic=true; $topic = new ForumTopics; $topic->boardID=1; $topic->name =$_POST['Blog']['title']; $topic->desc = null; $topic->creatorID = Yii::app()->user->id; if($blog->save() && $topic->save()) { $post = new ForumPosts; $post->topicID=$topic->id; $post->writerID=Yii::app()->user->id; $post->createdAt=date("d.m.Y H:i"); $post->answer=$_POST['Blog']['content']; $post->isBlog=true; $post->blogID=$blog->id; if($post->save()) { $blog->postID=$post->id; $blog->topicID=$topic->id; if(!$blog->update()) die("cant update blogpost"); $this->redirect(array('/Viatropolis/view','id'=>$blog->id)); } else die("Error saving post."); } else { $this->render("/Viatropolis/"."form",array("blog"=>$blog)); } } } public function actionDelete($id) { $blog = Blog::model()->findByPk($id); if($blog->delete()) { $this->redirect("/Viatropolis/index"); } else throw new CExeption("Could not delete post."); } public function actionError() { if($error=Yii::app()->errorHandler->error) { if(Yii::app()->request->isAjaxRequest) echo $error['message']; else $this->render("/Viatropolis/".'error', $error); } } public function actionInfo($p) { $this->render("/Viatropolis/".$p); } } ?><file_sep>/protected/modules/mall/assets/js/soundpicker.js // fillSoundSelection function soundPickInit(){ $.getJSON( "/mall/sound/all", function(data){ console.log("soundpacks:",data); ajaxChat.soundFiles = null; ajaxChat.soundFiles = new Object(); $.each(data, function(name,files) { $.each(files,function(pname,file) { ajaxChat.soundFiles[file]= "/"+name+"/"+file+".mp3"; }); console.log("sounds: ",ajaxChat.sounds); $("#soundPick").append( $("<option/>") .val(name) .html(name) ); }); } ); } jQuery(function(){ $("#soundPick").append( $("<option/>").val("x").html("Soundpack...") ); $("#soundPick").change(function(){ var pname = $("#soundPick").val(); $.ajax({ url:"/mail/sound/pack", dataType:"JSON", type:"GET", data:{pname:pname}, success:function(data){ console.log("soundpack: ",data); ajaxChat.setSetting('soundSend', data.send); ajaxChat.setSetting('soundRecive', data.recive); ajaxChat.setSetting('soundEnter', data.enter); ajaxChat.setSetting('soundLeave', data.leave); ajaxChat.setSetting('soundChatBot', data.chatbot); ajaxChat.setSetting('soundError', data.error); $.ajax({ url:"/mall/sound/save", type:"GET", data: {pname:pname}, success:function(d){console.log("Sound Pack saved",d);} }); } }); }); $.get( "/mall/sound/load", function(d){ $("#soundPick").val(d); } ); });<file_sep>/protected/controllers/LanguageController.php <?php class LanguageController extends Controller { public $langs = array("en"=>'English',"de"=>'Deutsch'); public function __construct(){ parent::__construct($this->id, $this->module); } public function actionGet() { echo json_encode($this->langs); } public function actionSet($lc) { Yii::app()->request->cookies['dragonsinn_chat_lang'] = new CHttpCookie('dragonsinn_chat_lang', $lc); } public function actionDefault($return=false) { if(!$return) { if(isset($_COOKIE['dragonsinn_chat_lang'])) echo $_COOKIE['dragonsinn_chat_lang']; else echo json_encode("en"); } else { if(isset($_COOKIE['dragonsinn_chat_lang'])) return $_COOKIE['dragonsinn_chat_lang']; else return "en"; } } } ?><file_sep>/protected/modules/notifyii/views/notifyiiReads/create.php <?php /* @var $this NotifyiiReadsController */ /* @var $model NotifyiiReads */ $this->breadcrumbs=array( 'Notifyii Reads'=>array('index'), 'Create', ); $this->menu=array( array('label'=>'List NotifyiiReads', 'url'=>array('index')), array('label'=>'Manage NotifyiiReads', 'url'=>array('admin')), ); ?> <h1>Create NotifyiiReads</h1> <?php echo $this->renderPartial('_form', array('model'=>$model)); ?><file_sep>/themes/drag0n/js/langPick.js jQuery(function(){ $.ajax({ url:'/language/get', dataType:"JSON", type:"GET", success:function(data){ $.each(data,function(i,v){ console.log("i:"+i+" v:"+v); $("#langPick").append( $("<option/>") .val(i) .html(v) ); }); } }); $.get( '/language/default', function(d){ $('#langPick').val(d); } ); $("#langPick").change(function(){ $.ajax({ url:'/language/set', data:{lc:$("#langPick").val()}, type:"GET", success:function(d){ location.reload(); } }); }); });<file_sep>/protected/messages/en/chatChannel.php <?php return array( 'name'=>'Channel name', 'orderID'=>'Ordering idendifyer', 'desc'=>'Channel description' ); ?><file_sep>/themes/drag0n/css/table.css.php <?php header("Content-Type: text/css"); ?> table {width:100%; margin-bottom: 30px;} thead a, thead a:hover, thead a:visited { background:black; color: #efefef; } tbody { border: 1; border-color: grey; color: white; } .odd { background: rgba(84,84,84, 0,7); } .even { background: rgba(0,0,0, 0.7); } .detail-view { background:black; } .grid-view .filters input, .grid-view .filters select { -moz-box-shadow: 0 0 0 0; -webkit-box-shadow: 0 0 0 0; box-shadow: 0 0 0 0; background: rgba(0,100,100,0.5); } .grid-view .filters input { width: 92%; }<file_sep>/protected/modules/charaBase/views/transfer/import.php <h1>Importing a character.</h1> <p> Here you will be able to import your characters from the previous version of BIRD.<br> Please take note of the following information: <ul> <li>Sex and orientation won't be transfered; but you will be able to set them when editing your character.</li> <li>Previous images wont be transfered. The old version stored images as plain HTML, which is not very well...</li> <li>The scenario will automatically be set to "Advanced" to display every field that'd be possible.</li> </ul> Happy importing! </p> <p> Please select the file that contains your characters, and click the checkbox if it is a file containing multiple characters, or a single character. </p> <?= CHtml::beginForm(array("transfer/import"),"post",array('enctype'=>'multipart/form-data')) ?> <div class="row"> Select file: <?= CHtml::fileField("cbFile") ?> </div> <div class="row"> Does this file contain multiple characters? <?= CHtml::checkBox("multi",false) ?> </div> <div class="row"> <?= CHtml::submitButton("Import") ?> </div> <?= CHtml::endForm() ?><file_sep>/protected/modules/forum/messages/de/main.php <?php return array( 'name'=>'Name', 'desc'=>'Beschreibung', 'answer'=>'Antwort', 'answerTo'=>'Antworten an', 'hint'=>'Benutze den Markdown-Syntax um deinen Post zu designen.<br> Diesen findest du <a target="_blank" href="http://daringfireball.net/projects/markdown/syntax">HIER</a> und <a target="_blank" href="http://michelf.ca/projects/php-markdown/extra/">HIER</a>. Du kannst auch HTML benutzen.', 'createdAt'=>'Erstellt am', 'editedAt'=>'Editiert am', 'Cedit'=>'Kategorie bearbeiten', 'Ccreate'=>'Erestelle neue Kategorie', 'Cdelete'=>'Lösche Kategorie', 'Bedit'=>'Bearbeite Board', 'Bcreate'=>'Erstelle neues Board', 'Bdelete'=>'Lösche Board', 'Tedit'=>'Bearbeite Thema', 'Tcreate'=>'Erstelle neues Thema', 'Tdelete'=>'Lösche dieses Thema', 'Tanswer'=>'Antworte zu diesem Thema', 'firstPost'=>'Erster Post für dieses Thema', 'Pedit'=>'Post bearbeiten', 'Pdelete'=>'Post löschen' ); ?><file_sep>/protected/modules/charaBase/controllers/TransferController.php <?php class TransferController extends Controller { // access control public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('import','export'), 'users'=>array('@'), ), array('deny', 'users'=>array('*'), ), ); } public function actionImport() { #extract($_FILES); extract($_POST); if(!isset($_FILES['cbFile']) && !isset($_POST['multi'])) { $this->render("import"); } else if(isset($_FILES['cbFile'])) { $data = unserialize(file_get_contents($_FILES['cbFile']['tmp_name'])); $Cdata = array(); $res = array(); if(!$_POST['multi']) { $Cdata[] = $data; } else { $Cdata = $data; } foreach($Cdata as $char) { $importer = new CharacterImporter(); if(empty($char['species'])) $char['species']="UNKNOWN"; $importer->attributes=$char; $importer->prepair(); if($importer->validate()) { $importer->save(); } else { echo "Error!! \n\n"; var_dump($importer->errors); die(); } if(isset($importer->id)) $res[]=$importer->id; else { die("\n\nNo ID was set."); } unset($importer); } foreach($res as $Pkey) { $impo = CharacterImporter::model()->findByPk($Pkey); $model = new Character("advanced"); $model->scenario=3; $model->attributes=(array)$impo; $model->uID=Yii::app()->user->id; if(!$model->save()) { $this->render("importError",array("model"=>$model)); die(); } else { $impo->delete(); $scc = true; unset($model); } } if($scc) { $this->render("importSuccess"); } } else throw new CException("o.o"); } public function actionExport($id=null) { if($id=="ALL") { $chars = Character::model()->findAll(); $file = serialize($chars); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=Characters.cb'); header('Content-Transfer-Encoding: binary'); ob_clean(); flush(); echo $file; exit; } else if($id!=null) { $char = Character::model()->findByPk($id); $file = serialize($chars); header('Content-Description: File Transfer'); header('Content-Type: application/octet-stream'); header('Content-Disposition: attachment; filename=Characters.cb'); header('Content-Transfer-Encoding: binary'); ob_clean(); flush(); echo $file; exit; } else throw new CException("No characterID specified!"); } } ?><file_sep>/protected/modules/charaBase/old/char.php <?php // constantfull classes: class SEX { const MALE=100; const FEMALE=200; const HERM=300; const MALE_HERM=301; const FEMALE_HERM=302; const SHEMALE=400; const CUNT_BOY=401; const GENDERLESS=500; const GENDER_SHIFTER=501; } class ATTD { const GOOD=10; const NEUTRAL=11; const BAD=12; const LAWFUL=220; const MIDDLE=221; const CHAOTIC=222; const LIGHT=30; const TWILIGHT=31; const DARK=32; } class charData_template { // Basic var $name; var $ID; var $category; var $position; public function __construct() { $l1 = array( "pic","casual","appearance","body","desc","relationship","relationship_extra","adult","spirit" ); foreach($l1 as $obj) { $this->$obj(); } } // Character detail creation public function pic() { $this->pic->avvie=NULL; $this->pic->solo=NULL; $this->pic->featured=NULL; } public function casual() { $this->casual->birthday=NULL; $this->casual->birthplace=NULL; } public function appearance() { $this->appearance->clothing=NULL; $this->appearance->makeup=NULL; $this->appearance->additional = FALSE; $this->appearance->addit_desc=NULL; } public function body() { $this->body->sex=NULL; $this->body->species=NULL; $this->body->height=NULL; $this->body->weight=NULL; $this->body->eyes->color=NULL; $this->body->eyes->style=NULL; $this->body->eyes->scelera=NULL; $this->body->hair->color=NULL; $this->body->hair->style=NULL; $this->body->hair->lengh=NULL; } public function desc() { $this->desc->history=NULL; $this->desc->likes=NULL; $this->desc->dislikes=NULL; $this->desc->addit = FALSE; $this->desc->addit_desc=NULL; } public function relationship() { $this->relationship->family=NULL; #= $mc->getFam($this->ID); $this->relationship->family_list=NULL; #= $mc->getFamList($this->ID); $this->relationship->partner=NULL; #= $mc->getPartner($this->ID); $this->relationship->mate=NULL; #= $mc->getMate($this->ID); $this->relationship->master=NULL; #= $mc->getMaster($this->ID); $this->relationship->pets=NULL; #= $mc->getPets($this->ID); $this->relationship->slaves=NULL; #= $mc->getSlaves($this->ID); } public function relationship_extra() { $this->relationship_extra->forms=NULL; #= $mc->getForms($this-ID); $this->relationship_extra->clan=NULL; #= $mc->getClan($this->ID); } public function adult() { $this->adult->ds=NULL; $this->adult->prefs=NULL; $this->adult->addit = FALSE; $this->adult->addit_desc=NULL; } public function spirit() { $this->spirit->status=NULL; $this->spirit->condition=NULL; $this->spirit->alignment=NULL; $this->spirit->sub_alignment=NULL; $this->spirit->type=NULL; $this->spirit->death->date=NULL; $this->spirit->death->cause=NULL; $this->spirit->death->place=NULL; } } $c= new charData_template(); print_r($c); ?><file_sep>/protected/modules/forum/models/ForumBoards.php <?php class ForumBoards extends CActiveRecord { public $id; public $name; public $desc; // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{Fboards}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('name','required'), array('desc','safe') ); } public function attributeLabels() { return array( 'name'=>Yii::t("forumModule.main","name"), 'desc'=>Yii::t('forumModule.main',"desc") ); } } ?><file_sep>/protected/modules/forum/views/view/topicView.php <h2><?=$topic->name?> <?php if($topic->sticky) echo "<small>Sticky</small>";?></h2> <small><?=$topic->desc?></small> <?php if(Yii::app()->user->isMod) { ?> <p> <?=CHtml::link("Edit topic",array("topic/edit","id"=>$topic->id))?> | <?=CHtml::link("Delete topic",array("topic/delete","id"=>$topic->id),array("onclick"=>"confirm('You sure?')"))?> </p> <?php } ?> <?php $topic->views++; ?> <br><br> <?php foreach($posts as $post) { $name = Yii::app()->getModule("user")->user($post->writerID)->username; $id = Yii::app()->getModule("user")->user($post->writerID)->id; $uname = CHtml::link($name,array("/user/user/view","id"=>$id)); $sig = Yii::app()->getModule("user")->user($post->writerID)->profile->getAttribute("sig"); #ProfileField::model()->findByAttributes(array("varname","sig"$post->writerID)->sig; echo '<div id="splitblock" class="forum">'; echo '<div id="splitS">'; echo "<h4>$uname</h4><br>"; echo 'Created at:<br> '.date("d.m.Y H:i",$post->createdAt).'<br>'; echo "Edited at:<br> ".date("d.m.Y H:i",$post->editedAt).'<br>'; if(!$post->isBlog) { if($post->writerID==Yii::app()->user->id || Yii::app()->isMod) { echo "<br>"; echo CHtml::link("Edit",array("post/edit","id"=>$post->id)); echo "<br>"; echo CHtml::link("delete",array("post/delete","id"=>$post->id)); } } else { echo CHtml::link("View as blog",array('/DragonsInn/view','id'=>$post->blogID)); } echo '</div>'; echo '<div id="splitB">'; $this->beginWidget('CMarkdown', array('purifyOutput'=>true)); echo $post->answer; $this->endWidget(); echo "<hr>"; echo $sig; echo '</div>'; echo '</div>'; echo '<div id="clearup"></div>'; } echo '<div class="form-actions">'; echo CHtml::link("Answer to this topic",array("post/answer","tid"=>$topic->id),array("class"=>"btn btn-inverse")); echo '</div>'; ?><file_sep>/themes/drag0n/css/bar.css.php <?php header("Content-Type: text/css"); ?> /*Menu section*/ .miniIcon {height: 28px; margin-top:-8px;} #bar { position: relative; display: block; background: rgba(0,0,0, 0.7); height: 30px; -moz-border-radius-bottomright: 20px; -moz-border-radius-bottomleft: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; -moz-box-shadow: 0px 5px 10px #888; -webkit-box-shadow: 0px 5px 10px #888; box-shadow: 0px 5px 10px #888; } #bar ul{ position: absolute; color: #FFFFFF; margin: 0px; padding-top: 5px; padding-bottom: 5px; padding-left: 10px; } #bar li{ display: block; float: left; padding-left: 5px; padding-right: 5px; z-index: 2; } #bar ul a{ color: #efefef; text-decoration: none; font-family: Arial, Helvetica, sans-serif; font-size: 14px; font-weight: 900; text-transform: capitalize; } #bar ul a:hover{ color: #666666; } /*copy from above, left side instead. */ #ubar { position: relative; display: block; } #ubar ul{ position: relative; color: #FFFFFF; margin: 0px; padding-top: 5px; padding-bottom: 5px; padding-right: 10px; } #ubar li{ display: block; float: right; padding-left: 5px; padding-right: 5px; } #ubar ul a{ color: #efefef; text-decoration: none; font-family: Arial, Helvetica, sans-serif; font-size: 14px; font-weight: 900; text-transform: capitalize; vertical-align: center; } #ubar ul a:hover{ color: #666666; } /*Again, but this time for the 2nd bar.*/ #Nbar { position: relative; display: block; background: rgba(0,0,0, 0.7); height: 25px; z-index: 2; -moz-border-radius-bottomright: 20px; -moz-border-radius-bottomleft: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; width: 338px; left: 17px; -moz-box-shadow: 0px 5px 10px #888; -webkit-box-shadow: 0px 5px 10px #888; box-shadow: 0px 5px 10px #888; } #Nbar ul{ position: absolute; color: #FFFFFF; margin: 0px; padding-bottom: 5px; padding-left: 10px; } #Nbar li{ display: block; float: left; padding-left: 5px; padding-right: 5px; z-index: 2; } #Nbar ul a{ color: #efefef; text-decoration: none; font-family: Arial, Helvetica, sans-serif; font-size: 14px; font-weight: 900; text-transform: capitalize; } #Nbar ul a:hover{ color: #666666; } <file_sep>/protected/models/Themes.php <?php class Themes extends CActiveRecord { public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{themes}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array("name, gstart, gend","required"), array('shadow','safe') ); } public $id; public $name; public $gstart; public $gend; public $shadow; } ?><file_sep>/protected/modules/forum/views/topic/form.php <?php if(isset($topic->id)) { ?> <h1>Edit topic</h1> <?php } else { ?> <h1>Create topic</h1> <?php } ?> <br> <fieldset> <?php /** @var BootActiveForm $form */ $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'horizontalForm', 'type'=>'horizontal', )); ?> <?php echo $form->textFieldRow($topic,"name",array("class"=>"entryField")); ?> <?php echo $form->textAreaRow($topic,"desc",array("class"=>"entryArea")); ?> <?php if(!isset($topic->id)) { echo $form->textAreaRow($topic,"firstPost",array("class"=>"entryArea",'hint'=>Yii::t("forumModule.main","hint"))); } ?> <div class="form-actions"> <?php if(Yii::app()->user->isMod) { echo CHtml::activeCheckBox($topic,"sticky",array("value"=>"1")); $this->widget('ext.ibutton.IButton', array( 'model' => $topic, 'attribute' => 'sticky', 'options' =>array( 'labelOn'=>"Sticky", 'labelOff'=>"Normal" ) )); } ?> <?php $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'type'=>'primary', 'label'=>'Submit')); ?> </div> <?php $this->endWidget(); ?> </fieldset><file_sep>/protected/modules/forum/ForumModule.php <?php class ForumModule extends CWebModule { public $defaultController="view"; public function init() { // this method is called when the module is being created // you may place code here to customize the module or the application // import the module-level models and components $this->setImport(array( 'forum.models.*', 'forum.components.*', )); // bootstrap enabler DN::makeBootstrap(); } public function beforeControllerAction($controller, $action) { if(parent::beforeControllerAction($controller, $action)) { // this method is called before any module controller action is performed // you may place customized code here return true; } else return false; } /** * @return string the base URL that contains all published asset files of this module. */ private $_assetsUrl; public function getAssetsUrl() { if ($this->_assetsUrl === null) $this->_assetsUrl = Yii::app()->getAssetManager()->publish( Yii::getPathOfAlias('forum.assets') // Comment this out for production. With this in place, module assets will be published // and copied over at every request, instaed of only once #,false,-1,true ); return $this->_assetsUrl; } } <file_sep>/protected/migrations/m121006_192253_AlertAfterAndBefore.php <?php class m121006_192253_AlertAfterAndBefore extends CDbMigration { public function up() { $this->addColumn('notifyii', 'alert_after_date', 'date'); $this->addColumn('notifyii', 'alert_before_date', 'date'); } public function down() { echo "m121006_192253_AlertAfterAndBefore does not support migration down.\n"; return false; } }<file_sep>/protected/config/main.php <?php // uncomment the following to define a path alias //Yii::setPathOfAlias('bootstrap',Yii::getPathOfAlias("ext.bootstrap")); // Debug ini_set('display_errors', 1); error_reporting(E_ALL); // This is the main Web application configuration. Any writable // CWebApplication properties can be configured here. return array( 'basePath'=>dirname(__FILE__).DIRECTORY_SEPARATOR.'..', 'name'=>"Viatropolis", 'theme'=>'drag0n', 'sourceLanguage'=>'00', 'language' => 'en', 'defaultController'=>'Viatropolis', // preloading 'log' component 'preload'=>array('log','less'), // 'bootstrap' // autoloading model and component classes 'import'=>array( 'application.modules.user.components.*', 'application.modules.user.models.*', 'application.models.*', 'application.components.*', 'application.controllers.*', 'application.modules.charabase.*', 'application.modules.charaBase.models.*', 'application.modules.charaBase.components.*', 'application.modules.mall.models.*', 'application.modules.forum.models.*', 'application.modules.charaBase.*', ), 'modules'=>array( //Singletons... 'charaBase', 'mall', // uncomment the following to enable the Gii tool 'gii'=>array( 'class'=>'system.gii.GiiModule', 'password'=>'<PASSWORD>', // If removed, Gii defaults to localhost only. Edit carefully to taste. 'ipFilters'=>array('127.0.0.1','::1'), 'generatorPaths'=>array( 'bootstrap.gii', ), ), 'user'=>array( # encrypting method (php hash function) 'hash' => 'md5', # send activation email 'sendActivationMail' => true, # allow access for non-activated users 'loginNotActiv' => true, # activate user on registration (only sendActivationMail = false) 'activeAfterRegister' => false, # automatically login from registration 'autoLogin' => false, # registration path 'registrationUrl' => array('/user/register'), # recovery password path 'recoveryUrl' => array('/user/recovery'), # login form path 'loginUrl' => array('/user/login'), # page after login 'returnUrl' => array('/mall'), # page after logout 'returnLogoutUrl' => array('/Viatropolis/index'), ), 'hybridauth'=>array( "baseUrl" => "http://".$_SERVER['SERVER_NAME']."/TEST/webroot/hybridauth/", 'withYiiUser' => true, "providers" => array ( // openid providers "OpenID" => array("enabled" => true), "Yahoo" => array ("enabled" => true), "AOL" => array ("enabled" => false), "Google" => array ( "enabled" => false, "keys" => array ("id" => "", "secret" => "" ), "scope" => "" ), "Facebook" => array ( "enabled" => true, "keys" => array ( "id" => "359491234141565", "secret" => "<KEY>" ), // A comma-separated list of permissions you want to request from the user. See the Facebook docs for a full list of available permissions: http://developers.facebook.com/docs/reference/api/permissions. "scope" => "email,publish_stream", // The display context to show the authentication page. Options are: page, popup, iframe, touch and wap. Read the Facebook docs for more details: http://developers.facebook.com/docs/reference/dialogs#display. Default: page "display" => "page" ), "Twitter" => array ( "enabled" => false, "keys" => array ( "key" => "<KEY>", "secret" => "<KEY>" ) ), // windows live "Live" => array ( "enabled" => false, "keys" => array ( "id" => "", "secret" => "" ) ), "MySpace" => array ( "enabled" => false, "keys" => array ( "key" => "", "secret" => "" ) ), "LinkedIn" => array ( "enabled" => false, "keys" => array ( "key" => "", "secret" => "" ) ), "Foursquare" => array ( "enabled" => false, "keys" => array ( "id" => "", "secret" => "" ) ), ), ), 'mailbox'=>array( # http://www.yiiframework.com/extension/mailbox/ 'userClass' => 'User', 'userIdColumn' => 'id', 'usernameColumn' => 'username', 'pageSize'=>50, 'userToUser'=>true, 'sendMsgs'=>true, 'sentbox'=>true, 'dragDelete'=>true, 'confirmDelete'=>1, 'recipientRead'=>true, #'cssFile'=>'/css/msg.css' #'menuPosition'=>'top', 'juiThemes'=>'widget', 'juiButtons'=>true, 'juiIcons'=>true, 'defaultSubject'=>"New Message...", 'editToField'=>true, 'linkUser'=>true, #'newsUserId'=>1 <- must find out mine. ), #'forum'=>array( # 'class'=>'application.modules.yii-forum.YiiForumModule', # 'dateReplaceWords'=>true, # 'threadsPerPage'=>20, #), 'forum', ), // application components 'components'=>array( /*'cache'=>array( 'class'=>'system.caching.CMemCache', 'servers'=>array( array('host'=>'localhost', 'port'=>11211, 'weight'=>60), ), ),*/ 'widgetFactory'=>array( 'widgets'=>array( 'CGridView'=>array( 'cssFile'=>false ), 'CDetailView'=>array( 'cssFile'=>false, ), 'GroupGridView'=>array( 'cssFile'=>false ), ), ), 'user'=>array( // enable cookie-based authentication 'allowAutoLogin'=>true, 'loginUrl'=>array('user/login'), #'logoutUrl'=>array("/main/index"), ), // uncomment the following to enable URLs in path-format 'coreMessages'=>array('basePath'=>'protected/messages'), 'urlManager'=>array( 'urlFormat'=>'path', 'showScriptName'=>false, 'rules'=>array( 'char/<ID:\d+>'=>'charaBase/view/char', 'chars'=>'charaBase/view/list', 'chars/<uID:\d+>'=>'charaBase/view/list', 'cpic/<ID:\d+>/<pid:\d+>'=>'charaBase/cpic/view', 'Viatropolis/info/<p:\w+>'=>'Viatropolis/info', 'user/<id:\d+>'=>'user/user/view', '<controller:\w+>/<id:\d+>'=>'<controller>/view', '<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>', '<controller:\w+>/<action:\w+>'=>'<controller>/<action>', ), ), 'db'=>array( 'connectionString' => 'mysql:host=localhost;dbname=viatrop_ajaxchat2', 'emulatePrepare' => true, 'username' => 'viatrop_ajaxchat', #db username goes here 'password' => '<PASSWORD>', #db password goes here 'charset' => 'utf8', 'tablePrefix'=>'tbl_', ), 'errorHandler'=>array( // use 'site/error' action to display errors 'errorAction'=>'Viatropolis/error', ), 'log'=>array( 'class'=>'CLogRouter', 'routes'=>array( array( 'class'=>'CFileLogRoute', 'levels'=>'error, warning', ), // uncomment the following to show log messages on web pages #array('class'=>'CWebLogRoute'), ), ), 'less'=>array( 'class'=>'ext.less.components.LessCompiler', 'forceCompile'=>false, // indicates whether to force compiling 'paths'=>array( 'less/style.less'=>'css/style.css', ), ), ), // application-level parameters that can be accessed // using Yii::app()->params['paramName'] 'params'=>array( // this is used in contact page 'adminEmail'=>'<EMAIL>', ), ); <file_sep>/protected/modules/charaBase/views/transfer/import2.php <?php echo "meep"; ?> <?php print_r($data); ?><file_sep>/protected/messages/de/info.php <?php //über diesen Ort $Tabout = "Über diesen Ort..."; $about = <<<EOF Drachennetz ist eine kleine aber feine comunity in der du mit Leuten abhängen kannst, dich mit Leuten unterhalten kannst oder falls du Lust hast mit ihnen Rpen kannst. Viele die auf dieser Drachennetz sind, sind Roleplayer und beherschen die Kunst des Bi-lingualen rpens (Deutsch und Englisch). <br><br> Alles began vor ein paar jahren als ich (Ingwie Phönix) und ein par andere Freunde ein bisschen mehr Privatsfäre beim Chatten und RPen wollten. Da einige jedoch damals noch unter 18 waren, waren sie sozusagen dort nicht erwünscht. Also habe ich diese seite vor ungefähr 2 Jahren, es könnten aber auch mehr sein, ins Leben gerufen. Seit dem wurde Drachennetz stetig von ausschließlich mir verbessert und modifiziert. Ich tuhe das jedoch alles in meiner freizeit. Man könnte sagen ich bin sowas wie ein one-man dev-team. <br><br> Seitdem andere Seiten (größere Seiten) ihr eigenes Team haben, habe ich nur mich selbst. Auf meinem Weg habe ich mir zusätzlich noch PHP, HTML, CSS und die Javascripte beigebracht und heute presentiere ich euch meine Software die ich „BIRD2“ nenne. Der Name BIRD entstand eigentlich wie fast alles zufällig, denn BIRD ist die Abkürzung für folgende Wörter: „Bring It Right Down“. Somit kann ich mich als stolzer Besitzer meiner eigenen gut programmierten Software zählen. Toumal (einer von SoFurry) hat mit außerdem informationen über eine framework gegeben die man Yii nennt. Framework war neu für mich aber innerhalb eines Jahres habe ich diese Drachennetz alleine erstellt. <br><br> Ich würde jedoch zu etwas Hilfe nicht nein sagen. Also wenn du gut programmieren kannst lass es mich wissen. Ich bin für jede Hilfe dankbar die ich kriegen kann. <br> <h3>Grüße, Ingwie Phoenix.</h3> <hr> <h2>The team</h2> <ul> <dt>Ingwie Phoenix <small>Admin, Besitzer</small></dt> <dd>Das bin ich. Ich bin seit Jahren der Programmierer und Besitzer dieser seite. :)</dd> <dt>Sapphy (aka. SapphireSky/Ceinios/Aria Leon) <small>Admin's mate, Grafikgehilfe, Ideenpotsau </small></dt> <dd>Sapphy versorgte mich immer mit informationen. Ohne ihn wäre die Charbase so nackt wie ein ungebohrenes Kind! Er ist derjenige, der die Sub-Projekte wie die Charbase, zur hälfte vielleicht auch ein bisschen mehr, erstellt hat. Außerdem war er derjenige, der mich hierzu inspiriert hat!</dd> <dt>Ranshiin <small>English moderator, VIP</small></dt> <dd>This Dieser süße Windrache ist schon seit einer langen Zeit auf meiner Sseite. Ich kann mich nicht mehr daran erinnern, wann er hier her gekommen ist. Wobei... es könnte damals gewesen sein als diese Seite Probleme mit einer anderen gehabt hatte. Aber egal... Ich mag es bei ihm zu sein. Und es macht spaß Sachen mit ihmzu machen. Außerdem ist er gut darin mir Kopfschmärzen zu bereiten, wenn er meine Software benutzt und sie zum Abstürzen bringt. Diese Sache dann wieder zu fixen ist das schwerste was man sich nur vorstellen kann. Therefore: <quote>Worst-Case Windragon</quote></dd> <dt>Lesia <small>German moderator</small></dt> <dd>Sie hat das deutsche in den Chat gebracht, da sie immer wieder welche von ihren deutschen Freunden mitgebracht hat. Außerdem ist sie diejenige, die auf alle deutschen aufpasst. </dd> <dt>Averian <small>Roleplayexpertin, VIP</small></dt> <dd>Ave ist eigentlich die einzige, die mit meinem RP-Level, welches sehr hoch ist, mithalten kann. Ave ist ein Vampir, das heißt Diskusionen über das Thema ob Vampire Furrys sind oder nicht sind vorprogrammiert. Aber eigentlich ist mir das egal. Sie ist sehr nett, hat eine tolle persönlichkeit und ist manchmal echt lustig. ^^</dd> </ul> <br><br><br> Die momentanen admins/mods: <ul> <li>Ingwie Phoenix: Admin, Besitzer, english/german</li> <li>Excel: Admin/Moderator, english/german</li> <li>Ranshiin: Moderator, english</li> <li>Lesia: Moderator, german</li> </ul> <i>Zur Zeit plane ich keine Rekrutierungen.</i> EOF; //donation! $Tdonation = " "; $donation = <<<EOF <br><br><center><h3> Hilf diesem Ort, damit er noch lange lebt! </h3></center><br><br> Dieser ort ist aus nichts als einer simplen Idee entstanden. Ich bin derjenige, der diese Seite am Laufen erhält. Ich bezahle alle Rechnungen die bezahlt werden müssen und kümmere mich mit Liebe um diese Seite. Also wenn du dankbar dafür bist, das ich mir alle Mühe gemacht habe, würde ich mich über eine kleine Spende freuen :) . Benutze einfach den Paypallbutton oder überweise es direkt an mich. email: <EMAIL><br><br> Spender werden als VIP's dargestellt und in den Danksagungen erwähnt. EOF; $Tcontact = "Kontaktiere Dragon's Inn"; $contact = <<<EOF Du kannst das Drachennetz personal ganz leicht erreichtn. Die nachfolgenden informationen sollten kein Spamm sein. !<br><br><br> <b>Ingwie Phoenix</b> <ul> <li>Facebook: <a href="http://facebook.com/ingwie2000">Ingwie Phoenix</a></li> <li>Public email: <a href="mailto:<EMAIL>"><EMAIL></a></li> <li>Skype: wlaningwie</li> <li>FurAffinity: <a href="http://furaffinity.com/user/ingwie2000">ingwie2000</a></li> <li>SoFurry: <a href="http://ingwie-phoenix.sofurry.com">Ingwie Phoenix</a></li> </ul><br> Excel -- None available yet.<br> Lesia -- None available yet.<br> Ranshiin -- None available yet. EOF; return array( 'Tabout'=>$Tabout, 'about'=>$about, 'Tdonation'=>$Tdonation, 'donation'=>$donation, 'Tcontact'=>$Tcontact, 'contact'=>$contact, ); ?> <file_sep>/protected/messages/de/admin.php <?php return array( // admin language 'mHead'=>'<p>Choose an area to manage.</p>', 'mChat'=>'Verwalte den Chat', 'mThemes'=>'Verwalte die Themes', 'mBlog'=>'Verwalte den Blog', 'aTheme'=>'Theme hinzufügen', 'tDesc'=>"<p> Hier kannst du die Themes verwalten, die in Dragon's Inn verwendbar sind.<br> Die Werte von <code>gstart</code>, <code>gend</code> und <code>shadow</code> sind HEX-Codierte Farben. Die <code>#</code> wird automatisch angefügt.<br> Wenn <code>shadow</code> nicht eingegeben wurde, wird der Wert von <code>gstart</code> genommen. </p>", 'cDef'=>'Standart Kanäle', 'aChat'=>'Kanal hinzufügen', 'cs'=>'Kanäle', 'aBlog'=>'Erstelle Blogeintrag', 'bDesc'=>"<p> Lösche, bearbeite oder füge Blogeinträge hinzu. Du kannst nur Einträge modifizieren die von dir erstellt wurden.<br> Um zum Bearbeiten oder Löschen zu gelangen, klicke auf den Namen und benutze die dortigen links. </p>", ); ?><file_sep>/protected/db/mysql.sql -- MySQL dump 10.13 Distrib 5.1.66, for debian-linux-gnu (x86_64) -- -- Host: localhost Database: dragonsinn -- ------------------------------------------------------ -- Server version 5.1.66-0+squeeze1 /*!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 */; /*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */; /*!40103 SET TIME_ZONE='+00:00' */; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; -- -- Table structure for table `AuthAssignment` -- DROP TABLE IF EXISTS `AuthAssignment`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `AuthAssignment` ( `itemname` varchar(255) COLLATE utf8_bin DEFAULT NULL, `userid` varchar(255) COLLATE utf8_bin DEFAULT NULL, `bizrule` text COLLATE utf8_bin, `date` text COLLATE utf8_bin ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `AuthItem` -- DROP TABLE IF EXISTS `AuthItem`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `AuthItem` ( `name` varchar(255) COLLATE utf8_bin DEFAULT NULL, `type` int(11) DEFAULT NULL, `description` text COLLATE utf8_bin, `data` text COLLATE utf8_bin ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `AuthItemChild` -- DROP TABLE IF EXISTS `AuthItemChild`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `AuthItemChild` ( `parent` varchar(255) COLLATE utf8_bin DEFAULT NULL, `child` varchar(255) COLLATE utf8_bin DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ajax_chat_bans` -- DROP TABLE IF EXISTS `ajax_chat_bans`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ajax_chat_bans` ( `userID` int(11) NOT NULL, `userName` varchar(64) COLLATE utf8_bin NOT NULL, `dateTime` datetime NOT NULL, `ip` varbinary(16) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ajax_chat_channels` -- DROP TABLE IF EXISTS `ajax_chat_channels`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ajax_chat_channels` ( `id` int(11) NOT NULL AUTO_INCREMENT, `orderID` int(11) NOT NULL DEFAULT '0', `name` varchar(255) COLLATE utf8_bin NOT NULL, `desc` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ajax_chat_defaults` -- DROP TABLE IF EXISTS `ajax_chat_defaults`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ajax_chat_defaults` ( `PK` int(1) NOT NULL, `adminChannels` varchar(255) COLLATE utf8_bin NOT NULL, `userChannels` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`PK`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ajax_chat_invitations` -- DROP TABLE IF EXISTS `ajax_chat_invitations`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ajax_chat_invitations` ( `userID` int(11) NOT NULL, `channel` int(11) NOT NULL, `dateTime` datetime NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ajax_chat_messages` -- DROP TABLE IF EXISTS `ajax_chat_messages`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ajax_chat_messages` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userID` int(11) NOT NULL, `userName` varchar(1000) COLLATE utf8_bin NOT NULL, `userRole` int(1) NOT NULL, `channel` int(11) NOT NULL, `dateTime` datetime NOT NULL, `ip` varbinary(16) NOT NULL, `text` text COLLATE utf8_bin, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=48732 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ajax_chat_online` -- DROP TABLE IF EXISTS `ajax_chat_online`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ajax_chat_online` ( `userID` int(11) NOT NULL, `userName` varchar(1000) COLLATE utf8_bin NOT NULL, `userRole` int(1) NOT NULL, `channel` int(11) NOT NULL, `dateTime` datetime NOT NULL, `ip` varbinary(16) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `ha_logins` -- DROP TABLE IF EXISTS `ha_logins`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `ha_logins` ( `id` int(11) NOT NULL AUTO_INCREMENT, `userId` int(11) NOT NULL, `loginProvider` varchar(50) COLLATE utf8_bin NOT NULL, `loginProviderIdentifier` varchar(100) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`), UNIQUE KEY `loginProvider_2` (`loginProvider`,`loginProviderIdentifier`), KEY `loginProvider` (`loginProvider`), KEY `loginProviderIdentifier` (`loginProviderIdentifier`), KEY `userId` (`userId`), KEY `id` (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_Fboards` -- DROP TABLE IF EXISTS `tbl_Fboards`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_Fboards` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin NOT NULL, `desc` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_Fcategories` -- DROP TABLE IF EXISTS `tbl_Fcategories`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_Fcategories` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin NOT NULL, `desc` text COLLATE utf8_bin NOT NULL, `boards` text COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_Fposts` -- DROP TABLE IF EXISTS `tbl_Fposts`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_Fposts` ( `id` int(11) NOT NULL AUTO_INCREMENT, `topicID` int(11) NOT NULL, `writerID` int(11) NOT NULL, `createdAt` int(11) NOT NULL, `editedAt` int(11) NOT NULL, `answer` text COLLATE utf8_bin NOT NULL, `isBlog` int(2) NOT NULL, `blogID` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_Ftopics` -- DROP TABLE IF EXISTS `tbl_Ftopics`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_Ftopics` ( `id` int(11) NOT NULL AUTO_INCREMENT, `boardID` int(11) NOT NULL, `creatorID` int(11) NOT NULL, `sticky` int(1) NOT NULL, `name` varchar(255) COLLATE utf8_bin NOT NULL, `desc` varchar(255) COLLATE utf8_bin NOT NULL, `views` int(11) NOT NULL, `isBlog` int(2) NOT NULL, `blogID` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_blog` -- DROP TABLE IF EXISTS `tbl_blog`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_blog` ( `id` int(11) NOT NULL AUTO_INCREMENT, `author` int(11) NOT NULL, `modified` int(11) NOT NULL, `tags` varchar(255) COLLATE utf8_bin NOT NULL, `title` varchar(255) COLLATE utf8_bin NOT NULL, `content` text COLLATE utf8_bin NOT NULL, `hasTopic` int(2) NOT NULL, `postID` int(11) NOT NULL, `topicID` int(11) NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_charabase` -- DROP TABLE IF EXISTS `tbl_charabase`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_charabase` ( `cID` int(11) NOT NULL AUTO_INCREMENT, `uID` int(11) NOT NULL, `name` varchar(255) COLLATE utf8_bin NOT NULL, `nickName` varchar(255) COLLATE utf8_bin NOT NULL, `category` tinyint(4) NOT NULL, `position` tinyint(4) NOT NULL, `scenario` int(5) NOT NULL, `cpic` text COLLATE utf8_bin NOT NULL, `birthday` date NOT NULL, `birthPlace` varchar(255) COLLATE utf8_bin NOT NULL, `sex` tinyint(4) NOT NULL, `orientation` tinyint(4) NOT NULL, `species` varchar(255) COLLATE utf8_bin NOT NULL, `makeup` varchar(255) COLLATE utf8_bin NOT NULL, `clothing` varchar(255) COLLATE utf8_bin NOT NULL, `addit_appearance` varchar(255) COLLATE utf8_bin NOT NULL, `height` varchar(255) COLLATE utf8_bin NOT NULL, `weight` varchar(255) COLLATE utf8_bin NOT NULL, `eye_c` varchar(255) COLLATE utf8_bin NOT NULL, `eye_s` varchar(255) COLLATE utf8_bin NOT NULL, `hair_c` varchar(255) COLLATE utf8_bin NOT NULL, `hair_s` varchar(255) COLLATE utf8_bin NOT NULL, `hair_l` varchar(255) COLLATE utf8_bin NOT NULL, `history` text COLLATE utf8_bin NOT NULL, `likes` text COLLATE utf8_bin NOT NULL, `dislikes` text COLLATE utf8_bin NOT NULL, `addit_desc` text COLLATE utf8_bin NOT NULL, `relationships` text COLLATE utf8_bin NOT NULL, `family` varchar(255) COLLATE utf8_bin NOT NULL, `partners` varchar(255) COLLATE utf8_bin NOT NULL, `pets` varchar(255) COLLATE utf8_bin NOT NULL, `slaves` varchar(255) COLLATE utf8_bin NOT NULL, `master` varchar(255) COLLATE utf8_bin NOT NULL, `forms` varchar(255) COLLATE utf8_bin NOT NULL, `clan` varchar(255) COLLATE utf8_bin NOT NULL, `dom_sub` tinyint(4) NOT NULL, `preferences` text COLLATE utf8_bin NOT NULL, `addit_adult` varchar(1000) COLLATE utf8_bin NOT NULL, `spirit_status` tinyint(4) NOT NULL, `spirit_condition` tinyint(4) NOT NULL, `spirit_alignment` tinyint(4) NOT NULL, `spirit_sub_alignment` tinyint(4) NOT NULL, `spirit_type` tinyint(4) NOT NULL, `spirit_death_date` date NOT NULL, `spirit_death_place` varchar(255) COLLATE utf8_bin NOT NULL, `spirit_death_cause` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`cID`) ) ENGINE=InnoDB AUTO_INCREMENT=430 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_charabaseImporter` -- DROP TABLE IF EXISTS `tbl_charabaseImporter`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_charabaseImporter` ( `id` int(10) NOT NULL AUTO_INCREMENT, `name` text COLLATE utf8_bin NOT NULL, `category` text COLLATE utf8_bin NOT NULL, `position` int(5) NOT NULL, `scenario` int(5) NOT NULL, `species` text COLLATE utf8_bin NOT NULL, `sex` text COLLATE utf8_bin NOT NULL, `birthPlace` text COLLATE utf8_bin NOT NULL, `hair_c` text COLLATE utf8_bin NOT NULL, `hair_s` text COLLATE utf8_bin NOT NULL, `hair_l` text COLLATE utf8_bin NOT NULL, `eye_s` text COLLATE utf8_bin NOT NULL, `eye_c` text COLLATE utf8_bin NOT NULL, `history` text COLLATE utf8_bin NOT NULL, `likes` text COLLATE utf8_bin NOT NULL, `dislikes` text COLLATE utf8_bin NOT NULL, `relationship` text COLLATE utf8_bin NOT NULL, `relationships` text COLLATE utf8_bin NOT NULL, `addit_desc` text COLLATE utf8_bin NOT NULL, `created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, UNIQUE KEY `ID` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=167 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_charabasePictures` -- DROP TABLE IF EXISTS `tbl_charabasePictures`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_charabasePictures` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin NOT NULL, `url` varchar(255) COLLATE utf8_bin NOT NULL, `desc` text COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=615 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_mailbox_conversation` -- DROP TABLE IF EXISTS `tbl_mailbox_conversation`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_mailbox_conversation` ( `conversation_id` int(10) unsigned NOT NULL AUTO_INCREMENT, `initiator_id` int(10) NOT NULL, `interlocutor_id` int(10) NOT NULL, `subject` varchar(100) NOT NULL DEFAULT '', `bm_read` tinyint(3) NOT NULL DEFAULT '0', `bm_deleted` tinyint(3) NOT NULL DEFAULT '0', `modified` int(10) unsigned NOT NULL, `is_system` enum('yes','no') NOT NULL DEFAULT 'no', `initiator_del` tinyint(1) unsigned DEFAULT '0', `interlocutor_del` tinyint(1) unsigned DEFAULT '0', PRIMARY KEY (`conversation_id`), KEY `initiator_id` (`initiator_id`), KEY `interlocutor_id` (`interlocutor_id`), KEY `conversation_ts` (`modified`), KEY `subject` (`subject`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_mailbox_message` -- DROP TABLE IF EXISTS `tbl_mailbox_message`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_mailbox_message` ( `message_id` int(11) unsigned NOT NULL AUTO_INCREMENT, `conversation_id` int(10) unsigned NOT NULL, `created` int(10) unsigned NOT NULL DEFAULT '0', `sender_id` int(10) unsigned NOT NULL DEFAULT '0', `recipient_id` int(10) unsigned NOT NULL DEFAULT '0', `text` mediumtext NOT NULL, `crc64` bigint(20) NOT NULL, PRIMARY KEY (`message_id`), KEY `sender_profile_id` (`sender_id`), KEY `recipient_profile_id` (`recipient_id`), KEY `conversation_id` (`conversation_id`), KEY `timestamp` (`created`), KEY `crc64` (`crc64`), FULLTEXT KEY `text` (`text`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_profiles` -- DROP TABLE IF EXISTS `tbl_profiles`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_profiles` ( `user_id` int(11) NOT NULL AUTO_INCREMENT, `first_name` varchar(255) DEFAULT NULL, `last_name` varchar(255) DEFAULT NULL, `social_fa` varchar(255) NOT NULL DEFAULT '', `sig` text NOT NULL, PRIMARY KEY (`user_id`), CONSTRAINT `user_profile_id` FOREIGN KEY (`user_id`) REFERENCES `tbl_users` (`id`) ON DELETE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_profiles_fields` -- DROP TABLE IF EXISTS `tbl_profiles_fields`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_profiles_fields` ( `id` int(11) NOT NULL AUTO_INCREMENT, `varname` varchar(50) NOT NULL DEFAULT '', `title` varchar(255) NOT NULL DEFAULT '', `field_type` varchar(50) NOT NULL DEFAULT '', `field_size` int(3) NOT NULL DEFAULT '0', `field_size_min` int(3) NOT NULL DEFAULT '0', `required` int(1) NOT NULL DEFAULT '0', `match` varchar(255) NOT NULL DEFAULT '', `range` varchar(255) NOT NULL DEFAULT '', `error_message` varchar(255) NOT NULL DEFAULT '', `other_validator` text, `default` varchar(255) NOT NULL DEFAULT '', `widget` varchar(255) NOT NULL DEFAULT '', `widgetparams` text, `position` int(3) NOT NULL DEFAULT '0', `visible` int(1) NOT NULL DEFAULT '0', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_themes` -- DROP TABLE IF EXISTS `tbl_themes`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_themes` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(255) COLLATE utf8_bin NOT NULL, `gstart` varchar(255) COLLATE utf8_bin NOT NULL, `gend` varchar(255) COLLATE utf8_bin NOT NULL, `shadow` varchar(255) COLLATE utf8_bin NOT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=34 DEFAULT CHARSET=utf8 COLLATE=utf8_bin; /*!40101 SET character_set_client = @saved_cs_client */; -- -- Table structure for table `tbl_users` -- DROP TABLE IF EXISTS `tbl_users`; /*!40101 SET @saved_cs_client = @@character_set_client */; /*!40101 SET character_set_client = utf8 */; CREATE TABLE `tbl_users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `username` varchar(20) NOT NULL DEFAULT '', `password` varchar(128) NOT NULL DEFAULT '', `email` varchar(128) NOT NULL DEFAULT '', `activkey` varchar(128) NOT NULL DEFAULT '', `superuser` int(1) NOT NULL DEFAULT '0', `status` int(1) NOT NULL DEFAULT '0', `create_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP, `lastvisit_at` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00', PRIMARY KEY (`id`), UNIQUE KEY `user_username` (`username`), UNIQUE KEY `user_email` (`email`) ) ENGINE=InnoDB AUTO_INCREMENT=35 DEFAULT CHARSET=utf8; /*!40101 SET character_set_client = @saved_cs_client */; /*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */; /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!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 */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */; -- Dump completed on 2013-02-04 0:53:21 <file_sep>/themes/drag0n/css/drag0n.css.php <?php header("Content-Type: text/css"); // Yes, unique. Using PHP in this CSS to speed up changings. // Variables. if(isset($_GET['gstart'])) { $gStart="#".$_GET['gstart']; } else { $gStart = "#efefef"; } if(isset($_GET['gend'])) { $gEnd="#".$_GET['gend']; } else { $gEnd = "#000000"; } if(isset($_GET['shadow'])) { $shadow = "#".$_GET['shadow']; } else { $shadow = "grey"; } ?> /*HTML elemnt resetter*/ li, ul, ul li{ margin:0; padding:0; } body { background: <?=$gStart?>; background: -webkit-gradient(linear, left top, left bottom, from(<?=$gStart?>), to(<?=$gEnd?>)); background: -moz-linear-gradient(top, <?=$gStart?>, <?=$gEnd?>); height: 100%; margin: 0px; padding: 0px; background-repeat: no-repeat; color: white; text-align: left; background-attachment:fixed; } .centerpic { right: auto; left: auto; display: block; margin-left: auto; margin-right: auto; text-align: center; z-index: 1; } #container { width: 95%; margin-left: auto; margin-right: auto; padding-top: 10px; position: relative; padding-bottom: 200px; } #content { -moz-box-shadow: 0px 3px 18px #888; -webkit-box-shadow: 0px 3px 18px #888; box-shadow: 0px 3px 18px #888; position: relative; background: rgba(0,0,0, 0.7); color: #EFEFEF; margin-bottom: 40px; padding-left: 10px; padding-right: 10px; padding-bottom: 20px; float: left; border-radius: 15px; } .withBar { width: 75%; } .withoutBar { width: 98%; } #sidebar { -moz-box-shadow: -3px -10px 50px 5px <?=$shadow?>; -webkit-box-shadow: -3px -10px 50px 5px <?=$shadow?>; box-shadow: -3px -10px 50px 10px <?=$shadow?>; background: rgba(0,0,0, 0.4); float: left; width: 20%; margin-right: 10px; padding-left: 3px; padding-right: 3px; position: relative; } #footer { float: right; background: rgba(0,0,0, 0.5); font-style: italic; text-align: right; width: auto; padding-top: 10px; padding-bottom: 10px; padding-left: 20px; padding-right: 10px; margin-top: 100px; margin-bottom: 20px; } #sidebar ul {list-style:none;} dt { font-weight: bold; } #content ul li { margin-left: 10px; } input, input[type=password], input[type=text], select, textarea { background: black; color: white; border: 0; -moz-box-shadow: 1px 1px 20px 2px <?=$shadow?>; -webkit-box-shadow: 1px 1px 20px 2px <?=$shadow?>; box-shadow: 1px 1px 20px 2px <?=$shadow?>; } #cpic img { max-height: 500px; right: auto; left: auto; display: block; margin-left: auto; margin-right: auto; text-align: center; } #post { margin-left: 20px; margin-right: 20px; } #post #title { font-size: 20pt; margin-left: 10px; margin-bottom: 3px; } #post #author { margin-bottom: 3px; margin-top: 5px; } #post #message { margin-top: 15px; background: black; } .bigText { width: 99%; height: 200px; } .smallText {width: 96.5%; height: 210px;} .miniText {width:96.5%; height: 70px;} #clearup { clear: both; padding-top:20px; } .clearup2 {clear:both;padding-top:2px;padding-bottom:2px;} #splitblock, .splitblock { width:100%; position:relative;} #splitblock #split { float:left; width: 39%; margin-left:77px; margin-right:93px; position:relative; } .allNormal{padding:0;margin:0;width:auto;height:auto;} .forum { border-top:1px solid <?=$shadow?>; border-bottom:1px solid <?=$shadow?>; } #splitblock #splitS { float:left; width:18%; border-style:solid;border-right:1px solid <?=$shadow?>; border-left:0 solid transparent; border-top:0; border-bottom:0;} #splitblock #splitSS { float:left; width:18%;} #splitblock #splitS h4 { margin-top: 5px; } #splitblock #splitB { float:left; width:80%; padding-left:10px; padding-top: 5px; padding-right: 10px;} #splitblock #splitB hr {border-color:<?=$shadow?>;} .prettySummary {text-align:left;} .entryField {width: 800px; } .entryArea {width: 800px; height: 150px;} .form-actions { background:transparent; border:0; } .breadcrumbs { margin-right: 36px; margin-left: 36px; padding-left:10px; background:rgba(0,0,0,0.2); -moz-border-radius-bottomright: 20px; -moz-border-radius-bottomleft: 20px; border-bottom-right-radius: 20px; border-bottom-left-radius: 20px; -moz-box-shadow: 0px 5px 10px #888; -webkit-box-shadow: 0px 5px 10px #888; box-shadow: 0px 5px 10px #888; } .breadcrumbs a { color:gold; text-decoration:none; } .categoryHeader {margin-top: 50px;} .odd.sticky, .even.sticky {background:rgba(173,255,47, 0.3);} .warning {text-align:center;color:red;} fieldset { padding-left: 5px; padding-right: 5px; } #footer input { -moz-box-shadow: 0 0 0 0; -webkit-box-shadow: 0 0 0 0; box-shadow: 0 0 0 0; } .CBlist {width:100%;position:absolute;} .CBentry {width: 200px;float:left;position:relative;} .CBitems {padding-bottom:20px;} /*System*/ .errorSummary, div.form .errorSummary, html body div#container div#content.withoutBar div.form form div.row input#UserLogin_username.error { border: 1px solid red; padding: 2px 2px 2px 2px; background: rgba(255,0,0, 0.3); } div.form div.success select, div.form div.success input, div.form div.success option, div.form div.error input, div.form div.error select, div.form div.error option { background:transparent; } .errorSummary ul, .errorSummary li { list-style: none; } /*#fileInfo {}*/ #imgDiv { float:left; position:relative; padding-left:15px; } img.show { height: 130px; } .putaway { margin-top:20px; } .goCenter { vertical-align: center; } .rightWalk { margin-left: 10px; } /*Modules*/ .hybridauth-providerlist { position: absolute; } #languagePickerContainer { position: fixed; padding-top: 6px; padding-left: 10px; z-index: 3; } <?php include("bar.css.php"); ?> <?php include("table.css.php"); ?> #ajaxChatContent { width:90%; background: rgba(0,0,0, 0.5); margin-left: auto; margin-right: auto; left: auto; right: auto; position: relative; margin-top: -145px; margin-bottom: 20px; padding-left:5px; padding-right:5px; padding-top: 5px; padding-bottom:5px; z-index:2; } #ajaxChatContent #ajaxChatChatList { height: 150px; overflow:scroll; } #ajaxChatContent #ajaxChatInputFieldContainer { margin-top:5px; } #ajaxChatContent #ajaxChatInputFieldContainer #ajaxChatInputField { box-shadow: 0 0 0 0; -moz-box-shadow: 0 0 0 0; -webkit-box-shadow: 0 0 0 0; width: 98.5%; margin-left: 3px; margin-right:3px; } .guest, .user, .moderator, .admin, .vip, .chatBot { font-weight:bold; } .admin, a.admin { color:blue; } .moderator, a.moderator { color:orange; } .user, a.user {color: white;} .chatBot { color:green; } .vip, a.vip { color:purple; } .delete { background:url('/themes/drag0n/images/delete.png') no-repeat right; margin-right:10px; } .yiilog { color:black; } code {background:transparent;} .miniIcon { max-width: 28px; margin-top:-5px; } <file_sep>/protected/messages/en/site.php <?php return array( // menu items 'chars'=>'Characters', 'ath'=>'About Viatropolis', 'contact'=>'Contact&Staff', //'donate'=>'Donate!', 'manage'=>"Manage Viatropolis", 'settings'=>'Settings', 'u'=>'You', 'lang'=>'Language', 'cbCreate'=>'Create', 'cbList'=>'List', 'cbManage'=>'Manage', 'cbExport'=>'export', 'cbImport'=>'Import', 'mChat'=>'Mall', 'mBlog'=>'Blog', 'mThemes'=>'Themes', // generic words 'play'=>'Play', 'cselect'=>'Character select', 'profil'=>"Profile", 'edit'=>'Edit', 'create'=>'Create', 'delete'=>'Delete', 'ban'=>'Ban', 'ipban'=>'IP-Ban', 'issue'=>'Issue', 'menu'=>'Menu', 'me'=>'Me', 'login'=>'Login', 'logout'=>'Logout', 'notifications'=>'Notifications', 'messages'=>'Messages' ); ?><file_sep>/protected/modules/forum/models/ForumPosts.php <?php class ForumPosts extends CActiveRecord { public $id; public $topicID; public $writerID; public $createdAt; public $editedAt; public $answer; public $isBlog=false; public $blogID; // default functions... public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{Fposts}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('answer','required') ); } public function attributeLabels() { return array( 'answer'=>Yii::t('forumModule.main',"answer") ); } } ?><file_sep>/protected/modules/charaBase/views/view/char.php <div> <h2><?=$model->name?> <small><?=$model->nickName?></small></h2> <h4>Category: <?=$CBT->category($model->category)?> | Position: <?=$CBT->position($model->position)?> | Owned by: <?=CHtml::link( Yii::app()->getModule("user")->user($model->uID)->username, array('/user/user/view','id'=>$model->uID) )?><br><br> <?php if(Yii::app()->user->id == $model->uID): ?> <small>[ <?=CHtml::link(Yii::t("charaBaseModule.cb","edit"), array("maintain/edit","ID"=>$model->cID))?> | <?=CHtml::link(Yii::t("charaBaseModule.cb","delete"), array("maintain/delete","ID"=>$model->cID))?> | <?=CHtml::link(Yii::t("charaBaseModule.cb","backup"), array("transfer/backup","ID"=>$model->cID))?> ]</small> <?php endif; ?> </h4><br><br> <div id="splitblock"> <div id="split"> <?php $data = array("species","sex","orientation","birthday","birthPlace"); echo '<h3 name="basic">'.Yii::t('charaBaseModule.cb','basic').'</h3>'; foreach($data as $label) { if($model->$label != "0000-00-00" and $model->$label != null) { switch($label) { case "sex": $o = $CBT->sex($model->$label); break; case "orientation": $o = $CBT->orientation($model->$label); break; default: $o = $model->$label; break; } echo '<b>'.Yii::t('charaBaseModule.cb', $label).":</b> ".$o."<br>"; } } ?><br> <?php if($model->scenario != 0) { $data = array('height','weight','eye_c','eye_s','hair_c', 'hair_s', 'hair_l'); echo '<h3 name="body">'.Yii::t('charaBaseModule.cb','body').'</h3>'; foreach($data as $label) { if($model->$label != "0000-00-00" and $model->$label != null) { switch($label) { default: $o = $model->$label; break; } echo '<b>'.Yii::t('charaBaseModule.cb', $label).":</b> ".$o."<br>"; } } } ?> </div> <div id="split"> <?php if($model->scenario == 3) { $data = array("makeup","clothing","addit_appearance"); echo '<h3 name="appearance">'.Yii::t('charaBaseModule.cb','appearance').'</h3>'; foreach($data as $label) { if($model->$label != "0000-00-00" and $model->$label != null) { switch($label) { default: $o = $model->$label; break; } echo '<b>'.Yii::t('charaBaseModule.cb', $label).":</b> ".$o."<br>"; } } ?><br> <?php $data = array( "spirit_condition","spirit_alignment","spirit_sub_alignment","spirit_type",'spirit_status', "spirit_death_date","spirit_death_place","spirit_death_cause" ); echo '<h3 name="spirit">'.Yii::t('charaBaseModule.cb','spirit').'</h3>'; foreach($data as $label) { if($model->$label != "0000-00-00" and $model->$label != null and $model->$label != 100) { switch($label) { case 'spirit_condition': $o = $CBT->spirit_condition($model->$label); break; case 'spirit_alignment': $o = $CBT->spirit_alignment($model->$label); break; case 'spirit_sub_alignment': $o = $CBT->spirit_sub_alignment($model->$label); break; case 'spirit_type': $o = $CBT->spirit_type($model->$label); break; case 'spirit_status': $o = $CBT->spirit_alignment($model->$label); break; default: $o = $model->$label; break; } echo '<b>'.Yii::t('charaBaseModule.cb', $label).":</b> ".$o."<br>"; } } } ?> </div> </div> <div id="clearup"></div> <?php if($model->scenario == 1 || $model->scenario == 2 || $model->scenario == 3) { ?> <hr> <h1 style="padding-top: 20px; padding-bottom: 25px;">Literature</h1> <?php if($model->history != null) { echo "<h2>".Yii::t("charaBaseModule.cb","history")."</h2>"; echo "<p>".$model->history."</p>"; } ?> <?php if($model->addit_desc != null) { echo "<h2>".Yii::t("charaBaseModule.cb","addit_desc")."</h2>"; echo "<p>".$model->addit_desc."</p>"; } ?> <div id="splitblock"> <div id="split"> <?php $data = array("likes"); foreach($data as $label) { if($model->$label != "0000-00-00" || $model->$label != null) { echo '<h3 name="likes">'.Yii::t('charaBaseModule.cb','likes').'</h3>'; echo "<p>".$model->$label."</p>"; } } ?> </div> <div id="split"> <?php $data = array("dislikes"); foreach($data as $label) { if($model->$label != "0000-00-00" || $model->$label != null) { echo '<h3 name="dislikes">'.Yii::t('charaBaseModule.cb','dislikes').'</h3>'; echo "<p>".$model->$label."</p>"; } } ?> </div> </div> <div style="clear: both; padding-top:20px;"></div> <?php } ?> <?php if($model->scenario != 0 && $model->scenario != 1) { ?> <div id="splitblock"> <div id="split"> <?php $data = array("relationships"); foreach($data as $label) { if($model->$label != "0000-00-00" and $model->$label != null) { echo '<h3 name="relationships">'.Yii::t('charaBaseModule.cb','relationships').'</h3>'; echo "<p>".$model->$label."</p>"; } } ?> </div> <div id="split"> <?php $data = array("dom_sub","prefs","addit_adult"); echo '<h3 name="adult">'.Yii::t('charaBaseModule.cb','adult').'</h3>'; foreach($data as $label) { if($model->$label != "0000-00-00" and $model->$label != null) { switch($label) { case 'dom_sub': $o = $CBT->ds($model->$label); break; default: $o = $model->$label; break; } echo '<b>'.Yii::t('charaBaseModule.cb', $label).":</b> ".$o."<br>"; } } ?> </div> </div> <?php } ?> <div style="clear: both; padding-top:20px;"></div> <div id="cpic"> <?php $picData=unserialize($model->cpic); #echo $model->cpic; if(is_array($picData)) { foreach($picData as $key=>$cpicNr) { $Cpic=CharacterPicture::model()->findByPk($cpicNr); if(is_object($Cpic)) { echo CHtml::link( CHtml::image($this->createUrl('cpic/view',array( 'pid'=>$Cpic->id, 'ID'=>$model->cID ))), array('cpic/view', 'pid'=>$Cpic->id, 'ID'=>$model->cID ) ); echo '<br><div style="text-align:center;">'.$Cpic->desc."</div><br><br>"; unset($Cpic); } } } ?> </div> </div><file_sep>/protected/models/Blog.php <?php class Blog extends CActiveRecord { public static function model($className=__CLASS__) { return parent::model($className); } public function tableName() { return '{{blog}}'; } public function primaryKey() { return 'id'; } public function rules() { return array( array('title, content','required'), array('modified','safe') ); } public $id; public $author; public $modified; public $tags="me,gusta"; public $title; public $content; public $hasTopic=false; public $postID=0; public $topicID=0; } ?><file_sep>/protected/messages/en/cb.php <?php return array( // CharaBase translation: English // By <NAME> 'name'=>"Name", 'nickName'=>'Nickname', 'sex'=>'Sex', 'orientation'=>'Orientation', 'species'=>'Species', 'category'=>'Category', 'position'=>'Position', 'scenario'=>'Scenario', 'birthday'=>'Birthday', 'birthPlace'=>'Place of birth', 'height'=>'Height', 'weight'=>'Weight', 'eye_c'=>'Eye color', 'eye_s'=>'Eye style', 'hair_c'=>'Hair color', 'hair_s'=>'Hair style', 'hair_l'=>'Hair length', 'makeup'=>'Makeup', 'clothing'=>'Clothing', 'addit_appearance'=>'Additional appearance details', 'history'=>'History', 'likes'=>'Likes', 'dislikes'=>'Dislikes', 'addit_desc'=>'Additional description', 'relationships'=>'Relationships', 'dom_sub'=>'Dominant/Submissive', 'prefs'=>'Preferences', 'addit_adult'=>'Additional adult description', 'spirit_status'=>'Status', 'spirit_condition'=>'Condition', 'spirit_alignment'=>'Alignment', 'spirit_sub_alignment'=>'Sub-Alignment', 'spirit_death_place'=>'Place of death', 'spirit_death_cause'=>'Cause of death', 'spirit_death_date'=>'Dead since', 'spirit_type'=>'Type', // Orientations 'straight'=>'Straight', 'gay'=>'Gay', 'lesbian'=>'Lesbian', 'bi'=>'Bisexual', 'omnisexual'=>'Omnisexual', 'pansexual'=>'Pansexual', 'asexual'=>'Asexual', 'noGo'=>'Not Interested', // dom/sub 'dom'=>'Dominant', 'sub'=>'Submissive', // Genders 'male'=>'Male', 'female'=>'Female', 'herm'=>'Herm', 'maleherm'=>'Maleherm', 'shemale'=>'Shemale', 'cuntboi'=>'Cuntboi', 'shifter'=>'Gendershifter', 'genderless'=>'Genderless', // Scenarios 'pic-only'=>'Pic-Only', 'simple'=>'Simple', 'detailed'=>'Detailed', 'advanced'=>'Advanced', // Position 'main'=>'Main', 'casual'=>'Casual', 'unplayed'=>'Unplayed', // category //'pic-only'=>'Pic-Only', <- Already defined above. No need to redefine. 'eng'=>'English', 'ger'=>'German', // Sections 'basic'=>'Basic Details', 'body'=>'Body', 'appearance'=>'Appearance', 'spirit'=>'Spirit', 'adult'=>'Adult', //'history'=>'History', <-- already defined above. //'likes'=>'Likes', //'dislikes'=>'Dislikes', //'relationships'=>'Relationships', //'addit_desc'=>'Additional Description', 'literature'=>'Literature', 'upload'=>'Upload picture', // spirit 'spirit_t_lightful'=>'Lightful being', 'spirit_t_darkness'=>"Darkness' being", 'spirit_t_bad'=>"Darkness' being", 'spirit_s_alive'=>'Alive', 'spirit_s_dead'=>'Dead', 'spirit_c_healthyHappy'=>'Happy&Healthy', 'spirit_c_happySick'=>'Sick but happy', 'spirit_c_depressed'=>'Depressed', 'spirit_c_sad'=>'Sad', 'spirit_c_alone'=>'Alone', 'spirit_c_raging'=>'Raging', 'spirit_c_mixed'=>'Mixed', 'spirit_a_good'=>'Good', 'spirit_a_neutral'=>'Neutral', 'spirit_a_bad'=>'Bad', 'spirit_sa_lawful'=>'Lawful', 'spirit_sa_middle'=>'Middle', 'spirit_sa_chaotic'=>'Chaotic', // uploader 'Uexists'=>'File exists.', 'Uforbidden'=>'File type not allowed for uploading.', 'Unoinput'=>'No input given for description.', 'Udescadded'=>'Description successfully updated!', 'Utoobig'=>'File is too large.', // deletion 'del_really'=>'Do you really want to delete this character?', 'del_yes'=>'Yes, delete this character', 'del_no'=>'No, keep character and return to last page', // profile 'email'=>'E-Mail address', 'nick'=>'Nickname', 'firstname'=>'First name', 'lastname'=>'<NAME>', 'ims'=>'Instant messengers', 'msn'=>'Windows Live', 'skype'=>'Skype', 'furrystuff'=>'Furry related websites', 'fa'=>'Furaffinity', 'sf'=>'SoFurry', 'ytk'=>'Yiffy International', 'fn'=>'FurNation', // other profiles 'hasMainChars'=>"{user}'s main characters", 'hasCasualChars'=>"{user}'s casual characters", 'hasUnplayedChars'=>"{user}'s unplayed characters", // pm 'pm_new'=>'New private message', 'pm_send'=>'Send a new private message', 'pm_trash'=>'Message trash', // forum 'new_topic'=>'New topic', 'new_post'=>'New post', 'new_category'=>'New category', 'delete_topic'=>'Delete topic', 'move_topic'=>'Move topic', 'rename_topic'=>'Rename topic', 'delete_category'=>'Delete category', 'edit_post'=>'Edit post', 'editedPost'=>'Edited at {date} by {editor}', 'delete_post'=>'Delete post', // commons 'reply'=>'Reply', 'watch'=>'Watch', 'unwatch'=>'Unwatch', 'fave'=>'Favorite', 'unfave'=>'Unfaorite', 'report'=>'Report', 'notification'=>'Notification', ); ?><file_sep>/protected/views/manage/themes.php <h1><?=Yii::t("admin","mThemes")?></h1> <?=Yii::t("admin","tDesc")?> <div id="splitblock"> <div id="split"> <h3>Themes</h3> <?php $this->widget("zii.widgets.grid.CGridView",array( 'dataProvider'=>$dp, 'columns'=>array( 'id', 'name', 'gstart', 'gend', 'shadow' ) )); ?> </div> <div id="split"> <h3><?=Yii::t("admin","aTheme")?></h3> <?php $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'verticalForm', )); echo $form->textFieldRow($theme, 'name', array('class'=>'span7')); echo $form->textFieldRow($theme, 'gstart', array('class'=>'span7')); echo $form->textFieldRow($theme, 'gend', array('class'=>'span7')); echo $form->textFieldRow($theme, 'shadow', array('class'=>'span7')); echo "<br>"; $this->widget('bootstrap.widgets.TbButton', array('buttonType'=>'submit', 'label'=>'Add', 'type'=>'success')); $this->endWidget(); ?> </div> </div><file_sep>/protected/modules/charaBase/views/maintain/form.php <?php $this->layout='//layouts/column1'; $pic_only = array();$simple = array();$detailed = array();$advanced = array(); foreach(array('nickName','name','sex','orientation','species') as $label) { $pic_only[] = CHtml::activeName($model,$label); } foreach(array('nickName','name','sex','orientation','species','height', 'weight', 'history','birthday','birthPlace','likes','dislikes') as $label) {$simple[]=CHtml::activeName($model,$label);} foreach( array('nickName','name','sex','orientation','species', 'height', 'weight','birthday','birthPlace', 'history','addit_desc','likes', 'dislikes', 'relationships', 'nickName','dom_sub', 'prefs', 'addit_adult') as $label) {$detailed[]=CHtml::activeName($model,$label);} foreach(array('name','sex','orientation','species','height', 'weight', 'nickName','birthPlace','birthday', 'clothing','makeup','addit_appearance', 'eye_c','eye_s','hair_c','hair_l','hair_s', 'history','likes','dislikes','addit_desc','relationships', 'dom_sub','prefs','addit_adult', 'spirit_status','spirit_condition','spirit_alignment','spirit_sub_alignment','spirit_type', 'spirit_death_date','spirit_death_cause','spirit_death_place') as $label) {$advanced[]=CHtml::activeName($model,$label);} ?> <script type="text/javascript"> scenarios = { pic_only: ["<?=implode('","',$pic_only)?>"], simple: ["<?=implode('","',$simple)?>"], detailed: ["<?=implode('","',$detailed)?>"], advanced: ["<?=implode('","',$advanced)?>"], data: ['pic_only','simple','detailed','advanced'], }; function CBDisplay(sID) { $('input,textarea,select,small,div.control-group,#YouDontNeedToSeeThis').hide(); $('[name="<?=CHtml::activeName($model,"category")?>"],'+ '[name="<?=CHtml::activeName($model,"position")?>"],'+ '[name="<?=CHtml::activeName($model,"scenario")?>"],#Character_cpic_desc').show(); var sData = scenarios[scenarios.data[sID]]; for(var key in sData) { $('[name="'+sData[key]+'"]').parent().parent().show(); $('[name="'+sData[key]+'"]').parent().show(); $('[name="'+sData[key]+'"]').show(); } switch(sID) { case "0": $('[name="appearance"],[name="spirit"],[name="body"],[name="history"],[name="likes"],[name="dislikes"],[name="relationships"],'+ '[name="adult"],[name="addit_desc"],[name="literature"]').hide(); $('[name="basic"]').show(); break; case "1": $('[name="appearance"],[name="spirit"],[name="likes"],[name="dislikes"],[name="adult"],[name="relationships"],[name="addit_desc"]').hide(); $('[name="basic"],[name="body"],[name="literature"]').show(); $('[name="history"],[name="likes"],[name="dislikes"]').show(); break; case "2": $('[name="appearance"],[name="spirit"]').hide(); $('[name="basic"],[name="body"],[name="likes"],[name="dislikes"],[name="adult"],[name="relationships"],[name="literature"],[name="addit_desc"]').show(); break; case "3": $('h3,[name="literature"],hr').show(); break; } $('.descBox, #themePicker').show(); $("#ajaxChatContent #ajaxChatInputFieldContainer #ajaxChatInputField").show(); $("#langPick").show(); } function postUpdate(filename,desc) { $.ajax({ type: "get", url: "<?=CHtml::normalizeUrl(array('maintain/cpic'))?>", data: {Fname:filename,Fdesc:desc}, }).done(function(data) { console.log(data); }); } </script><?php Yii::app()->clientScript->registerScript('cbChange','CBDisplay($("#Character_scenario").val());',CClientScript::POS_READY); ?> <?php $this->widget('ext.widgets.loading.LoadingWidget'); ?> <fieldset><?php /** @var BootActiveForm $form */ $form = $this->beginWidget('bootstrap.widgets.TbActiveForm', array( 'id'=>'horizontalForm', 'type'=>'horizontal', 'enableAjaxValidation' => false, 'htmlOptions' => array( 'enctype' => 'multipart/form-data' ), )); ?> <?php echo CHtml::errorSummary($model); ?> <?php echo '<h2>'.$model->getAttributeLabel('name').': '.CHtml::activeTextField($model,"name"); echo '&nbsp;&nbsp;&nbsp;<small name="'.$model->getAttributeLabel("nickName").'"><b>'.$model->getAttributeLabel("nickName")." ".CHtml::activeTextField($model,"nickName")."</b></small></h2>"; echo '<h4>'.$model->getAttributeLabel('scenario').": ". CHtml::activeDropDownList($model,'scenario', array($CBT->scenario(0),$CBT->scenario(1), $CBT->scenario(2),$CBT->scenario(3)), array('onchange'=>'CBDisplay(this.value);if(this.value=="0"){$("#Character_category").val(0);}else{$("#Character_category").val(1);}')). "&nbsp;&nbsp;".$model->getAttributeLabel('category').": ". CHtml::activeDropDownList($model,"category", array($CBT->category(0),$CBT->category(1),$CBT->category(2)), array('onchange'=>'if(this.value==0){$("#Character_scenario").val(0);CBDisplay("0");}else{$("#Character_scenario").val(1);CBDisplay("1");}')). "&nbsp;&nbsp;".$model->getAttributeLabel('position').": ". CHtml::activeDropDownList($model,"position",array($CBT->position(0),$CBT->position(1))). '</h4>'; ?> <div id="splitblock"> <div id="split"> <?php $data = array('species','sex','orientation','birthPlace','birthday'); echo '<h3 name="basic">'.Yii::t('charaBaseModule.cb','basic').'</h3>'; foreach($data as $label) { switch($label) { case 'sex': $html = $form->dropDownListRow($model,$label, array($CBT->sex(0),$CBT->sex(1),$CBT->sex(2),$CBT->sex(3),$CBT->sex(4), $CBT->sex(5),$CBT->sex(6),$CBT->sex(7)) ); break; case 'birthday': $html = $form->textFieldRow($model, $label,array('hint'=>"Format: TT.MM.JJJJ<br> If unknown: 00.00.0000 or blank")); break; case 'orientation': $html = $form->dropDownListRow($model,$label,array( $CBT->orientation(0),$CBT->orientation(1),$CBT->orientation(2), $CBT->orientation(3),$CBT->orientation(4),$CBT->orientation(5), $CBT->orientation(6), ) ); break; default: $html = $form->textFieldRow($model, $label); break; } echo '<div name="'.CHtml::activeName($model,$label).'">'.$html.'</div>'; } ?><br> <?php $data = array('height','weight','eye_c','eye_s','hair_c', 'hair_s', 'hair_l'); echo '<h3 name="body">'.Yii::t('charaBaseModule.cb','body').'</h3>'; foreach($data as $label) { echo $form->textFieldRow($model, $label); } ?> </div> <div id="split"> <?php $data = array('makeup','clothing','addit_appearance'); echo '<h3 name="appearance">'.Yii::t('charaBaseModule.cb','appearance').'</h3>'; foreach($data as $label) { switch($label) { case 'addit_appearance': $html = $form->textAreaRow($model,$label,array('class'=>'miniText')); break; default: $html = $form->textFieldRow($model, $label); break; } echo $html; } ?><br> <?php $data = array( 'spirit_status','spirit_condition','spirit_alignment', 'spirit_sub_alignment', 'spirit_type', 'spirit_death_place', 'spirit_death_date', 'spirit_death_cause' ); echo '<h3 name="spirit">'.Yii::t('charaBaseModule.cb','spirit').'</h3>'; foreach($data as $label) { switch($label) { case 'spirit_death_date': $html = $form->textFieldRow($model, $label,array('hint'=>"Format: TT.MM.JJJJ<br> If unknown: 00.00.0000 or blank")); break; case 'spirit_status': $html = $form->dropDownListRow($model,$label,array( $CBT->spirit_status(0),$CBT->spirit_status(1))); break; case 'spirit_condition': $html = $form->dropDownListRow($model,$label,array( $CBT->spirit_condition(0),$CBT->spirit_condition(1),$CBT->spirit_condition(2), $CBT->spirit_condition(3),$CBT->spirit_condition(4),$CBT->spirit_condition(5), )); break; case 'spirit_alignment': $html = $form->dropDownListRow($model,$label,array( $CBT->spirit_alignment(0),$CBT->spirit_alignment(1),$CBT->spirit_alignment(2), )); break; case 'spirit_sub_alignment': $html = $form->dropDownListRow($model,$label,array( $CBT->spirit_sub_alignment(0),$CBT->spirit_sub_alignment(1),$CBT->spirit_sub_alignment(2), )); break; case 'spirit_type': $html = $form->dropDownListRow($model,$label,array( $CBT->spirit_type(0),$CBT->spirit_type(1), )); break; default: $html = $form->textFieldRow($model, $label); break; } echo $html; } ?> </div> </div> <div id="clearup"></div> <?php echo '<hr name="literature"><h1 style="padding-top: 20px; padding-bottom: 25px;" name="literature">'.Yii::t('charaBaseModule.cb','literature').'</h1>'; ?> <?php echo '<h3 name="history">'.Yii::t('charaBaseModule.cb','history').'</h3><br>'; echo CHtml::activeTextArea($model,'history',array('class'=>'bigText')); ?> <?php echo '<h3 name="addit_desc">'.Yii::t('charaBaseModule.cb','addit_desc').'</h3><br>'; echo CHtml::activeTextArea($model,'addit_desc',array('class'=>'bigText')); ?> <div id="splitblock"> <div id="split"> <?php $data = array('likes'); echo '<h3 name="likes">'.Yii::t('charaBaseModule.cb','likes').'</h3>'; foreach($data as $label) { echo CHtml::activeTextArea($model,$label,array('class'=>'smallText'))."<br>"; } ?> </div> <div id="split"> <?php $data = array('dislikes'); echo '<h3 name="dislikes">'.Yii::t('charaBaseModule.cb','dislikes').'</h3>'; foreach($data as $label) { echo CHtml::activeTextArea($model,$label,array('class'=>'smallText'))."<br>"; } ?> </div> </div> <div id="clearup"></div> <div id="splitblock"> <div id="split"> <?php $data = array('relationships'); echo '<h3 name="relationships">'.Yii::t('charaBaseModule.cb','relationships').'</h3>'; foreach($data as $label) { echo CHtml::activeTextArea($model,$label,array('class'=>'smallText'))."<br>"; } ?> </div> <div id="split"> <?php $data = array('dom_sub', 'prefs','addit_adult'); echo '<h3 name="adult">'.Yii::t('charaBaseModule.cb','adult').'</h3>'; foreach($data as $label) { switch($label) { case 'addit_adult': $html = $form->textAreaRow($model,$label,array('class'=>'miniText')); break; case 'dom_sub': $html = $form->dropDownListRow($model,$label,array($CBT->ds(0),$CBT->ds(1))); break; default: $html = $form->textFieldRow($model, $label); break; } echo $html."<br>"; } ?> </div> </div> <?php echo CHtml::activeTextField($model,'cpic',array("type"=>"hidden")); ?> <?php $this->endWidget(); ?> <div id="clearup"></div> <div id="splitblock"> <h2>Uploads</h2> <?php $code = ' $("#cpic").fileupload({ url: "'.CHtml::normalizeUrl(array('cpic/save')).'", dataType: "json", maxFileSize: 5000000, acceptFileTypes: ["jpg","gif","bmp","png","JPG","GIF","BMP","PNG","JPGEG","jpeg"], error: function(e,data) { console.log("Error: ",data); }, add: function (e, data) { $.each(data.files, function(index,file){ var ext = file.name.split(".").pop(); var exts = $("#cpic").fileupload("option","acceptFileTypes"); //console.log("acc: ",exts); if($.inArray(ext, exts) == -1) { alert("Selected file is disallowed"); } else { Loading.show(); data.submit(); } }); }, done: function (e, data) { Loading.hide(); if(data.result.error==true) { alert("Error: "+data.result.msg); } else { $.each(data.result, function (index, file) { //console.log("working:"+file); //console.log("file nr:"+file); $("#"+file).empty(); det = $("<div />") .attr("class","splitblock") .attr("id",file) .append( $("<div/>") .attr("id","imgDiv") .append( $("<img />") .attr("class","show") .attr("src","'.(isset($model->cID) ? CHtml::normalizeUrl(array('cpic/view', 'ID'=>$model->cID)) : CHtml::normalizeUrl(array('cpic/view')) ).'/pid/"+file) ) ) .append($("<div/>") .attr("id","imgDiv") .append( $("<a/>") .attr("href","'.(isset($model->cID) ? CHtml::normalizeUrl(array('cpic/view', 'ID'=>$model->cID)) : CHtml::normalizeUrl(array('cpic/view')) ).'/pid/"+file) .html("Link to image") ) .append( $("<a/>") .attr("class","btn btn-danger btn-mini") .attr("href","#") .click(function(e){ e.preventDefault(); $.ajax({ url: "'.(isset($model->cID) ? CHtml::normalizeUrl(array('cpic/delete', 'ID'=>$model->cID)) : CHtml::normalizeUrl(array('cpic/delete')) ).'/pid/"+file, //dataType: "JSON", type: "GET", success: function(data){ console.log("ajax(del):",data); $("#"+file).html(null); }, }); }) .html("X") ) .append($("<br/>")) .append( $("<p/>").html("File name: <b>"+file.name+"</b> ("+Math.round( file.size*1/1000 )+"KB)") ) .append($("<p/>") .html("Full file URL: ") .append($("<input/>") .attr("type","text") .attr("readonly","readonly") .attr("class","span8 uneditable-input descBox") .val("'.(isset($model->cID) ? $this->createAbsoluteUrl('cpic/view',array('ID'=>$model->cID)) : $this->createAbsoluteUrl('cpic/view') ).'/pid/"+file) ) ) .append($("<span/>") .attr("class","goCenter") .html("Description: ") .append($("<input/>") .attr("type","text") .attr("class","span7 descBox") .attr("id","Character_cpic_desc_"+file) ) .append($("<a/>") .attr("class","btn btn-success btn-small rightWalk") .attr("href","#") .html("Update") .click(function(e){ e.preventDefault(); console.log("ready: "+file); console.log("desc: "+$("#Character_cpic_desc_"+file).val()); var desc = $("#Character_cpic_desc_"+file).val(); $.ajax({ url: "'.CHtml::normalizeUrl(array('cpic/desc')).'", //dataType: "JSON", type: "POST", data: {input: desc, pid: file}, success: function(data){ console.log("ajax:",data); $("#desc_"+file).html("Updated description."); }, }); }) ) .append($("<div/>") .attr("id","desc_"+file) ) ) .append( $("<div/>").attr("id","scs_"+file) ) ) .append( $("<div/>").attr("id","clearup") ) .append( $("<br/>") ); //console.log("det",det); $("#cpicList").append(det); }); } }, });'; ?> <?php $refresh = 'function refreshCpic(){$.getJSON("'.CHtml::normalizeUrl(array('cpic/list')).'",function(ares){ console.log(ares); var data = {result: ares}; $("#cpic").fileupload("option","done")(null, data); });}'; ?> <?php Yii::app()->clientScript ->registerScriptFile($this->module->assetsUrl.'/js/vendor/jquery.ui.widget.js',CClientScript::POS_HEAD) ->registerScriptFile($this->module->assetsUrl.'/js/jquery.iframe-transport.js',CClientScript::POS_HEAD) ->registerScriptFile($this->module->assetsUrl.'/js/jquery.fileupload.js',CClientScript::POS_HEAD) ->registerScriptFile($this->module->assetsUrl.'/js/libs/load-image.min.js',CClientScript::POS_HEAD) ->registerScriptFile($this->module->assetsUrl.'/js/libs/canvas-to-blob.min.js',CClientScript::POS_HEAD) ->registerScript('fileUploader',$code,CClientScript::POS_READY) ->registerScript('refreshCpics',$refresh,CClientScript::POS_HEAD) ->registerScript('runRefreshCpics',"refreshCpic();",CClientScript::POS_READY); ?> <p id="cpicList"></p> <div id="resource"></div> <div id="YouDontNeedToSeeThis"> <div id="delete" style="display:none;"> <?php $this->widget('bootstrap.widgets.TbButton', array('label'=>'X','type'=>'danger','size'=>'mini')); ?> </div> </div> </div> <div id="clearup"></div> <div style="text-align:center;"> <?php $this->widget('bootstrap.widgets.TbButton', array( 'label'=>Yii::t('charaBaseModule.cb','upload').' (max: '.(int)ini_get('post_max_size').'MB)', 'type'=>'inverse', 'size'=>'small', 'htmlOptions'=>array( 'onclick'=>'$("#cpic").click()' ), )); ?> <?=CHtml::activeFileField($model,'cpic',array('name'=>'cpic','id'=>'cpic',/*'multiple'=>'multiple'*/))?><br> <?php $this->widget('bootstrap.widgets.TbButton', array( 'buttonType'=>'submit', 'type'=>'primary', 'label'=>'Submit', 'size'=>'small', 'htmlOptions'=>array( 'onclick'=>'$("#horizontalForm").submit();' ) )); ?> </div> </fieldset><file_sep>/protected/modules/mall/lib/class/AJAXChatFileSystem.php <?php /* * @package AJAX_Chat * @author <NAME> * @copyright (c) <NAME> * @license GNU Affero General Public License * @link https://blueimp.net/ajax/ * @edited <NAME> <<EMAIL>> */ // Debug ini_set('display_errors', 1); error_reporting(E_ALL); // Class to provide methods for file system access: class AJAXChatFileSystem extends Controller { // completly overwritten... public static function getFileContents($file) { try{ $real=Yii::getPathOfAlias("chat").$file; ob_start(); if(file_exists($file)) include($file); else include($real); $buffer = '<?xml version="1.0" encoding="[CONTENT_ENCODING/]"?>'."\n"; $buffer.= ob_get_contents(); ob_end_clean(); return( $buffer ); } catch (Exception $e) { echo "Error: "; print_r($e); } } } ?><file_sep>/protected/modules/forum/controllers/BoardController.php <?php class BoardController extends Controller { public function filters() { return array( 'accessControl'); } public function accessRules() { return array( array('allow', 'actions'=>array('create','edit','delete'), 'users'=>array('@'), ), array('deny', 'actions'=>array("create",'edit','delete'), 'users'=>array('*'), ), ); } public function actionCreate($id) { $board = new ForumBoards; $category = ForumCategories::model()->findByPk($id); if(!isset($_POST['ForumBoards'])) { $this->render("form",array("board"=>$board)); } else { $board->attributes=$_POST['ForumBoards']; if($board->save()) { if(($cboards = unserialize($category->boards)) != false) { if(!in_array($board->id,$cboards)) { $cboards[]=$board->id; $category->boards=serialize($cboards); $category->update(); } } else { $category->boards=serialize(array($board->id)); $category->update(); } $this->redirect(array("view/board","id"=>$board->id)); } else { $this->render("form",array("board"=>$board)); } } } public function actionEdit($id) { $board = ForumBoards::model()->findByPk($id); if(!isset($_POST['ForumBoards'])) { $this->render("form",array("board"=>$board)); } else { $category->attributes=$_POST['ForumBoards']; if($category->save()) { $this->redirect(array("view/board","id"=>$board->id)); } else { $this->render("form",array("board"=>$board)); } } } public function actionDelete($id) { $board = ForumBoards::model()->findByPk($id); if($board != null) { $board->delete(); $this->redirect("/view/index"); } else throw new CException("Could not delete board."); } } ?><file_sep>/protected/controllers/ThemepickerController.php <?php class ThemepickerController extends Controller { public $themes = array(); public $themeList=array(); public function beforeAction($a) { $t = Themes::model()->findAll(); // merge the drag0n theme into it. $t = array_merge(array( array( 'id'=>'-1', 'name'=>'Viatropolis', 'gstart'=>null, 'gend'=>null, 'shadow'=>null ) ),$t); foreach($t as $theme) { $theme=(object)$theme; $this->themes[$theme->name] = array( 'gstart'=>$theme->gstart, 'gend'=>$theme->gend, 'shadow'=>$theme->shadow ); $this->themeList[$theme->id] = $theme->name; } return true; } public function actionSet($id,$for="site") { $baseSite = Yii::app()->theme->baseUrl."/css/drag0n.css.php"; $baseChat = Yii::app()->getModule("chat")->assetsUrl."/css/drag0n.css.php"; $theme = $this->themes[$this->themeList[$id]]; if($this->themeList[$id]!="drag0n") { $query = "?"; foreach($theme as $key=>$val) { if(!empty($val)) { $query .="$key=".urlencode($val)."&"; } } if(!isset($theme['shadow'])) { $query .="shadow=$shd&"; } $query = substr($query,0,-1); $stringSite = $baseSite.$query; $stringChat = $baseChat.$query; } else { $stringSite = $baseSite; $stringChat = $baseChat; } Yii::app()->request->cookies["themepicker"] = new CHttpCookie("themepicker", $stringSite); Yii::app()->request->cookies["themepickerChat"] = new CHttpCookie("themepickerChat", $stringChat); Yii::app()->request->cookies["themepickerTheme"] = new CHttpCookie("themepickerTheme", $id); switch($for) { case "site": echo $stringSite; break; case "chat": echo $stringChat; break; } } public function actionGet() { echo json_encode($this->themeList); } public function actionDefault() { if(isset($_COOKIE["themepickerTheme"])) echo $_COOKIE["themepickerTheme"]; else echo -1; } } ?><file_sep>/readme.md # Well, hey there. Viatropols v4t2 - 05/29/2013<file_sep>/protected/modules/mall/controllers/ViewController.php <?php class ViewController extends Controller { public function actionIndex($id) { $channel = AJAXChatChannels::model()->findByPk($id); $this->render("index",array("channel"=>$channel)); } } ?><file_sep>/protected/messages/en/info.php <?php //about the place $Tabout = "What can Global Conscious Mission do for you...."; $about = <<<EOF This is a system built by Viatropolis for all Global Conscious Shoppers to put everything you would ever need for a Green planet in one location.<br><br> Our Numbers:<br> <div id="splitblock"> <div id="split">300+ Merchants<br> 400,000+ Global Shoppers<br> 200+ Showrooms and offices<br> Weekly Mall Newsletters<br></div> <div id="split">Open 24/7/365<br> Special pricing for all shoppers<br> Monthly Keynot Event Days<br><br></div> </div> <br><br> We are building a community that will help change the world. These shopppers are looking for you now!<br><br> <b>Stores, Kiosks and Aisle Displays<b><br> All stores are custom designed to meet your brand, your logo, colors and fonts. Eatch store comes with up to ten links, and animated virtual host, directory listings, group listing, and free shopping cart with up to nine mall special items.<br> All kiosks are custom desgned to meet your brand, your logo, colors and fonts. Each kiosk comes with up to five links, directory listing, group listing, and free shopping cart with up to three mall special items.<br> All Aisle Displays are custom designed to meet your brand, your logo, colors and fonts. Each Display comes with up to three links: Visit our Web Page, Our Brochure, and Contact Us. <br><br> Currently Available:<br><br> Stores<br> Kiosks<br> Aisle Displays<br> Green Buildings Tower - West Wing<br> International Office Tower - East Wing<br><br> <hr> <h2>The team</h2> <ul> <dt><NAME> <small> Owner / Operator</small></dt> <dd>Need Information</dd><br> <dt><NAME><small> Lead Sales</small></dt> <dd>Need Information</dd><br> <dt>????<small> ????</small></dt> <dd>Need Information</dd><br> <dt>????<small> ????</small></dt> <dd>Need Information</dd><br> <dt>???? <small> ????</small></dt> <dd>Need Information</dd><br> </ul> <br><br> Design and Development: <ul> <li><NAME>: Admin, VP/Director of Technology, Development: VT 4.2 <a href="mailto:<EMAIL>">Email</a></li> <li><NAME>: Admin, English/German, Development: Bird 2.0 / VT 4.2 <a href="mailto:<EMAIL> ">Email</a></li> </ul> EOF; //donation! $Tdonation = " "; $donation = <<<EOF <br><br><center><h3>Help this place staying alive!</h3></center><br><br> This place was made out of nothing but an idea. I am paying all the server costs and maintaining and administrating everything entirely on my own! So if you are thankful for the gorgerous afford I am putting into this, then please donate. It can be a small donation even! Use the paypal button below, or donate straight to my email: <EMAIL><br><br> Donators will be VIP'd and named in the credits. EOF; $Tcontact = "Contact Global Conscious Mission"; $contact = <<<EOF You can contact the staff quite easyly. The following contact informations should not be used for spamming!<br><br><br> <b><NAME></b> <ul> <li>Public email: <a href="<EMAIL>"><EMAIL></a></li> </ul><br> <b><NAME></b> <ul> <li>Public email: <a href="<EMAIL>"><EMAIL></a></li> </ul> EOF; return array( 'Tabout'=>$Tabout, 'about'=>$about, //'Tdonation'=>$Tdonation, //'donation'=>$donation, 'Tcontact'=>$Tcontact, 'contact'=>$contact, ); ?><file_sep>/protected/modules/charaBase/messages/de/cb.php <?php return array( // CharaBase translation: English // By <NAME> 'name'=>"Name", 'nickName'=>'Spitzname', 'sex'=>'Geschlecht', 'orientation'=>'Orientierung', 'species'=>'Spezies', 'category'=>'Kategorie', 'position'=>'Position', 'scenario'=>'Szene', 'birthday'=>'Geburtstag', 'birthPlace'=>'Geburtsort', 'height'=>'Größe', 'weight'=>'Gewicht', 'eye_c'=>'Augenfarbe', 'eye_s'=>'Augenart', 'hair_c'=>'Haarfarbe', 'hair_s'=>'Haarstyle', 'hair_l'=>'Haarlänge', 'makeup'=>'Makeup', 'clothing'=>'Style (Anziehsachen)', 'addit_appearance'=>'Zusätzliche Details', 'history'=>'Geschichte', 'likes'=>'Interressen', 'dislikes'=>'Abneigungen', 'addit_desc'=>'Sonstiges', 'relationships'=>'Freundschaften&Beziehungen', 'dom_sub'=>'Dominant/Zurückhaltend', 'prefs'=>'Präferenz', 'addit_adult'=>'Zusätzliche erwachsenenbeschreibungen', 'spirit_status'=>'Status', 'spirit_condition'=>'Kondition', 'spirit_alignment'=>'Zugehörigkeit', 'spirit_sub_alignment'=>'2. Zugehörigkeit', 'spirit_death_place'=>'Todesort', 'spirit_death_cause'=>'Todesursache', 'spirit_death_date'=>'Tot seit', // Orientierungen 'straight'=>'Heterosexuell', 'gay'=>'Homosexuell', 'lesbian'=>'Lesbisch', 'bi'=>'Bisexuel', 'omnisexual'=>'Omnisexuel', 'pansexual'=>'Pansexuel', 'asexual'=>'Asexuel', 'noGo'=>'Nicht interessiert', // dominant/Scheu 'dom'=>'Dominant', 'sub'=>'Zurückhaltend (Scheu)', // Genders 'male'=>'Männlich', 'female'=>'Weiblich', 'herm'=>'Zwitter', 'maleherm'=>'Zwitter (Männlich)', 'shemale'=>'Transwestit', 'cuntboi'=>'Cuntboi', 'shifter'=>'Geschlechtswandler', 'genderless'=>'Geschlchtslos', // Szenarios 'pic-only'=>'Nur Fotos', 'simple'=>'Simpel', 'detailed'=>'Detailiert', 'advanced'=>'Erweitert', // Position 'main'=>'Haupt', 'casual'=>'Beiläufig', 'unplayed'=>'Ungespielt', // Kategorie //'pic-only'=>'Nur Bild', <- Already defined above. No need to redefine. 'eng'=>'Englisch', 'ger'=>'Deutsch', // Sektionen 'basic'=>'Basisdetails', 'body'=>'Körper', 'appearance'=>'Aussehen', 'spirit'=>'Geist', 'adult'=>'Erwachsen', //'history'=>'Geschichte', <-- already defined above. //'likes'=>'Interessen', //'dislikes'=>'Abneigungen', //'relationships'=>'Freundschaften', //'addit_desc'=>'Zusätzliche beschreibungen', 'literature'=>'Literatur', 'upload'=>'Uploade ein Bild', // spirit 'spirit_t_lightful'=>'Lichtwesen', 'spirit_t_darkness'=>"Finsterniswesen", 'spirit_s_alive'=>'Am Leben', 'spirit_s_dead'=>'Tot', 'spirit_c_healthyHappy'=>'Gesund und Munter', 'spirit_c_happySick'=>'Krank aber Munter', 'spirit_c_depressed'=>'Niedergeschlagen', 'spirit_c_sad'=>'Traurig', 'spirit_c_alone'=>'Aleine', 'spirit_c_raging'=>'Wütend', 'spirit_c_mixed'=>'Gemischt', 'spirit_a_good'=>'Gut', 'spirit_a_neutral'=>'Neutral', 'spirit_a_bad'=>'Böse', 'spirit_sa_lawful'=>'Gerecht', 'spirit_sa_middle'=>'Mittel', 'spirit_sa_chaotic'=>'Chaotisch', // uploader 'Uexists'=>'Bild existiert', 'Uforbidden'=>'Bildtyp ist nicht für den Upload geeignet.', 'Unoinput'=>'Nicht verfügbar.', 'Udescadded'=>'Beschreibung wurde erfolgreich Hochgeladen!', 'Utoobig'=>'Datei ist zu groß.', // Beseitigung 'del_really'=>'Willst du diesen Char wirklich Löschen?', 'del_yes'=>'Ja, diesen Char Löschen.', 'del_no'=>'Nein, Diesen Char berhalten und zur letzten Seite zurückkehren.', ); ?><file_sep>/protected/views/Viatropolis/csingle.php <?php $user = Yii::app()->getModule("user")->user($data->uID); switch($user->superuser) { case 0: $css = "user"; break; case 1: $css = "moderator"; break; case 2: $css = "admin"; break; case -1: $css = "vip"; break; } ?> <?="Owner: ".CHtml::link($user->username,array("/user/user/view","id"=>$data->uID))?><br> <?=Yii::t("CharaBaseModule.cb","name").": ".CHtml::link($data->name,array("/charaBase/view/char",'ID'=>$data->cID))?><br> <?=Yii::t("CharaBaseModule.cb","species").": ".$data->species?><br> <?=Yii::t("CharaBaseModule.cb","sex").": ".CBTranslator::sex($data->sex)?><br> <?=Yii::t("CharaBaseModule.cb","orientation").": ".CBTranslator::orientation($data->orientation)?><br> <hr>
8c23712a17062c49534f744c33e528bcb54038e9
[ "JavaScript", "SQL", "Markdown", "PHP" ]
118
PHP
viatropolis/v4t2
697edc192f7520a532129028658686b799bc900c
20250ae9034468075b3e7f05f1b9b9fc76946084
refs/heads/master
<repo_name>OliangchenO/easytrader<file_sep>/XueQiuUtil.py from datetime import datetime import json import logging import os import random import easytrader import redis from easytrader.log import log import easytrader.sendmail class XueQiuUtil: def __init__(self, debug=True): self.redis_export_time = 86400 self.r = redis.Redis(host='localhost', port=6379, db=0) self.date_str = datetime.now().strftime("%Y-%m-%d") # 获取当前文件路径 self.current_path = os.path.abspath(__file__) # 获取当前文件的父目录 self.father_path = os.path.abspath(os.path.dirname(self.current_path) + os.path.sep + ".") self.user = easytrader.use('xq') self.user.prepare(os.path.join(self.father_path, "xq.json")) self.log_level = logging.DEBUG if debug else logging.INFO self.redis_cookies = [ "xq_a_token=<PASSWORD>; xq_r_token=cf<KEY>", "xq_a_token=<PASSWORD>; xq_r_token=7c<PASSWORD>", "xq_a_token=a<KEY>; xq_r_token=a<KEY>fc4b99f"] def get_cookie(self): redis_cookies = json.loads(self.r.get("xue_qiu_cookies")) return redis_cookies[random.randint(0, len(redis_cookies)-1)] def reset_cookies(self): self.r.set("xue_qiu_cookies", json.dumps(self.redis_cookies)) def del_cookies(self, cookie): self.redis_cookies = json.loads(self.r.get("xue_qiu_cookies")) self.redis_cookies.remove(cookie) self.r.set("xue_qiu_cookies", json.dumps(self.redis_cookies)) def cookies_size(self): self.redis_cookies = json.loads(self.r.get("xue_qiu_cookies")) return len(self.redis_cookies) @staticmethod def sort_by_value(dict_to_sort, reverse): sorted_list = sorted(dict_to_sort.items(), key=lambda d: d[1], reverse=reverse) sorted_dict = {} for o in sorted_list: sorted_dict[o[0]] = o[1] return sorted_dict def get_top_cube_list(self, num): top_cubes_key = "top_cube_symbol_list_" + self.date_str top_cube_symbol_list = None if self.r.get(top_cubes_key) is not None: top_cube_symbol_list = json.loads(self.r.get(top_cubes_key)) if top_cube_symbol_list is None or len(top_cube_symbol_list) < num: top_cube_symbol_list = self.user.get_top_cube_list('YEAR', num) self.r.set(top_cubes_key, json.dumps(top_cube_symbol_list), self.redis_export_time) log.info(top_cube_symbol_list) return top_cube_symbol_list def get_top_cubes_holding(self, symbol): cube_holding_list_key = symbol + "_" + self.date_str holding_list = None if self.r.get(cube_holding_list_key) is not None: holding_list = json.loads(self.r.get(cube_holding_list_key)) if holding_list is None: try: cookies = self.get_cookie() holding_list = self.user.get_position_for_xq(self.cube_symbol, cookies) self.r.set(cube_holding_list_key, json.dumps(holding_list), self.redis_export_time) except Exception as e: log.info(e) self.del_cookies(cookies) if self.cookies_size() == 0: self.time.sleep(1200) self.reset_cookies() cookies = self.get_cookie() try: holding_list = self.user.get_position_for_xq(self.cube_symbol, cookies) except Exception as e: log.info(e) self.r.set(cube_holding_list_key, json.dumps(holding_list), self.redis_export_time) log.info(holding_list) return holding_list def follow_top_cube(self): self.reset_cookies() cube_list = self.get_top_cube_list(100) cubes_holding = {} for cube_symbol in cube_list: cubes_holding[cube_symbol] = self.get_top_cubes_holding(cube_symbol) log.info(cubes_holding) cubes_holding_pre = {} for (cube_symbol, holdings) in cubes_holding.items(): if holdings is not None: for holding_stock in holdings: self.r.set(holding_stock["stock_symbol"], holding_stock["stock_name"], self.redis_export_time) if holding_stock["stock_symbol"] is not None and holding_stock["stock_symbol"] in cubes_holding_pre: weight = float(cubes_holding_pre.get(holding_stock["stock_symbol"])) cubes_holding_pre[holding_stock["stock_symbol"]] = float(holding_stock["weight"]) + weight else: cubes_holding_pre[holding_stock["stock_symbol"]] = float(holding_stock["weight"]) # cube_holdings_rank = sorted(cubes_holding_pre.items(), key=lambda stock: stock[1], reverse=True) cube_holdings_rank = sorted(cubes_holding_pre.items(), key=lambda stock: stock[1], reverse=True) log.info("当前选股排名**********************************************") log.info(cube_holdings_rank) cube_holdings_5 = cube_holdings_rank[0:5] log.info("前五名持仓**************************************") cube_holdings_5_info = {} for code in cube_holdings_5: cube_holdings_5_info.setdefault(code[0], str(self.r.get(code[0]).decode())) log.info(cube_holdings_5_info) log.info("当前持仓:*********************************************") now_holding = self.user.get_position_for_xq() log.info(now_holding) should_buy_list = [] for buy_stock in cube_holdings_5: should_buy_list.append(buy_stock[0]) adjust_info = "调仓成功! " for now_holding_stock in now_holding: stock_symbol = now_holding_stock["stock_symbol"] if stock_symbol not in should_buy_list: # 当前持仓不在备选组合中卖出 self.user.adjust_weight(stock_symbol, 0) adjust_info = adjust_info + "卖出,股票代码:" + stock_symbol + "股票名称:" + self.r.get(stock_symbol) else: should_buy_list.remove(stock_symbol) balance = self.user.get_balance_for_follow() error_code = balance["error_code"] if error_code is None: cash = balance["cash"] if len(should_buy_list) > 0: weight = cash/len(should_buy_list) for buy_stock in should_buy_list: self.user.adjust_weight(buy_stock, weight) adjust_info = adjust_info + "买入,股票代码:" + buy_stock + " ,股票名称:" + self.r.get(buy_stock) + " ,买入比例:" + str(weight) mail = easytrader.sendmail.MailUtils() mail.send_email("<EMAIL>", "调仓成功", adjust_info) <file_sep>/follow_top_cube.py from XueQiuUtil import * xue_qiu = XueQiuUtil() xue_qiu.follow_top_cube() <file_sep>/testlog.py import logging logging.basicConfig(level=logging.DEBUG) logging.debug("This is a debug log.") logging.info("This is a info log.") logging.warning("This is a warning log.") logging.error("This is a error log.") logging.critical("This is a critical log.") <file_sep>/easytrader/sendmail.py import smtplib from email.mime.text import MIMEText import logging class MailUtils: def __init__(self, debug=True): # 设置服务器所需信息 # aliyun邮箱服务器地址 self.mail_host = 'smtp.aliyun.com' # aliyun邮箱用户名 self.mail_user = '<EMAIL>' # 密码(部分邮箱为授权码) self.mail_pass = '<PASSWORD>' # 邮件发送方邮箱地址 self.sender = '<EMAIL>' # 邮件接受方邮箱地址,注意需要[]包裹,这意味着你可以写多个邮件地址群发 self.receivers = ['593705862@qq.com'] self.log_level = logging.DEBUG if debug else logging.INFO def send_email(self, receivers, subject, content): # 设置email信息 # 邮件内容设置 message = MIMEText(content, 'plain', 'utf-8') # 邮件主题 message['Subject'] = subject # 发送方信息 message['From'] = self.sender # 接受方信息 message['To'] = receivers # 登录并发送邮件 try: smtp_obj = smtplib.SMTP() # 连接到服务器 smtp_obj.connect(self.mail_host, 25) # 登录到服务器 smtp_obj.login(self.mail_user, self.mail_pass) # 发送 smtp_obj.sendmail( self.sender, receivers, message.as_string()) # 退出 smtp_obj.quit() print('success') except smtplib.SMTPException as e: print('error', e) # 打印错误 <file_sep>/easytrader/log.py from datetime import datetime import logging.handlers import logging import os import sys def script_path(): path = os.path.realpath(sys.argv[0]) if os.path.isfile(path): path = os.path.dirname(path) return os.path.abspath(path) LOGGING_MSG_FORMAT = "%(asctime)s [%(levelname)s] %(filename)s %(lineno)s: %(message)s" LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' logging.basicConfig(level=logging.INFO, format=LOGGING_MSG_FORMAT, datefmt=LOGGING_DATE_FORMAT) log = logging.getLogger("easytrader") log.propagate = False #文件日志 log_path = os.path.join(script_path(), 'logs') if not os.path.exists(log_path): os.makedirs(log_path) file_name = datetime.now().strftime("%Y-%m-%d") + ".log" log_file = os.path.join(log_path, file_name) fh = logging.handlers.TimedRotatingFileHandler(log_file, 'midnight', 1, 3) fh.suffix = '%Y%m%d.log' fh.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT)) log.handlers.append(fh) #控制台日志 ch = logging.StreamHandler() ch.setFormatter(logging.Formatter(LOGGING_MSG_FORMAT)) log.handlers.append(ch) <file_sep>/log.py #!/usr/bin/env python # coding=utf-8 import logging import time class Logger(object): """ This is the class to wrap logging module """ def __init__(self): self.logger = logging.getLogger() self.logger.setLevel(logging.DEBUG) self.formatter = logging.Formatter('%(asctime)s - %(filename)s[line:%(lineno)d] - %(levelname)s: %(message)s') self.name = None self.path = None self.log_name = None self.log_path = None self.log_file_status = False self.terminal_status = False def log_init(self, path, name): self.name = name self.path = path self.log_name = self.name + time.strftime('_%Y%m%d%H%M', time.localtime(time.time())) self.log_path = self.path + "/" + self.log_name + '.log' def save_log(self, close=False): log_file = logging.FileHandler(self.log_path, "a") log_file.setFormatter(self.formatter) log_file.setLevel("INFO") if not self.log_file_status: self.logger.addHandler(log_file) self.log_file_status = True if close: log_file.close() def print_log(self): terminal = logging.StreamHandler() terminal.setFormatter(self.formatter) terminal.setLevel("INFO") if not self.terminal_status: self.logger.addHandler(terminal) self.terminal_status = True def handel_log(self): self.save_log() self.print_log() return self.logger set_log = Logger() if __name__ == '__main__': set_log.log_init("../logger", 'test') for i in range(0, 10): set_log.handel_log().info("test info") set_log.handel_log().error("test error") time.sleep(1) set_log.save_log(close=True) <file_sep>/easytrader/logger.py import logging from conda.cli.main_config import format_dict # 开发一个日志系统, 既要把日志输出到控制台, 还要写入日志文件 class Logger: def __init__(self, log_name, log_level, logger): ''' 指定保存日志的文件路径,日志级别,以及调用文件 将日志存入到指定的文件中 ''' # 创建一个logger self.logger = logging.getLogger(logger) self.logger.setLevel(log_level) # 创建一个handler,用于写入日志文件 fh = logging.FileHandler(log_name) fh.setLevel(log_level) # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # 定义handler的输出格式 fmt = logging.Formatter( "%(asctime)s [%(levelname)s] %(filename)s %(lineno)s: %(message)s" ) fh.setFormatter(fmt) ch.setFormatter(fmt) # 给logger添加handler self.logger.addHandler(fh) self.logger.addHandler(ch) def get_log(self): return self.logger
c477b9a38580ed3a05922fef92895b3e44957f22
[ "Python" ]
7
Python
OliangchenO/easytrader
6fcc8c6ade46699c921e0d7f9fa569b5f41ad4a7
8850542ea6fe736b23a6e190fba6d58cf9476db3
refs/heads/master
<repo_name>vincentgoay/my_saf_assessment<file_sep>/server/dbutil.js /* Attempting to get: const getGames = mkQuery('select * from game', pool); const getCommentById = mkQuery('select * from comment where gid = ?', pool); */ const mkQuery = function (sql, pool) { const f = function (params) { const p = new Promise( (resolve, reject) => { pool.getConnection( (err, conn) => { if (err) return reject(err); conn.query(sql, params || [], // default empty array (err, result) => { conn.release(); if (err) return reject(err); resolve(result); }) }); } ) return (p); } return (f); } module.exports = mkQuery; <file_sep>/server/server.js /// Load libraries require('dotenv').config(); const express = require('express'); const cors = require('cors'); const morgan = require('morgan'); const path = require('path'); const request = require('request'); const mysql = require('mysql'); const mkQuery = require('./dbutil'); /// Configuration const app = express(); const PORT = process.env.APP_PORT || 3000; // Setup Stanard Middlewares app.use(cors()); app.use(morgan('tiny')); // Setup MySQL const pool = mysql.createPool(require('./config')); // Queries const SEARCH_BOOK_BY_NAME_OR_TITLE = 'Select book_id, title, authors, rating from book2018 where title like ? or authors like ? limit ? offset ?'; const COUNT_BOOKS_SEARCH_BY_NAME_OR_TITLE = 'Select count(*) as book_count from book2018 where title like ? or authors like ?'; const GET_BOOK_BY_ID = 'Select * from book2018 where book_id = ?'; const searchBooksByNameOrTitle = mkQuery(SEARCH_BOOK_BY_NAME_OR_TITLE, pool); const countBooksByNameOrTitle = mkQuery(COUNT_BOOKS_SEARCH_BY_NAME_OR_TITLE, pool); const getBookById = mkQuery(GET_BOOK_BY_ID, pool); /// Define routes app.get('/api/search', (req, res) => { const terms = req.query.terms const searchTerm = `%${terms || ''}%`; const limit = parseInt(req.query.size) || 10; const offset = parseInt(req.query.start) || 0; const p0 = searchBooksByNameOrTitle([searchTerm, searchTerm, limit, offset]); const p1 = countBooksByNameOrTitle([searchTerm, searchTerm]); Promise.all([p0, p1]) .then(results => { const data = results[0]; const countBooks = results[1]; const books = data.map(v => { const authorsArray = String(v['authors']).split('|'); const book = { book_id: v['book_id'], title: v['title'], authors: authorsArray, rating: v['rating'] } return book; }) const bookResponse = { data: books, terms: terms, timestamp: new Date().getTime(), total: countBooks[0]['book_count'], limit: limit, offset: offset } console.log('searchBookByNameOrTitle Result: ', bookResponse); res.status(200) res.format({ 'default': () => { res.type('application/json') .json(bookResponse) } }) }) .catch(error => { const errorResponse = { status: 500, message: error, timestamp: new Date().getTime() } res.statusCode(500).type('application/json') .json(errorResponse); }) }) app.get('/api/book/:id', (req, res) => { const book_id = req.params.id; console.log('BookID: ', book_id); getBookById([book_id]) .then(result => { const book = result[0]; book.authors = String(result[0].authors).split('|') book.genres = String(result[0].genres).split('|') console.log('Book: ', book); res.status(200).type('application/json') .json({ data: book, timestamp: new Date().getTime() }); }) .catch(error => { const errorResponse = { status: 500, message: error, timestamp: new Date().getTime() } res.statusCode(500).type('application/json') .json(errorResponse); }) }) app.get('/api/book/:id/review', (req, res) => { const book_id = req.params.id; getBookById([book_id]) .then(result => { const book = result[0]; book.authors = String(result[0].authors).split('|') console.log('Book: ', book); // NYT Request Option const options = { url: process.env.API_URL, qs: { 'title': book.title, 'api-key': process.env.API_KEY } }; console.log('Options:', options); request(options, (error, response, body) => { if (!error && response.statusCode == 200) { const results = JSON.parse(body)['results']; const reviews = results.map(v => { const review = { book_id: book.book_id, title: book.title, authors: book.authors, byline: v.byline, summary: v.summary, url: v.url }; return review; }); res.status(200).type('application/json') .json({ data: reviews, timestamp: new Date().getTime() }); } else { const errorResponse = { status: 500, message: error, timestamp: new Date().getTime() } res.statusCode(500).type('application/json') .json(errorResponse); } }) }) .catch(error => { const errorResponse = { status: 500, message: error, timestamp: new Date().getTime() } res.statusCode(500).type('application/json') .json(errorResponse); }) }) /// Start application app.listen(PORT, () => { console.log(`Application started listening on ${PORT} at ${new Date()}`); }) <file_sep>/client/src/app/book.service.ts import { Injectable } from "@angular/core"; import { SearchCriteria, BooksResponse, BookResponse, ReviewResponse } from './models'; import { HttpClient, HttpParams, HttpHeaders } from '@angular/common/http'; @Injectable() export class BookService { constructor(private http: HttpClient) { } getBooks(searchCriteria: SearchCriteria): Promise<BooksResponse> { //TODO - for Task 3 and Task 4 let params = new HttpParams() .set('terms', searchCriteria.terms) if (searchCriteria.limit) { params = params.append('size', searchCriteria.limit.toString()); } if (searchCriteria.offset) { params = params.append('start', searchCriteria.offset.toString()); } const headers = new HttpHeaders() .set('Accept', 'application/json'); const url = 'api/search' console.log('API Request: ', url); return this.http.get<BooksResponse>(url, { headers, params}).toPromise(); } getBook(bookId: string): Promise<BookResponse> { //TODO - for Task 5 const url = `api/book/${bookId}`; console.log('API Request: ', url); return this.http.get<BookResponse>(url).toPromise(); } getReviews(bookId: string): Promise<ReviewResponse> { const url = `api/book/${bookId}/review`; console.log('API Request: ', url); return this.http.get<ReviewResponse>(url).toPromise() } }
8ad34c437126168d043cfb74402b911ecb5cbca6
[ "JavaScript", "TypeScript" ]
3
JavaScript
vincentgoay/my_saf_assessment
680205b83dda7548faf36a4c3ecdeb73be7e1b39
9ec4b4fe522c20d3fa990c83fe6412b3c3ee7677
refs/heads/master
<file_sep>package com.qmuiteam.qmui.widget.webview; import android.support.annotation.Nullable; import android.view.View; import android.webkit.WebChromeClient; import java.lang.ref.WeakReference; public class QMUIWebChromeClient extends WebChromeClient { private WeakReference<QMUIWebViewContainer> mWebViewContainer; public QMUIWebChromeClient(@Nullable QMUIWebViewContainer webViewContainer) { mWebViewContainer = new WeakReference<>(webViewContainer); } @Override public void onShowCustomView(View view, CustomViewCallback callback) { QMUIWebViewContainer container = mWebViewContainer.get(); if (container != null) { container.setCustomView(view); } } @Override public void onHideCustomView() { QMUIWebViewContainer container = mWebViewContainer.get(); if (container != null) { container.removeCustomView(); } } } <file_sep>package com.qmuiteam.qmui.widget.webview; import android.annotation.TargetApi; import android.content.Context; import android.content.res.Configuration; import android.graphics.Rect; import android.os.Build; import android.support.annotation.NonNull; import android.support.v4.view.WindowInsetsCompat; import android.util.AttributeSet; import android.view.KeyEvent; import android.view.View; import android.view.ViewGroup; import android.view.WindowInsets; import android.widget.FrameLayout; import com.qmuiteam.qmui.util.QMUINotchHelper; import com.qmuiteam.qmui.widget.QMUIWindowInsetLayout; public class QMUIWebViewContainer extends QMUIWindowInsetLayout { private QMUIWebView mWebView; private View mCustomView; private QMUIWebView.OnScrollChangeListener mOnScrollChangeListener; private Callback mCallback; public QMUIWebViewContainer(Context context) { super(context); } public QMUIWebViewContainer(Context context, AttributeSet attrs) { super(context, attrs); } public void setCallback(Callback callback) { mCallback = callback; } public void addWebView(@NonNull QMUIWebView webView, boolean needDispatchSafeAreaInset) { mWebView = webView; mWebView.setNeedDispatchSafeAreaInset(needDispatchSafeAreaInset); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { mWebView.setOnScrollChangeListener(new OnScrollChangeListener() { @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { if (mOnScrollChangeListener != null) { mOnScrollChangeListener.onScrollChange(v, scrollX, scrollY, oldScrollX, oldScrollY); } } }); } else { mWebView.setCustomOnScrollChangeListener(new QMUIWebView.OnScrollChangeListener() { @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { } }); } addView(mWebView, new FrameLayout.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } public void setCustomView(@NonNull View customView) { mCustomView = customView; addView(customView, new ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { // TODO only support for Android M+ ? if (customView instanceof ViewGroup) { ViewGroup viewGroup = (ViewGroup) customView; if (viewGroup.getChildCount() > 0) { viewGroup.getChildAt(0).setOnScrollChangeListener(new OnScrollChangeListener() { @Override public void onScrollChange(View v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) { if (mOnScrollChangeListener != null) { mOnScrollChangeListener.onScrollChange(v, scrollX, scrollY, oldScrollX, oldScrollY); } } }); } } } if (mCallback != null) { mCallback.onShowCustomView(); } } public void setNeedDispatchSafeAreaInset(boolean needDispatchSafeAreaInset) { if (mWebView != null) { mWebView.setNeedDispatchSafeAreaInset(needDispatchSafeAreaInset); } } public void removeCustomView() { if (mCustomView != null) { removeView(mCustomView); mCustomView = null; if (mCallback != null) { mCallback.onHideCustomView(); } } } public void destroy() { removeView(mWebView); removeAllViews(); mCustomView = null; mWebView.destroy(); } public void setCustomOnScrollChangeListener(QMUIWebView.OnScrollChangeListener onScrollChangeListener) { mOnScrollChangeListener = onScrollChangeListener; } @Override public boolean dispatchKeyEvent(KeyEvent event) { if (event.getKeyCode() == KeyEvent.KEYCODE_BACK && mCustomView != null) { // webView will consume this event and cancel fullscreen state, this is not expected return false; } return super.dispatchKeyEvent(event); } @Override @TargetApi(19) public boolean applySystemWindowInsets19(Rect insets) { if (getFitsSystemWindows()) { Rect childInsets = new Rect(insets); mQMUIWindowInsetHelper.computeInsetsWithGravity(this, childInsets); setPadding(childInsets.left, childInsets.top, childInsets.right, childInsets.bottom); return true; } return super.applySystemWindowInsets19(insets); } @Override @TargetApi(21) public boolean applySystemWindowInsets21(Object insets) { if (getFitsSystemWindows()) { int insetLeft = 0, insetRight = 0, insetTop = 0, insetBottom = 0; if (insets instanceof WindowInsetsCompat) { WindowInsetsCompat windowInsetsCompat = (WindowInsetsCompat) insets; insetLeft = windowInsetsCompat.getSystemWindowInsetLeft(); insetRight = windowInsetsCompat.getSystemWindowInsetRight(); insetTop = windowInsetsCompat.getSystemWindowInsetTop(); insetBottom = windowInsetsCompat.getSystemWindowInsetBottom(); } else if (insets instanceof WindowInsets) { WindowInsets windowInsets = (WindowInsets) insets; insetLeft = windowInsets.getSystemWindowInsetLeft(); insetRight = windowInsets.getSystemWindowInsetRight(); insetTop = windowInsets.getSystemWindowInsetTop(); insetBottom = windowInsets.getSystemWindowInsetBottom(); } if (QMUINotchHelper.needFixLandscapeNotchAreaFitSystemWindow(this) && getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { insetLeft = Math.max(insetLeft, QMUINotchHelper.getSafeInsetLeft(this)); insetRight = Math.max(insetRight, QMUINotchHelper.getSafeInsetRight(this)); } Rect childInsets = new Rect(insetLeft, insetTop, insetRight, insetBottom); mQMUIWindowInsetHelper.computeInsetsWithGravity(this, childInsets); setPadding(childInsets.left, childInsets.top, childInsets.right, childInsets.bottom); return true; } return super.applySystemWindowInsets21(insets); } public int getWebContentScrollY(){ if(mCustomView instanceof ViewGroup && ((ViewGroup)mCustomView).getChildCount() > 0){ ((ViewGroup)mCustomView).getChildAt(0).getScrollY(); }else if(mWebView != null){ return mWebView.getScrollY(); } return 0; } public int getWebContentScrollX(){ if(mCustomView instanceof ViewGroup && ((ViewGroup)mCustomView).getChildCount() > 0){ ((ViewGroup)mCustomView).getChildAt(0).getScrollX(); }else if(mWebView != null){ return mWebView.getScrollX(); } return 0; } public interface Callback { void onShowCustomView(); void onHideCustomView(); } }
e335a04afd80992a24e0662c8ae1a2070d934387
[ "Java" ]
2
Java
erainzhong/QMUI_Android
673d863a30363e28dedc598cbd7f847274ebd062
55d570a249a2f52246ce922725f38c429030ab85
refs/heads/master
<file_sep>class Survey::QuestionsType @@questions_types = {:general => 1} def self.questions_types @@questions_types end def self.questions_types_title titled = {} Survey::QuestionsType.questions_types.each{|k, v| titled[k.to_s.titleize] = v} titled end def self.questions_type_ids @@questions_types.values end def self.questions_type_keys @@questions_types.keys end @@questions_types.each do |key, val| define_singleton_method "#{key}" do val end end end<file_sep>module Survey VERSION = "0.1" end<file_sep>require 'test_helper' class PredefinedValueTest < ActiveSupport::TestCase test "should create a valid predefined_value" do predefined_value = create_predefined_value should_be_persisted predefined_value end test "should not create a predefined_value with a empty or nil name field" do predefined_value_a = create_predefined_value({:name => nil}) predefined_value_b = create_predefined_value({:name => ''}) should_not_be_persisted predefined_value_a should_not_be_persisted predefined_value_b end end<file_sep># Factories # Create a Survey::Survey def create_survey(opts = {}) Survey::Survey.create({ :name => ::Faker::Name.name, :attempts_number => 3, :description => ::Faker::Lorem.paragraph(1) }.merge(opts)) end # Create a Survey::Section def create_section(opts = {}) Survey::Section.create({ :head_number => ::Faker::Name.name, :name => ::Faker::Name.name, :description => ::Faker::Lorem.paragraph(1) }.merge(opts)) end # Create a Survey::Question def create_question(opts = {}) Survey::Question.create({ :text => ::Faker::Lorem.paragraph(1), :options_attributes => {:option => correct_option_attributes}, :questions_type_id => Survey::QuestionsType.general, :mandatory => false }.merge(opts)) end # Create a Survey::PredefinedValue def create_predefined_value(opts = {}) Survey::PredefinedValue.create({ :name => ::Faker::Name.name }.merge(opts)) end # Create a Survey::option but not saved def new_option(opts = {}) Survey::Option.new(option_attributes.merge(opts)) end # Create a Survey::Option def create_option(opts = {}) Survey::Option.create(option_attributes.merge(opts)) end def option_attributes { :text => ::Faker::Lorem.paragraph(1), :options_type_id => Survey::OptionsType.multi_choices } end def correct_option_attributes option_attributes.merge({:correct => true}) end def create_attempt(opts ={}) attempt = Survey::Attempt.create do |t| t.survey = opts.fetch(:survey, nil) t.participant = opts.fetch(:user, nil) opts.fetch(:options, []).each do |option| t.answers.new(:option => option, :question => option.question, :attempt => t) end end end def create_survey_with_sections(num, sections_num = 1) survey = create_survey sections_num.times do section = create_section num.times do question = create_question num.times do question.options << create_option(correct_option_attributes) end section.questions << question end survey.sections << section end survey.save survey end def create_attempt_for(user, survey, opts = {}) if opts.fetch(:all, :wrong) == :right correct_survey = survey.correct_options create_attempt({ :options => correct_survey, :user => user, :survey => survey}) else incorrect_survey = survey.correct_options incorrect_survey.shift create_attempt({ :options => incorrect_survey, :user => user, :survey => survey}) end end def create_answer(opts = {}) survey = create_survey_with_sections(1) section = survey.sections.first question = section.questions.first option = section.questions.first.options.first attempt = create_attempt(:user => create_user, :survey => survey) Survey::Answer.create({:option => option, :attempt => attempt, :question => question}.merge(opts)) end def create_answer_with_option_type(options_type, mandatory = false) option = create_option(:options_type_id => options_type) question = create_question({:questions_type_id => Survey::QuestionsType.general, :mandatory => mandatory}) section = create_section() survey = create_survey() question.options << option section.questions << question survey.sections << section survey.save attempt = create_attempt(:user => create_user, :survey => survey) return survey, option, attempt, question end # Dummy Model from Dummy Application def create_user User.create(:name => Faker::Name.name) end <file_sep>source "https://rubygems.org" gemspec gem "rdoc" group :test do gem 'sqlite3' end <file_sep>class Survey::OptionsType @@options_types = {:multi_choices => 1, :single_choice => 2, :number => 3, :text => 4, :multi_choices_with_text => 5, :single_choice_with_text => 6, :multi_choices_with_number => 7, :single_choice_with_number => 8, :large_text => 9} def self.options_types @@options_types end def self.options_types_title titled = {} Survey::OptionsType.options_types.each{|k, v| titled[k.to_s.titleize] = v} titled end def self.options_type_ids @@options_types.values end def self.options_type_keys @@options_types.keys end @@options_types.each do |key, val| define_singleton_method "#{key}" do val end end end<file_sep>class SurveyTest < ActiveSupport::TestCase test "should not create a valid survey without sections" do survey = create_survey should_not_be_persisted survey end test "should not create a survey with active flag true and empty questions collection" do surveyA = create_survey({:active => true}) surveyB = create_survey_with_sections(2) surveyB.active = true surveyB.save should_not_be_persisted surveyA should_be_persisted surveyB should_be_true surveyB.valid? end test "should create a survey with 3 sections" do num_questions = 3 survey = create_survey_with_sections(num_questions, num_questions) should_be_persisted survey assert_equal survey.sections.size, num_questions end test "should create a survey with 2 questions" do num_questions = 2 survey = create_survey_with_sections(num_questions, 1) should_be_persisted survey assert_equal survey.sections.first.questions.size, num_questions end test "should not create a survey with attempts_number lower than 0" do survey = create_survey({:attempts_number => -1}) should_not_be_persisted survey end test "should not save survey without all the needed fields" do survey_without_name = create_survey({:name => nil}) survey_without_description = create_survey({:description => nil}) %w(name description).each do |suffix| should_not_be_persisted eval("survey_without_#{suffix}") end end end
8d40d0fc709b3a6e045134fbe583caddbe438268
[ "Ruby" ]
7
Ruby
mateo9/questionnaire
542ff3d9c5a7afa3c0b264fce9e264f412468199
f09858f23f61ca378b3a64e33300b86d736529c9
refs/heads/master
<file_sep>import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; import Modal from 'react-bootstrap/Modal'; import Button from 'react-bootstrap/Button'; import Photo from './photo.jsx'; const modal = (props) => { const [showCamera, setShow] = useState(false); useEffect(() => {}, [showCamera]); return ( <div> <Modal show={props.displayModal} onHide={() => { setShow(false); props.close(); }} aria-labelledby='contained-modal-title-vcenter' centered > <Modal.Header closeButton> <Modal.Title> {props.currentPothole.descriptor} :{' '} {props.currentPothole.unique_key} </Modal.Title> </Modal.Header> <Modal.Body> <div> <p>Status: {props.currentPothole.status}</p> <p>Created Date: {props.currentPothole.created_date}</p> <p>Street Name: {props.currentPothole.street_name}</p> <p>City: {props.currentPothole.city}</p> <p>Lat: {props.currentPothole.latitude}</p> <p>Long: {props.currentPothole.longitude}</p> {props.currentPothole.descriptor === 'UserCreated' ? ( <Button variant='success' onClick={(e) => { e.preventDefault(); setShow(true); }} > Click to take Pic ! </Button> ) : ( '' )} {showCamera && props.currentPothole.descriptor === 'UserCreated' ? ( <Photo></Photo> ) : ( '' )} </div> </Modal.Body> </Modal> </div> ); }; export default modal; <file_sep>import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; import Modal from 'react-bootstrap/Modal'; import Button from 'react-bootstrap/Button'; import WeatherAPIKey from '../../config/weatherapi.js'; import axios from 'axios'; const WeatherModal = (props) => { const [weatherData, setWeather] = useState([]); useEffect(() => { axios .get( `http://api.weatherstack.com/current?access_key=${WeatherAPIKey}&query=New York` ) .then((result) => { console.log('Getting Weather Data: ', result); setWeather(result.data); }) .catch((error) => { console.log(error); }); }, []); return ( <Modal show={props.displayModal} onHide={() => { props.close(); }} aria-labelledby='contained-modal-title-vcenter' centered > <Modal.Header closeButton> <Modal.Title>Historical Weather Data</Modal.Title> </Modal.Header> <Modal.Body> <Button variant='primary'> Click to get current location: </Button> {weatherData.length !== 0 ? ( <div> <img src={weatherData.current.weather_icons[0]} /> <p> Precipitation: {weatherData.current.precip} </p> </div> ) : ( '' )} </Modal.Body> </Modal> ); }; export default WeatherModal; <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; import 'bootstrap/dist/css/bootstrap.min.css'; import Container from 'react-bootstrap/Container'; import Button from 'react-bootstrap/Button'; import Navbar from 'react-bootstrap/Navbar'; import Nav from 'react-bootstrap/Nav'; import Row from 'react-bootstrap/Row'; import Col from 'react-bootstrap/Col'; import Map from './components/map.jsx'; import WeatherModal from './components/weatherModal.jsx'; class App extends React.Component { constructor(props) { super(props); this.state = { showWeather: false, }; this.closeWeatherModal = this.closeWeatherModal.bind(this); } closeWeatherModal() { this.setState({ showWeather: !this.state.showWeather, }); } render() { return ( <Container> <Navbar collapseOnSelect expand='lg' variant='dark' bg='primary'> <Navbar.Brand href=''> Pothole Finder App</Navbar.Brand> <Navbar.Toggle aria-controls='responsive-navbar-nav' /> <Navbar.Collapse id='responsive-navbar-nav'> <Nav className='mr-auto'> <Nav.Link href='#createRequest'>Create Request</Nav.Link> <Nav.Link href='#viewPendingRequest'> View Pending Request </Nav.Link> </Nav> </Navbar.Collapse> </Navbar> <Row> <Col> <Map></Map> </Col> </Row> <Row> <Col xs={6}> <Button style={{ marginTop: '30px' }} variant='warning' onClick={() => { this.setState({ showWeather: !this.state.showWeather, }); }} > Historical Weather Data </Button> <WeatherModal displayModal={this.state.showWeather} close={this.closeWeatherModal} ></WeatherModal> </Col> <Col xs={6}> <Button style={{ marginTop: '30px' }} variant='info'> New York City Budget Data </Button> </Col> </Row> </Container> ); } } ReactDOM.render(<App />, document.getElementById('app')); <file_sep>import React, { useState, useEffect } from 'react'; import ReactDOM from 'react-dom'; const Photo = (props) => { const [displayPhoto, setPhoto] = useState(false); const [imageSrc, setImageSrc] = useState(''); useEffect(() => {}, [displayPhoto]); function cameraControl() { navigator.mediaDevices .getUserMedia({ video: true }) .then((result) => { const mediaStreamTrack = result.getVideoTracks()[0]; const imageCapture = new ImageCapture(mediaStreamTrack); // console.log(imageCapture); imageCapture .takePhoto() .then((blob) => { // Insert image return blob; }) .then((blob) => { setImageSrc(URL.createObjectURL(blob)); setPhoto(true); }) .catch((err) => { console.log('takePhoto() error: ', err); }); }) .catch((error) => console.error('getUserMedia() error:', error)); } return ( <div> {cameraControl()} {displayPhoto ? ( <img style={{ height: '200px', width: '325px' }} src={imageSrc} /> ) : ( '' )} </div> ); }; export default Photo;
d07e8cd3a9b3691eaf03e573c06a57d527c16160
[ "JavaScript" ]
4
JavaScript
druplall/PotholeFinder
3b55d84bf6d82f036b0bc95c5efd7fd71c70601f
8f69e65e1fe8b3570ee312618b18d61b37f3e251
refs/heads/master
<file_sep># Uncomment this line to define a global platform for your project # platform :ios, '6.0' target 'WatchSugar' do pod 'AFNetworking' pod 'CocoaLumberjack' pod 'UICKeyChainStore' end target 'WatchSugar WatchKit Extension' do platform :watchos, '2.0' pod 'AFNetworking' pod 'UICKeyChainStore' end<file_sep>// // Definitions.h // WatchSugar // // Created by <NAME> on 1/25/16. // Copyright © 2016 Flairify. All rights reserved. // #ifndef Definitions_h #define Definitions_h #define WSDexcomApplicationId @"INSERT APPLICATION ID GUID HERE" #endif /* Definitions_h */ <file_sep># watchSugar An Apple Watch Extension for viewing your Dexcom Share blood sugars on your watch face. ## How to get started developing 1. Clone repo. 2. Run ```git update-index --assume-unchanged Definitions.h``` 3. Install Cocoapods if you haven't already: ```sudo gem install cocoapods``` 4. Install dependencies using Cocoapods: ```pod install``` watchSugar uses [Objective Clean](http://objclean.com/) to enforce a conistent syntax. Please install that app and fix all style warnings before sending a pull request. ## A Note About Dexcom Application IDs In order to authenticate a user's Dexcom Share account with Dexcom's backend a valid Dexcom Application ID is needed. Application IDs are not provided in this repository and must be obtained manually. Once you have the Dexcom Application ID you wish to use set it in Definitions.h. Please be mindful of the above Step 2. if you wish to send me a pull request. You'll know your Dexcom Application ID is functioning as expected when the on-device Login flow is successful.
0ae7f64f9cab75ef5f63af9474486d82bd94f8a9
[ "Markdown", "C", "Ruby" ]
3
Ruby
rgitty/watchSugar
9cd1c6b82037c788597b8cd5934302edcfecce9d
b057df0bfff543d3343e26e89a3c4176f32e28df
refs/heads/master
<repo_name>merroth/tank-game<file_sep>/scripts/app.ts /// <reference path="game/game.core.ts" /> module tanks { //Interfaces interface ITankAppOptions { soundVolume: number, playerOptionsIndex: number, playerKeyBindings: { forward: number, backward: number, left: number, right: number, shoot: number }[], playerCount: number, playerHealth: number, playerColors: string[] } interface ITank extends ng.IModule { userOptions?: ITankAppOptions, defaultOptions?: ITankAppOptions, keyCodeName?: any } export var tankApp: ITank; tankApp = angular.module('tankApp', ['ui.router', 'ngCookies']); //Route tankApp.config(function ($urlRouterProvider, $stateProvider) { $urlRouterProvider.otherwise('/'); $stateProvider .state('home', { url: '/', templateUrl: 'view/home', controller: 'homeCtrl' }) .state('options', { url: '/options', templateUrl: 'view/options', controller: 'optionsCtrl' }) .state('game', { url: '/game', templateUrl: 'view/gamepage', controller: 'gameCtrl' }) .state('editor', { url: '/editor', templateUrl: 'view/worldbuilder', controller: 'worldbuilderCtrl' }); }); ////Front-page //Controller tankApp.controller('homeCtrl', ['$scope', function ($scope) { }]) ////Options-page //Controller .controller('optionsCtrl', ['$scope', '$cookies', function ($scope, $cookies) { $scope.userOptions = tankApp.userOptions; var pCtrl = tankApp.userOptions.playerKeyBindings[tankApp.userOptions.playerOptionsIndex]; $scope.buttonLabelForward = tankApp.keyCodeName[pCtrl.forward] || '------'; $scope.buttonLabelBackward = tankApp.keyCodeName[pCtrl.backward] || '------'; $scope.buttonLabelLeft = tankApp.keyCodeName[pCtrl.left] || '------'; $scope.buttonLabelRight = tankApp.keyCodeName[pCtrl.right] || '------'; $scope.buttonLabelShoot = tankApp.keyCodeName[pCtrl.shoot] || '------'; $scope.setOption = function (option, value) { tankApp.userOptions[option] = value; $cookies.putObject('userOptions', tankApp.userOptions); Sound.get('sfxMenuSelect').play(true); } $scope.setColor = function (color) { let oldColor = tankApp.userOptions.playerColors[tankApp.userOptions.playerOptionsIndex]; let sameColorPlayer = tankApp.userOptions.playerColors.indexOf(color); if (sameColorPlayer !== -1) { tankApp.userOptions.playerColors[sameColorPlayer] = oldColor; } tankApp.userOptions.playerColors[tankApp.userOptions.playerOptionsIndex] = color; $cookies.putObject('userOptions', tankApp.userOptions); Sound.get('sfxMenuSelect').play(true); } $scope.resetControls = function () { let defaultKeyBindings = angular.copy(tankApp.defaultOptions.playerKeyBindings); tankApp.userOptions.playerKeyBindings = defaultKeyBindings; $cookies.putObject('userOptions', tankApp.userOptions); $scope.getPlayerSettings(tankApp.userOptions.playerOptionsIndex); } $scope.getPlayerSettings = function (playerIndex) { if (tankApp.userOptions.playerKeyBindings.hasOwnProperty(playerIndex)) { tankApp.userOptions.playerOptionsIndex = playerIndex; $scope.buttonLabelForward = tankApp.keyCodeName[tankApp.userOptions.playerKeyBindings[playerIndex].forward] || '------'; $scope.buttonLabelBackward = tankApp.keyCodeName[tankApp.userOptions.playerKeyBindings[playerIndex].backward] || '------'; $scope.buttonLabelLeft = tankApp.keyCodeName[tankApp.userOptions.playerKeyBindings[playerIndex].left] || '------'; $scope.buttonLabelRight = tankApp.keyCodeName[tankApp.userOptions.playerKeyBindings[playerIndex].right] || '------'; $scope.buttonLabelShoot = tankApp.keyCodeName[tankApp.userOptions.playerKeyBindings[playerIndex].shoot] || '------'; $scope.activeKeyBinding = null; } Sound.get('sfxMenuSelect').play(true); } $scope.listenForKey = function (event, key) { $scope.activeKeyBinding = key; angular.element(event.target).one('keydown', function (e) { $scope.setKey(key, e.which) }); } $scope.setKey = function (key, code) { if (tankApp.keyCodeName.hasOwnProperty(code)) { let label = 'buttonLabel' + key.charAt(0).toUpperCase() + key.slice(1); tankApp.userOptions.playerKeyBindings.forEach(function (playerBindings, playerIndex) { //CLEANUP: This should probably be made into a generalized function for (let bindingName in playerBindings) { if (playerBindings[bindingName] == code) { tankApp.userOptions.playerKeyBindings[playerIndex][bindingName] = null; if (playerIndex == tankApp.userOptions.playerOptionsIndex && key != bindingName) { $scope['buttonLabel' + bindingName.charAt(0).toUpperCase() + bindingName.slice(1)] = '------'; } } } }); tankApp.userOptions.playerKeyBindings[tankApp.userOptions.playerOptionsIndex][key] = code; $scope[label] = tankApp.keyCodeName[code]; $cookies.putObject('userOptions', tankApp.userOptions); Sound.get('sfxMenuSelect').play(true); } else { Sound.get('sfxMenuBack').play(true); } $scope.activeKeyBinding = null; $scope.$apply(); } }]) ////Game-page //Controller .controller('gameCtrl', ['$scope', function ($scope) { //Generate world paramenters var canvas: HTMLCanvasElement = <HTMLCanvasElement>document.getElementById("gameCanvas"); //Create world var world = World.create(canvas); //Listen for "destroy" $scope.$on("$destroy", function (event) { //Kill world World.kill(); }); }]) ////Level-editor-page //Controller .controller('worldbuilderCtrl', ['$scope', function ($scope) { //Generate world paramenters var ctx: CanvasRenderingContext2D = <CanvasRenderingContext2D>document.getElementById("gameCanvas").getContext("2d"); $scope.canvas = ctx.canvas; var tiles: Tile[] = [TileGrass, TileIce, TileSand, TileWall]; $scope.tiles = tiles; var size: number = Math.abs(parseInt(prompt("Size of map (in tiles)", "64"))); //var size: number = 64; $scope.size = size; /*var defaultTile = tiles[Math.abs(parseInt(prompt( "Pick a default tiletype:\n\n" + tiles.map(function (a, index) { return a.name + ": " + index }).join("\n"), "0" )))];*/ var defaultTile = tiles[2]; $scope.defaultTile = defaultTile; //console.log(defaultTile); var currentTile = defaultTile; var hash: Hashmap = new Hashmap(size, defaultTile.id); hash.set(new Coord(1, 1), tiles[2].id); function draw() { var defaultPattern = (function () { if (defaultTile.ressource.descriptor == null) { return "black" } var anim = defaultTile.ressource.descriptor.anim.find(function (a) { return a.name == defaultTile.animation }) var localCanvas = document.createElement("canvas").getContext("2d"); localCanvas.canvas.width = 16; localCanvas.canvas.height = localCanvas.canvas.width; localCanvas.drawImage( defaultTile.ressource.resource, 0, 0 - (anim.top * Tile.tileSize) ) return ctx.createPattern(localCanvas.canvas, "repeat") })(); ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height); ctx.fillStyle = defaultPattern; ctx.fillRect(0, 0, ctx.canvas.width, ctx.canvas.height) for (let x = 0; x < ctx.canvas.width / Tile.tileSize; x++) { for (let y = 0; y < ctx.canvas.height / Tile.tileSize; y++) { let tileID = hash.get(new Coord(x, y)); if (tileID != defaultTile.id) { let tile = tiles.find(function (a) { return a.id == tileID; }); if (tile == void 0) { continue; } let anim: IDescriptorAnimation = Tile.ressource.descriptor.anim.find(function (a) { return a.name == tile.animation; }); ctx.drawImage( defaultTile.ressource.resource, 0, anim.top * Tile.tileSize, Tile.tileSize, Tile.tileSize, x * Tile.tileSize, y * Tile.tileSize, Tile.tileSize, Tile.tileSize, ) } } } ctx.strokeStyle = "rgba(0,0,0,0.1)"; ctx.lineWidth = 1; for (let x = 0; x < ctx.canvas.width; x += Tile.tileSize) { ctx.beginPath(); ctx.moveTo(x, 0); ctx.lineTo(x, ctx.canvas.height); ctx.closePath(); ctx.stroke(); } for (let y = 0; y < ctx.canvas.height; y += Tile.tileSize) { ctx.beginPath(); ctx.moveTo(0, y); ctx.lineTo(ctx.canvas.width, y); ctx.closePath(); ctx.stroke(); } } (function () { function initialDraw() { if (defaultTile.ressource.descriptor == null) { requestAnimationFrame(initialDraw) } else { draw(); } } initialDraw(); })() ctx.canvas.onmousemove = function (e: MouseEvent) { //return false; //console.log(123, e); var scaleOffest = (1 / ctx.canvas.width) * ctx.canvas.clientWidth; var x = Math.floor(((e.clientX - e.target.offsetLeft) / scaleOffest) / Tile.tileSize); var y = Math.floor(((e.clientY - e.target.offsetTop) / scaleOffest) / Tile.tileSize); var value = document.getElementById("tiles").value; if (e.ctrlKey) { hash.set(new Coord(x, y), value); draw(); } else if (e.shiftKey) { hash.remove(new Coord(x, y)); draw(); } } }]); tankApp.run(function ($rootScope, $cookies) { $rootScope.menuLink = function () { Sound.get('sfxMenuSelect').play(true); } $rootScope.backLink = function () { Sound.get('sfxMenuBack').play(true); } tankApp.defaultOptions = { soundVolume: 0.50, playerOptionsIndex: 0, playerKeyBindings: [ { forward: 38, backward: 40, left: 37, right: 39, shoot: 16 }, { forward: 87, backward: 83, left: 65, right: 68, shoot: 32 }, { forward: 73, backward: 75, left: 74, right: 76, shoot: 13 } ], playerCount: 2, playerHealth: 100, playerColors: [ 'red', 'blue', 'green' ] }; tankApp.userOptions = $cookies.getObject('userOptions'); //TODO: Fill an existing userOptions object from a old cookie with default values from defaultOptions // in case they are undefined if (tankApp.userOptions === undefined) { tankApp.userOptions = angular.copy(tankApp.defaultOptions); } let d = new Date(); d.setTime(d.getTime() + (24 * 60 * 60 * 1000)); $cookies.putObject('userOptions', tankApp.userOptions, { 'expires': d.toUTCString() }); tankApp.keyCodeName = { 9: "Tab", 12: "Clear", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", 32: "Space", 33: "PgUp", 34: "PgDwn", 35: "End", 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 45: "Insert", 46: "Delete", 48: "0", 49: "1", 50: "2", 51: "3", 52: "4", 53: "5", 54: "6", 55: "7", 56: "8", 57: "9", 60: "\x3C", 65: "A", 66: "B", 67: "C", 68: "D", 69: "E", 70: "F", 71: "G", 72: "H", 73: "I", 74: "J", 75: "K", 76: "L", 77: "M", 78: "N", 79: "O", 80: "P", 81: "Q", 82: "R", 83: "S", 84: "T", 85: "U", 86: "V", 87: "W", 88: "X", 89: "Y", 90: "Z", 96: "Num0", 97: "Num1", 98: "Num2", 99: "Num3", 100: "Num4", 101: "Num5", 102: "Num6", 103: "Num7", 104: "Num8", 105: "Num9", 106: "Num*", 107: "Num+", 109: "Num-", 110: "Num.", 111: "Num/", 160: "¨", 171: "+", 173: "-", 188: ",", 189: "½", 190: ".", 192: "´", 222: "'" }; new Resource({ fileLocation: "resources/sfx/menu_select.m4a", id: "sfxMenuSelect" }); new Resource({ fileLocation: "resources/sfx/menu_back.m4a", id: "sfxMenuBack" }); new Sound({ id: "sfxMenuSelect", resource: Resource.get("sfxMenuSelect") }); new Sound({ id: "sfxMenuBack", resource: Resource.get("sfxMenuBack") }); }); tankApp.directive('exclusiveSelect', function () { return { link: function (scope, element, attrs) { element.bind('click', function () { element.parent().children().removeClass('active'); element.addClass('active'); }); }, } }); } <file_sep>/tsconfig.json { "compilerOptions": { "outFile": "scripts/main.js", "watch": true }, "files": [ "scripts/app.ts", "scripts/game/game.utility.ts", "scripts/game/classes/actor.class.ts", "scripts/game/classes/projectiles.class.ts", "scripts/game/classes/weapon.class.ts", "scripts/game/classes/player.class.ts", "scripts/game/classes/level.class.ts", "scripts/game/game.core.ts" ] } <file_sep>/scripts/game/classes/actor.class.ts /// <reference path="../game.utility.ts" /> /// <reference path="../game.core.ts" /> //This file contains the base game object class for the game engine. //This "Actor" class holds information relevant to every kind of object in the game world module tanks { export interface IActorAnimation { name: string; count: number; } export interface IActor { position?: Coord; angle?: Angle; momentum?: Vector; acceleration?: number; size?: number; sprite?: Resource; turnrate?: number; anim?: IActorAnimation; zIndex?: EZindex; render?: boolean; collision?: Basics.Circle | Basics.Rect; moveable?: boolean; } export class Actor { static _actors: Actor[] = []; public position: Coord = new Coord(); public angle: Angle = new Angle(); public momentum: Vector = new Vector(); public acceleration: number = 0; public size: number = 0; public sprite: Resource = null; public anim: IActorAnimation = { name: "", count: 0 }; public turnrate: number = 1; public zIndex: EZindex = EZindex.actor; public render: boolean = true; public moveable: boolean = true; public collision: Basics.Circle | Basics.Rect = null; public draw: (ctx: CanvasRenderingContext2D) => void; constructor(parameters: IActor = {}) { for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } Actor._actors.push(this); } //Do thing on each frame public update(): boolean { return false; } protected _die() { Actor._actors.splice(Actor._actors.indexOf(this), 1); } public die() { this._die(); } } } <file_sep>/scripts/game/classes/level.class.ts /// <reference path="../game.utility.ts" /> /// <reference path="../game.core.ts" /> //Projectiles contains classes for each kind of projectile in the game //A projectile is a self propelling game object without direct user control, usually intended for dealing damage module tanks { export interface ITile { id?: string | number, name?: string, isBlocking?: boolean, ressource?: Resource, friction?: number, tileSize?: number animation?: string } export class Tile { //List of all tiles in existence static _tiles: ITile[] = []; //Running static id number of level static _id = 0; //tile image static tileImage: Resource = Resource.get("tileset"); //get Tile By Id static getById(id: number | string = null) { return this._tiles .filter(function (a) { return a.id == id }) .slice(0) .pop(); } //get Tile By name static getByName(name: number | string = null) { return this._tiles .filter(function (a) { return a.name == name }) .slice(0) .pop(); } //The identifier for this tile. static id: string | number = (function () { var id = 0; while (Tile._tiles.some(function (tile) { return tile.id == id; })) { id++; } return id; })(); //Can a player/projectile traverse this tile static isBlocking: boolean = false; //The ressource to draw on this tile static ressource: Resource = Resource.get("tileset"); //Default animation name static animation: string | number = "grass1"; //On a scale from 0 to 1, how much friction does this tile excert static friction: number = 1; //How big should one of these tiles be. static tileSize: number = 16; constructor(parameters: ITile = {}) { } } export class TileGrass extends Tile { static id = "tilegrass1"; static animation: string | number = "grass1"; constructor(parameters: ITile = {}) { super(parameters); } } export class TileIce extends Tile { static id = "tileice1"; static animation: string | number = "water1"; constructor(parameters: ITile = {}) { super(parameters); } } export class TileSand extends Tile { static id = "tilesand1" static animation: string | number = "sand1"; constructor(parameters: ITile = {}) { super(parameters); } } export class TileWall extends Tile { static id = "tilewall1" static animation: string | number = "grass1"; constructor(parameters: ITile = {}) { super(parameters); } } export interface ILevel { id?: string | number, defaultTile?: ITile, size?: number, tilehash?: string[] | number[], } export class Level { //Running static id number of level static _id = 0; public id; //Default tile to use in this level public defaultTile: ITile = TileSand; //Map size in tiles public size: number = 100; //Hashmap over tiles public tileSet: Hashmap = null; constructor(parameters: ILevel = {}) { for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } if (this.id == void 0) { this.id = Level._id++; } this.tileSet = new Hashmap(this.size, this.defaultTile.id) if (parameters.hasOwnProperty("tilehash")) { this.tileSet.data = parameters["tilehash"]; } } public save() { var self = this; var saveObject = { id: this.id.toString(), size: this.size, tilehash: Object.keys(this.tileSet.data) .filter(function (tile) { return (self.tileSet.data[tile] != void 0); }) .map(function (tile) { var obj = {}; obj[tile] = self.tileSet.data[tile]; return obj }), defaultTile: this.defaultTile.id } return JSON.stringify(saveObject); } } /* UNIT TESTS - RUN ONLY IN DEVELOPMENT AS THE TILES REGISTER GLOBALLY! var lvl = new Level({ id: "Level 1", size: 6 }); lvl.tileSet.set(new Coord(1, 1), 5); console.log(lvl.save()); */ } <file_sep>/scripts/app.d.ts declare module tanks { var tankApp: any; } <file_sep>/scripts/game/game.utility.ts //This file contains utility elements for the game engine. module tanks { /* utility interfaces & enums */ //Enum for rendering order export enum EZindex { //Dont assign values, simply move lines up or down to change rendering order "background", "terrain", "sub-sfx", "actor", "actor-sfx", "projectile", "top-sfx", "ui" } //Testing export var runTests = true; export function assert(label: string = "Unlabeled", statement: any, exptected: any = true) { var str = label + " exptected " + exptected + " found " + statement; if (statement != exptected) { console.warn(label, "exptected", exptected, "found", statement); } } //Container for basic elements like funtions or shapes export module Basics { //Distance betweem two coordinates export function distance(x1: number, y1: number, x2: number, y2: number): number { return Math.sqrt(Math.pow(x1 - x2, 2) + Math.pow(y1 - y2, 2)); } //Angle betweem two coordinates export function angleBetweenPoints(x1: number, y1: number, x2: number, y2: number): number { var angle = (Math.atan2(y1 - y2, x1 - x2) * 180 / Math.PI) % 360; if (angle < 0) { angle = Math.abs(angle - 180); } return angle; } //Would two lines intersect //http://stackoverflow.com/questions/9043805/test-if-two-lines-intersect-javascript-function#24392281 export function intersects(l1x1, l1y1, l1x2, l1y2, l2x1, l2y1, l2x2, l2y2): boolean | { lamb: number, gamma: number } { var det: number, gamma: number, lamb: number; det = (l1x2 - l1x1) * (l2y2 - l2y1) - (l2x2 - l2x1) * (l1y2 - l1y1); if (det === 0) { return false; //Return overlapping circle //return (angleBetweenPoints(l1x1, l1y1, l1x2, l1y2) == 0); } else { //lamb is progess over x axis lamb = ((l2y2 - l2y1) * (l2x2 - l1x1) + (l2x1 - l2x2) * (l2y2 - l1y1)) / det; //gamma is progess over y axis gamma = ((l1y1 - l1y2) * (l2x2 - l1x1) + (l1x2 - l1x1) * (l2y2 - l1y1)) / det; if ((0 < lamb && lamb < 1) && (0 < gamma && gamma < 1)) { return { lamb: lamb, gamma: gamma } } else { return false; } } }; } //Defines the concept of an "angle" and utility functions export class Angle { constructor(public degree: number = 0) { this.degree = this.degree % 360; } public set(degree: number): Angle { this.degree = degree % 360; return this; } public add(degree: number): Angle { this.degree = (this.degree + degree) % 360; return this; } public get(): number { return this.degree; } public static degreetoRadian(degree: number): number { return degree * (Math.PI / 180); } public static radianToDegree(radian: number): number { return radian * (180 / Math.PI); } } //Defines a point in space and utility functions export class Coord { constructor(public x: number = 0, public y: number = 0) { } //Distance between points wrapped for Coords public static distanceBetweenCoords(coordA: Coord, coordB: Coord): number { return Basics.distance(coordA.x, coordA.y, coordB.x, coordB.y); } //Angle between points formular wrapped for Coords public static angleBetweenCoords(coordA: Coord, coordB: Coord): Angle { return new Angle(Basics.angleBetweenPoints(coordA.x, coordA.y, coordB.x, coordB.y)); } } //Defines a force in space, based upon Coord export class Vector { constructor(public velocity: Coord = new Coord(), public max: number = Infinity, public degradeForce: number = 0.95) { } //Degrade the current momentum by an overridable factor public degrade(degradeForce: number = this.degradeForce): Vector { this.velocity.x *= this.degradeForce; this.velocity.y *= this.degradeForce; return this; } //Reverse the Vector to point in the opposite direction public reverse(): Vector { this.velocity.x = -1 * this.velocity.x; this.velocity.y = -1 * this.velocity.y; return this; } //Add a Coord force to the Vector public addForce(force: Coord = new Coord()): Vector { this.velocity.x += force.x; if (Math.abs(this.velocity.x) > this.max) { this.velocity.x = (this.velocity.x > 0 ? this.max : 0 - this.max); } this.velocity.y += force.y; if (Math.abs(this.velocity.y) > this.max) { this.velocity.y = (this.velocity.y > 0 ? this.max : 0 - this.max); } return this; } public get(): Coord { return this.velocity; } public set(force: Coord = this.velocity): Vector { this.velocity = force; return this; } //Get angle of force public getAngle(): Angle { return Coord.angleBetweenCoords(new Coord(), this.velocity); } } //A Hashmap maps 2 dimensional elements to a 1 dimensional array //This way we can use native array methods for faster manipulations if needed export class Hashmap { public data: any[] = []; public size: number = 10 public defaultValue: any = null constructor(size: number = 10, defaultValue: any = null) { if (defaultValue != this.defaultValue) { this.defaultValue = defaultValue; } if (typeof size == typeof this.size && isFinite(size) && size > 0) { this.size = Math.abs(size); } else { //console.warn("invalid size:", size, "using default", this.size, "instead"); } this.data.length = Math.pow(size, 2); } public get(coord: Coord) { let target = coord.x + (coord.y * this.size); if (target >= this.data.length) { //console.warn("out of range: too high", coord.x, ':', coord.y); return false; } if (target < 0) { //console.warn("out of range: only positive values accepted", coord.x, ':', coord.y); return false; } if (this.data[target] == void 0) { return this.defaultValue; } return this.data[target]; } public getAll(fillEmpty = true) { var arr = this.data.slice(0); for (let arrIndex = 0; arrIndex < arr.length; arrIndex++) { if (arr[arrIndex] == void 0 && fillEmpty == true) { arr[arrIndex] = this.defaultValue; } } return arr; } public set(coord: Coord, value: any) { let target = coord.x + (coord.y * this.size); if (target >= this.data.length) { //console.warn("out of range: too high", coord.x, ':', coord.y); return false; } if (target < 0) { //console.warn("out of range: only positive values accepted", coord.x, ':', coord.y); return false; } this.data[target] = value; return this; } public remove(coord: Coord) { let target = coord.x + (coord.y * this.size); if (target >= this.data.length) { //console.warn("out of range: too high", coord.x, ':', coord.y); return false; } if (target < 0) { //console.warn("out of range: only positive values accepted", coord.x, ':', coord.y); return false; } if (this.data[target] != void 0) { this.data[target] = void 0; } return this; } public setDefault(value: any) { this.defaultValue = value; return this; } } (function unitTest() { var h = new Hashmap(); assert("Hashmap gets negative", h.get(new Coord(-1, -1)), false); assert("Hashmap sets negative", h.set(new Coord(-1, -1), false), false); })() //More Basics export module Basics { //Shape is a base class for other Shapes //This class isn't exported because it shouldn't be used raw /** * Shape */ class Shape { constructor(public origo: Coord = new Coord()) { } } export class Rect extends Shape { constructor(public origo: Coord = new Coord(), public width: number = 0, public height: number = 0) { super(origo); } public setWidth(value: number = this.width) { this.width = Math.abs(value); return this; } public setHeight(value: number = this.height) { this.height = Math.abs(value); return this; } public circumference(): number { return 2 * ( Basics.distance(0, 0, 0, this.height) + Basics.distance(0, 0, this.width, 0) ) } public area(): number { return Basics.distance(0, 0, 0, this.height) * Basics.distance(0, 0, this.width, 0) } //Diagonal length of box public diagonal(): number { return Basics.distance(0, 0, this.width, this.height); } } /* */ // Unit Tests (function unitTest() { if (!runTests) { return false; } var c = new Rect(new Coord(10, 20), 10, 10); assert("Area of rect is 100", Math.floor(c.area()), 100); assert("Circumference of rect is 40", Math.floor(c.circumference()), 40); assert("Diagonal of rect is 14", Math.floor(c.diagonal()), 14); })(); /* */ //Circle contains mathematical formulars and data for a circle //This can easily be used for range factors and collisions export class Circle extends Shape { static areaToRadius(area: number): number { return area / Math.PI; } //omkreds public circumference(): number { return 2 * this.radius * Math.PI; } //areal public area(): number { return Math.PI * (this.radius * this.radius); } //korde public chord(vinkel: number = 1): number { //https://www.regneregler.dk/cirkel-korde return 2 * this.radius * Math.sin(Angle.degreetoRadian(vinkel) / 2); } constructor(public origo: Coord = new Coord(), public radius: number = 0) { super(); } } /* // Unit Tests */ (function unitTest() { if (!runTests) { return false; } var c = new Circle(new Coord(100, 100), 10); assert("Area of circle is 314", Math.floor(c.area()), 314); assert("Circumference of circle is 62", Math.floor(c.circumference()), 62); assert("Chord of circle is radius * 2 (10 * 2)", Math.floor(c.chord(180)), 20); })(); function RectCircleColliding(circle: Circle, rect: Rect) { var x = rect.origo.x - 0.5 * rect.width; var y = rect.origo.y - 0.5 * rect.height; //http://stackoverflow.com/a/21096179 var distX = Math.abs(circle.origo.x - x - rect.width / 2); var distY = Math.abs(circle.origo.y - y - rect.height / 2); if (distX > (rect.width / 2 + circle.radius)) { return false; } if (distY > (rect.height / 2 + circle.radius)) { return false; } if (distX <= (rect.width / 2)) { return true; } if (distY <= (rect.height / 2)) { return true; } var dx = distX - rect.width / 2; var dy = distY - rect.height / 2; return (dx * dx + dy * dy <= (circle.radius * circle.radius)); } export function shapeOverlap(shape1: Shape, shape2: Shape) { if (shape1 instanceof Rect && shape2 instanceof Rect) { return ( //Shape1 start before Shape2 ends (x) shape1.origo.x - 0.5 * shape1.width < shape2.origo.x + 0.5 * shape2.width && //Shape2 start before Shape1 ends (x) shape2.origo.x - 0.5 * shape2.width < shape1.origo.x + 0.5 * shape1.width && //Shape1 start before Shape2 ends (y) shape1.origo.y - 0.5 * shape1.height < shape2.origo.y + 0.5 * shape2.height && //Shape2 start before Shape1 ends (y) shape2.origo.y - 0.5 * shape2.height < shape1.origo.y + 0.5 * shape1.height ); } else if (shape1 instanceof Circle && shape2 instanceof Circle) { return Coord.distanceBetweenCoords(shape1.origo, shape2.origo) < shape1.radius + shape2.radius } else if (shape1 instanceof Circle && shape2 instanceof Rect) { return RectCircleColliding(shape1, shape2); } else if (shape1 instanceof Rect && shape2 instanceof Circle) { return RectCircleColliding(shape2, shape1); } else { return false; } } /* */ //Enum settings for bounce enum EBounce { //Moving in negative direction "substractive", //Moving in positive direction "additive", } //Determine angle of bounceof export function bounce(incomingAngle: number, angleOfCollisionTarget: number, solution: EBounce = EBounce.additive): number { //The Normal is tangent to the angleOfCollisionTarget var normal = (solution == EBounce.additive ? angleOfCollisionTarget - 90 : angleOfCollisionTarget + 90); //Force between 0 and 360 if (normal <= 0) { normal += 360; } if (incomingAngle <= 0) { incomingAngle += 360; } // var result = 90 * (1 + (angleOfCollisionTarget % 180 / 90)) - incomingAngle + normal; //Force result to be a positive degree while (result < 0) { result += 360; } return result % 360; } /* // Unit Tests */ (function unitTest() { if (!runTests) { return false; } assert("45 on 0 is 315", bounce(45, 0), 315); assert("135 on 0 is 225", bounce(135, 0), 225); assert("225 on 0 is 135", bounce(225, 0), 135); assert("315 on 0 is 45", bounce(315, 0), 45); assert("45 on 90 is 135", bounce(45, 90), 135); assert("135 on 90 is 45", bounce(135, 90), 45); assert("225 on 90 is 315", bounce(225, 90), 315); assert("315 on 90 is 225", bounce(315, 90), 225); })(); } export interface IDescriptorAnimation { name: string; top: number; count: number; rate: number; } export interface IDescriptor { width: number; height: number; anim: IDescriptorAnimation[]; } export interface IResource { fileLocation: string, descriptorLocation?: string, id?: string } //Resources consists of a graphic file and optionally a descriptor JSON file //Resources are loaded before game launch and referenced by assigned ID export class Resource { private static id: 0; public static Resources: Resource[] = []; public resource: HTMLImageElement | HTMLAudioElement | string | any = null; public descriptor: IDescriptor = null; public ready: boolean = false; public fileLocation: string = ""; public descriptorLocation: string = null; public id: string = "#" + (Resource.id++) public static get(id: string): Resource { var resource = this.Resources .filter(function (a) { return a.id == id; }); if (resource.length > 0) { return resource[0]; } } constructor(parameters: IResource = { fileLocation: "" }) { var self = this; var ready = 2; for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } if (this.descriptorLocation == null) { testReady(); } function testReady() { ready--; if (ready <= 0) { self.ready = true; } } //resource if (this.fileLocation.match(/\.png$|\.jpg$|\.bmp$|\.gif$/ig) !== null) { //Image this.resource = document.createElement("img"); this.resource.onload = function loaded() { testReady(); } this.resource.src = this.fileLocation; } else if (this.fileLocation.match(/\.json$/ig) !== null) { //JSON var req = new XMLHttpRequest(); req.open('GET', this.fileLocation); req.overrideMimeType("application/json"); req.onreadystatechange = function loaded() { self.resource = JSON.parse(req.responseText.replace(/\n|\t/ig, " ")); testReady() } req.send(); } else if (this.fileLocation.match(/\.m4a$|\.mp3$|\.ogg/ig) !== null) { //Sound this.resource = document.createElement("audio"); this.resource.onload = function loaded() { testReady(); } this.resource.src = this.fileLocation; } else { //Unkown filetype var req = new XMLHttpRequest(); req.open('GET', this.fileLocation); req.onreadystatechange = function loaded() { self.resource = req.responseText; testReady() } req.send(); } //descriptor if (this.descriptorLocation != null) { if (this.descriptorLocation.match(/\.json$/ig) !== null) { //JSON var req = new XMLHttpRequest(); req.open('GET', this.descriptorLocation); req.overrideMimeType("application/json"); req.onreadystatechange = function () { if (req.readyState === 4) { self.descriptor = JSON.parse(req.responseText); testReady() } } req.send(); } } Resource.Resources.push(this); } } export interface ISound { resource?: Resource soundBankCount?: number id?: string } //A class to hold sound specific attributes export class Sound { private static _id: number = 0; public static Sounds: Sound[] = []; public static get(id: string): Sound { var sound = this.Sounds .filter(function (a) { return a.id == id; }); if (sound.length > 0) { return sound[0]; } } public soundBankCount: number = 1; public soundBanks: HTMLAudioElement[] = []; public resource: Resource = null; public id: string = null; constructor(parameters: ISound = { id: "#" + (Sound._id++).toString() }) { for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } this.soundBanks.push(this.resource.resource); while (this.soundBanks.length < this.soundBankCount) { this.soundBanks.push(this.resource.resource.cloneNode()); } Sound.Sounds.push(this); } public play(force: boolean = false) { if (tankApp.userOptions.soundVolume > 0) { for (var soundBankIndex = 0; soundBankIndex < this.soundBanks.length; soundBankIndex++) { var soundBank = this.soundBanks[soundBankIndex]; if (soundBank.paused) { soundBank.volume = tankApp.userOptions.soundVolume; soundBank.play(); return this; } } if (force) { var sfx = this.soundBanks[0]; sfx.currentTime = 0; sfx.play(); } } return this; } public pause(rewind: boolean = false) { for (var soundBankIndex = 0; soundBankIndex < this.soundBanks.length; soundBankIndex++) { this.soundBanks[soundBankIndex].pause(); if (rewind) { this.soundBanks[soundBankIndex].currentTime = 0; } } return this; } } } //initialize load //in the future this should be elsewhere module tanks { //Resources new Resource({ fileLocation: "resources/single-tank-red.png", descriptorLocation: "resources/single-tank-red.json", id: "tankRedSprite" }); new Resource({ fileLocation: "resources/single-tank-blue.png", descriptorLocation: "resources/single-tank-red.json", id: "tankBlueSprite" }); new Resource({ fileLocation: "resources/single-tank-green.png", descriptorLocation: "resources/single-tank-red.json", id: "tankGreenSprite" }); new Resource({ fileLocation: "resources/bullet_normal.png", descriptorLocation: "resources/bullet_normal.json", id: "bulletSprite" }); new Resource({ fileLocation: "resources/bullet_burning.png", descriptorLocation: "resources/bullet_normal.json", id: "bulletBurningSprite" }); new Resource({ fileLocation: "resources/tiles_vertical.png", descriptorLocation: "resources/tileset_vertical.json", id: "tileset" }); new Resource({ fileLocation: "resources/wall.png", id: "wallSprite" }); new Resource({ fileLocation: "resources/sfx/menu_back.m4a", id: "sfxMenuBack" }); new Resource({ fileLocation: "resources/sfx/menu_select.m4a", id: "sfxMenuSelect" }); new Resource({ fileLocation: "resources/sfx/bullet_bounce.m4a", id: "sfxBulletBounce" }); new Resource({ fileLocation: "resources/sfx/bullet_spawn.m4a", id: "sfxBulletSpawn" }); new Resource({ fileLocation: "resources/sfx/flamethrower_spawn.m4a", id: "sfxFlamethrowerSpawn" }); new Resource({ fileLocation: "resources/sfx/bullet_hit.m4a", id: "sfxBulletHit" }); new Resource({ fileLocation: "resources/sfx/tank_die.m4a", id: "sfxTankDie" }); //Sound new Sound({ id: "sfxMenuBack", resource: Resource.get("sfxMenuBack") }); new Sound({ id: "sfxMenuSelect", resource: Resource.get("sfxMenuSelect") }); new Sound({ id: "sfxBulletBounce", resource: Resource.get("sfxBulletBounce") }); new Sound({ id: "sfxBulletSpawn", resource: Resource.get("sfxBulletSpawn"), soundBankCount: 10 }); new Sound({ id: "sfxFlamethrowerSpawn", resource: Resource.get("sfxFlamethrowerSpawn"), soundBankCount: 10 }); new Sound({ id: "sfxBulletHit", resource: Resource.get("sfxBulletHit"), soundBankCount: 4 }); new Sound({ id: "sfxTankDie", resource: Resource.get("sfxTankDie"), soundBankCount: 4 }); } <file_sep>/scripts/game/classes/weapon.class.ts /// <reference path="../game.utility.ts" /> /// <reference path="../game.core.ts" /> //This file contains weapon sets for the player objects //A weapon is a "hardpoint" for players that can manage meta information for projectiles such as fireRate or fireArc //or their position/angle relative to their respective player objects module tanks { export interface IWeapon extends IActor { //Obligatory field owner: Player; //Optional fields lifespan?: number; projectileType?: Projectile; fireArc?: Angle; angle?: Angle; position?: Coord; hitpoint?: number; fireRateMax?: number; fireRate?: number; maxProjectiles?: number; speed?: number; } export class Weapon extends Actor { //Lifespan of projectiles public lifespan: number = 100; //Type of projectile fired (This contains projectile relevant data like damage) public projectileType = Projectile; //List of fired projectiles public projectiles: Projectile[] = []; //Bullet spread by angle public fireArc: Angle = new Angle(); //Weapon angle (as offset to parent angle) public angle: Angle = new Angle(); //Position on parent (as offset by angle, numbers should be 2 equal numbers) public position: Coord = new Coord(); //A reference to parent public owner: Player = null; //If this weapon can be destroyed public hitpoint: number = Infinity; //Time between shots public fireRateMax: number = 20; //Countdown between shots public fireRate: number = 0; //Maximum allowed projectiles from this weapon at any given moment public maxProjectiles: number = Infinity; //Does this weapon have a renderable part? public render: boolean = false; //Speed of projectiles fired by this weapon public speed: number = 4; constructor(parameters: IWeapon = { owner: null }) { super(parameters); for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } } public update(): boolean { var self = this; self.cool(); return false; } public cool(amount: number = 1) { if (this.fireRate > 0) { this.fireRate -= amount; } return this; } public shoot(): Weapon { var self = this; if (self.fireRate < 1 && self.projectiles.length < self.maxProjectiles) { self.fireRate = self.fireRateMax * 1; var arcDegree = (Math.random() * self.fireArc.degree) - (self.fireArc.degree / 2); var degrees = self.owner.angle.degree + self.angle.degree + arcDegree; var cos = Math.cos(Angle.degreetoRadian(degrees)); var sin = Math.sin(Angle.degreetoRadian(degrees)); var projectile = new self.projectileType({ lifespan: self.lifespan, owner: self, position: new Coord(self.owner.position.x + cos * self.position.x, self.owner.position.y + sin * self.position.y), angle: new Angle(degrees), momentum: new Vector(new Coord(cos * self.speed, sin * self.speed), self.speed, 1) }); self.owner.projectiles.push(projectile); self.projectiles.push(projectile); if (projectile.sfx.spawn != null) { projectile.sfx.spawn.play(); } } return this; } } export class WeaponTankFlameThrower extends Weapon { public lifespan: number = 20; public fireRateMax: number = 10; public speed: number = 1.3; public fireArc: Angle = new Angle(45); public projectileType = FlameThrowerProjectile; } export class WeaponTankMainGun extends Weapon { public lifespan: number = 100; public fireRateMax: number = 200; public speed: number = 4; public fireArc: Angle = new Angle(1); public projectileType = MainGunProjectile; } } <file_sep>/README.md # tank-game Online at: https://merroth.github.io/tank-game/#/ ##TODO## ###Graphics### - ~~Barriers/Walls~~ - Tile variants (First pass done) - Transition tiles (Grass-to-sand, etc.) ###Simulation### - ~~World class~~ - ~~Player class~~ - ~~Projectile class~~ - ~~Weapon class~~ - Wall class - Tile class ###Configuration### - ~~Controls~~ - ~~Number of players~~ - ~~Player colour~~ - ~~Player health~~ - ~~Save settings~~ - ~~Reset defaults~~ (Only key bindings for now) ###Sound### - ~~Audio mixing (A BIT LOUD!)~~ - ~~Adjustable volume~~ <file_sep>/scripts/game/game.core.ts /// <reference path="game.utility.ts" /> //This file contains core classes for the game engine. //This file is dependent upon "game.utility.ts", which describes utility elements like "Angle" module tanks { interface IWorldSettings { resolution?: number; drawCollisionShapes?: boolean } export class World { public static worldActive: boolean = false; public static settings: IWorldSettings = { drawCollisionShapes: true } public static canvas: HTMLCanvasElement = null; private static updatehandle; public static players: Player[] = []; public static frame: number = 0; //CLEANUP: spawnPoints should probably be defined in a Level class or something once we make one. public static spawnPoints: { angle: Angle, position: Coord }[] = []; public static create(canvas: HTMLCanvasElement = null, settings: IWorldSettings = this.settings) { World.settings = settings; World.spawnPoints.push( { angle: new Angle(0), position: new Coord(40, 40) }, { angle: new Angle(180), position: new Coord(parseInt(canvas.getAttribute("width")) - 40, parseInt(canvas.getAttribute("height")) - 40) }, { angle: new Angle(270), position: new Coord(40, parseInt(canvas.getAttribute("height")) - 40) }, { angle: new Angle(90), position: new Coord(parseInt(canvas.getAttribute("width")) - 40, 40) }, ); World.canvas = canvas; //Generate players for (let i = 0; i < tankApp.userOptions.playerCount; i++) { //TODO: Possibly assign players randomly to spawnPoints, using something like this: //World.spawnPoints.splice(Math.floor(Math.random() * World.spawnPoints.length), 1) //CLEANUP: capitalizeFirstLetter function might be an idea at this point... let color = tankApp.userOptions.playerColors[i].charAt(0).toUpperCase() + tankApp.userOptions.playerColors[i].slice(1); World.players.push( new Player({ position: World.spawnPoints[i].position, angle: World.spawnPoints[i].angle, sprite: Resource.get("tank" + color + "Sprite") }) ); } //Start "World" //event listener window.addEventListener("keydown", World.listener, false); window.addEventListener("keyup", World.listener, false); World.worldActive = true; var startInterval = setInterval(function () { if (Resource.Resources.filter(function (a) { return a.ready == false })) { clearInterval(startInterval); World.update(true); } }, 4); return World; } public static listener(evt: KeyboardEvent) { var value: boolean = (evt.type == "keydown" ? true : false); var keyBindings = tankApp.userOptions.playerKeyBindings; switch (evt.keyCode) { //Player 1 case keyBindings[0].forward: World.players[0].controls.forward = value; break; case keyBindings[0].backward: World.players[0].controls.backward = value; break; case keyBindings[0].left: World.players[0].controls.left = value; break; case keyBindings[0].right: World.players[0].controls.right = value; break; case keyBindings[0].shoot: World.players[0].controls.shoot = value; break; //Player 2 case keyBindings[1].forward: World.players[1].controls.forward = value; break; case keyBindings[1].backward: World.players[1].controls.backward = value; break; case keyBindings[1].left: World.players[1].controls.left = value; break; case keyBindings[1].right: World.players[1].controls.right = value; break; case keyBindings[1].shoot: World.players[1].controls.shoot = value; break; //Player 3 case keyBindings[2].forward: World.players[2].controls.forward = value; break; case keyBindings[2].backward: World.players[2].controls.backward = value; break; case keyBindings[2].left: World.players[2].controls.left = value; break; case keyBindings[2].right: World.players[2].controls.right = value; break; case keyBindings[2].shoot: World.players[2].controls.shoot = value; break; } } public static update(changes: boolean = World.frame % 15 === 0): World { //Runs every frame if (World.worldActive !== true) { return this; } World.updatehandle = requestAnimationFrame(function () { World.update(); }); World.frame++; //Simulate terrain //Simulate actors //find actors who can actually collide var collisionSuspects = Actor._actors .filter(function collisionSuspectsFilter(actor) { return actor.collision != null; }); //Return the largest collision radius to test against //We can use this to filter later var maxCollisonDistanceToCheck = collisionSuspects .map(function maxCollisonToCheckMap(actor) { if (actor.collision instanceof Basics.Circle) { return actor.collision.radius; } else if (actor.collision instanceof Basics.Rect) { return Math.max(actor.collision.width, actor.collision.height); } }) .sort() .slice(0, 1)[0] * 2; //Load actors and sort by rendering order var actors = Actor._actors .sort(function (a, b) { return b.zIndex - a.zIndex; }); for (let actorIndex = 0; actorIndex < actors.length; actorIndex++) { let actor = actors[actorIndex]; //Only test collision on object within a realistic vicinity let localCollisionSuspects = collisionSuspects .filter(function (suspect) { return Coord.distanceBetweenCoords( suspect.position, actor.position ) <= maxCollisonDistanceToCheck; }) //Test for collision for (let collisionSuspectsIndex = 0; collisionSuspectsIndex < localCollisionSuspects.length; collisionSuspectsIndex++) { //current suspect let collisionSuspect = localCollisionSuspects[collisionSuspectsIndex]; if (actor === collisionSuspect) { continue; } /* */ //Test if collision shapes overlap if (Basics.shapeOverlap(collisionSuspect.collision, actor.collision)) { //If Projectile on Player collision if (actor instanceof Projectile && collisionSuspect instanceof Player && collisionSuspect != actor.owner.owner) { collisionSuspect.hitPoints -= actor.damage; actor.lifespan = 0; actor.hit = true; } //If Player on Player collision else if (actor instanceof Player && collisionSuspect instanceof Player) { //Calculate a force based upon the angle between actors let force = new Coord( Math.abs(Math.cos( Angle.degreetoRadian( Coord.angleBetweenCoords( actor.position, collisionSuspect.position ).degree ) )), Math.abs(Math.sin( Angle.degreetoRadian( Coord.angleBetweenCoords( actor.position, collisionSuspect.position ).degree ) )) ); //Align the force if (actor.position.x < collisionSuspect.position.x) { force.x *= -1 } if (actor.position.y < collisionSuspect.position.y) { force.y *= -1 } //Half the force if is to be distributed between two objects //Each object will get half of the force. Future implementations could consider mass. if (actor.moveable && collisionSuspect.moveable) { force.y *= 0.5; force.x *= 0.5; } //Add the force to the colliding actor if (actor.moveable) { actor.momentum.addForce(force); } //Add an equal and opposite force to the collisionSuspect if (collisionSuspect.moveable) { collisionSuspect.momentum.addForce(new Coord(force.x * -1, force.y * -1)); } } } /* */ } //Run update and listen for changes changes = (actor.update() ? true : changes); } //Simulate UI? //Draw if changes if (changes === true) { World.draw(); } return this; } public static draw(): World { var ctx: CanvasRenderingContext2D = World.canvas.getContext("2d"); ctx.save(); //clear rect ctx.clearRect(0, 0, parseInt(World.canvas.getAttribute("width")), parseInt(World.canvas.getAttribute("height"))); //Paint world //Paint actors var actorsToDraw = Actor._actors //filter to renderable actors. maybe filter to actors on canvas in the future? .filter(function filterActorsToDraw(actor: Actor) { return actor.render == true; }) .sort(function (actorA, actorB) { return actorA.zIndex - actorB.zIndex; }); for (var actorIndex = 0; actorIndex < actorsToDraw.length; actorIndex++) { var actor = actorsToDraw[actorIndex]; if (this.settings.drawCollisionShapes === true) { if (actor.collision instanceof Basics.Rect) { ctx.strokeRect( actor.collision.origo.x - actor.collision.width / 2, actor.collision.origo.y - actor.collision.height / 2, actor.collision.width, actor.collision.height ); } else if (actor.collision instanceof Basics.Circle) { ctx.beginPath(); ctx.arc( actor.collision.origo.x, actor.collision.origo.y, actor.collision.radius, 0, Math.PI * 2 ); ctx.stroke(); ctx.closePath(); } } //If actor has an abstract drawing method if (actor.draw != void 0) { actor.draw(ctx); continue; } //Move and rotate canvas to object ctx.translate(actor.position.x, actor.position.y); ctx.rotate(Angle.degreetoRadian(actor.angle.get())); //Draw image //Get current animation var animation = actor.sprite.descriptor.anim .filter(function findAnimation(anim) { return anim.name === actor.anim.name; })[0]; //Get current animation state var animationState = Math.floor( actor.anim.count / animation.rate ); //Loop animation if (animationState >= animation.count) { animationState = 0; actor.anim.count = animationState; } else if (animationState < 0) { animationState = animation.count - 1; actor.anim.count = animationState; } //Draw sprite image ctx.drawImage( actor.sprite.resource, animationState * actor.sprite.descriptor.width, animation.top * actor.sprite.descriptor.height, actor.sprite.descriptor.width, actor.sprite.descriptor.height, 0 - Math.floor(actor.sprite.descriptor.width / 2), 0 - Math.floor(actor.sprite.descriptor.height / 2), actor.sprite.descriptor.width, actor.sprite.descriptor.height ); //Reset canvas ctx.rotate(0 - Angle.degreetoRadian(actor.angle.get())); ctx.translate(0 - actor.position.x, 0 - actor.position.y); } //Paint ui ctx.restore(); return this; } public static kill() { //Destroy World cancelAnimationFrame(World.updatehandle); World.worldActive = false; World.spawnPoints = []; World.players = []; World.frame = 0; Actor._actors = []; window.removeEventListener("keydown", World.listener, false); window.removeEventListener("keyup", World.listener, false); } } } <file_sep>/scripts/game/classes/projectiles.class.ts /// <reference path="../game.utility.ts" /> /// <reference path="../game.core.ts" /> //Projectiles contains classes for each kind of projectile in the game //A projectile is a self propelling game object without direct user control, usually intended for dealing damage module tanks { export interface IProjectile extends IActor { //Obligatory field owner: Weapon; //Optional fields lifespan?: number; damage?: number; } export class Projectile extends Actor { public lifespan: number = 1; public owner: Weapon = null; public damage: number = 0; public size = 8; public hit: boolean = false; static repeatFire: boolean = false; public sprite: Resource = Resource.get("bulletSprite"); public anim: IActorAnimation = { name: "idle", count: 0 }; public zIndex: EZindex = EZindex.projectile; public collision: Basics.Circle | Basics.Rect; //Sound effects associated with the projectile, can be set to 'null' to make no sound. //Perhaps the check for null should be moved to the Sound class as a more general solution //instead of just checking wherever when we're just about to use it. public sfx = { spawn: Sound.get("sfxBulletSpawn"), hit: Sound.get("sfxBulletHit"), bounce: Sound.get("sfxBulletBounce") }; constructor(parameters: IProjectile = { owner: null }) { super(parameters); for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } this.collision = new Basics.Circle(this.position, this.size / 2); } public update(): boolean { var self = this; self.lifespan--; self.anim.count += 1; if (self.lifespan < 1) { if (self.hit && self.sfx.hit != null) { self.sfx.hit.play(); } else if (self.sfx.bounce != null) { self.sfx.bounce.play(); } self.die(); return false; } self.position.x += self.momentum.get().x; self.position.y += self.momentum.get().y; return true; } public die() { var self = this; //Remove from owner self.owner.owner.projectiles.splice(self.owner.projectiles.indexOf(self), 1); self.owner.projectiles.splice(self.owner.projectiles.indexOf(self), 1); //die self._die(); } } //Instances export class FlameThrowerProjectile extends Projectile { public damage: number = 10; public sprite: Resource = Resource.get("bulletBurningSprite"); public sfx = { spawn: Sound.get("sfxFlamethrowerSpawn"), hit: Sound.get("sfxBulletHit"), bounce: null }; } export class MainGunProjectile extends Projectile { public damage: number = 34; } } <file_sep>/scripts/game/classes/player.class.ts /// <reference path="../game.utility.ts" /> /// <reference path="../game.core.ts" /> //This file contains the player class //The player class describes a players "Actor", deals in control schemes and holds important information like hitPoints //Notice that player classes should never produce a "Projectile" on its own, but rather use "weaponBanks" as an in-between module tanks { export interface IPlayerControls { forward: boolean; backward: boolean; left: boolean; right: boolean; shoot: boolean; } export interface IPlayer extends IActor { controls?: IPlayerControls; } export class Player extends Actor { public weaponBanks: Weapon[] = []; public projectiles: Projectile[] = []; public sprite: Resource = Resource.get("tankRedSprite"); public anim: IActorAnimation = { name: "idle", count: 0 }; public momentum: Vector = new Vector(new Coord(), 2, 0.92); public acceleration: number = 0.05; public size: number = 32; public turnrate: number = 1; public hitPoints: number = tankApp.userOptions.playerHealth; public controls: IPlayerControls = { forward: false, backward: false, left: false, right: false, shoot: false } public collision: Basics.Circle | Basics.Rect; constructor(parameters: IPlayer = {}) { super(parameters); for (var key in parameters) { if (parameters.hasOwnProperty(key) && this.hasOwnProperty(key)) { this[key] = parameters[key]; } } this.collision = new Basics.Rect(this.position, this.size * 0.7, this.size * 0.7); //These are "Proof of concept" for gun placement and gun modification. //Real implementations should have a derived subclass to reference directly //instead of modifying the existing one directly this.weaponBanks.push( //Flamethrower new WeaponTankFlameThrower({ position: new Coord(10, 10), owner: this, angle: new Angle(180), }), //Main gun new WeaponTankMainGun({ owner: this, position: new Coord(10, 10), }) ); } public update(): boolean { var self = this; var changes = false; if (self.hitPoints < 1) { Sound.get('sfxTankDie').play(); self.die(); console.log("PLAYER " + (World.players.indexOf(self) * 1 + 1) + " IS DEAD!"); } //cooldowns for (var b = 0; b < self.weaponBanks.length; b++) { var bank = self.weaponBanks[b]; bank.cool(); } var cos = Math.cos(Angle.degreetoRadian(self.angle.get())); var sin = Math.sin(Angle.degreetoRadian(self.angle.get())); //Controls if (Math.abs(self.momentum.velocity.x) + Math.abs(self.momentum.velocity.y) > 0) { self.momentum.degrade(); self.position.x += self.momentum.get().x; self.position.y += self.momentum.get().y; changes = true; } if (self.controls.forward || self.controls.backward) { var direction = (self.controls.backward ? 0 - 1 : 1); self.anim.name = "move"; self.anim.count += direction; self.momentum.addForce(new Coord( (self.acceleration * cos) * direction, (self.acceleration * sin) * direction )); self.position.x += self.momentum.get().x; self.position.y += self.momentum.get().y; changes = true; } if (self.controls.left || self.controls.right) { var turn = (self.controls.left ? 0 - 1 : 1); if (!self.controls.forward && !self.controls.backward) { self.anim.name = "turn"; self.anim.count += turn; } self.angle.add(self.turnrate * turn); changes = true; } if (self.controls.shoot) { for (var w = 0; w < self.weaponBanks.length; w++) { var bank = self.weaponBanks[w]; bank.shoot(); } changes = true; } if (changes) { //Fix self animation overflow var animation = self.sprite.descriptor.anim .filter(function findAnimation(anim) { return anim.name === self.anim.name; })[0]; var animationState = Math.floor( self.anim.count / animation.rate ); if (animationState < 0) { self.anim.count = (animation.count * animation.rate) - 1; } else if (animationState >= animation.count) { self.anim.count = 0; } } return changes; } } }
e8d94f5c747343f87333c2af35b64bb00ec7642f
[ "Markdown", "TypeScript", "JSON with Comments" ]
11
TypeScript
merroth/tank-game
553d04c8bc0c134fa7e1996e9c02295a7de09cd5
5b2e4bc2e3ec1cc32b34a4cf5289040588f9294d
refs/heads/main
<repo_name>B-cavazos/javascript-practice<file_sep>/day-04/js/address.js const inputs = document.querySelectorAll('input'); console.log(inputs); const streetNumberInput = inputs[0]; const streetNameInput = inputs[1]; const cityInput = inputs[2]; const select = document.querySelector('select'); streetNumberInput.addEventListener('change', function(){ //if, AND if(this.value && parseInt(this.value)){ console.log('characters are in street number and theyre numbers!') } }); streetNameInput.addEventListener('change', function(){ console.log(this.value) (this.value && streetNumberInput.value) ? console.log('you typed some street name') : console.log('no number here'); //ternary, AND }); cityInput.addEventListener('change', function(){ // if else, NOT console.log(this.value) if(this.value){ console.log('characters are in the city') }else if(streetNameInput.value !== 'abc'){ console.log('make it abc') } }); select.addEventListener('change', function(){ //switch switch(this.value){ case 'ca': console.log('The Golden state'); break; case 'nv': console.log('Las Vegas is here'); break; case 'wa': console.log('The rainy State'); break; case 'or': console.log('The Beaver State'); break; } }); //validation <file_sep>/day-01/JS/main.js const myButton = document.querySelector('.this-button'); myButton.style.color = 'green'; myButton.style.fontSize = '50px'; myButton.innerText = 'Changed'; myButton.innerHTML = 'different'; myButton.addEventListener('mouseout', function(){ alert('hello') });
9d7c01f04909d2575057b384932da513c8e95a96
[ "JavaScript" ]
2
JavaScript
B-cavazos/javascript-practice
406fecdcea133c3b940bac9886210050f3511134
61a19004a7170e03506a08dfd28190917865fccc
refs/heads/master
<repo_name>DeepSouthT/arduino_lcd_touch_menu<file_sep>/src/window/navigationbar.cpp /******************************* * navigationbar.cpp * * Created: 07.06.2020 20:04:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Navigation bar displayed at the bottom of the display * This includes all its configurations * * Last modified: 13.06.2020 *******************************/ #include "window/navigationbar.h" #include "window/globalConfig.h" void navigationbar::rightButton(void) { uint16_t sx_loc = r_button_sx + window_sx; uint16_t sy_loc = r_button_sy + window_sy; navigationbarGLCD.setColor(VGA_WHITE); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); navigationbarGLCD.drawBitmap((sx_loc + 17), (sy_loc + 7), 48, 36, arrowHeadR); //navigationbarGLCD.setColor(10, 116, 255); //navigationbarGLCD.fillRect ((sx_loc + 12), (sy_loc + 20), (sx_loc + 37), (sy_loc + 30)); } void navigationbar::leftButton(void) { uint16_t sx_loc = l_button_sx + window_sx; uint16_t sy_loc = l_button_sy + window_sy; navigationbarGLCD.setColor(VGA_WHITE); navigationbarGLCD.drawRoundRect (sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); navigationbarGLCD.drawBitmap((sx_loc + 18), (sy_loc + 7), 48, 36, arrowHeadL); //navigationbarGLCD.setColor(10, 116, 255); //navigationbarGLCD.fillRect ((sx_loc + 40), (sy_loc + 20), (sx_loc + 65), (sy_loc + 30)); } void navigationbar::rightRedButton(void) { uint16_t sx_loc = r_button_sx + window_sx; uint16_t sy_loc = r_button_sy + window_sy; navigationbarGLCD.setColor(VGA_RED); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); delay(TOUCH_RESPONSE_DELAY); while (navigationbarTouch.dataAvailable()) { navigationbarTouch.read(); } navigationbarGLCD.setColor(VGA_WHITE); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); } void navigationbar::leftRedButton(void) { uint16_t sx_loc = l_button_sx + window_sx; uint16_t sy_loc = l_button_sy + window_sy; navigationbarGLCD.setColor(VGA_RED); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); delay(TOUCH_RESPONSE_DELAY); while (navigationbarTouch.dataAvailable()) { navigationbarTouch.read(); } navigationbarGLCD.setColor(VGA_WHITE); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); } void navigationbar::settingsButton(void) { uint16_t sx_loc = s_button_sx + window_sx; uint16_t sy_loc = s_button_sy + window_sy; navigationbarGLCD.setColor(VGA_WHITE); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); navigationbarGLCD.drawBitmap((sx_loc + 22), (sy_loc + 6), 43, 40, settings); } void navigationbar::settingsRedButton(void) { uint16_t sx_loc = s_button_sx + window_sx; uint16_t sy_loc = s_button_sy + window_sy; navigationbarGLCD.setColor(VGA_RED); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); delay(TOUCH_RESPONSE_DELAY); while (navigationbarTouch.dataAvailable()) { navigationbarTouch.read(); } navigationbarGLCD.setColor(VGA_WHITE); navigationbarGLCD.drawRoundRect(sx_loc, sy_loc, (sx_loc + button_w), (sy_loc + button_h)); } void navigationbar::drawNavigationbar(void) { navigationbar::rightButton(); navigationbar::settingsButton(); navigationbar::leftButton(); } void navigationbar::clearNavigationbar(void) { navigationbarGLCD.setColor(default_colour); navigationbarGLCD.fillRect(window_sx, window_sy, window_ex, window_ey); } <file_sep>/include/window/statusbar.h /******************************* * statusbar.h * * Created: 01.06.2020 21:48:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Status bar displayed at the top of the display * This includes all its configurations * * Last modified: 01.06.2020 *******************************/ #ifndef __STATUSBAR_H__ #define __STATUSBAR_H__ #include <UTFT.h> class statusbar { public: statusbar(UTFT& statusbarGLCD_): statusbarGLCD(statusbarGLCD_){}; ~statusbar(){}; //ToDo: return a status void drawStatusbar(void); void clearStatusbar(void); private: UTFT& statusbarGLCD; /// Static configuration const uint16_t window_sx = 0; const uint16_t window_sy = 0; const uint16_t window_ex = 319; const uint16_t window_ey = 30; const uint16_t default_colour = VGA_SILVER; }; #endif //__STATUSBAR_H__ <file_sep>/include/window/menu.h /******************************* * menu.h * * Created: 19.06.2020 22:01:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Base class for any menu * * Last modified: 19.06.2020 *******************************/ #ifndef __MENU_H__ #define __MENU_H__ #include <UTFT.h> #include "window/globalConfig.h" class menu { public: menu(){}; ~menu(){}; void drawMenuHead(UTFT& menuGLCD); void drawMenuData(UTFT& menuGLCD); void drawMenu(UTFT& menuGLCD); void clearMenuHead(UTFT& menuGLCD); void clearMenuData(UTFT& menuGLCD); void clearMenu(UTFT& menuGLCD); private: }; #endif //__MENU_H__<file_sep>/include/window/tempMenu.h /******************************* * tempMenu.h * * Created: 10.06.2020 21:59:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Temperature menu * This includes all its configurations * * Last modified: 19.06.2020 *******************************/ #ifndef __TEMPMENU_H__ #define __TEMPMENU_H__ #include <UTFT.h> #include "window/menu.h" // Icon extern unsigned int temp_icon[0x7B4]; extern unsigned int centigrade[0x60C]; extern uint8_t SevenSegNumFont[]; extern uint8_t BigFont[]; class tempmenu : menu { public: tempmenu(UTFT& tempmenuGLCD_): tempmenuGLCD(tempmenuGLCD_){}; ~tempmenu(){}; void drawMenuHead(void); void drawTemp(uint8_t temp); void drawMenuData(uint8_t temp); //ToDo: return a status void drawMenu(uint8_t temp); private: UTFT& tempmenuGLCD; }; #endif //__TEMPMENU_H__<file_sep>/include/window/navigationbar.h /******************************* * navigationbar.cpp * * Created: 07.06.2020 21:13:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Navigation bar displayed at the bottom of the display * This includes all its configurations * * Last modified: 13.06.2020 *******************************/ #ifndef __NAVIGATIONBAR_H__ #define __NAVIGATIONBAR_H__ #include <UTFT.h> #include <URTouch.h> // Icon extern unsigned int arrowHeadR[0x6C0]; extern unsigned int arrowHeadL[0x6C0]; extern unsigned int settings[0x6B8]; class navigationbar { public: navigationbar(UTFT& navigationbarGLCD_, URTouch& navigationbarTouch_): navigationbarGLCD(navigationbarGLCD_), navigationbarTouch(navigationbarTouch_){}; //navigationbar(UTFT& navigationbarGLCD_): navigationbarGLCD(navigationbarGLCD_){}; ~navigationbar(){}; //ToDo: return a status void drawNavigationbar(void); // void clearNavigationbar(void); // Function for drawing right button void rightButton(void); // Function for drawing left button void leftButton(void); // Function for drawing red button outline during the butten is pressed void rightRedButton(void); // Function for drawing red button outline during the butten is pressed void leftRedButton(void); // Function for drawing settings button void settingsButton(void); /// void settingsRedButton(void); private: UTFT& navigationbarGLCD; URTouch& navigationbarTouch; /// Static configuration : window const uint16_t window_sx = 0; const uint16_t window_sy = 189; const uint16_t window_ex = 319; const uint16_t window_ey = 239; const uint16_t default_colour = VGA_BLACK; /// Static configuration : button const uint16_t button_w = 82; const uint16_t button_h = 50; const uint16_t r_button_sx = 228; const uint16_t r_button_sy = 0; const uint16_t l_button_sx = 10; const uint16_t l_button_sy = 0; const uint16_t s_button_sx = 120; const uint16_t s_button_sy = 0; }; #endif //__NAVIGATIONBAR_H__ <file_sep>/src/window/clockMenu.cpp /******************************* * clockMenu.cpp * * Created: 10.06.2020 22:20:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Clock menu * This includes all its configurations * * Last modified: 09.07.2020 *******************************/ #include "window/clockMenu.h" void clockmenu::drawMenuHead(void) { menu::drawMenuHead(clockmenuGLCD); clockmenuGLCD.drawBitmap((window_head_sx + 10), (window_head_sy + 49), 50, 50, clockNeedle); } void clockmenu::deawTime(Local_time_t local_time) { clockmenuGLCD.setColor(VGA_WHITE); clockmenuGLCD.setBackColor(VGA_BLACK); clockmenuGLCD.setFont(BigFont); char str[5]; sprintf(str, "%02d", local_time.loc_time_hr); sprintf(str + strlen(str), ":"); sprintf(str + strlen(str), "%02d", local_time.loc_time_min); clockmenuGLCD.print(str, (window_data_sx + 158), (window_data_sy + 29)); sprintf(str, "%02d", local_time.loc_time_hr); sprintf(str + strlen(str), ":"); sprintf(str + strlen(str), "%02d", (local_time.loc_time_min + 4)); clockmenuGLCD.print(str, (window_data_sx + 158), (window_data_sy + 94)); } void clockmenu::drawMenuData(Local_time_t local_time) { menu::drawMenuData(clockmenuGLCD); clockmenuGLCD.drawBitmap((window_data_sx + 78), (window_data_sy + 24), 68, 43, german); clockmenuGLCD.drawBitmap((window_data_sx + 78), (window_data_sy + 89), 67, 43, canada); clockmenu::deawTime(local_time); } void clockmenu::drawMenu(Local_time_t local_time) { clockmenu::drawMenuHead(); clockmenu::drawMenuData(local_time); } <file_sep>/include/window/homeMenu.h /******************************* * homeMenu.h * * Created: 09.06.2020 21:19:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Home menu * This includes all its configurations * * Last modified: 21.06.2020 *******************************/ #ifndef __HOMEMENU_H__ #define __HOMEMENU_H__ #include <UTFT.h> #include "window/menu.h" // Icon extern unsigned int house[0x866]; extern unsigned int semicolon[0x172]; extern uint8_t SevenSegNumFont[]; extern uint8_t BigFont[]; class homemenu : menu { public: homemenu(UTFT& homemenuGLCD_): homemenuGLCD(homemenuGLCD_){}; ~homemenu(){}; void drawMenuHead(void); void deawTime(Local_time_t local_time); void drawMenuData(Local_time_t local_time); //ToDo: return a status void drawMenu(Local_time_t local_time); private: UTFT& homemenuGLCD; }; #endif //__HOMEMENU_H__<file_sep>/src/window/currencyMenu.cpp /******************************* * currencyMenu.cpp * * Created: 10.06.2020 22:38:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Currency menu * This includes all its configurations * * Last modified: 09.07.2020 *******************************/ #include "window/currencyMenu.h" void currencymenu::drawMenuHead(void) { menu::drawMenuHead(currencymenuGLCD); currencymenuGLCD.drawBitmap((window_head_sx + 10), (window_head_sy + 49), 35, 60, doller); } void currencymenu::drawCurrency(Currency_rate_t currency_rate) { currencymenuGLCD.setColor(VGA_WHITE); currencymenuGLCD.setBackColor(VGA_BLACK); currencymenuGLCD.setFont(BigFont); char str[2]; sprintf(str, "%02d", currency_rate.euro_de_rate); currencymenuGLCD.print(str, (window_data_sx + 158), (window_data_sy + 29)); sprintf(str, "%02d", currency_rate.doller_ca_rate); currencymenuGLCD.print(str, (window_data_sx + 158), (window_data_sy + 94)); } void currencymenu::drawMenuData(Currency_rate_t currency_rate) { menu::drawMenuData(currencymenuGLCD); currencymenuGLCD.drawBitmap((window_data_sx + 78), (window_data_sy + 24), 68, 43, german); currencymenuGLCD.drawBitmap((window_data_sx + 78), (window_data_sy + 89), 67, 43, canada); drawCurrency(currency_rate); } void currencymenu::drawMenu(Currency_rate_t currency_rate) { currencymenu::drawMenuHead(); currencymenu::drawMenuData(currency_rate); } <file_sep>/include/window/currencyMenu.h /******************************* * currencyMenu.h * * Created: 10.06.2020 22:35:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Currency menu * This includes all its configurations * * Last modified: 09.07.2020 *******************************/ #ifndef __CURRENCYMENU_H__ #define __CURRENCYMENU_H__ #include <UTFT.h> #include "window/menu.h" // Icon extern unsigned int doller[0x834]; extern unsigned int german[0xB6C]; extern unsigned int canada[0xB41]; extern uint8_t SevenSegNumFont[]; extern uint8_t BigFont[]; class currencymenu : menu { public: currencymenu(UTFT& currencymenuGLCD_): currencymenuGLCD(currencymenuGLCD_){}; ~currencymenu(){}; /// Currency rates struct Currency_rate_t { uint8_t euro_de_rate; uint8_t doller_ca_rate; } currency_rate; void drawMenuHead(void); void drawCurrency(Currency_rate_t currency_rate); void drawMenuData(Currency_rate_t currency_rate); //ToDo: return a status void drawMenu(Currency_rate_t currency_rate); private: UTFT& currencymenuGLCD; }; #endif //__CURRENCYMENU_H__<file_sep>/include/window/clockMenu.h /******************************* * clockMenu.h * * Created: 10.06.2020 22:17:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Clock menu * This includes all its configurations * * Last modified: 15.06.2020 *******************************/ #ifndef __CLOCKMENU_H__ #define __CLOCKMENU_H__ #include <UTFT.h> #include "window/menu.h" // Icon extern unsigned int clockNeedle[0x9C4]; extern unsigned int german[0xB6C]; extern unsigned int canada[0xB41]; extern uint8_t SevenSegNumFont[]; extern uint8_t BigFont[]; class clockmenu : menu { public: clockmenu(UTFT& clockmenuGLCD_): clockmenuGLCD(clockmenuGLCD_){}; ~clockmenu(){}; void drawMenuHead(void); void deawTime(Local_time_t local_time); void drawMenuData(Local_time_t local_time); void drawMenu(Local_time_t local_time); private: UTFT& clockmenuGLCD; }; #endif //__CLOCKMENU_H__<file_sep>/README.md # arduino_lcd_touch_menu Application for testing a multilevel menu tree on LCD touch screen. <file_sep>/src/window/homeMenu.cpp /******************************* * homeMenu.cpp * * Created: 09.06.2020 21:24:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Home menu * This includes all its configurations * * Last modified: 02.07.2020 *******************************/ #include "window/homeMenu.h" void homemenu::drawMenuHead(void) { menu::drawMenuHead(homemenuGLCD); homemenuGLCD.drawBitmap((window_head_sx + 10), (window_head_sy + 54), 50, 43, house); } void homemenu::deawTime(Local_time_t local_time) { homemenuGLCD.setColor(VGA_WHITE); homemenuGLCD.setBackColor(VGA_BLACK); homemenuGLCD.setFont(SevenSegNumFont); char str[2]; sprintf(str, "%02d", local_time.loc_time_hr); homemenuGLCD.print(str, (window_data_sx + 15), (window_data_sy + 24)); homemenuGLCD.drawBitmap((window_data_sx + 85), (window_data_sy + 32), 10, 37, semicolon); sprintf(str, "%02d", local_time.loc_time_min); homemenuGLCD.print(str, (window_data_sx + 98), (window_data_sy + 24)); homemenuGLCD.drawBitmap((window_data_sx + 168), (window_data_sy + 32), 10, 37, semicolon); sprintf(str, "%02d", local_time.loc_time_sec); homemenuGLCD.print(str, (window_data_sx + 182), (window_data_sy + 24)); } void homemenu::drawMenuData(Local_time_t local_time) { menu::drawMenuData(homemenuGLCD); homemenuGLCD.setColor(VGA_WHITE); homemenuGLCD.setBackColor(VGA_BLACK); homemenuGLCD.setFont(BigFont); homemenuGLCD.print("01.10.2019", (window_data_sx + 68), (window_data_sy + 89)); homemenu::deawTime(local_time); } void homemenu::drawMenu(Local_time_t local_time) { homemenu::drawMenuHead(); homemenu::drawMenuData(local_time); } <file_sep>/include/window/globalConfig.h /******************************* * globalConfig.h * * Created: 13.06.2020 17:53:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Global configurations * * Last modified: 13.06.2020 *******************************/ #ifndef __GLOBALCONFIG_H__ #define __GLOBALCONFIG_H__ /** * The amount of time which is delayed after each touch event * Only after this delay, the program proceed after a touch **/ #define TOUCH_RESPONSE_DELAY 150 /// Default backgraund of menus static const uint16_t default_menu_colour = VGA_BLACK; /// Global window coordinates static const uint16_t window_sx = 0; static const uint16_t window_sy = 31; static const uint16_t window_ex = 319; static const uint16_t window_ey = 179; /// Menu header window coordinates static const uint16_t window_head_sx = 0; static const uint16_t window_head_sy = 31; static const uint16_t window_head_ex = 61; static const uint16_t window_head_ey = 188; /// Menu content window coordinates static const uint16_t window_data_sx = 62; static const uint16_t window_data_sy = 31; static const uint16_t window_data_ex = 319; static const uint16_t window_data_ey = 179; /// Local time struct Local_time_t { uint8_t loc_time_hr; uint8_t loc_time_min; uint8_t loc_time_sec; }; #endif //__GLOBALCONFIG_H__ <file_sep>/src/main.cpp /******************************* * arduino_lcd_touch_menu.c * * Created: 22.09.2019 22:45:00 * Author : DeepSouthT * * Used: * IC > ATMega2560 * Board > Arduino Mega 2560 * IDE > Visual Studio Code 1.45.1 * PlugIn > PlatformIo 1.3.0 * Programmer > Arduino * Display > ITDB02-3.2S V2 (AptoFun TFT 3.2 TFT LCD Touch) / TFT_320QVT_9341 * Display adapter > AptoFun TFT 3.2 Shield for 5v to 3.3v level shift * * Description: * Sample application for multilevel menu tree * * ITDB02-3.2S V2 module is 3.2" TFT LCD with 65K color 320 x 240 resolutions * The controller of this LCD module is ILI9341 * The controller supports 16bit data interface with control interface of four wires * https://www.itead.cc/wiki/ITDB02-3.2S_Arduino_Shield_V2 * * Additional information: * (240 xRGB)(H) x 320(V) dots * 262K color (262144 color) in 18 bit data * In 16 bit, it is RGB565 * 720 ch source drive (240 xRGB or 240 x 3 = 720 segments/colomns) * 320 ch gate drive * 172800 bytes GRAM (it is exactly one frane in 18 bit color mode) * Memory band width: 30fps x 240 x 320 x 2.25 = 4,94 MBytes/sec * * The UTFT and URTouch libraries are from http://www.rinkydinkelectronics.com/index.php * * Version: * 0.1 > Basic menu with four screens (no image) * 0.2 > Basic menu with four screens with image * 0.3 > Migrating to VSCode + PlatformIO * * Last modified: 09.07.2020 *******************************/ #include <Arduino.h> #include <UTFT.h> #include <URTouch.h> #include "window/globalConfig.h" #include "window/statusbar.h" #include "window/navigationbar.h" #include "window/homeMenu.h" #include "window/tempMenu.h" #include "window/clockMenu.h" #include "window/currencyMenu.h" // Initialize display // ------------------ //UTFT myGLCD(ILI9341_16, 38, 39, 40, 41); UTFT myGLCD(ITDB32S_V2, 38, 39, 40, 41); // Initialize touchscreen // ---------------------- URTouch myTouch( 6, 5, 4, 3, 2); statusbar statusbar_obj(myGLCD); navigationbar navigationbar_obj(myGLCD, myTouch); homemenu homemenu_obj(myGLCD); tempmenu tempmenu_obj(myGLCD); clockmenu clockmenu_obj(myGLCD); currencymenu currencymenu_obj(myGLCD); // Declare which fonts we will be using extern uint8_t BigFont[]; extern uint8_t SevenSegNumFont[]; // Variables for the touch coordinates int x_touch, y_touch; bool update_home_data = false; bool update_clock_data = false; bool update_currency_data = false; bool update_temp_data = false; struct Local_time_t local_time; uint8_t temperature = 22; //struct Currency_rate_t currency_rate; /************************* ** Custom functions ** *************************/ // Function for drawing initial static areas void initStaticArea(void) { statusbar_obj.clearStatusbar(); navigationbar_obj.clearNavigationbar(); navigationbar_obj.drawNavigationbar(); } void homeScreen() { homemenu_obj.drawMenu(local_time); } void tempScreen() { tempmenu_obj.drawMenu(temperature); } void clockScreen() { clockmenu_obj.drawMenu(local_time); } void currencyScreen() { currencymenu_obj.drawMenu(currencymenu_obj.currency_rate); } // Collection of all screens void (*stateAll[4])() = {homeScreen, tempScreen, clockScreen, currencyScreen}; // Totel number of screens unsigned int statAll_count = sizeof(stateAll)/sizeof(stateAll[0]); // Function pointer pointing to the current screen void (*stateActive)(void); // Index for scrolling through the available screens int stateActiveIndex = 0; // Function to change the active screen on button press void stateChange(int input) { if(input == 1) { stateActiveIndex++; stateActiveIndex = stateActiveIndex%statAll_count; stateActive = stateAll[stateActiveIndex]; Serial.println("++"); Serial.println(stateActiveIndex); }else if(input == 0) { stateActiveIndex--; if(stateActiveIndex < 0) { stateActiveIndex = stateActiveIndex + statAll_count; } stateActiveIndex = stateActiveIndex%statAll_count; stateActive = stateAll[stateActiveIndex]; Serial.println("--"); Serial.println(stateActiveIndex); } else { stateActiveIndex = 0; stateActive = stateAll[stateActiveIndex]; Serial.println("??"); Serial.println(stateActiveIndex); } } ISR(TIMER1_COMPA_vect) { /// Time if (local_time.loc_time_sec < 59) { local_time.loc_time_sec++; } else { local_time.loc_time_sec = 0; if(local_time.loc_time_min < 59) { local_time.loc_time_min++; } else { local_time.loc_time_min = 0; if(local_time.loc_time_hr < 23) { local_time.loc_time_hr++; } else { local_time.loc_time_hr = 0;} } } /// Temperature if(local_time.loc_time_sec == 30) { temperature = 31; } else { temperature = 28; } update_home_data = true; update_clock_data = true; update_temp_data = true; } /************************* ** Required functions ** *************************/ void setup() { // initialize serial communication at 9600 bits per second: Serial.begin(9600); Serial.println("Started"); currencymenu_obj.currency_rate.euro_de_rate = 55; currencymenu_obj.currency_rate.doller_ca_rate = 44; //stop interrupts cli(); //set timer1 interrupt at 1Hz TCCR1A = 0;// set entire TCCR1A register to 0 TCCR1B = 0;// same for TCCR1B TCNT1 = 0;//initialize counter value to 0 // set compare match register for 1hz increments OCR1A = 15624;// = (16*10^6) / (1*1024) - 1 (must be <65536) // turn on CTC mode TCCR1B |= (1 << WGM12); // Set CS12 and CS10 bits for 1024 prescaler TCCR1B |= (1 << CS12) | (1 << CS10); // enable timer compare interrupt TIMSK1 |= (1 << OCIE1A); //allow interrupts sei(); // Initial setup myGLCD.InitLCD(); myGLCD.clrScr(); myTouch.InitTouch(); myTouch.setPrecision(PREC_MEDIUM); myGLCD.setFont(BigFont); myGLCD.setBackColor(0, 0, 255); myGLCD.setBrightness(16); // default/max is 16 // Initialize static areas initStaticArea(); // Start screen homemenu_obj.drawMenu(local_time); } void loop() { if (myTouch.dataAvailable()) { myTouch.read(); x_touch = myTouch.getX(); y_touch = myTouch.getY(); if((y_touch > 180) && (y_touch < 230)) // Lower buttons { if((x_touch > 10) && (x_touch < 113)) // Left button { navigationbar_obj.leftRedButton(); stateChange(0); stateActive(); } else if((x_touch > 114) && (x_touch < 226)) // Settings button { navigationbar_obj.settingsRedButton(); //stateChange(1); //stateActive(); } else if((x_touch > 227) && (x_touch < 339)) // Right button { navigationbar_obj.rightRedButton(); stateChange(1); stateActive(); } else { // Do nothing } } } if ((update_home_data)&&(stateActiveIndex == 0)) { homemenu_obj.deawTime(local_time); update_home_data = false; } else if ((update_temp_data)&&(stateActiveIndex == 1)) { tempmenu_obj.drawTemp(temperature); update_temp_data = false; } else if ((update_clock_data)&&(stateActiveIndex == 2)) { update_clock_data = false; clockmenu_obj.deawTime(local_time); } else if ((update_currency_data)&&(stateActiveIndex == 3)) { update_currency_data = false; currencymenu_obj.drawCurrency(currencymenu_obj.currency_rate); } } <file_sep>/src/window/statusbar.cpp /******************************* * statusbar.cpp * * Created: 01.06.2020 21:48:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Status bar displayed at the top of the display * This includes all its configurations * * Last modified: 04.06.2020 *******************************/ #include "window/statusbar.h" void statusbar::drawStatusbar(void) { statusbarGLCD.setColor(default_colour); statusbarGLCD.fillRect (0, 0, 319, 30); } void statusbar::clearStatusbar(void) { statusbarGLCD.setColor(default_colour); statusbarGLCD.fillRect(window_sx, window_sy, window_ex, window_ey); } <file_sep>/src/window/tempMenu.cpp /******************************* * tempMenu.cpp * * Created: 10.06.2020 22:03:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Temperature menu * This includes all its configurations * * Last modified: 19.06.2020 *******************************/ #include "window/tempMenu.h" void tempmenu::drawMenuHead(void) { menu::drawMenuHead(tempmenuGLCD); tempmenuGLCD.drawBitmap((window_head_sx + 10), (window_head_sy + 44), 29, 68, temp_icon); } void tempmenu::drawTemp(uint8_t temp) { tempmenuGLCD.setColor(VGA_WHITE); tempmenuGLCD.setBackColor(VGA_BLACK); tempmenuGLCD.setFont(SevenSegNumFont); char str[2]; sprintf(str, "%02d", temp); tempmenuGLCD.print(str, (window_data_sx + 98), (window_data_sy + 24)); } void tempmenu::drawMenuData(uint8_t temp) { menu::drawMenuData(tempmenuGLCD); tempmenuGLCD.drawBitmap((window_data_sx + 168), (window_data_sy + 29), 36, 43, centigrade); tempmenu::drawTemp(temp); } void tempmenu::drawMenu(uint8_t temp) { tempmenu::drawMenuHead(); tempmenu::drawMenuData(temp); } <file_sep>/src/window/menu.cpp /******************************* * clockMenu.cpp * * Created: 19.06.2020 22:09:00 * Author : DeepSouthT * * Used: * ToDo * * Description: * Base class for any menu * * Last modified: 19.06.2020 *******************************/ #include "window/menu.h" #include "window/globalConfig.h" void menu::drawMenuHead(UTFT& menuGLCD) { menu::clearMenuHead(menuGLCD); } void menu::drawMenuData(UTFT& menuGLCD) { menu::clearMenuData(menuGLCD); } void menu::drawMenu(UTFT& menuGLCD) { menu::drawMenuHead(menuGLCD); menu::drawMenuData(menuGLCD); } void menu::clearMenuHead(UTFT& menuGLCD) { menuGLCD.setColor(default_menu_colour); menuGLCD.fillRect (window_head_sx, window_head_sy, window_head_ex, window_head_ey); } void menu::clearMenuData(UTFT& menuGLCD) { menuGLCD.setColor(default_menu_colour); menuGLCD.fillRect (window_data_sx, window_data_sy, window_data_ex, window_data_ey); } void menu::clearMenu(UTFT& menuGLCD) { menuGLCD.setColor(default_menu_colour); menuGLCD.fillRect(window_sx, window_sy, window_ex, window_ey); }
9252ecfbba6d064dc16665ad5ddda821c3771c97
[ "Markdown", "C", "C++" ]
17
C++
DeepSouthT/arduino_lcd_touch_menu
1a1eecc0827dbcff208837c11e41a6342ef804e8
f669a25c7aff0c9720e212352bbeff6daff2beb8
refs/heads/master
<file_sep># OpenInfSys Homework <file_sep>VLANS = [10, 20, 30, 1, 2, 100, 10, 30, 3, 4, 10] VLANS = set(VLANS) VLANS = list(VLANS) print(VLANS) <file_sep>CONFIG = 'switchport trunk allowed vlan 1,3,10,20,30,100' CONFIG = CONFIG.split(' ') VLAN = CONFIG[4].split(',') print(VLAN) <file_sep>NAT = "ip nat inside source list ACL interface FastEthernet01 overload" NEWNAT = NAT.replace('Fast', 'Giga') print(NAT.replace('Fast', 'Giga')) <file_sep>import time delay = 10 def bank(): sum = int(input("Введите сумму вклада ")) percent = int(input("Введите процент ")) years = int(input("Введите количество лет ")) total = int(sum * (1 + (percent / 100)) ** years) print("Сумма вклада равна " + str(total)) print(bank()) time.sleep (delay) <file_sep>command1 = 'switchport trunk allowed vlan 1,3,10,20,30,100' command2 = 'switchport trunk allowed vlan 1,3,100,200,300' VLAN1 = command1.split(' ') VLAN2 = command2.split(' ') VLAN1 = VLAN1[4].split(',') VLAN2 = VLAN2[4].split(',') VLAN1 = set(VLAN1) VLAN2 = set(VLAN2) TOTAL = VLAN1 & VLAN2 TOTAL = list(TOTAL) print(TOTAL) <file_sep>MAC = 'AAAA:BBBB:CCCC' MAC = MAC.replace(':','') MAC = int(MAC, 16) MAC = bin(MAC) print(MAC) <file_sep>import time delay = 10 def xor_cipher( str, key ): encript_str = "" for letter in str: encript_str += chr( ord(letter) ^ key ) return encript_str strg = "Много разных букв" key = 2 print( "original:\t", strg ) encr_strg = xor_cipher( strg, key ) print( "encript:\t", encr_strg ) print( "decript:\t", xor_cipher( encr_strg, key ) ) time.sleep (delay)
4e31e43f21a78d61ecb0a55e6111137b4df58557
[ "Markdown", "Python" ]
8
Markdown
DariaMinyaylo/OpenInfSys
6d56dd4ebb8df384b7f0b539a357f930fbc5db0c
e353b1b27ed3d37976a8d5eb924a06cb66f7dfb6
refs/heads/master
<repo_name>wynforth/fflogpps<file_sep>/js/shared.js var s0 = performance.now(); const base_url = "https://www.fflogs.com:443/v1"; const percentColors = [ { pct: 0.0, color: { r: 0x00, g: 0xCC, b: 0x11 } }, { pct: 0.5, color: { r: 0xCC, g: 0xCC, b: 0x11 } }, { pct: 0.99, color: { r: 0xCC, g: 0x00, b: 0x11 } }, { pct: 1.0, color: { r: 0xFF, g: 0x00, b: 0x11 } } ]; var getColorForPercentage = function(pct) { for (var i = 1; i < percentColors.length - 1; i++) { if (pct < percentColors[i].pct) { break; } } var lower = percentColors[i - 1]; var upper = percentColors[i]; var range = upper.pct - lower.pct; var rangePct = (pct - lower.pct) / range; var pctLower = 1 - rangePct; var pctUpper = rangePct; var color = { r: Math.floor(lower.color.r * pctLower + upper.color.r * pctUpper), g: Math.floor(lower.color.g * pctLower + upper.color.g * pctUpper), b: Math.floor(lower.color.b * pctLower + upper.color.b * pctUpper) }; return 'rgb(' + [color.r, color.g, color.b].join(',') + ')'; // or output as hex if preferred } var getUrlParameter = function getUrlParameter(sParam) { var sPageURL = decodeURIComponent(window.location.search.substring(1)), sURLVariables = sPageURL.split('&'), sParameterName, i; for (i = 0; i < sURLVariables.length; i++) { sParameterName = sURLVariables[i].split('='); if (sParameterName[0] === sParam) { return sParameterName[1] === undefined ? true : sParameterName[1]; } } }; var api_key = getUrlParameter('api_key'); class Timer { constructor(name, duration){ this.name = name; this.duration = duration; this.current = 0; this.justFell = false; } restart(){ this.current = this.duration; } restartOffset(){ this.current += this.duration; } update(time){ if(time != 0){ var wasPos = this.current > 0; if(wasPos){ this.current -= time; } if(this.current < 0) if(wasPos) this.justFell = true; else this.justFell = false; } } set(time){ this.current = time; } stop(){ this.current = 0; } isActive(){ return this.current > 0; } extend(add, max){ this.current = Math.min(max, this.current + add); } canRefresh() { return this.isActive() || this.justFell; } } class Buff { constructor(name, bonus, active, restricted, exclusive){ this.name = name; this.bonus = bonus; this.active = active == undefined ? false:active; this.restricted = restricted == undefined ? []:restricted; this.exclusive = exclusive == undefined ? []:exclusive; this.stopTime = 0; //console.log(this.name); //console.log(this.restricted); } isAllowed(event){ if(!this.active) return false; if(this.restricted.length == 0 && this.exclusive.length == 0) return true; var valid = true; if(this.exclusive.length > 0) valid = this.exclusive.indexOf(event.name) > -1; //have to be ON the list if(this.restricted.length > 0) valid = this.restricted.indexOf(event.name) == -1; //have to be OFF the list return valid; } apply(potency, event){ if(this.isAllowed(event)){ return Math.trunc(potency * (1 + this.getBonus(event))); } return potency; } getDisplay(event){ return (this.getBonus(event) * 100).toFixed(0) + "%"; } getBonus(event){ return this.bonus; } applybuff(){ this.active = true; } stopBuff(event){ this.stopTime = event.fightTime; } removeBuff(){ this.active = false; this.stopTime = 0; } } class BuffDirect extends Buff{ constructor(name, bonus, active, restricted, exclusive){ super(name, bonus, active, restricted, exclusive); } apply(potency, event){ if(this.isAllowed(event)){ return potency + this.getBonus(event); } return potency; } getDisplay(){ return this.getBonus(); } } class BuffThunder extends BuffDirect { constructor(name, bonus, active, restricted, exclusive) { super(name, bonus, active, restricted, exclusive); } apply(potency, event) { this.setBonus(event); return super.apply(potency, event); } isAllowed(event) { this.setBonus(event); return super.isAllowed(event); } setBonus(event) { this.bonus = 0; if (event.type == 'damage') { switch (event.name) { case 'Thunder I': this.bonus = 240; break; case 'Thunder II': this.bonus = 120; break; case 'Thunder III': this.bonus = 320; break; case 'Thunder IV': this.bonus = 180; break; } } } } class BuffStack extends Buff{ constructor(name, initial, stackbonus, maxStacks, baseStacks, active, restricted, exclusive){ super(name, initial, active, restricted, exclusive); this.maxStacks = maxStacks; this.baseStacks = baseStacks; this.stacks = baseStacks; this.stackBonus = stackbonus == undefined ? 0:stackbonus; } isAllowed(event){ if(this.stacks > 0) return super.isAllowed(event); return false; } getBonus(){ //console.log(this); return this.bonus + (this.stackBonus * this.stacks); } addStacks(num){ this.stacks = Math.min(this.maxStacks, this.stacks + num); this.active = this.stacks > 0; } remStacks(num){ this.stacks = Math.max(0, this.stacks - num); this.active = this.stacks > 0; } setStacks(num){ if(num < 0) this.stacks = 0; else{ super.applybuff(); this.stacks = Math.min(this.maxStacks, num); } } applybuff(){ super.applybuff(); if(this.stacks <= 0) this.stacks = this.baseStacks; } removebuff(){ this.setStacks(0); super.removeBuff(); } } class BuffStackFire extends BuffStack{ constructor(name, initial, stackbonus, maxStacks, baseStacks, active, restricted, exclusive){ super(name, initial, stackbonus, maxStacks, baseStacks, active, restricted, exclusive); } getBonus(event){ //console.log(event); if(['Blizzard I', 'Blizzard II','Blizzard III', 'Blizzard IV', 'Freeze'].indexOf(event.name) > -1) return this.stacks * -.1; return this.bonus + (this.stackBonus * this.stacks); } } class BuffDirectConsumedStack extends BuffStack{ constructor(name, initial, stackbonus, maxStacks, baseStacks, active, restricted, exclusive){ super(name, initial, stackbonus, maxStacks, baseStacks, active, restricted, exclusive); } getBonus(){ //console.log(this); return this.bonus + (this.stackBonus * this.stacks); } apply(potency, event){ if(this.isAllowed(event)){ var ret = potency + this.getBonus(); this.stacks--; this.active = this.stacks > 0; return ret; } return potency; } getDisplay(){ return this.getBonus(); } } class BuffTimed extends Buff { constructor(name, bonus, duration, restricted, exclusive){ super(name, bonus, false, restricted, exclusive); this.duration = duration; this.current = 0; } applyBuff(event){ super.applyBuff(event); this.current = event.fightTime + this.duration; this.active = Object.keys(this.targets).length > 0; } update(event){ if(this.current != 0){ if(this.current <= event.fightTime){ this.current = 0; this.active = false; } } } isAllowed(event){ return this.current >= event.fightTime && super.isAllowed(event); } } class Debuff extends Buff{ constructor(name, bonus, restricted, exclusive){ super(name, bonus, false, restricted, exclusive); this.targets = []; } add(event){ if(event.targetID == null) console.log(event); if(this.targets.indexOf(event.targetID) == -1) this.targets.push(event.targetID); this.active = this.targets.length > 0; } remove(event){ var index = this.targets.indexOf(event.targetID); if(index > -1) this.targets.splice(index, 1); this.active = this.targets.length > 0; } clear(){ this.targets = []; } isTarget(targetID){ return this.targets.indexOf(targetID) > -1; } isAllowed(event){ if(this.isTarget(event.targetID)) return super.isAllowed(event); return false; } apply(potency, event){ if(this.isAllowed(event)) return super.apply(potency, event); return potency; } } class DebuffTimed extends Debuff { constructor(name, bonus, duration, restricted, exclusive){ super(name, bonus, false, restricted, exclusive); this.duration = duration; this.targets = {}; } add(event){ this.targets[event.targetID] = event.fightTime + this.duration; this.active = Object.keys(this.targets).length > 0; } remove(targetID){ //noop only removed when time runs out this.active = Object.keys(this.targets).length > 0; } update(event){ for(var t in this.targets){ //console.log(event); if(this.targets[t] <= event.fightTime){ //console.log("deleting " + t); delete this.targets[t]; } } this.active = Object.keys(this.targets).length > 0; } clear(){ this.targets = {}; } isTarget(targetID){ return this.targets.hasOwnProperty(targetID); } } class DebuffDirect extends Debuff{ constructor(name, bonus, restricted, exclusive){ super(name, bonus, restricted, exclusive); } apply(potency, event){ if(this.isAllowed(event)){ return potency + this.getBonus(); } return potency; } getDisplay(){ return this.getBonus(); } } class BuffDisplay{ constructor(name, color, image){ this.name = name; this.color = color; if(image == undefined) this.image = this.name.toLowerCase().replace(/ /g,'_') + '.png'; else this.image = image; } asHeader(){ if(this.image == '') console.log(this.name); return `<td class=\"status-col\"><img src="img/${this.image}" title="${this.name}"/></td>` } display(event, buff){ if(buff == undefined) return undefined; return this.displayString(event, buff); } displayString(event, buff){ if(buff.active) if(event.name == this.name && ["cast","applybuff", "applydebuff"].indexOf(event.type) > -1) return `<div class="center status-block" style="background-color: ${this.color}"><img src="img/${this.image}"/></div>` else return `<div class="center status-block" style="background-color: ${this.color}"></div>` return ''; } } class BuffDisplayCount extends BuffDisplay{ constructor(name, image){ super(name, '', image); } display(event, buff){ return `<div class="center status-block">${buff.stacks}</div>` } } class BuffDisplayGradient extends BuffDisplay{ constructor(name, image){ super(name, '', image); } display(event, buff){ return `<div title="Value: ${buff.stacks}" class="center status-block" style="background-color: ${getColorForPercentage(buff.stacks/buff.maxStacks)}"></div>` } } function httpGetAsync(theUrl, callback) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(JSON.parse(xmlHttp.responseText)); } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); } function fetchUrl(theUrl, callback, args) { var xmlHttp = new XMLHttpRequest(); xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) callback(JSON.parse(xmlHttp.responseText), args); } xmlHttp.open("GET", theUrl, true); // true for asynchronous xmlHttp.send(null); } function httpGet(theUrl) { var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", theUrl, false); // true for asynchronous xmlHttp.send(null); return JSON.parse(xmlHttp.responseText); } function getBasicData(event, fight) { //console.log(event); event.name = event.type == 'death' ? 'Death' : event.ability.name; event.fightTime = (event.timestamp - fight.start) / 1000, event.hitType = event.hitType == undefined ? '' : hitTypes[event.hitType], event.dmgType = event.amount == undefined ? 0 : event.ability.type, event.amount = event.amount == undefined ? 0 : event.amount, event.isDirect = event.multistrike == undefined ? false: event.multistrike return event; var data = {}; data = { 'type': event.type, 'name': event.type == 'death' ? 'Death' : event.ability.name, 'timestamp': event.timestamp, 'fightTime': (event.timestamp - fight.start) / 1000, 'target': event.targetID == undefined ? '' : event.targetID, 'isTargetFriendly': event.targetIsFriendly, 'source': event.sourceID == undefined ? '' : event.sourceID, 'isSourceFriendly': event.sourceIsFriendly, 'hitType': event.hitType == undefined ? '' : hitTypes[event.hitType], 'dmgType': event.amount == undefined ? 0 : event.ability.type, 'amount': event.amount == undefined ? 0 : event.amount, 'isDirect' : event.multistrike == undefined ? false: event.multistrike } return data; } var hitTypes = { 0: "Miss", 1: "Hit", 2: "Crit" } // OLD pre August 8 parses var damageTypes = { 0: "", 1: "physical", 2: "lightning", 4: "fire", 8: "sprint", 16: "water", 32: "unaspected", 64: "ice", 128: "earth", 512: "air", 1024: "ruin", } //post Aug 8 parses damageTypes = { 0: "", 1: "dot_phys", //2: "lightning", //4: "fire", 8: "heal", //16: "water", 32: "pet", 64: "dot_magic", 128: "phys", //512: "air", 1024: "magic", } var s1 = performance.now(); console.log("Shared Loaded in " + (s1-s0).toFixed(4) + "ms");<file_sep>/js/events.js function processReport(report) { var proc0 = performance.now(); //console.log("Report:"); console.log(report); var result = { report: { reportID: getUrlParameter("report"), fightID: getUrlParameter("fight"), }, fight: { team: {}, enemies: {} }, player: { name: getUrlParameter("name"), pets: [] }, events: {}, totals: {}, } result = parseReport(report, result); var par1 = performance.now(); console.log("Report parsing took " + (par1-proc0).toFixed(4) + "ms"); //console.log(result); var link = `https://www.fflogs.com/reports/${result.report.reportID}#fight=${result.report.fightID}&type=damage-done`; //$(".summary").append(`<b>${result.fight.team[result.player.ID]}</b> as a <span class="${result.player.type}">${result.player.type}</span> (<a href="${link}">FFLogs</a>)`); $(".container.summaries .header").html(`<b>${result.fight.team[result.player.ID]}</b> the ${result.player.type}`); $(".header").toggleClass(result.player.type, true); $(".container").toggleClass(result.player.type, true); if (result.player.pets.length > 0) { var pets = ''; for (var p in result.player.pets) { pets += result.fight.team[result.player.pets[p]] + ', '; } $(".container.summaries .header").append(` with ${pets.slice(0,-2)}`); } var nme = ''; for (var e in result.fight.enemies) { nme += result.fight.enemies[e] + ', '; } $(".container.summaries .header").append(` <b>VS.</b> ${nme.slice(0,-2)}`); $(".summary").append(`<span class="castType">Full report at <a href="${link}">FFLogs</a></span>`); $('.summary').append(`<b>Reported Duration:</b> ${result.fight.duration} seconds.`) var url = base_url + "/report/events/" + result.report.reportID + "?translate=true"; url += "&start=" + result.fight.start; url += "&end=" + result.fight.end; url += "&actorid=" + result.player.ID; url += "&api_key=" + api_key; //console.log(url); //console.log(result.fight.team); //console.log(result.fight.enemies); var callback = processGeneric; if (Object.keys(parseFunctions).indexOf(result.player.type) > -1) callback = processClass; fetchUrl(url, callback, result); var proc1 = performance.now(); console.log("processReport took " + (proc1-proc0).toFixed(4) + "ms"); } function updateEvent(data, fight) { tbl_row = ''; //console.log(data); tbl_row += `<td class="center">${data.fightTime.toFixed(3)}s</td>`; tbl_row += `<td>${data.name}<span class="castType">${data.type}</span></td>`; //tbl_row += `<td>${data.name}<span class="castType">${data.type}</span></td>`; if(damageTypes[data.dmgType] == undefined){ console.log("Damage Type: " + data.dmgType + " is undefined"); console.log(data); } tbl_row += `<td>${data.amount == 0 ? '':data.amount} <span class="castType">${data.isDirect ? "Direct ":''}${data.hitType}</span><span class="damage-block ${damageTypes[data.dmgType]}"></span></td>`; if (data.sourceIsFriendly){ tbl_row += `<td class="name">${fight.team[data.sourceID]}<span class="castType">-></span></td>`; } else { tbl_row += `<td class="name">${fight.enemies[data.sourceID]}<span class="castType">-></span></td>`; } tbl_row += '<td class="name">'; if (!data.hasOwnProperty('targetID')) { tbl_row += 'self/ground'; } else { if (data.targetIsFriendly) tbl_row += fight.team[data.targetID]; else { if (data.hasOwnProperty("targetResources")) { tbl_row += `${fight.enemies[data.targetID]} <span class="castType">${((data.targetResources.hitPoints/data.targetResources.maxHitPoints)*100).toFixed(2)}%</span>`; } else { tbl_row += fight.enemies[data.targetID]; } } } tbl_row += '</td>' if(data.hasOwnProperty('potency')){ if(data.potency == 0) tbl_row += `<td></td>`; else tbl_row += `<td><div class="right"><span data-toggle="tooltip" title="${data.tooltip}">${data.potency}</span></div></td>`; } if (data.hasOwnProperty('extra')) { for (var i = 0; i < data.extra.length; i++) { tbl_row += `<td class="center">${data.extra[i]}</td>`; } } //console.log(tbl_row); return `<tr>${tbl_row}</tr>`; //$(".ranking-table tbody").append(`<tr>${tbl_row}</tr>`); } function processGeneric(response) { var totalDamage = 0; result = parseGeneric(response); var lastEvent = { name: '', timestamp: '', target: '', amount: '', type: '' }; var rows = []; for (var e in result.events) { var event = result.events[e]; if (isSameEvent(event, lastEvent)) continue; rows.push(updateEvent(event, result.fight)); //$(".ranking-table tbody").append(updateEvent(event, result.fight)); if (event.type != 'heal') { totalDamage += event.amount == undefined ? 0 : event.amount; } lastEvent = event; } document.getElementById('rank-body').innerHTML = rows.join('') //update summary $(".summary").append(`<b>Total Damage:</b> ${totalDamage.toFixed(3)}</br>`); $(".summary").append(`<b>DPS:</b> ${(totalDamage / result.fight.duration).toFixed(2)}</br>`); } function processClass(response, result) { //console.log("Processing " + spec); var spec = result.player.type; var t0 = performance.now(); //console.log(response); if(['Dragoon','Ninja','Monk'].indexOf(spec) > -1) $('.summary').append(`<br/><b>Positionals:</b> Unless under True North positional potency is a weighted average assuming 9 in 10 hits are from the correct position.`) else if(spec == "Bard") $('.summary').append(`<br/><b>Pitch Perfect:</b> As DoT crits are not able to be tracked accurately the base potency for Pitch Perfect is only a guess.`) else if(spec == "Paladin") $('.summary').append(`<br/>Potency values for Spirits Within or Requiescat don't scale with health or mana respectively.`) else if(spec == "Warrior") $('.summary').append(`<br/><b>Berserk:</b> Bonus for Berserk is a guess based on observation, actual increase would depend on your current AP.`) else if(spec == 'Scholar' || spec == 'Summoner') $('.summary').append(`<br/><b>Bane:</b> Damage reduction from bane is not handled at all :P`) if(response.hasOwnProperty("nextPageTimestamp")) console.log("WARNING more time stamps exist WARNING"); $(".ranking-table tbody").html(""); $(".ranking-table thead tr").append(`<td style="width: 90px">Potency</td>`); var buffDisplay = buff_display[spec]; for(var b in buffDisplay){ if(buffDisplay[b].hasOwnProperty('name')) $(".ranking-table thead tr").append(buffDisplay[b].asHeader()); } var t1 = performance.now(); console.log("header updates took " + (t1 - t0).toFixed(4) + "ms"); t0 = performance.now(); result = parseFunctions[spec](response, result); t1 = performance.now(); console.log("Parseing took " + (t1 - t0).toFixed(4) + "ms"); var totalPotency = 0; var totalDamage = 0; var lastEvent = { name: '', timestamp: '', target: '', amount: '', type: '' }; var s0 = performance.now() var rows = []; for (var e in result.events) { var event = result.events[e]; if (isSameEvent(event, lastEvent)) continue; rows.push(updateEvent(event, result.fight)); if (event.type != 'heal') { if(event.potency != ""){ totalPotency += event.potency == "" ? 0 : event.potency; totalDamage += event.amount == undefined ? 0 : event.amount; } } lastEvent = event; } document.getElementById('rank-body').insertAdjacentHTML('beforeend', rows.join('')); var s1 = performance.now(); console.log("building rows " + (s1 - s0).toFixed(4) + "ms"); t0 = performance.now(); //update summary var totalTime = 0; console.log(result); if (Object.keys(result.totals).length >= 1) { for (var k in result.totals) { var total = result.totals[k]; if(total.potency > 0){ $(".summary-table tbody").append(getSummaryRowMulti(total.name, total.amount, total.potency, total.time, totalDamage, totalPotency)); totalTime = Math.max(totalTime, total.time); } } if (Object.keys(result.totals).length > 1) $(".summary-table tbody").append(getSummaryRow("Combined", totalDamage, totalPotency, totalTime)); } else { console.log("displaying from summed"); $(".summary-table tbody").append(getSummaryRow(result.player.name, totalDamage, totalPotency, result.fight.duration)); } if(result.hasOwnProperty('role_actions')){ $('.summary').append(`<br/><b>Role Actions Used:</b> ${result['role_actions'].join(", ")}`); } t1 = performance.now(); console.log("updating summary took " + (t1-t0).toFixed(4) + "ms"); s0 = performance.now(); //performance hit to enable fancy tooltips :/ $('[data-toggle="tooltip"]').tooltip({html: true}) s1 = performance.now(); console.log("enabling tooltips " + (s1 - s0).toFixed(4) + "ms"); } function getSummaryRow(name, damage, potency, duration){ return `<tr> <td><div class="center">${name}</div></td> <td><div class="center">${damage}</div></td> <td><div class="center">${duration.toFixed(2)}</div></td> <td><div class="center">${(damage / duration).toFixed(2)}</div></td> <td><div class="center">${potency}</div></td> <td><div class="center">${(potency / duration).toFixed(2)}</div></td> <td><div class="center">1:${(damage/potency).toFixed(2)}</div></td> </tr>`; } function getSummaryRowMulti(name, damage, potency, duration, totalDamage, totalPotency){ return `<tr> <td><div class="center">${name}</div></td> <td><div class="center">${damage} <span class="castType">${((damage/totalDamage)*100).toFixed(1)}%</span></div></td> <td><div class="center">${duration.toFixed(2)}</div></td> <td><div class="center">${(damage / duration).toFixed(2)}</div></td> <td><div class="center">${potency} <span class="castType">${((potency/totalPotency)*100).toFixed(1)}%</span></div></td> <td><div class="center">${(potency / duration).toFixed(2)}</div></td> <td><div class="center">1:${(damage/potency).toFixed(2)}</div></td> </tr>`; } function isSameEvent(current, previous) { return ((current.name == previous.name) && (current.timestamp == previous.timestamp) && (current.target == previous.target) && (current.amount == previous.amount) && (current.type == previous.type)); } function getReportData() { var url = base_url + "/report/fights/" + getUrlParameter("report") + "?translate=true&api_key=" + api_key; //console.log(url); httpGetAsync(url, processReport); } getReportData();<file_sep>/js/data.js const egiAbilities = [ //Demi-Bahamut 'Wyrmwave', 'Akh Morn', //emerald 'Gust', 'Backdraft', 'Downburst', //topaz 'Gouge', 'Shining Topaz', 'Storm', //garuda 'Wind Blade', 'Shockwave', 'Aerial Slash', 'Aerial Blast', //titan 'Rock Buster', 'Mountain Buster', 'Landslide', 'Earthen Fury', //ifrit 'Crimson Cyclone', 'Burning Strike', 'Radiant Shield', 'Flaming Crush', 'Inferno', 'Radiant Shield', ]; const all_potencies = { 'Bard': { 'Shot': 100, 'Heavy Shot': 150, 'Straight Shot': 140, 'Empyreal Arrow': 230, 'Iron Jaws': 100, 'Refulgent Arrow': 300, 'Quick Nock': 110, 'Rain Of Death': 100, 'Sidewinder': 100, "Misery's End": 190, 'Bloodletter': 130, "Mage's Ballad": 100, "Army's Paeon": 100, "The Wanderer's Minuet": 100, 'Caustic Bite': 120, 'Stormbite': 120, 'Pitch Perfect': 100, }, 'BlackMage': { 'Attack': 110, 'Fire': 180, 'Fire II': 80, 'Fire III': 240, 'Fire IV': 260, 'Flare': 260, 'Blizzard': 180, 'Blizzard II': 50, 'Blizzard III': 240, 'Blizzard IV': 260, 'Freeze': 100, 'Thunder I': 30, 'Thunder II': 30, 'Thunder III': 70, 'Thunder IV': 50, 'Scathe': 100, 'Foul': 650, }, 'Dragoon': { 'Attack': 110, 'True Thrust': 150, 'Vorpal Thrust': 100, 'Impulse Drive': 190, 'Heavy Thrust': (180 * 9 + 140) / 10, 'Piercing Talon': 120, 'Full Thrust': 100, 'Jump': 250, 'Disembowel': 100, 'Doom Spike': 130, 'Spineshatter Dive': 200, 'Chaos Thrust': (140 * 9 + 100) / 10, 'Dragonfire Dive': 300, 'Fang And Claw': (290 * 9 + 250) / 10, 'Wheeling Thrust': (290 * 9 + 250) / 10, 'Geirskogul': 220, 'Sonic Thrust': 100, 'Mirage Dive': 200, 'Nastrond': 320 }, 'Machinist': { 'Shot': 100, 'Hot Shot': 120, 'Split Shot': 160, 'Slug Shot': 100, 'Heartbreak': 240, 'Spread Shot': 80, 'Clean Shot': 100, 'Gauss Round': 200, 'Ricochet': 300, 'Cooldown': 150, 'Flamethrower': 60, 'Heated Split Shot': 190, 'Heated Slug Shot': 100, 'Heated Clean Shot': 100, 'Wildfire': 0, //Rook 'Charged Volley Fire': 160, 'Volley Fire': 80, 'Rook Overload': 800, //Bishop 'Aether Mortar': 60, 'Charged Aether Mortar': 90, 'Bishop Overload': 600, }, 'Monk': { 'Attack': 110, 'Bootshine': 140, 'True Strike': (140 + (180 * 9)) / 10, //weighted average 90% hitting positional 'Demolish': (30 + (70 * 9)) / 10, 'Dragon Kick': (100 + (140 * 9)) / 10, 'Twin Snakes': (100 + (130 * 9)) / 10, 'Snap Punch': (130 + (170 * 9)) / 10, 'Arm of the Destroyer': 50, 'One Ilm Punch': 120, 'Rockbreaker': 130, 'The Forbidden Chakra': 250, 'Elixir Field': 220, 'Steel Peak': 150, 'Shoulder Tackle': 100, 'Howling Fist': 210, 'Tornado Kick': 330, 'Riddle of Wind': 65, 'Earth Tackle': 100, 'Wind Tackle': 65, 'Fire Tackle': 130, }, 'Ninja': { 'Attack': 110, 'Spinning Edge': 150, 'Gust Slash': 100, 'Assassinate': 200, 'Throwing Dagger': 120, 'Mug': 140, 'Trick Attack': 400, //scan ahead for the vuln up state? 'Aeolian Edge': (160 * 9 + 100) / 10, 'Jugulate': 80, 'Shadow Fang': 100, 'Death Blossom': 110, 'Armor Crush': (160 * 9 + 100) / 10, 'Dream Within A Dream': 150, 'Hellfrog Medium': 400, 'Bhavacakra': 600, 'Fuma Shuriken': 240, 'Katon': 250, 'Raiton': 360, 'Hyoton': 140, 'Doton': 40, 'Suiton': 180 }, 'RedMage':{ 'Attack': 110, 'Riposte': 130, 'Zwerchhau': 100, 'Redoublement': 100, 'Jolt': 180, 'Impact': 270, 'Verthunder': 300, 'Verfire': 270, 'Verflare': 550, 'Veraero': 300, 'Verstone': 270, 'Verholy': 550, 'Scatter': 100, 'Moulinet': 60, 'Corps-a-corps': 130, 'Displacement': 130, 'Fleche': 420, 'Contre Sixte': 300, 'Jolt II': 240, 'Enchanted Riposte': 210, 'Enchanted Zwerchhau': 100, 'Enchanted Redoublement': 100, 'Enchanted Moulinet': 60, }, 'Samurai': { 'Attack': 110, 'Hakaze': 150, 'Jinpu': 100, 'Gekko': 100, 'Yukikaze': 100, 'Shifu': 100, 'Kasha': 100, 'Fuga': 100, 'Mangetsu': 100, 'Oka': 100, 'Ageha': 200, 'Enpi': 100, 'Higanbana': 240, '<NAME>': 720, '<NAME>': 360, 'Hissatsu: Gyoten': 100, 'Hissatsu: Yaten': 100, 'Hissatsu: Shinten': 300, 'Hissatsu: Kyuten': 150, 'Hissatsu: Seigan': 200, 'Hissatsu: Guren': 800, }, 'Summoner': { 'Attack': 110, 'Ruin': 100, 'Ruin II': 100, 'Ruin III': 150, 'Ruin IV': 200, 'Energy Drain': 150, 'Painflare': 200, 'Deathflare': 400, 'Miasma': 20, 'Miasma III': 50, 'Fester': 0, 'Tri-bind': 20, 'Shadow Flare': 0, 'Bio': 0, 'Bio II': 0, 'Bio III': 0, //special case 'Radiant Shield': 50, //'Summoner-Egi': 'Attack': 80, //Bahamut 'Wyrmwave': 160, 'Akh Morn': 680, //emerald 'Gust': 90, 'Backdraft': 80, 'Downburst': 80, //topaz 'Gouge': 70, 'Shining Topaz': 60, 'Storm': 60, //garuda 'Wind Blade': 110, 'Shockwave': 90, 'Aerial Slash': 90, 'Aerial Blast': 250, //titan 'Rock Buster': 85, 'Mountain Buster': 70, 'Landslide': 70, 'Earthen Fury': 200, //ifrit 'Crimson Cyclone': 110, 'Burning Strike': 135, 'Radiant Shield': 50, 'Flaming Crush': 110, 'Inferno': 200, }, 'DarkKnight': { 'Attack': 110, 'Hard Slash': 150, 'Spinning Slash': 100, 'Unleash': 50, 'Syphon Strike': 100, 'Unmend': 150, 'Power Slash': 100, 'Souleater': 100, 'Dark Passenger': 100, 'Salted Earth': 75, 'Plunge': 200, 'Abyssal Drain': 120, 'Carve And Spit': 100, 'Quietus': 160, 'Bloodspiller': 400, }, 'Paladin': { 'Attack': 110, 'Fast Blade': 160, 'Savage Blade': 100, 'Riot Blade': 100, 'Shield Lob': 120, 'Shield Bash': 110, 'Shield Swipe': 150, 'Spirits Within': 300, 'Total Eclipse': 110, 'Circle Of Scorn': 100, 'Goring Blade': 100, 'Royal Authority': 100, 'Sword Oath': 75, 'Holy Spirit': 400, 'Requiescat': 350, }, 'Warrior': { 'Attack': 110, 'Heavy Swing': 150, 'Skull Sunder': 100, 'Overpower': 120, 'Tomahawk': 130, 'Maim': 100, "Butcher's Block": 100, "Storm's Path": 100, 'Steel Cyclone': 200, "Storm's Eye": 100, 'Fell Cleave': 500, 'Decimate': 280, 'Onslaught': 100, 'Upheaval': 300, 'Inner Beast': 350, }, //Healers 'Astrologian': { 'Attack': 110, 'Malefic': 150, 'Malefic II': 180, 'Malefic III': 220, 'Stellar Burst': 150, 'Stellar Explosion': 200, 'Lord Of Crowns': 300, 'Gravity': 200, }, 'WhiteMage': { 'Attack': 110, 'Stone': 140, 'Stone II': 200, 'Stone III': 210, 'Stone IV': 250, 'Aero': 50, 'Aero II': 50, 'Aero III': 50, 'Assize': 300, 'Holy': 200, }, 'Scholar': { 'Attack': 110, 'Ruin': 100, 'Ruin II': 100, 'Energy Drain': 150, 'Miasma': 20, 'Miasma II': 100, 'Broil': 190, 'Broil II': 230, } } const all_dot_base = { 'Bard': { 'Storm Bite': 55, 'Caustic Bite': 45, }, 'BlackMage': { 'Thunder IV': 30, 'Thunder III': 40, }, 'Dragoon': { 'Chaos Thrust': 35, }, 'Machinist': { 'Flamethrower': 60, 'Wildfire': 0, }, 'Monk': { 'Demolish': 50, }, 'Ninja': { 'Shadow Fang': 35, 'Doton': 40, }, 'Samurai': { 'Higanbana': 35, }, 'RedMage': {}, 'Summoner': { 'Shadow Flare': 50, 'Bio': 40, 'Bio II': 35, 'Bio III': 50, 'Miasma': 35, 'Miasma III': 50, 'Inferno': 20, 'Radiant Shield': 50, }, 'DarkKnight': { 'Salted Earth': 75, }, 'Paladin': { 'Circle Of Scorn': 30, 'Goring Blade': 60, }, 'Warrior': { 'Vengeance': 50, }, 'Astrologian': { 'Combust': 40, 'Combust II': 50, }, 'WhiteMage': { 'Aero': 30, 'Aero II': 50, 'Aero III': 40, }, 'Scholar': { 'Bio': 40, 'Bio II': 35, 'Miasma': 35, 'Miasma II': 25, 'Shadow Flare': 50, } } const all_pos_potencies = { 'Bard': {}, 'BlackMage': {}, 'Dragoon': { 'Heavy Thrust': 180, 'Chaos Thrust': 140, 'Fang And Claw': 290, 'Wheeling Thrust': 290, }, 'Machinist': {}, 'Monk': { 'True Strike': 180, 'Demolish': 70, 'Dragon Kick': 140, 'Twin Snakes': 130, 'Snap Punch': 170 }, 'Ninja': { 'Aeolian Edge': 160, 'Armor Crush': 160, }, 'RedMage': {}, 'Samurai': {}, 'Summoner': {}, //tank 'DarkKnight': { 'Syphon Strike': 240, 'Souleater': 240, 'Dark Passenger': 240, 'Carve And Spit': 450, 'Quietus': 210, 'Bloodspiller': 540, }, 'Paladin': {}, 'Warrior': {}, //heals 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } const all_combo_potencies = { 'Bard': {}, 'BlackMage': {}, 'Dragoon': { 'Vorpal Thrust': 240, 'Full Thrust': 440, 'Disembowel': 230, 'Chaos Thrust': (270 * 9 + 230) / 10, 'Sonic Thrust': 170, 'Fang And Claw': 100 + ((290 * 9 + 250) / 10), 'Wheeling Thrust': 100 + ((290 * 9 + 250) / 10), }, 'Machinist': { 'Slug Shot': 200, 'Clean Shot': 240, 'Cooldown': 230, 'Heated Slug Shot': 230, 'Heated Clean Shot': 270, }, 'Ninja': { 'Gust Slash': 200, 'Aeolian Edge': (340 * 9 + 280) / 10, 'Shadow Fang': 200, 'Armor Crush': (300 * 9 + 240) / 10, }, 'RedMage': { 'Zwerchhau': 150, 'Redoublement': 230, 'Enchanted Zwerchhau': 290, 'Enchanted Redoublement': 470, }, 'Samurai': { 'Jinpu': 280, 'Gekko': 400, 'Yukikaze': 340, 'Shifu': 280, 'Kasha': 400, 'Mangetsu': 200, 'Oka': 200, }, 'Summoner': {}, 'DarkKnight': { 'Spinning Slash': 220, 'Syphon Strike': 250, 'Power Slash': 300, 'Souleater': 300, }, 'Paladin': { 'Goring Blade': 250, 'Royal Authority': 360, 'Savage Blade': 210, 'Riot Blade': 240, 'Rage Of Halone': 270, }, 'Warrior': { 'Skull Sunder': 200, 'Maim': 190, "Butcher's Block": 280, "Storm's Path": 270, "Storm's Eye": 270, }, //heals 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } const all_pos_combo_potencies = { 'Bard': {}, 'BlackMage': {}, 'Dragoon': { 'Chaos Thrust': 270, 'Fang And Claw': 100 + 290, 'Wheeling Thrust': 100 + 290, }, 'Machinist': {}, 'Monk': {}, 'Ninja': { 'Aeolian Edge': 340, 'Armor Crush': 300, }, 'RedMage': {}, 'Samurai': {}, 'Summoner': {}, 'DarkKnight': { 'Syphon Strike': 390, 'Souleater': 440, }, 'Paladin': {}, 'Warrior': {}, //heals 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } const all_combo = { 'Bard': {}, 'Dragoon': { 'Vorpal Thrust': ['True Thrust'], 'Full Thrust': ['Vorpal Thrust'], 'Disembowel': ['Impulse Drive'], 'Chaos Thrust': ['Disembowel'], 'Sonic Thrust': ['Doom Spike'], 'Wheeling Thrust': ['Fang And Claw'], 'Fang And Claw': ['Wheeling Thrust'], }, 'Machinist': {}, 'Monk': {}, 'Ninja': { 'Gust Slash': ['Spinning Edge'], 'Aeolian Edge': ['Gust Slash'], 'Shadow Fang': ['Gust Slash'], 'Armor Crush': ['Gust Slash'], }, 'RedMage': { 'Zwerchhau': ['Riposte', 'Enchanted Riposte'], 'Redoublement': ['Zwerchhau', 'Enchanted Zwerchhau'], 'Enchanted Zwerchhau': ['Riposte', 'Enchanted Riposte'], 'Enchanted Redoublement': ['Zwerchhau', 'Enchanted Zwerchhau'], }, 'Samurai': { 'Jinpu': ['Hakaze'], 'Gekko': ['Jinpu'], 'Shifu': ['Hakaze'], 'Kasha': ['Shifu'], 'Yukikaze': ['Hakaze'], 'Mangetsu': ['Fuga'], 'Oka': ['Fuga'], }, 'DarkKnight':{ 'Spinning Slash': ['Hard Slash'], 'Syphon Strike': ['Hard Slash'], 'Power Slash': ['Spinning Slash'], 'Souleater': ['Syphon Strike'], }, 'Paladin': { 'Riot Blade': ['Fast Blade'], 'Savage Blade': ['Fast Blade'], 'Royal Authority': ['Riot Blade'], 'Goring Blade': ['Riot Blade'], 'Rage Of Halone': ['Savage Blade'], }, 'Warrior': { 'Skull Sunder': ['Heavy Swing'], 'Maim': ['Heavy Swing'], "Butcher's Block": ['Skull Sunder'], "Storm's Path": ['Maim'], "Storm's Eye": ['Maim'], }, //heals 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } //anything that makes/breaks a combo const all_comboskills = { 'Bard': [], 'Dragoon': ['True Thrust', 'Vorpal Thrust', 'Impulse Drive', 'Heavy Thrust', 'Full Thrust', 'Disembowel', 'Chaos Thrust', 'Fang And Claw', 'Wheeling Thrust', 'Doom Spike', 'Sonic Thrust', 'Piercing Talon'], 'Machinist': [], 'Monk': [], 'Ninja': ['Gust Slash', 'Spinning Edge', 'Aeolian Edge', 'Shadow Fang', 'Throwing Dagger', 'Death Blossom'], 'RedMage': ['Moulinet', 'Enchanted Moulinet', 'Zwerchhau', 'Riposte', 'Enchanted Riposte', 'Redoublement', 'Enchanted Zwerchhau', 'Enchanted Redoublement'], 'Samurai': ['Hakaze', 'Jinpu', 'Gekko', 'Shifu', 'Kasha', 'Yukikaze', 'Mangetsu', 'Fuga', 'Oka', 'Enpi'], 'DarkKnight': ['Hard Slash', 'Spinning Slash', 'Unleash', 'Syphon Strike', 'Unmend', 'Power Slash', 'Souleater', 'Abyssal Drain', 'Quietus'/*, 'Bloodspiller'*/], 'Paladin': ['Fast Blade', 'Savage Blade', 'Riot Blade', 'Rage Of Halone', 'Goring Blade', 'Royal Authority', 'Holy Spirit', 'Shield Lob', 'Shield Bash', 'Total Eclipse', 'Clemency'], 'Warrior': ['Heavy Swing', 'Skull Sunder', 'Maim', "Butcher's Block", "Storm's Eye", "Storm's Path", 'Overpower', 'Tomahawk'], //heals 'Astrologian': [], 'WhiteMage': [], 'Scholar': [], } //all 'WeaponSkills' const all_weaponskills = { 'Bard': ["Heavy Shot","Straight Shot","Empyreal Arrow","Iron Jaws","Refulgent Arrow","Quick Nock","Caustic Bite","Stormbite"], 'Dragoon': ['True Thrust', 'Vorpal Thrust', 'Impulse Drive', 'Heavy Thrust', 'Full Thrust', 'Disembowel', 'Chaos Thrust', 'Fang And Claw', 'Wheeling Thrust', 'Doom Spike', 'Sonic Thrust', 'Piercing Talon'], 'Machinist': ['Hot Shot', 'Split Shot', 'Slug Shot', 'Spread Shot', 'Clean Shot', 'Cooldown', 'Heated Split Shot', 'Heated Slug Shot', 'Heated Clean Shot'], 'RedMage': ['Moulinet', 'Zwerchhau', 'Riposte', 'Redoublement', 'Enchanted Moulinet', 'Enchanted Riposte', 'Enchanted Zwerchhau', 'Enchanted Redoublement'], 'Samurai': ['Hakaze', 'Jinpu', 'Gekko', 'Shifu', 'Kasha', 'Yukikaze', 'Mangetsu', 'Fuga', 'Oka', 'Enpi', 'Higanbana', '<NAME>', '<NAME>'], 'DarkKnight': ['Hard Slash', 'Spinning Slash', 'Syphon Strike', 'Power Slash', 'Souleater', 'Quietus', 'Bloodspiller'], 'Paladin': ['Fast Blade', 'Savage Blade', 'Riot Blade', 'Rage Of Halone', 'Goring Blade', 'Royal Authority', 'Shield Lob', 'Shield Bash', 'Total Eclipse'], 'Warrior': ['Heavy Swing', 'Skull Sunder', 'Maim', "Butcher's Block", "Storm's Eye", "Storm's Path", 'Overpower', 'Tomahawk','Inner Beast', 'Steel Cyclone', 'Fell Cleave', 'Decimate'], //heals 'Astrologian': [], 'WhiteMage': [], 'Scholar': [], } //buffs const all_buffs = { 'Bard': { 'Increased Action Damage II': new Buff('Trait II', .20, true, ['Shot']), 'Raging Strikes': new Buff('Raging Strikes', .10), 'Straight Shot': new Buff('Straight Shot', (.10 * .45)), 'Foe Requiem': new Debuff('Foe Requiem', .03), "Army's Paeon": new Buff("Army's Paeon", 0), "Mage's Ballad": new Buff("Mage's Ballad", 0), "The Wanderer's Minuet": new Buff("The Wanderer's Minuet", 0), 'Storm Bite': new Debuff('Storm Bite', 0), 'Caustic Bite': new Debuff('Caustic Bite', 0), }, 'BlackMage':{ 'Thundercloud': new BuffThunder('Thundercloud', 1), 'Trait': new Buff('Magic & Mend II', .3, true, ['Attack']), 'Enochian': new Buff('Enochian', .1, false, ['Attack']), 'Thunder III': new Debuff('Thunder III', 0), 'Thunder IV': new Debuff('Thunder IV', 0), 'Astral Fire': new BuffStackFire('Astral Fire', .2, .2, 3, 1, false, [], ['Fire', 'Fire II', 'Fire III', 'Fire IV', 'Flare', 'Blizzard', 'Blizzard II', 'Blizzard III', 'Blizzard IV', 'Freeze']), 'Umbral Ice': new BuffStack('Umbral Ice', 0, -.1, 3, 1, false, [], ['Fire', 'Fire II', 'Fire III', 'Fire IV', 'Flare']), 'Sharpcast': new Buff('Sharpcast', 0), 'Triplecast': new Buff('Triplecast', 0), 'Swiftcast': new Buff('Swiftcast', 0), 'Circle Of Power': new Buff('Ley Lines', 0), }, 'Dragoon': { 'Blood Of The Dragon': new Buff('Blood Of The Dragon', .30, false, [], ['Jump', 'Spineshatter Dive']), 'Heavy Thrust': new Buff('Heavy Thrust', .15), 'Blood For Blood': new Buff('Blood For Blood', .15), 'Right Eye': new BuffStack('Right Eye', .10, 0, 1, 1), 'Battle Litany': new Buff('Battle Litany', (.15 * .45)), 'True North': new Buff('True North', 0), //'Piercing Resistance Down': new Debuff('Disemboweled', .05), 'Piercing Resistance Down': new DebuffTimed('Disembowel', .05, 30), }, 'Machinist': { 'Ammunition': new BuffDirectConsumedStack('Ammunition', 25, 0, 3, 3, false, [], all_weaponskills['Machinist']), 'Trait': new Buff('Action Damage II', .20, true, ['Shot']), 'Hot Shot': new Buff('Hot Shot', .08, false, ['Charged Volley Fire', 'Volley Fire', 'Aether Mortar', 'Charged Aether Mortar', 'Rook Overload', 'Bishop Overload']), 'Heat': new BuffStack('Heat', 0, 0, 100, 0), 'Overheated': new Buff('Overheated', .20, false, ['Charged Volley Fire', 'Volley Fire', 'Aether Mortar', 'Charged Aether Mortar', 'Rook Overload', 'Bishop Overload']), 'Vulnerability Up': new DebuffTimed('Hypercharge', .05, 10), 'Reassembled': new Buff('Reassembled', .45, false, [], all_weaponskills['Machinist']), 'Gauss Barrel': new Buff('Gauss Barrel', 0, true), 'Cleaner Shot': new Buff('Cleaner Shot', 0, false), 'Enhanced Slug Shot': new Buff('Enhanced Slug Shot', 0, false) }, 'Monk': { 'Greased Lightning': new BuffStack('Greased Lightning', 0, .1, 3, 1), 'Riddle Of Fire': new BuffStack('Riddle of Fire', .30, 0, 1, 1), 'Fists Of Fire': new Buff('Fists of Fire', .05, true), 'Internal Release': new Buff('Internal Release', .3 * .45, false, ['Bootshine']), 'True North': new Buff('True North', 0), 'Perfect Balance': new Buff('Perfect Balance', 0), 'Twin Snakes': new Buff('Twin Snakes', .10), 'Blunt Resistance Down': new DebuffTimed('Dragon Kick', .10, 15), }, 'Ninja': { 'Dripping Blades': new Buff('Dripping Blades II', .2, true, ['Attack']), 'True North': new Buff('True North', 0), 'Ten Chi Jin': new BuffStack('Ten Chi Jin', 1.0, 0,1, 1, false, [], ['<NAME>', 'Katon', 'Raiton', 'Hyoton', 'Doton', 'Suiton']), 'Shadow Fang': new Debuff('Shadow Fang', .10, ['Katon', 'Hellfrog Medium', 'Suiton', 'Raiton', 'Bhavacakra']), 'Vulnerability Up': new DebuffTimed('Trick Attack', .10, 10), 'Duality': new Buff('Duality',0), 'Huton': new Buff('Huton',0), }, 'RedMage': { 'Main & Mend II': new Buff('Trait', .30, true, ['Attack'], []), 'Embolden': new BuffStack('Embolden', 0, .02, 5, 5, false, ['Attack', 'Fleche', 'Contre Sixte', 'Corps-a-corps', 'Displacement', 'Moulinet', 'Zwerchhau', 'Riposte', 'Redoublement'], []), 'Acceleration': new Buff('Acceleration', 0), 'Swiftcast': new Buff('Swiftcast', 0), }, 'Samurai': { 'Enhanced Enpi': new BuffDirect('Enhanced Enpi', 200, false, [], ['Enpi']), 'Meikyo Shisui': new Buff('Meikyo Shisui', 0), 'True North': new Buff('True North', 0), 'Jinpu': new Buff('Jinpu', .10), 'Kaiten': new Buff('Hissatsu: Kaiten', .50, false, [], ['Hakaze', 'Jinpu', 'Gekko', 'Shifu', 'Kasha', 'Yukikaze', 'Mangetsu', 'Fuga', 'Oka', 'Enpi', 'Higanbana', '<NAME>', '<NAME>']), 'Slashing Resistance Down': new DebuffTimed('Yukikaze', .10, 30), }, 'Summoner': { 'Bio III': new DebuffDirect('Bio III', 150, [], ['Fester']), 'Miasma III': new DebuffDirect('Miasma III', 150, [], ['Fester']), 'Ruination': new DebuffDirect('Ruination', 20, [], ['Ruin', 'Ruin II', 'Ruin III', 'Ruin IV']), 'Magic & Mend': new Buff('Trait', .30, true, ['Radiant Shield']), 'Dreadwyrm Trance': new Buff('Dreadwyrm Trance', .10, false, egiAbilities.concat(['Attack', 'Radiant Shield'])), 'Rouse': new Buff('Rouse', .40, false, [], egiAbilities.concat(['Attack'])), 'Magic Vulnerability Up': new Debuff('Contagion', .10, ['Attack', 'Radiant Shield']), 'Physical Vulnerability Up': new Debuff('Radiant Shield', .02, [], ['Attack', 'Radiant Shield']), 'Swiftcast': new Buff('Swiftcast', 0), }, 'DarkKnight': { 'Dark Arts': new Buff('Dark Arts', 0), 'Grit': new Buff('Grit', -.20), 'Blood Weapon': new BuffStack('Blood Weapon', 0, 0, 1, 1), 'Darkside': new BuffStack('Darkside', .20, 0, 1, 1), }, 'Paladin': { 'Sword Oath': new BuffStack('Sword Oath', 0, 0, 100, 100), 'Shield Oath': new BuffStack('Shield Oath', -.20, 0, 100, 100), 'Requiescat': new Buff('Requiscat', .2, false, [], ['Holy Spirit', 'Clemency']), 'Fight Or Flight': new Buff('Fight or Flight', .25, false, ['Holy Spirit', 'Clemency']), 'Goring Blade': new Debuff('Goring Blade', 0), }, 'Warrior': { 'Defiance': new Buff('Defiance', -.20, false, ['Inner Beast', 'Steel Cyclone', 'Upheaval']), 'Unchained': new Buff('Unchained', .25, false, ['Inner Beast', 'Steel Cyclone']), 'Thrill Of Battle': new Buff('Thrill of Battle', 0), 'Berserk': new Buff('Berserk', .45), "Storm's Eye": new Buff("Storm's Eye", .20), 'Inner Release': new BuffStack('Inner Release', 0), 'Slashing Resistance Down': new DebuffTimed('Maim', .10, 24), 'Deliverance': new Buff('Deliverance', .05), }, //Healers 'Astrologian': { 'Trait': new Buff('Magic & Mend II', .3, true, ['Attack']), 'The Balance': new Buff('The Balance', .1), 'The Arrow': new Buff('The Arrow', 0), 'The Spear': new Buff('The Spear', (.10 * .45)), 'Cleric Stance': new Buff('Cleric Stance', .05, false, ['Attack']), 'Lightspeed': new BuffStack('Lightspeed', -.25, 0, 1, 1, false, [], ['Malefic', 'Malefic II', 'Malefic III', 'Combust', 'Combust II', 'Lord Of Crowns']), }, 'WhiteMage': { 'Trait': new Buff('Magic & Mend II', .3, true, ['Attack']), 'Cleric Stance': new Buff('Cleric Stance', .05, false, ['Attack']), }, 'Scholar': { 'Trait': new Buff('Magic & Mend II', .3, true, ['Attack']), 'Cleric Stance': new Buff('Cleric Stance', .05, false, ['Attack']), }, } const buff_display = { 'BlackMage': { 'Enochian': new BuffDisplay('Enochian', '#548785'), 'Circle Of Power': new BuffDisplay('Circle Of Power', '#A05FF0', 'ley_lines.png'), 'Sharpcast': new BuffDisplay('Sharpcast', '#A05F7F'), 'Triplecast': new BuffDisplay('Triplecast', '#984C85'), 'Swiftcast': new BuffDisplay('Swiftcast', '#E090C0'), 'Thundercloud': new BuffDisplay('Thundercloud', '#C0B0F0'), 'Thunder': new BuffDisplay('Thunder', '', 'thunder_iii.png'), 'State': new BuffDisplay('Song of Ice and Fire','', 'astral_umbral.png'), }, 'Bard':{ 'Straight Shot': new BuffDisplay('Straight Shot','#B01F00'), 'Foe Requiem': new BuffDisplay('Foe Requiem','#90D0D0'), 'Raging Strikes': new BuffDisplay('Raging Strikes','#D03F00'), 'Storm Bite': new BuffDisplay('Storm Bite','#9DBBD2'), 'Caustic Bite': new BuffDisplay('Caustic Bite','#D75896'), 'Bard Song': new BuffDisplay('Bard Song','', ), }, 'Dragoon': { 'Blood Of The Dragon': new BuffDisplay('Blood Of The Dragon', '#7DA3AD'), 'Heavy Thrust': new BuffDisplay('Heavy Thrust', '#CDA34C'), 'Blood For Blood': new BuffDisplay('Blood For Blood', '#901F1D'), 'Right Eye': new BuffDisplay('Right Eye', '#B41512'), 'Battle Litany': new BuffDisplay('Battle Litany', '#6F8C93'), 'Piercing Resistance Down': new BuffDisplay('Piercing Resistance Down', '#932F2F'), 'True North': new BuffDisplay('True North', '#C07F4F'), }, 'Machinist': { 'Gauss Barrel': new BuffDisplay('Gauss Barrel', '#A4786F'), 'Hot Shot': new BuffDisplay('Hot Shot', '#6D2600'), 'Vulnerability Up': new BuffDisplay('Vulnerability Up', '#932F2F', 'hypercharge.png'), 'Ammunition': new BuffDisplayCount('Ammunition', 'ammunition_loaded.png'), 'Heat': new BuffDisplayGradient('Heat', 'overheated.png'), }, 'Monk': { 'Greased Lightning': new BuffDisplay('Greased Lightning', '#4099CE'), 'Twin Snakes': new BuffDisplay('Twin Snakes', '#B7727D'), 'Blunt Resistance Down': new BuffDisplay('Blunt Resistance Down', '#932F2F', 'dragon_kick.png'), 'Internal Release': new BuffDisplay('Internal Release', '#8DD7AF'), 'Riddle Of Fire': new BuffDisplay('Riddle Of Fire', '#D8786F'), 'Perfect Balance': new BuffDisplay('Perfect Balance', '#DF964C'), 'True North': new BuffDisplay('True North', '#C07F4F'), }, 'Ninja': { 'Vulnerability Up': new BuffDisplay('Vulnerability Up', '#933630'), 'Shadow Fang': new BuffDisplay('Shadow Fang','#44B3DA'), 'Ten Chi Jin': new BuffDisplay('Ten Chi Jin','#BA4B4A'), 'True North': new BuffDisplay('True North', '#C07F4F'), 'Huton': new BuffDisplay('Huton','#7DB6C3'), }, 'RedMage': { 'Embolden': new BuffDisplay('Embolden', '#C19143'), 'Acceleration': new BuffDisplay('Acceleration', '#AF2234'), 'Swiftcast': new BuffDisplay('Swiftcast', '#E090C0'), }, 'Samurai': { 'Me<NAME>ui': new BuffDisplay('Meikyo Shisui','#E04F4F'), 'Jinpu': new BuffDisplay('Jinpu','#E0B000'), 'Slashing Resistance Down': new BuffDisplay('Slashing Resistance Down','#932F2F'), 'Kaiten': new BuffDisplay('Kaiten','#C04F0F','hissatsu_kaiten.png'), 'True North': new BuffDisplay('True North','#C07F4F'), }, 'Summoner': { 'Dreadwyrm Trance': new BuffDisplay('Dreadwyrm Trance','#C1294D'), 'Ruination': new BuffDisplay('Ruination','#4BA1EC'), 'Bio III': new BuffDisplay('Bio III','#56631E'), 'Miasma III': new BuffDisplay('Miasma III','#4B494F'), 'Rouse': new BuffDisplay('Rouse','#5796C4'), 'Magic Vulnerability Up': new BuffDisplay('Magic Vulnerability Up','#932F2F'), 'Physical Vulnerability Up': new BuffDisplay('Physical Vulnerability Up','#932F2F'), }, 'DarkKnight': { 'Darkside': new BuffDisplay('Darkside', "#943631"), 'Dark Arts': new BuffDisplay('Dark Arts', "#AB84C6"), 'Blood Weapon': new BuffDisplay('Blood Weapon', "#631118"), 'Grit': new BuffDisplay('Grit', '#92B8C9'), }, 'Paladin': { 'Fight Or Flight': new BuffDisplay('Fight Or Flight', '#C04B32'), 'Requiescat': new BuffDisplay('Requiescat', '#3A69CB'), 'Goring Blade': new BuffDisplay('Goring Blade', '#A45B20'), 'Oath': new BuffDisplay('Active Oath', '', 'shield_sword.png'), }, 'Warrior': { 'Berserk': new BuffDisplay('Berserk', '#BD633C'), "Storm's Eye": new BuffDisplay("Storm's Eye",'#DB9489'), 'Slashing Resistance Down': new BuffDisplay('Slashing Resistance Down','#932F2F'), //'Thrill Of Battle': new BuffDisplay('Thrill of Battle', '#fff'), //'Unchained': new BuffDisplay('Unchained', '#CE7CD1'), //'Inner Release': new BuffDisplay('Inner Release', '#9B553E'), 'Unchained Release': new BuffDisplay('Unchained Release', '', 'unchained_release.png'), 'Defiverance': new BuffDisplay('Stance', '', 'warrior_stance.png'), }, //Healers 'Astrologian': { //'Trait': new Buff('Magic & Mend II', .3, true, ['Attack']), 'The Balance': new BuffDisplay('The Balance', '#E08C51'), 'The Arrow': new BuffDisplay('The Arrow', '#4A7CAF'), 'The Spear': new BuffDisplay('The Spear', '#4152AF'), 'Lightspeed': new BuffDisplay('Lightspeed', '#AD9B5C'), 'Cleric Stance': new BuffDisplay('Cleric Stance', '#B24437'), }, 'WhiteMage': { 'Cleric Stance': new BuffDisplay('Cleric Stance', '#B24437'), }, 'Scholar': { 'Cleric Stance': new BuffDisplay('Cleric Stance', '#B24437'), }, } const all_timers = { 'Bard': { "Army's Paeon": new Timer("Army's Paeon", 30), "Mage's Ballad": new Timer("Mage's Ballad", 30), "The Wanderer's Minuet": new Timer("The Wanderer's Minuet", 30), }, 'BlackMage': { 'Enochian': new Timer('Enochian', 30), 'Astral Fire': new Timer('Astral Fire', 13), 'Umbral Ice': new Timer('Umbral Ice', 13), }, 'Dragoon': { "Blood Of The Dragon": new Timer("Blood of the Dragon", 20), }, 'Machinist': { 'Overheated': new Timer("Overheated", 10) }, 'Monk': {}, 'Ninja': { 'Huton': new Timer('Huton', 70), }, 'RedMage': {}, 'Samurai': {}, 'Summoner': { 'Summon Bahamut': new Timer('Summon Bahamut', 20), }, 'DarkKnight': {}, 'Paladin': {}, 'Warrior': {}, 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } const roleActions = { 'caster': ["Addle","Break","Drain","Diversion","Lucid Dreaming","Swiftcast","Mana Shift","Apocatastasis","Surecast","Erase"], 'healer': ["Cleric Stance","Break","Protect","Esuna","Lucid Dreaming","Swiftcast","Eye for an Eye","Largesse","Surecast","Rescue"], 'tank': ["Rampart","Low Blow","Provoke","Convalescence","Anticipation","Reprisal","Awareness","Interject","Ultimatum","Shirk"], 'melee': ["Second Wind","Arm's Length","Leg Sweep","Diversion","Invigorate","Bloodbath","Goad","Feint","Crutch","True North"], 'ranged': ["Second Wind","Foot Graze","Leg Graze","Peloton","Invigorate","Tactician","Refresh","Head Graze","Arm Graze","Palisade"] }; const role_actions = { 'Bard': ["Second Wind","Foot Graze","Leg Graze","Peloton","Invigorate","Tactician","Refresh","Head Graze","Arm Graze","Palisade"], 'Machinist': ["Second Wind","Foot Graze","Leg Graze","Peloton","Invigorate","Tactician","Refresh","Head Graze","Arm Graze","Palisade"], 'Dragoon': ["Second Wind","Arm's Length","Leg Sweep","Diversion","Invigorate","Bloodbath","Goad","Feint","Crutch","True North"], 'Monk': ["Second Wind","Arm's Length","Leg Sweep","Diversion","Invigorate","Bloodbath","Goad","Feint","Crutch","True North"], 'Ninja': ["Second Wind","Arm's Length","Leg Sweep","Diversion","Invigorate","Bloodbath","Goad","Feint","Crutch","True North"], 'Samurai': ["Second Wind","Arm's Length","Leg Sweep","Diversion","Invigorate","Bloodbath","Goad","Feint","Crutch","True North"], 'RedMage': ["Addle","Break","Drain","Diversion","Lucid Dreaming","Swiftcast","Mana Shift","Apocatastasis","Surecast","Erase"], 'BlackMage': ["Addle","Break","Drain","Diversion","Lucid Dreaming","Swiftcast","Mana Shift","Apocatastasis","Surecast","Erase"], 'Summoner': ["Addle","Break","Drain","Diversion","Lucid Dreaming","Swiftcast","Mana Shift","Apocatastasis","Surecast","Erase"], 'DarkKnight': ["Rampart","Low Blow","Provoke","Convalescence","Anticipation","Reprisal","Awareness","Interject","Ultimatum","Shirk"], 'Paladin': ["Rampart","Low Blow","Provoke","Convalescence","Anticipation","Reprisal","Awareness","Interject","Ultimatum","Shirk"], 'Warrior': ["Rampart","Low Blow","Provoke","Convalescence","Anticipation","Reprisal","Awareness","Interject","Ultimatum","Shirk"], 'Astrologian': ["Cleric Stance","Break","Protect","Esuna","Lucid Dreaming","Swiftcast","Eye for an Eye","Largesse","Surecast","Rescue"], 'WhiteMage': ["Cleric Stance","Break","Protect","Esuna","Lucid Dreaming","Swiftcast","Eye for an Eye","Largesse","Surecast","Rescue"], 'Scholar': ["Cleric Stance","Break","Protect","Esuna","Lucid Dreaming","Swiftcast","Eye for an Eye","Largesse","Surecast","Rescue"], } const all_damageSteps = { 'Bard': {}, 'BlackMage': { 'Foul': [.9, .8, .7, .6, .5], 'Flare': [.85, .7, .55, .4, .3], }, 'Dragoon': {}, 'Machinist': { 'Ricochet': [.9, .8, .7, .6, .5], 'Aether Mortar': [.9, .8, .7, .6, .5], 'Charged Aether Mortar': [.9, .8, .7, .6, .5], }, 'Monk': {}, 'Ninja': {}, 'RedMage': {}, 'Samurai': { 'Mangetsu': [.9, .8, .7, .6, .5], 'Oka': [.9, .8, .7, .6, .5], '<NAME>': [.9, .8, .7, .6, .5], 'Hissatsu: Guren': [.75, .5], }, 'Summoner': { 'Deathflare': [.9, .8, .7, .6, .5], '<NAME>': [.9, .8, .7, .6, .5], }, 'DarkKnight': {}, 'Paladin': {}, 'Warrior': {}, 'WhiteMage': { 'Holy': [.9, .8, .7, .6, .5], }, 'Astrologian': { 'Gravity': [.9, .8, .7, .6, .5], }, 'Scholar': { 'Bio': [.8, .6, .4, .2], 'Bio II': [.8, .6, .4, .2], 'Miasma': [.8, .6, .4, .2], 'Miasma II': [.8, .6, .4, .2], 'Shadow Flare': [.8, .6, .4, .2], }, } const all_combo_damageSteps = { 'Bard': {}, 'BlackMage': {}, 'Dragoon': {}, 'Machinist': {}, 'Monk': {}, 'Ninja': {}, 'RedMage': {}, 'Samurai': { 'Mangetsu': [.95, .9, .85, .8, .75], 'Oka': [.95, .9, .85, .8, .75], }, 'Summoner': {}, 'DarkKnight': {}, 'Paladin': {}, 'Warrior': {}, 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } const template = { 'Bard': {}, 'BlackMage': {}, 'Dragoon': {}, 'Machinist': {}, 'Monk': {}, 'Ninja': {}, 'RedMage': {}, 'Samurai': {}, 'Summoner': {}, //tanks 'DarkKnight': {}, 'Paladin': {}, 'Warrior': {}, //heals 'WhiteMage': {}, 'Astrologian': {}, 'Scholar': {}, } <file_sep>/js/compare.js async function processRankings(response) { var proc0 = performance.now(); //console.log("Report:"); //console.log(report); var rankings = response.rankings; //console.log(rankings); //rankings.length var r0 = performance.now(); var count = 0; for (var i=0; i < rankings.length; i++){ var r1 = performance.now(); console.log(rankings[i]); var fightID = rankings[i].fightID; var reportURL = base_url + "/report/fights/" + rankings[i].reportID + "?translate=true&api_key=" + api_key; //console.log(reportURL); fetchUrl(reportURL, processReport, rankings[i]); count +=2; if(count > 100 && ((r1 - r0) > 1000)){ console.log(count + " parses in " + (r1 - r0).toFixed(4) + "ms sleeping..."); //console.log("sleeping..."); var s0 = performance.now(); await sleep(1000); var s1 = performance.now(); console.log("Slept for " + (s1 - s0).toFixed(4) + "ms"); r0 = performance.now(); count = 0; } //return; } } function sleep(ms) { return new Promise(resolve => setTimeout(resolve, ms)); } function processReport(response, ranking){ var proc0 = performance.now(); //console.log("Report:"); //console.log(response); var result = { report: { reportID: ranking.reportID, fightID: ranking.fightID, }, fight: { team: {}, enemies: {} }, player: { name: ranking.name, pets: [] }, events: {}, totals: {}, } var reportResult = parseReport(response, result); var par1 = performance.now(); //console.log("Report parsing took " + (par1-proc0).toFixed(4) + "ms"); var url = base_url + "/report/events/" + result.report.reportID + "?translate=true"; url += "&start=" + result.fight.start; url += "&end=" + result.fight.end; url += "&actorid=" + result.player.ID; url += "&api_key=" + api_key; fetchUrl(url, processClass, result); var proc1 = performance.now(); //console.log("processReport took " + (proc1-proc0).toFixed(4) + "ms"); } function processClass(response, result) { //console.log("Processing " + spec); var spec = result.player.type; var t0 = performance.now(); t0 = performance.now(); result = parseFunctions[spec](response, result); t1 = performance.now(); //console.log("Parseing took " + (t1 - t0).toFixed(4) + "ms"); //console.log(result); var tbl_row = '<tr>'; var damage = 0; var potency = 0; var time = 0; if (Object.keys(result.totals).length > 1) { var time = 0; for (var k in result.totals) { damage += result.totals[k].amount; potency += result.totals[k].potency; time = Math.max(time, result.totals[k].time); } } else { damage = result.totals[result.player.ID].amount; potency = result.totals[result.player.ID].potency; time = result.totals[result.player.ID].time; } tbl_row += `<td><a href="events.html?name=${result.player.name}&report=${result.report.reportID}&fight=${result.report.fightID}&api_key=${api_key}">${result.player.name}</a><span class="damage-block ${result.player.type}"></span></td>`; tbl_row += `<td>${time}</td>`; //damage tbl_row += `<td>${damage}</td>`; //damage tbl_row += `<td>${(damage/time).toFixed(2)}</td>`; //dps tbl_row += `<td>${potency}</td>`; //damage tbl_row += `<td>${(potency/time).toFixed(2)}</td>`; //dps tbl_row += `<td>${(damage/potency).toFixed(2)}</td>`; //damage:potency tbl_row += '</tr>'; $(".ranking-table tbody").append(tbl_row); } function getRankingsData() { var url = base_url + '/rankings/encounter/' + getUrlParameter('encounter') + '?'; var opts = ['bracket', 'spec', 'region','metric','page','filter','api_key']; var terms = []; for(var i=0; i < opts.length; i++) if(getUrlParameter(opts[i]) != undefined) terms.push(`${opts[i]}=${getUrlParameter(opts[i])}`); url += terms.join('&'); console.log(url); httpGetAsync(url, processRankings); } getRankingsData();<file_sep>/python/testParse.py #--------------------------------------- # 1. Download full list of parses # 2. go through each one to get potency # 3. save as csv # 4. ... # 5. profit # # # # #---------------------------------------<file_sep>/README.md "# fflogpps" <file_sep>/js/parse.js const parseFunctions = { //DPS 'Bard': parseClass,//parseBard, 'Dragoon': parseClass,//parseDragoon, 'Monk': parseClass, //parseMonk, 'Ninja': parseClass, //parseNinja, 'RedMage': parseClass, //parseRedmage, 'Samurai': parseClass, //parseSamurai, 'Machinist': parseMachinist, //overheat and pet 'BlackMage': parseBlackmage, //astral/umbral math 'Summoner': parseSummoner, //pet //TANKS 'DarkKnight': parseClass, 'Paladin': parseClass, 'Warrior': parseClass, //HEALS 'Astrologian': parseClass, 'WhiteMage': parseClass, 'Scholar': parseClass } function parseReport(report, result) { //console.log("Parsing Report for " + report.title); var fightID = result.report.fightID; //console.log(fightID); for (var k in report.fights) { var fight = report.fights[k]; if (fight.id == fightID) { result.fight.start = fight.start_time; result.fight.end = fight.end_time; result.fight.duration = (fight.end_time - fight.start_time) / 1000; } } for (var k in report.friendlies) { var friend = report.friendlies[k]; for (var j in friend.fights) { if (friend.fights[j].id == fightID) { if (friend.hasOwnProperty("name")) { result.fight.team[friend.id] = friend.name; } if (friend.name == result.player.name) { result.player.ID = friend.id; result.player.type = friend.type; } } } } for (var k in report.enemies) { var enemy = report.enemies[k]; for (var j in enemy.fights) { if (enemy.fights[j].id == fightID) { if (enemy.hasOwnProperty("name")) { result.fight.enemies[enemy.id] = enemy.name; } } } } for (var k in report.friendlyPets) { var pet = report.friendlyPets[k]; for (var j in pet.fights) { if (pet.fights[j].id == fightID) { if (pet.hasOwnProperty("name")) { result.fight.team[pet.id] = pet.name; } if (pet.petOwner == result.player.ID) { result.player.pets.push(pet.id) break; } } } } return result; } function parseGeneric(response) { console.log("Parse Generic"); var prevTime = 0; for (var e in response.events) { var event = response.events[e]; console.log(event); //only events of self pets or targetted on self if (event.sourceID != result.player.ID) { if (result.player.pets.indexOf(event.sourceID) == -1 && event.type != "applybuff") { continue; } } getBasicData(event, result.fight); var potency = 0; result.events[e] = event; } return result; } function buildRow(data, fight) { tbl_row = ''; tbl_row += `<td>${data.name}<span class="castType">${data.type}</span></td>`; tbl_row += `<td>${data.amount == 0 ? '':data.amount} <span class="castType">${data.isDirect ? "Direct ":''}${data.hitType}</span><span class="damage-block ${damageTypes[data.dmgType]}"></span></td>`; if (data.isTargetFriendly) tbl_row += `<td>${fight.team[data.target]}</td>`; else tbl_row += `<td>${fight.enemies[data.target]}</td>`; tbl_row += `<td class="center">${data.fightTime.toFixed(2)}</td>`; if (data.extra != undefined) { for (var i = 0; i < data.extra.length; i++) { tbl_row += `<td class="center">${data.extra[i]}</td>`; } } return tbl_row; } function applyBuffs(value, event, buffs) { for (var b in buffs) { var buff = buffs[b]; if (buff.isAllowed(event) && buff.getBonus(event) != 0) { value = buff.apply(value, event); event.tooltip += buff.name + ": " + buff.getDisplay(event) + " [" + value.toFixed(0) + "]<br/>"; } } return value; } function hasBuff(name, buffs) { if (buffs.hasOwnProperty(name)) return buffs[name].active; return false; } function preScreen(type, events, buffs, timers, activePet) { var start = events[0].timestamp; if (type == "Bard") { //prescan first couple attacks to see what buffs fall off var prefoe = true; for (var e in events) { var event = events[e]; if (event.timestamp > start + 5000) //just 5 seconds which is enough time to ensure a server tick to see if foe is applied break; //if foe shows as an applybuff to self first in the log first, it wasn't precasted if (event.type == "applybuff") { if (event.ability.name == "Foe Requiem") prefoe = false; } if (event.type == "applydebuff") { if (event.ability.name == "Foe Requiem" && prefoe) buffs[event.ability.name].add(event); } } } else if (type == "RedMage") { var acceleration_cast = false; for (var e in events) { var event = events[e]; if (event.timestamp > start + 10000) //10 seconds ahead break; //foe shows as an applybuff to self first in the log first, it wasn't precasted if (event.type == "removebuff") { if (event.ability.name == "Acceleration") buffs["Acceleration"].applybuff(); } if (event.type == "applybuff") { if (event.ability.name == "Acceleration") acceleration_cast = true; } } if (acceleration_cast) buffs["Acceleration"].active = false; } else if (type == "Dragoon") { for (var e in events) { var event = events[e]; if (event.type == "cast") { if (event.ability.name == "Fang And Claw" || event.ability.name == "Wheeling Thrust" || event.ability.name == "Sonic Thrust") { timers["Blood Of The Dragon"].restart(); } } if (event.timestamp > start + 20000) break; } buffs["Blood Of The Dragon"].active = timers["Blood Of The Dragon"].isActive(); } else if (type == "Machinist") { var notgauss = false; var startRook = true; for (var e in events) { var event = events[e]; if (event.ability.name == "Gauss Barrel") { notgauss = true; } if (['Charged Volley Fire', 'Volley Fire', 'Aether Mortar', 'Charged Aether Mortar', 'Rook Overload', 'Bishop Overload'].indexOf(event.ability.name) > -1) { activePet[0] = event.sourceID } if (event.timestamp > start + 20000) break; } if (notgauss) { buffs['Gauss Barrel'].active = false; } buffs['Ammunition'].applybuff(); } else if (type == "Ninja") { var hutonCast = false; for (var e in events) { var event = events[e]; if (event.type == "cast") { if (event.ability.name == "Huton") { hutonCast; } } if (event.timestamp > start + 20000) break; } if (!hutonCast) timers['Huton'].restart(); } else if (type == "Summoner") { for (var e in events) { var event = events[e]; if (egiAbilities.indexOf(event.ability.name) > -1) { activePet[0] = event.sourceID } //the remove only shows up within 20 seconds if it was started prefight if (event.type == 'removebuff' && event.ability.name == "Rouse") { buffs['Rouse'].applybuff(); } if (event.timestamp > start + 20000) break; } } else if (type == 'DarkKnight'){ var grit_cast = false; var dark_cast = false; var dark_rem = false; for (var e in events) { var event = events[e]; if (event.timestamp > start + 10000) //10 seconds ahead break; //foe shows as an applybuff to self first in the log first, it wasn't precasted if (event.type == "removebuff") { if(!dark_cast && event.ability.name == 'Dark Arts') dark_rem = true; if (event.ability.name == "Grit") buffs["Grit"].applybuff(); } if (event.type == "applybuff") { if (event.ability.name == "Grit") grit_cast = true; } if(event.type == "cast"){ if(!dark_rem && event.ability.name == 'Dark Arts') dark_cast = true; } } if (grit_cast) buffs["Grit"].applybuff(); if(dark_rem && !dark_cast) buffs['Dark Arts'].applybuff(); } else if (type == 'Paladin'){ var oath_cast = false; var start_sword = false; for (var e in events) { var event = events[e]; if (event.timestamp > start + 10000) //10 seconds ahead break; //foe shows as an applybuff to self first in the log first, it wasn't precasted if (event.type == "cast") { if (event.ability.name == "Sword Oath" || event.ability.name == "Shield Oath") oath_cast = true; } if (event.type == "damage") { if (event.ability.name == "Sword Oath") start_sword = true; } } if (!oath_cast){ //no oath cast during opening meaning we start with one on if(start_sword) buffs['Sword Oath'].applybuff(); else buffs['Shield Oath'].applybuff(); } } else if (type == 'Warrior'){ var deliverance_start = false; for (var e in events) { var event = events[e]; if (event.timestamp > start + 20000) //20 seconds ahead break; //foe shows as an applybuff to self first in the log first, it wasn't precasted if (event.type == "cast") { //console.log(event.ability.name); if(['Inner Release', 'Fell Cleave', 'Decimate', 'Defiance'].indexOf(event.ability.name) > -1){ //delivrance ability was used //console.log(event.ability.name); deliverance_start = true; break; } else if(event.ability.name == 'Deliverance'){ break; } } } //if defiance is cast we assume we start with the other one, otherwise we are in defiance if(deliverance_start) buffs['Deliverance'].applybuff(); else buffs['Defiance'].applybuff(); } } function updateTimers(timers, buffs, ellapsed, event) { if (timers != undefined) { for (var t in timers) { timers[t].update(ellapsed); } } for (var b in buffs) { if (typeof buffs[b].update === 'function') { //console.log(buffs[b].targets); buffs[b].update(event); } } } function updateBuffs(buffs, timers, event, result, activePet) { //console.log(event); //BUFF APPLICATION if (event.type == "applybuff" || event.type == "refreshbuff") { if (buffs.hasOwnProperty(event.name) && (event.targetID == result.player.ID || event.targetID == activePet)) buffs[event.name].applybuff(); } else if (event.type == "applybuffstack") { if (buffs.hasOwnProperty(event.name) && (event.targetID == result.player.ID || event.targetID == activePet)) { buffs[event.name].setStacks(event.stack); } } else if (event.type == "applydebuff" || event.type == "refreshdebuff") { if (buffs.hasOwnProperty(event.name) && event.targetID != null) { buffs[event.name].add(event); } } //BUFF REMOVAL else if (event.type == "removebuff") { if (buffs.hasOwnProperty(event.name) && (event.targetID == result.player.ID || event.targetID == activePet)) buffs[event.name].stopBuff(event); } else if (event.type == "removebuffstack") { if (buffs.hasOwnProperty(event.name) && (event.targetID == result.player.ID || event.targetID == activePet)) buffs[event.name].setStacks(event.stack); } else if (event.type == "removedebuff") { if (buffs.hasOwnProperty(event.name)) buffs[event.name].remove(event); } //update matching buffs to timers if (timers != undefined) { for (var t in timers) { if (buffs.hasOwnProperty(t)) if (timers[t].isActive() && buffs[t].active == false) buffs[t].applybuff(); else if (!timers[t].isActive()) buffs[t].stopBuff(event); } } } function removeBuffs(buffs, event){ for(var b in buffs){ if(buffs[b].stopTime != 0 && buffs[b].stopTime < event.fightTime) buffs[b].removeBuff(); } } function updateExtras(extra, event, buffs, type) { var columns = buff_display[type]; for (var b in columns) { var displayString = columns[b].display(event, buffs[b]); if (displayString != undefined) extra.push(displayString); } } function reorderEvents(events){ console.log(events); } function getPotencies(spec){ var potencies = all_potencies[spec]; potencies['Death Bolt'] = 0; return potencies; } function parseClass(response, result) { var type = result.player.type; //console.log("Parsing " + type); var prevTime = 0; var ellapsed = 0; var lastWS = ""; var ratio = 0; //aoe spells var lastDamage = ''; var lastFightTime = ''; var dStep = 0; var damageSteps = all_damageSteps[type]; var combo_damageSteps = all_combo_damageSteps[type]; //pet support var activePet = 0; var petLookup = {}; for (var p in result.player.pets) { petLookup[result.fight.team[result.player.pets[p]]] = result.player.pets[p]; } result.totals[result.player.ID] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.ID], 'id': result.player.ID, 'time': 0 //result.fight.duration, } for (var p in result.player.pets) { result.totals[result.player.pets[p]] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.pets[p]], 'id': result.player.pets[p], 'time': 0 //result.fight.duration, } } //potencies var potencies = getPotencies(type); var combo_potencies = all_combo_potencies[type]; var pos_potencies = all_pos_potencies[type]; var pos_combo_potencies = all_pos_combo_potencies[type]; //dots var dot_potencies = {}; var dot_base = all_dot_base[type]; //skills var combo = all_combo[type]; var comboskills = all_comboskills[type]; var weaponskills = all_weaponskills[type]; //buffs var buffs = all_buffs[type]; //role actions var role_all = role_actions[type]; var role_taken = {}; for (var i = 0; i < role_all.length; i++) { role_taken[role_all[i]] = 0; } //timers var timers = all_timers[type]; /* reorder events to always be the same order for each timestamp begincast applybuff applydebuff refreshbuff cast damage heal removebuff removedebuff */ //reorderEvents(response.events); //prescan if (['Samurai','Monk'].indexOf(type) == -1){ var ps0 = performance.now(); preScreen(type, response.events, buffs, timers); var ps1 = performance.now(); console.log("Prescreen took " + (ps1-ps0).toFixed(4) + "ms"); } //Main Parsing var newCast = false; for (var e in response.events) { var event = response.events[e]; //only events of self pets or targetted on self if (event.sourceID != result.player.ID) { if (result.player.pets.indexOf(event.sourceID) == -1 && event.type != "applybuff") { continue; } } getBasicData(event, result.fight); var potency = 0; removeBuffs(buffs, event); if (event.type == "damage" && event.amount != 0) { if (event.dmgType == 1 || event.dmgType == 64) { //dots potency = dot_potencies[event.name]; event.tooltip = "DoT: " + event.name; } else { potency = potencies[event.name]; if (combo.hasOwnProperty(event.name)) { if (combo[event.name].indexOf(lastWS) > -1 || (event.name == lastWS && !newCast) || hasBuff('Meikyo Shisui', buffs)) { //hack for aoe combos if ((hasBuff("True North", buffs) || hasBuff('Dark Arts', buffs)) && pos_combo_potencies.hasOwnProperty(event.name)) potency = pos_combo_potencies[event.name]; else potency = combo_potencies[event.name]; } } else { if ((hasBuff("True North", buffs) || hasBuff('Dark Arts', buffs)) && pos_potencies.hasOwnProperty(event.name)) potency = pos_potencies[event.name]; } if (comboskills.indexOf(event.name) > -1 && !hasBuff("Duality", buffs)) { lastWS = event.name; } if (event.name == "Pitch Perfect") { var val = event.amount; if (event.isDirect) val *= 1 / 1.25; if (event.hitType == "Crit") val *= 1 / 1.45; val = val / ratio; if (val >= 400) potency = 420; else if (val >= 150) potency = 240; } else if(event.name == "Bloodspiller"){ if(hasBuff('Grit', buffs)) if(hasBuff('Dark Arts', buffs)) potency += 90; else potency += 75; } else if (event.name == 'Sidewinder'){ if(hasBuff('Storm Bite', buffs) && hasBuff('Caustic Bite', buffs)) potency = 260; else if(hasBuff('Storm Bite', buffs) || hasBuff('Caustic Bite', buffs)) potency = 170; } event.tooltip = event.name + ": " + potency + "<br/>"; //if the spell decreases on aoe test if the time and name are the same if (event.fightTime == lastFightTime && event.name == lastDamage) { //test for combo var curSteps = damageSteps; if (combo.hasOwnProperty(event.name)){ if (combo[event.name].indexOf(lastWS) > -1 || event.name == lastWS || hasBuff('Meikyo Shisui', buffs)) curSteps = combo_damageSteps; } if (curSteps.hasOwnProperty(event.name)) { //decriment the potency //console.log(event.fightTime + " - " + event.name); var step = curSteps[event.name][Math.min(dStep, curSteps[event.name].length - 1)]; potency = Math.trunc(potency * step); event.tooltip += "Multiple Targets: -" + ((1 - step) * 100).toFixed(0) + "% [" + potency.toFixed(0) + "]<br/>"; dStep++; } } else { lastDamage = event.name; lastFightTime = event.fightTime; dStep = 0; } if (event.name == 'Upheaval'){ //max health var maxhealth = event.sourceResources.maxHitPoints; if(hasBuff('Defiance', buffs)) maxhealth = maxhealth / 1.25; if(hasBuff('Thrill Of Battle', buffs)) maxhealth = maxhealth / 1.2; var bonus = Math.max(event.sourceResources.hitPoints/maxhealth, 1/3); //health bonus potency = Math.trunc(potency * (bonus)); event.tooltip += "Health Modifier: " + ((bonus-1) * 100).toFixed(0) + "% [" + potency.toFixed(0) + "]<br/>"; } potency = applyBuffs(potency, event, buffs); if (dot_base.hasOwnProperty(event.name)) { event.tooltip += "<br/>Dot Damage:<br/>"; dot_potencies[event.name] = applyBuffs(dot_base[event.name], event, buffs); } else if (event.name == "Stormbite") { //cast Stormbite, Dot Storm Bite so it doesnt fit the normal pattern event.tooltip += "<br/>Dot Damage:<br/>"; dot_potencies['Storm Bite'] = applyBuffs(dot_base['Storm Bite'], event, buffs); } else if (event.name == "Iron Jaws") { //iron jaws reapplies both dots event.tooltip += "<br/>Dot Damage:<br/>"; dot_potencies["Storm Bite"] = applyBuffs(dot_base["Storm Bite"], event, buffs); event.tooltip += "<br/>Dot Damage:<br/>"; dot_potencies["Caustic Bite"] = applyBuffs(dot_base["Caustic Bite"], event, buffs); } } if (potency == undefined) potency = 0; if (potency == 0 && event.amount != 0) { console.log("WARNING @ " + event.fightTime + ": Damage dealt with unknown potency [Report: " + result.report.reportID + " Player: " + result.player.name + "]"); } newCast = false; } //TIMERS AND TIMED BUFFS ellapsed = event.fightTime - prevTime; if (ellapsed != 0) updateTimers(timers, buffs, ellapsed, event); if (event.type == "cast") { //id match shouldn't be needed bt being safe if (role_all.indexOf(event.name) != -1 && event.sourceID == result.player.ID) { role_taken[event.name]++; } if (dot_base.hasOwnProperty(event.name)) { dot_potencies[event.name] = applyBuffs(dot_base[event.name], event, buffs); } else if(event.name == "Stormbite"){ dot_potencies['Storm Bite'] = applyBuffs(dot_base['Storm Bite'], event, buffs); } if (timers.hasOwnProperty(event.name)) { //bard unique, other songs need to stop when a new song starts if (type == "Bard") { var img = ''; var songs = ["The Wanderer's Minuet", "Mage's Ballad", "Army's Paeon"]; if (songs.indexOf(event.name) > -1) { for (var i = 0; i < songs.length; i++) timers[songs[i]].stop(); img = `<img src="/img/${event.name.replace(/'/g,"").replace(/ /g, "_").toLowerCase()}.png"/>`; } } timers[event.name].restart(); } //ability specific if (event.name == "Armor Crush") { timers["Huton"].update(-30); } else if (event.name == "Iron Jaws") { dot_potencies["Storm Bite"] = applyBuffs(dot_base["Storm Bite"], event, buffs); dot_potencies["Caustic Bite"] = applyBuffs(dot_base["Caustic Bite"], event, buffs); } else if (event.name == "Fang And Claw" || event.name == "Wheeling Thrust" || event.name == "Sonic Thrust") { if (timers["Blood Of The Dragon"].isActive()) timers["Blood Of The Dragon"].extend(10, 30); } else if(event.name == 'The Balance'){ if(event.targetID == null) buffs[event.name].bonus = .05; else buffs[event.name].bonus = .10; } else if(event.name == 'The Spear'){ if(event.targetID == null) buffs[event.name].bonus = .05 * 1.45; else buffs[event.name].bonus = .10 * 1.45; } else if(event.name == 'Earthly Star'){ activePet = petLookup[event.name]; } else if (event.name == 'Stellar Burst' || event.name == 'Stellar Explosion'){ activePet = 0; } newCast = true; } //BUFF APPLICATION //console.log(event); updateBuffs(buffs, timers, event, result); //class specifics if (type == "Monk") { if (event.type == "applybuff" || event.type == "refreshbuff") { if (event.name == "Fists Of Wind" || event.name == "Fists Of Earth") { buffs["Fists Of Fire"].active = false; buffs["Riddle Of Fire"].active = false; } } } else if (type == "Paladin") { if (event.type == "applybuff" || event.type == "refreshbuff" || event.type == 'applybuffstack') { if (event.name == "Shield Oath") { buffs["Sword Oath"].removebuff(); } else if (event.name == "Sword Oath") { buffs["Shield Oath"].removebuff(); } } } var extra = []; updateExtras(extra, event, buffs, type); //class specific if (type == "Bard") { if (buffs["The Wanderer's Minuet"].active) extra.push(`<div class="center status-block" style="background-color: #4F6F1F">${img}</div>`); else if (buffs["Mage's Ballad"].active) extra.push(`<div class="center status-block" style="background-color: #A07FC0">${img}</div>`); else if (buffs["Army's Paeon"].active) extra.push(`<div class="center status-block" style="background-color: #D07F5F">${img}</div>`); else extra.push(``); img = ''; } else if (type == "Paladin") { img = ''; if (["applybuff", "applydebuff"].indexOf(event.type) > -1) if(event.name == 'Sword Oath') img = `<img src="img/sword_oath.png">`; else if(event.name == 'Shield Oath') img = `<img src="img/shield_oath.png">`; if (hasBuff("Sword Oath", buffs)) extra.push(`<div class="center status-block" style="background-color: #93CACD">${img}</div>`); else if (buffs["Shield Oath"].active) extra.push(`<div class="center status-block" style="background-color: #E7DE95">${img}</div>`); else extra.push(``); img = ''; } else if (type == "Warrior") { //unchained and inner release if (["applybuff", "refreshbuff", "applydebuff"].indexOf(event.type) > -1) if(event.name == 'Unchained' || event.name == 'Inner Release') img = `<img src="img/${event.name.toLowerCase().replace(/ /g,'_')}.png">`; if (hasBuff("Unchained", buffs)) extra.push(`<div class="center status-block" style="background-color: #CE7CD1">${img}</div>`); else if (hasBuff("Inner Release", buffs)) extra.push(`<div class="center status-block" style="background-color: #9B553E">${img}</div>`); else extra.push(``); img = ''; //defiance vs deliverance img = ''; if (["applybuff", "refreshbuff", "applydebuff"].indexOf(event.type) > -1) if(event.name == 'Defiance' || event.name == 'Deliverance') img = `<img src="img/${event.name.toLowerCase()}.png">`; if (hasBuff("Defiance", buffs)) extra.push(`<div class="center status-block" style="background-color: #6E8C16">${img}</div>`); else if (hasBuff("Deliverance", buffs)) extra.push(`<div class="center status-block" style="background-color: #495685">${img}</div>`); else extra.push(``); img = ''; } event.extra = extra; event.potency = potency; prevTime = event.fightTime; result.events[e] = event; //update ratio currently only used for guessing pitch perfect :/ //dont acount for dots, since we cant properly tell crits or directs (do dots direct?) //ignore auto attacks from the non melee classes if(event.fightTime > 10){ if (!(['RedMage', 'BlackMage', 'Summoner', 'WhiteMage', 'Astrologian', 'Scholar'].indexOf(type) > -1 && event.name == "Attack")) { if (event.potency != 0 && (event.dmgType != 1 && event.dmgType != 64)) { var tp = event.potency * (event.isDirect ? 1.25 : 1) * (event.hitType == 'Crit' ? 1.45 : 1); var r = event.amount / tp; var expected = event.potency * ratio; expected = Math.trunc(expected * (event.isDirect ? 1.25 : 1)); expected = Math.trunc(expected * (event.hitType == 'Crit' ? 1.45 : 1)); var baseline = event.amount; var variance = expected / event.amount; if (ratio != 0 && (variance > 1.3 || variance < .7)) console.log('WARNING @ ' + event.fightTime + ': ' + event.name + ' - ' + expected.toFixed(0) + ' vs ' + event.amount + " [Report: " + result.report.reportID + " Player: " + result.player.name + "]"); //warning if something is far off from the ratio? if (ratio == 0) ratio = r; else ratio = (ratio + r) / 2 } } } if (event.amount > 0 && event.type != 'heal') { if (result.totals.hasOwnProperty(event.sourceID)) { result.totals[event.sourceID].amount += event.amount; result.totals[event.sourceID].potency += potency; } else { console.log("Unaccounted for source"); console.log(event); } } result.totals[result.player.ID].time += ellapsed; if (result.totals.hasOwnProperty(activePet)) result.totals[activePet].time += ellapsed; } //role actions used for (var r in role_taken) { if (role_taken[r] == 0) delete role_taken[r]; } result.role_actions = Object.keys(role_taken); return result; } function parseBlackmage(response, result) { var type = result.player.type; //console.log("Parsing BLM"); var suffix = ['', '', '_ii', '_iii']; //totals result.totals[result.player.ID] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.ID], 'id': result.player.ID, 'time': 0 //result.fight.duration, } //buffs var buffs = all_buffs[type]; //role actions var role_all = role_actions[type]; var role_taken = {}; for (var i = 0; i < role_all.length; i++) { role_taken[role_all[i]] = 0; } //timers var timers = all_timers[type]; //potencies var potencies = getPotencies(type); //dots var dot_potencies = {}; var dot_base = all_dot_base[type]; var first = true; var prevTime = 0; //aoe spells var lastDamage = ''; var lastFightTime = ''; var dStep = 0; var damageSteps = all_damageSteps[type]; var combo_damageSteps = all_combo_damageSteps[type]; //role actions var role_all = role_actions[type]; var role_taken = {}; for (var i = 0; i < role_all.length; i++) { role_taken[role_all[i]] = 0; } for (var e in response.events) { var potency = 0; var event = response.events[e]; //only events of self pets or targetted on self if (event.sourceID != result.player.ID) { if (result.player.pets.indexOf(event.sourceID) == -1 && event.type != "applybuff") { continue; } } getBasicData(event, result.fight); if (event.type == "damage" && event.amount != 0) { //Dots if (event.dmgType == 1 || event.dmgType == 64) { potency = dot_potencies[event.name]; event.tooltip = "DoT: " + event.name; } else { potency = potencies[event.name]; event.tooltip = event.name + ": " + potency + "<br/>"; //if the spell decreases on aoe test if the time and name are the same if (event.fightTime == lastFightTime && event.name == lastDamage) { if (damageSteps.hasOwnProperty(event.name)) { //decriment the potency console.log(event.fightTime + " - " + event.name); var step = damageSteps[event.name][Math.min(dStep, damageSteps[event.name].length - 1)]; potency = Math.trunc(potency * step); event.tooltip += "Multiple Targets: -" + ((1 - step) * 100).toFixed(0) + "% [" + potency.toFixed(0) + "]<br/>"; dStep++; } } else { lastDamage = event.name; lastFightTime = event.fightTime; dStep = 0; } potency = applyBuffs(potency, event, buffs); if (potency == undefined) potency = 0; if (potency == 0 && event.amount != 0) { console.log("WARNING: Damage dealt with unknown potency"); console.log(event); } } } //TIMERS AND TIMED BUFFS ellapsed = event.fightTime - prevTime; updateTimers(timers, buffs, ellapsed, event); if (timers['Enochian'].isActive() || timers['Enochian'].justFell) { //enoch.update(ellapsed); if (buffs['Astral Fire'].stacks <= 0 && buffs['Umbral Ice'].stacks <= 0) { timers['Enochian'].stop(); } else if (timers['Enochian'].current <= 0) { timers['Enochian'].restartOffset(); } } buffs["Enochian"].active = timers['Enochian'].isActive(); var img = ''; if (event.type == "cast") { //id match shouldn't be needed bt being safe if (role_all.indexOf(event.name) != -1 && event.sourceID == result.player.ID) { role_taken[event.name]++; } //update dots if (dot_base.hasOwnProperty(event.name)) { dot_potencies[event.name] = applyBuffs(dot_base[event.name], event, buffs); } if (timers.hasOwnProperty(event.name)) { timers[event.name].restart(); } } if (event.type == "damage") { switch (event.ability.name) { case "Fire": case "Fire II": if (buffs['Umbral Ice'].active) { timers['Umbral Ice'].stop(); buffs['Umbral Ice'].setStacks(0); } else { timers['Astral Fire'].restart(); buffs['Astral Fire'].addStacks(1); img = "astral_fire" + suffix[buffs['Astral Fire'].stacks] + ".png"; } break; case "Blizzard": case "Blizzard II": case "Freeze": if (buffs['Astral Fire'].active) { timers['Astral Fire'].stop(); buffs['Astral Fire'].setStacks(0); } else { timers['Umbral Ice'].restart(); buffs['Umbral Ice'].addStacks(1); img = "umbral_ice" + suffix[buffs['Umbral Ice'].stacks] + ".png"; } break; case "Fire III": case "Flare": timers['Astral Fire'].restart(); buffs['Astral Fire'].setStacks(3); timers['Umbral Ice'].stop(); img = "astral_fire_iii.png"; break; case "Blizzard III": timers['Umbral Ice'].restart(); buffs['Umbral Ice'].setStacks(3); timers['Astral Fire'].stop(); img = "umbral_ice_iii.png"; break; case "Transpose": if (umbral > 0) { timers['Astral Fire'].restart(); buffs['Astral Fire'].setStacks(1); timers['Umbral Ice'].stop(); img = "astral_fire" + suffix[umbralStack] + ".png"; } else if (astral > 0) { timers['Umbral Ice'].restart(); buffs['Umbral Ice'].setStacks(1); timers['Astral Fire'].stop(); img = "umbral_ice" + suffix[umbralStack] + ".png"; } break; } } //BUFF APPLICATION updateBuffs(buffs, timers, event, result); var extra = []; updateExtras(extra, event, buffs, type); var timg = ''; if (timg != '') timg = `<img src="img/${img}"/>`; if (buffs['Thunder IV'].active) { if (event.name == 'Thunder IV' && ["cast", "applybuff", "applydebuff"].indexOf(event.type) > -1) timg = `<img src="img/thunder_iv.png">`; extra.push(`<div class="center status-block" style="background-color: #A14AB6">${timg}</div>`); } else if (buffs['Thunder III'].active) { if (event.name == 'Thunder III' && ["cast", "applybuff", "applydebuff"].indexOf(event.type) > -1) timg = `<img src="img/thunder_iii.png">`; extra.push(`<div class="center status-block" style="background-color: #3D6DB6">${timg}</div>`); } else { extra.push(''); } timg = ''; if (img != '') img = `<img src="img/${img}"/>`; if (buffs['Astral Fire'].active) { extra.push(`<div class="center status-block" style="background-color: #F05F2F">${img}</div>`); } else if (buffs['Umbral Ice'].active) { extra.push(`<div class="center status-block" style="background-color: #5FD0F0">${img}</div>`); } else { extra.push(''); } img = ''; event.extra = extra; event.potency = potency; prevTime = event.fightTime; result.events[e] = event; //potency & time tracking if (event.amount > 0 && event.type != 'heal') { if (result.totals.hasOwnProperty(event.sourceID)) { result.totals[event.sourceID].amount += event.amount; result.totals[event.sourceID].potency += potency; } else { console.log("Unaccounted for source"); console.log(event); } } result.totals[result.player.ID].time += ellapsed; } //role actions used for (var r in role_taken) { if (role_taken[r] == 0) delete role_taken[r]; } result.role_actions = Object.keys(role_taken); //console.log(result); return result; } function parseMachinist(response, result) { var type = result.player.type; //console.log("Parsing MCH"); var prevTime = 0; var activePet = 0; var petLookup = {}; for (var p in result.player.pets) { petLookup[result.fight.team[result.player.pets[p]]] = result.player.pets[p]; } result.totals[result.player.ID] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.ID], 'id': result.player.ID, 'time': 0 //result.fight.duration, } for (var p in result.player.pets) { result.totals[result.player.pets[p]] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.pets[p]], 'id': result.player.pets[p], 'time': 0 //result.fight.duration, } } //trackers var heatChange = 0; var removeBarrel = false; var wildTarget = 0; var wildfirePot = 0; //potencies var potencies = getPotencies(type); var combo_potencies = all_combo_potencies[type]; //dots var dot_potencies = {}; var dot_base = all_dot_base[type]; var weaponskills = all_weaponskills[type]; //buffs var buffs = all_buffs[type]; //role actions var role_all = role_actions[type]; var role_taken = {}; for (var i = 0; i < role_all.length; i++) { role_taken[role_all[i]] = 0; } //timers var timers = all_timers[type]; //prescan //temp making it an array to pass by reference yay javascript activePet = [0]; preScreen('Machinist', response.events, buffs, timers, activePet); activePet = activePet[0]; for (var e in response.events) { var event = response.events[e]; //only events of self pets or targetted on self if (event.sourceID != result.player.ID) { if (result.player.pets.indexOf(event.sourceID) == -1 && event.type != "applybuff") { continue; } } getBasicData(event, result.fight); var potency = 0; if (event.type == "damage" && event.amount != 0) { //player damage if (event.dmgType == 64 || event.dmgType == 1) { if (event.name == "Flamethrower") heatChange = 20; //dots potency = dot_potencies[event.name]; event.tooltip = "DoT: " + event.name; } else { potency = potencies[event.name]; //action specific if (buffs['Heat'].stacks >= 50 && event.name == "Cooldown") potency = combo_potencies[event.name]; else if (hasBuff("Cleaner Shot", buffs) && (event.name == "Clean Shot" || event.name == "Heated Clean Shot")) potency = combo_potencies[event.name]; else if (hasBuff("Enhanced Slug Shot", buffs) && (event.name == "Slug Shot" || event.name == "Heated Slug Shot")) potency = combo_potencies[event.name]; event.tooltip = event.name + ": " + potency + "<br/>"; potency = applyBuffs(potency, event, buffs); if (event.targetID == wildTarget && event.sourceID == result.player.ID) { dot_potencies["Wildfire"] += potency * .25; } } if (potency == undefined) potency = 0; } //update timers var ellapsed = event.fightTime - prevTime; updateTimers(timers, buffs, ellapsed, event); if (!timers['Overheated'].isActive()) { buffs['Heat'].addStacks(heatChange); heatChange = 0; if (removeBarrel) { buffs['Heat'].setStacks(0); buffs['Gauss Barrel'].active = false; removeBarrel = false; } if (buffs['Heat'].stacks >= 100) { timers['Overheated'].restart(); removeBarrel = true; //mark barrel for removal } } if (event.type == "cast") { //id match shouldn't be needed bt being safe if (role_all.indexOf(event.name) != -1 && event.sourceID == result.player.ID) { role_taken[event.name]++; } switch (event.name) { case "Reload": buffs['Ammunition'].setStacks(3); break; case "Quick Reload": buffs['Ammunition'].addStacks(1) break; case "Barrel Stabilizer": buffs['Heat'].setStacks(50); break; case "Hot Shot": case "Split Shot": case "Slug Shot": case "Spread Shot": case "Clean Shot": case "Heated Split Shot": case "Heated Slug Shot": case "Heated Clean Shot": if (!buffs['Ammunition'].active && buffs['Gauss Barrel'].active) heatChange = 5; break; case "Cooldown": heatChange = -25; break; case "Gauss Barrel": buffs[event.name].applybuff(); gauss = true; break; case "Remove Barrel": buffs['Gauss Barrel'].active = false; gauss = false; break; case 'Wildfire': wildTarget = event.targetID; dot_potencies[event.name] = 0; break; } if (dot_base.hasOwnProperty(event.name)) { dot_potencies[event.name] = applyBuffs(dot_base[event.name], event, buffs); } if (event.name == "Bishop Autoturret" || event.name == "Rook Autoturret") activePet = petLookup[event.name]; } //BUFF APPLICATION updateBuffs(buffs, timers, event, result); //class specifics if (event.type == "applybuff") { if (event.name == "Flamethrower") heatChange = 20; } var extra = []; updateExtras(extra, event, buffs, type); event.extra = extra; event.potency = potency; prevTime = event.fightTime; result.events[e] = event; if (result.totals.hasOwnProperty(event.sourceID)) { result.totals[event.sourceID].amount += event.amount; result.totals[event.sourceID].potency += potency; } result.totals[result.player.ID].time += ellapsed; if (result.totals.hasOwnProperty(activePet)) result.totals[activePet].time += ellapsed; } //role actions used for (var r in role_taken) { if (role_taken[r] == 0) delete role_taken[r]; } result.role_actions = Object.keys(role_taken); return result; } function parseSummoner(response, result) { var type = result.player.type; //console.log("Parsing SMN"); var prevTime = 0; var prevPet = 0; var activePet = 0; var petLookup = {}; for (var p in result.player.pets) { petLookup[result.fight.team[result.player.pets[p]]] = result.player.pets[p]; } result.totals[result.player.ID] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.ID], 'id': result.player.ID, 'time': 0 //result.fight.duration, } for (var p in result.player.pets) { result.totals[result.player.pets[p]] = { 'amount': 0, 'potency': 0, 'name': result.fight.team[result.player.pets[p]], 'id': result.player.pets[p], 'time': 0 //result.fight.duration, } } //trackers var heatChange = 0; var removeBarrel = false; var wildTarget = 0; var wildfirePot = 0; //potencies var potencies = getPotencies(type); //dots var dot_potencies = {}; var dot_base = all_dot_base[type]; //buffs var buffs = all_buffs[type]; //role actions var role_all = role_actions[type]; var role_taken = {}; for (var i = 0; i < role_all.length; i++) { role_taken[role_all[i]] = 0; } //timers var timers = all_timers[type]; //prescan //temp making it an array to pass by reference yay javascript activePet = [0]; preScreen(type, response.events, buffs, timers, activePet); activePet = activePet[0]; for (var e in response.events) { var event = response.events[e]; if (event.sourceID != result.player.ID && event.sourceID != undefined) { if ((result.player.pets.indexOf(event.sourceID) == -1 && event.type != "applybuff" && event.type != "death")) { continue; } } getBasicData(event, result.fight); var potency = 0; if (event.type == "damage" && event.amount != 0) { if (event.dmgType == 1 || event.dmgType == 64) { //dots potency = dot_potencies[event.name]; event.tooltip = "DoT: " + event.name; } else { potency = potencies[event.name]; if (event.name == 'Attack') { if (event.sourceID == result.player.ID) potency = 110; else potency = 80; } event.tooltip = event.name + ": " + potency + "<br/>"; potency = applyBuffs(potency, event, buffs); } if (potency == undefined) potency = 0; } //update timers var ellapsed = event.fightTime - prevTime; updateTimers(timers, buffs, ellapsed, event); if (!timers['Summon Bahamut'].isActive() && prevPet != 0) { activePet = prevPet; prevPet = 0; } if (event.type == "cast") { //id match shouldn't be needed bt being safe if (role_all.indexOf(event.name) != -1 && event.sourceID == result.player.ID) { role_taken[event.name]++; } switch (event.name) { case "Tri-disaster": dot_potencies["Bio III"] = applyBuffs(dot_base["Bio III"], event, buffs); dot_potencies["Miasma III"] = applyBuffs(dot_base["Miasma III"], event, buffs); break; case "Summon Bahamut": prevPet = activePet; activePet = petLookup["Demi-Bahamut"]; timers['Summon Bahamut'].restart(); break; } if (dot_base.hasOwnProperty(event.name)) { dot_potencies[event.name] = applyBuffs(dot_base[event.name], event, buffs); } } //BUFF APPLICATION updateBuffs(buffs, timers, event, result, activePet); if(event.type == 'applybuff'){ if (dot_base.hasOwnProperty(event.name) && !dot_potencies.hasOwnProperty(event.name)) { dot_potencies[event.name] = applyBuffs(dot_base[event.name], event, buffs); } } var extra = []; updateExtras(extra, event, buffs, type); event.extra = extra; event.potency = potency; prevTime = event.fightTime; result.events[e] = event; if (result.totals.hasOwnProperty(event.sourceID)) { result.totals[event.sourceID].amount += event.amount; result.totals[event.sourceID].potency += potency; } result.totals[result.player.ID].time += ellapsed; if (result.totals.hasOwnProperty(activePet)) result.totals[activePet].time += ellapsed; } //role actions used for (var r in role_taken) { if (role_taken[r] == 0) delete role_taken[r]; } result.role_actions = Object.keys(role_taken); return result; }
e636557bfb11ea715bf46c614ea0eae8abe5aa02
[ "JavaScript", "Python", "Markdown" ]
7
JavaScript
wynforth/fflogpps
56ca9cbf7d743fb2b655d396753447a045e53676
b7ac46befd0d97f2b44237cde8a02bfe1db719fd
refs/heads/master
<repo_name>frankzheng43/rumor<file_sep>/length.py import pandas as pd import seaborn as sns import matplotlib.pyplot as plt import jieba rumor_file = r"F:\rumor\collect\20181121rumor_check.xlsx" xls_reader = pd.ExcelFile(rumor_file) df_rumor = pd.read_excel(xls_reader, converters={'stkcd':str}).fillna(value={"article_rumor": ""}) # 一些查看表格的命令 df_rumor.head() list(df_rumor) # 获取列的名称 df_rumor["article_rumor"].head() type(df_rumor) df_rumor.at[0, "article_rumor"] # 清理文本 def txt_cleaner(txt): txt = txt.replace("\n", "").replace("\t", "").replace("\r", "").replace( u'\xa0', u' ').replace(u'\u3000', u' ').replace(" ", "") return txt df_rumor["article_rumor"] = df_rumor["article_rumor"].apply(txt_cleaner) # 获取传闻的长度 df_rumor["length"] = df_rumor["article_rumor"].apply(len) # 用结巴分词将文本分词 jieba.load_userdict(r"F:\Pyproject\learnpy\测试词库\不确定性词.txt") def tokenize_to_word(sentence): """ 将句子进行分词 """ word_token = [] for i in jieba.cut(sentence): word_token.append(i) return word_token df_rumor["jieba"] = df_rumor["article_rumor"].apply(tokenize_to_word) # 获取不确定程度 with open(r"F:\Pyproject\learnpy\测试词库\不确定性词.txt", "r", encoding="utf8") as f: uncerlist = [i.strip() for i in f.readlines()] def uncercount(string): count = 0 for x in string: if x in uncerlist: count = count + 1 return count df_rumor["has_uncer"] = df_rumor["jieba"].apply(uncercount) # 对股票代码进行特殊的处理 df_rumor["stkcd"] = df_rumor["stkcd"].astype("str") df_rumor["stkcd"] = "'"+df_rumor["stkcd"] # 保存导出 df_rumor.to_csv("file_name2.csv", encoding="utf-16", sep='\t') # 一些作图 sns.distplot(df_rumor["length"]) sns.distplot(df_rumor["has_uncer"]) <file_sep>/extractpdf.r Sys.setlocale("LC_CTYPE", "chinese") library(stringr) library(rio) library(readtext) dest <- "F:/rumor/fullpdf/" myfiles_s <- list.files(path = paste0(dest, "pdf/"), pattern = "pdf|PDF") lapply( myfiles_s, function(i) system(paste( "c:/qpdf/bin/qpdf.exe", "--decrypt", paste0('"', dest, "pdf/", i, '"'), paste0('"', dest, "dec/", i, '"') )) ) myfiles_s_dec <- list.files(path = paste0(dest, "dec/"), pattern = "pdf|PDF") stkcd <- lapply( myfiles_s_dec, function(i) str_extract(i, regex("(((001|000|600)[0-9]{3})|60[0-9]{4})")) ) date <- lapply( myfiles_s_dec, function(i) str_extract(i, regex("[0-9]{4}[-]{0,1}[0-9]{2}[-]{0,1}[0-9]{2}")) ) date <- str_replace_all(date, "-", "") # temp < - do.call(rbind.data.frame, date) newname <- paste0(dest, "dec/", date, "_", stkcd, ".pdf") myfiles_dec <- list.files(path = paste0(dest, "dec/"), pattern = "pdf|PDF", full.names = TRUE) file.rename(myfiles_dec, newname) myfiles_dec_new <- list.files(path = paste0(dest, "dec/"), pattern = "pdf|PDF", full.names = TRUE) lapply( myfiles_dec_new, function(i) system(paste( "C:/xpdf/bin64/pdftotext.exe", "-enc UTF-8", paste0('"', i, '"') ), wait = FALSE ) ) txtfile <- list.files(path = paste0(dest, "dec/"), pattern = "txt", full.names = TRUE) b <- readtext(file = txtfile, encoding = "utf-8") b$date <- substr(b$doc_id, 1, 8) b$stkcd <- substr(b$doc_id, 10, 15) b$stkcd <- paste0("'", b$stkcd) b$text <- str_replace_all(b$text, "[\n\f\\s]", "") b$text <- str_replace_all(b$text, ",", "ï¼<U+008C>") b$summary_size <- str_length(b$text) export(x = b, file = "lookatme.csv", fwrite = FALSE, row.names = FALSE, quote = TRUE) <file_sep>/论文大纲及todo.md # 论文大纲 ## 绪论 ### 制度背景 1. 强制性澄清公告 2. 传闻的定义 ## 文献综述 ### 传闻的分类 ### 传闻的研究 ### 不确定性的研究 ## 理论分析与假设提出 1. H1:不确定性的增加促使传闻发生 H1a:宏观层面不确定性的增加促使传闻的发生 H1b:公司层面不确定性的增加促使传闻的发生 H1c:行业层面不确定性的增加初始传闻的发生 2. H2:传闻的产生对股价产生正向的冲击 H2a:传闻类型是并购时,传闻对股价的正向冲击最大 H2b:传闻描述越详尽时,传闻对股价的正向冲击越大 H3c:传闻。。。 ## 实证设计 ### 变量选取 #### 宏观不确定性 1. PEU 2. 其他:Bloom N,. The Impact of Uncertainty Shocks[J]. Econometrica, 2009, 77(3): 623–685. #### 传闻 #### 不确定性 #### 控制变量 ### PSM配对过程 ## 结论 ### 描述性统计 1. PEU时间变化趋势 ![](https://i.loli.net/2018/11/30/5c00ec390dee5.jpg) 2. 传闻描述性统计 3. ROA_sd描述性统计 4. 年份的分布 ![](https://i.loli.net/2018/12/08/5c0bb584018e1.jpg) 5. 相关系数 ![](https://i.loli.net/2018/12/08/5c0bb5c02be20.jpg) ### 主回归 ### 横截面差异 ### 稳健性检验 ## 附录
7a6ff2ed444c2177b057ad499314a38165944054
[ "Markdown", "Python", "R" ]
3
Python
frankzheng43/rumor
88d3ca1bd030f45f61f4c1cb351ba19bd2b787cb
fe3a2b50d69bae73700b287b4ea95c52997ec962
refs/heads/master
<file_sep>""" CP1404/CP5632 Practical Data file -> lists program """ FILENAME = "subject_data.txt" def main(): class_lists = get_data() display_subject_details(class_lists) def display_subject_details(class_lists): """Format and display the subject details.""" for i in range(0, len(class_lists)): print("{} is taught by {:12} and has {:>3} students".format(class_lists[i][0], class_lists[i][1], class_lists[i][2])) def get_data(): """Read data from file and return class information in a list of lists""" class_lists = [] input_file = open(FILENAME) for line in input_file: line = line.strip() # Remove the \n parts = line.split(',') # Separate the data into its parts parts[2] = int(parts[2]) # Make the number an integer (ignore PyCharm's warning) class_lists.append(parts) input_file.close() return class_lists main() <file_sep>numbers = [] for i in range(5): number = int(input("Enter Number: ")) numbers.append(number) print("The first number is " + str(numbers[0])) print("The last number is " + str(numbers[-1])) print("The smallest number is " + str(min(numbers))) print("The biggest number is " + str(max(numbers))) print("The average of all numbers is " + str(sum(numbers) / len(numbers))) usernames = ['jimbo', 'giltson98', 'derekf', 'WhatSup', 'NicolEye', 'swei45', 'BaseInterpreterInterface', 'BaseStdIn', 'Command', 'ExecState', 'InteractiveConsole', 'InterpreterInterface', 'StartServer', 'bob'] user_input = input("Enter your username: ") if user_input in usernames: print("Access Granted") else: print("Access Denied!") <file_sep>numbers = [3, 1, 4, 1, 5, 9, 2] # numbers[0] prints the first index so it would print 3 print(numbers[0]) # numbers[-1] prints the last index so it would print 2 print(numbers[-1]) # numbers[3] prints the fourth index so it prints 1 print(numbers[3]) # numbers[:-1] prints the entire list but stops before the last index print(numbers[:-1]) # numbers[3:4] prints the list starting at the 4th index and stopping before the 5th. (1) print(numbers[3:4]) # 5 in numbers would return True if 5 in numbers: print("5 in numbers is True") # 7 in numbers would return False if 7 not in numbers: print("7 in numbers is False") # "3" in numbers would return False if "3" not in numbers: print("'3' in numbers is False") # numbers + [6, 5, 3] would append these values to the end of the list numbers += [6, 5, 3] print(numbers) # 1. Change first element of numbers to the string "ten" numbers[0] = "ten" print(numbers) # 2. change last element of numbers to 1 numbers[-1] = 1 print(numbers) # 3. get all the elements from numbers except the first two elements = numbers[2:] print(elements) # 4. check if 9 is an element of numbers if 9 in numbers: print("True") else: print("False") <file_sep># On line 1 I saw a 12 # The smallest I could've seen was a 5 and the highest a 20 # On line 2 I saw a 5 # The smallest I could've seen was a 3 and the highest a 9 # A 4 could not be produced by the line 2 code # On line 3 I saw 4.474481... # The smallest I could've seen was a 2.5 and the highest a 5.5 import random number = random.randint(1, 100) print(number) <file_sep>HEX_COLOURS = {"Cyan1": "#00ffff", "BlueViolet": "#8a2be2", "DarkSeaGreen": "#8fbc8f", "FireBrick2": "#ee2c2c", "GhostWhite": "#f8f8ff", "GreenYellow": "#adff2f", "HotPink": "#ff69b4", "Lavender": "#e6e6fa", "NavyBlue": "#000080", "Wheat1": "#ffe7ba"} for key in HEX_COLOURS: print("{:>12s} is {}".format(key, HEX_COLOURS[key])) colour = input("Enter name of colour: ") while colour != "": if colour in HEX_COLOURS: print(colour + " is " + HEX_COLOURS[colour]) else: print("Invalid colour name.") colour = input("Enter name of colour: ") <file_sep>import random QUICK_PICK_COUNT = 6 QUICK_PICK_MIN = 1 QUICK_PICK_MAX = 45 def main(): pick_total = int(input("How many quick picks would you like? ")) for i in range(pick_total): picks = get_picks() display_picks(picks) def display_picks(picks): print("{:>2} {:>2} {:>2} {:>2} {:>2} {:>2}".format(picks[0], picks[1], picks[2], picks[3], picks[4], picks[5])) def get_picks(): """Gather random integers and return them in a list""" picks = [] for j in range(QUICK_PICK_COUNT): pick = random.randrange(QUICK_PICK_MIN, QUICK_PICK_MAX + 1) if pick not in picks: picks.append(pick) else: while pick in picks: pick = random.randrange(QUICK_PICK_MIN, QUICK_PICK_MAX + 1) picks.append(pick) picks.sort() return picks main() <file_sep>user_details = {} email = input("Enter your email: ") while email != "" and "@" in email: name_portion, domain = email.split("@") if "." in name_portion: name = name_portion.split(".") full_name = " ".join(name) prompt = input("Is your name {}? Y/N".format(full_name)) if prompt.upper() == "N": full_name = input("Enter your name: ") user_details[email] = full_name else: full_name = name_portion prompt = input("Is your name {}? Y/N".format(full_name)) if prompt.upper() == "N": full_name = input("Enter your name: ") user_details[email] = full_name email = input("Enter your email: ") for key in user_details: print("{} - ({})".format(user_details[key], key)) <file_sep>def main(): password = get_password() print_asterisks(password) def print_asterisks(password): print("Password Saved:", end=' ') for i in range(len(password)): print("*", end='') def get_password(): password = input("Enter Password: ") while len(password) < 5: print("Password cannot be shorter than 5 characters.") password = input("Re-enter password: ") return password main() <file_sep>from prac_08.silverservicetaxi import SilverServiceTaxi def main(): ss_taxi = SilverServiceTaxi("Hummer", 100, 2) ss_taxi.drive(18) fare = ss_taxi.get_fare() print(fare) print(ss_taxi) main() <file_sep>string = input("Enter sequence of words: ") words = string.split(' ') amount_of_every_word = {} for word in words: word_count = amount_of_every_word.get(word, 0) amount_of_every_word[word] = word_count + 1 longest_word = max(len(word) for word in words) words = list(amount_of_every_word.keys()) words.sort() for word in words: print("{:{}} : {}".format(word, longest_word, amount_of_every_word[word])) <file_sep>from prac_08.taxi import Taxi from prac_08.silverservicetaxi import SilverServiceTaxi TAXI_MENU = """Please select a Taxi to ride in: 1. Prius 2. Limo 3. Hummer ... """ VALID_SELECTIONS = ["PRIUS", "LIMO", "HUMMER"] def main(): current_taxi = None taxis = [Taxi("Prius", 100), SilverServiceTaxi("Limo", 100, 2), SilverServiceTaxi("Hummer", 100, 4)] main()<file_sep>from prac_08.unreliablecar import UnreliableCar def main(): dodgy_car = UnreliableCar("Commodore SV6", 150, 85) print(dodgy_car) dodgy_car.drive(30) print(dodgy_car) dodgy_car.drive(30) print(dodgy_car) dodgy_car.drive(30) print(dodgy_car) dodgy_car.drive(30) print(dodgy_car) main()
d2be05add43c3b7593df6c92730244c7bb99cc75
[ "Python" ]
12
Python
bradanderson1404/practicals
703e9ff5b560611c6c94ad54bb740869b61055e1
0ee44356daad6f60705146b91d18cb6f90ef89e1
refs/heads/master
<repo_name>svlugovoy/hw07<file_sep>/src/app/components/home/home.component.ts import {Component, OnInit} from '@angular/core'; import {User} from '../models/user'; import {Timestamp} from 'rxjs/operators/timestamp'; @Component({ selector: 'app-home', templateUrl: './home.component.html', styleUrls: ['./home.component.css'] }) export class HomeComponent implements OnInit { users: User[] = []; testPipe: string[] = ['One', 'Two']; testDate = Date.now(); numbers: number[] = [1, 2, 3, 33]; constructor() { } ngOnInit() { this.users.push({name: 'Evgeniy', age: 29}); this.users.push({name: 'Sergey', age: 19}); this.users.push({name: 'Olexandra', age: 22}); this.users.push({name: 'Petr', age: 40}); this.users.push({name: 'Victor', age: 31}); setTimeout( () => { this.testPipe.push('Three'); this.numbers.push(1000); console.log(this.testPipe); }, 9000); } } <file_sep>/src/app/pipes/my-date.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; import {Timestamp} from 'rxjs/operators/timestamp'; @Pipe({ name: 'myDate' }) export class MyDatePipe implements PipeTransform { transform(value: number, locale: string, options: object) { return new Date(value).toLocaleString(locale, options); } } <file_sep>/src/app/app.module.ts import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppComponent } from './app.component'; import { NavbarComponent } from './components/navbar/navbar.component'; import { HomeComponent } from './components/home/home.component'; import { MySlicePipe } from './pipes/my-slice.pipe'; import { MyJoinPipe } from './pipes/my-join.pipe'; import { BgDirective } from './directives/bg.directive'; import { MyIfDirective } from './directives/my-if.directive'; import { MyLoopDirective } from './directives/my-loop.directive'; import { MyDatePipe } from './pipes/my-date.pipe'; import { MySumPipe } from './pipes/my-sum.pipe'; import { MyStyleDirective } from './directives/my-style.directive'; import { MyClassDirective } from './directives/my-class.directive'; @NgModule({ declarations: [ AppComponent, NavbarComponent, HomeComponent, MySlicePipe, MyJoinPipe, BgDirective, MyIfDirective, MyLoopDirective, MyDatePipe, MySumPipe, MyStyleDirective, MyClassDirective ], imports: [ BrowserModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { } <file_sep>/src/app/pipes/my-sum.pipe.ts import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'mySum', pure: false }) export class MySumPipe implements PipeTransform { transform(array: number[]) { return array.reduce((a, b) => a + b ); } } <file_sep>/src/app/directives/bg.directive.ts import {Directive, ElementRef, HostListener, Input, Renderer2} from '@angular/core'; @Directive({ selector: '[appBg]', host: { '(click)': 'onClick()' } }) export class BgDirective { @Input('appBg') bgColor; @Input() fontSize; constructor( private element: ElementRef, private renderer: Renderer2 ) { // this.element.nativeElement.style.background = 'lime'; } onClick() { this.renderer.setStyle(this.element.nativeElement, 'background', this.bgColor); this.renderer.setStyle(this.element.nativeElement, 'font-size', this.fontSize); } @HostListener('mouseover') onHover() { this.renderer.setStyle(this.element.nativeElement, 'background', 'red'); } } <file_sep>/src/app/directives/my-style.directive.ts import {Directive, ElementRef, Input, OnInit, Renderer2} from '@angular/core'; @Directive({ selector: '[appMyStyle]' }) export class MyStyleDirective implements OnInit { @Input('appMyStyle') style; constructor( private element: ElementRef, private renderer: Renderer2 ) { } ngOnInit(): void { for (let key in this.style ) { this.renderer.setStyle(this.element.nativeElement, key, this.style[key]); } } } <file_sep>/src/app/directives/my-loop.directive.ts import {Directive, Input, OnChanges, TemplateRef, ViewContainerRef} from '@angular/core'; @Directive({ selector: '[appMyLoop]' }) export class MyLoopDirective implements OnChanges { @Input() appMyLoopOf: Array<any>; constructor( private templateRef: TemplateRef<any>, private viewContainer: ViewContainerRef ) { } ngOnChanges() { console.log(this.appMyLoopOf); for (let item of this.appMyLoopOf) { this.viewContainer.createEmbeddedView(this.templateRef, { $implicit: item, index: this.appMyLoopOf.indexOf(item), custom: '###' }); } } } <file_sep>/src/app/directives/my-class.directive.ts import {Directive, ElementRef, Input, OnInit, Renderer2, TemplateRef, ViewContainerRef} from '@angular/core'; @Directive({ selector: '[appMyClass]' }) export class MyClassDirective implements OnInit { @Input('appMyClass') clazz: string; constructor( private element: ElementRef, private renderer: Renderer2 ) { } ngOnInit(): void { this.renderer.addClass(this.element.nativeElement, this.clazz); } }
b7ec9786fb1c9609337253a113a0e30b366f84ae
[ "TypeScript" ]
8
TypeScript
svlugovoy/hw07
54baedb19bf088b290c628c29704f70768aa4c64
33b38387eac7ae1c47ef884481ad5940268afd55
refs/heads/master
<repo_name>bachbouch/ml.js<file_sep>/README.md # ml.js Machine Learning in Javascript ES6 <file_sep>/src/LinearRegression.js const LinearRegression = function() { //Theta*X + B = Y, let LEARNING_RATE; const MAX_ITERATIONS = 10000000; const computeError = (thetas, x, y) => { let totalError = 0; const len = x.length; for (let i = 0; i < len; i++) { let t = (y[i] - activation(thetas, x[i])); totalError += t * t; if (totalError > 1) return totalError; } return totalError / (2 * len); }; const activation = (thetas, X) => { let len = thetas.length, sum = 0; for (let i = 0; i < len; i++) { // This is much faster than mapreduce or Vector.dot sum += thetas[i] * X[i]; } return sum; }; let len, len_, x_len, gradients = []; const stepGradient = (X, Y, thetas, learningRate = LEARNING_RATE) => { // console.time('test'); // console.timeEnd('test'); // var g_counter = 0; // var len, // len_, // x_len, // gradients = []; // len = X.length; // len_ = 1 / len; // x_len = X[0].length; len = X.length, len_ = 1 / len, x_len = X[0].length; for (let i = 0; i < x_len; i++) { gradients[i] = 0; // this is faster than Array.prototype.fill } for (let i = 0; i < len; i++) { let temp = activation(thetas, X[i]) - Y[i], x_i = X[i]; // this made the algorithm 10x faster for (let j = 0; j < x_len; j++) { gradients[j] += temp * x_i[j]; } } for (let j = 0; j < x_len; j++) { thetas[j] -= (learningRate * gradients[j]); } // console.log(thetas) // return thetas; }; return { converge: (X, Y, learningRate = LEARNING_RATE, maxIterations = MAX_ITERATIONS) => { let thetas = []; for (let i = 0; i < X[0].length + 1; i++) thetas.push(Math.random()) let count = 0, len = X.length; for (let i = 0; i < len; i++) X[i].push(1); if (learningRate == LEARNING_RATE) LEARNING_RATE = 1 / Math.pow(10, (len * X[0].length).toString().split("").length - 1); else LEARNING_RATE = learningRate; let count_check = Math.max(10, Math.pow(10, (len * X[0].length).toString().split("").length - 3)); let error = 0; while (count < maxIterations) { count++; stepGradient(X, Y, thetas); if (count % count_check == 0) { error = computeError(thetas, X, Y); if (error < 0.01) return thetas.map(x => x.toFixed(4)); if (error > 9999999) return console.log("INFINITY ERROR ") } } return console.log("Maximized the number of iterations without conversion"); } }; }; export default LinearRegression();<file_sep>/python/lr.py # from sklearn import datasets # from sklearn.model_selection import cross_val_predict # from sklearn import linear_model # import matplotlib.pyplot as plt # lr = linear_model.LinearRegression() # boston = datasets.load_boston() # print(len(boston.data)) # y = boston.target # # cross_val_predict returns an array of the same size as `y` where each entry # # is a prediction obtained by cross validation: # predicted = cross_val_predict(lr, boston.data, y, cv=10) # fig, ax = plt.subplots() # ax.scatter(y, predicted) # ax.plot([y.min(), y.max()], [y.min(), y.max()], 'k--', lw=4) # ax.set_xlabel('Measured') # ax.set_ylabel('Predicted') # plt.show() print(__doc__) import random # Code source: <NAME> # License: BSD 3 clause import matplotlib.pyplot as plt import numpy as np from sklearn import datasets, linear_model # Load the diabetes dataset diabetes = datasets.load_diabetes() X = [] num_features = 100 num_samples = 100000 thetas = [] x = [] y = [] for i in range(0,num_features+1): thetas.append(round( random.random() * 10 , 4)) for i in range(0,num_samples): _x = [] for k in range(0,num_features): _x.append(round( random.random() * 10 , 4)) x.append(_x) _y = 0 for j in range(0,num_features): _y += thetas[j] * _x[j] _y += thetas[num_features] y.append(_y) # Use only one feature diabetes_X = diabetes.data[:, np.newaxis, 2] # Split the data into training/testing sets diabetes_X_train = diabetes_X[:-20] diabetes_X_test = diabetes_X[-20:] # Split the targets into training/testing sets diabetes_y_train = diabetes.target[:-20] diabetes_y_test = diabetes.target[-20:] # Create linear regression object regr = linear_model.LinearRegression() # Train the model using the training sets # regr.fit(diabetes_X_train, diabetes_y_train) regr.fit(x, y) print('THETAS: \n', thetas) # The coefficients print('Coefficients: \n', regr.coef_) # # The mean squared error # print("Mean squared error: %.2f" # % np.mean((regr.predict(diabetes_X_test) - diabetes_y_test) ** 2)) # # Explained variance score: 1 is perfect prediction # print('Variance score: %.2f' % regr.score(diabetes_X_test, diabetes_y_test)) # # Plot outputs # plt.scatter(diabetes_X_test, diabetes_y_test, color='black') # plt.plot(diabetes_X_test, regr.predict(diabetes_X_test), color='blue', # linewidth=3) # plt.xticks(()) # plt.yticks(()) plt.show()<file_sep>/src/Array.js Array.prototype.zeros = function() { }<file_sep>/src/index.js import logisticRegression from './LogisticRegression'; import LinearRegression from './LinearRegression'; let num_features = 10, num_samples = 10000, thetas = [], //[2.289, 11.788, 23.2, 1.4, 45.4, 3.5, 65.2, 12.5, 6, 12.4, 7.3], x = [], y = []; for (let i = 0; i < num_features + 1; i++) { thetas.push((Math.random() * 10).toFixed(4) - 0); } console.log(thetas); for (let i = 0; i < num_samples; i += 1) { let _x = []; for (let k = 0; k < num_features; k++) _x.push(Math.random().toFixed(4) - 0); x.push(_x); let _y = 0; for (let j = 0; j < num_features; j++) { _y += thetas[j] * _x[j]; } _y += thetas[num_features]; y.push(_y); } console.time('tester'); console.log(LinearRegression.converge(x, y)); console.timeEnd('tester');<file_sep>/src/LogisticRegression.js const LogisticRegression = function() { return { fit: () => { console.log("fitting"); } }; } export default LogisticRegression();<file_sep>/src/LinearRegression.1.js const LinearRegression = function() { //Theta*X + B = Y, const LEARNING_RATE = 0.0001; const MAX_ITERATIONS = 10000000; const computeError = (b, m, x, y) => { let totalError = 0; const len = x.length; for (let i = 0; i < len; i++) { //change this with reduce totalError += Math.pow(y[i] - (m * x[i] + b), 2); } return totalError / (2 * len); }; function stepGradient(X, Y, a_current, b_current, learningRate = LEARNING_RATE) { let b_gradient = 0, a_gradient = 0, len = X.length, new_b, new_a; for (let i = 0; i < len; i++) { let temp = (a_current * X[i] + b_current) - Y[i]; b_gradient += (1 / len) * temp; a_gradient += (1 / len) * temp * X[i]; } b_current -= (learningRate * b_gradient); a_current -= (learningRate * a_gradient); return [b_current, a_current] } return { converge: (X, Y, maxIterations = MAX_ITERATIONS) => { let a; let b; let converged_a = Math.random(); let converged_b = Math.random(); let count = 0; do { count++; if (count > maxIterations) return console.log("Maximized the number of iterations without conversion") a = converged_a; b = converged_b; let converged = stepGradient(X, Y, a, b); converged_a = converged[1]; converged_b = converged[0]; } while (Math.abs(a - converged_a) > 0.00000000000001 && Math.abs(b - converged_b) > 0.00000000000001) let roundedA = parseFloat(a.toFixed(6)) let roundedB = parseFloat(b.toFixed(6)) return [roundedA, roundedB]; } }; }; export default LinearRegression();
6045629c64d35e6ae7ab0de22c4ea0a0f4655a7b
[ "Markdown", "Python", "JavaScript" ]
7
Markdown
bachbouch/ml.js
5455ca83f4896d115ed280659a15fbb2b9e6647c
45684b95b66dd8607cacd7b34ea6021c406667f5
refs/heads/master
<repo_name>Harikrishnan-github/blockchain-hackernoon<file_sep>/hash-example.py from hashlib import sha256 import argparse import time # Lets decide that the hash of some integer x multiplied by another y must end in 0. # So hash(x * y) = ac23dc...0. # setup the arguments for the command line parser = argparse.ArgumentParser() parser.add_argument('-x', '--first_number', type=int, default=5, help='number of 0 in hash end') parser.add_argument('-n', '--number_of_zero', type=int, default=5, help='number of 0 in hash end') args = parser.parse_args() x = args.first_number # default to 5 y = 0 n = args.number_of_zero # default to 5 ending_zeros = '0' * n # n zeros at the end of the hash start_time = time.time() # start time of the program while sha256(f'{x*y}'.encode()).hexdigest()[-n:] != ending_zeros: print(sha256(f'{x*y}'.encode()).hexdigest()[-n:]) y += 1 print(sha256(f'{x*y}'.encode()).hexdigest()[-n:]) # calculate the running time total_seconds = time.time() - start_time print(f'total seconds are {total_seconds}') m, s = divmod(total_seconds, 60) h, m = divmod(m, 60) # Tried 840258 numbers and took 0:00:07 to be correct when n=5 # Tried 5199280 numbers and took 0:00:42 to be correct when n=6 # Tried 73102419 numbers and took 0:10:31 to be correct when n=7 print("Tried %d numbers and took %d:%02d:%02d to be correct" % (y, h, m, s)) <file_sep>/requirements.txt Flask==0.12.2 Flask-Script==2.0.6 requests==2.18.4 pandas==0.21.0 <file_sep>/README.md This is code for the tutorial at https://hackernoon.com/learn-blockchains-by-building-one-117428612f46 with my revisions. install python 3 if needed: ``$ brew install python3`, test with: `$ python3` ``` $ virtualenv -p python3 venv $ source venv/bin/activate $ pip3 install -r requirements.txt ``` `python3 hash-example.py -x 5 -n 5` this example shows how Proof of Work algorithm works with a simple hashing algorithm. Default x=5 and n=5 if no arguments are provided.
44620815bd1548c78c49e0b0b065262f4b195176
[ "Markdown", "Python", "Text" ]
3
Python
Harikrishnan-github/blockchain-hackernoon
31b390505361a6cca9308a52801dddddfb48bcb5
630d41ad7c7f5de9993e30387716575a40be8869
refs/heads/master
<file_sep>import sortRoutes from '../src/sort-routes' test('simple', () => { const result = sortRoutes([ { path: '/', }, { path: '/:user' }, { path: '/post/bar' }, { path: '/post/:id' }, { path: '/post/foo' } ]) expect(result).toMatchSnapshot() }) <file_sep>import path from 'path' import sortRoutes from './sort-routes' export interface Route { path: string file: string name: string children?: Route[] } function groupRoutes( routes: Set<Route>, rootRoutes: Set<Route> = routes ): Set<Route> { for (const route of routes) { const childRoutes: Set<Route> = new Set() for (const _route of routes) { if (_route.path.startsWith(`${route.path}/`)) { routes.delete(_route) rootRoutes.delete(_route) childRoutes.add(_route) } } if (childRoutes.size > 0) { route.children = sortRoutes( [...groupRoutes(childRoutes, rootRoutes)].map(childRoute => { let childPath = childRoute.path.slice(route.path.length + 1) if (childPath === 'index') { childPath = '' } return { ...childRoute, path: childPath } }) ).map(sorted => sorted.route) } } return new Set(sortRoutes([...routes]).map(({ route }) => ({ ...route, path: route.path.replace(/\/index$/, '') }))) } export function toRoutes( files: Array<string> | Set<string>, { cwd = '' } = {} ): Route[] { // Sort files in ASC so that we handle shorter path first files = [...files].sort() const routes: Set<Route> = new Set() for (let filePath of files) { filePath = slash(filePath) const routePath = filePathToRoutePath(filePath) routes.add({ path: routePath, file: slash(path.join(cwd, filePath)), name: getRouteName(filePath) }) } const groupedRoutes = groupRoutes(routes) return [...groupedRoutes] } function filePathToRoutePath(filePath: string) { const routePath = `/${filePath}` .replace(/\.[a-z]+$/i, '') // Remove extension .replace(/\[([^\]]+)\]/g, ':$1') if (routePath === '/index') { return '/' } return routePath } function getRouteName(filePath: string) { return filePath.replace(/[^a-z0-9_-]/gi, '-') } /** * Convert windows back slash to forward slash */ function slash(filepath: string) { return filepath.replace(/\\/g, '/') } <file_sep>interface Route { path: string } const paramRe = /^:(.+)/ const ROOT_POINTS = 100 // `/` path goes top const SEGMENT_POINTS = 4 const STATIC_POINTS = 3 const DYNAMIC_POINTS = 2 const SPLAT_PENALTY = 1 const isRootSegment = (segment: string) => segment === '' const isDynamic = (segment: string) => paramRe.test(segment) const isSplat = (segment: string) => segment === '*' function segmentize(uri: string) { return ( uri // strip starting/ending slashes .replace(/\/{2,}/, '/') .replace(/(^\/|\/$)/g, '') .split('/') ) } function rankRoute<T extends Route>(route: T, index: number) { let score = segmentize(route.path).reduce((score, segment) => { score += SEGMENT_POINTS if (isRootSegment(segment)) score += ROOT_POINTS else if (isDynamic(segment)) score += DYNAMIC_POINTS else if (isSplat(segment)) score -= SEGMENT_POINTS + SPLAT_PENALTY else score += STATIC_POINTS return score }, 0) return { route, score, index } } function sortRoutes<T extends Route>(routes: T[]) { return routes .map(rankRoute) .sort((a, b) => a.score < b.score ? 1 : a.score > b.score ? -1 : a.index - b.index ) } export default sortRoutes <file_sep>import { toRoutes } from '../src' test('simple', () => { expect(toRoutes(['index.vue', 'about.vue', 'user/index.vue'])).toMatchSnapshot() }) test('directory', () => { expect( toRoutes(['index.vue', 'foo/bar.vue', 'foo/baz.vue']) ).toMatchSnapshot() }) test('nesting routes', () => { expect(toRoutes(['index.vue', 'foo.vue', 'foo/bar.vue', 'foo/baz.vue'])) }) test('complex example', () => { expect( toRoutes([ '[user].vue', '[user]/index.vue', '[user]/profile.vue', 'explore.vue', 'explore/tweets.vue', 'post/[post].vue', 'post/[post]/index.vue', 'post/[post]/[comment].vue', 'post/[post]/[comment]/index.vue', 'post/[post]/[comment]/likes.vue', 'post/[post]/[comment]/replies.vue' ]) ).toMatchSnapshot() })
cb43d878e30fbd481a9ea22a85f3611834d844d8
[ "TypeScript" ]
4
TypeScript
ansidev/routes-generator
3847e4e61149172a1cde83ff63afb8475e22ebc6
af328b3d10a5f4ff381316261bfbcbe2b2674a35
refs/heads/master
<repo_name>jiger96/quiz2<file_sep>/quiz2/src/quiz2/testing.java package quiz2; import static org.junit.Assert.*; import org.junit.Test; public class testing { @Test public void testIP(){ car testCar = new car (35000, 0, 60, 10); double expectedValue = 9618.79; double result = testCar.ip(); assertEquals(expectedValue, result, 0.01); } public void testPay() { car testCar2 = new car (35000, 0 ,60, 10); double expected = 743.65; double result2 = testCar2.payment(); assertEquals(expected,result2, 0.01); } }
15e3af74e4649eada870b65c27cac2dafdecb4e4
[ "Java" ]
1
Java
jiger96/quiz2
6a32995955f6b3f86e8e6b1f37844dcf97eba9c2
524fe72aabe109f28cf98ca8cbb6e32af124b264
refs/heads/master
<repo_name>egonzalez49/Spot-Me<file_sep>/src/artist.js const electron = require('electron') const path = require('path') const BrowserWindow = electron.remote.BrowserWindow const name = document.getElementById('name') const followers = document.getElementById('label') const image = document.getElementById('photo') const genreList = document.getElementById('genres') const topTracks = document.getElementById('topTracks') const myModal = document.getElementById('myModal') const playlists = document.getElementById('playlists') const axios = require('axios') const superagent = require('superagent'); const express = require('express') const app = express(); const ipc = electron.ipcRenderer var {Howl, Howler} = require('howler') var Promise = require('promise'); var SpotifyWebApi = require('spotify-web-api-node'); var soundPlayer; var soundURLs = []; var soundURIs = []; var playlist = []; var playlistIDs = []; //Authentication Variables var redirect_uri = 'http://localhost:5000/callback'; var client_id = 'b413dae4cf6943de8286e1a9d8c4eb65'; var client_secret = '0584097fe6c54f6eae92e3f063c624a8'; var state = 'spotify_auth_state'; var scopes = ['user-top-read'], redirectUri = redirect_uri, clientId = client_id, clientSecret = client_secret, state = state; //API Wrapper Instantiation var spotifyApi = new SpotifyWebApi({ clientId: clientId, clientSecret: clientSecret, redirectUri: redirectUri }); //Authentication Code var code = null; //Artist ID var id = null; window.addEventListener("load", function() { ipc.send("get-artist-id"); //console.log("DONE!"); }); ipc.on('artist-id', function(event, arg1, arg2) { console.log(arg1); code = arg1; id = arg2; ipc.send("error-log", id); ipc.send("error-log", code); spotifyApi.setAccessToken(code); spotifyApi.getArtist(id).then( function(data) { console.log('Artist', data.body); var artist = data.body; name.innerHTML = "" + artist.name; followers.innerHTML = followers.innerHTML + " " + artist.followers.total.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");; image.src = artist.images[2].url; var genres = artist.genres; genres.forEach(function(genre) { var node = document.createTextNode("" + genre); node.innerHTML = id + console.log(genre); genreList.insertAdjacentHTML('afterbegin', '<p class="badge badge-pill badge-success">' + genre + '</p>'); }); }, function(err) { console.error(err); } ); spotifyApi.getArtistTopTracks(id, 'US').then( function(data) { console.log('Top Tracks', data.body); var tracks = data.body.tracks; while (topTracks.firstChild) { topTracks.removeChild(topTracks.firstChild); } tracks.forEach(function(song) { //console.log(song.name); var node = document.createElement("li"); node.className = "mt-3"; var textnode = document.createTextNode("" + song.name); var imgnode = document.createElement("img"); imgnode.src = song.album.images[2].url; imgnode.setAttribute("id", "photo2"); var playnode = document.createElement("img"); playnode.src = "../assets/images/play.png"; playnode.setAttribute("id", "play"); node.appendChild(imgnode); node.appendChild(textnode); node.appendChild(playnode); var savenode = document.createElement("img"); savenode.src = "../assets/images/save.png"; savenode.setAttribute("id", "play"); savenode.onclick = function () { openModal(Array.prototype.indexOf.call(topTracks.childNodes, savenode.parentNode)); }; node.appendChild(savenode); playnode.onclick = function() { playPreview(Array.prototype.indexOf.call(topTracks.childNodes, playnode.parentNode)); }; topTracks.appendChild(node); //imgnode.onclick = function() { playPreview(topTracks.children.indexOf(imgnode.parentNode)); }; soundURLs.push(song.preview_url); soundURIs.push(song.uri); //console.log(imgnode.parentNode); soundPlayer = new Howl({ src: [soundURLs[0]], format: ['mp3'], autoplay: false, volume: 0.3 }); //songIDs.push(song.id); }); }, function(err) { console.error(err); } ); var user; // Get the authenticated user spotifyApi.getMe() .then(function(data) { console.log('Some information about the authenticated user', data.body); user = data.body.display_name; // Get a user's playlists spotifyApi.getUserPlaylists() .then(function(data) { console.log('Retrieved playlists', data.body); var x = data.body.items; //console.log("X:" + x.name); x.forEach(function(pl) { //console.log(pl.name); //console.log(user); if(pl.owner.display_name === user) { playlist.push(pl.name); playlistIDs.push(pl.id); } }); while (playlists.firstChild) { playlists.removeChild(playlists.firstChild); } playlist.forEach(function(name) { var node = document.createElement("li"); var div = document.createElement("div"); div.className = "form-check"; node.className = "mt-3"; var textnode = document.createTextNode("" + name); var radio = document.createElement("input"); radio.className = "form-check-input"; radio.type = "radio"; radio.name = "action"; div.appendChild(radio); div.appendChild(textnode); node.appendChild(div); playlists.appendChild(node); }); //console.log("Playlists: " + playlist); },function(err) { console.log('Something went wrong!', err); }); }, function(err) { console.log('Something went wrong!', err); }); }); var uri; function openModal(value) { uri = soundURIs[value]; // while (playlists.firstChild) { // playlists.removeChild(playlists.firstChild); // } // console.log("RAN1"); // // playlist.forEach(function(name) { // var node = document.createElement("li"); // var div = document.createElement("div"); // div.className = "form-check"; // node.className = "mt-3"; // var textnode = document.createTextNode("" + name); // var radio = document.createElement("input"); // radio.className = "form-check-input"; // radio.type = "radio"; // radio.name = "action"; // div.appendChild(radio); // div.appendChild(textnode); // node.appendChild(div); // playlists.appendChild(node); // }); console.log("RAN2"); $('#alert_placeholder').html('<div id = "alert_placeholder"></div>'); $("#myModal").modal(); } const save = document.getElementById("saveBtn"); save.addEventListener('click', function (event) { var playlistNumber = null; for (var i = 0; i < playlists.childNodes.length; i++) { if (playlists.childNodes[i].childNodes[0].childNodes[0].checked) { playlistNumber = i; break; } } if (playlistNumber === null) { $('#alert_placeholder').html('<div class="alert alert-danger alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>' + '<strong>Error!</strong> Please select a playlist.</div>'); } else { var id = playlistIDs[playlistNumber]; // Add tracks to a playlist spotifyApi.addTracksToPlaylist(id, [uri]) .then(function(data) { console.log('Added tracks to playlist!'); $("#myModal").modal("toggle"); $('#alert_placeholder2').html('<div class="alert alert-success alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>' + '<strong>Success!</strong> Song added to playlist.</div>'); }, function(err) { console.log('Something went wrong!', err); }); console.log(playlistNumber); } }); var previousValue; var timeoutID; function playPreview(value) { // soundPlayer = new Audio(soundURLs[value]); // soundPlayer.play(); if (!soundPlayer.playing()) { previousValue = value; soundPlayer = new Howl({ src: [soundURLs[value]], format: ['mp3'], autoplay: false, volume: 0.3, }); soundPlayer.play(); timeoutID = setTimeout(previewEnd, 30000, value); var node = topTracks.childNodes[value]; node.childNodes[2].src = "../assets/images/pause.png"; console.log("Playing"); } else { soundPlayer.stop(); clearTimeout(timeoutID); console.log("Stopped"); soundPlayer = new Howl({ src: [soundURLs[value]], format: ['mp3'], autoplay: false, volume: 0.3, }); var node = topTracks.childNodes[previousValue]; node.childNodes[2].src = "../assets/images/play.png"; if (previousValue !== value) { soundPlayer.play(); timeoutID = setTimeout(previewEnd, 30000, value); var node = topTracks.childNodes[value]; node.childNodes[2].src = "../assets/images/pause.png"; previousValue = value; } } //soundPlayer.on("end", previewEnd(value)); } function previewEnd(value) { console.log("Ended"); var node = topTracks.childNodes[value]; node.childNodes[2].src = "../assets/images/play.png"; } <file_sep>/src/index.js const electron = require('electron') const path = require('path') const BrowserWindow = electron.remote.BrowserWindow const login = document.getElementById('login') const artistList = document.getElementById('artistlist') artistList.style.visibility = 'hidden'; const songList = document.getElementById('songlist') songList.style.visibility = 'hidden'; const recommended = document.getElementById('recArtists') const recDiv = document.getElementById('recommended') recDiv.style.visibility = 'hidden'; const playlists = document.getElementById('playlists') const axios = require('axios') const superagent = require('superagent'); const express = require('express') const app = express(); const ipc = electron.ipcRenderer var recURLs = []; var soundPlayer; var recNames = []; var soundURIs = []; var playlist = []; var playlistIDs = []; var Promise = require('promise'); var SpotifyWebApi = require('spotify-web-api-node'); var {Howl, Howler} = require('howler') //Authentication Variables var redirect_uri = 'http://localhost:5000/callback'; var client_id = 'b413dae4cf6943de8286e1a9d8c4eb65'; var client_secret = '0584097fe6c54f6eae92e3f063c624a8'; var state = 'spotify_auth_state'; var scopes = ['user-top-read', 'playlist-read-private', 'playlist-modify-public', 'playlist-modify-private', 'user-read-private'], redirectUri = redirect_uri, clientId = client_id, clientSecret = client_secret, state = state; //API Wrapper Instantiation var spotifyApi = new SpotifyWebApi({ clientId: clientId, clientSecret: clientSecret, redirectUri: redirectUri }); //Authentication URL var authorizeURL = spotifyApi.createAuthorizeURL(scopes, state); //Authentication Window var authWindow = new BrowserWindow({ width: 800, height: 600, show: false, 'node-integration': false, 'web-security': false }); var authUrl = authorizeURL; //When the Authentication Token Expires var tokenExpirationEpoch; //Authentication Code var code = null; var artistIDs = []; var songIDs = []; //Receives the Callback when Spotify Authentication Completed app.get('/callback', function(req, res) { code = req.query.code || null; var statereturned = req.query.state || null; spotifyApi.authorizationCodeGrant(code).then( function(data) { // Set the Access Token and Refresh Token spotifyApi.setAccessToken(data.body['access_token']); ipc.send("save-code", data.body['access_token']); spotifyApi.setRefreshToken(data.body['refresh_token']); // Save the amount of seconds until the access token expired // tokenExpirationEpoch = // new Date().getTime() / 1000 + data.body['expires_in']; // console.log( // 'Retrieved token. It expires in ' + // Math.floor(tokenExpirationEpoch - new Date().getTime() / 1000) + // ' seconds!' // ); spotifyApi.getMyTopArtists({ limit: 10, time_range: 'short_term' }).then( function(data) { //console.log('Top Artists', data.body.items); var topArtists = data.body.items; artistList.style.visibility = 'visible'; while (artists.firstChild) { artists.removeChild(artists.firstChild); } topArtists.forEach(function(artist) { var node = document.createElement("li"); node.className = "media mt-3"; //node.setAttribute("id", "list-item"); var textnode = document.createTextNode("" + artist.name); // var span = document.createElement("span"); // span.appendChild(document.createTextNode("" + artist.popularity)); // span.className = "badge badge-primary badge-pill"; // textnode.insertAdjacentElement("beforeend",span); var div = document.createElement("div"); div.className = "media-body"; div.appendChild(textnode); // var span = document.createElement("span"); // span.className = "badge badge-primary badge-pill"; // span.setAttribute("id", "popular"); // span.innerHTML = "" + artist.popularity; // textnode.appendChild(span); textnode.onclick = "viewArtist(i)"; var imgnode = document.createElement("img"); imgnode.className = " align-self-center mr-3"; imgnode.setAttribute("id", "resize"); imgnode.src = artist.images[2].url; node.appendChild(imgnode); node.appendChild(div); node.onclick = function() { viewArtist(Array.prototype.indexOf.call(artists.childNodes, node)); }; artists.appendChild(node); artistIDs.push(artist.id); }); var seed_artists = []; for (var i = 0; i < 4; i++) { seed_artists.push(artistIDs[i]); } console.log("Seed Artists: " + seed_artists); spotifyApi.getRecommendations({ limit: 10, seed_artists }).then( function(data) { //console.log('Recommended Artists', data.body); var recArtists = data.body.tracks; recDiv.style.visibility = 'visible'; while (recommended.firstChild) { recommended.removeChild(recommended.firstChild); } recArtists.forEach(function(song) { var node = document.createElement("li"); node.className = "mt-3"; var textnode = document.createTextNode("" + song.name); var imgnode = document.createElement("img"); imgnode.src = song.album.images[2].url; imgnode.setAttribute("id", "photo2"); imgnode.className = "mr-3"; var playnode = document.createElement("img"); playnode.src = "../assets/images/play.png"; playnode.setAttribute("id", "play"); node.appendChild(imgnode); node.appendChild(textnode); node.appendChild(playnode); var savenode = document.createElement("img"); savenode.src = "../assets/images/save.png"; savenode.setAttribute("id", "play"); savenode.onclick = function () { openModal(Array.prototype.indexOf.call(recommended.childNodes, savenode.parentNode)); }; node.appendChild(savenode); playnode.onclick = function() { playPreview(Array.prototype.indexOf.call(recommended.childNodes, playnode.parentNode)); }; //node.onclick = function() { viewArtist(Array.prototype.indexOf.call(songs.childNodes, node)); }; recommended.appendChild(node); soundURIs.push(song.uri); recURLs.push({name: song.name, preview: song.preview_url}); if(song.preview_url === null) { spotifyApi.getTrack(song.id, { market:'US' }).then( function(data) { //console.log('Track', data.body); for (var i = 0; i < recURLs.length; i++) { if (data.body.name === recURLs[i].name) { recURLs[i].preview = data.body.preview_url; //console.log("Inserting: " + data.body.name + " at " + i); break; } } }, function(err) { console.error(err); } ); } else { //recURLs.push(song.preview_url); } //console.log("URLs: " + recNames); soundPlayer = new Howl({ src: [recURLs[0].preview], format: ['mp3'], autoplay: false, volume: 0.3 }); }); }, function(err) { console.error(err); } ); }, function(err) { console.error(err); } ); spotifyApi.getMyTopTracks({ limit: 10, time_range: 'short_term' }).then( function(data) { //console.log('Top Tracks', data.body.items); var topSongs = data.body.items; songList.style.visibility = 'visible'; topSongs.forEach(function(song) { var node = document.createElement("li"); //node.setAttribute("class", "list-group-item"); node.className = "media mt-3"; var textnode = document.createTextNode("" + song.name); var div = document.createElement("div"); div.className = "media-body"; div.appendChild(textnode); var imgnode = document.createElement("img"); imgnode.className = "align-self-center mr-3"; imgnode.setAttribute("id", "resize"); imgnode.src = song.album.images[2].url; node.appendChild(imgnode); node.appendChild(div); //node.onclick = function() { viewArtist(Array.prototype.indexOf.call(songs.childNodes, node)); }; songs.appendChild(node); songIDs.push(song.id); }); }, function(err) { console.error(err); } ); var user; // Get the authenticated user spotifyApi.getMe() .then(function(data) { //console.log('Some information about the authenticated user', data.body); user = data.body.display_name; // Get a user's playlists spotifyApi.getUserPlaylists() .then(function(data) { //console.log('Retrieved playlists', data.body); var x = data.body.items; //console.log("X:" + x.name); x.forEach(function(pl) { //console.log(pl.name); //console.log(user); if(pl.owner.display_name === user) { playlist.push(pl.name); playlistIDs.push(pl.id); } }); while (playlists.firstChild) { playlists.removeChild(playlists.firstChild); } playlist.forEach(function(name) { var node = document.createElement("li"); var div = document.createElement("div"); div.className = "form-check"; node.className = "mt-3"; var textnode = document.createTextNode("" + name); var radio = document.createElement("input"); radio.className = "form-check-input"; radio.type = "radio"; radio.name = "action"; div.appendChild(radio); div.appendChild(textnode); node.appendChild(div); playlists.appendChild(node); }); console.log("Playlists: " + playlist); },function(err) { console.log('Something went wrong!', err); }); }, function(err) { console.log('Something went wrong!', err); }); }, function(err) { console.log( 'Something went wrong when retrieving the access token!', err.message ); } ); // // // }, // function(err) { // console.log( // 'Something went wrong when retrieving the access token!', // err.message // ); // } // ); authWindow.close(); }); var uri; function openModal(value) { uri = soundURIs[value]; // while (playlists.firstChild) { // playlists.removeChild(playlists.firstChild); // } // console.log("RAN1"); // // playlist.forEach(function(name) { // var node = document.createElement("li"); // var div = document.createElement("div"); // div.className = "form-check"; // node.className = "mt-3"; // var textnode = document.createTextNode("" + name); // var radio = document.createElement("input"); // radio.className = "form-check-input"; // radio.type = "radio"; // radio.name = "action"; // div.appendChild(radio); // div.appendChild(textnode); // node.appendChild(div); // playlists.appendChild(node); // }); console.log("RAN2"); $('#alert_placeholder').html('<div id = "alert_placeholder"></div>'); $("#myModal").modal(); } const save = document.getElementById("saveBtn"); save.addEventListener('click', function (event) { var playlistNumber = null; for (var i = 0; i < playlists.childNodes.length; i++) { if (playlists.childNodes[i].childNodes[0].childNodes[0].checked) { playlistNumber = i; break; } } if (playlistNumber === null) { $('#alert_placeholder').html('<div class="alert alert-danger alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>' + '<strong>Error!</strong> Please select a playlist.</div>'); } else { var id = playlistIDs[playlistNumber]; // Add tracks to a playlist spotifyApi.addTracksToPlaylist(id, [uri]) .then(function(data) { console.log('Added tracks to playlist!'); $("#myModal").modal("toggle"); $('#alert_placeholder2').html('<div class="alert alert-success alert-dismissible"><a href="#" class="close" data-dismiss="alert" aria-label="close">&times;</a>' + '<strong>Success!</strong> Song added to playlist.</div>'); }, function(err) { console.log('Something went wrong!', err); }); //console.log(playlistNumber); } }); var previousValue; var timeoutID; function playPreview(value) { // soundPlayer = new Audio(soundURLs[value]); // soundPlayer.play(); //var timeoutID; if (!soundPlayer.playing()) { previousValue = value; soundPlayer = new Howl({ src: [recURLs[value].preview], format: ['mp3'], autoplay: false, volume: 0.3, }); soundPlayer.play(); timeoutID = setTimeout(previewEnd, 30000, value); var node = recommended.childNodes[value]; node.childNodes[2].src = "../assets/images/pause.png"; console.log("Playing"); } else { soundPlayer.stop(); clearTimeout(timeoutID); console.log("Stopped"); soundPlayer = new Howl({ src: [recURLs[value].preview], format: ['mp3'], autoplay: false, volume: 0.3, }); var node = recommended.childNodes[previousValue]; node.childNodes[2].src = "../assets/images/play.png"; if (previousValue !== value) { soundPlayer.play(); timeoutID = setTimeout(previewEnd, 30000, value); var node = recommended.childNodes[value]; node.childNodes[2].src = "../assets/images/pause.png"; previousValue = value; } } //soundPlayer.on("end", previewEnd(value)); } function previewEnd(value) { console.log("Ended"); var node = recommended.childNodes[value]; node.childNodes[2].src = "../assets/images/play.png"; } // Continually print out the time left until the token expires.. var numberOfTimesUpdated = 0; console.log('Listening on 5000'); app.listen(5000); login.addEventListener('click', function (event) { login.style.display = 'none'; authWindow.loadURL(authUrl); authWindow.show(); event.preventDefault(); }) var toggle_artist = 0; //Short-term = 0, Medium-term = 1, Long-term = 2 var toggle_song = 0; function toggleArtist() { if (toggle_artist === 0) { toggle_artist = 1; document.getElementById('artistToggle').src = "../assets/images/mediumterm.png" document.getElementById('artistTerm').innerHTML = "Medium Term"; } else if (toggle_artist === 1) { toggle_artist = 2; document.getElementById('artistToggle').src = "../assets/images/longterm.png" document.getElementById('artistTerm').innerHTML = "Long Term"; } else { toggle_artist = 0; document.getElementById('artistToggle').src = "../assets/images/shortterm.png" document.getElementById('artistTerm').innerHTML = "Short Term"; } newFilter(toggle_artist, toggle_song); } function toggleSong() { if (toggle_song === 0) { toggle_song = 1; document.getElementById('songToggle').src = "../assets/images/mediumterm.png" document.getElementById('songTerm').innerHTML = "Medium Term"; } else if (toggle_song === 1) { toggle_song = 2; document.getElementById('songToggle').src = "../assets/images/longterm.png" document.getElementById('songTerm').innerHTML = "Long Term"; } else { toggle_song = 0; document.getElementById('songToggle').src = "../assets/images/shortterm.png" document.getElementById('songTerm').innerHTML = "Short Term"; } newFilter(toggle_artist, toggle_song); } function newFilter(valueArtist, valueSong) { var artistRange, songRange; if (valueArtist === 0) { artistRange = "short_term"; } else if (valueArtist === 1) { artistRange = "medium_term"; } else { artistRange = "long_term"; } if (valueSong === 0) { songRange = "short_term"; } else if (valueSong === 1) { songRange = "medium_term"; } else { songRange = "long_term"; } artistIDs = []; songIDs = []; spotifyApi.getMyTopArtists({ limit: 10, time_range: artistRange }).then( function(data) { console.log('Top Artists', data.body.items); var topArtists = data.body.items; artistList.style.visibility = 'visible'; while (artists.firstChild) { artists.removeChild(artists.firstChild); } topArtists.forEach(function(artist) { var node = document.createElement("li"); node.className = "media mt-3"; //node.setAttribute("id", "list-item"); var textnode = document.createTextNode("" + artist.name); var div = document.createElement("div"); div.className = "media-body"; div.appendChild(textnode); textnode.onclick = "viewArtist(i)"; var imgnode = document.createElement("img"); imgnode.className = " align-self-center mr-3"; imgnode.setAttribute("id", "resize"); imgnode.src = artist.images[2].url; node.appendChild(imgnode); node.appendChild(div); node.onclick = function() { viewArtist(Array.prototype.indexOf.call(artists.childNodes, node)); }; artists.appendChild(node); artistIDs.push(artist.id); }); }, function(err) { console.error(err); } ); spotifyApi.getMyTopTracks({ limit: 10, time_range: songRange }).then( function(data) { console.log('Top Tracks', data.body.items); var topSongs = data.body.items; songList.style.visibility = 'visible'; while (songs.firstChild) { songs.removeChild(songs.firstChild); } topSongs.forEach(function(song) { var node = document.createElement("li"); //node.setAttribute("class", "list-group-item"); node.className = "media mt-3"; var textnode = document.createTextNode("" + song.name); var div = document.createElement("div"); div.className = "media-body"; div.appendChild(textnode); var imgnode = document.createElement("img"); imgnode.className = "align-self-center mr-3"; imgnode.setAttribute("id", "resize"); imgnode.src = song.album.images[2].url; node.appendChild(imgnode); node.appendChild(div); //node.onclick = function() { viewArtist(Array.prototype.indexOf.call(songs.childNodes, node)); }; songs.appendChild(node); songIDs.push(song.id); }); }, function(err) { console.error(err); } ); } function viewArtist(value) { console.log(value); ipc.send("save-artist", code, artistIDs[value]); ipc.send("artist-window"); //Artist Window // var artistWindow = new BrowserWindow({ // width: 800, // height: 600, // show: false, // 'node-integration': false, // 'web-security': false // }); // // artistWindow.webContents.openDevTools(); // // artistWindow.loadFile("src/artist.html"); // artistWindow.show(); // // artistWindow.on('closed', () => { // artistWindow = null // }) }
b73583f7109f8f5ac78882713fb92ed048013bba
[ "JavaScript" ]
2
JavaScript
egonzalez49/Spot-Me
e55d81d2b7a581fa1fedd4e634b285adfe4a7a50
20416dd4dab66ee6de3a7d0978f6ab8c10fe39b0
refs/heads/master
<repo_name>henotia/CordovaEmbedded<file_sep>/README.md https://henotia.github.io/IonicEmbedded-1/ 참고<file_sep>/src/main/java/com/cyber_i/ionicembedded/IonicActivity.java package com.cyber_i.ionicembedded; import android.os.Bundle; import org.apache.cordova.CordovaActivity; import org.apache.cordova.CordovaWebView; import org.apache.cordova.CordovaWebViewImpl; import org.apache.cordova.engine.SystemWebView; import org.apache.cordova.engine.SystemWebViewEngine; public class IonicActivity extends CordovaActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.cordova_layout); super.init(); loadUrl(launchUrl); } @Override protected CordovaWebView makeWebView() { SystemWebView appView = (SystemWebView) findViewById(R.id.cordovaWebView); return new CordovaWebViewImpl(new SystemWebViewEngine(appView)); } @Override protected void createViews() { // do nothings } } <file_sep>/src/main/java/com/cyber_i/ionicembedded/IonicFragment.java package com.cyber_i.ionicembedded; import android.app.Fragment; import android.content.Intent; import android.content.res.Configuration; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.RelativeLayout; import org.apache.cordova.*; import org.json.JSONException; import java.util.ArrayList; public class IonicFragment extends Fragment { private CordovaWebView appView; protected CordovaPreferences preferences; protected String launchUrl; protected ArrayList<PluginEntry> pluginEntries; protected CordovaInterfaceImpl cordovaInterface; public static IonicFragment newInstance() { return new IonicFragment(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_layout, container, false); cordovaInterface = new CordovaInterfaceImpl(getActivity()); if (savedInstanceState != null) { cordovaInterface.restoreInstanceState(savedInstanceState); } loadConfig(); // system webview 구현 appView = makeWebView(); createViews(rootView); if (!appView.isInitialized()) { appView.init(cordovaInterface, pluginEntries, preferences); } cordovaInterface.onCordovaInit(appView.getPluginManager()); appView.loadUrl(launchUrl); return rootView; } private void createViews(View rootView) { // Cordova SystemWebView에 대한 Layout Parameter 설정 RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams( RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT); appView.getView().setLayoutParams(params); // rootView에 SystemWebView 추가 ((RelativeLayout) rootView).addView(appView.getView()); } private CordovaWebView makeWebView() { return new CordovaWebViewImpl(makeWebViewEngine()); } private CordovaWebViewEngine makeWebViewEngine() { return CordovaWebViewImpl.createEngine(getActivity(), preferences); } private void loadConfig() { ConfigXmlParser parser = new ConfigXmlParser(); parser.parse(getActivity()); preferences = parser.getPreferences(); preferences.setPreferencesBundle(getActivity().getIntent().getExtras()); pluginEntries = parser.getPluginEntries(); launchUrl = parser.getLaunchUrl(); } // Plugin 통신을 위한 추가 부분 @Override public void startActivityForResult(Intent intent, int requestCode) { cordovaInterface.setActivityResultRequestCode(requestCode); super.startActivityForResult(intent, requestCode); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); cordovaInterface.onActivityResult(requestCode, resultCode, data); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { try { cordovaInterface.onRequestPermissionResult(requestCode, permissions, grantResults); } catch (JSONException e) { e.printStackTrace(); } } public void onSaveInstanceState(Bundle outState) { cordovaInterface.onSaveInstanceState(outState); super.onSaveInstanceState(outState); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); if (appView == null) return; PluginManager pm = appView.getPluginManager(); if (pm != null) { pm.onConfigurationChanged(newConfig); } } }
113cb06a8a843d1bb34b12df7cc2f0831ea70a98
[ "Markdown", "Java" ]
3
Markdown
henotia/CordovaEmbedded
9305261bfe94d301e55e1aa548b8282b25a0cde3
719922274e1f929ddb53f2c86394c321b369d25e
refs/heads/master
<file_sep>'use strict'; const fs = require('fs'); const version = process.env.npm_package_version ? process.env.npm_package_version : process.argv[2]; if (!version) { throw "No version defined"; } let today = (new Date()).toISOString().split('T')[0]; fs.readFile('CHANGELOG.md', 'utf8', function (err, data) { if (err) { throw err; } if (!fs.existsSync('./out')) { fs.mkdirSync('./out'); } var body = data.match(/## \[Unreleased\]\s+(.*?)\s*## \[\d+/s); fs.writeFile('./out/RELEASE.md', body[1], 'utf8', function (err) { if (err) { throw err; } }); let textVersion = version.match(/\d+\.\d+\.\d+/) ? "v" + version : version fs.writeFile('./out/version.txt', textVersion, 'utf8', function (err) { if (err) { throw err; } }); var result = data.replace(/## \[Unreleased\]/, `## [Unreleased]\n\n## [${version}] - ${today}`); result = result.replace( /(\[Unreleased\]\: )(https\:\/\/github.com\/.*?\/compare\/)(v\d+\.\d+\.\d+)(\.{3})(HEAD)/, "$1$2v" + version + "$4$5\n[" + version + "]: $2$3$4v" + version ); fs.writeFile('CHANGELOG.md', result, 'utf8', function (err) { if (err) { throw err; } }); });<file_sep>import { workspace, TextEditor, Range, Position, TextDocument } from "vscode"; import Config from "./config"; /** * Provides helper function to types */ export default class TypeUtil { /** * Holds the current instance * * @type {TypeUtil} */ private static _instance: TypeUtil; /** * Returns the instance for this util * * @returns {TypeUtil} */ public static get instance(): TypeUtil { return this._instance || (this._instance = new this()); } /** * Resolve a type string that may contain union types * * @param {string} types * @param {string} head * @returns {string} */ public getResolvedTypeHints(types:string, head:string = null): string { let union:string[] = types.split("|"); for (let index = 0; index < union.length; index++) { union[index] = this.getFullyQualifiedType(union[index], head); union[index] = this.getFormattedTypeByName(union[index]); } return union.join("|"); } /** * Get the full qualified class namespace for a type * we'll need to access the document * * @param {string} type * @param {string} head * @returns {string} */ public getFullyQualifiedType(type:string, head:string):string { if (!Config.instance.get('qualifyClassNames')) { return type; } let useEx = new RegExp("use\\s+([^ ]*?)((?:\\s+as\\s+))?("+type+");", 'gm'); let full = useEx.exec(head); if (full != null && full[3] == type) { if (full[1].charAt(0) != '\\') { full[1] = '\\' + full[1]; } if (full[2] != null) { return full[1]; } return full[1] + type; } return type; } /** * Returns the user configuration based name for the given type * * @param {string} name */ public getFormattedTypeByName(name:string) { switch (name) { case 'bool': case 'boolean': if (!Config.instance.get('useShortNames')) { return 'boolean'; } return 'bool'; case 'int': case 'integer': if (!Config.instance.get('useShortNames')) { return 'integer'; } return 'int'; default: return name; } } /** * Take the value and parse and try to infer its type * * @param {string} value * @returns {string} */ public getTypeFromValue(value:string):string { let result:Array<string>; // Check for bool if (value.match(/^\s*(false|true)\s*$/i) !== null || value.match(/^\s*\!/i) !== null) { return this.getFormattedTypeByName('bool'); } // Check for int if (value.match(/^\s*([\d-]+)\s*$/) !== null) { return this.getFormattedTypeByName('int'); } // Check for float if (value.match(/^\s*([\d.-]+)\s*$/) !== null) { return 'float'; } // Check for string if (value.match(/^\s*(["'])/) !== null || value.match(/^\s*<<</) !== null) { return 'string'; } // Check for array if (value.match(/^\s*(array\(|\[)/) !== null) { return 'array'; } return '[type]'; } }
cf90dff76e7ce41e012b6b20fd6bb866f24683fe
[ "JavaScript", "TypeScript" ]
2
JavaScript
neild3r/vscode-php-docblocker-test
19646837f5dd1be5a77f85e06a61fa4e725b8a66
d8d383ca5b6100d2c3390c837e1a53eca10972f7
refs/heads/master
<file_sep>package com.app; import org.testng.annotations.Test; public class Test2 { @Test public void b1() { System.out.println("hi i amaaa a11p package"); } }
9a9aa916c0eb9eb8d69752c167cda915141635f9
[ "Java" ]
1
Java
Meghanachuttu/qwe12
fede9bda2099f18ea4b3b67bd3ac7b9a9585e330
96e691c9de9921f2b6add8f8824855747936146d
refs/heads/master
<file_sep>package shewchenko.com.github.homebookkeeping.months; /** * Created by shew on 01.08.15. */ public class Calculation { //JanActivity result = new JanActivity(); public float getToPay(float a, float b, float c){ return (a-b)*c; } public float getDifference(float current, float prevoius){ return current-prevoius; } } <file_sep>package shewchenko.com.github.homebookkeeping.months; import android.app.Activity; import android.os.Bundle; import shewchenko.com.github.homebookkeeping.R; /** * Created by shew on 31.07.15. */ public class MayActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.may); } }
75115837e53ffa415b346d97b03d84acc427c0e4
[ "Java" ]
2
Java
Shewchenko/HomeBookkeeping
a70f5a171a7345243652a744052111e226cd8567
720517a860e42846f0bdef9ee5fc09f08b56ee15
refs/heads/master
<repo_name>Decoux/Books<file_sep>/views/addBookVue.php <?php include("template/header.php") ?> <section class="container"> <form class="mt-5 d-flex flex-column col-md-6 mx-auto" action="addBook.php" method="post" enctype="multipart/form-data"> <p class="text-center">Ajouter un livre</p> <label for="title">Titre : </label> <?php if(isset($errors['title'])){ ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['title']; } ?></div> <input class="form-control" name="title" type="text" placeholder="Titre du livre"> <label for="author">Auteur : </label> <?php if(isset($errors['author'])){ ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['author']; } ?></div> <input class="form-control" name="author" type="text" placeholder="Auteur du livre"> <label for="categorie">Categorie : </label> <?php if(isset($errors['categorie'])){ ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['categorie']; } ?></div> <select class="form-control" name="categorie" id=""> <option type="text" selected disabled>Categorie</option> <option value="Science-fiction">Science-fiction</option> <option value="Thriller">Thriller</option> <option value="Horror">Horreur</option> <option value="Roman">Roman</option> </select> <label for="picture">Couverture : </label> <input name="picture" type="file" value="Couverture"> <label for="date">Date du livre : </label> <?php if(isset($errors['date'])){ ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['date']; } ?></div> <input class="form-control" name="date" type="date"> <label for="resume">Résumé : </label> <?php if(isset($errors['resume'])){ ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['resume']; } ?></div> <textarea class="form-control" name="resume" id="" cols="30" rows="10"></textarea> <button class="mt-3 mb-5 btn btn-success" type="submit">Enregister</button> </form> </section> <?php include("template/footer.php") ?><file_sep>/controllers/updateBook.php <?php session_start(); // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); $bookManager = new BookManager; $book = $bookManager->getBook($_GET['id']); foreach($book as $element){ $picture = $element['picture']; $categorie = $element['categories']; } if(!empty($_POST['title']) && !empty($_POST['author']) && !empty($_POST['categorie']) && !empty($_POST['date']) && !empty($_POST['resume'])){ $newBook = new Book([ 'title' => $_POST['title'], 'author' => $_POST['author'], 'date' => $_POST['date'], 'resume' => $_POST['resume'] ]); $newPicture = new Picture([ 'picture' => $_FILES['picture']['name'], 'alt' => $_FILES['picture']['name'] ]); $newCategorie = new Categorie([ 'categorie' => $_POST['categorie'] ]); $bookManager->updateBook($newBook, $_GET['id']); $bookManager->updatePicture($newPicture, $picture); move_uploaded_file($_FILES['picture']['tmp_name'], '../assets/img/' . basename($_FILES['picture']['name'])); $bookManager->updateCategorie($newCategorie, $categorie); } include "../views/updateBookVue.php";<file_sep>/entities/Admin.php <?php declare (strict_types = 1); class Admin extends Entity{ protected $firstname, $mail, $pass, $id; /** * Get the value of firstname */ public function getFirstname() { return $this->firstname; } /** * Set the value of firstname * * @return self */ public function setFirstname($firstname) { $this->firstname = $firstname; return $this; } /** * Get the value of mail */ public function getMail() { return $this->mail; } /** * Set the value of mail * * @return self */ public function setMail($mail) { $this->mail = $mail; return $this; } /** * Get the value of pass */ public function getPass() { return $this->pass; } /** * Set the value of pass * * @return self */ public function setPass($pass) { $this->pass = $pass; return $this; } /** * Get the value of id */ public function getId() { return $this->id; } /** * Set the value of id * * @return self */ public function setId($id) { $this->id = $id; return $this; } }<file_sep>/views/booksVue.php <?php include("template/header.php") ?> <section class="container"> <div class="d-flex flex-wrap"> <?php if(!empty($books)){ ?> <?php foreach($books as $book){ ?> <a href="book.php?id=<?php echo $book['book']->getId_books(); ?>" onmouseover="flip(this)" onmouseout="reFlip(this)" class="text card col-12 col-md-4 my-5 p-3"> <div><p class="text-center"><?php echo $book['book']->getTitle();?></p></div> <span class="px-2 back card__side--back is-switched card__wrapper text-wrap text-truncate"><?php echo $book['book']->getResume(); ?></span> <div id="<?php echo $book['book']->getPicture_id() ?>" class="sizeImgCard "> <img src="../assets/img/<?php if($book['picture']->getPicture() == NULL){echo 'dark-blue-book-background.jpg'; }else{ echo $book['picture']->getPicture(); } ?>" class="sizeImg card-img-top" alt="<?php if($element instanceof Picture){ echo $element->getAlt(); } ?>"> </div> </a> <?php } ?> <?php } ?> </div> </section> <?php include("template/footer.php"); ?><file_sep>/views/usersVue.php <?php include("template/header.php") ?> <section class="container"> <div class="table-responsive table-responsive-firefox"> <table class="mt-5 table table-striped"> <thead> <tr> <th scope="col">N°</th> <th scope="col">Nom</th> <th scope="col">Prenom</th> <th scope="col">Identifiant</th> <th scope="col">Identifiant</th> </tr> </thead> <tbody> <?php $i = 1; ?> <?php foreach($users as $user){ ?> <tr> <th scope="row"><?php echo $i; ?></th> <td><?php echo $user->getName(); ?></td> <td><?php echo $user->getFirstname(); ?></td> <td class="text-danger"><?php echo $user->getIdentifiant(); ?></td> <td><a href="userDetails.php?id=<?php echo $user->getId_user(); ?>" class="btn btn-outline-info"><input class="btn" type="submit" value="Details"></a></td> </tr> <?php $i++ ?> <?php } ?> </tbody> </table> </div> </section> <?php include("template/footer.php") ?> <file_sep>/models/BookManager.php <?php class BookManager extends Manager{ public function addBook(Book $book){ $req = $this->getDb()->prepare('INSERT INTO books(title, author, date, resume, picture_id, books_categorie_id) VALUE (:title, :author, :date, :resume, :picture_id, :books_categorie_id)'); $req->bindValue(':title', $book->getTitle(), PDO::PARAM_STR); $req->bindValue(':author', $book->getAuthor(), PDO::PARAM_STR); $req->bindValue(':date', $book->getDate(), PDO::PARAM_STR); $req->bindValue(':resume', $book->getResume(), PDO::PARAM_STR); $req->bindValue(':picture_id', $book->getPicture_id(), PDO::PARAM_INT); $req->bindValue(':books_categorie_id', $book->getBooks_categorie_id(), PDO::PARAM_INT); $req->execute(); } public function getBooks(){ $g = array(); $req = $this->getDb()->query('SELECT books.id_books id_books, books.title title, books.author author, books.date date, books.resume resume, books.picture_id picture_id, books.books_categorie_id books_categorie_id, pictures.id_picture id_picture, pictures.picture picture, pictures.alt alt, categorie.id_categorie id_categorie, categorie.categorie categorie FROM books INNER JOIN pictures INNER JOIN categorie ON books.picture_id = pictures.id_picture WHERE books.books_categorie_id = categorie.id_categorie'); $books = $req->fetchAll(PDO::FETCH_ASSOC); foreach($books as $book){ $res['book'] = new Book($book); $res['picture'] = new Picture($book); $res['categories'] = new Categorie($book); $g[] = $res; // $tab1[] = $tab2; // $tab2 = []; } return $g; } public function getBook($id){ $req = $this->getDb()->prepare('SELECT books.id_books id_books, books.title title, books.author author, books.date date, books.resume resume, books.picture_id picture_id, books.books_categorie_id books_categorie_id, pictures.id_picture id_picture, pictures.picture picture, pictures.alt alt, categorie.id_categorie id_categorie, categorie.categorie categorie FROM books INNER JOIN pictures ON books.picture_id = pictures.id_picture INNER JOIN categorie ON books.books_categorie_id = categorie.id_categorie WHERE books.id_books = :id_book'); $req->bindValue(':id_book', $id); $req->execute(); $book = $req->fetch(PDO::FETCH_ASSOC); $res['book'] = new Book($book); $res['picture'] = new Picture($book); $res['categories'] = new Categorie($book); $g[] = $res; return $g; } public function deleteBook($bookId){ $req = $this->db->prepare('DELETE FROM books WHERE id_books = :id'); $req->bindValue(':id', $bookId, PDO::PARAM_INT); $req->execute(); } public function updateBook(Book $book, $id){ $req = $this->getDb()->prepare('UPDATE books SET title = :title, author = :author, resume = :resume, date = :date WHERE id_books = :id'); $req->bindValue(':title', $book->getTitle(), PDO::PARAM_STR); $req->bindValue(':author', $book->getAuthor(), PDO::PARAM_STR); $req->bindValue(':resume', $book->getResume(), PDO::PARAM_STR); $req->bindValue(':date', $book->getDate(), PDO::PARAM_STR); $req->bindValue(':id', $id, PDO::PARAM_INT); $req->execute(); } public function updatePicture(Picture $newPicture, Picture $picture) { $req = $this->getDb()->prepare('UPDATE pictures SET picture = :picture, alt = :alt WHERE id_picture = :id'); $req->bindValue(':picture', $newPicture->getPicture(), PDO::PARAM_STR); $req->bindValue(':alt', $newPicture->getAlt(), PDO::PARAM_STR); $req->bindValue(':id', $picture->getId_picture(), PDO::PARAM_INT); $req->execute(); } public function updateCategorie(Categorie $newCategorie, categorie $categorie){ $req = $this->getDb()->prepare('UPDATE categorie SET categorie = :categorie WHERE id_categorie = :id'); $req->bindValue(':categorie', $newCategorie->getCategorie(), PDO::PARAM_STR); $req->bindValue(':id', $categorie->getId_categorie(), PDO::PARAM_STR); $req->execute(); } }<file_sep>/entities/User.php <?php declare (strict_types = 1); class User extends Entity{ protected $name, $firstname, $identifiant, $id_user, $id_book_borrow; /** * Get the value of name */ public function getName() { return $this->name; } /** * Set the value of name * * @return self */ public function setName($name) { $this->name = $name; return $this; } /** * Get the value of firstname */ public function getFirstname() { return $this->firstname; } /** * Set the value of firstname * * @return self */ public function setFirstname($firstname) { $this->firstname = $firstname; return $this; } /** * Get the value of identifiant */ public function getIdentifiant() { return $this->identifiant; } /** * Set the value of identifiant * * @return self */ public function setIdentifiant($identifiant) { $this->identifiant = $identifiant; return $this; } /** * Get the value of id_user */ public function getId_user() { return $this->id_user; } /** * Set the value of id_user * * @return self */ public function setId_user($id_user) { $this->id_user = $id_user; return $this; } /** * Get the value of id_book_borrow */ public function getId_book_borrow() { return $this->id_book_borrow; } /** * Set the value of id_book_borrow * * @return self */ public function setId_book_borrow($id_book_borrow) { $this->id_book_borrow = $id_book_borrow; return $this; } }<file_sep>/controllers/deleteBook.php <?php session_start(); // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); $bookManager = new BookManager; $bookManager->deleteBook($_GET['id']); // die('ok'); header('Location: ./books.php');<file_sep>/views/indexVue.php <?php include("template/header.php") ?> <section class="container"> <form class="mt-5 px-3 py-5 border border-light d-flex flex-column col-md-6 mx-auto" action="index.php" method="post"> <p class="text-center">Formulaire de connexion</p> <label for="name">Mail : </label> <?php if(isset($errors['mail'])){ ?><div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['mail']; }?></div> <?php if(isset($errors['no-exist'])){ ?><div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['no-exist']; }?></div> <input name="mail" class="form-control" type="text" placeholder="Entrez votre Email"> <label for="name">Pass : </label> <?php if(isset($errors['pass'])){ ?><div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"><?php echo $errors['pass']; } ?></div> <input name="pass" class="form-control" type="text" placeholder="Entrez votre mot de passe"> <button type="submit" class="mt-3 btn btn-success">Se connecter</button> <a class="" href="register.php"> <input class="col-12 mt-3 btn btn-info" type="button" value="S'inscrire"> </a> </form> </section> <?php include("template/footer.php") ?><file_sep>/views/updateUserVue.php <?php include("template/header.php") ?> <section class="container"> <form class="mt-5 d-flex flex-column col-md-6 mx-auto" action="updateUser.php?id=<?php echo $_GET['id']; ?>" method="post"> <p class="text-center">Ajouter un utilisateur</p> <label for="name">Nom : </label> <?php if (isset($errors['name'])) { ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"><?php echo $errors['name']; } ?></div> <input class="form-control" type="text" name="name" placeholder="Nom"> <label for="firstname">Prénom : </label> <?php if (isset($errors['firstname'])) { ?> <div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"> <?php echo $errors['firstname']; } ?> </div> <input class="form-control" type="text" name="firstname" placeholder="Prénom"> <button class="btn btn-success mt-3">Enregistrer</button> </form> </section> <?php include("template/footer.php") ?><file_sep>/controllers/addUser.php <?php session_start(); // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); $userManager = new UserManager; if(isset($_POST['name']) || isset($_POST['firstname'])){ $errors = array(); if(empty($_POST['name'])){ $errors['name'] = "Veuillez renseigner votre nom."; } if(empty($_POST['firstname'])){ $errors['firstname'] = "Veuillez renseigner votre prénom."; } if(empty($errors)){ $name = addslashes(strip_tags($_POST['name'])); $firstname = addslashes(strip_tags($_POST['firstname'])); $bytes = random_bytes(4); $identifiant = bin2hex($bytes); $user = new User([ 'name' => $name, 'firstname' => $firstname, 'identifiant' => $identifiant, ]); $userManager->addUser($user); header('Location: users.php'); } } include "../views/addUserVue.php";<file_sep>/assets/js/main.js //Animation for books display function flip(element){ cardFlip = element.childNodes[5]; // cardFlip.style.display = "none"; cardFlip.setAttribute('class', 'absolute opacityimg card__wrapper sizeImgCard'); console.log(cardFlip); secondCardFlip = element.childNodes[3]; secondCardFlip.setAttribute('class', 'resume opacityInherit px-2 back card__side--back is-switched card__wrapper text-wrap text-truncate'); secondCardFlip.style.display="block"; } function reFlip(element){ cardFlip = element.childNodes[5]; cardFlip.setAttribute('class', 'sizeImgCard'); secondCardFlip = element.childNodes[3]; secondCardFlip.style.display = "none"; } //Animation for details book $(document).ready(function () { $(".accordion p").hide(); $(".accordion h4").click(function () { $(this).next("p").slideToggle("slow") .siblings("p:visible").slideUp("slow"); $(this).toggleClass("active"); $(this).siblings("h4").removeClass("active"); }); }); <file_sep>/book.sql -- phpMyAdmin SQL Dump -- version 4.5.4.1deb2ubuntu2.1 -- http://www.phpmyadmin.net -- -- Client : localhost -- Généré le : Jeu 17 Janvier 2019 à 14:26 -- Version du serveur : 5.7.24-0ubuntu0.16.04.1 -- Version de PHP : 7.2.13-1+ubuntu16.04.1+deb.sury.org+1 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET time_zone = "+00:00"; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de données : `book` -- -- -------------------------------------------------------- -- -- Structure de la table `admin` -- CREATE TABLE `admin` ( `id` int(11) NOT NULL, `firstname` varchar(255) NOT NULL, `mail` text NOT NULL, `pass` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `admin` -- INSERT INTO `admin` (`id`, `firstname`, `mail`, `pass`) VALUES (8, 'Paul', '<EMAIL>', <PASSWORD>'), (9, 'mama', '<EMAIL>', <PASSWORD>'); -- -------------------------------------------------------- -- -- Structure de la table `books` -- CREATE TABLE `books` ( `id_books` int(11) NOT NULL, `title` varchar(255) NOT NULL, `author` varchar(255) NOT NULL, `date` date NOT NULL, `resume` text NOT NULL, `picture_id` int(11) NOT NULL, `books_categorie_id` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `books` -- INSERT INTO `books` (`id_books`, `title`, `author`, `date`, `resume`, `picture_id`, `books_categorie_id`) VALUES (20, 'Les Misérables', '<NAME>', '2019-01-03', 'Valjean, l’ancien forçat devenu bourgeois et protecteur des faibles ; Fantine, l’ouvrière écrasée par sa condition ; le couple Thénardier, figure du mal et de l’opportunisme ; Marius, l’étudiant idéaliste ; Gavroche, le gamin des rues impertinent qui meurt sur les barricades ; Javert, la fatalité imposée par la société sous les traits d’un policier vengeur… Et, bien sûr, Cosette, l’enfant victime. Voilà comment une Å“uvre immense incarne son siècle en quelques destins exemplaires, figures devenues mythiques qui continuent de susciter une multitude d’adaptations. ', 86, 51); -- -------------------------------------------------------- -- -- Structure de la table `categorie` -- CREATE TABLE `categorie` ( `id_categorie` int(11) NOT NULL, `categorie` varchar(255) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `categorie` -- INSERT INTO `categorie` (`id_categorie`, `categorie`) VALUES (50, 'Roman'), (51, 'Roman'); -- -------------------------------------------------------- -- -- Structure de la table `pictures` -- CREATE TABLE `pictures` ( `id_picture` int(11) NOT NULL, `picture` text NOT NULL, `alt` text NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `pictures` -- INSERT INTO `pictures` (`id_picture`, `picture`, `alt`) VALUES (85, 'Les-Miserables.jpg', 'Les-Miserables.jpg'), (86, 'Les-Miserables.jpg', 'Les-Miserables.jpg'); -- -------------------------------------------------------- -- -- Structure de la table `users` -- CREATE TABLE `users` ( `id_user` int(11) NOT NULL, `name` varchar(255) NOT NULL, `firstname` varchar(255) NOT NULL, `identifiant` varchar(10) NOT NULL, `id_book_borrow` int(11) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Contenu de la table `users` -- INSERT INTO `users` (`id_user`, `name`, `firstname`, `identifiant`, `id_book_borrow`) VALUES (4, 'Paul', 'Decoux', 'd771a672', 20), (5, 'Thierry', 'Van-Hecke', 'a74b8186', NULL); -- -- Index pour les tables exportées -- -- -- Index pour la table `admin` -- ALTER TABLE `admin` ADD PRIMARY KEY (`id`); -- -- Index pour la table `books` -- ALTER TABLE `books` ADD PRIMARY KEY (`id_books`), ADD KEY `picture_id` (`picture_id`), ADD KEY `categorie_id` (`books_categorie_id`); -- -- Index pour la table `categorie` -- ALTER TABLE `categorie` ADD PRIMARY KEY (`id_categorie`); -- -- Index pour la table `pictures` -- ALTER TABLE `pictures` ADD PRIMARY KEY (`id_picture`); -- -- Index pour la table `users` -- ALTER TABLE `users` ADD PRIMARY KEY (`id_user`); -- -- AUTO_INCREMENT pour les tables exportées -- -- -- AUTO_INCREMENT pour la table `admin` -- ALTER TABLE `admin` MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=10; -- -- AUTO_INCREMENT pour la table `books` -- ALTER TABLE `books` MODIFY `id_books` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21; -- -- AUTO_INCREMENT pour la table `categorie` -- ALTER TABLE `categorie` MODIFY `id_categorie` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=52; -- -- AUTO_INCREMENT pour la table `pictures` -- ALTER TABLE `pictures` MODIFY `id_picture` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=87; -- -- AUTO_INCREMENT pour la table `users` -- ALTER TABLE `users` MODIFY `id_user` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7; -- -- Contraintes pour les tables exportées -- -- -- Contraintes pour la table `books` -- ALTER TABLE `books` ADD CONSTRAINT `books_ibfk_1` FOREIGN KEY (`picture_id`) REFERENCES `pictures` (`id_picture`) ON DELETE CASCADE ON UPDATE CASCADE, ADD CONSTRAINT `books_ibfk_2` FOREIGN KEY (`books_categorie_id`) REFERENCES `categorie` (`id_categorie`) ON DELETE CASCADE ON UPDATE CASCADE; /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; <file_sep>/views/userDetailsVue.php <?php include("template/header.php") ?> <section class="container"> <h2 class="my-5 text-center">Details Utilisateur</h2> <p class="text-center">Nom : <?php echo $user->getName(); ?></p> <p class="text-center">Prénom : <?php echo $user->getFirstname(); ?></p> <p class="text-center">Identifiant : <?php echo $user->getIdentifiant(); ?></p> <?php if($user->getId_book_borrow() != null){ ?> <?php foreach($bookBorrow as $element){ ?> <p class="text-center">Nom du livre emprunté : <?php echo $element['book']->getTitle(); ?></p> <?php } ?> <?php } ?> <div class="d-flex justify-content-center"> <a class="btn btn-info" href="updateUser.php?id=<?php echo $_GET['id']; ?>"><input class="btn" type="submit" value="Modifier"></a> </div> </section> <?php include("template/footer.php") ?><file_sep>/views/registerVue.php <?php include("template/header.php") ?> <section class="container"> <form class="mt-5 px-3 py-5 border border-light d-flex flex-column col-md-6 mx-auto" action="register.php" method="post"> <p class="text-center">Formulaire d'inscription</p> <label for="name">Prénom : </label> <?php if (isset($errors['firstname'])) { ?><div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"><?php echo $errors['firstname']; } ?></div> <input name="firstname" class="form-control" type="text" placeholder="Entrez votre prénom"> <label for="name">Mail : </label> <?php if (isset($errors['mail']) || isset($errors['exist'])) { ?><div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"><?php if(isset($errors['mail'])){ echo $errors['mail']; }elseif(isset($errors['exist'])){ echo $errors['exist']; }} ?></div> <input name="mail" class="form-control" type="text" placeholder="Entrez votre Email"> <label for="name">Pass : </label> <?php if (isset($errors['pass'])) { ?><div class="bg-danger p-1 rounded my-1 text-white font-weight-bold"><?php echo $errors['pass']; } ?></div> <input name="pass" class="form-control" type="text" placeholder="Entrez votre mot de passe"> <button type="submit" class="mt-3 btn btn-info">S'inscrire</button> <a class="" href="index.php"> <input class="col-12 mt-3 btn btn-success" type="button" value="Se connecter"> </a> </form> </section> <?php include("template/footer.php") ?> <file_sep>/models/UserManager.php <?php class UserManager extends Manager{ public function addUser(User $user){ $req = $this->getDb()->prepare('INSERT INTO users(name, firstname, identifiant) VALUES(:name, :firstname, :identifiant)'); $req->bindValue(':name', $user->getName(), PDO::PARAM_STR); $req->bindValue(':firstname', $user->getFirstname(), PDO::PARAM_STR); $req->bindValue(':identifiant', $user->getIdentifiant(), PDO::PARAM_STR); $req->execute(); } public function getUsers(){ $usersObj = array(); $req = $this->getDb()->query('SELECT * FROM users'); $users = $req->fetchAll(PDO::FETCH_ASSOC); foreach($users as $user){ $usersObj[] = new User($user); } return $usersObj; } public function deleteUser($id){ $req = $this->db->prepare('DELETE FROM users WHERE identifiant = :id'); $req->bindValue(':id', $id, PDO::PARAM_STR); $req->execute(); } public function borrowReturnBook($user, $book){ $req = $this->getDb()->prepare('UPDATE users SET id_book_borrow = :id_book_borrow WHERE identifiant = :identifiant'); $req->bindValue(':id_book_borrow', $book, PDO::PARAM_INT); $req->bindValue(':identifiant', $user, PDO::PARAM_STR); $req->execute(); } public function getUser($id){ $req = $this->getDb()->prepare('SELECT * FROM users WHERE id_user = :id'); $req->bindValue(':id', $id, PDO::PARAM_INT); $req->execute(); $user_data = $req->fetch(PDO::FETCH_ASSOC); $user = new User($user_data); return $user; } public function updateUser($id, User $user){ $req = $this->getDb()->prepare('UPDATE users SET name = :name, firstname = :firstname WHERE id_user = :id'); $req->bindValue(':id', $id, PDO::PARAM_INT); $req->bindValue(':firstname', $user->getFirstname(), PDO::PARAM_STR); $req->bindValue(':name', $user->getName(), PDO::PARAM_STR); $req->execute(); } }<file_sep>/models/AdminManager.php <?php class AdminManager extends Manager{ public function addAdmin(Admin $admin){ $req = $this->getDb()->prepare('INSERT INTO admin(firstname, mail, pass) VALUE (:firstname, :mail, :pass)'); $req->bindValue(':firstname', $admin->getFirstname(), PDO::PARAM_STR); $req->bindValue(':mail', $admin->getMail(), PDO::PARAM_STR); $req->bindValue(':pass', $admin->getPass(), PDO::PARAM_STR); $req->execute(); } public function adminExist(Admin $admin){ $req = $this->getDb()->prepare('SELECT * FROM admin WHERE mail = :mail'); $req->bindValue(':mail', $admin->getMail(), PDO::PARAM_STR); $req->execute(); $adminExist = $req->fetch(PDO::FETCH_ASSOC); if($adminExist==TRUE){ $adminobj = new Admin($adminExist); return $adminobj; }else{ return; } } }<file_sep>/controllers/addBook.php <?php session_start(); // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); $pictureManager = new PictureManager; $categorieManager = new CategorieManager; $bookManager = new BookManager; if(isset($_POST['title']) || isset($_POST['author']) || isset($_POST['date']) || isset($_POST['resume']) || isset($_POST['categorie'])) { $title = addslashes(strip_tags($_POST['title'])); $author = addslashes(strip_tags($_POST['author'])); $resume = addslashes(strip_tags($_POST['resume'])); $picture = addslashes(strip_tags($_FILES['picture']['name'])); $errors = array(); if(empty($_POST['title'])){ $errors['title'] = "Veuillez renseigner le titre du livre"; } if(empty($_POST['author'])){ $errors['author'] = "Veuillez renseigner l'auteur du livre"; } if(empty($_POST['date'])){ $errors['date'] = "Veuillez renseigner la date de publication du livre"; } if(empty($_POST['resume'])){ $errors['resume'] = "Veuillez renseigner le résumé du livre"; } if(empty($_POST['categorie'])){ $errors['categorie'] = "Veuillez renseigner la categorie du livre"; } if(empty($errors)){ //object picture $picture = new Picture([ "picture" => $picture, "alt" => $picture ]); // insert in db and get last id $pictureManager->addPicture($picture); $pictureLast = $pictureManager->getLastPicture(); move_uploaded_file($_FILES['picture']['tmp_name'], '../assets/img/' . basename($_FILES['picture']['name'])); // object categorie $categorie = new Categorie([ "categorie" => $_POST['categorie'] ]); $categorieManager->addCategorie($categorie); $categorieLast = $categorieManager->getLastCategorie(); //object book $book = new Book([ "title" => $title, "author" => $author, "date" => $_POST['date'], "resume" => $resume, "picture_id" => $pictureLast->getId_picture(), "books_categorie_id" => $categorieLast->getId_categorie() ]); $bookManager->addBook($book); header('Location: books.php'); } } include "../views/addBookVue.php";<file_sep>/controllers/index.php <?php session_start(); // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); $adminManager = new AdminManager; if(isset($_POST['mail']) || isset($_POST['pass'])){ $pass = password_hash($_POST['pass'], PASSWORD_DEFAULT); $errors = array(); if(empty($_POST['mail'])){ $errors['mail'] = "veuillez renseigner votre adresse mail"; } if(empty($_POST['pass'])){ $errors['pass'] = "ve<PASSWORD> de passe"; } if (preg_match("#^[a-z0-9-._]+@[a-z0-9-._]{2,}\.[a-z]{2,4}$#", $_POST['mail'])) { //Security data $mail = addslashes(strip_tags($_POST['mail'])); } else { $errors['mail'] = "Veuillez entrer une adresse mail valide"; } if(empty($errors)){ $admin = new Admin([ 'mail' => $mail, 'pass' => $pass ]); if($adminManager->adminExist($admin)==NULL){ $errors['no-exist'] = "Veuillez vous inscrire"; }else{ $verifyAdmin = $adminManager->adminExist($admin); if(password_verify($_POST['pass'], $verifyAdmin->getPass())){ $_SESSION['id'] = $verifyAdmin->getId(); } } } } if(isset($_SESSION['id'])){ header('Location: books.php'); } include "../views/indexVue.php"; ?> <file_sep>/views/bookVue.php <?php include("template/header.php") ?> <section class="container"> <?php foreach($book as $element){ ?> <div class="row"> <div class="mt-3 mb-3 col-md-6"><img class="col-12" src="../assets/img/<?php if($element['picture']->getPicture()==NULL){ echo 'dark-blue-book-background.jpg'; }else{ echo $element['picture']->getPicture(); ?>" alt="<?php echo $element['picture']->getAlt(); } ?>"></div> <div class="col-md-6"> <div class="mt-5 accordion"> <h4 class="d-flex justify-content-between my-4 text-info">Titre<i class="far fa-eye"></i></h4> <p><?php echo $element['book']->getTitle(); ?></p> <h4 class="d-flex justify-content-between my-4 text-info">Auteur<i class="far fa-eye"></i></h4> <p><?php echo $element['book']->getAuthor(); ?></p> <h4 class="d-flex justify-content-between my-4 text-info">Categorie<i class="far fa-eye"></i></h4> <p><?php echo $element['categories']->getCategorie(); ?></p> <h4 class="d-flex justify-content-between my-4 text-info">Date de parution<i class="far fa-eye"></i></h4> <p><?php echo $element['book']->getDate(); ?></p> <h4 class="d-flex justify-content-between my-4 text-info">Resumé<i class="far fa-eye"></i></h4> <p><?php echo $element['book']->getResume(); ?></p> </div> <div class="d-flex flex-column mt-5 mb-5 "> <a class="col-12 my-2" href="deleteBook.php?id=<?php echo $element['book']->getId_books(); ?>"><input type="submit" class="col-12 btn btn-danger" value="Supprimer"></a> <a class="col-12 my-2" href="updateBook.php?id=<?php echo $element['book']->getId_books(); ?>"><input type="submit" class="col-12 btn btn-info" value="Modifier"></a> <a class="col-12 my-2" href="borrowBook.php"><input type="submit" class="btn btn-warning col-12" value="Empreinter"></a> <a class="col-12 my-2" href="returnBook.php"><input type="submit" class="btn btn-dark col-12" value="Restituer"></a> </div> </div> </div> <?php } ?> </section> <?php include("template/footer.php"); ?><file_sep>/models/CategorieManager.php <?php class categorieManager extends Manager { public function addCategorie(categorie $categorie) { $req = $this->getDb()->prepare('INSERT INTO categorie(categorie) VALUE (:categorie)'); $req->bindValue(':categorie', $categorie->getCategorie(), PDO::PARAM_STR); $req->execute(); } public function getLastCategorie() { $req = $this->getDb()->query('SELECT * FROM categorie ORDER BY id_categorie DESC LIMIT 1'); $categorieLast = $req->fetch(PDO::FETCH_ASSOC); $objectCategorie = new categorie($categorieLast); return $objectCategorie; } }<file_sep>/controllers/register.php <?php // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); //instance of adminManager $adminManager = new AdminManager; //condition for error message if(isset($_POST['firstname']) || isset($_POST['mail']) || isset($_POST['pass'])){ //Security data $firstname = addslashes(strip_tags($_POST['firstname'])); $pass = password_hash($_POST['pass'], PASSWORD_DEFAULT); $errors = array(); if(empty($_POST['firstname'])){ $errors['firstname'] = "Veuillez entrer votre prénom"; } if(preg_match("#^[a-z0-9-._]+@[a-z0-9-._]{2,}\.[a-z]{2,4}$#", $_POST['mail'])) { //Security data $mail = addslashes(strip_tags($_POST['mail'])); }else{ $errors['mail'] = "Veuillez entrer une adresse mail valide"; } if(empty($_POST['pass'])){ $errors['pass'] = "ve<PASSWORD>rer votre mot de passe"; } //if $errors = NULL we create an object admin if(empty($errors)){ $admin = new Admin([ 'firstname'=> $firstname, 'mail' => $mail, 'pass' => $<PASSWORD> ]); //if admin is exist if($adminManager->adminExist($admin)){ $errors['exist'] = "Ce pseudo ou ce mail est déja utilisé"; }else{ // If not exist, add admin object $adminManager->addAdmin($admin); header('Location: index.php'); } } } include "../views/registerVue.php"; ?><file_sep>/entities/Picture.php <?php declare (strict_types = 1); class Picture extends Entity{ protected $id_picture, $picture, $alt; /** * Get the value of picture */ public function getPicture() { return $this->picture; } /** * Set the value of picture * * @return self */ public function setPicture($picture) { $this->picture = $picture; return $this; } /** * Get the value of alt */ public function getAlt() { return $this->alt; } /** * Set the value of alt * * @return self */ public function setAlt($alt) { $this->alt = $alt; return $this; } /** * Get the value of id_picture */ public function getId_picture() { return $this->id_picture; } /** * Set the value of id_picture * * @return self */ public function setId_picture($id_picture) { $this->id_picture = $id_picture; return $this; } }<file_sep>/views/returnBookVue.php <?php include("template/header.php") ?> <section class="container"> <form class="mt-5 d-flex justify-content-center" action="returnBook.php" method="post"> <select class="custom-select" name="user" id=""> <?php foreach ($users as $user) { ?> <option value="<?php echo $user->getIdentifiant(); ?>"><?php echo $user->getName(); ?></option> <?php } ?> </select> <select class="custom-select" name="book" id=""> <?php foreach ($books as $book) { ?> <option value="<?php echo $book['book']->getId_books(); ?>"><?php echo $book['book']->getTitle(); ?></option> <?php } ?> </select> <button type="submit" class="btn btn-dark">Restituer</button> </form> </section> <?php include("template/footer.php") ?><file_sep>/controllers/books.php <?php session_start(); // On enregistre notre autoload. function chargerClasse($classname) { if (file_exists('../models/' . $classname . '.php')) { require '../models/' . $classname . '.php'; } else { require '../entities/' . $classname . '.php'; } } spl_autoload_register('chargerClasse'); $bookManager = new BookManager; if($bookManager->getBooks()!=NULL){ $books = $bookManager->getBooks(); } include "../views/booksVue.php";<file_sep>/entities/Book.php <?php declare (strict_types = 1); class Book extends Entity{ protected $id_books, $title, $author, $date, $resume, $picture_id, $books_categorie_id; /** * Get the value of title */ public function getTitle() { return $this->title; } /** * Set the value of title * * @return self */ public function setTitle($title) { $this->title = $title; return $this; } /** * Get the value of author */ public function getAuthor() { return $this->author; } /** * Set the value of author * * @return self */ public function setAuthor($author) { $this->author = $author; return $this; } /** * Get the value of date */ public function getDate() { return $this->date; } /** * Set the value of date * * @return self */ public function setDate($date) { $this->date = $date; return $this; } /** * Get the value of resume */ public function getResume() { return $this->resume; } /** * Set the value of resume * * @return self */ public function setResume($resume) { $this->resume = $resume; return $this; } /** * Get the value of picture_id */ public function getPicture_id() { return $this->picture_id; } /** * Set the value of picture_id * * @return self */ public function setPicture_id($picture_id) { $this->picture_id = $picture_id; return $this; } /** * Get the value of books_categorie_id */ public function getBooks_categorie_id() { return $this->books_categorie_id; } /** * Set the value of books_categorie_id * * @return self */ public function setBooks_categorie_id($books_categorie_id) { $this->books_categorie_id = $books_categorie_id; return $this; } /** * Get the value of id_books */ public function getId_books() { return $this->id_books; } /** * Set the value of id_books * * @return self */ public function setId_books($id_books) { $this->id_books = $id_books; return $this; } }<file_sep>/models/PictureManager.php <?php class PictureManager extends Manager{ public function addPicture(Picture $picture){ $req = $this->getDb()->prepare('INSERT INTO pictures(picture, alt) VALUE (:picture, :alt)'); $req->bindValue(':picture', $picture->getPicture(), PDO::PARAM_STR); $req->bindValue(':alt', $picture->getPicture(), PDO::PARAM_STR); $req->execute(); } public function getLastPicture() { $req = $this->getDb()->query('SELECT * FROM pictures ORDER BY id_picture DESC LIMIT 1'); $pictureLast = $req->fetch(PDO::FETCH_ASSOC); $objectPicture = new Picture($pictureLast); return $objectPicture; } }<file_sep>/entities/Categorie.php <?php declare (strict_types = 1); class Categorie extends Entity{ protected $id_categorie, $categorie; /** * Get the value of categorie */ public function getCategorie() { return $this->categorie; } /** * Set the value of categorie * * @return self */ public function setCategorie($categorie) { $this->categorie = $categorie; return $this; } /** * Get the value of id_categorie */ public function getId_categorie() { return $this->id_categorie; } /** * Set the value of id_categorie * * @return self */ public function setId_categorie($id_categorie) { $this->id_categorie = $id_categorie; return $this; } }<file_sep>/views/deleteUserVue.php <?php include("template/header.php") ?> <section class="container"> <form class="mt-5" action="deleteUser.php" method="post"> <div class="input-group mb-3"> <select name="identifiant" class="custom-select" id="inputGroupSelect02"> <option selected>Choose...</option> <?php foreach ($users as $user) { ?> <option value="<?php echo $user->getIdentifiant(); ?>"><?php echo $user->getName(); ?></option> <?php } ?> </select> <button type="submit" class="btn btn-danger">Supprimer</button> </div> </form> </section> <?php include("template/footer.php"); ?><file_sep>/views/template/header.php <!doctype html> <html class="no-js" lang=""> <head> <meta charset="utf-8"> <meta http-equiv="x-ua-compatible" content="ie=edge"> <title></title> <meta name="description" content=""> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="manifest" href="site.webmanifest"> <link rel="apple-touch-icon" href="icon.png"> <!-- Place favicon.ico in the root directory --> <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" integrity="<KEY> crossorigin="anonymous"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link rel="stylesheet" href="../assets/css/normalize.css"> <link rel="stylesheet" href="../assets/css/main.css"> </head> <body> <!--[if lte IE 9]> <p class="browserupgrade">You are using an <strong>outdated</strong> browser. Please <a href="https://browsehappy.com/">upgrade your browser</a> to improve your experience and security.</p> <![endif]--> <header id="header" class="main-header"> <nav class="navbar navbar-expand-lg navbar-light bg-light"> <?php if (isset($_SESSION['id'])) { ?> <a href="logout.php"> <input class="btn btn-danger" type="submit" value="Déconnexion"> </a> <?php } ?> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <?php if (isset($_SESSION['id'])) { ?> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item active"> <a class="nav-link" href="books.php">Liste des livres <span class="sr-only">(current)</span></a> </li> </ul> </div> </nav> <div class="header-nav"> <a href="addBook.php"><i class="fas fa-book"></i></a> <a href="users.php"><i class="fas fa-user"></i></a> <a href="addUser.php"><i class="fas fa-user-plus"></i></a> <a href="deleteUser.php"><i class="fas text-danger fa-user-alt-slash"></i></a> </div> <?php } ?> </header>
fa04881166c65596afc3f951abc40a82a4d395c5
[ "JavaScript", "SQL", "PHP" ]
30
PHP
Decoux/Books
cfeb78c3097d62110560742577643204911c65c3
0e6ba3d84829fc8b4b8c997538df5a84eaedc7a4
refs/heads/master
<repo_name>DanielDent/sync-docker<file_sep>/Dockerfile FROM danieldent/debian-jessie-base MAINTAINER <NAME> (https://www.danieldent.com/) RUN /usr/local/bin/install-resilio-sync.sh COPY rslsync.conf /etc/ COPY run_sync /opt/ EXPOSE 8888 EXPOSE 55555 VOLUME /mnt/sync ENTRYPOINT ["/opt/run_sync"] CMD ["--log", "--config", "/etc/rslsync.conf"] <file_sep>/run_sync #! /bin/sh mkdir -p /mnt/sync/folders mkdir -p /mnt/sync/config exec /usr/local/bin/rslsync --nodaemon $*
756210d6c1d705f7bd6773bd329e0166d5fa88ed
[ "Dockerfile", "Shell" ]
2
Dockerfile
DanielDent/sync-docker
83a19834bd715ff49e8647d48499cc13fec0df4d
cce21ec6e4cbef536152b4497d02fdf95858ac9b
refs/heads/master
<repo_name>kevjiang/sms_adventure<file_sep>/handler.py from scrapers import * from adventure import * from time import * def response_handler(body): ''' given text body string input If body = "nytimes needle", searches nytimes for needle Otherwise plays adventure game returns proper response message ''' message = "" # prompt for a search of word on NYT if "nytimes" in body.split(): needle = body.split()[1] url = 'http://www.nytimes.com' total_nyt_count = all_text_count(needle, url) message = "%s: %s homepage currently includes %d mentions of %s" % (strftime("%Y-%m-%d %I:%M:%S"), url, total_nyt_count, needle) elif "espn" in body.split(): needle = body.split()[1] url = 'http://www.espn.com' total_nyt_count = all_text_count(needle, url) message = "%s: %s homepage currently includes %d mentions of %s" % (strftime("%Y-%m-%d %I:%M:%S"), url, total_nyt_count, needle) elif 'start' == body: message = classroom0() elif 'take a nap' == body: message = take_nap() elif 'take notes' == body: message = take_notes() elif 'turn around' == body: message = turn_around() elif 'notes' == body: message = notes() else: message = rogue() return message<file_sep>/send_sms.py # Download the twilio-python library from http://twilio.com/docs/libraries from twilio.rest import TwilioRestClient from scrapers import * from time import * # Find these values at https://twilio.com/user/account account_sid = "<KEY>" auth_token = "<PASSWORD>" client = TwilioRestClient(account_sid, auth_token) needle = "Trump" url = 'http://www.nytimes.com' total_nyt_count = all_text_count(needle, url) body_text = "%s: nytimes.com homepage currently includes %d mentions of %s" % (strftime("%Y-%m-%d %I:%M:%S"), total_nyt_count, needle) message = client.messages.create(to="+17816402658", from_="+17815705388", body=body_text)<file_sep>/adventure.py def classroom0(): return "You are in a boring class. Do you 'take a nap' or 'take notes'?" def take_nap(): return "You fall asleep forever...and ever...and ever. Do you want to 'start' over?" def take_notes(): return "You furiously take notes as the teacher drones on. Your friend taps you on the shoulder. Do you 'turn around' or keep looking at your 'notes'" def turn_around(): return "You turn around, only to find that you have just stared into the eyes of a basilisk! Oh well...do you want to 'start' over?" def notes(): return "Unfortunately, this game is incomplete...please come back later for more! Do you want to 'start' over?" def rogue(): return "Text a valid command (denoted by single quotes). Or text 'start' to restart the game."
3f402e8de1eac08f45644c3b73c16c344f85fbee
[ "Python" ]
3
Python
kevjiang/sms_adventure
921551222ac03597060546decc840d4478866ed4
8ec031e6b032a3a37a4e199f9a89fc1bba951b13
refs/heads/master
<repo_name>FGDATA/aura-props<file_sep>/test.py from props import getNode, root def great_circle_route(a,b): """mock function for this test to work""" return 125.22 #create some nodes gps = getNode("/sensors/gps", create=True) fdm = getNode("/aero/engine", create=True) waypoint = getNode("/navigation/route/target", create=True) ap = getNode("/autopilot/settings", create=True) waypoint.lat=waypoint.lon=0 struct=(""" The Structure built in this test is: -/aero/engine/ |-reverser |-rev_throtle |-position _ name /autopilot/settings/ _target_heading /navigation/route/target/ |-waypoint.lat _ waypoint.lon /sensors/gps/ |-lat |-lon _alt """) print (struct) #testing populating some nodes (gps.lat, gps.lon, gps.alt, gps.speed, gps.ground_track) = (40.741895, -73.989308, 1225.25, 325, 4.5) (fdm.reverser, fdm.rev_throtle, fdm.position, fdm.name) = (False, 0.25, 23, "Garuff") ##playing with nodes usage heading = great_circle_route([gps.lat, gps.lon], [waypoint.lat, waypoint.lon]) ap.target_heading = heading #checking it comes together print """ ------------------Checking the Property Tree management on Python-------------\n""" print("the node /sensors/gps/lat is " + str(gps.lat)) print("the node /sensors/gps/lon is " + str(gps.lon)) print("the node /aero/engine/reverser is " + str(fdm.reverser)) print ("the node /autopilot/settings/target_heading is " + str(ap.target_heading))
a6141d3da18070aa745a147cfd9ecc9016216c2f
[ "Python" ]
1
Python
FGDATA/aura-props
00915e36b140139b50e076e19ca6d94a5349982d
2c05bd3002ae1713a476f4a66151e433bfebc968
refs/heads/main
<repo_name>chiragkapoorck/FOREX-predictions<file_sep>/README.md # Predicting Exchange Rate in Real-Time using Google Trends Data. Refer for complete documentation: https://drive.google.com/file/d/1GTT9hOPIFhBICPwy63GT9ylTDptMmvuX/view?usp=sharing <file_sep>/code_script.py #!/usr/bin/env python # coding: utf-8 # <h1>Rolling Regression and Forecasts.</h1> # <p> # <a href="https://www.statsmodels.org/stable/examples/notebooks/generated/rolling_ls.html">Statsmodel Documentation</a><br /> # <a href="https://plotly.com/python/">Plotly Documentation</a><br /> # <a href="https://pandas.pydata.org/docs/user_guide/index.html#user-guide">Pandas Documentation</a> # </p> # In[1]: import numpy as np import pandas as pd # statsmodel libraries import statsmodels.api as sm from statsmodels.regression.rolling import RollingOLS from statsmodels.tsa.seasonal import seasonal_decompose import matplotlib.pyplot as plt import seaborn seaborn.set_style('darkgrid') pd.plotting.register_matplotlib_converters() get_ipython().run_line_magic('matplotlib', 'inline') import cufflinks as cf from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot import plotly.express as px # For Notebooks init_notebook_mode(connected=True) # For offline use cf.go_offline() # <h2>Getting the Data Ready</h2> # <h3> Macroeconomic Data </h3> # In[2]: # exchange rate data er = pd.read_csv('./data/er.csv', index_col='DATE', parse_dates=True) er = er.iloc[:197] # cpi (prices) data cpi = pd.read_csv('./data/cpi.csv', index_col=1, parse_dates=True) cpi_can = cpi[cpi['LOCATION'] == 'CAN'] cpi_usa = cpi[cpi['LOCATION'] == 'USA'] # <h3> Google Trends Data </h3> # In[3]: # for the search term "prices" prices_usa = pd.read_csv('./data/prices-us.csv', index_col=0, parse_dates=True).iloc[:197] prices_can = pd.read_csv('./data/prices_can.csv', index_col=0, parse_dates=True).iloc[:197] # <h3> Compiling the data together </h3> # In[4]: df = pd.DataFrame() df['actual_exr'] = er.values.ravel() df['can/usa_cpi'] = (cpi_can['Value'].values)/cpi_usa['Value'].values df['can/usa_priceTerm'] = (prices_can.values)/prices_usa.values df.index = cpi_can.index df.describe() # <h2> Decomposing into trend and seasonality </h2> # In[5]: # for google trends indicator result = seasonal_decompose(df['can/usa_priceTerm'], model='additive') result.plot() plt.show() # In[6]: # for macroeconomic fundamental result = seasonal_decompose(df['can/usa_cpi'], model='additive') result.plot() plt.show() # In[7]: # for our dependent variable result = seasonal_decompose(df['actual_exr'], model='additive') result.plot() plt.show() # <h2> The Analysis </h2> # In[8]: window = 12 # window length to consider for training the model # <h3> Rolling Window Regression using official macroeconomic data </h3> # In[9]: y_predicted = list() for i in range(len(df)-window-1): y = df.iloc[i:i+window]['actual_exr'] X = sm.add_constant(df.iloc[i:i+window]['can/usa_cpi']) model = sm.OLS(y,X) results = model.fit() y_predicted.append(np.array([1,df.iloc[i+window+1]['can/usa_cpi']]).dot(np.array(results.params))) # <h3> Rolling Window Regression using google trends data as proxy</h3> # In[10]: y_predicted_gt = list() for i in range(len(df)-window-1): y = df.iloc[i:i+window]['actual_exr'] X = sm.add_constant(df.iloc[i:i+window]['can/usa_priceTerm']) model = sm.OLS(y,X) results = model.fit() y_predicted_gt.append(np.array([1,df.iloc[i+window+1]['can/usa_priceTerm']]).dot(np.array(results.params))) # <h2> Predictions </h2> # In[11]: df.loc[window+1:,'macro_prediction'] = y_predicted df.loc[window+1:,'google_trends_prediction'] = y_predicted_gt # In[12]: df[['actual_exr','macro_prediction','google_trends_prediction']].iplot() # <h2> Some graphical analysis </h2> # In[13]: px.scatter(df, x='can/usa_priceTerm', y='actual_exr', trendline='ols') # <h2> Error Analysis </h2> # In[14]: df['MSE_macro'] = (df['actual_exr'] - df['macro_prediction'])**2 df['MSE_gt'] = (df['actual_exr'] - df['google_trends_prediction'])**2 # In[15]: error = list() # In[16]: # structural model MSE error.append(df['MSE_macro'].describe()['mean']) error.append(df['MSE_gt'].describe()['mean']) # In[ ]: # In[17]: pd.DataFrame(error,['PPP Model','Google Trends Model'],columns=['Mean Square Prediction Error']) # In[ ]:
186e6ffcb6fdd8ac97e047aff7deb98aedfee1fb
[ "Markdown", "Python" ]
2
Markdown
chiragkapoorck/FOREX-predictions
a709297e82ac1365750b96643363a613867fe5a7
3c80896385222f2ac381a37666c01eaeb5d1dd24
refs/heads/master
<file_sep>// // SwiftUIView.swift // SwiftUIView // // Created by <NAME> on 05/08/21. // import SwiftUI @available(iOS 13.0, *) public struct GFRefreshableScrollViewModifier: ViewModifier { var action: () -> Void public init(action: @escaping () -> Void) { self.action = action } public func body(content: Content) -> some View { GFRefreshableScrollView(action: action) { content } } } <file_sep>// // GFRefreshableScrollView.swift // // Created by <NAME> on 05/08/21. // import SwiftUI /// Enable pull down to refresh by wrapping the view inside a GeometryReader /// and a ScrollView @available(iOS 13.0, *) public struct GFRefreshableScrollView<Content:View>: View { public init(action: @escaping () -> Void, @ViewBuilder content: @escaping () -> Content) { self.content = content self.refreshAction = action } public var body: some View { GeometryReader { geometry in ScrollView { content() .anchorPreference(key: OffsetPreferenceKey.self, value: .top) { geometry[$0].y } } .onPreferenceChange(OffsetPreferenceKey.self) { offset in if offset > threshold { refreshAction() } } } } // MARK: - Private private var content: () -> Content private var refreshAction: () -> Void private let threshold:CGFloat = 50.0 } internal struct OffsetPreferenceKey: PreferenceKey { static var defaultValue: CGFloat = 0 static func reduce(value: inout CGFloat, nextValue: () -> CGFloat) { value = nextValue() } } <file_sep># GFRefreshableScrollView Implementation of pull down to refresh in SwiftUI compatible with iOS 13. You can use it as a modifier to your existing views ```swift var body: some View { LazyVStack { if isLoading { ProgressView() } ForEach(posts) { post in PostView(post: post) } } .modifier(GFRefreshableScrollViewModifier(action: refreshAction)) } ``` Or use it instead of a ScrollView ```swift var body: some View { GFRefreshableScrollView(action: refreshList) { if isLoading { VStack { ProgressView() Text("loading...") } } VStack { ForEach(posts) { post in PostView(post: post) } } } } ``` If you want to find out more about the implementation please refer to my [blog post](https://www.gfrigerio.com/pull-down-to-refresh-in-swiftui/) # License GFRefreshableScrollView is available under the MIT license. See the LICENSE file for more info. <file_sep>import XCTest @testable import GFRefreshableScrollView final class GFRefreshableScrollViewTests: XCTestCase { }
7b5661e96d2783721fd48c1b0da72b5e1b4e8feb
[ "Swift", "Markdown" ]
4
Swift
gualtierofrigerio/GFRefreshableScrollView
77fd4fbb8900fe824ddc5f6e098a7b2c1e13cf82
f969d7f857515c4e9bdfee8b2e8deb8cbdad1931
refs/heads/master
<repo_name>pantharshit00/robo<file_sep>/main.ino const int trigPin = 9; const int echoPin = 10; //L293D //Motor A const int motorPin1 = 5; // Pin 14 of L293 const int motorPin2 = 6; // Pin 10 of L293 //Motor B const int motorPin3 = 4; // Pin 7 of L293 const int motorPin4 = 3; // Pin 2 of L293 long duration; int distance; void setup() { pinMode(trigPin, OUTPUT); // Sets the trigPin as an Output pinMode(echoPin, INPUT); // Sets the echoPin as an Input //Set pins as outputs pinMode(motorPin1, OUTPUT); pinMode(motorPin2, OUTPUT); pinMode(motorPin3, OUTPUT); pinMode(motorPin4, OUTPUT); Serial.begin(9600); // Starts the serial communication } void loop() { digitalWrite(trigPin, LOW); delayMicroseconds(2); digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW); duration = pulseIn(echoPin, HIGH); distance = duration * 0.034 / 2; // Speed sound I am taking as 340 m/s Kartikeya give ino if (distance > 30) { startMotorClockwise(); } else if (distance < 10) { startMotorsAntiClockwise(); } else { stopMotors(); } Serial.print("Distance: "); Serial.println(distance); } void startMotorClockwise() { digitalWrite(motorPin1, HIGH); digitalWrite(motorPin2, LOW); digitalWrite(motorPin3, HIGH); digitalWrite(motorPin4, LOW); Serial.print("DONE"); } void startMotorsAntiClockwise() { digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, HIGH); digitalWrite(motorPin3, LOW); digitalWrite(motorPin4, HIGH); Serial.print("DONEBB"); } void stopMotors() { digitalWrite(motorPin1, LOW); digitalWrite(motorPin2, LOW); digitalWrite(motorPin3, LOW); digitalWrite(motorPin4, LOW); } <file_sep>/README.md # robo School IoT project 1. It follows you pretty well
61fddbd85f9010dbc6882a600b8245d1081748ff
[ "Markdown", "C++" ]
2
C++
pantharshit00/robo
4519b5da85074b13b1cb71da5af7a170649ff548
c363c58351075e9341223995ec2cda03aa08751d
refs/heads/master
<file_sep><?php use yii\helpers\Html; use himiklab\colorbox\Colorbox; /** * Вывод одной новости * @var $model \app\models\News */ ?> <?= Colorbox::widget([ 'targets' => [ '.colorbox' => [ 'maxWidth' => 800, 'maxHeight' => 600, 'rel' => 'image-in-group', 'current' => 'Изображение {current} из {total}', ], ], 'coreStyle' => 1 ]) ?> <div class="row"> <article class="col-md-8"> <h2 class="bb-color"><?= $model->title; ?></h2> <p><?= $model->text; ?></p> </article> <aside class="col-md-4"> <!-- TODO PICTURES --> <?php if ($imageList): foreach ($imageList as $image): $imgPath = '/img/uploads/news/' . $model->id . '/' . $image; //ToDo причесать ?> <a href="<?= $imgPath; ?>" class="thumbnail col-md-6 colorbox image-in-group" title="<?= $model->title; ?>"> <img src="<?= $imgPath; ?>"> </a> <?php endforeach; endif; ?> </aside> </div><file_sep><?php use yii\helpers\Html; use yii\helpers\Url; /* @var $this yii\web\View */ $this->title = 'Новости'; if (! Yii::$app->user->isGuest): ?> <p> <?= Html::a('Управление', ['admin'], ['class' => 'btn btn-danger']) ?> </p> <?php endif; foreach ($news as $new): ?> <div class="row"> <h1 class="bb-color"><?= Html::encode($new->title); ?></h1> <p> <?= Html::encode($new->text); ?> </p> <p><a class="btn btn-outline" href="<?= Url::to(['/news']) . '/' . $new->id ?>">Подробнее</a></p> </div> <?php endforeach; ?><file_sep><?php /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ /* @var $model app\models\ContactForm */ use yii\helpers\Html; use yii\bootstrap\ActiveForm; use yii\captcha\Captcha; $this->title = 'Контакты'; $email = '<EMAIL>'; $tel1 = '+7 (495) 710-7298'; $tel2 = '+7 (903) 562-5952'; $tel3 = '+7 (903) 764-3886'; ?> <div class="site-contact"> <div class="row contact-content"> <h1 class="bb-color">Наши контакты</h1> <img src="../../img/contact-title.png" alt=""> <div class="contact-data"> <h3 class="bb-color">Email:</h3> <a href="mailto:<?= $email; ?>"><?= $email; ?></a> <h3 class="bb-color">Тел./Факс:</h3> <a href="tel:<?= $tel1; ?>"><?= $tel1; ?></a> <br> <a href="tel:<?= $tel2; ?>"><?= $tel2; ?></a> <br> <a href="tel:<?= $tel3; ?>"><?= $tel3; ?></a> </div> </div> </div> <file_sep><?php namespace app\models; use Yii; use yii\base\Model; use yii\web\UploadedFile; class UploadForm extends Model { /** * @var UploadedFile */ public $imageFile; public $imageJson; //ToDo Надо ли Json??? public $modelId; public $section; //Имя раздела сайта public $imgDir = 'img/uploads/'; public function rules() { return [ [['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'], ]; } public function upload() //ToDo { if ($this->validate()) { //ToDO Проверка существования папки?? $fullPath = $this->imgDir . $this->section . $this->modelId; mkdir($fullPath); $filePath = $fullPath . '/' . Yii::$app->getSecurity()->generateRandomString(12) . '.' . $this->imageFile->extension; $this->imageFile->saveAs($filePath); return true; } return false; } }<file_sep><?php use yii\helpers\Url; /* @var $this yii\web\View */ $this->title = 'Base Beauty – художественно-производственные мастерские по изготовлению студийных и татральных декораций'; ?> <div class="site-index"> <div class="index-jumbotron hidden-sm hidden-xs"> <h1 class="jumbotron-heading bb-color">&laquo;BASE-BEAUTY&raquo;</h1> <h3 class="jumbotron-small">ХУДОЖЕСТВЕННО</h3> <h3 class="jumbotron-small">-ПРОИЗВОДСТВЕННЫЕ</h3> <h3 class="jumbotron-small bb-color">МАСТЕРСКИЕ</h3> <div class="col-sm-5 jumbotron-description"> <h3 class="bb-color">Производство студийных и<br>театральных декораций</h3> <p class="text-justify">«Base-Beauty» - художественно-производственные мастерские, специализирующиеся в области изготовления студийных и театральных декораций. А так же в оформлении сцен для шоу-программ, концертов и корпоративных вечеринок. Эксклюзивное оформление презентаций и выставочных стендов а так же украшение свадеб и юбилеев от компании «Base-Beauty» это визитная карточка самого высокого уровня.</p> </div> </div> <div> <!-- --------------------------- START NEWS SECTION---------------------------- --> <div class="row bb-color-bg"> <?php foreach ($news as $new): ?> <div class="col-lg-4"> <h2><?= $new->title; ?></h2> <p class="text-justify"><?= \yii\helpers\StringHelper::truncate($new->text,300,'...'); ?></p> <p><a class="btn btn-outline btn-block" href="<?= Url::to(['/news']) . '/' . $new->id ?>">Подробнее</a></p> </div> <?php endforeach; ?> </div> <!-- --------------------------- END NEWS SECTION---------------------------- --> <div class="row project-stages"> <div class="col-lg-4"> <span class="big-number pull-left bb-color">1</span> <h4 class="bb-color">Работа над проектом</h4> <p>(создание декораций) всегда начинается с эскиза художественного оформления площадки (сцены, выставки и т.п.), создание которого предлагается каждому клиенту абсолютно бесплатно</p> </div> <div class="col-lg-4"> <span class="big-number pull-left bb-color">2</span> <h4 class="bb-color">Эскизирование</h4> <p>осуществляется художником, который встречается непосредственно с заказчиком, выезжая на объект, полностью выясняет все пожелания клиента и начинает работу над эскизами</p> </div> <div class="col-lg-4"> <span class="big-number pull-left bb-color">3</span> <h4 class="bb-color">Изготовление декораций</h4> <p>Составляется смета и начинается работа по изготовлению декораций. Процессу подготовки проектов декораций также способствует богатый опыт сотрудничества со смежными службами</p> </div> </div> <div class="row"> <div class="col-lg-6"> <img src="../../img/main-desc1.png" alt=""> </div> <div class="col-lg-6"> <h2 class="bb-color">От проектирования до создания декораций</h2> <p>Каждому клиенту мы предлагаем комплексное решение задач от проектирования до производства декораций, уникальный коллективный опыт компании прилагается абсолютно бесплатно. После выполнения эскизов они утверждаются, составляется смета и начинается работа по изготовлению декораций. Процессу подготовки проектов декораций также способствует богатый опыт сотрудничества со смежными службами, участвующими в обслуживании сцены (свет, сценические конструкции, газосвет, пиротехника, спецэффекты и т.п.) </p> </div> </div> <div class="row"> <div class="col-lg-6"> <h2 class="bb-color">О нас</h2> <p>"Base Beauty" – художественно-производственные мастерские, специализирующиеся в области изготовления сценических декораций для шоу-программ, концертов и презентаций, а также оформления и украшения выставочных стендов, свадеб, юбилеев и корпоративных вечеринок. Мы производим декорации не только для массовых мероприятий, но и для различных телевизионных проектов, телестудий, театральных постановок и т.д. <ul> <li>Работа над проектом (созданием декораций) всегда начинается с эскиза художественного оформления площадки (сцены, выставки и т.п.) </li> <li>Эскизирование осуществляется художником, который встречается непосредственно с заказчиком, выезжая на объект, полностью выясняет все пожелания клиента и начинает работу над эскизами </li> <li>После выполнения эскизов они утверждаются, осмечиваются и начинается работа по изготовлению декораций </li> </ul> </p> </div> <div class="col-lg-6"> <img src="../../img/main-desc2.png" alt="" class="pull-right"> </div> </div> <div class="row"> <div class="col-lg-6"> <img src="../../img/main-desc3.png" alt=""> </div> <div class="col-lg-6"> <h2 class="bb-color">Нам доверяют</h2> <p>За время существования компании "Base Beauty" с сентября 1993 года к нам обратились многие ведущие звёзды театра, кино и шоу-бизнеса такие как: А.&nbsp;Пугачева, И.&nbsp;Кобзон, В.&nbsp;Леонтьев, Ф.&nbsp;Киркоров, К.&nbsp;Орбакайте, В.&nbsp;Меладзе, Л.&nbsp;Долина, С.&nbsp;Ротару, Л.&nbsp;Лещенко, Т.&nbsp;Буланова, А.&nbsp;Буйнов, А.&nbsp;Цой, Ж.&nbsp;Агузарова, К.&nbsp;Лель, В.&nbsp;Сюткин, Жасмин, Иванушки&nbsp;int. и многие другие. </p> <p> А так же организаторы самых известных российских церемоний вручений популярных премий и наград, телевизионных проектов ведущих телеканалов страны, корпоративных праздников самых известных российских и зарубежных фирм </p> </div> </div> </div> </div> <file_sep><?php /* @var $this yii\web\View */ use yii\helpers\Html; $this->title = 'О нас'; ?> <div class="site-about"> <div class="row"> <aside class="col-lg-4"> <h1 class="bb-color">О нашей компании, почему мы...?</h1> <p>Очень часто по требованию заказчика некоторые компании создают проекты наполняя их таким количеством не оправданно красочных элементов, что гости пришедшие на мероприятие, перестают воспринимать все происходящее.</p> <p>Мы можем сделать для вашего проекта качественные и эксклюзивные декорации, но если вам нужно что то не дорогое и банальное, если вы не хотите увидеть блеск в глазах ваших гостей и услышать возгласы восхищения, то мы знаем кто для вас это сделает. Мы берем с вас деньги за то, что бы сделать идеальный проект для вашего мероприятия.</p> <p>Мы обладаем богатым опытом создания удивительных по своей красоте и смелостью внедрения технических решений развлекательных шоу. Отталкиваясь от своего опыта и понимания вашей идеи, мы ставим задачу и находим единственно правильное решение, которое и готовы вам предложить.</p> <p><strong><em>Если наша идея вас не устроит, увы …</em></strong></p> </aside> <div class="col-lg-8"> <img src="../../img/about-desc.jpg" alt="" class="img-responsive img-rounded"> </div> </div> </div> <file_sep><?php use yii\db\Migration; use app\models\User; /** * Handles the creation of table `user`. */ class m170907_121746_create_user_table extends Migration { /** * @inheritdoc */ public function up() { $this->createTable('user', [ 'id' => $this->primaryKey(), 'username' => $this->string(64)->notNull()->unique(), 'auth_key' => $this->string(32)->notNull(), 'password_hash' => $this->string()->notNull(), 'email' => $this->string(64)->notNull()->unique(), ]); // -------------------------------Test User --------------------------------------------------------- //ToDo УБРАТЬ В ПРОДАКШЕНЕ $user = new User(); $user->username = 'admin'; $user->email = '<EMAIL>'; $user->setPassword('<PASSWORD>'); $user->generateAuthKey(); $user->save(); // -------------------------------------------------------------------------------------------------- } /** * @inheritdoc */ public function down() { $this->dropTable('user'); } }<file_sep><?php /** * Created by PhpStorm. * User: Konstantin * Date: 04.08.2017 * Time: 11:28 */
5323629b722323887c850ff5823f1ed2b3c263a8
[ "PHP" ]
8
PHP
woodprop/BaseBeauty.ru
a952d870a727bad826567afe784a804844afad9b
dda0acd614bbad3b9f9a1898f0fd91487e58459c
refs/heads/master
<file_sep>require "acts_as_message_topic/version" module ActsAsMessageTopic # Your code goes here... end
782541ea88e58a3b422ad688780f2988ee03dad3
[ "Ruby" ]
1
Ruby
contently/acts_as_message_topic
8915af9dd9fe37a25bd43b4e96e2b92e889f9dfc
7ca1238272c0e5f5b7edb0def91e5eec2a4fb7e3
refs/heads/main
<repo_name>Mimi-c0der/Math-Quiz-Part-2<file_sep>/main.js function add_user(){ p1_var = document.getElementById("p1_name").value; p2_var = document.getElementById("p2_name").value; localStorage.setItem("player 1 name" , p1_var); localStorage.setItem("player 2 name" , p2_var); window.location = "game_page.html" }
daa8960ced86b3fdf8d9a1e86865669079b46273
[ "JavaScript" ]
1
JavaScript
Mimi-c0der/Math-Quiz-Part-2
74a1efab966a9e9cdbd529a3743b068ffb4e68d2
5bc350e5e1a1ecc65228b4887c8f18dbb8630a56
refs/heads/master
<repo_name>deogracia/ror-playground<file_sep>/README.md ror-playground ============== <file_sep>/config/initializers/session_store.rb # Be sure to restart your server when you modify this file. RorPlayground::Application.config.session_store :cookie_store, key: '_ror-playground_session'
0e9b771dfd41f3a7a40d7121b08a7fd3f96ccc8c
[ "Markdown", "Ruby" ]
2
Markdown
deogracia/ror-playground
02356d1992663c450211fc1894d771654697dee2
bc639726d01637309ab3e21eae3a38bb6868676f
refs/heads/master
<file_sep>spring.main.banner-mode=off server.port=8087 spring.datasource.url=jdbc:mysql://localhost:3306/my_db spring.datasource.username=bestuser spring.datasource.password=<PASSWORD> info.name=Employee info.description=Spring boot app. This app is used for CRUD operation with employees of our company. info.author=<NAME> management.endpoints.web.exposure.include=* spring.security.user.name=user spring.security.user.password=<PASSWORD><file_sep>package com.voronin.spring.boot.services; import com.voronin.spring.boot.entity.Employee; import com.voronin.spring.boot.repository.EmployeeRepository; import org.springframework.stereotype.Service; import java.util.List; @Service public class EmployeeServiceImpl implements EmployeeService { private final EmployeeRepository employeeRepository; public EmployeeServiceImpl(EmployeeRepository employeeRepository) { this.employeeRepository = employeeRepository; } @Override public List<Employee> findAll() { return this.employeeRepository.findAll(); } @Override public Employee save(Employee employee) { return this.employeeRepository.save(employee); } @Override public Employee findById(int id) { return this.employeeRepository.findById(id).orElseGet(Employee::new); } @Override public void deleteById(int id) { this.employeeRepository.deleteById(id); } @Override public List<Employee> findAllByName(String name) { return this.employeeRepository.findAllByName(name); } }
d020e1f1fedf7f1f0082007f7ea39c56a3da229c
[ "Java", "INI" ]
2
INI
Error4ik/spring-course
1b9d53494f7103ca6c0fe0566d24dedcdc9c69bf
1a6ff8858b99e1dacc294db557f2cf037ae71219
refs/heads/master
<repo_name>GavrilM/MemeFeed<file_sep>/README.md # MemeFeed Generates a meme based on the most popular meme pages on Facebook. Hack to learn the Facebook API.<file_sep>/app.py from flask import Flask, jsonify, render_template from livereload import Server import requests from random import randint from config import APP_KEY, APP_SECRET app = Flask('MemeFeed') app.debug = True def fb_request(endpoint): return 'https://graph.facebook.com/v2.10/{}?access_token={}|{}'.format(endpoint, APP_KEY, APP_SECRET) @app.route('/') def root(): resp = requests.get(fb_request('1717731545171536/feed/')) data = resp.json()['data'] random_post = data[randint(0,len(data))] print(len(data)) message = random_post['message'] if 'message' in random_post else '[No text]' post_attachment = requests.get(fb_request(random_post['id'] + '/attachments/')).json()['data'][0] if 'media' in post_attachment and 'image' in post_attachment['media'] and 'src' in post_attachment['media']['image']: src = post_attachment['media']['image']['src'] else: src = '' return render_template('meme.html', text=message, imgsrc=src) @app.route('/<post>') def post(post): resp = requests.get(fb_request(str(post) + '/attachments')).json() return render_template('meme.html', text='Hello', imgsrc='') Server(app.wsgi_app).serve()
c4bf81be9d03d5adac4eb9d0b4ab11bdaed21a5c
[ "Markdown", "Python" ]
2
Markdown
GavrilM/MemeFeed
a6ee1e22157c4e25fb58f34ca2d985b8a808f3fe
d73392920c75145900a8d7b8dabd5e0d5a600604
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Windows.Forms; namespace IGNco.Helper { public class DAL { public static string ConnectionStr = ""; // Your connection string gose here public int runCommand(string spName, List<DatabaseModel> Spcmd) { string pro = ConnectionStr; int nat = (int)_EnumManager.DbState.success; SqlConnection thisconnection = new SqlConnection(); thisconnection.ConnectionString = pro; try { SqlCommand cmd = new SqlCommand(spName, thisconnection); thisconnection.Open(); foreach (var param in Spcmd) { cmd.Parameters.AddWithValue(param.ParametrName, param.Value); } cmd.ExecuteNonQuery(); } catch { nat = (int)_EnumManager.DbState.error; } finally { thisconnection.Close(); } return nat; } public int hasRows(string spName, List<DatabaseModel> Spcmd) { int nat = (int)_EnumManager.DbState.success; string pro = ConnectionStr; SqlConnection thisconnection = new SqlConnection(); thisconnection.ConnectionString = pro; try { SqlCommand cmd = new SqlCommand(spName, thisconnection); thisconnection.Open(); foreach (var param in Spcmd) { cmd.Parameters.AddWithValue(param.ParametrName, param.Value); } SqlDataReader rdr0 = cmd.ExecuteReader(); if (rdr0.HasRows == true) { nat = (int)_EnumManager.DbState.hasrows; } else { nat = (int)_EnumManager.DbState.empty; } } catch { nat = (int)_EnumManager.DbState.error; } finally { thisconnection.Close(); } return nat; } public DataTable selectTable(string Ctxt, out int result) { DataTable dt = new DataTable(); string pro = ConnectionStr; SqlConnection thisconnection = new SqlConnection(); thisconnection.ConnectionString = pro; try { thisconnection.Open(); SqlDataAdapter rdr = new SqlDataAdapter(Ctxt, thisconnection); try { rdr.Fill(dt); if (dt.Rows.Count == 0) { result = (int)_EnumManager.DbState.empty; } else { result = (int)_EnumManager.DbState.success; } } catch { result = (int)_EnumManager.DbState.error; } } catch { result = (int)_EnumManager.DbState.error; } finally { thisconnection.Close(); } return dt; } public DataTable selectTable(string Ctxt, List<DatabaseModel> Spcmd, out int result) { DataTable dt = new DataTable(); string pro = ConnectionStr; SqlConnection thisconnection = new SqlConnection(); thisconnection.ConnectionString = pro; try { thisconnection.Open(); SqlCommand cmd = new SqlCommand(Ctxt, thisconnection); //cmd.CommandType = CommandType.StoredProcedure; foreach (var param in Spcmd) { cmd.Parameters.AddWithValue(param.ParametrName, param.Value); } SqlDataAdapter rdr = new SqlDataAdapter(cmd); try { rdr.Fill(dt); if (dt.Rows.Count == 0) { result = (int)_EnumManager.DbState.empty; } else { result = (int)_EnumManager.DbState.success; } } catch { result = (int)_EnumManager.DbState.error; } } catch { result = (int)_EnumManager.DbState.error; } finally { thisconnection.Close(); } return dt; } public string persianDateYear() { System.Globalization.PersianCalendar oPersianC = new System.Globalization.PersianCalendar(); string Day, Month, Year, Date = ""; //date Year = oPersianC.GetYear(System.DateTime.Now).ToString(); Date = Year; return Date; } public string persianDate() { System.Globalization.PersianCalendar oPersianC = new System.Globalization.PersianCalendar(); string Day, Month, Year, Date = ""; //date Year = oPersianC.GetYear(System.DateTime.Now).ToString(); Month = oPersianC.GetMonth(System.DateTime.Now).ToString(); Day = oPersianC.GetDayOfMonth(System.DateTime.Now).ToString(); if ((int.Parse(Month) > 0) && (int.Parse(Month) < 10)) { Month = "0" + Month; } if ((int.Parse(Day) > 0) && (int.Parse(Day) < 10)) { Day = "0" + Day; } Date = Year + "/" + Month + "/" + Day; return Date; } public string persianTime() { System.Globalization.PersianCalendar oPersianC = new System.Globalization.PersianCalendar(); string testc = ""; //date testc = oPersianC.GetHour(System.DateTime.Now).ToString(); testc += ":" + oPersianC.GetMinute(System.DateTime.Now).ToString(); return testc; } public string persianTimeAndSec() { System.Globalization.PersianCalendar oPersianC = new System.Globalization.PersianCalendar(); string testc = ""; //date testc = oPersianC.GetHour(System.DateTime.Now).ToString(); testc += ":" + oPersianC.GetMinute(System.DateTime.Now).ToString(); testc += ":" + oPersianC.GetSecond(System.DateTime.Now).ToString(); return testc; } public string getTextDoc(string path) { string text = ""; using (StreamReader stremreader = new StreamReader(path, true)) { text = stremreader.ReadToEnd() + "\n\r#"; } return text; } public bool SetTextDoc(string path, string text) { bool result = true; using (StreamWriter streamwriter = new StreamWriter(path, true)) { streamwriter.WriteLine(text); } return result; } public string checkID(string DbName) { string ID = Guid.NewGuid().ToString(); DAL dal = new DAL(); string spCom = string.Empty; List<DatabaseModel> dbList = new List<DatabaseModel>(); DatabaseModel dbm; spCom = "SELECT * from " + DbName + " where [ID]=@ID"; dbm = new DatabaseModel(); dbm.ParametrName = "@ID"; dbm.Value = ID; dbList.Add(dbm); int result = dal.hasRows(spCom, dbList); if (result != (int)_EnumManager.DbState.hasrows) { return ID; } return checkID(DbName); } public List<ListModel> MakeList(DataTable dt) { List<ListModel> list = new List<ListModel>(); ListModel lm; lm = new ListModel(); lm.Member = "-- انتخاب --"; lm.Value = "0"; list.Add(lm); for (int i = 0; i < dt.Rows.Count; i++) { lm = new ListModel(); lm.Member = dt.Rows[i][1].ToString(); lm.Value = dt.Rows[i][0].ToString(); list.Add(lm); } return list; } public string getData(string fileName) { string v = ""; //string dir = path; if (File.Exists(fileName + ".txt")) { StreamReader st = new StreamReader(fileName + ".txt"); string p1 = ""; do { p1 = st.ReadLine(); } while (st.Peek() != -1); st.Close(); v = p1; } else { v = ""; } return v; } public string SetData(string fileName, string txt) { string v = ""; //string dir = path; StreamWriter stw = null; stw = File.CreateText(fileName + ".txt"); stw.WriteLine(txt); stw.Close(); v = ""; return v; } } public class _EnumManager { public enum DbState { success, hasrows, empty, error } } public class ListModel { public string Member { get; set; } public object Value { get; set; } } public class DatabaseModel { public string ParametrName { get; set; } public object Value { get; set; } } public static class Prompt { public static string ShowDialog(string text, string caption) { Form prompt = new Form() { Width = 500, Height = 170, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption, StartPosition = FormStartPosition.CenterScreen }; Label textLabel = new Label() { Left = 50, Top = 20, Text = text, Width = 400 }; TextBox textBox = new TextBox() { Left = 50, Top = 50, Width = 400 }; Button confirmation = new Button() { Text = "Ok", Left = 350, Width = 100, Top = 75, DialogResult = DialogResult.OK }; confirmation.Click += (sender, e) => { prompt.Close(); }; prompt.Controls.Add(textBox); prompt.Controls.Add(confirmation); prompt.Controls.Add(textLabel); prompt.AcceptButton = confirmation; return prompt.ShowDialog() == DialogResult.OK ? textBox.Text : ""; } } } <file_sep># DAL ### A lib to help in coding this lib help to connect to sql server database in C# # How to use public static string ConnectionStr = "ConStr"; // Your connection string gose here Select: DAL dal = new DAL(); string spCom = string.Empty; DataTable dt = new DataTable(); spCom = "SELECT [ID],[Name] from [Table] where [ID]=@ID"; dbm = new DatabaseModel(); dbm.ParametrName = "@ID"; dbm.Value = Id.Text; dbList.Add(dbm); int result = 0; dt = dal.selectTable(spCom, out result); if (result == (int)_EnumManager.DbState.success) { //dt is filled with data } Insert, Update, Delete: string stb = string.Empty ; DAL dal = new DAL(); string spCom = string.Empty; List<DatabaseModel> dbList = new List<DatabaseModel>(); DatabaseModel dbm; spCom = "INSERT into [Table] ([Value1Col],[Value2Col],[Value3Col]) values" + " (@Value1,@Value2,@Value3)"; dbm = new DatabaseModel(){ ParametrName = "@Value1", Value = "Var1"}; dbList.Add(dbm); dbm = new DatabaseModel(){ ParametrName = "@Value2", Value = "Var2"}; dbList.Add(dbm); dbm = new DatabaseModel(){ ParametrName = "@Value3", Value = "Var3"}; dbList.Add(dbm); int result = dal.runCommand(spCom, dbList); if (result == (int)_EnumManager.DbState.success) { //Success } else { //Failes }
12ad6b6494ed4889228aab5d388729ae25480838
[ "Markdown", "C#" ]
2
C#
Alfred188/DAL
1c233108abc35bd2ef47c9824210395549e8dd53
be5dd29700b77fbec99354176e881c15a323a29a
refs/heads/master
<repo_name>tanusgit/HomeworkJava<file_sep>/Array1/src/numberofsamewords/Test.java package numberofsamewords; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; public class Test { public static void main(String[] args) { List<String> list = Arrays.asList("java", "php", "android", "sap", "php", "java", "win", "ios", "win", "hana", "android", "ios", "ios", "ios"); List<String> list2 = new ArrayList<String>(); list2.add("java"); list2.add("java"); list2.add("java"); list2.add("php"); list2.add("php"); list2.add("sap"); Map<String, Integer> l = findWordCount(list2); System.out.println(l); // count(list2); } private static Map<String, Integer> findWordCount(List<String> list) { Map<String, Integer> m = new HashMap<>(); for (int i = 0; i < list.size(); i++) { boolean exists = m.containsKey(list.get(i)); if (exists) { int count = m.get(list.get(i)); m.put(list.get(i), count + 1); } else { m.put(list.get(i), 1); //execute for the first time } } return m; } public static void count(List<String> list) { int count = 0; for (int i = 0; i < list.size(); i++) { for (int j = 0; j < list.size(); j++) { if (list.get(j).equals(list.get(i))) { count++; } } System.out.println(list.get(i) + " " + count); } } } <file_sep>/Array1/src/homework/AvoidDuplicate.java package homework; import java.util.ArrayList; import java.util.List; import java.util.Scanner; /* * taking the names and avoid the duplicates in arraylist */ public class AvoidDuplicate { public static void main(String[] args) { duplicate(); } //program is not working successfully static List<String> names = new ArrayList<>(); public static void duplicate() { Scanner m = new Scanner(System.in); while (true) { System.out.println("enter names"); String name = m.nextLine(); String res = name; if (name.equalsIgnoreCase("end")) { break; } names.add(name); } System.out.println(names); int size = names.size(); System.out.println(size + " is the size of the arraylist"); int count = 0; String first = names.get(count); System.out.println(first + " is the 1st element of the arraylist"); List<String> newName = new ArrayList<>(); for(int i = 1; i < size; i++) { if(!names.get(count).equals(names.get(i))){ newName.add(names.get(i)); } count++; } newName.add(first); System.out.println("after sorting ........."); System.out.println(newName); } } <file_sep>/Array1/src/findemployee/Findemployee.java package findemployee; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; public class Findemployee { public static void main(String[] args) { Employee e1 = new Employee(1, "Mina", 5000, "D1"); Employee e2 = new Employee(2, "Minali", 50000, "D2"); Employee e3 = new Employee(3, "Adi", 5000, "D3"); Employee e4 = new Employee(4, "Minali", 50000, "D2"); /*Map<String, String>map = new HashMap<>(); map.put("Mina", "D1"); map.put("Minali", "D2"); map.put("Adi", "D3"); map.put("Rith", "D2");*/ List<Employee> list = new ArrayList<>(); list.add(e1); list.add(e2); list.add(e3); list.add(e4); find(list); } private static void find(List<Employee> list) { //keep value in a list and then keep the list in hashmap as a value Map<String, String>map = new HashMap<>(); for(int i = 0; i < list.size(); i++) { if(map.containsKey(list.get(i).getDept())){ map.put(list.get(i).getDept(), list.get(i).getName()); } else { map.put(list.get(i).getDept(), list.get(i).getName()); } } System.out.println(map); } } <file_sep>/Array1/src/homeworkOnFile/SearchFileInDirectory.java package homeworkOnFile; import java.io.File; import java.nio.file.Path; import java.nio.file.Paths; public class SearchFileInDirectory { // client will give the file name and program has to tell whether // the file exists and which folder // search files public static void main(String[] args) { //search("initrd.img"); searchHelper("/home/td/Desktop/Java", "flower.odt"); } public static void searchHelper(String dir, String name) { File f2 = new File(dir); //System.out.println(f2.isDirectory()); File f3 = new File(name); //System.out.println(f3.isFile()); boolean found = false; //list all the files and directories with their full path for(File n: f2.listFiles()) { // System.out.println(n); //n is file so we need to call toString() to make it a string to compare with //file name if(n.isFile() && n.toString().contains(name)) { System.out.println("found in " + n.toString()); found = true; } else if(n.isDirectory()) { searchHelper(n.toString(), name); } } if(!found){ //System.out.println("not found"); } } public static void search(String name) { try { // creating file object to perform some file operations File f3 = new File(name); System.out.println(f3.isFile()); System.out.println(f3.getParentFile()); // searching for the root directory of any computer File[] fr = f3.listRoots(); boolean found = false; for (File m1 : fr) { // printing root System.out.println(m1); // checking if root is a directory // System.out.println(m1.isDirectory()); // taking all the files or directories in the root String n[] = m1.list(); for (String k : n) { // k is all the directories in the root directory // System.out.println(k); Path pathf = Paths.get(m1.toString(), k); File directory = new File(pathf.toString()); boolean res = directory.isDirectory(); // System.out.println(directory+ " " + res ); long l = directory.length(); if (directory.isFile()) { if (k.equals(name)) { System.out.println("found: " + name); found = true; } } } if (!found) { System.out.println("not found "); } } }catch(Exception e) { } } } /* * * if (directory != null) { System.out.println(directory.list().toString()); } * * creating file objects for all the directories or files in //the root by * adding the path of the file with the root's //directory's path, otherwise * computer won't understand //that it is a file/directory in the root * directory. we must give //the complete path to the computer. So we are * creating path by //joining the path of root and the file * System.out.println(k); Path pathf = Paths.get(m1.toString(), k); File * directory = new File(pathf.toString()); boolean res = * directory.isDirectory(); System.out.println(pathf.toString()+ " " + res ); * //System.out.println(directory); for (String eachFile : directory.list()) { * //System.out.println("files in " + directory + " " //+eachFile); } //first * root -> home -> td -> desktop -> java ->test10 if (k.equals(name)) { * System.out.println("found " + name + " in " + k); found = true; } } * if(!found) { System.out.println("did not find " + name); } } }catch(Exception * e) { * * } /*joining directory and file name by calling paths.get() which takes // * directory name and file name Path filePath = Paths.get(dir, name); File f2 = * new File(filePath.toString()); // f.listFiles(); boolean resdir = * f.isDirectory(); boolean resFile = f2.isFile(); File[] files = f.listRoots(); * for (File m : files) { System.out.println(m); } * * // System.out.println(resdir); // System.out.println(resFile); * * if (resdir == true && resFile == true) { for (String n : f.list()) { // * System.out.println(n); if (n.equals(name)) { System.out.println("found " + * name + " in " + f.getParent()); found = true; } } * * } if (!found) { System.out.println("it is not a directory or a file"); } if * (resdir == true && resFile == true && !found) { search(f.getParent(), name); * * File[] files = f.listRoots(); for(File m : files) { System.out.println(m); } */ <file_sep>/testFile.properties IPADDRESS=172.16.31.10 portNo=9089 dbName=oracle name=Tanu user=kkk pass=123 reultsperpage=22 <file_sep>/Array1/src/newhomeworkonCoreJava/Flames.java package newhomeworkonCoreJava; import java.util.Scanner; /*2.FLAMES program using java F - Friendship L - Love A - Affection M - Marriage E - Enemy S - Sister (Sibling) Ex: Enter First name: Krishna Enter Second name: Radha Output: Affection Kisn d apply 5 to FLAMES FLAMES 1. E is deleted FLAMS 2. M is deleted FLAS 3. S is deleted FLA 4. L is deleted FA 5. F is deleted A * */ public class Flames { public static void main(String[] args) { flames(); char p = 'p'; } String F = "Friendship"; String L = "Love"; String A = "Affection"; String M = "Marriage"; String E = "Enemy"; String S = "Sibling"; static Scanner sc = new Scanner(System.in); private static void flames() { // TODO Auto-generated method stub System.out.println("enter first name"); String input = sc.next(); System.out.println("enter second name"); String input2 = sc.next(); int l = input.length(); int l2 = input2.length(); int totalLength = l + l2; String res = ""; String res2 = ""; String res3 = ""; for (char c : input.toCharArray()) { Character cl = Character.toUpperCase(c); res = res +" " + cl; } for (char c : input2.toCharArray()) { Character cl = Character.toUpperCase(c); res2 = res2 + " " +cl; } String[] resarray = res.split(" "); String[] res2array = res2.split(" "); //making a new array with all the elements from the above 2 arrays String[] res3array = new String[resarray.length+res2array.length]; //copying every element from resarray to res3array for(int i = 0; i < resarray.length; i++) { res3array[i] = resarray[i]; } int count =0; for(int i = resarray.length; i < res3array.length; i++) { //res2array has only 4 elements so cant copy from 4th element res3array[i] = res2array[count++]; } System.out.println("printing res3array: " ); for(String s: res3array) { System.out.print(s); } System.out.println("*********************************"); //remove duplicates from new string array int count2 =0; String[] res4 = new String[res3array.length]; for(int i =0; i < res3array.length; i++) { for(int j =1; j < res3array.length; j++) { if(!(res3array[i].contains( res3array[j]))) { res4[i] = res3array[i]; } } } System.out.println("*************************"); for(String s: res4) { System.out.print(s + " "); } } } <file_sep>/Array1/src/homework/AvoidDuplicateArray.java package homework; public class AvoidDuplicateArray { /* * taking the names and avoid the duplicates */ } <file_sep>/Array1/src/multimapInJava/MultimapinJava.java package multimapInJava; import java.util.Arrays; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Map.Entry; public class MultimapinJava { public static void main(String[] args) { Map<Employee, List<String>> map = new HashMap<>(); List<String> values = Arrays.asList("apple", "orange", "kiwi", "mango"); Employee e1 = new Employee(1, "Mina", 5000, "D1"); Employee e2 = new Employee(2, "Minali", 50000, "D2"); Employee e3 = new Employee(3, "Adi", 5000, "D3"); Employee e4 = new Employee(4, "Minali", 50000, "D2"); map.put(e1, values); map.put(e2, values); map.put(e3, values); map.put(e4, values); System.out.println(map); //printMap(map); } private static void printMap(Map< Employee, List<String>> map) { for (Entry<Employee, List<String>> entry : map.entrySet()) { Employee key = entry.getKey(); List<String> value = entry.getValue(); System.out.println("key= " + key + " , value=" + value); } } } <file_sep>/Array1/src/numberofsamewords/Test2HashMap.java package numberofsamewords; import java.util.HashMap; import java.util.Map; public class Test2HashMap { public static void main(String[] args) { Map<String, Integer> map = new HashMap<>(); //Hashmap<key,value> map.put("Mango", 1); map.put("oragnge", 5); map.put("banana", 6); map.put("apple", 4); System.out.println(map); boolean res = map.containsKey("Mango"); //map.get() takes key and return the value System.out.println(map.get("banana")); System.out.println(res); System.out.println("***********************************************"); Map<Integer, String> map2 = new HashMap<>(); //Hashmap<key,value> map2.put( 1, "java"); map2.put( 5, "php"); map2.put(6, "java"); map2.put(4, "php"); System.out.println(map2); boolean res2 = map2.containsKey(1); //map.get() takes key and return the value System.out.println(map2.get(5)); System.out.println(res2); } } <file_sep>/Array1/src/homeworkonStars/NinetyDegree.java package homeworkonStars; import java.util.Scanner; public class NinetyDegree { public static void main(String[] args) { // printMatrix(5); takeMatrix(); } static Scanner sc = new Scanner(System.in); private static void printMatrix(int n) { int count = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(count++ + " "); } System.out.println(" "); } } private static void takeMatrix() { int input = 0; System.out.println("enter width"); int w = sc.nextInt(); System.out.println("enter height"); int h = sc.nextInt(); int[][] array = new int[h][w]; for (int i = 0; i < h; i++) { System.out.println("enter num"); for (int j = 0; j < w; j++) { input = sc.nextInt(); array[i][j] = input; } System.out.println(" "); } for (int[] n : array) { for (int k : n) { System.out.print(k + " "); } System.out.println(" "); } } public static void shiftNinetydegree(int[][] matrix) { } } <file_sep>/Array1/src/newhomeworkonCoreJava/Permetutation.java package newhomeworkonCoreJava; /*Input1 : kumar Input2: 2 Output: Ku Km Ka kr um ua ur ma mr ar Kum kua kur uma umr mar */ import java.util.ArrayList; public class Permetutation { public static void main(String[] args) { int n = 5; int p = 2; permute(n, p); String k = "Kumar"; permuteString(k, p); } private static void permuteString(String s, int p) { String res = ""; ArrayList<String> array = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { for (int j = i+1; j < s.length(); j++) { char c = s.charAt(i); char d = s.charAt(j); res = c + " " + d + " "; if (!array.contains(res)) { array.add(res); } } } System.out.println(array); } private static void permuteString3(String s, int p) { String res = ""; ArrayList<String> array = new ArrayList<>(); for (int i = 0; i < s.length(); i++) { for (int j = i+1; j < s.length(); j++) { for (int k = j+1; k < s.length(); k++) { char c = s.charAt(i); char d = s.charAt(j); char e = s.charAt(k); res = c + " " +d + " " + e + " "; if (!array.contains(res)) { array.add(res); } } } } System.out.println(array); } private static void permute(int n, int r) { int res = factorial(n) / (factorial(n - r)*factorial(r)) ; System.out.println(res); } private static int factorial(int n) { if (n == 1) { return 1; } else if (n == 0) { return 1; } else if (n > 1) { return n * factorial(n - 1); } else return -1; } } <file_sep>/Array1/src/homework/MergeArray.java package homework; import java.util.ArrayList; import java.util.List; public class MergeArray { /* * Strings 2 arraylists create * a third arraylist with first 2 arraylist while merging avoid duplicates */ //working well avoiding duplicates public static void main(String[] args) { String[] names = {"Rahul", "Mina", "Rahul", "Mina","Hina", "Rina", "Rina"}; String[] names2 = {"Rahul", "Rina"}; MergeArray m = new MergeArray(); m.merge(names, names2); } String array []; public void merge(String[] n, String[] m) { try { int l = n.length; int l2 = m.length; int l3 = l + l2; ArrayList<String> array = new ArrayList<>(); for(int i = 0; i < l; i ++) { array.add(n[i]); } //getting exception because i have tried to access //string array from the 4th element which is the last element //of string array m. //in arraylist we always add element at the end //so we dont need to specify any special index for the arraylist //but we do need to specify that we are accessing the m array from //it 0 index to the last index, in this case l2 is the length of the array //so loop will run until l2 and it will start from 0 as in any array //elements stays from 0 index for(int j = 0; j < l2; j ++) { array.add(m[j]); }//finished adding n and m array to the new array list for(String n2: array) { System.out.println(n2); } System.out.println("after removing duplicates ............."); //creating a new arraylist to avoid the duplicates ArrayList<String> array2 = new ArrayList<>(); for(int i = 0; i < array.size(); i ++) { if(!array2.contains(array.get(i))) { array2.add(array.get(i)); } } /* int count = 0; String first = array.get(0); ArrayList<String> array1 = new ArrayList<>(); for(int i = 1; i < array.size(); i++) { if(!(array.get(count).equals(array.get(i)))) { array1.add(array.get(i)); } count++; } array1.add(first); for(String n3: array1) { System.out.println(n3); }*/ for(String n3: array2) { System.out.println(n3); } }catch(Exception e) { System.out.println("invalid"); } } public String toString() { String res = ""; for(int i = 0; i < array.length; i ++) { res = array[i] + " "; } return res; } } <file_sep>/Array1/src/homework/Person.java package homework; import java.util.ArrayList; import java.util.Scanner; public class Person { /* * ask for id name age then if you wish to continue? If yes then ask for id name age if no print all the data add person objects in arraylist, size as an input, do you wish to add person */ String name; int age; int id; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getId() { return id; } public void setId(int id) { this.id = id; } public Person(String name, int age, int id) { super(); this.name = name; this.age = age; this.id = id; } } <file_sep>/Array1/src/newhomeworkonCoreJava/PatternPrint.java package newhomeworkonCoreJava; /* * 6.Patterns: Input : 5 a) 1 2 3 4 5 1 2 3 4 1 2 3 1 2 1 b) 1 1 2 1 2 3 1 2 3 4 1 2 3 4 5 c) Input 3 o/p: 1 2 3 4 5 6 7 8 9 e) Input :4 Output: 1 2 3 4 5 6 7 8 9 10 */ public class PatternPrint { public static void main(String[] args) { print1(5); System.out.println("************************"); print2(5); System.out.println("************************"); print3(3); System.out.println("************************"); print4(4); } private static void print1(int n) { // TODO Auto-generated method stub for (int i = n; i > 0; i--) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(" "); } } private static void print2(int n) { // TODO Auto-generated method stub for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(j + " "); } System.out.println(" "); } } private static void print3(int n) { // TODO Auto-generated method stub int count = 1; for (int i = 0; i < n; i++) { for (int j = 0; j < n; j++) { System.out.print(count++ + " "); } System.out.println(" "); } } private static void print4(int n) { // TODO Auto-generated method stub int count = 1; for (int i = 1; i <= n; i++) { for (int j = 1; j <= i; j++) { System.out.print(count++ + " "); } System.out.println(" "); } } } <file_sep>/testFile.md krishns,28,1313 where are you? IPADDRESS=172.16.31.10 portNo=9089 dbName=oracle name=kmr user=1234 pass=<PASSWORD> reultsperpage=20 <file_sep>/Array1/src/genericClass2InstanceVariable/CarGeneric.java package genericClass2InstanceVariable; //generic class with 2 instance variables public class CarGeneric<T,E>{ //if T means String then color and and wheel both would be string //solved the problem with <T,E> private T wheel; private E color; public T getWheel() { return wheel; } public E getColor() { return color; } public void setColor(E c) { color = c; } public void setWheel(T w) { wheel = w; } } <file_sep>/Array1/src/genericClass2InstanceVariable/Tesla.java package genericClass2InstanceVariable; public class Tesla { int price; int milege; public Tesla(int price, int milege) { super(); this.price = price; this.milege = milege; } public int getPrice() { return price; } public void setPrice(int price) { this.price = price; } public int getMilege() { return milege; } public void setMilege(int milege) { this.milege = milege; } @Override public String toString() { return "Tesla [price=" + price + ", milege=" + milege + "]"; } } <file_sep>/Array1/src/homework/DeleteInBetween.java package homework; public class DeleteInBetween { /* * delete from any position of an array */ //not working perfectly includes a 0 in the resulting array public static void main(String[] args) { int[] a = { 1, 2, 3}; int[] array3 = DeleteAt(1, a); for (int n : array3) { System.out.println(n); } } public static int[] DeleteAt(int index, int[] array) { int[] array2 = null; int [] array3 = null; try { int l = array.length; int newl = l - 1; int preValue; array2 = new int[l]; //we have to run the loop till l time as we are copying from the //bigger array so we must reach the end of the bigger array for (int i = 0; i < l; i++) { if (!(i == index)) { array2[i] = array[i]; } //array2[newl-1] = array[i+1]; } // return array2; } catch (ArrayIndexOutOfBoundsException e) { System.out.println("something went wrong"); } catch (NullPointerException e) { System.out.println("something went null"); } return array2; } }
136344baac16df8fbcef2e758739b338682f9bca
[ "Markdown", "Java", "INI" ]
18
Java
tanusgit/HomeworkJava
63dac005f961d8e1cc9799cc23fbee913c4e899c
4551b7319a18100febf3b89130878dd41d400f40
refs/heads/main
<repo_name>Johnvict/card-dto<file_sep>/src/environments/environment.prod.ts export const environment = { production: true, sheetURL: 'https://sheet.best/api/sheets/4883dc2a-a242-41fa-a537-2709cd1a5cb8' }; <file_sep>/src/app/services/helpers.service.ts import { Injectable } from "@angular/core"; @Injectable({ providedIn: 'root' }) export class HelpersService { constructor() { } /** * Format the expiry date to make it look more like a real date on card 08/21 * @param expiryDateInput number | string */ formatExpiryDate(expiryDateInput: number | string): string { expiryDateInput = String(expiryDateInput); expiryDateInput = expiryDateInput.replace("/", ""); expiryDateInput = expiryDateInput.substr(0, 2) + "/" + expiryDateInput.substr(2); return expiryDateInput; } /** * Formart card number to have dashes inbetween every four digits * @param cardInput string */ formatCardNumber(cardInput: string = "", mockMaskedCard = false): string { cardInput = String(cardInput); cardInput = this.removeDashes(cardInput); cardInput = `_${cardInput}`; let formatedCardNumber = ""; for (let i = 1; i < cardInput.length; i++) { formatedCardNumber += i % 4 === 0 && i !== cardInput.length - 1 ? mockMaskedCard ? `${this.maskData(cardInput[i], i, cardInput.length)}` : `${cardInput[i]}-` : mockMaskedCard ? this.maskData(cardInput[i], i, cardInput.length) : cardInput[i]; } return formatedCardNumber; } maskData(char: string, position: number, totalLength: number) { return position > 3 && position < (totalLength - 6) ? '*' : char; } /** * Remove the dashes to make the card number plain digits again * @param cardInput string */ removeDashes(cardInput: string): string { for (let i = 1; i < cardInput.length; i++) { cardInput = cardInput.replace("-", ""); } return cardInput; } }<file_sep>/src/app/pages/make-payment/make-payment.module.ts import { MaterialModule } from './../../material.module'; import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { Routes, RouterModule } from '@angular/router'; import { ReactiveFormsModule, FormsModule } from '@angular/forms'; import { MakePaymentComponent } from './make-payment.component'; const routes: Routes = [ { path: '', component: MakePaymentComponent } ]; @NgModule({ imports: [ CommonModule, FormsModule, ReactiveFormsModule, MaterialModule, [RouterModule.forChild(routes)], ], declarations: [MakePaymentComponent], exports: [MakePaymentComponent] }) export class MakePaymentModule { } <file_sep>/src/app/app.module.ts import { RequestInterceptor, DEFAULT_TIMEOUT } from './services/request.interceptor'; import { NgModule } from '@angular/core'; import { BrowserModule } from '@angular/platform-browser'; import { AppRoutingModule } from './app-routing.module'; import { AppComponent } from './app.component'; import { StoreModule } from '@ngrx/store'; import { BrowserAnimationsModule } from '@angular/platform-browser/animations'; import { reducer } from './store-setup/card.reducer'; import { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http'; import { MakePaymentComponent } from './pages/make-payment/make-payment.component'; import { MaterialModule } from './material.module'; @NgModule({ declarations: [ AppComponent, ], imports: [ BrowserModule, AppRoutingModule, HttpClientModule, StoreModule.forRoot({ cardData: reducer }, {}), BrowserAnimationsModule, MaterialModule ], providers: [ { provide: DEFAULT_TIMEOUT, useValue: 30000 }, { provide: HTTP_INTERCEPTORS, useClass: RequestInterceptor, multi: true }, ], bootstrap: [AppComponent], }) export class AppModule { } <file_sep>/src/app/store-setup/interfaces.ts export interface CardData { cardNumber: number | string; cardHolder: string; expiryDate: Date; securityCode?: string; amount: number; } export interface AppState { readonly cardData: CardData[]; } <file_sep>/src/app/store-setup/card.reducer.ts import { CardData } from './interfaces'; import * as CardActions from './card.actions'; import { Action, createReducer, on } from '@ngrx/store'; const initialState: CardData[] = []; const cardDataReducer = createReducer( initialState, on(CardActions.InitializeCard, (state, data) => { let initialData = [...data.data]; return initialData; }), on(CardActions.AddCard, (state, data) => { let newData = [...state, data.data]; console.log(data); return newData; // return state; }), on(CardActions.DeleteCard, (state, data) => { let newState: CardData[] = [...state]; newState.splice(data.index, 1); return newState; }) ); export function reducer(state: CardData[] = [], action: Action) { return cardDataReducer(state, action); } <file_sep>/src/app/services/payment.service.ts import { HelpersService } from './helpers.service'; import { map } from 'rxjs/operators'; import { Injectable } from "@angular/core"; import { environment } from './../../environments/environment'; import { HttpClient } from '@angular/common/http'; import { AppState, CardData } from "./../store-setup/interfaces"; import { Observable } from "rxjs"; import { Store } from "@ngrx/store"; import * as CardActions from './../store-setup/card.actions'; @Injectable({ providedIn: 'root' }) export class PaymentService { sheetURL = environment.sheetURL; cardData: CardData[] = []; constructor( private http: HttpClient, private store: Store<AppState>, private helpersService: HelpersService ) { this.preloadData(); } /** * Posts card data online and set the data to the state * @param data CardData */ post(data: CardData): Observable<CardData> { return this.http.post<CardData>(this.sheetURL, data); } /** * GET the existing card data from API */ get(): Observable<CardData[]> { return this.http.get<CardData[]>(this.sheetURL); } delete(index: number): Observable<CardData> { return this.http.delete<CardData>(`${this.sheetURL}/${index}`); } /** * Instantiate the loading of card data from API */ preloadData() { this.get() .pipe( /** We need to reformat the card number to make it readable */ map(rawData => rawData.map(each => ({ ...each, cardNumber: this.helpersService.formatCardNumber(String(each.cardNumber), true) }))) ).subscribe(data => { console.log(data); this.store.dispatch(CardActions.InitializeCard({ data: data })); }, error => { console.log(error); }); } }<file_sep>/src/app/app.component.ts import { NotificationService } from './services/notification.service'; import { NavigationEnd, Router } from '@angular/router'; import { PaymentService } from './services/payment.service'; import { Component } from '@angular/core'; import { BehaviorSubject, Observable } from 'rxjs'; import { AppState, CardData } from './store-setup/interfaces'; import { Store } from '@ngrx/store'; import * as CardActions from './store-setup/card.actions'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.scss'] }) export class AppComponent { title = 'card-dto'; cardData: Observable<CardData[]>; isHomeUrl = false; isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false as boolean); indexToDelete: number = -1; constructor( private paymentService: PaymentService, private store: Store<AppState>, private router: Router, private notificationService: NotificationService ) { this.routerEvent(); this.cardData = this.store.select('cardData'); } routerEvent() { this.router.events.subscribe(event => { if (event instanceof NavigationEnd) { console.log(event.url); this.isHomeUrl = event.url == '/' || event.url == '' ? true : false; } }); } deleteCardData(index: number) { this.indexToDelete = index; this.isLoading.next(true); this.paymentService.delete(index).subscribe( _ => { this.indexToDelete = -1; this.isLoading.next(false); this.store.dispatch(CardActions.DeleteCard({index})); this.notificationService.showToast('Card Data deleted successfully'); }, error => { this.indexToDelete = -1; this.isLoading.next(false); this.notificationService.showToast('Ooops! An error occured while processing your request') }); } } <file_sep>/src/app/store-setup/card.actions.ts import { CardData } from './interfaces'; import { createAction, props } from '@ngrx/store'; const INIT_CARD = '[CARD] Init'; const ADD_CARD = '[CARD] Add'; const DELETE_CARD = '[CARD] Delete'; export const InitializeCard = createAction( INIT_CARD, props<{data: CardData[]}>() ); export const AddCard = createAction( ADD_CARD, props<{data: CardData}>() ); export const DeleteCard = createAction( DELETE_CARD, props<{ index: number }>() ); export const actions = { ADD_CARD, DELETE_CARD };<file_sep>/src/app/services/request.interceptor.ts import { NotificationService } from './notification.service'; import { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor, HttpResponse, HttpErrorResponse } from '@angular/common/http'; import { Observable, throwError } from 'rxjs'; import { map, catchError, timeout } from 'rxjs/operators'; import { Injectable, InjectionToken, Inject } from '@angular/core'; export const DEFAULT_TIMEOUT = new InjectionToken<number>('defaultTimeout'); @Injectable() export class RequestInterceptor implements HttpInterceptor { constructor( @Inject(DEFAULT_TIMEOUT) protected defaultTimeout: number = 30, private notificationService: NotificationService ) { } intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> { request = request.clone({ setHeaders: { 'content-type': 'application/json', Accept: 'application/json' } }); const timeoutValue = request.headers.get('timeout') || this.defaultTimeout; const timeoutValueNumeric = Number(timeoutValue); let timer = 0; timer += 1; if (!window.navigator.onLine) { return throwError(this.manageError('Please check your internet connection and try again')); } else { return next.handle(request).pipe(timeout(timeoutValueNumeric), map((event: HttpEvent<any>) => { const inter = setInterval(() => { timer += 1; if (timer === 30) { timer = 0; clearInterval(inter); } }, 1000); if (event instanceof HttpResponse) { if (timer >= 30) { // this.notification.showToast('Request timed out!'); throw(new Error('Request timed out! Check your network and try again')); } clearInterval(inter); } return event; }), catchError((error: HttpErrorResponse) => { console.log(error); if (error.error instanceof ErrorEvent) { return throwError(error.error.message); } else { if (error.status === 0) { return throwError(this.manageError('Please check your internet connection and try again')); } else { return throwError(this.manageError('Request timeout. Please try again')); } } }) ); } } manageError(message: string) { this.notificationService.showToast(message); } } <file_sep>/src/app/pages/make-payment/make-payment.component.ts import { NotificationService } from './../../services/notification.service'; import { PaymentService } from './../../services/payment.service'; import { Component } from '@angular/core'; import { FormControl, FormGroup, Validators } from '@angular/forms'; import * as CardActions from './../../store-setup/card.actions'; import { BehaviorSubject } from 'rxjs'; import { Store } from '@ngrx/store'; import { AppState } from 'src/app/store-setup/interfaces'; import { HelpersService } from 'src/app/services/helpers.service'; import { Router } from '@angular/router'; @Component({ selector: 'app-make-payment', templateUrl: './make-payment.component.html', styleUrls: ['./make-payment.component.scss'] }) export class MakePaymentComponent { paymentForm: FormGroup = new FormGroup({ cardNumber: new FormControl("", [Validators.required, Validators.maxLength(24), Validators.minLength(16)]), cardHolder: new FormControl("", [Validators.required, Validators.minLength(5)]), expiryDate: new FormControl("", [Validators.required, Validators.maxLength(5), Validators.pattern(/^((0[1-9])|(1[0-2]))[\/\.\-]*((2[1-9])|(3[0]))$/)]), securityCode: new FormControl(""), amount: new FormControl("", [Validators.required, Validators.min(1)]), }); isLoading: BehaviorSubject<boolean> = new BehaviorSubject(false as boolean); constructor( private paymentService: PaymentService, private store: Store<AppState>, private notificationService: NotificationService, private helpersService: HelpersService, private router: Router ) { } formatExpiryDate(ev: any) { this.paymentForm.patchValue({ expiryDate: this.helpersService.formatExpiryDate(this.paymentForm.value.expiryDate) }); } formatCardNumber(event: any) { this.paymentForm.patchValue({ cardNumber: this.helpersService.formatCardNumber(this.paymentForm.value.cardNumber) }); } submitPayment() { this.isLoading.next(true); const formatedData = { cardNumber: this.helpersService.removeDashes(this.paymentForm.value.cardNumber) }; this.paymentService.post(this.paymentForm.value).subscribe(data => { this.store.dispatch(CardActions.AddCard({ data: {...this.paymentForm.value, cardNumber: this.helpersService.formatCardNumber(formatedData.cardNumber, true)}})); this.notificationService.showToast('Payment successful'); this.isLoading.next(false); this.router.navigate(['/']); }, error => { this.isLoading.next(false); this.notificationService.showToast('Sorry, an error occured while processing your request') }); } }
6dd020f3e9c3165607c602fdc7efba97ac423105
[ "TypeScript" ]
11
TypeScript
Johnvict/card-dto
78172e07f7472af52fe4dc82b97d6241957cb86d
adfb21006c80b77cd07d58ae45b0b2bce13d938b
refs/heads/main
<file_sep>#include <iostream> #include<iomanip> #include<fstream> #include<stdio.h> #include<stdlib.h> using namespace std; /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char** argv) { cout<<"opa"<<endl; ifstream txtFile; int li= 0; int col= 0; int m[100] [100]; int numeros; int numbers; int l; int c; int r; int contador; int counter; FILE *arquivo; arquivo = fopen("atividade4.txt","wt" ); if(arquivo==NULL){ printf("Nao deu"); exit(0); } // code in english /*cout<< "enter the amount of line"<<endl; cout<<"enter the ammount of column"<<endl; for(counter= 1; counter<= max; counter){ cout<<"enter the numbers"<<endl; cin>>numbers; fprintf(arquivo, " %d ",numbers); }*/ // Parte que constroi o grafo cout<< "digite a quantidade de linha" << endl; cin>>li; cout<<"Digite a quantidade de coluna" << endl; cin>>col; fprintf(arquivo," %d ",li ); fprintf(arquivo, " %d ",col); fprintf(arquivo, "\n"); cout<< m[li] [col]<<endl; int max = li* col; for(contador = 1; contador<=max;contador++){ cout<<"coloca os numeros "<<endl; cin>>numeros; fprintf (arquivo," %d ",numeros); } fclose (arquivo); txtFile.open("atividade4.txt"); txtFile >> l >> c; for(int i=0; i<l; i++) { for(int j=0; j<c;j++) { txtFile >> m[i] [j]; } } // code in english /*cout<<"Read size array"<< l << " x "<< c << endl; cout<<"matrix contents in the file:"<< endl;*/ cout<<"Ler matriz de tamanho " << l <<" x " << c <<endl; cout<< "conteudo da matriz no arquivo:" << endl; for(int i=0;i<l;i++) { for(int j=0;j<c;j++) { cout << m[i] [j] << " - "; } cout << endl; } arquivo = fopen("atividade4s.txt","w" ); if(arquivo==NULL){ printf("Nao deu"); exit(0); } // code in english //fprintf(arquivo, " matrix contents in the file:") fprintf(arquivo,"conteudo da Matriz resultado:"); fprintf (arquivo,"%d", l); fprintf(arquivo,"x"); fprintf(arquivo,"%d", c); fprintf(arquivo,"\n"); for(int i=0;i<l;i++) { for(int j=0;j<c;j++) { fprintf (arquivo, "%d-", m[i] [j]); } fprintf(arquivo,"\n"); } fprintf(arquivo,"Codigo de O<NAME>"); cout<<"Codigo de <NAME>"<<endl; return 1; system("pause"); }
6afe760aef88c95d8f1c06a2420b1d978f27c200
[ "C++" ]
1
C++
Otavioo361/constru-de-grafo
a653c18a44d8de5c974274309019fda539f13a6e
a9eb4fe696229ae784f566fd5b57aeaa75b26016
refs/heads/master
<repo_name>anaoktaa/admin-dashboard<file_sep>/src/components/custom-timeline/custom-timeline.component.js import React from 'react'; const CustomTimeline = ({ size, children, ...props }) => { const childrenWithProps = React.Children.map(children, child => { // checking isValidElement is the safe way and avoids a typescript error too const props = { size }; if (React.isValidElement(child)) { return React.cloneElement(child, props); } return child; }); return ( <div className='flex-column' {...props}> {childrenWithProps} </div> ) }; export default CustomTimeline;<file_sep>/src/pages/chart-boxes/chart-boxes-variation-1/colors/colors.component.js import React from 'react'; import { SettingOutlined, DesktopOutlined, RocketOutlined, RobotOutlined, GiftOutlined, FireOutlined, HeartOutlined, StarOutlined } from '@ant-design/icons'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; const Colors = () => { return ( <div className='grid-3-gap-30 mb-30'> <ChartBoxVar1 icon={<SettingOutlined />} bgColor='primary' iconBgColor='#eaeaea42' iconColor='white' defaultValue='45.8k' defaultValueDescription='Total Views' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='175.5%' progressValueColor='warning' zoom={true} /> <ChartBoxVar1 icon={<DesktopOutlined />} bgColor='success' iconBgColor='white' iconColor='success' defaultValue='17.2k' defaultValueDescription='Profiles' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='left' progressValue='175.5%' progressValueColor='white' zoom={true} /> <ChartBoxVar1 icon={<RocketOutlined />} bgColor='warning' iconBgColor='#eaeaea42' iconColor='white' defaultValue='5.82k' defaultValueDescription='Reports Submitted' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='54.1%' progressValueColor='white' zoom={true} /> <ChartBoxVar1 icon={<RobotOutlined />} bgColor='dark' iconBgColor='#eaeaea42' iconColor='white' defaultValue='5.82k' defaultValueDescription='Bugs Fixed' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='right' progressValue='182.2%' progressValueColor='info' /> <ChartBoxVar1 icon={<GiftOutlined />} bgColor='danger' iconBgColor='#eaeaea42' iconColor='white' defaultValue='5.82k' defaultValueDescription='Reports Submitted' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='182.2%' progressValueColor='white' /> <ChartBoxVar1 icon={<FireOutlined />} bgColor='info' iconBgColor='#eaeaea42' iconColor='white' defaultValue='5.82k' defaultValueDescription='Bugs Fixed' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='182.2%' progressValueColor='white' /> <ChartBoxVar1 bgColor='linear-gradient(to bottom,#3ed68a,#9071cc)' icon={<SettingOutlined />} iconBgColor='#fff' iconColor='#3ac47d' defaultValue='23k' defaultValueDescColor='#fff' defaultValueColor='#fff' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='#fff' /> <ChartBoxVar1 bgColor='linear-gradient(to right, #654ea3, #eaafc8)' icon={<HeartOutlined />} iconBgColor='#eaeaea42' iconColor='#654ea3' defaultValue='2.34k' defaultValueDescColor='#fff' defaultValueColor='#fff' defaultValueDescription='Profile' progressValueArrow='up' progressValue='176%' progressValueColor='#fff' zoom={true} /> <ChartBoxVar1 bgColor='linear-gradient(to right, #ff7e5f, #feb47b)' icon={<StarOutlined />} iconBgColor='#fff' iconColor='#feb47b' defaultValue='67.3k' defaultValueDescColor='#fff' defaultValueColor='#fff' defaultValueDescription='Reports Submitted' progressValueArrow='up' progressValue='190.2%' progressValueColor='#fff' /> </div> ) }; export default Colors;<file_sep>/src/pages/applications-chat/applications-chat.component.js import React, { useState } from 'react'; import { Avatar, Typography, Input } from 'antd'; import { SearchOutlined, SettingOutlined, MenuOutlined, CloseOutlined } from '@ant-design/icons'; import CustomButton from 'Components/custom-button/custom-button.component'; import CustomBadges from 'Components/custom-badges/custom-badges.component'; import CustomMenu from 'Components/custom-menu/custom-menu.component'; import CustomLabelBadges from 'Components/custom-label-badge/custom-label-badge.component'; import CustomMenuItem from 'Components/custom-menu-item/custom-menu-item.component'; import ChatBallon from 'Components/chat-ballon/chat-ballon.component'; import { CustomMenuItemHeader, CustomMenuDivider } from 'Components/custom-menu-item/custom-menu-item.styles'; import { MailboxData } from '../applications-mailbox/application-mailbox.data'; import { ChatList } from './application-chat.data'; import './applications-chat.styles.css'; const { Text } = Typography; const ApplicationChat = () => { const [ chatMenu, setChatMenu ] = useState(false); const HandleToggleChatMenu = () => { setChatMenu(!chatMenu); } return ( <div className='chat-apps-container'> <div className={`chat-inbox-list-container ${chatMenu? 'chat-inbox-list-container-show': ''}`}> <div className='width-100 padding-horizontal-20' > <Input addonBefore={<SearchOutlined />} placeholder='Search...' /> </div> <CustomMenu className='padding-top-20' role='secondary'> <CustomMenuItemHeader className='gray'> FRIENDS ONLINE </CustomMenuItemHeader> { MailboxData.map((item) => ( <CustomMenuItem activeColor='primary' active={item.activechat} key={item.id} className='chat-list-container'> <CustomBadges href='https://twitter.com' target='_blank' position='bottom' color='success' size={10} dot> <Avatar size={40} src={item.picture}/> </CustomBadges> <div className='chat-wrapper text-overflow width-100'> <div className='flex-row justify-content-space-between align-items-start'> <p className={`${item.activechat? 'chat-profile-name-active' : 'chat-profile-name'}`}>{item.name}</p> <p className='chat-date'>{item.datechat}</p> </div> <div className='flex-row justify-content-space-between align-items-start'> <p className={`${item.activechat? 'chat-detail-active' : 'chat-detail-list'}`}> {item.chat} </p> { item.unread? <CustomLabelBadges color='danger' pill={true}>{item.unread}</CustomLabelBadges> : null } </div> </div> </CustomMenuItem> )) } <CustomMenuDivider/> <CustomMenuItemHeader className='gray'> OFFLINE FRIENDS </CustomMenuItemHeader> </CustomMenu> <div className='flex-row padding-top-10 justify-content-center flex-wrap'> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='danger' position='bottom' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='danger' position='bottom' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank'className='mrb-10' color='danger' position='bottom' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='danger' position='bottom' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='danger' position='bottom' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> </div> <div className='padding-top-10'> <CustomButton variant='solid' color='success' pill >Offline Group Conversations</CustomButton> </div> </div> <div className={`chat-content-container ${chatMenu? 'chat-content-container-show' : ''}`}> <div className='chat-content-header flex-row justify-content-space-between align-items-center'> <div className='flex-row'> <div className='menu-chat-apps'> { chatMenu? <CloseOutlined onClick={HandleToggleChatMenu} style={{fontSize: '20px'}} className={`mr-20 close-menu ${chatMenu? 'show-close-menu' : ''}`}/> : <MenuOutlined onClick={HandleToggleChatMenu} style={{fontSize: '20px'}} className={`mr-20 close-menu ${chatMenu? '' : 'show-close-menu'}`} /> } <div className='mr-20'> <CustomBadges position='bottom' color='success' size={13} dot> <Avatar shape='square' size={38} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> </div> <div className='active-chat-profile-wrapper'> <p className='active-chat-profile-name'>Silaladungka</p> <Text className='gray fs-12'>Last seen : </Text> <Text className='fs-12' type="secondary">10 minutes ago</Text> </div> </div> <div className='menu-chat-apps-desktop'> <div className='flex-row'> <div className='mr-20'> <CustomBadges position='bottom' color='success' size={13} dot> <Avatar shape='square' size={45} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> </div> <div className='active-chat-profile-wrapper'> <p className='active-chat-profile-name'>Silaladungka</p> <Text className='gray'>Last seen online : </Text> <Text type="secondary">10 minutes ago</Text> </div> </div> <CustomButton color='primary' variant='solid' icon={<SettingOutlined />}> Actions </CustomButton> </div> </div> </div> <div className='chat-list-active-container'> <ChatBallon chatlist={ChatList} className='chat-box-container' /> <div className='text-input-chat-container'> <Input placeholder='Write here and hit enter to send...' /> </div> </div> </div> </div> ) }; export default ApplicationChat;<file_sep>/src/pages/element-badges-and-labels/labels-container/labels-container.component.js import React from 'react'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import CustomButton from 'Components/custom-button/custom-button.component'; const LabelsContainer = () => { return ( <div className='grid-2-gap-30'> <div> <CustomCard> <CustomCardTitleText> COLORS </CustomCardTitleText> <CustomCardBody> <CustomLabelBadge className='mrb-10' color='primary'> Primary </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='secondary'> Secondary </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='info'> Info </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='success'> Success </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='warning'> Warning </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='danger'> Danger </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='alt'> Alt </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='light'> Light </CustomLabelBadge> <CustomLabelBadge className='mrb-10' color='dark'> Dark </CustomLabelBadge> </CustomCardBody> <div className='line'/> <CustomCardTitleText> PILLS </CustomCardTitleText> <CustomCardBody> <CustomLabelBadge pill className='mrb-10' color='primary'> Primary </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='secondary'> Secondary </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='info'> Info </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='success'> Success </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='warning'> Warning </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='danger'> Danger </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='alt'> Alt </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='light'> Light </CustomLabelBadge> <CustomLabelBadge pill className='mrb-10' color='dark'> Dark </CustomLabelBadge> </CustomCardBody> <div className='line'/> <CustomCardTitleText> LINKS </CustomCardTitleText> <CustomCardBody> <CustomLabelBadge className='mrb-10' link href='https://twitter.com' target='_blank' className='mrb-10' color='primary'> Primary </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='secondary'> Secondary </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='info'> Info </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='success'> Success </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='warning'> Warning </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='danger'> Danger </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='alt'> Alt </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='light'> Light </CustomLabelBadge> <CustomLabelBadge link className='mrb-10' color='dark'> Dark </CustomLabelBadge> </CustomCardBody> </CustomCard> </div> <div> <CustomCard> <CustomCardTitleText> WITH BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' color='primary' variant='solid'> Primary <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='secondary' variant='solid'> Secondary <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='success' variant='solid'> Success <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='info' variant='solid'> Info <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='warning' variant='solid'> Warning <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='danger' variant='solid'> Danger <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='alt' variant='solid'> Alt <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='light' variant='solid'> Light <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='dark' variant='solid'> Dark <CustomLabelBadge className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomLabelBadge color='primary' className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomLabelBadge color='warning' className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomLabelBadge color='success' className='ml-5'>NEW</CustomLabelBadge> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomLabelBadge color='danger' className='ml-5'>NEW</CustomLabelBadge> </CustomButton> </CustomCardBody> </CustomCard> </div> </div> ) }; export default LabelsContainer;<file_sep>/src/components/custom-header/custom-header.component.js import React, { useState, useRef, useEffect } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; import { Typography, Avatar } from 'antd'; import admindash from '../../assets/logo/admin-dash.png'; import german from '../../assets/logo/german.png'; import './custom-header.styles.css'; import '../../App.css'; import { MenuUnfoldOutlined, GiftOutlined, SettingOutlined, MenuOutlined, MoreOutlined, MenuFoldOutlined, CloseOutlined, AppstoreOutlined, BellOutlined, RocketOutlined, DownOutlined } from '@ant-design/icons'; import { selectFoldDrawer, selectMegaMenuToggle, selectSettingHeaderToggle, selectFloatingHeaderTools, selectGridDashboardToggle, selectNotifHeaderToggle, selectLangHeaderToggle, selectActiveUserHeaderToggle, selectProfileHeaderToggle } from 'Redux_Component/application/application.selectors'; import { setFoldDrawer, setMegaMenuToggle, setSettingHeaderToggle, setFloatingHeaderTools, setGridDashboardToggle, setNotifHeaderToggle, setLangHeaderToggle, setActiveUserHeaderToggle, setProfileHeaderToggle } from 'Redux_Component/application/application.actions'; import onClickOutside from 'Components/onclick-outside/onclick-outside.component'; import withWindowResize from 'Components/with-window-resize/with-window-resize.component'; import MegaMenu from 'Components/mega-menu/mega-menu.component'; import SettingHeader from 'Components/setting-header/setting-header.component'; import SearchHeader from 'Components/search-header/search-header.component'; import GridMenu from 'Components/grid-menu/grid-menu.component'; import NotifHeader from 'Components/notif-header/notif-header.component'; import LangHeader from 'Components/lang-header/lang-header.component'; import ActiveUserHeader from 'Components/active-user-header/active-user-header.component'; import ProfileHeader from 'Components/profile-header/profile-header.component'; const { Text } = Typography; const CustomHeader = ({ foldDrawer, setFoldDrawer, megaMenuToggle, setMegaMenuToggle, actualSize, settingMenuToggle, setSettingHeaderToggle, setFloatingHeaderTools, floatingHeader,setGridDashboardToggle, gridMenuToggle, setNotifHeaderToggle, notifMenuToggle, setLangHeaderToggle, langMenuToggle, setActiveUserHeaderToggle, activeUserMenuToggle, setProfileHeaderToggle, profileMenuToggle }) => { const refMegaMenu = useRef(); const refSettingMenu = useRef(); const refGridMenu = useRef(); const refNotifMenu = useRef(); const refLangMenu = useRef(); const refActiveUserMenu = useRef(); const refProfileMenu = useRef(); const [showInputSearch, setShowInputSearch] = useState(false); const handleShowInputSearch = () => { if (!foldDrawer && !showInputSearch && actualSize.width <= 1024) { setFoldDrawer(false); } setShowInputSearch(!showInputSearch); } const handleMegaMenu = () => { if (!megaMenuToggle) { setMegaMenuToggle(!megaMenuToggle); } else { setMegaMenuToggle(!megaMenuToggle); } } const handleSettingMenu = () => { setSettingHeaderToggle(!settingMenuToggle); } const handleFoldDrawer = () => { if (showInputSearch && actualSize.width <= 1024) { setShowInputSearch(!showInputSearch); } setFoldDrawer(true); } const handleUnfoldDrawer = () => { setFoldDrawer(false); } const handleFloatingHeaderTool = () => { setFloatingHeaderTools(!floatingHeader); } const handleGridMenu = () => { setGridDashboardToggle(!gridMenuToggle); } const handleNotifMenu = () => { setNotifHeaderToggle(!notifMenuToggle); } const handleLangMenu = () => { setLangHeaderToggle(!langMenuToggle); } const handleProfileMenu = () => { setProfileHeaderToggle(!profileMenuToggle); } const handleActiveUserMenu = () => { setActiveUserHeaderToggle(!activeUserMenuToggle); } const handleOutsideMenu = (name) => { if (actualSize.width >= 986) { if (megaMenuToggle && name === 'megaMenu') { setMegaMenuToggle(false); } else if (settingMenuToggle && name === 'settingMenu') { setSettingHeaderToggle(false); } else if (gridMenuToggle && name === 'gridMenu') { setGridDashboardToggle(false); } else if (notifMenuToggle && name === 'notifMenu') { setNotifHeaderToggle(false); } else if (langMenuToggle && name === 'langMenu') { setLangHeaderToggle(false); } else if (activeUserMenuToggle && name === 'activeUserMenu') { setActiveUserHeaderToggle(false); } else if (profileMenuToggle && name === 'profileMenu') { setProfileHeaderToggle(false); } } } onClickOutside(refMegaMenu, handleOutsideMenu, 'megaMenu'); onClickOutside(refSettingMenu, handleOutsideMenu, 'settingMenu'); onClickOutside(refGridMenu, handleOutsideMenu, 'gridMenu'); onClickOutside(refNotifMenu, handleOutsideMenu, 'notifMenu'); onClickOutside(refLangMenu, handleOutsideMenu, 'langMenu'); onClickOutside(refActiveUserMenu, handleOutsideMenu, 'activeUserMenu'); onClickOutside(refProfileMenu, handleOutsideMenu, 'profileMenu'); return ( <div className={`header-styles-container ${foldDrawer ? 'header-styles-drawer-open ' : 'header-styles-drawer-close '}`}> <div className='desktop-header-view'> <div className='flex-space-center'> <div className='header-left-menu'> { foldDrawer? <MenuUnfoldOutlined onClick={handleUnfoldDrawer} className='header-menu-fold-icon' /> : <MenuFoldOutlined onClick={handleFoldDrawer} className='header-menu-fold-icon' /> } <SearchHeader showInputSearch={showInputSearch} handleShowInputSearch={handleShowInputSearch} /> <div ref={refMegaMenu} className='header-link-wrapper'> <Text onClick={handleMegaMenu} className={`header-link-menu ${!foldDrawer || showInputSearch ? 'header-link-menu-hidden' : ''}`} ><GiftOutlined /> Mega Menu</Text> <MegaMenu show={megaMenuToggle} /> </div> <div ref={refSettingMenu} className='header-link-wrapper'> <Text onClick={handleSettingMenu} className={`header-link-menu ${!foldDrawer || showInputSearch ? 'header-link-menu-hidden' : ''}`} ><SettingOutlined /> Settings</Text> <SettingHeader show={settingMenuToggle}/> </div> </div> <div className='header-right-menu'> <div ref={refGridMenu} className='header-avatar-wrap'> <Avatar onClick={handleGridMenu} className='grid-header-avatar' size={40}><AppstoreOutlined /></Avatar> <GridMenu show={gridMenuToggle}/> </div> <div ref={refNotifMenu} className='header-avatar-wrap'> <div onClick={handleNotifMenu} className='notif-header-wrapper'> <Avatar className='notif-header-avatar' size={40}> <BellOutlined /> </Avatar> <div className='notif-badge'/> </div> <NotifHeader show={notifMenuToggle}/> </div> <div ref={refLangMenu} className='header-avatar-wrap'> <Avatar onClick={handleLangMenu} size={40} className='lang-header-avatar' icon={<img src={german} alt='lang' style={{width: '65%', height: '65%'}}/>} /> <LangHeader show={langMenuToggle}/> </div> <div ref={refActiveUserMenu} className='header-avatar-wrap'> <Avatar onClick={handleActiveUserMenu} size={40} className='user-header-avatar'><RocketOutlined /></Avatar> <ActiveUserHeader show={activeUserMenuToggle}/> </div> <div ref={refProfileMenu} className='header-avatar-wrap'> <Avatar onClick={handleProfileMenu} size={40} className='profile-header-avatar' src="https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80" /> <DownOutlined className='profile-down-icon'/> <ProfileHeader show={profileMenuToggle}/> </div> <div className='header-avatar-wrap-column'> <p className='profile-name'><NAME></p> <p className='profile-position'>Software Engineer</p> </div> </div> </div> </div> <div className='mobile-tablet-header-view'> <div className='header-mobile-menu'> <div className='menu-drawer-icon-container'> <MenuOutlined onClick={handleUnfoldDrawer} className={`${foldDrawer ? 'burger-icon' : 'hidden-burger-icon'}`} /> <CloseOutlined onClick={handleFoldDrawer} className={`${foldDrawer? 'close-drawer-icon' : 'show-close-drawer-icon'}`} /> </div> <div> <img src={admindash} alt='admin-dash' width='100%' height='100%' /> </div> <div onClick={handleFloatingHeaderTool} className='more-outline-wrapper'> <MoreOutlined className='header-menu-more-outlined-icon' /> </div> </div> </div> </div> ) }; const mapStateToProps = createStructuredSelector({ settingMenuToggle: selectSettingHeaderToggle, foldDrawer: selectFoldDrawer, megaMenuToggle: selectMegaMenuToggle, floatingHeader: selectFloatingHeaderTools, gridMenuToggle: selectGridDashboardToggle, notifMenuToggle: selectNotifHeaderToggle, langMenuToggle: selectLangHeaderToggle, activeUserMenuToggle: selectActiveUserHeaderToggle, profileMenuToggle: selectProfileHeaderToggle }); const mapDispatchToProps = dispatch => ({ setSettingHeaderToggle: (val) => dispatch(setSettingHeaderToggle(val)), setFoldDrawer: (data) => dispatch(setFoldDrawer(data)), setMegaMenuToggle: (val) => dispatch(setMegaMenuToggle(val)), setFloatingHeaderTools: (val) => dispatch(setFloatingHeaderTools(val)), setGridDashboardToggle: (val) => dispatch(setGridDashboardToggle(val)), setNotifHeaderToggle: (val) => dispatch(setNotifHeaderToggle(val)), setLangHeaderToggle: (val) => dispatch(setLangHeaderToggle(val)), setActiveUserHeaderToggle: (val) => dispatch(setActiveUserHeaderToggle(val)), setProfileHeaderToggle: (val) => dispatch(setProfileHeaderToggle(val)) }); export default connect(mapStateToProps, mapDispatchToProps)(withWindowResize(CustomHeader));<file_sep>/src/pages/chart-boxes/chart-boxes-variation-1/chart-boxes-variation-1.component.js import React from 'react'; import CustomTabsWrapper from 'Components/custom-tabs-wrapper/custom-tabs-wrapper.component'; import CustomTabPanel from 'Components/custom-tab-panel/custom-tab-panel.component'; import Basic from './basic/basic.component'; import Colors from './colors/colors.component'; import Grids from './grids/grids.component'; import Alignments from './alignments/alignments.component'; import ProgressCircle from './progress-circle/progress-circle.component'; const ChartBoxesVariation1 = () => { return ( <CustomTabsWrapper> <CustomTabPanel data-key='basic' title='Basic'> <Basic/> </CustomTabPanel> <CustomTabPanel data-key='colors' title='Colors'> <Colors/> </CustomTabPanel> <CustomTabPanel data-key='grids' title='Grids'> <Grids/> </CustomTabPanel> <CustomTabPanel data-key='alignments' title='Alignments'> <Alignments/> </CustomTabPanel> <CustomTabPanel data-key='progress-circle' title='Progress Circle'> <ProgressCircle/> </CustomTabPanel> </CustomTabsWrapper> ) }; export default ChartBoxesVariation1;<file_sep>/src/pages/applications-faq/tab-example-1.component.js import React from 'react'; import { Collapse, Typography } from 'antd'; import AccountInformation from './account-information.component'; import CCInformation from './cc-information.component'; import './applications-faq.styles.css'; const { Panel } = Collapse; const { Title, Text } = Typography; const TabExample1 = () => { const TabExample1Content = [ { id: 1, title: 'Account Information', description: 'Enter your informations below', content: <AccountInformation/> }, { id: 2, title: 'Credit Card Informations', description: 'Enter your informations below', content: <CCInformation/> }, { id: 3, title: 'Personal Details', description: 'Enter your informations below', content: <CCInformation/> } ]; return ( <Collapse> { TabExample1Content.map((panel) => ( <Panel showArrow={false} style={{backgroundColor: 'white'}} key={panel.id} header={ <div> <Title className='primary-color' level={4}>{panel.title}</Title> <Text>{panel.description}</Text> </div> }> {panel.content} </Panel> )) } </Collapse> ) }; export default TabExample1;<file_sep>/src/components/custom-menu/custom-menu.component.js import React from 'react'; import { CustomMenuStyled } from './custom-menu.styles'; const CustomMenu = ({ pill, role, border, children, ...props }) => { const childrenWithProps = React.Children.map(children, child => { // checking isValidElement is the safe way and avoids a typescript error too const props = { role, pill, border }; if (React.isValidElement(child)) { if (child.type.name === 'CustomMenuItem') return React.cloneElement(child, props); return React.cloneElement(child); } return child; }); return ( <CustomMenuStyled {...props}> {childrenWithProps} </CustomMenuStyled> ) }; export default CustomMenu;<file_sep>/src/pages/dashboard-crm/dashboard-crm-var-1/dashboard-crm-var-1.component.js import React from 'react'; import { Line } from 'react-chartjs-2'; import { Typography, Progress, Table, Avatar } from 'antd'; import { DownOutlined, UpOutlined } from '@ant-design/icons'; import { CustomCard, BorderBottomCard, CustomCardBody, CustomCardHeader, CustomCardFooter } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import { colorsPalette } from 'Components/custom-color/custom-color'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import CustomButton from 'Components/custom-button/custom-button.component'; import { BandwidthReportData, ChartBox3Data, DataChart, DataChartComponentList } from '../dashboard-crm.data'; import { ColumnsEasyDynTable, DataEasyDynTable, DataHighlights2 } from 'Data/table.data'; import { Options6, Options8 } from 'Data/settings-chart.data'; const { Title } = Typography; const DashboardCrmVariation1 = () => { return ( <div> <div className='grid-3-gap-30 mb-30'> { ChartBox3Data.map(({ id, defaultValue, defaultValueColor, mainTitleText, descriptionText, progressBarValue, strokeWidth, progressBarColor, descriptionProgressDetail }) => ( <ChartBoxVar3 key={id} defaultValue={defaultValue} defaultValueColor={defaultValueColor} mainTitleText={mainTitleText} descriptionText={descriptionText} progressBarValue={progressBarValue} strokeWidth={strokeWidth} progressBarColor={progressBarColor} descriptionProgressDetail={descriptionProgressDetail} /> )) } </div> <div className='grid-2-gap-30 mb-30'> <div className='dcm-chart-boxes-1'> { DataChartComponentList.map(({id, value, description, graphData, borderColor}) => ( <CustomCard className='overflow-hidden' key={id}> <CustomCardBody className='relative'> <div className='mb-10'> <Title level={2} className='fw-400 color5d no-margin-no-padding '><span className='color98'>$</span>{value}</Title> <Title level={5} className='fw-400 color98 no-margin-no-padding'>{description}</Title> </div> <Line data={graphData} width={100} height={40} options={Options6} /> <BorderBottomCard bgColor={borderColor}/> </CustomCardBody> </CustomCard> )) } </div> <CustomCard className='overflow-hidden' > <CustomCardHeader>Bandwidth Reports</CustomCardHeader> <CustomCardBody> <div className='grid-2-gap-30 mb-30'> { BandwidthReportData.map((item) => ( <div key={item.id}> <div className='flex-row align-items-center'> <Title level={3} className={`fw-bold no-mb mr-20 ${(item.valueDetail.color) ? item.valueDetail.color : 'color5d'}`}>{item.valueDetail.value}</Title> { item.progress? <Progress strokeColor={`${colorsPalette[item.progress.color] ? colorsPalette[item.progress.color] : item.progress.color}`} percent={item.progress.value} size="small" showInfo={false} /> : null } </div> <Title level={5} className='color98 fw-400 no-margin-no-padding'>{item.description}</Title> </div> )) } </div> <Line data={DataChart.data5} width={100} height={50} options={Options6} /> </CustomCardBody> </CustomCard> </div> <CustomCard className='mb-30 overflow-auto'> <CustomCardHeader>Easy Dynamic Tables</CustomCardHeader> <CustomCardBody> <Table columns={ColumnsEasyDynTable} dataSource={DataEasyDynTable} /> </CustomCardBody> </CustomCard> <div className='dcm-grid-2-2 mb-30'> <div className='overflow-hidden'> <CustomCard className='overflow-hidden mb-30'> <CustomCardBody className='relative'> <Title level={3} className='fw-400 color5d no-margin-no-padding'>Received Messages</Title> <Title className='primary' style={{position: 'absolute', top: '50px', left: '70px'}} level={1}>348</Title> <Line data={DataChart.data6} width={100} height={70} options={Options6} /> <BorderBottomCard bgColor='primary'/> </CustomCardBody> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardBody className='relative'> <Title level={3} className='fw-400 color5d no-margin-no-padding '>Sent Messages</Title> <Title className='danger' style={{position: 'absolute', top: '50px', left: '70px'}} level={1}>348</Title> <Line data={DataChart.data7} width={100} height={70} options={Options6} /> <BorderBottomCard bgColor='danger'/> </CustomCardBody> </CustomCard> </div> <CustomCard className='overflow-hidden'> <CustomCardHeader>Sales Report</CustomCardHeader> <CustomCardBody> <div className='card-container text-align-left mb-30'> <div className='flex-row align-items-center padding-horizontal-20'> <Title level={1} className='fw-400 no-margin-no-padding '><span className='color98'>$</span>123&nbsp;</Title> <Title level={3} className='fw-400 color98 no-margin-no-padding'>Sales income</Title> </div> <Line data={DataChart.data1} width={100} height={20} options={Options8} /> </div> <p className='fs-14 color98 fw-400'>LAST MONTH HIGHTLIGHTS</p> <div className='height-300-only overflow-auto'> { DataHighlights2.map((item) => ( <div className='da-highlights-item'> <div className='flex-row align-items-center'> <Avatar className='mr-20' size={40} src={item.img} /> <div> <p className='color6d no-margin-no-padding'>{item.name}</p> </div> </div> <div className='flex-row-fit-content align-items-center'> <Title level={3} className='success'>{item.value}</Title> { item.icon.type === 'up' ? <UpOutlined className={item.icon.color} style={style.downIcon} /> : <DownOutlined className={item.icon.color} style={style.downIcon} /> } </div> </div> )) } </div> </CustomCardBody> </CustomCard> </div> <div className='grid-3-gap-30'> <CustomCard> <CustomCardHeaderWithImage backgroundColorOverlay='#545cd8' className='align-items-center flex-column'> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Lead UX Designer</p> </div> </CustomCardHeaderWithImage> <CustomCardFooter className='flex-column align-items-center justify-content-center' bgColor='#656ddc'> <CustomButton className='margin-top-8' color='dark' variant='solid'>Send Message</CustomButton> </CustomCardFooter> </CustomCard> <CustomCard> <CustomCardHeaderWithImage backgroundColorOverlay='#444054' className='align-items-center flex-column'> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Frontend UI Designer</p> </div> </CustomCardHeaderWithImage> <CustomCardFooter className='flex-column align-items-center justify-content-center' bgColor='#575365'> <CustomButton className='margin-top-8' color='warning' variant='solid'>Send Message</CustomButton> </CustomCardFooter> </CustomCard> <CustomCard> <CustomCardHeaderWithImage backgroundColorOverlay='#343a40' className='align-items-center flex-column'> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Backend Engineer</p> </div> </CustomCardHeaderWithImage> <CustomCardFooter className='flex-column align-items-center justify-content-center' bgColor='#494e53'> <CustomButton className='margin-top-8' color='success' variant='solid'>Send Message</CustomButton> </CustomCardFooter> </CustomCard> </div> </div> ) }; export default DashboardCrmVariation1; const style = { downIcon: { fontSize: '11px', marginLeft: '10px' }, settingIcon : { fontSize: '79px', color: '#a86799' } }; <file_sep>/src/pages/element-badges-and-labels/badges-container/badges-container.component.js import React from 'react'; import { LaptopOutlined, PictureOutlined, ShoppingOutlined, CrownOutlined, AlertOutlined, BugOutlined, DatabaseOutlined, MessageOutlined, BulbOutlined, RocketOutlined, TrophyOutlined, CameraOutlined, ThunderboltOutlined } from '@ant-design/icons'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import CustomBadges from 'Components/custom-badges/custom-badges.component'; import CustomButton from 'Components/custom-button/custom-button.component'; const BadgesContainer = () => { return ( <div className='grid-2-gap-30'> <div> <CustomCard className='mb-30'> <CustomCardTitleText> WITH BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' color='primary' variant='solid'> Primary <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='secondary' variant='solid'> Secondary <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='info' variant='solid'> Info <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='success' variant='solid'> Success <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='warning' variant='solid'> Warning <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='danger' variant='solid'> Danger <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='alt' variant='solid'> Alt <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='light' variant='solid'> Light <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='dark' variant='solid'> Dark <CustomBadges className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomBadges color='primary' className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomBadges color='success' className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomBadges color='danger' className='ml-5' number={2}/> </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid'> Link <CustomBadges color='warning' className='ml-5' number={2}/> </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> BADGE DOTS </CustomCardTitleText> <CustomCardBody> <div className='grid-3-gap-10'> <div> <CustomBadges className='mrb-5' color='primary' dot/> <CustomBadges className='mrb-5' color='secondary' dot/> <CustomBadges className='mrb-5' color='success' dot/> <CustomBadges className='mrb-5' color='info' dot/> <CustomBadges className='mrb-5' color='warning' dot/> <CustomBadges className='mrb-5' color='danger' dot/> <CustomBadges className='mrb-5' color='alt' dot/> <CustomBadges className='mrb-5' color='light' dot/> <CustomBadges className='mrb-5' color='dark' dot/> </div> <div> <CustomBadges size={7} className='mrb-5' color='primary' dot/> <CustomBadges size={7} className='mrb-5' color='secondary' dot/> <CustomBadges size={7} className='mrb-5' color='success' dot/> <CustomBadges size={7} className='mrb-5' color='info' dot/> <CustomBadges size={7} className='mrb-5' color='warning' dot/> <CustomBadges size={7} className='mrb-5' color='danger' dot/> <CustomBadges size={7} className='mrb-5' color='alt' dot/> <CustomBadges size={7} className='mrb-5' color='light' dot/> <CustomBadges size={7} className='mrb-5' color='dark' dot/> </div> <div> <CustomBadges size={10} className='mrb-5' color='primary' dot/> <CustomBadges size={10} className='mrb-5' color='secondary' dot/> <CustomBadges size={10} className='mrb-5' color='success' dot/> <CustomBadges size={10} className='mrb-5' color='info' dot/> <CustomBadges size={10} className='mrb-5' color='warning' dot/> <CustomBadges size={10} className='mrb-5' color='danger' dot/> <CustomBadges size={10} className='mrb-5' color='alt' dot/> <CustomBadges size={10} className='mrb-5' color='light' dot/> <CustomBadges size={10} className='mrb-5' color='dark' dot/> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> BADGE NUMBER </CustomCardTitleText> <CustomCardBody> <div> <CustomBadges className='mrb-5' color='primary' number={2}/> <CustomBadges className='mrb-5' color='secondary' number={2}/> <CustomBadges className='mrb-5' color='success' number={2}/> <CustomBadges className='mrb-5' color='info' number={2}/> <CustomBadges className='mrb-5' color='warning' number={2}/> <CustomBadges className='mrb-5' color='danger' number={2}/> <CustomBadges className='mrb-5' color='alt' number={2}/> <CustomBadges className='mrb-5' color='dark' number={2}/> <CustomBadges className='mrb-5' color='light' number={2}/> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> BADGE DOTS WITH BUTTON </CustomCardTitleText> <CustomCardBody> <CustomBadges className='mrb-10' color='secondary' size={12} dot> <CustomButton color='primary' variant='solid'> Primary </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='primary' size={12} dot> <CustomButton color='secondary' variant='solid'> Secondary </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='success' size={12} dot> <CustomButton color='success' variant='solid'> Success </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='info' size={12} dot> <CustomButton color='info' variant='solid'> Info </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='warning' size={12} dot> <CustomButton color='warning' variant='solid'> Warning </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='dark' size={12} dot> <CustomButton color='danger' variant='solid'> Danger </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='alt' size={12} dot> <CustomButton color='alt' variant='solid'> Alt </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='success' size={12} dot> <CustomButton color='light' variant='solid'> Light </CustomButton> </CustomBadges> <CustomBadges className='mrb-10' color='primary' size={12} dot> <CustomButton color='dark' variant='solid'> Dark </CustomButton> </CustomBadges> </CustomCardBody> </CustomCard> <CustomCard> <CustomCardTitleText> ICON WITH BADGES </CustomCardTitleText> <CustomCardBody> <CustomBadges className='mrb-20' color='secondary' size={12} dot> <LaptopOutlined style={style.iconStyle} /> </CustomBadges> <CustomBadges className='mrb-20' color='warning' size={12} dot> <PictureOutlined style={style.iconStyle} /> </CustomBadges> <CustomBadges className='mrb-20' color='danger' size={12} dot> <ShoppingOutlined style={style.iconStyle} /> </CustomBadges> <CustomBadges className='mrb-20' color='secondary' number={3}> <LaptopOutlined style={style.iconStyle} /> </CustomBadges> <CustomBadges className='mrb-20' color='warning' number={99}> <PictureOutlined style={style.iconStyle} /> </CustomBadges> <CustomBadges className='mrb-20' color='danger' size={12} dot> <ShoppingOutlined style={style.iconStyle} /> </CustomBadges> </CustomCardBody> </CustomCard> </div> <div> <CustomCard className='mb-30'> <CustomCardTitleText> ICON BUTTONS GRID I </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-3-col align-items-center justify-content-center'> <div className='grid-row-for-3-col'> <CustomBadges color='secondary' size={12} dot> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </CustomBadges> </div> <div className='grid-row-for-3-col'> <CustomBadges color='warning' size={10} dot> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </CustomBadges> </div> <div className='grid-row-for-3-col'> <CustomBadges color='primary' size={10} dot> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<TrophyOutlined />}> Danger </CustomButton> </CustomBadges> </div> <div className='grid-row-for-3-col'> <CustomBadges color='success' size={10} dot> <CustomButton square iconType='vertical' block color='warning' variant='no-outlined' icon={<RocketOutlined />}> Warning </CustomButton> </CustomBadges> </div> <div className='grid-row-for-3-col'> <CustomBadges color='alt' size={10} dot> <CustomButton square iconType='vertical' block color='info' variant='no-outlined' icon={<BulbOutlined />}> Info </CustomButton> </CustomBadges> </div> <div className='grid-row-for-3-col'> <CustomBadges color='dark' size={10} dot> <CustomButton square iconType='vertical' block color='secondary' variant='no-outlined' icon={<BugOutlined />}> Secondary </CustomButton> </CustomBadges> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> ICON BUTTONS GRID II </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomBadges color='secondary' size={12} dot> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </CustomBadges> </div> <div className='grid-row-for-2-col'> <CustomBadges color='warning' size={10} dot> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </CustomBadges> </div> <div className='grid-row-for-2-col'> <CustomBadges color='primary' size={10} dot> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<TrophyOutlined />}> Danger </CustomButton> </CustomBadges> </div> <div className='grid-row-for-2-col'> <CustomBadges color='success' size={10} dot> <CustomButton square iconType='vertical' block color='warning' variant='no-outlined' icon={<RocketOutlined />}> Warning </CustomButton> </CustomBadges> </div> </div> </CustomCardBody> </CustomCard> <CustomCard> <CustomCardTitleText> ICON BUTTONS GRID III </CustomCardTitleText> <CustomCardBody> <CustomBadges color='success' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='primary' variant='outlined' icon={<CrownOutlined />}> Primary </CustomButton> </CustomBadges> <CustomBadges color='primary' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='secondary' variant='outlined' icon={<AlertOutlined />}> Secondary </CustomButton> </CustomBadges> <CustomBadges color='warning' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='success' variant='outlined' icon={<CameraOutlined />}> Success </CustomButton> </CustomBadges> <CustomBadges color='danger' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='info' variant='outlined' icon={<BugOutlined />}> Info </CustomButton> </CustomBadges> <CustomBadges color='alt' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='warning' variant='outlined' icon={<BulbOutlined />}> Warning </CustomButton> </CustomBadges> <CustomBadges color='info' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='danger' variant='outlined' icon={<DatabaseOutlined />}> Danger </CustomButton> </CustomBadges> <CustomBadges color='secondary' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='alt' variant='outlined' icon={<MessageOutlined />}> Alt </CustomButton> </CustomBadges> <CustomBadges color='dark' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='light' variant='outlined' icon={<RocketOutlined />}> Light </CustomButton> </CustomBadges> <CustomBadges color='light' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='dark' variant='outlined' icon={<ThunderboltOutlined />}> Dark </CustomButton> </CustomBadges> <CustomBadges color='primary' className='mrb-10' size={10} dot> <CustomButton iconType='vertical' color='link' variant='outlined' icon={<TrophyOutlined />}> Link </CustomButton> </CustomBadges> </CustomCardBody> </CustomCard> </div> </div> ) }; const style = { iconStyle: { fontSize: 30, color: '#545cd8' } } export default BadgesContainer;<file_sep>/src/components/custom-card/custom-card.styles.js import styled, { css } from 'styled-components'; import { colorsPalette } from '../custom-color/custom-color'; const outlinedCard = css` border: 1px solid ${({outlined}) => outlined? colorsPalette[outlined] : 'transparent'}; `; const titleText = css` font-size: 14px; font-weight: 500; display: block; text-transform: uppercase; `; const hoverCard = css` &:hover { box-shadow: 0 0.46875rem 2.1875rem rgba(8,10,37,.03), 0 0.9375rem 1.40625rem rgb(8 10 37 / 8%), 0 0.25rem 0.53125rem rgb(33 35 64 / 23%), 0 0.125rem 0.1875rem rgb(8 10 37 / 21%); } `; export const BorderBottomCard = styled.div` position: absolute; left: 0; right: 0; bottom: 0; height: 4px; background-color: ${({bgColor}) => colorsPalette[bgColor]? colorsPalette[bgColor] : bgColor? bgColor : '#5d5d5d'}; `; const styleForCard = props => { if (props.outlined) { return outlinedCard; } if (props.contained) { return containedCard; } } const hoverStyleCard = props => { if (props.hover) { return hoverCard; } } export const CustomCard = styled.div` box-shadow: ${({noneBoxShadow}) => noneBoxShadow? 'none': ' 0 0.46875rem 2.1875rem rgba(8,10,37,.03), 0 0.9375rem 1.40625rem rgba(8,10,37,.03), 0 0.25rem 0.53125rem rgba(8,10,37,.05), 0 0.125rem 0.1875rem rgba(8,10,37,.03)'}; border-width: 0; transition: all .2s; border-radius: ${({noneBorderRadius}) => noneBorderRadius? '0px' : '5px'}; background-color: white; ${styleForCard}; ${hoverStyleCard}; height: fit-content; `; export const CustomCardBody = styled.div` padding: 15px; width: 100%; `; export const CustomCardHeader = styled.div` padding: 15px; ${titleText}; border-bottom: 1px solid #d6d6d6; `; export const CustomCardFooter = styled.div` padding: 15px; ${titleText}; border-top: ${({bgColor}) => bgColor? 'none' : '1px solid #d6d6d6'} ; display: flex; align-item: center; justify-content: flex-end; background-color: ${({bgColor}) => colorsPalette[bgColor]? colorsPalette[bgColor] : bgColor? bgColor : '#fff'}; `; export const CustomCardTitleText = styled.p` ${titleText}; margin: 0; padding: 15px 15px 0; color: #363875; `; export const CustomCardSubtitle = styled.p` font-size: 14px; color: ${({contained}) => contained? '#fff': '#a9a9a9'}; `; export const CardHeaderImg = styled.div` width: 100%; background-image: ${({imgUrl}) => imgUrl? `url(${imgUrl})` :null}; background-position: center; background-repeat: no-repeat; background-size: cover; color: white; position: relative; overflow-x: hidden; border-top-left-radius: ${({noneBorderRadius}) => noneBorderRadius? '0px' : '5px'}; border-top-right-radius: ${({noneBorderRadius}) => noneBorderRadius? '0px' : '5px'}; `; export const CardImgOverlay = styled.div` position: absolute; z-index: 10; top: 0; bottom: 0; left: 0; right: 0; background-color: ${({backgroundColorOverlay}) => colorsPalette[backgroundColorOverlay]? colorsPalette[backgroundColorOverlay] : backgroundColorOverlay? backgroundColorOverlay : '#252525bf'} `; const containedCard = css` color: ${({contained}) => contained? '#fff': '#000'}; ${CustomCardHeader} { background-color: ${({contained}) => colorsPalette[contained]? colorsPalette[contained] : contained? contained : '#fff'}; opacity: .92; border-bottom: none; } ${CustomCardFooter} { background-color: ${({contained}) => colorsPalette[contained]? colorsPalette[contained] : contained? contained : '#fff'}; opacity: .92; border-top: none; } ${CustomCardBody} { background-color: ${({contained}) => colorsPalette[contained]? colorsPalette[contained] : contained? contained : '#fff'}; } ${CustomCardTitleText} { color: ${({contained}) => contained? '#fff': '#495057'}; background-color: ${({contained}) => colorsPalette[contained]? colorsPalette[contained] : contained? contained : '#fff'}; } ${CustomCardSubtitle} { color: ${({contained}) => contained? '#fff': '#a9a9a9'}; } `; <file_sep>/src/components/chat-ballon/chat-ballon.component.js import React from 'react'; import { Avatar } from 'antd'; import { ChatBallonContainer, NotOwnerContainerChat, AvatarProfileContainer, ChatContainerText, TimeChat, ChatBallonOwnerContainer, OwnerContainerChat, ChatListEndWrapper, ChatListStartWrapper, ChatContainer } from './chat-ballon.styles'; const ChatBallon = ({ chatlist, ...props }) => { return ( <ChatContainer {...props}> { chatlist.map((item, index) => { if (item.ownerAccountChat ) { return ( <ChatBallonOwnerContainer key={index}> <ChatContainerText> { item.chatList.map((itemList) => { return ( <ChatListEndWrapper> { itemList.list.map((chatListText) => { return ( <OwnerContainerChat> {chatListText} </OwnerContainerChat> ) }) } <TimeChat>{itemList.date}</TimeChat> </ChatListEndWrapper> ) }) } </ChatContainerText> </ChatBallonOwnerContainer> ) } else { return ( <ChatBallonContainer key={index}> <AvatarProfileContainer> <Avatar size={40} src={item.picUrl} /> </AvatarProfileContainer> <ChatContainerText> { item.chatList.map((itemList) => { return ( <ChatListStartWrapper> { itemList.list.map((chatListText) => { return ( <NotOwnerContainerChat> {chatListText} </NotOwnerContainerChat> ) }) } <TimeChat>{itemList.date}</TimeChat> </ChatListStartWrapper> ) }) } </ChatContainerText> </ChatBallonContainer> ) } }) } </ChatContainer> ) }; export default ChatBallon;<file_sep>/src/components/chart-box-grid/chart-box-grid.styles.js import styled from 'styled-components'; export const ChartBoxGridContainer = styled.div` border-radius: 5px; position: relative; display: grid; grid-template-columns: repeat(${({col}) => col? col : 1}, 1fr); box-shadow: ${({showBoxShadow}) => showBoxShadow ? ' 0 0.46875rem 2.1875rem rgba(8,10,37,.03), 0 0.9375rem 1.40625rem rgba(8,10,37,.03), 0 0.25rem 0.53125rem rgba(8,10,37,.05), 0 0.125rem 0.1875rem rgba(8,10,37,.03)' : 'none'}; background-color : ${({bgColor}) => bgColor? bgColor : 'none'}; column-gap: ${({gap}) => gap? gap: 0}; height: fit-content; @media screen and (max-width: 986px) { grid-template-columns: repeat(${({col}) => col%2 === 1? 1 : 2}, 1fr); } @media screen and (max-width: 650px) { grid-template-columns: repeat(1, 1fr); } `;<file_sep>/src/pages/profile-boxes/profile-boxes.component.js import React from 'react'; import { Avatar, Typography } from 'antd'; import { RocketOutlined, ThunderboltOutlined, FileTextOutlined, DatabaseOutlined, MessageOutlined, CrownOutlined, AlertOutlined,TrophyOutlined } from '@ant-design/icons'; import { CustomCard, CustomCardBody, CustomCardFooter } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import CustomButton from 'Components/custom-button/custom-button.component'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; import './profile-boxes.styles.css'; const { Title, Text } = Typography; const ProfileBoxes = () => { return ( <div className='grid-3-gap-30'> <CustomCard> <CustomCardHeaderWithImage backgroundColorOverlay='success'> <div className='flex-column align-items-center'> <Avatar size={55} src='https://images.unsplash.com/photo-1542393881816-df51684879df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80' /> <div className='padding-top-10'> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <Text className='white'>Short profile description</Text> </div> <div className='padding-top-10'> <CustomButton variant='solid' color='warning'><strong className='black-gray'>Settings</strong></CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <Text className='block margin-bottom-10'> Curabitur ullamcorper ultricies nisi. Nam eget dui. Etiam rhoncus. </Text> <Text className='block margin-bottom-10'> Since the 1500s, when an unknown printer took a galley of type and scrambled. </Text> </CustomCardBody> <CustomCardFooter> <CustomButton shadow className='mr-10' color='link' variant='dashed'> Cancel </CustomButton> <CustomButton color='primary' variant='solid'>Submit</CustomButton> </CustomCardFooter> </CustomCard> <CustomCard> <CustomCardHeaderWithImage imgUrl='https://images.unsplash.com/photo-1467226632440-65f0b4957563?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=679&q=80' backgroundColorOverlay='#4f55b2c4'> <div className='flex-column align-items-center'> <Avatar shape='square' size={55} src='https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80' /> <div className='padding-top-10'> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <Text className='white'>Short profile description</Text> </div> <div className='padding-top-10'> <CustomButton className='mr-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}/> <CustomButton variant='solid' color='info'><strong>Settings</strong></CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <ChartBoxGridContainer col={1} showBoxShadow={false} showBorder={true}> <ChartBoxVar3 defaultValue="764k" defaultValueColor='primary' mainTitleText='January Sales' descriptionText='Lorem ipsum dolor' /> <ChartBoxVar3 defaultValue='194k' defaultValueColor='warning' mainTitleText='February Sales' descriptionText='Maecenas tempus, tellus' /> <ChartBoxVar3 defaultValue="-$54M" defaultValueColor='danger' mainTitleText='March Sales' descriptionText='Donec vitae sapien' /> <ChartBoxVar3 defaultValue="$19M" defaultValueColor='success' mainTitleText='April Sales' descriptionText='Curabitur ullamcorper ultricies' /> </ChartBoxGridContainer> </CustomCardBody> </CustomCard> <CustomCard> <CustomCardHeaderWithImage imgUrl='https://images.unsplash.com/photo-1513622790541-eaa84d356909?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=667&q=80' backgroundColorOverlay='#e91e63bf'> <div className='flex-column align-items-center'> <Avatar shape='square' size={55} src='https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80' /> <div className='padding-top-10'> <Title className='white no-margin-no-padding' level={4}><NAME></Title> </div> <div className='padding-top-10'> <CustomButton variant='solid' className='mr-10' color='success'><strong>Settings</strong></CustomButton> <CustomButton color='warning' variant='solid' icon={<RocketOutlined className='black-gray' />}/> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <div className='fixed-height'> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link fw-bold black-gray'> <div> <FileTextOutlined className='mr-10'/> Example File 2 </div> <div className='margin-left-auto hover-show-only'> <CustomButton style={style.iconButton} className='mr-10' color='danger' variant='solid' icon={<DatabaseOutlined style={style.icon}/>}/> <CustomButton style={style.iconButton} color='alt' variant='solid' icon={<MessageOutlined style={style.icon}/>}/> </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link fw-bold black-gray'> <div> <FileTextOutlined className='mr-10'/> Example File 2 </div> <div className='margin-left-auto hover-show-only'> <CustomButton style={style.iconButton} className='mr-10' color='danger' variant='solid' icon={<DatabaseOutlined style={style.icon}/>}/> <CustomButton style={style.iconButton} color='alt' variant='solid' icon={<MessageOutlined style={style.icon}/>}/> </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link fw-bold black-gray'> <div> <FileTextOutlined className='mr-10'/> Example File 2 </div> <div className='margin-left-auto hover-show-only'> <CustomButton style={style.iconButton} className='mr-10' color='danger' variant='solid' icon={<DatabaseOutlined style={style.icon}/>}/> <CustomButton style={style.iconButton} color='alt' variant='solid' icon={<MessageOutlined style={style.icon}/>}/> </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link fw-bold black-gray'> <div> <FileTextOutlined className='mr-10'/> Example File 2 </div> <div className='margin-left-auto hover-show-only'> <CustomButton style={style.iconButton} className='mr-10' color='danger' variant='solid' icon={<DatabaseOutlined style={style.icon}/>}/> <CustomButton style={style.iconButton} color='alt' variant='solid' icon={<MessageOutlined style={style.icon}/>}/> </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link fw-bold black-gray'> <div> <FileTextOutlined className='mr-10'/> Example File 2 </div> <div className='margin-left-auto hover-show-only'> <CustomButton style={style.iconButton} className='mr-10' color='danger' variant='solid' icon={<DatabaseOutlined style={style.icon}/>}/> <CustomButton style={style.iconButton} color='alt' variant='solid' icon={<MessageOutlined style={style.icon}/>}/> </div> </a> </li> </ul> </div> </CustomCardBody> <CustomCardFooter> <CustomButton className='mr-10' variant='no-outlined' color='success'><strong>Remove from list</strong></CustomButton> <CustomButton variant='no-outlined' color='danger'><strong>Send Message</strong></CustomButton> </CustomCardFooter> </CustomCard> <CustomCard> <CustomCardHeaderWithImage imgUrl='https://images.unsplash.com/photo-1471039497385-b6d6ba609f9c?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80' backgroundColorOverlay='#0c090bad'> <div className='flex-column align-items-center'> <Avatar shape='square' size={55} src='https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?ixlib=rb-1.2.1&auto=format&fit=crop&w=334&q=80' /> <div className='padding-top-10'> <Title className='white no-margin-no-padding' level={4}>Bryce Cordova</Title> <Text className='white'>Implementation Specialist</Text> </div> <div className='padding-top-10'> <CustomButton variant='solid' pill={true} className='mr-10' color='light'><strong>Load click</strong></CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody className='no-margin-no-padding'> <ChartBoxVar3 borderRadius={false} defaultValue="$568" defaultValueColor='#fbfbfbe6' mainTitleText='Clients' mainTitleColor='white' descriptionText='Total Clients Profit' descriptionTextColor='#fbfbfbe6' bgColor='linear-gradient(-20deg,#2b5876,#4e4376)' /> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<CrownOutlined style={style.iconStyleBigger}/>}> Primary </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<AlertOutlined style={style.iconStyleBigger}/>}> Success </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<TrophyOutlined style={style.iconStyleBigger}/>}> Danger </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<RocketOutlined style={style.iconStyleBigger}/>}> Warning </CustomButton> </div> </div> </CustomCardBody> </CustomCard> <CustomCard> <CustomCardHeaderWithImage backgroundColorOverlay='#33293e'> <div className='flex-column align-items-center'> <Avatar shape='square' size={55} src='https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80' /> <div className='padding-top-10'> <Title className='white no-margin-no-padding' level={4}>Isabelle Day</Title> <Text className='white'>Security Officert</Text> </div> <div className='padding-top-10'> <CustomButton variant='solid' className='mr-10' color='warning'><strong>View complete profile</strong></CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <p className='top-authors'>TOP AUTHORS</p> <div className='profile-boxes-card-container'> <Avatar size={46} src='https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80' /> <ChartBoxVar3 boxShadow={false} defaultValue="$129" defaultValueColor='danger' mainTitleText='<NAME>' descriptionText='Web Developer' /> </div> <div className='profile-boxes-card-container'> <Avatar size={46} src='https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80' /> <ChartBoxVar3 boxShadow={false} defaultValue="$54" defaultValueColor='success' mainTitleText='<NAME>' descriptionText='UI Designer' /> </div> <div className='profile-boxes-card-container'> <Avatar size={46} src='https://images.unsplash.com/photo-1542393881816-df51684879df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80' /> <ChartBoxVar3 boxShadow={false} defaultValue="$431" defaultValueColor='warning' mainTitleText='<NAME>' descriptionText='Java Programmer' /> </div> <div className='profile-boxes-card-container'> <Avatar size={46} src='https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80' /> <ChartBoxVar3 boxShadow={false} defaultValue="$77" defaultValueColor='primary' mainTitleText='<NAME>' descriptionText='Group ArchitectUI ' /> </div> </CustomCardBody> <CustomCardFooter> <CustomButton variant='solid' color='info'>View Details</CustomButton> </CustomCardFooter> </CustomCard> <CustomCard contained='#545cd8d1'> <CustomCardHeaderWithImage backgroundColorOverlay='#545cd8'> <div className='flex-column align-items-center'> <Avatar shape='square' size={55} src='https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80' /> <div className='padding-top-10'> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <Text className='white'>Applications Technician</Text> </div> <div className='padding-top-10'> <CustomButton className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}> <strong>View complete profile</strong> </CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <div className='flex-column align-items-center justify-content-center'> <CustomButton variant='solid' className='mr-10' color='dark'><strong>Send Message</strong></CustomButton> </div> </CustomCardBody> </CustomCard> </div> ) }; export default ProfileBoxes; const style = { icon: { fontSize: '10px' }, iconButton: { padding: '2px 10px' }, iconStyleBigger: { fontSize: '28px' } }<file_sep>/src/pages/applications-mailbox/application-mailbox.data.js export const MailboxData = [ { id: 1, name: '<NAME>', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '13 Dec', picture: 'https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80', lastseen: '15 minutes', chat: 'consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis', unread: 2, datechat: '12.12' }, { id: 2, name: '<NAME>', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '13 Oct', picture: 'https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', chat: 'tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, en', unread: 3, datechat: '11.11' }, { id: 3, name: 'Silaladungka', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '03 Feb', picture: 'https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', chat: 'imperdiet. Etiam ultricies nisi vel augue. Curabitur', activechat: 'true', }, { id: 4, name: '<NAME>', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '19 Mar', picture: 'https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', lastseen: '1 hour', chat: 'ellus eget condimentum rhoncus, sem quam semper libero, ', unread: 4, datechat: '09.11.20' }, { id: 5, name: '<NAME>', email : 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '02 Jun', picture: 'https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', chat: 'luctus pulvinar, hendrerit id, lorem. Maecenas nec odio et ante tincidunt tempus.', datechat: '09.11.20' }, { id: 6, name: '<NAME>', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '07 Aug', picture: 'https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?ixlib=rb-1.2.1&auto=format&fit=crop&w=334&q=80', chat: 'Donec vitae sapien ut libero venenatis faucibus', unread: 1, datechat: '09.11.20' }, { id: 7, name: '<NAME>', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '23 Sep', picture: 'https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', chat: 'Nullam quis ante. Etiam sit amet orci eget eros faucibus tincidunt. Duis leo. Sed fringilla mauris sit', datechat: '08.11.20' }, { id: 8, name: '<NAME>', email: 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient', date: '10 Oct', picture: 'https://images.unsplash.com/photo-1542393881816-df51684879df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', lastseen: '43 minutes', chat: 'Donec sodales sagittis magna. Sed consequat, leo eget bibendum sodales, augue velit cursus nunc,', datechat: '08.11.20' } ];<file_sep>/src/components/chart-box-var-1/chart-box-var-1.component.js import React from 'react'; import PropTypes from 'prop-types'; import { Progress } from 'antd'; import { DownOutlined, UpOutlined, ArrowLeftOutlined, ArrowRightOutlined } from '@ant-design/icons'; import { ChartBoxVarIconContainer, DefaultValueText, DefaultValueDescriptionText, ProgressValueTextContainer, ChartBoxVar1Container, ChartBoxVar1GridAlignment, ChartBox1Basic } from './chart-box-var-1.styles'; import { colorsPalette } from '../custom-color/custom-color'; import './chart-box-var-1.styles.css'; const ChartBoxVar1 = ({ bgColor, zoom, variant, icon, iconColor, iconBgColor, iconContainerShape, defaultValue, defaultValueDescription, progressValue, progressValueColor, progressValueArrow, defaultValueColor, defaultValueDescColor, border, boxShadow, borderRadius, col, progressBarValue, progressBarColor, trailColor, children, chart, bgOverlay, className, ...props }) => { let ArrowIcon = null; if (progressValueArrow === 'up') { ArrowIcon = <UpOutlined />; } else if (progressValueArrow === 'down') { ArrowIcon = <DownOutlined />; } else if (progressValueArrow === 'left') { ArrowIcon = <ArrowLeftOutlined />; } else if (progressValueArrow === 'right') { ArrowIcon = <ArrowRightOutlined />; } const ChartBoxBasic1Const = () => ( <ChartBox1Basic className={className} > { icon? <ChartBoxVarIconContainer iconContainerShape={iconContainerShape} iconColor={iconColor} iconBgColor={iconBgColor}> {icon} </ChartBoxVarIconContainer> : null } <DefaultValueText defaultValueColor={defaultValueColor}> {defaultValue} </DefaultValueText> <DefaultValueDescriptionText defaultValueDescColor={defaultValueDescColor}> {defaultValueDescription} </DefaultValueDescriptionText > { children? <div> {children} </div> : <ProgressValueTextContainer progressValueColor={progressValueColor}> <span>{ArrowIcon}</span> <span>{progressValue}</span> </ProgressValueTextContainer> } </ChartBox1Basic> ); if (variant === 'basic') { return ( <ChartBoxVar1Container className={className} row={props.row} col={col} border={border} boxShadow={boxShadow} borderRadius={borderRadius} bgColor={bgColor} zoom={zoom}> { chart? <div className='overflow-hidden'> <div className='chart-box-graph-container'> <div style={{overflow: 'hidden'}}> {chart} </div> <div style={{backgroundColor: bgOverlay? bgOverlay : '#ffffffb0'}} className='chart-box-graph-overlay'/> <div className='chart-box-detail-container'> <ChartBoxBasic1Const/> { progressBarValue? <Progress strokeColor={`${colorsPalette[progressBarColor] ? colorsPalette[progressBarColor] : progressBarColor}`} className='progression-bar-style' percent={progressBarValue} status="active" showInfo={false} /> : null } </div> </div> </div> : <div> <ChartBoxBasic1Const/> { progressBarValue? <Progress strokeColor={`${colorsPalette[progressBarColor] ? colorsPalette[progressBarColor] : progressBarColor}`} className='progression-bar-style' percent={progressBarValue} status="active" showInfo={false} /> : null } </div> } </ChartBoxVar1Container> ) } else if (variant === 'alignment') { return ( <ChartBoxVar1Container {...props} row={props.row} col={col} border={border} boxShadow={boxShadow} borderRadius={borderRadius} bgColor={bgColor} zoom={zoom}> <ChartBoxVar1GridAlignment icon={icon} > { icon? <ChartBoxVarIconContainer iconContainerShape={iconContainerShape} iconColor={iconColor} iconBgColor={iconBgColor}> {icon} </ChartBoxVarIconContainer> : null } <div> <DefaultValueDescriptionText style={{marginBottom: 0}} defaultValueDescColor={defaultValueDescColor}> {defaultValueDescription} </DefaultValueDescriptionText > <DefaultValueText style={{lineHeight: 1}} defaultValueColor={defaultValueColor}> {defaultValue} </DefaultValueText> { children? <div>{children}</div> : <ProgressValueTextContainer justifyContent='flex-start' progressValueColor={progressValueColor}> <span>{ArrowIcon}</span> <span>{progressValue}</span> </ProgressValueTextContainer> } </div> </ChartBoxVar1GridAlignment> { progressBarValue? <Progress strokeColor={`${colorsPalette[progressBarColor] ? colorsPalette[progressBarColor] : progressBarColor}`} className='progression-bar-style' percent={progressBarValue} status="active" showInfo={false} /> : null } </ChartBoxVar1Container> ) } else if (variant === 'progress-circle') { return ( <ChartBoxVar1Container className={className} row={props.row} col={col} border={border} boxShadow={boxShadow} borderRadius={borderRadius} bgColor={bgColor} zoom={zoom}> <ChartBoxVar1GridAlignment progress={true} > <div> <Progress status={progressBarColor === 'danger'? 'exception' : null } strokeColor={colorsPalette[progressBarColor] ? colorsPalette[progressBarColor] : progressBarColor} trailColor={trailColor} percent={progressBarValue} type="circle" width={70} /> </div> <div> <DefaultValueDescriptionText style={{marginBottom: 0}} defaultValueDescColor={defaultValueDescColor}> {defaultValueDescription} </DefaultValueDescriptionText > <DefaultValueText style={{lineHeight: 1}} defaultValueColor={defaultValueColor}> {defaultValue} </DefaultValueText> { children? <div> {children} </div> : <ProgressValueTextContainer justifyContent='flex-start' progressValueColor={progressValueColor}> <span>{ArrowIcon}</span> <span>{progressValue}</span> </ProgressValueTextContainer> } </div> </ChartBoxVar1GridAlignment> </ChartBoxVar1Container> ) } else { return <div/> } }; export default ChartBoxVar1; ChartBoxVar1.propTypes = { variant: PropTypes.oneOf(['basic', 'alignment', 'progress-circle']).isRequired, iconContainerShape: PropTypes.oneOf(['square', 'circle']), icon: PropTypes.elementType, iconColor: PropTypes.string, iconBgColor: PropTypes.string, defaultValue: PropTypes.string, defaultValueDescription: PropTypes.string, progressValue: PropTypes.string, progressValueColor: PropTypes.oneOf(['primary','secondary','link','danger','success','info','warning','dark','light']), progressValueArrow: PropTypes.oneOf(['up', 'down', 'left', 'right']), zoom: PropTypes.bool, defaultValueDescColor: PropTypes.string, defaultValueColor: PropTypes.string, bgColor: PropTypes.string, border: PropTypes.bool, boxShadow: PropTypes.bool, borderRadius: PropTypes.bool, col: PropTypes.number, progressBarValue: PropTypes.number, progressBarColor: PropTypes.string }; ChartBoxVar1.defaultProps = { variant: 'basic', iconContainerShape: 'circle', bgColor: 'white', border: false, boxShadow: true, borderRadius: true };<file_sep>/src/components/profile-header/profile-header.component.js import React from 'react'; import { Avatar, Button } from 'antd'; import { MessageOutlined, TagOutlined } from '@ant-design/icons'; import './profile-header.styles.css'; import '../../App.css'; const ProfileHeader = ({ show }) => { return ( <div className={`floating-menu card-container header-profile-menu ${show ? 'floating-menu-show' : 'floating-menu-close'}`}> <div className='card-header-container header-profile-menu-header'> <div className='card-header-overlay header-profile-menu-overlay'> <Avatar size={40} src="https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80" /> <div className='profile-desc-text-wrapper'> <p className='profile-menu-name-text'><NAME></p> <p className='profile-menu-position-text'>A short profile description</p> </div> <div className='profile-button-wrapper'> <Button >Logout</Button> </div> </div> </div> <div className='phc-body-container'> <p className='phc-main-title'>ACTIVITY</p> <div className='phc-content-menu'> <p className='phc-content-menu-atr'>Chat</p> <div className='phc-count-number'>8</div> </div> <div className='phc-content-menu'> <p className='phc-content-menu-atr'>Recover Password</p> </div> <p className='phc-main-title'>MY ACCOUNT</p> </div> <div className='phc-footer-container'> <div className='phc-box'> <div className='phc-box-content'> <div className='phc-box-field-1'> <MessageOutlined className='phc-box-field-icon-1' /> <p className='phc-box-field-text-1'>Message</p> </div> </div> <div className='phc-box-content'> <div className='phc-box-field-2'> <TagOutlined className='phc-box-field-icon-2'/> <p className='phc-box-field-text-2'>Support Tickets</p> </div> </div> </div> <Button type='primary'>Open Messages</Button> </div> </div> ) }; export default ProfileHeader;<file_sep>/src/pages/element-buttons/outlined-button-container/outlined-button-container.component.js import React from 'react'; import CustomButton from 'Components/custom-button/custom-button.component'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; const OutlinedButtonContainer = () => { return ( <div className='grid-2'> <CustomCard className='mobile-mb-30'> <CustomCardTitleText> COLOR STATES </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' variant='outlined' color='primary'>Primary</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='secondary'>Secondary</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='success'>Success</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='info'>Info</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='warning'>Info</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='danger'>Danger</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='alt'>Alt</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='light'>Light</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='dark'>Dark</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='link'>Link</CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mobile-mb-30'> <CustomCardTitleText> ACTIVE STATES </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' variant='outlined' color='primary' active >Primary</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='secondary' active>Secondary</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='success' active>Success</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='info' active>Info</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='warning' active>Info</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='danger' active>Danger</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='alt' active>Alt</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='light' active>Light</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='dark' active>Dark</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='link' active>Link</CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mobile-mb-30'> <CustomCardTitleText> WIDER </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' variant='outlined' color='primary' size='large'>Large</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='primary' size='normal'>Normal</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='primary' size='small'>Small</CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mobile-mb-30'> <CustomCardTitleText> SIZING </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' variant='outlined' color='primary' wide='large'>Large</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='primary' wide='normal'>Normal</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='primary' wide='small'>Small</CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mobile-mb-30'> <CustomCardTitleText> DISABLED STATES </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' variant='outlined' disabled color='primary'>Primary</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='secondary'>Secondary</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='success'>Success</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='info'>Info</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='warning'>Info</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='danger'>Danger</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='alt'>Alt</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='light'>Light</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='dark'>Dark</CustomButton> <CustomButton className='mrb-10' variant='outlined' disabled color='link'>Link</CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mobile-mb-30'> <CustomCardTitleText> BLOCK LEVEL </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' variant='outlined' color='primary' block>Primary</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='secondary' block>Secondary</CustomButton> <CustomButton className='mrb-10' variant='outlined' color='success' block>Success</CustomButton> </CustomCardBody> </CustomCard> </div> ) }; export default OutlinedButtonContainer;<file_sep>/src/components/chart-box-grid/chart-box-grid.component.js import React from 'react'; import PropTypes from 'prop-types'; import { ChartBoxGridContainer } from './chart-box-grid.styles'; const ChartBoxGrid = ({ children, col, showBorder, showBoxShadow, ...props }) => { let bgColor = null; let gap = 0; let totalChild = 0; React.Children.map(children, child => { totalChild = Number(totalChild)+1; }); const childrenWithProps = React.Children.map(children, child => { const boxShadow = false; const borderRadius = child.type.name === 'ChartBoxVar3' ? true : false; const border= true; const row = Math.ceil(totalChild/col); const width = col > 1 ? '100%' : '100%'; const props = { boxShadow, borderRadius, border, col, row, width, showBorder }; if (React.isValidElement(child)) { if (child.type.name === 'ChartBoxVar3') { bgColor = 'white'; gap = '30px'; } return React.cloneElement(child, props); } return child; }); return ( <ChartBoxGridContainer showBoxShadow={showBoxShadow} gap={gap} bgColor={bgColor} col={col} {...props}> {childrenWithProps} </ChartBoxGridContainer> ) }; export default ChartBoxGrid; ChartBoxGrid.defaultProps = { showBoxShadow: true, }; <file_sep>/src/pages/chart-boxes/chart-boxes-variation-2/colors/colors.component.js import React from 'react'; import ChartBoxVar2 from 'Components/chart-box-var-2/chart-box-var-2.component'; const Colors = () => { return ( <div className='grid-3-gap-30 mb-30'> <ChartBoxVar2 defaultValue="$1283" defaultValueColor='white' mainTitleText='Sales' mainTitleColor='white' descriptionText='Monthly Goals' descriptionTextColor='#d2d2d2' descriptionProgressValue='176%' descriptionProgressColor='#d2d2d2' descriptionProgressArrow='up' bgColor='primary' /> <ChartBoxVar2 defaultValue="368k" defaultValueColor='white' mainTitleText='Profiles' mainTitleColor='white' descriptionText='Active Users' descriptionTextColor='#eaeaea' descriptionProgressValue='66.5%' descriptionProgressColor='#eaeaea' descriptionProgressArrow='left' bgColor='info' /> <ChartBoxVar2 defaultValue="87%" defaultValueColor='white' mainTitleText='Clients' mainTitleColor='white' descriptionText='Returning' descriptionTextColor='warning' descriptionProgressValue='45' descriptionProgressColor='warning' descriptionProgressArrow='up' bgColor='#444054' /> <ChartBoxVar2 defaultValue="1,621" defaultValueColor='white' mainTitleText='Reports' mainTitleColor='white' defaultValueColor='white' descriptionText='Bugs Fixed' descriptionTextColor='white' descriptionProgressValue='27.2%' descriptionProgressColor='white' descriptionProgressArrow='right' bgColor='warning' /> <ChartBoxVar2 defaultValue="183" defaultValueColor='white' mainTitleText='Support Requests' mainTitleColor='white' descriptionText='Solved' descriptionTextColor='white' descriptionProgressValue='32' descriptionProgressColor='white' descriptionProgressArrow='down' bgColor='danger' /> <ChartBoxVar2 defaultValue="1,621" defaultValueColor='white' mainTitleText='Reports' mainTitleColor='white' descriptionText='Bugs Fixed' descriptionTextColor='white' descriptionProgressValue='17.2%' descriptionProgressColor='white' descriptionProgressArrow='right' bgColor='#2a5298' /> <ChartBoxVar2 defaultValue="$1283" mainTitleText='Sales' descriptionText='Monthly Goals' descriptionTextColor='white' descriptionProgressValue='176%' descriptionProgressColor='white' descriptionProgressArrow='up' progressBarValue={100} strokeWidth={10} progressBarColor='danger' descriptionProgressDetail='Successful Payments' bgColor='linear-gradient(120deg,#e0c3fc,#8ec5fc)' /> <ChartBoxVar2 defaultValue="368k" defaultValueColor='white' mainTitleText='Profiles' mainTitleColor='white' descriptionText='Active Users' descriptionTextColor='white' descriptionProgressValue='66.5%' descriptionProgressColor='white' descriptionProgressArrow='left' progressBarValue={60} strokeWidth={10} progressBarColor='warning' descriptionProgressDetail='Monthly Subscribers' descriptionProgressBarColor='white' bgColor='linear-gradient(-20deg,#2b5876,#4e4376)' /> <ChartBoxVar2 defaultValue="87%" mainTitleText='Clients' descriptionText='Returning' descriptionTextColor='danger' descriptionProgressValue='45' descriptionProgressColor='danger' descriptionProgressArrow='up' progressBarValue={90} strokeWidth={10} progressBarColor='primary' descriptionProgressDetail='Severe Reports' bgColor='linear-gradient(120deg,#f6d365,#fda085)' /> <ChartBoxVar2 defaultValue="1,621" mainTitleText='Reports' defaultValueColor='warning' descriptionText='Bugs Fixed' descriptionProgressValue='27.2%' descriptionProgressColor='info' descriptionProgressArrow='right' progressBarValue={70} strokeWidth={15} progressBarColor='primary' descriptionProgressDetail='Successful Payments' bgColor='linear-gradient(120deg,#84fab0,#8fd3f4)' /> <ChartBoxVar2 defaultValue="183" defaultValueColor='danger' mainTitleText='Support Requests' descriptionText='Solved' descriptionProgressValue='32' descriptionProgressArrow='down' progressBarValue={100} progressBarColor='danger' strokeWidth={18} descriptionProgressDetail='Monthly Subscribers' bgColor='linear-gradient(45deg,#ff9a9e,#fad0c4 99%,#fad0c4)' /> <ChartBoxVar2 defaultValue="1,621" mainTitleText='Reports' mainTitleColor='white' defaultValueColor='success' descriptionText='Bugs Fixed' descriptionTextColor='white' descriptionProgressValue='17.2%' descriptionProgressColor='white' descriptionProgressArrow='right' progressBarValue={80} progressBarColor='success' strokeWidth={13} descriptionProgressDetail='Severe Reports' descriptionProgressBarColor='white' bgColor='linear-gradient(90deg,#0f2027,#203a43,#2c5364)' /> </div> ) }; export default Colors;<file_sep>/src/pages/applications-faq/cc-information.component.js import React from 'react'; import { Form, Input } from 'antd'; const CCInformation = () => { return ( <Form layout='vertical'> <Form.Item label='Input without validation' help="Example help text that remains unchanged." > <Input /> </Form.Item> <Form.Item label={<span className='success-label'>Valid input</span>} hasFeedback validateStatus="success" help={<span className='success-label'>Sweet. That name is available</span>} > <Input className='success-input' /> </Form.Item> <Form.Item label={<span className='error-label'>Inalid input</span>} hasFeedback validateStatus="error" help={<span className='error-label'>Oh noes! That name is already taken</span>} > <Input/> </Form.Item> </Form> ) }; export default CCInformation;<file_sep>/src/pages/element-cards/element-cards.component.js import React from 'react'; import CustomTabsWrapper from 'Components/custom-tabs-wrapper/custom-tabs-wrapper.component'; import CustomTabPanel from 'Components/custom-tab-panel/custom-tab-panel.component'; import BasicCardContainer from './basic-card-container/basic-card-container.component'; import ColorStatesContainer from './color-states-card-container/color-states-card-container.component'; import AdvancedCardContainer from './advanced-card-container/advanced-card-container.component'; const ElementCards = () => { return ( <div> <CustomTabsWrapper> <CustomTabPanel data-key='basic' title='Basic'> <BasicCardContainer/> </CustomTabPanel> <CustomTabPanel data-key='color-states' title='Color States'> <ColorStatesContainer/> </CustomTabPanel> <CustomTabPanel data-key='advanced' title='Advanced'> <AdvancedCardContainer/> </CustomTabPanel> </CustomTabsWrapper> </div> ) }; export default ElementCards;<file_sep>/src/pages/element-navigation-menus/vertical-menu-container/vertical-menu-container.component.js import React from 'react'; import { InboxOutlined, BookOutlined, FileOutlined, PictureOutlined, MessageOutlined, WalletOutlined, SettingOutlined, PushpinOutlined, HourglassOutlined, } from '@ant-design/icons'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import CustomButton from 'Components/custom-button/custom-button.component'; import CustomMenu from 'Components/custom-menu/custom-menu.component'; import CustomMenuItem from 'Components/custom-menu-item/custom-menu-item.component'; import { CustomMenuItemHeader, CustomMenuDivider } from 'Components/custom-menu-item/custom-menu-item.styles'; const VerticalMenuContainer = () => { return ( <div> <CustomCard className='mb-30'> <CustomCardTitleText> VERTICAL MENU </CustomCardTitleText> <CustomCardBody> <div className='grid-2-gap-30'> <div className='mlr-30'> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link'> Link </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> Link <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> Another Link <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' disabled className='nav-link'> Disabled Link </a> </li> </ul> </div> <div className='mlr-30'> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link'> <div> <InboxOutlined style={style.iconStyle} /> Inbox </div> <CustomLabelBadge className='margin-left-auto' color='secondary' pill>86</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <BookOutlined style={style.iconStyle}/> Book </div> <CustomLabelBadge className='margin-left-auto' color='danger' pill>5</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <PictureOutlined style={style.iconStyle}/> Picture </div> </a> </li> <li className='nav-item'> <a href='#' disabled className='nav-link'> <div> <FileOutlined style={style.iconStyle}/> File Disabled </div> </a> </li> </ul> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> SEPARATORS AND HEADERS </CustomCardTitleText> <CustomCardBody> <div className='grid-2-gap-30'> <div className='mlr-30'> <ul className='nav'> <li className='nav-item'> <p className='nav-item-header'>Activity</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> Chat <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> Recover Password </a> </li> <li className='nav-item'> <p className='nav-item-header'>My Acccount</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> Settings <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> Messages <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> Logs </a> </li> <li className='nav-item nav-item-divider'> </li> <li className='nav-item'> <CustomButton variant='solid' color='danger' shadow>Cancel</CustomButton> </li> <li className='nav-item nav-item-divider'> </li> </ul> </div> <div className='mlr-30'> <ul className='nav'> <li className='nav-item'> <p className='nav-item-header'>Activity</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <MessageOutlined style={style.iconStyle}/> Chat </div> <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <WalletOutlined style={style.iconStyle}/> Recover Password </div> </a> </li> <li className='nav-item'> <p className='nav-item-header'>My Acccount</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <SettingOutlined style={style.iconStyle}/> Settings </div> <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <PushpinOutlined style={style.iconStyle} /> Logs </div> </a> </li> <li className='nav-item nav-item-divider'> </li> <li className='nav-item'> <CustomButton variant='solid' color='success' pill>Save</CustomButton> </li> <li className='nav-item nav-item-divider'> </li> </ul> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> MENU HOVER STYLES </CustomCardTitleText> <CustomCardBody> <div className='grid-4-gap-20'> <div className='flat-card-border padding-vertical-20 '> <CustomMenuItemHeader> Header </CustomMenuItemHeader> <CustomMenu role='primary'> <CustomMenuItem> Menus </CustomMenuItem> <CustomMenuItem> Settings </CustomMenuItem> <CustomMenuItem> Actions </CustomMenuItem> <CustomMenuDivider/> <CustomMenuItem> Divider </CustomMenuItem> </CustomMenu> </div> <div className='flat-card-border padding-vertical-20 '> <CustomMenuItemHeader> Header </CustomMenuItemHeader> <CustomMenu role='secondary'> <CustomMenuItem> Menus </CustomMenuItem> <CustomMenuItem> Settings </CustomMenuItem> <CustomMenuItem> Actions </CustomMenuItem> <CustomMenuDivider/> <CustomMenuItem> Divider </CustomMenuItem> </CustomMenu> </div> <div className='flat-card-border padding-vertical-20 '> <CustomMenuItemHeader> Header </CustomMenuItemHeader> <CustomMenu> <CustomMenuItem> Menus </CustomMenuItem> <CustomMenuItem> Settings </CustomMenuItem> <CustomMenuItem> Actions </CustomMenuItem> <CustomMenuDivider/> <CustomMenuItem> Divider </CustomMenuItem> </CustomMenu> </div> <div className='flat-card-border padding-vertical-20 '> <CustomMenuItemHeader> Header </CustomMenuItemHeader> <CustomMenu role='primary' pill={true}> <CustomMenuItem> Menus </CustomMenuItem> <CustomMenuItem> Settings </CustomMenuItem> <CustomMenuItem> Actions </CustomMenuItem> <CustomMenuDivider/> <CustomMenuItem> Divider </CustomMenuItem> </CustomMenu> </div> <div className='flat-card-border padding-vertical-20 '> <CustomMenuItemHeader> Header </CustomMenuItemHeader> <CustomMenu role='secondary' pill={true}> <CustomMenuItem> Menus </CustomMenuItem> <CustomMenuItem> Settings </CustomMenuItem> <CustomMenuItem> Actions </CustomMenuItem> <CustomMenuDivider/> <CustomMenuItem> Divider </CustomMenuItem> </CustomMenu> </div> <div className='flat-card-border padding-vertical-20 '> <CustomMenuItemHeader> Header </CustomMenuItemHeader> <CustomMenu> <CustomMenuItem> <InboxOutlined style={style.iconStyle} /> Menus </CustomMenuItem> <CustomMenuItem> <BookOutlined style={style.iconStyle}/> Settings </CustomMenuItem> <CustomMenuItem> <PictureOutlined style={style.iconStyle}/> Actions </CustomMenuItem> <CustomMenuDivider/> <CustomMenuItem> <FileOutlined style={style.iconStyle}/> Divider </CustomMenuItem> </CustomMenu> </div> </div> </CustomCardBody> </CustomCard> </div> ) }; const style = { iconStyle: { fontSize: '18px', width: '30px', textAlign: 'left', } } export default VerticalMenuContainer;<file_sep>/src/pages/element-timelines/dot-badges-container/dot-badges-container.component.js import React from 'react'; import { Typography } from 'antd'; import CustomTimeline from 'Components/custom-timeline/custom-timeline.component'; import CustomTimelineItem from 'Components/custom-timeline-item/custom-timeline-item.component'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; const { Text } = Typography; const DotBadgesContainer = () => { return ( <div className='grid-2-gap-30'> <div> <CustomCard className='mb-30'> <CustomCardTitleText> COLORFUL DOTS </CustomCardTitleText> <CustomCardBody> <CustomTimeline size='small'> <CustomTimelineItem color='danger'> All Hands Meeting </CustomTimelineItem> <CustomTimelineItem color='warning'> Yet another one, <Text type="success"> at 10.30 AM</Text> </CustomTimelineItem> <CustomTimelineItem color='success'> Build the productions release <CustomLabelBadge style={{marginLeft: '20px'}} color='danger'> NEW </CustomLabelBadge> </CustomTimelineItem> <CustomTimelineItem color='primary'> Something not important </CustomTimelineItem> <CustomTimelineItem color='info'> This dot has an info state </CustomTimelineItem> <CustomTimelineItem color='dark'> This dot has dark state </CustomTimelineItem> </CustomTimeline> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> BASICS </CustomCardTitleText> <CustomCardBody> <CustomTimeline size='regular'> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">11.00 PM</Text> } color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">12.00 PM</Text> } color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">15.00 PM</Text> } color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">12.00 PM</Text> } color='primary'> <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">11.00 PM</Text> } color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">12.00 PM</Text> } color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">15.00 PM</Text> } color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">12.00 PM</Text> } color='primary'> <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">11.00 PM</Text> } color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">12.00 PM</Text> } color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">15.00 PM</Text> } color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className='fs-12' type="secondary">12.00 PM</Text> } color='primary'> <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> </CustomTimeline> </CustomCardBody> </CustomCard> </div> <div> <CustomCard className='mb-30'> <CustomCardTitleText> SIMPLE DOTS </CustomCardTitleText> <CustomCardBody> <CustomTimeline size='small'> <CustomTimelineItem> All Hands Meeting </CustomTimelineItem> <CustomTimelineItem> Yet another one, <Text type="success"> at 10.30 AM</Text> </CustomTimelineItem> <CustomTimelineItem> Build the productions release </CustomTimelineItem> <CustomTimelineItem> <Text type="success">Something not important</Text> </CustomTimelineItem> </CustomTimeline> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> WITHOUT TIME </CustomCardTitleText> <CustomCardBody> <CustomTimeline size='regular'> <CustomTimelineItem color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem color='primary'> <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem color='primary'> <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem color='primary'> <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> </CustomTimeline> </CustomCardBody> </CustomCard> </div> </div> ) }; export default DotBadgesContainer;<file_sep>/src/pages/chart-boxes/chart-boxes-variation-1/progress-circle/progress-circle.component.js import React from 'react'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; const ProgressCircle = () => { return ( <div className='grid-3-gap-30 mb-30'> <ChartBoxVar1 variant='progress-circle' progressBarValue={100} progressBarColor='success' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' /> <ChartBoxVar1 variant='progress-circle' progressBarValue={43} progressBarColor='primary' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' /> <ChartBoxVar1 variant='progress-circle' progressBarValue={80} progressBarColor='warning' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' /> <ChartBoxVar1 variant='progress-circle' progressBarValue={100} progressBarColor='danger' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' /> <ChartBoxVar1 variant='progress-circle' progressBarValue={92} progressBarColor='info' defaultValue='2,82k' defaultValueDescription='Total Sales' progressValueArrow='down' progressValue='23.1%' progressValueColor='danger' /> <ChartBoxVar1 variant='progress-circle' progressBarValue={70} progressBarColor='alt' defaultValue='32k' defaultValueDescription='Follow Ups' progressValueArrow='left' progressValue='115.5%' progressValueColor='dark' /> <ChartBoxVar1 variant='progress-circle' progressBarValue={100} progressBarColor='success' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' zoom={true} /> <ChartBoxVar1 variant='progress-circle' progressBarValue={43} progressBarColor='primary' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' zoom={true} /> <ChartBoxVar1 variant='progress-circle' progressBarValue={80} progressBarColor='warning' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' zoom={true} /> <ChartBoxVar1 variant='progress-circle' progressBarValue={100} progressBarColor='danger' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' zoom={true} /> <ChartBoxVar1 variant='progress-circle' progressBarValue={92} progressBarColor='info' defaultValue='2,82k' defaultValueDescription='Total Sales' progressValueArrow='down' progressValue='23.1%' progressValueColor='danger' zoom={true} /> <ChartBoxVar1 variant='progress-circle' progressBarValue={70} progressBarColor='alt' defaultValue='32k' defaultValueDescription='Follow Ups' progressValueArrow='left' progressValue='115.5%' progressValueColor='dark' zoom={true} /> </div> ) }; export default ProgressCircle;<file_sep>/src/pages/chart-boxes/chart-boxes-variation-1/alignments/alignments.component.js import React from 'react'; import { SettingOutlined, DesktopOutlined, RocketOutlined, RobotOutlined, GiftOutlined, FireOutlined, HeartOutlined, StarOutlined } from '@ant-design/icons'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; const Alignments = () => { return ( <div className='grid-3-gap-30 mb-30'> <ChartBoxVar1 variant='alignment' icon={<SettingOutlined />} iconBgColor='primary' iconColor='primary' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' progressBarValue='80' progressBarColor='primary' /> <ChartBoxVar1 variant='alignment' icon={<DesktopOutlined />} iconBgColor='#d8f3e5' iconColor='#3ac47d' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' progressBarValue='100' progressBarColor='success' /> <ChartBoxVar1 variant='alignment' icon={<RobotOutlined />} iconContainerShape='square' iconBgColor='#f7d3dc' iconColor='#d92550' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' progressBarValue='70' progressBarColor='danger' /> <ChartBoxVar1 variant='alignment' icon={<RocketOutlined />} iconColor='#d6efff' iconBgColor='#30b1ff' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' progressBarValue='60' progressBarColor='warning' /> <ChartBoxVar1 variant='alignment' icon={<DesktopOutlined />} iconBgColor='#444054' iconColor='#8e8e8e' defaultValue='2,82k' defaultValueDescription='Total Sales' progressValueArrow='down' progressValue='23.1%' progressValueColor='danger' /> <ChartBoxVar1 variant='alignment' icon={<GiftOutlined />} iconBgColor='#dddef7' iconColor='#4367d8' defaultValue='32k' defaultValueDescription='Follow Ups' progressValueArrow='left' progressValue='115.5%' progressValueColor='dark' /> <ChartBoxVar1 variant='alignment' defaultValue='1.2M' defaultValueDescription='Leads Generated' progressValueArrow='left' progressValue='115.5%' progressValueColor='info' /> <ChartBoxVar1 variant='alignment' defaultValue='17.2k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='175.5%' progressValueColor='warning' /> <ChartBoxVar1 variant='alignment' defaultValue='58.2k' defaultValueDescription='Reports Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' /> <ChartBoxVar1 variant='alignment' defaultValue='63.2k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' /> <ChartBoxVar1 variant='alignment' defaultValue='3.47k' defaultValueDescription='Users Active' progressValueArrow='down' progressValue='31.2%' progressValueColor='danger' /> <ChartBoxVar1 variant='alignment' defaultValue='3.7M' defaultValueDescription='Lifetime Tickets' progressValueArrow='right' progressValue='121.9%' progressValueColor='warning' /> <ChartBoxVar1 variant='alignment' icon={<FireOutlined />} iconBgColor='#f7b924' iconColor='#fff' defaultValue='45.8k' defaultValueDescription='Total Views' zoom={true} /> <ChartBoxVar1 variant='alignment' icon={<HeartOutlined />} iconBgColor='#d92550' iconColor='#fff' defaultValue='17k' defaultValueDescription='Profile' zoom={true} /> <ChartBoxVar1 variant='alignment' icon={<StarOutlined />} iconContainerShape='square' iconBgColor='#3ac47d' iconColor='#fff' defaultValue='5,83k' defaultValueDescription='Report Submitted' zoom={true} /> </div> ) }; export default Alignments;<file_sep>/src/pages/dashboard-commerce/dashboard-commerce-var-1/dashboard-commerce-var-1.component.js import React from 'react'; import { Table, Typography, Avatar } from 'antd'; import { Line } from 'react-chartjs-2'; import { SettingOutlined, DesktopOutlined, RocketOutlined, RobotOutlined, AlertOutlined, CrownOutlined, FireOutlined, ClearOutlined } from '@ant-design/icons'; import CustomButton from 'Components/custom-button/custom-button.component'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; import ChartBoxVar2 from 'Components/chart-box-var-2/chart-box-var-2.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; import { CustomCard, CustomCardFooter, CustomCardBody, CustomCardHeader, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import { Data6 } from 'Data/chart.data'; import { Options2 } from 'Data/settings-chart.data'; import { DataTable2, Columns2 } from 'Data/table.data'; import '../dashboard-commerce.styles.css'; const { Title } = Typography; const DashboardCommerceVariation1 = () => { return ( <div> <div className='da-commerce-grid-2 mb-30'> <div className='width-100 overflow-auto'> <CustomCard> <CustomCardHeader> <CustomCardTitleText>INCOME REPORT</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <div style={{width: '100%', overflow: 'hidden'}}> <Line data={Data6} width={100} height={170} options={Options2} /> </div> <CustomCardTitleText className='mb-30'>TARGET SALES</CustomCardTitleText> <div className='width-100 overflow-hidden'> <ChartBoxGridContainer showBoxShadow={false} col={3}> <ChartBoxVar2 boxShadow={false} defaultValue="65%" progressBarValue={78} strokeWidth={6} progressBarColor='info' descriptionProgressDetail='Sales' /> <ChartBoxVar2 boxShadow={false} defaultValue="22%" progressBarValue={40} strokeWidth={6} progressBarColor='warning' descriptionProgressDetail='Profiles' /> <ChartBoxVar2 boxShadow={false} defaultValue="83%" progressBarValue={83} strokeWidth={6} progressBarColor='success' descriptionProgressDetail='Tickets' /> </ChartBoxGridContainer> </div> </CustomCardBody> </CustomCard> </div> <div className='width-100'> <ChartBoxGridContainer col={2}> <ChartBoxVar1 icon={<SettingOutlined />} iconBgColor='primary' iconColor='primary' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' zoom={true} /> <ChartBoxVar1 icon={<DesktopOutlined />} iconBgColor='#d8f3e5' iconColor='#3ac47d' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' zoom={true} /> <ChartBoxVar1 icon={<RobotOutlined />} iconContainerShape='square' iconBgColor='#f7d3dc' iconColor='#d92550' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' zoom={true} /> <ChartBoxVar1 icon={<RocketOutlined />} iconColor='#d6efff' iconBgColor='#30b1ff' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' zoom={true} /> </ChartBoxGridContainer> </div> </div> <CustomCard className='mb-30'> <CustomCardHeader> <CustomCardTitleText>Easy Dynamic Tables</CustomCardTitleText> </CustomCardHeader> <CustomCardBody className='overflow-auto'> <Table columns={Columns2} dataSource={DataTable2} /> </CustomCardBody> </CustomCard> <Title className='text-align-center' level={2}>Top Sellers Cards</Title> <div className='grid-3-gap-30 mb-30'> <CustomCard className='overflow-hidden'> <CustomCardHeaderWithImage backgroundColorOverlay='#0e0e0eb8' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1560505155-1d9db7cc6856?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80'}> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Senior Software Engineer</p> <CustomButton className='margin-top-8' color='success' variant='solid'>View Profile</CustomButton> </div> </CustomCardHeaderWithImage> <CustomCardBody> <div className='flex-column align-items-center'> <Title className='fw-400 color98' level={4}>Month Totals</Title> <Title className='color5d fw-400 no-margin-no-padding' level={5}> <strong className='danger'>12</strong> new leads, <strong className='success'>$56.4</strong> in sales </Title> <CustomButton className='margin-top-8' variant='outlined' pill color='primary'>Full Report</CustomButton> </div> </CustomCardBody> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardHeaderWithImage backgroundColorOverlay='#0e0e0eb8' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1560505155-1d9db7cc6856?ixlib=rb-1.2.1&auto=format&fit=crop&w=750&q=80'}> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Short Profile Description</p> <CustomButton className='margin-top-8' pill color='warning' shadow variant='solid'>View Profile</CustomButton> </div> </CustomCardHeaderWithImage> <CustomCardBody> <div className='flex-column align-items-center'> <Title className='fw-400 color98' level={4}>Month Totals</Title> <SettingOutlined spin={true} style={style.settingIcon} /> </div> </CustomCardBody> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardHeaderWithImage backgroundColorOverlay='#0e0e0eb8' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1546629313-ea9c287a8b9f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'}> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}>Silaladungka Jungkat Jungkit</Title> <p className='white no-margin-no-padding'>Lead UX Designer</p> <CustomButton className='margin-top-8' color='success' variant='solid'>View Profile</CustomButton> </div> </CustomCardHeaderWithImage> <CustomCardBody> <div className='flex-column align-items-center'> <Title className='color5d fw-400 no-margin-no-padding' level={4}> <strong className='danger'>12</strong> new leads, <strong className='success'>$56.4</strong> in sales </Title> </div> </CustomCardBody> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<CrownOutlined />}> Automation </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<AlertOutlined />}> Reports </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<FireOutlined />}> Activity </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<ClearOutlined />}> Settings </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> </div> </div> ) }; const style = { settingIcon : { fontSize: '49px', color: '#a86799' } } export default DashboardCommerceVariation1;<file_sep>/src/pages/applications-faq/applications-faq.component.js import React, { useState } from 'react'; import { MenuOutlined, CloseOutlined } from '@ant-design/icons'; import { CustomMenuItemHeader } from 'Components/custom-menu-item/custom-menu-item.styles'; import CustomMenu from 'Components/custom-menu/custom-menu.component'; import CustomMenuItem from 'Components/custom-menu-item/custom-menu-item.component'; import TabExample1 from './tab-example-1.component'; import TabExample2 from './tab-example-2.component'; import TabExample3 from './tab-example-3.component'; import './applications-faq.styles.css'; const ApplicationFaq = () => { const [ activeMenuItem, setActiveMenuItem ] = useState({ id: 'TabExample1', name: 'Tab Example 1', content: <TabExample1/>}); const FixedHeaderList = [ { id: 'TabExample1', name: 'Tab Example 1', content: <TabExample1/> }, { id: 'TabExample2', name: 'Tab Example 2', content: <TabExample2/> }, { id: 'TabExample3', name: 'Tab Example 3', content: <TabExample3/> } ]; const [ chatMenu, setChatMenu ] = useState(false); const HandleToggleChatMenu = () => { setChatMenu(!chatMenu); } const handleChooseMenuItem = item => { setActiveMenuItem(item); } return ( <div className='appliations-faq-container'> <div className={`${chatMenu? 'faq-menu-container-show' : 'faq-menu-container'}`}> <CustomMenu role='secondary' pill> <CustomMenuItemHeader> Fixed Menu </CustomMenuItemHeader> { FixedHeaderList.map((menuitem) => ( <CustomMenuItem onClick={() => handleChooseMenuItem(menuitem)} activeColor='primary' active={menuitem.id === activeMenuItem.id} key={menuitem.id} className='faq-margin-menu-item'> {menuitem.name} </CustomMenuItem> )) } </CustomMenu> </div> <div className={`${chatMenu? 'faq-content-container-show' : 'faq-content-container'}`}> <div className='app-faq-mobile'> { chatMenu? <CloseOutlined onClick={HandleToggleChatMenu} style={{fontSize: '20px'}} className={`mr-20 close-menu ${chatMenu? 'show-close-menu' : ''}`}/> : <MenuOutlined onClick={HandleToggleChatMenu} style={{fontSize: '20px'}} className={`mr-20 close-menu ${chatMenu? '' : 'show-close-menu'}`} /> } </div> {activeMenuItem.content} </div> </div> ) }; export default ApplicationFaq;<file_sep>/src/components/loader/loader.component.js import React from 'react'; import chunk from 'Assets/gif/chunk.gif'; import { LoaderContainer } from './loader.styles'; const Loader = () => { return ( <LoaderContainer> <img src={chunk}/><br/> <p className='color5d no-margin-no-padding'>Please wait while we load all the components examples</p> <p className='color98'>Because this is a demonstration, we load at once all the components examples. This wouldn't happen in a real live app!</p> </LoaderContainer> ) }; export default Loader;<file_sep>/src/App.js import React, { useEffect, useState } from 'react'; import { withRouter } from 'react-router'; import { createStructuredSelector } from 'reselect'; import { connect } from 'react-redux'; import 'antd/dist/antd.less'; import './ant-design.styles.css'; import './App.css'; import Routing from './routing'; import ComponentOnlyPathList from 'Data/component-only-path-list.data'; import { selectFoldDrawer } from 'Redux_Component/application/application.selectors'; import CustomBreadcrumb from 'Components/custom-breadcrumb/custom-breadcrumb.component'; import CustomHeader from 'Components/custom-header/custom-header.component'; import CustomDrawer from 'Components/custom-drawer/custom-drawer.component'; import FloatingMenuHeader from 'Components/floating-menu-header/floating-menu-header.component'; const App = ({ location, foldDrawer, ...props }) => { const [ currentLocation, setCurrentLocation ] = useState(null); const [ showComponentOnly, setShowComponentOnly ] = useState(false); useEffect(() => { const showDrawerHeaderOthers = () => { const found = ComponentOnlyPathList[location.pathname]; setShowComponentOnly(found); } showDrawerHeaderOthers(); }, [location]) useEffect(() => { const handleScrollTop = () => { if (currentLocation !== location) { setCurrentLocation(location) window.scrollTo(0, 0); } } handleScrollTop(); }, [location]); return ( <div className='app'> { !showComponentOnly? <> <CustomDrawer /> <CustomHeader/> <FloatingMenuHeader/> </> : null } <div className={`${showComponentOnly ? '' : `content-container ${foldDrawer || !showComponentOnly ? 'content-fold-close' : 'content-fold-open'}` }`}> <CustomBreadcrumb/> <div className={`${!showComponentOnly ? 'app-body-container' : 'app-body-container-no-padding'}`}> <Routing/> </div> </div> </div> ) }; const mapStateToProps = createStructuredSelector({ foldDrawer: selectFoldDrawer, }); export default connect(mapStateToProps)(withRouter(App));<file_sep>/src/redux/application/application.types.js const ApplicationTypes = { SET_FOLD_DRAWER: 'SET_FOLD_DRAWER', SET_FLOATING_HEADER_TOOLS: 'SET_FLOATING_HEADER_TOOLS', SET_MEGA_MENU_TOGGLE: 'SET_MEGA_MENU_TOGGLE', SET_SETTING_HEADAER_TOGGLE: 'SET_SETTING_HEADAER_TOGGLE', SET_GRID_DASHBOARD_TOGGLE: 'SET_GRID_DASHBOARD_TOGGLE', SET_NOTIF_HEADER_TOGGLE: 'SET_NOTIF_HEADER_TOGGLE', SET_LANG_HEADER_TOGGLE: 'SET_LANG_HEADER_TOGGLE', SET_ACTIVE_USER_HEADER_TOGGLE: 'SET_ACTIVE_USER_HEADER_TOGGLE', SET_PROFILE_HEADER_TOGGLE: 'SET_PROFILE_HEADER_TOGGLE', SET_BREADCRUMB: 'SET_BREADCRUMB' }; export default ApplicationTypes;<file_sep>/src/components/setting-header/setting-header.component.js import React from 'react'; import { Menu, Button } from 'antd'; import './setting-header.styles.css'; import '../../App.css'; const SettingHeader = ({ show }) => { return ( <div className={`card-container header-settings-menu ${show? 'header-setting-menu-show' : 'header-setting-menu-hidden'}`}> <div className='card-header-container header-settings-menu-header'> <div className='card-header-overlay header-setting-menu-overlay'> <p className='card-header-title'>Overview</p> <p className='card-header-desc'>Dropdown menus for everyone</p> </div> </div> <div className='header-setting-menu-body'> <p className='capitalize-color keyframes'>Key Frames</p> <div className='setting-menu-container'> <Menu> <Menu.Item> Service Calendar </Menu.Item> <Menu.Item> Knowledge Base </Menu.Item> <Menu.Item> Accounts </Menu.Item> </Menu> </div> <Button className='keyframes' type="primary" danger>Cancel</Button> </div> </div> ) }; export default SettingHeader;<file_sep>/src/pages/dashboard-crm/dashboard-crm.data.js export const BandwidthReportData = [ { id: 1, valueDetail: { value: '63%', }, description: 'Server Errors' }, { id: 2, valueDetail: { value: '63%', }, description: 'Total Income' }, { id: 3, valueDetail: { value: '61%', color: 'alt' }, description: 'Server Target', progress : { value: 61, color: 'alt' } }, { id: 4, valueDetail: { value: '71%', color: 'danger' }, description: 'Income Target', progress : { value: 71, color: 'danger' } }, ]; export const BandwidthReportData2 = [ { id: 1, valueDetail: { value: '63%', }, description: 'Generated Leads', progress : { value: 63, color: 'danger' } }, { id: 2, valueDetail: { value: '32%', }, description: 'Submitted Tickets', progress : { value: 32, color: 'success' } }, { id: 3, valueDetail: { value: '71%', }, description: 'Server Allocation', progress : { value: 71, color: 'dark' } }, { id: 4, valueDetail: { value: '41%', }, description: 'Generated Leads', progress : { value: 41, color: 'warning' } }, ]; export const ChartBox3Data = [ { id: 1, defaultValue: '1896', defaultValueColor: 'success', mainTitleText: "Total Orders", descriptionText: 'Last year expenses', progressBarValue: 80, strokeWidth: 8, progressBarColor: 'primary', descriptionProgressDetail: 'YoY Growth' }, { id: 2, defaultValue: '$14M', defaultValueColor: 'warning', mainTitleText : 'Products Sold', descriptionText: 'Total revenue streams', progressBarValue: 90, strokeWidth: 8, progressBarColor: 'danger', descriptionProgressDetail :'Sales' }, { id: 3, defaultValue: '$568', defaultValueColor: 'danger', mainTitleText : 'Followers', descriptionText : 'People Interested', progressBarValue: 40, strokeWidth : 8, progressBarColor : 'success', descriptionProgressDetail :'Twitter Progress' } ]; export const DataChart = { data1: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [230, 202, 312, 340, 291, 165, 320, 290, 563, 420, 281, 219], backgroundColor: 'transparent', borderColor: '#3ac47d', borderWidth: 3, }] }, data2: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [165, 230, 260, 463, 420, 481, 319, 320, 302, 312, 340, 291], backgroundColor: 'transparent', borderColor: '#545cd8', borderWidth: 3, }] }, data3: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [290, 202, 312, 240, 291, 165, 320, 256, 563, 420, 431, 389], backgroundColor: 'transparent', borderColor: '#f7b924', borderWidth: 3, }] }, data4: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [230, 277, 300, 263, 220, 481, 311, 320, 302, 412, 340, 391], backgroundColor: 'transparent', borderColor: '#d92550', borderWidth: 3, }] }, data5: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [290, 242, 312, 250, 291, 185, 320, 256, 363, 320, 331, 389], backgroundColor: '#fdeabc', borderColor: '#f5bf3c', borderWidth: 6, }] }, data6: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [290, 282, 302, 295, 291, 285, 320, 256, 363, 320, 331, 320], backgroundColor: '#e3e4f3', borderColor: '#9298f1', borderWidth: 3, }] }, data7: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [260, 252, 252, 265, 291, 285, 240, 256, 263, 320, 300, 309], backgroundColor: '#f3e3e7', borderColor: '#d92550', borderWidth: 3, }] }, data8: { labels: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'], datasets: [{ label: 'New Accounts', data: [165, 230, 260, 463, 420, 481, 319, 320, 302, 312, 340, 291], backgroundColor: '#54595e', borderColor: '#808387', borderWidth: 3, }] }, }; export const DataChartComponentList = [ { id: 1, value: 874, description: 'Sales last month', graphData: DataChart.data1, borderColor: 'success' }, { id: 2, value: 1283, description: 'Sales income', graphData: DataChart.data2, borderColor: 'primary' }, { id: 3, value: 1286, description: 'Last month sales', graphData: DataChart.data3, borderColor: 'warning' }, { id: 4, value: 564, description: 'Total revenue', graphData: DataChart.data4, borderColor: 'danger' }, ];<file_sep>/src/pages/applications-mailbox/applications-mailbox.component.js import React, { useState } from 'react'; import { Avatar, Checkbox, Typography, Rate, Input } from 'antd'; import { TagOutlined, CalendarOutlined, MenuOutlined, SearchOutlined, MessageOutlined, WalletOutlined, SettingOutlined, PushpinOutlined, HourglassOutlined, } from '@ant-design/icons'; import CustomButton from 'Components/custom-button/custom-button.component'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import CustomBadges from 'Components/custom-badges/custom-badges.component'; import CustomMenu from 'Components/custom-menu/custom-menu.component'; import CustomMenuItem from 'Components/custom-menu-item/custom-menu-item.component'; import { MailboxData } from './application-mailbox.data'; import './applications-mailbox.styles.css'; const { Title, Text } = Typography; const ApplicationsMailbox = () => { const [ mailboxMenu, setMailboxMenu ] = useState(false); const handleToggleMailboxMenu = () => { setMailboxMenu(!mailboxMenu); } return ( <div className='mailbox-container'> <div className={`mailbox-menu-container ${mailboxMenu? 'mailbox-menu-show': ''}`}> <CustomButton block pill shadow color='primary' variant='solid'>Write New Email</CustomButton> <ul className='nav padding-top-20'> <li className='nav-item'> <p className='nav-item-header'>My Account</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <MessageOutlined style={style.iconStyle}/> Chat </div> <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <WalletOutlined style={style.iconStyle}/> Sent Items </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <SettingOutlined style={style.iconStyle}/> All Messages </div> <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item nav-item-divider'> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Trash </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <PushpinOutlined style={style.iconStyle} /> Others </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item nav-item-divider'> </li> <li className='nav-item'> <p className='nav-item-header'>Online Friends</p> </li> <li> <div className='flex-row padding-top-10 justify-content-center flex-wrap'> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='primary' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='secondary' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1507003211169-0a1dd7228f2d?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank'className='mrb-10' color='success' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='info' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='warning' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='danger' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1488426862026-3ee34a7d66df?ixlib=rb-1.2.1&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='alt' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1542393881816-df51684879df?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='info' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <CustomBadges href='https://twitter.com' target='_blank' className='mrb-10' color='warning' size={10} dot> <Avatar size={40} src="https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> </CustomBadges> <div className='padding-top-10'> <CustomButton variant='solid' color='success' pill >Start New Conversations</CustomButton> </div> </div> </li> </ul> </div> <div className={`inbox-container ${mailboxMenu? 'inbox-container-show' : ''}`}> <div className='mailbox-header-container'> <div className='flex-row align-item-center'> <MenuOutlined className='mailbox-menu' onClick={handleToggleMailboxMenu} style={style.menuMailbox} /> <Title level={3}>Inbox</Title> </div> <div className='inbox-search-container' > <Input addonBefore={<SearchOutlined />} placeholder='Search...' /> </div> </div> <div> <CustomMenu role='secondary' border={true}> { MailboxData.map((item) => ( <CustomMenuItem className='no-margin-no-padding' key={item.id}> <div className='inbox-mail-container'> <div className='flex-column align-items-center justify-content-center'> <Checkbox/> </div> <div style={{marginTop: '-5px'}}> <Rate count={1}/> </div> <div lassName='flex-column align-items-center justify-content-center'> <Avatar size={40} src={item.picture} /> </div> <div> <p className='profile-name'>{item.name}</p> { item.lastseen? <p className='last-seen-text'>Last seen {item.lastseen} ago</p> : null } </div> <div className='text-overflow padding-horizontal-10'> <Text className='gray'> {item.email} </Text> </div> <div lassName='flex-column align-items-center justify-content-center'> <TagOutlined className='gray'/> </div> <div className='flex-column align-items-end'> <Text className='gray'> <CalendarOutlined/> &nbsp; {item.date} </Text> </div> </div> <div className='inbox-mail-container-mobile'> <div className='flex-column align-items-center justify-content-center'> <Checkbox/> </div> <div style={{marginTop: '-5px'}}> <Rate count={1}/> </div> <div lassName='flex-column align-items-center justify-content-center'> <Avatar size={40} src={item.picture} /> </div> <div className='text-overflow padding-horizontal-10'> <p className='profile-name'>{item.name}</p> <Text className='gray'> {item.email} </Text> </div> <div className='flex-column align-items-end'> <Text className='gray'> <CalendarOutlined/> &nbsp; {item.date} </Text> </div> </div> </CustomMenuItem> )) } </CustomMenu> </div> </div> </div> ) }; const style = { iconStyle: { fontSize: '18px', width: '30px', textAlign: 'left', }, menuMailbox : { padding: 0, cursor: 'pointer' ,margin: '0 25px 0 0', lineHeight: '40px', fontSize: '20px', } } export default ApplicationsMailbox;<file_sep>/src/loader/loader.component.js import Loadable from 'react-loadable'; import Loader from 'Components/loader/loader.component'; export const DashboardAnalyticPage = Loadable({ loader: () => import('../pages/dashboard-analytic/dashboard-analytic.component'), loading: Loader, }); export const DashboardCommercePage = Loadable({ loader: () => import('../pages/dashboard-commerce/dashboard-commerce.component'), loading: Loader, }); export const DashboardSalesPage = Loadable({ loader: () => import('../pages/dashboard-sales/dashboard-sales.component'), loading: Loader, }); export const DashboardCrmPage = Loadable({ loader: () => import('../pages/dashboard-crm/dashboard-crm.component'), loading: Loader, }); export const ElementButtonsPage = Loadable({ loader: () => import('../pages/element-buttons/element-buttons.component'), loading: Loader, }); export const ElementCardsPage = Loadable({ loader: () => import('../pages/element-cards/element-cards.component'), loading: Loader, }); export const ElementBadgesAndLabelsPage = Loadable({ loader: () => import( '../pages/element-badges-and-labels/element-badges-and-labels.component' ), loading: Loader, }); export const ElementNavigationMenusPage = Loadable({ loader: () => import( '../pages/element-navigation-menus/element-navigation-menus.component' ), loading: Loader, }); export const ElementTimelinesPage = Loadable({ loader: () => import('../pages/element-timelines/element-timelines.component'), loading: Loader, }); export const ApplicationsMailboxPage = Loadable({ loader: () => import('../pages/applications-mailbox/applications-mailbox.component'), loading: Loader, }); export const ApplicationChatPage = Loadable({ loader: () => import('../pages/applications-chat/applications-chat.component'), loading: Loader, }); export const ApplicationFaqPage = Loadable({ loader: () => import('../pages/applications-faq/applications-faq.component'), loading: Loader, }); export const ChartBoxesVariation1Page = Loadable({ loader: () => import( '../pages/chart-boxes/chart-boxes-variation-1/chart-boxes-variation-1.component' ), loading: Loader, }); export const ChartBoxesVariation2Page = Loadable({ loader: () => import( '../pages/chart-boxes/chart-boxes-variation-2/chart-boxes-variation-2.component' ), loading: Loader, }); export const ChartBoxesVariation3Page = Loadable({ loader: () => import( '../pages/chart-boxes/chart-boxes-variation-3/chart-boxes-variation-3.component' ), loading: Loader, }); export const ProfileBoxesPage = Loadable({ loader: () => import('../pages/profile-boxes/profile-boxes.component'), loading: Loader, }); export const SigninPage = Loadable({ loader: () => import('../pages/signin/signin.component'), loading: Loader, }); export const SigninBoxedPage = Loadable({ loader: () => import('../pages/signin-boxed/signin-boxed.component'), loading: Loader, }); export const SignupPage = Loadable({ loader: () => import('../pages/signup/signup.component'), loading: Loader, }); export const SignupBoxedPage = Loadable({ loader: () => import('../pages/signup-boxed/signup-boxed.component'), loading: Loader, }); export const ForgotPasswordPage = Loadable({ loader: () => import('../pages/forgot-password/forgot-password.component'), loading: Loader, }); export const ForgotPasswordBoxedPage = Loadable({ loader: () => import('../pages/forgot-password-boxed/forgot-password-boxed.component'), loading: Loader, }); export const Page404 = Loadable({ loader: () => import('../pages/page-404/page-404.component'), loading: Loader, }); <file_sep>/src/components/task-list-container/task-list-container.styles.js import styled from 'styled-components'; import { colorsPalette } from 'Components/custom-color/custom-color'; export const TaskListBorderLeft = styled.div` width: 4px; border-radius: 5px; background-color: ${({color}) => color? 'rgba('+colorsPalette[color+'Rgb']+',.4)' : '#bdb6b6'}; `; export const TaskListContainerStyle = styled.div` padding: 10px 5px; border-bottom: 1px solid #bdb6b694;*/ &:hover { ${TaskListBorderLeft} { background-color: ${({color}) => color? 'rgba('+colorsPalette[color+'Rgb']+'1)' : '#bdb6b6'}; } } `; export const TaskListGrid = styled.div` display: grid; grid-template-columns: 30px 1fr; height: fit-content; gap: 10px; `; export const TaskListBorderContainer = styled.div` display: flex; height: auto; justify-content: center; position: relative; `; <file_sep>/src/components/task-list-container/task-list-container.component.js import React from 'react'; import { TaskListContainerStyle, TaskListGrid, TaskListBorderContainer, TaskListBorderLeft } from './task-list-container.styles'; const TaskListContainer = ({ color, children, ...props }) => { return ( <TaskListContainerStyle color={color} {...props}> <TaskListGrid> <TaskListBorderContainer> <TaskListBorderLeft color={color}> </TaskListBorderLeft> </TaskListBorderContainer> <div> { children } </div> </TaskListGrid> </TaskListContainerStyle> ) }; export default TaskListContainer;<file_sep>/src/components/chart-box-var-3/chart-box-var-3.component.js import React from 'react'; import { Progress } from 'antd'; import PropTypes from 'prop-types'; import { ChartBoxVar3Container, ChartBoxVar3Grid } from './chart-box-var-3.styles'; import { MainTitleText, DescriptionText, RightContainer, DescriptionProgressBarText, } from '../chart-box-var-2/chart-box-var-2.styles'; import { DefaultValueText } from '../chart-box-var-1/chart-box-var-1.styles'; import { colorsPalette } from '../custom-color/custom-color'; const ChartBoxVar3 = ({ bgColor, boxShadow, borderRadius, defaultValue, mainTitleText, descriptionText, mainTitleColor, descriptionTextColor, defaultValueColor, strokeWidth, progressBarColor, width, progressBarValue, descriptionProgressDetail, descriptionProgressBarColor, ...props }) => { return ( <ChartBoxVar3Container {...props} showBorder={props.showBorder} col={props.col} row={props.row} bgColor={bgColor} boxShadow={boxShadow} borderRadius={borderRadius}> <ChartBoxVar3Grid width={width}> <div className='flex-column justify-content-center'> <MainTitleText mainTitleColor={mainTitleColor} className='fw-bold'>{mainTitleText}</MainTitleText> { descriptionText? <DescriptionText descriptionTextColor={descriptionTextColor} >{descriptionText}</DescriptionText>: null } </div> <RightContainer> <DefaultValueText defaultValueColor={defaultValueColor}>{defaultValue}</DefaultValueText> </RightContainer> </ChartBoxVar3Grid> { progressBarValue? <div style={{width: width? width: '100%'}}> <Progress strokeWidth={strokeWidth} strokeColor={`${colorsPalette[progressBarColor] ? colorsPalette[progressBarColor] : progressBarColor}`} percent={progressBarValue} status="active" showInfo={false} /> <DescriptionProgressBarText descriptionProgressBarColor={descriptionProgressBarColor}> {descriptionProgressDetail} </DescriptionProgressBarText> </div> : null } </ChartBoxVar3Container> ) }; export default ChartBoxVar3; ChartBoxVar3.propTypes = { bgColor: PropTypes.string, boxShadow: PropTypes.bool, borderRadius: PropTypes.bool, mainTitleColor: PropTypes.string }; ChartBoxVar3.defaultProps = { bgColor: 'white', boxShadow: true, borderRadius: true, mainTitleColor: '#737373', descriptionTextColor: '#949494', }; <file_sep>/src/pages/element-buttons/element-buttons.component.js import React from 'react'; import CustomTabsWrapper from 'Components/custom-tabs-wrapper/custom-tabs-wrapper.component'; import CustomTabPanel from 'Components/custom-tab-panel/custom-tab-panel.component'; import SolidButtonContainer from './solid-buttons-container/solid-button-container.component'; import OutlinedButtonContainer from './outlined-button-container/outlined-button-container.component'; import Outlined2xButtonContainer from './outlined2x-button-container/outlined2x-button-container.component'; import DashedButtonContainer from './dashed-button-container/dashed-button-container.component'; import PillsButtonContainer from './pills-button-container/pills-button-container.component'; import SquareButtonContainer from './square-button-container/square-button-container.component'; import ShadowButtonContainer from './shadow-button-container/shadow-button-container.component'; import HorizontalIconContainer from './horizontal-icon-container/horizontal-icon-container.component'; import VerticalIconContainer from './vertical-icon-container/vertical-icon-container.component'; const ElementButtons = () => { return ( <div> <CustomTabsWrapper > <CustomTabPanel data-key='solid' title='Solid'> <SolidButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='outlined' title='Outlined'> <OutlinedButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='outlined-2x' title='Outlined 2x'> <Outlined2xButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='dashed' title='Dashed'> <DashedButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='pills' title='Pills'> <PillsButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='square' title='Square'> <SquareButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='shadow' title='Shadow'> <ShadowButtonContainer/> </CustomTabPanel> <CustomTabPanel data-key='horizontal-icon' title='Horizontal Icon'> <HorizontalIconContainer/> </CustomTabPanel> <CustomTabPanel data-key='vertical-icon' title='Vertical Icon'> <VerticalIconContainer/> </CustomTabPanel> </CustomTabsWrapper> </div> ) }; export default ElementButtons;<file_sep>/src/components/mega-menu/mega-menu.component.js import React from 'react'; import { Typography } from 'antd'; import { ContactsOutlined, ContainerOutlined, PictureOutlined, DashboardOutlined } from '@ant-design/icons'; import './mega-menu.styles.css'; const { Title } = Typography; const MegaMenu = ({ show }) => { return ( <div className={`mega-menu-container ${show? 'mmc-show' : 'mmc-hidden'}`}> <div className='mega-menu-tooltip'/> <div className='mega-menu-content'> <div className='mega-menu-overview'> <Title level={5}>Overview</Title> <div className='mega-menu-content-wrap'> <a href='#'><ContactsOutlined className='mega-menu-icon' />Contacts</a> </div> <div className='mega-menu-content-wrap'> <a href='#'><ContainerOutlined className='mega-menu-icon'/>Incidents</a> </div> <div className='mega-menu-content-wrap'> <a href='#'><PictureOutlined className='mega-menu-icon'/>Companies</a> </div> <div className='mega-menu-content-wrap'> <a href='#'><DashboardOutlined className='mega-menu-icon'/>Dashboard</a> </div> </div> <div className='mega-menu-overview'> <Title level={5}>Favourites</Title> <div className='mega-menu-content-wrap'> <a href='#'>Report Conversions</a> </div> <div className='mega-menu-content-wrap'> <a href='#'>Quick Start</a> </div> <div className='mega-menu-content-wrap'> <a href='#'>Users & Groups</a> </div> <div className='mega-menu-content-wrap'> <a href='#'>Properties</a> </div> </div> <div className='mega-menu-overview'> <Title level={5}>Sales & Marketing</Title> <div className='mega-menu-content-wrap'> <a href='#'>Resource Groups</a> </div> <div className='mega-menu-content-wrap'> <a href='#'>Goal Metrics</a> </div> <div className='mega-menu-content-wrap'> <a href='#'>Campaign</a> </div> <div className='mega-menu-content-wrap'> <a href='#'>Queues</a> </div> </div> </div> </div> ) }; export default MegaMenu;<file_sep>/src/pages/dashboard-analytic/dashboard-analytic-var-1/dashboard-analytic-var-1.component.js import React, { useRef } from 'react'; import { Typography, Carousel, Table, Input, Checkbox } from 'antd'; import { Line } from 'react-chartjs-2'; import { GlobalOutlined, CustomerServiceOutlined, DownOutlined, CrownOutlined, MacCommandOutlined, LeftOutlined, RightOutlined, UpOutlined, CheckOutlined, DeleteOutlined, } from '@ant-design/icons'; import { CustomCard, CustomCardFooter, CustomCardBody, CustomCardHeader, CustomCardTitleText, } from 'Components/custom-card/custom-card.styles'; import { DefaultValueDescriptionText, DefaultValueText, ProgressValueTextContainer, ChartBoxVarIconContainer, } from 'Components/chart-box-var-1/chart-box-var-1.styles'; import CustomButton from 'Components/custom-button/custom-button.component'; import CustomTimeline from 'Components/custom-timeline/custom-timeline.component'; import CustomTimelineItem from 'Components/custom-timeline-item/custom-timeline-item.component'; import ChatBallon from 'Components/chat-ballon/chat-ballon.component'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; import TaskListContainer from 'Components/task-list-container/task-list-container.component'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import { ChatList2 } from '../../applications-chat/application-chat.data'; import { Data1, Data2, Data3 } from 'Data/chart.data'; import { Options } from 'Data/settings-chart.data'; import { DataTable1, Columns1 } from 'Data/table.data'; const { Text } = Typography; const DashboardAnalyticVariation1 = () => { const customeSlider = useRef(); // setting slider configurations const sliderSettings = { infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, arrows: false, dots: false, }; const gotoNext = () => { customeSlider.current.innerSlider.slickNext(); }; const gotoPrev = () => { customeSlider.current.innerSlider.slickPrev(); }; return ( <div> <CustomCard className="mb-30"> <CustomCardHeader> <CustomCardTitleText>Portfolio Performance</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <div className="flex-column align-items-center"> <div className="grid-3-gap-10 width-100"> <div className="mb-10 flex-row align-items-center"> <ChartBoxVarIconContainer className="mr-30" iconContainerShape="circle" iconColor="#444444" iconBgColor="#f7b924" > <CustomerServiceOutlined /> </ChartBoxVarIconContainer> <div> <DefaultValueDescriptionText style={{ marginBottom: 0 }}> Cash Deposit </DefaultValueDescriptionText> <DefaultValueText style={{ lineHeight: 1 }}> 1,7M </DefaultValueText> <div className="flex-row align-items-center"> <ProgressValueTextContainer progressValueColor="danger" justifyContent="flex-start" > <span> <DownOutlined /> </span> <span>54.1%</span> </ProgressValueTextContainer> <Text className="no-mb margin-top-8"> &nbsp; Less Earnings </Text> </div> </div> </div> <div className="mb-10 flex-row align-items-center"> <ChartBoxVarIconContainer className="mr-30" iconContainerShape="circle" iconColor="white" iconBgColor="#d92550" > <CrownOutlined /> </ChartBoxVarIconContainer> <div> <DefaultValueDescriptionText style={{ marginBottom: 0 }}> Invested Dividents </DefaultValueDescriptionText> <DefaultValueText style={{ lineHeight: 1 }}> 9M </DefaultValueText> <div className="flex-row align-items-center"> <Text className="no-mb margin-top-8"> Growth Rate&nbsp; </Text> <ProgressValueTextContainer progressValueColor="info" justifyContent="flex-start" > <span> <DownOutlined /> </span> <span>14.1%</span> </ProgressValueTextContainer> </div> </div> </div> <div className="mb-10 flex-row align-items-center"> <ChartBoxVarIconContainer className="mr-30" iconContainerShape="circle" iconColor="white" iconBgColor="#3ac47d" > <MacCommandOutlined /> </ChartBoxVarIconContainer> <div> <DefaultValueDescriptionText style={{ marginBottom: 0 }}> Capital Gains </DefaultValueDescriptionText> <DefaultValueText defaultValueColor="success" style={{ lineHeight: 1 }} > $563 </DefaultValueText> <div className="flex-row align-items-center"> <Text className="no-mb margin-top-8"> Increased by&nbsp; </Text> <ProgressValueTextContainer progressValueColor="warning" justifyContent="flex-start" > <span> <DownOutlined /> </span> <span>7.35%</span> </ProgressValueTextContainer> </div> </div> </div> </div> </div> </CustomCardBody> <CustomCardFooter className="flex-column justify-content-center align-items-center"> <CustomButton shadow icon={<GlobalOutlined />} size="large" variant="solid" color="primary" pill={true} > View Complete Report </CustomButton> </CustomCardFooter> </CustomCard> <div className="grid-2-gap-30 mb-30"> <CustomCard className="overflow-hidden"> <CustomCardHeader> <CustomCardTitleText>Techinical Support</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <div className="technical-support-container-2 flex-column align-items-center justify-content-center"> <button className="button-navigation button-prev" onClick={() => gotoPrev()} > <LeftOutlined /> </button> <button className="button-navigation button-next" onClick={() => gotoNext()} > <RightOutlined /> </button> <div style={{ width: '100%' }}> <Carousel {...sliderSettings} ref={customeSlider}> <div className="relative"> <div className="da-absolute-chart-title-container"> <p className="da-fs-20-upper color6d"> NEW ACCOUNTS SINCE 2019 </p> <div className="flex-row align-items-center"> <UpOutlined className="da-icon-detail-performance success" /> <p className="da-fs-34-bold color5d">78</p> <p className="da-fs-30-fw-400 color98">%</p> <p className="fs-16 success no-mb ml-10">+14</p> </div> </div> <Line data={Data1} width={100} height={300} options={Options} /> </div> <div className="relative"> <div className="da-absolute-chart-title-container"> <p className="da-fs-20-upper color6d">HELPDESK TIKCET</p> <div className="flex-row align-items-center"> <p className="da-fs-34-bold warning">34</p> <p className="fs-16 no-mb ml-10 color98">5%</p> <p className="fs-16 no-mb ml-5">increase</p> </div> </div> <Line data={Data2} width={100} height={300} options={Options} /> </div> <div className="relative"> <div className="da-absolute-chart-title-container"> <p className="da-fs-20-upper color6d"> LAST YEAR TOTAL SALES </p> <div className="flex-row align-items-center"> <p className="da-fs-34-bold fw-400 color98">$</p> <p className="da-fs-34-bold primary color5d">629</p> <DownOutlined className="da-icon-detail-performance primary ml-5" /> </div> </div> <Line data={Data3} width={100} height={300} options={Options} /> </div> </Carousel> </div> </div> </CustomCardBody> </CustomCard> <CustomCard> <CustomCardHeader> <CustomCardTitleText>Timeline Example</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <div className="dashboard-analytic-timeline-container"> <CustomTimeline size="regular"> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 11.00 PM </Text> } color="success" > <Text className="uppercase fs-14 fw-bold"> All hands meeting </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, today at{' '} <Text type="warning">11.00 PM</Text> </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 12.00 PM </Text> } color="warning" > <p className="no-margin-no-padding"> Another meeting today, at{' '} <Text type="danger" className="fw-bold"> 12.00 PM </Text> </p> <p className="no-margin-no-padding"> Yet another one, at <Text type="success">15.00 PM</Text> </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 15.00 PM </Text> } color="danger" > <Text className="uppercase fs-14 fw-bold"> Build the production release </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 12.00 PM </Text> } color="primary" > <Text type="success" className="uppercase fs-14 fw-bold"> Something not important </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 11.00 PM </Text> } color="success" > <Text className="uppercase fs-14 fw-bold"> All hands meeting </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, today at{' '} <Text type="warning">11.00 PM</Text> </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 12.00 PM </Text> } color="warning" > <p className="no-margin-no-padding"> Another meeting today, at{' '} <Text type="danger" className="fw-bold"> 12.00 PM </Text> </p> <p className="no-margin-no-padding"> Yet another one, at <Text type="success">15.00 PM</Text> </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 15.00 PM </Text> } color="danger" > <Text className="uppercase fs-14 fw-bold"> Build the production release </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 12.00 PM </Text> } color="primary" > <Text type="success" className="uppercase fs-14 fw-bold"> Something not important </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 11.00 PM </Text> } color="success" > <Text className="uppercase fs-14 fw-bold"> All hands meeting </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, today at{' '} <Text type="warning">11.00 PM</Text> </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 12.00 PM </Text> } color="warning" > <p className="no-margin-no-padding"> Another meeting today, at{' '} <Text type="danger" className="fw-bold"> 12.00 PM </Text> </p> <p className="no-margin-no-padding"> Yet another one, at <Text type="success">15.00 PM</Text> </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 15.00 PM </Text> } color="danger" > <Text className="uppercase fs-14 fw-bold"> Build the production release </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem label={ <Text className="fs-12" type="secondary"> 12.00 PM </Text> } color="primary" > <Text type="success" className="uppercase fs-14 fw-bold"> Something not important </Text> <p className="no-margin-no-padding"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> </CustomTimeline> </div> </CustomCardBody> <CustomCardFooter></CustomCardFooter> </CustomCard> </div> <CustomCard className="mb-30"> <CustomCardHeader> <CustomCardTitleText>Easy Dynamic Tables</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <Table columns={Columns1} dataSource={DataTable1} /> </CustomCardBody> </CustomCard> <div className="grid-2-gap-30 mb-30"> <CustomCard> <CustomCardHeader> <CustomCardTitleText>Task List</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <TaskListContainer className="da-tasklist" color="primary"> <div className="da-task-list-container"> <Checkbox></Checkbox> <div className="flex-column"> <div className="flex-row"> <Text className="fw-bold color5d mr-10">Wash the car</Text> <CustomLabelBadge color="danger">Danger</CustomLabelBadge> </div> <Text className="color98">Written by Bob</Text> </div> <div className="da-task-list-hidden flex-row justify-content-end"> <CustomButton className="mr-10" color="success" variant="solid" icon={<CheckOutlined />} /> <CustomButton className="mr-10" color="danger" variant="solid" icon={<DeleteOutlined />} /> </div> </div> </TaskListContainer> <TaskListContainer className="da-tasklist" color="warning"> <div className="da-task-list-container"> <Checkbox></Checkbox> <div className="flex-column"> <div className="flex-row"> <Text className="fw-bold color5d mr-10"> Task with badge </Text> </div> <Text className="color98">Show on hover actions !</Text> </div> <div className="flex-row justify-content-end"> <div className="da-task-list-hidden"> <CustomButton className="mr-10" color="success" variant="solid" icon={<CheckOutlined />} /> </div> <CustomLabelBadge color="success">NEW</CustomLabelBadge> </div> </div> </TaskListContainer> <TaskListContainer className="da-tasklist" color="danger"> <div className="da-task-list-container"> <Checkbox></Checkbox> <div className="flex-column"> <Text className="fw-bold color5d mr-10"> Development Task </Text> <Text className="color98">Finish React ToDo AppList !</Text> </div> <div className="flex-row justify-content-end"> <CustomButton className="mr-10" color="success" variant="solid" icon={<CheckOutlined />} /> <CustomButton className="mr-10" color="danger" variant="solid" icon={<DeleteOutlined />} /> </div> </div> </TaskListContainer> <TaskListContainer className="da-tasklist" color="success"> <div className="da-task-list-container"> <Checkbox></Checkbox> <div className="flex-column"> <div className="flex-row"> <Text className="fw-bold color5d mr-10">Wash the car</Text> <CustomLabelBadge color="warning">INFO</CustomLabelBadge> </div> <Text className="color98">Written by Bob</Text> </div> <div className="da-task-list-hidden flex-row justify-content-end"> <CustomButton className="mr-10" color="success" variant="solid" icon={<CheckOutlined />} /> <CustomButton className="mr-10" color="danger" variant="solid" icon={<DeleteOutlined />} /> </div> </div> </TaskListContainer> <TaskListContainer className="da-tasklist" color="primary"> <div className="da-task-list-container"> <Checkbox></Checkbox> <div className="flex-column"> <div className="flex-row"> <Text className="fw-bold color5d mr-10"> Task with Badge </Text> <CustomLabelBadge color="info">NEW</CustomLabelBadge> </div> <Text className="color98">Written by Silaladungka</Text> </div> <div className="flex-row justify-content-end"> <CustomButton className="mr-10" color="success" variant="solid" icon={<CheckOutlined />} /> <CustomButton className="mr-10" color="danger" variant="solid" icon={<DeleteOutlined />} /> </div> </div> </TaskListContainer> </CustomCardBody> <CustomCardFooter> <CustomButton color="link" variant="solid" className="mr-10"> Cancel </CustomButton> <CustomButton color="primary" variant="solid"> Add Task </CustomButton> </CustomCardFooter> </CustomCard> <CustomCard> <CustomCardHeader> <CustomCardTitleText>Chat Box</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <ChatBallon className="dashboard-analytic-timeline-container" chatlist={ChatList2} /> <div className="text-input-chat-container"> <Input placeholder="Write here and hit enter to send..." /> </div> </CustomCardBody> </CustomCard> </div> <div className="mb-30"> <ChartBoxGridContainer col={3}> <ChartBoxVar3 defaultValue="1896" defaultValueColor="success" mainTitleText="Total Orders" descriptionText="Last year expenses" progressBarValue={80} strokeWidth={6} progressBarColor="primary" descriptionProgressDetail="YoY Growth" /> <ChartBoxVar3 defaultValue="$568" defaultValueColor="primary" mainTitleText="Clients" descriptionText="Total Clients Profit" progressBarValue={50} strokeWidth={6} progressBarColor="warning" descriptionProgressDetail="Retention" /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor="warning" mainTitleText="Products Sold" descriptionText="Total revenue streams" progressBarValue={100} strokeWidth={6} progressBarColor="danger" descriptionProgressDetail="Sales" /> <ChartBoxVar3 defaultValue="46%" defaultValueColor="danger" mainTitleText="Followers" descriptionText="Peple interested" progressBarValue={40} strokeWidth={6} progressBarColor="success" descriptionProgressDetail="Twitter Progress" /> <ChartBoxVar3 defaultValue="36%" defaultValueColor="danger" mainTitleText="Products Sold" descriptionText="Total revenue streams" progressBarValue={80} strokeWidth={6} progressBarColor="success" descriptionProgressDetail="Sales" /> <ChartBoxVar3 defaultValue="$23M" defaultValueColor="primary" mainTitleText="Followers" descriptionText="Peple interested" progressBarValue={90} strokeWidth={6} progressBarColor="warning" descriptionProgressDetail="Twitter Progress" /> </ChartBoxGridContainer> </div> </div> ); }; export default DashboardAnalyticVariation1; <file_sep>/src/components/chat-ballon/chat-ballon.styles.js import styled from 'styled-components'; import { colorsPalette } from '../custom-color/custom-color'; export const ChatContainer = styled.div` overflow-Y : auto; overflow-X: hidden; ` export const ChatBallonContainer = styled.div` display: grid; grid-template-columns: 50px auto; align-items: flex-start; justify: flex-start; margin-bottom: 20px; `; export const ChatBallonOwnerContainer = styled.div` display: flex; width: 100%; align-items: flex-start; justify-content: flex-end; margin-bottom: 20px; padding-right: 20px; `; export const ChatListEndWrapper = styled.div` display: flex; flex-direction: column; align-items: flex-end; margin-bottom: 10px; `; export const ChatListStartWrapper = styled.div` display: flex; flex-direction: column; align-items: flex-start; margin-bottom: 10px; `; export const OwnerContainerChat = styled.div` margin-left: 15px; background-color: ${colorsPalette.primary}; color: ${colorsPalette.primaryText}; padding: 10px 25px; border-bottom-left-radius: 10px; border-top-left-radius: 10px; border-bottom-right-radius: 10px; margin-bottom: 10px; width: fit-content; line-height: 2; `; export const ChatContainerText = styled.div` width: calc(100% - 50px); `; export const NotOwnerContainerChat = styled.div` margin-left: 15px; background-color: #f0f0f6; padding: 10px 25px; border-bottom-left-radius: 10px; border-top-right-radius: 10px; border-bottom-right-radius: 10px; margin-bottom: 10px; width: fit-content; line-height: 2; `; export const AvatarProfileContainer = styled.div` width: 40px; `; export const TimeChat = styled.p` margin: 0 0 0 25px; font-size: 11px; color: #949292 !important; `;<file_sep>/src/pages/forgot-password-boxed/forgot-password-boxed.component.js import React from 'react'; import { Typography, Form, Input, Button } from 'antd'; const { Title } = Typography; import '../signin/signin.styles.css'; import '../signin-boxed/signin-boxed.styles.css'; import '../signup/signup.styles.css'; import '../signup-boxed/signup-boxed.styles.css'; const ForgotPasswordBoxed = () => { return ( <div className='signin-boxed-container'> <div className='signin-page-logo-white'/> <div className='card-container '> <Form name="basic" initialValues={{ remember: true }} > <div className='signin-boxed-form-container'> <div className='flex-start-column'> <Title level={3} className='signin-page-welcome-back'>Forgot your Password</Title> <Title level={5} className='signin-page-please-text'>Use the form below to recover it.</Title> </div> <div className='signin-box-form-wrapper'> <div className='signin-form-wrapper'> <Form.Item name="email" rules={[{ required: true, message: 'Please input your email!' }]} > <Input placeholder='Your email'/> </Form.Item> </div> <div className='flex-start'> <Title level={5} className='signin-page-sign-up-text'>Sign in existing account</Title> </div> </div> </div> <div className='signin-page-line'></div> <Form.Item> <div className='flex-end signin-footer'> <Button type="primary">Recover Password</Button> </div> </Form.Item> </Form> </div> </div> ) }; export default ForgotPasswordBoxed;<file_sep>/src/routing.js import React from 'react'; import { Route, Switch } from 'react-router-dom'; import { DashboardAnalyticPage, DashboardCommercePage, DashboardCrmPage, DashboardSalesPage, ElementBadgesAndLabelsPage, ElementButtonsPage, ElementCardsPage, ElementNavigationMenusPage, ElementTimelinesPage, ApplicationChatPage, ApplicationFaqPage, ApplicationsMailboxPage, ChartBoxesVariation1Page, ChartBoxesVariation2Page, ChartBoxesVariation3Page, ProfileBoxesPage, SigninBoxedPage, SigninPage, SignupBoxedPage, SignupPage, ForgotPasswordBoxedPage, ForgotPasswordPage, Page404 } from 'Loader/loader.component'; const Routing = () => { return ( <Switch> <Route exact path='/' component={DashboardAnalyticPage} /> <Route exact path='/pages/login' component={SigninPage}/> <Route exact path='/pages/login-boxed' component={SigninBoxedPage}/> <Route exact path='/pages/register' component={SignupPage}/> <Route exact path='/pages/register-boxed' component={SignupBoxedPage}/> <Route exact path='/pages/forgot-password' component={ForgotPasswordPage}/> <Route exact path='/pages/forgot-password-boxed' component={ForgotPasswordBoxedPage}/> <Route exact path='/elements/buttons' component={ElementButtonsPage}/> <Route exact path='/elements/badges' component={ElementBadgesAndLabelsPage}/> <Route exact path='/elements/cards' component={ElementCardsPage}/> <Route exact path='/elements/navigations' component={ElementNavigationMenusPage}/> <Route exact path='/elements/timelines' component={ElementTimelinesPage}/> <Route exact path='/applications/mailbox' component={ApplicationsMailboxPage}/> <Route exact path='/applications/chat' component={ApplicationChatPage}/> <Route exact path='/applications/faq' component={ApplicationFaqPage}/> <Route exact path='/chart-boxes/variation-1' component={ChartBoxesVariation1Page}/> <Route exact path='/chart-boxes/variation-2' component={ChartBoxesVariation2Page}/> <Route exact path='/chart-boxes/variation-3' component={ChartBoxesVariation3Page}/> <Route exact path='/profile-boxes' component={ProfileBoxesPage} /> <Route exact path='/dashboard/analytics' component={DashboardAnalyticPage}/> <Route exact path='/dashboard/commerce' component={DashboardCommercePage}/> <Route exact path='/dashboard/sales' component={DashboardSalesPage}/> <Route exact path='/dashboard/crm' component={DashboardCrmPage}/> <Route path='*' exact={true} component={Page404} /> </Switch> ) }; export default Routing;; <file_sep>/src/pages/dashboard-sales/dashboard-sales.component.js import React from 'react'; import { Typography, Avatar, Table, Progress } from 'antd'; import { TrophyOutlined, DownOutlined, UpOutlined, LaptopOutlined, CheckCircleTwoTone, AntDesignOutlined } from '@ant-design/icons'; import { Line, Bar } from 'react-chartjs-2'; import { CustomCard, CustomCardFooter, CustomCardBody, CustomCardHeader } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import CustomButton from 'Components/custom-button/custom-button.component'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; import CustomTabsWrapper from 'Components/custom-tabs-wrapper/custom-tabs-wrapper.component'; import CustomTabPanel from 'Components/custom-tab-panel/custom-tab-panel.component'; import CustomBadges from 'Components/custom-badges/custom-badges.component'; import CustomTimeline from 'Components/custom-timeline/custom-timeline.component'; import CustomTimelineItem from 'Components/custom-timeline-item/custom-timeline-item.component'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; import { Data2, Data3, Data12 } from 'Data/chart.data'; import { Options6, Options7 } from 'Data/settings-chart.data'; import { DataHighlights2, DataTopPerformanceLaptop, ColumnsEasyDynTable, DataEasyDynTable } from 'Data/table.data'; import { colorsPalette } from 'Components/custom-color/custom-color'; import './dashboard-sales.styles.css'; const { Title, Text } = Typography; const DashboardSales = () => { return ( <div> <div className='grid-3-gap-30'> <CustomCard className='overflow-hidden'> <CustomCardHeader> <TrophyOutlined /> &nbsp;Top Sellers </CustomCardHeader> <CustomCardBody> <div className='mb-30'> <div> <p className='fs-16 fw-400 color98'>NEW ACCOUNT SALES SINCE 2018</p> <div className='flex-row align-items-center'> <UpOutlined className='da-icon-detail-performance success ml-5' /> <p className='da-fs-34-bold primary color5d'>9%</p> <p className='fs-14 no-mb ml-5 danger'>+14% failed</p> </div> </div> <Line data={Data2} width={100} height={40} options={Options6} /> </div> <div> <p className='fs-14 color98 fw-400'>AUTHORS</p> <div className='height-400 overflow-auto'> { DataHighlights2.map((item) => ( <div className='da-highlights-item'> <div className='flex-row align-items-center'> <Avatar className='mr-20' size={40} src={item.img} /> <div> <p className='color6d no-margin-no-padding'>{item.name}</p> <CustomLabelBadge pill color='dark'> {item.badge} </CustomLabelBadge> </div> </div> <div className='flex-row-fit-content align-items-center'> <Title level={3} className='success'>{item.value}</Title> { item.icon.type === 'up' ? <UpOutlined className={item.icon.color} style={style.downIcon} /> : <DownOutlined className={item.icon.color} style={style.downIcon} /> } </div> </div> )) } </div> </div> </CustomCardBody> <CustomCardFooter className='width-100 align-items-center justify-content-center flex-row'> <CustomButton color='primary' variant='solid'>View Complete Report</CustomButton> </CustomCardFooter> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardHeader> <LaptopOutlined /> &nbsp;Best Selling Products </CustomCardHeader> <CustomCardBody> <div className='mb-30'> <div> <p className='fs-16 fw-400 color98'>TOSHIBA LAPTOPS</p> <div className='flex-row align-items-center'> <DownOutlined className='da-icon-detail-performance warning ml-5' /> <p className='da-fs-34-bold primary color5d'>$984</p> <p className='fs-14 no-mb ml-5 success'>+14</p> </div> </div> <Line data={Data3} width={100} height={40} options={Options6} /> </div> <div> <p className='fs-14 color98 fw-400'>TOP PERFORMING</p> <div className='height-400 overflow-auto'> { DataTopPerformanceLaptop.map((item) => ( <div className='da-highlights-item'> <div className='flex-row align-items-center'> <Progress type="circle" strokeColor={colorsPalette[item.progress.color]} width={60} className='mr-20' percent={item.progress.value} status="active" /> <div> <p className='color6d no-margin-no-padding'>{item.name}</p> <CustomLabelBadge pill color='dark'> {item.badge} </CustomLabelBadge> </div> </div> <div className='flex-row-fit-content align-items-center'> <Title level={3} className='success'>{item.value}</Title> { item.icon.type === 'up' ? <UpOutlined className={item.icon.color} style={style.downIcon} /> : <DownOutlined className={item.icon.color} style={style.downIcon} /> } </div> </div> )) } </div> </div> </CustomCardBody> <CustomCardFooter className='width-100 align-items-center justify-content-center flex-row'> <CustomButton color='primary' variant='solid'>View All Participants</CustomButton> </CustomCardFooter> </CustomCard> <CustomCard className='span-grid-column overflow-hidden'> <CustomCardBody> <Title level={4}>Portfolio Performance</Title> <div className='mb-30'> <ChartBoxVar1 boxShadow={false} variant='progress-circle' progressBarValue={70} progressBarColor='success' defaultValue='$563' defaultValueColor='success' defaultValueDescription='Capital Gains' > <div className='margin-top-8'> <span className='color6d'>Increased by <UpOutlined className='warning'/> <strong className='warning'>7.35%</strong></span> </div> </ChartBoxVar1> <ChartBoxVar1 boxShadow={false} variant='progress-circle' progressBarValue={42} progressBarColor='danger' defaultValue='$194' defaultValueColor='danger' defaultValueDescription='Withdrawal' > <div className='margin-top-8'> <span className='color6d'>Down by <DownOutlined className='success'/> <strong className='success'>21.8%</strong></span> </div> </ChartBoxVar1> </div> <div className='flex-column align-items-center'> <div className='mb-30 text-align-center'> <Title className='color5d no-margin-no-padding' level={4}>Target Sales</Title> <Title className='color98 fw-400 no-margin-no-padding' level={5}>Total Performance for this month</Title> </div> <Bar data={Data12} height={260} options={Options7} /> </div> </CustomCardBody> </CustomCard> <CustomCard className='ds-span-2 mb-30'> <CustomCardHeader>Easy Dynamic Tables</CustomCardHeader> <CustomCardBody> <Table columns={ColumnsEasyDynTable} dataSource={DataEasyDynTable} /> </CustomCardBody> </CustomCard> <CustomCard className='span-grid-column mb-30'> <CustomCardHeader>Technical Support</CustomCardHeader> <CustomCardHeaderWithImage noneBorderRadius={true} backgroundColorOverlay='#adadade6' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1546629313-ea9c287a8b9f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'}> <Title className='text-align-center' level={4}>Notifications</Title> <Text>You have <strong className='danger'> 22</strong> notifications unread</Text> </CustomCardHeaderWithImage> <CustomCardBody> <CustomTabsWrapper> <CustomTabPanel data-key='message' title='Message'> <div className='ds-notification-height'> <CustomTimeline size='small'> <CustomTimelineItem color='danger'> All Hands Meeting </CustomTimelineItem> <CustomTimelineItem color='warning'> Yet another one, <Text type="success"> at 10.30 AM</Text> </CustomTimelineItem> <CustomTimelineItem color='success'> Build the productions release <CustomLabelBadge style={{marginLeft: '20px'}} color='danger'> NEW </CustomLabelBadge> </CustomTimelineItem> <CustomTimelineItem color='primary'> <p>Something not important</p> <Avatar.Group maxCount={4} maxStyle={{ color: '#f56a00', backgroundColor: '#fde3cf' }}> <Avatar src="https://zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png" /> <Avatar style={{ backgroundColor: '#f56a00' }}>K</Avatar> <Avatar style={{ backgroundColor: '#545cd8' }}>U</Avatar> <Avatar style={{ backgroundColor: '#d92550' }}>I</Avatar> <Avatar style={{ backgroundColor: '#1890ff' }} icon={<AntDesignOutlined />} /> </Avatar.Group> </CustomTimelineItem> </CustomTimeline> </div> </CustomTabPanel> <CustomTabPanel data-key='events' title='Events'> <div className='ds-notification-height'> <CustomTimeline size='regular'> <CustomTimelineItem color='success'> <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='warning'> <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem color='danger'> <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> </CustomTimeline> </div> </CustomTabPanel> <CustomTabPanel data-key='system-error' title='System Error'> <div className='flex-column align-items-center mb-30'> <CheckCircleTwoTone twoToneColor="#31b16f" style={{fontSize: '80px', marginBottom: '20px'}}/> <Title className='fw-400 no-margin-no-padding color98' level={4}>All caught up !</Title> <Title className='fw-400 no-margin-no-padding' level={3}>There are no system errors !</Title> </div> </CustomTabPanel> </CustomTabsWrapper> </CustomCardBody> <CustomCardFooter className='flex-row align-items-center justify-content-center'> <CustomBadges className='mrb-10' color='warning' size={12} dot> <CustomButton color='dark' pill shadow variant='solid'> View All Messages </CustomButton> </CustomBadges> </CustomCardFooter> </CustomCard> </div> <div className='mb-30'> <ChartBoxGridContainer col={3}> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='warning' mainTitleText='Clients' descriptionText='Total Clients Profit' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='danger' mainTitleText='Products Sold' descriptionText='Total revenue streams' /> </ChartBoxGridContainer> </div> </div> ) }; const style = { downIcon: { fontSize: '11px', marginLeft: '10px' }, settingIcon : { fontSize: '79px', color: '#a86799' } } export default DashboardSales;<file_sep>/src/pages/dashboard-analytic/dashboard-analytic-var-1/dashboard-analytic.data.js import React from 'react'; import { Typography, Carousel, Table, Tag, Space, Input, Checkbox } from 'antd'; export const Data1 = { labels: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ], datasets: [ { label: 'New Accounts', data: [180, 202, 312, 430, 111, 165, 320, 290, 563, 640, 721, 821], backgroundColor: '#d8f3e5', borderColor: '#3ac47d', borderWidth: 6, }, ], }; export const Data2 = { labels: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ], datasets: [ { label: 'Helpdesk Tickets', data: [200, 202, 212, 210, 220, 203, 205, 210, 209, 226, 220, 222], backgroundColor: '#fdf1d3', borderColor: '#f7b924', borderWidth: 6, }, ], }; export const Data3 = { labels: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ], datasets: [ { label: 'Total Sales', data: [120, 122, 128, 130, 126, 125, 120, 123, 120, 125, 133, 127, 120], backgroundColor: '#dddef7', borderColor: '#545cd8', borderWidth: 6, }, ], }; export const Data4 = { labels: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ], datasets: [ { label: 'Helpdesk Tickets', data: [120, 122, 128, 130, 126, 125, 120, 123, 120, 125, 133, 127, 120], backgroundColor: '#f1dae1', borderColor: '#d92550', borderWidth: 6, }, ], }; export const Data5 = { datasets: [ { data: [ 0.3, 0.4, 0.5, 0.35, 0.28, 0.3, 0.43, 0.51, 0.39, 0.45, 0.41, 0.45, ], borderWidth: 0, backgroundColor: '#6269d6', }, ], labels: [ 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', ], }; export const Options = { elements: { point: { radius: 0 }, }, //point legend: { display: false, }, maintainAspectRatio: false, label: false, scales: { xAxes: [ { gridLines: { display: false, drawBorder: false, }, ticks: { display: false, }, }, ], yAxes: [ { gridLines: { display: false, }, ticks: { display: false, }, }, ], }, }; export const Options2 = { elements: { point: { radius: 4 }, }, //point legend: { display: false, }, maintainAspectRatio: false, label: false, scales: { xAxes: [ { gridLines: { display: false, drawBorder: false, }, ticks: { display: false, }, stacked: false, }, ], yAxes: [ { gridLines: { display: false, }, ticks: { display: false, }, }, ], }, }; export const Options3 = { legend: { display: false }, animation: { animateScale: true, }, maintainAspectRatio: false, scales: { xAxes: [ { barPercentage: 1, categoryPercentage: 1, gridLines: { display: false, drawBorder: false, }, ticks: { display: false, }, }, ], yAxes: [ { barPercentage: 1, categoryPercentage: 1, gridLines: { display: false, drawBorder: false, }, ticks: { display: false, }, }, ], }, tooltips: {}, }; export const Columns = [ { title: 'Name', dataIndex: 'name', key: 'name', render: (text) => <a>{text}</a>, }, { title: 'Age', dataIndex: 'age', key: 'age', }, { title: 'Address', dataIndex: 'address', key: 'address', }, { title: 'Tags', key: 'tags', dataIndex: 'tags', responsive: ['lg'], render: (tags) => ( <> {tags.map((tag) => { let color = tag.length > 5 ? 'geekblue' : 'green'; if (tag === 'loser') { color = 'volcano'; } return ( <Tag color={color} key={tag}> {tag.toUpperCase()} </Tag> ); })} </> ), }, { title: 'Action', key: 'action', responsive: ['lg'], render: (text, record) => ( <Space size="middle"> <a>Invite {record.name}</a> <a>Delete</a> </Space> ), }, ]; export const Data = [ { key: '1', name: '<NAME>', age: 32, address: 'New York No. 1 Lake Park', tags: ['nice', 'developer'], }, { key: '2', name: '<NAME>', age: 42, address: 'London No. 1 Lake Park', tags: ['loser'], }, { key: '3', name: '<NAME>', age: 32, address: 'Sidney No. 1 Lake Park', tags: ['cool', 'teacher'], }, ]; <file_sep>/src/components/search-header/search-header.component.js import React from 'react'; import { Avatar } from 'antd'; import { SearchOutlined } from '@ant-design/icons'; import './search-header.styles.css'; const SearchHeader = ({ showInputSearch, handleShowInputSearch }) => { return ( <div className='header-search-input-container'> <input type='text' placeholder='Type to search' className={`header-search-input ${showInputSearch ? 'header-search-input-open' : ''}`} /> <Avatar onClick={handleShowInputSearch} className={`header-search-button ${showInputSearch ? 'header-search-rotate' : ''}`} size={42}><SearchOutlined /></Avatar> </div> ) }; export default SearchHeader;<file_sep>/src/components/chart-box-var-3/chart-box-var-3.styles.js import styled, { css } from 'styled-components'; import { colorsPalette } from '../custom-color/custom-color'; const borderCss = css` border-bottom: 1px solid #d6d6d6d6; &:nth-last-child(${({col}) => col? '-n+'+(col): 'n'}) { border-bottom-width: 0; } `; const borderRadiusCss = css` &:first-child { border-top-left-radius: 5px; } &:nth-child(${({col}) => col? col : 0}) { border-top-right-radius: 5px; } &:nth-child(${({col, row}) => col? ((col*row) - (col-1)) : 1}) { border-bottom-left-radius: 5px; } &:last-child { border-bottom-right-radius: 5px; } `; const borderStyle = props => { if (props.showBorder) { return borderCss; } } const borderRadiusStyle = props => { if (props.borderRadius) { return borderRadiusCss; } } export const ChartBoxVar3Container = styled.div` background: ${({bgColor}) => colorsPalette[bgColor]? colorsPalette[bgColor] : bgColor ? bgColor : 'white' }; box-shadow: ${({boxShadow}) => boxShadow? '0 0.46875rem 2.1875rem rgba(8,10,37,.03), 0 0.9375rem 1.40625rem rgba(8,10,37,.03), 0 0.25rem 0.53125rem rgba(8,10,37,.05), 0 0.125rem 0.1875rem rgba(8,10,37,.03)' : 'none'}; border-radius: ${({borderRadius}) => borderRadius? '5px' : '0px'}; padding: 10px; height: fit-content; ${borderRadiusStyle}; ${borderStyle}; display: flex; flex-direction: column; align-items: center; `; export const ChartBoxVar3Grid = styled.div` display: grid; grid-template-columns: 1fr minmax(100px, .5fr); width: ${({width}) => width? width : '100%'}; align-items: end; `;<file_sep>/src/pages/signup/signup.component.js import React from 'react'; import { Typography, Form, Input, Checkbox, Button } from 'antd'; import './signup.styles.css'; import '../signin/signin.styles.css'; const { Title, Text, Link } = Typography; const SignupPage = () => { return ( <div className='signin-page-container'> <div className='signup-page-form'> <div className='signin-page-logo'/> <Title level={3} className='signin-page-welcome-back'>Welcome</Title> <div className='flex-start'> <Title level={5} className='signin-page-please-text'>It only takes</Title> <Title level={5} className='signin-page-green-text'> &nbsp;a few seconds&nbsp; </Title> <Title level={5} className='signin-page-please-text'>to create your account</Title> </div> <Form name="basic" initialValues={{ remember: true }} > <div className='signin-page-form-container'> <div className='signin-page-from-part '> <label className='label-input'>Username</label> <Form.Item name="email" rules={[{ required: true, message: 'Please input your username!' }]} > <Input placeholder='Your email address'/> </Form.Item> </div> <div className='signin-page-from-part '> <label className='label-input'>Name</label> <Form.Item name="name" rules={[{ required: true, message: 'Please input your password!' }]} > <Input placeholder='Your name'/> </Form.Item> </div> <div className='signin-page-from-part '> <label className='label-input'>Password</label> <Form.Item name="password" rules={[{ required: true, message: 'Please input your username!' }]} > <Input.Password placeholder='<PASSWORD>'/> </Form.Item> </div> <div className='signin-page-from-part '> <label className='label-input'>Repeat Password</label> <Form.Item name="repeat-password" rules={[{ required: true, message: 'Please input your password!' }]} > <Input.Password placeholder='<PASSWORD> password here'/> </Form.Item> </div> <div className='signin-page-from-part2'> <Form.Item name="remember" valuePropName="checked"> <Checkbox>Accept our Term and Conditions</Checkbox> </Form.Item> </div> </div> <div className='flex-start'> <Text className='signup-have-account'>Already have an account? </Text> <Link className='signup-have-account' href="https://ant.design" target="_blank"> &nbsp;Sign in </Link> </div> <Form.Item> <div className='flex-end'> <Button className='bg-round-button' type="primary">Create Account</Button> </div> </Form.Item> </Form> </div> <div className='signup-page-image-slider'> <div className='signup-page-slide-image1'> <div className='signin-image-overlay'> <div className='signin-overlay-container'> <p className='signin-overlay-title-text'>Scalabel, Modular and Consistent</p> <p className='signin-overlay-description-text' > Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. </p> </div> </div> </div> </div> </div> ) }; export default SignupPage; <file_sep>/src/components/custom-button/custom-button.component.js import React from 'react'; import PropTypes from 'prop-types'; import { CustomButtonStyled, CustomButtonMenuItem } from './custom-button.styles'; import './custom-button.styles.css'; const CustomButton = ({ variant, color, className, children, pill, square, shadow, icon, block, iconPosition, iconType, size, wide, role, active, ...props }) => { if (icon) { return ( <CustomButtonStyled size={size} wide={wide} shadow={shadow} pill={pill} square={square} variant={variant} color={color} className={className} block={block} icon={icon} iconType={iconType} {...props}> <div className={`${iconType === 'vertical' ? 'custom-button-icon-container-vertical' : 'custom-button-icon-container'}`}> { !iconPosition || iconPosition === 'left'? <span className={` ${children ? 'icon-span-container': 'icon-span-only-container'} ${iconType === 'vertical' ? 'icon-block' : ''} ` }> {icon}</span> :null } {children} { iconPosition && iconPosition === 'right'? <span className={` ${children ? 'icon-span-container': 'icon-span-only-container'} ${iconType === 'vertical' ? 'icon-block' : ''} ` }>{icon}</span> :null } </div> </CustomButtonStyled> ) } else { return ( <CustomButtonStyled size={size} wide={wide} shadow={shadow} pill={pill} square={square} variant={variant} color={color} className={className} block={block} {...props}> {children} </CustomButtonStyled> ) } }; CustomButton.propTypes = { variant : PropTypes.oneOf(['solid', 'outlined', 'outlined-2x', 'dashed', 'no-outlined']), color: PropTypes.oneOf(['primary', 'secondary', 'warning', 'success', 'danger', 'info', 'alt', 'dark', 'light', 'link']), pill: PropTypes.bool, square: PropTypes.bool, shadow: PropTypes.bool, block: PropTypes.bool, icon: PropTypes.element, iconType: PropTypes.oneOf(['horizontal', 'vertical']), iconPosition: PropTypes.oneOf(['left', 'right']), size: PropTypes.oneOf(['large', 'normal', 'small']), wide: PropTypes.oneOf(['large', 'normal', 'small']) }; CustomButton.defaultProps = { variant: 'no-outlined', color: 'primary', pill: false, square: false, shadow: false, block: false, size: 'normal', wide: 'normal' }; export default CustomButton;<file_sep>/src/components/custom-menu/custom-menu.styles.js import styled from 'styled-components'; export const CustomMenuStyled = styled.ul` display: flex; flex-wrap: wrap; padding-left: 0; margin-bottom: 0; list-style: none; width: 100%; `; <file_sep>/src/pages/dashboard-crm/dashboard-crm-var-2/dasboard-crm-var-2.component.js import React from 'react'; import { Line } from 'react-chartjs-2'; import { Typography, Progress, Table, Avatar } from 'antd'; import { DownOutlined, UpOutlined, RocketOutlined, ThunderboltOutlined, FileTextOutlined, DatabaseOutlined, MessageOutlined, CrownOutlined, AlertOutlined, TrophyOutlined } from '@ant-design/icons'; import { CustomCard, CustomCardBody, CustomCardHeader, CustomCardTitleText, CustomCardFooter } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import { colorsPalette } from 'Components/custom-color/custom-color'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import CustomButton from 'Components/custom-button/custom-button.component'; import { BandwidthReportData2, DataChart } from '../dashboard-crm.data'; import { DataTable2, Columns2, DataHighlights2 } from 'Data/table.data'; import { Options6, Options8 } from 'Data/settings-chart.data'; const { Title } = Typography; const DashboardCrmVariation2 = () => { return ( <div> <div className='grid-3-gap-30 mb-30'> <ChartBoxVar3 defaultValue="1896" defaultValueColor='white' mainTitleText='Total Orders' mainTitleColor='white' descriptionText='Last year expenses' descriptionTextColor='white' bgColor='linear-gradient(0deg,#a18cd1 0,#fbc2eb)' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='white' mainTitleText='Clients' mainTitleColor='white' descriptionText='Total Clients Profit' descriptionTextColor='#fbfbfbe6' bgColor='linear-gradient(-20deg,#2b5876,#4e4376)' /> <ChartBoxVar3 className='span-grid-column' defaultValue="$14M" defaultValueColor='white' mainTitleText='Products Sold' mainTitleColor='white' descriptionText='Total revenue streams' descriptionTextColor='white' bgColor='linear-gradient(180deg,#00b09b,#96c93d)' /> </div> <div className='dcm-grid-1-5-2 mb-30'> <CustomCard className='overflow-hidden'> <CustomCardHeader>Sales Report</CustomCardHeader> <CustomCardBody> <div className='card-container text-align-left mb-30'> <div className='flex-row align-items-center padding-horizontal-20'> <Title level={1} className='fw-400 no-margin-no-padding '><span className='color98'>$</span>123&nbsp;</Title> <Title level={3} className='fw-400 color98 no-margin-no-padding'>Sales Total</Title> </div> <Line data={DataChart.data1} width={100} height={30} options={Options8} /> </div> <p className='fs-14 color98 fw-400'>LAST MONTH HIGHTLIGHTS</p> <div className='height-200 overflow-auto'> { DataHighlights2.map((item) => ( <div className='da-highlights-item'> <div className='flex-row align-items-center'> <Avatar className='mr-20' size={40} src={item.img} /> <div> <p className='color6d no-margin-no-padding'>{item.name}</p> </div> </div> <div className='flex-row-fit-content align-items-center'> <Title level={3} className='success'>{item.value}</Title> { item.icon.type === 'up' ? <UpOutlined className={item.icon.color} style={style.downIcon} /> : <DownOutlined className={item.icon.color} style={style.downIcon} /> } </div> </div> )) } </div> </CustomCardBody> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardHeader>Bandwidth Reports</CustomCardHeader> <CustomCardBody> <div className='mb-30'> <Line data={DataChart.data5} width={100} height={40} options={Options6} /> </div> <div className='grid-2-gap-30 mb-30'> { BandwidthReportData2.map((item) => ( <div key={item.id}> <div className='flex-row align-items-center justify-content-space-between'> <Title level={3} className={`fw-bold no-mb mr-20 ${(item.valueDetail.color) ? item.valueDetail.color : 'color5d'}`}>{item.valueDetail.value}</Title> <p className='color98 fw-400 no-margin-no-padding'>{item.description}</p> </div> { item.progress? <Progress strokeColor={`${colorsPalette[item.progress.color] ? colorsPalette[item.progress.color] : item.progress.color}`} percent={item.progress.value} size="small" showInfo={false} /> : null } </div> )) } </div> </CustomCardBody> </CustomCard> </div> <div className='grid-3-gap-30 mb-30 overflow-hidden'> <CustomCard className='overflow-hidden'> <CustomCardBody> <Title level={3} className='fw-400 color5d no-margin-no-padding'>Received Messages</Title> <Title className='primary no-margin-no-padding' level={1}>348</Title> <Line data={DataChart.data6} width={100} height={50} options={Options6} /> </CustomCardBody> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardBody> <Title level={3} className='fw-400 color5d no-margin-no-padding '>Sent Messages</Title> <Title className='danger no-margin-no-padding' level={1}>348</Title> <Line data={DataChart.data7} width={100} height={50} options={Options6} /> </CustomCardBody> </CustomCard> <CustomCard contained='dark' className='overflow-hidden'> <CustomCardBody> <Title level={3} className='fw-400 warning no-margin-no-padding '>Total Inbox</Title> <Title className='warning no-margin-no-padding' level={1}>348</Title> <Line data={DataChart.data8} width={100} height={50} options={Options6} /> </CustomCardBody> </CustomCard> </div> <CustomCard className='mb-30'> <CustomCardHeader> <CustomCardTitleText>Easy Dynamic Tables</CustomCardTitleText> </CustomCardHeader> <CustomCardBody className='overflow-auto'> <Table columns={Columns2} dataSource={DataTable2} /> </CustomCardBody> </CustomCard> <div className='grid-3-gap-30'> <CustomCard className='overflow-hidden'> <CustomCardHeaderWithImage backgroundColorOverlay='#545cd866' imgUrl='https://images.unsplash.com/photo-1550537687-c91072c4792d?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=334&q=80' className='align-items-center flex-column'> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Lead UX Designer</p> </div> <CustomButton className='margin-top-8' color='warning' variant='solid'>Message</CustomButton> </CustomCardHeaderWithImage> <CustomCardBody> <Title className='color98 text-align-center' level={4}>Lorem ipsum dolor sit amet</Title> </CustomCardBody> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<CrownOutlined style={style.iconStyleBigger}/>}> View Profile </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<AlertOutlined style={style.iconStyleBigger}/>}> Leads Generated </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardHeaderWithImage backgroundColorOverlay='#545cd866' imgUrl='https://images.unsplash.com/photo-1553526777-5ffa3b3248d8?ixlib=rb-1.2.1&ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&auto=format&fit=crop&w=334&q=80' className='align-items-center flex-column'> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1560787313-5dff3307e257?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Frontend UI Designer</p> </div> <CustomButton className='margin-top-8' color='warning' variant='solid'>Message</CustomButton> </CustomCardHeaderWithImage> <CustomCardBody> <Title className='color98 text-align-center' level={4}>Aenean massa cum sociis natoque penatibus et magnis dis parturient montes</Title> </CustomCardBody> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='alt' variant='no-outlined' icon={<RocketOutlined />}> View Profile </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='alt' variant='no-outlined' icon={<ThunderboltOutlined />}> Leads Leads </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> <CustomCard className='overflow-hidden'> <CustomCardHeaderWithImage backgroundColorOverlay='#545cd866' imgUrl='https://images.unsplash.com/photo-1557672172-298e090bd0f1?ixid=MXwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHw%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=334&q=80' className='align-items-center flex-column'> <div className='flex-column align-items-center'> <Avatar size={45} src="https://images.unsplash.com/photo-1568967729548-e3dbad3d37e0?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <Title className='white no-margin-no-padding' level={4}><NAME></Title> <p className='white no-margin-no-padding'>Backend Engineer</p> </div> <CustomButton className='margin-top-8' color='warning' variant='solid'>Message</CustomButton> </CustomCardHeaderWithImage> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<FileTextOutlined style={style.iconStyleBigger}/>}> Automation </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<DatabaseOutlined style={style.iconStyleBigger}/>}> Reports </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<MessageOutlined style={style.iconStyleBigger}/>}> Activity </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<TrophyOutlined style={style.iconStyleBigger}/>}> Settings </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> </div> </div> ) }; const style = { downIcon: { fontSize: '11px', marginLeft: '10px' }, settingIcon : { fontSize: '79px', color: '#a86799' }, iconStyleBigger: { fontSize: '28px' } }; export default DashboardCrmVariation2;<file_sep>/src/components/custom-menu-item/custom-menu-item.component.js import React from 'react'; import { CustomMenuItemStyled } from './custom-menu-item.styles'; const CustomMenuItem = ({ active, activeColor, children, ...props }) => { return ( <CustomMenuItemStyled active={active} activeColor={activeColor} {...props}> {children} </CustomMenuItemStyled> ) }; export default CustomMenuItem;<file_sep>/src/pages/chart-boxes/chart-boxes-variation-2/chart-boxes-variation-2.component.js import React from 'react'; import CustomTabsWrapper from 'Components/custom-tabs-wrapper/custom-tabs-wrapper.component'; import CustomTabPanel from 'Components/custom-tab-panel/custom-tab-panel.component'; import Basic from './basic/basic.component'; import Colors from './colors/colors.component'; const ChartBoxesVariation2 = () => { return ( <CustomTabsWrapper> <CustomTabPanel data-key='basic' title='Basic'> <Basic/> </CustomTabPanel> <CustomTabPanel data-key='colors' title='Colors'> <Colors/> </CustomTabPanel> </CustomTabsWrapper> ) }; export default ChartBoxesVariation2;<file_sep>/src/components/custom-breadcrumb/custom-breadcrumb.component.js import React from 'react'; import { connect } from 'react-redux'; import { Typography } from 'antd'; import { createStructuredSelector } from 'reselect'; import { selectBreadCrumb } from 'Redux_Component/application/application.selectors'; import './custom-breadcrumb.styles.css'; const { Link, Text } = Typography; const CustomBreadcrumb = ({ breadCrumb }) => { const locationArr = breadCrumb? breadCrumb.url.split("/") : []; if (breadCrumb && breadCrumb.title) { return ( <div className='app-theme-container'> <div className='app-theme-icon-wrapper'> <div className='bg-icon-gradient-ripple'> {breadCrumb? breadCrumb.icon : null} {/* <PieChartTwoTone twoToneColor="#9adec2" /> */} </div> </div> <div className='app-theme-text-container'> <p className='app-theme-title-main'>{breadCrumb ? breadCrumb.title : null}</p> <Text type="secondary"> {breadCrumb? breadCrumb.description : null} </Text> </div> <div className='app-theme-breadcrumb-container'> <Link href="https://ant.design" target="_blank"> {breadCrumb? breadCrumb.icon : null} &nbsp; </Link> { locationArr.map((path, index) => { if (index !== locationArr.length - 1 ) { return ( <Link href="https://ant.design" target="_blank" style={{textTransform: 'capitalize'}}> {path} / &nbsp; </Link> ) } else { return ( <Text style={{textTransform: 'capitalize'}}> {path} </Text> ) } }) } </div> </div> ) } else { return ( <div/> ) } }; const mapStateToProps = createStructuredSelector ({ breadCrumb : selectBreadCrumb }); export default connect(mapStateToProps)(CustomBreadcrumb);<file_sep>/src/pages/applications-faq/account-information.component.js import React from 'react'; import { Form, Input } from 'antd'; import CustomButton from 'Components/custom-button/custom-button.component'; const AccountInformation = () => { return ( <Form layout='vertical'> <Form.Item label='Email' name='email' style={{ display: 'inline-block', width: 'calc(50% - 8px)' }} > <Input placeholder="Type your email here" /> </Form.Item> <Form.Item label='Password' name='password' style={{ display: 'inline-block', width: 'calc(50% - 8px)', marginLeft: '16px' }} > <Input type='password' placeholder="Type your password here" /> </Form.Item> <Form.Item label='Address' name='address'> <Input placeholder="1234 Main Street" /> </Form.Item> <Form.Item label='Address 2' name='address2'> <Input placeholder="Apartment, floor, or building" /> </Form.Item> <Form.Item label='City' name='city' style={{ display: 'inline-block', width: 'calc(50% - 8px)', marginRight: '8px' }} > <Input placeholder="City" /> </Form.Item> <Form.Item label='States' name='states' style={{ display: 'inline-block', width: 'calc(30% - 16px)', margin: '0 8px' }} > <Input placeholder="State" /> </Form.Item> <Form.Item label='Zip' name='zip' style={{ display: 'inline-block', width: 'calc(20% - 8px)', marginLeft: '8px' }} > <Input placeholder="Zip" /> </Form.Item> <Form.Item className='padding-top-20' colon={false}> <CustomButton color='primary' variant='solid'> Submit </CustomButton> </Form.Item> </Form> ) }; export default AccountInformation;<file_sep>/src/components/chart-box-var-2/chart-box-var-2.styles.js import styled from 'styled-components'; import { colorsPalette } from '../custom-color/custom-color'; export const ChartBoxVar2Container = styled.div` padding: 10px; box-sizing: border-box; box-shadow: ${({boxShadow}) => boxShadow? ' 0 0.46875rem 2.1875rem rgba(8,10,37,.03), 0 0.9375rem 1.40625rem rgba(8,10,37,.03), 0 0.25rem 0.53125rem rgba(8,10,37,.05), 0 0.125rem 0.1875rem rgba(8,10,37,.03)': 'none'}; border-radius: 5px; background: ${({bgColor}) => colorsPalette[bgColor]? colorsPalette[bgColor] : bgColor? bgColor : 'white' }; height: fit-content; `; export const ChartBoxGrid = styled.div` display: grid; grid-template-columns: minmax(100px, 1fr) 1fr; align-items: flex-start; justify-content: flex-start; `; export const MainTitleText = styled.p` color: ${({mainTitleColor}) => colorsPalette[mainTitleColor]? colorsPalette[mainTitleColor] : mainTitleColor? mainTitleColor : '#4a4a4a'}; margin-bottom: 3px; font-size: 14px; `; export const DescriptionText = styled.p` color: ${({descriptionTextColor}) => colorsPalette[descriptionTextColor]? colorsPalette[descriptionTextColor] :descriptionTextColor? descriptionTextColor : '#828282'}; font-size: 14px; margin-bottom: 2px; `; export const DescriptionProgressBarText = styled.div` color: ${({descriptionProgressBarColor}) => colorsPalette[descriptionProgressBarColor]? colorsPalette[descriptionProgressBarColor] :descriptionProgressBarColor? descriptionProgressBarColor : '#828282'}; font-size: 14px; text-align: left; margin-bottom: 2px; `; export const DescriptionProgressText = styled.p` color: ${({descriptionProgressColor}) => colorsPalette[descriptionProgressColor]? colorsPalette[descriptionProgressColor] :descriptionProgressColor? descriptionProgressColor : '#828282'}; margin-bottom: 3px; font-size: 14px; font-weight: 500; margin-bottom: 3px; `; export const RightContainer = styled.div` display: flex; flex-direction: column; align-items: flex-end; `; <file_sep>/src/pages/element-buttons/vertical-icon-container/vertical-icon-container.component.js import React from 'react'; import { CrownOutlined, AlertOutlined, CameraOutlined, BugOutlined, BulbOutlined, DatabaseOutlined, MessageOutlined, RocketOutlined, ThunderboltOutlined, TrophyOutlined } from '@ant-design/icons'; import CustomButton from 'Components/custom-button/custom-button.component'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; const VerticalIconContainer = () => { return ( <div className='grid-2'> <div> <CustomCard className='mb-30'> <CustomCardTitleText> SOLID ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton iconType='vertical' className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}> Info </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> COLOR TRANSITION </CustomCardTitleText> <CustomCardBody> <CustomButton iconType='vertical' className='mrb-10' color='primary' variant='outlined' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='secondary' variant='outlined' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='success' variant='outlined' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='info' variant='outlined' icon={<BugOutlined />}> Info </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='warning' variant='outlined' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='danger' variant='outlined' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='alt' variant='outlined' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='light' variant='outlined' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='dark' variant='outlined' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton iconType='vertical' className='mrb-10' color='link' variant='outlined' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> OUTLINE 2X SHADOW ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton iconType='vertical' shadow className='mrb-10' color='primary' variant='outlined-2x' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='secondary' variant='outlined-2x' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='success' variant='outlined-2x' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='info' variant='outlined-2x' icon={<BugOutlined />}> Info </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='warning' variant='outlined-2x' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='danger' variant='outlined-2x' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='alt' variant='outlined-2x' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='light' variant='outlined-2x' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='dark' variant='outlined-2x' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='link' variant='outlined-2x' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> OUTLINE 2X SHADOW ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton block iconType='vertical' className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton block iconType='vertical' className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton block iconType='vertical' className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> </CustomCardBody> </CustomCard> </div> <div> <CustomCard className='mb-30'> <CustomCardTitleText> SOLID SQUARE ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton square iconType='vertical' className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}> Info </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> TRANSITION BUTTONS WIHTOUT BORDER </CustomCardTitleText> <CustomCardBody> <CustomButton square iconType='vertical' className='mrb-10' color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='secondary' variant='no-outlined' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='success' variant='no-outlined' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='info' variant='no-outlined' icon={<BugOutlined />}> Info </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='warning' variant='no-outlined' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='danger' variant='no-outlined' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='alt' variant='no-outlined' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='light' variant='no-outlined' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='dark' variant='no-outlined' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton square iconType='vertical' className='mrb-10' color='link' variant='no-outlined' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> OUTLINE 2X SHADOW ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton iconType='vertical' shadow className='mrb-10' color='primary' variant='dashed' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='secondary' variant='dashed' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='success' variant='dashed' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='info' variant='dashed' icon={<BugOutlined />}> Info </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='warning' variant='dashed' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='danger' variant='dashed' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='alt' variant='dashed' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='light' variant='dashed' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='dark' variant='dashed' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton iconType='vertical' shadow className='mrb-10' color='link' variant='dashed' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> GRID MENU HOVER COLOR </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-3-col align-items-center justify-content-center'> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<TrophyOutlined />}> Danger </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='warning' variant='no-outlined' icon={<RocketOutlined />}> Warning </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='info' variant='no-outlined' icon={<BulbOutlined />}> Info </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='secondary' variant='no-outlined' icon={<BugOutlined />}> Secondary </CustomButton> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> GRID MENU BIGGER TWO COLUMNS </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<TrophyOutlined />}> Danger </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='warning' variant='no-outlined' icon={<RocketOutlined />}> Warning </CustomButton> </div> </div> </CustomCardBody> </CustomCard> </div> </div> ) }; export default VerticalIconContainer;<file_sep>/src/components/custom-badges/custom-badges.component.js import React from 'react'; import PropTypes from 'prop-types'; import { BadgeStyle } from './custom-badges.styles'; import './custom-badges.styles.css'; const CustomBadges = ({ color, dot, number, size, children, position, className, link, href, target, ...props }) => { if (!children) { return ( <BadgeStyle className={className} size={size} dot={dot} number={number} color={color} {...props}> { number? number: null } </BadgeStyle> ) } else { let classNameForBadge = null; if (children.type.displayName === 'Avatar') { if (children.props.shape === 'circle') { classNameForBadge = position === 'bottom'? 'badges-with-avatar-circle-style-bottom' :'badges-with-avatar-circle-style'; } else { classNameForBadge = position === 'bottom'? 'badges-with-avatar-square-style-bottom' : 'badges-with-avatar-square-style'; } } else { if (children.props.iconType === 'vertical') { classNameForBadge = 'badges-with-child-style-grid-button'; } else { classNameForBadge = 'badges-with-child-style'; } } if (href) { return ( <a href={href} target={target} className={`custom-badge-wrapper ${className}`}> {children} <BadgeStyle className={`${classNameForBadge}`} size={size} dot={dot} number={number} color={color} {...props}> { number? number: null } </BadgeStyle> </a> ) } else { return ( <div className={`${children.props.block ? 'custom-badge-grid-button-wrapper' : 'custom-badge-wrapper'} ${className}`}> {children} <BadgeStyle className={`${classNameForBadge}`} size={size} dot={dot} number={number} color={color} {...props}> { number? number: null } </BadgeStyle> </div> ) } } }; CustomBadges.propTypes = { color: PropTypes.oneOf(['primary', 'secondary', 'warning', 'success', 'danger', 'info', 'alt', 'dark', 'light', 'link']), dot: PropTypes.bool, number: PropTypes.oneOfType([PropTypes.string,PropTypes.number,]), size: PropTypes.oneOfType([PropTypes.string,PropTypes.number,]), position: PropTypes.oneOf(['top', 'bottom']), link: PropTypes.bool, href: PropTypes.string, target: PropTypes.string }; export default CustomBadges;<file_sep>/src/pages/forgot-password/forgot-password.component.js import React from 'react'; import { Carousel, Typography, Form, Input, Button } from 'antd'; import '../signin/signin.styles.css'; import '../signin-boxed/signin-boxed.styles.css'; import '../signup/signup.styles.css'; import '../signup-boxed/signup-boxed.styles.css'; const { Title } = Typography; const ForgotPassword = () => { return ( <div className='signin-page-container'> <div className='signin-page-image-slider'> <Carousel autoplay> <div className='signin-page-slide-image1'> <div className='signin-image-overlay'> <div className='signin-overlay-container'> <p className='signin-overlay-title-text'>Complex but Lightweight</p> <p className='signin-overlay-description-text' > Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes </p> </div> </div> </div> <div className='signin-page-slide-image2'> <div className='signin-image-overlay'> <div className='signin-overlay-container'> <p className='signin-overlay-title-text'>Scalabel, Modular and Consistent</p> <p className='signin-overlay-description-text' > Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. </p> </div> </div> </div> <div className='signin-page-slide-image3'> <div className='signin-image-overlay'> <div className='signin-overlay-container'> <p className='signin-overlay-title-text'>Complex but Lightweight</p> <p className='signin-overlay-description-text' > Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. </p> </div> </div> </div> </Carousel> </div> <div className='signin-page-form'> <div className='signin-page-logo'/> <Title level={3} className='signin-page-welcome-back'>Forgot your Password?</Title> <Title level={5} className='signin-page-please-text'>Use the form below to recover it.</Title> <Form name="basic" initialValues={{ remember: true }} > <div className='signin-page-form-container'> <div className='signin-page-from-part2'> <label className='label-input'>Email</label> <Form.Item name="email" rules={[{ required: true, message: 'Please input your username!' }]} > <Input placeholder='Your username'/> </Form.Item> </div> </div> <Title level={5} className='signin-page-sign-up-text'>Sign in existing account</Title> <Form.Item> <div className='flex-end'> <Button type="primary">Recover Password</Button> </div> </Form.Item> </Form> </div> </div> ) }; export default ForgotPassword;<file_sep>/src/pages/element-cards/color-states-card-container/color-states-card-container.component.js import React from 'react'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; const ColorStatesContainer = () => { const CardColorStates = ({ }) => ( <div> <CustomCard outlined='primary' className='mb-30'> <CustomCardTitleText>PRIMARY CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='secondary' className='mb-30'> <CustomCardTitleText>SECONDARY CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='success' className='mb-30'> <CustomCardTitleText>SUCCESS CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='info' className='mb-30'> <CustomCardTitleText>INFO CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='warning' className='mb-30'> <CustomCardTitleText>WARNING CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='alt' className='mb-30'> <CustomCardTitleText>ALTERNATE CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='light' className='mb-30'> <CustomCardTitleText>LIGHT CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='dark' className='mb-30'> <CustomCardTitleText>DARK CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard outlined='danger' className='mb-30'> <CustomCardTitleText>DANGER CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> </div> ); return ( <div className='grid-3-gap-30'> <CardColorStates/> <CardColorStates/> <div> <CustomCard contained='primary' className='mb-30'> <CustomCardTitleText>PRIMARY CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='secondary' className='mb-30'> <CustomCardTitleText>SECONDARY CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='success' className='mb-30'> <CustomCardTitleText>SUCCESS CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='info' className='mb-30'> <CustomCardTitleText>INFO CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='warning' className='mb-30'> <CustomCardTitleText>WARNING CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='alt' className='mb-30'> <CustomCardTitleText>ALTERNATE CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='light' className='mb-30'> <CustomCardTitleText>LIGHT CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='dark' className='mb-30'> <CustomCardTitleText>DARK CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> <CustomCard contained='danger' className='mb-30'> <CustomCardTitleText>DANGER CARD SHADOW</CustomCardTitleText> <CustomCardBody> <p> With supporting text below as a natural lead-in to additional content. </p> </CustomCardBody> </CustomCard> </div> </div> ) }; export default ColorStatesContainer;<file_sep>/src/pages/element-buttons/horizontal-icon-container/horizontal-icon-container.component.js import React from 'react'; import { CrownOutlined, AlertOutlined, CameraOutlined, BugOutlined, BulbOutlined, DatabaseOutlined, MessageOutlined, RocketOutlined, ThunderboltOutlined, TrophyOutlined } from '@ant-design/icons'; import CustomButton from 'Components/custom-button/custom-button.component'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; const HorizontalIconContainer = () => { return ( <div className='grid-2'> <div> <CustomCard className='mb-30'> <CustomCardTitleText> SOLID ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}> Info </CustomButton> <CustomButton className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> OUTLINE PILL ICONS BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton pill className='mrb-10' color='primary' variant='outlined' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton pill className='mrb-10' color='secondary' variant='outlined' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton pill className='mrb-10' color='success' variant='outlined' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton pill className='mrb-10' color='info' variant='outlined' icon={<BugOutlined />}> Info </CustomButton> <CustomButton pill className='mrb-10' color='warning' variant='outlined' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton pill className='mrb-10' color='danger' variant='outlined' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton pill className='mrb-10' color='alt' variant='outlined' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton pill className='mrb-10' color='light' variant='outlined' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton pill className='mrb-10' color='dark' variant='outlined' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton pill className='mrb-10' color='link' variant='outlined' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> DASH SHADOW ICONS BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton shadow className='mrb-10' color='primary' variant='dashed' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton shadow className='mrb-10' color='secondary' variant='dashed' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton shadow className='mrb-10' color='success' variant='dashed' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton shadow className='mrb-10' color='info' variant='dashed' icon={<BugOutlined />}> Info </CustomButton> <CustomButton shadow className='mrb-10' color='warning' variant='dashed' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton shadow className='mrb-10' color='danger' variant='dashed' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton shadow className='mrb-10' color='alt' variant='dashed' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton shadow className='mrb-10' color='light' variant='dashed' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton shadow className='mrb-10' color='dark' variant='dashed' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton shadow className='mrb-10' color='link' variant='dashed' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> BLOCK ICONS BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton block className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton block shadow className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton block shadow className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> SIZE ICONS BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton size='large' className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Large Size </CustomButton> <CustomButton size='normal' shadow className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Normal Size </CustomButton> <CustomButton size='small' shadow className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Small Size </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> SIZE ICONS BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton iconPosition='right' pill size='large' className='mrb-10' color='warning' variant='solid' icon={<CrownOutlined />}> Large Size </CustomButton> <CustomButton iconPosition='right' pill shadow size='normal' shadow className='mrb-10' color='success' variant='outlined' icon={<AlertOutlined />}> Normal Size </CustomButton> <CustomButton iconPosition='right' pill size='small' className='mrb-10' color='danger' variant='dashed' icon={<CameraOutlined />}> Small Size </CustomButton> </CustomCardBody> </CustomCard> </div> <div> <CustomCard className='mb-30'> <CustomCardTitleText> ICONS SQUARE BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton square className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton square className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton square className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton square className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}> Info </CustomButton> <CustomButton square className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton square className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton square className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton square className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton square className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton square className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> OUTLINED 2X SHADOW ICONS BUTTONS </CustomCardTitleText> <CustomCardBody> <CustomButton shadow className='mrb-10' color='primary' variant='outlined-2x' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton shadow className='mrb-10' color='secondary' variant='outlined-2x' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton shadow className='mrb-10' color='success' variant='outlined-2x' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton shadow className='mrb-10' color='info' variant='outlined-2x' icon={<BugOutlined />}> Info </CustomButton> <CustomButton shadow className='mrb-10' color='warning' variant='outlined-2x' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton shadow className='mrb-10' color='danger' variant='outlined-2x' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton shadow className='mrb-10' color='alt' variant='outlined-2x' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton shadow className='mrb-10' color='light' variant='outlined-2x' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton shadow className='mrb-10' color='dark' variant='outlined-2x' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton shadow className='mrb-10' color='link' variant='outlined-2x' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> SOLID ICONS </CustomCardTitleText> <CustomCardBody> <CustomButton pill className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}> Primary </CustomButton> <CustomButton pill className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}> Secondary </CustomButton> <CustomButton pill className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}> Success </CustomButton> <CustomButton pill className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}> Info </CustomButton> <CustomButton pill className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}> Warning </CustomButton> <CustomButton pill className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}> Danger </CustomButton> <CustomButton pill className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}> Alt </CustomButton> <CustomButton pill className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}> Light </CustomButton> <CustomButton pill className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}> Dark </CustomButton> <CustomButton pill className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}> Link </CustomButton> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> ICONS ONLY </CustomCardTitleText> <CustomCardBody> <CustomButton className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}/> <CustomButton className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}/> <CustomButton className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}/> <CustomButton className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}/> <CustomButton className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}/> <CustomButton className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}/> <CustomButton className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}/> <CustomButton className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}/> <CustomButton className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}/> <CustomButton className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}/> </CustomCardBody> <div className='line'/> <CustomCardBody> <CustomButton pill className='mrb-10' color='primary' variant='outlined' icon={<CrownOutlined />}/> <CustomButton pill className='mrb-10' color='secondary' variant='outlined' icon={<AlertOutlined />}/> <CustomButton pill className='mrb-10' color='success' variant='outlined' icon={<CameraOutlined />}/> <CustomButton pill className='mrb-10' color='info' variant='outlined' icon={<BugOutlined />}/> <CustomButton pill className='mrb-10' color='warning' variant='outlined' icon={<BulbOutlined />}/> <CustomButton pill className='mrb-10' color='danger' variant='outlined' icon={<DatabaseOutlined />}/> <CustomButton pill className='mrb-10' color='alt' variant='outlined' icon={<MessageOutlined />}/> <CustomButton pill className='mrb-10' color='light' variant='outlined' icon={<RocketOutlined />}/> <CustomButton pill className='mrb-10' color='dark' variant='outlined' icon={<ThunderboltOutlined />}/> <CustomButton pill className='mrb-10' color='link' variant='outlined' icon={<TrophyOutlined />}/> </CustomCardBody> <div className='line'/> <CustomCardBody> <CustomButton shadow className='mrb-10' color='primary' variant='dashed' icon={<CrownOutlined />}/> <CustomButton shadow className='mrb-10' color='secondary' variant='dashed' icon={<AlertOutlined />}/> <CustomButton shadow className='mrb-10' color='success' variant='dashed' icon={<CameraOutlined />}/> <CustomButton shadow className='mrb-10' color='info' variant='dashed' icon={<BugOutlined />}/> <CustomButton shadow className='mrb-10' color='warning' variant='dashed' icon={<BulbOutlined />}/> <CustomButton shadow className='mrb-10' color='danger' variant='dashed' icon={<DatabaseOutlined />}/> <CustomButton shadow className='mrb-10' color='alt' variant='dashed' icon={<MessageOutlined />}/> <CustomButton shadow className='mrb-10' color='light' variant='dashed' icon={<RocketOutlined />}/> <CustomButton shadow className='mrb-10' color='dark' variant='dashed' icon={<ThunderboltOutlined />}/> <CustomButton shadow className='mrb-10' color='link' variant='dashed' icon={<TrophyOutlined />}/> </CustomCardBody> <div className='line'/> <CustomCardBody> <CustomButton square className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}/> <CustomButton square className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}/> <CustomButton square className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}/> <CustomButton square className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}/> <CustomButton square className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}/> <CustomButton square className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}/> <CustomButton square className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}/> <CustomButton square className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}/> <CustomButton square className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}/> <CustomButton square className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}/> </CustomCardBody> <div className='line'/> <CustomCardBody> <CustomButton shadow className='mrb-10' color='primary' variant='outlined-2x' icon={<CrownOutlined />}/> <CustomButton shadow className='mrb-10' color='secondary' variant='outlined-2x' icon={<AlertOutlined />}/> <CustomButton shadow className='mrb-10' color='success' variant='outlined-2x' icon={<CameraOutlined />}/> <CustomButton shadow className='mrb-10' color='info' variant='outlined-2x' icon={<BugOutlined />}/> <CustomButton shadow className='mrb-10' color='warning' variant='outlined-2x' icon={<BulbOutlined />}/> <CustomButton shadow className='mrb-10' color='danger' variant='outlined-2x' icon={<DatabaseOutlined />}/> <CustomButton shadow className='mrb-10' color='alt' variant='outlined-2x' icon={<MessageOutlined />}/> <CustomButton shadow className='mrb-10' color='light' variant='outlined-2x' icon={<RocketOutlined />}/> <CustomButton shadow className='mrb-10' color='dark' variant='outlined-2x' icon={<ThunderboltOutlined />}/> <CustomButton shadow className='mrb-10' color='link' variant='outlined-2x' icon={<TrophyOutlined />}/> </CustomCardBody> <div className='line'/> <CustomCardBody> <CustomButton pill className='mrb-10' color='primary' variant='solid' icon={<CrownOutlined />}/> <CustomButton pill className='mrb-10' color='secondary' variant='solid' icon={<AlertOutlined />}/> <CustomButton pill className='mrb-10' color='success' variant='solid' icon={<CameraOutlined />}/> <CustomButton pill className='mrb-10' color='info' variant='solid' icon={<BugOutlined />}/> <CustomButton pill className='mrb-10' color='warning' variant='solid' icon={<BulbOutlined />}/> <CustomButton pill className='mrb-10' color='danger' variant='solid' icon={<DatabaseOutlined />}/> <CustomButton pill className='mrb-10' color='alt' variant='solid' icon={<MessageOutlined />}/> <CustomButton pill className='mrb-10' color='light' variant='solid' icon={<RocketOutlined />}/> <CustomButton pill className='mrb-10' color='dark' variant='solid' icon={<ThunderboltOutlined />}/> <CustomButton pill className='mrb-10' color='link' variant='solid' icon={<TrophyOutlined />}/> </CustomCardBody> </CustomCard> </div> </div> ) }; export default HorizontalIconContainer;<file_sep>/src/pages/element-timelines/icon-badges-container/icon-badges-container.component.js import React from 'react'; import { Typography } from 'antd'; import { IdcardOutlined, SettingOutlined, CloudOutlined } from '@ant-design/icons'; import CustomTimeline from 'Components/custom-timeline/custom-timeline.component'; import CustomTimelineItem from 'Components/custom-timeline-item/custom-timeline-item.component'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; const { Text } = Typography; const IconBadgesContainer = () => { return ( <CustomCard> <CustomCardTitleText> Basics </CustomCardTitleText> <CustomCardBody> <CustomTimeline size='small'> <CustomTimelineItem dot={<IdcardOutlined />} color='danger' > <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem dot={<SettingOutlined spin={true}/>} color='warning' > <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem dot={<CloudOutlined />} color='success' > <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem dot={<IdcardOutlined />} color='primary' > <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem dot={<IdcardOutlined />} color='danger' fill={true} > <Text className='uppercase fs-14 fw-bold'>All hands meeting</Text> <p className='no-margin-no-padding'>Lorem ipsum dolor sit amet, today at <Text type="warning">11.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem dot={<SettingOutlined spin={true}/>} color='warning' fill={true} > <p className='no-margin-no-padding'>Another meeting today, at <Text type="danger" className='fw-bold'>12.00 PM</Text></p> <p className='no-margin-no-padding'>Yet another one, at <Text type="success">15.00 PM</Text></p> </CustomTimelineItem> <CustomTimelineItem dot={<CloudOutlined />} color='success' fill={true} > <Text className='uppercase fs-14 fw-bold'>Build the production release</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> <CustomTimelineItem dot={<IdcardOutlined />} color='primary' fill={true} > <Text type="success" className='uppercase fs-14 fw-bold'>Something not important</Text> <p className='no-margin-no-padding'> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis </p> </CustomTimelineItem> </CustomTimeline> </CustomCardBody> </CustomCard> ) }; export default IconBadgesContainer;<file_sep>/README.md # Admin Dash Ant Design - Admin Dashboard Template [![Netlify Status](https://api.netlify.com/api/v1/badges/8a2a6bd5-7900-42b7-b863-2b6580865473/deploy-status)](https://app.netlify.com/sites/admndash/deploys) **Ant Dash** is a responsive Ant Design admin template. Ite provides you with a collection of ready to use custom page, charts, different dashboard variations, a collection of applications and some elements. Preview of this awesome admin template available here : https://admndash.netlify.app/ ### Demo Site: [[Here]](https://admndash.netlify.app/) ### Built With - [Ant.design](https://ant.design/) - [Chart.js](http://www.chartjs.org/) - [Ant.design](https://ant.design/) - [Chart.js](http://www.chartjs.org/) - [Styled-Components](https://www.npmjs.com/package/styled-components) - [React-chartjs-2](https://github.com/reactchartjs/react-chartjs-2) - [React-loadable](https://www.npmjs.com/package/react-loadable) <file_sep>/webpack.config.js const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const AsyncChunkNames = require('webpack-async-chunk-names-plugin'); module.exports = { mode: ( process.env.NODE_ENV ? process.env.NODE_ENV : 'development' ), entry: ['babel-polyfill', './src/index.js'], output: { path: path.join(__dirname, 'dist'), filename: '[name].js', chunkFilename: '[name].js', publicPath: '/' }, resolve: { alias: { Assets: path.resolve(__dirname, 'src/assets/'), Components: path.resolve(__dirname, 'src/components/'), Data: path.resolve(__dirname, 'src/data/'), Redux_Component: path.resolve(__dirname, 'src/redux/'), Loader : path.resolve(__dirname, 'src/loader/') } }, devServer: { historyApiFallback: true, }, module: { rules: [ { test: /\.(js|jsx)$/, exclude: /node_modules/, use: { loader: 'babel-loader' } }, { test: /\.(css)$/, use: ['style-loader', 'css-loader','less-loader'] }, { test: /\.html$/, use: { loader: 'html-loader' } }, { test: /\.(png|jpg|gif|svg|eot|ttf|woff|woff2)$/, loader: 'url-loader', options: { limit: 10000 } }, { test: /\.less$/, use: [{ loader: 'style-loader', }, { loader: 'css-loader', }, { loader: 'less-loader', options: { lessOptions: { modifyVars: { 'primary-color': '#545cd8', 'link-color': '#545cd8', 'success-color': '#31b16f', 'error-color': '#d92550', 'warning-color': '#f7b924', 'info-color': '#30b1ff', 'border-radius-base': '2px', }, javascriptEnabled: true, }, }, }], } ], }, plugins: [ new HtmlWebpackPlugin({ template: 'public/index.html', favicon: 'public/favicon.ico' }), new AsyncChunkNames() ], optimization: { runtimeChunk: 'single', splitChunks: { chunks: 'all', maxInitialRequests: Infinity, minSize: 0, cacheGroups: { vendor: { test: /[\\/]node_modules[\\/]/, } }, }, }, }<file_sep>/src/pages/element-navigation-menus/grid-menu-container/grid-menu-container.component.js import React from 'react'; import { CrownOutlined, AlertOutlined, BugOutlined, BulbOutlined, RocketOutlined,TrophyOutlined } from '@ant-design/icons'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import CustomButton from 'Components/custom-button/custom-button.component'; const GridMenuContainer = () => { return ( <div className='grid-2-gap-30'> <div> <CustomCard className='mb-30'> <CustomCardTitleText> GRID MENU HOVER COLOR </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-3-col align-items-center justify-content-center'> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<TrophyOutlined />}> Danger </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='warning' variant='no-outlined' icon={<RocketOutlined />}> Warning </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='info' variant='no-outlined' icon={<BulbOutlined />}> Info </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='secondary' variant='no-outlined' icon={<BugOutlined />}> Secondary </CustomButton> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> GIRD MENU BIGGER </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-3-col align-items-center justify-content-center'> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<CrownOutlined style={style.iconStyleBigger}/>}> Primary </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<AlertOutlined style={style.iconStyleBigger}/>}> Success </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<TrophyOutlined style={style.iconStyleBigger}/>}> Danger </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<RocketOutlined style={style.iconStyleBigger}/>}> Warning </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<BulbOutlined style={style.iconStyleBigger}/>}> Info </CustomButton> </div> <div className='grid-row-for-3-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<BugOutlined style={style.iconStyleBigger}/>}> Secondary </CustomButton> </div> </div> </CustomCardBody> </CustomCard> </div> <div> <CustomCard className='mb-30'> <CustomCardTitleText> GRID MENU TWO COLUMNS </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='primary' variant='no-outlined' icon={<CrownOutlined />}> Primary </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<AlertOutlined />}> Success </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<TrophyOutlined />}> Danger </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='warning' variant='no-outlined' icon={<RocketOutlined />}> Warning </CustomButton> </div> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> GIRD MENU BIGGER TWO COLUMNSS </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<CrownOutlined style={style.iconStyleBigger}/>}> Primary </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<AlertOutlined style={style.iconStyleBigger}/>}> Success </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<TrophyOutlined style={style.iconStyleBigger}/>}> Danger </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='link' variant='no-outlined' icon={<RocketOutlined style={style.iconStyleBigger}/>}> Warning </CustomButton> </div> </div> </CustomCardBody> </CustomCard> </div> </div> ) }; const style = { iconStyleBigger: { fontSize: '32px' } } export default GridMenuContainer;<file_sep>/src/pages/applications-chat/application-chat.data.js export const ChatList = [ { date: "1604877011000", picUrl: 'https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', ownerAccountChat: false, chatList: [ { date: "16 minutes ago", list: ["Lorem ipsum dolor sit amet", "consectetuer adipiscing elit. Aenean commodo ligula eget dolor", "Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes", "Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem." ] } ] }, { date: "1604877131000", picUrl: "https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80", ownerAccountChat: true, chatList: [ { date: "15 minutes ago", list: ["Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo"] }, { date: "14 minutes ago", list: ["Iyaa ini aku coba dulu"] } ] }, { date: "1604877371000", picUrl: 'https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', chatList: [ { date: "12 minutes ago", list: ["Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo"] }, { date: "10 minutes ago", list: ["Iyaa ini aku coba dulu"] }, { date: "9 minutes ago", list: ["Nulla consequat massa quis enim. Donec pede justo, fringilla vel, ", "aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a", "venenatis vitae, justo"] }, ] } ]; export const ChatList2 = [ { date: "1604877011000", picUrl: 'https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', ownerAccountChat: false, chatList: [ { date: "16 minutes ago", list: ["Lorem ipsum dolor sit amet", "consectetuer adipiscing elit.", ] } ] }, { date: "1604877131000", picUrl: "https://images.unsplash.com/photo-1551069613-1904dbdcda11?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=356&q=80", ownerAccountChat: true, chatList: [ { date: "15 minutes ago", list: ["Nulla consequat massa quis enim."] }, { date: "14 minutes ago", list: ["Iyaa ini aku coba dulu"] } ] }, { date: "1604877371000", picUrl: 'https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80', chatList: [ { date: "12 minutes ago", list: ["Nulla consequat venenatis vitae, justo"] }, { date: "10 minutes ago", list: ["Iyaa ini aku coba dulu"] }, { date: "9 minutes ago", list: ["Nulla consequat massa quis enim. Donec pede justo, fringilla vel, "] }, ] } ]; <file_sep>/src/components/notif-header/notif-header.component.js import React from 'react'; import { Timeline } from 'antd'; import { ClockCircleOutlined } from '@ant-design/icons'; import './notif-header.styles.css'; import '../../App.css'; const NotifHeader = ({ show }) => { return ( <div className={`floating-menu card-container header-notif-menu ${show? 'floating-menu-show' : 'floating-menu-close'}`}> <div className='card-header-container header-notif-menu-header'> <div className='card-header-overlay header-notif-menu-overlay'> <p className='card-header-title'>Notifications</p> <p className='card-header-desc'> You have <strong>21</strong> messages unread </p> </div> </div> <div className='header-notif-menu-body'> <Timeline> <Timeline.Item>All hands meeting</Timeline.Item> <Timeline.Item>Another meeting today, at 12.01 PM</Timeline.Item> <Timeline.Item dot={<ClockCircleOutlined className="timeline-clock-icon" />} color="red"> Build the productions release </Timeline.Item> <Timeline.Item>Network problems being solved 2015-09-01</Timeline.Item> </Timeline> </div> </div> ) }; export default NotifHeader;<file_sep>/src/pages/chart-boxes/chart-boxes-variation-3/chart-boxes-variation-3.component.js import React from 'react'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; const ChartBoxesVariation3 = () => { return ( <div> <div className='grid-3-gap-30 mb-30'> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' descriptionText='Total Clients Profit' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='warning' mainTitleText='Products Sold' descriptionText='Total revenue streams' /> <ChartBoxVar3 defaultValue="46%" defaultValueColor='danger' mainTitleText='Followers' descriptionText='Peple interested' /> </div> <div className='line mb-30'/> <div className='grid-3-gap-30 mb-30'> <ChartBoxVar3 defaultValue="1896" defaultValueColor='gray' mainTitleText='Total Orders' mainTitleColor='white' descriptionText='Last year expenses' descriptionTextColor='white' bgColor='linear-gradient(120deg,#e0c3fc,#8ec5fc)' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='#fbfbfbe6' mainTitleText='Clients' mainTitleColor='white' descriptionText='Total Clients Profit' descriptionTextColor='#fbfbfbe6' bgColor='linear-gradient(-20deg,#2b5876,#4e4376)' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='danger' mainTitleText='Products Sold' descriptionText='Total revenue streams' descriptionTextColor='gray' bgColor='linear-gradient(120deg,#f6d365,#fda085)' /> <ChartBoxVar3 defaultValue="46%" defaultValueColor='primary' mainTitleText='Followers' descriptionText='Peple interested' bgColor='linear-gradient(120deg,#84fab0,#8fd3f4)' /> </div> <div className='line mb-30'/> <div className='grid-3-gap-30 mb-30'> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' progressBarValue={80} strokeWidth={6} progressBarColor='primary' descriptionProgressDetail='YoY Growth' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' descriptionText='Total Clients Profit' progressBarValue={50} strokeWidth={15} progressBarColor='warning' descriptionProgressDetail='Retention' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='warning' mainTitleText='Products Sold' descriptionText='Total revenue streams' progressBarValue={100} strokeWidth={6} progressBarColor='danger' descriptionProgressDetail='Sales' /> <ChartBoxVar3 defaultValue="46%" defaultValueColor='danger' mainTitleText='Followers' descriptionText='Peple interested' progressBarValue={40} strokeWidth={10} progressBarColor='success' descriptionProgressDetail='Twitter Progress' /> </div> <div className='line mb-30'/> <div className='mb-30'> <ChartBoxGridContainer col={3}> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' descriptionText='Total Clients Profit' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='warning' mainTitleText='Products Sold' descriptionText='Total revenue streams' /> </ChartBoxGridContainer> </div> <div className='line mb-30'/> <div className='mb-30'> <ChartBoxGridContainer col={3}> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' progressBarValue={80} strokeWidth={6} progressBarColor='primary' descriptionProgressDetail='YoY Growth' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' descriptionText='Total Clients Profit' progressBarValue={50} strokeWidth={15} progressBarColor='warning' descriptionProgressDetail='Retention' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='warning' mainTitleText='Products Sold' descriptionText='Total revenue streams' progressBarValue={100} strokeWidth={6} progressBarColor='danger' descriptionProgressDetail='Sales' /> <ChartBoxVar3 defaultValue="46%" defaultValueColor='danger' mainTitleText='Followers' descriptionText='Peple interested' progressBarValue={40} strokeWidth={10} progressBarColor='success' descriptionProgressDetail='Twitter Progress' /> </ChartBoxGridContainer> </div> <div className='grid-2-gap-30'> <ChartBoxGridContainer col={1} showBorder={true}> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' progressBarValue={80} strokeWidth={6} progressBarColor='primary' descriptionProgressDetail='YoY Growth' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' descriptionText='Total Clients Profit' progressBarValue={50} strokeWidth={15} progressBarColor='warning' descriptionProgressDetail='Retention' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='warning' mainTitleText='Products Sold' descriptionText='Total revenue streams' progressBarValue={100} strokeWidth={6} progressBarColor='danger' descriptionProgressDetail='Sales' /> <ChartBoxVar3 defaultValue="46%" defaultValueColor='danger' mainTitleText='Followers' descriptionText='Peple interested' progressBarValue={40} strokeWidth={10} progressBarColor='success' descriptionProgressDetail='Twitter Progress' /> </ChartBoxGridContainer> <ChartBoxGridContainer col={1} showBorder={true}> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' descriptionText='Last year expenses' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' descriptionText='Total Clients Profit' /> <ChartBoxVar3 defaultValue="$14M" defaultValueColor='warning' mainTitleText='Products Sold' descriptionText='Total revenue streams' /> <ChartBoxVar3 defaultValue="46%" defaultValueColor='danger' mainTitleText='Followers' descriptionText='Peple interested' /> </ChartBoxGridContainer> </div> </div> ) }; export default ChartBoxesVariation3;<file_sep>/src/pages/signup-boxed/signup-boxed.component.js import React from 'react'; import { Typography, Form, Input, Checkbox, Button } from 'antd'; import './signup-boxed.styles.css'; import '../signin-boxed/signin-boxed.styles.css'; import '../signup/signup.styles.css'; import '../signin/signin.styles.css'; const { Title, Text, Link } = Typography; const SignupBoxed = () => { return ( <div className='signup-boxed-container'> <div className='card-container '> <Form name="basic" initialValues={{ remember: true }} > <div className='signin-boxed-form-container'> <div className='flex-start'> <Title level={3} className='signin-page-welcome-back'>Welcome</Title> </div> <div className='flex-start'> <Title level={5} className='signin-page-please-text'>It only takes</Title> <Title level={5} className='signin-page-green-text'> &nbsp;a few seconds&nbsp; </Title> <Title level={5} className='signin-page-please-text'>to create your account</Title> </div> <div className='signin-box-form-wrapper'> <div className='signin-form-wrapper'> <Form.Item name="email" rules={[{ required: true, message: 'Please input your username!' }]} > <Input placeholder='Your email address'/> </Form.Item> </div> <div className='signin-form-wrapper'> <Form.Item name="name" rules={[{ required: true, message: 'Please input your password!' }]} > <Input placeholder='Your name'/> </Form.Item> </div> <div className='signin-form-wrapper'> <Form.Item name="password" rules={[{ required: true, message: 'Please input your username!' }]} > <Input.Password placeholder='Password here'/> </Form.Item> </div> <div className='signin-form-wrapper'> <Form.Item name="repeat-password" rules={[{ required: true, message: 'Please input your password!' }]} > <Input.Password placeholder='<PASSWORD>'/> </Form.Item> </div> <div className='signin-form-wrapper'> <Form.Item name="remember" valuePropName="checked"> <Checkbox>Accept our Term and Conditions</Checkbox> </Form.Item> </div> </div> </div> <div className='signin-page-line'></div> <div className='flex-start pad-20'> <Text className='signup-have-account-small'>Already have an account? </Text> <Link className='signup-have-account-small' href="https://ant.design" target="_blank"> &nbsp;Sign in </Link> <Text className='signup-have-account-small'>&nbsp;|&nbsp; </Text> <Link className='signup-have-account-small' href="https://ant.design" target="_blank"> &nbsp;Recover Password </Link> </div> <div className='signin-page-line'></div> <Form.Item> <div className='flex-end signin-footer'> <Button className='bg-round-button' type="primary">Create Account</Button> </div> </Form.Item> </Form> </div> </div> ) }; export default SignupBoxed;<file_sep>/src/pages/chart-boxes/chart-boxes-variation-1/grids/grids.component.js import React from 'react'; import { SettingOutlined, DesktopOutlined, RocketOutlined, RobotOutlined, GiftOutlined, HeartOutlined, StarOutlined } from '@ant-design/icons'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; import './grids.styles.css'; const Grids = () => { return ( <div className='chart-boxes-grid-container'> <ChartBoxGridContainer col={2}> <ChartBoxVar1 icon={<SettingOutlined />} iconBgColor='primary' iconColor='primary' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' /> <ChartBoxVar1 icon={<DesktopOutlined />} iconBgColor='#d8f3e5' iconColor='#3ac47d' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' /> <ChartBoxVar1 icon={<RobotOutlined />} iconContainerShape='square' iconBgColor='#f7d3dc' iconColor='#d92550' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' /> <ChartBoxVar1 icon={<RocketOutlined />} iconColor='#d6efff' iconBgColor='#30b1ff' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' /> </ChartBoxGridContainer> <ChartBoxGridContainer col={3}> <ChartBoxVar1 icon={<SettingOutlined />} iconBgColor='primary' iconColor='primary' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' /> <ChartBoxVar1 icon={<DesktopOutlined />} iconBgColor='#d8f3e5' iconColor='#3ac47d' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' /> <ChartBoxVar1 icon={<RobotOutlined />} iconContainerShape='square' iconBgColor='#f7d3dc' iconColor='#d92550' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' /> <ChartBoxVar1 icon={<RocketOutlined />} iconColor='#d6efff' iconBgColor='#30b1ff' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' /> <ChartBoxVar1 icon={<RobotOutlined />} iconContainerShape='square' iconBgColor='#f7d3dc' iconColor='#d92550' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' /> <ChartBoxVar1 icon={<RocketOutlined />} iconColor='#d6efff' iconBgColor='#30b1ff' defaultValue='62k' defaultValueDescription='Bugs Fixed' progressValueArrow='right' progressValue='175.5%' progressValueColor='info' /> </ChartBoxGridContainer> <ChartBoxGridContainer col={2}> <ChartBoxVar1 icon={<SettingOutlined />} bgColor='primary' iconBgColor='#eaeaea42' iconColor='white' defaultValue='45.8k' defaultValueDescription='Total Views' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='175.5%' progressValueColor='warning' zoom={true} /> <ChartBoxVar1 icon={<DesktopOutlined />} bgColor='success' iconBgColor='white' iconColor='success' defaultValue='17.2k' defaultValueDescription='Profiles' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='left' progressValue='175.5%' progressValueColor='white' zoom={true} /> <ChartBoxVar1 icon={<RocketOutlined />} bgColor='warning' iconBgColor='#eaeaea42' iconColor='white' defaultValue='5.82k' defaultValueDescription='Reports Submitted' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='54.1%' progressValueColor='white' zoom={true} /> <ChartBoxVar1 icon={<GiftOutlined />} bgColor='danger' iconBgColor='#eaeaea42' iconColor='white' defaultValue='5.82k' defaultValueDescription='Reports Submitted' defaultValueDescColor='white' defaultValueColor='white' progressValueArrow='up' progressValue='182.2%' progressValueColor='white' zoom={true} /> </ChartBoxGridContainer> <ChartBoxGridContainer col={3}> <ChartBoxVar1 icon={<SettingOutlined />} iconBgColor='primary' iconColor='primary' defaultValue='23k' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='success' zoom={true} /> <ChartBoxVar1 icon={<DesktopOutlined />} iconBgColor='#d8f3e5' iconColor='#3ac47d' defaultValue='17k' defaultValueDescription='Profile' progressValueArrow='left' progressValue='136%' progressValueColor='warning' zoom={true} /> <ChartBoxVar1 icon={<RobotOutlined />} iconContainerShape='square' iconBgColor='#f7d3dc' iconColor='#d92550' defaultValue='5,83k' defaultValueDescription='Report Submitted' progressValueArrow='up' progressValue='54.1%' progressValueColor='primary' zoom={true} /> <ChartBoxVar1 bgColor='linear-gradient(to bottom,#3ed68a,#9071cc)' icon={<SettingOutlined />} iconBgColor='#fff' iconColor='#3ac47d' defaultValue='23k' defaultValueDescColor='#fff' defaultValueColor='#fff' defaultValueDescription='Total Views' progressValueArrow='up' progressValue='176%' progressValueColor='#fff' zoom={true} /> <ChartBoxVar1 bgColor='linear-gradient(to right, #654ea3, #eaafc8)' icon={<HeartOutlined />} iconBgColor='#eaeaea42' iconColor='#654ea3' defaultValue='2.34k' defaultValueDescColor='#fff' defaultValueColor='#fff' defaultValueDescription='Profile' progressValueArrow='up' progressValue='176%' progressValueColor='#fff' zoom={true} /> <ChartBoxVar1 bgColor='linear-gradient(to right, #ff7e5f, #feb47b)' icon={<StarOutlined />} iconBgColor='#fff' iconColor='#feb47b' defaultValue='67.3k' defaultValueDescColor='#fff' defaultValueColor='#fff' defaultValueDescription='Reports Submitted' progressValueArrow='up' progressValue='190.2%' progressValueColor='#fff' zoom={true} /> </ChartBoxGridContainer> </div> ) }; export default Grids;<file_sep>/src/data/component-only-path-list.data.js const ComponentOnlyPathList = { '/pages/login': '/pages/login', '/pages/login-boxed': '/pages/login-boxed', '/pages/register': '/pages/register', '/pages/register-boxed': '/pages/register-boxed', '/pages/forgot-password': '/pages/forgot-password', '/pages/forgot-password-boxed': '/pages/forgot-password-boxed' }; export default ComponentOnlyPathList;<file_sep>/src/pages/element-navigation-menus/element-navigation-menus.component.js import React from 'react'; import CustomTabsWrapper from 'Components/custom-tabs-wrapper/custom-tabs-wrapper.component'; import CustomTabPanel from 'Components/custom-tab-panel/custom-tab-panel.component'; import GridMenuContainer from './grid-menu-container/grid-menu-container.component'; import VerticalMenuContainer from'./vertical-menu-container/vertical-menu-container.component'; import HeaderMenuContainer from './header-menu-container/header-menu-container.component'; import './element-navigation-menus.styles.css'; const ElementNavigationMenus = () => { return ( <CustomTabsWrapper> <CustomTabPanel data-key='basic' title='Grid Menu'> <GridMenuContainer/> </CustomTabPanel> <CustomTabPanel data-key='color-states' title='Vertical Menu'> <VerticalMenuContainer/> </CustomTabPanel> <CustomTabPanel data-key='advanced' title='Header Menu'> <HeaderMenuContainer/> </CustomTabPanel> </CustomTabsWrapper> ) }; export default ElementNavigationMenus;<file_sep>/src/data/settings-chart.data.js export const Options = { elements: { point: { radius: 0 } }, //point legend: { display: false }, maintainAspectRatio: false, label: false, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, }], yAxes :[ { gridLines: { display: false }, ticks: { display: false }, }, ], } } export const Options2 = { elements: { point: { radius: 4 } }, //point legend: { display: false }, maintainAspectRatio: false, label: false, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, stacked: false }], yAxes :[ { gridLines: { display: false }, ticks: { display: false }, }, ], } } /*Hidden label, border false, */ export const Options3 = { legend: { display: false }, animation: { animateScale: true }, maintainAspectRatio: false, scales: { xAxes: [{ barPercentage: 1, categoryPercentage: 1, gridLines: { display: false, drawBorder: false }, ticks: { display: false }, }], yAxes: [{ barPercentage: 1, categoryPercentage: 1, gridLines: { display: false, drawBorder: false }, ticks: { display: false }, }] }, tooltips: { } }; /*Visible label, border true, */ export const Options4 = { legend: { display: false }, animation: { animateScale: true }, maintainAspectRatio: false, scales: { xAxes: [{ barPercentage: 1, categoryPercentage: 1, gridLines: { display: true, drawBorder: true }, ticks: { display: true }, }], yAxes: [{ barPercentage: 1, categoryPercentage: 1, gridLines: { display: false, drawBorder: false }, ticks: { display: false }, }] }, tooltips: { } }; /*Hidden label, border false, */ export const Options5 = { legend: { display: false }, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, stacked: true }], yAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, stacked: true }] } }; //Line chart no x and y axes label no point export const Options6 = { legend: { display: false }, elements: { point: { radius: 0 } }, maintainAspectRatio: true, label: false, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, }], yAxes :[ { gridLines: { display: false }, ticks: { display: false }, }], } } //Bar chart, display label at the top, hidden x and y axes label export const Options7 = { legend: { display: true }, maintainAspectRatio: true, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, stacked: true }], yAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, stacked: true }] } }; //Line chart no x and y axes label no point export const Options8 = { legend: { display: false }, elements: { point: { radius: 5 } }, maintainAspectRatio: true, label: false, scales: { xAxes: [{ gridLines: { display: false, drawBorder: false }, ticks: { display: false }, }], yAxes :[ { gridLines: { display: false }, ticks: { display: false }, }], } } <file_sep>/src/components/chart-box-var-1/chart-box-var-1.styles.js import styled, {css } from 'styled-components'; import { colorsPalette } from '../custom-color/custom-color'; const zoom = css` &:hover { z-index: 10000; transform: scale(1.1); border-radius: 5px; } `; export const cboxzoom = props => { if (props.zoom) { return zoom; } } const borderCss = css` border-bottom: 1px solid #d6d6d6d6; &:not(:nth-child(${({col}) => col? (col)+'n' : 'n'})) { border-right: 1px solid #d6d6d6d6; } &:nth-last-child(${({col}) => col? '-n+'+(col): 'n'}) { border-bottom-width: 0; } `; const borderRadiusCss = css` &:first-child { border-top-left-radius: 5px; } &:nth-child(${({col}) => col? col : 0}) { border-top-right-radius: 5px; } &:nth-child(${({col, row}) => col? ((col*row) - (col-1)) : 0}) { border-bottom-left-radius: 5px; } &:last-child { border-bottom-right-radius: 5px; } `; export const borderStyled = props => { if (props.border) { return borderCss; } } export const ChartBox1Basic = styled.div` display: flex; flex-direction: column; padding: 15px 20px; align-items: center; justify-content: center; `; export const ChartBoxVar1GridAlignment = styled.div` display: grid; grid-template-columns: ${({icon, progress}) => icon? ' 80px 1fr': progress? '90px 1fr': '1fr' }; align-items: center; padding: 15px 20px; `; export const ChartBoxVar1Container = styled.div` background: ${({bgColor}) => colorsPalette[bgColor]? colorsPalette[bgColor] : bgColor }; box-shadow: ${({boxShadow}) => boxShadow? '0 0.46875rem 2.1875rem rgba(8,10,37,.03), 0 0.9375rem 1.40625rem rgba(8,10,37,.03), 0 0.25rem 0.53125rem rgba(8,10,37,.05), 0 0.125rem 0.1875rem rgba(8,10,37,.03)' : 'none'}; border-radius: ${({borderRadius}) => borderRadius? '5px' : '0px'}; align-items: center; transition: all .3s; transform: scale(1); ${cboxzoom}; ${borderStyled}; ${borderRadiusCss}; position: relative; width: 100%; `; export const ChartBoxVarIconContainer = styled.div` padding: 12px; border-radius : ${({iconContainerShape}) => iconContainerShape === 'circle'? '50%' : '3px'} ; width: 50px; height: 50px; display: flex; justify-content: center; align-items: center; font-size: 25px; background-color: ${({iconBgColor}) => colorsPalette[iconBgColor]? 'rgba('+colorsPalette[iconBgColor+'Rgb']+',.17)' : iconBgColor}; color: ${({iconColor}) => colorsPalette[iconColor]? colorsPalette[iconColor] : iconColor}; `; export const DefaultValueText = styled.p` margin: 3px 0 0; font-size: 32px; color: ${({defaultValueColor}) => colorsPalette[defaultValueColor]? colorsPalette[defaultValueColor]: defaultValueColor? defaultValueColor : '#505050'} ; font-weight: ${({normal}) => normal? '400': 'bold'}; `; export const DefaultValueDescriptionText = styled.p` color: ${({defaultValueDescColor}) => colorsPalette[defaultValueDescColor]? colorsPalette[defaultValueDescColor] : defaultValueDescColor ? defaultValueDescColor : '#929292'}; margin-bottom: 6px; `; export const ProgressValueTextContainer = styled.div` margin-top: 8px; display: flex; align-items: center; justify-content: ${({justifyContent}) => justifyContent? justifyContent : 'center'}; font-size: 14px; font-weight: 500; color: ${({progressValueColor}) => colorsPalette[progressValueColor]? colorsPalette[progressValueColor] : progressValueColor}; span { margin-right: 2px; } `; <file_sep>/src/pages/element-navigation-menus/header-menu-container/header-menu-container.component.js import React from 'react'; import { Typography } from 'antd'; import { MessageOutlined, SettingOutlined, HourglassOutlined, WalletOutlined, PushpinOutlined } from '@ant-design/icons'; import { CustomCard, CustomCardBody, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import CustomButton from 'Components/custom-button/custom-button.component'; const { Title } = Typography; const { Text, Link } = Typography; const HeaderMenuContainer = () => { return ( <div> <CustomCard className='mb-30'> <CustomCardTitleText> GRID HEADER MENU </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-4-col'> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#545cd887' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <Title className='white text-align-center' level={4}>Settings</Title> <span className='white text-align-center'>Manage all of your options</span> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <p className='nav-item-header'>Activity</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> Chat <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <p className='nav-item-header'>My Acccount</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> Settings <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> Messages <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#d92550c4' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <Title className='white text-align-center' level={4}>Settings</Title> <span className='white text-align-center'>Manage all of your options</span> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <p className='nav-item-header'>Activity</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <MessageOutlined style={style.iconStyle}/> Chat </div> <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <p className='nav-item-header'>My Acccount</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <SettingOutlined style={style.iconStyle}/> Settings </div> <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#3ac47dbf' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <Title className='white text-align-center' level={4}>Settings</Title> <span className='white text-align-center'>Manage all of your options</span> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <p className='nav-item-header'>Activity</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <MessageOutlined style={style.iconStyle}/> Chat </div> <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <p className='nav-item-header'>My Acccount</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <SettingOutlined style={style.iconStyle}/> Settings </div> <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#30b1ffbf' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <Title className='white text-align-center' level={4}>Settings</Title> <span className='white text-align-center'>Manage all of your options</span> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link'> <div> <MessageOutlined style={style.iconStyle}/> Chat </div> <CustomLabelBadge className='margin-left-auto' color='info' pill={true}>2</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <SettingOutlined style={style.iconStyle}/> Settings </div> <CustomLabelBadge className='margin-left-auto' color='success'>NEW</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> </div> </CustomCardBody> </CustomCard> <CustomCard className='mb-30'> <CustomCardTitleText> MENU HEADER BUTTONS SOLID BACKGROUND </CustomCardTitleText> <CustomCardBody> <div className='grid-menu-3-col grid-gap-20'> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#f7b924' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <Title style={{marginBottom: '0px'}} className='white text-align-center' level={4}>Settings</Title> <span className='white text-align-center'>Manage all of your options</span> <div className='flex-row align-items-center padding-top-20'> <div className='width-100 padding-top-10 '> <CustomButton style={style.marginRight10} size='small' variant='solid' color='dark'>Settings</CustomButton> <CustomButton size='small' variant='solid' color='primary'> <SettingOutlined/></CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link'> <div> <WalletOutlined style={style.iconStyle}/> Recover Password </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <PushpinOutlined style={style.iconStyle} /> Logs </div> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#444054' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <div className='flex-column align-items-start'> <Title style={{marginBottom: '0px'}} className='white text-align-center' level={4}>Settings</Title> <span className='white text-align-center'>Manage all of your options</span> <div className='flex-space-center padding-top-10'> <CustomButton style={style.marginRight10} size='small' variant='solid' color='primary'>Settings</CustomButton> <CustomButton size='small' variant='solid' color='danger'> <SettingOutlined/></CustomButton> </div> </div> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link'> <div> <WalletOutlined style={style.iconStyle}/> Recover Password </div> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <PushpinOutlined style={style.iconStyle} /> Logs </div> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> <CustomCard noneBoxShadow noneBorderRadius className='mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#eee' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1602529830051-14d6f235f3d6?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=768&q=80'}> <div className='flex-row justify-content-space-between align-items-start'> <div className='flex-column align-items-start'> <Title style={{marginBottom: '0px', color: 'black !important'}} className='black text-align-center' level={4}>Settings</Title> <span className='black text-align-center'>Manage all of your options</span> </div> <CustomButton size='small' variant='solid' color='warning'> <SettingOutlined/></CustomButton> </div> </CustomCardHeaderWithImage> <CustomCardBody> <ul className='nav'> <li className='nav-item'> <a href='#' className='nav-link'> <div> <WalletOutlined style={style.iconStyle}/> Recover Password </div> </a> </li> <li className='nav-item'> <p className='nav-item-header'>My Account</p> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <HourglassOutlined style={style.iconStyle} /> Messages </div> <CustomLabelBadge className='margin-left-auto' color='warning'>512</CustomLabelBadge> </a> </li> <li className='nav-item'> <a href='#' className='nav-link'> <div> <PushpinOutlined style={style.iconStyle} /> Logs </div> </a> </li> <li className='nav-item nav-item-divider'> </li> </ul> </CustomCardBody> </CustomCard> </div> </CustomCardBody> </CustomCard> </div> ) }; const style = { iconStyle: { fontSize: '15px', width: '30px', textAlign: 'left', }, marginRight10 : { marginRight: '10px' } } export default HeaderMenuContainer;<file_sep>/src/components/active-user-header/active-user-header.component.js import React from 'react'; import { Typography, Button } from 'antd'; import { UserOutlined, SettingOutlined } from '@ant-design/icons'; import './active-user-header.styles.css'; import '../../App.css'; const { Title, Text } = Typography; const ActiveUserHeader = ({ show })=> { return ( <div className={`floating-menu card-container header-active-user-menu ${show? 'floating-menu-show': 'floating-menu-close'} `}> <div className='card-header-container header-active-user-menu-header'> <div className='card-header-overlay header-active-user-menu-overlay'> <p className='card-header-title'>Users Online</p> <p className='card-header-desc'>Recent account Activity Overview</p> </div> </div> <div className='active-menu-body'> <UserOutlined className='header-active-menu-icon' /> <Title style={{marginBottom: '6px'}} level={1}>999k</Title> <Text style={{marginBottom: '13px'}} >Profile views since last login</Text> <Button style={{background: '#f7b924', color: '#000', border: 'none', borderRadius: '20px'}} type="primary"><SettingOutlined spin={true}/> Primary Button</Button> </div> </div> ) }; export default ActiveUserHeader;<file_sep>/src/components/lang-header/lang-header.component.js import React from 'react'; import { Menu } from 'antd'; import './lang-header.styles.css'; import '../../App.css'; import germany from '../../assets/flag/germany.png'; import indonesia from '../../assets/flag/indonesia.png'; import italy from '../../assets/flag/italy.png'; import usa from '../../assets/flag/usa.png'; const LangHeader = ({ show }) => { return ( <div className={`floating-menu card-container header-lang-menu ${show? 'floating-menu-show' : 'floating-menu-close'}`}> <div className='card-header-container header-lang-menu-header'> <div className='card-header-overlay header-lang-menu-overlay'> <p className='card-header-desc'> Choose language </p> </div> </div> <div className='header-lang-body'> <p className='capitalize-color keyframes'>Popular Languages</p> <Menu> <Menu.Item> <div className='lhc-menu-item-content'> <div className='lhc-lang-img-container'> <img src={indonesia} alt='indonesia' width='100%' height='100%'/> </div> <p>Indonesia</p> </div> </Menu.Item> <Menu.Item> <div className='lhc-menu-item-content'> <div className='lhc-lang-img-container'> <img src={usa} alt='usa' width='100%' height='100%'/> </div> <p>USA</p> </div> </Menu.Item> </Menu> <div className='lhc-line'/> <p className='capitalize-color keyframes'>Others Languages</p> <Menu> <Menu.Item> <div className='lhc-menu-item-content'> <div className='lhc-lang-img-container'> <img src={germany} alt='germany' width='100%' height='100%'/> </div> <p>Germany</p> </div> </Menu.Item> <Menu.Item> <div className='lhc-menu-item-content'> <div className='lhc-lang-img-container'> <img src={italy} alt='italy' width='100%' height='100%'/> </div> <p>Italy</p> </div> </Menu.Item> </Menu> </div> </div> ) }; export default LangHeader;<file_sep>/src/components/custom-label-badge/custom-label-badge.styles.js import styled, { css } from 'styled-components'; import { colorsPalette } from '../custom-color/custom-color'; const labelbadge = css` padding: 1px 10px; font-weight: bold; font-size: 11px; text-transform: uppercase; border-radius: ${({pill}) => pill? '20px': '5px'}; display: inline-block; align-self: center; background-color: ${({color}) => color? colorsPalette[color] : '#fff'}; color: ${({color}) => color? colorsPalette[color+'Text'] : '#000'}; ` export const LabelBadge = styled.span` ${labelbadge}; `; export const LabelBadgeLink = styled.a` ${labelbadge}; cursor: pointer; &:hover { color: ${({color}) => color? colorsPalette[color+'Text'] : '#000'}; background-color: ${({color}) => color? colorsPalette[color+'Dark'] : '#fff'}; } `;<file_sep>/src/pages/dashboard-commerce/dashboard-commerce-var-2/dashsboard-commerce-var-2.component.js import React, { useRef } from 'react'; import { Typography, Avatar, Carousel, Table } from 'antd'; import { Line, Bar } from 'react-chartjs-2'; import { DownOutlined, UpOutlined, LeftOutlined, RightOutlined, ScheduleOutlined, ArrowRightOutlined, AlertOutlined, CrownOutlined, FireOutlined, ClearOutlined, SettingOutlined } from '@ant-design/icons'; import CustomButton from 'Components/custom-button/custom-button.component'; import ChartBoxVar1 from 'Components/chart-box-var-1/chart-box-var-1.component'; import CustomLabelBadge from 'Components/custom-label-badge/custom-label-badge.component'; import ChartBoxVar3 from 'Components/chart-box-var-3/chart-box-var-3.component'; import ChartBoxGridContainer from 'Components/chart-box-grid/chart-box-grid.component'; import { CustomCard, CustomCardFooter, CustomCardBody, CustomCardHeader, CustomCardTitleText } from 'Components/custom-card/custom-card.styles'; import { CustomCardHeaderWithImage } from 'Components/custom-card/custom-card-header-with-image.component'; import { Data7, Data8, Data9, Data10, Data5, Data11 } from 'Data/chart.data'; import { Options6, Options4, Options5, Options3, Options } from 'Data/settings-chart.data'; import { DataTable2, DataHighlights, Columns3 } from 'Data/table.data'; import '../dashboard-commerce.styles.css'; const { Title, Text } = Typography; const DashboardCommerceVariation2 = () => { const customeSlider = useRef(); // setting slider configurations const sliderSettings ={ infinite: true, speed: 500, slidesToShow: 1, slidesToScroll: 1, arrows: false, dots: false }; const gotoNext = () => { customeSlider.current.innerSlider.slickNext() } const gotoPrev = () => { customeSlider.current.innerSlider.slickPrev() } return ( <div> <div className='da-commerce-grid-2-2 mb-30'> <div className='width-100 overflow-auto'> <CustomCard className='mb-30'> <CustomCardHeader> <CustomCardTitleText>INCOME REPORT</CustomCardTitleText> </CustomCardHeader> <CustomCardBody> <div style={{width: '100%', overflow: 'hidden'}}> <Line data={Data7} width={100} height={240} options={Options4} /> </div> </CustomCardBody> </CustomCard> <CustomCard> <CustomCardBody> <Title level={4} className='color6d mb-6'>Target Sales</Title> <Title level={5} className='color98 fw-400 no-margin-no-padding'>Total performance for this Month</Title> <ChartBoxGridContainer col={2} showBorder={false} showBoxShadow={false}> <ChartBoxVar3 defaultValue="1896" defaultValueColor='success' mainTitleText='Total Orders' progressBarValue={80} strokeWidth={6} progressBarColor='primary' descriptionProgressDetail='YoY Growth' /> <ChartBoxVar3 defaultValue="$568" defaultValueColor='primary' mainTitleText='Clients' progressBarValue={50} strokeWidth={6} progressBarColor='warning' descriptionProgressDetail='Retention' /> </ChartBoxGridContainer> </CustomCardBody> </CustomCard> </div> <div className='flex-column overflow-hidden'> <CustomCard className='mb-30'> <CustomCardHeader> <CustomCardTitleText>HIGHLIGHTS</CustomCardTitleText> <CustomCardBody> <div className='da-highlights-container '> { DataHighlights.map((item) => ( <div className='da-highlights-item'> <div className='flex-row align-items-center'> <Avatar className='mr-20' size={40} src={item.img} /> <div> <p className='color6d no-margin-no-padding'>{item.name}</p> <CustomLabelBadge pill color='primary'> {item.badge} </CustomLabelBadge> </div> </div> <div className='flex-row-fit-content align-items-center'> <Title level={3} className='success'>{item.value}</Title> { item.icon.type === 'up' ? <UpOutlined className={item.icon.color} style={style.downIcon} /> : <DownOutlined className={item.icon.color} style={style.downIcon} /> } </div> </div> )) } </div> </CustomCardBody> </CustomCardHeader> </CustomCard> <CustomCard className='overflow-hidden mb-30'> <CustomCardBody> <Title level={4} className='primary mb-6'>Monthly Statistics</Title> <div className='technical-support-container flex-column align-items-center justify-content-center'> <button className='button-navigation button-prev' onClick={()=>gotoPrev()}> <LeftOutlined /> </button> <button className='button-navigation button-next' onClick={()=>gotoNext()}> <RightOutlined /> </button> <div style={{width: '100%'}}> <Carousel {...sliderSettings} ref={customeSlider}> <div> <div> <div className='flex-row align-items-center'> <p className='da-fs-34-bold color5d mr-10'>$568</p> <p className='color98 no-margin-no-padding'>Total Expanses Today</p> </div> </div> <Bar data={Data8} height={120} options={Options5} /> </div> <div> <div> <div className='flex-row align-items-center'> <p className='da-fs-34-bold color5d mr-10'>$1025</p> <p className='color98 no-margin-no-padding'>Revenue increase this quarter</p> </div> </div> <Line data={Data9} height={120} options={Options6} /> </div> <div> <div> <div className='flex-row align-items-center'> <p className='da-fs-34-bold color5d mr-10'>$103M</p> <p className='color98 no-margin-no-padding'>Total Sales this Month</p> </div> </div> <Line data={Data10} height={120} options={Options6} /> </div> </Carousel> </div> </div> </CustomCardBody> </CustomCard> </div> </div> <CustomCard className='mb-30'> <CustomCardHeader> <CustomCardTitleText>Easy Dynamic Tables</CustomCardTitleText> </CustomCardHeader> <CustomCardBody className='overflow-auto'> <Table columns={Columns3} dataSource={DataTable2} /> </CustomCardBody> </CustomCard> <div className='grid-2-gap-30'> <div className='overflow-hidden'> <div className='da-box-chart-container-fixed-without-shadow mb-30'> <ChartBoxVar1 bgColor="linear-gradient(-20deg,#2b5876,#4e4376)" icon={<ScheduleOutlined />} iconBgColor='#ffffffd4' iconColor='primary' defaultValue='3M' defaultValueColor='white' defaultValueDescription='Cash Deposit' defaultValueDescColor='white' progressValueArrow='up' progressValue='176%' bgOverlay='transparent' progressValueColor='white' chart={ <div style={{paddingTop: '100px'}}> <Bar data={Data5} height={240} width={100} options={Options3} /> </div> } > <Text className='fw-bold white'><span className='white'><DownOutlined /> 54.1% </span> down last 30 days</Text> </ChartBoxVar1> </div> <div className='da-box-chart-container-fixed-without-shadow mb-30'> <ChartBoxVar1 bgColor="linear-gradient(to right, #007991, #78ffd6)" icon={<ScheduleOutlined />} iconBgColor='#ffffffd4' iconColor='#068094' defaultValue='1.5M' defaultValueColor='white' defaultValueDescription='Bugs Fixed' defaultValueDescColor='white' progressValueArrow='up' progressValue='176%' bgOverlay='transparent' progressValueColor='white' chart={ <div style={{paddingTop: '100px'}}> <Line data={Data11} height={240} width={100} options={Options} /> </div> } > <Text className='fw-bold white'><span className='white'><ArrowRightOutlined /></span> 175.5%</Text> </ChartBoxVar1> </div> </div> <div> <CustomCard className='overflow-hidden mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#0e0e0eb8' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1546629313-ea9c287a8b9f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'}> <div className='flex-row justify-content-space-between align-items-center padding-vertical-20'> <div className='flex-row-fit-content'> <Avatar size={50} className='mr-20' src="https://images.unsplash.com/photo-1589329482108-e414c7c6b8c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=334&q=80" /> <div className='flex-column text-align-left'> <Title className='white no-margin-no-padding' level={4}>Silaladungka</Title> <p className='white no-margin-no-padding'>Lead UX Designer</p> </div> </div> <CustomButton className='margin-top-8' color='success' variant='solid'>View Profile</CustomButton> </div> </CustomCardHeaderWithImage> <CustomCardBody> <div className='flex-column align-items-center'> <Title className='color5d fw-400 no-margin-no-padding' level={4}> <strong className='danger'>12</strong> new leads, <strong className='success'>$56.4</strong> in sales </Title> </div> </CustomCardBody> <CustomCardFooter className='flex-column no-margin-no-padding'> <div className='grid-menu-2-col'> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<CrownOutlined />}> Automation </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='danger' variant='no-outlined' icon={<AlertOutlined />}> Reports </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='success' variant='no-outlined' icon={<FireOutlined />}> Activity </CustomButton> </div> <div className='grid-row-for-2-col'> <CustomButton square iconType='vertical' block color='dark' variant='no-outlined' icon={<ClearOutlined />}> Settings </CustomButton> </div> </div> </CustomCardFooter> </CustomCard> <CustomCard className='overflow-hidden mb-30'> <CustomCardHeaderWithImage backgroundColorOverlay='#0e1a79c2' className='align-items-center flex-column' imgUrl={'https://images.unsplash.com/photo-1546629313-ea9c287a8b9f?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=400&q=80'}> <div className='flex-column align-items-center'> <Title className='white no-margin-no-padding' level={3}>Top Sellers</Title> <Title className='white no-margin-no-padding fw-400' level={5}>Yet another example of Card Boxes</Title> <CustomButton className='margin-top-10' color='warning' variant='solid'>View Profile</CustomButton> </div> </CustomCardHeaderWithImage> <CustomCardBody className='no-margin-no-padding'> <div className='grid-2-gap-30 align-items-center'> <div className='flex-column align-items-center'> <SettingOutlined spin={true} style={style.settingIcon} /> </div> <div className='border-bottom-container width-100'> <div className='border-bottom-item'> <Title className='no-margin-no-padding danger' level={1}>$363M</Title> <p className='color98'>Sales today</p> </div> <div className='border-bottom-item'> <Title className='no-margin-no-padding primary' level={1}>$187M</Title> <p className='color98'>Sales this month</p> </div> </div> </div> </CustomCardBody> <CustomCardFooter > <CustomButton variant='no-outlined' block color='warning'>Refresh All</CustomButton> </CustomCardFooter> </CustomCard> </div> </div> </div> ) }; const style = { downIcon: { fontSize: '11px', marginLeft: '10px' }, settingIcon : { fontSize: '79px', color: '#a86799' } } export default DashboardCommerceVariation2;
912ac17fb4c50a62d9d72cf4345b325342c9bf51
[ "JavaScript", "Markdown" ]
80
JavaScript
anaoktaa/admin-dashboard
a9ecf5c4f27f866f1548a59b2e3a07f4bafe125f
937c81a63af8c7f1a4f20a9fda5df0d1c581311d
refs/heads/master
<repo_name>GWU-Advanced-OS/lwt-v1-group-name<file_sep>/scheddev/lwt.c #include<stdio.h> #include<stdlib.h> #include<assert.h> #include<sl.h> #include"include/kalloc.h" #include"include/lwt.h" #define LWT_CAS(d,t,v) do{ \ t = d; \ }while(!ps_cas(&d,t,t+v)) void __lwt_start(); void __lwt_schedule(void); static inline void __lwt_dispatch(lwt_t curr, lwt_t next); void __init_counter(void); void __init_thread_head(void); void lwt_init() { kinit(); __init_thread_head(); } void __init_thread_head() { uint size = sizeof(struct _lwt_t) + STACK_SIZE; lwt_head = (lwt_t) kalloc(size); assert(lwt_head); ps_list_init_d(lwt_head); lwt_head->ip = (ulong)0; lwt_head->sp = (ulong)0; lwt_head->id = gcounter.lwt_count; lwt_head->status = LWT_ACTIVE; lwt_head->tid = cos_thdid(); int t; LWT_CAS(gcounter.lwt_count,t,1); LWT_CAS(gcounter.runable_counter,t,1); } lwt_t lwt_create(lwt_fn_t fn, void *data, lwt_flags_t flags) { lwt_t lwt_new; assert(fn); //malloc the new thread and stack uint size = sizeof(struct _lwt_t) + STACK_SIZE; lwt_new = (lwt_t) kalloc(size); assert(lwt_new); lwt_new->id = gcounter.lwt_count; lwt_new->ip = (ulong) (&__lwt_start); lwt_new->sp = (ulong)lwt_new + size - 4; lwt_new->status = LWT_ACTIVE; lwt_new->lwt_nojoin = flags; lwt_new->fn = fn; lwt_new->data = data; //lwt_new->kthd = sl_thd_curr(); lwt_new->tid = lwt_head->tid; lwt_new->joiner = NULL; lwt_new->target = NULL; lwt_new->return_val = NULL; int t; LWT_CAS(gcounter.lwt_count,t,1); LWT_CAS(gcounter.runable_counter,t,1); ps_list_add_d(ps_list_prev_d(lwt_head),lwt_new); return lwt_new; } void* lwt_join(lwt_t lwt) { void *temp_data; int t; assert(lwt); if(lwt->lwt_nojoin) return NULL; lwt_head->joiner = lwt; lwt->target = lwt_head; if(lwt->status == LWT_ACTIVE) { lwt_head->status = LWT_BLOCKED; LWT_CAS(gcounter.blocked_counter,t,1); LWT_CAS(gcounter.runable_counter,t,-1); lwt_yield(NULL); /*lwt_chan_t c = lwt_chan(0); c->snd_cnt = 1; lwt_head->data = c; lwt_rcv(c); lwt_chan_deref(c);*/ } temp_data = lwt->return_val; ps_list_rem_d(lwt); kfree((void *)lwt,sizeof(struct _lwt_t) + STACK_SIZE); LWT_CAS(gcounter.died_counter,t,-1); return temp_data; } void lwt_die(void *data) { int t; lwt_head->return_val = (void *)data; LWT_CAS(gcounter.runable_counter,t,-1); if(lwt_head->lwt_nojoin) { lwt_t tmp_curr = lwt_head; do{ lwt_head = ps_list_next_d(lwt_head); }while(lwt_head->status != LWT_ACTIVE); assert(tmp_curr != lwt_head); ps_list_rem_d(tmp_curr); kfree((void *)tmp_curr,sizeof(struct _lwt_t) + STACK_SIZE); struct _lwt_t trash; __lwt_dispatch(&trash,lwt_head); } /* * if the current thread is the joiner of a specific thread, * set this blocked thread active */ if(lwt_head->target != LWT_NULL)// && lwt_head->target->status == LWT_BLOCKED) { LWT_CAS(gcounter.blocked_counter,t,-1); LWT_CAS(gcounter.runable_counter,t,1); lwt_head->target->status = LWT_ACTIVE; /*lwt_snd((lwt_chan_t)lwt_head->target->data,(void *)1); lwt_chan_deref((lwt_chan_t)lwt_head->target->data);*/ } LWT_CAS(gcounter.died_counter,t,1); lwt_head->status = LWT_DEAD; __lwt_schedule(); } int lwt_yield(lwt_t lwt) { if(lwt == NULL) { __lwt_schedule(); } else if (lwt->status == LWT_ACTIVE) { if(lwt->tid == lwt_head->tid) { lwt_t tmp_curr = lwt_head; lwt_head = lwt; __lwt_dispatch(tmp_curr,lwt_head); } else { __lwt_schedule(); } } return -1; } lwt_t lwt_current(void) { return lwt_head; } /* * gets the thread id of a specified thread. * returns -1 if the thread not exists */ int lwt_id(lwt_t lwt) { assert(lwt); if (!lwt) { return -1; } return lwt->id; } /* * get the number of threads that are either runnable, * blocked (i.e. that are joining, on a lwt that hasn't died), * or that have died */ int lwt_info(lwt_info_t t) { switch (t) { case LWT_INFO_NTHD_RUNNABLE: return gcounter.runable_counter; case LWT_INFO_NTHD_BLOCKED: return gcounter.blocked_counter; case LWT_INFO_NTHD_ZOMBIES: return gcounter.died_counter; case LWT_INFO_NCHAN: return gcounter.nchan_counter; case LWT_INFO_NSNDING: return gcounter.nsnding_counter; case LWT_INFO_NRCVING: return gcounter.nrcving_counter; default: return -1; } } void __lwt_start() { void *return_val = lwt_head->fn(lwt_head->data); lwt_die(return_val); } void __lwt_schedule(void) { lwt_t temp; temp = lwt_head; do{ lwt_head = ps_list_next_d(lwt_head); }while(lwt_head->status != LWT_ACTIVE); if (temp != lwt_head) { __lwt_dispatch(temp, lwt_head); } return; } static inline void __lwt_dispatch(lwt_t curr, lwt_t next) { __asm__ __volatile__( "pushal\n\t" //PUSH ALL other register "movl $1f, (%%eax)\n\t" //save IP to TCB "movl %%esp, (%%ebx)\n\t" //save SP to TCB "movl %%edx, %%esp\n\t" //recover the SP "jmp %%ecx\n\t" //recover the IP "1:" //LABEL "popal" :: "a"(&curr->ip), "b"(&curr->sp), "c"(next->ip), "d"(next->sp) : "cc", "memory"); //for switching back to old thread, nested? return; } /* * Currently assume that sz is always 0. * This function uses malloc to allocate * the memory for the channel. */ lwt_chan_t lwt_chan(int sz) { lwt_chan_t new; assert(sz >= 0); uint size = sizeof(struct lwt_channel) + (sz + 1) * sizeof(void *); new = (lwt_chan_t) kalloc(size); assert(new); new->data_buffer.size = sz + 1; new->data_buffer.start = 0; new->data_buffer.end = 0; new->data_buffer.data = (void*) new + sizeof(struct lwt_channel); new->snd_cnt = 0; new->snd_thds = NULL; new->id = gcounter.nchan_id; new->rcv_thd = lwt_head; new->iscgrp = 0; new->cgrp = NULL; int t; LWT_CAS(gcounter.nchan_id,t,1); LWT_CAS(gcounter.nchan_counter,t,1); return new; } /* * Deallocate the channel if no threads still * have references to the channel. */ void lwt_chan_deref(lwt_chan_t c) { assert(c); if(c->snd_cnt > 0) { c->snd_cnt--; } else if (c->rcv_thd == lwt_head && c->rcv_thd->status == LWT_ACTIVE) { int t; LWT_CAS(gcounter.nchan_counter,t,-1); c->rcv_thd = NULL; //will also set "rcv_thd" as NULL kfree((void*)c,sizeof(struct lwt_channel) + c->data_buffer.size * sizeof(void *)); } } int lwt_snd(lwt_chan_t c, void *data) { //data being NULL or rcv being null is illegal assert(data && c); /* if (c->rcv_thd == NULL) { return -1; }*/ int t; LWT_CAS(gcounter.nsnding_counter,t,1); LWT_CAS(gcounter.runable_counter,t,-1); if(c->data_buffer.size == 1) { //block current thread while (c->rcv_thd->status == LWT_ACTIVE)//blocked == 0) { lwt_yield(LWT_NULL); } //if there is node that is new added without filling the data,fill it clist_t new_clist; uint size = sizeof(struct clist_head); new_clist = (clist_t) kalloc(size); assert(new_clist); new_clist->thd = lwt_head; new_clist->data = data; if(c->snd_thds == NULL) { ps_list_init_d(new_clist); c->snd_thds = new_clist; } else { ps_list_add_d(ps_list_prev_d(c->snd_thds),new_clist); } } else { int tail; do{ while((c->data_buffer.end + 1)%c->data_buffer.size == c->data_buffer.start) { lwt_yield(LWT_NULL); } tail = c->data_buffer.end; c->data_buffer.data[tail] = data; }while(!ps_cas(&(c->data_buffer.end), tail,(tail + 1)%c->data_buffer.size)); } //add the event if (c->iscgrp && (c->data_buffer.start + 1)%c->data_buffer.size == c->data_buffer.end) { if(c->cgrp->events == NULL) { ps_list_init_d(c); c->cgrp->events = c; } else { ps_list_add_d(ps_list_prev_d(c->cgrp->events),c); } } c->rcv_thd->status = LWT_ACTIVE; struct sl_thd* sl = sl_thd_lkup(c->rcv_thd->tid); if(sl->state == SL_THD_BLOCKED) { sl->state = SL_THD_RUNNABLE; sl_mod_wakeup(sl_mod_thd_policy_get(sl)); } LWT_CAS(gcounter.nsnding_counter,t,-1); LWT_CAS(gcounter.runable_counter,t,1); return 0; } void *lwt_rcv(lwt_chan_t c) { assert(c != NULL); void* temp; c->rcv_thd = lwt_head; /* if (c->rcv_thd != lwt_head) { return NULL; }*/ int t; LWT_CAS(gcounter.nrcving_counter,t,1); LWT_CAS(gcounter.runable_counter,t,-1); c->rcv_thd->status = LWT_WAITING;//blocked = 1; if(c->data_buffer.size == 1) { //if snd_thds is null, block the reciever to wait for sender while (c->snd_thds == NULL)//ps_list_head_empty(&c->snd_head)) { lwt_yield(LWT_NULL); } temp = c->snd_thds->data; if(ps_list_singleton_d(c->snd_thds)) { assert(c->snd_thds); kfree((void *)c->snd_thds,sizeof(struct clist_head)); c->snd_thds = NULL; } else { clist_t tmp = c->snd_thds; c->snd_thds = ps_list_next_d(tmp); ps_list_rem_d(tmp); assert(c->snd_thds); kfree((void *)c->snd_thds,sizeof(struct clist_head)); } } else { int head; do{ //if empty, block rcv, remove c from ready queue while(c->data_buffer.start == c->data_buffer.end) { lwt_yield(LWT_NULL); } head = c->data_buffer.start; temp = c->data_buffer.data[head]; }while(!ps_cas(&c->data_buffer.start,head,(head + 1)%c->data_buffer.size)); } if (c->iscgrp && c->data_buffer.start == c->data_buffer.end) { if(c->cgrp->events != NULL) { if(ps_list_singleton_d(c)) { c->cgrp->events = NULL; } else { c->cgrp->events = ps_list_next_d(c); ps_list_rem_d(c); } } } LWT_CAS(gcounter.nrcving_counter,t,-1); LWT_CAS(gcounter.runable_counter,t,1); c->rcv_thd->status = LWT_ACTIVE; //remove the event return temp; } /* * a channel is sent over the channel (sending is sent over c). * This is used for reference counting to determine * when to deallocate the channel. */ int lwt_snd_chan(lwt_chan_t c, lwt_chan_t sending) { //data being NULL or rcv being null is illegal assert(c && sending); sending->snd_cnt++; sending->rcv_thd = lwt_head; return lwt_snd(c,sending); } /* Same as for lwt rcv except a channel is sent over the channel.*/ lwt_chan_t lwt_rcv_chan(lwt_chan_t c) { return lwt_rcv(c); } /* * This function, like lwt create, creates a new thread. * The difference is that instead of passing a void * to that new thread, * it passes a channel. */ lwt_t lwt_create_chan(lwt_chan_fn_t fn, lwt_chan_t c, lwt_flags_t flag) { assert(fn); assert(c); lwt_t lwt = lwt_create((lwt_fn_t)fn,(void*)c,flag); c->snd_cnt++; return lwt; } lwt_cgrp_t lwt_cgrp(void) { lwt_cgrp_t new; uint size = sizeof(struct cgroup); new = (lwt_cgrp_t) kalloc(size); assert(new); new->n_chan = 0; new->events = NULL; return new; } int lwt_cgrp_free(lwt_cgrp_t cgrp) { assert(cgrp); if (NULL == cgrp->events && 0 == cgrp->n_chan) { kfree((void *)cgrp,sizeof(struct cgroup)); return 0; } return -1; } int lwt_cgrp_add(lwt_cgrp_t cgrp, lwt_chan_t c) { if (c->iscgrp == 1) return -1; //A channel can be added into only one group cgrp->n_chan++; c->iscgrp = 1; c->cgrp = cgrp; return 0; } int lwt_cgrp_rem(lwt_cgrp_t cgrp, lwt_chan_t c) { assert(!c->snd_thds); if (c->snd_thds != NULL || c->data_buffer.start != c->data_buffer.end) return 1; //cgrp has a pending event if(cgrp != c->cgrp) return -1; cgrp->n_chan--; c->iscgrp = 0; c->cgrp = NULL; return 0; } lwt_chan_t lwt_cgrp_wait(lwt_cgrp_t cgrp) { lwt_head->status = LWT_WAITING; while (cgrp->events == NULL) { lwt_yield(NULL); } lwt_head->status = LWT_ACTIVE; return cgrp->events; } void lwt_chan_mark_set(lwt_chan_t c, void *data) { c->mark = data; return; } void *lwt_chan_mark_get(lwt_chan_t c) { return c->mark; } void *__lwt_kthd_entry(void* data) { __init_thread_head(); kthd_parm_t parm = (kthd_parm_t) data; parm->lwt = lwt_head; lwt_create(parm->fn,parm->c, LWT_NOJOIN); int id = cos_thdid(); while(1) { sl_cs_enter(); lwt_head = parm->lwt; lwt_yield(NULL); sl_cs_exit(); lwt_t tmp = parm->lwt; int anum = 0; do{ if(tmp->status == LWT_ACTIVE) anum++; tmp = ps_list_next_d(tmp); }while(tmp != parm->lwt); if(anum == 1) { sl_thd_block(0); } sl_thd_yield(0); } } int lwt_kthd_create(lwt_fn_t fn, lwt_chan_t c) { kthd_parm_t parm = (kthd_parm_t)kalloc(sizeof(struct __kthd_parm_t)); assert(parm); parm->fn = fn; parm->c = c; struct sl_thd *s = sl_thd_alloc(__lwt_kthd_entry,parm); union sched_param spl = {.c = {.type = SCHEDP_PRIO, .value = 10}}; sl_thd_param_set(s, spl.v); return (s != NULL)-1; } int lwt_snd_thd(lwt_chan_t c, lwt_t sending) { assert(sending != lwt_head); sending->status = LWT_BLOCKED; int t; LWT_CAS(gcounter.runable_counter,t,-1); return lwt_snd(c,sending); } lwt_t lwt_rcv_thd(lwt_chan_t c) { lwt_t lwt = lwt_rcv(c); lwt->tid = lwt_head->tid; ps_list_rem_d(lwt); ps_list_add_d(ps_list_prev_d(lwt_head),lwt); lwt->status = LWT_ACTIVE; int t; LWT_CAS(gcounter.runable_counter,t,1); return lwt; } <file_sep>/compare_test_file.c #include <stdio.h> #include <stdlib.h> #include <assert.h> #include "include/lwt.h" #define rdtscll(val) __asm__ __volatile__("rdtsc" : "=A" (val)) void * lm_fn_null(void *d) { return NULL; } void test_lwt_yield(void) { int i; unsigned long long start, end; for (i = 0 ; i < 1000 ; i++){ lwt_create(lm_fn_null, NULL, LWT_NOJOIN); } rdtscll(start); lwt_yield(LWT_NULL); rdtscll(end); printf("[PERF] %5lld <- yield 1000 in lwt\n", (end-start)); } void * lm_fn_chan(lwt_chan_t to) { lwt_chan_t from; int i; from = (lwt_chan_t)lwt_chan(0); lwt_snd_chan(to, from); for (i = 0 ; i < 10000 ; i++) { lwt_snd(to, (void*)1); lwt_rcv(from); } lwt_chan_deref(from); return NULL; } void test_lwt_channel() { lwt_chan_t from, to; lwt_t t; int i; unsigned long long start, end; from = (lwt_chan_t)lwt_chan(0); t = lwt_create_chan((lwt_chan_fn_t)lm_fn_chan, from, LWT_JOIN); to = (lwt_chan_t)lwt_rcv_chan(from); rdtscll(start); for (i = 0 ; i < 10000 ; i++) { lwt_rcv(from); lwt_snd(to, (void*)2); } lwt_chan_deref(to); rdtscll(end); printf("[PERF] %5lld <- channel in lwt\n", (end-start)/(10000*2)); lwt_join(t); } void * lm_fn_identity(void *d) { return d; } void test_lwt_create(void) { int i; unsigned long long start, end; rdtscll(start); for (i = 0 ; i < 10000 ; i++){ lwt_create(lm_fn_identity, NULL, LWT_NOJOIN); } rdtscll(end); printf("[PERF] %5lld <- thd_create in lwt\n", (end-start)/10000); } void* lm_fn_multiwait(void *d) { assert(d); int i; for (i = 0 ; i < 10000 ; i++) { if ((i % 7) == 0) { int j; for (j = 0 ; j < (i % 8) ; j++) lwt_yield(LWT_NULL); } lwt_snd((lwt_chan_t)d, (void*)lwt_id(lwt_current())); } } void test_lwt_cgrp() { lwt_chan_t cs[100]; lwt_t ts[100]; int i; lwt_cgrp_t g; unsigned long long start, end; g = lwt_cgrp(); assert(g); for(i = 0 ; i < 100 ; i++) { cs[i] = lwt_chan(0); assert(cs[i]); ts[i] = lwt_create_chan(lm_fn_multiwait, cs[i],LWT_NOJOIN); assert(ts[i]); lwt_chan_mark_set(cs[i], (void*)lwt_id(ts[i])); assert(0 == lwt_cgrp_add(g, cs[i])); } assert(lwt_cgrp_free(g) == -1); rdtscll(start); for(i = 0 ; i < 10000 * 100; i++) { lwt_chan_t c; int r; c = lwt_cgrp_wait(g); //assert(c); r = (int)lwt_rcv(c); //assert(r == (int)lwt_chan_mark_get(c)); } rdtscll(end); printf("[PERF] %5lld <- grp in lwt, size %d\n", (end-start)/(10000*100),100); for(i = 0 ; i < 100 ; i++) { lwt_cgrp_rem(g, cs[i]); lwt_chan_deref(cs[i]); } assert(0 == lwt_cgrp_free(g)); return; } void run_lm_tests() { //test_lwt_yield(); //test_lwt_channel(); // test_lwt_create(); test_lwt_cgrp(); } <file_sep>/lwt.c #include<stdio.h> #include<stdlib.h> #include<assert.h> #include"include/kalloc.h" #include"include/lwt.h" void __lwt_start(); void __lwt_schedule(void); static inline void __lwt_dispatch(lwt_t curr, lwt_t next); void __init_counter(void); void __init_thread_head(void); void lwt_init() { kinit(); __init_thread_head(); } void __init_thread_head() { uint size = sizeof(struct _lwt_t) + STACK_SIZE; lwt_head = (lwt_t) kalloc(size); assert(lwt_head); ps_list_init_d(lwt_head); lwt_head->ip = (ulong)0; lwt_head->sp = (ulong)0; lwt_head->id = gcounter.lwt_count++; lwt_head->status = LWT_ACTIVE; //lwt_head->kthd = sl_thd_curr(); // lwt_head->tid = cos_thdid(); gcounter.runable_counter++; } lwt_t lwt_create(lwt_fn_t fn, void *data, lwt_flags_t flags) { lwt_t lwt_new; assert(fn); //malloc the new thread and stack uint size = sizeof(struct _lwt_t) + STACK_SIZE; lwt_new = (lwt_t) kalloc(size); assert(lwt_new); lwt_new->id = gcounter.lwt_count++; lwt_new->ip = (ulong) (&__lwt_start); lwt_new->sp = (ulong)lwt_new + size - 4; lwt_new->status = LWT_ACTIVE; lwt_new->lwt_nojoin = flags; lwt_new->fn = fn; lwt_new->data = data; //lwt_new->kthd = sl_thd_curr(); //lwt_new->tid = cos_thdid(); lwt_new->joiner = NULL; lwt_new->target = NULL; lwt_new->return_val = NULL; gcounter.runable_counter++; ps_list_add_d(ps_list_prev_d(lwt_head),lwt_new); return lwt_new; } void* lwt_join(lwt_t lwt) { void *temp_data; assert(lwt); if(lwt->lwt_nojoin) return NULL; lwt_head->joiner = lwt; lwt->target = lwt_head; if(lwt->status == LWT_ACTIVE) { lwt_head->status = LWT_BLOCKED; gcounter.blocked_counter++; gcounter.runable_counter--; lwt_yield(lwt); /*lwt_chan_t c = lwt_chan(0); c->snd_cnt = 1; lwt_head->data = c; lwt_rcv(c); lwt_chan_deref(c);*/ } temp_data = lwt->return_val; ps_list_rem_d(lwt); kfree((void *)lwt,sizeof(struct _lwt_t) + STACK_SIZE); gcounter.died_counter--; return temp_data; } void lwt_die(void *data) { /* * if the current thread is the joiner of a specific thread, * set this blocked thread active */ if(lwt_head->target != LWT_NULL)// && lwt_head->target->status == LWT_BLOCKED) { gcounter.blocked_counter--; lwt_head->target->status = LWT_ACTIVE; gcounter.runable_counter++; /*lwt_snd((lwt_chan_t)lwt_head->target->data,(void *)1); lwt_chan_deref((lwt_chan_t)lwt_head->target->data);*/ } lwt_head->return_val = (void *)data; gcounter.runable_counter--; if(lwt_head->lwt_nojoin) { struct _lwt_t tmp; lwt_t tmp_curr = lwt_head; lwt_head = ps_list_next_d(lwt_head); ps_list_rem_d(tmp_curr); kfree((void *)&tmp,sizeof(struct _lwt_t) + STACK_SIZE); __lwt_dispatch(tmp_curr,lwt_head); } else { lwt_head->status = LWT_DEAD; gcounter.died_counter++; __lwt_schedule(); } } int lwt_yield(lwt_t lwt) { if(lwt == NULL) { __lwt_schedule(); } else if (lwt->status == LWT_ACTIVE) { lwt_t tmp_curr = lwt_head; lwt_head = lwt; __lwt_dispatch(tmp_curr,lwt_head); } return -1; } lwt_t lwt_current(void) { return lwt_head; } /* * gets the thread id of a specified thread. * returns -1 if the thread not exists */ int lwt_id(lwt_t lwt) { assert(lwt); if (!lwt) { return -1; } return lwt->id; } /* * get the number of threads that are either runnable, * blocked (i.e. that are joining, on a lwt that hasn't died), * or that have died */ int lwt_info(lwt_info_t t) { switch (t) { case LWT_INFO_NTHD_RUNNABLE: return gcounter.runable_counter; case LWT_INFO_NTHD_BLOCKED: return gcounter.blocked_counter; case LWT_INFO_NTHD_ZOMBIES: return gcounter.died_counter; case LWT_INFO_NCHAN: return gcounter.nchan_counter; case LWT_INFO_NSNDING: return gcounter.nsnding_counter; case LWT_INFO_NRCVING: return gcounter.nrcving_counter; default: return -1; } } void __lwt_start() { void *return_val = lwt_head->fn(lwt_head->data); lwt_die(return_val); } void __lwt_schedule(void) { lwt_t temp; temp = lwt_head; lwt_head = ps_list_next_d(lwt_head); while(lwt_head->status != LWT_ACTIVE) { lwt_head = ps_list_next_d(lwt_head); } if (temp != lwt_head) { __lwt_dispatch(temp, lwt_head); } return; } static inline void __lwt_dispatch(lwt_t curr, lwt_t next) { __asm__ __volatile__( "pushal\n\t" //PUSH ALL other register "movl $1f, (%%eax)\n\t" //save IP to TCB "movl %%esp, (%%ebx)\n\t" //save SP to TCB "movl %%edx, %%esp\n\t" //recover the SP "jmp %%ecx\n\t" //recover the IP "1:" //LABEL "popal" :: "a"(&curr->ip), "b"(&curr->sp), "c"(next->ip), "d"(next->sp) : "cc", "memory"); //for switching back to old thread, nested? return; } /* * Currently assume that sz is always 0. * This function uses malloc to allocate * the memory for the channel. */ lwt_chan_t lwt_chan(int sz) { lwt_chan_t new; assert(sz >= 0); uint size = sizeof(struct lwt_channel) + (sz + 1) * sizeof(void *); new = (lwt_chan_t) kalloc(size); assert(new); new->data_buffer.size = sz + 1; new->data_buffer.start = 0; new->data_buffer.end = 0; new->data_buffer.data = (void*)new+sizeof(struct lwt_channel);//kalloc(new->data_buffer.size * sizeof(void *)); new->snd_cnt = 0; new->snd_thds = NULL; new->id = gcounter.nchan_id++; gcounter.nchan_counter++; new->rcv_thd = lwt_head; new->iscgrp = 0; new->cgrp = NULL; return new; } /* * Deallocate the channel if no threads still * have references to the channel. */ void lwt_chan_deref(lwt_chan_t c) { assert(c); if(c->snd_cnt > 0) { c->snd_cnt--; } else if (c->rcv_thd == lwt_head && c->rcv_thd->status == LWT_ACTIVE) { gcounter.nchan_counter--; c->rcv_thd = NULL; //will also set "rcv_thd" as NULL int size = sizeof(struct lwt_channel) + c->data_buffer.size * sizeof(void*); // kfree((void*)c->data_buffer.data,c->data_buffer.size * sizeof(void*)); kfree((void*)c,size);//sizeof(struct lwt_channel)); } } int lwt_snd(lwt_chan_t c, void *data) { //data being NULL or rcv being null is illegal assert(data && c); /* if (c->rcv_thd == NULL) { return -1; }*/ gcounter.nsnding_counter++; gcounter.runable_counter--; if(c->data_buffer.size == 1) { //block current thread while (c->rcv_thd->status == LWT_ACTIVE)//blocked == 0) { lwt_yield(LWT_NULL); } //if there is node that is new added without filling the data,fill it clist_t new_clist; uint size = sizeof(struct clist_head); new_clist = (clist_t) kalloc(size); assert(new_clist); new_clist->thd = lwt_head; new_clist->data = data; if(c->snd_thds == NULL) { ps_list_init_d(new_clist); c->snd_thds = new_clist; } else { ps_list_add_d(ps_list_prev_d(c->snd_thds),new_clist); } } else { while((c->data_buffer.end + 1)%c->data_buffer.size == c->data_buffer.start) { lwt_yield(LWT_NULL); } c->data_buffer.data[c->data_buffer.end] = data; c->data_buffer.end = (c->data_buffer.end + 1)%c->data_buffer.size; } //add the event if (c->iscgrp && (c->data_buffer.start + 1)%c->data_buffer.size == c->data_buffer.end) { if(c->cgrp->events == NULL) { ps_list_init_d(c); c->cgrp->events = c; } else { ps_list_add_d(ps_list_prev_d(c->cgrp->events),c); } } c->rcv_thd->status = LWT_ACTIVE; gcounter.nsnding_counter--; gcounter.runable_counter++; return 0; } void *lwt_rcv(lwt_chan_t c) { assert(c != NULL); void* temp; /* if (c->rcv_thd != lwt_head) { return NULL; }*/ c->rcv_thd->status = LWT_WAITING;//blocked = 1; gcounter.nrcving_counter++; gcounter.runable_counter--; if(c->data_buffer.size == 1) { //if snd_thds is null, block the reciever to wait for sender while (c->snd_thds == NULL)//ps_list_head_empty(&c->snd_head)) { lwt_yield(LWT_NULL); } temp = c->snd_thds->data; if(ps_list_singleton_d(c->snd_thds)) { assert(c->snd_thds); kfree((void *)c->snd_thds,sizeof(struct clist_head)); c->snd_thds = NULL; } else { clist_t tmp = c->snd_thds; c->snd_thds = ps_list_next_d(tmp); ps_list_rem_d(tmp); assert(c->snd_thds); kfree((void *)c->snd_thds,sizeof(struct clist_head)); } } else { //if empty, block rcv, remove c from ready queue while(c->data_buffer.start == c->data_buffer.end) { lwt_yield(LWT_NULL); } temp = c->data_buffer.data[c->data_buffer.start]; c->data_buffer.start = (c->data_buffer.start + 1)%c->data_buffer.size; } if (c->iscgrp && c->data_buffer.start == c->data_buffer.end) { if(c->cgrp->events != NULL) { if(ps_list_singleton_d(c)) { c->cgrp->events = NULL; } else { c->cgrp->events = ps_list_next_d(c); ps_list_rem_d(c); } } } gcounter.nrcving_counter--; gcounter.runable_counter++; c->rcv_thd->status = LWT_ACTIVE; //remove the event return temp; } /* * a channel is sent over the channel (sending is sent over c). * This is used for reference counting to determine * when to deallocate the channel. */ int lwt_snd_chan(lwt_chan_t c, lwt_chan_t sending) { //data being NULL or rcv being null is illegal assert(c && sending); sending->snd_cnt++; sending->rcv_thd = lwt_head; return lwt_snd(c,sending); } /* Same as for lwt rcv except a channel is sent over the channel.*/ lwt_chan_t lwt_rcv_chan(lwt_chan_t c) { return lwt_rcv(c); } /* * This function, like lwt create, creates a new thread. * The difference is that instead of passing a void * to that new thread, * it passes a channel. */ lwt_t lwt_create_chan(lwt_chan_fn_t fn, lwt_chan_t c, lwt_flags_t flag) { assert(fn); assert(c); lwt_t lwt = lwt_create((lwt_fn_t)fn,(void*)c,flag); c->snd_cnt++; return lwt; } lwt_cgrp_t lwt_cgrp(void) { lwt_cgrp_t new; uint size = sizeof(struct cgroup); new = (lwt_cgrp_t) kalloc(size); assert(new); new->n_chan = 0; new->events = NULL; return new; } int lwt_cgrp_free(lwt_cgrp_t cgrp) { assert(cgrp); if (NULL == cgrp->events && 0 == cgrp->n_chan) { kfree((void *)cgrp,sizeof(struct cgroup)); return 0; } return -1; } int lwt_cgrp_add(lwt_cgrp_t cgrp, lwt_chan_t c) { if (c->iscgrp == 1) return -1; //A channel can be added into only one group cgrp->n_chan++; c->iscgrp = 1; c->cgrp = cgrp; return 0; } int lwt_cgrp_rem(lwt_cgrp_t cgrp, lwt_chan_t c) { assert(!c->snd_thds); if (c->snd_thds != NULL || c->data_buffer.start != c->data_buffer.end) return 1; //cgrp has a pending event if(cgrp != c->cgrp) return -1; cgrp->n_chan--; c->iscgrp = 0; c->cgrp = NULL; return 0; } lwt_chan_t lwt_cgrp_wait(lwt_cgrp_t cgrp) { lwt_head->status = LWT_WAITING; while (cgrp->events == NULL) { lwt_yield(NULL); } lwt_head->status = LWT_ACTIVE; return cgrp->events; } void lwt_chan_mark_set(lwt_chan_t c, void *data) { c->mark = data; return; } void *lwt_chan_mark_get(lwt_chan_t c) { return c->mark; } lwt_t __lwt_init(lwt_fn_t fn) { return NULL; } /* void *__lwt_kthd_entry(void* data) { kthd_parm_t parm = (kthd_parm_t) data; __init_thread_head(); parm->lwt = lwt_create_chan((lwt_chan_fn_t)parm->fn,parm->c, LWT_NOJOIN); while(1) { lwt_yield(NULL); sl_thd_yield(0); } } int lwt_kthd_create(lwt_fn_t fn, lwt_chan_t c) { kthd_parm_t parm = (kthd_parm_t)kalloc(sizeof(struct __kthd_parm_t)); assert(parm); parm->fn = fn; parm->c = c; return (sl_thd_alloc(fn,c) == NULL) - 1; }*/ <file_sep>/scheddev/include/lwt.h #include"ps_list.h" #ifndef _LWT_H #define _LWT_H #ifndef DEBUG #define DEBUG(format,...) printf("[DEBUG INFO]: FILE %s, LINE %d"format"\n",__FILE__,__LINE__, ##__VA_ARGS__) #endif #ifndef STACK_SIZE #define STACK_SIZE 3074 #endif #define RING_SIZE 1024 #define LWT_NULL NULL typedef unsigned long ulong; typedef unsigned int uint; typedef unsigned short ushort; typedef unsigned char uchar; typedef void *(*lwt_fn_t) (void *); typedef enum { LWT_INFO_NTHD_RUNNABLE, LWT_INFO_NTHD_BLOCKED, LWT_INFO_NTHD_ZOMBIES, LWT_INFO_NCHAN, LWT_INFO_NSNDING, LWT_INFO_NRCVING, } lwt_info_t; typedef enum { LWT_ACTIVE, LWT_BLOCKED, LWT_DEAD, LWT_WAITING, }lwt_status_t; typedef enum { LWT_JOIN, LWT_NOJOIN, }lwt_flags_t; typedef struct _lwt_t { ulong ip; ulong sp; uint id; lwt_status_t status; lwt_flags_t lwt_nojoin; lwt_fn_t fn; // struct sl_thd* kthd; uint tid; void* data; void *return_val; struct _lwt_t *joiner; struct _lwt_t *target; struct ps_list list; }*lwt_t; typedef struct _global_counter_t { /*auto-increment counter for thread*/ uint lwt_count; /*counter for runable thread*/ uint runable_counter; /*counter for blocked thread*/ uint blocked_counter; /*counter for died thread*/ uint died_counter; /*counter for number of channels that are active*/ uint nchan_counter; /*(number of threads blocked sending on channels)*/ uint nsnding_counter; /*(number of threads blocked receiving on channels)*/ uint nrcving_counter; uint nchan_id; }global_counter_t; typedef struct ring_buffer { int size; int start; int end; void** data; } ring_buffer; typedef struct cgroup { int id; int n_chan; //number of channels in the group //the channel that ready to receive, point to the head of the event queue struct lwt_channel *events; // struct ps_list list; } cgroup, *lwt_cgrp_t; typedef struct clist_head { void* data; lwt_t thd; struct ps_list list; } clist_head, *clist_t; typedef struct lwt_channel { int id; /* channel's id*/ /* sender’s data */ int snd_cnt; /* number of sending threads */ clist_t snd_thds; /* receiver’s data */ int rcv_blocked; lwt_t rcv_thd; /* the receiver */ void *mark; /* chan's data */ int iscgrp; //check if it added to a group lwt_cgrp_t cgrp; // belongs to which group // int size; // size of the buffer ring_buffer data_buffer; struct ps_list list; } lwt_channel, *lwt_chan_t; typedef struct __kthd_parm_t { struct sl_thd* kthd; lwt_t lwt; lwt_fn_t fn; lwt_chan_t c; }*kthd_parm_t; typedef void *(*lwt_chan_fn_t)(lwt_chan_t); /* head of the queue of thread*/ lwt_t lwt_head; global_counter_t gcounter; lwt_t lwt_create(lwt_fn_t fn, void *data, lwt_flags_t flags); void *lwt_join(lwt_t thread); void lwt_die(void *data); int lwt_yield(lwt_t lwt); lwt_t lwt_current(void); int lwt_id(lwt_t lwt); int lwt_info(lwt_info_t t); void __lwt_start(); void *__lwt_stack_get(void); lwt_chan_t lwt_chan(int sz); void lwt_chan_deref(lwt_chan_t c); int lwt_snd(lwt_chan_t c,void *data); void *lwt_rcv(lwt_chan_t c); int lwt_snd_chan(lwt_chan_t c,lwt_chan_t sending); lwt_chan_t lwt_rcv_chan(lwt_chan_t c); lwt_t lwt_create_chan(lwt_chan_fn_t fn, lwt_chan_t c, lwt_flags_t flag); lwt_cgrp_t lwt_cgrp(void); int lwt_cgrp_free(lwt_cgrp_t cgrp); int lwt_cgrp_add(lwt_cgrp_t cgrp, lwt_chan_t c); int lwt_cgrp_rem(lwt_cgrp_t cgrp, lwt_chan_t c); lwt_chan_t lwt_cgrp_wait(lwt_cgrp_t cgrp); void lwt_chan_mark_set(lwt_chan_t c, void *data); void *lwt_chan_mark_get(lwt_chan_t); int lwt_kth_create(lwt_fn_t fn, lwt_chan_t c); int lwt_snd_thd(lwt_chan_t c,lwt_t sending); lwt_t lwt_rcv_thd(lwt_chan_t c); #endif <file_sep>/include/kalloc.h #ifndef KALLOC_H #define KALLOC_H #include <stdio.h> #include <stdlib.h> #include <assert.h> #include <string.h> /* Modify to meet your requirement, if necessary */ #ifndef PAGESIZE #define PAGESIZE (10 * 1024 * 1024) #endif void kinit(void); /* init the pool, necessary*/ char* kalloc(int n); void kfree(char *v, int len); #endif /* KALLOC_H */ <file_sep>/README.md # Homework 1: Lightweight Threads V1 First Homework on LWT Thread creation and deletion. - Find the homework specification in `csci_6411_lwt.pdf` - Find the dispatch function's prototype in `lwt_dispatch.h`, and the implementation in `lwt_dispatch.o`. ## Deadline This assignment is due on Monday, February 6th at midnight. Your last commit before this deadline counts as your submission. ## Using `git` Please remember to make many small commits. I want to see a story of progress through your commits, not a single large dump of a bunch of code. This will be good practice in how to use version control systems properly. For the most part, you'll find that 99% of the time, the following commands are sufficient - `git commit -a` - `git diff` - `git status` (*always* use this before committing) - `git diff -stat` - `git push` - `git pull` - `git clone` You can learn about each of these using the internet, or `git help X` where `X` is the command portion of the above examples. <file_sep>/TRADEOFF.md # Trade-offs and implementation ## Lwt isolation We create an idle lwt for each kthd, when it is created. This idle lwt can be the head and entry of the lwt queue of this kthd. However, in this condition, if the preemption happens, the lwt_head which is a global variable will be modified, which means when switching back to this kthd, lwt_head may be a lwt of another kthd. So we decided to add critical section to our kthd. ## Inter-kthd Comunication We choose to make the channel support both local and remote communication. When a rcv request is made, if there is no data in the channel, this lwt will block itself to wait for the snd. If it is inner-kthd communication, the performance should be decent. However, if it is inter-kthd communication, many performance will be wasted on context switch. ## Synchronization Since preemption may happen, we need to make sure that global or shared variable like global counter and ring_buffer of each channel should be safely operated, so we add cas to these variable to make sure the security of them. ## Result model name : Intel(R) Core(TM) i5-4258U CPU @ 2.40GHz | | System&Param | context_switch(per thread) | pipe/channel(per thread) | proc/thd_create(per thread) | event_notification(per thread) | |-----|:------------------------------------------:|:------------------------------------:|:-------------------------:|:----------------------------:|:-------------------------------:| | 1 | linux/lmbench(time:ms) | 54.25 (1000threads) | 51.2161(2 process) | 188.2574 | 1.2477(100files) | | 2 | lwt_local hw3 | 43 | 150 | 233 | 2000 | | 3 | lwt_local | 5071 | 932 | 7290 | 74490 | | 4 | lwt_remote | 822071 | 415394 | 136831 | 730890 | # Golang ## Creating goroutines With golang, people can just add a “go” before that function to make it a goroutine, and then it will be scheduled. The goroutinue is pretty light-weight, since it just have a 4K stack ,a ip and a sp, which are very similar to our lwt. However, in contrast to our lwt library, it is easier to create a light weight thread using golang. ## Using channel for communication After searching the information about golang, we found channel and goroutine can be the most significant features of golang. In general, the channel share the same design ideas with our lwt_channel. When the buffer size of the channel is 0, communication between threads will be synchronous. If the size is larger than 0, the sender will not be blocked until the buffer is full. But it is easier to use the channel in go language. For example, “msg := <-c” is the receive code, which looks quite short and clear. ## Multi-wait Although we carefully searched the Internet about the channel group in golang, we didn’t find any information about this. Firstly, we just found the waitgroup function, which is used to block the program to wait for goroutines. Then, we found the select statement. If no channels are readly, the statement blocks until one becomes available. If more than one of the channels are ready, it just randomly picks a channel to receive. This looks really our implementation of channel group. However, it is still slightly different. We pick the event following the “FIFO” rules. Not only that, channels in the select statement are fixed, and our cgrp can dynamically add and remove channels. ## Concurrency In golang scheduler, we have three components, which are M, P, G. M,P,G represent kernel thread, context, and goroutine respectively. The number of P controls the degree of concurrency. Each P maintains a goroutine queue. And the G runs on the M. If the M0 does a syscall and is blocked, The P of M0 will move to another M like M1, which could be an idle M or just be created. When M0 woke up, it will try to get a P from other M. If it doesn’t get the P, it will put its goroutine in a global runqueue, and then get back to the thread pool. P will periodically check the global runqueue to make sure these goroutines can be executed. Decision about preemption can be made by the sysmon() background thread. This function will periodically do epoll operation and check if each P runs for too long. It it find a P has been in Psyscal state for more a sysmon time period and there is runnable task, it will switch P. If it find a P in Prunning state running for more than 10ms, it will set the stackguard of current G of P StackPreempt to let the G know it should give up the running opportunity. <file_sep>/scheddev/kalloc.c #include "include/kalloc.h" struct cos_compinfo *ci; struct run { struct run *next; int len; }*freelist; void kinit(void) { char *start,*t,*prev,*cur; int i; ci = cos_compinfo_get(cos_defcompinfo_curr_get()); start = cos_page_bump_alloc(ci); assert(start); prev = start; for(i = 1; i < PAGENUM; i++) { t = cos_page_bump_alloc(ci); assert(t && t == prev + 4096); prev = t; } memset(start,0,PAGESIZE); kfree(start, PAGESIZE); } void kfree(char *v, int len) { struct run *r, *rend, **rp, *p, *pend; assert(len > 0 && len <= PAGESIZE); /* It's supposed to reset memory segement here * But perf reduces quite a lot like 60 => 600. * So I gave up. */ //memset(v, 0, len); p = (struct run*)v; pend = (struct run*)(v + len); for(rp=&freelist; (r=*rp) != 0 && r <= pend; rp=&r->next){ rend = (struct run*)((char*)r + r->len); /* p next to r: replace r with p */ if(pend == r){ p->len = len + r->len; p->next = r->next; *rp = p; goto ret; } /* r next to p: replace p with r */ if(rend == p){ r->len += len; if(r->next && r->next == pend){ r->len += r->next->len; r->next = r->next->next; } goto ret; } } /* Not in the list * Suppose to be return by malloc in kalloc() * Append it to the list */ p->len = len; p->next = r; *rp = p; ret: return; } char* kalloc(int n) { char *p; struct run *r, **rp; assert(n <= PAGESIZE && n > 0); for(rp=&freelist; (r=*rp) != 0; rp=&r->next){ if(r->len == n){ *rp = r->next; return (char*)r; } if(r->len > n){ r->len -= n; p = (char*)r + r->len; return p; } } /* out of memory, malloc new segement * But it shouldn't happen often */ kfree(cos_page_bump_alloc(ci),4096); printc("rare condition\n"); return kalloc(n);//cos_alloc_page(); } <file_sep>/scheddev/unit_schedlib.c /* * Copyright 2016, <NAME> and <NAME>, GWU, <EMAIL>. * * This uses a two clause BSD License. */ #include <stdio.h> #include <string.h> #include <cos_component.h> #include <cobj_format.h> #include <cos_defkernel_api.h> #include "include/lwt.h" #include <sl.h> #undef assert #define assert(node) do { if (unlikely(!(node))) { debug_print("assert error in @ "); *((int *)0) = 0; } } while (0) #define PRINT_FN prints #define debug_print(str) (PRINT_FN(str __FILE__ ":" STR(__LINE__) ".\n")) #define BUG() do { debug_print("BUG @ "); *((int *)0) = 0; } while (0); #define SPIN(iters) do { if (iters > 0) { for (; iters > 0 ; iters -- ) ; } else { while (1) ; } } while (0) static void cos_llprint(char *s, int len) { call_cap(PRINT_CAP_TEMP, (int)s, len, 0, 0); } int prints(char *s) { int len = strlen(s); cos_llprint(s, len); return len; } int __attribute__((format(printf,1,2))) printc(char *fmt, ...) { char s[128]; va_list arg_ptr; int ret, len = 128; va_start(arg_ptr, fmt); ret = vsnprintf(s, len, fmt, arg_ptr); va_end(arg_ptr); cos_llprint(s, ret); return ret; } #define N_TESTTHDS 8 #define WORKITERS 10000 void test_thd_fn(void *data) { while (1) { int workiters = WORKITERS * ((int)data); printc("kthd id %d %d %d\n",cos_thdid(), (int)data,workiters); SPIN(workiters); sl_thd_yield(0); } } void test_yields(void) { int i; struct sl_thd *threads[N_TESTTHDS]; union sched_param sp = {.c = {.type = SCHEDP_PRIO, .value = 10}}; for (i = 0 ; i < /*N_TESTTHDS*/2 ; i++) { threads[i] = sl_thd_alloc(test_thd_fn, (void *)(i + 1)); assert(threads[i]); sl_thd_param_set(threads[i], sp.v); } } void test_high(void *data) { struct sl_thd *t = data; while (1) { sl_thd_yield(t->thdid); printc("h"); } } void test_low(void *data) { while (1) { int workiters = WORKITERS * 10; SPIN(workiters); printc("l"); } } void test_blocking_directed_yield(void) { struct sl_thd *low, *high; union sched_param sph = {.c = {.type = SCHEDP_PRIO, .value = 5}}; union sched_param spl = {.c = {.type = SCHEDP_PRIO, .value = 10}}; low = sl_thd_alloc(test_low, NULL); high = sl_thd_alloc(test_high, low); sl_thd_param_set(low, spl.v); sl_thd_param_set(high, sph.v); } void fn(void) { int i; for(i = 0; i < 100; i++) { //printc("lwt curr id %d\n",lwt_current()->id); printc("%d ",i+1); lwt_yield(NULL); } } void fn_cpy(void) { int i; for(i = 0; i < 100; i++) { //printc("lwt curr id %d\n",lwt_current()->id); printc("%d ",100 - i); lwt_yield(NULL); } } void test_remote_yield() { lwt_chan_t c1 = lwt_chan(0); lwt_chan_t c2 = lwt_chan(0); // lwt_chan_t c3 = lwt_chan(0); assert(lwt_kthd_create(fn,c1) == 0); assert(lwt_kthd_create(fn_cpy,c2) == 0); // assert(lwt_kthd_create(fn,c3) == 0); } void fn2(lwt_chan_t to) { lwt_chan_t from; int i; from = lwt_chan(0); lwt_snd_chan(to, from); assert(from->snd_cnt); for (i = 0 ; i < 10000 ; i++) { lwt_snd(to, (void*)1); assert(2 == (int)lwt_rcv(from)); } lwt_chan_deref(from); } void fn1(lwt_chan_t from) { lwt_chan_t to; int i; unsigned long long start, end; to = lwt_rcv_chan(from); assert(to->snd_cnt); rdtscll(start); for (i = 0 ; i < 10000 ; i++) { assert(1 == (int)lwt_rcv(from)); lwt_snd(to, (void*)2); } lwt_chan_deref(to); rdtscll(end); printc("[PERF] %5lld <- snd+rcv (buffer size %d)\n", (end-start)/(10000*2), from->data_buffer.size - 1); lwt_join(to->rcv_thd); } void test_remote_communication(int sz) { lwt_chan_t c1 = lwt_chan(sz); assert(lwt_kthd_create(fn1,c1) == 0); assert(lwt_kthd_create(fn2,c1) == 0); } void fn_print(void* data) { printc("[PRINT] target kid %d self kid %d lwt id%d\n",data,lwt_head->tid,lwt_head->id); assert(data == lwt_head->tid); } void fn_rcv_thd(lwt_chan_t from) { int i = 0; while(i < 10) { lwt_t lwt = lwt_rcv_thd(from); assert(lwt); i++; } } void fn_snd_thd(lwt_chan_t to) { int i = 0; while(i < 10) { lwt_t lwt = lwt_create((lwt_fn_t)fn_print,(void*)to->rcv_thd->tid,LWT_NOJOIN); lwt_snd_thd(to,lwt); i++; } lwt_t lwt = lwt_create((lwt_fn_t)fn_print,(void*)lwt_head->tid,LWT_NOJOIN); } void test_thd_snd() { lwt_chan_t c1 = lwt_chan(0); assert(lwt_kthd_create(fn_rcv_thd,c1) == 0); assert(lwt_kthd_create(fn_snd_thd,c1) == 0); } void * fn_asnd(lwt_chan_t to) { int i; for (i = 0 ; i < 100 ; i++) lwt_snd(to, (void*)(i+1)); lwt_chan_deref(to); return NULL; } void fn_arcv(lwt_chan_t from) { int i; unsigned long long start, end; assert(LWT_ACTIVE == lwt_current()->status); assert(from); rdtscll(start); for (i = 0 ; i < 100 ; i++) assert(i+1 == (int)lwt_rcv(from)); rdtscll(end); printc("[PERF] %5lld <- asynchronous snd->rcv (buffer size %d)\n", (end-start)/(100*2), from->data_buffer.size - 1); lwt_chan_deref(from); } void test_remote_asy(int chsz) { lwt_chan_t c = lwt_chan(chsz); assert(lwt_kthd_create(fn_arcv,c) == 0); assert(lwt_kthd_create(fn_asnd,c) == 0); } void* fn_grp_snd(void *d) { assert(d); int i; for (i = 0 ; i < 10000 ; i++) { if ((i % 7) == 0) { int j; for (j = 0 ; j < (i % 8) ; j++) lwt_yield(LWT_NULL); } lwt_snd((lwt_chan_t)d, ((lwt_chan_t)d)->id); } } void* fn_multisend(lwt_chan_t c) { int i; lwt_chan_t ct; for(i = 0; i < 30; i++) { ct = lwt_rcv_chan(c); lwt_create_chan((lwt_chan_fn_t)fn_grp_snd,ct,LWT_NOJOIN); } lwt_yield(LWT_NULL); return NULL; } void* fn_multiwait(lwt_chan_t c) { int i; lwt_chan_t *cs = (lwt_chan_t*)kalloc(sizeof(lwt_chan_t)*10); lwt_cgrp_t g; unsigned long long start, end; g = lwt_cgrp(); assert(g); for(i = 0; i < 10; i++) { cs[i] = lwt_chan(0); lwt_chan_mark_set(cs[i], (cs[i])->id); lwt_snd_chan(c,cs[i]); assert(0 == lwt_cgrp_add(g, cs[i])); } assert(lwt_cgrp_free(g) == -1); rdtscll(start); for(i = 0 ; i < 10000 * 10; i++) { lwt_chan_t c; int r; c = lwt_cgrp_wait(g); assert(c); r = (int)lwt_rcv(c); assert(r == (int)lwt_chan_mark_get(c)); } rdtscll(end); printc("[PERF] %5lld <- multiwait (group size %d)\n", (end-start)/(10000*10), 100); for(i = 0 ; i < 10; i++) { lwt_cgrp_rem(g, cs[i]); lwt_chan_deref(cs[i]); } assert(0 == lwt_cgrp_free(g)); return NULL; } void test_kthd_multiwait() { lwt_chan_t c = lwt_chan(0); assert(0 == lwt_kthd_create((lwt_fn_t)fn_multisend, c)); assert(0 == lwt_kthd_create((lwt_fn_t)fn_multiwait, c)); } void* fn_record(void) { unsigned long long start, end; rdtscll(start); lwt_yield(NULL); rdtscll(end); printc("[PERF] %5lld <- thd_yield in lwt\n", (end-start)/11); } void* fn_nulll(void) {lwt_yield(NULL);} void test_kthd_create(void) { int i; unsigned long long start, end; lwt_chan_t c = lwt_chan(0); rdtscll(start); for (i = 0 ; i < 10 ; i++){ lwt_kthd_create(fn_nulll, c, LWT_NOJOIN); } rdtscll(end); printc("[PERF] %5lld <- thd_create in lwt\n", (end-start)/10); } void test_kthd_yield(void) { int i; lwt_chan_t c = lwt_chan(0); lwt_kthd_create(fn_record, c, LWT_NOJOIN); for (i = 0 ; i < 10 ; i++){ lwt_kthd_create(fn_nulll, c, LWT_NOJOIN); } } void cos_init(void) { struct cos_defcompinfo *defci = cos_defcompinfo_curr_get(); struct cos_compinfo *ci = cos_compinfo_get(defci); printc("Unit-test for the scheduling library (sl)\n"); cos_meminfo_init(&(ci->mi), BOOT_MEM_KM_BASE, COS_MEM_KERN_PA_SZ, BOOT_CAPTBL_SELF_UNTYPED_PT); cos_defcompinfo_init(); sl_init(); kinit(); // test_yields(); // test_blocking_directed_yield(); // maintest(); // test_remote_yield(); // test_remote_communication(0); // test_remote_communication(1); // test_remote_communication(4); // test_remote_communication(16); // test_remote_communication(64); // test_thd_snd(); // test_remote_asy(10); test_kthd_multiwait(); // test_kthd_yield(); // test_kthd_create(); sl_sched_loop(); printc("testfinished\n"); assert(0); return; }
62a06c016487e07665bbd114d427cd060070dd83
[ "Markdown", "C" ]
9
C
GWU-Advanced-OS/lwt-v1-group-name
3d6e39adf81e54c90b559349408f6d8bc011e60b
0317a1108ab9a80d2431e2c4fb2b62981814a2df
refs/heads/master
<file_sep>#!/usr/bin/python3 from collections import defaultdict from threading import Thread import collections import os import sys import mido import pickle import json import time import re # TODO: turn off LED, once relevant encoder has been tweaked # TODO: In queueEncoders() freeze ALL encoders until out of tweak mode to prevent unwanted vals being stored # TODO: Un-light pad LEDs once corresponding encoder has been set to lock value # TODO: Create unfreezeAllEncoders() method # TODO: Once all encoders corresponding to stored values have been tweaked, unfreeze all encoders # TODO: Light up pads to indicate which encoders are still to be synced # TODO: (nice to have) Light up pads to indicate encoder values as they are turned (e.g. 8-15: 1 pad lit, 16-23: 2 pads lit...) # TODO: Leave LEDs corresponding to active encoders lit in blue while in 'play mode' (e.g. nothing frozen - something in pending) # TODO: When in calibration mode light up all active (and frozen) encoders in magenta # TODO: What do we do when the encoder happens to already have the right value? # TODO: Configure defaults to be helpful values - e.g. filter cutoff all the way open etc # 29/03: # recap: # the encoders still need to be frozen for channels with pending values to be sync-ed # We can't easily add an 'editable' property to the defaultdict of cc values # so instead perhaps we need a list of pending encoders to be tweaked ######################################################################################### # # # CCPatch - A command line tool to create, save, and load patches of Midi CC Vals # # # # Create a patch: Execute ccpatch.py and tweak knobs # # Save a patch: Send a sysex [7F,7F,06,01] message to ccpatch.py # # Play a patch: Send a sysex [7F,7F,06,02] message to ccpatch.py # # Load a patch: Pass filename to ccpatch.py: # # - Load values into memory # # - Broadcast the values to synths etc # # - Set the values as current for the controller via sysex # # # # Stop: 0x58 Start: 0x59 Cntrl/Seq: 0x5A ExtSync: 0x5B # # Recall: 0x5C Store: 0x5D Shift: 0x5E Chan: 0x5F # # # ######################################################################################### CONTROLLER_DEVICE = "BeatStep" INSTRUMENT_DEVICE = "in_from_ccpatch" RED = 0x01 BLUE = 0x10 MAGENTA = 0x11 OFF = 0x00 STOP = 0x58 START = 0x59 CTRLSEQ = 0x5A EXTSYNC = 0x5B RECALL = 0x5C STORE = 0x5D SHIFT = 0x5E CHAN = 0x5F class CCPatch: curChan = 0x00 curCCMessage = None lastCCMessage = None controllerPort = None instrumentPort = None values = defaultdict(dict) defaultValue = 64 pending = set() controlMap = {0x20:0x0C,0x21:0x0D,0x22:0x0E, 0x24:0x0F,0x25:0x10,0x26:0x11, 0x28:0x12,0x29:0x13,0x2A:0x14, 0x2C:0x15,0x2D:0x16,0x2E:0x17} #print(list(mydict.keys())[list(mydict.values()).index(16)]) # Prints george #controlToEncoder = lambda self,c:c+20 #look encoder up from controller (if it exists) #controlToEncoder = lambda self,c:list(self.controlMap.keys())[list(self.controlMap.values()).index(c)] #encoderToControl = lambda self,c:c-20 encoderToControl = lambda self,e:self.controlMap[e] encoderToPad = lambda self,c:c+0x50 #encoders = range(0x20, 0x30) encoders = (0x20,0x21,0x22, 0x24,0x25,0x26, 0x28,0x29,0x2a, 0x2c,0x2d,0x2e) channels = range(0,15) encodersFrozen = False defaultEncoderVal = 0x40 sysexListeners = {} ccListeners = {} reservedCCs = range(0x34,0x41) defaultVals = { 0x20:64,0x21:127,0x22:0,0x23:0, 0x24:64,0x25:127,0x26:0,0x27:0, 0x28:64,0x29:127,0x2a:0,0x2b:0, 0x2c:64,0x2d:127,0x2e:0,0x2f:0 } padFuncs = {} def controlToEncoder(self,control): if control in self.controlMap.values(): return list(self.controlMap.keys())[list(self.controlMap.values()).index(control)] return 0 def initVals(self): for channel in self.channels: for encoder in self.encoders: self.setCCVal(channel,self.encoderToControl(encoder),self.defaultVals[encoder]) def doInit(self,val): self.init() def init(self): self.initVals() self.queueEncoders() self.freezeAllEncoders() def configure(self): self.padFuncs = { #CTRLSEQ:self.doSomething, EXTSYNC:self.doInit, #RECALL:self.doSomething, STORE:self.toggleFreezeEncoders, SHIFT:self.decrementChan, CHAN:self.incrementChan} mido.set_backend('mido.backends.rtmidi') self.connectController() self.connectInstrument() # Listen for current global chan which will be requested next self.addSysexListener((0xF0,0x00, 0x20, 0x6b, 0x7F, 0x42, 0x02, 0x00, 0x40, 0x06, 0xF7),self.setCurChan) hexGetGlobalChan = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x01, 0x00, 0x40, 0x06] self.sendSysexToController(hexGetGlobalChan) # Beatstep transport stop self.addSysexListener((0xF0,0x7F,0x7F,0x06,0x01,0xF7), self.save) # Beatstep transport start self.addSysexListener((0xF0,0x7F,0x7F,0x06,0x02,0xF7), self.play) self.assignPadFunctions() hexGetGlobalChan = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x01, 0x00, 0x40, 0x06] self.sendSysexToController(hexGetGlobalChan) def assignPadFunctions(self): i = 0 for padData in self.padFuncs.items(): self.setPadToSwitchMode(padData[0]) self.assignControlToPad(padData[0],self.reservedCCs[i]) self.addCCListener((self.reservedCCs[i]),padData[1]) i=i+1 def setPadToSwitchMode(self,pad): self.sendSysexToController([0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x01, pad, 0x08]) def assignControlToPad(self,pad,control): self.sendSysexToController([0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x03, pad, control]) def sendSysexToController(self,sysex): #print(str(sysex)) try: self.controllerPort.send(mido.Message('sysex', data=sysex)) except Exception as e: print("Error sending sysex to device") def sendControlValueToInstrument(self,channel,control,value): #print(str(sysex)) try: self.instrumentPort.send(mido.Message('control_change', channel=channel, control=control, value=value)) except Exception as e: print("Error sending sysex to device") def setCurChan(self,value) : print("Setting channel to: "+str(value)) self.curChan = value[0] def decrementChan(self,value): self.emptyPending() if self.curChan > 0: self.curChan -= 1 hexSetGlobalChan = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x40, 0x06, self.curChan] self.sendSysexToController(hexSetGlobalChan) hexSetChanIndicator = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x10, 0x70+self.curChan, 0x11] self.sendSysexToController(hexSetChanIndicator) print("Decrementing global channel " + str(self.curChan+1)) if self.hasCCVals(self.curChan): self.queueEncoders() self.freezeAllEncoders() def incrementChan(self,value): self.emptyPending() if self.curChan < 15: self.curChan += 1 #else: self.curChan = 0 hexSetGlobalChan = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x40, 0x06, self.curChan] self.sendSysexToController(hexSetGlobalChan) hexSetChanIndicator = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x10, 0x70+self.curChan, 0x11] self.sendSysexToController(hexSetChanIndicator) print("Incrementing global channel " + str(self.curChan+1)) if self.hasCCVals(self.curChan): self.queueEncoders() self.freezeAllEncoders() # Compares sysex commands. Returns either False, or with an array of remaining unmatched bytes from sysex2 # In the case of an exact match, returns an empty list def compareSysex(self,sysex_listener,sysex_message): # results array for return values in sysex message result = [] # either sysex_listener or sysex_message could be longer than the other # if the listener is longer than the message then it won't match # so we may as well return false if len(sysex_listener) > len(sysex_message): return False # if we have an exact match then return an empty list for return vals if sysex_listener == sysex_message: return [] # remove the trailing 0xF7 from sysex_listener, or else it may try to compare it sysex_listener = list(sysex_listener) sysex_listener.remove(0xF7) sysex_listener = tuple(sysex_listener) # if any bytes don't match now up to the length of sysex_listener then it's not a match for i in range(0,len(sysex_listener)): if sysex_listener[i] != sysex_message[i]: return False # loop through any remaining message bytes (except the trailing 0xF7), which don't appear in sysex_listener # These are result bytes for i in range(len(sysex_listener),len(sysex_message)): if (sysex_message[i] != 0xF7): result.append(sysex_message[i]) return result def processCCListeners(self,message): for cc in self.ccListeners: if cc == message.control: self.ccListeners[cc](message.value) def processSysexListeners(self,message): for sysex in self.sysexListeners: values = self.compareSysex(sysex,message.bytes()) if values != False : if len(values) > 0: self.sysexListeners[sysex](values) else: self.sysexListeners[sysex]() def addSysexListener(self,message,function): #print("registering "+str(message)) self.sysexListeners[message] = function def addCCListener(self,control,function): #print("registering "+str(control)) self.ccListeners[control] = function def keyExists(self,key): return key in self.values.keys() def getPortName(self,pattern): for portName in mido.get_input_names()+mido.get_output_names(): if re.search(pattern,portName): return portName def cleanName(self,name): return name[:name.rfind(' ')] def connectController(self): print("Attempting to connect to " + CONTROLLER_DEVICE + "...") try: device = self.getPortName(CONTROLLER_DEVICE) self.controllerPort = mido.open_ioport(device, callback=lambda m, cn=self.cleanName(device): self.onMessage(cn, m)) print("Successfully connected to " + device) except Exception as e: print('Unable to open MIDI ports: {}'.format(CONTROLLER_DEVICE), file=sys.stderr) def connectInstrument(self): print("Attempting to connect to " + INSTRUMENT_DEVICE + "...") try: device = self.getPortName(INSTRUMENT_DEVICE) self.instrumentPort = mido.open_output(device) print("Successfully connected to " + device) except Exception as e: print('Unable to open MIDI output: {}'.format(INSTRUMENT_DEVICE), file=sys.stderr) def freezeEncoder(self,encoder,value): #print("Freezing encoder: "+str(encoder)+", value: "+str(value)) minVal = value maxVal = value if value < 127: minVal = value maxVal = value+1 else: minVal = value-1 maxVal = value hexSetMin = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x04, encoder, minVal] hexSetMax = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x05, encoder, maxVal] try: self.controllerPort.send(mido.Message('sysex', data=hexSetMin)) self.controllerPort.send(mido.Message('sysex', data=hexSetMax)) except Exception as e: print(str(hexSetMin)) print(str(hexSetMax)) print("Error sending sysex to device") def unfreezeEncoder(self,encoder): #print("Unfreezing controller: "+str(encoder)) hexSetMin = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x04, encoder, 0] hexSetMax = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x05, encoder, 127] try: self.controllerPort.send(mido.Message('sysex', data=hexSetMin)) self.controllerPort.send(mido.Message('sysex', data=hexSetMax)) except Exception as e: print("Error sending sysex to device") def toggleFreezeEncoders(self,val): if self.encodersFrozen: self.unfreezeAllEncoders() else: self.queueEncoders() self.freezeAllEncoders() # freeze all encoders, regardless of whether the corresponding control has a stored value def freezeAllEncoders(self): print("Freezing all encoders") for encoder in self.encoders: control = self.encoderToControl(encoder) value = self.getCCVal(self.curChan, control) pad = self.encoderToPad(encoder) self.freezeEncoder(encoder,value) self.encodersFrozen = True self.refreshLEDs() def unfreezeAllEncoders(self): print("Unfreezing all encoders") for encoder in self.encoders: self.unfreezeEncoder(encoder) self.encodersFrozen = False self.emptyPending() self.refreshLEDs() def emptyPending(self): self.pending = set() def queueEncoders(self): for channeldata in self.values.items(): #print(channeldata) # get the values for current (probably new) channel if channeldata[0] == self.curChan: for controldata in channeldata[1].items(): control = int(controldata[0]) value = int(controldata[1]) encoder = self.controlToEncoder(control) if encoder > 0: pad = self.encoderToPad(encoder) self.pending.add(encoder) def padLED(self, targetPad, color): hexSetEncoderIndicator = [0x00, 0x20, 0x6B, 0x7F, 0x42, 0x02, 0x00, 0x10, targetPad, color] self.sendSysexToController(hexSetEncoderIndicator) #self.sendSysexToController(hexSetEncoderIndicator) def load(self,filename): print("Loading patch file "+filename) success = False if os.path.isfile(filename): #try: with open(filename) as json_file: dict = json.load(json_file) self.values = defaultdict(defaultdict,dict) success = True #except: # print("Error loading patch file: "+filename) else: print("Patch file "+filename+" does not exist") if (success): self.queueEncoders() self.freezeEncoders() def save(self): filename = "patch-"+time.strftime("%Y%m%d%H%M")+".json" try: with open(filename, 'w') as f: json.dump(self.values, f) except: print("Error saving patch file") return print("Saved patch file "+filename+" to file...") def play(self): for channeldata in self.values.items(): for controldata in channeldata[1].items(): control = int(controldata[0]) value = int(controldata[1]) encoder = self.controlToEncoder(control) if encoder > 0: pad = self.encoderToPad(encoder) self.sendControlValueToInstrument(channeldata[0],control,value) self.padLED(pad,RED) def onMessage(self, name, message): if message.type not in ['control_change','sysex']: return if message.type == 'control_change': self.processCCListeners(message) self.lastCCMessage = None self.curCCMessage = (name, message.channel, message.control, message.value) # only listen to new, unreserved CCs on the current channel if self.curCCMessage != self.lastCCMessage and message.channel == self.curChan and message.control not in self.reservedCCs: print(message) if len(self.pending) == 0: #print("setting value to: "+str(message.value)) self.setCCVal(self.curChan,message.control,message.value) self.lastCCMessage = self.curCCMessage else: encoder = self.controlToEncoder(message.control) print(str(encoder)) if encoder > 0: self.removeFromPendingIfCalibrated(encoder, message.value) #self.removeFromPendingIfCalibrated(self.controlToEncoder(message.control), message.value) elif message.type == 'sysex': self.processSysexListeners(message) else: print(message) thread = Thread(target = self.refreshLEDs) thread.start() #self.refreshLEDs() # Check to see if control is pending calibration, if it's value has been correctly calibrated # and if so, remove it from the pending list and turn off the corresponding pad LED. def removeFromPendingIfCalibrated(self, encoder, value): if encoder in self.pending: if value == self.getCCVal(self.curChan, self.encoderToControl(encoder)): self.pending.remove(encoder) indicatorPad = self.encoderToPad(encoder) return True return False def hasCCVal(self, channel, control): return control in self.values[channel] def hasCCVals(self, channel): return len(self.values[channel]) def getCCVal(self, channel, control): if control in self.values[channel]: return self.values[self.curChan][control] else: return self.defaultEncoderVal def setCCVal(self, channel, control, value): self.values[channel][control] = value def refreshLEDs(self): # sleep 1 sec, or else indicator pads won't stay lit time.sleep(0.25) for encoder in self.encoders: control = self.encoderToControl(encoder) value = self.getCCVal(self.curChan, control) pad = self.encoderToPad(encoder) if encoder in self.pending: self.padLED(pad,MAGENTA) elif self.hasCCVal(self.curChan,control): if self.encodersFrozen: self.padLED(pad,BLUE) else: self.padLED(pad,OFF) else: self.padLED(pad,OFF) patch = CCPatch() patch.configure() patch.init() if len(sys.argv) > 1: patch.load(sys.argv[1]) while True: continue <file_sep># ccpatch A utility for creating, saving, and loading patches of midi controller values
3d283f4755e473bfb87d1c8c5605e2e25b460610
[ "Markdown", "Python" ]
2
Python
dabbingcoders/ccpatch
cf06ee5c7abdfd4a9a08e642fb07676cbe772383
4a77b6e812a1e9f1e724e51da7cc24dbfa68a6d9
refs/heads/master
<repo_name>elzamattam/tourism<file_sep>/html files/thrissur.htm <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=<device-width>, initial-scale=1.0"> <link rel="stylesheet" href="/tourismform/css/districts.css"> <title>Thrissur</title> <h1>Thrissur</h1> </head> <body> <p> Thrissur (formerly Trichur) is a revenue district of Kerala situated in the central part of that state. Spanning an area of about 3,032 km2, Thrissur district is home to over 10% of Kerala's population. Thrissur district is bordered by the districts of Palakkad and Malappuram to the north, and the districts of Ernakulam and Idukki to the south. The Arabian Sea lies to the west and Western Ghats stretches towards the east. Thrissur district was formed on 1 July 1949, with the headquarters at Thrissur City. Thrissur is known as the cultural capital of Kerala, and the land of Poorams. The district is known for its ancient temples, churches, and mosques. Thrissur Pooram is the most colourful temple festival in Kerala. </p> <img src="/tourismform/images/tcr.jpg" alt="Thrissur pooram"> </body> </html><file_sep>/node files/core.js var os = require("os"); //console.log("The current working directory is" + os.homedir()); console.log("The OS is" + os.platform()); const EventEmitter = require("events"); const events = new EventEmitter(); events.on("rains", () => { console.log("It is raining . Take Umbrella"); }); events.on("danger", () => { console.log("Escape!Situation is dangerous"); }); /*Synchronous events.emit("danger"); var fs = require("fs"); var ans = fs.readdirSync("./"); console.log("Answer is " + ans);*/ //Asynchronous var fs = require("fs"); fs.readdir("./", (error, result) => { if (error) console.log("Error occured" + error); else console.log("Answer is" + result); })<file_sep>/html files/malappuram.htm <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link rel="stylesheet" href="/tourismform/css/districts.css"> <title>Malappuram</title> <h1>Malappuram</h1> </head> </head> <body> <p> Malappuram (/mələppurəm/ (About this soundlisten)), located in the southern part of former Malabar district, is a revenue district of the Indian state of Kerala. The city of Malappuram, the district headquarters, gives the district its name. It is the most populous district in Kerala, which is home to about 12.3% of the total population of the state.[6] The district was formed on 16 June 1969 spanning an area of about 3,550 km2 (1,371 sq mi). Today it is the third-largest district in Kerala in terms of area. Malappuram district was carved out by combining some portions of the former Palakkad and Kozhikode districts- Eranad taluk and portions of Tirur taluk in the former Kozhikode district, and portions of Perinthalmanna taluk and Ponnani taluk in the former Palakkad district (before 1969). </p> <img src="/tourismform/images/mal.jpg" alt="Malappuram kottakkunnu"> </body> </html><file_sep>/node files/http.js /*var http = require("http"); var server = http.createServer(function(req, res) { res.write("Welcome to the server"); res.end(); }); server.listen(3210);*/ var server=http.createServer(function(req,res){ if(req.url==) })<file_sep>/node files/node.js /*function greetings(name) { console.log(`Hello ${name}. Welcome to Node.js`); } greetings("Elza"); console.log(`Process Platform:${process.version}`);*/ //console.log("Greetings"); //Global Scope //window.console.log("Browser");//browser environment //globalThis.console.log("Node"); //var name = "Gokul"; //console.log(name); //console.log(global.name); //var chalk = require("chalk"); var messenger = require("./messenger"); messenger.printer("Elza"); //console.log(chalk.blue('Hello world!'));
6cded7b1bf5e166899b4860d590136cc520d2a77
[ "JavaScript", "HTML" ]
5
HTML
elzamattam/tourism
92d194ab21c524cfbf3f2bb78c6fa9a2acb6d1bc
fbee73fcd5671ac04a2a7cb58237ea7d042d569a
refs/heads/master
<file_sep>package com.teguh.liga.repository.local import androidx.lifecycle.LiveData import androidx.room.* import com.teguh.liga.model.Word @Dao interface WordDao { @Query("SELECT * FROM word_table ORDER BY word ASC") fun getAlhpabetizedWords(): LiveData<List<Word>> @Insert(onConflict = OnConflictStrategy.IGNORE) suspend fun insert(word: Word) @Query("DELETE FROM word_table") suspend fun deleteAll() }
74616dcfb624f09e6462421ae83eda2777ce6131
[ "Kotlin" ]
1
Kotlin
teguhsiswanto87/RoomWithView
bf24faa24d5de676381f11c4c605878db6d3edbd
4713a6ee6c4e328d351fc7376481efb48348678b
refs/heads/master
<repo_name>atloZ/KonyvespolcApp<file_sep>/KonyvespolcApp/Konyv.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace KonyvespolcApp { public class Konyv { String konyvNev; int aktualisLap; int maxLap; Boolean aktual; public Konyv(string konyvNev, int aktualisLap, int maxLap, bool aktual) { this.KonyvNev = konyvNev; this.AktualisLap = aktualisLap; this.MaxLap = maxLap; this.Aktual = aktual; } public string KonyvNev { get => konyvNev; set => konyvNev = value; } public int AktualisLap { get => aktualisLap; set => aktualisLap = value; } public int MaxLap { get => maxLap; set => maxLap = value; } public bool Aktual { get => aktual; set => aktual = value; } } } <file_sep>/KonyvespolcApp/Konyvek.cs using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KonyvespolcApp { public static class Konyvek { private static List<Konyv> konyvs = new List<Konyv>(); public static void hozzaAd(ListBox lb, string konyvNev, int aktualisLap, int maxLap, Boolean aktual) { Konyv k = new Konyv(konyvNev, aktualisLap, maxLap, aktual); konyvs.Add(k); lb.Items.Add(konyvNev); } private static void beolvas(ListBox lb, string path) { using (StreamReader sr = new StreamReader(path)) { while (!sr.EndOfStream) { string[] s = sr.ReadLine().Split(';'); hozzaAd(lb, s[0], int.Parse(s[1]), int.Parse(s[2]), Boolean.Parse(s[3])); } sr.Close(); lb.Items.Clear(); } } public static void kiir(ListBox lb, string path) { using (StreamWriter sw = new StreamWriter(path)) { for (int i = 0; i < konyvs.Count; i++) { Boolean select = lb.GetItemText(lb.SelectedItem) != null && lb.GetItemText(lb.SelectedItem) == konyvs[i].KonyvNev ? true : false; sw.WriteLine( konyvs[i].KonyvNev + ";" + konyvs[i].AktualisLap + ";" + konyvs[i].MaxLap + ";" + select); } sw.Close(); } } public static ListBox listBoxFeltolt(ListBox listBox, string path) { beolvas(listBox, path); for (int i = 0; i < konyvs.Count; i++) { listBox.Items.Add(konyvs[i].KonyvNev); } return listBox; } public static int[] aktualMaxLap(ListBox lb) { int[] ketto = new int[2]; for (int i = 0; i < konyvs.Count; i++) { if (lb.GetItemText(lb.SelectedItem) == konyvs[i].KonyvNev) { ketto[0] = konyvs[i].AktualisLap; ketto[1] = konyvs[i].MaxLap; } } return ketto; } public static void selecter(ListBox lb) { for (int i = 0; i < konyvs.Count; i++) { if (lb.GetItemText(lb.SelectedItem) == konyvs[i].KonyvNev) { lb.Items[i] = true; } } } } } <file_sep>/KonyvespolcApp/Form1.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace KonyvespolcApp { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { } private void buttonBetoltes_Click(object sender, EventArgs e) { string file = null; if (openFileDialog1.ShowDialog(this) == DialogResult.OK) { file = openFileDialog1.InitialDirectory + openFileDialog1.FileName; Konyvek.listBoxFeltolt(listBoxKonyvek, file); } Konyvek.selecter(listBoxKonyvek); } private void buttonMentes_Click(object sender, EventArgs e) { if (textBoxAktualLap.Text != "" && textBoxMaxLap.Text != "" && listBoxKonyvek.SelectedItem != null) { string file = null; if (saveFileDialog1.ShowDialog(this) == DialogResult.OK) { file = saveFileDialog1.InitialDirectory + saveFileDialog1.FileName; } Konyvek.kiir(listBoxKonyvek, file); } else { MessageBox.Show("Kihagyott egy mezőt, ne hadjon üres mezőt!"); } } private void buttonHozzaad_Click(object sender, EventArgs e) { if (textBoxAktualLap.Text != "" && textBoxMaxLap.Text != "" && textBoxUjKonyv.Text != "") { Konyvek.hozzaAd( listBoxKonyvek, textBoxUjKonyv.Text, int.Parse(textBoxAktualLap.Text), int.Parse(textBoxMaxLap.Text), false); textBoxAktualLap.Clear(); textBoxMaxLap.Clear(); textBoxUjKonyv.Clear(); } else { MessageBox.Show("üresen hagyott mező!"); } } private void listBoxKonyvek_SelectedIndexChanged(object sender, EventArgs e) { int[] index = Konyvek.aktualMaxLap(listBoxKonyvek); textBoxAktualLap.Text = index[0].ToString(); textBoxMaxLap.Text = index[1].ToString(); } private void textBoxAktualLap_KeyPress(object sender, KeyPressEventArgs e) { if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.')) { e.Handled = true; } } } }
32ccdda210326f45919f6cc57976a6cf4f40fe18
[ "C#" ]
3
C#
atloZ/KonyvespolcApp
10a0a63c25f54b0094aae4f905f6a91eadf865af
810c16a5677959e92d4ee633a1e9c54d92fee6bd
refs/heads/master
<file_sep>//namespace Login{ // Its deprecated function so use module var LoginModule; (function (LoginModule) { // In grouping you need to specify which can be used outside // Use keyword export to allow this function ValidateLogin() { } LoginModule.ValidateLogin = ValidateLogin; function ChangePassword() { } LoginModule.ChangePassword = ChangePassword; //By declaring export you can use it outside var Password = (function () { function Password() { } return Password; }()); LoginModule.Password = <PASSWORD>; })(LoginModule || (LoginModule = {})); // This will give error as namespace is Login //ValidateLogin(); //ChangePassword(); // Access it by namespace / module name which is exported //Login.ValidateLogin(); //SLogin.ChangePassword(); <file_sep>var QueueDemo = (function () { function QueueDemo() { //We can declare array by following methods //list: string[]; // Its only decleared so no memory is assigned to variable list this.list = Array(); } //list_1 = Array<string>(); //list_2 = []; QueueDemo.prototype.add = function (value) { this.list.push(value); }; QueueDemo.prototype["delete"] = function () { return this.list.pop(); }; QueueDemo.prototype.read = function () { for (var i = 0; i < this.list.length; ++i) { console.log(this.list[i]); } }; return QueueDemo; }()); var result = new QueueDemo(); result.add('Mahesh'); console.log('Add operatin executed'); console.log(result.list); result.read(); console.log('Read operatin executed'); console.log(result.list); result["delete"](); console.log('Delete operatin executed'); console.log(result.list); <file_sep>//Include login function By using namespace //<reference path="LoginFunction.ts" /> //Import module by giving name of file LoginFunctionModule //.ts not needed // ./ represents current folder import {} from './LoginFunctionModule' LoginModule.ValidateLogin(); LoginModule.ChangePassword();<file_sep>interface PersonalInfo{ firstName: string lastName: string [otherProperty:string] : any // For optional parameters } function RestParams(n1:string,...n2:string[]){ } RestParams('a','b','c'); function RestaParamInterface(info:PersonalInfo){ console.log(info.firstName); console.log(info.Age); } RestaParamInterface(<PersonalInfo>{ firstName:'Mahesh' ,lastName:'' ,email:'' ,Address:'' ,Age: 30 ,MyAddress:{city:'pune',pincode:111111} }) <file_sep>namespace Login{ // Its deprecated function so use module //module Login{ // module will do same functionality as namespace // In grouping you need to specify which can be used outside // Use keyword export to allow this export function ValidateLogin(){ } export function ChangePassword(){ } //By declaring export you can use it outside export class Password{ } } // This will give error as namespace is Login //ValidateLogin(); //ChangePassword(); // Access it by namespace / module name which is exported Login.ValidateLogin(); Login.ChangePassword(); <file_sep>class QueueDemo{ //We can declare array by following methods //list: string[]; // Its only decleared so no memory is assigned to variable list list = Array<string>(); //list_1 = Array<string>(); //list_2 = []; add(value:string){ this.list.push(value); } delete(): string { return this.list.pop(); } read(){ for(var i = 0; i < this.list.length; ++i){ console.log(this.list[i]); } } } var result = new QueueDemo(); result.add('Mahesh'); console.log('Add operatin executed'); console.log(result.list); result.read(); console.log('Read operatin executed'); console.log(result.list); result.delete(); console.log('Delete operatin executed'); console.log(result.list); <file_sep>//one interface Ilog //- Method WriteLog() interface Ilog{ WriteLog(); } //one class SqlLog class SqlLog{ WriteLog(){ console.log('SQL Write'); } } //second class NotepadLog class NotepadLog implements Ilog{ WriteLog(){ console.log('notepad Write'); } WriteLogInNotepad(){ console.log('Notepad write'); } } // Factory witch give Ilog object class Factory{ getObject(className:string){ if(className == "SQL"){ return new SqlLog() } else if(className == "NotePad"){ return new NotepadLog() } else{ return null; } } } //Client application var f = new Factory(); var obj = f.getObject('SQL'); obj.WriteLog(); obj = f.getObject('NotePad'); obj.WriteLog(); <file_sep>function RestParams(n1) { var n2 = []; for (var _i = 1; _i < arguments.length; _i++) { n2[_i - 1] = arguments[_i]; } } RestParams('a', 'b', 'c'); function RestaParamInterface(info) { console.log(info.firstName); console.log(info.Age); } RestaParamInterface({ firstName: 'Mahesh', lastName: '', email: '', Address: '', Age: 30, MyAddress: { city: 'pune', pincode: 111111 } }); <file_sep>abstract class ScientificCalculator{ Add(n1:number,n2:number){ return n1 + n2; } Subtract(n1:number,n2:number){ return n1 - n2; } Multiple(n1:number,n2:number){ return n1 * n2; } Division(n1:number,n2:number){ return n1 / n2; } //If you dont know logic of method then make it as abstract function abstract Sin(n1:number,n2:number); } class Nokia extends ScientificCalculator{ //Implement function abstract method Sin Sin(n1:number,n2:number){ return 1 } //return 1; } //client applicatino var s = new Nokia(); var r = s.Add(11,12); console.log(r); r = s.Sin(11,12); console.log(r) // // Client appplication //You can not create object of abctact class or interface /** var s = new ScientificCalculator(); var r = s.Add(11,12); console.log(r); /**/ <file_sep>document.getElementsByTagName("div")[0].innerHTML = "Hi from js"; import "JQuery"; $(document).ready(function(){ $("div").click(function(){ alert('hello'); }) }); <file_sep>//Guideline - if you are using more than 5 arguments use model and use it function UserRegistration( userName:string ,firstName:string ,lastName:string ){ } UserRegistration('username','h','c'); /**/ //User interfaces when you are using model as it will be easy to manage code interface UserInfo{ userName: string firstName: string lastName?: string // Make property nullable or make it as optional } /**/ /**/ class UserInfo_Class{ userName: string firstName: string lastName: string } /**/ function UserRegistration_2(info:UserInfo){ } function UserRegistration_Class(info:UserInfo_Class){ } <file_sep>//systemjs.config.js //IFFI Function (Self called function) (function(){ System.config({ map:{ app:"src", "JQuery":"node_modules/jquery/dist/jquery.js" }, packages:{ app:{ main:"./main.js" } } }) })(this); <file_sep>var __extends = (this && this.__extends) || (function () { var extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return function (d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; })(); var ScientificCalculator = (function () { function ScientificCalculator() { } ScientificCalculator.prototype.Add = function (n1, n2) { return n1 + n2; }; ScientificCalculator.prototype.Subtract = function (n1, n2) { return n1 - n2; }; ScientificCalculator.prototype.Multiple = function (n1, n2) { return n1 * n2; }; ScientificCalculator.prototype.Division = function (n1, n2) { return n1 / n2; }; return ScientificCalculator; }()); var Nokia = (function (_super) { __extends(Nokia, _super); function Nokia() { return _super !== null && _super.apply(this, arguments) || this; } Nokia.prototype.Sin = function (n1, n2) { return 1; }; //return 1; return Nokia; }(ScientificCalculator)); //client applicatino var s = new Nokia(); var r = s.Add(11, 12); console.log(r); r = s.Sin(11, 12); console.log(r); // // Client appplication //You can not create object of abctact class or interface /** var s = new ScientificCalculator(); var r = s.Add(11,12); console.log(r); /**/ <file_sep>/// <reference path="declartion.ts" /> class DeclarationClass{ } var obj = new DeclarationClass(); obj.add(10,12);<file_sep>class ScientificCalculator{ Add(n1:number,n2:number){ return n1 + n2; } Subtract(n1:number,n2:number){ return n1 - n2; } Multiple(n1:number,n2:number){ return n1 * n2; } Division(n1:number,n2:number){ return n1 / n2; } } <file_sep>/// <reference path="declartion.ts" /> var DeclarationClass = (function () { function DeclarationClass() { } return DeclarationClass; }()); var obj = new DeclarationClass(); obj.add(10, 12); <file_sep> function calculate(){ var first = (document.getElementById('first') as HTMLInputElement).value; var firstAsString = (document.getElementById('first') as HTMLInputElement).value.toString(); console.log('Here'); console.log(firstAsString); //var second = document.getElementsByName('second').value; var second = (document.getElementById('second') as HTMLInputElement).value; var result = parseInt(first) + parseInt(second); alert('addition of ' + first + ' and ' + second + ' is ' + result); } <file_sep>//one class SqlLog var SqlLog = (function () { function SqlLog() { } SqlLog.prototype.WriteLog = function () { console.log('SQL Write'); }; return SqlLog; }()); //second class NotepadLog var NotepadLog = (function () { function NotepadLog() { } NotepadLog.prototype.WriteLog = function () { console.log('notepad Write'); }; NotepadLog.prototype.WriteLogInNotepad = function () { console.log('Notepad write'); }; return NotepadLog; }()); // Factory witch give Ilog object var Factory = (function () { function Factory() { } Factory.prototype.getObject = function (className) { if (className == "SQL") { return new SqlLog(); } else if (className == "NotePad") { return new NotepadLog(); } else { return null; } }; return Factory; }()); //Client application var f = new Factory(); var obj = f.getObject('SQL'); obj.WriteLog(); obj = f.getObject('NotePad'); obj.WriteLog(); <file_sep>var Calculator = (function () { function Calculator() { } Calculator.prototype.Add = function (n1, n2) { return n1 + n2; }; Calculator.prototype.Substraction = function (n1, n2) { return n1 - n2; }; Calculator.prototype.Multi = function (n1, n2) { return n1 * n1; }; Calculator.prototype.Division = function (n1, n2) { return n1 / n2; }; return Calculator; }()); var x = 10; var obj1 = new Calculator(); var result = obj1.Add(11, 22); //var result = obj1.Substraction('a','b'); // We can not pass string as data type is number //var result = obj1 <file_sep>class Calculator { Add(n1:number,n2:number){ return n1 + n2; } Substraction(n1:number,n2:number){ return n1 - n2; } Multi(n1:number,n2:number){ return n1 * n1; } Division(n1:number,n2:number){ return n1 / n2; } } var x = 10; var obj1 = new Calculator(); var result = obj1.Add(11,22); //var result = obj1.Substraction('a','b'); // We can not pass string as data type is number //var result = obj1<file_sep>JQuery("#firstname").val("<NAME>"); Add(11, 22); <file_sep>//Include login function By using namespace //<reference path="LoginFunction.ts" /> "use strict"; exports.__esModule = true; LoginModule.ValidateLogin(); LoginModule.ChangePassword(); <file_sep>function Add_JS(n1,n2){ return n1 + n2; } function Add_TS(n1: number, n2: number): number{ return n1 + n2; } function Add_Generic<T>(n1: T,n2: T): T{ return n1; } Add_JS(11,22); Add_JS("11","22"); Add_TS(11,22); //Add_TS("11","22"); Add_Generic<number>(11,22); Add_Generic<string>("11","22"); Add_Generic<string | number>("11",22); function ConvertToType<T,K>(value:T):K{ return null; }<file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-widh", inital-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <body> <script src="javascripts/application.js" type="text/javascript" charset="utf-8" async defer></script> <input type="text" name = "first"> <input type="text" name = "second"> <button name="submit" onclick="calculate();">Submit</button> </body> </html><file_sep>declare var JQuery:any; JQuery("#firstname").val("test data"); declare function Add(n1,n2); // Which will bypass error while access Add, or JQuery etc Add(11,22);<file_sep>function hello(){ console.log('hello'); alert('hi'); return null; } hello();<file_sep>/// <reference path="globals/jquery/index.d.ts" /> jQuery(""); <file_sep>//Guideline - if you are using more than 5 arguments use model and use it function UserRegistration( userName:string ,firstName:string ,lastName:string ){ } UserRegistration('username','h','c'); /**/ //User interfaces when you are using model as it will be easy to manage code interface UserInfo{ userName: string firstName: string lastName?: string // Make property nullable or make it as optional } /**/ /**/ class UserInfo_Class{ userName: string firstName: string lastName: string } /**/ function UserRegistration_2(info:UserInfo){ } function UserRegistration_Class(info:UserInfo_Class){ } //Get values from interface - will create objec of interface "UserInfo" var userInfo_1 = <UserInfo>{ userName: 'maheshchalke' ,firstName: 'Mahesh' //,lastName: 'C' }; UserRegistration_2(userInfo_1); //UserRegistration_2(userInfo); //you can pass interface using inline code like /** UserRegistration_2(<UserInfo>{ firstName: 'Mahesh' ,lastName: 'C' ,userName: 'maheshchalke' }); /**/ //you can pass interface using inline code like /** UserRegistration_2(<UserInfo>{firstName: 'Mahesh',lastName: 'C',userName: 'maheshchalke'}); /**/ /**/ // Will give error for otpinal parameter UserRegistration_2({userName:'Mahesh',firstName:'Mahesh'}) /**/ <file_sep>// Here T data type that we can define on creating object. var QueueDemoGeneric = (function () { function QueueDemoGeneric() { this.list = []; this.list_1 = Array(); this.list_2 = []; } QueueDemoGeneric.prototype.add = function (value) { this.list.push(value); }; QueueDemoGeneric.prototype["delete"] = function () { return this.list.pop(); }; QueueDemoGeneric.prototype.read = function () { for (var i = 0; i < this.list.length; ++i) { console.log(this.list[i]); } }; return QueueDemoGeneric; }()); var result = new QueueDemoGeneric(); result.add('Mahesh'); console.log('Add operatin executed'); console.log(result.list); result.add('Dinesh'); console.log('Add operatin executed'); console.log(result.list); result.read(); console.log('Read operatin executed'); console.log(result.list); result["delete"](); console.log('Delete operatin executed'); console.log(result.list); // Access it for number var result1 = new QueueDemoGeneric(); result1.add(10); // Access it for number and string var result2 = new QueueDemoGeneric(); result2.add("Mahesh"); result2.add(10); console.log(result2.list); <file_sep>// Here T data type that we can define on creating object. class QueueDemoGeneric<T>{ list: T[] = []; list_1 = Array<string>(); list_2 = []; add(value:T){ this.list.push(value); } delete(): T { return this.list.pop(); } read(){ for(var i = 0; i < this.list.length; ++i){ console.log(this.list[i]); } } } var result = new QueueDemoGeneric<string>(); result.add('Mahesh'); console.log('Add operatin executed'); console.log(result.list); result.add('Dinesh'); console.log('Add operatin executed'); console.log(result.list); result.read(); console.log('Read operatin executed'); console.log(result.list); result.delete(); console.log('Delete operatin executed'); console.log(result.list); // Access it for number var result1 = new QueueDemoGeneric<number>(); result1.add(10); // Access it for number and string var result2 = new QueueDemoGeneric<string | number>(); result2.add("Mahesh"); result2.add(10); console.log(result2.list); <file_sep>// Example for calculator to use Factory pattern interface ICal{ Result(a,b); } class Add implements ICal{ Result(a,b){ return a + b; } } class Subtract implements ICal{ Result(a,b){ return a - b; } } class Cal_Factory{ getObject(className:string){ if(className == "Add"){ return new Add() } else if(className == "Subtract"){ return new Subtract() } else{ return null; } } } //Client side application var c = new Cal_Factory(); var r = c.getObject('Add').Result(22,2); console.log(r) //24 r = c.getObject('Subtract').Result(22,2); console.log(r) //20 <file_sep><!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-widh", inital-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> </head> <body> <script > function Dosomething(){ console.log('null param call') } function Dosomething(val){ console.log('vlaue param call') } Dosometing(); //it will call last function Dosometing('adfdf'); // it will call last function </script> </body> </html><file_sep>//If you define a variable the function will be limited to function and class only. //let defines scope in block. var x = 10; if(true){ let y = 20; // let will define scope of code so it will be limited only in if condition } //console.log(y); //It will give error cannot fine name 'y' as we have defined variable with let keyword. var i = 0; { let i = 0; // It will allow to decleare as it have another scope } for(let i=0;i<5;i++){ console.log(i); } console.log(i); //It will give error cannot fine name 'i' as we have defined i with keyword let const z =10; //z=20; //Will give error because its constant. console.log('----------------------------'); for(var j = 0; j < 5; j++){ console.log(j); } /** print output after 2 second **/ console.log("Print output after 2 second") for(let j = 0; j < 5; j++){ setTimeout(function(){ console.log(j); },5000) }<file_sep>var Add = (function () { function Add() { } Add.prototype.Result = function (a, b) { return a + b; }; return Add; }()); var Subtract = (function () { function Subtract() { } Subtract.prototype.Result = function (a, b) { return a - b; }; return Subtract; }()); var Cal_Factory = (function () { function Cal_Factory() { } Cal_Factory.prototype.getObject = function (className) { if (className == "Add") { return new Add(); } else if (className == "Subtract") { return new Subtract(); } else { return null; } }; return Cal_Factory; }()); //Client side application var c = new Cal_Factory(); var r = c.getObject('Add').Result(22, 2); console.log(r); //24 r = c.getObject('Subtract').Result(22, 2); console.log(r); //20 <file_sep>'use strict' console.log("typescript donee"); class Employee{ } var str : String; str = 'a string data type'; var num : Number; num = 10; var bool : Boolean; bool = false; var globalVar = 'abc'; var anyDatatype : any; // supports all like js var unionDatatype : string|number; unionDatatype = 'abc'; unionDatatype = 10; //unionDatatype = false; var tupleDatatype : [string,number,boolean]; // here in array what the data type should be is mentioned tupleDatatype = ['abc',1.2,false]; //tupleDatatype = [1.2,false,'abc']; enum color{ red,gree,blue } var enumColor : color; enumColor = color.blue; var userDefinedDatatype : 'Mr.' | 'Miss'; userDefinedDatatype= 'Miss'; //userDefinedDatatype = "hi"; var arrayDatatype : number[]; var arrayDatatype2 : Array<number>; arrayDatatype = [1,2,3]; arrayDatatype2 = [1,2,3];<file_sep>//Guideline - if you are using more than 5 arguments use model and use it function UserRegistration(userName, firstName, lastName) { } UserRegistration('username', 'h', 'c'); /**/ /**/ var UserInfo_Class = (function () { function UserInfo_Class() { } return UserInfo_Class; }()); /**/ function UserRegistration_2(info) { } function UserRegistration_Class(info) { } //Get values from interface - will create objec of interface "UserInfo" var userInfo_1 = { userName: 'maheshchalke', firstName: 'Mahesh' //,lastName: 'C' }; UserRegistration_2(userInfo_1); //UserRegistration_2(userInfo); //you can pass interface using inline code like /** UserRegistration_2(<UserInfo>{ firstName: 'Mahesh' ,lastName: 'C' ,userName: 'maheshchalke' }); /**/ //you can pass interface using inline code like /** UserRegistration_2(<UserInfo>{firstName: 'Mahesh',lastName: 'C',userName: 'maheshchalke'}); /**/ /**/ // Will give error for otpinal parameter UserRegistration_2({ userName: 'Mahesh', firstName: 'Mahesh' }); /**/ <file_sep>//namespace Login{ // Its deprecated function so use module var Login; (function (Login) { // In grouping you need to specify which can be used outside // Use keyword export to allow this function ValidateLogin() { } Login.ValidateLogin = ValidateLogin; function ChangePassword() { } Login.ChangePassword = <PASSWORD>Password; //By declaring export you can use it outside var Password = (function () { function Password() { } return Password; }()); Login.Password = <PASSWORD>; })(Login || (Login = {})); Login.ValidateLogin(); Login.ChangePassword(); <file_sep>function hello() { console.log('hello'); alert('hi'); return null; } hello(); <file_sep> // Make nullable using question mark to provide overriding of function function Dosomething(val?,val2?,val3?:number){ console.log('vlaue param call') } Dosomething(); //it will call last function Dosomething('adfdf'); // it will call last function // When you don't know how many parameters it is going to take //Here you need to send by array //var myValue = [11,22,33,44] //AnyInputParam(myValue) function AnyInputParam(val:number[]){ console.log('value Param call'); } // You can call this funciton as //AnyInputParamAsNoArray(1,2,3,4) function AnyInputParamAsNoArray(...val:number[]){ console.log('Any input params as no array input') } AnyInputParamAsNoArray(1,2,3,4); // for default parameter function DefaultParam(var1,var2=3){ console.log(var1); console.log(var2); } DefaultParam(11); DefaultParam(11,22); function OverLoadded(val:boolean); function OverLoadded(val:number); function OverLoadded(val:any){ } OverLoadded(11); OverLoadded(true); //OverLoadded("myname"); // It will give error as its sending string <file_sep>function add(n1,n2):number{ return n1 + n2; } // Add function can be written as lambda express as follows // Advantage of lambda express is it preserves context of variables. var add_lambda = (n1,n2):number=>{ return n1 + n2; } function subtract(n1,n2):number{ return n1 - n2; } var subtract_lambda = (n1,n2):number=>{ return n1 - n2; } // Both function calls will give same output as follows console.log(add(10,10)); console.log(add_lambda(10,10)); console.log(subtract(10,10)); console.log(subtract_lambda(10,10));
6c7f6c952e15533c6b3e477bf03f5dc4f0eb514a
[ "JavaScript", "TypeScript" ]
40
JavaScript
maheshchalke2006/angular2
e4636ddc0650429170bd9c1ffc6c5cb3a298e7e0
cb397540b5d6afd9b39b14aa815b08d181e7ba24
refs/heads/master
<file_sep># frozen_string_literal: true RSpec.describe 'bit_field/type/reserved' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.enable(:register, [:name, :size, :type]) RgGen.enable(:bit_field, [:name, :bit_assignment, :initial_value, :reference, :type]) RgGen.enable(:bit_field, :type, [:reserved, :rw]) end describe 'register_map' do before(:all) do delete_configuration_facotry delete_register_map_factory end def create_bit_fields(&block) create_register_map { register_block(&block) }.bit_fields end specify 'ビットフィール型は:reserved' do bit_fields = create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 1; type :reserved } end end expect(bit_fields[0]).to have_property(:type, :reserved) end it '不揮発性ビットフィールドである' do bit_fields = create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 1; type :reserved } end end expect(bit_fields[0]).to have_property(:volatile?, false) end specify 'アクセス属性は予約済み属性' do bit_fields = create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 1; type :reserved } end end expect(bit_fields[0]).to match_access(:reserved) end specify '初期値の指定は不要' do expect { create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 1; type :reserved; initial_value 0 } end register do name :bar bit_field { name :bar; bit_assignment lsb: 1; type :reserved } end end }.not_to raise_error end specify '参照ビットフィールドの指定は不要' do expect { create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 1; type :reserved } end register do name :bar bit_field { name :bar; bit_assignment lsb: 1; type :reserved; reference 'baz.baz' } end register do name :baz bit_field { name :baz; bit_assignment lsb: 1; type :rw; initial_value 0 } end end }.not_to raise_error end end describe 'sv rtl' do include_context 'sv rtl common' before(:all) do delete_configuration_facotry delete_register_map_factory end before(:all) do RgGen.enable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.enable(:register_block, [:name, :byte_size]) RgGen.enable(:register, :sv_rtl_top) RgGen.enable(:bit_field, :sv_rtl_top) end after(:all) do RgGen.disable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.disable(:register_block, [:name, :byte_size]) end def create_bit_fields(&body) create_sv_rtl(&body).bit_fields end describe '#generate_code' do it 'rggen_bit_field_reservedをインスタンスするコードを出力する' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :reserved } bit_field { name 'bit_field_1'; bit_assignment lsb: 16, width: 16; type :reserved } end register do name 'register_1' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 64; type :reserved } end register do name 'register_2' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :reserved } end register do name 'register_3' size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :reserved } end register do name 'register_4' size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :reserved } end end expect(bit_fields[0]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_reserved u_bit_field ( .bit_field_if (bit_field_sub_if) ); CODE expect(bit_fields[1]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_reserved u_bit_field ( .bit_field_if (bit_field_sub_if) ); CODE expect(bit_fields[2]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_reserved u_bit_field ( .bit_field_if (bit_field_sub_if) ); CODE expect(bit_fields[3]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_reserved u_bit_field ( .bit_field_if (bit_field_sub_if) ); CODE expect(bit_fields[4]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_reserved u_bit_field ( .bit_field_if (bit_field_sub_if) ); CODE expect(bit_fields[5]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_reserved u_bit_field ( .bit_field_if (bit_field_sub_if) ); CODE end end end describe 'sv ral' do include_context 'sv ral common' before(:all) do delete_register_map_factory end describe '#access' do it 'ROを返す' do sv_ral = create_sv_ral do register do name :foo bit_field { name :foo; bit_assignment lsb: 1; type :reserved } end end expect(sv_ral.bit_fields[0].access).to eq 'RO' end end end end <file_sep># frozen_string_literal: true RSpec.describe 'register/type' do include_context 'clean-up builder' include_context 'register map common' describe 'register map' do before(:all) do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map { read_write } end RgGen.define_list_item_feature(:bit_field, :type, :bar) do register_map { read_only } end RgGen.define_list_item_feature(:bit_field, :type, :baz) do register_map { write_only } end RgGen.define_list_item_feature(:bit_field, :type, :qux) do register_map { reserved } end RgGen.enable(:global, [:bus_width, :address_width]) RgGen.enable(:register, [:type, :size]) RgGen.enable(:register, :type, [:foo, :bar, :baz]) RgGen.enable(:bit_field, [:bit_assignment, :initial_value, :reference, :type]) RgGen.enable(:bit_field, :type, [:foo, :bar, :baz, :qux]) end after(:all) do RgGen.delete(:bit_field, :type, [:foo, :bar, :baz, :qux]) end def create_registers(&block) configuration = create_configuration(bus_width: 32, address_width: 16) register_map = create_register_map(configuration) do register_block(&block) end register_map.registers end describe 'レジスタ型' do before(:all) do RgGen.define_list_item_feature(:register, :type, [:foo, :bar, :qux]) do register_map {} end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, [:foo, :bar, :qux]) end describe '#type' do it '指定したレジスタ型を返す' do [ [:foo, :bar], [:FOO, :BAR], ['foo', 'bar'], ['FOO', 'BAR'], [random_string(/foo/i), random_string(/bar/i)] ].each do |foo_type, bar_type| registers = create_registers do register do type foo_type bit_field { bit_assignment lsb: 0;type :foo } end register do type bar_type bit_field { bit_assignment lsb: 0;type :foo } end end expect(registers[0]).to have_property(:type, :foo) expect(registers[1]).to have_property(:type, :bar) end end context 'レジスタ型が未指定の場合' do it ':defaultを返す' do registers = create_registers do register do bit_field { bit_assignment lsb: 0;type :foo } end register do type nil bit_field { bit_assignment lsb: 0;type :foo } end register do type '' bit_field { bit_assignment lsb: 0;type :foo } end end expect(registers[0]).to have_property(:type, :default) expect(registers[1]).to have_property(:type, :default) expect(registers[2]).to have_property(:type, :default) end end end context '有効になっていないレジスタ型が指定された場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register { type :qux } end }.to raise_register_map_error 'unknown register type: :qux' end end context '定義されていないレジスタ型が指定された場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register { type :baz } end }.to raise_register_map_error 'unknown register type: :baz' end end end describe 'ビットフィールド' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map {} end RgGen.define_list_item_feature(:register, :type, :bar) do register_map { no_bit_fields } end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, [:foo, :bar]) end context '.no_bit_fieldの指定がない場合' do specify 'ビットフィールドが必要' do expect { create_registers do register { type :foo } end }.to raise_register_map_error 'no bit fields are given' end end context '.no_bit_fieldsの指定がある場合' do specify 'ビットフィールドを持たない' do registers = create_registers do register do type :bar end register do type :bar bit_field { bit_assignment lsb: 0;type :foo } end end expect(registers[0].bit_fields).to be_empty expect(registers[1].bit_fields).to be_empty end end specify '規定型はビットフィールドを必要とする' do expect { create_registers do register {} end }.to raise_register_map_error 'no bit fields are given' end end describe 'アクセス属性' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map {} end RgGen.define_list_item_feature(:register, :type, :bar) do register_map do writable? { true } readable? { true } end end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, [:foo, :bar]) end context '.writable?/.readable?の指定がない場合' do let(:registers) do create_registers do register do type :foo bit_field { type :foo; bit_assignment lsb: 0 } end register do type :foo bit_field { type :bar; bit_assignment lsb: 0 } end register do type :foo bit_field { type :baz; bit_assignment lsb: 0 } end register do type :foo bit_field { type :qux; bit_assignment lsb: 0 } end end end specify '書き込み可能なビットフィールドがあれば、書き込み可能レジスタ' do expect(registers[0]).to have_property(:writable?, true) expect(registers[1]).to have_property(:writable?, false) expect(registers[2]).to have_property(:writable?, true) expect(registers[3]).to have_property(:writable?, false) end specify '読み込み可能、または、予約済みビットフィードがあれば、読み込み可能レジスタ' do expect(registers[0]).to have_property(:readable?, true) expect(registers[1]).to have_property(:readable?, true) expect(registers[2]).to have_property(:readable?, false) expect(registers[3]).to have_property(:readable?, true) end end context '.writable?/.readable?の指定がある場合' do specify '.writable?/.readable?に与えられたブロックの評価結果がアクセス属性になる' do registers = create_registers do register do type :bar bit_field { bit_assignment lsb: 0; type :bar } end register do type :bar bit_field { bit_assignment lsb: 0; type :baz } end register do type :bar bit_field { bit_assignment lsb: 0; type :qux } end end expect(registers[0]).to have_properties [[:writable?, true], [:readable?, true]] expect(registers[1]).to have_properties [[:writable?, true], [:readable?, true]] expect(registers[2]).to have_properties [[:writable?, true], [:readable?, true]] end end end describe 'レジスタ幅' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map {} end RgGen.define_list_item_feature(:register, :type, :bar) do register_map { no_bit_fields } end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, [:foo, :bar]) end context 'ビットフィールドを持つ場合' do specify 'レジスタ幅はビットフィールドの最大MSBをバス幅に切り上げた値' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 31, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 0, width: 32; type :foo } end register do type :foo bit_field { bit_assignment lsb: 0, width: 8; type :foo } bit_field { bit_assignment lsb: 24, width: 8; type :foo } end register do type :foo bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 63, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 0, width: 64; type :foo } end register do type :foo bit_field { bit_assignment lsb: 31, width: 2; type :foo } end register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 0, width: 1, sequence_size: 2, step: 31; type :foo } end register do type :foo bit_field { bit_assignment lsb: 0, width: 1, sequence_size: 2, step: 32; type :foo } end end expect(registers[0]).to have_properties([[:width, 32], [:byte_width, 4]]) expect(registers[1]).to have_properties([[:width, 32], [:byte_width, 4]]) expect(registers[2]).to have_properties([[:width, 32], [:byte_width, 4]]) expect(registers[3]).to have_properties([[:width, 32], [:byte_width, 4]]) expect(registers[4]).to have_properties([[:width, 64], [:byte_width, 8]]) expect(registers[5]).to have_properties([[:width, 64], [:byte_width, 8]]) expect(registers[6]).to have_properties([[:width, 64], [:byte_width, 8]]) expect(registers[7]).to have_properties([[:width, 64], [:byte_width, 8]]) expect(registers[8]).to have_properties([[:width, 64], [:byte_width, 8]]) expect(registers[9]).to have_properties([[:width, 32], [:byte_width, 4]]) expect(registers[10]).to have_properties([[:width, 64], [:byte_width, 8]]) end end context 'ビットフィールドを持たない場合' do specify 'レジスタ幅はバス幅と同じ' do registers = create_registers do register do type :bar end end expect(registers[0]).to have_property(:width, 32) end end end describe '配列レジスタ' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map { support_array_register } end RgGen.define_list_item_feature(:register, :type, :bar) do register_map {} end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, [:foo, :bar]) end context '.support_array_registerが指定されている場合' do specify 'sizeが指定されているレジスタが配列レジスタ' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:array?, false) expect(registers[1]).to have_property(:array?, true) expect(registers[2]).to have_property(:array?, true) end end context '.support_array_registerが指定されていない場合' do specify 'sizeの指定にかかわらず、配列レジスタではない' do registers = create_registers do register do type :bar bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:array?, false) expect(registers[1]).to have_property(:array?, false) expect(registers[2]).to have_property(:array?, false) end end specify '規定型は配列レジスタに対応する' do registers = create_registers do register do size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:array?, true) end describe '#array_size' do context 'レジスタが配列レジスタの場合' do it '配列の大きさを返す' do registers = create_registers do register do type :foo size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:array_size, match([2])) expect(registers[1]).to have_property(:array_size, match([2, 3])) end end context 'レジスタが配列レジスタではない場合' do it 'nilを返す' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:array_size, nil) expect(registers[1]).to have_property(:array_size, nil) expect(registers[2]).to have_property(:array_size, nil) end end end context '#count' do context 'レジスタが配列レジスタの場合' do it '配列の総要素数を返す' do registers = create_registers do register do type :foo size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:count, 2) expect(registers[1]).to have_property(:count, 6) end end context 'レジスタが配列レジスタではない場合' do specify '要素数は1' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end end expect(registers[0]).to have_property(:count, 1) expect(registers[1]).to have_property(:count, 1) expect(registers[2]).to have_property(:count, 1) end end end end describe '#byte_size' do context '.byte_sizeの指定がない場合' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map {} end RgGen.define_list_item_feature(:register, :type, :bar) do register_map { support_array_register } end RgGen.define_list_item_feature(:register, :type, :baz) do register_map { no_bit_fields } end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, [:foo, :bar, :baz]) end specify '#byte_widthにsizeをかけた値が#byte_size' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :foo size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2] bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 32, width: 1; type :foo } end end expect(registers[0]).to have_property(:byte_size, 4) expect(registers[1]).to have_property(:byte_size, 8) expect(registers[2]).to have_property(:byte_size, 8) expect(registers[3]).to have_property(:byte_size, 16) expect(registers[4]).to have_property(:byte_size, 24) expect(registers[5]).to have_property(:byte_size, 48) registers = create_registers do register do type :bar bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :bar size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar size [2] bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :bar size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :bar size [2, 3] bit_field { bit_assignment lsb: 32, width: 1; type :foo } end end expect(registers[0]).to have_property(:byte_size, 4) expect(registers[1]).to have_property(:byte_size, 8) expect(registers[2]).to have_property(:byte_size, 8) expect(registers[3]).to have_property(:byte_size, 16) expect(registers[4]).to have_property(:byte_size, 24) expect(registers[5]).to have_property(:byte_size, 48) registers = create_registers do register do type :baz end register do type :baz size [2] end register do type :baz size [2, 3] end end expect(registers[0]).to have_property(:byte_size, 4) expect(registers[1]).to have_property(:byte_size, 8) expect(registers[2]).to have_property(:byte_size, 24) end end context '.byte_sizeが指定されている場合' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map do byte_size { 2 * byte_width } end end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, :foo) end specify '与えられたブロックの評価結果が#byte_size' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :foo size [2] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2] bit_field { bit_assignment lsb: 32, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 0, width: 1; type :foo } end register do type :foo size [2, 3] bit_field { bit_assignment lsb: 32, width: 1; type :foo } end end expect(registers[0]).to have_property(:byte_size, 8) expect(registers[1]).to have_property(:byte_size, 16) expect(registers[2]).to have_property(:byte_size, 8) expect(registers[3]).to have_property(:byte_size, 16) expect(registers[4]).to have_property(:byte_size, 8) expect(registers[5]).to have_property(:byte_size, 16) end end end describe 'オプションの指定' do before(:all) do RgGen.define_list_item_feature(:register, :type, :foo) do register_map do property :input_options, body: -> { options } end end end after(:all) do delete_register_map_factory RgGen.delete(:register, :type, :foo) end specify 'レジスタ型に対するオプションを指定することができる' do registers = create_registers do register do type [:foo, :option_1] bit_field { bit_assignment lsb: 0;type :foo } end register do type [:foo, :option_1, :option_2] bit_field { bit_assignment lsb: 0;type :foo } end register do type ' foo : option_1:fizz' bit_field { bit_assignment lsb: 0;type :foo } end register do type ' foo : option_1:fizz, option_2:buzz' bit_field { bit_assignment lsb: 0;type :foo } end register do type <<~'TYPE' foo: option_1:fizz, option_2:buzz option_3:fizzbuzz TYPE bit_field { bit_assignment lsb: 0;type :foo } end end expect(registers[0].type).to eq :foo expect(registers[0].input_options).to match([:option_1]) expect(registers[1].type).to eq :foo expect(registers[1].input_options).to match([:option_1, :option_2]) expect(registers[2].type).to eq :foo expect(registers[2].input_options).to match(['option_1:fizz']) expect(registers[3].type).to eq :foo expect(registers[3].input_options).to match(['option_1:fizz', 'option_2:buzz']) expect(registers[4].type).to eq :foo expect(registers[4].input_options).to match(['option_1:fizz', 'option_2:buzz', 'option_3:fizzbuzz']) end context 'オプションが未指定の場合' do specify '空の配列が渡される' do registers = create_registers do register do type :foo bit_field { bit_assignment lsb: 0;type :foo } end register do type [:foo] bit_field { bit_assignment lsb: 0;type :foo } end register do type 'foo' bit_field { bit_assignment lsb: 0;type :foo } end register do type 'foo:' bit_field { bit_assignment lsb: 0;type :foo } end end expect(registers[0].input_options).to be_empty expect(registers[1].input_options).to be_empty expect(registers[2].input_options).to be_empty expect(registers[3].input_options).to be_empty end end end end end <file_sep># frozen_string_literal: true RSpec.describe 'register/size' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.enable(:register, :size) end def create_register(&block) create_register_map { register_block(&block) }.registers.first end describe '#size' do it '入力された大きさを返す' do register = create_register { register { size 1 } } expect(register).to have_property(:size, match([1])) register = create_register { register { size [1] } } expect(register).to have_property(:size, match([1])) register = create_register { register { size [1, 2, 3] } } expect(register).to have_property(:size, match([1, 2, 3])) end context '未入力の場合' do it 'nilを返す' do register = create_register { register {} } expect(register.size).to be_nil register = create_register { register { size nil } } expect(register.size).to be_nil register = create_register { register { size [] } } expect(register.size).to be_nil register = create_register { register { size '' } } expect(register.size).to be_nil end end end specify '文字列も入力できる' do register = create_register { register { size '1' } } expect(register).to have_property(:size, match([1])) register = create_register { register { size '[1]' } } expect(register).to have_property(:size, match([1])) register = create_register { register { size '1, 2' } } expect(register).to have_property(:size, match([1, 2])) register = create_register { register { size '[1, 2]' } } expect(register).to have_property(:size, match([1, 2])) register = create_register { register { size '1, 2, 3' } } expect(register).to have_property(:size, match([1, 2, 3])) register = create_register { register { size '[1, 2, 3]' } } expect(register).to have_property(:size, match([1, 2, 3])) end describe 'エラーチェック' do context '入力文字列がパターンに一致しなかった場合' do it 'RegisterMapErrorを起こす' do [ 'foo', '0xef_gh', '[1', '1]', '[1,2', '1, 2]', '[foo, 2]', '[1, foo]', '[1:2]' ].each do |value| expect { create_register { register { size value } } }.to raise_register_map_error "illegal input value for register size: #{value.inspect}" end end end context '大きさの各要素が整数に変換できなかった場合' do it 'RegisterMapErrorを起こす' do [nil, true, false, 'foo', '0xef_gh', Object.new].each_with_index do |value, i| if [1, 2, 5].include?(i) expect { create_register { register { size value } } }.to raise_register_map_error "cannot convert #{value.inspect} into register size" end expect { create_register { register { size [value] } } }.to raise_register_map_error "cannot convert #{value.inspect} into register size" expect { create_register { register { size [1, value] } } }.to raise_register_map_error "cannot convert #{value.inspect} into register size" expect { create_register { register { size [1, 2, value] } } }.to raise_register_map_error "cannot convert #{value.inspect} into register size" end end end context '大きさに 1 未満の要素が含まれる場合' do it 'RegisterMapErrorを起こす' do [0, -1, -2, -7].each do |value| expect { create_register { register { size value } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}]" expect { create_register { register { size [value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}]" expect { create_register { register { size [1, value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [1, #{value}]" expect { create_register { register { size [value, 1] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}, 1]" expect { create_register { register { size [value, value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}, #{value}]" expect { create_register { register { size [1, value, 2] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [1, #{value}, 2]" expect { create_register { register { size [1, 2, value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [1, 2, #{value}]" expect { create_register { register { size [1, value, value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [1, #{value}, #{value}]" expect { create_register { register { size [value, 1, value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}, 1, #{value}]" expect { create_register { register { size [value, value, 1] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}, #{value}, 1]" expect { create_register { register { size [value, value, value] } } }.to raise_register_map_error "non positive value(s) are not allowed for register size: [#{value}, #{value}, #{value}]" end end end end end <file_sep># frozen_string_literal: true RSpec.describe 'bit_field/sv_rtl_top' do include_context 'sv rtl common' include_context 'clean-up builder' before(:all) do RgGen.enable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.enable(:register_block, [:name, :byte_size]) RgGen.enable(:register, [:name, :offset_address, :size, :type]) RgGen.enable(:bit_field, [:name, :bit_assignment, :type, :initial_value, :reference]) RgGen.enable(:bit_field, :type, :rw) RgGen.enable(:register_block, :sv_rtl_top) RgGen.enable(:register, :sv_rtl_top) RgGen.enable(:bit_field, :sv_rtl_top) end def create_bit_fields(&body) create_sv_rtl(&body).bit_fields end describe 'bit_field_sub_if' do it 'rggen_bit_field_ifのインスタンスを持つ' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 8, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 32, width: 64; type :rw; initial_value 0 } end end expect(bit_fields[0]) .to have_interface :bit_field, :bit_field_sub_if, { name: 'bit_field_sub_if', interface_type: 'rggen_bit_field_if', parameter_values: [1] } expect(bit_fields[1]) .to have_interface :bit_field, :bit_field_sub_if, { name: 'bit_field_sub_if', interface_type: 'rggen_bit_field_if', parameter_values: [8] } expect(bit_fields[2]) .to have_interface :bit_field, :bit_field_sub_if, { name: 'bit_field_sub_if', interface_type: 'rggen_bit_field_if', parameter_values: [8] } expect(bit_fields[3]) .to have_interface :bit_field, :bit_field_sub_if, { name: 'bit_field_sub_if', interface_type: 'rggen_bit_field_if', parameter_values: [64] } end end describe '#local_index' do context 'ビットフィールドが連番ではない場合' do it 'nilを返す' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x20 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end end expect(bit_fields[0].local_index).to be_nil expect(bit_fields[1].local_index).to be_nil expect(bit_fields[2].local_index).to be_nil end end context 'ビットフィールドが連番になっている場合' do it 'スコープ中のインデックスを返す' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0, sequence_size: 2; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, sequence_size: 2; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x20 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, sequence_size: 2; type :rw; initial_value 0 } end end expect(bit_fields[0].local_index).to match_identifier('i') expect(bit_fields[1].local_index).to match_identifier('j') expect(bit_fields[2].local_index).to match_identifier('k') end end end describe '#loop_variables' do context 'ビットフィールドがループ中にある場合' do it 'ループ変数の一覧を返す' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x20 bit_field { name 'bit_field_0'; bit_assignment lsb: 0, sequence_size: 2; type :rw; initial_value 0 } end register do name 'register_3' offset_address 0x30 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, sequence_size: 2; type :rw; initial_value 0 } end register do name 'register_4' offset_address 0x40 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, sequence_size: 2; type :rw; initial_value 0 } end end expect(bit_fields[0].loop_variables).to match([ match_identifier('i') ]) expect(bit_fields[1].loop_variables).to match([ match_identifier('i'), match_identifier('j') ]) expect(bit_fields[2].loop_variables).to match([ match_identifier('i') ]) expect(bit_fields[3].loop_variables).to match([ match_identifier('i'), match_identifier('j') ]) expect(bit_fields[4].loop_variables).to match([ match_identifier('i'), match_identifier('j'), match_identifier('k') ]) end end context 'ビットフィールドがループ中にないばあい' do it 'nilを返す' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end end expect(bit_fields[0].loop_variables).to be_nil end end end describe '#value' do let(:bit_fields) do create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 20, width: 2, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 24, width: 2, sequence_size: 2, step: 4; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 20, width: 2, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 24, width: 2, sequence_size: 2, step: 4; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x20 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 20, width: 2, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 24, width: 2, sequence_size: 2, step: 4; type :rw; initial_value 0 } end end end context '無引数の場合' do it '自身が保持する値への参照を返す' do expect(bit_fields[0].value).to match_identifier('register_if[0].value[0+:1]') expect(bit_fields[1].value).to match_identifier('register_if[0].value[8+:8]') expect(bit_fields[2].value).to match_identifier('register_if[0].value[16+1*i+:1]') expect(bit_fields[3].value).to match_identifier('register_if[0].value[20+2*i+:2]') expect(bit_fields[4].value).to match_identifier('register_if[0].value[24+4*i+:2]') expect(bit_fields[5].value).to match_identifier('register_if[1+i].value[0+:1]') expect(bit_fields[6].value).to match_identifier('register_if[1+i].value[8+:8]') expect(bit_fields[7].value).to match_identifier('register_if[1+i].value[16+1*j+:1]') expect(bit_fields[8].value).to match_identifier('register_if[1+i].value[20+2*j+:2]') expect(bit_fields[9].value).to match_identifier('register_if[1+i].value[24+4*j+:2]') expect(bit_fields[10].value).to match_identifier('register_if[5+2*i+j].value[0+:1]') expect(bit_fields[11].value).to match_identifier('register_if[5+2*i+j].value[8+:8]') expect(bit_fields[12].value).to match_identifier('register_if[5+2*i+j].value[16+1*k+:1]') expect(bit_fields[13].value).to match_identifier('register_if[5+2*i+j].value[20+2*k+:2]') expect(bit_fields[14].value).to match_identifier('register_if[5+2*i+j].value[24+4*k+:2]') end end context '引数でレジスタのオフセット/ビットフィールドのオフセット/幅が指定された場合' do it '指定されたオフセット/幅での自身が保持する値への参照を返す' do expect(bit_fields[0].value(1, 1, 1)).to match_identifier('register_if[0].value[0+:1]') expect(bit_fields[0].value('i', 'j', 1)).to match_identifier('register_if[0].value[0+:1]') expect(bit_fields[1].value(1, 1, 4)).to match_identifier('register_if[0].value[8+:4]') expect(bit_fields[1].value('i', 'j', 4)).to match_identifier('register_if[0].value[8+:4]') expect(bit_fields[2].value(1, 1, 1)).to match_identifier('register_if[0].value[17+:1]') expect(bit_fields[2].value('i', 'j', 1)).to match_identifier('register_if[0].value[16+1*j+:1]') expect(bit_fields[3].value(1, 1, 1)).to match_identifier('register_if[0].value[22+:1]') expect(bit_fields[3].value('i', 'j', 1)).to match_identifier('register_if[0].value[20+2*j+:1]') expect(bit_fields[4].value(1, 1, 1)).to match_identifier('register_if[0].value[28+:1]') expect(bit_fields[4].value('i', 'j', 1)).to match_identifier('register_if[0].value[24+4*j+:1]') expect(bit_fields[5].value(1, 1, 1)).to match_identifier('register_if[2].value[0+:1]') expect(bit_fields[5].value('i', 'j', 1)).to match_identifier('register_if[1+i].value[0+:1]') expect(bit_fields[6].value(1, 1, 4)).to match_identifier('register_if[2].value[8+:4]') expect(bit_fields[6].value('i', 'j', 4)).to match_identifier('register_if[1+i].value[8+:4]') expect(bit_fields[7].value(1, 1, 1)).to match_identifier('register_if[2].value[17+:1]') expect(bit_fields[7].value('i', 'j', 1)).to match_identifier('register_if[1+i].value[16+1*j+:1]') expect(bit_fields[8].value(1, 1, 1)).to match_identifier('register_if[2].value[22+:1]') expect(bit_fields[8].value('i', 'j', 1)).to match_identifier('register_if[1+i].value[20+2*j+:1]') expect(bit_fields[9].value(1, 1, 1)).to match_identifier('register_if[2].value[28+:1]') expect(bit_fields[9].value('i', 'j', 1)).to match_identifier('register_if[1+i].value[24+4*j+:1]') end end end describe '#generate_code' do it 'ビットフィールド階層のコードを出力する' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 20, width: 2, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 24, width: 2, sequence_size: 2, step: 4; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 20, width: 2, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 24, width: 2, sequence_size: 2, step: 4; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x20 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 20, width: 2, sequence_size: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 24, width: 2, sequence_size: 2, step: 4; type :rw; initial_value 0 } end end expect(bit_fields[0]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_0 rggen_bit_field_if #(1) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 0, 1) rggen_bit_field_rw #( .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_0_bit_field_0) ); end CODE expect(bit_fields[1]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_1 rggen_bit_field_if #(8) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 8, 8) rggen_bit_field_rw #( .WIDTH (8), .INITIAL_VALUE (8'h00) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_0_bit_field_1) ); end CODE expect(bit_fields[2]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_2 genvar i; for (i = 0;i < 2;++i) begin : g rggen_bit_field_if #(1) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 16+1*i, 1) rggen_bit_field_rw #( .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_0_bit_field_2[i]) ); end end CODE expect(bit_fields[3]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_3 genvar i; for (i = 0;i < 2;++i) begin : g rggen_bit_field_if #(2) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 20+2*i, 2) rggen_bit_field_rw #( .WIDTH (2), .INITIAL_VALUE (2'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_0_bit_field_3[i]) ); end end CODE expect(bit_fields[4]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_4 genvar i; for (i = 0;i < 2;++i) begin : g rggen_bit_field_if #(2) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 24+4*i, 2) rggen_bit_field_rw #( .WIDTH (2), .INITIAL_VALUE (2'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_0_bit_field_4[i]) ); end end CODE expect(bit_fields[5]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_0 rggen_bit_field_if #(1) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 0, 1) rggen_bit_field_rw #( .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_1_bit_field_0[i]) ); end CODE expect(bit_fields[6]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_1 rggen_bit_field_if #(8) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 8, 8) rggen_bit_field_rw #( .WIDTH (8), .INITIAL_VALUE (8'h00) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_1_bit_field_1[i]) ); end CODE expect(bit_fields[7]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_2 genvar j; for (j = 0;j < 2;++j) begin : g rggen_bit_field_if #(1) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 16+1*j, 1) rggen_bit_field_rw #( .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_1_bit_field_2[i][j]) ); end end CODE expect(bit_fields[8]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_3 genvar j; for (j = 0;j < 2;++j) begin : g rggen_bit_field_if #(2) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 20+2*j, 2) rggen_bit_field_rw #( .WIDTH (2), .INITIAL_VALUE (2'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_1_bit_field_3[i][j]) ); end end CODE expect(bit_fields[9]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_4 genvar j; for (j = 0;j < 2;++j) begin : g rggen_bit_field_if #(2) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 24+4*j, 2) rggen_bit_field_rw #( .WIDTH (2), .INITIAL_VALUE (2'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_1_bit_field_4[i][j]) ); end end CODE expect(bit_fields[10]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_0 rggen_bit_field_if #(1) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 0, 1) rggen_bit_field_rw #( .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_2_bit_field_0[i][j]) ); end CODE expect(bit_fields[11]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_1 rggen_bit_field_if #(8) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 8, 8) rggen_bit_field_rw #( .WIDTH (8), .INITIAL_VALUE (8'h00) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_2_bit_field_1[i][j]) ); end CODE expect(bit_fields[12]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_2 genvar k; for (k = 0;k < 2;++k) begin : g rggen_bit_field_if #(1) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 16+1*k, 1) rggen_bit_field_rw #( .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_2_bit_field_2[i][j][k]) ); end end CODE expect(bit_fields[13]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_3 genvar k; for (k = 0;k < 2;++k) begin : g rggen_bit_field_if #(2) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 20+2*k, 2) rggen_bit_field_rw #( .WIDTH (2), .INITIAL_VALUE (2'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_2_bit_field_3[i][j][k]) ); end end CODE expect(bit_fields[14]).to generate_code(:register, :top_down, <<~'CODE') if (1) begin : g_bit_field_4 genvar k; for (k = 0;k < 2;++k) begin : g rggen_bit_field_if #(2) bit_field_sub_if(); `rggen_connect_bit_field_if(bit_field_if, bit_field_sub_if, 24+4*k, 2) rggen_bit_field_rw #( .WIDTH (2), .INITIAL_VALUE (2'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .o_value (o_register_2_bit_field_4[i][j][k]) ); end end CODE end end end <file_sep># frozen_string_literal: true RgGen.define_simple_feature(:bit_field, :initial_value) do register_map do property :initial_value, default: 0 property :initial_value?, body: -> { !@initial_value.nil? } build do |value| @initial_value = begin Integer(value) rescue ArgumentError, TypeError error "cannot convert #{value.inspect} into initial value" end end verify(:component) do error_condition { option[:require] && !initial_value? } message { 'no initial value is given' } end verify(:component) do error_condition { initial_value? && initial_value < min_initial_value } message do 'input initial value is less than minimum initial value: ' \ "initial value #{initial_value} " \ "minimum initial value #{min_initial_value}" end end verify(:component) do error_condition { initial_value? && initial_value > max_initial_value } message do 'input initial value is greater than maximum initial value: ' \ "initial value #{initial_value} " \ "maximum initial value #{max_initial_value}" end end verify(:component) do error_condition { initial_value? && !match_valid_condition? } message do "does not match the valid initial value condition: #{initial_value}" end end private def option @option ||= (bit_field.options && bit_field.options[:initial_value]) || {} end def min_initial_value bit_field.width == 1 ? 0 : -(2**(bit_field.width - 1)) end def max_initial_value 2**bit_field.width - 1 end def match_valid_condition? !option.key?(:valid_condition) || instance_exec(@initial_value, &option[:valid_condition]) end end end <file_sep># frozen_string_literal: true RgGen.define_list_item_feature(:register, :type, :indirect) do register_map do define_helpers do index_verifier = Class.new do def initialize(&block) instance_eval(&block) end def error_condition(&block) @error_condition = block end def message(&block) @message = block end def verify(feature, index) error?(feature, index) && raise_error(feature, index) end def error?(feature, index) feature.instance_exec(index, &@error_condition) end def raise_error(feature, index) error_message = feature.instance_exec(index, &@message) feature.__send__(:error, error_message) end end define_method(:verify_index) do |&block| index_verifiers << index_verifier.new(&block) end def index_verifiers @index_verifiers ||= [] end end define_struct :index_entry, [:name, :value] do def value_index? !array_index? end def array_index? value.nil? end def distinguishable?(other) name == other.name && value != other.value && [self, other].all?(&:value_index?) end def find_index_field(bit_fields) bit_fields.find { |bit_field| bit_field.full_name == name } end end property :index_entries property :collect_index_fields do |bit_fields| index_entries.map { |entry| entry.find_index_field(bit_fields) } end byte_size { byte_width } support_array_register support_overlapped_address input_pattern [ /(#{variable_name}\.#{variable_name})/, /(#{variable_name}\.#{variable_name}):(#{integer})?/ ], match_automatically: false build do @index_entries = parse_index_entries end verify(:component) do error_condition do register.array? && register.array_size.length < array_index_fields.length end message { 'too many array indices are given' } end verify(:component) do error_condition do register.array? && register.array_size.length > array_index_fields.length end message { 'less array indices are given' } end verify(:all) do check_error do index_entries.each(&method(:verify_indirect_index)) end end verify_index do error_condition do |index| !index_entries.one? { |other| other.name == index.name } end message do |index| "same bit field is used as indirect index more than once: #{index.name}" end end verify_index do error_condition { |index| !index_field(index) } message do |index| "no such bit field for indirect index is found: #{index.name}" end end verify_index do error_condition do |index| index_field(index).register.name == register.name end message do |index| "own bit field is not allowed for indirect index: #{index.name}" end end verify_index do error_condition { |index| index_field(index).register.array? } message do |index| 'bit field of array register is not allowed ' \ "for indirect index: #{index.name}" end end verify_index do error_condition { |index| index_field(index).sequential? } message do |index| 'sequential bit field is not allowed ' \ "for indirect index: #{index.name}" end end verify_index do error_condition { |index| index_field(index).reserved? } message do |index| 'reserved bit field is not allowed ' \ "for indirect index: #{index.name}" end end verify_index do error_condition do |index| !index.array_index? && (index.value > (2**index_field(index).width - 1)) end message do |index| 'bit width of indirect index is not enough for ' \ "index value #{index.value}: #{index.name}" end end verify_index do error_condition do |index| index.array_index? && (array_index_value(index) > 2**index_field(index).width) end message do |index| 'bit width of indirect index is not enough for ' \ "array size #{array_index_value(index)}: #{index.name}" end end verify(:all) do error_condition { !distinguishable? } message { 'cannot be distinguished from other registers' } end private def parse_index_entries (!options.empty? && options.map(&method(:create_index_entry))) || (error 'no indirect indices are given') end def create_index_entry(value) input_values = split_value(value) if input_values.size == 2 index_entry.new(input_values[0], convert_index_value(input_values[1])) elsif input_values.size == 1 index_entry.new(input_values[0]) else error 'too many arguments for indirect index ' \ "are given: #{value.inspect}" end end def split_value(value) input_value = Array(value) field_name = input_value.first if sting_or_symbol?(field_name) && match_pattern(field_name) [*match_data.captures, *input_value[1..-1]] else error "illegal input value for indirect index: #{value.inspect}" end end def sting_or_symbol?(value) [String, Symbol].any?(&value.method(:is_a?)) end def convert_index_value(value) Integer(value) rescue ArgumentError, TypeError error "cannot convert #{value.inspect} into indirect index value" end def verify_indirect_index(index) helper.index_verifiers.each { |verifier| verifier.verify(self, index) } end def index_field(index) @index_fields ||= {} @index_fields[index.name] ||= index.find_index_field(register_block.bit_fields) end def array_index_fields @array_index_fields ||= index_entries.select(&:array_index?) end def array_index_value(index) @array_index_values ||= array_index_fields .map.with_index { |entry, i| [entry.name, register.array_size[i]] } .to_h @array_index_values[index.name] end def distinguishable? register_block .registers.select { |other| share_same_range?(other) } .all? { |other| distinguishable_indices?(other.index_entries) } end def share_same_range?(other) register.name != other.name && register.overlap?(other) end def distinguishable_indices?(other_entries) index_entries.any? do |entry| other_entries.any?(&entry.method(:distinguishable?)) end end end sv_rtl do build do logic :register, :indirect_index, { width: index_width } end main_code :register do |code| code << indirect_index_assignment << nl code << process_template(File.join(__dir__, 'indirect_sv_rtl.erb')) end private def index_fields @index_fields ||= register.collect_index_fields(register_block.bit_fields) end def index_width @index_width ||= index_fields.map(&:width).inject(:+) end def index_values loop_variables = register.loop_variables register.index_entries.zip(index_fields).map do |entry, field| if entry.array_index? loop_variables.shift[0, field.width] else hex(entry.value, field.width) end end end def indirect_index_assignment assign(indirect_index, concat(index_fields.map(&:value))) end end sv_ral do unmapped offset_address { register.offset_address } main_code :ral_package do class_definition(model_name) do |sv_class| sv_class.base 'rggen_ral_indirect_reg' sv_class.variables variables sv_class.body { model_body } end end private def model_body process_template(File.join(__dir__, 'indirect_sv_ral.erb')) end def index_properties array_position = -1 register.index_entries.zip(index_fields).map do |entry, field| value = if entry.value_index? hex(entry.value, field.width) else "array_index[#{array_position += 1}]" end [*entry.name.split('.'), value] end end def index_fields register.collect_index_fields(register_block.bit_fields) end end end <file_sep># frozen_string_literal: true register_block { name 'block_0' byte_size 256 register { name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0 , width: 4; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 4 , width: 4; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 8 , width: 1; type :rw; initial_value 0 } } register { name 'register_1' offset_address 0x04 bit_field { name 'bit_field_0'; bit_assignment lsb: 0 , width: 4; type :ro } bit_field { name 'bit_field_1'; bit_assignment lsb: 8 , width: 4; type :ro } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 8; type :rof; initial_value 0xab } bit_field { name 'bit_field_3'; bit_assignment lsb: 24, width: 8; type :reserved } } register { name 'register_2' offset_address 0x04 bit_field { name 'bit_field_0'; bit_assignment lsb: 0 , width: 4; type :wo; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8 , width: 4; type :w0trg } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4; type :w1trg } } register { name 'register_3' offset_address 0x08 bit_field { name 'bit_field_0'; bit_assignment lsb: 0 , width: 4; type :rc; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8 , width: 4; type :rc; initial_value 0; reference 'register_0.bit_field_0' } bit_field { name 'bit_field_2'; bit_assignment lsb: 12, width: 4; type :ro; reference 'register_3.bit_field_1' } bit_field { name 'bit_field_3'; bit_assignment lsb: 16, width: 4; type :rs; initial_value 0 } } register { name 'register_4' offset_address 0x0C bit_field { name 'bit_field_0'; bit_assignment lsb: 0 , width: 4; type :rwc; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 4 , width: 4; type :rwc; initial_value 0; reference 'register_2.bit_field_1' } bit_field { name 'bit_field_2'; bit_assignment lsb: 8 , width: 4; type :rwe; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 12, width: 4; type :rwe; initial_value 0; reference 'register_0.bit_field_2' } bit_field { name 'bit_field_4'; bit_assignment lsb: 16, width: 4; type :rwl; initial_value 0 } bit_field { name 'bit_field_5'; bit_assignment lsb: 20, width: 4; type :rwl; initial_value 0; reference 'register_0.bit_field_2' } } register { name 'register_5' offset_address 0x10 bit_field { name 'bit_field_0'; bit_assignment lsb: 0 , width: 4; type :w0c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 4 , width: 4; type :w0c; initial_value 0; reference 'register_0.bit_field_0' } bit_field { name 'bit_field_2'; bit_assignment lsb: 8 , width: 4; type :ro ; reference 'register_5.bit_field_1' } bit_field { name 'bit_field_3'; bit_assignment lsb: 12, width: 4; type :w1c; initial_value 0 } bit_field { name 'bit_field_4'; bit_assignment lsb: 16, width: 4; type :w1c; initial_value 0; reference 'register_0.bit_field_0' } bit_field { name 'bit_field_5'; bit_assignment lsb: 20, width: 4; type :ro ; reference 'register_5.bit_field_4' } bit_field { name 'bit_field_6'; bit_assignment lsb: 24, width: 4; type :w0s; initial_value 0 } bit_field { name 'bit_field_7'; bit_assignment lsb: 28, width: 4; type :w1s; initial_value 0 } } register { name 'register_6' offset_address 0x20 size 4 # bit assignments: [7:0] [23:16] [39:32] [55:48] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8, sequence_size: 4, step: 16; type :rw; initial_value 0 } # bit assignments: [15:8] [31:24] [47:40] [63:56] bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8, sequence_size: 4, step: 16; type :rw; initial_value 0 } } register { name 'register_7' offset_address 0x40 size [2, 4] type [:indirect, 'register_0.bit_field_0', 'register_0.bit_field_1', ['register_0.bit_field_2', 1]] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8, sequence_size: 4, step: 16; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8, sequence_size: 4, step: 16; type :rw; initial_value 0 } } register { name 'register_8' offset_address 0x80 size 32 type :external } } <file_sep># frozen_string_literal: true RgGen.define_list_item_feature(:bit_field, :type, :rw) do register_map do read_write non_volatile initial_value require: true end end RgGen.define_list_item_feature(:bit_field, :type, :wo) do register_map do write_only non_volatile initial_value require: true end end RgGen.define_list_item_feature(:bit_field, :type, [:rw, :wo]) do sv_rtl do build do output :register_block, :value_out, { name: "o_#{full_name}", data_type: :logic, width: width, array_size: array_size, array_format: array_port_format } end main_code :bit_field, from_template: true end end <file_sep># frozen_string_literal: true RSpec.describe 'bit_field/type' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.enable(:register, [:name, :size, :type]) RgGen.enable(:bit_field, [:name, :bit_assignment, :initial_value, :reference, :type]) RgGen.enable(:bit_field, :type, [:foo, :bar, :baz]) end describe 'register_map' do def create_bit_fields(&block) create_register_map { register_block(&block) }.bit_fields end describe 'ビットフィールド型' do before(:all) do RgGen.define_list_item_feature(:bit_field, :type, [:foo, :bar, :qux]) do register_map {} end end after(:all) do delete_register_map_factory RgGen.delete(:bit_field, :type, [:foo, :bar, :qux]) end specify '指定した型を #type で取得できる' do [ [:foo, :bar], [:FOO, :BAR], ['foo', 'bar'], [random_string(/foo/i), random_string(/bar/i)], [' foo', ' bar'], ['foo ', 'bar '] ].each do |foo_type, bar_type| bit_fields = create_bit_fields do register do name 'foo_bar' bit_field { name 'foo'; bit_assignment lsb: 0; type foo_type } bit_field { name 'bar'; bit_assignment lsb: 1; type bar_type } end end expect(bit_fields[0]).to have_property(:type, :foo) expect(bit_fields[1]).to have_property(:type, :bar) end end context '型が指定されなかった場合' do it 'RegisterMapErrorを起こす' do expect { create_bit_fields do register do name 'foo' bit_field { name 'foo'; bit_assignment lsb: 0 } end end }.to raise_register_map_error 'no bit field type is given' expect { create_bit_fields do register do name 'foo' bit_field { name 'foo'; bit_assignment lsb: 0; type nil } end end }.to raise_register_map_error 'no bit field type is given' expect { create_bit_fields do register do name 'foo' bit_field { name 'foo'; bit_assignment lsb: 0; type '' } end end }.to raise_register_map_error 'no bit field type is given' end end context '有効になっていない型が指定された場合' do it 'RegisterMapErrorを起こす' do expect { create_bit_fields do register do name 'qux' bit_field { name 'qux'; bit_assignment lsb: 0; type :qux } end end }.to raise_register_map_error 'unknown bit field type: :qux' end end context '未定義の型が指定された場合' do it 'RegisterMapErrorを起こす' do expect { create_bit_fields do register do name 'baz' bit_field { name 'baz'; bit_assignment lsb: 0; type :buz } end end }.to raise_register_map_error 'unknown bit field type: :buz' end end end describe 'アクセス属性' do def create_bit_field(&block) RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map(&block) end bit_fields = create_bit_fields do register do name 'foo' bit_field { name 'foo'; bit_assignment lsb: 0; type :foo } end end bit_fields.first end after do delete_register_map_factory RgGen.delete(:bit_field, :type, :foo) end describe '.read_write' do it '読み書き属性を設定する' do bit_field = create_bit_field { read_write } expect(bit_field).to match_access(:read_write) end end describe '.read_olny' do it '読み取り専用属性を設定する' do bit_field = create_bit_field { read_only } expect(bit_field).to match_access(:read_only) end end describe '.write_only' do it '書き込み専用属性を設定する' do bit_field = create_bit_field { write_only } expect(bit_field).to match_access(:write_only) end end describe '.reserved' do it '予約済み属性を設定する' do bit_field = create_bit_field { reserved } expect(bit_field).to match_access(:reserved) end end specify '規定属性は読み書き属性' do bit_field = create_bit_field {} expect(bit_field).to match_access(:read_write) end end describe '揮発性' do context '.volatileが指定されている場合' do before do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map { volatile } end end after do delete_register_map_factory RgGen.delete(:bit_field, :type, :foo) end specify 'ビットフィールドは揮発性' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } end end expect(bit_fields[0]).to have_property(:volatile?, true) end end context '.non_volatileが指定されている場合' do before do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map { non_volatile } end end after do delete_register_map_factory RgGen.delete(:bit_field, :type, :foo) end specify 'ビットフィールドは不揮発性' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } end end expect(bit_fields[0]).to have_property(:volatile?, false) end end context '.volatile?にブロックが指定された場合' do before do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map do volatile? { @volatile } build { @volatile = true } end end RgGen.define_list_item_feature(:bit_field, :type, :bar) do register_map do volatile? { @volatile } build { @volatile = false } end end end after do delete_register_map_factory RgGen.delete(:bit_field, :type, [:foo, :bar]) end specify 'ブロックの評価結果がビットフィールドの揮発性' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } bit_field { name 'bit_field_1'; bit_assignment lsb: 1; type :bar } end end expect(bit_fields[0]).to have_property(:volatile?, true) expect(bit_fields[1]).to have_property(:volatile?, false) end end context '未指定の場合' do before do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map {} end end after do delete_register_map_factory RgGen.delete(:bit_field, :type, :foo) end specify 'ビットフィールドは不揮発性' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } end end expect(bit_fields[0]).to have_property(:volatile?, true) end end end end describe 'sv ral' do include_context 'sv ral common' def create_bit_fields(&body) create_sv_ral(&body).bit_fields end describe '#access' do before(:all) do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map {} sv_ral {} end RgGen.define_list_item_feature(:bit_field, :type, :bar) do register_map {} sv_ral { access :baz } end end after(:all) do delete_register_map_factory delete_sv_ral_factory RgGen.delete(:bit_field, :type, [:foo, :bar]) end context 'アクセス権の指定がない場合' do it '大文字化した型名をアクセス権として返す' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } end end expect(bit_fields[0].access).to eq 'FOO' end end context '.accessでアクセス権の指定がある場合' do it '指定されたアクセス権を大文字化して返す' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :bar } end end expect(bit_fields[0].access).to eq 'BAZ' end end end describe '#model_name' do before(:all) do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map {} sv_ral {} end RgGen.define_list_item_feature(:bit_field, :type, :bar) do register_map {} sv_ral { model_name :rggen_bar_field } end RgGen.define_list_item_feature(:bit_field, :type, :baz) do register_map {} sv_ral { model_name { "rggen_ral_#{bit_field.name}" } } end end after(:all) do delete_register_map_factory delete_sv_ral_factory RgGen.delete(:bit_field, :type, [:foo, :bar, :baz]) end context 'モデル名の指定がない場合' do it 'rggen_ral_fieldをモデル名として返す' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } end end expect(bit_fields[0].model_name).to eq :rggen_ral_field end end context '.model_nameでモデル名の指定がある場合' do it '指定されたモデル名を返す' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :bar } end end expect(bit_fields[0].model_name).to eq :rggen_bar_field end end context '.model_nameにブロックが渡された場合' do it 'ブロックの実行結果をモデル名として返す' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :baz } end end expect(bit_fields[0].model_name).to eq 'rggen_ral_bit_field_0' end end end describe '#ral_model' do before(:all) do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map {} sv_ral {} end RgGen.define_list_item_feature(:bit_field, :type, :bar) do register_map {} sv_ral { model_name :rggen_bar_field } end RgGen.define_list_item_feature(:bit_field, :type, :baz) do register_map {} sv_ral { model_name { "rggen_ral_#{bit_field.name}" } } end end after(:all) do delete_register_map_factory delete_sv_ral_factory RgGen.delete(:bit_field, :type, [:foo, :bar, :baz]) end it 'フィールドモデル変数#ral_model' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } bit_field { name 'bit_field_1'; bit_assignment lsb: 1, sequence_size: 4; type :foo } end register do name 'register_1' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :bar } bit_field { name 'bit_field_1'; bit_assignment lsb: 1, sequence_size: 4; type :bar } end register do name 'register_2' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :baz } bit_field { name 'bit_field_1'; bit_assignment lsb: 1, sequence_size: 4; type :baz } end end expect(bit_fields[0]) .to have_variable :register, :ral_model, { name: 'bit_field_0', data_type: :rggen_ral_field, random: true } expect(bit_fields[1]) .to have_variable :register, :ral_model, { name: 'bit_field_1', data_type: :rggen_ral_field, array_size: [4], array_format: :unpacked, random: true } expect(bit_fields[2]) .to have_variable :register, :ral_model, { name: 'bit_field_0', data_type: :rggen_bar_field, random: true } expect(bit_fields[3]) .to have_variable :register, :ral_model, { name: 'bit_field_1', data_type: :rggen_bar_field, array_size: [4], array_format: :unpacked, random: true } expect(bit_fields[4]) .to have_variable :register, :ral_model, { name: 'bit_field_0', data_type: 'rggen_ral_bit_field_0', random: true } expect(bit_fields[5]) .to have_variable :register, :ral_model, { name: 'bit_field_1', data_type: 'rggen_ral_bit_field_1', array_size: [4], array_format: :unpacked, random: true } end end describe '#constructors' do before(:all) do RgGen.define_list_item_feature(:bit_field, :type, :foo) do register_map { volatile } sv_ral {} end RgGen.define_list_item_feature(:bit_field, :type, :bar) do register_map { non_volatile } sv_ral {} end RgGen.define_list_item_feature(:bit_field, :type, :baz) do register_map {} sv_ral { access :rw } end end after(:all) do delete_register_map_factory delete_sv_ral_factory RgGen.delete(:bit_field, :type, [:foo, :bar]) end it 'フィールドモデルの生成と構成を行うコードを出力する' do bit_fields = create_bit_fields do register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :foo } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8; type :foo } bit_field { name 'bit_field_2'; bit_assignment lsb: 16; type :foo; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 24, width: 8; type :foo; initial_value 0xab } end register do name 'register_1' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :bar } bit_field { name 'bit_field_1'; bit_assignment lsb: 1; type :baz } end register do name 'register_2' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :foo } bit_field { name 'bit_field_1'; bit_assignment lsb: 4, width: 4, sequence_size: 4, step: 8; type :foo } end end code_block = RgGen::Core::Utility::CodeUtility::CodeBlock.new bit_fields.flat_map(&:constructors).each do |constructor| code_block << [constructor, "\n"] end expect(code_block).to match_string(<<~'CODE') `rggen_ral_create_field_model(bit_field_0, 0, 1, FOO, 1, 1'h0, 0) `rggen_ral_create_field_model(bit_field_1, 8, 8, FOO, 1, 8'h00, 0) `rggen_ral_create_field_model(bit_field_2, 16, 1, FOO, 1, 1'h0, 1) `rggen_ral_create_field_model(bit_field_3, 24, 8, FOO, 1, 8'hab, 1) `rggen_ral_create_field_model(bit_field_0, 0, 1, BAR, 0, 1'h0, 0) `rggen_ral_create_field_model(bit_field_1, 1, 1, RW, 1, 1'h0, 0) `rggen_ral_create_field_model(bit_field_0[0], 0, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_0[1], 8, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_0[2], 16, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_0[3], 24, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_1[0], 4, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_1[1], 12, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_1[2], 20, 4, FOO, 1, 4'h0, 0) `rggen_ral_create_field_model(bit_field_1[3], 28, 4, FOO, 1, 4'h0, 0) CODE end end end end <file_sep># frozen_string_literal: true require 'rggen/built_in' require 'rggen/spreadsheet_loader' RgGen.enable :global, [ :bus_width, :address_width, :array_port_format, :fold_sv_interface_port ] RgGen.enable :register_block, [:name, :byte_size] RgGen.enable :register, [:name, :offset_address, :size, :type] RgGen.enable :register, :type, [:external, :indirect] RgGen.enable :bit_field, [ :name, :bit_assignment, :type, :initial_value, :reference, :comment ] RgGen.enable :bit_field, :type, [ :rc, :reserved, :ro, :rof, :rs, :rw, :rwc, :rwe, :rwl, :w0c, :w1c, :w0s, :w1s, :w0trg, :w1trg, :wo ] RgGen.enable :register_block, [:sv_rtl_top, :protocol] RgGen.enable :register_block, :protocol, [:apb, :axi4lite] RgGen.enable :register, [:sv_rtl_top] RgGen.enable :bit_field, [:sv_rtl_top] RgGen.enable :register_block, [:sv_ral_package] <file_sep># frozen_string_literal: true source 'https://rubygems.org' # Specify your gem's dependencies in rggen.gemspec gemspec [ 'rggen-devtools', 'rggen-core', 'rggen-spreadsheet-loader', 'rggen-systemverilog' ].each do |rggen_library| library_path = File.expand_path("../#{rggen_library}", __dir__) if Dir.exist?(library_path) && !ENV['USE_GITHUB_REPOSITORY'] gem rggen_library, path: library_path else gem rggen_library, git: "https://github.com/rggen/#{rggen_library}.git" end end if ENV['USE_FIXED_GEMS'] ['facets'].each do |library| library_path = File.expand_path("../#{library}", __dir__) if Dir.exist?(library_path) && !ENV['USE_GITHUB_REPOSITORY'] gem library, path: library_path else gem library, git: "https://github.com/taichi-ishitani/#{library}.git" end end gem 'ruby-ole', '>= 1.2.12.2' gem 'rubyzip', '>= 1.2.3' gem 'spreadsheet', '>= 1.2.1' end group :develop do gem 'rake' gem 'rubocop', '>= 0.48.0', require: false end group :test do gem 'codecov', require: false gem 'regexp-examples', require: false gem 'rspec', '>= 3.8' gem 'simplecov', require: false end <file_sep># frozen_string_literal: true RgGen.define_simple_feature(:bit_field, :sv_rtl_top) do sv_rtl do export :local_index export :loop_variables export :array_size export :value build do interface :bit_field, :bit_field_sub_if, { name: 'bit_field_sub_if', interface_type: 'rggen_bit_field_if', parameter_values: [bit_field.width] } end main_code :register do local_scope("g_#{bit_field.name}") do |scope| scope.loop_size loop_size scope.variables variables scope.body(&method(:body_code)) end end pre_code :bit_field do |code| code << bit_field_if_connection << nl end def local_index (bit_field.sequential? || nil) && create_identifier(index_name) end def index_name depth = (register.loop_variables&.size || 0) + 1 loop_index(depth) end def loop_variables (inside_loop? || nil) && [*register.loop_variables, local_index].compact end def array_size (inside_loop? || nil) && [*register.array_size, bit_field.sequence_size].compact end def value(register_offset = nil, bit_field_offset = nil, width = nil) bit_field_offset ||= local_index width ||= bit_field.width register_block .register_if[register.index(register_offset)] .value[bit_field.lsb(bit_field_offset), width] end private def inside_loop? register.array? || bit_field.sequential? end def loop_size (bit_field.sequential? || nil) && { index_name => bit_field.sequence_size } end def variables bit_field.declarations(:bit_field, :variable) end def body_code(code) bit_field.generate_code(:bit_field, :top_down, code) end def bit_field_if_connection macro_call( :rggen_connect_bit_field_if, [ register.bit_field_if, bit_field.bit_field_sub_if, bit_field.lsb(local_index), bit_field.width ] ) end end end <file_sep># frozen_string_literal: true RSpec.describe 'bit_field/type/w1c' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.enable(:register, [:name, :size, :type]) RgGen.enable(:bit_field, [:name, :bit_assignment, :initial_value, :reference, :type]) RgGen.enable(:bit_field, :type, [:w1c, :rw]) end describe 'register_map' do before(:all) do delete_configuration_facotry delete_register_map_factory end def create_bit_fields(&block) create_register_map { register_block(&block) }.bit_fields end specify 'ビットフィールド型は:w1c' do bit_fields = create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 0; type :w1c; initial_value 0 } end end expect(bit_fields[0]).to have_property(:type, :w1c) end it '揮発性ビットフィールドである' do bit_fields = create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 0; type :w1c; initial_value 0 } end end expect(bit_fields[0]).to have_property(:volatile?, true) end specify 'アクセス属性は読み書き可' do bit_fields = create_bit_fields do register do name :foo bit_field { name :foo; bit_assignment lsb: 0; type :w1c; initial_value 0 } end end expect(bit_fields[0]).to match_access(:read_write) end specify '初期値の指定が必要' do expect { create_bit_fields do register do name :foo bit_field { name :foo_0; bit_assignment lsb: 0, width: 1; type :w1c; initial_value 0 } bit_field { name :foo_1; bit_assignment lsb: 1, width: 2; type :w1c; initial_value 1 } end end }.not_to raise_error expect { create_bit_fields do register do name :foo bit_field { name :foo_0; bit_assignment lsb: 0, width: 1; type :w1c } end end }.to raise_register_map_error end context '参照ビットフィールドの指定がある場合' do specify '同一幅のビットフィールドの指定が必要' do expect { create_bit_fields do register do name :foo bit_field { name :foo_0; bit_assignment lsb: 0, width: 1; type :w1c; reference 'bar.bar_0'; initial_value 0 } bit_field { name :foo_1; bit_assignment lsb: 1, width: 2; type :w1c; reference 'bar.bar_1'; initial_value 0 } end register do name :bar bit_field { name :bar_0; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } bit_field { name :bar_1; bit_assignment lsb: 1, width: 2; type :rw; initial_value 0 } end end }.not_to raise_error expect { create_bit_fields do register do name :foo bit_field { name :foo_0; bit_assignment lsb: 0, width: 1; type :w1c; reference 'bar.bar_0'; initial_value 0 } bit_field { name :foo_1; bit_assignment lsb: 1, width: 2; type :w1c; reference 'bar.bar_1'; initial_value 0 } end register do name :bar bit_field { name :bar_0; bit_assignment lsb: 0, width: 2; type :rw; initial_value 0 } bit_field { name :bar_1; bit_assignment lsb: 2, width: 1; type :rw; initial_value 0 } end end }.to raise_register_map_error end end end describe 'sv rtl' do include_context 'sv rtl common' before(:all) do delete_configuration_facotry delete_register_map_factory end before(:all) do RgGen.enable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.enable(:register_block, [:name, :byte_size]) RgGen.enable(:register_block, :sv_rtl_top) RgGen.enable(:register, :sv_rtl_top) RgGen.enable(:bit_field, :sv_rtl_top) end after(:all) do RgGen.disable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.disable(:register_block, [:name, :byte_size]) end def create_bit_fields(&body) configuration = create_configuration(array_port_format: array_port_format) create_sv_rtl(configuration, &body).bit_fields end let(:array_port_format) do [:packed, :unpacked, :serialized].sample end it '入力ポート#set/出力ポート#value_outを持つ' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0 } end register do name 'register_1' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 64; type :w1c; initial_value 0 } end register do name 'register_2' size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0 } end register do name 'register_3' size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0 } end end expect(bit_fields[0]) .to have_port :register_block, :set, { name: 'i_register_0_bit_field_0_set', direction: :input, data_type: :logic, width: 1 } expect(bit_fields[0]) .to have_port :register_block, :value_out, { name: 'o_register_0_bit_field_0', direction: :output, data_type: :logic, width: 1 } expect(bit_fields[1]) .to have_port :register_block, :set, { name: 'i_register_0_bit_field_1_set', direction: :input, data_type: :logic, width: 2 } expect(bit_fields[1]) .to have_port :register_block, :value_out, { name: 'o_register_0_bit_field_1', direction: :output, data_type: :logic, width: 2 } expect(bit_fields[2]) .to have_port :register_block, :set, { name: 'i_register_0_bit_field_2_set', direction: :input, data_type: :logic, width: 4, array_size: [2], array_format: array_port_format } expect(bit_fields[2]) .to have_port :register_block, :value_out, { name: 'o_register_0_bit_field_2', direction: :output, data_type: :logic, width: 4, array_size: [2], array_format: array_port_format } expect(bit_fields[3]) .to have_port :register_block, :set, { name: 'i_register_1_bit_field_0_set', direction: :input, data_type: :logic, width: 64 } expect(bit_fields[3]) .to have_port :register_block, :value_out, { name: 'o_register_1_bit_field_0', direction: :output, data_type: :logic, width: 64 } expect(bit_fields[4]) .to have_port :register_block, :set, { name: 'i_register_2_bit_field_0_set', direction: :input, data_type: :logic, width: 1, array_size: [4], array_format: array_port_format } expect(bit_fields[4]) .to have_port :register_block, :value_out, { name: 'o_register_2_bit_field_0', direction: :output, data_type: :logic, width: 1, array_size: [4], array_format: array_port_format } expect(bit_fields[5]) .to have_port :register_block, :set, { name: 'i_register_2_bit_field_1_set', direction: :input, data_type: :logic, width: 2, array_size: [4], array_format: array_port_format } expect(bit_fields[5]) .to have_port :register_block, :value_out, { name: 'o_register_2_bit_field_1', direction: :output, data_type: :logic, width: 2, array_size: [4], array_format: array_port_format } expect(bit_fields[6]) .to have_port :register_block, :set, { name: 'i_register_2_bit_field_2_set', direction: :input, data_type: :logic, width: 4, array_size: [4, 2], array_format: array_port_format } expect(bit_fields[6]) .to have_port :register_block, :value_out, { name: 'o_register_2_bit_field_2', direction: :output, data_type: :logic, width: 4, array_size: [4, 2], array_format: array_port_format } expect(bit_fields[7]) .to have_port :register_block, :set, { name: 'i_register_3_bit_field_0_set', direction: :input, data_type: :logic, width: 1, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[7]) .to have_port :register_block, :value_out, { name: 'o_register_3_bit_field_0', direction: :output, data_type: :logic, width: 1, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[8]) .to have_port :register_block, :set, { name: 'i_register_3_bit_field_1_set', direction: :input, data_type: :logic, width: 2, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[8]) .to have_port :register_block, :value_out, { name: 'o_register_3_bit_field_1', direction: :output, data_type: :logic, width: 2, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[9]) .to have_port :register_block, :set, { name: 'i_register_3_bit_field_2_set', direction: :input, data_type: :logic, width: 4, array_size: [2, 2, 2], array_format: array_port_format } expect(bit_fields[9]) .to have_port :register_block, :value_out, { name: 'o_register_3_bit_field_2', direction: :output, data_type: :logic, width: 4, array_size: [2, 2, 2], array_format: array_port_format } end context '参照信号を持つ場合' do it '出力ポート#value_unmaskedを持つ' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0; reference 'register_3.bit_field_0' } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0; reference 'register_3.bit_field_1' } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0; reference 'register_3.bit_field_2' } end register do name 'register_1' size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0; reference 'register_3.bit_field_0' } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0; reference 'register_3.bit_field_1' } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0; reference 'register_3.bit_field_2' } end register do name 'register_2' size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0; reference 'register_3.bit_field_0' } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0; reference 'register_3.bit_field_1' } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0; reference 'register_3.bit_field_2' } end register do name 'register_3' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4; type :rw; initial_value 0 } end end expect(bit_fields[0]) .to have_port :register_block, :value_unmasked, { name: 'o_register_0_bit_field_0_unmasked', direction: :output, data_type: :logic, width: 1 } expect(bit_fields[1]) .to have_port :register_block, :value_unmasked, { name: 'o_register_0_bit_field_1_unmasked', direction: :output, data_type: :logic, width: 2 } expect(bit_fields[2]) .to have_port :register_block, :value_unmasked, { name: 'o_register_0_bit_field_2_unmasked', direction: :output, data_type: :logic, width: 4, array_size: [2], array_format: array_port_format } expect(bit_fields[3]) .to have_port :register_block, :value_unmasked, { name: 'o_register_1_bit_field_0_unmasked', direction: :output, data_type: :logic, width: 1, array_size: [4], array_format: array_port_format } expect(bit_fields[4]) .to have_port :register_block, :value_unmasked, { name: 'o_register_1_bit_field_1_unmasked', direction: :output, data_type: :logic, width: 2, array_size: [4], array_format: array_port_format } expect(bit_fields[5]) .to have_port :register_block, :value_unmasked, { name: 'o_register_1_bit_field_2_unmasked', direction: :output, data_type: :logic, width: 4, array_size: [4, 2], array_format: array_port_format } expect(bit_fields[6]) .to have_port :register_block, :value_unmasked, { name: 'o_register_2_bit_field_0_unmasked', direction: :output, data_type: :logic, width: 1, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[7]) .to have_port :register_block, :value_unmasked, { name: 'o_register_2_bit_field_1_unmasked', direction: :output, data_type: :logic, width: 2, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[8]) .to have_port :register_block, :value_unmasked, { name: 'o_register_2_bit_field_2_unmasked', direction: :output, data_type: :logic, width: 4, array_size: [2, 2, 2], array_format: array_port_format } end end context '参照信号を持たない場合' do it '出力ポート#value_unmaskedを持たない' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0 } end register do name 'register_1' size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0 } end register do name 'register_2' size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :w1c; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4, sequence_size: 2, step: 8; type :w1c; initial_value 0 } end end expect(bit_fields[0]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_0_bit_field_0_unmasked', direction: :output, data_type: :logic, width: 1 } expect(bit_fields[1]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_0_bit_field_1_unmasked', direction: :output, data_type: :logic, width: 2 } expect(bit_fields[2]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_0_bit_field_2_unmasked', direction: :output, data_type: :logic, width: 4, array_size: [2], array_format: array_port_format } expect(bit_fields[3]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_1_bit_field_0_unmasked', direction: :output, data_type: :logic, width: 1, array_size: [4], array_format: array_port_format } expect(bit_fields[4]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_1_bit_field_1_unmasked', direction: :output, data_type: :logic, width: 2, array_size: [4], array_format: array_port_format } expect(bit_fields[5]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_1_bit_field_2_unmasked', direction: :output, data_type: :logic, width: 4, array_size: [4, 2], array_format: array_port_format } expect(bit_fields[6]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_2_bit_field_0_unmasked', direction: :output, data_type: :logic, width: 1, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[7]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_2_bit_field_1_unmasked', direction: :output, data_type: :logic, width: 2, array_size: [2, 2], array_format: array_port_format } expect(bit_fields[8]) .to not_have_port :register_block, :value_unmasked, { name: 'o_register_2_bit_field_2_unmasked', direction: :output, data_type: :logic, width: 4, array_size: [2, 2, 2], array_format: array_port_format } end end describe '#generate_code' do let(:array_port_format) { :packed } it 'rggen_bit_field_w01cをインスタンスするコードを生成する' do bit_fields = create_bit_fields do name 'block_0' byte_size 256 register do name 'register_0' bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 1; type :w1c; reference 'register_5.bit_field_0'; initial_value 1 } bit_field { name 'bit_field_2'; bit_assignment lsb: 8, width: 8; type :w1c; initial_value 0 } bit_field { name 'bit_field_3'; bit_assignment lsb: 16, width: 8; type :w1c; reference 'register_5.bit_field_2'; initial_value 0xab } end register do name 'register_1' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 64; type :w1c; initial_value 0 } end register do name 'register_2' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 4, width: 4, sequence_size: 4, step: 8; type :w1c; reference 'register_5.bit_field_1'; initial_value 0 } end register do name 'register_3' size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 4, width: 4, sequence_size: 4, step: 8; type :w1c; reference 'register_5.bit_field_1'; initial_value 0 } end register do name 'register_4' size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 4, sequence_size: 4, step: 8; type :w1c; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 4, width: 4, sequence_size: 4, step: 8; type :w1c; reference 'register_5.bit_field_1'; initial_value 0 } end register do name 'register_5' bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 8; type :rw; initial_value 0 } end end expect(bit_fields[0]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (1), .INITIAL_VALUE (1'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_0_bit_field_0_set), .i_mask (1'h1), .o_value (o_register_0_bit_field_0), .o_value_unmasked () ); CODE expect(bit_fields[1]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (1), .INITIAL_VALUE (1'h1) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_0_bit_field_1_set), .i_mask (register_if[11].value[0+:1]), .o_value (o_register_0_bit_field_1), .o_value_unmasked (o_register_0_bit_field_1_unmasked) ); CODE expect(bit_fields[2]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (8), .INITIAL_VALUE (8'h00) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_0_bit_field_2_set), .i_mask (8'hff), .o_value (o_register_0_bit_field_2), .o_value_unmasked () ); CODE expect(bit_fields[3]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (8), .INITIAL_VALUE (8'hab) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_0_bit_field_3_set), .i_mask (register_if[11].value[16+:8]), .o_value (o_register_0_bit_field_3), .o_value_unmasked (o_register_0_bit_field_3_unmasked) ); CODE expect(bit_fields[4]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (64), .INITIAL_VALUE (64'h0000000000000000) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_1_bit_field_0_set), .i_mask (64'hffffffffffffffff), .o_value (o_register_1_bit_field_0), .o_value_unmasked () ); CODE expect(bit_fields[5]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (4), .INITIAL_VALUE (4'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_2_bit_field_0_set[i]), .i_mask (4'hf), .o_value (o_register_2_bit_field_0[i]), .o_value_unmasked () ); CODE expect(bit_fields[6]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (4), .INITIAL_VALUE (4'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_2_bit_field_1_set[i]), .i_mask (register_if[11].value[8+:4]), .o_value (o_register_2_bit_field_1[i]), .o_value_unmasked (o_register_2_bit_field_1_unmasked[i]) ); CODE expect(bit_fields[7]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (4), .INITIAL_VALUE (4'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_3_bit_field_0_set[i][j]), .i_mask (4'hf), .o_value (o_register_3_bit_field_0[i][j]), .o_value_unmasked () ); CODE expect(bit_fields[8]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (4), .INITIAL_VALUE (4'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_3_bit_field_1_set[i][j]), .i_mask (register_if[11].value[8+:4]), .o_value (o_register_3_bit_field_1[i][j]), .o_value_unmasked (o_register_3_bit_field_1_unmasked[i][j]) ); CODE expect(bit_fields[9]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (4), .INITIAL_VALUE (4'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_4_bit_field_0_set[i][j][k]), .i_mask (4'hf), .o_value (o_register_4_bit_field_0[i][j][k]), .o_value_unmasked () ); CODE expect(bit_fields[10]).to generate_code(:bit_field, :top_down, <<~'CODE') rggen_bit_field_w01c #( .CLEAR_VALUE (1'b1), .WIDTH (4), .INITIAL_VALUE (4'h0) ) u_bit_field ( .i_clk (i_clk), .i_rst_n (i_rst_n), .bit_field_if (bit_field_sub_if), .i_set (i_register_4_bit_field_1_set[i][j][k]), .i_mask (register_if[11].value[8+:4]), .o_value (o_register_4_bit_field_1[i][j][k]), .o_value_unmasked (o_register_4_bit_field_1_unmasked[i][j][k]) ); CODE end end end end <file_sep># frozen_string_literal: true register_block { name 'block_1' byte_size 128 register { name 'register_0' offset_address 0x00 size [2, 4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8, sequence_size: 4, step: 16; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8, sequence_size: 4, step: 16; type :ro; reference 'register_1.bit_field_1' } } register { name 'register_1' offset_address 0x40 size [2, 4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 8, sequence_size: 4, step: 16; type :ro; reference 'register_0.bit_field_0' } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 8, sequence_size: 4, step: 16; type :rw; initial_value 0 } } } <file_sep># frozen_string_literal: true require_relative 'rggen/version' require_relative 'rggen/default_setup_file' require_relative 'rggen/built_in' <file_sep># frozen_string_literal: true RSpec.describe RgGen do include_context 'clean-up builder' describe '規定セットアップファイル' do before(:all) do @original_stdout = $stdout $stdout = File.open(File::NULL, 'w') end after(:all) do $stdout = @original_stdout end let(:builder) { RgGen.builder } describe RgGen::DEFAULT_SETUP_FILE do it '規定セットアップファイルのパスを示す' do path = File.expand_path('../../lib/rggen/setup/default.rb', __dir__) expect(RgGen::DEFAULT_SETUP_FILE).to eq path end end specify 'セットアップファイルが未指定の場合、規定セットアップファイルが読み込まれる' do RgGen::BuiltIn.module_eval do const_defined?(:BUILT_IN_FILES) && remove_const(:BUILT_IN_FILES) end $LOADED_FEATURES.delete_if do |file| [ %r{rggen/systemverilog\.rb}, %r{rggen/built_in\.rb}, %r{rggen/spreadsheet_loader\.rb} ].any? do |pattern| pattern.match(file) end end expect(builder).to receive(:setup).with(:systemverilog, equal(RgGen::SystemVerilog)) expect(builder).to receive(:setup).with(:'built-in', equal(RgGen::BuiltIn)) expect(builder).to receive(:setup).with(:'spreadsheet-loader', equal(RgGen::SpreadsheetLoader)) expect(builder).to receive(:enable).with(:global, match([:bus_width, :address_width, :array_port_format, :fold_sv_interface_port])).and_call_original expect(builder).to receive(:enable).with(:register_block, match([:name, :byte_size])).and_call_original expect(builder).to receive(:enable).with(:register, match([:name, :offset_address, :size, :type])).and_call_original expect(builder).to receive(:enable).with(:register, :type, match([:external, :indirect])).and_call_original expect(builder).to receive(:enable).with(:bit_field, match([:name, :bit_assignment, :type, :initial_value, :reference, :comment])).and_call_original expect(builder).to receive(:enable).with(:bit_field, :type, match([:rc, :reserved, :ro, :rof, :rs, :rw, :rwc, :rwe, :rwl, :w0c, :w1c, :w0s, :w1s, :w0trg, :w1trg, :wo])).and_call_original expect(builder).to receive(:enable).with(:register_block, match([:sv_rtl_top, :protocol])).and_call_original expect(builder).to receive(:enable).with(:register_block, :protocol, match([:apb, :axi4lite])).and_call_original expect(builder).to receive(:enable).with(:register, match([:sv_rtl_top])).and_call_original expect(builder).to receive(:enable).with(:bit_field, match([:sv_rtl_top])).and_call_original expect(builder).to receive(:enable).with(:register_block, match([:sv_ral_package])).and_call_original cli = RgGen::Core::CLI.new(builder) cli.run(['--verbose-version']) end end end <file_sep># frozen_string_literal: true require_relative 'built_in/version' module RgGen VERSION = BuiltIn::VERSION end <file_sep># frozen_string_literal: true module RgGen DEFAULT_SETUP_FILE = File.expand_path('setup/default.rb', __dir__).freeze end <file_sep># frozen_string_literal: true RSpec.describe 'bit_field/initial_value' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.define_simple_feature(:bit_field, :options) do register_map do property :options build { |value| @options = value } end end RgGen.enable(:global, :bus_width) RgGen.enable(:bit_field, [:bit_assignment, :options, :initial_value].shuffle) end after(:all) do RgGen.delete(:bit_field, :options) end def create_bit_field(width, option_values, *input_value) register_map = create_register_map do register_block do register do bit_field do initial_value input_value[0] unless input_value.empty? bit_assignment lsb: 0, width: width options initial_value: option_values end end end end register_map.bit_fields.first end let(:default_option) do { require: false } end describe '#initial_value' do it '入力された初期値を返す' do { 1 => [0, 1], 2 => [-2, -1, 0, 1, 3], 3 => [-4, -1, 0, 1, 3, 7] }.each do |width, initial_values| initial_values.each do |initial_value| bit_field = create_bit_field(width, default_option, initial_value) expect(bit_field).to have_property(:initial_value, initial_value) bit_field = create_bit_field(width, default_option, initial_value.to_f) expect(bit_field).to have_property(:initial_value, initial_value) bit_field = create_bit_field(width, default_option, initial_value.to_s) expect(bit_field).to have_property(:initial_value, initial_value) next if initial_value.negative? bit_field = create_bit_field(width, default_option, format('0x%x', initial_value)) expect(bit_field).to have_property(:initial_value, initial_value) end end end context '初期値が未入力の場合' do it '既定値 0 を返す' do bit_field = create_bit_field(1, default_option) expect(bit_field).to have_property(:initial_value, 0) end end context '入力が空白の場合' do it '既定値 0 を返す' do bit_field = create_bit_field(1, default_option, nil) expect(bit_field).to have_property(:initial_value, 0) bit_field = create_bit_field(1, default_option, '') expect(bit_field).to have_property(:initial_value, 0) end end end describe 'initial_value?' do it '初期値が設定されたかどうかを返す' do bit_field = create_bit_field(1, default_option) expect(bit_field).to have_property(:initial_value?, false) bit_field = create_bit_field(1, default_option, nil) expect(bit_field).to have_property(:initial_value?, false) bit_field = create_bit_field(1, default_option, '') expect(bit_field).to have_property(:initial_value?, false) bit_field = create_bit_field(1, default_option, 1) expect(bit_field).to have_property(:initial_value?, true) end end describe 'エラーチェック' do context '入力が整数に変換できない場合' do it 'RegisterMapErrorを起こす' do [true, false, 'foo', '0xef_gh', Object.new].each do |value| expect { create_bit_field(1, default_option, value) }.to raise_register_map_error "cannot convert #{value.inspect} into initial value" end end end context '初期値の指定が必須の場合で、初期値の指定がない場合' do it 'RegisterMapErrorを起こす' do expect { create_bit_field(1, { require: true }) }.to raise_register_map_error 'no initial value is given' expect { create_bit_field(1, { require: true }, nil) }.to raise_register_map_error 'no initial value is given' expect { create_bit_field(1, { require: true }, '') }.to raise_register_map_error 'no initial value is given' end end context '入力が最小値未満の場合' do it 'RegisterMapErrorを起こす' do { 1 => [0, [-1, -2, rand(-16..-3)]], 2 => [-2, [-3, -4, rand(-16..-5)]], 3 => [-4, [-5, -6, rand(-16..-7)]] }.each do |width, (min_value, values)| values.each do |value| expect { create_bit_field(width, default_option, value) }.to raise_register_map_error 'input initial value is less than minimum initial value: ' \ "initial value #{value} minimum initial value #{min_value}" end end end end context '入力が最大値を超える場合' do it 'RegisterMapErrorを起こす' do { 1 => [1, [2, 3, rand(4..16)]], 2 => [3, [4, 5, rand(6..16)]], 3 => [7, [8, 9, rand(10..16)]] }.each do |width, (max_value, values)| values.each do |value| expect { create_bit_field(width, default_option, value) }.to raise_register_map_error 'input initial value is greater than maximum initial value: ' \ "initial value #{value} maximum initial value #{max_value}" end end end end context 'オプションでvalid_conditionの指定があり' do let(:valid_condition) do proc do |v| min = 2**bit_field.width - 3 max = 2**bit_field.width - 2 (min..max).include?(v) end end context '与えられたブロックの評価結果が真の場合' do it 'RegisterMapErrorを起こさない' do expect { create_bit_field(3, { valid_condition: valid_condition}, 5) }.not_to raise_error expect { create_bit_field(3, { valid_condition: valid_condition}, 6) }.not_to raise_error end end context '評価結果が偽の場合' do it 'RegisterMapErrorを起こす' do expect { create_bit_field(3, { valid_condition: valid_condition}, 4) }.to raise_register_map_error 'does not match the valid initial value condition: 4' expect { create_bit_field(3, { valid_condition: valid_condition}, 7) }.to raise_register_map_error 'does not match the valid initial value condition: 7' end end end end end <file_sep># frozen_string_literal: true RSpec.describe 'register/type/indirect' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.enable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.enable(:register_block, [:byte_size]) RgGen.enable(:register, [:name, :offset_address, :size, :type]) RgGen.enable(:register, :type, [:indirect]) RgGen.enable(:bit_field, [:name, :bit_assignment, :initial_value, :reference, :type]) RgGen.enable(:bit_field, :type, [:ro, :rw, :wo, :reserved]) end describe 'register map' do before(:all) do delete_configuration_facotry delete_register_map_factory end def create_registers(&block) register_map = create_register_map do register_block do byte_size 256 instance_eval(&block) end end register_map.registers end specify 'レジスタ型は:indirect' do registers = create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x04 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end expect(registers.first).to have_property(:type, :indirect) end specify '#sizeに依らず、#byte_sizeは#byte_widthを示す' do registers = create_registers do register do name :foo offset_address 0x0 type [:indirect, ['baz.baz_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 type [:indirect, ['baz.baz_0', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end expect(registers[0]).to have_property(:byte_size, 4) expect(registers[1]).to have_property(:byte_size, 8) registers = create_registers do register do name :foo offset_address 0x0 size 2 type [:indirect, 'baz.baz_0', ['baz.baz_1', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size 3 type [:indirect, 'baz.baz_0', ['baz.baz_1', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 2; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 2, width: 1; type :rw; initial_value 0 } end end expect(registers[0]).to have_property(:byte_size, 4) expect(registers[1]).to have_property(:byte_size, 8) registers = create_registers do register do name :foo offset_address 0x0 size [2, 3] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [3, 4] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 2; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 2, width: 3; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 5, width: 1; type :rw; initial_value 0 } end end expect(registers[0]).to have_property(:byte_size, 4) expect(registers[1]).to have_property(:byte_size, 8) end describe '#index_entries' do it 'オプショで指定されたインデックス一覧を返す' do registers = create_registers do register do name :foo offset_address 0x0 type [:indirect, ['qux.qux_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2] type [:indirect, 'qux.qux_1', ['qux.qux_2', 1]] bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :baz offset_address 0x0 size [2, 3] type [:indirect, 'qux.qux_0', 'qux.qux_1', ['qux.qux_2', 2]] bit_field { name :baz_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :qux offset_address 0x4 bit_field { name :qux_0; bit_assignment lsb: 0, width: 2; type :rw; initial_value 0 } bit_field { name :qux_1; bit_assignment lsb: 2, width: 2; type :rw; initial_value 0 } bit_field { name :qux_2; bit_assignment lsb: 4, width: 2; type :rw; initial_value 0 } end end expect(registers[0].index_entries.map(&:to_h)).to match([ { name: 'qux.qux_2', value: 0 } ]) expect(registers[1].index_entries.map(&:to_h)).to match([ { name: 'qux.qux_1', value: nil }, { name: 'qux.qux_2', value: 1 } ]) expect(registers[2].index_entries.map(&:to_h)).to match([ { name: 'qux.qux_0', value: nil }, { name: 'qux.qux_1', value: nil }, { name: 'qux.qux_2', value: 2 } ]) end specify '文字列でインデックスを指定することができる' do registers = create_registers do register do name :foo offset_address 0x0 type 'indirect: qux.qux_2:0' bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2] type 'indirect: qux.qux_1, qux.qux_2:1' bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :baz offset_address 0x0 size [2, 3] type 'indirect: qux.qux_0, qux.qux_1, qux.qux_2: 2' bit_field { name :baz_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :qux offset_address 0x4 bit_field { name :qux_0; bit_assignment lsb: 0, width: 2; type :rw; initial_value 0 } bit_field { name :qux_1; bit_assignment lsb: 2, width: 2; type :rw; initial_value 0 } bit_field { name :qux_2; bit_assignment lsb: 4, width: 2; type :rw; initial_value 0 } end end expect(registers[0].index_entries.map(&:to_h)).to match([ { name: 'qux.qux_2', value: 0 } ]) expect(registers[1].index_entries.map(&:to_h)).to match([ { name: 'qux.qux_1', value: nil }, { name: 'qux.qux_2', value: 1 } ]) expect(registers[2].index_entries.map(&:to_h)).to match([ { name: 'qux.qux_0', value: nil }, { name: 'qux.qux_1', value: nil }, { name: 'qux.qux_2', value: 2 } ]) end end describe 'エラーチェック' do context 'インデックスの指定がない場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type :indirect end end }.to raise_register_map_error 'no indirect indices are given' end end context 'インデックス名が文字列、または、シンボルではない場合' do it 'RegisterMapErrorを起こす' do [nil, true, false, Object.new, []].each do |value| expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, value] end end }.to raise_register_map_error "illegal input value for indirect index: #{value.inspect}" end end end context 'フィールド名が入力パターンに一致しない場合' do it 'RegisterMapErrorを起こす' do ['0foo.foo', 'foo.0foo', 'foo.foo.0', 'foo.foo:0xef_gh'].each do |value| expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, value] end end }.to raise_register_map_error "illegal input value for indirect index: #{value.inspect}" end end end context 'インデックス値が整数に変換できない場合' do it 'RegisterMapErrorを起こす' do [nil, true, false, '', '0xef_gh', Object.new].each do |value| expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', value]] end end }.to raise_register_map_error "cannot convert #{value.inspect} into indirect index value" end end end context 'インデックス指定の引数が多すぎる場合' do it 'RegisterMapErrorを起こす' do value = ['bar.bar_0', 1, nil] expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, value] end end }.to raise_register_map_error "too many arguments for indirect index are given: #{value}" value = ['bar.bar_0:0', 1] expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, value] end end }.to raise_register_map_error "too many arguments for indirect index are given: #{value}" value = ['bar.bar_0:0', nil] expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, value] end end }.to raise_register_map_error "too many arguments for indirect index are given: #{value}" end end context '同じビットフィールドが複数回使用された場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', 0], ['bar.bar_0', 1]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x04 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end }.to raise_register_map_error 'same bit field is used as indirect index more than once: bar.bar_0' end end context 'インデックス用のビットフィールドが存在しない場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_1', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x04 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end }.to raise_register_map_error 'no such bit field for indirect index is found: bar.bar_1' expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['baz.bar_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x04 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end }.to raise_register_map_error 'no such bit field for indirect index is found: baz.bar_0' end end context 'インデックスビットフィールドが自身のビットフィールドの場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['foo.foo_1', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name :foo_1; bit_assignment lsb: 1; type :rw; initial_value 0 } end end }.to raise_register_map_error 'own bit field is not allowed for indirect index: foo.foo_1' end end context 'インデックスビットフィールドが配列レジスタに属している場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 size [2] bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end }.to raise_register_map_error 'bit field of array register is not allowed for indirect index: bar.bar_0' end end context 'インデックスビットフィールドが連番ビットフィールドの場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0, sequence_size: 1; type :rw; initial_value 0 } end end }.to raise_register_map_error 'sequential bit field is not allowed for indirect index: bar.bar_0' end end context 'インデックスビットフィールドの属性が予約済みの場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0; type :reserved } end end }.to raise_register_map_error 'reserved bit field is not allowed for indirect index: bar.bar_0' end end context 'インデックス値がインデックスビットフィールドの幅より大きい場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['bar.bar_0', 2]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end }.to raise_register_map_error 'bit width of indirect index is not enough for index value 2: bar.bar_0' end end context '配列インデックスに過不足がある場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 size [1] type [:indirect, 'bar.bar_0', 'bar.bar_1'] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name :bar_1; bit_assignment lsb: 1; type :rw; initial_value 0 } end end }.to raise_register_map_error 'too many array indices are given' expect { create_registers do register do name :foo offset_address 0x0 size [1, 2, 3] type [:indirect, 'bar.bar_0', 'bar.bar_1'] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name :bar_1; bit_assignment lsb: 1; type :rw; initial_value 0 } end end }.to raise_register_map_error 'less array indices are given' end end context '配列の大きさがインデックスビットフィールドの幅より大きい場合' do it 'RegisterMapErrorを起こす' do expect { create_registers do register do name :foo offset_address 0x0 size 3 type [:indirect, 'bar.bar_0'] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end end }.to raise_register_map_error 'bit width of indirect index is not enough for array size 3: bar.bar_0' expect { create_registers do register do name :foo offset_address 0x0 size [2, 3] type [:indirect, 'bar.bar_0', 'bar.bar_1'] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x4 bit_field { name :bar_0; bit_assignment lsb: 0; type :rw; initial_value 0 } bit_field { name :bar_1; bit_assignment lsb: 1; type :rw; initial_value 0 } end end }.to raise_register_map_error 'bit width of indirect index is not enough for array size 3: bar.bar_1' end end describe 'インデックスの区別' do context 'インデックスが他のレジスタと区別できる場合' do it 'エラーを起こさない' do expect { create_registers do register do name :foo offset_address 0x4 type [:indirect, ['baz.baz_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 type [:indirect, ['baz.baz_0', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.not_to raise_error expect { create_registers do register do name :foo offset_address 0x0 type [:indirect, ['baz.baz_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :ro } end register do name :bar offset_address 0x0 type [:indirect, ['baz.baz_0', 0]] bit_field { name :bar_0; bit_assignment lsb: 0; type :wo; initial_value 0 } end register do name :baz offset_address 0x4 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.not_to raise_error expect { create_registers do register do name :foo offset_address 0x4 size [2] type [:indirect, 'baz.baz_0', ['baz.baz_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2] type [:indirect, 'baz.baz_0', ['baz.baz_2', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.not_to raise_error expect { create_registers do register do name :foo offset_address 0x4 size [2] type [:indirect, 'baz.baz_0', ['baz.baz_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.not_to raise_error expect { create_registers do register do name :foo offset_address 0x4 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.not_to raise_error end end context 'インデックスが他のレジスタと区別できない場合' do it 'エラーを起こさない' do expect { create_registers do register do name :foo offset_address 0x4 type [:indirect, ['baz.baz_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 type [:indirect, ['baz.baz_0', 0]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.to raise_register_map_error 'cannot be distinguished from other registers' expect { create_registers do register do name :foo offset_address 0x4 type [:indirect, ['baz.baz_0', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 type [:indirect, ['baz.baz_1', 0]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.to raise_register_map_error 'cannot be distinguished from other registers' expect { create_registers do register do name :foo offset_address 0x4 size 2 type [:indirect, 'baz.baz_0'] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size 2 type [:indirect, 'baz.baz_1'] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.to raise_register_map_error 'cannot be distinguished from other registers' expect { create_registers do register do name :foo offset_address 0x4 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_1'] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_2'] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.to raise_register_map_error 'cannot be distinguished from other registers' expect { create_registers do register do name :foo offset_address 0x4 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_2', ['baz.baz_2', 0]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.to raise_register_map_error 'cannot be distinguished from other registers' expect { create_registers do register do name :foo offset_address 0x4 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_1', ['baz.baz_2', 0]] bit_field { name :foo_0; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name :bar offset_address 0x0 size [2, 2] type [:indirect, 'baz.baz_0', 'baz.baz_2', ['baz.baz_0', 1]] bit_field { name :bar_0; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name :baz offset_address 0x8 bit_field { name :baz_0; bit_assignment lsb: 0, width: 4; type :rw; initial_value 0 } bit_field { name :baz_1; bit_assignment lsb: 4, width: 4; type :rw; initial_value 0 } bit_field { name :baz_2; bit_assignment lsb: 8, width: 4; type :rw; initial_value 0 } end end }.to raise_register_map_error 'cannot be distinguished from other registers' end end end end end let(:register_map_body) do proc do byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } bit_field { name 'bit_field_1'; bit_assignment lsb: 8, width: 2; type :rw; initial_value 0 } bit_field { name 'bit_field_2'; bit_assignment lsb: 16, width: 4; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 type [:indirect, ['register_0.bit_field_0', 1]] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x14 size [2] type [:indirect, 'register_0.bit_field_1'] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } end register do name 'register_3' offset_address 0x18 size [2, 4] type [:indirect, 'register_0.bit_field_1', 'register_0.bit_field_2'] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } end register do name 'register_4' offset_address 0x1c size [2, 4] type [:indirect, ['register_0.bit_field_0', 0], 'register_0.bit_field_1', 'register_0.bit_field_2'] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :rw; initial_value 0 } end register do name 'register_5' offset_address 0x20 type [:indirect, ['register_0.bit_field_0', 0]] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :ro } end register do name 'register_6' offset_address 0x24 type [:indirect, ['register_0.bit_field_0', 0]] bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 1; type :wo; initial_value 0 } end end end describe 'sv rtl' do include_context 'sv rtl common' before(:all) do RgGen.enable(:register_block, :sv_rtl_top) RgGen.enable(:register, :sv_rtl_top) RgGen.enable(:bit_field, :sv_rtl_top) end let(:registers) do create_sv_rtl(&register_map_body).registers end it 'logic変数#indirect_indexを持つ' do expect(registers[1]) .to have_variable :register, :indirect_index, { name: 'indirect_index', data_type: :logic, width: 1 } expect(registers[2]) .to have_variable :register, :indirect_index, { name: 'indirect_index', data_type: :logic, width: 2 } expect(registers[3]) .to have_variable :register, :indirect_index, { name: 'indirect_index', data_type: :logic, width: 6 } expect(registers[4]) .to have_variable :register, :indirect_index, { name: 'indirect_index', data_type: :logic, width: 7 } end describe '#generate_code' do it 'rggen_indirect_registerをインスタンスするコードを出力する' do expect(registers[1]).to generate_code(:register, :top_down, <<~'CODE') assign indirect_index = {register_if[0].value[0+:1]}; rggen_indirect_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h10), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .INDIRECT_INDEX_WIDTH (1), .INDIRECT_INDEX_VALUE ({1'h1}) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[1]), .i_indirect_index (indirect_index), .bit_field_if (bit_field_if) ); CODE expect(registers[2]).to generate_code(:register, :top_down, <<~'CODE') assign indirect_index = {register_if[0].value[8+:2]}; rggen_indirect_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h14), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .INDIRECT_INDEX_WIDTH (2), .INDIRECT_INDEX_VALUE ({i[0+:2]}) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[2+i]), .i_indirect_index (indirect_index), .bit_field_if (bit_field_if) ); CODE expect(registers[3]).to generate_code(:register, :top_down, <<~'CODE') assign indirect_index = {register_if[0].value[8+:2], register_if[0].value[16+:4]}; rggen_indirect_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h18), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .INDIRECT_INDEX_WIDTH (6), .INDIRECT_INDEX_VALUE ({i[0+:2], j[0+:4]}) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[4+4*i+j]), .i_indirect_index (indirect_index), .bit_field_if (bit_field_if) ); CODE expect(registers[4]).to generate_code(:register, :top_down, <<~'CODE') assign indirect_index = {register_if[0].value[0+:1], register_if[0].value[8+:2], register_if[0].value[16+:4]}; rggen_indirect_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h1c), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .INDIRECT_INDEX_WIDTH (7), .INDIRECT_INDEX_VALUE ({1'h0, i[0+:2], j[0+:4]}) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[12+4*i+j]), .i_indirect_index (indirect_index), .bit_field_if (bit_field_if) ); CODE expect(registers[5]).to generate_code(:register, :top_down, <<~'CODE') assign indirect_index = {register_if[0].value[0+:1]}; rggen_indirect_register #( .READABLE (1), .WRITABLE (0), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h20), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .INDIRECT_INDEX_WIDTH (1), .INDIRECT_INDEX_VALUE ({1'h0}) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[20]), .i_indirect_index (indirect_index), .bit_field_if (bit_field_if) ); CODE expect(registers[6]).to generate_code(:register, :top_down, <<~'CODE') assign indirect_index = {register_if[0].value[0+:1]}; rggen_indirect_register #( .READABLE (0), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h24), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .INDIRECT_INDEX_WIDTH (1), .INDIRECT_INDEX_VALUE ({1'h0}) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[21]), .i_indirect_index (indirect_index), .bit_field_if (bit_field_if) ); CODE end end end describe 'sv ral' do include_context 'sv ral common' let(:registers) do create_sv_ral(&register_map_body).registers end it 'レジスタモデル変数#ral_modelを持つ' do expect(registers[1]) .to have_variable :register_block, :ral_model, { name: 'register_1', data_type: 'register_1_reg_model', random: true } expect(registers[2]) .to have_variable :register_block, :ral_model, { name: 'register_2', data_type: 'register_2_reg_model', array_size: [2], array_format: :unpacked, random: true } expect(registers[3]) .to have_variable :register_block, :ral_model, { name: 'register_3', data_type: 'register_3_reg_model', array_size: [2, 4], array_format: :unpacked, random: true } expect(registers[4]) .to have_variable :register_block, :ral_model, { name: 'register_4', data_type: 'register_4_reg_model', array_size: [2, 4], array_format: :unpacked, random: true } expect(registers[5]) .to have_variable :register_block, :ral_model, { name: 'register_5', data_type: 'register_5_reg_model', random: true } expect(registers[6]) .to have_variable :register_block, :ral_model, { name: 'register_6', data_type: 'register_6_reg_model', random: true } end describe '#constructors' do it 'レジスタモデルの生成と構成を行うコードを出力する' do code_block = RgGen::Core::Utility::CodeUtility::CodeBlock.new registers[1..-1].flat_map(&:constructors).each do |constructor| code_block << [constructor, "\n"] end expect(code_block).to match_string(<<~'CODE') `rggen_ral_create_reg_model(register_1, '{}, 8'h10, RW, 1, g_register_1.u_register) `rggen_ral_create_reg_model(register_2[0], '{0}, 8'h14, RW, 1, g_register_2.g[0].u_register) `rggen_ral_create_reg_model(register_2[1], '{1}, 8'h14, RW, 1, g_register_2.g[1].u_register) `rggen_ral_create_reg_model(register_3[0][0], '{0, 0}, 8'h18, RW, 1, g_register_3.g[0].g[0].u_register) `rggen_ral_create_reg_model(register_3[0][1], '{0, 1}, 8'h18, RW, 1, g_register_3.g[0].g[1].u_register) `rggen_ral_create_reg_model(register_3[0][2], '{0, 2}, 8'h18, RW, 1, g_register_3.g[0].g[2].u_register) `rggen_ral_create_reg_model(register_3[0][3], '{0, 3}, 8'h18, RW, 1, g_register_3.g[0].g[3].u_register) `rggen_ral_create_reg_model(register_3[1][0], '{1, 0}, 8'h18, RW, 1, g_register_3.g[1].g[0].u_register) `rggen_ral_create_reg_model(register_3[1][1], '{1, 1}, 8'h18, RW, 1, g_register_3.g[1].g[1].u_register) `rggen_ral_create_reg_model(register_3[1][2], '{1, 2}, 8'h18, RW, 1, g_register_3.g[1].g[2].u_register) `rggen_ral_create_reg_model(register_3[1][3], '{1, 3}, 8'h18, RW, 1, g_register_3.g[1].g[3].u_register) `rggen_ral_create_reg_model(register_4[0][0], '{0, 0}, 8'h1c, RW, 1, g_register_4.g[0].g[0].u_register) `rggen_ral_create_reg_model(register_4[0][1], '{0, 1}, 8'h1c, RW, 1, g_register_4.g[0].g[1].u_register) `rggen_ral_create_reg_model(register_4[0][2], '{0, 2}, 8'h1c, RW, 1, g_register_4.g[0].g[2].u_register) `rggen_ral_create_reg_model(register_4[0][3], '{0, 3}, 8'h1c, RW, 1, g_register_4.g[0].g[3].u_register) `rggen_ral_create_reg_model(register_4[1][0], '{1, 0}, 8'h1c, RW, 1, g_register_4.g[1].g[0].u_register) `rggen_ral_create_reg_model(register_4[1][1], '{1, 1}, 8'h1c, RW, 1, g_register_4.g[1].g[1].u_register) `rggen_ral_create_reg_model(register_4[1][2], '{1, 2}, 8'h1c, RW, 1, g_register_4.g[1].g[2].u_register) `rggen_ral_create_reg_model(register_4[1][3], '{1, 3}, 8'h1c, RW, 1, g_register_4.g[1].g[3].u_register) `rggen_ral_create_reg_model(register_5, '{}, 8'h20, RO, 1, g_register_5.u_register) `rggen_ral_create_reg_model(register_6, '{}, 8'h24, WO, 1, g_register_6.u_register) CODE end end describe '#generate_code' do it 'レジスタレベルのRALモデルの定義を出力する' do expect(registers[1]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_1_reg_model extends rggen_ral_indirect_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction function void setup_index_fields(); setup_index_field("register_0", "bit_field_0", 1'h1); endfunction endclass CODE expect(registers[2]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_2_reg_model extends rggen_ral_indirect_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction function void setup_index_fields(); setup_index_field("register_0", "bit_field_1", array_index[0]); endfunction endclass CODE expect(registers[3]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_3_reg_model extends rggen_ral_indirect_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction function void setup_index_fields(); setup_index_field("register_0", "bit_field_1", array_index[0]); setup_index_field("register_0", "bit_field_2", array_index[1]); endfunction endclass CODE expect(registers[4]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_4_reg_model extends rggen_ral_indirect_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction function void setup_index_fields(); setup_index_field("register_0", "bit_field_0", 1'h0); setup_index_field("register_0", "bit_field_1", array_index[0]); setup_index_field("register_0", "bit_field_2", array_index[1]); endfunction endclass CODE expect(registers[5]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_5_reg_model extends rggen_ral_indirect_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RO, 1, 1'h0, 0) endfunction function void setup_index_fields(); setup_index_field("register_0", "bit_field_0", 1'h0); endfunction endclass CODE expect(registers[6]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_6_reg_model extends rggen_ral_indirect_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, WO, 0, 1'h0, 1) endfunction function void setup_index_fields(); setup_index_field("register_0", "bit_field_0", 1'h0); endfunction endclass CODE end end end end <file_sep># frozen_string_literal: true RSpec.describe 'register/type/external' do include_context 'clean-up builder' include_context 'register map common' before(:all) do RgGen.enable(:global, [:bus_width, :address_width, :fold_sv_interface_port]) RgGen.enable(:register_block, :byte_size) RgGen.enable(:register, [:name, :type, :offset_address, :size]) RgGen.enable(:register, :type, :external) RgGen.enable(:bit_field, :name) end describe 'register map' do before(:all) do delete_configuration_facotry delete_register_map_factory end def create_registers(&block) configuration = create_configuration(bus_width: 32, address_width: 16) register_map = create_register_map(configuration) do register_block do byte_size 256 instance_exec(&block) end end register_map.registers end specify 'レジスタ型は:external' do registers = create_registers do register { name 'register_0'; offset_address 0x00; type :external } end expect(registers[0].type).to eq :external end specify 'アクセス属性は読み書き可能' do registers = create_registers do register { name 'register_0'; offset_address 0x00; type :external } end expect(registers[0]).to be_readable.and be_writable end it 'ビットフィールドを持たない' do registers = create_registers do register do name 'register_0' offset_address 0x00 type :external bit_field { name :foo } bit_field { name :bar } end end expect(registers[0].bit_fields).to be_empty end it '配列レジスタではない' do registers = create_registers do register { name 'register_0'; offset_address 0x00; type :external } register { name 'register_1'; offset_address 0x10; type :external; size [1] } register { name 'register_2'; offset_address 0x20; type :external; size [16] } end expect(registers[0]).not_to be_array expect(registers[1]).not_to be_array expect(registers[2]).not_to be_array end it '単一サイズ定義のみ対応している' do expect { create_registers do register { name 'register_0'; offset_address 0x00; type :external; size [1, 1] } end }.to raise_register_map_error 'external register type supports single size definition only' end end describe 'sv rtl' do include_context 'sv rtl common' before(:all) do RgGen.enable(:register_block, :sv_rtl_top) RgGen.enable(:register, :sv_rtl_top) end def create_registers(fold_sv_interface_port, &body) configuration = create_configuration(fold_sv_interface_port: fold_sv_interface_port) create_sv_rtl(configuration, &body).registers end context 'fold_sv_interface_portが有効になっている場合' do let(:register) do registers = create_registers(true) do byte_size 256 register { name 'register_0'; offset_address 0x00; type :external; size [1] } end registers.first end it 'インターフェースポート#bus_ifを持つ' do expect(register) .to have_interface_port :register_block, :bus_if, { name: 'register_0_bus_if', interface_type: 'rggen_bus_if', modport: 'master' } end specify '#bus_ifは個別ポートに展開されない' do expect(register) .to not_have_port :register_block, :valid, { name: 'o_register_0_valid', data_type: :logic, direction: :output, width: 1 } expect(register) .to not_have_port :register_block, :address, { name: 'o_register_0_address', data_type: :logic, direction: :output, width: 8 } expect(register) .to not_have_port :register_block, :write, { name: 'o_register_0_write', data_type: :logic, direction: :output, width: 1 } expect(register) .to not_have_port :register_block, :write_data, { name: 'o_register_0_data', data_type: :logic, direction: :output, width: 32 } expect(register) .to not_have_port :register_block, :strobe, { name: 'o_register_0_strobe', data_type: :logic, direction: :output, width: 4 } expect(register) .to not_have_port :register_block, :ready, { name: 'i_register_0_ready', data_type: :logic, direction: :input, width: 1 } expect(register) .to not_have_port :register_block, :status, { name: 'i_register_0_status', data_type: :logic, direction: :input, width: 2 } expect(register) .to not_have_port :register_block, :read_data, { name: 'i_register_0_data', data_type: :logic, direction: :input, width: 32 } end end context 'fold_sv_interface_portが無効になっている場合' do let(:register) do registers = create_registers(false) do byte_size 256 register { name 'register_0'; offset_address 0x00; type :external; size [1] } end registers.first end it '個別ポートに展開された#bus_ifを持つ' do expect(register) .to have_port :register_block, :valid, { name: 'o_register_0_valid', data_type: :logic, direction: :output, width: 1 } expect(register) .to have_port :register_block, :address, { name: 'o_register_0_address', data_type: :logic, direction: :output, width: 8 } expect(register) .to have_port :register_block, :write, { name: 'o_register_0_write', data_type: :logic, direction: :output, width: 1 } expect(register) .to have_port :register_block, :write_data, { name: 'o_register_0_data', data_type: :logic, direction: :output, width: 32 } expect(register) .to have_port :register_block, :strobe, { name: 'o_register_0_strobe', data_type: :logic, direction: :output, width: 4 } expect(register) .to have_port :register_block, :ready, { name: 'i_register_0_ready', data_type: :logic, direction: :input, width: 1 } expect(register) .to have_port :register_block, :status, { name: 'i_register_0_status', data_type: :logic, direction: :input, width: 2 } expect(register) .to have_port :register_block, :read_data, { name: 'i_register_0_data', data_type: :logic, direction: :input, width: 32 } end it 'rggen_bus_ifのインスタンスを持つ' do expect(register) .to have_interface :register, :bus_if, { name: 'bus_if', interface_type: 'rggen_bus_if', parameter_values: [8, 32] } end end describe '#generate_code' do it 'rggen_exernal_registerをインスタンスするコードを出力する' do registers = create_registers(true) do byte_size 256 register { name 'register_0'; offset_address 0x00; type :external; size [1] } register { name 'register_1'; offset_address 0x80; type :external; size [32] } end expect(registers[0]).to generate_code(:register, :top_down, <<~'CODE') rggen_external_register #( .ADDRESS_WIDTH (8), .BUS_WIDTH (32), .START_ADDRESS (8'h00), .END_ADDRESS (8'h03) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[0]), .bus_if (register_0_bus_if) ); CODE expect(registers[1]).to generate_code(:register, :top_down, <<~'CODE') rggen_external_register #( .ADDRESS_WIDTH (8), .BUS_WIDTH (32), .START_ADDRESS (8'h80), .END_ADDRESS (8'hff) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[1]), .bus_if (register_1_bus_if) ); CODE registers = create_registers(false) do byte_size 256 register { name 'register_0'; offset_address 0x00; type :external; size [1] } register { name 'register_1'; offset_address 0x80; type :external; size [32] } end expect(registers[0]).to generate_code(:register, :top_down, <<~'CODE') rggen_external_register #( .ADDRESS_WIDTH (8), .BUS_WIDTH (32), .START_ADDRESS (8'h00), .END_ADDRESS (8'h03) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[0]), .bus_if (bus_if) ); assign o_register_0_valid = bus_if.valid; assign o_register_0_address = bus_if.address; assign o_register_0_write = bus_if.write; assign o_register_0_data = bus_if.write_data; assign o_register_0_strobe = bus_if.strobe; assign bus_if.ready = i_register_0_ready; assign bus_if.status = rggen_status'(i_register_0_status); assign bus_if.read_data = i_register_0_data; CODE expect(registers[1]).to generate_code(:register, :top_down, <<~'CODE') rggen_external_register #( .ADDRESS_WIDTH (8), .BUS_WIDTH (32), .START_ADDRESS (8'h80), .END_ADDRESS (8'hff) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[1]), .bus_if (bus_if) ); assign o_register_1_valid = bus_if.valid; assign o_register_1_address = bus_if.address; assign o_register_1_write = bus_if.write; assign o_register_1_data = bus_if.write_data; assign o_register_1_strobe = bus_if.strobe; assign bus_if.ready = i_register_1_ready; assign bus_if.status = rggen_status'(i_register_1_status); assign bus_if.read_data = i_register_1_data; CODE end end end describe 'sv ral' do include_context 'sv ral common' let(:registers) do ral = create_sv_ral do byte_size 256 register { name 'register_0'; offset_address 0x00; type :external; size [1] } register { name 'register_1'; offset_address 0x80; type :external; size [32] } end ral.registers end it '外部レジスタブロックモデル変数#ral_modelを持つ' do expect(registers[0]) .to have_variable :register_block, :ral_model, { name: 'register_0', data_type: 'REGISTER_0', random: true } expect(registers[1]) .to have_variable :register_block, :ral_model, { name: 'register_1', data_type: 'REGISTER_1', random: true } end it 'パラメータ#model_typeと#integrateを持つ' do expect(registers[0]) .to have_parameter :register_block, :model_type, { name: 'REGISTER_0', data_type: 'type', default: 'rggen_ral_block' } expect(registers[0]) .to have_parameter :register_block, :integrate_model, { name: 'INTEGRATE_REGISTER_0', data_type: 'bit', default: 1 } expect(registers[1]) .to have_parameter :register_block, :model_type, { name: 'REGISTER_1', data_type: 'type', default: 'rggen_ral_block' } expect(registers[1]) .to have_parameter :register_block, :integrate_model, { name: 'INTEGRATE_REGISTER_1', data_type: 'bit', default: 1 } end describe '#constructors' do it '外部レジスタブロックモデルの生成と構成を行うコードを出力する' do code_block = RgGen::Core::Utility::CodeUtility::CodeBlock.new registers.flat_map(&:constructors).each do |constructor| code_block << [constructor, "\n"] end expect(code_block).to match_string(<<~'CODE') `rggen_ral_create_block_model(register_0, 8'h00, this, INTEGRATE_REGISTER_0) `rggen_ral_create_block_model(register_1, 8'h80, this, INTEGRATE_REGISTER_1) CODE end end end end <file_sep># frozen_string_literal: true RgGen.define_list_item_feature(:bit_field, :type, [:rwc, :rwe, :rwl]) do register_map do read_write volatile? { bit_field.type == :rwc || !bit_field.reference? } initial_value require: true reference use: true, width: 1 end sv_rtl do build do if clear_port? input :register_block, :clear, { name: "i_#{full_name}_clear", data_type: :logic, width: 1, array_size: array_size, array_format: array_port_format } end if enable_port? input :register_block, :enable, { name: "i_#{full_name}_enable", data_type: :logic, width: 1, array_size: array_size, array_format: array_port_format } end if lock_port? input :register_block, :lock, { name: "i_#{full_name}_lock", data_type: :logic, width: 1, array_size: array_size, array_format: array_port_format } end output :register_block, :value_out, { name: "o_#{full_name}", data_type: :logic, width: width, array_size: array_size, array_format: array_port_format } end main_code :bit_field, from_template: true private def clear_port? bit_field.type == :rwc && !bit_field.reference? end def enable_port? bit_field.type == :rwe && !bit_field.reference? end def lock_port? bit_field.type == :rwl && !bit_field.reference? end def control_signal reference_bit_field || control_port[loop_variables] end def control_port case bit_field.type when :rwc clear when :rwe enable when :rwl lock end end end end RgGen.define_list_item_feature(:bit_field, :type, :rwc) do sv_ral do access 'RW' end end RgGen.define_list_item_feature(:bit_field, :type, [:rwe, :rwl]) do sv_ral do model_name do "rggen_ral_#{bit_field.type}_field #(#{reference_names})" end private def reference_names reference = bit_field.reference register = reference&.register [register&.name, reference&.name] .map { |name| string(name) } .join(', ') end end end <file_sep># frozen_string_literal: true RgGen.define_list_feature(:register, :type) do register_map do base_feature do define_helpers do def writable?(&block) @writability = block end def readable?(&block) @readability = block end attr_reader :writability attr_reader :readability def no_bit_fields @no_bit_fields = true end def need_bit_fields? !@no_bit_fields end def support_array_register @support_array_register = true end def support_array_register? @support_array_register || false end def byte_size(&block) @byte_size = block if block_given? @byte_size end def support_overlapped_address @support_overlapped_address = true end def support_overlapped_address? @support_overlapped_address || false end end property :type, body: -> { @type || :default } property :writable?, forward_to: :writability property :readable?, forward_to: :readability property :width, body: -> { @width ||= calc_width } property :byte_width, body: -> { @byte_width ||= width / 8 } property :array?, forward_to: :array_register? property :array_size, body: -> { (array? && register.size) || nil } property :count, body: -> { @count ||= calc_count } property :byte_size, body: -> { @byte_size ||= calc_byte_size } property :match_type?, body: ->(register) { register.type == type } property :support_overlapped_address?, forward_to_helper: true build do |value| @type = value[:type] @options = value[:options] helper.need_bit_fields? || register.need_no_children end verify(:component) do error_condition do helper.need_bit_fields? && register.bit_fields.empty? end message { 'no bit fields are given' } end private attr_reader :options def writability if @writability.nil? block = helper.writability || default_writability @writability = instance_exec(&block) end @writability end def default_writability -> { register.bit_fields.any?(&:writable?) } end def readability if @readability.nil? block = helper.readability || default_readability @readability = instance_exec(&block) end @readability end def default_readability lambda do block = ->(bit_field) { bit_field.readable? || bit_field.reserved? } register.bit_fields.any?(&block) end end def calc_width bus_width = configuration.bus_width if helper.need_bit_fields? ((collect_msb.max + bus_width) / bus_width) * bus_width else bus_width end end def collect_msb register.bit_fields.collect do |bit_field| bit_field.msb((bit_field.sequence_size || 1) - 1) end end def array_register? helper.support_array_register? && !register.size.nil? end def calc_count Array(array_size).reduce(1, :*) end def calc_byte_size if helper.byte_size instance_exec(&helper.byte_size) else Array(register.size).reduce(1, :*) * byte_width end end end default_feature do support_array_register verify(:feature) do error_condition { @type } message { "unknown register type: #{@type.inspect}" } end end factory do convert_value do |value| type, options = split_input_value(value) { type: find_type(type), options: Array(options) } end def select_feature(cell) if cell.empty_value? target_feature else target_features[cell.value[:type]] end end private def split_input_value(value) if value.is_a?(String) split_string_value(value) else input_value = Array(value) [input_value[0], input_value[1..-1]] end end def split_string_value(value) type, options = split_string(value, ':', 2) [type, split_string(options, /[,\n]/, 0)] end def split_string(value, separator, limit) value&.split(separator, limit)&.map(&:strip) end def find_type(type) types = target_features.keys types.find(&type.to_sym.method(:casecmp?)) || type end end end sv_rtl do base_feature do private def readable register.readable? && 1 || 0 end def writable register.writable? && 1 || 0 end def bus_width configuration.bus_width end def address_width register_block.local_address_width end def offset_address hex(register.offset_address, address_width) end def width register.width end def valid_bits bits = register.bit_fields.map(&:bit_map).inject(:|) hex(bits, register.width) end def register_index register.local_index || 0 end def register_if register_block.register_if[register.index] end def bit_field_if register.bit_field_if end end default_feature do template_path = File.join(__dir__, 'type', 'default_sv_rtl.erb') main_code :register, from_template: template_path end factory do def select_feature(_configuration, register) target_features[register.type] end end end sv_ral do base_feature do define_helpers do def model_name(&body) @model_name = body if block_given? @model_name end def offset_address(&body) @offset_address = body if block_given? @offset_address end def unmapped @unmapped = true end def unmapped? !@unmapped.nil? end def constructor(&body) @constructor = body if block_given? @constructor end end export :constructors build do variable :register_block, :ral_model, { name: register.name, data_type: model_name, array_size: register.array_size, random: true } end def constructors (array_index_list || [nil]).map.with_index do |array_index, i| constructor_code(array_index, i) end end private def model_name if helper.model_name instance_eval(&helper.model_name) else "#{register.name}_reg_model" end end def array_index_list (register.array? || nil) && begin index_table = register.array_size.map { |size| (0...size).to_a } index_table[0].product(*index_table[1..-1]) end end def constructor_code(array_index, index) if helper.constructor instance_exec(array_index, index, &helper.constructor) else macro_call( :rggen_ral_create_reg_model, arguments(array_index, index) ) end end def arguments(array_index, index) [ ral_model[array_index], array(array_index), offset_address(index), access_rights, unmapped, hdl_path(array_index) ] end def offset_address(index = 0) address = if helper.offset_address instance_exec(index, &helper.offset_address) else register.offset_address + register.byte_width * index end hex(address, register_block.local_address_width) end def access_rights if register.writable? && register.readable? 'RW' elsif register.writable? 'WO' else 'RO' end end def unmapped helper.unmapped? && 1 || 0 end def hdl_path(array_index) [ "g_#{register.name}", *Array(array_index).map { |i| "g[#{i}]" }, 'u_register' ].join('.') end def variables register.declarations(:register, :variable) end def field_model_constructors register.bit_fields.flat_map(&:constructors) end end default_feature do main_code :ral_package do class_definition(model_name) do |sv_class| sv_class.base 'rggen_ral_reg' sv_class.variables variables sv_class.body { model_body } end end private def model_body process_template(File.join(__dir__, 'type', 'default_sv_ral.erb')) end end factory do def select_feature(_configuration, register) target_features[register.type] end end end end <file_sep># frozen_string_literal: true module RgGen module BuiltIn VERSION = '0.11.0' end end <file_sep># frozen_string_literal: true RgGen.define_simple_feature(:register, :size) do register_map do property :size input_pattern [ /(#{integer}(:?,#{integer})*)/, /\[(#{integer}(:?,#{integer})*)\]/ ], match_automatically: false build do |values| @size = parse_values(values) end verify(:feature) do error_condition { size && !size.all?(&:positive?) } message do "non positive value(s) are not allowed for register size: #{size}" end end private def parse_values(values) Array( values.is_a?(String) && parse_string_values(values) || values ).map(&method(:convert_value)) end def parse_string_values(values) if match_pattern(values) split_match_data(match_data) else error "illegal input value for register size: #{values.inspect}" end end def split_match_data(match_data) match_data.captures.first.split(',') end def convert_value(value) Integer(value) rescue ArgumentError, TypeError error "cannot convert #{value.inspect} into register size" end end end <file_sep># frozen_string_literal: true require 'bundler/setup' require 'rggen/core' require 'rggen/devtools/spec_helper' builder = RgGen::Core::Builder.create RgGen.builder(builder) RSpec.configure do |config| RgGen::Devtools::SpecHelper.setup(config) end RGGEN_ROOT = File.expand_path('..', __dir__) require 'rggen' require 'rggen/spreadsheet_loader' <file_sep># frozen_string_literal: true RgGen.define_list_feature(:bit_field, :type) do register_map do base_feature do define_helpers do def read_write @readable = true @writable = true end def read_only @readable = true @writable = false end def write_only @readable = false @writable = true end def reserved @readable = false @writable = false end def readable? @readable.nil? || @readable end def writable? @writable.nil? || @writable end def volatile @volatility = -> { true } end def non_volatile @volatility = -> { false } end def volatile?(&block) @volatility = block end attr_reader :volatility def options @options ||= {} end def initial_value(**option) options[:initial_value] = option end def reference(**option) options[:reference] = option end end property :type property :readable?, forward_to_helper: true property :writable?, forward_to_helper: true property :read_only?, body: -> { readable? && !writable? } property :write_only?, body: -> { writable? && !readable? } property :reserved?, body: -> { !(readable? || writable?) } property :volatile?, forward_to: :volatility property :options, forward_to_helper: true build { |value| @type = value } private def volatility if @volatility.nil? @volatility = helper.volatility.nil? || instance_exec(&helper.volatility) end @volatility end end default_feature do verify(:feature) do error_condition { !type } message { 'no bit field type is given' } end verify(:feature) do error_condition { type } message { "unknown bit field type: #{type.inspect}" } end end factory do convert_value do |value| types = target_features.keys types.find(&value.to_sym.method(:casecmp?)) || value end def select_feature(cell) target_features[cell.value] end end end sv_rtl do base_feature do private def array_port_format configuration.array_port_format end def full_name bit_field.full_name('_') end def width bit_field.width end def array_size bit_field.array_size end def initial_value hex(bit_field.initial_value, bit_field.width) end def mask reference_bit_field || hex(2**bit_field.width - 1, bit_field.width) end def reference_bit_field bit_field.reference? && bit_field .find_reference(register_block.bit_fields) .value( register.local_index, bit_field.local_index, bit_field.reference_width ) end def bit_field_if bit_field.bit_field_sub_if end def loop_variables bit_field.loop_variables end end factory do def select_feature(_configuration, bit_field) target_features[bit_field.type] end end end sv_ral do base_feature do define_helpers do attr_setter :access def model_name(name = nil, &block) @model_name = name || block || @model_name @model_name end end export :access export :model_name export :constructors build do variable :register, :ral_model, { name: bit_field.name, data_type: model_name, array_size: array_size, random: true } end def access (helper.access || bit_field.type).to_s.upcase end def model_name if helper.model_name&.is_a?(Proc) instance_eval(&helper.model_name) else helper.model_name || :rggen_ral_field end end def constructors (bit_field.sequence_size&.times || [nil]).map do |index| macro_call( :rggen_ral_create_field_model, arguments(index) ) end end private def array_size Array(bit_field.sequence_size) end def arguments(index) [ ral_model[index], bit_field.lsb(index), bit_field.width, access, volatile, reset_value, valid_reset ] end def volatile bit_field.volatile? && 1 || 0 end def reset_value hex(bit_field.initial_value, bit_field.width) end def valid_reset bit_field.initial_value? && 1 || 0 end end default_feature do end factory do def select_feature(_configuration, bit_field) target_features[bit_field.type] end end end end <file_sep># frozen_string_literal: true RSpec.describe 'register/type/default' do include_context 'clean-up builder' before(:all) do RgGen.enable(:global, [:bus_width, :address_width, :array_port_format]) RgGen.enable(:register_block, [:name, :byte_size]) RgGen.enable(:register, [:name, :offset_address, :size, :type]) RgGen.enable(:bit_field, [:name, :bit_assignment, :type, :initial_value, :reference]) RgGen.enable(:bit_field, :type, [:rw, :ro, :wo]) end let(:register_map_body) do proc do name 'block_0' byte_size 256 register do name 'register_0' offset_address 0x00 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_1' offset_address 0x10 size [4] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_2' offset_address 0x20 size [2, 2] bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :rw; initial_value 0 } end register do name 'register_3' offset_address 0x30 bit_field { name 'bit_field_0'; bit_assignment lsb: 0, width: 32; type :rw; initial_value 0 } end register do name 'register_4' offset_address 0x40 bit_field { name 'bit_field_0'; bit_assignment lsb: 4, width: 4, sequence_size: 4, step: 8; type :rw; initial_value 0 } end register do name 'register_5' offset_address 0x50 bit_field { name 'bit_field_0'; bit_assignment lsb: 32; type :rw; initial_value 0 } end register do name 'register_6' offset_address 0x60 bit_field { name 'bit_field_0'; bit_assignment lsb: 4, width: 4, sequence_size: 8, step: 8; type :rw; initial_value 0 } end register do name 'register_7' offset_address 0x70 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :ro } end register do name 'register_8' offset_address 0x80 bit_field { name 'bit_field_0'; bit_assignment lsb: 0; type :wo; initial_value 0 } end end end describe 'sv rtl' do include_context 'sv rtl common' before(:all) do RgGen.enable(:register_block, :sv_rtl_top) RgGen.enable(:register, :sv_rtl_top) RgGen.enable(:bit_field, :sv_rtl_top) end describe '#generate_code' do let(:registers) { create_sv_rtl(&register_map_body).registers } it 'rggen_default_registerをインスタンスするコードを出力する' do expect(registers[0]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h00), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[0]), .bit_field_if (bit_field_if) ); CODE expect(registers[1]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h10), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .REGISTER_INDEX (i) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[1+i]), .bit_field_if (bit_field_if) ); CODE expect(registers[2]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h20), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .REGISTER_INDEX (2*i+j) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[5+2*i+j]), .bit_field_if (bit_field_if) ); CODE expect(registers[3]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h30), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'hffffffff), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[9]), .bit_field_if (bit_field_if) ); CODE expect(registers[4]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h40), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'hf0f0f0f0), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[10]), .bit_field_if (bit_field_if) ); CODE expect(registers[5]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h50), .BUS_WIDTH (32), .DATA_WIDTH (64), .VALID_BITS (64'h0000000100000000), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[11]), .bit_field_if (bit_field_if) ); CODE expect(registers[6]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h60), .BUS_WIDTH (32), .DATA_WIDTH (64), .VALID_BITS (64'hf0f0f0f0f0f0f0f0), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[12]), .bit_field_if (bit_field_if) ); CODE expect(registers[7]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (1), .WRITABLE (0), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h70), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[13]), .bit_field_if (bit_field_if) ); CODE expect(registers[8]).to generate_code(:register, :top_down, <<~'CODE') rggen_default_register #( .READABLE (0), .WRITABLE (1), .ADDRESS_WIDTH (8), .OFFSET_ADDRESS (8'h80), .BUS_WIDTH (32), .DATA_WIDTH (32), .VALID_BITS (32'h00000001), .REGISTER_INDEX (0) ) u_register ( .i_clk (i_clk), .i_rst_n (i_rst_n), .register_if (register_if[14]), .bit_field_if (bit_field_if) ); CODE end end end describe 'sv ral' do include_context 'sv ral common' let(:registers) { create_sv_ral(&register_map_body).registers } it 'レジスタモデル変数#ral_modelを持つ' do expect(registers[0]) .to have_variable :register_block, :ral_model, { name: 'register_0', data_type: 'register_0_reg_model', random: true } expect(registers[1]) .to have_variable :register_block, :ral_model, { name: 'register_1', data_type: 'register_1_reg_model', array_size: [4], array_format: :unpacked, random: true } expect(registers[2]) .to have_variable :register_block, :ral_model, { name: 'register_2', data_type: 'register_2_reg_model', array_size: [2, 2], array_format: :unpacked, random: true } end describe '#constructors' do it 'レジスタモデルの生成と構成を行うコードを出力する' do code_block = RgGen::Core::Utility::CodeUtility::CodeBlock.new registers.flat_map(&:constructors).each do |constructor| code_block << [constructor, "\n"] end expect(code_block).to match_string(<<~'CODE') `rggen_ral_create_reg_model(register_0, '{}, 8'h00, RW, 0, g_register_0.u_register) `rggen_ral_create_reg_model(register_1[0], '{0}, 8'h10, RW, 0, g_register_1.g[0].u_register) `rggen_ral_create_reg_model(register_1[1], '{1}, 8'h14, RW, 0, g_register_1.g[1].u_register) `rggen_ral_create_reg_model(register_1[2], '{2}, 8'h18, RW, 0, g_register_1.g[2].u_register) `rggen_ral_create_reg_model(register_1[3], '{3}, 8'h1c, RW, 0, g_register_1.g[3].u_register) `rggen_ral_create_reg_model(register_2[0][0], '{0, 0}, 8'h20, RW, 0, g_register_2.g[0].g[0].u_register) `rggen_ral_create_reg_model(register_2[0][1], '{0, 1}, 8'h24, RW, 0, g_register_2.g[0].g[1].u_register) `rggen_ral_create_reg_model(register_2[1][0], '{1, 0}, 8'h28, RW, 0, g_register_2.g[1].g[0].u_register) `rggen_ral_create_reg_model(register_2[1][1], '{1, 1}, 8'h2c, RW, 0, g_register_2.g[1].g[1].u_register) `rggen_ral_create_reg_model(register_3, '{}, 8'h30, RW, 0, g_register_3.u_register) `rggen_ral_create_reg_model(register_4, '{}, 8'h40, RW, 0, g_register_4.u_register) `rggen_ral_create_reg_model(register_5, '{}, 8'h50, RW, 0, g_register_5.u_register) `rggen_ral_create_reg_model(register_6, '{}, 8'h60, RW, 0, g_register_6.u_register) `rggen_ral_create_reg_model(register_7, '{}, 8'h70, RO, 0, g_register_7.u_register) `rggen_ral_create_reg_model(register_8, '{}, 8'h80, WO, 0, g_register_8.u_register) CODE end end describe '#generate_code' do it 'レジスタレベルのRALモデルの定義を出力する' do expect(registers[0]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_0_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction endclass CODE expect(registers[1]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_1_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction endclass CODE expect(registers[2]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_2_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RW, 0, 1'h0, 1) endfunction endclass CODE expect(registers[3]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_3_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 32, RW, 0, 32'h00000000, 1) endfunction endclass CODE expect(registers[4]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_4_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0[4]; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0[0], 4, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[1], 12, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[2], 20, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[3], 28, 4, RW, 0, 4'h0, 1) endfunction endclass CODE expect(registers[5]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_5_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 64, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 32, 1, RW, 0, 1'h0, 1) endfunction endclass CODE expect(registers[6]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_6_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0[8]; function new(string name); super.new(name, 64, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0[0], 4, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[1], 12, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[2], 20, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[3], 28, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[4], 36, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[5], 44, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[6], 52, 4, RW, 0, 4'h0, 1) `rggen_ral_create_field_model(bit_field_0[7], 60, 4, RW, 0, 4'h0, 1) endfunction endclass CODE expect(registers[7]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_7_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, RO, 1, 1'h0, 0) endfunction endclass CODE expect(registers[8]).to generate_code(:ral_package, :bottom_up, <<~'CODE') class register_8_reg_model extends rggen_ral_reg; rand rggen_ral_field bit_field_0; function new(string name); super.new(name, 32, 0); endfunction function void build(); `rggen_ral_create_field_model(bit_field_0, 0, 1, WO, 0, 1'h0, 1) endfunction endclass CODE end end end end <file_sep># frozen_string_literal: true lib = File.expand_path('lib', __dir__) $LOAD_PATH.include?(lib) || $LOAD_PATH.unshift(lib) require 'rggen/version' Gem::Specification.new do |spec| spec.name = 'rggen' spec.version = RgGen::VERSION spec.authors = ['<NAME>'] spec.email = ['<EMAIL>'] spec.summary = 'Code generation tool for control/status registers' spec.description = <<~'DESCRIPTION' RgGen is a code generation tool for ASIC/IP/FPGA/RTL engineers. It will automatically generate soruce code related to control/status registers (CSR), e.g. SytemVerilog RTL, UVM RAL model, from human readable register map specifications. DESCRIPTION spec.homepage = 'https://github.com/rggen/rggen' spec.license = 'MIT' spec.metadata = { 'bug_tracker_uri' => 'https://github.com/rggen/rggen/issues', 'mailing_list_uri' => 'https://groups.google.com/d/forum/rggen', 'source_code_uri' => 'https://github.com/rggen/rggen', 'wiki_uri' => 'https://github.com/rggen/rggen/wiki' } spec.files = `git ls-files lib sample LICENSE CODE_OF_CONDUCT.md README.md`.split($RS) spec.require_paths = ['lib'] spec.required_ruby_version = '>= 2.3' spec.add_runtime_dependency 'rggen-core', '~> 0.11' spec.add_runtime_dependency 'rggen-spreadsheet-loader', '~> 0.10' spec.add_runtime_dependency 'rggen-systemverilog', '~> 0.11' spec.add_development_dependency 'bundler' end <file_sep>[![Gem Version](https://badge.fury.io/rb/rggen.svg)](https://badge.fury.io/rb/rggen) [![Build Status](https://travis-ci.org/rggen/rggen.svg?branch=master)](https://travis-ci.org/rggen/rggen) [![Maintainability](https://api.codeclimate.com/v1/badges/5ee2248300ec0517e597/maintainability)](https://codeclimate.com/github/rggen/rggen/maintainability) [![codecov](https://codecov.io/gh/rggen/rggen/branch/master/graph/badge.svg)](https://codecov.io/gh/rggen/rggen) [![Quality Gate Status](https://sonarcloud.io/api/project_badges/measure?project=rggen_rggen&metric=alert_status)](https://sonarcloud.io/dashboard?id=rggen_rggen) [![Gitter](https://badges.gitter.im/rggen/rggen.svg)](https://gitter.im/rggen/rggen?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) # RgGen RgGen is a code generation tool for ASIC/IP/FPGA/RTL engineers. It will automatically generate soruce code related to control/status registers (CSR), e.g. SytemVerilog RTL, UVM RAL model, from human readable register map specifications. RgGen has following features: * Generate source files related to CSR from register map specifications * Source files listed below will be generated: * SystemVerilog RTL * UVM RAL model * Register map specifications can be written in human readable format * Supported formats are listed below: * Ruby with APIs to describe register map information * YAML * JSON * Spreadsheet (XLSX, XLS, OSD, CSV) * Costomize RgGen for you environment * E.g. add special bit field types ## Installation ### Ruby RgGen is written in the [Ruby](https://www.ruby-lang.org/en/about/) programing language and its required version is 2.3 or later. You need to install any of these versions of Ruby before installing RgGen tool. To install Ruby, see [this page](https://www.ruby-lang.org/en/downloads/). ### Installatin Command RgGen depends on [RgGen::Core](https://github.com/rggen/rggen-core), [RgGen::SystemVerilog](https://github.com/rggen/rggen-systemverilog), [RgGen::SpreadsheetLoader](https://github.com/rggen/rggen-spreadsheet-loader) and other Ruby libraries. To install RgGen and dependencies, use the command below: ``` $ gem install rggen ``` RgGen and dependencies will be installed on your system root. If you want to install them on other location, you need to specify install path and set the `GEM_PATH` environment variable: ``` $ gem install --install-dir YOUR_INSTALL_DIRECTORY rggen $ export GEM_PATH=YOUR_INSTALL_DIRECTORY ``` You would get the following error message duaring installation if you have the old RgGen (version < 0.9). ``` ERROR: Error installing rggen: "rggen" from rggen-core conflicts with installed executable from rggen ``` To resolve the above error, there are three solutions. See [this page](https://github.com/rggen/rggen/wiki/Resolve-Confliction-of-Installed-Executable) ## Usage See [Wiki documents](https://github.com/rggen/rggen/wiki). ## Contact Feedbacks, bug reports, questions and etc. are wellcome! You can post them by using following ways: * [GitHub Issue Tracker](https://github.com/rggen/rggen/issues) * [Chat Room](https://gitter.im/rggen/rggen) * [Mailing List](https://groups.google.com/d/forum/rggen) * [Mail](mailto:<EMAIL>) ## See Also * https://github.com/rggen/rggen-core * https://github.com/rggen/rggen-systemverilog * https://github.com/rggen/rggen-spreadsheet-loader ## Copyright & License Copyright &copy; 2019 <NAME>. RgGen is licensed unther the [MIT License](https://opensource.org/licenses/MIT), see [LICENSE](LICENSE) for futher detils. ## Code of Conduct Everyone interacting in the RgGen project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/rggen/rggen/blob/master/CODE_OF_CONDUCT.md). <file_sep># frozen_string_literal: true RSpec.describe 'register_block/protocol' do include_context 'configuration common' include_context 'clean-up builder' describe 'configuration' do before(:all) do RgGen.define_list_item_feature(:register_block, :protocol, [:foo, :bar, :baz]) do sv_rtl {} end end before do RgGen.enable(:register_block, :protocol) end after do RgGen.disable(:register_block, :protocol) delete_configuration_facotry end describe '#protocol' do before do RgGen.enable(:register_block, :protocol, [:qux, :baz, :foo]) end specify '既定値は定義されているプロトコルで、最初に有効になったプロトコル' do configuration = create_configuration expect(configuration).to have_property(:protocol, :baz) configuration = create_configuration(protocol: nil) expect(configuration).to have_property(:protocol, :baz) configuration = create_configuration(protocol: '') expect(configuration).to have_property(:protocol, :baz) end it '指定されたホストプロトコルを返す' do { foo: [ 'foo', 'FOO', random_string(/foo/i) ], baz: [ 'baz', 'BAZ', random_string(/baz/i) ] }.each do |protocol, values| values.each do |value| configuration = create_configuration(protocol: value) expect(configuration).to have_property(:protocol, protocol) configuration = create_configuration(protocol: value.to_sym) expect(configuration).to have_property(:protocol, protocol) end end end end describe 'エラーチェック' do context '使用可能なプロトコルがない場合' do before do RgGen.enable(:register_block, :protocol, :qux) end it 'ConfigurationErrorを起こす' do expect { create_configuration }.to raise_configuration_error 'no protocols are available' expect { create_configuration(protocol: nil) }.to raise_configuration_error 'no protocols are available' expect { create_configuration(protocol: '') }.to raise_configuration_error 'no protocols are available' end end context '有効になっていないプロトコルを指定した場合' do before do RgGen.enable(:register_block, :protocol, [:foo, :bar, :qux]) end it 'ConfigurationErrorを起こす' do value = random_string(/baz/i) expect { create_configuration(protocol: value) }.to raise_configuration_error "unknown protocol: #{value.inspect}" value = random_string(/baz/i).to_sym expect { create_configuration(protocol: value) }.to raise_configuration_error "unknown protocol: #{value.inspect}" end end context '定義されていないプロトコルを指定した場合' do before do RgGen.enable(:register_block, :protocol, [:foo, :bar, :qux]) end it 'ConfigurationErrorを起こす' do value = random_string(/qux/i) expect { create_configuration(protocol: value) }.to raise_configuration_error "unknown protocol: #{value.inspect}" value = random_string(/qux/i).to_sym expect { create_configuration(protocol: value) }.to raise_configuration_error "unknown protocol: #{value.inspect}" end end end end end <file_sep># frozen_string_literal: true RgGen.define_list_item_feature(:register, :type, :external) do register_map do writable? { true } readable? { true } no_bit_fields verify(:component) do error_condition { register.size && register.size.length > 1 } message do 'external register type supports single size definition only' end end end sv_rtl do build do if configuration.fold_sv_interface_port? interface_port :register_block, :bus_if, { name: "#{register.name}_bus_if", interface_type: 'rggen_bus_if', modport: 'master' } else output :register_block, :valid, { name: "o_#{register.name}_valid", data_type: :logic, width: 1 } output :register_block, :address, { name: "o_#{register.name}_address", data_type: :logic, width: address_width } output :register_block, :write, { name: "o_#{register.name}_write", data_type: :logic, width: 1 } output :register_block, :write_data, { name: "o_#{register.name}_data", data_type: :logic, width: bus_width } output :register_block, :strobe, { name: "o_#{register.name}_strobe", data_type: :logic, width: byte_width } input :register_block, :ready, { name: "i_#{register.name}_ready", data_type: :logic, width: 1 } input :register_block, :status, { name: "i_#{register.name}_status", data_type: :logic, width: 2 } input :register_block, :read_data, { name: "i_#{register.name}_data", data_type: :logic, width: bus_width } interface :register, :bus_if, { name: 'bus_if', interface_type: 'rggen_bus_if', parameter_values: [address_width, bus_width], variables: [ 'valid', 'address', 'write', 'write_data', 'strobe', 'ready', 'status', 'read_data' ] } end end main_code :register, from_template: true main_code :register do |code| unless configuration.fold_sv_interface_port? [ [valid, bus_if.valid], [address, bus_if.address], [write, bus_if.write], [write_data, bus_if.write_data], [strobe, bus_if.strobe], [bus_if.ready, ready], [bus_if.status, "rggen_status'(#{status})"], [bus_if.read_data, read_data] ].map { |lhs, rhs| code << assign(lhs, rhs) << nl } end end private def address_width register_block.local_address_width end def byte_width configuration.byte_width end def start_address hex(register.offset_address, address_width) end def end_address address = register.offset_address + register.byte_size - 1 hex(address, address_width) end end sv_ral do build do parameter :register_block, :model_type, { name: model_name, data_type: 'type', default: 'rggen_ral_block' } parameter :register_block, :integrate_model, { name: "INTEGRATE_#{model_name}", data_type: 'bit', default: 1 } end model_name { register.name.upcase } constructor do macro_call( 'rggen_ral_create_block_model', [ral_model, offset_address, 'this', integrate_model] ) end end end <file_sep># frozen_string_literal: true require 'rggen/systemverilog' require_relative 'built_in/version' module RgGen module BuiltIn BUILT_IN_FILES = [ 'built_in/global/address_width', 'built_in/global/array_port_format', 'built_in/global/bus_width', 'built_in/global/fold_sv_interface_port', 'built_in/register_block/byte_size', 'built_in/register_block/name', 'built_in/register_block/protocol', 'built_in/register_block/protocol/apb', 'built_in/register_block/protocol/axi4lite', 'built_in/register_block/sv_ral_package', 'built_in/register_block/sv_rtl_top', 'built_in/register/name', 'built_in/register/offset_address', 'built_in/register/size', 'built_in/register/sv_rtl_top', 'built_in/register/type', 'built_in/register/type/external', 'built_in/register/type/indirect', 'built_in/bit_field/bit_assignment', 'built_in/bit_field/comment', 'built_in/bit_field/initial_value', 'built_in/bit_field/name', 'built_in/bit_field/reference', 'built_in/bit_field/sv_rtl_top', 'built_in/bit_field/type', 'built_in/bit_field/type/rc_w0c_w1c', 'built_in/bit_field/type/reserved', 'built_in/bit_field/type/ro', 'built_in/bit_field/type/rof', 'built_in/bit_field/type/rs_w0s_w1s', 'built_in/bit_field/type/rw_wo', 'built_in/bit_field/type/rwc_rwe_rwl', 'built_in/bit_field/type/w0trg_w1trg' ].freeze def self.load_built_in BUILT_IN_FILES.each { |file| require_relative file } end def self.setup(_builder) load_built_in end end setup :'built-in', BuiltIn end <file_sep>sonar.projectKey=rggen_rggen sonar.organization=rggen sonar.sources=./lib sonar.host.url=https://sonarcloud.io sonar.scm.provider=git
d0f01919c937a0201b5394ae029991adfe920ad8
[ "Markdown", "Ruby", "INI" ]
34
Ruby
275244143/rggen
7d6bfa40dfac8df122d32027da59cb071199415e
87221e8867b205b59e54d78ac08766b190608126
refs/heads/master
<repo_name>phoenix24/casita<file_sep>/casita-actor/src/main/java/casita/exectution/ForkJoinContext.java package casita.exectution; import casita.actorsystem.ActorHolder; import lombok.Getter; public class ForkJoinContext implements ExecutionContext { @Getter private String name; @Override public void addInbox(ActorHolder holder) { } @Override public void removeInbox(ActorHolder holder) { } } <file_sep>/casita-actor/src/main/java/casita/exception/ActorShutException.java package casita.exception; public class ActorShutException extends RuntimeException { public ActorShutException(String message) { super(message); } } <file_sep>/casita-actor/src/main/java/casita/inbox/Inbox.java package casita.inbox; public interface Inbox { public int size(); public void add(Object message); public Object get(); } <file_sep>/casita-actor/src/main/java/casita/utils/ThreadUtils.java package casita.utils; import java.util.concurrent.ThreadFactory; import java.util.function.Function; public class ThreadUtils { public static Function<String, ThreadFactory> tFactory = name -> runnable -> new Thread(runnable, name); } <file_sep>/casita-actor/src/main/java/casita/actorsystem/ActorSystem.java package casita.actorsystem; import casita.actor.Actor; import casita.exception.DuplicateActorException; import casita.exception.BadActorException; import casita.exectution.ExecutionContext; import casita.exectution.ThreadPoolContext; import casita.inbox.Inbox; import casita.utils.NetUtils; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import lombok.Getter; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.stream.Collectors; public final class ActorSystem { @Getter private final String name; @Getter private final String hostname; private final Map<ActorPath, ActorHolder> actors; private final Map<ActorPath, ExecutionContext> actorContexts; private final Map<String, ExecutionContext> executionContexts; private final static ExecutionContext EXEC_DEFAULT = ThreadPoolContext.create(); private ActorSystem(String name, List<ExecutionContext> contexts) { this.name = name; this.hostname = NetUtils.getHostAddress(); this.actors = Maps.newConcurrentMap(); this.actorContexts = Maps.newConcurrentMap(); this.executionContexts = contexts.stream() .collect(Collectors.toMap(ExecutionContext::getName, ex -> ex)); } public static ActorSystem create(String name, List<ExecutionContext> contexts) { ImmutableList<ExecutionContext> _contexts = ImmutableList.<ExecutionContext>builder() .addAll(contexts) .add(EXEC_DEFAULT) .build(); return new ActorSystem(name, _contexts); } public static ActorSystem create(String name) { return create(name, Lists.newArrayList()); } public Actor createActor(ActorConf conf) { Objects.requireNonNull(conf, "actor conf cannot be null"); ActorPath path = ActorPath.create(conf.getPath()); if (this.actors.containsKey(path)) { throw new DuplicateActorException("a duplicate actor of same path already exists"); } ActorHolder holder = ActorHolder.create(this, conf); ActorPath actorPath = holder.getActorPath(); ExecutionContext context = conf.getContext() == null ? EXEC_DEFAULT : this.executionContexts.get(conf.getContext()); context.addInbox(holder); this.actors.put(actorPath, holder); this.actorContexts.put(actorPath, context); return holder.getActor(); } public void shutdownActor(final ActorHolder holder) { ActorPath path = holder.getActorPath(); synchronized (path) { ExecutionContext context = this.actorContexts.get(path); context.removeInbox(holder); this.actors.remove(path); this.actorContexts.remove(path); } } public void send(final ActorPath path, final Object message) { //todo: extend for actor lifecycle message. //todo: extend for remote actor. //todo: this.actors or inbox for remove are not available. if (Objects.isNull(path) || !this.actors.containsKey(path)) { throw new BadActorException("invalid actor: bad actor specified"); } ActorHolder holder = this.actors.get(path); Actor actor = holder.getActor(); if (Objects.isNull(actor) || !actor.isAlive()) { throw new BadActorException("invalid actor: already shut or died"); } Inbox inbox = holder.getInbox(); inbox.add(message); } public void send(Actor actor, Object message) { send(actor.getPath(), message); } public void send(String path, Object message) { send(ActorPath.create(path), message); } } <file_sep>/casita-actor/src/main/java/casita/exectution/ExecutionContext.java package casita.exectution; import casita.actorsystem.ActorHolder; public interface ExecutionContext { public String getName(); public void addInbox(ActorHolder holder); public void removeInbox(ActorHolder holder); } <file_sep>/casita-actor/src/main/java/casita/actor/Actor.java package casita.actor; import casita.actorsystem.ActorPath; public interface Actor { //todo: support for typed messages later. public ActorPath getPath(); public void shutdown(); public boolean isAlive(); public void send(Actor actor, Object message); public void send(String actor, Object message); public void send(ActorPath actor, Object message); public void receive(Object message); public void receiveMessage(Object message); } <file_sep>/casita-actor/src/main/java/casita/supervisor/Policy.java package casita.supervisor; public interface Policy { public boolean canExecute(); public boolean shouldRestart(); } <file_sep>/casita-actor/src/main/java/casita/actor/ActorFactory.java package casita.actor; import casita.actorsystem.ActorConf; import casita.actorsystem.ActorSystem; import java.lang.reflect.InvocationTargetException; import java.util.Objects; public class ActorFactory { public static Actor create(ActorConf conf, ActorSystem system) throws NoSuchMethodException, IllegalAccessException, InvocationTargetException, InstantiationException { String path = conf.getPath(); Class<? extends Actor> klass = conf.getKlass(); Objects.requireNonNull(path, "actor path cannot be null"); Objects.requireNonNull(klass, "actor class cannot be null"); Objects.requireNonNull(system, "actor system cannot be null"); return klass .getDeclaredConstructor(ActorSystem.class, String.class) .newInstance(system, path); } } <file_sep>/casita-actor/src/main/java/casita/exception/BadActorException.java package casita.exception; public class BadActorException extends RuntimeException { public BadActorException(String message) { super(message); } } <file_sep>/readme.md ### casita ![casita](https://github.com/phoenix24/casita/workflows/build/badge.svg) a toy actor system <file_sep>/casita-actor/src/test/java/casita/actor/TestActorContexts.java package casita.actor; import casita.actorsystem.ActorConf; import casita.actorsystem.ActorPath; import casita.actorsystem.ActorSystem; import casita.exectution.ThreadPoolContext; import org.junit.Test; import java.util.List; public class TestActorContexts { public static class MyActor extends BaseActor { public MyActor(ActorSystem system, String path) { super(system, ActorPath.create(path)); } @Override public void receiveMessage(Object message) { System.out.println(this.getPath() + "-actor implementation: " + message); } } @Test public void createContextActor() throws InterruptedException { ActorSystem system = ActorSystem.create( "actor-system1", List.of( new ThreadPoolContext("context1"), new ThreadPoolContext("context2") ) ); ActorConf.ActorConfBuilder builder = ActorConf.builder() .klass(MyActor.class) .inbox("inmemory") .policy("never"); Actor actor1 = system.createActor(builder.path("actr1").context("context1").build()); Actor actor2 = system.createActor(builder.path("actr2").context("context2").build()); Actor actor3 = system.createActor(builder.path("actr3").build()); Actor actor4 = system.createActor(builder.path("actr4").build()); Actor actor5 = system.createActor(builder.path("actr5").build()); String message = "hello world"; for (int i = 0; i < 5; i++) { system.send(actor1, String.format("%s - %s, new context1", message, i)); system.send(actor2, String.format("%s - %s, new context2", message, i)); system.send(actor3, String.format("%s - %s, def context", message, i)); system.send(actor4, String.format("%s - %s, def context", message, i)); system.send(actor5, String.format("%s - %s, def context", message, i)); } Thread.sleep(10000L); } } <file_sep>/casita-actor/src/main/java/casita/inbox/InboxInMemory.java package casita.inbox; import java.util.concurrent.ArrayBlockingQueue; public class InboxInMemory implements Inbox { public ArrayBlockingQueue<Object> queue; public InboxInMemory(int capacity) { this.queue = new ArrayBlockingQueue<>(capacity); } @Override public void add(Object message) { this.queue.offer(message); } @Override public Object get() { return this.queue.poll(); } @Override public int size() { return this.queue.size(); } } <file_sep>/casita-actor/src/test/java/casita/actor/TestActorSleepy.java package casita.actor; import casita.actorsystem.ActorConf; import casita.actorsystem.ActorPath; import casita.actorsystem.ActorSystem; import org.junit.Test; public class TestActorSleepy { public static class MyActor extends BaseActor { public MyActor(ActorSystem system, String path) { super(system, ActorPath.create(path)); } @Override public void receiveMessage(Object message) { try { System.out.println("sleepy-actor implementation: " + message); Thread.sleep(1000L); } catch (InterruptedException e) { System.out.println("some thing interrupted"); } } } @Test public void createSleepyActor() throws InterruptedException { ActorSystem system = ActorSystem.create("actor-system1"); ActorConf conf = ActorConf.builder() .klass(MyActor.class) .path("sleepy") .inbox("inmemory") .policy("never") .build(); Actor actor = system.createActor(conf); String message = "hello world"; for (int i = 0; i < 20; i++) { system.send(actor, String.format("%s - %s", message, i)); } } } <file_sep>/casita-actor/src/main/java/casita/actorsystem/ActorHolder.java package casita.actorsystem; import casita.actor.Actor; import casita.actor.ActorFactory; import casita.exception.ActorCreationException; import casita.inbox.Inbox; import casita.inbox.InboxFactory; import casita.supervisor.Policy; import casita.supervisor.PolicyFactory; import lombok.Builder; import lombok.Data; import static java.util.Objects.requireNonNull; @Data @Builder public class ActorHolder { private Inbox inbox; private Policy policy; private Actor actor; private ActorPath actorPath; public static ActorHolder create(ActorSystem system, ActorConf conf) { try { return ActorHolder.builder() .actor(ActorFactory.create(requireNonNull(conf), system)) .inbox(InboxFactory.create(requireNonNull(conf.getInbox()))) .policy(PolicyFactory.create(requireNonNull(conf.getPolicy()))) .actorPath(ActorPath.create(requireNonNull(conf.getPath()))) .build(); } catch (Exception e) { e.printStackTrace(); throw new ActorCreationException("failed to create actor:" + conf.getPath()); } } public void execute(final Object message) { while (this.policy.canExecute()) { try { this.actor.receive(message); return; } catch (Exception e) { System.err.println("actor execution exception: " + e.getMessage()); boolean restart = this.policy.shouldRestart(); System.err.println("actor supervision policy restart? " + restart); } } } }
3783ce476af51e87544c95825a5ccd90c2afc952
[ "Markdown", "Java" ]
15
Java
phoenix24/casita
805d65aac02e664fe21389643c5cadb2c055ce41
38a3a779904257e1038b02320da5d2fc9ee9d3b9
refs/heads/master
<repo_name>SilasPC/RustyBoi<file_sep>/Cargo.toml [package] name = "rust_stuff" version = "0.1.0" authors = ["Balisong <<EMAIL>>"] edition = "2018" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html [dependencies] sdl2 = { version = "0.34", features = ["bundled","static-link"] } gl = "0.14" nalgebra = "0.21" anyhow = "1.0" rand = "0.7" png = "0.16" noise = "0.6" toml = "0.5" lazy_static = "1.4" downcast-rs = "1.1"<file_sep>/src/entities/components/components/mod.rs use super::ComponentMaster; mod player; pub use player::PlayerComponent; mod jump_move; pub use jump_move::JumpMove; pub fn create_master() -> ComponentMaster { let mut master = ComponentMaster::default(); master.register("JumpMove", Box::new(JumpMove::default())); master.register("Player", Box::new(PlayerComponent::default())); master } mod prelude { pub use crate::entities::components::Component; pub use crate::entities::{Entity,EntityMutor,EntityData}; pub use crate::world::{World,WorldMutor,WorldData}; pub use super::super::Meta; pub use crate::input::Input; } <file_sep>/src/main.rs #[macro_use] extern crate downcast_rs; extern crate gl; extern crate sdl2; mod engine; mod entities; mod input; mod world; mod items; mod renderer; use anyhow::*; fn main() { match main_program() { Err(e) => println!("Error report:\n\n{:?}", e), Ok(_) => println!("Program exited gracefully"), } } use engine::display::Display; use engine::loader::Loader; use engine::texture::GLTexture; use world::{Camera,World}; use renderer::MasterRenderer; use world::tiles::*; fn main_program() -> Result<()> { let loader = Loader::from_relative_exe_path(std::path::Path::new("../../assets"))?; let mut display = Display::new( loader .load_image("img/icon.png") .context("Failed to load window icon")?, )?; let renderer = MasterRenderer::load(&loader) .context("Failed to create render master")?; use entities::{Entity,EntityData,EntityMaster}; let mut player = Entity::new(EntityData::new(GLTexture::from_loader(&loader, "img/player.png")?, Vector2::new(0.0,2.0), Vector2::new(2.0,3.0), 5.0), std::collections::HashMap::default()); let entity_master = EntityMaster::load_and_create(&loader) .context("Failed to create EntityMaster")?; entity_master.add_component_to("Player", &mut player)?; let mut camera = Camera::centered_at(&player); use engine::texture_atlas::TextureAtlas; let texture = GLTexture::from_loader(&loader, "img/textures.png")?; let atlas = TextureAtlas::from_texture(texture, 6); let mut tiles = TileMaster::create(); tiles.add("Air", SimpleTile::air()); tiles.add("Grass", SimpleTile::from(0, true)); tiles.add("Stone", SimpleTile::from(1, true)); tiles.add("Dirt", SimpleTile::from(2, true)); tiles.add("Wood", SimpleTile::from(3, true)); tiles.add("Sand", SimpleTile::from(4, true)); tiles.add("Torch", SimpleTile::from(5, false)); let mut world = World::new( palette!(tiles, "Air", "Stone", "Grass", "Dirt"), palette!(tiles, "Air", "Stone", "Sand", "Sand"), 987654321, tiles.tiles.get("Air").unwrap().clone() ); /*map.set_tile(TileCoord::from(1.0, 0.0), SimpleTile::from(24, false)); map.set_tile(TileCoord::from(2.0, 0.0), SimpleTile::from(25, false)); map.set_tile(TileCoord::from(3.0, 0.0), SimpleTile::from(26, false)); map.set_tile(TileCoord::from(2.0, 1.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(2.0, 2.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(2.0, 3.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(2.0, 4.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(2.0, 5.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(2.0, 6.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(2.0, 7.0), SimpleTile::from(19, false)); map.set_tile(TileCoord::from(1.0, 8.0), SimpleTile::from(12, false)); map.set_tile(TileCoord::from(2.0, 8.0), SimpleTile::from(13, false)); map.set_tile(TileCoord::from(3.0, 8.0), SimpleTile::from(14, false)); map.set_tile(TileCoord::from(1.0, 9.0), SimpleTile::from(6, false)); map.set_tile(TileCoord::from(2.0, 9.0), SimpleTile::from(7, false)); map.set_tile(TileCoord::from(3.0, 9.0), SimpleTile::from(8, false));*/ use nalgebra::Vector2; use input::Input; let mut input = Input::new(); use std::time::Instant; let start = Instant::now(); world.tmp( entity_master.instantiate_all() ); world.tmp( vec![player] ); unsafe { gl::ClearColor(0.3, 0.3, 0.5, 1.0); } 'main: loop { use sdl2::event::Event::*; use sdl2::keyboard::Keycode; input.prepare_read(); while let Some(event) = display.poll_event() { input.read_event(&event); match event { Quit { .. } => break 'main, KeyDown { keycode: Some(Keycode::Escape), .. } => break 'main, _ => {} } } let mouse_world_pos = camera .world_position_from_screen_coords(display.mouse_screen_coords(), display.aspect_ratio()); let mouse_tile_coord = TileCoord::from_vec(&mouse_world_pos); use entities::components::Meta; let meta = Meta { input: &input, delta_time: display.delta_time(), mouse: (mouse_tile_coord, mouse_world_pos), tiles: &tiles, }; world.update(&meta); unsafe { gl::Clear(gl::COLOR_BUFFER_BIT); } let sky_light_scale = start.elapsed().as_secs_f32().mul_add(0.6,0.0).cos().mul_add(0.5, 0.5); world.map_mut().for_chunks_in_area( |chunk| { chunk.regen_mesh(&atlas); renderer.chunk.render(chunk, &camera, &atlas, display.aspect_ratio(), sky_light_scale); }, camera.position(), 5.0 + display.aspect_ratio() / camera.get_zoom(), ); renderer.item.render_static( display.aspect_ratio(), &Vector2::new(0.5,0.5), 0.5 ); world.foreach_entity( |entity| { renderer.entity.render( entity, &camera, display.aspect_ratio(), world.map().get_total_light_scale(entity.tile_coord(), sky_light_scale).unwrap_or(1.0) ); } ); display.update(); } Ok(()) } <file_sep>/src/entities/components/master.rs use std::collections::HashMap; use std::any::{Any, TypeId}; use downcast_rs::Downcast; use super::super::EntityMutor; use crate::world::WorldMutor; use anyhow::*; #[derive(Default)] pub struct ComponentMaster { defaults: HashMap<String, (TypeId, Box<dyn Component>)>, } impl ComponentMaster { pub fn register(&mut self, name: &str, default: Box<dyn Component>) { self.defaults.insert(name.to_owned(), (default.type_id(), default)); } pub fn create_instance(&self, name: &str) -> Result<(TypeId, Box<dyn Component>)> { let (type_id, cmp) = self.defaults.get(name).ok_or(anyhow!("Failed to find component \"{}\"",name))?; Ok((type_id.clone(),cmp.create())) } } pub trait Component: Downcast { fn create(&self) -> Box<dyn Component>; fn update(&mut self, entity: &mut EntityMutor, world: &mut WorldMutor, meta: &Meta) {} } impl_downcast!(Component); use crate::world::tiles::TileCoord; use nalgebra::Vector2; use crate::world::tiles::TileMaster; pub struct Meta<'a> { pub input: &'a crate::input::Input, pub delta_time: f32, pub mouse: (TileCoord, Vector2<f32>), pub tiles: &'a TileMaster, } <file_sep>/src/renderer.rs use crate::engine::loader::Loader; use crate::world::ChunkRenderer; use crate::entities::EntityRenderer; use crate::items::renderer::ItemRenderer; use anyhow::*; pub struct MasterRenderer { pub chunk: ChunkRenderer, pub entity: EntityRenderer, pub item: ItemRenderer, } impl MasterRenderer { pub fn load(loader: &Loader) -> Result<Self> { let chunk = ChunkRenderer::create(&loader) .context("Failed to create chunk renderer")?; let entity = EntityRenderer::create(&loader) .context("Failed to create entity renderer")?; let item = ItemRenderer::create(&loader) .context("Failed to create item renderer")?; Ok(MasterRenderer { chunk, entity, item, }) } } <file_sep>/src/entities/renderer.rs use gl; use gl::types::*; use crate::engine::loader::*; use crate::engine::program::Program; use crate::engine::shader::Shader; use crate::engine::vao::VAO; use crate::world::Camera; use super::Entity; use nalgebra::Vector2; use anyhow::*; pub struct EntityRenderer { program: Program, offset_loc: GLint, scale_loc: GLint, pre_scale_loc: GLint, light_scale_loc: GLint, vao: VAO, } impl EntityRenderer { pub fn create(loader: &Loader) -> Result<EntityRenderer> { let vert_shader = Shader::from_vert_source(&loader.load_cstring("shaders/entity_vert.glsl")?)?; let frag_shader = Shader::from_frag_source(&loader.load_cstring("shaders/entity_frag.glsl")?)?; let program = Program::create(vert_shader, frag_shader)?; let offset_loc = program.get_uniform_location("offset")?; let scale_loc = program.get_uniform_location("scale")?; let pre_scale_loc = program.get_uniform_location("pre_scale")?; let light_scale_loc = program.get_uniform_location("light_scale")?; let vao = VAO::square(); Ok(EntityRenderer { program, pre_scale_loc, offset_loc, scale_loc, light_scale_loc, vao, }) } pub fn render(&self, entity: &Entity, cam: &Camera, aspect_ratio: f32, light_scale: f32) { self.program.set_used(); unsafe { gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, entity.texture_id()); gl::TexParameterf( gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLfloat, ); gl::TexParameterf( gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLfloat, ); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); } let mut offset = entity.position() - cam.position(); if entity.is_facing_left() {offset.x += entity.size().x;} Program::load_vec2(self.offset_loc, &offset); let mut pre_scale = entity.size().clone(); if entity.is_facing_left() {pre_scale.x *= -1.0;} Program::load_vec2(self.pre_scale_loc, &pre_scale); let zoom = cam.get_zoom(); Program::load_vec2(self.scale_loc, &Vector2::new(zoom / aspect_ratio, zoom)); Program::load_float(self.light_scale_loc, light_scale); unsafe { gl::BindVertexArray(self.vao.id()); gl::EnableVertexAttribArray(0); gl::EnableVertexAttribArray(1); gl::DrawArrays( gl::TRIANGLES, 0, // starting index self.vao.tri_count() * 3, ); gl::DisableVertexAttribArray(0); gl::DisableVertexAttribArray(1); gl::BindVertexArray(0); } unsafe { gl::BindTexture(gl::TEXTURE_2D, 0); gl::Disable(gl::BLEND); } } } <file_sep>/src/items/item.rs pub struct Item { } <file_sep>/src/engine/texture.rs use gl; use gl::types::*; use crate::engine::loader::Loader; use anyhow::*; use std::rc::Rc; pub type Texture = Rc<Box<GLTexture>>; pub struct GLTexture { width: u32, height: u32, id: GLuint, } impl GLTexture { pub fn from_loader(loader: &Loader, name: &str) -> Result<Texture> { let (data, width, height) = loader.load_image(name).context("Failed to load image")?; Ok(Self::from_data(&data, width, height)) } fn from_data(data: &Vec<u8>, width: u32, height: u32,) -> Texture { let mut id: GLuint = 0; unsafe { gl::GenTextures(1, &mut id); gl::BindTexture(gl::TEXTURE_2D, id); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_BASE_LEVEL, 0); gl::TexParameteri(gl::TEXTURE_2D, gl::TEXTURE_MAX_LEVEL, 0); gl::TexImage2D( gl::TEXTURE_2D, 0, gl::RGBA8 as GLint, width as i32, height as i32, 0, gl::RGBA, gl::UNSIGNED_BYTE, data.as_ptr() as *const GLvoid ); gl::BindTexture(gl::TEXTURE_2D, 0); } Rc::new(Box::new(GLTexture { id, width, height })) } pub fn id(&self) -> GLuint {self.id} pub fn aspect_ratio(&self) -> f32 {self.width as f32 / self.height as f32} pub fn width(&self) -> u32 {self.width} pub fn height(&self) -> u32 {self.height} } impl Drop for GLTexture { fn drop(&mut self) { unsafe { gl::DeleteTextures(1, &self.id); } } } <file_sep>/src/items/renderer.rs use gl; use gl::types::*; use crate::engine::loader::*; use crate::engine::program::Program; use crate::engine::shader::Shader; use crate::engine::vao::VAO; use crate::engine::texture::{Texture, GLTexture}; use super::item::Item; use nalgebra::Vector2; use anyhow::*; pub struct ItemRenderer { texture: Texture, program: Program, offset_loc: GLint, scale_loc: GLint, vao: VAO, } impl ItemRenderer { pub fn create(loader: &Loader) -> Result<Self> { let vert_shader = Shader::from_vert_source(&loader.load_cstring("shaders/item_vert.glsl")?)?; let frag_shader = Shader::from_frag_source(&loader.load_cstring("shaders/item_frag.glsl")?)?; let program = Program::create(vert_shader, frag_shader)?; let offset_loc = program.get_uniform_location("offset")?; let scale_loc = program.get_uniform_location("scale")?; let texture = GLTexture::from_loader(loader, "img/item.png")?; let vao = VAO::square(); Ok(Self { program, texture, offset_loc, scale_loc, vao, }) } pub fn render_static(&self, aspect_ratio: f32, position: &Vector2<f32>, scale: f32) { self.program.set_used(); unsafe { gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, self.texture.id()); gl::TexParameterf( gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLfloat, ); gl::TexParameterf( gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLfloat, ); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); } Program::load_vec2(self.offset_loc, position); Program::load_vec2(self.scale_loc, &Vector2::new(scale / aspect_ratio, scale)); unsafe { gl::BindVertexArray(self.vao.id()); gl::EnableVertexAttribArray(0); gl::EnableVertexAttribArray(1); gl::DrawArrays( gl::TRIANGLES, 0, // starting index self.vao.tri_count() * 3, ); gl::DisableVertexAttribArray(0); gl::DisableVertexAttribArray(1); gl::BindVertexArray(0); } unsafe { gl::BindTexture(gl::TEXTURE_2D, 0); gl::Disable(gl::BLEND); } } } <file_sep>/src/world/world_gen.rs use noise::*; use super::tiles::Tile; // factor = feature size const PI: f64 = 3.14159265359; const FACTOR: f64 = 10.0 * PI; const SHIFT: f64 = 0.5; const BIOME_FACTOR: f64 = 50.0 * PI; const BIOME_SHIFT: f64 = 10.5; const CAVE_FACTOR: f64 = 100.0 * PI; const CAVE_SHIFT: f64 = 2.0 * PI; pub struct WorldGen { palette: [Tile; 4], palette2: [Tile; 4], perlin: Perlin, } impl WorldGen { pub fn new(palette: [Tile; 4], palette2: [Tile; 4], seed: u32) -> Self { WorldGen { palette, palette2, perlin: Perlin::new().set_seed(seed), } } pub fn get(&self, x: f64, y: f64) -> Tile { let palette = self.biome_pallete(x, y); let density = self.density(x, y); if density <= 0.0 {return palette[0].clone();} if density >= 1.0 {return palette[1].clone();} if self.density(x, y+1.0) <= 0.0 {palette[2].clone()} else {palette[3].clone()} } fn density(&self, x: f64, y: f64) -> f64 { let cave_noise = self.perlin.get([x/CAVE_FACTOR+CAVE_SHIFT,y/CAVE_FACTOR+CAVE_SHIFT]).powi(2); if cave_noise > 0.4 {return 0.0;} (1.0-0.1*(y+10.0)) + 0.5 * self.perlin.get([x/FACTOR+SHIFT,y/FACTOR+SHIFT]) } fn biome_pallete(&self, x: f64, y: f64) -> &[Tile; 4] { if self.perlin.get([x/BIOME_FACTOR+BIOME_SHIFT,y/BIOME_FACTOR+BIOME_SHIFT]) > 0.0 { &self.palette2 } else { &self.palette } } } <file_sep>/src/entities/bounding_box.rs use crate::world::WorldMap; use nalgebra::Vector2; const EPSILON: f32 = 0.0001; pub struct BoundingBox { position: Vector2<f32>, size: Vector2<f32>, } impl BoundingBox { pub fn new(position: Vector2<f32>, size: Vector2<f32>) -> Self { BoundingBox { position, size: size - Vector2::new(EPSILON,EPSILON), } } pub fn position(&self) -> &Vector2<f32> {&self.position} pub fn size(&self) -> &Vector2<f32> {&self.size} pub fn move_collide_velocity(&mut self, velocity: &mut Vector2<f32>, delta_time: f32, world: &WorldMap) -> (bool,bool) { let mut did_collide = (false,false); let xf = self.position.x.floor(); self.position.x += velocity.x * delta_time; if xf != self.position.x.floor() { if self.collide_x(velocity.x > 0.0, world) {did_collide.0 = true; velocity.x = 0.0;} } let yf = self.position.x.floor(); self.position.y += velocity.y * delta_time; if yf != self.position.y.floor() { if self.collide_y(velocity.y > 0.0, world) {did_collide.1 = true; velocity.y = 0.0;} } did_collide } fn collide_x(&mut self, vx_pos: bool, world: &WorldMap) -> bool { if world.is_collidable_or_out_of_bounds(&self.position) { if vx_pos { self.position.x = self.position.x.floor() - EPSILON; } else { self.position.x = self.position.x.ceil(); } return true } false } fn collide_y(&mut self, vy_pos: bool, world: &WorldMap) -> bool { if world.is_collidable_or_out_of_bounds(&self.position) { if vy_pos { self.position.y = self.position.y.floor() - EPSILON; } else { self.position.y = self.position.y.ceil(); } return true } return false } } <file_sep>/src/world/mod.rs pub mod tiles; mod lighting; mod chunk_renderer; pub use chunk_renderer::*; mod chunk; pub use chunk::*; mod map; pub use map::*; mod world_gen; pub use world_gen::*; mod camera; pub use camera::*; mod ray; pub use ray::*; mod world; pub use world::*; <file_sep>/src/entities/entity.rs use std::collections::HashMap; use std::cell::{RefCell,RefMut}; use std::any::TypeId; use crate::engine::texture::Texture; use crate::world::Ray; use crate::world::tiles::TileCoord; use crate::world::WorldMutor; use super::bounding_box::BoundingBox; use super::components::{Component,Meta}; use nalgebra::Vector2; pub struct EntityData { texture: Texture, bounding_box: BoundingBox, is_grounded: bool, facing_left: bool, pending_force: Vector2<f32>, velocity: Vector2<f32>, mass: f32, } pub struct Entity { data: EntityData, components: HashMap<TypeId,RefCell<Box<dyn Component>>> } impl std::ops::Deref for Entity { type Target = EntityData; fn deref(&self) -> &EntityData {&self.data} } impl std::ops::DerefMut for Entity { fn deref_mut(&mut self) -> &mut EntityData {&mut self.data} } pub struct EntityMutor<'a> (&'a mut EntityData, &'a HashMap<TypeId,RefCell<Box<dyn Component>>>); impl<'a> EntityMutor<'a> { pub fn data(&mut self) -> &mut EntityData {&mut self.0} pub fn has_component<T: Component>(&self) -> bool { self.1.contains_key(&TypeId::of::<T>()) } pub fn mut_component<T,F>(&self, f: F) -> Option<()> where T: Component, F: Fn(&mut T) { let cell = self.1.get(&TypeId::of::<T>())?; let mut bor = cell.try_borrow_mut().ok()?; let mut val = bor.downcast_mut::<T>()?; f(&mut val); Some(()) } } const GRAVITY: f32 = 15.0; impl Entity { pub fn new(data: EntityData, components: HashMap<TypeId,RefCell<Box<dyn Component>>>) -> Self { Entity { data, components } } pub fn update(&mut self, world: &mut WorldMutor, meta: &Meta) { let mut mutor = EntityMutor ( &mut self.data, &self.components ); for component in self.components.values() { component.borrow_mut().update(&mut mutor, world, meta); } self.data.update(meta.delta_time, world); } pub unsafe fn add_component(&mut self, id: TypeId, cmp: Box<dyn Component>) { self.components.insert(id, RefCell::new(cmp)); } } impl EntityData { pub fn new(texture: Texture, position: Vector2<f32>, size: Vector2<f32>, mass: f32) -> Self { EntityData { texture, bounding_box: BoundingBox::new(position, size), is_grounded: false, facing_left: false, mass, pending_force: Vector2::new(0.0,0.0), velocity: Vector2::new(0.0,0.0), } } pub fn ray_toward(&self, pos: &Vector2<f32>) -> Ray { Ray::new(&self.position(), &(pos - self.position())) } pub fn tile_coord(&self) -> TileCoord {TileCoord::from_vec(self.bounding_box.position())} pub fn set_is_facing_left(&mut self, is_facing_left: bool) { self.facing_left = is_facing_left; } pub fn is_facing_left(&self) -> bool {self.facing_left} pub fn texture_id(&self) -> gl::types::GLuint {self.texture.id()} pub fn position(&self) -> &Vector2<f32> {&self.bounding_box.position()} pub fn size(&self) -> &Vector2<f32> {&self.bounding_box.size()} pub fn velocity(&self) -> &Vector2<f32> {&self.velocity} pub fn is_grounded(&self) -> bool {self.is_grounded} pub fn center(&self) -> Vector2<f32> {self.position() + self.size() / 2.0} pub fn try_jump(&mut self) -> bool { if self.is_grounded() { self.add_force(&Vector2::new(0.0,self.mass * 10.0)); true } else {false} } pub fn add_force(&mut self, force: &Vector2<f32>) { self.velocity += force / self.mass; } pub fn add_force_continuous(&mut self, force: &Vector2<f32>) { self.pending_force += 200.0 * force; } pub fn add_speed_force_continuous(&mut self, force: &Vector2<f32>) { self.pending_force += force * 200.0 / self.mass; } pub fn update(&mut self, delta_time: f32, world: &mut WorldMutor) { if self.is_grounded { self.is_grounded = world.map().is_collidable_or_out_of_bounds(&(self.position()+Vector2::new(0.0,-0.1))); } if !self.is_grounded { self.velocity.y -= GRAVITY * delta_time; } self.velocity += self.pending_force * (delta_time / self.mass); self.pending_force = Vector2::new(0.0,0.0); // solution found using infinite geometric series... hope it works lol self.velocity.x *= 1.0 - delta_time * 7.0; let falling = self.velocity.y < 0.0; let col_res = self.bounding_box.move_collide_velocity(&mut self.velocity, delta_time, world.map()); if col_res.1 && falling {self.is_grounded = true;} } } <file_sep>/src/world/camera.rs use crate::entities::Entity; use nalgebra::Vector2; pub struct Camera { zoom: f32, position: Vector2<f32>, // target: Option<Vector2<f32>>, } impl Camera { pub fn centered_at(entity: &Entity) -> Self { Camera { zoom: 0.06, position: entity.position().clone(), } } pub fn set_position(&mut self, pos: &Vector2<f32>) {self.position = *pos;} pub fn lerp_towards(&mut self, pos: &Vector2<f32>, delta_time: f32) { self.position = self.position.lerp(pos, 3.0 * delta_time); } pub fn get_zoom(&self) -> f32 {self.zoom} pub fn position(&self) -> &Vector2<f32> {&self.position} pub fn world_position_from_screen_coords(&self, (mx, my): (f32, f32), aspect_ratio: f32) -> Vector2<f32> { Vector2::new( self.position.x + aspect_ratio * (2.0 * mx - 1.0) / self.zoom, self.position.y + (1.0 - 2.0 * my) / self.zoom, ) } } <file_sep>/assets/entities/slime/data.toml mass = 1.0 [[components]] name = "JumpMove" <file_sep>/src/world/lighting.rs use std::collections::{VecDeque, HashMap}; use super::tiles::{Tile,TileCoord}; use super::map::WorldMap; pub const MAX_LIGHT: u16 = 32; pub const MAX_LIGHT_F: f32 = MAX_LIGHT as f32; struct RNode { coord: TileCoord, old_light_value: u16, } struct Node { coord: TileCoord, light_value: u16, } #[derive(Default)] pub struct LightCalculator { pending: Vec<Node>, pending_removal: VecDeque<RNode>, sky_pending: Vec<Node>, } impl LightCalculator { pub fn update(&mut self, map: &mut WorldMap, coord: TileCoord, old: Tile, new: Tile) { if new.light_obstruction() > old.light_obstruction() || new.light_emission() < old.light_emission() { if let Some(old_light_value) = map.get_light(coord) { map.set_light(coord, 0); self.pending_removal.push_back(RNode { coord, old_light_value }); } } if new.light_emission() > old.light_emission() { self.pending.push(Node {coord, light_value: new.light_emission()}); } } pub fn add_sky(&mut self, coord: TileCoord, light_value: u16) {self.sky_pending.push(Node {coord, light_value});} pub fn process(&mut self, map: &mut WorldMap) { self.remove_light(map); self.propagate_light(map); while let Some(node) = self.sky_pending.pop() { if map.set_sky_light(node.coord, node.light_value).is_none() {continue} if node.light_value == 1 {continue} let mut coord = node.coord; macro_rules! check_add { () => { if let Some(l) = map.get_sky_light(coord) { if let Some(tile) = map.get_tile_at(coord) { let obstr = tile.light_obstruction(); if obstr < node.light_value && l < node.light_value - obstr { self.sky_pending.push(Node {coord, light_value: node.light_value - obstr}); } } } } } coord.x += 1; check_add!(); coord.x -= 2; check_add!(); coord.x += 1; coord.y += 1; check_add!(); coord.y -= 2; if let Some(l) = map.get_light(coord) { if let Some(tile) = map.get_tile_at(coord) { if node.light_value == MAX_LIGHT && !tile.is_collidable() { if l < MAX_LIGHT { self.sky_pending.push(Node {coord, light_value: MAX_LIGHT}); } } else { let obstr = tile.light_obstruction(); if obstr < node.light_value && l < node.light_value - obstr { self.sky_pending.push(Node {coord, light_value: node.light_value - obstr}); } } } } } } fn remove_light(&mut self, map: &mut WorldMap) { let mut rebounds = HashMap::new(); while let Some(node) = self.pending_removal.pop_front() { let mut coord = node.coord; macro_rules! propagate { () => { if let Some(cur_light) = map.get_light(coord) { if cur_light > 0 { if let Some(tile) = map.get_tile_at(coord) { let obstr = tile.light_obstruction(); // println!("{:?} => {} {} {}\n",coord,node.old_light_value,cur_light,obstr); if node.old_light_value >= cur_light + obstr { // could have been source if map.set_light(coord, 0).is_none() {continue} self.pending_removal.push_back(RNode {coord, old_light_value: cur_light}); rebounds.remove(&coord); } else if cur_light > 0 { // println!("prop maybe {} {}",coord.x,coord.y); rebounds.insert(coord, cur_light); } } } } } } coord.x += 1; propagate!(); coord.x -= 2; propagate!(); coord.x += 1; coord.y += 1; propagate!(); coord.y -= 2; propagate!(); } for (coord, cur_light) in rebounds.iter() { self.pending.push(Node {coord: *coord, light_value: *cur_light}); } } fn propagate_light(&mut self, map: &mut WorldMap) { while let Some(node) = self.pending.pop() { if map.set_light(node.coord, node.light_value).is_none() {continue} if node.light_value == 1 {continue} let mut coord = node.coord; macro_rules! check_add { () => { if let Some(l) = map.get_light(coord) { if let Some(tile) = map.get_tile_at(coord) { let obstr = tile.light_obstruction(); if obstr < node.light_value && l < node.light_value - obstr { self.pending.push(Node {coord, light_value: node.light_value - obstr}); } } } } } coord.x += 1; check_add!(); coord.x -= 2; check_add!(); coord.x += 1; coord.y += 1; check_add!(); coord.y -= 2; check_add!(); } } } <file_sep>/src/world/chunk.rs use crate::engine::vao::*; use crate::engine::texture_atlas::*; use nalgebra::Vector2; use super::tiles::{Tile,TileCoord}; use super::world_gen::WorldGen; use super::lighting::MAX_LIGHT_F; pub const CHUNK_SIZE_F: f32 = 16.0; pub const CHUNK_SIZE: usize = CHUNK_SIZE_F as usize; pub struct Chunk { pos: Vector2<f32>, tiles: [[Tile; CHUNK_SIZE]; CHUNK_SIZE], light: [[u16; CHUNK_SIZE]; CHUNK_SIZE], // 8 bits light, then 8 bits skylight vao: VAO, needs_mesh_update: bool, needs_light_update: bool, } macro_rules! make_array { ($n:expr, $constructor:expr) => {{#[allow(unused_unsafe)]unsafe { #[allow(deprecated)] let mut items: [_; $n] = std::mem::uninitialized(); for (i, place) in items.iter_mut().enumerate() { std::ptr::write(place, $constructor(i)); } items }}} } impl Chunk { pub fn new(x: i32, y: i32, generator: &WorldGen) -> Self { let tiles = make_array!(CHUNK_SIZE, |tx| make_array!(CHUNK_SIZE, |ty| generator.get((16*x+tx as i32) as f64, (16*y+ty as i32) as f64) ) ); let mut vao = VAO::empty(); vao.add_float_vbo(1); vao.add_float_vbo(1); let light = [[0; CHUNK_SIZE]; CHUNK_SIZE]; Chunk { needs_mesh_update: true, needs_light_update: true, light, pos: Vector2::new(x as f32 * CHUNK_SIZE_F, y as f32 * CHUNK_SIZE_F), tiles, vao } } pub fn get_light(&self, coord: TileCoord) -> u16 {self.light[coord.sub_x()][coord.sub_y()] >> 8} pub fn set_light(&mut self, coord: TileCoord, light: u16) { let l = &mut self.light[coord.sub_x()][coord.sub_y()]; *l &= 0xff; *l |= light << 8; self.needs_light_update = true; } pub fn get_sky_light(&self, coord: TileCoord) -> u16 {self.light[coord.sub_x()][coord.sub_y()] & 0xff} pub fn set_sky_light(&mut self, coord: TileCoord, light: u16) { let l = &mut self.light[coord.sub_x()][coord.sub_y()]; *l &= 0xff00; *l |= light; self.needs_light_update = true; } pub fn set(&mut self, coord: TileCoord, tile: Tile) { self.tiles[coord.sub_x()][coord.sub_y()] = tile; self.needs_mesh_update = true; } pub fn get(&self, coord: TileCoord) -> Tile { self.tiles[coord.sub_x()][coord.sub_y()].clone() } pub fn pos(&self) -> &Vector2<f32> {&self.pos} pub fn vao(&self) -> &VAO {&self.vao} pub fn regen_mesh(&mut self, atlas: &TextureAtlas) { if !self.needs_mesh_update { if self.needs_light_update { self.regen_light(); self.needs_light_update = false; } return; } self.needs_mesh_update = false; self.needs_light_update = false; let mut verts = Vec::<f32>::default(); let mut txs = Vec::<f32>::default(); for x in 0..CHUNK_SIZE { for y in 0..CHUNK_SIZE { if self.tiles[x][y].should_render() { let t = atlas.uv_bounds_from_index(self.tiles[x][y].texture_index()); let x = x as f32; let y = y as f32; verts.push(x); txs.push(t.0); verts.push(y); txs.push(t.1); verts.push(x); txs.push(t.0); verts.push(y+1.0); txs.push(t.3); verts.push(x+1.0); txs.push(t.2); verts.push(y+1.0); txs.push(t.3); verts.push(x); txs.push(t.0); verts.push(y); txs.push(t.1); verts.push(x+1.0); txs.push(t.2); verts.push(y+1.0); txs.push(t.3); verts.push(x+1.0); txs.push(t.2); verts.push(y); txs.push(t.1); } } } self.vao.update_verts(verts); self.vao.update_float_vbo(1, txs); self.regen_light(); } pub fn regen_light(&mut self) { let mut lights = vec![]; let mut sky_lights = vec![]; for x in 0..CHUNK_SIZE { for y in 0..CHUNK_SIZE { if self.tiles[x][y].should_render() { let light = self.light[x][y]; let sky_light = (light & 0xff) as f32 / MAX_LIGHT_F; let light = (light >> 8) as f32 / MAX_LIGHT_F; lights.extend([light; 6].iter().to_owned()); sky_lights.extend([sky_light; 6].iter().to_owned()); } } } self.vao.update_float_vbo(2, lights); self.vao.update_float_vbo(3, sky_lights); } } <file_sep>/src/world/tiles/coord.rs use super::super::chunk::CHUNK_SIZE_F; const CHUNK_SIZE: i32 = super::super::chunk::CHUNK_SIZE as i32; use nalgebra::Vector2; #[derive(Clone,Copy,PartialEq,Eq,Debug,Hash)] pub struct TileCoord { pub x: i32, pub y: i32, } impl TileCoord { pub fn new(x: i32, y: i32) -> Self {TileCoord {x, y}} pub fn from(x: f32, y: f32) -> Self { TileCoord { x: x.floor() as i32, y: y.floor() as i32, } } pub fn from_vec(vec: &Vector2<f32>) -> Self { TileCoord { x: vec.x.floor() as i32, y: vec.y.floor() as i32, } } pub fn chunk_x(&self) -> i32 {(self.x as f32 / CHUNK_SIZE_F).floor() as i32} pub fn chunk_y(&self) -> i32 {(self.y as f32 / CHUNK_SIZE_F).floor() as i32} pub fn sub_x(&self) -> usize { let x = self.x % CHUNK_SIZE; if x < 0 {(x+CHUNK_SIZE) as usize} else {x as usize} } pub fn sub_y(&self) -> usize { let y = self.y % CHUNK_SIZE; if y < 0 {(y+CHUNK_SIZE) as usize} else {y as usize} } } <file_sep>/src/entities/components/components/jump_move.rs use std::time::Instant; use rand::prelude::*; use super::prelude::*; use nalgebra::Vector2; pub struct JumpMove { last_jump: Instant, dir: f32, rng: ThreadRng, duration: f32, } impl JumpMove { pub fn default() -> Self {Self {last_jump: Instant::now(), dir: 0.2, rng: ThreadRng::default(), duration: 3.0}} } impl Component for JumpMove { fn create(&self) -> Box<dyn Component> {Box::new(Self::default())} fn update(&mut self, entity: &mut EntityMutor, _world: &mut WorldMutor, _meta: &Meta) { if self.last_jump.elapsed().as_secs_f32() > self.duration { self.last_jump = Instant::now(); entity.data().try_jump(); if self.rng.gen::<f32>() < 0.3 { self.dir *= -1.0; } } if !entity.data().is_grounded() { entity.data().add_speed_force_continuous(&Vector2::new(self.dir,0.0)); } } } <file_sep>/src/world/tiles/mod.rs mod tile; pub use tile::*; mod coord; pub use coord::TileCoord; mod master; pub use master::TileMaster; <file_sep>/src/engine/display.rs use std::time::Instant; use super::viewport::Viewport; use sdl2::surface::Surface; use sdl2::pixels::PixelFormatEnum; use anyhow::*; #[allow(unused)] pub struct Display { sdl: sdl2::Sdl, video_subsystem: sdl2::VideoSubsystem, context: sdl2::video::GLContext, window: sdl2::video::Window, last_update: Option<Instant>, delta_time: f32, event_pump: sdl2::EventPump, viewport: Viewport, } impl Display { pub fn new(mut icon: (Vec<u8>,u32,u32)) -> Result<Self> { let sdl = sdl2::init().map_err(|err| anyhow!(err)).context("Failed to get sdl")?; let video_subsystem = sdl.video().map_err(|err| anyhow!(err)).context("Failed to get video subsystem")?; let gl_attr = video_subsystem.gl_attr(); gl_attr.set_context_profile(sdl2::video::GLProfile::Core); gl_attr.set_context_version(4, 5); let mut window = video_subsystem .window("Hr. Langpat", 500, 500) .position_centered() .opengl() .resizable() .build()?; let surface = Surface::from_data(icon.0.as_mut_slice(), icon.1, icon.2, 0, PixelFormatEnum::RGBA32) .map_err(|err| anyhow!(err)).context("Failed to create icon surface")?; window.set_icon(surface); let context = window.gl_create_context().map_err(|err| anyhow!(err)).context("Failed to get gl context")?; let _gl = gl::load_with(|s| { video_subsystem.gl_get_proc_address(s) as *const std::os::raw::c_void }); let event_pump = sdl.event_pump().map_err(|err| anyhow!(err)).context("Failed to get event pump")?; let viewport = Viewport::new(500, 500); sdl.mouse().capture(true); Ok(Display { sdl, video_subsystem, context, window, last_update: None, delta_time: 0.0, event_pump, viewport }) } pub fn delta_time(&self) -> f32 { self.delta_time.min(0.05) // min 20 fps } pub fn frame_rate(&self) -> Option<f32> {if self.delta_time != 0.0 {Some(1.0 / self.delta_time)} else {None}} pub fn update(&mut self) { self.window.gl_swap_window(); if let Some(last_update) = self.last_update { self.delta_time = last_update.elapsed().as_secs_f32(); } self.last_update = Some(Instant::now()); } pub fn aspect_ratio(&self) -> f32 {self.viewport.aspect_ratio()} pub fn mouse_screen_coords(&self) -> (f32, f32) { let state = self.event_pump.mouse_state(); ( state.x() as f32 / self.viewport.width() as f32, state.y() as f32 / self.viewport.height() as f32, ) } pub fn poll_event(&mut self) -> Option<sdl2::event::Event> { use sdl2::event::{WindowEvent, Event}; if let Some(event) = self.event_pump.poll_event() { match event { Event::Window { win_event, .. } => { use WindowEvent::*; match win_event { Resized(w, h) => { self.viewport.set(w, h); } _ => {} } }, _ => {} } return Some(event); } None } } <file_sep>/src/engine/texture_atlas.rs use super::texture::Texture; pub struct TextureAtlas { texture: Texture, size: u32, } impl TextureAtlas { pub fn from_texture(texture: Texture, size: u32) -> Self { TextureAtlas { texture, size } } pub fn uv_bounds_from_index(&self, index:u32) -> (f32,f32,f32,f32) { let x_low: f32 = (index % self.size) as f32; let y_low = (index / self.size) as f32; // division between u32's should round down let size = self.size as f32; let subsize = 1.0 / size; ( x_low / size, y_low / size + subsize, // y's are swapped for some reason x_low / size + subsize, y_low / size, ) } pub fn size(&self) -> u32 {self.size} pub fn texture_id(&self) -> gl::types::GLuint {self.texture.id()} } <file_sep>/src/entities/components/components/player.rs use super::prelude::*; use nalgebra::Vector2; pub struct PlayerComponent { reach_distance: f32 } impl PlayerComponent { pub fn default() -> Self { PlayerComponent { reach_distance: 7.0, } } } impl Component for PlayerComponent { fn create(&self) -> Box<dyn Component> {Box::new(PlayerComponent::default())} fn update(&mut self, entity: &mut EntityMutor, world: &mut WorldMutor, meta: &Meta) { let center_position = entity.data().center(); entity .data() .set_is_facing_left(meta.mouse.1.x < center_position.x); if meta.input.left_is_held() { entity.data().add_force_continuous(&Vector2::new(-1.0,0.0)); } if meta.input.right_is_held() { entity.data().add_force_continuous(&Vector2::new(1.0,0.0)); } if meta.input.jump_was_pressed() {entity.data().try_jump();} if meta.input.primary_was_pressed() { if (meta.mouse.1 - center_position).magnitude() < self.reach_distance { world.break_tile(meta.mouse.0); } } else if meta.input.secondary_was_pressed() { if (center_position - meta.mouse.1).magnitude() < self.reach_distance { world.place_tile(meta.mouse.0, meta.tiles.tiles.get("Torch").unwrap().clone()); } } } } <file_sep>/src/engine/vao.rs use gl; use gl::types::*; pub struct VAO { id: GLuint, tri_count: i32, vert_vbo: GLuint, vbos: Vec<GLuint>, } impl VAO { pub fn empty() -> Self {VAO::from(vec![], vec![])} pub fn square() -> Self { let verts = vec![ 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, ]; let txs = vec![ 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0, ]; VAO::from(verts, txs) } pub fn update_verts(&mut self, verts: Vec<f32>) { self.tri_count = (verts.len() / 3) as i32; send_to_vbo(verts, self.vert_vbo); } pub fn update_float_vbo(&mut self, layout_location: u32, data: Vec<f32>) { unsafe { gl::BindVertexArray(self.id); send_to_vbo(data, self.vbos[layout_location as usize - 1]); gl::BindVertexArray(0); } } pub fn add_float_vbo_with(&mut self, component_count: i32, data: Vec<f32>) { self.add_float_vbo(component_count); self.update_float_vbo(self.vbos.len() as u32, data); } pub fn add_float_vbo(&mut self, component_count: i32) { let mut vbo: GLuint = 0; unsafe { gl::GenBuffers(1, &mut vbo); } self.vbos.push(vbo); unsafe { gl::BindVertexArray(self.id); gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::EnableVertexAttribArray(self.vbos.len() as u32); // layout location gl::VertexAttribPointer( self.vbos.len() as u32, // layout location component_count, // the number of values per vertex (vecX) gl::FLOAT, // data type gl::FALSE, // normalized (int-to-float conversion) (0 * std::mem::size_of::<f32>()) as gl::types::GLint, // stride (byte offset between consecutive attributes) std::ptr::null(), // offset of the first component ); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::DisableVertexAttribArray(self.vbos.len() as u32); // layout location gl::BindVertexArray(0); } } pub fn from(verts: Vec<f32>, txs: Vec<f32>) -> VAO { let tri_count = (verts.len() / 3) as i32; let vert_vbo = create_vbo(verts); let mut vao: GLuint = 0; unsafe { gl::GenVertexArrays(1, &mut vao); gl::BindVertexArray(vao); gl::BindBuffer(gl::ARRAY_BUFFER, vert_vbo); gl::EnableVertexAttribArray(0); // this is "layout (location = 0)" in vertex shader gl::VertexAttribPointer( 0, // index of the generic vertex attribute ("layout (location = 0)") 2, // the number of components per generic vertex attribute gl::FLOAT, // data type gl::FALSE, // normalized (int-to-float conversion) (0 * std::mem::size_of::<f32>()) as gl::types::GLint, // stride (byte offset between consecutive attributes) std::ptr::null(), // offset of the first component ); gl::BindBuffer(gl::ARRAY_BUFFER, 0); gl::BindVertexArray(0); } let mut vao = VAO { id: vao, vert_vbo, vbos: vec![], tri_count }; vao.add_float_vbo_with(2, txs); vao } pub fn id(&self) -> GLuint {self.id} pub fn tri_count(&self) -> i32 {self.tri_count} } impl Drop for VAO { fn drop(&mut self) { unsafe { gl::DeleteVertexArrays(1, &[self.id] as *const GLuint); // gl::DeleteBuffers(1, self.vbo as *const GLuint); } } } fn create_vbo(data: Vec<f32>) -> GLuint { let mut vbo: GLuint = 0; unsafe { gl::GenBuffers(1, &mut vbo); send_to_vbo(data, vbo); } vbo } fn send_to_vbo(data: Vec<f32>, vbo: GLuint) { unsafe { gl::BindBuffer(gl::ARRAY_BUFFER, vbo); gl::BufferData( gl::ARRAY_BUFFER, (data.len() * std::mem::size_of::<f32>()) as gl::types::GLsizeiptr, data.as_ptr() as *const gl::types::GLvoid, gl::STATIC_DRAW, ); gl::BindBuffer(gl::ARRAY_BUFFER, 0); } } <file_sep>/src/entities/master.rs use std::cell::RefCell; use std::any::TypeId; use std::collections::HashMap; use crate::engine::loader::Loader; use crate::engine::texture::{Texture, GLTexture}; use super::entity::{Entity,EntityData}; use super::components::ComponentMaster; use super::components::Component; use super::components::components::create_master; use nalgebra::Vector2; use anyhow::*; struct EntityTemplate { pub texture: Texture, pub mass: f32, pub components: HashMap<TypeId, Box<dyn Component>>, } impl EntityTemplate { pub fn instantiate(&self) -> Entity { let data = EntityData::new( self.texture.clone(), Vector2::new(0.0,2.0), Vector2::new(self.texture.width() as f32 / 8.0, self.texture.height() as f32 / 8.0), self.mass ); let mut components = HashMap::with_capacity(self.components.len()); for (id, cmp) in &self.components { components.insert(id.clone(), RefCell::new(cmp.create())); } Entity::new(data,components) } } pub struct EntityMaster { entities: Vec<EntityTemplate>, #[allow(unused)] component_master: ComponentMaster, } impl EntityMaster { pub fn load_and_create(loader: &Loader) -> Result<Self> { let mut entities = vec![]; let mut component_master = create_master(); let dirs = loader.read_dirs_in_dir("entities")?.into_iter(); for dir in dirs { let data = loader.load_toml(&format!("entities/{}/data.toml", dir))?; let texture = GLTexture::from_loader(loader, &format!("entities/{}/texture.png", dir))?; use toml::Value::*; let mass = match data["mass"] { Float(mass) => Ok(mass as f32), _ => Err(anyhow!("Expected mass to be a float")) }?; let mut components = HashMap::default(); if let Some(Array(dawd)) = data.get("components") { for table in dawd { let name = table["name"].as_str().ok_or(anyhow!("Non-string component name"))?; let (type_id, cmp) = component_master.create_instance(name)?; components.insert(type_id, cmp); } } entities.push(EntityTemplate { mass, texture, components }) } Ok(EntityMaster { entities, component_master, }) } pub fn instantiate_all(&self) -> Vec<Entity> { self.entities .iter() .map(|tmpl| tmpl.instantiate()) .collect() } pub fn add_component_to(&self, name: &str, entity: &mut Entity) -> Result<()> { let (id, cmp) = self.component_master.create_instance(name)?; unsafe {entity.add_component(id, cmp);} Ok(()) } } <file_sep>/src/input.rs use sdl2::keyboard::Keycode; use sdl2::mouse::MouseButton; #[derive(PartialEq,Eq)] pub enum ButtonState { Unpressed, Pressed, Held, } #[derive(PartialEq,Eq)] pub enum Button { Key(Keycode), MouseButton(MouseButton) } impl From<Keycode> for Button { fn from(key: Keycode) -> Self {Button::Key(key)} } impl From<MouseButton> for Button { fn from(btn: MouseButton) -> Self {Button::MouseButton(btn)} } pub struct Input { jump: (Button, ButtonState), right: (Button, ButtonState), left: (Button, ButtonState), up: (Button, ButtonState), down: (Button, ButtonState), primary: (Button, ButtonState), secondary: (Button, ButtonState), } #[allow(unused)] impl Input { pub fn new() -> Input { use ButtonState::Unpressed; use Keycode::*; Input { jump: (Space.into(), Unpressed), left: (A.into(), Unpressed), right: (D.into(), Unpressed), up: (W.into(), Unpressed), down: (S.into(), Unpressed), primary: (MouseButton::Left.into(), Unpressed), secondary: (MouseButton::Right.into(), Unpressed), } } #[warn(unused)] pub fn prepare_read(&mut self) { if self.jump.1 == ButtonState::Pressed {self.jump.1 = ButtonState::Held;} if self.left.1 == ButtonState::Pressed {self.left.1 = ButtonState::Held;} if self.right.1 == ButtonState::Pressed {self.right.1 = ButtonState::Held;} if self.up.1 == ButtonState::Pressed {self.up.1 = ButtonState::Held;} if self.down.1 == ButtonState::Pressed {self.down.1 = ButtonState::Held;} if self.primary.1 == ButtonState::Pressed {self.primary.1 = ButtonState::Held;} if self.secondary.1 == ButtonState::Pressed {self.secondary.1 = ButtonState::Held;} } #[warn(unused)] pub fn read_event(&mut self, event: &sdl2::event::Event) { use sdl2::event::Event; match event { Event::KeyDown { keycode: Some(key), repeat: false, .. } => {self.do_press(key.clone().into());}, Event::MouseButtonDown { mouse_btn: btn, .. } => {self.do_press(btn.clone().into());}, Event::KeyUp { keycode: Some(key), .. } => {self.do_release(key.clone().into());}, Event::MouseButtonUp { mouse_btn: btn, .. } => {self.do_release(btn.clone().into());}, _ => {} } } fn do_press(&mut self, key: Button) { if key == self.jump.0 {self.jump.1 = ButtonState::Pressed;} if key == self.left.0 {self.left.1 = ButtonState::Pressed;} if key == self.right.0 {self.right.1 = ButtonState::Pressed;} if key == self.up.0 {self.up.1 = ButtonState::Pressed;} if key == self.down.0 {self.down.1 = ButtonState::Pressed;} if key == self.primary.0 {self.primary.1 = ButtonState::Pressed;} if key == self.secondary.0 {self.secondary.1 = ButtonState::Pressed;} } fn do_release(&mut self, key: Button) { if key == self.jump.0 {self.jump.1 = ButtonState::Unpressed;} if key == self.left.0 {self.left.1 = ButtonState::Unpressed;} if key == self.right.0 {self.right.1 = ButtonState::Unpressed;} if key == self.up.0 {self.up.1 = ButtonState::Unpressed;} if key == self.down.0 {self.down.1 = ButtonState::Unpressed;} if key == self.primary.0 {self.primary.1 = ButtonState::Unpressed;} if key == self.secondary.0 {self.secondary.1 = ButtonState::Unpressed;} } pub fn jump_was_pressed(&self) -> bool {self.jump.1 == ButtonState::Pressed} pub fn jump_is_held(&self) -> bool {self.jump.1 != ButtonState::Unpressed} pub fn right_is_held(&self) -> bool {self.right.1 != ButtonState::Unpressed} pub fn left_is_held(&self) -> bool {self.left.1 != ButtonState::Unpressed} pub fn up_is_held(&self) -> bool {self.up.1 != ButtonState::Unpressed} pub fn down_is_held(&self) -> bool {self.down.1 != ButtonState::Unpressed} pub fn down_was_pressed(&self) -> bool {self.down.1 == ButtonState::Pressed} pub fn primary_was_pressed(&self) -> bool {self.primary.1 == ButtonState::Pressed} pub fn primary_is_held(&self) -> bool {self.primary.1 != ButtonState::Unpressed} pub fn secondary_was_pressed(&self) -> bool {self.secondary.1 == ButtonState::Pressed} pub fn secondary_is_held(&self) -> bool {self.secondary.1 != ButtonState::Unpressed} } <file_sep>/src/engine/loader.rs use std::path::{Path, PathBuf}; use std::fs::File; use std::io::Read; use std::ffi; use anyhow::*; pub struct Loader { root_path: PathBuf, } impl Loader { pub fn load_toml(&self, name: &str) -> Result<toml::Value> { use toml::*; let path = resource_name_to_path(&self.root_path, name); self.load_str(name)? .parse::<Value>() .map_err(|e| anyhow!(e)) .context("Tried to parse TOML file") } pub fn read_dirs_in_dir(&self, name: &str) -> Result<Vec<String>> { use std::fs; let dir = resource_name_to_path(&self.root_path, name); let mut dirs = vec![]; for entry in fs::read_dir(dir)? { let entry = entry?; if !entry.metadata()?.is_dir() {continue} let name = entry .file_name() .into_string() .map_err(|e| anyhow!("OsString conversion failure during read_dir on resource \"{}\":\n{:?}", name, e))?; dirs.push(name); } Ok(dirs) } pub fn from_relative_exe_path(rel_path: &Path) -> Result<Loader> { let exe_file_name = ::std::env::current_exe() .context("Could not get executable path")?; let exe_path = exe_file_name.parent() .context("Could not get executable path")?; Ok(Loader { root_path: exe_path.join(rel_path) }) } pub fn load_str(&self, name: &str) -> Result<String> { let mut file = self.open_file(name)?; // allocate buffer of the same size as file let mut buffer: Vec<u8> = Vec::with_capacity( file.metadata()?.len() as usize + 1 ); file.read_to_end(&mut buffer)?; String::from_utf8(buffer) .map_err(|e| anyhow!(e)) .context("Failed to load string from file") } pub fn load_cstring(&self, name: &str) -> Result<ffi::CString> { let mut file = self.open_file(name)?; // allocate buffer of the same size as file let mut buffer: Vec<u8> = Vec::with_capacity( file.metadata()?.len() as usize + 1 ); file.read_to_end(&mut buffer)?; // check for nul byte if buffer.iter().find(|i| **i == 0).is_some() { return Err(anyhow!("File contains null byte")); } Ok(unsafe { ffi::CString::from_vec_unchecked(buffer) }) } pub fn load_image(&self, name: &str) -> Result<(Vec<u8>,u32,u32)> { let file = self.open_file(name)?; let decoder = png::Decoder::new(file); let (info, mut reader) = decoder.read_info()?; let mut buf: Vec<u8> = vec![0; info.buffer_size()]; reader.next_frame(&mut buf)?; Ok((buf,info.width,info.height)) } fn open_file(&self, name: &str) -> Result<File> { let file = File::open( resource_name_to_path(&self.root_path, name) ).context(format!("Failed to open file \"{}\"", name))?; Ok(file) } } fn resource_name_to_path(root_dir: &Path, location: &str) -> PathBuf { let mut path: PathBuf = root_dir.into(); for part in location.split("/") { path = path.join(part); } path } <file_sep>/src/world/chunk_renderer.rs use gl; use gl::types::*; use crate::engine::loader::*; use crate::engine::program::Program; use crate::engine::shader::Shader; use crate::engine::texture_atlas::TextureAtlas; use super::camera::Camera; use super::chunk::Chunk; use nalgebra::Vector2; use anyhow::*; pub struct ChunkRenderer { program: Program, offset_loc: GLint, scale_loc: GLint, sky_light_scale_loc: GLint, } impl ChunkRenderer { pub fn create(loader: &Loader) -> Result<ChunkRenderer> { let vert_shader = Shader::from_vert_source(&loader.load_cstring("shaders/chunk_vert.glsl")?)?; let frag_shader = Shader::from_frag_source(&loader.load_cstring("shaders/chunk_frag.glsl")?)?; let program = Program::create(vert_shader, frag_shader)?; let offset_loc = program.get_uniform_location("offset")?; let scale_loc = program.get_uniform_location("scale")?; let sky_light_scale_loc = program.get_uniform_location("sky_light_scale")?; Ok(ChunkRenderer { program, offset_loc, scale_loc, sky_light_scale_loc, }) } pub fn render(&self, chunk: &Chunk, cam: &Camera, atlas: &TextureAtlas, aspect_ratio: f32, time: f32) { self.program.set_used(); unsafe { gl::ActiveTexture(gl::TEXTURE0); gl::BindTexture(gl::TEXTURE_2D, atlas.texture_id()); gl::TexParameterf( gl::TEXTURE_2D, gl::TEXTURE_MIN_FILTER, gl::NEAREST as GLfloat, ); gl::TexParameterf( gl::TEXTURE_2D, gl::TEXTURE_MAG_FILTER, gl::NEAREST as GLfloat, ); gl::Enable(gl::BLEND); gl::BlendFunc(gl::SRC_ALPHA, gl::ONE_MINUS_SRC_ALPHA); } Program::load_vec2(self.offset_loc, &(chunk.pos() - cam.position())); let zoom = cam.get_zoom(); Program::load_vec2(self.scale_loc, &Vector2::new(zoom / aspect_ratio, zoom)); Program::load_float(self.sky_light_scale_loc, time); unsafe { gl::BindVertexArray(chunk.vao().id()); gl::EnableVertexAttribArray(0); gl::EnableVertexAttribArray(1); gl::EnableVertexAttribArray(2); gl::EnableVertexAttribArray(3); gl::DrawArrays( gl::TRIANGLES, 0, // starting index chunk.vao().tri_count() * 3, ); gl::DisableVertexAttribArray(0); gl::DisableVertexAttribArray(1); gl::DisableVertexAttribArray(2); gl::DisableVertexAttribArray(3); gl::BindVertexArray(0); } unsafe { gl::BindTexture(gl::TEXTURE_2D, 0); gl::Disable(gl::BLEND); } } } <file_sep>/src/entities/mod.rs mod bounding_box; mod entity; pub use entity::*; mod renderer; pub use renderer::*; mod master; pub use master::*; pub mod components; <file_sep>/src/world/tiles/master.rs use std::collections::HashMap; use super::tile::Tile; #[macro_export] macro_rules! palette { ($master:expr, $($name:expr),*) => { [ $( $master.tiles.get($name).map(|t| t.clone()).ok_or_else( || anyhow!("Failed to get tile for palette: {}",$name) )?, )* ] } } pub struct TileMaster { pub tiles: HashMap<&'static str, Tile>, } impl TileMaster { pub fn create() -> Self { TileMaster { tiles: HashMap::new(), } } pub fn add(&mut self, name: &'static str, tile: Tile) { self.tiles.insert(name,tile); } } <file_sep>/src/engine/mod.rs pub mod program; pub mod shader; pub mod vao; pub mod loader; pub mod texture; pub mod texture_atlas; pub mod viewport; pub mod display; mod util; <file_sep>/src/world/map.rs use std::collections::HashMap; use super::{Chunk, CHUNK_SIZE_F}; const CHUNK_SIZE: isize = super::chunk::CHUNK_SIZE as isize; use super::tiles::{Tile,TileCoord}; use super::WorldGen; use super::lighting::{LightCalculator, MAX_LIGHT}; use nalgebra::Vector2; pub struct WorldMap { chunks: HashMap<Vector2<i32>, Chunk>, } impl WorldMap { pub fn new(generator: &WorldGen, light_calculator: &mut LightCalculator) -> Self { let mut chunks = HashMap::default(); for x in -5..=5 { for y in -3..=3 { chunks.insert(Vector2::<i32>::new(x,y), Chunk::new(x, y, &generator)); } } let mut map = WorldMap { chunks, }; for x in -5*CHUNK_SIZE..=5*CHUNK_SIZE { let mut y = 3 * CHUNK_SIZE; while !map.is_collidable_or_out_of_bounds(&Vector2::new(x as f32, y as f32)) { map.set_sky_light(TileCoord::from(x as f32, y as f32), MAX_LIGHT); y -= 1; } y += 1; light_calculator.add_sky(TileCoord::from(x as f32, y as f32), MAX_LIGHT) } light_calculator.process(&mut map); map } pub fn is_collidable_or_out_of_bounds(&self, pos: &Vector2<f32>) -> bool { if let Some(tile) = self.get_tile(pos) { return tile.is_collidable(); } true } pub fn is_collidable_or_out_of_bounds_at(&self, coord: TileCoord) -> bool { if let Some(tile) = self.get_tile_at(coord) { return tile.is_collidable(); } true } pub fn get_light(&self, coord: TileCoord) -> Option<u16> { self.chunk_at_tile_coord(coord)?.get_light(coord).into() } pub fn set_light(&mut self, coord: TileCoord, light: u16) -> Option<()> { self.chunk_at_tile_coord_mut(coord)?.set_light(coord, light).into() } pub fn get_sky_light(&self, coord: TileCoord) -> Option<u16> { self.chunk_at_tile_coord(coord)?.get_sky_light(coord).into() } pub fn set_sky_light(&mut self, coord: TileCoord, light: u16) -> Option<()> { self.chunk_at_tile_coord_mut(coord)?.set_sky_light(coord, light).into() } pub fn get_total_light_scale(&self, coord: TileCoord, sky_light_scale: f32) -> Option<f32> { let block_light = self.get_light(coord)? as f32; let sky_light = self.get_sky_light(coord)? as f32; Some(block_light.max(sky_light * sky_light_scale) / super::lighting::MAX_LIGHT_F) } pub fn set_tile(&mut self, coord: TileCoord, tile: Tile) -> Option<()> { self.chunk_at_tile_coord_mut(coord)?.set(coord, tile).into() } pub fn get_tile(&self, pos: &Vector2<f32>) -> Option<Tile> { self.chunk_at(pos)?.get(TileCoord::from_vec(pos)).into() } pub fn get_tile_at(&self, coord: TileCoord) -> Option<Tile> { self.chunk_at_tile_coord(coord)?.get(coord).into() } pub fn chunk_at(&self, pos: &Vector2<f32>) -> Option<&Chunk> { let key = Vector2::new((pos.x/16.0).floor() as i32,(pos.y/16.0).floor() as i32); self.chunks.get(&key) } pub fn chunk_at_mut(&mut self, pos: &Vector2<f32>) -> Option<&mut Chunk> { let key = Vector2::new((pos.x/16.0).floor() as i32,(pos.y/16.0).floor() as i32); self.chunks.get_mut(&key) } pub fn chunk_at_tile_coord(&self, coord: TileCoord) -> Option<&Chunk> { let key = Vector2::new(coord.chunk_x(),coord.chunk_y()); self.chunks.get(&key) } pub fn chunk_at_tile_coord_mut(&mut self, coord: TileCoord) -> Option<&mut Chunk> { let key = Vector2::new(coord.chunk_x(),coord.chunk_y()); self.chunks.get_mut(&key) } pub fn for_chunks_in_area<F>(&mut self, f: F, pos: &Vector2<f32>, radius: f32) where F: Fn(&mut Chunk) { let minx = ((pos.x - radius) / CHUNK_SIZE_F).floor() as i32; let maxx = ((pos.x + radius) / CHUNK_SIZE_F).ceil() as i32; let miny = ((pos.y - radius) / CHUNK_SIZE_F).floor() as i32; let maxy = ((pos.y + radius) / CHUNK_SIZE_F).ceil() as i32; for x in minx..maxx { for y in miny..maxy { if let Some(chunk) = self.chunks.get_mut(&Vector2::new(x,y)) { f(chunk); } } } } } <file_sep>/src/entities/components/mod.rs pub mod components; mod master; pub use master::*; <file_sep>/src/engine/shader.rs use gl; use std; use std::ffi::CStr; use gl::types::*; use super::util::*; use anyhow::*; pub struct Shader { id: GLuint, } impl Shader { pub fn from_source(source: &CStr, kind: GLenum) -> Result<Shader> { let id = shader_from_source(source, kind)?; Ok(Shader { id }) } pub fn from_vert_source(source: &CStr) -> Result<Shader> { Shader::from_source(source, gl::VERTEX_SHADER) } pub fn from_frag_source(source: &CStr) -> Result<Shader> { Shader::from_source(source, gl::FRAGMENT_SHADER) } pub fn id(&self) -> GLuint { self.id } } impl Drop for Shader { fn drop(&mut self) { unsafe { gl::DeleteShader(self.id); } } } fn shader_from_source(source: &CStr, kind: GLenum) -> Result<GLuint> { let id = unsafe { gl::CreateShader(kind) }; let mut success: GLint = 1; unsafe { gl::ShaderSource(id, 1, &source.as_ptr(), std::ptr::null()); gl::CompileShader(id); gl::GetShaderiv(id, gl::COMPILE_STATUS, &mut success); } if success == 0 { let mut len: GLint = 0; unsafe { gl::GetShaderiv(id, gl::INFO_LOG_LENGTH, &mut len); } let error = create_whitespace_cstring_with_len(len as usize); unsafe { gl::GetShaderInfoLog( id, len, std::ptr::null_mut(), error.as_ptr() as *mut GLchar, ); } return Err(anyhow!(error.to_string_lossy().into_owned())).context("Failed to compile shader"); } Ok(id) } <file_sep>/src/engine/program.rs use gl; use std; use std::ffi::CString; use gl::types::*; use super::util::*; use super::shader::*; use nalgebra::{Matrix4, Vector4, Vector2}; use anyhow::*; #[allow(unused)] pub struct Program { id: GLuint, vert: Shader, frag: Shader, } impl Program { pub fn create(vert_shader: Shader, frag_shader: Shader) -> Result<Program> { let program_id = unsafe { gl::CreateProgram() }; let mut success: gl::types::GLint = 1; unsafe { gl::AttachShader(program_id, vert_shader.id()); gl::AttachShader(program_id, frag_shader.id()); gl::LinkProgram(program_id); gl::ValidateProgram(program_id); gl::GetProgramiv(program_id, gl::LINK_STATUS, &mut success); } if success == 0 { let mut len: GLint = 0; unsafe { gl::GetProgramiv(program_id, gl::INFO_LOG_LENGTH, &mut len); } let error = create_whitespace_cstring_with_len(len as usize); unsafe { gl::GetProgramInfoLog( program_id, len, std::ptr::null_mut(), error.as_ptr() as *mut GLchar, ); } return Err(anyhow!(error.to_string_lossy().into_owned())); } unsafe { gl::DetachShader(program_id, vert_shader.id()); gl::DetachShader(program_id, frag_shader.id()); } Ok(Program { id: program_id, vert: vert_shader, frag: frag_shader }) } pub fn set_used(&self) { unsafe { gl::UseProgram(self.id); } } pub fn get_uniform_location(&self, name: &str) -> Result<GLint> { let cname = CString::new(name).or(Err(anyhow!("Uniform name contains null-byte")))?; let location = unsafe { gl::GetUniformLocation(self.id, cname.as_bytes_with_nul().as_ptr() as *const i8) }; match location { -1 => Err(anyhow!("Uniform \"{}\" not found",name)), _ => Ok(location) } } pub fn load_float(location: GLint, val: f32) { unsafe { gl::Uniform1f(location, val); } } pub fn load_vec2(location: GLint, vec: &Vector2<f32>) { unsafe { gl::Uniform2f(location, vec.x, vec.y); } } #[allow(unused)] pub fn load_vec4(location: GLint, vec: &Vector4<f32>) { unsafe { gl::Uniform4f(location, vec.x, vec.y, vec.z, vec.w); } } #[allow(unused)] pub fn load_mat4(location: GLint, mat: &Matrix4<f32>) { unsafe { gl::UniformMatrix4fv( location, 1, gl::FALSE, mat.as_slice().as_ptr() as *const f32 ); } } } impl Drop for Program { fn drop(&mut self) { unsafe { gl::DeleteProgram(self.id); } } } <file_sep>/src/world/world.rs use super::tiles::{Tile,TileCoord}; use super::world_gen::WorldGen; use super::lighting::LightCalculator; use super::map::WorldMap; use crate::entities::Entity; use crate::entities::components::Meta; use std::cell::RefCell; use nalgebra::Vector2; pub struct WorldData { light_calculator: LightCalculator, #[allow(unused)] generator: WorldGen, map: WorldMap, air_tile: Tile, } pub struct World { data: WorldData, entities: Vec<RefCell<Entity>>, // TODO: store in some faster data structure for lookup/queries } pub struct WorldMutor<'a> (&'a mut WorldData, &'a Vec<RefCell<Entity>>); impl<'a> WorldMutor<'a> { pub fn entities_in_range(&mut self, pos: &Vector2<f32>, range: f32, f: impl Fn(&mut Entity)) { for ent in self.1.iter() { if let Ok(mut ent) = ent.try_borrow_mut() { if (pos - ent.position()).magnitude() < range {f(&mut ent);} } } } } impl<'a> std::ops::Deref for WorldMutor<'a> { type Target = WorldData; fn deref(&self) -> &WorldData {self.0} } impl<'a> std::ops::DerefMut for WorldMutor<'a> { fn deref_mut(&mut self) -> &mut WorldData {self.0} } impl std::ops::Deref for World { type Target = WorldData; fn deref(&self) -> &WorldData {&self.data} } impl std::ops::DerefMut for World { fn deref_mut(&mut self) -> &mut WorldData {&mut self.data} } impl World { pub fn new(palette: [Tile; 4], palette2: [Tile; 4], seed: u32, air_tile: Tile) -> Self { let generator = WorldGen::new(palette, palette2, seed); let mut light_calculator = LightCalculator::default(); let map = WorldMap::new(&generator, &mut light_calculator); World { data: WorldData { light_calculator, generator, map, air_tile, }, entities: vec![], } } pub fn update(&mut self, meta: &Meta) { self.data.light_calculator.process(&mut self.data.map); let mut mutor = WorldMutor (&mut self.data, &self.entities); for entity in &self.entities { entity.borrow_mut().update(&mut mutor, meta); } } pub fn tmp(&mut self, ents: Vec<Entity>) { for ent in ents { self.entities.push(RefCell::new(ent)); } } pub fn foreach_entity(&self, f: impl Fn(&Entity)) { for ent in &self.entities { f(&ent.borrow()); } } } impl WorldData { pub fn map(&self) -> &WorldMap {&self.map} pub fn map_mut(&mut self) -> &mut WorldMap {&mut self.map} pub fn break_tile(&mut self, coord: TileCoord) -> Option<()> { let prev_tile = self.map.get_tile_at(coord)?; prev_tile.before_break(coord, &mut self.map)?; self.map.set_tile(coord, self.air_tile.clone()); self.light_calculator.update(&mut self.map, coord, prev_tile, self.air_tile.clone()); Some(()) } pub fn place_tile(&mut self, coord: TileCoord, tile: Tile) -> Option<()> { let prev_tile = self.map.get_tile_at(coord)?; if !prev_tile.replaceable() {return None} tile.before_place(coord, &mut self.map)?; self.map.set_tile(coord, tile.clone())?; self.light_calculator.update(&mut self.map, coord, prev_tile, tile); Some(()) } } <file_sep>/src/world/ray.rs const EPSILON: f32 = 0.0001; use super::map::WorldMap; use nalgebra::Vector2; pub struct Ray { position: Vector2<f32>, direction: Vector2<f32>, max_dist: f32, min_dist: f32, ignore_origin: bool, } #[allow(unused)] impl Ray { pub fn new(pos: &Vector2<f32>, dir: &Vector2<f32>) -> Self { Ray { position: pos.clone(), direction: dir.clone(), max_dist: 0.0, min_dist: 0.0, ignore_origin: false } } pub fn ignore_origin(mut self) -> Self { self.ignore_origin = true; self } pub fn minimum_distance(mut self, dist: f32) -> Self { self.min_dist = dist; self } pub fn maximum_distance(mut self, dist: f32) -> Self { self.max_dist = dist; self } pub fn cast(&self, map: &WorldMap) -> Option<Vector2<f32>> { let mut cur = self.position.clone(); let dir = &self.direction; if !self.ignore_origin && map.is_collidable_or_out_of_bounds(&cur) { if self.min_dist > 0.0 {return None;} else {return Some(cur);} } 'rayloop: loop { let mut dx = cur.x.ceil() - cur.x; let mut dy = cur.y.ceil() - cur.y; let t: f32; let used_x: bool; if dir.x < 0.0 {dx -= 1.0;} if dir.y < 0.0 {dy -= 1.0;} if dir.x == 0.0 { t = dy/dir.y; used_x = false; } else if dir.y == 0.0 { t = dx/dir.x; used_x = true; } else { let (t0, used_x0) = min(dx/dir.x, dy/dir.y); t = t0; used_x = used_x0; } cur += t * dir; if self.max_dist > 0.0 && (cur - self.position).magnitude() > self.max_dist {return None;} if used_x { if dir.x < 0.0 { cur.x -= EPSILON; } else {cur.x += EPSILON;} } else { if dir.y < 0.0 { cur.y -= EPSILON; } else {cur.y += EPSILON;} } if map.is_collidable_or_out_of_bounds(&cur) {break 'rayloop;} } if self.min_dist > 0.0 && (cur - self.position).magnitude() < self.min_dist {None} else {Some(cur)} } } fn min(a: f32, b: f32) -> (f32, bool) { if a <= b {(a,true)} else {(b,false)} } <file_sep>/src/engine/viewport.rs pub struct Viewport { width: i32, height: i32, } impl Viewport { pub fn new(width:i32, height: i32) -> Self { Viewport { width, height } } pub fn aspect_ratio(&self) -> f32 { self.width as f32 / self.height as f32 } pub fn set(&mut self, w: i32, h: i32) { self.width = w; self.height = h; self.update(); } pub fn width(&self) -> i32 {self.width} pub fn height(&self) -> i32 {self.height} pub fn update(&self) { unsafe { gl::Viewport(0, 0, self.width, self.height); } } } <file_sep>/src/world/tiles/tile.rs use super::super::map::WorldMap; use super::coord::TileCoord; use super::super::lighting::MAX_LIGHT; use std::rc::Rc; #[derive(Clone)] pub struct Tile { rc: Rc<Box<dyn TileT>>, } impl PartialEq for Tile { fn eq(&self, other: &Tile) -> bool { std::ptr::eq(self.rc.as_ref(), other.rc.as_ref()) } } impl std::ops::Deref for Tile { type Target = Box<dyn TileT>; fn deref(&self) -> &Box<dyn TileT> {&self.rc} } pub struct SimpleTile { collidable: bool, data: u8, } impl SimpleTile { pub fn air() -> Tile {Tile { rc: Rc::new(Box::new(SimpleTile { data: 0, collidable: false, }))}} pub fn from(data: u8, collidable: bool) -> Tile {Tile { rc: Rc::new(Box::new(SimpleTile { data: data + 1, collidable, }))}} } impl TileT for SimpleTile { fn replaceable(&self) -> bool {self.data == 0} fn light_emission(&self) -> u16 {if self.data == 6 {MAX_LIGHT} else {0}} fn texture_index(&self) -> u32 {self.data as u32 - 1} fn is_collidable(&self) -> bool {self.collidable} fn should_render(&self) -> bool {self.data != 0} fn light_obstruction(&self) -> u16 {if self.data == 0 {1} else {5}} } pub struct MultiTile { atlas_height: u8, texture: (u8,u8), size: (u8,u8), offset: (u8,u8), } impl MultiTile { pub fn test(offset:(u8,u8), atlas_height: u8, texture: (u8,u8), size: (u8,u8)) -> Tile { Tile { rc: Rc::new(Box::new(MultiTile {atlas_height, texture, size, offset})) } } } impl TileT for MultiTile { fn texture_index(&self) -> u32 { self.texture.0 as u32 + self.texture.1 as u32 * self.atlas_height as u32 } fn is_collidable(&self) -> bool {false} fn before_break(&self, coord: TileCoord, map: &mut WorldMap) -> Option<()> { for x in 0 ..= self.size.0 as i32 { for y in 0 ..= self.size.1 as i32 { map.set_tile(TileCoord::new(x+coord.x-self.offset.0 as i32, y+coord.y-self.offset.1 as i32), SimpleTile::air()); } } Some(()) } fn before_place(&self, coord: TileCoord, map: &mut WorldMap) -> Option<()> { for x in 0 .. self.size.0 as i32 { for y in 0 .. self.size.1 as i32 { map.set_tile( TileCoord::new(x+coord.x-self.offset.0 as i32, y+coord.y-self.offset.1 as i32), MultiTile::test((x as u8,y as u8),self.atlas_height,(self.texture.0+x as u8,self.texture.1+y as u8),self.size) ); } } Some(()) } } #[allow(unused)] pub trait TileT { fn replaceable(&self) -> bool {false} fn light_emission(&self) -> u16 {0} fn light_obstruction(&self) -> u16 {1} fn texture_index(&self) -> u32; fn is_collidable(&self) -> bool {true} fn should_render(&self) -> bool {true} fn before_break(&self, coord: TileCoord, map: &mut WorldMap) -> Option<()> {Some(())} fn before_place(&self, coord: TileCoord, map: &mut WorldMap) -> Option<()> {Some(())} } <file_sep>/src/items/mod.rs pub mod renderer; pub mod item;
fcdc55dc854b52cbccdc8ebd8489a68e4376a47f
[ "TOML", "Rust" ]
40
TOML
SilasPC/RustyBoi
2ae0f272ab140457fb1f865dd34521b6aa335de4
4a37815c56d0e9b8630964162320e4bc5ae43559