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
|
<repo_name>christopheleduc/Jeu_du_taquin<file_sep>/script_cl.js
// mouvements possibles
const HAUT = "H";
const BAS = "B";
const DROITE = "D";
const GAUCHE = "G";
// nombre de cases par côtégit
var side = 4;
// changement de style css en fonction de "side"
document.documentElement.style.setProperty("--side", side);
// retient l'état courant du taquin
var current_state = [];
// position de la case vide
const empty_cell = {i: 0, j:0};
// Tableau qui reçoit l'image du jeu réussit
let winner = [];
// Tableau qui reçoit le chemin
let soluce = [];
let test_a = [];
// Initialisation de l'état courant
function setInitState () {
current_state = []; // on vide le {tableau
var l = side; // l = nombre de cases par côté
for (var i = 0; i < l; i++) {
current_state[i] = [];
for (var j = 0; j < l; j++) {
if (i == l-1 && j == l-1) {
val = 0;
} else {
val = i*l + j + 1;
}
current_state[i][j] = val;
}
}
empty_cell.i = side-1;
empty_cell.j = side-1;
winner = $.extend(true, [], current_state);
//winner = current_state;
//return winner;
}
// execute les mouvements
function applyMove(state, ec, move) {
// Si Bas sauf ligne 0 (i = 0)
if (move == BAS && ec.i > 0) {
let a = state [ec.i-1] [ec.j];
state [ec.i] [ec.j] = a;
state [ec.i-1] [ec.j] = 0;
// state [ec.i].splice([ec.j] , 1 , a);
// state [ec.i-1].splice([ec.j] , 1 , 0);
ec.i = ec.i-1;
// Si Haut sauf ligne 3 (i = 3)
} else if (move == HAUT && ec.i < 3) {
let a = state[ec.i+1][ec.j];
//console.log(a);
state [ec.i] [ec.j] = a;
state [ec.i+1] [ec.j] = 0;
//state [ec.i].splice([ec.j] , 1 , a);
//state [ec.i+1].splice([ec.j] , 1 , 0);
ec.i = ec.i+1;
// Si Droite sauf Colonne 0 (j = 0)
} else if (move == DROITE && ec.j > 0) {
let a = state[ec.i][ec.j-1];
//console.log(a);
state [ec.i] [ec.j] = a;
state [ec.i] [ec.j-1] = 0;
// state [ec.i].splice([ec.j] , 1 , a);
// state [ec.i].splice([ec.j-1] , 1 , 0);
ec.j = ec.j-1;
// Si Gauche sauf Colonne 3 (j = 3)
} else if (move == GAUCHE && ec.j < 3) {
let a = state[ec.i][ec.j+1];
//console.log(a);
state [ec.i][ec.j] = a;
state [ec.i][ec.j+1] = 0;
// state [ec.i].splice([ec.j] , 1 , a);
// state [ec.i].splice([ec.j+1] , 1 , 0);
ec.j = ec.j+1;
}
displayState(state);
}
// lien calcul ==> HTML
function displayState(tab) {
$(".grid").empty();
for (let i = 0; i < tab.length; i++) {
for (let j = 0; j < tab[i].length; j++) {
const elem = tab[i][j];
if (elem) {
const item = $(
`<div data-i="${i}" data-j="${j}" class="item">${elem}</div>`
);
$(".grid").append(item);
} else {
$(".grid").append(`<div class="vide"></div>`);
}
}
}
}
$(".check").click(function() {
console.log("Is winning? ", checkWin(current_state));
checkWin (actuel_state);
// TODO: penser à implémenter la fonction checkWin
});
$(".reset").click(reset);
$(".shuffle").click(function() {
console.log("trd")
// pas le temps de faire le shuffle
doRandomShuffle(current_state, empty_cell, soluce);
displayState (current_state);
});
// Clic Solution
$(".solution").click(function() {
console.log("Solution demandée par l'utilisateur·ice")
findSolution(current_state, empty_cell, soluce);
});
// Fonction Solution
function findSolution(curr_state, emp_cell, sole) {
// for(var i = 0, len = sole.length; i < len; ++i) {
// console.log(i);
// console.log(sole[i]);
// applyMove(curr_state, emp_cell, sole[i]);
// }
var i = 0;
var soleInterne = sole;
len = sole.length;
let intervalID = setInterval(function()
{
console.log(i);
console.log(soleInterne[i]);
applyMove(curr_state, emp_cell, soleInterne[i]);
if (i == soleInterne.length-1) {
clearInterval(intervalID)};
++i;
}, 1000);
console.log(sole);
sole = [];
soluce = sole;
//setInitState();
//displayState (current_state);
//return (soluce);
}
// Pour augmenter / diminuer la taille d'un côté.
$(".plus").click(function() {
document.documentElement.style.setProperty("--side", ++side);
reset();
console.log("Plus grand")
});
$(".minus").click(function() {
document.documentElement.style.setProperty("--side", --side);
reset();
console.log("Plus petit")
});
// Clic Shuffle
$(".shuffle").click(function () {
//reset();
doRandomShuffle(current_state, empty_cell, soluce);
displayState(current_state);
//soluce = [];
});
// Fonction shuffle
function doRandomShuffle(current_state, e_cell, soluce) {
let altern = 173;
for (let k = 0; k < altern; k++) {
let random = Math.floor(Math.random() * (5 - 1 + 1)) + 1;
if (random === 1 && e_cell.i < 3) {
applyMove(current_state, e_cell, "H");
test_a.push("B");
soluce.unshift("B");
} else if (random === 2 && e_cell.i > 0) {
applyMove(current_state, e_cell, "B");
test_a.push("H");
soluce.unshift("H");
} else if (random === 3 && e_cell.j > 0) {
applyMove(current_state, e_cell, "D");
test_a.push("G");
soluce.unshift("G");
} else if (random === 4 && e_cell.j < 3) {
applyMove(current_state, e_cell, "G");
test_a.push("D");
soluce.unshift("D");
} else {
}
}
console.log("normal: " + test_a);
console.log("inverse: " + soluce);
//return (soluce);
}
// Ici on gere l'ajout dynamique de .item
$(".grid").on('click', '.item', function(){
console.log("J'existe et resisterai à ma mort dans un reset/ shuffle ",
"Valeur:", $(this).html(),
"Position i:", $(this).attr("data-i"),
"Position j:", $(this).attr("data-j")
)
});
// Avec le code ci-dessous, j'ai des problèmes à chaque reset car les item sont
// supprimés.
// Pas de gestion dynamique de .item
// $(".item").click(function(){
// console.log("Je n'existe que jusqu'à ma mort dans un reset/ shuffle")
//
// Une jolie fenetre est prévue pour quand on gagne
var modal = document.getElementById("myModal");
// Pour fermer la fenetre avec un "X"
var span = document.getElementsByClassName("close")[0];
// Pour afficher la fenetre quand on a gagné, appeler cette fonction
function displayWin () {
modal.style.display = "block";
}
// Quand on clique sur <span> (x), on ferme
span.onclick = function() {
modal.style.display = "none";
}
// On ferme aussi si on clique n'importe où
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
// Pour récupérer l'appui sur les flèches du clavier
document.onkeydown = checkKey;
function checkKey(e) {
e = e || window.event;
if (e.keyCode == 38 && empty_cell.i < 3) {
soluce.unshift("B");
// up arrow
applyMove (current_state, empty_cell, HAUT);
}
else if (e.keyCode == 40 && empty_cell.i > 0) {
soluce.unshift("H");
applyMove (current_state, empty_cell, BAS);
}
else if (e.keyCode == 37 && empty_cell.j < 3) {
soluce.unshift("D");
// left arrow
applyMove (current_state, empty_cell, GAUCHE);
}
else if (e.keyCode == 39 && empty_cell.j > 0) {
soluce.unshift("G");
// right arrow
applyMove (current_state, empty_cell, DROITE);
}
displayState(current_state);
if (checkWin(current_state)) {
displayWin();
}
}
function checkWin (actuel_state) {
if (JSON.stringify(winner) != JSON.stringify(actuel_state)) {
console.log("Sorry, you loose !");
console.log("CurrentState: " + JSON.stringify(actuel_state));
console.log("Winner: " + JSON.stringify(winner));
return (false);
} else {
console.log("Congratulation, you win !");
console.log("CurrentState: " + JSON.stringify(actuel_state));
console.log("Winner: " + JSON.stringify(winner));
return (true);
}
//console.log("checkwin");
}
function reset () {
soluce = [];
setInitState();
displayState (current_state);
//return (soluce);
}
// Affichage initial : on fait un reset
reset();
//winner = setInitState();
|
bb7b956816b597cfe967c7c4f3adb50c02b81d09
|
[
"JavaScript"
] | 1
|
JavaScript
|
christopheleduc/Jeu_du_taquin
|
fbd3d7f910167411cba50f5dd0374b1afd862276
|
12695bf9ecb2f96c89f9b76df3ee9cb62536193b
|
refs/heads/master
|
<repo_name>York5/MyRepo<file_sep>/js/test.js
function show() {
console.log('Hello World!');
}
function show2() {
console.log('Javascript is Awesome')
}
|
10c0fbef6f52fa6e7000ece43bd8939e51897750
|
[
"JavaScript"
] | 1
|
JavaScript
|
York5/MyRepo
|
a31ed30ad02111c7ec5eb980e11ab9a3e13881b1
|
4c45c00bf528aab39a47e68ca7bc63bc5e7f08dd
|
refs/heads/master
|
<repo_name>minnie-J/Hello<file_sep>/Hello/src/main/java/hello/minhee/domain/ImagesDomain.java
package hello.minhee.domain;
public class ImagesDomain {
private int ino;
private int pno;
private String url;
public ImagesDomain() {}
public ImagesDomain(int ino, int pno, String url) {
this.ino = ino;
this.pno = pno;
this.url = url;
}
public int getIno() {
return ino;
}
public void setIno(int ino) {
this.ino = ino;
}
public int getPno() {
return pno;
}
public void setPno(int pno) {
this.pno = pno;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
}
<file_sep>/Hello/src/main/java/hello/minhee/dao/ImagesMapper.java
package hello.minhee.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import hello.minhee.domain.ImagesDomain;
@Mapper
public interface ImagesMapper {
// 어노테이션 방식
// 프로젝트 번호에 해당되는 이미지 불러옴
@Select("select * from images where pno = #{pno}")
public List<ImagesDomain> selectImagesByPno(@Param("pno") int pno);
// xml방식 - 그냥 연습 예제
public List<ImagesDomain> selectByIno(int ino);
}
<file_sep>/Hello/src/main/java/hello/minhee/dao/ProjectsMapper.java
package hello.minhee.dao;
import java.util.List;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import hello.minhee.domain.ProjectsDomain;
@Mapper
public interface ProjectsMapper {
// 전체 프로젝트 리스트 - 메인 페이지에 리스트로 가져옴
@Select("select * from projects")
public List<ProjectsDomain> selectAll();
// // 번호에 해당되는 프로젝트 - 모달 호출때 필요
// @Select("select * from projects where pno = #{pno}")
// public List<ProjectsDomain> selectByPno(@Param("pno") int pno);
// 번호에 해당되는 프로젝트 - 모달 호출때 필요.. 리스트말고 한줄만있어도 되는거잖아?
@Select("select * from projects where pno = #{pno}")
public ProjectsDomain selectByPno(@Param("pno") int pno);
}
<file_sep>/Hello/src/main/java/hello/minhee/service/ImagesService.java
package hello.minhee.service;
import java.util.List;
import hello.minhee.domain.ImagesDomain;
public interface ImagesService {
public List<ImagesDomain> selectImagesByPno(int pno);
public List<ImagesDomain> selectByIno(int ino);
}
<file_sep>/Hello/src/main/java/hello/minhee/controller/ImagesController.java
package hello.minhee.controller;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import hello.minhee.domain.ImagesDomain;
import hello.minhee.service.ImagesService;
@RestController
@RequestMapping(value = "/images")
public class ImagesController {
private static final Logger logger = LoggerFactory.getLogger(ImagesController.class);
@Autowired
private ImagesService imagesService;
@RequestMapping(value = "/all/{pno}", method = RequestMethod.GET)
public ResponseEntity<List<ImagesDomain>> selectImagesByPno(
@PathVariable(name = "pno") Integer pno) {
logger.info("selectImagesByPno(pno: {})", pno);
List<ImagesDomain> imageList = imagesService.selectImagesByPno(pno);
ResponseEntity<List<ImagesDomain>> entity = new ResponseEntity<List<ImagesDomain>>(imageList, HttpStatus.OK);
return entity;
}
}
<file_sep>/Hello/src/main/java/hello/minhee/service/ImagesServiceImple.java
package hello.minhee.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import hello.minhee.dao.ImagesMapper;
import hello.minhee.domain.ImagesDomain;
@Service
public class ImagesServiceImple implements ImagesService {
@Autowired
private ImagesMapper imagesMapper;
@Override
public List<ImagesDomain> selectImagesByPno(int pno) {
return imagesMapper.selectImagesByPno(pno);
}
@Override
public List<ImagesDomain> selectByIno(int ino) {
return imagesMapper.selectByIno(ino);
}
}
|
1057bbbb92634f183ae5e2aa0b7ea521ea5fa4ac
|
[
"Java"
] | 6
|
Java
|
minnie-J/Hello
|
8f27efa3e4bf7f17211250bb921384716f9dc052
|
fe07b9b4f4d20c7afe680ea2e6f34a7cd49bcf48
|
refs/heads/master
|
<repo_name>natalie-mbula/nana<file_sep>/PathFinder-Refurb.ino
#include <Wire.h>
#include <LCD.h>
#include <LiquidCrystal_I2C.h>
const int trigPin = 22 ; // Sonar sensor pin Trigger
const int echoPin = 23 ; // Sonar sensor pin Echo
long duration ; // Sonar Duration Variable
const int pathS1 = 52;
const int pathS2 = 50;
const int pathS3 = 48;
const int pathS4 = 46;
const int pathS5 = 44;
const int touchPin = 42; // Touch Sensor on the 5 Channel Line Tracker Sensor.
int S1, S2, S3, S4, S5, S6 ;
const int Motor1A = 2;
const int Motor1B = 3;
const int Motor2A = 5;
const int Motor2B = 4;
const int PWM1 = 6;
const int PWM2 = 7;
const int ledLeft = 31; // signals as the robot turns Left....
const int ledRight = 30; // signals as the robot turns Right....
const int buzzerPin = 10;
#define I2C_ADDR 0x3F //Define I2C Address
#define BACKLIGHT_PIN 3
#define En_pin 2
#define Rw_pin 1
#define Rs_pin 0
#define D4_pin 4
#define D5_pin 5
#define D6_pin 6
#define D7_pin 7
LiquidCrystal_I2C lcd(I2C_ADDR, En_pin,Rw_pin,Rs_pin,D4_pin,D5_pin,D6_pin,D7_pin);
void setup() {
Serial.begin(9600); // connect serial
pinMode(Motor1A, OUTPUT);
pinMode(Motor1B, OUTPUT);
pinMode(Motor2A, OUTPUT);
pinMode(Motor2B, OUTPUT);
pinMode(PWM1, OUTPUT);
pinMode(PWM2, OUTPUT);
pinMode( pathS1 , INPUT);
pinMode( pathS2 , INPUT);
pinMode( pathS3 , INPUT);
pinMode( pathS4 , INPUT);
pinMode( pathS5 , INPUT);
pinMode( touchPin , INPUT);
pinMode( ledLeft , OUTPUT);
pinMode( ledRight , OUTPUT);
pinMode( buzzerPin , OUTPUT);
digitalWrite( ledLeft , LOW );
digitalWrite( ledRight , LOW );
digitalWrite( buzzerPin , LOW );
digitalWrite(Motor1A, LOW);
digitalWrite(Motor1B, LOW);
digitalWrite(Motor2A, LOW);
digitalWrite(Motor2B, LOW);
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
lcd.begin (20,4);
//Switch on the backlight
lcd.setBacklightPin(BACKLIGHT_PIN,POSITIVE);
lcd.setBacklight(HIGH);
//goto first column (column 0) and first line (Line 0)
lcd.setCursor(0,0);
lcd.print(" -RIARA UNIVERSITY- ");
//goto first column (column 0) and second line (line 1)
lcd.setCursor(0,1);
lcd.print(" Robotics Contest ");
lcd.setCursor(0,2);
lcd.print(" - - - - -- - - - - ");
lcd.setCursor(0,3);
lcd.print(" - - - - -- - - - - ");
delay(5000);
lcd.setCursor(0,2);
lcd.print(" -ROBOT NAVIGATING- ");
analogWrite(buzzerPin, 0);
searchPath();
}
void loop() {
while( checkObjectDistance() > 20 )
{
digitalWrite(ledRight, LOW); // Switch off signals
digitalWrite(ledLeft, LOW);
readpathsensor();
// Robot moving on the path - While there is no object on the path.
while (S1 == 0 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 0 &&( checkObjectDistance() > 20 ))
{
digitalWrite(ledRight, LOW);
digitalWrite(ledLeft, LOW);
analogWrite(PWM1, 200);
analogWrite(PWM2, 180);
lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,2);
lcd.print(" ON PATH ");
lcd.setCursor(0,3);
lcd.print(" ");
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
readpathsensor();
}
// Robot deviating to the left
while ((S1 == 0 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 1 ) || (S1 == 0 && S2 == 0 && S3 == 1 && S4 == 1 && S5 == 1 ) || (S1 == 0 && S2 == 0 && S3 == 0 && S4 == 1 && S5 == 1 ) || (S1 == 0 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 1 )&&( checkObjectDistance() > 20 ))
{
digitalWrite(ledRight, HIGH);
digitalWrite(ledLeft, LOW);
analogWrite(PWM1, 80);
analogWrite(PWM2, 145);
lcd.setCursor(0,2);
lcd.print(" Deviating Left ");
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
readpathsensor();
}
// Robot deviating to the Right
while ( ( S1 == 1 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 0 ) || ( S1 == 1 && S2 == 1 && S3 == 1 && S4 == 0 && S5 == 0 ) || ( S1 == 1 && S2 == 1 && S3 == 0 && S4 == 0 && S5 == 0 ) || ( S1 == 1 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 0 )&&( checkObjectDistance() > 20 ))
{
digitalWrite(ledRight, LOW );
digitalWrite(ledLeft, HIGH);
analogWrite(PWM1, 130);
analogWrite(PWM2, 60);
lcd.setCursor(0,2);
lcd.print(" Deviating Right ");
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
readpathsensor();
}
if (S1 == 0 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 0 )
{
digitalWrite(ledRight, LOW);
digitalWrite(ledLeft, LOW);
lcd.setCursor(0,2);
lcd.print(" -- NO PATH -- ");
digitalWrite(Motor1A, LOW);
digitalWrite(Motor1B, LOW);
digitalWrite(Motor2A, LOW);
digitalWrite(Motor2B, LOW);
robotTurnRight();
readpathsensor();
}
// No path available - The robot should not move
if (S1 == 1 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 1 )
{
digitalWrite(ledRight, LOW);
digitalWrite(ledLeft, LOW);
lcd.setCursor(0,2);
lcd.print(" -PATH NOT DEFINED- ");
digitalWrite(Motor1A, LOW);
digitalWrite(Motor1B, LOW);
digitalWrite(Motor2A, LOW);
digitalWrite(Motor2B, LOW);
readpathsensor();
robotTurnRight();
}
}
objectFound();
}
int checkObjectDistance(){
digitalWrite(trigPin, LOW);
delayMicroseconds(5);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
pinMode(echoPin, INPUT);
duration = pulseIn(echoPin, HIGH);
long cm = (duration/2) / 29.1;
Serial.print(cm);
Serial.print("cm");
Serial.println();
return cm;
}
void hoot(){
tone(buzzerPin, 400, 1000);
delay(300);
tone(buzzerPin, 450, 1000);
delay(300);
tone(buzzerPin, 500, 1500);
noTone(buzzerPin);
}
void readpathsensor(){
S1 = digitalRead(pathS1);
S2 = digitalRead(pathS2);
S3 = digitalRead(pathS3);
S4 = digitalRead(pathS4);
S5 = digitalRead(pathS5);
return S1, S2, S3, S4, S5;
}
void brake(){
digitalWrite(Motor1A, HIGH);
digitalWrite(Motor1B, HIGH);
digitalWrite(Motor2A, HIGH);
digitalWrite(Motor2B, HIGH);
}
void robotTurnRight(){
analogWrite(PWM1, 160);
analogWrite(PWM2, 160);
digitalWrite(Motor1A, HIGH); //
digitalWrite(Motor1B, LOW); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
delay(200);
readpathsensor();
while ( S1 == 0 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 0 )
{
digitalWrite(ledRight, LOW ); //
digitalWrite(ledLeft, HIGH); // signaling the robot turning Left
analogWrite(PWM1, 160);
analogWrite(PWM2, 160);
lcd.setCursor(0,2);
lcd.print(" Turning Right ");
digitalWrite(Motor1A, HIGH); //
digitalWrite(Motor1B, LOW); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
readpathsensor();
}
delay(200);
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, LOW); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, LOW); //
delay(100);
return;
}
void robotTurnLeft(){
analogWrite(PWM1, 160);
analogWrite(PWM2, 160);
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, HIGH); //
digitalWrite(Motor2B, LOW); //
delay(200);
readpathsensor();
while ( S1 == 0 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 0 )
{
digitalWrite(ledRight, HIGH );
digitalWrite(ledLeft, LOW);
analogWrite(PWM1, 180);
analogWrite(PWM2, 200);
lcd.setCursor(0,2);
lcd.print(" Turning Left ");
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, HIGH); //
digitalWrite(Motor2B, LOW); //
readpathsensor();
}
delay(200);
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, LOW); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, LOW); //
delay(100);
return;
}
void searchPath(){
lcd.setCursor(0,1);
lcd.print("Robot searching path");
lcd.setCursor(0,2);
lcd.print(" .................. ");
lcd.setCursor(0,3);
lcd.print(" - PLEASE WAIT. - ");
readpathsensor();
if(S1 == 0 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 0){
brake();
readpathsensor();
return;
}
while(checkObjectDistance > 20){
readpathsensor();
if(S1 == 0 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 0 && (checkObjectDistance > 20)){
analogWrite(PWM1, 160);
analogWrite(PWM2, 160);
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
readpathsensor();
}
if (S1 == 1 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 0 && (checkObjectDistance > 20) )
{
while( S3 != 1 )
{
analogWrite(PWM1, 160);
analogWrite(PWM2, 160);
digitalWrite(Motor1A, LOW); //
digitalWrite(Motor1B, HIGH); //
digitalWrite(Motor2A, LOW); //
digitalWrite(Motor2B, HIGH); //
readpathsensor();
}
brake();
return;
}
if (S1 == 0 && S2 == 0 && S3 == 0 && S4 == 0 && S5 == 1 && (checkObjectDistance > 20))
{
while( S3 != 1 )
{
analogWrite(PWM1, 160);
analogWrite(PWM2, 160);
digitalWrite(Motor1A, LOW);
digitalWrite(Motor1B, HIGH);
digitalWrite(Motor2A, LOW);
digitalWrite(Motor2B, HIGH);
readpathsensor();
}
brake();
return;
}
if (S1 == 1 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 1&& (checkObjectDistance > 20) )
{
brake();
robotTurnRight();
readpathsensor();
return;
}
if (S1 == 0 && S2 == 1 && S3 == 1 && S4 == 1 && S5 == 0 && (checkObjectDistance > 20) )
{
brake();
readpathsensor();
return;
}
}
while( checkObjectDistance < 19){
lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,2);
lcd.print("-! OBJECT ON PATH !-");
lcd.setCursor(0,3);
lcd.print(" ");
brake();
hoot();
robotTurnLeft();
delay(200);
readpathsensor();
}
}
void objectFound(){
// If the Robot finds and oject on the path, It should stop moving, diplay, and hoot
// Then should Resume path navigation once the path is cleared.
while( checkObjectDistance() < 19 )
{
lcd.setCursor(0,1);
lcd.print(" ");
lcd.setCursor(0,2);
lcd.print("-! OBJECT ON PATH !-");
lcd.setCursor(0,3);
lcd.print(" ");
brake();
hoot();
delay(200);
}
}
<file_sep>/README.md
# nana
The world is my canvas.
|
e391911aae24c5cbb7bd54ee7b8bfb3824515812
|
[
"Markdown",
"C++"
] | 2
|
C++
|
natalie-mbula/nana
|
7a0cc52ca62c6ca386e9dc83ccf48188844fd7b7
|
bf8a96692530bf9347c8f4d19745c11698062a37
|
refs/heads/master
|
<repo_name>SergeySSmirnov/kohana-defender<file_sep>/readme.md
#Kohana defender module
Allows apply authentication and authorization capabilities on your site.
This project based on:
- https://github.com/Wouterrr/A1;
- https://github.com/Wouterrr/ACL;
- https://github.com/Wouterrr/A2.<file_sep>/classes/Defender/Defender_Core.php
<?php
namespace RUSproj\Kohana\Defender\Defender;
use RUSproj\Kohana\Defender\ {
Defender,
Defender_Exception
};
use Arr, Config_Group, Date, Exception, Kohana, Kohana_Exception, ORM, Request, Session, Session_Exception, Text;
/**
* Defender core class for user authentication and authorization.
*
* Use bcrypt.
* Based on Kohana's AUTH, <NAME>'s AUTHLITE и <NAME>'s Bonafide.
*
* @see http://codahale.com/how-to-safely-store-a-password/
* @package Defender
* @copyright (c) 2011 Wouter
* @copyright (c) 2011 <NAME>
* @copyright (c) 2011 <NAME>
* @copyright (c) 2011 Kohana Team
* @copyright (c) 2010-19 RUSproj, <NAME>
* @license MIT
*/
abstract class Defender_Core
{
/**
* Конфигурационные данные модуля.
* @var Config_Group
*/
protected static $config = null;
/**
* Экземпляр класса безопасности.
* @var Defender
*/
protected static $instance = null;
/**
* Сессия, текущего пользователя.
* @var Session
*/
protected static $sess = null;
/**
* Generate bcrypt hash for data.
* @param string $input Data.
* @param string $salt Solt (optional, will be generated if null).
* @param int $cost Hah power (optional, if null will be loaded from config).
* @return string
*/
public static function hash(string $input, string $salt = null, int $cost = null): string {
if (empty($salt)) { // Если не указана соль, то генерируем ее
$salt = Text::random('alnum', 22);
}
if (empty($cost)) { // Если не указана мощность хэша, то генерируем ее
$cost = self::$config['cost'];
}
$cost = sprintf('%02d', min(31, max($cost, 4))); // Применяем нулевой отступ мощности для нормализации диапазона 4-31
$salt = <PASSWORD>$' . $cost . '$' . $salt . '$'; // Создаем соль, подходящую для bcrypt
return crypt($input, $salt); // Формируем хэш и возвращаем его
}
/**
* Создаёт запись пользователя с указанными параметрами. Если пользователь с таким логином существует, то ему будут назначены лишь указанные права.
* @param string $userName Имя пользователя, которого необходимо создать.
* @param string $userPasswd Пароль создаваемого пользователя.
* @param boolean $userActive Признак что пользователь должен иметь статус "Активен".
* @param array $roles Список ролей, назначемых создаваемому пользователю.
* @param string|Config_Group $config Конфигурационные данные модуля или название конфигурации.
* @return Defender Объект безопасности (экземпляр класса Defender).
*/
public static function create(string $userName, string $userPasswd, bool $userActive = FALSE, array $roles = [], $config = 'defender'): Defender {
self::initConfig($config); // Инициализируем конфигурацию
if (!is_object(self::getUserModel($userName))) { // Если пользователя не существует, то создаём его
ORM::factory(ucfirst(self::$config['user_model']))->set(self::$config['uattr']['username'], $userName)->set(self::$config['uattr']['password'], $userPasswd)->set(self::$config['uattr']['active'], $userActive)->create();
}
$_defender = self::instance($userName);
$_defender->addRole($roles); // Назначаем пользователю права
return $_defender; // Возвращаем объект безопасности
}
/**
* Возвращает объект безопасности (экземпляр класса Defender).
* @param string $userName Имя пользователя для которого необходимо получить объект безопасности.
* @param string|Config_Group $config Конфигурационные данные модуля или название конфигурации.
* @return Defender Объект безопасности (экземпляр класса Defender).
* @throws Defender_Exception Генерируется в случае ошибок инициализации объекта безопасности.
* @throws Session_Exception Генерируется в том случае, если время бездействия пользователя истекло.
*/
public static function instance(string $userName = '', $config = 'defender'): Defender {
if (isset(self::$instance) && empty($userName)) { // Пытаемся сразу же вернуть существующий экземпляр безопасности
return self::$instance;
}
if (CRYPT_BLOWFISH !== 1) { // Если сервер не поддерживает bcrypt, то генерируем исключение
throw new Defender_Exception('Данный сервер не поддерживает возможность хэширования bcrypt.');
}
self::initConfig($config); // Инициализируем конфигурацию
self::$sess = Session::instance(self::$config['session']['type']); // Получаем сессию текущего пользователя
$_lastTime = self::$sess->get(self::$config['session']['key'] . '_TIME', null); // Дата и время последнего обращения пользователя к системе
$_defender = new Defender(self::getUserModel(empty($userName) ? self::$sess->get(self::$config['session']['key'], null) : $userName)); // Формируем объект безопасности
if (($_lastTime > 0) && ($_lastTime <= time())) { // Если время бездействия истекло, то закрываем сеанс и генерируем исключение
self::logout();
throw new Session_Exception('Сессия завершена в связи с бездействием более ' . self::$config['session']['expiration'] . ' секунд.');
}
if (empty($userName)) { // Если запрашиваем информацию о текущем пользователе, то запоминаем его
self::$instance = $_defender;
}
self::$sess->set(self::$config['session']['key'] . '_TIME', time() + self::$config['session']['expiration']); // Запоминаем время завершения сеанса пользователя по бездействию
return $_defender;
}
/**
* Осуществляет попытку входа пользователя и возвращает объект безопасности (экземпляр класса Defender).
* @param string $userName Имя пользователя.
* @param string $password <PASSWORD>.
* @param string|Config_Group $config Конфигурационные данные модуля или название конфигурации.
* @return Defender Объект безопасности (экземпляр класса Defender).
* @throws Defender_Exception Генерируется в случае ошибок инициализации объекта безопасности.
* @throws Kohana_Exception Генерируется в том случае, если сервер не поддерживает Bcrypt.
* @throws Session_Exception Генерируется в том случае, если время бездействия пользователя истекло.
*/
public static function login(string $userName, string $password, $config = 'defender'): Defender {
try {
if (empty($password)) { // Учетные записи с пустыми паролями запрещены
throw new Defender_Exception('Пароль не может быть пустым.');
}
if (CRYPT_BLOWFISH !== 1) { // Если сервер не поддерживает bcrypt, то генерируем исключение
throw new Defender_Exception('Данный сервер не поддерживает возможность хэширования bcrypt.');
}
self::initConfig($config); // Инициализируем конфигурацию
$_user = self::getUserModel($userName); // Получаем модель пользователя
if (!is_object($_user)) { // Если информацию о пользователе не удалось загрузить, генерируем исключение
self::logEvent('auth', 'failed', 'Невозможно загрузить информацию о пользователе :user.', [':user' => $userName]);
throw new Defender_Exception('Вы исчерпали лимит попыток доступа.');
}
if (!$_user->get(self::$config['uattr']['active'])) { // Если учётная запись деактивирована, то генерируем исключение
self::logEvent('auth', 'failed', 'Попытка входа в систему пользователя :user, учетная запись которого была деактивирована ранее системным администратором.', [':user' => $userName]);
throw new Defender_Exception('Вы не можете войти в систему, так как ваша учетная запись деактивирована системным администратором.');
}
if (isset(self::$config['uattr']['failed_attempts']) && // Если в конфигурации определен параметр число безуспешных попыток входа
isset(self::$config['uattr']['last_attempt']) && // и в конфигурации определен параметр дата и время последней попытки входа
(count(Arr::get(self::$config, 'rate_limits', [])) > 0)) // и в конфигурации определен массив соответствия числа попыток входа и времени блокировки (для защиты от подбора паролей)
{
$_attempt = 1 + (int)$_user->get(self::$config['uattr']['failed_attempts']); // Увеличиваем число безуспешных попыток входа
if (($_attempt > 1) && !empty($_user->get(self::$config['uattr']['last_attempt']))) { // Если уже была попытка входа
ksort(self::$config['rate_limits']); // Сортируем массив соответствия
foreach (array_reverse(self::$config['rate_limits'], true) as $attempts => $time) { // Пробегаемся по массиву
if ($_attempt > $attempts) { // Если номер попытки входа больше чем разрешенное число попыток
if ((strtotime($_user->get(self::$config['uattr']['last_attempt'])) + $time) > time()) { // Если время блокировки очередно попытки входа не закончилось, то генерируем исключение
self::logEvent('auth', 'failed', 'Пользователь :user исчерпал лимит попыток входа в систему. Попытка: :attempt, Время блокировки: :time.', [':user' => $userName, ':attempt' => $_attempt, ':time' => $time]);
throw new Defender_Exception('Вы исчерпали лимит попыток доступа. Попытайтесь позже через ' . $time . ' секунд.');
} else { // Иначе переходим к следующей записи соответствия
break;
}
}
}
}
}
if (self::check($password, $_user->get(self::$config['uattr']['password']))) { // Если пароль успешно проверен, то завершаем аутентификацию
if (isset(self::$config['uattr']['failed_attempts']) && isset(self::$config['uattr']['last_attempt'])) { // Если в конфигурации определен параметр число попыток входа, то сбрасываем число безуспешных попыток входа и время входа
$_user->set(self::$config['uattr']['failed_attempts'], 0)->set(self::$config['uattr']['last_attempt'], null);
}
if (isset(self::$config['uattr']['last_login'])) { // Если в конфигурации определен параметр время последнего входа, то устанавливаем время последнего входа
$_user->set(self::$config['uattr']['last_login'], Date::formatted_time('now', 'Y-m-d H:i:s'));
}
if (isset(self::$config['uattr']['logins'])) { // Если в конфигурации определен параметр число входов пользователя, то увеличиваем число попыток входа пользователя
$_user->set(self::$config['uattr']['logins'], $_user->get(self::$config['uattr']['logins']) + 1);
}
$_user->save(); // Сохраняем настройки
self::$instance = new Defender($_user); // Формируем объект безопасности
if (!isset(self::$sess)) {
self::$sess = Session::instance(self::$config['session']['type']); // Генерируем новую сессию
}
self::$sess->regenerate(); // Генерируем новую сессию
self::$sess->set(self::$config['session']['key'], $userName); // Запоминаем в сессии имя пользователя
self::$sess->set(self::$config['session']['key'] . '_TIME', time() + self::$config['session']['expiration']); // Запоминаем в сессии время завершения сеанса пользователя по бездействию
self::logEvent('auth', 'success', 'Пользователь :user успешно прошел аутентификацию в системе.', [':user' => $userName]);
return self::$instance;
} else { // Если пароль неверный, то запоминаем число попыток входа и время последней попытки
if (isset(self::$config['uattr']['failed_attempts'])) {
$_user->set(self::$config['uattr']['failed_attempts'], $_user->get(self::$config['uattr']['failed_attempts']) + 1);
}
if (isset(self::$config['uattr']['last_attempt'])) {
$_user->set(self::$config['uattr']['last_attempt'], Date::formatted_time('now', 'Y-m-d H:i:s'));
}
$_user->save(); // Сохраняем новые данные
self::logEvent('auth', 'failed', 'Пользователь :user провалил аутентификацию.', [':user' => $userName]);
throw new Defender_Exception('Неверно введено имя пользователя или пароль. Повторите попытку ввода.');
}
} catch (Exception $e) { // При ошибке обнуляем права доступа пользователя
self::$instance = new Defender(); // Загружаем информацию о правах доступа для гостя
throw $e; // Генерируем то же самое исключение
}
}
/**
* Осуществляет завершение сеанса пользователя и удаление данных сессии и cookie.
*/
public static function logout() {
self::$sess->destroy();
self::$sess->regenerate();
self::logEvent('auth', 'success', 'Пользователь :user вышел из системы.', [':user' => self::getUserName()]);
self::$instance = new Defender(); // Загружаем объект безопасности для гостя
}
/**
* Возвращает сессию текущего пользователя. В случае необходимости инициализирует новую сессию.
* @return Session
*/
public static function getSession(): Session {
if (!isset(self::$sess)) {
self::$sess = Session::instance(self::$config['session']['type']);
}
return self::$sess;
}
/**
* Возвращает имя учётной записи текущего пользователя.
* @return string Имя учётной записи текущего пользователя.
*/
public static function getUserName(): string {
if (!isset(self::$instance)) {
self::instance();
}
$_user = isset(self::$instance) ? self::$instance->getUser() : null;
return (is_object($_user) ? $_user->{self::$config['uattr']['username']} : 'Гость');
}
/**
* Возвращает true, если пользователь вошел в систему, в противном случае false.
* @return boolean
*/
public static function isUser(): bool {
if (!isset(self::$instance)) {
self::instance();
}
return isset(self::$instance) && is_object(self::$instance->getUser());
}
/**
* При необходимости осуществляет инициализацию конфигурации.
* @param string|Config_Group $config Конфигурационные данные модуля или название конфигурации.
*/
protected static function initConfig($config = 'defender') {
if (!isset(self::$config)) { // При необходимости загружаем файл с конфигурацией модуля
self::$config = is_string($config) ? Kohana::$config->load($config) : $config;
}
}
/**
* Возвращает модель данных указанного пользователя.
* @param int|string|ORM $user Идентификатор, имя или модель пользователя.
* @return null|ORM Модель данных указанного пользователя. Если пользователь не существует, то вернёт null.
*/
protected static function getUserModel($user) {
$_model = null;
if ($user instanceof ORM) {
return $user;
} else {
$_model = ORM::factory(self::$config['user_model'], (is_string($user) ? [self::$config['uattr']['username'] => $user] : $user)); // В зависимости от типа данных, представленных в $user ищем по имени или ID пользователя
if (!$_model->loaded()) {
$_model = null;
}
}
return $_model;
}
/**
* Возвращает модель данных указанной роли.
* @param int|string|ORM $role Идентификатор или код роли.
* @throws Defender_Exception Генерируется в том случае, если не определён драйвер для доступа к БД или указанная запись не найдена.
* @return ORM Модель данных указанной роли. Если роль не существует, то вернёт null.
*/
protected static function getRoleModel($role): ORM {
$_model = null;
if ($role instanceof ORM) {
return $role;
} else {
$_model = ORM::factory(self::$config['role_model'], (is_string($role) ? [self::$config['rattr']['rolecode'] => $role] : $role)); // В зависимости от типа данных, представленных в $role ищем по имени или ID роли
if (!$_model->loaded()) {
throw new Defender_Exception('Указанная запись роли не найдена.');
}
}
return $_model;
}
/**
* Осуществляет запись сообщения о произошедшем событии в системный журнал событий.
* @param string $type Тип произошедшего события (параметры: auth или access как описано в конфигурационном файле).
* @param string $event Результат операции (success или failed).
* @param string $message Описание произошедшего события.
* @param array $values Массив значений, которые будут заменены в тексте сообщения.
*/
protected static function logEvent(string $type, string $event, string $message, array $values = null) {
if (!isset($values[':user'])) {
$values[':user'] .= self::getUserName();
}
$values[':user'] .= ' (IP: ' . Request::$client_ip . ')';
if (isset(self::$config['logging'][$type][$event]) && (self::$config['logging'][$type][$event] !== false)) {
Kohana::$log->add(self::$config['logging'][$type][$event], mb_strtoupper($type . '_' . $event) . ' = ' . $message, $values, ['no_back_trace' => true]);
}
}
/**
* Осуществляет проверку соответствия хэша пароля и хранимого ключа сессии.
* @param string $password <PASSWORD>, который необходимо проверить.
* @param string $hash Хэш пароля.
* @return boolean Возвращает true, если пароль и хэш совпадают.
*/
protected static function check(string $password, string $hash): bool {
$matches = [];
// $2a$ (4) 00 (2) $ (1) <salt> (22)
preg_match('/^\$2a\$(\d{2})\$(.{22})/D', $hash, $matches);
// Extract the iterations and salt from the hash
$_cost = Arr::get($matches, 1);
$_salt = Arr::get($matches, 2);
// return result
return self::hash($password, $_salt, $_cost) === $hash;
}
/**
* Данные о текущем пользователе. Если текущй пользователь - Гость, то значение равно null.
* @var object
*/
protected $user = null;
/**
* Массив названий ролей текущего пользователя.
* @var array
*/
protected $roles = [];
/**
* Массив правил, определяющих разрешения для текущего пользователя.
* @var array
*/
protected $rules = [];
/**
* Инициализирует экземпляр класса Defender.
* @param ORM $user Модель пользователя для которого необходимо получить объект безопасности.
*/
protected function __construct($user = null) {
$this->user = is_object($user) ? $user : null; // Запоминаем объект информации о пользователе
$_rolesModel = null;
if (is_object($user)) {
$_rolesModel = $user->get(self::$config['uattr']['roles'])->find_all(); // Загружаем все записи в соответствии со связью, описанной в модели пользователя
} else {
$_rolesModel = [ORM::factory(self::$config['role_model'], [self::$config['rattr']['rolecode'] => 'guest'])];
}
foreach ($_rolesModel as $_rule) { // Запоминаем роли и допустимые действия пользователя в отдельном массиве
$this->roles[] = $_rule->get(self::$config['rattr']['id']);
$this->roles[] = $_rule->get(self::$config['rattr']['rolename']);
$this->roles[] = $_rule->get(self::$config['rattr']['rolecode']);
if (!empty($this->rules)) {
$this->rules = array_merge_recursive($this->rules, unserialize($_rule->get(self::$config['rattr']['roleact'])));
} else {
$this->rules = unserialize($_rule->get(self::$config['rattr']['roleact']));
}
}
}
/**
* Return model of the current user. Return null if user was not found.
* @return ORM
*/
public function getUser() {
return $this->user; // Возвращаем объект текущего пользователя
}
/**
* Осуществляет проверку наличия у пользователя указанному названию, коду или идентификатору роли. Вернет true - если у пользователя присутствует указанная роль, false - в противном случае.
* @param string $role Название, код или идентификатор роли, которое необходимо проверить.
* @return boolean Вернет true - если у пользователя присутствует указанное название, код или идентификатор роли, false - в противном случае.
*/
public function hasRole(string $role): bool {
return array_search($role, $this->roles) !== false ? true : false;
}
/**
* Осуществляет проверку наличия у пользователя указанных ролей или кодов роли. Вернет true - если у пользователя присутствуют указанные роли или её коды, false - в противном случае.
* @param array $roles Массив названий и/или кодов ролей, которые необходимо проверить. Если будет задан не массив, то метод вернёт false.
* @param boolean $oneOf Признак необходимости проверить присутствие у пользователя любой одной роли из списка.
* @return boolean Вернет true - если у пользователя присутствует указанные роли или её коды, false - в противном случае.
*/
public function hasRoles(array $roles, bool $oneOf): bool {
if (!is_array($roles)) {
return false;
}
$_result = array_intersect($roles, $this->roles);
if ($oneOf) {
return count($_result) > 0;
} else {
return count($_result) == count($roles);
}
}
/**
* Осуществляет проверку возможности доступа текущего пользователя к указанному ресурсу.
* @param string $control Контрол, к которому необходимо проверить возможность доступа.
* @param string $action Действие внутри контрола, к которому необходимо проверить возможность доступа.
* @return boolean
*/
public function isAllowed(string $control = '', string $action = ''): bool {
$control = strtolower($control);
$action = strtolower($action);
if (empty($this->rules)) {
return false;
}
if (array_key_exists('*', $this->rules)) { // Если указан подстановочный символ, значит у пользователя неограниченный доступ ко всем контролам и действиям
return true;
} elseif (array_key_exists($control, $this->rules)) {
if (in_array('*', $this->rules[$control], true)) { // Если указан полный доступам ко всем действияем внутри контрола
return true;
} elseif (in_array($action, $this->rules[$control], true)) { // Если разрешен доступ к контролу и действию данного контрола
return true;
}
}
return false; // Если доступ не разрешен, значит он запрещён
}
/**
* Return is SA user or not.
* @return boolean
*/
public function isSA(): bool {
return $this->hasRole('sa');
}
/**
* Производит повторную проверку пароля текущего пользователя.
* Может использоваться для подтверждения прав пользователя при попытке выполнить действия, для которых требуется повышенная безопасность. Применяется даже в том случаае, когда пользователь прошел аутентификацию.
* @example
* if ( $authext->check_password($user, $this->request->post('password'))) {
* // delete account or some other special action
* }
* @param object $user Объект БД с данными, соответствующими пользователю.
* @param string $password <PASSWORD>, который необходимо проверить.
* @return boolean Результат выполнения проверки пароля.
*/
public function checkPassword($password): bool {
if (!is_object($this->user)) {
return false;
}
$_passwHash = $this->user->get(self::$config['uattr']['password']);
return self::check($password, $_passwHash);
}
/**
* Remove user record from DB.
*/
public function delete() {
if (is_object($this->user)) { // Если пользователь существует, то пытаемся удалить его
$this->user->delete();
}
}
/**
* Add role or roles to the user.
* @param int|string|array|ORM $role Role ID or name.
* @throws Defender_Exception Thrown if specified record not found or error occurred.
*/
public function addRole($role) {
if (is_object($this->user)) { // Если пользователь существует, то пытаемся удалить его
$_userRoles = $this->user->get(self::$config['uattr']['roles'])->find_all()->as_array(self::$config['rattr']['id']);
foreach ((array)$role as $_r) {
$_roleModelID = self::getRoleModel($_r)->get(self::$config['rattr']['id']);
if (!array_key_exists($_roleModelID, $_userRoles)) {
$this->user->add(self::$config['uattr']['roles'], [$_roleModelID], true);
}
}
}
}
/**
* Remove user role or roles.
* @param int|string|array|ORM $role Role ID or name.
*/
public function removeRole($role) {
if (is_object($this->user)) { // Если пользователь существует, то пытаемся удалить его
$_userRoles = $this->user->get(self::$config['uattr']['roles'])->find_all()->as_array(self::$config['rattr']['id']);
foreach ((array)$role as $_r) {
$_roleModelID = self::getRoleModel($_r)->get(self::$config['rattr']['id']);
if (array_key_exists($_roleModelID, $_userRoles)) {
$this->user->remove(self::$config['uattr']['roles'], [$_roleModelID]);
}
}
}
}
}
<file_sep>/config/defender.php
<?php return [
/**
* Power of the Bcrypt - any number between 4 and 31 -> hash is better if number is hihter
*/
'cost' => 12,
/**
* Session preferences.
*/
'session' => [
'type' => 'native', // Session type: native, database, ...
'expiration' => 3600, // Time of user inactivity before the session is finished
'key' => 'DEFENDER' // Key stored in session with user data
],
/**
* Login block on failed attempt.
* Name of the key - number of failed attempts.
* Value of the key - block time.
* IMPORTANT!!! In DB must exist fields last_attempt and failed_attempt + uncomment lines below.
*/
'rate_limits' => [
3 => 30, // after 3 failed attempts, wait 30 seconds between each next attempt
5 => 60, // after 5 failed attempts, wait 1 minute between each next attempt
10 => 300 // after 5 failed attempts, wait 10 minutes between each next attempt
],
/**
* Logging settings.
*/
'logging' => [
'auth' => [ // Authentication
'success' => LOG::INFO,
'failed' => LOG::WARNING,
],
'access' => [ // User access
'success' => LOG::INFO,
'failed' => LOG::WARNING,
]
],
/**
* ORM model names which used to get user info.
* @tutorial Models must contains relation fields user и role.
*/
'user_model' => 'User', // Users
'role_model' => 'Role', // Roles
/**
* Map between fields from code and fields from DB.
*/
'uattr' => [ // User model
'id' => 'id', // User ID
'username' => 'username', // User name
'password' => '<PASSWORD>', // <PASSWORD>
'active' => 'active', // User is active
//'last_login' => 'last_login', // (optional) Date and time of the last user logon
//'logins' => 'logins', // (optional) User logon number
//'last_attempt' => 'last_attempt', // (optional) Date and time of the last success logon attempt
//'failed_attempts' => 'failed_attempts', // (optional) Date and time of the last failed logon attempt
'roles' => 'roles' // Link to the Role model of the user
],
'rattr' => [ // Role model
'id' => 'id', // Role ID
'rolename' => 'rolename', // Role name
'rolecode' => 'rolecode', // Role code
'roleact' => 'roleact', // Actions allowed to the role
'users' => 'users' // Link to the User model
],
];
/*
* DB scripts
*
*
'scripts' => [
'users' => "
CREATE TABLE users (
uid int(10) UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Идентификатор записи пользователя.',
username varchar(32) NOT NULL COMMENT 'Уникальный логин пользователя.',
password varchar(255) NOT NULL COMMENT '<PASSWORD>.',
active tinyint(1) NOT NULL DEFAULT 0 COMMENT 'Признак того, что учетная запись пользователя активна в данный момент.',
last_login datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Дата и время последнего входа пользователя в систему.',
logins int(10) UNSIGNED NOT NULL COMMENT 'Число входов пользователя.',
last_attempt datetime NOT NULL DEFAULT '0000-00-00 00:00:00' COMMENT 'Дата и время последней попытки входа пользователя в систему.',
failed_attempts smallint(5) UNSIGNED NOT NULL COMMENT 'Число безуспешных попыток входа.',
PRIMARY KEY (uid),
UNIQUE INDEX USER_LOGIN (username),
)
ALTER TABLE ROLES COMMENT 'Данные о пользователях системы.';
INSERT INTO users(uid, username, password, active) VALUES (1, 'admin', <PASSWORD>', 1); // admin 123456; ",
'roles' => "
CREATE TABLE roles (
rid int UNSIGNED NOT NULL AUTO_INCREMENT COMMENT 'Идентификатор записи роли.',
name varchar(255) NOT NULL COMMENT 'Название роли.',
code varchar(45) NOT NULL COMMENT 'Код роли',
role longtext NOT NULL COMMENT 'Действия, допустимые для роли.',
PRIMARY KEY (rid),
KEY ROLE_NAME (name)
);
ALTER TABLE roles COMMENT 'Справочник. Содержит список ролей, которые возможны в системе.';
INSERT INTO roles(rid, rolNazv, rolDeistviya) VALUES (1, 'Guest', 'restrict all');
INSERT INTO roles(rid, rolNazv, rolDeistviya) VALUES (2, 'SuperAdmin', 'allow all'); ",
'user_roles' => "
CREATE TABLE user_roles (
uid int(10) UNSIGNED NOT NULL COMMENT 'Идентификатор записи пользователя.',
rid int(10) UNSIGNED NOT NULL COMMENT 'Идентификатор записи роли.',
PRIMARY KEY (uid, rid),
)
ALTER TABLE user_roles COMMENT = 'Данные о ролях пользователей.';
INSERT INTO user_roles(uid, rid) VALUES (1, 2); ",
],
*/
<file_sep>/classes/Defender.php
<?php
namespace RUSproj\Kohana\Defender;
use RUSproj\Kohana\Defender\Defender\Defender_Core;
/**
* User authentication and authorization cabilities.
*
* @package Defender
* @author <NAME>
* @copyright (c) 2010-19 RUSproj, <NAME>
* @license MIT
*/
class Defender extends Defender_Core
{
}
<file_sep>/classes/Defender_Exception.php
<?php
namespace RUSproj\Kohana\Defender;
use Kohana_Exception;
/**
* Exception which thrown by Defender module.
*
* @package Defender
* @author <NAME>
* @copyright (c) 2010-19 RUSproj, <NAME>
* @license MIT
*/
class Defender_Exception extends Kohana_Exception
{
}
|
172a5cc976d43418e01299ad26636cf965d7f5f2
|
[
"Markdown",
"PHP"
] | 5
|
Markdown
|
SergeySSmirnov/kohana-defender
|
4c5899bb5d0ed0c86fc28f8a40c1ca2e6b6e2bc0
|
3bba2bd28441f3b60451ff41652a36d0eb4bc1e2
|
refs/heads/master
|
<repo_name>herbertg14/user-activity-code-challenge<file_sep>/attainia_ws/Attainia_Api/views.py
from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response
from .models import User
from .serializers import UserSerializer
@api_view(['GET', 'POST'])
def all_users(request):
if request.method == 'GET':
users = User.objects.all()
serializer = UserSerializer(users, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = UserSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
@api_view(['GET'])
def inactive_users(request):
if request.method == 'GET':
users = User.objects.all()
serializer = UserSerializer(users, many=True)
data = serializer.data
responseData = []
for user in data:
if (user['login_count'] == 0):
responseData.append(user)
return Response(responseData)
@api_view(['GET'])
def active_users(request):
if request.method == 'GET':
users = User.objects.all()
serializer = UserSerializer(users, many=True)
data = serializer.data
responseData = []
for user in data:
if (user['login_count'] > 0):
responseData.append(user)
return Response(responseData)
<file_sep>/attainia_ws/Attainia_Api/urls.py
from django.urls import path
from .views import all_users, inactive_users, active_users
urlpatterns = [
path('users/', all_users),
path('inactiveUsers/', inactive_users),
path('activeUsers/', active_users)
]<file_sep>/README.md
# Attainia App
### How to run Django API
1. python -m venv env
2. source env/bin/activate (env\Scripts\activate)
3. pip install -r requirements.txt
4. cd attainia_ws/
5. python manage.py makemigrations
6. python manage.py migrate
7. python manage.py runserver
##### Admin information
* email: <EMAIL>
* username: admin
* password: <PASSWORD>
### How to run Vue App
1. cd attainia_ui
2. npm install
3. npm run serve
4. Go to http://localhost:8080/<file_sep>/attainia_ws/Attainia_Api/apps.py
from django.apps import AppConfig
class AttainiaApiConfig(AppConfig):
name = 'Attainia_Api'
|
450a5c7fa4810cf0f4c7a01bc2ab42290f377219
|
[
"Markdown",
"Python"
] | 4
|
Python
|
herbertg14/user-activity-code-challenge
|
01a242e3ba01078b505cfff7901821dbe94bf6c0
|
3a67e663d7e92d9ee3015482fd935e7ab6b90e62
|
refs/heads/master
|
<repo_name>aprusik/EXERCISE-grid-based-motion-planner<file_sep>/README.md
# Grid-Based Motion Planner Exercise
Plans a route through an arbitrary grid with blocked, empty, start and goal cells so that each goal is visited.
## Input Syntax
1. Line with number of collumns in grid (`col`)
2. Line with number of rows in grid (`row`)
3. `row` rows, each `col` characters long consisting of the following characters:
* `_` for empty cells
* `#` for blocked cells
* `*` for goal cells
* `@` for the start cell (only one cell can be a start position)
### Example Input
```
4
4
___*
_#_*
__##
_@_*
```
## Output
A series of cardinal direction instructions (`N`, `S`, `E`, `W`) planning a path through the grid so that each goal cell is visited, starting at the starte cell. When a goal cell is visited, `V` is displayed instead of a directional instruction to indicate the goal has been reached.
Each instruction is presented on its own line in order from top to bottom.
The instructions are followed by the number of search nodes generated and expanded in the process of the calculation.
### Example Output
```
E
E
V
W
W
W
N
N
N
E
E
E
V
S
V
114 nodes generated
57 nodes expanded
```
## Build/Run Instructions
### Requirements
* Scala
### Usage
The program accepts 1-2 command line arguments:
1. algorithm: can be `depth-first`, `depth-first-id`, `uniform-cost`, or `a-star`
2. heuristic: if algorithm is `a-star`, which heuristic to use; can be `h0`, `h1`, or `h2`
The Grid is then accepted from standard input.
### Windows (PowerShell)
* Build with: `scalac stateSearch/*.scala`, and `scalac *.scala`
* Run with: `scala GridPathApp <algorithm> <heuristic>`
* Recommended: pipe in the contents of a plaintext file with the grid like so: `Get-Content <grid-file> | scala GridPathApp <algorithm> <heuristic>`
### MacOS / Linux Shell
Use included build and run scripts.
You can pipe the contents of a plaintext file into the run script and it should send it to the program's standard input to run.
Let me know if you have any problems building or running the program.
## Algorithms and Discussion
### Implementation & Class Descriptions
* **GridPathApp**: main execution class which parses the inputs and creates the initial GridWorld
* **GridWorld**: parses input to create world, holds static information associated with the world (i.e. obsticals, empty spaces, goals, start locations, etc.); also creates the "robot", which is the traversal entity.
* **Robot**: Holds dynamic information about the "robot"’s location, it’s movement history (Scala List for easy popping), the goals remaining (a mutable set of INTs which represent the index of the goal in the array because a goal cannot be in the same place twice). There is also an ID which serves for easy node identification and a count of the nodes generated.
* **Vacuum hash function**: there is a hash function on the vacuum that simply strings the goal set hash and location together to guarantee uniqueness, then hashes that.
### Algorithms
GridPathApp parses the given argument to either “depth-first” or “uniform-cost”, then creates and runs the associated algorithm class. Both algorithms are implemented using a tail-recursive structure as Scala is a recursion-optimized language. Nodes for the algorithms are implemented via the use of a case class which packages the node information for easy access and usage. There is a lot of duplicated code between the two of these classes which should probably be consolidated into a generic State Search class which they both inherit.
#### Depth First Search Algorithm (DFSStateSearch.scala)
https://en.wikipedia.org/wiki/Depth-first_search
There is a depth limit set to 1,000,000 as to not allow the algorithm to run infinitely but allow for very large worlds. This can be modified by changing the value of the DEPTH_LIMIT constant. A weak duplicate checking method is also implemented for cycle checking which recursively traverses the parent nodes.
This algorithm is **NOT** optimal, it only returns the first solution found. It uses very little space, but is slow. If the correct path requires more than the depth bound of steps, it will not be found.
#### Depth First Search-Iterative Deepening Algorithm (DepthFirstID.scala)
https://en.wikipedia.org/wiki/Iterative_deepening_depth-first_search
This algorithm is implemented by utilizing the standard Depth-First Search algorithm implemented above, with a new optional parameter of maxDepth. If no solution is found at a depth of 0 (the root), the maxDepth is increased and the search is run again until one is found.
This algorithm is slow, but uses little space and unlike normal Depth First Search, it finds an optimal solution.
#### Uniform Cost Algorithm (UCStateSearch.scala)
A precursor to [Dijkstra's Algorithm](https://en.wikipedia.org/wiki/Dijkstra%27s_algorithm).
There is a cycle checking method that tests a HashSet of generated nodes to ensure no duplicates are expanded. A HashSet was used because each node state only needs to exist once within it; it uses the hashing algorithm implemented in the Robot class.
This algorithm is slow, and uses a lot of space, but is guarenteed to find and optimal solution (least number of steps).
#### A* (AStar.scala)
https://en.wikipedia.org/wiki/A*_search_algorithm
The most sophisticated of the search algorithms here; this algorithm is implemented by building upon a modified version of the UniformCost.scala class. The modification adds a newNode function which is used in the search function to determine the node weight. newNode is overridden in AStar.scala to include a heuristic value which is calculated via a method passed in during construction.
Its time and space complexity vary with the particular heuristic used, but will generally be at least as good as Uniform Cost. If the heuristic is admissable (the three included are), it is guarenteed to find an optimal solution.
##### Heuristic 0 (h0)
This heuristic simply returns 0, resulting in an algorithm that runs identically to Uniform-Cost.
##### Heuristic 1 (h1)
This heuristic returns the average of all distances to the goals from the robot. This heuristic is admissible because the maximum average distance would occur when one node is left, leaving the Euclidian distance as a lower bound to the remaining movement over walls and the grid.
##### Heuristic 2 (h2)
This heuristic plots the optimal Euclidian distance between all nodes assuming there are no walls, and the robot can travel straight from one node to another. This is accomplished by finding the distance from the robot to the nearest node, then the distance from that node to the next, and so on, returning the total distance. This is admissible because the robot must travel through each node, and the optimal Euclidian path through each node can be calculated in the above way because if a node other than the nearest is chosen in the chain, the total distance will be greater. The robot cannot travel on Euclidian paths; it must make its way on a grid, which uses more or the same movement when rounded as the Euclidian path, and it also may have to find its way around walls, ensuring that h2 is a lower bound to the remaining distance.
<file_sep>/run.sh
#!/bin/sh
scala GridPathApp $@
|
b8da6ffc20618488494a56086920346bb51672f8
|
[
"Markdown",
"Shell"
] | 2
|
Markdown
|
aprusik/EXERCISE-grid-based-motion-planner
|
82383968392039dc01fe01db99bb7a4c7aba363c
|
669e0a165ef3a7fa9f8ce6e8beb52d575d87ca3f
|
refs/heads/master
|
<file_sep>## Week 1 Project - <NAME>
# Impots data into R
data <- read.table("./household_power_consumption.txt", sep = ";", stringsAsFactors = F, header = T, nrows = 70000)
# Converts class of Date and Time variables
dates <- as.Date(data[,1], "%d/%m/%Y")
data[1] <- dates
# Selects only the required dates
data <- subset(data, Date == "2007-02-01" | Date == "2007-02-02")
#### PLOT 4 ####
png(filename = "plot4.png")
par(mfrow = c(2, 2))
plot(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , as.double(data$Global_active_power), type = "l", ylab = "Global Active Power", xlab = "")
plot(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Voltage, type = "l", ylab = "Voltage", xlab = "datetime")
plot(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Sub_metering_1, type = "l", ylab = "Energy sub metering", xlab = "")
lines(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Sub_metering_2, col = "red")
lines(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Sub_metering_3, col = "blue")
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black", "red", "blue"), lty = c(1, 1, 1))
plot(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , as.double(data$Global_reactive_power), type = "l", ylab = "Global_reactive_power", xlab = "datetime")
dev.off()
<file_sep>## Week 1 Project - <NAME>
# Impots data into R
data <- read.table("./household_power_consumption.txt", sep = ";", stringsAsFactors = F, header = T, nrows = 70000)
# Converts class of Date and Time variables
dates <- as.Date(data[,1], "%d/%m/%Y")
data[1] <- dates
# Selects only the required dates
data <- subset(data, Date == "2007-02-01" | Date == "2007-02-02")
#### PLOT 3 ####
png(filename = "plot3.png")
plot(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Sub_metering_1, type = "l", ylab = "Energy sub metering", xlab = "")
lines(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Sub_metering_2, col = "red")
lines(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , data$Sub_metering_3, col = "blue")
legend("topright", legend = c("Sub_metering_1", "Sub_metering_2", "Sub_metering_3"), col = c("black", "red", "blue"), lty = c(1, 1, 1))
dev.off()
<file_sep>## Week 1 Project - <NAME>
# Impots data into R
data <- read.table("./household_power_consumption.txt", sep = ";", stringsAsFactors = F, header = T, nrows = 70000)
# Converts class of Date and Time variables
dates <- as.Date(data[,1], "%d/%m/%Y")
data[1] <- dates
# Selects only the required dates
data <- subset(data, Date == "2007-02-01" | Date == "2007-02-02")
#### PLOT 2 ####
png(filename = "plot2.png")
plot(strptime(paste(data$Date, data$Time, sep = " "), format = "%Y-%m-%d %H:%M:%S") , as.double(data$Global_active_power), type = "l", ylab = "Global Active Power (kilowatts)", xlab = "")
dev.off()
|
8d59843cfcbcb7a87e59c0ee493333c4f6607a4f
|
[
"R"
] | 3
|
R
|
brianbohorquez/ExData_Plotting1
|
3fdb0697f02b10dabc957ec96780cb051fb0304f
|
98c62655517a5cee9f3698a1a68289ae28117c63
|
refs/heads/master
|
<repo_name>15jennlee15/TPOT_scripts<file_sep>/fMRI/rx/models/affect/Onesample/group_sbatch_con0013.txt
#!/bin/bash
#SBATCH --time=0-00:01:00
#SBATCH --partition=short
# Set your study
STUDY=/projects/adapt_lab/shared/TPOT
# SPM Path
SPM_PATH=/projects/adapt_lab/jlewis5/ERdissertation/spm12
# Set MATLAB script path
SCRIPT=${STUDY}/TPOT_Scripts/fMRI/rx/models/affect/Onesample/LabelAngry_LabelSad.m
# PROP the results files
RESULTS_INFIX=rx_con13
# Set output dir and make it if it doesn't exist
OUTPUTDIR=${STUDY}/out/rx
if [ ! -d ${OUTPUTDIR} ]; then
mkdir -p ${OUTPUTDIR}
fi
# run script
module load matlab
srun --job-name="${RESULTS_INFIX}" -o "${OUTPUTDIR}"/"${RESULTS_INFIX}".log \
matlab -nosplash -nodisplay -nodesktop -r "clear; addpath('$SPM_PATH'); spm_jobman('initcfg'); spm_jobman('run','$SCRIPT'); exit"
|
dae2b690e58bc5254a3cf9e4738ff16ed2c6abb5
|
[
"Shell"
] | 1
|
Shell
|
15jennlee15/TPOT_scripts
|
7deded80b58fcf8bc0e0cf046c411cb7b1ef9d15
|
456b7c92de56754eddef1f01147ee760a5c1f3fa
|
refs/heads/develop
|
<file_sep>install: git-hooks grunt-tape
bower install; \
npm install; \
npm run-script update-webdriver;
clean:
rm -rf node_modules vendor build bin tmp;
reset: clean install
grunt-tape:
rm -rf ./node_modules/grunt-tape; \
git clone <EMAIL>:cosmopolithome/grunt-tape.git ./node_modules/grunt-tape; \
cd ./node_modules/grunt-tape; \
npm install; \
cd ../..;
git-hooks:
cp ./project_hooks/pre-push ./.git/hooks/pre-push; \
chmod +x ./.git/hooks/pre-push;<file_sep>my_ansible_playbooks
====================
Mes playbooks modifiés pour Ansible
<file_sep>#!/usr/bin/bash
echo 1
return 0
<file_sep>#!/usr/bin/env bash
do_exit(){
echo $policy
exit 1
}
protected_branches="develop master"
for protected_branch in $protected_branches; do
policy='[Policy] Never push, force push or delete the '$protected_branch' branch! (Prevented with pre-push hook.)'
current_branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')
push_command=$(ps -ocommand= -p $PPID)
is_destructive='force|delete|\-f'
will_remove_protected_branch=':'$protected_branch
if [[ $push_command =~ $is_destructive ]] && [[ $push_command == $protected_branch ]]; then
do_exit
fi
if [[ $push_command =~ $will_remove_protected_branch ]]; then
do_exit
fi
if [[ $push_command =~ $is_destructive ]] && [[ $protected_branch == $current_branch ]]; then
do_exit
fi
done
exit 0
<file_sep># test_repo
Mon repo test
|
f354f32dfa18b6ef9bc6dc75c287848adcc8ad34
|
[
"Markdown",
"Makefile",
"Shell"
] | 5
|
Makefile
|
cchaudier/test_repo
|
71b4b84be71431c40b262f8959838f145b672aa5
|
e2dcd74b2962185ca68877fa8bfc70fd6e962f09
|
refs/heads/master
|
<repo_name>prashant169/FlipCoinHeadOrTell<file_sep>/FlipCoinCombination.sh
#! /bin/bash
echo -e "enter the times to toss coin \c"
read num
Head=0
Tail=0
for (( i=0; i<$num; i++ ))
do
random=$(( RANDOM%2 ))
if [ $random -eq 1 ]
then
(( Head++ ))
else
(( Tail++ ))
fi
done
declare -A Coins
Coins[(( Head ))]=$Head
Coins[(( Tail ))]=$Tail
echo "HEAD & TAIL: "${Coins[@]}
h=$(( $Head*100 ))
headper=$(( $h/$num ))
t=$(( $Tail*100 ))
tailper=$(( $t/$num ))
echo " head: $headper% , tail: $tailper% "
<file_sep>/HeadOrTell.sh
#i /bin/bash -x
isHead=1
isHead=2
flip=$((RANDOM%2))
if [ $flip -eq 1 ]
then
echo "Head"
else
echo "Tail"
fi
|
1d27fbcddcf9032398ba82ef8e47f1b1048b9aed
|
[
"Shell"
] | 2
|
Shell
|
prashant169/FlipCoinHeadOrTell
|
ac4fa716cbf30a62024f250e843861613ab4283c
|
0b002460af75be89c4d2ad826d1eee7448fb5c57
|
refs/heads/main
|
<repo_name>donebd/lowproglabs<file_sep>/laba5/mylib/src/testLib.c
#include "stree.h"
#include <stdio.h>
#include "testLib.h"
#include <stdlib.h>
#include <time.h>
void test0() {
srand(time(NULL));
printf("Test creating tree\n");
printf("Enter root of tree: ");
int root;
scanf("%d", &root);
Tree tree = create(root);
int nodes;
printf("How many nodes: ");
int node;
int a;
scanf("%d", &nodes);
for (int i = 0; i < nodes; i++) {
tprint(&tree, 10);
printf("Where connect next node?");
scanf("%d", &node);
a = rand();
addNode(a, findNode(node, &tree));
}
tprint(&tree, 10);
}
void test1() {
printf("Test remove node\n");
Tree newtree = create(10);
addNode(228, newtree.root);
addNode(69, findNode(228, &newtree));
addNode(98, findNode(69, &newtree));
addNode(12, findNode(69, &newtree));
addNode(47, findNode(228, &newtree));
addNode(137, newtree.root);
addNode(55, findNode(137, &newtree));
addNode(224, findNode(55, &newtree));
tprint(&newtree, 10);
printf("Max element = %d \n", findMax(&newtree)->data);
printf("How many nodes want to delete: ");
int node;
int nodes;
scanf("%d", &nodes);
for (int i = 0; i < nodes; i++) {
printf("Removing element: ");
scanf("%d", &node);
removeWith(node, &newtree);
tprint(&newtree, 10);
if (newtree.root == NULL) {
printf("Test over\n");
return;
}
printf("Max element = %d \n", findMax(&newtree)->data);
}
}
<file_sep>/laba5/tests/Makefile
.PHONY: all clean
OBJS= tests.o
FLAGS= -std=c11 -pedantic -Wall -Wextra -O1 -I ../mylib/include
all: tests
clean:
$(R) $(OBJS)
$(R) $(OBJS:.o=.d)
$(R) tests tests.exe
vpath %.c \
src/
vpath %.a \
../mylib
# Не забудем зависимость от библиотеки!
# И компилятору, и make передается только название библиотеки, из него формируется имя файла библиотеки
tests: $(OBJS) -lmylib
$(CC) -o $@ $^
%.o: %.c
$(CC) -MD $(FLAGS) -c -o $@ $<
-include $(OBJS:.o=.d)<file_sep>/laba4/part1/Horner.h
#ifndef LABA4_HORNER_H
#define LABA4_HORNER_H
double horner(double arr[], int n, double x);
#endif //LABA4_HORNER_H
<file_sep>/laba5/mylib/Makefile
# "Фиктивные" цели
.PHONY: all clean
# Объектные файлы, собираемые в статическую библиотеку
OBJS= stree.o
# Файл библиотеки
# Действует соглашение: файл библиотеки <mylib> имеет имя lib<mylib>.a
MYLIBNAME= libmylib.a
# Чтобы достичь цели "all", требуется построить библиотеку
all: $(MYLIBNAME)
# Чтобы достичь цели "clean", требуется удалить созданные при сборке файлы
# - объектные файлы
# - файлы зависимостей
# - файл библиотек
clean:
$(R) $(OBJS)
$(R) $(OBJS:.o=.d)
$(R) $(MYLIBNAME)
# Make должна искать файлы *.h в каталогах include и src
vpath %.h include src
# ..., а файлы *.c - в каталоге src
vpath %.c src
# Рецепт построения файла библиотеки из имеющихся объектных файлов
# значением переменной $@ будет имя файла библиотеки
# значением переменной $^ будет список (с пробелом в качестве символа-разделителя) зависимостей
# (с удаленными дубликатами), в данном случае - список объектных файлов
$(MYLIBNAME): $(OBJS)
$(AR) -rsc $@ $^
# Рецепт построения объектного файла из исходного текста
# значением переменной $< будет имя первого файла в списке зависимостей, в данном случае - имя исходного файла
%.o: %.c
$(CC) -MD $(CFLAGS) -c -o $@ $<
# Включаем всю имеющуюся информацию о зависимостях
# Лидирующий "-" означает, что отсутствие файла .d не является ошибкой
-include $(OBJS:.o=.d)
<file_sep>/README.md
# lowproglabs
ВСЕГО ХОРОШЕГО
<file_sep>/laba5/mylib/src/stree.c
#include <stdio.h>
#include "stdlib.h"
#include "stree.h"
Node *addNode(int x, Node *node) {//возвращает адрес ребенка
Node *new;
if (node == NULL) {
node = (Node *) malloc(sizeof(Node));
node->data = x;
node->down = node->right = NULL;
new = node;
} else {
if (node->down == NULL) {
node->down = (Node *) malloc(sizeof(Node));
node->down->data = x;
node->down->down = node->down->right = NULL;
new = node->down;
} else {
Node *child = node->down;
while (child->right != NULL) {//двигаемся в право
child = child->right;
}
child->right = (Node *) malloc(sizeof(Node));
child->right->data = x;
child->right->down = child->right->right = NULL;
new = child->right;
}
}
return new;
}
Node *findClosest(Node *node, Node *root) {//найти или брата слева или предка
if (node == NULL || root == NULL) return NULL;
if (root->right == node) return root;
if (root->down == node) return root;
Node *findRight = NULL;
Node *findDown = NULL;
if (root->right != NULL) findRight = findClosest(node, root->right);
if (root->down != NULL) findDown = findClosest(node, root->down);
if (findRight != NULL) return findRight;
if (findDown != NULL) return findDown;
return NULL;
}
Node *findParent(Node *node, Tree *tree){
if (tree == NULL) {
printf("404 Tree not found\n");
return NULL;
}
if (findClosest(node, tree->root) == NULL){
return NULL;
}
Node *parent = node;
Node *prev = node;
while (parent->down != prev){
prev = parent;
parent = findClosest(parent,tree->root);
}
return parent;
}
void removeNode(Node *node, Tree *tree) {
if (node == NULL)return;
if (tree == NULL) {
printf("404 Tree not found\n");
return;
}
removeNode(node->down, tree);
if (node->right != NULL) {
node->data = node->right->data;
node->down = node->right->down;
node->right = node->right->right;
} else {
Node *closest = findClosest(node, tree->root);
if (closest == NULL) {
removeNode(node->down, tree);
free(tree->root);
tree->root = NULL;
return;
}
if (closest->right == node) {
free(closest->right);
closest->right = NULL;
}
if (closest->down == node) {
free(closest->down);
closest->down = NULL;
}
}
}
Node *hFind(int x, Node *root){
if (root == NULL) return NULL;
Node *findRight = NULL;
Node *findDown = NULL;
if (root->data == x) {
return root;
}
if (root->right != NULL) findRight = hFind(x, root->right);
if (root->down != NULL) findDown = hFind(x, root->down);
if (findRight != NULL) return findRight;
if (findDown != NULL) return findDown;
return NULL;
}
Node *findNode(int x, Tree *tree) {//найти первый узел с параметром
if (tree == NULL) {
printf("404 Tree not found\n");
return NULL;
}
return hFind(x, tree->root);
}
void removeWith(int x, Tree *tree) {//удалить первый узел с параметром
if (tree == NULL) {
printf("404 Tree not found\n");
return;
}
removeNode(findNode(x, tree), tree);
}
int calcChild(Node *node) {//посчитать число детей узла
int cnt = 0;
if (node->down == NULL) return 0;
Node next = *node->down;
cnt++;
while (next.right != NULL) {
cnt++;
next = *next.right;
}
return cnt;
}
Node *Max(Node *root, Node *max) {
if (max->data < root->data) max = root;
if (root->right != NULL) max = Max(root->right, max);
if (root->down != NULL) max = Max(root->down, max);
return max;
}
Node *findMax(Tree *tree) {
if (tree->root == NULL) {
printf("404 Tree not found\n");
return NULL;
}
Node *max = Max(tree->root, tree->root);
return max;
}
struct tree create(int x) {
Node *root = addNode(x, NULL);
struct tree new;
new.root = root;
return new;
}
void hPrint(Node *node, int d) {
if (node == NULL) return;
for (int i = 0; i < d; i++)
printf(" ");
printf("%d\n", node->data);
hPrint(node->down, d + 4);
hPrint(node->right, d);
}
void tprint(Tree *tree) {//вывод дерева в консоль
if (tree->root == NULL) {
printf("404 Tree not found\n");
return;
}
printf("---------Tree----------\n");
hPrint(tree->root,5);
printf("-----------------------\n");
}
<file_sep>/laba4/part2/makeCompile/main.c
#include <stdio.h>
#include "Horner.h"
int main() {
double array[] = {55, 128.5, -12, 9};
double x = 2.1;
int n = sizeof(array)/8;
double f = horner(array, n, x);
int i;
for(i = 0; i < n; i++)
printf("[%.2f] ", array[i]);
printf("\nx=%f\nf(x)=%f",x,f);
return 0;
}
<file_sep>/laba5/Makefile
# Параметры для компилятора
# Стандарт языка СИ 11 года, агрегаторы предупреждений и указание папки, где следует искать хедеры
export CFLAGS= -std=c11 -Wall -pedantic -Wextra -I ./include
# Выбор компилятора
export CC=gcc
# Для удаления файлов
export R=del -f
# Build - сборка библиотеки + программы.
build:
make buildlib
make buildapp
make buildtest
@echo ------------------------------
@echo To start tests write make test
@echo To start demo write make app
# Buildlib - собрать статически-линкуемую библиотеку в каталоге mylib
buildlib:
$(MAKE) -C mylib
# Buildpp - скомпилировать программу с использованием нашей библиотеки
buildapp:
$(MAKE) -C myapp
buildtest:
$(MAKE) -C tests
# Test - запустить модульные тесты и вывести результат на консоль
test:
./tests/tests.exe
app:
./myapp/myapp.exe
.PHONY: build buildlib buildapp buildtests test app clean
# Clean - удаление всех файлов сгенерированных в процессе работы мейк-файлов и компилятора
# Вызывается во всех папках, где есть мейк-файлы
clean:
$(MAKE) -C mylib clean
$(MAKE) -C myapp clean
$(MAKE) -C tests clean<file_sep>/laba4/part1/Horner.c
#include "Horner.h"
double horner(double arr[], int n, double x){
int i;
if (n < 2) {
if (n == 1) return arr[0];
return 0;
}
double fx = arr[0]*x + arr[1];
for(i=2; i<n; i++) {
fx *= x;
fx += arr[i];
}
return fx;
}<file_sep>/laba5/mylib/include/stree.h
#ifndef LABA5_STREE_H
#define LABA5_STREE_H
#define Node struct node
Node {
int data;
Node *down;//самый левый ребенок
Node *right;//брат справа
};
struct tree {
Node *root;
};
typedef struct tree Tree;
Node *addNode(int x, Node *node);
Node *findClosest(Node *node, Node *root);
void removeNode(Node *node, Tree *tree);
Node *hFind(int x, Node *root);
Node *findNode(int x, Tree *tree);
void removeWith(int x, Tree *tree);
int calcChild(Node *node);
Node *Max(Node *root, Node *max);
Node *findMax(Tree *tree);
struct tree create(int x);
void hPrint(Node *node, int d);
void tprint(Tree *tree);
Node *findParent(Node *node, Tree *tree);
#endif //LABA5_STREE_H
<file_sep>/laba5/mylib/include/testLib.h
#ifndef LABA5_TESTLIB_H
#define LABA5_TESTLIB_H
void test0();
void test1();
#endif //LABA5_TESTLIB_H
<file_sep>/laba5/tests/src/tests.c
#include "stree.h"
#include <stdio.h>
void tests() {
Tree tree = create(10);
Node *child0 = addNode(55, tree.root);
if (tree.root->down == child0) printf("Test init tree complete.\n");//test add
else {
printf("!!!Test init tree incorrect!!!");
return;
}
if (findParent(child0, &tree) == tree.root) printf("Test find parent complete.\n");//test find parent
else {
printf("!!!Test find parent incorrect!!!");
return;
}
if (calcChild(tree.root) == 1 && calcChild(child0) == 0) printf("Test calc child complete.\n");//test calc child
else {
printf("!!!Test calc child incorrect!!!");
return;
}
addNode(15, child0);
if (findParent(findNode(15, &tree), &tree) == child0) printf("Test find with parameter complete.\n");//test find with par
else {
printf("!!!Test find with parameter incorrect!!!");
return;
}
if (findParent(tree.root, &tree) == NULL) printf("Test find incorrect parent complete.\n");//test find incorrect parent
else {
printf("!!!Test find incorrect parent incorrect!!!");
return;
}
if (findNode(228, &tree) == NULL) printf("Test find incorrect node complete.\n");//test find incorrect node
else {
printf("!!!Test find incorrect node incorrect!!!");
return;
}
addNode(1337, child0);
addNode(1488, child0);
addNode(65, child0);
addNode(798787979, child0);
if (findMax(&tree) == findNode(798787979, &tree)) printf("Test find max node complete.\n");//test find max node
else {
printf("!!!Test find max node incorrect!!!");
return;
}
addNode(45, findNode(798787979, &tree));
if (findParent(findParent(findNode(45, &tree), &tree), &tree) == child0)
printf("Test nested search complete.\n");//test nested search
else {
printf("!!!Test nested search incorrect!!!");
return;
}
if (calcChild(child0) == 5) printf("Test calc children complete.\n");//test calc child
else {
printf("!!!Test calc children incorrect!!!");
return;
}
removeNode(findNode(798787979, &tree), &tree);
if (findNode(45, &tree) == NULL && findNode(798787979, &tree) == NULL && calcChild(child0) == 4 &&
findMax(&tree)->data == 1488)
printf("Test remove node complete.\n");//test remove node
else {
printf("!!!Test remove node incorrect!!!");
return;
}
printf("All test passed /'0'/ \n");
}
int main(){
tests();
return 0;
}
|
ce5087f7ac976ea33f044f3a1f63d970c5e0e35c
|
[
"Markdown",
"C",
"Makefile"
] | 12
|
C
|
donebd/lowproglabs
|
635acbdd216d983a45ff6c189dd630c19f082cef
|
bbce2b91b6a85cb59b8fff0f2e778925750fcf73
|
refs/heads/master
|
<file_sep>//
// Page.swift
// MovieDB
//
import Foundation
/// A class used as a generic wrapper to handle paginated requests.
internal struct Page<Entity: Decodable> {
/// A currently downloaded page.
let page: Int
/// An array of generic results associated with a given page.
let results: [Entity]
}
extension Page: Decodable {
private enum CodingKeys: String, CodingKey {
case page
case results
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
page = try container.decode(Int.self, forKey: .page)
results = try container.decode([Entity].self, forKey: .results)
}
}
<file_sep>//
// MovieDetailViewController.swift
// MovieDB
//
import UIKit
internal final class MovieDetailViewController: UIViewController {
private lazy var stackView: UIStackView = {
let stackView = UIStackView.autolayoutView()
stackView.axis = .vertical
stackView.spacing = 20
stackView.alignment = .center
return stackView
}()
private lazy var posterImage: UIImageView = {
let imageView = UIImageView.autolayoutView()
imageView.contentMode = .scaleAspectFit
return imageView
}()
private lazy var titleLabel = UILabel.autolayoutView()
private lazy var statusLabel = UILabel.autolayoutView()
private lazy var revenueLabel = UILabel.autolayoutView()
private lazy var overviewLabel: UILabel = {
let label = UILabel.autolayoutView()
label.numberOfLines = 0
return label
}()
private lazy var dollarNumberFormatter: NumberFormatter = {
let numberFormatter = NumberFormatter()
numberFormatter.locale = Locale(identifier: "en_US")
numberFormatter.numberStyle = .currency
return numberFormatter
}()
private let movie: Movie
private let movieDataProvider: MovieDataProvider
/// Creates a new instance of MovieDetailViewController. It's a class used to display details of a given movie.
///
/// - Parameters:
/// - movie: a movie that details should be downloaded for.
/// - movieDataProvider: a class used to download movie details from API.
init(movie: Movie, movieDataProvider: MovieDataProvider) {
self.movie = movie
self.movieDataProvider = movieDataProvider
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable, message: "Not available, use init(movie: _, movieDataProvider: _)")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
title = movie.title
view.backgroundColor = .white
view.addSubview(stackView)
stackView.addArrangedSubviews([posterImage, titleLabel, statusLabel, revenueLabel, overviewLabel])
let constraints = [
stackView.topAnchor.constraint(equalTo: view.layoutMarginsGuide.topAnchor, constant: 50),
stackView.centerXAnchor.constraint(equalTo: view.centerXAnchor),
stackView.rightAnchor.constraint(equalTo: view.layoutMarginsGuide.rightAnchor),
stackView.leftAnchor.constraint(equalTo: view.layoutMarginsGuide.leftAnchor),
posterImage.heightAnchor.constraint(equalToConstant: 250)
]
NSLayoutConstraint.activate(constraints)
downloadMovieDetails()
}
private func downloadMovieDetails() {
movieDataProvider.obtainMovieDetails(movie: movie) { [weak self] result in
switch result {
case .success(let details):
self?.realoadWith(movieDetails: details)
case .failure(let error):
self?.presentAlert(message: error.humanReadableDescription)
}
}
}
private func realoadWith(movieDetails: MovieDetails) {
titleLabel.text = movieDetails.title
statusLabel.text = movieDetails.status
revenueLabel.text = movieDetails.revenue == 0 ? nil : dollarNumberFormatter.string(from: NSNumber(value: movieDetails.revenue))
overviewLabel.text = movieDetails.overview
posterImage.loadResource(path: movieDetails.posterPath)
}
}
<file_sep>//
// NetworkClient.swift
// MovieDB
//
import Foundation
internal protocol NetworkClient {
/// Performs a given Request to the API.
///
/// - Parameters:
/// - request: a request that should be performed.
/// - completion: a completion block executed after network call has finished. Returns a swift Result instance with either a Page with results or an error.
func perform<Response>(request: Request<Response>, completion: @escaping (Result<Response, NetworkError>) -> ()) where Response: Decodable
}
internal final class DefaultNetworkClient: NetworkClient {
private let urlSession = URLSession(configuration: URLSessionConfiguration.default)
internal func perform<Response>(request: Request<Response>, completion: @escaping (Result<Response, NetworkError>) -> ()) where Response: Decodable {
let request = URLRequest(request: request)
urlSession.dataTask(with: request) { [weak self] (data, response, error) in
if let error = error {
self?.dispatch(result: Result.failure(NetworkError.systemError(error: error)), on: completion)
return
}
guard let httpResponse = response as? HTTPURLResponse, let data = data else {
return
}
if let responseError = NetworkError(code: httpResponse.statusCode) {
self?.dispatch(result: Result.failure(responseError), on: completion)
return
}
do {
let responseData = try JSONDecoder().decode(Response.self, from: data)
self?.dispatch(result: Result.success(responseData), on: completion)
} catch let error {
self?.dispatch(result: Result.failure(NetworkError.improperResponse(error: error)), on: completion)
}
}.resume()
}
private func dispatch<Response>(result: Result<Response, NetworkError>, on closure: @escaping (Result<Response, NetworkError>) -> ()) {
DispatchQueue.main.async {
closure(result)
}
}
}
<file_sep>//
// MovieDetail.swift
// MovieDB
//
import Foundation
internal struct MovieDetails {
/// API id of the movie.
let id: Int
/// A title of the movie.
let title: String
/// A short description of the movie.
let overview: String
/// A link to the homepage of the movie.
let homepage: String?
/// Revenue of the movie in dollars.
let revenue: Int
/// Release status of the movie.
let status: String
/// Path to the poster image. Should be appended to image base url.
let posterPath: String?
}
extension MovieDetails: Decodable {
private enum CodingKeys: String, CodingKey {
case id
case title
case overview
case homepage
case revenue
case status
case poster_path
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
title = try container.decode(String.self, forKey: .title)
overview = try container.decode(String.self, forKey: .overview)
homepage = try container.decodeIfPresent(String.self, forKey: .homepage)
revenue = try container.decode(Int.self, forKey: .revenue)
status = try container.decode(String.self, forKey: .status)
posterPath = try container.decodeIfPresent(String.self, forKey: .poster_path)
}
}
<file_sep>//
// URL.swift
// MovieDB
//
import Foundation
internal extension URL {
/// Specifies the types http schemes used to perform requests.
///
/// - http: perform request qithout usage of ssl.
/// - https: perform request using ssl.
enum Scheme: String {
case http, https
}
/// A string with a base URL's host to API.
static let baseURLString = "api.themoviedb.org"
/// A string with a base URL's host for image downloading.
static let imageDownloadBaseURLString = "image.tmdb.org"
/// A base URL for API.
static var baseURL: URL? {
var components = URLComponents()
components.scheme = Scheme.https.rawValue
components.host = URL.baseURLString
return components.url
}
/// A base URL for image downloads.
static var imageDownloadBaseURL: URL? {
var components = URLComponents()
components.scheme = Scheme.https.rawValue
components.host = URL.imageDownloadBaseURLString
return components.url
}
}
<file_sep>#
# Podfile
#
platform :ios, '11.0'
inhibit_all_warnings!
use_frameworks!
target 'MovieDB' do
end
target 'MovieDBTests' do
end
# Keys
plugin 'cocoapods-keys', {
project: 'MovieDB',
keys: [
'MovieDatabaseAPIKey'
]
}
<file_sep>//
// NSObject.swift
// MovieDB
//
import Foundation
internal extension NSObject {
/// Returns class name stripped from module name.
class var className: String {
let namespaceClassName = NSStringFromClass(self)
return namespaceClassName.components(separatedBy: ".").last!
}
/// Returns class name stripped from module name.
var className: String {
let namespaceClassName = NSStringFromClass(self.classForCoder)
return namespaceClassName.components(separatedBy: ".").last!
}
}
<file_sep>//
// Request.swift
// MovieDB
//
import Foundation
/// Specifies the moethods used to perform netowrk requests.
///
/// - GET: GET http method.
/// - POST: POST http method.
internal enum HttpMethod: String {
case GET, POST
}
internal struct Request<Response: Decodable> {
/// Method that should be used to perform the request.
let method: HttpMethod
/// Path to a specified resource in API.
let path: String
/// Query items that should be appended to the request's url.
let queryItems: [URLQueryItem]
}
<file_sep>//
// URLRequestExtensionTests.swift
// MovieDBTests
//
// Created by <NAME> on 28/04/2019.
// Copyright © 2019 netguru. All rights reserved.
//
import XCTest
@testable import MovieDB
class URLRequestExtensionTests: XCTestCase {
func testRequestInitialization() {
let queryItems = [
URLQueryItem(name: "test1", value: "test1"),
URLQueryItem(name: "test2", value: "test2")
]
let request = Request<Movie>(method: .GET, path: "/v2/test/api", queryItems: queryItems)
let urlRequest = URLRequest(request: request, addAuthorization: false)
XCTAssertEqual(urlRequest.httpMethod, "GET", "Improper method for request.")
XCTAssertEqual(urlRequest.url?.absoluteString, "https://api.themoviedb.org/v2/test/api?test1=test1&test2=test2", "Improper url string from components.")
}
}
<file_sep>//
// ViewController.swift
// MovieDB
//
import UIKit
internal final class MovieListViewController: UIViewController {
private lazy var tableView: UITableView = {
let tableView = UITableView.autolayoutView()
tableView.dataSource = self
tableView.delegate = self
tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.className)
tableView.rowHeight = 50
return tableView
}()
private lazy var sortButton = UIBarButtonItem(title: "Sort", style: .plain, target: self, action: #selector(sortTapped))
private var movies = [Movie]()
private var currentPage = 1
private var sorted = false
private let movieDataProvider: MovieDataProvider
/// Creates a new instance of MovieListViewController. It's a class used to display a paginated list of all movies.
///
/// - Parameter movieDataProvider: a class used to download movie list.
init(movieDataProvider: MovieDataProvider) {
self.movieDataProvider = movieDataProvider
super.init(nibName: nil, bundle: nil)
}
@available(*, unavailable, message: "Not available, use init(movieDataProvider: _)")
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem = sortButton
view.backgroundColor = .white
view.addSubview(tableView)
let constraints = [
tableView.topAnchor.constraint(equalTo: view.topAnchor),
tableView.bottomAnchor.constraint(equalTo: view.bottomAnchor),
tableView.rightAnchor.constraint(equalTo: view.rightAnchor),
tableView.leftAnchor.constraint(equalTo: view.leftAnchor)
]
NSLayoutConstraint.activate(constraints)
downloadMovieList(page: currentPage, sorted: sorted)
}
private func downloadMovieList(page: Int, sorted: Bool) {
movieDataProvider.obtainMovies(page: page, sorted: sorted) { [weak self] result in
switch result {
case .success(let element):
self?.movies.append(contentsOf: element.results)
self?.tableView.reloadData()
case .failure(let error):
self?.presentAlert(message: error.humanReadableDescription)
}
}
}
@objc private func sortTapped() {
currentPage = 1
sorted.toggle()
movies.removeAll()
tableView.reloadData()
downloadMovieList(page: currentPage, sorted: sorted)
}
}
extension MovieListViewController: UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return movies.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.className, for: indexPath)
let movie = movies[indexPath.row]
cell.textLabel?.text = movie.title
cell.detailTextLabel?.text = movie.overview
cell.accessoryType = .disclosureIndicator
return cell
}
func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
guard indexPath.row == movies.count - 1 else { return }
currentPage += 1
downloadMovieList(page: currentPage, sorted: sorted)
}
}
extension MovieListViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let movie = movies[indexPath.row]
let viewController = ViewControllerAssembly.defaultAssembly.movieDetailsViewController(movie: movie)
navigationController?.pushViewController(viewController, animated: true)
tableView.deselectRow(at: indexPath, animated: true)
}
}
<file_sep>//
// UIViewController.swift
// MovieDB
//
import UIKit
internal extension UIViewController {
/// Presents a UIAlertController on screen with a given message and single ok button to dismiss it.
///
/// - Parameter message: a message that should be presented within the alert.
func presentAlert(message: String) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
let okAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
alertController.addAction(okAction)
present(alertController, animated: true, completion: nil)
}
}
<file_sep>//
// UIImageView.swift
// MovieDB
//
import UIKit
internal extension UIImageView {
/// Loads the image for a image view with a given resource url appendix string.
///
/// - Parameter path: an appendix that should be added to bas image download url. Obtained from API.
func loadResource(path: String?) {
DispatchQueue.global().async { [weak self] in
guard
var url = URL.imageDownloadBaseURL,
let path = path
else {
return
}
url.appendPathComponent("/t/p/w1280")
url.appendPathComponent(path)
do {
let data = try Data(contentsOf: url)
let image = UIImage(data: data)
DispatchQueue.main.async {
self?.image = image
}
} catch {
}
}
}
}
<file_sep>//
// Assembly.swift
// MovieDB
//
import Foundation
internal final class ViewControllerAssembly {
/// A singleton instance of ViewControllerAssembly.
static let defaultAssembly = ViewControllerAssembly()
private let dependencyAssembly = DependencyAssembly()
/// A method used to create a view controller with movie list.
///
/// - Returns: a view controller used for movie list preseentation.
func moviewListViewController() -> MovieListViewController {
return MovieListViewController(movieDataProvider: dependencyAssembly.movieDataProvider)
}
/// A method used to create a view controller with movie details.
///
/// - Parameter movie: a movie that details should be presented for.
/// - Returns: a view controller used for movie details preseentation for a given movie.
func movieDetailsViewController(movie: Movie) -> MovieDetailViewController {
return MovieDetailViewController(movie: movie, movieDataProvider: dependencyAssembly.movieDataProvider)
}
}
fileprivate final class DependencyAssembly {
/// A class used to perform networking calls.
lazy var networkClient = DefaultNetworkClient()
/// A class used to download movie details.
lazy var movieDataProvider = DefaultMovieDataProvider(networkClient: networkClient)
}
<file_sep>//
// UIViewExtensionTests.swift
// MovieDBTests
//
// Created by <NAME> on 28/04/2019.
// Copyright © 2019 netguru. All rights reserved.
//
import XCTest
@testable import MovieDB
class UIViewExtensionTests: XCTestCase {
func testAutolayoutView() {
let view = UIView.autolayoutView()
XCTAssertFalse(view.translatesAutoresizingMaskIntoConstraints, "Translates autoresizing masks into constraints not turned off properly.")
}
}
<file_sep>//
// Movie.swift
// MovieDB
//
import Foundation
internal struct Movie {
/// API id of the movie.
let id: Int
/// Title of the movie.
let title: String
/// Short description of the movie.
let overview: String
}
extension Movie: Decodable {
private enum CodingKeys: String, CodingKey {
case id
case title
case overview
case releaseDate = "release_date"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decode(Int.self, forKey: .id)
title = try container.decode(String.self, forKey: .title)
overview = try container.decode(String.self, forKey: .overview)
}
}
<file_sep>//
// NetworkError.swift
// MovieDB
//
import Foundation
/// Represents all errors that can be thrown while performin network requests.
///
/// - systemError: operating system threw an error. This is porbably caused by no internet connection, wrong SSL cerficiate installed etc.
/// - describedError: request returned 4XX return code with a desription of an error.
/// - improperResponse: parsing the obtained response was impossible. Check the Codable conformances in models.
/// - notFound: received a 404 error code in response.
/// - badRequest: received a 40X indicating the performed request contained wrong data.
/// - serverError: received a 5XX error. Probably the server is down.
/// - unauthorized: received a 401 error. Did not provide sufficien authorization.
internal enum NetworkError: Error {
case systemError(error: Error)
case describedError(description: String)
case improperResponse(error: Error)
case notFound
case badRequest
case serverError
case unauthorized
/// Initializes a new instance of APIRequestError. Created only if passed code indicated error.
///
/// - Parameter code: HTTP status code.
init?(code: Int) {
switch code {
case 404:
self = .notFound
case 401:
self = .unauthorized
case 400...499:
self = .badRequest
case 500...599:
self = .serverError
default:
return nil
}
}
/// Resturns a human readable description of the error.
internal var humanReadableDescription: String {
switch self {
case .systemError(error: let error):
return error.localizedDescription
case .describedError(description: let description):
return description
case .notFound:
return "There seems to be some issues with the API link. Please contact us."
case .badRequest, .improperResponse(error: _):
return "There seems to be some issues with the API response. Please contact us."
case .unauthorized:
return "Authorization token expired. Please contact us."
case .serverError:
return "Server is not responding for some reason. Please try again later."
}
}
}
<file_sep>//
// UIStackViewExtensionTests.swift
// MovieDBTests
//
// Created by <NAME> on 28/04/2019.
// Copyright © 2019 netguru. All rights reserved.
//
import XCTest
@testable import MovieDB
class UIStackViewExtensionTests: XCTestCase {
func testArrangedSubviews() {
let subview1 = UIImageView()
let subview2 = UIView()
let subview3 = UILabel()
let stackView = UIStackView()
stackView.addArrangedSubviews([subview1, subview2, subview3])
XCTAssertEqual(stackView.arrangedSubviews.count, 3, "Wrong amount of arranged subviews")
XCTAssertEqual(stackView.arrangedSubviews[0], subview1, "Wrong first arranged subview")
XCTAssertEqual(stackView.arrangedSubviews[2], subview3, "Wrong second arranged subview")
}
}
<file_sep># MovieDB
It's a simple application for displayingg movies.
### Instalation
After clone, you should install cocoapods with:
```bash
pod install
```
project uses Cocoapods-Keys for key encryption. Duringg pod installation you should provide a proper API Key to access movie database. You can obtain one from https://www.themoviedb.org. You can also add an `.env` file with:
`MovieDatabaseAPIKey = your_api_key_here`
<file_sep>//
// URLRequest.swift
// MovieDB
//
import Foundation
import Keys
internal extension URLRequest {
/// Dafult timeout for all requests.
private static let defaultTimeoutInterval: TimeInterval = 30
/// An API key for the internet movie database. Taken from cocoapods keys.
private static let apiKey = Keys.MovieDBKeys().movieDatabaseAPIKey
/// Creates a new instance of URL request for a given Request instance. Adds api key authorization.
///
/// - Parameters:
/// - request: a request with all data used to create a URLRequest.
/// - addAuthorization: specifies if api key should be added to request.
init<Response>(request: Request<Response>, addAuthorization: Bool = true) {
var components = URLComponents()
components.scheme = URL.Scheme.https.rawValue
components.host = URL.baseURLString
components.path = request.path
components.queryItems = request.queryItems
if addAuthorization {
components.queryItems?.append(URLQueryItem(name: "api_key", value: URLRequest.apiKey))
}
guard let url = components.url else {
preconditionFailure("Failed to create url from given components.")
}
self.init(url: url, cachePolicy: .reloadIgnoringLocalAndRemoteCacheData, timeoutInterval: URLRequest.defaultTimeoutInterval)
}
}
<file_sep>//
// MovieDataProvider.swift
// MovieDB
//
import Foundation
internal protocol MovieDataProvider {
/// Creates a new instance of MovieDataProvider. A clas sused to obtain movie's data.
///
/// - Parameter networkClient: a network client that should be used to download movies.
init(networkClient: NetworkClient)
/// Downloads a paginated list of all movies with a specified page number. List can be sorted by movie's release date.
///
/// - Parameters:
/// - page: a page that movies should be downloaded for.
/// - sorted: specifies if list should be sorted by movie's release date.
/// - completion: a completion block executed after network call has finished. Returns a swift Result instance with either a Page with results or an error.
func obtainMovies(page: Int, sorted: Bool, completion: @escaping (Result<Page<Movie>, NetworkError>) -> ())
/// Downloads a details of a given movie.
///
/// - Parameters:
/// - movie: a movie fro which details should be downloaded.
/// - completion: a completion block executed after network call has finished. Returns a swift Result instance with either a Page with results or an error.
func obtainMovieDetails(movie: Movie, completion: @escaping (Result<MovieDetails, NetworkError>) -> ())
}
/// Default implementation of MovieDataProvider.
internal final class DefaultMovieDataProvider: MovieDataProvider {
private enum Path {
case movieList
case movieDetail(id: Int)
var urlString: String {
switch self {
case .movieList:
return "/3/discover/movie"
case .movieDetail(let id):
return "/3/movie/\(id)"
}
}
}
private let networkClient: NetworkClient
init(networkClient: NetworkClient) {
self.networkClient = networkClient
}
func obtainMovies(page: Int, sorted: Bool, completion: @escaping (Result<Page<Movie>, NetworkError>) -> ()) {
var queryItems = [URLQueryItem(name: "page", value: String(page))]
if sorted {
queryItems.append(URLQueryItem(name: "sort_by", value: "release_date.desc"))
}
let request = Request<Page<Movie>>(
method: .GET,
path: Path.movieList.urlString,
queryItems: queryItems
)
networkClient.perform(request: request, completion: completion)
}
func obtainMovieDetails(movie: Movie, completion: @escaping (Result<MovieDetails, NetworkError>) -> ()) {
let request = Request<MovieDetails>(
method: .GET,
path: Path.movieDetail(id: movie.id).urlString,
queryItems: []
)
networkClient.perform(request: request, completion: completion)
}
}
<file_sep>//
// UIStackView.swift
// MovieDB
//
import UIKit
internal extension UIStackView {
/// Convenience method allowing to add an array of arranged subviews.
///
/// - Parameter subviews: array of views to be added as arranged subviews.
func addArrangedSubviews(_ subviews: [UIView]) {
subviews.forEach { self.addArrangedSubview($0) }
}
}
<file_sep>//
// NSObjectExtensionTests.swift
// MovieDBTests
//
// Created by <NAME> on 28/04/2019.
// Copyright © 2019 netguru. All rights reserved.
//
import XCTest
@testable import MovieDB
class NSObjectExtensionTests: XCTestCase {
func testInstanceClassName() {
let testView = UIView()
XCTAssertEqual(testView.className, "UIView", "Improper instance class name for UIView")
let testTableViewCell = UITableViewCell()
XCTAssertEqual(testTableViewCell.className, "UITableViewCell", "Improper instance class name for UITableViewCell")
let testObject = NSObject()
XCTAssertEqual(testObject.className, "NSObject", "Improper instance class name for NSObject")
}
func testStaticClassName() {
XCTAssertEqual(UIView.className, "UIView", "Improper instance class name for UIView")
XCTAssertEqual(UITableViewCell.className, "UITableViewCell", "Improper instance class name for UIView")
XCTAssertEqual(NSObject.className, "NSObject", "Improper instance class name for NSObject")
}
}
|
32d91fab522af21c180ba011f962415671354f5b
|
[
"Swift",
"Ruby",
"Markdown"
] | 22
|
Swift
|
poszposz/moviedb
|
d796a34be8f49f77997849d650fe0b9142a08570
|
2e73c5d9e8c5115810c3b3bf9149b01f27665671
|
refs/heads/master
|
<file_sep>class Admin::Blog::BaseController < ComfyBlog.config.admin_controller.to_s.constantize
# ...
end<file_sep>module Blog::ApplicationHelper
def comfy_blog_form_for(record_or_name_or_array, *args, &proc)
options = args.extract_options!
form_for(
record_or_name_or_array,
*(args << options.merge(:builder => ComfyBlog::FormBuilder)), # .config.form_builder.to_s.constantize)),
&proc
)
end
# URL helpers for blog_post_(path/url)
%w(path url).each do |type|
define_method "blog_post_#{type}" do |post|
send("dated_blog_post_#{type}", post.year, ("%02d" % post.month), post.slug)
end
end
def blah
'blah'
end
end
<file_sep>require File.expand_path('../../../test_helper', File.dirname(__FILE__))
class Admin::Blog::PostsControllerTest < ActionController::TestCase
def test_get_index
get :index
assert_response :success
assert assigns(:posts)
assert_template :index
end
def test_get_index_with_pagination
if defined?(WillPaginate) || defined?(Kaminari)
get :index, :page => 99
assert_response :success
assert assigns(:posts)
assert_equal 0, assigns(:posts).size
end
end
def test_get_new
get :new
assert_response :success
assert assigns(:post)
assert_template :new
assert_select "form[action='/admin/blog/posts']"
end
def test_creation
assert_difference 'Blog::Post.count' do
post :create, :post => {
:title => 'Test',
:content => 'Content'
}
assert_response :redirect
assert_redirected_to :action => :edit, :id => assigns(:post)
assert_equal 'Blog Post created', flash[:notice]
end
end
def test_creation_failure
assert_no_difference 'Blog::Post.count' do
post :create, :post => { }
assert_response :success
assert_template :new
assert assigns(:post)
assert_equal 'Failed to create Blog Post', flash[:error]
end
end
def test_get_edit
get :edit, :id => blog_posts(:default)
assert_response :success
assert_template :edit
assert assigns(:post)
end
def test_get_edit_failure
get :edit, :id => 'bogus'
assert_response :redirect
assert_redirected_to :action => :index
assert_equal 'Blog Post not found', flash[:error]
end
def test_update
post = blog_posts(:default)
put :update, :id => post, :post => {
:title => 'Updated Post'
}
assert_response :redirect
assert_redirected_to :action => :edit, :id => assigns(:post)
assert_equal 'Blog Post updated', flash[:notice]
post.reload
assert_equal 'Updated Post', post.title
end
def test_update_failure
post = blog_posts(:default)
put :update, :id => post, :post => {
:title => ''
}
assert_response :success
assert_template :edit
assert_equal 'Failed to update Blog Post', flash[:error]
post.reload
assert_not_equal '', post.title
end
def test_destroy
assert_difference 'Blog::Post.count', -1 do
delete :destroy, :id => blog_posts(:default)
assert_response :redirect
assert_redirected_to :action => :index
assert_equal 'Blog Post removed', flash[:notice]
end
end
end<file_sep>class String
# Transforms strings into a nice, URL-friendly format
def slugify
self.downcase.gsub(/\W|_/, ' ').strip.squeeze(' ').gsub(/\s/, '-')
end
end<file_sep>require File.expand_path('../../../test_helper', File.dirname(__FILE__))
class Blog::ApplicationHelperTest < ActionView::TestCase
def test_blog_post_path
assert_equal '/2012/01/default-title', blog_post_path(blog_posts(:default))
assert_equal 'http://test.host/2012/01/default-title', blog_post_url(blog_posts(:default))
end
end
<file_sep>require File.expand_path('../test_helper', File.dirname(__FILE__))
class TaggingTest < ActiveSupport::TestCase
def test_fixtures_validity
Blog::Tagging.all.each do |tagging|
assert tagging.valid?, tagging.errors.to_s
end
end
def test_destroy_for_tag
assert_difference ['Blog::Tagging.count', 'Blog::Tag.count'], -1 do
blog_taggings(:tag).destroy
end
end
def test_destroy_for_category
assert_difference 'Blog::Tagging.count', -1 do
assert_no_difference 'Blog::Tag.count' do
blog_taggings(:category).destroy
end
end
end
def test_scopes
assert_equal 1, Blog::Tagging.for_tags.count
assert_equal 1, Blog::Tagging.for_categories.count
end
end
<file_sep>require File.expand_path('../../test_helper', File.dirname(__FILE__))
class Blog::PostsControllerTest < ActionController::TestCase
def test_get_index
get :index
assert_response :success
assert_template :index
assert assigns(:posts)
assert_equal 1, assigns(:posts).size
end
def test_get_index_as_rss
get :index, :format => :rss
assert_response :success
assert_template :index
assert assigns(:posts)
assert_equal 1, assigns(:posts).size
end
def test_get_index_with_unpublished
blog_posts(:default).update_attribute(:is_published, false)
get :index
assert_response :success
assert_equal 0, assigns(:posts).size
end
def test_get_index_with_pagination
if defined?(WillPaginate) || defined?(Kaminari)
get :index, :page => 99
assert_response :success
assert_equal 0, assigns(:posts).size
end
end
def test_get_index_for_tagged
get :index, :tag => blog_tags(:tag).name
assert_response :success
assert_equal 1, assigns(:posts).size
get :index, :tag => 'invalid'
assert_response :success
assert_equal 0, assigns(:posts).size
end
def test_get_index_for_categorized
get :index, :category => blog_tags(:category).name
assert_response :success
assert_equal 1, assigns(:posts).size
get :index, :category => 'invalid'
assert_response :success
assert_equal 0, assigns(:posts).size
end
def test_get_index_for_year_archive
get :index, :year => 2012
assert_response :success
assert_equal 1, assigns(:posts).size
get :index, :year => 1999
assert_response :success
assert_equal 0, assigns(:posts).size
end
def test_get_index_for_month_archive
get :index, :year => 2012, :month => 1
assert_response :success
assert_equal 1, assigns(:posts).size
get :index, :year => 2012, :month => 12
assert_response :success
assert_equal 0, assigns(:posts).size
end
def test_get_show
get :show, :id => blog_posts(:default)
assert_response :success
assert_template :show
assert assigns(:post)
end
def test_get_show_unpublished
post = blog_posts(:default)
post.update_attribute(:is_published, false)
get :show, :id => post
assert_response 404
end
def test_get_show_with_date
post = blog_posts(:default)
get :show, :year => post.year, :month => post.month, :slug => blog_posts(:default).slug
assert_response :success
assert_template :show
assert assigns(:post)
end
def test_get_show_with_date_invalid
get :show, :year => '1999', :month => '99', :slug => 'invalid'
assert_response 404
end
def test_get_show_with_disqus
ComfyBlog.config.disqus_shortname = 'test'
post = blog_posts(:default)
get :show, :year => post.year, :month => post.month, :slug => blog_posts(:default).slug
assert_response :success
end
end
<file_sep>require File.expand_path('../test_helper', File.dirname(__FILE__))
class ConfigurationTest < ActiveSupport::TestCase
def test_configuration
assert config = ComfyBlog.configuration
assert_equal 'ComfyBlog', config.title
assert_equal 'A Simple Blog', config.description
assert_equal 'admin', config.admin_route_prefix
assert_equal '', config.public_route_prefix
assert_equal 'ApplicationController', config.admin_controller
assert_equal 'ComfyBlog::FormBuilder', config.form_builder
assert_equal 10, config.posts_per_page
assert_equal false, config.auto_publish_comments
assert_equal nil, config.disqus_shortname
end
def test_initialization_overrides
ComfyBlog.config.admin_route_prefix = 'new-admin'
assert_equal 'new-admin', ComfyBlog.config.admin_route_prefix
end
def test_disqus_enabled?
assert !ComfyBlog.disqus_enabled?
ComfyBlog.config.disqus_shortname = 'test'
assert ComfyBlog.disqus_enabled?
end
end<file_sep># ComfyBlog [](http://travis-ci.org/comfy/comfy-blog) [](https://gemnasium.com/comfy/comfy-blog)
ComfyBlog is an simple blog management engine for Rails 3.1 apps. It also integrates with [ComfortableMexicanSofa](https://github.com/comfy/comfortable-mexican-sofa) CMS Engine
CabForward branched from github: 'joshuaogle/comfy-blog', branch: 'feature/1-8-1'
## Installation
Add gem definition to your Gemfile:
gem 'comfy_blog'
Then from the Rails project's root run:
bundle install
rails g comfy:blog
Add the blog routes.
ComfyBlog::Routing.admin
ComfyBlog::Routing.content
then migrate
rake db:migrate
Now you should be able to go to `/admin/blog/posts` and add new blog posts.
## Configuration
First thing you want to do is change title and description of the blog.
For that you need to adjust `comfy_blog` initializer.
config.title = 'ComfyBlog'
config.description = 'A Simple Blog'
You'll notice that you can access blog's admin area without any type of authentication.
This is because ComfyBlog doesn't deal with users, it only knows how to save and show
blog posts. You probably want to put blog's admin controllers behind your controller
that handles authentication.
config.admin_controller = 'YourAdminBaseController'
If you want blog's controller paths to match your admin path, like `cms-admin`. Change
the following configuration.
config.admin_route_prefix = 'cms-admin'
By default blog posts are served from the root. If you want to section off blog content
to a `/blog` path. Adjust this configuration:
config.public_route_prefix = 'blog'
Provided views to display blog posts are pretty basic and you'll probably want to change
them right away. You can change the layout from the default `application` to something else.
config.public_layout = 'blog'
Since ComfyBlog is an engine, it allows you to completely overwrite views. It's enough to
create `app/views/blog/posts/index.html.erb` (could be HAML or whatever you want) and structure
it in any way you want. There's also `show.html.erb` and `_post.html.erb` available.
Pagination is done using either [WillPaginate](https://github.com/mislav/will_paginate) or [Kaminari](https://github.com/amatsuda/kaminari). Add either in your Gemfile.
You can control number of posts per page by adjusting this config:
config.posts_per_page = 10
Posted comments will be sitting in the queue waiting to be published. You can auto publish them
by setting this to `true`:
config.auto_publish_comments = true
You can use Disqus to manage comments by setting the following config:
config.disqus_shortname = 'forum_shortname'
ComfyBlog is released under the [MIT license](https://github.com/comfy/comfy-blog/raw/master/LICENSE)
Copyright 2012 <NAME>, [The Working Group Inc](http://www.twg.ca)
<file_sep>class Admin::Blog::CommentsController < Admin::Blog::BaseController
require "rails_autolink/helpers"
before_filter :load_post, :only => [:index]
before_filter :load_comment, :only => [:destroy, :publish]
def index
@comments = @post ? @post.comments : Blog::Comment.all
end
def destroy
@comment.destroy
end
def publish
@comment.update_attribute(:is_published, true)
end
protected
def load_post
return unless params[:post_id]
@post = Blog::Post.find(params[:post_id])
rescue ActiveRecord::RecordNotFound
flash[:error] = 'Blog Post not found'
redirect_to :action => :index
end
def load_comment
@comment = Blog::Comment.find(params[:id])
rescue ActiveRecord::RecordNotFound
# ... do nothing
end
end<file_sep>class Admin::Blog::TagsController < Admin::Blog::BaseController
before_filter :build_tag, :only => [:new, :create]
before_filter :load_tag, :only => [:edit, :update, :destroy]
def index
@tags = Blog::Tag.order('is_category DESC', :name)
end
def edit
render
end
def new
render
end
def update
@tag.update_attributes!(params[:tag])
flash[:notice] = 'Blog Tag updated'
redirect_to :action => :index
rescue ActiveRecord::RecordInvalid
flash.now[:error] = 'Failed to update Blog Tag'
render :action => :edit
end
def create
@tag.save!
flash[:notice] = 'Blog Tag created'
redirect_to :action => :index
rescue ActiveRecord::RecordInvalid
flash.now[:error] = 'Failed to create Blog Tag'
render :action => :new
end
def destroy
@tag.destroy
flash[:notice] = 'Blog Tag removed'
redirect_to :action => :index
end
protected
def build_tag
@tag = Blog::Tag.new(params[:tag])
end
def load_tag
@tag = Blog::Tag.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:error] = 'Blog Tag not found'
redirect_to :action => :index
end
end
<file_sep>class Blog::Tagging < ActiveRecord::Base
attr_accessible :post
self.table_name = :blog_taggings
# -- Relationships --------------------------------------------------------
belongs_to :post
belongs_to :tag, :counter_cache => true
# -- Callbacks ------------------------------------------------------------
after_destroy :destroy_tag
# -- Scopes ---------------------------------------------------------------
scope :for_tags, includes(:tag).where('blog_tags.is_category' => false)
scope :for_categories, includes(:tag).where('blog_tags.is_category' => true)
protected
def destroy_tag
self.tag.destroy if !self.tag.is_category? && self.tag.taggings.count == 0
end
end
<file_sep>source 'http://rubygems.org'
gem 'rails', '>=3.1.0'
gem 'rails_autolink', '>=1.0.4'
gem 'jquery-rails', '>=1.0.0'
# gem 'will_paginate', '>=3.0.2'
# gem 'kaminari', '>=0.0.0'
group :test do
gem 'sqlite3'
gem 'jeweler'
end<file_sep>require File.expand_path('../test_helper', File.dirname(__FILE__))
class PostTest < ActiveSupport::TestCase
def test_fixtures_validity
Blog::Post.all.each do |post|
assert post.valid?, post.errors.full_messages.to_s
end
end
def test_validation
post = Blog::Post.new
assert post.invalid?
assert_has_errors_on post, [:title, :slug, :content]
end
def test_validation_of_slug_uniqueness
old_post = blog_posts(:default)
old_post.update_attributes!(:published_at => Time.now)
post = Blog::Post.new(:title => old_post.title, :content => 'Test Content')
assert post.invalid?
assert_has_errors_on post, [:slug]
old_post.update_attributes!(:published_at => 1.year.ago)
assert post.valid?
end
def test_creation
assert_difference 'Blog::Post.count' do
post = Blog::Post.create!(
:title => 'Test Post',
:content => 'Test Content'
)
assert_equal 'test-post', post.slug
assert_equal Time.now.year, post.year
assert_equal Time.now.month, post.month
end
end
def test_set_slug
post = Blog::Post.new(:title => 'Test Title')
post.send(:set_slug)
assert_equal 'test-title', post.slug
end
def test_set_date
post = Blog::Post.new
post.send(:set_published_at)
post.send(:set_date)
assert_equal post.published_at.year, post.year
assert_equal post.published_at.month, post.month
end
def test_set_published_at
post = Blog::Post.new
post.send(:set_published_at)
assert post.published_at.present?
end
def test_sync_tags
post = blog_posts(:default)
assert_equal 'tag', post.tag_names
post.tag_names = 'one, two, three'
assert_equal 'one, two, three', post.tag_names
assert_difference ['Blog::Tag.count', 'Blog::Tagging.count'], 2 do
post.save!
post.reload
assert_equal 'one, two, three', post.tag_names
end
end
def test_sync_tags_duplicate
post = blog_posts(:default)
post.tag_names = 'tag, category'
assert_no_difference ['Blog::Tagging.count'] do
post.save!
end
end
def test_sync_categories
post = blog_posts(:default)
assert_equal 1, post.tags.categories.count
assert_difference 'Blog::Tagging.count', -1 do
post.update_attribute(:category_ids, blog_tags(:category).id => 0)
post.reload
assert_equal 0, post.tags.categories.count
end
assert_difference 'Blog::Tagging.count' do
post.update_attribute(:category_ids, blog_tags(:category).id => 1)
post.reload
assert_equal 1, post.tags.categories.count
end
end
def test_destroy
assert_difference ['Blog::Post.count', 'Blog::Comment.count'], -1 do
blog_posts(:default).destroy
end
end
def test_scope_published
post = blog_posts(:default)
assert post.is_published?
assert_equal 1, Blog::Post.published.count
post.update_attribute(:is_published, false)
assert_equal 0, Blog::Post.published.count
end
def test_scope_for_year
assert_equal 1, Blog::Post.for_year(2012).count
assert_equal 0, Blog::Post.for_year(2013).count
end
def test_scope_for_month
assert_equal 1, Blog::Post.for_month(1).count
assert_equal 0, Blog::Post.for_month(2).count
end
def test_scope_tagged_with
assert_equal 1, Blog::Post.tagged_with('tag').count
assert_equal 0, Blog::Post.tagged_with('category').count
assert_equal 0, Blog::Post.tagged_with('invalid').count
end
def test_scope_categorized_as
assert_equal 1, Blog::Post.categorized_as('category').count
assert_equal 0, Blog::Post.categorized_as('tag').count
assert_equal 0, Blog::Post.categorized_as('invalid').count
end
def test_tag_names
assert_equal 'tag', blog_posts(:default).tag_names
end
def test_category_ids
assert_equal ({
blog_tags(:category).id.to_s => '1'
}), blog_posts(:default).category_ids
end
end
<file_sep>class Blog::CommentsController < ApplicationController
def create
@post = Blog::Post.published.find(params[:post_id])
@comment = @post.comments.new(params[:comment])
#add spam blocker code (bot will not know to leave the hidden field blank)
if params[:comment][:validation].blank?
@comment.save!
else
Rails.logger.info "\n\n***** Someone tried to hit me with a bot! (But I'm smarter than that.) *****\n\n"
end
respond_to do |f|
f.html do
if params[:comment][:validation].blank?
flash[:notice] = 'Comment created'
else
flash[:notice] = 'Comment aborted'
end
redirect_to dated_blog_post_path(@post.year, @post.month, @post.slug)
end
f.js
end
rescue ActiveRecord::RecordNotFound
respond_to do |f|
f.html do
flash[:error] = 'Blog Post not found'
redirect_to blog_posts_path
end
f.js do
render :nothing => true, :status => 404
end
end
rescue ActiveRecord::RecordInvalid
respond_to do |f|
f.html do
render 'blog/posts/show'
end
f.js
end
end
end<file_sep>require File.expand_path('../../../test_helper', File.dirname(__FILE__))
class Admin::Blog::TagsControllerTest < ActionController::TestCase
def test_get_index
get :index
assert_response :success
assert_template :index
assert assigns(:tags)
end
def test_get_edit
get :edit, :id => blog_tags(:tag)
assert_response :success
assert_template :edit
assert assigns(:tag)
end
def test_get_new
get :new
assert_response :success
assert_template :new
assert assigns(:tag)
end
def test_update
tag = blog_tags(:tag)
assert_no_difference 'Blog::Tag.count' do
put :update, :id => tag, :tag => {
:name => 'Updated'
}
assert_response :redirect
assert_redirected_to :action => :index
tag.reload
assert_equal 'Updated', tag.name
end
end
def test_update_failure
tag = blog_tags(:tag)
assert_no_difference 'Blog::Tag.count' do
put :update, :id => tag, :tag => {
:name => 'Duplicate' # Notice case
}
assert_response :success
assert_template :edit
assert_equal 'Failed to update Blog Tag', flash[:error]
tag.reload
assert_equal 'tag', tag.name
end
end
def test_creation
assert_difference 'Blog::Tag.count' do
post :create, :tag => {
:name => 'test'
}
assert_response :redirect
assert_redirected_to :action => :index
assert assigns(:tag).valid?
assert_equal 'Blog Tag created', flash[:notice]
end
end
def test_creation_failure
assert_no_difference 'Blog::Tag.count' do
post :create, :tag => {
:name => 'Duplicate' # Notice case
}
assert_response :success
assert_template :new
assert assigns(:tag).invalid?
assert_equal 'Failed to create Blog Tag', flash[:error]
end
end
def test_destroy
assert_difference 'Blog::Tag.count', -1 do
delete :destroy, :id => blog_tags(:tag)
assert_response :redirect
assert_redirected_to :action => :index
assert_equal 'Blog Tag removed', flash[:notice]
end
end
end
<file_sep>require File.expand_path('../test_helper', File.dirname(__FILE__))
class RoutingTest < ActionDispatch::IntegrationTest
def setup
reset_config
Rails.application.reload_routes!
end
def test_admin_route_prefix
ComfyBlog.config.admin_route_prefix = 'custom-admin'
Rails.application.reload_routes!
get '/custom-admin/blog/posts'
assert_response :success
end
def test_public_route_prefix
ComfyBlog.config.public_route_prefix = 'blog'
Rails.application.reload_routes!
get '/blog'
assert_response :success
end
end<file_sep>class Blog::Post < ActiveRecord::Base
attr_accessible :title, :slug, :author, :tag_names, :excerpt, :content, :published_at, :is_published, :category_ids
self.table_name = :blog_posts
# -- Attributes -----------------------------------------------------------
attr_accessor :tag_names,
:category_ids
# -- Relationships --------------------------------------------------------
has_many :comments, :dependent => :destroy
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
# -- Validations ----------------------------------------------------------
validates :title, :slug, :year, :month, :content,
:presence => true
validates :slug,
:uniqueness => { :scope => [:year, :month] }
# -- Scopes ---------------------------------------------------------------
default_scope order('published_at DESC')
scope :published, where(:is_published => true)
scope :for_year, lambda { |year|
where(:year => year)
}
scope :for_month, lambda { |month|
where(:month => month)
}
scope :tagged_with, lambda { |tag|
joins(:tags).where('blog_tags.name' => tag, 'blog_tags.is_category' => false)
}
scope :categorized_as, lambda { |tag|
joins(:tags).where('blog_tags.name' => tag, 'blog_tags.is_category' => true)
}
# -- Callbacks ------------------------------------------------------------
before_validation :set_slug,
:set_published_at,
:set_date
after_save :sync_tags,
:sync_categories
# -- Instance Methods -----------------------------------------------------
def tag_names(reload = false)
@tag_names = nil if reload
@tag_names ||= self.tags.tags.collect(&:name).join(', ')
end
def category_ids
@category_ids ||= self.tags.categories.inject({}){|h, c| h[c.id.to_s] = '1'; h}
end
protected
def set_slug
self.slug ||= self.title.to_s.slugify
end
def set_date
self.year = self.published_at.year
self.month = self.published_at.month
end
def set_published_at
self.published_at ||= Time.zone.now
end
def sync_tags
return unless tag_names
self.taggings.for_tags.destroy_all
self.tag_names.split(',').map{ |t| t.strip }.uniq.each do |tag_name|
self.tags << Blog::Tag.find_or_create_by_name(tag_name) rescue nil
end
end
def sync_categories
self.category_ids.each do |category_id, flag|
case flag.to_i
when 1
if category = Blog::Tag.categories.find_by_id(category_id)
category.taggings.create(:post => self) rescue nil
end
when 0
self.taggings.for_categories.where(:tag_id => category_id).destroy_all
end
end
end
end<file_sep>module ComfyBlog::Routing
def self.admin
Rails.application.routes.draw do
namespace :admin, :path => ComfyBlog.config.admin_route_prefix do
namespace :blog do
resources :posts, :except => [:show] do
unless ComfyBlog.disqus_enabled?
resources :comments, :only => [:index]
end
end
unless ComfyBlog.disqus_enabled?
resources :comments, :only => [:index, :destroy] do
put :publish, :on => :member
end
end
resources :tags, :except => [:show]
end
end unless ComfyBlog.config.admin_route_prefix.blank?
end
end
def self.content
Rails.application.routes.draw do
scope ComfyBlog.config.public_route_prefix, :module => :blog do
get '/' => 'posts#index', :as => :blog_posts
get 'tag/:tag' => 'posts#index', :as => :tagged_blog_posts
get 'category/:category' => 'posts#index', :as => :categorized_blog_posts
with_options :constraints => { :year => /\d{4}/, :month => /\d{1,2}/ } do |o|
o.get ':year' => 'posts#index', :as => :year_blog_posts
o.get ':year/:month' => 'posts#index', :as => :month_blog_posts
o.get ':year/:month/:slug' => 'posts#show', :as => :dated_blog_post
end
unless ComfyBlog.disqus_enabled?
post ':post_id/comments' => 'comments#create', :as => :blog_post_comments
end
get ':id' => 'posts#show', :as => :blog_post
end
end
end
end
<file_sep>require File.expand_path('../../test_helper', File.dirname(__FILE__))
class Blog::CommentsControllerTest < ActionController::TestCase
def test_creation
p = blog_posts(:default)
assert_difference 'Blog::Comment.count' do
post :create, :post_id => p, :comment => {
:author => 'Test',
:email => '<EMAIL>',
:content => 'Test Content'
}
assert_response :redirect
assert_redirected_to dated_blog_post_path(p.year, p.month, p.slug)
assert_equal 'Comment created', flash[:notice]
comment = Blog::Comment.last
assert_equal 'Test', comment.author
assert_equal p, comment.post
end
end
def test_creation_failure
p = blog_posts(:default)
assert_no_difference 'Blog::Comment.count' do
post :create, :post_id => p, :comment => { }
assert_response :success
assert_template :show
end
end
def test_creation_failure_invalid_post
assert_no_difference 'Blog::Comment.count' do
post :create, :post_id => 'invalid', :comment => { }
assert_response :redirect
assert_redirected_to blog_posts_path
assert_equal 'Blog Post not found', flash[:error]
end
end
def test_creation_xhr
p = blog_posts(:default)
assert_difference 'Blog::Comment.count' do
xhr :post, :create, :post_id => p, :comment => {
:author => 'Test',
:email => '<EMAIL>',
:content => 'Test Content'
}
assert_response :success
assert_template :create
comment = Blog::Comment.last
assert_equal 'Test', comment.author
assert_equal p, comment.post
end
end
def test_creation_xhr_failure
p = blog_posts(:default)
assert_no_difference 'Blog::Comment.count' do
xhr :post, :create, :post_id => p, :comment => { }
assert_response :success
assert_template :create
end
end
def test_creation_xhr_failure_invalid_post
assert_no_difference 'Blog::Comment.count' do
xhr :post, :create, :post_id => 'invalid', :comment => { }
assert_response 404
end
end
end<file_sep># Loading engine only if this is not a standalone installation
unless defined? ComfyBlog::Application
require File.expand_path('comfy_blog/engine', File.dirname(__FILE__))
end
[ 'comfy_blog/core_ext/string',
'comfy_blog/configuration',
'comfy_blog/routing',
'comfy_blog/form_builder'
].each do |path|
require File.expand_path(path, File.dirname(__FILE__))
end
module ComfyBlog
class << self
def configure
yield configuration
end
def configuration
@configuration ||= Configuration.new
end
alias :config :configuration
def disqus_enabled?
self.config.disqus_shortname.present?
end
end
end<file_sep>defined?(ComfyBlog::Application) && ComfyBlog::Application.routes.draw do
ComfyBlog::Routing.admin
ComfyBlog::Routing.content
end
<file_sep>require File.expand_path('../../../test_helper', File.dirname(__FILE__))
class Admin::Blog::CommentsControllerTest < ActionController::TestCase
def test_get_index
get :index
assert_response :success
assert_template :index
assert assigns(:comments)
assert !assigns(:post)
end
def test_get_index_for_post
get :index, :post_id => blog_posts(:default)
assert_response :success
assert_template :index
assert assigns(:post)
assert assigns(:comments)
end
def test_publish
comment = blog_comments(:default)
comment.update_attribute(:is_published, false)
xhr :put, :publish, :id => comment
assert_response :success
comment.reload
assert comment.is_published
end
def test_destroy
assert_difference 'Blog::Comment.count', -1 do
xhr :delete, :destroy, :id => blog_comments(:default)
assert_response :success
end
end
end<file_sep>require File.expand_path('../test_helper', File.dirname(__FILE__))
class TagTest < ActiveSupport::TestCase
def test_fixtures_validity
Blog::Tag.all.each do |tag|
assert tag.valid?, tag.errors.to_s
end
end
def test_validation
old_tag = blog_tags(:tag)
tag = Blog::Tag.new(:name => old_tag.name)
assert tag.invalid?
assert_has_errors_on tag, [:name]
end
def test_strip_name
tag = Blog::Tag.new(:name => ' Test Tag ')
assert tag.valid?
assert_equal 'Test Tag', tag.name
end
def test_creation
assert_difference 'Blog::Tag.count' do
tag = Blog::Tag.create(:name => 'Test Tag')
end
end
def test_destroy
assert_difference ['Blog::Tag.count', 'Blog::Tagging.count'], -1 do
blog_tags(:tag).destroy
end
end
def test_scopes
assert_equal 2, Blog::Tag.tags.count
assert_equal blog_tags(:tag), Blog::Tag.tags.first
assert_equal blog_tags(:duplicate), Blog::Tag.tags.last
assert_equal 1, Blog::Tag.categories.count
assert_equal blog_tags(:category), Blog::Tag.categories.first
end
end
<file_sep>class Admin::Blog::PostsController < Admin::Blog::BaseController
before_filter :build_post, :only => [:new, :create]
before_filter :load_post, :only => [:edit, :update, :destroy]
def index
@posts = if defined? WillPaginate
Blog::Post.paginate :page => params[:page]
elsif defined? Kaminari
Blog::Post.page params[:page]
else
Blog::Post.all
end
end
def new
render
end
def create
@post.save!
flash[:notice] = 'Blog Post created'
redirect_to :action => :edit, :id => @post
rescue ActiveRecord::RecordInvalid
flash.now[:error] = 'Failed to create Blog Post'
render :action => :new
end
def edit
render
end
def update
@post.update_attributes!(params[:post])
flash[:notice] = 'Blog Post updated'
redirect_to :action => :edit, :id => @post
rescue ActiveRecord::RecordInvalid
flash.now[:error] = 'Failed to update Blog Post'
render :action => :edit
end
def destroy
@post.destroy
flash[:notice] = 'Blog Post removed'
redirect_to :action => :index
end
protected
def load_post
@post = Blog::Post.find(params[:id])
rescue ActiveRecord::RecordNotFound
flash[:error] = 'Blog Post not found'
redirect_to :action => :index
end
def build_post
@post = Blog::Post.new(params[:post])
end
end<file_sep>defined?(ComfyBlog::Application) && ComfyBlog::Application.configure do
ComfyBlog::Application.config.secret_token = '<KEY>'
end<file_sep>class Blog::PostsController < ApplicationController
layout ComfyBlog.config.public_layout
def index
scope = if params[:tag]
Blog::Post.published.tagged_with(params[:tag])
elsif params[:category]
Blog::Post.published.categorized_as(params[:category])
elsif params[:year]
scope = Blog::Post.published.for_year(params[:year])
params[:month] ? scope.for_month(params[:month]) : scope
else
Blog::Post.published
end
respond_to do |f|
f.html do
@posts = if defined? WillPaginate
scope.paginate :per_page => ComfyBlog.config.posts_per_page, :page => params[:page]
elsif defined? Kaminari
scope.page(params[:page]).per(ComfyBlog.config.posts_per_page)
else
scope
end
end
f.rss do
@posts = scope.limit(ComfyBlog.config.posts_per_page)
end
end
end
def show
@post = if params[:slug] && params[:year] && params[:month]
Blog::Post.published.find_by_year_and_month_and_slug!(params[:year], params[:month], params[:slug])
else
Blog::Post.published.find(params[:id])
end
rescue ActiveRecord::RecordNotFound
if defined? ComfortableMexicanSofa
render :cms_page => '/404', :status => 404
else
render :text => 'Post not found', :status => 404
end
end
end
<file_sep>class Blog::Tag < ActiveRecord::Base
attr_accessible :name, :is_category
self.table_name = :blog_tags
# -- Relationships --------------------------------------------------------
has_many :taggings, :dependent => :destroy
has_many :posts, :through => :taggings
# -- Validations ----------------------------------------------------------
validates_uniqueness_of :name, :case_sensitive => false
# -- Callbacks ------------------------------------------------------------
before_validation :strip_name
# -- Scopes ---------------------------------------------------------------
scope :categories, where(:is_category => true)
scope :tags, where(:is_category => false)
protected
def strip_name
self.name = self.name.strip if self.name
end
end
<file_sep>module ComfyBlog
class Configuration
# Title of your Blog
attr_accessor :title
# What is your blog all about
attr_accessor :description
# Default url to access admin area is http://yourhost/cms-admin/
# You can change 'cms-admin' to 'admin', for example.
attr_accessor :admin_route_prefix
# Prefix of the url where blog posts are served from. If you wish to
# serve posts from /blog change this setting to 'blog'. Default is blank.
attr_accessor :public_route_prefix
# Controller that should be used for admin area
attr_accessor :admin_controller
# Form builder
attr_accessor :form_builder
# Layout used for public posts/comments
attr_accessor :public_layout
# Number of posts per page. Default is 10
attr_accessor :posts_per_page
# Comments can be automatically approved/published by changing this setting
# Default is false.
attr_accessor :auto_publish_comments
# Comments can be fully handled by Disqus. Set this config to use it.
attr_accessor :disqus_shortname
# Configuration defaults
def initialize
@title = 'ComfyBlog'
@description = 'A Simple Blog'
@admin_route_prefix = 'admin'
@public_route_prefix = ''
@admin_controller = 'ApplicationController'
@form_builder = 'ComfyBlog::FormBuilder'
@public_layout = 'application'
@posts_per_page = 10
@auto_publish_comments = false
@disqus_shortname = nil
end
end
end
|
5d30239b84459c524efbb2c100280d566ee3fdf3
|
[
"Markdown",
"Ruby"
] | 29
|
Ruby
|
CabForward/comfy-blog
|
a48283f1feabbfa935e197482ffca7c15b2d79ed
|
88cd02cda2c05f93da9a920f6b71218f52fef7af
|
refs/heads/master
|
<repo_name>wilkerjnoleto/sorteflashapp2<file_sep>/app/src/main/java/com/sorteflash/sorteflashapp/ListPedidoActivity.java
package com.sorteflash.sorteflashapp;
import android.content.Intent;
import android.os.Bundle;
import android.os.StrictMode;
import android.support.v7.app.AppCompatActivity;
import android.widget.ListView;
import android.widget.TextView;
import java.util.List;
public class ListPedidoActivity extends AppCompatActivity {
private ListView listView;
private TextView nomeUserLogado;
private UsuarioLogar usuarioLogar = new UsuarioLogar();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().hide();
setContentView(R.layout.activity_listpedidos);
if (android.os.Build.VERSION.SDK_INT > 9) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
}
Intent interacao = getIntent();
Bundle receber = interacao.getExtras();
usuarioLogar.setNome(receber.getString("nomeusuario"));
usuarioLogar.setTutorId(receber.getString("tutorId"));
nomeUserLogado = (TextView) findViewById(R.id.textView2);
nomeUserLogado.setText("Usuário: " + usuarioLogar.getNome());
listView = findViewById(R.id.list);
List<Pedido> listaDePedidos = new RotaPedidos().listaPedidoPorCambista(usuarioLogar.getTutorId());
LayouListaPedidos adapter = new LayouListaPedidos(listaDePedidos,this);
listView.setAdapter(adapter);
}
}
<file_sep>/app/src/main/java/com/sorteflash/sorteflashapp/LayouListaClientes.java
package com.sorteflash.sorteflashapp;
import android.app.Activity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import org.w3c.dom.Text;
import java.util.List;
public class LayouListaClientes extends BaseAdapter {
private final List<Clientes> listaClientes;
private final Activity act;
public LayouListaClientes(List<Clientes> listaClientes, Activity act) {
this.listaClientes = listaClientes;
this.act = act;
}
@Override public int getCount(){return listaClientes.size();}
@Override public Object getItem(int position){return listaClientes.get(position);}
@Override public long getItemId(int position){return 0;}
@Override public View getView(int position, View convertView, ViewGroup parent){
View view = act.getLayoutInflater().inflate(R.layout.lista_clientes_personalizada,parent,false);
Clientes clientes = listaClientes.get(position);
TextView nome = (TextView) view.findViewById(R.id.lista_nome);
TextView descricao = (TextView) view.findViewById(R.id.lista_descricao);
nome.setText("Nome: " + clientes.getNome());
descricao.setText("Cid.:"+clientes.getCidade() + " - Tel." + clientes.getTelefone());
return view;
}
}
<file_sep>/app/src/main/java/com/sorteflash/sorteflashapp/RotaClientes.java
package com.sorteflash.sorteflashapp;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.ResponseBody;
public class RotaClientes {
public List<Clientes> listaClientesPorCambista(String tutorId) {
List<Clientes> resultado = new ArrayList<>();
try {
//rota de teste - http://192.168.127.12:5000/api
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"tutorId\" : \""+tutorId+"\"}");
Request request = new Request.Builder()
.url("http://192.168.127.12:5000/api/usuarios/listar-por-tutor")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("Cookie", "session=eyJmbGFzaCI6e319; session.sig=MwT6aSgX1rSKg7mAgoHLtyJoI2k")
.build();
Response response = client.newCall(request).execute();
//System.out.println(response.body().string());
String jsonData = response.body().string();
JSONArray objetoJSON = (JSONArray) JSONValue.parseWithException(jsonData.toString());
if (objetoJSON != null) {
for (Iterator it = objetoJSON.iterator(); it.hasNext();) {
JSONObject obj = (JSONObject) it.next();
Clientes clientes = new Clientes();
clientes.set_id(obj.get("_id").toString());
clientes.setBairro(obj.get("bairro").toString());
clientes.setCidade(obj.get("cidade").toString());
try{clientes.setCpf(obj.get("cpf").toString());}catch(Exception e){}
clientes.setEndereco(obj.get("endereco").toString());
clientes.setEstado(obj.get("estado").toString());
clientes.setNome(obj.get("nome").toString());
clientes.setPerfil(obj.get("perfil").toString());
clientes.setTelefone(obj.get("telefone").toString());
clientes.setTutorId(obj.get("tutorId").toString());
resultado.add(clientes);
}
}
}catch(Exception e){
e.printStackTrace();
}
return resultado;
}
/* public static void main(String args[]) {
RotaClientes rotaClientes = new RotaClientes();
System.out.println(rotaClientes.listaClientesPorCambista(""));
}*/
}
<file_sep>/app/src/main/java/com/sorteflash/sorteflashapp/RotaPedidos.java
package com.sorteflash.sorteflashapp;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class RotaPedidos {
public List<Pedido> listaPedidoPorCambista(String tutorId) {
List<Pedido> resultado = new ArrayList<>();
try {
//rota de teste - http://192.168.3.11:5000/api
OkHttpClient client = new OkHttpClient();
MediaType mediaType = MediaType.parse("application/json");
RequestBody body = RequestBody.create(mediaType, "{\"tutorId\" : \""+tutorId+"\"}");
Request request = new Request.Builder()
.url("http://192.168.3.11:5000/api/pedidos/listar-pedidos")
.post(body)
.addHeader("content-type", "application/json")
.addHeader("Cookie", "session=eyJmbGFzaCI6e319; session.sig=MwT6aSgX1rSKg7mAgoHLtyJoI2k")
.build();
Response response = client.newCall(request).execute();
String jsonData = response.body().string();
JSONArray objetoJSON = (JSONArray) JSONValue.parseWithException(jsonData.toString());
if (objetoJSON != null) {
for (Iterator it = objetoJSON.iterator(); it.hasNext();) {
JSONObject obj = (JSONObject) it.next();
Pedido pedido = new Pedido();
pedido.setCodigo(obj.get("codigo").toString());
pedido.setData(obj.get("data").toString());
JSONObject contatos = (JSONObject) obj.get("clienteId");
pedido.setCliente(contatos.get("nome").toString());
resultado.add(pedido);
}
}
}catch(Exception e){
e.printStackTrace();
}
return resultado;
}
/*
public static void main(String args[]) {
RotaPedidos rotaClientes = new RotaPedidos();
System.out.println(rotaClientes.listaPedidoPorCambista("5f7f1d1869483d43b788df30"));
}
*/
}
|
641de92ea2a91bd97ce5f883a285eb7672909135
|
[
"Java"
] | 4
|
Java
|
wilkerjnoleto/sorteflashapp2
|
b1ea9d81954e4a68b86d5c62166b1e44871df778
|
1480cfb207f45a9748e14e91995b6b6f18b04fd8
|
refs/heads/master
|
<repo_name>zorksylar/mem-bench<file_sep>/base/memory_utils.cpp
#include "memory_utils.hpp"
// for OSX
#ifndef MAP_ANONYMOUS
# define MAP_ANONYMOUS MAP_ANON
#endif
namespace base {
void *map_anon_memory(unsigned long size, bool mlocked,
const char *opeartion, bool zero) {
void *space = mmap(NULL, size, PROT_READ|PROT_WRITE,
MAP_ANONYMOUS|MAP_SHARED, -1, 0);
verify(space != MAP_FAILED);
if (mlocked) {
verify(mlock(space, size) < 0);
}
if (zero) {
memset(space, 0, size);
}
return space;
}
} // namespace base
<file_sep>/core/numa_utils.hpp
#include <numa.h>
#include <sched.h>
#include "base/all.hpp"
using namespace base;
void * numa_alloc_node(size_t bytes, int node) {
void *p = numa_alloc_onnode(bytes, node);
verify(p != NULL);
// force to alloc physical memory on this region
memset(p, 0, bytes);
return p;
}
void * numa_alloc_cpu(size_t bytes, int cpu) {
int node = numa_node_of_cpu(cpu);
return numa_alloc_node(bytes, node);
}
void pin_to_node(int cpu) {
int node = numa_node_of_cpu(cpu);
int ret = numa_run_on_node(node);
verify(ret == 0);
ret = sched_yield();
verify(ret == 0);
}
<file_sep>/base/memory_utils.hpp
#pragma once
#include <sys/types.h>
#include <unistd.h>
#include <sys/mman.h>
#include <string.h>
#include "basetypes.hpp"
namespace base {
/* malloc extreme lagge memory */
void *map_anon_memory(unsigned long size, bool mlocked, const char *operation, bool zero = false);
} //namespace base
<file_sep>/Makefile
# dirs
SRC_DIR = base
BLD_DIR = build
OBJ_DIR = $(BLD_DIR)/objs
CORE_DIR = core
#check os
OS := $(shell uname)
ifeq ($(OS), Darwin)
CXX?=clang++
else
CXX?=g++
endif
#cxx
CXXFLAGS?= -O3 -DNDEBUG -Wall -Wno-unused-function
LDFLAGS?=
CXX11FLAGS?= -std=c++11
ifeq ($(OS), Darwin)
CXX11FLAGS += -stdlib=libc++
endif
CXXFLAGS+= $(CXX11FLAGS)
#env
EXTRA_INCLUDES=-I. -I/home/zork/bin/boost_1_55_0/include -I./$(CORE_DIR)
SYSLIBS=-lpthread -lboost_system -lboost_thread -lnuma
EXTRA_LIBS=-L./$(BLD_DIR) -L/home/zork/bin/boost_1_55_0/lib
#SYS_LIBS=
#targets
CPP_FILES= $(wildcard $(SRC_DIR)/*.cpp)
OBJ_FILES=$(addprefix $(OBJ_DIR)/, $(notdir $(CPP_FILES:.cpp=.o)))
CORE_FILES= $(wildcard $(CORE_DIR)/*.cpp)
CORE_OBJS = $(addprefix $(OBJ_DIR)/, $(notdir $(CORE_FILES:.cpp=.o)))
#make
OUT_LIBA=$(BLD_DIR)/libbase.a
OUT_BIN=$(BLD_DIR)/bench
all : $(OUT_LIBA) $(OUT_BIN)
-include $(OBJ_FILES:.o=.d)
MKDIR_OBJ :
mkdir -p $(OBJ_DIR)
$(OBJ_FILES) : $(OBJ_DIR)/%.o : $(SRC_DIR)/%.cpp | MKDIR_OBJ
$(CXX) $(CXXFLAGS) $(EXTRA_INCLUDES) -c -o $@ $<
$(CXX) $(CXX11FLAGS) -MM -MT '$(OBJ_DIR)/$*.o' $< > $(@:.o=.d)
$(OUT_LIBA) : $(OBJ_FILES)
ar rcs $@ $^
$(CORE_OBJS) : $(OBJ_DIR)/%.o : $(CORE_DIR)/%.cpp | MKDIR_OBJ
$(CXX) $(CXXFLAGS) $(EXTRA_INCLUDES) -c -o $@ $<
$(CXX) $(CXX11FLAGS) $(EXTRA_INCLUDES) -MM -MT '$(OBJ_DIR)/$*.o' $< > $(@:.o=.d)
$(OUT_BIN) : $(CORE_OBJS) $(OUT_LIBA)
$(CXX) $(CXXFLAGS) $(EXTRA_INCLUDES) -o $@ $(CORE_OBJS) $(OUT_LIBA) $(EXTRA_LIBS) $(SYSLIBS) $(LDFLAGS)
.PHONY:
clean:
rm -rf build/
<file_sep>/core/bench.cpp
#include <string.h>
#include "base/all.hpp"
#include "numa_utils.hpp"
#include <boost/thread.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/thread/barrier.hpp>
#define MIN_BUFFER_SIZE (1024 * 1024 * 1024)
#define BUFFER_SIZE (1024 * 1024 * 1024 + 4096)
unsigned long buffer_items = 1;
#define LCG_NEXT(_n, mask) ((1103515245*(_n) + 12345) & mask)
using namespace base;
static double convert(double mbps) {
double factor = (1 << 20) / ((double)1000000.0);
return factor * mbps;
}
enum AccessPattern{
SEQ,
RAND,
};
class mem_speed {
int cpu;
//pthread_barrier_t *thread_sync;
boost::barrier *thread_sync;
unsigned char *local_buffer;
unsigned char *remote_buffer;
unsigned long chunk_size;
enum AccessPattern ap;
public :
mem_speed(int cpu, unsigned char *local_buffer,
unsigned char *remote_buffer, unsigned long chunk_size,
boost::barrier *thread_sync, enum AccessPattern ap) :
cpu(cpu), local_buffer(local_buffer),
remote_buffer(remote_buffer), chunk_size(chunk_size),
thread_sync(thread_sync), ap(ap)
{
pin_to_node(cpu);
}
void do_seq_work() {
unsigned char tmp[chunk_size];
// seq local read
//int rc = pthread_barrier_wait(thread_sync);
//verify(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) ;
thread_sync->wait();
Timer timer;
timer.start();
for (unsigned long i = 0;i < BUFFER_SIZE;i += chunk_size) {
memcpy(tmp, local_buffer + i, chunk_size);
}
timer.stop();
double mbps = (double)(BUFFER_SIZE) / timer.elapsed_usec();
LOG_INFO << "MEM_LOCAL_READ_SPPED " << convert(mbps) << "MB/s" ;
// seq remote read
timer.reset();
timer.start();
for (unsigned long i = 0;i < BUFFER_SIZE;i += chunk_size) {
memcpy(tmp, remote_buffer + i, chunk_size);
}
timer.stop();
mbps = (double)(BUFFER_SIZE) / timer.elapsed_usec();
LOG_INFO << "MEM_REMOTE_READ_SPPED " << convert(mbps) << "MB/s" ;
// seq local write
timer.reset();
timer.start();
for (unsigned long i = 0;i < BUFFER_SIZE;i += chunk_size) {
memcpy(local_buffer + i, tmp, chunk_size);
}
timer.stop();
mbps = (double)(BUFFER_SIZE) / timer.elapsed_usec();
LOG_INFO << "MEM_LOCAL_WRITE_SPPED " << convert(mbps) << "MB/s" ;
// seq remote write
timer.reset();
timer.start();
for (unsigned long i = 0;i < BUFFER_SIZE;i += chunk_size) {
memcpy(remote_buffer + i, tmp, chunk_size);
}
timer.stop();
mbps = (double)(BUFFER_SIZE) / timer.elapsed_usec();
LOG_INFO << "MEM_REMOTE_WRITE_SPPED " << convert(mbps) << "MB/s" ;
}
void do_rand_work() {
unsigned char tmp[chunk_size];
const unsigned long mask = buffer_items - 1;
//int rc = pthread_barrier_wait(thread_sync);
//verify(rc != 0 && rc != PTHREAD_BARRIER_SERIAL_THREAD) ;
thread_sync->wait();
Timer timer;
// rand local read
timer.start();
for (unsigned long i = 0, j = 0;i < buffer_items; i++) {
memcpy(tmp, local_buffer + j * chunk_size, chunk_size);
j = LCG_NEXT(j, mask);
}
timer.stop();
double mbps = ((double)buffer_items * chunk_size) / timer.elapsed_usec();
LOG_INFO << "MEM_LOCAL_READ_SPEED " << convert(mbps) << "MB/s";
// rand remote read
timer.reset();
timer.start();
for (unsigned long i = 0, j = 0;i < buffer_items; i++) {
memcpy(tmp, remote_buffer + j * chunk_size, chunk_size);
j = LCG_NEXT(j, mask);
}
timer.stop();
mbps = ((double)buffer_items * chunk_size) / timer.elapsed_usec();
LOG_INFO << "MEM_REMOTE_READ_SPEED " << convert(mbps) << "MB/s";
// rand local write
timer.reset();
timer.start();
for (unsigned long i = 0, j = 0;i < buffer_items; i++) {
memcpy(local_buffer + j * chunk_size, tmp, chunk_size);
j = LCG_NEXT(j, mask);
}
timer.stop();
mbps = ((double)buffer_items * chunk_size) / timer.elapsed_usec();
LOG_INFO << "MEM_LOCAL_WRITE_SPEED " << convert(mbps) << "MB/s";
// rand remote write
timer.reset();
timer.start();
for (unsigned long i = 0, j = 0;i < buffer_items; i++) {
memcpy(remote_buffer + j * chunk_size, tmp, chunk_size);
j = LCG_NEXT(j, mask);
}
timer.stop();
mbps = ((double)buffer_items * chunk_size) / timer.elapsed_usec();
LOG_INFO << "MEM_REMOTE_WRITE_SPEED " << convert(mbps) << "MB/s";
}
void operator() () {
if (ap == SEQ) {
do_seq_work();
} else if (ap == RAND) {
do_rand_work();
}
}
};
int main(int argc, char **argv) {
// check numa
if (numa_available() < 0) {
std::cerr << "numa not available" << std::endl;
return 1;
}
numa_set_strict(1);
int ncpus = numa_num_task_cpus();
verify(ncpus >= 1);
LOG_INFO << "ncpus : " << ncpus ;
int nnodes = numa_num_configured_nodes();
verify(nnodes >= 1);
LOG_INFO << "nnodes : " << nnodes;
int local_node = 0, remote_node = 1;
int local_cpu = 1;
unsigned long threads, chunk_size;
enum AccessPattern ap;
if (argc < 4) {
std::cerr << "Usage " << argv[0] << " chunk_size threads ap " << std::endl;
std::cerr << " ap : seq ,rand " << std::endl;
exit(-1);
}
chunk_size = atol(argv[1]);
threads = atol(argv[2]);
if (strcmp("seq", argv[3]) == 0) {
ap = SEQ;
} else if (strcmp("rand", argv[3]) == 0) {
ap = RAND;
} else {
std::cerr << " ap shold be seq or rand " << std::endl;
exit(-1);
}
//pthread_t thread_array [threads];
boost::thread ** thread_array = new boost::thread * [threads];
mem_speed **obj = new mem_speed *[threads];
//pthread_barrier_t thread_sync;
//verify(pthread_barrier_init(&thread_sync, NULL, threads));
boost::barrier * thread_sync = new boost::barrier(threads);
unsigned long alloc_bytes = BUFFER_SIZE;
if ( ap == RAND ) {
while (buffer_items * chunk_size < MIN_BUFFER_SIZE ) {
buffer_items = buffer_items * 2;
}
alloc_bytes = buffer_items * chunk_size;
}
for (unsigned long i = 0;i < threads; i++) {
// allocate local buffer and remote buffer
unsigned char *l_buffer = (unsigned char *)numa_alloc_node(alloc_bytes, local_node);
unsigned char *r_buffer = (unsigned char *)numa_alloc_node(alloc_bytes, remote_node);
//obj[i] = new mem_speed(local_cpu, l_buffer, r_buffer, chunk_size, &thread_sync, ap);
obj[i] = new mem_speed(local_cpu, l_buffer, r_buffer, chunk_size, thread_sync, ap);
//Pthread_create(thread_array[i], NULL, std::ref(*obj[i]), NULL);
thread_array[i] = new boost::thread(boost::ref(*obj[i]));
}
for (unsigned long i = 0;i < threads; i++ ) {
//Pthread_join(thread_array[i], NULL);
thread_array[i]->join();
}
return 0;
}
|
b85752ea92c7a5811abcca76010589219cd689f5
|
[
"Makefile",
"C++"
] | 5
|
C++
|
zorksylar/mem-bench
|
3d18e58f1bcb6a97e6e9e9fc4311b899a6f1c4cc
|
3c3e524c974cf0779902dfd5455cebcb5353f68f
|
refs/heads/main
|
<file_sep>package mavenBank;
import Entities.Customer;
import Entities.SavingsAccount;
import mavenBank.DataStore.CustomerRepo;
import mavenBank.DataStore.services.BankService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import static org.junit.jupiter.api.Assertions.*;
public class AccountTest {
SavingsAccount joshuaAccount;
Customer joshua;
@BeforeEach
void setUp () {
joshuaAccount = new SavingsAccount();
joshua = new Customer();
}
@Test
void openAccount(){
joshua.setBVN(BankService.generateBVN());
joshua.setFirstName("Dome");
joshua.setSurname("joshua");
joshua.setEmail("<EMAIL>");
joshua.setPhone("08183563309");
joshua.setPassword("<PASSWORD>");
joshuaAccount.setAccountNumber(BankService.generateAccountNumber());
joshuaAccount.setBalance( new BigDecimal(5000));
joshua.getAccounts().add(joshuaAccount);
assertTrue(joshua.getAccounts().contains(joshuaAccount));
assertFalse(CustomerRepo.getCustomers().isEmpty());
}
}
<file_sep>package mavenBank.engines;
import Entities.Account;
import Entities.Customer;
import mavenBank.Exceptions.MavenBankException;
import mavenBank.Exceptions.MavenBankLoanException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
public class LoanEngineByRelationLength implements LoanEngine{
@Override
public BigDecimal calculateAmountAutoApprove(Customer customer, Account accountSeekingLoan) throws MavenBankException {
validateLoanRequest(customer, accountSeekingLoan);
//calculate loan amount
BigDecimal oneMonthPercentage = BigDecimal.valueOf(0.00);
BigDecimal fiveMonthPercentage = BigDecimal.valueOf(0.02);
BigDecimal sixMonthPercentage = BigDecimal.valueOf(0.04);
BigDecimal twelveMonthPercentage = BigDecimal.valueOf(0.06);
BigDecimal twentyThreeMonthPercentage = BigDecimal.valueOf(0.08);
BigDecimal twentyFourMonthPercentage = BigDecimal.valueOf(0.1);
long period = ChronoUnit.MONTHS.between(customer.getRelationshipStartDate(), LocalDateTime.now());
BigDecimal totalCustomerBalance = BigDecimal.ZERO;
if (customer.getAccounts().size() > BigDecimal.ONE.intValue()) {
for (Account customerAccount : customer.getAccounts()) {
totalCustomerBalance = totalCustomerBalance.add(customerAccount.getBalance());
}
}
BigDecimal loanAmountApproveAutomatically;
if ( period <= 2 && period > 0){
loanAmountApproveAutomatically = totalCustomerBalance.multiply(oneMonthPercentage);
}else if ( period > 2 && period <= 5){
loanAmountApproveAutomatically = totalCustomerBalance.multiply(fiveMonthPercentage);
}else if(period > 5 && period <=11 ){
loanAmountApproveAutomatically = totalCustomerBalance.multiply(sixMonthPercentage);
}else if(period > 11 && period <= 17){
loanAmountApproveAutomatically = totalCustomerBalance.multiply(twelveMonthPercentage);
}else if(period > 17 && period <= 23){
loanAmountApproveAutomatically = totalCustomerBalance.multiply(twentyThreeMonthPercentage);
}else
loanAmountApproveAutomatically = totalCustomerBalance.multiply(twentyFourMonthPercentage);
return loanAmountApproveAutomatically;
}
}
<file_sep>"# BankApp"
<file_sep>package mavenBank.DataStore.services;
import Entities.Account;
import Entities.Customer;
import Entities.LoanRequest;
import mavenBank.Exceptions.MavenBankLoanException;
public interface LoanService {
public LoanRequest approveLoanRequest(Account loanAccount)throws MavenBankLoanException;
public LoanRequest approveLoanRequest(Customer customer, Account accountSeekingForLoan)throws MavenBankLoanException;
}
<file_sep>package mavenBank.DataStore.services;
import java.time.Year;
public class BankService {
private static long currentBVN = 2;
private static long currentAccountNumber = 1000110003;
private static long transactionId = 0;
public static long getTransactionId() {
return transactionId;
}
public static long generateId(){
transactionId++;
return transactionId;
}
private static void setTransactionId(long transactionId) {
BankService.transactionId = transactionId;
}
private static void setCurrentBVN(long currentBVN) {
BankService.currentBVN = currentBVN;
}
public static long getCurrentAccountNumber() {
return currentAccountNumber;
}
private static void setCurrentAccountNumber(long currentAccountNumber) {
BankService.currentAccountNumber = currentAccountNumber;
}
public static long getCurrentBVN() {
return currentBVN;
}
public static long generateBVN(){
currentBVN++;
return currentBVN;
}
public static long generateAccountNumber(){
currentAccountNumber++;
return currentAccountNumber;
}
public static void tearDown() {
currentAccountNumber = 1000110003;
currentBVN = 2;
}
}
<file_sep>package mavenBank.DataStore.services;
import Entities.*;
import mavenBank.DataStore.CustomerRepo;
import mavenBank.DataStore.LoanRequestStatus;
import mavenBank.DataStore.LoanType;
import mavenBank.Exceptions.MavenBankException;
import mavenBank.Exceptions.MavenBankLoanException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class LoanServiceImplTest {
LoanRequest joshuaLoanRequest;
private AccountService accountService;
private LoanService loanService;
@BeforeEach
void setUp() {
loanService = new LoanServiceImpl();
accountService = new AccountServiceImpl();
joshuaLoanRequest = new LoanRequest();
joshuaLoanRequest.setApplyDate(LocalDate.now());
joshuaLoanRequest.setInterest(0.1);
joshuaLoanRequest.setStatus(LoanRequestStatus.NEW);
joshuaLoanRequest.setTenor(24);
joshuaLoanRequest.setTypeOfLoan(LoanType.SME);
}
@AfterEach
void tearDown() {
BankService.tearDown();
CustomerRepo.setUp();
}
@Test
void approveLoanRequestWithAccountBalance(){
try {
Account joshuaCurrentAccount = accountService.findAccount(1000110002);
assertNull(joshuaCurrentAccount.getAccountLoanRequest());
joshuaLoanRequest.setAmount(BigDecimal.valueOf(9000000));
joshuaCurrentAccount.setAccountLoanRequest(joshuaLoanRequest);//FICO
assertNotNull(joshuaCurrentAccount.getAccountLoanRequest());
LoanRequest processedLoanRequest = loanService.approveLoanRequest(joshuaCurrentAccount);
assertNotNull(processedLoanRequest);
assertEquals(LoanRequestStatus.APPROVED, processedLoanRequest.getStatus());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void approveLoanRequestWithNullAccount(){
assertThrows(MavenBankLoanException.class, ()-> loanService.approveLoanRequest(null));
}
@Test
void approveLoanRequestWithNullLoanRequest(){
CurrentAccount currentAccountWithoutLoanRequest = new CurrentAccount();
assertThrows(MavenBankLoanException.class, ()->loanService.approveLoanRequest(currentAccountWithoutLoanRequest));
}
@Test
void approveLoanRequestWithNullCustomer(){
assertThrows(MavenBankLoanException.class, ()-> loanService.approveLoanRequest(null, new SavingsAccount()));
}
@Test
void approveLoanRequestWithCustomerEngagement(){
try {
Account judaCurrentAccount = accountService.findAccount(1000110003);
judaCurrentAccount.setAccountLoanRequest(joshuaLoanRequest);
}catch(MavenBankException accountCanBeFoundException){
accountCanBeFoundException.printStackTrace();
}
}
@Test
void approveLoanWithCustomerRelationWithTotalVolume(){
try {
Account joshuaSavingsAccount = accountService.findAccount(1000110001);
Optional<Customer> optionalCustomer = CustomerRepo.getCustomers().values().stream().findFirst();
Customer joshua = optionalCustomer.isPresent() ? optionalCustomer.get() : null;
assertNotNull(joshua);
joshua.setRelationshipStartDate(joshuaSavingsAccount.getStartDate().minusYears(2));
assertEquals(BigDecimal.valueOf(450000), joshuaSavingsAccount.getBalance());
joshuaLoanRequest.setAmount(BigDecimal.valueOf(3000000));
joshuaSavingsAccount.setAccountLoanRequest(joshuaLoanRequest);
LoanRequest decision = loanService.approveLoanRequest(joshua, joshuaSavingsAccount);
assertEquals(LoanRequestStatus.APPROVED, joshuaLoanRequest.getStatus());
}catch(MavenBankException accountCanBeFoundException){
accountCanBeFoundException.printStackTrace();
}
}
@Test
void approveLoanRequestWithAccountBalanceAndHighLoanRequestAmount(){
try {
Account joshuaCurrentAccount = accountService.findAccount(1000110002);
assertNull(joshuaCurrentAccount.getAccountLoanRequest());
joshuaLoanRequest.setAmount(BigDecimal.valueOf(90000000));
joshuaCurrentAccount.setAccountLoanRequest(joshuaLoanRequest);//FICO
assertNotNull(joshuaCurrentAccount.getAccountLoanRequest());
LoanRequest processedLoanRequest = loanService.approveLoanRequest(joshuaCurrentAccount);
assertNotNull(processedLoanRequest);
assertEquals(LoanRequestStatus.PENDING, processedLoanRequest.getStatus());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void approveLoanRequestWithCustomerButWithoutAccount(){
assertThrows(MavenBankLoanException.class, ()-> loanService.approveLoanRequest(new Customer(), null));
}
}<file_sep>package mavenBank.DataStore;
public enum LoanStatus {
ACTIVE, CLOSED,NON_PERFORMING;
}
<file_sep>package mavenBank.engines;
import Entities.Account;
import Entities.Customer;
import mavenBank.DataStore.LoanRequestStatus;
import mavenBank.Exceptions.MavenBankLoanException;
import java.math.BigDecimal;
public class LoanEngineByBalance implements LoanEngine {
@Override
public BigDecimal calculateAmountAutoApprove(Customer customer, Account account) throws MavenBankLoanException {
validateLoanRequest(customer, account);
BigDecimal totalVolumeBalance = BigDecimal.valueOf(0.2);
BigDecimal totalCustomerBalance = BigDecimal.ZERO;
if (customer.getAccounts().size() > BigDecimal.ONE.intValue()) {
for (Account customerAccount : customer.getAccounts()) {
totalCustomerBalance = totalCustomerBalance.add(customerAccount.getBalance());
}
}
BigDecimal loanAmountApproveAutomatically = BigDecimal.ZERO;
if (totalCustomerBalance.intValue() > BigDecimal.ZERO.intValue()){
loanAmountApproveAutomatically = totalCustomerBalance.multiply(totalVolumeBalance);
}
return loanAmountApproveAutomatically;
}
}
<file_sep>package Entities;
import mavenBank.DataStore.BankTransactionType;
import mavenBank.DataStore.services.BankService;
import java.math.BigDecimal;
import java.time.LocalDateTime;
public class BankTransaction {
private long id;
private LocalDateTime dateTime;
private BankTransactionType type;
private BigDecimal amount;
public BankTransaction(BankTransactionType type, BigDecimal tXAmount){
this.id = BankService.generateId();
this.dateTime = LocalDateTime.now();
this.type = type;
amount = tXAmount;
}
public long getTransactionId() {
return id;
}
public void setTransactionId(long transactionId) {
this.id = transactionId;
}
public LocalDateTime getDateTime() {
return dateTime;
}
public void setDateTime(LocalDateTime dateTime) {
this.dateTime = dateTime;
}
public BankTransactionType getType() {
return type;
}
public void setType(BankTransactionType type) {
this.type = type;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}
<file_sep>package mavenBank.DataStore;
public enum AccountType {
CURRENTACCOUNT, SAVINGSACCOUNT;
}
<file_sep>package mavenBank.DataStore.services;
import Entities.Account;
import Entities.BankTransaction;
import mavenBank.DataStore.AccountType;
import Entities.Customer;
import mavenBank.DataStore.LoanStatus;
import mavenBank.Exceptions.MavenBankException;
import java.math.BigDecimal;
public interface AccountService {
long openAccount(Customer customer, AccountType typeofAccount) throws MavenBankException;
BigDecimal deposit(BigDecimal decimal, long accountNumber) throws MavenBankException;
long openSavingsAccount(Customer customer)throws MavenBankException;
long OpenCurrentAccount(Customer customer)throws MavenBankException;
Account findAccount(Customer customer, long accountNumber) throws MavenBankException;
Account findAccount(long accountNumber) throws MavenBankException;
BigDecimal withdraw(BigDecimal decimal, long accountNumber) throws MavenBankException;
void applyForOverdraft(Account account);
LoanStatus applyForLoan();
void addBankTransaction(BankTransaction transaction, Account account) throws MavenBankException;
}
<file_sep>package mavenBank.DataStore.services;
import Entities.Account;
import Entities.BankTransaction;
import Entities.LoanRequest;
import mavenBank.DataStore.*;
import mavenBank.Exceptions.MavenBankException;
import Entities.Customer;
import mavenBank.Exceptions.MavenBankInsufficientAmountException;
import mavenBank.Exceptions.MavenBankTransactionException;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.util.Optional;
import static org.junit.jupiter.api.Assertions.*;
class AccountServiceImplTest {
private AccountService accountService;
private Customer abu;
private Customer bessie;
private Account abuAccount;
private Account bessieAccount;
@BeforeEach
void setUp(){
accountService = new AccountServiceImpl();
abu = new Customer();
bessie = new Customer();
abu.setBVN(BankService.generateBVN());
abu.setFirstName("Dome");
abu.setSurname("joshua");
abu.setEmail("<EMAIL>");
abu.setPhone("08183563309");
abu.setPassword("<PASSWORD>");
bessie.setBVN(BankService.generateBVN());
bessie.setFirstName("Dome");
bessie.setSurname("joshua");
bessie.setEmail("<EMAIL>");
bessie.setPhone("08183563309");
bessie.setPassword("<PASSWORD>");
}
@AfterEach
void tearDown(){
BankService.tearDown();
CustomerRepo.setUp();
}
@Test
void openAccount(){
assertFalse(CustomerRepo.getCustomers().containsKey(abu.getBVN()));
assertEquals(1000110003, BankService.getCurrentAccountNumber());
assertEquals(4, BankService.getCurrentBVN());
try {
long account = accountService.openAccount(abu, AccountType.SAVINGSACCOUNT);
assertFalse(CustomerRepo.getCustomers().isEmpty());
assertEquals(1000110004, BankService.getCurrentAccountNumber());
assertTrue(CustomerRepo.getCustomers().containsKey(abu.getBVN()));
assertFalse(abu.getAccounts().isEmpty());
assertEquals(account, abu.getAccounts().get(0).getAccountNumber());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void testOpenAccountThrowsAnException(){
assertThrows(MavenBankException.class, ()-> accountService.openAccount(null, AccountType.SAVINGSACCOUNT));
}
@Test
void SameCustomerCannotOpenSameTypeOfAccount(){
Optional<Customer> optionalJoshua = CustomerRepo.getCustomers().values().stream().findFirst();
Customer joshua = (optionalJoshua.isEmpty())? null : optionalJoshua.get();
assertFalse(CustomerRepo.getCustomers().isEmpty());
assertEquals(1000110003, BankService.getCurrentAccountNumber());
System.out.println(joshua.getAccounts().get(0).getClass().getTypeName());
System.out.println(joshua.getAccounts().get(0).getClass().getSimpleName());
System.out.println(AccountType.SAVINGSACCOUNT.toString());
assertEquals(AccountType.SAVINGSACCOUNT.toString(), joshua.getAccounts().get(0).getClass().getSimpleName().toUpperCase());
assertThrows(MavenBankException.class, ()-> accountService.openAccount(joshua, AccountType.SAVINGSACCOUNT));
assertEquals(2, joshua.getAccounts().size());
assertEquals(1000110003, BankService.getCurrentAccountNumber());
}
@Test
void openCurrentAccount(){
// assertFalse(CustomerRepo.getCustomers().containsKey(abu.getBVN()));
assertEquals(1000110003, BankService.getCurrentAccountNumber());
try {
long account = accountService.openAccount(abu, AccountType.CURRENTACCOUNT);
assertFalse(CustomerRepo.getCustomers().isEmpty());
assertEquals(1000110004, BankService.getCurrentAccountNumber());
assertTrue(CustomerRepo.getCustomers().containsKey(abu.getBVN()));
assertFalse(abu.getAccounts().isEmpty());
assertEquals(account, abu.getAccounts().get(0).getAccountNumber());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void twoCustomersCanOpenAccount(){
// assertFalse(CustomerRepo.getCustomers().containsKey(abu.getBVN()));
assertEquals(1000110003, BankService.getCurrentAccountNumber());
assertFalse(CustomerRepo.getCustomers().isEmpty());
try {
long account = accountService.openAccount(abu, AccountType.SAVINGSACCOUNT);
assertFalse(CustomerRepo.getCustomers().isEmpty());
assertEquals(1000110004, BankService.getCurrentAccountNumber());
assertTrue(CustomerRepo.getCustomers().containsKey(abu.getBVN()));
assertFalse(abu.getAccounts().isEmpty());
assertEquals(account, abu.getAccounts().get(0).getAccountNumber());
long newAccount = accountService.openAccount(bessie, AccountType.SAVINGSACCOUNT);
assertFalse(CustomerRepo.getCustomers().isEmpty());
assertEquals(1000110005, BankService.getCurrentAccountNumber());
assertTrue(CustomerRepo.getCustomers().containsKey(bessie.getBVN()));
assertFalse(bessie.getAccounts().isEmpty());
assertEquals(newAccount, bessie.getAccounts().get(0).getAccountNumber());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void deposit(){
try {
Account abuSavingsAccount = accountService.findAccount(1000110001);
assertEquals(BigDecimal.valueOf(450000), abuSavingsAccount.getBalance());
BigDecimal accountBalance = accountService.deposit(new BigDecimal(50000), 1000110001);
assertEquals(new BigDecimal(500000), accountBalance);
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void findAccount(){
try {
Account johnSavingsAccount = accountService.findAccount(1000110002);
assertNotNull(johnSavingsAccount);
assertEquals(1000110002, johnSavingsAccount.getAccountNumber());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void findAccountWithInvalidAccountNumber(){
try {
Account johnSavingsAccount = accountService.findAccount(2000);
assertNull(johnSavingsAccount);
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void depositNegativeAmount(){
try {
Account joshuaSavingsAccount = accountService.findAccount(1000110001);
assertEquals(BigDecimal.valueOf(450000), joshuaSavingsAccount.getBalance());
assertThrows(MavenBankException.class, ()-> accountService.deposit(new BigDecimal(-5000), 1000110001));
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void depositNegativeAmountThrowsAnException(){
assertThrows(MavenBankTransactionException.class, ()-> accountService.deposit(new BigDecimal(-5000), 1000110002));
}
@Test
void depositWithVeryLargeAmount(){
try {
Account abuSavingsAccount = accountService.findAccount(1000110001);
BigDecimal originalBalance = abuSavingsAccount.getBalance();
assertEquals(BigDecimal.valueOf(450000), originalBalance);
BigDecimal depositAmount = new BigDecimal("10000000000000");
BigDecimal accountBalance = accountService.deposit(depositAmount, 1000110001);
BigDecimal newBalance = originalBalance.add(depositAmount);
assertEquals(newBalance, accountBalance);
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void depositWithInvalidAccountNumberShouldNotDeposit(){
try {
Account newAccount = accountService.findAccount(1000110005);
assertNull(newAccount);
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void withdraw() {
try {
Account availableAccount = accountService.findAccount(1000110001);
assertEquals(BigDecimal.valueOf(450000), availableAccount.getBalance());
BigDecimal withdrawalAmount = accountService.withdraw(BigDecimal.valueOf(300000), availableAccount.getAccountNumber());
assertEquals(BigDecimal.valueOf(300000), withdrawalAmount);
assertEquals(BigDecimal.valueOf(150000), availableAccount.getBalance());
}catch (MavenBankTransactionException ex){
ex.printStackTrace();
}catch (MavenBankException ex) {
ex.printStackTrace();
}
}
@Test
void customerCannotWithdrawNegativeAmount(){
try {
Account availableAccount = accountService.findAccount(1000110001);
assertEquals(BigDecimal.valueOf(450000), availableAccount.getBalance());
assertThrows(MavenBankTransactionException.class, ()-> accountService.withdraw(BigDecimal.valueOf(-500000), 1000110001));
}catch (MavenBankTransactionException ex){
ex.printStackTrace();
}catch (MavenBankException ex) {
ex.printStackTrace();
}
}
@Test
void withdrawAmountHigherThanAccountBalance(){
try {
Account availableAccount = accountService.findAccount(1000110001);
assertEquals(BigDecimal.valueOf(450000), availableAccount.getBalance());
assertThrows(MavenBankInsufficientAmountException.class, ()-> accountService.withdraw(BigDecimal.valueOf(500000), availableAccount.getAccountNumber()));
assertEquals(BigDecimal.valueOf(450000), availableAccount.getBalance());
}catch (MavenBankTransactionException ex){
ex.printStackTrace();
}catch (MavenBankException ex) {
ex.printStackTrace();
}
}
@Test
void withdrawFromAWrongAccountNumberThrowsAnException(){
try {
Account availableAccount = accountService.findAccount(1000110001);
Account withdrawingAccount = accountService.findAccount(10001109);
assertEquals(BigDecimal.valueOf(450000), availableAccount.getBalance());
}catch(MavenBankTransactionException ex){
ex.printStackTrace();
}catch (MavenBankException ex){
ex.printStackTrace();
}
assertThrows(MavenBankTransactionException.class, ()-> accountService.withdraw(BigDecimal.valueOf(5000), 1000110009));
}
@Test
void applyForLoan(){
LoanRequest joshuaLoanRequest = new LoanRequest();
joshuaLoanRequest.setApplyDate(LocalDate.now());
joshuaLoanRequest.setAmount(BigDecimal.valueOf(50000000));
joshuaLoanRequest.setInterest(0.1);
joshuaLoanRequest.setStatus(LoanRequestStatus.NEW);
joshuaLoanRequest.setTenor(24);
joshuaLoanRequest.setTypeOfLoan(LoanType.SME);
try {
Account joshuaCurrentAccount = accountService.findAccount(1000110002);
assertNull(joshuaCurrentAccount.getAccountLoanRequest());
joshuaCurrentAccount.setAccountLoanRequest(joshuaLoanRequest);//FICO
assertNotNull(joshuaCurrentAccount.getAccountLoanRequest());
}catch(MavenBankTransactionException ex){
ex.printStackTrace();
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void addBankTransactionWithNullTransaction(){
assertThrows(MavenBankTransactionException.class, ()-> accountService.addBankTransaction(null, abuAccount));
}
@Test
void addBankTransactionWithNullAccount(){
BankTransaction transaction = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(10));
assertThrows(MavenBankTransactionException.class, ()-> accountService.addBankTransaction(transaction, null));
}
@Test
void addBankTransactionWithDeposit() {
try {
Account judasSavingsAccount = accountService.findAccount(1000110003);
assertNotNull(judasSavingsAccount);
assertEquals(BigDecimal.ZERO, judasSavingsAccount.getBalance());
assertEquals(0, judasSavingsAccount.getTransactions().size());
BankTransaction janeDeposit = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(10000));
accountService.addBankTransaction(janeDeposit, judasSavingsAccount);
assertEquals(BigDecimal.valueOf(10000), judasSavingsAccount.getBalance());
assertEquals(1, judasSavingsAccount.getTransactions().size());
} catch (MavenBankException ex) {
ex.printStackTrace();
}
}
@Test
void addBankTransactionWithNegativeDeposit(){
try {
Account judasSavingsAccount = accountService.findAccount(1000110003);
assertNotNull(judasSavingsAccount);
assertEquals(BigDecimal.ZERO, judasSavingsAccount.getBalance());
assertEquals(0, judasSavingsAccount.getTransactions().size());
BankTransaction janeDeposit = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(-10000));
assertThrows(MavenBankTransactionException.class, ()-> accountService.addBankTransaction(janeDeposit, judasSavingsAccount));
assertEquals(BigDecimal.ZERO, judasSavingsAccount.getBalance());
assertEquals(0, judasSavingsAccount.getTransactions().size());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
@Test
void addBankTransactionForWithdrawal(){
try{
Account janeSavingsAccount = accountService.findAccount(1000110003);
assertNotNull(janeSavingsAccount);
BankTransaction depositTx = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(50000));
accountService.addBankTransaction(depositTx, janeSavingsAccount);
assertEquals(BigDecimal.valueOf(50000), janeSavingsAccount.getBalance());
assertEquals(1, janeSavingsAccount.getTransactions().size());
BankTransaction withdrawTx = new BankTransaction(BankTransactionType.WITHDRAW, BigDecimal.valueOf(20000));
accountService.addBankTransaction(withdrawTx, janeSavingsAccount);
assertEquals(BigDecimal.valueOf(30000), janeSavingsAccount.getBalance());
assertEquals(2, janeSavingsAccount.getTransactions().size());
}catch (MavenBankException exception){
exception.printStackTrace();
}
}
@Test
void addBankTransactionWithNegativeWithdrawal(){
try{
Account judasSavingsAccount = accountService.findAccount(1000110003);
assertNotNull(judasSavingsAccount);
assertEquals(BigDecimal.ZERO, judasSavingsAccount.getBalance());
assertEquals(0, judasSavingsAccount.getTransactions().size());
BankTransaction depositTx = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(50000));
accountService.addBankTransaction(depositTx, judasSavingsAccount);
assertEquals(BigDecimal.valueOf(50000), judasSavingsAccount.getBalance());
assertEquals(1, judasSavingsAccount.getTransactions().size());
BankTransaction withdrawTx = new BankTransaction(BankTransactionType.WITHDRAW, BigDecimal.valueOf(-20000));
assertThrows(MavenBankTransactionException.class, ()->accountService.addBankTransaction(withdrawTx, judasSavingsAccount));
assertEquals(BigDecimal.valueOf(50000), judasSavingsAccount.getBalance());
assertEquals(1, judasSavingsAccount.getTransactions().size());
}catch (MavenBankException ex){
ex.printStackTrace();
}
}
}<file_sep>package mavenBank.DataStore;
import Entities.*;
import mavenBank.DataStore.services.AccountService;
import mavenBank.DataStore.services.AccountServiceImpl;
import mavenBank.DataStore.services.BankService;
import mavenBank.Exceptions.MavenBankException;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
public class CustomerRepo {
private static Map<Long, Customer> customers = new HashMap<>();
public static Map<Long, Customer> getCustomers() {
return customers;
}
private void setCustomers(Map<Long, Customer> customers) {
customers = customers;
}
// public static void tearDown(){
// customers=null;
// }
static {
setUp();
}
public static void setUp(){
Customer joshua = new Customer();
joshua.setBVN(1);
joshua.setFirstName("Dome");
joshua.setSurname("joshua");
joshua.setEmail("<EMAIL>");
joshua.setPhone("08183563309");
joshua.setPassword("<PASSWORD>");
Account joshuaSavingsAccount = new SavingsAccount(1000110001);
joshua.setRelationshipStartDate(joshuaSavingsAccount.getStartDate());
BankTransaction initialDeposit = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(300000));
joshuaSavingsAccount.getTransactions().add(initialDeposit);
BankTransaction upkeepAllowanceDeposit= new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(50000));
upkeepAllowanceDeposit.setDateTime(LocalDateTime.now().minusMonths(3));
joshuaSavingsAccount.getTransactions().add(upkeepAllowanceDeposit);
BankTransaction mayAllowanceDeposit= new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(50000));
mayAllowanceDeposit.setDateTime(LocalDateTime.now().minusMonths(2));
joshuaSavingsAccount.getTransactions().add(mayAllowanceDeposit);
BankTransaction juneAllowanceDeposit = new BankTransaction(BankTransactionType.DEPOSIT, BigDecimal.valueOf(50000));
juneAllowanceDeposit.setDateTime(LocalDateTime.now().minusMonths(2));
joshuaSavingsAccount.getTransactions().add(juneAllowanceDeposit);
joshuaSavingsAccount.setBalance(BigDecimal.valueOf(450000));
joshua.getAccounts().add(joshuaSavingsAccount);
Account joshuaCurrentAccount = new CurrentAccount(1000110002, new BigDecimal(50000000));
joshua.getAccounts().add(joshuaCurrentAccount);
customers.put(joshua.getBVN(), joshua);
Customer judas = new Customer();
judas.setBVN(2);
judas.setFirstName("Dome");
judas.setSurname("joshua");
judas.setEmail("<EMAIL>");
judas.setPhone("08183563309");
judas.setPassword("<PASSWORD>");
Account judasSavingsAccount = new SavingsAccount(1000110003);
judas.setRelationshipStartDate(judasSavingsAccount.getStartDate());
judas.getAccounts().add(judasSavingsAccount);
customers.put(judas.getBVN(), judas);
}
}
<file_sep>package mavenBank.engines;
import Entities.Account;
import Entities.Customer;
import mavenBank.Exceptions.MavenBankException;
import mavenBank.Exceptions.MavenBankLoanException;
import java.math.BigDecimal;
public interface LoanEngine {
BigDecimal calculateAmountAutoApprove(Customer customer, Account accountSeekingLoan) throws MavenBankException;
default void validateLoanRequest(Customer customer, Account accountSeekingLoan) throws MavenBankLoanException {
if (customer == null) {
throw new MavenBankLoanException("No Customer provided for loan request");
}
validateLoanRequest(accountSeekingLoan);
}
default void validateLoanRequest(Account accountSeekingLoan)throws MavenBankLoanException{
if(accountSeekingLoan == null){
throw new MavenBankLoanException("An account is required for processing");
}if(accountSeekingLoan.getAccountLoanRequest() == null){
throw new MavenBankLoanException("No Loan provided for processing");
}
}
}
<file_sep>package mavenBank.DataStore.services;
import Entities.*;
import mavenBank.DataStore.AccountType;
import mavenBank.DataStore.BankTransactionType;
import mavenBank.DataStore.CustomerRepo;
import mavenBank.DataStore.LoanStatus;
import mavenBank.Exceptions.MavenBankException;
import mavenBank.Exceptions.MavenBankInsufficientAmountException;
import mavenBank.Exceptions.MavenBankTransactionException;
import java.math.BigDecimal;
public class AccountServiceImpl implements AccountService{
@Override
public long openAccount(Customer customer, AccountType typeofAccount) throws MavenBankException {
long accountNumber = BigDecimal.ZERO.longValue();
if(typeofAccount == AccountType.SAVINGSACCOUNT){
accountNumber = openSavingsAccount(customer);
}
else if(typeofAccount == AccountType.CURRENTACCOUNT){
accountNumber = OpenCurrentAccount(customer);
}
return accountNumber;
}
@Override
public BigDecimal deposit(BigDecimal amount, long accountNumber) throws MavenBankException, MavenBankTransactionException {
Account depositAccount = findAccount(accountNumber);
validateTransactions(amount, depositAccount);
BigDecimal newAmount = depositAccount.getBalance().add(amount);
depositAccount.setBalance(newAmount);
return newAmount;
}
@Override
public long openSavingsAccount(Customer customer) throws MavenBankException {
if(customer == null) {
throw new MavenBankException("Customer or Type Can't be Null");
}
SavingsAccount newAccount = new SavingsAccount();
if(accountTypeExists(customer, newAccount.getClass().getTypeName())){
throw new MavenBankException("Account Type already Exists for this user, Thanks");
}
newAccount.setAccountNumber(BankService.generateAccountNumber());
customer.getAccounts().add(newAccount);
CustomerRepo.getCustomers().put(customer.getBVN(),customer);
return newAccount.getAccountNumber();
}
@Override
public long OpenCurrentAccount(Customer customer) throws MavenBankException {
if(customer == null) {
throw new MavenBankException("Customer Can't be Null");
}
CurrentAccount newAccount = new CurrentAccount();
if(accountTypeExists(customer, newAccount.getClass().getTypeName())){
throw new MavenBankException("Account Type already Exists for this user, Thanks");
}
newAccount.setAccountNumber(BankService.generateAccountNumber());
customer.getAccounts().add(newAccount);
CustomerRepo.getCustomers().put(customer.getBVN(),customer);
return newAccount.getAccountNumber();
}
@Override
public Account findAccount(Customer customer, long accountNumber)throws MavenBankException {
return null;
}
@Override
public Account findAccount(long accountNumber) throws MavenBankException{
boolean accountFound = false;
Account foundAccount = null;
for (Customer customer: CustomerRepo.getCustomers().values()) {
for (Account account:customer.getAccounts()){
if(account.getAccountNumber() == accountNumber){
foundAccount = account;
accountFound = true;
break;
}
if(accountFound)
break;
}
}
return foundAccount;
}
@Override
public BigDecimal withdraw(BigDecimal amount, long accountNumber) throws MavenBankTransactionException,MavenBankInsufficientAmountException, MavenBankException {
Account availableAccount = findAccount(accountNumber);
validateTransactions(amount, availableAccount);
try{
checkForSufficientBalance(amount, availableAccount);
}catch (MavenBankInsufficientAmountException ex){
this.applyForOverdraft(availableAccount);
throw ex;//Rethrow
}
BigDecimal newBalance = debitAccount(amount, accountNumber);
return amount;
}
@Override
public void applyForOverdraft(Account account) {
//TODO
}
@Override
public LoanStatus applyForLoan() {
return null;
}
@Override
public void addBankTransaction(BankTransaction transaction, Account account) throws MavenBankException {
if(transaction == null || account == null){
throw new MavenBankTransactionException("Transaction and Account required");
}
if(transaction.getType() == BankTransactionType.DEPOSIT){
deposit(transaction.getAmount(), account.getAccountNumber());
}
else if (transaction.getType() == BankTransactionType.WITHDRAW){
withdraw(transaction.getAmount(), account.getAccountNumber());
}
account.getTransactions().add(transaction);
}
public void checkForSufficientBalance(BigDecimal amount, Account account) throws MavenBankInsufficientAmountException {
if(amount.compareTo(account.getBalance()) > 0){
throw new MavenBankInsufficientAmountException("Insufficient account balance");
}
}
private BigDecimal debitAccount(BigDecimal amount, long accountNumber) throws MavenBankException {
Account availableAccount = findAccount(accountNumber);
BigDecimal newAmount = availableAccount.getBalance().subtract(amount);
availableAccount.setBalance(newAmount);
return newAmount;
}
private void validateTransactions(BigDecimal amount, Account account) throws MavenBankTransactionException, MavenBankInsufficientAmountException {
if(amount.compareTo(BigDecimal.ZERO) < BigDecimal.ONE.intValue()){
throw new MavenBankTransactionException("Invalid Amount");}
if (account == null) {
throw new MavenBankTransactionException("Account Not Found ensure you enter a valid account Number");
}
}
public boolean accountTypeExists(Customer customer, String type){
boolean checkIfItExist = false;
for (Account account:customer.getAccounts()) {
if (account.getClass().getTypeName() == type) {
checkIfItExist = true;
break;
}
}
return checkIfItExist;
}
}
|
1ff63e07aebc294a99c2d1559b078873b69b1cfe
|
[
"Markdown",
"Java"
] | 15
|
Java
|
akenz1901/BankApp
|
1e96ea8e7e86bf36afa0cf2288575903c6a3cf2c
|
1f95dde08be2951a36af8248779116db399e7a80
|
refs/heads/master
|
<repo_name>cwal1220/RaspberryKPU<file_sep>/Python/switch_test_1.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
LED1 = 23
SW = 18
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(LED1, GPIO.OUT) #GPIO23를 사용선언
GPIO.setup(SW, GPIO.IN, pull_up_down=GPIO.PUD_UP) #풀업 설정
key_state = False # 키 상태 저장 변수
while True:
if GPIO.input(SW) == False: # 버튼을 눌렀을 때
key_state = not key_state
GPIO.output(LED1, key_state)
time.sleep(0.5) # 중복 입력 방지를 위한 0.5초 대기
GPIO.cleanup() #GPIO 초기화
<file_sep>/Python/buzzer.py
import RPi.GPIO as GPIO
import time
BUZZER = 17
GPIO.setmode(GPIO.BCM)
GPIO.setup(BUZZER, GPIO.OUT)
while True:
GPIO.output(BUZZER, True) #LED에 불이 들어옴
time.sleep(1) #500ms 대기
GPIO.output(BUZZER, False)
time.sleep(1) # 500ms 대기<file_sep>/Python/pirMotionSensor.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
INPUT_PIN = 4
g_nPirState = False
g_nVal = 0
GPIO.setmode(GPIO.BCM)
GPIO.setup(INPUT_PIN, GPIO.IN)
while True:
g_nVal = GPIO.input(INPUT_PIN)
if g_nVal:
if g_nVal:
if not g_nPirState:
print('Motion Detected!!')
g_nPirState = True
else:
if g_nPirState:
print('Motion ended...')
g_nPirState = False<file_sep>/C/buzzer.c
#include <wiringPi.h>
#include <stdio.h>
#define BUZZER 17
int main(void)
{
if(wiringPiSetupGpio() == -1)
return 1;
pinMode(BUZZER, OUTPUT);
while(1)
{
digitalWrite(BUZZER, HIGH);
delay(1000);
digitalWrite(BUZZER, LOW);
delay(1000);
}
return 0;
}<file_sep>/Python/pwm_test_1.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
LEDB = 25
LEDR = 23
LEDG = 24
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(LEDR, GPIO.OUT)
GPIO.setup(LEDG, GPIO.OUT)
GPIO.setup(LEDB, GPIO.OUT)
pwm_r = GPIO.PWM(LEDR, 200) # Red LED PWM
pwm_g = GPIO.PWM(LEDG, 200) # Greed LED PWM
pwm_b = GPIO.PWM(LEDB, 200) # Blue LED PWM
pwm_r.start(0)
pwm_g.start(0)
pwm_b.start(0)
while True:
for i in range(100):
pwm_r.ChangeDutyCycle(i)
time.sleep(0.01)
for i in range(100):
pwm_g.ChangeDutyCycle(i)
time.sleep(0.01)
for i in range(100):
pwm_b.ChangeDutyCycle(i)
time.sleep(0.01)
GPIO.cleanup() #GPIO 초기화
<file_sep>/C/led.c
#include <stdio.h>
#include <wiringPi.h> //GPIO Access Library 헤더파일 포함
#define LED_RED_1 23 // GPIO23, LED 포트 RED핀(pin16) 정의
int main (void)
{
int i=0;
if(wiringPiSetupGpio() == -1)
//Wiring Pi의 GPIO를 사용하기 위한 설정(초기화)
return 1;
printf("GPIO LED Test \n");
pinMode(LED_RED_1,OUTPUT);
//LED 포트 RED1 핀 출력 설정
digitalWrite(LED_RED_1,LOW);
//LED RED1 핀에 LOW(0) 출력
while(1)
{
printf("GPIO LED Test =%d\n", i);
digitalWrite(LED_RED_1,HIGH); // LED ON
delay(500); //500ms 지연
digitalWrite(LED_RED_1,LOW); //LED OFF
delay(500);
i++;
}
return 0;
}
<file_sep>/Python/switch.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
LED1 = 23
SW = 18
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(LED1, GPIO.OUT) #GPIO23를 사용선언
GPIO.setup(SW, GPIO.IN, pull_up_down=GPIO.PUD_UP)
while True:
if GPIO.input(SW): # 버튼을 누르지 않을 때
GPIO.output(LED1, False)
else: # 버튼을 눌렀을 때
GPIO.output(LED1, True)
GPIO.cleanup() #GPIO 초기화
<file_sep>/C/hc-sr04.c
#include <stdio.h>
#include <wiringPi.h>
#define TP 20
#define EP 21
float getDistance(void)
{ float fDistance;
int nStartTime, nEndTime;
digitalWrite(TP, LOW);
delayMicroseconds(2);
// pull the Trig pin to high level for more than 10us impulse
digitalWrite(TP, HIGH);
delayMicroseconds(10);
digitalWrite(TP, LOW);
while(digitalRead(EP)==LOW);
nStartTime = micros();
while(digitalRead(EP) == HIGH);
nEndTime = micros();
fDistance = (nEndTime - nStartTime) / 29. / 2.;
return fDistance;
}
int main(void)
{
if(wiringPiSetupGpio() == -1) {
return 1;
}
pinMode(TP,OUTPUT);
pinMode(EP,INPUT);
while(1)
{
float fDistance = getDistance();
printf("Distance:%.2fcm\n", fDistance);
delay(1000);
}
return 0;
}<file_sep>/C/switch.c
#include <stdio.h>
#include <wiringPi.h>
#define SW 18 // GPIO18, Pin12 스위치 핀 정의
#define LED1 23 // GPIO23, LED 포트를 pin16으로 정의
int main()
{
if(wiringPiSetupGpio() == -1) // GPIO포트 초기화
// wiringPiSetupGpio()를 사용하는 경우 gpio readall의 wPi 값 사용
return 1 ;
pinMode(SW, INPUT); // switch 포트는 입력으로 설정
pinMode(LED1, OUTPUT); // LED1 포트는 출력으로 설정
while(1)
{
if(digitalRead(SW) == 0) //스위치가 눌러 졌는지 확인
{
digitalWrite(LED1, HIGH); // LED1 포트에 ‘1’을 출력
delay(500); // 500mS 지연
}
else
{
digitalWrite(LED1, LOW); // LED1 포트에 ‘0’을 출력
delay(500); // 500mS 지연
}
}
return 0 ;
}
<file_sep>/C/blink.c
#include <stdio.h>
#include <wiringPi.h> //GPIO 라이브러리 사용
#define INPUT_PIN 18 // GPIO18, PIN No=12
#define OUTPUT_PIN 27 // GPIO27, PIN=13
int main(void)
{ //GPIO 초기화
if (wiringPiSetupGpio() == -1) {
return 1;
}
pinMode(INPUT_PIN, INPUT); //GPIO18은 입력모드로 설정
pinMode(OUTPUT_PIN, OUTPUT); //GPIO27은 출력모드로 설정
pullUpDnControl (INPUT_PIN, PUD_UP); //핀18은 풀업
printf("digitalRead (INPUT_PIN) : %d\n", digitalRead (INPUT_PIN));
pullUpDnControl (INPUT_PIN, PUD_DOWN) ;
printf("digitalRead (INPUT_PIN) : %d\n", digitalRead (INPUT_PIN));
return 0;
}
<file_sep>/C/switch_test_1.c
#include <stdio.h>
#include <wiringPi.h>
#define SW 18 // GPIO18, Pin12 스위치 핀 정의
#define LED1 23 // GPIO23, LED 포트를 pin16으로 정의
int main()
{
int keystate = 0;
if(wiringPiSetupGpio() == -1)
return 1;
pinMode(SW, INPUT);
pinMode(LED1, OUTPUT);
while(1)
{
if(digitalRead(SW) == 1) // 스위치가 입력되면
{
keystate = !keystate; // 키 입력을 토글
digitalWrite(LED1, keystate);
delay(500);
}
}
return 0;
}<file_sep>/C/cds.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <wiringPi.h>
#define CDS 10
int main(void)
{
if (wiringPiSetupGpio () == -1)
return 1;
pinMode(CDS, INPUT);
while (1)
{
if(digitalRead(CDS) == 0)
printf("Dark....\n");
if(digitalRead(CDS) == 1)
printf("Bright!!!\n");
delay(200);
}
return 0;
}<file_sep>/Python/pwm.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
LED1 = 23
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(LED1, GPIO.OUT) #GPIO23를 사용선언
pwm = GPIO.PWM(LED1, 200) #PWM 200Hz 주파수 설정
pwm.start(0) # 출력이 0%인 상태에서 시작
while True:
pwm.ChangeDutyCycle(50) #밝기 50%
time.sleep(1) # 1초 대기
pwm.ChangeDutyCycle(100) #밝기 100%
time.sleep(1) # 1초 대기
GPIO.cleanup() #GPIO 초기화
<file_sep>/C/pwm.c
#include <stdio.h>
#include <wiringPi.h>
#include <softPwm.h> // pwm를 쓰기 위해서 라이브러리 파일
#define LED 23 //GPIO 23
int main(void)
{
if(wiringPiSetupGpio() == -1) //GPIO 초기화
return 1;
pinMode(LED, OUTPUT); //GPIO LED핀을 출력으로 설정
digitalWrite(LED, LOW); //GPIO LED핀에 ‘0’값을 출력
softPwmCreate(LED,0,200);
// softPwmCreate (int pin, int initialValue, int pwmRange)
// PWM 핀을 설정,(사용할 핀, pwm값), PWM 값은 0~200사이 범위를 갖고
// 기본 값을 0으로 하는 PWM핀을 설정
printf("Test Software PWM\n");
while(1)
{
softPwmWrite(LED,100);
//softPwmWrite (PWMpin, PWMvalue) value=0~1023
delay(1000);
softPwmWrite(LED,200);
delay(1000);
}
return 0;
}<file_sep>/Python/led_test_1.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
LED_RED_1 = 23
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(LED_RED_1, GPIO.OUT) #GPIO23를 사용선언
while True:
for i in range(0, 50, 1):
GPIO.output(LED_RED_1, True)
time.sleep(i/100)
GPIO.output(LED_RED_1, False)
time.sleep(i/100)
for i in range(50, 0, -1):
GPIO.output(LED_RED_1, True)
time.sleep(i/100)
GPIO.output(LED_RED_1, False)
time.sleep(i/100)
GPIO.cleanup() #GPIO 초기화
<file_sep>/Python/servo.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
SERVO = 6
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(SERVO, GPIO.OUT) #GPIO23를 사용선언
pwm = GPIO.PWM(SERVO, 50) #PWM 200Hz 주파수 설정
pwm.start(5) # 출력이 0%인 상태에서 시작
while True:
pwm.ChangeDutyCycle(5) # Max Left
time.sleep(1) # 1초 대기
pwm.ChangeDutyCycle(7.5) # Middle
time.sleep(1) # 1초 대기
GPIO.cleanup() #GPIO 초기화
<file_sep>/Python/interrupt.py
import RPi.GPIO as GPIO
import time
LED = 23
SW = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(SW, GPIO.IN, pull_up_down=GPIO.PUD_UP)
GPIO.setup(LED, GPIO.OUT)
# 인터럽트 발생시 호출되는 함수
def interrupt_callback(channel):
print('Interrupt :', channel)
GPIO.output(LED, True) # LED On
time.sleep(1) # 1초 대기
GPIO.output(LED, False) # LED Off
# FALLING엣지 검출 시 콜백함수 호출
GPIO.add_event_detect(SW, GPIO.FALLING, callback=interrupt_callback, bouncetime=300)
# 무한 대기..
while True:
pass<file_sep>/Python/hc-sr04.py
import RPi.GPIO as gpio
import time
gpio.setmode(gpio.BCM)
trig = 13
echo = 19
print('start')
gpio.setup(trig, gpio.OUT)
gpio.setup(echo, gpio.IN)
while True :
gpio.output(trig, False)
time.sleep(0.5)
gpio.output(trig, True)
time.sleep(0.00001)
gpio.output(trig, False)
while gpio.input(echo) == 0 :
pulse_start = time.time()
while gpio.input(echo) == 1 :
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17000
distance = round(distance, 2)
print('Distance : ', distance, 'cm')
<file_sep>/C/led_test_1.c
#include<stdlib.h>
#include<wiringPi.h>
#include<stdio.h>
#define LED_RED1 23
int main(void)
{
int frq = 100;
int i=0;
if(wiringPiSetupGpio() == -1)
return -1;
pinMode(LED_RED1,OUTPUT);
digitalWrite(LED_RED1,LOW);
while(1)
{
for(i=0;i<50;i++)
{
frq+= i*10;
digitalWrite(LED_RED1,HIGH);
delay(frq);
digitalWrite(LED_RED1,LOW);
delay(frq);
}
for(i=0;i<50;i++)
{
frq-= i*10;
digitalWrite(LED_RED1,HIGH);
delay(frq);
digitalWrite(LED_RED1,LOW);
delay(frq);
}
}
return 0;
}
<file_sep>/C/buzzer_music.c
#include <wiringPi.h>
#include <softTone.h>
#include <stdio.h>
#define BUZZER 17
#define CL1 131
#define CL2 147
#define CL3 165
#define CL4 175
#define CL5 196
#define CL6 221
#define CL7 248
#define CM1 262
#define CM2 294
#define CM3 330
#define CM4 350
#define CM5 393
#define CM6 441
#define CM7 495
#define CH1 525
#define CH2 589
#define CH3 661
#define CH4 700
#define CH5 786
#define CH6 882
#define CH7 990
int song_1[] = {CM3,CM5,CM6,CM3,CM2,CM3,CM5,CM6,CH1,CM6,CM5,CM1,CM3,CM2,
CM2,CM3,CM5,CM2,CM3,CM3,CL6,CL6,CL6,CM1,CM2,CM3,CM2,CL7,
CL6,CM1,CL5};
int beat_1[] = {1,1,3,1,1,3,1,1,1,1,1,1,1,1,3,1,1,3,1,1,1,1,1,1,1,2,1,1,
1,1,1,1,1,1,3};
int song_2[] = {CM1,CM1,CM1,CL5,CM3,CM3,CM3,CM1,CM1,CM3,CM5,CM5,CM4,CM3,CM2,
CM2,CM3,CM4,CM4,CM3,CM2,CM3,CM1,CM1,CM3,CM2,CL5,CL7,CM2,CM1
};
int beat_2[] = {1,1,1,3,1,1,1,3,1,1,1,1,1,1,3,1,1,1,2,1,1,1,3,1,1,1,3,3,2,3};
int main(void)
{
int i, j;
if(wiringPiSetupGpio() == -1)
return 1;
pinMode(BUZZER, OUTPUT); // BUZZER PIN OUTPUT SET
if(softToneCreate(BUZZER) == -1)
return 1;
while(1)
{
printf("music is being played...\n");
digitalWrite(BUZZER, LOW); // BUZZER OFF
for(i=0; i<sizeof(song_1)/4; i++)
{
softToneWrite(BUZZER, song_1[i]);
delay(beat_1[i] * 500);
}
for(i=0; i<sizeof(song_2)/4; i++)
{
softToneWrite(BUZZER, song_2[i]);
delay(beat_2[i] * 500);
}
}
return 0;
}<file_sep>/C/servo.c
#include <wiringPi.h>
#include <stdio.h>
#include <stdlib.h>
#include <softPwm.h>
#define MOTOR 6
int main(void)
{
int pos = 10 ;
int dir = 1 ;
if (wiringPiSetupGpio() == -1)
return -1; //init wiringPi
pinMode(MOTOR, OUTPUT) ; //set the 0 pin as OUTPUT
digitalWrite(MOTOR, LOW) ; //0 pin output LOW voltage
softPwmCreate(MOTOR, 0, 200) ;
//pwm initialize HIGH time 0, LOW time 200ms
while(1) {
pos += dir ;
if (pos < 10 || pos > 20) dir *= -1 ;
softPwmWrite(MOTOR, pos);
delay(500);
printf("%d\n", pos);
}
return 0 ;
}<file_sep>/Python/buzzer_music.py
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
gpio_pin = 17
scale = [ 261, 294, 329, 349, 392, 440, 493, 523 ]#도레미파솔라시도
GPIO.setup(gpio_pin, GPIO.OUT)
list = [4, 4, 5, 5, 4, 4, 2, 4, 4, 2, 2, 1]
p = GPIO.PWM(gpio_pin, 100)
p.start(100)
p.ChangeDutyCycle(90)
for i in range(12):
print (i+1)
p.ChangeFrequency(scale[list[i]])
if i == 6:
time.sleep(1)
else :
time.sleep(0.5)
p.stop()
<file_sep>/C/pwm_test_1.c
#include<stdio.h>
#include<wiringPi.h>
#include<softPwm.h>
#define LEDB 25
#define LEDR 23
#define LEDG 24
int main(void)
{
int bright = 0;
if(wiringPiSetupGpio() == -1)
return 1;
pinMode(LEDR,OUTPUT);
pinMode(LEDG,OUTPUT);
pinMode(LEDB,OUTPUT);
digitalWrite(LEDR,LOW);
digitalWrite(LEDG,LOW);
digitalWrite(LEDB,LOW);
softPwmCreate(LEDR,0,200);
softPwmCreate(LEDG,0,200);
softPwmCreate(LEDB,0,200);
int i = 0;
while(1)
{
for(i=0;i<100;i++) {
softPwmWrite(LEDR,bright);
delay(10);
bright+=2;
if(bright > 200)
bright = 0;
}
for(i=0;i<100;i++) {
softPwmWrite(LEDG,bright);
delay(10);
bright+=2;
if(bright > 200)
bright = 0;
}
for(i=0;i<100;i++) {
softPwmWrite(LEDB,bright);
delay(10);
bright+=2;
if(bright > 200)
bright = 0;
}
}
return 0;
}<file_sep>/Python/cds.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
CDS = 10
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(CDS, GPIO.IN) #GPIO23를 사용선언
while True:
if GPIO.input(CDS):
print('Bright!!!')
else:
print('Dark....')
time.sleep(0.2)<file_sep>/C/interrupt.c
#include <stdio.h>
#include <string.h>
#include <errno.h>
#include <stdlib.h>
#include <wiringPi.h>
#define INT_GPIO 18 //GPIO18(Pin12)
#define LED 23 //BCM_GPIO23(pin16)
volatile int INTcounter =0;
// GPIO_ISR: ISP 서버루틴, 이벤트가 일어날때마다 call
void GPIO_ISR(void) {
INTcounter++;
printf("Interrupt Event count = %d\n",INTcounter);
digitalWrite(LED, HIGH);
delay(1000);
digitalWrite(LED, LOW);
delay(1000);
}
int main(void) {
if (wiringPiSetupGpio() == -1)
return 1;
pinMode(LED, OUTPUT);
digitalWrite(LED, LOW);
pinMode(INT_GPIO, INPUT);
// 18번 입력 핀에 인터럽트 부착
if(wiringPiISR(INT_GPIO, INT_EDGE_FALLING, &GPIO_ISR) < 0)
{
fprintf(stderr,"Unable to setup ISR %s\n",strerror(errno));
return 1;
}
while ( 1 )
{
if(waitForInterrupt(INT_GPIO, 5000000) <1)
{
printf( "waitForInterrupt error occurred \n");
return 1;
}
return 0;
}
}
<file_sep>/C/pirMotionSensor.c
#include <stdio.h>
#include <wiringPi.h>
#define INPUT_PIN 4
int g_nPirState = LOW;
int g_nVal = 0;
int main(void)
{
if(wiringPiSetupGpio() == -1)
return 1;
pinMode(INPUT_PIN,INPUT);
while(1)
{
g_nVal = digitalRead(INPUT_PIN);
if(g_nVal == HIGH)
{
if(g_nPirState == LOW)
printf("Motion Detected!!\n");
g_nPirState = HIGH;
}
else
{
if(g_nPirState == HIGH)
printf("Motion ended.\n");
g_nPirState = LOW;
}
}
return 0;
}<file_sep>/Python/led.py
import RPi.GPIO as GPIO #GPIO를 사용하기 위해 추가
import time #time.sleep을 사용하기 위해 추가
LED_RED_1 = 23
GPIO.setmode(GPIO.BCM) #BCM을 이용하면 GPIO num으로 표시, BOARD를 이용하면 Pin num으로 표시.
GPIO.setup(LED_RED_1, GPIO.OUT) #GPIO23를 사용선언
i=0
while True:
print('LED Test :',i)
GPIO.output(LED_RED_1, True) #LED에 불이 들어옴
time.sleep(0.5) #500ms 대기
GPIO.output(LED_RED_1, False)
time.sleep(0.5) # 500ms 대기
i += 1
GPIO.cleanup() #GPIO 초기화
|
49a6c7082d97293c3970f0c4fe5b720afb8b4064
|
[
"C",
"Python"
] | 27
|
Python
|
cwal1220/RaspberryKPU
|
032308069c587db2b7b8a6b324b3716ce2dc341f
|
d6ef8ad453a28ad7abbf0f83e5af4bba380704d9
|
refs/heads/master
|
<repo_name>blurplejs/extension<file_sep>/index.js
module.exports = {
Command: require('./src/Command'),
Bot: require('./src/Bot'),
Webhook: require('./src/Webhook')
}
<file_sep>/src/Command.js
module.exports = class Command {
constructor (extension, signature) {
this.extension = extension
this.signature = this.parse(signature)
}
parse (signature) {
let argumentRegex = /{(.+?)}/g
let matches, args = []
let start = Infinity
while (matches = argumentRegex.exec(signature)) {
start = Math.min(matches.index)
args.push(match[1])
}
return {
command: signature.substring(0, start),
arguments: args
}
}
fillArguments (text) {
let list = {}
let input = text.replace(this.signature.command, '').split(' ')
for (let argument of this.signature.arguments) {
let match = []
if (match = argument.match(/(.+?)\?/)) {
// optional argument
} else if (match = argument.match(/(.+?)=(.+)/)) {
// default value
} else if (match = argument.match(/(.+?)\*/)) {
// variadic argument
}
}
return list
}
matches (message) {
let content = message.content
return this.signature.command == content
}
call (message) {
if (!this.matches(message)) {
return
}
let args = this.fillArguments(message.content)
this.handler.call(this.extension, message, args)
}
then (handler) {
this.handler = handler
return this
}
synonym (name) {
return this
}
}
<file_sep>/src/Bot.js
module.exports = class Bot {
}
|
c82d79900c7611d4e3ecadf2843ce3ab74526342
|
[
"JavaScript"
] | 3
|
JavaScript
|
blurplejs/extension
|
7bc15660e2271d3b9d045d366ddb9b944d517775
|
543e754b98685fa3c7b90626ddb15869be0f4b6c
|
refs/heads/master
|
<file_sep>/*------------------
メモ帳上での操作
------------------*/
$("#open-browser").on('click', function(){
$('#search').removeClass('hidden');
$('#memo-card').css("display" , "none");;
})
function hideWebBrowser(){
$('#search').addClass('hidden');
$('#memo-card').css("display" , "");
}
//キー入力をするとメニューに戻す
var $doc = $(document);
$doc.on('keydown', function(e){
hideWebBrowser();
})
/*------------------
Web Browser
------------------*/
//検索機能
$("#google > div").on("click",function(){
searchWords = $('#google > input').val();
postDataToPython(searchWords, 'search');
});
//詳細閲覧機能
$(document).on("click", "#search > p > a", function(){
event.preventDefault();
searchURL = $(this).attr('href');
postDataToPython(searchURL,'content');
});
function postDataToPython(search, status){
$.ajax({
type: 'POST',
url: "./php/callpy.php",
data:{
status: status,
word: search,
}
})
.then(
//Success
function(data){
$('#search').html(data);
},
function(){
alert("Webブラウザの読み込みに失敗しました");
}
);
}<file_sep>/*------------------
全体のロジック
------------------*/
var len = localStorage.length;
var memoCard = {};
var latestIdNumber;
var currentIdNumber = 1;
$(function(){
if(isLocalStorageNull){
createMemoData(1);
}
getCurrentID();
memoCard = getMemoData(1);
setMemoData();
setMenuBar();
});
/*------------------
メモ帳の関数
------------------*/
function getCurrentID(){
if(len == 0){
latestIdNumber = 1;
}else{
latestIdNumber = convertKeyToId(localStorage.key(len-1));
}
console.log("latestIdNumber:" + latestIdNumber);
}
function createMemoData(id){
id = convertIdToKey(id);
let initData = JSON.stringify({date: getDate() ,title:"タイトル",note:"本文を入力してください..."});
localStorage.setItem(id,initData);
}
function getMemoData(id){
id = convertIdToKey(id);
return JSON.parse(localStorage.getItem(id));
}
function setMemoData(){
$("#title").val(memoCard.title);
$("#note").val(memoCard.note);
}
function reloadMemoData(id){
memoCard = getMemoData(id);
id = convertIdToKey(id);
$("#title").val(memoCard.title);
$("#note").val(memoCard.note);
}
//メモ帳の追加
$("#add").on("click",function(){
latestIdNumber++;
createMemoData(latestIdNumber);
setMenuBar();
console.log("Add memo card. Latest ID Number is " + latestIdNumber);
})
function saveMemoData(){
let $change = $(this).attr("id");
memoCard[$change] = $(this).val();
memoCard.date = getDate();
localStorage.setItem(convertIdToKey(currentIdNumber), JSON.stringify(memoCard));
setMenuBar();
}
// 入力の度にローカルストレージに格納
$('#memo-card > textarea').on("input", saveMemoData);
/*------------------
メニューバー
------------------*/
function setMenuBar(){
len = localStorage.length;
var navContent = "";
for (let i=0; i<len; i++){
let key = localStorage.key(i);
let keyValue = getMemoData(key);
navContent += `<li id="${key}" class="memo-index">${keyValue.title}
<ul><li>${getStringDate(keyValue.date)}</li></ul>
<ul><li>${trimForDescription(keyValue.note)}</li></ul>
</li>`;
}
$("#memo-list").html(navContent);
}
//メニュー遷移
$(document).on("click", "#memo-list > li", function () {
key = $(this).attr("id");
reloadMemoData(key);
console.log("Move to ID:" + $(this).attr("id") + " ...");
currentIdNumber = convertKeyToId(key);
setMenuBar();
hideWebBrowser();
});
function trimForDescription(note){
const charCount = 30;
if(note.length <= charCount){
return note.slice(0,charCount);
}else{
return note.slice(0,charCount) + "...";
}
}
/*------------------
その他関数(コンバーター・NULL判定 etc.)
------------------*/
function convertKeyToId(key){
return Number(key.slice(1));
}
function convertIdToKey(id){
if(typeof id !== "string") id = "m" + id;
return id;
}
function getDate(){
let d = new Date();
return d;
}
function getStringDate(d){
d = new Date(d);
return `${d.getFullYear()}年${(d.getMonth()) + 1}月${d.getDate()}日 ${d.getHours()}:${d.getMinutes()}`;
}
function isLocalStorageNull(){
if(localStorage.length == 0) return true;
return false;
}
//全削除
$("#clear-all").on("click",function(){
if(confirm('本当に全部削除しますか?')){
localStorage.clear();
console.log("Clear All of Memo Data...")
len = 0;
createMemoData(1);
getCurrentID();
memoCard = getMemoData(1);
setMemoData();
setMenuBar();
}else{
return false;
}
});
/*------------------
今回学んだこと
■IDやClassのワイルドカード指定
http://tacosvilledge.hatenablog.com/entry/2018/05/10/141542
■JSON.stringfy
https://team-lab.github.io/skillup-nodejs/1/6.html
■読み込みごに追加したDOMにajaxを設定
https://qiita.com/negi/items/6ec0d3cedba499eac81a
https://qiita.com/horikeso/items/5f6863a49e8348f63c4b
------------------*/
<file_sep># -*- coding: utf-8 -*-
import urllib.request
from urllib.parse import parse_qsl
from urllib.parse import urlparse
from bs4 import BeautifulSoup
from requests import get as GET
import sys
# 引数を取得
args = sys.argv
argument0 = args[0]
argument1 = args[1]
argument2 = args[2]
if argument2 == 'search':
# 検索結果をスクレイピング
html = GET("https://www.google.co.jp/search?q=" + argument1).text
bs = BeautifulSoup(html, 'lxml')
for el in bs.select("h3.r a"):
title = el.get_text()
url = dict(parse_qsl(urlparse(el.get("href")).query))["q"]
print('<p><a href="' + url + '">' + title + '</a></p>')
elif argument2 == 'content':
# 内容を表示
url = argument1
data = urllib.request.urlopen(url).read()
html = data.decode('utf-8')
soup = BeautifulSoup(html, 'html.parser')
body = soup.html.body
print(body)
# PHP to Python
# https://qiita.com/minamoto_user/items/f90ceb2f88994639ca95
# 文字コードの指定
# https://teratail.com/questions/108167
# Google 検索結果
# https://teratail.com/questions/122535<file_sep><?php
$command='export LANG=ja_JP.UTF-8; /anaconda3/bin/python /Applications/XAMPP/xamppfiles/htdocs/gs/js02/homework/py/scrayping.py "'.$_POST['word'].'" "'.$_POST['status'].'"';
system($command,$output);
echo "$output";
//exec($command, $output);
//print "$output[1]\n";
?>
|
c490951e1d2457ad9e14f54006c041d5d6abd07e
|
[
"JavaScript",
"Python",
"PHP"
] | 4
|
JavaScript
|
cha1ra/localstorageHomework
|
39cf8206eca615d7615c8f47af6e9ec01001f17b
|
983c18d626fa60d2dac014884c32164fd30aee11
|
refs/heads/master
|
<file_sep>#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""CursesChat v0.3
A simple local chat system using Ncurses"""
import curses
import os
import pickle
import time
class Data:
"""Chat log data"""
def __init__(self, users=[('Adrien', 0b1110)]):
self.users = users
self.curUserId = 0
self.lastUserId = 0
self.log = {"main":[]}
self.room = 0
self.rooms = ["main"]
def addUser(self, name, color):
"""Adds a user"""
self.users.append((name, color))
def nextUser(self):
"""Switch to next user"""
self.curUserId = (self.curUserId+1) % len(self.users)
def prevUser(self):
"""Switch to previous user"""
self.curUserId = (self.curUserId-1) % len(self.users)
def curUser(self):
"""Get current user name"""
return self.users[self.curUserId][0]
def getLogOffset(self, offset, lines, room=""):
"""Get a certain amount of lines from the log, with an initial offset"""
if room=="":
room=self.rooms[self.room]
if not self.log.__contains__(room):
self.log[room] = []
self.rooms.append(room)
length = len(self.log[room])
lineList = []
if lines>length:
lineList += [['', 0, '']] * (lines - length) # Padding on the top if the log is too small (no offset accounted)
if self.log.__contains__(room):
if lines+offset>length:
lineList += self.log[room][max(0,length-lines):length]
else:
lineList += self.log[room][offset:offset+lines]
return lineList
def getLogSize(self, room=""):
"""Get log size"""
if room=="":
room=self.rooms[self.room]
if not self.log.__contains__(room):
self.log[room] = []
self.rooms.append(room)
return len(self.log[room])
def nextRoom(self):
"""Switches to the next available room"""
self.room = (self.room + 1) % len(self.rooms)
def prevRoom(self):
"""Switches to the previous available room"""
self.room = (self.room - 1) % len(self.rooms)
def appendLog(self, text, room=""):
"""Append data to log"""
if room=="":
room=self.rooms[self.room]
# Creates the room if it's a brand new one
if not self.log.__contains__(room):
self.log[room] = []
self.rooms.append(room)
self.log[room].append([time.strftime("[%F %T]"), self.curUserId, text])
def exportLog(self, filePath, room=""):
"""Export a room's log to text file"""
logFile = open(filePath, "w")
if room=="":
room=self.rooms[self.room]
# Create room if new
if not self.log.__contains__(room):
self.log[room] = []
self.rooms.append(room)
for logEntry in self.log[room]:
userName, colorId = self.users[logEntry[1]]
logFile.write("%s <\x1B[38;5;%dm%s\x1B[0m> %s\n" % (logEntry[0], colorId, userName, logEntry[2]))
logFile.close()
def exportAll(self, rootPath="."):
"""Export every room log to a file under rootPath.
RootPath must exist."""
if not os.path.isdir(rootPath+"/"):
print("ERR: {arg1} is not a valid directory".format(arg1=rootPath))
return
for room in self.log.keys():
print("\x1B[1;34m:: \x1B[37m{chan}\x1B[0m exported to \x1B[1m{root}/{chan}.log\x1B[0m".format(chan=room, root=rootPath))
self.exportLog("{root}/{chan}.log".format(root=rootPath, chan=room), room)
def importLog(self, filePath, room=""):
"""Import a text log into a new room"""
if room=="":
room=self.rooms[self.room]
if not self.log.__contains__(room):
self.log[room] = []
userDict = {name[0]:idx for idx, name in enumerate(self.users)}
if not os.path.isfile(filePath):
return
logFile = open(filePath, "r")
for logLine in logFile.readlines():
try:
# If something goes wrong with this line, jump to the next one
lineTimestamp = " ".join(logLine.split()[0:2])
userTag = logLine[len(lineTimestamp)+2:].split(">")[0]
# Get color from ansi escaped control color if present (else make it to default grey)
if userTag.find("\x1B")>=0:
userTag = userTag.split("\x1B[")[1]
userColor, userName = userTag[0:userTag.find("m")], userTag[userTag.find("m")+1:]
else:
userColor = "37"
userName = userTag
if not userDict.__contains__(userName):
# New user, get his / her color id first
userColorId = 0
# Light color 1;x or 9x
if userColor[0:2]=="1;" or (len(userColor)==1 and userColor=="1"):
if len(userColor)>1:
userColor = userColor[2:]
else:
userColor = "37"
userColorId = 0b1000
if userColor[0:1]=="9":
userColorId = 0b1000
# 256color-palette color id ?
if userColor[0:5]=="38;5;":
userColorId = int(userColor[5:])
else:
# Normal color
userColorId += int(userColor[1])
# Add user to lookup table
userDict[userName] = len(self.users)
self.users.append((userName, userColorId))
# Add (finally!!) log line
self.log[room].append([lineTimestamp, userDict[userName], logLine[logLine.find(">")+2:].replace("\n", "")])
except:
pass
logFile.close()
class Win:
def __init__(self, chatData):
"""Initiates curses"""
self.data = chatData
self.screen = curses.initscr()
curses.noecho()
curses.cbreak()
self.screen.keypad(1)
self.height, self.width = self.screen.getmaxyx()
self.offset = max(0,self.data.getLogSize() - (self.height-4))
self.hOffset = 0
self.win = curses.newwin(self.height-2, self.width, 1, 0)
self.__initWinLayouts__()
curses.start_color()
curses.use_default_colors()
# 'normal' xterm is already 256-color capable
if os.environ["TERM"].find("xterm") >= 0 or os.environ["TERM"].find("screen") >= 0:
for i in range(0, 256):
curses.init_pair(i, i, -1)
else:
for i in range(0, curses.COLORS):
curses.init_pair(i , i, -1)
def __resizeTerm__(self):
"""Resizes the terminal"""
self.height, self.width = self.screen.getmaxyx()
curses.resizeterm(self.height, self.width)
self.win = curses.newwin(self.height-2, self.width, 1, 0)
self.offset = max(0,self.data.getLogSize() - (self.height-4))
self.win.clear()
self.screen.clear()
self.__initWinLayouts__()
def __initWinLayouts__(self):
"""Draw window borders"""
self.win.clear()
self.win.border(0)
self.screen.refresh()
self.win.refresh()
def __clear__(self):
"""Clear the terminal and stop everything Curses-related"""
curses.nocbreak()
self.screen.keypad(0)
curses.echo()
curses.endwin()
def drawWindow(self):
"""Draw the windows"""
if curses.is_term_resized(self.height, self.width):
self.__resizeTerm__()
y = 0
line = 0
userw = max([len(i[0]) for i in self.data.users])
lineTextSize = len(str(self.data.getLogSize()))
maxLine = self.width - (lineTextSize+userw+25)
logSize = self.data.getLogSize()
if self.offset+self.height-4>logSize:
self.offset = max(0, logSize - (self.height-4))
self.screen.addstr(0, 0, "│", curses.color_pair(0b0111))
for roomId, room in enumerate(self.data.rooms):
self.screen.addstr(" %d:%s " % (roomId, room), curses.color_pair(0b0111 + 0x100*(room==self.data.rooms[self.data.room])))
self.screen.addch("│", curses.color_pair(0b0111))
self.screen.clrtoeol()
if self.height-4>logSize:
self.win.clear()
for lineLog in self.data.getLogOffset(self.offset, self.height-4):
if lineLog[0]=="":
self.win.addstr(1+y, 1, "~", curses.color_pair(0b1100))
else:
# line number
self.win.addstr(1+y, 1, "%*s: " % (lineTextSize, line+self.offset), curses.color_pair(0b1011))
today = (lineLog[0][1:11]==time.strftime("%F"))
# Timestamp
if today:
self.win.addstr("[" + lineLog[0][12:21], curses.color_pair(0b010))
else:
self.win.addstr(lineLog[0][0:17] + "]", curses.color_pair(0b010))
# Nickname
self.win.addstr(" %*s" % (userw, self.data.users[lineLog[1]][0]), curses.color_pair(self.data.users[lineLog[1]][1]))
# Text
self.win.addstr(' │ ' + lineLog[2][self.hOffset:min(self.hOffset+maxLine+8*(today),len(lineLog[2]))])
self.win.clrtoeol()
line += 1
y += 1
self.win.border(0)
self.drawInputWin()
self.win.refresh()
def drawInputWin(self):
"""Draw the input window"""
self.screen.addstr(self.height-1, 0, "<" + str(self.data.curUserId)+":")
self.screen.addstr(self.data.curUser(), curses.color_pair(self.data.users[self.data.curUserId][1]))
self.screen.addstr("> ")
self.screen.clrtoeol()
self.screen.refresh()
def showHelp(self):
"""Show help window"""
helpW = curses.newwin(self.height-2, self.width, 1, 0)
helpW.addstr(1, 1, "[num] G : offset (default: last line)", curses.color_pair(0b0111))
helpW.addstr(2, 1, "[num] d : delete log line (default: last line)", curses.color_pair(0b0111))
helpW.addstr(3, 1, "⇑, ⇓, ⇐, ⇒ : scroll", curses.color_pair(0b0111))
helpW.addstr(4, 1, "[num] i,Enter : insert line and optionally set user", curses.color_pair(0b0111))
helpW.addstr(5, 1, "n, p, +, - : set user", curses.color_pair(0b0111))
helpW.addstr(6, 1, "[num] TAB : switch to next room (or given room ID)", curses.color_pair(0b0111))
helpW.addstr(7, 1, "Shift TAB : switch to previous room", curses.color_pair(0b0111))
helpW.addstr(8, 1, "r : creates a new room", curses.color_pair(0b0111))
helpW.addstr(9, 1, "D : deletes current room", curses.color_pair(0b0111))
helpW.addstr(10, 1, "c : removes current room from active list (DON'T delete it)", curses.color_pair(0b0111))
helpW.addstr(11, 1, "l : list rooms", curses.color_pair(0b0111))
helpW.addstr(12, 1, "e / w : Edit or Write current room log from / to a text log file", curses.color_pair(0b0111))
helpW.addstr(13, 1, "q : exit", curses.color_pair(0b0111))
helpW.border(0)
helpW.refresh()
helpW.get_wch() # Wait a key press
del helpW
self.win.touchwin()
self.win.refresh()
def listRooms(self):
"""Show rooms list"""
userListWindow = curses.newwin(self.height-2, self.width, 1, 0)
status = ["hidden", "active"]
color = [0b111, 0b1010]
maxW = 0
xOffset = 1
indexOffset = 0
for index, roomName in enumerate(self.data.log.keys()):
if (index-indexOffset)+1 == self.height-4: #off=0 idx=9 h=10
indexOffset += self.height-4
xOffset += maxW + 1
maxW = 0
else:
txt = "[%s] %s" % (status[self.data.rooms.__contains__(roomName)], roomName)
maxW = max(maxW, len(txt))
userListWindow.insstr(index - indexOffset + 1, xOffset, txt, curses.color_pair(color[self.data.rooms.__contains__(roomName)]))
userListWindow.border(0)
userListWindow.refresh()
userListWindow.get_wch() # Wait a key press
del userListWindow
self.win.touchwin()
self.win.refresh()
def getTextLine(self):
"""Allow the user to insert a line into the chat log"""
curses.echo()
curses.curs_set(1)
self.drawInputWin()
txt = self.screen.getstr()
curses.noecho()
if len(txt)>0:
self.data.appendLog(txt.decode("utf8", errors="ignore"))
self.data.curUserId, self.data.lastUserId = self.data.lastUserId, self.data.curUserId
# Increment offset to look at end of log when you input a new line
logSize = self.data.getLogSize()
self.offset = max(0, logSize-(self.height-4))
def newRoom(self):
"""Adds a room"""
curses.echo()
curses.curs_set(1)
self.screen.addstr(self.height-1, 0, "[room name] ")
self.screen.clrtoeol()
self.screen.refresh()
txt = ""
txt = self.screen.getstr().decode("utf8", errors="ignore")
if len(txt)>0:
self.data.rooms.append(txt)
if not self.data.log.__contains__(txt):
self.data.log[txt] = []
self.data.room = len(self.data.rooms) - 1
self.offset = max(0, self.data.getLogSize() - (self.height-4))
self.__initWinLayouts__()
curses.noecho()
curses.curs_set(0)
def importExport(self, arg="export"):
"""Import from / Export to a log text file
arg: 'export' → send to file, 'import' → import from file"""
curses.echo()
curses.curs_set(1)
self.screen.addstr(self.height-1, 0, "[file name] ")
self.screen.clrtoeol()
self.screen.refresh()
txt = ""
txt = self.screen.getstr(self.width-12).decode("utf8", errors="ignore")
if len(txt)>0:
# Export
if arg=="export":
self.data.exportLog(txt)
# Import
elif arg=="import":
self.data.importLog(txt)
curses.noecho()
class App:
"""Chat app instance
cData: Data"""
def __init__(self, data = Data()):
"""Inits cData"""
self.cData = data
self.cmdHooks = {
"i": self.__cmdInsert, "\x0A": self.__cmdInsert,
"KEY_UP": self.__cmdCursor, "KEY_DOWN": self.__cmdCursor, "KEY_LEFT": self.__cmdCursor, "KEY_RIGHT": self.__cmdCursor, "KEY_PPAGE": self.__cmdCursor, "KEY_NPAGE": self.__cmdCursor, "KEY_HOME": self.__cmdCursor, "^": self.__cmdCursor, "KEY_END": self.__cmdCursor, "G": self.__cmdCursor,
" ": self.__cmdSwitchRoom, "KEY_BTAB": self.__cmdSwitchRoom,
"D": self.__cmdRoomDel, "c": self.__cmdRoomDel,
"d": self.__cmdDelLog,
"e": self.__cmdImportExport, "w": self.__cmdImportExport,
"n": self.__cmdData, "+": self.__cmdData,
"p": self.__cmdData, "-": self.__cmdData,
"r": self.__cmdData,
"h": self.__cmdData,
"l": self.__cmdData
}
def load(self, pickleFilePath="/media/hdd/Docs/Chat.pickle"):
"""Load app from a pickle file"""
if not os.path.isfile(pickleFilePath):
print("ERR: %s not found" % pickleFilePath)
return
pickleFile = open(pickleFilePath, "rb")
data = pickle.load(pickleFile)
self.cData = Data()
self.cData.users = data["users"]
self.cData.curUserId = data["curUserId"]
self.cData.lastUserId = data["lastUserId"]
self.cData.log = data["log"]
self.cData.room = data["curRoom"]
self.cData.rooms = data["roomList"]
pickleFile.close()
def save(self, pickleFilePath="/media/hdd/Docs/Chat.pickle"):
"""Save app to pickle file"""
pickleFile = open(pickleFilePath, "wb")
pickle.dump({"users": self.cData.users, "curUserId": self.cData.curUserId, "lastUserId": self.cData.lastUserId, "log": self.cData.log, "roomList": self.cData.rooms, "curRoom": self.cData.room}, pickleFile)
pickleFile.close()
def initData(self, userList=None):
"""Creates a new empty chat data storage"""
if userList != None:
self.cData = Data(userList)
else:
self.cData = Data()
def start(self):
"""Starts the main app loop"""
if self.cData==None:
self.initData()
self.cWin = Win(self.cData)
try:
chStack = ""
self.cWin.drawWindow()
while True:
curses.curs_set(0)
try:
curCh = self.cWin.screen.getkey()
except curses.error:
curCh = ""
if curses.is_term_resized(self.cWin.height, self.cWin.width):
self.cWin.__resizeTerm__()
# Escape → cancel command stack
if curCh=="\x1B":
chStack = ""
# Exit chat
elif curCh=='q':
break
# Bound character: executes associated function(s)
elif self.cmdHooks.__contains__(curCh):
self.cmdHooks[curCh](curCh, chStack)
self.cWin.drawWindow()
chStack = ""
# Print current command stack and add current character
else:
chStack += curCh
# Draw command bar
try:
self.cWin.screen.addstr(self.cWin.height-1, 0, "<"+str(self.cData.curUserId)+":")
self.cWin.screen.addstr(self.cData.users[self.cData.curUserId][0], curses.color_pair(self.cData.users[self.cData.curUserId][1]))
self.cWin.screen.addstr("> ")
self.cWin.screen.addstr(chStack.encode("latin1").decode("utf8"), curses.color_pair(0b0111))
self.cWin.screen.clrtoeol()
except UnicodeDecodeError:
pass
self.cWin.screen.refresh()
self.cWin.win.refresh()
# Clears curses windows at exit
self.cWin.__clear__()
except:
global chatInfo
from sys import exc_info
# Clears curses windows even if we crashed
self.cWin.__clear__()
chatInfo = exc_info()
print("Exception occured, see object chatInfo")
##### Internal main commands #####
def __cmdInsert(self, cur, argStr=""):
"""Insert mode"""
userId = self.cData.curUserId
try: # If number passed before, take it as user number to switch to
userId = int(argStr)
except ValueError:
pass
finally:
self.cData.curUserId = userId % len(self.cData.users)
self.cWin.getTextLine()
def __cmdCursor(self, cur, argStr=""):
"""Cursor movement"""
logSize = self.cData.getLogSize()
# Horizontal ⇐
if cur=="KEY_LEFT" and self.cWin.hOffset>=int(self.cWin.width/4):
self.cWin.hOffset -= int(self.cWin.width/4)
# Horizontal ⇒
elif cur=="KEY_RIGHT":
self.cWin.hOffset += int(self.cWin.width/4)
# Line ⇑
elif cur=="KEY_UP" and self.cWin.offset>0:
self.cWin.offset -= 1
# Line ⇓
elif cur=="KEY_DOWN" and (self.cWin.offset+self.cWin.height-4<logSize):
self.cWin.offset += 1
# Page ⇑
elif cur=="KEY_PPAGE":
self.cWin.offset = max(0, self.cWin.offset - (self.cWin.height-4))
# Page ⇓
elif cur=="KEY_NPAGE":
if self.cWin.offset + self.cWin.height-4 < logSize:
self.cWin.offset += self.cWin.height-4
if self.cWin.offset + self.cWin.height-4 > logSize:
self.cWin.offset = logSize - (self.cWin.height-4)
# Top of buffer
elif ["^", "KEY_HOME"].__contains__(cur):
self.cWin.offset = 0
# Bottom of buffer
elif cur == "KEY_END":
self.cWin.offset = logSize - (self.cWin.height-4)
# Sets buffer display offset
elif cur=="G":
lnOffset = max(0,logSize - (self.cWin.height-4))
try:
lnOffset = int(argStr)
except ValueError:
pass
finally:
self.cWin.offset = lnOffset
if (self.cWin.offset + self.cWin.height-4) > logSize:
self.cWin.offset = logSize - (self.cWin.height-4)
# Offset can't be negative
self.cWin.offset = max(0, self.cWin.offset)
def __cmdSwitchRoom(self, cur, argStr=""):
"""Switch between rooms"""
# Switch to next room
if cur==" ":
roomId = self.cData.room + 1
try:
roomId = int(argStr)
except ValueError:
pass
finally:
self.cData.room = (roomId) % len(self.cData.rooms)
self.cWin.offset = max(0, self.cData.getLogSize() - (self.cWin.height-4))
# Switch to previous room
elif cur=="KEY_BTAB":
self.cData.prevRoom()
self.cWin.__initWinLayouts__()
def __cmdRoomDel(self, cur, argStr=""):
"""Deletes current room if not the only one"""
if len(self.cData.rooms)>1:
if cur=="D":
del self.cData.log[self.cData.rooms[self.cData.room]]
del self.cData.rooms[self.cData.room]
self.cData.room = max(0, self.cData.room - 1)
self.cWin.offset = max(0, self.cData.getLogSize() - (self.cWin.height-4))
self.cWin.__initWinLayouts__()
def __cmdDelLog(self, cur, argStr=""):
"""Delete a log line"""
logSize = self.cData.getLogSize()
lnDel = logSize - 1
if logSize > 0:
try:
lnDel = min(max(int(argStr),0), logSize)
except ValueError:
pass
finally:
self.cWin.offset = max(0, logSize - (self.cWin.height-4))
del self.cData.log[self.cData.rooms[self.cData.room]][lnDel]
self.cWin.win.touchwin()
def __cmdImportExport(self, cur, argStr=""):
"""Import / Export log file"""
# e=Edit, w=Write
self.cWin.importExport({"e":"import", "w":"export"}[cur])
if cur=="e":
self.cWin.__initWinLayouts__()
def __cmdData(self, cur, argStr):
"""Commands against Chat.Data"""
if ["n", "+"].__contains__(cur):
self.cData.nextUser()
elif ["p", "-"].__contains__(cur):
self.cData.prevUser()
elif cur == "r":
self.cWin.newRoom()
elif cur == "h":
self.cWin.showHelp()
elif cur == "l":
self.cWin.listRooms()
if __name__ == "__main__":
chat = App()
chat.start()
# vim: ts=4 sts=4 sw=4 et
|
0f3e94bfc5e1b183ced100d515e76241c1336748
|
[
"Python"
] | 1
|
Python
|
adrien-s/Chat.py
|
fb00fe61060bc10177ddf05bc83daf47c47d047c
|
96a8906dfa7952421a651212e402c38fac01cc1d
|
refs/heads/main
|
<repo_name>edangx100/Dog_Tinder<file_sep>/server.js
require("dotenv").config();
const express = require("express");
const app = express();
const PORT = process.env.PORT || 3000;
const mongoose = require("mongoose");
const MONGODB_URI = process.env.MONGODB_URI;
// Mongoose connection
mongoose.connection.on("error", (err) =>
console.log(err.message + " is Mongod not running?")
);
mongoose.connection.on("disconnected", () => console.log("mongo disconnected"));
mongoose.connect(MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
});
mongoose.connection.once("open", () => {
console.log("connected to mongoose...");
});
// Middleware
app.use(express.json());
// Controllers
const usersController = require("./controllers/user");
const dogsController = require("./controllers/dog");
const likeEventsController = require("./controllers/likeEvent")
app.use("/users", usersController)
app.use("/dogs", dogsController)
app.use("/likeevents", likeEventsController)
app.listen(PORT, () => {
console.log("Matching happening on port", PORT);
});
<file_sep>/controllers/user.js
const express = require("express")
const router = express.Router()
const User = require("../models/User")
// INDEX
router.get("/", (req, res) => {
User.find({}, (err, foundUsers) => {
if (err) {
res.status(400).json({ error: err.message });
}
res.status(200).json(foundUsers);
});
});
// CREATE
router.post("/", (req, res) => {
User.create(req.body, (error, createdUser) => {
if (error) {
res.status(400).json({ error: error.message });
}
res.status(200).send(createdUser);
});
});
// ========================== //
// ========================== //
// DELETE
router.delete("/:id", (req, res) => {
User.findByIdAndRemove(req.params.id, (err, deletedUser) => {
if (err) {
res.status(400).json({ error: err.message });
}
res.status(200).json(deletedUser);
});
});
// UPDATE
router.put("/:id", (req, res) => {
User.findByIdAndUpdate(
req.params.id,
req.body,
{ new: true },
(err, updatedUser) => {
if (err) {
res.status(400).json({ error: err.message });
}
res.status(200).json(updatedUser);
}
);
});
// ========================== //
// ========================== //
router.get("/seed", (req, res) => {
User.remove({}, (error, users) => {
User.create([{
"username": "jerk13",
"password": "<PASSWORD>",
"email": "<EMAIL>",
"firstName": "Jerrick",
"lastName": "What",
"location": "N",
"type": "user",
"description": "looking for some mate for my doge",
"dog": "60fac0f512cc4a0015da2b4e",
},
{
"username": "slyguy",
"password": "<PASSWORD>",
"email": "<EMAIL>",
"firstName": "Sylvester",
"lastName": "What",
"location": "W",
"type": "user",
"description": "doge please",
"dog": "<PASSWORD>",
},
{
"username": "joyboy",
"password": "<PASSWORD>",
"email": "<EMAIL>",
"firstName": "Jay",
"lastName": "What",
"location": "C",
"type": "user",
"description": "where is a good place for dog",
"dog": "<PASSWORD>",
},
{
"username": "edddd",
"password": "<PASSWORD>",
"email": "<EMAIL>",
"firstName": "Ed",
"lastName": "What",
"location": "C",
"type": "user",
"description": "i have a big dog",
"dog": "<PASSWORD>",
}
], (err, data) => {
res.redirect("/users");
});
});
});
module.exports = router
|
c7d15cfbaf4ed98bff86abd4e5e818b0f5e37918
|
[
"JavaScript"
] | 2
|
JavaScript
|
edangx100/Dog_Tinder
|
98de3d2ef3ba5da1209fee1b46fc457e3895a861
|
222a4184fb2b9cdfc16e1e4cf94a909e875a7e2c
|
refs/heads/master
|
<file_sep>"""
Your chance to explore Loops and Turtles!
Authors: <NAME>, <NAME>, <NAME>, <NAME>,
their colleagues and <NAME>.
"""
########################################################################
# DONE: 1.
# On Line 5 above, replace PUT_YOUR_NAME_HERE with your own name.
########################################################################
########################################################################
# DONE: 2.
#
# You should have RUN the PREVIOUS module and READ its code.
# (Do so now if you have not already done so.)
#
# Below this comment, add ANY CODE THAT YOUR WANT, as long as:
# 1. You construct at least 2 rg.SimpleTurtle objects.
# 2. Each rg.SimpleTurtle object draws something
# (by moving, using its rg.Pen). ANYTHING is fine!
# 3. Each rg.SimpleTurtle moves inside a LOOP.
#
# Be creative! Strive for way-cool pictures! Abstract pictures rule!
#
# If you make syntax (notational) errors, no worries -- get help
# fixing them at either this session OR at the NEXT session.
#
# Don't forget to COMMIT your work by using VCS ~ Commit and Push.
########################################################################
import rosegraphics as rg
window = rg.TurtleWindow()
angel = rg.SimpleTurtle('turtle')
angel.pen = rg.Pen('midnight blue', 3)
angel.speed = 5
drewe = rg.SimpleTurtle('turtle')
drewe.pen = rg.Pen('pink', 3)
drewe.speed = 10
size = 100
for k in range(8):
angel.draw_circle(size)
drewe.draw_square(size)
angel.pen_up()
angel.right(45)
angel.forward(10)
angel.left(45)
angel.pen_down()
drewe.pen_up()
drewe.right(45)
drewe.forward(10)
drewe.left(45)
drewe.pen_down()
size = size - 10
window.close_on_mouse_click()
|
ad0b95c5fab919a839af441162354d331b0840f4
|
[
"Python"
] | 1
|
Python
|
riveraar/IntroductionToPython
|
be4d6bf7c347a9289a7e41e1b7dd24657ef6fdec
|
191d70e37042a455ea787f2ce0168dc4c5f5452b
|
refs/heads/main
|
<repo_name>sfc-gh-cxu/go-testmod<file_sep>/pkg/pkg.go
package pkg
import "fmt"
func Foo() {
fmt.Printf("hello\n")
}
<file_sep>/go.mod
module github.com/sfc-gh-cxu/go-testmod
go 1.15
|
8a041382f092403b561ee6e6b1b8056c0168ec34
|
[
"Go Module",
"Go"
] | 2
|
Go
|
sfc-gh-cxu/go-testmod
|
e69647ca7e4babd71daf80b4b4a8350e62def673
|
36fd99ae125034e8d3af6273d575be138925965a
|
refs/heads/master
|
<repo_name>vladislav2/MyCV<file_sep>/MyCV/CollectionVC.swift
//
// CollectionVC.swift
// MyCV
//
// Created by user on 15.04.2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
private let reuseIdentifier = "Cell"
class CollectionVC: UICollectionViewController {
let nameProjectArray = ["FifteenPuzzle", "Test task 1", "Test task 2", "Test task 3"]
let nameImageArray = ["15Puzzle", "GM", "OWMap", "apiRest"]
let descriptionProjectArray = ["It's just a Fifteen Puzzle.",
"Here GoogleMaps were added and scrolling on the map within the city limits was limited. Also added a retracting view in which you can select the options for which you need to filter the places on the map. And by pressing a button or lowering the gesture view on the map shows the places that have passed the filter.",
"This application is for the weather, there are initially 2 default cities here, the user can find and add a city from the list, see more detailed information about the weather and the forecast for 5 days. As well as the user can see the weather forecast for their geolocation.",
"Here the authorization screen is implemented and further viewing through the tableView of the list of establishments, and by clicking on the button in the cell, you can go to the URL to their website."]
let imageNameArray = [["p1", "p2"],["g1", "g2", "g3", "g4"],["w1", "w2", "w3", "w4"],["b1", "b2", "b3"]]
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let dvc = segue.destination as! ProjectVC
guard let index = collectionView.indexPathsForSelectedItems?.first?.row else { return }
dvc.nameProject = nameProjectArray[index]
dvc.descriptionProject = descriptionProjectArray[index]
dvc.imageNameArray = imageNameArray[index]
}
// MARK: UICollectionViewDataSource
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return nameProjectArray.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! CollectionViewCell
cell.imageView.image = UIImage(named: nameImageArray[indexPath.row])
cell.label.text = nameProjectArray[indexPath.row]
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
let width = self.view.bounds.width / 2 - 40
let height = width + 40
return CGSize(width: width, height: height)
}
}
<file_sep>/MyCV/ProjectVC.swift
//
// ProjectVC.swift
// MyCV
//
// Created by user on 15.04.2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class ProjectVC: UIViewController {
var nameProject = ""
var descriptionProject = ""
var imageNameArray = [""]
private var imageArray: [UIImage] = []
private var heightContentSizeImageScrollView: CGFloat = 500
@IBOutlet weak var nameProjectLabel: UILabel!
@IBOutlet weak var descriptionTextView: UITextView!
@IBOutlet weak var imageScrollView: UIScrollView!
override func viewDidLoad() {
super.viewDidLoad()
getImages()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
settingAndFillUI()
}
private func settingAndFillUI() {
nameProjectLabel.text = nameProject
descriptionTextView.text = descriptionProject
imageScrollView.bounds = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: heightContentSizeImageScrollView)
imageScrollView.contentSize = CGSize(width: self.view.bounds.width * CGFloat(imageNameArray.count), height: heightContentSizeImageScrollView)
addContentToImageScrollView()
}
private func addContentToImageScrollView() {
var imageViewRect = CGRect(x: 0, y: 0, width: imageScrollView.bounds.width, height: imageScrollView.bounds.height)
for image in imageArray {
let imageViewContent = newImageViewWithImage(image: image, frame: imageViewRect)
imageScrollView.addSubview(imageViewContent)
imageViewRect.origin.x += imageViewRect.size.width
}
}
private func getImages(){
for name in imageNameArray {
guard let image = UIImage(named: name) else { return }
imageArray.append(image)
}
}
func newImageViewWithImage(image: UIImage, frame: CGRect) -> UIImageView {
let imageView = UIImageView(frame: frame)
imageView.contentMode = .scaleAspectFit
imageView.image = image
return imageView
}
}
<file_sep>/MyCV/CollectionViewCell.swift
//
// CollectionViewCell.swift
// MyCV
//
// Created by user on 15.04.2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class CollectionViewCell: UICollectionViewCell {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var label: UILabel!
}
<file_sep>/MyCV/FirstVC.swift
//
// ViewController.swift
// MyCV
//
// Created by user on 13.04.2019.
// Copyright © 2019 <NAME>. All rights reserved.
//
import UIKit
class FirstVC: UIViewController {
private let phoneNumber = "0969351945"
private let email = "<EMAIL>"
private let webURL = "https://vk.com/id121856329"
private let skypeName = "veretennikov80"
private func contactBy(contactName: String, tag: Int) {
var idURL: URL!
switch tag {
case 1: guard let callURL = URL(string: "telprompt://\(contactName)") else { return }
idURL = callURL
case 2: guard let emailURL = URL(string: "mailto:\(contactName)") else { return }
idURL = emailURL
case 3: guard let webURL = URL(string: "\(contactName)") else { return }
idURL = webURL
case 4: guard let skypeURL = URL(string: "skype:\(contactName)") else { return }
idURL = skypeURL
default: break
}
let application:UIApplication = UIApplication.shared
if (application.canOpenURL(idURL)) {
if #available(iOS 10.0, *) {
application.open(idURL, options: [:], completionHandler: nil)
} else {
application.openURL(idURL as URL)
}
}
}
@IBAction func goToProjectsButton(_ sender: UIButton) {
performSegue(withIdentifier: "GoToAllProjects", sender: nil)
}
@IBAction func contactByContactButton(_ sender: UIButton) {
switch sender.tag {
case 1: contactBy(contactName: phoneNumber, tag: sender.tag)
case 2: contactBy(contactName: email, tag: sender.tag)
case 3: contactBy(contactName: webURL, tag: sender.tag)
case 4: contactBy(contactName: skypeName, tag: sender.tag)
default:
break
}
}
}
|
4e1acf62d3dcc7f66aae8dfdee1f18ae018daf26
|
[
"Swift"
] | 4
|
Swift
|
vladislav2/MyCV
|
4c92cc35f3f1525aaf01ff9fa8fd127e5f3f2eef
|
baca3ec115180f7d53b2425106e4a94d1d08bd14
|
refs/heads/master
|
<file_sep>console.log('artwise is so cool!');
var host = location.origin.replace(/^http/, 'ws')
var ws = new WebSocket(host);
//global variables that update mondrian
artwise = {};
artwise.data = [];
ws.onmessage = function (event) {
artwise.data = JSON.parse(event.data);
console.log(artwise.data);
};
function incrementor() {
artwise.map1++;
if (artwise.map1 > 254) {
artwise.map1 = 0
}
}
var canvas = document.getElementById("canvas1");
// attaching the sketchProc function to the canvas
var processingInstance = new Processing(canvas, sketchProc);
var i = 0;
/*
while (i < 500) {
setTimeout(function() {
incrementor();
console.log(artwise.map1);
},50*i);
i++;
}
*/
<file_sep>artwise
=======
###TOOLS SETUP
1.) Git Repo
git clone https://github.com/susannekaiser/artwise.git
2.) Install nodejs on Linux
sudo apt-get update
sudo apt-get install python-software-properties python g++ make
sudo add-apt-repository ppa:chris-lea/node.js
sudo apt-get update
sudo apt-get install nodejs
###SETUP PROJECT
```
cd artwise
npm install
npm install -g karma-cli
```
Start server
`node server.js`
Access application
`localhost:5000/app/index.html'
Start tests
`karma start`
###To run tests
`npm install -g karma karma-cli`
`karma start`
###Add credentials for contextIO
Create file `artwise/server/contextio.yml`
Content:
```
default:
contextIo:
key: xxx
secret: xxxx
```
<file_sep>/* global describe, it */
describe('Give it some context', function () {
describe('maybe a bit more context here', function () {
it('should run here few assertions', function () {
var message = { date: 1402152565 };
expect(moment().diff(moment(message.date, 'X'), 'days')).toBe(0);
message.date = 1402056732;
// yesterday: 1
expect(moment().diff(moment(message.date, 'X'), 'days')).toBe(1);
// message.date = 1202056732;
// expect(moment().diff(moment(message.date, 'X'), 'days')).toBe(1);
});
});
});
<file_sep>var _ = require('lodash');
var moment = require('moment');
var old = moment().subtract('days', 3);
var yesterday = moment().subtract('days', 1);
var today = moment();
var fakeEmails;
exports.init = function() {
};
exports.readEmail = function(callback, callbackParameter) {
fakeEmails = [];
_.times(GLOBAL.TODAY_INTERNAL || 20, createInternalToday);
_.times(GLOBAL.TODAY_EXTERNAL || 10, createExternalToday);
_.times(4, createInternalYesterday);
_.times(21, createExternalYesterday);
_.times(4, createInternalOld);
_.times(4, createExternalOld);
callback(fakeEmails, callbackParameter);
};
function createInternalToday() {
fakeEmails.push( { addresses: { from: { email: '<EMAIL>' }},
flags: [],
date: today });
}
function createExternalToday() {
fakeEmails.push( { addresses: { from: { email: '<EMAIL>' }},
flags: [],
date: today });
}
function createInternalYesterday() {
fakeEmails.push( { addresses: { from: { email: '<EMAIL>' }},
flags: [],
date: yesterday });
}
function createExternalYesterday() {
fakeEmails.push( { addresses: { from: { email: '<EMAIL>' }},
flags: [],
date: yesterday });
}
function createInternalOld() {
fakeEmails.push( { addresses: { from: { email: '<EMAIL>' }},
flags: [],
date: old });
}
function createExternalOld() {
fakeEmails.push( { addresses: { from: { email: '<EMAIL>' }},
flags: [],
date: old });
}
exports.getAccountInfo = function(callback, callbackParameter) {
callback( { email_adresses: [ '<EMAIL>'] }, callbackParameter);
};
|
72a5d34852b740cdd2d8e220e01511a309656827
|
[
"JavaScript",
"Markdown"
] | 4
|
JavaScript
|
jvdheyden/artwise
|
ab98785e933386b105bb36a05576c91900ac5312
|
f8d04daeaa63b8bc40e088c3b6ae2510cf47871d
|
refs/heads/main
|
<file_sep>val zero = 0
val message = "Hello world !"
fun sayHello() = "hello everyone"
private lateinit var answer: String
private val question = "What is your name?"
fun main(args: Array<String>) {
println(question)
answer = "akahito"
println("Your name is $answer")
}
// $
// What is your name?
// Your name is akahito
// Statementではなく、Expression
var kotlinVariable: String = when (var fortuneParams) {
"0" -> "大吉"
"1" -> "中吉"
"2" -> "小吉"
else -> "吉"
}
println(kotlinVariable)
// 大吉
// SQL文と可読性
var sql: String = "INSERT INTO customer_list (first_name, last_name, age) VALUES ('Wilman', 'Kala', '23')"
var organizedSQL: String = "INSERT INTO "
organizedSQL += "product_list (item, name, price) "
organizedSQL += "VALUES ('vaporizer', 'eGo ONE', '4,000')"
// INSERT INTO product_list (item, name, price) VALUES ('vaporizer', 'eGo ONE', '4,000')
// create function on Kotlin
fun main(args: Array<String>) {
println("Hello, World")
}
// the function's parameters are separated by commas
// and to return an Int type value, the colon ":" is gonna be used at the end
private fun minOf(a: Int, b: Int): Int {
return if (a<b) a else b
}
// in Kotlin, most control structures are expressions but statements
// like even "Hello World" actually returns a "Unit" typed value; the default type created by Kotlin
// also the "Unit" type corresponds to "void" in Java
fun main(args: Array<String>) {
println("Hello world!")
}
var hello: Unit = main(arrayOf(""))
// functions of readability
// "=" is better than : Type and { braces }
fun sayHello(): Unit { println("Hello") }
fun sayHello(): Unit = println("Hello")
fun sayHello() = println("Hello")
// another example
fun getUrlApi() { return "http://www.nogoodreadability.api.com" }
fun getUrlApi(): String { return "http://www.notbad.api.com" }
fun getUtlApi() = "http://www.mr.readability.api.com"
// question
fun main(args: Array<String>) {
// write code here!
println("Welcome OpenClassrooms Students!")
fun addNumbers(a: Int, b: Int) = a + b
fun getUsernameUpperCase(username: String) = username.toUpperCase()
fun isUsernameOfTeacher(username: String) = if (username == "Phil" || username == "George") true else false
println(addNumbers(1, 2))
println(getUsernameUpperCase("Phil"))
println(isUsernameOfTeacher("Phil"))
}
// declare functions out of scope of main
fun addNumbers(a: Int, b: Int) = a + b
fun getUsernameUpperCase(username: String) = username.toUpperCase()
// if expressions can be more readable like... only below
fun isUsernameOfTeacher(username: String) = username == "Phil" || username == "George"
fun main(args: Array<String>) {
println("Result is ${addNumbers(21, 21)}.") // 42
println("username to uppercase : ${getUsernameUpperCase("phil")}.") // PHIL
println("teacher? : ${isUsernameOfTeacher("Phil")}.") // true
}
|
f9aabdc5e1d94445b00bd173105b27a2b12e9611
|
[
"Kotlin"
] | 1
|
Kotlin
|
akahito1006/ocr_kt
|
1287fa372029dbd2a5cae6235fc997b57e6c9a4e
|
37ddbf007574f52001b02978d8e112bf8bf1e2ea
|
refs/heads/master
|
<file_sep>Denna primtalsfaktorisator var skapad av <NAME> (19BEHE)
för användning av Stockholm Science and Innovation School<file_sep>
from __future__ import division
import math
while True:
def primenumbers(x):
while x % 2 == 0:
print(2)
x = x / 2
for i in range(3, int(math.sqrt(x)) + 1, 2):
while x % i == 0:
print(i)
x = x / i
if x > 2:
print(int(x))
x1 = int(input("skriv talet du vill faktorisera :"))
primenumbers(x1)
|
2552426c88e861e9a8252a405a58f38aa7072d3e
|
[
"Python",
"Text"
] | 2
|
Text
|
TheGoldenCow/Primtalsfaktoriseraren
|
30da691df93a24c3c95ba4dac30436221a78f708
|
8419e685632d8eb118ab3685eb969cf339b94778
|
refs/heads/master
|
<file_sep>---
title: "Remote FASTER - Basics"
permalink: /docs/remote-basics/
excerpt: "Remote FASTER"
last_modified_at: 2021-04-12
toc: false
classes: wide
---
Details coming soon!
<file_sep>// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license.
using FASTER.core;
using System;
using System.Threading;
namespace MemOnlyCache
{
public class CacheSizeTracker : IObserver<IFasterScanIterator<CacheKey, CacheValue>>
{
readonly FasterKV<CacheKey, CacheValue> store;
long storeSize;
public long TotalSize => storeSize + store.OverflowBucketCount * 64;
public CacheSizeTracker(FasterKV<CacheKey, CacheValue> store, int memorySizeBits)
{
this.store = store;
storeSize = store.IndexSize * 64;
storeSize += 1L << memorySizeBits;
// Register subscriber to receive notifications of log evictions from memory
store.Log.SubscribeEvictions(this);
}
public void AddSize(int size) => Interlocked.Add(ref storeSize, size);
public void OnCompleted() { }
public void OnError(Exception error) { }
public void OnNext(IFasterScanIterator<CacheKey, CacheValue> iter)
{
int size = 0;
while (iter.GetNext(out RecordInfo info, out CacheKey key, out CacheValue value))
{
size += key.GetSize;
if (!info.Tombstone) // ignore deleted records being evicted
size += value.GetSize;
}
Interlocked.Add(ref storeSize, -size);
}
}
}
<file_sep>using FASTER.core;
using Xunit;
using System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
namespace AsyncStress
{
public class FasterWrapper<Key, Value>
{
readonly FasterKV<Key, Value> _store;
readonly AsyncPool<ClientSession<Key, Value, Value, Value, Empty, SimpleFunctions<Key, Value, Empty>>> _sessionPool;
// OS Buffering is safe to use in this app because Reads are done after all updates
internal static bool useOsReadBuffering = false;
public FasterWrapper()
{
var logDirectory ="d:/FasterLogs";
var logFileName = Guid.NewGuid().ToString();
var logSettings = new LogSettings
{
LogDevice = new ManagedLocalStorageDevice(Path.Combine(logDirectory, $"{logFileName}.log"), deleteOnClose: true, osReadBuffering: useOsReadBuffering),
ObjectLogDevice = new ManagedLocalStorageDevice(Path.Combine(logDirectory, $"{logFileName}.log"), deleteOnClose: true, osReadBuffering: useOsReadBuffering),
PageSizeBits = 12,
MemorySizeBits = 13
};
Console.WriteLine($" Using {logSettings.LogDevice.GetType()}");
_store = new FasterKV<Key, Value>(1L << 20, logSettings);
_sessionPool = new AsyncPool<ClientSession<Key, Value, Value, Value, Empty, SimpleFunctions<Key, Value, Empty>>>(
logSettings.LogDevice.ThrottleLimit,
() => _store.For(new SimpleFunctions<Key, Value, Empty>()).NewSession<SimpleFunctions<Key, Value, Empty>>());
}
// This can be used to verify the same amount data is loaded.
public long TailAddress => _store.Log.TailAddress;
// Indicates how many operations went pending
public int UpsertPendingCount = 0;
public int ReadPendingCount = 0;
public async ValueTask UpsertAsync(Key key, Value value)
{
if (!_sessionPool.TryGet(out var session))
session = await _sessionPool.GetAsync();
var r = await session.UpsertAsync(key, value);
while (r.Status == Status.PENDING)
{
Interlocked.Increment(ref UpsertPendingCount);
r = await r.CompleteAsync();
}
_sessionPool.Return(session);
}
public void Upsert(Key key, Value value)
{
if (!_sessionPool.TryGet(out var session))
session = _sessionPool.GetAsync().GetAwaiter().GetResult();
var status = session.Upsert(key, value);
if (status == Status.PENDING)
{
// This should not happen for sync Upsert().
Interlocked.Increment(ref UpsertPendingCount);
session.CompletePending();
}
_sessionPool.Return(session);
}
public async ValueTask UpsertChunkAsync((Key, Value)[] chunk)
{
if (!_sessionPool.TryGet(out var session))
session = _sessionPool.GetAsync().GetAwaiter().GetResult();
for (var ii = 0; ii < chunk.Length; ++ii)
{
var r = await session.UpsertAsync(chunk[ii].Item1, chunk[ii].Item2);
while (r.Status == Status.PENDING)
{
Interlocked.Increment(ref UpsertPendingCount);
r = await r.CompleteAsync();
}
}
_sessionPool.Return(session);
}
public async ValueTask<(Status, Value)> ReadAsync(Key key)
{
if (!_sessionPool.TryGet(out var session))
session = await _sessionPool.GetAsync();
var result = (await session.ReadAsync(key).ConfigureAwait(false)).Complete();
_sessionPool.Return(session);
return result;
}
public ValueTask<(Status, Value)> Read(Key key)
{
if (!_sessionPool.TryGet(out var session))
session = _sessionPool.GetAsync().GetAwaiter().GetResult();
var result = session.Read(key);
if (result.status == Status.PENDING)
{
Interlocked.Increment(ref ReadPendingCount);
session.CompletePendingWithOutputs(out var completedOutputs, wait: true);
int count = 0;
for (; completedOutputs.Next(); ++count)
{
Assert.Equal(key, completedOutputs.Current.Key);
result = (Status.OK, completedOutputs.Current.Output);
}
completedOutputs.Dispose();
Assert.Equal(1, count);
}
_sessionPool.Return(session);
return new ValueTask<(Status, Value)>(result);
}
public async ValueTask ReadChunkAsync(Key[] chunk, ValueTask<(Status, Value)>[] results, int offset)
{
if (!_sessionPool.TryGet(out var session))
session = _sessionPool.GetAsync().GetAwaiter().GetResult();
// Reads in chunk are performed serially
for (var ii = 0; ii < chunk.Length; ++ii)
results[offset + ii] = new ValueTask<(Status, Value)>((await session.ReadAsync(chunk[ii])).Complete());
_sessionPool.Return(session);
}
public async ValueTask<(Status, Value)[]> ReadChunkAsync(Key[] chunk)
{
if (!_sessionPool.TryGet(out var session))
session = _sessionPool.GetAsync().GetAwaiter().GetResult();
// Reads in chunk are performed serially
(Status, Value)[] result = new (Status, Value)[chunk.Length];
for (var ii = 0; ii < chunk.Length; ++ii)
result[ii] = (await session.ReadAsync(chunk[ii]).ConfigureAwait(false)).Complete();
_sessionPool.Return(session);
return result;
}
public void Dispose()
{
_sessionPool.Dispose();
_store.Dispose();
}
}
}
<file_sep>---
title: "Remote FASTER - Samples"
permalink: /docs/remote-samples/
excerpt: "Remote FASTER Samples"
last_modified_at: 2021-04-12
toc: false
classes: wide
---
Samples coming soon!
<file_sep>using System;
using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;
using FASTER.core;
using System.Linq;
namespace AsyncStress
{
public class Program
{
// ThreadingMode descriptions are listed in Usage()
enum ThreadingMode
{
None,
Single,
ParallelAsync,
ParallelSync,
Chunks
}
static ThreadingMode upsertThreadingMode = ThreadingMode.ParallelAsync;
static ThreadingMode readThreadingMode = ThreadingMode.ParallelAsync;
static int numTasks = 4;
static int numOperations = 1_000_000;
static void Usage()
{
Console.WriteLine($"Options:");
Console.WriteLine($" -u <mode>: Upsert threading mode (listed below); default is {ThreadingMode.ParallelAsync}");
Console.WriteLine($" -r <mode>: Read threading mode (listed below); default is {ThreadingMode.ParallelAsync}");
Console.WriteLine($" -t #: Number of tasks for {ThreadingMode.ParallelSync} and {ThreadingMode.Chunks}; default is {numTasks}");
Console.WriteLine($" -n #: Number of operations; default is {numOperations}");
Console.WriteLine($" -b #: Use OS buffering for reads; default is {FasterWrapper<int, int>.useOsReadBuffering}");
Console.WriteLine($" -?, /?, --help: Show this screen");
Console.WriteLine();
Console.WriteLine($"Threading Modes:");
Console.WriteLine($" None: Do not run this operation");
Console.WriteLine($" Single: Run this operation single-threaded");
Console.WriteLine($" ParallelAsync: Run this operation using Parallel.For with an Async lambda");
Console.WriteLine($" ParallelSync: Run this operation using Parallel.For with an Sync lambda and parallelism limited to numTasks");
Console.WriteLine($" Chunks: Run this operation using a set number of async tasks to operate on partitioned chunks");
}
public static async Task Main(string[] args)
{
if (args.Length > 0)
{
for (var ii = 0; ii < args.Length; ++ii)
{
var arg = args[ii];
string nextArg()
{
var next = ii < args.Length - 1 && args[ii + 1][0] != '-' ? args[++ii] : string.Empty;
if (next.Length == 0)
throw new ApplicationException($"Need arg value for {arg}");
return next;
}
if (arg == "-u")
upsertThreadingMode = Enum.Parse<ThreadingMode>(nextArg(), ignoreCase: true);
else if (arg == "-r")
readThreadingMode = Enum.Parse<ThreadingMode>(nextArg(), ignoreCase: true);
else if (arg == "-t")
numTasks = int.Parse(nextArg());
else if (arg == "-n")
numOperations = int.Parse(nextArg());
else if (arg == "-b")
FasterWrapper<int, int>.useOsReadBuffering = true;
else if (arg == "-?" || arg == "/?" || arg == "--help")
{
Usage();
return;
}
else
throw new ApplicationException($"Unknown switch: {arg}");
}
}
await ProfileStore(new FasterWrapper<int, int>());
}
private static async Task ProfileStore(FasterWrapper<int, int> store)
{
static string threadingModeString(ThreadingMode threadingMode)
=> threadingMode switch
{
ThreadingMode.Single => "Single threading",
ThreadingMode.ParallelAsync => "Parallel.For using async lambda",
ThreadingMode.ParallelSync => $"Parallel.For using sync lambda and {numTasks} tasks",
ThreadingMode.Chunks => $"Chunks partitioned across {numTasks} tasks",
_ => throw new ApplicationException("Unknown threading mode")
};
int chunkSize = numOperations / numTasks;
// Insert
if (upsertThreadingMode == ThreadingMode.None)
{
throw new ApplicationException("Cannot Skip Upserts");
}
else
{
Console.WriteLine($" Inserting {numOperations} records with {threadingModeString(upsertThreadingMode)} ...");
var sw = Stopwatch.StartNew();
if (upsertThreadingMode == ThreadingMode.Single)
{
for (int i = 0; i < numOperations; i++)
await store.UpsertAsync(i, i);
}
else if (upsertThreadingMode == ThreadingMode.ParallelAsync)
{
var writeTasks = new ValueTask[numOperations];
Parallel.For(0, numOperations, key => writeTasks[key] = store.UpsertAsync(key, key));
foreach (var task in writeTasks)
await task;
}
else if (upsertThreadingMode == ThreadingMode.ParallelSync)
{
// Without throttling parallelism, this ends up very slow with many threads waiting on FlushTask.
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = numTasks };
Parallel.For(0, numOperations, parallelOptions, key => store.Upsert(key, key));
}
else
{
Debug.Assert(upsertThreadingMode == ThreadingMode.Chunks);
var chunkTasks = new ValueTask[numTasks];
for (int ii = 0; ii < numTasks; ii++)
{
var chunk = new (int, int)[chunkSize];
for (int i = 0; i < chunkSize; i++) chunk[i] = (ii * chunkSize + i, ii * chunkSize + i);
chunkTasks[ii] = store.UpsertChunkAsync(chunk);
}
foreach (var chunkTask in chunkTasks)
await chunkTask;
}
sw.Stop();
Console.WriteLine($" Insertion complete in {sw.ElapsedMilliseconds} ms; TailAddress = {store.TailAddress}, Pending = {store.UpsertPendingCount}");
}
// Read
Console.WriteLine();
if (readThreadingMode == ThreadingMode.None)
{
Console.WriteLine(" Skipping Reads");
}
else
{
Console.WriteLine($" Reading {numOperations} records with {threadingModeString(readThreadingMode)} (OS buffering: {FasterWrapper<int, int>.useOsReadBuffering}) ...");
var readTasks = new ValueTask<(Status, int)>[numOperations];
var readPendingString = string.Empty;
var sw = Stopwatch.StartNew();
if (readThreadingMode == ThreadingMode.Single)
{
for (int ii = 0; ii < numOperations; ii++)
{
readTasks[ii] = store.ReadAsync(ii);
await readTasks[ii];
}
}
else if (readThreadingMode == ThreadingMode.ParallelAsync)
{
Parallel.For(0, numOperations, key => readTasks[key] = store.ReadAsync(key));
foreach (var task in readTasks)
await task;
}
else if (readThreadingMode == ThreadingMode.ParallelSync)
{
// Without throttling parallelism, this ends up very slow with many threads waiting on completion.
var parallelOptions = new ParallelOptions { MaxDegreeOfParallelism = numTasks };
Parallel.For(0, numOperations, parallelOptions, key => readTasks[key] = store.Read(key));
foreach (var task in readTasks)
await task;
readPendingString = $"; Pending = {store.ReadPendingCount}";
}
else
{
var chunkTasks = Enumerable.Range(0, numTasks).Select(ii =>
{
var chunk = new int[chunkSize];
for (int i = 0; i < chunkSize; i++) chunk[i] = ii * chunkSize + i;
return store.ReadChunkAsync(chunk, readTasks, ii * chunkSize);
}).ToArray();
foreach (var chunkTask in chunkTasks)
await chunkTask;
}
sw.Stop();
Console.WriteLine($" Reads complete in {sw.ElapsedMilliseconds} ms{readPendingString}");
// Verify
Console.WriteLine(" Verifying read results ...");
Parallel.For(0, numOperations, key =>
{
(Status status, int? result) = readTasks[key].Result;
Assert.Equal(Status.OK, status);
Assert.Equal(key, result);
});
Console.WriteLine(" Results verified");
}
store.Dispose();
}
}
}
|
53ae1288e91729ec4eabf7971ebd8a07f52b8fb0
|
[
"Markdown",
"C#"
] | 5
|
Markdown
|
tommydb/FASTER
|
844dc8ae81e16999b25641648176de6fa35c2fe0
|
6dacbdafbdced460fdf7a09f909701dc1828865f
|
refs/heads/master
|
<file_sep># my dev box my setup
zsh:
# install zsh
brew install zsh
chsh -s /bin/zsh # change default shell
# install oh-my-zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
ln -s ~/dotfiles/zsh/dato-af-magic.zsh-theme ~/.oh-my-zsh/themes/
mv ~/.zshrc ~/.zshrc.pre-setup
ln -s ~/dotfiles/zsh/zshrc ~/.zshrc
# auto-suggestions plugin
git clone https://github.com/zsh-users/zsh-autosuggestions.git $ZSH_CUSTOM/plugins/zsh-autosuggestions
# syntax highlighting
git clone https://github.com/zsh-users/zsh-syntax-highlighting.git $ZSH_CUSTOM/plugins/zsh-syntax-highlighting
bash:
# setup terminal profile
ln -s ~/dotfiles/bash_profile.home ~/.bash_profile
vim:
# vim setup
ln -s ~/dotfiles/vim/vimrc ~/.vimrc
vim-no-plugins:
mv ~/.vimrc ~/.vimrc.bak
ln -s /dotfiles/vim/vimrc.no_plugins ~/.vimrc
emaces:
# emacs
ln -s ~/dotfiles/emacs/emacs ~/.emacs
ln -s ~/dotfiles/emacs/emacs.d ~/.emacs.d
git:
# my git setup
ln -s ~/dotfiles/git/gitignore_global ~/.gitignore_global
devbox:
# build devbox with built-in VSCode IDE etc
cd ~/dotfiles/devbox && docker build -t dato/devbox -f Dockerfile.devbox .
# dev:
# cd $$HOME/dotfiles/devbox && docker build -t dato/devbox -f Dockerfile.devbox .
devbox-start: devbox-stop
docker run -d \
--name=devbox \
-p 8080:8080 \
-e PUID="$(id -u)" \
-e PGID="$(id -g)" \
-v "${HOME}/.config/code-server/settings.json:/codeserver/data/User/settings.json" \
-v "${PWD}:/workspace" \
dato/devbox
sleep 3
open -a Safari http://0.0.0.0:8080
devbox-stop:
docker stop devbox; docker rm devbox > /dev/null || true
<file_sep>#!/bin/bash
apt-get update
apt-get install -y vim
# ln -s /dotfiles/vim/vimrc.simple ~/.vimrc
ln -s ~/dotfiles/vim/vimrc.no_plugins ~/.vimrc
<file_sep>#!/bin/bash
# dev box my setup
# install zsh
brew install zsh
chsh -s /bin/zsh # change default shell
# install oh-my-zsh
sh -c "$(curl -fsSL https://raw.github.com/ohmyzsh/ohmyzsh/master/tools/install.sh)"
ln -s ~/dotfiles/zsh/dato-af-magic.zsh-theme ~/.oh-my-zsh/themes/
mv ~/.zshrc ~/.zshrc.pre-setup
ln -s ~/dotfiles/zsh/zshrc ~/.zshrc
# setup terminal profile
ln -s ~/dotfiles/bash_profile.home ~/.bash_profile
# vim
ln -s ~/dotfiles/vim/vimrc ~/.vimrc
# emacs
ln -s ~/dotfiles/emacs/emacs ~/.emacs
ln -s ~/dotfiles/emacs/emacs.d ~/.emacs.d
# git
ln -s ~/dotfiles/git/gitignore_global ~/.gitignore_global
# vscode build
cd ~/dotfiles/devbox && docker build -t dato/devbox -f Dockerfile.devbox .
|
fa3d329cae6baa8b1b91986ef7d5b308c8f5e666
|
[
"Makefile",
"Shell"
] | 3
|
Makefile
|
proteos/dotfiles
|
4ba2abce94861e24853dfa122d0f51decf685b92
|
17e38a36e1d15871d8e2940e5521c04d53f9440c
|
refs/heads/master
|
<repo_name>ayrus-surya/wt2-data-visualizer<file_sep>/home/index.php
<html>
<script>
<?php
echo "parent.obj.response('hello')"
?>
</script>
</html>
|
d2f0f3e687c07682716d7a7d2b157e3296b15a81
|
[
"PHP"
] | 1
|
PHP
|
ayrus-surya/wt2-data-visualizer
|
718085706437d7f8177d5ae221b45714f86467d2
|
70413130355c5ed2079406873012e00343169633
|
refs/heads/master
|
<file_sep>this.Lifts = React.createClass({
getInitialState: function() {
return {
lifts: this.props.data
};
},
getDefaultProps: function() {
return {
lifts: []
};
},
addLift: function(lift) {
var lifts;
lifts = this.state.lifts.slice();
lifts.push(lift);
return this.setState({
lifts: lifts
});
},
render: function() {
var lift;
return React.DOM.div({
className: 'lifts'
}, React.DOM.h1({
className: 'title'
}, 'Lifts'), React.createElement(LiftForm, {
handleNewLift: this.addLift
}), React.DOM.table({
className: 'table table-bordered'
}, React.DOM.thead(null), React.DOM.th(null, 'Date'), React.DOM.th(null, 'Lift Name'), React.DOM.th(null, 'Weight Lifted'), React.DOM.th(null, 'Reps Performed'), React.DOM.th(null, '1 RM'), React.DOM.tbody(null, (function() {
var i, len, ref, results;
ref = this.state.lifts;
results = [];
for (i = 0, len = ref.length; i < len; i++) {
lift = ref[i];
results.push(React.createElement(Lift, {
key: lift.id,
lift: lift
}));
}
return results;
}).call(this))));
}
});
<file_sep>this.Lift = React.createClass({
render: function() {
return React.DOM.tr(null,
React.DOM.td(null, this.props.lift.date),
React.DOM.td(null, this.props.lift.liftname),
React.DOM.td(null, this.props.lift.weightlifted),
React.DOM.td(null, this.props.lift.repsperformed),
React.DOM.td(null, this.props.lift.onerm));
}
});
<file_sep>this.LiftForm = React.createClass({
getInitialState: function() {
return {
date: '',
liftname: '',
ismetric: '',
weightlifted: '',
repsperformed: '',
onerm: ''
};
},
handleValueChange: function(e) {
var obj, valueName;
valueName = e.target.name;
return this.setState((
obj = {},
obj["" + valueName] = e.target.value,
obj
));
},
valid: function() {
return this.state.date && this.state.liftname && this.state.ismetric && this.state.weightlifted && this.state.repsperformed && this.state.onerm;
},
handleSubmit: function(e) {
e.preventDefault();
return $.post('', {
lift: this.state
}, (function(_this) {
return function(data) {
_this.props.handleNewLift(data);
return _this.setState(_this.getInitialState());
};
})(this), 'JSON');
},
render: function() {
return React.DOM.form({
className: 'form-inline',
onSubmit: this.handleSubmit
}, React.DOM.div({
className: 'form-group'
}, React.DOM.input({
type: 'date',
className: 'form-control',
placeholder: 'date',
name: 'date',
value: this.state.date,
onChange: this.handleValueChange
}), React.DOM.input({
type: 'text',
className: 'form-control',
placeholder: 'liftname',
name: 'liftname',
value: this.state.liftname,
onChange: this.handleValueChange
}), React.DOM.input({
type: 'boolean',
className: 'form-control',
placeholder: 'ismetric',
name: 'ismetric',
value: this.state.ismetric,
onChange: this.handleValueChange
}), React.DOM.input({
type: 'number',
className: 'form-control',
placeholder: 'weightlifted',
name: 'weightlifted',
value: this.state.weightlifted,
onChange: this.handleValueChange
}), React.DOM.input({
type: 'number',
className: 'form-control',
placeholder: 'repsperformed',
name: 'repsperformed',
value: this.state.repsperformed,
onChange: this.handleValueChange
}), React.DOM.input({
type: 'number',
className: 'form-control',
placeholder: 'onerm',
name: 'onerm',
value: this.state.onerm,
onChange: this.handleValueChange
}), React.DOM.button({
type: 'submit',
className: 'btn btn-primary',
disabled: !this.valid()
}, 'Create Lift')));
}
});
|
64fec36af88bc1768742382bf19991e324b8a87d
|
[
"JavaScript"
] | 3
|
JavaScript
|
TorchLabs/react-rails-wrapper
|
d24f7142f3fdf26ad3f86b00dc6cce0f631c77a9
|
835bda173f78ed6b164a0009e769d5d69c144300
|
refs/heads/master
|
<file_sep>from django.urls import path
app_name = 'experiments'
from .views import ExperimentListView
urlpatterns = [
path('', ExperimentListView.as_view(), name='home')
]<file_sep>from django.views.generic.list import ListView
from .models import Experiment
class ExperimentListView(ListView):
model = Experiment<file_sep>CESS Experiment Administration Portal
=====================================
<file_sep>from django.contrib import admin
from django.contrib.auth.models import Group
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin as BaseUserAdmin
from .forms import UserAdminCreationForm, UserAdminChangeForm
User = get_user_model()
class UserAdmin(BaseUserAdmin):
form = UserAdminChangeForm
add_form = UserAdminCreationForm
# Display Fields
list_display = (
'email', 'is_admin', 'is_researcher', 'is_student', 'is_active',
'is_confirmed')
list_filter = ('is_admin',)
fieldsets = (
(None, {'fields': ('email', 'password',)}),
('Personal info', {'fields': ('first_name', 'last_name', )}),
('Permissions', {'fields': ('is_admin', 'is_researcher', 'is_student',
'is_active', 'is_confirmed',)}),
)
# Add User Fields
add_fieldsets = (
(None, {
'classes': ('wide',),
'fields': ('email', 'first_name', 'last_name', '<PASSWORD>',
'<PASSWORD>')}
),
)
search_fields = ('email',)
ordering = ('email',)
filter_horizontal = ()
admin.site.register(User, UserAdmin)
# Remove Group Model from admin. We're not using it.
admin.site.unregister(Group)
<file_sep>from django.db import models
from django.contrib.auth import get_user_model
from model_utils.models import TimeStampedModel
User = get_user_model()
class Location(TimeStampedModel):
address = models.CharField(max_length=255, blank=False)
slug = models.CharField(max_length=255, unique=True)
class UniversityDepartment(TimeStampedModel):
name = models.CharField(max_length=255)
def __str__(self):
return self.name
class ResearcherProfile(TimeStampedModel):
user = models.ForeignKey(User, on_delete=models.CASCADE)
department = models.ForeignKey(
UniversityDepartment, on_delete=models.CASCADE)
def __str__(self):
return self.first_name + " " + self.last_name
class Experiment(TimeStampedModel):
researchers = models.ManyToManyField(User)
name = models.CharField(max_length=255)
human_subject_id = models.CharField(max_length=255, blank=False)
def __str__(self):
return self.name
class Session(TimeStampedModel):
location = models.ForeignKey(Location, on_delete=models.CASCADE)
experiment = models.ForeignKey(Experiment, on_delete=models.CASCADE)
session_number = models.PositiveIntegerField(default=0)
start_time = models.DateTimeField(blank=False)
end_time = models.DateTimeField(blank=False)
def __str__(self):
return "Session {} ({}-{})".format(
self.start_time.strftime("%m%d%Y%H%M"))
<file_sep># Generated by Django 2.0.3 on 2018-03-23 18:24
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('accounts', '0005_auto_20180323_1411'),
]
operations = [
migrations.AddField(
model_name='user',
name='first_name',
field=models.CharField(default='Peter', max_length=255),
preserve_default=False,
),
migrations.AddField(
model_name='user',
name='last_name',
field=models.CharField(default='Lastly', max_length=255),
preserve_default=False,
),
]
<file_sep>from django.db import models
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin)
class UserManager(BaseUserManager):
def create_user(self, email, first_name, last_name, password=None, is_active=True,
is_researcher=False, is_student=False, is_admin=False,
is_confirmed=True):
if not email:
raise ValueError("User must have an email address")
if not password:
raise ValueError("User must have a password")
if not first_name:
raise ValueError("User must have a first_name")
if not last_name:
raise ValueError("User must have a last_name")
user = self.model(
email=self.normalize_email(email), first_name=first_name,
last_name=last_name)
user.set_password(password)
user.is_active = is_active
user.is_researcher = is_researcher
user.is_student = is_student
user.is_admin = is_admin
user.is_confirmed = is_confirmed
user.save(using=self._db)
return user
def create_superuser(self, email, password, first_name, last_name):
user = self.create_user(
email,
password=<PASSWORD>,
is_admin=True,
is_researcher=True,
first_name=first_name,
last_name=last_name
)
user.save(using=self._db)
return user
def create_admin(self, email, password=None):
self.create_user(email, password, is_admin=True)
def create_researcher(self, email, password=None):
self.create_user(email, password, is_researcher=True)
def create_student(self, email, password=None):
self.create_user(email, password, is_student=True)
class User(AbstractBaseUser):
USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['first_name', 'last_name']
email = models.EmailField(max_length=255, unique=True)
first_name = models.CharField(max_length=255, blank=False, null=False)
last_name = models.CharField(max_length=255, blank=False, null=False)
# is_active must be true in order to login
is_active = models.BooleanField(default=True)
is_researcher = models.BooleanField(default=False)
is_student = models.BooleanField(default=False)
is_admin = models.BooleanField(default=False)
is_confirmed = models.BooleanField(default=False)
confirmed_date = models.DateTimeField(auto_now=True)
objects = UserManager()
def __str__(self):
return self.email
# def get_absolute_url(self):
# return reverse('users:detail', kwargs={'username': self.username})
def get_full_name(self):
return self.first_name + " " + self.last_name
def get_short_name(self):
return self.email
def has_perm(self, perm, obj=None):
return True
def has_module_perms(self, app_label):
return True
@property
def is_staff(self):
return self.is_admin
<file_sep>from django.contrib.auth.views import LoginView
from django.shortcuts import redirect
from django.urls import reverse_lazy
from .forms import LoginForm
class LoginView(LoginView):
authentication_form = LoginForm
template_name = 'accounts/login.html'
def get_form_kwargs(self):
kwargs = super(LoginView, self).get_form_kwargs()
kwargs.update({'request': self.request})
return kwargs
def form_valid(self, form):
return redirect(reverse_lazy('experiments:home'))
# def login_page(request):
# form = LoginForm(request.POST)
# context = {'form': form}
# if form.is_valid():
# email = form.cleaned_data.get("email")
# password = form.cleaned_data.get("password")
# user = authenticate(request, email=email, password=<PASSWORD>)
# if user is not None:
# login(request, user)
# return redirect('/login')
# else:
# print("Error")
#
# return render(request, "accounts/login.html", context)
|
b18449be6b9d6f111f84c552aa1410501394cc26
|
[
"Markdown",
"Python"
] | 8
|
Python
|
cesslab/ceap
|
4585c86ce90c248fe169da9db1c6fe09c16ff8dc
|
8ec053bc1a84c8a8b376516a4e19e95b6b26d417
|
refs/heads/master
|
<repo_name>vongola12324/LBSBroadcast<file_sep>/app/src/main/java/tw/vongola/lbsbroadcast/WebSocketService.java
package tw.vongola.lbsbroadcast;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.widget.TextView;
import com.github.nkzawa.socketio.client.IO;
import com.github.nkzawa.socketio.client.Socket;
import com.github.nkzawa.emitter.Emitter;
import org.json.JSONException;
import org.json.JSONObject;
import java.net.URISyntaxException;
import java.util.Locale;
public class WebSocketService extends Service implements TextToSpeech.OnInitListener{
private Socket webSocket;
{
try {
webSocket = IO.socket("http://blackteatoast.asuscomm.com:8080");
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
private TextToSpeech tts = null;
private static final String TAG="BroadcastTTS";
private Handler handler;
private Emitter.Listener onNewMessage = new Emitter.Listener() {
@Override
public void call(Object... args) {
try {
if (((JSONObject)args[0]).has("Msg")){
tts.speak(((JSONObject)args[0]).getString("Msg"), TextToSpeech.QUEUE_ADD, null);
}
} catch (JSONException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
};
@Override
public void onCreate(){
super.onCreate();
webSocket.on("recvMsg", onNewMessage);
webSocket.connect();
Log.d("WebSocket", "Connected");
tts = new TextToSpeech(this, this);
tts.setSpeechRate((float) 1.2);
}
@Override
public void onDestroy(){
webSocket.disconnect();
webSocket.off("recvMsg", onNewMessage);
if (this.tts != null) {
this.tts.stop();
this.tts.shutdown();
}
Log.v(TAG, "BroadcastService Service OnDestory");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void sendMessage(double[] location){
JSONObject json = new JSONObject();
try {
json.put("longitude", location[0]);
json.put("latitude", location[1]);
} catch (JSONException e) {
e.printStackTrace();
}
if (json.length() > 0)
webSocket.emit("sendLocation", json);
}
@Override
public void onInit(int status) {
Log.v(TAG, "BroadcastService Service OnInit");
if (status == TextToSpeech.SUCCESS) {
int result = this.tts.setLanguage(Locale.TAIWAN);
if (result == TextToSpeech.LANG_MISSING_DATA ||
result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.v(TAG, "Language is not available.");
}
} else {
Log.v(TAG, "Could not initialize TextToSpeech.");
}
}
}
<file_sep>/README.md
# LBSBroadcast
具有適地性的語音廣播服務(客戶端)
## Requirement
- Android 4.4.4(以上)
- TTS
- 3G/4G/Wifi
- GPS
- Backend Server
## APK
[Download](http://file.vongola.tw/apk/LBSBroadcast.apk)
<file_sep>/app/src/main/java/tw/vongola/lbsbroadcast/GPSService.java
package tw.vongola.lbsbroadcast;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;
import android.widget.Toast;
import java.util.List;
public class GPSService extends Service implements LocationListener {
private Context mContext;
private LocationManager lms;
public GPSService(){
}
public GPSService(Context mContext) {
this.mContext = mContext;
// this.lms = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
//取得系統定位服務
this.lms = (LocationManager) (mContext.getSystemService(Context.LOCATION_SERVICE));
if (this.lms.isProviderEnabled(LocationManager.GPS_PROVIDER) || this.lms.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
lms = (LocationManager) mContext.getSystemService(LOCATION_SERVICE);
} else {
Toast.makeText(mContext, "請開啟定位服務", Toast.LENGTH_LONG).show();
mContext.startService(new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS)); //開啟設定頁面
}
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
public double[] getLocation() { //將定位資訊顯示在畫面中
double[] coordinates = new double[2];
if(lms != null && lms.isProviderEnabled(LocationManager.GPS_PROVIDER) || this.lms.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
List<String> providers = lms.getProviders(true);
Location bestLocation = null;
for (String provider : providers) {
Location l = lms.getLastKnownLocation(provider);
if (l == null) {
continue;
}
if (bestLocation == null || l.getAccuracy() < bestLocation.getAccuracy()) {
// Found best last known location: %s", l);
bestLocation = l;
}
}
coordinates[0] = bestLocation.getLongitude(); //取得經度
coordinates[1] = bestLocation.getLatitude(); //取得緯度
}
else {
Log.d("GPS", "Can not get Location!");
Toast.makeText(mContext, "無法定位座標", Toast.LENGTH_LONG).show();
}
return coordinates;
}
}
|
e44a2e676e223e8947e62272dc6080c121b29e90
|
[
"Markdown",
"Java"
] | 3
|
Java
|
vongola12324/LBSBroadcast
|
e06be5adb9d0eb2e80d51a6c5db3dbff31ef96bb
|
afad8025c60df8612494cb1f90380dc6b099318b
|
refs/heads/master
|
<repo_name>Edfa3ly/sentry-symfony<file_sep>/test/Fixtures/CustomExceptionListener.php
<?php
namespace Sentry\SentryBundle\Test\Fixtures;
use Sentry\SentryBundle\EventListener\ExceptionListener;
/**
* @package Sentry\SentryBundle\Tests\Fixtures
*/
class CustomExceptionListener extends ExceptionListener
{
}
<file_sep>/test/DependencyInjection/SentryExtensionTest.php
<?php
namespace Sentry\SentryBundle\Test\DependencyInjection;
use PHPUnit\Framework\TestCase;
use Sentry\SentryBundle\DependencyInjection\SentryExtension;
use Sentry\SentryBundle\EventListener\ExceptionListener;
use Sentry\SentryBundle\SentrySymfonyClient;
use Sentry\SentryBundle\Test\Fixtures\CustomExceptionListener;
use Symfony\Component\Config\Definition\Exception\InvalidConfigurationException;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\Container;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface;
class SentryExtensionTest extends TestCase
{
private const SUPPORTED_SENTRY_OPTIONS_COUNT = 36;
private const LISTENER_TEST_PUBLIC_ALIAS = 'sentry.exception_listener.public_alias';
public function test_that_configuration_uses_the_right_default_values()
{
$container = $this->getContainer();
$this->assertSame('kernel/root/..', $container->getParameter('sentry.app_path'));
$this->assertSame(SentrySymfonyClient::class, $container->getParameter('sentry.client'));
$this->assertNull($container->getParameter('sentry.dsn'));
$this->assertSame(ExceptionListener::class, $container->getParameter('sentry.exception_listener'));
$this->assertSame([HttpExceptionInterface::class], $container->getParameter('sentry.skip_capture'));
$priorities = $container->getParameter('sentry.listener_priorities');
$this->assertInternalType('array', $priorities);
$this->assertSame(0, $priorities['request']);
$this->assertSame(0, $priorities['kernel_exception']);
$this->assertSame(0, $priorities['console_exception']);
$options = $container->getParameter('sentry.options');
$this->assertCount(self::SUPPORTED_SENTRY_OPTIONS_COUNT, $options);
// same order as in Configuration class
$this->assertSame('php', $options['logger']);
$this->assertNull($options['server']);
$this->assertNull($options['secret_key']);
$this->assertNull($options['public_key']);
$this->assertSame(1, $options['project']);
$this->assertFalse($options['auto_log_stacks']);
$this->assertNull($options['name']);
$this->assertNull($options['site']);
$this->assertSame([], $options['tags']);
$this->assertNull($options['release']);
$this->assertSame('test', $options['environment']);
$this->assertSame(1, $options['sample_rate']);
$this->assertTrue($options['trace']);
$this->assertSame(\Raven_Client::MESSAGE_LIMIT, $options['message_limit']);
$this->assertSame([], $options['exclude']);
$this->assertNull($options['http_proxy']);
$this->assertSame([], $options['extra']);
$this->assertSame('sync', $options['curl_method']);
$this->assertSame('curl', $options['curl_path']);
$this->assertTrue($options['curl_ipv4']);
$this->assertNull($options['ca_cert']);
$this->assertTrue($options['verify_ssl']);
$this->assertNull($options['curl_ssl_version']);
$this->assertFalse($options['trust_x_forwarded_proto']);
$this->assertNull($options['mb_detect_order']);
$this->assertNull($options['error_types']);
$this->assertSame('kernel/root/..', $options['app_path']);
$this->assertContains('kernel/root/../vendor', $options['excluded_app_paths']);
$this->assertContains('kernel/root/../app/cache', $options['excluded_app_paths']);
$this->assertContains('kernel/root/../var/cache', $options['excluded_app_paths']);
$this->assertSame(['kernel/root/..'], $options['prefixes']);
$this->assertTrue($options['install_default_breadcrumb_handlers']);
$this->assertTrue($options['install_shutdown_handler']);
$this->assertSame([\Raven_Processor_SanitizeDataProcessor::class], $options['processors']);
$this->assertSame([], $options['processorOptions']);
}
public function test_that_it_uses_app_path_value()
{
$container = $this->getContainer(
[
'options' => ['app_path' => 'sentry/app/path'],
]
);
$options = $container->getParameter('sentry.options');
$this->assertSame(
'sentry/app/path',
$options['app_path']
);
}
public function test_that_it_uses_client_value()
{
$container = $this->getContainer(
[
'client' => 'clientClass',
]
);
$this->assertSame(
'clientClass',
$container->getParameter('sentry.client')
);
}
public function test_that_it_uses_environment_value()
{
$container = $this->getContainer(
[
'options' => ['environment' => 'custom_env'],
]
);
$options = $container->getParameter('sentry.options');
$this->assertSame(
'custom_env',
$options['environment']
);
}
/**
* @dataProvider emptyDsnValueProvider
*/
public function test_that_it_ignores_empty_dsn_value($emptyDsn)
{
$container = $this->getContainer(
[
'dsn' => $emptyDsn,
]
);
$this->assertNull($container->getParameter('sentry.dsn'));
}
public function emptyDsnValueProvider()
{
return [
[null],
[''],
[' '],
[' '],
];
}
public function test_that_it_uses_dsn_value()
{
$container = $this->getContainer(
[
'dsn' => 'custom_dsn',
]
);
$this->assertSame(
'custom_dsn',
$container->getParameter('sentry.dsn')
);
}
public function test_that_it_uses_http_proxy_value()
{
$container = $this->getContainer(
[
'options' => [
'http_proxy' => 'http://user:password@host:port',
],
]
);
$options = $container->getParameter('sentry.options');
$this->assertSame(
'http://user:password@host:port',
$options['http_proxy']
);
}
public function test_that_it_is_invalid_if_exception_listener_fails_to_implement_required_interface()
{
$this->expectException(InvalidConfigurationException::class);
$this->getContainer(
[
'exception_listener' => 'Some\Invalid\Class',
]
);
}
public function test_that_it_uses_exception_listener_value()
{
$class = CustomExceptionListener::class;
$container = $this->getContainer(
[
'exception_listener' => $class,
]
);
$this->assertSame(
$class,
$container->getParameter('sentry.exception_listener')
);
}
public function test_that_it_uses_skipped_capture_value()
{
$container = $this->getContainer(
[
'skip_capture' => [
'classA',
'classB',
],
]
);
$this->assertSame(
['classA', 'classB'],
$container->getParameter('sentry.skip_capture')
);
}
public function test_that_it_uses_release_value()
{
$container = $this->getContainer(
[
'options' => ['release' => '1.0'],
]
);
$options = $container->getParameter('sentry.options');
$this->assertSame(
'1.0',
$options['release']
);
}
public function test_that_it_uses_prefixes_value()
{
$container = $this->getContainer(
[
'options' => [
'prefixes' => [
'dirA',
'dirB',
],
],
]
);
$options = $container->getParameter('sentry.options');
$this->assertSame(
['dirA', 'dirB'],
$options['prefixes']
);
}
public function test_that_it_has_sentry_client_service_and_it_defaults_to_symfony_client()
{
$client = $this->getContainer()->get('sentry.client');
$this->assertInstanceOf(SentrySymfonyClient::class, $client);
}
public function test_that_it_has_sentry_exception_listener_and_it_defaults_to_default_exception_listener()
{
$listener = $this->getContainer()->get(self::LISTENER_TEST_PUBLIC_ALIAS);
$this->assertInstanceOf(ExceptionListener::class, $listener);
}
public function test_that_it_has_proper_event_listener_tags_for_exception_listener()
{
$containerBuilder = new ContainerBuilder();
$extension = new SentryExtension();
$extension->load([], $containerBuilder);
$definition = $containerBuilder->getDefinition('sentry.exception_listener');
$tags = $definition->getTag('kernel.event_listener');
$this->assertSame(
[
[
'event' => 'kernel.request',
'method' => 'onKernelRequest',
'priority' => '%sentry.listener_priorities.request%',
],
[
'event' => 'kernel.exception',
'method' => 'onKernelException',
'priority' => '%sentry.listener_priorities.kernel_exception%',
],
['event' => 'console.command', 'method' => 'onConsoleCommand'],
[
'event' => 'console.error',
'method' => 'onConsoleError',
'priority' => '%sentry.listener_priorities.console_exception%',
],
],
$tags
);
}
public function test_that_it_sets_all_sentry_options()
{
$options = [
'logger' => 'logger',
'server' => 'server',
'secret_key' => 'secret_key',
'public_key' => 'public_key',
'project' => 'project',
'auto_log_stacks' => true,
'name' => 'name',
'site' => 'site',
'tags' => [
'tag1' => 'tagname',
'tag2' => 'tagename 2',
],
'release' => 'release',
'environment' => 'environment',
'sample_rate' => 0.9,
'trace' => false,
'timeout' => 1,
'message_limit' => 512,
'exclude' => [
'test1',
'test2',
],
'excluded_exceptions' => [
'test3',
'test4',
],
'http_proxy' => 'http_proxy',
'extra' => [
'extra1' => 'extra1',
'extra2' => 'extra2',
],
'curl_method' => 'curl_method',
'curl_path' => 'curl_path',
'curl_ipv4' => false,
'ca_cert' => 'ca_cert',
'verify_ssl' => false,
'curl_ssl_version' => 'curl_ssl_version',
'trust_x_forwarded_proto' => true,
'mb_detect_order' => 'mb_detect_order',
'error_types' => 'E_ALL & ~E_DEPRECATED & ~E_NOTICE',
'app_path' => 'app_path',
'excluded_app_paths' => ['excluded_app_path1', 'excluded_app_path2'],
'prefixes' => ['prefix1', 'prefix2'],
'install_default_breadcrumb_handlers' => false,
'install_shutdown_handler' => false,
'processors' => ['processor1', 'processor2'],
'processorOptions' => [
'processor1' => [
'processorOption1' => 'asasdf',
],
'processor2' => [
'processorOption2' => 'asasdf',
],
],
'ignore_server_port' => true,
];
$this->assertCount(self::SUPPORTED_SENTRY_OPTIONS_COUNT, $options);
$defaultOptions = $this->getContainer()->getParameter('sentry.options');
foreach ($options as $name => $value) {
$this->assertNotEquals(
$defaultOptions[$name],
$value,
'Test precondition failed: using default value for ' . $name
);
}
$container = $this->getContainer(['options' => $options]);
$this->assertSame($options, $container->getParameter('sentry.options'));
}
private function getContainer(array $configuration = []): Container
{
$containerBuilder = new ContainerBuilder();
$containerBuilder->setParameter('kernel.root_dir', 'kernel/root');
$containerBuilder->setParameter('kernel.environment', 'test');
$mockEventDispatcher = $this
->createMock(EventDispatcherInterface::class);
$mockRequestStack = $this
->createMock(RequestStack::class);
$containerBuilder->set('request_stack', $mockRequestStack);
$containerBuilder->set('event_dispatcher', $mockEventDispatcher);
$containerBuilder->setAlias(self::LISTENER_TEST_PUBLIC_ALIAS, new Alias('sentry.exception_listener', true));
$extension = new SentryExtension();
$extension->load(['sentry' => $configuration], $containerBuilder);
$containerBuilder->compile();
return $containerBuilder;
}
}
<file_sep>/CHANGELOG.md
# Changelog
All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).
## [Unreleased]
## 2.3.0 - 2019-01-28
### Added
- Add support for `ignore_server_port` option (#187, thanks @nocive)
### Changed
- Remove `server_name` option default value: this will help reporting the server name correctly in Docker containers (#181, thanks @jvasseur)
- Refactor `ExceptionListener` to have a dedicated `getUserData()` protected method (#180, thanks @bouland)
## 2.2.0 - 2019-01-05
### Added
- Add the `route` tag automatically to any event generated by a request (#167, thanks @ruudk)
### Changed
- Make the `ExceptionListener` more extendable by making all members at least `protected` (#176, thanks @bouland)
## 2.1.0 - 2018-11-05
### Added
- Add new `excluded_exceptions` option in config (#123, thanks @mcfedr)
- Add config for autowiring the client (#158, thanks @gander)
### Changed
- Migrate YAML config to XML; drop dependency on `symfony/yaml` (#155, thanks @Pierstoval)
### Fixed
- Remove deprecation raised by Symfony 4.2 (#161, thanks @chalasr)
## 2.0.3 - 2018-06-01
### Added
- Add `symfony_version` as a default tag (#116, thanks @hjanuschka)
### Fixed
- Retrieve use IP address from Symfony, to honor trusted proxies (#131, thanks @eliecharra)
## 2.0.2 - 2018-03-06
### Fixed
- Fix `processorOptions` in yaml configuration (#107)
## 2.0.1 - 2018-01-31
### Fixed
- Avoid reporting CLI errors twice (#104)
## 2.0.0 - 2017-12-12
### Added
- Add support for Symfony 4.x
### Changed
- The `SentryBundle::VERSION` constant has been replaced with the `SentryBundle::getVersion(): string` method, to get a more accurate result
- Due to a deprecation in `symfony/console`, we require it at at least version 3.3, and we added a method to `SentryExceptionListenerInterface`:
```php
public function onConsoleException(ConsoleErrorEvent $event);
```
### Removed
- Drop support for Symfony 2.x
- Drop support for PHP 5 and 7.0
## 1.0.3 - 2018-06-01
### Added
- Add `symfony_version` as a default tag (#117, backport of #116, thanks @hjanuschka)
### Fixed
- Retrieve use IP address from Symfony, to honor trusted proxies (#132, backport of #131, thanks @eliecharra)
## 1.0.2 - 2018-03-06
### Fixed
- Fix `processorOptions` in YAML configuration (#109, backport of #107)
## 1.0.1 - 2017-12-04
### Changed
- The `sentry.client` service is now explicitly declared as public
## 1.0.0 - 2017-11-07
### Added
- Add official support to PHP 7.2 (#71)
### Changed
- Changed source folder from `src/Sentry/SentryBundle` to just `src/` (thanks to PSR-4 and Composer this doesn't affect you)
- Re-sort the constructor's arguments of `ExceptionListener`
- The `SentrySymfonyClient` is no longer an optional argument of `ExceptionListener`; it's now required
### Fixed
- Remove usage of `create_function()` to avoid deprecations (#71)
- Fix a possible bug that could make Sentry crash if an error is triggered before loading a console command
- Fix a fatal error when the user token is not authenticated (#78)
### Removed
- Drop deprecated fields from configuration; the same options can be used (since 0.8.3) under `sentry.options`
- Dropped the third argument from the `SentrySymfonyClient` constructor; `error_types` are now fetched from the second argument, the options array
- Remove support for PHP versions lower than 5.6, since they are now EOL
- Remove support for HHVM
## 0.8.8 - 2018-06-01
### Added
- Add `symfony_version` as a default tag (backport of #116, thanks @hjanuschka)
- Add the new `excluded_exceptions` option from Sentry client 1.9 (see [getsentry/sentry-php#583](https://github.com/getsentry/sentry-php/pull/583); #124, backport of #123, thanks @mcfedr)
### Changed
- Require at least version 1.9 of the `sentry/sentry` base client, due to #124
### Fixed
- Retrieve use IP address from Symfony, to honor trusted proxies (backport of #131, thanks @eliecharra)
## 0.8.7 - 2017-10-23
### Fixed
- Fix a fatal error when the user token is not authenticated (#78)
## 0.8.6 - 2017-08-24
### Changed
- Migrate service definitions to non-deprecated option configuration values
### Fixed
- Fix expected type of the `options.error_types` config value (scalar instead of array, discovered in #72)
- Fix handling of deprecated options value
## 0.8.5 - 2017-08-22
### Fixed
- `trim()` DSN value from config, to avoid issues with .env files on BitBucket (see https://github.com/getsentry/sentry-symfony/pull/21#issuecomment-323673938)
## 0.8.4 - 2017-08-08
### Fixed
- Fix exception being thrown when both deprecated and new options are used.
## 0.8.3 - 2017-08-07
### Changed
- Migrate all the options from the config root to `sentry.options` (#68); the affected options are still usable in the old form, but they will generate deprecation notices. They will be dropped in the 1.0 release.
Before:
```yaml
sentry:
app_path: ~
environment: ~
error_types: ~
excluded_app_paths: ~
prefixes: ~
release: ~
```
After:
```yaml
sentry:
options:
app_path: ~
environment: ~
error_types: ~
excluded_app_paths: ~
prefixes: ~
release: ~
```
- Migrate from PSR-0 to PSR-4
## 0.8.2 - 2017-07-28
### Fixed
- Fix previous release with cherry pick of the right commit from #67
## 0.8.1 - 2017-07-27
### Fixed
- Force load of client in console commands to avoid missing notices due to lazy-loading (#67)
## 0.8.0 - 2017-06-19
### Added
- Add `SentryExceptionListenerInterface` and the `exception_listener` option in the configuration (#47) to allow customization of the exception listener
- Add `SentrySymfonyEvents::PRE_CAPTURE` and `SentrySymfonyEvents::SET_USER_CONTEXT` events (#47) to customize event capturing information
- Make listeners' priority customizable through the new `listener_priorities` configuration key
### Fixed
- Make SkipCapture work on console exceptions too
## 0.7.1 - 2017-01-26
### Fixed
- Quote sentry.options in services.yml.
## 0.7.0 - 2017-01-20
### Added
- Expose all configuration options (#36).
## 0.6.0 - 2016-10-24
### Fixed
- Improve app path detection to exclude root folder and exclude vendor.
## 0.5.0 - 2016-09-08
### Changed
- Raise sentry/sentry minimum requirement to ## 1.2.0. - 2017-xx-xx Fixed an issue with a missing import (#24)### . - 2017-xx-xx ``prefixes`` and ``app_path`` will now be bound by default.
## 0.4.0 - 2016-07-21
### Added
- Added ``skip_capture`` configuration for excluding exceptions.
### Changed
- Security services are now optional.
- Console exceptions are now captured.
- Default PHP SDK hooks will now be installed (via ``Raven_Client->install``).
- SDK will now be registered as 'sentry-symfony'.
## 0.3.0 - 2016-05-19
### Added
- Added support for capturing the current user.
<file_sep>/CONTRIBUTING.md
# Contribution notes
## Release process
* Make sure `CHANGELOG.md` is up to date (add the release date) and the build is green.
* If this is the first release for this minor version, create a new branch for it:
```
$ git checkout -b releases/1.7.x
```
* Update the hardcoded `SentryBundle::VERSION` constant:
```
class SentryBundle extends Bundle
{
const VERSION = '1.7.0';
}
```
* Commit the changes:
```
$ git commit -am "Release 1.7.0"
```
* Tag the new commit:
```
git tag 1.7.0
```
* Push the tag:
```
git push --tags
```
* Switch back to `master`:
```
git checkout master
```
* Add the next minor release to the `CHANGES` file:
```
## 1.8.0 (unreleased)
```
* Update the hardcoded `SentryBundle::VERSION` constant:
```
class Raven_Client
{
const VERSION = '1.8.x-dev';
}
```
* Lastly, update the composer version in ``composer.json``:
```
"extra": {
"branch-alias": {
"dev-master": "1.8.x-dev"
}
}
```
* Commit the changes:
```
$ git commit -am "Cleanup after release 1.7"
```
All done! Composer will pick up the tag and configuration automatically.
<file_sep>/test/EventListener/ExceptionListenerTest.php
<?php
namespace Sentry\SentryBundle\Test\EventListener;
use PHPUnit\Framework\TestCase;
use Sentry\SentryBundle\DependencyInjection\SentryExtension;
use Sentry\SentryBundle\Event\SentryUserContextEvent;
use Sentry\SentryBundle\EventListener\ExceptionListener;
use Sentry\SentryBundle\EventListener\SentryExceptionListenerInterface;
use Sentry\SentryBundle\SentrySymfonyEvents;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Event\ConsoleErrorEvent;
use Symfony\Component\Console\Event\ConsoleExceptionEvent;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\DependencyInjection\Alias;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\EventDispatcher\EventDispatcherInterface;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\RequestStack;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Event\GetResponseForExceptionEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\AuthorizationCheckerInterface;
use Symfony\Component\Security\Core\Authorization\Voter\AuthenticatedVoter;
use Symfony\Component\Security\Core\User\UserInterface;
class ExceptionListenerTest extends TestCase
{
private const LISTENER_TEST_PUBLIC_ALIAS = 'sentry.exception_listener.public_alias';
private $containerBuilder;
private $mockSentryClient;
private $mockTokenStorage;
private $mockAuthorizationChecker;
private $mockEventDispatcher;
/**
* @var RequestStack
*/
private $requestStack;
public function setUp()
{
$this->mockTokenStorage = $this->createMock(TokenStorageInterface::class);
$this->mockAuthorizationChecker = $this->createMock(AuthorizationCheckerInterface::class);
$this->mockSentryClient = $this->createMock(\Raven_Client::class);
$this->mockEventDispatcher = $this->createMock(EventDispatcherInterface::class);
$this->requestStack = new RequestStack();
$containerBuilder = new ContainerBuilder();
$containerBuilder->setParameter('kernel.root_dir', 'kernel/root');
$containerBuilder->setParameter('kernel.environment', 'test');
$containerBuilder->set('request_stack', $this->requestStack);
$containerBuilder->set('security.token_storage', $this->mockTokenStorage);
$containerBuilder->set('security.authorization_checker', $this->mockAuthorizationChecker);
$containerBuilder->set('sentry.client', $this->mockSentryClient);
$containerBuilder->set('event_dispatcher', $this->mockEventDispatcher);
$containerBuilder->setAlias(self::LISTENER_TEST_PUBLIC_ALIAS, new Alias('sentry.exception_listener', true));
$extension = new SentryExtension();
$extension->load([], $containerBuilder);
$this->containerBuilder = $containerBuilder;
}
public function test_that_it_is_an_instance_of_sentry_exception_listener()
{
$this->containerBuilder->compile();
$listener = $this->getListener();
$this->assertInstanceOf(ExceptionListener::class, $listener);
}
public function test_that_user_data_is_not_set_on_subrequest()
{
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::SUB_REQUEST);
$this->mockSentryClient
->expects($this->never())
->method('set_user_data')
->withAnyParameters();
$this->mockEventDispatcher
->expects($this->never())
->method('dispatch')
->withAnyParameters();
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_user_data_is_not_set_if_token_storage_not_present()
{
$this->containerBuilder->set('security.token_storage', null);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockSentryClient
->expects($this->never())
->method('set_user_data')
->withAnyParameters();
$this->mockEventDispatcher
->expects($this->never())
->method('dispatch')
->withAnyParameters();
$this->assertFalse($this->containerBuilder->has('security.token_storage'));
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_user_data_is_not_set_if_authorization_checker_not_present()
{
$this->containerBuilder->set('security.authorization_checker', null);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockSentryClient
->expects($this->never())
->method('set_user_data')
->withAnyParameters();
$this->mockEventDispatcher
->expects($this->never())
->method('dispatch')
->withAnyParameters();
$this->containerBuilder->compile();
$this->assertFalse($this->containerBuilder->has('security.authorization_checker'));
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_user_data_is_not_set_if_token_not_present()
{
$user = $this->createMock(UserInterface::class);
$user->method('getUsername')
->willReturn('username');
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockAuthorizationChecker
->method('isGranted')
->with($this->identicalTo(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED))
->willReturn(true);
$this->mockTokenStorage
->method('getToken')
->willReturn(null);
$this->mockSentryClient
->expects($this->never())
->method('set_user_data')
->withAnyParameters();
$this->mockEventDispatcher
->expects($this->never())
->method('dispatch')
->withAnyParameters();
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_user_data_is_not_set_if_not_authorized()
{
$user = $this->createMock(UserInterface::class);
$user->method('getUsername')->willReturn('username');
$mockToken = $this->createMock(TokenInterface::class);
$mockToken
->method('getUser')
->willReturn($user);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockAuthorizationChecker
->method('isGranted')
->with($this->identicalTo(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED))
->willReturn(false);
$this->mockTokenStorage
->method('getToken')
->willReturn($mockToken);
$this->mockSentryClient
->expects($this->never())
->method('set_user_data')
->withAnyParameters();
$this->mockEventDispatcher
->expects($this->never())
->method('dispatch')
->withAnyParameters();
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_username_is_set_from_user_interface_if_token_present_and_user_set_as_user_interface()
{
$user = $this->createMock(UserInterface::class);
$user->method('getUsername')->willReturn('username');
$mockToken = $this->createMock(TokenInterface::class);
$mockToken
->method('getUser')
->willReturn($user);
$mockToken
->method('isAuthenticated')
->willReturn(true);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this
->mockAuthorizationChecker
->method('isGranted')
->with($this->identicalTo(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED))
->willReturn(true);
$this->mockTokenStorage
->method('getToken')
->willReturn($mockToken);
$this
->mockSentryClient
->expects($this->once())
->method('set_user_data')
->with($this->identicalTo('username'));
$this
->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with(
$this->identicalTo(SentrySymfonyEvents::SET_USER_CONTEXT),
$this->isInstanceOf(SentryUserContextEvent::class)
);
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_username_is_set_from_user_interface_if_token_present_and_user_set_as_string()
{
$mockToken = $this->createMock(TokenInterface::class);
$mockToken
->method('getUser')
->willReturn('some_user');
$mockToken
->method('isAuthenticated')
->willReturn(true);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockAuthorizationChecker
->method('isGranted')
->with($this->identicalTo(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED))
->willReturn(true);
$this->mockTokenStorage
->method('getToken')
->willReturn($mockToken);
$this->mockSentryClient
->expects($this->once())
->method('set_user_data')
->with($this->identicalTo('some_user'));
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with(
$this->identicalTo(SentrySymfonyEvents::SET_USER_CONTEXT),
$this->isInstanceOf(SentryUserContextEvent::class)
);
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_username_is_set_from_user_interface_if_token_present_and_user_set_object_with_to_string()
{
$mockUser = $this->getMockBuilder('stdClass')
->setMethods(['__toString'])
->getMock();
$mockUser
->expects($this->once())
->method('__toString')
->willReturn('std_user');
$mockToken = $this->createMock(TokenInterface::class);
$mockToken
->method('getUser')
->willReturn($mockUser);
$mockToken
->method('isAuthenticated')
->willReturn(true);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockAuthorizationChecker
->method('isGranted')
->with($this->identicalTo(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED))
->willReturn(true);
$this->mockTokenStorage
->method('getToken')
->willReturn($mockToken);
$this->mockSentryClient
->expects($this->once())
->method('set_user_data')
->with($this->identicalTo('std_user'));
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with(
$this->identicalTo(SentrySymfonyEvents::SET_USER_CONTEXT),
$this->isInstanceOf(SentryUserContextEvent::class)
);
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_ip_is_set_from_request_stack()
{
$mockToken = $this->createMock(TokenInterface::class);
$mockToken
->method('getUser')
->willReturn('some_user');
$mockToken
->method('isAuthenticated')
->willReturn(true);
$mockEvent = $this->createMock(GetResponseEvent::class);
$this->requestStack->push(new Request([], [], [], [], [], [
'REMOTE_ADDR' => '1.2.3.4',
]));
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockAuthorizationChecker
->method('isGranted')
->with($this->identicalTo(AuthenticatedVoter::IS_AUTHENTICATED_REMEMBERED))
->willReturn(true);
$this->mockTokenStorage
->method('getToken')
->willReturn($mockToken);
$this->mockSentryClient
->expects($this->once())
->method('set_user_data')
->with($this->identicalTo('some_user'), null, ['ip_address' => '1.2.3.4']);
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_regression_with_unauthenticated_user_token_PR_78()
{
$mockToken = $this->createMock(TokenInterface::class);
$mockToken
->method('isAuthenticated')
->willReturn(false);
$mockEvent = $this->createMock(GetResponseEvent::class);
$mockEvent
->expects($this->once())
->method('getRequestType')
->willReturn(HttpKernelInterface::MASTER_REQUEST);
$this->mockTokenStorage
->method('getToken')
->willReturn($mockToken);
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelRequest($mockEvent);
}
public function test_that_it_does_not_report_http_exception_if_included_in_capture_skip()
{
$mockEvent = $this->createMock(GetResponseForExceptionEvent::class);
$mockEvent
->expects($this->once())
->method('getException')
->willReturn(new HttpException(401));
$this->mockEventDispatcher
->expects($this->never())
->method('dispatch')
->withAnyParameters();
$this->mockSentryClient
->expects($this->never())
->method('captureException')
->withAnyParameters();
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelException($mockEvent);
}
public function test_that_it_captures_exception()
{
$reportableException = new \Exception();
$mockEvent = $this->createMock(GetResponseForExceptionEvent::class);
$mockEvent
->expects($this->once())
->method('getException')
->willReturn($reportableException);
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with($this->identicalTo(SentrySymfonyEvents::PRE_CAPTURE), $this->identicalTo($mockEvent));
$this->mockSentryClient
->expects($this->once())
->method('captureException')
->with($this->identicalTo($reportableException));
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelException($mockEvent);
}
public function test_that_it_captures_exception_with_route()
{
$reportableException = new \Exception();
$mockEvent = $this->createMock(GetResponseForExceptionEvent::class);
$mockEvent
->expects($this->once())
->method('getException')
->willReturn($reportableException);
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with($this->identicalTo(SentrySymfonyEvents::PRE_CAPTURE), $this->identicalTo($mockEvent));
$data = [
'tags' => [
'route' => 'homepage',
],
];
$this->requestStack->push(new Request([], [], ['_route' => 'homepage']));
$this->mockSentryClient
->expects($this->once())
->method('captureException')
->with($this->identicalTo($reportableException), $data);
$this->containerBuilder->compile();
$listener = $this->getListener();
$listener->onKernelException($mockEvent);
}
/**
* @dataProvider mockCommandProvider
*/
public function test_that_it_captures_console_exception(?Command $mockCommand, string $expectedCommandName)
{
if (! class_exists('Symfony\Component\Console\Event\ConsoleExceptionEvent')) {
$this->markTestSkipped('ConsoleExceptionEvent does not exist anymore on Symfony 4');
}
if (null === $mockCommand) {
$this->markTestSkipped('Command missing is not possibile with ConsoleExceptionEvent');
}
$exception = $this->createMock(\Exception::class);
/** @var InputInterface $input */
$input = $this->createMock(InputInterface::class);
/** @var OutputInterface $output */
$output = $this->createMock(OutputInterface::class);
$event = new ConsoleExceptionEvent($mockCommand, $input, $output, $exception, 10);
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with($this->identicalTo(SentrySymfonyEvents::PRE_CAPTURE), $this->identicalTo($event));
$this->mockSentryClient
->expects($this->once())
->method('captureException')
->with(
$this->identicalTo($exception),
$this->identicalTo([
'tags' => [
'command' => $expectedCommandName,
'status_code' => 10,
],
])
);
$this->containerBuilder->compile();
/** @var SentryExceptionListenerInterface $listener */
$listener = $this->getListener();
$listener->onConsoleException($event);
}
/**
* @dataProvider mockCommandProvider
*/
public function test_that_it_captures_console_error(?Command $mockCommand, string $expectedCommandName)
{
$error = $this->createMock(\Error::class);
/** @var InputInterface $input */
$input = $this->createMock(InputInterface::class);
/** @var OutputInterface $output */
$output = $this->createMock(OutputInterface::class);
$event = new ConsoleErrorEvent($input, $output, $error, $mockCommand);
$event->setExitCode(10);
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with($this->identicalTo(SentrySymfonyEvents::PRE_CAPTURE), $this->identicalTo($event));
$this->mockSentryClient
->expects($this->once())
->method('captureException')
->with(
$this->identicalTo($error),
$this->identicalTo([
'tags' => [
'command' => $expectedCommandName,
'status_code' => 10,
],
])
);
$this->containerBuilder->compile();
/** @var SentryExceptionListenerInterface $listener */
$listener = $this->getListener();
$listener->onConsoleError($event);
}
public function mockCommandProvider()
{
$mockCommand = $this->createMock(Command::class);
$mockCommand
->expects($this->once())
->method('getName')
->willReturn('cmd name');
return [
[$mockCommand, 'cmd name'],
[null, 'N/A'], // the error may have been triggered before the command is loaded
];
}
public function test_that_it_can_replace_client()
{
$replacementClient = $this->createMock(\Raven_Client::class);
$reportableException = new \Exception();
$mockEvent = $this->createMock(GetResponseForExceptionEvent::class);
$mockEvent
->expects($this->once())
->method('getException')
->willReturn($reportableException);
$this->mockEventDispatcher
->expects($this->once())
->method('dispatch')
->with($this->identicalTo(SentrySymfonyEvents::PRE_CAPTURE), $this->identicalTo($mockEvent));
$this->mockSentryClient
->expects($this->never())
->method('captureException')
->withAnyParameters();
$replacementClient
->expects($this->once())
->method('captureException')
->with($this->identicalTo($reportableException));
$this->containerBuilder->compile();
/** @var ExceptionListener $listener */
$listener = $this->getListener();
$this->assertInstanceOf(ExceptionListener::class, $listener);
$listener->setClient($replacementClient);
$listener->onKernelException($mockEvent);
}
private function getListener(): SentryExceptionListenerInterface
{
return $this->containerBuilder->get(self::LISTENER_TEST_PUBLIC_ALIAS);
}
}
<file_sep>/test/Fixtures/InvalidExceptionListener.php
<?php
namespace Sentry\SentryBundle\Test\Fixtures;
/**
* An invalid <code>ExceptionListener</code> for testing.
*
* This exception listener does not implement, or extend a class that
* implements, the appropriate interface that the dependency injection
* container requires.
*
* @package Sentry\SentryBundle\Tests\Fixtures
*/
class InvalidExceptionListener
{
}
<file_sep>/src/SentryBundle.php
<?php
namespace Sentry\SentryBundle;
use Jean85\PrettyVersions;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class SentryBundle extends Bundle
{
public static function getVersion(): string
{
return PrettyVersions::getVersion('sentry/sentry-symfony')
->getPrettyVersion();
}
}
|
3d52060f4e349985d6fcbf291e4f035804845ab4
|
[
"Markdown",
"PHP"
] | 7
|
PHP
|
Edfa3ly/sentry-symfony
|
b64a72673da2ac2243aed509d1b3c0aad4119ee4
|
8b21beb4adca45d3fb5d1022c3655a6f3ce49ead
|
refs/heads/master
|
<file_sep>/*
* Student.cpp
*
* Created on: Sep 10, 2019
* Author: Huy
*/
#include "Student.h"
#include <string>
using namespace std;
/*void Student::setName(void)
{
cout << "Enter name: " << endl;
//gets(name); //To include spaces in the input
cin >> name;
cout <<"Student's name is " <<name << endl;
}*/
void Student::setName(std::string s)
{
name = s;
}
/*void Student::setAddress(void)
{
cout << "Enter address: " << endl ;
gets(address); //To include spaces in the input
//cin >> address;
cout <<"Student's address is " <<address << endl;
}*/
void Student::setAddress(std::string x)
{
address = x;
}
/*void Student::setMatrNumber(void)
{
cout << "Enter matriculation number: " << endl;
cin >> matrNumber;
cout <<"Student's matriculation number is " <<matrNumber << endl;
}*/
void Student::setMatrNumber(int i)
{
matrNumber = i;
}
void Student::setCurrentSemester(int j)
{
currentSemester = j;
}
void Student::setPlannedSemesters(int k)
{
plannedSemesters = k;
}
void Student::setFullInfo()
{
cout << "Enter name: " << endl ;
std::getline (std::cin,tempName);
setName(tempName);
//std::cout << "Hello, " << name << "!\n";
cout << "Enter address: " << endl ;
std::getline (std::cin,tempAddress);
setAddress(tempAddress);
cout << "Enter matriculation number: " << endl;
cin >> tempmatrNumber;
setMatrNumber(tempmatrNumber);
cout << "Enter current semester: " << endl;
cin >> tempcurrentSemester;
setCurrentSemester(tempcurrentSemester);
cout << "Enter planned semesters: " << endl;
cin >> tempplannedSemesters;
setPlannedSemesters(tempplannedSemesters);
remainedSemesters = plannedSemesters - currentSemester;
//cout << "The study will take " << remainedSemesters << " semester(s)" << endl;
}
string Student::getName()
{
return name;
}
string Student::getAddress()
{
return address;
}
int Student::getMatrNumber()
{
return matrNumber;
}
int Student::getCurrentSemester() //Question: Why we need "Student::" before function name. If not, "Student::" is required before variable name. eg Student::currentSemester. Why?
{
return currentSemester;
}
int Student::getPlannedSemesters()
{
return plannedSemesters;
};
void Student::getFullInfo() //Question: Not clear when to require "Student::" before function/ variable. Example: below variables don't require "Student::"
{
cout << "Student's name is: " << getName() << endl;
cout << "Student's address is: " << getAddress() << endl;
cout << "Student's matriculation number is: " << getMatrNumber() << endl;
cout << "Student's current semester is: " << getCurrentSemester() << endl;
cout << "Student's number of planned semesters is: " << getPlannedSemesters() << endl;
cout << "Student's number of remained semesters is: " << remainedSemesters << endl;
}
// Need to edit: set function need argument. Ex: setName(string s) .
// Then input can be parsed from keyboard to that argument.
<file_sep>/*
* Student.h
*
* Created on: Sep 10, 2019
* Author: Huy
*/
#ifndef STUDENT_H_
#define STUDENT_H_
#include <iostream>
#include <stdio.h>
#include <string>
class Student
{
private:
std::string name;
std::string address;
int matrNumber;
int currentSemester;
int plannedSemesters;
public:
std::string tempName;
std::string tempAddress;
int tempmatrNumber;
int tempcurrentSemester;
int tempplannedSemesters;
int remainedSemesters;
void setName(std::string s);
void setAddress(std::string x);
void setMatrNumber(int i);
void setCurrentSemester(int j);
void setPlannedSemesters(int k);
void setFullInfo();
std::string getName();
std::string getAddress();
int getMatrNumber();
int getCurrentSemester();
int getPlannedSemesters();
void getFullInfo();
};
#endif /* STUDENT_H_ */
<file_sep>/*
* main.cpp
*
* Created on: Sep 8, 2019
* Author: Huy
*/
#include <iostream>
#include <stdio.h>
#include <string>
#include "Student.h"
using namespace std;
int main(int argc, char* argv[]) {
int i;
Student myStudent1, myStudent2;
myStudent1.setFullInfo();
myStudent1.getFullInfo();
myStudent2.setFullInfo();
myStudent2.getFullInfo(); //Question: Student2 has bug. Cannot enter name. Get straight to address. Why?
//myStudent2.setFullInfo();
//myStudent.setCurrentSemester();
/*for (i = 1; i < 10; i++)
{
j = i*i;
cout << i << " * " << i << " = " << j << endl;
}*/
}
|
9baba709883feddae3ccf1630a8a38f8cd35145b
|
[
"C++"
] | 3
|
C++
|
minhhuyle1993/Student_Class
|
7f3d94b06ba8d4e6c20833866f79435921e6c3db
|
97994a7c1079fb7641bbed4d7dbf69ec06363a15
|
refs/heads/master
|
<file_sep>import { QueryResult } from "@apollo/react-common";
import { QueryHookOptions, useQuery as _useQuery } from "@apollo/react-hooks";
import { Operation, OperationData, OperationVariables } from "./operation";
export abstract class Query<D, V> extends Operation<D, V> {}
export const useQuery = <T extends Query<unknown, unknown>>(
query: T,
options: QueryHookOptions<OperationData<T>, OperationVariables<T>> = null
): QueryResult<OperationData<T>, OperationVariables<T>> =>
_useQuery(query.statement, options);
<file_sep>import { OperationVariables as _OperationVariables } from "@apollo/react-common";
import { DocumentNode } from "graphql";
export abstract class Operation<D = unknown, V = _OperationVariables> {
protected data: D;
protected variables: V;
constructor(public statement: DocumentNode) {}
}
export type OperationData<
T extends Operation<unknown, unknown>
> = T extends Operation<infer D, unknown> ? D : never;
export type OperationVariables<
T extends Operation<unknown, unknown>
> = T extends Operation<unknown, infer V> ? V : never;
<file_sep>import { MutationFunction as _MutationFunction } from "@apollo/react-common";
import {
MutationHookOptions,
MutationTuple,
useMutation as _useMutation
} from "@apollo/react-hooks";
import { Operation, OperationData, OperationVariables } from "./operation";
export abstract class Mutation<D, V> extends Operation<D, V> {}
export type MutationFunction<
T extends Mutation<unknown, unknown>
> = _MutationFunction<OperationData<T>, OperationVariables<T>>;
export const useMutation = <T extends Mutation<unknown, unknown>>(
mutation: T,
options: MutationHookOptions<OperationData<T>, OperationVariables<T>> = null
): MutationTuple<OperationData<T>, OperationVariables<T>> =>
_useMutation(mutation.statement, { onError: () => null, ...options });
<file_sep># react-apollo-typed-hooks
[][workflows-nodejs]
Wrappers for [Apollo][]'s React hooks with simplified typings.
## Usage
**tl;dr**:
- Extend `Mutation` or `Query` with type parameters for the shapes of the
result data and the allowed parameters for each query or mutation allowed by
your application.
- Instantiate the classes with the query to execute.
- Use `useQuery` and `useMutation` with the same API provided by
`@apollo/react-hooks`, but pass the instance instead of the query node. You'll
get detailed type information for all query and mutation variables and
results.
```tsx
import * as React from "react";
import gql from "graphql-tag";
import { Query, useQuery } from "react-apollo-typed-hooks";
const QUERY = gql`
query {
testQuery {
ok
}
}
`;
class TestQuery extends Query<{ testQuery: { ok: boolean } }, {}> {}
const q = new TestQuery(QUERY);
export const Component = () => {
const { data } = useQuery(q);
return <div>{data?.testQuery?.ok && `${data.testQuery.ok}`</div>;
};
```
## Copyright
Copyright © 2020 <NAME>. Licensed under the [MIT License](LICENSE).
[apollo]: https://www.apollographql.com
[workflows-nodejs]: https://github.com/jbhannah/react-apollo-typed-hooks/actions?query=workflow%3ANode.js
<file_sep>export { Mutation, MutationFunction, useMutation } from "./mutation";
export { Query, useQuery } from "./query";
|
1e0d802fa98cff377b2f51d4f10666c695e002b9
|
[
"Markdown",
"TypeScript"
] | 5
|
TypeScript
|
jbhannah/react-apollo-typed-hooks
|
bcfd6adf2e475611945675f48c776f6033ace3a1
|
8df8d484fc04eea5d8593eae43eb241bb06adb0c
|
refs/heads/master
|
<repo_name>moningkai/RoadPlane_StereoMatching<file_sep>/RoadPlane_Estimation.cpp
//
// Created by nvidia on 7/17/18.
//
#include "RoadPlane_Estimation.h"
namespace rm
{
int myget_time()
{
time_t t_sec0;
struct timeb tb_start;
ftime(&tb_start);
time(&t_sec0);
return (int)(t_sec0*1000+tb_start.millitm);
}
RoadPlane_Estimation::RoadPlane_Estimation() {}
RoadPlane_Estimation::~RoadPlane_Estimation() {}
void RoadPlane_Estimation::init(Stereo_CamPara& in_stereo_camPara)
{
//initialize stereo matcher
auto ts=in_stereo_camPara;
m_stereoMeasurer.initial_stereo_system(ts.image_size,ts.left_K,ts.right_K,ts.left_distor,ts.right_distor,ts.r2l_Tran,ts.min_range,ts.max_range);
//initialize road model
m_camHeight=ts.init_cam_height; m_camPitch=ts.init_cam_pitch;
//initialize ENet
}
void RoadPlane_Estimation::run_road_plane_estimation(Mat in_leftImg, Mat in_rightImg)
{
//preprocess of stereo images
int ts_pre=myget_time();
//影像畸变纠正
preprocess_stereo_images(in_leftImg,in_rightImg,m_undistorLimg,m_undistorRimg);
cout<<"pre:"<<(myget_time()-ts_pre)<<" ";
//segment images => l/r_segImg in left or right image
if(false)
{
segment_images(m_undistorLimg,m_l_segImg);
segment_images(m_undistorRimg,m_r_segImg);
}
else
{
//just for test
ts_pre=myget_time();
segment_i_images(m_undistorLimg,-1,m_l_segImg);
segment_i_images(m_undistorRimg, 1,m_r_segImg);
m_cur_frameID++;
cout<<"seg:"<<(myget_time()-ts_pre)<<" ";
}
//get certain kind object ROI from segImg
cv::Scalar road_color(128,64,128);
ts_pre=myget_time();
get_objectROI_from_segImg(m_l_segImg,road_color,m_l_roadROI);//将指定颜色的区域标白,其他区域颜色置黑
get_objectROI_from_segImg(m_r_segImg,road_color,m_r_roadROI);
cout<<"roi:"<<(myget_time()-ts_pre)<<" ";
//key points detection => l/r_ObjectKPts in left or right ObjectROI
//find match points of l_ObjectKPts in r_ObjectKPts => ObjectKPts_matchID
ts_pre=myget_time();
m_stereoMeasurer.run_ORB_KeyPoints_detection_and_matching(m_l_roadKPts,m_r_roadKPts,m_roadKPts_matchID,m_l_roadROI,m_r_roadROI);
cout<<"getP:"<<(myget_time()-ts_pre)<<" ";
//calculate homography matrix based on match points => Object_HMatrix: l_imgX = HMatrix*r_imgX
ts_pre=myget_time();
calculate_homography_matrix(m_l_roadKPts,m_r_roadKPts,m_roadKPts_matchID,m_road_HMatrix);//计算单应性矩阵
cout<<"getH:"<<(myget_time()-ts_pre)<<" ";
//get object boundry based on left right image and homography matrix => Object_boundry
ts_pre=myget_time();
get_object_boundry(m_road_HMatrix,m_roadBoundry);//获取区域边界
cout<<"getB:"<<(myget_time()-ts_pre)<<" ";
}
void RoadPlane_Estimation::preprocess_stereo_images(Mat in_leftImg, Mat in_rightImg, Mat &out_leftImg,
Mat &out_rightImg)
{
//rectify distortion of image
//影像畸变纠正
m_stereoMeasurer.stereo_images_rectification(in_leftImg,in_rightImg,out_leftImg,out_rightImg);
}
void RoadPlane_Estimation::segment_images(Mat in_Img, Mat &out_segImg)
{
}
//just for test , none real segment function
void RoadPlane_Estimation::segment_i_images(Mat in_Img,int left_or_right, Mat &out_segImg)
{
char filename[256];
if(left_or_right==-1) sprintf(filename,"/home/nvidia/Pictures/03/left_segments/%06d.png",m_cur_frameID);
if(left_or_right== 1) sprintf(filename,"/home/nvidia/Pictures/03/right_segments/%06d.png",m_cur_frameID);
Mat middel_segImg=cv::imread(filename);
out_segImg=cv::Mat::zeros(in_Img.size(),CV_8UC3);
middel_segImg.copyTo(out_segImg.colRange(out_segImg.cols/2 - middel_segImg.cols/2,out_segImg.cols/2 + middel_segImg.cols/2));
}
void RoadPlane_Estimation::get_objectROI_from_segImg(Mat in_segImg, cv::Scalar obj_classColor, Mat &out_objectROI)
{
//=============该方法耗时约 17/2=9 ms========================//
// re-allocate binary map if necessary
// same size as input image, but 1-channel
out_objectROI.create(in_segImg.size(),CV_8UC1);
// get the iterators
cv::Mat_<cv::Vec3b>::const_iterator it= in_segImg.begin<cv::Vec3b>();
cv::Mat_<cv::Vec3b>::const_iterator itend= in_segImg.end<cv::Vec3b>();
cv::Mat_<uchar>::iterator itout= out_objectROI.begin<uchar>();
// for each pixel
for ( ; it!= itend; ++it, ++itout)
{
// process each pixel ---------------------
// compute distance from target color
if ((*it)[0] == obj_classColor.val[0]
&& (*it)[1] == obj_classColor.val[1]
&& (*it)[2] == obj_classColor.val[2])
{
*itout= 255;
}
else
{
*itout= 0;
}
// end of pixel processing ----------------
}
}
void RoadPlane_Estimation::calculate_homography_matrix(vector<cv::KeyPoint> in_l_KPts, vector<cv::KeyPoint> in_r_KPts,
vector<cv::DMatch> in_KPts_matchID, Mat &out_ObjectHMatrix)
{
vector<cv::Point2f> temp_l_pts,temp_r_pts;
temp_l_pts.reserve(in_KPts_matchID.size());
temp_r_pts.reserve(in_KPts_matchID.size());
for (int i = 0; i < in_KPts_matchID.size(); ++i) {
temp_l_pts.push_back(in_l_KPts[in_KPts_matchID[i].trainIdx].pt);
temp_r_pts.push_back(in_r_KPts[in_KPts_matchID[i].queryIdx].pt);
}//for(i)
if(temp_r_pts.size()== temp_l_pts.size() && temp_r_pts.size() >= 4)
{
//l_p = H*r_p
out_ObjectHMatrix = cv::findHomography(temp_r_pts,temp_l_pts,cv::RANSAC,5,cv::noArray(),2000,0.99);
out_ObjectHMatrix.convertTo(out_ObjectHMatrix,CV_32FC1);
}//if
else out_ObjectHMatrix=cv::Mat();
#ifdef DEBUG_SHOW_HMATRIXRESULT
cv::Mat r_ptsM(3,temp_r_pts.size(),CV_32FC1);
for (int i = 0; i < temp_r_pts.size(); ++i) {
r_ptsM.at<float>(0,i)=temp_r_pts[i].x;
r_ptsM.at<float>(1,i)=temp_r_pts[i].y;
r_ptsM.at<float>(2,i)=1.0f;
}//for(i)
cv::Mat l_ptsM=out_ObjectHMatrix*r_ptsM;
vector<cv::Point2f> ().swap(temp_l_pts);
temp_l_pts.reserve(temp_r_pts.size());
for (int i = 0; i < temp_r_pts.size(); ++i) {
temp_l_pts.push_back(cv::Point2f(l_ptsM.at<float>(0,i)/l_ptsM.at<float>(2,i), l_ptsM.at<float>(1,i)/l_ptsM.at<float>(2,i)));
}//for(i)
int t_iterNUM=temp_r_pts.size()/10;
for (int i = 0; i < t_iterNUM; ++i) {
vector<cv::KeyPoint> tt_lKPs,tt_rKPs;
vector<cv::DMatch> tt_lMatch;
for (int j = 0; j <10 ; ++j) {
tt_lKPs.push_back(cv::KeyPoint(temp_l_pts[i*t_iterNUM+j],2));
tt_rKPs.push_back(cv::KeyPoint(temp_r_pts[i*t_iterNUM+j],2));
tt_lMatch.push_back(cv::DMatch(j,j,1));
}//for(j)
cv::Mat show_matching_l;
cv::drawMatches(m_stereoMeasurer.m_undisRightImg,tt_rKPs,m_stereoMeasurer.m_undisLeftImg,tt_lKPs,tt_lMatch,show_matching_l);
cv::imshow("after H-trans",show_matching_l);
cv::waitKey(1);
}//for(i)
#endif
}
void RoadPlane_Estimation::get_object_boundry(Mat in_ObjectHMatrix, vector<cv::Point2i> &out_ObjectBoundry)
{
if(in_ObjectHMatrix.cols != 3 && in_ObjectHMatrix.rows != 3) return;
if(in_ObjectHMatrix.type()!=CV_32FC1) in_ObjectHMatrix.convertTo(in_ObjectHMatrix,CV_32FC1);
//calculate remaping map_x and map_y
cv::Size img_size=m_stereoMeasurer.m_undisLeftImg.size();
cv::Mat tmap_x(img_size,CV_32FC1);
cv::Mat tmap_y(img_size,CV_32FC1);
cv::Mat temp_3XN(3,img_size.width*img_size.height,CV_32FC1);
float *fdata=(float*)temp_3XN.data;
for (int i = 0; i <img_size.height; ++i) {
for (int j = 0; j < img_size.width; ++j) {
fdata[0*temp_3XN.cols+i*img_size.width+j]=(float)j;
fdata[1*temp_3XN.cols+i*img_size.width+j]=(float)i;
fdata[2*temp_3XN.cols+i*img_size.width+j]=1.0f;
}//for(j)
}//for(i)
cv::Mat temp_result= in_ObjectHMatrix*temp_3XN;
cv::divide(temp_result.row(0),temp_result.row(2),temp_result.row(0));
cv::divide(temp_result.row(1),temp_result.row(2),temp_result.row(1));
fdata=(float*)temp_result.data;
float *fxp=(float*)tmap_x.data;
float *fyp=(float*)tmap_y.data;
for (int i = 0; i <img_size.height; ++i) {
for (int j = 0; j < img_size.width; ++j) {
fxp[i*img_size.width+j]= fdata[0*temp_result.cols+i*img_size.width+j];
fyp[i*img_size.width+j]= fdata[1*temp_result.cols+i*img_size.width+j];
}//for(j)
}//for(i)
m_stereoMeasurer.m_gpu_buffer.temp_map[0]= tmap_x.clone();
m_stereoMeasurer.m_gpu_buffer.temp_map[1]= tmap_y.clone();
cv::/*cuda::*/remap(m_stereoMeasurer.m_gpu_buffer.undis_LImgGrey,m_stereoMeasurer.m_gpu_buffer.temp_GreyImg,
m_stereoMeasurer.m_gpu_buffer.temp_map[0],m_stereoMeasurer.m_gpu_buffer.temp_map[1],cv::INTER_LINEAR);
cv::Mat temp_tranImg,ori_img;
//cv::bilateralFilter(m_stereoMeasurer.m_gpu_buffer.temp_GreyImg,m_stereoMeasurer.m_gpu_buffer.temp_GreyImg,3,20,20);
temp_tranImg = m_stereoMeasurer.m_gpu_buffer.temp_GreyImg.clone();
//cv::bilateralFilter(m_stereoMeasurer.m_gpu_buffer.undis_RImgGrey,m_stereoMeasurer.m_gpu_buffer.temp_GreyImg,3,20,20);
ori_img = m_stereoMeasurer.m_gpu_buffer.undis_RImgGrey.clone();
cv::GaussianBlur(ori_img,ori_img,cv::Size(5,5),2.0,2.0);
cv::GaussianBlur(temp_tranImg,temp_tranImg,cv::Size(5,5),2.0,2.0);
cv::absdiff(ori_img,temp_tranImg,temp_tranImg);
temp_tranImg.convertTo(temp_tranImg,CV_8UC1);
}
}
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.9)
project(RoadPlane_StereoMatching)
set(CMAKE_CXX_STANDARD 11)
find_package(OpenCV REQUIRED)
aux_source_directory(./ SOURCE_FILE)
add_executable(RoadPlane_StereoMatching ${SOURCE_FILE} MyDraw.h)
target_link_libraries(RoadPlane_StereoMatching ${OpenCV_LIBS})
#定义DEBUG_SHOW宏,该宏用于开发调试,显示过程信息
#option(DEBUG_mode "ON for debug or OFF for release" ON)
#IF(DEBUG_mode)
#ADD_DEFINITIONS(-DDEBUG_SHOW_RECTIFYIMAGE)
ADD_DEFINITIONS(-DDEBUG_SHOW_KERPOINTMATCH)
ADD_DEFINITIONS(-DDEBUG_SHOW_CONTOURS)
#ADD_DEFINITIONS(-DDEBUG_SHOW_HMATRIXRESULT)
#ENDIF()<file_sep>/Stereo_LaneDetection.h
//
// Created by nvidia on 7/30/18.
//
#ifndef ROADPLANE_STEREOMATCHING_STEREO_LANEDETECTION_H
#define ROADPLANE_STEREOMATCHING_STEREO_LANEDETECTION_H
#include <opencv2/opencv.hpp>
#include <iostream>
#include <vector>
using namespace std;
/********************************definition of coordination*********************************
* road coordination:original point on camera optical point,forward(+Z),right(+X),down(+Y)
* camera cooradination:original point on camera optical point,optical axis forward(+Z),right(+X),down(+Y)
* */
struct LaneDetectPara{
//...
};
struct MapINFO {
float laneArea_width;//meter
float laneNum;
float angle;//[-PI/2,PI/2],included angle of road and camera optical axis,camera optical axis is the datum,anti-clockwise is positive
//...
MapINFO():laneArea_width(2.5),laneNum(2),angle(-1000){};
};
struct ScanPoint{
cv::Point2f p;
int flag;
float confidence;
};
class Stereo_LaneDetection
{
public:
virtual ~Stereo_LaneDetection();
public:
Stereo_LaneDetection();
//input inital lane detection parameter
LaneDetectPara m_para;
//current map information
MapINFO m_mapInfo;
void init(LaneDetectPara ldp);//>>m_para
//current images and previous images
cv::Mat m_L_CurImgGrey,m_R_CurImgGrey,m_L_PreImgGrey,m_R_PreImgGrey;
//roadHMatrix(H):Homography Matrix of road plane(l_point=H*r_point)
cv::Mat m_roadHMatrix,m_initalRoadHMatrix;
//transMatrix(T):transform 3D points from previous frame to current current frame(cur_point3d=T*pre_point3d)
cv::Mat m_transMatrix;
//in_roadHMatrix(H):Homography Matrix of road plane(l_point=H*r_point)
//in_transMatrix(T):transform 3D points from previous frame to current current frame(cur_point3d=T*pre_point3d)
void run_lane_detection(cv::Mat in_L_img,cv::Mat in_R_img,cv::Mat in_roadHMatrix = cv::Mat(),
cv::Mat in_transMatrix = cv::Mat(),MapINFO in_mapInfo = MapINFO());
void get_candidate_lines_from_stereo_images();
vector<vector<ScanPoint>> m_pre_lane,m_cur_lane;
void lanes_tracing();
void single_line_tracing(vector<ScanPoint> in_lane,vector<ScanPoint> &out_cur_lane);
};
#endif //ROADPLANE_STEREOMATCHING_STEREO_LANEDETECTION_H
<file_sep>/Stereo_LaneDetection.cpp
//
// Created by nvidia on 7/30/18.
//
#include "Stereo_LaneDetection.h"
cv::Mat joint_stereoImage(cv::Mat l_img,cv::Mat r_img)
{
cv::Mat js(l_img.rows+r_img.rows,l_img.cols,l_img.type());
l_img.convertTo(js.rowRange(0,l_img.rows),js.type());
r_img.convertTo(js.rowRange(l_img.rows,js.rows),js.type());
return js;
}
Stereo_LaneDetection::Stereo_LaneDetection() {}
Stereo_LaneDetection::~Stereo_LaneDetection() {
}
void Stereo_LaneDetection::init(LaneDetectPara ldp) {
//m_para=...
//initialize lane tracing parameter>>m_scanlines
//calculate roadHMatrix based on initial parameter
//m_roadHMatrix=...
}
void Stereo_LaneDetection::run_lane_detection(cv::Mat in_L_img,cv::Mat in_R_img,cv::Mat in_roadHMatrix,
cv::Mat in_transMatrix,MapINFO in_mapInfo)
{
//check consistency of left image and right image
if(in_L_img.size()!=in_R_img.size()) return;
if(in_L_img.type()!=CV_8UC1)in_L_img.convertTo(m_L_CurImgGrey,CV_8UC1);
else m_L_CurImgGrey=in_L_img.clone();
if(in_R_img.type()!=CV_8UC1)in_R_img.convertTo(m_R_CurImgGrey,CV_8UC1);
else m_R_CurImgGrey=in_R_img.clone();
if(in_roadHMatrix.size()!=cv::Size(3,3)) in_roadHMatrix.convertTo(m_roadHMatrix,CV_32FC1);
else m_roadHMatrix=m_initalRoadHMatrix.clone();
if(in_transMatrix.size()!=cv::Size(4,4)) in_transMatrix.convertTo(m_transMatrix,CV_32FC1);
else m_transMatrix=cv::Mat::eye(4,4,CV_32FC1);
if(in_mapInfo.angle >= -CV_PI/2 && in_mapInfo.angle <= CV_PI/2) m_mapInfo=in_mapInfo;
else m_mapInfo.angle=-1000;
//get candidate lines from stereo images >> candidate points on scan lines
get_candidate_lines_from_stereo_images();
//lane tracing:m_pre_lane>>m_cur_lane
lanes_tracing();
//lanes analysis and fitting
//update tracing targets
//save current information as previous information of next frame
m_L_PreImgGrey=m_L_CurImgGrey.clone();
m_R_PreImgGrey=m_R_CurImgGrey.clone();
m_pre_lane.swap(m_cur_lane);
//...
}
void Stereo_LaneDetection::get_candidate_lines_from_stereo_images() {
//create canny edge map
cv::Mat t_L_blur,t_R_blur;
cv::Mat t_L_canny,t_R_canny;
cv::GaussianBlur(m_L_CurImgGrey,t_L_blur,cv::Size(5,5),2.0,2.0);
cv::GaussianBlur(m_R_CurImgGrey,t_R_blur,cv::Size(5,5),2.0,2.0);
cv::Canny(t_L_blur,t_L_canny,30,80);
cv::Canny(t_R_blur,t_R_canny,30,80);
//get contours from canny map
vector<vector<cv::Point>> t_L_contours,t_R_contours;
cv::findContours(t_L_canny,t_L_contours,CV_RETR_LIST,CV_CHAIN_APPROX_NONE);
cv::findContours(t_R_canny,t_R_contours,CV_RETR_LIST,CV_CHAIN_APPROX_NONE);
#ifdef DEBUG_SHOW_CONTOURS
cv::RNG rng;
for (int i = 0; i <t_L_contours.size(); ++i) {
if(t_L_contours[i].size()<30)continue;
cv::drawContours(m_L_CurImgGrey,t_L_contours,i,cv::Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)));
}
for (int i = 0; i <t_R_contours.size(); ++i) {
if(t_R_contours[i].size()<30)continue;
cv::drawContours(m_R_CurImgGrey,t_R_contours,i,cv::Scalar(rng.uniform(0,255),rng.uniform(0,255),rng.uniform(0,255)));
}
cv::imshow("CONTOURS",joint_stereoImage(m_L_CurImgGrey,m_R_CurImgGrey));
cv::waitKey(1);
#endif
//match contours using roadHMatrix
//judge up or down peak in canny map
}
void Stereo_LaneDetection::lanes_tracing() {
}
void Stereo_LaneDetection::single_line_tracing(vector<ScanPoint> in_pre_lane,vector<ScanPoint> &out_cur_lane) {
}<file_sep>/StereoMeasurement.h
#ifndef STEREOMEASUREMENT_H
#define STEREOMEASUREMENT_H
#include <opencv2/opencv.hpp>
#include <vector>
/*The coordinate of this class is defined as what opencv have defined(X:right,Y:down,Z:forward)
*
* */
using namespace std;
enum Stereo_State
{
STEREO_BAD,
STEREO_INITIAL_OK,
STEREO_RECTIFY_OK//图像已进行畸变校正
};
enum SPT_Type { SPT_SURF,SPT_SIFT,SPT_ORB };
struct Stereo_GPUbuffer
{
cv::Mat dis_LImg,dis_RImg,
undis_LImg,undis_RImg,
undis_LImgGrey,
undis_RImgGrey,
l_mask,r_mask,
rec_map[2][2],//remap()的映射矩阵.[0][0].[0][1]代表左相机的mapx,mapy;
temp_map[2],
temp_GreyImg;
};
class StereoMeasurement
{
public:
StereoMeasurement();
~StereoMeasurement();
//------------------------------camera-parameter---------------------------//
//主距
double m_l_focalLength, m_r_focalLength;
//distance between two cameras
double m_Base_length;
//左右相机内参矩阵
cv::Mat m_l_K, m_r_K;
//左右相机畸变参数
cv::Mat m_l_distor, m_r_distor;
//右相机到左相机的变换矩阵
cv::Mat m_r2l_Tran;
//最大视差,由相机基线和相机像素焦距决定,initial_stereo_system的结果
//单位:像素.含义:D=X_left - X_right
int m_max_disparity,m_min_disparity,m_max_yDisparityErr;
//stereo images recitification parameter
cv::Mat m_rec_Rl,//左相机到公共平面的旋转矩阵,大小:3x3
m_rec_Rr,//右相机到公共平面的旋转矩阵,大小:3x3
m_rec_Pl,//左相机投影矩阵--把三维空间的点投影到平面,大小:3x4
m_rec_Pr,//右相机投影矩阵,大小:3x4
m_rec_Q;//重投影矩阵--把图像上的点投影到三维空间,大小:视调用函数结果而定
//stereo images recitification parameter
cv::Mat m_rec_map[2][2];//remap()的映射矩阵.[0][0].[0][1]代表左相机的mapx,mapy;[1][0],[1][1]代表右相机的mapx,mapy
//Data allocations are very expensive on CUDA. Use a buffer to solve: allocate once reuse later.
Stereo_GPUbuffer m_gpu_buffer;
Stereo_State m_state;
//rectified image
cv::Mat m_undisLeftImg,m_undisRightImg;
//range of detection
double m_min_range,m_max_range;
//standard deviation of min_range and max_range
//标准差.
double m_min_sd,m_max_sd;
//初始化,in_left_K:内参矩阵 in_left_distor:畸变系数 in_r2l_Tran:右影像到左影像的变换矩阵 min/max_range:min/max range of detection
void initial_stereo_system(cv::Size image_size,cv::Mat in_left_K, cv::Mat in_right_K,
cv::Mat in_left_distor, cv::Mat in_right_distor, cv::Mat in_r2l_Tran, double min_range,double max_range);
//影像畸变纠正
void stereo_images_rectification(cv::Mat dis_leftImg, cv::Mat dis_rightImg, cv::Mat &undis_leftImg, cv::Mat &undis_rightImg);
//------------------------------KeyPoints-descripter---------------------------//
cv::Ptr<cv::ORB> m_gpu_orb;
//r_Pts[l_m_dest[i].queryIdx] is the match point of l_Pts[l_m_dest[i].trainIdx]
void run_ORB_KeyPoints_detection_and_matching(vector<cv::KeyPoint> &out_l_Pts,vector<cv::KeyPoint> &out_r_Pts,vector<cv::DMatch> &out_l_m_dest,
cv::Mat in_l_Mask,cv::Mat in_r_Mask);
//计算图像输入点的描述子
void get_points_descripter(int left_or_right, vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc,SPT_Type spt_type=SPT_ORB);
void get_points_SUFTdescripter(int left_or_right, vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc);
void get_points_ORBdescripter(int left_or_right, vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc);
void get_points_SIFTdescripter(int left_or_right, vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc);
//----------------------------------Matching-----------------------------------//
cv::Ptr<cv::DescriptorMatcher> m_DMatcher_normL2,m_DMatcher_normHammin;
//l_desc为referrenc,r_desc为target,匹配结果>>vector<int> t_m_dest对应右点集id;
void match_descripter_of_Pts(cv::Mat t_l_desc, cv::Mat t_r_desc, vector<cv::DMatch> &t_l_m_dest,SPT_Type spt_type=SPT_ORB);
void match_double_Points_implement(int left_or_right,vector<cv::KeyPoint> in_ref_Pts, vector<cv::KeyPoint> in_tar_Pts,cv::Mat reference_desc,cv::Mat target_desc,
vector<vector<cv::DMatch>> &m_dest, SPT_Type spt_type=SPT_ORB);
//进行左右一致性/双向验证检测>>vector<int> t_m_dest对应右点集id;
void leftRightConsistency_and_FBCheck(vector<vector<cv::DMatch>> t_l_m_dest, vector<vector<cv::DMatch>> t_r_m_dest, vector<vector<cv::DMatch>> &t_l_consistency_dest);
//在已有匹配结果上,获取亚像素精度的视差
void get_subpixel_disparity(cv::Mat in_leftImg, cv::Mat in_rightImg, vector<cv::KeyPoint> in_l_Pts,
vector<int> t_l_consistency_dest, vector<double> &t_out_disp);
//计算左点集在右图像上的候选区域
void get_candidate_corresponding_area_of_leftPts(vector<cv::KeyPoint> in_l_Pts, vector< vector<cv::KeyPoint>> &t_cand_rightPts);
//根据相机内参、视差,计算点集的空间坐标
void cal_Points_3D_coordinate(cv::Mat in_K, vector<cv::KeyPoint> in_l_Pts, vector<double> t_out_disp, vector<cv::Point3d> &out_l_Pts);
//对点集进行测量:输出左影像点集在左相机空间坐标系的坐标
void run_points_measurement_process(vector<cv::KeyPoint> in_l_Pts, vector<cv::KeyPoint> in_r_Pts,
vector<cv::Point3d> &out_l_Pts, SPT_Type spt_type = SPT_ORB);
//对左点集进行图像匹配
void matching_single_Points_process(vector<cv::KeyPoint> in_l_Pts,vector<cv::DMatch> &out_matchID,SPT_Type spt_type=SPT_ORB);
//对左点-右点集进行图像匹配
void matching_double_Points_process(vector<cv::KeyPoint> in_l_Pts, vector<cv::KeyPoint> in_r_Pts, vector<cv::DMatch> &out_matchID,SPT_Type spt_type=SPT_ORB);
};
#endif
<file_sep>/main.cpp
#include <iostream>
#include <opencv2/opencv.hpp>
#include "RoadPlane_Estimation.h"
#include "Stereo_LaneDetection.h"
#include <sys/timeb.h>
using namespace std;
using namespace cv;
int myget_time()
{
time_t t_sec0;
struct timeb tb_start;
ftime(&tb_start);
time(&t_sec0);
return (int)(t_sec0*1000+tb_start.millitm);
}
int main()
{
rm::RoadPlane_Estimation road_estimator;
Stereo_LaneDetection lane_detector;
rm::Stereo_CamPara scp;
//camera intrinsic matrix
double K[]={718.856,0.0,607.1928,
0.0,718.856,185.2157,
0.0,0.0,1.0};
//transform matrix of right image coordinate to left image coordinate
double r2l_trans[]={1.0,0.0,0.0,1.0,
0.0,1.0,0.0,0.0,
0.0,0.0,1.0,0.0,
0.0,0.0,0.0,1.0};//因为目前读取的图像已经进行校正过,故该矩阵设为1,即:右图像到左图像不用进行旋转和平移
cv::Mat left_K(3,3,CV_64FC1,K);//intrinsic
cv::Mat right_K(3,3,CV_64FC1,K);//intrinsic
cv::Mat distor_M=cv::Mat::zeros(1,5,CV_64FC1);//distortion matrix of camera
cv::Mat trans_r2l_M(4,4,CV_64FC1,r2l_trans);//r2l
scp.left_K=left_K; scp.right_K=right_K;
scp.left_distor=distor_M; scp.right_distor=distor_M;
scp.r2l_Tran=trans_r2l_M;
scp.init_cam_height=1.50;
scp.init_cam_pitch=0.0;
scp.image_size = cv::Size(1242,375);
scp.min_range=4;
scp.max_range=50;
road_estimator.init(scp);
cv::VideoCapture left_reader,right_reader;
if(!left_reader.open("/home/nvidia/Pictures/03/left/%06d.png")){cerr<<"error in opening video_1!"<<endl;return -1;}
if(!right_reader.open("/home/nvidia/Pictures/03/right/%06d.png")){cerr<<"error in opening video_2!"<<endl;return -1;}
while(1)
{
Mat img1,img2;
if(!left_reader.read(img1)){cerr<<"error in reading video_1!"<<endl;break;}
if(!right_reader.read(img2)){cerr<<"error in reading video_2!"<<endl;break;}
int tstart=myget_time();
//road plane estimation
road_estimator.run_road_plane_estimation(img1,img2);
//lane detection
lane_detector.run_lane_detection(road_estimator.m_undistorLimg,road_estimator.m_undistorRimg,road_estimator.m_road_HMatrix);
cout<<"total:"<<myget_time()- tstart << " ms" << std::endl;
int c=cv::waitKey(1);
if(c==27){ break;}
}//while
return 0;
}<file_sep>/StereoMeasurement.cpp
#include "StereoMeasurement.h"
#include "MyDraw.h"
StereoMeasurement::StereoMeasurement()
{
m_state = STEREO_BAD;
}
StereoMeasurement::~StereoMeasurement()
{
}
void StereoMeasurement::initial_stereo_system(cv::Size image_size,cv::Mat in_left_K, cv::Mat in_right_K,
cv::Mat in_left_distor, cv::Mat in_right_distor, cv::Mat in_r2l_Tran,
double min_range,double max_range)
{
if (in_left_K.rows!=3 || in_left_K.cols != 3 || in_right_K.rows != 3 || in_right_K.cols != 3
|| in_r2l_Tran.rows != 4 || in_r2l_Tran.cols != 4
|| in_left_distor.cols!=5 || in_left_distor.rows!=1 || in_right_distor.cols!=5 || in_right_distor.rows!=1)
{
m_state = STEREO_BAD;
cerr<<"paramerter data error!"<<endl;
return;
}
m_l_K = in_left_K.clone(); m_r_K = in_right_K.clone();
m_l_distor = in_left_distor.clone(); m_r_distor = in_right_distor.clone();
m_r2l_Tran = in_r2l_Tran.clone();
m_l_focalLength = (m_l_K.at<double>(0, 0) + m_l_K.at<double>(1, 1)) / 2;
m_r_focalLength = (m_r_K.at<double>(0, 0) + m_r_K.at<double>(1, 1)) / 2;
m_min_range=min_range>0.0f?min_range:0.0f;
m_max_range=max_range>0.0f?max_range:0.0f;
m_Base_length=sqrt(m_r2l_Tran.at<double>(0,3)*m_r2l_Tran.at<double>(0,3)+
m_r2l_Tran.at<double>(1,3)*m_r2l_Tran.at<double>(1,3)+
m_r2l_Tran.at<double>(2,3)*m_r2l_Tran.at<double>(2,3));
//calculate standard deviation
m_min_sd=(m_min_range*m_min_range)/(m_l_focalLength*m_Base_length);
m_max_sd=(m_max_range*m_max_range)/(m_l_focalLength*m_Base_length);
m_min_disparity=(m_l_focalLength*m_Base_length)/m_max_range;
m_max_disparity=(m_l_focalLength*m_Base_length)/m_min_range;
m_max_disparity=m_max_disparity>255?255:m_max_disparity;
m_min_disparity=m_min_disparity<0?0:m_min_disparity;
m_max_yDisparityErr=1;
//rectify
cv::Mat t_R=m_r2l_Tran.rowRange(0,3).colRange(0,3).inv();//left image to right image
cv::Mat t_T=-t_R*m_r2l_Tran.rowRange(0,3).col(3);//left image to right image
cv::stereoRectify(m_l_K,m_l_distor,m_r_K,m_r_distor,image_size
,t_R,t_T,m_rec_Rl,m_rec_Rr,m_rec_Pl,m_rec_Pr,m_rec_Q,cv::CALIB_ZERO_DISPARITY,0);//设置CV_CALIB_ZERO_DISPARITY,函数的作用是使每个相机的主点在校正后的图像上有相同的像素坐标。
//计算映射
//计算图像的映射表 mapx,mapy
//mapx,mapy这两个映射表接下来可以给remap()函数调用,来校正图像,使得两幅图像共面并且行对准
cv::initUndistortRectifyMap(m_l_K,m_l_distor, m_rec_Rl, m_rec_Pl, image_size, CV_32FC1, m_rec_map[0][0], m_rec_map[0][1]);
cv::initUndistortRectifyMap(m_r_K,m_r_distor, m_rec_Rr, m_rec_Pr, image_size, CV_32FC1, m_rec_map[1][0], m_rec_map[1][1]);
m_gpu_buffer.rec_map[0][0]=m_rec_map[0][0].clone();
m_gpu_buffer.rec_map[0][1]=m_rec_map[0][1].clone();
m_gpu_buffer.rec_map[1][0]=m_rec_map[1][0].clone();
m_gpu_buffer.rec_map[1][1]=m_rec_map[1][1].clone();
m_gpu_buffer.temp_map[0].create(image_size,CV_32FC1);
m_gpu_buffer.temp_map[1].create(image_size,CV_32FC1);
//initialize gpu images
m_gpu_buffer.dis_LImg.create(image_size,CV_8UC3);
m_gpu_buffer.dis_RImg.create(image_size,CV_8UC3);
m_gpu_buffer.undis_LImg.create(image_size,CV_8UC3);
m_gpu_buffer.undis_RImg.create(image_size,CV_8UC3);
m_gpu_buffer.undis_LImgGrey.create(image_size,CV_8UC1);
m_gpu_buffer.undis_RImgGrey.create(image_size,CV_8UC1);
m_gpu_buffer.l_mask.create(image_size,CV_8UC1);
m_gpu_buffer.r_mask.create(image_size,CV_8UC1);
m_gpu_buffer.temp_GreyImg.create(image_size,CV_8UC1);
m_DMatcher_normHammin=cv::DescriptorMatcher::create(cv::NORM_HAMMING);
m_DMatcher_normL2=cv::DescriptorMatcher::create(cv::NORM_L2);
//initialize points detector
//m_gpu_orb=cv::ORB::create(250,0.8f,4,50,0,2,cv::ORB::FAST_SCORE,7,10);
m_gpu_orb=cv::ORB::create();
m_state = STEREO_INITIAL_OK;
}
//影像畸变纠正
void StereoMeasurement::stereo_images_rectification(cv::Mat dis_leftImg, cv::Mat dis_rightImg, cv::Mat & undis_leftImg, cv::Mat & undis_rightImg)
{
if (m_state == STEREO_BAD)
{
cerr<<"initial_error!"<<endl;
return;
}//if rectification isn't work
m_gpu_buffer.dis_LImg=dis_leftImg.clone();
m_gpu_buffer.dis_RImg=dis_rightImg.clone();
//rectify image by remap
cv::remap(m_gpu_buffer.dis_LImg, m_gpu_buffer.undis_LImg, m_gpu_buffer.rec_map[0][0], m_gpu_buffer.rec_map[0][1], cv::INTER_LINEAR);//左校正
cv::remap(m_gpu_buffer.dis_RImg, m_gpu_buffer.undis_RImg, m_gpu_buffer.rec_map[1][0], m_gpu_buffer.rec_map[1][1], cv::INTER_LINEAR);//右校正
undis_leftImg = m_gpu_buffer.undis_LImg.clone();
undis_rightImg = m_gpu_buffer.undis_RImg.clone();
m_undisLeftImg=undis_leftImg.clone();
m_undisRightImg=undis_rightImg.clone();
m_state = STEREO_RECTIFY_OK;
//将校正后的图像显示出来,查看结果
#ifdef DEBUG_SHOW_RECTIFYIMAGE
cv::Mat showImage(dis_leftImg.size().height,2*dis_leftImg.size().width,CV_8UC3);
//将校正后的图像合并在一张图上
cv::Rect rectLeft(0,0,dis_leftImg.size().width,dis_leftImg.size().height);
cv::Rect rectRight(dis_leftImg.size().width,0,dis_leftImg.size().width,dis_leftImg.size().height);
undis_leftImg.copyTo(showImage(rectLeft));
undis_rightImg.copyTo(showImage(rectRight));
//画上对应的线条
for (int i = 0; i < 10; ++i)
{
cv::line(showImage,cv::Point(0,showImage.rows*i/10),cv::Point(showImage.cols,showImage.rows*i/10),cv::Scalar(0,255,0));
}
cv::resize(showImage, showImage, cv::Size(dis_leftImg.cols,dis_leftImg.rows/2), 0, 0, cv::INTER_LINEAR);//将图像大小调整为左相机图片一样大小,方便查看
cv::imshow("image after remap()",showImage);
cv::moveWindow("image after remap()",0,0);
cv::waitKey(1);
#endif
}
void StereoMeasurement::get_points_descripter(int left_or_right, vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc,SPT_Type spt_type)
{
switch(spt_type)
{
case SPT_SURF:
get_points_SUFTdescripter(left_or_right,in_Pts,t_out_desc);
break;
case SPT_ORB:
get_points_ORBdescripter(left_or_right,in_Pts,t_out_desc);
break;
case SPT_SIFT:
get_points_SIFTdescripter(left_or_right,in_Pts,t_out_desc);
break;
}
}
void StereoMeasurement::get_points_SUFTdescripter(int left_or_right, std::vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc){
}
void StereoMeasurement::get_points_ORBdescripter(int left_or_right, std::vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc){
cv::/*cuda::*/Mat t_desc;
if(left_or_right==-1 && in_Pts.size()>0)m_gpu_orb->compute(m_gpu_buffer.undis_LImgGrey,in_Pts,t_desc);
if(left_or_right== 1 && in_Pts.size()>0)m_gpu_orb->compute(m_gpu_buffer.undis_RImgGrey,in_Pts,t_desc);
t_out_desc = t_desc.clone();
}
void StereoMeasurement::get_points_SIFTdescripter(int left_or_right, std::vector<cv::KeyPoint> in_Pts, cv::Mat &t_out_desc){
}
void StereoMeasurement::match_descripter_of_Pts(cv::Mat t_l_desc, cv::Mat t_r_desc, std::vector<cv::DMatch> &t_l_m_dest,SPT_Type spt_type)
{
vector<vector<cv::DMatch>> temp_matchs;
switch (spt_type)
{
case SPT_ORB:
//m_DMatcher_normHammin->match(t_l_desc,t_r_desc,t_l_m_dest);
m_DMatcher_normHammin->knnMatch(t_l_desc,t_r_desc,temp_matchs,3);
break;
case SPT_SURF:
break;
case SPT_SIFT:
break;
}
t_l_m_dest.swap(temp_matchs[0]);
}
void StereoMeasurement::leftRightConsistency_and_FBCheck(vector<vector<cv::DMatch>> t_l_m_dest, vector<vector<cv::DMatch>> t_r_m_dest, vector<vector<cv::DMatch>> &out_matchID) {
//---------------Identify left-right consistency---------------//
//find max id of right key points
int tr_maxSize = 0;
for (int i = 0; i < t_l_m_dest.size(); ++i)
{
for (int j = 0; j < t_l_m_dest[i].size(); ++j)
{
if (t_l_m_dest[i][j].trainIdx > tr_maxSize)
tr_maxSize = t_l_m_dest[i][j].trainIdx;
}//for(j)
}//for(i)
for (int i = 0; i < t_r_m_dest.size(); ++i)
{
for (int j = 0; j < t_r_m_dest[i].size(); ++j)
{
if (t_r_m_dest[i][j].queryIdx > tr_maxSize)
tr_maxSize = t_r_m_dest[i][j].queryIdx;
}//for(j)
}//for(i)
tr_maxSize++;
//create a look up table of right points
vector<int> r_matchID_table(tr_maxSize,-1);
for (int i = 0; i < t_r_m_dest.size(); ++i) r_matchID_table[t_r_m_dest[i][0].queryIdx]= i;
//find point which fits left-right consistency
vector<vector<cv::DMatch>> ().swap(out_matchID);
out_matchID.reserve(t_l_m_dest.size());
for (int i = 0; i < t_l_m_dest.size(); ++i)
{
vector<cv::DMatch> temp_l; temp_l.reserve(3);
for (int j = 0; j < t_l_m_dest[i].size(); ++j)
{
if(r_matchID_table[t_l_m_dest[i][j].trainIdx]>=0)
{
int tidx=r_matchID_table[t_l_m_dest[i][j].trainIdx];
for (int k = 0; k <t_r_m_dest[tidx].size(); ++k)
{
if(t_r_m_dest[tidx][k].trainIdx == t_l_m_dest[i][j].queryIdx) temp_l.push_back(t_l_m_dest[i][j]);
}//for(k)
}//if
}//for(j)
if(temp_l.size()>0) out_matchID.push_back(temp_l);
}//for(i)
}
void StereoMeasurement::get_subpixel_disparity(cv::Mat in_leftImg, cv::Mat in_rightImg, vector<cv::KeyPoint> in_l_Pts,
vector<int> t_l_consistency_dest, vector<double> &t_out_disp)
{
}
void StereoMeasurement::get_candidate_corresponding_area_of_leftPts(vector<cv::KeyPoint> in_l_Pts, vector<vector<cv::KeyPoint>>& t_cand_rightPts)
{
}
void StereoMeasurement::cal_Points_3D_coordinate(cv::Mat in_K, vector<cv::KeyPoint> in_l_Pts, vector<double> t_out_disp, vector<cv::Point3d>& out_l_Pts)
{
}
void StereoMeasurement::run_points_measurement_process(vector<cv::KeyPoint> in_l_Pts, vector<cv::KeyPoint> in_r_Pts,
vector<cv::Point3d> &out_l_Pts, SPT_Type spt_type)
{
vector<double> t_out_disp(in_l_Pts.size(),0.0f);
vector<cv::DMatch> t_out_matchID;
//two matching mode
if (in_r_Pts.size() == 0)
matching_single_Points_process(in_l_Pts, t_out_matchID,spt_type);
else
matching_double_Points_process(in_l_Pts, in_r_Pts, t_out_matchID,spt_type);
//cal disparity
for (int i = 0; i < t_out_matchID.size(); ++i) {
auto tm=t_out_matchID[i];
t_out_disp[tm.trainIdx]=((double)(in_r_Pts[tm.queryIdx].pt.x-in_l_Pts[tm.trainIdx].pt.x));
}//for(i)
cal_Points_3D_coordinate(m_l_K, in_l_Pts, t_out_disp, out_l_Pts);
}
void StereoMeasurement::matching_single_Points_process(vector<cv::KeyPoint> in_l_Pts,
vector<cv::DMatch> &out_matchID,SPT_Type spt_type)
{
vector<vector<cv::KeyPoint>> t_cand_rightPts;
get_candidate_corresponding_area_of_leftPts(in_l_Pts, t_cand_rightPts);//>>vector<vector<Point2d>>cand_rightPts
for (int i = 0; i < in_l_Pts.size(); i++) {
vector<cv::KeyPoint> t_in_l_P(1);
t_in_l_P[0] = in_l_Pts[i];
matching_double_Points_process(t_in_l_P, t_cand_rightPts[i], out_matchID,spt_type);
//.............
}//for(i)
}
void StereoMeasurement::matching_double_Points_process(vector<cv::KeyPoint> in_l_Pts, vector<cv::KeyPoint> in_r_Pts,
vector<cv::DMatch> &out_matchID,SPT_Type spt_type)
{
cv::Mat t_out_l_desc, t_out_r_desc;
get_points_descripter(-1, in_l_Pts, t_out_l_desc,spt_type);//根据特征点计算描述子
get_points_descripter( 1, in_r_Pts, t_out_r_desc,spt_type);
std::vector<vector<cv::DMatch>> t_l_m_dest, t_r_m_dest,t_matchID;
//left reference:find best-fit target from candidate points
match_double_Points_implement(-1,in_l_Pts,in_r_Pts,t_out_l_desc,t_out_r_desc,t_l_m_dest,spt_type);
//right reference:find best-fit target from candidate points
match_double_Points_implement( 1,in_r_Pts,in_l_Pts,t_out_r_desc,t_out_l_desc,t_r_m_dest,spt_type);
leftRightConsistency_and_FBCheck(t_l_m_dest, t_r_m_dest, t_matchID);//取交集
//find optimal matching set
vector<cv::DMatch> ().swap(out_matchID); out_matchID.reserve(t_matchID.size());
for (int i = 0; i < t_matchID.size(); ++i)
{
cv::DMatch tdm=t_matchID[i][0];
for (int j = 0; j < t_matchID[i].size(); ++j)
{
if(t_matchID[i][j].distance<tdm.distance) tdm=t_matchID[i][j];
}//for(j)
out_matchID.push_back(tdm);
}//for(i)
//-----------------------debug----------------------//
#ifdef DEBUG_SHOW_KERPOINTMATCH
cv::Mat show_matching_l;
cv::drawMatches(m_undisLeftImg,in_l_Pts,m_undisRightImg,in_r_Pts,out_matchID,show_matching_l,cv::Scalar(0,255,0),cv::Scalar(0,0,255));
rm::drawVerticalMatches(m_undisLeftImg,in_l_Pts,m_undisRightImg,in_r_Pts,t_matchID[0],show_matching_l);
cv::imshow("show_matching_l",show_matching_l);
cv::waitKey(1);
#endif
}
//train query
void StereoMeasurement::match_double_Points_implement(int left_or_right, vector<cv::KeyPoint> in_ref_Pts, vector<cv::KeyPoint> in_tar_Pts,
cv::Mat ref_desc,cv::Mat tar_desc,vector<vector<cv::DMatch>> &m_dest,SPT_Type spt_type){
for (int i = 0; i <in_ref_Pts.size(); i++)
{
std::vector<cv::DMatch> temp_m_dest;
cv::Mat temp_l_desc;
temp_l_desc=ref_desc.row(i).clone();
std::vector<int> temp_r_id;
temp_r_id.reserve(10);
int trefNUM=in_ref_Pts.size();
int ttarNUM=in_tar_Pts.size();
if(trefNUM!=ref_desc.rows || ttarNUM!=tar_desc.rows)
{
return;
}
//pick candidate Pts
for (int j = 0; j <in_tar_Pts.size(); j++)
{
if(left_or_right== 1)
{
if((in_tar_Pts[j].pt.x-in_ref_Pts[i].pt.x)<=m_max_disparity &&
(in_tar_Pts[j].pt.x-in_ref_Pts[i].pt.x)>=0 &&
abs(in_tar_Pts[j].pt.y-in_ref_Pts[i].pt.y)<=m_max_yDisparityErr)
temp_r_id.push_back(j);
}
else
{
if((in_ref_Pts[i].pt.x-in_tar_Pts[j].pt.x)<=m_max_disparity &&
(in_ref_Pts[i].pt.x-in_tar_Pts[j].pt.x)>=0 &&
abs(in_ref_Pts[i].pt.y-in_tar_Pts[j].pt.y)<=m_max_yDisparityErr)
temp_r_id.push_back(j);
}
}//for(j)
if(temp_r_id.size()<1)
{
//no candidate points
//m_dest.push_back(cv::DMatch(i,-1,10000.0f));
}
else
{
cv::Mat temp_r_desc(temp_r_id.size(),tar_desc.cols,tar_desc.type());//存储候选点描述子
for (int j = 0; j <temp_r_id.size(); j++) temp_r_desc.row(j)=tar_desc.row(temp_r_id[j]).clone();
//find best-fit target
match_descripter_of_Pts(temp_l_desc, temp_r_desc, temp_m_dest,spt_type);
if(temp_m_dest.size()>0)
{
for (int j = 0; j < temp_m_dest.size(); ++j)
{
temp_m_dest[j].queryIdx=i;
temp_m_dest[j].trainIdx=temp_r_id[temp_m_dest[j].trainIdx];
}//for(j)
m_dest.push_back(temp_m_dest);
}//if
}//if
}//for(i)
}
void StereoMeasurement::run_ORB_KeyPoints_detection_and_matching(vector<cv::KeyPoint> &out_l_Pts,
vector<cv::KeyPoint> &out_r_Pts,
vector<cv::DMatch> &out_l_m_dest,
cv::Mat in_l_Mask,cv::Mat in_r_Mask)
{
if(m_state==STEREO_RECTIFY_OK)
{
//对BGR空间的图像直接进行计算很费时间,所以,需要转换为灰度图
//convert image on gpu
cv::cvtColor(m_gpu_buffer.undis_LImg,m_gpu_buffer.undis_LImgGrey,CV_BGR2GRAY);
cv::cvtColor(m_gpu_buffer.undis_RImg,m_gpu_buffer.undis_RImgGrey,CV_BGR2GRAY);
//upload mask to gpu
if(in_l_Mask.size() == m_undisLeftImg.size() && in_r_Mask.size() == m_undisLeftImg.size())
{
m_gpu_buffer.l_mask=in_l_Mask.clone();
m_gpu_buffer.r_mask=in_r_Mask.clone();
}
else
{
m_gpu_buffer.l_mask.setTo(cv::Scalar(255));
m_gpu_buffer.r_mask.setTo(cv::Scalar(255));
}
//get ORB key points
//首先对两幅图像进行特征点的检测(描述子的计算在后面进行计算)
//Mask specifying where to look for keypoints (optional). It must be a 8-bit integer
// matrix with non-zero values in the region of interest.
//so 在路面进行特征点检测
m_gpu_orb->detect(m_gpu_buffer.undis_LImgGrey,out_l_Pts,m_gpu_buffer.l_mask);
m_gpu_orb->detect(m_gpu_buffer.undis_RImgGrey,out_r_Pts,m_gpu_buffer.r_mask);
SPT_Type t_spt_type=SPT_ORB;
matching_double_Points_process(out_l_Pts,out_r_Pts,out_l_m_dest,t_spt_type);
}
else
{
std::cout<<"Rectification of stereo images is not successful! stop points detection!" <<std::endl;
}
}
<file_sep>/RoadPlane_Estimation.h
//
// Created by nvidia on 7/17/18.
//
#ifndef ROADPLANE_ESTIMATION_H
#define ROADPLANE_ESTIMATION_H
#include "StereoMeasurement.h"
#include <opencv2/opencv.hpp>
#include <sys/timeb.h>
namespace rm
{
using cv::Mat;
using std::cout;using std::cin;using std::vector;
struct Stereo_CamPara
{
cv::Size image_size;
cv::Mat left_K, right_K;//左右相机内参矩阵
cv::Mat left_distor, right_distor;//左右相机畸变参数
cv::Mat r2l_Tran;//右相机到左相机的变换矩阵
double init_cam_height,init_cam_pitch;//相机初始高度,俯仰角
double min_range, max_range;//min/max range of detection
Stereo_CamPara():init_cam_height(0.0),init_cam_pitch(0.0),min_range(0.0),max_range(30.0){};
};
class RoadPlane_Estimation {
public:
RoadPlane_Estimation();
virtual ~RoadPlane_Estimation();
//stereo matching implementation
StereoMeasurement m_stereoMeasurer;
//initial camera height and pitch
//相机高度以及相机俯仰角
double m_camHeight,m_camPitch;
//undistortion image after preprocessing
Mat m_undistorLimg,m_undistorRimg;
//segment resuilt has a same size with undistorL/Rimg
Mat m_l_segImg,m_r_segImg;
//road roi mask:only 255 represent road
Mat m_l_roadROI,m_r_roadROI;
//key points in road roi
vector<cv::KeyPoint> m_l_roadKPts,m_r_roadKPts;
//left and right match key point ID
vector<cv::DMatch> m_roadKPts_matchID;
//homography matrix of object plane
Mat m_road_HMatrix;
//Object boundry
vector<cv::Point2i> m_roadBoundry;
public:
//initializa stereo camera system and road model
void init(Stereo_CamPara& in_stereo_camPara);
void run_road_plane_estimation(Mat in_leftImg,Mat in_rightImg);
private:
//去除图像畸变
void preprocess_stereo_images(Mat in_leftImg,Mat in_rightImg,Mat &out_leftImg,Mat &out_rightImg);
//out_segImg contains several kinds of color representing object classes
void segment_images(Mat in_Img,Mat &out_segImg);
//--------for-test--------//
int m_cur_frameID = 0;//for test
void segment_i_images(Mat in_Img,int left_or_right,Mat &out_segImg);
//--------for-test--------//
void get_objectROI_from_segImg(Mat in_segImg,cv::Scalar obj_classColor,Mat &out_objectROI);
void calculate_homography_matrix(vector<cv::KeyPoint> in_l_KPts,vector<cv::KeyPoint> in_r_KPts,
vector<cv::DMatch> in_KPts_matchID,Mat &out_ObjectHMatrix);
void get_object_boundry(Mat in_ObjectHMatrix,vector<cv::Point2i> &out_ObjectBoundry);
};
}
#endif //ROADPLANE_ESTIMATION_H
<file_sep>/README.md
#说明
双目视觉用于车道线检测.目前代码尚未完成.
12.45 mnk
<file_sep>/MyDraw.h
/*M///////////////////////////////////////////////////////////////////////////////////////
//
// IMPORTANT: READ BEFORE DOWNLOADING, COPYING, INSTALLING OR USING.
//
// By downloading, copying, installing or using the software you agree to this license.
// If you do not agree to this license, do not download, install,
// copy or use the software.
//
//
// Intel License Agreement
// For Open Source Computer Vision Library
//
// Copyright (C) 2000, Intel Corporation, all rights reserved.
// Third party copyrights are property of their respective owners.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistribution's of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * Redistribution's in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// * The name of Intel Corporation may not be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// This software is provided by the copyright holders and contributors "as is" and
// any express or implied warranties, including, but not limited to, the implied
// warranties of merchantability and fitness for a particular purpose are disclaimed.
// In no event shall the Intel Corporation or contributors be liable for any direct,
// indirect, incidental, special, exemplary, or consequential damages
// (including, but not limited to, procurement of substitute goods or services;
// loss of use, data, or profits; or business interruption) however caused
// and on any theory of liability, whether in contract, strict liability,
// or tort (including negligence or otherwise) arising in any way out of
// the use of this software, even if advised of the possibility of such damage.
//
//M*/
#ifndef MY_DRAW_CPP
#define MY_DRAW_CPP
const int draw_shift_bits = 4;
const int draw_multiplier = 1 << draw_shift_bits;
#include <opencv2/opencv.hpp>
//#include <opencv2/features2d.hpp>
//#include "opencv2/imgproc.hpp"
//
//#include "opencv2/core/utility.hpp"
//#include "opencv2/core/private.hpp"
//#include "opencv2/core/ocl.hpp"
//#include "opencv2/core/hal/hal.hpp"
namespace rm
{
/*
* Functions to draw keypoints and matches.
*/
static inline void
_drawKeypoint(cv::InputOutputArray img, const cv::KeyPoint &p, const cv::Scalar &color, int flags)
{
CV_Assert(!img.empty());
cv::Point center(cvRound(p.pt.x * draw_multiplier), cvRound(p.pt.y * draw_multiplier));
if (flags & cv::DrawMatchesFlags::DRAW_RICH_KEYPOINTS)
{
int radius = cvRound(p.size / 2 * draw_multiplier); // KeyPoint::size is a diameter
// draw the circles around keypoints with the keypoints size
circle(img, center, radius, color, 1, cv::LINE_AA, draw_shift_bits);
// draw orientation of the keypoint, if it is applicable
if (p.angle != -1)
{
float srcAngleRad = p.angle * (float) CV_PI / 180.f;
cv::Point orient(cvRound(cos(srcAngleRad) * radius),
cvRound(sin(srcAngleRad) * radius)
);
line(img, center, center + orient, color, 1, cv::LINE_AA, draw_shift_bits);
}
#if 0
else
{
// draw center with R=1
int radius = 1 * draw_multiplier;
circle( img, center, radius, color, 1, LINE_AA, draw_shift_bits );
}
#endif
}
else
{
// draw center with R=3
int radius = 3 * draw_multiplier;
circle(img, center, radius, color, 1, cv::LINE_AA, draw_shift_bits);
}
}
// void drawKeypoints( cv::InputArray image, const std::vector<cv::KeyPoint>& keypoints, cv::InputOutputArray outImage,
// const cv::Scalar& _color, int flags )
// {
// //cv::CV_INSTRUMENT_REGION()
//
// if( !(flags & cv::DrawMatchesFlags::DRAW_OVER_OUTIMG) )
// {
// if( image.type() == CV_8UC3 )
// {
// image.copyTo( outImage );
// }
// else if( image.type() == CV_8UC1 )
// {
// cvtColor( image, outImage, cv::COLOR_GRAY2BGR );
// }
// else
// {
// CV_Error( cv::Error::StsBadArg, "Incorrect type of input image.\n" );
// }
// }
//
// cv::RNG& rng=cv::theRNG();
// bool isRandColor = _color == cv::Scalar::all(-1);
//
// CV_Assert( !outImage.empty() );
// std::vector<cv::KeyPoint>::const_iterator it = keypoints.begin(),
// end = keypoints.end();
// for( ; it != end; ++it )
// {
// cv::Scalar color = isRandColor ? cv::Scalar(rng(256), rng(256), rng(256)) : _color;
// _drawKeypoint( outImage, *it, color, flags );
// }
// }
static void _prepareImgAndDrawKeypoints(cv::InputArray img1, const std::vector<cv::KeyPoint> &keypoints1,
cv::InputArray img2, const std::vector<cv::KeyPoint> &keypoints2,
cv::InputOutputArray _outImg, cv::Mat &outImg1, cv::Mat &outImg2,
const cv::Scalar &singlePointColor, int flags)
{
cv::Mat outImg;
cv::Size img1size = img1.size(), img2size = img2.size();
cv::Size size(MAX(img1size.width, img2size.width), img1size.height + img2size.height);
//cv::Size size( img1size.width + img2size.width, MAX(img1size.height, img2size.height) );
if (flags & cv::DrawMatchesFlags::DRAW_OVER_OUTIMG)
{
outImg = _outImg.getMat();
if (size.width > outImg.cols || size.height > outImg.rows)
CV_Error(cv::Error::StsBadSize, "outImg has size less than need to draw img1 and img2 together");
//outImg1 = outImg( cv::Rect(0, 0, img1size.width, img1size.height) );
//outImg2 = outImg( cv::Rect(img1size.width, 0, img2size.width, img2size.height) );
outImg1 = outImg(cv::Rect(0, 0, img1size.width, img1size.height));
outImg2 = outImg(cv::Rect(0, img1size.height, img2size.width, img2size.height));
}
else
{
_outImg.create(size, CV_MAKETYPE(img1.depth(), 3));
outImg = _outImg.getMat();
outImg = cv::Scalar::all(0);
//outImg1 = outImg( cv::Rect(0, 0, img1size.width, img1size.height) );
//outImg2 = outImg( cv::Rect(img1size.width, 0, img2size.width, img2size.height) );
outImg1 = outImg(cv::Rect(0, 0, img1size.width, img1size.height));
outImg2 = outImg(cv::Rect(0, img1size.height, img2size.width, img2size.height));
if (img1.type() == CV_8U)
cvtColor(img1, outImg1, cv::COLOR_GRAY2BGR);
else
img1.copyTo(outImg1);
if (img2.type() == CV_8U)
cvtColor(img2, outImg2, cv::COLOR_GRAY2BGR);
else
img2.copyTo(outImg2);
}
// draw keypoints
if (!(flags & cv::DrawMatchesFlags::NOT_DRAW_SINGLE_POINTS))
{
cv::Mat _outImg1 = outImg(cv::Rect(0, 0, img1size.width, img1size.height));
drawKeypoints(_outImg1, keypoints1, _outImg1, singlePointColor,
flags | cv::DrawMatchesFlags::DRAW_OVER_OUTIMG);
//cv::Mat _outImg2 = outImg( cv::Rect(img1size.width, 0, img2size.width, img2size.height) );
cv::Mat _outImg2 = outImg(cv::Rect(0, img1size.height, img2size.width, img2size.height));
drawKeypoints(_outImg2, keypoints2, _outImg2, singlePointColor,
flags | cv::DrawMatchesFlags::DRAW_OVER_OUTIMG);
}
}
static inline void
_drawVerticalMatch(cv::InputOutputArray outImg, cv::InputOutputArray outImg1, cv::InputOutputArray outImg2,
const cv::KeyPoint &kp1, const cv::KeyPoint &kp2, const cv::Scalar &matchColor, int flags)
{
cv::RNG &rng = cv::theRNG();
bool isRandMatchColor = matchColor == cv::Scalar::all(-1);
cv::Scalar color = isRandMatchColor ? cv::Scalar(rng(256), rng(256), rng(256)) : matchColor;
_drawKeypoint(outImg1, kp1, color, flags);
_drawKeypoint(outImg2, kp2, color, flags);
cv::Point2f pt1 = kp1.pt,
pt2 = kp2.pt,
//dpt2 = cv::Point2f(std::min(pt2.x + outImg1.size().width, float(outImg.size().width - 1)), pt2.y),
dpt2 = cv::Point2f(pt2.x, std::min(pt2.y + outImg1.size().height, float(outImg.size().height - 1)));
line(outImg,
cv::Point(cvRound(pt1.x * draw_multiplier), cvRound(pt1.y * draw_multiplier)),
cv::Point(cvRound(dpt2.x * draw_multiplier), cvRound(dpt2.y * draw_multiplier)),
color, 1, cv::LINE_AA, draw_shift_bits);
}
void drawVerticalMatches(cv::InputArray img1, const std::vector<cv::KeyPoint> &keypoints1,
cv::InputArray img2, const std::vector<cv::KeyPoint> &keypoints2,
const std::vector<cv::DMatch> &matches1to2, cv::InputOutputArray outImg,
const cv::Scalar& matchColor=cv::Scalar::all(-1), const cv::Scalar& singlePointColor=cv::Scalar::all(-1),
const std::vector<char>& matchesMask=std::vector<char>(), int flags=cv::DrawMatchesFlags::DEFAULT)
{
if (!matchesMask.empty() && matchesMask.size() != matches1to2.size())
CV_Error(cv::Error::StsBadSize, "matchesMask must have the same size as matches1to2");
cv::Mat outImg1, outImg2;
_prepareImgAndDrawKeypoints(img1, keypoints1, img2, keypoints2,
outImg, outImg1, outImg2, singlePointColor, flags);
// draw matches
for (size_t m = 0; m < matches1to2.size(); m++)
{
if (matchesMask.empty() || matchesMask[m])
{
int i1 = matches1to2[m].queryIdx;
int i2 = matches1to2[m].trainIdx;
CV_Assert(i1 >= 0 && i1 < static_cast<int>(keypoints1.size()));
CV_Assert(i2 >= 0 && i2 < static_cast<int>(keypoints2.size()));
const cv::KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
_drawVerticalMatch(outImg, outImg1, outImg2, kp1, kp2, matchColor, flags);
}
}
}
void drawVerticalMatches(cv::InputArray img1, const std::vector<cv::KeyPoint> &keypoints1,
cv::InputArray img2, const std::vector<cv::KeyPoint> &keypoints2,
const std::vector<std::vector<cv::DMatch> > &matches1to2, cv::InputOutputArray outImg,
const cv::Scalar& matchColor=cv::Scalar::all(-1), const cv::Scalar& singlePointColor=cv::Scalar::all(-1),
const std::vector<std::vector<char> >& matchesMask=std::vector<std::vector<char> >(), int flags=cv::DrawMatchesFlags::DEFAULT)
{
if (!matchesMask.empty() && matchesMask.size() != matches1to2.size())
CV_Error(cv::Error::StsBadSize, "matchesMask must have the same size as matches1to2");
cv::Mat outImg1, outImg2;
_prepareImgAndDrawKeypoints(img1, keypoints1, img2, keypoints2,
outImg, outImg1, outImg2, singlePointColor, flags);
// draw matches
for (size_t i = 0; i < matches1to2.size(); i++)
{
for (size_t j = 0; j < matches1to2[i].size(); j++)
{
int i1 = matches1to2[i][j].queryIdx;
int i2 = matches1to2[i][j].trainIdx;
if (matchesMask.empty() || matchesMask[i][j])
{
const cv::KeyPoint &kp1 = keypoints1[i1], &kp2 = keypoints2[i2];
_drawVerticalMatch(outImg, outImg1, outImg2, kp1, kp2, matchColor, flags);
}
}
}
}
}
#endif
|
492008678a332fec2a2bc1df8d7ff612618719c5
|
[
"Markdown",
"CMake",
"C++"
] | 10
|
C++
|
moningkai/RoadPlane_StereoMatching
|
2917c8ce36d728486721ddfa428695dd36012036
|
42039953757ae75d0b4a55a83553abab6d9f95ce
|
refs/heads/master
|
<file_sep>from dataProcessing import *
from textTester import *
def main():
#Input data ->Mahdi
customerInterArrivalTime = [1,2,3,4]
ableServiceTime = [5,6,7,8]
bakerServiceTime = [10,11,12,13]
ableBakerPriority = 0 #If 0 => Able is first if 1 => baker is first if 2 => randomly chosen
selectCustomerOrTime = True #If true customer number is given if false time period is given
customerCount = 100
timeLength = 0
# Data processing -> MrHs
if(selectCustomerOrTime):
count = customerCount
else:
count = timeLength
lili = customerGenerator(customerInterArrivalTime, ableServiceTime, bakerServiceTime, ableBakerPriority, selectCustomerOrTime, count)
# printing output using django -> Mahdi
test(lili)
return 0
main()<file_sep>from caller import *
import random
def getInterArrivalTime(customerList):
return random.choice(customerList)
def getAbleOrBaker(ableAvailTime,bakerAvailTime,priority):
if(ableAvailTime == bakerAvailTime):
if(priority == 2):
select = random.choice([0,1])
return select
else:
return priority
else:
if(ableAvailTime < bakerAvailTime):
return 0
else:
return 1
def getServiceTime(ableOrBaker,ableList,bakerList):
if(ableOrBaker == 0):
return random.choice(ableList)
else:
return random.choice(bakerList)
def customerGenerator(customerTimeList,ableList,bakerList,priority,customerOrTime,count):
customerList = list()
if(customerOrTime):
for i in range(count):
if(len(customerList) == 0): # The fist caller
if(priority == 2):
priority = random.choice([0,1])
if(priority == 0):
servTime = random.choice(ableList)
customerList.append(Caller(0,0,0,0,0,servTime,0,servTime,0,0,0))
if(priority == 1):
servTime = random.choice(bakerList)
customerList.append(Caller(0,0,0,0,1,servTime,0,0,servTime,0,0))
else:
interArrVlTime = getInterArrivalTime(customerTimeList)
timeInSystem = customerList[len(customerList)-1].arrivalTime
if(priority == 2):
priority = random.choice([0,1])
ableBaker = getAbleOrBaker(customerList[len(customerList)-1].ableServiceCompletedTime, customerList[len(customerList)-1].bakerServiceCompletedTime, priority)
servTime = getServiceTime(ableBaker, ableList, bakerList)
if(ableBaker == 0):
arrivalTime = customerList[len(customerList)-1].arrivalTime + interArrVlTime
whenAbleAvailable = customerList[len(customerList)-1].ableServiceCompletedTime
whenBakerAvailableTime = customerList[len(customerList)-1].bakerServiceCompletedTime
if(arrivalTime > whenAbleAvailable):
whenServiceBegins = arrivalTime
else:
whenServiceBegins = whenAbleAvailable
if(arrivalTime < whenServiceBegins):
delay = whenServiceBegins - arrivalTime
else:
delay = 0
customerList.append(Caller(interArrVlTime,arrivalTime,whenAbleAvailable,whenBakerAvailableTime,0,servTime,whenServiceBegins,whenAbleAvailable + servTime,whenBakerAvailableTime,delay,timeInSystem))
if(ableBaker == 1):
arrivalTime = customerList[len(customerList)-1].arrivalTime + interArrVlTime
whenAbleAvailable = customerList[len(customerList)-1].ableServiceCompletedTime
whenBakerAvailableTime = customerList[len(customerList)-1].bakerServiceCompletedTime
if(arrivalTime > whenBakerAvailableTime):
whenServiceBegins = arrivalTime
else:
whenServiceBegins = whenBakerAvailableTime
if(arrivalTime < whenServiceBegins):
delay = whenServiceBegins - arrivalTime
else:
delay = 0
customerList.append(Caller(interArrVlTime,arrivalTime,whenAbleAvailable,whenBakerAvailableTime,1,servTime,whenServiceBegins,whenAbleAvailable,whenBakerAvailableTime + servTime,delay,timeInSystem))
else:
pass
return customerList <file_sep>from dataProcessing import *
from textTester import *
from django.shortcuts import render
from django.http import HttpResponse
from django.template.loader import get_template
from django.template import Context
import datetime
def fun(s):
if s == 'n2':
return [1,2,4,8]
elif s == 'n3':
return [1,3,9,27]
elif s == 'kh1':
return [1,2,3,4]
elif s == 'kh2':
return [2,4,6,8]
elif s == 'kh3':
return [7,8,9,10]
elif s == 'kh4':
return [5,7,11,13]
return [1 , 2 , 3 , 4]
def startSimulation(request):
if request.method == "GET":
customerInterArrivalTime = fun(request.GET['customerInterArrivalTime'])
ableServiceTime = fun(request.GET['ableServiceTime'])
bakerServiceTime = fun(request.GET['bakerServiceTime'])
if request.GET['ableBakerPriority'] == 'able' :
ableBakerPriority = 0
elif request.GET['ableBakerPriority'] == 'baker' :
ableBakerPriority = 1
elif request.GET['ableBakerPriority'] == 'rand':
ableBakerPriority = 2
if request.GET['selectCustomerOrTime'] == 'customerCount':
selectCustomerOrTime = True
customerCount = int(request.GET['value'])
else:
selectCustomerOrTime = False
timeLength = int(request.GET['value'])
# Data processing -> MrHs
if(selectCustomerOrTime):
count = customerCount
else:
count = timeLength
lili = customerGenerator(customerInterArrivalTime, ableServiceTime, bakerServiceTime, ableBakerPriority, selectCustomerOrTime, count)
# printing output using django -> Mahdi
array2dOFRow = test(lili)
delayFrequencyDictionary = {}
for i in lili:
if(delayFrequencyDictionary.has_key(i.callerDelay)):
delayFrequencyDictionary[i.callerDelay] += 1
else:
delayFrequencyDictionary[i.callerDelay] = 1
keyList = delayFrequencyDictionary.keys()
keyList.sort()
listx = []
listy = []
listx2 = []
listy2 = []
for i in keyList:
listx.append(str(i))
listx2.append(str(i))
listy.append(str(delayFrequencyDictionary[i]))
listy2.append(str(delayFrequencyDictionary[i]*100/len(lili)))
return render(request, 'sim.html', {'allData': array2dOFRow ,
'listX' : listx ,
'listY': listy ,
'listX2' : listx2 ,
'listY2': listy2
})
def home(request):
now = datetime.datetime.now()
t = get_template('home.html')
html = t.render(Context({'hhh': "hhh"}))
return HttpResponse(html)
<file_sep>from copy import copy, deepcopy
def test(lili):
allData = []
for i in range(len(lili)):
k = lili[i]
s = [str(i),str(k.interArrivalTime),str(k.arrivalTime),str(k.whenAbleAvailable),str(k.whenBakerAvailable),str(k.serverChosen),str(k.serviceTime),str(k.timeServiceBegins),str(k.ableServiceCompletedTime),str(k.bakerServiceCompletedTime),str(k.callerDelay),str(k.timeInsystem)];
allData.append(deepcopy(s))
return allData
<file_sep># This class holds the information of a CallerMacro
class Caller():
interArrivalTime = 0
arrivalTime = 0
whenAbleAvailable = 0
whenBakerAvailable = 0
serverChosen = 0 # 0 is able and 1 is baker
serviceTime = 0
timeServiceBegins = 0
ableServiceCompletedTime = 0
bakerServiceCompletedTime = 0
callerDelay = 0
timeInsystem = 0
def __init__(self,i1,i2,i3,i4,i5,i6,i7,i8,i9,i10,i11):
self.interArrivalTime = i1
self.arrivalTime = i2
self.whenAbleAvailable = i3
self.whenBakerAvailable = i4
self.serverChosen = i5
self.serviceTime = i6
self.timeServiceBegins = i7
self.ableServiceCompletedTime = i8
self.bakerServiceCompletedTime = i9
self.callerDelay = i10
self.timeInsystem = i11
<file_sep># ableBakerProblem
A simulation of able baker problem using python2.7 and django
------------------------------------------------------------
- مهدی این پی دی اف رو که گذاشتم خیلی مفیده صفحات ۲۰ تا ۲۵ مرتبط با مسیله است حتما مطالعه کن که کلیات مسیله رو بدونی
|
8c2432851b2c9e44c4d74edcfff974244ae237c6
|
[
"Markdown",
"Python"
] | 6
|
Python
|
mrhsce/ableBakerProblem
|
f633f1406388e1908e013fe6cc8b3cb4f23fdc63
|
5d583a5c91f29f5c981fe95fe1b0a253b2992cee
|
refs/heads/main
|
<repo_name>brunobach/instagram-bot<file_sep>/index.js
const puppeteer = require('puppeteer');
var comments = 0;
mainComment = async () =>{
const browser = await puppeteer.launch({headless: false});
const page = await browser.newPage();
// Login flow
await page.goto('https://www.instagram.com/accounts/login/?source=auth_switcher');
await page.waitForSelector('input[name="username"]');
await page.type('input[name="username"]', 'usuario');
await page.type('input[name="password"]', '<PASSWORD>');
await page.click('button[type="submit"]');
// Waiting for page to refresh
await page.waitForNavigation();
// Navigate to post and submitting the comment
await page.goto('https://www.instagram.com/p/CM_InIypqtY/');
setInterval(async () => {
comment()
},36000)
const comment = async () => {
comments++
console.log(`_taineforneck comentou: ${comments} vezes.`)
await page.waitForSelector('textarea');
await page.type('textarea', randomize());
await page.click('button[type="submit"]');
}
}
function randomize() {
const randomimicos = [
'🔥 Sarah',
'Sarah 🔥',
'🔥 Sarah 🔥',
'A Sarah Sai',
'🐍 Sarah',
'Sarah 🐍🐍🐍',
'Vem passar chapinha aqui fora SARAH 🐍',
'SARAH 💥',
'Sarah',
'Sarah! 💥🔥🐍'
]
const palavras = Math.floor(Math.random() * 10);
return randomimicos[palavras]
}
mainComment()
|
305daceba4aafc03f0399e85642e7560f991c707
|
[
"JavaScript"
] | 1
|
JavaScript
|
brunobach/instagram-bot
|
d7b640b7335d606aa3ea0696dd81bcaa056615f2
|
dc7a128d579c8e665e1667dac373202b566e07aa
|
refs/heads/main
|
<file_sep># Number-Guessing-Game
This is a number guessing game using Python.
I have used pyttsx3 library for speech and random library to generate random numbers.
<file_sep># Number Guessing Game
# importing module
import random
import pyttsx3 as pyt
engine = pyt.init()
newVoiceRate = 125
eng_voice = 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Speech\Voices\Tokens\TTS_MS_EN-US_DAVID_11.0'
engine.setProperty('voice', eng_voice)
engine.setProperty('rate', newVoiceRate)
pyt.speak('Welcome to Number Guessing Game')
engine.runAndWait()
pyt.speak('Enter Number of Chances')
chance = int(input("Total Chances --> "))
try_again = 'yes'
while try_again == 'yes':
rand_num = random.randint(1, 10)
pyt.speak("Enter Number between 1 to 10")
counting = 0
while counting < chance:
if counting == chance-1:
pyt.speak("It's your last chance")
else:
pyt.speak(f"It's Your Chance {counting + 1}")
num = int(input('-->'))
if counting == chance-1 and num != rand_num:
pyt.speak('Sorry! your chance is finished ... and You loss the game')
print('You Loss')
pyt.speak(f"Correct number is : {rand_num}")
break
elif num == rand_num:
pyt.speak("Nice trial You won the game")
print('You Won')
break
elif num > rand_num:
pyt.speak("Give some smaller number")
elif num < rand_num:
pyt.speak("Give some greater number")
counting += 1
pyt.speak("Do you want to Play again?")
try_again = input("Want to Play again?? (yes or no) : ")
if try_again == 'yes':
pyt.speak('Welcome again in Number Guessing Game')
else:
pyt.speak('Thank You for Playing Number Guessing Game ... Come Soon')
|
0b35c9b5dcfc33e0126d51525a7fa9db3ead4228
|
[
"Markdown",
"Python"
] | 2
|
Markdown
|
mishu-mnp/Number-Guessing-Game
|
f871616465783daeb383d23dcafb523eee5e16f1
|
ff76534eed7b44fa6495fc4339b8f06456b94c7e
|
refs/heads/master
|
<file_sep><?php
namespace Sayeed\CustomMigrate\Commands;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class CustomMigrateCommand extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'migrate:custom {--f|file=} {--r|refresh} {--d|directory=}';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Custom migrate using file name';
/**
* Create a new command instance.
*
* @return void
*/
public function __construct()
{
parent::__construct();
}
/**
* Execute the console command.
*
* @return mixed
*/
public $migrator;
public $resolver;
public $files;
public function handle()
{
$directory = $this->option('directory');
$given_file = $this->option('file');
$refresh = $this->option('refresh');
$mainPath = database_path('migrations');
$directories = glob($mainPath.'/' . $directory . '*' , GLOB_ONLYDIR);
$paths = array_merge([$mainPath], $directories);
if ($given_file) {
$files[0] = $mainPath.'/'.$given_file.'.php';
} else {
$files = glob($paths[0] . '/*.php');
}
if(Schema::hasTable('migrations')) {
$batch_no = DB::table('migrations')->max('batch');
$this->info('MIGRATION STARTED');
foreach ($files as $key => $file) {
$basename = basename($file);
$file_info = pathinfo($basename);
$file_name = $file_info['filename'];
$file_content = explode("Schema::create(", file_get_contents($file));
$table_create_migrate = true;
if (count($file_content) > 1) {
$file_content = explode("'", $file_content[1]);
if (count($file_content) > 1) {
$table_name = trim($file_content[0], '"');
$table_name = trim($table_name, "'");
} else {
$this->error('-> '.$file_name.' Migration file invalid');
continue;
}
} else {
$table_create_migrate = false;
// non table-create migration
//$this->error('-> '.$file_name.' Migration file invalid');
}
if ($refresh) {
DB::table('migrations')->where('migration', $file_name)->delete();
if ($table_create_migrate) {
Schema::dropIfExists($table_name);
if (Schema::hasTable($table_name)) {
Schema::drop($table_name);
}
}
}
require_once($mainPath.'/'.$basename);
$all_classes = get_declared_classes();
$lastTableClassName = end($all_classes);
$already_migrate = DB::table('migrations')->where('migration', $file_name)->first();
if($already_migrate) {
if ($table_create_migrate) {
$this->line('-> '.$file_name.' ALREADY MIGRATED');
if (!Schema::hasTable($table_name)) {
$tableClass = new $lastTableClassName();
$tableClass->up();
$this->info('-> '.$file_name.' SUCCESSFULLY MIGRATED');
}
} else {
$tableClass = new $lastTableClassName();
$tableClass->up();
$this->info('-> '.$file_name.' SUCCESSFULLY RE-MIGRATED');
}
} else {
try {
DB::table('migrations')->insert(['migration' => $file_name, 'batch' => ($batch_no+1)]);
if ($table_create_migrate) {
if (Schema::hasTable($table_name)) {
$this->info('-> ' . $file_name . ' ADDED IN MIGRATION TABLE');
}
}
$tableClass = new $lastTableClassName();
$tableClass->up();
$this->info('-> '.$file_name.' SUCCESSFULLY MIGRATED');
} catch(\Exception $exception) {
//$this->error($exception);
$this->error('-> SOME PROBLEM OCCURS, PLEASE INFORM TO DEVELOPER <-');
}
}
}
$this->info('MIGRATION COMPLETED');
} else {
$this->error('-> MIGRATIONS TABLE NOT FOUND. PLEASE RUN FIRST "php artisan migrate" <-');
}
}
}
<file_sep># Laravel Custom DB Migrate
Laravel Custom DB Migrate allows fine grain control of migrations inside your Laravel or Lumen application. You can choose which migration files - or groups of files inside the directory - get migrated to the database.
- [Laravel Custom DB Migrate](#laravel-custom-db-migrate)
- [Installation](#installation)
- [Laravel 5.5 and above](#laravel-55-and-above)
- [Laravel 5.4 and older](#laravel-54-and-older)
- [Lumen](#lumen)
- [Usage](#usage)
- [Migrate specific file](#migrate-specific-file)
- [Migrate specific directory](#migrate-specific-directory)
- [Refreshing migrations](#refreshing-migrations)
- [Credits](#credits)
## Installation
You can install the package via composer:
```shell
composer require sayeed/custom-migrate
```
### Laravel 5.5 and above
The package will automatically register itself, so you can start using it immediately.
### Laravel 5.4 and older
In Laravel version 5.4 and older, you have to add the service provider in `config/app.php` file manually:
```php
'providers' => [
// ...
Sayeed\CustomMigrate\CustomMigrateServiceProvider::class,
];
```
### Lumen
After installing the package, you will have to register it in `bootstrap/app.php` file manually:
```php
// Register Service Providers
// ...
$app->register(Sayeed\CustomMigrate\CustomMigrateServiceProvider::class);
];
```
## Usage
After installing the package, you will now see a new ```php artisan migrate:custom``` command.
### Migrate specific file
You can migrate a specific file inside your `database/migrations` folder using:
```php artisan migrate:custom -f 2018_10_14_054732_create_tests_table```
Alternatively, you can use the longform version:
```php artisan migrate:custom --file 2018_10_14_054732_create_tests_table```
### Migrate specific directory
You can migrate a specific directory inside your `database/migrations` folder using:
```php artisan migrate:custom -d migrations-subfolder```
Alternatively, you can use the longform version:
```php artisan migrate:custom --directory migrations-subfolder```
### Refreshing migrations
You can refresh migrations inside your project using:
```php artisan migrate:custom -r```
Alternatively, you can use the longform version:
```php artisan migrate:custom --refresh```
## Credits
- [<NAME>](https://github.com/jbhasan)
- [<NAME>](https://github.com/morpheus7CS)
For any questions, you can reach out to the author of this package, <NAME>.
Thank you for using it.
|
943b91d734d21a9dfe87290e4f8b371cb31cf3e3
|
[
"Markdown",
"PHP"
] | 2
|
PHP
|
jbhasan/custom-migration
|
edf057c360e6bb2a6518e88723a1015ff4d1468e
|
0b6932947571e741cc15c462b51182e79f6c2c75
|
refs/heads/master
|
<file_sep>app.factory('requestService', ['$uibModal', '$filter', '$q', 'config', function ($uibModal, $filter, $q, config) {
return {
request: {
'regular': null,
'fixed': null,
'pager': {
'currentPage': 1,
'itemsPerPage': 15,
'maxSize': 5
}
},
filterRequest: function (type, id) {
return $filter('filter')(this.request[type], {'_id': config.local ? id : {'$oid': id}});
},
getRequest: function (type, query) {
return (this.request[type]) ? $q.resolve({data: this.request[type]}) : config.getData(config[type], query);
},
addRequest: function (type, data) {
return config.postData(config[type], data);
},
updateRequest: function (type, id, data) {
var filter = config.local ? '{"_id":"' + id + '"}' : '{"_id":{"$oid":"' + id.$oid + '"}}';
return config.updateData(config[type], filter, {$set: data});
},
deleteRequest: function (type, id) {
return config.deleteData(config[type], id);
},
newRequest: function (type, template, controller) {
var modalInstance = $uibModal.open({
templateUrl: template,
controller: controller,
size: 'lg',
resolve: {
record: function () {
return {
'type': type,
'action': 'new'
};
}
}
});
},
editRequest: function (type, template, controller, id) {
var self = this;
var modalInstance = $uibModal.open({
templateUrl: template,
controller: controller,
size: 'lg',
resolve: {
record: function () {
return {
'type': type,
'action': 'edit',
'data': self.filterRequest(type, id)
}
}
}
});
},
viewRequest: function (type, template, controller, id) {
var self = this;
var modalInstance = $uibModal.open({
templateUrl: template,
controller: controller,
size: 'lg',
resolve: {
record: function () {
return {
'type': type,
'action': 'view',
'data': self.filterRequest(type, id)
}
}
}
});
}
};
}]);
<file_sep>app.controller('fixedPaymentController', ['$scope', '$q', '$filter', 'config', 'vehicleService', 'partyService', 'requestService', 'packageService', 'pdfService',
function ($scope, $q, $filter, config, vehicleService, partyService, requestService, packageService, pdfService) {
var initialVehicleData;
$scope.data = null;
$scope.localEnv = config.local;
$scope.loading = false;
$scope.currMonth = new Date().getMonth();
$scope.monthList = config.months;
$scope.yearList = config.years();
$scope.filter = {};
$scope.filter.year = new Date().getFullYear().toString();
$scope.filter.month = $scope.monthList[$scope.currMonth];
$q.all([vehicleService.getVehicle('own'), partyService.getParty('client')]).then(function (res) {
$scope.vehicleList = $filter('filter')(res[0].data[0].data, {'selectFixed': 'Yes'});
initialVehicleData = angular.copy($scope.vehicleList);
if (!vehicleService.vehicle.own) {
vehicleService.vehicle.own = res[0].data;
}
$scope.partyList = res[1].data[0].data;
if (!partyService.party.client) {
partyService.party.client = res[1].data;
}
});
$scope.$watch('filter.party', function (newValue, oldValue) {
$scope.filter.vehicle = "";
if (!newValue) {
return;
}
$scope.vehicleList = $filter('filter')(initialVehicleData, {'fixed': {'companyName': newValue}});
});
$scope.calculatePayment = function () {
$scope.data = [];
$scope.loading = true;
if (requestService.request.fixed) {
$scope.data = $filter('filter')(requestService.request.fixed, {
"partyName": $scope.filter.party,
"vehicle": $scope.filter.vehicle,
"month": $scope.filter.month,
"year": $scope.filter.year
});
$scope.loading = false;
getPackageData();
} else {
requestService.getRequest("fixed", 'q={"partyName":"' + $scope.filter.party + '","vehicle":"' + $scope.filter.vehicle + '","month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}&s={"date":-1}').then(function (res) {
$scope.loading = false;
$scope.data = res.data;
getPackageData();
});
}
};
var getPackageData = function () {
var packageCode = $filter('filter')(initialVehicleData, {
'vehicleName': $scope.filter.vehicle.split(',')[0],
'vehicleNo': $scope.filter.vehicle.split(',')[1]
})[0].fixed.package;
packageService.getPackage('fix').then(function (res) {
var pkg = ($filter('filter')(res.data[0].data, {'packageCode': packageCode})[0]);
calculateTotalAmt(pkg);
});
},
calculateTotalAmt = function (pkg) {
$scope.allData = {
'basicAmt': pkg.basicAmt,
'basicKM': pkg.kmRate.minKm,
'extraKmRate': pkg.kmRate.extraKm,
'extraHrRate': pkg.hrRate.extraHr,
'totalKm': 0,
'extraHr': 0,
'DAAmt': 0,
'DAAmtCount': 0,
'nightHaltAmt': 0,
'nightHaltAmtCount': 0,
'overTimeAmt': 0,
'tollAmt': 0,
'parkingAmt': 0,
'monthTotal': 0
};
for (var i = 0; i < $scope.data.length; i++) {
$scope.allData.totalKm += $scope.data[i].totalKm;
$scope.allData.extraHr += $scope.data[i].extraHr;
$scope.allData.DAAmt += $scope.data[i].diverAllowanceAmt;
if ($scope.data[i].diverAllowanceAmt > 0) {
$scope.allData.DAAmtCount++;
}
$scope.allData.nightHaltAmt += $scope.data[i].nightHaltAmt;
if ($scope.data[i].nightHaltAmt > 0) {
$scope.allData.nightHaltAmtCount++;
}
$scope.allData.overTimeAmt += $scope.data[i].driverOverTime;
$scope.allData.tollAmt += $scope.data[i].tollAmt;
$scope.allData.parkingAmt += $scope.data[i].parkingAmt;
}
$scope.allData.monthTotal = ($scope.allData.totalKm <= $scope.allData.basicKM ? $scope.allData.basicAmt : $scope.allData.basicAmt + ($scope.allData.totalKm - $scope.allData.basicKM) * pkg.kmRate.extraKm) + ($scope.allData.extraHr * pkg.hrRate.extraHr) + $scope.allData.DAAmt + $scope.allData.nightHaltAmt + $scope.allData.tollAmt + $scope.allData.parkingAmt;
},
processForFixedpdf = function (data) {
var rowData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [i + 1, $filter('date')(data[i].date, 'dd-MMM-yyyy'), data[i].requestType == 'local' ? 'Local' : 'Out Station', data[i].totalKm + ' KM', data[i].extraHr + ' Hr', $filter('number')(data[i].diverAllowanceAmt, '2') + '/-', $filter('number')(data[i].nightHaltAmt, '2') + '/-', $filter('number')(data[i].tollAmt, '2') + '/-', $filter('number')(data[i].parkingAmt, '2') + '/-'];
rowData.push(rowItem);
}
return rowData;
};
$scope.exportData = function () {
var columns = ['Sr. No', 'Date', 'Request Type', 'Trip KM', 'Extra Hours', 'Driver Allowance', 'Night Halt', 'Toll Amount', 'Parking Amount'];
pdfService.buildPDF(columns, processForFixedpdf($scope.data), 'Fixed Payments', 'Fixed_Payments', 0, 'Party Name : ' + $scope.filter.party + ', Vehicle Name : ' + $scope.filter.vehicle + ', Month : ' + $scope.filter.month + ', Year : ' + $scope.filter.year + ' :: Total Amount : ' + $filter('number')($scope.allData.monthTotal, '2') + '/-');
};
}]);<file_sep>app.controller('driverController',
['$scope', '$state', '$rootScope', 'driverService', 'messageService', 'config', '$uibModal',
function ($scope, $state, $rootScope, driverService, messageService, config, $uibModal) {
$scope.data = [];
$scope.loading = true;
$scope.localEnv = config.local;
var init = function () {
driverService.getDriver().then(success, function () {
$state.go('login');
});
},
driverModal = function (type, data) {
$uibModal.open({
templateUrl: 'driver/driver-modal.html',
controller: 'driverModalController',
size: 'lg',
resolve: {
record: function () {
return {
'action': type,
'data': data
};
}
}
});
},
success = function (res) {
$scope.data = res.data;
if (!driverService.driver) {
driverService.driver = res.data;
}
$scope.loading = false;
};
$rootScope.$on('driver', function () {
init();
});
init();
$scope.addDriver = function () {
driverModal('new', {});
};
$scope.viewRequest = function (id) {
driverModal('view', driverService.filterRecord(id)[0]);
};
$scope.editRequest = function (id) {
driverModal('edit', driverService.filterRecord(id)[0]);
};
$scope.deleteRequest = function (id) {
messageService.deleteConfirm().result.then(function (data) {
if (data) {
$scope.deleteRecord(id);
}
});
};
$scope.deleteRecord = function (id) {
var driverName = driverService.filterRecord(id)[0].name;
driverService.deleteDriver(id).then(function (res) {
driverService.driver = null;
init();
messageService.showMessage({
'type': 'success',
'title': 'Driver',
'text': 'Driver ' + driverName + ' Deleted successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Driver',
'text': 'Driver ' + driverName + ' can not be deleted at this time. Please try again.'
});
});
}
}]);<file_sep>app.controller('addVehicleExpenseController',
['$scope', '$rootScope', '$filter', '$uibModalInstance', 'expenseService', 'vehicleService', 'messageService', 'record',
function ($scope, $rootScope, $filter, $uibModalInstance, expenseService, vehicleService, messageService, record) {
$scope.expense = angular.copy(record.data);
$scope.action = record.action;
$scope.expense.date = $scope.action === 'new' ? new Date() : new Date($scope.expense.date);
if ($scope.action === 'new') {
$scope.expense.paymentMode = "cash";
}
if ($scope.action === 'edit') {
var recordId = $scope.expense._id;
}
;
$scope.loading = false;
$scope.hideView = ($scope.action === 'view');
$scope.calendar = {};
$scope.openCalendar = function () {
$scope.calendar.open = true;
}
$scope.closeModal = function () {
$uibModalInstance.close();
};
vehicleService.getVehicle('own').then(function (res) {
$scope.vehicleList = res.data[0].data;
if (!vehicleService.vehicle.own) {
vehicleService.vehicle.own = res.data;
}
});
$scope.submitRequest = function () {
$scope.expense.month = $filter('date')($scope.expense.date, "MMM");
$scope.expense.year = $filter('date')($scope.expense.date, "yyyy");
$scope.loading = true;
if ($scope.action === 'new') {
expenseService.addExpense('vehicleExpense', $scope.expense).then(function () {
$scope.closeModal();
expenseService.expense.vehicleExpense = null;
$rootScope.$emit('vehicleExpense');
messageService.showMessage({
'type': 'success',
'title': 'Vehicle Expense',
'text': 'New vehicle expense added successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Vehicle Expense',
'text': 'Vehicle expense not added successfully. Please try again.'
});
});
} else {
delete $scope.expense._id;
expenseService.updateExpense('vehicleExpense', recordId, $scope.expense).then(function () {
$scope.closeModal();
expenseService.expense.vehicleExpense = null;
$rootScope.$emit('vehicleExpense');
messageService.showMessage({
'type': 'success',
'title': 'Vehicle Expense',
'text': 'Vehicle expense updated successfully.'
});
}, function (err) {
messageService.showMessage({
'type': 'error',
'title': 'Vehicle Expense',
'text': 'Vehicle expense not updated successfully. Please try again.'
});
});
}
};
}]);<file_sep>app.controller('vehicleSummaryController', ['$scope', '$state', '$filter', 'config', 'vehicleService', 'requestService', 'expenseService',
function ($scope, $state, $filter, config, vehicleService, requestService, expenseService) {
$scope.yearList = config.years();
if (sessionStorage.getItem('year')) {
$scope.year = sessionStorage.getItem('year');
} else {
$scope.year = new Date().getFullYear().toString();
}
var monthSet = config.months,
chartData = {local: [], out: [], income: [], expense: []}, incomeChart, expenseChart, localChart, outChart,
init = function () {
$scope.loading = true;
vehicleService.getVehicle('own').then(function (res) {
$scope.vehicleList = res.data[0].data;
if (sessionStorage.getItem('veh')) {
$scope.vehicleSelect = sessionStorage.getItem('veh');
} else {
$scope.vehicleSelect = $scope.vehicleList[0].vehicleName + ',' + $scope.vehicleList[0].vehicleNo;
}
loadSummary();
if (!vehicleService.vehicle.own) {
vehicleService.vehicle.own = res.data;
}
});
},
loadSummary = function () {
requestService.request.regular = null;
requestService.getRequest('regular', 'q={"year":"' + $scope.year + '", "vehicleSelect":"own","vehicle.vehicle":"' + $scope.vehicleSelect + '"}&f={"requestType":1,"profit":1,"month":1}').then(function (res) {
for (var i = 0; i < monthSet.length; i++) {
chartData.local.push($filter('filter')(res.data, {'month': monthSet[i], 'requestType': 'local'}).length);
chartData.out.push($filter('filter')(res.data, {'month': monthSet[i], 'requestType': 'out'}).length);
calculateIncome($filter('filter')(res.data, {'month': monthSet[i]}));
}
getExpense();
});
},
calculateIncome = function (m) {
var totalProfit = 0;
for (var k = 0; k < m.length; k++) {
totalProfit = totalProfit + m[k].profit;
}
chartData.income.push(totalProfit);
},
getExpense = function () {
expenseService.getExpense('vehicleExpense', 'q={"year":"' + $scope.year + '", "vehicle":"' + $scope.vehicleSelect + '"}&f={"expenseAmt":1,"month":1}').then(function (res) {
for (var i = 0; i < monthSet.length; i++) {
calculateExpense($filter('filter')(res.data, {'month': monthSet[i]}));
}
updateSummary();
});
},
calculateExpense = function (e) {
var totalExpense = 0;
for (var k = 0; k < e.length; k++) {
totalExpense = totalExpense + e[k].expenseAmt;
}
chartData.expense.push(totalExpense);
},
updateSummary = function () {
$scope.loading = false;
angular.forEach(chartData, function (item, key) {
new Chart(document.getElementById(key), {
type: 'bar',
data: {
labels: config.months,
datasets: [{
label: key.toUpperCase() + ' ',
backgroundColor: "rgba(54,162,235,0.2)",
borderColor: "rgba(54,162,235,1)",
borderWidth: 0.5,
hoverBackgroundColor: "rgba(54,162,235,0.4)",
hoverBorderColor: "rgba(54,162,235,1)",
data: item
}]
}
});
});
sessionStorage.removeItem('veh');
sessionStorage.removeItem('year');
};
init();
$scope.redrawGraph = function () {
sessionStorage.setItem('veh', $scope.vehicleSelect);
sessionStorage.setItem('year', $scope.year);
$state.reload();
}
}]);<file_sep>app.factory('vehicleService', ['$uibModal', '$filter', '$q', 'config', function ($uibModal, $filter, $q, config) {
return {
vehicle: {
'own': null,
'other': null
},
filterRecord: function (type, id) {
return $filter('filter')(this.vehicle[type][0].data, {'_id': id});
},
getVehicle: function (type) {
return (this.vehicle[type]) ? $q.resolve({data: this.vehicle[type]}) : config.getData(config.vehicle, 'q={"name":"' + type + '"}');
},
addVehicle: function (filter, item) {
item._id = config.guid();
return config.updateData(config.vehicle, filter, {$push: {data: item}});
},
updateVehicle: function (filter, item) {
return config.updateData(config.vehicle, filter, {$set: {"data.$": item}});
},
deleteVehicle: function (filter, id) {
var item = {'_id': id};
return config.updateData(config.vehicle, filter, {$pull: {data: item}});
}
}
}]);<file_sep>app.controller('bookingController',
['$scope', '$state', '$rootScope', 'bookingService', 'messageService', 'config', '$uibModal',
function ($scope, $state, $rootScope, bookingService, messageService, config, $uibModal) {
$scope.data = [];
$scope.loading = true;
$scope.localEnv = config.local;
var init = function () {
bookingService.getBooking().then(success, function () {
$state.go('login');
});
},
bookingModal = function (type, data) {
$uibModal.open({
templateUrl: 'booking/booking-modal.html',
controller: 'bookingModalController',
size: 'lg',
resolve: {
record: function () {
return {
'action': type,
'data': data
};
}
}
});
},
success = function (res) {
$scope.data = res.data;
if (!bookingService.booking) {
bookingService.booking = res.data;
}
$scope.loading = false;
};
$rootScope.$on('booking', function () {
init();
});
init();
$scope.addBooking = function () {
bookingModal('new', {
AC: 'Yes'
});
};
$scope.viewRequest = function (id) {
bookingModal('view', bookingService.filterRecord(id)[0]);
};
$scope.editRequest = function (id) {
bookingModal('edit', bookingService.filterRecord(id)[0]);
};
$scope.deleteRequest = function (id) {
messageService.deleteConfirm().result.then(function (data) {
if (data) {
$scope.deleteRecord(id);
}
});
};
$scope.deleteRecord = function (id) {
var bookingName = bookingService.filterRecord(id)[0].name;
bookingService.deleteBooking(id).then(function (res) {
bookingService.booking = null;
init();
messageService.showMessage({
'type': 'success',
'title': 'Advanced Booking',
'text': 'Booking ' + bookingName + ' Deleted successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Advanced Booking',
'text': 'Booking ' + bookingName + ' can not be deleted at this time. Please try again.'
});
});
}
}]);<file_sep>(function () {
describe("Sample Test", function () {
it('Addition of 2 number',function(){
expect(2+3).equals(5);
});
});
}());
<file_sep>app.service('messageService',['$uibModal',function($uibModal){
this.showMessage=function(context){
$uibModal.open({
templateUrl: 'common/modal/message.html',
controller:'messageController',
size:'md',
resolve:{
message:function(){
return context
}
}
});
};
this.deleteConfirm = function (context) {
return $uibModal.open({
templateUrl: 'common/modal/deleteConfirmation.html',
controller:'deleteConfirmationController',
size:'sm',
resolve:{
message: function(){
return context
}
}
});
}
}]);<file_sep>app.controller('driverPaymentController',
['$scope', '$q', '$filter', 'config', 'driverService', 'requestService', 'expenseService', 'pdfService',
function ($scope, $q, $filter, config, driverService, requestService, expenseService, pdfService) {
$scope.data = [];
$scope.localEnv = config.local;
$scope.loading = true;
$scope.currMonth = new Date().getMonth();
$scope.monthList = config.months;
$scope.yearList = config.years();
$scope.filter = {};
$scope.filter.year = new Date().getFullYear().toString();
$scope.filter.month = $scope.monthList[$scope.currMonth];
var getLocalRequestCount = function (driver) {
return $filter('filter')($scope.regularData, {
'vehicle': {'driver': driver},
'requestType': 'local'
}).length + $filter('filter')($scope.fixedData, {'driver': driver, 'requestType': 'local'}).length;
},
getOutRequestCount = function (driver) {
return $filter('filter')($scope.regularData, {
'vehicle': {'driver': driver},
'requestType': 'out'
}).length + $filter('filter')($scope.fixedData, {'driver': driver, 'requestType': 'out'}).length;
},
getAllowance = function (driver) {
var allowanceList = $filter('filter')($scope.regularData, {'vehicle': {'driver': driver}});
var allowanceTotal = 0;
for (var i = 0; i < allowanceList.length; i++) {
allowanceTotal = allowanceTotal + allowanceList[i].driverAllowance + allowanceList[i].driverOverTime;
}
return allowanceTotal;
},
getFixReqAmt = function (driver) {
var fixedDataList = $filter('filter')($scope.fixedData, {'driver': driver});
var fixedTotal = 0;
for (var i = 0; i < fixedDataList.length; i++) {
fixedTotal = fixedTotal + fixedDataList[i].diverAllowanceAmt + fixedDataList[i].driverOverTime + fixedDataList[i].nightHaltAmt;
}
return fixedTotal;
},
getAdvanceAmt = function (driver) {
var advancedList = $filter('filter')($scope.expenseData, {'driver': driver});
var advancedTotal = 0;
for (var i = 0; i < advancedList.length; i++) {
advancedTotal = advancedTotal + advancedList[i].expenseAmt;
}
return advancedTotal;
},
getTotalSalary = function (driverDataItem) {
return (driverDataItem.salary + driverDataItem.allowance + driverDataItem.fixrequestAmt) - driverDataItem.advanceAmt;
},
getRegularData = function () {
var def = $q.defer();
if (requestService.request.regular) {
var regData = $filter('filter')(requestService.request.regular, {
'vehicleSelect': 'own',
"month": $scope.filter.month,
"year": $scope.filter.year
});
def.resolve(regData)
} else {
requestService.getRequest("regular", 'q={"vehicleSelect":"own","month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
def.resolve(res.data);
});
}
return def.promise;
},
getFixedData = function () {
var def = $q.defer();
if (requestService.request.fixed) {
var fixData = requestService.request.fixed.filter(function (item) {
return ((item.regularVehicle == "own" && item.vehicleSelect == "daily") || (item.regularVehicle == "own" && item.vehicleSelect == "own") || (item.regularVehicle == "indirect" && item.vehicleSelect == "own")) && item.month == $scope.filter.month && item.year == $scope.filter.year;
});
def.resolve(fixData)
} else {
requestService.getRequest("fixed", 'q={"$or":[{"regularVehicle":"own","vehicleSelect":"daily"},{"regularVehicle":"own","vehicleSelect":"own"},{"regularVehicle":"indirect","vehicleSelect":"own"}],"month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
def.resolve(res.data);
});
}
return def.promise;
},
getExpenseData = function () {
var def = $q.defer();
if (expenseService.expense.driverExpense) {
var expData = $filter('filter')(expenseService.expense.driverExpense, {
"month": $scope.filter.month,
"year": $scope.filter.year
});
def.resolve(expData);
} else {
expenseService.getExpense('driverExpense', 'q={"month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
def.resolve(res.data);
});
}
return def.promise;
},
processForpdf = function (data) {
var rowData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [i + 1, data[i].name, $filter('number')(data[i].salary, '2') + '/-', data[i].localRequest, data[i].outRequest, $filter('number')((data[i].allowance + data[i].fixrequestAmt), '2') + '/-', $filter('number')(data[i].advanceAmt, '2') + '/-', $filter('number')(data[i].totalSalary, '2') + '/-'];
rowData.push(rowItem);
}
return rowData;
};
$scope.calculatePayment = function () {
$scope.data = [];
$scope.loading = true;
$q.all([getRegularData(), getFixedData(), getExpenseData()]).then(function (data) {
$scope.regularData = data[0];
$scope.fixedData = data[1];
$scope.expenseData = data[2];
for (var i = 0; i < $scope.driverList.length; i++) {
$scope.driverList[i].localRequest = getLocalRequestCount($scope.driverList[i].name);
$scope.driverList[i].outRequest = getOutRequestCount($scope.driverList[i].name);
$scope.driverList[i].allowance = getAllowance($scope.driverList[i].name);
$scope.driverList[i].fixrequestAmt = getFixReqAmt($scope.driverList[i].name);
$scope.driverList[i].advanceAmt = getAdvanceAmt($scope.driverList[i].name);
$scope.driverList[i].totalSalary = getTotalSalary($scope.driverList[i]);
}
$scope.data = $scope.driverList;
$scope.loading = false;
});
};
driverService.getDriver().then(function (res) {
$scope.driverList = res.data;
$scope.calculatePayment();
});
$scope.exportData = function () {
var columns = ['Sr. No', 'Driver Name', 'Base Salary', 'Local Requests', 'Out Requests', 'Total D.A.', 'Total Advanced', 'Total Salary'];
pdfService.buildPDF(columns, processForpdf($scope.data), 'Driver Salary - ' + $scope.filter.month + ' ' + $scope.filter.year, 'Driver_Salary_' + $scope.filter.month + '_' + $scope.filter.year, 0);
};
}]);
<file_sep>app.factory('calculation',[function(){
return{
convertIntoDate:function(str){
return str.getFullYear()+'/'+(str.getMonth()+1)+'/'+str.getDate();
},
convertIntoTime:function(str){
return str.getHours()+':'+str.getMinutes()+':'+str.getSeconds();
},
duration:function(sDate,eDate,sTime,eTime){
var buildSDate=this.convertIntoDate(sDate);
var buildSTime=this.convertIntoTime(sTime);
var startTimeStamp = new Date(buildSDate + ' ' + buildSTime);
var buildEDate=this.convertIntoDate(eDate);
var buildETime=this.convertIntoTime(eTime);
var EndTimeStamp = new Date(buildEDate + " " + buildETime);
return (EndTimeStamp-startTimeStamp);
}
}
}]);<file_sep>app.controller('headerController', ['$scope', '$state', '$http', 'requestService', 'vehicleService',
'packageService', 'driverService', 'partyService', 'expenseService',
function ($scope, $state, $http, requestService, vehicleService, packageService, driverService, partyService, expenseService) {
$scope.logOut = function () {
requestService.request.regular = null;
requestService.request.fixed = null;
packageService.package.local = null;
packageService.package.out = null;
packageService.package.fix = null;
vehicleService.vehicle.own = null;
vehicleService.vehicle.other = null;
driverService.driver = null;
partyService.party.client = null;
partyService.party.operator = null;
expenseService.expense.vehicleExpense = null;
expenseService.expense.driverExpense = null;
$http.get('/logout').then(function (res) {
$state.go('login');
}, function () {
console.log('ERROR');
});
}
}]);<file_sep>var gulp = require('gulp'),
sass = require('gulp-sass'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
uglify = require('gulp-uglify'),
inject = require('gulp-inject'),
util = require('gulp-util'),
minifyCss = require('gulp-minify-css'),
templateCache = require('gulp-angular-templatecache'),
sequence = require('gulp-sequence'),
gulpBowerFiles = require('gulp-bower-files'),
wiredep = require('wiredep').stream,
minifyHTML = require('gulp-minify-html'),
order = require('gulp-order'),
server = require('gulp-develop-server');
var pjson = require('./package.json');
var version = pjson.version;
var NwBuilder = require('node-webkit-builder');
var nw = new NwBuilder({
files: './deskapp/**/**', // use the glob format
platforms: ['osx32', 'osx64', 'win32', 'win64'],
version: '0.0.1'
});
//Create Executeables
gulp.task('exe',function(){
// Build returns a promise
nw.build().then(function () {
console.log('all done!');
}).catch(function (error) {
console.error(error);
});
});
//Convert SASS to CSS
gulp.task('sass',function(){
util.log('SASS -> CSS');
return gulp.src('app/scss/**/*.scss')
.pipe(order(['global.scss','**/*.scss']))
.pipe(sass())
.pipe(concat('main.min_'+version+'.css'))
.pipe(minifyCss())
.pipe(gulp.dest('dist/css'));
});
//Minify Javascript
gulp.task('javascript',function(){
util.log('Javascript file...');
return gulp.src(['app/src/**/*.js'])
.pipe(order(['src/app.js','**/*.js']))
.pipe(concat('script.js'))
.pipe(rename('script.min_'+version+'.js'))
.pipe(uglify())
.pipe(gulp.dest('dist/script'));
});
//Create template cache
gulp.task('template',function(){
util.log('Template Cache...');
return gulp.src(['app/src/**/*.html','!app/src/index.html'])
.pipe(minifyHTML({ empty: true }))
.pipe(templateCache({standalone:true}))
.pipe(uglify())
.pipe(rename('template.min_'+version+'.js'))
.pipe(gulp.dest('dist/template'));
});
gulp.task('bower-copy',function(){
return gulpBowerFiles().pipe(gulp.dest("dist/bower_components"));
});
gulp.task('bower-minify',function(){
util.log('Minification of bower components');
return gulp.src('dist/bower_components/**/*.js')
.pipe(uglify())
.pipe(gulp.dest("dist/bower_components"));
});
gulp.task('bower-inject',function () {
return gulp.src('dist/index.html')
.pipe(wiredep({
ignorePath:'../',
exclude:['bower_components/footable/css/footable.core.css']
}))
.pipe(gulp.dest('dist'));
});
//Inject files to index
gulp.task('inject',function(){
util.log('Inject to index');
var target = gulp.src('app/src/index.html'),
jsSources = gulp.src(['dist/template/*.js','dist/script/*.js'],{read:false},{relative: true}),
cssSource = gulp.src(['dist/css/*.css'],{read:false},{relative: true});
target.pipe(inject(jsSources,{ignorePath:'dist/', addRootSlash:false}))
.pipe(inject(cssSource,{ignorePath:'dist', addRootSlash:false}))
.pipe(gulp.dest('dist/'));
});
//Watch for file changes
gulp.task('watch',function() {
gulp.watch('app/scss/**/*.scss',['sass']);
gulp.watch('app/src/**/*.js',['javascript']);
gulp.watch('app/src/**/*.html',['template']);
});
gulp.task('bower',sequence('bower-copy','bower-inject','bower-minify'));
gulp.task('build',sequence(['sass','javascript','template'],'inject','bower'));
// run server
gulp.task('server:start', function(){
server.listen({path:'server.js'});
});
// restart server if server_old.js changed
gulp.task( 'server:restart', function() {
gulp.watch( [ 'server.js' ], server.restart );
});
<file_sep>app.controller('addRegularRequestController',
['$scope',
'$rootScope',
'$q',
'$filter',
'$uibModalInstance',
'requestService',
'vehicleService',
'driverService',
'partyService',
'packageService',
'messageService',
'record',
'calculation',
function ($scope,
$rootScope,
$q,
$filter,
$uibModalInstance,
requestService,
vehicleService,
driverService,
partyService,
packageService,
messageService,
record,
calculation) {
'use strict';
$scope.request = true;
$scope.loading = false;
$scope.action = record.action;
var currDate = new Date(),
newObj = {
'requestType': 'local',
'selectClient': 'party',
'vehicleSelect': 'own',
'driverSelect': 'existing',
'startTrip': {
'date': currDate
},
'endTrip': {
'date': currDate
},
'openingKm': 0,
'closingKm': 0,
'totalKm': 0,
'totalHr': 0,
'totalDays': 0,
'vehicle': {
'AC': 'Yes'
},
'inDirect': {
'AC': 'Yes'
},
'operator': {
'AC': 'Yes'
},
'agency': {
'AC': 'Yes'
},
'driverAllowance': 0,
'advancedFromAgency': 0,
'advanceAmt': 0,
'driverOverTime': 0,
'tollAmt': 0,
'parkingAmt': 0,
'totalAmt': 0,
'nightHalt': 0,
'ownerTotal': 0,
'profit': 0,
'payStatus': 'bill_not_sent'
}, loadDependencies = function () {
$q.all([vehicleService.getVehicle('own'),
vehicleService.getVehicle('other'),
driverService.getDriver(),
partyService.getParty('client'),
partyService.getParty('operator')]).then(function (res) {
/*Own Vehicle List*/
$scope.vehicleList = res[0].data[0].data;
if (!vehicleService.vehicle.own) {
vehicleService.vehicle.own = res[0].data;
}
/*Other Vehicle List*/
$scope.oVehicleList = res[1].data[0].data;
if (!vehicleService.vehicle.other) {
vehicleService.vehicle.other = res[1].data;
}
/*Driver List*/
$scope.driverList = res[2].data;
if (!driverService.driver) {
driverService.driver = res[2].data;
}
/*Client List*/
$scope.partyList = res[3].data[0].data;
if (!partyService.party.client) {
partyService.party.client = res[3].data;
}
/*Operator List*/
$scope.operatorList = res[4].data[0].data;
if (!partyService.party.operator) {
partyService.party.operator = res[4].data;
}
$scope.$watch('requestData.operator.operatorName', function (newVal, oldVal) {
$scope.requestData.operator.vehicle = "";
if (newVal) {
$scope.operatorVehicleList = $filter('filter')($scope.operatorList, {'name': newVal})[0].vehicle;
}
});
$scope.$watch('requestData.requestType', function (newVal, oldVal) {
packageService.getPackage(newVal).then(function (res) {
$scope.packageList = res.data[0].data;
/*$scope.requestData.vehicle.partyPackage="";
$scope.requestData.inDirect.ownerPackage="";
$scope.requestData.inDirect.partyPackage="";
$scope.requestData.agency.agencyPackage="";
$scope.requestData.agency.partyPackage="";
$scope.requestData.operator.operatorPackage="";
$scope.requestData.operator.partyPackage="";*/
if (!packageService.package[newVal]) {
packageService.package[newVal] = res.data;
}
});
});
});
};
if ($scope.action !== 'view') {
loadDependencies();
}
$scope.requestData = ($scope.action === 'new') ? newObj : record.data[0];
if (record.action === 'edit') {
$scope.requestData.startTrip.date = new Date($scope.requestData.startTrip.date);
$scope.requestData.endTrip.date = new Date($scope.requestData.endTrip.date);
$scope.requestData.startTrip.time = new Date($scope.requestData.startTrip.time);
$scope.requestData.endTrip.time = new Date($scope.requestData.endTrip.time);
var recordId = $scope.requestData._id;
}
$scope.hideView = record.action === 'view';
$scope.switchView = function () {
$scope.request = !$scope.request;
};
$scope.closeModal = function () {
$uibModalInstance.close();
};
$scope.calendar = {};
$scope.openCalendar = function (type) {
$scope.calendar[type] = true;
};
/*Calculations*/
$scope.calculateTotalKm = function () {
$scope.requestData.totalKm = ($scope.requestData.closingKm - $scope.requestData.openingKm);
};
$scope.calculateTotalHr = function () {
$scope.requestData.totalHr = calculation.duration($scope.requestData.startTrip.date, $scope.requestData.endTrip.date, $scope.requestData.startTrip.time, $scope.requestData.endTrip.time) / 3600000;
$scope.requestData.totalHr = $filter('number')($scope.requestData.totalHr, '2')
};
$scope.calculateTotalDays = function () {
var noOfDays = Math.round(0.4 + calculation.duration($scope.requestData.startTrip.date, $scope.requestData.endTrip.date, $scope.requestData.startTrip.time, $scope.requestData.endTrip.time) / 86400000);
$scope.requestData.totalDays = noOfDays <= 0 ? 1 : noOfDays;
};
$scope.calculateOutTotal = function (pgCode, pgName) {
var tripTotal = 0;
$scope.requestData.driverOverTime = 0;
var partyPackage = $filter('filter')($scope.packageList, {'packageCode': pgCode})[0];
if (pgName === 'party') {
$scope.requestData.reqPackage = JSON.parse(angular.toJson(partyPackage));
}
tripTotal = tripTotal + $scope.requestData.totalDays * partyPackage.basicAmt;
var extraKm = $scope.requestData.totalKm - (partyPackage.kmRate.minKm * $scope.requestData.totalDays);
if (extraKm > 0) {
tripTotal = tripTotal + (extraKm * partyPackage.kmRate.extraKm);
}
return tripTotal + $scope.requestData.tollAmt + $scope.requestData.parkingAmt + $scope.requestData.nightHalt;
};
$scope.calculateTotal = function (pgCode, pgName) {
var tripTotal = 0;
var partyPackage = $filter('filter')($scope.packageList, {'packageCode': pgCode})[0];
if (pgName === 'party') {
$scope.requestData.reqPackage = JSON.parse(angular.toJson(partyPackage));
}
if ($scope.requestData.totalKm <= partyPackage.kmRate.minKm && $scope.requestData.totalHr <= partyPackage.hrRate.minHr) {
$scope.requestData.driverOverTime = 0;
tripTotal = tripTotal + partyPackage.basicAmt;
}
if ($scope.requestData.totalHr > partyPackage.hrRate.minHr && $scope.requestData.totalKm <= partyPackage.kmRate.minKm) {
// var baseHrAmt = (Math.floor($scope.requestData.totalHr / partyPackage.hrRate.minHr)) * partyPackage.basicAmt;
var baseHrAmt = partyPackage.basicAmt;
var extraHrAmt = (Number($scope.requestData.totalHr) - partyPackage.hrRate.minHr) * partyPackage.hrRate.extraHr;
$scope.requestData.driverOverTime = ($scope.requestData.totalHr % 12) * 20;
tripTotal = tripTotal + (baseHrAmt + extraHrAmt);
}
if ($scope.requestData.totalKm > partyPackage.kmRate.minKm && $scope.requestData.totalHr <= partyPackage.hrRate.minHr) {
var baseKmAmt = partyPackage.basicAmt;
// var baseKmAmt = (Math.floor($scope.requestData.totalKm / partyPackage.kmRate.minKm)) * partyPackage.basicAmt;
var extraKm = ($scope.requestData.totalKm - partyPackage.kmRate.minKm);
var extraKmAmt = extraKm > 0 ? extraKm * partyPackage.kmRate.extraKm : 0;
$scope.requestData.driverOverTime = 0;
tripTotal = tripTotal + (baseKmAmt + extraKmAmt);
}
if ($scope.requestData.totalKm > partyPackage.kmRate.minKm && $scope.requestData.totalHr > partyPackage.hrRate.minHr) {
var baseHrAmt = (Math.floor($scope.requestData.totalHr / partyPackage.hrRate.minHr)) * partyPackage.basicAmt;
var extraHrAmt = (Number($scope.requestData.totalHr) - partyPackage.hrRate.minHr) * partyPackage.hrRate.extraHr;
var extraKm = ($scope.requestData.totalKm - partyPackage.kmRate.minKm);
var extraKmAmt = extraKm > 0 ? extraKm * partyPackage.kmRate.extraKm : 0;
$scope.requestData.driverOverTime = ($scope.requestData.totalHr % 12) * 20;
tripTotal = tripTotal + (baseHrAmt + extraHrAmt + extraKmAmt);
}
return tripTotal + $scope.requestData.tollAmt + $scope.requestData.parkingAmt + $scope.requestData.nightHalt;
};
$scope.calculate = function () {
switch ($scope.requestData.vehicleSelect) {
case 'own': {
if ($scope.requestData.requestType === 'out') {
$scope.requestData.totalAmt = $scope.calculateOutTotal($scope.requestData.vehicle.partyPackage, 'party');
$scope.requestData.profit = ($scope.requestData.totalAmt - $scope.requestData.driverAllowance - $scope.requestData.driverOverTime);
} else {
$scope.requestData.totalAmt = $scope.calculateTotal($scope.requestData.vehicle.partyPackage, 'party') - $scope.requestData.advanceAmt;
$scope.requestData.profit = ($scope.requestData.totalAmt - $scope.requestData.driverAllowance - $scope.requestData.driverOverTime) + $scope.requestData.advanceAmt;
}
break;
}
case 'indirect': {
if ($scope.requestData.requestType === 'out') {
$scope.requestData.totalAmt = $scope.calculateOutTotal($scope.requestData.inDirect.partyPackage, 'party');
$scope.requestData.ownerTotal = $scope.calculateOutTotal($scope.requestData.inDirect.ownerPackage, 'owner');
$scope.requestData.profit = $scope.requestData.totalAmt - $scope.requestData.ownerTotal;
} else {
$scope.requestData.totalAmt = $scope.calculateTotal($scope.requestData.inDirect.partyPackage, 'party') - $scope.requestData.advanceAmt - $scope.requestData.advancedFromAgency;
$scope.requestData.ownerTotal = $scope.calculateTotal($scope.requestData.inDirect.ownerPackage, 'owner');
$scope.requestData.profit = ($scope.requestData.totalAmt - $scope.requestData.ownerTotal) + $scope.requestData.advanceAmt + $scope.requestData.advancedFromAgency;
}
break;
}
case 'operator': {
if ($scope.requestData.requestType === 'out') {
$scope.requestData.totalAmt = $scope.calculateOutTotal($scope.requestData.operator.partyPackage, 'party');
$scope.requestData.ownerTotal = $scope.calculateOutTotal($scope.requestData.operator.operatorPackage, 'owner');
$scope.requestData.profit = $scope.requestData.totalAmt - $scope.requestData.ownerTotal;
} else {
$scope.requestData.totalAmt = $scope.calculateTotal($scope.requestData.operator.partyPackage, 'party') - $scope.requestData.advanceAmt - $scope.requestData.advancedFromAgency;
$scope.requestData.ownerTotal = $scope.calculateTotal($scope.requestData.operator.operatorPackage, 'owner');
$scope.requestData.profit = ($scope.requestData.totalAmt - $scope.requestData.ownerTotal) + $scope.requestData.advanceAmt + $scope.requestData.advancedFromAgency;
}
break;
}
case 'other': {
if ($scope.requestData.requestType === 'out') {
$scope.requestData.totalAmt = $scope.calculateOutTotal($scope.requestData.agency.partyPackage, 'party');
$scope.requestData.ownerTotal = $scope.calculateOutTotal($scope.requestData.agency.agencyPackage, 'owner');
$scope.requestData.profit = $scope.requestData.totalAmt - $scope.requestData.ownerTotal;
} else {
$scope.requestData.totalAmt = $scope.calculateTotal($scope.requestData.agency.partyPackage, 'party') - $scope.requestData.advanceAmt - $scope.requestData.advancedFromAgency;
$scope.requestData.ownerTotal = $scope.calculateTotal($scope.requestData.agency.agencyPackage, 'owner');
$scope.requestData.profit = ($scope.requestData.totalAmt - $scope.requestData.ownerTotal) + $scope.requestData.advanceAmt + $scope.requestData.advancedFromAgency;
}
break;
}
}
};
$scope.submitRequest = function () {
$scope.loading = true;
if ($scope.requestData.vehicleSelect === 'operator') {
$scope.requestData.operator.vehicleName = $scope.requestData.operator.vehicle.split(',')[0];
$scope.requestData.operator.vehicleNo = $scope.requestData.operator.vehicle.split(',')[1];
}
$scope.requestData.month = $filter('date')($scope.requestData.startTrip.date, "MMM");
$scope.requestData.year = $filter('date')($scope.requestData.startTrip.date, "yyyy");
if ($scope.action === 'new') {
requestService.addRequest('regular', $scope.requestData).then(function (res) {
$scope.closeModal();
requestService.request.regular = null;
$rootScope.$emit('regularRequest');
messageService.showMessage({
'type': 'success',
'title': 'Regular Request',
'text': 'New regular request added successfully.'
});
}, function () {
$scope.closeModal();
messageService.showMessage({
'type': 'error',
'title': 'Regular Request',
'text': 'New regular request not added successfully. Please try again.'
});
});
} else {
delete $scope.requestData._id;
requestService.updateRequest('regular', recordId, JSON.parse(angular.toJson($scope.requestData))).then(function (res) {
$scope.closeModal();
requestService.request.regular = null;
$rootScope.$emit('regularRequest');
messageService.showMessage({
'type': 'success',
'title': 'Regular Request',
'text': 'Regular request Updated successfully.'
});
}, function () {
$scope.closeModal();
messageService.showMessage({
'type': 'error',
'title': 'Regular Request',
'text': 'Request not Updated successfully. Please try again.'
});
});
}
}
}]);
<file_sep>app.controller('localPackageController', ['$scope', '$state', '$rootScope', '$uibModal', 'packageService', 'messageService', 'gridMap',
function ($scope, $state, $rootScope, $uibModal, packageService, messageService, gridMap) {
$scope.data = [];
$scope.gridConfig = gridMap.PACKAGE;
$scope.loading = true;
var success = function (res) {
$scope.data = res.data[0].data;
if (!packageService.package.local) {
packageService.package.local = res.data;
}
$scope.loading = false;
},
init = function () {
packageService.getPackage('local').then(success, function () {
// $state.go('login');
});
},
packageModal = function (action, data) {
$uibModal.open({
templateUrl: 'package/package-modal.html',
controller: 'packageModalController',
size: 'lg',
resolve: {
record: function () {
return {
'action': action,
'type': 'local',
'data': data
};
}
}
});
};
$rootScope.$on('localPackage', function () {
init();
});
init();
$scope.newPackage = function () {
packageModal('new', {});
};
$scope.view = function (id) {
packageModal('view', packageService.filterRecord('local', id)[0]);
};
$scope.edit = function (id) {
packageModal('edit', packageService.filterRecord('local', id)[0]);
};
$scope.delete = function (id) {
messageService.deleteConfirm().result.then(function (data) {
if (data) {
$scope.deleteRecord(id);
}
});
};
$scope.deleteRecord = function (id) {
var pkgName = packageService.filterRecord('local', id)[0].packageCode;
packageService.deletePackage('{"name":"local"}', id).then(function () {
packageService.package["local"] = null;
init();
messageService.showMessage({
'type': 'success',
'title': 'Package',
'text': 'Package ' + pkgName + ' Deleted successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Package',
'text': 'Package ' + pkgName + ' can not be deleted at this time. Please try again.'
});
});
}
}]);<file_sep>app.controller('clientPaymentController', ['$scope', '$q', '$filter', 'config', 'partyService', 'requestService', 'pdfService',
function ($scope, $q, $filter, config, partyService, requestService, pdfService) {
$scope.data = null;
$scope.localEnv = config.local;
$scope.loading = false;
$scope.currMonth = new Date().getMonth();
$scope.monthList = config.months;
$scope.yearList = config.years();
$scope.filter = {};
$scope.filter.year = new Date().getFullYear().toString();
$scope.filter.month = $scope.monthList[$scope.currMonth];
partyService.getParty('client').then(function (res) {
$scope.partyList = res.data[0].data;
if (!partyService.party.client) {
partyService.party.client = res.data;
}
});
var partyTotal = function (data) {
$scope.partyTotal = 0;
for (var i = 0; i < data.length; i++) {
$scope.partyTotal = $scope.partyTotal + data[i].totalAmt + data[i].tollAmt + data[i].parkingAmt;
}
},
processForpdf = function (data) {
var rowData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [i + 1, $filter('date')(data[i].startTrip.date, 'dd-MMM-yyyy'), data[i].requestType === 'local' ? 'Local' : 'Out Station', data[i].vehicleSelect === 'own' ? data[i].vehicle.vehicle : data[i].vehicleSelect === 'indirect' ? data[i].inDirect.vehicle : data[i].vehicleSelect === 'operator' ? data[i].operator.vehicleName : data[i].agency.vehicleName, $filter('number')(data[i].totalAmt, '2') + '/-', $filter('number')(data[i].tollAmt, '2') + '/-', $filter('number')(data[i].parkingAmt, '2') + '/-', $filter('number')((data[i].totalAmt + data[i].tollAmt + data[i].parkingAmt), '2') + '/-'];
rowData.push(rowItem);
}
return rowData;
};
$scope.calculatePayment = function () {
$scope.data = [];
$scope.loading = true;
if (requestService.request.regular) {
$scope.data = $filter('filter')(requestService.request.regular, {
"selectClient": "party",
"partyName": $scope.filter.party,
"month": $scope.filter.month,
"year": $scope.filter.year
});
$scope.loading = false;
partyTotal($scope.data);
} else {
requestService.getRequest("regular", 'q={"selectClient":"party","partyName":"' + $scope.filter.party + '","month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}&s={"startTrip.date":-1}').then(function (res) {
$scope.loading = false;
$scope.data = res.data;
partyTotal($scope.data);
});
}
};
$scope.exportData = function () {
var columns = ['Sr. No', 'Date', 'Request Type', 'Vehicle', 'Trip Amount', 'Toll Amount', 'Parking Amount', 'Total Amount'];
pdfService.buildPDF(columns, processForpdf($scope.data), 'Client Payments', 'Client_Payments', 0, 'Party Name : ' + $scope.filter.party + ', Month : ' + $scope.filter.month + ', Year : ' + $scope.filter.year + ' :: Total Amount : ' + $filter('number')($scope.partyTotal, '2') + '/-');
};
}]);
<file_sep># Travel Management
This application is develop for Travel Agency to manage their vehicle data such as requests, Payment, Expenses, driver salaries as well as export the report based on the vehicle.
The application is under development.
## Installation
```
npm install
npm start
```
Use following URL to run the application
> [http://localhost:9090/](http://localhost:9090/).
Login Credentials
> Username : admin
> Password : <PASSWORD><file_sep>app.constant('gridMap',{
'PACKAGE':[{
"name":"Package Code",
"hideOn":"phone",
"map":"packageCode"
},{
"name":"Basic Amount",
"map":"basicAmt",
"type":"amount"
},{
"name":"Minimum KMs",
"map":"kmRate.minKm"
},{
"name":"Minimum Hours",
"map":"hrRate.minHr"
},{
"name":"Extra KM Rate",
"map":"kmRate.extraKm",
"type":"amount",
"hideOn":"phone,tablet"
},{
"name":"Extra HR Rate",
"map":"hrRate.extraHr",
"type":"amount",
"hideOn":"phone,tablet"
}],
'VEHICLE':{
'OWN':[{
"name":"Vehicle No.",
"map":"vehicleNo"
},{
"name":"Vehicle Name",
"hideOn":"phone,tablet",
"map":"vehicleName"
},{
"name":"Vehicle owner",
"hideOn":"phone",
"map":"vehicleOwner"
},{
"name":"Vehicle Type",
"hideOn":"phone,tablet",
"map":"vehicleType"
},{
"name":"Loan",
"type":"amount",
"map":"loan.loanAmt"
},{
"name":"Fixed To Company",
"map":"selectFixed"
}],
'OTHER':[{
"name":"Vehicle No.",
"map":"vehicleNo"
},{
"name":"Vehicle Name",
"hideOn":"phone",
"map":"vehicleName"
},{
"name":"Vehicle owner",
"map":"vehicleOwner"
},{
"name":"Vehicle Type",
"hideOn":"phone",
"map":"vehicleType"
}]
},
'PARTY':{
'CLIENT':[{
"name":"Party Name",
"map":"name"
},{
"name":"Party Address",
"hideOn":"phone,tablet",
"map":"address"
},{
"name":"Party Contact",
"type":"phone",
"map":"contact"
},{
"name":"Party Email",
"hideOn":"phone,tablet",
"map":"email"
},{
"name":"Comments",
"hideOn":"phone,tablet",
"map":"comments"
}],
'OPERATOR':[{
"name":"<NAME>",
"map":"name"
},{
"name":"Operator Address",
"map":"address",
"hideOn":"phone,tablet"
},{
"name":"Operator contact",
"map":"contact",
"type":"phone"
},{
"name":"Operator Email",
"map":"email",
"hideOn":"phone,tablet"
},{
"name":"Vehicle",
"map":"vehicle",
"hideOn":"phone,tablet",
"type":"repeat"
},{
"name":"Comments",
"map":"comments",
"hideOn":"phone,tablet"
}]
}
});<file_sep>app.factory('partyService', ['$uibModal', '$filter', '$q', 'config', function ($uibModal, $filter, $q, config) {
return {
party: {
'client': null,
'operator': null
},
filterRecord: function (type, id) {
return $filter('filter')(this.party[type][0].data, {'_id': id});
},
getParty: function (type) {
return (this.party[type]) ? $q.resolve({data: this.party[type]}) : config.getData(config.party, 'q={"name":"' + type + '"}');
},
addParty: function (filter, item) {
item._id = config.guid();
return config.updateData(config.party, filter, {$push: {data: item}});
},
updateParty: function (filter, item) {
return config.updateData(config.party, filter, {$set: {"data.$": item}});
},
deleteParty: function (filter, id) {
var item = {'_id': id};
return config.updateData(config.party, filter, {$pull: {data: item}});
}
}
}]);<file_sep>app.controller('indirectPaymentController',
['$scope', '$q', '$filter', 'config', 'vehicleService', 'requestService', 'pdfService',
function ($scope, $q, $filter, config, vehicleService, requestService, pdfService) {
$scope.data = null;
$scope.localEnv = config.local;
$scope.loading = false;
$scope.currMonth = new Date().getMonth();
$scope.monthList = config.months;
$scope.yearList = config.years();
$scope.filter = {};
$scope.filter.year = new Date().getFullYear().toString();
$scope.filter.month = $scope.monthList[$scope.currMonth];
vehicleService.getVehicle('other').then(function (res) {
$scope.vehicleList = res.data[0].data;
if (!vehicleService.vehicle.other) {
vehicleService.vehicle.other = res.data;
}
});
var fetchRegularData = function () {
var regularData;
if (requestService.request.regular) {
regularData = $filter('filter')(requestService.request.regular, {
'vehicleSelect': 'indirect',
"inDirect": {"vehicle": $scope.filter.vehicle},
"month": $scope.filter.month,
"year": $scope.filter.year
});
fetchFixedData(regularData);
} else {
requestService.getRequest("regular", 'q={"vehicleSelect":"indirect","inDirect.vehicle":"' + $scope.filter.vehicle + '","month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
regularData = res.data;
fetchFixedData(regularData)
});
}
},
fetchFixedData = function (regData) {
var fixedData;
if (requestService.request.fixed) {
fixedData = $filter('filter')(requestService.request.fixed, {
'vehicleSelect': 'indirect',
"inDirect": {"vehicle": $scope.filter.vehicle},
"month": $scope.filter.month,
"year": $scope.filter.year
});
calculateTotal(regData, fixedData);
} else {
requestService.getRequest("fixed", 'q={"vehicleSelect":"indirect","inDirect.vehicle":"' + $scope.filter.vehicle + '","month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
fixedData = res.data;
calculateTotal(regData, fixedData);
});
}
},
calculateTotal = function (regData, fixData) {
$scope.data = regData.concat(fixData);
$scope.loading = false;
$scope.indirectTotal = 0;
for (var i = 0; i < $scope.data.length; i++) {
$scope.indirectTotal = $scope.indirectTotal + $scope.data[i].totalAmt + $scope.data[i].tollAmt + $scope.data[i].parkingAmt;
}
},
processForpdf = function (data) {
var rowData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [i + 1, $filter('date')(data[i].date ? data[i].date : data[i].startTrip.date, 'dd-MMM-yyyy'), data[i].requestType === 'local' ? 'Local' : 'Out Station', $filter('number')(data[i].totalAmt, '2') + '/-', $filter('number')(data[i].tollAmt, '2') + '/-', $filter('number')(data[i].parkingAmt, '2') + '/-', $filter('number')((data[i].totalAmt + data[i].tollAmt + data[i].parkingAmt), '2') + '/-'];
rowData.push(rowItem);
}
return rowData;
};
$scope.exportData = function () {
var columns = ['Sr. No', 'Date', 'Request Type', 'Trip Amount', 'Toll Amount', 'Parking Amount', 'Total Amount'];
pdfService.buildPDF(columns, processForpdf($scope.data), 'Indirect Payment - ' + $scope.filter.month + ' ' + $scope.filter.year, 'Indirect_Payment_' + $scope.filter.month + '_' + $scope.filter.year, 0, 'Party Name : ' + $scope.filter.vehicle + ', Month : ' + $scope.filter.month + ', Year : ' + $scope.filter.year + ' :: Total Amount : ' + $filter('number')($scope.indirectTotal, '2') + '/-');
};
$scope.calculatePayment = function () {
$scope.data = [];
$scope.loading = true;
fetchRegularData();
};
}]);
<file_sep>app.controller('operatorPaymentController',
['$scope', '$q', '$filter', 'config', 'partyService', 'requestService', 'pdfService',
function ($scope, $q, $filter, config, partyService, requestService, pdfService) {
$scope.data = [];
$scope.localEnv = config.local;
$scope.loading = true;
$scope.currMonth = new Date().getMonth();
$scope.monthList = config.months;
$scope.yearList = config.years();
$scope.filter = {};
$scope.filter.year = new Date().getFullYear().toString();
$scope.filter.month = $scope.monthList[$scope.currMonth];
var opearatorRegData = null,
opearatorFixData = null,
getRegularData = function () {
var def = $q.defer();
if (requestService.request.regular) {
var regData = requestService.request.regular.filter(function (item) {
return (item.selectClient == "operator" || item.vehicleSelect == "operator") && item.month == $scope.filter.month && item.year == $scope.filter.year;
});
def.resolve(regData);
} else {
requestService.getRequest("regular", 'q={"$or":[{"selectClient":"operator"},{"vehicleSelect":"operator"}],"month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
def.resolve(res.data);
});
}
return def.promise;
},
getFixedData = function () {
var def = $q.defer();
if (requestService.request.fixed) {
var fixData = requestService.request.fixed.filter(function (item) {
return item.vehicleSelect == "operator" && item.month == $scope.filter.month && item.year == $scope.filter.year;
});
def.resolve(fixData)
} else {
requestService.getRequest("fixed", 'q={"vehicleSelect":"operator","month":"' + $scope.filter.month + '","year":"' + $scope.filter.year + '"}').then(function (res) {
def.resolve(res.data);
});
}
return def.promise;
},
getPaymentIn = function (item) {
var paymentIn = 0;
var req = $filter('filter')(opearatorRegData, {"selectClient": "operator", "operatorName": item.name});
item.totalInReq = req.length;
for (var i = 0; i < req.length; i++) {
paymentIn = paymentIn + ((req[i].totalAmt + req[i].tollAmt + req[i].parkingAmt + req[i].driverOverTime) - (req[i].advanceAmt ? req[i].advanceAmt : 0));
}
return paymentIn;
},
getPaymentOut = function (item) {
var paymentOut = 0;
var req = $filter('filter')(opearatorRegData, {
"vehicleSelect": "operator",
"operator": {"operatorName": item.name}
});
var fixReq = $filter('filter')(opearatorFixData, {
"vehicleSelect": "operator",
"operator": {"operatorName": item.name}
});
item.totalOutReq = req.length + fixReq.length;
for (var i = 0; i < req.length; i++) {
paymentOut = paymentOut + (req[i].ownerTotal + req[i].tollAmt + req[i].parkingAmt + req[i].driverOverTime);
}
for (var i = 0; i < fixReq.length; i++) {
paymentOut = paymentOut + fixReq[i].totalAmt + fixReq[i].tollAmt + fixReq[i].parkingAmt + fixReq[i].driverOverTime;
}
return paymentOut;
},
processForpdf = function (data) {
var rowData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [i + 1, data[i].name, data[i].totalInReq, data[i].totalOutReq, $filter('number')(data[i].paymentIn, '2') + '/-', $filter('number')(data[i].paymentOut, '2') + '/-', $filter('number')(data[i].diff, '2') + '/-'];
rowData.push(rowItem);
}
return rowData;
};
$scope.calculatePayment = function () {
$scope.data = [];
$scope.loading = true;
$q.all([getRegularData(), getFixedData()]).then(function (data) {
opearatorRegData = data[0];
opearatorFixData = data[1];
angular.forEach($scope.operatorList, function (item) {
item.paymentIn = getPaymentIn(item);
item.paymentOut = getPaymentOut(item);
item.diff = item.paymentIn - item.paymentOut;
});
$scope.data = $scope.operatorList;
$scope.loading = false;
});
};
$scope.getOperatorDetail = function (id, name) {
console.log(id);
console.log(name);
};
$scope.exportData = function () {
var columns = ['Sr.No', 'Operator Name', 'Out Bound Requests', 'In Bound Requests', 'Payment In', 'Payment Out', 'Difference'];
pdfService.buildPDF(columns, processForpdf($scope.data), 'Operator Payment - ' + $scope.filter.month + ' ' + $scope.filter.year, 'Operator_Payment_' + $scope.filter.month + '_' + $scope.filter.year, 0);
};
partyService.getParty('operator').then(function (res) {
$scope.operatorList = res.data[0].data;
$scope.calculatePayment();
});
}]);
<file_sep>app.controller('dashboardController',['$scope','$q','driverService','packageService','vehicleService','partyService',function($scope,$q,driverService,packageService,vehicleService,partyService){
$scope.currDate = new Date();
}]);<file_sep>app.controller('driverModalController',
['$scope', '$rootScope', '$uibModalInstance', 'driverService', 'messageService', 'record',
function ($scope, $rootScope, $uibModalInstance, driverService, messageService, record) {
'use strict';
$scope.driver = angular.copy(record.data);
$scope.action = record.action;
$scope.driver.joinDate = $scope.action === 'new' ? new Date() : new Date($scope.driver.joinDate);
if ($scope.action === 'edit') {
var recordId = $scope.driver._id;
}
$scope.calendar = {
open: false
};
$scope.loading = false;
$scope.hideView = ($scope.action === 'view');
$scope.openCalendar = function () {
$scope.calendar.open = true;
};
$scope.closeModal = function () {
$uibModalInstance.close();
};
$scope.submitRequest = function () {
$scope.loading = true;
if (record.action === 'new') {
driverService.addDriver($scope.driver).then(function () {
$scope.closeModal();
driverService.driver = null;
$rootScope.$emit('driver');
messageService.showMessage({
'type': 'success',
'title': 'Driver',
'text': 'New driver added successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Driver',
'text': 'Driver not added successfully. Please try again.'
});
});
} else {
delete $scope.driver._id;
driverService.updateDriver(recordId, $scope.driver).then(function () {
$scope.closeModal();
driverService.driver = null;
$rootScope.$emit('driver');
messageService.showMessage({
'type': 'success',
'title': 'Driver',
'text': 'Driver updated successfully.'
});
}, function (err) {
messageService.showMessage({
'type': 'error',
'title': 'Driver',
'text': 'Driver not updated successfully. Please try again.'
});
});
}
};
}]);<file_sep>app.controller('expenseController', ['$scope', function ($scope) {
}]);
<file_sep>app.controller('packageModalController',
['$scope', '$rootScope', '$uibModalInstance', 'packageService', 'messageService', 'record',
function ($scope, $rootScope, $uibModalInstance, packageService, messageService, record) {
'use strict';
$scope.package = angular.copy(record.data);
$scope.action = record.action;
$scope.type = record.type;
$scope.loading = false;
$scope.hideView = ($scope.action === 'view');
$scope.closeModal = function () {
$uibModalInstance.close();
};
$scope.submitRequest = function () {
$scope.loading = true;
if (record.action === 'new') {
packageService.addPackage('{"name":"' + $scope.type + '"}', $scope.package).then(function () {
$scope.closeModal();
packageService.package[$scope.type] = null;
$rootScope.$emit($scope.type + 'Package');
messageService.showMessage({
'type': 'success',
'title': 'Package',
'text': 'New ' + $scope.type + ' package added successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Package',
'text': $scope.type + ' package not added successfully. Please try again.'
});
});
} else {
packageService.updatePackage('{"name":"' + $scope.type + '","data._id":"' + $scope.package._id + '"}', $scope.package)
.then(function () {
$scope.closeModal();
packageService.package[$scope.type] = null;
$rootScope.$emit($scope.type + 'Package');
messageService.showMessage({
'type': 'success',
'title': 'Package',
'text': 'New ' + $scope.type + ' package updated successfully.'
});
}, function (err) {
messageService.showMessage({
'type': 'error',
'title': 'Package',
'text': $scope.type + ' package not updated successfully. Please try again.'
});
});
}
};
}]);<file_sep>app.factory('driverService', ['$filter', '$q', 'config', function ($filter, $q, config) {
return {
driver: null,
filterRecord: function (id) {
return $filter('filter')(this.driver, {'_id': config.local ? id : {'$oid': id}});
},
getDriver: function () {
if (this.driver) {
return $q.resolve({data: this.driver});
} else {
return config.getData(config.driver, 'q={}');
}
},
addDriver: function (driver) {
return config.postData(config.driver, driver);
},
updateDriver: function (id, data) {
var filter = config.local ? '{"_id":"' + id + '"}' : '{"_id":{"$oid":"' + id.$oid + '"}}';
return config.updateData(config.driver, filter, {$set: data});
},
deleteDriver: function (id) {
return config.deleteData(config.driver, id);
}
}
}]);<file_sep>app.directive('responsiveGrid',['$timeout',function($timeout){
return function($sc,$el,$attr){
var table = $($el).parent().parent();
if($sc.$last && !table.hasClass('footable-loaded')){
$timeout(function(){
table.footable();
}, 10);
};
if($sc.$last && table.hasClass('footable-loaded')){
$timeout(function(){
table.trigger('footable_redraw');
}, 10);
}
}
}]);
/*Grid Directive*/
app.directive('grid',['config',function(config){
return{
restrict:'AE',
templateUrl:'common/grid.html',
replace:true,
scope: {
datasource: '=',
gridconfig: '=',
viewData: '&view',
editData: '&edit',
deleteData: '&delete'
},
controller:['$scope',function($scope){
$scope.localEnv=config.local;
$scope.gridData=$scope.gridconfig;
$scope.$watch('datasource',function(){
$scope.data=$scope.datasource;
});
}]
}
}]);
/*Input Validators*/
app.directive('number',function(){
var REGEX = /^\-?\d+$/;
return{
restrict:'A',
require:'ngModel',
link:function($sc,$el,$attr,$ctrl){
$ctrl.$validators.number=function(modelValue, viewValue){
return REGEX.test(viewValue);
}
}
}
});<file_sep>app.controller('allListController', ['$scope', '$state', '$rootScope', '$q', '$filter', 'config', 'requestService', 'vehicleService', 'driverService', 'partyService', 'messageService', 'pdfService',
function ($scope, $state, $rootScope, $q, $filter, config, requestService, vehicleService, driverService, partyService, messageService, pdfService) {
$scope.data = [];
$scope.localEnv = config.local;
$scope.loading = true;
$scope.currMonth = new Date().getMonth();
$scope.monthList = config.months;
var initialData;
$scope.filter = {
'type': 'party'
};
$scope.filter.month = $scope.monthList[$scope.currMonth];
var init = function () {
$q.all([requestService.getRequest('regular', 's={"startTrip.date":-1}'),
requestService.getRequest('fixed', 's={"date":-1}'),
vehicleService.getVehicle('own'),
driverService.getDriver(),
partyService.getParty('client')]).then(function (data) {
$scope.loading = false;
getAllRequests(data[0].data, data[1].data);
vehicleList(data[2].data);
driverList(data[3].data);
partyList(data[4].data);
}, function () {
$state.go('login');
});
},
pagination = function () {
$scope.loading = false;
$scope.totalItems = $scope.data.length;
$scope.currentPage = requestService.request.pager.currentPage;
$scope.itemsPerPage = requestService.request.pager.itemsPerPage;
$scope.maxSize = requestService.request.pager.maxSize;
},
partyList = function (data) {
$scope.partyList = data[0].data;
if (!partyService.party.client) {
partyService.party.client = data;
}
},
vehicleList = function (data) {
$scope.vehicleList = data[0].data;
if (!vehicleService.vehicle.own) {
vehicleService.vehicle.own = data;
}
},
driverList = function (data) {
$scope.driverList = data;
if (!driverService.driver) {
driverService.driver = data;
}
},
getAllRequests = function (regData, fixData) {
if (!requestService.request.regular) {
requestService.request.regular = regData;
}
if (!requestService.request.fixed) {
requestService.request.fixed = fixData;
}
var allData = [];
angular.forEach(regData, function (item, key) {
allData.push({
'_id': $scope.localEnv ? item._id : item._id.$oid,
'date': item.startTrip.date,
'request': 'regular',
'requestType': item.requestType === 'local' ? 'Local' : 'Out Station',
'client': item.selectClient === 'party' ? item.partyName : item.selectClient === 'operator' ? item.operatorName : item.userName,
'vehicle': item.vehicleSelect === 'own' ? item.vehicle.vehicle : item.vehicleSelect === 'indirect' ? item.inDirect.vehicle : item.vehicleSelect === 'operator' ? item.operator.vehicleName + ',' + item.operator.vehicleNo : item.agency.vehicleName + ',' + item.agency.vehicleNo,
'driver': item.vehicleSelect === 'own' ? item.vehicle.driver : item.vehicleSelect === 'indirect' ? item.inDirect.driver : item.vehicleSelect === 'operator' ? item.operator.driver : item.agency.driver,
'totalKm': item.totalKm,
'month': item.month,
'year': item.year
});
});
angular.forEach(fixData, function (item, key) {
allData.push({
'_id': $scope.localEnv ? item._id : item._id.$oid,
'date': item.date,
'request': 'fixed',
'requestType': item.requestType === 'local' ? 'Local' : 'Out Station',
'client': item.partyName,
'vehicle': item.vehicleSelect === "daily" ? item.vehicle : item.vehicleSelect === "own" ? item.own.vehicle : item.vehicleSelect === "indirect" ? item.inDirect.vehicle : item.vehicleSelect === "operator" ? item.operator.vehicleName + ',' + item.operator.vehicleNo : item.agency.vehicleName + ',' + item.agency.vehicleNo,
'driver': (item.vehicleSelect === "daily" || item.vehicleSelect === "own") ? item.driver : item.vehicleSelect === "indirect" ? item.inDirect.driver : item.vehicleSelect === "operator" ? item.operator.driver : item.agency.driver,
'totalKm': item.totalKm,
'month': item.month,
'year': item.year
});
});
$scope.data = $filter('orderBy')(allData, '-date');
initialData = angular.copy($scope.data);
pagination()
};
init();
$rootScope.$on('fixedRequest', function () {
init();
});
$rootScope.$on('regularRequest', function () {
init();
});
$scope.applyFilter = function () {
switch ($scope.filter.type) {
case 'party': {
$scope.data = $filter('filter')(initialData, {"client": $scope.filter.party, "month": $scope.filter.month});
break;
}
case 'vehicle': {
$scope.data = $filter('filter')(initialData, {
"vehicle": $scope.filter.vehicle,
"month": $scope.filter.month
});
break;
}
case 'driver': {
$scope.data = $filter('filter')(initialData, {"driver": $scope.filter.driver, "month": $scope.filter.month});
break;
}
}
};
$scope.clearFilter = function () {
$scope.data = initialData;
$scope.filter.type = 'party';
$scope.filter.party = "";
$scope.filter.vehicle = "";
$scope.filter.driver = "";
$scope.filter.month = $scope.monthList[$scope.currMonth];
};
$scope.viewRequest = function (type, id) {
var ctrl = (type == 'regular') ? 'addRegularRequestController' : 'addFixedRequestController';
requestService.viewRequest(type, 'request/' + type + '/add-' + type + '-request.html', ctrl, id);
};
$scope.editRequest = function (type, id) {
var ctrl = (type == 'regular') ? 'addRegularRequestController' : 'addFixedRequestController';
requestService.editRequest(type, 'request/' + type + '/add-' + type + '-request.html', ctrl, id);
};
$scope.deleteRequest = function (type, id) {
messageService.deleteConfirm().result.then(function (data) {
if (data) {
$scope.deleteRecord(type, id);
}
});
};
$scope.deleteRecord = function (type, id) {
requestService.deleteRequest(type, id).then(function (res) {
requestService.request[type] = null;
init();
messageService.showMessage({
'type': 'success',
'title': type + ' Request',
'text': type + ' Request Deleted successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': type + ' Request',
'text': type + ' Request can not be deleted at this time. Please try again.'
});
});
};
$scope.processForAllpdf = function (data) {
var rowData = [];
for (var i = 0; i < data.length; i++) {
var rowItem = [i + 1, $filter('date')(data[i].date, 'dd-MMM-yyyy'), data[i].request, data[i].requestType, data[i].client, data[i].vehicle, data[i].driver, data[i].totalKm + ' KM'];
rowData.push(rowItem);
}
return rowData;
};
$scope.exportData = function () {
var columns = ['Sr. No', 'Date', 'Request', 'Request Type', 'Cliet Name', 'Vehicle', 'Driver', 'Total KM'];
pdfService.buildPDF(columns, $scope.processForAllpdf($scope.data), 'All Requests', 'All_Requests');
};
}]);
<file_sep>var app = angular.module('travelApp', ['ui.router', 'templates', 'ui.bootstrap']);
app.config(['$stateProvider', '$urlRouterProvider', function ($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise('/login');
$stateProvider
.state('login', {
url: '/login',
views: {
'header': {
templateUrl: 'header/auth-header.html'
},
'page': {
templateUrl: 'login/login.html',
controller: 'loginController'
}
}
})
.state('register', {
url: '/register',
views: {
'header': {
templateUrl: 'header/auth-header.html'
},
'page': {
templateUrl: 'register/register.html',
controller: 'registerController'
}
}
})
.state('forgot', {
url: '/forgot',
views: {
'header': {
templateUrl: 'header/auth-header.html'
},
'page': {
templateUrl: 'forgotPassword/forgotpassword.html',
controller: 'forgotPasswordController'
}
}
})
.state('dashboard', {
url: '/dashboard',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'dashboard/dashboard.html',
controller: 'dashboardController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('request', {
url: '/request',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'request/request.html',
controller: 'requestController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('request.regular', {
url: '/regular',
templateUrl: 'request/regular/regular-request.html',
controller: 'regularListController'
})
.state('request.fixed', {
url: '/fixed',
templateUrl: 'request/fixed/fixed-request.html',
controller: 'fixedListController'
})
.state('request.all', {
url: '/all',
templateUrl: 'request/all/all-request.html',
controller: 'allListController'
})
.state('package', {
url: '/package',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'package/package.html',
controller: 'packageController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('package.local', {
url: '/local',
templateUrl: 'package/local/local-package.html',
controller: 'localPackageController'
})
.state('package.out', {
url: '/out',
templateUrl: 'package/out/out-package.html',
controller: 'outPackageController'
})
.state('package.fix', {
url: '/fix',
templateUrl: 'package/fix/fix-package.html',
controller: 'fixPackageController'
})
.state('vehicle', {
url: '/vehicle',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'vehicle/vehicle.html',
controller: 'vehicleController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('vehicle.own', {
url: '/own',
templateUrl: 'vehicle/own/own-vehicle.html',
controller: 'ownVehicleController'
})
.state('vehicle.other', {
url: '/other',
templateUrl: 'vehicle/other/other-vehicle.html',
controller: 'otherVehicleController'
})
.state('driver', {
url: '/driver',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'driver/driver.html',
controller: 'driverController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('party', {
url: '/party',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'party/party.html',
controller: 'partyController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('party.client', {
url: '/client',
templateUrl: 'party/client/client.html',
controller: 'clientController'
})
.state('party.operator', {
url: '/operator',
templateUrl: 'party/operator/operator.html',
controller: 'operatorController'
})
.state('expense', {
url: '/expense',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'expense/expense.html',
controller: 'expenseController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('expense.vehicle', {
url: '/vehicle',
templateUrl: 'expense/vehicle/vehicle-expense.html',
controller: 'vehicleExpenseController'
})
.state('expense.driver', {
url: '/driver',
templateUrl: 'expense/driver/driver-expense.html',
controller: 'driverExpenseController'
})
.state('payment', {
url: '/payment',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'payment/payment.html',
controller: 'paymentController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('payment.fixed', {
url: '/fixed',
templateUrl: 'payment/fixed/fixed-payment.html',
controller: 'fixedPaymentController'
})
.state('payment.client', {
url: '/client',
templateUrl: 'payment/client/client-payment.html',
controller: 'clientPaymentController'
})
.state('payment.operator', {
url: '/operator',
templateUrl: 'payment/operator/operator-payment.html',
controller: 'operatorPaymentController'
})
.state('payment.indirect', {
url: '/indirect',
templateUrl: 'payment/indirect/indirect-payment.html',
controller: 'indirectPaymentController'
})
.state('payment.driver', {
url: '/driver',
templateUrl: 'payment/driver/driver-payment.html',
controller: 'driverPaymentController'
})
.state('summary', {
url: '/summary',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'summary/summary.html',
controller: 'summaryController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
.state('summary.vehicle', {
url: '/vehicle',
templateUrl: 'summary/vehicle/vehicle-summary.html',
controller: 'vehicleSummaryController'
})
.state('summary.driver', {
url: '/driver',
templateUrl: 'summary/driver/driver-summary.html',
controller: 'driverSummaryController'
})
.state('booking', {
url: '/booking',
views: {
'header': {
templateUrl: 'header/home-header.html',
controller: 'headerController'
},
'page': {
templateUrl: 'booking/booking.html',
controller: 'bookingController'
},
'footer': {
templateUrl: 'footer/footer.html'
}
}
})
}]);
<file_sep>app.controller('bookingModalController',
['$scope', '$rootScope', '$uibModalInstance', 'bookingService', 'messageService', 'record',
function ($scope, $rootScope, $uibModalInstance, bookingService, messageService, record) {
'use strict';
$scope.booking = angular.copy(record.data);
$scope.action = record.action;
if (record.action === 'edit') {
$scope.booking.pickUpDate = new Date($scope.booking.pickUpDate);
$scope.booking.pickUpTime = new Date($scope.booking.pickUpTime);
}
if ($scope.action === 'edit') {
var recordId = $scope.booking._id;
}
$scope.calendar = {
open: false
};
$scope.loading = false;
$scope.hideView = ($scope.action === 'view');
$scope.openCalendar = function () {
$scope.calendar.open = true;
};
$scope.closeModal = function () {
$uibModalInstance.close();
};
$scope.submitRequest = function () {
$scope.loading = true;
if (record.action === 'new') {
bookingService.addBooking($scope.booking).then(function () {
$scope.closeModal();
bookingService.booking = null;
$rootScope.$emit('booking');
messageService.showMessage({
'type': 'success',
'title': 'Booking',
'text': 'New Booking added successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Booking',
'text': 'Booking not added successfully. Please try again.'
});
});
} else {
delete $scope.booking._id;
bookingService.updateBooking(recordId, $scope.booking).then(function () {
$scope.closeModal();
bookingService.booking = null;
$rootScope.$emit('booking');
messageService.showMessage({
'type': 'success',
'title': 'Booking',
'text': 'Booking updated successfully.'
});
}, function (err) {
messageService.showMessage({
'type': 'error',
'title': 'Booking',
'text': 'Booking not updated successfully. Please try again.'
});
});
}
};
}]);
<file_sep>app.controller('ownVehicleController', ['$scope', '$state', '$rootScope', '$uibModal', 'vehicleService', 'messageService', 'gridMap',
function ($scope, $state, $rootScope, $uibModal, vehicleService, messageService, gridMap) {
$scope.data = [];
$scope.gridConfig = gridMap.VEHICLE.OWN;
$scope.loading = true;
var success = function (res) {
$scope.data = res.data[0].data;
if (!vehicleService.vehicle.own) {
vehicleService.vehicle.own = res.data;
}
$scope.loading = false;
},
init = function () {
vehicleService.getVehicle('own').then(success, function () {
$state.go('login');
});
},
vehicleModal = function (action, data) {
$uibModal.open({
templateUrl: 'vehicle/vehicle-modal.html',
controller: 'vehicleModalController',
size: 'lg',
resolve: {
record: function () {
return {
'action': action,
'type': 'own',
'data': data
};
}
}
});
};
$rootScope.$on('ownVehicle', function () {
init();
});
init();
$scope.newVehicle = function () {
vehicleModal('new', {});
};
$scope.view = function (id) {
vehicleModal('view', vehicleService.filterRecord('own', id)[0]);
};
$scope.edit = function (id) {
vehicleModal('edit', vehicleService.filterRecord('own', id)[0]);
};
$scope.delete = function (id) {
messageService.deleteConfirm().result.then(function (data) {
if (data) {
$scope.deleteRecord(id);
}
});
};
$scope.deleteRecord = function (id) {
var vehName = vehicleService.filterRecord('own', id)[0].vehicleName;
vehicleService.deleteVehicle('{"name":"own"}', id).then(function () {
vehicleService.vehicle["own"] = null;
init();
messageService.showMessage({
'type': 'success',
'title': 'Vehicle',
'text': 'Vehicle ' + vehName + ' Deleted successfully.'
});
}, function () {
messageService.showMessage({
'type': 'error',
'title': 'Vehicle',
'text': 'vehicle ' + vehName + ' can not be deleted at this time. Please try again.'
});
});
};
}]);
|
dfa63698c005094e6d8642ac8f29895bffd62866
|
[
"JavaScript",
"Markdown"
] | 31
|
JavaScript
|
santosh2686/desktop
|
42798c76197bfc8d1e4e84ada969e9d885062a13
|
d2687fa9412ff7d2d344455bca09eac96ead1e9d
|
refs/heads/master
|
<repo_name>inmar/actions-dpn-python-version-check<file_sep>/src/main.ts
import * as core from '@actions/core';
import * as exec from '@actions/exec';
import * as requests from 'request-promise-native';
import * as util from 'util';
async function run() {
try {
const pypi_hostname: string = core.getInput("pypi_hostname");
const pypi_username: string = core.getInput("pypi_username");
const pypi_password: string = core.getInput("pypi_password");
const package_name: string = core.getInput("package_name");
const package_directory: string = core.getInput("package_directory");
const use_package_version: string = core.getInput("use_package_version");
var version: string = core.getInput("version");
if (use_package_version == "true") {
var output: string = "";
var setup_py = package_directory.replace(/\/+$/g, '') + '/setup.py'
await exec.exec('python', [setup_py, '--version'], {
listeners: {
stdout: (data: Buffer) => {
output += data.toString();
}
}
});
version = output.trim();
core.info(`Using version from ${setup_py}: ${version}`);
}
if (!version) {
throw new Error("Must specify version or use_package_version");
}
const request_options = {
auth: {user: pypi_username, password: <PASSWORD>},
json: true
};
const url: string = `https://${pypi_hostname}/api/package/${package_name}/`;
core.debug(`Fetching url: ${url}`);
const resp = await requests.get(url, request_options);
core.debug(`Response: ${JSON.stringify(resp)}`);
for (const existing_package of resp.packages) {
const existing_version: string = existing_package.version;
core.debug(`Existing package: ${JSON.stringify(existing_package)}`);
core.debug(`Existing version: ${existing_version}`);
if (existing_version === version) {
throw new Error("Version already exists in package server");
}
core.debug(`No match: ${util.inspect(existing_version)} vs ${util.inspect(version)}`);
}
} catch (error) {
core.setFailed(error.message);
}
}
run();
<file_sep>/lib/main.js
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __importStar = (this && this.__importStar) || function (mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) for (var k in mod) if (Object.hasOwnProperty.call(mod, k)) result[k] = mod[k];
result["default"] = mod;
return result;
}
Object.defineProperty(exports, "__esModule", { value: true });
const core = __importStar(require("@actions/core"));
const exec = __importStar(require("@actions/exec"));
const requests = __importStar(require("request-promise-native"));
const util = __importStar(require("util"));
function run() {
return __awaiter(this, void 0, void 0, function* () {
try {
const pypi_hostname = core.getInput("pypi_hostname");
const pypi_username = core.getInput("pypi_username");
const pypi_password = core.getInput("pypi_password");
const package_name = core.getInput("package_name");
const package_directory = core.getInput("package_directory");
const use_package_version = core.getInput("use_package_version");
var version = core.getInput("version");
if (use_package_version == "true") {
var output = "";
var setup_py = package_directory.replace(/\/+$/g, '') + '/setup.py';
yield exec.exec('python', [setup_py, '--version'], {
listeners: {
stdout: (data) => {
output += data.toString();
}
}
});
version = output.trim();
core.info(`Using version from ${setup_py}: ${version}`);
}
if (!version) {
throw new Error("Must specify version or use_package_version");
}
const request_options = {
auth: { user: pypi_username, password: <PASSWORD> },
json: true
};
const url = `https://${pypi_hostname}/api/package/${package_name}/`;
core.debug(`Fetching url: ${url}`);
const resp = yield requests.get(url, request_options);
core.debug(`Response: ${JSON.stringify(resp)}`);
for (const existing_package of resp.packages) {
const existing_version = existing_package.version;
core.debug(`Existing package: ${JSON.stringify(existing_package)}`);
core.debug(`Existing version: ${existing_version}`);
if (existing_version === version) {
throw new Error("Version already exists in package server");
}
core.debug(`No match: ${util.inspect(existing_version)} vs ${util.inspect(version)}`);
}
}
catch (error) {
core.setFailed(error.message);
}
});
}
run();
|
a85f3be7c8f89fd121f6a48db9cf2488c4c82590
|
[
"JavaScript",
"TypeScript"
] | 2
|
TypeScript
|
inmar/actions-dpn-python-version-check
|
30376e9b92466f0782a47e1dd589b9d7367d2a14
|
a7c5e465cf955e7eaee9aa8c591f6264ff8c8e2c
|
refs/heads/main
|
<file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.viewModel
import android.os.Handler
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import kotlin.random.Random
class MyViewModel : ViewModel() {
var aa by mutableStateOf(0)
var s1 by mutableStateOf(0)
var s2 by mutableStateOf(0)
var m1 by mutableStateOf(0)
var m2 by mutableStateOf(0)
lateinit var handler: Handler
lateinit var runss: Runnable
var isRun by mutableStateOf(false)
fun start() {
val ss = Random.nextInt(1000, 2599)
// val ss = 10
aa = 0
isRun = true
handler = Handler()
runss = Runnable {
aa++
val time = ss - aa
if (time < 0) {
isRun = false
return@Runnable
}
val s = time / 60
val m = time - s * 60
if (s.toString().length == 1) {
s1 = 0
s2 = s
} else {
s1 = s / 10
s2 = s % 10
}
if (m.toString().length == 1) {
m1 = 0
m2 = m
} else {
m1 = m / 10
m2 = m % 10
}
Log.d(
"66881010",
"aa = $aa time = $time s1 = $s1 s2 = $s2 m1 = $m1 m2 = $m2"
)
handler.postDelayed(runss, 1000)
}
handler.postDelayed(runss, 1000)
}
}
<file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge
import android.os.Bundle
import android.view.WindowManager
import androidx.activity.compose.setContent
import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.material.FabPosition
import androidx.compose.material.FloatingActionButton
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Scaffold
import androidx.compose.material.Surface
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.androiddevchallenge.data.num
import com.example.androiddevchallenge.ui.theme.MyTheme
import com.example.androiddevchallenge.utils.DarkModeUtils
import com.example.androiddevchallenge.utils.StatusBarUtils
import com.example.androiddevchallenge.view.CountdownView
import com.example.androiddevchallenge.viewModel.MyViewModel
class MainActivity : AppCompatActivity() {
val viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
getWindow().setFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN
)
val isDark = DarkModeUtils.isDarkMode(this)
StatusBarUtils.initStatusBar(this, null, isDark)
setContent {
MyTheme {
MyApp()
}
}
}
}
// Start building your app here!
@Composable
fun MyApp() {
val viewModel: MyViewModel = viewModel()
Surface(color = MaterialTheme.colors.background) {
Scaffold(
floatingActionButton = {
FloatingActionButton(
onClick = { viewModel.start() },
backgroundColor = Color(0xff2ea3e4)
) {
Text(
text = "RUN",
color = Color.White,
fontSize = 20.sp,
fontWeight = FontWeight.Bold
)
}
},
floatingActionButtonPosition = FabPosition.End,
content = {
Box(
// #2ea3e4
modifier = Modifier
.fillMaxSize()
.background(Color(0xff2b6d8c)),
contentAlignment = Alignment.Center
) {
var size = 35.dp
Column(
horizontalAlignment = Alignment.CenterHorizontally,
content = {
Row() {
// num[viewModel.aa % 10]
CountdownView(numss = num[viewModel.s1], size = size)
CountdownView(numss = num[viewModel.s2], size = size)
CountdownView(numss = num[10], size = size)
CountdownView(numss = num[viewModel.m1], size = size)
CountdownView(numss = num[viewModel.m2], size = size)
}
}
)
}
}
)
}
}
@Preview("Light Theme", widthDp = 360, heightDp = 640)
@Composable
fun LightPreview() {
MyTheme {
MyApp()
}
}
@Preview("Dark Theme", widthDp = 360, heightDp = 640)
@Composable
fun DarkPreview() {
MyTheme(darkTheme = true) {
MyApp()
}
}
<file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.data
import androidx.compose.ui.graphics.Color
/**
* 用来显示点阵的三维数组
*/
val digit = arrayOf(
arrayOf(
arrayOf(0, 0, 1, 1, 1, 0, 0),
arrayOf(0, 1, 1, 0, 1, 1, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 0, 1, 1, 0),
arrayOf(0, 0, 1, 1, 1, 0, 0)
),
arrayOf(
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 1, 1, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(1, 1, 1, 1, 1, 1, 1)
),
arrayOf(
arrayOf(0, 1, 1, 1, 1, 1, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 1, 1, 0, 0, 0),
arrayOf(0, 1, 1, 0, 0, 0, 0),
arrayOf(1, 1, 0, 0, 0, 0, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 1, 1, 1, 1, 1)
),
arrayOf(
arrayOf(1, 1, 1, 1, 1, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 1, 1, 1, 0, 0),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 1, 1, 1, 0)
),
arrayOf(
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 1, 1, 1, 0),
arrayOf(0, 0, 1, 1, 1, 1, 0),
arrayOf(0, 1, 1, 0, 1, 1, 0),
arrayOf(1, 1, 0, 0, 1, 1, 0),
arrayOf(1, 1, 1, 1, 1, 1, 1),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 1, 1, 1, 1)
),
arrayOf(
arrayOf(1, 1, 1, 1, 1, 1, 1),
arrayOf(1, 1, 0, 0, 0, 0, 0),
arrayOf(1, 1, 0, 0, 0, 0, 0),
arrayOf(1, 1, 1, 1, 1, 1, 0),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 1, 1, 1, 0)
),
arrayOf(
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 1, 1, 0, 0, 0),
arrayOf(0, 1, 1, 0, 0, 0, 0),
arrayOf(1, 1, 0, 0, 0, 0, 0),
arrayOf(1, 1, 0, 1, 1, 1, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 1, 1, 1, 0)
),
arrayOf(
arrayOf(1, 1, 1, 1, 1, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 0, 1, 1, 0, 0, 0),
arrayOf(0, 0, 1, 1, 0, 0, 0),
arrayOf(0, 0, 1, 1, 0, 0, 0),
arrayOf(0, 0, 1, 1, 0, 0, 0)
),
arrayOf(
arrayOf(0, 1, 1, 1, 1, 1, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 1, 1, 1, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 1, 1, 1, 0)
),
arrayOf(
arrayOf(0, 1, 1, 1, 1, 1, 0),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(1, 1, 0, 0, 0, 1, 1),
arrayOf(0, 1, 1, 1, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 0, 1, 1),
arrayOf(0, 0, 0, 0, 1, 1, 0),
arrayOf(0, 0, 0, 1, 1, 0, 0),
arrayOf(0, 1, 1, 0, 0, 0, 0)
),
arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 1, 1, 0),
arrayOf(0, 1, 1, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 1, 1, 0),
arrayOf(0, 1, 1, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0)
)
)
val num = arrayOf(
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 1, 0, 0),
arrayOf(0, 1, 0, 0),
arrayOf(0, 1, 0, 0),
arrayOf(0, 1, 0, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 0, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(1, 1, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 0, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 1, 1, 1),
arrayOf(0, 0, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 0, 0),
arrayOf(1, 1, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 0, 0),
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(0, 0, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 1, 1, 0),
),
arrayOf(
arrayOf(1, 1, 1, 0),
arrayOf(1, 0, 1, 0),
arrayOf(1, 1, 1, 0),
arrayOf(0, 0, 1, 0),
arrayOf(0, 0, 1, 0),
),
arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 1, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 1, 0, 0),
arrayOf(0, 0, 0, 0),
),
)
val init = arrayOf(
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
arrayOf(0, 0, 0, 0),
)
val ColorSer = arrayOf(
Color.Yellow,
Color(0xffee7600),
Color(0xffee82ee),
Color.Red,
Color(0xffEE9A00),
Color(0xffff00ff),
Color(0xffffd700),
Color(0xffff0000),
Color(0xffa020f0),
Color(0xffab82ff),
Color(0xff9aff9a),
Color(0xff7fffd4),
Color(0xff00f5ff),
Color.Magenta
)
<file_sep>/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.androiddevchallenge.view
import android.util.Log
import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.Spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.animation.core.spring
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Color.Companion.White
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.unit.Dp
import androidx.lifecycle.viewmodel.compose.viewModel
import com.example.androiddevchallenge.viewModel.MyViewModel
@Composable
fun CountdownView(modifier: Modifier = Modifier, numss: Array<Array<Int>>, size: Dp) {
val viewModel: MyViewModel = viewModel()
var blue by remember { mutableStateOf(true) }
val color1 by animateColorAsState(
White,
animationSpec = spring(Spring.StiffnessVeryLow, 500000f),
)
val color2 by animateColorAsState(
Color(0xff2b6d8c),
animationSpec = spring(Spring.StiffnessVeryLow, 500000f),
)
val rotation by animateFloatAsState(
if (blue) 89.5f else 0f,
animationSpec = spring(25f, 1000000f),
finishedListener = {
if (viewModel.isRun == false) {
}
blue = !blue
}
)
val rotation1 by animateFloatAsState(
targetValue = 0f,
animationSpec = spring(Spring.StiffnessVeryLow, 1000000f),
)
val rotation2 by animateFloatAsState(
targetValue = 89f,
animationSpec = spring(Spring.StiffnessVeryLow, 1000000f),
)
return LazyColumn {
itemsIndexed(numss) { itemPosition, row ->
LazyRow {
itemsIndexed(row) { position, data ->
Log.d("6688", "item $itemPosition posttion $position")
Box(
modifier = Modifier
.graphicsLayer(
// rotationX = if(!viewModel.isRun) 89f else (if (num[viewModel.aa % 10][itemPosition][position] == 1) rotation1 else rotation2),
rotationX = if (viewModel.isRun) rotation else 0f
)
.width(size)
.height(size)
.padding(size / 10)
// .background(Color.White)
// .background(if (!viewModel.isRun) Color.White else (if(blue) color2 else (if (num[viewModel.aa % 10][itemPosition][position] == 1) color1 else color2)))
.background(if (!viewModel.isRun) Color.White else (if (numss[itemPosition][position] == 1) color1 else color2))
)
}
}
}
}
}
|
7b1d485311188f923daca09385dc747d0d551770
|
[
"Kotlin"
] | 4
|
Kotlin
|
senlin175/Countdown
|
e85d490966b5c2a3104ac37c9ab094d32114bb7f
|
765d302f96fb05de14bb71d4bb36cbf482ed6b86
|
refs/heads/master
|
<repo_name>tbs1980/SplineBenchmarks<file_sep>/cmake/FindEinspline.cmake
# - Find the Einspline library
#
# Usage:
# find_package(Einspline [REQUIRED] [QUIET] )
#
# It sets the following variables:
# EINSPLINE_FOUND ... true if Einspline is found on the system
# EINSPLINE_LIBRARIES ... full path to Einspline library
# EINSPLINE_INCLUDES ... Einspline include directory
#
# The following variables will be checked by the function
# EINSPLINE_USE_STATIC_LIBS ... if true, only static libraries are found
# EINSPLINE_ROOT ... if set, the libraries are exclusively searched
# under this path
# EINSPLINE_LIBRARY ... Einspline library to use
# EINSPLINE_INCLUDE_DIR ... Einspline include directory
#
#If environment variable EINSPLINEWDIR is specified, it has same effect as EINSPLINE_ROOT
if( NOT EINSPLINE_ROOT AND ENV{EINSPLINEDIR} )
set( EINSPLINE_ROOT $ENV{EINSPLINEDIR} )
endif()
# Check if we can use PkgConfig
find_package(PkgConfig)
#Determine from PKG
if( PKG_CONFIG_FOUND AND NOT EINSPLINE_ROOT )
pkg_check_modules( PKG_EINSPLINE QUIET "einspline" )
endif()
#Check whether to search static or dynamic libs
set( CMAKE_FIND_LIBRARY_SUFFIXES_SAV ${CMAKE_FIND_LIBRARY_SUFFIXES} )
if( ${EINSPLINE_USE_STATIC_LIBS} )
set( CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_STATIC_LIBRARY_SUFFIX} )
else()
set( CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_SHARED_LIBRARY_SUFFIX} )
endif()
if( EINSPLINE_ROOT )
#find libs
find_library( EINSPLINE_LIB NAMES "einspline" PATHS ${EINSPLINE_ROOT} PATH_SUFFIXES "lib" "lib64" NO_DEFAULT_PATH )
#find includes , only check one header for now
find_path( EINSPLINE_INCLUDES NAMES "bspline_base.h" PATHS ${EINSPLINE_ROOT} PATH_SUFFIXES "include/einspline" NO_DEFAULT_PATH )
else (EINSPLINE_ROOT)
find_library( EINSPLINE_LIB NAMES "einspline" PATHS ${PKG_EINSPLINE_LIBRARY_DIRS} ${LIB_INSTALL_DIR} )
find_path( EINSPLINE_INCLUDES NAMES "bspline_base.h" PATHS ${PKG_EINSPLINE_INCLUDE_DIRS} ${INCLUDE_INSTALL_DIR} )
endif(EINSPLINE_ROOT)
set(EINSPLINE_LIBRARIES ${EINSPLINE_LIB})
set( CMAKE_FIND_LIBRARY_SUFFIXES ${CMAKE_FIND_LIBRARY_SUFFIXES_SAV} )
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(EINSPLINE DEFAULT_MSG EINSPLINE_INCLUDES EINSPLINE_LIBRARIES)
mark_as_advanced(EINSPLINE_INCLUDES EINSPLINE_LIBRARIES)
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 2.8)
# guard against in-source builds (got this from Eigen)
if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR})
message(FATAL_ERROR "In-source builds not allowed. Please make a new directory (called a build dir
ectory) and run CMake from there. You may need to remove CMakeCache.txt. ")
endif()
#add the customised package searches to the module path
set(CMAKE_MODULE_PATH ${PROJECT_SOURCE_DIR}/cmake)
find_package(GSL REQUIRED)
find_package(Eigen3 REQUIRED)
#find_package(FFTW3 REQUIRED)
#find_package(Einspline REQUIRED)
find_package(Splinter REQUIRED)
if(CMAKE_COMPILER_IS_GNUCXX )
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -pedantic -Wall -Wextra -Wfatal-errors")
endif()
if(GSL_FOUND)
include_directories(${GSL_INCLUDE_DIRS})
add_executable(gslSpline gslSpline.cpp)
target_link_libraries(gslSpline ${GSL_LIBRARIES})
endif(GSL_FOUND)
if(EIGEN3_FOUND)
include_directories(${EIGEN3_INCLUDE_DIR})
add_executable(eigenSpline eigenSpline.cpp)
endif(EIGEN3_FOUND)
#if(Einspline_FOUND and FFTW_FOUND)
#include_directories(${FFTW_INCLUDES})
#include_directories(${EINSPLINE_INCLUDES})
# add_executable(einsplineSpline einsplineSpline.cpp)
# target_link_libraries(einsplineSpline ${EINSPLINE_LIBRARIES} ${FFTW_LIBRARIES})
#endif(Einspline_FOUND and FFTW3_FOUND)
if(Splinter_FOUND)
include_directories(${EIGEN3_INCLUDE_DIR})
include_directories(${Splinter_INCLUDE_DIR})
set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11")
add_executable(splinterSpline splinterSpline.cpp)
target_link_libraries(splinterSpline ${Splinter_LIBRARIES})
endif(Splinter_FOUND)
<file_sep>/cmake/FindSplinter.cmake
# https://github.com/bgrimstad/splinter
#
# Splinter_ROOT root search path
# Splinter_INCLUDE_DIR inlcude directories
# Splinter_LIBRARIES libraries
#
find_path(Splinter_INCLUDE_DIR NAMES datatable.h PATHS ${Splinter_ROOT}/include/SPLINTER)
find_library(Splinter_LIBRARIES NAMES splinter-2-0 PATHS ${Splinter_ROOT}/lib ${Splinter_ROOT}/lib64)
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(Splinter DEFAULT_MSG
Splinter_INCLUDE_DIR Splinter_LIBRARIES)
mark_as_advanced(Splinter_INCLUDE_DIR Splinter_LIBRARIES)
<file_sep>/eigenSpline.cpp
#include <cmath>
#include <iostream>
#include <algorithm>
#include <cassert>
#include <fstream>
#include <Eigen/Core>
#include <unsupported/Eigen/Splines>
// define helpers to scale X values down to [0, 1]
struct scaledValue
{
scaledValue(double const xMin,double const xMax)
:mXMin(xMin),mXMax(xMax)
{
assert(mXMax > mXMin);
}
const double operator()(double const x) const
{
return (x - mXMin) / (mXMax - mXMin);
}
double mXMin,mXMax;
};
Eigen::RowVectorXd scaledValues(Eigen::VectorXd const& x)
{
return x.unaryExpr(scaledValue(x.minCoeff(),x.maxCoeff())).transpose();
}
void testSine()
{
typedef Eigen::Spline<double,1> Spline1d;
// create data
const size_t numData = 1000;
Eigen::VectorXd x(numData);
Eigen::VectorXd y(numData);
const double a = 0;
const double b = 4*M_PI;
const double dx = (b-a)/double(numData);
for(size_t i=0;i<numData;++i)
{
x(i) = a + i*dx;
y(i) = std::sin(x(i));
}
// create a spline
Spline1d spline(
Eigen::SplineFitting<Spline1d>::Interpolate(y.transpose(),
std::min<int>(x.rows() - 1, 3),scaledValues(x))
);
std::ofstream outFile;
outFile.open("eigenSplinePlot.dat",std::ios::trunc);
for(size_t i=0;i<numData;++i)
{
double xiSc = scaledValue(x.minCoeff(),x.maxCoeff())(x(i));
double yiSpl = spline(xiSc)(0);
outFile<<x(i)<<"\t"<<y(i)<<"\t"<<yiSpl<<std::endl;
}
outFile.close();
}
int main(void)
{
testSine();
return 0;
}
<file_sep>/einsplineSpline.cpp
#include <cmath>
#include <cassert>
#include <fstream>
#include <nubspline.h>
void testSine()
{
// crete data
const size_t numData = 1000;
const double a = 0;
const double b = 4*M_PI;
const double dx = (b-a)/double(numData);
double *p_x = new double[numData];
double *p_y = new double[numData];
for(size_t i=0;i<numData;++i)
{
p_x[i] = a + i*dx;
p_y[i] = std::sin(p_x[i]);
}
// create spline
NUgrid* p_grid = create_general_grid(p_x,numData);
BCtype_d bc;
bc.lCode = NATURAL;
bc.rCode = NATURAL;
NUBspline_1d_d* p_spline =(NUBspline_1d_d*) create_NUBspline_1d_d (p_grid, bc,p_y);
std::ofstream outFile;
outFile.open("einsplineSplinePlot.dat",std::ios::trunc);
for(size_t i=0;i<numData;++i)
{
double yiSpl ;
eval_NUBspline_1d_d(p_spline,p_x[i],&yiSpl);
outFile<<p_x[i]<<"\t"<<p_y[i]<<"\t"<<yiSpl<<std::endl;
}
outFile.close();
// free memory
delete[] p_x;
delete[] p_y;
if(p_grid != NULL) destroy_grid (p_grid);
if(p_spline != NULL) destroy_Bspline (p_spline);
}
int main(void)
{
testSine();
return 0;
}
<file_sep>/splinterSpline.cpp
#include <iostream>
#include <cmath>
#include <fstream>
// https://github.com/bgrimstad/splinter
#include "datatable.h"
#include "bsplineapproximant.h"
int main(void)
{
// Create new DataTable to manage samples
SPLINTER::DataTable samples;
// Sample the function
SPLINTER::DenseVector x(1);
const int numData = 1000;
const double a = 0;
const double b = 4*M_PI;
const double dx = (b-a)/double(numData);
for(int i = 0; i < 1000; i++)
{
x(0) = a + i*dx;
double y = std::sin(x(0));
// Store sample
samples.addSample(x,y);
}
// Build B-splines that interpolate the samples
SPLINTER::BSplineApproximant bspline3(samples, SPLINTER::BSplineType::CUBIC);
std::ofstream outFile;
outFile.open("splinterSplinePlot.dat",std::ios::trunc);
for(int i=0;i<numData;++i)
{
x(0) = a + i*dx;
double yiSpl = bspline3.eval(x);
outFile<<x(0)<<"\t"<<std::sin(x(0))<<"\t"<<yiSpl<<std::endl;
}
outFile.close();
return 0;
}
<file_sep>/plotGSLSpline.py
import numpy as np
import matplotlib.pyplot as plt
data = np.loadtxt("./gslSplinePlot.dat")
plt.plot(data[:,0],data[:,1],'b+',label="data")
plt.plot(data[:,0],data[:,2],'r-',label="spline")
plt.legend(loc=0)
plt.savefig("./gslSplinePlot.png")
<file_sep>/cmake/FindGSL.cmake
# Find gnu scientific library GSL (http://www.gnu.org/software/gsl/)
#
# Usage:
# find_package(GSL [REQUIRED] [QUIET] )
#
# Search path variable:
# GSL_ROOT
#
# Once run this will define:
#
# GSL_FOUND = system has GSL lib
# GSL_LIBRARIES = full path to the libraries
# GSL_INCLUDE_DIRS = full path to the header files
#
find_library(GSL_LIBRARY NAMES gsl HINTS /usr /usr/local PATHS ${GSL_ROOT} /usr /usr/local PATH_SUFFIXES lib lib64 DOC "GSL library")
find_library(GSL_CBLAS_LIBRARY NAMES gslcblas HINTS /usr /usr/local PATHS ${GSL_ROOT} /usr /usr/local PATH_SUFFIXES lib lib64 DOC "GSL cblas library")
find_path(GSL_INCLUDE_DIR NAMES gsl/gsl_version.h HINTS /usr /usr/local PATHS ${GSL_ROOT} /usr /usr/local PATH_SUFFIXES include DOC "GSL headers")
set(GSL_LIBRARIES ${GSL_LIBRARY} ${GSL_CBLAS_LIBRARY})
set(GSL_INCLUDE_DIRS ${GSL_INCLUDE_DIR} )
include(FindPackageHandleStandardArgs)
find_package_handle_standard_args(GSL DEFAULT_MSG GSL_LIBRARIES GSL_INCLUDE_DIRS)
mark_as_advanced(GSL_LIBRARIES GSL_INCLUDE_DIRS)
<file_sep>/gslSpline.cpp
#include <cassert>
#include <cmath>
#include <iostream>
#include <fstream>
#include <gsl/gsl_bspline.h>
#include <gsl/gsl_multifit.h>
#include <gsl/gsl_vector.h>
#include <gsl/gsl_rng.h>
#include <gsl/gsl_randist.h>
void testSine()
{
const size_t order = 4;
const size_t numData = 1000;
const size_t numCoeffs = 12;
const size_t numBreaks = numCoeffs + 2 - order;
assert(numCoeffs > order);
assert(numData > 2);
// allocate a cubic bspline workspace
gsl_bspline_workspace *p_bw = gsl_bspline_alloc(order, numBreaks);
gsl_vector *p_B = gsl_vector_alloc(numCoeffs);
gsl_matrix *p_X = gsl_matrix_alloc(numData, numCoeffs);
gsl_matrix *p_cov = gsl_matrix_alloc(numCoeffs, numCoeffs);
gsl_multifit_linear_workspace *p_mw = gsl_multifit_linear_alloc(numData, numCoeffs);
gsl_vector *p_c = gsl_vector_alloc(numCoeffs);
// create data to be fitted
gsl_vector *p_x, *p_y;
gsl_vector *p_w;
gsl_vector *p_x_test, *p_y_test;
gsl_rng *p_r;
p_x = gsl_vector_alloc(numData);
p_y = gsl_vector_alloc(numData);
p_w = gsl_vector_alloc(numData);
p_x_test = gsl_vector_alloc(numData);
p_y_test = gsl_vector_alloc(numData);
gsl_rng_env_setup();
p_r = gsl_rng_alloc(gsl_rng_default);
const double a = 0;
const double b = 4*M_PI;
const double dx = (b-a)/double(numData-1);
const double sigma = 1e-2;
for (size_t i = 0; i < numData; ++i)
{
double xi = a + i*dx;
double yi = std::sin(xi);
double dy = gsl_ran_gaussian(p_r, sigma);
yi += dy;
gsl_vector_set(p_x, i, xi);
gsl_vector_set(p_y, i, yi);
gsl_vector_set(p_w, i, 1. / (sigma * sigma));
}
// use uniform breakpoints on [0,4*M_PI]
gsl_bspline_knots_uniform(a, b, p_bw);
// construct the fit matrix
assert(p_x->size == p_y->size);
for(size_t i=0;i< p_x->size;++i)
{
double xi = gsl_vector_get(p_x, i);
// compute B_j(xi) for all j
gsl_bspline_eval(xi, p_B, p_bw);
// fill in row i of X
for (size_t j = 0; j < numCoeffs; ++j)
{
double Bj = gsl_vector_get(p_B, j);
gsl_matrix_set(p_X, i, j, Bj);
}
}
// do the fit
double chisq;
gsl_multifit_wlinear(p_X, p_w, p_y, p_c, p_cov, &chisq, p_mw);
// output the smoothed curve
std::ofstream outFile;
outFile.open("gslSplinePlot.dat",std::ios::trunc);
for (size_t i = 0; i < numData; ++i)
{
double xi = gsl_vector_get(p_x, i);
gsl_bspline_eval(xi, p_B, p_bw);
double yerr,yspl;
gsl_multifit_linear_est(p_B, p_c, p_cov, &yspl, &yerr);
double yi = gsl_vector_get(p_y, i);
outFile<<xi<<"\t"<<yi<<"\t"<<yspl<<std::endl;
}
outFile.close();
// free memory
gsl_bspline_free(p_bw);
gsl_vector_free(p_B);
gsl_matrix_free(p_X);
gsl_matrix_free(p_cov);
gsl_multifit_linear_free(p_mw);
gsl_vector_free(p_c);
gsl_vector_free(p_x);
gsl_vector_free(p_y);
gsl_vector_free(p_w);
gsl_vector_free(p_x_test);
gsl_vector_free(p_y_test);
gsl_rng_free(p_r);
}
int main(void)
{
testSine();
return 0;
}
<file_sep>/README.md
# SplineBenchmarks
Benchmarking publicly available spline libraries
|
84c871b29bfe8113e03cab69b6b8f1dc3da65062
|
[
"Markdown",
"Python",
"CMake",
"C++"
] | 10
|
CMake
|
tbs1980/SplineBenchmarks
|
45933f28b901a43464d3f9dfb6c545b50d85a652
|
a4b9aa46da0ddbb04d7e04edc39a8a190cfcbcbf
|
refs/heads/master
|
<file_sep>/*
Compressed ISO9660 conveter by BOOSTER
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <zlib.h>
#include <c_console.h>
#include "ciso.h"
#include "stdafx.h"
#pragma comment( lib , "libz_stub_weak.a" )
const char *fname_in, *fname_out;
FILE *fin, *fout;
z_stream z;
unsigned int *index_buf = NULL;
unsigned int *crc_buf = NULL;
unsigned char *block_buf1 = NULL;
unsigned char *block_buf2 = NULL;
/****************************************************************************
compress ISO to CSO
****************************************************************************/
CISO_H ciso;
int ciso_total_block;
unsigned long check_file_size(FILE *fp) {
unsigned long pos;
if (fseek(fp, 0, SEEK_END) < 0)
return -1;
pos = ftell(fp);
if (pos == -1) return pos;
// init ciso header
memset(&ciso, 0, sizeof(ciso));
ciso.magic[0] = 'C';
ciso.magic[1] = 'I';
ciso.magic[2] = 'S';
ciso.magic[3] = 'O';
ciso.ver = 0x01;
ciso.block_size = 0x800; /* ISO9660 one of sector */
ciso.total_bytes = pos;
#if 0
/* align >0 has bug */
for (ciso.align = 0; (ciso.total_bytes >> ciso.align) >0x80000000LL; ciso.align++);
#endif
ciso_total_block = pos / ciso.block_size;
fseek(fp, 0, SEEK_SET);
return pos;
}
/****************************************************************************
decompress CSO to ISO
****************************************************************************/
int decomp_ciso(void) {
//unsigned long long file_size;
unsigned int index, index2;
unsigned long read_pos, read_size;
//int total_sectors;
int index_size;
int block;
//unsigned char buf4[4];
int cmp_size;
int status;
int percent_period;
int percent_cnt;
int plain;
// read header
if (fread(&ciso, 1, sizeof(ciso), fin) != sizeof(ciso)) {
WriteLine("file read error\n");
return 1;
}
// check header
if (
ciso.magic[0] != 'C' ||
ciso.magic[1] != 'I' ||
ciso.magic[2] != 'S' ||
ciso.magic[3] != 'O' ||
ciso.block_size == 0 ||
ciso.total_bytes == 0
) {
WriteLine("ciso file format error\n");
return 1;
}
// Calcualte ciso Total blocks.
ciso_total_block = ciso.total_bytes / ciso.block_size;
// allocate index block
index_size = (ciso_total_block + 1) * sizeof(unsigned long);
index_buf = (unsigned int *)malloc(index_size);
block_buf1 = (unsigned char *)malloc(ciso.block_size);
block_buf2 = (unsigned char *)malloc(ciso.block_size * 2);
if (!index_buf || !block_buf1 || !block_buf2) {
WriteLine("Can't allocate memory\n");
return 1;
}
memset(index_buf, 0, index_size);
// read index block
if (fread(index_buf, 1, index_size, fin) != index_size) {
WriteLine("file read error\n");
return 1;
}
// show info
WriteLine("Decompress '%s' to '%s'\n", fname_in, fname_out);
WriteLine("Total File Size %ld bytes\n", ciso.total_bytes);
WriteLine("block size %d bytes\n", ciso.block_size);
WriteLine("total blocks %d blocks\n", ciso_total_block);
WriteLine("index align %d\n", 1 << ciso.align);
// init zlib
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
// decompress data
percent_period = ciso_total_block / 100;
percent_cnt = 0;
for (block = 0; block < ciso_total_block; block++) {
if (--percent_cnt <= 0) {
percent_cnt = percent_period;
WriteLine("decompress %d%%\r", block / percent_period);
}
if (inflateInit2(&z, -15) != Z_OK) {
WriteLine("deflateInit : %s\n", (z.msg) ? z.msg : "???");
return 1;
}
// check index
index = index_buf[block];
plain = index & 0x80000000;
index &= 0x7fffffff;
read_pos = index << (ciso.align);
//WriteLine("Index : %d\nPlain : %d\nRead Position : %ld\n", index, plain, read_pos);
if (plain) {
read_size = ciso.block_size;
} else {
index2 = index_buf[block + 1] & 0x7fffffff;
read_size = (index2 - index) << (ciso.align);
}
fseek(fin, read_pos, SEEK_SET);
z.avail_in = fread(block_buf2, 1, read_size, fin);
if (z.avail_in != read_size) {
WriteLine("block=%d : read error\n", block);
return 1;
}
if (plain) {
memcpy(block_buf1, block_buf2, read_size);
cmp_size = read_size;
} else {
z.next_out = block_buf1;
z.avail_out = ciso.block_size;
z.next_in = block_buf2;
status = inflate(&z, Z_FULL_FLUSH);
if (status != Z_STREAM_END) {
WriteLine("block %d:inflate : %s[%d]\n", block, (z.msg) ? z.msg : "error", status);
return 1;
}
cmp_size = ciso.block_size - z.avail_out;
if (cmp_size != ciso.block_size) {
WriteLine("block %d : block size error %d != %d\n", block, cmp_size, ciso.block_size);
return 1;
}
}
// write decompressed block
if (fwrite(block_buf1, 1, cmp_size, fout) != cmp_size) {
WriteLine("block %d : Write error\n", block);
return 1;
}
// term zlib
if (inflateEnd(&z) != Z_OK) {
WriteLine("inflateEnd : %s\n", (z.msg) ? z.msg : "error");
return 1;
}
}
WriteLine("ciso decompress completed\n");
return 0;
}
/****************************************************************************
compress ISO
****************************************************************************/
int comp_ciso(int level) {
unsigned long file_size;
unsigned long write_pos;
//int total_sectors;
int index_size;
int block;
unsigned char buf4[64];
int cmp_size;
int status;
int percent_period;
int percent_cnt;
int align, align_b, align_m;
file_size = check_file_size(fin);
if (file_size == 0) {
WriteLine("Can't get file size\n");
return 1;
}
// allocate index block
index_size = (ciso_total_block + 1) * sizeof(unsigned long);
index_buf = (unsigned int *)malloc(index_size);
crc_buf = (unsigned int *)malloc(index_size);
block_buf1 = (unsigned char *)malloc(ciso.block_size);
block_buf2 = (unsigned char *)malloc(ciso.block_size * 2);
if (!index_buf || !crc_buf || !block_buf1 || !block_buf2) {
WriteLine("Can't allocate memory\n");
return 1;
}
memset(index_buf, 0, index_size);
memset(crc_buf, 0, index_size);
memset(buf4, 0, sizeof(buf4));
// init zlib
z.zalloc = Z_NULL;
z.zfree = Z_NULL;
z.opaque = Z_NULL;
// show info
WriteLine("Compress '%s' to '%s'\n", fname_in, fname_out);
WriteLine("Total File Size %ld bytes\n", ciso.total_bytes);
WriteLine("block size %d bytes\n", ciso.block_size);
WriteLine("index align %d\n", 1 << ciso.align);
WriteLine("compress level %d\n", level);
// write header block
fwrite(&ciso, 1, sizeof(ciso), fout);
// dummy write index block
fwrite(index_buf, 1, index_size, fout);
write_pos = sizeof(ciso) + index_size;
// compress data
percent_period = ciso_total_block / 100;
percent_cnt = ciso_total_block / 100;
align_b = 1 << (ciso.align);
align_m = align_b - 1;
for (block = 0; block < ciso_total_block; block++) {
if (--percent_cnt <= 0) {
percent_cnt = percent_period;
WriteLine("compress %3d%% avarage rate %3d%%\r"
, block / percent_period
, block == 0 ? 0 : 100 * write_pos / (block * 0x800));
}
if (deflateInit2(&z, level, Z_DEFLATED, -15, 8, Z_DEFAULT_STRATEGY) != Z_OK) {
WriteLine("deflateInit : %s\n", (z.msg) ? z.msg : "???");
return 1;
}
// write align
align = (int)write_pos & align_m;
if (align) {
align = align_b - align;
if (fwrite(buf4, 1, align, fout) != align) {
WriteLine("block %d : Write error\n", block);
return 1;
}
write_pos += align;
}
// mark offset index
index_buf[block] = write_pos >> (ciso.align);
// read buffer
z.next_out = block_buf2;
z.avail_out = ciso.block_size * 2;
z.next_in = block_buf1;
z.avail_in = fread(block_buf1, 1, ciso.block_size, fin);
if (z.avail_in != ciso.block_size) {
WriteLine("block=%d : read error\n", block);
return 1;
}
// compress block
// status = deflate(&z, Z_FULL_FLUSH);
status = deflate(&z, Z_FINISH);
if (status != Z_STREAM_END) {
WriteLine("block %d:deflate : %s[%d]\n", block, (z.msg) ? z.msg : "error", status);
return 1;
}
cmp_size = ciso.block_size * 2 - z.avail_out;
// choise plain / compress
if (cmp_size >= ciso.block_size) {
cmp_size = ciso.block_size;
memcpy(block_buf2, block_buf1, cmp_size);
// plain block mark
index_buf[block] |= 0x80000000;
}
// write compressed block
if (fwrite(block_buf2, 1, cmp_size, fout) != cmp_size) {
WriteLine("block %d : Write error\n", block);
return 1;
}
// mark next index
write_pos += cmp_size;
// term zlib
if (deflateEnd(&z) != Z_OK) {
WriteLine("deflateEnd : %s\n", (z.msg) ? z.msg : "error");
return 1;
}
}
// last position (total size)
index_buf[block] = write_pos >> (ciso.align);
// write header & index block
fseek(fout, sizeof(ciso), SEEK_SET);
fwrite(index_buf, 1, index_size, fout);
WriteLine("ciso compress completed , total size = %8d bytes , rate %d%%\n"
, (int)write_pos, (int)(write_pos * 100 / ciso.total_bytes));
return 0;
}
/****************************************************************************
main
****************************************************************************/
int ciso_do(int argc, char *argv[]) {
int level;
int result;
WriteLine("Compressed ISO9660 converter Ver.1.01 by BOOSTER\n");
if (argc != 4) {
WriteLine("Usage: ciso level infile outfile\n");
WriteLine(" level: 1-9 compress ISO to CSO (1=fast/large - 9=small/slow\n");
WriteLine(" 0 decompress CSO to ISO\n");
return 0;
}
level = argv[1][0] - '0';
if (level < 0 || level > 9) {
WriteLine("Unknown mode: %c\n", argv[1][0]);
return 1;
}
fname_in = argv[2];
fname_out = argv[3];
if ((fin = fopen(fname_in, "rb")) == NULL) {
WriteLine("Can't open %s\n", fname_in);
return 1;
}
if ((fout = fopen(fname_out, "wb")) == NULL) {
WriteLine("Can't create %s\n", fname_out);
return 1;
}
if (level == 0)
result = decomp_ciso();
else
result = comp_ciso(level);
// free memory
if (index_buf) free(index_buf);
if (crc_buf) free(crc_buf);
if (block_buf1) free(block_buf1);
if (block_buf2) free(block_buf2);
// close files
fclose(fin);
fclose(fout);
return result;
}
<file_sep>/*
Compressed ISO9660 conveter by BOOSTER
Ported to PS4 by cfwprpht
*/
LibCiso for PS4.
Do not need a specific SDK.
Printf() functions are changed to libhbs c_console wrappers.
Needs Zlib for PS4 to work proper.
The Zlib Library from the PS4 it self can not be used to Decompress or Compress a ISO/CISO old psp style like.
|
e8e7ac9f29d9a02d5712b53d02a1791c15546b72
|
[
"Markdown",
"C"
] | 2
|
C
|
cfwprpht/PS4_Ciso
|
8da519710f8c8098b6e32cffe49881f9914da5f3
|
4e99bb85c484ba9562963a73ec7004af8b0e8562
|
refs/heads/main
|
<repo_name>joaomarcoslp3/letmeask<file_sep>/src/hooks/index.ts
export * from './useAuth'
export * from './useRoom'
|
ac4e72bcfb5c4108f7394b0909d89d99475c7584
|
[
"TypeScript"
] | 1
|
TypeScript
|
joaomarcoslp3/letmeask
|
5931e68bd6f2466a7b32e7c0012f5e4e6bf65564
|
80f597e40564f242f7dd20d8a666bdcd31d99a35
|
refs/heads/develop
|
<file_sep>(()=> {
const form = document.querySelector('.form');
const toggleLinks = document.getElementsByClassName("register");
// toggle the forms
toggleForms = ()=> {
form.lastElementChild.classList.toggle('registration');
form.firstElementChild.classList.toggle('registration');
}
for (var i = 0; i < toggleLinks.length; i++) {
toggleLinks[i].addEventListener('click', toggleForms);
}
})();
<file_sep>class User {
constructor(name, age, address, maritalStatus, username, password) {
this.name = name;
this.age = age;
this.address = address;
this.maritalStatus = maritalStatus;
this.password = <PASSWORD>;
}
}<file_sep> const acctDet = document.querySelector('.msg a');
const trans = document.querySelector('.t1 a');
const transHist = document.querySelector('.t2 a');
const imgCont = document.querySelector('.img-cont');
const acctDetCont = document.querySelector('.acct-details-cont');
const transHistCont = document.querySelector('.trans-hist-cont');
transHist.addEventListener('click', function() {
imgCont.classList.toggle('hide');
acctDetCont.classList.toggle('hide');
transHistCont.classList.toggle('hide');
});
acctDet.addEventListener('click', ()=> {
if (!acctDetCont.classList.contains('hide') && !imgCont.classList.contains('hide')) {
return;
} else {
imgCont.classList.toggle('hide');
acctDetCont.classList.toggle('hide');
transHistCont.classList.toggle('hide');
}
});
|
3ec45896d6eb7fa2d194c0d424341ecfabd3382c
|
[
"JavaScript"
] | 3
|
JavaScript
|
didymus707/Banka
|
80084732e4029612ae8073ea65adedfc37bf0966
|
f4e46edae014ed941947e38b88f8771e9d0de08d
|
refs/heads/master
|
<repo_name>b4tchkn/The-Box<file_sep>/The Box/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class GameManager : MonoBehaviour {
/* constで定数を表す */
public const int WALL_FRONT = 1; //前
public const int WALL_RIGHT = 2; //右
public const int WALL_BACK = 3; //後
public const int WALL_LEFT = 4; //左
public GameObject panelWalls;
public GameObject buttonMessage;
public GameObject buttonMessageText;
private int wallNo; //現在の向いている方向
// Use this for initialization
void Start ()
{
wallNo = WALL_FRONT;
}
// Update is called once per frame
void Update ()
{
}
public void PushButtonMemo ()
{
DisplayMessage("エッフェル塔と書いてある");
}
public void PushButtonMessage ()
{
buttonMessage.SetActive(false); //メッセージを消す
}
public void PushButtonRight ()
{
wallNo++;
//WALL_LEFTより右に行こうとした場合WALL_FRONTに戻す
if (wallNo > WALL_LEFT)
{
wallNo = WALL_FRONT;
}
DisplayWall();
}
public void PushButtonLeft ()
{
wallNo--;
if (wallNo < WALL_FRONT)
{
wallNo = WALL_LEFT;
}
DisplayWall();
}
void DisplayMessage(string mes)
{
buttonMessage.SetActive(true);
buttonMessageText.GetComponent<Text>().text = mes;
}
void DisplayWall()
{
switch (wallNo)
{
case WALL_FRONT:
panelWalls.transform.localPosition = new Vector3(0.0f, 0.0f, 0.0f);
break;
case WALL_RIGHT:
panelWalls.transform.localPosition = new Vector3(-1000.0f, 0.0f, 0.0f);
break;
case WALL_BACK:
panelWalls.transform.localPosition = new Vector3(-2000.0f, 0.0f, 0.0f);
break;
case WALL_LEFT:
panelWalls.transform.localPosition = new Vector3(-3000.0f, 0.0f, 0.0f);
break;
}
}
}
|
8d55a571ffbb6d61c0b2c514eab49a7c9e6fa6f5
|
[
"C#"
] | 1
|
C#
|
b4tchkn/The-Box
|
815e7639c5762e37a0fa528eb725db1d85cc21b3
|
38843451293a4068ca382b42d76df9c9b540ed32
|
refs/heads/master
|
<file_sep># OptimusLibrary
项目的通用框架
多年开发积累的库
pod 'OptimusLibrary'
<file_sep>//
// Macro.h
// CBHGroupCar
//
// Created by mac on 2018/1/24.
// Copyright © 2018年 mac. All rights reserved.
//
#ifndef Macro_h
#define Macro_h
#pragma mark - theme
//#define Main_Color_Red HEXCOLOR(@"#CD0000")
#define Main_Color_Green HEXCOLOR(@"#00cccc")
#define Main_Color_Blue HEXCOLOR(@"#1d96d5")
#define Main_Color_DeepBlue HEXCOLOR(@"#0e7ae6")
//#define Main_Color_Gray HEXCOLOR(@"#666666")
//#define Main_Color_LightGray HEXCOLOR(@"#999999")
//#define Main_Color_Black HEXCOLOR(@"#333333")
#define Main_Color_White HEXCOLOR(@"#FFFFFF")
#define Main_Color_Orange HEXCOLOR(@"#EC8D24")
#define Main_Color_Gold HEXCOLOR(@"#d3b275")
#define Main_Color_Red RGBACOLOR(184,26,8,1)
#define Main_Color_LightRed RGBACOLOR(184,26,8,0.5)
#define Main_Color_Black RGBACOLOR(51,51,51,1)
#define Main_Color_LightBlack RGBACOLOR(74,74,74,1)
#define Main_Color_Gray RGBACOLOR(102,102,102,1)
#define Main_Color_LightGray RGBACOLOR(153,153,153,1)
#define Main_Color_BGLightGray RGBACOLOR(247,247,247,1)
#define Main_Color_Yellow RGBACOLOR(245,166,35,1)
#define Main_Color Main_Color_Blue
#define Main_Color_BG HEXCOLOR(@"#f4f4f4")
#pragma mark - 关键字
/** 获取APP名称 */
#define APP_NAME ([[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleDisplayName"])
/** 程序版本号 */
#define APP_VERSION [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"]
/** 获取APP build版本 */
#define APP_BUILD ([[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"])
/** User-Agent */
#define APP_USER_AGENT [NSString stringWithFormat:@"石虎/%@ (%@;U;%@ %@;%@/%@)", \
APP_VERSION, DeviceModel, DeviceSystemName, DeviceVersion, DeviceLocal, DeviceLang]
///系统版本
#define OS_VERSION [[[UIDevice currentDevice] systemVersion] floatValue]
///自定义log
#define NSLog(FORMAT, ...) printf("%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
///系统font
#define SYSTEMFONT(fon) [UIFont systemFontOfSize:fon withScale:autoSizeScale]
#define SYSTEMBOLDFONT(fon) [UIFont boldSystemFontOfSize:fon withScale:autoSizeScale]
#define SYSTEMNAMEFONT(name,fon) [UIFont nameFont:name size:fon withScale:autoSizeScale]
///网络返回安全转换dic
#define EncodeFormDic(dic,key) [dic[key] isKindOfClass:[NSString class]] ? dic[key] :([dic[key] isKindOfClass:[NSNumber class]] ? [dic[key] stringValue]:@"")
///若引用
#define WeakObj(o) autoreleasepool{} __weak __block typeof(o) o##p = o;
#define WeakSelf WeakObj(self)
///16进制颜色
#define HEXCOLOR(str) [WFFunctions WFColorWithHexString:str alpha:1]
#define HEXCOLORALPHA(str,alp) [WFFunctions WFColorWithHexString:str alpha:alp]
#define UIColorFromHEX(rgbValue) [UIColor colorWithRed:((float)((rgbValue & 0xFF0000) >> 16))/255.0 green:((float)((rgbValue & 0xFF00) >> 8))/255.0 blue:((float)(rgbValue & 0xFF))/255.0 alpha:1.0]
///三基色
#define RGBACOLOR(r,g,b,a) [UIColor colorWithRed:(r)/255.0 green:(g)/255.0 blue:(b)/255.0 alpha:(a)]
///GCD 的宏定义
//GCD - 一次性执行
#define kDISPATCH_ONCE_BLOCK(onceBlock) static dispatch_once_t onceToken; dispatch_once(&onceToken, onceBlock);
//GCD - 在Main线程上运行
#define kDISPATCH_MAIN_THREAD(mainQueueBlock) dispatch_async(dispatch_get_main_queue(), mainQueueBlock);
//GCD - 开启异步线程
#define kDISPATCH_GLOBAL_QUEUE_DEFAULT(globalQueueBlock) dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), globalQueueBlock);
///数据绑定
#define WFKeypath(objc,keyPath) @(((void)objc.keyPath,#keyPath))
#define WFObserver(TARGET, KEYPATH, HANDLER) ({\
GCBaseObservationModel *observation = [GCBaseObservationModel new];\
observation.observation = TARGET;\
observation.keyPath = WFKeypath(TARGET,KEYPATH);\
[observation setHandler:HANDLER];\
[self registObservation:observation];\
})
///判断模拟器环境
#if TARGET_IPHONE_SIMULATOR
#define SIMULATOR 1
#elif TARGET_OS_IPHONE
#define SIMULATOR 0
#endif
///全屏幕的高度
#define WF_SCREEN_HEIGHT [[UIScreen mainScreen]bounds].size.height
///全屏幕的宽度
#define WF_SCREEN_WIDTH [[UIScreen mainScreen]bounds].size.width
///是不是iPhone X系列机型
#define isiPhoneX ([[NSString stringWithFormat:@"%.2f",(WF_SCREEN_WIDTH / WF_SCREEN_HEIGHT)] isEqualToString:@"0.46"] ? YES : NO)
///安全区域导航条高度差
#define WF_NAVIGATION_SAFE_OFFSET (isiPhoneX ? 24.0 : 0.0)
///安全区域选项卡高度差
#define WF_TAB_SAFE_OFFSET (isiPhoneX ? 34.0 : 0.0)
///导航条高度(包含iPhone X)
#define WF_NAVIGATION_BAR_HEIGHT 64.0
///tabbar高度(包含iPhone X)
#define WF_TAB_BAR_HEIGHT 49.0
///带navigationbar View 的高度
#define WF_UI_VIEW_HEIGHT (WF_SCREEN_HEIGHT - WF_NAVIGATION_BAR_HEIGHT - WF_NAVIGATION_SAFE_OFFSET)
#pragma mark - 按照iPhone 6的屏幕尺寸,等比缩放的适配方
#define WH_Ration (CGFloat)(667.0f / 375.0f)
#define autoSizeScale (CGFloat)WF_SCREEN_WIDTH / 375.0f
CG_INLINE CGFloat
WFSC(CGFloat num) {
CGFloat scale = autoSizeScale;
CGFloat xnum = num * scale;
return xnum;
}
CG_INLINE CGFloat
WFSCB(CGFloat num) {
CGFloat scalex = autoSizeScale;
CGFloat xnum = num / scalex;
return xnum;
}
CG_INLINE CGFloat
WFCGFloatX(CGFloat num) {
return WFSC(num);
}
CG_INLINE CGFloat
WFCGFloatY(CGFloat num) {
return WFSC(num);
}
//WFCGFloatBackX
CG_INLINE CGFloat
WFCGFloatBackX(CGFloat num) {
return WFSCB(num);
}
//WFCGFloatBackY
CG_INLINE CGFloat
WFCGFloatBackY(CGFloat num) {
return WFSCB(num);
}
CG_INLINE CGSize
WFCGSizeMake(CGFloat width, CGFloat height)
{
CGSize size;
CGFloat scale = autoSizeScale;
CGFloat wwidth = width * scale;
CGFloat hheight = height * scale;
size = CGSizeMake(wwidth, hheight);
return size;
}
CG_INLINE CGRect
WFCGRectMake(CGFloat x, CGFloat y, CGFloat width, CGFloat height)
{
CGRect rect;
CGFloat scale = autoSizeScale;
CGFloat xx = x * scale;
CGFloat yy = y * scale;
CGFloat wwidth = width * scale;
CGFloat hheight = height * scale;
rect = CGRectMake(xx, yy, wwidth, hheight);
return rect;
}
CG_INLINE CGPoint
WFCGPointMake(CGFloat x, CGFloat y)
{
CGPoint point;
CGFloat scale = autoSizeScale;
CGFloat xx = x * scale;
CGFloat yy = y * scale;
point = CGPointMake(xx, yy);
return point;
}
#endif /* Macro_h */
|
cfb8f1d4f766ce54a43e955c63b8a505a74a1bda
|
[
"Markdown",
"C"
] | 2
|
Markdown
|
megatronxx/OptimusLibrary
|
285b044f626649a4187cb35a1a19250f29aab979
|
eac4499bc70764c00d08265e20bdc695fac7b08d
|
refs/heads/master
|
<file_sep>package server;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.GridPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.stage.Stage;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
public class JFXServer extends Application {
private List<TaskClientConnection> connectionList = new ArrayList<>();
private GridPane gridpane;
private volatile boolean running = true;
private ServerSocket serverSocket;
private String[] clients = {
"Masha",
"Petr",
"Olga",
"Julia",
"Marina",
"Anton",
"Oleg",
"Vasily",
"Tamara",
"Linia",
"Nikolay",
"Alena",
"Andrew"
};
private HBox createClient(String clientName) {
Label name = new Label(clientName);
name.setPrefSize(Integer.MAX_VALUE, Integer.MAX_VALUE);
name.setAlignment(Pos.CENTER_RIGHT);
Label status = new Label(ConnectionUtil.CLIENT_EXIT);
status.setTextFill(Color.GRAY);
status.setPrefSize(Integer.MAX_VALUE, Integer.MAX_VALUE);
status.setAlignment(Pos.CENTER_LEFT);
HBox hBox = new HBox(10);
hBox.getChildren().addAll(name, status);
return hBox;
}
private HBox getClient(String clientName) {
int idx = -1;
for (int i = 0; i < clients.length; i++) {
if (clients[i].equals(clientName)) {
idx = i;
break;
}
}
if (idx == -1) {
return null;
} else {
return (HBox) this.gridpane.getChildren().get(idx);
}
}
private String getServerIP() {
String IP;
try {
Socket socket = new Socket();
socket.connect(new InetSocketAddress("google.com", 80));
IP = socket.getLocalAddress().getHostAddress();
socket.close();
} catch (IOException e) {
IP = "";
}
return IP;
}
@Override
public void stop() {
for (TaskClientConnection taskClientConnection : connectionList) {
taskClientConnection.terminate();
}
connectionList.clear();
this.running = false;
if (this.serverSocket != null) {
try {
this.serverSocket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void start(Stage primaryStage) {
VBox root = new VBox();
this.gridpane = new GridPane();
this.gridpane.setHgap(10);
this.gridpane.setVgap(10);
int ii = (int) Math.sqrt(this.clients.length);
if (ii * ii < this.clients.length) {
ii++;
}
for (int i = 0; i < this.clients.length; i++) {
this.gridpane.add(this.createClient(this.clients[i]), i % ii, i / ii);
}
root.getChildren().addAll(this.gridpane);
primaryStage.setTitle("My server: " + this.getServerIP());
double WINDOW_WIDTH = 500.0;
double WINDOW_HEIGHT = 500.0;
primaryStage.setScene(new Scene(root, WINDOW_WIDTH, WINDOW_HEIGHT));
primaryStage.setMinWidth(WINDOW_WIDTH);
primaryStage.setMinHeight(WINDOW_HEIGHT);
primaryStage.sizeToScene();
primaryStage.show();
new Thread(() -> {
try {
this.serverSocket = new ServerSocket(ConnectionUtil.port);
while (this.running) {
Socket socket = null;
try {
socket = this.serverSocket.accept();
} catch (IOException ex) {
System.out.println("bye");
}
if (socket != null) {
TaskClientConnection connection = new TaskClientConnection(socket, this, connectionList.size());
System.out.println("new connecton");
connectionList.add(connection);
//create a new thread
Thread thread = new Thread(connection);
thread.start();
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}).start();
}
public void removeConnection(int id) {
int idx = -1;
for (int i = 0; i < this.connectionList.size(); i++) {
if (connectionList.get(i).getId() == id) {
idx = i;
break;
}
}
this.connectionList.remove(idx);
}
public void setClientStatus(String name, String status) {
Platform.runLater(() -> {
HBox uiclient = this.getClient(name);
if (uiclient != null) {
Label label = (Label) uiclient.getChildren().get(1);
label.setText(status);
switch (status) {
case ConnectionUtil.CLIENT_ALIVE:
label.setTextFill(Color.BLUE);
break;
case ConnectionUtil.CLIENT_START:
label.setTextFill(Color.GREEN);
break;
case ConnectionUtil.CLIENT_STOP:
label.setTextFill(Color.RED);
break;
case ConnectionUtil.CLIENT_EXIT:
label.setTextFill(Color.GRAY);
break;
}
}
});
}
public static void main(String[] args) {
launch(args);
}
}
<file_sep>package client;
import javafx.application.Application;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.ToggleButton;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.Stage;
import server.ConnectionUtil;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
public class JFXClient extends Application {
private DataOutputStream output = null;
private Socket socket = null;
private static String name = null;
public static String host = null;
private Text statusText = new Text();
@Override
public void start(Stage primaryStage) {
VBox root = new VBox();
root.setAlignment(Pos.CENTER);
root.setPadding(new Insets(10));
root.setSpacing(5);
ToggleButton button = new ToggleButton("Start");
button.setStyle("-fx-base: green;");
button.setDisable(true);
button.setOnAction(new ButtonListener());
root.getChildren().addAll(button, this.statusText);
primaryStage.setTitle(name);
double WINDOW_WIDTH = 300.0;
double WINDOW_HEIGHT = 300.0;
primaryStage.setScene(new Scene(root, WINDOW_WIDTH, WINDOW_HEIGHT));
primaryStage.setMinWidth(WINDOW_WIDTH);
primaryStage.setMinHeight(WINDOW_HEIGHT);
primaryStage.sizeToScene();
primaryStage.show();
// try to create socket and send "I'm alive" message to server
try {
this.socket = new Socket(host, ConnectionUtil.port);
this.output = new DataOutputStream(socket.getOutputStream());
this.statusText.setText("Connected");
button.setDisable(false);
this.sendMessage(name + ":" + ConnectionUtil.CLIENT_ALIVE);
} catch (IOException ex) {
// if can't set the connection
this.closeSocket();
button.setDisable(true);
}
}
private void sendMessage(String msg) {
if (this.output != null) {
try {
this.output.writeUTF(msg);
this.output.flush();
} catch (IOException e) {
this.closeSocket();
}
}
}
private void closeSocket() {
this.statusText.setText("Server not found");
try {
if (this.output != null) {
this.output.close();
this.output = null;
}
if (this.socket != null) {
this.socket.close();
this.output = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public void stop() throws Exception {
this.sendMessage(name + ":" + ConnectionUtil.CLIENT_EXIT);
this.closeSocket();
super.stop();
System.out.println("bye");
}
public static void main(String[] args) {
host=args[0];
name=args[1];
launch(args);
}
private class ButtonListener implements EventHandler<ActionEvent> {
@Override
public void handle(ActionEvent event) {
ToggleButton button = (ToggleButton) event.getTarget();
if (button.isSelected()) {
button.setText("Stop");
button.setStyle("-fx-base: red;");
sendMessage(name + ":" + ConnectionUtil.CLIENT_START);
} else {
button.setText("Start");
button.setStyle("-fx-base: green;");
sendMessage(name + ":" + ConnectionUtil.CLIENT_STOP);
}
}
}
}
<file_sep>package server;
public class ConnectionUtil {
public final static int port = 8888;
//messages
public final static String CLIENT_START = "start";
public final static String CLIENT_STOP = "stop";
public final static String CLIENT_ALIVE = "alive";
public final static String CLIENT_EXIT = "exit";
}
<file_sep>package server;
import java.io.DataInputStream;
import java.io.IOException;
import java.net.Socket;
public class TaskClientConnection implements Runnable {
private int id;
private Socket socket;
private JFXServer server;
private DataInputStream input;
private volatile boolean running = true;
public void terminate() {
this.running = false;
try {
if (input != null) input.close();
if (socket != null) socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public TaskClientConnection(Socket socket, JFXServer server, int id) {
this.socket = socket;
this.server = server;
this.id = id;
}
@Override
public void run() {
try {
input = new DataInputStream(socket.getInputStream());
while (this.running) {
String message = null;
try {
message = input.readUTF();
} catch (IOException e) {
System.out.println("Looks like client is dead");
}
if (message != null && message.indexOf(':') != -1) {
String[] temp = message.split(":");
String name = temp[0];
String cmd = temp[1];
switch (cmd) {
case ConnectionUtil.CLIENT_ALIVE:
this.server.setClientStatus(name, ConnectionUtil.CLIENT_ALIVE);
break;
case ConnectionUtil.CLIENT_START:
this.server.setClientStatus(name, ConnectionUtil.CLIENT_START);
break;
case ConnectionUtil.CLIENT_STOP:
this.server.setClientStatus(name, ConnectionUtil.CLIENT_STOP);
break;
case ConnectionUtil.CLIENT_EXIT:
this.running = false;
this.server.setClientStatus(name, ConnectionUtil.CLIENT_EXIT);
this.server.removeConnection(this.id);
break;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
public int getId() {
return id;
}
}
|
56c2a5a4343b2b57cba30c59f53741d2e447032b
|
[
"Java"
] | 4
|
Java
|
avysotsk/csjfx
|
ad7094276640ef62600a4bbd45923bafe22b6233
|
7fa89489cb59b7bd37e70fc9a1d74a4f3b923a42
|
refs/heads/master
|
<file_sep>server.port=9000
spring.jpa.database=oracle
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect
spring.jpa.show-sql=true
spring.datasource.url=jdbc:oracle:thin:@localhost:1522:XE
spring.datasource.username=mpos
spring.datasource.password=<PASSWORD>
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver<file_sep>package com.yada.mis.ars.web;
import com.yada.mis.ars.query.AccountTransQuery;
import com.yada.mis.ars.service.AccountTransService;
import com.yada.mis.ars.service.FileHandleService;
import com.yada.mis.ars.view.AccountTransView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Pageable;
import org.springframework.data.web.PageableDefault;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class WebController {
private AccountTransService accountTransService;
private FileHandleService fileHandleService;
@Autowired
public WebController(AccountTransService accountTransService, FileHandleService fileHandleService) {
this.accountTransService = accountTransService;
this.fileHandleService = fileHandleService;
}
@Value("${file-token}")
private String fileToken;
@RequestMapping("/")
public AccountTransView query(AccountTransQuery query, @PageableDefault(value = 100) Pageable pageable) {
return accountTransService.queryView(query, pageable);
}
@RequestMapping("/export")
public String export(String passWord, String fileName, String fileType) {
if(fileToken.equals(passWord)) {
if ("eacq".equals(fileType)) {
return fileHandleService.handleEacq(fileName);
} else {
return fileHandleService.handleOther(fileName);
}
} else {
return "没有访问该资源的权限";
}
}
@ExceptionHandler(Exception.class)
public String handleException(Exception e) {
return e.getMessage();
}
}
<file_sep>package com.yada.mis.ars.dao;
import com.yada.mis.ars.model.HisTranList;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface HisTranListDao extends JpaRepository<HisTranList, Long>, JpaSpecificationExecutor<HisTranList> {
}
<file_sep>package com.yada.mis.ars.dao;
import com.yada.mis.ars.model.AccountTrans;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations = {"classpath:application.properties"})
@SpringApplicationConfiguration
public class AccountTransDaoTest {
@Autowired
protected AccountTransDao accountTransDao;
@Test
public void test(){
List<AccountTrans> count = accountTransDao.findAll();
System.out.println(count);
}
}<file_sep>package com.yada.mis.ars.dao;
import com.yada.mis.ars.model.HisTranList;
import com.yada.mis.ars.query.HisTranListQuery;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(locations = {"classpath:application.properties"})
@SpringApplicationConfiguration
public class HisTranListDaoTest {
@Autowired
private HisTranListDao hisTranListDao;
@Test
public void test() {
HisTranListQuery query = new HisTranListQuery();
query.setRespCode("00");
query.setTranFlag("0");
query.setSafFlag("0");
List<HisTranList> list = hisTranListDao.findAll(query);
System.out.println(list);
}
}<file_sep>package com.yada.mis.ars.dao;
import com.yada.mis.ars.model.EacqTrans;
import org.springframework.data.repository.CrudRepository;
import java.util.List;
public interface EacqTransDao extends CrudRepository<EacqTrans, Long> {
List<EacqTrans> findByFileName(String fileName);
}
<file_sep>package com.yada.mis.ars.utils;
import org.junit.Test;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ObjectToModelTest {
@Test
public void toAlipayTrans() {
String line = "2088721458626814 48045977 条码支付 退款 2017072521001004110201027611\t 20170725 2017-07-25 17:00:49 -0.01 0.00 -0.01 2831118770910097001\t 0.01 2831117115762363001";
String tran = line.replaceAll("\\s+", "#");
String[] strings = tran.split("#");
StringBuilder a = new StringBuilder();
for(int i = 0; i < strings.length; i ++) {
a.append("\n").append(i).append(":").append(strings[i]);
}
System.out.println(a);
}
@Test
public void toWechatTrans() {
String line = "35199461 48404434 MICROPAY REFUND 4004792001201707242368913298 20170725 2017-07-25 11:44:11 0.00 0.00 -17.00 50000203702017072501457120848 2829217145247599001 ORIGINAL SUCCESS 17.00 0.00 2819937908559743001 ABC_DEBIT 涓\uE15Eぇ鍏\uE0A6櫌锛堟繁鍦筹級 ";
String tran = line.replaceAll("\\s+", "#");
String[] strings = tran.split("#");
StringBuilder a = new StringBuilder();
for(int i = 0; i < strings.length; i ++) {
a.append("\n").append(i).append(":").append(strings[i]);
}
System.out.println(a);
}
@Test
public void toEacqTrans() {
String line = "1 48001132 000579 6222601310021307590 20130719 074432 629.00 1.26 627.74 722100 PCEP 0000 CUPD 319968384183";
Pattern pattern = Pattern.compile(".{1}\\s+(.{8})\\s+(.{6})\\s+(.{20})\\s+(\\d{8})\\s+(\\d{6})\\s+(.{13}).\\s+(.{12}).\\s+(.{13}).\\s+(.{6})\\s+(.{4})\\s+((.{4})|(.{4})\\s+(.{4})\\s+(.{12}))");
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}<file_sep>package com.yada.mis.ars.dao;
import com.yada.mis.ars.model.AccountTrans;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
public interface AccountTransDao extends JpaRepository<AccountTrans, String>,JpaSpecificationExecutor<AccountTrans> {
}
<file_sep>package com.yada.mis.ars.utils;
import com.yada.mis.ars.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class ObjectToModel {
private static SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
public static AlipayTrans toAlipayTrans(String line, String fileName) {
String tran = line.replaceAll("\\s+", "#");
String[] strings = tran.split("#");
AlipayTrans trans = new AlipayTrans();
// 商户编号
String merNo = strings[0];
trans.setMerNo(merNo);
// 终端号
String termNo = strings[1];
trans.setTermNo(termNo);
// 交易方式
String tranType = strings[2];
trans.setTranType(tranType);
// 业务类型
String busType = strings[3];
trans.setBusType(busType);
// 支付宝交易号
String aliTranNo = strings[4];
trans.setAliTranNo(aliTranNo);
// 结算日期
String settleDate = strings[5];
trans.setSettleDate(settleDate);
// 交易时间
String tranDate = strings[6] + " " + strings[7];
trans.setTranDate(tranDate);
// 交易金额
String tranAmt = strings[8];
trans.setTranAmt(tranAmt);
// 手续费
String fee = strings[9];
trans.setFee(fee);
// 结算金额
String settleAmt = strings[10];
trans.setSettleAmt(settleAmt);
if ("退款".equals(strings[3])) {
// 退款批次号/请求号
String batchNo = strings[11];
trans.setBatchNo(batchNo);
// 订单金额
String orderAmt = strings[12];
trans.setOrderAmt(orderAmt);
// 商户订单号
String orderNo = strings[13];
trans.setOrderNo(orderNo);
} else {
// 订单金额
String orderAmt = strings[11];
trans.setOrderAmt(orderAmt);
// 商户订单号
String orderNo = strings[12];
trans.setOrderNo(orderNo);
}
// 备注
String remarks = "";
trans.setRemarks(remarks);
// 文件来源
trans.setFileName(fileName);
trans.setExpDate(df.format(new Date()));
return trans;
}
public static WechatTrans toWechatTrans(String line, String fileName) {
String tran = line.replaceAll("\\s+", "#");
String[] strings = tran.split("#");
WechatTrans trans = new WechatTrans();
// 商户编号
String merNo = strings[0];
trans.setMerNo(merNo);
// 终端号
String termNo = strings[1];
trans.setTermNo(termNo);
// 交易方式
String tranType = strings[2];
trans.setTranType(tranType);
// 交易状态
String tranStatus = strings[3];
trans.setTranStatus(tranStatus);
// 微信订单号
String wcTranNo = strings[4];
trans.setWcTranNo(wcTranNo);
// 结算日期
String settleDate = strings[5];
trans.setSettleDate(settleDate);
// 交易时间
String tranDate = strings[6] + " " + strings[7];
trans.setTranDate(tranDate);
// 交易金额
String tranAmt = strings[8];
trans.setTranAmt(tranAmt);
// 手续费
String fee = strings[9];
trans.setFee(fee);
// 结算金额
String settleAmt = strings[10];
trans.setSettleAmt(settleAmt);
if ("REFUND".equals(strings[3])) {
// 微信退款单号
String wcRefundNo = strings[11];
trans.setWcRefundNo(wcRefundNo);
// 商户退款单号
String refundNo = strings[12];
trans.setRefundNo(refundNo);
// 退款类型
String refundType = strings[13];
trans.setRefundType(refundType);
// 退款状态
String refundStatus = strings[14];
trans.setRefundStatus(refundStatus);
// 退款金额
String refundAmt = strings[15];
trans.setRefundAmt(refundAmt);
// 退款手续费
String refundFee = strings[16];
trans.setRefundFee(refundFee);
// 商户订单号
String orderNo = strings[17];
trans.setOrderNo(orderNo);
// 付款银行
String bankType = strings[18];
trans.setBankType(bankType);
// 备注
String remarks = strings[19];
trans.setRemarks(remarks);
} else {
// 微信退款单号
String wcRefundNo = strings[11];
trans.setWcRefundNo(wcRefundNo);
// 商户退款单号
String refundNo = strings[12];
trans.setRefundNo(refundNo);
// 退款金额
String refundAmt = strings[13];
trans.setRefundAmt(refundAmt);
// 退款手续费
String refundFee = strings[14];
trans.setRefundFee(refundFee);
// 商户订单号
String orderNo = strings[15];
trans.setOrderNo(orderNo);
// 付款银行
String bankType = strings[16];
trans.setBankType(bankType);
// 备注
String remarks = strings[17];
trans.setRemarks(remarks);
}
// 文件来源
trans.setFileName(fileName);
trans.setExpDate(df.format(new Date()));
return trans;
}
public static EacqTrans toEacqTrans(Matcher matcher, String fileName) {
EacqTrans trans = new EacqTrans();
// 终端号
String termNo = matcher.group(1);
trans.setTermNo(termNo);
// 批号
String batchNo = matcher.group(2);
trans.setBatchNo(batchNo);
// 交易卡号
String cardNo = matcher.group(3);
trans.setCardNo(cardNo);
// 交易日期
String tranDate = matcher.group(4);
trans.setTranDate(tranDate);
// 交易时间
String tranTime = matcher.group(5);
trans.setTranTime(tranTime);
// 交易金额
String tranAmt = matcher.group(6);
trans.setTranAmt(tranAmt);
// 手续费
String fee = matcher.group();
trans.setFee(fee);
// 结算金额
String settleAmt = matcher.group(7);
trans.setSettleAmt(settleAmt);
// 授权码
String authNo = matcher.group(8);
trans.setAuthNo(authNo);
// 交易码
String tranType = matcher.group(9);
trans.setTranType(tranType);
// 分期
String stag = matcher.group(10);
trans.setStag(stag);
// 卡别
String cardType = matcher.group(11);
trans.setCardType(cardType);
// 参考号
String rrn = matcher.group(12);
trans.setRrn(rrn);
// 文件来源
trans.setFileName(fileName);
trans.setExpDate(df.format(new Date()));
return trans;
}
public static AccountTrans toAccountTrans(HisTranList hisTranList) {
AccountTrans trans = new AccountTrans();
trans.setTraceNo(hisTranList.getTraceNo() + "");// 流水号
trans.setBatchNo(hisTranList.getBatchNo() + "");// 批次号
trans.setMerNo(hisTranList.getMerchantId());// 商户号
trans.setTermNo(hisTranList.getTerminalId());// 终端号
trans.setCardNo(hisTranList.getCardNo());// 卡号
trans.setTranType(hisTranList.getTranType());// 交易类型
trans.setTranDate(hisTranList.getPosTranStamp());// 交易时间
trans.setTranAmt(hisTranList.getTranAmt() + "");// 金额
trans.setRrn(hisTranList.getRrn());// 参考号
trans.setInvoiceNo(hisTranList.getInvoiceNo() + "");// 票据号
return trans;
}
}
<file_sep>package com.yada.mis.ars.config;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Component
@ConfigurationProperties(prefix = "eacq")
public class EacqProperties {
private String fileFormat;
private String orgCode;
private String orgNo;
private String dateFormat;
private String charset;
private String regex;
public String getFileFormat() {
return fileFormat;
}
public void setFileFormat(String fileFormat) {
this.fileFormat = fileFormat;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getOrgNo() {
return orgNo;
}
public void setOrgNo(String orgNo) {
this.orgNo = orgNo;
}
public String getDateFormat() {
return dateFormat;
}
public void setDateFormat(String dateFormat) {
this.dateFormat = dateFormat;
}
public String getCharset() {
return charset;
}
public void setCharset(String charset) {
this.charset = charset;
}
public String getRegex() {
return regex;
}
public void setRegex(String regex) {
this.regex = regex;
}
}
<file_sep>FROM jhouzard/docker-jdk6-mvn3
RUN mkdir -p /opt/ars
WORKDIR /opt/ars
COPY settings.xml /opt/maven/conf/
COPY . /opt/ars
RUN mvn clean package -Dmaven.test.skip=true \
&& cp -R ./target/*.jar ./app.jar
EXPOSE 9000
CMD ["java", "-jar", "/opt/ars/app.jar"]<file_sep>package com.yada.mis.ars.model;
import javax.persistence.*;
/**
* 支付宝交易明细
*/
@Entity
@SequenceGenerator(name = "eacq_trans_seq", sequenceName = "eacq_trans_seq", allocationSize = 1)
public class EacqTrans {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "eacq_trans_seq")
private long id;
// 终端号
@Column
private String termNo;
// 批号
@Column
private String batchNo;
// 交易卡号
@Column
private String cardNo;
// 交易日期
@Column
private String tranDate;
// 交易时间
@Column
private String tranTime;
// 交易金额
@Column
private String tranAmt;
// 手续费
@Column
private String fee;
// 结算金额
@Column
private String settleAmt;
// 授权码
@Column
private String authNo;
// 交易码
@Column
private String tranType;
// 分期
@Column
private String stag;
// 卡别
@Column
private String cardType;
// 参考号
@Column
private String rrn;
// 文件来源
@Column
private String fileName;
// 导入日期
@Column
private String expDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTermNo() {
return termNo;
}
public void setTermNo(String termNo) {
this.termNo = termNo;
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getTranDate() {
return tranDate;
}
public void setTranDate(String tranDate) {
this.tranDate = tranDate;
}
public String getTranTime() {
return tranTime;
}
public void setTranTime(String tranTime) {
this.tranTime = tranTime;
}
public String getTranAmt() {
return tranAmt;
}
public void setTranAmt(String tranAmt) {
this.tranAmt = tranAmt;
}
public String getFee() {
return fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getSettleAmt() {
return settleAmt;
}
public void setSettleAmt(String settleAmt) {
this.settleAmt = settleAmt;
}
public String getAuthNo() {
return authNo;
}
public void setAuthNo(String authNo) {
this.authNo = authNo;
}
public String getTranType() {
return tranType;
}
public void setTranType(String tranType) {
this.tranType = tranType;
}
public String getStag() {
return stag;
}
public void setStag(String stag) {
this.stag = stag;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getRrn() {
return rrn;
}
public void setRrn(String rrn) {
this.rrn = rrn;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
}
<file_sep>package com.yada.mis.ars.model;
import javax.persistence.*;
/**
* 支付宝交易明细
*/
@Entity
@SequenceGenerator(name = "alipay_trans_seq", sequenceName = "alipay_trans_seq", allocationSize = 1)
public class AlipayTrans {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "alipay_trans_seq")
private long id;
// 商户编号
@Column
private String merNo;
// 终端号
@Column
private String termNo;
// 交易方式
@Column
private String tranType;
// 业务类型
@Column
private String busType;
// 支付宝交易号
@Column
private String aliTranNo;
// 结算日期
@Column
private String settleDate;
// 交易时间
@Column
private String tranDate;
// 交易金额
@Column
private String tranAmt;
// 手续费
@Column
private String fee;
// 结算金额
@Column
private String settleAmt;
// 退款批次号/请求号
@Column
private String batchNo;
// 订单金额
private String orderAmt;
// 商户订单号
@Column
private String orderNo;
// 备注
@Column
private String remarks;
// 文件来源
@Column
private String fileName;
// 导入日期
@Column
private String expDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMerNo() {
return merNo;
}
public void setMerNo(String merNo) {
this.merNo = merNo;
}
public String getTermNo() {
return termNo;
}
public void setTermNo(String termNo) {
this.termNo = termNo;
}
public String getTranType() {
return tranType;
}
public void setTranType(String tranType) {
this.tranType = tranType;
}
public String getBusType() {
return busType;
}
public void setBusType(String busType) {
this.busType = busType;
}
public String getAliTranNo() {
return aliTranNo;
}
public void setAliTranNo(String aliTranNo) {
this.aliTranNo = aliTranNo;
}
public String getSettleDate() {
return settleDate;
}
public void setSettleDate(String settleDate) {
this.settleDate = settleDate;
}
public String getTranDate() {
return tranDate;
}
public void setTranDate(String tranDate) {
this.tranDate = tranDate;
}
public String getTranAmt() {
return tranAmt;
}
public void setTranAmt(String tranAmt) {
this.tranAmt = tranAmt;
}
public String getFee() {
return fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getSettleAmt() {
return settleAmt;
}
public void setSettleAmt(String settleAmt) {
this.settleAmt = settleAmt;
}
public String getBatchNo() {
return batchNo;
}
public void setBatchNo(String batchNo) {
this.batchNo = batchNo;
}
public String getOrderAmt() {
return orderAmt;
}
public void setOrderAmt(String orderAmt) {
this.orderAmt = orderAmt;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
}
<file_sep>package com.yada.mis.ars.model;
import javax.persistence.*;
/**
* 微信交易明细
*/
@Entity
@SequenceGenerator(name = "wechat_trans_seq", sequenceName = "eacq_trans_seq", allocationSize = 1)
public class WechatTrans {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "wechat_trans_seq")
private long id;
// 商户编号
@Column
private String merNo;
// 终端号
@Column
private String termNo;
// 交易类型
@Column
private String tranType;
// 交易状态
@Column
private String tranStatus;
// 微信订单号
@Column
private String wcTranNo;
// 结算日期
@Column
private String settleDate;
// 交易时间
@Column
private String tranDate;
// 交易金额
@Column
private String tranAmt;
// 手续费
@Column
private String fee;
// 结算金额
@Column
private String settleAmt;
// 微信退款单号
@Column
private String wcRefundNo;
// 商户退款单号
@Column
private String refundNo;
// 退款类型
@Column
private String refundType;
// 退款状态
@Column
private String refundStatus;
// 退款金额
@Column
private String refundAmt;
// 退款手续费
@Column
private String refundFee;
// 商户订单号
@Column
private String orderNo;
// 付款银行
@Column
private String bankType;
// 备注
@Column
private String remarks;
// 文件来源
@Column
private String fileName;
// 导入日期
@Column
private String expDate;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getMerNo() {
return merNo;
}
public void setMerNo(String merNo) {
this.merNo = merNo;
}
public String getTermNo() {
return termNo;
}
public void setTermNo(String termNo) {
this.termNo = termNo;
}
public String getTranType() {
return tranType;
}
public void setTranType(String tranType) {
this.tranType = tranType;
}
public String getTranStatus() {
return tranStatus;
}
public void setTranStatus(String tranStatus) {
this.tranStatus = tranStatus;
}
public String getWcTranNo() {
return wcTranNo;
}
public void setWcTranNo(String wcTranNo) {
this.wcTranNo = wcTranNo;
}
public String getSettleDate() {
return settleDate;
}
public void setSettleDate(String settleDate) {
this.settleDate = settleDate;
}
public String getTranDate() {
return tranDate;
}
public void setTranDate(String tranDate) {
this.tranDate = tranDate;
}
public String getTranAmt() {
return tranAmt;
}
public void setTranAmt(String tranAmt) {
this.tranAmt = tranAmt;
}
public String getFee() {
return fee;
}
public void setFee(String fee) {
this.fee = fee;
}
public String getSettleAmt() {
return settleAmt;
}
public void setSettleAmt(String settleAmt) {
this.settleAmt = settleAmt;
}
public String getWcRefundNo() {
return wcRefundNo;
}
public void setWcRefundNo(String wcRefundNo) {
this.wcRefundNo = wcRefundNo;
}
public String getRefundNo() {
return refundNo;
}
public void setRefundNo(String refundNo) {
this.refundNo = refundNo;
}
public String getRefundType() {
return refundType;
}
public void setRefundType(String refundType) {
this.refundType = refundType;
}
public String getRefundStatus() {
return refundStatus;
}
public void setRefundStatus(String refundStatus) {
this.refundStatus = refundStatus;
}
public String getRefundAmt() {
return refundAmt;
}
public void setRefundAmt(String refundAmt) {
this.refundAmt = refundAmt;
}
public String getRefundFee() {
return refundFee;
}
public void setRefundFee(String refundFee) {
this.refundFee = refundFee;
}
public String getOrderNo() {
return orderNo;
}
public void setOrderNo(String orderNo) {
this.orderNo = orderNo;
}
public String getBankType() {
return bankType;
}
public void setBankType(String bankType) {
this.bankType = bankType;
}
public String getRemarks() {
return remarks;
}
public void setRemarks(String remarks) {
this.remarks = remarks;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
}
<file_sep>package com.yada.mis.ars.service;
import com.yada.mis.ars.dao.AccountTransDao;
import com.yada.mis.ars.dao.AlipayTransDao;
import com.yada.mis.ars.dao.HisTranListDao;
import com.yada.mis.ars.model.AlipayTrans;
import com.yada.mis.ars.model.HisTranList;
import com.yada.mis.ars.query.HisTranListQuery;
import com.yada.mis.ars.utils.ObjectToModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import java.util.List;
@Component
public class AlipayTransService {
private Logger logger = LoggerFactory.getLogger(this.getClass());
private AlipayTransDao alipayTransDao;
private HisTranListDao hisTranListDao;
private AccountTransDao accountTransDao;
@Autowired
public AlipayTransService(AlipayTransDao alipayTransDao, HisTranListDao hisTranListDao, AccountTransDao accountTransDao) {
this.alipayTransDao = alipayTransDao;
this.hisTranListDao = hisTranListDao;
this.accountTransDao = accountTransDao;
}
public void account(AlipayTrans alipayTrans) {
logger.info("开始匹配支付宝交易:{}", alipayTrans.getOrderNo());
alipayTransDao.save(alipayTrans);
// 匹配支付宝交易, 交易号、交易类型tranType 81 83 addDate
HisTranListQuery query = new HisTranListQuery();
query.setAddData(alipayTrans.getAliTranNo());
List<HisTranList> list = hisTranListDao.findAll(query);
for (HisTranList his : list) {
accountTransDao.save(ObjectToModel.toAccountTrans(his));
}
if (list.size() == 0) {
logger.warn("没有匹配到支付宝交易:{}", alipayTrans.getOrderNo());
}
}
}
<file_sep>package com.yada.mis.ars.model;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
@Entity
public class HisTranList {
@Id
private long traceNo; // NOT NULL NUMBER(38)
@Column
private long batchNo;// NOT NULL NUMBER(38)
@Column
private long bankBatchNo;// NOT NULL NUMBER(38)
@Column
private long voidBatchNo;// NOT NULL NUMBER(38)
@Column
private long bankTraceNo;// NOT NULL NUMBER(38)
@Column
private long voidTraceNo;// NOT NULL NUMBER(38)
@Column
private long invoiceNo;// NOT NULL NUMBER(38)
@Column
private long bankInvoiceNo;// NOT NULL NUMBER(38)
@Column
private long voidInvoiceNo;// NOT NULL NUMBER(38)
@Column
private float tranAmt; // NOT NULL FLOAT(126)
@Column
private float voidAmt;// NOT NULL FLOAT(126)
@Column
private float addAmt;// NOT NULL FLOAT(126)
@Column
private String tranType;// NOT NULL CHAR(2)
@Column
private String voidTranType;// CHAR(2)
@Column
private String voidOldType;// CHAR(2)
@Column
private String cardNo;// NOT NULL CHAR(19)
@Column
private String expDate;// CHAR(4)
@Column
private String cardType;// CHAR(2)
@Column
private String cardName;// CHAR(20)
@Column
private String posTranStamp;// CHAR(16)
@Column
private String localTranStamp;// CHAR(16)
@Column
private String bankTranStamp;// CHAR(16)
@Column
private String merchantId;// CHAR(15)
@Column
private String bankTerminalId;// CHAR(15)
@Column
private String bankMerchantId;// CHAR(15)
@Column
private String operNo;// CHAR(6)
@Column
private String authNo;// CHAR(6)
@Column
private String rrn;// CHAR(12)
@Column
private String respCode;// CHAR(2)
@Column
private String respCodeBank;// CHAR(4)
@Column
private String respBankId;// CHAR(8)
@Column
private String respHostId;// CHAR(2)
@Column
private String inputMode;// CHAR(3)
@Column
private String posConCode;// CHAR(2)
@Column
private String ccyCode;// CHAR(3)
@Column
private String mcc;// CHAR(4)
@Column
private String idType;// CHAR(2)
@Column
private String personalId;// CHAR(18)
@Column
private String settleFlag;// CHAR(1)
@Column
private String tranFlag;// CHAR(1)
@Column
private String safFlag;// CHAR(1)
@Column
private String offlineFlag;// CHAR(1)
@Column
private String adviceFlag;// CHAR(1)
@Column
private String mccCode;// CHAR(4)
@Column
private String bankCode;// CHAR(2)
@Column
private String terminalId;// CHAR(8)
@Column
private String centerType;// CHAR(11)
@Column
private String addData;// CHAR(100)
@Column
private String orgId;// VARCHAR2(16)
public long getTraceNo() {
return traceNo;
}
public void setTraceNo(long traceNo) {
this.traceNo = traceNo;
}
public long getBatchNo() {
return batchNo;
}
public void setBatchNo(long batchNo) {
this.batchNo = batchNo;
}
public long getBankBatchNo() {
return bankBatchNo;
}
public void setBankBatchNo(long bankBatchNo) {
this.bankBatchNo = bankBatchNo;
}
public long getVoidBatchNo() {
return voidBatchNo;
}
public void setVoidBatchNo(long voidBatchNo) {
this.voidBatchNo = voidBatchNo;
}
public long getBankTraceNo() {
return bankTraceNo;
}
public void setBankTraceNo(long bankTraceNo) {
this.bankTraceNo = bankTraceNo;
}
public long getVoidTraceNo() {
return voidTraceNo;
}
public void setVoidTraceNo(long voidTraceNo) {
this.voidTraceNo = voidTraceNo;
}
public long getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(long invoiceNo) {
this.invoiceNo = invoiceNo;
}
public long getBankInvoiceNo() {
return bankInvoiceNo;
}
public void setBankInvoiceNo(long bankInvoiceNo) {
this.bankInvoiceNo = bankInvoiceNo;
}
public long getVoidInvoiceNo() {
return voidInvoiceNo;
}
public void setVoidInvoiceNo(long voidInvoiceNo) {
this.voidInvoiceNo = voidInvoiceNo;
}
public float getTranAmt() {
return tranAmt;
}
public void setTranAmt(float tranAmt) {
this.tranAmt = tranAmt;
}
public float getVoidAmt() {
return voidAmt;
}
public void setVoidAmt(float voidAmt) {
this.voidAmt = voidAmt;
}
public float getAddAmt() {
return addAmt;
}
public void setAddAmt(float addAmt) {
this.addAmt = addAmt;
}
public String getTranType() {
return tranType;
}
public void setTranType(String tranType) {
this.tranType = tranType;
}
public String getVoidTranType() {
return voidTranType;
}
public void setVoidTranType(String voidTranType) {
this.voidTranType = voidTranType;
}
public String getVoidOldType() {
return voidOldType;
}
public void setVoidOldType(String voidOldType) {
this.voidOldType = voidOldType;
}
public String getCardNo() {
return cardNo;
}
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
public String getExpDate() {
return expDate;
}
public void setExpDate(String expDate) {
this.expDate = expDate;
}
public String getCardType() {
return cardType;
}
public void setCardType(String cardType) {
this.cardType = cardType;
}
public String getCardName() {
return cardName;
}
public void setCardName(String cardName) {
this.cardName = cardName;
}
public String getPosTranStamp() {
return posTranStamp;
}
public void setPosTranStamp(String posTranStamp) {
this.posTranStamp = posTranStamp;
}
public String getLocalTranStamp() {
return localTranStamp;
}
public void setLocalTranStamp(String localTranStamp) {
this.localTranStamp = localTranStamp;
}
public String getBankTranStamp() {
return bankTranStamp;
}
public void setBankTranStamp(String bankTranStamp) {
this.bankTranStamp = bankTranStamp;
}
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId;
}
public String getBankTerminalId() {
return bankTerminalId;
}
public void setBankTerminalId(String bankTerminalId) {
this.bankTerminalId = bankTerminalId;
}
public String getBankMerchantId() {
return bankMerchantId;
}
public void setBankMerchantId(String bankMerchantId) {
this.bankMerchantId = bankMerchantId;
}
public String getOperNo() {
return operNo;
}
public void setOperNo(String operNo) {
this.operNo = operNo;
}
public String getAuthNo() {
return authNo;
}
public void setAuthNo(String authNo) {
this.authNo = authNo;
}
public String getRrn() {
return rrn;
}
public void setRrn(String rrn) {
this.rrn = rrn;
}
public String getRespCode() {
return respCode;
}
public void setRespCode(String respCode) {
this.respCode = respCode;
}
public String getRespCodeBank() {
return respCodeBank;
}
public void setRespCodeBank(String respCodeBank) {
this.respCodeBank = respCodeBank;
}
public String getRespBankId() {
return respBankId;
}
public void setRespBankId(String respBankId) {
this.respBankId = respBankId;
}
public String getRespHostId() {
return respHostId;
}
public void setRespHostId(String respHostId) {
this.respHostId = respHostId;
}
public String getInputMode() {
return inputMode;
}
public void setInputMode(String inputMode) {
this.inputMode = inputMode;
}
public String getPosConCode() {
return posConCode;
}
public void setPosConCode(String posConCode) {
this.posConCode = posConCode;
}
public String getCcyCode() {
return ccyCode;
}
public void setCcyCode(String ccyCode) {
this.ccyCode = ccyCode;
}
public String getMcc() {
return mcc;
}
public void setMcc(String mcc) {
this.mcc = mcc;
}
public String getIdType() {
return idType;
}
public void setIdType(String idType) {
this.idType = idType;
}
public String getPersonalId() {
return personalId;
}
public void setPersonalId(String personalId) {
this.personalId = personalId;
}
public String getSettleFlag() {
return settleFlag;
}
public void setSettleFlag(String settleFlag) {
this.settleFlag = settleFlag;
}
public String getTranFlag() {
return tranFlag;
}
public void setTranFlag(String tranFlag) {
this.tranFlag = tranFlag;
}
public String getSafFlag() {
return safFlag;
}
public void setSafFlag(String safFlag) {
this.safFlag = safFlag;
}
public String getOfflineFlag() {
return offlineFlag;
}
public void setOfflineFlag(String offlineFlag) {
this.offlineFlag = offlineFlag;
}
public String getAdviceFlag() {
return adviceFlag;
}
public void setAdviceFlag(String adviceFlag) {
this.adviceFlag = adviceFlag;
}
public String getMccCode() {
return mccCode;
}
public void setMccCode(String mccCode) {
this.mccCode = mccCode;
}
public String getBankCode() {
return bankCode;
}
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
public String getTerminalId() {
return terminalId;
}
public void setTerminalId(String terminalId) {
this.terminalId = terminalId;
}
public String getCenterType() {
return centerType;
}
public void setCenterType(String centerType) {
this.centerType = centerType;
}
public String getAddData() {
return addData;
}
public void setAddData(String addData) {
this.addData = addData;
}
public String getOrgId() {
return orgId;
}
public void setOrgId(String orgId) {
this.orgId = orgId;
}
}
<file_sep>package com.yada.mis.ars.service;
import com.yada.mis.ars.dao.AccountTransDao;
import com.yada.mis.ars.model.AccountTrans;
import com.yada.mis.ars.query.AccountTransQuery;
import com.yada.mis.ars.view.AccountTransView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Component;
@Component
public class AccountTransService {
private AccountTransDao accountTransDao;
@Autowired
public AccountTransService(AccountTransDao accountTransDao) {
this.accountTransDao = accountTransDao;
}
public AccountTransView queryView(AccountTransQuery query, Pageable pageable) {
Page<AccountTrans> page = accountTransDao.findAll(query, pageable);
AccountTransView view = new AccountTransView();
view.setSize(page.getSize());
view.setPage(page.getNumber());
view.setTotal(page.getTotalElements());
view.setContent(page.getContent());
return view;
}
}
|
6c55485d9e76417ec2ab8930cc90083d0b9540db
|
[
"Java",
"Dockerfile",
"INI"
] | 17
|
INI
|
lirenhao/MisAccount
|
2cf963b0553d270bff5124a8f4e1d99e3dd06290
|
ff3a9e1b9a3ddc2f34ef4d6cd773c4f93ccf0ab8
|
refs/heads/master
|
<file_sep>//
// ViewController.swift
// TouchID
//
// Created by john.lin on 2018/10/16.
// Copyright © 2018年 john.lin. All rights reserved.
//
import UIKit
import LocalAuthentication
struct KeychainConfiguration {
static let serviceName = "TouchMeIn"
static let accessGroup: String? = nil
}
class ViewController: UIViewController {
@IBAction func saveUserData(_ sender: Any) {
saveAccountDetailsTokeychain(account: "a123", password: "<PASSWORD>")
}
@IBAction func authTouchID(_ sender: Any) {
let root = RootViewController()
self.present(root, animated: true, completion: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
authenticateUserUsingTouchId()
}
fileprivate func authenticateUserUsingTouchId(){
let context = LAContext()
var authError: NSError?
//判斷是否支援 touch ID
if context.canEvaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, error: &authError){
self.evaulateTouchIdAuthenticity(context: context)
} else {
guard let error = authError else {
return
}
showError(error: error as! LAError)
}
}
func evaulateTouchIdAuthenticity(context: LAContext) {
guard let lastAccessedUserName = UserDefaults.standard.object(forKey: "lastAccessedUserName") as? String else {
return
}
//驗證 touch ID
context.evaluatePolicy(.deviceOwnerAuthenticationWithBiometrics, localizedReason: lastAccessedUserName) { (success, error) in
if success {
self.loadPasswordFromKeychainAndAuthenticateUser(lastAccessedUserName)
} else {
if let error = error as? LAError {
self.showError(error: error)
}
}
}
}
func evaluatePolicyFailErrorMessageForLA(error: LAError) -> String {
var message = ""
if #available(iOS 11.0, *) {
switch error.code {
case LAError.biometryNotAvailable:
message = "Authentication could not start because the device does not support biometric authentication."
case LAError.biometryLockout:
message = "Authentication could not continue because the user has been locked out of biometric authentication, due to failing authentication too many times."
case LAError.biometryNotEnrolled:
message = "Authentication could not start because the user has not enrolled in biometric authentication."
default:
message = "Did not find error code on LAError object"
}
} else {
switch error.code {
case LAError.touchIDLockout:
message = "Too many failed attempts."
case LAError.touchIDNotAvailable:
message = "TouchID is not available on the device"
case LAError.touchIDNotEnrolled:
message = "TouchID is not enrolled on the device"
default:
message = "Did not find error code on LAError object"
}
// Fallback on earlier versions
}
return message
}
func showError(error: LAError) {
var message: String = ""
switch error.code {
case LAError.authenticationFailed:
message = "The user failed to provide valid credentials"
case LAError.appCancel:
message = "Authentication was cancelled by application"
case LAError.invalidContext:
message = "The context is invalid"
case LAError.notInteractive:
message = "Not interactive"
case LAError.passcodeNotSet:
message = "Passcode is not set on the device"
case LAError.systemCancel:
message = "Authentication was cancelled by the system"
case LAError.userCancel:
message = "The user did cancel"
case LAError.userFallback:
message = "The user chose to use the fallback"
default:
message = evaluatePolicyFailErrorMessageForLA(error: error)
}
showAlertController(message)
}
fileprivate func loadPasswordFromKeychainAndAuthenticateUser(_ account: String) {
guard !account.isEmpty else {
return
}
let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: account, accessGroup: KeychainConfiguration.accessGroup)
do {
let storedPassword = try passwordItem.readPassword()
print(storedPassword)
let root = RootViewController()
self.present(root, animated: true, completion: nil)
} catch KeychainPasswordItem.KeychainError.noPassword {
print("No saved password")
} catch {
print("Unhandled error")
}
}
func showAlertController(_ message: String) {
let alertController = UIAlertController(title: nil, message: message, preferredStyle: .alert)
alertController.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alertController, animated: true, completion: nil)
}
fileprivate func saveAccountDetailsTokeychain(account: String, password: String) {
// guard account.isEmpty, password.isEmpty else {
// return
// }
UserDefaults.standard.set(account, forKey: "lastAccessedUserName")
let passwordItem = KeychainPasswordItem(service: KeychainConfiguration.serviceName, account: account, accessGroup: KeychainConfiguration.accessGroup)
do {
try passwordItem.savePassword(password)
} catch {
print("Error saving password")
}
}
}
|
a02b2e97f0794c126fd9e40324e354f40edfa65e
|
[
"Swift"
] | 1
|
Swift
|
forever19735/TouchID
|
010fd983f94c7ee6af51d332c7a60edfc08c9208
|
c4338583a5e865f13806172642f6aefd1323b06f
|
refs/heads/master
|
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* server.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ylazrek <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/28 19:33:22 by ylazrek #+# #+# */
/* Updated: 2021/08/31 17:29:12 by ylazrek ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
void handle(int sig)
{
unsigned char off_bit;
if (sig == SIGUSR1)
{
if (g_msg.size < 8)
{
g_msg.c = g_msg.c | (0x1 << g_msg.size);
++g_msg.size;
}
}
else if (sig == SIGUSR2)
{
if (g_msg.size < 8)
{
off_bit = 0xFF ^ (0x01 << g_msg.size);
g_msg.c = g_msg.c & (off_bit);
++g_msg.size;
}
}
if (g_msg.size == 8)
{
g_msg.size = 0;
write(1, &g_msg.c, 1);
g_msg.c = 0x0;
}
}
int main(int ac, char **av)
{
struct sigaction act;
if (ac == 1)
{
(void)av;
ft_putnbr_fd(getpid(), 1);
write(1, "\n", 1);
g_msg.c = 0x0;
g_msg.size = 0;
act.__sigaction_u.__sa_handler = handle;
sigemptyset(&act.sa_mask);
act.sa_flags = SA_RESTART;
sigaction(SIGUSR1, &act, NULL);
sigaction(SIGUSR2, &act, NULL);
while (1)
pause();
}
else
write(1, "Error: argument\n", 16);
return (0);
}
<file_sep>SRCS_C = client.c \
tools.c
SRCS_S = server.c \
puts.c
CC = gcc
FLAGS = -Wall -Wextra -Werror
NAME_C = client
NAME_S = server
OBJS_C = $(SRCS_C:.c=.o)
OBJS_S = $(SRCS_S:.c=.o)
%.o : %.c minitalk.h
$(CC) $(FLAGS) -c $< -o $@
all : $(NAME_C) $(NAME_S)
$(NAME_C) : $(OBJS_C)
$(CC) $(FLAGS) $(OBJS_C) -o $(NAME_C)
$(NAME_S) : $(OBJS_S)
$(CC) $(FLAGS) $(OBJS_S) -o $(NAME_S)
clean :
/bin/rm -f $(OBJS_C)
/bin/rm -f $(OBJS_S)
fclean : clean
/bin/rm -f $(NAME_C)
/bin/rm -f $(NAME_S)
re : fclean all
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* client.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ylazrek <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/28 16:49:09 by ylazrek #+# #+# */
/* Updated: 2021/08/31 17:27:58 by ylazrek ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
int ft_atoi(const char *str)
{
unsigned int num;
int i;
int np;
np = 1;
i = 0;
num = 0;
while (str[i] == ' ' || str[i] == '\t' || str[i] == '\f'
|| str[i] == '\r' || str[i] == '\n' || str[i] == '\v')
i++;
if (str[i] == '+' || str[i] == '-')
if (str[i++] == '-')
np = -1;
while (str[i] >= '0' && str[i] <= '9')
{
num = num * 10 + (str[i] - '0');
i++;
}
return ((int)(np * num));
}
int is_num(const char *str)
{
int i;
int cnt;
i = 0;
cnt = 0;
if (str[0] == '+' && ft_strlen(str) == 1)
return (0);
if (str[i] == '+')
i++;
while (str[i])
{
if (str[i] < '0' || str[i] > '9')
return (0);
i++;
cnt++;
}
if (cnt > 10)
return (0);
else if (cnt == 10)
return (compaire(str, "2147483647"));
return (1);
}
void send_sig(int pid, int sig)
{
if (kill(pid, sig) == -1)
{
write(1, "Error: PID not found\n", 21);
exit(1);
}
}
void ft_send(int pid, char **av, unsigned char mask)
{
int i;
int j;
unsigned char c;
i = 0;
while (av[2][i])
{
c = av[2][i];
j = 0;
while (j < 8)
{
if ((c & mask) == mask)
send_sig(pid, SIGUSR1);
else if ((c & mask) == 0x0)
send_sig(pid, SIGUSR2);
mask = mask << 1;
j++;
usleep(75);
}
mask = 0x01;
i++;
usleep(75);
}
}
int main(int ac, char **av)
{
int pid;
unsigned char mask;
if (ac == 3)
{
if (is_num(av[1]) && ft_strcmp(av[2], ""))
{
pid = ft_atoi(av[1]);
if (pid < 100 || pid > 99998)
return (1);
mask = 0x01;
ft_send(pid, av, mask);
}
else
write(1, "Error: argument\n", 16);
}
else
write(1, "Error: argument\n", 16);
return (0);
}
<file_sep>/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* minitalk.h :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ylazrek <<EMAIL>> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2021/08/29 16:25:58 by ylazrek #+# #+# */
/* Updated: 2021/08/31 17:28:26 by ylazrek ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef MINITALK_H
# define MINITALK_H
# include <unistd.h>
# include <stdio.h>
# include <stdlib.h>
# include <signal.h>
typedef struct s_msg
{
unsigned char c;
size_t size;
} t_msg;
t_msg g_msg;
size_t ft_strlen(const char *str);
int ft_strcmp(char *s1, char *s2);
void handle(int sig);
int is_num(const char *str);
int compaire(const char *str, const char *max);
int ft_atoi(const char *str);
void send_sig(int pid, int sig);
void ft_putnbr_fd(int n, int fd);
void ft_putstr_fd(char const *s, int fd);
void ft_putchar_fd(char c, int fd);
#endif
|
8f28f12bee13996ec3b6571f00493085762b1c53
|
[
"C",
"Makefile"
] | 4
|
C
|
lazrekyasser/MiniTalk
|
58d53479fb1eb44278447b4ea37d44b96b93515c
|
85ea13f772f818e40e095734b50c23d2051242a3
|
refs/heads/master
|
<file_sep>const conect =require('../conectionBD');
//GET ALL USERS
function getUsers(request,response){
var id = request.params.id;
var nombre = request.params.nombre;
request.checkParams("id", "Enter a valid number.").isInt();
var errors = request.validationErrors();
if (errors) {
response.send(errors);
return;
} else {
conect.db.query('SELECT * FROM hola where id=?', [request.params.id], (err,rows) => {
if(err) throw err;
//console.log(rows[0].nombre);
// response.send({"user":rows[0].id, "ced":rows[0].nombre });
response.end(JSON.stringify(rows));
});
}
}
module.exports={
getUsers
};
<file_sep>const conect =require('../conectionBD');
//GET ALL USERS
function getNotificationPush(request,response){
return response.status(200).set('text/csv').send('{"estado":"ddd"}');
}
module.exports={
getNotificationPush
};
|
b9e25403423e4aed5a9efdd3ed641203bd3c1b3d
|
[
"JavaScript"
] | 2
|
JavaScript
|
hugparra/API_REST_APP
|
8c3357a0db8e0de3fe48382f2c35800576413cab
|
a263908de2925b31600820ab66148cb5d19a72b7
|
refs/heads/master
|
<repo_name>xiongliangmei/springboot-mybatis<file_sep>/src/test/java/com/SupportTest.java
package com;
import com.entity.User;
import com.mapper.UserMapper;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.List;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SupportTest {
}
|
52c81bb9a7be72855d98f9746dc5933b00a84eb4
|
[
"Java"
] | 1
|
Java
|
xiongliangmei/springboot-mybatis
|
a0982a21f6f5a8b161f3f631c6fd77ad857c7c88
|
ed7922b982d0d894abd0000722c2664c2b6363d8
|
refs/heads/master
|
<file_sep>$(document).ready(function () {
var slobj = document.all('SLObject');
// Declare a proxy to reference the hub.
var chat = $.connection.DYdin;
// Create a function that the hub can call to broadcast messages.
chat.client.broadcastMessage = function (name, message) {
if (slobj != null) {
slobj.content.SLDataAccess.OnData(name, message);
}
};
// Start the connection.
$.connection.hub.start().done(function () {
if (slobj != null) {
slobj.content.SLDataAccess.OnConnected();
}
}).fail(function (reason) {
if (slobj != null) {
slobj.content.SLDataAccess.OnErr(reason);
}
});
});
function sendToServer(name, message) {
//authentication
$.connection.hub.qs = { "userName": name };
// Call the Send method on the hub.
$.connection.DYdin.server.send(name, message);
}<file_sep>slclient
xmal:
<Grid x:Name="LayoutRoot" Background="White">
<ListBox x:Name="lb" HorizontalAlignment="Left" Height="229" Margin="10,34,0,0" VerticalAlignment="Top" Width="380"/>
<Button x:Name="bt1" Content="发送" HorizontalAlignment="Left" Margin="277,268,0,0" VerticalAlignment="Top" Width="113"/>
<TextBlock Text="名字:" HorizontalAlignment="Left" Margin="10,10,0,0" TextWrapping="Wrap" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="42,6,0,0" TextWrapping="Wrap" x:Name="tb_name" VerticalAlignment="Top" Width="230"/>
<TextBox HorizontalAlignment="Left" Height="23" Margin="10,267,0,0" TextWrapping="Wrap" x:Name="tb_msg" VerticalAlignment="Top" Width="262"/>
<Button x:Name="bt_login" Content="登陆" HorizontalAlignment="Left" Margin="277,6,0,0" VerticalAlignment="Top" Width="113" Height="23"/>
</Grid>
code:
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
HtmlPage.RegisterScriptableObject("SLDataAccess", this);
bt1.Click += bt1_Click;
tb_msg.KeyDown += tb_msg_KeyDown;
}
void tb_msg_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter && tb_msg.Text != string.Empty)
{
bt1_Click(null, null);
}
}
void bt1_Click(object sender, RoutedEventArgs e)
{
HtmlPage.Window.Invoke("sendToServer", tb_name.Text, tb_msg.Text);
tb_msg.Text = string.Empty;
}
[ScriptableMember]
public void OnConnected()
{
lb.Items.Insert(0, "连接完成.......");
}
[ScriptableMember]
public void OnData(string name, string msg)
{
lb.Items.Insert(0, name + ":" + msg);
}
[ScriptableMember]
public void OnErr(string msg)
{
lb.Items.Insert(0, "error:" + msg);
}
}<file_sep>DYSignalrDemo
=============
DYSignalrDemo
<file_sep>using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace DYSignalRTemplate1
{
[HubName("DYdin")]
public class ChatHub : Hub
{
public void Send(string name, string message)
{
var user = Context.QueryString["userName"];
if (user == null || !user.StartsWith("j"))
{
return;
}
// Call the broadcastMessage method to update clients.
Clients.All.broadcastMessage(name, message);
}
}
}
|
35b90bc710c7469cf2ed012b42f680a6ef3692e4
|
[
"JavaScript",
"C#",
"Text",
"Markdown"
] | 4
|
JavaScript
|
jacle169/DYSignalrDemo
|
d30662bcbf70f3619f38275069b257302248d4c3
|
1c48d268761d3331046b0a6759ef80faa5534406
|
refs/heads/master
|
<repo_name>cogorcho/Labo2Html-2016<file_sep>/js/localStorage.js
'use strict'
let storage = () => { return localStorage }
let getKeys = (storage) => { return Object.keys(storage) }
let getCount = (keys) => { return keys.length }
let readItem = (storage, key) => { return JSON.parse(storage.getItem(key)) }
let checkItem = (storage, key) => {
return (storage.getItem(key) === null) ? false : true
}
let deleteItem = (storage, dni) => {
return checkItem(storage,dni) ? storage.removeItem(dni) : false
}
let addItem = (storage, item) => {
if (checkItem(storage,item.dni))
deleteItem(storage, item.dni)
storage.setItem(item.dni, JSON.stringify(item))
}
let printKeys = (keys, storage) => {
keys.map( key => printBonito(readItem(storage,key)) )
}
let printBonito = (item) => {
console.log('Dni: ' + getDni(item))
console.log('Nombre: ' + getApellido(item) + ', ' + getNombre(item))
console.log('FNac: ' + getFnac(item))
console.log('Email: ' + getCorreo(item))
console.log('Sexo: ' + getSexo(item))
return false;
}
let getDni = (item) => { return item.dni };
let getNombre = (item) => { return item.nombre };
let getApellido = (item) => { return item.apellido };
let getFnac = (item) => { return item.fnac };
let getCorreo = (item) => { return item.correo };
let getSexo = (item) => { return item.sexo };
<file_sep>/README.md
# Labo2Html-2016
Html, CSS y Javascript TSP FRSN Labo2 2016
<file_sep>/js/files.js
let canvas = () => document.getElementById('icanvas')
let canvasContext = (canvas) => canvas.getContext('2d')
let image = () => new Image();
let fileReader = () => new FileReader()
let handleFileSelect = (evt) => renderImage(evt.target.files[0], fileReader(), image(), canvasContext(canvas()), canvas())
document.getElementById('ifoto').addEventListener('change', handleFileSelect, false);
let renderImage = (file, fileReader, image, context, canvas) => {
fileReader.onload = function(event) {
image.src = event.target.result;
image.onload = function() {
context.drawImage(image, 0, 0, image.width, image.height, 0, 0, canvas.width, canvas.height);
}
}
// when the file is read it triggers the onload event above.
fileReader.readAsDataURL(file);
}
let clearCanvas = (canvas) => {
canvasContext(canvas).save();
// Use the identity matrix while clearing the canvas
canvasContext(canvas).setTransform(1, 0, 0, 1, 0, 0);
canvasContext(canvas).clearRect(0, 0, canvas.width, canvas.height);
// Restore the transform
canvasContext(canvas).restore();
}
|
5c11c8a3f930d2247c35d959db3ed321b7c69149
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
cogorcho/Labo2Html-2016
|
93dc7cfeb0f661878c8989f1b6ae61690ee24a23
|
f710de381d933c9961a3114fc7704a424075d247
|
refs/heads/master
|
<repo_name>readmenot/emoji-domain-checker<file_sep>/index.js
'use strict';
// emojis is an array of emojis you want to check. atm it's all the utf8 emojis but you can edit it
// to be whatever you want. example: ['👌👍', '🍑🍆', '😣']
const emojis = require("emoji-chars");
const http = require('https');
const urlencode = require('urlencode');
let index = 0;
function check() {
if (index < emojis.length) {
setTimeout(() => {
checkEmoji()
}, 50);
}
}
function checkEmoji() {
const c = emojis[index];
const addrs = `https://xn--qeiaa.ws/domain/${ urlencode(c) }.ws`;
http.get(addrs, (res) => {
const statusCode = res.statusCode;
const contentType = res.headers['content-type'];
let error;
if (statusCode !== 200) {
error = new Error(`Request Failed.\n` +
`Status Code: ${statusCode}`);
}
if (error) {
console.log(error.message);
res.resume(); // consume response data to free up memory
return;
}
res.setEncoding('utf8');
let rawData = '';
res.on('data', (chunk) => rawData += chunk);
res.on('end', () => {
try {
if (rawData.includes('ws is available!')) console.log(c);
} catch (e) {
console.log(e.message);
}
index++;
check();
});
}).on('error', (e) => {
console.log(`Got error: ${e.message}`);
});
}
check();
<file_sep>/README.md
# register emoji domains
EMOJI DOMAINS ARE 100% COMPATIBLE WITH ALL BROWSERS.
You didn't know this worked, did you?
## install
- clone the repo.
- run `npm install`
- change `emojis` under `index.js` to have whatever you want to look for.
## HOW DOES IT WORK?
This repo will make an https call to ❤❤❤.ws and let you know if one of the domains you look for is available.
Behind the scenes, all domains are ASCII, even if you see the domain name displayed as an emoji.
The actual mechanics aren't that important, but the key thing to know is that the browser uses a strategy called "punycoding" to convert "❤❤❤" to "xn--qeiaa" behind the scenes.
Most browsers keep this process hidden... but even when it's not, your emoji domain will work.
### CAN I MIX ASCII AND EMOJI?
It's all emoji or nothing!
... I'm not sure why, but I suspect it's to avoid domain spoofing.
### EMOJI SEARCH RESULTS?
Emoji domains are fully Google compatible.
IS THIS COMPATIBLE WITH OTHER GODADDY SERVICES?
Yes. We eat our own dog food.
Everything on ❤❤❤.ws is set up through GoDaddy: the domain, SSL, email forwarding, etc...
### WHY AREN'T THERE MORE EMOJI DOMAINS?
There will be.
The language of emojis is universal, understood all over the world.
As mobile first web usage skyrockets, the logic of emoji domain names is inescapable.
Until now, emoji domain names been difficult to register. One has to have a reasonably sophisticated knowledge of punycode and whatnot to even look to see whether domains are available. From there, the setup is a bit of a pain.
It's not like you can go to the GoDaddy homepage on a mobile phone and start entering emojis.
❤❤❤.ws solves that problem.
|
e481b740cd339c8cfd9cc2d3fa5326d83d55d647
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
readmenot/emoji-domain-checker
|
4ce8119e198e9e8f6204f7a9afdca37dbb9832ec
|
1c552b9ec1c6adbcc32e2c84e48c834bfe23d99a
|
refs/heads/master
|
<repo_name>hamzaelmorsali/teoria_equazioni<file_sep>/EquazioniLibrary/Equazioni.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace EquazioniLibrary
{
public static class Equazioni
{
public static bool IsDetermined(double a,double b)
{
bool risp = false;
if (a != 0 && b!=0)
{
risp = true;
}
return risp;
}
public static bool IsImpossible(double b, double a)
{
bool risp = false;
if (b != 0 && a == 0)
{
risp = true;
}
return risp;
}
public static bool IsNotDetermined(double a,double b)
{
bool risp = true;
if (a == 0 && b==0)
{
risp = false;
}
return risp;
}
public static bool IsDegree2(double a)
{
bool risp = true;
if (a==0)
{
risp = false;
}
return risp;
}
public static string Delta(double a,double b,double c)
{
string risp = "";
if (IsImpossible(a,b))
{
risp = "il delta è impossibile";
}
else if (IsNotDetermined(a, b))
{
risp = "il delta ha una di una soluzione";
}
else if(IsDetermined(a,b))
{
risp = "il delta ha piu di una soluzione";
}
double d = (b * b) - 4 * a * c;
double x1 = -b + Math.Sqrt(d);
double x2 = -b - Math.Sqrt(d);
if(d== 0)
{
risp = "eseiste solo una soluzione";
}
else if(d>0)
{
risp = "l'equazione ha 2 soluzioni";
}
else
{
risp = "il delta è impossibile";
}
return risp;
}
public static string IsDegree1(double a,double b)
{
string risp = "";
if (a == 0 && b == 0)
{
risp = "l'equazione è indeterminata";
}
else if (a == 0 && b != 0)
{
risp = "l'equazione è impossibile";
}
else
{
risp = "l'equazione è determinata";
}
return risp;
}
}
}
<file_sep>/EquazioniLibrary_tests/UnitTest1.cs
using System;
using EquazioniLibrary;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace EquazioniLibrary_tests
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestIsDetermined()
{
double a = 3,b=-5;
bool respattesa = true, resp = Equazioni.IsDetermined(a,b);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsDetermined1()
{
double a = 0,b=0;
bool respattesa = false, resp = Equazioni.IsDetermined(a,b);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsDetermined2()
{
double a = -2,b=3;
bool respattesa = true, resp = Equazioni.IsDetermined(a,b);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsImpossible()
{
double b = -2, a = 0;
bool respattesa = false, resp = Equazioni.IsImpossible(a, b);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestDelta()
{
double a = 0,b=0,c=0;
string respattesa = "eseiste solo una soluzione", resp = Equazioni.Delta(a,b,c);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsDegree2()
{
double a = 0;
bool respattesa = false, resp = Equazioni.IsDegree2(a);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestDelta1()
{
double a = 4, b = -9, c = 3;
string respattesa = "l'equazione ha 2 soluzioni", resp = Equazioni.Delta(a, b, c);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestDelta3()
{
double a = 4, b = -9, c = 10;
string respattesa = "il delta è impossibile", resp = Equazioni.Delta(a, b, c);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsDegree1()
{
double a = 0,b=0;
string respattesa = "l'equazione è indeterminata", resp = Equazioni.IsDegree1(a,b);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsDegree1_1()
{
double a = 0,b=5;
string respattesa = "l'equazione è impossibile", resp = Equazioni.IsDegree1(a,b);
Assert.AreEqual(respattesa, resp);
}
[TestMethod]
public void TestIsDegree1_2()
{
double a = 7, b = 5;
string respattesa = "l'equazione è determinata", resp = Equazioni.IsDegree1(a, b);
Assert.AreEqual(respattesa, resp);
}
}
}
|
f8c97ea6500f9248058249070471b265b242538f
|
[
"C#"
] | 2
|
C#
|
hamzaelmorsali/teoria_equazioni
|
55c06fce8d82e4cdb8030bca88d01dc2397fe064
|
507d5facb7655397c43bd76d3274e1fd3d953239
|
refs/heads/master
|
<repo_name>iliasusalifu/SMSAPP<file_sep>/app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
protect_from_forgery
layout 'application'
@page_title = 'SMS Content Management Platform'
def authorize
if session[:user_id]
return true
else
redirect_to :controller => 'users', :action => 'login'
end
end
private
def allocate_user_session(name,password)
user = User.authenticate(name,password)
session[:user_id] = user.id if user
user
end
def deallocate_user_session
session[:user_id] = nil
end
def render_404(exception = nil)
if exception
logger.info "Rendering 404: #{exception.message}"
end
render :file => "#{Rails.root}/public/404.html", :status => 404, :layout => false
end
#returns currently logged in user
def get_current_user
User.find(session[:user_id])
end
end
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_filter :authorize, :except => ['login','new','create','log_user_in']
#before_filter :validate_password, :only => ['edit','update','destroy'], :unless => is_admin?(User.find(params[:id]))
# GET /users
# GET /users.json
def index
@users = User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: @users }
end
end
# GET /users/1
# GET /users/1.json
def show
@user = User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @user }
end
end
# GET /users/new
# GET /users/new.json
def new
@user = User.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: @user }
end
end
# GET /users/1/edit
def edit
begin
@user_to_edit = User.find(params[:id]) #user whose information is to be edited
rescue ActiveRecord::RecordNotFound
logger.debug "Attempt to access invalid user with id '#{params[:id]}'"
render_404 and return
end
@user = get_current_user #currently logged in user
if authorized_to_edit_user?(@user,@user_to_edit) #if admin user or self then allow edit
render :layout => 'dashboard'
else
flash.keep[:warning] = "You are not authorized to edit this user. This action has been logged."
##Log action to database goes here.
redirect_to dashboards_path
end
end
# POST /users
# POST /users.json
def create
@user = User.new(params[:user])
respond_to do |format|
if @user.save
flash.keep[:success] = 'User was successfully Created.'
flash.keep[:notice] = 'A confirmation email has been sent to your email box. Click on the confirmation link to complete registration.'
format.html { redirect_to login_path }
#format.json { render json: @user, status: :created, location: @user }
else
format.html { render action: "new" }
#format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# PUT /users/1
# PUT /users/1.json
def update
@user = User.find(params[:id])
respond_to do |format|
if @user.update_attributes(params[:user])
flash.keep[:success] = 'User was successfully updated.'
format.html { redirect_to @user }
format.json { head :no_content }
else
format.html { redirect_to action: "edit" }
format.json { render json: @user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
@user = User.find(params[:id])
@user.destroy
flash.keep[:success] = 'User was successfully destroyed.'
flash.keep[:warn] = 'You will not be able to login using the deleted account'
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
def login
@user = User.new
respond_to do |format|
format.html {render action: "login" }
end
end
def log_user_in
@user = allocate_user_session(params[:user][:name],params[:user][:password])
if @user
flash.keep[:notice] = 'You have successfully logged in!'
respond_to do |format|
format.html {redirect_to dashboards_path }
end
else
flash.keep[:error] = 'Login unsuccessful. Try again with the correct username and password'
respond_to do |format|
format.html {redirect_to login_path }
end
end
end
def log_user_out
deallocate_user_session
flash.keep[:notice] = 'You have successfully logged out!'
respond_to do |format|
format.html {redirect_to login_path }
end
end
private
def authorized_to_edit_user?(current_user,user_to_edit_id)
logger.debug "#{current_user.id == user_to_edit_id}"
logger.debug "current_user.id = #{current_user.id} and user_to_edit_id = #{user_to_edit_id}"
if (current_user == user_to_edit_id)
return true
elsif current_user.is_admin?
return true
else
return false
end
end
end
<file_sep>/app/models/user.rb
require 'digest/sha2'
class User < ActiveRecord::Base
validates :name, :presence => true, :uniqueness => true
validates :email,:presence => true, :uniqueness => true
validates :password, :confirmation => true
attr_accessor :password_confirmation
attr_reader :password
attr_accessible :email, :hashed_password, :name, :password, :password_confirmation
validate :password_must_be_present
def is_admin?
self.role == 'admin' ? true : false
end
def User.authenticate(name,password)
if user = find_by_name(name)
if user.hashed_password == encrypt_password(password, user.salt)
user
end
end
end
def User.encrypt_password(password, salt)
Digest::SHA2.hexdigest(password + 'random' + salt)
end
def password=(<PASSWORD>)
@password=<PASSWORD>
generate_salt
if password.present?
self.hashed_password = self.class.encrypt_password(password,salt)
end
end
private
def password_must_be_present
errors.add(:password, "Missing password") unless hashed_password.present?
end
def generate_salt
self.salt = self.object_id.to_s + rand.to_s
end
end
<file_sep>/app/helpers/users_helper.rb
module UsersHelper
def error_field?(object,field,message = nil)
if object
if message.nil?
(object.errors[field.to_sym].any?) ? 'field_with_errors': ''
else
(object.errors[field.to_sym].include?(message))? 'field_with_errors' : ''
end
else
''
end
end
end
|
acb63ea5954c467791fd5fec3c79c7543a1f395d
|
[
"Ruby"
] | 4
|
Ruby
|
iliasusalifu/SMSAPP
|
085c7e881c61c49b9ad6eeb19d05a14aff5c7665
|
58ec13760f04b8c470aa7ffcdb9aae28e8e0a7bc
|
refs/heads/main
|
<repo_name>hogiyogi597/Chartify<file_sep>/src/theme/styles.ts
const styles = {
global: {
body: {
bg: 'brand.lightest',
color: 'brand.darkest'
}
}
}
export default styles<file_sep>/src/theme/components/box.ts
const Box = {
variants: {
}
}
export default Box<file_sep>/src/theme/components/tabs.ts
const Tabs = {
parts: ['tabs', 'tab'],
baseStyle: {
tabs: {
},
tab: {
_selected: { backgroundColor: 'brand.primary-light' },
_focus: { boxShadow: 'none' }
}
}
}
export default Tabs<file_sep>/src/models/accumulatedAverages.ts
export interface AccumulatedAverages {
acousticness: number;
danceability: number;
energy: number;
instrumentalness: number;
loudness: number;
speechiness: number;
valence: number;
}
export const AccumulatedAveragesM = {
empty: {
acousticness: 0,
danceability: 0,
energy: 0,
instrumentalness: 0,
loudness: 0,
speechiness: 0,
valence: 0,
},
combineAll: (arr: AccumulatedAverages[]) => {
return arr.reduce((pv, cv) => AccumulatedAveragesM.combine(pv, cv), AccumulatedAveragesM.empty)
},
combine: (one: AccumulatedAverages, two: AccumulatedAverages) => {
return {
acousticness: one.acousticness + two.acousticness,
danceability: one.danceability + two.danceability,
energy: one.energy + two.energy,
instrumentalness: one.instrumentalness + two.instrumentalness,
loudness: one.loudness + two.loudness,
speechiness: one.speechiness + two.speechiness,
valence: one.valence + two.valence,
}
},
average: (accumulatedValues: AccumulatedAverages, total: number) => {
return {
acousticness: accumulatedValues.acousticness / total,
danceability: accumulatedValues.danceability / total,
energy: accumulatedValues.energy / total,
instrumentalness: accumulatedValues.instrumentalness / total,
loudness: accumulatedValues.loudness / total,
speechiness: accumulatedValues.speechiness / total,
valence: accumulatedValues.valence / total,
}
}
}<file_sep>/src/models/radarChartData.ts
export interface ChartData {
analysisFeature: string
[playlistName: string]: string
}<file_sep>/src/theme/components/index.ts
export { default as Box } from './box'
export { default as Tabs } from './tabs'
<file_sep>/src/theme/colors.ts
const colors = {
brand: {
'darkest': "#0b132b",
'darker': "#1c2541",
"dark": "#3a506b",
"primary": "#5bc0be",
"primary-light": "#6fffe9",
'secondary': 'yellow',
'secondary-light': 'lightyellow',
'light': '',
'lighter': '',
'lightest': 'white'
},
graph: {
0: "#5bc0be",
1: 'yellow',
2: 'orange',
3: 'blue',
4: 'green'
}
}
export default colors<file_sep>/src/theme/index.ts
import { extendTheme } from '@chakra-ui/core'
import colors from './colors'
import styles from './styles'
import { Box, Tabs } from './components'
const overrides = {
styles,
colors,
components: {
Box: {
baseStyle: {
bgColor: 'brand.primary'
}
},
Tabs,
}
}
export default extendTheme(overrides)
|
e81990a3f3dca26e98a76c640e2b675e52936467
|
[
"TypeScript"
] | 8
|
TypeScript
|
hogiyogi597/Chartify
|
1568d801f6ea74d46bb06c08afb18b599ec7432c
|
05afa0235a4358b23b41e100674da1db4283e64c
|
refs/heads/master
|
<file_sep>package control;
import java.util.Scanner;
public class IfTest7 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("숫자를 입력하세요: ");
int number1 = sc.nextInt();
System.out.print("숫자를 하나 더 입력하세요: ");
int number2 = sc.nextInt();
if (number1 > number2) {
System.out.println("처음 입력하신 숫자 " + number1 + "이 두번째로 입력하신 숫자 " + number2 + "보다 큽니다");
} else if (number1 == number2) {
System.out.println("처음 입력하신 숫자 " + number1 + "와 두번째로 입력하신 숫자 " + number2 + "가 같습니다");
} else {
System.out.println("처음 입력하신 숫자 " + number1 + "가 두번째로 입력하신 숫자 " + number2 + "보다 작습니다");
}
}
}
<file_sep>package window2;
public class Dog {
// 정적특징(상태)
// - 꼬리가 있음.
// - 다리갯수
boolean tail;
int leg;
// 동적특징(동작)
// - 짖다
// - 꼬리를 흔들다.
public void bark() {
System.out.println("멍멍!!");
}
public void shake() {
System.out.println("꼬리를 흔들다!!");
}
}
<file_sep>package control;
import java.util.Date;
import java.util.Scanner;
public class SwitchTest2 {
public static void main(String[] args) {
Date date = new Date();
int month = date.getMonth() + 1;
int day = date.getDay();
int hour = date.getHours();
int min = date.getMinutes();
int sec = date.getSeconds();
System.out.println(month + "월 ");
System.out.println(hour + ":" + min + ":" + sec);
switch (day) {
case 0:
System.out.println("일요일");
break;
case 1:
System.out.println("월요일");
break;
case 2:
System.out.println("화요일");
break;
case 3:
System.out.println("수요일");
break;
case 4:
System.out.println("목요일");
break;
case 5:
System.out.println("금요일");
break;
default:
System.out.println("토요일");
break;
}
System.out.println("오늘은 " + day +"입니다.");
}
}
<file_sep>package menu;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.awt.event.ActionEvent;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JTextArea;
public class MyDiary extends JFrame {
private JTextField noText;
private JTextField titleText;
public MyDiary() {
getContentPane().setBackground(Color.GREEN);
// 컨트롤+쉬프트+f(자동 정리)
setTitle("나의 일기장 시작화면");
setSize(289, 680);
FlowLayout flow = new FlowLayout();
getContentPane().setLayout(flow);
JLabel img = new JLabel("");
getContentPane().add(img);
ImageIcon icon = new ImageIcon("일기장.PNG");
img.setIcon(icon);
JLabel no = new JLabel("번호");
getContentPane().add(no);
noText = new JTextField();
noText.setForeground(Color.RED);
getContentPane().add(noText);
noText.setColumns(20);
JLabel lblNewLabel = new JLabel("제목");
getContentPane().add(lblNewLabel);
titleText = new JTextField();
getContentPane().add(titleText);
titleText.setColumns(20);
JLabel label = new JLabel("내용");
getContentPane().add(label);
JTextArea contentText = new JTextArea();
contentText.setColumns(12);
contentText.setFont(new Font("휴먼둥근헤드라인", Font.BOLD, 20));
contentText.setTabSize(4);
contentText.setRows(5);
getContentPane().add(contentText);
JButton save = new JButton("일기저장");
save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String noT = noText.getText();
String titleT = titleText.getText();
String contentT = contentText.getText();
// 컨트롤+알트+화살표아래(복사:블록안잡고)
// 컨트롤+c,컨트롤+v(복사:블록잡고)
// 컨트롤+쉬프트+F(format)
try {
// URL url = new URL("http://www.kb.com");
// IPAddress("172.16.58.3");
FileWriter f = new FileWriter("c:/diary/" + noT + ".txt");
f.write(noT + "\r\n");
f.write(titleT + "\r\n");
f.write(contentT + "\r\n");
f.flush();
f.close();
noText.setText("");
titleText.setText("");
contentText.setText("");
JOptionPane.showMessageDialog(null, "파일로 저장 성공!!!!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "파일로 저장 실패!!!!");
}
}
});
save.setFont(new Font("휴먼둥근헤드라인", Font.BOLD, 30));
getContentPane().add(save);
JButton read = new JButton("일기읽기");
read.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String noT = noText.getText();
try {
FileReader f2 = new FileReader("c:/diary/" + noT + ".txt");
BufferedReader reader = new BufferedReader(f2);
String noR = reader.readLine();
String titleR = reader.readLine();
String contentR = reader.readLine();
noText.setText(noR);
titleText.setText(titleR);
contentText.setText(contentR);
noText.setForeground(Color.RED);
JOptionPane.showMessageDialog(null, "파일로 읽기 성공!!!!");
} catch (Exception e2) {
JOptionPane.showMessageDialog(null, "파일로 읽기 실패!!!!");
}
}
});
read.setFont(new Font("휴먼둥근헤드라인", Font.BOLD, 30));
getContentPane().add(read);
setVisible(true);
}
public static void main(String[] args) {
MyDiary name = new MyDiary();
}
}
<file_sep>package window2;
import java.util.Scanner;
public class MyShop4 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("숫자2개를 입력해주세요");
System.out.print("숫자1:");
int input1=sc.nextInt();
System.out.print("숫자2:");
int input2=sc.nextInt();
Cal2 cal2 = new Cal2();
int sum = cal2.myCal(input1, input2);
System.out.println("최종결과는"+sum*100);
}
}
<file_sep>package control;
import java.util.Scanner;
public class IfTest5 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("내가 태어난 연도는>> ");
int year = sc.nextInt();
int age = 2018 - year + 1;
if (age >= 19) {
System.out.println("올해 당신의 나이는 " + age + "살이며, 성인입니다.");
}else {
System.out.println("올해 당신의 나이는 " + age + "살이며, 미성년자입니다.");
}
}
}
<file_sep>package inherit;
public class MyHome {
public static void main(String[] args) {
SuperMan superMan = new SuperMan();
superMan.name="클라크";//person
superMan.age=100;//person
superMan.speed=100;//man
superMan.high=1000;//supeMan
superMan.smile();
superMan.run();
superMan.fly();
}
}
<file_sep>package window2;
public class Cal {
public void add(int x,int y) {
System.out.println("두 수의 합은"+ (x + y));
}
public void minus(int x,int y) {
System.out.println("두 수의 차는"+ (x - y));
}
public void mul(int x,int y) {
System.out.println("두 수의 곱은"+ (x*y));
}
public void div(int x,int y) {
System.out.println("두 수의 나눗셈은"+ (x/y));
}
}<file_sep>package menu;
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import java.awt.Color;
import java.awt.Font;
import javax.swing.JLabel;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
//컨트롤+쉬프트+0(영문)
public class Chinafood extends JFrame {
private JTextField textField;
private JTextField textField_1;
int count=0;
final int price=5000;
JLabel lblNewLabel_2;
public Chinafood() {
getContentPane().setBackground(Color.YELLOW);
setSize(700,500);
setTitle("주문하세요....");
ImageIcon icon=new ImageIcon("중국집.png");
FlowLayout flow = new FlowLayout();
getContentPane().setLayout(flow);
JButton btnNewButton = new JButton("짜장면");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
textField.setText(count+"");
textField_1.setText(count*price+"");
ImageIcon icon1=new ImageIcon("짜장면.jpg");
lblNewLabel_2.setIcon(icon1);
}
});
btnNewButton.setFont(new Font("맑은 고딕", Font.BOLD, 12));
btnNewButton.setBackground(Color.ORANGE);
btnNewButton.setForeground(Color.MAGENTA);
btnNewButton.setToolTipText("짜장면 하나가 추가됨");
getContentPane().add(btnNewButton);
JButton btnNewButton_1 = new JButton("유린기");
btnNewButton_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
textField.setText(count+"");
textField_1.setText(count*price+"");
ImageIcon icon2=new ImageIcon("유린기.jpg");
lblNewLabel_2.setIcon(icon2);
}
});
btnNewButton_1.setForeground(Color.RED);
getContentPane().add(btnNewButton_1);
JButton btnNewButton_2 = new JButton("전가복");
btnNewButton_2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
count++;
textField.setText(count+"");
textField_1.setText(count*price+"");
ImageIcon icon3=new ImageIcon("전가복.jpg");
lblNewLabel_2.setIcon(icon3);
}
});
btnNewButton_2.setForeground(Color.BLUE);
getContentPane().add(btnNewButton_2);
JLabel lblNewLabel = new JLabel("개수");
getContentPane().add(lblNewLabel);
textField = new JTextField();
textField.setFont(new Font("굴림", Font.BOLD, 20));
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("금액");
getContentPane().add(lblNewLabel_1);
textField_1 = new JTextField();
textField_1.setFont(new Font("굴림", Font.BOLD, 20));
getContentPane().add(textField_1);
textField_1.setColumns(10);
lblNewLabel_2 = new JLabel("");
getContentPane().add(lblNewLabel_2);
lblNewLabel_2.setIcon(icon);
setVisible(true);
}
public static void main(String[] args) {
Chinafood china = new Chinafood();
}
}
<file_sep>package diary;
import java.awt.FlowLayout;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.awt.Color;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JTextArea;
public class MyDiary extends JFrame {
private JTextField noText;
public MyDiary() {
getContentPane().setBackground(Color.GREEN);
//컨트롤+쉬프트+f(자동 정리)
setTitle("나의 일기장 작성화면");
setSize(520, 700);
FlowLayout flow = new FlowLayout();
getContentPane().setLayout(flow);
JLabel lblNewLabel = new JLabel("");
getContentPane().add(lblNewLabel);
ImageIcon icon = new ImageIcon("일기장-위.png");
lblNewLabel.setIcon(icon);
JLabel no = new JLabel("번호");
getContentPane().add(no);
noText = new JTextField();
noText.setFont(new Font("휴먼둥근헤드라인", Font.BOLD, 20));
getContentPane().add(noText);
noText.setColumns(15);
JButton save = new JButton("일기저장");
save.setBackground(Color.MAGENTA);
save.setFont(new Font("휴먼둥근헤드라인", Font.BOLD, 40));
getContentPane().add(save);
JButton read = new JButton("일기읽기");
read.setBackground(Color.ORANGE);
read.setFont(new Font("휴먼둥근헤드라인", Font.BOLD, 40));
getContentPane().add(read);
setVisible(true);
}
public static void main(String[] args) {
MyDiary name = new MyDiary();
}
}
<file_sep>package array;
public class Arraytest3 {
public static void main(String[] args) {
int[] n = { 100, 200, 300 };
System.out.println(n[0]);
System.out.println(n.length);
//-----------------------------
double[] eye = { 0.3, 0.5, 1.5 };
for (int i = 0; i < eye.length;i++) {
System.out.println(eye[i]);
}
for (double d : eye) {
System.out.println(d);
}
//-------------------------------
String[] names = {"김아무개","박아무개","이아무개"};
for (String s : names) {
System.out.println(s);
}
System.out.println(names);
}
}
|
996b8b6f9af584b75b8ee08b40dc7061a758be64
|
[
"Java"
] | 11
|
Java
|
leelindi/java
|
d75cafd1f897acdeb09e1b1530b7ee1b329f3adb
|
12a041006047668a9a55b19a05b2d7b8b5015cc1
|
refs/heads/main
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<title>View Products</title>
<meta charset="utf-8" />
<!--bootstrap -->
<link
rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css">
<link
rel="stylesheet"
href="<?php echo base_url(); ?>assets/bootstrap/css/bootstrap-responsive.min.css"/>
<!-- secondary CSS file and JS files -->
<link
rel="stylesheet"
href="<?php echo base_url(); ?>assets/css/home.css"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
</head>
<body>
<!-- nav bar -->
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<a class="navbar-brand" href="../welcome">
<img src="../../assets/images/product.png" width="30" height="30" class="d-inline-block align-top" alt="">
</a>
<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav mr-auto">
<li class="nav-item">
    
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Products
</a>
<div class="dropdown-menu" aria-labelledby="navbarDropdown">
<a class="dropdown-item" href="../Product/display">Display products</a>
<a class="dropdown-item" href="../Product/insert">Insert product</a>
</div>
</li>
    
<a class="nav-link" href="../Report/display">Get Report</a>
</ul>
</div>
</nav>
<!-- nav bar end-->
<!-- breadcrumb-->
<ul class="breadcrumb">
<li><a href="../welcome">Home</a></li>
<li>Display</li>
</ul>
<!-- breadcrumb end-->
<table class="table table-bordered">
<thead>
<tr>
<th scope="col">Product ID</th>
<th scope="col">Name</th>
<th scope="col">Category</th>
<th scope="col">Price</th>
<th scope="col">Description</th>
</tr>
</thead>
<?php
//echo $data;
foreach($data as $row){
//get data sent from controller
echo "<tr>";
echo "<td>".$row->product_id."</td>";
echo "<td >".$row->name."</td>";
echo "<td>".$row->category."</td>";
echo "<td>".$row->price."</td>";
echo "<td colspan='10'>".$row->description."</td>";
echo "<td class=display_button><a class= 'btn btn-danger' href='delete/".$row->product_id."'>Delete</a></td>";
echo "<td class=display_button><a class= 'btn btn-primary' href='update/".$row->product_id."'>Update</a></td>";
echo "</tr>";
}
?>
</table>
</body>
</html><file_sep><?php
class Home extends CI_Controller
{
public function __construct(){
// Constructor that loads helper and models
parent::__construct();
$this->load->helper('url');
}
public function view(){
$this->load->view('home');
}
}
?>
<file_sep><?php
class Product extends CI_Controller
{
public function __construct(){
// Constructor that loads helper and models
parent::__construct();
$this->load->database();
$this->load->helper('url');
$this->load->model('Product_model');
}
public function display(){
//echo "View loaded successfully";
$result['data']=$this->Product_model->display_products();
$this->load->view('display_products',$result);
}
public function insert(){
$this->load->view('insert_product');
//echo "View loaded successfully";
if($this->input->post('insert')){
//echo "Button pressed successfully";
$product_id=$this->input->post('product_id');
$name=$this->input->post('name');
$category=$this->input->post('category');
$price=$this->input->post('price');
$description=$this->input->post('description');
$this->Product_model->insert_product($product_id,$name,$category,$price,$description);
//JS popup message
echo '<script language=\"javascript"\>alert("Record inserted successfully");</script>';
redirect("Product/insert");
}
}
//function to update records in database
public function update($product_id){
$this->load->view('update_product',$product_id);
//echo "$product_id";
if($this->input->post('update')){
echo "Button pressed successfully";
$name=$this->input->post('name');
$category=$this->input->post('category');
$price=$this->input->post('price');
$description=$this->input->post('description');
$this->Product_model->update_product($product_id,$name,$category,$price,$description);
//JS popup message
echo '<script language=\"javascript"\>alert("Record inserted successfully");</script>';
redirect("Product/display");
}
}
//function to delete a record with the given product id
public function delete($product_id){
$this->Product_model->delete_product($product_id);
echo '<script language="javascript">alert("Record deleted successfully");</script>';
redirect("Product/display");
}
}<file_sep><?php
class Form extends CI_Controller{
public function __construct(){
parent::__construct(); // Construct CI's core so that you can use it
$this->load->helper('url');
$this->load->helper('form_validation');
}
public function form(){
$this->form_validation->set_rules
}
}<file_sep><?php
class Report extends CI_Controller
{
public function __construct(){
// Constructor that loads helper and models
parent::__construct();
$this->load->database();
//load url and session
$this->load->helper('url');
$this->load->library('session');
$this->load->model('Product_model');
}
public function display(){
//model method which returns number of products in table
$result['count']=$this->Product_model->get_count();
//model methods which returns number of products per category in table
$result['count_music']=$this->Product_model->get_count_music();
$result['count_antique']=$this->Product_model->get_count_antique();
//model methods which returns most and least expensive products in table
$result['lowest_product']=$this->Product_model->lowest_product();
$result['highest_product']=$this->Product_model->highest_product();
$this->load->view('report',$result);
$this->session->set_userdata($result);
//echo($result['count']);
}
}<file_sep>-- phpMyAdmin SQL Dump
-- version 4.9.1
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Aug 06, 2020 at 05:37 PM
-- Server version: 10.4.8-MariaDB
-- PHP Version: 7.3.11
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET AUTOCOMMIT = 0;
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `thenus_antique_shop`
--
-- --------------------------------------------------------
--
-- Table structure for table `product`
--
CREATE TABLE `product` (
`product_id` varchar(4) NOT NULL,
`name` varchar(20) NOT NULL,
`category` varchar(15) NOT NULL,
`price` decimal(10,0) NOT NULL,
`description` varchar(50) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `product`
--
INSERT INTO `product` (`product_id`, `name`, `category`, `price`, `description`) VALUES
('P001', 'English Flute', 'Music', '10000', 'Normal flute'),
('P002', 'VOC plate', 'Antique', '4000', 'An antique plate'),
('P003', 'Electric Guitar', 'Music', '60000', 'An electric guitar'),
('P004', 'Antique Cupboard', 'Antique', '20000', 'Old antique cupboard'),
('P005', 'Sitar', 'Music', '30000', 'An old Sitar'),
('P006', 'Piccolo', 'Music', '15000', 'A short high-pitched flute');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `product`
--
ALTER TABLE `product`
ADD PRIMARY KEY (`product_id`);
COMMIT;
/*!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># Antique-Shop-using-MVC
A simple primitive application made using Codeigniter under MVC architecture.
## Steps for deploy:
1. Copy the contents of the repo into our localhost system. (Xampp, Wamp etc.)
2. Import the `thenus_antique_shop.sql` dump file into your DBMS.
3. Change the existing content of [application/config/database.php](application/config/database.php) to :
```php
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => 'USER_NAME',
'password' => '',
'database' => 'DATABASE_NAME_OF_STEP_2',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
```
## Feedback:
This was a last minute done procrastinated assignment :stuck_out_tongue:
<file_sep><?php
//model class to get product details
class Product_model extends CI_Model {
public function display_products()
{
$query = $this->db->query("select * from product");
return $query->result();
}
function display_product_by_id($product_id)
//method which returns records of product_id sent by parameter
{
$query = $this->db->query("select product_id from product where product_id='".$product_id."'");
return $query->result();
}
function get_count()
//method which gets number of products in table
{
$query = $this->db->query("select count(product_id) from product");
return $query->row();
}
function get_count_music()
//method which gets number of Musical products in table
{
$query = $this->db->query("select count(product_id) from product where category='Music'");
return $query->row();
}
function get_count_antique()
//method which gets number of Antique products in table
{
$query = $this->db->query("select count(product_id) from product where category='Antique'");
return $query->row();
}
function insert_product($product_id,$name,$category,$price,$description)
//function which enters a new product
{
$query="insert into product values('$product_id','$name','$category','$price','$description')";
$this->db->query($query);
}
public function update_product($product_id,$name,$category,$price,$description)
//method which updates a given product
{
$query="update product SET name='$name',category='$category',price='$price',description='$description' where product_id='".$product_id."'";
$this->db->query($query);
}
function delete_product($product_id)
//method which returns records of product_id sent by parameter
{
$this->db->query("delete from product where product_id='".$product_id."'");
}
function highest_product()
//method which gets most expensive table in the table
{
$query = $this->db->query("select name from product
order by price DESC
limit 1
");
return $query->row();
}
function lowest_product()
//method which gets least expensive table in the table
{
$query = $this->db->query("select name from product
order by price ASC
limit 1
");
return $query->row();
}
}
?>
|
b20c98fb6bf5761a583cfb4aa352ba2f67b95651
|
[
"Markdown",
"SQL",
"PHP"
] | 8
|
PHP
|
ov1n/Antique-Shop-using-MVC
|
913563cbbf055b9f3a9bb4335b4324b34cc266eb
|
89712f9ffea47d4d5880f0f9c38bf2789fa09455
|
refs/heads/master
|
<file_sep>umask 027
set -o vi
alias pacman='pacman --color=auto'
alias emerge='emerge --color y'
alias ls='ls --color=always --group-directories-first'
eval $(dircolors)
alias grep='grep --colour=auto'
alias info=myinfo
myinfo() { unalias info; info --subnode $1 2>/dev/null | less; alias info=myinfo; }
alias vim="vim -o"
alias diff="git diff --no-index --color-words"
alias wget="wget --hsts-file=$HOME/.local/var/wget-hsts"
prompt=$([ $UID -eq 0 ] && echo ↯ || echo ▶)
PS1="\[\033[00m\]\[\033[01;34m\]\w \[\033[01;31m\]$prompt\[\033[00m\] "
export INPUTRC="$HOME/.config/confrepo/inputrc"
export EDITOR=/usr/bin/vim
export MANROFFOPT="-c"
export MANPAGER="bash -c \"vim -R +'set ft=man ts=8 nomod nolist nonu noma' +'map q ZZ'</dev/tty <(col -b)\""
PATH="$PATH:$HOME/go/bin"
HISTCONTROL=ignoreboth:erasedups
HISTSIZE=100000
HISTFILE="$HOME/.local/var/bash_history"
HISTFILESIZE=100000
HISTIGNORE="&:ls:[bf]g:exit"
shopt -s histappend
export LESS='-R -M -x1,5 --shift 10 --silent'
export LESSHISTFILE="$HOME/.local/var/less_history"
export LC_TIME="de_CH.UTF-8"
export NODE_REPL_HISTORY="$HOME/.local/var/node_history"
export SQLITE_HISTORY="$HOME/.local/var/sqlite_history"
export PGUSER=postgres
export PGHOST=localhost
export PSQLRC=$HOME/.config/confrepo/psqlrc
function gg {
local IFS=$'\n'
local PS3="Select which file to open: "
select l in $(git grep --color=always -n $@); do
[ -z "$l" ] && continue
vim "+let @/ = '\C$@'" "+setlocal hlsearch" $(
awk -F$'\x1b' '{gsub("\\[32m", "+", $6); gsub("\\[35m", "", $2); print $6; print $2}' <<<$l
)
break
done
}
psql () {
local sed_cmd='s/\(^([0-9]\+ rows\?)\|^\(-\[\ RECORD\ [0-9]\+\ \]\)\?[-+]\+\||\)/'
sed_cmd+="$(echo -e '\033[0;32m')\1$(echo -e '\033[0m')/g"
PAGER="sed '$sed_cmd' | less -FX" command psql --pset=pager=always "$@"
}
<file_sep>#!/bin/bash
mkdir -p ~/.local/var/
mkdir -p ~/.config/git/
mkdir -p ~/.config/procps/
mkdir -p ~/.vim/
declare -A DOT_FILES=(
["$HOME/.vim/vimrc"]=vimrc
["$HOME/.bashrc"]=bashrc
["$HOME/.tmux.conf"]=tmux.conf
["$HOME/.config/git/config"]=gitconfig
["$HOME/.config/procps/toprc"]=toprc
["$HOME/.gdbinit"]=gdbinit
["$HOME/.sqliterc"]=sqliterc
)
RC_REPO=$PWD
for path in "${!DOT_FILES[@]}"; do
[ -e $path ] && echo Skipping $path && continue
cd $(dirname $path)
ln --relative -s $RC_REPO/${DOT_FILES[$path]} $(basename $path)
done
|
c740e814456fee5e8de78f39da758ecbee565535
|
[
"Shell"
] | 2
|
Shell
|
filbi/devenv
|
de70822b93219434f87dcccae4e518af07036704
|
2f89174fa7238b704a795040bf322cddd1670340
|
refs/heads/master
|
<repo_name>niuyueyang/mobx<file_sep>/src/App.js
import React, { Component } from 'react';
import {observable} from 'mobx';
import {observer,inject} from 'mobx-react';
@inject("store") @observer
class App extends Component {
//对象,数组,map可以利用observable转化为可观察对象
arrObservable(){
var arr=[1,2,3,4,5];
var result=observable(arr);
console.log(result[0]) //1
}
objObservable(){
var obj={a:1,b:2};
var result=observable(obj);
console.log(result.a)
}
//Boolean,String,Number需要利用observable.box作为转化
StrObservable(){
var str=observable.box('hello');
var num=observable.box(1);
var bool=observable.box(true);
console.log(str.get(),num.get(),bool.get())
//set重新赋值
str.set('world');
num.set(0);
bool.set(false);
console.log(str.get(),num.get(),bool.get())
}
decoObservable(store){
console.log(store.resultCom)
//console.log(store)
// var store=new store();
// console.log(store)
}
render() {
const { store } = this.props;
return (
<div className="App">
<button onClick={()=>{this.arrObservable();}}>mobx处理数组</button>
<br/><br/>
<button onClick={()=>{this.objObservable();}}>mobx处理对象</button>
<br/><br/>
<button onClick={()=>{this.StrObservable();}}>mobx处理String,Number,Boolean</button>
<br/><br/>
<button onClick={()=>{this.decoObservable(store);}}>mobx修饰器</button>
<br/><br/>
<button onClick={()=>{store.actionChange('hello world',1)}}>mobx action</button>
</div>
);
}
}
export default App;
|
33cb893983a7deeab98e24614c6b2da13ec33695
|
[
"JavaScript"
] | 1
|
JavaScript
|
niuyueyang/mobx
|
8ca0bcf0ed40567ee82380f7f67aed127ef78484
|
b591d260cec1753f736c01a3b719ccc576d33cc8
|
refs/heads/master
|
<repo_name>ejclarke/office<file_sep>/wrangling/step3.py
# STEP 3: count how many times a character is mentioned
# before this step, I manually combined all of the caps.txt files
# to create one file with the full text of all seasons
with open('fullshow.txt', encoding = 'utf-8') as f:
lines = f.readlines()
# initiate an empty list
lst = []
# fill the list with each line in which a character's name appears
for line in lines:
for word in line.split():
if "Danny" in word:
lst.append(line)
counts = dict()
# iterate through the list, counting each time a speaker
# mentions the character we're interested in (speaker names
# end in :)
for i in lst:
for l in i.split():
if l.endswith(':'):
counts[l] = counts.get(l, 0) + 1
# sort and print only the top 10
# this was dumb and I wish I hadn't done it -
# just get the whole list and whittle it down in R
t = sorted(counts.items(), key=lambda x:-x[1])[:10]
# append the counts to the end of a mentionagg.txt file
with open('mentionagg.txt', 'a+') as open_file:
for x in t:
open_file.write("\nDANNY {0} {1}".format(*x))<file_sep>/app/app.R
library(shiny)
library(tidyverse)
library(ggplot2)
library(shinythemes)
library(tools)
library(toOrdinal)
d <- read.table('./data/count1.txt')
d <- data.frame(d)
d$season <- 1
d2 <- read.table('./data/count2.txt')
d2 <- data.frame(d2)
d2$season <- 2
d3 <- read.table('./data/count3.txt')
d3 <- data.frame(d3)
d3$season <- 3
d4 <- read.table('./data/count4.txt')
d4 <- data.frame(d4)
d4$season <- 4
d5 <- read.table('./data/count5.txt')
d5 <- data.frame(d5)
d5$season <- 5
d6 <- read.table('./data/count6.txt')
d6 <- data.frame(d6)
d6$season <- 6
d7 <- read.table('./data/count7.txt')
d7 <- data.frame(d7)
d7$season <- 7
d8 <- read.table('./data/count8.txt')
d8 <- data.frame(d8)
d8$season <- 8
d9 <- read.table('./data/count9.txt')
d9 <- data.frame(d9)
d9$season <- 9
total <- rbind(d, d2, d3, d4, d5, d6, d7, d8, d9)
total <- total[order(total$V1),]
sumdf = aggregate(total$V2, by = list(total$V1), FUN = sum)
sumdf$rank[order(-sumdf$x)] <- 1:nrow(sumdf)
# Define UI for application that draws a histogram
ui <- fluidPage(
theme = shinytheme("readable"),
# Application title
titlePanel("Character Mentions in The Office"),
# tags$style(type='text/css', ".selectize-dropdown-content {max-height: 600px; }"),
# Sidebar with a slider input for number of bins
tabsetPanel(
tabPanel("By Season",
sidebarLayout(
sidebarPanel(
sliderInput("characters",
"Number of characters:",
min = 1,
max = 35,
value = 10),
radioButtons("season",
"Season:",
choices = c("All", 1,2,3,4,5,6,7,8,9)),
width = 2
),
# Show a plot of the generated distribution
mainPanel(
plotOutput("totalmentions")
)
)),
tabPanel("By Character",
fluidPage(
sidebarPanel(
br(),
selectInput("name",
"Character:",
choices = unique(total$V1)),
br(),
uiOutput("chartext"),
width = 2),
fluidRow(
br(),
splitLayout(cellWidths = c("10%", "60%", "30%"),
br(),
plotOutput("charplot"),
br()),
br(),
splitLayout(cellWidths = c("49%", "2%", "49%"),
plotOutput("subjectplot"),
br(),
plotOutput("personplot")),
br(),
br()
), width = 11)
))
)
# Define server logic required to draw a histogram
server <- function(input, output) {
selectedseason <- reactive({if(input$season == "All"){
total} else {
subset(total, season %in% input$season)}})
chartotals <- reactive({aggregate(selectedseason()$V2, by = list(V1 = selectedseason()$V1), FUN = sum)})
plotdf = reactive({head(arrange(chartotals(),desc(x)), n = input$characters)})
output$totalmentions <- renderPlot({
ggplot(plotdf()) +
geom_col(aes(reorder(plotdf()$V1, -plotdf()$x), plotdf()$x),fill = "#325999") +
labs(x = "Character",
y = "Count",
title = titletext()) +
theme_minimal() +
theme(plot.title = element_text(size = 20, hjust = .5),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 16, angle = angle(), hjust = hjust()),
axis.text.y = element_text(size = 16)) +
guides(fill = FALSE)
})
titletext <- reactive({
if(input$season == "All"){
paste("Total Character Mentions: All Seasons")
} else {
paste("Total Character Mentions: Season", input$season)
}
})
angle <- reactive({
if(input$characters < 18){
NULL
} else {
45
}
})
hjust <- reactive({
if(input$characters < 18){
.5
} else {
1
}
})
selectedchar <- reactive({subset(total, V1 %in% input$name)})
output$charplot <- renderPlot({
ggplot(selectedchar()) +
geom_line(aes(x = season, y = V2)) +
geom_point(aes(x = season, y = V2), size = 4, color = "#325999") +
labs(x = "Season",
y = "Count",
title = paste(sep = "", input$name, "'s Total Mentions By Season")) +
theme_minimal() +
theme(plot.title = element_text(size = 20, hjust = .5),
axis.title.x = element_text(size = 18),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 16),
axis.text.y = element_text(size = 16)) +
guides(fill = FALSE) +
scale_x_continuous(breaks = c(1,2,3,4,5,6,7,8,9))
})
speakerdf = read.table('./data/mentionagg.txt', header = TRUE)
speakerdf = data.frame(speakerdf)
speakerdf$name = toTitleCase(as.character(speakerdf$name))
speakerdf$speaker = toTitleCase(as.character(speakerdf$speaker))
selectedobject <- reactive({subset(speakerdf, name %in% input$name)})
output$subjectplot <- renderPlot({
ggplot(selectedobject()) +
geom_col(aes(reorder(speaker, -count), count), fill = "#325999") +
labs(x = "Character",
y = "Count",
title = paste(sep = "", "Who says ", input$name, "'s name?")) +
theme_minimal() +
theme(plot.title = element_text(size = 20, hjust = .5),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 16),
axis.text.y = element_text(size = 16)) +
guides(fill = FALSE)
})
persondf = read.table('./data/speaker.txt', header = TRUE)
persondf = data.frame(persondf)
persondf$speaker = toTitleCase(as.character(persondf$speaker))
persondf$object = toTitleCase(as.character(persondf$object))
persondf = persondf[order(persondf$speaker, -persondf$count),]
personplotdf <- reactive({subset(persondf, speaker %in% input$name)})
ppdf = reactive({head(arrange(personplotdf(),desc(count)), n = 10)})
output$personplot <- renderPlot({
ggplot(ppdf()) +
geom_col(aes(reorder(object, -count), count), fill = "#325999") +
labs(x = "Character",
y = "Count",
title = paste(sep = "", "Which names does ", input$name, " say?")) +
theme_minimal() +
theme(plot.title = element_text(size = 20, hjust = .5),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(size = 16),
axis.text.y = element_text(size = 16)) +
guides(fill = FALSE)
})
chardf <- reactive({subset(sumdf, Group.1 %in% input$name)})
output$chartext <- renderUI({ str1 <- paste(strong("Total mentions: "),
chardf()$x,
br(),
strong("Rank: "),
toOrdinal(chardf()$rank),
"out of",
nrow(sumdf))
HTML(paste(str1[1]))
})
}
# Run the application
shinyApp(ui <- ui, server <- server)
<file_sep>/README.md
# Character Mentions in the Office
## Shiny app for <a href = "https://ejclarke.shinyapps.io/officem/">mobile</a> and <a href = "https://ejclarke.shinyapps.io/office/">desktop</a>
Using transcripts from <a href = "http://www.officequotes.net/">OfficeQuotes.Net</a>, I parsed each season of The Office to see who was mentioned the most and who talked about whom. I used Python 3, R, and a litte manual editing in Notepad++.
The result is an interactive visualization in R/Shiny, which I've optimized for mobile as well as desktop. I used the 35 characters listed as main or recurring on <a href = "https://en.wikipedia.org/wiki/List_of_The_Office_(U.S._TV_series)_characters">Wikipedia</a> and tried to incorporate common nicknames in my search parameters.
If you'd like to see the process, all of my Python code (and the source files) are in the wrangling folder. The app and mobileapp folders contain the R code that I used to create the app. This was a single day project.
<file_sep>/wrangling/step2.py
# STEP TWO: total mentions per season per character
# before this step, I did a find/replace in Notepad++
# searching for '\[.*?\]'' and replacing with '' so any names
# in action brackets weren't counted
# open the file created in step 1
# it has the full text of each episode with the speaker
# in all caps
with open('caps9.txt', encoding = 'utf-8') as f:
lines = f.readlines()
# initiate a bunch of 0 counters, 1 for each character
# there's 100% a faster/better way to do this, but this works
andycount = 0
erincount = 0
jimcount = 0
pamcount = 0
michaelcount = 0
dwightcount = 0
ryancount = 0
robertcount = 0
jancount = 0
roycount = 0
stanleycount = 0
kevincount = 0
meredithcount = 0
angelacount = 0
oscarcount = 0
phylliscount = 0
kellycount = 0
tobycount = 0
creedcount = 0
darrylcount = 0
hollycount = 0
gabecount = 0
nelliecount = 0
clarkcount = 0
petecount = 0
toddcount = 0
davidcount = 0
karencount = 0
charlescount = 0
jocount = 0
senatorcount = 0
deangelocount = 0
valcount = 0
cathycount = 0
dannycount = 0
# iterate through the words and count names (and commonly
# used nicknames)
for line in lines:
for word in line.split():
if 'Andy' in word:
andycount += 1
if 'Erin' in word:
erincount += 1
if 'Jim' in word:
jimcount += 1
if 'Pam' in word:
pamcount += 1
if 'Mike' in word or 'Michael' in word:
michaelcount += 1
if 'Dwight' in word:
dwightcount += 1
if 'Ryan' in word:
ryancount += 1
if word == 'Robert':
robertcount += 1
if 'Jan' in word:
jancount += 1
if 'Roy' in word:
roycount += 1
if 'Stanley' in word:
stanleycount += 1
if 'Kev' in word:
kevincount += 1
if 'Meredith' in word:
meredithcount += 1
if 'Angela' in word:
angelacount += 1
if 'Oscar' in word:
oscarcount += 1
if 'Phyl' in word:
phylliscount += 1
if 'Kel' in word:
kellycount += 1
if 'Toby' in word:
tobycount += 1
if 'Creed' in word:
creedcount += 1
if 'Darryl' in word:
darrylcount += 1
if 'Holly' in word:
hollycount += 1
if 'Gabe' in word:
gabecount += 1
if 'Nellie' in word:
nelliecount += 1
if 'Clark' in word:
clarkcount += 1
if 'Pete' in word:
petecount += 1
if 'Todd' in word or 'Pack' in word:
toddcount += 1
if 'David' in word:
davidcount += 1
if 'Karen' in word:
karencount += 1
if 'Charles' in word:
charlescount += 1
if word == 'Jo':
jocount += 1
if 'senator' in word.lower():
senatorcount += 1
if 'Deangelo' in word:
deangelocount += 1
if word == 'Val':
valcount += 1
if 'Cathy' in word or 'Kathy' in word:
cathycount += 1
if 'Danny' in word:
dannycount += 1
# I printed to the command line and piped to results
# to a new series of files called count1.txt - count9.txt
print('\nAndy' , andycount , '\nErin' , erincount , '\nJim' , jimcount , '\nPam' , pamcount , '\nMichael' , michaelcount , '\nDwight' , dwightcount , '\nRyan' , ryancount , '\nRobert' , robertcount , '\nJan' , jancount , '\nRoy' , roycount , '\nStanley' , stanleycount , '\nKevin' , kevincount , '\nMeredith' , meredithcount , '\nAngela' , angelacount , '\nOscar' , oscarcount , '\nPhyllis' , phylliscount , '\nKelly' , kellycount , '\nToby' , tobycount , '\nCreed' , creedcount , '\nDarryl' , darrylcount , '\nHolly' , hollycount , '\nGabe' , gabecount , '\nNellie' , nelliecount , '\nClark' , clarkcount , '\nPete' , petecount , '\nTodd' , toddcount , '\nDavid' , davidcount , '\nKaren' , karencount , '\nCharles' , charlescount , '\nJo' , jocount , '\nSenator' , senatorcount , '\nDeangelo' , deangelocount , '\nVal' , valcount , '\nCathy' , cathycount , '\nDanny' , dannycount)<file_sep>/wrangling/step1.py
# STEP ONE: convert speaker names to all caps
# each season's full text is accessed from a separate file
# the file is formatted so that each line of dialogue is on a separate line
with open('season9.txt', encoding = 'utf-8') as f:
lines = f.readlines()
# create an empty list for appending lines
lst = []
# iterate through the words in the file
for line in lines:
for word in line.split():
# words ending with : are a speaker
if word.endswith(':'):
# create a new line, all caps the speaker's name for easier searching later
word = "\n" + word.upper()
# reappend the word
lst.append(word)
else:
lst.append(word)
# write to a separate file
# everything is the same except the speaker's name is in all caps
with open('caps9.txt', 'w') as write_file:
print(' '.join(lst), file = write_file)
|
ab7f820ed7c6d84c88d46fa71fb6b8390d3ecbd7
|
[
"Markdown",
"Python",
"R"
] | 5
|
Python
|
ejclarke/office
|
a5826a382d793687561c4e9abdafd927ac206fca
|
a79fc82eb495202289c37169424e7031c2c6fe7c
|
refs/heads/main
|
<file_sep>#include<stdio.h>
main(){
signed short a = 0xf0f0;
unsigned short b = 0xf0f0;
b = (unsigned)(((unsigned)(b=a)) >> 8);
printf("%x\n",b);
printf("%x\n",2**16);
}<file_sep>
int func1( int a){
static int b=1;
printf("%d\n",b++);
return a;
}<file_sep>main(){
int i;
// for (i=0;i<255;i++)
// printf("\t %d = %c \n",i,i);
// printf(" %c\n%c%c%c\n%c %c\n",79,47,124,92,47,92);
printf(" %c\n%c%c%c\n%c %c\n",79,47,179,92,47,92);
}<file_sep>#include<stdio.h>
void main(){
int i,j=20;
for ( i=0; i<j; i-- )
printf("%d. Hello World\n", i);
}<file_sep>
void func2(int *c){
printf("value recieved from func1:\n c = %d\n",c);
printf("Value when Rx in func2: %d\n",*c);
*c = (*c) * 10;
printf("Value changed in func2: %d\n",*c);
}<file_sep>static int var=10;<file_sep>
#ifndef SRINIVASA
#define SRINIVASA
void disp(int, int);
void square(int, int);
#endif
<file_sep>
#include<stdio.h>
#include<malloc.h>
main(){
int i,j;
//char ch=getche();
//j = ch;
i = getch();
//printf("\nascii = %u\t%c\n",j,ch);
printf("\nscancode = %u\n",i);
}<file_sep>
#include<stdio.h>
//#include"aadrs_value.h"
//#include"addrs_func2.h"
#define swap(a,b) (((a>b) && (c=a)) || (c=b) )
int main1(){
static int a = 1;
printf("Before Tx in main: a = %d\n",a);
func1(&a);
printf("After Rx in main: a= %d\n",a);
return 0;
}
int main(){
int a=5,b=10,c;
swap(a,b);
printf("c=%d\n",c);
return 0;
}<file_sep>#include<stdio.h>
#define case1 1
#define case2 2
void main(){
const int CASE1=1;
int idx;
for ( idx=0; idx<3; idx++)
{
switch(idx)
{
case case1: printf("Case = %d\n", idx);
break;
case case2: printf("Case = %d\n", idx);
break;
default: printf("Default Case = %d\n", idx);
break;
}
}
}<file_sep>
#ifndef SRINIVASA
#define SRINIVASA
char* select_name(int, int);
void random_index(int);
void key_set();
void user_try(char *, int);
void get_name(char*, int);
#endif<file_sep>#include<stdio.h>
main(){
FILE *src_ptr,*dest_ptr;
char ch;
src_ptr = fopen("file.c", 'r');
dest_ptr = fopen("out.txt", 'w');
fclose(src_ptr);
fclose(dest_ptr);
}<file_sep>#include<stdio.h>
#include<conio.h>
#include"magic.h"
int test_func(void);
int main(){
int first, num_sqr;
printf("Enter the first number:\n");
scanf("%d",&first);
printf("Enter the number of rows/coloumns:\n");
scanf("%d",&num_sqr);
if(num_sqr%2 == 0)
{
printf("Invalid number, enter an odd number:\n");
main();
}
else
square(first,num_sqr);
return 0;
}
<file_sep>
void rev_func(int val){
int temp;
while(val/10)
{
val= val%10;
}
printf("%d",val);
}<file_sep>
#include<stdio.h>
/*
#define SETBIT(word,pos) ((word) |= (1<<(pos)))
#define CLRBIT(word,pos) ((word) &= ~(1<<(pos)))
#define PUTBIT(word,pos,val) ((val) ? SETBIT(word,pos) : CLRBIT(word,pos))
#define SetBit8(ptr,pos,val) PUTBIT(*((uint8 *)ptr),pos,val)
*/
main(){
short int a= 0x00fd;
printf("1 = %x\n",a);
//SetBit8(&a,1,1);
printf("2 = %x\n",a);
}<file_sep>
#ifndef SRINIVASA
#define SRINIVASA
void func2(int *);
#endif
<file_sep>
#include<stdio.h>
#include"aadrs_value.h"
#include"addrs_func2.h"
int main(){
static int a = 1;
printf("Before Tx in main: a = %d\n",a);
printf("Addrs of a in main:\n &a = %d\n",&a);
func1(&a);
printf("After Rx in main: a= %d\n",a);
return 0;
}
<file_sep>
void square(int first, int num_sqr){
int i,j,a[16][16];
int last = first + (num_sqr*num_sqr)-1;
for(i=0;i<num_sqr;i++)
for(j=0;j<num_sqr;j++)
{
if (i==0 && j==num_sqr/2)
a[i][j] = first;
else
a[i][j] = 0;
}
i=0;
j=num_sqr/2;
while(first++ < last){
i--;
j++;
if(j>=num_sqr && i==0)
{
j = 0;
a[i][j] = first;
}
else
if(i<1 && j>=num_sqr)
{
if(!a[i+2][j-1])
{
i = i+2;
j = j-1;
a[i][j] = first;
}
else
{
j = 0;
a[i][j] = first;
}
}
else
if(i<0)
{
i = num_sqr-1;
a[i][j] = first;
}
else
if(j>=num_sqr)
{
j = 0;
a[i][j] = first;
}
else
{
if(!a[i][j])
a[i][j] = first;
else
{
i = i+2;
j = j-1;
a[i][j] = first;
}
}
}
disp(a,num_sqr);
}
<file_sep>
int cc,aa,bb;
#define SRI(num1) cc=5
#undef SRI
#define SRI(num2) enum num2 {aa,bb}
main(){
int num1;
SRI(num1);
SRI(num2);
printf("aa=%d\tbb=%d\tcc=%d\n",aa,bb,cc);
}<file_sep>
#include<stdio.h>
#include"func1.h"
int main(){
int a=1,i,ret;
for(i=0;i<5;i++)
{
ret = func1(a);
}
return 0;
}<file_sep>#define MAX 5
char* select_name(int choice, int random)
{
char *clients[MAX] = {"HONDA","TOYOTA","NISSAN","VOLVO","MITSUBISHI"};
char *country[MAX] = {"INDIA","GERMANY","AMERICA","JAPAN","ITALY"};
char *product[MAX] = {"SENSORS","ECU","HEATER","TESTERS","BLAUPUNKT"};
char *department[MAX] = {"DIESEL","GASOLINE","TRANSLATION","MULTIMEDIA","EMERGING"};
switch(choice){
case 1:
printf("\nCatagory:- CLIENTS\n\n");
return clients[random];
break;
case 2:
printf("\nCatagory:- COUNTRY\n\n");
return country[random];
break;
case 3:
printf("\nCatagory:- PRODUCT\n\n");
return product[random];
break;
case 4:
printf("\nCatagory:- DEPARTMENT\n\n");
return department[random];
break;
default:
printf("Enter a valid choice please:\n");
return 1;
break;
}
}
void random_index(int choice)
{
int random;
char *name;
char next_chance;
do
{
random=rand();
}while(!(random<MAX && random>=0));
name = select_name(choice, random); // select a random name
get_name(name,choice); // link to impl
return 0;
}
<file_sep>void key_set(){
char alpha[26];
int i;
printf("\n\n");
for(i=0;i<26;i++)
alpha[i]=65+i;
for(i=0;i<26;i++)
printf("%c\t",alpha[i]);
printf("\n\n");
}<file_sep>#include<stdio.h>
main()
{
printf("HI\n");
}
<file_sep>
int main1(){
double signed i=0;
printf("Hello");
for(;;);
printf("world %d\n",i);
printf("size=%d\n",sizeof(i));
return 0;
}
int main(){
int val = 12345;
printf("\nReverse=%d\n",rev_func(val));
return 0;
}<file_sep>
main(){
signed long a=0xa0ffffff;
signed long b;
b=a>>16;
printf("a=%x\nb=%x\n",a,b);
}<file_sep>#include<stdio.h>
#include "static.h"
main(){
printf("%i\n", var);
}
<file_sep>
#define CHANCES 5 // no of error chances
void user_try(char *name, int choice){
char input_ch;
int i;
int errors=0,occur=0,status=0;
char *cast; // for character wise access of name
char temp[30]; // to hold character array of name
char disp_arr[30];
cast = (char *)name;
for(i=0;i<30;i++)
{
temp[i] = 0; // clear temp and disp_arr
disp_arr[i] = 0;
}
for(i=0;i<strlen(name);i++)
temp[i] = *(cast++); // temp = cast
while(1){
occur=0;
if(errors<5)
{
input_ch = toupper(getch());
printf("\r");
for(i=0;i<=strlen(name);i++)
{
if(strcmp(disp_arr,name)) // equal => returns 0
{
if( temp[i] == input_ch)
{
disp_arr[i]=input_ch;
occur=1;
}
}
printf(" %c ",disp_arr[i]);
} // for //
if(!occur)
{
errors++;
occur=0;
}
printf(" \t%d ",CHANCES-errors); // chances left
if(!strcmp(disp_arr,name))
{
printf("\n\nYOU WON IN DECODING:\n%s\n\n",name);
status = 1;
return 0;
}
} // if
else
break;
} // while
if(!status)
{
printf("\nSoryy you lost\n\n");
printf("The Word was %s\n\n",name);
printf("Oops! you are HANGED!!!\n\n");
printf(" %c\n%c%c%c\n%c %c\n\n",79,47,179,92,47,92); // hang
return 0;
}
}
void get_name(char *name,int choice){
int i;
int a[30];
for(i=0;i<strlen(name);i++)
{
a[i] = '-';
printf(" %c ",a[i]);
}
printf("\tChances left for you:- %d\n",CHANCES);
printf("\n");
user_try(name,choice); //user input
return 0;
}
<file_sep>
#ifndef SRINIVASA
#define SRINIVASA
int func1( int);
#endif
<file_sep>#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
#include "math.h"
#include "string.h"
#include "ctype.h"
#include "malloc.h"
#include "time.h"
/*
For Debugging
gcc try.c -ggdb
gdb a.exe
*/
/********************************************************************************************/
/*
Write a program to implement the Fibonacci series
Sorting and searching algorithms...
aphabetical order and name search
*/
int main1() {
int var=0.5;
if( -0.5 <= var <= 0.5 )
printf("Correctly tested\n");
else
printf("InCorrectly tested\n");
return (0);
}
/********************************************************************************************/
main2(){
char *p=0;
char **pp=0;
printf("%d\n",(++p) );
printf("%d\n",(++pp) );
}
/********************************************************************************************/
main3(){
int a,b;
int *x=&a, *y=&b;
printf("%i\n", (int)(x-y));
printf("%i\n", ((int)x-(int)y));
}
/********************************************************************************************/
main4(){
int x=10;
int y=20;
int *p=&x;
int **pp=&p;
*pp=&y;
printf("%d\t%d\n",*p, **pp);
}
/********************************************************************************************/
func(char *p){
char arr[6]="World";
// p=arr;
*p=arr[4];
//return (arr);
}
main5(){
char array[6]="Hello", *p=array;
func(p);
printf("%s\n",p);
}
/********************************************************************************************/
main6(){
int a=111, b=222, c;
(0 && (c=a) ) || (c=b);
printf("c=%i\n",c);
}
//#define print(n) (printf("token#n"=%d\n",token##n) )
/********************************************************************************************/
main7(){
//print(9);
}
/********************************************************************************************/
#define NEG(a) -a+1
main8(){
int x=3;
printf("%d\n", NEG(NEG(x)));
}
/********************************************************************************************/
/*
#define ONE 1
#define TWO 2
#define ONE TWO
#define TWO ONE
main9(){
printf("ONE=%d\tTWO=%d",ONE,TWO);
}
*/
/********************************************************************************************/
/*
main10(){
short var=0x2211;
char *ptr = &var;
printf("%x",*ptr);
}
*/
/********************************************************************************************/
main11(){
int a=2,b=10;
// printf("%d",a+++++b);
}
/********************************************************************************************/
main12(){
struct AA
{
int bit:3;
};
struct AA a;
a.bit=0xff;
printf("%d",a.bit);
}
/********************************************************************************************/
main13(){
char *str1="SRI", *str2="RAMA";
int i;
printf("1)%s\t%s",str1,str2);
for(i=strlen(str1);i<strlen(str2);i++)
{
*(str1+i) = *(str2+i);
}
*( str1+strlen(str1)+strlen(str2) ) = '\0' ;
printf("\n2)%s\t%s",str1,str2);
}
/*******************************************************************************************/
/*************************** MAGIC SQUARE ***************************************/
/*******************************************************************************************/
/*
void disp(int a[16][16], int num_sqr){
int i,j;
printf("\n\n");
for(i=0;i<num_sqr;i++)
{
for(j=0;j<num_sqr;j++)
printf("%d\t",a[i][j]);
printf("\n\n");
}
printf("\n\n");
}
void square(int first, int num_sqr){
int i,j,a[16][16];
int last = first + (num_sqr*num_sqr)-1;
for(i=0;i<num_sqr;i++)
for(j=0;j<num_sqr;j++)
{
if (i==0 && j==num_sqr/2)
a[i][j] = first;
else
a[i][j] = 0;
}
i=0;
j=num_sqr/2;
while(first++ < last){
i--;
j++;
if(j>=num_sqr && i==0)
{
j = 0;
a[i][j] = first;
}
else
if(i<1 && j>=num_sqr)
{
if(!a[i+2][j-1])
{
i = i+2;
j = j-1;
a[i][j] = first;
}
else
{
j = 0;
a[i][j] = first;
}
}
else
if(i<0)
{
i = num_sqr-1;
a[i][j] = first;
}
else
if(j>=num_sqr)
{
j = 0;
a[i][j] = first;
}
else
{
if(!a[i][j])
a[i][j] = first;
else
{
i = i+2;
j = j-1;
a[i][j] = first;
}
}
}
disp(a,num_sqr);
}
int main(){
int first, num_sqr;
printf("Enter the first number:\n");
scanf("%d",&first);
printf("Enter the number of rows/coloumns:\n");
scanf("%d",&num_sqr);
if(num_sqr%2 == 0)
{
printf("Invalid number, enter an odd number:\n");
main();
}
else
square(first,num_sqr);
return 0;
}
*/
/*******************************************************************************************/
/*******************************************************************************************/
main14(){
char *ptr1="Sri", *ptr2="Rama";
printf("&ptr1=%d\n&ptr2=%d\nptr1=%d\nptr2=%d\n*ptr1=%s\n*ptr2=%s\n",&ptr1,&ptr2,ptr1,ptr2,ptr1,ptr2);
printf(( &ptr1>&ptr2)?"%s%s":"%s", ptr1,ptr2);
}
/********************************************************************************************/
main15()
{
unsigned unsign = 0 ;
signed sign = -1 ;
( unsign > sign ) ? printf("unsign > sign") : printf("sign > unsign") ;
}
/********************************************************************************************/
void change()
{
/* Write something in this function so that the output of printf in main
function should give 5 . Do not change the main function */
}
main16()
{
int i=5;
change();
i=10;
printf("%d",i);
}
/********************************************************************************************/
main17(){
struct str{
int a;
short int b;
int c;
}st={11,2,3};
/* st.a=st.a;
st.b=2;
st.c=3;
*/
/* st=st;
&st;
st.a=st.a;
st.b=st.b;
st.c = st.c;
printf("st.c=%d\n",st.c);
*/
printf("st=%d\n&st=%p\nst=%d\nst.a=%d\nst.b=%d\n&st=%d\nst.c=%d\n",st,&st,st,st.a,st.b,&st,st.c);
printf("st = %d\n",st);
printf("&st = %p\n",&st);
printf("st = %d\n",st);
printf("st.a = %d\n",st.a);
printf("st.b = %d\n",st.b);
printf("&st = %p\n",&st);
printf("st.c = %d\n",st.c);
}
/********************************************************************************************/
main18(){
int a;
struct st{
int a;
int b;
}st;
printf("%p\n%p\n",(&a),&st );
}
/********************************************************************************************/
main19(){
char (*p1)[10] , *p2[10], *(p3[10]);
printf("p1 = %i\np2 = %i\np3 = %i\n",sizeof(p1),sizeof(p2),sizeof(p3) ) ;
}
/********************************************************************************************/
main20(){
/*
while()
{
printf("While in Endless Loop\n");
}
*/
for(;;) printf("for in Endless Loop\n");
/* for(;;)
; // Necessary
*/
}
/********************************************************************************************/
int v,i,j,k,l,s,a[99];
int main21(int argc, char* argv[ ])
{
for(scanf("%d",&s);*a-s;v=a[j*=v]-a[i],k=i<s,
j+=(v=j<s&&(!k&&!!printf(2+"\n\n%c"-(!l<<!j),
" #Q"[l^v?(l^j)&1:2])&&++l||a[i]<s&&v&&v-i+j&&v+i-j))
&&!(l%=s),v||(i==j?a[i+=k]=0:++a[i])>=s*k&&++a[--i])
;
}
/********************************************************************************************/
#define M 5;
#define N 10;
main22()
{
int sum = 1;
sum = sum + M + N;
printf("sum=%d\n", sum );
}
/********************************************************************************************/
#define NEGVE(a) -a
main23(){
int x=3;
printf("%d\n", NEGVE(NEGVE(x)));
}
/********************************************************************************************/
int main24()
{
char number=-64;
char numberDiv2;
numberDiv2 = number >> 1;
printf("%d",numberDiv2);
}
/********************************************************************************************/
main25(l
,a,n,d)char**a;{
for(d=atoi(a[1])/10*80-
atoi(a[2])/5-596;n="@NKA\
CLCCGZAAQBEAADAFaISADJABBA^\
SNLGAQABDAXIMBAACTBATAHDBAN\
ZcEMMCCCCAAhEIJFAEAAABAfHJE\
TBdFLDAANEfDNBPHdBcBBBEA_AL\
H E L L O, W O R L D! "
[l++-3];)for(;n-->64;)
putchar(!d+++33^
l&1);}
/********************************************************************************************/
main26(){
int i1=5;
register int i2=22;
register int i3=33;
struct st{
int a;
int b;
int c;
}st={1,2,3};
for(i1=0;i1<10;)
printf("%d\n",i1++);
i2+=3;
i3+=2;
printf("%d\t%d\n",i2,i3);
printf("Give an enter\n");
getch();
}
/********************************************************************************************/
int factorial(int num){
if ( (num == 0) || (num == 1) )
{
return (1);
}
else if(num<0)
{
printf("Enter a positive number\n");
exit(0);
}
else
{
num*=factorial(num-1) ;
}
printf("num=%d\n",num);
return (num);
}
main27(){
int number,soln;
printf("Enter a positive number for factorial\n");
scanf("%d",&number);
soln = factorial(number);
printf("Factorial of %d = %d",number, soln);
}
/********************************************************************************************/
main28()
{
char i=0;
int (*x)[10], *y[10];
for(;i>=0;i++) ;
printf("%d\n",i);
printf("Size of (*x)[10]=%d\nSize of *y[10]=%d\n",sizeof(x),sizeof(y) );
}
/********************************************************************************************/
main29(){
int a=2;
int b=9;
int c=1;
while(b)
{
if( ( (b%2)==1 ) )
c=c*a;
a=a*a;
b=b/2;
}
printf("%d\n",c);
}
/********************************************************************************************/
#define STYLE1 char
main30()
{
typedef char STYLE2;
STYLE1 x;
STYLE2 y;
x=255;
y=254;
printf("%d %d\n",x,y);
}
/********************************************************************************************/
main31(){
char *pDestn,*pSource="I Love You Daddy";
pDestn=(char *)malloc(strlen(pSource));
strcpy(pDestn,pSource);
printf("%s\n",pDestn);
free(pDestn);
}
/********************************************************************************************/
/*
main32(){
char a[5][5],flag=0;
a[0][0]='A';
flag=((a==*a)&&(*a==a[0]));
printf("a = %d\n",a);
printf("*a = %d\n",*a);
printf("a[0] = %d\n",a[0]);
printf("flag=%d\n",flag);
}
*/
/********************************************************************************************/
main33(){
char a =0xAA ;
int b ;
b = (int) a ;
printf("Before = %x\n",b);
b = b >> 4 ;
printf("After = %x",b);
}
/********************************************************************************************/
main34(){
int d=5;
printf("%f",d);
}
/********************************************************************************************/
main35()
{
int i;
for(i=1;i<4;i++){
switch(i){
case 1:printf("%d",i);break;
case 2:printf("%d",i);break;
case 3:printf("%d",i);break;
}
switch(i) case 4:printf("%d",i);
}
printf("\ni=%d\n",i);
}
/********************************************************************************************/
main36()
{
char *s="\12345s\n";
printf("sizeof s = %d\n",sizeof(s));
printf("strlen s = %d",strlen(s));
}
/********************************************************************************************/
main37()
{
unsigned i=1; /* unsigned char k= -1 => k=255; */
signed j=-1; /* char k= -1 => k=65535 */
/* unsigned or signed int k= -1 =>k=65535 */
if(i<j)
printf("less");
else
if(i>j)
printf("greater");
else
if(i==j)
printf("equal");
}
/********************************************************************************************/
int f();
main38()
{
f(1);
f(1,2);
f(1,2,3);
}
f(int i,int j,int k)
{
printf("%d\t%d\t%d\n",i,j,k);
}
/********************************************************************************************/
main39()
{
int i=7;
printf("%d\n",(++i)*(++i) );
printf("%d\n",(i++)*(i++) );
printf("%d\n",(++i)*(i++) );
printf("%d\n",(i++)*(++i) );
}
/********************************************************************************************/
main40(){
static i=3;
printf("%d\t",i--);
(i>0) ? main():printf("\n");
printf("%d\t",++i);
}
/********************************************************************************************/
main41(){
char *s[]={ "dharma","hewlett-packard","siemens","ibm"};
char **p;
p=s;
printf("%s\n",++*p );
printf("%s\n",*p++ );
printf("%s\n",++*p );
}
/********************************************************************************************/
main42(){
int a=0,b,c;
b=((a=0))?2:3;
printf("%d\n",b);
if(b=0)
printf("b=1\n");
else
printf("b=0\n");
printf("c=%d\n",(c=0) );
}
/********************************************************************************************/
main43(){
int a=2,c;
switch(a){
case 2: c=3;
case 3: c=4;
case 4: c=5;
case 5: c=6;
default: c=0;
}
printf("c=%d\n",c);
}
/********************************************************************************************/
main44(){
int *b;
*b=3;
printf("*b=%d\n",*b);
}
/********************************************************************************************/
main45(){
int i=0;
for(i=0;i<20;i++)
{
switch(i){
case 0:i+=5;
case 1:i+=2;
case 5:i+=5;
default: i+=4;
break;}
printf("%d,",i);
}
}
/********************************************************************************************/
main46()
{
int i;
char a[]="String";
char *p="New Sring";
char *Temp;
Temp=a;
//a=malloc(strlen(p) + 1);
strcpy(a,p); //Line number:9//
p = malloc(strlen(Temp) + 1);
strcpy(p,Temp);
printf("%s\n%s",a,p);
free(p);
free(a);
}
/********************************************************************************************/
main47(){
unsigned int x=-1;
int y;
y = ~0;
printf("%u\t%u\n",x,y);
if(x == y)
printf("same");
else
printf("not same");
}
/********************************************************************************************/
char *gxxx()
{static char xxx[1024];
printf("Base addr of array = %p\n",xxx);
return xxx;
}
main48()
{char *g="string";
strcpy(gxxx(),g);
printf("1. %s\n", gxxx());
g = gxxx();
strcpy(g,"oldstring");
printf("The string is : %s",gxxx());
}
/********************************************************************************************/
/*
int global1 = 11; /* Data Segment, Value retained at that address even after return *
static int global2 = 22; /* Data Segment, Value retained at that address even after return *
main49(){
static int stat = 33; /* Data Segment, Value retained at that address even after return *
char arr[]={'S','R','I','N','I','V','A','S','A'}, *local_ptr=arr; /* Stack, Value cleared at that address after return *
char *str_ptr = "Hello World"; /* Data Segment, Value retained at that address even after return *
printf("global1 \t 0x%p \t %d\n",&global1,global1);
printf("static global2 \t 0x%p \t %d\n",&global2,global2);
printf("static local \t 0x%p \t %d\n",&stat,stat);
printf("ch \t\t 0x%p \t %c\n",&ch,ch);
printf("local \t\t 0x%p \t %d\n",&local,local);
printf("*ptr \t\t 0x%p \t %d\n",ptr,*ptr);
printf("str_ptr \t 0x%p \t %s\n",str_ptr,str_ptr);
}
*/
/********************************************************************************************/
main50(){
struct sample1
{
unsigned char m1 __attribute__((__packed__));
unsigned short m2 __attribute__((__packed__));
unsigned long m3 __attribute__((__packed__));
};
struct sample2
{
unsigned char m1;
unsigned short m2;
unsigned long m3;
} __attribute__((__packed__));
struct sample3
{
unsigned char m1;
unsigned short m2;
unsigned long m3;
} ;
struct sample4
{
unsigned char m1;
unsigned long m3;
unsigned short m2;
} ;
printf("sizeof sample1 is %d\n",sizeof(struct sample1) );
printf("sizeof sample2 is %d\n",sizeof(struct sample2) );
printf("sizeof sample3 is %d\n",sizeof(struct sample3) );
printf("sizeof sample4 is %d\n",sizeof(struct sample4) );
}
/********************************************************************************************/
int var_x=10;
#define DEF 3
//#include"2.c"
//var_x=20;
#ifdef DEF
#undef DEF
#define DEF 5
#endif
main51(){
printf("%d\n",var_x);
}
/********************************************************************************************/
main52(){
struct st{
int a;
int b;
int c;
}st = {11,22,33};
printf("st = %d\n",st);
printf("&st = %p\n",&st);
printf("st = %d\n",st);
printf("st.a = %d\n",st.a);
printf("st = %d\n",st);
printf("st.b = %d\n",st.b);
printf("&st = %d\n",&st);
printf("st = %d\n",st);
printf("st.c = %d\n",st.c);
}
/********************************************************************************************/
main53(){
int a=5,b=10;
printf("a = %d\tb = %d\n",a,b);
a^=b^=a^=b;
printf("a = %d\tb = %d\n",a,b);
}
/********************************************************************************************/
/*
main54(){
const int a=1;
const int *p=&a;
int b=10,c=20;
printf("a = %d\n", a);
printf("*p = %d\n", *p);
a=2;
printf("\n");
printf("a = %d\n", a);
printf("*p = %d\n", *p);
*p=3;
printf("\n");
printf("a = %d\n", a);
printf("*p = %d\n", *p);
a=b+c;
printf("\n");
printf("a = %d\n", a);
printf("*p = %d\n", *p);
p=&b;
printf("\n");
printf("a = %d\n", a);
printf("*p = %d\n", *p);
}
*/
/********************************************************************************************/
main55(){
/* short a=32767;
long b;
b = a<<16 ;
printf("%d\n",b);
*/
char a=-1;
printf("%d\n", a<<7);
printf("%d",a);
}
/********************************************************************************************/
func_arr(int *arr[5]){
int i;
for(i=0;i<5;i++)
printf("%d\t",*(arr[i]) );
printf("\n");
}
main56(){
int a=11,b=22,c=33,d=434,e=55;
int *a1=&a,*b1=&b,*c1=&c,*d1=&d,*e1=&e;
int *arr[5] = {a1, b1, c1, d1, e1};
printf("&a=%i\ta1=%i\t*a1=%i\t&a1=%i\n",&a,a1,*a1, &a1);
printf("arr=%i\t&arr=%i\tarr[0]=%i\t&arr[0]=%i\n",arr,&arr,arr[0],&arr[0] );
func_arr(arr);
}
/********************************************************************************************/
main58()
{
int a;
for(a=0;a<=255;a++)
printf("a=%d\t~a=%d\n", a, ~a);
}
/********************************************************************************************/
main59(){
unsigned char i;
signed char a;
for(i=0;i<255;i++)
{
a = (signed char) i;
printf("i=%d\ta=%d\n",i,a);
}
}
/********************************************************************************************/
main60(){
unsigned char a = 255;
signed int b;
unsigned int c;
signed short d;
printf("\na = %i\t\t(signed)a = %i\n\n",a,(signed char)a);
b = (signed int)a ;
printf("b = (signed int) a => b=%i, a=%i\n",b,a);
c = (unsigned int)b ;
printf("c = (unsigned int) b => c=%i, b=%i\n",c,b);
b = (signed int)c ;
printf("b = (signed int) c => b=%i, c=%i\n",b,c);
d = (signed short)b ;
printf("d = (signed short) b => d=%i, b=%i\n",d,b);
}
/********************************************************************************************/
main61(){
int a=0, i=5,j=5, arr[i][j];
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
{
if(j==3)
{
arr[i][j]= ++a ;
break;
}
}
if(i==4)
break;
}
printf("j=%d\ti=%d\n",j,i) ;
/*
for(i=0; i<5; i++)
{
for(j=0; j<5; j++)
{
if(1)
{
printf("\t%d",arr[i][j]) ;
break;
}
}
if(1)
{
printf("\n");
break;
}
}
*/
}
/****************************************************************************************/
void usleep(unsigned long u)
{
clock_t end, start = clock();
if (start == (clock_t) -1) return;
end = start + CLOCKS_PER_SEC * (u / 1000000.0);
while (clock() != end) ;
}
int main62(void)
{
int i;
for (i = 0; i < 20; i++)
{
usleep(500000);
/* puts("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n");
puts("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n\n");
printf("%*s\n", 10 + i * 2, " __@ ");
printf("%*s\n", 10 + i * 2, " _`\\<,_");
printf("%*s\n", 10 + i * 2, "(*)/ (*) ");
*/
}
return 0;
}
/***************************************************************************************/
#define MSB_POS 8
main63(){
int c , a=30 , b=03;
int z , x=32 , y=5;
c = ( ( a *100 ) + b ) ;
printf("a=%d\nb=%d\nc=%d\n",a,b,c );
z= x>>4 & 1 ;
printf("x=%d\ny=%d\nz=%d\n",x,y,z );
}
/*****************************************************************************************/
main64(){
short int a=-38;
unsigned short int b;
b=a;
printf("%x\n",b);
}
/*****************************************************************************************/
main65(){
char a=0;
char b=0x07;
a=0x07&0x07;
printf("%d\n",a);
}
/*****************************************************************************************/
main66(){
int a,b=1;
(a=b)?printf("True"):printf("False");
if(fprintf(stderr,"\nHello"))
printf("\nHello True");
}
/*****************************************************************************************/
main(){
struct s{
signed int a1;
unsigned short int a2;
signed int a3;
short signed int a4;
};
struct s str1={0,0,0,0};
struct s str2={0xAAAAAAAA,0xBBBB,0xCCCCCCCC,0xDDDDDDDD};
str1=str2;
int a;
printf("%i\n",sizeof(str1) );
for(a=0;a<4;a++)
{
// *(&(s1.a1)+a) = a;
printf("%x\n",*(&(str1.a1)+a) ) ;
}
}
<file_sep>main(){
int i=1;
if(--i)
printf("HI\n");
printf("%d\n",i);
}
<file_sep>
#ifndef SRINIVASA
#define SRINIVASA
void rev_func(int);
#endif<file_sep>#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<ctype.h>
#include<conio.h>
#include"hang.h"
main(){
int choice;
printf("\n\tWELCOME TO HANG-MAN\n");
printf("==================================\n");
printf("\t\t:-Srinivasa.K.N\n\t\t:ver 1.5\n\n\n");
printf("BOSCH Categories:\n");
printf("-----------------\n");
printf("1. Client\n2. Country\n3. Product\n4. Department\n");
printf("\nEnter your field of interest:\n");
scanf("%d",&choice);
if(choice<1 || choice>4)
{
printf("\n\nEnter a valid choice\n\n");
main();
}
else
{
// key_set(); // in disp
random_index(choice); // database
}
while(1){
printf("Would U like to continue:?\n\n");
if(toupper(getch()) == 'Y')
{
printf("Want to change the catagory:?\n\n");
if(toupper(getch()) == 'Y')
{
system("cls");
main();
}
else
{
system("cls");
random_index(choice);
}
}
else
exit(0);
}
return 0;
}<file_sep>
void func1( int * b){
(*b) +1;
printf("Value in func1: %d\n", *b);
func2(&b);
printf("Value after unwinding of func2:= %d\n",*b);
}<file_sep>#include<stdio.h>
#include<conio.h>
void main1() {
int array1[5]={1,2,3,4,5}, array2[5]={11,22,33,44,55}, array3[5]={111,222,333,444,555};
int array4[2][2]={66,77,88,99};
int idx, i, *ptr1, *ptr2, *ptr3, *ptr4[3];
ptr1 = array1;
ptr2 = &array2[0];
ptr3 = array3;
ptr4[0] = array1;
ptr4[1] = array2;
ptr4[2] = array3;
for(idx=0; idx<5 ; idx++)
{
printf("%d\t",*(ptr1+idx));
}
for(idx=0; idx<5 ; idx++)
{
printf("%d\t",*(ptr2+idx));
}
for(idx=0; idx<5 ; idx++)
{
printf("%d\t",*(ptr3++));
}
printf("\n");
/*
for(idx=0; idx<2 ; idx++)
{
// printf("%d\t%d\t",*(ptr4[idx]), *(ptr4[idx+1]) );
printf("%d\t",*(ptr4[idx]) );
}
printf("\n");
*/
printf("Array of pointers:\n");
for(idx=0; idx<3; idx++)
{
for(i=0; i<5; i++)
{
printf("%d\t", *ptr4[i] );
}
printf("%d\t", *ptr4[idx] );
}
}
void main2() {
int array1[5]={1,2,3,4,5}, array2[5]={11,22,33,44,55}, array3[5]={111,222,333,444,555};
int idx, i, *ptr4[3];
ptr4[0] = array1;
ptr4[1] = array2;
ptr4[2] = array3;
printf("Array of pointers:\n");
/*
for(idx=0; idx<3; idx++)
{
for(i=0; i<5; i++)
{
printf("%d\t", *(ptr4+i) );
}
printf("\n%d\t", *ptr4[idx] );
}
*/
for(i=0; i<3; i++)
{
for(idx=0; idx<5; idx++)
{
printf("%d\t", *(ptr4[i]+idx) );
}
printf("\n%d\t\n", *ptr4[i+1] );
}
printf("\n");
}
void main(){
signed int sint32=0;
unsigned int uint32=0;
printf("size of sint32 = %i\nsize of uint32 = %i\n",sizeof(sint32),sizeof(uint32));
printf("sint32\t\tuint32\n-------\t\t-------\n");
/*for(sint32=0xffffff,uint32=0xffffff ;sint32,uint32; sint32++,uint32++)
{
//printf("%i\t\t%i\n",sint32,uint32);
}*/
printf("%i\t\t%i\n",sint32-1,uint32-1);
}<file_sep>#include<stdio.h>
#include<conio.h>
void main(){
int *ptr1, *ptr2, variable=5, variable_array[5]={0,11,22,33,44};
ptr1 = &variable;
ptr2 = variable_array;
printf("\nptr1 = %d\n", *ptr1);
printf("pointer array values :\n");
for(int i =0; i<5; i++)
{
printf("ptr2[%d] = %d\t",i, *(ptr2+i) );
}
}<file_sep>#include<stdio.h>
#include<conio.h>
void main(){
unsigned char a=0;
while(++a)
{
printf("%i\n", a);
}
getch();
}<file_sep>
#ifndef SRINIVASA
#define SRINIVASA
void func1( int * );
#endif<file_sep>
int main(){
signed short val=0x7fff,val1=0;
printf(" %d\t%x\n",1,-1);
printf(" %d\t%x\n",val,val);
val = -val;
printf("%d\t%x\n",val,val);
val = (signed short)val;
printf("%i\t%x\n",val,val);
return 0;
}<file_sep>
#include<stdio.h>
#define CLRBIT(a,bp) a = ( a & ~(1 << bp ) )
main(){
signed short x=32768;
int a=0xff, *p=&a, bp=3;
printf("\nBefore clearing \n%x\n",a);
// CLRBIT(a,bp);
CLRBIT(*p,bp);
printf("\nAfter clearing \n%x\n",a);
printf("\n%i\n",x);
}<file_sep>#include<stdio.h>
#include<conio.h>
void main1(){
int i, *ptr1, *ptr2, variable=5, variable_array[5]={0,11,22,33,44};
ptr1 = &variable;
ptr2 = variable_array;
printf("\nptr1 = %d\n", *ptr1);
printf("pointer array values :\n");
for( i =0; i<5; i++)
{
printf("ptr2[%d] = %d\t",i, *(ptr2++) );
}
}
void main(){
short *array[5]={10,20,30,40,50}, i;
for (i=0;i<5;i++)
printf("%d\t", *((&(array[0]))++) );
printf("\n");
}<file_sep>
void disp(int a[16][16], int num_sqr){ //go to change
int i,j;
printf("\n\n");
for(i=0;i<num_sqr;i++)
{
for(j=0;j<num_sqr;j++)
printf("%d\t",a[i][j]);
printf("\n\n");
}
printf("\n\n");
}
|
961da747f0655c9867649bfc024888229812a5e4
|
[
"C",
"C++"
] | 41
|
C
|
knsrinivasa/c_test
|
db77d1bfacbf550cee9d5d60f9866b26b51c3cf7
|
7656b22a7fe778be03976395970434e22b41338e
|
refs/heads/master
|
<repo_name>LefterWu/simple_seckill<file_sep>/src/main/sql/schema.sql
-- 数据库初始化脚本
-- select version();
-- +-----------+
-- | version() |
-- +-----------+
-- | 5.7.25 |
-- +-----------+
-- 创建数据库
CREATE DATABASE seckill;
-- 使用数据库
use seckill;
-- 创建秒杀库存表
CREATE TABLE `seckill` (
`seckill_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '商品库存id',
`name` varchar(120) NOT NULL COMMENT '商品名称',
`number` int(11) NOT NULL COMMENT '库存数量',
`start_time` timestamp NOT NULL DEFAULT '1970-01-01 12:00:00' COMMENT '秒杀开启时间',
`end_time` timestamp NOT NULL DEFAULT '1970-01-01 12:00:00' COMMENT '秒杀结束时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`seckill_id`),
KEY `idx_start_time` (`start_time`),
KEY `idx_end_time` (`end_time`),
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8 COMMENT='秒杀库存表';
-- 初始化数据
insert into
seckill(name,number,start_time,end_time)
values
('7999元秒杀iphone XS MAX 256G',20,'2018-11-10 00:00:00','2018-11-12 00:00:00'),
('10999元秒杀sony a7rm3',10,'2019-01-01 00:00:00','2019-12-31 00:00:00'),
('1元秒杀小米充电宝',100,'2018-11-10 00:00:00','2018-11-12 00:00:00'),
('4999元秒杀微星GTX 1080Ti',50,'2019-06-17 00:00:00','2019-06-19 00:00:00');
-- 秒杀成功明细表
-- 用户登录认证相关的信息
CREATE TABLE `success_killed` (
`seckill_id` bigint(20) NOT NULL COMMENT '秒杀商品id',
`user_phone` varchar(20) NOT NULL COMMENT '用户手机号',
`state` tinyint(4) NOT NULL DEFAULT '-1' COMMENT '状态标示:-1:无效 0:成功 1:已付款 2:已发货',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`seckill_id`,`user_phone`), /*联合主键,防止重复插入*/
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='秒杀成功明细表';
<file_sep>/README.md
# Simple_seckill
A simple high concurrency seckill system.
## 目录
* [Simple\_seckill](#simple_seckill)
* [主要功能](#%E4%B8%BB%E8%A6%81%E5%8A%9F%E8%83%BD)
* [项目主要技术](#%E9%A1%B9%E7%9B%AE%E4%B8%BB%E8%A6%81%E6%8A%80%E6%9C%AF)
* [数据库表设计](#%E6%95%B0%E6%8D%AE%E5%BA%93%E8%A1%A8%E8%AE%BE%E8%AE%A1)
* [前端交互逻辑](#%E5%89%8D%E7%AB%AF%E4%BA%A4%E4%BA%92%E9%80%BB%E8%BE%91)
* [Restful接口设计](#restful%E6%8E%A5%E5%8F%A3%E8%AE%BE%E8%AE%A1)
* [交互逻辑](#%E4%BA%A4%E4%BA%92%E9%80%BB%E8%BE%91)
* [后端业务逻辑](#%E5%90%8E%E7%AB%AF%E4%B8%9A%E5%8A%A1%E9%80%BB%E8%BE%91)
* [秒杀优化分析](#%E7%A7%92%E6%9D%80%E4%BC%98%E5%8C%96%E5%88%86%E6%9E%90)
* [静态资源](#%E9%9D%99%E6%80%81%E8%B5%84%E6%BA%90)
* [暴露秒杀地址接口](#%E6%9A%B4%E9%9C%B2%E7%A7%92%E6%9D%80%E5%9C%B0%E5%9D%80%E6%8E%A5%E5%8F%A3)
* [执行秒杀操作接口](#%E6%89%A7%E8%A1%8C%E7%A7%92%E6%9D%80%E6%93%8D%E4%BD%9C%E6%8E%A5%E5%8F%A3)
* [优化分析](#%E4%BC%98%E5%8C%96%E5%88%86%E6%9E%90)
* [补充:MySQL的隔离机制](#%E8%A1%A5%E5%85%85mysql%E7%9A%84%E9%9A%94%E7%A6%BB%E6%9C%BA%E5%88%B6)
* [瓶颈分析](#%E7%93%B6%E9%A2%88%E5%88%86%E6%9E%90)
* [优化思路](#%E4%BC%98%E5%8C%96%E6%80%9D%E8%B7%AF)
* [其他方案](#%E5%85%B6%E4%BB%96%E6%96%B9%E6%A1%88)
* [优化总结](#%E4%BC%98%E5%8C%96%E6%80%BB%E7%BB%93)
## 主要功能
- 页面
- 秒杀商品列表页
- 秒杀开启页
- 后端功能
- 暴露秒杀地址接口
- 秒杀业务执行接口
## 项目主要技术
- 基于maven搭建
- 采用SSM框架整合
- Druid数据库连接池
- 基于注解的声明式事务
- 前端bootstrap+jQuery
- 模块化js
- Redis缓存
- protostuff序列化
## 数据库表设计
sql建表文件存放位置\src\main\sql
```sql
-- 创建数据库
CREATE DATABASE seckill;
-- 使用数据库
use seckill;
-- 创建秒杀库存表
CREATE TABLE `seckill` (
`seckill_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '商品库存id',
`name` varchar(120) NOT NULL COMMENT '商品名称',
`number` int(11) NOT NULL COMMENT '库存数量',
`start_time` timestamp NOT NULL DEFAULT '1970-01-01 12:00:00' COMMENT '秒杀开启时间',
`end_time` timestamp NOT NULL DEFAULT '1970-01-01 12:00:00' COMMENT '秒杀结束时间',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`seckill_id`),
KEY `idx_start_time` (`start_time`),
KEY `idx_end_time` (`end_time`),
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB AUTO_INCREMENT=1004 DEFAULT CHARSET=utf8 COMMENT='秒杀库存表';
-- 秒杀成功明细表
-- 用户登录认证相关的信息
CREATE TABLE `success_killed` (
`seckill_id` bigint(20) NOT NULL COMMENT '秒杀商品id',
`user_phone` varchar(20) NOT NULL COMMENT '用户手机号',
`state` tinyint(4) NOT NULL DEFAULT '-1' COMMENT '状态标示:-1:无效 0:成功 1:已付款 2:已发货',
`create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`seckill_id`,`user_phone`), /*联合主键,防止重复插入*/
KEY `idx_create_time` (`create_time`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='秒杀成功明细表';
```
## 前端交互逻辑
### Restful接口设计
```
// 秒杀列表
GET /seckill/list
// 详情页
GET /seckill/{id}/detail
// 系统时间
GET /seckill/time/now
// 暴露秒杀地址
POST /seckill/{id}/exposer
// 执行秒杀
POST /seckill/{id}/{md5}/execution
```
### 交互逻辑
用户访问秒杀商品列表页` /seckill`
客户端请求`url: /seckill/{seckillId}/detail`,
前端控制器处理请求,携带seckill参数并转发到detail页面,
detail页面调用`seckill.detail.init`方法进行初始化工作,显示秒杀倒计时,执行秒杀逻辑等操作
## 后端业务逻辑
- 暴露秒杀接口
- 先从后端缓存中获取seckill对象,没有则从数据库中查找并放入缓存
- 获取md5,并返回暴露秒杀地址对象
<img src="README/clipboard.png" style="zoom:70%">
- 执行秒杀业务
- 由 记录购买行为 + 减库存 两项操作构成事务
- 使用Spring声明式事务
```mysql
# 事务开始
insert ignore into success_killed(seckill_id,user_phone,state)
values (#{seckillId}, #{userPhone}, 0)
update seckill
set number = number - 1
where seckill_id = #{seckillId}
and start_time <= #{killTime}
and end_time >= #{killTime}
and number > 0;
# 事务结束
```
- 秒杀优化行级锁的持有时间
<img src="README/1551608891940.png" style="zoom:70%">
## 秒杀优化分析
### 静态资源
- CDN加速
- list列表页,js,css等静态资源
### 暴露秒杀地址接口
- 后端Redis缓存
- 暴露秒杀地址接口中,首先要获取秒杀商品
由于秒杀商品一般不会改变,因此可以做缓存
- 超时的基础上维护一致性
### 执行秒杀操作接口
#### 优化分析
- 无法使用CDN缓存
- 无法使用后端缓存,会造成库存问题
- 热点商品竞争问题
- 行级锁在Commit后释放
#### 补充:MySQL的隔离机制
MySQL默认隔离级别为**可重复读**
事务在读取某数据的瞬间(就是开始读取的瞬间),必须先对其加 **行级共享锁**,直到事务结束才释放;
事务在更新某数据的瞬间(就是发生更新的瞬间),必须先对其加 **行级排他锁**,直到事务结束才释放。
#### 瓶颈分析
减库存操作和记录购买行为构成了事务,行级锁在commit后提交,优化方向为减少行级锁的持有时间
两种操作间存在网络延迟和GC垃圾收集
网络延迟和GC操作是造成性能瓶颈主要问题
<img src="README/1551621379105.png" style="zoom:70%">
网络延迟:
- 同城机房:0.5-2 ms
- 异地机房:根据地理位置在几十毫秒上下
#### 优化思路
**将客户端逻辑放到MySQL服务端,避免网络延迟和GC影响**
- 使用存储过程:整个事务在MySQL端完成
Spring中的声明式事务或者手动控制事务都是在客户端完成的,存储过程能够使得事务在服务器端完成,
有效减少网络延迟和GC的影响
#### 其他方案
- 原子计数器记录商品库存 -> 采用NoSQL实现,例如redis
- 记录行为消息放入消息队列 -> 分布式MQ实现,主流的有rabbitMQ,rocketMQ等
- 消费消息并落地 -> 记录到MySQL中
本方案优点:
- 超高并发量
缺点:
- 运维成本高,稳定性
- NoSQL和MQ都是分布式服务,运维成本很高
- 开发成本:数据一致性,回滚方案等
- 工程师要非常熟悉这些组件
- 难以保证幂等性:重复秒杀问题
- 需要专门维护NoSQL方案记录重复秒杀用户
### 优化总结
- 前端控制:暴露接口,防止重复点击
- 动静分离:CDN缓存,后端Redis缓存
- 事务竞争优化:减少行级锁持有时间
|
808fd500f5ab1c2e89305c596051d56067ace285
|
[
"Markdown",
"SQL"
] | 2
|
SQL
|
LefterWu/simple_seckill
|
7b7eaf1fdbde69b8dc3deaf59981491545188eaa
|
e22e8ac7b4959c217788313c9f0a104a1461f79a
|
refs/heads/master
|
<file_sep><nav class="col-lg-12 col-md-12 col-sm-12 col-xs-12 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Form->postLink(
__('Delete'),
['action' => 'delete', $timetable->id],
['confirm' => __('Are you sure you want to delete # {0}?', $timetable->id)]
)
?></li>
<li><?= $this->Html->link(__('List Timetable'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="timetable form col-lg-12 col-md-12 columns content">
<?= $this->Form->create($timetable) ?>
<fieldset>
<legend><?= __('Add Timetable') ?></legend>
<div class="form-group">
<label for="lesson_id"><?= __('Lessons') ?></label>
<?=
$this->Form->select('lesson_id', $lessons,
['placeholder' => __('Lessons'), 'empty' => __('Choose lesson'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="teacher_id"><?= __('Teachers') ?></label>
<?=
$this->Form->select('teacher_id', $teachers,
['placeholder' => __('Teachers'), 'empty' => __('Choose teacher'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="class_id"><?= __('Schoolclass') ?></label>
<?=
$this->Form->select('class_id', $classNames,
['placeholder' => __('Gender'), 'empty' => __('Choose school class'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="date_birth"><?= __('Date and time begin') ?></label>
<?=
$this->Form->text('date_begin',
['value' => date('Y-m-01 H:00:00'),
'class' => 'date-month-year-hour-minute form-control']);
?>
</div>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
<file_sep><h2 class="form-signin-heading"><?= __('Contact to administrator for creating account') ?></h2>
<file_sep><nav class="col-lg-12 col-sm-12 col-xs-12 columns breadcrumb" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Journal') ?></li>
</ul>
</nav>
<div class="row col-lg-12 col-xs-12 col-sm-12">
<a class="btn btn-default" href="javascript:void(0)" role="button"><?= __('Give homework') ?></a>
</div>
<div class="journal index col-lg-12 col-xs-12 col-sm-12 columns content">
<h3 class="page-header"><?= __('Journal') ?></h3>
//chooser for getting journal ( select lesson and class )
<?= $this->Form->create(null, ['class' => 'form-horizontal']) ?>
<div class="form-group col-lg-6 col-xs-6 col-sm-6">
<label for="schoolclas"><?= __('Schoolclas') ?></label>
<?=
$this->Form->select('schoolclas', $classNames,
['value' => $classId,
'placeholder' => __('Schoolclas'), 'empty' => __('Choose schoolclas'),
'class' => 'form-control manual-journal-schoolclas']);
?>
</div>
<div class="form-group col-lg-6 col-xs-6 col-sm-6">
<label for="lesson"><?= __('Lesson') ?></label>
<?=
$this->Form->select('lesson', $lessons,
['value' => $lessonId,
'placeholder' => __('Lesson'), 'empty' => __('Choose lesson'), 'class' => 'form-control manual-journal-lesson']);
?>
</div>
<?= $this->Form->button(__('Change'),
['class' => 'btn btn-md btn-primary']) ?>
<?= $this->Form->button(__('Add'),
['class' => 'btn btn-md btn-warning']) ?>
<?= $this->Form->end() ?>
<?php
if (!empty($timetable)) {
foreach ($timetable as $timetableItem) {
$className = $timetableItem['Schoolclass']['prefix'].
$timetableItem['Schoolclass']['class_number'].
$timetableItem['Schoolclass']['suffix'];
echo "<h1>Current lesson: ".$timetableItem['Lesson']['name'].". Class: $className . </h1>";
}
}
?>
//<?php // print_r ( $pupils ); ?>
</div>
<file_sep>
<!DOCTYPE html>
<html lang="en">
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<?= $this->fetch('title') ?>
</title>
<!-- Bootstrap Core CSS -->
<link href="/panel/theme2/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="/panel/theme2/bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">
<!-- Timeline CSS -->
<link href="/panel/theme2/dist/css/timeline.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="/panel/theme2/dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="/panel/theme2/bower_components/morrisjs/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="/panel/theme2/bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<div id="page-wrapper">
<div class="container-fluid">
<?= $this->Flash->render() ?>
<section class="container clearfix">
<?= $this->fetch('content') ?>
</section>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<footer>
</footer>
<?php echo $this->element('modal'); ?>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
<!--scripts loaded here from cdn for performance -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.js"></script>
<script src="/js/mistake.js"></script>
<script>
$('document').ready(function () {
$('.message.error').wrap( "<p class='bg-danger'></p>" );
});
</script>
<style>
.bg-danger {
padding: 10px;
}
</style>
</body>
</html>
<file_sep><?php
namespace App\Controller;
use App\Controller\AppController;
/**
* PupilSchoolclasses Controller
*
* @property \App\Model\Table\PupilSchoolclassesTable $PupilSchoolclasses
*/
class PupilSchoolclassesController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->paginate = [
'contain' => ['Classes', 'Pupils']
];
$this->set('pupilSchoolclasses', $this->paginate($this->PupilSchoolclasses));
$this->set('_serialize', ['pupilSchoolclasses']);
}
/**
* View method
*
* @param string|null $id Pupil Schoolclass id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$pupilSchoolclass = $this->PupilSchoolclasses->get($id, [
'contain' => ['Classes', 'Pupils']
]);
$this->set('pupilSchoolclass', $pupilSchoolclass);
$this->set('_serialize', ['pupilSchoolclass']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$pupilSchoolclass = $this->PupilSchoolclasses->newEntity();
if ($this->request->is('post')) {
$pupilSchoolclass = $this->PupilSchoolclasses->patchEntity($pupilSchoolclass, $this->request->data);
if ($this->PupilSchoolclasses->save($pupilSchoolclass)) {
$this->Flash->success(__('The pupil schoolclass has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The pupil schoolclass could not be saved. Please, try again.'));
}
}
$classes = $this->PupilSchoolclasses->Classes->find('list', ['limit' => 200]);
$pupils = $this->PupilSchoolclasses->Pupils->find('list', ['limit' => 200]);
$this->set(compact('pupilSchoolclass', 'classes', 'pupils'));
$this->set('_serialize', ['pupilSchoolclass']);
}
/**
* Edit method
*
* @param string|null $id Pupil Schoolclass id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$pupilSchoolclass = $this->PupilSchoolclasses->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$pupilSchoolclass = $this->PupilSchoolclasses->patchEntity($pupilSchoolclass, $this->request->data);
if ($this->PupilSchoolclasses->save($pupilSchoolclass)) {
$this->Flash->success(__('The pupil schoolclass has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The pupil schoolclass could not be saved. Please, try again.'));
}
}
$classes = $this->PupilSchoolclasses->Classes->find('list', ['limit' => 200]);
$pupils = $this->PupilSchoolclasses->Pupils->find('list', ['limit' => 200]);
$this->set(compact('pupilSchoolclass', 'classes', 'pupils'));
$this->set('_serialize', ['pupilSchoolclass']);
}
/**
* Delete method
*
* @param string|null $id Pupil Schoolclass id.
* @return \Cake\Network\Response|null Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$pupilSchoolclass = $this->PupilSchoolclasses->get($id);
if ($this->PupilSchoolclasses->delete($pupilSchoolclass)) {
$this->Flash->success(__('The pupil schoolclass has been deleted.'));
} else {
$this->Flash->error(__('The pupil schoolclass could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
<file_sep><?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
?>
<!DOCTYPE html>
<html>
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<?= $this->fetch('title') ?>
</title>
<link href="/images/favicon.ico" type="image/x-icon" rel="icon"/>
<link href="/images/favicon.ico" type="image/x-icon" rel="shortcut icon"/>
<?= $this->fetch('meta') ?>
<?= $this->fetch('css') ?>
<?= $this->fetch('script') ?>
<!-- Bootstrap Core CSS -->
<link href="/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="/css/sb-admin.css" rel="stylesheet">
<link href="/css/style.css" rel="stylesheet">
<!-- Morris Charts CSS -->
<link href="/css/plugins/morris.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="send-mistake-report" class="send-mistake-report col-lg-3 col-xs-3 col-sm-1">
<a href="#">Повідомити про помилку</a>
</div>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href=""><?= $this->fetch('title') ?></a>
</div>
<!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens -->
<div class="collapse navbar-collapse navbar-ex1-collapse">
<?php echo $this->element('teacher'); ?>
</div>
<!-- /.navbar-collapse -->
</nav>
<div id="page-wrapper">
<div class="container-fluid">
<?= $this->Flash->render() ?>
<section class="container clearfix">
<?= $this->fetch('content') ?>
</section>
</div>
<!-- /.container-fluid -->
</div>
<!-- /#page-wrapper -->
</div>
<!-- /#wrapper -->
<footer>
</footer>
<?php echo $this->element('modal'); ?>
<!-- Morris Charts JavaScript -->
<script src="/js/plugins/morris/raphael.min.js"></script>
<script src="/js/plugins/morris/morris.min.js"></script>
<script src="/js/plugins/morris/morris-data.js"></script>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
<script src="/js/custom.js"></script>
</body>
</html>
<file_sep><nav class="col-lg-12 col-sm-12 col-xs-12 columns breadcrumb" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('New Pupil'), ['action' => 'add']) ?></li>
</ul>
</nav>
<div class="flash col-lg-12 col-md-12 "><?= $this->Flash->render() ?></div>
<div class="pupil index col-lg-12 col-md-12 columns content">
<h3 class="page-header"><?= __('Pupils') ?></h3>
<table cellpadding="0" cellspacing="0" class="table table-striped">
<thead>
<tr>
<th><?= $this->Paginator->sort('id') ?></th>
<th><?= $this->Paginator->sort('name') ?></th>
<th><?= $this->Paginator->sort('surname') ?></th>
<th><?= $this->Paginator->sort('gender') ?></th>
<th><?= $this->Paginator->sort('date_birth') ?></th>
<th><?= $this->Paginator->sort('date_register') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($pupil as $pupil): ?>
<tr>
<td><?= $this->Number->format($pupil->id) ?></td>
<td><?= $pupil->name ?></td>
<td><?= $pupil->surname ?></td>
<td><?= $pupil->gender_name; ?></td>
<td><?= h($pupil->date_birth) ?></td>
<td><?= h($pupil->date_register) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $pupil->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $pupil->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $pupil->id], ['confirm' => __('Are you sure you want to delete # {0}?', $pupil->id)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div>
</div>
<file_sep><!-- Modal -->
<div class="modal fade" id="mistake-modal" tabindex="-1" role="dialog" aria-labelledby="mistakeModalLabel">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="mistake-modal-label">Помилка</h4>
</div>
<div class="modal-body">
<input type="hidden" name="mistake-url" class="mistake-input" value="<?= $this->request->here ?>">
<textarea name="mistake-body" class="mistake-input mistake-body" style="width: 100%" placeholder="Опишіть помилку"></textarea>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default modal-close" data-dismiss="modal">Закрити</button>
<button type="button" class="btn btn-primary modal-send">Надіслати помилку</button>
</div>
</div>
</div>
</div>
<file_sep><?php
namespace App\Model\Entity;
use Cake\ORM\Entity;
class Pupil extends Entity
{
protected $_virtual = ['gender_name'];
public function _getGenderName(){
$genderName = "";
if ( !empty($this->_properties['gender']) ){
switch ( (int)$this->_properties['gender'] ){
case 1:
$genderName = __("male");
break;
case 2:
$genderName = __("female");
break;
}
}
return $genderName;
}
}<file_sep><nav class="col-lg-12 col-sm-12 col-xs-12 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('Edit Journal'), ['action' => 'edit', $journal->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Journal'), ['action' => 'delete', $journal->id], ['confirm' => __('Are you sure you want to delete # {0}?', $journal->id)]) ?> </li>
<li><?= $this->Html->link(__('List Journal'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Journal'), ['action' => 'add']) ?> </li>
</ul>
</nav>
<h1 class="page-header"><?= __('Pupil') ?> #<?= h($journal->id) ?></h1>
<div class="journal view col-lg-12 col-md-12 columns content">
<table class="vertical-table">
<tr>
<th><?= __('Id') ?></th>
<td><?= $this->Number->format($journal->id) ?></td>
</tr>
<tr>
<th><?= __('User Id') ?></th>
<td><?= $this->Number->format($journal->user_id) ?></td>
</tr>
<tr>
<th><?= __('Lesson Id') ?></th>
<td><?= $this->Number->format($journal->lesson_id) ?></td>
</tr>
<tr>
<th><?= __('Mark Id') ?></th>
<td><?= $this->Number->format($journal->mark_id) ?></td>
</tr>
<tr>
<th><?= __('Status Id') ?></th>
<td><?= $this->Number->format($journal->status_id) ?></td>
</tr>
</table>
</div>
<file_sep># qmatio
Soft for school: Ivankovichy
<file_sep>jQuery.validator.addMethod("phoneUA", function(value, element) {
// allow any non-whitespace characters as the host part
return this.optional( element ) || /^((\+[1-9]{1,4}[ \-]*)|(\([0-9]{2,3}\)[ \-]*)|([0-9]{2,4})[ \-]*)*?[0-9]{3,4}?[ \-]*[0-9]{3,4}?$/.test( value );
}, 'Please specify a valid phone number.');<file_sep><?php
return [
'SchoolSettings' => [
'lesson_length' => 45,
]
];<file_sep><nav class="large-3 medium-4 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('Edit Pupil Schoolclass'), ['action' => 'edit', $pupilSchoolclass->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Pupil Schoolclass'), ['action' => 'delete', $pupilSchoolclass->id], ['confirm' => __('Are you sure you want to delete # {0}?', $pupilSchoolclass->id)]) ?> </li>
<li><?= $this->Html->link(__('List Pupil Schoolclasses'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Pupil Schoolclass'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Classes'), ['controller' => 'Classes', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Class'), ['controller' => 'Classes', 'action' => 'add']) ?> </li>
</ul>
</nav>
<div class="pupilSchoolclasses view large-9 medium-8 columns content">
<h3><?= h($pupilSchoolclass->id) ?></h3>
<table class="vertical-table">
<tr>
<th><?= __('Class') ?></th>
<td><?= $pupilSchoolclass->has('class') ? $this->Html->link($pupilSchoolclass->class->id, ['controller' => 'Classes', 'action' => 'view', $pupilSchoolclass->class->id]) : '' ?></td>
</tr>
<tr>
<th><?= __('Id') ?></th>
<td><?= $this->Number->format($pupilSchoolclass->id) ?></td>
</tr>
<tr>
<th><?= __('Pupil Id') ?></th>
<td><?= $this->Number->format($pupilSchoolclass->pupil_id) ?></td>
</tr>
</table>
</div>
<file_sep><?php
/**
* CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
* @link http://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license http://www.opensource.org/licenses/mit-license.php MIT License
*/
?>
<!DOCTYPE html>
<html>
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="generator" content="Codeply">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" />
<link href="//cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" rel="stylesheet" />
<link rel="stylesheet" href="//code.ionicframework.com/ionicons/2.0.1/css/ionicons.min.css" />
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css">
<link rel="stylesheet" href="/front/css/styles.css" />
<title>
<?= $this->fetch('title') ?>
</title>
<?php echo $this->Html->meta ( 'favicon.ico', '/images/favicon.ico', [ 'type' => 'icon']); ?>
<?= $this->fetch('meta') ?>
<?= $this->fetch('css') ?>
<?= $this->fetch('script') ?>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<nav id="topNav" class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-navbar">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand page-scroll" href="#first"><i class="ion-ios-analytics-outline"></i> Іванковичі</a>
</div>
<div class="navbar-collapse collapse" id="bs-navbar">
<ul class="nav navbar-nav">
<li>
<a class="page-scroll" href="#one">Головна</a>
</li>
<li>
<a class="page-scroll" href="#two">Проекти</a>
</li>
<!-- <li>
<a class="page-scroll" href="#three">Gallery</a>
</li>-->
<!-- <li>
<a class="page-scroll" href="#four">Features</a>
</li>-->
<li>
<a class="page-scroll" href="#contacts">Контакти</a>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li>
<a class="page-scroll" data-toggle="modal" title="Про проект" href="#aboutModal">Про проект</a>
</li>
</ul>
</div>
</div>
</nav>
<header id="first">
<div class="header-content">
<div class="inner">
<h1 class="cursive">Ivankovichy</h1>
<h4>Я - громадянин Іванковичей</h4>
<hr>
<a href="#video-background" id="toggleVideo" data-toggle="collapse" class="btn btn-primary btn-xl">Вимкнути відео</a>
<a href="#one" class="btn btn-primary btn-xl page-scroll">Почати працювати</a>
</div>
</div>
<video autoplay="" loop="" class="fillWidth fadeIn wow collapse in" data-wow-delay="0.5s" poster="https://s3-us-west-2.amazonaws.com/coverr/poster/Traffic-blurred2.jpg" id="video-background">
<source src="https://s3-us-west-2.amazonaws.com/coverr/mp4/Traffic-blurred2.mp4" type="video/mp4">Your browser does not support the video tag. I suggest you upgrade your browser.
</video>
</header>
<section class="bg-primary" id="one">
<div class="container">
<div class="row">
<div class="col-lg-6 col-lg-offset-3 col-md-8 col-md-offset-2 text-center">
<h2 class="margin-top-0 text-primary">Проект "Я - громадянин Іванковичей"</h2>
<br>
<p class="text-faded">
Головна ціль проекту - teacher електронних засобів для участі у громадському житті Іванковичей.
</p>
<a href="#two" class="btn btn-default btn-xl page-scroll">Перейти до проектів</a>
</div>
</div>
</div>
</section>
<section id="two">
<div class="container">
<div class="row">
<div class="col-lg-12 text-center">
<h2 class="margin-top-0 text-primary">Проекти</h2>
<hr class="primary">
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-lg-4 col-md-4 text-center">
<div class="feature">
<i class="icon-lg ion-android-laptop wow fadeIn" data-wow-delay=".3s"></i>
<a href="#three">
<h3>Електронна Школа Qmatio</h3>
</a>
<p class="text-muted">Проект автоматизації </p>
</div>
</div>
<div class="col-lg-4 col-md-4 text-center">
<div class="feature">
<i class="icon-lg ion-ios-search wow fadeInUp" data-wow-delay=".2s"></i>
<h3>Місцевий референдум</h3>
<p class="text-muted">Проект проведення голосування у підтримку тих чи інших напрямів розвитку Іванковичей</p>
</div>
</div>
<div class="col-lg-4 col-md-4 text-center">
<div class="feature">
<i class="icon-lg ion-ios-star-outline wow fadeIn" data-wow-delay=".3s"></i>
<h3>Твій лікар</h3>
<p class="text-muted">Проект спілкування з лікарем, електронна черга.</p>
</div>
</div>
</div>
</div>
</section>
<section id="three" class="no-padding">
<div class="container-fluid">
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4">
<h2 class="text-center text-primary">QMatio. Школа </h2>
<hr>
<div class="media wow fadeInRight">
<p>Програмний комплекс для автоматизації та віртуалізації
навчального процессу у системі загальноосвітніх закладів.</p>
<h3>Мета: </h3>
<p>використання автоматизованих систем при
мінімальному навантаженні на викладацький склад та максимально можливому функціоналі.
</p>
<ul>
<li>
<a href="/teacher/users/login" target="_blank">Вхід для вчителів</a>
<p><b>login: teacher</b><br>
<b>pass: <PASSWORD></b></p>
</li>
<li>
<a href="/manager/users/login" target="_blank">Вхід для менеджерів школи</a>
<p><b>login: manager</b><br>
<b>pass: <PASSWORD></b></p>
</li>
<li>
<a href="/pupil/users/login" target="_blank">Вхід для учнів</a>
<p><b>login: pupil</b><br>
<b>pass: <PASSWORD></b></p>
</li>
<li>
<a href="/parent/users/login" target="_blank">Вхід для батьків</a>
<p><b>login: parent</b><br>
<b>pass: <PASSWORD></b></p>
</li>
</ul>
</div>
</div>
</div>
</div>
</section>
<section class="container-fluid" id="four">
<div class="row">
<div class="col-xs-10 col-xs-offset-1 col-sm-6 col-sm-offset-3 col-md-4 col-md-offset-4">
<h2 class="text-center text-primary">Фнукціонал:</h2>
<hr>
<div class="media wow fadeInRight">
<h3>Для вчителів:</h3>
<div class="media-body media-middle">
<ul>
<li>можливість контролювати наявність учнів ( за умов дозволу батьків можливе автоматичне визначення місцезнаходження учня );</li>
<li>додатковий безпосередній зв”язок з батьками;</li>
<li>неможливість корегування розкладу, домашніх завдань та оцінок дитиною;</li>
<li>автоматизація документації по переведенню дітей з одного класу в наступний;</li>
<li>додаткові можливості професійного спілкування з вчителями в інших школах;</li>
<li>можливість анонімного зв’язку з адміністрацією школи.</li>
</ul>
</div>
<div class="media-right">
<i class="icon-lg ion-ios-bolt-outline"></i>
</div>
</div>
<hr>
<div class="media wow fadeIn">
<h3>Для учнів:</h3>
<div class="media-left">
<i class="icon-lg ion-ios-flask-outline"></i>
</div>
<div class="media-body media-middle">
<ul>
<li>акутальна інформація про розклад занять з нагадуванням про зміни;</li>
<li>додаткова інформація про домашні завдання;</li>
<li>додаткові навчальні матеріали.</li>
</ul>
</div>
</div>
<hr>
<div class="media wow fadeInRight">
<h3>Для батьків:</h3>
<div class="media-body media-middle">
<ul>
<li>отримання інформації про успіхи або проблеми дитини в on-line режимі;</li>
<li>швидкий доступ до вчителів та адміністрації школи;</li>
<li>можливість колективного спілкування в межах батьківського комітету.</li>
</ul>
</div>
<div class="media-right">
<i class="icon-lg ion-ios-heart-outline"></i>
</div>
</div>
<hr>
</div>
</div>
</section>
<aside class="bg-dark" id="contacts">
<div class="container text-center">
<div class="call-to-action">
<h2 class="text-primary">Контакти</h2>
</div>
<br>
<hr/>
<br>
<div class="row">
<div class="col-lg-10 col-lg-offset-1">
<div class="row">
<div class="col-sm-4 col-xs-12 text-center">
<i class="icon-lg fa fa-envelope" title="email"></i>
<p><a href="mailto:<EMAIL>"><EMAIL></a></p>
</div>
<div class="col-sm-4 col-xs-12 text-center">
<i class="icon-lg fa fa-skype" title="skype"></i>
<p><a href="skype:gregzorbov">gregzorbov</a></p>
</div>
<div class="col-sm-4 col-xs-12 text-center">
<i class="icon-lg fa fa-phone" title="phone"></i>
<p><a href="javascript:void(0)">+380509523035</a></p>
</div>
</div>
</div>
</div>
</div>
</aside>
<section id="last">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 text-center">
<h2 class="margin-top-0 wow fadeIn">Зворотній зв'язок</h2>
<hr class="primary">
<p>Ми любимо зворотній зв'язок. Заповніть форму нижче і ми зв'яжемося з вами.</p>
</div>
<div class="col-lg-10 col-lg-offset-1 text-center">
<form class="contact-form row">
<div class="col-md-4">
<label></label>
<input type="text" name="name" id="name" class="form-control name" placeholder="Name">
</div>
<div class="col-md-4">
<label></label>
<input type="text" name="email" id="email" class="form-control email" placeholder="Email">
</div>
<div class="col-md-4">
<label></label>
<input type="text" name="phone" id="phone" class="form-control phone" placeholder="Phone">
</div>
<div class="col-md-12">
<label></label>
<textarea class="form-control message" name="message" id="message" rows="9" placeholder="Your message here.."></textarea>
</div>
<div class="col-md-4 col-md-offset-4">
<label></label>
<button type="submit" class="btn btn-primary btn-block btn-lg">Send <i class="ion-android-arrow-forward"></i></button>
</div>
</form>
</div>
</div>
</div>
</section>
<footer id="footer">
<div class="container-fluid">
<div class="row">
<div class="col-xs-6 col-sm-3 column">
<h4>Проекти</h4>
<ul class="list-unstyled">
<li><a href="#three">Електронна Школа Qmatio</a></li>
<li><a href="#two">Місцевий референдум</a></li>
<li><a href="#two">Твій лікар</a></li>
</ul>
</div>
<div class="col-xs-6 col-sm-3 column">
<h4>Меню</h4>
<ul class="list-unstyled">
<li>
<a class="page-scroll" href="#one">Головна</a>
</li>
<li>
<a class="page-scroll" href="#two">Проекти</a>
</li>
<li>
<a class="page-scroll" href="#contacts">Контакти</a>
</li>
<!-- <li><a href="#">Privacy Policy</a></li>
<li><a href="#">Terms & Conditions</a></li>-->
</ul>
</div>
<div class="col-xs-12 col-sm-3 column">
<!-- <h4>Stay Posted</h4>
<form>
<div class="form-group">
<input type="text" class="form-control" title="No spam, we promise!" placeholder="Tell us your email">
</div>
<div class="form-group">
<button class="btn btn-primary" data-toggle="modal" data-target="#sendMessageModal" type="button">Subscribe for updates</button>
</div>
</form>-->
</div>
<div class="col-xs-12 col-sm-3 text-right">
<h4>Follow</h4>
<ul class="list-inline">
<li><a rel="nofollow" href="" title="Twitter"><i class="icon-lg ion-social-twitter-outline"></i></a> </li>
<li><a rel="nofollow" href="" title="Facebook"><i class="icon-lg ion-social-facebook-outline"></i></a> </li>
<li><a rel="nofollow" href="" title="Dribble"><i class="icon-lg ion-social-dribbble-outline"></i></a></li>
</ul>
</div>
</div>
<br/>
<span class="pull-right text-muted small"><a href="http://gregzorb.com/">Made By gregzorb.com</a> ©2016 QMatio</span>
</div>
</footer>
<div id="galleryModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-body">
<img src="//placehold.it/1200x700/222?text=..." id="galleryImage" class="img-responsive" />
<p>
<br/>
<button class="btn btn-primary btn-lg center-block" data-dismiss="modal" aria-hidden="true">Close <i class="ion-android-close"></i></button>
</p>
</div>
</div>
</div>
</div>
<div id="aboutModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-body">
<h2 class="text-center">Про проект</h2>
<h5 class="text-center">
Проект "Я - громадянин Іванковичей"
</h5>
<p class="text-justify">
Головна ціль проекту - використання електронних засобів для участі у громадському житті Іванковичей.
</p>
<br/>
<button class="btn btn-primary btn-lg center-block" data-dismiss="modal" aria-hidden="true"> OK </button>
</div>
</div>
</div>
</div>
<div id="sendMessageModal" class="modal fade" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-body">
<h2 class="text-center success-send-message hidden"><?= __('Awesome!') ?></h2>
<p class="text-center success-send-message hidden"><?= __('Your request sended. Look for answer in email.') ?></p>
<h2 class="text-center error-send-message hidden"><?= __('Error!') ?></h2>
<br/>
<button class="btn btn-primary btn-lg center-block" data-dismiss="modal" aria-hidden="true">OK <i class="ion-android-close"></i></button>
</div>
</div>
</div>
</div>
<!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/js/bootstrap.min.js"></script>
<!--scripts loaded here from cdn for performance -->
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery-easing/1.3/jquery.easing.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/wow/1.1.2/wow.js"></script>
<script src="/js/plugins/validate/jquery.validate.min.js"></script>
<script src="/js/plugins/validate/additional-methods.min.js"></script>
<script src="/js/plugins/validate/custom.js"></script>
<script src="/front/js/scripts.js"></script>
</body>
</html>
<file_sep><!--bin/cake bake controller --prefix pupil users
bin/cake bake view --prefix pupil users-->
<!--bin/cake bake template --prefix admin users
uk_UA.utf8
bin/cake bake controller --prefix teacher schoolclass
bin/cake bake template --prefix teacher schoolclass
-->
<!DOCTYPE html>
<html lang="en">
<head>
<?= $this->Html->charset() ?>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>
<?= $this->fetch('title') ?>
</title>
<!-- Bootstrap Core CSS -->
<link href="/panel/theme2/bower_components/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- MetisMenu CSS -->
<link href="/panel/theme2/bower_components/metisMenu/dist/metisMenu.min.css" rel="stylesheet">
<!-- Timeline CSS -->
<link href="/panel/theme2/dist/css/timeline.css" rel="stylesheet">
<!-- Custom CSS -->
<link href="/panel/theme2/dist/css/sb-admin-2.css" rel="stylesheet">
<!-- Custom Fonts -->
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div id="wrapper">
<!-- Navigation -->
<nav class="navbar navbar-default navbar-static-top" role="navigation" style="margin-bottom: 0">
<?php echo $this->element('navigation'); ?>
<?php echo $this->element('menu'); ?>
</nav>
<div id="page-wrapper">
<div class="row">
<div class="col-lg-12">
<?= $this->fetch('content') ?>
</div>
</div>
</div>
</div>
<!-- jQuery -->
<script src="/panel/theme2/bower_components/jquery/dist/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<!-- Bootstrap Core JavaScript -->
<script src="/panel/theme2/bower_components/bootstrap/dist/js/bootstrap.min.js"></script>
<!-- Metis Menu Plugin JavaScript -->
<script src="/panel/theme2/bower_components/metisMenu/dist/metisMenu.min.js"></script>
<!-- Custom Theme JavaScript -->
<script src="/panel/theme2/dist/js/sb-admin-2.js"></script>
<!-- Custom Lesson CSS -->
<link href="/css/style.css" rel="stylesheet">
</body>
</html>
<file_sep><nav class="large-3 medium-4 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?=
$this->Html->link(__('Edit Schoolclas'),
['action' => 'edit', $schoolclas->id])
?> </li>
<li><?=
$this->Form->postLink(__('Delete Schoolclas'),
['action' => 'delete', $schoolclas->id],
['confirm' => __('Are you sure you want to delete # {0}?',
$schoolclas->id)])
?> </li>
<li><?= $this->Html->link(__('List Schoolclass'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Schoolclas'), ['action' => 'add']) ?> </li>
</ul>
</nav>
<div class="schoolclass view col-lg-12 col-md-12 columns content">
<div class="row">
<h4>
<small><?= __('Class name') ?>:</small>
<?= h($schoolclas->class_name); ?>
</h4>
</div>
<div class="row">
<?php if (!empty($pupils)) { ?>
<table class="table table-striped">
<tr>
<th><?= __('Name') ?></th>
<th><?= __('Date Birth') ?></th>
<th><?= __('Date Register') ?></th>
</tr>
<?php
foreach ($pupils as $pupil) {
echo "<pre>";
print_r ($pupil );
echo "</pre>";
$p = $pupil['pupil'][0];
$pupilName = $p['surname']." ".
$p['name']." ".
$p['patronymic'];
?>
<tr>
<td><?= $pupilName ?></td>
<td><?= $p['date_birth'] ?></td>
<td><?= $p['date_register'] ?></td>
</tr>
<?php } ?>
</table>
<?php } ?>
</div>
</div>
<file_sep><?php
namespace App\Controller\Teacher;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
/**
* Journal Controller
*
* @property \App\Model\Table\JournalTable $Journal
*/
class JournalController extends AppController
{
public $uses = [
'Pupil'
];
public function initialize()
{
parent::initialize();
$this->loadModel('Pupil');
$this->loadModel('TimeTable');
}
/**
* Index method
*
* @return void
*/
public function index()
{
//get current lesson and params
$lessonId = 0;
$this->set(compact('lessonId'));
$classId = 0;
$this->set(compact('classId'));
//get all names for schoolclasses
$classNames = $this->getClassNames();
$this->set(compact('classNames'));
//get all names for lessons
$lessons = $this->getLessons();
$this->set(compact('lessons'));
$teacher = $this->Auth->user();
//find from timetable
$conditions = ['teacher_id' => $teacher['id'],
'Lesson.is_active' => true,
'date_begin <= '=> date("Y-m-d H:i:s"),//lesson started
'date_begin > '=> date("Y-m-d H:i:s", strtotime("-".$this->schoolSettings['lesson_length']." minutes")),
];
//init models
$this->Timetable = TableRegistry::get('Timetable');
$this->Lesson = TableRegistry::get('Lesson');
$this->Schoolclass = TableRegistry::get('Schoolclass');
$timetableLessons = $this->Timetable
->find( 'all', ['conditions' => $conditions ])
->autoFields(true)
->select($this->Schoolclass)
->select($this->Lesson)
->hydrate(false)
->join([
'table' => 'lessons',
'alias' => 'Lesson',
'type' => 'INNER',
'conditions' => 'Lesson.id = lesson_id',
])
->join([
'table' => 'schoolclass',
'alias' => 'Schoolclass',
'type' => 'INNER',
'conditions' => 'Schoolclass.id = class_id',
])
;
$timetable = [];
if ( !empty($timetableLessons->toArray())){
$timetable = $timetableLessons->toArray();
}
$schoolClassIds = array_column($timetable, 'class_id');
$pupils = [];
if (!empty($schoolClassIds)) {
$this->Pupil = TableRegistry::get('Pupil');
$conditions = ['PupilSchoolclass.class_id' => ' IN ('.implode(",", $schoolClassIds).")"];
$pupils = $this->Pupil->find('all', [
'conditions' => [$conditions]
])
->join([
'table' => 'pupil_schoolclasses',
'alias' => 'PupilSchoolclass',
'type' => 'INNER',
'conditions' => [
'Pupil.id = PupilSchoolclass.pupil_id',
]
])
->hydrate(false)
->toArray()
;
}
$this->set(compact('pupils'));
$this->set(compact('timetable'));
$this->set('_serialize', ['journal']);
}
/**
* View method
*
* @param string|null $id Journal id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$journal = $this->Journal->get($id, [
'contain' => []
]);
$this->set('journal', $journal);
$this->set('_serialize', ['journal']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$journal = $this->Journal->newEntity();
if ($this->request->is('post')) {
$journal = $this->Journal->patchEntity($journal, $this->request->data);
if ($this->Journal->save($journal)) {
$this->Flash->success(__('The journal has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The journal could not be saved. Please, try again.'));
}
}
$this->set(compact('journal'));
$this->set('_serialize', ['journal']);
}
/**
* Edit method
*
* @param string|null $id Journal id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$journal = $this->Journal->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$journal = $this->Journal->patchEntity($journal, $this->request->data);
if ($this->Journal->save($journal)) {
$this->Flash->success(__('The journal has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The journal could not be saved. Please, try again.'));
}
}
$this->set(compact('journal'));
$this->set('_serialize', ['journal']);
}
/**
* Delete method
*
* @param string|null $id Journal id.
* @return \Cake\Network\Response|null Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$journal = $this->Journal->get($id);
if ($this->Journal->delete($journal)) {
$this->Flash->success(__('The journal has been deleted.'));
} else {
$this->Flash->error(__('The journal could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
<file_sep><div class="navbar-default sidebar" role="navigation">
<div class="sidebar-nav navbar-collapse">
<ul class="nav" id="side-menu">
<li class="sidebar-search">
<div class="input-group custom-search-form">
<input type="text" class="form-control" placeholder="Search...">
<span class="input-group-btn">
<button class="btn btn-default" type="button">
<i class="fa fa-search"></i>
</button>
</span>
</div>
<!-- /input-group -->
</li>
<?php $url = $this->Html->Url->build(['controller'=>'index','action' => 'index']); ?>
<li class="<?= $this->request->here == $url? 'active': '' ?>">
<a href="<?= $url ?>"><i class="fa fa-fw fa-dashboard"></i> <?= __('Home') ?></a>
</li>
<?php $url = $this->Html->Url->build(['controller'=>'journal','action' => 'index']); ?>
<li class="<?= $this->request->here == $url? 'active': '' ?>">
<a href="<?= $url ?>"><i class="fa fa-fw fa-book"></i> <?= __('Journal') ?></a>
</li>
<?php $url = $this->Html->Url->build(['controller'=>'timetable','action' => 'index']); ?>
<li class="<?= $this->request->here == $url? 'active': '' ?>">
<a href="<?= $url ?>"><i class="fa fa-fw fa-table"></i> <?= __('Timetable') ?></a>
</li>
<?php $url = $this->Html->Url->build(['controller'=>'schoolclass','action' => 'index']); ?>
<li class="<?= $this->request->here == $url? 'active': '' ?>">
<a href="<?= $url ?>"><i class="fa fa-fw fa-table"></i> <?= __('Classes') ?></a>
</li>
<?php $url = $this->Html->Url->build(['controller'=>'pupil','action' => 'index']); ?>
<li class="<?= $this->request->here == $url? 'active': '' ?>">
<a href="<?= $url ?>"><i class="fa fa-fw fa-table"></i> <?= __('Pupils') ?></a>
</li>
<li>
<a href="javascript:;" data-toggle="collapse" data-target="#demo"><i class="fa fa-fw fa-arrows-v"></i> Аналітика <i class="fa fa-fw fa-caret-down"></i></a>
<ul id="demo" class="collapse">
<?php $url = $this->Html->Url->build(['controller'=>'mark','action' => 'index']); ?>
<li class="<?= $this->request->here == $url? 'active': '' ?>">
<a href="<?= $url; ?>"><i class="fa fa-fw fa-table"></i> <?= __('Зведена інформація: оцінки') ?></a>
</li>
</ul>
</li>
</ul>
</div>
<!-- /.sidebar-collapse -->
</div><file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
/**
* Schoolclass Controller
*
* @property \App\Model\Table\SchoolclassTable $Schoolclass
*/
class SchoolclassController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->set('schoolclass', $this->paginate($this->Schoolclass));
$this->set('_serialize', ['schoolclass']);
}
/**
* View method
*
* @param string|null $id Schoolclas id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$schoolclas = $this->Schoolclass->get($id,
[
'contain' => []
]);
$this->set('schoolclas', $schoolclas);
$this->set('_serialize', ['schoolclas']);
$this->loadModel('PupilSchoolclasses');
$pupils = $this->PupilSchoolclasses->find('all',[
'conditions' => ['class_id' => $id]
]);
$pupils = $pupils->contain(['Pupil']);
echo "<pre>"; print_r ( $pupils ); echo "</pre>";
$this->set(compact('pupils'));
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$schoolclas = $this->Schoolclass->newEntity();
if ($this->request->is('post')) {
$schoolclas = $this->Schoolclass->patchEntity($schoolclas,
$this->request->data);
if ($this->Schoolclass->save($schoolclas)) {
$this->Flash->success(__('The schoolclas has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The schoolclas could not be saved. Please, try again.'));
}
}
$this->set(compact('schoolclas'));
$this->set('_serialize', ['schoolclas']);
}
/**
* Edit method
*
* @param string|null $id Schoolclas id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$schoolclas = $this->Schoolclass->get($id,
[
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$schoolclas = $this->Schoolclass->patchEntity($schoolclas,
$this->request->data);
if ($this->Schoolclass->save($schoolclas)) {
$this->Flash->success(__('The schoolclas has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The schoolclas could not be saved. Please, try again.'));
}
}
$this->set(compact('schoolclas'));
$this->set('_serialize', ['schoolclas']);
}
/**
* Delete method
*
* @param string|null $id Schoolclas id.
* @return \Cake\Network\Response|null Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$schoolclas = $this->Schoolclass->get($id);
if ($this->Schoolclass->delete($schoolclas)) {
$this->Flash->success(__('The schoolclas has been deleted.'));
} else {
$this->Flash->error(__('The schoolclas could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}<file_sep><nav class="col-lg-12 col-md-12 col-sm-12 col-xs-12 columns breadcrumb" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('List Pupil'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="pupil form col-lg-12 col-md-12 columns content">
<?= $this->Form->create($pupil) ?>
<fieldset>
<legend><?= __('Add Pupil') ?></legend>
<div class="form-group">
<label for="name"><?= __('Name') ?></label>
<?=
$this->Form->text('name',
['placeholder' => __('Name'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="surname"><?= __('Surname') ?></label>
<?=
$this->Form->text('surname',
['placeholder' => __('Surname'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="patronymic"><?= __('Patronymic') ?></label>
<?=
$this->Form->text('patronymic',
['placeholder' => __('Patronymic'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="gender"><?= __('Gender') ?></label>
<?=
$this->Form->select('gender', [1 => 'Male', 2 => 'Female'],
['placeholder' => __('Gender'), 'empty' => __('Choose gender'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="date_birth"><?= __('Date Birth') ?></label>
<?=
$this->Form->text('date_birth',
['placeholder' => __('Date Birth'),
'value' => date('Y-01-01', strtotime('-7 year')),
'class' => 'date-month-year form-control']);
?>
</div>
</fieldset>
<?= $this->Form->button(__('Submit'), ['class' => 'form-control']) ?>
<?= $this->Form->end() ?>
</div>
<file_sep>/*
Created on : Jan 23, 2016, 9:22:22 PM
Author : gregzorb
*/
$('document').ready(function(){
$('.send-mistake-report').on('click', function(){
$('#mistake-modal').modal();
} );
$('#mistake-modal .modal-send').on('click', sendMistake);
});
function sendMistake(){
//ajax
$('#mistake-modal').modal('close');
}
<file_sep><?php
namespace App\Controller\Manager;
use App\Controller\AppController;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
/**
* Static content controller
*
* This controller will render views from Template/Pages/
*
* @link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
*/
class IndexController extends AppController
{
/**
* Displays a view
*
* @return void|\Cake\Network\Response
* @throws \Cake\Network\Exception\NotFoundException When the view file could not
* be found or \Cake\View\Exception\MissingTemplateException in debug mode.
*/
public function index()
{
}
}<file_sep><nav class="col-lg-12 col-md-12 col-sm-12 col-xs-12 columns breadcrumb" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?=
$this->Form->postLink(
__('Delete'), ['action' => 'delete', $pupil->id],
['confirm' => __('Are you sure you want to delete # {0}?',
$pupil->id)]
)
?></li>
<li><?= $this->Html->link(__('List Pupil'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="pupil form col-lg-12 col-md-12 columns content">
<?= $this->Form->create($pupil) ?>
<fieldset>
<legend><?= __('Edit Pupil') ?></legend>
<div class="form-group">
<label for="name"><?= __('Name') ?></label>
<?=
$this->Form->text('name',
['placeholder' => __('Name'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="surname"><?= __('Surname') ?></label>
<?=
$this->Form->text('surname',
['placeholder' => __('Surname'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="patronymic"><?= __('Patronymic') ?></label>
<?=
$this->Form->text('patronymic',
['placeholder' => __('Patronymic'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="gender"><?= __('Gender') ?></label>
<?=
$this->Form->select('gender', [1 => __('Male'), 2 => __('Female')],
['placeholder' => __('Gender'), 'empty' => __('Choose gender'), 'class' => 'form-control']);
?>
</div>
<div class="form-group">
<label for="date_birth"><?= __('Date Birth') ?></label>
<?=
$this->Form->text('date_birth',
['placeholder' => __('Date Birth'), 'class' => 'date-month-year form-control']);
?>
</div>
<?= $this->Form->hidden('date_register'); ?>
<div class="form-group">
<label for="gender"><?= __('Schoolclas') ?></label>
<?=
$this->Form->select('schoolclas', $classNames,
['value' => $classId,
'placeholder' => __('Schoolclas'), 'empty' => __('Choose schoolclas'), 'class' => 'form-control']);
?>
</div>
</fieldset>
<?= $this->Form->button(__('Submit'), ['class' => 'form-control']) ?>
<?= $this->Form->end() ?>
</div>
<file_sep>(function ($) {
"use strict";
var validator = null,
contactForm = $('.contact-form');
$('body').scrollspy({
target: '.navbar-fixed-top',
offset: 60
});
$('#topNav').affix({
offset: {
top: 200
}
});
new WOW().init();
$('a.page-scroll').bind('click', function (event) {
var $ele = $(this);
$('html, body').stop().animate({
scrollTop: ($($ele.attr('href')).offset().top - 60)
}, 1450, 'easeInOutExpo');
event.preventDefault();
});
$('.navbar-collapse ul li a').click(function () {
/* always close responsive nav after click */
$('.navbar-toggle:visible').click();
});
$('#galleryModal').on('show.bs.modal', function (e) {
$('#galleryImage').attr("src", $(e.relatedTarget).data("src"));
});
function validateSendMessage() {
contactForm.validate({
rules: {
name: "required",
email: {
required: true,
email: true
},
phone: {
required: true,
phoneUA: true
},
message: {
required: true
}
},
submitHandler: function () {
$.ajax({
dataType: "json",
url: "/message/sendUserRequest",
data: contactForm.serialize(),
method: "POST",
success: function (res) {
if (res.result.status == true) {
$('.modal-body .success-send-message').removeClass('hidden');
$('.modal-body .error-send-message').addClass('hidden');
$('#sendMessageModal').modal('show');
$('#last').fadeOut('slow');
} else {
showErrorMessageModal();
}
},
fail: function () {
showErrorMessageModal();
$('#sendMessageModal').modal('show');
}
});
return false;
}
});
}
function showErrorMessageModal() {
$('.modal-body .success-send-message').addClass('hidden');
$('.modal-body .error-send-message').removeClass('hidden');
$('#sendMessageModal').modal('show');
}
$('document').ready(function () {
validateSendMessage();
});
})(jQuery);<file_sep><?php
namespace App\Controller\Teacher;
use App\Controller\AppController;
/**
* Users Controller
*
* @property \App\Model\Table\UsersTable $Users
*/
class UsersController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->viewBuilder()->layout('users');
}
}
<file_sep><nav class="col-lg-12 col-md-12 col-sm-12 col-xs-12 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('New Timetable'), ['action' => 'add']) ?></li>
</ul>
</nav>
<div class="timetable index col-lg-12 col-md-12 columns content">
<h3 class="page-header"><?= __('Timetable') ?></h3>
<table cellpadding="0" cellspacing="0" class="table table-striped">
<thead>
<tr>
<th><?= $this->Paginator->sort('id') ?></th>
<th><?= $this->Paginator->sort('lesson_id') ?></th>
<th><?= $this->Paginator->sort('teacher_id') ?></th>
<th><?= $this->Paginator->sort('class_id') ?></th>
<th><?= $this->Paginator->sort('date_table') ?></th>
<th><?= $this->Paginator->sort('date_begin') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($timetable as $timetable): ?>
<tr>
<td><?= $this->Number->format($timetable->id) ?></td>
<td><?= $this->Number->format($timetable->lesson_id) ?></td>
<td><?= $this->Number->format($timetable->teacher_id) ?></td>
<td><?= $this->Number->format($timetable->class_id) ?></td>
<td><?= h($timetable->date_table) ?></td>
<td><?= h($timetable->date_begin) ?></td>
<td class="actions">
<?= $this->Html->link(__('View'), ['action' => 'view', $timetable->id]) ?>
<?= $this->Html->link(__('Edit'), ['action' => 'edit', $timetable->id]) ?>
<?= $this->Form->postLink(__('Delete'), ['action' => 'delete', $timetable->id], ['confirm' => __('Are you sure you want to delete # {0}?', $timetable->id)]) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div>
</div>
<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
/**
* Pupil Controller
*
* @property \App\Model\Table\PupilTable $Pupil
*/
class PupilController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->set('pupil', $this->paginate($this->Pupil));
$this->set('_serialize', ['pupil']);
}
/**
* View method
*
* @param string|null $id Pupil id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$pupil = $this->Pupil->get($id, [
'contain' => []
]);
$this->set('pupil', $pupil);
$this->set('_serialize', ['pupil']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$pupil = $this->Pupil->newEntity();
if ($this->request->is('post')) {
$this->request->data['date_register'] = date("Y-m-d");
$pupil = $this->Pupil->patchEntity($pupil,
$this->request->data);
$pupil->set('date_birth', $this->request->data['date_birth']);
$pupil->set('date_register', date("Y-m-d H:i:s"));
$pupil->set('date_update', date("Y-m-d H:i:s"));
if ($this->Pupil->save($pupil)) {
$this->Flash->success(__('The pupil has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The pupil could not be saved. Please, try again.'));
}
}
$this->set(compact('pupil'));
$this->set('_serialize', ['pupil']);
}
/**
* Edit method
*
* @param string|null $id Pupil id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$pupil = $this->Pupil->get($id);
$this->loadModel('Schoolclass');
$schoolclassesItems = $this->Schoolclass->find('all', [
'conditions' => ['is_deleted' => false, 'is_active' => true]
]);
$classNames = [];
if (!empty($schoolclassesItems)) {
foreach ($schoolclassesItems as $schoolclassesItem) {
$classNames[$schoolclassesItem->id] = $schoolclassesItem->class_name;
}
}
$this->set(compact('classNames'));
$this->PupilSchoolclasses = TableRegistry::get('PupilSchoolclasses');
$pupilSchoolclassItems = $this->PupilSchoolclasses->find('all', [
'conditions' => ['pupil_id' => $id]
]);
$classId = "";
$pupilSchoolclass = $this->PupilSchoolclasses->newEntity();
if (!empty($pupilSchoolclassItems)) {
foreach ($pupilSchoolclassItems as $pupilSchoolclassItem) {
$pupilSchoolclass = $pupilSchoolclassItem;
$classId = $pupilSchoolclass->class_id;
break;
}
}
$this->set(compact('classId'));
if ($this->request->is(['patch', 'post', 'put'])) {
$pupil = $this->Pupil->patchEntity($pupil, $this->request->data);
$pupil->set('date_birth', $this->request->data['date_birth']);
$pupil->set('date_register', $this->request->data['date_register']);
$pupil->set('date_update', date("Y-m-d H:i:s"));
$pupilSchoolclass->pupil_id = $id;
$pupilSchoolclass->class_id = $this->request->data['schoolclas'];
if (!$this->Pupil->save($pupil) ) {
$this->Flash->error(__('The pupil could not be saved. Please, try again.'));
return $this->redirect($this->referer());
}
if (!$this->PupilSchoolclasses->save($pupilSchoolclass)) {
$this->Flash->error(__('The class could not be saved. Please, try again.'));
return $this->redirect($this->referer());
}
$this->Flash->success(__('The pupil has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->set(compact('pupil'));
$this->set('_serialize', ['pupil']);
}
/**
* Delete method
*
* @param string|null $id Pupil id.
* @return \Cake\Network\Response|null Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$pupil = $this->Pupil->get($id);
if ($this->Pupil->delete($pupil)) {
$this->Flash->success(__('The pupil has been deleted.'));
} else {
$this->Flash->error(__('The pupil could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}<file_sep><h1 class="page-header"><?= __('Dashboard') ?></h1>
<div class="row">
<div class="col-lg-3 col-md-6">
<div class="panel panel-primary">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-bell fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">000</div>
<div><?= __('Lessons today') ?></div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left"><?= __('View Details') ?></span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-green">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-tasks fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">000</div>
<div>New Tasks!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-yellow">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-envelope fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">000</div>
<div>New messages!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
<div class="col-lg-3 col-md-6">
<div class="panel panel-red">
<div class="panel-heading">
<div class="row">
<div class="col-xs-3">
<i class="fa fa-support fa-5x"></i>
</div>
<div class="col-xs-9 text-right">
<div class="huge">000</div>
<div>Support Tickets!</div>
</div>
</div>
</div>
<a href="#">
<div class="panel-footer">
<span class="pull-left">View Details</span>
<span class="pull-right"><i class="fa fa-arrow-circle-right"></i></span>
<div class="clearfix"></div>
</div>
</a>
</div>
</div>
</div>
<div class="col-sm-12 col-xs-12 col-lg-8">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-tasks fa-fw"></i> <?= __('Lessons');?>
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<?= __('Actions'); ?>
<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li><a href="#"><?= __('Hide'); ?></a>
</li>
<li><a href="#"><?= __('Close'); ?></a>
</li>
<li class="divider"></li>
<li><a href="#"><?= __('Remove forever'); ?></a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<ul>
<?php
$id = NULL;
foreach ($lessons as $id => $lesson) {
echo "<li><a href=\"/lesson/lesson/$id\">$lesson</a></li>";
}
?>
</ul>
</div>
<!-- /.panel-body -->
</div>
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-newspaper-o fa-fw"></i> <?= __('News');?>
<div class="pull-right">
<div class="btn-group">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown" aria-expanded="false">
<?= __('Actions'); ?>
<span class="caret"></span>
</button>
<ul class="dropdown-menu pull-right" role="menu">
<li><a href="#"><?= __('Hide'); ?></a>
</li>
<li><a href="#"><?= __('Close'); ?></a>
</li>
<li class="divider"></li>
<li><a href="#"><?= __('Remove forever'); ?></a>
</li>
</ul>
</div>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<ul>
<?php
$id = NULL;
foreach ($news as $id => $singleNews) {
echo "<li><a href=\"/lesson/$id\">$singleNews</a></li>";
}
?>
</ul>
</div>
<!-- /.panel-body -->
</div>
</div>
<div class="col-sm-12 col-xs-12 col-lg-4">
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-bell fa-fw"></i> Notifications Panel
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="list-group">
<a href="#" class="list-group-item">
<i class="fa fa-comment fa-fw"></i> New Comment
<span class="pull-right text-muted small"><em>4 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-envelope fa-fw"></i> Message Sent
<span class="pull-right text-muted small"><em>27 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-tasks fa-fw"></i> New Task
<span class="pull-right text-muted small"><em>43 minutes ago</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-bolt fa-fw"></i> Emergency!
<span class="pull-right text-muted small"><em>11:13 AM</em>
</span>
</a>
<a href="#" class="list-group-item">
<i class="fa fa-warning fa-fw"></i> Error
<span class="pull-right text-muted small"><em>10:57 AM</em>
</span>
</a>
</div>
<!-- /.list-group -->
<a href="#" class="btn btn-default btn-block">View All Alerts</a>
</div>
<!-- /.panel-body -->
</div>
<div class="chat-panel panel panel-default">
<div class="panel-heading">
<i class="fa fa-comments fa-fw"></i>
Chat
<div class="btn-group pull-right">
<button type="button" class="btn btn-default btn-xs dropdown-toggle" data-toggle="dropdown">
<i class="fa fa-chevron-down"></i>
</button>
<ul class="dropdown-menu slidedown">
<li>
<a href="#">
<i class="fa fa-refresh fa-fw"></i> Refresh
</a>
</li>
<li>
<a href="#">
<i class="fa fa-check-circle fa-fw"></i> Available
</a>
</li>
<li>
<a href="#">
<i class="fa fa-times fa-fw"></i> Busy
</a>
</li>
<li>
<a href="#">
<i class="fa fa-clock-o fa-fw"></i> Away
</a>
</li>
<li class="divider"></li>
<li>
<a href="#">
<i class="fa fa-sign-out fa-fw"></i> Sign Out
</a>
</li>
</ul>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<ul class="chat">
<li class="left clearfix">
<span class="chat-img pull-left">
<img src="http://placehold.it/50/55C1E7/fff" alt="User Avatar" class="img-circle">
</span>
<div class="chat-body clearfix">
<div class="header">
<strong class="primary-font">Name Surname</strong>
<small class="pull-right text-muted">
<i class="fa fa-clock-o fa-fw"></i> 12 mins ago
</small>
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare dolor, quis ullamcorper ligula sodales.
</p>
</div>
</li>
<li class="right clearfix">
<span class="chat-img pull-right">
<img src="http://placehold.it/50/FA6F57/fff" alt="User Avatar" class="img-circle">
</span>
<div class="chat-body clearfix">
<div class="header">
<small class=" text-muted">
<i class="fa fa-clock-o fa-fw"></i> 15 mins ago</small>
<strong class="pull-right primary-font"><NAME></strong>
</div>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Curabitur bibendum ornare dolor, quis ullamcorper ligula sodales.
</p>
</div>
</li>
</ul>
</div>
<!-- /.panel-body -->
<div class="panel-footer">
<div class="input-group">
<input id="btn-input" type="text" class="form-control input-sm" placeholder="Type your message here...">
<span class="input-group-btn">
<button class="btn btn-warning btn-sm" id="btn-chat">
Send
</button>
</span>
</div>
</div>
<!-- /.panel-footer -->
</div>
</div>
<file_sep>/*
Created on : Jan 23, 2016, 9:22:22 PM
Author : gregzorb
*/
$('document').ready(function () {
// col-lg-3 col-xs-3 col-sm-1
var mistakeLink = '<div id="send-mistake-report" class="send-mistake-report btn btn-warning ">' +
'Повідомити про помилку' +
'</div>';
$('#wrapper').before(mistakeLink);
$('.send-mistake-report').on('click', function () {
$('#mistake-modal').modal();
});
$('#mistake-modal .modal-send').on('click', sendMistake);
$('#mistake-modal .modal-close').on('click', function () {
$('#mistake-modal').modal('close');
});
});
function sendMistake() {
$.ajax({
dataType: "json",
url: "/message/sendUserRequest",
data: $('.mistake-input').serialize(),
method: "POST",
success: function () {
$('.modal-content .mistake-result').remove();
$('.modal-title').after('<p class="mistake-result bg-success">Thanks for your message</p>');
$('#mistake-modal').modal('close');
},
fail: function () {
$('.modal-content .mistake-result').remove();
$('.modal-title').after('<p class="mistake-result bg-danger">Error while reporting</p>')
$('#mistake-modal').modal('close');
}
});
}
<file_sep><nav class="col-lg-12 col-sm-12 col-xs-12 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('List Schoolclass'), ['action' => 'index']) ?></li>
</ul>
</nav>
<div class="flash col-lg-12 col-md-12 "><?= $this->Flash->render() ?></div>
<div class="schoolclass form col-lg-12 col-md-12 columns content">
<h3 class="page-header"><?= __('Schoolclass') ?></h3>
<?= $this->Form->create($schoolclas) ?>
<fieldset>
<legend><?= __('Add Schoolclas') ?></legend>
<div class="form-group col-lg-4 col-md-4">
<?php echo $this->Form->input('prefix', ['type' => 'text', 'class' => 'form-control']); ?>
</div>
<div class="form-group col-lg-2 col-md-2">
<?php echo $this->Form->input('class_number', ['type' => 'text', 'class' => 'form-control']); ?>
</div>
<div class="form-group col-lg-4 col-md-4">
<?php echo $this->Form->input('suffix', ['type' => 'text', 'class' => 'form-control']); ?>
</div>
<div class="form-group col-lg-2 col-md-2">
<?php echo $this->Form->input('is_active', [ 'type' => 'checkbox', 'class' => 'form-control']); ?>
</div>
<?php echo $this->Form->input('is_deleted', [ 'type' => 'hidden', 'value' => 0]); ?>
</fieldset>
<?= $this->Form->button(__('Submit')) ?>
<?= $this->Form->end() ?>
</div>
<file_sep><nav class="col-lg-12 col-md-12 col-sm-12 col-xs-12 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('Edit Pupil'),
['action' => 'edit', $pupil->id])
?> </li>
<li><?=
$this->Form->postLink(__('Delete Pupil'),
['action' => 'delete', $pupil->id],
['confirm' => __('Are you sure you want to delete # {0}?',
$pupil->id)])
?> </li>
<li><?= $this->Html->link(__('List Pupil'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Pupil'), ['action' => 'add']) ?> </li>
</ul>
</nav>
<div class="pupil view col-lg-12 col-md-12 columns content">
<h3 class="col-lg-12 col-md-6 col-sm-12 col-xs-12 ">
<?= h($pupil->name)." ". h($pupil->patronymic) ." ". h($pupil->surname) ?>
</h3>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<?php $avatarUrl = "http://modeley.net/photo/4493/15442.jpg"; ?>
<img src="<?= $avatarUrl ?>" class="col-lg-push-2 col-lg-8 col-md-6 col-sm-12 col-xs-12">
</div>
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 ">
<table class="table table-striped">
<tr>
<th><?= __('Id') ?></th>
<td><?= $this->Number->format($pupil->id) ?></td>
</tr>
<tr>
<th><?= __('Gender') ?></th>
<td><?= ($pupil->gender == 1? __('Male'): __('Female')) ?></td>
</tr>
<tr>
<th><?= __('Date Birth') ?></th>
<td><?= $this->Time->format( $pupil->date_birth, \IntlDateFormatter::MEDIUM) ?></td>
</tr>
<tr>
<th><?= __('Date Register') ?></th>
<td><?= $this->Time->format( $pupil->date_register, \IntlDateFormatter::MEDIUM) ?></td>
</tr>
</table>
</div>
</div>
<file_sep><?php
namespace App\Model\Table;
use Cake\ORM\Table;
use Cake\Validation\ValidatorAwareTrait;
use Cake\Validation\Validator;
class PupilTable extends Table
{
public function validationDefault(Validator $validator)
{
$validator->notEmpty('name');
$validator->notEmpty('surname');
$validator->notEmpty('patronymic');
$validator->notEmpty('gender');
$validator->notEmpty('date_birth');
$validator->notEmpty('date_register');
$validator->notEmpty('date_update');
return $validator;
}
}<file_sep><?php
namespace App\Controller\Admin;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
/**
* Timetable Controller
*
* @property \App\Model\Table\TimetableTable $Timetable
*/
class TimetableController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->set('timetable', $this->paginate($this->Timetable));
$this->set('_serialize', ['timetable']);
}
/**
* View method
*
* @param string|null $id Timetable id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$timetable = $this->Timetable->get($id, [
'contain' => []
]);
$this->set('timetable', $timetable);
$this->set('_serialize', ['timetable']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$classNames = $this->getClassNames();
$this->set(compact('classNames'));
$teachers = $this->getTeacherList();
$this->set(compact('teachers'));
$lessons = $this->getLessons();
$this->set(compact('lessons'));
$timetable = $this->Timetable->newEntity();
if ($this->request->is('post')) {
$timetable = $this->Timetable->patchEntity($timetable, $this->request->data);
if ($this->Timetable->save($timetable)) {
$this->Flash->success(__('The timetable has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The timetable could not be saved. Please, try again.'));
}
}
$this->set(compact('timetable'));
$this->set('_serialize', ['timetable']);
}
/**
* Edit method
*
* @param string|null $id Timetable id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$classNames = $this->getClassNames();
$this->set(compact('classNames'));
$teachers = $this->getTeacherList();
$this->set(compact('teachers'));
$lessons = $this->getLessons();
$this->set(compact('lessons'));
$timetable = $this->Timetable->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$timetable = $this->Timetable->patchEntity($timetable, $this->request->data);
if ($this->Timetable->save($timetable)) {
$this->Flash->success(__('The timetable has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The timetable could not be saved. Please, try again.'));
}
}
$this->set(compact('timetable'));
$this->set('_serialize', ['timetable']);
}
/**
* Delete method
*
* @param string|null $id Timetable id.
* @return \Cake\Network\Response|null Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$timetable = $this->Timetable->get($id);
if ($this->Timetable->delete($timetable)) {
$this->Flash->success(__('The timetable has been deleted.'));
} else {
$this->Flash->error(__('The timetable could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
<file_sep><!-- File: src/Template/Users/login.ctp -->
<h2 class="form-signin-heading"><?= __('Please enter your username and password') ?></h2>
<br>
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<?=
$this->Form->input('username',
[
"label" => [
"text" => __('Enter your username'),
"class" => "sr-only",
],
"class" => "form-control",
"placeholder" => __('Enter your username'),
])
?>
<br>
<?=
$this->Form->input('password',
[
"label" => [
"text" => __('Enter your password'),
"class" => "sr-only",
],
"class" => "form-control",
"placeholder" => __('Enter your password')])
?>
<br>
<?= $this->Form->button(__('Login'),
['class' => 'btn btn-lg btn-primary btn-block']);
?>
<div>
<!-- TODO: create links -->
<?php echo $this->Html->link(__('Create account'),'/users/register', []); ?>
or
<?php echo $this->Html->link(__('reset password'), '/users/reset'); ?>
</div>
<?= $this->Form->end() ?>
<file_sep><h2 class="form-signin-heading"><?= __('Please enter your username for recover password') ?></h2>
<?= $this->Flash->render('auth') ?>
<?= $this->Form->create() ?>
<?=
$this->Form->input('username',
[
"label" => [
"text" => __('Enter your username'),
"class" => "sr-only",
],
"class" => "form-control",
"placeholder" => __('Enter your username'),
])
?>
<br>
<?= $this->Form->button(__('Reset password'),
['class' => 'btn btn-lg btn-primary btn-block']);
?>
<br>
<?= $this->Form->end() ?>
<file_sep><nav class="col-lg-12 col-sm-12 col-xs-12 columns breadcrumb" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Journal') ?></li>
</ul>
</nav>
<div class="journal index col-lg-12 col-xs-12 col-sm-12 columns content">
<h3 class="page-header"><?= __('Journal') ?></h3>
<table cellpadding="0" cellspacing="0" class="table table-striped">
<thead>
<tr>
<th><?= $this->Paginator->sort('id') ?></th>
<th><?= $this->Paginator->sort('user_id') ?></th>
<th><?= $this->Paginator->sort('lesson_id') ?></th>
<th><?= $this->Paginator->sort('mark_id') ?></th>
<th><?= $this->Paginator->sort('status_id') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($journal as $journal): ?>
<tr>
<td><?= $this->Number->format($journal->id) ?></td>
<td><?= $this->Number->format($journal->user_id) ?></td>
<td><?= $this->Number->format($journal->lesson_id) ?></td>
<td><?= $this->Number->format($journal->mark_id) ?></td>
<td><?= $this->Number->format($journal->status_id) ?></td>
<td class="actions">
<?=
$this->Html->link(__('View'),
['action' => 'view', $journal->id])
?>
<?=
$this->Html->link(__('Edit'),
['action' => 'edit', $journal->id])
?>
<?=
$this->Form->postLink(__('Delete'),
['action' => 'delete', $journal->id],
['confirm' => __('Are you sure you want to delete # {0}?',
$journal->id)])
?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< '.__('previous')) ?>
<?= $this->Paginator->numbers() ?>
<?= $this->Paginator->next(__('next').' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div>
</div>
<?php
$datesWithLessons = [
4, 7, 11, 14, 18, 21
];
?>
<!-- Page Heading -->
<div class="row col-lg-12 col-xs-12 col-sm-12">
<h3 class="page-header"><?= __('Current lesson') ?>: <?php echo $currentLesson['name']; ?></h3>
</div>
<!-- /.row -->
<div class="row col-lg-12 col-xs-12 col-sm-12">
<a class="btn btn-default" href="javascript:void(0)" role="button"><?= __('Give homework') ?></a>
</div>
<div class="row col-lg-12 col-xs-12 col-sm-12">
<ol class="breadcrumb">
<li class="active">
<i class="fa fa-dashboard"></i> <?= __('Pupils'); ?>
</li>
</ol>
</div>
<div class="row col-lg-12 col-xs-12 col-sm-12">
<table class="table table-striped">
<tr>
<th><?= __('Pupil'); ?></th>
<?php
foreach ($datesWithLessons as $dateWithLessons) {
echo "<th>$dateWithLessons</th>";
}
?>
</tr>
<?php foreach ($pupils as $pupil) { ?>
<tr>
<td>
<?php
$viewFullName = $pupil->get('surname')." ".
$pupil->get('name')." ".
$pupil->get('patronymic');
?>
<?=
$this->Html->link($viewFullName,
['controller' => 'pupil', 'action' => 'view', $pupil->get('id')])
?>
</td>
<td>Н</td>
<td>Н</td>
<td>Н</td>
<td>Н</td>
<td>Н</td>
<td>
<input type="number" min="1" max="12" step="1" pattern="[0-9]*" inputmode="numeric">
</td>
</tr>
<?php } ?>
</table>
</div>
<file_sep><?php
namespace App\Controller\Teacher;
use App\Controller\AppController;
use Cake\ORM\TableRegistry;
/**
* Timetable Controller
*
* @property \App\Model\Table\TimetableTable $Timetable
*/
class TimetableController extends AppController
{
/**
* Index method
*
* @return void
*/
public function index()
{
$this->set('timetable', $this->paginate($this->Timetable));
$this->set('_serialize', ['timetable']);
}
/**
* View method
*
* @param string|null $id Timetable id.
* @return void
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function view($id = null)
{
$timetable = $this->Timetable->get($id, [
'contain' => []
]);
$this->set('timetable', $timetable);
$this->set('_serialize', ['timetable']);
}
/**
* Add method
*
* @return void Redirects on successful add, renders view otherwise.
*/
public function add()
{
$this->Schoolclass = TableRegistry::get('Schoolclass');
$schoolclassesItems = $this->Schoolclass->find('all', [
'conditions' => ['is_deleted' => false, 'is_active' => true]
]);
$classNames = [];
if (!empty($schoolclassesItems)) {
foreach ($schoolclassesItems as $schoolclassesItem) {
$classNames[$schoolclassesItem->id] = $schoolclassesItem->class_name;
}
}
$this->set(compact('classNames'));
$this->User = TableRegistry::get('Users');
$userItems = $this->User->find('all', [
'conditions' => ['role' => 'teacher']
]);
$teachers = [];
if (!empty($userItems)){
foreach ( $userItems as $item){
$teachers[$item->id] = $item->username;
}
}
$this->set(compact('teachers'));
$this->Lesson = TableRegistry::get('Lessons');
$lessonItems = $this->Lesson->find('all', [
'conditions' => []
]);
$lessons = [];
if (!empty($lessonItems)){
foreach ( $lessonItems as $item){
$lessons[$item->id] = $item->name;
}
}
$this->set(compact('lessons'));
$timetable = $this->Timetable->newEntity();
if ($this->request->is('post')) {
$timetable = $this->Timetable->patchEntity($timetable, $this->request->data);
if ($this->Timetable->save($timetable)) {
$this->Flash->success(__('The timetable has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The timetable could not be saved. Please, try again.'));
}
}
$this->set(compact('timetable'));
$this->set('_serialize', ['timetable']);
}
/**
* Edit method
*
* @param string|null $id Timetable id.
* @return void Redirects on successful edit, renders view otherwise.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function edit($id = null)
{
$timetable = $this->Timetable->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$timetable = $this->Timetable->patchEntity($timetable, $this->request->data);
if ($this->Timetable->save($timetable)) {
$this->Flash->success(__('The timetable has been saved.'));
return $this->redirect(['action' => 'index']);
} else {
$this->Flash->error(__('The timetable could not be saved. Please, try again.'));
}
}
$this->set(compact('timetable'));
$this->set('_serialize', ['timetable']);
}
/**
* Delete method
*
* @param string|null $id Timetable id.
* @return \Cake\Network\Response|null Redirects to index.
* @throws \Cake\Network\Exception\NotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$timetable = $this->Timetable->get($id);
if ($this->Timetable->delete($timetable)) {
$this->Flash->success(__('The timetable has been deleted.'));
} else {
$this->Flash->error(__('The timetable could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
<file_sep><nav class="col-lg-12 col-md-12 col-sm-12 col-xs-12 columns" id="actions-sidebar">
<ul class="side-nav">
<li class="heading"><?= __('Actions') ?></li>
<li><?= $this->Html->link(__('Edit Timetable'), ['action' => 'edit', $timetable->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Timetable'), ['action' => 'delete', $timetable->id], ['confirm' => __('Are you sure you want to delete # {0}?', $timetable->id)]) ?> </li>
<li><?= $this->Html->link(__('List Timetable'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Timetable'), ['action' => 'add']) ?> </li>
</ul>
</nav>
<div class="timetable view col-lg-12 col-md-12 columns content">
<h3><?= h($timetable->id) ?></h3>
<table class="vertical-table">
<tr>
<th><?= __('Id') ?></th>
<td><?= $this->Number->format($timetable->id) ?></td>
</tr>
<tr>
<th><?= __('Lesson Id') ?></th>
<td><?= $this->Number->format($timetable->lesson_id) ?></td>
</tr>
<tr>
<th><?= __('Teacher Id') ?></th>
<td><?= $this->Number->format($timetable->teacher_id) ?></td>
</tr>
<tr>
<th><?= __('Class Id') ?></th>
<td><?= $this->Number->format($timetable->class_id) ?></td>
</tr>
<tr>
<th><?= __('Date Table') ?></th>
<td><?= h($timetable->date_table) ?></td>
</tr>
<tr>
<th><?= __('Date Begin') ?></th>
<td><?= h($timetable->date_begin) ?></td>
</tr>
</table>
</div>
<file_sep><?php
namespace App\Controller\Teacher;
use App\Controller\AppController;
use Cake\Core\Configure;
use Cake\Network\Exception\NotFoundException;
use Cake\View\Exception\MissingTemplateException;
use Cake\ORM\TableRegistry;
/**
* Static content controller
*
* This controller will render views from Template/Pages/
*
* @link http://book.cakephp.org/3.0/en/controllers/pages-controller.html
*/
class IndexController extends AppController
{
/**
* Displays a view
*
* @return void|\Cake\Network\Response
* @throws \Cake\Network\Exception\NotFoundException When the view file could not
* be found or \Cake\View\Exception\MissingTemplateException in debug mode.
*/
public function index()
{
$lessons = [
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
];
$this->set(compact('lessons'));
$news = [
'Батьківські збори',
'Засідання вчителів',
'Методичні вказівки',
'Новина',
'Новина',
'Новина',
'Новина',
'Новина',
'Новина',
];
$this->set(compact('news'));
}
}<file_sep><?php
$lessons = [
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
'Математика, 7А',
];
$news = [
'Батьківські збори',
'Засідання вчителів',
'Методичні вказівки',
'Новина',
'Новина',
'Новина',
'Новина',
'Новина',
'Новина',
];
?>
<div class="row col-sm-12 col-xs-12">
<div class="col-sm-6 col-xs-12">
<div class="panel panel-green">
<div class="panel-heading">
<h3 class="panel-title">Уроки сьогодні</h3>
</div>
<div class="panel-body">
<ul>
<?php
$id = NULL;
foreach ($lessons as $id => $lesson) {
echo "<li><a href=\"/lesson/lesson/$id\">$lesson</a></li>";
}
?>
</ul>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="panel panel-green">
<div class="panel-heading">
<h3 class="panel-title">Новини тижня</h3>
</div>
<div class="panel-body">
<ul>
<?php
$id = NULL;
foreach ($news as $id => $singleNews) {
echo "<li><a href=\"/lesson/$id\">$singleNews</a></li>";
}
?>
</ul>
</div>
</div>
</div>
</div>
<div class="row col-sm-12 col-xs-12">
<div class="col-sm-6 col-xs-12">
<div class="panel panel-green">
<div class="panel-heading">
<h3 class="panel-title">Інше</h3>
</div>
<div class="panel-body">
<ul>
<li> інше</li>
<li> інше</li>
<li> інше</li>
<li> інше</li>
</ul>
</div>
</div>
</div>
<div class="col-sm-6 col-xs-12">
<div class="panel panel-green">
<div class="panel-heading">
<h3 class="panel-title">Інше</h3>
</div>
<div class="panel-body">
<ul>
<li> інше</li>
<li> інше</li>
<li> інше</li>
<li> інше</li>
</ul>
</div>
</div>
</div>
</div>
|
b47dd793191eb14d26a13341c595df2876ce81d2
|
[
"Markdown",
"JavaScript",
"PHP"
] | 41
|
PHP
|
hopealive/qmatio
|
2219895075cb16437ea5e667db652eeda1661b1a
|
eb4ec4255f5c63d090d9d3490c22b02064908be9
|
refs/heads/master
|
<repo_name>robpullan85/GitHubProjects<file_sep>/README.md
# **Memory Game Project**
The project is a memory game based on matching paired symbols by turning over cards.
The project was created and relies heavily on HTML, CSS, JavaScript and jQuery.
The JavaScript code was broken down to include pre-initialized variables, arrays and small functions to help make the code more readable. All the HTML, CSS and JavaScript contained descriptive class, ID, variables and array names.
The game will start with a modal window asking the player to begin the game and explaining how to play the game.
Once they click ‘start game’ the timer will start immediately and will stop once the game was finished.
During gameplay the star rating and move count is tracked. A move count is defined as turning over 2 cards and not 1. The star ratings are based on how many moves the player uses to complete the game.
The game will be marked as finished once the all cards have been matched to their corresponding symbol which then displays another modal window with the game statistics.
In this modal window the player is then offered another game.
<file_sep>/jQuery.js
$(document).ready(function()
{
// initial arrays set
let arrayClassName = [];
let arrayIdName = [];
let arraySelectorName = [];
// initial variables set
let matchCount = 0;
let movesCount = 0;
// click event to restart the game at the players choice.
$('.restart').click(cardShuffle);
// restarts game from the completed modal window.
$('#restartGameCompleted').click(cardShuffle);
// updates the number of moves the player has taken.
$('#starsNumber').html(movesCount)
// Shows the modal on page load.
$('#beginModal').modal('show');
// Opens the modal to being the game.
$('#beginGame').click(setTimer);
// Event function to await the user to select a card.
$('.card').click(function()
{
if ($(this).hasClass('show open'))
{
$(this).removeClass('show open');
}
else
{
$(this).addClass('show open');
var className = $(this).children().attr('class');
var idName = $(this).children().attr('id');
var selectorName = $(this);
arrayClassName.push(className);
arrayIdName.push(idName);
arraySelectorName.push(selectorName);
if (arrayClassName.length === 2)
{
// Calls the amount of moves taken.
moveAmount();
if (arrayClassName[0] === arrayClassName[1] && arrayIdName[0] !== arrayIdName[1])
// Checks for card match
cardMatch();
else
// If no card match the function below will reset the cards
resetCards();
}
}
// Checks the amount of card matches.
gameCheck();
});
// Function to shuffles the cards
function cardShuffle() {
var arraydeckClass = $(".deck");
var arraycardClass = arraydeckClass.children();
while (arraycardClass.length) {
arraydeckClass.append(arraycardClass.splice(Math.floor(Math.random() * arraycardClass.length), 1)[0]);
}
$('.card').removeClass('show open match');
matchCount = 0;
starMoveReset();
stopTimer();
resetTimer();
setTimer()
};
// Function to reset the star and moves section back to default.
function starMoveReset(){
movesCount = 0;
$('#starsNumber').html(movesCount)
for (var i = 1; i < 4; i++)
$('#star' + i).removeClass('fa fa-star-o').addClass('fa fa-star');
}
// This function will keep track of the amount moves taking place
// and edits the stars depending on number of stars.
function moveAmount()
{
movesCount += 1;
$('#starsNumber').html(movesCount)
if (movesCount > 24)
$('#star2').removeClass('fa-star').addClass('fa-star-o');
else if (movesCount > 12)
$('#star3').removeClass('fa-star').addClass('fa-star-o');
else
return;
};
// This function will show a card match and empty the arrays.
function cardMatch()
{
arraySelectorName[0].removeClass('show').addClass('match');
arraySelectorName[1].removeClass('show').addClass('match');
arrayIdName = [];
arrayClassName = [];
arraySelectorName = [];
matchCount += 1;
return matchCount;
};
// This function will reset the cards back to default using a time delay.
function resetCards()
{
setTimeout(function() {
arraySelectorName[0].removeClass('show open');
arraySelectorName[1].removeClass('show open');
arrayIdName = [];
arrayClassName = [];
arraySelectorName = [];
}, 500);
};
// Checks if all the cards have been matched.
function gameCheck()
{
var winWindows = $('#completedModal');
setTimeout(function()
{
if (matchCount === 8)
{
stopTimer()
completedModal();
}
}, 500);
};
// Displays the completed modal with statistics.
function completedModal()
{
// time game finished
var seconds = secondsLabel.innerHTML = pad(totalSeconds%60);
var minutes = minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
$('#secondsFinished').html(seconds);
$('#minutesFinished').html(minutes);
// move total
$('#completedModal').modal('show');
// star rating
$('#starsNumberModal').html(movesCount);
if (movesCount > 24)
$('#starRatingModal').html(1)
else if (movesCount > 12)
$('#starRatingModal').html(2)
else
$('#starRatingModal').html("Top")
}
}); // End of document ready function
<file_sep>/Timer.js
// function to assist the setTime function, stops the timer
// receiving 3 digit numbers
function pad(val) {
valString = val + "";
if(valString.length < 2)
{
return "0" + valString;
}
else
{
return valString;
}
}
// function to keep the timer ticking, depends on the pad function
totalSeconds = 0;
function setTime(minutesLabel, secondsLabel) {
totalSeconds++;
secondsLabel.innerHTML = pad(totalSeconds%60);
minutesLabel.innerHTML = pad(parseInt(totalSeconds/60));
}
// function to start the timer
function setTimer() {
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
time = setInterval(function() { setTime(minutesLabel, secondsLabel)}, 1000);
}
// function to stop timer at the current position
function stopTimer() {
clearInterval(time);
}
// function to reset timer back to 00:00
function resetTimer(){
totalSeconds = 0;
minutesLabel = document.getElementById("minutes");
secondsLabel = document.getElementById("seconds");
secondsLabel.innerHTML = "00";
minutesLabel.innerHTML = "00";
}
|
db3d108b7c44fd3127399656ebe28bdab00d10e9
|
[
"Markdown",
"JavaScript"
] | 3
|
Markdown
|
robpullan85/GitHubProjects
|
eb17031e13782a5c2649550b328a9ff47bcd987d
|
4fdb762c6c220f52104e037063bfffe0d3222a77
|
refs/heads/master
|
<repo_name>vuvuongvi/SystemT-FrontEnd<file_sep>/src/views/Pages/Graphql/Graphql.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import ApolloClient from 'apollo-boost';
import { ApolloProvider } from '@apollo/react-hooks';
import { gql } from 'apollo-boost';
const client = new ApolloClient({
uri: 'http://localhost:3002/graphql',
});
let loginQuery = gql`
query login($name: String!, $password: String!) {
login(name: $name, password: $password) {
token
}
}
`
export const authenSignIn = async (name, password) => {
client.query({
query: loginQuery,
variables: {
name: name,
password: <PASSWORD>
}
}).then(result => {
if (result) {
localStorage.setItem('sys_access', result.data.login.token);
}
});
}
<file_sep>/src/views/Pages/Login/Login.js
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { Button, Card, CardBody, CardGroup, Col, Container, Form, Input, InputGroup, InputGroupAddon, InputGroupText, Row } from 'reactstrap';
import { authenSignIn } from '../Graphql/Graphql'
import gql from 'graphql-tag';
import { setToken } from './token';
import {Redirect} from 'react-router-dom'
class Login extends Component {
state = {
login: true,
email: '',
password: '',
name: '',
isLogin: true
}
render() {
const { login, email, password, name, isLogin } = this.state
return (
<div className="app flex-row align-items-center">
<Container>
<Row className="justify-content-center">
<Col md="8">
<CardGroup>
<Card className="p-4">
<CardBody>
<Form>
<h4 className="mv3">{isLogin ? 'Login' : 'Sign Up'}</h4>
<p className="text-muted">Sign In to your account</p>
<div className="flex flex-column">
{!login && (
<input
value={name}
onChange={e => this.setState({ name: e.target.value })}
type="text"
placeholder="Your name"
/>
)}
<input
value={email}
onChange={e => this.setState({ email: e.target.value })}
type="text"
placeholder="Your email address"
/>
<input
value={password}
onChange={e => this.setState({ password: e.target.value })}
type="password"
placeholder="Choose a safe password"
/>
</div>
<div className="flex mt3">
<button type="button" class="btn btn-primary" onClick={this._confirm}>
{login ? 'login' : 'create account'}
</button>
<button type="button" onClick={() => this.setState({ login: !login })} class="pointer button"><span class="cil-contrast btn-icon mr-2"></span>
{login
? 'Need to create account?'
: 'already have an account'
}
</button>
</div>
</Form>
</CardBody>
</Card>
</CardGroup>
</Col>
</Row>
</Container>
</div>
)
}
_confirm = async () => {
let authen = authenSignIn(this.state.email, this.state.password)
.catch((error) => {
throw new Error(error);
})
if(authen) {
window.location.href = '/dashboard'
}
}
_saveUserData = token => {
setToken(token)
}
}
export default Login;
|
3d04971451cbf794be814a395418a2ebafa9c9f8
|
[
"JavaScript"
] | 2
|
JavaScript
|
vuvuongvi/SystemT-FrontEnd
|
6c2e36f3d74a0c5a960a56c626c59593c96598a0
|
a483d664c84df0f2c54b51003bde4768c382f8a2
|
refs/heads/main
|
<file_sep>const { test, assert } = require('@playwright/test');
test('Test 1', async ({page}) => {
// const browser = await firefox.launch({
// headless: false
// });
// const context = await browser.newContext();
// // Open new page
// const page = await context.newPage();
// Go to https://app.front.workwolf.com/credentials
await page.goto('https://app.front.workwolf.com/credentials');
// Go to https://app.front.workwolf.com/
await page.goto('https://app.front.workwolf.com/');
// Go to https://app.front.workwolf.com/login
await page.goto('https://app.front.workwolf.com/login');
// Click input[name="email"]
await page.click('input[name="email"]');
// Fill input[name="email"]
await page.fill('input[name="email"]', '<EMAIL>');
// Press Enter
await page.press('input[name="email"]', 'Enter');
// Click input[name="password"]
await page.click('input[name="password"]');
// Press CapsLock
await page.press('input[name="password"]', 'CapsLock');
// Fill input[name="password"]
await page.fill('input[name="password"]', 'A');
// Press CapsLock
await page.press('input[name="password"]', 'CapsLock');
// Fill input[name="password"]
await page.fill('input[name="password"]', '<PASSWORD>#');
// Press Enter
await Promise.all([
page.waitForNavigation(/*{ url: 'https://app.front.workwolf.com/credentials' }*/),
page.press('input[name="password"]', 'Enter')
]);
// Click text="Reference Guide"
const [page1] = await Promise.all([
page.waitForEvent('popup'),
page.click('text="Reference Guide"')
]);
// Close page
await page1.close();
// Click text="DOWNLOAD REPORT"
await page.click('text="DOWNLOAD REPORT"');
// 0× click
await page.click('//div[starts-with(normalize-space(.), \'Packfinder - Personality AssessmentReference GuideCOMPLETEDShow Personality Asse\')]');
// Click //*[local-name()="svg"]
await page.click('//*[local-name()="svg"]');
// Close page
await page.close();
});<file_sep>const { test, expect } = require('@playwright/test');
test('Test 2', async ({page}) => {
// Go to https://app.front.workwolf.com/credentials
await page.goto('https://app.front.workwolf.com/credentials');
// Go to https://app.front.workwolf.com/
await page.goto('https://app.front.workwolf.com/');
// Go to https://app.front.workwolf.com/login
await page.goto('https://app.front.workwolf.com/login');
// Click input[name="email"]
await page.click('input[name="email"]');
// Fill input[name="email"]
await page.fill('input[name="email"]', '<EMAIL>');
// Press Enter
await page.press('input[name="email"]', 'Enter');
// Click input[name="password"]
await page.click('input[name="password"]');
// Press CapsLock
await page.press('input[name="password"]', 'CapsLock');
// Fill input[name="password"]
await page.fill('input[name="password"]', 'A');
// Press CapsLock
await page.press('input[name="password"]', 'CapsLock');
// Fill input[name="password"]
await page.fill('input[name="password"]', '<PASSWORD>#');
// Press Enter
await Promise.all([
page.waitForNavigation(/*{ url: 'https://app.front.workwolf.com/credentials' }*/),
page.press('input[name="password"]', 'Enter')
]);
// Click //header[starts-with(normalize-space(.), 'Dashboard Digital Work Passport Orders CartAbout usProductsSupportLog outDashboa')]/button/*[local-name()="svg"]
await page.click('//header[starts-with(normalize-space(.), \'Dashboard Digital Work Passport Orders CartAbout usProductsSupportLog outDashboa\')]/button/*[local-name()="svg"]');
// Click text=/.*Dashboard.*/
await page.click('text=/.*Dashboard.*/');
expect(page.url()).toBe('https://app.front.workwolf.com/dashboard');
// Click text="Manage my Viewers"
await page.click('text="Manage my Viewers"');
expect(page.url()).toBe('https://app.front.workwolf.com/access/viewers');
// Click //header[starts-with(normalize-space(.), 'Dashboard Digital Work Passport Orders CartAbout usProductsSupportLog outDashboa')]/button/*[local-name()="svg"]
await page.click('//header[starts-with(normalize-space(.), \'Dashboard Digital Work Passport Orders CartAbout usProductsSupportLog outDashboa\')]/button/*[local-name()="svg"]');
// Click text=/.*Dashboard.*/
await page.click('text=/.*Dashboard.*/');
expect(page.url()).toBe('https://app.front.workwolf.com/dashboard');
// Click text="Manage my Requests"
await page.click('text="Manage my Requests"');
expect(page.url()).toBe('https://app.front.workwolf.com/access/pending');
// Click //*[local-name()="svg"]
await page.click('//*[local-name()="svg"]');
// Close page
await page.close();
});<file_sep>const { test, expect } = require('@playwright/test');
test('Test 6', async ({page}) => {
// Go to https://app.front.workwolf.com/credentials
await page.goto('https://app.front.workwolf.com/credentials');
// Go to https://app.front.workwolf.com/
await page.goto('https://app.front.workwolf.com/');
// Go to https://app.front.workwolf.com/login
await page.goto('https://app.front.workwolf.com/login');
// Click input[name="email"]
await page.click('input[name="email"]');
// Fill input[name="email"]
await page.fill('input[name="email"]', '<EMAIL>');
// Press Enter
await page.press('input[name="email"]', 'Enter');
// Click input[name="password"]
await page.click('input[name="password"]');
// Press CapsLock
await page.press('input[name="password"]', '<PASSWORD>');
// Fill input[name="password"]
await page.fill('input[name="password"]', 'A');
// Press CapsLock
await page.press('input[name="password"]', 'Caps<PASSWORD>');
// Fill input[name="password"]
await page.fill('input[name="password"]', '<PASSWORD>#');
// Press Enter
await Promise.all([
page.waitForNavigation(/*{ url: 'https://app.front.workwolf.com/credentials' }*/),
page.press('input[name="password"]', 'Enter')
]);
// Click //*[local-name()="svg"]
await page.click('//*[local-name()="svg"]');
// Fill input[name="firstName"]
await page.fill('input[name="firstName"]', 'Steven');
// Go to https://app.front.workwolf.com/logout
await page.goto('https://app.front.workwolf.com/logout');
// Close page
await page.close();
});
|
7e0ccfd6389e6b5c6da0618676087b412204e84d
|
[
"JavaScript"
] | 3
|
JavaScript
|
stevenxu1998/Playwright
|
59c75fcb1cd7be4e40b505fcc2a49ead9763ce2d
|
c56c21a7ffb1ae4f8f67c851939fb0466777d676
|
refs/heads/master
|
<file_sep>/**
* @type import('hardhat/config').HardhatUserConfig
*/
module.exports = {
solidity: {
version: '0.6.12',
settings: {
evmVersion: 'istanbul',
optimizer: {
enabled: true,
runs: 200
}
}
}
};<file_sep># [Qubit Finance](https://qbt.fi)
dapp: https://qbt.fi
### Project Overview
Docs: https://qubit-finance.gitbook.io/qubit-finance/
<br />
## BSC Mainnet Contracts
- ProxyAdmin: [0x40151e5d012E7de6000F7144288ef50af78882be](https://bscscan.com/address/0x40151e5d012E7de6000F7144288ef50af78882be)
- QubitToken: [<KEY>](https://bscscan.com/address/0x17B7163cf1Dbd286E262ddc68b553D899B93f526)
- Qore: [0xF70314eb9c7Fe7D88E6af5aa7F898b3A162dcd48](https://bscscan.com/address/0xF70314eb9c7Fe7D88E6af5aa7F898b3A162dcd48)
- QValidator: [0x0cD79409eD80d8a153A3c729aa1f8b5D44A29282](https://bscscan.com/address/0x0cD79409eD80d8a153A3c729aa1f8b5D44A29282)
- QubitLocker: [0xB8243be1D145a528687479723B394485cE3cE773](https://bscscan.com/address/0xB8243be1D145a528687479723B394485cE3cE773)
- QDistributor: [0x67B806ab830801348ce719E0705cC2f2718117a1](https://bscscan.com/address/0x67B806ab830801348ce719E0705cC2f2718117a1)
- DashboardBSC: [0x3BF0EbF0B846Fff73Df543bACacC542A6CE9fc15](https://bscscan.com/address/0x3BF0EbF0B846Fff73Df543bACacC542A6CE9fc15)
- QubitReservoir: [0xa7bc9a205A46017F47949F5Ee453cEBFcf42121b](https://bscscan.com/address/0xa7bc9a205A46017F47949F5Ee453cEBFcf42121b)
- QubitDevReservoir: [0xB224eD67C2F89Ae97758a9DB12163A6f30830EB2](https://bscscan.com/address/0xB224eD67C2F89Ae97758a9DB12163A6f30830EB2)
#### Qubit Markets
| asset | Contract Address |
|------|--------------|
| BNB | [0xbE1B5D17777565D67A5D2793f879aBF59Ae5D351](https://bscscan.com/address/0xbE1B5D17777565D67A5D2793f879aBF59Ae5D351)|
| BTCB | [0xd055D32E50C57B413F7c2a4A052faF6933eA7927](https://bscscan.com/address/0xd055D32E50C57B413F7c2a4A052faF6933eA7927)|
| ETH | [0xb4b77834C73E9f66de57e6584796b034D41Ce39A](https://bscscan.com/address/0xb4b77834C73E9f66de57e6584796b034D41Ce39A)|
| USDT | [0x99309d2e7265528dC7C3067004cC4A90d37b7CC3](https://bscscan.com/address/0x99309d2e7265528dC7C3067004cC4A90d37b7CC3)|
| BUSD | [0xa3A155E76175920A40d2c8c765cbCB1148aeB9D1](https://bscscan.com/address/0xa3A155E76175920A40d2c8c765cbCB1148aeB9D1)|
| USDC | [0x1dd6E079CF9a82c91DaF3D8497B27430259d32C2](https://bscscan.com/address/0x1dd6E079CF9a82c91DaF3D8497B27430259d32C2)|
| DAI | [0x474010701715658fC8004f51860c90eEF4584D2B](https://bscscan.com/address/0x474010701715658fC8004f51860c90eEF4584D2B)|
| CAKE | [0xaB9eb4AE93B705b0A74d3419921bBec97F51b264](https://bscscan.com/address/0xaB9eb4AE93B705b0A74d3419921bBec97F51b264)|
| QBT | [0xc<KEY>](https://bscscan.com/address/0xcD2CD343CFbe284220677C78A08B1648bFa39865)|
<br />
## BSC Testnet Contracts
- ProxyAdmin: [0x40151e5d012E7de6000F7144288ef50af78882be](https://testnet.bscscan.com/address/0x40151e5d012E7de6000F7144288ef50af78882be)
- QubitToken: [0xF523e4478d909968090a232eB380E2dd6f802518](https://testnet.bscscan.com/address/0xF523e4478d909968090a232eB380E2dd6f802518)
- Qore: [0xb3f98A31A02d133f65da961086EcDa4133bdf48e](https://testnet.bscscan.com/address/0xb3f98A31A02d133f65da961086EcDa4133bdf48e)
- QValidator: [0xf512C21E691297361df143920d4eC2A98b17cC07](https://testnet.bscscan.com/address/0xf512C21E691297361df143920d4eC2A98b17cC07)
- QubitLocker: [0xeA34f39DF510eAFFb789d575c9aa800d61476256](https://testnet.bscscan.com/address/0xeA34f39DF510eAFFb789d575c9aa800d61476256)
- QDistributor: [0xA2897BEDE359e56F67D06F42C39869719E59bEcc](https://testnet.bscscan.com/address/0xA2897BEDE359e56F67D06F42C39869719E59bEcc)
- DashboardBSC: [0x5bA1B272D60f46371279aE7a1C13227Fb93F99c1](https://testnet.bscscan.com/address/0x5bA1B272D60f46371279aE7a1C13227Fb93F99c1)
- QubitReservoir: [0x21824518e7E443812586c96aB5B05E9F91831E06](https://testnet.bscscan.com/address/0x21824518e7E443812586c96aB5B05E9F91831E06)
- QubitDevReservoir: [0x0cD79409eD80d8a153A3c729aa1f8b5D44A29282](https://testnet.bscscan.com/address/0x0cD79409eD80d8a153A3c729aa1f8b5D44A29282)
#### Qubit Markets
| asset | Contract Address |
|------|--------------|
| BNB | [0x80D1486eF600cc56d4df9ed33bAF53C60D5A629b](https://testnet.bscscan.com/address/0x80D1486eF600cc56d4df9ed33bAF53C60D5A629b)|
| ETH | [0x9E980e2c702268E6b97400Da1aB1Ee6ccc238f52](https://testnet.bscscan.com/address/0x9E980e2c702268E6b97400Da1aB1Ee6ccc238f52)|
| USDT | [0xB8243be1D145a528687479723B394485cE3cE773](https://testnet.bscscan.com/address/0xB8243be1D145a528687479723B394485cE3cE773)|
| BUSD | [0x38e2Ab4caDd92b87739aA5A71847e0B70bD4e631](https://testnet.bscscan.com/address/0x38e2Ab4caDd92b87739aA5A71847e0B70bD4e631)|
| DAI | [0x1771Fe35B71bbF5Ff7328ef5836e896850709F24](https://testnet.bscscan.com/address/0x1771Fe35B71bbF5Ff7328ef5836e896850709F24)|
| QBT | [0x67B806ab830801348ce719E0705cC2f2718117a1](https://testnet.bscscan.com/address/0x67B806ab830801348ce719E0705cC2f2718117a1)|
<br />
# Contact Us
- Twitter: [@QubitFin](https://twitter.com/QubitFin)
- Discord: [https://discord.gg/JGJBWRxX2Y](https://discord.gg/JGJBWRxX2Y)
- Telegram: [https://t.me/QubitFinOfficial](https://t.me/QubitFinOfficial)
- Email: [<EMAIL>](mailto:<EMAIL>)
|
15fe72f7699a3ee43fe424355ff304aa317bc392
|
[
"Markdown",
"TypeScript"
] | 2
|
TypeScript
|
codixor/qubit-finance
|
60a0fd8928fc74ef0b7f643693b7ef00ccac8266
|
c1753fc4c1237659e7f3c73239d261a26568d170
|
refs/heads/master
|
<repo_name>lafada/stack_poc<file_sep>/api/controllers/user_controller.js
var jsonfile = require('jsonfile');
var path = require('path');
var user_json = path.dirname(__dirname) + '/data/user.json';
module.exports.create = function (req, res) {
jsonfile.readFile(user_json, function(err, obj) {
var user_data = obj || [];
user_data.push(req.body);
jsonfile.writeFile(user_json, user_data, {spaces: 2}, function(err) {
if (err) {
console.error(err);
}
})
});
res.json(req.body);
};
module.exports.list = function (req, res) {
jsonfile.readFile(user_json, function(err, obj) {
res.json(obj || []);
});
};
<file_sep>/app/scripts/controllers/user_controller.js
app.controller('userController', ['$scope', '$resource',
function($scope, $resource){
var user_resource = $resource('/api/user');
$scope.users = [];
user_resource.query(function (response) {
$scope.users = response;
});
$scope.userCreate = function() {
var user = new user_resource();
user.name = $scope.userName;
user.$save(function(response) {
$scope.users.push(response);
});
$scope.userName = "";
};
}]);
|
984bdc8f404f0e85a02f0c76fa105097c427c268
|
[
"JavaScript"
] | 2
|
JavaScript
|
lafada/stack_poc
|
1825b40db153b02d7c81b92b78939265887dd4a0
|
d623729e463e52e4342cb69165a5d1e13087e2d6
|
refs/heads/main
|
<repo_name>TheJuiceFR/PLBMP<file_sep>/plbmp.lua
local bmp={}
local bmpmt={__index=bmp}
bmp.size={0,0}
bmp.data={}
--[[a sample of a data table:
{
{{1,1,1},{1,0.5,0},{1,.5,1}},
{{1,.7,1},{0,.9,1},{.8,.3,.2}},
{{1,1,1},{.3,.7,1},{0,0,0}}
}
]]
local function offset(file,off)
file:seek("set",off)
end
local function getByte(file,off)
offset(file,off)
return file:read(1):byte()
end
local function getWord(file,off)
offset(file,off)
local b1=file:read(1)
local b2=file:read(1)
return b1:byte()+b2:byte()*256
end
local function unmask() --now that we're outside of the building and we're 6ft apart
end
local function getDWord(file,off)
offset(file,off)
local b1=file:read(1)
local b2=file:read(1)
local b3=file:read(1)
local b4=file:read(1)
return b1:byte()+b2:byte()*256+b3:byte()*65536+b4:byte()*16777216
end
function bmp:getColor(x,y)
if type(x)=="table" then
y=x[2]
x=x[1]
end
assert(x<self.size[1] and y<self.size[2],"Coordinates out of bounds")
return self.data[x][y]
end
function bmp.open(filename)
local file=assert(io.open(filename,'rb'))
assert(getWord(file,0)==0x4D42,tostring(filename)..": not a bitmap file")
local bpp=getWord(file,0x1C)
local start=getDWord(file,0x0A)
local width=getDWord(file,0x12)
local height=getDWord(file,0x16)
local comp=getDWord(file,0x1E)
local padbytes=((getDWord(file,0x02)-start)-(width*height*(bpp/8)))/height
local res={}
setmetatable(res,bmpmt)
res.size={width,height}
res.data={}
for x=0,width-1 do
res.data[x]={}
end
local cursor=start
if comp==0 then
for y=height-1,0,-1 do
for x=0,width-1 do
res.data[x][y]={getByte(file,cursor)/255,getByte(file,cursor+1)/255,getByte(file,cursor+2)/255}
cursor=cursor+3
end
cursor=cursor+padbytes
end
--[[elseif comp==3 then
--The bitmasks for each color component.
redBM=getDWord(file,0x36) --Schedule a doctor's appointment asap
greenBM=getDWord(file,0x3A) --Eat less vegetables
blueBM=getDWord(file,0x3E) --Go to the ER
alphaBM=getDWord(file,0x42) --Be proud of yourself
]]
else
error("compression type "..tostring(comp).." not supported.")
end
return res
end
return bmp
<file_sep>/README.md
# PLBMP
Pure Lua Bitmap manipulation
Using a binding can be confusing and/or annoying.
To me, simply making a bitmap library is simpler. :)
|
18f3a73511b46840731dca4c8a30d8ef82dcd23d
|
[
"Markdown",
"Lua"
] | 2
|
Lua
|
TheJuiceFR/PLBMP
|
8208cd2db655501e18df988526a66e6e552787c7
|
d1493975ec20fa927eb2963d581ade916104d23e
|
refs/heads/master
|
<repo_name>Smalley2001/Measles-Vaccination-Project<file_sep>/proj05.py
#############################################################################
# Project #5
#
#Create a function that will open a file given by the user
# Use exception handling to check if the user's file actually exists
# Print an error message if the file doesn't exist
# Re-prompt if the user entered an invalid file.
# return the user's file
#Create a function to read the file and return the overall United States
# MMR coverage.
#Create a function to get the minimum state coverage in the United States
# Create a variable that will store the minimum value.
# Read each file line and create variables to store state and percentage
# Use conditional statements to ignore NA values.
# Use conditional statement to compare the percentage to the minimum value.
# return the minimum percentage and the corresponding state
#Create a function to get the maximum state coverage in the United States
# Create a variable that will store the maximum value.
# Read each file line and create variables to store state and percentage.
# Use conditional statements to ignore NA values.
# Use conditional statement to compare the percentage to the maximum value.
# return the maximum percentage and the corresponding state
#Create a function to check if a state's coverage is less than 90%.
# Create a variable that stores 90 and read the file lines.
# Check if state's percentages are less than 90%
# Use conditional statements to ignore the NA value in the file.
# If they are less than 90%, print the state and percentage coverage.
#Create a function to write the states with coverage less than 90%
#in a new text file
# Print the those lines in the new text files.
#Create a function to call all the previous functions.
# print the header. the overall coverage, and the min and max coverage
#############################################################################
def open_file():
'''
This function will not take any arguments.
In a while loop, prompt the user to enter a file name. Use exception
handling to determine if the file can be opened. If it can,
return the file. If it can't, print error message and re-prompt the
user.
'''
while True:
prompt= input("Input a file name: ") #prompt user
try:
file= open(prompt) #check for file
return file
except FileNotFoundError: #if file doesn't exist
print("Error: file not found. Please try again.") #error message
def get_us_value(fp):
'''
This function will take a file as an argument. The function will read
the file from the beginning and will do nothing until it reaches the end
of the file. Return the United States MMR coverage as a float.
'''
fp.seek(0) #start reading file at beginning
fp.readline() #read line
fp.readline() #read next line
for line in fp: #while reading the lines, do nothing
pass
return float(line[25:].strip()) #return the MMR coverage
def get_min_value_and_state(fp):
'''
This function takes a file as an argument. It has a variable that will
set the minimum value equal to a large number. The function also has
a variable that will store an empty string. The function will read
each line in the file and ignore any line that has NA for the MMR coverage
Store the state value in a variable and the percentage in a variable.
Create a conditional statement to check if the minimum value number is
greater than the percentage, if it is, the new minimum value is the
percentage. return the minimum value and the connected state.
'''
minimum_value= 77456337638 #assigned min value
min_state= "" # empty string used to store the minimum state
fp.seek(0) #read first line
fp.readline() #read line
fp.readline() #read next line
for line in fp: #check for NA and continue to next line
if "NA" in line:
continue
state= line[0:25].strip()
percentage= float(line[25:].strip())
if minimum_value>percentage: # check if minimum is greater than percent
minimum_value=percentage #new assignment
min_state= state #new assignment
return min_state,minimum_value
def get_max_value_and_state(fp):
'''This function takes a file as an argument. It has a variable that will
set the max value equal to a small number. The function also has
a variable that will store an empty string. The function will read
each line in the file and ignore any line that has NA for the MMR coverage
Store the state value in a variable and the percentage in a variable.
Create a conditional statement to check if the max value number is
less than the percentage, if it is, the new max value is the
percentage. return the max value and the connected state.'''
max_value= 0 #assigned a max value
max_state= "" #empty string to be used to store state
fp.seek(0) #read first line
fp.readline() #read line
fp.readline() #read next line
for line in fp: #continues iteration for lines with NA
if "NA" in line:
continue
state= line[0:25].strip()
percentage= float(line[25:].strip())
if max_value<percentage: # check if max is less than percentage
max_value=percentage #new assignment
max_state= state #new assignment
return max_state,max_value
def display_herd_immunity(fp):
'''This function takes a file as an argument. Create a variable
to be equal to 90. Read each line file, ignore files with NA. The
function checks if percentage is less than 90, if so print the state
and percentage.'''
print("\nStates with insufficient Measles herd immunity.")
print("{:<25s}{:>5s}".format("State","Percent"))
ninety_percent= 90 #set equal to 90 for comparison
fp.seek(0) #read first line
fp.readline() #read line
fp.readline() #read next line
for line in fp: #continue past lines with NA
if "NA" in line:
continue
state= line[0:25].strip()
percentage= float(line[25:].strip())
if percentage<ninety_percent: #condition if percent is less than 90
print("{:<25s}{:>5.1f}%".format(state,percentage)) #print results
def write_herd_immunity(fp):
'''This function takes a file as an argument. This has the same exact
procedures as display_herd_immunity but this function will write
the results to a new text file. '''
herd= open("herd.txt","w") #create new text flle
#In each print statement, set the current file equal to the outfile
print("\nStates with insufficient Measles herd immunity.", file=herd)
print("{:<25s}{:>5s}".format("State","Percent"), file=herd)
ninety_percent= 90
fp.seek(0)
fp.readline()
fp.readline()
for line in fp:
if "NA" in line:
continue
state= line[0:25].strip()
percentage= float(line[25:].strip())
if percentage<ninety_percent:
#Writes state and percentage in herd file.
print("{:<25s}{:>5.1f}%".format(state,percentage), file=herd)
def main():
'''This function does not take any arguments. This function will call
the previous function to display the overal MMR report. '''
fp = open_file() #calls open_file() to get a file
header = fp.readline() #reads the header line of the file
print(header) #print the header
value=get_us_value(fp) #calls get_us_value() to get overall coverage
#Calls get_min_value_and_state() to get the minimum values and states
min_state,min_value = get_min_value_and_state(fp)
#Calls get_max_value_and_state() to get the max values and states
max_state,max_value= get_max_value_and_state(fp)
#print results
print("Overall US MMR coverage: {}%".format(value))
print("State with minimal MMR coverage: {} {}%".format(min_state,min_value))
print("State with maximum MMR coverage: {} {}%".format(max_state,max_value))
#calls display_herd_immunity() to get states with percent less than 90
display_herd_immunity(fp)
#calls write_herd_immunity() to write the info from display_herd_immunity
#into herd.txt
write_herd_immunity(fp)
#Call the function
if __name__ == "__main__":
main()
|
f9994ec70f76a2d748c9f27f50e31025fcb7aa7f
|
[
"Python"
] | 1
|
Python
|
Smalley2001/Measles-Vaccination-Project
|
27c7f9315ae25d89c5d1f1b6a59866ab9fafb41e
|
fe3a23b3a7664df359b546f73c917ef196ba9698
|
refs/heads/master
|
<repo_name>QuiD-0/Study<file_sep>/C/namespace.cpp
#include<iostream>
namespace cinNcoutSpace{
int scanf;
const char *printf;
};
int main() {
cinNcoutSpace::scanf = 123;
cinNcoutSpace::printf = "hello";
printf("%i\n", cinNcoutSpace::scanf);
printf("%s\n", cinNcoutSpace::printf);
getchar();
}<file_sep>/C/369별.c
#include<stdio.h>
int main()
{
int n, m, t, o, i;
printf("0~999 사이의 숫자중 3,6,9가 들어가면 *이 출력되는 프로그램입니다.\n");
printf("0~999 사이의 숫자를 입력해주세요\n");
scanf_s("%d", &n);
if (n < 1 || n>999)
printf("범위를 벗어난 수입니다.다시 입력해주세요\n");
else
{
for (i = 1; i <= n; i++)
{
m = i / 100;
t = i / 10;
o = i % 10;
printf("%d",i);
if (m!=0&&m%3==0)
printf("*");
if (t != 0 && t % 3 == 0)
printf("*");
if (o != 0 && o % 3 == 0)
printf("*");
printf("\n");
}
}
return 0;
}<file_sep>/C/1로만들기 1463.c
#include<stdio.h>
int main() {
int n, i;
int dp[1000001] = {0};
scanf_s("%d", &n);
dp[0] = dp[1] = 0;
for (i = 2; i <= n; i++) {
dp[i] = dp[i - 1] + 1;
if (i % 2 == 0 && dp[i - 1] + 1 > dp[i / 2] + 1)
dp[i] = dp[i / 2] + 1;
if (i % 3 == 0 && dp[i - 1] + 1 > dp[i / 3] + 1)
dp[i] = dp[i / 3] + 1;
}
printf("%d", dp[n]);
}<file_sep>/C/R2_3046.c
#include<stdio.h>
int main(){
int r1,s;
scanf("%d %d",&r1,&s);
printf("%d",(s-r1)+s);
}<file_sep>/C/방인원구하기.c
#include<stdio.h>
//n층 n호 사람수는 n-1층1~n호까지의 합
int main() {
int array[100][100];
int col, row, r, c, h;
for (scanf("%d", &r); r--;) {
scanf("%d", &c);
scanf("%d", &h);
for (col = 0; col < 15; col++) {
for (row = 0; row < 15; row++) {
if (col == 0) {
array[0][row] = row + 1;
}
else if(row==0){
array[col][0] = 1;
}
else {
array[col][row] = array[col - 1][row] + array[col][row - 1];
}
}
}
printf("%d\n", array[c][h-1]);
}
return(0);
}<file_sep>/node/number.js
console.log(2+2);
console.log('1'+'1');
sad='Lorem \nipsum';
console.log(sad);
letter = `qwerqwer ${sad} asd sds`;
console.log(letter);
<file_sep>/node/file.js
var fs = require('fs');
fs.readFile('sample.txt','utf8',function(err,data){
console.log(data);
}); //비동기
var testFolder = './data';
fs.readdir(testFolder, function(error, filelist){
console.log(filelist);
});
console.log(__filename);
console.log(__dirname);
var result = fs.readFileSync('sample.txt', 'utf8'); //동기
console.log(result);<file_sep>/C/홀짝판별기.c
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
void main() {
int array[2][5];
int i,j,total=0;
for (j = 0; j < 2; j++) {
for (i = 0; i < 5; i++) {
scanf("%d", &array[j][i]);
}
}
printf("even : ");
for (j = 0; j < 2; j++) {
for (i = 0; i < 5; i++) {
if (array[j][i] % 2 == 0)
printf("%d, ", array[j][i]);
}
}
printf("\nodd : ");
for (j = 0; j < 2; j++) {
for (i = 0; i < 5; i++) {
if (array[j][i] % 2 == 1)
printf("%d, ", array[j][i]);
}
}
scanf("%d", &i);
}<file_sep>/C/e값.cpp
#include<stdio.h>
#include<math.h>
int main(void)
{
int i = 1; // i선언및 초기화
long double base;//base선언
printf("x\t (1+1/x)^x\n"); //출력
for (i = 583500; i < 584000; i = i + 20)//i가 584000이 될 때까지 i+20을 해주고 FOR문안의 내용반복
{
base = 1 + (double)1 / (double)i;// base=(1+1/i)
printf("%d\t %f\n", i, pow(base, (double)i));//i, base^i 출력
}
return 0;
}<file_sep>/python/네이버 영화 순위 파일로 저장.py
import os
import datetime
from bs4 import BeautifulSoup
import urllib.request
url = 'https://movie.naver.com/movie/sdb/rank/rmovie.nhn'
with urllib.request.urlopen(url) as fs :
soup = BeautifulSoup(fs.read().decode(fs.headers.get_content_charset()), 'html.parser')
items = soup.find_all('div', {'class' : 'tit3'})
local = datetime.datetime.now()
date= str(local.year)+'_'+str(local.month)+'_'+str(local.day)
desktopPath = os.path.expanduser('~')
filePath = desktopPath + '\desktop\영화순위'+str(date)+'.txt'
with open( filePath, 'w+') as file:
for i in range(20) :
file.write(str(i + 1) + '위\t ' + items[i].get_text(strip = True)+'\n')
<file_sep>/Web/php+mysql/insert_process.php
<?php
include('connect.php');
$filtered=array(
'title'=>mysqli_real_escape_string($conn, $_POST['title']),
'description'=>mysqli_real_escape_string($conn, $_POST['description'])
);
$sql = "
INSERT INTO topic
(title, description, created)
VALUES(
'{$filtered['title']}',
'{$filtered['description']}',
NOW()
)
";
mysqli_query($conn, $sql);
<file_sep>/C/while 1부터 100까지합.c
#include<stdio.h>
#pragma warning (push,2)
int main() {
int inital, total, i;
total = 0;
i = 100;
inital = 1;
while (inital <=i)
{
total +=inital ;
inital++;
}
printf("%d\n", total);
scanf_s("%d", &i);
}<file_sep>/C/함수.c
#include<stdio.h>
void hello() {
printf("hello\n");
return;
}
int total(int n) {
int i;
int t = 0;
for (i = 0; i <= n; i++) {
t += i;
}
return(t);
}
void main() {
int x;
hello();
scanf("%d",&x);
printf("\n%d\n", total(x));
scanf("%d", &x);
}<file_sep>/C/링크드리스트.cpp
#include "stdio.h"
#include "malloc.h"
#include "string.h"
struct nodeType
{
char* name;
nodeType* link;
};
void main()
{
void linkedListFunction();
linkedListFunction();
getchar();
printf("\n\n Type any character <Enter> : ");
getchar();
}
void linkedListFunction()
{
nodeType* newNode;
nodeType* head;
nodeType* current;
nodeType* previousNode;
head = NULL;
char* name;
int choice;
printf("\n insert=1, delete=2, search=3, traverse=4, quit=9 : ");
scanf("%i", &choice);
while (choice != 9)
{
switch (choice)
{
case 1:
printf(" Type insert name : ");
name = (char*)malloc(20);
scanf("%s", name);
newNode = (nodeType*)malloc(sizeof(nodeType));
newNode->name = name;
newNode->link = NULL;
if (head == NULL)
{
head = newNode;
}
else
{
current = head;
while (current != NULL)
{
previousNode = current;
current = current->link;
};
previousNode->link = newNode;
}
break;
case 2:
printf(" Type remove name : ");
name = (char*)malloc(20);
scanf("%s", name);
current = head;
if (current != NULL)
{
if (!strcmp(head->name, name))
{
head = current->link;
}
else
{
while (current != NULL)
{
if (strcmp(current->name, name))
{
previousNode = current;
current = current->link;
}
else
{
previousNode->link = current->link;
break;
}
}
}
}
if (current == NULL)
printf("\n Have no node \n");
else
printf("\n delete name : %s\n", current->name);
break;
case 3:
printf(" Type search name : ");
name = (char*)malloc(20);
scanf("%s", name);
current = head;
while (current != NULL)
{
if (strcmp(current->name, name))
current = current->link;
else break;
}
if (current == NULL)
{
printf("\n Have no node \n");
}
else
{
printf("\n search name : %s\n", current->name);
}
break;
case 4:
if (head == NULL)
{
printf("\n Have no node \n");
}
else
{
current = head;
while (current != NULL)
{
printf("\n %s %p, %p", current->name, current,current->link);
current = current->link;
}
printf("\n");
}
break;
default: printf("\n Type Error \n");
}
printf("\n insert=1, delete=2, search=3, traverse=4, quit=9 : ");
scanf("%i", &choice);
}
}
<file_sep>/C/다리놓기 1010.c
#include <stdio.h>
#include <string.h>
int d[31][31];
int C(int n, int r) {
if (n == r || r == 0) return 1;
if (d[n][r] >= 0) return d[n][r];
return d[n][r] = C(n - 1, r) + C(n - 1, r - 1);
}
int main() {
memset(d, -1, sizeof(d));
int t;
scanf("%d", &t);
while (t--) { //for(scanf("%d",t);t--;)을 사용하면 위 2줄을 한줄로가능
int n, m;
scanf("%d %d", &n, &m);
printf("%d\n", C(m, n));
}
/* 아래는 오버플로우발생 ㅠ.ㅠ
#include<stdio.h>
int main() {
int i, t, n, m, j;
int b = 1;
unsigned long long k = 1;
unsigned long long l = 1;
for (scanf("%d", &t); t--;) {
scanf("%d %d", &n, &m);
if (m - n < n)
n = m - n;
for (i = 1; i < n+1; i++) {
k *= m;
l *=b;
b++;
m--;
}
j = k / l;
printf("%d", j);
b = 1;
k = 1;
l = 1;
}
}
*/<file_sep>/C/함수,합구하기.c
#include<stdio.h>
int sum(int a,int b,int c) {
int total = 0;
for (a; a <= b; a+= c) {
total += a;
}
return total;
}
int main() {
int num1, num2, in;
scanf("%d %d %d", &num1, &num2, &in);
printf("%d", sum(num1, num2, in));
scanf("%d", &num1);
}<file_sep>/C/숫자 비교.c
#include<stdio.h>
int main() {
int num1, num2, ans;
printf("type two numer! : ");
scanf_s("%d %d", &num1, &num2);
while (1)
{
printf("\n%d + %d는 무엇일까요?\n", num1, num2);
scanf_s("%d", &ans);
if (ans == (num1 + num2)) {
printf("정답입니다.!\n");
break;
}
else {
printf("오답입니다. 다시 해보세요!\n");
}
}
scanf_s("%d", &num1);
}<file_sep>/C/OX맞추기.c
#include<stdio.h>
#include<string.h>
int main() {
char array[80];
int i, count = 0, index = 1, num, j;
scanf("%d", &num);
for (j = 0; j < num; j++) {
scanf("%s", &array);
count = 0;
index = 1;
for (i = 0;array[i]!='\0'; i++) {
if (array[i] == 'O') {
count += index;
index++;
}
else {
index = 1;
}
}
printf("%d\n", count);
}
return(0);
}
<file_sep>/java/shop/PayType.java
package shop;
public enum PayType {CASH,CARD}
<file_sep>/Web/php+mysql/update_process.php
<?php
include('connect.php');
$filtered=array(
'id'=>mysqli_real_escape_string($conn, $_POST['id']),
'title'=>mysqli_real_escape_string($conn, $_POST['title']),
'description'=>mysqli_real_escape_string($conn, $_POST['description'])
);
$sql="
UPDATE topic SET title = '{$filtered['title']}',description = '{$filtered['description']}' WHERE id = '{$filtered['id']}'";
mysqli_query($conn, $sql);
<file_sep>/C/포인터.cpp
#include<stdio.h>
int main() {
int i;
int *p;
p = &i;
i = 1;
printf("p=%x\n",p);
printf("&p=%x\n", &p);
printf("i=%x\n", i);
printf("&i=%x\n", &i);
*p = 10;
printf("p=%x\n", p);
printf("&p=%x\n", &p);
printf("i=%x\n", i);
printf("&i=%x\n", &i);
scanf_s("%d", &i);
}<file_sep>/C/for n씩증가시킨값의 합.c
#include<stdio.h>
#pragma warning(push,2)
void main() {
int num1, max, step, total, inital;
printf("초기값 최댓값 증가치를 순서대로 입력하세요.");
scanf_s("%d %d %d", &num1, &max, &step);
inital = num1;
if (max < num1) printf("최대값은 초기값보다 작아야 합니다.");
else if (step == 0)printf("증가치는 0이 아니여야 합니다.");
else {
for (total = 0; num1 <= max; num1 += step) {
total += num1;
}
printf("\n%d부터 %d까지 %d씩 증가하는 값들의 합은 %d입니다.\n", inital, max, step, total);
}
scanf_s("%d", &num1);
}<file_sep>/C/함수 영어문자비교.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *eng[] = { "zero","one","two","three","four","five","six","seven","eight","nine","ten" };
int calc(int a,char *b) {
int count = 0;
while (count<3) {
if (strcmp(eng[a],b)==0) {
return count;
}
else {
count++;
printf("\n%d는 영어로 무엇입니까? : ", a);
scanf("%s", b);
}
}
return count;
}
int main() {
int num1, num2, i;
char *string = (char *)malloc(1);
int array[4] = { 0 };
while (1)
{
printf("=========================================\n");
printf("Type two integers<Quit : 10이상> : ");
scanf("%d", &num1);
if (num1 > 10)break;
printf("\n%d는 영어로 무엇입니까? : ", num1);
scanf("%s", string);
switch (calc(num1,string)) {
case(0):printf("\nexcellent\n"); array[0]++; break;
case(1):printf("\nvery good\n"); array[1]++; break;
case(2):printf("\ngood\n"); array[2]++; break;
default:printf("\nbad : %s\n",eng[num1]); array[3]++;
}
}
for (i = 0; i < 3; i++) {
printf("%d번째 맞힌 개수 : %d\n", i + 1, array[i]);
}
printf("못맞힌 개수 : %d\n", array[3]);
}<file_sep>/C/함수,더하기맞추기.c
#include<stdio.h>
int calc(int a, int b, int c) {
int count = 0;
while (count<3) {
if (c == a + b) {
return count;
}
else {
count++;
printf("%d + %d : ",a, b);
scanf("%d", &c);
}
}
return count;
}
int main() {
int num1, num2, sum, i;
int array[4] = { 0 };
while (1)
{
printf("Type two integers<Quit : 0 0> : ");
scanf("%d %d", &num1, &num2);
if (num1 == 0 && num2 == 0)break;
printf("\n%d + %d : ", num1, num2);
scanf("%d", &sum);
switch (calc(num1, num2, sum)) {
case(0):printf("excellent\n"); array[0]++; break;
case(1):printf("very good\n"); array[1]++; break;
case(2):printf("good\n"); array[2]++; break;
default:printf("bad : %d\n", num1 + num2); array[3]++;
}
}
for (i = 0; i < 3; i++) {
printf("%d번째 맞힌 개수 : %d\n",i+1, array[i]);
}
printf("못맞힌 개수 : %d\n", array[3]);
}<file_sep>/C/테트리스 소스cpp.cpp
#include <cstdio>
#include <cstdlib>
#include <windows.h>
#include <time.h>
#include <conio.h>
#include <mmsystem.h> //사운드_관련_헤더
#pragma comment(lib,"winmm.lib") //사운드_관련(라이브러리_읽어들임) <-> 프로젝트 설정->'라이브러리 참조'로도 가능
#include <process.h>
//방향키
#define LEFT 75
#define RIGHT 77
#define UP 72
#define DOWN 80
#define SPACE 32
#define ESC 27
//맵_크기
#define map_x 17
#define map_y 20
#define map_x_move 2
#define map_y_move 3
#define map_save_num 6
//전역_변수
static int map_feild[map_y][map_x];
static int remove_map_feild[map_y][map_x];
bool game_runtime = TRUE;
int model_selcet_1 = 0, model_selcet_2 = 0, model_transform = 0, x = 0, y = 1;
bool model_select_ok = FALSE, convert_on = FALSE;
bool y_comdown = FALSE;
int key_input1 = 0, key_input2 = 0, key_input3 = 0, key_input4 = 0, model_control = 0;
int model_x_[map_save_num], model_y_[map_save_num];
int curtime = 0, count = 0;
bool player_interrupt = FALSE;
int CLOCK_PER_SEC = 1000;
//enum
typedef enum { NOCURSOR, SOLIDCURSOR, NORMALCURSOR } CURSOR_TYPE;
//함수_전방선언
void print_test_num(void);
void game_init();
void map_frame_draw(void);
void event_key_input(void);
void block_draw(void);
void block_delete(void);
void select_model(void);
void block_init(void);
void block_0(void);
void block_1(void);
void block_2(void);
void block_3(void);
void block_convert(void);
void block_line_delete(void);
void block_line_remove(int Clear_limit);
void block_down(void);
void block_3_redraw(void);
bool block_transform(int model_control_num);
bool block_crush_L(int model_control_num);
bool block_crush_R(int model_control_num);
bool block_crush_D(int model_control_num);
//---------------------------------------
void setcolor(int color, int bgcolor = 0);
void gotoxy(int x, int y);
void setcursortype(CURSOR_TYPE c);
//본문------------------------------------------
int main(void)
{
//초기화 및 맵을 그린다.
game_init();
map_frame_draw();
//게임이 실행 되는 중
while (game_runtime)
{
//시간제어
int time = double(clock()) / CLOCK_PER_SEC;
if (curtime<time && !player_interrupt)
{
curtime = time;
block_down();
}
event_key_input();
select_model();
block_delete();
//빈 공간을 한번 출력함으로써 부분적으로 삭제한다.
gotoxy(95, 8);
printf(" ", time);
gotoxy(95, 8);
printf("Time : %d\n", time);
//모델을 선택한다.
switch (model_selcet_1)
{
case 0:
block_0();
break;
case 1:
block_1();
break;
case 2:
block_2();
break;
case 3:
block_3();
break;
}
//선택한 모델을 그린다.
block_draw();
}
return 0;
}
//함수_선언(제작)------------------------------------------
//테스트를 위한 함수
void print_test_num(void)
{
gotoxy(55, 2);
printf("model_selcet_1 : %d", model_selcet_1);
gotoxy(55, 3);
printf("model_selcet_2 : %d", model_selcet_2);
int i = 0;
//지움
gotoxy(95, 2);
printf(" ");
gotoxy(95, 3);
printf(" ");
//그림
setcolor(2);
gotoxy(95, 2);
printf("순수: X= %d", x);
setcolor(2);
gotoxy(95, 3);
printf("순수: Y= %d", y);
//지움
for (i = 0; i<map_save_num; i++)
{
gotoxy(95, 4);
printf(" ");
gotoxy(95, 5);
printf(" ");
gotoxy(95, 6);
printf(" ");
gotoxy(95, 7);
printf(" ");
}
//그림
for (i = 0; i<map_save_num; i++)
{
setcolor(2);
gotoxy(95, 4);
printf("x=%d번 ", i);
gotoxy(95, 5);
printf("= %d", model_x_[i]);
gotoxy(95, 6);
printf("y=%d번 ", i);
gotoxy(95, 7);
printf("= %d", model_y_[i]);
}
}
//사용자 입력 함수
void event_key_input(void)
{
int evnet_key;
//kbhit()는 키가 눌렸는지 안눌렸는지 알려준다.
if (_kbhit())
{
print_test_num();
//getch()는 어떤 키가 눌렸는지 알려준다.
evnet_key = _getch();
switch (evnet_key)
{
case LEFT:
if (!block_crush_L(model_control))
{
x--;
}
break;
case RIGHT:
if (!block_crush_R(model_control))
{
x++;
}
break;
case UP:
if (!block_transform(model_control))
{
model_transform++;
}
break;
case DOWN:
player_interrupt = TRUE;
if (!y_comdown)
{
block_down();
}
break;
case SPACE:
player_interrupt = TRUE;
if (!y_comdown)
{
block_down();
}
break;
case ESC:
game_runtime = FALSE;
break;
}
}
else
{
player_interrupt = FALSE;
}
}
//블럭을 한칸 내린다.
void block_down(void)
{
//블럭을 변환하는 변환 값이 없으면
if (!convert_on)
{
//충돌체크를 하고, 이상이 없으면 y를 내린다.
if (!block_crush_D(model_control))
{
y_comdown = TRUE;
y++;
}
}
else
{
//충돌이 되었으면 삭제, 블럭 초기화.
block_line_delete();
block_init();
}
y_comdown = FALSE;
}
//블럭 라인삭제
void block_line_delete(void)
{
int i, j;
bool remove_on = FALSE;
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 3)
{
count++;
}
}
if (count == map_x - 2) //양쪽 벽 제외
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 3)
{
map_feild[j][i] = 0;
remove_on = TRUE;
}
}
if (remove_on)
{
block_line_remove(j);
remove_on = FALSE;
}
}
count = 0;
i = 0;
}
j = 0;
}
//삭제 된 위의 블럭 라인 이동
void block_line_remove(int Clear_limit)
{
int i, j;
//copy
for (j = 0; j<Clear_limit; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 3)
{
remove_map_feild[j][i] = map_feild[j][i];
}
}
i = 0;
}
//clear
for (j = 0; j<Clear_limit; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 3)
{
map_feild[j][i] = 0;
}
}
i = 0;
}
//paste
for (j = 0; j<Clear_limit; j++)
{
for (i = 0; i<map_x; i++)
{
if (remove_map_feild[j][i] == 3)
{
map_feild[j + 1][i] = remove_map_feild[j][i];
}
}
i = 0;
}
//clear
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
remove_map_feild[j][i] = 0;
}
i = 0;
}
}
//블럭 초기화
void block_init(void)
{
model_control = 0;
key_input1 = 0;
key_input2 = 0;
key_input3 = 0;
key_input4 = 0;
x = map_x / 2;
y = 1;
model_transform = 0;
model_select_ok = FALSE;
convert_on = FALSE;
block_draw();
block_3_redraw();
}
//블럭 왼쪽 충돌 체크
bool block_crush_L(int model_control_num)
{
int i;
for (i = 0; i <= model_control_num; i++)
{
if (map_feild[model_y_[i]][model_x_[i] - 1] == 1 || map_feild[model_y_[i]][model_x_[i] - 1] == 3)
{
return TRUE;
}
}
return FALSE;
}
//블럭 오른쪽 충돌 체크
bool block_crush_R(int model_control_num)
{
int i;
for (i = 0; i <= model_control_num; i++)
{
if (map_feild[model_y_[i]][model_x_[i] + 1] == 1 || map_feild[model_y_[i]][model_x_[i] + 1] == 3)
{
return TRUE;
}
}
return FALSE;
}
//블럭 아래 충돌 체크
bool block_crush_D(int model_control_num)
{
int i;
for (i = 0; i <= model_control_num; i++)
{
if (map_feild[model_y_[i] + 1][model_x_[i]] == 1 || map_feild[model_y_[i] + 1][model_x_[i]] == 3)
{
convert_on = TRUE;
block_convert();
return TRUE;
}
}
return FALSE;
}
//블럭을 변환한다 (이동 불가의 쌓인 블럭으로)
void block_convert(void)
{
int i, j;
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 2)
{
map_feild[j][i] = 3;
}
}
i = 0;
}
j = 0;
block_3_redraw();
}
//움직일 수 있는 블럭 =2 , 쌓인 블럭 =3
//3번 블럭, 즉 쌓인 블럭을 다시 그린다는 의미.
void block_3_redraw(void)
{
int i, j;
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 3)
{
gotoxy(i * 2 + map_x_move, j + map_y_move);
setcolor(14);
puts("■");
}
}
i = 0;
}
j = 0;
}
//2번 블럭을 삭제한다.
void block_delete(void)
{
int i, j;
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 2)
{
map_feild[j][i] = 0;
}
}
i = 0;
}
j = 0;
}
//0번 블럭 선택.
void block_0(void)
{
if (!convert_on)
{
if (model_transform>1)
{
model_transform = 0;
}
switch (model_transform)
{
case 0:
key_input1 = 0; //기본
key_input2 = 0; //기본
break;
case 1:
key_input1 = 1; //변형
key_input2 = -2; //변형
break;
}
map_feild[y + key_input1][x - 1] = 2;
map_feild[y][x] = 2;
map_feild[y + 1][x] = 2;
map_feild[y + 1 + key_input1][x + 1 + key_input2] = 2;
model_x_[0] = x - 1;
model_y_[0] = y + key_input1;
model_x_[1] = x;
model_y_[1] = y;
model_x_[2] = x;
model_y_[2] = y + 1;
model_x_[3] = x + 1 + key_input2;
model_y_[3] = y + 1 + key_input1;
model_control = 3;
}
}
void block_1(void)
{
if (!convert_on)
{
if (model_transform>1)
{
model_transform = 0;
}
switch (model_transform)
{
case 0:
key_input1 = 0; //기본
key_input2 = 0; //기본
key_input3 = 0; //기본
key_input4 = 0; //기본
break;
case 1:
key_input1 = -1; //변형
key_input2 = -2; //변형
key_input3 = 1; //변형
key_input4 = 2; //변형
break;
}
map_feild[y + key_input4][x - 2 + key_input4] = 2; //0,6
map_feild[y + key_input3][x - 1 + key_input3] = 2; //0,7
map_feild[y][x] = 2; //0,8
map_feild[y + key_input1][x + 1 + key_input1] = 2; //0,9
map_feild[y + key_input2][x + 2 + key_input2] = 2; //0,10
model_x_[0] = x - 2 + key_input4;
model_y_[0] = y + key_input4;
model_x_[1] = x - 1 + key_input3;
model_y_[1] = y + key_input3;
model_x_[2] = x;
model_y_[2] = y;
model_x_[3] = x + 1 + key_input1;
model_y_[3] = y + key_input1;
model_x_[4] = x + 2 + key_input2;
model_y_[4] = y + key_input2;
model_control = 4;
}
}
void block_2(void)
{
if (!convert_on)
{
map_feild[y][x] = 2; //0,8
map_feild[y][x + 1] = 2; //0,9
map_feild[y + 1][x] = 2; //1,8
map_feild[y + 1][x + 1] = 2; //1,9
model_x_[0] = x;
model_y_[0] = y + 1;
model_x_[1] = x + 1;
model_y_[1] = y + 1;
model_control = 1;
}
}
void block_3(void)
{
if (!convert_on)
{
if (model_transform>3)
{
model_transform = 0;
}
switch (model_transform)
{
case 0:
map_feild[y][x] = 2; //0,8
map_feild[y][x + 1] = 2; //0,9
map_feild[y + 1][x + 1] = 2; //1,9
map_feild[y + 2][x + 1] = 2; //2,9
model_x_[0] = x;
model_y_[0] = y;
model_x_[1] = x + 1;
model_y_[1] = y + 2;
model_control = 1;
break;
case 1:
map_feild[y + 1][x + 2] = 2; //1,10
map_feild[y + 2][x] = 2; //2,8
map_feild[y + 2][x + 1] = 2; //2,9
map_feild[y + 2][x + 2] = 2; //2,10
model_x_[0] = x;
model_y_[0] = y + 2;
model_x_[1] = x + 1;
model_y_[1] = y + 2;
model_x_[2] = x + 2;
model_y_[2] = y + 2;
model_control = 2;
break;
case 2:
map_feild[y][x + 1] = 2; //0,9
map_feild[y + 1][x + 1] = 2; //1,9
map_feild[y + 2][x + 1] = 2; //2,9
map_feild[y + 2][x + 2] = 2; //2,10
model_x_[0] = x + 1;
model_y_[0] = y + 2;
model_x_[1] = x + 2;
model_y_[1] = y + 2;
model_control = 1;
break;
case 3:
map_feild[y + 2][x] = 2; //2,8
map_feild[y + 2][x + 1] = 2; //2,9
map_feild[y + 2][x + 2] = 2; //2,10
map_feild[y + 3][x] = 2; //3,8
model_x_[0] = x + 1;
model_y_[0] = y + 2;
model_x_[1] = x + 2;
model_y_[1] = y + 2;
model_x_[2] = x;
model_y_[2] = y + 3;
model_control = 2;
break;
}
}
}
//블럭 모양 변경
bool block_transform(int model_control_num)
{
int i;
int _key_input1, _key_input2, _key_input3, _key_input4;
int _model_x_[6], _model_y_[6];
int _model_transform, _model_control;
_model_control = model_control_num;
_model_transform = model_transform;
_model_transform++;
//블록별로 지정이 필요함.
//해당 스위치문만 유동적
switch (model_selcet_1)
{
case 0:
if (_model_transform>1)
{
_model_transform = 0;
}
switch (_model_transform)
{
case 0:
_key_input1 = 0; //기본
_key_input2 = 0; //기본
break;
case 1:
_key_input1 = 1; //변형
_key_input2 = -2; //변형
break;
}
_model_x_[0] = x - 1;
_model_y_[0] = y + _key_input1;
_model_x_[1] = x;
_model_y_[1] = y;
_model_x_[2] = x;
_model_y_[2] = y + 1;
_model_x_[3] = x + 1 + _key_input2;
_model_y_[3] = y + 1 + _key_input1;
break;
case 1:
if (_model_transform>1)
{
_model_transform = 0;
}
switch (_model_transform)
{
case 0:
_key_input1 = 0; //기본
_key_input2 = 0; //기본
_key_input3 = 0; //기본
_key_input4 = 0; //기본
break;
case 1:
_key_input1 = -1; //변형
_key_input2 = -2; //변형
_key_input3 = 1; //변형
_key_input4 = 2; //변형
break;
}
_model_x_[0] = x - 2 + _key_input4;
_model_y_[0] = y + _key_input4;
_model_x_[1] = x - 1 + _key_input3;
_model_y_[1] = y + _key_input3;
_model_x_[2] = x;
_model_y_[2] = y;
_model_x_[3] = x + 1 + _key_input1;
_model_y_[3] = y + _key_input1;
_model_x_[4] = x + 2 + _key_input2;
_model_y_[4] = y + _key_input2;
break;
case 2:
_model_x_[0] = x;
_model_y_[0] = y + 1;
_model_x_[1] = x + 1;
_model_y_[1] = y + 1;
break;
case 3:
if (_model_transform>3)
{
_model_transform = 0;
}
switch (_model_transform)
{
case 0:
_model_x_[0] = x;
_model_y_[0] = y;
_model_x_[1] = x + 1;
_model_y_[1] = y + 2;
_model_control = 1;
break;
case 1:
_model_x_[0] = x;
_model_y_[0] = y + 2;
_model_x_[1] = x + 1;
_model_y_[1] = y + 2;
_model_x_[2] = x + 2;
_model_y_[2] = y + 2;
_model_control = 2;
break;
case 2:
_model_x_[0] = x + 1;
_model_y_[0] = y + 2;
_model_x_[1] = x + 2;
_model_y_[1] = y + 2;
_model_control = 1;
break;
case 3:
_model_x_[0] = x + 1;
_model_y_[0] = y + 2;
_model_x_[1] = x + 2;
_model_y_[1] = y + 2;
_model_x_[2] = x;
_model_y_[2] = y + 3;
_model_control = 2;
break;
}
break;
}
for (i = 0; i <= _model_control; i++)
{
if (map_feild[_model_y_[i]][_model_x_[i]] == 1 || map_feild[_model_y_[i]][_model_x_[i]] == 3)
{
return TRUE;
}
}
return FALSE;
}
//블럭을 그린다.
void block_draw(void)
{
int i, j;
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 0)
{
gotoxy(i * 2 + map_x_move, j + map_y_move);
setcolor(15);
puts(" ");
}
if (map_feild[j][i] == 2)
{
gotoxy(i * 2 + map_x_move, j + map_y_move);
setcolor(15);
puts("■");
}
}
i = 0;
}
j = 0;
}
//맵을 그린다.
void map_frame_draw(void)
{
int i, j;
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (map_feild[j][i] == 1)
{
gotoxy(i * 2 + map_x_move, j + map_y_move);
setcolor(8);
puts("▣");
}
else if (map_feild[j][i] == 0)
{
gotoxy(i * 2 + map_x_move, j + map_y_move);
puts(" ");
}
}
i = 0;
printf("\n");
}
j = 0;
}
//게임 전체 초기화
void game_init()
{
//system("mode con: cols=76 lines=24");
system("mode con: cols=148 lines=28");
setcursortype(NOCURSOR);
srand(time(NULL));
model_selcet_2 = rand() % 4;
int i, j;
for (i = 0; i<map_save_num; i++)
{
model_x_[i] = 0;
model_y_[i] = 0;
}
for (j = 0; j<map_y; j++)
{
for (i = 0; i<map_x; i++)
{
if (i == 0 || i == map_x - 1)
{
map_feild[j][i] = 1;
}
else if (j == 0 || j == map_y - 1)
{
map_feild[j][i] = 1;
}
}
i = 0;
}
print_test_num();
}
//모델 선택
void select_model(void)
{
if (!model_select_ok)
{
model_selcet_1 = model_selcet_2;
model_selcet_2 = rand() % 4;
block_init();
model_select_ok = TRUE;
}
}
//기본_필요_함수------------------------------------------------------------------
void setcolor(int color, int bgcolor) //글자색상
{
color &= 0xf;
bgcolor &= 0xf;
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), (bgcolor << 4) | color);
}
void gotoxy(int x, int y) //커서이동
{
COORD pos = { x, y };
SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);
}
void setcursortype(CURSOR_TYPE c) //커서제거(타입)
{
CONSOLE_CURSOR_INFO CurInfo;
switch (c) {
case NOCURSOR:
CurInfo.dwSize = 1;
CurInfo.bVisible = FALSE;
break;
case SOLIDCURSOR:
CurInfo.dwSize = 100;
CurInfo.bVisible = TRUE;
break;
case NORMALCURSOR:
CurInfo.dwSize = 20;
CurInfo.bVisible = TRUE;
break;
}
SetConsoleCursorInfo(GetStdHandle(STD_OUTPUT_HANDLE), &CurInfo);
}
<file_sep>/node/callBack.js
function a(){
console.log('a');
}
a();
var b = function(){
console.log('b')
}
b();
function slow (callback){
callback();
}
slow(a);
slow(b);<file_sep>/C/SW1206.c
#include<stdio.h>
int array[1000];
int count[10];
int big(int a, int b, int c, int d) {
int biga = (a > b) ? a : b;
int bigb = (c > d) ? c : d;
int res = (biga > bigb) ? biga : bigb;
return res;
}
int main() {
int wide = 0;
for (int t=0; t < 10;t++) {
scanf_s("%d", &wide);
for (int i = 0; i < wide; i++) {
scanf_s("%d", &array[i]);
}
for (int i = 2; i < wide - 2; i++) {
int bignum = big(array[i - 2], array[i - 1], array[i + 1], array[i + 2]);
if (array[i] > bignum) count[t] = count[t] + array[i] - bignum;
}
}
for (int t = 0; t < 10; t++) {
printf("#%d %d\n", t+1, count[t]);
}
return 0;
}<file_sep>/java/gui/CtoF.java
package gui;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
public class CtoF extends JFrame{
Label l1 = new Label("¼·¾¾ (¨¬C)");
Label l2 = new Label("Ⱦ¾ (¨¬F)");
TextField t1 = new TextField();
TextField t2 = new TextField();
JButton button1 = new JButton("¼·¾¾ -> Ⱦ¾");
JButton button2 = new JButton("Ⱦ¾ -> ¼·¾¾");
Panel p1= new Panel();
public void Grid() {
p1.setLayout(new GridLayout(3,2));
p1.add(l1);
p1.add(l2);
p1.add(t1);
p1.add(t2);
button1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double a = Double.parseDouble(t1.getText());
a=a*1.8+32;
String s=String.valueOf(a);
t2.setText(s);
}
});
button2.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
double a = Double.parseDouble(t2.getText());
a=(a-32)*5/9;
String s=String.valueOf(a);
t1.setText(s);
}
});
p1.add(button1);
p1.add(button2);
}
public CtoF() {
super("C to F // F to C");
getContentPane().add(p1);
Grid();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300,200);
setVisible(true);
}
public static void main(String[] args) {
CtoF app = new CtoF();
}
}
<file_sep>/C/구조체.c
#include<stdio.h>
struct MyStruct
{
char * first_name;
char * last_name;
};
struct MyStruct2
{
int telecom;
int countrynumber;
int number;
};
struct id
{
struct MyStruct name;
struct MyStruct2 phone;
struct email
{
char* mail;
};
};
void main() {
struct MyStruct na = { "lee", "jaeung" };
struct MyStruct2 na2 = { 010,1111,2222 };
struct id lee;
lee.name = na;
lee.phone = na2;
lee.mail = "wodnd@sdasd";
printf("%s %d %s", lee.name.first_name,lee.phone.number,lee.mail);
getchar();
}<file_sep>/C/아스키값출력.c
#include<stdio.h>
int main()
{
char ch;
printf("문자 입력\n");
scanf_s("%c", &ch);//ch에 문자형을 저장
printf("입력하신 %c의 ASCII값은 %d입니다", ch, ch); //ch를 각각 문자형 정수형으로 표현
return 0;
}<file_sep>/C/간단한 반복문식.c
#include <stdio.h>
int T;
int main()
{
for (scanf("%d", &T);T--;) {
printf("%d", T);
}
}<file_sep>/C/나무.cpp
#include <stdio.h>
#include <conio.h>
int main()
{
int h, w, i, j;
int leftc, rightc;
scanf_s("%d", &h); //피라미드 높이, 만약에 높이(층수)를 입력 받아서 하고 싶으면 scanf("%d", &h);해주시면 됩니다.
leftc = rightc = h - 1; //피라미드의 Center(루프가 0 부터 시작하니까 h - 1) 처음은 좌우가 같습니다.
w = 2 * h - 1; //피라미드의 폭
for (i = 0; i < h * w; i++) //높이와 폭을 곱하면 피라미드의 전체(공백까지 합한)갯수가 나옵니다.
{
j = i % w; //j는 폭을 나타냅니다. 한줄이 끝나면 줄은 0부터 다시 시작하니까
if (j >= leftc && j <= rightc) printf("*");//별이 처음에는 가운데 하나, 다음칸은 Center에서 좌우로 하나씩 증가 하니까
else printf(" "); //Center가 아닌 나머지에는 공백출력
if ((i + 1) % w == 0) //폭의 끝까지 가면
{
printf("\n"); //줄을 바꾸어주고
leftc--; //왼쪽 Center는 1감소
rightc++; //오른쪽 Center는 1증가
}
}
_getch();
return 0;
}<file_sep>/C/두 수의합 맞을때 까지 반복.c
#include<stdio.h>
#pragma warning (push,2)
int main() {
int num1, num2, count, i;
while (1) {
count = 1;
printf("=============================================");
printf("\n0 0 을입력하면 나가집니다. \n두수를 입력하세요 : \n");
scanf_s("%d %d", &num1, &num2);
if (num1 == 0 && num2 == 0)break;
while(1){
printf("\n%d + %d : =", num1, num2);
scanf_s("%d", &i);
if (i == num1 + num2) {
printf("정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("오답입니다. 다시 맞춰보세요 \n ");
count++;
}
}
}
printf("수고하셧습니다. 나가려면 아무키나 입력해주세요. \n");
scanf_s("%d", &i);
}<file_sep>/C/한수1065.c
#include<stdio.h>
int main()
{
int N, i, j;
int total_hansu = 0;
int temp;
int hund, thou,ten, one;
int dif1, dif2;
scanf_s("%d", &N);
for (i = 0; i <= N; i++)
{
if (i < 100 && i>0)
{
total_hansu++;
}
else if (i >= 100 && i < 1000)
{
hund = i / 100;
ten = i % 100 / 10;
one = i % 10;
dif1 = hund - ten;
dif2 = ten - one;
if (dif1 == dif2)
{
total_hansu++;
}
}
else if (i == 1000)
;
}
printf("%d", total_hansu);
}<file_sep>/C/분수합.cpp
#include <stdio.h>
typedef struct
{
int numerator;
int denominator;
} FRACTION;
int main(void)
{
FRACTION fr1;
FRACTION fr2;
FRACTION res;
printf("Key first fraction in the form of x/y: ");
scanf_s("%d /%d", &fr1.numerator, &fr1.denominator);
printf("Key second fraction in the form of x/y: ");
scanf_s("%d /%d", &fr2.numerator, &fr2.denominator);
if (fr1.denominator == fr2.denominator) {
res.numerator = fr1.numerator + fr2.numerator;
res.denominator = fr1.denominator ;
printf("\nThe result of %d/%d + %d/%d is %d/%d",
fr1.numerator, fr1.denominator,
fr2.numerator, fr2.denominator,
res.numerator, res.denominator);
}
else {
res.numerator = fr1.numerator * fr2.denominator + fr2.numerator* fr1.denominator;
res.denominator = fr1.denominator * fr2.denominator;
printf("\nThe result of %d/%d + %d/%d is %d/%d",
fr1.numerator, fr1.denominator,
fr2.numerator, fr2.denominator,
res.numerator, res.denominator);
}
return 0;
}<file_sep>/Web/php/xss.php
<?php
echo '<script>alert("알림");</script>';
<file_sep>/C/평균10039.c
#include<stdio.h>
int main() {
int i, sum=0;
int x[5] = { 0 };
for (i = 0; i<5; i++)
{
scanf("%d", &x[i]);
if (x[i] < 40)
x[i] = 40;
sum =sum+ x[i];
}
printf("%d", sum / 5);
}<file_sep>/C/사칙연산 소스.c
#include<stdio.h>
int main()
{
int a, b, y;
printf( " 두 숫자를 입력하세요 \n" );
scanf_s( "%d",&a );
scanf_s( "%d",&b );
printf("연산을 선택하세요");
printf("1= + \n 2= - \n 3= * \n 4= / \n");
scanf_s("%d" ,&y);
if (y == 1)
{
printf("%d + %d = %d", a, b, a + b);
}
if (y == 2)
{
printf("%d - %d = %d", a, b, a - b);
}
if (y == 3)
{
printf("%d * %d = %d", a, b, a * b);
}
if (y == 4)
{
printf("%d / %d = %d", a, b, a / b);
}
return 0;
}
<file_sep>/Web/php+mysql/connect.php
<?php
$conn=mysqli_connect("IP:PORT", "ID", "PASSWORD", "DATABASE NAME");
<file_sep>/C/팩토리얼.c
#include<stdio.h>
int factorial(int a)
{
int i;
int f = 1;
for (i = 1; i <= a; i++)
{
f = f*i;
if (i == 1)
printf("%d", i);
else
printf("*%d", i);
}
printf("=%d", f);
return f;
}
int main()
{
int n;
int a;
printf("N!을 구하는 프로그램이다. N=?.");
scanf_s("%d", &n);
if (n < 1||n>10)
printf("1~10 사이의 수를 입력하라.\n");
else
{
a = factorial(n);
printf("\n%d!는 %d이다.\n", n, a);
}
return 0;
}<file_sep>/C/simple sort.c
#include<stdio.h>
void main() {
int array[5];
int temp, i, count=0;
printf("\ntype 5 integer : ");
for (i = 0; i < 5; i++) {
scanf("%d", &array[i]);}
printf("\nbefore sort : ");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
while (count != 4) {
count = 0;
for (i = 0; i < 4; i++) {
if (array[i] > array[i + 1]) {
temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
}
else count++;
}
}
printf("\n\nafter sort : ");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
scanf("%d", &i);
}<file_sep>/Web/php+mysql/index.php
<!DOCTYPE html>
<html lang="en">
<head>
<?php
include 'print.php';
?>
<meta charset="utf-8">
<title>web</title>
</head>
<body>
<h1><a href="index.php">WEB</a></h1>
<ol>
<?php
print_list() ?>
</ol>
<a href="insert.html" target="popup"
onclick="window.open('http://kanishkkunal.in','popup','width=600,height=300')">추가</a>
<?php if (isset($_GET['id'])) {
$link="<a href=\"update.php?id={$_GET['id']}\"target=\"popup\"onclick=\"window.open('http://kanishkkunal.in','popup','width=600,height=300')\">수정</a>
<form method=\"post\" action=\"delete.php\"target=\"POPUPW\"onsubmit=\"POPUPW = window.open('about:blank','POPUPW',
'width=600,height=400');\"><input type=\"hidden\" name=\"id\" value=\"{$_GET['id']}\"><input type=\"submit\" value=\"삭제\"></form>";
echo($link);
} ?>
<h2><?php print_title(); ?></h2>
<p>
<?php
print_description();?>
</p>
</body>
</html>
<file_sep>/C/for별나무.c
#include<stdio.h>
int main()
{
int h, n, i, m, j = 0;
scanf_s("%d", &n);//높이n 입력
for (h = 1; h <= n; h++)//h가 1부터n까지 1씩 증가
{
m = 2 * h - 1; //h마다 별의 개수
for (i = n - h; 0 < i; i--)//(높이-h)만큼의 별 앞 공백
{
printf(" ");
}
for (j = 1; j <= m; j++) // 2h-1개수만큼 *출력
{
printf("*");
}
printf("\n");//한층끝
}
return 0;
}<file_sep>/C/분수찾기1193.c
#include<stdio.h>
int main() {
int num, i, j, func, ak, minus, func2, minus2;
scanf("%d", &num);
for (i = 1;; i++) {
func = 2 * i*i - 3*i + 2;
if (func > num) {
ak = i - 1;
j = 2 * ak - 1;
break;
}
}
func2 = 2 * i*i - 3 * i + 2;
func = 2 * ak*ak - 3 * ak + 2;
minus = num - func;
minus2 = func2 - num;
if (num - func < j) {
i = j;
printf("%d/%d", j - minus, 1+ minus);
}
else {
i = j;
printf("%d/%d", j+2 - minus2, minus2);
}
}<file_sep>/python/papago번역기.py
import os
import sys
import json
import urllib.request
client_id = "ubGrRSG3YIxiHqX7cRBw" # 개발자센터에서 발급받은 Client ID 값
client_secret = "<KEY>" # 개발자센터에서 발급받은 Client Secret 값
encText = input("번역할 말을 입력하세요. :")
data = "source=ko&target=en&text=" + encText
url = "https://openapi.naver.com/v1/papago/n2mt"
request = urllib.request.Request(url)
request.add_header("X-Naver-Client-Id",client_id)
request.add_header("X-Naver-Client-Secret",client_secret)
response = urllib.request.urlopen(request, data=data.encode("utf-8"))
rescode = response.getcode()
if(rescode==200):
response_body = response.read()
response_body=response_body.decode('utf-8')
a=json.loads(response_body)
print(a["message"]['result']['translatedText'])
input("종료")
else:
print("Error Code:" + rescode)<file_sep>/C/숫자셋트개수맞추기.c
#include <stdio.h>
int main()
{
int num[100] = { 0, };
int N, mn;
int i = 1, j;
int max = 0;
scanf("%d", &N);
while (i <= N)
{
mn = (N / i) % 10;
if (mn == 9)
{
num[6] += 1;
}
else
{
num[mn] += 1;
}
i *= 10;
}
if (num[6] % 2 == 0)
{
num[6] = num[6] / 2;
}
else
{
num[6] = (num[6] / 2) + 1;
}
for (j = 0; j <= 8; j++)
{
if (num[j] > max)
max = num[j];
}
if (N == 0) {
max = 1;
}
printf("%d", max);
return (0);
}<file_sep>/Web/php+mysql/delete.php
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<?php include('print.php'); ?>
<title></title>
</head>
<body>
<h1>데이터 삭제</h1>
<form action="delete_process.php" method="post">
<h2><?php
include('connect.php');
$sql = "SELECT * FROM topic where id=".$_POST['id'];
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row['title'];
?></h2>
<p>
<?php
include('connect.php');
$sql = "SELECT * FROM topic where id=".$_POST['id'];
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row['description'];
?>
</p>
<input type="submit" value="삭제하기" onClick="window.close()">
<input type="hidden" name="id" value="<?=$_POST['id']?>">
</form>
</body>
</html>
<file_sep>/C/윷놀이.c
#include<stdio.h>
int main() {
int x[4] = { 0 };
int count = 64;
for (int j = 3; j > 0; j--) {
for (int i = 0; i < 4; i++) {
scanf("%d", &x[i]);
if (x[i] == 0)
count++;
}
if (count == 64)
count = 69;
printf("%c\n", count);
count = 64;
}
}<file_sep>/python/네이버음악 순위.py
from bs4 import BeautifulSoup
import urllib.request
url = 'https://music.naver.com/'
with urllib.request.urlopen(url) as fs :
soup = BeautifulSoup(fs.read().decode(fs.headers.get_content_charset()), 'html.parser')
items = soup.find_all('span', {'class' : 'm_ell'})
for i in range(50) :
print(str(i + 1) + '위\t: ' + items[i*3].get_text(strip = True)+ '\t' + items[i*3+1].get_text(strip = True))
input()
<file_sep>/C/분산처리1009.c
#include<stdio.h>
int main() {
int t, a, b, i;
int c=1;
for (scanf("%d", &t); t--;) {
scanf("%d%d", &a, &b);
for (i = 0; i < b; i++) {
c *= a;
c %= 10;
}
if (c == 0)
printf("10\n");
else
printf("%d\n", c);
c = 1;
}
}<file_sep>/Tensorflow/boston_predict.py
import pandas as pd
import tensorflow as tf
파일경로 = 'https://raw.githubusercontent.com/blackdew/tensorflow1/master/csv/boston.csv'
보스턴 = pd.read_csv(파일경로)
print(보스턴.columns)
보스턴.head()
독립 = 보스턴[['crim', 'zn', 'indus', 'chas', 'nox', 'rm', 'age', 'dis', 'rad', 'tax',
'ptratio', 'b', 'lstat']]
종속 = 보스턴[['medv']]
print(독립.shape, 종속.shape)
X = tf.keras.layers.Input(shape=[13])
H = tf.keras.layers.Dense(10, activation='swish')(X)
Y = tf.keras.layers.Dense(1)(H)
model=tf.keras.models.Model(X,Y)
model.compile(loss='mse')
model.fit(독립,종속, epochs=100)
model.predict(독립[0:5])
model.get_weights()
<file_sep>/Web/php/update.php
<?php include 'func.php'; ?>
<form action="update_process.php" method="post">
<input type="hidden" name="old_title" value="<?php echo $_GET['id'] ?>">
<p>
<input type="text" name="title" placeholder="Title" value="<?php print_title(); ?>">
</p>
<p>
<textarea name="description" rows="8" cols="80"><?php print_description(); ?></textarea>
</p>
<input type="submit">
</form>
<file_sep>/Tensorflow/iris.py
import pandas as pd
import tensorflow as tf
파일경로 = 'https://raw.githubusercontent.com/blackdew/tensorflow1/master/csv/iris.csv'
아이리스 = pd.read_csv(파일경로)
아이리스 =pd.get_dummies(아이리스)
아이리스.head()
print(아이리스.columns)
독립 = 아이리스[['꽃잎길이', '꽃잎폭', '꽃받침길이', '꽃받침폭']]
종속 = 아이리스[['품종_setosa', '품종_versicolor','품종_virginica' ]]
print(독립.shape,종속.shape)
x=tf.keras.layers.Input(shape=[4])
H = tf.keras.layers.Dense(8, activation="swish")(x)
H = tf.keras.layers.Dense(8, activation="swish")(H)
H = tf.keras.layers.Dense(8, activation="swish")(H)
y=tf.keras.layers.Dense(3,activation='softmax')(H)
model=tf.keras.models.Model(x,y)
model.compile(loss='categorical_crossentropy', metrics='accuracy')
model.fit(독립,종속, epochs=1000, verbose=0)
model.fit(독립,종속, epochs=10)
print(model.predict(독립[45:55]))
print(종속[45:55])
print(model.get_weights())
<file_sep>/python/IT뉴스TOP30엑셀 출력.py
from openpyxl import Workbook
from bs4 import BeautifulSoup
import urllib.request
import datetime
import os
date= datetime.datetime.today().strftime('%Y%m%d')
url = 'https://news.naver.com/main/ranking/popularDay.nhn?rankingType=popular_day§ionId=105&date='+date
with urllib.request.urlopen(url) as fs :
soup = BeautifulSoup(fs.read().decode(fs.headers.get_content_charset()), 'html.parser')
items = soup.find_all('div', {'class' : 'ranking_headline'})
links=soup.find_all('a',{'class':'nclicks(rnk.sci)'})
desktopPath = os.path.expanduser('~')
filePath = desktopPath + '\뉴스'
wb = Workbook()
ws = wb.active
ws.column_dimensions['B'].width = 60
ws.column_dimensions['C'].width = 12
for i in range (30):
ws.cell(row=i+1,column=1).value=str(i+1)+'위'
ws.cell(row=i+1,column=2).value=items[i].get_text(strip = True)
ws.cell(row=i+1,column=3).value=str('링크로 이동')
ws.cell(row=i+1,column=3).hyperlink=str('https://news.naver.com')+links[2*i].attrs['href']
wb.save(filePath+date+".xlsx")
<file_sep>/Web/기념일 계산기/main.js
function addDate() {
//숫자형식으로 날짜 입력받음
var inital = document.getElementById("selectDate").value;
//날짜 형식으로 변환
var sday = new Date(inital);
//num의 value를 받아옴
var plusdays = document.getElementById("num").value;
//둘중 하나라도 입력값이 없을때
if (!inital || !plusdays) {
var string = "다시 입력 해주세요."
document.getElementById("result").innerHTML = string;
return;
}
//입력받은 값을 정수로 변환시켜줌
plusdays = parseInt(plusdays);
//select - option 인덱스를 받아옴
var target = document.getElementById("select");
var value = target[target.selectedIndex].value;
//index가 0일때 (option "주년"선택시)
if (value == 0) {
var option = "주년"
var addDate = (sday.getFullYear() + plusdays) + "년" + (sday.getMonth() + 1) + "월" + sday.getDate() + "일 입니다.";
}
//index가 1일때 (option "일"선택시)
else {
var option = "일"
sday.setDate(sday.getDate() + plusdays);
var addDate = sday.getFullYear() + "년" + (sday.getMonth() + 1) + "월" + sday.getDate() + "일 입니다.";
}
var string = inital + "부터 " + plusdays + option + " 뒤는 "
document.getElementById("result").innerHTML = string + addDate;
}
<file_sep>/C/입력숫자 모두더하기.c
#include<stdio.h>
#include<math.h>
void main() {
int num1, n, i,total=0;
scanf_s("%d", &n);
scanf_s("%d", &num1);
for (i = n; i > 0; i--) {
total += num1 / pow(10.0,i);
num1 = num1 % (int)pow(10.0, i);
}
printf("%d", total);
}<file_sep>/C/함수2.c
#include<stdio.h>
int num1, num2, num3, n;
int one(int a, int b, int c)
{
int res;
res = a % b *c;
printf("%d %% %d * %d = %d 입니다.\n",a,b,c,res);
return 0;
}
int two(int a, int b, int c)
{
int res;
res = a * b - c;
printf("%d * %d - %d = %d 입니다.\n", a, b, c, res);
return 0;
}
int main()
{
printf("1. n %% n * n \t 2. n * n - n 을 계산하는 프로그램 입니다.");
while (1)
{
printf(" \n번호를 입력하세요.\n");
scanf_s("%d", &n);
switch (n)
{
case(1):
{
printf("세 정수를 입력해주세요.\n");
scanf_s("%d %d %d", &num1, &num2, &num3);
if (num2 == 0)
{
printf("분모는 0이 아니여야 합니다. 다시입력해주세요.");
continue;
}
one(num1, num2, num3);
break;
}
case(2):
{
printf("세 정수를 입력해주세요.\n");
scanf_s("%d %d %d", &num1, &num2, &num3);
two(num1, num2, num3);
break;
}
default:
{
printf("다시 입력해주세요.\n");
continue;
}
}
printf("계속하려면 1번 그만하려면 2번을 입력하세요.\n");
scanf_s("%d", &n);
if (n == 1)
continue;
if (n == 2)
break;
else
printf("잘못된 입력입니다.\n");
}
return 0;
}
<file_sep>/C/벌집최단거리2292.c
#include<stdio.h>
int main()
{
int num, i, sum;
scanf("%d", &num);
for (i = 1; i <1000000000; i++) {
sum = 3 * i*i - (3 * i) + 1;
if (num <= sum) {
printf("%d", i);
break;
}
}
return 0;
}<file_sep>/C/소행성1004.c
#include <stdio.h>
#include<math.h>
int main(void)
{
int Test;
int x1, y1, x2, y2;
int n;
int cx, cy, r;
int count = 0;
for (scanf("%d", &Test);Test--;)
{
scanf("%d %d %d %d", &x1, &y1, &x2, &y2);
for (scanf("%d", &n);n--;)
{
scanf("%d %d %d", &cx, &cy, &r);
if (pow((cx - x1),2) + pow((cy - y1),2)>= r * r || pow((cx - x2),2) + pow((cy - y2),2) >= r * r)
{
if (pow((cx - x1), 2) + pow((cy - y1), 2) < r * r)
count++;
if (pow((cx - x2), 2) + pow((cy - y2), 2) < r * r)
count++;
}
}
printf("%d\n", count);
count = 0;
}
}<file_sep>/C/출력방식.c
#include<stdio.h>
int main() {
int a;
scanf_s("%o", &a);
printf("i= %i\n", a);
printf("d= %d\n", a);
printf("x= %x\n", a);
printf("u= %u\n", a);
printf("o= %o\n", a);
scanf_s("%d", &a);
}
<file_sep>/C/linear search.c
#include<stdio.h>
void main() {
int array[5];
int num1, i;
int count;
for (i = 0; i < 5; i++) {
scanf("%d", &array[i]);
}
printf("\nlist : ");
for (i = 0; i < 5; i++) {
printf("%d ", array[i]);
}
while (1) {
printf("\n\nType a search value : (0 to quit)");
scanf("%d", &num1);
count = 0;
if (num1 == 0) break;
for (i = 0; i < 5; i++) {
if (num1 == array[i]) {
printf("\nposition : %d", i);
count++;
}
}
if (count == 0)printf("\nhave no %d\n", num1);
}
printf("Type any character : ");
scanf("%d", &i);
}<file_sep>/C/연산자.c
#include<stdio.h>
int main() {
int a;
a = 10;
a++; printf("%d\n",a); //11
++a; printf("%d\n",a ); //12
a--; printf("%d\n", a); //11
--a; printf("%d\n", a); //10
printf("%d\n", a++); //10
printf("%d\n", ++a); //12
a -= 1 + 2; // a=a-(1+2);
printf("%d\n", a);
a = a - 1 + 2;
printf("%d\n", a);
getchar();
}<file_sep>/C/boolean.c
#include<stdio.h>
#include<stdbool.h> //불리언 사용시 필요한 헤더
int main() {
int x;
bool y;
printf("\n정수를 입력 하세요.\n");
scanf_s("%d", &x);
y = x;
printf("\ni=%i", y);
printf("\no=%o", y);
printf("\nd=%d", y);
printf("\nu=%u", y);
printf("\nx=%x", y);
//불리언 판별식
if (y!=0) //y가 0이 아닐때
{
printf("\n y는 0이 아닙니다");
}
else
{
printf("\n y는 0입니다.");
}
scanf_s("%d", &x);
}<file_sep>/C/queue.c
#include<stdio.h>
#define SIZE 15
int queue[SIZE] = { 0 };
int index = -1;
int point = 0;
int empty() {
if (point > index) return 0;
return 1;
}
int full() {
if (index == SIZE - 1) return 0;
return 1;
}
void in(num) {
if (!full()) {
printf("overflow\n");
}
queue[(++index)%SIZE] = num;
}
void out() {
if (!empty()) {
printf("underflow\n");
}
if (point > index) exit(1);
else {
printf("%d\n", queue[(point++) % SIZE]);
}
}
int main() {
in(1);
in(2);
in(3);
in(4);
in(5);
out();
out();
out();
out();
out();
//out(); //언더플로우
in(6);
in(7);
in(8);
in(9);
in(10);
in(11);
in(12);
in(13);
in(14);
in(15);
//in(16);오버플로우
out();
out();
out();
out();
out();
}<file_sep>/C/셀프넘버4673.c
#include<stdio.h>
int d[10100];
int dn(int i)
{
int res = i;
if (i >= 10000) { res += i / 10000; i %= 10000; }
if (i >= 1000) { res += i / 1000; i %= 1000; }
if (i >= 100) { res += i / 100; i %= 100; }
if (i >= 10) { res += i / 10; i %= 10; }
res += i;
return res;
}
int main()
{
int i;
for (i = 1; i <= 10000; i++)
{
d[dn(i)] = 1;
if (d[i]==0)
{
printf("%d\n", i);
}
}
}<file_sep>/C/방정식해.c
#include<stdio.h>
#include<math.h>
int main()
{
int a, b, c;
printf("이 프로그램은 이차방정식의 해를 구하는 프로그램입니다. \n ax^2+bx+c의 세 값을 입력해주세요");
scanf_s("%d%d%d", &a, &b, &c);
printf("%dx^2+%dx+%d의 해를 구합니다.", a, b, c);
int d = sqrt(4 * a*c - b ^ 2);
int e = b ^ 2 - 4 * a*c;
int f= sqrt(e);
if (e > 0)
printf("실근을 가집니다. \n 그해는 %d,%d입니다.", (-b + f) / 2 * a, (-b - f) / 2 * a);
else if (e == 0)
printf("중근을 가집니다. \n 그해는 %d입니다.", -b / 2 * a);
else
printf("허근을 가집니다. \n 그해는 %d+-%di입니다.", -b / 2 * a, ( d/ 2 * a) ^ 2);
return 0;
}
<file_sep>/C/음계.c
#include<stdio.h>
int main() {
int array[8];
int count = 0, i,j;
for (j = 0; j < 8; j++) {
scanf("%d", &array[j]);
}
for (i = 0; i < 7; i++) {
if (array[i] < array[i + 1]) {
count++;
}
else if (array[i] > array[i + 1]) {
count--;
}
}
switch (count)
{
case(7):printf("ascending"); break;
case(-7):printf("descending"); break;
default:printf("mixed"); break;
}
return(0);
}<file_sep>/C/sort.c
#include <stdio.h>
#define SIZE 4
void merge(int *x, int *y, int *z){
int x_index=0, y_index = 0;
for(int i = 0; i < SIZE * 2; i++){
if (x_index >= SIZE) {
*z = *y;
y++;
z++;
}
else if(y_index >= SIZE){
*z = *x;
x++;
z++;
}
else{
if(*x > *y){
*z = *y;
y++;
z++;
}
else if(*y > *x){
*z = *x;
x++;
z++;
}
}
}
}
int main(){
int x[SIZE] = {3,7,11,13};
int y[SIZE] = {2,5,6,9};
int z[SIZE*2];
merge(x,y,z);
for(int i = 0; i < SIZE*2; i++)
printf("%d\n", *(z+i));
}
<file_sep>/python/2배수 출력파일 만들기.py
import os
desktopPath = os.path.expanduser('~')
filePath = desktopPath + '\desktop\iX2.txt'
file = open( filePath, 'w+')
for i in range(1, 1000):
file.write( str(i) + "," + str( i*2 ) + "\n" )
file.close()
os.system(filePath)
<file_sep>/react/my-app/src/Comment.js
import React from 'react';
const style = {
root: {
width: '20%',
margin: 'auto',
padding: 16,
backgroundColor: 'white',
borderRadius: 16,
},
nameText: {
color: 'black',
fontSize: 20,
fontWeight: '700',
},
contentText: {
color: 'black',
fontSize: 16,
},
};
class Comment extends React.Component {
render() {
const { name, content } = this.props;
return (
<div style={style.root}>
<div style={style.nameText}>{name}</div>
<div style={style.contentText}>{content}</div>
</div>
);
}
}
export default Comment;<file_sep>/C/원n등분 좌표.c
#include<stdio.h>
#include<math.h>
int main()
{
int choice;
double a, b, r, n, theta, c, s, i, pi, res;
pi = 3.141592;
while(1)
{
printf("\n---------------------------------------------------------------------------\n");
printf("중심이 (a,b) 반지름이 r인원을 n등분한점. \n a,b,r,n을 입력해주세요\n");
scanf_s("%lf%lf%lf%lf", &a, &b, &r, &n);
printf("1 n등분한 점 출력\n2 접선의 방정식 출력\n3 x절편 출력\n4 종료\n");
scanf_s("%d", &choice);
switch (choice)
{
case(1):
printf("n등분한점을 출력합니다.\n");
for (i = 0; i < n; i++)
{
theta = i*(2 * pi / n);
c = cos(theta);
s = sin(theta);
printf("(%0.4lf,%0.4lf)\n", r*c + a, r*s + b);
}
break;
case(2):
printf("접선의 방정식을 출력합니다.\n");
for (i = 0; i < n; i++)
{
theta = i*(2 * pi / n);
c = cos(theta);
s = sin(theta);
if ((r*s + b) < 0)
printf("%0.2lfx%0.2lfy=%0.4lf\n", r*c + a, r*s + b, r*r);
else
printf("%0.2lfx+%0.2lfy=%0.4lf\n", r*c + a, r*s + b, r*r);
}
break;
case(3):
printf("x절편을 구합니다.\n");
for (i = 0; i < n; i++)
{
theta = i*(2 * pi / n);
c = cos(theta);
s = sin(theta);
res = r*r / (r*c + a);
printf("%0.3lf\n", res);
}
break;
case(4):
printf("프로그램을 종료합니다.\n");
break;
default:
printf("다시 입력해주세요\n");
}
}
return 0;
}
<file_sep>/C/swap.c
#include<stdio.h>
void swap(int *a, int* b) {
int t;
t = *a;
*a = *b;
*b = t;
}
int main() {
int i, j;
printf("type two integer : ");
scanf("%d %d", &i, &j);
printf("\n\n before swap: \n i=%d j=%d", i, j);
swap(&i, &j);
printf("\n\n after swap: \n i=%d j=%d", i, j);
scanf("%d", &i);
}<file_sep>/C/방배정10250.c
#include <stdio.h>
int T, H, W, N;
int main()
{
for (scanf("%d", &T); T--;) {
scanf("%d%d%d", &H, &W, &N);
printf("%d%02d\n", (N - 1) % H + 1, (N - 1) / H + 1);
}
}<file_sep>/C/esm1476.c
#include<stdio.h>
int main() {
int e=0, s=0, m=0;
int mye, mys, mym;
int count = 0;
scanf_s("%d %d %d", &mye, &mys, &mym);
for (int i = 0;; i++)
{
e = (e + 1) % 16;
if (e == 0) e++;
s = (s + 1) % 29;
if (s == 0) s++;
m = (m + 1) % 20;
if (m == 0) m++;
count++;
if (e == mye && s == mys && m == mym) break;
}
printf("%d", count);
return 0;
}<file_sep>/C/char.c
#include <stdio.h>
int main()
{
char c1 = 'a'; // 문자 변수를 선언하고 문자 a를 저장
char c2 = 'b'; // 문자 변수를 선언하고 문자 b를 저장
char c3 = 'C';
// char를 %c로 출력하면 문자가 출력되고, %d로 출력하면 정숫값이 출력됨
printf("%c, %d\n", c1, c1); // a, 97: a의 ASCII 코드값은 97
printf("%c, %d\n", c2, c2); // b, 98: b의 ASCII 코드값은 98
printf("%c, %d\n", c3, c3);
getchar();
}<file_sep>/python/CGV순위 출력.py
from bs4 import BeautifulSoup
import urllib.request
url = 'http://www.cgv.co.kr/movies/'
with urllib.request.urlopen(url) as fs :
soup = BeautifulSoup(fs.read().decode(fs.headers.get_content_charset()), 'html.parser')
items = soup.find_all('strong', {'class' : 'title'})
for i in range(10) :
print(str(i + 1) + '위\t: ' + items[i].get_text(strip = True))
input()
<file_sep>/C/while 영어 맞추기.c
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
int num1, count, i;
char * string = (char *)malloc(1);
while (1) {
count = 1;
printf("====================================================");
printf("\n6이상을 입력하면 나가집니다. \n수를 입력하세요 : \n");
scanf_s("%d", &num1);
if (num1 > 5)break;
while (1) {
printf("\n%d 는 영어로 무엇일까요?\n", num1);
scanf_s("%s", string,16);
switch (num1)
{
case 0: {
while (1) {
if (strcmp(string, "zero") == 0) {
printf("\n정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("\n오답입니다. 다시 맞춰보세요 \n");
count++;
scanf_s("%s", string,16);
}
}
}break;
case 1: {
while (1) {
if (strcmp(string, "one") == 0) {
printf("\n정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("\n오답입니다. 다시 맞춰보세요 \n");
count++;
scanf_s("%s", string,16);
}
}
}break;
case 2: {
while (1) {
if (strcmp(string, "two") == 0) {
printf("\n정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("\n오답입니다. 다시 맞춰보세요 \n");
count++;
scanf_s("%s", string,16);
}
}
}break;
case 3: {
while (1) {
if (strcmp(string, "three") == 0) {
printf("\n정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("\n오답입니다. 다시 맞춰보세요 \n");
count++;
scanf_s("%s", string,16);
}
}
}break;
case 4: {
while (1) {
if (strcmp(string, "four") == 0) {
printf("\n정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("\n오답입니다. 다시 맞춰보세요 \n");
count++;
scanf_s("%s", string,16);
}
}break;
}break;
case 5: {
while (1) {
if (strcmp(string, "five") == 0) {
printf("\n정답입니다! %d번 만에 맞추셧군요!\n", count);
switch (count)
{
case 1: printf("exellent!\n"); break;
case 2: printf("great!\n"); break;
case 3: printf("good!\n"); break;
case 4: printf("correct!\n"); break;
default:printf("hmm..더 노력하세요\n");
}
break;
}
else {
printf("\n오답입니다. 다시 맞춰보세요 \n");
count++;
scanf_s("%s", string,16);
}
}
}break;
}break;
}
}
printf("\n수고하셧습니다. 나가려면 아무키나 입력해주세요. \n");
scanf_s("%d", &i);
}<file_sep>/Web/php+mysql/print.php
<?php
function print_list()
{
include('connect.php');
$sql = "SELECT * FROM topic";
$result = mysqli_query($conn, $sql);
while ($row = mysqli_fetch_array($result)) {
echo '<li><a href="index.php?id='.$row[0].'">'.$row['title'].'</a></li>';
}
};
function print_title()
{
if (isset($_GET['id'])) {
include('connect.php');
$sql = "SELECT * FROM topic where id=".$_GET['id'];
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row['title'];
} else {
echo 'welcome';
}
}
function print_description()
{
if (isset($_GET['id'])) {
include('connect.php');
$sql = "SELECT * FROM topic where id=".$_GET['id'];
$result = mysqli_query($conn, $sql);
$row = mysqli_fetch_array($result);
echo $row['description'];
} else {
echo 'hello this is welcome page.';
}
}
<file_sep>/Web/php+mysql/delete_process.php
<?php
include('connect.php');
$sql = "
delete from topic where id={$_POST['id']}
";
mysqli_query($conn, $sql);
<file_sep>/C/문자열.c
// 배열을사용해서 사용자한테 영어 20자정도를 입력받아서 그대로 출력하는 프로그램을 짜오기
#include<stdio.h>
#include <string.h>
int main()
{
char string[20];
int i;
while (1) {
printf("출력할 글을 입력하세요.\n");
gets(string);
if ( strlen(string) > 20)
{
printf("20자 이내로 입력해주세요.\n");
continue;
}
printf("입력하신 문자열은 %s 입니다.\n\n", string);
}
return 0;
}<file_sep>/C/x^2적분.c
#include<stdio.h>
int main(){
int n;
float a,b,i,x,y;
y=0;
scanf("%f%f%d",&a,&b,&n);
x=(b-a)/n;//가로
for(i=1;i<=n;i++)//n번 반복
{
y=y+x*a*a;// 높이*가로 =넓이를 y에저장
a=a+x;//a에 가로더함
}
printf("%f",y); //넓이 출력
}
<file_sep>/C/사칙연산.c
#include<stdio.h>
int main() {
int a, b;
printf("두 수를 입력 해 주세요.\n");
scanf_s("%i %i", &a, &b);
printf(" %i + %i = %i 입니다.\n", a, b, a + b);
printf(" %i - %i = %i 입니다.\n", a, b, a - b);
printf(" %i / %i = %i 입니다.\n", a, b, a / b);
printf(" %i * %i = %i 입니다.\n", a, b, a * b);
printf(" %i %% %i = %i 입니다.\n", a, b, a % b);
scanf_s("%d",&a);
}<file_sep>/Web/php+mysql/update.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<?php include('print.php'); ?>
<title>Document</title>
</head>
<body>
<h1>데이터 수정</h1>
<form action="update_process.php" method="post">
<input type="hidden" name="id" value="<?=$_GET['id']?>">
<input type="text" name="title" placeholder="title" value="<?php print_title(); ?>"><br>
<textarea name="description" rows="8" cols="80" placeholder="description"><?php print_description(); ?></textarea>
<input type="submit" onClick="window.close()" value="수정하기">
</form>
</body>
</html>
|
8ebb1a8900d220407aa4cb230b671482f334f88e
|
[
"JavaScript",
"Java",
"Python",
"PHP",
"C",
"C++"
] | 83
|
C++
|
QuiD-0/Study
|
78b499c276280c47cf8759bbb975274e68b6c9b2
|
a9066ca3a273c79702d4f45ed444185ccf8404d3
|
refs/heads/master
|
<repo_name>andrew-blomquist-6/cypress-terminal-report<file_sep>/index.js
const methods = require('methods');
const PADDING = {
LOG: '\t\t ',
};
function pipeLogsToTerminal(config = {}) {
let oldConsoleMethods = {};
let logs = [];
Cypress.on('fail', error => {
const [type, message] = logs[logs.length - 1];
logs[logs.length - 1] = [type, message, 'failed'];
throw error;
});
Cypress.on('window:before:load', () => {
const docIframe = window.parent.document.querySelector("[id*='Your App']");
const appWindow = docIframe.contentWindow;
const createWrapper = (method, logType) => {
oldConsoleMethods[method] = appWindow.console[method];
appWindow.console[method] = (...args) => {
logs.push([logType, args.join(' ')]);
oldConsoleMethods[method](...args);
};
};
createWrapper('warn', 'warn');
createWrapper('error', 'error');
if (config.printConsoleInfo) {
createWrapper('info', 'info');
createWrapper('log', 'log');
}
});
Cypress.Commands.overwrite('log', (subject, ...args) => {
logs.push(['cy:log', args.join(' ')]);
subject(...args);
});
Cypress.on('log:added', options => {
if (options.instrument === 'command' && options.consoleProps) {
if (
options.name === 'log' ||
(options.name === 'task' && options.message.match(/terminalLogs/))
) {
return;
}
let detailMessage = '';
if (options.name === 'xhr') {
detailMessage =
(options.consoleProps.Stubbed === 'Yes' ? 'STUBBED ' : '') +
options.consoleProps.Method +
' ' +
options.consoleProps.URL;
}
if (options.name === 'request') {
return;
}
const log =
options.name + '\t' + options.message + (detailMessage !== '' ? ' ' + detailMessage : '');
logs.push(['cy:command', log, options.state]);
}
});
Cypress.Commands.overwrite('request', async (originalFn, ...args) => {
let log;
// args can have up to 3 arguments
// https://docs.cypress.io/api/commands/request.html#Syntax
if (args[0].method) {
log = `${args[0].method} ${args[0].url ? `${args[0].url}` : args[0]}`;
} else if (isValidHttpMethod(args[0])) {
log = `${args[0]} ${args[1]}`;
} else {
log = `${args[0]}`;
}
const response = await originalFn(...args).catch(async e => {
let body = {};
if (
// check the body is there
e.onFail().toJSON().consoleProps.Yielded &&
e.onFail().toJSON().consoleProps.Yielded.body
) {
body = e.onFail().toJSON().consoleProps.Yielded.body;
}
log += `\n${PADDING.LOG}${e.message.match(/Status:.*\d*/g)}
${PADDING.LOG}Response: ${await responseBodyParser(body)}`;
logs.push(['cy:request', log]);
throw e;
});
log += `\n${PADDING.LOG}Status: ${response.status}
${PADDING.LOG}Response: ${await responseBodyParser(response.body)}`;
logs.push(['cy:request', log]);
return response;
});
function isValidHttpMethod(str) {
return typeof str === 'string' && methods.some(s => str.toLowerCase().includes(s));
}
Cypress.Commands.overwrite('server', (originalFn, options = {}) => {
const prevCallback = options && options.onAnyResponse;
options.onAnyResponse = async (route, xhr) => {
if (prevCallback) {
prevCallback(route, xhr);
}
if (!route) {
return;
}
logs.push([
String(xhr.status).match(/^2[0-9]+$/) ? 'cy:route:info' : 'cy:route:warn',
`Status: ${xhr.status} (${route.alias})\n${PADDING.LOG}Method: ${xhr.method}\n${
PADDING.LOG
}Url: ${xhr.url}\n${PADDING.LOG}Response: ${await responseBodyParser(xhr.response.body)}`,
]);
};
originalFn(options);
});
Cypress.mocha.getRunner().on('test', () => {
logs = [];
});
afterEach(function() {
if (this.currentTest.state !== 'passed' || (config && config.printLogs === 'always')) {
cy.task('terminalLogs', logs);
}
});
}
async function responseBodyParser(body) {
if (!body) {
return 'EMPTY_BODY';
} else if (typeof body === 'string') {
return body;
} else if (typeof body === 'object') {
if (typeof body.text === 'function') {
return await body.text();
}
const padding = `\n${PADDING.LOG}`;
return `${JSON.stringify(body, null, 2).replace(/\n/g, padding)}`;
}
return 'UNKNOWN_BODY';
}
function nodeAddLogsPrinter(on, options = {}) {
const chalk = require('chalk');
on('task', {
terminalLogs: messages => {
messages.forEach(([type, message, status]) => {
let color = 'white',
typeString = ' [unknown] ',
processedMessage = message,
trim = options.defaultTrimLength || 200,
icon = '-';
if (type === 'warn') {
color = 'yellow';
typeString = ' cons.warn ';
icon = '⚠';
} else if (type === 'error') {
color = 'red';
typeString = ' cons.error ';
icon = '⚠';
} else if (type === 'cy:log') {
color = 'green';
typeString = ' cy:log ';
icon = 'ⓘ';
}else if (type === 'log') {
color = 'white';
typeString = ' cons:log ';
icon = 'ⓘ';
} else if (type === 'info') {
color = 'white';
typeString = ' cons:info ';
icon = 'ⓘ';
} else if (type === 'cy:command') {
typeString = ' cy:command ';
color = 'green';
icon = '✔';
trim = options.commandTrimLength || 600;
} else if (type === 'cy:route:info') {
typeString = ' cy:route ';
color = 'green';
icon = '⛗';
trim = options.routeTrimLength || 5000;
} else if (type === 'cy:route:warn') {
typeString = ' cy:route ';
color = 'yellow';
icon = '⛗';
trim = options.routeTrimLength || 5000;
} else if (type === 'cy:request') {
typeString = ` cy:request `;
color = 'green';
icon = '✔';
trim = options.routeTrimLength || 600;
}
if (status && status === 'failed') {
color = 'red';
icon = '✘';
}
if (message.length > trim) {
processedMessage = message.substring(0, trim) + ' ...';
}
console.log(chalk[color](typeString + icon + ' '), processedMessage);
});
console.log('\n\n');
return null;
},
});
}
module.exports = {
/**
* Installs the cypress plugin for printing logs to terminal.
*
* Needs to be added to plugins file.
*
* @param {Function} on
* Cypress event listen handler.
* @param {object} options
* Options for displaying output:
* - defaultTrimLength?: Trim length for console and cy.log.
* - commandTrimLength?: Trim length for cy commands.
*/
installPlugin: (on, options = {}) => nodeAddLogsPrinter(on, options),
/**
* Installs the logs collector for cypress.
*
* Needs to be added to support file.
*/
installSupport: config => pipeLogsToTerminal(config),
};
<file_sep>/README.md
# Cypress terminal report
[](https://travis-ci.com/archfz/cypress-terminal-report)
Plugin for cypress that adds better terminal output __when tests fail__
on the terminal for better debugging. Prints cy commands, console.warn,
console.error and request response data captured with cy.route.
> Note: If you want to display the logs when test succeed as well then check the
[options](#options) for the support install.
> Note: Currently logs do not appear in the dashboard. If you want to see them go
to your CI runner and check the pipeline logs there.

## Install
1. Install npm package.
```bash
npm i --save-dev cypress-terminal-report
```
2. Register the output plugin in `cypress/plugins/index.js`
```js
module.exports = (on) => {
require('cypress-terminal-report').installPlugin(on);
};
```
3. Register the log collector support in `cypress/support/index.js`
```js
require('cypress-terminal-report').installSupport();
```
## Options
Options for the plugin install: `.installPlugin(on, options)`:
- `options.defaultTrimLength` - default: 200; max length of cy.log and console.warn/console.error.
- `options.commandTrimLength` - default: 600; max length of cy commands.
- `options.routeTrimLength` - default: 5000; max length of cy.route request data.
Options for the support install: `.installSupport(options)`:
- `options.printLogs` - default: null; possible values: null, 'always' - When set to always
logs will be printed for successful test as well as failing ones.
- `printConsoleInfo` - default: null; possible values: null, true - When true `console.log()`
and `console.info()` logs will also be printed to the terminal, besides warn and error.
## Release notes
#### 1.1.0
- Added notice for logs not appearing in dashboard. from [issue](https://github.com/archfz/cypress-terminal-report/issues/8)
- Added [support for logging](#options) console.info and console.log. in [issue](https://github.com/archfz/cypress-terminal-report/issues/12)
- Added better logging of cy.requests. in [issue](https://github.com/archfz/cypress-terminal-report/issues/12) by [@zhex900](https://github.com/zhex900)
#### 1.0.0
- Added tests and CI to repository.
- Added support for showing logs even for successful tests. in [issue](https://github.com/archfz/cypress-terminal-report/issues/3) by [@zhex900](https://github.com/zhex900)
- Fixed issue with incorrectly labeled failed commands. in [issue](https://github.com/archfz/cypress-terminal-report/issues/3) by [@zhex900](https://github.com/zhex900)
- Fixed issue with logs from cy.route breaking tests on XHR API type of requests. [merge-request](https://github.com/archfz/cypress-terminal-report/pull/1) by [@zhex900](https://github.com/zhex900)
|
293d6ad656ad72924f40f651960c3db071d2105a
|
[
"JavaScript",
"Markdown"
] | 2
|
JavaScript
|
andrew-blomquist-6/cypress-terminal-report
|
c2b832f57d369676fa3823c076c1e061d5fe7945
|
a9431b04a9e7d441d79455736aa5defe70768055
|
refs/heads/master
|
<repo_name>wxuanzhi/Water2<file_sep>/app/src/main/java/com/fju/water/ResultActivity.java
package com.fju.water;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
public class ResultActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_result);
float money = getIntent().getFloatExtra("FEE",-1);
Log.d("ResultActivity",money+"");
TextView feeText = findViewById(R.id.money);
int n = (int)(money + 0.5f);//四捨五入
feeText.setText(n+ "");
}
}
|
1c1dae9ca3204ccaa04eaa27908e8f42e5ce17c5
|
[
"Java"
] | 1
|
Java
|
wxuanzhi/Water2
|
1e0747b1858199b7f26f5d95ca85ebbd90e6c8f1
|
7e01ddcde2c8e01ebb7c468fb3f1555105163f59
|
refs/heads/master
|
<repo_name>brokerstir/codecademy-js<file_sep>/contacts.js
// This code written for the contact list lesson on the codecademy javascript tutorial.
// The first task is to create an object of friends.
var friends = {
allan: {
firstName: "Allan",
lastName: "Caralina",
number: "09 000 0001",
address: ['Sabawl', 'Castillejos', 'Zambales']
},
kiko: {
firstName: "Kiko",
lastName: "Kiko",
number: "09 000 0011",
address: ['San Antonio', 'Zambales']
},
charie: {
firstName: "Charie",
lastName: "Aiza",
number: "09 00 0111",
address: ['Malate', 'Manila', 'PI']
},
bill: {
firstName: "Bill",
lastName: "Gates",
number: "(206) 555-5555",
address: ['One Microsoft Way','Redmond','WA','98052']
},
steve: {
firstName: "Steve",
lastName: "<NAME>",
number: "(266) 555-5555",
address: ['Infinite Loop','Silicone Valley']
},
};
// Our object of friends is complete.
// Now we create a function to print the main key of each contact.
var list = function(friends) {
// Use a for loop to log through every key and print it.
for (var key in friends) {
console.log(key);
}
}
// End of function
// Now we create a search function.
// This will allow us to search by first name.
var search = function(name) {
// Use a for loop to find and print a match.
for (var key in friends) {
if (friends[key].firstName === name) {
console.log(friends[key]);
return friends[key];
}
}
}<file_sep>/README.md
# codecademy-js
Worked Lessons from Codecademy JavaScript Tutorial
<file_sep>/namesearch.js
// This program should search a block of text for my name and return it, if found.
var text = "My name is Robert, not Ricky. That's what my parents \ named me - Robert.";
var myName = "Robert";
var hits = [];
for(var i = 0; i < text.length; i++) {
if(text[i] === 'R') {
for(var j = i; j < (i + myName.length); j++) {
hits.push(text[j]);
}
}
}
if(hits.length === 0) {
console.log("Your name wasn't found!");
} else if(hits != myName) {
delete hits;
} else {
console.log(hits);
}
|
3883ec733889a9e18cc8b460cec16c28ff0d4ae7
|
[
"JavaScript",
"Markdown"
] | 3
|
JavaScript
|
brokerstir/codecademy-js
|
e4e92ce91bbabe407d41c27e01f69d6bcde6c623
|
ff1001fef04ab7608adefbedb8fcd3762798228e
|
refs/heads/master
|
<file_sep>#include "RenderCamera.h"
RenderCamera::RenderCamera(){}
RenderCamera::~RenderCamera(){
}
<file_sep>#ifndef VECTOR3_HEADER_GUARD
#define VECTOR3_HEADER_GUARD
#include <GL\glew.h>
#include <iostream>
#include "Errors.h"
struct Vector3{
GLfloat x;
GLfloat y;
GLfloat z;
Vector3() : x(0), y(0), z(0){}
Vector3(GLfloat x, GLfloat y, GLfloat z) : x(x), y(y), z(z){}
GLfloat get(int index){
if (index == 0){
return x;
}
else if (index == 1){
return y;
}
else if (index == 2){
return z;
}
else{
fprintf(stdout, "Vector4 get() Error: Index %i is invalid(code: %i)", index, ERROR_VECTOR3_INDEX_NOT_FOUND);
return x;
}
}
Vector3 operator * (Vector3 &factor){
return Vector3(
x * factor.x,
y * factor.y,
z * factor.z);
}
GLfloat sum(){
return x + y + z;
}
};
#endif
<file_sep>#ifndef RENDER_BATCH_HEADER_GUARD
#define RENDER_BATCH_HEADER_GUARD
#include <iostream>
#include <GL\glew.h>
#include "Errors.h"
#include "Vertex.h"
class RenderBatch{
private:
int maxVerticesCount;
unsigned vertexArray;
unsigned vertexBuffer;
int renderType;
public:
RenderBatch(int maxVerticesCount, int renderType);
~RenderBatch();
/* Actions */
void render();
};
#endif
<file_sep>#ifndef VECTOR4_DEF_GUARD
#define VECTOR4_DEF_GUARD
#define VECTOR_POSITION 1
#define VECTOR_DIRECTION 0
#include <GL\glew.h>
#include <iostream>
#include "Errors.h"
struct Vector4 {
GLfloat x;
GLfloat y;
GLfloat z;
GLint w;
Vector4() : x(0), y(0), z(0), w(0){}
Vector4(GLfloat x, GLfloat y, GLfloat z, GLint w) : x(x), y(y), z(z), w(w){}
GLfloat get(int index){
if (index == 0){
return x;
} else if (index == 1){
return y;
} else if (index == 2){
return z;
} else if (index == 3){
return w;
} else{
fprintf(stdout, "Vector4 get() Error: Index %i is invalid(code: %i)", index, ERROR_VECTOR4_INDEX_NOT_FOUND);
return x;
}
}
Vector4 operator * (Vector4 &factor){
return Vector4(
x * factor.x,
y * factor.y,
z * factor.z,
w * factor.w);
}
Vector4 operator *= (Vector4 &factor){
return *this * factor;
}
GLfloat sum(){
return x + y + z + w;
}
};
#endif<file_sep>#include "RenderBatch.h"
RenderBatch::RenderBatch(int maxVerticesCount, int renderType):
maxVerticesCount(maxVerticesCount),
renderType(renderType){
//Make sure we are not creating to small of a RenderBatch, 1-4Mb is the optimal size
if (maxVerticesCount < 1000){
fprintf(stdout, "Render Batch Error: maxVerticesCount must be over 1000 was %i(code: %i)", maxVerticesCount, ERROR_RENDER_BATCH_MIN_VERTICES_LOW);
}
glGetError();
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, maxVerticesCount * sizeof(Vertex), nullptr, GL_STREAM_DRAW);
}
RenderBatch::~RenderBatch(){}//TODO Implement RenderBatch::~RenderBatch()
/* Actions */
void RenderBatch::render(){
}<file_sep>#ifndef SHADER_LOADER_DEF_GUARD
#define SHADER_LOADER_DEF_GUARD
#include <GL\glew.h>
#include <fstream>
#include <string>
#include <vector>
#include <minmax.h>
#include "Errors.h"
using namespace std;
class ShaderLoader{
public:
static int create(GLenum shaderType, char *filePath, GLuint shaderProgram);
static int load(char *filePath, GLuint *shader, GLuint shaderProgram);
static int link(GLuint shaderProgram);
};
#endif<file_sep>#ifndef TRANSFORM_MATRIX_HEADER_GUARD
#define TRANFORM_MATRIX_HEADER_GUARD
#include "Matrix4.h"
struct TransformMatrix{
Matrix4 translationMatrix;
Matrix4 rotationMatrix;
Matrix4 scaleMatrix;
TransformMatrix() :
translationMatrix(Matrix4(1)),
rotationMatrix(Matrix4(1)),
scaleMatrix(Matrix4(1)){}
TransformMatrix(Matrix4 translationMatrix, Matrix4 rotationMatrix, Matrix4 scaleMatrix):
translationMatrix(translationMatrix),
rotationMatrix(rotationMatrix),
scaleMatrix(scaleMatrix){}
Matrix4 transform(){
return translationMatrix * rotationMatrix * scaleMatrix;
}
};
#endif
<file_sep>#ifndef VERTEX_PRIMITIVE_HEADER_GUARD
#define VERTEX_PRIMITIVE_HEADER_GUARD
#include "vector"
#include "TransformMatrix.h"
#include "Vertex.h"
using namespace std;
class VertexPrimitive{
private:
TransformMatrix transformMatrix;
vector<Vertex> vertices;
public:
VertexPrimitive(vector<Vertex> vertices);
~VertexPrimitive();
/* Actions */
vector<Vertex> transform();
/* Getters */
TransformMatrix getTransformMatrix();
vector<Vertex> getVertices();
/* Setters */
void setTransformMatrix(TransformMatrix transformMatrix);
void setVertices(vector<Vertex> vertices);
};
#endif
<file_sep>#ifndef ERRORS_DEF_GUARD
#define ERRORS_DEF_GUARD
/*
0-99 General errors
100-199 File errors
200-299 Shader errors
300-399 Vector errors
400-499 RenderBatch errors
*/
#define ERROR_OK 0
#define ERROR_FAIL 1
#define ERROR_GLFW_INIT_FAIL 2
#define ERROR_GLEW_INIT_FAIL 3
#define ERROR_FILE_NOT_FOUND 100
#define ERROR_FILE_EMPTY 101
#define ERROR_SHADERS_LOAD_FAIL 200
#define ERROR_SHADER_CHECK_FAIL 201
#define ERROR_SHADER_LINK_FAIL 202
#define ERROR_VECTOR3_INDEX_NOT_FOUND 300
#define ERROR_VECTOR4_INDEX_NOT_FOUND 301
#define ERROR_RENDER_BATCH_MIN_VERTICES_LOW 400
#endif<file_sep>#include <iostream>
#include <GL\glew.h>
#include <GLFW\glfw3.h>
#include "Errors.h"
#include "Vector4.h"
#include "ShaderLoader.h"
using namespace std;
void error_callback(int error, const char* desc){
fprintf(stdout, "GLFW Error: %s\n", desc);
}
void key_callback(GLFWwindow* window, int key, int scancode, int action, int mods){
if (key == GLFW_KEY_ESCAPE && action == GLFW_PRESS){
glfwSetWindowShouldClose(window, GL_TRUE);
}
}
int main(){
//Init GLFW
glfwSetErrorCallback(error_callback);
if (!glfwInit()){
return ERROR_GLFW_INIT_FAIL;
}
//Setup context
GLFWwindow* window = glfwCreateWindow(640, 480, "Hello OpenGl", NULL, NULL);
if (!window){
glfwTerminate();
return ERROR_GLFW_INIT_FAIL;
}
glfwMakeContextCurrent(window);
glfwSetKeyCallback(window, key_callback);
//Bind Gl
GLenum glewInitErr = glewInit();
if (glewInitErr != GLEW_OK){
fprintf(stdout, "Glew Error: %s\n", glewGetErrorString(glewInitErr));
return ERROR_GLEW_INIT_FAIL;
}
//Setup Vertex arrays
GLuint vertexArray;
glGenVertexArrays(1, &vertexArray);
glBindVertexArray(vertexArray);
Vector4 vertexBufferData[] = {
Vector4(-1.0f, -1.0f, 0.0f, VECTOR_POSITION),
Vector4(1.0f, -1.0f, 0.0f, VECTOR_POSITION),
Vector4(0.0f, 1.0f, 0.0f, VECTOR_POSITION)
};
GLuint vertexBuffer;
glGenBuffers(1, &vertexBuffer);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glBufferData(GL_ARRAY_BUFFER, sizeof(vertexBufferData), vertexBufferData, GL_STATIC_DRAW);
GLuint shaderProgram = glCreateProgram();
int vertexShaderLoadError = ShaderLoader::create(GL_VERTEX_SHADER, "simple_vertex_shader.glsl", shaderProgram);
int fragmentShaderLoadError = ShaderLoader::create(GL_FRAGMENT_SHADER, "simple_fragment_shader.glsl", shaderProgram);
if (vertexShaderLoadError != ERROR_OK || fragmentShaderLoadError != ERROR_OK){
printf("Shaders failed to load, Vertex Error: %i, Fragment Error: %i", vertexShaderLoadError, fragmentShaderLoadError);
return ERROR_SHADERS_LOAD_FAIL;
}
int shadersLinkError = ShaderLoader::link(shaderProgram);
if (shadersLinkError != ERROR_OK){
printf("Shaders link fail");
return ERROR_SHADER_LINK_FAIL;
}
while (!glfwWindowShouldClose(window)){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glUseProgram(shaderProgram);
glEnableVertexAttribArray(0);
glBindBuffer(GL_ARRAY_BUFFER, vertexBuffer);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, (void*)0);
glDrawArrays(GL_TRIANGLES, 0, 3);
glDisableVertexAttribArray(0);
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwDestroyWindow(window);
glfwTerminate();
return ERROR_OK;
}<file_sep>#ifndef RENDER_CAMERA_HEADER_GUARD
#define RENDER_CAMERA_HEADER_GUARD
#include "TransformMatrix.h"
class RenderCamera{
private:
TransformMatrix transformMatrix;
public:
RenderCamera();
~RenderCamera();
};
#endif
<file_sep>#ifndef VERTEX_HEADER_GUARD
#define VERTEX_HEADER_GUARD
#include "Vector4.h"
struct Vertex{
Vector4 position;
Vector4 color;
Vertex(Vector4 position, Vector4 color) : position(position), color(color){}
};
#endif
<file_sep>#include "VertexPrimitive.h"
VertexPrimitive::VertexPrimitive(vector<Vertex> vertices):
vertices(vertices),
transformMatrix(TransformMatrix()){}
VertexPrimitive::~VertexPrimitive(){}
/* Actions */
vector<Vertex> VertexPrimitive::transform(){
Matrix4 tranformation = getTransformMatrix().transform();
vector<Vertex> transformedVertices = getVertices();
for (int i = 0; i < transformedVertices.size(); i++){
transformedVertices[i].position = tranformation * transformedVertices[i].position;
}
return transformedVertices;
}
/* Getters */
TransformMatrix VertexPrimitive::getTransformMatrix(){
return transformMatrix;
}
vector<Vertex> VertexPrimitive::getVertices(){
return vertices;
}
/* Setters */
void VertexPrimitive::setTransformMatrix(TransformMatrix transformMatrix){
VertexPrimitive::transformMatrix = transformMatrix;
}
void VertexPrimitive::setVertices(vector<Vertex> vertices){
VertexPrimitive::vertices = vertices;
}
<file_sep>#include "ShaderLoader.h"
int ShaderLoader::create(GLenum shaderType, char *filePath, GLuint shaderProgram){
GLuint shader = glCreateShader(shaderType);
int loadStatus = ShaderLoader::load(filePath, &shader, shaderProgram);
glDeleteShader(shader);
return loadStatus;
}
int ShaderLoader::load(char *filePath, GLuint *shader, GLuint shaderProgram){
//Load shader file
string shaderFileContents;
ifstream shaderFile(filePath, ios::in);
if (shaderFile.is_open()){
string line;
while (getline(shaderFile, line)){
shaderFileContents += "\n" + line;
}
shaderFile.close();
}
//Compile shader
const char *shaderSourcePointer = shaderFileContents.c_str();
glShaderSource(*shader, 1, &shaderSourcePointer, NULL);
glCompileShader(*shader);
//Check shader
GLint shaderCheckResult = GL_FALSE;
int infoLogLength;
glGetShaderiv(*shader, GL_COMPILE_STATUS, &shaderCheckResult);
glGetShaderiv(*shader, GL_INFO_LOG_LENGTH, &infoLogLength);
vector<char> shaderErrorMessage(infoLogLength);
glGetShaderInfoLog(*shader, infoLogLength, NULL, &shaderErrorMessage[0]);
if (shaderErrorMessage[0] != NULL){
fprintf(stdout, "Check Shader Error\n%s\n", &shaderErrorMessage[0]);
return ERROR_SHADER_CHECK_FAIL;
}
glAttachShader(shaderProgram, *shader);
return ERROR_OK;
}
int ShaderLoader::link(GLuint shaderProgram){
GLint shaderCheckResult = GL_FALSE;
int infoLogLength;
glLinkProgram(shaderProgram);
glGetProgramiv(shaderProgram, GL_LINK_STATUS, &shaderCheckResult);
glGetProgramiv(shaderProgram, GL_INFO_LOG_LENGTH, &infoLogLength);
vector<char> programErrorMessage(max(infoLogLength, int(1)));
glGetProgramInfoLog(shaderProgram, infoLogLength, NULL, &programErrorMessage[0]);
if (programErrorMessage[0] != NULL){
fprintf(stdout, "Link Error\n%s\n", &programErrorMessage[0]);
return ERROR_SHADER_LINK_FAIL;
}
return ERROR_OK;
}
<file_sep>#ifndef MATRIX4_DEF_GUARD
#define MATRIX4_DEF_GUARD
#include "Vector4.h"
struct Matrix4{
Vector4 x;
Vector4 y;
Vector4 z;
Vector4 w;
Matrix4() : x(Vector4()), y(Vector4()), z(Vector4()), w(Vector4()){}
Matrix4(Vector4 x, Vector4 y, Vector4 z, Vector4 w) : x(x), y(y), z(z), w(w){}
Matrix4(float identityValue) : x(Vector4()), y(Vector4()), z(Vector4()), w(Vector4()){
x.x = identityValue;
y.y = identityValue;
z.z = identityValue;
w.w = identityValue;
}
Vector4 getColumn(int colNum){
return Vector4(x.get(colNum), y.get(colNum), z.get(colNum), w.get(colNum));
}
Matrix4 operator * (Matrix4 &matrix){
return Matrix4(
x * matrix.getColumn(0),
y * matrix.getColumn(1),
z * matrix.getColumn(2),
w * matrix.getColumn(3));
}
Vector4 operator * (Vector4 &vector){
return Vector4(
(x * vector).sum(),
(y * vector).sum(),
(z * vector).sum(),
(w * vector).sum());
}
};
#endif
|
c166b0ea88918629e554d8a67bef26a14afd606c
|
[
"C",
"C++"
] | 15
|
C++
|
Noah-Huppert/HelloGl
|
d40d0bc2ad19c361886283dd8975e53bc96a2a9a
|
02633ebeb0ceb34bff8c116f75f272093cd01fe6
|
refs/heads/master
|
<file_sep>[](https://travis-ci.org/Kraymer/cronicle)
cronicle :hourglass_flowing_sand::arrows_counterclockwise::floppy_disk:
========
> **/ˈkɹɒnɪkəl/** :
>
> 1. *n.* a factual written account of important events in the order of their occurrence
> 2. *n.* software to archive the *N* most recent backups of a file in a folder named after the job frequency. Recommended use is to trigger it via a cron job.
Originally, `cronicle` has been conceived as a solution to this particular [serverfault](https://serverfault.com) question : [How to keep: daily backups for a week, weekly for a month, monthly for a year, and yearly after that](https://serverfault.com/questions/575163/how-to-keep-daily-backups-for-a-week-weekly-for-a-month-monthly-for-a-year-a).
[](https://asciinema.org/a/155861)
Features
--------
- **simplicity:** add one line to your `crontab` and you're done
- **files rotation:** keep the N most recent versions of a file
- **space efficient:** use symlinks in target directories to store a single occurence of each backup instead of performing copies. When removing a link, remove the underlying file if no other link point to it.
Usage
-----
In order to manage a file backups with cronicle, you must have a section in the `config.yaml` that matches the backups names. Under it you can then define values (number of archives to keep) for the four kinds of periodic archives : `daily`, `weekly`, `monthly`, `yearly`.
Or define a custom periodicity using the *pipe syntax* eg `bimonthly|60: 3` to keep archives every
two months over the last six months.
Example
-------
If you have dumps of a database in a `~/dumps` directory named like `mydb-20170101.dump`, `mydb-20170102.dump`, and want to keep each dump for 7 days plus go back up to two months ; a working `${HOME}/.config/cronicle/config.yaml` content would be :
/home/johndoe/dumps/mydb-*.dump:
daily: 7
monthly: 2
Next `cronicle` call will result in the creation of folders `DAILY` and `MONTHLY` in `/home/johndoe/dumps/`, each folder containing symlinks to the .dump files.
Installation
------------
cronicle is written for [Python 2.7](https://www.python.org/downloads/) and [Python 3](https://www.python.org/downloads/),
is tested on Linux and Mac OS X.
Install with [pip](https://pip.pypa.io/en/stable/) via
`pip install git+https://github.com/Kraymer/cronicle.git` command.
`cron` triggering
-----------------
For a no-brainer use, I recommend to run cronicle via cron, just after the command in charge of performing the backup. A `crontab` example :
@daily pg_dump -Fc mydb > /home/johndoe/dumps/mydb-`date +%F`.dump
@daily cronicle -r /home/johndoe/dumps/mydb-`date +%F`.dump
If used with the `config.yaml` as defined in the previous section, this daily call to cronicle guarantees that you will keep at most 9 database dumps (7 latest daily + 2 monthly).
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Copyright (c) 2018 <NAME> - kray.me
# The MIT License http://www.opensource.org/licenses/mit-license.php
"""Use cron to rotate backup files!
"""
import click
import glob
import logging
from collections import OrderedDict
from datetime import datetime
from os import (lstat, makedirs, path, remove, symlink, unlink)
from shutil import rmtree
from .config import config
__author__ = '<NAME> <<EMAIL>>'
__version__ = '0.1.0'
logger = logging.getLogger(__name__)
DEFAULT_CFG = {'daily': 0, 'weekly': 0, 'monthly': 0, 'yearly': 0, 'pattern': '*'}
# Names of frequency folders that will host symlinks, and minimum number of days between 2 archives
FREQUENCY_FOLDER_DAYS = {
'DAILY': 1,
'WEEKLY': 7,
'MONTHLY': 30,
'YEARLY': 365,
}
CONFIG_PATH = path.join(config.config_dir(), 'config.yaml')
def set_logging(verbose=False):
"""Set logging level based on verbose flag.
"""
levels = {0: logging.WARNING, 1: logging.INFO, 2: logging.DEBUG}
logging.basicConfig(level=levels[verbose], format='%(levelname)s: %(message)s')
def frequency_folder_days(ffolder):
"""Return minimum number of days between 2 archives inside given folder
"""
try:
return FREQUENCY_FOLDER_DAYS[ffolder.upper()]
except KeyError:
pass
try:
return int(ffolder.split('|')[-1])
except:
return None
def file_create_day(filepath):
"""Return file creation date with a daily precision.
"""
try:
filedate = lstat(path.realpath(filepath)).st_birthtime
except AttributeError:
filedate = lstat(path.realpath(filepath)).st_mtime
return datetime.fromtimestamp(filedate).replace(hour=0, minute=0, second=0, microsecond=0)
def archives_create_days(folder, pattern='*'):
"""Return OrderedDict of archives symlinks sorted by creation days (used as keys).
"""
creation_dates = {}
abs_pattern = path.join(folder, path.basename(pattern))
for x in glob.glob(abs_pattern):
if path.islink(x):
creation_dates[file_create_day(x)] = x
return OrderedDict(sorted(creation_dates.items()))
def delta_days(filename, folder, cfg):
"""Return nb of elapsed days since last archive in given folder.
"""
archives = archives_create_days(folder, cfg['pattern'])
if archives:
last_archive_day = list(archives.keys())[-1]
return (file_create_day(filename) - last_archive_day).days
def timed_symlink(filename, ffolder, cfg):
"""Create symlink for filename in ffolder if enough days elapsed since last archive.
Return True if symlink created.
"""
target_dir = path.abspath(path.join(path.dirname(filename), ffolder.split('|')[0]))
days_elapsed = delta_days(filename, target_dir, cfg)
if (days_elapsed is not None) and days_elapsed < frequency_folder_days(ffolder):
logger.info('No symlink created : too short delay since last archive')
return
target = path.join(target_dir, path.basename(filename))
if not path.lexists(target):
if not path.exists(target_dir):
makedirs(target_dir)
logger.info('Creating symlink %s' % target)
symlink(filename, target)
else:
logger.error('%s already exists' % target)
return
return True
def rotate(filename, ffolder, _remove, cfg):
"""Keep only the n last links of folder that matches same pattern than filename.
"""
others_ffolders = [x.split('|')[0].upper() for x in set(cfg.keys()) - set([ffolder])]
target_dir = path.abspath(path.join(path.dirname(filename), ffolder.split('|')[0]))
# sort new -> old
links = list(archives_create_days(target_dir, cfg['pattern']).values())[::-1]
for link in links[cfg[ffolder.lower()]:]: # skip the n most recents
filepath = path.realpath(link)
logger.info('Unlinking %s' % link)
unlink(link)
if _remove and not is_symlinked(filepath, others_ffolders):
if path.isfile(filepath):
remove(filepath)
elif path.isdir(filepath):
rmtree(filepath)
def is_symlinked(filepath, folders):
"""Return True if filepath has symlinks pointing to it in given folders.
"""
dirname, basename = path.split(filepath)
for folder in folders:
target = path.abspath(path.join(dirname, folder, basename))
if path.lexists(target):
return True
return False
def find_config(filename, cfg=None):
"""Return the config matched by filename or the default one.
"""
res = DEFAULT_CFG
dirname, basename = path.split(filename)
if not cfg:
cfg = config
# Overwrite default config fields with matched config ones
for key in cfg.keys():
abskey = path.join(dirname, key) if not path.isabs(key) else key
for x in glob.glob(abskey):
if x.endswith(filename):
cfg = config[key].get()
res.update(cfg)
for frequency in cfg:
if frequency_folder_days(frequency) is None:
logger.error("Invalid configuration attribute '%s'" % key)
exit(1)
res['pattern'] = key
return res
@click.command(context_settings=dict(help_option_names=['-h', '--help']),
help=('Keep rotated time-spaced archives of files. FILES names must match one of '
' the patterns present in %s.' % CONFIG_PATH),
epilog=('See https://github.com/Kraymer/cronicle/blob/master/README.md#usage for '
'more infos'))
@click.argument('filenames', type=click.Path(exists=True), metavar='FILES', nargs=-1)
@click.option('-r', '--remove', '_remove',
help='Remove previous file backup when no symlink points to it.',
default=False, is_flag=True)
@click.option('-d', '--dry-run', count=True,
help='Just print instead of writing on filesystem.')
@click.option('-v', '--verbose', count=True)
@click.version_option(__version__)
def cronicle_cli(filenames, _remove, dry_run, verbose):
set_logging(max(verbose, dry_run))
if dry_run: # disable functions performing filesystem operations
globals().update({func: lambda *x: None for func in ('remove', 'symlink', 'unlink')})
for filename in filenames:
filename = path.abspath(filename)
cfg = find_config(filename)
logger.debug('Config is %s' % cfg)
if not cfg:
logger.error('No pattern found in %s that matches %s.' % (
CONFIG_PATH, filename))
exit(1)
for ffolder in [x.upper() for x in set(cfg.keys()) - set(['pattern'])]:
timed_symlink(filename, ffolder, cfg)
for ffolder in [x.upper() for x in set(cfg.keys()) - set(['pattern'])]:
rotate(filename, ffolder, _remove, cfg)
if __name__ == "__main__":
cronicle_cli()
<file_sep>#!/usr/bin/env python
import os
import unittest
from cronicle import find_config, config
RSRC = os.path.join(os.path.realpath(os.path.dirname(__file__)), 'rsrc')
FILENAME = '%s/prefix_01_suffix.ext' % RSRC
config.add({
RSRC + '/prefix_*_suffix.ext': {'daily': 1}})
class Test(unittest.TestCase):
def test_find_config_ok(self):
res = find_config('rsrc/prefix_01_suffix.ext', config)
self.assertEqual(res['daily'], 1)
def test_find_config_ko(self):
res = find_config('rsrc/prefix_01_suffix', config)
self.assertEqual(res, None)
<file_sep>from . import confit
config = confit.LazyConfig('cronicle', __name__)
<file_sep>click
ordereddict
pyyaml
six
tox
python-dateutil
|
0198abbbf639281e877d5755b2d9d8f7c09ebd25
|
[
"Markdown",
"Python",
"Text"
] | 5
|
Markdown
|
501st-alpha1/cronicle
|
684ae55632a313e871409edf4832c136e36c8ac1
|
7a99974d622487e153aaf98e5ee79920e96fb996
|
refs/heads/master
|
<file_sep>package asu.turinggeeks.controller;
import static asu.turinggeeks.configuration.SessionAttributes.ATTR_OAUTH_ACCESS_TOKEN;
import static asu.turinggeeks.configuration.SessionAttributes.ATTR_OAUTH_REQUEST_TOKEN;
import static org.springframework.web.context.request.RequestAttributes.SCOPE_SESSION;
import org.scribe.model.OAuthRequest;
import org.scribe.model.Response;
import org.scribe.model.Token;
import org.scribe.model.Verb;
import org.scribe.model.Verifier;
import org.scribe.oauth.OAuthService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.context.request.WebRequest;
import org.springframework.web.servlet.ModelAndView;
import asu.turinggeeks.configuration.OAuthServiceProvider;
@Controller
public class FacebookController {
@Autowired
private OAuthServiceProvider facebookServiceProvider;
private static final Token EMPTY_TOKEN = null;
@RequestMapping(value={"/facebook"}, method = RequestMethod.GET)
public String login(WebRequest webRequest) {
Token accessToken = (Token) webRequest.getAttribute(ATTR_OAUTH_ACCESS_TOKEN, SCOPE_SESSION);
if(accessToken == null) {
OAuthService service = facebookServiceProvider.getService();
webRequest.setAttribute(ATTR_OAUTH_REQUEST_TOKEN, EMPTY_TOKEN, SCOPE_SESSION);
return "redirect:" + service.getAuthorizationUrl(EMPTY_TOKEN);
}
return "success";
}
@RequestMapping(value={"/facebook-callback"}, method = RequestMethod.GET)
public ModelAndView callback(@RequestParam(value="code", required=false) String oauthVerifier, WebRequest webRequest) {
OAuthService service = facebookServiceProvider.getService();
Token requestToken = (Token) webRequest.getAttribute(ATTR_OAUTH_REQUEST_TOKEN, SCOPE_SESSION);
Verifier verifier = new Verifier(oauthVerifier);
Token accessToken = service.getAccessToken(requestToken, verifier);
webRequest.setAttribute(ATTR_OAUTH_ACCESS_TOKEN, accessToken, SCOPE_SESSION);
OAuthRequest oauthRequest = new OAuthRequest(Verb.GET, "https://graph.facebook.com/me");
service.signRequest(accessToken, oauthRequest);
Response oauthResponse = oauthRequest.send();
System.out.println(oauthResponse.getBody());
ModelAndView mav = new ModelAndView("redirect:login");
return mav;
}
}<file_sep>app.config.oauth.facebook.apikey=806255789500708
app.config.oauth.facebook.apisecret=9c29d57ff0620aee9770aca68ca3d797
app.config.oauth.facebook.callback=http://localhost:8080/meetme/loginSuccess
app.config.oauth.twitter.apikey=<KEY>
app.config.oauth.twitter.apisecret=<KEY>
app.config.oauth.twitter.callback=http://localhost:8080/meetme/loginSuccess<file_sep># MeetMe
This is the target repository for the SER515 MeetMe SCORE project
1. _parser_base_main.py_ - This module is the output of the grako parser generation which has two classes MyParser and MySemantics. MySemantics class is overridden to traverse the tree and implement customized handling for translation phase. MyParser is used to instantiate a parser and parse the input with help of the customized MySemantics.
2. _exp_parser.py_ – The module has a class ExpSemantics and a global function translate().
3. **ExpSemantics** - Overrides functions corresponding to each rulein the grammar from MySemantics class which are used which enables the parser to use custom semantics. The functions in ExpSemantics class can be used to modify the AST to format it and are subject to interpretation in model module e.g. CleanUp in some functions is necessary to get rid of all the blank statements and redundant members.
4. **Translate()**
5. Instantiates a Parser generated from grako.
6. Runs the preprocessor to make the input file provided from input parameter to make it compatible with the Parser.
7. The Parser object has the custom Semantics passed to it which enables it to use the custom semantics.
8. Writes processed input to the output file.
### TRANSLATOR
The translator is the stage where the semantics come into the picture as the syntax analysis is done until the AST is generated. The tree is traversed in a DFS manner and each node in the AST interpreted according to the Semantics class provided (ExpSemantics here for lists2helix) and ultimately as the root is reached collective output of all the nodes below can be processed to produce the translated lists python code.
The translation phase using Grako can be summarized in the following steps:
1. Create a PEG grammar that represents the syntax to be parsed. A Parser and a Semantics class is generated based on the input grammar by grako.
2. Use the class Parser generated by Semantics class.
3. Define a custom Semantics class which implements functions corresponding to each rule that take input as AST and returns its interpretation.
4. Define a custom class corresponding to each rule which has a template and subclasses Model.Renderer. This class is used by Semantics class functions to interpret the input AST and returns the interpretation to the next rule.
Some of the prominent features of the translation phase are as follows:
1. **Variable resolution**
2. The variable resolution is done in the functions process_var() of the BaseStartStmt class and check_var_usage() function of class start for parent files and process_var_libl*() and constructor of class libl_start for included lists or libls.
3. The variables are either defined or referred to somewhere in the code which makes the semantics specific to
4. Variable Definition
5. Variable Reference
6. Variable Scope Validation
7. **Variable Definition**
8. Variable definition is mainly done by a declare statement in the TestMgr List syntax.
9. Variable definition however in Python needs the context and hence the resolution of the context to be used is deferred.
10. To signify that a particular variable is defined, the variable is prefixed with “$@var_def”. This is done in the constructor of expression. The LHS variable is the only one which is prefixed with aforementioned prefix. Moreover, nodes which are indexed are also prefixed and replaced with the context later at the root node.
11. The variable is resolved later as the traversal reaches the root node where the processing is aware if the particular statement is in setup, testcase or teardown section. Hence, the prefix $@var_def is replaced with its context.
12. Context resolution is done by following replacement :
13. **Testcase** –
14. **$@var_def** = self.(nodes) Or no context(for variables )
15. **Setup** -
16. **$@var_def** = cls.env.(nodes) Or cls. (for variables)
17. **Teardown** –
18. **$@var_def** = cls.env.(nodes) Or cls. (for variables)
19. **Teardown** –
20. **$@var_def** = cls.env.(nodes) Or cls. (for variables)
21. Included files –
22. All variables are local and no context prefix is prepended.
23. Nodes – env.nodes[]
2. **Variable Reference** –
3. A “name” in the lists syntax grammar denotes the use of a variable. Therefore, when it is interpreted, a $@var_ prefix is added to denote that it’s a variable for later processing.
4. Therefore, all the variables used in the lists have a prefix $@var_ which are then resolved at the root when the context is known thus replacing the prefix with the context.
5. The function find_replace_var() in class BaseStartStmt also parse the RHS of an assignment statement and command of task statement for variable references as they cannot be parsed into strings readily from the grammar.
6. Such cases of variable reference are prefixed with $@replace_ and are replaced by the context according to the sections they are present in.
7. **Variable Scope Validation** –
8. We assume that the Test list should successfully run with the TestMgr framework and hence it is implied that there will not be any variable reference which is not defined. Such a case can still occur if an invalid test case is used, the invalid variable references are checked against variables being maintained in a dictionary. These maintained variables are defined in included files and in current local scope and are stored as soon as they are defined.
9. The scope of TestMgr List is global provided the included files also have scope listed as global. Therefore, making this compatible with Python unit test cases and python scope rules, every time a list or libl is included in global scope in Test lists, the current file’s globals dictionary has to be updated with all the included lists variables and local variables defined in the included list or libl.
10. Therefore following functions and class are relevant to this functionality –
11. **read_include_symtable()**
12. **write_sym_table()**
13. **RegPatternInclude().process_var()**
14. **Handling Include Lists and libls**
15. The handling of included lists and libls requires a different starting point in the grammar as the format of the included libls and lists does not have setup, teardown and testcase sections. Hence, the rule libl_start deals with the start rule of libl and lists included in the test lists.
16. Include statements are interpreted and translated to prefix #$@read_include_var@<file_to_include> to indicate that a file has been included for later processing.
17. However, include statements are handled with the help of the function handle_include_stmt() from the class included.
18. The handle_include_stmt() function is similar to translate function in the exp_parser module. It creates a Parser object and passes the custom Semantics class ExpSemantics but the start rule is different which is libl_start.
19. So essentially, it resembles a depth first processing where if an include statement is encountered the processing of the present file is suspended until the processing of the included file is complete and the same applies for included files as well. Thus it handles recursive inclusion of files very well.
20. Following depicts the processing graphically.
##IMAGE
21. **Tasks execution**
22. The TestMgr framework has task statements which involve a certain command being executed on a set of clients or nodes. These tasks have specific variables like stdout, stderr, last_pid, etc. which are readily available for use.
23. However, Helix framework does not have these “special” variables readily available. One solution is to maintain all the tasks in variables but that would make the translated code ugly and therefore, it is necessary to maintain the last executed task at every statement.
24. This enables the translator to prepend the last executed task statement with a variable assignment “proc = ” whenever it comes across a special variable like stdout, stderr, lastpid, etc.
25. The ifStmt , however, can apply this strategy only in its block of code. If the variable reference is outside the ifElse blocks of code and the last executed task is in both the blocks of if and else statements, then each of the last task executed in both the blocks are prepended with “proc = ” variable assignment. This is done as it is impossible to decide which of the blocks will get executed at compile time.
26. The processing to maintain the last executed task takes place in the check_var_usage() and libl_start constructor function.
27. check_var_usage() – for parent file.
28. libl_start() - for included files.
### ADDING FUNCTIONALITY TO EXISTING CODE
Adding functionality to the existing code base is an impending task as there is a possibility that the new things should be added in future. With this consideration, here are some cases and corresponding suggested ways in which specific things can be added –
1. **Add Special Variable handling ** - – Special variables like stdout, stderr, etc. (A list can be found on the taskmgr syntax documentation under title “variable substitution”) which require special handling can be added by making a class and implementing the function handle_var() in it. **Module – variable_handle.py.**
2. In the Variable_Handle class, subclass BaseVariableHandle class and implement a function handle_var() in it which will return the desired value of the variable in the translated code e.g. stdout = proc.stdout.
3. Add the variable name and its class instantiation as a key,value pair in the dictionary var_map_out in init function of Variable_Handle class.
4. **Add new Node class variable handling** – Node class variables like linux, windows, nodes, client, etc. are handled in the class NodeHandle. The BaseNodeHandle class is the base class which is to which has the structure of a new node class variable.
5. Add a new class which denotes the new class variable by subclassing the BaseNodeHandle.
6. Add the supposed processed name for the name as a key, value pair in VAR_MAP dictionary.
7. Add the name of node variable and its class instantiation to var_class dictionary in NodeHandle class.
7. **Add new rule to the grammar** -
8. Add the new rule to the grammar and try to compile it with grako to ensure that there are no errors in the added grammar.
9. After successful compilation, a new parser is generated which is important to use as using the previously generated parser, it will not reflect the change made in the grammar.
10. Add a function corresponding to the rule in the class ExpSemantics. The function will instantiate an object which corresponds to a class in model.py module.
11. Add a class corresponding to the rule in model.py which subclasses Model class. This subclass of Model is supposed to have a render_fields method and an interpretation of the input AST such that a translated output is recorded while instantiating the object.
12. **Add new regular expression parsing** – There can be a requirement where new markers have to be introduced to signify that the processing of that particular entity cannot be done at the current moment and have to be deferred.
13. Add a class in **reg_exp_module.py** which represents the regular expression to be used to parse.
14. Add the class to reg_pattern dictionary and hence the factory method will be able to find it.
### OVERVIEW OF INDICATORS/MARKERS USED INTERNAL TO TRANSLATION
There are some directives used to allow the translator to take some actions to produce the desired output, when it is processing at the root. Following is a brief account of all such directives used. As we format the output at each level of the tree traversal
1. **$@var_def** – used for variable definitions in order to signify to the translator that a context has to be applied in place of the $@var_def if the variable it is prepended to is available in the maintained variable dictionary. It is also used to denote node addressing irrespective of whether they are indexed or not. Nodes or clients in tasks statements also have context to be replacement of $@var_def prefix.
e.g. $@var_defa = 1 => cls.a = 1 (Setup/ Teardown section)
$@var_defnode[0] => cls.env.node[0] (Setup/ Teardown section)
2. **$@var_** – used for variable references and definitions. In case of definitions, it is replaced by $@var_def. It is also replaced with its context prefix while translation.
e.g. $@var_somevariable = 1 => somevariable = 1 (testcase)
3. **$@replace_** – The variables used in strings in RHS or command of task statements are parsed and prefixed by $@replace_ to be replaced later by the context prefix.
“$$variable is $$value” => “{variable} is {value}”.format(**)
4. **$@ifdefined_** – used for operator “||=” so that the translated code has the variable check if it is defined in locals() or not while processing it later.
5. **#@read_include_var@** – This directive takes care of include statements. Whenever an include statement is encountered, the processing at root node(start rule) is indicated to read all the variables from the included file to ensure strict scope validation of the variables.
6. **#$@decorate_** – There are some statements like hardware(--hardware), etc. which form as a decorator in the helix framework. Moreover, the decorators can be added only when we are aware that the current processing corresponds to Setup, teardown or testcase rule. Therefore, it is at the processing of start rule we put decorators as we come across this directive.
7. **@task** – A task statement is denoted by @task prefix in the task_stmt grammar rule interpretation. It is useful to maintain the last executed task to format it when a special variable(stdout, stderr, lastpid) is encountered.
8. **@$lookup** – Lookup is used to identify the context of a processing section in the check_var_usage() function.
### FLOW CHART
Parsers do not have a definite flow chart as it completely depends on the AST it is traversing. However, different functions corresponding to grammar rules are called by Grako through _call(), _invoke_rule, and rule() functions.
2.
3.
4.
5.
6.
7.
8.
4.
a.
b.
a.
b.
2.
a.
b.
c.
3.
a.
b.
c.
d.
4. Add new regular expression parsing – There can be a requirement where new markers have to be introduced to signify that the processing of that particular entity cannot be done at the current moment and have to be deferred.
a. Add a class in reg_exp_module.py which represents the regular expression to be used to parse.
b. Add the class to reg_pattern dictionary and hence the factory method will be able to find it.
|
f1f3c0e88c82218bf479cb8519f582fc2b593d2c
|
[
"Markdown",
"Java",
"INI"
] | 3
|
Java
|
prafull1249/MeetME_webApplication
|
55cbfdcc4b725573d9fd5356923dc5a094cd2487
|
9d5de04fabc6da70c62b7c2cd8de9c5ea22043b4
|
refs/heads/main
|
<file_sep>const express = require('express')
const mongoose = require('mongoose')
const jwt = require('jsonwebtoken')
const { jwtkey } = require('../keys')
const router = express.Router();
const User = mongoose.model('User');
const Meal = mongoose.model('Meal');
router.post('/signup', async (req, res) => {
const { email, password, age, height, weight } = req.body;
try {
const user = new User({ email, password, age, height, weight });
await user.save();
console.log("worked")
res.status(204).send()
} catch (err) {
return res.status(422).send(err.message)
}
})
router.post('/signin', async (req, res) => {
const body = req.body
if (!body.email || !body.password) {
return res.status(422).send({ error: "must provide email or password1" })
}
const user = await User.findOne({ email: body.email })
if (!user) {
return res.status(422).send({ error: "must provide email or password2" })
}
if (!user) {
return res.status(422).send({ error: "must provide email or password3" })
}
try {
await user.comparePassword(body.password, user.password);
const token = jwt.sign({ userId: user._id }, jwtkey)
res.send({ token: token, email: user.email, age: user.age, height: user.height, weight: user.weight, _id: user._id })
} catch {
return res.status(422).send({ error: "must provide email or password4" })
}
})
router.post('/addFood', async (req, res) => {
const { name, calories, date, mealtype, userId } = req.body;
try {
const meal = new Meal({ name, calories, date, mealtype, userId });
await meal.save();
console.log("worked")
res.status(204).send()
} catch (err) {
return res.status(422).send(err.message)
}
})
router.get('/meals/:userId', async (req, res) => {
const userId = req.params.userId;
const todayFirstHour = new Date();
const todayLastHour = new Date();
const addTwoHours = 2 * 60 * 60 * 1000;
todayFirstHour.setHours(0, 0, 0, 0);
todayLastHour.setHours(23, 59, 59, 999);
todayFirstHour.setTime(addTwoHours + todayFirstHour.getTime());
todayLastHour.setTime(addTwoHours + todayLastHour.getTime());
Meal.find({
$and: [
{
date: {
$gte: todayFirstHour,
$lt: todayLastHour
}
},
{
userId: userId
}
]
}).then((meals) => {
res.status(200).json({
meals: meals
})
});
})
router.get('/history/:userId', async (req, res) => {
const userId = req.params.userId;
const today = new Date();
const lastDayLastHour = new Date();
const oneWeekAgo = new Date();
const weekInMilliseconds = 7 * 24 * 60 * 60 * 1000;
lastDayLastHour.setHours(0, 0, 0, 0);
lastDayLastHour.setTime(lastDayLastHour.getTime() - 60 * 60 * 1000)
oneWeekAgo.setTime(oneWeekAgo.getTime() - weekInMilliseconds);
Meal.find({
$and: [
{
date: {
$gte: oneWeekAgo,
$lt: lastDayLastHour
}
},
{
userId: userId
}
]
}).then((meals) => {
console.log(meals)
res.status(200).json({
meals: meals
})
})
;
})
module.exports = router<file_sep>module.exports={
mongoUrl:"mongodb+srv://marian123:585149@cluster0.9vjqk.mongodb.net/<dbname>?retryWrites=true&w=majority",
jwtkey:"asadsafwafa"
}<file_sep>
import React from 'react';
import { View, Text, StyleSheet, ScrollView } from 'react-native';
import AsyncStorage from '@react-native-community/async-storage';
class HistoryScreen extends React.Component {
constructor(props) {
super(props)
this.state = {
meals: []
}
}
async componentDidMount() {
let user = await AsyncStorage.getItem("user_id");
user = JSON.parse(user);
fetch('http://192.168.43.47:3000/history/' + user.id, {
method: 'GET',
})
.then((response) => {
response.json().then((object) => {
this.setState({
meals:object.meals
})
})
})
.catch((err) => console.log(err))
}
render() {
return <ScrollView style={styles.container}>
{
this.state.meals.map((meal) => {
return (<View key={meal._id} style={styles.meal} >
<Text style={styles.mealName}>Meal name:{meal.name}</Text>
<Text style={styles.mealCalories}>Meal calories:{meal.calories}</Text>
<Text style={styles.mealCalories}>Date:{meal.date.toString().substr(0,16)}</Text>
</View>)
})
}
</ScrollView>
}
};
export default HistoryScreen;
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
},
text: {
fontSize: 30,
width: '100%',
borderWidth: 3,
color: 'white',
paddingLeft: 10,
fontWeight: 'bold',
borderColor: '#6067A8'
},
itemsContainer: {
display: 'flex',
backgroundColor: '#6067A8',
width: '80%',
marginLeft: '10%',
marginTop: 20
},
textButton: {
textAlign: 'center',
paddingTop: 10,
fontSize: 20,
fontWeight: 'bold',
color: 'black'
},
button: {
width: '20%',
backgroundColor: '#BCC2F5',
},
meal: {
backgroundColor: 'pink',
margin: 10,
borderRadius: 8,
},
mealName: {
color: 'black',
fontSize: 15,
padding: 5,
fontWeight: 'bold'
},
mealCalories: {
color: 'black',
fontSize: 15,
padding: 5,
fontWeight: 'bold'
}
});<file_sep>import React, { useState, createRef } from 'react';
import DropDownPicker from 'react-native-dropdown-picker';
import AsyncStorage from '@react-native-community/async-storage';
import {
StyleSheet,
TextInput,
View,
Text,
Image,
KeyboardAvoidingView,
Keyboard,
TouchableOpacity,
ScrollView,
} from 'react-native';
import Loader from '../Components/Loader';
const AddFoodScreen = (props) => {
const [name, setMealName] = useState('');
const [calories, setMealCalories] = useState('');
const [mealtype, setMealType] = useState('');
const [loading, setLoading] = useState(false);
const [errortext, setErrortext] = useState('');
const [
isSuccess,
setIsSuccess
] = useState(false);
const nameInputRef = createRef();
const caloriesInputRef = createRef();
const mealtypeInputRef = createRef();
const handleSubmitButton = () => {
setErrortext('');
if (!name) {
alert('Please fill Food Name');
return;
}
if (!calories) {
alert('Please fill number of calories');
return;
}
setLoading(true);
AsyncStorage.getItem("user_id").then((user) => {
user = JSON.parse(user);
fetch('http://192.168.43.47:3000/addFood', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({
"name": name,
"calories": calories,
"mealtype": mealtype.value,
"date": new Date(),
"userId": user.id
}),
})
.then((response) => {
if (response.status === 204) {
fetch('http://192.168.43.47:3000/meals/' + user.id, {
method: 'GET',
})
.then((response) => {
response.json().then((object) => {
AsyncStorage.setItem(
'meals', JSON.stringify(object.meals)
).then(() => {
setIsSuccess(true);
});
})
})
.catch((err) => console.log(err))
} else {
setErrortext('Unsuccessfully');
setLoading(false);
}
})
.catch((error) => {
setLoading(false);
console.error(error);
});
})
};
if (isSuccess) {
return (
<View
style={{
flex: 1,
backgroundColor: '#307ecc',
justifyContent: 'center',
}}>
<Image
source={require('../../Image/success.png')}
style={{
height: 150,
resizeMode: 'contain',
alignSelf: 'center'
}}
/>
<Text style={styles.successTextStyle}>
Meal added Successfullly
</Text>
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={() => {
setIsSuccess(false);
props.navigation.navigate('HomeScreen', {})
}}>
<Text style={styles.buttonTextStyle}>Home</Text>
</TouchableOpacity>
</View>
);
}
return (
<View style={{ flex: 1, backgroundColor: '#307ecc' }}>
<Loader loading={loading} />
<ScrollView
keyboardShouldPersistTaps="handled"
contentContainerStyle={{
justifyContent: 'center',
alignContent: 'center',
}}>
<View style={{ alignItems: 'center' }}>
<Image
source={require('../../Image/aboutreact.png')}
style={{
width: '50%',
height: 100,
resizeMode: 'contain',
margin: 30,
}}
/>
</View>
<KeyboardAvoidingView enabled>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={
(Name) => setMealName(Name)
}
underlineColorAndroid="#f000"
placeholder="Enter Meal Name"
placeholderTextColor="#8b9cb5"
ref={nameInputRef}
returnKeyType="next"
onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={false}
/>
</View>
<View style={styles.SectionStyle}>
<TextInput
style={styles.inputStyle}
onChangeText={
(Calories) => setMealCalories(Calories)
}
placeholder="Enter Calories"
placeholderTextColor="#8b9cb5"
keyboardType="default"
ref={caloriesInputRef}
onSubmitEditing={Keyboard.dismiss}
blurOnSubmit={false}
underlineColorAndroid="#f000"
returnKeyType="next"
/>
</View>
<View style={styles.SectionStyle}>
<DropDownPicker
items={[
{ label: 'Breakfast', value: 'breakfast' },
{ label: 'Lunch', value: 'lunch' },
{ label: 'Dinner', value: 'dinner' },
]}
defaultValue="breakfast"
containerStyle={{ height: 40 }}
dropDownStyle={{ backgroundColor: '#307ecc' }}
onChangeItem={(Mealtype) => setMealType(Mealtype)}
itemStyle={{
height: 20
}}
style={{
width: 340,
borderRadius: 20,
backgroundColor: '#307ecc',
borderTopLeftRadius: 10, borderTopRightRadius: 10,
borderBottomLeftRadius: 10, borderBottomRightRadius: 10
}}
labelStyle={{
textAlign: 'left',
color: 'white'
}}
dropDownStyle={{
borderBottomLeftRadius: 20, borderBottomRightRadius: 20,
backgroundColor: '#307ecc',
}}
/>
</View>
{errortext != '' ? (
<Text style={styles.errorTextStyle}>
{errortext}
</Text>
) : null}
<TouchableOpacity
style={styles.buttonStyle}
activeOpacity={0.5}
onPress={handleSubmitButton}>
<Text style={styles.buttonTextStyle}>
SUMBIT
</Text>
</TouchableOpacity>
</KeyboardAvoidingView>
</ScrollView>
</View>
);
}
export default AddFoodScreen;
const styles = StyleSheet.create({
SectionStyle: {
flexDirection: 'row',
height: 40,
marginTop: 20,
marginLeft: 35,
marginRight: 35,
margin: 10,
},
buttonStyle: {
backgroundColor: '#7DE24E',
borderWidth: 0,
color: '#FFFFFF',
borderColor: '#7DE24E',
height: 40,
alignItems: 'center',
borderRadius: 30,
marginLeft: 35,
marginRight: 35,
marginTop: 20,
marginBottom: 20,
},
buttonTextStyle: {
color: '#FFFFFF',
paddingVertical: 10,
fontSize: 16,
},
inputStyle: {
flex: 1,
color: 'white',
paddingLeft: 15,
paddingRight: 15,
borderWidth: 1,
borderRadius: 30,
borderColor: '#dadae8',
},
errorTextStyle: {
color: 'red',
textAlign: 'center',
fontSize: 14,
},
successTextStyle: {
color: 'white',
textAlign: 'center',
fontSize: 18,
padding: 30,
},
});
|
5cf006b423cd86ab490c1282da2bf6a5ed4e5065
|
[
"JavaScript"
] | 4
|
JavaScript
|
marianharalamb98/Calorie-Tracking
|
b6c8d073e9b9f1a9e1526f036a709aca07236d9b
|
b9af93d7132a63eeac9bf64ea4e9748fee76470d
|
refs/heads/master
|
<repo_name>jayArnel/meme-generator-nodejs<file_sep>/static/js/meme_generator.js
$(document).ready(function() {
var canvas = document.getElementById('preview');
canvas.width = 1000;
canvas.height = 700;
var ctx;
var memeImg;
var title = "";
var subtitle = "";
function initContext() {
ctx = canvas.getContext('2d');
ctx.font = '50px Impact'
ctx.fillStyle = '#FFF'
ctx.strokeStyle = '#000'
ctx.textAlign="center";
}
initContext();
drawMeme();
$('.text label').click(function() {
var parent = $(this).parent();
var input = parent.find('input');
$(input).focus();
});
$('#download').on('click', function() {
this.href = document.getElementById('preview').toDataURL('image/jpeg');
this.download = 'meme.jpeg';
});
$('.upload').on('click', function(e) {
$('#upload-meme').trigger('click');
});
$('#upload-meme').on('change', function (e) {
var reader = new FileReader();
ctx.clearRect(0, 0, canvas.width, canvas.height);
reader.onload = function(event){
memeImg = new Image();
memeImg.onload = function(){
if (!isCanvasBlank(canvas) || !(title.length == 0 && subtitle.length == 0) ) {
$('#download').removeAttr('hidden');
console.log(title.length, subtitle.length);
} else {
$('#download').attr('hidden', true);
}
drawMeme();
}
memeImg.src = event.target.result;
}
reader.readAsDataURL(e.target.files[0]);
});
// updating text
$('.title input[type="text"]').on('keyup', function() {
title = $(this).val();
subtitle = $('.subtitle input[type="text"]').val();
if (!isCanvasBlank(canvas) || !(title.length == 0 && subtitle.length == 0) ) {
$('#download').removeAttr('hidden');
} else {
$('#download').attr('hidden', true);
}
ctx.clearRect(0,0, canvas.width, canvas.height);
drawMeme();
});
$('.subtitle input[type="text"]').on('keyup', function() {
subtitle = $(this).val();
title = $('.title input[type="text"]').val();
if (!isCanvasBlank(canvas) || !(title.length == 0 && subtitle.length == 0) ) {
$('#download').removeAttr('hidden');
console.log(title.length, subtitle.length);
} else {
$('#download').attr('hidden', true);
}
ctx.clearRect(0,0, canvas.width, canvas.height);
drawMeme();
});
function drawMemeImage() {
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
if (memeImg) {
canvas.height = memeImg.height;
canvas.width = memeImg.width;
initContext();
ctx.fillStyle = "white";
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(memeImg,0,0);
}
}
function drawTitle(context, text, x, y, maxWidth, lineHeight) {
try {
var words = text.split(' ');
var line = '';
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, y);
context.strokeText(line, x, y);
line = words[n] + ' ';
y += lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
context.strokeText(line, x, y);
} catch(err) {
return null;
}
}
function drawSubtitle(context, text, x, y, maxWidth, lineHeight) {
try {
var words = text.split(' ');
var line = '';
var topLineY = y - lineHeight;
for(var n = 0; n < words.length; n++) {
var testLine = line + words[n] + ' ';
var metrics = context.measureText(testLine);
var testWidth = metrics.width;
if (testWidth > maxWidth && n > 0) {
context.fillText(line, x, topLineY);
context.strokeText(line, x, topLineY);
line = words[n] + ' ';
topLineY -= lineHeight;
} else {
line = testLine;
}
}
context.fillText(line, x, y);
context.strokeText(line, x, y);
} catch(err) {
return null;
}
}
function isCanvasBlank(cnvs) {
var blank = document.createElement('canvas');
blank.width = cnvs.width;
blank.height = cnvs.height;
return cnvs.toDataURL() == blank.toDataURL();
}
$('#clear').on('click', function(e) {
e.preventDefault();
ctx.clearRect(0,0, canvas.width, canvas.height);
$('.title input[type="text"]').val('');
$('.subtitle input[type="text"]').val('');
$('#download').attr('hidden', true);
title = "";
subtitle = "";
});
function drawMeme() {
drawMemeImage();
drawTitle(ctx, title, (canvas.width / 2), 65, canvas.width, 45);
drawSubtitle(ctx, subtitle, (canvas.width / 2), (canvas.height - 35), canvas.width, 45);
}
});
|
1668d5d1091686fe7d4787086ea5398217def194
|
[
"JavaScript"
] | 1
|
JavaScript
|
jayArnel/meme-generator-nodejs
|
6d2f2b867732ce550e15ab2ad00328cdb92d834b
|
ec0855fbeda468e6f2aa2a8fe217377c5f1c96ca
|
refs/heads/master
|
<repo_name>mcgagnier/linux-lesson-plan<file_sep>/db/getUsersByFirst.sql
SELECT * FROM users
WHERE first = ${first};
<file_sep>/index.js
const express = require('express');
const fs = require('fs');
const path = require('path');
const axios = require('axios');
const CronJob = require('cron').CronJob;
const massive = require('massive')
const bodyParser = require('body-parser')
require('dotenv').config()
var connectionString = process.env.connectionString;
const app = express();
app.use(bodyParser.json())
//indexing
massive(connectionString).then(massiveInstance => {
app.set('db', massiveInstance);
})
//
//
//
// process.argv.forEach((val, index, array) => {
// if(val === 'write-to-demo-linux') {
// //File writing use case #2
// //This allows us to write to an existing file
// // var stream = fs.createWriteStream("demoLinux.txt", {flags:'a'});
// // stream.write('I am adding to the file')
// // stream.end();
// var stream = fs.createWriteStream("starwarsperson.txt", {flags:'a'});
// stream.write('I am adding to the file')
// stream.end();
// }
// })
//
// //File writing use case #1
// //Make a call to a third party api, and write results to a text file
// //If this file doesn't exist, then writeFile will create it
// //This method will overwrite all contents of a file if it exists so be careful
//
// //Scenario
// //I make a call to a server that's been adding my star wars users to their database. I make a call everynight and need to write this to a file to be process in the morning by me
// axios.get('https://swapi.co/api/people/1/').then(person => {
// if(person.data) {
// let rightNow = new Date();
// let personText = `This is my person ${person.data.name} and this is the time it was retrieved ${rightNow}`;
// fs.writeFile('starwarsperson.txt', personText, (err) => {
// // throws an error, you could also catch it here
//
// if (err) throw err;
// });
// }
// }).catch(err => {
// fs.writeFile('starwarsperson.txt', err, (error) => {
// // throws an error, you could also catch it here
// if (error) throw error;
// });
// })
//
// // Chron tasks
// //Runs every second
// new CronJob('* * * * * *', () => {
// console.log('You will see this message every second')
// }, null, true)
//
// //runs every 30 seconds
// new CronJob('30 * * * * *', () => {
// console.log('You will see this message every 30 seconds')
// }, null, true)
//
// //runs every 30 minutes
// new CronJob('00 30 * * * *', () => {
// console.log('You will see this message every 30 minutes')
// }, null, true)
//
// //runs every weekday at 10:15
// new CronJob('00 15 10 * * 1-5', () => {
// console.log('You will see this message every weekday at 10:15')
// }, null, true)
//
// //Example of using cron to go in and delete files
// //will run every night at 2
// new CronJob('10 * * * * *', () => {
// console.log('Starting the cron task')
// var directory = './garbage'
// fs.readdir(directory, (err, files) => {
// if (err) throw err;
//
// for (const file of files) {
// console.log('getting inside for looop')
// fs.unlink(path.join(directory, file), err => {
// if (err) throw err;
// var filePath = `./garbage/${file}`
// fs.closeSync(fs.openSync(filePath, 'w'))
// });
//
// }
// console.log('Finished deleting files')
// });
// }, null, true)
//Routes
app.get('/api/users', (req, res) => {
var db = app.get('db');
console.log(req.query)
if(req.query.first) {
var first = req.query.first;
}
var date1 = new Date();
db.getUsersByFirst({first}).then(users => {
var date2 = new Date();
var diff = date2 - date1;
console.log('difference in millisenconds', diff)
res.status(200).send(users)
})
})
app.listen(3000, () => {
console.log('listening on port 3000')
})
<file_sep>/indexing.js
//What is indexing on a database?
//When I have a column in a database, say a first name column, that column may be 50 characters long per record. These records are not going to be unique and neither will they be sorted according to their binary values. So, in order to find all matching occurences of the name 'Zach' in a table in that column, the database much search through every single record. If I have 5 million records in a table, it must search all 5 million records to decide that there are only 15 instances of 'Zach' in the entire table.
//Indexes aim to solve this problem. I can create an index on the first name column and drastically reduce the amount of time that it takes to search a column. if I create an index on firstName with the first 4 characters, the database will create another table behind the scenes that is an binary orded column of the first 4 characters in the first name column.
//Example
//'ange'
//'arty'
//....
//'zach'
//'zack'
//Now, the next time that I go to search this table's first name column, and I ask for all records of 'Zach', it jumps to the first instance of 'Zach', goes until it not longer has a match and knows that there are no further matches in the table. It may only search through 100 records instead of 5 million. This is why indexing can speed up the process so much.
//The downside of indexing is that it takes 1. physical space on the disk to create the indexed table and 2. it takes longer to write a new record to the table for each indexed column because it must not only write the record to the original table, but then has to go write it to the indexed table and reorganize that table
//Show examples of using databse indexes using postgresql and index.js and logging out times
<file_sep>/cron.js
//What is cron?
//It is a program in Unix that is used to execute commands or scripts automatically at a specified time/date.
//When to use a cron task?
//You may want to do an automatic email check from a piece of software you are working on and run it every 5 minutes. Or you might want to run a file clean up script that deletes garbage files every night. or every 3 days. Or maybe you are syncing data with an external database through a third party api, and instead of manually going and running that script every 15 minutes you want it to run automatically.
//Go to index.js for chron tasks
<file_sep>/toy-problems/buildTower/solution.js
function towerBuilder(nFloors) {
// build here
var character = '*'
var building = []
for(var i = nFloors; i > 1; i--) {
character += '**'
}
building.push(character)
var characterArray = character.split('')
var beginningIndex = 0;
var lastIndex = characterArray.length - 1;
for(var i = 1; i < nFloors; i++) {
characterArray[beginningIndex] = ' ';
characterArray[lastIndex] = ' ';
beginningIndex++;
lastIndex--;
var newString = characterArray.join('')
building.unshift(newString)
}
return building;
}
towerBuilder(3)
<file_sep>/notes.txt
1. Start with findSquare toy problem - 15 min
2. Move into linux.js - 30 min
3. move into files.js - 15 min
4. take break - 15 min
5. do buildTower toy problem - 30 min
6. move into indexing.js - 30 min
7. finish with chron.js - 30 min
<file_sep>/linux.js
//What is Linux?
//It is an operating system that is extremely prevalent in society. It runs in phones, cars, supercomputers and stock exchanges. The reason its so popular is because it's one of the most reliable, secure and open source operating systems available.
//Why use Linux?
//Linux is completely free first off. It's open source so you'll never have to pay to use it. It's also very secure. Linux very rarely has issues with malware, viruses or slow downs.
//How does that relate to us?
//Many web servers run Linux for one so you may use Linux at jobs in the future, but the main thing I want to focus on is the terminal for the Mac and Ubuntu for windows. We're familiar with using the command line for basic commands like ls or cd but there are many other extremely useful commands out there that are very helpful to understand how to use.
//Commands
//ls - list files in current directory
//alterations
//ls -a - lists hidden files
//ls -X - lists files in order based on file extensions
//ls -l - list detailed information about files and directories (show permissions)
//Permissions are broken into 4 sections
//- in the first position indicated a file while d indicates a directory
//rwx then comes next, indicating read write and execute permissions for the owner of the file
//rwx comes after with read, write and execute permissions for members of the group owning the file
//Lastly, rwx read write and execute permissions for other users
//read permission refers to users capability to read the contents of a file
//write refers to a users capability to write or modify a file or directory
//execute refers to a users capability to execute a file or view the contents of a directory
//after the permissions you see zs zs
//this referes to the owner:group
//zs is the owner and group
//I could change the owner or the group using chmod
//cd - change directories
//alterations
//cd ~ - takes user to home directory
//cd /usr/local/lib - takes user to absolute path specified
//cd .. -takes a user back one directory
//mv - moves or renames files
//alterations
//mv -T source destination - rename source to destination
//mv source destination - move source file to destination folder
//man -- gives you details about a specific command
//mkdir --creates a directory
//alterations
//mkdir -m a=rwx -sets permissions on newly created file
//rmdir - removes empty directory. Does not work on non empty directory
//rm - used to delete files. by default does not delete directories. use wisely, once a file is deleted it's gone forever.
//alterations
//rm -r - used to delete files recursively, in a directory
//rm -f - do not prompt for permission before removing files
//rm -rf - remove all files recursively in a directory without asking for permission
//touch - creates a file
//clear - clears the termial of input commands
//tail - outputs the last part of a file. by default tail prints the last 10 lines of a file
//alterations
//tail -f - causes tail to loop forever constantly checking for new inputs to the file
//tail -n 40 - outputs the last 40 lines of a file
//grep - processes text line by line and prints any lines which match a specified pattern
//syntax for grep
//grep 'word' filename
//grep 'word' filename filename2
//grep -c 'word' filename (count number of occurences)
//grep -r 'here' ./* or directory name (search recursively for all examples of string in directory)
//cat - simplest way to view text files contents on linux cli
//Example cat
//cat demoLinux.js | grep 'I'
//ps - shows running processes
//break down of ps output
//PID - Process id which identifies the running process
//TTY - Terminal type
//Time - amount of time to run
//Command - command that kicked it off
//Combine ps -A with grep to find a certain command running
//top - very similar to ps but a little more detailed
//pid - process id
//user - user who initiaed process
//pr/ni - "nice" value of process. basically, this is how prioritized this is
//virt/res/shr - all related to memory
//s - current state of process
//cpu/mem - total load on cpu and memory
//time - total cpu time used by the process since it started
//command - name of the process
//kill - used to kill a running process on your system using the pid
//passing arguments via command line to a file
//Show running index.js passing write to demo linux and have it write to the file using fs
<file_sep>/toy-problems/findSquare/solution.js
var isSquare = function(n){
if(n < 0) {
return false;
}
var possibleCommon = findLowestCommon(n)
if(possibleCommon >= 0) {
return true
}
else {
return false;
}
function findLowestCommon(n) {
var lowest = -1;
for(var i = 0; i <= n; i++) {
if(i * i === n) {
lowest = i;
break;
}
}
return lowest;
}
}
|
af12dcdc9ae431d01b6ea3fa997c592c208e1fbe
|
[
"JavaScript",
"SQL",
"Text"
] | 8
|
SQL
|
mcgagnier/linux-lesson-plan
|
06b7d81ea9ed4473eabd3881e1d054540719e489
|
6b106d18a701d7416572d223565ae4e152701864
|
refs/heads/main
|
<file_sep>// File: main.c (For CMSC 412 Homework 2)
// Author: <NAME>
// Date: January 22, 2021
// Purpose: This C Program is designed to create 3 processes using the fork() method, have them wait for child creation, and have each process print their PIDs.
// import necessary C libraries
#include <stdio.h>
#include <sys/wait.h>
#include <unistd.h>
// main() function
int main() {
// Variable initialization
int pid, status;
pid = getpid(); // Process G
// Process creation (P)
switch(fork()) {
// Error checking
case -1:
printf("Fork error: G/P");
break;
// Process P
case 0:
// Process creation (C)
switch(fork()) {
// Error checking
case -1:
printf("Fork error: P/C");
break;
// Process C
case 0:
printf("I am the child process C and my pid is %d. My parent P has pid %d. My grandparent G has pid %d.\n", getpid(), getppid(), pid);
break;
// Process P
default:
wait(&status); // wait for C to finish excecution
printf("I am the parent process P and my pid is %d. My parent G has pid %d.\n", getpid(), pid);
break;
} // end of inner switch
break;
// Process G
default:
wait(&status); // wait for P to finish execution
printf("I am the grandparent process G and my pid is %d.\n", pid);
} // end of outer switch
} // end of main() function
|
e458ed2466221b41cca126408810bf8b50286909
|
[
"C"
] | 1
|
C
|
johnkucera00/CMSC-412-Project-2-ProcessCreator
|
f224ba9b15876049a1f62d5fd9a08c2c2ef46cf1
|
229293c73f6841ec5215aad4aac5a057b2d694ed
|
refs/heads/master
|
<repo_name>kjhg478/simple_board<file_sep>/src/page/post/PostMain.js
import React from 'react';
import PostList from './PostList';
const PostMain = props => {
return (
<>
<h2 align="center">게시판</h2>
<PostList />
</>
)
}
export default PostMain;
|
614811d179c3bb958707d8c59ee9d8d324278482
|
[
"JavaScript"
] | 1
|
JavaScript
|
kjhg478/simple_board
|
a39b93d3a30565fbbe5dcda8958f8444770a4636
|
860bfcc52ce696825d485a35be2c5eb8595417df
|
refs/heads/master
|
<file_sep>#!/bin/bash
docker rm -f deepdream
<file_sep>#!/bin/bash
docker build -t jrlangford/caffe docker/caffe
docker build -t jrlangford/deepdream docker/deepdream
<file_sep>#Deep Dream Docker
This is a docker container that can run Google's [ deepdream ] ( https://github.com/google/deepdream ) repo.
##Start Jupyter
Jupyter is an interactive notebook environment running in a web server.
Google's deepdream is distributed as a python notebook.
```
$ ./run.sh
```
The host's 8888 port is forwarded to Jupyter's UI port so you can access it in the following way:
```
<hostname>:8888
```
Now you can access the `deepdream` directory and open the notebook `dream.ipynb`i.
Follow the notebook's intructions to try deep dream.
The first run takes longer since the repo's container images and a deep neural network model are fetched from the docker hub.
##Stop Jupyter
```
$ ./stop.sh
```
##Build the containers
Building the images is not necessary since they are fetched from the docker hub.
If, for any reason, you still wish to build them locally the following script
does the job.
```
$ ./build-containers.sh
```
<file_sep>FROM ubuntu:14.04
MAINTAINER <NAME> <<EMAIL>>
RUN apt-get update && apt-get install -y \
git \
bc \
libatlas-base-dev \
libatlas-dev \
libboost-all-dev \
libopencv-dev \
libprotobuf-dev \
libgoogle-glog-dev \
libgflags-dev \
protobuf-compiler \
libhdf5-dev \
libleveldb-dev \
liblmdb-dev \
libsnappy-dev
RUN apt-get install python-numpy
RUN cd root && git clone https://github.com/BVLC/caffe.git && cd caffe && \
cp Makefile.config.example Makefile.config && \
sed -i 's/# CPU_ONLY/CPU_ONLY/g' Makefile.config && \
make -j"$(nproc)" all && \
make pycaffe
ENV PYTHONPATH /root/caffe/python
<file_sep>#!/bin/bash
BASE_MODEL=$(pwd)/workspace/models/bvlc_googlenet/bvlc_googlenet.caffemodel
if [ ! -f $BASE_MODEL ]
then
echo "Downloading base DNN model"
wget -O $BASE_MODEL http://dl.caffe.berkeleyvision.org/bvlc_googlenet.caffemodel
fi
docker run -d -v $(pwd)/workspace:/root/data --name=deepdream -p 8888:8888 jrlangford/deepdream
|
bd6298a917183fbe569f36c6d2011dd4a364885c
|
[
"Markdown",
"Dockerfile",
"Shell"
] | 5
|
Shell
|
jrlangford/deepdream-docker
|
0cf58d03ffa693b4e8119b9391d9649dbe6c00c0
|
afbf219af8827b9395c68e08acb00280f18cd310
|
refs/heads/master
|
<file_sep>package com.boot.demo.tools;
import java.util.Date;
import java.util.Map;
import java.util.TreeMap;
import com.boot.demo.doc.ConfigDocument;
import org.bson.types.ObjectId;
import org.springframework.data.annotation.Transient;
public class Constant {
/**数据库配置doc内容*/
public static ConfigDocument config = new ConfigDocument();
public static String SIGN_APP_KEY = "";
public static String THIRD_PARTY_PREFIX = ""; //第三方注册ID前缀
public static String JPUSH_PREFIX = ""; //极光推送注册前缀
public final static String THIRD_PARTY_PREFIX_USER = "user-"; //第三方注册ID中间名-用户
public final static String THIRD_PARTY_PREFIX_VISITOR = "visitor-"; //第三方注册ID中间名-游客
/**服务器存放文件文件夹路径,删除时候使用*/
public final static String PC_SAVEPATH = "E:/static";
/*部署环境 */
/**开发环境*/
public final static int ENVIRONMENT_DEV = 0; //开发环境
/**生产环境*/
public final static int ENVIRONMENT_PRO = 1; //生产环境
public static int ENVIRONMENT_CURRENT = 0;//当前环境
/**用户共享时的当前APPID*/
public static final int USER_SHARE_APPID = 3;
/**后台管理的app签名key*/
public static String SIGN_MANAGE_KEY = "community#S1D$F5S*H";
/* redis Key值前缀 */
public final static String CACHE_PREFIX_SMS = "sms:community";
public final static String CACHE_PREFIX_REGISTER = "register:community";
public final static String CACHE_PREFIX_UPDATE_MOBILE = "update:community";
public final static String CACHE_PREFIX_LOGIN = "login:community";
public final static String CACHE_PREFIX_RED_PACKET = "redpacket:community";
public final static String CACHE_USER_ID_HASHCODE = "redisuserid:community";
/*用户状态*/
public final static int USER_STATUS_NO_ACTIVE = 1; //未激活
public final static int USER_STATUS_COMM = 2; //正常
public final static int USER_STATUS_FROZEN = 3; //冻结
public final static int USER_STATUS_NOLINE = 4; //离线
//用户隐私设置,被呼叫的隐私设置:0-允许任何人拨打、1-仅允许通讯录好友拨打、2-不允许任何人拨打
/**允许任何人拨打*/
@Transient
public final static int CALL_SECRET_ALL = 0;
/**仅允许通讯录好友拨打*/
@Transient
public final static int CALL_SECRET_FRIEND = 1;
/**不允许任何人拨打*/
@Transient
public final static int CALL_SECRET_NEVER = 2;
/*首次登陆欢迎信息*/
public final static String MSG_WELCOME = "";
/**默认的返回的点赞头像的数量6*/
public final static int LIKE_MSG_NUM = 6;
/**默认展示的动态评论数量2*/
public final static int COMM_MSG_NUM = 2;
/*返回列表条数限制 */
public final static int LIST_LIMIT_4 = 4; //4条
public final static int LIST_LIMIT_5 = 5; //5条
public final static int LIST_LIMIT_10 = 10; //10条
public final static int LIST_LIMIT_12 = 12; //12条
public final static int LIST_LIMIT_20 = 20; //20条
public final static int LIST_LIMIT_35 = 35; //35条
public final static int LIST_LIMIT_50 = 50; //50条
public final static int LIST_LIMIT_100 = 100; //100条
public final static int LIST_LIMIT_1000 = 1000; //1000条
/*操作日志status值 */
public final static int LOG_STATUS_SUCCESS = 0; //成功
public final static int LOG_STATUS_ERROR = 1; //失败
/**很大的一个时间戳,拿来比较比他小的全部时间 9500053977312L*/
public final static long BigTimestamp = 9999999999999L ;
/**地球半径,精确到米*/
public final static double EarthRadius = 6378100.0;
/*通用状态*/
public final static int COMM_STATUS_NORMAL = 0; //正常
public final static int COMM_STATUS_CLOSE = 1; //关闭
/*通用审核状态*/
public final static int COMM_AUDIT_STATUS_ING = 1; //审核中
public final static int COMM_AUDIT_STATUS_SUCCESS = 2; //审核通过
public final static int COMM_AUDIT_STATUS_REFUSE = 3; //审核拒绝
public final static int COMM_AUDIT_STATUS_DELETE = 4; //删除
//通用角色
/**通用角色:1-创建者*/
@Transient
public final static int ROLE_CREATOR = 1;
/**通用角色:2-管理员*/
@Transient
public final static int ROLE_MANAGE = 2;
/**通用角色:3-普通成员*/
@Transient
public final static int ROLE_MEMBER = 3;
/*广告分类*/
public final static int AD_TYPE_APP_START = 1; //APP启动页广告
public final static int AD_TYPE_APP_HOME_BANNER = 2; //APP首页轮播广告
public final static int AD_TYPE_LIVE_ROLL_TEXT = 3; //直播跑马灯文字广播
public final static int AD_TYPE_TVAPP_START = 4; //APP启动页广告
/*文件类型,0:无文件、1:图片、2:视频*/
public final static int FILE_TYPE_NO = 0;
public final static int FILE_TYPE_IMG = 1;
public final static int FILE_TYPE_VIDEO = 2;
/**一个过时的objectId,不能比较大小*/
public final static String OBSOLETE_OBJECTID = "598d9d841fb5a10c6ceb2ac9";
/**一个很大的objectId,弃用,造成查询时不是最大的查询数据丢失。*/
@Deprecated
public final static String MAX_OBJECTID = new ObjectId(new Date(System.currentTimeMillis()*100000)).toString();
/**某ip每指定时间内可以获取验证码次数限,数据库获取*/
public static int IP_GET_CODE_MAXNUM = 9;
/**某ip每次请求上限指定时间周期,单位:s*/
public static long IP_GET_CODE_MAXTIME = 10*60;
/* 推送设备类型 */
public final static int PUSH_DEVTYPE_IOS = 1; // ios
public final static int PUSH_DEVTYPE_ANDROID = 2; // android
public final static Map<String, String> MYFILE_PREFIX_MAP = new TreeMap<>();
static {
MYFILE_PREFIX_MAP.put("COMM_JS","http://file.aroundme.tv/webmodel");
}
}
<file_sep>package com.boot.demo.core.cpntroller;
import com.boot.demo.core.controller.TestController;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.junit4.SpringRunner;
import java.util.Map;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestControllerTests {
private static TestController testController;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
/* ClassPathXmlApplicationContext ct=new ClassPathXmlApplicationContext("spring-base.xml");//取到系统核心配置文件
testController=ct.getBean("com.boot.demo.core.controller.TestController",TestController.class);//从bean工程获取接口bean*/
}
//调用接口
@Test
public void test(){
try {
String result = testController.test(1);
System.out.println("测试结果:" + result);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}<file_sep>package com.boot.demo.tools;
public class ResultModel {
private ResultCode resultCode;
private String msg;
public ResultModel() {
this.resultCode = ResultCode.SUCCESS;
this.msg = resultCode.getMsg();
}
public int getCode() {
return resultCode.getCode();
}
public String getMsg() {
return msg;
}
public void add(String msg) {
this.resultCode = ResultCode.EXCEPTION;
this.msg = msg;
}
public void addSuccess(String msg) {
this.resultCode = ResultCode.SUCCESS;
this.msg = msg;
}
public void add(ResultCode resultCode) {
this.resultCode = resultCode;
this.msg = resultCode.getMsg();
}
}
<file_sep>package com.boot.demo.annotation;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface Sign {
/**
* APP密钥
*/
public final static int APP_KEY = 1;
/**
* 用户密钥
*/
public final static int USER_KEY = 2;
/**
* 不用验证
*/
public final static int NO_CHECK = 3;
int keyType();
}
|
c34403a0ef25fca1cfc0f3956698194298c24bb9
|
[
"Java"
] | 4
|
Java
|
ningwanlong/demo-boot
|
60247ab6751d636af012a700da9c012994fcec37
|
aa7aac603db8ecfca52a59a714c321a622dafc41
|
refs/heads/master
|
<repo_name>patriotina/telebot_supportbot<file_sep>/src/echo-bot2.py
# -*- coding: utf-8 -*-
import constants
import telebot
import datetime
import time
from telebot import types
bot = telebot.TeleBot(constants.tapsup_token)
class tr_message:
def __init__(self, msgstart = False):
self.is_start = msgstart
t_message = 'Обращение в службу поддержки \n'
print(bot.get_me())
troublemessage = ''
tb_msg = tr_message(msgstart=False)
def log(message, answer):
from datetime import datetime
print(datetime.now(), end='; ')
print('Message from {0} {1}; ID: {2}; Text: {3}; '.format(message.from_user.first_name,
message.from_user.last_name,
str(message.from_user.id),
message.text), end='')
print('Answer:', answer)
@bot.message_handler(commands=["start"])
def cmd_start(message):
answer = 'Станадртный флоу'
log(message, answer)
tb_msg.is_start = True
tb_msg.t_message += str(datetime.datetime.now()) + '\n'
tb_msg.t_message += 'Message from {0} {1}; AKA {2} ID: {3}; From chat: {4}; \n'.format(message.from_user.first_name,
message.from_user.last_name,
message.from_user.username,
str(message.from_user.id),
message.chat.title)
print(str(message))
keyboard = types.InlineKeyboardMarkup()
url_button = types.InlineKeyboardButton(text="Перейти к списку заявок", url="http://help.373soft.ru/issues")
keyboard.add(url_button)
bot.send_message(message.chat.id, "Привет! Нажми на кнопку и перейди в поисковик.", reply_markup=keyboard)
keyboard = types.ReplyKeyboardMarkup(True, True, True)
keyboard.row('/Водитель')
keyboard.row('/Комплекс')
keyboard.row('/Оператор')
ans = bot.send_message(message.chat.id, 'У кого проблема?', reply_markup=keyboard)
#bot.register_next_step_handler(ans, standart_driver)
@bot.message_handler(commands=["chatid"])
def cmd_chatid(message):
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, message.chat.id, reply_markup=hide_keyb)
@bot.message_handler(commands=["Водитель"])
def standart_driver(message):
tb_msg.t_message += 'Проблема на стороне водителя\n'
keyboard = types.ReplyKeyboardMarkup(True)
keyboard.row('/Подключение')
keyboard.row('/Приложение')
keyboard.row('/Оплата')
bot.send_message(message.chat.id, 'С чем у водителей проблема?', reply_markup=keyboard)
@bot.message_handler(commands=["Подключение"])
def driver_connection(message):
tb_msg.t_message += 'Проблемы с подключением к системе\n'
msg = 'Дополните информацию: позывные, все водители или единичный случай, еще какие-то особенности и подробности'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Приложение"])
def driver_application(message):
tb_msg.t_message += 'Проблемы в приложении водителя \n'
keyboard = types.ReplyKeyboardMarkup(True)
keyboard.row('/Кнопка')
keyboard.row('/Маршрут')
keyboard.row('/Другое')
bot.send_message(message.chat.id, 'Что не работает в приложении?', reply_markup=keyboard)
@bot.message_handler(commands=["Кнопка"])
def application_button(message):
tb_msg.t_message += 'В приложении не работает кнопка \n'
msg = 'Дополните информацию: позывные, все водители или единичный случай, еще какие-то особенности и подробности'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Маршрут"])
def application_route(message):
tb_msg.t_message += 'В приложении не корректно расчитывается маршрут \n'
msg = 'Дополните информацию: позывные, все водители или единичный случай, еще какие-то особенности и подробности'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Другое"])
def application_other(message):
tb_msg.t_message += 'Приложение работает не корректно \n'
msg = 'Дополните информацию: позывные, все водители или единичный случай, еще какие-то особенности и подробности'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Оплата"])
def driver_payment(message):
tb_msg.t_message += 'Проблемы с оплатой у водителя \n'
msg = 'Дополните информацию: позывные, все водители или единичный случай, еще какие-то особенности и подробности'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Комплекс"])
def standart_soft(message):
tb_msg.t_message += 'Проблема с комплекосм\n'
keyboard = types.ReplyKeyboardMarkup(True)
keyboard.row('/Телефония')
keyboard.row('/Приложение')
bot.send_message(message.chat.id, 'Какя часть комплекса не работает?', reply_markup=keyboard)
@bot.message_handler(commands=["Телефония"])
def soft_phone(message):
tb_msg.t_message += 'Проблема с телефонией\n'
keyboard = types.ReplyKeyboardMarkup(True)
keyboard.row('/Входящая')
keyboard.row('/Исходящая')
keyboard.row('/Блокировка')
bot.send_message(message.chat.id, 'Какое направление телефонии требует внимания?', reply_markup=keyboard)
@bot.message_handler(commands=["Входящая"])
def phone_in(message):
tb_msg.t_message += 'Проблема с входящими звонками\n'
msg = 'Допишите комментарий с какого момента не работает и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Исходящая"])
def phone_out(message):
tb_msg.t_message += 'Проблема с отзвонами\n'
msg = 'Допишите комментарий с какого момента не работает, по всем каналам или нет и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Блокировка"])
def phone_block(message):
tb_msg.t_message += 'Заблокировать абонента\n'
msg = 'Допишите кого и по какой причине заблокировать и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=["Оператор"])
def oper(message):
tb_msg.t_message += 'Проблема с местом оператора\n'
keyboard = types.ReplyKeyboardMarkup(True)
keyboard.row('/Не работает ПК')
keyboard.row('/Проблема с таксиофисом')
keyboard.row('/Не работает гарнитура')
keyboard.row('/Не верное время')
bot.send_message(message.chat.id, 'Что не работает?', reply_markup=keyboard)
@bot.message_handler(commands=['/Не работает ПК'])
def oper_pc(message):
print('operator PC')
tb_msg.t_message += 'Не работает ПК \n'
msg = 'Сообщите номер ПК и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=['/Проблема с таксиофисом'])
def oper_taxioffice(message):
print('taxioffice troubles')
tb_msg.t_message += 'Проблема с таксиофисом \n'
msg = 'Сообщите номер ПК где не работает комплекс и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=['/Не работает гарнитура'])
def oper_garniture(message):
print('garniture troubles')
tb_msg.t_message += 'Не работает гарнитура \n'
msg = 'Сообщите номер ПК где не работает гарнитура и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=['/Не верное время'])
def oper_pctime(message):
print('pc time troubles')
tb_msg.t_message += 'Не верное время на ПК \n'
msg = 'Сообщите номер ПК с некорректным временем и отправьте заявку кнопкой /Готово'
hide_keyb = types.ReplyKeyboardRemove()
bot.send_message(message.chat.id, msg, reply_markup=hide_keyb)
@bot.message_handler(commands=['spec'])
def cmd_spec(message):
answer = 'Что случилось?'
log(message, answer)
bot.send_message(message.chat.id, 'Что случилось?')
@bot.message_handler(commands=['alarm'])
def cmd_alarm(message):
answer = 'Описание аварии!!!'
log(message, answer)
bot.send_message(message.chat.id, 'Описание аварии!!!')
@bot.message_handler(commands=['Готово'])
def done_ask(message):
#global troublemessage
#troublemessage += str(message.text)
tb_msg.is_start = False
keyboard = types.ReplyKeyboardMarkup(True, True, True)
keyboard.row('/start', '/alarm', '/spec')
bot.send_message(message.chat.id, tb_msg.t_message, reply_markup=keyboard)
tb_msg.t_message = ''
@bot.message_handler(content_types=["text"])
def repeat_all_message(message):
# answer = "Hello, #username"
# log(message, answer)
if tb_msg.is_start:
tb_msg.t_message += message.text
keyboard = types.ReplyKeyboardMarkup(True)
keyboard.row('/Готово')
msg = 'Дополните описание проблемы, если больше нечего добавить, нажмите /Готово'
else:
keyboard = types.ReplyKeyboardMarkup(True, True, True)
keyboard.row('/start', '/alarm', '/spec')
# button_start = types.KeyboardButton(text='/start', request_location=True)
# button_alarm = types.KeyboardButton(text='/alarm')
# button_spec = types.KeyboardButton(text='/spec')
# keyboard.add(button_start, button_alarm, button_spec)
# url_button = types.InlineKeyboardButton(text="go to yandex", url="ya.ru")
# keyboard.add(url_button)
msg = "Hello, " + str(message.from_user.username)
bot.send_message(message.chat.id, msg, reply_markup=keyboard)
print(message.text)
if __name__ == '__main__':
try:
bot.polling(none_stop = True)
except Exception:
time.sleep(15)
'''
def initializeTeleBot():
logger = telebot.logger
telebot.logger.setLevel(logging.INFO)
telebot.apihelper.proxy = {
#'http': 'socks5://login:pass@par3.google.385444444444444493392625027464760522671600012331238.proxy.veesecurity.com:443',
'https': 'socks5://login:pass@par5.google.v98nxnmrtpf8t0oe1j4dcy4tlg636jiv.proxy.veesecurity.com:443'
}
bot = telebot.TeleBot(bottoken.token)
boturl=const.boturl
#print(bot.get_webhook_info())
bot.delete_webhook()
bot.set_webhook(url=boturl)
print(bot.get_webhook_info())
return bot
'''
<file_sep>/src/ttalert.py
import constants
import telebot
import datetime
import time
from telebot import types
from telebot.types import InlineKeyboardButton
#from flask import Flask
bot = telebot.TeleBot(constants.ttalarm)
t_message = ''
@bot.message_handler(commands=["start"])
def cmd_start(message):
answer = 'Начнем'
#log(message, answer)
#tb_msg.is_start = True
t_message = ''
t_message += str(datetime.datetime.now()) + '\n'
t_message += 'Message from {0} {1}; AKA {2} ID: {3}; From chat: {4}; \n'.format(message.from_user.first_name,
message.from_user.last_name,
message.from_user.username,
str(message.from_user.id),
message.chat.title)
print(str(message))
keyboard = types.InlineKeyboardMarkup()
#url_button = types.InlineKeyboardButton(text="Перейти к списку заявок", url="http://help.373soft.ru/issues")
#keyboard.add(url_button)
inl_button = types.InlineKeyboardButton(text="Авария!", callback_data='AlarmOn')
inl_button2 = types.InlineKeyboardButton(text="Проблема решена", callback_data='AlarmOff')
iss_but = types.InlineKeyboardButton(text='Создать заявку', url="help.373soft.ru/create_task/")
keyboard.row(inl_button, inl_button2, iss_but)
#keyboard.add(inl_button)
#keyboard.add(inl_button2)
#bot.send_message(message.from_user.id, "Что у нас?", reply_markup=keyboard)
#keyboard = types.ReplyKeyboardMarkup(True, False)
#keyboard.row('/alarm', '/ok')
ans = bot.send_message(message.chat.id, 'Всё ок?', reply_markup=keyboard)
@bot.message_handler(commands=["alarm"])
def cmd_alarm(message):
alm_message = 'Alarm;'
alm_message += str(datetime.datetime.now()) + ';'
alm_message += str(message.from_user.id) + ';'
alm_message += str(message.chat.id)
print(alm_message)
keyboard = types.InlineKeyboardMarkup()
# url_button = types.InlineKeyboardButton(text="Перейти к списку заявок", url="http://help.373soft.ru/issues")
# keyboard.add(url_button)
inl_button = types.InlineKeyboardButton(text="Подать заявку", url="help.373soft.ru/create_task/")
inl_button2 = types.InlineKeyboardButton(text="Посмотреть заявки", url="help.373soft.ru/issues/")
keyboard.row(inl_button, inl_button2)
ms = bot.send_message(message.chat.id, alm_message, reply_markup=keyboard)
alm_message = ''
@bot.message_handler(commands=["ok"])
def cmd_norm(message):
alm_message = 'AlarmOff;'
alm_message += str(datetime.datetime.now()) + ';'
alm_message += str(message.from_user.id) + ';'
alm_message += str(message.chat.id)
print(alm_message)
ms = bot.send_message(message.chat.id, alm_message)
@bot.inline_handler(func=lambda query: len(query.query) is 0)
def empty_query(query):
hint = "первый хинт"
try:
r = types.InlineQueryResultArticle(
id='1',
#parse_mode='Markdown',
title="Бот \"Спасатель\"",
description=hint,
input_message_content=types.InputTextMessageContent(
message_text="Подать заявку на Аварию"),
url="http://help.373soft.ru/create_task",
#disable_web_page_preview=True,
# Не будем показывать URL в подсказке
hide_url=False
)
bot.answer_inline_query(query.id, [r])
except Exception as e:
print(e)
restricted_messages = ['Авария', 'авария', 'авари', 'Авари']
GROUP_ID = -367377146
ro_msg = 'Вам запрещено отправлять сюда сообщения в течение 10 минут'
city_list = {'test': -367377146}
city_alarm_list = {}
#<EMAIL>(func=lambda message: message.text and message.text.lower() in restricted_messages)# and message.chat.id == GROUP_ID)
@bot.message_handler(content_types='text')
def find_alarm(message):
#print(message)
if 'авария' in message.text.lower():
#print(alm_message)
reply_keyboard = types.InlineKeyboardMarkup()
#alarm_url = 'help.373soft.ru/alarm?alrm_msg_id=' + str(message.message_id) + '&alrm_author=' + str(message.from_user.id) + '&alrm_city=' + str(message.chat.id)
#inl_button = types.InlineKeyboardButton(text="Да", url=alarm_url)
inl_button2 = types.InlineKeyboardButton(text="Нет", callback_data='AlarmOff')
#iss_but = types.InlineKeyboardButton(text='Создать заявку', url="help.373soft.ru/create_task/")
#reply_keyboard.row(inl_button, inl_button2)
ms = bot.send_message(message.chat.id, 'Случилась авария? ')
alarm_url = 'help.373soft.ru/alarm?alrm_msg_id=' + str(ms.message_id) + '&alrm_author=' + str(message.from_user.id) + '&alrm_city=' + str(message.chat.id)
inl_button = types.InlineKeyboardButton(text="Да", url=alarm_url)
reply_keyboard.row(inl_button, inl_button2)
bot.edit_message_text(text='Случилась авария?', chat_id=ms.chat.id, message_id=ms.message_id, reply_markup=reply_keyboard)
#bot.send_message(message.chat.id, ms.message_id)
#bot.delete_message(message.chat.id, 261)
#print(message.text)
#print(message.chat.id)
#bot.edit_message_text(text='хуярия', chat_id=message.chat.id, message_id=331)
@bot.callback_query_handler(func=lambda c: True)
def calls(c):
if c.data == 'AlarmOn':
alm_message = 'AlarmOn;'
city_alarm_list[c.message.chat.id] = 1
reply_keyboard = types.InlineKeyboardMarkup()
inl_button = types.InlineKeyboardButton(text="Исправлено", url='ya.ru')
reply_keyboard.row(inl_button)
bot.edit_message_text(chat_id=c.message.chat.id, message_id=c.message.message_id, text='Взято в работу', reply_markup=reply_keyboard)
elif c.data == 'AlarmOff':
alm_message = 'AlarmOff;'
city_alarm_list[c.message.chat.id] = 0
bot.delete_message(c.message.chat.id, c.message.message_id)
alm_message += str(datetime.datetime.now()) + ';'
alm_message += str(c.message.from_user.id) + ';'
alm_message += str(c.message.chat.id)
alm_message += str('\n')
f = open('alarm.log', 'a')
f.write(alm_message)
f.close()
#bot.send_message(c.message.chat.id, alm_message)
# Банить будем за капслок, постепенно
# print('Yyyeeeaaahh')
# bot.restrict_chat_member(message.chat.id, message.from_user.id, until_date=time.time()+6)
# bot.send_message(message.chat.id, ro_msg,
# reply_to_message_id=message.message_id)
if __name__ == '__main__':
try:
bot.polling(none_stop = True)
except Exception:
time.sleep(15)
|
28b2e00a0dfad1f75d26af07619069e68df78803
|
[
"Python"
] | 2
|
Python
|
patriotina/telebot_supportbot
|
c9016454e92111b2919f47e754601bd643aae584
|
6e52000443fdbc202e913d61aa87e2a178d0fee6
|
refs/heads/master
|
<file_sep>#!/bin/bash
N=100
M=20
T=10
alpha=0.01
x=6
GRAPH_PATH=./result/graph${N}.pkl
DATA_PATH=./result/data${N}.pkl
LIST_PATH=./result/list${N}.pkl
rm ${DATA_PATH}
rm ${GRAPH_PATH}
rm ${LIST_PATH}
python gen_graph.py -n $N -i 2 --graph=${GRAPH_PATH}
#python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=0.04 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=1
#python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=0.04 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=2
#python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=0.05 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=1
#python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=0.05 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=2
python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=0.06 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=1
python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=0.06 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=2
python draw_figures.py ${DATA_PATH} 6
#python main.py -n $N -i 4 -m $M -t $T -M random -f single_line -a no+info --txt=4-15 --lamuta=0.04 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=0.15
#python main.py -n $N -i 4 -m $M -t $T -M random -f single_line -a no+info --txt=5-20 --lamuta=0.05 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=0.2
<file_sep>from __future__ import division
import pickle
import matplotlib.pyplot as plt
import sys
r_path = sys.argv[1]
x = int(sys.argv[2])
def draw_one_line(data, times, line, point):
lens = len(data)
index = range(1,lens+1)
plt.plot(index, data, line)
for i in range(lens):
plt.plot(index[i], data[i], point, alpha = times[i]/(max(times)))
#print times[i]/(max(times))
if __name__ == "__main__":
pkl = open(r_path, 'rb')
data = []
times = []
#for i in range(6):
for i in range(x):
data.append(pickle.load(pkl))
times.append(pickle.load(pkl))
lens = len(data)
line = ['g-','b-','k-','y-','r-']
shape = ['gs', 'b+' , 'k*' , 'yo' ,'rx' ]
for i in range(lens):
draw_one_line(data[i],times[i], line[i], shape[i])
plt.show()
<file_sep>BA_network
==========
BA network, to study economics
<file_sep>#!/bin/bash
#same=0+0, use different m_list, same=0+1, use the same m_ist
#add=0, use random m_list, add=1, use add m_list
#kind=1, no info level, kind=2, with info level
N=500
M=30
T=30
lamuta=0.05
alpha=$lamuta
#the lines in data file
t=5
GRAPH_PATH=graphs/graph${N}-$t-$lamuta.pkl
DATA_PATH=data/4-13/data${N}-$t-$lamuta.pkl
LIST_PATH=lists/list${N}-$t-$lamuta.pkl
echo 'sleeping...'
sleep 10
echo 'remove data'
rm ${DATA_PATH}
rm ${GRAPH_PATH}
rm ${LIST_PATH}
python gen_graph.py -n $N -i 2 --graph=${GRAPH_PATH}
#python gen_m_list.py $LIST_PATH 20 2
python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=${lamuta} --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=1 --list=${LIST_PATH} --same=0 --add=1
python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=${lamuta} --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=2 --list=${LIST_PATH} --same=0 --add=1
python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=${lamuta} --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=3 --list=${LIST_PATH} --same=0 --add=1
python main.py -n $N -i 2 -m $M -t $T -M random -f single_line -a no+info --txt=6-1 --lamuta=${lamuta} --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=4 --list=${LIST_PATH} --same=0 --add=1
python main.py -n $N -i 2 -m $M -t 1 -M purpose -f single_line -a no+info --txt=6-1 --lamuta=${lamuta} --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=${alpha} --kind=1 --list=${LIST_PATH} --same=0 --add=1
python draw_figures.py ${DATA_PATH} 5
#python main.py -n $N -i 4 -m $M -t $T -M random -f single_line -a no+info --txt=4-15 --lamuta=0.04 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=0.15
#python main.py -n $N -i 4 -m $M -t $T -M random -f single_line -a no+info --txt=5-20 --lamuta=0.05 --graph=${GRAPH_PATH} --data=${DATA_PATH} --alpha=0.2
|
117101afac154724640fa784e5f44520fbe08d81
|
[
"Markdown",
"Python",
"Shell"
] | 4
|
Shell
|
buaakq/BA_network
|
ef67e0bf130fdc75d8fdf6a2bc336e8b6f9b9661
|
3d794ccf0ef9e1d9b6efed9bdc874b1e53494091
|
refs/heads/master
|
<file_sep># JSCS TeamCity Reporter Test Harness
This project exists to be able to test the [jscs-teamcity-reporter](https://github.com/wurmr/jscs-teamcity-reporter).
## Usage
```
$ npm install
$ npm test
```
<file_sep>(function () {
'use strict';
undeclared();
});
|
93d5ba8966f2ef86b9ab18a4b8753ba3b0ff5a0e
|
[
"Markdown",
"JavaScript"
] | 2
|
Markdown
|
wurmr/Jscs-Teamcity-Reporter-Test-Harness
|
9c41eadce4e541ee37418957049f03faef2c6fcc
|
2dec85bd0e86f9e090e83c816652e507bd3dc50e
|
refs/heads/master
|
<repo_name>insanustu/TSDemux<file_sep>/src/M2TSProcessor.cpp
#include "ElementaryStreamData.h"
#include "M2TSProcessor.h"
#include "PacketHeader.h"
#include "TableHeader.h"
#include "PAT.h"
#include "PMT.h"
#include "PESPacketHeader.h"
namespace {
enum class PredefinedPid : uint16_t {
PAT = 0x0000,
CAT = 0x0001,
TSDT = 0x0002,
IPMP = 0x0003,
NIT_ST = 0x0010,
STD_BAT_ST = 0x0011,
EIT_ST_CIT = 0x0012,
RST_ST = 0x0013,
TDT_TOT_ST = 0x0014,
NET_SYNC = 0x0015,
RNT = 0x0016,
INBAND_SIG = 0x001C,
MEASURE = 0x001D,
DIT = 0x001E,
SIT = 0x001F
};
}
namespace m2tsext {
Result<std::monostate> M2TSProcessor::processPacket(TPacketData& packetData) {
PacketHeader ph(packetData.data());
if (ph.syncByte() != 'G') {
// format of ts is corrupted
return Error("Wrong sync byte error: " + ph.syncByte());;
}
if (ph.transportErrorIndicator()) {
// skip broken packet
return std::monostate();
}
if (!ph.hasPayload()) {
// skip packet without a payload
return std::monostate();
}
if (PredefinedPid(ph.pid()) == PredefinedPid::PAT) {
processPATPacket(ph);
}
else if (ph.pid() == programPID) {
processPMTPacket(ph);
}
else if (ph.pid() == audioPID) {
const auto& result = processAudioPacket(ph);
if (result.isOK()) {
return result;
}
return Error("Error while processing an audio packet: " + result.error().what());
}
else if (ph.pid() == videoPID) {
const auto& result = processVideoPacket(ph);
if (result.isOK()) {
return result;
}
return Error("Error while processing a video packet: " + result.error().what());
}
return std::monostate();
}
void M2TSProcessor::setAudioDataProcessor(TDataProcessor&& aProcessor) {
audioDataProcessor = std::move(aProcessor);
}
void M2TSProcessor::setVideoDataProcessor(TDataProcessor&& vProcessor) {
videoDataProcessor = std::move(vProcessor);
}
void M2TSProcessor::processPATPacket(const PacketHeader& packetHeader)
{
auto tableHeader = packetHeader.payloadData();
if (packetHeader.payloadUnitStartIndicator()) {
auto fillers = tableHeader[0];
++tableHeader;
tableHeader += fillers;
}
TableHeader th(tableHeader);
if (th.getTableDataLength() == 0) {
return;
}
programPID = PAT(th.getTableData()).pid();
}
void M2TSProcessor::processPMTPacket(const PacketHeader& packetHeader)
{
auto tableHeader = packetHeader.payloadData();
if (packetHeader.payloadUnitStartIndicator()) {
auto fillers = tableHeader[0];
++tableHeader;
tableHeader += fillers;
}
TableHeader th(tableHeader);
if (th.getTableDataLength() == 0) {
return;
}
PMT pmt(th.getTableData());
auto totalElementaryStreamInfoLength = th.getTableDataLength() - 4 - pmt.getProgramInfoLength();
auto totalElementaryStreamStartData = pmt.getElementaryStreamInfoData();
while (totalElementaryStreamInfoLength > 0) {
ElementaryStreamData esd(totalElementaryStreamStartData);
if (esd.isAudio()) {
audioPID = esd.elementaryPID();
}
if (esd.isVideo()) {
videoPID = esd.elementaryPID();
}
totalElementaryStreamInfoLength -= esd.elementaryStreamDataSize();
totalElementaryStreamStartData += esd.elementaryStreamDataSize();
}
}
Result<std::monostate> processPES(const PacketHeader& packetHeader,
TDataProcessor& dataProcessor,
uint16_t& remainingPESLength) {
const uint8_t* data = packetHeader.payloadData();
uint16_t dataSize = packetHeader.payloadSize();
if (packetHeader.payloadUnitStartIndicator()) {
PESPacketHeader pes(packetHeader.payloadData());
data += pes.headerLength();
remainingPESLength = pes.packetDataSize();
dataSize -= pes.headerLength();
}
if (remainingPESLength != 0) {
dataSize = std::min(dataSize, remainingPESLength);
remainingPESLength -= dataSize;
}
return dataProcessor(data, dataSize);
}
Result<std::monostate> M2TSProcessor::processAudioPacket(const PacketHeader& packetHeader)
{
if (!audioDataProcessor) {
return std::monostate();
}
return processPES(packetHeader, audioDataProcessor, audioPESLength);
}
Result<std::monostate> M2TSProcessor::processVideoPacket(const PacketHeader& packetHeader)
{
if (!videoDataProcessor) {
return std::monostate();
}
return processPES(packetHeader, videoDataProcessor, videoPESLength);
}
}
<file_sep>/src/m2tsextractor.h
#pragma once
#include "Error.h"
#include <istream>
namespace m2tsext {
// gets a stream containing MPEG-2 TS
// splits it on video and audio
// and writes the splitted into output streams
// @m2tsStream - input MPEG-2 TS stream to split
// @outVideoStream - output video stream
// @outAudioStream - output audio stream
Result<std::monostate> extractVideoAudioFromM2TSSstream(
std::istream& m2tsStream,
std::ostream& outVideoStream,
std::ostream& outAudioStream);
}
<file_sep>/src/m2tsextractor.cpp
#include "m2tsextractor.h"
#include "M2TSProcessor.h"
#include "PacketHeader.h"
#include <iostream>
namespace m2tsext {
Result<std::monostate> extractVideoAudioFromM2TSSstream(
std::istream& m2tsStream,
std::ostream& outVideoStream,
std::ostream& outAudioStream) {
M2TSProcessor mpr;
if (outAudioStream) {
mpr.setAudioDataProcessor([&outAudioStream](const uint8_t* data, size_t dataSize) -> Result<std::monostate> {
outAudioStream.write((char*)data, dataSize);
if (!outAudioStream.good()) {
return Error("Error writing audio stream occured");
}
return std::monostate();
});
}
if (outVideoStream) {
mpr.setVideoDataProcessor([&outVideoStream](const uint8_t* data, size_t dataSize) -> Result<std::monostate> {
outVideoStream.write((char*)data, dataSize);
if (!outVideoStream.good()) {
return Error("Error writing video stream occured");
}
return std::monostate();
});
}
while (m2tsStream) {
TPacketData data;
m2tsStream.read((char*)data.data(), data.size());
const auto bytesRead = m2tsStream.gcount();
if (bytesRead != 0 && bytesRead != data.size()) {
return Error("Error occured while reading from the input stream");
}
const auto& result = mpr.processPacket(data);
if (result.isOK()) {
continue;
}
return result;
}
return std::monostate();
}
}
<file_sep>/src/AdaptationField.h
#pragma once
#include <cstdint>
namespace m2tsext {
// Class wrapping adaptation field in MPEG-2 TS packet header
// +=========================================================
// | 8 | adaptation field length
// +---------------------------------------------------------
// | 1 | discontinuity indicator
// +---------------------------------------------------------
// | 1 | random access indicator
// +---------------------------------------------------------
// | 1 | elementary stream priority indicator
// +---------------------------------------------------------
// | 1 | PCR flag
// +---------------------------------------------------------
// | 1 | OPCR flag
// +---------------------------------------------------------
// | 1 | splicing point flag
// +---------------------------------------------------------
// | 1 | transport private data flag
// +---------------------------------------------------------
// | 1 | adaptation field extension flag
// +======== Optional =======================================
// | 48 | PCR
// +---------------------------------------------------------
// | 48 | OPCR
// +---------------------------------------------------------
// | 8 | splice countdown
// +---------------------------------------------------------
// | 8 | transport private data length
// +---------------------------------------------------------
// | ~~~ | transport private data
// +---------------------------------------------------------
// | ~~~ | adaptation extension
// +---------------------------------------------------------
// | ~~~ | stuffing bytes
// +=========================================================
class AdaptationField {
public:
explicit AdaptationField(const uint8_t* _data) : data(_data) {}
uint8_t adaptationFieldLength() const {
return data[0];
}
bool discontinuity() const {
return data[1] & 0x80;
}
bool randomAccess() const {
return data[1] & 0x40;
}
bool elementaryStreamHighPriority() const {
return data[1] & 0x20;
}
bool hasPCR() const {
return data[1] & 0x10;
}
bool hasOPCR() const {
return data[1] & 0x08;
}
bool hasSpliceCoundownField() const {
return data[1] & 0x04;
}
bool hasTransportPrivateData() const {
return data[1] & 0x02;
}
bool hasAdaptationExtention() const {
return data[1] & 0x01;
}
private:
const uint8_t* data;
};
}<file_sep>/src/PMT.h
#pragma once
#include "util.h"
namespace m2tsext {
// Class wrapping PMT of MPEG-2 TS
// +==============================
// | 3 | reserved bits
// +------------------------------
// | 13 | PCR PID
// +------------------------------
// | 4 | reserved bits
// +------------------------------
// | 2 | unused bits
// +------------------------------
// | 10 | program info length
// +------------------------------
// | N*8 | program descriptors
// +------------------------------
// | N*8 | elementary info data
// +==============================
class PMT {
public:
explicit PMT(const uint8_t* _data) : data(_data) {}
uint16_t getPCR_PID() const { return readPIDFromBigEndian(data); }
uint16_t getProgramInfoLength() const { return readFromBigEndian<uint16_t>(&data[2]) & 0x03ff; }
const uint8_t* getElementaryStreamInfoData() const { return data + 4 + getProgramInfoLength(); }
private:
const uint8_t* data;
};
}<file_sep>/src/ElementaryStreamData.h
#pragma once
#include "util.h"
namespace m2tsext {
// Class wrapping elementary stream data
// +=======================================
// | 8 | stream type
// +---------------------------------------
// | 3 | reserved bits
// +---------------------------------------
// | 13 | elementary PID
// +---------------------------------------
// | 4 | reserved bits
// +---------------------------------------
// | 2 | ES info length unused bits
// +---------------------------------------
// | 10 | ES info length
// +---------------------------------------
// | N*8 | elementary stream descriptors
// +=======================================
class ElementaryStreamData {
public:
explicit ElementaryStreamData(const uint8_t* _data) : data(_data) {}
uint8_t streamType() const { return data[0]; }
uint16_t elementaryPID() const { return readFromBigEndian<uint16_t>(&data[1]) & 0x1fff; }
uint16_t esInfoLength() const { return readFromBigEndian<uint16_t>(&data[3]) & 0x03ff; }
uint16_t elementaryStreamDataSize() const { return esInfoLength() + 5; }
bool isAudio() const;
bool isVideo() const;
private:
const uint8_t* data;
};
}
<file_sep>/src/PacketHeader.h
#pragma once
#include "AdaptationField.h"
#include "util.h"
namespace m2tsext {
constexpr uint16_t PACKET_SIZE = 188;
// Class wrapping packet header of MPEG-2 TS
// +========================================
// | 8 | sync byte
// +----------------------------------------
// | 1 | transport error indicator
// +----------------------------------------
// | 1 | payload unit start indicator
// +----------------------------------------
// | 1 | transport priority
// +----------------------------------------
// | 13 | PID
// +----------------------------------------
// | 2 | transport scrambling
// +----------------------------------------
// | 2 | adaptation field control
// +----------------------------------------
// | 4 | continuity counter
// +======= OPTIONAL =======================
// | ~~~ | adaptation field
// +----------------------------------------
// | ~~~ | payload data
// +========================================
class PacketHeader {
public:
explicit PacketHeader(const uint8_t* _data) : data(_data) {}
uint8_t syncByte() const {
return data[0];
}
bool transportErrorIndicator() const {
return data[1] & 0x80;
}
bool payloadUnitStartIndicator() const {
return data[1] & 0x40;
}
bool transportPriority() const {
return data[1] & 0x20;
}
uint16_t pid() const {
return readPIDFromBigEndian(&data[1]);
}
uint8_t transportScramblingControl() const {
return (data[3] & 0xc0) >> 6;
}
bool hasPayload() const {
return data[3] & 0x10;
}
bool hasAdaptationField() const {
return data[3] & 0x20;
}
uint8_t continuityCounter() const {
return data[3] & 0xf;
}
const uint8_t* payloadData() const {
auto payloadData = data + 4;
if (hasAdaptationField()) {
AdaptationField af(payloadData);
payloadData += af.adaptationFieldLength();
++payloadData; // skip the adaptation field length length (1 byte)
}
return payloadData;
}
const uint16_t payloadSize() const {
return uint16_t(data + PACKET_SIZE - payloadData());
}
private:
const uint8_t* data;
};
}
<file_sep>/src/PESPacketHeader.h
#pragma once
#include "util.h"
namespace m2tsext {
// Class wrapping PES packet header
// +===============================
// | 24 | 0x000001
// +-------------------------------
// | 8 | stream id
// +-------------------------------
// | 16 | PES packet length
// +-------------------------------
// | > 24 | optional PES header
// +-------------------------------
// | ~~~ | stuffing bytes
// +-------------------------------
// | ~~~ | data
// +===============================
class PESPacketHeader {
public:
explicit PESPacketHeader(const uint8_t* _data) : data(_data) {}
uint32_t startCode() const { return readFromBigEndian<uint32_t>(data); }
uint16_t packetLength() const { return readFromBigEndian<uint16_t>(&data[4]); }
uint8_t headerLength() const { return data[8] + 9; }
uint16_t packetDataSize() const {
if (packetLength() == 0) {
return 0;
}
return packetLength() - headerLength() + 6;
}
private:
const uint8_t* data;
};
}
<file_sep>/src/TableHeader.h
#pragma once
#include "util.h"
namespace m2tsext {
// Class wrapping table header of MPEG-2 TS
// +=======================================
// | 8 | table ID
// +---------------------------------------
// | 1 | section syntax indicator
// +---------------------------------------
// | 1 | private bit
// +---------------------------------------
// | 2 | reserved bits
// +---------------------------------------
// | 2 | unused bits
// +---------------------------------------
// | 10 | section length
// +---------------------------------------
// | N*8 | syntax section/table data
// +=======================================
class TableHeader {
public:
explicit TableHeader(const uint8_t* _data) : data(_data) {}
uint8_t tableID() const { return data[0]; }
bool sectionSyntaxIndicator() const { return data[1] & 0x80; }
bool privateBit() const { return data[1] & 0x40; }
uint16_t sectionLength() const { return readFromBigEndian<uint16_t>(&data[1]) & 0x03ff; }
const uint8_t* getTableData() const { return data + 8; }
// table data length is a section length - CRC(4) - table_syntax_length(5)
const uint16_t getTableDataLength() const { return sectionLength() - 9; }
private:
const uint8_t* data;
};
}<file_sep>/CMakeLists.txt
cmake_minimum_required (VERSION 3.4)
project(TSDemux)
set (TSDemux_VERSION_MAJOR 0)
set (TSDemux_VERSION_MINOR 1)
set (CMAKE_CXX_STANDARD 17)
set (CMAKE_SUPPRESS_REGENERATION true)
set_property (DIRECTORY PROPERTY VS_STARTUP_PROJECT "ts-demux")
file(GLOB_RECURSE HEADER_FILES "src/*.h")
file(GLOB_RECURSE SOURCE_FILES "src/*.cpp")
add_executable(ts-demux
${SOURCE_FILES}
${HEADER_FILES})
target_include_directories(ts-demux PRIVATE
src)
<file_sep>/src/PAT.h
#pragma once
#include "util.h"
namespace m2tsext {
// Class wrapping PAT in MPEG-2 TS
// +==============================
// | 16 | program num
// +------------------------------
// | 3 | reserved bits
// +------------------------------
// | 13 | program map PID
// +==============================
class PAT {
public:
explicit PAT(const uint8_t* _data) : data(_data) {}
uint16_t pid() const { return readPIDFromBigEndian(&data[2]); }
private:
const uint8_t* data;
};
}
<file_sep>/src/main.cpp
#include "Error.h"
#include "m2tsextractor.h"
#include "util.h"
#include <fstream>
#include <iostream>
void printErrorParameters() {
m2tsext::printErrorMessage( "Wrong parameters. Usage:\n"
"\tts-demux -i <input_file> -a <audio_file> -v <video_file>\n");
}
void printErrorNoInputFile(const std::string& file) {
m2tsext::printErrorMessage("No such file: " + file);
}
void printErrorNoOutputFile(const std::string& file) {
m2tsext::printErrorMessage("Could not create: " + file);
}
int main(int argc, char* argv[]) {
auto parameters = m2tsext::parseParameters(argc, argv);
if (parameters.empty()) {
printErrorParameters();
return 1;
}
auto inputFileName = parameters["-i"];
auto audioOutputFileName = parameters["-a"];
auto videoOutputFileName = parameters["-v"];
if (inputFileName.empty() ||
(audioOutputFileName.empty() && videoOutputFileName.empty())) {
printErrorParameters();
return 1;
}
std::ifstream i(inputFileName, std::ios::binary);
if (!i.is_open()) {
printErrorNoInputFile(inputFileName);
return 1;
}
std::ofstream a(audioOutputFileName, std::ios::binary);
if (!audioOutputFileName.empty() && !a.is_open()) {
printErrorNoOutputFile(audioOutputFileName);
return 1;
}
std::ofstream v(videoOutputFileName, std::ios::binary);
if (!videoOutputFileName.empty() && !v.is_open()) {
printErrorNoOutputFile(videoOutputFileName);
return 1;
}
const auto& result = m2tsext::extractVideoAudioFromM2TSSstream(i, v, a);
if (!result.isOK()) {
m2tsext::printErrorMessage(result.error().what());
return 1;
}
return 0;
}
<file_sep>/src/util.h
#pragma once
#include <string>
#include <unordered_map>
#include <iostream>
namespace m2tsext {
template <typename T, size_t NBytes>
struct ReadFromBigEndian;
template <typename T>
struct ReadFromBigEndian<T, 1> {
static T read(const uint8_t* data) {
return T(data[0]);
}
};
template <typename T>
struct ReadFromBigEndian<T, 2> {
static T read(const uint8_t* data) {
return data[1] | (T(data[0]) << 8);
}
};
template <typename T>
struct ReadFromBigEndian<T, 4> {
static T read(const uint8_t* data) {
return (T(data[0]) << 24) | (T(data[1]) << 16) | (T(data[2]) << 8) | data[3];
}
};
template <typename T>
struct ReadFromBigEndian<T, 8> {
static T read(const uint8_t* data) {
return (T(data[0]) << 56) | (T(data[1]) << 48) | (T(data[2]) << 40) | (T(data[3]) << 32) |
(T(data[4]) << 24) | (T(data[5]) << 16) | (T(data[6]) << 8) | data[7];
}
};
// function to read primitive types from big-endian
// endian-independently
template <typename T>
T readFromBigEndian(const uint8_t* data) {
return ReadFromBigEndian<T, sizeof(T)>::read(data);
}
inline uint16_t readPIDFromBigEndian(const uint8_t* data) {
return m2tsext::readFromBigEndian<uint16_t>(data) & 0x1fff;
}
std::unordered_map<std::string, std::string> parseParameters (
int numberOfParameters, char* parameters[]);
inline void printErrorMessage(const std::string& msg) {
std::cerr << "\033[1;31m" << msg << "\033[0m\n";
}
}
<file_sep>/src/M2TSProcessor.h
#pragma once
#include "Error.h"
#include "PacketHeader.h"
#include <array>
#include <functional>
#include <vector>
namespace m2tsext {
using TDataProcessor = std::function<Result<std::monostate>(const uint8_t* data, size_t dataSize)>;
using TPacketData = std::array<uint8_t, PACKET_SIZE>;
// Class used for MPEG-2 TS splitting
class M2TSProcessor {
public:
// function that process any input packet from MPEG-2 TS
Result<std::monostate> processPacket(TPacketData& packetData);
// sets the function that is called for audio data from splitted TS
void setAudioDataProcessor(TDataProcessor&& aProcessor);
// sets the function that is called for video data from splitted TS
void setVideoDataProcessor(TDataProcessor&& vProcessor);
private:
uint16_t programPID{};
uint16_t videoPID{};
uint16_t audioPID{};
uint16_t videoPESLength{};
uint16_t audioPESLength{};
TDataProcessor audioDataProcessor;
TDataProcessor videoDataProcessor;
void processPATPacket(const PacketHeader& packetHeader);
void processPMTPacket(const PacketHeader& packetHeader);
Result<std::monostate> processAudioPacket(const PacketHeader& packetHeader);
Result<std::monostate> processVideoPacket(const PacketHeader& packetHeader);
};
}
<file_sep>/src/ElementaryStreamData.cpp
#include "ElementaryStreamData.h"
#include <unordered_set>
namespace {
enum ElementaryStreamType : uint8_t {
MPEG_1_VIDEO = 0x01,
MPEG_2_HIGHER_RATE_INTERLACED_VIDEO = 0x02,
MPEG_1_AUDIO = 0x03,
MPEG_2_HALVED_SAMPLE_RATE_AUDIO = 0x04,
MPEG_2_LOWER_BIT_RATE_AUDIO = 0x0f,
MPEG_4_H_263_BASED_VIDEO = 0x10,
MPEG_4_LOAS_MULTI_FORMAT_FRAMED_AUDIO = 0x11,
H_264_LOWER_BIT_RATE_VIDEO = 0x1b,
MPEG_4_RAW_AUDIO = 0x1c,
MPEG_4_AUXILIARY_VIDEO = 0x1e,
JPEG_2000_VIDEO = 0x21,
H_265_ULTRA_HD_VIDEO = 0x24,
PCM_FOR_BLUE_RAY_AUDIO = 0x80,
DOLBY_DIGITAL_FOR_BLUE_RAY_AUDIO = 0x81,
DOLBY_TRUE_HD_LOSSLESS_FOR_BLUE_RAY_AUDIO = 0x83,
DOLBY_DIGITAL_PLUS_FOR_BLUE_RAY_AUDIO = 0x84,
DTS_8_CHANNEL_FOR_BLUE_RAY_AUDIO = 0x85,
DTS_8_LOSSLESS_FOR_BLUE_RAY_AUDIO = 0x86,
DOLBY_DIGITAL_PLUS_AUDIO = 0x87,
DOLBY_DIGITAL_WITH_AES_AUDIO = 0xc1,
ADTS_AAC_WITH_AES_AUDIO = 0xcf,
MICROSOFT_WINDOWS_MEDIA_9_VIDEO = 0xea
};
const std::unordered_set<ElementaryStreamType, std::hash<uint8_t>> AUDIO_STREAMS = {
ElementaryStreamType::MPEG_1_AUDIO,
ElementaryStreamType::MPEG_2_HALVED_SAMPLE_RATE_AUDIO,
ElementaryStreamType::MPEG_2_LOWER_BIT_RATE_AUDIO,
ElementaryStreamType::MPEG_4_LOAS_MULTI_FORMAT_FRAMED_AUDIO,
ElementaryStreamType::MPEG_4_RAW_AUDIO,
ElementaryStreamType::PCM_FOR_BLUE_RAY_AUDIO,
ElementaryStreamType::DOLBY_DIGITAL_FOR_BLUE_RAY_AUDIO,
ElementaryStreamType::DOLBY_TRUE_HD_LOSSLESS_FOR_BLUE_RAY_AUDIO,
ElementaryStreamType::DOLBY_DIGITAL_PLUS_FOR_BLUE_RAY_AUDIO,
ElementaryStreamType::DTS_8_CHANNEL_FOR_BLUE_RAY_AUDIO,
ElementaryStreamType::DTS_8_LOSSLESS_FOR_BLUE_RAY_AUDIO,
ElementaryStreamType::DOLBY_DIGITAL_PLUS_AUDIO,
ElementaryStreamType::DOLBY_DIGITAL_WITH_AES_AUDIO,
ElementaryStreamType::ADTS_AAC_WITH_AES_AUDIO
};
const std::unordered_set<ElementaryStreamType, std::hash<uint8_t>> VIDEO_STREAMS = {
ElementaryStreamType::MPEG_1_VIDEO,
ElementaryStreamType::MPEG_2_HIGHER_RATE_INTERLACED_VIDEO,
ElementaryStreamType::MPEG_4_H_263_BASED_VIDEO,
ElementaryStreamType::H_264_LOWER_BIT_RATE_VIDEO,
ElementaryStreamType::MPEG_4_AUXILIARY_VIDEO,
ElementaryStreamType::JPEG_2000_VIDEO,
ElementaryStreamType::H_265_ULTRA_HD_VIDEO,
ElementaryStreamType::MICROSOFT_WINDOWS_MEDIA_9_VIDEO
};
}
namespace m2tsext {
bool ElementaryStreamData::isAudio() const {
return AUDIO_STREAMS.find(ElementaryStreamType(streamType())) != AUDIO_STREAMS.end();
}
bool ElementaryStreamData::isVideo() const {
return VIDEO_STREAMS.find(ElementaryStreamType(streamType())) != VIDEO_STREAMS.end();
}
}
<file_sep>/src/util.cpp
#include "util.h"
namespace m2tsext {
std::unordered_map<std::string, std::string> parseParameters(
int numberOfParameters, char* parameters[]) {
if ((numberOfParameters & 1) == 0) { // if number of parameters (but 0) is odd, return empty
return {};
}
std::unordered_map<std::string, std::string> toReturn;
for(auto i = 1; i < numberOfParameters; i += 2) {
toReturn[parameters[i]] = parameters[i+1];
}
return toReturn;
}
}
<file_sep>/src/Error.h
#pragma once
#include <string>
#include <variant>
namespace m2tsext {
class Error {
std::string description;
public:
Error(const char* description) : description(description) {}
Error(const std::string& description) : description(description) {}
const std::string& what() const { return description; }
};
template <typename T>
class Result {
std::variant<T, Error> result;
public:
Result(const T& value) : result(value) {}
Result(const Error& error) : result(error) {}
bool isOK() const { return result.index() == 0; }
const T& value() const { return std::get<0>(result); }
const Error& error() const { return std::get<1>(result); }
};
}<file_sep>/README.md
# TSDemux
tool to extract video and audio from the MPEG-2 TS stream. without 3rd libraries
## How to build
```
cd TSDemux
cmake .
make
```
## How to use
```
./ts-demux -i <input_ts_file> -a <audio_file_to_extract> -v <video_file_to_extract>
```
e.g.
```
./ts-demux -i awesome-video.ts -a awesome-audio.aac -v awesome-video-onlny.h264
```
## Design highlight
The tool reads the source file packet by packet (188 bytes), extracts video and audio related data and stores it into corresponding files provided with command line parameters.
All the main logic is performed by M2TSProcessor class.
Actually it processes only 3 types of TS packets and ignores others:
PAT - to detect the program translated and its PMT. Each time it comes, current program PID is updated.
PMT - to detect the elementary stream for video/audio. Each time it comes, PID of audio/video streams are updated
PES - elementary stream packet that contains raw data of vide and audio to be extracted. Each time it comes, the raw data is stored in the corresponding output stream.
|
79a249c1c36dd06b85d5c34cd8a89e1788a3109a
|
[
"Markdown",
"CMake",
"C++"
] | 18
|
C++
|
insanustu/TSDemux
|
f9d48d7212a35bbdd75ba5f7e8f1bce0361bcc99
|
fe03ff70ad9363fd670e2cbf9ce3f31828f78aa6
|
refs/heads/master
|
<repo_name>srsuryadev/key-value-store<file_sep>/src/trie.h
#include <iostream>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <stdint.h>
#include <string>
using namespace std;
typedef struct node node;
struct node {
node* kids[256];
char* value;
int value_len;
};
class Trie {
public:
Trie();
void put(string key, string value);
string get(string key);
vector<string> get_keys_for_prefix(string prefix);
private:
node* root;
node* new_node();
node* put(node* x, string key, string val, int depth);
node* get(node* x, string key, int depth);
void enumerate(vector<string>* strings, node* x);
};
<file_sep>/src/bloom_filter.h
#include <math.h>
#include <string>
#include <iostream>
#include <fstream>
using namespace std;
class BloomFilter {
double false_positive;
int size;
int hash_count;
vector<bool> bloom_filter;
std::ofstream out_index_;
std::ifstream in_index_;
string id_;
bool is_write_;
int hash_func(string elem, int num) {
int hash_code = 0;
int power_factor = 1;
for (int i = 0; i < elem.size(); i++) {
hash_code += (elem[i] - '0') * power_factor * num;
power_factor *= 2;
}
return hash_code;
}
public:
BloomFilter(string id, int num_elem, bool is_write_) {
this->false_positive = 0.1;
this->size = - (num_elem * log(false_positive) /
pow(log(2.0), 2.0));
this->hash_count = (size / num_elem) * log(2);
vector<bool> temp(size, false);
this->bloom_filter = temp;
this->id_ = id;
this->is_write_ = is_write_;
if (this->is_write_) {
this->out_index_.open(this->id_, std::ofstream::out);
} else {
this->in_index_.open(this->id_, std::ifstream::in);
}
}
void add(string elem) {
for (int i = 0; i < hash_count; i++) {
int hash_index = hash_func(elem, i) % size;
bloom_filter[hash_index] = true;
}
cout<<"ADDED to bloom filter\n";
}
bool check(string elem) {
for (int i = 0; i < hash_count; i++) {
int hash_code = hash_func(elem, i) % size;
if (!bloom_filter[hash_code]) {
return false;
}
}
return true;
}
void Read() {
int size;
in_index_.read((char*)&size, sizeof(int));
this->size = size;
for (int i = 0; i < size; i++) {
bool value;
in_index_.read((char*)&value, sizeof(bool));
this->bloom_filter[i] = value;
}
}
void Write() {
cout << "writing bloom data for " <<this->id_ << endl;
out_index_.write((char*)&this->size, sizeof(int));
for (int i = 0; i < this->size; i++) {
bool value = this->bloom_filter[i];
out_index_.write((char*)&value, sizeof(bool));
}
out_index_.flush();
}
~BloomFilter() {
if (this->is_write_) {
out_index_.close();
} else {
in_index_.close();
}
}
};<file_sep>/src/log_table.h
#include <stdint.h>
#include <map>
#include <string>
#include <sys/types.h>
#include <dirent.h>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/fstream.hpp>
#include <list>
#include <cstdlib>
#include <ctime>
#include "bloom_filter.h"
#include "sparse_index.h"
#include "record.h"
using namespace std;
class LogTable {
private:
static const string file_name_;
static const boost::filesystem::path data_path_;
std::ofstream out_logtable_;
std::ifstream in_logtable_;
string NextFileName() {
string new_file = file_name_ + "_" + std::to_string(time(0)) + "_" + to_string(clock());
return new_file;
}
void Create() {
this->file_name = this->NextFileName();
cout << "great" << endl;
cout << "created: " << this->file_name << endl;
string path = data_path_ .string() + "/" + this->file_name;
this->bloom_filter = new BloomFilter( data_path_ .string() + "/"
+ "bloom_" + this->file_name ,
500000, true);
this->sparse_index = new SparseIndex( data_path_.string() + "/"
+ "sparse_" + this->file_name, true);
out_logtable_.open(data_path_ .string() + "/" + this->file_name,
std::ofstream::out);
}
void Open(string file_name) {
this->file_name = file_name;
this->bloom_filter = new BloomFilter( data_path_ .string() + "/"
+ "bloom_"+ this->file_name ,
500000, false);
this->sparse_index = new SparseIndex( data_path_.string() + "/"
+ "sparse_" + this->file_name, false);
cout << "read bloom" <<endl;
//Load the index files
this->bloom_filter->Read();
this->sparse_index->Read();
in_logtable_.open(data_path_ .string() + "/" + file_name,
std::ifstream::in);
}
Record Read() {
Record record;
record.read(&this->in_logtable_);
return record;
}
void CloseOut() {
out_logtable_.close();
}
void CloseIn() {
in_logtable_.close();
}
public:
BloomFilter* bloom_filter;
SparseIndex* sparse_index;
string file_name;
LogTable();
LogTable(const LogTable &logtable);
~LogTable();
LogTable(string file_name);
void Write(list<Record> &records);
void Write(Record &record);
void Discard();
Record* Search(string key, int file_offset);
list<Record>* SearchPrefix(string key);
class Iterator {
LogTable* logtable;
Record *next_record;
public:
Iterator(LogTable* logtable) {
this->logtable = logtable;
}
bool HasNext() {
if (!logtable->in_logtable_.is_open()) {
next_record = 0;
return false;
}
next_record = new Record;
if (!next_record->read(&logtable->in_logtable_)) {
next_record = 0;
return false;
}
//TODO do check for end of file or checksum
return true;
}
Record* Move() {
if (HasNext())
return next_record;
return 0;
}
Record* Next(){
return next_record;
}
};
static Record* Get(string key) {
Record* record = 0;
list<LogTable>* log_tables = LogTable::GetLogTables();
std::list<LogTable>::iterator it;
for (it = log_tables->begin(); it != log_tables->end(); it++) {
// TODO: Use bloom filter to skip the log tables
cout << "Going to read and check bloom" << endl;
if (!it->bloom_filter->check(key)) {
cout << "Not present in bloom " << it->file_name << endl;
continue;
} else {
cout << "Key is present in bloom" << endl;
}
// TODO: if present, seek to the nearest offset using the sparse index
int key_offset = it->sparse_index->GetOffset(key);
Record* temp_record = it->Search(key, key_offset);
if (temp_record && !temp_record->get_value().is_deleted()) {
if (record) {
if (record->get_value().get_time() <
temp_record->get_value().get_time()) {
record = temp_record;
}
} else {
record = temp_record;
}
}
}
return record;
}
static list<Record>* GetPrefix(string key) {
list<Record>* records = new list<Record>();
list<LogTable>* log_tables = LogTable::GetLogTables();
std::list<LogTable>::iterator it;
for (it = log_tables->begin(); it != log_tables->end(); it++) {
// TODO: Use bloom filter to skip the log tables
// TODO: if present, seek to the nearest offset using the sparse index
list<Record>* record_tmp = it->SearchPrefix(key);
if (record_tmp->size() > 0) {
records->insert(records->end(), record_tmp->begin(),
record_tmp->end());
}
}
return records;
}
static list<LogTable>* GetLogTables() {
list<LogTable>* log_tables = new list<LogTable>();
DIR *dir;
struct dirent *ent;
if ((dir = opendir (data_path_.c_str())) != NULL) {
while ((ent = readdir (dir)) != NULL) {
string file_name = ent->d_name;
if (file_name.find(file_name_) == 0) {
cout << ent->d_name << endl;
LogTable log_table(ent->d_name);
log_tables->push_back(log_table);
}
}
closedir (dir);
}
return log_tables;
}
static void Merge() {
list<LogTable>* log_tables = LogTable::GetLogTables();
if (log_tables->size() < 2)
return;
LogTable *merge_table = new LogTable();
std::list<LogTable>::iterator it;
it = log_tables->begin();
LogTable logtable1 = *it;
it++;
LogTable logtable2 = *it;
it++;
LogTable::Merge2(merge_table, logtable1, logtable2);
logtable1.Discard();
logtable2.Discard();
string file_name = merge_table->file_name;
//Writing the index files
merge_table->bloom_filter->Write();
merge_table->sparse_index->Write();
delete merge_table;
string last_file_name = "";
while (it != log_tables->end()) {
cout<< "In merge loop" << endl;
merge_table = new LogTable();
LogTable log_table1(file_name);
LogTable::Merge2(merge_table, log_table1, *(it));
log_table1.Discard();
it->Discard();
file_name = merge_table->file_name;
merge_table->bloom_filter->Write();
merge_table->sparse_index->Write();
delete merge_table;
it++;
}
}
static LogTable* Merge2(LogTable* result, LogTable &log_table1, LogTable &log_table2) {
LogTable *merged_table = result;
LogTable::Iterator *it1 = new Iterator(&log_table1);
LogTable::Iterator *it2 = new Iterator(&log_table2);
Record *record1, *record2;
record1 = it1->Move();
record2 = it2->Move();
while (record1 != 0 && record2 != 0) {
if (record1->get_key()
.compare(record2->get_key()) < 0) {
merged_table->Write(*record1);
record1 = it1->Move();
} else if (record1->get_key()
.compare(record2->get_key()) > 0) {
merged_table->Write(*record2);
record2 = it2->Move();
} else {
if (record1->get_value().get_time() > record2->get_value().get_time()) {
merged_table->Write(*record1);
} else {
merged_table->Write(*record2);
}
record1 = it1->Move();
record2 = it2->Move();
}
}
while (record1 != 0) {
merged_table->Write(*record1);
record1 = it1->Move();
}
while (record2 != 0) {
merged_table->Write(*record2);
record2 = it2->Move();
}
return merged_table;
}
};<file_sep>/src/main.cc
//#include "wal.h"
//#include "record.h"
#include "log_table.h"
#include <iostream>
using namespace std;
int main() {
LogTable *log_table = new LogTable();
cout << "good: " << log_table->file_name << endl;
return 0;
/*
WAL *wal = WAL::GetInstance();
wal->CreateWriteStream();
Record record;
Value value;
value.set_value("Val1");
record.set_key("Key1");
record.set_value(value);
wal->Append(record);
cout<<"WROTE RECORD\n";
Record record2;
Value value2;
value2.set_value("Val2");
record2.set_key("Key2");
record2.set_value(value2);
wal->Append(record2);
cout<<"WROTE RECORD\n";
Record record3;
Value value3;
value3.set_value("Val3");
record3.set_key("Key3");
record3.set_value(value3);
wal->Append(record3);
cout<<"WROTE RECORD\n";
wal->CloseWriteStream();
WAL::Iterator wal_iter(wal);
wal->OpenReadStream();
while(wal_iter.HasNext()) {
Record rec = wal_iter.Next();
cout<<"READ KEY: "<<rec.get_key()<<endl;
}
wal->CloseReadStream();
wal->Discard();
return 0;*/
}<file_sep>/src/skiplist.h
/*******************************************************************************
* Copyright 2020 <NAME> <<EMAIL>> *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder nor the names of its contributors*
* may be used to endorse or promote products derived from this software without*
* specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE *
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER*
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
********************************************************************************
* *
* File: skiplist.h *
* *
* Description: A concurrent skiplist based on the paper 'Lock-Free Linked Lists*
* and Skip Lists' by <NAME> and <NAME> (23rd Annual ACM *
* SIGACT-SIGOPS Symposium on Principles Of Distributed Computing, 2004) *
* *
*******************************************************************************/
#ifndef SKIPLIST_H
#define SKIPLIST_H
#include <iostream>
#include <cstdlib>
#include <cstdint>
#include <cstring>
#include <stdint.h>
#include <stdlib.h>
#include <string>
#include <random>
#include <atomic>
#include <list>
#include "record.h"
#include "value.h"
// Adapted from linux/blob/master/arch/x86/include/asm/cmpxchg.h
#define x86_64_cmpxchg(ptr, old, new, lock) \
({ \
volatile uintptr_t __ret; \
volatile uintptr_t __old = (old); \
volatile uintptr_t __new = (new); \
volatile uintptr_t *__ptr = (volatile uintptr_t *)(ptr); \
asm volatile(lock "cmpxchgq %2,%1" \
: "=a" (__ret), "+m" (*__ptr) \
: "r" (__new), "0" (__old) \
: "memory"); \
__ret; \
})
#define CAS(ptr, old, new) \
x86_64_cmpxchg((ptr), (old), (new), "lock; ")
using namespace std;
typedef struct node node;
typedef struct find_start_res find_start_res;
typedef struct search_res search_res;
typedef struct try_flag_node_res try_flag_node_res;
typedef struct insert_node_res insert_node_res;
#define MAXLEVEL 16
#define KEYLENGTH 128
#define DUPLICATE_KEY 0
#define NO_SUCH_KEY 1
#define NO_SUCH_NODE 2
#define DELETED 3
#define IN 4
#define LARGEST_KEY "LARGEST_KEY"
#define SMALLEST_KEY "SMALLEST_KEY"
#define CACHE_LINE_SIZE 64
#define EXTRACT_MARK(x) ((((uintptr_t)x >> 1) << 63) >> 63)
#define EXTRACT_FLAG(x) (((uintptr_t)x << 63) >> 63)
#define PT(x) (node*)(void*)(((uintptr_t)x >> 2) << 2)
struct node {
char* key;
node* back_link;
node* successor;
node* up;
node* down;
node* tower_root;
char* value;
};
struct find_start_res {
node* lowest_node;
char level;
};
struct search_res {
node* prev;
node* next;
};
struct try_flag_node_res {
node* prev_node;
char res;
bool success;
};
struct insert_node_res {
node* prev;
node* new_node;
};
class SkipList {
public:
std::atomic<int> count;
~SkipList();
SkipList();
void put(string key, string value);
string get(string key);
vector<string> get_keys_for_prefix(string prefix);
list<Record> get_all_data();
private:
node* head_tower[MAXLEVEL + 1];
node* tail_tower[MAXLEVEL + 1];
node* head;
node* tail;
char level;
double probability = 0.5;
char random_level();
insert_node_res insert_node(node* new_node, node* prev_node,
node* next_node, string value, char level);
node* insert(string key, string value);
node* create_new_node(string key, string value, node* down,
node* tower_root);
node* create_new_node(string key, node* down, node* tower_root);
try_flag_node_res try_flag_node(node* prev_node, node* target_node);
search_res search_right_other(string key, node* current_node,
char level);
search_res search_right(string key, node* current_node,
char level);
find_start_res find_start(char level);
search_res search_to_level(string key, char level);
node* search(string key);
node* deletion(string key);
node* deletion_node(node* prev_node, node* del_node);
void help_marked(node* prev_node, node* del_node);
void help_flagged(node* prev_node, node* del_node);
void try_mark(node* del_node);
void enumerate(vector<string>* strings, node* x, string prefix);
};
#endif
<file_sep>/src/kvserver.cpp
#include <string>
#include <iostream>
#include <sys/time.h>
#include "kvstore.h"
#include <signal.h>
using namespace std;
#include <grpcpp/grpcpp.h>
#include "kvstore.grpc.pb.h"
using grpc::Server;
using grpc::ServerBuilder;
using grpc::ServerContext;
using grpc::ServerWriter;
using grpc::Status;
using kvstore::KVStore;
using kvstore::KeyRequest;
using kvstore::KeyValueRequest;
using kvstore::SetResponse;
using kvstore::ValueResponse;
struct timeval stop, start;
static volatile int A = 0, B = 0, C = 0;
class KVStoreImpl final : public KVStore::Service {
private:
KeyValueStore db;
public:
Status set(ServerContext *context, const KeyValueRequest *key_val_req, SetResponse *set_res) override {
A++;
string key = key_val_req->key();
string value = key_val_req->value();
bool result = db.set(key, value);
set_res->set_issuccessful(result);
return Status::OK;
}
Status getPrefix(ServerContext *context, const KeyRequest *key_req, ServerWriter<ValueResponse> *res_writer) override {
C++;
string key = key_req->key();
cout<<"Received GET_PREFIX request --- Key: "<<key<<endl;
int i;
for(i=0; i<10; i++) {
string val = "Value" + to_string(i);
cout<<"Writing "<<val<<" to stream\n";
ValueResponse val_res;
val_res.set_value(val);
res_writer->Write(val_res);
}
return Status::OK;
}
};
void runServer() {
ServerBuilder server_builder;
const string address("0.0.0.0:5000");
server_builder.AddListeningPort(address, grpc::InsecureServerCredentials());
KVStoreImpl KVStoreService;
server_builder.RegisterService(&KVStoreService);
unique_ptr<Server> server(server_builder.BuildAndStart());
gettimeofday(&stop, NULL);
cout<< (stop.tv_sec - start.tv_sec) * 1000000 + stop.tv_usec - start.tv_usec<<endl;
cout<<"Server up and running on port: "<<address<<endl;
server->Wait();
}
void handler(int dummy) {
cout<<"\nTotal SET: "<<A<<endl;
cout<<"Total GET: "<<B<<endl;
cout<<"Total GET_PREFIX: "<<C<<endl;
exit(0);
}
int main(int argc, char** argv) {
gettimeofday(&start, NULL);
signal(SIGINT, handler);
runServer();
return 0;
}
<file_sep>/src/record.cc
#include "record.h"
void Record::set_key(string key) {
this->key = key;
}
void Record::set_value(Value value) {
this->value = value;
}
string Record::get_key() {
return this->key;
}
Value Record::get_value() {
return this->value;
}
void Record::write(ofstream *out) {
cout<<"Writing Record BEGIN\n";
unsigned int checksum = CalculateChecksum(*this);
out->write((char *) &checksum, sizeof(checksum));
size_t key_size = key.size();
out->write((char *) &key_size, sizeof(key_size));
out->write((char *) key.data(), key_size);
string val = value.get_value();
(*out) << val.size();
out->write(val.data(), val.size());
(*out) << value.get_time();
(*out) << value.is_deleted();
cout<<"Writing Record END\n";
}
void Record::write(FILE* &out) {
unsigned int checksum = CalculateChecksum(*this);
fwrite(&checksum, sizeof(checksum), 1, out);
int key_size = key.size();
fwrite(&key_size, sizeof(key_size), 1, out);
fwrite(key.data(), key_size, 1, out);
int val_size = value.get_value().size();
fwrite(&val_size, sizeof(val_size), 1, out);
fwrite(value.get_value().data(), val_size, 1, out);
long ts = value.get_time();
fwrite(&ts, sizeof(ts), 1, out);
bool deleted_flag = value.is_deleted();
fwrite(&deleted_flag, sizeof(deleted_flag), 1, out);
}
bool Record::read(ifstream *in) {
cout<<in->eof()<<endl;
if(in->eof())
return false;
unsigned int file_checksum;
(*in) >> file_checksum;
cout<<in->fail()<<endl;
if(in->fail())
return false;
cout<<file_checksum<<endl;
int str_size;
(*in) >> str_size;
if(in->fail())
return false;
string key;
key.resize(str_size);
in->read(&key[0], str_size);
if(in->fail())
return false;
(*in) >> str_size;
if(in->fail())
return false;
string val;
val.resize(str_size);
in->read(&val[0], str_size);
if(in->fail())
return false;
long ts;
(*in) >> ts;
if(in->fail())
return false;
bool delete_flag;
(*in) >> delete_flag;
if(in->fail())
return false;
Value value = Value(val, ts, delete_flag);
this->key = key;
this->value = value;
if(file_checksum != CalculateChecksum(*this)) {
cout<<"CHECKSUM MISMATCH\n";
return false;
} else {
cout<<"CHECKSUM MATCH\n";
return true;
}
}
bool Record::read(FILE* &in) {
//cout<<in->eof()<<endl;
if(feof(in))
return false;
unsigned int file_checksum;
size_t x = fread(&file_checksum, sizeof(file_checksum), 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
//cout<<file_checksum<<endl;
int str_size;
x = fread(&str_size, sizeof(str_size), 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
string key;
key.resize(str_size);
x = fread(&key[0], str_size, 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
x = fread(&str_size, sizeof(str_size), 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
string val;
val.resize(str_size);
x = fread(&val[0], str_size, 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
long ts;
x = fread(&ts, sizeof(ts), 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
bool delete_flag;
x = fread(&delete_flag, sizeof(delete_flag), 1, in);
if(x == 0 && (ferror(in) || feof(in)))
return false;
Value value = Value(val, ts, delete_flag);
this->key = key;
this->value = value;
if(file_checksum != CalculateChecksum(*this)) {
//cout<<"CHECKSUM MISMATCH\n";
return false;
} else {
//cout<<"CHECKSUM MATCH\n";
return true;
}
}
unsigned int Record::CalculateChecksum(Record record) {
boost::crc_32_type crc32;
string key = record.get_key();
crc32.process_bytes(key.data(), key.length());
crc32.process_bytes(record.get_value().get_value().data(), record.get_value().get_value().length());
int timestamp = record.get_value().get_time();
crc32.process_bytes(×tamp, sizeof(timestamp));
bool delete_flag = record.get_value().is_deleted();
crc32.process_bytes(&delete_flag, sizeof(delete_flag));
return crc32.checksum();
}
<file_sep>/src/sparse_index.cc
#include "sparse_index.h"
const int SparseIndex::SPARSENESS = 1000;
SparseIndex::SparseIndex(string id, bool is_write) {
this->id_ = id;
this->is_write_ = is_write;
this->counter = 0;
if (this->is_write_) {
out_index_.open(id, std::ofstream::out);
} else {
in_index_.open(id, std::ifstream::in);
}
}
int SparseIndex::GetOffset(string key) {
auto it = sparse_index_.upper_bound(key);
if(it == sparse_index_.begin())
return 0;
it--;
//cout<<"Returning offset: "<<it->second<<endl;
return it->second;
}
void SparseIndex::put(string key, int offset) {
if(counter % SPARSENESS == 0) {
//cout<<"Sparse Index created at this point --- "<<key<<" "<<offset<<endl;
sparse_index_[key] = offset;
}
counter++;
cout<<"Added to sparse index\n";
}
void SparseIndex::Read() {
//Reading only the map
int size = 0;
int v = 0;
char k[129];
while(in_index_.read((char*)&size, sizeof(int))) {
in_index_.read(k, size);
k[size] = '\0';
in_index_.read((char*)&v, sizeof(int));
this->sparse_index_[string(k)] = v;
}
}
void SparseIndex::Write() {
//Writing only the map
cout << "writing sparse index for " <<this->id_ << endl;
for(auto it = sparse_index_.begin(); it!=sparse_index_.end(); it++) {
int size = it->first.length();
out_index_.write((char *) &size, sizeof(int));
out_index_.write(it->first.c_str(), size);
out_index_.write((char*)&(it->second), sizeof(int));
}
out_index_.flush();
}
SparseIndex::~SparseIndex() {
if (this->is_write_) {
out_index_.close();
} else {
in_index_.close();
}
}
<file_sep>/src/ephemeral_table.h
#include<stdint.h>
#include <map>
#include <string>
using namespace std;
class EphemeralTable {
public:
~EphemeralTable();
EphemeralTable get_instance();
bool set(string key, string value);
string get(string key);
string get_prefix(string key);
private:
map<string, string> table;
EphemeralTable();
};<file_sep>/src/kvstore.cc
#include "kvstore.h"
mutex KeyValueStore::_mutex;
KeyValueStore::KeyValueStore() {
first_skip_list = new SkipList();
second_skip_list = new SkipList();
current_skip_list = first_skip_list;
prev_skip_list = 0;
//While recover merge the log tables;
_mutex.lock();
// collate the existing logtables on recover
LogTable::Merge();
cout << "goint to create WAL" << endl;
// If the WAL has records use it to recover
WAL *wal = WAL::GetInstance();
cout<<"WAL Created\n";
wal->OpenReadStream();
cout<<"WAL Opened\n";
WAL::Iterator *it = new WAL::Iterator(wal);
cout<<"Iter ready\n";
while (it->HasNext()) {
//cout<<"Reading from WAL\n";
Record record = it->Next();
string key = record.get_key();
string value = record.get_value().get_value();
current_skip_list->put(key, value);
}
wal->CloseReadStream();
wal->CreateWriteStream();
cout << "created wal" << endl;
_mutex.unlock();
}
bool KeyValueStore::set(string key, string value) {
cout<<"Received SET request --- Key: "<<key<<" Value: "<<value<<endl;
WAL* wal = WAL::GetInstance();
Record record;
record.set_key(key);
Value _val;
_val.set_value(value);
record.set_value(_val);
wal->Append(record);
current_skip_list->put(key, value);
if (++current_skip_list->count == CUT_OFF_COUNT) {
// TODO: force first list to disk
// use the other list
// we don't actually need a mutex because count is atomic
_mutex.lock();
if ((uintptr_t)current_skip_list == (uintptr_t)first_skip_list) {
cout<<"----------IF PART---------"<<endl;
current_skip_list = second_skip_list;
prev_skip_list = first_skip_list;
first_skip_list = new SkipList();
} else {
cout<<"----------ELSE PART---------"<<endl;
current_skip_list = first_skip_list;
prev_skip_list = second_skip_list;
second_skip_list = new SkipList();
}
list<Record> records = prev_skip_list->get_all_data();
// reset the prevskip list
delete prev_skip_list;
prev_skip_list = 0;
_mutex.unlock();
//TODO: In future, we can use another thread to put
// the skiplist contents to the logtable;
LogTable logtable;
cout << "write data to logtable" << endl;
logtable.Write(records);
//Truncate the existing WAL and create a fresh
//wal->OpenReadStream();
}
return true;
}
string KeyValueStore::get(string key) {
cout<<"Received GET request --- Key: "<<key<<endl;
string value = current_skip_list->get(key);
if (value.size() == 0 && prev_skip_list != 0) {
value = prev_skip_list->get(key);
if (value.size() > 0)
return value;
}
if (value.size() == 0) {
Record* record = LogTable::Get(key);
return record->get_value().get_value();
}
return current_skip_list->get(key);
}
vector<string> KeyValueStore::get_prefix(string prefix_key) {
vector<string> ret_val;
cout<<"Received GET request for prefix --- Key: "<< prefix_key <<endl;
return current_skip_list->get_keys_for_prefix(prefix_key);
}
<file_sep>/src/log_table.cc
#include "log_table.h"
const string LogTable::file_name_ = "logtable";
const boost::filesystem::path LogTable::data_path_ = "data";
LogTable::LogTable() {
cout<<"created file in write mode"<<endl;
this->Create();
}
LogTable::LogTable(const LogTable &logtable) {
this->file_name = logtable.file_name;
this->Open(this->file_name);
}
void LogTable::Discard() {
if (remove((data_path_.string() + "/" + this->file_name).c_str()) == 0)
cout << "successfully deleted: " << this->file_name << endl;
else
cout << "unable delete: " << this->file_name << endl;
if (remove((data_path_.string() + "/" + "bloom_" + this->file_name).c_str()) == 0)
cout << "successfully deleted: " << "bloom_" + this->file_name << endl;
else
cout << "unable delete: " << "bloom_" + this->file_name << endl;
if (remove((data_path_.string() + "/" + "sparse_" + this->file_name).c_str()) == 0)
cout << "successfully deleted: " << "sparse_" + this->file_name << endl;
else
cout << "unable delete: " << "sparse_" + this->file_name << endl;
}
LogTable::LogTable(string file_name) {
this->file_name = file_name;
this->Open(this->file_name);
}
LogTable:: ~LogTable() {
if (!this->in_logtable_.is_open())
this->CloseIn();
if (!this->out_logtable_.is_open()) {
this->CloseOut();
}
}
void LogTable::Write(list<Record> &records) {
std::list<Record>::iterator it;
for (it = records.begin(); it != records.end(); it++) {
cout<<"write record with key: "<<it->get_key()<<endl;
//this->bloom_filter->add(it->get_key());
this->sparse_index->put(it->get_key(), out_logtable_.tellp());
it->write(&this->out_logtable_);
}
cout<< "written data" << endl;
this->out_logtable_.flush();
//this->bloom_filter->Write();
this->sparse_index->Write();
}
void LogTable::Write(Record &record) {
this->bloom_filter->add(record.get_key());
this->sparse_index->put(record.get_key(), out_logtable_.tellp());
record.write(&this->out_logtable_);
cout<< "written record" << endl;
this->out_logtable_.flush();
}
Record* LogTable::Search(string key, int file_offset = ios_base::beg) {
this->in_logtable_.seekg(file_offset);
LogTable::Iterator *it = new Iterator(this);
while (it->HasNext()) {
Record* record = it->Next();
cout << "Key: " << record->get_key() << endl;
if (record->get_key().compare(key) == 0) {
return record;
}
}
return NULL;
}
list<Record>* LogTable::SearchPrefix(string key) {
list<Record>* records = new list<Record>();
LogTable::Iterator *it = new Iterator(this);
while (it->HasNext()) {
Record* record = it->Next();
if (record->get_key().find(key) == 0) {
records->push_back(*record);
}
}
return records;
}
<file_sep>/test/test.cc
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <vector>
#include "skiplist.h"
using namespace std;
#define NUM_THREADS 5
#define NUM_OP_PER_THREAD 10
#define MAX_LEN_STRING 30
#define WRITE_OP 0
#define GET_OP 1
#define GET_PREFIX 2
void generate_random_string(char *s, int len) {
static const char valid_chars[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"012345678_$-@#:;,.";
int i;
for (i = 0; i < len; i++) {
s[i] = valid_chars[rand() % 61];
}
s[i] = '\0';
}
string generate_random_string() {
int len = 0;
while (len == 0)
len = rand() % MAX_LEN_STRING;
char* s = (char*) malloc(len * sizeof(char) + 1);
generate_random_string(s, len);
string result = s;
return result;
}
void *call(void *listptr) {
SkipList* list = (SkipList*)listptr;
vector<string> keys;
int count = 0;
while(count < NUM_OP_PER_THREAD) {
int op = rand() % 3;
if (op == WRITE_OP) {
string key = generate_random_string();
string value = generate_random_string();
keys.push_back(key);
cout<< "key: " << key << " Value: " << value << endl;
list->put(key, value);
} else if (op == GET_OP && keys.size() > 0) {
int index = rand() % keys.size();
string key = keys[index];
cout << "value: " << list->get(key) << " for key " << key << endl;
} else if (op == GET_PREFIX && keys.size() > 0) {
// Testing for get() suffices if deletion isn't done
}
count++;
}
pthread_exit(NULL);
}
int main () {
pthread_t threads[NUM_THREADS];
SkipList a;
for( int i = 0; i < NUM_THREADS; i++ ) {
int rc = pthread_create(&threads[i], NULL, call, (void *)&a);
if (rc) {
cout << "Not able to create thread" << endl;
exit(-1);
}
}
pthread_exit(NULL);
}
<file_sep>/README.md
# key-value-store<file_sep>/src/kvclient.cpp
#include <iostream>
#include <cstdlib>
#include <pthread.h>
#include <vector>
#include <grpcpp/grpcpp.h>
#include "kvstore.grpc.pb.h"
using namespace std;
#define WRITE_OP 0
#define GET_OP 1
#define GET_PREFIX 2
using grpc::Channel;
using grpc::ClientContext;
using grpc::ClientReader;
using grpc::Status;
using kvstore::KVStore;
using kvstore::KeyRequest;
using kvstore::KeyValueRequest;
using kvstore::SetResponse;
using kvstore::ValueResponse;
int NUM_THREADS;
int NUM_OP_PER_THREAD;
int MAX_LEN_STRING;
int MODE;
string ADDRESS;
void generate_random_string(char *s, int len) {
static const char valid_chars[] =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
"012345678_$-@#:;,.";
int i;
for (i = 0; i < len; i++) {
s[i] = valid_chars[rand() % 61];
}
s[i] = '\0';
}
string generate_random_string() {
int len = 0;
while (len == 0)
len = rand() % MAX_LEN_STRING;
char* s = (char*) malloc(len * sizeof(char) + 1);
generate_random_string(s, len);
string result = s;
return result;
}
class KVStoreClient {
private:
unique_ptr<KVStore::Stub> stub_;
public:
KVStoreClient(shared_ptr<Channel> channel) : stub_(KVStore::NewStub(channel)) {}
bool set(const string key, const string value) {
ClientContext context;
KeyValueRequest req;
req.set_key(key);
req.set_value(value);
SetResponse res;
Status status = stub_->set(&context, req, &res);
if(status.ok()){
return res.issuccessful();
} else {
cout<<status.error_code()<<": "<<status.error_message()<<endl;
return false;
}
}
string get(const string key) {
ClientContext context;
KeyRequest req;
req.set_key(key);
ValueResponse res;
Status status = stub_->get(&context, req, &res);
if(status.ok()){
return res.value();
} else {
cout<<status.error_code()<<": "<<status.error_message()<<endl;
return "";
}
}
bool getPrefix(const string key, vector<string> &result) {
ClientContext context;
KeyRequest req;
req.set_key(key);
unique_ptr<ClientReader<ValueResponse>> res_reader(stub_->getPrefix(&context, req));
ValueResponse val_res;
while(res_reader->Read(&val_res)) {
//cout<<"Received value in stream: "<<val_res.value()<<endl;
result.push_back(val_res.value());
}
Status status = res_reader->Finish();
if (status.ok()) {
return true;
} else {
cout<<"getPrefix RPC Failed\n";
return false;
}
}
};
void printStringVector(vector<string> &V) {
int i;
for(i=0; i<V.size(); i++) {
cout<<V[i]<<" ";
}
cout<<endl;
}
void* runClient(void *args) {
const string address(ADDRESS);
KVStoreClient KVStoreClient(grpc::CreateChannel(
address,
grpc::InsecureChannelCredentials()
));
int i;
vector<string> keys;
for(i=0; i<NUM_OP_PER_THREAD; i++) {
int op = WRITE_OP;
if(MODE == 2) {
op = rand() % 3;
} else if (MODE == 1) {
op = GET_OP;
}
if (op == WRITE_OP) {
string key = generate_random_string();
string value = generate_random_string();
keys.push_back(key);
cout<< "Setting --- key: " << key << " Value: " << value << endl;
cout<<"Success: "<<KVStoreClient.set(key, value)<<endl;
} else if (op == GET_OP && keys.size() > 0) {
int index = rand() % keys.size();
string key = keys[index];
cout << "Getting --- value: " << KVStoreClient.get(key) << " for key " << key << endl;
}
}
return 0;
}
int main(int argc, char *argv[]) {
if(argc != 6) {
cout<<"Insufficient number of arguments\n";
return 0;
}
ADDRESS = argv[1];
NUM_THREADS = stoi(argv[2]);
NUM_OP_PER_THREAD = stoi(argv[3]);
MAX_LEN_STRING = stoi(argv[4]);
MODE = stoi(argv[5]);
pthread_t threads[NUM_THREADS];
int i;
for(i=0; i<NUM_THREADS; i++) {
int rc = pthread_create(&threads[i], NULL, runClient, NULL);
if (rc) {
cout << "Not able to create thread" << endl;
exit(-1);
}
}
for(i=0; i<NUM_THREADS; i++) {
pthread_join(threads[i], NULL);
}
return 0;
}
<file_sep>/src/wal.cc
#include "wal.h"
WAL* WAL::wal = 0;
mutex WAL::_mutex;
WAL::WAL() {
file_name = "log";
}
WAL* WAL::GetInstance() {
//To be thread safe
lock_guard<mutex> lock(WAL::_mutex);
if (!wal) {
wal = new WAL;
//wal->CreateWriteStream();
//wal->OpenReadStream();
}
return wal;
}
//Truncates the existing wal file if existed
void WAL::CreateWriteStream() {
_mutex.lock();
wal_out = fopen(this->file_name.c_str(), "w");
_mutex.unlock();
}
void WAL::OpenReadStream() {
wal_in = fopen(this->file_name.c_str(), "r");
}
void WAL::CloseWriteStream() {
fclose(wal_out);
}
void WAL::CloseReadStream() {
fclose(wal_in);
}
bool WAL::Discard() {
//To be thread safe
_mutex.lock();
if (remove(this->file_name.c_str())) {
return true;
}
_mutex.unlock();
return false;
}
void WAL::Append(Record record) {
//To be thread safe
_mutex.lock();
record.write(wal_out);
_mutex.unlock();
fsync(fileno(wal_out));
}
WAL::Iterator::Iterator(WAL *_wal) {
wal = _wal;
next_record = 0;
counter = 0;
T = 0;
FILE *p_file = NULL;
p_file = fopen(wal->file_name.c_str(), "r");
struct stat info;
stat(wal->file_name.c_str(), &info);
file_size = info.st_size;
cout<<"File size: "<<file_size<<endl;
fclose(p_file);
}
bool WAL::Iterator::HasNext() {
//false if file not open
if(wal->wal_in == NULL) {
cout<<"File opening failed\n";
return false;
}
if(T == file_size) {
cout<<"EOF\n";
return false;
}
if(next_record != 0)
return true;
//cout<<"Gonna read record\n";
next_record = new Record;
if(!next_record->read(wal->wal_in)) {
//If false because of checksum match, continue to read next records.
return false;
}
T += sizeof(*next_record);
return true;
}
Record WAL::Iterator::Next() {
Record record = *next_record;
delete next_record;
next_record = 0;
counter++;
if(counter % 10000 == 0)
cout<<"Sending "<<counter<<endl;
return record;
}
<file_sep>/src/wal.h
#ifndef WAL_H
#define WAL_H
#include "record.h"
#include <unistd.h>
#include <stdio.h>
#include <mutex>
#include <sys/stat.h>
class WAL {
private:
static WAL *wal;
static mutex _mutex;
string file_name;
FILE* wal_out;
FILE* wal_in;
WAL();
public:
static WAL* GetInstance();
void CreateWriteStream();
void OpenReadStream();
void CloseWriteStream();
void CloseReadStream();
bool Discard();
void Append(Record record);
class Iterator {
private:
WAL *wal;
Record *next_record;
size_t file_size;
int counter;
int T;
public:
Iterator(WAL*);
bool HasNext();
Record Next();
};
};
#endif
<file_sep>/src/Makefile
CC = g++
CFLAGS = -g -Wall -Wextra
RM = rm -rf
LDFLAGS = -L/usr/local/lib `pkg-config --libs protobuf grpc++`\
-lgrpc++_reflection\
-ldl -lboost_system -l pthread
CPPFLAGS += `pkg-config --cflags protobuf grpc` -g
CXXFLAGS += -std=c++17 -g
BOOSTFLAGS = -lboost_system
GRPC_CPP_PLUGIN = grpc_cpp_plugin
GRPC_CPP_PLUGIN_PATH ?= `which $(GRPC_CPP_PLUGIN)`
DB = kvstore.o value.o record.o wal.o log_table.o skiplist.o sparse_index.o
default: kvclient kvserver
kvclient: kvstore.pb.o kvstore.grpc.pb.o kvclient.o
$(CXX) $^ $(LDFLAGS) -o $@
kvserver: kvstore.pb.o kvstore.grpc.pb.o $(DB) kvserver.o
$(CXX) $^ $(LDFLAGS) -o $@
kvstore: kvstore.o value.o record.o wal.o log_table.o #main.o
$(CC) $(CFLAGS) $^ -o $@
#%.o: %.cc
# $(CC) $(CFLAGS) -c $<
%.grpc.pb.cc: %.proto
protoc --grpc_out=. --plugin=protoc-gen-grpc=$(GRPC_CPP_PLUGIN_PATH) $<
%.pb.cc: %.proto
protoc --cpp_out=. $<
clean:
rm -f *.o *.pb.cc *.pb.h kvclient kvserver
<file_sep>/src/sparse_index.h
#ifndef SPARSE_INDEX_H
#define SPARSE_INDEX_H
#include <map>
#include <iostream>
#include <fstream>
using namespace std;
class SparseIndex {
private:
static const int SPARSENESS;
map<string, int> sparse_index_;
int counter;
std::ofstream out_index_;
std::ifstream in_index_;
string id_;
bool is_write_;
public:
SparseIndex(string, bool);
int GetOffset(string);
void put(string, int);
void Read();
void Write();
~SparseIndex();
};
#endif
<file_sep>/src/value.h
#ifndef VALUE_H
#define VALUE_H
#include <string>
#include <iostream>
#include <fstream>
#include <ctime>
using namespace std;
class Value {
private:
string value;
long timestamp;
bool deleted;
public:
Value();
Value(string, long, bool);
string get_value();
long get_time();
bool is_deleted();
void set_value(string value);
void mark_deleted();
//Not Required. Can be removed
void write(ofstream out);
//Not Required. Can be removed
void read(ifstream in);
};
#endif
<file_sep>/src/kvstore.h
#ifndef KVSTORE_H
#define KVSTORE_H
#include <string>
#include <iostream>
#include <vector>
#include "skiplist.h"
#include "log_table.h"
#include "wal.h"
#include "value.h"
#include <mutex>
using namespace std;
// count at which to abandon current skiplist
#define CUT_OFF_COUNT 500000
class KeyValueStore {
public:
KeyValueStore();
bool set(string key, string value);
string get(string key);
vector<string> get_prefix(string prefix_key);
private:
static mutex _mutex;
SkipList* current_skip_list;
SkipList* prev_skip_list;
SkipList* first_skip_list;
SkipList* second_skip_list;
};
#endif
<file_sep>/src/skiplist.cc
/*******************************************************************************
* Copyright 2020 <NAME> <<EMAIL>> *
* *
* Redistribution and use in source and binary forms, with or without *
* modification, are permitted provided that the following conditions are met: *
* *
* 1. Redistributions of source code must retain the above copyright notice, *
* this list of conditions and the following disclaimer. *
* *
* 2. Redistributions in binary form must reproduce the above copyright notice, *
* this list of conditions and the following disclaimer in the documentation *
* and/or other materials provided with the distribution. *
* *
* 3. Neither the name of the copyright holder nor the names of its contributors*
* may be used to endorse or promote products derived from this software without*
* specific prior written permission. *
* *
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" *
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE *
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE *
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE *
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR *
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF *
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER*
* IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) *
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE *
* POSSIBILITY OF SUCH DAMAGE. *
* *
********************************************************************************
* *
* File: skiplist.cc *
* *
* Description: A concurrent skiplist based on the paper 'Lock-Free Linked Lists*
* and Skip Lists' by <NAME> and <NAME> (23rd Annual ACM *
* SIGACT-SIGOPS Symposium on Principles Of Distributed Computing, 2004) *
* *
*******************************************************************************/
#include "skiplist.h"
SkipList::SkipList() {
char* x_key = (char*)malloc(KEYLENGTH);
memset(x_key, 0, KEYLENGTH);
char* y_key = (char*)malloc(KEYLENGTH);
memset(y_key, -1U, KEYLENGTH);
node* prev_x = NULL;
node* prev_y = NULL;
for (int i = 0; i <= MAXLEVEL; i++) {
node* x = (node*)malloc(sizeof(node));
head_tower[i] = x;
x->key = x_key;
node* y = (node*)malloc(sizeof(node));
y->key = y_key;
tail_tower[i] = y;
x->value = y->value = NULL;
x->back_link = NULL;
y->back_link = x;
x->down = prev_x;
if (prev_x) {
prev_x->up = x;
}
y->down = prev_y;
if (prev_y) {
prev_y->up = y;
}
x->successor = y;
y->successor = NULL;
prev_x = x;
prev_y = y;
}
prev_x->up = prev_x;
prev_y->up = prev_y;
head = head_tower[0];
tail = tail_tower[0];
count = 0;
}
SkipList::~SkipList() {
node* x = head->successor;
while ((uintptr_t)x != (uintptr_t)tail) {
std::free(x->key);
std::free(x->value);
node* temp = x;
x = x->successor;
node* temp_up;
while ((temp_up = temp->up) != NULL) {
free(temp);
temp = temp_up;
}
free(temp);
}
std::free(head->key);
std::free(tail->key);
for (int i = 0; i <= MAXLEVEL; i++) {
free(head_tower[i]);
free(tail_tower[i]);
}
}
char SkipList::random_level() {
char temp = 1;
std::random_device rd;
std::default_random_engine generator(rd());
std::uniform_real_distribution<double> distribution(0.1, 1);
double number = distribution(generator);
while (((distribution(generator)) < probability) && (temp < MAXLEVEL)) {
temp++;
}
return temp;
}
/***********************************************************************
* SkipList::search() : searches for a root node with the supplied key *
**********************************************************************/
node* SkipList::search(string key) {
search_res res = search_to_level(key, 1);
node* current_node = res.prev;
node* next_node = res.next;
if (string(current_node->key) == key) {
return current_node;
} else {
return ((node*)((void*)NO_SUCH_KEY));
}
}
/*******************************************************************************
* SkipList::search_to_level() starts from the head tower and searches for two *
* consecutive nodes on level 'level', such that the first has a key less than *
* or equal to k, and the second has a key strictly greater than k *
******************************************************************************/
search_res SkipList::search_to_level(string key, char level) {
find_start_res res = find_start(level);
node* current_node = res.lowest_node;
char current_level = res.level;
while (current_level > level) { // search down to level v + 1
search_res temp_res = search_right(key, current_node, current_level);
current_node = temp_res.prev->down;
current_level--;
}
return search_right(key, current_node, current_level); // search on level v
}
/***************************************************************************
* SkipList::find_start() searches the head tower for the lowest node that *
* points to the tail tower *
***************************************************************************/
find_start_res SkipList::find_start(char level) {
node* current_node = head;
char current_level = 1;
while (1) {
if (current_node->up == NULL) {
break;
}
else if (current_node->up->successor == NULL) {
break;
}
if ((((uintptr_t)(current_node->up->successor) !=
(uintptr_t)tail_tower[current_level])) ||
(current_level < level )) {
current_node = current_node->up;
current_level++;
} else {
break;
}
}
find_start_res ret_val;
ret_val.lowest_node = current_node;
ret_val.level = current_level;
return ret_val;
}
/*******************************************************************************
* SkipList::search_right starts from node curr_node and searches the level for*
* two consecutive nodes such that the first has a key less than or equal to k,*
* and the second has a key strictly greater than k *
******************************************************************************/
search_res SkipList::search_right(string key, node* current_node, char cur_lev){
node* next_node = PT(current_node->successor);
while (next_node && ((uintptr_t)next_node !=
(uintptr_t)tail_tower[cur_lev - 1])
&& (string(next_node->key) <= key)) {
while (EXTRACT_MARK(next_node->tower_root->successor) == 1) {
try_flag_node_res res = try_flag_node(current_node, next_node);
current_node = res.prev_node;
char status = res.res;
if (status == IN) {
help_flagged(current_node, next_node);
}
next_node = PT(current_node->successor);
}
if (string(next_node->key) <= key) {
current_node = next_node;
next_node = PT(current_node->successor);
}
}
search_res ret_val;
ret_val.prev = current_node;
ret_val.next = next_node;
return ret_val;
}
/*******************************************************************************
* SkipList::search_right starts from node curr_node and searches the level for*
* two consecutive nodes such that the first has a key less than k and the *
* second has a key greater than or equal to k *
******************************************************************************/
search_res SkipList::search_right_other(string key, node* current_node,
char cur_lev) {
node* next_node = PT(current_node->successor);
while (next_node && ((uintptr_t)next_node !=
(uintptr_t)tail_tower[cur_lev - 1])
&& (string(next_node->key) < key)) {
while (EXTRACT_MARK(next_node->tower_root->successor) == 1) {
try_flag_node_res res = try_flag_node(current_node, next_node);
current_node = res.prev_node;
char status = res.res;
if (status == IN) {
help_flagged(current_node, next_node);
}
next_node = PT(current_node->successor);
}
if (string(next_node->key) < key) {
current_node = next_node;
next_node = PT(current_node->successor);
}
}
search_res ret_val;
ret_val.prev = current_node;
ret_val.next = next_node;
return ret_val;
}
/*****************************************************************************
*SkipList::try_flag_node() attempts to flag the predecessor of target_node. *
****************************************************************************/
try_flag_node_res SkipList::try_flag_node(node* prev_node, node* target_node) {
try_flag_node_res ret_val;
while (1) {
if ((((uintptr_t)PT(prev_node->successor)) == (uintptr_t)target_node) &&
EXTRACT_FLAG(prev_node->successor) == 1) {
ret_val.prev_node = prev_node;
ret_val.res = IN;
ret_val.success = false;
return ret_val;
}
// try compare and swap
// prev val : target_node, 0, 0
// new val: target_node, 0, 1
uintptr_t cas_result = CAS(&(prev_node->successor),
(uintptr_t)target_node, ((uintptr_t)(target_node) | 1));
if (cas_result == (uintptr_t)target_node) {
ret_val.prev_node = prev_node;
ret_val.res = IN;
ret_val.success = true;
return ret_val;
} else if (cas_result == ((uintptr_t)target_node) | 1) {
ret_val.prev_node = prev_node;
ret_val.res = IN;
ret_val.success = false;
return ret_val;
}
while (EXTRACT_MARK(prev_node) == 1) {
prev_node = prev_node->back_link;
}
// TODO
char level = 1;
search_res searching =
search_right_other(string(target_node->key), prev_node, level);
prev_node = searching.prev;
node* del_node = searching.next;
if ((uintptr_t)del_node != (uintptr_t)target_node) {
ret_val.prev_node = prev_node;
ret_val.res = DELETED;
ret_val.success = false;
return ret_val;
}
}
}
node* SkipList::create_new_node(string key, string value, node* down,
node* tower_root) {
node* x = (node*)malloc(sizeof(node));
char* x_key = (char*)malloc(KEYLENGTH);
x->key = x_key;
memset(x->key, 0, KEYLENGTH);
memcpy(x->key, key.c_str(), key.length());
char* val = (char*)malloc(value.length() + 1);
memcpy(val, value.c_str(), value.length());
val[value.length()] = '\0';
x->up = NULL;
x->value = val;
x->down = NULL;
x->tower_root = x;
return x;
}
node* SkipList::create_new_node(string key, node* down, node* tower_root) {
node* x = (node*)malloc(sizeof(node));
x->value = tower_root->value;
x->up = NULL;
x->down = down;
x->successor = tail_tower[0];
down->up = x;
x->tower_root = tower_root;
x->key = tower_root->key;
return x;
}
node* SkipList::insert(string key, string value) {
search_res result = search_to_level(key, 1);
node* prev_node = result.prev;
node* next_node = result.next;
if (string(prev_node->key) == key) {
// update value and return DUPLICATE_KEY
//std::free(prev_node->value);
prev_node->value = (char*)malloc(
value.length() + 1);
memcpy(prev_node->value, value.c_str(), value.length());
prev_node->value[value.length()] = '\0';
return (node*)(void*)DUPLICATE_KEY;
}
node* new_rnode = create_new_node(key, value, NULL, NULL);
new_rnode->tower_root = new_rnode;
node* new_node = new_rnode;
char new_level = random_level();
char current_level = 1;
while (1) {
insert_node_res ins_result = insert_node(new_node, prev_node, next_node,
value, current_level);
node* prev_node = ins_result.prev;
node* result = ins_result.new_node;
if (((uintptr_t)result == DUPLICATE_KEY) && (current_level == 1)) {
std::free(new_node);
return (node*)(void*)DUPLICATE_KEY;
}
if (EXTRACT_MARK(new_rnode) == 1) {
if (((uintptr_t)result == (uintptr_t)new_node) &&
((uintptr_t)new_node != (uintptr_t)new_rnode)) {
deletion_node(prev_node, new_node);
}
return new_rnode;
}
if (current_level == new_level) {
return new_rnode;
}
current_level++;
node* last_node = new_node;
new_node = create_new_node(key, last_node, new_rnode);
search_res res = search_to_level(key, current_level);
prev_node = res.prev;
next_node = res.next;
}
} // end SkipList::insert()
insert_node_res SkipList::insert_node(node* new_node, node* prev_node,
node* next_node, string value, char current_level) {
insert_node_res ret_val;
if (string(prev_node->key) == string(new_node->key)) {
std::free(prev_node->value);
prev_node->value =
(char*)malloc(value.length() + 1);
memcpy(prev_node->value, value.c_str(), value.length());
prev_node->value[value.length()] = '\0';
ret_val.prev = prev_node;
ret_val.new_node = ((node*)(void*)DUPLICATE_KEY);
return ret_val;
}
while (1) {
node* prev_successor = prev_node->successor;
if (EXTRACT_FLAG(prev_successor) == 1) {
help_flagged(prev_node, PT(prev_successor->successor));
} else {
new_node->successor = next_node;
uintptr_t cas_result = CAS(&(prev_node->successor),
(uintptr_t)next_node, (uintptr_t)new_node);
if (cas_result == (uintptr_t)next_node) {
ret_val.prev = prev_node;
ret_val.new_node = new_node;
return ret_val;
} else {
if (EXTRACT_FLAG(prev_node->successor)) {
help_flagged(prev_node, PT(next_node->successor));
}
while (EXTRACT_MARK(prev_node)) {
prev_node = prev_node->back_link;
}
}
}
search_res res = search_right(string(new_node->key), prev_node,
current_level);
prev_node = res.prev;
next_node = res.next;
if (string(prev_node->key) == string(new_node->key)) {
std::free(prev_node->value);
prev_node->value =
(char*)malloc(value.length() + 1);
memcpy(prev_node->value, value.c_str(), value.length());
prev_node->value[value.length()] = '\0';
ret_val.prev = prev_node;
ret_val.new_node = ((node*)(void*)DUPLICATE_KEY);
return ret_val;
}
} // end while loop
} // end SkipList::insert_node()
void SkipList::put(string key, string value) {
node* new_entry = insert(key, value);
}
string SkipList::get(string key) {
string ret_val;
node* search_res = search(key);
if (uintptr_t(search_res) == NO_SUCH_KEY) {
return ret_val;
}
return string(search_res->value);
}
void SkipList::enumerate(vector<string>* strings, node* x, string prefix) {
int prefix_len = prefix.length();
while (x) {
if ((uintptr_t)x == (uintptr_t)tail) {
break;
}
if (EXTRACT_MARK(x) == 1) {
x = x->successor;
continue; // marked for deletion
}
int str_len = string(x->key).length();
if (prefix_len == str_len) {
if (string(x->key) == prefix) {
// the prefix is exactly same as this key
strings->push_back(string(x->value));
} else {
// lengths are same but no match, so return
return;
}
} else if (prefix_len < str_len) {
if (string(x->key).substr(0, prefix_len) == prefix) {
// prefix is exactly same as this key's prefix
strings->push_back(string(x->value));
} else {
// prefix didn't match, return
return;
}
} else {
// length of the prefix is greater, return
return;
}
x = x->successor;
}
} // end SkipList::enumerate()
vector<string> SkipList::get_keys_for_prefix(string prefix) {
vector<string> strings;
search_res res = search_to_level(prefix, 1);
node* current_node = res.prev;
node* next_node = res.next;
enumerate(&strings, current_node, prefix);
return strings;
} // end SkipList::get_keys_for_prefix()
list<Record> SkipList::get_all_data() {
list<Record> ret_val;
cout<<"HEAD NULL? "<<(head == 0)<<endl;
node* x = head->successor;
while ((uintptr_t)x != (uintptr_t)tail) {
cout<<"READ from skiplist "<<x->key<<endl;
Record rec;
Value val;
val.set_value(string(x->value));
rec.set_key(string(x->key));
rec.set_value(val);
x = x->successor;
ret_val.push_back(rec);
}
return ret_val;
}
node* SkipList::deletion(string key) {
return NULL;
}
node* SkipList::deletion_node(node* prev_node, node* del_node) {
return NULL;
}
void SkipList::help_marked(node* prev_node, node* del_node) {
}
void SkipList::help_flagged(node* prev_node, node* del_node) {
}
void SkipList::try_mark(node* del_node) {
}
<file_sep>/src/record.h
#ifndef RECORD_H
#define RECORD_H
#include <string.h>
#include "value.h"
#include <fstream>
#include <iostream>
#include <boost/crc.hpp>
#include <stdio.h>
using namespace std;
class Record {
private:
string key;
Value value;
unsigned int CalculateChecksum(Record);
public:
void set_key(string key);
void set_value(Value value);
string get_key();
Value get_value();
void write(ofstream *out);
void write(FILE* &out);
bool read(FILE* &in);
bool read(ifstream *in);
};
#endif
<file_sep>/src/value.cc
#include "value.h"
using namespace std;
Value::Value(string val, long ts, bool delete_flag) {
this->value = val;
this->timestamp = ts;
this->deleted = delete_flag;
}
Value::Value() {}
string Value::get_value() {
return this->value;
}
long Value::get_time() {
return this->timestamp;
}
bool Value::is_deleted() {
return this->deleted;
}
void Value::set_value(string value) {
this->value = value;
this->timestamp = time(0);
this->deleted = false;
}
void Value::mark_deleted() {
this->deleted = true;
}
//Not Required. Can be removed
void Value::write(ofstream out) {
size_t len = value.size();
out.write((char*)&len, sizeof(size_t));
out.write(value.c_str(), len);
out.write((char*)×tamp, sizeof(long));
out.write((char*)&deleted, sizeof(bool));
}
//Not Required. Can be removed
void Value::read(ifstream in) {
size_t len;
in.read((char*)&len, sizeof(size_t));
char* value_arr = new char[len + 1];
in.read(value_arr, len);
value_arr[len] = '\0';
this->value = value_arr;
delete [] value_arr;
in.read((char*)×tamp, sizeof(long));
in.read((char*)&deleted, sizeof(bool));
}
<file_sep>/src/trie.cc
#include "trie.h"
Trie::Trie() {
root = (node*) malloc(sizeof(node));
memset(root, 0, sizeof(node));
}
node* Trie::new_node() {
int num_bytes = sizeof(node);
node* ptr = (node*) malloc(num_bytes);
memset(ptr, 0, num_bytes);
return ptr;
}
void Trie::put(string key, string value) {
root = put(root, key, value, 0);
}
string Trie::get(string key) {
node* x = get(root, key, 0);
if (x == NULL) {
return NULL;
} else {
return (string)(x->value);
}
}
node* Trie::get(node* x, string key, int depth) {
if (x == NULL) {
return NULL;
}
if (depth == key.length()) {
return x;
}
char c = key[depth];
return get(x->kids[c], key, depth + 1);
}
vector<string> Trie::get_keys_for_prefix(string prefix) {
vector<string> strings;
node* prefix_node = get(root, prefix, 0);
if (prefix_node == NULL) {
return strings;
}
enumerate(&strings, prefix_node);
return strings;
}
void Trie::enumerate(vector<string>* strings, node* x) {
if (x->value != NULL) {
strings->push_back((string)(x->value));
}
for (int i = 0; i < 256; i++) {
if (x->kids[i] != NULL) {
enumerate(strings, x->kids[i]);
}
}
}
node* Trie::put(node* x, string key, string value, int depth) {
if (x == NULL) {
x = new_node();
}
if (depth == key.length()) {
int len = value.length();
char* val = (char*) malloc(len);
memcpy(val, value.c_str(), len);
x->value = val;
x->value_len = len;
return x;
}
char c = key[depth];
x->kids[c] = put(x->kids[c], key, value, depth + 1);
return x;
}
|
227864221167847e9e75a6fdb9c73fd8e4deb891
|
[
"Markdown",
"Makefile",
"C++"
] | 24
|
C++
|
srsuryadev/key-value-store
|
637f9745c1ddc76ea6bc7f8546ba6fd03e45e55b
|
004425be8c4675cf4618838ced5c044c52370f03
|
refs/heads/main
|
<file_sep>import React, { useEffect, useState } from 'react';
import 'antd/dist/antd.css';
import { Table,Form } from 'antd';
import axios from 'axios'
import { Link,useHistory, useParams } from 'react-router-dom';
const Demo = () => {
const [form] = Form.useForm();
const history = useHistory();
const [Items,setItems] = useState([
form.setFieldsValue({
user:"",
qualification:'',
coach_blog:'',
coach_desc:''
})
]);
useEffect((key)=>{
axios.get('http://localhost:3200/coach')
.then(res=>{
console.log(res.data)
setItems(res.data)
})
.catch(function (error) {
console.log(error);
});
},[]);
const columns = [
{
title:'User',
dataIndex:'user',
key:'user'
},
{
title:'Qualification',
dataIndex:'qualification',
key:'qualification'
},
{
title:'Coach_blog',
dataIndex:'coach_blog',
key:'coach_blog'
},
{
title:'Coach_desc',
dataIndex:'coach_desc',
key:'coach_desc'
},
]
const params=useParams()
const onRow = (key) =>({
onClick: () =>
history.push(`/Coach_form/${key._id}/${key.user}/${key.qualification}/${key.coach_blog}/${key.coach_desc}/${params['coachId']|| ''}`,
{
}),
})
return (
<>
<Link to={'/Coach_form'} className="nav-link">Create</Link>
<Table dataSource={Items} columns={columns} onRow={onRow}/>
</>
);
};
export default Demo;<file_sep>import firebase from 'firebase';
const firebaseConfig = {
apiKey: "<KEY>",
authDomain: "formlistreact.firebaseapp.com",
projectId: "formlistreact",
storageBucket: "formlistreact.appspot.com",
messagingSenderId: "232821786612",
appId: "1:232821786612:web:0720dad683667cbe07dba1",
measurementId: "G-9NJPZTE1EZ"
};
firebase.initializeApp(firebaseConfig);
var storage = firebase.storage();
export {storage}<file_sep>import 'antd/dist/antd.css';
import { Form, Input, Button, Row, Col } from 'antd';
import axios from 'axios'
//import { PlusCircleOutlined } from '@ant-design/icons';
import { Link,useParams } from 'react-router-dom';
//const { Column, ColumnGroup } = Table;
import {useState,useEffect} from "react"
const layout = {
labelCol: {
span: 4
},
wrapperCol: {
span: 14
}
};
const tailLayout = {
wrapperCol: {
offset: 8,
span: 16
}
};
export const Coach_form = () =>{
const [form] = Form.useForm();
//const history = useHistory();
const params = useParams('coachId');
const [user, setUser] = useState('');
const [qualification, setQualification] = useState('');
const [coach_blog, setCB] = useState('');
const [coach_desc, setCD] = useState('');
const [Items] = useState([]);
const onFinish = () => {
alert(Items);
axios.post('http://localhost:3200/coach' ,{
user: user,
qualification: qualification,
coach_blog: coach_blog,
coach_desc: coach_desc,
headers: {'Content-Type': 'multipart/form-data'}}
)
.then(function (AxiosResponse){
console.log(AxiosResponse);
})
.catch(function (AxiosResponse){
console.log(AxiosResponse);
});
};
useEffect(()=>{
form.setFieldsValue({
user:params.user,
qualification:params.qualification,
coach_blog:params.coach_blog,
coach_desc:params.coach_desc
})
console.log(params);
},[params,form]);
return(
<>
<Form form={form} {...layout}
onFinish={onFinish}
autoComplete="on">
<Row gutter={[16, 24]}>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="user"
label="User"
rules={[{ required: true, message: 'Enter User Id' }]}
>
<Input value={user} name="user" onChange={(e)=>{
setUser(e.target.value)
}}/>
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="qualification"
label="Qualification"
rules={[{ required: true, message: 'Enter Qualification' }]}
>
<Input value={qualification} name="qualification" onChange={(e)=>{
setQualification(e.target.value)}}/>
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="coach_blog"
label="Coach_blog"
rules={[{ required: true, message: 'Enter Coach_blog' }]}
>
<Input name="coach_blog" value={coach_blog} onChange={(e)=>{
setCB(e.target.value)}}/>
</Form.Item>
</Col>
<Col xs={24} sm={24} md={12}>
<Form.Item
name="coach_desc"
label="Coach_desc"
rules={[{ required: true, message: 'Enter Coach_desc' }]}
>
<Input name="coach_desc" value={coach_desc} onChange={(e)=>{
setCD(e.target.value)}}/>
</Form.Item>
</Col>
<Col xs={24} sm={24} md={24}>
<Form.Item {...tailLayout}>
<Button type="primary" {...tailLayout} htmlType="submit">
Submit
</Button>
</Form.Item>
</Col>
<Col xs={12} sm={12} md={12}>
<Form.Item>
<Link to={'/'} className="nav-link">Back</Link>
</Form.Item>
</Col>
</Row>
</Form>
</>
)
}
|
946bba3d4a3ce2de18f91b80b86f2e51519dcce0
|
[
"JavaScript"
] | 3
|
JavaScript
|
kamal-re/RegisterFrontEnd
|
2fbbd5ae29451784bbed27e8ae8c2eda398d1390
|
9e3a76fe382bfdbf20816f59bd80501f5f5ff810
|
refs/heads/master
|
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
import gym
import torch.nn.utils as nn_utils
import time
import csv
import act
from actor_critic_02 import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model_02 import *
from i2a_act import *
import common
USE_CUDA = torch.cuda.is_available()
ROLLOUTS_STEPS = 3
LEARNING_RATE = 1e-4
POLICY_LR = 1e-4
TEST_EVERY_BATCH = 3
NUM_ENVS = 16
NUM_OF_EPISODES = 100000
REWARD_STEPS = 5
GAMMA = 0.99
CLIP_GRAD = 0.5
ENTROPY_BETA = 0.01
VALUE_LOSS_COEF = 0.5
BATCH_SIZE = REWARD_STEPS * 16
SAVE_EVERY_BATCH = 10000
def train_a2c(net, mb_obs, mb_rewards, mb_actions, mb_values, optimizer, step_idx, device="cpu"):
optimizer.zero_grad()
mb_adv = mb_rewards - mb_values
adv_v = torch.FloatTensor(mb_adv).to(device)
obs_v = torch.FloatTensor(mb_obs).to(device)
rewards_v = torch.FloatTensor(mb_rewards).to(device)
actions_t = torch.LongTensor(mb_actions).to(device)
logits_v, values_v, ponder_dictionary = net(obs_v)
log_prob_v = F.log_softmax(logits_v, dim=1)
log_prob_actions_v = adv_v * log_prob_v[range(len(mb_actions)), actions_t]
loss_policy_v = -log_prob_actions_v.mean()
loss_value_v = F.mse_loss(values_v.squeeze(-1), rewards_v)
prob_v = F.softmax(logits_v, dim=1)
entropy_loss_v = (prob_v * log_prob_v).sum(dim=1).mean()
loss_v = ENTROPY_BETA * entropy_loss_v + VALUE_LOSS_COEF * loss_value_v + loss_policy_v
loss_v.backward()
nn_utils.clip_grad_norm_(net.parameters(), CLIP_GRAD)
optimizer.step()
return obs_v
def iterate_batches(envs, net, device="cpu"):
n_actions = envs[0].action_space.n
act_selector = ProbabilityActionSelector()
obs = [e.reset() for e in envs]
batch_dones = [[False] for _ in range(NUM_ENVS)]
total_reward = [0.0] * NUM_ENVS
total_steps = [0] * NUM_ENVS
mb_obs = np.zeros((NUM_ENVS, REWARD_STEPS) + IMG_SHAPE, dtype=np.uint8)
mb_rewards = np.zeros((NUM_ENVS, REWARD_STEPS), dtype=np.float32)
mb_values = np.zeros((NUM_ENVS, REWARD_STEPS), dtype=np.float32)
mb_actions = np.zeros((NUM_ENVS, REWARD_STEPS), dtype=np.int32)
mb_probs = np.zeros((NUM_ENVS, REWARD_STEPS, n_actions), dtype=np.float32)
for _ in range(NUM_OF_EPISODES):
batch_dones = [[dones[-1]] for dones in batch_dones]
done_rewards = []
done_steps = []
for n in range(REWARD_STEPS):
obs_v = default_states_preprocessor(obs).to(device)
mb_obs[:, n] = obs_v.data.cpu().numpy()
logits_v, values_v, _ = net(obs_v)
probs_v = F.softmax(logits_v, dim=1)
probs = probs_v.data.cpu().numpy()
actions = act_selector(probs)
mb_probs[:, n] = probs
mb_actions[:, n] = actions
mb_values[:, n] = values_v.squeeze().data.cpu().numpy()
for e_idx, e in enumerate(envs):
o, r, done, _ = e.step(actions[e_idx])
total_reward[e_idx] += r
total_steps[e_idx] += 1
if done:
o = e.reset()
done_rewards.append(total_reward[e_idx])
done_steps.append(total_steps[e_idx])
total_reward[e_idx] = 0.0
total_steps[e_idx] = 0
obs[e_idx] = o
mb_rewards[e_idx, n] = r
batch_dones[e_idx].append(done)
# obtain values for the last observation
obs_v = default_states_preprocessor(obs).to(device)
_, values_v = net(obs_v)
values_last = values_v.squeeze().data.cpu().numpy()
for e_idx, (rewards, dones, value) in enumerate(zip(mb_rewards, batch_dones, values_last)):
rewards = rewards.tolist()
if not dones[-1]:
rewards = discount_with_dones(rewards + [value], dones[1:] + [False], GAMMA)[:-1]
else:
rewards = discount_with_dones(rewards, dones[1:], GAMMA)
mb_rewards[e_idx] = rewards
out_mb_obs = mb_obs.reshape((-1,) + IMG_SHAPE)
out_mb_rewards = mb_rewards.flatten()
out_mb_actions = mb_actions.flatten()
out_mb_values = mb_values.flatten()
out_mb_probs = mb_probs.flatten()
yield out_mb_obs, out_mb_rewards, out_mb_actions, out_mb_values, out_mb_probs, \
np.array(done_rewards), np.array(done_steps)
def set_seed(seed, envs=None, cuda=False):
np.random.seed(seed)
torch.manual_seed(seed)
if cuda:
torch.cuda.manual_seed(seed)
if envs:
for idx, env in enumerate(envs):
env.seed(seed + idx)
if __name__ == "__main__":
device = torch.device("cuda" if USE_CUDA else "cpu")
envs = [common.make_env() for _ in range(NUM_ENVS)]
test_env = common.make_env(test=True)
obs_shape = envs[0].observation_space.shape
act_n = envs[0].action_space.n
net_policy = ActorCritic(obs_shape, act_n).to(device)
net_em = EnvironmentModel(obs_shape, act_n)
net_em.load_state_dict(torch.load("breakout.env"))
net_em = net_em.to(device)
net_i2a = I2A(obs_shape, act_n, net_em, net_policy, ROLLOUTS_STEPS).to(device)
print(net_i2a)
obs = envs[0].reset()
obs_v = common.default_states_preprocessor([obs]).to(device)
res = net_i2a(obs_v)
optimizer = optim.RMSprop(net_i2a.parameters(), lr=LEARNING_RATE, eps=1e-5)
policy_opt = optim.Adam(net_policy.parameters(), lr=POLICY_LR)
step_idx = 0
total_steps = 0
ts_start = time.time()
best_reward = None
best_test_reward = None
for mb_obs, mb_rewards, mb_actions, mb_values, mb_probs, done_rewards, done_steps in \
common.iterate_batches(envs, net_i2a, act=True,device=device):
if len(done_rewards) > 0:
total_steps += sum(done_steps)
speed = total_steps / (time.time() - ts_start)
if best_reward is None:
best_reward = done_rewards.max()
elif best_reward < done_rewards.max():
best_reward = done_rewards.max()
obs_v = common.train_a2c(net_i2a, mb_obs, mb_rewards, mb_actions, mb_values,
optimizer, step_idx, act=True,device=device)
# policy distillation
probs_v = torch.FloatTensor(mb_probs).to(device)
policy_opt.zero_grad()
logits_v, _ = net_policy(obs_v)
policy_loss_v = -F.log_softmax(logits_v, dim=1) * probs_v.view_as(logits_v)
policy_loss_v = policy_loss_v.sum(dim=1).mean()
policy_loss_v.backward()
policy_opt.step()
step_idx += 1
if step_idx % SAVE_EVERY_BATCH == 0:
fname = "breakout.i2a"
torch.save(net_em.state_dict(), fname)
torch.save(net_policy.state_dict(), fname + ".policy")
if step_idx % TEST_EVERY_BATCH == 0:
test_reward, test_steps = common.test_model(test_env, net_i2a, device=device)
append_to_file = [step_idx, test_reward]
with open('i2a_performance.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(append_to_file)
if best_test_reward is None or best_test_reward < test_reward:
if best_test_reward is not None:
fname = "breakout.i2a"
torch.save(net_i2a.state_dict(), fname)
torch.save(net_policy.state_dict(), fname + ".policy")
print("Save I2A NET at step", step_idx)
else:
fname = "breakout.env.i2a"
torch.save(net_em.state_dict(), fname)
print("Save I2A ENV NET at step", step_idx)
best_test_reward = test_reward
print("%d: test reward=%.2f, steps=%.2f, best_reward=%.2f" % (
step_idx, test_reward, test_steps, best_test_reward))
fname = "breakout.i2a"
torch.save(net_i2a.state_dict(), fname)
torch.save(net_policy.state_dict(), fname + ".policy")
torch.save(net_em.state_dict(), fname + ".env.dat")
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
from actor_critic import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import *
from IPython.display import clear_output
#import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
#7 different pixels in MiniPacman
pixels = (
(0.0, 1.0, 1.0),
(0.0, 1.0, 0.0),
(0.0, 0.0, 1.0),
(1.0, 1.0, 1.0),
(1.0, 1.0, 0.0),
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0),
)
pixel_to_categorical = {pix:i for i, pix in enumerate(pixels)}
num_pixels = len(pixels)
print("Num pixels", num_pixels)
#For each mode in MiniPacman there are different rewards
mode_rewards = {
"regular": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"avoid": [0.1, -0.1, -5, -10, -20],
"hunt": [0, 1, 10, -20],
"ambush": [0, -0.1, 10, -20],
"rush": [0, -0.1, 9.9]
}
reward_to_categorical = {mode: {reward:i for i, reward in enumerate(mode_rewards[mode])} for mode in mode_rewards.keys()}
def pix_to_target(next_states):
# print("size next_states", next_states.transpose(0,2,3,1).reshape(-1,3))
# print("size next_states", next_states)
target = []
for pixel in next_states.transpose(0, 2, 3, 1).reshape(-1, 3):
#print(pixel)
target.append(pixel_to_categorical[tuple([np.ceil(pixel[0]), np.ceil(pixel[1]), np.ceil(pixel[2])])])
return target
def target_to_pix(imagined_states):
pixels = []
to_pixel = {value: key for key, value in pixel_to_categorical.items()}
for target in imagined_states:
pixels.append(list(to_pixel[target]))
return np.array(pixels)
def rewards_to_target(mode, rewards):
target = []
for reward in rewards:
target.append(reward_to_categorical[mode][reward])
return target
def plot(frame_idx, rewards, losses):
clear_output(True)
plt.figure(figsize=(20,5))
plt.subplot(131)
plt.title('loss %s' % losses[-1])
plt.plot(losses)
plt.show()
def displayImage(image, step, reward):
s = str(step) + " " + str(reward)
plt.title(s)
plt.imshow(image)
plt.show()
print(len(mode_rewards["regular"]))
mode = "regular"
num_envs = 16
def make_env():
def _thunk():
env = MiniPacman(mode, 1000)
return env
return _thunk
env = make_env()
envs = [make_env() for i in range(num_envs)]
envs = SubprocVecEnv(envs)
state_shape = env().observation_space.shape
num_actions = env().action_space.n
print("state shape",state_shape)
print("num actions", num_actions)
print("num pixeles", num_pixels)
env_model = EnvModel(state_shape, num_pixels, len(mode_rewards["regular"]))
actor_critic = ActorCritic(state_shape, num_actions)
print("len mode rewards regular", len(mode_rewards["regular"]))
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(env_model.parameters())
if USE_CUDA:
env_model = env_model.cuda()
actor_critic = actor_critic.cuda()
actor_critic.load_state_dict(torch.load("actor_critic_" + mode))
def get_action(state):
if state.ndim == 4:
state = torch.FloatTensor(np.float32(state))
else:
state = torch.FloatTensor(np.float32(state)).unsqueeze(0)
action = actor_critic.act(Variable(state, volatile=True))
action = action.data.cpu().squeeze(1).numpy()
return action
def play_games(envs, frames):
states = envs.reset()
for frame_idx in range(frames):
actions = get_action(states)
next_states, rewards, dones, _ = envs.step(actions)
yield frame_idx, states, actions, rewards, next_states, dones
states = next_states
reward_coef = 0.1
num_updates = 10000
SAVE_EVERY_BATCH = 1000
losses = []
all_rewards = []
best_loss = np.inf
for frame_idx, states, actions, rewards, next_states, dones in play_games(envs, num_updates):
states = torch.FloatTensor(states)
actions = torch.LongTensor(actions)
batch_size = states.size(0)
onehot_actions = torch.zeros(batch_size, num_actions, *state_shape[1:])
onehot_actions[range(batch_size), actions] = 1
inputs = Variable(torch.cat([states, onehot_actions], 1))
if USE_CUDA:
inputs = inputs.cuda()
imagined_state, imagined_reward = env_model(inputs)
target_state = pix_to_target(next_states)
target_state = Variable(torch.LongTensor(target_state))
target_reward = rewards_to_target(mode, rewards)
target_reward = Variable(torch.LongTensor(target_reward))
optimizer.zero_grad()
image_loss = criterion(imagined_state, target_state)
reward_loss = criterion(imagined_reward, target_reward)
loss = image_loss + reward_coef * reward_loss
loss.backward()
optimizer.step()
losses.append(loss.data[0])
all_rewards.append(np.mean(rewards))
if frame_idx % 100 == 0:
print("frame", frame_idx)
if loss < best_loss:
print("SAVING NETWORK: Best loss updated: %.4e -> %.4e" % (best_loss, loss))
best_loss = loss
torch.save(env_model.state_dict(), "env_model_" + mode)
frame_idx += 1
if frame_idx + 1 % SAVE_EVERY_BATCH == 0:
print("Saving Network on step: ", frame_idx)
torch.save(env_model.state_dict(), "env_model_" + mode)
if frame_idx % 400 == 0:
print("STEP", frame_idx, "Loss updated: %.4e -> %.4e" % (best_loss, loss))
torch.save(env_model.state_dict(), "env_model_" + mode)<file_sep>import torch
import torch.optim as optim
import common
from actor_critic_02 import ActorCritic
LEARNING_RATE = 1e-4
TEST_EVERY_BATCH = 300
if __name__ == "__main__":
device = torch.device("cuda")
envs = [common.make_env() for _ in range(common.NUM_ENVS)]
test_env = common.make_env(test=True)
net = ActorCritic(envs[0].observation_space.shape, envs[0].action_space.n).to(device)
print(net)
optimizer = optim.RMSprop(net.parameters(), lr=LEARNING_RATE, eps=1e-5)
step_idx = 0
total_steps = 0
best_reward = None
best_test_reward = None
for mb_obs, mb_rewards, mb_actions, mb_values, _, done_rewards, done_steps in common.iterate_batches(envs, net, device=device):
common.train_a2c(net, mb_obs, mb_rewards, mb_actions, mb_values,
optimizer, step_idx, device=device)
step_idx += 1
if step_idx % TEST_EVERY_BATCH == 0:
test_reward, test_steps = common.test_model(test_env, net, device=device)
if best_test_reward is None or best_test_reward < test_reward:
if best_test_reward is not None:
fname = "pacman_a2c.net"
torch.save(net.state_dict(), fname)
best_test_reward = test_reward
print("%d: test reward=%.2f, steps=%.2f, best_reward=%.2f" % (step_idx, test_reward, test_steps, best_test_reward))
if step_idx > 100000:
break
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.autograd as autograd
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import EnvModel
from actor_critic import OnPolicy, ActorCritic, RolloutStorage
from IPython.display import clear_output
import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
pixels = (
(0.0, 1.0, 0.0),
(0.0, 1.0, 1.0),
(0.0, 0.0, 1.0),
(1.0, 1.0, 1.0),
(1.0, 1.0, 0.0),
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)
)
pixel_to_onehot = {pix:i for i, pix in enumerate(pixels)}
num_pixels = len(pixels)
task_rewards = {
"regular": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"avoid": [0.1, -0.1, -5, -10, -20],
"hunt": [0, 1, 10, -20],
"ambush": [0, -0.1, 10, -20],
"rush": [0, -0.1, 9.9]
}
reward_to_onehot = {mode: {reward:i for i, reward in enumerate(task_rewards[mode])} for mode in task_rewards.keys()}
def pix_to_target(next_states):
target = []
for pixel in next_states.transpose(0, 2, 3, 1).reshape(-1, 3):
target.append(pixel_to_onehot[tuple([np.round(pixel[0]), np.round(pixel[1]), np.round(pixel[2])])])
return target
def target_to_pix(imagined_states):
pixels = []
to_pixel = {value: key for key, value in pixel_to_onehot.items()}
for target in imagined_states:
pixels.append(list(to_pixel[target]))
return np.array(pixels)
def rewards_to_target(mode, rewards):
target = []
for reward in rewards:
target.append(reward_to_onehot[mode][reward])
return target
def displayImage(image, step, reward):
s = str(step) + " " + str(reward)
plt.title(s)
plt.imshow(image)
plt.show()
class RolloutEncoder(nn.Module):
def __init__(self, in_shape, num_rewards, hidden_size):
super(RolloutEncoder, self).__init__()
self.in_shape = in_shape
self.features = nn.Sequential(
nn.Conv2d(in_shape[0], 16, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv2d(16, 16, kernel_size=3, stride=2),
nn.ReLU(),
)
self.gru = nn.GRU(self.feature_size() + num_rewards, hidden_size)
def forward(self, state, reward):
num_steps = state.size(0)
batch_size = state.size(1)
state = state.view(-1, *self.in_shape)
state = self.features(state)
state = state.view(num_steps, batch_size, -1)
rnn_input = torch.cat([state, reward], 2)
_, hidden = self.gru(rnn_input)
return hidden.squeeze(0)
def feature_size(self):
return self.features(autograd.Variable(torch.zeros(1, *self.in_shape))).view(1, -1).size(1)
class I2A(OnPolicy):
def __init__(self, in_shape, num_actions, num_rewards, hidden_size, imagination, full_rollout=True):
super(I2A, self).__init__()
self.in_shape = in_shape
self.num_actions = num_actions
self.num_rewards = num_rewards
self.imagination = imagination
self.features = nn.Sequential(
nn.Conv2d(in_shape[0], 16, kernel_size=3, stride=1),
nn.ReLU(),
nn.Conv2d(16, 16, kernel_size=3, stride=2),
nn.ReLU(),
)
self.encoder = RolloutEncoder(in_shape, num_rewards, hidden_size)
if full_rollout:
self.fc = nn.Sequential(
nn.Linear(self.feature_size() + num_actions * hidden_size, 256),
nn.ReLU(),
)
else:
self.fc = nn.Sequential(
nn.Linear(self.feature_size() + hidden_size, 256),
nn.ReLU(),
)
self.critic = nn.Linear(256, 1)
self.actor = nn.Linear(256, num_actions)
def forward(self, state):
batch_size = state.size(0)
imagined_state, imagined_reward = self.imagination(state.data)
hidden = self.encoder(Variable(imagined_state), Variable(imagined_reward))
hidden = hidden.view(batch_size, -1)
state = self.features(state)
state = state.view(state.size(0), -1)
x = torch.cat([state, hidden], 1)
x = self.fc(x)
logit = self.actor(x)
value = self.critic(x)
return logit, value
def feature_size(self):
return self.features(autograd.Variable(torch.zeros(1, *self.in_shape))).view(1, -1).size(1)
class ImaginationCore(object):
def __init__(self, num_rolouts, in_shape, num_actions, num_rewards, env_model, distil_policy, full_rollout=True):
self.num_rolouts = num_rolouts
self.in_shape = in_shape
self.num_actions = num_actions
self.num_rewards = num_rewards
self.env_model = env_model
self.distil_policy = distil_policy
self.full_rollout = full_rollout
def __call__(self, state):
state = state.cpu()
batch_size = state.size(0)
rollout_states = []
rollout_rewards = []
if self.full_rollout:
state = state.unsqueeze(0).repeat(self.num_actions, 1, 1, 1, 1).view(-1, *self.in_shape)
action = torch.LongTensor([[i] for i in range(self.num_actions)]*batch_size)
action = action.view(-1)
rollout_batch_size = batch_size * self.num_actions
else:
action = self.distil_policy.act(Variable(state, volatile=True))
action = action.data.cpu()
rollout_batch_size = batch_size
for step in range(self.num_rolouts):
onehot_action = torch.zeros(rollout_batch_size, self.num_actions, *self.in_shape[1:])
onehot_action[range(rollout_batch_size), action] = 1
inputs = torch.cat([state, onehot_action], 1)
imagined_state, imagined_reward = self.env_model(Variable(inputs, volatile=True))
imagined_state = F.softmax(imagined_state).max(1)[1].data.cpu()
imagined_reward = F.softmax(imagined_reward).max(1)[1].data.cpu()
imagined_state = target_to_pix(imagined_state.numpy())
imagined_state = torch.FloatTensor(imagined_state).view(rollout_batch_size, *self.in_shape)
onehot_reward = torch.zeros(rollout_batch_size, self.num_rewards)
onehot_reward[range(rollout_batch_size), imagined_reward] = 1
rollout_states.append(imagined_state.unsqueeze(0))
rollout_rewards.append(onehot_reward.unsqueeze(0))
state = imagined_state
action = self.distil_policy.act(Variable(state, volatile=True))
action = action.data.cpu()
return torch.cat(rollout_states), torch.cat(rollout_rewards)
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.autograd as autograd
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from actor_critic import *
from breakout import *
from IPython.display import clear_output
import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
mode = "regular"
num_envs = 16
def make_env():
def _thunk():
env = AtariGame(mode, 1000)
return env
return _thunk
envs = [make_env() for i in range(num_envs)]
envs = SubprocVecEnv(envs)
state_shape = envs.observation_space.shape
#a2c hyperparams:
gamma = 0.99
entropy_coef = 0.01
value_loss_coef = 0.5
max_grad_norm = 0.5
num_steps = 5
num_frames = 300#int(10e5)
#rmsprop hyperparams:
lr = 7e-4
eps = 1e-5
alpha = 0.99
#Init a2c and rmsprop
actor_critic = ActorCritic(envs.observation_space.shape, envs.action_space.n)
optimizer = optim.RMSprop(actor_critic.parameters(), lr, eps=eps, alpha=alpha)
if USE_CUDA:
actor_critic = actor_critic.cuda()
rollout = RolloutStorage(num_steps, num_envs, envs.observation_space.shape)
rollout.cuda()
all_rewards = []
all_losses = []
state = envs.reset()
#print("state len:",len(state))
state = torch.FloatTensor(np.float32(state))
rollout.states[0].copy_(state)
episode_rewards = torch.zeros(num_envs, 1)
final_rewards = torch.zeros(num_envs, 1)
for i_update in range(num_frames):
for step in range(num_steps):
action = actor_critic.act(Variable(state))
next_state, reward, done, _ = envs.step(action.squeeze(1).cpu().data.numpy())
reward = torch.FloatTensor(reward).unsqueeze(1)
episode_rewards += reward
masks = torch.FloatTensor(1-np.array(done)).unsqueeze(1)
final_rewards *= masks
final_rewards += (1-masks) * episode_rewards
episode_rewards *= masks
if USE_CUDA:
masks = masks.cuda()
state = torch.FloatTensor(np.float32(next_state))
rollout.insert(step, state, action.data, reward, masks)
_, next_value = actor_critic(Variable(rollout.states[-1], volatile=True))
next_value = next_value.data
returns = rollout.compute_returns(next_value, gamma)
logit, action_log_probs, values, entropy = actor_critic.evaluate_actions(
Variable(rollout.states[:-1]).view(-1, *state_shape),
Variable(rollout.actions).view(-1, 1)
)
values = values.view(num_steps, num_envs, 1)
action_log_probs = action_log_probs.view(num_steps, num_envs, 1)
advantages = Variable(returns) - values
value_loss = advantages.pow(2).mean()
action_loss = -(Variable(advantages.data) * action_log_probs).mean()
optimizer.zero_grad()
loss = value_loss * value_loss_coef + action_loss - entropy * entropy_coef
loss.backward()
nn.utils.clip_grad_norm(actor_critic.parameters(), max_grad_norm)
optimizer.step()
if i_update % 100 == 0:
print("i_update",i_update)
# all_rewards.append(final_rewards.mean())
# all_losses.append(loss.data[0])
# plt.figure(figsize=(20,5))
# plt.subplot(131)
# plt.title('epoch %s. reward: %s' % (i_update, np.mean(all_rewards[-10:])))
# plt.plot(all_rewards)
# plt.subplot(132)
# plt.title('loss %s' % all_losses[-1])
# plt.plot(all_losses)
# #plt.show()
rollout.after_update()
torch.save(actor_critic.state_dict(), "breakout" + mode)
# import time
# def displayImage(image, step, reward):
# clear_output(True)
# s = "step: " + str(step) + " reward: " + str(reward)
# plt.figure(figsize=(10,3))
# plt.title(s)
# plt.imshow(image)
# plt.show()
# time.sleep(0.1)
# env = MiniPacman(mode, 1000)
# done = False
# state = env.reset()
# total_reward = 0
# step = 1
# while not done:
# current_state = torch.FloatTensor(state).unsqueeze(0)
# if USE_CUDA:
# current_state = current_state.cuda()
# action = actor_critic.act(Variable(current_state))
# next_state, reward, done, _ = env.step(action.data[0, 0])
# total_reward += reward
# state = next_state
# image = torch.FloatTensor(state).permute(1, 2, 0).cpu().numpy()
# displayImage(image, step, total_reward)
# step += 1<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
import gym
import time
import torch.nn.utils as nn_utils
from actor_critic_02 import ActorCritic
from environment_model_02 import *
import common
LEARNING_RATE = 1e-3
TEST_EVERY_BATCH = 1000
USE_CUDA = torch.cuda.is_available()
NUM_ENVS = 16
REWARD_STEPS = 5
GAMMA = 0.99
BATCH_SIZE = REWARD_STEPS * 16
CLIP_GRAD = 0.5
ENTROPY_BETA = 0.01
VALUE_LOSS_COEF = 0.5
OBS_WEIGHT = 10.0
REWARD_WEIGHT = 1.0
FRAMES_COUNT = 2
IMG_SHAPE = (FRAMES_COUNT, 84, 84)
EM_OUT_SHAPE = (1, ) + IMG_SHAPE[1:]
NUM_OF_EPISODES = 50000
SAVE_EVERY_BATCH = 1000
def get_obs_diff(prev_obs, cur_obs):
prev = np.array(prev_obs)[-1]
cur = np.array(cur_obs)[-1]
prev = prev.astype(np.float32) / 255.0
cur = cur.astype(np.float32) / 255.0
return cur - prev
#different iterate_batches than the one in common.py
def iterate_batches(envs, net, device="cpu"):
act_selector = common.ProbabilityActionSelector()
mb_obs = np.zeros((BATCH_SIZE, ) + IMG_SHAPE, dtype=np.uint8)
mb_obs_next = np.zeros((BATCH_SIZE, ) + EM_OUT_SHAPE, dtype=np.float32)
mb_actions = np.zeros((BATCH_SIZE, ), dtype=np.int32)
mb_rewards = np.zeros((BATCH_SIZE, ), dtype=np.float32)
obs = [e.reset() for e in envs]
total_reward = [0.0] * NUM_ENVS
total_steps = [0] * NUM_ENVS
batch_idx = 0
done_rewards = []
done_steps = []
for _ in range(500000):
obs_v = common.default_states_preprocessor(obs).to(device)
logits_v, values_v = net(obs_v)
probs_v = F.softmax(logits_v, dim=1)
probs = probs_v.data.cpu().numpy()
actions = act_selector(probs)
for e_idx, e in enumerate(envs):
o, r, done, _ = e.step(actions[e_idx])
mb_obs[batch_idx] = obs[e_idx]
mb_obs_next[batch_idx] = get_obs_diff(obs[e_idx], o)
mb_actions[batch_idx] = actions[e_idx]
mb_rewards[batch_idx] = r
total_reward[e_idx] += r
total_steps[e_idx] += 1
batch_idx = (batch_idx + 1) % BATCH_SIZE
if batch_idx == 0:
yield mb_obs, mb_obs_next, mb_actions, mb_rewards, done_rewards, done_steps
done_rewards.clear()
done_steps.clear()
if done:
o = e.reset()
done_rewards.append(total_reward[e_idx])
done_steps.append(total_steps[e_idx])
total_reward[e_idx] = 0.0
total_steps[e_idx] = 0
obs[e_idx] = o
if __name__ == "__main__":
device = torch.device("cuda" if USE_CUDA else "cpu")
envs = [common.make_env() for _ in range(NUM_ENVS)]
net = ActorCritic(envs[0].observation_space.shape, envs[0].action_space.n)
net_em = EnvironmentModel(envs[0].observation_space.shape, envs[0].action_space.n).to(device)
net.load_state_dict(torch.load("pacman_a2c.net"))
net = net.to(device)
print(net_em)
optimizer = optim.Adam(net_em.parameters(), lr=LEARNING_RATE)
step_idx = 0
best_loss = np.inf
for mb_obs, mb_obs_next, mb_actions, mb_rewards, done_rewards, done_steps in iterate_batches(envs, net, device):
# if len(done_rewards) > 0:
# m_reward = np.mean(done_rewards)
# m_steps = np.mean(done_steps)
# print("%d: done %d episodes, mean reward=%.2f, steps=%.2f" % (
# step_idx, len(done_rewards), m_reward, m_steps))
# tb_tracker.track("total_reward", m_reward, step_idx)
# tb_tracker.track("total_steps", m_steps, step_idx)
obs_v = torch.FloatTensor(mb_obs).to(device)
obs_next_v = torch.FloatTensor(mb_obs_next).to(device)
actions_t = torch.LongTensor(mb_actions.tolist()).to(device)
rewards_v = torch.FloatTensor(mb_rewards).to(device)
optimizer.zero_grad()
out_obs_next_v, out_reward_v = net_em(obs_v.float()/255, actions_t)
loss_obs_v = F.mse_loss(out_obs_next_v.squeeze(-1), obs_next_v)
loss_rew_v = F.mse_loss(out_reward_v.squeeze(-1), rewards_v)
loss_total_v = OBS_WEIGHT * loss_obs_v + REWARD_WEIGHT * loss_rew_v
loss_total_v.backward()
optimizer.step()
loss = loss_total_v.data.cpu().numpy()
if loss < best_loss:
print("Best loss updated: %.4e -> %.4e" % (best_loss, loss))
best_loss = loss
fname = "pacman_env.net"
print("Saving Network")
print("STEP", step_idx)
torch.save(net_em.state_dict(), fname)
step_idx += 1
if step_idx % SAVE_EVERY_BATCH == 0:
fname = "breakout.env"
print("Saving Network")
print("STEP", step_idx)
torch.save(net_em.state_dict(), fname)
if step_idx % 200 == 0:
print("STEP", step_idx, "Loss updated: %.4e -> %.4e" % (best_loss, loss))
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
import gym
import time
import torch.nn.utils as nn_utils
from actor_critic_02 import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import *
import common
LEARNING_RATE = 1e-4
TEST_EVERY_BATCH = 1000
USE_CUDA = torch.cuda.is_available()
NUM_ENVS = 16
REWARD_STEPS = 5
GAMMA = 0.99
BATCH_SIZE = REWARD_STEPS * 16
CLIP_GRAD = 0.5
ENTROPY_BETA = 0.01
VALUE_LOSS_COEF = 0.5
OBS_WEIGHT = 10.0
REWARD_WEIGHT = 1.0
FRAMES_COUNT = 2
IMG_SHAPE = (FRAMES_COUNT, 84, 84)
EM_OUT_SHAPE = (1, ) + IMG_SHAPE[1:]
NUM_OF_EPISODES = 300000
SAVE_EVERY_BATCH = 5000
atari_games = [
'CarnivalNoFrameskip-v4',
'AlienNoFrameskip-v4',
'AmidarNoFrameskip-v4',
'BankHeistNoFrameskip-v4',
'MsPacmanNoFrameskip-v4',
'TutankhamNoFrameskip-v4',
'VentureNoFrameskip-v4',
'WizardOfWorNoFrameskip-v4',
'AssaultNoFrameskip-v4',
'AsteroidsNoFrameskip-v4',
'BeamRiderNoFrameskip-v4',
'CentipedeNoFrameskip-v4',
'ChopperCommandNoFrameskip-v4',
'CrazyClimberNoFrameskip-v4',
# 'DemonAttackNoFrameskip-v4',
# 'AtlantisNoFrameskip-v4',
# 'GravitarNoFrameskip-v4',
# 'PhoenixNoFrameskip-v4',
# 'PooyanNoFrameskip-v4',
# 'RiverraidNoFrameskip-v4',
# 'SeaquestNoFrameskip-v4',
# 'SpaceInvadersNoFrameskip-v4',
# 'StarGunnerNoFrameskip-v4',
# 'TimePilotNoFrameskip-v4',
# 'ZaxxonNoFrameskip-v4',
# 'YarsRevengeNoFrameskip-v4',
# 'AsterixNoFrameskip-v4',
# 'ElevatorActionNoFrameskip-v4',
# 'BerzerkNoFrameskip-v4',
# 'FreewayNoFrameskip-v4',
# 'FrostbiteNoFrameskip-v4',
# 'JourneyEscapeNoFrameskip-v4',
# 'KangarooNoFrameskip-v4',
# 'KrullNoFrameskip-v4',
# 'PitfallNoFrameskip-v4',
# 'SkiingNoFrameskip-v4',
# 'UpNDownNoFrameskip-v4',
# 'QbertNoFrameskip-v4',
# 'RoadRunnerNoFrameskip-v4',
# 'DoubleDunkNoFrameskip-v4',
# 'IceHockeyNoFrameskip-v4',
# 'MontezumaRevengeNoFrameskip-v4',
# 'GopherNoFrameskip-v4',
# 'BreakoutNoFrameskip-v4',
# 'PongNoFrameskip-v4',
# 'PrivateEyeNoFrameskip-v4',
# 'TennisNoFrameskip-v4',
# 'VideoPinballNoFrameskip-v4',
# 'FishingDerbyNoFrameskip-v4',
# 'NameThisGameNoFrameskip-v4',
# 'BowlingNoFrameskip-v4',
# 'BattleZoneNoFrameskip-v4',
# 'BoxingNoFrameskip-v4',
# 'JamesbondNoFrameskip-v4',
# 'RobotankNoFrameskip-v4',
# 'SolarisNoFrameskip-v4',
# 'EnduroNoFrameskip-v4',
# 'KungFuMasterNoFrameskip-v4',
]
if __name__ == "__main__":
device = torch.device("cuda" if USE_CUDA else "cpu")
envs = [common.make_env() for _ in range(NUM_ENVS)]
test_env = common.make_env(test=True)
net = ActorCritic(envs[0].observation_space.shape, envs[0].action_space.n).to(device)
print(net)
optimizer = optim.RMSprop(net.parameters(), lr=LEARNING_RATE, eps=1e-5)
step_idx = 0
total_steps = 1000
best_reward = None
ts_start = time.time()
best_test_reward = None
for mb_obs, mb_rewards, mb_actions, mb_values, _, done_rewards, done_steps in \
common.iterate_batches(envs, net, device=device):
if len(done_rewards) > 0:
total_steps += sum(done_steps)
speed = total_steps / (time.time() - ts_start)
if best_reward is None:
best_reward = done_rewards.max()
elif best_reward < done_rewards.max():
best_reward = done_rewards.max()
common.train_a2c(net, mb_obs, mb_rewards, mb_actions, mb_values,
optimizer, step_idx, device=device)
step_idx += 1
# if step_idx % 1000 == 0:
# print("step", step_idx)
if step_idx % SAVE_EVERY_BATCH == 0:
fname = "breakout_a2c.pth"
torch.save(net.state_dict(), fname)
if step_idx % TEST_EVERY_BATCH == 0:
test_reward, test_steps = common.test_model(test_env, net, device=device)
if best_test_reward is None or best_test_reward < test_reward:
if best_test_reward is not None:
fname = "breakout_a2c.pth"
torch.save(net.state_dict(), fname)
print("Saving Net")
best_test_reward = test_reward
print("%d: test reward=%.2f, steps=%.2f, best_reward=%.2f" % (
step_idx, test_reward, test_steps, best_test_reward))
fname = "breakout_a2c.pth"
torch.save(net.state_dict(), fname)
<file_sep>import gym
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.autograd as autograd
import wrapper
from actor_critic_02 import ActorCritic
from i2a_02 import *
from environment_model import *
import common
mode = "regular"
USE_CUDA = torch.cuda.is_available()
FRAMES_COUNT = 2
env_name = "Breakout-v0"
env = common.make_env(test=True)
state_shape = env.observation_space.shape
action_space = env.action_space.n
##RANDOM TEST
rewards_per_episode = 0
list_of_rewards = []
for i_episode in range(20):
rewards_per_episode = 0
observation = env.reset()
done = False
t = 0
while not done:
t += 1
action = env.action_space.sample()
observation, reward, done, info = env.step(action)
rewards_per_episode += reward
list_of_rewards.append(rewards_per_episode)
print("random actions training")
print(list_of_rewards)
print("RANDOM: One Million Updates MEAN", np.mean(list_of_rewards))
#A2C TEST
actor_critic = ActorCritic(state_shape, action_space)
if USE_CUDA:
actor_critic = actor_critic.cuda()
actor_critic.load_state_dict(torch.load("pacman_one_million1"))
device = torch.device("cuda" if USE_CUDA else "cpu")
list_of_rewards = []
total_reward = 0.0
total_steps = 0
agent = common.PolicyAgent(lambda x: actor_critic(x)[0], device=device, apply_softmax=True)
done = False
for _ in range(20):
obs = env.reset()
total_reward = 0.0
done = False
while not done:
env.render()
action = agent([obs])[0][0]
obs, r, done, _ = env.step(action)
total_reward += r
list_of_rewards.append(total_reward)
print("One Million Updates", list_of_rewards)
print("One Million Updates MEAN", np.mean(list_of_rewards))
#I2A test
# actor_critic = ActorCritic(state_shape, action_space)
# if USE_CUDA:
# actor_critic = actor_critic.cuda()
# #actor_critic.load_state_dict(torch.load("pacman_one_million1"))
# device = torch.device("cuda" if USE_CUDA else "cpu")
# list_of_rewards = []
# total_reward = 0.0
# total_steps = 0
# net_em = EnvironmentModel(state_shape, action_space)
# net_em.load_state_dict(torch.load("pacman_one_million_env_model"))
# net_em = net_em.to(device)
# ROLLOUTS_STEPS = 3
# net_i2a = I2A(state_shape, action_space, net_em, actor_critic, ROLLOUTS_STEPS).to(device)
# net_em.load_state_dict(torch.load("pacman_one_million_i2a"))
# print(net_i2a)
# agent = PolicyAgent(lambda x: net_i2a(x)[0], device=device, apply_softmax=True)
# done = False
# for _ in range(20):
# obs = env.reset()
# total_reward = 0.0
# done = False
# while not done:
# action = agent([obs])[0][0]
# obs, r, done, _ = env.step(action)
# total_reward += r
# list_of_rewards.append(total_reward)
# print("I2A: One Million Updates", list_of_rewards)
# print("I2A: One Million Updates MEAN", np.mean(list_of_rewards))
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
import gym
import time
import torch.nn.utils as nn_utils
from actor_critic_02 import ActorCritic
LEARNING_RATE = 1e-4
TEST_EVERY_BATCH = 1000
USE_CUDA = torch.cuda.is_available()
NUM_ENVS = 16
REWARD_STEPS = 5
GAMMA = 0.99
BATCH_SIZE = REWARD_STEPS * 16
CLIP_GRAD = 0.5
ENTROPY_BETA = 0.01
VALUE_LOSS_COEF = 0.5
OBS_WEIGHT = 10.0
REWARD_WEIGHT = 1.0
FRAMES_COUNT = 2
IMG_SHAPE = (FRAMES_COUNT, 84, 84)
EM_OUT_SHAPE = (1, ) + IMG_SHAPE[1:]
NUM_OF_EPISODES = 1000000
ACT_PONDER_PENALTY = 1
class ActionSelector:
"""
Abstract class which converts scores to the actions
"""
def __call__(self, scores):
raise NotImplementedError
class ProbabilityActionSelector(ActionSelector):
"""
Converts probabilities of actions into action by sampling them
"""
def __call__(self, probs):
assert isinstance(probs, np.ndarray)
actions = []
for prob in probs:
actions.append(np.random.choice(len(prob), p=prob))
return np.array(actions)
def default_states_preprocessor(states):
"""
Convert list of states into the form suitable for model. By default we assume Variable
:param states: list of numpy arrays with states
:return: Variable
"""
if len(states) == 1:
np_states = np.expand_dims(states[0], 0)
else:
np_states = np.array([np.array(s, copy=False) for s in states], copy=False)
return torch.tensor(np_states)
def discount_with_dones(rewards, dones, gamma):
discounted = []
r = 0
for reward, done in zip(rewards[::-1], dones[::-1]):
r = reward + gamma*r*(1.-done)
discounted.append(r)
return discounted[::-1]
def iterate_batches(envs, net, device="cpu", act=False):
n_actions = envs[0].action_space.n
act_selector = ProbabilityActionSelector()
obs = [e.reset() for e in envs]
batch_dones = [[False] for _ in range(NUM_ENVS)]
total_reward = [0.0] * NUM_ENVS
total_steps = [0] * NUM_ENVS
mb_obs = np.zeros((NUM_ENVS, REWARD_STEPS) + IMG_SHAPE, dtype=np.uint8)
mb_rewards = np.zeros((NUM_ENVS, REWARD_STEPS), dtype=np.float32)
mb_values = np.zeros((NUM_ENVS, REWARD_STEPS), dtype=np.float32)
mb_actions = np.zeros((NUM_ENVS, REWARD_STEPS), dtype=np.int32)
mb_probs = np.zeros((NUM_ENVS, REWARD_STEPS, n_actions), dtype=np.float32)
for _ in range(NUM_OF_EPISODES):
batch_dones = [[dones[-1]] for dones in batch_dones]
done_rewards = []
done_steps = []
for n in range(REWARD_STEPS):
obs_v = default_states_preprocessor(obs).to(device)
mb_obs[:, n] = obs_v.data.cpu().numpy()
logits_v, values_v, _ = net(obs_v)
probs_v = F.softmax(logits_v, dim=1)
probs = probs_v.data.cpu().numpy()
actions = act_selector(probs)
mb_probs[:, n] = probs
mb_actions[:, n] = actions
mb_values[:, n] = values_v.squeeze().data.cpu().numpy()
for e_idx, e in enumerate(envs):
o, r, done, _ = e.step(actions[e_idx])
total_reward[e_idx] += r
total_steps[e_idx] += 1
if done:
o = e.reset()
done_rewards.append(total_reward[e_idx])
done_steps.append(total_steps[e_idx])
total_reward[e_idx] = 0.0
total_steps[e_idx] = 0
obs[e_idx] = o
mb_rewards[e_idx, n] = r
batch_dones[e_idx].append(done)
# obtain values for the last observation
obs_v = default_states_preprocessor(obs).to(device)
_, values_v, _ = net(obs_v)
values_last = values_v.squeeze().data.cpu().numpy()
for e_idx, (rewards, dones, value) in enumerate(zip(mb_rewards, batch_dones, values_last)):
rewards = rewards.tolist()
if not dones[-1]:
rewards = discount_with_dones(rewards + [value], dones[1:] + [False], GAMMA)[:-1]
else:
rewards = discount_with_dones(rewards, dones[1:], GAMMA)
mb_rewards[e_idx] = rewards
out_mb_obs = mb_obs.reshape((-1,) + IMG_SHAPE)
out_mb_rewards = mb_rewards.flatten()
out_mb_actions = mb_actions.flatten()
out_mb_values = mb_values.flatten()
out_mb_probs = mb_probs.flatten()
yield out_mb_obs, out_mb_rewards, out_mb_actions, out_mb_values, out_mb_probs, \
np.array(done_rewards), np.array(done_steps)
def train_a2c(net, mb_obs, mb_rewards, mb_actions, mb_values, optimizer, step_idx, device="cpu", act=False):
optimizer.zero_grad()
mb_adv = mb_rewards - mb_values
adv_v = torch.FloatTensor(mb_adv).to(device)
obs_v = torch.FloatTensor(mb_obs).to(device)
rewards_v = torch.FloatTensor(mb_rewards).to(device)
actions_t = torch.LongTensor(mb_actions).to(device)
logits_v, values_v, ponder_dict = net(obs_v)
log_prob_v = F.log_softmax(logits_v, dim=1)
log_prob_actions_v = adv_v * log_prob_v[range(len(mb_actions)), actions_t]
loss_policy_v = -log_prob_actions_v.mean()
loss_value_v = F.mse_loss(values_v.squeeze(-1), rewards_v)
prob_v = F.softmax(logits_v, dim=1)
entropy_loss_v = (prob_v * log_prob_v).sum(dim=1).mean()
loss_v = ENTROPY_BETA * entropy_loss_v + VALUE_LOSS_COEF * loss_value_v + loss_policy_v
if ponder_dict:
loss_v += (
ACT_PONDER_PENALTY * ponder_dict["ponder_cost"].mean()
)
loss_v.backward()
nn_utils.clip_grad_norm_(net.parameters(), CLIP_GRAD)
optimizer.step()
return obs_v
def make_env(test=False, clip=True):
if test:
args = {'reward_clipping': False,
'episodic_life': False}
else:
args = {'reward_clipping': clip}
return wrapper.wrap_dqn(gym.make('BreakoutNoFrameskip-v4'),
stack_frames=FRAMES_COUNT,
**args)
class BaseAgent:
"""
Abstract Agent interface
"""
def initial_state(self):
"""
Should create initial empty state for the agent. It will be called for the start of the episode
:return: Anything agent want to remember
"""
return None
def __call__(self, states, agent_states):
"""
Convert observations and states into actions to take
:param states: list of environment states to process
:param agent_states: list of states with the same length as observations
:return: tuple of actions, states
"""
assert isinstance(states, list)
assert isinstance(agent_states, list)
assert len(agent_states) == len(states)
raise NotImplementedError
class PolicyAgent(BaseAgent):
"""
Policy agent gets action probabilities from the model and samples actions from it
"""
# TODO: unify code with DQNAgent, as only action selector is differs.
def __init__(self, model, action_selector=ProbabilityActionSelector(), device="cpu",
apply_softmax=False, preprocessor=default_states_preprocessor):
self.model = model
self.action_selector = action_selector
self.device = device
self.apply_softmax = apply_softmax
self.preprocessor = preprocessor
def __call__(self, states, agent_states=None):
"""
Return actions from given list of states
:param states: list of states
:return: list of actions
"""
if agent_states is None:
agent_states = [None] * len(states)
if self.preprocessor is not None:
states = self.preprocessor(states)
if torch.is_tensor(states):
states = states.to(self.device)
probs_v = self.model(states)
if self.apply_softmax:
probs_v = F.softmax(probs_v, dim=1)
probs = probs_v.data.cpu().numpy()
actions = self.action_selector(probs)
return np.array(actions), agent_states
def test_model(env, net, rounds=3, device="cpu"):
total_reward = 0.0
total_steps = 0
agent = PolicyAgent(lambda x: net(x)[0], device=device, apply_softmax=True)
for _ in range(rounds):
obs = env.reset()
while True:
action = agent([obs])[0][0]
obs, r, done, _ = env.step(action)
total_reward += r
total_steps += 1
if done:
break
return total_reward / rounds, total_steps / rounds
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
ROLLOUT_HIDDEN = 256
ROLLOUT_HIDDEN = 256
FRAMES_COUNT = 2
IMG_SHAPE = (FRAMES_COUNT, 84, 84)
EM_OUT_SHAPE = (1, ) + IMG_SHAPE[1:]
class EnvironmentModel(nn.Module):
def __init__(self, input_shape, n_actions):
super(EnvironmentModel, self).__init__()
self.input_shape = input_shape
self.n_actions = n_actions
# input color planes will be equal to frames plus one-hot encoded actions
n_planes = input_shape[0] + n_actions
self.conv1 = nn.Sequential(
nn.Conv2d(n_planes, 64, kernel_size=4, stride=4, padding=1),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.ReLU(),
)
self.conv2 = nn.Sequential(
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.ReLU()
)
# output is one single frame with delta from the current frame
self.deconv = nn.ConvTranspose2d(64, 1, kernel_size=4, stride=4, padding=0)
self.reward_conv = nn.Sequential(
nn.Conv2d(64, 64, kernel_size=3),
nn.MaxPool2d(2),
nn.ReLU(),
nn.Conv2d(64, 64, kernel_size=3),
nn.MaxPool2d(2),
nn.ReLU()
)
rw_conv_out = self._get_reward_conv_out((n_planes, ) + input_shape[1:])
self.reward_fc = nn.Sequential(
nn.Linear(rw_conv_out, 128),
nn.ReLU(),
nn.Linear(128, 1)
)
def _get_reward_conv_out(self, shape):
o = self.conv1(torch.zeros(1, *shape))
o = self.reward_conv(o)
return int(np.prod(o.size()))
def forward(self, imgs, actions):
batch_size = actions.size()[0]
act_planes_v = torch.FloatTensor(batch_size, self.n_actions, *self.input_shape[1:]).zero_().to(actions.device)
act_planes_v[range(batch_size), actions] = 1.0
comb_input_v = torch.cat((imgs, act_planes_v), dim=1)
c1_out = self.conv1(comb_input_v)
c2_out = self.conv2(c1_out)
c2_out += c1_out
img_out = self.deconv(c2_out)
rew_conv = self.reward_conv(c2_out).view(batch_size, -1)
rew_out = self.reward_fc(rew_conv)
return img_out, rew_out<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.autograd as autograd
import wrapper
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from actor_critic import *
from breakout import *
from IPython.display import clear_output
#import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
mode = "regular"
num_envs = 16
env_name = "Breakout-v0"
def make_env():
def _thunk():
env = wrapper.make_env(env_name)
return env
return _thunk
env = make_env()
envs = [make_env() for i in range(num_envs)]
envs = SubprocVecEnv(envs)
state_shape = env().observation_space.shape
action_space = env().action_space.n
#a2c hyperparams:
gamma = 0.99
entropy_coef = 0.01
value_loss_coef = 0.5
max_grad_norm = 0.5
num_steps = 5
num_frames = int(10e4)
#rmsprop hyperparams:
lr = 7e-4
eps = 1e-5
alpha = 0.99
#Init a2c and rmsprop
actor_critic = ActorCritic(state_shape, action_space)
optimizer = optim.RMSprop(actor_critic.parameters(), lr, eps=eps, alpha=alpha)
if USE_CUDA:
actor_critic = actor_critic.cuda()
rollout = RolloutStorage(num_steps, num_envs, state_shape)
rollout.cuda()
all_rewards = []
all_losses = []
state = envs.reset()
# #print("state len:",len(state))
state = torch.FloatTensor(np.float32(state))
rollout.states[0].copy_(state)
episode_rewards = torch.zeros(num_envs, 1)
final_rewards = torch.zeros(num_envs, 1)
action = actor_critic.act(Variable(state))
print(action)
for i_update in range(num_frames):
for step in range(num_steps):
action = actor_critic.act(Variable(state))
next_state, reward, done, _ = envs.step(action.squeeze(1).cpu().data.numpy())
reward = torch.FloatTensor(reward).unsqueeze(1)
episode_rewards += reward
masks = torch.FloatTensor(1-np.array(done)).unsqueeze(1)
final_rewards *= masks
final_rewards += (1-masks) * episode_rewards
episode_rewards *= masks
if USE_CUDA:
masks = masks.cuda()
state = torch.FloatTensor(np.float32(next_state))
rollout.insert(step, state, action.data, reward, masks)
_, next_value = actor_critic(Variable(rollout.states[-1], volatile=True))
next_value = next_value.data
returns = rollout.compute_returns(next_value, gamma)
logit, action_log_probs, values, entropy = actor_critic.evaluate_actions(
Variable(rollout.states[:-1]).view(-1, *state_shape),
Variable(rollout.actions).view(-1, 1)
)
values = values.view(num_steps, num_envs, 1)
action_log_probs = action_log_probs.view(num_steps, num_envs, 1)
advantages = Variable(returns) - values
value_loss = advantages.pow(2).mean()
action_loss = -(Variable(advantages.data) * action_log_probs).mean()
optimizer.zero_grad()
loss = value_loss * value_loss_coef + action_loss - entropy * entropy_coef
loss.backward()
nn.utils.clip_grad_norm(actor_critic.parameters(), max_grad_norm)
optimizer.step()
if i_update % 100 == 0:
print("i_update",i_update)
# all_rewards.append(final_rewards.mean())
# all_losses.append(loss.data[0])
# plt.figure(figsize=(20,5))
# plt.subplot(131)
# plt.title('epoch %s. reward: %s' % (i_update, np.mean(all_rewards[-10:])))
# plt.plot(all_rewards)
# plt.subplot(132)
# plt.title('loss %s' % all_losses[-1])
# plt.plot(all_losses)
# #plt.show()
rollout.after_update()
torch.save(actor_critic.state_dict(), "breakout_cien_mil")
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import torch.autograd as autograd
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import EnvModel
from actor_critic import OnPolicy, ActorCritic, RolloutStorage
from i2a import *
from IPython.display import clear_output
import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
Variable1 = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
pixels = (
(0.0, 1.0, 0.0),
(0.0, 1.0, 1.0),
(0.0, 0.0, 1.0),
(1.0, 1.0, 1.0),
(1.0, 1.0, 0.0),
(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)
)
pixel_to_onehot = {pix:i for i, pix in enumerate(pixels)}
num_pixels = len(pixels)
task_rewards = {
"regular": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9],
"avoid": [0.1, -0.1, -5, -10, -20],
"hunt": [0, 1, 10, -20],
"ambush": [0, -0.1, 10, -20],
"rush": [0, -0.1, 9.9]
}
reward_to_onehot = {mode: {reward:i for i, reward in enumerate(task_rewards[mode])} for mode in task_rewards.keys()}
def pix_to_target(next_states):
target = []
for pixel in next_states.transpose(0, 2, 3, 1).reshape(-1, 3):
target.append(pixel_to_onehot[tuple([np.round(pixel[0]), np.round(pixel[1]), np.round(pixel[2])])])
return target
def target_to_pix(imagined_states):
pixels = []
to_pixel = {value: key for key, value in pixel_to_onehot.items()}
for target in imagined_states:
pixels.append(list(to_pixel[target]))
return np.array(pixels)
def rewards_to_target(mode, rewards):
target = []
for reward in rewards:
target.append(reward_to_onehot[mode][reward])
return target
# def displayImage(image, step, reward):
# s = str(step) + " " + str(reward)
# plt.title(s)
# plt.imshow(image)
# plt.show()
mode = "regular"
num_envs = 16
def make_env():
def _thunk():
env = MiniPacman(mode, 1000)
return env
return _thunk
envs = [make_env() for i in range(num_envs)]
envs = SubprocVecEnv(envs)
state_shape = envs.observation_space.shape
num_actions = envs.action_space.n
num_rewards = len(task_rewards[mode])
#TRAIN I2A
full_rollout = True
env_model = EnvModel(envs.observation_space.shape, num_pixels, num_rewards)
env_model.load_state_dict(torch.load("env_model_" + mode))
distil_policy = ActorCritic(envs.observation_space.shape, envs.action_space.n)
distil_optimizer = optim.Adam(distil_policy.parameters())
imagination = ImaginationCore(1, state_shape, num_actions, num_rewards, env_model, distil_policy, full_rollout=full_rollout)
actor_critic = I2A(state_shape, num_actions, num_rewards, 256, imagination, full_rollout=full_rollout)
#rmsprop hyperparams:
lr = 7e-4
eps = 1e-5
alpha = 0.99
optimizer = optim.RMSprop(actor_critic.parameters(), lr, eps=eps, alpha=alpha)
if USE_CUDA:
env_model = env_model.cuda()
distil_policy = distil_policy.cuda()
actor_critic = actor_critic.cuda()
import time
def displayImage(image, step, reward):
clear_output(True)
s = "step: " + str(step) + " reward: " + str(reward)
plt.figure(figsize=(10,3))
plt.title(s)
plt.imshow(image)
plt.show()
time.sleep(0.1)
env = MiniPacman(mode, 1000)
done = False
state = env.reset()
total_reward = 0
step = 1
while not done:
current_state = torch.FloatTensor(state).unsqueeze(0)
if USE_CUDA:
current_state = current_state.cuda()
action = actor_critic.act(Variable1(current_state))
next_state, reward, done, _ = env.step(action.data[0, 0])
total_reward += reward
state = next_state
image = torch.FloatTensor(state).permute(1, 2, 0).cpu().numpy()
displayImage(image, step, total_reward)
step += 1<file_sep>import torch
from torch import nn
import torch.nn.functional as F
from torch.autograd import Variable
class ACTFromCell(nn.Module):
def __init__(self, rnn_cell, max_ponder=100, epsilon=0.01,
batch_first=False):
super(ACTFromCell, self).__init__()
self.rnn_cell = rnn_cell
self.batch_first = batch_first
self.max_ponder = max_ponder
self.epsilon = epsilon
self._is_lstm = isinstance(self.rnn_cell, nn.LSTMCell)
self.ponder_linear = nn.Linear(self.rnn_cell.hidden_size, 1)
def forward(self, input_, hx=None, compute_ponder_cost=True):
if self.batch_first:
# Move batch to second
input_ = input_.transpose(0, 1)
if hx is None:
hx = Variable(input_.data.new(
input_.size(1), self.rnn_cell.hidden_size
).zero_())
if self._is_lstm:
cx = hx
# Pre-allocate variables
time_size, batch_size, input_dim_size = input_.size()
selector = input_.data.new(batch_size).byte()
hx_list, cx_list = [], []
ponder_cost = 0
ponder_times = []
# For each t
for input_row in input_:
accum_h = Variable(input_.data.new(batch_size).zero_())
accum_hx = Variable(input_.data.new(
input_.size(1), self.rnn_cell.hidden_size
).zero_())
if self._is_lstm:
accum_cx = Variable(input_.data.new(
input_.size(1), self.rnn_cell.hidden_size
).zero_())
selector = selector.fill_(1)
if self._is_lstm:
accum_cx = accum_cx.zero_()
step_count = Variable(input_.data.new(batch_size).zero_())
input_row_with_flag = torch.cat([
input_row,
Variable(input_row.data.new(batch_size, 1).zero_())
], dim=1)
if compute_ponder_cost:
step_ponder_cost = Variable(input_.data.new(batch_size).zero_())
for act_step in range(self.max_ponder):
idx = bool_to_idx(selector)
if compute_ponder_cost:
# Weird but matches formulation
step_ponder_cost[idx] = -accum_h[idx]
if self._is_lstm:
hx[idx], cx[idx] = self.rnn_cell(
input_row_with_flag[idx], (hx[idx], cx[idx]))
else:
hx[idx] = self.rnn_cell(input_row_with_flag[idx], hx[idx])
accum_hx[idx] += hx[idx]
h = F.sigmoid(self.ponder_linear(hx[idx]).squeeze(1))
accum_h[idx] += h
p = h - (accum_h[idx] - 1).clamp(min=0)
accum_hx[idx] += p.unsqueeze(1) * hx[idx]
if self._is_lstm:
accum_cx[idx] += p.unsqueeze(1) * cx[idx]
step_count[idx] += 1
selector = (accum_h < 1 - self.epsilon).data
if not selector.any():
break
input_row_with_flag[:, input_dim_size] = 1
ponder_times.append(step_count.data.cpu().numpy())
if compute_ponder_cost:
ponder_cost += step_ponder_cost
hx = accum_hx / step_count.clone().unsqueeze(1)
hx_list.append(hx)
if self._is_lstm:
cx = accum_cx / step_count.clone().unsqueeze(1)
cx_list.append(cx)
if self._is_lstm:
all_hx = [
torch.stack(hx_list),
torch.stack(cx_list),
]
hx, cx = hx.unsqueeze(0), cx.unsqueeze(1)
else:
all_hx = torch.stack(hx_list)
hx = hx.unsqueeze(0)
if self.batch_first:
# Move batch to first
if self._is_lstm:
all_hx = all_hx[0].transpose(0, 1)
else:
all_hx = all_hx.transpose(0, 1)
return all_hx, hx, {
"ponder_cost": ponder_cost,
"ponder_times": ponder_times,
}
def reset_parameters(self):
self.rnn_cell.reset_parameters()
self.ponder_linear.reset_parameters()
self.ponder_linear.bias.data.fill_(1)
def bool_to_idx(idx):
return idx.nonzero().squeeze(1)
def resolve_model(config):
if config.use_act:
model_class = ParityACTModel
else:
model_class = ParityRNNModel
model = model_class(config)
if config.cuda:
model = model.cuda()
return model
<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
from actor_critic import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import *
from IPython.display import clear_output
#import matplotlib.pyplot as plt
USE_CUDA = torch.cuda.is_available()
Variable = lambda *args, **kwargs: autograd.Variable(*args, **kwargs).cuda() if USE_CUDA else autograd.Variable(*args, **kwargs)
mode = "regular"
num_envs = 16
env_name = "Breakout-v0"
def make_env():
def _thunk():
env = wrapper.make_env(env_name)
return env
return _thunk
env = make_env()
envs = [make_env() for i in range(num_envs)]
envs = SubprocVecEnv(envs)
state_shape = env().observation_space.shape
action_space = env().action_space.n
num_pixels = 210
print("state shape", state_shape)
print("action_space", action_space)
env_model = EnvModel(state_shape, num_pixels, num_rewards=6)#len(mode_rewards["regular"]))
actor_critic = ActorCritic(state_shape, action_space)
criterion = nn.CrossEntropyLoss()
optimizer = optim.Adam(env_model.parameters())
if USE_CUDA:
env_model = env_model.cuda()
actor_critic = actor_critic.cuda()
actor_critic.load_state_dict(torch.load("breakout_cien_mil"))
def pix_to_target(next_states):
target = []
for pixel in next_states.transpose(0, 2, 3, 1).reshape(-1, 3):
target.append(pixel_to_categorical[tuple([np.ceil(pixel[0]), np.ceil(pixel[1]), np.ceil(pixel[2])])])
return target
def target_to_pix(imagined_states):
pixels = []
to_pixel = {value: key for key, value in pixel_to_categorical.items()}
for target in imagined_states:
pixels.append(list(to_pixel[target]))
return np.array(pixels)
def rewards_to_target(mode, rewards):
target = []
for reward in rewards:
target.append(reward_to_categorical[mode][reward])
return target
def get_action(state):
if state.ndim == 4:
state = torch.FloatTensor(np.float32(state))
else:
state = torch.FloatTensor(np.float32(state)).unsqueeze(0)
action = actor_critic.act(Variable(state, volatile=True))
action = action.data.cpu().squeeze(1).numpy()
return action
def play_games(envs, frames):
states = envs.reset()
for frame_idx in range(frames):
actions = get_action(states)
next_states, rewards, dones, _ = envs.step(actions)
yield frame_idx, states, actions, rewards, next_states, dones
states = next_states
reward_coef = 0.1
num_updates = 10000
losses = []
all_rewards = []
for frame_idx, states, actions, rewards, next_states, dones in play_games(envs, num_updates):
states = torch.FloatTensor(states)
actions = torch.LongTensor(actions)
batch_size = states.size(0)
onehot_actions = torch.zeros(batch_size, action_space, *state_shape[1:])
onehot_actions[range(batch_size), actions] = 1
inputs = Variable(torch.cat([states, onehot_actions], 1))
# print()
# print("INSIDE LOOP")
# print("states_size",states.size())
# print("actions_size",actions.size())
# print("one_hot_action_size",onehot_actions.size())
# print("inputs_size",inputs.size())
if USE_CUDA:
inputs = inputs.cuda()
# print()
# print("INSIDE NET")
imagined_state, imagined_reward = env_model(inputs)#states, onehot_actions)
target_state = pix_to_target(next_states)
target_state = Variable(torch.LongTensor(target_state))
target_reward = rewards_to_target(mode, rewards)
target_reward = Variable(torch.LongTensor(target_reward))
optimizer.zero_grad()
image_loss = criterion(imagined_state, target_state)
reward_loss = criterion(imagined_reward, target_reward)
loss = image_loss + reward_coef * reward_loss
loss.backward()
optimizer.step()
losses.append(loss.data[0])
all_rewards.append(np.mean(rewards))
if frame_idx % 100 == 0:
print("frame", frame_idx)
# plot(frame_idx, all_rewards, losses)
torch.save(env_model.state_dict(), "breakout_model")
<file_sep>import gym
from gym import spaces
from deepmind import PillEater, observation_as_rgb
# class DiscreteOneHotWrapper(gym.ObservationWrapper):
# def __init__(self, env):
# super(DiscreteOneHotWrapper, self).__init__(env)
# assert isinstance(env.observation_space, gym.spaces.Discrete)
# self.observation_space = gym.spaces.Box(0.0, 1.0, (env.observation_space.n, ), dtype=np.float32)
# def observation(self, observation):
# res = np.copy(self.observation_space.low)
# res[observation] = 1.0
# return res
class AtariGame:
def __init__(self, mode, frame_cap):
self.mode = mode
self.frame_cap = frame_cap
self.env = gym.make('Breakout-v0')
self.action_space = env.action_space #spaces.Discrete(5)
self.observation_space = env.observation_space #spaces.Box(low=0, high=1.0, shape=(3, 15, 19))
def step(self, action):
self.env.step(action)
env_reward, env_pcontinue, env_frame = self.env.observation()
self.done = env_pcontinue != 1
env_frame = env_frame.transpose(2, 0, 1)
return env_frame, env_reward, self.done, {}
def reset(self):
image, _, _ = self.env.start()
image = observation_as_rgb(image)
self.done = False
image = image.transpose(2, 0, 1)
return image
# def main():
# env = gym.make('MsPacman-v0')
# for i_episode in range(2000):
# observation = env.reset()
# for t in range(200):
# env.render()
# #print(observation)
# action = env.action_space.sample()
# observation, reward, done, info = env.step(action)
# if done:
# print("Episode finished after {} timesteps".format(t+1))
# break
# if __name__ == '__main__':
# main()<file_sep>import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
import gym
import torch.nn.utils as nn_utils
import time
import csv
from actor_critic_02 import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import *
from i2a_02 import *
import common
USE_CUDA = torch.cuda.is_available()
ROLLOUTS_STEPS = 3
LEARNING_RATE = 1e-4
POLICY_LR = 1e-4
TEST_EVERY_BATCH = 1000
NUM_ENVS = 16
NUM_OF_EPISODES = 100000
REWARD_STEPS = 5
GAMMA = 0.99
CLIP_GRAD = 0.5
ENTROPY_BETA = 0.01
VALUE_LOSS_COEF = 0.5
BATCH_SIZE = REWARD_STEPS * 16
SAVE_EVERY_BATCH = 10000
def set_seed(seed, envs=None, cuda=False):
np.random.seed(seed)
torch.manual_seed(seed)
if cuda:
torch.cuda.manual_seed(seed)
if envs:
for idx, env in enumerate(envs):
env.seed(seed + idx)
if __name__ == "__main__":
device = torch.device("cuda" if USE_CUDA else "cpu")
envs = [common.make_env() for _ in range(NUM_ENVS)]
test_env = common.make_env(test=True)
obs_shape = envs[0].observation_space.shape
act_n = envs[0].action_space.n
net_policy = ActorCritic(obs_shape, act_n).to(device)
net_em = EnvironmentModel(obs_shape, act_n)
net_em.load_state_dict(torch.load("breakout.env"))
net_em = net_em.to(device)
net_i2a = I2A(obs_shape, act_n, net_em, net_policy, ROLLOUTS_STEPS).to(device)
print(net_i2a)
obs = envs[0].reset()
obs_v = common.default_states_preprocessor([obs]).to(device)
res = net_i2a(obs_v)
optimizer = optim.RMSprop(net_i2a.parameters(), lr=LEARNING_RATE, eps=1e-5)
policy_opt = optim.Adam(net_policy.parameters(), lr=POLICY_LR)
step_idx = 0
total_steps = 0
ts_start = time.time()
best_reward = None
best_test_reward = None
for mb_obs, mb_rewards, mb_actions, mb_values, mb_probs, done_rewards, done_steps in \
common.iterate_batches(envs, net_i2a, device):
if len(done_rewards) > 0:
total_steps += sum(done_steps)
speed = total_steps / (time.time() - ts_start)
if best_reward is None:
best_reward = done_rewards.max()
elif best_reward < done_rewards.max():
best_reward = done_rewards.max()
obs_v = common.train_a2c(net_i2a, mb_obs, mb_rewards, mb_actions, mb_values,
optimizer, step_idx, device=device)
# policy distillation
probs_v = torch.FloatTensor(mb_probs).to(device)
policy_opt.zero_grad()
logits_v, _ = net_policy(obs_v)
policy_loss_v = -F.log_softmax(logits_v, dim=1) * probs_v.view_as(logits_v)
policy_loss_v = policy_loss_v.sum(dim=1).mean()
policy_loss_v.backward()
policy_opt.step()
step_idx += 1
if step_idx % SAVE_EVERY_BATCH == 0:
fname = "breakout.i2a"
torch.save(net_em.state_dict(), fname)
torch.save(net_policy.state_dict(), fname + ".policy")
if step_idx % TEST_EVERY_BATCH == 0:
test_reward, test_steps = common.test_model(test_env, net_i2a, device=device)
append_to_file = [step_idx, test_reward]
with open('i2a_performance.csv', 'a') as f:
writer = csv.writer(f)
writer.writerow(append_to_file)
if best_test_reward is None or best_test_reward < test_reward:
if best_test_reward is not None:
fname = "breakout.i2a"
torch.save(net_i2a.state_dict(), fname)
torch.save(net_policy.state_dict(), fname + ".policy")
print("Save I2A NET at step", step_idx)
else:
fname = "breakout.env.i2a"
torch.save(net_em.state_dict(), fname)
print("Save I2A ENV NET at step", step_idx)
best_test_reward = test_reward
print("%d: test reward=%.2f, steps=%.2f, best_reward=%.2f" % (
step_idx, test_reward, test_steps, best_test_reward))
fname = "breakout.i2a"
torch.save(net_i2a.state_dict(), fname)
torch.save(net_policy.state_dict(), fname + ".policy")
torch.save(net_em.state_dict(), fname + ".env.dat")
<file_sep>
import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
import torch.autograd as autograd
import torch.nn.functional as F
import wrapper
import gym
import torch.nn.utils as nn_utils
import time
import csv
from actor_critic_02 import ActorCritic
from multiprocessing_env import SubprocVecEnv
from minipacman import MiniPacman
from environment_model import *
from i2a_02 import *
import common
USE_CUDA = torch.cuda.is_available()
ROLLOUTS_STEPS = 3
LEARNING_RATE = 1e-4
POLICY_LR = 1e-4
TEST_EVERY_BATCH = 1000
NUM_ENVS = 16
NUM_OF_EPISODES = 100000
REWARD_STEPS = 5
GAMMA = 0.99
CLIP_GRAD = 0.5
ENTROPY_BETA = 0.01
VALUE_LOSS_COEF = 0.5
BATCH_SIZE = REWARD_STEPS * 16
SAVE_EVERY_BATCH = 10000
def set_seed(seed, envs=None, cuda=False):
np.random.seed(seed)
torch.manual_seed(seed)
if cuda:
torch.cuda.manual_seed(seed)
if envs:
for idx, env in enumerate(envs):
env.seed(seed + idx)
if __name__ == "__main__":
device = torch.device("cuda" if USE_CUDA else "cpu")
|
473fe35915fe8dd8c483d2acbda136badf184eb8
|
[
"Python"
] | 17
|
Python
|
fcancino/reinforcement_learning_experiments
|
338affcb6358a0f6c5f6ee6c8872a1769437b8d0
|
ab7a5997949dab6c1290821b351e9ca95138a07f
|
refs/heads/master
|
<repo_name>harvestcloud/react-client<file_sep>/src/App.js
import React from 'react';
import './App.css';
function WhatDoesTheServerSay() {
return (
<div className="what-does-the-server-say">
<h2>
What does the <span className="fox">fox</span> <em>server</em> say?
</h2>
<div className="alert alert-success">
<pre>Hello</pre>
Hello
</div>
</div>
);
}
function App() {
return (
<div className="App">
<h1>Harvest Cloud</h1>
<hr />
<WhatDoesTheServerSay />
</div>
);
}
export default App;
<file_sep>/Dockerfile
# Build stage
FROM node:8.17 AS build
WORKDIR /usr/src/app
COPY package.json yarn.lock ./
RUN yarn
COPY . ./
RUN yarn build
CMD ["yarn", "start"]
# Prod stage
FROM nginx:1.12-alpine as prod
COPY --from=build /usr/src/app/build /usr/share/nginx/html
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]
|
383a8a2a7264d50d98e997f965e071c789032411
|
[
"JavaScript",
"Dockerfile"
] | 2
|
JavaScript
|
harvestcloud/react-client
|
ef02b4404d99a46a2e91687a0865372761f81880
|
bc4603767002052522c8c83958f1841e0f094b39
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.