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>InfiniteSkipper55/School-Parent-Communication-Application<file_sep>/src/main/java/com/cg/spc/service/IDiaryNotesServiceImplementation.java package com.cg.spc.service; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.spc.entities.DiaryNotes; import com.cg.spc.repository.DiaryNotesRepository; @Service public class IDiaryNotesServiceImplementation implements DiaryNotesService { @Autowired private DiaryNotesRepository diaryNotesRepository; @Override public DiaryNotes addDiaryNotes(DiaryNotes diaryNotes) { return diaryNotesRepository.save(diaryNotes); } @Override public DiaryNotes updateDiaryNotes(DiaryNotes diaryNotes) { Optional<DiaryNotes> optional = diaryNotesRepository.findById(diaryNotes.getDiaryNotesId()); if (optional.isPresent()) { diaryNotesRepository.saveAndFlush(diaryNotes); } return diaryNotes; } @Override public DiaryNotes deleteDiaryNotes(int diaryNotesId) { Optional<DiaryNotes> existingDiaryNotesContainer = diaryNotesRepository.findById(diaryNotesId); DiaryNotes existingDiaryNotes = null; if (existingDiaryNotesContainer.isPresent()) { existingDiaryNotes = existingDiaryNotesContainer.get(); diaryNotesRepository.deleteById(diaryNotesId); } return existingDiaryNotes; } @Override public List<DiaryNotes> retrieveAllDiaryNotesByDate(Date dateOfDiaryNotes) { List<DiaryNotes> existingDiaryNotes = diaryNotesRepository.findByDate(dateOfDiaryNotes); Collections.sort(existingDiaryNotes, new Comparator<DiaryNotes>() { public int compare(DiaryNotes m1, DiaryNotes m2) { return m1.getDateOfDiaryNotes().compareTo(m2.getDateOfDiaryNotes()); } }); return existingDiaryNotes; } @Override public List<DiaryNotes> retrieveAllDiaryNotesBySubject(int subjectId) { return null; } } <file_sep>/src/main/java/com/cg/spc/entities/FeeInstallment.java package com.cg.spc.entities; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity(name="FEE_INSTALLMENT_1") public class FeeInstallment { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "FEE_INSTALLMENT_ID") private int feeInstallmentId; @Column(name = "FEE_INSTALLMENT") private double feeInstallment; @Temporal(value=TemporalType.DATE) @Column(name = "DUE_DATE") private Date dueDate; @Temporal(value=TemporalType.DATE) @Column(name = "FEE_PAYMENT_DATE") private Date feePaymentDate; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "FEE_COLUMN") private Fee fee; public int getFeeInstallmentId() { return feeInstallmentId; } public void setFeeInstallmentId(int feeInstallmentId) { this.feeInstallmentId = feeInstallmentId; } public double getFeeInstallment() { return feeInstallment; } public void setFeeInstallment(double feeInstallment) { this.feeInstallment = feeInstallment; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; } public Date getFeePaymentDate() { return feePaymentDate; } public void setFeePaymentDate(Date feePaymentDate) { this.feePaymentDate = feePaymentDate; } public Fee getFee() { return fee; } public void setFee(Fee fee) { this.fee = fee; } public FeeInstallment(int feeInstallmentId, double feeInstallment, Date dueDate, Date feePaymentDate, Fee fee) { super(); this.feeInstallmentId = feeInstallmentId; this.feeInstallment = feeInstallment; this.dueDate = dueDate; this.feePaymentDate = feePaymentDate; this.fee = fee; } public FeeInstallment() { super(); } } <file_sep>/target - Copy/Dockerfile FROM openjdk:11 COPY . /usr/src/myapp WORKDIR /usr/src/myapp EXPOSE 8081 CMD ["java", "-jar", "SchoolParentCommunicationApplication-0.0.1-SNAPSHOT.jar"]<file_sep>/src/main/java/com/cg/spc/controller/UserController.java package com.cg.spc.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.User; import com.cg.spc.service.UserService; @RestController @RequestMapping("/api") public class UserController { @Autowired private UserService userService; public UserController(UserService userService) { super(); this.userService = userService; } @PostMapping("/addnewuser") public User addNewUser(@RequestBody User user) { return userService.addNewUser(user); } @PostMapping("/signin") public User signIn(@RequestBody User user) { return userService.signIn(user); } @PostMapping("/signout") public User signOut(@RequestBody User user) { return userService.signOut(user); } } <file_sep>/src/main/java/com/cg/spc/repository/DiaryNotesRepository.java package com.cg.spc.repository; import java.util.Date; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.cg.spc.entities.DiaryNotes; public interface DiaryNotesRepository extends JpaRepository<DiaryNotes, Integer> { @Query(value = "SELECT * FROM DIARY_NOTES_1 WHERE DATE_OF_DIARY_NOTES = ?1", nativeQuery =true) List<DiaryNotes> findByDate(Date dateOfDiaryNotes); } <file_sep>/src/main/java/com/cg/spc/controller/ClassDiaryController.java package com.cg.spc.controller; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.ClassDiary; import com.cg.spc.service.ClassDiaryService; @RestController @RequestMapping("/api") public class ClassDiaryController { @Autowired private ClassDiaryService classDiaryService; public ClassDiaryController(ClassDiaryService classDiaryService) { super(); this.classDiaryService = classDiaryService; } @PostMapping("/classdiaries") public ClassDiary addClassDiary(@RequestBody ClassDiary classDiary) { return classDiaryService.addClassDiary(classDiary); } @PostMapping("/classdiaries/{classDiaryId}") public Optional<ClassDiary> retrieveClassDiary(@PathVariable int classDiaryId) { return classDiaryService.retrieveClassDiary(classDiaryId); } } <file_sep>/src/main/java/com/cg/spc/entities/Exam.java package com.cg.spc.entities; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity(name="EXAM_1") public class Exam { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "EXAM_ID") private int examId; @Temporal(value=TemporalType.TIMESTAMP) @Column(name = "DATE_OF_EXAM") private Date dateOfExam; @Column(name = "MAX_MARKS") private int maxMarks; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "SUBJECT") private Subject subject; @Enumerated(value=EnumType.STRING) @Column(name="EXAM_TYPE") private ExamType examType; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "CLASS_ID") private ClassId classId; public int getExamId() { return examId; } public void setExamId(int examId) { this.examId = examId; } public Date getDateOfExam() { return dateOfExam; } public void setDateOfExam(Date dateOfExam) { this.dateOfExam = dateOfExam; } public int getMaxMarks() { return maxMarks; } public void setMaxMarks(int maxMarks) { this.maxMarks = maxMarks; } public Subject getSubject() { return subject; } public void setSubject(Subject subject) { this.subject = subject; } public ExamType getExamType() { return examType; } public void setExamType(ExamType examType) { this.examType = examType; } public ClassId getClassId() { return classId; } public void setClassId(ClassId classId) { this.classId = classId; } public Exam(int examId, Date dateOfExam, int maxMarks, Subject subject, ExamType examType, ClassId classId) { super(); this.examId = examId; this.dateOfExam = dateOfExam; this.maxMarks = maxMarks; this.subject = subject; this.examType = examType; this.classId = classId; } public Exam() { super(); } } <file_sep>/src/main/java/com/cg/spc/repository/StudentExamAttemptRepository.java package com.cg.spc.repository; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.cg.spc.entities.Student; import com.cg.spc.entities.StudentExamAttempt; public interface StudentExamAttemptRepository extends JpaRepository<StudentExamAttempt, Integer> { @Query(value = "SELECT * FROM STUDENT_EXAM_ATTEMPT_1 WHERE STUDENT = ?1", nativeQuery =true) List<StudentExamAttempt> findByStudent(Student student); } <file_sep>/src/main/java/com/cg/spc/controller/FeeInstallmentController.java package com.cg.spc.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.FeeInstallment; import com.cg.spc.service.FeeInstallmentService; @RestController @RequestMapping("/api") public class FeeInstallmentController { @Autowired private FeeInstallmentService feeInstallmentService; public FeeInstallmentController(FeeInstallmentService feeInstallmentService) { super(); this.feeInstallmentService = feeInstallmentService; } @PostMapping("/feeinstallments") public FeeInstallment makePayment(@RequestBody FeeInstallment feeInstallment) { return feeInstallmentService.makePayment(feeInstallment); } @GetMapping("/feeinstallments/{userId}") public List<FeeInstallment> pendingInstallments(@PathVariable long userId){ return feeInstallmentService.pendingInstallments(userId); } @GetMapping("/feeinstallmentsbyid/{feeInstallmentId}") public Optional<FeeInstallment> retrieveFeeInstallmentById(@PathVariable int feeInstallmentId) { return feeInstallmentService.retrieveFeeInstallmentById(feeInstallmentId); } @GetMapping("/feeinstallments/{feeId}") public List<FeeInstallment> retrieveAllFeeInstallmentsByFee(@PathVariable int feeId){ return feeInstallmentService.retrieveAllFeeInstallmentsByFee(feeId); } } <file_sep>/src/main/java/com/cg/spc/controller/DiaryNotesController.java package com.cg.spc.controller; import java.util.Date; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.DiaryNotes; import com.cg.spc.service.DiaryNotesService; @RestController @RequestMapping("/api") public class DiaryNotesController { @Autowired private DiaryNotesService diaryNotesService; public DiaryNotesController(DiaryNotesService diaryNotesService) { super(); this.diaryNotesService = diaryNotesService; } @PostMapping("/diarynotes") public DiaryNotes addDiaryNotes(@RequestBody DiaryNotes diaryNotes) { return diaryNotesService.addDiaryNotes(diaryNotes); } @PutMapping("/diarynotes") public DiaryNotes updateDiaryNotes(@RequestBody DiaryNotes diaryNotes) { return diaryNotesService.updateDiaryNotes(diaryNotes); } @DeleteMapping("/diarynotes/{diaryNotesId}") public DiaryNotes deleteDiaryNotes(@PathVariable int diaryNotesId) { return diaryNotesService.deleteDiaryNotes(diaryNotesId); } @GetMapping("/diarynotes") public List<DiaryNotes> retrieveAllDiaryNotesByDate(@RequestBody Date dateOfDiaryNotes){ return diaryNotesService.retrieveAllDiaryNotesByDate(dateOfDiaryNotes); } @GetMapping("/diarynotes/{subjectId}") public List<DiaryNotes> retrieveAllDiaryNotesBySubject(@PathVariable int subjectId){ return diaryNotesService.retrieveAllDiaryNotesBySubject(subjectId); } } <file_sep>/src/main/java/com/cg/spc/service/IConcernServiceImplementation.java package com.cg.spc.service; import java.util.List; import java.util.Optional; import java.util.stream.Collectors; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.spc.entities.Concern; import com.cg.spc.entities.Parent; import com.cg.spc.repository.ConcernRepository; import com.cg.spc.repository.ParentRepository; @Service public class IConcernServiceImplementation implements ConcernService { @Autowired private ConcernRepository concernRepository; @Autowired private ParentRepository parentRepository; @Override public Concern addConcern(Concern concern) { Parent parent = concern.getParent(); if(parent != null) { int parentId = parent.getParentId(); Optional<Parent> parentContainer = parentRepository.findById(parentId); if(parentContainer.isPresent()) { concern.setParent(parentContainer.get()); } } return concernRepository.save(concern); } @Override public Concern updateConcern(Concern concern) { int concernId = concern.getConcernId(); Optional<Concern> existingConcernContainer = concernRepository.findById(concernId); Concern existingConcern = null; if(existingConcernContainer.isPresent()) { existingConcern = existingConcernContainer.get(); existingConcern.setConcernDescription(concern.getConcernDescription()); existingConcern.setResolved(concern.isResolved()); concernRepository.saveAndFlush(existingConcern); } return existingConcern; } @Override public List<Concern> retrieveAllConcerns() { return concernRepository.findAll(); } @Override public List<Concern> retrieveAllConcernsByParent(int parentId) { Optional<Parent> parent = parentRepository.findById(parentId); if(parent.isPresent()) { return concernRepository.findByParent(parent.get()); } return null; } @Override public List<Concern> retrieveAllUnResolvedConcerns() { List<Concern> concerns = concernRepository.findAll(); List<Concern> allUnResolvedConcerns = concerns.stream().filter(e -> !e.isResolved()) .collect(Collectors.toList()); return allUnResolvedConcerns; } @Override public Concern retrieveAllUnResolvedConcernsByParent(int parentId) { Optional<Parent> parent = parentRepository.findById(parentId); Concern concerns = null; if (parent.isPresent()) { concerns = concernRepository.findByParent1(parent.get()); } if (!concerns.isResolved()) { return concerns; } return null; } } <file_sep>/src/main/java/com/cg/spc/service/IClassDiaryServiceImplementation.java package com.cg.spc.service; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.spc.entities.ClassDiary; import com.cg.spc.entities.DiaryNotes; import com.cg.spc.repository.ClassDiaryRepository; import com.cg.spc.repository.DiaryNotesRepository; @Service public class IClassDiaryServiceImplementation implements ClassDiaryService { @Autowired private ClassDiaryRepository classDiaryRepository; @Autowired private DiaryNotesRepository diaryNotesRepository; @Override public ClassDiary addClassDiary(ClassDiary classDiary) { DiaryNotes diaryNotes = classDiary.getDiaryNotes(); if(diaryNotes != null) { int diaryNotesId = diaryNotes.getDiaryNotesId(); Optional<DiaryNotes> diaryNotesContainer = diaryNotesRepository.findById(diaryNotesId); if(diaryNotesContainer.isPresent()) { classDiary.setDiaryNotes(diaryNotesContainer.get()); } } return classDiaryRepository.save(classDiary); } @Override public Optional<ClassDiary> retrieveClassDiary(int classDiaryId) { return classDiaryRepository.findById(classDiaryId); } } <file_sep>/src/main/java/com/cg/spc/service/IUserServiceImplementation.java package com.cg.spc.service; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.spc.entities.User; import com.cg.spc.repository.UserRepository; @Service public class IUserServiceImplementation implements UserService { @Autowired UserRepository userRepository; @Override public User addNewUser(User user) { return userRepository.save(user); } @Override public User signIn(User user) { User userNow = userRepository.findByUserName(user.getUserName()); if (user.getPassword().equals(userNow.getPassword())) { return userNow; } return null; } @Override public User signOut(User user) { User userNow = userRepository.findByUserName(user.getUserName()); if (user.getPassword().equals(userNow.getPassword())) { return userNow; } return null; } } <file_sep>/src/main/java/com/cg/spc/entities/Fee.java package com.cg.spc.entities; import java.util.Date; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity(name="FEE_1") public class Fee { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "FEE_ID") private int feeId; @Column(name = "TOTAL_FEES_DUE") private double totalFeesDue; @Column(name = "TOTAL_FEES_RECEIVED") private double totalFeesReceived; @Temporal(value=TemporalType.DATE) @Column(name = "STARTING_MONTH") private Date startMonthYear; @Temporal(value=TemporalType.DATE) @Column(name = "ENDING_MONTH") private Date endMonthYear; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "STUDENT") private Student student; public int getFeeId() { return feeId; } public void setFeeId(int feeId) { this.feeId = feeId; } public double getTotalFeesDue() { return totalFeesDue; } public void setTotalFeesDue(double totalFeesDue) { this.totalFeesDue = totalFeesDue; } public double getTotalFeesReceived() { return totalFeesReceived; } public void setTotalFeesReceived(double totalFeesReceived) { this.totalFeesReceived = totalFeesReceived; } public Date getStartMonthYear() { return startMonthYear; } public void setStartMonthYear(Date startMonthYear) { this.startMonthYear = startMonthYear; } public Date getEndMonthYear() { return endMonthYear; } public void setEndMonthYear(Date endMonthYear) { this.endMonthYear = endMonthYear; } public Student getStudent() { return student; } public void setStudent(Student student) { this.student = student; } public Fee(int feeId, double totalFeesDue, double totalFeesReceived, Date startMonthYear, Date endMonthYear, Student student) { super(); this.feeId = feeId; this.totalFeesDue = totalFeesDue; this.totalFeesReceived = totalFeesReceived; this.startMonthYear = startMonthYear; this.endMonthYear = endMonthYear; this.student = student; } public Fee() { super(); } } <file_sep>/src/main/java/com/cg/spc/service/IAttendanceServiceImplementation.java package com.cg.spc.service; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.cg.spc.entities.Attendance; import com.cg.spc.entities.Student; import com.cg.spc.repository.AttendanceRepository; import com.cg.spc.repository.StudentRepository; @Service public class IAttendanceServiceImplementation implements AttendanceService{ @Autowired private AttendanceRepository attendanceRepository; @Autowired private StudentRepository studentRepository; @Override public Attendance addAttendance(Attendance attendance) { Student student = attendance.getStudent(); if(student != null) { long studentId = student.getUserId(); Optional<Student> studentContainer = studentRepository.findById(studentId); if(studentContainer.isPresent()) { attendance.setStudent(studentContainer.get()); } } return attendanceRepository.save(attendance); } @Override public Attendance updateAttendance(Attendance attendance) { Optional<Attendance> existingAttendanceContainer = attendanceRepository.findById(attendance.getAttendanceId()); if (existingAttendanceContainer.isPresent()) { attendanceRepository.saveAndFlush(attendance); } return attendance; } @Override public List<Attendance> listAttendanceByMonth(Date date) { List<Attendance> existingAttendance = attendanceRepository.findByDate(date); Collections.sort(existingAttendance, new Comparator<Attendance>() { public int compare(Attendance m1, Attendance m2) { return m1.getDateOfClass().compareTo(m2.getDateOfClass()); } }); return existingAttendance; } @Override public List<Attendance> listAttendanceByStudent(long userId) { Optional<Student> student = studentRepository.findById(userId); if (student.isPresent()) { return attendanceRepository.findByStudentId(student.get()); } return null; } } <file_sep>/src/main/java/com/cg/spc/controller/ConcernController.java package com.cg.spc.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.Concern; import com.cg.spc.service.ConcernService; @RestController @RequestMapping("/api") public class ConcernController { @Autowired private ConcernService concernService; public ConcernController(ConcernService concernService) { super(); this.concernService = concernService; } @PostMapping("/concerns") public Concern addConcern(@RequestBody Concern concern) { return concernService.addConcern(concern); } @PutMapping("/concerns") public Concern updateConcern(@RequestBody Concern concern) { return concernService.updateConcern(concern); } @GetMapping("/concerns") public List<Concern> retrieveAllConcerns(){ return concernService.retrieveAllConcerns(); } @GetMapping("/concernsbyparent/{parentId}") public List<Concern> retrieveAllConcernsByParent(@PathVariable int parentId){ return concernService.retrieveAllConcernsByParent(parentId); } @GetMapping("/unresolvedconcerns") public List<Concern> retrieveAllUnResolvedConcerns(){ return concernService.retrieveAllUnResolvedConcerns(); } @GetMapping("/concerns/{parentId}") public Concern retrieveAllUnResolvedConcernsByParent(@PathVariable int parentId){ return concernService.retrieveAllUnResolvedConcernsByParent(parentId); } } <file_sep>/src/main/java/com/cg/spc/service/FeeInstallmentService.java package com.cg.spc.service; import java.util.List; import java.util.Optional; import com.cg.spc.entities.FeeInstallment; public interface FeeInstallmentService { public FeeInstallment makePayment(FeeInstallment feeInstallment); public List<FeeInstallment> pendingInstallments(long userId); public Optional<FeeInstallment> retrieveFeeInstallmentById(int feeInstallmentId); List<FeeInstallment> retrieveAllFeeInstallmentsByFee(int feeId); } <file_sep>/src/main/java/com/cg/spc/repository/StudentRepository.java package com.cg.spc.repository; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import com.cg.spc.entities.ClassId; import com.cg.spc.entities.Student; public interface StudentRepository extends JpaRepository<Student, Long> { @Query(value = "SELECT * FROM STUDENT_1 WHERE CURRENT_CLASS = ?1", nativeQuery =true) Student findByStudent(ClassId classId); } <file_sep>/target - Copy/maven-archiver/pom.properties artifactId=SchoolParentCommunicationApplication groupId=com.poc version=0.0.1-SNAPSHOT <file_sep>/src/main/java/com/cg/spc/controller/StudentExamAttemptController.java package com.cg.spc.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.StudentExamAttempt; import com.cg.spc.service.StudentExamAttemptService; @RestController @RequestMapping("/api") public class StudentExamAttemptController { @Autowired private StudentExamAttemptService studentExamAttemptService; public StudentExamAttemptController(StudentExamAttemptService studentExamAttemptService) { super(); this.studentExamAttemptService = studentExamAttemptService; } @PostMapping("/studentexamattempts") public StudentExamAttempt addStudentExamAttempt(@RequestBody StudentExamAttempt studentExamAttempt) { return studentExamAttemptService.addStudentExamAttempt(studentExamAttempt); } @PutMapping("/studentexamattempts") public StudentExamAttempt updateStudentExamAttempt(@RequestBody StudentExamAttempt studentExamAttempt) { return studentExamAttemptService.updateStudentExamAttempt(studentExamAttempt); } @DeleteMapping("/studentexamattempts/{studentExamAttemptId}") public StudentExamAttempt deleteStudentExamAttempt(@PathVariable int studentExamAttemptId) { return studentExamAttemptService.deleteStudentExamAttempt(studentExamAttemptId); } @GetMapping("/studentexamattempts/{userId}") public List<StudentExamAttempt> retrieveAllStudentExamAttemptByStudent(@PathVariable long userId){ return studentExamAttemptService.retrieveAllStudentExamAttemptByStudent(userId); } @GetMapping("/studentexamattempts/{studentExamAttemptId}") public Optional<StudentExamAttempt> retrieveStudentExamAttemptById(@PathVariable int studentExamAttemptId) { return studentExamAttemptService.retrieveStudentExamAttemptById(studentExamAttemptId); } } <file_sep>/src/main/java/com/cg/spc/entities/Concern.java package com.cg.spc.entities; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.EnumType; import javax.persistence.Enumerated; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity(name="CONCERN_1") public class Concern { @Id @GeneratedValue(strategy = GenerationType.AUTO) private int concernId; private String concernDescription; private boolean resolved; @Enumerated(value=EnumType.STRING) @Column(name="CONCERN_TYPE") private ConcernType concernType; @Enumerated(value=EnumType.STRING) @Column(name="CONCERN_PARTY") private ConcernParty concernParty; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "PARENT") private Parent parent; public int getConcernId() { return concernId; } public void setConcernId(int concernId) { this.concernId = concernId; } public String getConcernDescription() { return concernDescription; } public void setConcernDescription(String concernDescription) { this.concernDescription = concernDescription; } public boolean isResolved() { return resolved; } public void setResolved(boolean resolved) { this.resolved = resolved; } public ConcernType getConcernType() { return concernType; } public void setConcernType(ConcernType concernType) { this.concernType = concernType; } public ConcernParty getConcernParty() { return concernParty; } public void setConcernParty(ConcernParty concernParty) { this.concernParty = concernParty; } public Parent getParent() { return parent; } public void setParent(Parent parent) { this.parent = parent; } public Concern(int concernId, String concernDescription, boolean resolved, ConcernType concernType, ConcernParty concernParty, Parent parent) { super(); this.concernId = concernId; this.concernDescription = concernDescription; this.resolved = resolved; this.concernType = concernType; this.concernParty = concernParty; this.parent = parent; } public Concern() { super(); } } <file_sep>/src/main/java/com/cg/spc/entities/ClassDiary.java package com.cg.spc.entities; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; @Entity(name="CLASS_DIARY") public class ClassDiary { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "CLASS_DIARY_ID") private int classDiaryId; @OneToOne(cascade = CascadeType.ALL) @JoinColumn(name = "DIARY_NOTES") private DiaryNotes diaryNotes; public int getClassDiaryId() { return classDiaryId; } public void setClassDiaryId(int classDiaryId) { this.classDiaryId = classDiaryId; } public DiaryNotes getDiaryNotes() { return diaryNotes; } public void setDiaryNotes(DiaryNotes diaryNotes) { this.diaryNotes = diaryNotes; } public ClassDiary(int classDiaryId, DiaryNotes diaryNotes) { super(); this.classDiaryId = classDiaryId; this.diaryNotes = diaryNotes; } public ClassDiary() { super(); } } <file_sep>/src/main/java/com/cg/spc/entities/DiaryNotes.java package com.cg.spc.entities; import java.util.Date; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Temporal; import javax.persistence.TemporalType; @Entity(name="DIARY_NOTES_1") public class DiaryNotes { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "DIARY_NOTES_ID") private int diaryNotesId; @Temporal(value=TemporalType.DATE) @Column(name = "DATE_OF_DIARY_NOTES") private Date dateOfDiaryNotes; public int getDiaryNotesId() { return diaryNotesId; } public void setDiaryNotesId(int diaryNotesId) { this.diaryNotesId = diaryNotesId; } public Date getDateOfDiaryNotes() { return dateOfDiaryNotes; } public void setDateOfDiaryNotes(Date dateOfDiaryNotes) { this.dateOfDiaryNotes = dateOfDiaryNotes; } public DiaryNotes(int diaryNotesId, Date dateOfDiaryNotes) { super(); this.diaryNotesId = diaryNotesId; this.dateOfDiaryNotes = dateOfDiaryNotes; } public DiaryNotes() { super(); } } <file_sep>/src/main/java/com/cg/spc/controller/ParentController.java package com.cg.spc.controller; import java.util.List; import java.util.Optional; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PutMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.cg.spc.entities.Parent; import com.cg.spc.service.ParentService; @RestController @RequestMapping("/api") public class ParentController { @Autowired private ParentService parentService; public ParentController(ParentService parentService) { super(); this.parentService = parentService; } @PostMapping("/parents") public Parent addParent(@RequestBody Parent parent) { return parentService.addParent(parent); } @PutMapping("/parents") public Parent updateParent(@RequestBody Parent parent) { return parentService.updateParent(parent); } @GetMapping("/parents/{classId}") public List<Parent> retrieveParentListByClass(@PathVariable long classId){ return parentService.retrieveParentListByClass(classId); } @GetMapping("/parents/{userId}") public List<Parent> retrieveParentByStudent(@PathVariable long userId) { return parentService.retrieveParentByStudent(userId); } @GetMapping("/parents/{parentId}") public Optional<Parent> retrieveParentById(@PathVariable int parentId) { return parentService.retrieveParentById(parentId); } }
60606a5d5ba44dfa1c830f2c55a63dd059d0f8a6
[ "Java", "Dockerfile", "INI" ]
24
Java
InfiniteSkipper55/School-Parent-Communication-Application
b19e40ebc00336653837b0cb93e2e5e903a848c5
c2a042771bf54e589dd3a4e602c27138fb4e8222
refs/heads/master
<file_sep>/* ============================================================================== DelayLine.cpp Created: 19 Feb 2018 4:40:29pm Author: <NAME> ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" class DelayLine{ public: void initDelay(float _delayInSeconds, float _fs){ delayInSeconds = _delayInSeconds; fs = _fs; setDelayTime(_delayInSeconds); } void setDelayTime(float _delayInSeconds){ delayInSamples = ceil(fs*delayInSeconds); if (delayInSamples > 88200) delayInSamples = 88200; frac = fs*delayInSeconds - floor(fs*delayInSeconds); } void setFeedback(float _feedback){ feedback = _feedback; } void setFrequency(float freq){ delayInSamples = ceil(fs/freq); } void tick(float input){ int writePos = (pos + 1) % delayInSamples; int readPos = pos - delayInSamples; if (readPos < 0) readPos += delayInSamples; int nextReadPos = (readPos + 1) % delayInSamples; float out = frac * delay[readPos] + (1-frac)*delay[nextReadPos]; delay[writePos] = input + feedback*out; pos = writePos; } float getOutput(){ int readPos = pos - delayInSamples; if (readPos < 0) readPos += delayInSamples; int nextReadPos = (readPos + 1) % delayInSamples; return frac * delay[readPos] + (1-frac)*delay[nextReadPos]; } float getLPOutput(){ float out = getOutput(); float currentOut = a*out + (1-a)*previousOutput; previousOutput = out; return currentOut; } private: float delayInSeconds; int delayInSamples; float frac; int pos; float a = 0.5; float previousOutput = 0; float feedback = 0.0; float fs = 44100; float delay[88200] = {}; };<file_sep>/* ============================================================================== SynthVoice.h Created: 14 Feb 2018 2:48:28pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "SynthSound.h" #include "FractionalDelay.h" #include "KSExtended.h" #include "ClarinetCook.h" #include "FluteCook.h" class SynthVoice : public SynthesiserVoice { public: void reset(); bool canPlaySound(SynthesiserSound* sound) override; void setInstType(int newInstType); void startNote(int midiNoteNumber, float velocity, SynthesiserSound* sound, int currentPitchWheelPosition) override; void stopNote(float velocity, bool allowTailOff) override; void pitchWheelMoved(int newPitchWheelValue) override; void controllerMoved(int controllerNumber, int newControllerValue) override; void renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples) override; void setParameters(int newInstType, float pluckLength, float pluckPoint, float lowPassCoef, float mouthPressure, float reedClosure, float blowLength, float m, float embochureDelay, float noiseAmount); //======================================================= private: int instType; double f0; FractionalDelay delayBridge; FractionalDelay delayFretboard; KSExtended ksModel; ClarinetCook clarinetCookModel; FluteCook fluteCookModel; };<file_sep># PMSS-SMC18 Code for the physical modelling for sound synthesis class - Spring18 <file_sep>/* ============================================================================== SynthSound.cpp Created: 14 Feb 2018 2:48:35pm Author: franc ============================================================================== */ #include "SynthSound.h" bool SynthSound::appliesToNote(int midiNoteNumber) { return true; } bool SynthSound::appliesToChannel(int midiNoteNumber) { return true; } <file_sep>/* ============================================================================== SynthVoice.cpp Created: 14 Feb 2018 2:48:28pm Author: franc ============================================================================== */ #include "SynthVoice.h" void SynthVoice::reset() { f0 = 0.0; instType = 0; ksModel.reset(getSampleRate()); clarinetCookModel.reset(getSampleRate()); fluteCookModel.reset(getSampleRate()); } bool SynthVoice::canPlaySound(SynthesiserSound* sound) { return dynamic_cast <SynthSound*>(sound) != nullptr; } void SynthVoice::setInstType(int newInstType) { instType = newInstType; } void SynthVoice::startNote(int midiNoteNumber, float /*velocity*/, SynthesiserSound* /*sound*/, int /*currentPitchWheelPosition*/) { f0 = MidiMessage::getMidiNoteInHertz(midiNoteNumber); ksModel.setF0(f0); clarinetCookModel.setF0(f0); fluteCookModel.setF0(f0); } void SynthVoice::stopNote(float /*velocity*/, bool /*allowTailOff*/) { clarinetCookModel.stopBlowing(); clearCurrentNote(); } void SynthVoice::pitchWheelMoved(int newPitchWheelValue) { } void SynthVoice::controllerMoved(int controllerNumber, int newControllerValue) { } void SynthVoice::renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples) { switch (instType) { case 0: clarinetCookModel.reset(getSampleRate()); fluteCookModel.reset(getSampleRate()); ksModel.renderNextBlock(outputBuffer, startSample, numSamples); break; case 1: ksModel.reset(getSampleRate()); fluteCookModel.reset(getSampleRate()); clarinetCookModel.renderNextBlock(outputBuffer, startSample, numSamples); break; case 2: ksModel.reset(getSampleRate()); clarinetCookModel.reset(getSampleRate()); fluteCookModel.renderNextBlock(outputBuffer, startSample, numSamples); default: ksModel.renderNextBlock(outputBuffer, startSample, numSamples); break; } } void SynthVoice::setParameters(int newInstType, float pluckLength, float pluckPoint, float lowPassCoef, float mouthPressure, float reedClosure, float m, float blowLength, float embochureDelay, float noiseAmount) { instType = newInstType; ksModel.setPluckLength(pluckLength); ksModel.setPluckPoint(pluckPoint); ksModel.setLowPassCoef(lowPassCoef); clarinetCookModel.setMouthPressure(mouthPressure); clarinetCookModel.setReedClosure(reedClosure); clarinetCookModel.setM(m); clarinetCookModel.setLowPassCoef(lowPassCoef); fluteCookModel.setBlowLength(blowLength); fluteCookModel.setEmbochureDelay(embochureDelay); fluteCookModel.setNoiseAmount(noiseAmount); fluteCookModel.setLowPassCoef(lowPassCoef); }<file_sep>/* ============================================================================== FluteCook.h Created: 18 Feb 2018 9:42:04pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "FractionalDelay.h" /** Slide flute model by <NAME> */ class FluteCook { public: void reset(double newSampleRate); void setF0(double newF0); void setLowPassCoef(float newLowPassCoef); void setBlowLength(double newBlowLength); void setEmbochureDelay(double newEmbochureDelay); void setNoiseAmount(double newNoiseAmount); void renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples); private: double sampleRate; double f0; float noiseAmount; float reflectionCoef; float boreVelocityReflected; float breathVelocity[44100]; float excitationLength; int excitationLengthSamples; int breathCounter; bool isBlowing; float lowPassBore[2]; float delayLengthBore; float delayLengthEmbochure; float lowPassCoef; FractionalDelay delayEmbochure; FractionalDelay delayBore; void calculateDelayLength(); float jetModel(float currentMouthPressure); void calculateExcitation(); };<file_sep>/* ============================================================================== KSExtended.h Created: 18 Feb 2018 4:58:19pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "FractionalDelay.h" /** Karplus-Strong model with triangular-wave pluck and pluck point implementation */ class KSExtended { public: void reset(double newSampleRate); void setF0(double newF0); void setPluckPoint(float newPluckPoint); void setPluckLength(float newPluckLength); void setLowPassCoef(float newLowPassCoef); void renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples); private: double sampleRate; double f0; float pluckPoint; float pluckLength; int pluckLengthSamples; int pluckCounter; bool isPlucked; float lowPassBridge[2]; float lowPassFretboard[2]; float excitation[4000]; float delayLengthBridge; float delayLengthFretboard; float lowPassCoef; FractionalDelay delayBridge; FractionalDelay delayFretboard; void calculateDelayLength(); void calculatePluck(); };<file_sep>/* ============================================================================== ClarinetCook.h Created: 18 Feb 2018 4:58:26pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" #include "FractionalDelay.h" /** Clarinet model by Perry Cook: 1 waveguide */ class ClarinetCook { public: void reset(double newSampleRate); void setF0(double newF0); void setMouthPressure(float newMouthPressure); void setReedClosure(float newReedClosure); void setM(float newM); void setLowPassCoef(float newLowPassCoef); void stopBlowing(); void renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples); private: double sampleRate; double f0; float mouthPressure; float reedClosureDeltaPressure; float m; float reflectionCoef; float borePressureReflected; bool isBlowing; float lowPassBore[2]; float delayLengthBore; float lowPassCoef; FractionalDelay delayBore; void calculateDelayLength(); float reedModel(float currentMouthPressure); };<file_sep>/* ============================================================================== FluteCook.cpp Created: 18 Feb 2018 9:42:04pm Author: franc ============================================================================== */ #include "FluteCook.h" void FluteCook::reset(double newSampleRate) { sampleRate = newSampleRate; f0 = 440; excitationLength = 400.0e-3; reflectionCoef = 0.0; boreVelocityReflected = 0.0; breathCounter = 0; lowPassCoef = 0.3; noiseAmount = 0.1; isBlowing = false; delayEmbochure.reset(sampleRate); delayBore.reset(sampleRate); delayLengthEmbochure = 10.0e-3; delayLengthBore = 100; for (int i = 0; i < 2; i++) lowPassBore[i] = 0.0; calculateExcitation(); } void FluteCook::setF0(double newF0) { f0 = newF0; calculateDelayLength(); if (!isBlowing) { isBlowing = true; breathCounter = 0; } } void FluteCook::setBlowLength(double newBlowLength) { excitationLength = newBlowLength; calculateExcitation(); } void FluteCook::setEmbochureDelay(double newEmbochureDelay) { delayLengthEmbochure = newEmbochureDelay; } void FluteCook::setNoiseAmount(double newNoiseAmount) { noiseAmount = newNoiseAmount; } void FluteCook::calculateDelayLength() { delayLengthBore = sampleRate / f0 / 2; } void FluteCook::setLowPassCoef(float newLowPassCoef) { lowPassCoef = newLowPassCoef; } float FluteCook::jetModel(float currentBreathVelocity) { float deltaVelocityDelayed; float delayLengthEmbochureSamples = std::round(sampleRate * delayLengthEmbochure); float deltaVelocity = currentBreathVelocity + 0.1 * boreVelocityReflected; delayEmbochure.writeToBuffer(deltaVelocity); deltaVelocityDelayed = delayEmbochure.readFromBuffer(delayLengthEmbochureSamples); return deltaVelocityDelayed - deltaVelocityDelayed * deltaVelocityDelayed * deltaVelocityDelayed; } void FluteCook::calculateExcitation() { Random randomNumber; excitationLengthSamples = std::round(sampleRate * excitationLength); float noise; float breathNoise; float attackLengthSamples = std::round(sampleRate * 0.075 * excitationLength); float decayLengthSamples = std::round(sampleRate * 0.125 * excitationLength); float sustainLengthSamples = std::round(sampleRate * 0.6 * excitationLength); float releaseLengthSamples = std::round(sampleRate * 0.2 * excitationLength); float attackIncrement = (1 - 0) / (attackLengthSamples - 1); float decayIncrement = (0.9 - 1) / (decayLengthSamples - 1); float sustainIncrement = 0; float releaseIncrement = (0 - 0.9) / (releaseLengthSamples - 1); float temp = 0; for (int i = 0; i < excitationLengthSamples; i++) { if (i < attackLengthSamples) { temp += attackIncrement; breathVelocity[i] = temp; } else if (i < attackLengthSamples + decayLengthSamples) { temp += decayIncrement; breathVelocity[i] = temp; } else if (i < attackLengthSamples + decayLengthSamples + sustainLengthSamples) { temp += sustainIncrement; breathVelocity[i] = temp; } else { temp += releaseIncrement; breathVelocity[i] = temp; } } for (int i = 0; i < excitationLengthSamples; i++) { noise = 2.0 * randomNumber.nextFloat() - 1.0; breathNoise = breathVelocity[i] * noiseAmount * noise; breathVelocity[i] += breathNoise; } } void FluteCook::renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples) { float input; float outputSample; float boreVelocityTransmitted; for (int sample = 0; sample < numSamples; sample++) { if (isBlowing) { input = breathVelocity[breathCounter++]; if (breathCounter >= excitationLengthSamples) isBlowing = false; } else input = 0.0; boreVelocityTransmitted = jetModel(input) + 0.9 * boreVelocityReflected; lowPassBore[0] = (1 - lowPassCoef) * boreVelocityTransmitted + lowPassCoef * lowPassBore[1]; lowPassBore[1] = lowPassBore[0]; delayBore.writeToBuffer(lowPassBore[0]); outputSample = lowPassBore[0]; boreVelocityReflected = delayBore.readFromBuffer(delayLengthBore); for (int channel = 0; channel < outputBuffer.getNumChannels(); ++channel) outputBuffer.addSample(channel, startSample, outputSample); startSample++; } }<file_sep>/* ============================================================================== Parameters.h Created: 14 Feb 2018 2:48:23pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" struct Parameters { Parameters(AudioProcessor &processor); bool update(); int instType; float pluckLength; float pluckPoint; float lowPassCoef; float reedClosure; float mouthPressure; float m; float blowLength; float embochureDelay; float noiseAmount; AudioProcessorValueTreeState valueTree; };<file_sep>/* ============================================================================== Parameters.cpp Created: 14 Feb 2018 2:48:23pm Author: franc ============================================================================== */ #include "Parameters.h" Parameters::Parameters(AudioProcessor &processor) : valueTree(processor, nullptr) { valueTree.createAndAddParameter("pluckLength", "Pluck Length", "ms", NormalisableRange<float>(0.0, 100.0), 20.0, nullptr, nullptr); valueTree.createAndAddParameter("pluckPoint", "Pluck Point", "", NormalisableRange<float>(0.0, 1.0), 0.3, nullptr, nullptr); valueTree.createAndAddParameter("lowPassCoef", "Amplitude", "", NormalisableRange<float>(0.0, 1.0), 0.3, nullptr, nullptr); valueTree.createAndAddParameter("instType", "Instrument Type", "", NormalisableRange<float>(0.0, 2.0), 0.0, nullptr, nullptr); valueTree.createAndAddParameter("reedClosure", "Reed Closure deltaPressure", "", NormalisableRange<float>(-1.0, 1.0), -0.1, nullptr, nullptr); valueTree.createAndAddParameter("mouthPressure", "Mouth Pressure", "", NormalisableRange<float>(0.0, 0.5), 0.09, nullptr, nullptr); valueTree.createAndAddParameter("m", "M (stiffness + embochure)", "", NormalisableRange<float>(0.0, 5.0), 1.0, nullptr, nullptr); valueTree.createAndAddParameter("blowLength", "Blow Length", "ms", NormalisableRange<float>(0.0, 800.0), 400.0, nullptr, nullptr); valueTree.createAndAddParameter("noiseAmount", "Noise Amount", "", NormalisableRange<float>(0.0, 0.5), 0.1, nullptr, nullptr); valueTree.createAndAddParameter("embochureDelay", "Embochure Delay", "", NormalisableRange<float>(0.0, 50.0), 10.0, nullptr, nullptr); } bool Parameters::update() { auto prevPluckLength = pluckLength; auto prevPluckPoint = pluckPoint; auto prevLowPassCoef = lowPassCoef; auto prevInstType = instType; auto prevReedClosure = reedClosure; auto prevMouthPressure = mouthPressure; auto prevM = m; auto prevBlowLength = blowLength; auto prevEmbochureDelay = embochureDelay; auto prevNoiseAmount = noiseAmount; instType = *valueTree.getRawParameterValue("instType"); pluckLength = *valueTree.getRawParameterValue("pluckLength"); pluckPoint = *valueTree.getRawParameterValue("pluckPoint"); lowPassCoef = *valueTree.getRawParameterValue("lowPassCoef"); reedClosure = *valueTree.getRawParameterValue("reedClosure"); mouthPressure = *valueTree.getRawParameterValue("mouthPressure"); m = *valueTree.getRawParameterValue("m"); blowLength = *valueTree.getRawParameterValue("blowLength"); embochureDelay = *valueTree.getRawParameterValue("embochureDelay"); noiseAmount = *valueTree.getRawParameterValue("noiseAmount"); if (prevPluckLength != pluckLength || prevPluckPoint != pluckPoint || prevLowPassCoef != lowPassCoef || prevInstType != instType || prevReedClosure != reedClosure || prevMouthPressure != mouthPressure || prevM != m || prevBlowLength != blowLength || prevEmbochureDelay != embochureDelay || prevNoiseAmount != noiseAmount) return true; else return false; }<file_sep>/* ============================================================================== FractionalDelay.h Created: 14 Feb 2018 2:48:02pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class FractionalDelay { public: FractionalDelay(); void reset(double audioSampleRate); float readFromBuffer(float delaySamples); void writeToBuffer(float sampleIn); private: float delayBuffer[44100]; int writeIdx; double sampleRate; };<file_sep>/* ============================================================================== KSExtended.cpp Created: 18 Feb 2018 4:58:19pm Author: franc ============================================================================== */ #include "KSExtended.h" void KSExtended::reset(double newSampleRate) { sampleRate = newSampleRate; f0 = 440; pluckCounter = 0; pluckLength = 20.0e-3; pluckPoint = 0.3; lowPassCoef = 0.5; isPlucked = false; delayBridge.reset(sampleRate); delayFretboard.reset(sampleRate); delayLengthBridge = 70; delayLengthFretboard = 30; for (int i = 0; i < 4000; i++) excitation[i] = 0.0; for (int i = 0; i < 2; i++) { lowPassBridge[i] = 0.0; lowPassFretboard[i] = 0.0; } calculatePluck(); } void KSExtended::calculatePluck() { double phase = 0.0; double pluckFrequency = 1 / pluckLength; double deltaPhase = 2 * double_Pi * pluckFrequency / sampleRate; pluckLengthSamples = (int)std::round(pluckLength * sampleRate); for (int i = 0; i < pluckLengthSamples; i++) { excitation[i] = phase <= double_Pi ? -1 + 2 / double_Pi * phase : 3 - 2 / double_Pi * phase; phase += deltaPhase; } } void KSExtended::setF0(double newF0) { f0 = newF0; calculateDelayLength(); if (!isPlucked) { isPlucked = true; pluckCounter = 0; } } void KSExtended::calculateDelayLength() { delayLengthBridge = pluckPoint * sampleRate / f0; delayLengthFretboard = (1 - pluckPoint) * sampleRate / f0; } void KSExtended::setPluckPoint(float newPluckPoint) { pluckPoint = newPluckPoint; calculateDelayLength(); } void KSExtended::setPluckLength(float newPluckLength) { pluckLength = newPluckLength; calculatePluck(); } void KSExtended::setLowPassCoef(float newLowPassCoef) { lowPassCoef = newLowPassCoef; } void KSExtended::renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples) { float outputSample; float input; for (int sample = 0; sample < numSamples; sample++) { if (isPlucked) { input = excitation[pluckCounter++]; if (pluckCounter >= pluckLengthSamples) isPlucked = false; } else input = 0.0; delayBridge.writeToBuffer(input + lowPassFretboard[0]); delayFretboard.writeToBuffer(input + lowPassBridge[0]); lowPassBridge[0] = (1 - lowPassCoef) * delayBridge.readFromBuffer(delayLengthBridge) + lowPassCoef * lowPassBridge[1]; lowPassFretboard[0] = (1 - lowPassCoef) * delayFretboard.readFromBuffer(delayLengthFretboard) + lowPassCoef * lowPassFretboard[1]; lowPassBridge[1] = lowPassBridge[0]; lowPassFretboard[1] = lowPassFretboard[0]; outputSample = delayFretboard.readFromBuffer(delayLengthFretboard); for (int channel = 0; channel < outputBuffer.getNumChannels(); ++channel) outputBuffer.addSample(channel, startSample, outputSample); startSample++; } }<file_sep>/* ============================================================================== FractionalDelay.cpp Created: 14 Feb 2018 2:48:02pm Author: franc ============================================================================== */ #include "FractionalDelay.h" FractionalDelay::FractionalDelay() { writeIdx = 22051; for (int i = 0; i < 44100; i++) delayBuffer[i] = 0.0; sampleRate = 44.1e3; } void FractionalDelay::reset(double audioSampleRate) { sampleRate = audioSampleRate; writeIdx = 22051; for (int i = 0; i < 44100; i++) delayBuffer[i] = 0.0; } float FractionalDelay::readFromBuffer(float delaySamples) { int delaySamplesInt = (int)std::floor(delaySamples); float delaySamplesFrac = delaySamples - delaySamplesInt; int readIdx = writeIdx - delaySamplesInt; if (readIdx < 0) readIdx += 44100; float output; if (readIdx == 0) output = (1 - delaySamplesFrac) * delayBuffer[readIdx] + delaySamplesFrac * delayBuffer[44099]; else output = (1 - delaySamplesFrac) * delayBuffer[readIdx] + delaySamplesFrac * delayBuffer[readIdx - 1]; return output; } void FractionalDelay::writeToBuffer(float sampleIn) { delayBuffer[writeIdx++] = sampleIn; if (writeIdx > 44099) writeIdx = 0; }<file_sep>/* ============================================================================== SynthSound.h Created: 14 Feb 2018 2:48:35pm Author: franc ============================================================================== */ #pragma once #include "../JuceLibraryCode/JuceHeader.h" class SynthSound : public SynthesiserSound { public: bool appliesToNote(int midiNoteNumber) override; bool appliesToChannel(int midiNoteNumber) override; };<file_sep>/* ============================================================================== Violin.cpp Created: 20 Feb 2018 9:07:00am Author: <NAME> ============================================================================== */ #include "../JuceLibraryCode/JuceHeader.h" #include "DelayLine.cpp" class Violin{ public: Violin(){ } void init(float sampleRate){ fs = sampleRate; deltaPhase = M_PI * 2 * (vibratoFreq/fs); nutDelay.initDelay(0.01,fs); nutDelay.setFrequency(freq*(1-betaRatio)); brigdeDelay.initDelay(0.01,fs); brigdeDelay.setFrequency(freq*betaRatio); } void setVibratoGain(float g){ vibratoGain = g; } void setFrequency(float f){ freq = f; nutDelay.setFrequency(freq*(1-betaRatio)); brigdeDelay.setFrequency(freq*betaRatio); } float play(float velocity){ if (velocity > maxVelocity) velocity = maxVelocity; auto bowVelocity = velocity; auto brigdeReflection = -brigdeDelay.getLPOutput(); auto nutReflection = -nutDelay.getOutput(); auto stringVelocity = brigdeReflection + nutReflection; auto vdelta = bowVelocity - stringVelocity; // bow table auto bow = (vdelta + offset) * slope; bow = fabs(bow) + 0.75; bow = pow(bow,-4); if (bow < 0.01) bow = 0.01; else if (bow > 0.98) bow = 0.98; auto newVelocity = vdelta * bow; float out = -nutReflection; brigdeDelay.tick(newVelocity + nutReflection); nutDelay.tick(newVelocity + brigdeReflection); auto sine = sin(phase); phase += deltaPhase; if (phase > M_PI * 2) phase -= M_PI * 2; nutDelay.setFrequency(freq * (1.0 - betaRatio ) + (freq * vibratoGain * sine) ); return out; } private: DelayLine nutDelay, brigdeDelay; double fs = 44100; float freq = 220; float maxVelocity = 0.25; float offset = 0.001; float slope = 5; float betaRatio = 0.127236; float v = 0; float phase = 0; float vibratoFreq = 6.5; float deltaPhase = 0; float vibratoGain = 0.008; }; <file_sep>/* ============================================================================== ClarinetCook.cpp Created: 18 Feb 2018 4:58:26pm Author: franc ============================================================================== */ #include "ClarinetCook.h" void ClarinetCook::reset(double newSampleRate) { sampleRate = newSampleRate; f0 = 440; mouthPressure = 0.09; reflectionCoef = 0.0; reedClosureDeltaPressure = -0.1; borePressureReflected = 0.0; m = 1; lowPassCoef = 0.3; isBlowing = false; delayBore.reset(sampleRate); delayLengthBore = 100; for (int i = 0; i < 2; i++) lowPassBore[i] = 0.0; } void ClarinetCook::setF0(double newF0) { f0 = newF0; calculateDelayLength(); if (!isBlowing) isBlowing = true; } void ClarinetCook::setMouthPressure(float newMouthPressure) { mouthPressure = newMouthPressure; } void ClarinetCook::setReedClosure(float newReedClosure) { reedClosureDeltaPressure = newReedClosure; } void ClarinetCook::setM(float newM) { m = newM; } void ClarinetCook::stopBlowing() { isBlowing = false; } void ClarinetCook::calculateDelayLength() { delayLengthBore = sampleRate / f0 / 2; } void ClarinetCook::setLowPassCoef(float newLowPassCoef) { lowPassCoef = newLowPassCoef; } float ClarinetCook::reedModel(float currentMouthPressure) { float deltaPressure = borePressureReflected - currentMouthPressure; if (deltaPressure < reedClosureDeltaPressure) return 1; else return 1 - m * (deltaPressure - reedClosureDeltaPressure); } void ClarinetCook::renderNextBlock(AudioBuffer <float> &outputBuffer, int startSample, int numSamples) { float outputSample; float currentMouthPressure; float borePressureTransmitted; for (int sample = 0; sample < numSamples; sample++) { if (isBlowing) currentMouthPressure = mouthPressure; else currentMouthPressure = 0.0; reflectionCoef = reedModel(currentMouthPressure); borePressureTransmitted = reflectionCoef * borePressureReflected + (1 - reflectionCoef) * currentMouthPressure; delayBore.writeToBuffer(borePressureTransmitted); lowPassBore[0] = (1 - lowPassCoef) * delayBore.readFromBuffer(delayLengthBore) + lowPassCoef * lowPassBore[1]; lowPassBore[1] = lowPassBore[0]; outputSample = borePressureTransmitted; borePressureReflected = - lowPassBore[0]; for (int channel = 0; channel < outputBuffer.getNumChannels(); ++channel) outputBuffer.addSample(channel, startSample, outputSample); startSample++; } }
b1cbfd354b243dd2e99e46276d877980fa40d7f1
[ "Markdown", "C", "C++" ]
17
C++
1V-Oct/PMSS-SMC18
7aaaaff5ae7af4bfe82625719a28d99b3ffe19bc
6e352ce5090a88492f4f1fd0ed35d41a94718a05
refs/heads/master
<repo_name>ricksterhd123/skywarriors-web<file_sep>/public/javascripts/list.js /** * Create a list of players from player info object */ function clearPlayerList(){ var div = document.getElementById('playerList'); if (div) { document.body.removeChild(div); } } function createPlayerList(playerInfo){ clearPlayerList(); var div = document.createElement('div'); div.id = "playerList"; var listTitle = document.createElement('h2'); listTitle.innerHTML = `Players online (${playerInfo.length})`; div.appendChild(listTitle); for (let i = 0; i <= playerInfo.length - 1; i++){ let listItem = document.createElement('li'); listItem.innerHTML = playerInfo[i].name; div.appendChild(listItem); } document.body.appendChild(div); } <file_sep>/public/javascripts/ajax.js // XML HTTP request object var http = null; var playerInfo = null; var timer = null; var error = false; function errMsg(){ if (error) return; hideCanvas(true); clearPlayerList(); let errMsg = document.createElement('p'); errMsg.id = "errMsg"; errMsg.innerHTML = "appears to be offline..."; document.body.appendChild(errMsg); error = true; } function clearErrMsg(){ if (!error) return; let msg = document.getElementById('errMsg'); document.body.removeChild(msg); } function updatePlayerInfo(){ if (http.readyState == XMLHttpRequest.DONE){ if (http.status == 200){ let response = http.responseText; // error if (response == "e") { errMsg(); return false; }else { clearErrMsg(); } // parse response into json let newPlayerInfo = JSON.parse(response); if (playerInfo == newPlayerInfo) return false; // render player list and draw canvas playerInfo = newPlayerInfo; drawPlayers(playerInfo); createPlayerList(playerInfo); } else{ console.log(`Something went wrong, status code: ${http.status}`); } } return true; } /** * GET /players and retrieve data from the mtasa server. */ function getPlayersOnline(){ http = new XMLHttpRequest(); if (!http){ console.log("Giving up :("); return false; } http.onreadystatechange = updatePlayerInfo; http.open('GET', '/players'); http.send(); } getPlayersOnline(); timer = setInterval(getPlayersOnline, 5000); <file_sep>/README.md # skywarriors-web A simple web page showing online players, and other stats from an MTA:SA server # Features: - Real time map positions - List of players online
18140f36a6d7f2b85e02a5de60daf78ad2c58c98
[ "JavaScript", "Markdown" ]
3
JavaScript
ricksterhd123/skywarriors-web
56be11f2c614efd2cd27fb21120f4f222e6ff9d8
da97a49275d99601390622650d20859b73b2f9a9
refs/heads/master
<repo_name>chenguang281/LearnModel<file_sep>/routeConfig.py #!/usr/bin/env python # -*- coding: utf-8 -*- from Sys.controller.sys_menu_controller import route_sys_menu from templates import app from flask import make_response """ 蓝图配置 """ """ sys模块路由 """ app.register_blueprint(route_sys_menu, url_prefix="/") # 注入sys角色模块蓝图管理 @app.errorhandler(404) def error_404(e): response = make_response( "<script>alert('页面不存在');window.opener=null;window.open('','_self');window.close();</script>") return response <file_sep>/Sys/service/ModelService.py #!/usr/bin/env python # -*- coding: utf-8 -*- from gensim.models import word2vec def searchByVector(word, max_len, first_num, top_num, word_li, model): """ 广度搜索和word相关的词语 :param word: 输入词语 :param max_len: 返回列表的最大长度±first_num :param first_num: 每次从topn中取出的长度 :param top_num: topn的长度 :param word_li: 准备返回的列表 :param model: 词向量模型 :return: """ if len(word_li) > max_len: return word_li li = [] # 得到这一层的所有词向量,进行保存 for w in word: if w in word_li: # 如果查询过词向量,直接过.不再次查询 continue word_li.append(w) li.extend(model.most_similar(w, topn=top_num)) # 得到一次前十个词语 next_li = [] # 下一轮将要搜的词语 for j in range(first_num): next_li.append(li[j][0]) return searchByVector(next_li, max_len, first_num, top_num, word_li, model) # if __name__ == '__main__': # model = word2vec.Word2Vec.load('train.model') # 加载词向量模型 # uuuuiiii = searchByVector(['说'], 50, 7, 10, [], model) # for i in uuuuiiii: # print(i) <file_sep>/templates/__init__.py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Flask from flask_sqlalchemy import SQLAlchemy from flask_script import Manager import os class Application(Flask): def __init__(self, import_name, template_folder=None, static_folder=None): super(Application, self).__init__(import_name, template_folder=template_folder, static_folder=static_folder) self.config.from_pyfile('config/base_setting.py') db.init_app(self) db = SQLAlchemy() app = Application(__name__, template_folder='../templates', static_folder='../static') app.secret_key = os.urandom(24) manager = Manager(app) <file_sep>/Sys/controller/sys_menu_controller.py #!/usr/bin/env python # -*- coding: utf-8 -*- from flask import Blueprint, render_template route_sys_menu = Blueprint("sys_menu", __name__) @route_sys_menu.route("/") def index(): print(11111111111) return render_template("index.html")
4826d6e970066d5270f8b903b6a2ae2769013875
[ "Python" ]
4
Python
chenguang281/LearnModel
1be25ab8a3759cf0a0c87d9ebcdad7c8b28e6802
ddc15d7125ce06f8a8b2e04ce49e0581c28d8554
refs/heads/master
<repo_name>rlimaeco/orka<file_sep>/orka/app/__init__.py #coding: utf-8 import logging from flask import Flask from flask.ext.appbuilder import SQLA, AppBuilder from index import IndexView from security import OrkaSecurityManager from docker import Client """ Configuração de log """ logging.basicConfig(format='%(asctime)s:%(levelname)s:%(name)s:%(message)s') logging.getLogger().setLevel(logging.DEBUG) # Instância do cliente Docker cli = Client(base_url='unix://var/run/docker.sock') app = Flask(__name__) app.config.from_object('orka.config') db = SQLA(app) appbuilder = AppBuilder(app, db.session, indexview=IndexView, security_manager_class=OrkaSecurityManager) appbuilder.base_template='orka/baselayout.html' #appbuilder.security_cleanup() from sqlalchemy.engine import Engine from sqlalchemy import event #Only include this for SQLLite constraints @event.listens_for(Engine, "connect") def set_sqlite_pragma(dbapi_connection, connection_record): # Will force sqllite contraint foreign keys cursor = dbapi_connection.cursor() cursor.execute("PRAGMA foreign_keys=ON") cursor.close() from . import models, views <file_sep>/setup.py #coding: utf-8 import os from setuptools import setup, find_packages # Orka # <NAME>, <NAME> e <NAME> # Plataforma de Gerenciamento de Contêineres Docker # Parser dos pacotes necessários with open('requirements.txt') as f: reqs = f.read().splitlines() def read(fname): return open(os.path.join(os.path.dirname(__file__), fname)).read() setup( name = "orka", version = "0.2.1", author = "TFG Orka Equipe", author_email = "<EMAIL>, <EMAIL>, <EMAIL>", description = ("Plataforma de Gerenciamento de Contêineres Docker"), license = "MIT", keywords = "docker python flask", packages=find_packages(), include_package_data=True, long_description=read('README.md'), install_requires=reqs, classifiers=[ "Development Status :: 3 - Alpha", "Topic :: Utilities", "License :: OSI Approved :: MIT License", ], entry_points = { 'console_scripts': [ 'orka = orka.__main__:main' ] }, )<file_sep>/requirements.txt Babel==2.3.4 backports.ssl-match-hostname==3.5.0.1 blinker==1.4 click==6.4 colorama==0.3.7 DateTime==4.0.1 docker-py==1.10.3 docker-pycreds==0.2.1 enum34==1.1.2 Flask==0.10.1 Flask-AppBuilder==1.8.1 Flask-Babel==0.11.1 Flask-BabelPkg==0.9.6 Flask-Login==0.2.11 Flask-Mail==0.9.1 Flask-OpenID==1.2.5 Flask-SQLAlchemy==2.0 Flask-WTF==0.12 ipaddress==1.0.17 itsdangerous==0.24 Jinja2==2.8 MarkupSafe==0.23 Pillow==3.1.1 python-openid==2.2.5 pytz==2016.3 requests==2.10.0 six==1.10.0 speaklater==1.3 SQLAlchemy==1.0.12 websocket-client==0.37.0 Werkzeug==0.11.5 WTForms==2.1 zope.interface==4.1.3 <file_sep>/orka/app/views/__init__.py #coding: utf-8 """ Inicializador da montagem das visões """ import logging from flask import render_template from flask.ext.babel import lazy_gettext as _ from flask.ext.appbuilder import BaseView, expose, has_access from service import ServiceView from container import ContainerView from image import ImageView from .. import db, appbuilder # Início Log log = logging.getLogger(__name__) """ Controlador de erro 404 """ @appbuilder.app.errorhandler(404) def page_not_found(e): return render_template('404.html', base_template=appbuilder.base_template, appbuilder=appbuilder), 404 db.create_all() appbuilder.add_link("Dashboard", label=_("Dashboard"), href='/', icon='fa-home') appbuilder.add_view(ServiceView(), "Services", label=_('Services'), icon='fa-server') appbuilder.add_view(ContainerView(), "Container", label=_('Container'), icon='fa-database') appbuilder.add_view(ImageView(), "Images", label=_('Images'), icon='fa-hdd-o') security = appbuilder.sm active_views = [ "Service", "Container", "Image", "Images", "Dashboard", "UserInfoEditView", "ResetPasswordView", "ResetMyPasswordView", "OrkaUserDBView" ] allroles = security.get_all_roles() roles = [str(x) for x in allroles] admin_role = allroles[0] if not "User" in roles: user_role = security.add_role("User") for perm in admin_role.permissions: for view in active_views: if (view in str(perm)): security.add_permission_role(user_role, perm) print "[Security] Permissão de Usuário: ", perm log.info("Flask-Appbuilder Versão: {0}".format(appbuilder.version)) <file_sep>/docs/app.rst app package =========== Submodules ---------- app.bash module --------------- .. automodule:: app.bash :members: :undoc-members: :show-inheritance: app.forms module ---------------- .. automodule:: app.forms :members: :undoc-members: :show-inheritance: app.index module ---------------- .. automodule:: app.index :members: :undoc-members: :show-inheritance: app.models module ----------------- .. automodule:: app.models :members: :undoc-members: :show-inheritance: app.views module ---------------- .. automodule:: app.views :members: :undoc-members: :show-inheritance: Module contents --------------- .. automodule:: app :members: :undoc-members: :show-inheritance: <file_sep>/docs/testdata.rst testdata module =============== .. automodule:: testdata :members: :undoc-members: :show-inheritance: <file_sep>/orka/app/views/image.py #coding: utf-8 from . import BaseView, expose, has_access from flask.ext.babel import lazy_gettext as _ class ImageView(BaseView): """ A simple view that implements the index for the site """ route_base = '/image' default_view = 'image' index_template = 'orka/image.html' base_permissions = ['can_edit', 'can_delete', 'can_download', 'can_list', 'can_add', 'can_show'] @expose('/') def image(self): self.update_redirect() return self.render_template(self.index_template, appbuilder=self.appbuilder) <file_sep>/orka/app/models/node.py #coding: utf-8 from . import Model, Column, Integer, String class Node(Model): __tablename__ = "node" id = Column(Integer, primary_key=True) name = Column(String(150), unique=True, nullable=False) node_id = Column(String(256)) ip = Column(String(64)) network_config = Column(String(256)) def __repr__(self): return self.name<file_sep>/orka/app/models/container.py #coding: utf-8 from . import Model, Column, Integer,\ String, relationship, Text, ForeignKey, Boolean class Container(Model): ''' Definição container_type 0: Storage 1: Application ''' __tablename__ = "container" id = Column(Integer, primary_key=True) name = Column(String(150)) hash_id = Column(String(64)) port = Column(String(64)) domain_name = Column(String(64)) cpu_reserved = Column(Integer) storage_reserved = Column(Integer) docker_file = Column(Text) image_id = Column(Integer, ForeignKey('image.id')) image = relationship("Image") node_id = Column(Integer, ForeignKey('node.id')) node = relationship("Node") status = Column(Boolean, default=False) def __repr__(self): return self.name <file_sep>/orka/app/views/service.py #coding: utf-8 from . import _, BaseView, expose, has_access class ServiceView(BaseView): """ A simple view that implements the index for the site """ route_base = '/service' default_view = 'service' index_template = 'orka/services.html' base_permissions = ['can_edit', 'can_delete', 'can_download', 'can_list', 'can_add', 'can_show'] @expose('/') def service(self): self.update_redirect() return self.render_template(self.index_template, appbuilder=self.appbuilder) <file_sep>/orka/__main__.py #coding: utf-8 import sys def main(args=None): """Rotina Principal""" if args is None: args = sys.argv[1:] # Porta Padrão port = 8070 run = False for termo in args: if termo == '-p': port = args[args.index(termo)] elif termo == 'run': run = True elif termo == 'ola': print "Olá :)" if run: from app import app print "\n\nBem Vindo a plataforma Orka" print ("\nAbra o navegador em http://localhost:%s:" % (port)) app.run(host='0.0.0.0', port=port, debug=False, threaded=True) if __name__ == "__main__": main()<file_sep>/orka/app/templates/orka/navbar.html {% set menu = appbuilder.menu %} {% set languages = appbuilder.languages %} <nav class="navbar {{menu.extra_classes}} navbar-fixed-top" style="border-radius: 0 !important;" role="navigation"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#sidebar-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> {% if appbuilder.app_icon %} <a class="" style="position: absolute" href="{{appbuilder.get_url_for_index}}"> <img style="max-height: 44px; padding-top:6px;padding-left: 28%;" src="{{appbuilder.app_icon}}" > </a> {% else %} <span class="navbar-brand"> <a href="{{appbuilder.get_url_for_index}}"> {{ appbuilder.app_name }} </a> </span> {% endif %} </div> <div class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> {% include 'orka/navbar_right.html' %} </ul> </div> </div> </nav> <file_sep>/orka/app/index.py from flask.ext.appbuilder.security.registerviews import RegisterUserDBView from flask.ext.appbuilder import IndexView from flask.ext.babel import lazy_gettext as _ class IndexView(IndexView): index_template = 'index.html' class RegisterUserDBView(RegisterUserDBView): email_template = 'security/register_mail.html' email_subject = _('Your Account activation') activation_template = 'activation.html' form_title = _('Fill out the registration form') error_message = _('Not possible to register you at the moment, try again later') message = _('Registration sent to your email') <file_sep>/README.md # Orka ##Projeto de TFG 2016 ###**UNIFEI** - Engenharia da Computação ---------------------------------- Branches | Conteúdo -------- | -------- Master | Versão Estável Develop | Versão em Desenvolvimento Monografia | Edição dos arquivos em LaTeX Revisao_Bibliografica | Pesquisa e embasamento teórico Workshop | Apresentação e Documentação Eng_Soft | Modelagem e Estruturação ## Instalação Dev: - Criar ambiente virtual > Necessário pacote python-virtualenv ```bash git clone https://github.com/diogoamatos/orka.git cd orka virtualenv venv . venv/bin/activate pip install -r requirements.txt ``` > Caso encontre algum erro na instalação do Pillow , no Ubuntu instalar os seguintes pacotes: ```bash sudo apt-get install libtiff5-dev libjpeg8-dev zlib1g-dev libfreetype6-dev liblcms2-dev libwebp-dev tcl8.6-dev tk8.6-dev python-tk sudo apt-get build-dep python-imaging ``` - Executar servidor ```bash fabmanager run ``` - Abrir navegador em localhost:8080 ## Configurações Finais * Criar usuário administrador ```bash fabmanager create-admin ``` Complete os dados e isto irá criar o usuário administrador * Internacionalização Execute ao menos uma vez este comando para sincronizar os idiomas ```bash fabmanager babel-compile ``` ## Let's code ! ### [Material de Apoio](https://sites.google.com/site/tfgeco/material-de-apoio) <file_sep>/orka/app/models/image.py #coding: utf-8 from . import Model, Column, Integer, String class Image(Model): __tablename__ = "image" id = Column(Integer, primary_key=True) digest = Column(String(256)) name = Column(String(64), unique=True, nullable=False) version = Column(String(20)) def __repr__(self): return self.name<file_sep>/orka/app/models/__init__.py import datetime from sqlalchemy import Table, Column, Integer, String, ForeignKey, Text, Sequence, Date, Boolean from sqlalchemy.orm import relationship, backref from flask.ext.appbuilder import Model from flask.ext.babel import lazy_gettext as _ from flask_appbuilder.security.sqla.models import User from flask_appbuilder.models.mixins import UserExtensionMixin from . import container, image, node
dd3c249e5464652d867bf16e248519eaf654aa0b
[ "HTML", "reStructuredText", "Markdown", "Python", "Text" ]
16
Python
rlimaeco/orka
fe8b173bfd9fb4a76a246c11136bc73286791412
d2d009cbbd927e84520ff1d340f53f4a9f24dc3f
refs/heads/master
<file_sep>var controller={} var poste=require("../models/poste"); var client=require("../models/client"); var attribuer=require("../models/attribute"); var bcrypt = require('bcrypt'); var user=require("../models/user"); const { DateTime } = require("luxon"); attribuer.belongsTo(poste); attribuer.belongsTo(client); client.hasOne(attribuer); poste.hasOne(attribuer); controller.liste= (req,res)=>{ /* bcrypt.hash("password", 1, function(err, hash) { // Store hash in your password DB. user.create( { password: <PASSWORD>, login:"admin" }, ) })*/ if(req.signedCookies["user"]){ attribuer.findAll({include:[{model:client},{model:poste}]}).then(async attributions=>{ var ordi = await poste.findAll({}); //res.send(attributions); res.render("index",{postes:ordi,attributions:attributions}); }); }else{ res.render("login"); } } controller.filtre= (req,res)=>{ if(req.signedCookies["user"]){ // var jour = DateTime.fromSQL(req.query.jour+" 00:00:00"); jour=req.query.jour; //var jour=day.getFullYear()+"-"+day.getMonth()+"-"+day.getDate(); jour= DateTime.fromISO(jour).toFormat('dd/LL/yyyy'); if(req.query.jour){ attribuer.findAll({where:{jour: jour },include:[{model:client},{model:poste}]}).then(async attributions=>{ var postes = await poste.findAll({}); var content=""; for(let p in postes){ // console.log(postes[p]) content+=" <div class='card col-md-4 col-xs-12 poste'>"+ " <div class='card-body d-flex flex-column'>"+ " <h5 class='card-title'>"+ postes[p].nom+""+ " <button class='btn btn-danger d-flex flex-row justify-content-around delete_poste' data-id='"+postes[p].id +"' > "+ " <i class='fas fa-trash-alt'></i> "+ " </button>"+ "</h5>" for(var i=8;i<19;i++ ){ // postes[p].jour content+= "<span class='row d-flex justify-content-between heures'>" +i+ "h " h=(i<10) ? '0'+i :i; ordi=attributions.filter(o=>{return o.posteId==postes[p].id} ); t= ordi.filter( x=>{ return x.heure.match([h])} ); //console.log(t); if(t.length>0){ content+= t[0].client.nom +" "+t[0].client.prenom +"<button class='btn-small btn-warning remove' data-id='"+t[0].id+"' > <i class='fas fa-trash-alt'></i></button>"; }else{ content+= "<button class='btn-small btn-info add' data-heure='"+h+"' data-poste='"+ postes[p].id+"'><i class='fas fa-plus-circle'></i></button> " } content+="</span> " } content+= " </div>"+ "</div>" } res.send({content:content}); }); }else{ res.redirect("/"); } }else{ res.render("login"); } } controller.attribuer=(req,res)=>{ data=req.body; date=new Date(); jour=date.toLocaleDateString(); attribuer.create({ posteId:data.poste, clientId:data.user, jour:jour, heure:data.heure+":00:00" }).then( () =>{ res.sendStatus(200); }) } controller.delete= (req,res)=>{ id=req.body.attr attribuer.destroy({where:{id:id}}).then(()=>{ res.sendStatus(200); } ) } module.exports = controller;
0de6d976425b565c3848ee545fdb2f3288164178
[ "JavaScript" ]
1
JavaScript
pyrce/gestion_ordi
d0739a431e668c01cd5ce5e1dca9293bc512fcc3
a3872a01f02fec25501dc12411bf64dfd7b00cfd
refs/heads/main
<file_sep># Решение задачи классификации изображений из набора данных Oregon Wildlife с использованием нейронных сетей глубокого обучения и техники обучения Fine Tuning ## 1. Тренировка без применения Fine Tuning ![iXQQxiSlZuI](https://user-images.githubusercontent.com/61012068/113757677-9256b800-971b-11eb-8ea9-88c50275360b.jpg) </br> accuracy ![](./graphic/before_accuracy.svg) loss ![](./graphic/before_loss.svg) ## 2. Нахождение оптимального темпа обучения ### 2.1 Статический Ниже представлены графики обучения с ```lr = 1e-7, 1e-8, 1e-9, 1e-10``` </br></br> ![wbVQ9f-m1R4](https://user-images.githubusercontent.com/61012068/113757708-9c78b680-971b-11eb-9f9f-22f164545b64.jpg) </br> accuracy ![](./graphic/lrs_accuracy.svg) loss ![](./graphic/lrs_loss.svg) Из 4-х вариантов у ```lr = 1e-9``` точность в среднем на ```~0.007``` больше чем у ```lr = 1e-8``` и у ```lr = 1e-10```. Его у будем считать оптимальным из предложенных вариантов </br> ### 2.2 Изменяющийся по экспоненциальному закону Формула изменения темпа обучния имеет следующий вид: ```python lrate = 1e-8 * exp(-k * num_epoch) ``` Где ```k = 0.3, 0.5, 0.7, 0.9``` </br></br> ![YDhkuCh4haM](https://user-images.githubusercontent.com/61012068/113771611-452f1200-972c-11eb-815e-8d0c6f23eec6.jpg) </br> accuracy ![](./graphic/exp_accuracy.svg) loss ![](./graphic/exp_loss.svg) Среди рассмотренных вариантов очень трудно выделить оптимальный так как разница в точности с среднем ```~0.002```. Для средующих сравнений выберем вариант с ```k = 0.9```. ### 2.3 Изменяющийся по ступенчатому закону ```python lrate = 1e-8 * drop^floor(epoch / epoch_drop) ``` Где ```drop = 0.5, 0.75, 0.98```, ```epoch_drop = 10, 5, 0.98``` соответственно </br></br> ![n-uos1f0RqM](https://user-images.githubusercontent.com/61012068/113762092-e44e0c80-9720-11eb-8295-b679c3bb1310.jpg) </br> accuracy ![](./graphic/step_accuracy.svg) loss ![](./graphic/step_loss.svg) У варианта с ```drop = 0.5, epoch_drop = 10``` точность в среднем на ```~0.006``` больше чем у других, его и будем считать оптимальным их данных 3-х вариантов. ### 2.4 Сравнение 3-х вышеописанных способов инициализации темпа обучения ![n1misDfq4Xw](https://user-images.githubusercontent.com/61012068/113769032-3004b400-9729-11eb-97ef-c27244a32331.jpg) </br> accuracy ![](./graphic/all_accuracy.svg) loss ![](./graphic/all_loss.svg) Среди 3-х представленных вариантов лучше всего показал себя ```lr = 1e-9```. Точность больше в среднем на ```~0.008```, ошибка меньше в среднем на ```0.0067``` ## 3. Тренировка с применением Fine Tuning ![99u4N7chvRk](https://user-images.githubusercontent.com/61012068/113769335-8f62c400-9729-11eb-85f5-b40dbb76cdbb.jpg) </br> accuracy ![](./graphic/last_accuracy.svg) loss ![](./graphic/last_loss.svg) Применяя технику Fine Tuning точность удалось увеличилась в среднем на ```~0.0038``` <file_sep>import numpy as np import argparse import tensorflow as tf import glob import time import tensorflow_datasets as tfds from tensorflow.python import keras as keras from tensorflow.keras.applications import EfficientNetB0 from tensorflow.keras.layers.experimental import preprocessing LOG_DIR = 'logs' BATCH_SIZE = 64 NUM_CLASSES = 20 RESIZE_TO = 224 def build_model(): inputs = tf.keras.layers.Input(shape=(224, 224, 3)) model = EfficientNetB0(include_top=False, weights='imagenet', input_tensor=inputs) model.trainable = False x = tf.keras.layers.GlobalAveragePooling2D()(model.output) x = tf.keras.layers.Flatten()(x) #x = tf.keras.layers.BatchNormalization()(x) #x = tf.keras.layers.Dropout(0.2)(x) #x = tf.keras.layers.Dense(100, activation=tf.keras.layers.ReLU())(x) outputs = tf.keras.layers.Dense(NUM_CLASSES, activation="softmax")(x) return tf.keras.Model(inputs=inputs, outputs=outputs) def input_preprocess(image, label): label = tf.one_hot(label, NUM_CLASSES) return image, label def main(): args = argparse.ArgumentParser() args.add_argument('--train', type=str, help='Glob pattern to collect train tfrecord files, use single quote to escape *') args = args.parse_args() ds_train = tf.keras.preprocessing.image_dataset_from_directory( args.train, labels='inferred', color_mode='rgb', batch_size=BATCH_SIZE, image_size=(RESIZE_TO, RESIZE_TO), shuffle=True, seed=13, validation_split=0.3, subset="training" ) ds_validation = tf.keras.preprocessing.image_dataset_from_directory( args.train, labels='inferred', color_mode='rgb', batch_size=BATCH_SIZE, image_size=(RESIZE_TO, RESIZE_TO), shuffle=True, seed=13, validation_split=0.3, subset="validation" ) #ds_train = ds_train.map(lambda image, label: (tf.image.resize(image, size), label)) #ds_validation = ds_validation.map(lambda image, label: (tf.image.resize(image, size), label)) ds_train = ds_train.map(input_preprocess, num_parallel_calls=tf.data.experimental.AUTOTUNE) ds_train = ds_train.prefetch(tf.data.experimental.AUTOTUNE) ds_validation = ds_validation.map(input_preprocess) model = build_model() print(model.summary()) model.compile( optimizer=tf.optimizers.Adam(lr=1e-3), loss=tf.keras.losses.categorical_crossentropy, metrics=[tf.keras.metrics.categorical_accuracy], ) model.fit( ds_train, epochs=50, validation_data=ds_validation, callbacks=[ tf.keras.callbacks.TensorBoard(LOG_DIR), ] ) if __name__ == '__main__': main() <file_sep># Изучение влияние параметра “темп обучения” на процесс обучения нейронной сети на примере решения задачи классификации Oregon Wildlife с использованием техники обучения Transfer Learning ## ```# static_lr.py``` ## 1. Графики тренировки нейронной сети со статическим темпом обучения ### epoch categorical accuracy ![9EpJfjgo2as](https://user-images.githubusercontent.com/61012068/111904289-302d6000-8a57-11eb-8238-659a7749af1a.jpg) ![](./graphic/static_categorical_accuracy.svg) ### epoch loss ![](./graphic/static_loss.svg) *** ## Анализ Лучше всех себя показал ```lr = 0.001```. Точность его составила ```~0.8871``` за ```~20``` эпох. Хуже всех показал себя ```lr = 0.0001```. За ```50``` эпох он смог достичь точности лишь ```0.8622```, что на ```0.0249``` меньше чем ```lr = 0.001```. </br> Итог: параметр, обеспечивающий самую быструю скорость сходимости - ```0.01```, параметр, обеспечивающий максимальную точность: ```0.001```. Оптимальным будем считать ```lr = 0.001``` ## ```# n_static_lr.py``` ### Формула ```python lrate = initial_lrate * exp(-k * num_epoch) ``` ## 2. Графики тренировки нейронной сети с темпом обучения, изменяющегося по экспоненциальному закону с параметрами: </br> ```initial_lrate = 0.1``` </br> ```k = 0.1, 0,2, ..., 0.5``` </br> ```num_epoch = 1, 2, ..., 50``` </br> </br> ![изображение](https://user-images.githubusercontent.com/61012068/111904308-505d1f00-8a57-11eb-92b4-b09483f01d86.png) ### epoch categorical accuracy ![](./graphic/exp_categorical_accuracy.svg) ### epoch loss ![](./graphic/exp_loss.svg) *** ## Анализ Используя темп обучения изменяющийся по экспоненциальному закону удалось добиться большей скорости сходимости (```~15``` эпох) для всех ```k != 0.1```, в сравнении с ```lr = 0.001```. Среди всех представленных вариантов экспоненциального затухания выделяется лишь ```k = 0.1```. Скорость его сходимости составила ```~30``` эпох, что на ```15``` эпох больше, в сравнении с другими вариантами. Точность в среднем меньше на ```0.04```. </br> Итог: параметр, обеспечивающий самую быструю скорость сходимости - ```k = 0.5```, параметр, обеспечивающий максимальную точность - все, кроме ```k = 0.1```. Оптимальный будем считать ```k = 0.5``` ### Формула ```python lrate = initial_lrate * drop^floor(epoch / epochs_drop) ``` ## 3. Графики тренировки нейронной сети с темпом обучения, изменяющегося по ступенчатому закону с параметрами: </br> ```initial_lrate = 0.1``` </br> ```drop = 0.99, 0.95, 0.5, 0.4, 0.35, 0.3, 0.1``` </br> ```epochs_drop = 1, 2, 10, 7, 7, 5, 1``` </br> </br> ![изображение](https://user-images.githubusercontent.com/61012068/111904315-59e68700-8a57-11eb-9088-8b8d958053a3.png) ### epoch categorical accuracy ![](./graphic/step_categorical_accuracy.svg) ### epoch loss ![](./graphic/step_loss.svg) *** # Анализ 3 Варианта,а именно ```drop = 0.4, 0.35, 0.3```, ```epochs_drop = 7, 7, 5``` показали примерно одинаковые результаты(```~15``` эпох для сходимости, ```~0.893``` точность), оставшиеся 3 проявили себя немного хуже(```~18``` эпох для сходимости, ```~0.88``` точность). Из этого можно сделать вывод что уменьшение ```epochs_drop``` и увеличение ```drop``` позитивно сказывается на скорости сходимости и точности модели. Итог: вариант со следующими параметрами показал как самую быструю скорость сходимости, так и максимальную точность - ```drop = 0.3```, ```epochs_drop = 5```. # Итог итогов Благодаря применению политик экспотенциального и пошагового(ступенчатого) изменения темпа обучения удалось добиться большей скорости сходимости(примерно на ```12``` эпох), хотя прибавка в точности совсем незначительная(```~0.002```) <file_sep>Решение задачи классификации изображений из набора данных Oregon Wildlife с использованием нейронных сетей глубокого обучения и техники обучения Transfer Learning # 1. Cлучайное начальное приближение ## Архитектура ```python inputs = tf.keras.layers.Input(shape=(RESIZE_TO, RESIZE_TO, 3)) outputs = EfficientNetB0(include_top=True, weights=None, classes=NUM_CLASSES)(inputs) return tf.keras.Model(inputs=inputs, outputs=outputs) ``` ## Визуализация обучения Синяя - данные для валидации(проверки качества) <br/> Розовая - тренировочные данные ### epoch categorical accuracy ![](./graphic/epoch_categorical_accuracy(2).svg) ### epoch loss ![](./graphic/epoch_loss(2).svg) *** ## Анализ Из графиков видно что нейросеть очень плохо обучается. Понятно, почему это происходит. Ситуация как в лабораторной работе #1, только в этом случае все обстоит еще сложнее, так как тренируемых параметров гораздо больше. В теории нейросеть должна просто запомнить данные в силу своей сложности и небольшого набора данных. На практике же этого не происходит потому что в архитектуре ```EfficientNetB0``` присутствуют слои ```Batch Normalization``` и ```Dropout``` которые вносят определенную регуляризацию, особенно ```Dropout```. # 2. Transfer Learning ## Архитектура ```python inputs = tf.keras.layers.Input(shape=(RESIZE_TO, RESIZE_TO, 3)) model = EfficientNetB0(include_top=False, weights='imagenet', input_tensor=inputs) model.trainable = False x = tf.keras.layers.GlobalAveragePooling2D()(model.output) x = tf.keras.layers.Flatten()(x) outputs = tf.keras.layers.Dense(NUM_CLASSES, activation="softmax")(x) return tf.keras.Model(inputs=inputs, outputs=outputs) ```` *** ## Визуализация обучения Оранжевая - данные для валидации(проверки качества) <br/> Синяя - тренировочные данные ### epoch categorical accuracy ![](./graphic/epoch_categorical_accuracy(4).svg) ### epoch loss ![](./graphic/epoch_loss(4).svg) # Анализ Из графиков мы видим что точность на валидационном наборе данных достигает 0.95 <br/> Отмечаем также быструю сходимость (5 эпох ~ 0.9 точность на валидации). Все это достигается за счет уменьшения тренируемых параметров примерно в 160 раз, по сравнению со слуйчайным приближением. Еще один плюс Transfer Learning это то что нам не нужно иметь много данных для обучения, так как мы обучаем только несколько слоев(один), поэтому даже при нашем датасете (12786 объектов) переобучения не происходит. <file_sep># Использование техник аугментации данных для улучшения сходимости процесса обучения нейронной сети на примере решения задачи классификации Oregon Wildlife Ниже представлены результаты тренировки EfficientNet-B0 (предварительно обученной на базе изображений imagenet) с использованием 4-ех видов аугментации, а также их композиция. Все графики представлены для валидационного набора данных. ## 1. Манипуляции с яркостью и контрастом ### ```# brightness_contrast.py``` Изначально формула для темпа обучения использовалась следующая: ```python 1. lrate = 0.1 * exp(-0.5 * num_epoch) ``` После 3 тренировок она была заменена на: </br> ```python 2. lrate = 0.01 * exp(-0.3 * num_epoch) ``` На легенде ниже у графиков полученных с помощью первого способа задания темпа обучения в имени отсутствует параметр ```k```. Остальные графики были получены с использванием второго способа. </br> Сравнивая эти два способа изменения темпа обучения видно что второй показал себя лучше и поэтому будет использваться далее везде, где не уточнено обратное. </br></br> ![mOQG5QcN_fI](https://user-images.githubusercontent.com/61012068/113139373-b2740c00-922f-11eb-94b9-74b077b265d3.jpg) accuracy ![](./graphic/BrightnessContrast_accuracy.svg) loss ![](./graphic/BrightnessContrast_loss.svg) Изменяя яркость и контраст удалось найти параметры увеличивающие точность на ```~0.05```, в сравнении с экспоненциальным изменением темпа обучения с параметрами ```initial_lrate = 0.1, k = 0.5```. Эти параметры будем считать оптимальными. ## 2. Поворот изображения на случайный угол ### ```# rotate.py``` ### 2.1 Исследование параметров ![mGxwmqOuNb4](https://user-images.githubusercontent.com/61012068/113133246-185c9580-9228-11eb-9c78-f79fe160f828.jpg) accuracy ![](./graphic/Rotate_accuracy.svg) loss ![](./graphic/Rotate_loss.svg) Максимальной точности (```~0.89```), что на ```~0.02``` хуже чем без аугментации, удалось достить благодаря параметрам ```alpha = 15, p = 0.25```, их и будем считать оптимальными. ### 2.2 Исследование методов интерполяции и экстраполяции ![s-2JZSeM0s8](https://user-images.githubusercontent.com/61012068/113134749-de8c8e80-9229-11eb-89e8-e3df172a6462.jpg) accuracy ![](./graphic/Rotate2_accuracy.svg) loss ![](./graphic/Rotate2_loss.svg) На графике с именем ```Rotate_a15_p1_k0.3``` использовались следующие методы интерполяции: ```interpolation - LINEAR```, ```extrapolation - REFLECT_101``` соответсвенно. По результатам тренировки лучшего метода апроксимации и интерполяции определить не удалось, так как показали они себя в среднем одинаково (```~0.8``` точность). Поэтому оптимальными будем считать параметры: ```interpolation - LINEAR```, ```extrapolation - REFLECT_101```. ## 3. Использование случайной части изображения ### ```# crop.py``` ![PyaxZp33zNQ](https://user-images.githubusercontent.com/61012068/113120720-8c903c80-921a-11eb-95b6-ab515b509f4d.jpg) accuracy ![](./graphic/RandomCrop_accuracy.svg) loss ![](./graphic/RandomCrop_loss.svg) В результате применения метода спользование случайной части изображения удалось тостичь максимальной точности (```~0.89```), что в среднем на (```0.02```) меньше чем без угментации. Параметры при которых нам удалось достичь такого результата будем считать оптимальными. ## 4. Добавление случайного шума ### ```# noise.py``` ![tYMn-ArmZmw](https://user-images.githubusercontent.com/61012068/113120731-8f8b2d00-921a-11eb-8aee-9e6810aa77c4.jpg) accuracy ![](./graphic/GaussNoise_accuracy.svg) loss ![](./graphic/GaussNoise_loss.svg) Добавляя случайный шум удалось получить точность как при использовании экспоненциального закона изменения темпа обучения с параметрами ```initial_lrate = 0.1, k = 0.5```, а именно ```~0.8925```. Поэтому оптимальными парамтерами будем считать ```min = 50, max = 60, p = 1``` ## 5. Композиция ```python transforms = A.Compose([ A.RandomBrightnessContrast (brightness_limit=[-0.3, -0.3], contrast_limit=[1, 1], p=1), A.Rotate(limit=15, p=0.25), A.RandomCrop(224, 224, p=1), A.GaussNoise(var_limit=(50, 60), p=1), ]) ``` ![xRjniFQXyoY](https://user-images.githubusercontent.com/61012068/113560012-fd649980-960a-11eb-8776-ac4dd6f7f655.jpg) accuracy ![](./graphic/all_accuracy.svg) loss ![](./graphic/all_loss.svg) Применяя все вышеописанные аугментации удалось добиться, в среднем, точности (```~0.874```), что на ```~0.018``` меньше чем без аугментации. <file_sep>"""This module implements data feeding and training loop to create model to classify X-Ray chest images as a lab example for BSU students. """ __author__ = '<NAME>, <EMAIL>' __copyright__ = """Copyright 2020 <NAME>""" import argparse import glob import numpy as np import tensorflow as tf import time import os import math import albumentations as A import matplotlib.pyplot as plt from functools import partial from tensorflow.keras.applications import EfficientNetB0 from tensorflow.python import keras as keras from tensorflow.python.keras.callbacks import LearningRateScheduler from tensorflow.keras.preprocessing import image # Avoid greedy memory allocation to allow shared GPU usage gpus = tf.config.experimental.list_physical_devices('GPU') for gpu in gpus: tf.config.experimental.set_memory_growth(gpu, True) LOG_DIR = 'logs' BATCH_SIZE = 64 NUM_CLASSES = 20 RESIZE_TO = 224 TRAIN_SIZE = 12786 def parse_proto_example(proto): keys_to_features = { 'image/encoded': tf.io.FixedLenFeature((), tf.string, default_value=''), 'image/label': tf.io.FixedLenFeature([], tf.int64, default_value=tf.zeros([], dtype=tf.int64)) } example = tf.io.parse_single_example(proto, keys_to_features) example['image'] = tf.image.decode_jpeg(example['image/encoded'], channels=3) example['image'] = tf.image.convert_image_dtype(example['image'], dtype=tf.uint8) example['image'] = tf.image.resize(example['image'], tf.constant([256, 256]), method='nearest') return example['image'], tf.one_hot(example['image/label'], depth=NUM_CLASSES) def aug_fn(image, label, transforms): def Transform(image): data = {"image":image} aug_data = transforms(**data) aug_img = aug_data["image"] aug_img = tf.image.resize(aug_img, size=[RESIZE_TO, RESIZE_TO]) aug_img = tf.cast(aug_img, tf.uint8) return aug_img aug_image = tf.numpy_function(func=Transform, inp=[image], Tout=(tf.uint8)) return aug_image, label def set_shapes(img, label, img_shape=(RESIZE_TO, RESIZE_TO, 3)): img.set_shape(img_shape) return img, label def create_dataset(filenames, batch_size, transforms): """Create dataset from tfrecords file :tfrecords_files: Mask to collect tfrecords file of dataset :returns: tf.data.Dataset """ return tf.data.TFRecordDataset(filenames)\ .map(parse_proto_example, num_parallel_calls=tf.data.AUTOTUNE)\ .map(partial(aug_fn, transforms=transforms), num_parallel_calls=tf.data.AUTOTUNE)\ .map(set_shapes, num_parallel_calls=tf.data.AUTOTUNE)\ .batch(BATCH_SIZE)\ .prefetch(tf.data.AUTOTUNE) def build_model(): inputs = tf.keras.layers.Input(shape=(RESIZE_TO, RESIZE_TO, 3)) model = EfficientNetB0(include_top=False, weights='imagenet', input_tensor=inputs) model.trainable = False x = tf.keras.layers.GlobalAveragePooling2D()(model.output) #x = tf.keras.layers.BatchNormalization()(x) #x = tf.keras.layers.Dropout(0.2)(x) #x = tf.keras.layers.Dense(100, activation=tf.keras.layers.ReLU())(x) outputs = tf.keras.layers.Dense(NUM_CLASSES, activation="softmax")(x) return tf.keras.Model(inputs=inputs, outputs=outputs) def main(): args = argparse.ArgumentParser() args.add_argument('--train', type=str, help='Glob pattern to collect train tfrecord files, use single quote to escape *') args = args.parse_args() '''transforms = A.Compose([ A.RandomBrightnessContrast (brightness_limit=[-0.3, -0.3], contrast_limit=[1, 1], p=1), A.Rotate(limit=15, p=0.25), A.RandomCrop(224, 224, p=1), A.GaussNoise(var_limit=(50, 60), p=1), ]) exp_sheduler = lambda epoch: 0.01 * math.exp(-0.3*epoch) dataset = create_dataset(glob.glob(args.train), BATCH_SIZE, transforms) for i, (x, y) in enumerate(dataset2.take(8)): plt.imshow(x[i]) output_path = os.path.join('examples/',str(i)+'.jpg') plt.savefig(output_path) train_size = int(TRAIN_SIZE * 0.7 / BATCH_SIZE) train_dataset = dataset.take(train_size) validation_dataset = dataset.skip(train_size) model = build_model() model.compile( optimizer=tf.optimizers.Adam(), loss=tf.keras.losses.categorical_crossentropy, metrics=[tf.keras.metrics.categorical_accuracy], ) log_dir='{}/before2'.format(LOG_DIR) print(log_dir) model.fit( train_dataset, epochs=50, validation_data=validation_dataset, callbacks=[ tf.keras.callbacks.TensorBoard(log_dir), tf.keras.callbacks.LearningRateScheduler(exp_sheduler), ] ) model.save('model2.h5')''' alpha = [30, 35, 40] p = [0.2, 0.15, 0.1] for i in range(3): transforms = A.Compose([ A.RandomBrightnessContrast (brightness_limit=[-0.3, -0.3], contrast_limit=[1, 1], p=1), A.Rotate(limit=alpha[i], p=p[i]), A.RandomCrop(224, 224, p=1), A.GaussNoise(var_limit=(50, 60, p=1), ]) step_sheduler = lambda epoch: 1e-8 * math.pow(0.5, math.floor((1+epoch)/10)) dataset = create_dataset(glob.glob(args.train), BATCH_SIZE, transforms) train_size = int(TRAIN_SIZE * 0.7 / BATCH_SIZE) train_dataset = dataset.take(train_size) validation_dataset = dataset.skip(train_size) log_dir='{}/rotate_{}_{}_{}'.format(LOG_DIR, alpha[i], p[i], time.time()) model = tf.keras.models.load_model('model2.h5') def unfreeze_model(model): for layer in model.layers: if not isinstance(layer, tf.keras.layers.BatchNormalization): layer.trainable = True model.compile( optimizer=tf.optimizers.Adam(), loss=tf.keras.losses.categorical_crossentropy, metrics=[tf.keras.metrics.categorical_accuracy], ) unfreeze_model(model) print(model.summary()) model.fit( train_dataset, epochs=50, validation_data=validation_dataset, callbacks=[ tf.keras.callbacks.TensorBoard(log_dir), tf.keras.callbacks.LearningRateScheduler(step_sheduler), ] ) if __name__ == '__main__': main() <file_sep>Ниже представлены результаты обучения двух моделей для задачи классификации на наборе данных 'Oregon Wildlife' # 1. Начальная сеть ## Архитектура ```python inputs = tf.keras.Input(shape=(RESIZE_TO, RESIZE_TO, 3)) x = tf.keras.layers.Conv2D(filters=8, kernel_size=3)(inputs) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Flatten()(x) outputs = tf.keras.layers.Dense(NUM_CLASSES, activation=tf.keras.activations.softmax)(x) ``` ## Описание ### Conv2D ```Conv2D``` представляет собой свертку 3х3 с ```padding = 0``` и ```strides = (1,1)``` ### MaxPool2D ```MaxPool2D``` выбирает из 4(```padding=0, stride=0, size=(2,2)```) 'пикселей' один с максимальным значением, тем самым уменьшая исходную размерность в 4 раза ### Flatten ```Flatten``` преобразует размерность данных из ```(8, 111, 111)``` в ```(None, 98568)``` ### Dense ```Dense``` представляет собой полносвязный слой с размерностью ```(None, 98568)``` на входе и ```(None, 20)``` на выходе <br/> За ним следует функция акивации ```softmax``` которая превращает выходы из ```Dense``` в вероятности *** ## Графика Blue - данные для валидации(проверки качества) <br/> Orange - тренировочные данные ### epoch categorical accuracy ![](./graphic/epoch_categorical_accuracy(1).svg) ### epoch loss ![](./graphic/epoch_loss(1).svg) *** ## 2. Модифицированная сеть ## Архитектура ```python inputs = tf.keras.Input(shape=(RESIZE_TO, RESIZE_TO, 3)) x = tf.keras.layers.Conv2D(filters=8, kernel_size=3, activation=tf.keras.layers.ReLU())(inputs) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Conv2D(filters=16, kernel_size=3, activation=tf.keras.layers.ReLU())(x) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Conv2D(filters=32, kernel_size=3, activation=tf.keras.layers.ReLU())(x) x = tf.keras.layers.MaxPool2D()(x) x = tf.keras.layers.Conv2D(filters=64, kernel_size=3, activation=tf.keras.layers.ReLU())(x) x = tf.keras.layers.Flatten()(x) x = tf.keras.layers.Dense(94, activation=tf.keras.layers.ReLU())(x) outputs = tf.keras.layers.Dense(NUM_CLASSES, activation=tf.keras.activations.softmax)(x) ``` ## Описание ### ReLU ```ReLU``` представляет собой функцию активации которая нужна для придания нелинейности нейронной сети <br/> ### В нейронную сеть были добавлены 3 ```Conv2D``` слоя чтобы увеличить возможность выразить более сложные признаки, этим обуславливается и наличие большего числа фильтров в данных слоях,а именно ```16, 32, 64```, благодаря этим изменениям сеть может различать признаки более сложные чем линии,градиенты, и т.п. а именно их комбинации. Так же увеличение количества фильтров с каждым слоем показывает себя лучше чем статическое их значение, так как разничных комбинайций более простых признаков становится все больше.В архитектуру так же был добавлен дополнительный полносвязный слой для лучшего разделения на классы. В качестве нелинейности выбрана функция ```ReLU```. *** ## Графика Orange - данные для валидации(проверки качества) <br/> Grey - тренировочные данные ### epoch categorical accuracy ![](./graphic/epoch_categorical_accuracy(2).svg) ### epoch loss ![](./graphic/epoch_loss(2).svg) *** # 3. Анализ Из графиков видно, что первая модель быстрее обучается, что можно объяснить ее простотой. Для второй же модели, возможно, понадобится больше эпох.Возможно так же что второй модели сложно обучится потому что не хватает данных. Так же на обе модели сказывается случаная инициализация весов, из за чего можно очень долго искать минимум функции ошибки.
2c4955c851786111996be5d98485962ab7288b06
[ "Markdown", "Python" ]
7
Markdown
WHO777/labs
90e3f7827c9400a3cc205506abb2970d582367e4
b8b0a426d381a78f46c555d30c3124788618103a
refs/heads/master
<repo_name>EGM/JSCodeRun<file_sep>/src/screens/MainScreen.test.js import React, { Component } from 'react'; import renderer from 'react-test-renderer'; import { MainScreen } from './MainScreen'; jest.mock('../components/CodeEditor', () => 'CodeEditor'); jest.mock('../components/Output', () => 'Output'); jest.mock('../components/HeaderBar', () => 'HeaderBar'); describe('MainScreen', () => { it('should render correctly', () => { const rendered = renderer.create(<MainScreen />).toJSON(); expect(rendered).toMatchSnapshot(); }); describe('runCode', () => { it('should produce an array of a single output when code is logged', () => { const instance = renderer.create(<MainScreen />).getInstance(); instance.setState({ code: 'console.log("Test output")' }); const expected = [ { message: 'Test output', status: 'OK' } ]; instance.runCode(); expect(instance.state.output).toEqual(expected); }); it('should produce an array of a multiple outputs when code is logged', () => { const instance = renderer.create(<MainScreen />).getInstance(); instance.setState({ code: 'console.log("Test output"); console.log("More output");' }); const expected = [ { message: 'Test output', status: 'OK' }, { message: 'More output', status: 'OK' } ]; instance.runCode(); expect(instance.state.output).toEqual(expected); }); it('should produce an array of a multiple error outputs when code errors', () => { const instance = renderer.create(<MainScreen />).getInstance(); instance.setState({ code: 'badcode' }); const expected = [ { message: 'ReferenceError: badcode is not defined', status: 'ERROR' } ]; instance.runCode(); expect(instance.state.output).toEqual(expected); }); }); });
b21f6a4e9524da8cdfc6ec9ba7daa89fd75df1db
[ "JavaScript" ]
1
JavaScript
EGM/JSCodeRun
262e6bd12a720a466437cfeedf44c0a799d411fe
a53fdf134ce16bf9c70cd0c26450f5039238a517
refs/heads/master
<repo_name>patlaughlin/how_to_make_an_rpg<file_sep>/manifest.lua -- -- A manifest of all the game's assets -- manifest = { scripts = { ['main.lua'] = { path = "main.lua" }, }, textures = { ['tiles_00.png'] = { path = "images/tiles_00.png", }, ['tiles_01.png'] = { path = "images/tiles_01.png", }, ['tiles_02.png'] = { path = "images/tiles_02.png", }, ['tiles_03.png'] = { path = "images/tiles_03.png", }, ['tiles_04.png'] = { path = "images/tiles_04.png", }, ['tiles_05.png'] = { path = "images/tiles_05.png", }, ['tiles_06.png'] = { path = "images/tiles_06.png", }, ['tiles_07.png'] = { path = "images/tiles_07.png", }, ['tiles_08.png'] = { path = "images/tiles_08.png", }, ['tiles_09.png'] = { path = "images/tiles_09.png", }, ['tiles_10.png'] = { path = "images/tiles_10.png", }, } } <file_sep>/settings.lua name = "Drawing a Full Map" width = 256 height = 224 manifest = "manifest.lua" main_script = "main.lua" on_update = "update()" webserver = false <file_sep>/main.lua LoadLibrary("Renderer") LoadLibrary("Sprite") LoadLibrary("System") LoadLibrary("Texture") gTextures = { Texture.Find("tiles_00.png"), Texture.Find("tiles_01.png"), Texture.Find("tiles_02.png"), Texture.Find("tiles_03.png"), Texture.Find("tiles_04.png"), Texture.Find("tiles_05.png"), Texture.Find("tiles_06.png"), Texture.Find("tiles_07.png"), Texture.Find("tiles_08.png"), Texture.Find("tiles_09.png"), Texture.Find("tiles_10.png"), } function GenerateUVs(texture, tileSize) local uvs = {} local textureWidth = texture:GetWidth() local textureHeight = texture:GetHeight() local width = tileSize / textureWidth local height = tileSize / textureHeight local cols = textureWidth / tileSize local rows = textureHeight / tileSize local u0 = 0 local v0 = 0 local u1 = width local v1 = height for j = 0, rows - 1 do for i = 0, cols -1 do table.insert(uvs, {u0, v0, u1, v1}) u0 = u0 + width u1 = u1 + width end u0 = 0 v0 = v0 + height u1 = width v1 = v1 + height end return uvs end gMap = { 1,1,1,1,5,6, 7,1, -- 1 1,1,1,1,5,6,7,1, -- 2 1,1,1,1,5,6,7,1, -- 3 3,3,3,3,11,6,7,1, -- 4 9,9,9,9,9,9,10,1, -- 5 1,1,1,1,1,1,1,1, -- 6 1,1,1,1,1,1,2,3, -- 7 } gUVs = { -- Left Top Right Bottom -- U V U V {0, 0, 0.0625, 0.0625}, {0.0625, 0, 0.125, 0.0625}, {0.125, 0, 0.1875, 0.0625}, 44 {0.1875, 0, 0.25, 0.0625}, {0.25, 0, 0.3125, 0.0625}, {0.3125, 0, 0.375, 0.0625}, {0.375, 0, 0.4375, 0.0625}, {0.4375, 0, 0.5, 0.0625}, {0.5, 0, 0.5625, 0.0625}, {0.5625, 0, 0.625, 0.0625}, {0.625, 0, 0.6875, 0.0625}, } gMapWidth = 8 gMapHeight = 7 gTileWidth = gTextures[1]:GetWidth() gTileHeight = gTextures[1]:GetHeight() gDisplayWidth = System.ScreenWidth() gDisplayHeight = System.ScreenHeight() gTop = gDisplayHeight / 2 - gTileHeight / 2 gLeft = -gDisplayWidth / 2 + gTileWidth / 2 function GetTile(map, rowsize, x, y) x = x + 1 -- change from 1 -> rowsize -- to 0 -> rowsize - 1 return map[x + y * rowsize] end gRenderer = Renderer.Create() local row = 0 for col = 0, gMapWidth - 1 do local coords = string.format("[%d,%d]: ", col, row) print(coords, GetTile(gMap, gMapWidth, col, row)) end gTileSprite = Sprite.Create() gTileSprite:SetTexture(gTextures[1]) function update() for j = 0, gMapHeight - 1 do for i = 0, gMapWidth - 1 do local tile = GetTile(gMap, gMapWidth, i, j) local texture = gTextures[tile] gTileSprite:SetTexture(texture) gTileSprite:SetPosition(gLeft + i * gTileWidth, gTop - j * gTileHeight) gRenderer:DrawSprite(gTileSprite) end end end
e60adf853d61d748bef183fc68e045915cd535ff
[ "Lua" ]
3
Lua
patlaughlin/how_to_make_an_rpg
641437c188c696f217531d3cd78ca0df23cd01d9
5984a78a5809792a2b76f127ab22859dd7855754
refs/heads/master
<repo_name>fcostin/xmonad-config<file_sep>/apply_settings.sh #! /usr/bin/env bash cp .xinitrc ~/.xinitrc cp .xmobarrc ~/.xmobarrc cp .xmonad/xmonad.hs ~/.xmonad/xmonad.hs
0e515fbf75ce13d4b7b0092fd1dae23a419956f3
[ "Shell" ]
1
Shell
fcostin/xmonad-config
4b0a4eb2c389cbad369367e9a193c02f419615dc
ac2bd19cc949f8d209c28a8de6ade987deee2387
refs/heads/master
<repo_name>An-AngryBear/Sandwich-Maker<file_sep>/javascripts/condiments.js var SandwichMaker = (function(maker) { var condimentPrices = { "Mustard": 0.15, "Mayo": 0.15, "<NAME>": 0.15, "Horseradish": .15, "<NAME>": 0.20, }; let condiments = Object.create(null); condiments.returnCondimentNames = function() { let condiments = []; for (key in condimentPrices) { condiments.push(key); } return condiments; }; condiments.addCondiment = function(ingredientSelected) { return condimentPrices[ingredientSelected]; }; maker.Condiments = condiments; return maker; })(SandwichMaker || {});<file_sep>/javascripts/SandwichMaker.js var SandwichMaker = (function(maker) { // Private variable to store the price var totalPrice = 0; var pendingPrices = { meats: {}, cheese: {}, veggies: {}, breads: {}, condiments: {} }; let calculator = Object.create(null); // Iterates over pendingPrices and adjusts the total price based on user selection function getTotalPrice() { let arrayMaker = Object.values(pendingPrices); let getValues = arrayMaker.reduce(function(acc, cur) { return acc.concat(Object.values(cur)); },[]) let getTotal = getValues.reduce(function(acc, cur) { return acc + cur; }) totalPrice = getTotal.toFixed(2); console.log(totalPrice); } // adjust the pending prices based on quantity selected calculator.quantityMultiplier = function(price, quantity, ingredientType, ingredientSubType) { let multipliedPrice = price * quantity; switch(ingredientType) { case "Meats": pendingPrices.meats[ingredientSubType] = parseFloat(multipliedPrice.toFixed(2)); break; case "Cheese": pendingPrices.cheese[ingredientSubType] = parseFloat(multipliedPrice.toFixed(2)); break; case "Veggies": pendingPrices.veggies[ingredientSubType] = parseFloat(multipliedPrice.toFixed(2)); break; case "Breads": pendingPrices.breads[ingredientSubType] = parseFloat(multipliedPrice.toFixed(2)); break; case "Condiments": pendingPrices.condiments[ingredientSubType] = parseFloat(multipliedPrice.toFixed(2)); } getTotalPrice(); } calculator.getPrice = function() { return totalPrice; } maker.Calc = calculator; return maker })(SandwichMaker || {}); <file_sep>/javascripts/cheese.js var SandwichMaker = (function(maker) { var cheesePrices = { "Cheddar": 0.50, "Swiss": 0.50, "American": .25, "Bleu": .50, "Mozzarella": .50 }; let cheese = Object.create(null); cheese.returnCheeseNames = function() { let cheeses = []; for (key in cheesePrices) { cheeses.push(key); } return cheeses; }; cheese.addCheese = function(ingredientSelected) { return cheesePrices[ingredientSelected]; }; maker.Cheese = cheese; return maker; })(SandwichMaker || {});<file_sep>/javascripts/DOMHandler.js const ingredientsOutput = document.getElementById("ingredients"), priceOutput = document.getElementById("display-box"); // dynamically places checkboxes and labels into the document based on ingredient/price objects on ingredient modules function putSectionBoxesInDom() { let ingredientObject = { "Breads": SandwichMaker.Bread.returnBreadNames(), "Meats": SandwichMaker.Meats.returnMeatNames(), "Cheese": SandwichMaker.Cheese.returnCheeseNames(), "Veggies": SandwichMaker.Veggies.returnVeggieNames(), "Condiments": SandwichMaker.Condiments.returnCondimentNames() } for(var key in ingredientObject) { let toStickInDom = document.createElement('div'); toStickInDom.innerHTML = `<label class="head-label">${key}</label> <section id="${key.toLowerCase()}-chooser"> <checkboxcontainer><input type="checkbox" name="${key}" class="checkbox"><label>${ingredientObject[key][0]}</label></checkboxcontainer> <checkboxcontainer><input type="checkbox" name="${key}" class="checkbox"><label>${ingredientObject[key][1]}</label></checkboxcontainer> <checkboxcontainer><input type="checkbox" name="${key}" class="checkbox"><label>${ingredientObject[key][2]}</label></checkboxcontainer> <checkboxcontainer><input type="checkbox" name="${key}" class="checkbox"><label>${ingredientObject[key][3]}</label></checkboxcontainer> <checkboxcontainer><input type="checkbox" name="${key}" class="checkbox"><label>${ingredientObject[key][4]}</label></checkboxcontainer> </section>`; ingredientsOutput.appendChild(toStickInDom); } } // listens for the change in value of any number input box, sends information to the calculator to calculate final price in real time document.addEventListener("input", function() { if(event.target.hasAttribute('placeholder') && event.target.value >= 0) { let ingredientType = event.target.parentNode.parentNode.parentNode.firstChild.innerHTML; let ingredientSubType = event.target.nextSibling.nextSibling.innerHTML; switch(event.target.parentNode.parentNode.id) { case "meats-chooser": SandwichMaker.Calc.quantityMultiplier(SandwichMaker.Meats.addMeat(ingredientSubType), event.target.value, ingredientType, ingredientSubType); break; case "veggies-chooser": SandwichMaker.Calc.quantityMultiplier(SandwichMaker.Veggies.addVeggie(ingredientSubType), event.target.value, ingredientType, ingredientSubType); break; case "cheese-chooser": SandwichMaker.Calc.quantityMultiplier(SandwichMaker.Cheese.addCheese(ingredientSubType), event.target.value, ingredientType, ingredientSubType); break; case "condiments-chooser": SandwichMaker.Calc.quantityMultiplier(SandwichMaker.Condiments.addCondiment(ingredientSubType), event.target.value, ingredientType, ingredientSubType); break; case "breads-chooser": SandwichMaker.Calc.quantityMultiplier(SandwichMaker.Bread.addBread(ingredientSubType), event.target.value, ingredientType, ingredientSubType); break; default: console.log("error identifying ingredient"); }; adjustPriceDisplay(); } }) // uses the final price to update the documents display box function adjustPriceDisplay() { let priceToAppend = document.createElement('p'), displayText = document.createElement('h3'); priceToAppend.setAttribute("class", "price") priceOutput.innerHTML = ""; displayText.innerHTML = `<h3>Final Sandwich Price:</h3>`; priceToAppend.innerHTML = `$${SandwichMaker.Calc.getPrice()}`; priceOutput.append(displayText, priceToAppend); } // Listens for a checkbox to be checked. If checked, inserts an ingredient quantity box next to the checked selection. // If unchecked, removes the number input box ingredientsOutput.addEventListener("change", function() { if(event.target.hasAttribute("name")) { if(event.target.checked) { let howMany = document.createElement('input'); howMany.defaultValue = 0; howMany.setAttribute('type', "number"); howMany.setAttribute('class', "howManyBox"); howMany.setAttribute('placeholder', "Portions?") event.target.parentNode.insertBefore(howMany, event.target); } else if (event.target.previousSibling.hasAttribute('class') && event.target.previousSibling.classList.contains('howManyBox')) { let ingredientType = event.target.parentNode.parentNode.parentNode.firstChild.innerHTML; let ingredientSubType = event.target.nextSibling.innerHTML; SandwichMaker.Calc.quantityMultiplier(0, 0, ingredientType, ingredientSubType); event.target.previousSibling.remove(); adjustPriceDisplay(); } } }) putSectionBoxesInDom(); adjustPriceDisplay();<file_sep>/javascripts/bread.js var SandwichMaker = (function(maker) { var breadPrices = { "Ciabatta" : 0.40, "Whole Grain" : 0.25, "Honey Wheat" : 0.25, "White" : 0.25, "Rye" : .35 }; let bread = Object.create(null); bread.returnBreadNames = function() { let breads = []; for (key in breadPrices) { breads.push(key); } return breads; }; bread.addBread = function(ingredientSelected) { return breadPrices[ingredientSelected]; }; maker.Bread = bread; return maker; })(SandwichMaker || {});<file_sep>/javascripts/meats.js var SandwichMaker = (function(maker) { var meatPrices = { "Bacon" : 1.50, "Turkey" : .90, "Ham" : .90, "Roast Beef" : 1.15, "Salami" : 1.00 }; let meat = Object.create(null); meat.returnMeatNames = function() { let meats = []; for (key in meatPrices) { meats.push(key); } return meats; }; meat.addMeat = function(IngredientSelected) { return meatPrices[IngredientSelected]; }; maker.Meats = meat; return maker; })(SandwichMaker || {});<file_sep>/javascripts/veggies.js var SandwichMaker = (function(maker) { var veggiesPrices = { "Banana Peppers" : 0.25, "Lettuce" : 0.25, "Tomatoes" : 0.25, "Onions" : 0.10, "Pickles" : .10 }; let veggies = Object.create(null); veggies.returnVeggieNames = function() { let veggiesList = []; for (key in veggiesPrices) { veggiesList.push(key); } return veggiesList; }; veggies.addVeggie = function(ingredientSelected) { return veggiesPrices[ingredientSelected]; }; maker.Veggies = veggies; return maker; })(SandwichMaker || {});
1921ce6797978b128f68a6058da6abd0e5caff01
[ "JavaScript" ]
7
JavaScript
An-AngryBear/Sandwich-Maker
34b0e3ef01e114e5b1a800e8851b6781b0ec3b0d
ea9271d292ae2179f9d3524847a646f6dc374a91
refs/heads/main
<file_sep>import numpy as np import pandas as pd from keras.models import Sequential from keras.layers import Dense from sklearn.model_selection import KFold from sklearn.preprocessing import MinMaxScaler from sklearn.metrics import roc_curve, auc import matplotlib.pyplot as plt df = pd.read_excel("heart.xlsx") print(df.head()) data = df.to_numpy() X = data[:, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]] y = data[:, -1] kfold_n_split = 10 kf = KFold(n_splits=kfold_n_split, shuffle=True, random_state=2) kfold_get = kf.split(X) list = [] for j in range(kfold_n_split): print("fold: ", j) result = next(kfold_get) X_train = X[result[0]] X_test = X[result[1]] y_train = y[result[0]] y_test = y[result[1]] scaler = MinMaxScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) model = Sequential() model.add(Dense(8, input_dim=X.shape[1], activation='relu')) model.add(Dense(5, activation='relu')) model.add(Dense(1, activation='sigmoid')) model.compile(loss='binary_crossentropy', optimizer='adam', metrics=['accuracy']) model.fit(X_train, y_train, epochs=200, batch_size=100, validation_split=0.1, verbose=0) y_pred = model.predict(X_test) fpr, tpr, _ = roc_curve(y_test, y_pred) auc_score = auc(fpr, tpr) print("for fold :", j, " auc = ", auc_score) list.append(auc_score) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange', lw=lw) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show() print(sum(list) / 10) <file_sep>import pandas as pd import matplotlib.pyplot as plt from sklearn.metrics import roc_curve,auc from sklearn.ensemble import RandomForestClassifier df = pd.read_excel("heart.xlsx") print(df.head()) data = df.to_numpy() X = data[:, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]] y = data[:, -1] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.1, random_state=42) from sklearn.preprocessing import MinMaxScaler scaler = MinMaxScaler() scaler.fit(X_train) X_train = scaler.transform(X_train) X_test = scaler.transform(X_test) X_train.shape model = RandomForestClassifier(max_depth=3, random_state=0) model = model.fit(X_train, y_train) y_pred = model.predict(X_test) fpr, tpr, _ = roc_curve(y_test, y_pred) auc_score = auc(fpr, tpr) print("auc = ",auc_score) plt.figure() lw = 2 plt.plot(fpr, tpr, color='darkorange',lw=lw) plt.plot([0, 1], [0, 1], color='navy', lw=lw, linestyle='--') plt.xlim([0.0, 1.0]) plt.ylim([0.0, 1.05]) plt.xlabel('False Positive Rate') plt.ylabel('True Positive Rate') plt.title('Receiver operating characteristic example') plt.legend(loc="lower right") plt.show()<file_sep># all-machineLearning-hospital A number of machine learning models for hospital data
8f2ef30d8570a9b759c2e8da07c71f259ac536e2
[ "Markdown", "Python" ]
3
Python
ordikhan/all-machineLearning-hospital
ab035e9472ef612b1a76c94087b6556e09c07e13
b29945f58b95db202e3d321e9ed39f236209f021
refs/heads/master
<repo_name>petchc/SoundAugmentation<file_sep>/main.py from __future__ import print_function import soundfile as sf import matplotlib.pyplot as plt import os import shutil import argparse import numpy as np import tensorflow as tf from sklearn import metrics import math from datetime import datetime import resampy import time import datetime import sys import six from pathlib import Path from scipy import stats import random as rd import prepare_data import vggish_slim import vggish_params import data_transformation import Postprocessor np.set_printoptions(threshold=sys.maxsize) tf.compat.v1.set_random_seed(41) slim = tf.contrib.slim def train(X_train, Y_train, X_eval, Y_eval, checkpoint_dir,save_dir, num_epochs=1,minibatch_size=32,print_cost=True,augmentation=False): ''' Training and Validation loop including the data augmentation step. The data augmentation will executed only when parameter augmentation=True ''' # The original coding is obtained from VGGish supporting code but it has been modified by the project. # ref https://github.com/tensorflow/models/blob/master/research/audioset/vggish/vggish_train_demo.py tf.compat.v1.set_random_seed(41) seed = 43 loss_train=[] map_train=[] auc_train=[] d_prime_train=[] loss_eval_list=[] map_eval=[] auc_eval=[] d_prime_eval=[] m_train = X_train.shape[0] n_y = Y_train.shape[1] m_eval = X_eval.shape[0] start = datetime.datetime.now() standard_normal = stats.norm() best_loss = 999 stopping_step = 0 if(augmentation == True): prepare_data.create_folder('./audio_aug') with tf.Graph().as_default(), tf.compat.v1.Session() as sess: # Define classification layer for training and validation loop. logits = vggish_slim.define_audio_slim(training=True,is_reuse=None) logits_eval = vggish_slim.define_audio_slim(training=False,is_reuse=True) # Build TensorFlow graph for training and validation loop. with tf.compat.v1.variable_scope('mymodel'): # Prediction function predict = tf.sigmoid(logits, name='prediction') predict_eval = tf.sigmoid(logits_eval, name='prediction_eval') # Add training ops. with tf.compat.v1.variable_scope('train'): global_step = tf.Variable( 0, name='global_step', trainable=False, collections=[tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, tf.compat.v1.GraphKeys.GLOBAL_STEP]) # Define placeholder for feeding the labels # Labels are fed as a batch multi-hot vectors, with # a 1 in the position of each positive class label, and 0 elsewhere. labels = tf.compat.v1.placeholder( tf.float32, shape=(None, n_y ), name='labels') # Define loss function and calculate loss xent = tf.nn.sigmoid_cross_entropy_with_logits( logits=logits, labels=labels, name='xent') loss = tf.reduce_mean(xent, name='loss_op') tf.compat.v1.summary.scalar('loss', loss) xent_eval = tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_eval, labels=labels, name='xent_eval') loss_eval = tf.reduce_mean(xent_eval, name='loss_op_eval') tf.compat.v1.summary.scalar('loss_eval', loss_eval) # Use the same optimizer and hyperparameters as used to train VGGish. optimizer = tf.compat.v1.train.AdamOptimizer( learning_rate=vggish_params.LEARNING_RATE, epsilon=vggish_params.ADAM_EPSILON) optimizer.minimize(loss, global_step=global_step, name='train_op') # Initialize all variables in the model sess.run(tf.compat.v1.global_variables_initializer()) saver = tf.compat.v1.train.Saver() # Locate all the tensors and ops we need for the training and validation loop. features_tensor = sess.graph.get_tensor_by_name( 'audio/audio_input_features:0') features_tensor_eval = sess.graph.get_tensor_by_name( 'audio_1/audio_input_features:0') labels_tensor = sess.graph.get_tensor_by_name('mymodel/train/labels:0') global_step_tensor = sess.graph.get_tensor_by_name( 'mymodel/train/global_step:0') loss_tensor = sess.graph.get_tensor_by_name('mymodel/train/loss_op:0') loss_tensor_eval = sess.graph.get_tensor_by_name('mymodel/train/loss_op_eval:0') train_op = sess.graph.get_operation_by_name('mymodel/train/train_op') prediction_tensor = sess.graph.get_tensor_by_name('mymodel/prediction:0') prediction_tensor_eval = sess.graph.get_tensor_by_name('mymodel/prediction_eval:0') #Build TensorFlow graph for VGGish feature extraction. graph = tf.Graph() with graph.as_default(): # set the trainable parameter to False to forbid the VGGish in further parameters training. vggish_slim.define_vggish_slim(training=False) sess_ext = tf.compat.v1.Session(graph=graph) # load VGGish pre-trained checkpoint vggish_slim.load_vggish_slim_checkpoint(sess_ext, checkpoint_dir + "vggish_model.ckpt") input_tensor = graph.get_tensor_by_name('vggish/input_features:0') output_tensor = graph.get_tensor_by_name('vggish/embedding:0') # load PCA parameters pproc = Postprocessor.Postprocessor(checkpoint_dir + "vggish_pca_params.npz") #Training process for epoch in range(num_epochs): print('\n###################') print('# Training loop #') print('###################') avg_loss_train = 0. avg_map_train = 0. avg_auc_train = 0. avg_d_prime_train = 0. step_train=0 # number of minibatches of size minibatch_size in the train set num_minibatches_train = int(np.ceil(m_train / minibatch_size)) seed = seed + 1 # Generate minibatches minibatches_files_train = prepare_data.random_mini_batches_files(X_train, Y_train, minibatch_size, seed, shuffle=True) for minibatch_file in minibatches_files_train: # Select a minibatch for loading the data and do data tranformation and pre-processing step (minibatch_X, minibatch_Y) = prepare_data.get_train_data(minibatch_file,sess_ext,input_tensor,output_tensor,pproc,is_train=True,seed=seed,is_augment=augmentation) # Run the training graph num_steps_train ,step_loss_train,pred_tensor_train, _ = sess.run( [global_step_tensor,loss_tensor,prediction_tensor, train_op], feed_dict={features_tensor: minibatch_X, labels_tensor: minibatch_Y}) # Calculate the measurements step_auc_train = metrics.roc_auc_score(np.asarray(minibatch_Y), pred_tensor_train, average='micro') step_map_train = metrics.average_precision_score(np.asarray(minibatch_Y), pred_tensor_train, average='micro') step_d_prime_train = standard_normal.ppf(step_auc_train) * np.sqrt(2.0) avg_loss_train += step_loss_train / num_minibatches_train avg_map_train += step_map_train / num_minibatches_train avg_auc_train += step_auc_train / num_minibatches_train avg_d_prime_train += step_d_prime_train / num_minibatches_train # Print first step result then print result every 10 steps until the last step. if((step_train+1) % 10 == 0 or step_train+1==num_minibatches_train or step_train==0): print("Epoch {}/{}, Step: {}/{} ,Loss: {:.5f}, MAP: {:.5f}, AUC: {:.5f}, d-prime: {:.5f}" \ .format(epoch+1,num_epochs, \ step_train +1 ,num_minibatches_train,step_loss_train,step_map_train,step_auc_train,step_d_prime_train)) step_train += 1 # Check data augmentation condition. if(augmentation == True and vggish_params.AUGMENT_SAVE == False): shutil.rmtree('./audio_aug') prepare_data.create_folder('./audio_aug') print('\n###################') print('# Validation loop #') print('###################') avg_loss_eval = 0. avg_map_eval = 0. avg_auc_eval = 0. avg_d_prime_eval = 0. # number of minibatches of size minibatch_size in the validation set num_minibatches_eval = int(np.ceil(m_eval / minibatch_size)) # Generate minibatches minibatches_files_eval = prepare_data.random_mini_batches_files(X_eval, Y_eval, minibatch_size, seed, shuffle=False) step_eval = 0 for minibatch_file_eval in minibatches_files_eval: # Select a minibatch and do data tranformation and pre-processing step (minibatch_X_eval, minibatch_Y_eval) = prepare_data.get_train_data(minibatch_file_eval,sess_ext,input_tensor,output_tensor,pproc,is_train=False,seed=seed,is_augment=False) # Run the validation graph num_steps_eval ,step_loss_eval,pred_tensor_eval = sess.run( [global_step_tensor, loss_tensor_eval,prediction_tensor_eval], feed_dict={features_tensor_eval: minibatch_X_eval, labels_tensor: minibatch_Y_eval}) # Calculate the measurements step_auc_eval = metrics.roc_auc_score(np.asarray(minibatch_Y_eval), pred_tensor_eval, average='micro') step_map_eval = metrics.average_precision_score(np.asarray(minibatch_Y_eval), pred_tensor_eval, average='micro') step_d_prime_eval = standard_normal.ppf(step_auc_eval) * np.sqrt(2.0) avg_loss_eval += step_loss_eval / num_minibatches_eval avg_map_eval += step_map_eval / num_minibatches_eval avg_auc_eval += step_auc_eval / num_minibatches_eval avg_d_prime_eval += step_d_prime_eval / num_minibatches_eval # Print first step result then print result every 10 steps until the last step. if((step_eval+1) % 10 == 0 or step_eval+1==num_minibatches_eval or step_eval==0): print("Epoch {}/{}, Step: {}/{} ,Loss: {:.5f}, mAP: {:.5F}, AUC: {:.5F}, d-prime: {:.5F}" \ .format(epoch+1,num_epochs, \ step_eval+1 ,num_minibatches_eval,step_loss_eval,step_map_eval,step_auc_eval,step_d_prime_eval)) step_eval += 1 # Print summay result of each epoch if print_cost == True: print("\n---Epoch %i Summary---" % (epoch+1)) loss_train.append(avg_loss_train) map_train.append(avg_map_train) auc_train.append(avg_auc_train) d_prime_train.append(avg_d_prime_train) print("Training : loss %.5f, mAP %.5f, AUC %.5f, d-prime %.5f" % (avg_loss_train,avg_map_train,avg_auc_train,avg_d_prime_train)) loss_eval_list.append(avg_loss_eval) map_eval.append(avg_map_eval) auc_eval.append(avg_auc_eval) d_prime_eval.append(avg_d_prime_eval) print("Validation : loss %.5f, mAP %.5f, AUC %.5f, d-prime %.5f" % (avg_loss_eval,avg_map_eval,avg_auc_eval,avg_d_prime_eval)) # Implement the early stopping if (avg_loss_eval < best_loss): stopping_step = 0 best_loss = avg_loss_eval save_sess = sess else: stopping_step += 1 if stopping_step >= 3: print("\nEarly stopping is trigger at epoch: {} loss:{:.5f}".format(epoch+1,avg_loss_eval)) print("Model is convergence at epoch: {}".format(epoch-2)) break # Save the models save_path = saver.save(sess, save_dir + "model_base_test_3_epoch_%i.ckpt" % (epoch+1)) print("Model saved in path: %s" % save_path) #Plot result graphs plt.plot(np.squeeze(loss_train), 'b', label='Training loss') plt.plot(np.squeeze(loss_eval_list), 'r', label='Validation loss') plt.ylabel('Loss') plt.xlabel('Epochs') plt.title('The loss of the training and validation dataset') plt.legend() plt.xlim([0,epoch-3]) locs, labels = plt.xticks() labels = [int(item)+1 for item in locs] plt.xticks(locs, labels) plt.savefig("./figures/Loss_per_epoch_test_conv_3.png") plt.show() plt.close() plt.plot(np.squeeze(map_train), 'b', label='Training mAP') plt.plot(np.squeeze(map_eval), 'r', label='Validation mAP') plt.ylabel('mAP') plt.xlabel('Epochs') plt.title('The mean average precision\nof the training and validation dataset') plt.legend() plt.xlim([0,epoch-3]) locs, labels = plt.xticks() labels = [int(item)+1 for item in locs] plt.xticks(locs, labels) plt.savefig("./figures/mAP_per_epoch_test_conv_3.png") plt.show() plt.close() plt.plot(np.squeeze(auc_train), 'b', label='Training AUC') plt.plot(np.squeeze(auc_eval), 'r', label='Validation AUC') plt.ylabel('AUC') plt.xlabel('Epochs') plt.title('The area under the curve\nof the training and validation dataset') plt.legend() plt.xlim([0,epoch-3]) locs, labels = plt.xticks() labels = [int(item)+1 for item in locs] plt.xticks(locs, labels) plt.savefig("./figures/AUC_per_epoch_test_conv_3.png") plt.show() plt.close() plt.plot(np.squeeze(d_prime_train), 'b', label='Training d-prime') plt.plot(np.squeeze(d_prime_eval), 'r', label='Validation d-prime') plt.ylabel('d-prime') plt.xlabel('Epochs') plt.title('The d-prime of the training and validation dataset') plt.legend() plt.xlim([0,epoch-3]) locs, labels = plt.xticks() labels = [int(item)+1 for item in locs] plt.xticks(locs, labels) plt.savefig("./figures/d_prime_per_epoch_test_conv_3.png") plt.show() plt.close() end = datetime.datetime.now() elapsed = end - start print('Elapsed Time:',elapsed) # Running inference loop for checking the prediction result print('\n###################') print('# Example testing #') print('###################') data, sampleratde = sf.read(Path(files_name_eval[0])) wave_array_example_pre = data_transformation.waveform_to_examples(data,sampleratde,display=0) [embedding_batch] = sess_ext.run([output_tensor], feed_dict={input_tensor: wave_array_example_pre}) wave_arrays = pproc.postprocess(embedding_batch) sess = save_sess pred_test = sess.run(prediction_tensor_eval, feed_dict={features_tensor_eval: wave_arrays}) model_vars = tf.compat.v1.trainable_variables() print(slim.model_analyzer.analyze_vars(model_vars, print_info=True)) return pred_test,sess.graph def test(X_test,Y_test,checkpoint_dir,checkpoint_path,label_columns_name,minibatch_size=32,print_cost=True): ''' Test loop is used to evaluate the model performance by restore the best model from the training and validation loop. ''' tf.compat.v1.set_random_seed(41) seed = 43 m_test = X_test.shape[0] n_y = Y_test.shape[1] standard_normal = stats.norm() np.seterr(divide='ignore', invalid='ignore') #Build TensorFlow graph for test loop. with tf.Graph().as_default(), tf.compat.v1.Session() as sess: # Define classification layer for test loop. logits_test = vggish_slim.define_audio_slim(training=False,is_reuse=None) with tf.compat.v1.variable_scope('mymodel'): # Prediction function predict_test = tf.sigmoid(logits_test, name='prediction_test') # Add test ops. with tf.variable_scope('train'): global_step = tf.Variable( 0, name='global_step', trainable=False, collections=[tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, tf.compat.v1.GraphKeys.GLOBAL_STEP]) labels = tf.compat.v1.placeholder( tf.float32, shape=(None, n_y ), name='labels') xent_test = tf.nn.sigmoid_cross_entropy_with_logits( logits=logits_test, labels=labels, name='xent_test') loss_test = tf.reduce_mean(xent_test, name='loss_op_test') tf.compat.v1.summary.scalar('loss_test', loss_test) # Initialize all variables in the model sess.run(tf.compat.v1.global_variables_initializer()) # Restore the model for evaluation saver = tf.compat.v1.train.Saver() saver.restore(sess, checkpoint_path) # Locate all the tensors and ops we need for the test loop. features_tensor_test = sess.graph.get_tensor_by_name( 'audio/audio_input_features:0') labels_tensor = sess.graph.get_tensor_by_name('mymodel/train/labels:0') global_step_tensor = sess.graph.get_tensor_by_name( 'mymodel/train/global_step:0') loss_tensor_test = sess.graph.get_tensor_by_name('mymodel/train/loss_op_test:0') prediction_tensor_test = sess.graph.get_tensor_by_name('mymodel/prediction_test:0') # Define VGGish as feature extraction. graph = tf.Graph() with graph.as_default(): vggish_slim.define_vggish_slim(training=False) sess_ext = tf.compat.v1.Session(graph=graph) # Load variables from pre-trainined checkpoint vggish_slim.load_vggish_slim_checkpoint(sess_ext, checkpoint_dir + "vggish_model.ckpt") input_tensor = graph.get_tensor_by_name('vggish/input_features:0') output_tensor = graph.get_tensor_by_name('vggish/embedding:0') # Load PCA parameters pproc = Postprocessor.Postprocessor(checkpoint_dir + "vggish_pca_params.npz") print('\n###################') print('# Testing loop #') print('###################') avg_loss_test = 0. avg_map_test= 0. avg_auc_test = 0. avg_d_prime_test = 0. step_test = 0 avg_map_class_test = np.zeros_like(Y_test[0]) # Calculate the number of msize of minibatches num_minibatches_test = int(np.ceil(m_test / minibatch_size)) # number of minibatches of size minibatch_size in the test set minibatches_files_test = prepare_data.random_mini_batches_files(X_test, Y_test, minibatch_size, seed, shuffle=False) for minibatch_file_test in minibatches_files_test: # Select a minibatch for loading the data and do data tranformation and pre-processing step (minibatch_X_test, minibatch_Y_test) = prepare_data.get_train_data(minibatch_file_test,sess_ext,input_tensor,output_tensor,pproc,is_train=False,seed=seed,is_augment=False) # Run the test graph num_steps_test ,step_loss_test,pred_tensor_test = sess.run( [global_step_tensor, loss_tensor_test,prediction_tensor_test], feed_dict={features_tensor_test: minibatch_X_test, labels_tensor: minibatch_Y_test}) # Calculate the measurements step_auc_test = metrics.roc_auc_score(np.asarray(minibatch_Y_test), pred_tensor_test, average='micro') step_map_test = metrics.average_precision_score(np.asarray(minibatch_Y_test), pred_tensor_test, average='micro') step_d_prime_test = standard_normal.ppf(step_auc_test) * np.sqrt(2.0) avg_loss_test += step_loss_test / num_minibatches_test avg_map_test += step_map_test / num_minibatches_test avg_auc_test += step_auc_test / num_minibatches_test avg_d_prime_test += step_d_prime_test / num_minibatches_test step_map_class_test = metrics.average_precision_score(np.asarray(minibatch_Y_test), pred_tensor_test, average=None) step_map_class_test[np.isnan(step_map_class_test)] = 0 avg_map_class_test += step_map_class_test / num_minibatches_test # Print step results if((step_test+1) % 10 == 0 or step_test+1==num_minibatches_test or step_test==0): print("Step: {}/{} ,Loss: {:.5f}, mAP: {:.5F}, AUC: {:.5F}, d-prime: {:.5F}" \ .format( step_test+1 ,num_minibatches_test,step_loss_test,step_map_test,step_auc_test,step_d_prime_test)) step_test += 1 # Print summary result if print_cost == True: print('###################') print("------Summary------" ) print('###################') print("Testing : loss %.5f, mAP %.5f, AUC %.5f, d-prime %.5f" % (avg_loss_test,avg_map_test,avg_auc_test,avg_d_prime_test)) #Plot result graphs sum_of_labels_test = Y_test.sum(axis=0) index = avg_map_class_test.argsort()[-10:][::-1] #top 10 classes fig = plt.figure(figsize=(10,5)) ax1 = fig.add_subplot(111) ax1.set_ylim(0,6000) ax1.bar(label_columns_name[index],sum_of_labels_test[index],alpha=0.55,color='C0',label='Audio files') ax1.set_ylabel('Number of audio files') ax1.set_title('The number of audio files and mAP of top 10 classes') ax1.set_xticklabels(labels=label_columns_name[index],rotation=35) ax2 = ax1.twinx() ax2.stem(avg_map_class_test[index],linefmt='r-', markerfmt='ro',basefmt='k-',use_line_collection=True,label='mAP') ax2.set_ylabel('mAP') ax2.set_xlabel('Classes') ax2.set_ylim(bottom=0.,top=1.0) lines, labels = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc=0) plt.tight_layout() plt.savefig("./figures/map_top_10_class_model_aug_conv_3_augmented.png") fig.show() plt.close() np.set_printoptions(precision=5) print('---Top 10 result---') print(label_columns_name[index]) print(sum_of_labels_test[index]) print(avg_map_class_test[index]) index = avg_map_class_test.argsort()[0:10][::-1] #last 10 classes fig = plt.figure(figsize=(10,5)) ax1 = fig.add_subplot(111) ax1.set_ylim(0,70) ax1.bar(label_columns_name[index],sum_of_labels_test[index],alpha=0.55,color='C0',label='Audio files') ax1.set_ylabel('Number of audio files') ax1.set_title('The number of audio files and mAP of last 10 classes') ax1.set_xticklabels(labels=label_columns_name[index],rotation=35) ax2 = ax1.twinx() ax2.stem(avg_map_class_test[index],linefmt='r-', markerfmt='ro',basefmt='k-',use_line_collection=True,label='mAP') ax2.set_ylabel('mAP') ax2.set_xlabel('Classes') ax2.set_ylim(bottom=0.,top=1.0) lines, labels = ax1.get_legend_handles_labels() lines2, labels2 = ax2.get_legend_handles_labels() ax2.legend(lines + lines2, labels + labels2, loc=0) plt.tight_layout() plt.savefig("./figures/map_last_10_class_model_aug_conv_3_augmented.png") fig.show() plt.close() print('---Last 10 result---') print(label_columns_name[index]) print(sum_of_labels_test[index]) print(avg_map_class_test[index]) def inference(file_path,checkpoint_dir,checkpoint_path): ''' Inference loop for prediction the audio file. ''' with tf.Graph().as_default(), tf.compat.v1.Session() as sess: logits_inf = vggish_slim.define_audio_slim(training=False,is_reuse=None) with tf.compat.v1.variable_scope('mymodel'): predict_inf = tf.sigmoid(logits_inf, name='prediction_inf') # Add inference ops. with tf.variable_scope('train'): global_step = tf.Variable( 0, name='global_step', trainable=False, collections=[tf.compat.v1.GraphKeys.GLOBAL_VARIABLES, tf.compat.v1.GraphKeys.GLOBAL_STEP]) # Initialize all variables in the model sess.run(tf.compat.v1.global_variables_initializer()) # Restore the model saver = tf.compat.v1.train.Saver() saver.restore(sess, checkpoint_path) # Locate all the tensors and ops we need for the inference loop. features_tensor_inf = sess.graph.get_tensor_by_name( 'audio/audio_input_features:0') prediction_tensor_inf = sess.graph.get_tensor_by_name('mymodel/prediction_inf:0') graph = tf.Graph() with graph.as_default(): vggish_slim.define_vggish_slim(training=False) sess_ext = tf.compat.v1.Session(graph=graph) vggish_slim.load_vggish_slim_checkpoint(sess_ext, checkpoint_dir + "vggish_model.ckpt") input_tensor = graph.get_tensor_by_name('vggish/input_features:0') output_tensor = graph.get_tensor_by_name('vggish/embedding:0') pproc = Postprocessor.Postprocessor(checkpoint_dir + "vggish_pca_params.npz") print('\n###################') print('# Inference loop #') print('###################') try: data, sampleratde = sf.read(Path(file_path)) wave_array_example_pre = data_transformation.waveform_to_examples(data,sampleratde,display=0) [embedding_batch] = sess_ext.run([output_tensor], feed_dict={input_tensor: wave_array_example_pre}) wave_arrays = pproc.postprocess(embedding_batch) pred_inf_restore = sess.run(prediction_tensor_inf, feed_dict={features_tensor_inf: wave_arrays}) return pred_inf_restore except: print('This program does not support the input file format or file does not found ') # The main program for selecting modes. if __name__ == '__main__': # Arguments parser = argparse.ArgumentParser(description="") subparsers = parser.add_subparsers(dest='mode') parser_train = subparsers.add_parser('train') parser_train.add_argument('--csv_dir', type=str) parser_train.add_argument('--dataset_train_dir', type=str) parser_train.add_argument('--vggish_checkpoint_dir', type=str) parser_train.add_argument('--save_checkpoint_dir', type=str) parser_train.add_argument('--epoch',type=int) parser_train.add_argument('--batch_size',type=int) parser_train.add_argument('--augmentation',action='store_true') parser_test = subparsers.add_parser('test') parser_test.add_argument('--csv_dir', type=str) parser_test.add_argument('--dataset_test_dir', type=str) parser_test.add_argument('--vggish_checkpoint_dir', type=str) parser_test.add_argument('--checkpoint_path', type=str) parser_test.add_argument('--batch_size',type=int) parser_test_augmented = subparsers.add_parser('test_augmented') parser_test_augmented.add_argument('--csv_dir', type=str) parser_test_augmented.add_argument('--dataset_test_dir', type=str) parser_test_augmented.add_argument('--vggish_checkpoint_dir', type=str) parser_test_augmented.add_argument('--checkpoint_path', type=str) parser_test_augmented.add_argument('--batch_size',type=int) parser_inf = subparsers.add_parser('inference') parser_inf.add_argument('--csv_dir', type=str) parser_inf.add_argument('--file_path', type=str) parser_inf.add_argument('--vggish_checkpoint_dir', type=str) parser_inf.add_argument('--checkpoint_path', type=str) args = parser.parse_args() if args.mode == "train": # Select training mode. if args.augmentation == True: print('Training mode - Augmentation') elif args.augmentation == False: print('Training mode - Normal') # Prepare filenames and lables for training and validation. files_name_train,labels_train,files_name_eval,labels_eval = prepare_data.get_filenames_and_labels(args) # Pass the arguments and data to training and validation loop. output_tensor_test,sess_graph = train(files_name_train, labels_train, files_name_eval, labels_eval, args.vggish_checkpoint_dir, args.save_checkpoint_dir,num_epochs=args.epoch,minibatch_size=args.batch_size,print_cost=True,augmentation=args.augmentation) np.set_printoptions(precision=5) for i in range(len(output_tensor_test)): print('Second: ',i) print('Top 10 prob labels: ',output_tensor_test[i].argsort()[-10:][::-1]) print('Raw probability values: ',output_tensor_test[i][output_tensor_test[i].argsort()[-10:][::-1]]) print('-------------------------------------------') elif args.mode == "test": print('Testing mode') # Prepare filesname and lables for test. files_name_test,labels_test,label_columns_name = prepare_data.get_filenames_and_labels_test(args) # Pass the arguments and data to test loop. test(files_name_test, labels_test,args.vggish_checkpoint_dir,args.checkpoint_path,label_columns_name,minibatch_size=args.batch_size,print_cost=True) elif args.mode =="test_augmented": print('Testing mode with augmented data') # Prepare filenames and lables for test with augmented test set. files_name_test,labels_test,label_columns_name = prepare_data.get_filenames_and_labels_test_augment(args) # Pass the arguments and data to test loop. test(files_name_test, labels_test,args.vggish_checkpoint_dir,args.checkpoint_path,label_columns_name,minibatch_size=args.batch_size,print_cost=True) elif args.mode == "inference": print('Inference mode') label_columns = prepare_data.get_labels_indices(args.csv_dir) # Pass the arguments and data to inference loop. output_tensor_inf = inference(args.file_path,args.vggish_checkpoint_dir,args.checkpoint_path) np.set_printoptions(precision=5) try: for i in range(len(output_tensor_inf)): print('Second: ',i) print('Top 10 prob labels name : ',label_columns[output_tensor_inf[i].argsort()[-10:][::-1]]) print('Top 10 prob labels id : ',output_tensor_inf[i].argsort()[-10:][::-1]) print('Raw probability values : ',output_tensor_inf[i][output_tensor_inf[i].argsort()[-10:][::-1]]) print('-------------------------------------------') except: pass else: print("Please complete the input parameter") <file_sep>/gen_augment.py from __future__ import print_function import soundfile as sf import shutil import os import numpy as np from pathlib import Path import pandas as pd import time import random as rd import ffmpeg def map_dataset(df_csv,file_path): ''' Create the mapping between filename and dataset location using content in csv file and dataset directory path. Args: csv_dir : directory path of csv file file_path : directory path of evaluation dataset Return: list of mapping between filename and dataset location. ''' input_path = file_path df_map = pd.DataFrame() df_map['Fname'] = input_path + df_csv["# YTID"].str.slice(0,1).str.upper() + '/' + df_csv["# YTID"].str.slice(1,2).str.upper() + \ '/' + df_csv["# YTID"].str.slice(2,3).str.upper() + '/' + df_csv["# YTID"] + '_' + (df_csv["start_seconds"]*1000).astype(int).astype(str) \ + '_' + (df_csv["end_seconds"]*1000).astype(int).astype(str) + '.flac' return df_map def get_filenames_and_labels_test(csv_dir,dataset_test_dir): ''' Reading the filename from csv file and mapping with the dataset location. Args: csv_dir : directory path of csv file dataset_test_dir : directory path of evaluation dataset Return: list of filenames with location path. ''' csv_dir = csv_dir dataset_test_dir = dataset_test_dir df_test = pd.read_csv(Path(csv_dir + 'eval_segments.csv'),sep=',',skiprows=2, engine='python',quotechar = '"',skipinitialspace = True,) print('Preprocessing for dataset location and labels...') df_test_map = map_dataset(df_test,dataset_test_dir) files_name_test = df_test_map['Fname'].values return files_name_test def create_folder(fd): if not os.path.exists(fd): os.makedirs(fd) def get_augmentation_data(files_name_test): ''' Generate augmented test set using 10 fixed FFmpeg pipeline to simulate 10 sources which using to record audio files. Detail of each fileter please see Appendix B. Args: files_name_test : list of test files to perform the data augmentation. Output: augmented test set. ''' output_aug_dir = '/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_augmented_10_pipelines/' #create folder if it does not exits create_folder(output_aug_dir) #clear the folder it is already exites shutil.rmtree('/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_augmented_10_pipelines') create_folder(output_aug_dir) seed=1 i=0 toteal_file = len(files_name_test) for file_name in files_name_test: # random pipeline for each audio file rd.seed(seed) augment_rd = rd.randint(0,9) # Pipeline 1 if(augment_rd==0): file_name_aug = output_aug_dir + file_name.split('/')[-1] try: ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=2) .filter(filter_name='afftdn') .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.8,ratio=20,attack=20,release=200) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=50,decays=1) .output(file_name_aug,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 2 if(augment_rd==1): file_name_aug = output_aug_dir + file_name.split('/')[-1] try: ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=4) .filter(filter_name='afftdn') .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.7,ratio=15,attack=15,release=100) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=100,decays=1) .output(file_name_aug,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 3 if(augment_rd==2): file_name_aug = output_aug_dir + file_name.split('/')[-1] try: ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=6) .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.5,ratio=10,attack=10,release=50) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=200,decays=1) .output(file_name_aug,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 4 elif(augment_rd==3): file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.aac') try: ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=2) .filter(filter_name='afftdn') .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.8,ratio=20,attack=20,release=200) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=50,decays=1) .output(file_name_aug,acodec='aac') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.aac','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 5 elif(augment_rd==4): file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.aac') try: ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=4) .filter(filter_name='afftdn') .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.7,ratio=15,attack=15,release=100) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=100,decays=1) .output(file_name_aug,acodec='aac') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.aac','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 6 elif(augment_rd==5): file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.aac') try: ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=6) .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.5,ratio=10,attack=10,release=50) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=200,decays=1) .output(file_name_aug,acodec='aac') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.aac','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 7 elif(augment_rd==6): try: file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.mp3') ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=2) .filter(filter_name='afftdn') .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.8,ratio=20,attack=20,release=200) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=50,decays=1) .output(file_name_aug,acodec='mp3') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.mp3','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 8 elif(augment_rd==7): try: file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.mp3') ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=4) .filter(filter_name='afftdn') .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.7,ratio=15,attack=15,release=100) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=100,decays=1) .output(file_name_aug,acodec='mp3') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.mp3','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 9 elif(augment_rd==8): try: file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.mp3') ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=6) .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.5,ratio=10,attack=10,release=50) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=200,decays=1) .output(file_name_aug,acodec='mp3') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.mp3','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass # Pipeline 10 elif(augment_rd==9): try: file_name_aug = output_aug_dir + file_name.split('/')[-1].replace('000.flac','000.mp3') ffmpeg_proc = (ffmpeg .input(file_name) .filter(filter_name='volume',volume=3) .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=0.8,ratio=20,attack=20,release=200) .filter(filter_name='aecho',in_gain=1,out_gain=0.8,delays=200,decays=1) .output(file_name_aug,acodec='mp3') .overwrite_output() .run(quiet=True) ) file_name_aug_flac = file_name_aug.replace('.mp3','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) except: pass print("Files: {}/{} ".format(i+1,toteal_file)) seed= seed+1 i=i+1 if __name__ == '__main__': files_name_test = get_filenames_and_labels_test('/export/home/2368985c/MSc_Project_Sound_Augmentation/csv_file/','/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_eval_tmp/') print('Generating augmented test set') get_augmentation_data(files_name_test) <file_sep>/README.md # Exploring data augmentation for sound classification This project aims to study the opportunity to apply data augmentation in sound classification then identify difficulties and limitations of techniques ## Usage - [main.py](https://github.com/petchc/SoundAugmentation/blob/master/main.py) : Main function to run the entire experiment. - [prepare_data.py](https://github.com/petchc/SoundAugmentation/blob/master/prepare_data.py) : Create list of filenames and labels, Generate minibatches, Reading the audio file, apply feature extraction and perform data augmentation. - [data_transformation.py](https://github.com/petchc/SoundAugmentation/blob/master/data_transformation.py) : Transform the raw audio file to into input examples. - [vggish_slim.py](https://github.com/petchc/SoundAugmentation/blob/master/vggish_slim.py) : Define VGGish architecture, classification and logits layer, and process the VGGish checkpoint loading. - [vggish_params.py](https://github.com/petchc/SoundAugmentation/blob/master/vggish_params.py) : Program and VGGish parameters. - [Postprocessor.py](https://github.com/petchc/SoundAugmentation/blob/master/Postprocessor.py) : Perform PCA process. - [gen_augment.py](https://github.com/petchc/SoundAugmentation/blob/master/gen_augment.py) : Generate augmented test set by 10 fixed pipelines. ## Tools - [TensorFlow: VGGish](https://github.com/tensorflow/models/tree/master/research/audioset) - [Google AudioSet](https://research.google.com/audioset/index.html) - [VGGish model checkpoint](https://storage.googleapis.com/audioset/vggish_model.ckpt) - [Embedding PCA parameters](https://storage.googleapis.com/audioset/vggish_pca_params.npz) ## Datasets - [Balanced train segments](https://www.dropbox.com/sh/r547ggvdivljt32/AACQjpGsEpquDZqSlgCQOUc-a?dl=0&preview=audio.zip) - [Evaluation segments](https://www.dropbox.com/sh/r547ggvdivljt32/AACQjpGsEpquDZqSlgCQOUc-a?dl=0&preview=eval_segments.zip) - [Augmented test set](https://drive.google.com/file/d/1-MOR4V1H3C0rXdyn0KYM2Or2Su5ghof2/view?usp=sharing) ## CSV files - [Balanced train segments](http://storage.googleapis.com/us_audioset/youtube_corpus/v1/csv/balanced_train_segments.csv) - [Evaluation segments](http://storage.googleapis.com/us_audioset/youtube_corpus/v1/csv/eval_segments.csv) - [Class labels indices](http://storage.googleapis.com/us_audioset/youtube_corpus/v1/csv/class_labels_indices.csv) ## Training command This is example of training command. You can change the directory to your own directory path. - Normal mode. ```python3 main.py train --csv_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/csv_file/ --dataset_train_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_train_tmp/ --vggish_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/vggish_ckpt/ --save_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/tmp/ --epoch=500 --batch_size=64``` - Augmentation mode. ```python3 main.py train --csv_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/csv_file/ --dataset_train_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_train_tmp/ --vggish_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/vggish_ckpt/ --save_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/tmp/ --epoch=500 --batch_size=64 --augmentation``` ## Test command This is example of training command. You can change the directory to your own directory path and you need to specify the model checkpoint to evaluate. - Test with original test set. ```python3 main.py test --csv_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/csv_file/ --dataset_test_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_eval_tmp/ --vggish_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/vggish_ckpt/ --checkpoint_path=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/tmp/model_base_conv_3_epoch_18.ckpt --batch_size=64``` - Test with augmented test set. ```python3 main.py test_augmented --csv_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/csv_file/ --dataset_test_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_augmented_10_pipelines/ --vggish_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/vggish_ckpt/ --checkpoint_path=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/tmp/model_aug_conv_3_epoch_18.ckpt --batch_size=64``` ## Generate augmented test set ```python3 main.py gen_augment.py``` ## Inference command This is example of inference command for prediction the labels of audio file. ```python3 main.py inference --csv_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/csv_file/ --file_path=/export/home/2368985c/MSc_Project_Sound_Augmentation/audio_eval_tmp/-/0/P/-0p7hKXZ1ww_30000_40000.flac --vggish_checkpoint_dir=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/vggish_ckpt/ --checkpoint_path=/export/home/2368985c/MSc_Project_Sound_Augmentation/SoundAugmentation/tmp/model_aug_conv_3_epoch_18.ckpt``` PS. Below command use to alter folder name to upper case (Linux command) ```find path/to/dir -type d | awk -F"/" '$NF != toupper($NF) {l = n = $0; sub($NF "$", toupper($NF), n); print "mv " l " " n;}' | tac | sh``` <file_sep>/prepare_data.py import pandas as pd import argparse import numpy as np import os import math import soundfile as sf from pathlib import Path import data_transformation import random as rd from random import shuffle import ffmpeg def split_and_label(rows_labels, label_mapping ,n_classes): # retrieves a list of all the relevant classes and split it into individual label. row_labels_list = [] for row in rows_labels: row_labels = row.split(',') labels_array = np.zeros((n_classes)) for label in row_labels: index = label_mapping[label] labels_array[index] = 1 row_labels_list.append(labels_array) return row_labels_list def map_dataset(df_csv,file_path,label_column_value,num_classes): # map filename to local path and encode the labels to one-hot encoding for the baseline model n_classes = num_classes input_path = file_path df_map = pd.DataFrame() df_map['Fname'] = input_path + df_csv["# YTID"].str.slice(0,1).str.upper() + '/' + df_csv["# YTID"].str.slice(1,2).str.upper() + \ '/' + df_csv["# YTID"].str.slice(2,3).str.upper() + '/' + df_csv["# YTID"] + '_' + (df_csv["start_seconds"]*1000).astype(int).astype(str) \ + '_' + (df_csv["end_seconds"]*1000).astype(int).astype(str) + '.flac' df_map["Label"] = df_csv.positive_labels label_columns = label_column_value label_mapping = dict((label, index) for index, label in enumerate(label_columns)) for col in label_columns: df_map[col] = 0 df_map[label_columns] = split_and_label(df_map['Label'], label_mapping ,n_classes) return df_map def map_dataset_augment(df_csv,file_path,label_column_value,num_classes): # map filename to local path and encode the labels to one-hot encoding for data augmentation model n_classes = num_classes input_path = file_path df_map = pd.DataFrame() df_map['Fname'] = input_path + df_csv["# YTID"] + '_' + (df_csv["start_seconds"]*1000).astype(int).astype(str) \ + '_' + (df_csv["end_seconds"]*1000).astype(int).astype(str) + '.flac' df_map["Label"] = df_csv.positive_labels label_columns = label_column_value label_mapping = dict((label, index) for index, label in enumerate(label_columns)) for col in label_columns: df_map[col] = 0 df_map[label_columns] = split_and_label(df_map['Label'], label_mapping ,n_classes) return df_map def get_labels_indices(csv_dir): # get all classes name column_df = pd.read_csv(Path(csv_dir + 'class_labels_indices.csv'),usecols=["display_name"]) label_columns_name = column_df.display_name.values print('Preprocessing for dataset location and labels...') return label_columns_name def get_filenames_and_labels_test(args): # get filenames with file location and the associated labels for test with original test set num_classes = 527 csv_dir = args.csv_dir dataset_test_dir = args.dataset_test_dir df_test = pd.read_csv(Path(csv_dir + 'eval_segments.csv'),sep=',',skiprows=2, engine='python',quotechar = '"',skipinitialspace = True,) column_df = pd.read_csv(Path(csv_dir + 'class_labels_indices.csv'),usecols=["mid","display_name"]) label_columns = column_df.mid.values label_columns_name = column_df.display_name.values print('Preprocessing for dataset location and labels...') df_test_map = map_dataset(df_test,dataset_test_dir,column_df.mid.values,num_classes) files_name_test = df_test_map['Fname'].values labels_test = df_test_map.loc[:,label_columns].values return files_name_test,labels_test,label_columns_name def get_filenames_and_labels_test_augment(args): # get filenames with file location and the associated labels for test with augmented test set num_classes = 527 csv_dir = args.csv_dir dataset_test_dir = args.dataset_test_dir df_test = pd.read_csv(Path(csv_dir + 'eval_segments.csv'),sep=',',skiprows=2, engine='python',quotechar = '"',skipinitialspace = True,) column_df = pd.read_csv(Path(csv_dir + 'class_labels_indices.csv'),usecols=["mid","display_name"]) label_columns = column_df.mid.values label_columns_name = column_df.display_name.values print('Preprocessing for dataset location and labels...') df_test_map = map_dataset_augment(df_test,dataset_test_dir,column_df.mid.values,num_classes) files_name_test = df_test_map['Fname'].values labels_test = df_test_map.loc[:,label_columns].values return files_name_test,labels_test,label_columns_name def get_filenames_and_labels(args): # get filenames with file location and the associated labels for training the model num_classes = 527 csv_dir = args.csv_dir dataset_train_dir = args.dataset_train_dir df_train = pd.read_csv(Path(csv_dir + 'balanced_train_segments.csv'),sep=',',skiprows=2, engine='python',quotechar = '"',skipinitialspace = True,) column_df = pd.read_csv(Path(csv_dir + 'class_labels_indices.csv'),usecols=["mid"]) label_columns = column_df.mid.values print('Preprocessing for dataset location and labels...') df_train_map = map_dataset(df_train,dataset_train_dir,column_df.mid.values,num_classes) files_name_train_all = df_train_map['Fname'].values labels_train_all = df_train_map.loc[:,label_columns].values np.random.seed(1) permutation = list(np.random.permutation(files_name_train_all.shape[0])) shuffled_X = files_name_train_all[permutation] shuffled_Y = labels_train_all[permutation] files_name_train = shuffled_X[0:20000] labels_train = shuffled_Y[0:20000] files_name_eval = shuffled_X[20000:] labels_eval = shuffled_Y[20000:] return files_name_train,labels_train,files_name_eval,labels_eval def random_mini_batches_files(X, Y, mini_batch_size = 64, seed = 0 , shuffle=True): ''' Creates a list of random minibatches from (X, Y) It will product list of filename as minibatch Args: X : list of filenames Y : ground true label mini_batch_size : size of the mini-batches seed : random seed to generate the different list of filename in each epoch. shuffle : shuffle the data or not Return: mini_batches : list of synchronous (mini_batch_X, mini_batch_Y) ''' #ref https://www.kaggle.com/darienbm/wine-classification-using-tensorflow m = X.shape[0] mini_batches = [] if(shuffle==True): # Step 1: Shuffle (X, Y) np.random.seed(seed) permutation = list(np.random.permutation(m)) shuffled_X = X[permutation] shuffled_Y = Y[permutation, :] elif(shuffle==False): shuffled_X = X shuffled_Y = Y # Step 2: Partition (shuffled_X, shuffled_Y). Minus the end case. # number of mini batches of size mini_batch_size in your partitioning -> step size num_complete_minibatches = math.floor(m/mini_batch_size) for k in range(0, num_complete_minibatches): mini_batch_X = shuffled_X[k*mini_batch_size : (k+1)*mini_batch_size] mini_batch_Y = shuffled_Y[k*mini_batch_size : (k+1)*mini_batch_size, :] mini_batch = (mini_batch_X, mini_batch_Y) mini_batches.append(mini_batch) # Handling the end case (last mini-batch < mini_batch_size) if m % mini_batch_size != 0: mini_batch_X = shuffled_X[num_complete_minibatches*mini_batch_size : m] mini_batch_Y = shuffled_Y[num_complete_minibatches*mini_batch_size : m, :] mini_batch = (mini_batch_X, mini_batch_Y) mini_batches.append(mini_batch) return mini_batches def data_augmentation(file_name,seed): ''' Applying 7 random parameters from 5 filters and 3 type of audios to generate the artificial audio files in order to training the augmentation model. ''' input_file = file_name output_aug_dir = './audio_aug/' # random parameters rd.seed(seed) volume_rd = rd.randint(1, 10) threshold_rd = rd.uniform(0.5,0.8) ratio_rd = rd.randint(10, 20) attack_rd = rd.randint(1, 20) release_rd = rd.randint(10, 250) decays_rd =rd.uniform(0.5,1) format_type = rd.randint(0,2) # FLAC format if(format_type==0): file_name_aug = output_aug_dir + input_file.split('/')[-1] acodec_rd='flac' # AAC format elif(format_type==1): file_name_aug = output_aug_dir + input_file.split('/')[-1].replace('000.flac','000.aac') acodec_rd='aac' # MP3 format elif(format_type==2): file_name_aug = output_aug_dir + input_file.split('/')[-1].replace('000.flac','000.mp3') acodec_rd='mp3' # augmentation pipeline ffmpeg_proc = (ffmpeg .input(input_file) .filter(filter_name='volume',volume=volume_rd) .filter(filter_name='firequalizer',gain_entry='entry(125,0);entry(250,-5);entry(1000,-2.5);entry(6000,3);entry(7500,0)') .filter(filter_name='acompressor',threshold=threshold_rd,ratio=ratio_rd,attack=attack_rd,release=release_rd) .filter(filter_name='silenceremove',stop_periods=-1,stop_duration=2,stop_threshold='-50dB') .filter(filter_name='aecho',in_gain=1,out_gain=0.9,delays=500,decays=decays_rd) .output(file_name_aug,acodec=acodec_rd) .overwrite_output() .run(quiet=True) ) # convert file types from AAC to FLAC due to SoundFile library does not support to read AAC format. if(format_type==1): file_name_aug_flac = file_name_aug.replace('.aac','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) file_name_aug = file_name_aug_flac # convert file types from MP3 to FLAC due to SoundFile library does not support to read MP3 format. if(format_type==2): file_name_aug_flac = file_name_aug.replace('.mp3','.flac') ffmpeg_proc = (ffmpeg .input(file_name_aug) .output(file_name_aug_flac,acodec='flac') .overwrite_output() .run(quiet=True) ) file_name_aug = file_name_aug_flac return file_name_aug def get_train_data(minibatch_file,sess_ext,input_tensor,output_tensor,pproc,is_train,seed=0,is_augment=False): ''' Read the list of file names from minibatch and perform preprocessing then return as list of example frame and associated labels ''' files_name,labels_name = minibatch_file all_examples=[] all_labels=[] no_file=0 for file_name in files_name: try: data, sampleratde = sf.read(Path(file_name)) wave_arrays_pre = data_transformation.waveform_to_examples(data,sampleratde,0) [embedding_batch] = sess_ext.run([output_tensor], feed_dict={input_tensor: wave_arrays_pre}) wave_arrays = pproc.postprocess(embedding_batch) if(wave_arrays.shape[0]!=0): wave_labels = np.array([labels_name[no_file]] * wave_arrays.shape[0]) all_examples.append(wave_arrays) all_labels.append(wave_labels) ''' This is a data augmentation function to generate artificial audio file for each file. ''' if(is_augment == True): file_name_aug = data_augmentation(file_name,seed) data, sampleratde = sf.read(Path(file_name_aug)) wave_arrays_pre = data_transformation.waveform_to_examples(data,sampleratde,0) [embedding_batch] = sess_ext.run([output_tensor], feed_dict={input_tensor: wave_arrays_pre}) wave_arrays = pproc.postprocess(embedding_batch) if(wave_arrays.shape[0]!=0): wave_labels = np.array([labels_name[no_file]] * wave_arrays.shape[0]) all_examples.append(wave_arrays) all_labels.append(wave_labels) seed = seed+1 except: pass no_file = no_file+1 all_examples = np.concatenate(all_examples) all_labels = np.concatenate(all_labels) if(is_train==True): labeled_examples = list(zip(all_examples, all_labels)) shuffle(labeled_examples) #Separate and return the features and labels. features = [example for (example, _) in labeled_examples] labels = [label for (_, label) in labeled_examples] return (features, labels) elif(is_train==False): return (all_examples, all_labels) def create_folder(fd): if not os.path.exists(fd): os.makedirs(fd) def get_filename(path): path = os.path.realpath(path) na_ext = path.split('/')[-1] na = os.path.splitext(na_ext)[0] return na
deeded4a747f17d301f4e66a627f3f1cae9dcb68
[ "Markdown", "Python" ]
4
Python
petchc/SoundAugmentation
78a12d6991676e0a89baedf5afbb87ce74c8ae66
ab242a04f045abdf806a1e55b840cbe4cba66258
refs/heads/master
<file_sep> $(document).ready(function(){ $.ajax({ type: "GET", url: "text", cache: false }).done(function(pagina){ $("#Contenedor").text(pagina) }); $("#boton").click(function(){ $.ajax({ type: "GET", url: "text2", cache: false }).done(function(pagina){ $("#Contenedor").text(pagina) }); }); $("#boton2").click(function(){ $.ajax({ type: "GET", url: "text3", cache: false }).done(function(pagina){ $("#Contenedor").html(pagina) }); }); });
71a3bcdeb27ffbe063eafe71358dd67f8bb500b4
[ "JavaScript" ]
1
JavaScript
dpaz/X-NAV-JQ-Ajax
b4119fe6ac6ef4d485c8675dbb213a485ae5f8ec
62eaaae26c8fce0b816e824924177ceb5fcffb2f
refs/heads/master
<repo_name>ifonefox/IRCBot<file_sep>/README.md IRCBot ====== An all-in-one "robot" for irc channels.<file_sep>/src/tests/TwitterTests.java package tests; import static org.junit.Assert.*; import bot.StatusUpdate; import org.junit.Test; public class TwitterTests { @Test public void test() { assertEquals(StatusUpdate.auth(), 0); assertEquals(StatusUpdate.update("test"), 0); assertEquals(StatusUpdate.contactMe("Test"), 0); } } <file_sep>/src/bot/StatusUpdate.java package bot; import twitter4j.DirectMessage; import twitter4j.Status; import twitter4j.Twitter; import twitter4j.TwitterException; import twitter4j.TwitterFactory; import twitter4j.auth.AccessToken; import twitter4j.auth.RequestToken; import java.io.BufferedReader; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.Properties; public class StatusUpdate { private static String consumerKey="REMOVED"; private static String consumerSecret="REMOVED"; public static int auth(){ File file = new File("twitterbot.properties"); Properties prop = new Properties(); InputStream is = null; OutputStream os = null; try{ if (file.exists()){ is = new FileInputStream(file); prop.load(is); } if(null !=prop.getProperty("oauth.consumerKey") && null != prop.getProperty("oauth.consumerSecret")){ prop.setProperty("oauth.consumerKey", consumerKey); prop.setProperty("oauth.consumerSecret", consumerSecret); os = new FileOutputStream("twitterbot.properties"); prop.store(os, "twitterbot.properties"); os.close(); } } catch(IOException e){ e.printStackTrace(); return -1; } finally { if (is !=null){ try{ is.close(); } catch (IOException e){ } } if (os !=null){ try{ os.close(); } catch (IOException e){ } } } try{ Twitter twitter = new TwitterFactory().getInstance(); twitter.setOAuthConsumer(consumerKey, consumerSecret); RequestToken requestToken = twitter.getOAuthRequestToken(); System.out.println("RT: "+requestToken.getToken()); System.out.println("RTS: "+requestToken.getTokenSecret()); AccessToken accessToken = null; //check if accessToken is saved or not. if it isn't... BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); while (null == accessToken){ System.out.println("Open URL:\n"+requestToken.getAuthenticationURL()); try { Runtime.getRuntime().exec("open "+requestToken.getAuthenticationURL()); } catch (IOException e) { System.out.println("Error opening url. Do it yourself."); } System.out.print("PIN: "); String pin = br.readLine(); try{ if (pin.length() > 0){ accessToken = twitter.getOAuthAccessToken(requestToken, pin); } else { accessToken = twitter.getOAuthAccessToken(requestToken); } } catch (TwitterException e){ if (401 == e.getStatusCode()) System.out.println("Access token error"); else e.printStackTrace(); } } System.out.println("AT: "+accessToken.getToken()); System.out.println("ATS: "+accessToken.getTokenSecret()); System.out.println("User: "+accessToken.getScreenName()); System.out.println("UserID: "+accessToken.getUserId()); try{ prop.setProperty("oauth.accessToken", accessToken.getToken()); prop.setProperty("oauth.accessTokenSecret", accessToken.getTokenSecret()); prop.setProperty("oauth.userID", Long.toString(accessToken.getUserId())); os = new FileOutputStream(file); prop.store(os, "twitterbot.properties"); os.close(); //store accessToken FileOutputStream fos = new FileOutputStream(new File("accessToken.object")); ObjectOutputStream oos = new ObjectOutputStream(fos); oos.writeObject(twitter); oos.close(); fos.close(); } catch (IOException e){ e.printStackTrace(); return -1; } finally{ if (is !=null){ try{ is.close(); } catch (IOException e){ } } } System.out.println("Authenticated to "+file.getAbsolutePath()); return 0; } catch (TwitterException e){ e.printStackTrace(); System.out.println("Failed to get accessToken: " + e.getMessage()); return -1; } catch (IOException e){ e.printStackTrace(); System.out.println("Input failure"); return -1; } } public static String update(String statusText){ try { Twitter twitter = new TwitterFactory().getInstance(); try{ File file = new File("twitterbot.properties"); Properties prop = new Properties(); InputStream is = null; if(!file.exists()){ System.out.println("Authenticate first"); return ""; } is = new FileInputStream(file); prop.load(is); String token = prop.getProperty("oauth.accessToken"); String tokenSecret = prop.getProperty("oauth.accessTokenSecret"); AccessToken accessToken = new AccessToken (token, tokenSecret); System.out.println(accessToken.toString()); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(accessToken); System.out.println("HERE"); System.out.println(twitter.getScreenName()); } catch (IllegalStateException e){ if (!twitter.getAuthorization().isEnabled()){ System.out.println("OAuth not set up"); return ""; } } Status status = twitter.updateStatus(statusText); System.out.println("Status updated"); return "https://twitter.com/IRCTweeterBot/status/"+status.getId(); } catch (TwitterException e){ e.printStackTrace(); System.out.println("Failed to get timeline: "+e.getMessage()); return ""; } catch (IOException e){ e.printStackTrace(); System.out.println("Input error"); return ""; } } public static int contactMe(String messageText){ try { Twitter twitter = new TwitterFactory().getInstance(); try{ File file = new File("twitterbot.properties"); Properties prop = new Properties(); InputStream is = null; if(!file.exists()){ System.out.println("Authenticate first"); return -1; } is = new FileInputStream(file); prop.load(is); String token = prop.getProperty("oauth.accessToken"); String tokenSecret = prop.getProperty("oauth.accessTokenSecret"); AccessToken accessToken = new AccessToken (token, tokenSecret); System.out.println(accessToken.toString()); twitter.setOAuthConsumer(consumerKey, consumerSecret); twitter.setOAuthAccessToken(accessToken); System.out.println("HERE"); System.out.println(twitter.getScreenName()); } catch (IllegalStateException e){ if (!twitter.getAuthorization().isEnabled()){ System.out.println("OAuth not set up"); return -1; } } @SuppressWarnings("unused") DirectMessage message = twitter.sendDirectMessage("iHum4n", messageText); System.out.println("Status updated"); return 0; } catch (TwitterException e){ e.printStackTrace(); System.out.println("Failed to get timeline: "+e.getMessage()); return -1; } catch (IOException e){ e.printStackTrace(); System.out.println("Input error"); return -1; } } }
f972b0171fd976e68e2b051d8cc60a28d14a29ab
[ "Markdown", "Java" ]
3
Markdown
ifonefox/IRCBot
00363a34f05f02b0d4d0e7486474747aa6999e5b
7f26ec3bcb89ff99df7fa223ecc06cfbbcc2c351
refs/heads/master
<file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetBackgroundAuto(false); ofSetVerticalSync(true); ofEnableAlphaBlending(); ofSetFrameRate(60); ofBackground(0, 0, 0); myRectangle.startPos.set(10, 400); myRectangle.endPos.set(1000, 200); myRectangle.shaper = 2.0; pct = 0.0; myRectangle.interpolateByPct(pct); } //-------------------------------------------------------------- void testApp::update(){ pct += 0.01f; if (pct > 1) { pct = 0; } myRectangle.interpolateByPct(pct); } //-------------------------------------------------------------- void testApp::draw(){ fadeToBlack(); myRectangle.draw(); } //-------------------------------------------------------------- void testApp::fadeToBlack() { ofSetRectMode(OF_RECTMODE_CORNER); ofSetColor(0, 0, 0, 20); ofRect(0, 0, ofGetWidth(), ofGetHeight()); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetVerticalSync(true); ofSetFrameRate(60); ofBackground(0, 0, 0); ofEnableBlendMode(OF_BLENDMODE_ADD); pimg.loadImage("particle32.png"); } //-------------------------------------------------------------- void testApp::update(){ for (int i = 0; i < particles.size(); i++){ particles[i].resetForce(); particles[i].addDampingForce(); particles[i].update(); } } //-------------------------------------------------------------- void testApp::draw(){ ofSetColor(127, 127, 127, 200); ofNoFill(); ofEnableSmoothing(); ofBeginShape(); for (int i = 0; i < particles.size(); i++){ ofCurveVertex(particles[i].pos.x, particles[i].pos.y); } ofEndShape(); ofDisableSmoothing(); ofSetColor(255, 255, 255); ofFill(); for (int i = 0; i < particles.size(); i++){ pimg.draw(particles[i].pos.x - 16, particles[i].pos.y - 16); } } //-------------------------------------------------------------- void testApp::keyPressed (int key){ if (key == 'f') { ofToggleFullscreen(); } } //-------------------------------------------------------------- void testApp::keyReleased (int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ prevMouseX = x; prevMouseY = y; } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ //1フレーム前の座標から、現在のマウス座標との差分を算出 float dx = x - prevMouseX; float dy = y - prevMouseY; //新規にパーティクルを作成、計算したベクトルを付与 particle myParticle; myParticle.setInitialCondition(x,y, dx*0.5,dy*0.5); //配列に追加 particles.push_back(myParticle); //現在のマウス座標を記録 prevMouseX = x; prevMouseY = y; } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ particles.clear(); } //-------------------------------------------------------------- void testApp::mouseReleased(){ } <file_sep>/* s_main.h PdLib v0.3 Copyright 2010 <NAME>. All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY BRYAN SUMMERSETT ``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 BRYAN SUMMERSETT 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Bryan Summersett. */ //#import "AudioOutput.h" int sys_main(const char *libdir, const char *externs, const char *openfiles, const char *searchpath, int soundRate, int blockSize, int nOutChannels, int nInChannels/*, AudioCallbackFn callback*/); int openit(const char *dirname, const char *filename); void sys_send_msg(const char *msg); void sys_exit(void); // global lock for PD void sys_lock(void); void sys_unlock(void); extern int sys_hasstarted; <file_sep>#include "testApp.h" float bg, fg; //-------------------------------------------------------------- void testApp::setup(){ ofBackground(255, 255, 255); ofSetCircleResolution(128); ofSetFrameRate(60); ofSetVerticalSync(true); } //-------------------------------------------------------------- void testApp::update(){ bg = sin(ofGetElapsedTimef() * 2.0) * 127 + 127; fg = sin(ofGetElapsedTimef() * 3.0) * 127 + 127; } //-------------------------------------------------------------- void testApp::draw(){ ofBackground(bg, bg, bg); ofSetColor(fg, fg, fg); ofTranslate(ofGetWidth()/2, ofGetHeight()/2); ofCircle(0, 0, 300); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<file_sep>#include "testApp.h" void testApp::setup(){ ofSetFrameRate(60); ofSetVerticalSync(true); ofSetCircleResolution(32); ofEnableBlendMode(OF_BLENDMODE_ADD); ofBackground(0, 0, 0); mySound.loadSound("sounds/drumLoop.aif"); mySound.setLoop(true); nBandsToGet = 1024; mySound.play(); } void testApp::update(){ ofSoundUpdate(); fft = ofSoundGetSpectrum(nBandsToGet); } void testApp::draw(){ float width = float(ofGetWidth()) / float(nBandsToGet) / 2.0f; for (int i = 0;i < nBandsToGet; i++){ int b = float(255) / float(nBandsToGet) * i; int g = 31; int r = 255 - b; ofSetColor(r, g, b); ofCircle(ofGetWidth()/2 + width * i, ofGetHeight()/2, fft[i] * 800); ofCircle(ofGetWidth()/2 - width * i, ofGetHeight()/2, fft[i] * 800); } } <file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetVerticalSync(true); ofSetFrameRate(60); ofSetBackgroundAuto(false); //ofEnableAlphaBlending(); ofBackground(0, 0, 0); pimg.loadImage("particle32.png"); } //-------------------------------------------------------------- void testApp::update(){ for (int i = 0; i < particles.size(); i++){ particles[i].resetForce(); particles[i].addForce(0.0, 0.28); particles[i].addDampingForce(); particles[i].bounceOffWalls(); particles[i].update(); } } //-------------------------------------------------------------- void testApp::draw(){ ofEnableBlendMode(OF_BLENDMODE_ALPHA); ofSetColor(0, 0, 0, 31); ofRect(0, 0, ofGetWidth(), ofGetHeight()); ofEnableBlendMode(OF_BLENDMODE_ADD); ofSetColor(255, 255, 255); for (int i = 0; i < particles.size(); i++){ pimg.draw(particles[i].pos.x-16, particles[i].pos.y-16); } } //-------------------------------------------------------------- void testApp::keyPressed (int key){ } //-------------------------------------------------------------- void testApp::keyReleased (int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ //1フレーム前の座標から、現在のマウス座標との差分を算出 float dx = x - preMouse.x; float dy = y - preMouse.y; //新規にパーティクルを作成、計算したベクトルを付与 particle myParticle; myParticle.setInitialCondition(x,y, dx*0.5,dy*0.5); //配列に追加 particles.push_back(myParticle); //現在のマウス座標を記録 preMouse.x = x; preMouse.y = y; } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ particles.clear(); preMouse.x = x; preMouse.y = y; } //-------------------------------------------------------------- void testApp::mouseReleased(){ } <file_sep>/* SuperCollider real time audio synthesis system Copyright (c) 2002 <NAME>. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SC_Unit_ #define _SC_Unit_ #include "SC_Types.h" typedef void (*UnitCtorFunc)(struct Unit* inUnit); typedef void (*UnitDtorFunc)(struct Unit* inUnit); typedef void (*UnitCalcFunc)(struct Unit *inThing, int inNumSamples); struct SC_Unit_Extensions { float * todo; }; struct Unit { struct World *mWorld; struct UnitDef *mUnitDef; struct Graph *mParent; uint16 mNumInputs, mNumOutputs; int16 mCalcRate; int16 mSpecialIndex; // used by unary and binary ops int16 mParentIndex; int16 mDone; struct Wire **mInput, **mOutput; struct Rate *mRate; SC_Unit_Extensions* mExtensions; //future proofing and backwards compatibility; used to be SC_Dimension struct pointer float **mInBuf, **mOutBuf; UnitCalcFunc mCalcFunc; int mBufLength; }; typedef struct Unit Unit; enum { kUnitDef_CantAliasInputsToOutputs = 1 }; // easy macros, the unit variable must be named 'unit'. #ifndef SC_WIN32 // These return float* pointers to input and output buffers. #define IN(index) (unit->mInBuf[index]) #define OUT(index) (unit->mOutBuf[index]) // These return a float value. Used for control rate inputs and outputs. #define IN0(index) (IN(index)[0]) #define OUT0(index) (OUT(index)[0]) #else // Win32 headers (included by C std library headers) define IN and OUT macros // for their own purposes. To avoid problems we don't define IN and OUT here // but define SC_IN and SC_OUT instead. Source files that use IN and OUT need // to include definitions of IN, and OUT referencing SC_IN and SC_OUT after // all headers have been included. #define SC_IN(index) (unit->mInBuf[index]) #define SC_OUT(index) (unit->mOutBuf[index]) #define IN0(index) (SC_IN(index)[0]) #define OUT0(index) (SC_OUT(index)[0]) #endif // get the rate of the input. #define INRATE(index) (unit->mInput[index]->mCalcRate) // get the blocksize of the input #define INBUFLENGTH(index) (unit->mInput[index]->mFromUnit->mBufLength) // set the calculation function #define SETCALC(func) (unit->mCalcFunc = (UnitCalcFunc)&func) // calculate a slope for control rate interpolation to audio rate. #define CALCSLOPE(next,prev) ((next - prev) * sc_typeof_cast(next)unit->mRate->mSlopeFactor) // get useful values #define SAMPLERATE (unit->mRate->mSampleRate) #define SAMPLEDUR (unit->mRate->mSampleDur) #define BUFLENGTH (unit->mBufLength) #define BUFRATE (unit->mRate->mBufRate) #define BUFDUR (unit->mRate->mBufDuration) #define FULLRATE (unit->mWorld->mFullRate.mSampleRate) #define FULLBUFLENGTH (unit->mWorld->mFullRate.mBufLength) // macros to grab a Buffer reference from the buffer indicated by the UGen's FIRST input #define GET_BUF \ float fbufnum = ZIN0(0); \ if (fbufnum < 0.f) { fbufnum = 0.f; } \ if (fbufnum != unit->m_fbufnum) { \ uint32 bufnum = (int)fbufnum; \ World *world = unit->mWorld; \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph *parent = unit->mParent; \ if(localBufNum <= parent->localBufNum) { \ unit->m_buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ unit->m_buf = world->mSndBufs + bufnum; \ } \ } else { \ unit->m_buf = world->mSndBufs + bufnum; \ } \ unit->m_fbufnum = fbufnum; \ } \ SndBuf *buf = unit->m_buf; \ float *bufData __attribute__((__unused__)) = buf->data; \ uint32 bufChannels __attribute__((__unused__)) = buf->channels; \ uint32 bufSamples __attribute__((__unused__)) = buf->samples; \ uint32 bufFrames = buf->frames; \ int mask __attribute__((__unused__)) = buf->mask; \ int guardFrame __attribute__((__unused__)) = bufFrames - 2; #define SIMPLE_GET_BUF \ float fbufnum = ZIN0(0); \ fbufnum = sc_max(0.f, fbufnum); \ if (fbufnum != unit->m_fbufnum) { \ uint32 bufnum = (int)fbufnum; \ World *world = unit->mWorld; \ if (bufnum >= world->mNumSndBufs) { \ int localBufNum = bufnum - world->mNumSndBufs; \ Graph *parent = unit->mParent; \ if(localBufNum <= parent->localBufNum) { \ unit->m_buf = parent->mLocalSndBufs + localBufNum; \ } else { \ bufnum = 0; \ unit->m_buf = world->mSndBufs + bufnum; \ } \ } else { \ unit->m_buf = world->mSndBufs + bufnum; \ } \ unit->m_fbufnum = fbufnum; \ } \ SndBuf *buf = unit->m_buf; \ // macros to get pseudo-random number generator, and put its state in registers #define RGET \ RGen& rgen = *unit->mParent->mRGen; \ uint32 s1 = rgen.s1; \ uint32 s2 = rgen.s2; \ uint32 s3 = rgen.s3; #define RPUT \ rgen.s1 = s1; \ rgen.s2 = s2; \ rgen.s3 = s3; typedef void (*UnitCmdFunc)(struct Unit *unit, struct sc_msg_iter *args); typedef void (*PlugInCmdFunc)(World *inWorld, void* inUserData, struct sc_msg_iter *args, void *replyAddr); #endif <file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetBackgroundAuto(false); ofSetVerticalSync(true); ofEnableAlphaBlending(); ofSetFrameRate(60); ofBackground(0, 0, 0); startPos.set(10, 400); endPos.set(1000, 300); pct = 0.0; shaper = 0.5; } //-------------------------------------------------------------- void testApp::update(){ pct += 0.01f; if (pct > 1) { pct = 0; } currentPos = interpolateByPct(pct, shaper); } //-------------------------------------------------------------- void testApp::draw(){ fadeToBlack(); ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(31, 127, 255); ofRect(currentPos.x, currentPos.y, 20, 20); } //-------------------------------------------------------------- ofPoint testApp::interpolateByPct(float _pct, float _shaper){ float pct = powf(_pct, _shaper); ofPoint pos; pos.x = (1-pct) * startPos.x + (pct) * endPos.x; pos.y = (1-pct) * startPos.y + (pct) * endPos.y; return pos; } //-------------------------------------------------------------- void testApp::fadeToBlack() { ofSetRectMode(OF_RECTMODE_CORNER); ofSetColor(0, 0, 0, 10); ofRect(0, 0, ofGetWidth(), ofGetHeight()); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<file_sep>/* ofxPd v0.02 Copyright 2010 by <NAME>, <NAME>. this code uses code from pdlib "AudioOutput.h", so pdlib license is included here: AudioOutput.h PdLib v0.3 Copyright 2010 <NAME>. All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY BRYAN SUMMERSETT ``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 BRYAN SUMMERSETT 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Bryan Summersett. */ #include "ofxPd.h" #include <assert.h> extern "C" { #include "m_pd.h" #include "m_imp.h" #include "s_main.h" #include "s_stuff.h" extern void sched_audio_callbackfn(void); }; void ofxPd::setup( string _lib_dir, int _in_chans, int _out_chans, int _bitrate, int _block_size ) { lib_dir = ofToDataPath(_lib_dir); out_chans = _out_chans; in_chans = _in_chans; bitrate = _bitrate; block_size = _block_size; } void ofxPd::addOpenFile( string file_path ) { open_files.push_back( ofToDataPath( file_path ) ); } void ofxPd::addSearchPath( string path ) { search_path.push_back( ofToDataPath( path ) ); } void ofxPd::start() { this->startThread(); // sleep until pd engine has fully started while ( !sys_hasstarted ) ofSleepMillis( 500 ); } void ofxPd::stop() { if ( this->isThreadRunning() ) sys_exit(); } void ofxPd::threadedFunction() { // concatenate string vectors to single strings string externs_cat, open_files_cat, search_path_cat; for ( int i=0; i<externs.size(); i++ ) { if ( i > 0 ) externs_cat += ":"; externs_cat += externs[i]; } for ( int i=0; i<open_files.size(); i++ ) { if ( i > 0 ) open_files_cat += ":"; open_files_cat += open_files[i]; } for ( int i=0; i<search_path.size(); i++ ) { if ( i > 0 ) search_path_cat += ":"; search_path_cat += search_path[i]; } int sound_rate = bitrate; int n_out_channels = out_chans; int n_in_channels = in_chans; sys_main( lib_dir.c_str(), externs_cat.c_str(), open_files_cat.c_str(), search_path_cat.c_str(), sound_rate, block_size, n_out_channels, n_in_channels ); } void ofxPd::renderAudio( float* output, int bufferSize, int nChannels ) { // adapted from AudioOutputController by <NAME> // sys_schedblocksize is How many frames we have per PD dsp_tick // inNumberFrames is how many frames have been requested int inNumberFrames = bufferSize; // Make sure we're dealing with evenly divisible numbers between // the number of frames requested vs the block size for a given PD dsp tick. //Otherwise this looping scheme we're doing below doesn't make much sense. assert(inNumberFrames % sys_schedblocksize == 0); // How many times to generate a DSP event in PD int times = inNumberFrames / sys_schedblocksize; for(int i = 0; i < times; i++) { // do one Pd DSP block sys_lock(); sched_audio_callbackfn(); sys_unlock(); // This should cover sys_noutchannels channels. Turns non-interleaved into // interleaved audio. for (int n = 0; n < sys_schedblocksize; n++) { for(int ch = 0; ch < sys_noutchannels; ch++) { t_sample fsample = CLAMP(sys_soundout[n+sys_schedblocksize*ch],-1,1); output[(n*sys_noutchannels+ch) + // offset in iteration i*sys_schedblocksize*sys_noutchannels] // iteration starting address = fsample; } } // After loading the samples, we need to clear them for the next iteration memset(sys_soundout, 0, sizeof(t_sample)*sys_noutchannels*sys_schedblocksize); } } void ofxPd::renderAudio( float * input, float* output, int bufferSize, int nChannels ){ // adapted from AudioOutputController by <NAME> // sys_schedblocksize is How many frames we have per PD dsp_tick // inNumberFrames is how many frames have been requested int inNumberFrames = bufferSize; // Make sure we're dealing with evenly divisible numbers between // the number of frames requested vs the block size for a given PD dsp tick. //Otherwise this looping scheme we're doing below doesn't make much sense. assert(inNumberFrames % sys_schedblocksize == 0); // How many times to generate a DSP event in PD int times = inNumberFrames / sys_schedblocksize; for(int i = 0; i < times; i++) { for (int n = 0; n < sys_schedblocksize; n++) { for(int ch = 0; ch < sys_ninchannels; ch++) { sys_soundin[n+sys_schedblocksize*ch] = input[(n*sys_ninchannels+ch) + // offset in iteration i*sys_schedblocksize*sys_ninchannels]; // iteration starting address } } // do one Pd DSP block sys_lock(); sched_audio_callbackfn(); sys_unlock(); // This should cover sys_noutchannels channels. Turns non-interleaved into // interleaved audio. for (int n = 0; n < sys_schedblocksize; n++) { for(int ch = 0; ch < sys_noutchannels; ch++) { t_sample fsample = CLAMP(sys_soundout[n+sys_schedblocksize*ch],-1,1); output[(n*sys_noutchannels+ch) + // offset in iteration i*sys_schedblocksize*sys_noutchannels] // iteration starting address = fsample; //sys_soundin[n+sys_schedblocksize*ch] = ofRandom(-0.5,0.5); // iteration starting address } } // After loading the samples, we need to clear them for the next iteration memset(sys_soundout, 0, sizeof(t_sample)*sys_noutchannels*sys_schedblocksize); } } void ofxPd::sendFloat( const string& receive_target, float the_float ) { sendRawMessage( ";"+receive_target+" "+ofToString(the_float) ); } void ofxPd::sendRawMessage( const string& message ) { // senda message to pd t_binbuf *b = binbuf_new(); static char msg_buf[MAXPDSTRING+1]; strncpy( msg_buf, message.c_str(), message.size() ); binbuf_text(b, msg_buf, message.size() ); sys_lock(); binbuf_eval(b, 0, 0, 0); sys_unlock(); binbuf_free(b); } <file_sep>#include "testApp.h" void testApp::setup(){ ofSetFrameRate(60); ofBackground(0, 0, 0); reverb = new ofxSCSynth("reverb"); reverb->create(); baseSound = new ofxSCSynth("baseSound"); baseSound->create(); } void testApp::update(){ //Ring更新 for(vector <Ring *>::iterator it = rings.begin(); it != rings.end();){ (*it)->update(); if ((*it)->dead) { delete (*it); it = rings.erase(it); } else { ++it; } } } void testApp::draw(){ //Ringを描画 for(vector <Ring *>::iterator it = rings.begin(); it != rings.end(); ++it){ (*it)->draw(); } } void testApp::keyPressed(int key){} void testApp::keyReleased(int key){} void testApp::mouseMoved(int x, int y ){} void testApp::mouseDragged(int x, int y, int button){} void testApp::mousePressed(int x, int y, int button){} void testApp::mouseReleased(int x, int y, int button){ //newRingの楽器を新規に生成し演奏 int note[8] = {28, 35, 40, 47, 52, 59, 64, 71}; newRing = new ofxSCSynth("newRing"); newRing->set("note", note[int(ofRandom(0, 8))]); newRing->set("pan", (x - ofGetWidth() / 2.0) / ofGetWidth() * 2.0); newRing->create(); //Ringを追加 rings.push_back(new Ring(ofPoint(x, y))); } void testApp::windowResized(int w, int h){}<file_sep>#include "testApp.h" void testApp::setup(){ ofSetupScreen(); ofBackground(0, 0, 0); ofSetVerticalSync(true); sampleRate = 44100; /* Sampling Rate */ initialBufferSize = 512; /* Buffer Size. you have to fill this buffer with sound*/ ofSoundStreamSetup(2,0,this, sampleRate, initialBufferSize, 4); lAudio.assign(initialBufferSize, 0.0); rAudio.assign(initialBufferSize, 0.0); mode = 0; } void testApp::update(){ } void testApp::draw(){ ofSetColor(225); ofDrawBitmapString("MAXIMILIAN OSCILATORS", 32, 32); ofDrawBitmapString("0:sin, 1:saw, 2:pulse, 3:phasor, 4:triangle, 5:noise", 32, 48); ofNoFill(); // draw the left channel: ofPushStyle(); ofPushMatrix(); ofTranslate(32, 150, 0); ofSetColor(225); ofDrawBitmapString("Left Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 900, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (int i = 0; i < lAudio.size(); i++){ float x = ofMap(i, 0, lAudio.size(), 0, 900, true); ofVertex(x, 100 -lAudio[i]*100.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the right channel: ofPushStyle(); ofPushMatrix(); ofTranslate(32, 350, 0); ofSetColor(225); ofDrawBitmapString("Right Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 900, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (int i = 0; i < rAudio.size(); i++){ float x = ofMap(i, 0, rAudio.size(), 0, 900, true); ofVertex(x, 100 -rAudio[i]*100.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); } void testApp::audioOut (float * output, int bufferSize, int nChannels){ for (int i = 0; i < bufferSize; i++){ float freq = mouseY; float pan = (float)mouseX / (float)ofGetWidth(); switch (mode) { case 0: wave = osc.sinewave(freq); break; case 1: wave = osc.saw(freq); break; case 2: wave = osc.pulse(freq, 0.99); break; case 3: wave = osc.phasor(freq); break; case 4: wave = osc.triangle(freq); break; case 5: wave = osc.noise(); break; default: wave = osc.sinewave(freq); break; } mymix.stereo(wave, outputs, pan); lAudio[i] = output[i*nChannels ] = outputs[0]; rAudio[i] = output[i*nChannels + 1] = outputs[1]; } } void testApp::audioIn (float * input, int bufferSize, int nChannels){ for (int i = 0; i < bufferSize; i++){ } } void testApp::keyPressed(int key){ if (key == '0') { mode = 0; } if (key == '1') { mode = 1; } if (key == '2') { mode = 2; } if (key == '3') { mode = 3; } if (key == '4') { mode = 4; } if (key == '5') { mode = 5; } }<file_sep>#include "rectangle.h" void Rectangle::draw() { ofFill(); ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(31,127,255); ofRect(pos.x, pos.y, 20,20); } void Rectangle::interpolateByPct(float _pct){ pct = powf(_pct, shaper); pos.x = (1-pct) * startPos.x + (pct) * endPos.x; pos.y = (1-pct) * startPos.y + (pct) * endPos.y; }<file_sep>#pragma once #include "ofMain.h" #include "ofxCv.h" #include "ofxKinect.h" #include "ofxControlPanel.h" #include "ofxSuperColliderServer.h" #include "ofxSuperCollider.h" #include "MyRect.h" class testApp : public ofBaseApp { public: void setup(); void update(); void draw(); void exit(); void drawPointCloud(); void drawCv(); void keyPressed (int key); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); ofImage kinectImage; ofImage depthImage; ofEasyCam easyCam; ofxControlPanel gui; ofxKinect kinect; ofxCv::ContourFinder contourFinder; ofxSCSynth* reverb; list <MyRect *> rects; ofxCv::Point2f lastPos1, lastPos2; ofPoint interPos; int drawWaitTime; int drawWaitCount; bool drawRect; }; <file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup() { ofBackground(0, 0, 0); hardware.setup(); hardware.setLedOption(LED_OFF); context.setup(); depth.setup(&context); user.setup(&context); } //-------------------------------------------------------------- void testApp::update(){ hardware.update(); context.update(); depth.update(); user.update(); } //-------------------------------------------------------------- void testApp::draw(){ depth.draw(0,0,640,480); user.draw(); ofxTrackedUser* tracked = user.getTrackedUser(0); tracked->debugDraw(); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } <file_sep>#include "testApp.h" using namespace cv; using namespace ofxCv; void testApp::setup() { //画面設定 ofBackgroundHex(0x000000); ofSetFrameRate(60); // Kinect初期化 kinect.setRegistration(true); kinect.init(); kinect.open(); // GUI gui.setup("ofxKinect Point Cloud", 0, 0, 360, ofGetHeight()); gui.addPanel("panel 1", 3); gui.setWhichColumn(0); gui.addToggle("Pick Color", "pick_color", false); gui.addSlider("Point size", "point_size", 2.0, 0.0, 10.0, false); gui.addSlider("Step size", "step", 2, 1, 10, true); gui.addSlider("Z position", "posz", -400, -1000, 0, true); gui.addSlider("Min Area Radius", "min_radius", 10, 0, 500, true); gui.addSlider("Max Area Radius", "max_radius", 400, 0, 500, true); gui.addSlider("Z threshold", "z_thresh", 1000, 0, 4000, true); gui.addSlider("CV Threshold", "cv_thresh", 200, 0, 255, true); gui.addSlider("CV Screen Offset", "cv_offset", 400, 0, 1000, true); gui.addSlider("Camera Tilt Angle", "angle", 0, -40, 40, true); gui.addDrawableRect("Kinect Depth", &depthImage, 160, 120); gui.loadSettings("controlPanelSettings.xml"); } void testApp::update() { kinect.update(); gui.update(); // カメラ角度設定 kinect.setCameraTiltAngle(gui.getValueI("angle")); // 輪郭抽出の範囲設定 contourFinder.setMinAreaRadius(gui.getValueI("min_radius")); contourFinder.setMaxAreaRadius(gui.getValueI("max_radius")); // 深度情報の画像から、輪郭抽出 if(kinect.isFrameNew()) { kinectImage.setFromPixels(kinect.getPixels(), kinect.width, kinect.height, OF_IMAGE_COLOR); depthImage.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height, OF_IMAGE_GRAYSCALE); contourFinder.setThreshold(gui.getValueI("cv_thresh")); contourFinder.findContours(depthImage); } } void testApp::draw() { // ドラッグで視線を変更できるように(ofEasyCam) easyCam.begin(); glEnable(GL_DEPTH_TEST); //ポイントクラウドの描画 ofPushMatrix(); ofScale(1, -1, -1); ofTranslate(0, 0, gui.getValueI("posz")); drawPointCloud(); // CV描画 ofTranslate(0, 0, gui.getValueI("cv_offset")); drawCv(); ofPopMatrix(); glDisable(GL_DEPTH_TEST); easyCam.end(); // GUI表示 ofSetLineWidth(1); gui.draw(); } void testApp::drawPointCloud() { // 画面の幅と高さ int w = 640; int h = 480; // メッシュを生成 ofMesh mesh; mesh.setMode(OF_PRIMITIVE_POINTS); // 設定した間隔で、画面の深度情報と色を取得してメッシュの頂点に設定 int step = gui.getValueI("step"); for(int y = 0; y < h; y += step) { for(int x = 0; x < w; x += step) { if(kinect.getDistanceAt(x, y) < gui.getValueI("z_thresh")) { if (gui.getValueB("pick_color")) { mesh.addColor(kinect.getColorAt(x,y)); } else { mesh.addColor(ofFloatColor(255,255,255)); } mesh.addVertex(kinect.getWorldCoordinateAt(x, y)); } } } // メッシュの頂点を描画 glPointSize(gui.getValueF("point_size")); ofPushMatrix(); ofEnableBlendMode(OF_BLENDMODE_ADD); mesh.drawVertices(); ofPopMatrix(); } void testApp::drawCv() { ofPushMatrix(); ofEnableBlendMode(OF_BLENDMODE_ADD); ofTranslate(-kinect.width/2, -kinect.height/2, 0); // 深度情報を表示 ofSetColor(100, 100, 100); kinect.drawDepth(0, 0, kinect.width, kinect.height); // CV 輪郭線分析画面の表示 ofPushMatrix(); // 輪郭線を表示 ofTranslate(0, 0, -1); ofSetColor(127, 127, 127); ofSetLineWidth(3); contourFinder.draw(); // 輪郭の中心位置に円を配置 ofSetColor(255, 127, 0); for (int i = 0; i < contourFinder.size(); i++) { Point2f pos = contourFinder.getCentroid(i); ofCircle(pos.x, pos.y, 3); } // もし検出点が2点だったら、矩形を描画 if (contourFinder.size() > 1) { Point2f pos0 = contourFinder.getCentroid(0); Point2f pos1 = contourFinder.getCentroid(1); float width = pos1.x - pos0.x; float height = pos1.y - pos0.y; ofSetColor(0, 127, 127); ofRect(pos0.x, pos0.y, width, height); } ofPopMatrix(); ofPopMatrix(); } void testApp::exit() { // Kinect終了 kinect.close(); } void testApp::keyPressed (int key) { if (key == ' ') { gui.toggleView(); } if (key == 'f') { ofToggleFullscreen(); } } void testApp::mouseDragged(int x, int y, int button){ gui.mouseDragged(x, y, button); } void testApp::mousePressed(int x, int y, int button){ gui.mousePressed(x, y, button); } void testApp::mouseReleased(int x, int y, int button){ gui.mouseReleased(); } <file_sep>/* Copyright (c) 1997-1999 <NAME> and others. * For information on usage and redistribution, and for a DISCLAIMER OF ALL * WARRANTIES, see the file, "LICENSE.txt," in this distribution. */ #include "m_pd.h" #include "m_imp.h" #include "s_stuff.h" #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <string.h> #include <stdio.h> #include <fcntl.h> #include <stdlib.h> #ifdef UNISTD #include <unistd.h> #endif #ifdef MSW #include <io.h> #include <windows.h> #include <winbase.h> #endif #ifdef _MSC_VER /* This is only for Microsoft's compiler, not cygwin, e.g. */ #define snprintf sprintf_s #endif //#include "AudioOutput.h" char *pd_version; char pd_compiletime[] = __TIME__; char pd_compiledate[] = __DATE__; void pd_init(void); int sys_startgui(const char *guipath); int m_mainloop(void); int m_batchmain(void); void sys_addhelppath(char *p); int sys_debuglevel; int sys_verbose; int sys_noloadbang; int sys_nogui; int sys_hipriority = -1; /* -1 = don't care; 0 = no; 1 = yes */ int sys_guisetportnumber; /* if started from the GUI, this is the port # */ int sys_nosleep = 0; /* skip all "sleep" calls and spin instead */ char *sys_guicmd; t_symbol *sys_libdir; t_symbol *sys_guidir; static t_namelist *sys_openlist; static t_namelist *sys_messagelist; int sys_oldtclversion; /* hack to warn g_rtext.c about old text sel */ /* old s_audio.c globals */ int sys_dacsr = 22050; int sys_schedblocksize = 256; // block size int sys_noutchannels = 2; int sys_ninchannels = 2; /* AudioCallbackFn sys_userCallbackFn = NULL; extern void sched_audio_callbackfn(void); void audioOutputCallbackFn(const AudioTimeStamp *inTimestamp) { if (sys_userCallbackFn) { (*sys_userCallbackFn)(inTimestamp); } sched_audio_callbackfn(); } AudioCallbackParams sys_callbackparams = { &audioOutputCallbackFn, NULL, 0 };*/ t_sample *sys_soundout; // global var for samples t_sample *sys_soundin; int sys_printtostderr; int sys_hasstarted = 0; int sys_nmidiout = -1; int sys_nmidiin = -1; int sys_midiindevlist[1] = {1}; int sys_midioutdevlist[1] = {1}; char sys_font[100] = #ifdef MSW "Courier"; #else "Courier"; #endif char sys_fontweight[] = "bold "; /* currently only used for iemguis */ //static int sys_main_advance; //static int sys_main_callback; //static int sys_listplease; int sys_externalschedlib; char sys_externalschedlibname[MAXPDSTRING]; int sys_extraflags; char sys_extraflagsstring[MAXPDSTRING]; int sys_run_scheduler(const char *externalschedlibname, const char *sys_extraflagsstring); int sys_noautopatch; /* temporary hack to defeat new 0.42 editing */ typedef struct _fontinfo { int fi_fontsize; int fi_maxwidth; int fi_maxheight; int fi_hostfontsize; int fi_width; int fi_height; } t_fontinfo; /* these give the nominal point size and maximum height of the characters in the six fonts. */ static t_fontinfo sys_fontlist[] = { {8, 6, 10, 0, 0, 0}, {10, 7, 13, 0, 0, 0}, {12, 9, 16, 0, 0, 0}, {16, 10, 20, 0, 0, 0}, {24, 15, 25, 0, 0, 0}, {36, 25, 45, 0, 0, 0}}; #define NFONT (sizeof(sys_fontlist)/sizeof(*sys_fontlist)) /* here are the actual font size structs on msp's systems: MSW: font 8 5 9 8 5 11 font 10 7 13 10 6 13 font 12 9 16 14 8 16 font 16 10 20 16 10 18 font 24 15 25 16 10 18 font 36 25 42 36 22 41 linux: font 8 5 9 8 5 9 font 10 7 13 12 7 13 font 12 9 16 14 9 15 font 16 10 20 16 10 19 font 24 15 25 24 15 24 font 36 25 42 36 22 41 */ static t_fontinfo *sys_findfont(int fontsize) { unsigned int i; t_fontinfo *fi; for (i = 0, fi = sys_fontlist; i < (NFONT-1); i++, fi++) if (fontsize < fi[1].fi_fontsize) return (fi); return (sys_fontlist + (NFONT-1)); } int sys_nearestfontsize(int fontsize) { return (sys_findfont(fontsize)->fi_fontsize); } int sys_hostfontsize(int fontsize) { return (sys_findfont(fontsize)->fi_hostfontsize); } int sys_fontwidth(int fontsize) { return (sys_findfont(fontsize)->fi_width); } int sys_fontheight(int fontsize) { return (sys_findfont(fontsize)->fi_height); } int sys_defaultfont; #ifdef MSW #define DEFAULTFONT 12 #else #define DEFAULTFONT 10 #endif int openit(const char *dirname, const char *filename) { char dirbuf[MAXPDSTRING], *nameptr; int fd = open_via_path(dirname, filename, "", dirbuf, &nameptr, MAXPDSTRING, 0); if (fd >= 0) { close (fd); glob_evalfile(0, gensym(nameptr), gensym(dirbuf)); return 0; } else { error("%s: can't open", filename); return -1; } } /* this is called from the gui process. The first argument is the cwd, and succeeding args give the widths and heights of known fonts. We wait until these are known to open files and send messages specified on the command line. We ask the GUI to specify the "cwd" in case we don't have a local OS to get it from; for instance we could be some kind of RT embedded system. However, to really make this make sense we would have to implement open(), read(), etc, calls to be served somehow from the GUI too. */ void glob_initfromgui(void *dummy, t_symbol *s, int argc, t_atom *argv) { char *cwd = atom_getsymbolarg(0, argc, argv)->s_name; t_namelist *nl; unsigned int i; int j; int nhostfont = (argc-2)/3; sys_oldtclversion = atom_getfloatarg(1, argc, argv); if (argc != 2 + 3 * nhostfont) bug("glob_initfromgui"); for (i = 0; i < NFONT; i++) { int best = 0; int wantheight = sys_fontlist[i].fi_maxheight; int wantwidth = sys_fontlist[i].fi_maxwidth; for (j = 1; j < nhostfont; j++) { if (atom_getintarg(3 * j + 4, argc, argv) <= wantheight && atom_getintarg(3 * j + 3, argc, argv) <= wantwidth) best = j; } /* best is now the host font index for the desired font index i. */ sys_fontlist[i].fi_hostfontsize = atom_getintarg(3 * best + 2, argc, argv); sys_fontlist[i].fi_width = atom_getintarg(3 * best + 3, argc, argv); sys_fontlist[i].fi_height = atom_getintarg(3 * best + 4, argc, argv); } #if 0 for (i = 0; i < 6; i++) fprintf(stderr, "font (%d %d %d) -> (%d %d %d)\n", sys_fontlist[i].fi_fontsize, sys_fontlist[i].fi_maxwidth, sys_fontlist[i].fi_maxheight, sys_fontlist[i].fi_hostfontsize, sys_fontlist[i].fi_width, sys_fontlist[i].fi_height); #endif /* load dynamic libraries specified with "-lib" args */ for (nl = sys_externlist; nl; nl = nl->nl_next) if (!sys_load_lib(0, nl->nl_string)) post("%s: can't load library", nl->nl_string); /* open patches specifies with "-open" args */ for (nl = sys_openlist; nl; nl = nl->nl_next) openit(cwd, nl->nl_string); namelist_free(sys_openlist); sys_openlist = 0; /* send messages specified with "-send" args */ for (nl = sys_messagelist; nl; nl = nl->nl_next) { t_binbuf *b = binbuf_new(); binbuf_text(b, nl->nl_string, strlen(nl->nl_string)); binbuf_eval(b, 0, 0, 0); binbuf_free(b); } namelist_free(sys_messagelist); sys_messagelist = 0; } void sys_send_msg(const char *msg) { t_binbuf *b = binbuf_new(); binbuf_text(b, (char*) msg, strlen(msg)); binbuf_eval(b, 0, 0, 0); binbuf_free(b); } static void sys_afterargparse(void); static void pd_makeversion(void) { char foo[100]; sprintf(foo, "Pd version %d.%d-%d%s\n",PD_MAJOR_VERSION, PD_MINOR_VERSION,PD_BUGFIX_VERSION,PD_TEST_VERSION); pd_version = malloc(strlen(foo)+1); strcpy(pd_version, foo); } /* this is called from main() in s_entry.c */ int sys_main(const char *libdir, const char *externs, const char *openfiles, const char *searchpath, int soundRate, int blockSize, int nOutChannels, int nInChannels/*, AudioCallbackFn callback*/) { // sys_userCallbackFn = callback; sys_externalschedlib = 0; sys_extraflags = 0; sys_soundout = malloc(sizeof(t_sample) * sys_schedblocksize * sys_noutchannels); memset(sys_soundout, 0, sizeof(t_sample) * sys_schedblocksize * sys_noutchannels); sys_soundin = malloc(sizeof(t_sample) * sys_schedblocksize * sys_ninchannels); memset(sys_soundin, 0, sizeof(t_sample) * sys_schedblocksize * sys_ninchannels); sys_dacsr = soundRate; sys_schedblocksize = blockSize; sys_noutchannels = nOutChannels; sys_ninchannels = nInChannels; // pure data defaults pd_init(); /* start the message system */ sys_libdir = gensym(libdir); // Find lib dir sys_guidir = gensym(libdir); // should be libdir + "/bin" usually, but it doesn't really matter in our case sys_searchpath = namelist_append_files(sys_searchpath, searchpath); sys_openlist = namelist_append_files(sys_openlist, openfiles); // open files sys_externlist = namelist_append_files(sys_externlist, externs); // open externs at start up sys_printtostderr = sys_nogui = 1; sys_verbose = 1; if (!sys_defaultfont) sys_defaultfont = DEFAULTFONT; sys_afterargparse(); /* post-argparse settings */ /* build version string from defines in m_pd.h */ pd_makeversion(); if (sys_startgui(libdir)) /* start the gui */ return(1); // bryansum // Run the either m_pollingscheduler, which actually computes ticks, // or m_callbackscheduler, which waits for the hardware to callback for DSP ticks. // // we will be using the callback mechanism sched_set_using_audio(SCHED_AUDIO_CALLBACK); sys_hasstarted = 1; return (m_mainloop()); } /* stuff to do, once, after calling sys_argparse() -- which may itself be called more than once (first from "settings, second from .pdrc, then from command-line arguments */ static void sys_afterargparse(void) { char sbuf[MAXPDSTRING]; /* add "extra" library to path */ strncpy(sbuf, sys_libdir->s_name, MAXPDSTRING-30); sbuf[MAXPDSTRING-30] = 0; strcat(sbuf, "/extra"); sys_setextrapath(sbuf); /* add "doc/5.reference" library to helppath */ strncpy(sbuf, sys_libdir->s_name, MAXPDSTRING-30); sbuf[MAXPDSTRING-30] = 0; strcat(sbuf, "/doc/5.reference"); sys_helppath = namelist_append_files(sys_helppath, sbuf); } <file_sep>#pragma once #include "ofMain.h" #include "ofxMaxim.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); void audioOut(float * input, int bufferSize, int nChannels); void audioIn(float * input, int bufferSize, int nChannels); int initialBufferSize; int sampleRate; double wave,sample,outputs[2]; ofxMaxiMix mymix; ofxMaxiOsc osc; //Oscilator int mode; vector <float> lAudio; vector <float> rAudio; }; <file_sep>/* * MyRect.cpp * ofxKinect * * Created by <NAME> on 10/11/26. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #include "MyRect.h" MyRect::MyRect(ofPoint _p1, ofPoint _p2) { p1 = _p1; p2 = _p2; posZ = 0; speedZ = ofRandom(0.02, 0.2); dead = false; pitchRatio[0]= 1.0; pitchRatio[1]= 9.0/8.0; pitchRatio[2]= 5.0/4.0; pitchRatio[3]= 4.0/3.0; pitchRatio[4]= 3.0/2.0; pitchRatio[5]= 5.0/3.0; pitchRatio[6]= 15.0/8.0; p2.x > p1.x ? rectPos.x = p1.x : rectPos.x = p2.x; p2.y > p1.y ? rectPos.y = p1.y : rectPos.y = p2.y; width = abs(p2.x - p1.x); height = abs(p2.y - p1.y); scanSpeed = ofRandom(1.0, 2.0); scanPos = 0; int zone = (ofGetHeight() - (rectPos.y + height))/(ofGetHeight()/12); freq = 5 * pow(2.0, zone) * pitchRatio[int(ofRandom(0, 6))]; if (freq > 18000) { freq = 18000; } pan = ofRandom(-1, 1); amp = abs(float(p2.y - p1.y) / 1000.0); perc = new ofxSCSynth("mySaw"); perc->set("amp", amp); perc->set("freq", freq); perc->set("decay", width/scanSpeed/60.0); perc->set("pan", pan); perc->create(); } void MyRect::update() { //posZ += speedZ; scanPos += scanSpeed; if (scanPos > width) { scanPos -= width; perc = new ofxSCSynth("mySaw"); perc->set("amp", amp); perc->set("freq", freq); perc->set("decay", width/scanSpeed/60.0); perc->set("pan", pan); perc->create(); posZ-=5; if (posZ > 1000) { dead = true; } } } void MyRect::draw(){ ofFill(); float alpha = 255 - scanPos / width * 255.0; ofSetColor(0, 255, 255, alpha); ofPushMatrix(); ofTranslate(0, 0, posZ); ofRect(rectPos.x, rectPos.y, scanPos, height); ofPopMatrix(); }<file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ //ofxMultipleAppの初期化 ofxMultipleApp::init(); //シーンの登録 sceneA = new SceneA(); sceneB = new SceneB(); sceneC = new SceneC(); ofxMultipleApp::addApp(sceneA); ofxMultipleApp::addApp(sceneB); ofxMultipleApp::addApp(sceneC); //最初に表示するシーンを選択 currentApp = sceneA; currentApp->show(); sceneA->enable = true; } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ //ログ表示 ofSetHexColor(0xFFFFFF); ofDrawBitmapString("Press key to change scene :\nScene A [1], Scene B [2], Scene C [3]", 20, 20); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ //キー入力によって、シーンを切り替え switch (key) { case '1': currentApp->hide(); currentApp->enable = false; currentApp = sceneA; currentApp->show(); sceneA->enable = true; break; case '2': currentApp->hide(); currentApp->enable = false; currentApp = sceneB; currentApp->show(); sceneB->enable = true; break; case '3': currentApp->hide(); currentApp->enable = false; currentApp = sceneC; currentApp->show(); sceneC->enable = true; break; case 'f': ofToggleFullscreen(); break; } } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } <file_sep>#include "testApp.h" void testApp::setup(){ ofBackground(255, 255, 255); //ビットマップ画像の読みこみ myImage.loadImage("t_hero.png"); //8段階の文字の濃度を文字列に pixelString = " .-+*a&@"; } void testApp::update(){ } void testApp::draw(){ int left = (ofGetWidth() - myImage.width) / 2; int top = (ofGetHeight() - myImage.height) / 2; ofTranslate(left, top); unsigned char * pixels = myImage.getPixels(); int skip = 5; ofSetColor(0, 0, 0); for (int i = 0; i < myImage.width; i = i + skip){ for (int j = 0; j < myImage.height; j = j + skip){ int brightness = pixels[j * myImage.width + i]; float pct = 1.0 - brightness / 255.0; //濃度の応じた文字をとりだし string str = pixelString.substr(int(pct * 8),1); //文字を描画 ofDrawBitmapString(str, i, j); } } }<file_sep>#include "rectangle.h" void Rectangle::draw() { ofFill(); ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(0, 63, 255); ofRect(pos.x, pos.y, 5, 5); } void Rectangle::interpolateByPct(float _pct){ float ppct = powf(_pct, shaper); pos.x = (1-ppct) * startPos.x + (ppct) * endPos.x; pos.y = (1-ppct) * startPos.y + (ppct) * endPos.y; }<file_sep>#include "testApp.h" void testApp::setup(){ ofSetFrameRate(60); ofBackground(0, 0, 0); //OSCの初期化 static const string HOST = "localhost"; static const int PORT = 8000; osc_sender.setup( "localhost", PORT); // pdのための定数を定義 // 出力と入力のチャンネル数 static const int NUM_OUT_CHANNELS = 2; static const int NUM_IN_CHANNELS = 2; // サンプリングレイト static const int BITRATE = 44100; // バッファーサイズ static const int BUFFER_SIZE = 256; // 使用するバッファーの数 static const int NUM_BUFFERS = 4; // Pdのブロックサイズ static const int PD_BLOCK_SIZE = 64; // Pdを初期化 pd.setup( "", NUM_OUT_CHANNELS, NUM_IN_CHANNELS, BITRATE, PD_BLOCK_SIZE ); // Pdファイルを読み込み pd.addOpenFile( "simple_fm.pd" ); // Pdを開始 pd.start(); // オーディオ入力を定義 audioInputData = new float[BUFFER_SIZE*NUM_IN_CHANNELS]; // サウンド出力を初期化 ofSoundStreamSetup( NUM_OUT_CHANNELS, NUM_IN_CHANNELS, this, BITRATE, BUFFER_SIZE, NUM_BUFFERS ); // Pdから音を出力 pd.startDSP(); } void testApp::update(){ } void testApp::draw(){ ofSetColor(0, 127, 255); ofCircle(mouseX, mouseY, 20); } void testApp::keyPressed (int key){ } void testApp::keyReleased (int key){ } void testApp::mouseMoved(int x, int y ){ // マウスの座標をPdのパラメータとして送出 pd.sendFloat( "modulator_freq", x ); pd.sendFloat( "modulator_index", y ); } void testApp::mouseDragged(int x, int y, int button){ } void testApp::mousePressed(int x, int y, int button){ } void testApp::mouseReleased(int x, int y, int button){ } void testApp::windowResized(int w, int h){ } void testApp::audioOut (float * output, int bufferSize, int nChannels){ //Pdの音を計算 pd.renderAudio( audioInputData, output, bufferSize, nChannels ); } void testApp::audioIn (float * input, int bufferSize, int nChannels){ memcpy(audioInputData, input, bufferSize*nChannels*sizeof(float)); }<file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0,0,0); ofSetVerticalSync(true); ofSetFrameRate(60); for (int i = 0; i < 50; i++){ particle myParticle; float x = 500 + 100 * cos ( (i / 200.0) * TWO_PI); float y = 500 + 100 * sin ( (i / 200.0) * TWO_PI); myParticle.setInitialCondition(x,y ,0,0); particles.push_back(myParticle); } // change this to // for (int i = 0; i < 10; i++){ // to see a chain for (int i = 0; i < particles.size(); i++){ spring mySpring; mySpring.distance = 8; mySpring.springiness = 0.2f; mySpring.particleA = & (particles[i ]); mySpring.particleB = & (particles[(i+1) % particles.size()]); springs.push_back(mySpring); } //shader.setup("shaders/gradient"); shader.load("shaders/gradient.vert", "shaders/gradient.frag"); shader.printActiveUniforms(); } //-------------------------------------------------------------- void testApp::update(){ // on every frame // we reset the forces // add in any forces on the particle // perfom damping and // then update for (int i = 0; i < particles.size(); i++){ particles[i].resetForce(); } for (int i = 0; i < particles.size(); i++){ particles[i].addRepulsionForce(mouseX, mouseY, 200, 0.7f); for (int j = 0; j < i; j++){ particles[i].addRepulsionForce(particles[j], 80, 0.2); } } for (int i = 0; i < springs.size(); i++){ springs[i].update(); } for (int i = 0; i < particles.size(); i++){ particles[i].bounceOffWalls(); particles[i].addDampingForce(); particles[i].update(); } } //-------------------------------------------------------------- void testApp::draw(){ float minx, maxx, miny, maxy; for (int i = 0; i < particles.size(); i++){ if (i == 0) { minx = particles[i].pos.x; maxx = particles[i].pos.x; miny = particles[i].pos.y; maxy = particles[i].pos.y; } else { minx = min(minx, particles[i].pos.x); maxx = max(maxx, particles[i].pos.x); miny = min(miny, particles[i].pos.y); maxy = max(maxy, particles[i].pos.y); } } float x = minx; float y = miny; float w = maxx - minx; float h = maxy - miny; shader.begin(); shader.setUniform1f("x", x); shader.setUniform1f("y", y); shader.setUniform1f("w", w); shader.setUniform1f("h", h); shader.setUniform2f("gradientCenter", x + w * 0.5f, y + h*0.5f); shader.setUniform2f("gradientAngle", (float)sin(PI/4.0), (float)cos(PI/4.0)); shader.setUniform1f("gradientLength", 250.0f); shader.setUniform3f("gradientColorA", 10.0f / 255.0f, 175.0f / 255.0f, 240.0f / 255.0f); shader.setUniform3f("gradientColorB", 10.0f / 255.0f, 240.0f / 255.0f, 63.0f / 255.0f); shader.setUniform1f("gradientAlpha", 1.0f); ofFill(); ofBeginShape(); for (int i = 0; i < particles.size(); i++){ ofVertex(particles[i].pos.x, particles[i].pos.y); } ofEndShape(); shader.end(); ofSetColor(0xffffff); /*for (int i = 0; i < particles.size(); i++){ particles[i].draw(); } for (int i = 0; i < springs.size(); i++){ springs[i].draw(); }*/ } //-------------------------------------------------------------- void testApp::keyPressed (int key){ switch (key){ case ' ': // reposition everything: for (int i = 0; i < particles.size(); i++){ particles[i].setInitialCondition(ofRandom(0,ofGetWidth()),ofRandom(0,ofGetHeight()),0,0); } break; } } //-------------------------------------------------------------- void testApp::keyReleased (int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ particles[0].pos.set(mouseX, mouseY); /*particles.erase(particles.begin()); particle myParticle; myParticle.setInitialCondition(x,y,0,0); particles.push_back(myParticle);*/ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ particles[0].bFixed = true; } //-------------------------------------------------------------- void testApp::mouseReleased(){ particles[0].bFixed = false; } <file_sep>#include "testApp.h" ofPoint pos; //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0, 0, 0); ofSetFrameRate(60); ofSetVerticalSync(true); ofEnableBlendMode(OF_BLENDMODE_ADD); num = 100; } //-------------------------------------------------------------- void testApp::update(){ } //-------------------------------------------------------------- void testApp::draw(){ ofTranslate(ofGetWidth() / 2, ofGetHeight() / 2); ofSetHexColor(0x3399ff); for (int i = 0; i < num; i++) { ofRotateZ(360.f / num); float pos = sin((ofGetElapsedTimef() + 10000) * ((float)i / num / 2.0)) * ofGetHeight() / 1.8; //ofCircle(pos, 0, 2); ofRect(pos, 0, 1, 1); } ofSetHexColor(0xffffff); ofDrawBitmapString("point num = " + ofToString(num, 0), 20 - ofGetWidth()/2, 20 - ofGetHeight()/2); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ num+=100; } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<file_sep>#include "testApp.h" void testApp::setup(){ //画面設定 ofBackgroundHex(0x000000); ofEnableAlphaBlending(); glEnable(GL_DEPTH_TEST); cam.setDistance(100); //シェーダー読込み shader.load("gradient"); } void testApp::update(){ } void testApp::draw(){ ofPushMatrix(); ofTranslate(ofGetWidth()/2, ofGetHeight()/2); cam.begin(); //シェーダー開始 shader.begin(); // 球体と立方体を描画 ofSphere(0, -22, 0, 20); ofBox(0, 22, 0, 30); // シェーダー終了 shader.end(); cam.end(); ofPopMatrix(); } void testApp::keyPressed(int key){ if (key == 'f') ofToggleFullscreen(); }<file_sep>#include "testApp.h" void testApp::setup(){ //画面設定 ofBackgroundHex(0x000000); ofEnableAlphaBlending(); glEnable(GL_DEPTH_TEST); cam.setDistance(100); //シェーダー読込み shader.load("gradient"); } void testApp::update(){ } void testApp::draw(){ ofPushMatrix(); ofTranslate(ofGetWidth()/2, ofGetHeight()/2); cam.begin(); // シェーダー開始 shader.begin(); // シェーダーへ経過時間を送信 shader.setUniform1f("time", ofGetElapsedTimef()*0.1); // 円を描く ofSphere(0, 0, 0, 30); // シェーダー終了 shader.end(); cam.end(); ofPopMatrix(); } void testApp::keyPressed(int key){ }<file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofBackground(0,0,0); ofSetVerticalSync(true); ofSetFrameRate(60); //Particle A 初期設定 particle_a.setInitialCondition(400, 400, 0, 0); //Particle B 初期設定 particle_b.setInitialCondition(500, 500, 0, 0); //ばね(spring)を、パーティクル間に張る mySpring.distance = 100; //ばねの長さ mySpring.springiness = 0.1f; //ばねの硬さ mySpring.particleA = &particle_a; mySpring.particleB = &particle_b; } //-------------------------------------------------------------- void testApp::update(){ //力をリセット particle_a.resetForce(); particle_b.resetForce(); //バネを更新 mySpring.update(); //パーティクルの状態を更新 (壁でバウンド) particle_a.bounceOffWalls(); particle_a.update(); particle_b.bounceOffWalls(); particle_b.update(); } //-------------------------------------------------------------- void testApp::draw(){ ofSetColor(255, 255, 255); //ばねを描画 mySpring.draw(); //particleを描画 particle_a.draw(); particle_b.draw(); } //-------------------------------------------------------------- void testApp::keyPressed (int key){ } //-------------------------------------------------------------- void testApp::keyReleased (int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ particle_a.pos.set(mouseX, mouseY); } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ particle_a.bFixed = true; } //-------------------------------------------------------------- void testApp::mouseReleased(){ particle_a.bFixed = false; } <file_sep>/* SuperCollider real time audio synthesis system Copyright (c) 2002 <NAME>. All rights reserved. http://www.audiosynth.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #ifndef _SC_Prototypes_ #define _SC_Prototypes_ #include <ctype.h> // for size_t #include "SC_Types.h" #include "scsynthsend.h" //////////////////////////////////////////////////////////////////////// // replacement for calloc. // calloc lazily zeroes memory on first touch. This is good for most purposes, but bad for realtime audio. void* zalloc(size_t n, size_t size); //////////////////////////////////////////////////////////////////////// void World_Run(struct World *inWorld); void World_Start(World *inWorld); void World_Cleanup(World *inWorld); void World_SetSampleRate(struct World *inWorld, double inSampleRate); extern "C" { void* World_Alloc(struct World *inWorld, size_t inByteSize); void* World_Realloc(struct World *inWorld, void *inPtr, size_t inByteSize); void World_Free(struct World *inWorld, void *inPtr); void World_NRTLock(World *world); void World_NRTUnlock(World *world); } size_t World_TotalFree(struct World *inWorld); size_t World_LargestFreeChunk(struct World *inWorld); int32 GetKey(struct Node *inNode); int32 GetHash(struct Node *inNode); bool World_AddNode(struct World *inWorld, struct Node* inNode); bool World_RemoveNode(struct World *inWorld, struct Node* inNode); extern "C" { struct Node* World_GetNode(struct World *inWorld, int32 inID); struct Graph* World_GetGraph(struct World *inWorld, int32 inID); } struct Group* World_GetGroup(struct World *inWorld, int32 inID); int32 *GetKey(struct UnitDef *inUnitDef); int32 GetHash(struct UnitDef *inUnitDef); bool AddUnitDef(struct UnitDef* inUnitDef); bool RemoveUnitDef(struct UnitDef* inUnitDef); struct UnitDef* GetUnitDef(int32* inKey); int32 *GetKey(struct BufGen *inBufGen); int32 GetHash(struct BufGen *inBufGen); bool AddBufGen(struct BufGen* inBufGen); bool RemoveBufGen(struct BufGen* inBufGen); struct BufGen* GetBufGen(int32* inKey); int32 *GetKey(struct PlugInCmd *inPlugInCmd); int32 GetHash(struct PlugInCmd *inPlugInCmd); bool AddPlugInCmd(struct PlugInCmd* inPlugInCmd); bool RemovePlugInCmd(struct PlugInCmd* inPlugInCmd); struct PlugInCmd* GetPlugInCmd(int32* inKey); int PlugIn_DoCmd(struct World *inWorld, int inSize, char *inArgs, struct ReplyAddress *inReply); int32 *GetKey(struct GraphDef *inGraphDef); int32 GetHash(struct GraphDef *inGraphDef); void World_AddGraphDef(struct World *inWorld, struct GraphDef* inGraphDef); void World_RemoveGraphDef(struct World *inWorld, struct GraphDef* inGraphDef); struct GraphDef* World_GetGraphDef(struct World *inWorld, int32* inKey); void World_FreeAllGraphDefs(World *inWorld); void GraphDef_Free(GraphDef *inGraphDef); void GraphDef_Define(World *inWorld, GraphDef *inList); void GraphDef_FreeOverwritten(World *inWorld); SCErr bufAlloc(struct SndBuf* buf, int numChannels, int numFrames, double sampleRate); //////////////////////////////////////////////////////////////////////// void Rate_Init(struct Rate *inRate, double inSampleRate, int inBufLength); //////////////////////////////////////////////////////////////////////// #define GRAPHDEF(inGraph) ((GraphDef*)((inGraph)->mNode.mDef)) #define GRAPH_PARAM_TABLE(inGraph) (GRAPHDEF(inGraph)->mParamSpecTable) int Graph_New(struct World *inWorld, struct GraphDef *def, int32 inID, struct sc_msg_iter* args, struct Graph** outGraph,bool argtype=true); void Graph_Ctor(struct World *inWorld, struct GraphDef *inGraphDef, struct Graph *graph, struct sc_msg_iter *msg,bool argtype); void Graph_Dtor(struct Graph *inGraph); int Graph_GetControl(struct Graph* inGraph, uint32 inIndex, float& outValue); int Graph_GetControl(struct Graph* inGraph, int32 inHash, int32 *inName, uint32 inIndex, float& outValue); void Graph_SetControl(struct Graph* inGraph, uint32 inIndex, float inValue); void Graph_SetControl(struct Graph* inGraph, int32 inHash, int32 *inName, uint32 inIndex, float inValue); void Graph_MapControl(Graph* inGraph, uint32 inIndex, uint32 inBus); void Graph_MapControl(Graph* inGraph, int32 inHash, int32 *inName, uint32 inIndex, uint32 inBus); void Graph_MapAudioControl(Graph* inGraph, uint32 inIndex, uint32 inBus); void Graph_MapAudioControl(Graph* inGraph, int32 inHash, int32 *inName, uint32 inIndex, uint32 inBus); void Graph_Trace(Graph *inGraph); void Graph_RemoveID(World* inWorld, Graph *inGraph); //////////////////////////////////////////////////////////////////////// int Node_New(struct World *inWorld, struct NodeDef *def, int32 inID, struct Node **outNode); void Node_Dtor(struct Node *inNode); void Node_Remove(struct Node* s); void Node_Delete(struct Node* inNode); void Node_AddAfter(struct Node* s, struct Node *afterThisOne); void Node_AddBefore(struct Node* s, struct Node *beforeThisOne); void Node_Replace(struct Node* s, struct Node *replaceThisOne); void Node_SetControl(Node* inNode, int inIndex, float inValue); void Node_SetControl(Node* inNode, int32 inHash, int32 *inName, int inIndex, float inValue); void Node_MapControl(Node* inNode, int inIndex, int inBus); void Node_MapControl(Node* inNode, int32 inHash, int32 *inName, int inIndex, int inBus); void Node_MapAudioControl(Node* inNode, int inIndex, int inBus); void Node_MapAudioControl(Node* inNode, int32 inHash, int32 *inName, int inIndex, int inBus); void Node_StateMsg(Node* inNode, int inState); void Node_Trace(Node* inNode); void Node_SendReply(Node* inNode, int replyID, const char* cmdName, int numArgs, const float* values); void Node_SendReply(Node* inNode, int replyID, const char* cmdName, float value); extern "C" { void Node_SetRun(Node* inNode, int inRun); void Node_SendTrigger(Node* inNode, int triggerID, float value); void Node_End(struct Node* inNode); void Node_NullCalc(struct Node* inNode); void Unit_DoneAction(int doneAction, struct Unit* unit); } //////////////////////////////////////////////////////////////////////// extern "C" { void Group_Calc(Group *inGroup); void Graph_Calc(struct Graph *inGraph); } int Group_New(World *inWorld, int32 inID, Group** outGroup); void Group_Dtor(Group *inGroup); void Group_DeleteAll(Group *inGroup); void Group_DeepFreeGraphs(Group *inGroup); void Group_AddHead (Group *s, Node *child); void Group_AddTail (Group *s, Node *child); void Group_Insert(Group *s, Node *child, int inIndex); void Group_SetControl(struct Group* inGroup, uint32 inIndex, float inValue); void Group_SetControl(struct Group *inGroup, int32 inHash, int32 *inName, uint32 inIndex, float inValue); void Group_MapControl(Group* inGroup, uint32 inIndex, uint32 inBus); void Group_MapControl(Group* inGroup, int32 inHash, int32 *inName, uint32 inIndex, uint32 inBus); void Group_MapAudioControl(Group* inGroup, uint32 inIndex, uint32 inBus); void Group_MapAudioControl(Group* inGroup, int32 inHash, int32 *inName, uint32 inIndex, uint32 inBus); void Group_Trace(Group* inGroup); void Group_DumpTree(Group* inGroup); void Group_DumpTreeAndControls(Group* inGroup); void Group_CountNodeTags(Group* inGroup, int* count); void Group_CountNodeAndControlTags(Group* inGroup, int* count, int* controlAndDefCount); void Group_QueryTree(Group* inGroup, big_scpacket* packet); void Group_QueryTreeAndControls(Group* inGroup, big_scpacket *packet); //////////////////////////////////////////////////////////////////////// struct Unit* Unit_New(struct World *inWorld, struct UnitSpec *inUnitSpec, char*& memory); void Unit_EndCalc(struct Unit *inUnit, int inNumSamples); void Unit_End(struct Unit *inUnit); void Unit_Dtor(struct Unit *inUnit); extern "C" { void Unit_ZeroOutputs(struct Unit *inUnit, int inNumSamples); } //////////////////////////////////////////////////////////////////////// void SendDone(struct ReplyAddress *inReply, const char *inCommandName); void SendDoneWithIntValue(struct ReplyAddress *inReply, const char *inCommandName, int value); void SendFailure(struct ReplyAddress *inReply, const char *inCommandName, const char *errString); void ReportLateness(struct ReplyAddress *inReply, float32 seconds); void DumpReplyAddress(struct ReplyAddress *inReplyAddress); int32 Hash(struct ReplyAddress *inReplyAddress); //////////////////////////////////////////////////////////////////////// extern "C" { int32 server_timeseed(); } //////////////////////////////////////////////////////////////////////// typedef bool (*AsyncStageFn)(World *inWorld, void* cmdData); typedef void (*AsyncFreeFn)(World *inWorld, void* cmdData); int PerformAsynchronousCommand ( World *inWorld, void* replyAddr, const char* cmdName, void *cmdData, AsyncStageFn stage2, // stage2 is non real time AsyncStageFn stage3, // stage3 is real time - completion msg performed if stage3 returns true AsyncStageFn stage4, // stage4 is non real time - sends done if stage4 returns true AsyncFreeFn cleanup, int completionMsgSize, void* completionMsgData ); //////////////////////////////////////////////////////////////////////// #endif <file_sep>#include "testApp.h" //-------------------------------------------------------------- void testApp::setup(){ ofSetBackgroundAuto(false); //ofSetVerticalSync(true); ofSetFrameRate(60); ofBackground(0, 0, 0); for (int i = 0; i < NUM; i++) { myRectangle[i].startPos.set(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); myRectangle[i].endPos.set(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); myRectangle[i].pct = 0.0f; myRectangle[i].shaper = 1.5; myRectangle[i].speed = ofRandom(0.002f, 0.01f); myRectangle[i].interpolateByPct(0.0); } } //-------------------------------------------------------------- void testApp::update(){ for (int i = 0; i < NUM; i++) { myRectangle[i].pct += myRectangle[i].speed; myRectangle[i].interpolateByPct(myRectangle[i].pct); if (myRectangle[i].pct > 1) { myRectangle[i].pct = 0; myRectangle[i].startPos = myRectangle[i].endPos; myRectangle[i].endPos.set(ofRandom(ofGetWidth()), ofRandom(ofGetHeight())); } } } //-------------------------------------------------------------- void testApp::draw(){ fadeToBlack(); ofEnableBlendMode(OF_BLENDMODE_ADD); for (int i = 0; i < NUM; i++) { myRectangle[i].draw(); } } //-------------------------------------------------------------- void testApp::fadeToBlack() { ofEnableBlendMode(OF_BLENDMODE_ALPHA); ofSetRectMode(OF_RECTMODE_CORNER); ofSetColor(0, 0, 0, 10); ofRect(0, 0, ofGetWidth(), ofGetHeight()); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<file_sep>#pragma once #include "ofMain.h" #include "ofxMultipleApp.h" class SceneA : public ofxSubApp { void setup(); void update(); void draw(); void show(); void hide(); void remove(); ofEasyCam cam; ofLight light; float rot; }; <file_sep>#include "testApp.h" void testApp::setup(){ //画面設定 ofBackgroundHex(0x000000); ofEnableAlphaBlending(); glEnable(GL_DEPTH_TEST); cam.setDistance(100); //シェーダー読込み shader.load("gradient"); } void testApp::update(){ } void testApp::draw(){ ofPushMatrix(); ofTranslate(ofGetWidth()/2, ofGetHeight()/2); cam.begin(); //シェーダー開始 shader.begin(); //シェーダーへ値を送信 shader.setUniform1f("x", 0.0f); shader.setUniform1f("y", 0.0f); shader.setUniform1f("w", 20.0f); shader.setUniform1f("h", 10.0f); // マウスのX座標の位置で、Blue成分の色を変更 shader.setUniform1f("color", (float)(mouseX / (float)ofGetWidth())); // 球体と立方体を描画 ofSphere(0, -22, 0, 20); ofBox(0, 22, 0, 40); // シェーダー終了 shader.end(); cam.end(); ofPopMatrix(); } void testApp::keyPressed(int key){ if (key == 'f') ofToggleFullscreen(); }<file_sep>#include "testApp.h" testApp::~testApp() { } void testApp::setup(){ ofSetupScreen(); ofBackground(0, 0, 0); ofSetVerticalSync(true); sampleRate = 44100; initialBufferSize = 512; ofSoundStreamSetup(2,0,this, sampleRate, initialBufferSize, 4); lAudio.assign(initialBufferSize, 0.0); rAudio.assign(initialBufferSize, 0.0); } void testApp::update(){ } void testApp::draw(){ ofSetColor(225); ofDrawBitmapString("MAXIMILIAN FM SYNTHESIS", 32, 32); ofNoFill(); // draw the left channel: ofPushStyle(); ofPushMatrix(); ofTranslate(32, 100, 0); ofSetColor(225); ofDrawBitmapString("Left Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 900, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (int i = 0; i < lAudio.size(); i++){ float x = ofMap(i, 0, lAudio.size(), 0, 900, true); ofVertex(x, 100 -lAudio[i]*100.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); // draw the right channel: ofPushStyle(); ofPushMatrix(); ofTranslate(32, 300, 0); ofSetColor(225); ofDrawBitmapString("Right Channel", 4, 18); ofSetLineWidth(1); ofRect(0, 0, 900, 200); ofSetColor(245, 58, 135); ofSetLineWidth(3); ofBeginShape(); for (int i = 0; i < rAudio.size(); i++){ float x = ofMap(i, 0, rAudio.size(), 0, 900, true); ofVertex(x, 100 -rAudio[i]*100.0f); } ofEndShape(false); ofPopMatrix(); ofPopStyle(); } void testApp::audioOut (float * output, int bufferSize, int nChannels){ for (int i = 0; i < bufferSize; i++){ float index, modFreq; ofMap(modFreq, 0, mouseX, 20, 8000); ofMap(index, 0, mouseY, 1, 2000); wave = car.sinewave(mouseY*mod.sinewave(mouseX/10)+440); //FM Synth mymix.stereo(wave, outputs, 0.5); lAudio[i] = output[i*nChannels ] = outputs[0]; rAudio[i] = output[i*nChannels + 1] = outputs[1]; } } void testApp::audioIn(float * input, int bufferSize, int nChannels){ for (int i = 0; i < bufferSize; i++){ } }<file_sep>#pragma once #include "ofMain.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed(int key); ofLight light; // ライト ofEasyCam cam; // カメラ ofShader shader; // シェーダー }; <file_sep>#pragma once #include "ofMain.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); ofSoundPlayer mySound; float * fft; int nBandsToGet; };<file_sep>#pragma once #include "ofMain.h" #include "ofxMaxim.h" class testApp : public ofBaseApp{ public: ~testApp(); void setup(); void update(); void draw(); void audioOut(float * input, int bufferSize, int nChannels); /* output method */ void audioIn(float * input, int bufferSize, int nChannels); /* input method */ int initialBufferSize; int sampleRate; double outputs[2]; double wave; ofxMaxiMix mymix; //Mixer ofxMaxiOsc car; //FM career ofxMaxiOsc mod; //FM modulator vector <float> lAudio; vector <float> rAudio; }; <file_sep>#ifndef _TEST_APP #define _TEST_APP //#define USE_IR // Uncomment this to use infra red instead of RGB cam... #include "ofxOpenNI.h" #include "ofMain.h" class testApp : public ofBaseApp{ public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); ofxOpenNIContext context; ofxDepthGenerator depth; ofxUserGenerator user; ofxHardwareDriver hardware; }; #endif <file_sep>#include "testApp.h" ofPoint pos; //-------------------------------------------------------------- void testApp::setup(){ ofBackground(255, 255, 255); ofSetCircleResolution(128); ofSetFrameRate(60); ofSetVerticalSync(true); ofSetBackgroundAuto(false); ofEnableAlphaBlending(); } //-------------------------------------------------------------- void testApp::update(){ pos.x = ofRandom(ofGetWidth()); pos.y = ofRandom(ofGetHeight()); } //-------------------------------------------------------------- void testApp::draw(){ if (ofDist(ofGetWidth()/2, ofGetHeight()/2, pos.x, pos.y) < 200) { ofSetColor(63, 255, 63, 127); } else { if (pos.x < ofGetWidth()/2) { ofSetColor(63, 63, 255, 127); } else { ofSetColor(255, 63, 63, 127); } } ofCircle(pos.x, pos.y, 10); } //-------------------------------------------------------------- void testApp::keyPressed(int key){ } //-------------------------------------------------------------- void testApp::keyReleased(int key){ } //-------------------------------------------------------------- void testApp::mouseMoved(int x, int y ){ } //-------------------------------------------------------------- void testApp::mouseDragged(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mousePressed(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::mouseReleased(int x, int y, int button){ } //-------------------------------------------------------------- void testApp::windowResized(int w, int h){ } //-------------------------------------------------------------- void testApp::gotMessage(ofMessage msg){ } //-------------------------------------------------------------- void testApp::dragEvent(ofDragInfo dragInfo){ }<file_sep>/* * MyRect.h * ofxKinect * * Created by <NAME> on 10/11/26. * Copyright 2010 __MyCompanyName__. All rights reserved. * */ #ifndef _MY_RECT #define _MY_RECT #include "ofMain.h" #include "ofxSuperCollider.h" class MyRect { public: MyRect(ofPoint p1, ofPoint p2); void update(); void draw(); ofPoint p1, p2; ofPoint rectPos; float width; float height; float pitchRatio[7]; float scanSpeed; float scanPos; float freq; float pan; float amp; float posZ; float speedZ; bool dead; ofxSCSynth* perc; }; #endif<file_sep>#pragma once #include "ofMain.h" class Rectangle { public: void draw(); void interpolateByPct(float pct); ofPoint pos; ofPoint startPos; ofPoint endPos; float pct; float shaper; };<file_sep>#include "testApp.h" using namespace cv; using namespace ofxCv; void testApp::setup() { //画面設定 ofBackgroundHex(0x000000); ofSetFrameRate(60); // Kinect初期化 kinect.setRegistration(true); kinect.init(); kinect.open(); // GUI gui.setup("ofxKinect Point Cloud", 0, 0, 360, ofGetHeight()); gui.addPanel("panel 1", 3); gui.setWhichColumn(0); gui.addToggle("Pick Color", "pick_color", false); gui.addSlider("Point size", "point_size", 2.0, 0.0, 10.0, false); gui.addSlider("Step size", "step", 2, 1, 10, true); gui.addSlider("Z position", "posz", -400, -1000, 0, true); gui.addSlider("Min Area Radius", "min_radius", 10, 0, 500, true); gui.addSlider("Max Area Radius", "max_radius", 400, 0, 500, true); gui.addSlider("Z threshold", "z_thresh", 1000, 0, 4000, true); gui.addSlider("CV Threshold", "cv_thresh", 200, 0, 255, true); gui.addSlider("CV Screen Offset", "cv_offset", 400, 0, 1000, true); gui.addSlider("Camera Tilt Angle", "angle", 0, -40, 40, true); gui.addDrawableRect("Kinect Depth", &depthImage, 160, 120); gui.loadSettings("controlPanelSettings.xml"); // SuerCollier初期設定 ofxSuperColliderServer::init(); reverb = new ofxSCSynth("reverb"); reverb->create(); // Rect表示関係 drawRect = false; drawWaitCount = 0; } void testApp::update() { kinect.update(); gui.update(); // カメラ角度設定 kinect.setCameraTiltAngle(gui.getValueI("angle")); // 輪郭抽出の範囲設定 contourFinder.setMinAreaRadius(gui.getValueI("min_radius")); contourFinder.setMaxAreaRadius(gui.getValueI("max_radius")); // 深度情報の画像から、輪郭抽出 if(kinect.isFrameNew()) { kinectImage.setFromPixels(kinect.getPixels(), kinect.width, kinect.height, OF_IMAGE_COLOR); depthImage.setFromPixels(kinect.getDepthPixels(), kinect.width, kinect.height, OF_IMAGE_GRAYSCALE); contourFinder.setThreshold(gui.getValueI("cv_thresh")); contourFinder.findContours(depthImage); } //分析した中心点を補完 if (contourFinder.size() == 2) { Point2f pos1, pos2; if(contourFinder.getCentroid(0).x < contourFinder.getCentroid(1).x) { pos1 = contourFinder.getCentroid(0); pos2 = contourFinder.getCentroid(1); } else { pos1 = contourFinder.getCentroid(1); pos2 = contourFinder.getCentroid(0); } lastPos1 += (pos1 - lastPos1) * 0.05; lastPos2 += (pos2 - lastPos2) * 0.05; } //描画した四角形を追加 if (contourFinder.size() == 2 && !drawRect) { drawWaitCount++; if (drawWaitCount > 120) { drawRect = true; } } else if (drawRect) { ofPoint pos1, pos2; pos1.x = lastPos1.x; pos2.x = lastPos2.x; pos1.y = lastPos1.y; pos2.y = lastPos2.y; MyRect* r = new MyRect(pos1, pos2); rects.push_back(r); drawRect = false; drawWaitCount = 0; } //四角形更新 for(list <MyRect *>::iterator it = rects.begin(); it != rects.end();){ (*it)->update(); if ((*it)->dead) { delete *it; it = rects.erase(it); } else { ++it; } } } void testApp::draw() { // ドラッグで視線を変更できるように(ofEasyCam) easyCam.begin(); glEnable(GL_DEPTH_TEST); //ポイントクラウドの描画 ofPushMatrix(); ofScale(1, -1, -1); ofTranslate(0, 0, gui.getValueI("posz")); drawPointCloud(); // CV描画 ofTranslate(0, 0, gui.getValueI("cv_offset")); drawCv(); ofPopMatrix(); glDisable(GL_DEPTH_TEST); easyCam.end(); // GUI表示 ofSetLineWidth(1); gui.draw(); } void testApp::drawPointCloud() { // 画面の幅と高さ int w = 640; int h = 480; // メッシュを生成 ofMesh mesh; mesh.setMode(OF_PRIMITIVE_POINTS); // 設定した間隔で、画面の深度情報と色を取得してメッシュの頂点に設定 int step = gui.getValueI("step"); for(int y = 0; y < h; y += step) { for(int x = 0; x < w; x += step) { if(kinect.getDistanceAt(x, y) < gui.getValueI("z_thresh")) { if (gui.getValueB("pick_color")) { mesh.addColor(kinect.getColorAt(x,y)); } else { mesh.addColor(ofFloatColor(255,255,255)); } mesh.addVertex(kinect.getWorldCoordinateAt(x, y)); } } } // メッシュの頂点を描画 glPointSize(gui.getValueF("point_size")); ofPushMatrix(); ofEnableBlendMode(OF_BLENDMODE_ADD); mesh.drawVertices(); ofPopMatrix(); } void testApp::drawCv() { ofPushMatrix(); ofEnableBlendMode(OF_BLENDMODE_ADD); ofTranslate(-kinect.width/2, -kinect.height/2, 0); // 深度情報を表示 ofSetColor(100, 100, 100); kinect.drawDepth(0, 0, kinect.width, kinect.height); // CV 輪郭線分析画面の表示 ofPushMatrix(); // 輪郭線を表示 ofTranslate(0, 0, -1); ofSetColor(100, 100, 100); ofSetLineWidth(2); contourFinder.draw(); // 輪郭の中心位置に円を配置 ofSetColor(255, 127, 0); for (int i = 0; i < contourFinder.size(); i++) { Point2f pos = contourFinder.getCentroid(i); ofCircle(pos.x, pos.y, 3); } //現在描画中の四角形を表示 if (contourFinder.size() == 2) { //補完されたBlobsの中心 ofFill(); ofSetColor(255, 0, 0); ofCircle(lastPos1.x, lastPos1.y, 3); ofCircle(lastPos2.x, lastPos2.y, 3); //四角形 ofNoFill(); ofSetColor(200, 200, 200); ofBeginShape(); ofVertex(lastPos1.x, lastPos1.y); ofVertex(lastPos2.x, lastPos1.y); ofVertex(lastPos2.x, lastPos2.y); ofVertex(lastPos1.x, lastPos2.y); ofEndShape(true); } //listに格納した四角形の描画 ofFill(); list <MyRect*>::iterator it; for (it = rects.begin(); it != rects.end(); ++it) { (*it)->draw(); } ofPopMatrix(); ofPopMatrix(); } void testApp::exit() { // Kinect終了 kinect.close(); } void testApp::keyPressed (int key) { if (key == ' ') { gui.toggleView(); } if (key == 'f') { ofToggleFullscreen(); } } void testApp::mouseDragged(int x, int y, int button){ gui.mouseDragged(x, y, button); } void testApp::mousePressed(int x, int y, int button){ gui.mousePressed(x, y, button); } void testApp::mouseReleased(int x, int y, int button){ gui.mouseReleased(); } <file_sep>#include "rectangle.h" void Rectangle::draw() { ofFill(); ofSetRectMode(OF_RECTMODE_CENTER); ofSetColor(31,127,255); ofRect(pos.x, pos.y, 20,20); }<file_sep>/* ofxPd v0.03 Copyright 2010 by <NAME>, <NAME>. this code uses code from pdlib "AudioOutput.h", so pdlib license is included here: AudioOutput.h PdLib v0.3 Copyright 2010 <NAME>. All rights reserved. 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. THIS SOFTWARE IS PROVIDED BY BRYAN SUMMERSETT ``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 BRYAN SUMMERSETT 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. The views and conclusions contained in the software and documentation are those of the authors and should not be interpreted as representing official policies, either expressed or implied, of Bryan Summersett. */ #include "ofMain.h" #include "ofxThread.h" class ofxPd : public ofxThread { public: /// lib_dir is the directory in which to look for pd files /// in_chans, out_chans, bitrate and block_size are passed to Pd engine /// if in_chans is >0, you should call the input+output version of renderAudio to pass /// input audio to the Pd engine void setup( string lib_dir, int in_chans = 0, int out_chans = 2, int bitrate = 44100, int block_size = 64 ); /// add the given file to the list to be opened on startup void addOpenFile( string file_path ); /// add the given path to the search path void addSearchPath( string search_path ); /// start pd core; DSP (sound processing) is started separately void start(); /// stop pd core void stop(); /// start DSP (sends 'pd dsp 1' message) void startDSP() { sendRawMessage("; pd dsp 1" ); } /// stop DSP (sends 'pd dsp 0' message) void stopDSP() { sendRawMessage("; pd dsp 0" ); } /// send a message to the pd engine void sendRawMessage( const string& message ); /// send the given float to the given receive target in pd void sendFloat( const string& receive_target, float number ); /// callback for audio rendering (output only) void renderAudio( float* output, int bufferSize, int nChannels ); /// callback for audio rendering (input and output) void renderAudio( float * input, float* output, int bufferSize, int nChannels ); private: // the thing to run in a thread void threadedFunction(); string lib_dir; vector <string> externs; vector <string> search_path; vector <string> open_files; int out_chans; int in_chans; int bitrate; int block_size; }; <file_sep>#pragma once #include "ofMain.h" #include "ofxMultipleApp.h" #include "SceneA.h" #include "SceneB.h" #include "SceneC.h" class testApp : public ofBaseApp { public: void setup(); void update(); void draw(); void keyPressed (int key); void keyReleased(int key); void mouseMoved(int x, int y ); void mouseDragged(int x, int y, int button); void mousePressed(int x, int y, int button); void mouseReleased(int x, int y, int button); void windowResized(int w, int h); SceneA *sceneA; SceneB *sceneB; SceneC *sceneC; ofxSubApp *currentApp; };
6db30ab89eff30fb4a6515a7257d624f19ed0404
[ "C", "C++" ]
43
C++
yiiiko/openFrameworks-examples
876e6fb79e9a184e1e29ff27543e92512330b578
7e8e4c16c400d40776aa339585ec7ff869a8dcaa
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PR_TE_T1_E3 { class Program { /* Solicitar un año al usuario y devolverle si se trata de un año bisiesto. Ejemplo: 1997 -> “1997 no es un año bisiesto” */ static void Main(string[] args) { // Declaración de variables #region Declaración de variables string strEntrada; double dblAño; string strResultado = "no es bisiesto."; #endregion // Solicitud de datos al usuario #region Solicitud de datos al Usuario do { Console.WriteLine("Por favor ingrese un año"); strEntrada = Console.ReadLine(); } while (!esAñoValido(strEntrada)); #endregion // Procesamiento de datos #region Procesamiento de datos dblAño = double.Parse(strEntrada); if (dblAño % 4 == 0) { strResultado = " es bisiesto."; } if (dblAño%100 == 0) { if(dblAño%400 == 0) { strResultado = " es bisiesto."; } else { strResultado = " es secular común."; } } #endregion // Muestra resultado Console.WriteLine("El año " + dblAño + strResultado); Console.ReadKey(); } /// <summary> /// Función que devuelve verdadero si una cadena de texto correponde a un número real /// </summary> /// <param name="unNumero">Cadena de texto </param> /// <returns>Verdadero si la cadena de texto puede ser convertida a número</returns> static bool esAñoValido(string unNumero) { try { if (double.Parse(unNumero)>=0) { return true; } } catch { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Por favor ingrese un número válido"); Console.Beep(); System.Threading.Thread.Sleep(600); Console.ResetColor(); Console.Clear(); } return false; } } }
9c1fac2b59320d06c5856c74d1cb49984944c8e9
[ "C#" ]
1
C#
MynorXico/PR_TE_T1_E3
bcc762328ad75928ee9b3b618571819347c29656
40e9904d1f6273fd95371e5b4be556e5d755181c
refs/heads/master
<repo_name>hentsR/CoreNet<file_sep>/README.md # CoreNet ASP.Net MVC5 Project to build an automated CMS Backoffice <file_sep>/Mikolo.CoreNet.Profil/Service/IProfilService.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Mikolo.CoreNet.Profil.Service { public interface IProfilService { } }
85802f272c1079279a83283916e35f8133048a16
[ "Markdown", "C#" ]
2
Markdown
hentsR/CoreNet
0aa2297b64a19663e61eb7800b1016d7711fdf98
7821a6c18247607ec2b9b0ed1c8221489aa2e854
refs/heads/master
<repo_name>alarky/isucon3_perl<file_sep>/script/init.sh #!/bin/sh . /home/isucon/env.sh cd /home/isucon/webapp/perl; /home/isucon/local/perl-5.18/bin/carton exec perl /home/isucon/webapp/perl/script/initialize.pl >> /tmp/initialize.log 2>&1
877e30c621cf9bb0b0b1f8f6af14ef37ead929c4
[ "Shell" ]
1
Shell
alarky/isucon3_perl
3de7049ec80f13111c47c2b5418ec3da382e6a15
15208cf2eab196b99cfa0c78bde950e0f28e4ea3
refs/heads/master
<repo_name>Jessiecaicai/FirstProject<file_sep>/src/main/resources/static/js/login.js function IbtnEnter_onclick() { checklogin(); return false; } function checklogin() { if ($("#TxtUserName").val() == "") { alert("用户名不能为空!"); $("#TxtUserName").focus(); return false; } if ($("#TxtPassword").val() == "") { alert("密码不能为空!"); $("#TxtPassword").focus(); return false; } $.ajax({ type: "POST", url: "login" , data: JSON.stringify({ "id" : id, "password" : <PASSWORD> }), traditional : false, cache : false, dataType:'json', //contentType:'application/json; charset=UTF-8', success: function (data) { if (data.success==true) { console.log(data.success); window.location.href = "index"; //location.href = "index.aspx"; // return true; } else { alert("请确认您输入的用户名或密码输入是否正确!"); $("#TxtUserName").val(""); $("#TxtPassword").val(""); $("#TxtUserName").focus(); return false; } } }) } <file_sep>/src/main/java/hfutonline/controller/BringInController.java package hfutonline.controller; import hfutonline.service.BringInService; /** * Created by lenovo on 2017/9/12. * * @author Jessie * */ import hfutonline.entity.BringIn; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import javax.annotation.Resource; import hfutonline.dto.Result; import hfutonline.entity.BringIn; import hfutonline.exception.BringInException; import hfutonline.service.BringInService; @Controller public class BringInController { private static final Logger logger = LoggerFactory.getLogger(BringInController.class); @Resource private BringInService bringInService; /** * way:add * * @param bringIn * @return * @author:Jessie */ @RequestMapping(value="/addBringInfo",method=RequestMethod.POST) @ResponseBody public Result<String> addBringIn(@RequestBody BringIn bringIn) { try { bringInService.addBringIn(bringIn); }catch (BringInException e){ logger.error(e.getMessage(), e); e.printStackTrace(); } logger.info("添加成功", bringIn); return new Result<String>(true, "提交成功", null); } /** * way:delete * * @param bringIn * @return * @author Jessie */ @RequestMapping(value="/deleteBringInfo",method=RequestMethod.POST) @ResponseBody public Result<String> deleteBringIn(@RequestBody BringIn bringIn) { try{ bringInService.deleteBringIn(bringIn.getId()); }catch(BringInException e){ logger.error(e.getMessage(),e); e.printStackTrace(); } logger.info("删除成功",bringIn); return new Result<String>(true,"删除成功",null); } @RequestMapping(value = "/updateBringInfo",method = RequestMethod.POST) @ResponseBody public Result<String> updateBringIn(@RequestBody BringIn bringIn){ try{ bringInService.updateBringIn(bringIn); }catch(BringInException e){ logger.error(e.getMessage(),e); e.printStackTrace(); } logger.info("修改成功",bringIn); return new Result<String>(true,"更新成功",null); } @RequestMapping(value="/listBringInById",method=RequestMethod.POST) @ResponseBody public Result<List<BringIn>> list(@RequestBody BringIn bringIn){ try{ List<BringIn> listBringInById=bringInService.listBringInById(bringIn.getId()); logger.info("根据id查找成功",listBringInById); return new Result<List<BringIn>>(true,"根据id查找成功",listBringInById); }catch(BringInException e){ logger.error(e.getMessage(),e); e.printStackTrace(); return new Result<List<BringIn>>(false,e.getMessage(),null); } } @RequestMapping(value = "/bringIn/list", method = RequestMethod.POST) @ResponseBody public Result<List<BringIn>> list() { System.out.println("cfvgbhjnmk"); try { List<BringIn> list = bringInService.listAll(); logger.info("获取新闻列表成功", list); System.out.println(list.get(1).getName()); return new Result<List<BringIn>>(true, "获取招聘人员列表成功", list); } catch (BringInException e) { logger.error(e.getMessage(), e); e.printStackTrace(); return new Result<List<BringIn>>(false, e.getMessage(), null); } } /* @RequestMapping(value="/bringIn/page",method = RequestMethod.POST) @ResponseBody public Result<List<BringIn>> listPage(@RequestBody Page page){ Integer start=0; try{ try { start = Integer.parseInt(); } catch (NumberFormatException e) { // 当浏览器没有传参数start时 } List<BringIn> listPage=bringInService.page(start,10); logger.info("分页成功",listPage); return new Result<List<BringIn>>(true,"分页成功",listPage); }catch (BringInException e){ logger.error(e.getMessage(),e); e.printStackTrace(); return new Result<List<BringIn>>(false,e.getMessage(),null); } }*/ @RequestMapping(value="/bringIn/total",method = RequestMethod.POST) @ResponseBody public Integer total(){ Integer total; try{ total=bringInService.total(); logger.info("计算总数成功",total); return total; }catch (BringInException e){ logger.error(e.getMessage(),e); e.printStackTrace(); return 0; } } } <file_sep>/src/main/java/hfutonline/dao/UserDao.java package hfutonline.dao; import org.apache.ibatis.annotations.*; import java.util.List; import hfutonline.dao.dynamicSQLProvider.DynamicSQLProvider; import hfutonline.entity.User; /** * Created by lenovo on 2017/9/11. */ @Mapper public interface UserDao { @Select("select * from user where id=#{id}") @Results({ @Result(property = "id", column = "id"), @Result(property = "userName", column = "userName"), @Result(property = "password", column = "password"), @Result(property = "phoneNumber", column = "phoneNumber"), @Result(property = "qq", column = "qq") }) User queryById(@Param("id") Integer id); @Select("select * from user where userName=#{userName}") @Results({ @Result(property = "id", column = "id"), @Result(property = "userName", column = "userName"), @Result(property = "password", column = "password"), @Result(property = "phoneNumber", column = "phoneNumber"), @Result(property = "qq", column = "qq") }) User queryByUserName(@Param("userName") String userName); /** * 添加一个学生对象 * add:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @param user * @return * @since JDK 1.8 */ @Insert("insert ignore into user(userName,phoneNumber,qq) values(#{user.userName}, #{user.phoneNumber}, #{user.qq})") Integer add(@Param("user") User user); /** * 学生列表 * listAll:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @return * @since JDK 1.8 */ @Select("select id, userName, phoneNumber, qq from user") @Results({ @Result(property = "id", column = "id"), @Result(property = "userName", column = "userName"), @Result(property = "phoneNumber", column = "phoneNumber"), @Result(property = "qq", column = "qq"), }) List<User> listAll(); /** * 根据学生ID号删除学生 * deleteById:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @param id * @return * @since JDK 1.8 */ @Delete("delete from user where id=#{id}") Integer deleteById(@Param("id") Integer id); /** * 更新学生信息 * update:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @param user * @return * @since JDK 1.8 */ @UpdateProvider(type = DynamicSQLProvider.class, method = "update") Integer update(@Param("user") User user); } <file_sep>/src/main/java/hfutonline/entity/BringIn.java package hfutonline.entity; import java.util.Date; /** * Created by lenovo on 2017/9/11. */ public class BringIn { private Integer id; private String name; private Integer people; private Date time; private String title; private String type; private String location; private String worktime; private String workplace; private String pay; private String deadline; private String sex; private String grade; private String place; private String need; public Integer getId() { return id; } public void setId(Integer id){ this.id=id; } public String getName(){ return name; } public void setName(String name){ this.name=name; } public Integer getPeople(){ return people; } public void setPeople(Integer people){ this.people=people; } public Date getTime(){ return time; } public void setTime(Date time){ this.time=time; } public String getTitle(){ return title; } public void setTitle(String title){ this.title=title; } public String getType(){ return type; } public void setType(String type){ this.type=type; } public String getLocation(){ return location; } public void setLocation(String location){ this.location=location; } public String getWorktime(){ return worktime; } public void setWorktime(String worktime){ this.worktime=worktime; } public String getWorkplace(){ return workplace; } public void setWorkplace(String workplace){ this.workplace=workplace; } public String getPay(){ return pay; } public void setPay(String pay){ this.pay=pay; } public String getDeadline(){ return deadline; } public void setDeadline(String deadline){ this.deadline=deadline; } public String getSex(){ return sex; } public void setSex(String sex){ this.sex=sex; } public String getGrade(){ return grade; } public void setGrade(String grade){ this.grade=grade; } public String getPlace(){ return place; } public void setPlace(String place){ this.place=place; } public String getNeed(){ return need; } public void setNeed(String need){ this.need=need; } @Override public String toString() { return "BringIn[id=" + id + " , name=" + name + " , people="+people+",time="+time+",title="+title+",type="+type+"," + "location="+location+",worktime="+worktime+",workplace="+workplace+",pay="+pay+",deadline="+deadline+",sex=" +sex+",grade="+grade+",place="+place+",need="+need+"]"; } } <file_sep>/src/main/java/hfutonline/service/UserService.java package hfutonline.service; import java.util.List; import hfutonline.entity.User; import hfutonline.exception.UserException; /** * Created by lenovo on 2017/9/10. */ public interface UserService { public void login(User user) throws UserException; public void register(User user) throws UserException; public List<User> listAll() throws UserException; public void addUser(User user) throws UserException; public void deleteUser(Integer id) throws UserException; public void updateUser(User user) throws UserException; } <file_sep>/README.md # FirstProject the first project by springboot. <file_sep>/src/main/java/hfutonline/controller/UserController.java package hfutonline.controller; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.*; import java.util.List; import javax.annotation.Resource; import javax.servlet.http.HttpSession; import hfutonline.dto.Result; import hfutonline.entity.User; import hfutonline.exception.UserException; import hfutonline.service.UserService; /** * Created by lenovo on 2017/9/10. */ @Controller public class UserController { private static final Logger logger = LoggerFactory.getLogger(UserController.class); @Resource private UserService userService; /** * 登录 * login:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author Jessie * @return * @since JDK 1.8 */ @ResponseBody @RequestMapping(value = "/login", method = RequestMethod.POST) //public Result<String> login( public Result<String> login( //@ModelAttribute User user){ //System.out.print(user.getId()); @RequestBody User user,HttpSession session) { try { userService.login(user); } catch (UserException e) { logger.error(e.getMessage(), e); e.printStackTrace(); return new Result<String>(false, "登录失败", null); } logger.info("登录成功:" + user); return new Result<String>(true, "登录成功", null); } /** * 登录界面 * index:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @return * @since JDK 1.8 */ //@ResponseBody @RequestMapping(value = "/") public String login() { return "/login"; } /** * 首页 * home:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @return * @since JDK 1.8 */ @RequestMapping(value="/admin-main") public String home() { return "/admin-main"; } @RequestMapping(value="/admin-left") public String admin() { return "/admin-left"; } @RequestMapping(value="/index") public String index() { return "/index"; } @RequestMapping(value="/manage") public String manage() { return "/manage"; } /** * 注册 * register:(这里用一句话描述这个方法的作用). <br/> * TODO(这里描述这个方法适用条件 – 可选).<br/> * TODO(这里描述这个方法的执行流程 – 可选).<br/> * TODO(这里描述这个方法的使用方法 – 可选).<br/> * TODO(这里描述这个方法的注意事项 – 可选).<br/> * * @author huangting * @param user * @return * @since JDK 1.8 */ @RequestMapping(value = "/user/" + "register", method = RequestMethod.POST) @ResponseBody public Result<String> register( @RequestBody User user) { //logger.info(user.toString()); try { userService.register(user); } catch (UserException e) { logger.error(e.getMessage(), e); e.printStackTrace(); return new Result<String>(false, e.getMessage(), null); } logger.info("注册成功", user); return new Result<String>(true, "注册成功", null); } @RequestMapping(value = "/user/list", method = RequestMethod.POST) @ResponseBody public Result<List<User>> list() { try { List<User> list = userService.listAll(); logger.info("获取新闻列表成功", list); return new Result<List<User>>(true, "获取学生列表成功", list); } catch (UserException e) { logger.error(e.getMessage(), e); e.printStackTrace(); return new Result<List<User>>(false, e.getMessage(), null); } } } <file_sep>/src/main/java/hfutonline/dao/dynamicSQLProvider/DynamicSQLProvider.java package hfutonline.dao.dynamicSQLProvider; import hfutonline.entity.User; import hfutonline.entity.BringIn; import org.apache.ibatis.jdbc.SQL; /** * 提供动态SQL * ClassName: DynamicSQLProvider <br/> * Function: TODO ADD FUNCTION. <br/> * Reason: TODO ADD REASON(可选). <br/> * * @author Jessie * @version * @since JDK 1.8 */ public class DynamicSQLProvider { /* public String update(User user){ return new SQL() { { UPDATE("user"); if (user.getUserName() != null) { SET("userName = #{user.userName}"); } if (user.getPhoneNumber() != null) { SET("phoneNumber = #{user.phoneNumber}"); } if (user.getQq() != null) { SET("qq = #{user.qq}"); } if (user.getPassword() != null) { SET("password = #{<PASSWORD>}"); } WHERE("id = #{user.id}"); } }.toString(); } */ public String update(BringIn bringIn){ return new SQL(){ { UPDATE("bringIn"); if (bringIn.getName()!=null){ SET("name=#{bringIn.name}"); } if (bringIn.getDeadline()!=null){ SET("deadline=#{bringIn.deadline}"); } if (bringIn.getGrade()!=null){ SET("grade=#{bringIn.grade}"); } if (bringIn.getLocation()!=null){ SET("location=#{bringIn.location}"); } if (bringIn.getNeed()!=null){ SET("need=#{bringIn.need}"); } if (bringIn.getPay()!=null){ SET("pay=#{bringIn.pay}"); } if (bringIn.getPeople()!=null){ SET("people=#{bringIn.people}"); } if (bringIn.getPlace()!=null){ SET("place=#{bringIn.place}"); } if (bringIn.getSex()!=null){ SET("sex=#{bringIn.sex}"); } if (bringIn.getTime()!=null){ SET("time=#{bringIn.time}"); } if (bringIn.getTitle()!=null){ SET("title=#{bringIn.title}"); } if (bringIn.getType()!=null){ SET("type=#{bringIn.type}"); } if (bringIn.getWorkplace()!=null){ SET("workplace=#{bringIn.workplace}"); } if (bringIn.getWorktime()!=null){ SET("worktime=#{bringIn.worktime}"); } WHERE("id=#{bringIn.id}"); } }.toString(); } } <file_sep>/src/main/java/hfutonline/exception/UserException.java package hfutonline.exception; /** * Created by lenovo on 2017/9/10. */ public class UserException extends Exception{ private static final long serialVersionUID = 1L; public UserException(String message, Throwable cause) { super(message, cause); } public UserException(String message) { super(message); } } <file_sep>/src/main/resources/static/js/index.js function addData(){ // alert( $("#name").val()); $.ajax({ url: '/addBringInfo', type: 'POST', dataType: 'json', //data: $('#form1').serialize(), /* data: { "name": $("#name").val(), "type":$("#type").val(), id:0 },*/ data: JSON.stringify({ "name":$("#name").val(), "people":$("#people").val(), "time":$("#time").val(), "title":$("#title").val(), "type":$("#type").val(), "location":$("#location").val(), "worktime":$("#worktime").val(), "workplace":$("#workplace").val(), "pay":$("#pay").val(), "deadline":$("#deadline").val(), "sex":$("#sex").val(), "grade":$("#grade").val(), "place":$("#place").val(), "need":$("#need").val() }), traditional : false, cache : false, async: false, contentType : 'application/json; charset=UTF-8', // bedforeSend: $("#table1").html('加载中...请稍后!'), // success: $('form').submit(function () { // alert($(this).serialize()); // return false; // }), success: function (result) { // console.log(databack); // alert("成功!"); if(result.success){ alert("提交成功!") } // alert($(this).serialize()); }, error: function () { console.log("提交失败,请重试!"); alert("失败了"); } }) }
27a67540a174ce396a6a10b19c5c357456d7f308
[ "JavaScript", "Java", "Markdown" ]
10
JavaScript
Jessiecaicai/FirstProject
b7fa9b0d4999af8c69d6f3368410ed2f7e0dbf46
e197f04b233417ee1da6e0e253776685c4ad5ead
refs/heads/master
<file_sep># HackTech2018 -- TO DO -- 1. Find a way to use computer camera with python 2. Take picture with that camera 3. Compare picture with "base pic" <file_sep>import tkinter from PIL import ImageTk, Image import facetest def go(): label1 = tkinter.Label(window, text= "Loading ... When the camera comes, hold your product up and press 'q' when ready").pack() names = ["Kaushik", "Radhika", "Maegan", "Chris"] namesMoney = [20,20,20,20] facetest.deletePersonGroup() facetest.createPersonGroup() ids = facetest.createPerson(names) facetest.trainGroup() facetest.getItem() costArr = facetest.itemDetect("https://chrishacktech.blob.core.windows.net/photos/blobItem.jpg") cost = facetest.parseCost(costArr) print (cost) if (cost == -1): cost = input("Sorry, number not recognized. Please type in.") testImage = facetest.captureImage() foundName = facetest.detectFace(testImage) detection = "We detected " + foundName + ". Searching in database..." print (detection) label2 = tkinter.Label(window, text= detection) i = 0 while i < len(names): if (names[i] == foundName): break i = i + 1 if i < len(names): costFactor = "Your current bank account balance is " + str(namesMoney[i]) + " . Total cost is " + str(cost) print (costFactor) label3 = tkinter.Label(window, text= costFactor) newBankBalance = int(namesMoney[i]) - int(cost) if (newBankBalance < 0): label4 = tkinter.Label(window, text = "Transaction denied. You have no more funds.") print("Transaction denied. You have no more funds.") else: label5 = tkinter.Label(window, text = "Transaction accepted. Your FacePay balance is now " + str(newBankBalance)) print("Transaction accepted. Your FacePay balance is now " + str(newBankBalance)) namesMoney[i] = newBankBalance else: print ("We couldn't find you. Please try again.") window = tkinter.Tk() window.title("FacePay") b1 = tkinter.Button(window, text= "New user") b1.pack() b2 = tkinter.Button(window, text= "Existing user", command = lambda: go()) b2.pack() window.mainloop() <file_sep>import time import requests #import cv2 import operator #import numpy as np # Import library to display results #import matplotlib.pyplot as plt #from matplotlib.lines import Line2D # # %matplotlib inline # Display images within Jupyter # Variables _url = 'https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/RecognizeText' _key = '3197c93f163c49e2a07e2a1c7e7ac5f4' # _url = 'https://westus.api.cognitive.microsoft.com/vision/v1.0/RecognizeText' # _key = '<KEY>' _maxNumRetries = 10 def processRequest( json, data, headers, params ): """ Helper function to process the request to Project Oxford Parameters: json: Used when processing images from its URL. See API Documentation data: Used when processing image read from disk. See API Documentation headers: Used to pass the key information and the data type request """ retries = 0 result = None while True: response = requests.request( 'post', _url, json = json, data = data, headers = headers, params = params ) if response.status_code == 429: print( "Message: %s" % ( response.json() ) ) if retries <= _maxNumRetries: time.sleep(1) retries += 1 continue else: print( 'Error: failed after retrying!' ) break elif response.status_code == 202: result = response.headers['Operation-Location'] else: print( "Error code: %d" % ( response.status_code ) ) print( "Message: %s" % ( response.json() ) ) break return result def getOCRTextResult( operationLocation, headers ): """ Helper function to get text result from operation location Parameters: operationLocation: operationLocation to get text result, See API Documentation headers: Used to pass the key information """ retries = 0 result = None while True: response = requests.request('get', operationLocation, json=None, data=None, headers=headers, params=None) if response.status_code == 429: print("Message: %s" % (response.json())) if retries <= _maxNumRetries: time.sleep(1) retries += 1 continue else: print('Error: failed after retrying!') break elif response.status_code == 200: result = response.json() else: print("Error code: %d" % (response.status_code)) print("Message: %s" % (response.json())) break return result def showResultOnImage( result, img ): """Display the obtained results onto the input image""" img = img[:, :, (2, 1, 0)] fig, ax = plt.subplots(figsize=(12, 12)) ax.imshow(img, aspect='equal') lines = result['recognitionResult']['lines'] for i in range(len(lines)): words = lines[i]['words'] for j in range(len(words)): tl = (words[j]['boundingBox'][0], words[j]['boundingBox'][1]) tr = (words[j]['boundingBox'][2], words[j]['boundingBox'][3]) br = (words[j]['boundingBox'][4], words[j]['boundingBox'][5]) bl = (words[j]['boundingBox'][6], words[j]['boundingBox'][7]) text = words[j]['text'] x = [tl[0], tr[0], tr[0], br[0], br[0], bl[0], bl[0], tl[0]] y = [tl[1], tr[1], tr[1], br[1], br[1], bl[1], bl[1], tl[1]] line = Line2D(x, y, linewidth=3.5, color='red') ax.add_line(line) ax.text(tl[0], tl[1] - 2, '{:s}'.format(text), bbox=dict(facecolor='blue', alpha=0.5), fontsize=14, color='white') plt.axis('off') plt.tight_layout() plt.draw() plt.show() # URL direction to image #urlImage = 'https://s3.us-east-2.amazonaws.com/hacktech2018/IMG_1043.jpg' urlImage = 'https://drive.google.com/open?id=1vlV-OGBUldLmvdVxgljRxv27EYrJsdpP' # Computer Vision parameters params = { 'handwriting' : 'true'} headers = dict() headers['Ocp-Apim-Subscription-Key'] = _key headers['Content-Type'] = 'application/json' json = { 'url': urlImage } data = None result = None operationLocation = processRequest(json, data, headers, params) if (operationLocation != None): headers = {} headers['Ocp-Apim-Subscription-Key'] = _key while True: time.sleep(1) result = getOCRTextResult(operationLocation, headers) if result['status'] == 'Succeeded' or result['status'] == 'Failed': break if result is not None and result['status'] == 'Succeeded': print(result) # Load the original image, fetched from the URL #arr = np.asarray( bytearray( requests.get( urlImage ).content ), dtype=np.uint8 ) # img = cv2.cvtColor( cv2.imdecode( arr, -1 ), cv2.COLOR_BGR2RGB ) #showResultOnImage( result, img ) <file_sep>import facetest import random import time def newUserOrientation(): nameInput = input("Ok, please give me your name") numberInput = input("And please give me your number too [10-digits please]") names.append(nameInput) namesMoney.append(20.00) namesNumbers.append(numberInput) facetest.createPerson(names) print("Ok, smile for the camera and press 'q' when ready!") facetest.trainGroup() print ("Ok, please wait. Due to legal restrictions, we can only call have 20 API calls a minute.") time.sleep(60) print ("You may now proceed") facetest.createPersonGroup() names = ["<NAME>", "<NAME>", "<NAME>", "<NAME>"] namesMoney = [20.00,20.00,20.00,20.00] namesNumbers = ["4088910387", "6506563747", "5714251850", "4083488437"] existingUser = ['existing', 'exist', 'Existing', 'existing user', 'Existing user', 'Existing User', 'E', 'e'] newUser = ['new', 'New', 'new user', 'New user', 'New User', 'N', 'n'] userInput = input("Are you a new user or existing user?") if (userInput in newUser): newUserOrientation() else: facetest.createPerson(names) facetest.trainGroup() while True: numItems = input("Tell me, how many items are you looking to buy today?") items, prices = facetest.processItems(numItems) cost = facetest.determineCost(prices) print ("Press q to take a picture of yourself") personImage = facetest.captureImage() foundName = facetest.detectFace(personImage) print ("Is that you, " + foundName + "?") i = 0 while i < len(names): if(names[i] == foundName): break i = i + 1 if i <= len(names): if (i == len(names)): i = i - 1 print("Here is your receipt: ") facetest.processReceipt(items, prices) print ("Here is your total balance: " + str(namesMoney[i])) newBankBalance = float(namesMoney[i]) - float(cost) if (newBankBalance < 0): newBankBalance = 0 if (newBankBalance == 0): print ("Please keep in mind that you are broke. You cannot afford whatever you are buying. This session has now terminated") break else: userDet = input("Your final balance is " + str(newBankBalance) + ". Would you like to complete the transaction? [Y/N]") if (userDet == "Y"): print("Transaction accepted. Your FacePay balance is now " + str(newBankBalance)) namesMoney[i] = newBankBalance else: print ("This session has ended.") break else: print("Sorry, we couldn't find you. Please try again") userDetermine = input("This session has ended. Do you wish to continue? [Y/N]") if (userDetermine != "Y"): break <file_sep>import logging from random import randint from flask import Flask, render_template from flask_ask import Ask, statement, question, session app = Flask(__name__) ask = Ask(app, "/") logging.getLogger("flask_ask").setLevel(logging.DEBUG) global state global numItemsScanned @ask.launch def new_game(): global state state = 0 return question(render_template('welcome')) @ask.intent("YesIntent") def useYes(): global state if state == 0: state = 1 return question(render_template('user')) elif state == 1: state = 2 return question(render_template('exist')) elif state == 2: state = 3 return question(render_template('scan')) @ask.intent("AnswerIntent", convert={'num': int}) def numItems(num): global state if state == 2: return statement(render_template('scan', num=num)) numItemsScanned = num return question(render_template('quit')) @ask.intent("NoIntent") def useNo(): global state if state == 0: return question(render_template('nocout')) elif state == 1: return question(render_template('register')) return question(render_template('quit')) # @ask.intent("StopIntent") # def quitFunct(): # return if __name__ == '__main__': app.run(debug=True)<file_sep>#change back to python 3.6 later (only changes involve urllib) import requests import json import urllib.request, urllib.parse, urllib.error import cv2 from azure.storage.blob import ContentSettings from azure.storage.blob import BlockBlobService import imagerecognition import face_pay #import urllib, urllib2 #hard coded values key = "1f3021aa1ab74cedaf685826f631ab5a" headers= {"Host": 'westcentralus.api.cognitive.microsoft.com', "Content-Type":'application/json','Ocp-Apim-Subscription-Key': key } personGroupId = "test123" #create person group def createPersonGroup(): url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/"+ personGroupId #not used elsewhere personGroupDisplayName = "My Group" body = { "name": personGroupDisplayName } response = requests.put(url=url,json=body,headers=headers) #delete person group removes everything related to it def deletePersonGroup(): url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/" + personGroupId response = requests.delete(url=url,headers=headers) #takes in the user's id, gets their name, and adds a photo from an url def addFace(personID): name = getPersonName(personID) if(name == '<NAME>'): photo = 'https://media.licdn.com/dms/image/C5103AQF6o6kmZyN5qQ/profile-displayphoto-shrink_200_200/0?e=1525255200&v=alpha&t=qSE3eKdrVZkrpMpWnS9ldheYY7t0NF1E6d2wbkL3ig8' elif(name == '<NAME>'): photo = 'https://scontent-lax3-1.xx.fbcdn.net/v/t31.0-8/22859851_833930706775284_2298164206331624972_o.jpg?oh=da14e9f5d3f6dd67ed16ac6b5d49ca23&oe=5B49CFC2' elif(name == '<NAME>'): photo = 'https://scontent-lax3-1.xx.fbcdn.net/v/t31.0-8/18839535_710270525842729_6235509578421077480_o.jpg?oh=812bc4ca650131295a23e089e02c7f3b&oe=5B442168' elif(name == '<NAME>'): photo = 'https://scontent-lax3-1.xx.fbcdn.net/v/t31.0-8/21457362_1762418087392430_5728002921223690541_o.jpg?oh=1e62faa1f514bef393fb4a5e5cf3830d&oe=5B4BFA1C' else: captureImageToBlob() photo = 'https://chrishacktech.blob.core.windows.net/photos/newuser_blob.jpg' url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/"+personGroupId+"/persons/"+personID+"/persistedFaces" data = {"url":photo} requests.post(url=url,json=data,headers=headers) #create person group person (including faces). returns list of ids of created people def createPerson(names): url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/"+personGroupId+"/persons" #hardcoded names #names = ["Kaushik", "Radhika", "Maegan", "Chris"] ids = [] for name in names: body = { "name": name } response = requests.post(url=url,json=body,headers=headers) try: tempID = str(response.json()["personId"]) except: print("createPerson rate limited") ids.append(tempID) addFace(tempID) return ids #deletes a person from their person id def deletePerson(personID): url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/"+personGroupId+"/persons/"+personID response = requests.delete(url=url,headers=headers) def getPersonName(personID): getURL = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/" + personGroupId + "/persons/" + personID response = requests.get(url=getURL,headers=headers) try: name = response.json()["name"] except: print("getPersonName rate limited") return name def trainGroup(): url = "https://westcentralus.api.cognitive.microsoft.com/face/v1.0/persongroups/"+personGroupId+"/train" response = requests.post(url=url, headers=headers) def detectFace(imageUrl): localHeaders = {"Host": 'westcentralus.api.cognitive.microsoft.com', "Content-Type":'application/octet-stream','Ocp-Apim-Subscription-Key': key } urlAPI = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?' + urllib.parse.urlencode({ 'returnFaceId': 'true'}) #photo to check data = open(imageUrl, 'rb').read() #body = { "url" : imageUrl} response = requests.post(url = urlAPI, data = data, headers = localHeaders) #print (response.json()) try: theirID = response.json()[0]["faceId"] except: print("rate limits suck") faceIDs = [theirID] identifyURL = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/identify' body = {"personGroupId":personGroupId,"faceIds":faceIDs,"maxNumOfCandidatesReturned": 1,"confidenceThreshold": 0.5} response = requests.post(url = identifyURL, json = body, headers = headers) try: winner = response.json()[0]['candidates'][0]['personId'] except: print("rate limited") return getPersonName(winner) def processItems(numIteScan): numItemsScanned = int(numIteScan) i = 1 items = [] prices = [] while (i <= numItemsScanned): cap = cv2.VideoCapture(0) while (True): ret, frame = cap.read() if ret is True: rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) else: continue cv2.imshow('frame', rgb) if cv2.waitKey(1) & 0xFF == ord('q'): picName = 'item' + str(i) + '.jpg' out = cv2.imwrite(picName, frame) cap.release() break cv2.destroyAllWindows() words = imagerecognition.rekognition(picName) itemName, itemPrice = imagerecognition.walmartSearch(words) items.append(itemName) prices.append(itemPrice) i = i + 1 return items, prices #def getItem(): # cap = cv2.VideoCapture(0) # # while(True): # ret, frame = cap.read() # if ret is True: # rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) # else: # continue # cv2.imshow('frame', rgb) # if cv2.waitKey(1) & 0xFF == ord('q'): # picName = 'blobItem.jpg' # out = cv2.imwrite(picName, frame) # cap.release() # cv2.destroyAllWindows() # break # block_blob_service.create_blob_from_path( # 'photos', # picName, # picName, # content_settings=ContentSettings(content_type='image/jpg')) #def itemDetect(imageUrl): # handWriteDetectKey = "<KEY>" # text_recognition_url = "https://westcentralus.api.cognitive.microsoft.com/vision/v1.0/RecognizeText" # detectHeaders = {'Ocp-Apim-Subscription-Key': handWriteDetectKey} # detectParams = {'handwriting' : True} # detectData = {'url': imageUrl} # response = requests.post(text_recognition_url, headers=detectHeaders, params=detectParams, json=detectData) # response.raise_for_status() # operation_url = response.headers["Operation-Location"] # import time # analysis = {} # while not "recognitionResult" in analysis: # response_final = requests.get(response.headers["Operation-Location"], headers=detectHeaders) # analysis = response_final.json() # time.sleep(1) #val = [(line["boundingBox"], line["text"]) for line in analysis["recognitionResult"]["lines"]] # val = [line["text"] for line in analysis["recognitionResult"]["lines"]] # return val def captureImage(): cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() if ret is True: rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) else: continue cv2.imshow('frame', rgb) if cv2.waitKey(1) & 0xFF == ord('q'): picName = 'capture.jpg' out = cv2.imwrite(picName, frame) cap.release() cv2.destroyAllWindows() return picName def captureImageToBlob(): cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() if ret is True: rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) else: continue cv2.imshow('frame', rgb) if cv2.waitKey(1) & 0xFF == ord('q'): picName = 'newuser_blob.jpg' out = cv2.imwrite(picName, frame) block_blob_service = BlockBlobService(account_name='chrishacktech', account_key='<KEY>') block_blob_service.create_blob_from_path( 'photos', picName, picName, content_settings=ContentSettings(content_type='image/jpg')) cap.release() cv2.destroyAllWindows() break def determineCost(arr): return sum(arr) def processReceipt(items, prices): i = 0 while (i < len(items)): print ("Item " + str(i+1) + ": " + items[i] + " " + str(prices[i])) i = i + 1 print ("Total: " + str(sum(prices))) <file_sep>########### Python 2.7 ############# import requests, json, urllib.request, urllib.parse, urllib.error headers = { # Request headers 'Content-Type': 'application/json', 'Ocp-Apim-Subscription-Key': '1f3021aa1ab74cedaf685826f631ab5a', } def detectFace(): urlAPI = 'https://westcentralus.api.cognitive.microsoft.com/face/v1.0/detect?' + urllib.parse.urlencode({ 'returnFaceId': 'true'}) body = { "url" : "https://scontent-lax3-1.xx.fbcdn.net/v/t31.0-8/18595423_1720002141634025_1533763974652478544_o.jpg?oh=b720f6bde1d2226661bbd757a82d5f1d&oe=5B45CAF0"} response = requests.post(url = urlAPI, json = body, headers = headers) print(response.json()[0]["faceId"]) detectFace()<file_sep>import requests import json import cv2 import boto3 import boto.s3.connection import boto import urllib.parse key = '4a06edca17014688b808c4318d99a0ca' headers= {"Content-Type":'application/json'} def captureImage(): cap = cv2.VideoCapture(0) while(True): ret, frame = cap.read() if ret is True: rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA) else: continue cv2.imshow('frame', rgb) if cv2.waitKey(1) & 0xFF == ord('q'): picName = 'capture.jpg' out = cv2.imwrite(picName, frame) cap.release() cv2.destroyAllWindows() return picName def rekognition(image): bucket='rekognition-examples-bucket-hacktech' #add updated image to bucket conn = boto.s3.connect_to_region('us-east-1', aws_access_key_id = '<KEY>', aws_secret_access_key = '4j3e4Vw01xcLKEe9E3Nv1wTnhysFa2pL/IXOg9FL',calling_format = boto.s3.connection.OrdinaryCallingFormat(),) tempBucket = conn.get_bucket(bucket) key_name = image; k = tempBucket.new_key(key_name) k.set_contents_from_filename(key_name) client = boto3.client('rekognition','us-east-1') fileName=image #get image from bucket response = client.detect_text(Image={'S3Object':{'Bucket':bucket,'Name':fileName}}) words = [] for i in range(len(response["TextDetections"])): word = response["TextDetections"][i]["DetectedText"] if(any(j.isdigit() for j in word)): #nothing with a number is being stored continue word = str(word).lower() if word not in words and len(word) > 2: #dont want short words like a or as words.append(word) return words def walmartSearch(words): count = 0 queryString = "" while count < len(words)/3: currentWord = words[count] queryString = queryString + currentWord + " " count = count + 1 queryString = queryString[:-1] url = "http://api.walmartlabs.com/v1/search?apiKey=<KEY>&sort=price&format=json&" + urllib.parse.urlencode({"query":queryString}) response = requests.get(url=url,headers=headers).json() itemName = response["items"][0]["name"] itemPrice = response["items"][0]["salePrice"] return itemName, itemPrice <file_sep>import cv2 # Windows dependencies # - Python 2.7.6: http://www.python.org/download/ # - OpenCV: http://opencv.org/ # - Numpy -- get numpy from here because the official builds don't support x64: # http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy # Mac Dependencies # - brew install python # - pip install numpy # - brew tap homebrew/science # - brew install opencv
a6d3f3d9399db960058fe04270d036ef16ae12e9
[ "Markdown", "Python" ]
9
Markdown
chailey/HackTech2018
efb9899a37ce36b2bc79301b3177f2bf7a696648
75e5252f5ae0aacb2cdf6b39f2ce4bf6950c923f
refs/heads/main
<file_sep>#include "cg.hpp" #include <algorithm> #include <cassert> #include <cstdint> #include <fstream> #include <iostream> #include <map> #include <memory> #include <sstream> #include <unordered_map> #include <unordered_set> #include <vector> #include <tuple> #include <string> // Get targets to callers mapping. This is an intermediate state from raw call // graph to reverse call graph. Filtering is done at this step. // The mapping is inclusive of all functions, i.e., a key exist even if a // function has no caller. void CallGraph::UpdateTargetToCallers(const CallGraphFilter& F) { auto Filter = F; //< Filter may be updated. // Transform function name filters to function pc filters. if (Filter.ExcludeFuncsWithKeywordInName.size()) { for (const auto &El : FuncAddrToName) { uint64_t FuncPc = El.first; const auto &FuncName = El.second; for (const auto &Keyword : Filter.ExcludeFuncsWithKeywordInName) if (FuncName.find(Keyword) != std::string::npos) Filter.ExcludeFuncs.insert(FuncPc); } } auto ShouldExcludeFunc = [&](uint64_t FuncPc) -> bool { // Don't exclude if it is specifically asked for. if (FuncAddrToName.count(FuncPc)) { auto FuncName = FuncAddrToName[FuncPc]; for (const auto &FName : Filter.IncludeCallsToFunctionsWithName) { if (FuncName == FName) return false; } } // Filter based on the function pc. if (Filter.ExcludeFuncs.count(FuncPc)) return true; // Filter based on indirect targetness. if (Filter.ExcludeUnknownIndirTargets && IndirTargetUnknownType.count(FuncPc)) return true; return false; }; // // Precompute indirect call sites. // // Every indirect call site with UNKNOWN type id. std::vector<CallSite> IndirCallUnknownTypeCallSites; if (!Filter.ExcludeUnknownIndirCalls) { for (auto CallSitePc : IndirCallUnknownType) { uint64_t CallerPc = CallSiteToCaller.find(CallSitePc)->second; if (ShouldExcludeFunc(CallerPc)) continue; IndirCallUnknownTypeCallSites.emplace_back(CallerPc, CallSitePc); } } // Type id to indirect call sites. std::unordered_map<uint64_t, std::vector<CallSite>> TypeIdToIndirCallSites; for (const auto &El : TypeIdToIndirCalls) { uint64_t TypeId = El.first; for (uint64_t CallSitePc : El.second) { uint64_t CallerPc = CallSiteToCaller.find(CallSitePc)->second; if (ShouldExcludeFunc(CallerPc)) continue; TypeIdToIndirCallSites[TypeId].emplace_back(CallerPc, CallSitePc); } } // Add for indirect calls. for (const auto &El : FuncAddrToName) { uint64_t FuncPc = El.first; if (ShouldExcludeFunc(FuncPc)) continue; auto &FuncTargetToCallers = TargetsToCallers[FuncPc]; // Add indirect calls based on function's indirect target properties. bool FuncIsIndirTarget = IndirTargetToTypeId.count(FuncPc) || IndirTargetUnknownType.count(FuncPc); if (FuncIsIndirTarget) { // Add indirect calls with unknown type id. if (!Filter.ExcludeUnknownIndirCalls) FuncTargetToCallers.insert(FuncTargetToCallers.end(), IndirCallUnknownTypeCallSites.begin(), IndirCallUnknownTypeCallSites.end()); // Add indirect calls with matching type id. bool FuncHasTypeId = IndirTargetToTypeId.count(FuncPc); if (FuncHasTypeId) { //< Function with type id. // Add call sites with matching type id. uint64_t FuncTypeId = IndirTargetToTypeId.find(FuncPc)->second; if (!TypeIdToIndirCallSites[FuncTypeId].empty()) { auto CallSites = TypeIdToIndirCallSites[FuncTypeId]; FuncTargetToCallers.insert(FuncTargetToCallers.end(), CallSites.begin(), CallSites.end()); } } else if (!Filter.ExcludeIndirCallsToUnknownTargets) { //< Function with unknown type id. // Add all indirect calls as potential caller. // Only add call sites with known type ids. The rest are added or not // based on another filter value. for (const auto &El : TypeIdToIndirCallSites) { const auto CallSites = El.second; TargetsToCallers[FuncPc].insert(TargetsToCallers[FuncPc].end(), CallSites.begin(), CallSites.end()); } } } } // // Add for direct calls // for (auto const &El : FuncAddrToDirCallSites) { uintptr_t CallerPc = El.first; const auto &Calls = El.second; if (ShouldExcludeFunc(CallerPc)) continue; for (const auto &Call : Calls) { auto CallSitePc = std::get<0>(Call); auto TargetPc = std::get<1>(Call); if (ShouldExcludeFunc(CallSitePc) || ShouldExcludeFunc(TargetPc)) continue; TargetsToCallers[TargetPc].emplace_back(CallerPc, CallSitePc); } } } CallGraph::CallGraph(std::istream &In, const CallGraphFilter &CGF) { std::string X; auto TryReadHex64 = [&](std::stringstream &SS, uint64_t &H) -> bool { if (!SS.good()) return false; SS >> std::hex >> H; return true; }; auto ReadHex64 = [&](std::stringstream &SS, uint64_t &H) { if(!TryReadHex64(SS, H)) { std::cerr << "cannot read hex value" << std::endl; exit(-1); }; }; auto ReadHex64List = [&](std::stringstream &SS, std::vector<uint64_t>& V) -> size_t { size_t Count = 0; uint64_t H; while (TryReadHex64(SS, H)) { V.push_back(H); Count++; } return Count; }; // Read from file. while(std::getline(In, X)) { // Read indirect target types. if (!X.find("INDIRECT TARGET TYPES")) { assert (TypeIdToIndirTargets.empty() && "Multiple \"INDIRECT TARGETS TYPES\" sections."); while (std::getline(In, X)) { //< Read type id per line if (X == "") break; std::stringstream Line(X); // Read type id. It can be an id or string "UNKNOWN". std::string TypeId; Line >> TypeId; if (TypeId == "UNKNOWN") { std::vector<uint64_t> V; ReadHex64List(Line, V); IndirTargetUnknownType.insert(V.begin(), V.end()); } else { uint64_t TypeIdVal = std::stoull(TypeId, 0, 16); // TODO: use these for without callgraph evaluation // TypeIdVal = 0; ReadHex64List(Line, TypeIdToIndirTargets[TypeIdVal]); // Reverse mapping. for (auto FuncPc : TypeIdToIndirTargets[TypeIdVal]) IndirTargetToTypeId[FuncPc] = TypeIdVal; } } } // Read indirect call types. if (!X.find("INDIRECT CALL TYPES")) { assert (TypeIdToIndirCalls.empty() && "Multiple \"INDIRECT CALLS TYPES\" sections."); while (std::getline(In, X)) { if (X == "") break; std::stringstream Line(X); // Read type id and indirect call site pcs. uint64_t TypeId; ReadHex64(Line, TypeId); // TODO: use these for without callgraph evaluation //TypeId = 0; auto &CallSitePcList = TypeIdToIndirCalls[TypeId]; ReadHex64List(Line, CallSitePcList); // Reverse mapping: indirect call site pc to type id. for (auto CallSitePc : CallSitePcList) IndirCallToTypeId[CallSitePc] = TypeId; } } // Read indirect call sites. if (!X.find("INDIRECT CALL SITES")) { assert (FuncAddrToIndirCallSites.empty() && "Multiple \"INDIRECT CALL SITES\" sections."); while (std::getline(In, X)) { if (X == "") break; std::stringstream Line(X); // Read caller pc. uint64_t CallerPc; ReadHex64(Line, CallerPc); // Read indirect call site pcs. std::vector<uint64_t> CallSitePcs; ReadHex64List(Line, CallSitePcs); FuncAddrToIndirCallSites[CallerPc] = CallSitePcs; // Insert to set of all indirect call site pcs. IndirCallSiteAddrs.insert(CallSitePcs.begin(), CallSitePcs.end()); } } // Read direct call sites. if (!X.find("DIRECT CALL SITES")) { assert (FuncAddrToDirCallSites.empty() && "Multiple \"DIRECT CALL SITES\" sections."); while (std::getline(In, X)) { if (X == "") break; std::stringstream Line(X); // Read caller pc. uint64_t CallerPc; ReadHex64(Line, CallerPc); // Read direct call site and target pcs. uint64_t CallSitePc, TargetPc; while (TryReadHex64(Line, CallSitePc)) { ReadHex64(Line, TargetPc); FuncAddrToDirCallSites[CallerPc].emplace_back(CallSitePc, TargetPc); // Insert to set of all direct call site pcs. DirCallSiteAddrs.insert(CallSitePc); } } } // Read functions. if (!X.find("FUNCTIONS")) { assert (FuncAddrToName.empty() && "Multiple \"FUNCTION SYMBOLS\" sections."); while (std::getline(In, X)) { if (X == "") break; std::stringstream Line(X); // Read function pc. uint64_t FunctionPc; ReadHex64(Line, FunctionPc); // Read function name. std::string FuncName; Line >> FuncName; FuncAddrToName[FunctionPc] = FuncName; } } } // Set FuncNameToAddr. for (auto &El : FuncAddrToName) FuncNameToAddr[El.second] = El.first; // Set targets without any info. for (auto &El : FuncAddrToName) { uint64_t FuncPc = El.first; if (!IndirTargetToTypeId.count(FuncPc) && !IndirTargetUnknownType.count(FuncPc)) TargetsWithNoInfo.insert(FuncPc); } // Set indirect calls without a type id. for (auto IndirCallSitePc : IndirCallSiteAddrs) if (IndirCallToTypeId.count(IndirCallSitePc)) IndirCallUnknownType.insert(IndirCallSitePc); // Set call site to caller mappings. for (const auto& El: FuncAddrToDirCallSites) { uint64_t Func = El.first; for (const auto &DirCallSite : El.second) { uint64_t CallSite = std::get<0>(DirCallSite); CallSiteToCaller[CallSite] = Func; } } for (const auto& El: FuncAddrToIndirCallSites) { uint64_t Func = El.first; for (const auto &IndirCallSite : El.second) CallSiteToCaller[IndirCallSite] = Func; } // Update target to callers. UpdateTargetToCallers(CGF); } <file_sep>#ifndef __REVERSE_CALL_GRAPH_H__ #define __REVERSE_CALL_GRAPH_H__ #include "cg.hpp" struct FunctionNode; struct CallSiteNode { FunctionNode* Caller; //< Owner of the call site node. uint64_t CallSitePc; //< Call site pc. CallSiteNode() : Caller(nullptr), CallSitePc(0) {} }; struct FunctionNode { uint64_t EntryPc; //< Function entry pc. CallSiteNode* Callers; //< Callers of this function. uint64_t NumCallers; //< Length of the num callers. FunctionNode(uint64_t EntryPc) : EntryPc(EntryPc), Callers(nullptr), NumCallers(0) {} }; // A compact and efficient reverse call graph representation. struct ReverseCallGraph { std::unordered_map<uint64_t, FunctionNode*> FuncPcToNode; std::unordered_map<uint64_t, CallSiteNode*> CallSitePcToNode; ReverseCallGraph(const CallGraph&); // Deallocate for FunctionNode and CallSiteNode instances. ~ReverseCallGraph(); }; #endif <file_sep>#include <algorithm> #include <cassert> #include <cstdint> #include <fstream> #include <iostream> #include <map> #include <sstream> #include <iomanip> #include <unordered_map> #include <unordered_set> #include <vector> #include <string> #include <chrono> #include "cg.hpp" #include "rcg.hpp" typedef std::vector<uint64_t> StackTrace; // Followings are set on program initialization from CLI. They are kept global // to avoid passing them as arguments to each recursive call to DFS. // Alternatively, a class can be implemented for DFS where these will be kept // as instance members. size_t MaxDepth = 0; //< Maximum depth to search for. uint64_t PruningDepth1 = 0; //< Pruning depth 1. uint64_t PruningDepth2 = 0; //< Pruning depth 2. uint64_t *ST = nullptr; //< Stack trace to fill by reconstruction. //< Allocated based on the maximum depth. ReverseCallGraph *RCG = nullptr; //< Reverse call graph. // Followings are set everytime before calling DFS based on the stack trace // to reconstruct. std::vector<uint64_t> WantedST; //< Wanted stack trace. uint64_t WantedHash = 0; //< The hash for WantedST. uint64_t WantedHashMed1 = 0; //< Pruning hash 1. uint64_t WantedHashMed2 = 0; //< Pruning hash 2. int DoesNotMatchCount = 0; //< Count how many incorrect reconstructions //< were made. // Pretty print a stack trace. template<class T> void PrettyPrintST(const CallGraph &CG, T it_begin, size_t length) { std::cerr << "Stack Trace (length=" << std::dec << length <<"): " << std::endl; for (size_t I = 0; I < length; I++) { uint64_t CallSitePc = *it_begin; uint64_t CallerPc = CG.CallSiteToCaller.find(CallSitePc)->second; std::string CallerName = "UNKNOWN_NAME"; if (CG.FuncAddrToName.count(CallerPc)) CallerName = CG.FuncAddrToName.find(CallerPc)->second; // Print frame. std::cerr << " " << I << ": [" << std::hex << CallSitePc << "] " << CallerName << "[" << std::hex << CallerPc << "]" << std::endl; it_begin++; } } // Pretty print a stack trace. void PrettyPrintST(const CallGraph &CG, std::vector<uint64_t> st) { PrettyPrintST(CG, st.begin(), st.size()); } // Check whether two stack traces are the same. template<class T1, class T2> bool AreSTSame(T1 it1_begin, size_t size1, T2 it2_begin, size_t size2) { if (size1 != size2) return false; for (int I = 0; I < size1; I++) { if (*it1_begin != *it2_begin) return false; it1_begin++; it2_begin++; } return true; } uint64_t HashStep(uint64_t Hash, uint64_t PC, size_t Idx) { uint64_t CRC32 = __builtin_ia32_crc32di(Hash, PC); if (Idx == PruningDepth1) { return CRC32 | (Hash << (48)); } else if (Idx == PruningDepth2) { return CRC32 | ((Hash >> 48) << 48) | ((Hash & 0xFFFFll) << 32); } else { return CRC32 | ((Hash >> 32) << 32); } } uint64_t Hash(const StackTrace &ST) { uint64_t Res = 0; for (size_t I = 0; I < ST.size(); I++) Res = HashStep(Res, ST[I], I); return Res; } // Reads the stack traces from input stream, and returns a vector of stack // traces together with the name of the entry function and the hash of the // stack trace. The first frame from the list is eliminated and used as the // entry point. std::vector<std::tuple<std::string/*FuncName*/, uint64_t/*Hash*/, StackTrace>> ReadStackTracesFromASanOut(std::istream &In, const CallGraph &CG, size_t DepthLimit) { std::vector<std::tuple<std::string, uint64_t, StackTrace>> Res; std::string X; int CountStackTracesClipped = 0; int CountHashCollisions = 0; int CSCouldntFind = 0; std::unordered_set<uint64_t> HashesFound; while (std::getline(In, X)) { std::stringstream Line(X); std::string FirstWord; Line >> FirstWord; if (FirstWord != std::string("ST:")) continue; std::string FuncName; StackTrace ST; int CurrentDepth = 0; while (true) { uint64_t PC; Line >> std::hex >> PC; if (!CG.CallSiteToCaller.count(PC)) { CSCouldntFind++; break; } // Get the entry point if (CurrentDepth == 0) { CurrentDepth++; if (!CG.CallSiteToCaller.count(PC)) { fprintf(stderr, "WARNING: Failed to find caller for the call site at %p.\n", (void*)PC); break; } else { auto Caller = CG.CallSiteToCaller.find(PC)->second; if (!CG.FuncAddrToName.count(Caller)) { fprintf(stderr, "WARNING: Failed to find func name for caller at %p.\n", (void*)Caller); break; } FuncName = CG.FuncAddrToName.find(Caller)->second; } continue; } if (!Line) break; ST.push_back(PC); if (CurrentDepth++ == DepthLimit) { CountStackTracesClipped++; break; } } uint64_t STHash = Hash(ST); if (HashesFound.count(STHash)) CountHashCollisions++; Res.emplace_back(FuncName, STHash, ST); } if (CountStackTracesClipped) fprintf(stderr, "WARNING: %d stack traces were clipped as they exceeded " "the depth limit.\n", CountStackTracesClipped); if (CountHashCollisions) fprintf(stderr, "WARNING: %d stack traces had hash collisions.\n", CountHashCollisions); if (CSCouldntFind) fprintf(stderr, "WARNING: %d stack traces were ignored since they included filtered frames.\n", CSCouldntFind); return Res; } // Returns whether the stack trace is found. If it is found, prints a success // message and the number of incorrect reconstructions. bool DFS(size_t CurrentDepth, uint64_t CurrentHash, FunctionNode *EntryFunc) { // Check hash match if (CurrentHash == WantedHash) { bool DidMatch = AreSTSame(WantedST.begin(), WantedST.size(), ST, CurrentDepth); if (DidMatch) { std::cerr << "SUCCESS: Matches!\n"; std::cerr << "Found " << DoesNotMatchCount << " incorrect reconstructions due to collisions" << std::endl; return true; } else { DoesNotMatchCount++; } } if (CurrentDepth > MaxDepth) return false; // If the current depth is one of the pruning depths, check the hash against // the pruning hashes. if (CurrentDepth == PruningDepth1+1) { // Pruning depth 1: prune based on the highest 16-bits bucket if ((CurrentHash >> 48) != WantedHashMed1) return false; } else if (CurrentDepth == PruningDepth2+1) { // Pruning depth 2: prune based on the second highest 16-bits bucket if (((CurrentHash >> 32) & 0xFFFFll) != WantedHashMed2) return false; } // Continue search from the callers of the current function. auto NumCallers = EntryFunc->NumCallers; auto Callers = EntryFunc->Callers; for (int I = 0; I < NumCallers; I++) { const CallSiteNode &CSN = Callers[I]; // Fill one frame in the stack trace. ST[CurrentDepth] = CSN.CallSitePc; bool Found = DFS( CurrentDepth + 1, HashStep(CurrentHash, CSN.CallSitePc, CurrentDepth), CSN.Caller ); if (Found) return true; } return false; } int main(int argc, char **argv) { if (argc != 6) { std::cerr << "OVERVIEW: efficient stack trace collection and reconstruction simulation tool" << std::endl; std::cerr << "USAGE: " << argv[0] << " call_graph_disasm_file" //< 1st << " stack_traces_file" //< 2nd << " max_depth" //< 3rd << " pruning_depth_1" //< 4th << " pruning_depth_2" //< 5th << "\n\n"; std::cerr << " call_graph_disasm_file " << "File containing call graph disassembly output obtained from llvm-objdump --call-graph-info\n" << " stack_traces_file " << "File containing stack traces to compress/decompress, obtained using ASAN hooks\n" << " max_depth " << "Maximum depth at which to clip the stack traces and stop the reconstruction search\n" << " pruning_depth_1 " << "First pruning depth\n" << " pruning_depth_2 " << "Second pruning depth\n" << std::endl; return -1; } // TODO: Verify the input values. Specifically, verify the filepath inputs. // Read the medium indices. PruningDepth1 = atoi(argv[4]); PruningDepth2 = atoi(argv[5]); // Create call graph filter. CallGraphFilter CGF; // Force including the allocation/deallocation functions. These may not have // ids in the .callgraph section as they are linked from outside the binary. CGF.IncludeCallsToFunctionsWithName = { "free", "malloc", "calloc", "realloc", "_ZdlPv"/*delete*/, "_ZdaPv"/*delete[]*/, "_Znwm"/*new*/, "_Znam"/*new[]*/, "_ZnwmRKSt9nothrow_t", /* new(ulong, std::nothrow_t)*/ }; // Exclude ASAN-related functions or functions that are infeasible to appear // on the allocation/deallocation traces. CGF.ExcludeFuncsWithKeywordInName = {"asan", "interceptor", "@plt", "sanitizer", "__clang_call_terminate"}; // Exclude any node/edge related to the unknown indirect calls/targets. CGF.ExcludeIndirCallsToUnknownTargets = true; CGF.ExcludeUnknownIndirCalls = true; CGF.ExcludeUnknownIndirTargets = true; // Read the call graph. std::ifstream CGIn(argv[1]); CallGraph CG(CGIn, CGF); // Compute the light-weight reverse call graph. auto RevCG = ReverseCallGraph(CG); // Read the maximum depth. size_t Depth = atoi(argv[3]); // Read the stack traces. std::ifstream TargetStacksIn(argv[2]); auto STS = ReadStackTracesFromASanOut(TargetStacksIn, CG, Depth); // Set globals used by DFS. These are intentionally set global to avoid // recursively passing the same arguments for the DFS function. Alternatively, // a search class may be implemented where these are stored per instance. MaxDepth = Depth; ST = new uint64_t[MaxDepth+1]; RCG = &RevCG; std::cerr << "Starting the reconstructions." << std::endl; for (const auto &STI : STS) { std::string FuncName = std::get<0>(STI); // Further set the globals used by DFS. WantedHash = std::get<1>(STI); WantedST = std::get<2>(STI); WantedHashMed1 = WantedHash >> 48; WantedHashMed2 = (WantedHash >> 32) & 0xFFFFll; DoesNotMatchCount = 0; // Print info on the stack trace that is going to be reconstructed. auto FuncEntryPc = CG.FuncNameToAddr[FuncName]; std::cerr << "\nFuncName: " << FuncName << "\nFuncEntryPc: " << std::hex << FuncEntryPc << "\nStack trace hash: " << std::hex << WantedHash << "\nStack trace: " << std::endl; PrettyPrintST(CG, WantedST); auto start = std::chrono::high_resolution_clock::now(); // Start reconstruction. bool Ret = DFS(/*CurrentDepth=*/0, /*CurrentHash=*/0, /*EntryFunc=*/RCG->FuncPcToNode[FuncEntryPc]); // Print after reconstruction logs. auto stop = std::chrono::high_resolution_clock::now(); auto duration = std::chrono::duration_cast<std::chrono::seconds>(stop - start); std::cerr << "Time elapsed (sec): " << std::dec <<duration.count() << std::endl; if (!Ret) std::cerr << "\nFAIL: Could not reconstruct the stack trace.\n"; std::cerr<< "\n=========================================\n" << std::endl; } if (MaxDepth) delete[] ST; return 0; } <file_sep>// A toy example just to produce some stack traces. #include<stdlib.h> int f1(int); char f2(int); float f3(int); int (*fp_f1)(int) = f1; char (*fp_f2)(int) = f2; float (*fp_f3)(int) = f3; void malloc_free() { char* m = malloc(1); if (m) free(m); } int f1(int depth) { if (!depth--) return 0; if (depth < 3) malloc_free(); if (depth % 3) return fp_f3(depth); if (depth % 2) return fp_f2(depth); return fp_f3(depth); } char f2(int depth) { if (!depth--) return 0; if (depth < 3) malloc_free(); if (depth % 3) return f3(depth); if (depth % 2) return f2(depth); return f3(depth); } float f3(int depth) { if (!depth--) return 0; if (depth < 3) malloc_free(); if (depth % 2) return fp_f2(depth); if (depth % 3) return fp_f3(depth); return fp_f1(depth); } int main() { f1(32); f1(31); f1(30); f2(32); f2(31); f2(30); f3(32); f3(31); f3(30); return 0; } <file_sep>#ifndef __CALL_GRAPH_H__ #define __CALL_GRAPH_H__ #include <iostream> #include <unordered_map> #include <unordered_set> #include <vector> #include <tuple> #include <string> struct CallSite { uint64_t CallerPc; uint64_t CallSitePc; CallSite(uint64_t CallerPc, uint64_t CallSitePc) : CallerPc(CallerPc), CallSitePc(CallSitePc) {} }; struct CallGraphFilter { // Include calls to functions. Preceeds to any other filter. std::unordered_set<std::string> IncludeCallsToFunctionsWithName; // Exclude: direct calls from/to it, indirect calls from/to it. std::unordered_set<uint64_t> ExcludeFuncs; // Check if the keyword appears somewhere in the function name string. // Exclude: direct calls from/to it, indirect calls from/to it. std::unordered_set<std::string> ExcludeFuncsWithKeywordInName; // Exclude: direct calls from/to it, indirect calls from/to it. // Include: nothing. bool ExcludeUnknownIndirTargets; // Exclude: indirect calls to unknown targets. // Include: direct calls from/to it, indirect calls from it. bool ExcludeIndirCallsToUnknownTargets; // Exclude: indirect calls without a type id. bool ExcludeUnknownIndirCalls; }; // Raw call graph representation that is not optimized for space but for // convenience in bringing information. struct CallGraph { // Indirect targets. std::unordered_map<uint64_t, std::vector<uint64_t>> TypeIdToIndirTargets; std::unordered_map<uint64_t, uint64_t> IndirTargetToTypeId; std::unordered_set<uint64_t> IndirTargetUnknownType; // those tagged "UNKNOWN". std::unordered_set<uint64_t> TargetsWithNoInfo; // No info on call graph section. // Indirect calls. std::unordered_map<uint64_t, std::vector<uint64_t>> TypeIdToIndirCalls; std::unordered_map<uint64_t, uint64_t> IndirCallToTypeId; std::unordered_set<uint64_t> IndirCallUnknownType; // Indirect call sites: { CallerFuncPc: [IndirectCallSiteAddr,] } std::unordered_map<uint64_t, std::vector<uint64_t>> FuncAddrToIndirCallSites; // Direct call sites: { CallerAddr: [(CallSiteAddr, TargetAddr),] } std::unordered_map<uint64_t, std::vector<std::tuple<uint64_t, uint64_t>> > FuncAddrToDirCallSites; // Set of all call sites. std::unordered_set<uint64_t> DirCallSiteAddrs; std::unordered_set<uint64_t> IndirCallSiteAddrs; // Functions std::unordered_map<uint64_t, std::string> FuncAddrToName; std::unordered_map<std::string, uint64_t> FuncNameToAddr; std::unordered_map<uint64_t, uint64_t> CallSiteToCaller; std::unordered_map<uint64_t/*TargetFuncPc*/, std::vector<CallSite>/*potential calls to it*/> TargetsToCallers; private: void UpdateTargetToCallers(const CallGraphFilter& F); public: // Read from llvm-objdump output CallGraph(std::istream &In, const CallGraphFilter &CGF); void Print(std::ostream &Out) const; void PrintReverseCG(std::ostream &Out, bool demagle) const; }; #endif <file_sep># Efficient stack trace collection and reconstruction simulation This document describes how to run an end-to-end example for efficient stack trace collection and reconstruction. ## Setup the workspace ``` mkdir ~/callgraph-ws export CALLGRAPH_WS=~/callgraph-ws/ ``` ## Install `LLVM` Clone the llvm-project, which includes implementations for: * `clang -fcall-graph-section` to compute and store call graph in binary * `llvm-objdump --call-graph-info` to extract call graph from binary * `clang -fsanitize=address` with hooks for collecting stack traces on alloc/dealloc. ``` cd $CALLGRAPH_WS git clone https://github.com/necipfazil/llvm-project cd llvm-project/ git checkout necip-call-graph ``` Build and install: ``` mkdir build && cd build cmake -DLLVM_ENABLE_PROJECTS="clang;compiler-rt" ../llvm make -j && sudo make install export CALLGRAPH_BIN=$CALLGRAPH_WS/llvm-project/build/bin/ ``` ## Build `st_reconst` Clone and build the stack trace reconstruction simulation tool: ``` cd $CALLGRAPH_WS git clone https://github.com/necipfazil/efficient-st-collection-simulation cd efficient-st-collection-simulation clang++ -O3 -msse4.2 rcg.cpp cg.cpp st_reconst.cpp -o st_reconst ``` ## Do reconstruction with example Build with `.callgraph` section and ASAN hooks for stack trace collection: ``` $CALLGRAPH_BIN/clang -fcall-graph-section -fsanitize=address toy_example.c -o toy_example.o ``` Extract call graph: ``` $CALLGRAPH_BIN/llvm-objdump --call-graph-info toy_example.o > callgraph.dis ``` Run to collect stack traces: ``` ./toy_example.o 2> stack_traces.txt ``` Do reconstruction simulation (16 is the maximum depth; 4 and 6 are the pruning depths): ``` ./st_reconst callgraph.dis stack_traces.txt 16 4 6 ``` The simulation tool will: * Deserialize the call graph from `callgraph.dis` and create a reverse call graph, * Compress each stack trace in `stack_traces.txt`, * Decompress the stack traces through reverse call graph traversal. The output will include log messages per stack trace reconstructed such as: ``` FuncName: malloc FuncEntryPc: 49c020 Stack trace hash: 32410000726d1dfc Stack trace: Stack Trace (length=5): 0: [4cdab2] malloc_free[4cdaa0] 1: [4cda1b] f3[4cd9e0] 2: [4cd993] f2[4cd940] 3: [4cda3b] f3[4cd9e0] 4: [4cd993] f2[4cd940] SUCCESS! Matches! Found 0 incorrect reconstructions due to collisions Time elapsed (sec): 0 ``` <file_sep>#include "rcg.hpp" #include "cg.hpp" ReverseCallGraph::~ReverseCallGraph() { for (auto &El : FuncPcToNode) { if (El.second->NumCallers) delete[] El.second->Callers; El.second->Callers = nullptr; delete El.second; } FuncPcToNode.clear(); CallSitePcToNode.clear(); } ReverseCallGraph::ReverseCallGraph(const CallGraph& RawCG) { // Get the filtered target to callers mapping. auto &TargetToCallers = RawCG.TargetsToCallers; // Create function nodes. for (const auto &El : TargetToCallers) { uint64_t FuncPc = El.first; FuncPcToNode[FuncPc] = new FunctionNode(FuncPc); } // Set callers. for (const auto &El : TargetToCallers) { uint64_t FuncPc = El.first; FunctionNode *FuncNode = FuncPcToNode[FuncPc]; const std::vector<CallSite> &Callers = El.second; uint64_t NumCallers = Callers.size(); // Allocate for callers. FuncNode->NumCallers = NumCallers; if (NumCallers) FuncNode->Callers = new CallSiteNode[NumCallers]; // Set callers. for (int I = 0; I < NumCallers; I++) { const CallSite CS = Callers[I]; //< Get info from. CallSiteNode &CSN = FuncNode->Callers[I]; //< Fill info to. // Set caller. CSN.CallSitePc = CS.CallSitePc; CSN.Caller = FuncPcToNode[CS.CallerPc]; // Set CallSiteToPcNode mapping for reverse call graph. CallSitePcToNode[CS.CallSitePc] = &CSN; } } }
512ccf7d7544b5d6ca67c70db505e74d6aa20ae6
[ "Markdown", "C", "C++" ]
7
C++
necipfazil/efficient-st-collection-simulation
c3d9a15183328866a4a3df96be1fafa3b2f581d4
0ec965f1628678eecc2f14016393f162380ebf0d
refs/heads/master
<file_sep># To-do-app It's a to-do-list app. You can add, delete and finish your tasks. LIVE: ```diff - It's working with a fake JSON data-base. (To check real version download or clone repository.) ``` https://offblack.github.io/to-do-list/ ![alt text](https://raw.githubusercontent.com/Offblack/to-do-list/master/screenshot.png) ## What's inside? - Adding - Deleting - Finishing ## Some details Technologies: - ES-6 - Webpack - Sass - API ## How to use it? 1. Install all dependencies `npm install` 2. Run `npm run start-api` to start a JSON (data-base) server 3. Run `npm run start` to start a server and begin developing 4. Run `npm run build` to create a build <file_sep>import './utilities/all.min.js'; import './routing/index.js';<file_sep>import * as DOM from './../dom'; const getTemplate = url => new Promise(resolve => resolve(url)); const render = html => { DOM.DOMInit(); DOM.get().viewContainer.innerHTML = html }; export const load = view => new Promise((resolve, reject) => { getTemplate(view).then(html => { render(html); resolve() }) });<file_sep>import { get, DOMInit, } from './dom.js' import axios from './axios'; const getAll = () => { return new Promise((resolve, reject) => { axios .get('/tasks') .then(base => base.data) .then(tasks => resolve(tasks)) .catch(err => console.log(err)); }); } export const listInit = () => { getAll() .then(tasks => { tasks.forEach((oneTask) => { get().tasksList.innerHTML += `<ul class="one-task" id="${oneTask.id}"> <span class="task-check-icon"><i class="fas fa-check"></i></span> <p class="task-title">${oneTask.title}</p> <i class="far fa-clock timer-icon"></i> <span class="task-delete-icon" data-key="${oneTask.id}"><i class="fas fa-times"></i></span> </ul>`; }); DOMInit(); [...get().taskDeleteIcons].forEach(oneDelete => oneDelete.addEventListener('click', deleteOneTask)); [...get().taskCheckIcons].forEach(oneDelete => oneDelete.addEventListener('click', finishOneTask)); }); } export const searchSpecifyNote = element => { let searchingTitle = ''; searchingTitle = element.target.value.toLowerCase(); get().tasksList.innerHTML = ''; let taskAfterSearching = [...get().taskTitles].filter(title => title.textContent.toLowerCase().includes(searchingTitle)); taskAfterSearching.forEach(title => { get().tasksList.appendChild(title.parentNode); }); } export const actualTime = () => { const actualDate = new Date(); const options1 = { weekday: 'long' }; const actualDay = new Intl.DateTimeFormat('en-US', options1).format(actualDate); const options2 = { month: 'long' }; const actualMonth = new Intl.DateTimeFormat('en-US', options2).format(actualDate); const oneDate = `${actualDay}, ${actualDate.getDate()} ${actualMonth}`; return oneDate; } const finishOneTask = function () { this.parentNode.classList.toggle('finished-task') } const deleteOneTask = function () { return new Promise(() => { axios .delete(`/tasks/${this.dataset.key}`) .then(() => { get().tasksList.innerHTML = ''; listInit(); }) .catch(err => console.log(err)); }); } const addNewTask = (e) => { if (get().addInput.value != '') { return new Promise((resolve, reject) => { e.preventDefault(); axios .post('/tasks', { id: document.querySelectorAll('.one-task').id + 1, title: get().addInput.value.trim() }) .then(() => { get().tasksList.innerHTML = ''; listInit(); get().addInput.value = ''; }) .catch(err => console.log(err)); }); } else { e.preventDefault(); } } export const showTasksInput = () => { get().downSection.innerHTML = ` <div class="back-icon"> <i class="fas fa-chevron-left"></i> </div> <div id="adder"> <form class="add-form"> <input id="add-input" type="text" placeholder="Add..."> <button class="add-button"> <i class="fas fa-plus-circle add-icon"></i> </button> </form> </div>` DOMInit(); get().backIcon.addEventListener('click', hideTasksInput); get().addForm.addEventListener('submit', addNewTask); } const hideTasksInput = () => { get().downSection.innerHTML = ` What have for today? <div class="arrow-icons"> <i class="fas fa-chevron-right"></i> <i class="fas fa-chevron-right"></i> </div>` DOMInit(); get().arrowIcons.addEventListener('click', showTasksInput); }<file_sep>import { get, DOMInit } from './../dom.js'; import * as EventActions from './../event-actions.js'; const NavigationInit = () => { DOMInit(); const searchForNote = get().searchTask.addEventListener('input', EventActions.searchSpecifyNote); const setActualDate = () => get().pageDate.textContent = EventActions.actualTime(); const init = () => { setActualDate(); } init(); } export default NavigationInit;<file_sep>import * as view from './view.js'; import appInit from './../tasks/index.js'; import introView from './../../views/intro.html'; import tasksView from './../../views/tasks.html'; export const index = () => { view.load(introView).then(() => { setTimeout(tasks, 4000) }) } export const tasks = () => { view.load(tasksView).then(() => { appInit(); }) } export const notFound = () => { document.body.innerHTML = "Ops... Something went wrong! :(" }<file_sep>import { DOMInit, get } from './../dom.js'; import * as EventActions from './../event-actions.js'; const ListToDoInit = () => { EventActions.listInit(); DOMInit(); get().arrowIcons.addEventListener('click', EventActions.showTasksInput); } export default ListToDoInit;<file_sep>let DOM = {}; export const DOMInit = () => { DOM = { viewContainer: document.querySelector('#view-container'), searchTask: document.querySelector('#search-task'), tasksList: document.querySelector('.tasks-list'), allTask: document.querySelectorAll('.one-task'), taskTitles: document.querySelectorAll('.task-title'), taskCheckIcons: document.querySelectorAll('.task-check-icon'), taskDeleteIcons: document.querySelectorAll('.task-delete-icon'), pageDate: document.querySelector('#page-date'), arrowIcons: document.querySelector('.arrow-icons'), downSection: document.querySelector('.motivational-quotes'), backIcon: document.querySelector('.back-icon'), addForm: document.querySelector('.add-form'), addInput: document.querySelector('#add-input') } } export const get = () => { return DOM; } export default get;<file_sep>import navigationInit from './../navigation/index.js'; import toDoListInit from './../to-do-list/index.js'; const appInit = () => { navigationInit(); toDoListInit(); } export default appInit;<file_sep>import page from 'page'; import * as Routes from './routes.js'; page.base('/to-do-list') page('/', Routes.index) page('/tasks', Routes.tasks) page('*', Routes.notFound) page()
ce7c550a79b864f09d3fbb794ab16f70d5417f29
[ "Markdown", "JavaScript" ]
10
Markdown
Offblack/to-do-list
6591eaa71bb737644fef4e8eb203e31e331350cb
52169ad50b0adc56e7c1c14d3d20f5eede336d7f
refs/heads/master
<file_sep>#!/bin/bash export DATABASE_URL="jdbc:postgresql://localhost/webchange?user=webchange&password=<PASSWORD>" export PUBLIC_DIR="/srv/www/webchange/public" export UPLOAD_DIR="/srv/www/webchange/public/upload" java -jar /srv/www/webchange/current.jar<file_sep>-- :name create-school! :<! -- :doc creates a new school record INSERT INTO schools (id, name) VALUES (:id, :name) RETURNING id -- :name create-class! :<! -- :doc creates a new class record INSERT INTO classes (name, school_id) VALUES (:name, :school_id) RETURNING id -- :name update-class! :! :n -- :doc updates an existing class record UPDATE classes SET name = :name WHERE id = :id -- :name delete-class! :! :n -- :doc deletes class DELETE from classes WHERE id = :id -- :name create-student! :<! -- :doc creates a new student record INSERT INTO students (class_id, user_id, school_id, access_code, gender, date_of_birth) VALUES (:class_id, :user_id, :school_id, :access_code, :gender, :date_of_birth) RETURNING id -- :name update-student! :! :n -- :doc updates an existing student record class UPDATE students SET class_id = :class_id, gender = :gender, date_of_birth = :date_of_birth WHERE id = :id -- :name update-student-access-code! :! :n -- :doc updates an existing student record access-code UPDATE students SET access_code = :access_code WHERE id = :id -- :name unassign-student! :! :n -- :doc unassigns student UPDATE students SET class_id = null WHERE user_id = :user_id -- :name delete-student! :! :n -- :doc deletes student DELETE from students WHERE user_id = :user_id -- :name get-classes :? :* -- :doc retrieve all classes by school SELECT * from classes WHERE school_id = :school_id -- :name get-class :? :1 -- :doc retrieve class record SELECT * from classes WHERE id = :id; -- :name get-students-by-class :? :* -- :doc retrieve students given class id SELECT * from students WHERE class_id = :class_id -- :name get-students-by-school :? :* -- :doc retrieve students given class id SELECT * from students WHERE school_id = :school_id -- :name get-students-unassigned :? :* -- :doc retrieve students without a class SELECT * from students WHERE class_id is null -- :name get-student :? :1 -- :doc retrieve students by id SELECT * from students WHERE id = :id -- :name get-student-by-user :? :1 -- :doc retrieve student by user id SELECT * from students WHERE user_id = :user_id -- :name find-student-by-code :? :1 -- :doc retrieve student by access code and school id SELECT * from students WHERE school_id = :school_id AND access_code = :access_code -- :name create-teacher! :<! -- :doc creates a new teacher record INSERT INTO teachers (user_id, school_id) VALUES (:user_id, :school_id) RETURNING id -- :name get-teacher-by-user :? :1 -- :doc retrieve teacher by user id SELECT * from teachers WHERE user_id = :user_id -- :name get-teacher-by-school :? :* -- :doc retrieve teacher by user id SELECT * from teachers WHERE school_id = :school_id -- :name get-first-school :? :1 -- :doc retrieve first school record SELECT * from schools LIMIT 1 -- :name access-code-exists? :? :1 -- :doc retrieve first school record SELECT true as result from students WHERE school_id = :school_id AND access_code = :access_code -- :name create-new-school! :<! -- :doc creates a new school record INSERT INTO schools (name) VALUES (:name) RETURNING id -- :name get-school :? :1 -- :doc retrieve school record SELECT * from schools WHERE id = :id -- :name get-schools :? :* -- :doc retrieve school records SELECT * from schools -- :name update-school! :! :n -- :doc updates an existing school record UPDATE schools SET name = :name WHERE id = :id -- :name delete-school! :! :n -- :doc deletes school DELETE from schools WHERE id = :id<file_sep>-- :name create-progress! :<! -- :doc creates a new course progress record INSERT INTO course_progresses (user_id, course_id, data) VALUES (:user_id, :course_id, :data) RETURNING id -- :name save-progress! :! :n -- :doc updates an existing course progress record UPDATE course_progresses SET data = :data WHERE id = :id -- :name get-progress :? :1 -- :doc retrieves a progress record given the user id and course id SELECT * FROM course_progresses WHERE user_id = :user_id and course_id = :course_id -- :name get-course-progresses-by-school :? :* -- :doc retrieves a progress record given the user id and course id SELECT cp.* FROM course_progresses cp JOIN users u ON (cp.user_id=u.id) JOIN students s ON (s.user_id=u.id) WHERE s.school_id = :school_id -- :name get-course-events-by-school :? :* -- :doc retrieves a progress record given the user id and course id SELECT ce.* FROM course_events ce JOIN users u ON (ce.user_id=u.id) JOIN students s ON (s.user_id=u.id) WHERE s.school_id = :school_id -- :name create-event! :<! -- :doc creates a new course event record INSERT INTO course_events (user_id, course_id, created_at, type, guid, data) VALUES (:user_id, :course_id, :created_at, :type, :guid, :data) RETURNING id -- :name create-course-stat! :<! -- :doc creates a new course stat record INSERT INTO course_stats (user_id, class_id, course_id, data) VALUES (:user_id, :class_id, :course_id, :data) RETURNING id -- :name get-course-stats :? :* -- :doc retrieves course stats records for given class id and course id SELECT * FROM course_stats WHERE class_id = :class_id and course_id = :course_id -- :name get-course-stats-by-school :? :* -- :doc retrieves course stats records for given user id and course id SELECT cs.* FROM course_stats cs JOIN users u ON (cs.user_id=u.id) JOIN students s ON (s.user_id=u.id) WHERE s.school_id = :school_id -- :name get-user-course-stat :? :1 -- :doc retrieves course stats records for given user id and course id SELECT * FROM course_stats WHERE user_id = :user_id and course_id = :course_id -- :name save-course-stat! :! :n -- :doc updates an existing course stat record UPDATE course_stats SET data = :data WHERE id = :id -- :name update-course-stat-class! :! :n -- :doc updates a course stat class by user UPDATE course_stats SET class_id = :class_id WHERE user_id = :user_id -- :name unassign-course-stat! :! :n -- :doc unassigns course stat from class UPDATE course_stats SET class_id = null WHERE user_id = :user_id -- :name delete-course-stat! :! :n -- :doc deletes course stat DELETE from course_stats WHERE user_id = :user_id -- :name create-activity-stat! :<! -- :doc creates a new activity stat record INSERT INTO activity_stats (user_id, course_id, activity_id, data) VALUES (:user_id, :course_id, :activity_id, :data) RETURNING id -- :name get-user-activity-stats :? :* -- :doc retrieves activity stats records for given user id and course id SELECT * FROM activity_stats WHERE user_id = :user_id and course_id = :course_id -- :name get-activity-stat :? :1 -- :doc retrieves activity stat record for given user id, course id and activity id SELECT * FROM activity_stats WHERE user_id = :user_id and course_id = :course_id and activity_id = :activity_id -- :name save-activity-stat! :! :n -- :doc updates an existing activity stat record UPDATE activity_stats SET data = :data WHERE id = :id -- :name get-activity-stats-by-school :? :* -- :doc retrieves activity stats records for given school SELECT ast.* FROM activity_stats ast JOIN users u ON (ast.user_id=u.id) JOIN students s ON (s.user_id=u.id) WHERE s.school_id = :school_id<file_sep>#!/bin/bash #export DATABASE_URL="jdbc:postgresql://localhost/webchange?user=webchange&password=<PASSWORD>" #export PUBLIC_DIR="/srv/www/webchange/public" #export UPLOAD_DIR="/srv/www/webchange/public/upload" export config="/srv/www/webchange/config.edn" java -jar /srv/www/webchange/current.jar <file_sep>#!/bin/bash DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd)" echo $DIR sudo -u postgres -i bash << EOF psql --command="CREATE USER webchange WITH PASSWORD '<PASSWORD>';" createdb --owner=webchange webchange psql webchange --command='CREATE EXTENSION IF NOT EXISTS "uuid-ossp";' psql webchange < $DIR/dump-secondary.sql EOF source config.sh #java -jar webchange.jar migrate #java -jar webchange.jar init-secondary $SCHOOL_ID $EMAIL $PASSWORD <file_sep>-- :name create-user! :<! -- :doc creates a new user record INSERT INTO users (first_name, last_name, email, password, active, created_at, last_login, website_id) VALUES (:first_name, :last_name, :email, :password, :active, :created_at, :last_login, :website_id) RETURNING id -- :name update-student-user! :! :n -- :doc updates an existing user record UPDATE users SET first_name = :first_name, last_name = :last_name WHERE id = :id -- :name update-website-user! :! :n -- :doc updates an existing user record UPDATE users SET first_name = :first_name, last_name = :last_name, email = :email WHERE website_id = :website_id -- :name activate-user! :! :n -- :doc activates an existing user record UPDATE users SET active = true WHERE id = :id -- :name get-user :? :1 -- :doc retrieves a user record given the id SELECT * FROM users WHERE id = :id -- :name find-user-by-email :? :1 -- :doc retrieves a user record given the email SELECT * FROM users WHERE email = :email -- :name find-user-by-website-id :? :1 -- :doc retrieves a user record given the website id SELECT * FROM users WHERE website_id = :website_id -- :name delete-user! :! :n -- :doc deletes a user record given the id DELETE FROM users WHERE id = :id; -- :name get-users-by-school :? :* -- :doc retrieve all versions of given course SELECT u.* FROM users u LEFT JOIN teachers t ON (t.user_id=u.id) LEFT JOIN students s ON (s.user_id=u.id) WHERE t.school_id = :school_id or s.school_id = :school_id; -- :name create-course! :<! -- :doc creates a new course record INSERT INTO courses (name, slug, lang, image_src, status, owner_id, website_user_id) VALUES (:name, :slug, :lang, :image_src, :status, :owner_id, :website_user_id) RETURNING id -- :name save-course-info! :! :n -- :doc updates an existing course record UPDATE courses SET name = :name, slug = :slug, lang = :lang, image_src = :image_src WHERE id = :id -- :name save-course! :<! -- :doc creates a new course version record INSERT INTO course_versions (course_id, data, owner_id, created_at) VALUES (:course_id, :data, :owner_id, :created_at) RETURNING id -- :name get-course-by-id :? :1 -- :doc retrieve a course record given the id SELECT * from courses WHERE id = :id; -- :name get-course :? :1 -- :doc retrieve a course record given the slug SELECT * from courses WHERE slug = :slug; -- :name get-available-courses :? :* -- :doc retrieve all available courses SELECT * from courses WHERE status = 'published' ORDER BY name DESC LIMIT 30; -- :name get-courses-by-website-user :? :* -- :doc retrieve draft courses given website user id SELECT * from courses WHERE status = 'draft' AND website_user_id = :website_user_id ORDER BY name DESC LIMIT 30; -- :name get-course-version :? :1 -- :doc retrieve course version by id SELECT * from course_versions WHERE id = :id; -- :name get-latest-course-version :? :1 -- :doc retrieve last version of given course SELECT * from course_versions WHERE course_id = :course_id ORDER BY created_at DESC LIMIT 1; -- :name get-course-versions :? :* -- :doc retrieve all versions of given course SELECT * from course_versions WHERE course_id = :course_id ORDER BY created_at DESC LIMIT 30; -- :name get-courses :? :* -- :doc retrieve a course record given the name SELECT * from courses; -- :name find-courses-by-name :? :* -- :doc retrieve a course record given the name SELECT * from courses where name=:name; -- :name create-scene! :<! -- :doc creates a new scene record INSERT INTO scenes (course_id, name) VALUES (:course_id, :name) RETURNING id -- :name save-scene! :<! -- :doc creates a new course version record INSERT INTO scene_versions (scene_id, data, owner_id, created_at) VALUES (:scene_id, :data, :owner_id, :created_at) RETURNING id -- :name get-scene :? :1 -- :doc retrieve a scene record given the course id and the name SELECT * from scenes WHERE course_id = :course_id AND name = :name; -- :name get-scenes :? :* -- :doc retrieve a scene record given the course id and the name SELECT * from scenes; -- :name get-scene-version :? :1 -- :doc retrieve scene version by id SELECT * from scene_versions WHERE id = :id; -- :name get-latest-scene-version :? :1 -- :doc retrieve last version of given scene SELECT * from scene_versions WHERE scene_id = :scene_id ORDER BY created_at DESC LIMIT 1; -- :name get-scene-versions :? :* -- :doc retrieve all versions of given scene SELECT * from scene_versions WHERE scene_id = :scene_id ORDER BY created_at DESC LIMIT 30; -- :name delete-scene-skills! :! :n -- :doc deletes all scene skills DELETE FROM scene_skills WHERE scene_id = :scene_id; -- :name create-scene-skill! :! :n -- :doc creates a new scene-skill link INSERT INTO scene_skills (scene_id, skill_id) VALUES (:scene_id, :skill_id); <file_sep>-- :name create-or-update-user! :! :n -- :doc creates a new user record INSERT INTO users (id, first_name, last_name, email, password, active, created_at, last_login, guid) VALUES (:id, :first_name, :last_name, :email, :password, :active, :created_at, :last_login, :guid) ON CONFLICT ON CONSTRAINT users_pkey DO UPDATE SET first_name=:first_name, last_name=:last_name, email=:email, password=:<PASSWORD>, active=:active, created_at=:created_at, last_login=:last_login WHERE users.guid=:guid -- :name create-or-update-user-by-guid! :! :n -- :doc creates a new user record INSERT INTO users (guid, first_name, last_name, email, password, active, created_at, last_login) VALUES (:guid, :first_name, :last_name, :email, :password, :active, :created_at, :last_login) ON CONFLICT ON CONSTRAINT user_unique DO UPDATE SET first_name=:first_name, last_name=:last_name, email=:email, password=:<PASSWORD>, active=:active, created_at=:created_at, last_login=:last_login WHERE users.guid=:guid -- :name create-or-update-teacher! :! :n -- :doc creates a new teacher record INSERT INTO teachers (user_id, school_id) VALUES (:user_id, :school_id) ON CONFLICT ON CONSTRAINT teacher_unique DO NOTHING; -- :name clear-teachers! :! :n -- :doc deletes teachers DELETE from teachers; -- :name create-or-update-student! :! :n -- :doc creates a new student record INSERT INTO students (class_id, user_id, school_id, access_code, gender, date_of_birth) VALUES (:class_id, :user_id, :school_id, :access_code, :gender, :date_of_birth) ON CONFLICT ON CONSTRAINT student_unique DO UPDATE SET school_id=:school_id, access_code=:access_code, gender=:gender, date_of_birth=:date_of_birth, class_id=:class_id WHERE students.user_id=:user_id -- :name create-or-update-class! :! :n -- :doc creates a new student record INSERT INTO classes (id, name, school_id, guid) VALUES (:id, :name, :school_id, :guid) ON CONFLICT ON CONSTRAINT classes_pkey DO UPDATE SET name=:name, school_id=:school_id WHERE classes.id=:id -- :name create-or-update-class-by-guid! :! :n -- :doc creates a new student record INSERT INTO classes (guid, name, school_id) VALUES (:guid, :name, :school_id) ON CONFLICT ON CONSTRAINT class_unique DO UPDATE SET name=:name, school_id=:school_id WHERE classes.guid=:guid -- :name create-or-update-courses! :! :n -- :doc creates a new student record INSERT INTO courses (id, name, slug, lang, image_src, status, owner_id, website_user_id) VALUES (:id, :name, :slug, :lang, :image_src, :status, :owner_id, :website_user_id) ON CONFLICT ON CONSTRAINT courses_pkey DO UPDATE SET name=:name, slug=:slug, lang=:lang, image_src=:image_src, status=:status, owner_id=:owner_id, website_user_id=:website_user_id WHERE courses.id=:id -- :name create-or-update-course-versions! :! :n -- :doc creates a new student record INSERT INTO course_versions (id, course_id, data, owner_id, created_at) VALUES (:id, :course_id, :data, :owner_id, :created_at) ON CONFLICT ON CONSTRAINT course_versions_pkey DO UPDATE SET course_id=:course_id, data=:data, owner_id=:owner_id, created_at=:created_at WHERE course_versions.id=:id -- :name get-course-versions-by-school :? :* -- :doc retrieve course version by id SELECT a.* FROM course_versions a INNER JOIN ( SELECT course_id, MAX(created_at) created_at FROM course_versions GROUP BY course_id ) b ON a.course_id = b.course_id AND a.created_at = b.created_at; -- :name create-or-update-course-stat! :! :n -- :doc creates a new course stat record INSERT INTO course_stats (user_id, class_id, course_id, data) VALUES (:user_id, :class_id, :course_id, :data) ON CONFLICT ON CONSTRAINT course_stats_unique DO UPDATE SET data=:data WHERE course_stats.user_id=:user_id and course_stats.class_id=:class_id and course_stats.course_id=:course_id; -- :name create-or-update-progress! :! :n -- :doc creates a new course progress record INSERT INTO course_progresses (user_id, course_id, data) VALUES (:user_id, :course_id, :data) ON CONFLICT ON CONSTRAINT course_progresses_unique DO UPDATE SET data=:data WHERE course_progresses.user_id=:user_id and course_progresses.course_id=:course_id; -- :name create-or-update-event! :! :n -- :doc creates a new course event record INSERT INTO course_events (user_id, course_id, created_at, type, guid, data) VALUES (:user_id, :course_id, :created_at, :type, :guid, :data) ON CONFLICT ON CONSTRAINT course_events_unique DO UPDATE SET data=:data WHERE course_events.guid=:guid; -- :name find-course-events-by-id :? :1 -- :doc retrieves a progress record given the user id and course id SELECT * FROM course_events WHERE id = :id -- :name create-or-update-dataset! :! :n -- :doc creates a new dataset record INSERT INTO datasets (id, course_id, name, scheme) VALUES (:id, :course_id, :name, :scheme) ON CONFLICT ON CONSTRAINT datasets_pkey DO UPDATE SET course_id=:course_id, name=:name, scheme=:scheme WHERE datasets.id=:id -- :name clear-dataset-items! :! :<! -- :doc truncate table TRUNCATE TABLE dataset_items; -- :name create-or-update-dataset-item-with-id! :! :n -- :doc creates a new dataset item record INSERT INTO dataset_items (id, dataset_id, name, data) VALUES (:id, :dataset_id, :name, :data) ON CONFLICT ON CONSTRAINT dataset_items_pkey DO UPDATE SET dataset_id=:dataset_id, name=:name, data=:data WHERE dataset_items.id=:id -- :name create-or-update-lesson-set! :! :n -- :doc creates a new lesson set item record INSERT INTO lesson_sets (id, name, dataset_id, data) VALUES (:id, :name, :dataset_id, :data) ON CONFLICT ON CONSTRAINT lesson_sets_pkey DO UPDATE SET dataset_id=:dataset_id, name=:name, data=:data WHERE lesson_sets.id=:id -- :name create-or-update-scene! :! :n -- :doc creates a new scene record INSERT INTO scenes (id, course_id, name) VALUES (:id, :course_id, :name) ON CONFLICT ON CONSTRAINT scenes_pkey DO UPDATE SET course_id=:course_id, name=:name WHERE scenes.id=:id -- :name create-or-update-scene-version! :! :n -- :doc creates a new course version record INSERT INTO scene_versions (id, scene_id, data, owner_id, created_at) VALUES (:id, :scene_id, :data, :owner_id, :created_at) ON CONFLICT ON CONSTRAINT scene_versions_pkey DO UPDATE SET scene_id=:scene_id, data=:data, owner_id=:owner_id, created_at=:created_at WHERE scene_versions.id=:id -- :name get-scene-versions-by-school :? :* -- :doc retrieve scene version by id SELECT a.* FROM scene_versions a INNER JOIN ( SELECT scene_id, MAX(created_at) created_at FROM scene_versions GROUP BY scene_id ) b ON a.scene_id = b.scene_id AND a.created_at = b.created_at; -- :name create-or-update-activity-stat! :! :n -- :doc creates a new activity stat record INSERT INTO activity_stats (user_id, course_id, activity_id, data) VALUES (:user_id, :course_id, :activity_id, :data) ON CONFLICT ON CONSTRAINT activity_stats_unique DO UPDATE SET data=:data WHERE activity_stats.user_id=:user_id and activity_stats.course_id=:course_id and activity_stats.activity_id=:activity_id; -- :name find-users-by-guid :? :* -- :doc Characters with returned columns specified select * from users where guid in (:v*:guids); -- :name delete-activity-stats-by-user-id! :! :n -- :doc deletes activity stats DELETE from activity_stats where user_id=:user_id; -- :name delete-activity-stats-by-id! :! :n -- :doc deletes activity stats DELETE from activity_stats where id=:id; -- :name delete-course-events-by-user-id! :! :n -- :doc deletes course events DELETE from course_events where user_id=:user_id; -- :name delete-course-events-by-id! :! :n -- :doc deletes course events DELETE from course_events where id=:id; -- :name delete-course-progresses-by-user-id! :! :n -- :doc deletes course progresses DELETE from course_progresses where user_id=:user_id; -- :name delete-course-progresses-by-id! :! :n -- :doc deletes course progresses DELETE from course_progresses where id=:id; -- :name delete-course-stats-by-class-id! :! :n -- :doc deletes course progresses DELETE from course_stats where class_id=:class_id; -- :name delete-course-stats-by-user-id! :! :n -- :doc deletes course progresses DELETE from course_stats where user_id=:user_id; -- :name delete-course-stats-by-id! :! :n -- :doc deletes course progresses DELETE from course_stats where id=:id; -- :name delete-teachers-by-user-id! :! :n -- :doc deletes teachers DELETE from teachers where user_id=:user_id; -- :name delete-student-by-class-id! :! :n -- :doc deletes student DELETE from students WHERE class_id = :class_id -- :name delete-student-by-id! :! :n -- :doc deletes student DELETE from students WHERE id = :id -- :name delete-teacher-by-id! :! :n -- :doc deletes teacher by id DELETE from teachers WHERE id=:id; -- :name delete-course-by-id! :! :n -- :doc deletes courses by id DELETE from courses WHERE id=:id; -- :name delete-course-version-by-id! :! :n -- :doc deletes course-version by id DELETE from course_versions WHERE id=:id; -- :name delete-dataset-by-id! :! :n -- :doc deletes dataset by id DELETE from datasets WHERE id=:id; -- :name delete-dataset-item-by-id! :! :n -- :doc deletes dataset-item by id DELETE from dataset_items WHERE id=:id; -- :name delete-lesson-set-by-id! :! :n -- :doc deletes lesson-set by id DELETE from lesson_sets WHERE id=:id; -- :name delete-scene-by-id! :! :n -- :doc deletes scene by id DELETE from scenes WHERE id=:id; -- :name delete-scene-version-by-id! :! :n -- :doc deletes scene-version by id DELETE from scene_versions WHERE id=:id; <file_sep>#!/bin/bash sudo chmod 777 mkdir /srv/ mkdir -p /srv/www/webchange/releases cp ./run /srv/www/webchange/run cp ./config.edn /srv/www/webchange/ cp ./current.jar /srv/www/webchange/ chmod a+x /srv/www/webchange/run sudo bash << EOF cp ./webchange.service /etc/systemd/system/webchange.service systemctl daemon-reload systemctl enable webchange.service EOF
0f1d918d6db9098557671b79c239c9ba4e6af3d4
[ "SQL", "Shell" ]
8
Shell
sbs6809/webchange
086584cb98926031999e7322eeae7736e1a82071
c51d8eb6fe51a34ca821fa4de0f446fb8fdf9ddf
refs/heads/master
<repo_name>vevarm/Sia<file_sep>/api/ecosystem_test.go package api // ecosystem_test.go provides tooling and tests for whole-ecosystem testing, // consisting of multiple full, non-state-sharing nodes connected in various // arrangements and performing various full-ecosystem tasks. // // To the absolute greatest extent possible, nodes are queried and updated // exclusively through the API. import ( "errors" "net/url" "testing" "time" "github.com/NebulousLabs/Sia/types" ) // addStorageToAllHosts adds a storage folder with a bunch of storage to each // host. func addStorageToAllHosts(sts []*serverTester) error { for _, st := range sts { values := url.Values{} values.Set("path", st.dir) values.Set("size", "1048576") err := st.stdPostAPI("/host/storage/folders/add", values) if err != nil { return err } } return nil } // announceAllHosts will announce every host in the tester set to the // blockchain. func announceAllHosts(sts []*serverTester) error { // Check that all announcements will be on the same chain. _, err := synchronizationCheck(sts) if err != nil { return err } // Announce each host. for _, st := range sts { // Set the host to be accepting contracts. acceptingContractsValues := url.Values{} acceptingContractsValues.Set("acceptingcontracts", "true") err = st.stdPostAPI("/host", acceptingContractsValues) if err != nil { return err } // Fetch the host net address. var hg HostGET err = st.getAPI("/host", &hg) if err != nil { return err } // Make the announcement. announceValues := url.Values{} announceValues.Set("address", string(hg.ExternalSettings.NetAddress)) err = st.stdPostAPI("/host/announce", announceValues) if err != nil { return err } } // Wait until all of the transactions have propagated to all of the nodes. // // TODO: Replace this direct transaction pool call with a call to the // /transactionpool endpoint. // // TODO: At some point the number of transactions needed to make an // announcement may change. Currently its 2. for i := 0; i < 50; i++ { if len(sts[0].tpool.TransactionList()) == len(sts)*2 { break } time.Sleep(time.Millisecond * 100) } if len(sts[0].tpool.TransactionList()) != len(sts)*2 { return errors.New("Host announcements do not seem to have propagated to the leader's tpool") } // Mine a block and then wait for all of the nodes to syncrhonize to it. _, err = sts[0].miner.AddBlock() if err != nil { return err } _, err = synchronizationCheck(sts) if err != nil { return err } // Block until every node has completed the scan of every other node, so // that each node has a full hostdb. for _, st := range sts { var ah HostdbActiveGET for i := 0; i < 50; i++ { err = st.getAPI("/hostdb/active", &ah) if err != nil { return err } if len(ah.Hosts) >= len(sts) { break } time.Sleep(time.Millisecond * 100) } if len(ah.Hosts) < len(sts) { return errors.New("one of the nodes hostdbs was unable to find at least one host announcement") } } return nil } // fullyConnectNodes takes a bunch of tester nodes and connects each to the // other, creating a fully connected graph so that everyone is on the same // chain. // // After connecting the nodes, it verifies that all the nodes have // synchronized. func fullyConnectNodes(sts []*serverTester) error { for i, sta := range sts { var gg GatewayGET err := sta.getAPI("/gateway", &gg) if err != nil { return err } // Connect this node to every other node. for _, stb := range sts[i+1:] { // NOTE: this check depends on string-matching an error in the // gateway. If that error changes at all, this string will need to // be updated. err := stb.stdPostAPI("/gateway/connect/"+string(gg.NetAddress), nil) if err != nil && err.Error() != "already connected to this peer" { return err } } } // Perform a synchronization check. _, err := synchronizationCheck(sts) return err } // fundAllNodes will make sure that each node has mined a block in the longest // chain, then will mine enough blocks that the miner payouts manifest in the // wallets of each node. func fundAllNodes(sts []*serverTester) error { // Check that all of the nodes are synchronized. chainTip, err := synchronizationCheck(sts) if err != nil { return err } // Mine a block for each node to fund their wallet. for i := range sts { err := waitForBlock(chainTip, sts[i]) if err != nil { return err } // Mine a block. The next iteration of this loop will ensure that the // block propagates and does not get orphaned. block, err := sts[i].miner.AddBlock() if err != nil { return err } chainTip = block.ID() } // Wait until the chain tip has propagated to the first node. err = waitForBlock(chainTip, sts[0]) if err != nil { return err } // Mine types.MaturityDelay more blocks from the final node to mine a // block, to guarantee that all nodes have had their payouts mature, such // that their wallets can begin spending immediately. for i := types.BlockHeight(0); i <= types.MaturityDelay; i++ { _, err := sts[0].miner.AddBlock() if err != nil { return err } } // Block until every node has the full chain. _, err = synchronizationCheck(sts) return err } // synchronizationCheck takes a bunch of server testers as input and checks // that they all have the same current block as the first server tester. The // first server tester needs to have the most recent block in order for the // check to work. func synchronizationCheck(sts []*serverTester) (types.BlockID, error) { // Prefer returning an error in the event of a zero-length server tester - // an error should be returned if the developer accidentally uses a nil // slice instead of whatever value was intended, and there's no reason to // check for synchronization if there aren't any nodes to be synchronized. if len(sts) == 0 { return types.BlockID{}, errors.New("no server testers provided") } var cg ConsensusGET err := sts[0].getAPI("/consensus", &cg) if err != nil { return types.BlockID{}, err } leaderBlockID := cg.CurrentBlock for i := range sts { // Spin until the current block matches the leader block. success := false for j := 0; j < 100; j++ { err = sts[i].getAPI("/consensus", &cg) if err != nil { return types.BlockID{}, err } if cg.CurrentBlock == leaderBlockID { success = true break } time.Sleep(time.Millisecond * 100) } if !success { return types.BlockID{}, errors.New("synchronization check failed - nodes do not seem to be synchronized") } } return leaderBlockID, nil } // waitForBlock will block until the provided chain tip is the most recent // block in the provided testing node. func waitForBlock(chainTip types.BlockID, st *serverTester) error { var cg ConsensusGET success := false for j := 0; j < 100; j++ { err := st.getAPI("/consensus", &cg) if err != nil { return err } if cg.CurrentBlock == chainTip { success = true break } time.Sleep(time.Millisecond * 100) } if !success { return errors.New("node never reached the correct chain tip") } return nil } // TestHostPoorConnectivity creates several full server testers and links them // together in a way that might mimic a full host ecosystem with a renter, and // then isolates one of the hosts from the network, denying the host proper // transaction propagation. The renters performed chained contract forming and // uploading in the same manner that might happen in the wild, and then the // host must get a file contract to the blockchain despite not getting any of // the dependencies into the transaction pool from the flood network. func TestHostPoorConnectivity(t *testing.T) { if testing.Short() { t.SkipNow() } // Create the various nodes that will be forming the simulated ecosystem of // this test. stLeader, err := createServerTester(t.Name()) if err != nil { t.Fatal(err) } stHost1, err := blankServerTester(t.Name() + " - Host 1") if err != nil { t.Fatal(err) } stHost2, err := blankServerTester(t.Name() + " - Host 2") if err != nil { t.Fatal(err) } stHost3, err := blankServerTester(t.Name() + " - Host 3") if err != nil { t.Fatal(err) } stHost4, err := blankServerTester(t.Name() + " - Host 4") if err != nil { t.Fatal(err) } stRenter1, err := blankServerTester(t.Name() + " - Renter 1") if err != nil { t.Fatal(err) } stRenter2, err := blankServerTester(t.Name() + " - Renter 2") if err != nil { t.Fatal(err) } // Fetch all of the addresses of the nodes that got created. var ggSTL, ggSTH1, ggSTH2, ggSTH3, ggSTH4, ggSTR1, ggSTR2 GatewayGET err = stLeader.getAPI("/gateway", &ggSTL) if err != nil { t.Fatal(err) } err = stHost1.getAPI("/gateway", &ggSTH1) if err != nil { t.Fatal(err) } err = stHost2.getAPI("/gateway", &ggSTH2) if err != nil { t.Fatal(err) } err = stHost3.getAPI("/gateway", &ggSTH3) if err != nil { t.Fatal(err) } err = stHost4.getAPI("/gateway", &ggSTH4) if err != nil { t.Fatal(err) } err = stRenter1.getAPI("/gateway", &ggSTR1) if err != nil { t.Fatal(err) } err = stRenter2.getAPI("/gateway", &ggSTR2) if err != nil { t.Fatal(err) } // Connect all of the peers in a circle, so that everyone is connected but // there are a lot of hops. err = stLeader.stdPostAPI("/gateway/connect/"+string(ggSTH1.NetAddress), nil) if err != nil { t.Fatal(err) } err = stHost1.stdPostAPI("/gateway/connect/"+string(ggSTH2.NetAddress), nil) if err != nil { t.Fatal(err) } err = stHost2.stdPostAPI("/gateway/connect/"+string(ggSTH3.NetAddress), nil) if err != nil { t.Fatal(err) } err = stHost3.stdPostAPI("/gateway/connect/"+string(ggSTH4.NetAddress), nil) if err != nil { t.Fatal(err) } err = stHost4.stdPostAPI("/gateway/connect/"+string(ggSTR1.NetAddress), nil) if err != nil { t.Fatal(err) } err = stRenter1.stdPostAPI("/gateway/connect/"+string(ggSTR2.NetAddress), nil) if err != nil { t.Fatal(err) } err = stRenter2.stdPostAPI("/gateway/connect/"+string(ggSTL.NetAddress), nil) if err != nil { t.Fatal(err) } // Connectivity check - all nodes should be synchronized to the leader's // chain, which should have been the longest. allTesters := []*serverTester{stLeader, stHost1, stHost2, stHost3, stHost4, stRenter1, stRenter2} chainTip, err := synchronizationCheck(allTesters) if err != nil { t.Fatal(err) } // Mine a block from each node, to give the node money in the wallet that // is recognized by the shared chain. for i := range allTesters { // Wait until the current tester has 'chainTip' as its current // block, to make sure the network is building a community chain // instead of creating orphans. var cg ConsensusGET success := false for j := 0; j < 100; j++ { err = allTesters[i].getAPI("/consensus", &cg) if err != nil { t.Fatal(err) } if cg.CurrentBlock == chainTip { success = true break } time.Sleep(time.Millisecond * 100) } if !success { t.Fatal("nodes do not seem to be synchronizing") } err := allTesters[i].cs.Flush() if err != nil { t.Fatal(err) } // Mine a block for this node. The next iteration will wait for // synchronization before mining the block for the next node. block, err := allTesters[i].miner.AddBlock() if err != nil { t.Fatal(err, i) } chainTip = block.ID() } // Wait until the leader has the most recent block. var cg ConsensusGET success := false for i := 0; i < 100; i++ { err = allTesters[0].getAPI("/consensus", &cg) if err != nil { t.Fatal(err) } if cg.CurrentBlock == chainTip { success = true break } time.Sleep(time.Millisecond * 100) } if !success { t.Fatal("nodes do not seem to be synchronizing") } // Make sure that everyone has the most recent block. _, err = synchronizationCheck(allTesters) if err != nil { t.Fatal(err) } // Mine blocks from the leader until everyone's miner payouts have matured // and become spendable. for i := types.BlockHeight(0); i <= types.MaturityDelay; i++ { _, err := stLeader.miner.AddBlock() if err != nil { t.Fatal(err) } } _, err = synchronizationCheck(allTesters) if err != nil { t.Fatal(err) } } <file_sep>/modules/wallet/database_test.go package wallet import ( "os" "path/filepath" "testing" "github.com/NebulousLabs/Sia/build" "github.com/NebulousLabs/Sia/modules" "github.com/NebulousLabs/Sia/types" "github.com/NebulousLabs/bolt" ) // TestDBOpen tests the wallet.openDB method. func TestDBOpen(t *testing.T) { w := new(Wallet) err := w.openDB("") if err == nil { t.Fatal("expected error, got nil") } testdir := build.TempDir(modules.WalletDir, "TestDBOpen") os.MkdirAll(testdir, 0700) err = w.openDB(filepath.Join(testdir, dbFile)) if err != nil { t.Fatal(err) } w.db.View(func(tx *bolt.Tx) error { for _, b := range dbBuckets { if tx.Bucket(b) == nil { t.Error("bucket", string(b), "does not exist") } } return nil }) w.db.Close() } // TestDBHistoricHelpers tests the get/put helpers for the HistoricOutputs and // HistoricClaimStarts buckets. func TestDBHistoricHelpers(t *testing.T) { wt, err := createBlankWalletTester("TestDBHistoricOutputs") if err != nil { t.Fatal(err) } defer wt.closeWt() id := types.OutputID{1, 2, 3} c := types.NewCurrency64(7) wt.wallet.mu.Lock() dbPutHistoricOutput(wt.wallet.dbTx, id, c) c2, err := dbGetHistoricOutput(wt.wallet.dbTx, id) if err != nil { t.Fatal(err) } else if c2.Cmp(c) != 0 { t.Fatal(c, c2) } wt.wallet.mu.Unlock() soid := types.SiafundOutputID{1, 2, 3} c = types.NewCurrency64(7) wt.wallet.mu.Lock() defer wt.wallet.mu.Unlock() dbPutHistoricClaimStart(wt.wallet.dbTx, soid, c) c2, err = dbGetHistoricClaimStart(wt.wallet.dbTx, soid) if err != nil { t.Fatal(err) } else if c2.Cmp(c) != 0 { t.Fatal(c, c2) } }
d24ce581119a58d72799270342dac26b6c05d7d0
[ "Go" ]
2
Go
vevarm/Sia
1ee0914344f07e229f347a0e5cf086075132525e
59298961afa89ec9077b057711fbfb258235213c
refs/heads/master
<file_sep>package com.example; import android.app.Activity; import android.os.Bundle; import android.os.Message; import android.widget.TextView; import android.os.Handler; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.net.ServerSocket; import java.net.Socket; public class MyServer extends Activity { ServerSocket ss = null; String mClientMsg = ""; Thread mCommsThread = null; protected static final int MSG_ID = 0x1337; public static final int SERVERPORT = 6000; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); TextView tv = (TextView)findViewById(R.id.TextView01); tv.setText("Nothing from client yet"); this.mCommsThread = new Thread(new CommsThread()); this.mCommsThread.start(); } protected void onStop(){ super.onStop(); try{ ss.close(); }catch (IOException e){ e.printStackTrace(); } } Handler myUpdateHandler = new Handler(){ public void handleMessage(Message msg){ switch (msg.what){ case MSG_ID: TextView tv = (TextView)findViewById(R.id.TextView01); tv.setText(mClientMsg); default: break; } super.handleMessage(msg); } }; class CommsThread implements Runnable{ public void run(){ Socket socket = null; try{ ss = new ServerSocket(SERVERPORT); }catch(IOException e){ e.printStackTrace(); } while (!Thread.currentThread().isInterrupted()){ Message m = new Message(); m.what = MSG_ID; try{ if (socket == null) socket = ss.accept(); BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream())); String st = null; st = input.readLine(); mClientMsg = st; myUpdateHandler.sendMessage(m); } catch (IOException e){ e.printStackTrace(); } } } } } <file_sep>package SocketServer; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; /** * Created with IntelliJ IDEA. * User: richard * Date: 5/31/12 * Time: 10:25 AM * To change this template use File | Settings | File Templates. */ public class SocketServer { private static ServerSocket serverSocket=null; public static void main(String[] args){ try{ serverSocket = new ServerSocket(4444); }catch(IOException e){ System.out.println("Couldn't listen to port 4444"); System.exit(-1); } Socket clientSocket = null; try{ clientSocket = serverSocket.accept(); }catch (IOException e){ System.out.println("Accept failed on port 4444"); System.exit(-1); } } } <file_sep>package com.synctest; import java.lang.Exception; import java.util.ArrayList; import android.content.ContentProvider; import android.text.TextUtils; import android.os.Bundle; import android.content.Context; import android.content.ContentValues; import android.content.ContentProviderOperation; import android.database.Cursor; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; public class DatabaseHelper extends SQLiteOpenHelper{ private static final String DATABASE_NAME = "my_games.db"; public DatabaseHelper(Context context){ super(context, DATABASE_NAME, null, 1); } @Override public void onCreate(SQLiteDatabase db){ Cursor c = db.rawQuery("SELECT name FROM sqlite_master WHERE type='table' AND name='my_games'", null); try{ if (c.getCount() == 0){ db.execSQL("CREATE TABLE my_games (_id INTEGER PRIMARY KEY AUTOINCREMENT, title TEXT, difficulty TEXT);"); ContentValues cv = new ContentValues(); /*cv.put(TestProvider.Contract.TITLE, "God of War"); cv.put(TestProvider.Contract.DIFFICULTY, "Varying"); db.insert("my_games", TestProvider.Contract.TITLE, cv);*/ } }finally{ c.close(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion){ db.execSQL("DROP TABLE IF EXISTS my_games"); onCreate(db); } } <file_sep>package com.example; import android.app.Activity; import android.app.ListActivity; import android.content.Intent; import android.graphics.Color; import android.net.Uri; import android.os.Bundle; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import java.io.File; public class MyActivity extends ListActivity { private File curDir; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); if (savedInstanceState==null) curDir = new File("/"); else curDir = new File(savedInstanceState.getString("curDir")); setListAdapter(new FileAdapter()); } @Override public void onSaveInstanceState(Bundle bundle){ bundle.putString("curDir", curDir.toString()); } public void onListItemClick(ListView parent, View v, int position, long id){ String file = (String)getListAdapter().getItem(position); File newDir = new File(curDir.getAbsolutePath(), file); if (newDir.isDirectory() && newDir.list()!= null){ if (newDir.list().length > 0){ curDir=newDir; setListAdapter(new FileAdapter()); } }else if(newDir.isFile()){ Intent intent = new Intent(Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(newDir), "text/plain"); startActivity(intent); } } public void onBackPressed(){ if (curDir.toString().equals("/")){ super.onBackPressed(); }else{ curDir=curDir.getParentFile(); setListAdapter(new FileAdapter()); } } class FileAdapter extends ArrayAdapter<String>{ FileAdapter(){ super(MyActivity.this, R.layout.row, R.id.label, curDir.list()); } public View getView(int position, View convertView, ViewGroup parent){ View row = super.getView(position, convertView, parent); if (curDir.list()!=null){ TextView textView = (TextView)row.findViewById(R.id.label); File current_file = new File(curDir, (String)getListAdapter().getItem(position)); if (current_file.isDirectory()){ textView.setTextColor(Color.CYAN); } } return row; } } } <file_sep> package com.synctest; import java.util.ArrayList; import android.content.ContentProvider; import android.text.TextUtils; import android.os.Bundle; import android.content.Context; import android.content.ContentValues; import android.content.ContentProviderOperation; import android.content.UriMatcher; import android.content.ContentUris; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteQueryBuilder; import android.provider.BaseColumns; import android.net.Uri; public class TestProvider extends ContentProvider { private static final int GAMES=1; private static final int GAMES_ID=2; private static final UriMatcher MATCHER; private static final String TABLE = "my_games"; private DatabaseHelper db = null; public static final class Contract implements BaseColumns{ public static final String AUTHORITY = "com.synctest.TestProvider"; public static final Uri CONTENT_URI= Uri.parse("content://com.synctest.TestProvider/my_games"); public static final String DEFAULT_SORT_ORDER="title"; public static final String TITLE="title"; public static final String DIFFICULTY="difficulty"; public static final String _ID = "_id"; } static{ MATCHER = new UriMatcher(UriMatcher.NO_MATCH); MATCHER.addURI("com.synctest.TestProvider", "my_games", GAMES); MATCHER.addURI("com.synctest.TestProvider", "my_games/#", GAMES_ID); } @Override public boolean onCreate() { db = new DatabaseHelper(getContext()); return ((db == null)? false:true); } @Override public int delete(Uri url, String where, String[] whereArgs){ int count = db.getWritableDatabase().delete(TABLE, where, whereArgs); getContext().getContentResolver().notifyChange(url, null); return count; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); qb.setTables(TABLE); String orderBy; if (TextUtils.isEmpty(sort)) orderBy = Contract.DEFAULT_SORT_ORDER; else orderBy = sort; Cursor c = qb.query(db.getReadableDatabase(), projection, selection, selectionArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } @Override public Uri insert(Uri url, ContentValues initialValues){ long rowID = db.getWritableDatabase().insert(TABLE, Contract.TITLE, initialValues); if (rowID > 0){ Uri uri = ContentUris.withAppendedId(Contract.CONTENT_URI, rowID); getContext().getContentResolver().notifyChange(uri, null); return uri; } throw new SQLException("Failed to insert row int " + url); } @Override public int update(Uri url, ContentValues values, String where, String[] whereArgs) { int count = db.getWritableDatabase().update(TABLE, values, where, whereArgs); getContext().getContentResolver().notifyChange(url, null); return count; } @Override public String getType(Uri url){ if (isCollectionUri(url)) return("vnd.com.synctest.cursor.dir/my_games"); return ("vnd.com.synctest.cursor.item/my_games"); } private boolean isCollectionUri(Uri url){ return(MATCHER.match(url) == GAMES); } } <file_sep>package com.example; import android.app.Activity; import android.app.PendingIntent; import android.os.Bundle; import android.telephony.SmsManager; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.RadioGroup; import android.widget.Toast; import android.content.Intent; public class SmsGame extends Activity { RadioGroup choice; Button submit; EditText number; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); choice = (RadioGroup)findViewById(R.id.choice); submit = (Button)findViewById(R.id.submit); number = (EditText)findViewById(R.id.number); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { String phoneNo = number.getText().toString(); String data = ""; switch (choice.getCheckedRadioButtonId() ){ case R.id.rock: data = "r"; break; case R.id.paper: data = "p"; break; case R.id.scissors: data="s"; break; default: } if (!data.equals("") && phoneNo.length()>0){ sendSMS(phoneNo, data); }else{ Toast toast = Toast.makeText(getApplicationContext(), "Please choose your weapon and opponent", Toast.LENGTH_SHORT); toast.show(); } } }); } private void sendSMS(String phoneNo, String data){ PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this, SmsGame.class), 0); SmsManager sms = SmsManager.getDefault(); sms.sendTextMessage(phoneNo, null, data, pendingIntent, null); } } <file_sep>package com.example; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.telephony.SmsMessage; import android.os.Bundle; import android.widget.Toast; /** * Created with IntelliJ IDEA. * User: richard * Date: 5/25/12 * Time: 8:28 AM * To change this template use File | Settings | File Templates. */ public class SmsReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent){ Bundle extras = intent.getExtras(); SmsMessage[] msgs = null; String str = ""; if (extras!= null){ Object[] pdus = (Object[])extras.get("pdus"); msgs = new SmsMessage[pdus.length]; for (int i=0; i< msgs.length; ++i){ msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]); str+= msgs[i].getMessageBody().toString(); str+= "\n"; } Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); } } } <file_sep>package com.synctest; import android.view.View; import android.app.Activity; import android.os.Bundle; import android.content.Context; import android.content.ContentResolver; import android.widget.EditText; import android.widget.Toast; import android.text.Editable; import android.content.ContentValues; import java.util.ArrayList; import java.lang.Exception; import android.content.ContentProviderOperation; public class GameAdder extends Activity { private EditText title; private EditText difficulty; @Override public void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.game_adder); title = (EditText)findViewById(R.id.title); difficulty = (EditText)findViewById(R.id.difficulty); } // Called when the Add Item button is clicked public void addToList(View view){ String titleStr = title.getText().toString(); String difficultyStr = difficulty.getText().toString(); if (titleStr == null || difficultyStr == null) return; ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>(); // Add name field ops.add(ContentProviderOperation.newInsert( TestProvider.Contract.CONTENT_URI) .withValue(TestProvider.Contract.TITLE, titleStr) .withValue(TestProvider.Contract.DIFFICULTY, difficultyStr) .build()); try{ getContentResolver().applyBatch(TestProvider.Contract.AUTHORITY, ops); Toast.makeText(this, "Game Added", Toast.LENGTH_SHORT).show(); }catch(Exception e){ e.printStackTrace(); } finish(); } }
7a21808df588a1a94fd45f037fcee646171ae1eb
[ "Java" ]
8
Java
whalenrp/android-summer-projects
c4e1b5186459a60ee81fb944616830242f9b199b
4155d6c6f1d6c4ae41cc56b36b23861a06d334ac
refs/heads/master
<file_sep>import reducer from '../../futils/reducer' // ------------------------------------ // Constants // ------------------------------------ // Constants Here // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { } // ------------------------------------ // Reducer // ------------------------------------ const initialState = {} export default reducer(initialState, ACTION_HANDLERS) <file_sep>import React from 'react' const Searchbox = () => <div className='topbar'> <input type='text' name='search' placeholder='Enter package name' className='searchbar' /> </div> export default Searchbox <file_sep>import reducer from '../futils/reducer' const Actionhandlers = { TOGGLE_NAV: (state, action) => ({ ...state, shownav: !state.shownav }) } const Init = { shownav: false } export default reducer(Init, Actionhandlers) <file_sep>import React from 'react' import PT from 'prop-types' // eslint-disable-line import { LineChart, Line } from 'recharts' export const SampleGraph = ({ data, width, height }) => <LineChart width={width} height={height} data={data} margin={{ top: 5 }}> <Line type='monotone' dataKey='downloads' stroke='#F82462' strokeWidth={2} /> </LineChart> SampleGraph.propTypes = { data: PT.array, width: PT.number, height: PT.number } const PackCard = ({ name, data }) => <div className='card-outside'> <div className='card-body'> <div className='card-top'> <div className='card-heading'>{name}</div> <div>34⭐️/10🍴</div> </div> <div className='card-desc'> Retask is a simple task queue implementation written for human beings. It provides generic solution to create and manage task queues. </div> </div> <div className='card-graph'> <SampleGraph data={data} height={110} width={280} /> </div> </div> PackCard.propTypes = { name: PT.string, data: PT.array } export default PackCard <file_sep># General Js #### Installation and Development - Clone the Repo `git clone https://github.com/kanitsharma/general-js`. - Change directory `cd general-js`. - Checkout to required branch according to the style of configuration. - Remove git records `rm -rf .git` - `npm i or yarn install` to install dependencies. - `npm start or yarn start` to start development server. - `npm build` to build project. - `npm deploy` to deploy to `gh-pages`. <file_sep>import React from 'react' import PropTypes from 'prop-types' import { RotatingPlane } from 'better-react-spinkit' const Loader = ({ loading }) => <div> {loading && <div className='loader-overlay'> <RotatingPlane size={100} color='#fff' /> </div> } </div> Loader.propTypes = { loading: PropTypes.bool } export default Loader <file_sep>import { call, put, takeLatest, all } from 'redux-saga/effects' //eslint-disable-line import actionSpreader from '../../utils/actionspreader' import request from '../../utils/request' const packageInfoUrl = pack => `https://api.npmjs.org/downloads/range/last-month/${pack}` export function * getFamousListener (action) { yield put(actionSpreader('LOADER', { loading: true })) try { const [ downloadedData ] = yield all([ call(request, packageInfoUrl(action.payload.tag)) ]) yield put(actionSpreader('FAMOUSDATA', { Downloads: downloadedData })) } catch (e) { yield put(actionSpreader('GETFAMOUSERROR')) } } export function * showcaseSaga () { yield takeLatest('GETFAMOUS', getFamousListener) } export default [showcaseSaga] <file_sep>import React from 'react' import PropTypes from 'prop-types' const VerticalSection = ({ tags, click, active }) => <div className='vertical'> {tags.map((tag, i) => <div className={`tag`} onClick={() => click(tag)} key={i}>#{tag} <span className={tag === active ? 'active' : ''} /> </div>) } </div> VerticalSection.propTypes = { tags: PropTypes.array, click: PropTypes.func, active: PropTypes.string } export default VerticalSection <file_sep>import reducer from '../../futils/reducer' // ------------------------------------ // Constants // ------------------------------------ // Constants Here // ------------------------------------ // Action Handlers // ------------------------------------ const ACTION_HANDLERS = { FAMOUSDATA: (s, a) => ({ ...s, Downloads: a.payload.Downloads.downloads, active: a.payload.Downloads.package, loading: false }), LOADER: (s, a) => ({ ...s, loading: a.payload.loading }) } // ------------------------------------ // Reducer // ------------------------------------ const initialState = { Downloads: [], active: '', loading: false } export default reducer(initialState, ACTION_HANDLERS) <file_sep>import React, { Component } from 'react' import PT from 'prop-types' import Gridcomponent from '../../components/gridcomponent' import PackCard, { SampleGraph } from '../../components/packcard' import Hheader from '../../components/hover-header' import HeadingHero from '../../static/Orange Juice.jpeg' import VerticalSection from '../../components/verticalsection' import Loader from '../../components/loader' import Searchbox from '../../components/searchbox' class Showcase extends Component { componentDidMount () { this.props.getfamous('react') } render () { const tags = [ 'webpack', 'react', 'angular', 'vue', 'jquery' ] const { Downloads, active, loading } = this.props return <div className='column-container'> <div className='background' /> <VerticalSection active={active} tags={tags} click={(tag) => this.props.getfamous(tag)} /> <Loader loading={loading} /> <Searchbox /> <div className='grid-heading'>Popular Packages</div> <div className='row-container'> <Hheader htext={active} vtext='vuejs/vue' btext='A progressive, incrementally-adoptable JavaScript framework for building UI on the web.' width='300' height='300' hcolor='#fff' component={Downloads ? <SampleGraph data={Downloads} width={300} height={300} /> : null} source={HeadingHero} boxpos='start' hpos='center' hsize='5' animation={false} /> <Hheader htext={active} vtext='vuejs/vue' btext='A progressive, incrementally-adoptable JavaScript framework for building UI on the web.' width='300' height='300' hcolor='#fff' component={Downloads ? <SampleGraph data={Downloads} width={300} height={300} /> : null} source={HeadingHero} boxpos='start' hpos='center' hsize='5' animation={false} /> </div> <div className='grid-heading'>Latest Packages</div> <Gridcomponent> {[1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 3].map((x, i) => <PackCard name={active} data={Downloads} key={i} />)} </Gridcomponent> </div> } } Showcase.propTypes = { getfamous: PT.func, Downloads: PT.array, active: PT.string, loading: PT.bool } export default Showcase <file_sep>import React from 'react' import { Link } from 'react-router' import PropTypes from 'prop-types' import { connect } from 'react-redux' const Navmenu = ({ togglenav }) => <div className='menu-overlay'> <div className='menu'> <Link to='/home' onClick={() => togglenav()} className='menu-item'>Home</Link> <Link to='/showcase' onClick={() => togglenav()} className='menu-item'>Projects</Link> <Link to='/about' onClick={() => togglenav()} className='menu-item'>About</Link> </div> </div> Navmenu.propTypes = { togglenav: PropTypes.func } const mapStateToProps = state => ({ }) const mapDispatchToProps = dispatch => ({ togglenav: () => dispatch({ type: 'TOGGLE_NAV' }) }) export default connect(mapStateToProps, mapDispatchToProps)(Navmenu) <file_sep>import React from 'react' import PropTypes from 'prop-types' const Landingsection = ({ children, hpos, vpos, background, size }) => { const basicstyle = { display: 'flex', flexDirection: 'column', alignItems: hpos, justifyContent: vpos, background: background, } return ( <div className='panel' style={basicstyle}> {children} </div> ) } Landingsection.propTypes = { children: PropTypes.node, hpos: PropTypes.string, vpos: PropTypes.string, background: PropTypes.string, size: PropTypes.string } export default Landingsection <file_sep>import React, { Component } from 'react' import PropTypes from 'prop-types' class Hheader extends Component { constructor (props) { super(props) this.state = { x : 0, y : 0, width : 500, height : 250, boxpos : `row`, vtextpos : -2, hpos : 0, mpos : `auto`, } } componentDidMount () { if (this.props.boxpos === 'start') { this.setState({ boxpos: `row` }) } else if (this.props.boxpos === 'end') { this.setState({ boxpos: `row-reverse`, vtextpos : 95 }) } if (this.props.hpos === 'start') { this.setState({ hpos: 0, mpos : `auto` }) } else if (this.props.hpos === 'center') { this.setState({ hpos: 20, mpos : `0px` }) } else if (this.props.hpos === `end`) { this.setState({ hpos : 50, mpos : `0px` }) } } render () { const container = { width : `${this.state.width}px`, height : `auto`, display : `flex`, flexDirection : `${this.state.boxpos}`, position : `relative` } const vertical = { writingMode : `vertical-lr`, position : `absolute`, bottom : 0, left : `${this.state.vtextpos}%`, padding : `5px 0px`, color: `#fcfcfc` } const column = { display : `flex`, flexDirection : `column`, justifyContent : `space-between`, alignItems : `flex-${this.props.boxpos}` } const middle = { margin : `${this.state.mpos} 10px`, zIndex : `10` } const transform1 = { position : `absolute`, color: `${this.props.hcolor}`, top : `${this.state.hpos}%`, left : `17%`, fontSize : `${this.props.hsize}em`, transform : `translate(${this.state.x}px,${this.state.y}px)`, transition : `all 0.1s ease` } const transform2 = { transform : `translate(-${this.state.x}px,-${this.state.y}px)`, width : `${this.props.width}px`, height : `${this.props.height}px`, transition : `all 0.1s ease` } const hover = event => { if (this.props.animation) { this.setState({ x : (event.pageX - document.getElementById('div').offsetLeft) * 0.05, y : (event.pageY - document.getElementById('div').offsetTop) * 0.1 }) } } const leave = event => { this.setState({ x : 0, y : 0 }) } const enter = event => { if (this.props.animation) { this.setState({ x : event.clientX * 0.01, y : event.clientY * 0.01 }) } } return ( <div onMouseMove={hover} onMouseEnter={enter} onMouseLeave={leave} style={container} id='div'> <div style={transform2} className='headerbox'> {this.props.component || <img src={this.props.source} width={this.props.width} height={this.props.height} />} </div> <p style={vertical}>{this.props.vtext}</p> <h1 style={transform1}>{this.props.htext}</h1> <div style={column}> <p style={middle}>{this.props.mtext}</p> <p style={{ zIndex:`10`, margin: `0px 10px`, color: `#fcfcfc` }}>{this.props.btext}</p> </div> </div> ) } } Hheader.propTypes = { animation: PropTypes.bool, source: PropTypes.string, component: PropTypes.element, vtext: PropTypes.string, mtext: PropTypes.string, htext: PropTypes.string, btext: PropTypes.string, width: PropTypes.string, height: PropTypes.string, hsize: PropTypes.string, hpos: PropTypes.string, boxpos: PropTypes.string, hcolor: PropTypes.string } export default Hheader <file_sep>import React, { Component } from 'react' import PropTypes from 'prop-types' class Swiftscroll extends Component { componentDidMount () { let scrollamount = 0 let panelcounter = 0 let wait = false const well = this.well well.style.transform = 'translateY(0)' const panels = [...document.querySelectorAll('.panel')] well.addEventListener('wheel', e => { if (e.deltaY < 0 && panelcounter > 0 && wait === false) { wait = true scrollamount += this.props.amount panelcounter-- well.style.transform = `translateY(${scrollamount}vh)` setTimeout(function () { wait = false }, 1000) } if (e.deltaY > 0 && panelcounter < panels.length - 1 && wait === false) { wait = true scrollamount -= this.props.amount panelcounter++ well.style.transform = `translateY(${scrollamount}vh)` setTimeout(function () { wait = false }, 1000) } setTimeout(() => {}, 1000) }) } render () { const wrapper = { overflow: 'hidden', height: '100vh' } return ( <div style={wrapper}> <div ref={(input) => { this.well = input }} className='well' > {this.props.children} </div> </div> ) } } Swiftscroll.propTypes = { amount: PropTypes.number, children: PropTypes.node } export default Swiftscroll <file_sep>import React from 'react' import Navmenu from './navmenu' import PropTypes from 'prop-types' import { connect } from 'react-redux' import { pick } from 'ramda' import ReactCSSTransitionGroup from 'react-addons-css-transition-group' const Header = ({ togglenav, shownav }) => { return ( <div> <div className='header'> <div className={`nav-icon ${shownav ? 'open' : ''}`} onClick={() => togglenav()}> <span /> <span /> <span /> </div> </div> <ReactCSSTransitionGroup transitionName='nav' transitionEnterTimeout={1000} transitionLeaveTimeout={450}> {shownav && <Navmenu />} </ReactCSSTransitionGroup> </div> ) } Header.propTypes = { togglenav: PropTypes.func, shownav: PropTypes.bool } const mapStateToProps = state => ({ ...pick(['shownav'], state.togglenav) }) const mapDispatchToProps = dispatch => ({ togglenav: () => dispatch({ type: 'TOGGLE_NAV' }) }) export default connect(mapStateToProps, mapDispatchToProps)(Header)
b13b76880b62c877823dd256f353014e8392898f
[ "JavaScript", "Markdown" ]
15
JavaScript
kanitsharma/general-js
ce3ed4b8d1f6ceaacc3e0429e5eabcc0fbccb900
a182959a81ddb2b39552d81f68f352d1c9b1e962
refs/heads/master
<repo_name>ltititans/Student_Project<file_sep>/Hibernate_Project2/src/main/java/com/lti/hib_ex/Hibernate_Project2/App.java package com.lti.hib_ex.Hibernate_Project2; import java.util.Scanner; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; import org.hibernate.cfg.Configuration; import com.lti.hib_ex.Hibernate_Project2.Student; /** * Hello world! * */ public class App { public static void main( String[] args ) { Configuration configuration = new Configuration().configure(); StandardServiceRegistryBuilder builder =new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()); SessionFactory factory=configuration.buildSessionFactory(builder.build()); Session session=factory.openSession(); Student student=new Student(); Scanner ob=new Scanner(System.in); System.out.println("Enter your choice:"); int n=ob.nextInt(); if(n==1) { student.setName("ABD"); student.setAddress("Africa"); session.beginTransaction(); session.save(student); session.getTransaction().commit(); } else if(n==2) { student.setRollno(1); student.setName("MSD"); student.setAddress("India"); session.beginTransaction(); session.update(student); session.getTransaction().commit(); } } }
388c44f47feb53d76657b11dff9df74dc744ae48
[ "Java" ]
1
Java
ltititans/Student_Project
e6caec318bdb630c746b926ad1df5ca225d365ea
437e338128c4c9e6b6eab2f023b47c51b7f68806
refs/heads/master
<file_sep>/* * File: foo.c * Author: woe * * Created on September 10, 2018, 5:57 PM */ #include "xc.h" <file_sep># # Generated - do not edit! # # NOCDDL # CND_BASEDIR=`pwd` # default configuration CND_ARTIFACT_DIR_default=dist/default/production CND_ARTIFACT_NAME_default=Sample_Code.production.hex CND_ARTIFACT_PATH_default=dist/default/production/Sample_Code.production.hex CND_PACKAGE_DIR_default=${CND_DISTDIR}/default/package CND_PACKAGE_NAME_default=samplecode.tar CND_PACKAGE_PATH_default=${CND_DISTDIR}/default/package/samplecode.tar <file_sep># drivers-elective #### Programmer used PICKit 3 #### Microcontroller used -- todo -- #### IDE used MPLab X 5.5
5cfb7ee64e99ea3f9634317b8dddda1d4c42e84a
[ "Markdown", "C", "Makefile" ]
3
C
javenschuetz/drivers-elective
c8440ac80a31e0ed415868623aea10d1be313bca
7dccee196647049d232603c508c5579d880e9e36
refs/heads/master
<file_sep>DZ po FLITE ==== Цель работы: ----- Написать на языке С и отладить программу, реализующую следующие функции: * Задание множества чисел в двоичной системе; * Перевод из двоичной в десятичную систему исчисления; * Вывод элементов 2-х множеств; 1: Исходные данные -------- Количество множеств, длина множества 1 и 2 2: Выполнение -------- Задание двух множеств в двоичной системе; Перевод из двоичной в десятичную систему исчисления; Вывод элементов 2-х множеств; 4: Вывод ----------- Мы получили программу, с помощью которой мы можем задать множества в двоичной системе исчисления, перевести элементы множества из двоичной системы исчисления в десятичную и получить вывод элементов множества. <file_sep>#include <stdio.h> #include <stdlib.h> #include <math.h> int main(){ printf("Kol: "); int kol; scanf("%d", &kol); unsigned long *binary1, *binary2, *decimal; binary1 = calloc(kol, sizeof(unsigned long)); binary2 = calloc(kol, sizeof(unsigned long)); decimal = calloc(kol, sizeof(unsigned long)); int n; for(n=0;n<kol;n++){ scanf("%lu", &binary1[n]); binary2[n] = binary1[n];} for(n=0;n<kol;n++){ int m=0,buff=0; while(binary2[n] != 0){ if(binary2[n]%10 > 0){ buff = pow(2,m); decimal[n] = decimal[n] + buff;} binary2[n] /= 10; m++;}} for(n=0;n<kol;n++){ printf("Dvoichnaya-%lu; Desyatichnaya-%lu\n",binary1[n], decimal[n]);} return 0;}
dc0257623882aa54cdfec13fab63d23730bd63e1
[ "Markdown", "C" ]
2
Markdown
n4talia/hello-world
01b6b5c032330a1abcf9e3bd6e302e9431d308ee
d3476797850e2c95aeb611a4f5f80f1d6e0f2c98
refs/heads/master
<file_sep><?php class Advent { protected $dataSet; public function __construct() { // 2 values = 252724 // 3 values = 276912720 $this->dataSet = explode("\n", file_get_contents('./src/input-day-1.txt')); } public function calculate() { foreach ($this->dataSet as $record) { foreach ($this->dataSet as $newRecord) { foreach ($this->dataSet as $thirdRecord) { if ($record + $newRecord + $thirdRecord === 2020) { var_dump([$record, $newRecord, $thirdRecord, $record * $newRecord * $thirdRecord]); return; } } } } } } (new Advent)->calculate();
53ee9c19df444d0711498eaad952c0f8038e1ab5
[ "PHP" ]
1
PHP
codebros-nl/advent-of-code-2020
ca05544856ed65b028473f42cb22e92afb707ac2
0a5c462b98998fd766f183446ccd028c5c96bb9e
refs/heads/master
<file_sep># KnockDetect 手机端敲击检测 Knock Detect on mobile 本项目的博客地址: CSDN:[http://blog.csdn.net/u013182263/article/details/51828742](http://blog.csdn.net/u013182263/article/details/51828742) 博客园:[http://www.cnblogs.com/ztysir/p/5628667.html](http://www.cnblogs.com/ztysir/p/5628667.html) 简书:[http://www.jianshu.com/p/efb9abc50969](http://www.jianshu.com/p/efb9abc50969) 个人博客:[CrazyZty.github.io](http:CrazyZty.github.io) <file_sep>package com.Tool.Global; import java.util.LinkedList; public class Variable { public static boolean isBigEnding = false; public static int knockNumber = 0; public static LinkedList<Float> linearAccelerationZList; public static String StorageDirectoryPath; public static String ErrorFilePath; }
227063667db2b4711e0585c40441df46312b40e6
[ "Markdown", "Java" ]
2
Markdown
quekai/KnockDetect
ce049e4cf004c9b3e6f074aa5e355d87215d4ab0
e08d708b45c1a51aaeb0876b508eb1fa84269032
refs/heads/master
<file_sep>package fit5120.seniorparking; import android.content.ContentValues; import android.content.Context; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import java.util.HashMap; import java.util.LinkedHashMap; /** * Created by liyunhong on 30/3/17. */ public class DatabaseHelper extends SQLiteOpenHelper { //set database properties public static final String DATABASE_NAME = "CarDB"; public static final int DATABASE_VERSION = 1; public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL(CarInfo.CREATE_STATEMENT); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { db.execSQL("DROP TABLE IF EXISTS " + CarInfo.TABLE_NAME); onCreate(db); } public void AddCarInfo(CarInfo car) { SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(CarInfo.COLUMN_LEVEL, car.getLevel()); values.put(CarInfo.COLUMN_COLOR, car.getColor()); values.put(CarInfo.COLUMN_LETTER, car.getLetter()); values.put(CarInfo.COLUMN_NUMBER, car.getNumber()); values.put(CarInfo.COLUMN_TIME,car.getTime()); values.put(CarInfo.COLUMN_LATITUDE, car.getLatitude()); values.put(CarInfo.COLUMN_LONGITUDE,car.getLongitude()); db.insert(CarInfo.TABLE_NAME, null, values); db.close(); } public void UpdateCarInfo(CarInfo car) { String[] selectionArgs = {String.valueOf(CarInfo.COLUMN_ID)}; String selection = CarInfo.COLUMN_ID + " LIKE ?"; SQLiteDatabase db = this.getWritableDatabase(); ContentValues values = new ContentValues(); values.put(CarInfo.COLUMN_LEVEL, car.getLevel()); values.put(CarInfo.COLUMN_COLOR, car.getColor()); values.put(CarInfo.COLUMN_LETTER, car.getLetter()); values.put(CarInfo.COLUMN_NUMBER, car.getNumber()); values.put(CarInfo.COLUMN_TIME,car.getTime()); values.put(CarInfo.COLUMN_LATITUDE, car.getLatitude()); values.put(CarInfo.COLUMN_LONGITUDE,car.getLongitude()); db.update(CarInfo.TABLE_NAME,values,selection, selectionArgs); db.close(); } public HashMap<Long,CarInfo> GetAllCarInfo() { HashMap<Long,CarInfo> carInfo = new LinkedHashMap<>(); SQLiteDatabase db = this.getReadableDatabase(); Cursor cursor = db.rawQuery("SELECT * FROM " + CarInfo.TABLE_NAME, null); //add each car info to hashmap if(cursor.moveToFirst()) { do { CarInfo carInfoNew = new CarInfo(cursor.getLong(0), cursor.getString(1), cursor.getString(2), cursor.getString(3), cursor.getString(4),cursor.getString(5), cursor.getString(6),cursor.getString(7)); carInfo.put(carInfoNew.get_id(), carInfoNew); } while(cursor.moveToNext()); } cursor.close(); return carInfo; } public void RemoveCarInfo(CarInfo carInfo) { SQLiteDatabase db = this.getWritableDatabase(); db.delete(CarInfo.TABLE_NAME, CarInfo.COLUMN_ID + " = ?", new String[] {String.valueOf(carInfo.get_id())}); } public void RemoveAllCar() { SQLiteDatabase db = this.getWritableDatabase(); db.execSQL("delete from "+ CarInfo.TABLE_NAME); } public void Close() { this.close(); } } <file_sep>package layout; import android.Manifest; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.Image; import android.net.Uri; import android.os.Bundle; import android.provider.Settings; import android.support.v4.app.Fragment; import android.support.v4.app.FragmentTransaction; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ImageView; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.Toast; import java.io.File; import java.io.FileInputStream; import java.util.ArrayList; import fit5120.seniorparking.CarImage; import fit5120.seniorparking.CarInfo; import fit5120.seniorparking.DatabaseHelper; import fit5120.seniorparking.DatabaseImg; import fit5120.seniorparking.GPSTracker; import fit5120.seniorparking.R; import fit5120.seniorparking.SpinnerActivity; /** * A simple {@link Fragment} subclass. * Activities that contain this fragment must implement the * {@link ParkingInfo.OnFragmentInteractionListener} interface * to handle interaction events. * Use the {@link ParkingInfo#newInstance} factory method to * create an instance of this fragment. */ public class ParkingInfo extends Fragment { private OnFragmentInteractionListener mListener; private Spinner sLevel,sNumber, sLetter, sHour, sMin; private String resLevel, resColor,resNumber,resLetter, resHour,resMin, resTime, resLat, resLon; private Button resSave; private ImageView img; private RadioGroup rGroup; private GPSTracker gps; //handle db private DatabaseHelper dbHelper; //an object of carInfo to store related info private CarInfo carInfoStoroe = new CarInfo(); public ParkingInfo() { // Required empty public constructor } /** * Use this factory method to create a new instance of * this fragment using the provided parameters. * @return A new instance of fragment ParkingInfo. */ // TODO: Rename and change types and number of parameters public static ParkingInfo newInstance() { ParkingInfo fragment = new ParkingInfo(); Bundle args = new Bundle(); return fragment; } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1647); // Inflate the layout for this fragment View parkingInfoView = inflater.inflate(R.layout.fragment_parking_info, container, false); this.sLevel = (Spinner) parkingInfoView.findViewById(R.id.spinner_level); this.sNumber = (Spinner) parkingInfoView.findViewById(R.id.spinner_number); this.sLetter = (Spinner) parkingInfoView.findViewById(R.id.spinner_letter); this.sHour = (Spinner) parkingInfoView.findViewById(R.id.spinner_hour); this.sMin = (Spinner) parkingInfoView.findViewById(R.id.spinner_minute); this.resSave = (Button) parkingInfoView.findViewById(R.id.save); this.rGroup = (RadioGroup) parkingInfoView.findViewById(R.id.radioGroup); this.img = (ImageView) parkingInfoView.findViewById(R.id.car_image) ; this.gps = new GPSTracker(getActivity()); DatabaseImg dbImg = new DatabaseImg(getActivity()); if(dbImg.GetAllCarImg() != null) { ArrayList<CarImage> carImg = new ArrayList<>(dbImg.GetAllCarImg().values()); if(carImg.size() > 0) { String imgString = carImg.get(0).getImg(); try { File imgFile = new File(imgString); Bitmap bitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); if(bitmap == null) System.out.println("123452"); img.setImageBitmap(bitmap); } catch (Exception e) { } } } //set level adapter // Create an ArrayAdapter using the string array and a default spinner layout ArrayAdapter<CharSequence> levelAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.level, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears levelAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // Apply the adapter to the spinner sLevel.setAdapter(levelAdapter); sLevel.setOnItemSelectedListener(new SpinnerActivity()); //set hour adapter ArrayAdapter<CharSequence> hourAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.hour, android.R.layout.simple_spinner_item); hourAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sHour.setAdapter(hourAdapter); sHour.setOnItemSelectedListener(new SpinnerActivity()); //set hour adapter ArrayAdapter<CharSequence> minAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.minute, android.R.layout.simple_spinner_item); minAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sMin.setAdapter(minAdapter); sMin.setOnItemSelectedListener(new SpinnerActivity()); //set number adapter ArrayAdapter<CharSequence> numberAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.number, android.R.layout.simple_spinner_item); numberAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sNumber.setAdapter(numberAdapter); sNumber.setOnItemSelectedListener(new SpinnerActivity()); //set letter adapter ArrayAdapter<CharSequence> letterAdapter = ArrayAdapter.createFromResource(getActivity(), R.array.letter, android.R.layout.simple_spinner_item); letterAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); sLetter.setAdapter(letterAdapter); sLetter.setOnItemSelectedListener(new SpinnerActivity()); //set radio group rGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() { public void onCheckedChanged(RadioGroup group, int checkedId) { // checkedId is the RadioButton selected switch(checkedId) { case R.id.radio_blue: resColor = "Blue"; break; case R.id.radio_red: resColor = "Red"; break; case R.id.radio_yellow: resColor = "Yellow"; break; default: resColor = "Not selected"; } } }); resSave.setOnClickListener(new View.OnClickListener(){ @Override public void onClick(View v) { //get db handler dbHelper = new DatabaseHelper(getActivity()); //delete existing car info if car is existing in db. if(dbHelper.GetAllCarInfo().size() != 0) { dbHelper.RemoveAllCar(); } resLevel = String.valueOf(sLevel.getSelectedItem()); resHour = sHour.getSelectedItem().toString(); resMin = sMin.getSelectedItem().toString(); resNumber = sNumber.getSelectedItem().toString(); resLetter = sLetter.getSelectedItem().toString(); if(gps.canGetLocation()) { resLat = String.valueOf(gps.getLatitude()); resLon = String.valueOf(gps.getLongitude()); } else { resLat = "-90.8770"; resLon = "145.0443"; } //set values from user input carInfoStoroe.setLevel(resLevel); carInfoStoroe.setColor(resColor); carInfoStoroe.setLetter(resLetter); carInfoStoroe.setNumber(resNumber); carInfoStoroe.setLatitude(resLat); carInfoStoroe.setLongitude(resLon); System.out.println(resLat + "========="); System.out.println(resLon + "========="); int resTimeMins; if(resHour.equals("--")) { if(resMin.equals("--")) { resTimeMins = 0; } else { resTimeMins = Integer.valueOf(resMin); } } else { if(resMin.equals("--")) { resTimeMins = Integer.valueOf(resHour)*60; } else { resTimeMins = Integer.valueOf(resHour)*60 + Integer.valueOf(resMin); } } carInfoStoroe.setTime(resTimeMins + ""); dbHelper.AddCarInfo(carInfoStoroe); Toast.makeText(getActivity(), "Save successfully ", Toast.LENGTH_SHORT).show(); dbHelper.close(); } }); return parkingInfoView; } public void onRadioButtonClicked(View view) { // Is the button now checked? boolean checked = ((RadioButton) view).isChecked(); // Check which radio button was clicked switch(view.getId()) { case R.id.radio_blue: if (checked) resColor = "blue"; break; case R.id.radio_yellow: if (checked) resColor = "Yellow"; break; case R.id.radio_red: if (checked) resColor = "Red"; break; default: resColor = "No Color Selected"; } } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * <p> * See the Android Training lesson <a href= * "http://developer.android.com/training/basics/fragments/communicating.html" * >Communicating with Other Fragments</a> for more information. */ public interface OnFragmentInteractionListener { // TODO: Update argument type and name void onFragmentInteraction(Uri uri); } }
bc38237b59df72a0d81043842b32548290d35961
[ "Java" ]
2
Java
stardaemon/SeniorParking
a16f26cff6e8fde0e4249de5df54e034db4d966a
f510549deb62a09817de4e491379d9d3fb2cc4f9
refs/heads/master
<file_sep>// let userName = prompt ("Ім'я?"); // let dateBirth = +prompt ("Рік народження?") // let yearNow = 2021; // let ageRetirement = 60; // let one = " вийде на пенсію через "; // let result = ((dateBirth + ageRetirement) - yearNow); // let two = " років."; // let three = " вже пенсіонер."; // if ( result < 60 && result > 0) { // alert(userName + one + result + two); // } else if ( result <= 0 ) { // alert(userName + three); // } let userName = prompt ("Ім'я?"); let dateBirth = +prompt ("Рік народження?"); let yearNow = 2021; let ageRetirement = 60; let years = "років"; function calcAge () { let age = yearNow - dateBirth; return age } console.log(calcAge()); function yearsUntilRetirement (yes, no) { let yearsUntil = ageRetirement - calcAge(); return yearsUntil console.log ( '${userName} залишилося ${yearsUntil} ${years} до пенсії ' ); } console.log(yearsUntilRetirement());
3207ffae40582cc746a9d01e9fc534a05ac9f1b3
[ "JavaScript" ]
1
JavaScript
LKob/lesson-15-ageRetierment
cece274f1bdb92c3d30040e93b796bdea771e74e
8e9268705620cfe9982b89d22b7ebbe2e52c50bf
refs/heads/master
<repo_name>yurish4e/wmt-base-PHP-MySQL<file_sep>/scripts/form.php <?php require 'connect.php'; $short_problem = $_REQUEST['short_problem']; $full_problem = $_REQUEST['full_problem']; $info = $_REQUEST['info']; $notice = $_REQUEST['notice']; $insert_sql = "INSERT INTO general_problems (short_problem, full_problem, info, notice)" . "VALUES('{$short_problem}', '{$full_problem}', '{$info}', '{$notice}');"; mysql_query($insert_sql); exit('<meta http-equiv="refresh" content="0; url=../index.php" />'); ?><file_sep>/index.php <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; "> <meta charset="utf-8"> <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/> <link rel="stylesheet" href="css/bootstrap.css" type="text/css"> <link rel="stylesheet" href="css/style.css" type="text/css"> <link rel="stylesheet" href="style.css" type="text/css"> <script src="jquery-1.11.2.min.js"></script> <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script> <title>Problems</title> </head> <body> <script type="text/javascript"> $(document).ready(function(){ $("p").click(function () { $(this).siblings("article").slideToggle("fast"); }); }); </script> <script type="text/javascript"> $(document).ready(function() { $('article').draggable(); }); </script> <script type="text/javascript"> $( init ); function init() { $('#redaction').draggable(); } </script> <ul class="nav nav-tabs"> <li role="presentation" class="active"><a href="index.php">Home</a></li> <li role="presentation"><a href="info_form.html">Add answer</a></li> </ul> <div class="row-fluid"> <div class="col-md-8 problem-block"> <h1>General questions</h1> <?php require 'scripts/connect.php'; ?> <?php $query="SELECT * FROM `general_problems`" ; $res=mysql_query($query); while($query=mysql_fetch_array($res))// выводим данные из БД { echo "<div>"; echo "<p>".$query[ 'short_problem']. "</p>"; echo "<article>".$query[ 'full_problem']. "</article>"; echo "<article>".$query[ 'info']. "</article>"; echo "<article class=\"notice\">".$query[ 'notice']. "</article>"; echo "</div>"; } mysql_free_result($res); // очищаем ?> </div> <div class="col-md-4"> <textarea id="" cols="80" rows="10"></textarea> </div> </div> </body> </html>
42513e3f09df0dc1c20f14717e8779c757832ae7
[ "PHP" ]
2
PHP
yurish4e/wmt-base-PHP-MySQL
ebeb0e19d1b686441d8d4e22824cb57a9f512e91
fe0c8ea8627ce1f9a9ffb90433e0159e47e2c8f6
refs/heads/master
<file_sep>require 'rest-client' require 'YAML' When(/^The client requests GET "([^"]*)"$/) do |resource| response = send_request(BASE_PATH_USERS_SERVICE+'?apikey='+TEST_APIKEY, {}) @response = response @status = response.code end Then(/^The response should be a (\d+) OK$/) do |status_code| expect(status_code.to_i).to eql(@status) end Then(/^I get the first user id$/) do @users = JSON.parse @response @userid = @users['data'][0]['id'] end When(/^The client requests GET details of a userid$/) do userid_response = send_request(BASE_PATH_USERS_SERVICE+'/'+@userid+'?apikey='+TEST_APIKEY, {}) @userid_response = userid_response end And(/^The user response has below attributes$/) do |table| user_response_parsed = JSON.parse @userid_response data_array = table.raw.map {|row| row.first} attributes = user_response_parsed['data']['attributes'] attributes.each do |key| expect(data_array.index(key[0]) > -1).to eql(true) end end def send_request(url, headers) response = RestClient.get(url, headers={}) return response end<file_sep>source "http://www.rubygems.org" gem 'rest-client' gem 'expect' gem 'json'<file_sep>require 'yaml' path = './config.yml' CONFIG = YAML::load(File.open(path)) TEST_APIKEY = CONFIG['test_apikey'] BASE_PATH_USERS_SERVICE = CONFIG['base_path_users_service']
d2582e2a00fc65b1cc4af257f71d061b3251f946
[ "Ruby" ]
3
Ruby
Amuktha/v2-api-functional-tests
b4383bcbebf5f9e59893d01488cdaeef69447abc
4e483aad0611bd00012474af7096d0c4fa217aac
refs/heads/master
<repo_name>jblin2042/blackjack<file_sep>/dealer.cpp /* * dealer.cpp * * Created on: 2019年9月16日 * Author: jb */ #include <iostream> #include <vector> #include <utility> using namespace std ; #include "player.hpp" #include "banker.hpp" #include "card.hpp" #include "dealer.hpp" #define BLACKJACK_MAX 21 Blackjack::Blackjack ( ) { _card = new Card ( 1 ) ; _card->shuffleCards ( ) ; } Blackjack::~Blackjack ( ) { delete _card ; } int Blackjack::initDealCard ( Player * & player , Banker * & banker ) { cout << "玩家第一張牌:" ; pair < int , string > card = this->dealCard ( true ) ; player->addCards ( card ) ; cout << "莊家第一張牌:" ; card = this->dealCard ( true ) ; banker->addCards ( card ) ; cout << "玩家第二張牌:" ; card = this->dealCard ( true ) ; player->addCards ( card ) ; cout << "莊家第二張牌:" ; card = this->dealCard ( false ) ; banker->addCards ( card ) ; return 0 ; } pair < int , string > Blackjack::dealCard ( bool show ) { pair < int , string > card = _card->dealCard ( ) ; if ( show ) { cout << card.first ; cout << " " << card.second << endl ; } else cout << "-" << endl ; return card ; } bool Blackjack::isBusted ( vector < pair < int , string > > card_vec ) { if ( BLACKJACK_MAX < this->calculatePoints ( card_vec ) ) return true ; return false ; } bool Blackjack::isWin ( vector < pair < int , string > > card_vec ) { if ( BLACKJACK_MAX == this->calculatePoints ( card_vec ) ) return true ; return false ; } float Blackjack::calculatePoints ( vector < pair < int , string > > card_vec ) { int n = card_vec.size ( ) ; float points = 0 ; int ace_n = 0 ; for ( int i = 0 ; i < n ; ++ i ) { pair < int , string > one = card_vec [ i ] ; switch ( one.first ) { case 1 : ++ ace_n ; break ; case 11 : case 12 : case 13 : points += 10 ; break ; default : points += one.first ; break ; } } // 計算若是有 ace 則點數應該要如何分配才會最恰當 int ace_11_ct = 0 ; if ( ace_n ) { int less_points = BLACKJACK_MAX - static_cast < int > ( points ) ; for ( ace_11_ct = ace_n ; ace_11_ct > 0 ; -- ace_11_ct ) { if ( 11 * ace_11_ct + ( ace_n - ace_11_ct ) <= less_points ) break ; } } return static_cast < float > ( points + ( ace_11_ct * 11 ) + ( ace_n - ace_11_ct ) ) ; } void Blackjack::showEnd ( vector < pair < int , string > > card_vec ) { int sz = static_cast < int > ( card_vec.size ( ) ) ; cout << "Game<Blackjack>此次點數 : " << this->calculatePoints ( card_vec ) << endl ; for ( int i = 0 ; i < sz ; ++ i ) cout << card_vec [ i ].first << " , " << card_vec [ i ].second << endl ; return ; } #define TEN_POINT_5_MAX 10.5 TenPoint5::TenPoint5 ( ) { _card = new Card ( 1 ) ; _card->shuffleCards ( ) ; } TenPoint5::~TenPoint5 ( ) { delete _card ; } int TenPoint5::initDealCard ( Player * & player , Banker * & banker ) { cout << "玩家第一張牌:" ; pair < int , string > card = this->dealCard ( true ) ; player->addCards ( card ) ; cout << "莊家第一張牌:" ; card = this->dealCard ( false ) ; banker->addCards ( card ) ; return 0 ; } pair < int , string > TenPoint5::dealCard ( bool show ) { pair < int , string > card = _card->dealCard ( ) ; if ( show ) { cout << card.first ; cout << " " << card.second << endl ; } else cout << "-" << endl ; return card ; } bool TenPoint5::isBusted ( vector < pair < int , string > > card_vec ) { if ( TEN_POINT_5_MAX < this->calculatePoints ( card_vec ) ) return true ; return false ; } bool TenPoint5::isWin ( vector < pair < int , string > > card_vec ) { if ( TEN_POINT_5_MAX == this->calculatePoints ( card_vec ) ) return true ; return false ; } float TenPoint5::calculatePoints ( vector < pair < int , string > > card_vec ) { int n = card_vec.size ( ) ; float points = 0 ; for ( int i = 0 ; i < n ; ++ i ) { pair < int , string > one = card_vec [ i ] ; switch ( one.first ) { case 11 : case 12 : case 13 : points += 0.5 ; break ; default : points += one.first ; break ; } } return points ; } void TenPoint5::showEnd ( vector < pair < int , string > > card_vec ) { int sz = static_cast < int > ( card_vec.size ( ) ) ; cout << "Game<TenPoint5>此次點數 : " << this->calculatePoints ( card_vec ) << endl ; for ( int i = 0 ; i < sz ; ++ i ) cout << card_vec [ i ].first << " , " << card_vec [ i ].second << endl ; return ; } <file_sep>/dealer.hpp /* * dealer.hpp * * Created on: 2019年9月16日 * Author: jb */ #ifndef DEALER_HPP_ #define DEALER_HPP_ #include <iostream> #include <vector> #include <utility> using namespace std ; #include "player.hpp" #include "banker.hpp" #include "card.hpp" #define interface struct #define implements public #define extends public #define abstract interface Dealer { virtual ~Dealer ( ) { } virtual int initDealCard ( Player * &player , Banker * &banker ) = 0 ; virtual pair < int , string > dealCard ( bool show ) = 0 ; virtual bool isBusted ( vector < pair < int , string > > card_vec ) = 0 ; virtual bool isWin ( vector < pair < int , string > > card_vec ) = 0 ; virtual float calculatePoints ( vector < pair < int , string > > card_vec ) = 0 ; virtual void showEnd ( vector < pair < int , string > > card_vec ) = 0 ; } ; class Blackjack : implements Dealer { Card * _card ; public: Blackjack ( ) ; ~Blackjack ( ) ; int initDealCard ( Player * &player , Banker * &banker ) ; pair < int , string > dealCard ( bool show ) ; bool isBusted ( vector < pair < int , string > > card_vec ) ; bool isWin ( vector < pair < int , string > > card_vec ) ; float calculatePoints ( vector < pair < int , string > > card_vec ) ; void showEnd ( vector < pair < int , string > > card_vec ) ; } ; class TenPoint5 : implements Dealer { Card * _card ; public: TenPoint5 ( ) ; ~TenPoint5 ( ) ; int initDealCard ( Player * &player , Banker * &banker ) ; pair < int , string > dealCard ( bool show ) ; bool isBusted ( vector < pair < int , string > > card_vec ) ; bool isWin ( vector < pair < int , string > > card_vec ) ; float calculatePoints ( vector < pair < int , string > > card_vec ) ; void showEnd ( vector < pair < int , string > > card_vec ) ; } ; #endif /* DEALER_HPP_ */ <file_sep>/player.hpp /* * player.hpp * * Created on: 2019年9月16日 * Author: jb */ #ifndef PLAYER_HPP_ #define PLAYER_HPP_ #include <vector> #include <iostream> #include <utility> using namespace std ; class Player { vector < pair < int , string > > _owned_card ; public: void addCards ( pair < int , string > card ) ; const vector < pair < int , string > > & getAllCard ( void ) ; bool askDealCard ( void ) ; void clearOwnedCard ( void ) ; void showAllCard ( void ) ; } ; #endif /* PLAYER_HPP_ */ <file_sep>/player.cpp /* * player.cpp * * Created on: 2019年9月16日 * Author: jb */ #include <vector> #include <iostream> #include <utility> using namespace std ; #include "player.hpp" void Player::showAllCard ( void ) { for ( int i = 0 ; i < static_cast < int > ( _owned_card.size ( ) ) ; ++ i ) { cout << "" << _owned_card [ i ].first ; cout << " " << _owned_card [ i ].second << " , " ; } cout << endl ; return ; } void Player::addCards ( pair < int , string > card ) { _owned_card.push_back ( card ) ; return ; } const vector < pair < int , string > > & Player::getAllCard ( void ) { return _owned_card ; } bool Player::askDealCard ( void ) { string ask_str ( "" ) ; cout << "是否繼續<y>:" ; cin >> ask_str ; if ( ask_str == "y" ) return true ; return false ; } void Player::clearOwnedCard ( void ) { _owned_card.clear ( ) ; return ; } <file_sep>/main.cpp /* * main.cpp * * Created on: 2019年9月16日 * Author: jb */ #include <iostream> using namespace std ; extern "C" { #include <unistd.h> } #include "dealer.hpp" #include "player.hpp" #include "banker.hpp" int main ( void ) { Dealer * dealer = NULL ; Player * player = new Player ( ) ; Banker * banker = NULL ; cout << "選擇遊戲 <1:Blackjack> , <other:10點半>:" ; string s ( "" ) ; cin >> s ; if ( s == "1" ) { cout << "選擇遊戲:Blackjack" << endl ; dealer = new Blackjack ( ) ; banker = new Banker ( true ) ; } else { cout << "選擇遊戲:10點半" << endl ; dealer = new TenPoint5 ( ) ; banker = new Banker ( false ) ; } string dummy_str ( "" ) ; while ( true ) { cout << endl << "玩家遊戲開始<1:繼續> , <other:結束>:" ; cin >> dummy_str ; if ( dummy_str != "1" ) { cout << "遊戲結束" << endl ; break ; } player->clearOwnedCard ( ) ; banker->clearOwnedCard ( ) ; bool banker_busted = false ; bool player_busted = false ; dealer->initDealCard ( player , banker ) ; // 玩家 while ( true ) { // 是否滿足此次最大值 player->showAllCard ( ) ; if ( dealer->isWin ( player->getAllCard ( ) ) ) { cout << "Max" << endl ; sleep ( 2 ) ; break ; } // 詢問玩家是否需要牌 // if ( player->askDealCard ( ) ) player->addCards ( dealer->dealCard ( true ) ) ; else break ; // 確認是否爆炸 // player_busted = dealer->isBusted ( player->getAllCard ( ) ) ; if ( player_busted ) { cout << "玩家爆點" << endl ; sleep ( 2 ) ; break ; } } cout << "玩家:" << endl ; dealer->showEnd ( player->getAllCard ( ) ) ; cout << endl ; // 玩家爆炸 ,遊戲直接重來 if ( player_busted ) { cout << "莊家:" << endl ; dealer->showEnd ( banker->getAllCard ( ) ) ; cout << endl ; cout << "***** 莊家贏 *****" << endl ; continue ; } float player_points = dealer->calculatePoints ( player->getAllCard ( ) ) ; // 莊家 while ( true ) { cout << endl << "換莊家" << endl ; sleep ( 2 ) ; banker->showAllCard ( ) ; // 是否滿足此次最大值 if ( dealer->isWin ( banker->getAllCard ( ) ) ) { cout << "Max" << endl ; sleep ( 2 ) ; break ; } // 詢問玩家是否需要牌 // if ( banker->askDealCard ( player_points , dealer->calculatePoints ( banker->getAllCard ( ) ) ) ) banker->addCards ( dealer->dealCard ( true ) ) ; else break ; // 確認是否爆炸 // banker_busted = dealer->isBusted ( banker->getAllCard ( ) ) ; if ( banker_busted ) { cout << "莊家爆點" << endl ; sleep ( 2 ) ; break ; } } cout << "莊家:" << endl ; dealer->showEnd ( banker->getAllCard ( ) ) ; cout << endl ; if ( banker_busted ) { cout << "***** 玩家贏 *****" << endl ; continue ; } float banker_points = dealer->calculatePoints ( banker->getAllCard ( ) ) ; if ( player_points == banker_points ) cout << "***** 平手 *****" << endl ; else if ( player_points > banker_points ) cout << "***** 玩家贏 *****" << endl ; else cout << "***** 莊家:贏 *****" << endl ; } delete dealer ; dealer = NULL ; delete player ; player = NULL ; delete banker ; banker = NULL ; return 0 ; } <file_sep>/banker.hpp /* * banker.hpp * * Created on: 2019年9月16日 * Author: jb */ #ifndef BANKER_HPP_ #define BANKER_HPP_ #include <vector> #include <iostream> #include <utility> using namespace std ; class Banker { bool _is_black_jack ; vector < pair < int , string > > _owned_card ; public: Banker ( bool is_black_jack ) ; void addCards ( pair < int , string > card ) ; const vector < pair < int , string > > & getAllCard ( void ) ; bool askDealCard ( float player_points , float self_points ) ; void showAllCard ( void ) ; void clearOwnedCard ( void ) ; } ; #endif /* BANKER_HPP_ */ <file_sep>/card.hpp /* * card.hpp * * Created on: 2019年9月4日 * Author: jb */ #ifndef CARD_HPP_ #define CARD_HPP_ #include <iostream> #include <vector> #include <utility> using namespace std ; class Card { vector < pair < int , string > > _card_vec ; int _deal_num ; // 目前發牌的數量 int _card_num ; // 撲克牌的組數 int _cards_max ; // 撲克牌的上限數量 void showAll ( void ) ; void showDeal ( void ) ; void showNondeal ( void ) ; public: /**產生牌組數量 * * @param poker_num : 撲克牌組數 */ Card ( int card_num ) ; void shuffleCards ( void ) ; pair < int , string > dealCard ( void ) ; } ; #endif /* CARD_HPP_ */ <file_sep>/makefile CXX=g++ OBJ:=banker.o card.o dealer.o main.o player.o FLAG:=-Wall -O3 -s INC:= LIB:= EXE:=blackjack all: $(CXX) -c *.cpp $(CXX) $(OBJ) -o $(EXE) $(FLAG) rm -r $(OBJ) clean: rm -r $(OBJ) rm -r $(EXE) <file_sep>/card.cpp /* * poker.cpp * * Created on: 2019年9月4日 * Author: jb */ #include <iostream> #include <vector> #include <utility> #include "card.hpp" extern "C" { #include <stdlib.h> #include <time.h> } using namespace std ; Card::Card ( int card_num ) { _card_vec.clear ( ) ; _deal_num = 0 ; _card_num = card_num ; string brand_color [ ] = { "黑桃" , "紅心" , "方塊" , "梅花" } ; for ( int n = 0 ; n < card_num ; ++ n ) for ( int i = 0 ; i < 4 ; ++ i ) for ( int j = 1 ; j < 14 ; ++ j ) _card_vec.push_back ( make_pair ( j , brand_color [ i ] ) ) ; _cards_max = _card_vec.size ( ) ; } void Card::shuffleCards ( void ) { srand ( clock ( ) ) ; int porker_num = static_cast < int > ( _card_vec.size ( ) ) ; int shuffle_times = ( rand ( ) % 50000 ) + 100 ; int s = 0 ; int t = 0 ; for ( int i = 0 ; i < shuffle_times ; ++ i ) { s = rand ( ) % porker_num ; t = rand ( ) % porker_num ; pair < int , string > data = _card_vec [ s ] ; _card_vec [ s ] = _card_vec [ t ] ; _card_vec [ t ] = data ; } return ; } void Card::showAll ( void ) { for ( int i = 0 ; i < static_cast < int > ( _card_vec.size ( ) ) ; ++ i ) { cout << _card_vec [ i ].first ; cout << " " << _card_vec [ i ].second << endl ; } return ; } void Card::showDeal ( void ) { for ( int i = 0 ; i < _deal_num ; ++ i ) { cout << _card_vec [ i ].first ; cout << " " << _card_vec [ i ].second << endl ; } return ; } void Card::showNondeal ( void ) { for ( int i = _deal_num ; i < static_cast < int > ( _card_vec.size ( ) ) ; ++ i ) { cout << _card_vec [ i ].first ; cout << " " << _card_vec [ i ].second << endl ; } return ; } pair < int , string > Card::dealCard ( void ) { return _cards_max <= _deal_num ? make_pair ( 0 , "-" ) : _card_vec [ _deal_num ++ ] ; } //Poker::Poker ( bool ghost_card ) //{ // string brand_color [ ] = { "黑桃" , "紅心" , "方塊" , "梅花" } ; // for ( int i = 0 ; i < 4 ; ++ i ) // for ( int j = 1 ; j < 14 ; ++ j ) // _p.push_back ( make_pair ( j , brand_color [ i ] ) ) ; // // if ( ghost_card ) // { // _p.push_back ( make_pair ( 1 , "Joker" ) ) ; // _p.push_back ( make_pair ( 2 , "Joker" ) ) ; // } //} //void Poker::shuffleCards ( void ) //{ // srand ( clock ( ) ) ; // int porker_num = static_cast < int > ( _p.size ( ) ); // int shuffle_times = ( rand ( ) % 50000 ) + 100 ; // int s = 0 ; // int t = 0 ; // // for ( int i = 0 ; i < shuffle_times ; ++ i ) // { // s = rand ( ) % porker_num ; // t = rand ( ) % porker_num ; // // pair < int , string > data = _p [ s ] ; // _p [ s ] = _p [ t ] ; // _p [ t ] = data ; // } // return ; //} //void Poker::show ( void ) //{ // for ( int i = 0 ; i < static_cast < int > ( _p.size ( ) ) ; ++ i ) // { // cout << "" << _p [ i ].first ; // cout << " " << _p [ i ].second << endl ; // } // return ; //} int main_card_test ( void ) { Card p ( 5 ) ; // p.showAll ( ) ; p.shuffleCards ( ) ; cout << endl << endl ; // cout << "ssssssssssssss" << endl ; // while ( 1 ) // { // pair < int , string > pp = p.dealCard ( ) ; // if ( ! pp.first ) break ; // cout << pp.first << " , " << pp.second << endl ; // } pair < int , string > tmp = p.dealCard ( ) ; cout << endl ; cout << "1:" << tmp.first << endl ; cout << "2:" << tmp.second << endl ; cout << endl ; return 0 ; }
e0a5dca6d31bcfc6221f76acb10047a9f025e25c
[ "Makefile", "C++" ]
9
C++
jblin2042/blackjack
312ab8eb6be78d531a2af9645a7cb183955c8495
adeb2f4133453d617d602e2f15a5289b1e85202e
refs/heads/main
<repo_name>LucasFeli/Motocycle-Fans<file_sep>/controllers/auth.controllers.js const User = require("../models/User.model"); const bcrypt = require("bcryptjs"); const { hasCorrectPasswordFormat, isMongoError, isMongooseErrorValidation, } = require("../utils/validators.utils"); exports.signup = async (req, res) => { try { const { password, username, email } = req.body; const hasMissingCredentials = !password || !email || !username; if (hasMissingCredentials) { return res.status(400).json({ message: "missing credentials" }); } if (!hasCorrectPasswordFormat(password)) { return res.status(400).json({ message: "incorrect password format" }); } const user = await User.findOne({ email }); if (user) { return res.status(400).json({ message: "email alredy exists" }); } const name = await User.findOne({ username }); if (name) { return res.status(400).json({ message: "username alredy exists" }); } const saltRounds = 10; const salt = await bcrypt.genSalt(saltRounds); const hashedPassword = await bcrypt.hash(password, salt); const newUser = await User.create({ username, email, hashedPassword }); req.session.userId = newUser._id; return res.status(200).json({ user: newUser.email, id: newUser._id, username: newUser.username}); } catch (e) { if (isMongooseErrorValidation(e)) { return res.status(400).json({ message: "incorrect email format" }); } if (isMongoError(e)) { return res.status(400).json({ message: "duplicate field" }); } return res.status(400).json({ message: "wrong request" }); } }; exports.login = async (req, res) => { try { const { password, email } = req.body; const hasMissingCredentials = !password || !email; if (hasMissingCredentials) { return res.status(400).json({ message: "missing credentials" }); } if (!hasCorrectPasswordFormat(password)) { return res.status(400).json({ message: "incorrect password format" }); } const user = await User.findOne({ email }); if (!user) { return res.status(400).json({ message: "user does not exist" }); } const hasCorrectPassword = await bcrypt.compare( password, user.hashedPassword ); if (!hasCorrectPassword) { return res.status(401).json({ message: "unauthorize" }); } req.session.userId = user._id; return res.status(200).json({ user: user.email, id: user._id }); } catch (e) { if (isMongooseErrorValidation(e)) { return res.status(400).json({ message: "incorrect email format" }); } return res.status(400).json({ message: "wrong request" }); } }; exports.logout = async (req, res) => { await req.session.destroy(); res.status(200).json({ message: "logout" }); }; exports.getUser = async (req, res) => { const { userId } = req.session; const { username,email, _id,myMotocycles } = await User.findById(userId) .populate("myMotocycles").lean(); res.status(200).json({ id: _id, email, username,myMotocycles }); }; <file_sep>/routes/motocycle.route.js const { Router } = require("express"); const route = Router(); const fileParser = require("../config/cloudinary.config"); const { getMotocycles, getMotocycle, createMotocycle, updateMotocycle, deleteMotocycle, } = require("../controllers/motocycle.controlers"); route .get("/", getMotocycles) .get("/:motocycleId", getMotocycle) .post("/create", createMotocycle) .post("/upload", fileParser.single("image"), (req, res, next) => { console.log("req.file", req.file) if (!req.file) { next(new Error("No file uploaded")); return; } res.json(req.file.path); }) .put("/:motocycleId", updateMotocycle) .delete("/:motocycleId", deleteMotocycle); module.exports = route; <file_sep>/seed/data.js module.exports = [ { marca: "Yamaha TMAX 560", modelo : 2020, motor: "Dos cilindros en paralelo inclinados hacia delante, refrigerado por líquido, 4 tiempos, DOHC, 4 válvulas ", image: "https://i.blogs.es/87c510/yamaha-tmax-560-2020--2/1366_2000.jpg", description: "Este 2020 la firma de los diapasones no se ha andado con medias tintas y presenta al Yamaha TMAX 560, el TMAX más potente de la historia, además de una estética más agresiva a juego con un comportamiento dinámico aún más afilado.", }, { marca: "Suzuki A 50 P/D", modelo : 1979, motor: "Dos tiempos, válvula de piston, monocilindrico ", image:"https://s1.cdn.autoevolution.com/images/moto_gallery/SUZUKI-A50-14461_1.jpg", description: "La nueva Suzuki era una máquina profesional para mirar con una gran postura y actitud de moto. La usabilidad también fue una delicia con un sistema de autolubricación mucho antes de su tiempo, la bomba fue impulsada por el engranaje inactivo de arranque que a su vez tomó su impulso desde el eje de salida de la caja de engranajes, esto resultó en el eje de arranque no funciona cuando se aprieta el embrague, pero es un pequeño precio a pagar por la facilidad que se encuentra en el momento del llenado. ", }, { marca: "KTM 300 EXC TPI ERZBERGRODEO ", modelo : 2021, motor: "Dos tiempos, 300cc ", image:"https://www.ktm.com/ktmgroup-storage/PHO_BIKE_90_RE_300-EXC-TPI-Erzberg-MY21-90-Right_%23SALL_%23AEPI_%23V1.png", description: "La KTM 300 EXC ha estado a la vanguardia del loco ritmo de desarrollo que es el Enduro Extremo. Este ágil y ligera moto offroad no teme a ningún obstáculo y se convierte en la máquina definitiva para conquistar la legendaria Iron Giant. La edición limitada especial ERZBERGRODEO está cargada de piezas KTM PowerParts y luce un exclusivo kit de gráficos para conmemorar este evento tan especial. ", }, { marca: "Suzuki GSX-R600 ", modelo : 2018, motor: "Motor de 599 cc y 4 cilindros con inyección de combustible que proporciona una gran potencia desde el ralentí hasta la línea roja", image:"https://www.totalmotorcycle.com/wp-content/uploads/2017/11/2018-Suzuki-GSX-R600b-1024x682.jpg ", description: "La Suzuki GSX-R 600 2018 es una motocicleta deportiva líder en su clase, digna de su herencia GSX-R ganadora de carreras. Ya sea que este curveando por tu zona favorita o dominando la pista de carreras, ofrece un rendimiento sin igual. ",}, ];
dcd73071cc34eba91967ab7e5b7201ccc979ca6b
[ "JavaScript" ]
3
JavaScript
LucasFeli/Motocycle-Fans
6e2751774b1faf1ebe3473d3f638e35b4e21a42d
9b1aa5407a5a4823006b50c87c9cba44e84ba7d7
refs/heads/main
<file_sep>package main import ( "net/http" "net/http/httptest" "testing" "time" ) func TestRacer(t *testing.T) { t.Run("get response", func(t *testing.T) { fastOne := mockHTTPTest(8 * time.Millisecond) slowOne := mockHTTPTest(12 * time.Millisecond) defer fastOne.Close() defer slowOne.Close() _, err := Racer(fastOne.URL, slowOne.URL) assertTimeout(t, err, nil) }) t.Run("get timeout", func(t *testing.T) { runTime := mockHTTPTest(5 * time.Second) defer runTime.Close() _, err := racer(runTime.URL, runTime.URL, 3*time.Second) if err == nil { t.Errorf("we don't have an error, but we want it") } }) } func mockHTTPTest(delay time.Duration) *httptest.Server { mockURL := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { time.Sleep(delay) w.WriteHeader(http.StatusOK) })) return mockURL } func assertTimeout(t *testing.T, got, want error) { if got != nil { t.Fatalf("get error %s but we don't want it", got) } if got != want { t.Errorf("something wrong here, looks timeout") } } func BenchmarkMockA(b *testing.B) { fastOne := mockHTTPTest(8 * time.Millisecond) defer fastOne.Close() Racer(fastOne.URL, fastOne.URL) } func BenchmarkMockB(b *testing.B) { fastOne := mockHTTPTest(8 * time.Millisecond) defer fastOne.Close() racer(fastOne.URL, fastOne.URL, delayTimeout) } <file_sep>package main import ( "reflect" ) func walk(v interface{}, fn func(input string)) { val := getValue(v) walkValue := func(value reflect.Value) { walk(value.Interface(), fn) } switch val.Kind() { case reflect.String: fn(val.String()) case reflect.Struct: // struct have method NumField() and Field() for i := 0; i < val.NumField(); i++ { walkValue(val.Field(i)) } case reflect.Array, reflect.Slice: // slice and array have method Len() and Index() for i := 0; i < val.Len(); i++ { walkValue(val.Index(i)) } case reflect.Map: // map have method MapKeys() and MapIndex() for _, key := range val.MapKeys() { walkValue(val.MapIndex(key)) } } } func getValue(v interface{}) reflect.Value { val := reflect.ValueOf(v) // if val.Kind() is pointer, we need get the underlying value of val if val.Kind() == reflect.Ptr { val = val.Elem() } return val } <file_sep># Learning Go with TDD In this repo, you will see some examples of Go basic syntax, and each directory contains the corresponding topic test file and source code, related topics come from repo [here](https://github.com/quii/learn-go-with-tests). And I expanded it properly and rewrited some code with fully tested. Whatever you learn it for work or something else, it's really worth it, let's Go. ## Content - hello - integer - iteration - array - slice - smi: struct/method/interface - pe: pointer/error - maps: map - di: dependency injection - mock: mocking - concurrency - select - reflect // a little hard - sync - context // a little hard - rnr: A test based on property // a little hard - math ## YSK > YSK: You Should Know. - platform: go1.15.2 darwin/amd64 - run common test: `go test -v` - run benchmark test: `go test -bench=.` - use `go test -cover` to get the test cover ratio - test file named as xxx_test.go - test function named as TestXxx and it only recive one arugment - don't expect to write perfect code at once, please iterate slowly - write the simple test and test it first, then write the main code and refactor them, REPL - example function cannot excute if you forget the comment `// Output: result` - write the good comment for all you functions please, especially exported ones - use table driven tests to make test file easier to expand and maintain - use `[]struct{}{}` to make your code hierarchical and maintain better - when a function or method was invocated, parameters will be copied. So, always use `*Struct` be a reciver - type alias can be useful, also you can declare methods on them: `type Transaction uintptr` - import `errors`, cause of error checking always useful, and read [this one](https://dave.cheney.net/2016/04/27/dont-just-check-errors-handle-them-gracefully) - use `_, ok` to check if operation is ok, ok is a bool value - never initialize an empty map variable like `var m map[int]string`, cause of nil pointer exception. You should do this: `m = make(map[int]string)` or `m = map[int]string{}` - if you want to put the data somewhere, please use `io.Writer`, it is a good general interface, better than `bytes.Buffer` - DI makes separation of concerns: decoupling where the data arrives and how it is generated, and reuse the code in the different situation - try to get your code to be tested as soon as possible - when we want to start a goroutine, we often use anonymous functions, just like this: `go func() {}()` - to enable race detector, run the test with the race flag: `go test -race` - use channel to pass the data in goroutine, `ch <- data` is send data and `data := <-ch` is receive data - use `net/http/httptest` to create a mock http server - use `select` to implement process synchronization - use `time.After()` to prevent your system from being permanently blocked - don't use reflection unless you really need it - nobody likes anonymous nested stuct in the complicated code, so please be nice - pointer type value cannot use the NumField method in reflect, you need to call Elem() to extract the underlying value before executing this method - slice have no method NumField in reflect, we should use method Len and Index - use `sync.WaitGroup` to synchronize concurrent processes - use `sync.Mutex` to solve data race issue, and the zero value for a Mutex is an unlocked mutex - a Mutex must not be copied after first use - `Use a sync.Mutex or a channel?` see [here](https://github.com/golang/go/wiki/MutexOrChannel) - use channels when passing ownership of data - use mutexes for managing state - in my ex-company, they use both Mutex and channel, and they use channel to customize a new Mutex - use `go vet` to check your code always - don't use type embedding, you'll ignore the impact it brings, and that's hard to track bug down - use `context` to manage long-running processes - don't use `context.Value` or you got fired, here's [why](https://faiface.github.io/post/context-should-go-away-go2/) - use `strings.Builder` to build a string with less memory copy - use `testing/quick` to test the code with random numbers quickly ## TODO - error checking - refactor ## Credit Thanks to [@quii](https://github.com/quii) for his contribution. And also I found a good Go tutorial to make you learn Go better, please visit [here](https://golangbot.com/learn-golang-series/) to check it out. ## License MIT. <file_sep>package slice import ( "fmt" "reflect" "testing" ) func TestSum(t *testing.T) { check := func(t *testing.T, got, want int) { if got != want { t.Errorf("got '%q' want '%d'", got, want) } } t.Run("", func(t *testing.T) { nums := []int{1, 2, 3, 4, 5} got := Sum(nums) want := 15 check(t, got, want) }) t.Run("", func(t *testing.T) { nums := []int{1, 2, 3} got := Sum(nums) want := 6 check(t, got, want) }) } func TestSumAll(t *testing.T) { check := func(t *testing.T, got, want int) { if got != want { t.Errorf("got '%d' want '%d'", got, want) } } t.Run("", func(t *testing.T) { num1 := []int{1, 2, 3, 4, 5, 6} num2 := []int{0, 8, 3} got := SumAll(num1, num2) want := 32 check(t, got, want) }) t.Run("", func(t *testing.T) { num1 := []int{6} num2 := []int{0, 3} got := SumAll(num1, num2) want := 9 check(t, got, want) }) } func TestSumToNew(t *testing.T) { check := func(t *testing.T, got, want []int) { if !reflect.DeepEqual(got, want) { t.Errorf("got '%q' want '%q'", got, want) } } t.Run("", func(t *testing.T) { got := SumToNew([]int{1, 2, 3}, []int{0, 1}) want := []int{6, 1} check(t, got, want) }) t.Run("", func(t *testing.T) { got := SumToNew([]int{3}, []int{}) want := []int{3, 0} check(t, got, want) }) } func ExampleSum() { nums := []int{1, 2, 3, 4} ret := Sum(nums) fmt.Println(ret) // Output: 10 } func ExampleSumAll() { num1 := []int{2, 3} num2 := []int{1, 2, 3, 4} ret := SumAll(num1, num2) fmt.Println(ret) // Output: 15 } func ExampleSumToNew() { num1 := []int{} num2 := []int{3, 3} newslice := SumToNew(num1, num2) fmt.Println(newslice) // Output: [0 6] } <file_sep>package main import ( "sync" ) // Counter defines a counter type Counter struct { mu sync.Mutex value int } // NewCounter news a pointer type Counter // Don't initilize it directly in your code func NewCounter() *Counter { return &Counter{} } // Incr increases value func (c *Counter) Incr() { c.mu.Lock() defer c.mu.Unlock() c.value++ } // Value returns the value func (c *Counter) Value() int { return c.value } <file_sep>package main import ( "context" "errors" "net/http" "testing" "time" ) // SpyStore defines a spy Store type SpyStore struct { response string t *testing.T } // SpyResonseWriter defines new ResponseWriter type SpyResponseWriter struct { written bool } // rewrite Header() func (w *SpyResponseWriter) Header() http.Header { w.written = true return nil } // rewrite Write() func (w *SpyResponseWriter) Write([]byte) (int, error) { w.written = true return 0, errors.New("not implemented") } // rewrite WriteHeader() func (w *SpyResponseWriter) WriteHeader(code int) { w.written = true } // Fetch fetchs the data from SpyStore func (s *SpyStore) Fetch(ctx context.Context) (string, error) { data := make(chan string, 1) go func() { var ret string for _, resp := range s.response { select { case <-ctx.Done(): s.t.Log("store cancelled") return default: time.Sleep(10 * time.Millisecond) ret += string(resp) } } data <- ret }() select { case <-ctx.Done(): return "", ctx.Err() case res := <-data: return res, nil } } <file_sep>package smi import ( "fmt" //"math" "testing" ) func TestPerimeter(t *testing.T) { assertTest := []struct { name string shape Shaper want float64 }{ //{"R", Rectangle{Shape{1.0, 20.0}}, 42.0}, //{"C", Circle{2.0}, 12.566370614359172}, {name: "Rectangle", shape: Rectangle{Shape{length: 1.0, width: 20.0}}, want: 42.0}, {name: "Circle", shape: Circle{radius: 2.0}, want: 12.566370614359172}, } for _, tt := range assertTest { t.Run(tt.name, func(t *testing.T) { got := tt.shape.Perimeter() if got != tt.want { t.Errorf("got '%f' want '%f'", got, tt.want) } }) } } /* func TestPerimeter(t *testing.T) { check := func(t *testing.T, shape Shaper, want float64) { t.Helper() got := shape.Perimeter() if got != want { t.Errorf("got '%.2f' want '%.2f'", got, want) } } t.Run("Rectangle", func(t *testing.T) { r := Rectangle{Shape{1.0, 20.0}} //got := r.Perimeter() want := 42.0 check(t, r, want) }) t.Run("Circle", func(t *testing.T) { c := Circle{2.0} //got := c.Perimeter() want := 12.566370614359172 check(t, c, want) }) } */ func ExamplePerimeter() { //r := Rectangle{Shape{1.0, 20.0}} //ret := r.Perimeter() //fmt.Println(ret) //// Output: 42 c := Circle{2.0} ret := c.Perimeter() fmt.Println(ret) // Output: 12.566370614359172 } func TestArea(t *testing.T) { assertTest := []struct { name string shape Shaper want float64 }{ //{"R", Rectangle{Shape{1.0, 20.0}}, 20.0}, //{"C", Circle{2.0}, 12.566370614359172}, //{"T", Triangle{2.0, 1.0}, 1.0}, {name: "Rectangle", shape: Rectangle{Shape{length: 1.0, width: 20.0}}, want: 20.0}, {name: "Circle", shape: Circle{radius: 2.0}, want: 12.566370614359172}, {name: "Triangle", shape: Triangle{length: 2.0, height: 1.0}, want: 1.0}, } for _, tt := range assertTest { t.Run(tt.name, func(t *testing.T) { got := tt.shape.Area() if got != tt.want { t.Errorf("got '%f' want '%f'", got, tt.want) } }) } } /* func TestArea(t *testing.T) { check := func(t *testing.T, shape Shaper, want float64) { t.Helper() got := shape.Area() if got != want { t.Errorf("got '%.2f' want '%.2f'", got, want) } } t.Run("Rectangle", func(t *testing.T) { r := Rectangle{Shape{1.0, 20.0}} //got := r.Area() want := 20.0 check(t, r, want) }) t.Run("Circle", func(t *testing.T) { c := Circle{2.0} //got := c.Area() want := 4.0 * math.Pi check(t, c, want) }) } */ func ExampleArea() { //r := Rectangle{Shape{1.0, 20.0}} //ret := r.Area() //fmt.Println(ret) //// Output: 20 c := Circle{2.0} ret := c.Area() fmt.Println(ret) // Output: 12.566370614359172 } <file_sep>package main import ( "context" "fmt" _ "log" "net/http" ) // Store fetchs the data type Store interface { Fetch(ctx context.Context) (string, error) } // Server returns a handler func Server(store Store) http.HandlerFunc { return func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() data, err := store.Fetch(ctx) if err != nil { //log.Print("== met err ----> ", err) return } fmt.Fprint(w, data) } } <file_sep>package main import ( "context" "net/http" "net/http/httptest" "testing" "time" ) func TestServer(t *testing.T) { data := "hello context" t.Run("fetch data from store", func(t *testing.T) { store := &SpyStore{response: data, t: t} ser := Server(store) request := httptest.NewRequest(http.MethodGet, "/", nil) cancelCtx, cancel := context.WithCancel(request.Context()) time.AfterFunc(5*time.Millisecond, cancel) request = request.WithContext(cancelCtx) response := &SpyResponseWriter{} ser.ServeHTTP(response, request) if response.written { t.Error("response not allow to written") } }) t.Run("not allowed", func(t *testing.T) { store := &SpyStore{response: data, t: t} ser := Server(store) request := httptest.NewRequest(http.MethodGet, "/", nil) response := httptest.NewRecorder() ser.ServeHTTP(response, request) if response.Body.String() != data { t.Errorf("got %s want %s", response.Body.String(), data) } }) } <file_sep>package main import ( "sync" "testing" ) func TestCounter(t *testing.T) { c := NewCounter() want := 1000 var wg sync.WaitGroup wg.Add(want) t.Run("concurrent safely", func(t *testing.T) { t.Helper() for i := 0; i < want; i++ { go func(w *sync.WaitGroup) { c.Incr() wg.Done() }(&wg) } wg.Wait() assertCounter(t, c, want) }) } func assertCounter(t *testing.T, got *Counter, want int) { if got.Value() != want { t.Errorf("got %d but we want %d", got.Value(), want) } } <file_sep>package main import ( "testing" ) func TestHello(t *testing.T) { assertMsg := func(t *testing.T, got, want string) { t.Helper() if got != want { t.Errorf("got '%q' want '%q'", got, want) } } t.Run("Espanol", func(t *testing.T) { got := Hello("i0Ek3", "Espanol") want := "Hola, i0Ek3" assertMsg(t, got, want) }) t.Run("English", func(t *testing.T) { got := Hello("", "English") want := "Hello, i0Ek3" assertMsg(t, got, want) }) } <file_sep>package main import ( "errors" "net/http" "time" ) var ( Timeout = errors.New("timeout") delayTimeout = time.Duration(10 * time.Millisecond) ) //// a common version //// Racer picks fast url //func Racer(a, b string) string { // ea := mockHTTP(a) // eb := mockHTTP(b) // // if ea > eb { // return a // } // return b //} // //func mockHTTP(u string) time.Duration { // tu := time.Now() // http.Get(u) // ea := time.Since(tu) // return ea //} // a select version // Racer picks fast url func Racer(a, b string) (string, error) { return racer(a, b, delayTimeout) } func racer(a, b string, delay time.Duration) (string, error) { select { case <-mockHTTP(a): return a, nil case <-mockHTTP(b): return b, nil case <-time.After(delay): return "", Timeout } } func mockHTTP(u string) chan bool { ch := make(chan bool) go func() { http.Get(u) ch <- true }() return ch } <file_sep>package array import ( "fmt" "testing" ) func TestSum(t *testing.T) { num := [5]int{1, 2, 3, 4, 5} got := Sum2(num) want := 15 if got != want { t.Errorf("got '%q' want '%d' given arr '%v'", got, want, num) } } func ExampleSum() { num := [...]int{1, 2, 3, 4, 5} ret := Sum2(num) fmt.Println(ret) // Output: 15 } <file_sep>package main import ( "math" "testing" a "github.com/i0Ek3/asrt" ) func TestCal(t *testing.T) { t.Run("-0.5", func(t *testing.T) { number := -0.5 got := Cal(number) want := math.Cos(number) a.Asrt(t, got, want) }) t.Run("0.5", func(t *testing.T) { number := 0.5 got := Cal(number) want := math.Cos(number) a.Asrt(t, got, want) }) t.Run("0", func(t *testing.T) { number := 0.0 got := int(Cal(number)) want := 1 a.Asrt(t, got, want) }) } func BenchmarkCal(b *testing.B) { for i := 0; i < b.N; i++ { Cal(math.Pi) } } <file_sep>package iteration // Repeat repeats the str count times func Repeat(count int, str string) string { var ret string for i := 0; i < count; i++ { ret += str } return ret } <file_sep>package main import ( "reflect" "testing" ) type Person struct { Name string Profile Profile } type Profile struct { Age int City string } func TestWalk(t *testing.T) { cases := []struct { Name string Input interface{} ExpectedCalls []string }{ /* // DO NOT USE ANONYMOUS NESTED // STRUCT IN THE COMPLICATED CODE { "use pointer", &Person{ "i0Ek3" Profile{30, "Tokoy"} }, []string{"i0Ek3", "Tokoy"}, }, { "nested anonymous struct", Person{ "Satoshi", Profile{30, "Tokoy"}, }, []string{"Satoshi", "Tokoy"}, }, { "slices test", []Profile{ {33, "Paris"}, {32, "Berlin"}, }, []string{"Paris", "Berlin"}, }, { "arrays test", [2]Profile{ {33, "Paris"}, {32, "Berlin"}, }, []string{"Paris", "Berlin"}, },*/ { "maps test", map[int]string{ 1: "tokoy", 2: "paris", }, []string{"tokoy", "paris"}, }, } var got []string for _, test := range cases { t.Run(test.Name, func(t *testing.T) { walk(test.Input, func(input string) { got = append(got, input) }) assertReflect(t, got, test.ExpectedCalls) }) t.Run("maps test", func(t *testing.T) { m := map[int]string{ 1: "tokoy", 2: "paris", } walk(m, func(input string) { got = append(got, input) }) assertContains(t, got, "tokoy") assertContains(t, got, "paris") }) } } func assertReflect(t *testing.T, got, expected []string) { if !reflect.DeepEqual(got, expected) { t.Errorf("got %v but we expected %v", got, expected) } } func assertContains(t *testing.T, haystack []string, needle string) { flag := false for _, v := range haystack { if v == needle { flag = true } } if !flag { t.Errorf("got %+v but we expected %s", haystack, needle) } } <file_sep>package maps import ( //"errors" ) // ErrXxxx defines the error message const ( ErrNotFound = MapsErr("cannot find the value") ErrExist = MapsErr("value already exists") ErrNotExist = MapsErr("value not exists") ) // MapsErr defines type alias type MapsErr string // Error() defines the map error masssges func (e MapsErr) Error() string { return string(e) } // Maps defines the map type type Maps map[int]string // Mapper as Maps's interface type Mapper interface { Search(id int) string Add(id int, value string) error Update(id int, value string) error Delete(id int) error } // Search searchs value from map func (m Maps) Search(id int) (string, error) { result, ok := m[id] if !ok { return "", ErrNotFound } return result, nil } // Add adds new item into map func (m Maps) Add(id int, value string) error { //_, ok := m[id] //if !ok { // m[id] = value //} //return ErrExist _, err := m.Search(id) switch err { case ErrNotFound: m[id] = value case nil: return ErrExist default: return err } return nil } // Update updates the value of map func (m Maps) Update(id int, value string) error { _, err := m.Search(id) switch err { case ErrNotFound: return ErrNotExist case nil: m[id] = value default: return err } return nil } // Delete deletes the value of map // delete the not existing value we'll show you error func (m Maps) Delete(id int) error { _, err := m.Search(id) switch err { case ErrNotFound: return ErrNotExist case nil: delete(m, id) default: return err } return nil } <file_sep>package rnr import ( "strings" ) // RNR defines a map: Value to Roman type RNR struct { Value uint16 Roman string } type RomanNumber []RNR type windowedRoman string // RN returns a corresponding string with given number func RN(number uint16) string { var ret strings.Builder for _, v := range mapRNR { for number >= v.Value { ret.WriteString(v.Roman) number -= v.Value } } return ret.String() } // NR returns a corresponding int with given roman func NR(roman string) (ret uint16) { for _, symbols := range windowedRoman(roman).Symbols() { ret += mapRNR.ValueOf(symbols...) } return } // ValueOf fetchs value from given arguments func (r RomanNumber) ValueOf(romans ...byte) uint16 { roman := string(romans) for _, s := range r { if s.Roman == roman { return s.Value } } return 0 } // Exists checks if roman equal Roman func (r RomanNumber) Exists(romans ...byte) bool { roman := string(romans) for _, s := range r { if s.Roman == roman { return true } } return false } // mapRNR defines a map for RNR var mapRNR = RomanNumber{ {1000, "M"}, {900, "CM"}, {500, "D"}, {400, "CD"}, {100, "C"}, {90, "XC"}, {50, "L"}, {40, "XL"}, {10, "X"}, {9, "IX"}, {5, "V"}, {4, "IV"}, {1, "I"}, } func (w windowedRoman) Symbols() (symbols [][]byte) { for i := 0; i < len(w); i++ { symbol := w[i] if i+1 < len(w) && isSubtractive(symbol) && mapRNR.Exists(symbol, w[i+1]) { symbols = append(symbols, []byte{byte(symbol), byte(w[i+1])}) i++ } else { symbols = append(symbols, []byte{byte(symbol)}) } } return } func isSubtractive(symbol uint8) bool { return symbol == 'I' || symbol == 'X' || symbol == 'C' } <file_sep>package concurrency import ( "reflect" "testing" "time" ) func wschecker(url string) bool { if url != "" { return true } return false } func TestCheckWebsite(t *testing.T) { urls := []string{ "http://www.baidu.com", "https://github.com", "https://www.google.com", "", } expected := map[string]bool{ "http://www.baidu.com": true, "https://github.com": true, "https://www.google.com": true, "": false, } ret := CheckWebsite(wschecker, urls) if len(ret) != len(urls) { t.Errorf("got %d want %d", len(ret), len(urls)) } if !reflect.DeepEqual(ret, expected) { t.Errorf("got %v want %v", ret, expected) } } func sleeper(_ string) bool { time.Sleep(20 * time.Millisecond) return true } func BenchmarkCheckWebsite(b *testing.B) { urls := make([]string, 100) for i := 0; i < len(urls); i++ { urls[i] = "https://this.is.a.test.com" } for i := 0; i < b.N; i++ { CheckWebsite(sleeper, urls) } } <file_sep>package rnr import ( "fmt" "testing" "testing/quick" ) var cases = []struct { Number uint16 Roman string }{ {Number: 1, Roman: "I"}, {Number: 2, Roman: "II"}, {Number: 3, Roman: "III"}, {Number: 4, Roman: "IV"}, {Number: 5, Roman: "V"}, {Number: 6, Roman: "VI"}, {Number: 7, Roman: "VII"}, {Number: 8, Roman: "VIII"}, {Number: 9, Roman: "IX"}, {Number: 10, Roman: "X"}, {Number: 14, Roman: "XIV"}, {Number: 18, Roman: "XVIII"}, {Number: 20, Roman: "XX"}, {Number: 39, Roman: "XXXIX"}, {Number: 40, Roman: "XL"}, {Number: 47, Roman: "XLVII"}, {Number: 49, Roman: "XLIX"}, {Number: 50, Roman: "L"}, {Number: 100, Roman: "C"}, {Number: 90, Roman: "XC"}, {Number: 400, Roman: "CD"}, {Number: 500, Roman: "D"}, {Number: 900, Roman: "CM"}, {Number: 1000, Roman: "M"}, {Number: 1984, Roman: "MCMLXXXIV"}, {Number: 3999, Roman: "MMMCMXCIX"}, {Number: 2014, Roman: "MMXIV"}, {Number: 1006, Roman: "MVI"}, {Number: 798, Roman: "DCCXCVIII"}, } func TestRN(t *testing.T) { for _, test := range cases { t.Run(fmt.Sprintf("%d --> %q", test.Number, test.Roman), func(t *testing.T) { got := RN(test.Number) assertRN(t, got, test.Roman) }) } } func assertRN(t *testing.T, got, want string) { if got != want { t.Errorf("got %q but we want %q", got, want) } } func TestNR(t *testing.T) { for _, test := range cases { t.Run(fmt.Sprintf("%q --> %d", test.Roman, test.Number), func(t *testing.T) { got := NR(test.Roman) assertNR(t, got, test.Number) }) } } func assertNR(t *testing.T, got, want uint16) { if got != want { t.Errorf("got %d but we want %d", got, want) } } func TestProperties(t *testing.T) { assertion := func(number uint16) bool { if number > 3999 { return true } t.Log("testing", number) roman := RN(number) value := NR(roman) return value == number } if err := quick.Check(assertion, &quick.Config{ MaxCount: 1000, }); err != nil { t.Error("failed checks", err) } } <file_sep>package pe import ( "errors" "fmt" ) // InsufficientBalanceErr defines the error for withdraw var InsufficientBalanceErr = errors.New("cannot withdraw casuse of insufficient balance") // Bitcoin indicates the balance of BTC wallet type Bitcoin int // Wallet defines the bitcoin wallet type Wallet struct { balance Bitcoin } type Transaction interface { Deposit(amount Bitcoin) Balance() Bitcoin Withdraw(amount Bitcoin) error } // Deposit saves the btc into wallet func (w *Wallet) Deposit(amount Bitcoin) { w.balance += amount } // Balance outputs the balance of wallet func (w *Wallet) Balance() Bitcoin { return w.balance } // String redefines the string function with Bitcoin func (b Bitcoin) String() string { return fmt.Sprintf("%d BTC", b) } // Withdraw withdraws the btc from the wallet func (w *Wallet) Withdraw(amount Bitcoin) error { if amount > w.balance { return InsufficientBalanceErr } w.balance -= amount return nil } <file_sep>package main import ( "fmt" ) const ( greetingEN = "Hello, " greetingSP = "Hola, " ) // Hello says hello for you func Hello(s, lan string) string { if s == "" { s = "i0Ek3" } return greeting(lan) + s } func greeting(lan string) (prefix string) { switch lan { case "Espanol": prefix = greetingSP case "English": prefix = greetingEN default: } return } func main() { fmt.Println(Hello("i0Ek3", "Espanol")) } <file_sep>package main import ( "bytes" "testing" ) func TestGreet(t *testing.T) { name := "i0Ek3" buf := bytes.Buffer{} Greet(&buf, name) got := buf.String() want := "Hello " + name if got != want { t.Errorf("got '%q' want '%q'", got, want) } } <file_sep>package main import ( "fmt" "io" "os" "time" ) const ( begin = 3 last = "Go!" sleep = "sleep" write = "write" ) // Sleeper defines sleep interface type Sleeper interface { Sleep() } // Spy is a mock to record how many Sleep() was invocated type SpySleep struct { Calls int } // Sleep mocks sleep func (s *SpySleep) Sleep() { s.Calls++ } // CountdownOperationSpy spys times of call type CountdownOperationSpy struct { Calls []string } // Sleep add sleep into slice func (s *CountdownOperationSpy) Sleep() { s.Calls = append(s.Calls, sleep) } // Write writes into slice func (s *CountdownOperationSpy) Write(p []byte) (n int, err error) { s.Calls = append(s.Calls, write) return } // ConfigurableSleeper defines sleep duration type ConfigurableSleeper struct { duration time.Duration } // Sleep sleeps duration time func (s *ConfigurableSleeper) Sleep() { time.Sleep(s.duration) } // Countdown counts the number func Countdown(out io.Writer, slp Sleeper) { for i := begin; i > 0; i-- { slp.Sleep() fmt.Fprintln(out, i) } slp.Sleep() fmt.Fprint(out, last) } func main() { slp := &ConfigurableSleeper{1 * time.Second} Countdown(os.Stdout, slp) } <file_sep>package concurrency import () type result struct { string bool } // WebsiteChecker defines a function type type WebsiteChecker func(string) bool // CheckWebsite checks if the url is correct func CheckWebsite(wc WebsiteChecker, urls []string) map[string]bool { results := make(map[string]bool) retCh := make(chan result) for _, url := range urls { go func(u string) { retCh <- result{u, wc(u)} }(url) } for i := 0; i < len(urls); i++ { result := <-retCh results[result.string] = result.bool } return results } <file_sep>package main import ( "math" ) // Cal calculates the value for given needs func Cal(number float64) float64 { if number < 0 { return mathHelper(number) } else if number == 0 { math.Inf(0) } return math.Cos(number) } func mathHelper(number float64) float64 { return calNegative(number) } func calNegative(number float64) float64 { return math.Cos(math.Abs(number)) } <file_sep>package integer // Add adds two int numbers func Add(a, b int) int { return a + b } <file_sep>package main import ( "fmt" "io" "net/http" ) // Greet greets someone func Greet(w io.Writer, name string) { fmt.Fprintf(w, "Hello %s", name) } // GreetHandler handles request and ack response func GreetHandler(w http.ResponseWriter, r *http.Request) { Greet(w, "i0Ek3") } func main() { fmt.Println("Please open the url http://localhost:6789 to visit it.") http.ListenAndServe(":6789", http.HandlerFunc(GreetHandler)) } <file_sep>module go_tests go 1.15 require github.com/i0Ek3/asrt v0.0.0-20201109040949-e64a9040fd89 <file_sep>package integer import ( "fmt" "testing" ) func TestAdd(t *testing.T) { got := Add(2, 1) want := 3 if got != want { t.Errorf("got '%q' want '%q'", got, want) } } func ExampleAdd() { sum := Add(1, 2) fmt.Println(sum) // Output: 3 } <file_sep>package slice // Sum gets the ans of slice func Sum(s []int) int { ret := 0 for _, v := range s { ret += v } return ret } // SumAll calucates the ans of all slice func SumAll(s1, s2 []int) int { ret := 0 for _, v1 := range s1 { ret += v1 } for _, v2 := range s2 { ret += v2 } return ret } // SumToNew makes each slice ans to new slice func SumToNew(s ...[]int) []int { var ret []int for i := 0; i < len(s); i++ { if len(s) == 0 { ret = append(ret, 0) } else { ret = append(ret, Sum(s[i])) } } return ret } <file_sep>package array // Sum1 gets the ans of arr with common for loop func Sum1(arr [5]int) int { sum := 0 for i := 0; i < 5; i++ { sum += arr[i] } return sum } // Sum2 gets the ans of arr with for range loop func Sum2(arr [5]int) int { sum := 0 for _, v := range arr { sum += v } return sum } <file_sep>package pe import ( "fmt" "testing" ) func TestWallet(t *testing.T) { // Use assert functions replace assistant anonymous functions /* assertBalance := func(t *testing.T, w Wallet, want Bitcoin) { got := w.Balance() if got != want { t.Errorf("got '%s' want '%s'", got, want) } } assertError := func(t *testing.T, got error, want error) { if got == nil { t.Fatal("we need an error") } if got != want { t.Errorf("got '%s' want '%s'", got, want) } } */ w := Wallet{} t.Run("Depoist", func(t *testing.T) { w.Deposit(Bitcoin(10)) want := Bitcoin(10) assertBalance(t, w, want) }) t.Run("Withdraw", func(t *testing.T) { err := w.Withdraw(Bitcoin(10)) want := Bitcoin(0) assertBalance(t, w, want) assertNoError(t, err) }) t.Run("Withdraw with unenough balance", func(t *testing.T) { initBalance := Bitcoin(10) w = Wallet{initBalance} err := w.Withdraw(Bitcoin(100)) assertBalance(t, w, initBalance) assertError(t, err, InsufficientBalanceErr) }) } func assertBalance(t *testing.T, w Wallet, want Bitcoin) { got := w.Balance() if got != want { t.Errorf("got '%s' want '%s'", got, want) } } func assertNoError(t *testing.T, got error) { if got != nil { t.Fatal("got an error but we don't need it") } } func assertError(t *testing.T, got error, want error) { if got == nil { t.Fatal("we need an error") } if got != want { t.Errorf("got '%s' want '%s'", got, want) } } func ExampleDeposit() { w := Wallet{} w.Deposit(Bitcoin(10)) ret := w.Balance() fmt.Println(ret) // Output: 10 BTC } func ExampleWithdraw() { w := Wallet{} w.Withdraw(Bitcoin(0)) ret := w.Balance() fmt.Println(ret) // Output: 0 BTC } <file_sep>package maps import "testing" func TestSearch(t *testing.T) { id := 1 m := Maps{id: "map test"} t.Run("known id", func(t *testing.T) { got, _ := m.Search(id) want := "map test" assertStrings(t, got, want) }) t.Run("unknown id", func(t *testing.T) { _, err := m.Search(-1) assertError(t, err, ErrNotFound) }) } func assertStrings(t *testing.T, got, want string) { t.Helper() if got != want { t.Errorf("got '%s' want '%s'", got, want) } } func assertError(t *testing.T, got, want error) { t.Helper() if got != want { t.Errorf("got '%s' want '%s'", got, want) } } func TestAdd(t *testing.T) { t.Run("new value", func(t *testing.T) { m := Maps{} id := 2 value := "test too" err := m.Add(id, value) assertError(t, err, nil) assertValue(t, m, id, value) }) t.Run("existing value", func(t *testing.T) { m := Maps{} id := 1 value := "map test" err := m.Add(id, value) assertError(t, err, ErrExist) assertValue(t, m, id, value) }) } func assertValue(t *testing.T, m Maps, id int, value string) { t.Helper() got, err := m.Search(id) if err != nil { t.Fatal("should find added value:", err) } if value != got { t.Errorf("got '%s' want '%s'", got, value) } } func TestUpdate(t *testing.T) { t.Run("new value", func(t *testing.T) { id := 3 value := "test too" m := Maps{} err := m.Update(id, value) assertError(t, err, ErrNotExist) }) t.Run("existing value", func(t *testing.T) { id := 3 value := "test too" m := Maps{id: value} newValue := "new value" err := m.Update(id, newValue) assertError(t, err, nil) assertValue(t, m, id, newValue) }) } func TestDelete(t *testing.T) { t.Run("not existing value", func(t *testing.T) { id := 4 m := Maps{} err := m.Delete(id) assertError(t, err, ErrNotExist) }) t.Run("existing value", func(t *testing.T) { id := 3 m := Maps{} err := m.Delete(id) assertError(t, err, nil) }) } <file_sep>package smi import ( "math" ) // Shape defines some shapes type Shape struct { length float64 width float64 } // Shaper defines some method of Shape type Shaper interface { Perimeter() float64 Area() float64 } // Rectangle type Rectangle struct { Shape } // Circle type Circle struct { radius float64 } // Triangle type Triangle struct { length float64 height float64 } // Perimeter calculates the perimeter of given shape //func (r Rectangle) Perimeter() float64 { // r.area = r.length * r.width // return r.area //} //// Perimeter calculates the perimeter of given shape //func Perimeter(l, w float64) float64 { // return 2 * (l + w) //} // //// Area calculates the area of given shape //func Area(l, w float64) float64 { // return l * w //} // Perimeter calculates the perimeter of Rectangle func (r Rectangle) Perimeter() float64 { return 2 * (r.length + r.width) } // Area calculates the area of Rectangle func (r Rectangle) Area() float64 { return r.length * r.width } // Perimeter calculates the perimeter of Circle func (c Circle) Perimeter() float64 { return 2 * c.radius * math.Pi } // Area calculates the area of Circle func (c Circle) Area() float64 { return math.Pi * math.Pow(2, c.radius) } // Perimeter calculates the area of Triangle func (t Triangle) Perimeter() float64 { // cannot calculate the perimeter of Triangle directly return 0.0 } // Area calculates the area of Triangle func (t Triangle) Area() float64 { return 0.5 * t.length * t.height }
48f7df823f28f7121680e3da8f9d61abc6308fe3
[ "Markdown", "Go Module", "Go" ]
35
Go
i0Ek3/go_tests
c75f451b82dde0c4c893e8c6a6d7f501f79a405e
cc60dc03e69ccbd34cf82ddb821faa2d1aeaa665
refs/heads/master
<file_sep>const messageTypes = { LEFT: "left", RIGHT: "right", LOGIN: "login" }; // Chat Stuff const chatWindow = document.getElementById("chat"); const messagesList = document.getElementById("messagesList"); const messageInput = document.getElementById("messageInput"); const sendBtn = document.getElementById("sendBtn"); // Login Stuff let username = ""; const usernameInput = document.getElementById("usernameInput"); const loginBtn = document.getElementById("loginBtn"); const loginWindow = document.getElementById("login"); const messages = []; //{ author, date, content, type } var socket = io(); socket.on("message", message => { console.log(message); if (message.type !== messageTypes.LOGIN) { if (message.author === username) { message.type = messageTypes.RIGHT; } else { message.type = messageTypes.LEFT; } } messages.push(message); displayMessages(); chatWindow.scrollTop = chatWindow.scrollHeight; }); // take in message object, and return corresponding message HTML const createMessageHTML = message => { if (message.type === messageTypes.LOGIN) { return `<p class="secondary-text text-center mb-2">${ message.author } has joined the chat...</p>`; } return `<div class="message ${ message.type === messageTypes.LEFT ? "message-left" : "message-right" }"> <div id="message-details" class="flex"> <p class="message-author">${ message.type === messageTypes.RIGHT ? "" : message.author }</p> <p class="message-date">${message.date}</p> </div> <p class="message-content">${message.content}</p> </div>`; }; const displayMessages = () => { console.log("displaying messages!"); const messagesHTML = messages .map(message => createMessageHTML(message)) .join(""); messagesList.innerHTML = messagesHTML; }; displayMessages(); // sendBtn callback sendBtn.addEventListener("click", e => { e.preventDefault(); if (!messageInput.value) { return alert("must type up a message"); } const date = new Date(), day = date.getDate(), year = date.getFullYear(), month = ("0" + (date.getMonth() + 1)).slice(-2), dateString = `${month}/${day}/${year}`; const message = { author: username, date: dateString, content: messageInput.value }; sendMessages(message); messageInput.value = ""; // Scroll to the bottom of the screen after every message // chatWindow.scrollTop = chatWindow.scrollHeight; }); const sendMessages = message => { socket.emit("message", message); }; // loginBtn callback loginBtn.addEventListener("click", e => { // preventDefault of a form e.preventDefault(); // set the usename and crete logged in message if (!usernameInput.value) { return alert("Must type in username!"); } username = usernameInput.value; sendMessages({ author: username, type: messageTypes.LOGIN }); // hide login and show chat window loginWindow.classList.add("hidden"); chatWindow.classList.remove("hidden"); });
21aa836818e3a757b556cf204548663e63e64a15
[ "JavaScript" ]
1
JavaScript
todorovicd/chatAppSocketIO
94d70b67f4235486d686d56f9b3fb0ee60df2c7f
459b740f321874e80eaf6633d20e18809602d6fc
refs/heads/master
<repo_name>deepfence-demo/secure-gitops<file_sep>/flux/04-image-update.sh #/bin/sh flux create image update flux-system \ --git-repo-ref=flux-system \ --git-repo-path="./clusters/digital_ocean" \ --checkout-branch=master \ --push-branch=master \ --author-name=fluxcdbot \ --author-email=<EMAIL> \ --commit-template="{{range .Updated.Images}}{{println .}}{{end}}" \ --export > ../clusters/digital_ocean/flux-system-automation.yaml sed -i '' -e '$ d' ../clusters/digital_ocean/flux-system-automation.yaml <file_sep>/flux/03-image-policy.sh #/bin/sh registry=registry.deepfence.net repo=( adservice cartservice checkoutservice currencyservice emailservice frontend paymentservice productcatalogservice recommendationservice shippingservice ) for name in "${repo[@]}"; do flux create image policy ${name} \ --image-ref=${name} \ --select-semver='>=0.2.0 <0.3.0' \ --export > ../clusters/digital_ocean/${name}-policy.yaml sed -i '' -e '$ d' ../clusters/digital_ocean/${name}-policy.yaml done <file_sep>/flux/02-image-scanning.sh #/bin/sh registry=registry.deepfence.net repo=( adservice cartservice checkoutservice currencyservice emailservice frontend paymentservice productcatalogservice recommendationservice shippingservice ) for name in "${repo[@]}"; do flux create image repository ${name} \ --image=${registry}/${name} \ --interval=0m30s \ --export > ../clusters/digital_ocean/${name}-registry.yaml sed -i '' -e '$ d' ../clusters/digital_ocean/${name}-registry.yaml echo " secretRef:" >> ../clusters/digital_ocean/${name}-registry.yaml echo " name: ${registry}" >> ../clusters/digital_ocean/${name}-registry.yaml done <file_sep>/flux/01-bootstrap.sh #/bin/sh flux bootstrap github \ --components-extra=image-reflector-controller,image-automation-controller \ --owner=${GITHUB_USER} \ --repository=secure-gitops \ --branch=master \ --path=./clusters/digital_ocean \ --personal \ --private \ --token-auth <file_sep>/README.md ## Secure GitOps This demo illustrates Secure GitOps practices by incorporating GitHub Actions and [Deepfence ThreatMapper](https://github.com/deepfence/ThreatMapper) vulnerability scanning for Continuous Integration (CI) and [WeaveWorks Flux](https://github.com/fluxcd/flux) for Continuous Delivery (CD). Visit https://fluxcd.io/docs/guides/image-update/ for instructions on how to use Flux.
7370aba67fe536b42fc4bdfe757a8a7a87c23735
[ "Markdown", "Shell" ]
5
Shell
deepfence-demo/secure-gitops
f1a26d97ddfe2271d5f4d394f67bb97e972f24dc
408e00e443a3ae891e753bfad68585fce6f486cd
refs/heads/master
<repo_name>caed04/Sypro-cms<file_sep>/README.md Syproco CMS ======================== Syproco cms es un proyecto personal, con el fin de poder crear un repositorio de base para comenzar projectos web. Tecnologias? -------------- He basado este micro proyecto en las siguientes tecnologias: * Symfony, * Twig, * Doctrine ORM/DBAL, * Less, * Gulp. Instalación? -------------- * Clonar: `https://github.com/caed04/Sypro-cms.git`, * `composer install`, * `npm install`, * `bower install`, * `php bin/console server:run`, * `gulp`, [1]: https://symfony.com/doc/3.2/setup.html [6]: https://symfony.com/doc/current/bundles/SensioFrameworkExtraBundle/index.html [7]: https://symfony.com/doc/3.2/doctrine.html [8]: https://symfony.com/doc/3.2/templating.html [9]: https://symfony.com/doc/3.2/security.html [10]: https://symfony.com/doc/3.2/email.html [11]: https://symfony.com/doc/3.2/logging.html [12]: https://symfony.com/doc/3.2/assetic/asset_management.html [13]: https://symfony.com/doc/current/bundles/SensioGeneratorBundle/index.html <file_sep>/gulpfile.js var gulp = require('gulp'), less = require('gulp-less'), sourcemaps = require('gulp-sourcemaps'), autoprefixer = require('gulp-autoprefixer'), notify = require('gulp-notify'), concat = require('gulp-concat'), uglify = require('gulp-uglify'), cleanCSS = require('gulp-clean-css'), browserSync = require('browser-sync').create(); var lessStylesUrl = './web/src/less/', scriptsUrl = './web/src/js/', htmlFilesUrl = './app/Resources/views', distCssUrl = './web/dist/css/', distScriptsUrl = './web/dist/js/'; var url = 'http://127.0.0.1/SYPROCO-CMS/Sypro-cms/web/', symfonyServerUrl = 'http://127.0.0.1:8000/'; // TASK-STYLES gulp.task('styles', function(){ gulp.src( lessStylesUrl +'*.less') .pipe(sourcemaps.init()) .pipe(less()).on('error', notify.onError(function(){ return 'Error compiling less.\n' + error; })) .pipe(autoprefixer({ browsers:['last 2 versions'], cascade:false })) .pipe(cleanCSS({compatibility: 'ie8'})) .pipe(sourcemaps.write('./maps')) .pipe(gulp.dest(distCssUrl)) .pipe(notify({ title: 'LESS', message: 'SUCCESS: Compiled file' })) .pipe(browserSync.stream()); }); // TASK-SCRIPTS gulp.task('scripts', function(){ return gulp.src( scriptsUrl +'*.js') .pipe(concat('all.min.js')) .pipe(uglify()) .pipe(gulp.dest(distScriptsUrl)); }); // TASK-BROWSER-SYNC gulp.task('browser-sync', function(){ browserSync.init({ injectChanges: true, files: [htmlFilesUrl +'/**/*.twig','./web/dist/**/*.{css,js}'], proxy: symfonyServerUrl }) }); // TASK-WATCH gulp.task('watch', function(){ gulp.watch(lessStylesUrl +'*.less', ['styles']); gulp.watch(scriptsUrl +'*.js', ['scripts']); }); //TASK-DEFAULT gulp.task('default', ['styles', 'scripts', 'browser-sync', 'watch']);<file_sep>/web/src/js/main.js /** * Created by caed0 on 2017-04-21. */
35ece200271d22174e1e04985e8efc1c491b41ab
[ "Markdown", "JavaScript" ]
3
Markdown
caed04/Sypro-cms
c4815c66452f394f0d13b5d1bafc1e8e0900ffcd
d636394d2245ef85934e755ed1ecfb733473740a
refs/heads/master
<repo_name>diptibaral/lab2<file_sep>/app/src/main/java/com/dipti/lab2/RadioButtonActivity.kt package com.dipti.lab2 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.RadioButton import android.widget.TextView class RadioButtonActivity : AppCompatActivity() { private lateinit var textView: TextView private lateinit var male: RadioButton private lateinit var female: RadioButton override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_radio_button) textView = findViewById(R.id.textView) male= findViewById(R.id.male) female = findViewById(R.id.female) displayCheck() } fun displayCheck() { male.setOnClickListener { if (male.isChecked) { println("male")//shows in logcat textView.text = male.text.toString() } } female.setOnClickListener { if (female.isChecked) { println("female") textView.text = female.text.toString() } } } }<file_sep>/app/src/main/java/com/dipti/lab2/MainActivity.kt package com.dipti.lab2 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import android.widget.TextView class MainActivity : AppCompatActivity() { private lateinit var textView: TextView private lateinit var button: Button var count = 0 override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) textView = findViewById(R.id.textView) button = findViewById(R.id.button2) button.setOnClickListener { count = count + 1 showCount(count) } } fun showCount(c: Int) { textView.setText(c.toString()) } }
31052fcc977267722b78c3665c0f7d9ea8c17934
[ "Kotlin" ]
2
Kotlin
diptibaral/lab2
28dfd057a934fcce9d8694b6014ca63aef5bae87
5a1ce6aead198e96a8665d52715032d1f317ff16
refs/heads/main
<repo_name>hyungchanchoi/AlgorithmTrading_pykiwoom<file_sep>/get_contract_data copy.py from pykiwoom.kiwoom import * import pandas as pd import time from datetime import datetime,timedelta today = datetime.today().strftime("%Y%m%d") kiwoom = Kiwoom() kiwoom.CommConnect(block=True) state = kiwoom.GetConnectState() if state == 0: print("미연결") elif state == 1: print("연결완료") ############################### 종목명,종목코드 딕셔너리 ######################################### name_to_code = {} code_to_name = {} kospi = kiwoom.GetCodeListByMarket(0) kodaq = kiwoom.GetCodeListByMarket(10) etf = kiwoom.GetCodeListByMarket(8) for code in kospi: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name for code in kodaq: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name for code in etf: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name ############################### daily 종목 ######################################### codes = ['삼성전자','SK하이닉스','LG화학','삼성전자우','NAVER','삼성바이오로직스','현대차','삼성SDI','셀트리온','기아차','TIGER TOP10'] ############################### 체결강도 조회 함수 ######################################### # TR 요청 (연속조회) def get_contract_data(code): dfs = [] df = kiwoom.block_request("opt10046", 종목코드 = code, 틱범위 = 1, 체결강도구분 =1, output="체결강도시간별", next=0) dfs.append(df) while kiwoom.tr_remained: df = kiwoom.block_request("opt10046", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="체결강도시간별", next=2) dfs.append(df) print(df['체결시간'].iloc[0]) time.sleep(1) df = pd.concat(dfs) df = df[['체결시간','전일대비','등락율','체결강도','체결강도5분','체결강도20분','체결강도60분']] return df[::-1] ############################### main ######################################### ### get data ### print('--- start getting strength data ---') for name in codes: df = get_contract_data(name_to_code[name]) df.to_pickle('strength/'+ name +'(S)_'+today) print(name,'completed') print('--- task completed --- ') <file_sep>/README.md # AlgorithmTrading_pykiwoom ### COMPONENTS ### 1. GET_HISTORIC_TICK_DATA.PY ### 2. DATA ANALYSIS ### 3. BACKTEST # 키움 API로부터 종목 과거 틱 데이터 저장하기 - GET_HISTORIC_TICK_DATA.PY ### 터미널에서 파일 실행 시, ### 1. 주식시장 내 모든 종목 코드와, 종목명 딕셔너리 형태로 저장 ### 2. 틱 데이터를 구하고자 하는 종목명 입력 ### (만약 잘못된 종목명인 경우 재입력 요구) ### 3. 종목명 입력 시, continue or stop? 입력 ### (stop인 경우, 입력한 종목에 대한 틱 데이터 저장 시작, 그 외 command일 경우 그 다음 종목명 입력) ### 4. 틱 데이터를 구하고자 하는 종목명 입력 후 stop 입력 시, 데이터 저장 문구와 함께 키움서버로부터 데이터 저장 시작 ### 5. 원하는 경로로 'pickle'의 형태로 저장<file_sep>/get_historic_data.py from pykiwoom.kiwoom import * import pandas as pd import time from datetime import datetime,timedelta today = datetime.today().strftime("%Y%m%d") kiwoom = Kiwoom() kiwoom.CommConnect(block=True) state = kiwoom.GetConnectState() if state == 0: print("미연결") elif state == 1: print("연결완료") ############################### 종목명,종목코드 딕셔너리 ######################################### name_to_code = {} code_to_name = {} kospi = kiwoom.GetCodeListByMarket(0) kodaq = kiwoom.GetCodeListByMarket(10) etf = kiwoom.GetCodeListByMarket(8) for code in kospi: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name for code in kodaq: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name for code in etf: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name ############################### daily 종목 ######################################### daily = ['KODEX 200','KODEX 인버스','KODEX 혁신기술테마액티브','TIGER 200','TIGER 인버스','TIGER AI코리아그로스액티브', 'KODEX 삼성그룹','KODEX 삼성그룹밸류','삼성전자','삼성전자우'] ############################### 틱/분 차트 조회 함수 ######################################### # TR 요청 (연속조회) def get_tick_data(code): dfs = [] df = kiwoom.block_request("opt10079", 종목코드 = code, 틱범위 = 5, 수정주가구분 =1, output="주식틱차트조회", next=0) dfs.append(df) while kiwoom.tr_remained: df = kiwoom.block_request("opt10079", 종목코드 = code, 틱범위 = 5, 수정주가구분 =1, output="주식틱차트조회", next=2) dfs.append(df) print(df['체결시간'].iloc[0]) if int(df['체결시간'].iloc[0])< 20210111000000: break time.sleep(1) df = pd.concat(dfs) df = df[['체결시간','현재가','거래량']] return df[::-1] def get_min_data(code): dfs = [] df = kiwoom.block_request("opt10080", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="주식틱차트조회", next=0) dfs.append(df) while kiwoom.tr_remained: df = kiwoom.block_request("opt10080", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="주식틱차트조회", next=2) dfs.append(df) time.sleep(1) df = pd.concat(dfs) df = df[['체결시간','현재가','거래량']] return df[::-1] def get_day_data(code): dfs = [] df = kiwoom.block_request("opt10081", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="주식일봉차트조회", next=0) dfs.append(df) while kiwoom.tr_remained: df = kiwoom.block_request("opt10081", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="주식일봉차트조회", next=2) dfs.append(df) time.sleep(1) df = pd.concat(dfs) df = df[['일자','현재가','거래량']] return df[::-1] ############################### main ######################################### command = 'continue' data = None codes = [] ### input data type ### while True: data = input('data type / tick or min or day? : ') if data not in ['tick','min','day','daily'] : print('wrong data type') continue else: break ### input code name ### while command != 'stop': if data == 'daily': break name = input('종목명 :') if name not in name_to_code.keys(): print('wrong name') continue else: code = name_to_code[name] codes.append(code) command = input('continue or stop? : ') print('--- start getting historic data ---') ### get data ### if data == 'tick': for code in codes: df = get_tick_data(code) df.to_pickle('datas/'+code_to_name[code]+'(T)_'+today) print(code_to_name[code],'completed') elif data == 'min': for code in codes: df = get_min_data(code) df.to_pickle('datas/'+code_to_name[code]+'(m)_'+today) print(code_to_name[code],'completed') elif data == 'day': for code in codes: df = get_day_data(code) df.to_pickle('datas/'+code_to_name[code]+'(d)_'+today) print(code_to_name[code],'completed') elif data == 'daily': print('--- daily data ---') for name in daily: df = get_min_data(name_to_code[name]) df.to_pickle('datas/'+name+'(m)_'+today) print(name,'completed') print('--- task completed --- ') <file_sep>/find_coint_pairs.py ##### 대신증권 연결 확인 import win32com.client instCpCybos = win32com.client.Dispatch("CpUtil.CpCybos") print(instCpCybos.IsConnect) import pandas as pd import numpy as np import math from datetime import datetime,timedelta import time today = datetime.today().strftime("%Y%m%d") ############ CYBOS API CHART METHOD ################## def CheckVolumn(instStockChart, code,finish, start): # SetInputValue instStockChart.SetInputValue(0, code) instStockChart.SetInputValue(1, ord('1')) instStockChart.SetInputValue(2,finish ) instStockChart.SetInputValue(3,start) instStockChart.SetInputValue(4, 60) instStockChart.SetInputValue(5, 8) instStockChart.SetInputValue(6, ord('D')) instStockChart.SetInputValue(9, ord('1')) # BlockRequest instStockChart.BlockRequest() # GetData volumes = [] numData = instStockChart.GetHeaderValue(3) for i in range(numData): volume = instStockChart.GetDataValue(0, i) volumes.append(volume) if len(volumes) == 0: return 0 # Calculate average volume averageVolume = (sum(volumes) - volumes[0]) / (len(volumes) -1) if(averageVolume > 1000000 ): return 1 else: return 0 # 분 차트 받아오기 def get_min(code,today,start,time): # 종목, 기간, 오늘, 시점, 분, 시간간격 # print(start, today) instStockChart = win32com.client.Dispatch("CpSysDib.StockChart") instStockChart.SetInputValue(0, code ) instStockChart.SetInputValue(1, ord('1')) instStockChart.SetInputValue(2, today) instStockChart.SetInputValue(3, start) # instStockChart.SetInputValue(4, 1000) instStockChart.SetInputValue(5, (0,1,5)) instStockChart.SetInputValue(6, ord('m')) # 'D':일 'm' : 분, 'T' : 틱 instStockChart.SetInputValue(7, time) # 데이터 주기 instStockChart.SetInputValue(9, ord('1')) instStockChart.SetInputValue(10, 3) instStockChart.BlockRequest() numData = instStockChart.GetHeaderValue(3) numField = instStockChart.GetHeaderValue(1) temp = {} for i in range(numData): temp[str(instStockChart.GetDataValue(0, i)) +'.'+ str(instStockChart.GetDataValue(1, i))] = [instStockChart.GetDataValue(2, i)] temp = pd.DataFrame(temp).transpose() temp.index.names = ['time'] return temp def merge(temp,data ): temp = pd.merge(left = temp , right = data, how = "inner", on = "time") return temp ############# MAIN ################## if __name__ == '__main__': finish = int(input('What Date to search?(YYYYMMDD) :')) start = finish - 10000 ############ SAVE CODE, NAME AS DICTIONARY ################## instCpCodeMgr = win32com.client.Dispatch("CpUtil.CpCodeMgr") codeList = instCpCodeMgr.GetStockListByMarket(1) code_to_name = {} name_to_code = {} for code in codeList: name = instCpCodeMgr.CodeToName(code) code_to_name[code] = name name_to_code[name] = code ############ GET CODE WHICH EXCEED CERTAIN VOLUME ################## instStockChart = win32com.client.Dispatch("CpSysDib.StockChart") instCpCodeMgr = win32com.client.Dispatch("CpUtil.CpCodeMgr") codeList = instCpCodeMgr.GetStockListByMarket(1) buyList = [] buyName= [] i = 0 ; j= 0 start = time.time() for code in codeList: j+=1 if CheckVolumn(instStockChart, code,finish,start) == 1: buyList.append(code) buyName.append(code_to_name[code]) print(code, code_to_name[code],' ----',j,'/',len(codeList)) i+=1 if i > 58 and time.time() - start < 15: time.sleep( 16 - (time.time() - start)) start = time.time() i=0 ############ GET MIN DATA ################## buyDict = {} for code in buyList : #buyList buyDict[code] = [np.log(get_min(code,finish,start,1))] ############ SAVE AS DATAFRAME ################## data = pd.DataFrame(buyDict[buyList[0]][0]) buyCode = buyList for code in buyList[1:] : temp = buyDict[code][0] if len(merge(data,temp)) < 6600 or int(temp.isnull().sum()) > 0: buyCode.remove(code) buyName.remove(code_to_name[code]) continue data = merge(data,temp) data.columns = buyName data.to_pickle('data_coint_pairs.xlsx')<file_sep>/get_low_data.py from pykiwoom.kiwoom import * import pandas as pd import numpy as np import time from datetime import datetime,timedelta today = datetime.today().strftime("%Y%m%d") kiwoom = Kiwoom() kiwoom.CommConnect(block=True) state = kiwoom.GetConnectState() if state == 0: print("미연결") elif state == 1: print("연결완료") ############################### 종목명,종목코드 딕셔너리 ######################################### name_to_code = {} code_to_name = {} kospi = kiwoom.GetCodeListByMarket(0) kosdaq = kiwoom.GetCodeListByMarket(10) for code in kospi: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name for code in kosdaq: name = kiwoom.GetMasterCodeName(code) name_to_code[name] = code code_to_name[code] = name ############################### 전 종목 분 차트 조회 함수 ######################################### # TR 요청 (연속조회) def one_day(temp,test_day): begin = np.where( np.array(temp['체결시간']) > str(test_day))[0][0] end = np.where( str(test_day+1) > np.array(temp['체결시간']) )[0][-1] df = temp.iloc[begin-1:end] return df def get_min_data(low_lists,code): dfs = [] df = kiwoom.block_request("opt10080", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="주식분봉차트조회", next=0) dfs.append(df) i = 0 while kiwoom.tr_remained: df = kiwoom.block_request("opt10080", 종목코드 = code, 틱범위 = 1, 수정주가구분 =1, output="주식분봉차트조회", next=2) dfs.append(df) print(df['체결시간'].iloc[0][:8]) time.sleep(3.7) i +=1 if i ==1: break df = pd.concat(dfs) df = df[['체결시간','현재가']] df = df[::-1] for date in range(int(df['체결시간'].iloc[0][:8]),int(df['체결시간'].iloc[-1][:8])+1): print(date) if 20201231 < date < 20210101: continue temps = pd.DataFrame() temps = one_day(df,date) if len(temps) != 0: temps['현재가'] = abs(pd.to_numeric(temps['현재가'])) temps['등락률'] = (temps['현재가'] - temps['현재가'].iloc[0]) / temps['현재가'].iloc[0] else: continue if len(np.where(np.array(temps['등락률']) < -0.29)[0]) > 0 : low_lists.append((code_to_name[code],str(date))) print(code_to_name[code],str(date)) ############################### main ######################################### print('--- start getting historic data ---') ### get data ### if __name__ == '__main__': low_lists = [] i = 1 for code in kosdaq: print(code_to_name[code],'start','(',i,'/',len(kosdaq),')') get_min_data(low_lists,code) print(code_to_name[code],'completed','(',i,'/',len(kosdaq),')') i += 1 print(low_lists) print('--- task completed --- ')
7a472b8332ae5d40f037d7b133a3f6873bf70838
[ "Markdown", "Python" ]
5
Python
hyungchanchoi/AlgorithmTrading_pykiwoom
3edb1eb115bdedeedea736b9c56ca8df208dc146
3653a77892b70a263a138d14996767843c3c5513
refs/heads/master
<repo_name>ry/scss.go<file_sep>/libsass/util.hpp #ifndef SASS_UTIL #define SASS_UTIL #ifndef SASS_AST #include "ast.hpp" #endif #include <string> namespace Sass { namespace Util { std::string normalize_underscores(const std::string& str); bool containsAnyPrintableStatements(Block* b); bool isPrintable(Ruleset* r); bool isPrintable(Feature_Block* r); bool isPrintable(Media_Block* r); bool isPrintable(Block* b); bool isAscii(int ch); } } #endif <file_sep>/scss_test.go package scss import ( "io/ioutil" "os" "path" "path/filepath" "regexp" "strings" "testing" ) func TestBootstrap(t *testing.T) { inputPath := "bootstrap-sass/stylesheets/_bootstrap.scss" source, err := readAll(inputPath) if err != nil { t.Fatal(err) } loader := TestLoader{ Dir: path.Dir(inputPath), } output, err := Compile(inputPath, string(source), false, loader) if err != nil { t.Fatal(err) } println(output) } func TestBasicImports(t *testing.T) { inputPath := "spec/spec/basic/14_imports/input.scss" check(t, inputPath) } func TestAll(t *testing.T) { matches, err := filepath.Glob("spec/spec/*/*/input.scss") if err != nil { t.Fatal("glob fail") } if len(matches) == 0 { t.Fatal("no spec matches") } for _, inputPath := range matches { if strings.HasPrefix(inputPath, "spec/spec/libsass-todo") { continue } println(inputPath) check(t, inputPath) } } func findPath(p string) string { if !fileExists(p) { p = p + ".scss" if !fileExists(p) { p = path.Join(path.Dir(p), "_"+path.Base(p)) if !fileExists(p) { panic("can't find input path: " + p) } } } return p } func firstPathExists(paths []string) string { for _, p := range paths { println(p) if fileExists(p) { return p } } panic("couldn't find any!") return "" } type TestLoader struct { Dir string } func (l TestLoader) Load(parentPath string, importedPath string) (out Import) { println("parentPath", parentPath) println("importedPath", importedPath) var absImportedPath string if path.IsAbs(importedPath) { absImportedPath = importedPath } else { parentDir := path.Dir(parentPath) absImportedPath = path.Join(parentDir, importedPath) } paths := PossiblePaths(absImportedPath) if paths == nil { // return error? out.Path = importedPath return out } p := firstPathExists(paths) out.Path = p source_bytes, err := readAll(p) if err != nil { panic(err) } out.Source = string(source_bytes) return out } // The ruby spec that we're using to test uses the following function to // "clean" the output. So we want to reproduce its behavior exactly. // // def _clean_output(css) // css.gsub(/\s+/, " ") // .gsub(/ *\{/, " {\n") // .gsub(/([;,]) */, "\\1\n") // .gsub(/ *\} */, " }\n") // .strip // end func cleanOutput(css string) string { r1, _ := regexp.Compile(`\s+`) css = r1.ReplaceAllString(css, " ") r2, _ := regexp.Compile(` *\{`) css = r2.ReplaceAllString(css, " {\n") /* uh.. how do i do pattern match replace? too lazy to figure out right now. r3, _ := regexp.Compile(`([;,]) *`) css = r3.ReplaceAllString(css, "\\1\n") */ r4, _ := regexp.Compile(` *\} *`) css = r4.ReplaceAllString(css, " }\n") return strings.TrimSpace(css) } func check(t *testing.T, inputPath string) { expectedOutputPath := expectedOutputPath(inputPath) if !fileExists(expectedOutputPath) { t.Fatalf("output file doesn't exist: %s", expectedOutputPath) } source, err := readAll(inputPath) if err != nil { t.Fatal(err) } loader := TestLoader{ Dir: path.Dir(inputPath), } output, err := Compile(inputPath, string(source), false, loader) if err != nil { t.Fatal(err) } expectedOutputBytes, err := readAll(expectedOutputPath) if err != nil { t.Fatal(err) } expectedOutput := string(expectedOutputBytes) expectedOutput = cleanOutput(expectedOutput) output = cleanOutput(output) if output != expectedOutput { println("loader.Dir", loader.Dir) println("--------------------output------") println(output) println("--------------------expected----") println(expectedOutput) println("--------------------------------") t.Fatal("expected output does not match output for " + inputPath) } } func fileExists(filename string) bool { fi, err := os.Stat(filename) if os.IsNotExist(err) { return false } if err != nil { panic(err) } if fi.IsDir() { return false } return true } func readAll(fn string) ([]byte, error) { file, err := os.Open(fn) if err != nil { return nil, err } defer file.Close() return ioutil.ReadAll(file) } func expectedOutputPath(inputPath string) string { return path.Join(path.Dir(inputPath), "expected_output.css") } <file_sep>/libsass/sass_functions.cpp #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #include "context.hpp" #include "sass_functions.h" extern "C" { using namespace std; // Struct to hold custom function callback struct Sass_C_Function_Descriptor { const char* signature; Sass_C_Function function; void* cookie; }; Sass_C_Function_List sass_make_function_list(size_t length) { return (Sass_C_Function_List) calloc(length + 1, sizeof(Sass_C_Function_Callback)); } Sass_C_Function_Callback sass_make_function(const char* signature, Sass_C_Function function, void* cookie) { Sass_C_Function_Callback cb = (Sass_C_Function_Callback) calloc(1, sizeof(Sass_C_Function_Descriptor)); if (cb == 0) return 0; cb->signature = signature; cb->function = function; cb->cookie = cookie; return cb; } const char* sass_function_get_signature(Sass_C_Function_Callback fn) { return fn->signature; } Sass_C_Function sass_function_get_function(Sass_C_Function_Callback fn) { return fn->function; } void* sass_function_get_cookie(Sass_C_Function_Callback fn) { return fn->cookie; } // External import entry struct Sass_Import { char* path; char* source; char* srcmap; }; // Struct to hold importer callback struct Sass_C_Import_Descriptor { Sass_C_Import_Fn function; void* cookie; }; Sass_C_Import_Callback sass_make_importer(Sass_C_Import_Fn function, void* cookie) { Sass_C_Import_Callback cb = (Sass_C_Import_Callback) calloc(1, sizeof(Sass_C_Import_Descriptor)); if (cb == 0) return 0; cb->function = function; cb->cookie = cookie; return cb; } Sass_C_Import_Fn sass_import_get_function(Sass_C_Import_Callback fn) { return fn->function; } void* sass_import_get_cookie(Sass_C_Import_Callback fn) { return fn->cookie; } // Creator for sass custom importer return argument list struct Sass_Import** sass_make_import_list(size_t length) { return (Sass_Import**) calloc(length + 1, sizeof(Sass_Import*)); } // Creator for a single import entry returned by the custom importer inside the list // We take ownership of the memory for source and srcmap (freed when context is destroyd) struct Sass_Import* sass_make_import_entry(const char* path, char* source, char* srcmap) { Sass_Import* v = (Sass_Import*) calloc(1, sizeof(Sass_Import)); if (v == 0) return 0; v->path = strdup(path); v->source = source; v->srcmap = srcmap; return v; } // Setters and getters for entries on the import list void sass_import_set_list_entry(struct Sass_Import** list, size_t idx, struct Sass_Import* entry) { list[idx] = entry; } struct Sass_Import* sass_import_get_list_entry(struct Sass_Import** list, size_t idx) { return list[idx]; } // Deallocator for the allocated memory void sass_delete_import_list(struct Sass_Import** list) { struct Sass_Import** it = list; if (list == 0) return; while(*list) { free((*list)->path); free((*list)->source); free((*list)->srcmap); free(*list); ++list; } free(it); } // Getter for import entry const char* sass_import_get_path(struct Sass_Import* entry) { return entry->path; } const char* sass_import_get_source(struct Sass_Import* entry) { return entry->source; } const char* sass_import_get_srcmap(struct Sass_Import* entry) { return entry->srcmap; } // Explicit functions to take ownership of the memory // Resets our own property since we do not know if it is still alive char* sass_import_take_source(struct Sass_Import* entry) { char* ptr = entry->source; entry->source = 0; return ptr; } char* sass_import_take_srcmap(struct Sass_Import* entry) { char* ptr = entry->srcmap; entry->srcmap = 0; return ptr; } } <file_sep>/libsass/sass.cpp #include <cstdlib> #include <cstring> #include <vector> #include <sstream> #include "sass.h" #include "inspect.hpp" extern "C" { using namespace std; // caller must free the returned memory char* sass_string_quote (const char *str, const char quotemark) { string quoted = Sass::quote(str, quotemark); char *cstr = (char*) malloc(quoted.length() + 1); std::strcpy(cstr, quoted.c_str()); return cstr; } // caller must free the returned memory char* sass_string_unquote (const char *str) { string unquoted = Sass::unquote(str); char *cstr = (char*) malloc(unquoted.length() + 1); std::strcpy(cstr, unquoted.c_str()); return cstr; } } <file_sep>/libsass/sass_context.h #ifndef SASS_C_CONTEXT #define SASS_C_CONTEXT #include <stddef.h> #include <stdbool.h> #include "sass.h" #ifdef __cplusplus extern "C" { #endif // Forward declaration struct Sass_Compiler; // Forward declaration struct Sass_Options; struct Sass_Context; // : Sass_Options struct Sass_File_Context; // : Sass_Context struct Sass_Data_Context; // : Sass_Context // Create and initialize an option struct struct Sass_Options* sass_make_options (void); // Create and initialize a specific context struct Sass_File_Context* sass_make_file_context (const char* input_path); struct Sass_Data_Context* sass_make_data_context (char* source_string); // Call the compilation step for the specific context int sass_compile_file_context (struct Sass_File_Context* ctx); int sass_compile_data_context (struct Sass_Data_Context* ctx); // Create a sass compiler instance for more control struct Sass_Compiler* sass_make_file_compiler (struct Sass_File_Context* file_ctx); struct Sass_Compiler* sass_make_data_compiler (struct Sass_Data_Context* data_ctx); // Execute the different compilation steps individually // Usefull if you only want to query the included files int sass_compiler_parse(struct Sass_Compiler* compiler); int sass_compiler_execute(struct Sass_Compiler* compiler); // Release all memory allocated with the compiler // This does _not_ include any contexts or options void sass_delete_compiler(struct Sass_Compiler* compiler); // Release all memory allocated and also ourself void sass_delete_file_context (struct Sass_File_Context* ctx); void sass_delete_data_context (struct Sass_Data_Context* ctx); // Getters for context from specific implementation struct Sass_Context* sass_file_context_get_context (struct Sass_File_Context* file_ctx); struct Sass_Context* sass_data_context_get_context (struct Sass_Data_Context* data_ctx); // Getters for context options from Sass_Context struct Sass_Options* sass_context_get_options (struct Sass_Context* ctx); struct Sass_Options* sass_file_context_get_options (struct Sass_File_Context* file_ctx); struct Sass_Options* sass_data_context_get_options (struct Sass_Data_Context* data_ctx); void sass_file_context_set_options (struct Sass_File_Context* file_ctx, struct Sass_Options* opt); void sass_data_context_set_options (struct Sass_Data_Context* data_ctx, struct Sass_Options* opt); // Getters for options int sass_option_get_precision (struct Sass_Options* options); enum Sass_Output_Style sass_option_get_output_style (struct Sass_Options* options); bool sass_option_get_source_comments (struct Sass_Options* options); bool sass_option_get_source_map_embed (struct Sass_Options* options); bool sass_option_get_source_map_contents (struct Sass_Options* options); bool sass_option_get_omit_source_map_url (struct Sass_Options* options); bool sass_option_get_is_indented_syntax_src (struct Sass_Options* options); const char* sass_option_get_input_path (struct Sass_Options* options); const char* sass_option_get_output_path (struct Sass_Options* options); const char* sass_option_get_image_path (struct Sass_Options* options); const char* sass_option_get_include_path (struct Sass_Options* options); const char* sass_option_get_source_map_file (struct Sass_Options* options); Sass_C_Function_List sass_option_get_c_functions (struct Sass_Options* options); Sass_C_Import_Callback sass_option_get_importer (struct Sass_Options* options); // Setters for options void sass_option_set_precision (struct Sass_Options* options, int precision); void sass_option_set_output_style (struct Sass_Options* options, enum Sass_Output_Style output_style); void sass_option_set_source_comments (struct Sass_Options* options, bool source_comments); void sass_option_set_source_map_embed (struct Sass_Options* options, bool source_map_embed); void sass_option_set_source_map_contents (struct Sass_Options* options, bool source_map_contents); void sass_option_set_omit_source_map_url (struct Sass_Options* options, bool omit_source_map_url); void sass_option_set_is_indented_syntax_src (struct Sass_Options* options, bool is_indented_syntax_src); void sass_option_set_input_path (struct Sass_Options* options, const char* input_path); void sass_option_set_output_path (struct Sass_Options* options, const char* output_path); void sass_option_set_image_path (struct Sass_Options* options, const char* image_path); void sass_option_set_include_path (struct Sass_Options* options, const char* include_path); void sass_option_set_source_map_file (struct Sass_Options* options, const char* source_map_file); void sass_option_set_c_functions (struct Sass_Options* options, Sass_C_Function_List c_functions); void sass_option_set_importer (struct Sass_Options* options, Sass_C_Import_Callback importer); // Getter for context const char* sass_context_get_output_string (struct Sass_Context* ctx); int sass_context_get_error_status (struct Sass_Context* ctx); const char* sass_context_get_error_json (struct Sass_Context* ctx); const char* sass_context_get_error_message (struct Sass_Context* ctx); const char* sass_context_get_error_file (struct Sass_Context* ctx); size_t sass_context_get_error_line (struct Sass_Context* ctx); size_t sass_context_get_error_column (struct Sass_Context* ctx); const char* sass_context_get_source_map_string (struct Sass_Context* ctx); char** sass_context_get_included_files (struct Sass_Context* ctx); // Setters for specific data context option // const char* sass_data_context_get_source_string (struct Sass_Data_Context* ctx); void sass_data_context_set_source_string (struct Sass_Data_Context* ctx, char* source_string); // Push function for include paths (no manipulation support for now) void sass_option_push_include_path (struct Sass_Options* options, const char* path); #ifdef __cplusplus } #endif #endif<file_sep>/libsass/output_nested.cpp #include "output_nested.hpp" #include "inspect.hpp" #include "ast.hpp" #include "context.hpp" #include "to_string.hpp" #include "util.hpp" #include <iostream> #include <sstream> #include <typeinfo> namespace Sass { using namespace std; Output_Nested::Output_Nested(bool source_comments, Context* ctx) : buffer(""), rendered_imports(""), indentation(0), source_comments(source_comments), ctx(ctx) { } Output_Nested::~Output_Nested() { } inline void Output_Nested::fallback_impl(AST_Node* n) { Inspect i(ctx); n->perform(&i); buffer += i.get_buffer(); } void Output_Nested::operator()(Import* imp) { Inspect insp(ctx); imp->perform(&insp); if (!rendered_imports.empty()) { rendered_imports += "\n"; } rendered_imports += insp.get_buffer(); } void Output_Nested::operator()(Block* b) { if (!b->is_root()) return; for (size_t i = 0, L = b->length(); i < L; ++i) { size_t old_len = buffer.length(); (*b)[i]->perform(this); if (i < L-1 && old_len < buffer.length()) append_to_buffer("\n"); } } void Output_Nested::operator()(Ruleset* r) { Selector* s = r->selector(); Block* b = r->block(); bool decls = false; // disabled to avoid clang warning [-Wunused-function] // Selector_List* sl = static_cast<Selector_List*>(s); // Filter out rulesets that aren't printable (process its children though) if (!Util::isPrintable(r)) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } if (b->has_non_hoistable()) { decls = true; indent(); if (source_comments) { stringstream ss; ss << "/* line " << r->position().line << ", " << r->path() << " */" << endl; append_to_buffer(ss.str()); indent(); } s->perform(this); append_to_buffer(" {\n"); ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; bool bPrintExpression = true; // Check print conditions if (typeid(*stm) == typeid(Declaration)) { Declaration* dec = static_cast<Declaration*>(stm); if (dec->value()->concrete_type() == Expression::STRING) { String_Constant* valConst = static_cast<String_Constant*>(dec->value()); string val(valConst->value()); if (val.empty()) { bPrintExpression = false; } } else if (dec->value()->concrete_type() == Expression::LIST) { List* list = static_cast<List*>(dec->value()); bool all_invisible = true; for (size_t list_i = 0, list_L = list->length(); list_i < list_L; ++list_i) { Expression* item = (*list)[list_i]; if (!item->is_invisible()) all_invisible = false; } if (all_invisible) bPrintExpression = false; } } // Print if OK if (!stm->is_hoistable() && bPrintExpression) { if (!stm->block()) indent(); stm->perform(this); append_to_buffer("\n"); } } --indentation; buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); append_to_buffer(" }\n"); } if (b->has_hoistable()) { if (decls) ++indentation; // indent(); for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } if (decls) --indentation; } } void Output_Nested::operator()(Feature_Block* f) { Feature_Query* q = f->feature_queries(); Block* b = f->block(); // Filter out feature blocks that aren't printable (process its children though) if (!Util::isPrintable(f)) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } indent(); ctx->source_map.add_mapping(f); append_to_buffer("@supports "); q->perform(this); append_to_buffer(" {\n"); Selector* e = f->selector(); if (e && b->has_non_hoistable()) { // JMA - hoisted, output the non-hoistable in a nested block, followed by the hoistable ++indentation; indent(); e->perform(this); append_to_buffer(" {\n"); ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { if (!stm->block()) indent(); stm->perform(this); append_to_buffer("\n"); } } --indentation; buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); append_to_buffer(" }\n"); --indentation; ++indentation; ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } --indentation; --indentation; } else { // JMA - not hoisted, just output in order ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { if (!stm->block()) indent(); } stm->perform(this); if (!stm->is_hoistable()) append_to_buffer("\n"); } --indentation; } buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); append_to_buffer(" }\n"); } void Output_Nested::operator()(Media_Block* m) { List* q = m->media_queries(); Block* b = m->block(); // Filter out media blocks that aren't printable (process its children though) if (!Util::isPrintable(m)) { for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { stm->perform(this); } } return; } indent(); ctx->source_map.add_mapping(m); append_to_buffer("@media "); q->perform(this); append_to_buffer(" {\n"); Selector* e = m->selector(); if (e && b->has_non_hoistable()) { // JMA - hoisted, output the non-hoistable in a nested block, followed by the hoistable ++indentation; indent(); e->perform(this); append_to_buffer(" {\n"); ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { if (!stm->block()) indent(); stm->perform(this); append_to_buffer("\n"); } } --indentation; buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); append_to_buffer(" }\n"); --indentation; ++indentation; ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); } } --indentation; --indentation; } else { // JMA - not hoisted, just output in order ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { if (!stm->block()) indent(); } stm->perform(this); if (!stm->is_hoistable()) append_to_buffer("\n"); } --indentation; } buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); append_to_buffer(" }\n"); } void Output_Nested::operator()(At_Rule* a) { string kwd = a->keyword(); Selector* s = a->selector(); Expression* v = a->value(); Block* b = a->block(); bool decls = false; // indent(); append_to_buffer(kwd); if (s) { append_to_buffer(" "); s->perform(this); } else if (v) { append_to_buffer(" "); v->perform(this); } if (!b) { append_to_buffer(";"); return; } append_to_buffer(" {\n"); ++indentation; decls = true; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable()) { if (!stm->block()) indent(); stm->perform(this); append_to_buffer("\n"); } } --indentation; if (decls) ++indentation; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (stm->is_hoistable()) { stm->perform(this); append_to_buffer("\n"); } } if (decls) --indentation; buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); if (b->has_hoistable()) { buffer.erase(buffer.length()-1); if (ctx) ctx->source_map.remove_line(); } append_to_buffer(" }\n"); } void Output_Nested::indent() { append_to_buffer(string(2*indentation, ' ')); } void Output_Nested::append_to_buffer(const string& text) { buffer += text; if (ctx && !ctx->_skip_source_map_update) ctx->source_map.update_column(text); } } <file_sep>/libsass/Makefile.am ACLOCAL_AMFLAGS = -I m4 AM_CFLAGS = -Wall -fPIC AM_CXXFLAGS = -Wall -fPIC if ENABLE_COVERAGE AM_CFLAGS += -O0 --coverage AM_CXXFLAGS += -O0 --coverage else AM_CFLAGS += -O2 AM_CXXFLAGS += -O2 endif pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = support/libsass.pc lib_LTLIBRARIES = libsass.la libsass_la_SOURCES = \ cencode.c \ ast.cpp \ base64vlq.cpp \ bind.cpp \ constants.cpp \ context.cpp \ contextualize.cpp \ copy_c_str.cpp \ error_handling.cpp \ eval.cpp \ expand.cpp \ extend.cpp \ file.cpp \ functions.cpp \ inspect.cpp \ node.cpp \ json.cpp \ output_compressed.cpp \ output_nested.cpp \ parser.cpp \ prelexer.cpp \ remove_placeholders.cpp \ sass.cpp \ sass_util.cpp \ sass_values.cpp \ sass_context.cpp \ sass_functions.cpp \ sass_interface.cpp \ sass2scss.cpp \ source_map.cpp \ to_c.cpp \ to_string.cpp \ units.cpp \ utf8_string.cpp \ util.cpp libsass_la_CXXFLAGS = $(AM_CXXFLAGS) -std=c++0x libsass_la_LDFLAGS = -no-undefined -version-info 0:9:0 if ENABLE_COVERAGE libsass_la_LDFLAGS += -lgcov endif include_HEADERS = sass2scss.h sass_context.h sass_functions.h sass_values.h sass.h if ENABLE_TESTS noinst_PROGRAMS = sass-tester sass_tester_SOURCES = $(SASS_SASSC_PATH)/sassc.c sass_tester_LDADD = libsass.la sass_tester_LDFLAGS = -no-install if ENABLE_COVERAGE sass_tester_LDFLAGS += -lgcov nodist_EXTRA_sass_tester_SOURCES = non-existent-file-to-force-CXX-linking.cxx endif TESTS = \ $(SASS_SPEC_PATH)/spec/basic \ $(SASS_SPEC_PATH)/spec/benchmarks \ $(SASS_SPEC_PATH)/spec/bourbon \ $(SASS_SPEC_PATH)/spec/libsass \ $(SASS_SPEC_PATH)/spec/scss \ $(SASS_SPEC_PATH)/spec/todo LOG_COMPILER = $(RUBY) $(SASS_SPEC_PATH)/sass-spec.rb AM_LOG_FLAGS = -c ./sass-tester SASS_SASSC_PATH ?= sassc SASS_SPEC_PATH ?= sass-spec SASSC_BIN = $(SASS_SASSC_PATH)/bin/sassc RUBY_BIN = ruby $(SASSC_BIN): libsass.la cd $(SASS_SASSC_PATH) && $(MAKE) test: $(SASSC_BIN) $(RUBY_BIN) $(SASS_SPEC_PATH)/sass-spec.rb -c $(SASSC_BIN) -s $(LOG_FLAGS) $(SASS_SPEC_PATH) test_build: $(SASSC_BIN) $(RUBY_BIN) $(SASS_SPEC_PATH)/sass-spec.rb -c $(SASSC_BIN) -s --ignore-todo $(LOG_FLAGS) $(SASS_SPEC_PATH) test_issues: $(SASSC_BIN) $(RUBY_BIN) $(SASS_SPEC_PATH)/sass-spec.rb -c $(SASSC_BIN) $(LOG_FLAGS) $(SASS_SPEC_PATH)/spec/issues endif <file_sep>/import_cb.c #include "_cgo_export.h" #include <sass_context.h> #include <stdlib.h> #include <stdio.h> struct Sass_Import** import_cb(const char* parentPath, const char* importPath, void* cookie) { void* import_entries_ptr = go_import_cb((char*)parentPath, (char*)importPath, cookie); struct Sass_Import** imports = (struct Sass_Import**)(import_entries_ptr); return imports; } struct Sass_Data_Context* new_context(char* input_path, char* source, int compress, void* cookie) { struct Sass_Data_Context* data_context = sass_make_data_context(source); struct Sass_Context* context = sass_data_context_get_context(data_context); struct Sass_Options* options = sass_context_get_options(context); // SASS_STYLE_NESTED // SASS_STYLE_EXPANDED // SASS_STYLE_COMPACT // SASS_STYLE_COMPRESSED if (compress != 0) { sass_option_set_output_style(options, SASS_STYLE_COMPRESSED); } sass_option_set_input_path(options, input_path); Sass_C_Import_Callback importer = sass_make_importer(import_cb, cookie); sass_option_set_importer(options, importer); return data_context; } <file_sep>/libsass/prelexer.hpp #define SASS_PRELEXER namespace Sass { namespace Prelexer { typedef int (*ctype_predicate)(int); typedef const char* (*prelexer)(const char*); // Match a single character literal. template <char pre> const char* exactly(const char* src) { return *src == pre ? src + 1 : 0; } // Match a string constant. template <const char* prefix> const char* exactly(const char* src) { const char* pre = prefix; while (*pre && *src == *pre) ++src, ++pre; return *pre ? 0 : src; } // Match a single character that satifies the supplied ctype predicate. template <ctype_predicate pred> const char* class_char(const char* src) { return pred(*src) ? src + 1 : 0; } // Match a single character that is a member of the supplied class. template <const char* char_class> const char* class_char(const char* src) { const char* cc = char_class; while (*cc && *src != *cc) ++cc; return *cc ? src + 1 : 0; } // Match a sequence of characters that all satisfy the supplied ctype predicate. template <ctype_predicate pred> const char* class_chars(const char* src) { const char* p = src; while (pred(*p)) ++p; return p == src ? 0 : p; } // Match a sequence of characters that are all members of the supplied class. template <const char* char_class> const char* class_chars(const char* src) { const char* p = src; while (class_char<char_class>(p)) ++p; return p == src ? 0 : p; } // Match a sequence of characters up to the next newline. template <const char* prefix> const char* to_endl(const char* src) { if (!(src = exactly<prefix>(src))) return 0; while (*src && *src != '\n') ++src; return src; } // Match a sequence of characters delimited by the supplied chars. template <char beg, char end, bool esc> const char* delimited_by(const char* src) { src = exactly<beg>(src); if (!src) return 0; const char* stop; while (1) { if (!*src) return 0; stop = exactly<end>(src); if (stop && (!esc || *(src - 1) != '\\')) return stop; src = stop ? stop : src + 1; } } // Match a sequence of characters delimited by the supplied strings. template <const char* beg, const char* end, bool esc> const char* delimited_by(const char* src) { src = exactly<beg>(src); if (!src) return 0; const char* stop; while (1) { if (!*src) return 0; stop = exactly<end>(src); if (stop && (!esc || *(src - 1) != '\\')) return stop; src = stop ? stop : src + 1; } } // Match any single character. const char* any_char(const char* src); // Match any single character except the supplied one. template <char c> const char* any_char_except(const char* src) { return (*src && *src != c) ? src+1 : 0; } // Matches zero characters (always succeeds without consuming input). const char* epsilon(const char*); // Matches the empty string. const char* empty(const char*); // Succeeds of the supplied matcher fails, and vice versa. template <prelexer mx> const char* negate(const char* src) { return mx(src) ? 0 : src; } // Tries to match a certain number of times (between the supplied interval). template<prelexer mx, size_t lo, size_t hi> const char* between(const char* src) { for (size_t i = 0; i < lo; ++i) { src = mx(src); if (!src) return 0; } for (size_t i = lo; i <= hi; ++i) { const char* new_src = mx(src); if (!new_src) return src; src = new_src; } return src; } // Tries the matchers in sequence and returns the first match (or none) template <prelexer mx1, prelexer mx2> const char* alternatives(const char* src) { const char* rslt; (rslt = mx1(src)) || (rslt = mx2(src)); return rslt; } // Same as above, but with 3 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3> const char* alternatives(const char* src) { const char* rslt; (rslt = mx1(src)) || (rslt = mx2(src)) || (rslt = mx3(src)); return rslt; } // Same as above, but with 4 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4> const char* alternatives(const char* src) { const char* rslt; (rslt = mx1(src)) || (rslt = mx2(src)) || (rslt = mx3(src)) || (rslt = mx4(src)); return rslt; } // Same as above, but with 5 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5> const char* alternatives(const char* src) { const char* rslt; (rslt = mx1(src)) || (rslt = mx2(src)) || (rslt = mx3(src)) || (rslt = mx4(src)) || (rslt = mx5(src)); return rslt; } // Same as above, but with 6 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5, prelexer mx6> const char* alternatives(const char* src) { const char* rslt; (rslt = mx1(src)) || (rslt = mx2(src)) || (rslt = mx3(src)) || (rslt = mx4(src)) || (rslt = mx5(src)) || (rslt = mx6(src)); return rslt; } // Same as above, but with 7 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5, prelexer mx6, prelexer mx7> const char* alternatives(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) || (rslt = mx2(rslt)) || (rslt = mx3(rslt)) || (rslt = mx4(rslt)) || (rslt = mx5(rslt)) || (rslt = mx6(rslt)) || (rslt = mx7(rslt)); return rslt; } // Same as above, but with 8 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5, prelexer mx6, prelexer mx7, prelexer mx8> const char* alternatives(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) || (rslt = mx2(rslt)) || (rslt = mx3(rslt)) || (rslt = mx4(rslt)) || (rslt = mx5(rslt)) || (rslt = mx6(rslt)) || (rslt = mx7(rslt)) || (rslt = mx8(rslt)); return rslt; } // Tries the matchers in sequence and succeeds if they all succeed. template <prelexer mx1, prelexer mx2> const char* sequence(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) && (rslt = mx2(rslt)); return rslt; } // Same as above, but with 3 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3> const char* sequence(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) && (rslt = mx2(rslt)) && (rslt = mx3(rslt)); return rslt; } // Same as above, but with 4 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4> const char* sequence(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) && (rslt = mx2(rslt)) && (rslt = mx3(rslt)) && (rslt = mx4(rslt)); return rslt; } // Same as above, but with 5 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5> const char* sequence(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) && (rslt = mx2(rslt)) && (rslt = mx3(rslt)) && (rslt = mx4(rslt)) && (rslt = mx5(rslt)); return rslt; } // Same as above, but with 6 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5, prelexer mx6> const char* sequence(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) && (rslt = mx2(rslt)) && (rslt = mx3(rslt)) && (rslt = mx4(rslt)) && (rslt = mx5(rslt)) && (rslt = mx6(rslt)); return rslt; } // Same as above, but with 7 arguments. template <prelexer mx1, prelexer mx2, prelexer mx3, prelexer mx4, prelexer mx5, prelexer mx6, prelexer mx7> const char* sequence(const char* src) { const char* rslt = src; (rslt = mx1(rslt)) && (rslt = mx2(rslt)) && (rslt = mx3(rslt)) && (rslt = mx4(rslt)) && (rslt = mx5(rslt)) && (rslt = mx6(rslt)) && (rslt = mx7(rslt)); return rslt; } // Match a pattern or not. Always succeeds. template <prelexer mx> const char* optional(const char* src) { const char* p = mx(src); return p ? p : src; } // Match zero or more of the supplied pattern template <prelexer mx> const char* zero_plus(const char* src) { const char* p = mx(src); while (p) src = p, p = mx(src); return src; } // Match one or more of the supplied pattern template <prelexer mx> const char* one_plus(const char* src) { const char* p = mx(src); if (!p) return 0; while (p) src = p, p = mx(src); return src; } // Match a single character satisfying the ctype predicates. const char* space(const char* src); const char* alpha(const char* src); const char* digit(const char* src); const char* xdigit(const char* src); const char* alnum(const char* src); const char* punct(const char* src); // Match multiple ctype characters. const char* spaces(const char* src); const char* alphas(const char* src); const char* digits(const char* src); const char* xdigits(const char* src); const char* alnums(const char* src); const char* puncts(const char* src); // Match a line comment. const char* line_comment(const char* src); const char* line_comment_prefix(const char* src); // Match a block comment. const char* block_comment(const char* src); const char* block_comment_prefix(const char* src); // Match either. const char* comment(const char* src); // Match double- and single-quoted strings. const char* double_quoted_string(const char* src); const char* single_quoted_string(const char* src); const char* string_constant(const char* src); // Match interpolants. const char* interpolant(const char* src); // Whitespace handling. const char* optional_spaces(const char* src); const char* optional_comment(const char* src); const char* spaces_and_comments(const char* src); const char* no_spaces(const char* src); const char* backslash_something(const char* src); // Match CSS css variables. const char* custom_property_name(const char* src); // Match a CSS identifier. const char* identifier(const char* src); // Match selector names. const char* sel_ident(const char* src); // Match interpolant schemas const char* identifier_schema(const char* src); const char* value_schema(const char* src); const char* filename(const char* src); const char* filename_schema(const char* src); const char* url_schema(const char* src); const char* url_value(const char* src); const char* vendor_prefix(const char* src); // Match CSS '@' keywords. const char* at_keyword(const char* src); const char* import(const char* src); const char* media(const char* src); const char* supports(const char* src); const char* keyframes(const char* src); const char* keyf(const char* src); const char* mixin(const char* src); const char* function(const char* src); const char* return_directive(const char* src); const char* include(const char* src); const char* content(const char* src); const char* extend(const char* src); const char* if_directive(const char* src); const char* else_directive(const char* src); const char* elseif_directive(const char* src); const char* for_directive(const char* src); const char* from(const char* src); const char* to(const char* src); const char* through(const char* src); const char* each_directive(const char* src); const char* in(const char* src); const char* while_directive(const char* src); const char* warn(const char* src); const char* directive(const char* src); const char* at_keyword(const char* src); const char* null(const char* src); // Match CSS type selectors const char* namespace_prefix(const char* src); const char* type_selector(const char* src); const char* hyphens_and_identifier(const char* src); const char* hyphens_and_name(const char* src); const char* universal(const char* src); // Match CSS id names. const char* id_name(const char* src); // Match CSS class names. const char* class_name(const char* src); // Attribute name in an attribute selector const char* attribute_name(const char* src); // Match placeholder selectors. const char* placeholder(const char* src); // Match CSS numeric constants. const char* sign(const char* src); const char* unsigned_number(const char* src); const char* number(const char* src); const char* coefficient(const char* src); const char* binomial(const char* src); const char* percentage(const char* src); const char* dimension(const char* src); const char* hex(const char* src); const char* rgb_prefix(const char* src); // Match CSS uri specifiers. const char* uri_prefix(const char* src); const char* uri(const char* src); const char* url(const char* src); // Match CSS "!important" keyword. const char* important(const char* src); // Match CSS "!optional" keyword. const char* optional(const char* src); // Match Sass "!default" keyword. const char* default_flag(const char* src); const char* global_flag(const char* src); // Match CSS pseudo-class/element prefixes const char* pseudo_prefix(const char* src); // Match CSS function call openers. const char* functional(const char* src); const char* functional_schema(const char* src); const char* pseudo_not(const char* src); // Match CSS 'odd' and 'even' keywords for functional pseudo-classes. const char* even(const char* src); const char* odd(const char* src); // Match CSS attribute-matching operators. const char* exact_match(const char* src); const char* class_match(const char* src); const char* dash_match(const char* src); const char* prefix_match(const char* src); const char* suffix_match(const char* src); const char* substring_match(const char* src); // Match CSS combinators. const char* adjacent_to(const char* src); const char* precedes(const char* src); const char* parent_of(const char* src); const char* ancestor_of(const char* src); // Match SCSS variable names. const char* variable(const char* src); // Match Sass boolean keywords. const char* true_val(const char* src); const char* false_val(const char* src); const char* and_op(const char* src); const char* or_op(const char* src); const char* not_op(const char* src); const char* eq_op(const char* src); const char* neq_op(const char* src); const char* gt_op(const char* src); const char* gte_op(const char* src); const char* lt_op(const char* src); const char* lte_op(const char* src); // IE stuff const char* ie_stuff(const char* src); const char* ie_args(const char* src); const char* ie_keyword_arg(const char* src); // match urls const char* url(const char* src); // Path matching functions. const char* folder(const char* src); const char* folders(const char* src); // Utility functions for finding and counting characters in a string. template<char c> const char* find_first(const char* src) { while (*src && *src != c) ++src; return *src ? src : 0; } template<prelexer mx> const char* find_first(const char* src) { while (*src && !mx(src)) ++src; return *src ? src : 0; } template<prelexer mx> const char* find_first_in_interval(const char* beg, const char* end) { while ((beg < end) && *beg) { if (mx(beg)) return beg; ++beg; } return 0; } template <char c> unsigned int count_interval(const char* beg, const char* end) { unsigned int counter = 0; while (beg < end && *beg) { if (*beg == c) ++counter; ++beg; } return counter; } template <prelexer mx> unsigned int count_interval(const char* beg, const char* end) { unsigned int counter = 0; while (beg < end && *beg) { const char* p; if ((p = mx(beg))) { ++counter; beg = p; } else { ++beg; } } return counter; } const char* chunk(const char* src); } } <file_sep>/libsass/util.cpp #include "util.hpp" namespace Sass { namespace Util { using std::string; string normalize_underscores(const string& str) { string normalized = str; for(size_t i = 0, L = normalized.length(); i < L; ++i) { if(normalized[i] == '_') { normalized[i] = '-'; } } return normalized; } bool isPrintable(Ruleset* r) { if (r == NULL) { return false; } Block* b = r->block(); bool hasSelectors = static_cast<Selector_List*>(r->selector())->length() > 0; if (!hasSelectors) { return false; } bool hasDeclarations = false; bool hasPrintableChildBlocks = false; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (dynamic_cast<Has_Block*>(stm)) { Block* pChildBlock = ((Has_Block*)stm)->block(); if (isPrintable(pChildBlock)) { hasPrintableChildBlocks = true; } } else { hasDeclarations = true; } if (hasDeclarations || hasPrintableChildBlocks) { return true; } } return false; } bool isPrintable(Feature_Block* f) { if (f == NULL) { return false; } Block* b = f->block(); bool hasSelectors = f->selector() && static_cast<Selector_List*>(f->selector())->length() > 0; bool hasDeclarations = false; bool hasPrintableChildBlocks = false; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable() && f->selector() != NULL && !hasSelectors) { // If a statement isn't hoistable, the selectors apply to it. If there are no selectors (a selector list of length 0), // then those statements aren't considered printable. That means there was a placeholder that was removed. If the selector // is NULL, then that means there was never a wrapping selector and it is printable (think of a top level media block with // a declaration in it). } else if (typeid(*stm) == typeid(Declaration) || typeid(*stm) == typeid(At_Rule)) { hasDeclarations = true; } else if (dynamic_cast<Has_Block*>(stm)) { Block* pChildBlock = ((Has_Block*)stm)->block(); if (isPrintable(pChildBlock)) { hasPrintableChildBlocks = true; } } if (hasDeclarations || hasPrintableChildBlocks) { return true; } } return false; } bool isPrintable(Media_Block* m) { if (m == NULL) { return false; } Block* b = m->block(); bool hasSelectors = m->selector() && static_cast<Selector_List*>(m->selector())->length() > 0; bool hasDeclarations = false; bool hasPrintableChildBlocks = false; for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (!stm->is_hoistable() && m->selector() != NULL && !hasSelectors) { // If a statement isn't hoistable, the selectors apply to it. If there are no selectors (a selector list of length 0), // then those statements aren't considered printable. That means there was a placeholder that was removed. If the selector // is NULL, then that means there was never a wrapping selector and it is printable (think of a top level media block with // a declaration in it). } else if (typeid(*stm) == typeid(Declaration) || typeid(*stm) == typeid(At_Rule)) { hasDeclarations = true; } else if (dynamic_cast<Has_Block*>(stm)) { Block* pChildBlock = ((Has_Block*)stm)->block(); if (isPrintable(pChildBlock)) { hasPrintableChildBlocks = true; } } if (hasDeclarations || hasPrintableChildBlocks) { return true; } } return false; } bool isPrintable(Block* b) { if (b == NULL) { return false; } for (size_t i = 0, L = b->length(); i < L; ++i) { Statement* stm = (*b)[i]; if (typeid(*stm) == typeid(Declaration) || typeid(*stm) == typeid(At_Rule)) { return true; } else if (typeid(*stm) == typeid(Ruleset)) { Ruleset* r = (Ruleset*) stm; if (isPrintable(r)) { return true; } } else if (typeid(*stm) == typeid(Feature_Block)) { Feature_Block* f = (Feature_Block*) stm; if (isPrintable(f)) { return true; } } else if (typeid(*stm) == typeid(Media_Block)) { Media_Block* m = (Media_Block*) stm; if (isPrintable(m)) { return true; } } else if (dynamic_cast<Has_Block*>(stm) && isPrintable(((Has_Block*)stm)->block())) { return true; } } return false; } bool isAscii(int ch) { return ch >= 0 && ch < 128; } } } <file_sep>/Makefile host := $(shell go env GOHOSTOS) ifeq ($(host),darwin) ldflags = -lc++ else ldflags = -lm -lstdc++ endif # We use pkg-config so that we can use absolute paths to the libsass directory # that don't need to be hard coded in the scss.go file. It would be nice if # the cgo macros in go had some sort of current directory variable. This would # eliminiate the need to do this. define PKG_CONFIG_BODY Name: scss.go Version: 0.0.1 Description: scss.go Cflags: -g -I$(PWD)/libsass Libs: $(ldflags) $(PWD)/libsass/lib/libsass.a endef # why am i exporting this variable? see # http://stackoverflow.com/questions/649246/is-it-possible-to-create-a-multi-line-string-variable-in-a-makefile export PKG_CONFIG_BODY install: libsass/lib/libsass.a *.go scss.pc go install scss.pc: echo "$$PKG_CONFIG_BODY" > scss.pc libsass/lib/libsass.a: libsass/*.cpp libsass/*.hpp libsass/*.h $(MAKE) -C ./libsass scss.go.test: libsass/lib/libsass.a *.go *.c scss.pc go test -c test: scss.go.test ./scss.go.test clean: $(MAKE) -C ./libsass clean rm -f scss.go.test scss.pc .PHONY: install test clean <file_sep>/libsass/sass_values.h #ifndef SASS_C_VALUES #define SASS_C_VALUES #include <stddef.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif // Forward declaration union Sass_Value; // Type for Sass values enum Sass_Tag { SASS_BOOLEAN, SASS_NUMBER, SASS_COLOR, SASS_STRING, SASS_LIST, SASS_MAP, SASS_NULL, SASS_ERROR }; // Tags for denoting Sass list separators enum Sass_Separator { SASS_COMMA, SASS_SPACE }; // Return the sass tag for a generic sass value // Check is needed before accessing specific values! enum Sass_Tag sass_value_get_tag (union Sass_Value* v); // Check value to be of a specific type // Can also be used before accessing properties! bool sass_value_is_null (union Sass_Value* v); bool sass_value_is_number (union Sass_Value* v); bool sass_value_is_string (union Sass_Value* v); bool sass_value_is_boolean (union Sass_Value* v); bool sass_value_is_color (union Sass_Value* v); bool sass_value_is_list (union Sass_Value* v); bool sass_value_is_map (union Sass_Value* v); bool sass_value_is_error (union Sass_Value* v); // Getters and setters for Sass_Number double sass_number_get_value (union Sass_Value* v); void sass_number_set_value (union Sass_Value* v, double value); const char* sass_number_get_unit (union Sass_Value* v); void sass_number_set_unit (union Sass_Value* v, char* unit); // Getters and setters for Sass_String const char* sass_string_get_value (union Sass_Value* v); void sass_string_set_value (union Sass_Value* v, char* value); // Getters and setters for Sass_Boolean bool sass_boolean_get_value (union Sass_Value* v); void sass_boolean_set_value (union Sass_Value* v, bool value); // Getters and setters for Sass_Color double sass_color_get_r (union Sass_Value* v); void sass_color_set_r (union Sass_Value* v, double r); double sass_color_get_g (union Sass_Value* v); void sass_color_set_g (union Sass_Value* v, double g); double sass_color_get_b (union Sass_Value* v); void sass_color_set_b (union Sass_Value* v, double b); double sass_color_get_a (union Sass_Value* v); void sass_color_set_a (union Sass_Value* v, double a); // Getter for the number of items in list size_t sass_list_get_length (union Sass_Value* v); // Getters and setters for Sass_List enum Sass_Separator sass_list_get_separator (union Sass_Value* v); void sass_list_set_separator (union Sass_Value* v, enum Sass_Separator value); // Getters and setters for Sass_List values union Sass_Value* sass_list_get_value (union Sass_Value* v, size_t i); void sass_list_set_value (union Sass_Value* v, size_t i, union Sass_Value* value); // Getter for the number of items in map size_t sass_map_get_length (union Sass_Value* v); // Getters and setters for Sass_List keys and values union Sass_Value* sass_map_get_key (union Sass_Value* v, size_t i); void sass_map_set_key (union Sass_Value* v, size_t i, union Sass_Value*); union Sass_Value* sass_map_get_value (union Sass_Value* v, size_t i); void sass_map_set_value (union Sass_Value* v, size_t i, union Sass_Value*); // Getters and setters for Sass_Error char* sass_error_get_message (union Sass_Value* v); void sass_error_set_message (union Sass_Value* v, char* msg); // Creator functions for all value types union Sass_Value* sass_make_null (void); union Sass_Value* sass_make_boolean (bool val); union Sass_Value* sass_make_string (const char* val); union Sass_Value* sass_make_number (double val, const char* unit); union Sass_Value* sass_make_color (double r, double g, double b, double a); union Sass_Value* sass_make_list (size_t len, enum Sass_Separator sep); union Sass_Value* sass_make_map (size_t len); union Sass_Value* sass_make_error (const char* msg); // Generic destructor function for all types // Will release memory of all associated Sass_Values // Means we will delete recursively for lists and maps void sass_delete_value (union Sass_Value* val); #ifdef __cplusplus } #endif #endif<file_sep>/spec/lib/sass_spec/runner.rb require 'minitest' require 'pathname' require_relative 'test' require_relative 'test_case' class SassSpec::Runner def initialize(options = {}) @options = options end def run unless @options[:silent] puts "Recursively searching under directory '#{@options[:spec_directory]}' for test files to test '#{@options[:sass_executable]}' with." stdout, stderr, status = Open3.capture3("#{@options[:sass_executable]} -v") puts stdout end test_cases = _get_cases SassSpec::Test.create_tests(test_cases, @options) minioptions = [] if @options[:verbose] minioptions.push '--verbose' end exit Minitest.run(minioptions) end def _get_cases cases = [] glob = File.join(@options[:spec_directory], "**", "#{@options[:input_file]}") Dir.glob(glob) do |filename| expected = Pathname.new(filename).dirname.join(@options[:expected_file]) input = Pathname.new(filename) if filename.include?(@options[:filter]) cases.push SassSpec::TestCase.new(input.realpath(), expected.realpath(), @options) end end cases end end <file_sep>/spec/lib/sass_spec/cli.rb module SassSpec::CLI require 'optparse' def self.parse options = { sass_executable: "sass", spec_directory: "spec", skip: false, verbose: false, filter: "", limit: -1, unexpected_pass: false, # Constants input_file: 'input.scss', expected_file: 'expected_output.css' } OptionParser.new do |opts| opts.banner = "Usage: ./sass-spec.rb [options] Examples: Run `sassc --style compressed input.scss`: ./sass-spec.rb -c 'sass --style compressed' Run tests only in the spec/basic folder: ./sass-spec.rb spec/basic This script will search for all files under the spec (or specified) directory that are named input.scss. It will then run a specified binary and check that the output matches the expected output. If you want set up your own test suite, follow a similar hierarchy as described in the initial comment of this script for your test hierarchy. Make sure the command you provide prints to stdout. " opts.on("-v", "--verbose", "Run verbosely") do options[:verbose] = true end opts.on("-c", "--command COMMAND", "Sets a specific binary to run (defaults to '#{options[:sass_executable]}')") do |v| options[:sass_executable] = v end opts.on("--ignore-todo", "Skip any folder named 'todo'") do options[:skip_todo] = true end opts.on("--filter PATTERN", "Run tests that match the pattern you provide") do |pattern| options[:filter] = pattern end opts.on("--limit NUMBER", "Limit the number of tests run to this positive integer.") do |limit| options[:limit] = limit.to_i end opts.on("-s", "--skip", "Skip tests that fail to exit successfully") do options[:skip] = true end opts.on("--unexpected-pass", "When running the todo tests, flag as an error when a test passes which is marked as todo.") do options[:unexpected_pass] = true end opts.on("--silent", "Don't show any logs") do options[:silent] = true end end.parse! options[:spec_directory] = ARGV[0] if !ARGV.empty? options end end <file_sep>/scss.go package scss /* #cgo pkg-config: scss.pc #include <sass.h> #include <sass_context.h> #include <stdlib.h> // Defined in import_cb.c struct Sass_Data_Context* new_context(char* input_path, char* source, int compress, void* cookie); */ import "C" import ( "errors" "math/rand" "path" "unsafe" ) type Import struct { Path string Source string // leave blank if import should be passed to css //Map string } type Loader interface { Load(parentPath string, importPath string) Import } // This is our internal context type internalContext struct { name string loader Loader cContext *C.struct_Sass_Context } //export go_import_cb func go_import_cb(parentPath_s *C.char, importPath_s *C.char, cookie unsafe.Pointer) **C.struct_Sass_Import { iContext := (*internalContext)(cookie) // For some reason the importPath_s comes in quoted. unquoted_importPath := C.sass_string_unquote(importPath_s) defer C.free(unsafe.Pointer(unquoted_importPath)) importPath := C.GoString(unquoted_importPath) unquoted_parentPath := C.sass_string_unquote(parentPath_s) defer C.free(unsafe.Pointer(unquoted_parentPath)) parentPath := C.GoString(unquoted_parentPath) /* options := C.sass_context_get_options(iContext.cContext) outputPath_s := C.sass_option_get_output_path(options) outputPath := C.GoString(outputPath_s) println("outputPath", outputPath) */ //println(">>>>>>> before", parentPath, importPath) //println(">>>>>>> loader:", string(iContext.name)) import_ := iContext.loader.Load(parentPath, importPath) //println("<<<<<<< after", parentPath, importPath) // Copy The golang []Import object into something sass understands. c_imports := C.sass_make_import_list(C.size_t(1)) path_s := C.CString(import_.Path) // This is so source_s will be NULL. which triggers direct imports??? var source_s *C.char if len(import_.Source) > 0 { source_s = C.CString(import_.Source) } entry := C.sass_make_import_entry(path_s, source_s, nil) C.sass_import_set_list_entry(c_imports, 0, entry) // Who owns what? sass has a shitty API C.free(unsafe.Pointer(path_s)) //C.free(unsafe.Pointer(source_s)) return c_imports } // Returns scss files that this could refer to. // this issues no syscalls. func PossiblePaths(p string) (out []string) { ext := path.Ext(p) if ext == ".css" { return nil } else if ext == "" { out = make([]string, 2) out[0] = path.Join(path.Dir(p), "_"+path.Base(p)+".scss") out[1] = p + ".scss" } else if ext == ".scss" { out = make([]string, 1) out[0] = p } else { panic("uhh") } return out } var sassContextMap = make(map[int32]*internalContext) func Compile(inputPath string, source string, compress bool, loader Loader) (string, error) { input_path_s := C.CString(inputPath) defer C.free(unsafe.Pointer(input_path_s)) source_s := C.CString(source) defer C.free(unsafe.Pointer(source_s)) // This is to work around a crash I was hitting where // the internalContext would be GCed (I think) while we are // inside of sass_compile_data_context, despite the object // being rooted in this scope. // It seems attaching it to this global map fixes the bug? sassContextId := rand.Int31() sassContextMap[sassContextId] = &internalContext{ name: inputPath, loader: loader, } defer delete(sassContextMap, sassContextId) iContext := sassContextMap[sassContextId] cookie := unsafe.Pointer(iContext) var compress_c C.int if compress { compress_c = 1 } else { compress_c = 0 } data_context := C.new_context(input_path_s, source_s, compress_c, cookie) defer C.sass_delete_data_context(data_context) context := C.sass_data_context_get_context(data_context) iContext.cContext = context C.sass_compile_data_context(data_context) status := C.sass_context_get_error_status(context) if status == 0 { output_s := C.sass_context_get_output_string(context) output := C.GoString(output_s) return output, nil } else { // error /* error_json_s := C.sass_context_get_error_json(context) error_json := C.GoString(error_json_s) //println("error json", error_json) */ error_message_s := C.sass_context_get_error_message(context) error_message := C.GoString(error_message_s) //println("error message", error_message) return "", errors.New(error_message) } } <file_sep>/libsass/inspect.cpp #include "inspect.hpp" #include "ast.hpp" #include "context.hpp" #include <cmath> #include <iostream> #include <iomanip> namespace Sass { using namespace std; Inspect::Inspect(Context* ctx) : buffer(""), indentation(0), ctx(ctx) { } Inspect::~Inspect() { } // statements void Inspect::operator()(Block* block) { if (!block->is_root()) { append_to_buffer(" {\n"); ++indentation; } for (size_t i = 0, L = block->length(); i < L; ++i) { indent(); (*block)[i]->perform(this); // extra newline at the end of top-level statements if (block->is_root()) append_to_buffer("\n"); append_to_buffer("\n"); } if (!block->is_root()) { --indentation; indent(); append_to_buffer("}"); } // remove extra newline that gets added after the last top-level block if (block->is_root()) { size_t l = buffer.length(); if (l > 2 && buffer[l-1] == '\n' && buffer[l-2] == '\n') { buffer.erase(l-1); if (ctx) ctx->source_map.remove_line(); } } } void Inspect::operator()(Ruleset* ruleset) { ruleset->selector()->perform(this); ruleset->block()->perform(this); } void Inspect::operator()(Propset* propset) { propset->property_fragment()->perform(this); append_to_buffer(": "); propset->block()->perform(this); } void Inspect::operator()(Media_Block* media_block) { if (ctx) ctx->source_map.add_mapping(media_block); append_to_buffer("@media "); media_block->media_queries()->perform(this); media_block->block()->perform(this); } void Inspect::operator()(Feature_Block* feature_block) { if (ctx) ctx->source_map.add_mapping(feature_block); append_to_buffer("@supports "); feature_block->feature_queries()->perform(this); feature_block->block()->perform(this); } void Inspect::operator()(At_Rule* at_rule) { append_to_buffer(at_rule->keyword()); if (at_rule->selector()) { append_to_buffer(" "); at_rule->selector()->perform(this); } if (at_rule->block()) { at_rule->block()->perform(this); } else { append_to_buffer(";"); } } void Inspect::operator()(Declaration* dec) { if (dec->value()->concrete_type() == Expression::NULL_VAL) return; if (ctx) ctx->source_map.add_mapping(dec->property()); dec->property()->perform(this); append_to_buffer(": "); if (ctx) ctx->source_map.add_mapping(dec->value()); dec->value()->perform(this); if (dec->is_important()) append_to_buffer(" !important"); append_to_buffer(";"); } void Inspect::operator()(Assignment* assn) { append_to_buffer(assn->variable()); append_to_buffer(": "); assn->value()->perform(this); if (assn->is_guarded()) append_to_buffer(" !default"); append_to_buffer(";"); } void Inspect::operator()(Import* import) { if (!import->urls().empty()) { if (ctx) ctx->source_map.add_mapping(import); append_to_buffer("@import "); import->urls().front()->perform(this); append_to_buffer(";"); for (size_t i = 1, S = import->urls().size(); i < S; ++i) { append_to_buffer("\n"); if (ctx) ctx->source_map.add_mapping(import); append_to_buffer("@import "); import->urls()[i]->perform(this); append_to_buffer(";"); } } } void Inspect::operator()(Import_Stub* import) { if (ctx) ctx->source_map.add_mapping(import); append_to_buffer("@import "); append_to_buffer(import->file_name()); append_to_buffer(";"); } void Inspect::operator()(Warning* warning) { if (ctx) ctx->source_map.add_mapping(warning); append_to_buffer("@warn "); warning->message()->perform(this); append_to_buffer(";"); } void Inspect::operator()(Comment* comment) { comment->text()->perform(this); } void Inspect::operator()(If* cond) { append_to_buffer("@if "); cond->predicate()->perform(this); cond->consequent()->perform(this); if (cond->alternative()) { append_to_buffer("\n"); indent(); append_to_buffer("else"); cond->alternative()->perform(this); } } void Inspect::operator()(For* loop) { append_to_buffer("@for "); append_to_buffer(loop->variable()); append_to_buffer(" from "); loop->lower_bound()->perform(this); append_to_buffer((loop->is_inclusive() ? " through " : " to ")); loop->upper_bound()->perform(this); loop->block()->perform(this); } void Inspect::operator()(Each* loop) { append_to_buffer("@each "); append_to_buffer(loop->variables()[0]); for (size_t i = 1, L = loop->variables().size(); i < L; ++i) { append_to_buffer(", "); append_to_buffer(loop->variables()[i]); } append_to_buffer(" in "); loop->list()->perform(this); loop->block()->perform(this); } void Inspect::operator()(While* loop) { append_to_buffer("@while "); loop->predicate()->perform(this); loop->block()->perform(this); } void Inspect::operator()(Return* ret) { append_to_buffer("@return "); ret->value()->perform(this); append_to_buffer(";"); } void Inspect::operator()(Extension* extend) { append_to_buffer("@extend "); extend->selector()->perform(this); append_to_buffer(";"); } void Inspect::operator()(Definition* def) { if (def->type() == Definition::MIXIN) { append_to_buffer("@mixin "); } else { append_to_buffer("@function "); } append_to_buffer(def->name()); def->parameters()->perform(this); def->block()->perform(this); } void Inspect::operator()(Mixin_Call* call) { append_to_buffer(string("@include ") += call->name()); if (call->arguments()) { call->arguments()->perform(this); } if (call->block()) { append_to_buffer(" "); call->block()->perform(this); } if (!call->block()) append_to_buffer(";"); } void Inspect::operator()(Content* content) { if (ctx) ctx->source_map.add_mapping(content); append_to_buffer("@content;"); } void Inspect::operator()(List* list) { string sep(list->separator() == List::SPACE ? " " : ", "); if (list->empty()) return; bool items_output = false; for (size_t i = 0, L = list->length(); i < L; ++i) { Expression* list_item = (*list)[i]; if (list_item->is_invisible()) { continue; } if (items_output) append_to_buffer(sep); list_item->perform(this); items_output = true; } } void Inspect::operator()(Binary_Expression* expr) { expr->left()->perform(this); switch (expr->type()) { case Binary_Expression::AND: append_to_buffer(" and "); break; case Binary_Expression::OR: append_to_buffer(" or "); break; case Binary_Expression::EQ: append_to_buffer(" == "); break; case Binary_Expression::NEQ: append_to_buffer(" != "); break; case Binary_Expression::GT: append_to_buffer(" > "); break; case Binary_Expression::GTE: append_to_buffer(" >= "); break; case Binary_Expression::LT: append_to_buffer(" < "); break; case Binary_Expression::LTE: append_to_buffer(" <= "); break; case Binary_Expression::ADD: append_to_buffer(" + "); break; case Binary_Expression::SUB: append_to_buffer(" - "); break; case Binary_Expression::MUL: append_to_buffer(" * "); break; case Binary_Expression::DIV: append_to_buffer("/"); break; case Binary_Expression::MOD: append_to_buffer(" % "); break; default: break; // shouldn't get here } expr->right()->perform(this); } void Inspect::operator()(Unary_Expression* expr) { if (expr->type() == Unary_Expression::PLUS) append_to_buffer("+"); else append_to_buffer("-"); expr->operand()->perform(this); } void Inspect::operator()(Function_Call* call) { append_to_buffer(call->name()); call->arguments()->perform(this); } void Inspect::operator()(Function_Call_Schema* call) { call->name()->perform(this); call->arguments()->perform(this); } void Inspect::operator()(Variable* var) { append_to_buffer(var->name()); } void Inspect::operator()(Textual* txt) { append_to_buffer(txt->value()); } // helper functions for serializing numbers // string frac_to_string(double f, size_t p) { // stringstream ss; // ss.setf(ios::fixed, ios::floatfield); // ss.precision(p); // ss << f; // string result(ss.str().substr(f < 0 ? 2 : 1)); // size_t i = result.size() - 1; // while (result[i] == '0') --i; // result = result.substr(0, i+1); // return result; // } // string double_to_string(double d, size_t p) { // stringstream ss; // double ipart; // double fpart = std::modf(d, &ipart); // ss << ipart; // if (fpart != 0) ss << frac_to_string(fpart, 5); // return ss.str(); // } void Inspect::operator()(Number* n) { stringstream ss; ss.precision(ctx ? ctx->precision : 5); ss << fixed << n->value(); string d(ss.str()); for (size_t i = d.length()-1; d[i] == '0'; --i) { d.resize(d.length()-1); } if (d[d.length()-1] == '.') d.resize(d.length()-1); if (n->numerator_units().size() > 1 || n->denominator_units().size() > 0) { error(d + n->unit() + " is not a valid CSS value", n->path(), n->position()); } if (!n->zero()) { if (d.substr(0, 3) == "-0.") d.erase(1, 1); if (d.substr(0, 2) == "0.") d.erase(0, 1); } append_to_buffer(d == "-0" ? "0" : d); append_to_buffer(n->unit()); } // helper function for serializing colors template <size_t range> static double cap_channel(double c) { if (c > range) return range; else if (c < 0) return 0; else return c; } void Inspect::operator()(Color* c) { stringstream ss; double r = round(cap_channel<0xff>(c->r())); double g = round(cap_channel<0xff>(c->g())); double b = round(cap_channel<0xff>(c->b())); double a = cap_channel<1> (c->a()); // retain the originally specified color definition if unchanged if (!c->disp().empty()) { ss << c->disp(); } else if (a >= 1) { // see if it's a named color int numval = r * 0x10000; numval += g * 0x100; numval += b; if (ctx && ctx->colors_to_names.count(numval)) { ss << ctx->colors_to_names[numval]; } else { // otherwise output the hex triplet ss << '#' << setw(2) << setfill('0'); ss << hex << setw(2) << static_cast<unsigned long>(r); ss << hex << setw(2) << static_cast<unsigned long>(g); ss << hex << setw(2) << static_cast<unsigned long>(b); } } else { ss << "rgba("; ss << static_cast<unsigned long>(r) << ", "; ss << static_cast<unsigned long>(g) << ", "; ss << static_cast<unsigned long>(b) << ", "; ss << a << ')'; } append_to_buffer(ss.str()); } void Inspect::operator()(Boolean* b) { append_to_buffer(b->value() ? "true" : "false"); } void Inspect::operator()(String_Schema* ss) { // Evaluation should turn these into String_Constants, so this method is // only for inspection purposes. for (size_t i = 0, L = ss->length(); i < L; ++i) { if ((*ss)[i]->is_interpolant()) append_to_buffer("#{"); (*ss)[i]->perform(this); if ((*ss)[i]->is_interpolant()) append_to_buffer("}"); } } void Inspect::operator()(String_Constant* s) { append_to_buffer(s->needs_unquoting() ? unquote(s->value()) : s->value()); } void Inspect::operator()(Feature_Query* fq) { size_t i = 0; (*fq)[i++]->perform(this); for (size_t L = fq->length(); i < L; ++i) { (*fq)[i]->perform(this); } } void Inspect::operator()(Feature_Query_Condition* fqc) { if (fqc->operand() == Feature_Query_Condition::AND) append_to_buffer(" and "); else if (fqc->operand() == Feature_Query_Condition::OR) append_to_buffer(" or "); else if (fqc->operand() == Feature_Query_Condition::NOT) append_to_buffer(" not "); if (!fqc->is_root()) append_to_buffer("("); if (!fqc->length()) { fqc->feature()->perform(this); append_to_buffer(": "); fqc->value()->perform(this); } // else for (size_t i = 0, L = fqc->length(); i < L; ++i) (*fqc)[i]->perform(this); if (!fqc->is_root()) append_to_buffer(")"); } void Inspect::operator()(Media_Query* mq) { size_t i = 0; if (mq->media_type()) { if (mq->is_negated()) append_to_buffer("not "); else if (mq->is_restricted()) append_to_buffer("only "); mq->media_type()->perform(this); } else { (*mq)[i++]->perform(this); } for (size_t L = mq->length(); i < L; ++i) { append_to_buffer(" and "); (*mq)[i]->perform(this); } } void Inspect::operator()(Media_Query_Expression* mqe) { if (mqe->is_interpolated()) { mqe->feature()->perform(this); } else { append_to_buffer("("); mqe->feature()->perform(this); if (mqe->value()) { append_to_buffer(": "); mqe->value()->perform(this); } append_to_buffer(")"); } } void Inspect::operator()(Null* n) { append_to_buffer("null"); } // parameters and arguments void Inspect::operator()(Parameter* p) { append_to_buffer(p->name()); if (p->default_value()) { append_to_buffer(": "); p->default_value()->perform(this); } else if (p->is_rest_parameter()) { append_to_buffer("..."); } } void Inspect::operator()(Parameters* p) { append_to_buffer("("); if (!p->empty()) { (*p)[0]->perform(this); for (size_t i = 1, L = p->length(); i < L; ++i) { append_to_buffer(", "); (*p)[i]->perform(this); } } append_to_buffer(")"); } void Inspect::operator()(Argument* a) { if (!a->name().empty()) { append_to_buffer(a->name()); append_to_buffer(": "); } // Special case: argument nulls can be ignored if (a->value()->concrete_type() == Expression::NULL_VAL) { return; } a->value()->perform(this); if (a->is_rest_argument()) { append_to_buffer("..."); } } void Inspect::operator()(Arguments* a) { append_to_buffer("("); if (!a->empty()) { (*a)[0]->perform(this); for (size_t i = 1, L = a->length(); i < L; ++i) { append_to_buffer(", "); (*a)[i]->perform(this); } } append_to_buffer(")"); } // selectors void Inspect::operator()(Selector_Schema* s) { s->contents()->perform(this); } void Inspect::operator()(Selector_Reference* ref) { if (ref->selector()) ref->selector()->perform(this); else append_to_buffer("&"); } void Inspect::operator()(Selector_Placeholder* s) { append_to_buffer(s->name()); } void Inspect::operator()(Type_Selector* s) { if (ctx) ctx->source_map.add_mapping(s); append_to_buffer(s->name()); } void Inspect::operator()(Selector_Qualifier* s) { if (ctx) ctx->source_map.add_mapping(s); append_to_buffer(s->name()); } void Inspect::operator()(Attribute_Selector* s) { if (ctx) ctx->source_map.add_mapping(s); append_to_buffer("["); append_to_buffer(s->name()); if (!s->matcher().empty()) { append_to_buffer(s->matcher()); if (s->value()) { s->value()->perform(this); } // append_to_buffer(s->value()); } append_to_buffer("]"); } void Inspect::operator()(Pseudo_Selector* s) { if (ctx) ctx->source_map.add_mapping(s); append_to_buffer(s->name()); if (s->expression()) { s->expression()->perform(this); append_to_buffer(")"); } } void Inspect::operator()(Wrapped_Selector* s) { if (ctx) ctx->source_map.add_mapping(s); append_to_buffer(s->name()); s->selector()->perform(this); append_to_buffer(")"); } void Inspect::operator()(Compound_Selector* s) { for (size_t i = 0, L = s->length(); i < L; ++i) { (*s)[i]->perform(this); } } void Inspect::operator()(Complex_Selector* c) { Compound_Selector* head = c->head(); Complex_Selector* tail = c->tail(); Complex_Selector::Combinator comb = c->combinator(); if (head && !head->is_empty_reference()) head->perform(this); if (head && !head->is_empty_reference() && tail) append_to_buffer(" "); switch (comb) { case Complex_Selector::ANCESTOR_OF: break; case Complex_Selector::PARENT_OF: append_to_buffer(">"); break; case Complex_Selector::PRECEDES: append_to_buffer("~"); break; case Complex_Selector::ADJACENT_TO: append_to_buffer("+"); break; } if (tail && comb != Complex_Selector::ANCESTOR_OF) { append_to_buffer(" "); } if (tail) tail->perform(this); } void Inspect::operator()(Selector_List* g) { if (g->empty()) return; (*g)[0]->perform(this); for (size_t i = 1, L = g->length(); i < L; ++i) { append_to_buffer(", "); (*g)[i]->perform(this); } } inline void Inspect::fallback_impl(AST_Node* n) { } void Inspect::indent() { append_to_buffer(string(2*indentation, ' ')); } string unquote(const string& s) { if (s.empty()) return ""; if (s.length() == 1) { if (s[0] == '"' || s[0] == '\'') return ""; } char q; if (*s.begin() == '"' && *s.rbegin() == '"') q = '"'; else if (*s.begin() == '\'' && *s.rbegin() == '\'') q = '\''; else return s; string t; t.reserve(s.length()-2); for (size_t i = 1, L = s.length()-1; i < L; ++i) { // if we see a quote, we need to remove the preceding backslash from t if (s[i] == q) t.erase(t.length()-1); t.push_back(s[i]); } return t; } string quote(const string& s, char q) { if (s.empty()) return string(2, q); if (!q || s[0] == '"' || s[0] == '\'') return s; string t; t.reserve(s.length()+2); t.push_back(q); for (size_t i = 0, L = s.length(); i < L; ++i) { if (s[i] == q) t.push_back('\\'); t.push_back(s[i]); } t.push_back(q); return t; } void Inspect::append_to_buffer(const string& text) { buffer += text; if (ctx && !ctx->_skip_source_map_update) ctx->source_map.update_column(text); } } <file_sep>/libsass/sass_values.cpp #ifdef _WIN32 #include <io.h> #else #include <unistd.h> #endif #include <cstdlib> #include <cstring> #include "sass_values.h" extern "C" { using namespace std; struct Sass_Unknown { enum Sass_Tag tag; }; struct Sass_Boolean { enum Sass_Tag tag; bool value; }; struct Sass_Number { enum Sass_Tag tag; double value; char* unit; }; struct Sass_Color { enum Sass_Tag tag; double r; double g; double b; double a; }; struct Sass_String { enum Sass_Tag tag; char* value; }; struct Sass_List { enum Sass_Tag tag; enum Sass_Separator separator; size_t length; // null terminated "array" union Sass_Value** values; }; struct Sass_Map { enum Sass_Tag tag; size_t length; struct Sass_MapPair* pairs; }; struct Sass_Null { enum Sass_Tag tag; }; struct Sass_Error { enum Sass_Tag tag; char* message; }; union Sass_Value { struct Sass_Unknown unknown; struct Sass_Boolean boolean; struct Sass_Number number; struct Sass_Color color; struct Sass_String string; struct Sass_List list; struct Sass_Map map; struct Sass_Null null; struct Sass_Error error; }; struct Sass_MapPair { union Sass_Value* key; union Sass_Value* value; }; // Return the sass tag for a generic sass value enum Sass_Tag sass_value_get_tag(union Sass_Value* v) { return v->unknown.tag; } // Check value for specified type bool sass_value_is_null(union Sass_Value* v) { return v->unknown.tag == SASS_NULL; } bool sass_value_is_map(union Sass_Value* v) { return v->unknown.tag == SASS_MAP; } bool sass_value_is_list(union Sass_Value* v) { return v->unknown.tag == SASS_LIST; } bool sass_value_is_number(union Sass_Value* v) { return v->unknown.tag == SASS_NUMBER; } bool sass_value_is_string(union Sass_Value* v) { return v->unknown.tag == SASS_STRING; } bool sass_value_is_boolean(union Sass_Value* v) { return v->unknown.tag == SASS_BOOLEAN; } bool sass_value_is_error(union Sass_Value* v) { return v->unknown.tag == SASS_ERROR; } bool sass_value_is_color(union Sass_Value* v) { return v->unknown.tag == SASS_COLOR; } // Getters and setters for Sass_Number double sass_number_get_value(union Sass_Value* v) { return v->number.value; } void sass_number_set_value(union Sass_Value* v, double value) { v->number.value = value; } const char* sass_number_get_unit(union Sass_Value* v) { return v->number.unit; } void sass_number_set_unit(union Sass_Value* v, char* unit) { v->number.unit = unit; } // Getters and setters for Sass_String const char* sass_string_get_value(union Sass_Value* v) { return v->string.value; } void sass_string_set_value(union Sass_Value* v, char* value) { v->string.value = value; } // Getters and setters for Sass_Boolean bool sass_boolean_get_value(union Sass_Value* v) { return v->boolean.value; } void sass_boolean_set_value(union Sass_Value* v, bool value) { v->boolean.value = value; } // Getters and setters for Sass_Color double sass_color_get_r(union Sass_Value* v) { return v->color.r; } void sass_color_set_r(union Sass_Value* v, double r) { v->color.r = r; } double sass_color_get_g(union Sass_Value* v) { return v->color.g; } void sass_color_set_g(union Sass_Value* v, double g) { v->color.g = g; } double sass_color_get_b(union Sass_Value* v) { return v->color.b; } void sass_color_set_b(union Sass_Value* v, double b) { v->color.b = b; } double sass_color_get_a(union Sass_Value* v) { return v->color.a; } void sass_color_set_a(union Sass_Value* v, double a) { v->color.a = a; } // Getters and setters for Sass_List size_t sass_list_get_length(union Sass_Value* v) { return v->list.length; } enum Sass_Separator sass_list_get_separator(union Sass_Value* v) { return v->list.separator; } void sass_list_set_separator(union Sass_Value* v, enum Sass_Separator separator) { v->list.separator = separator; } // Getters and setters for Sass_List values union Sass_Value* sass_list_get_value(union Sass_Value* v, size_t i) { return v->list.values[i]; } void sass_list_set_value(union Sass_Value* v, size_t i, union Sass_Value* value) { v->list.values[i] = value; } // Getters and setters for Sass_Map size_t sass_map_get_length(union Sass_Value* v) { return v->map.length; } // Getters and setters for Sass_List keys and values union Sass_Value* sass_map_get_key(union Sass_Value* v, size_t i) { return v->map.pairs[i].key; } union Sass_Value* sass_map_get_value(union Sass_Value* v, size_t i) { return v->map.pairs[i].value; } void sass_map_set_key(union Sass_Value* v, size_t i, union Sass_Value* key) { v->map.pairs[i].key = key; } void sass_map_set_value(union Sass_Value* v, size_t i, union Sass_Value* val) { v->map.pairs[i].value = val; } // Getters and setters for Sass_Error char* sass_error_get_message(union Sass_Value* v) { return v->error.message; }; void sass_error_set_message(union Sass_Value* v, char* msg) { v->error.message = msg; }; // Creator functions for all value types union Sass_Value* sass_make_boolean(bool val) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->boolean.tag = SASS_BOOLEAN; v->boolean.value = val; return v; } union Sass_Value* sass_make_number(double val, const char* unit) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->number.tag = SASS_NUMBER; v->number.value = val; v->number.unit = strdup(unit); if (v->number.unit == 0) { free(v); return 0; } return v; } union Sass_Value* sass_make_color(double r, double g, double b, double a) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->color.tag = SASS_COLOR; v->color.r = r; v->color.g = g; v->color.b = b; v->color.a = a; return v; } union Sass_Value* sass_make_string(const char* val) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->string.tag = SASS_STRING; v->string.value = strdup(val); if (v->string.value == 0) { free(v); return 0; } return v; } union Sass_Value* sass_make_list(size_t len, enum Sass_Separator sep) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->list.tag = SASS_LIST; v->list.length = len; v->list.separator = sep; v->list.values = (union Sass_Value**) calloc(len, sizeof(union Sass_Value)); if (v->list.values == 0) { free(v); return 0; } return v; } union Sass_Value* sass_make_map(size_t len) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->map.tag = SASS_MAP; v->map.length = len; v->map.pairs = (struct Sass_MapPair*) calloc(len, sizeof(struct Sass_MapPair)); if (v->map.pairs == 0) { free(v); return 0; } return v; } union Sass_Value* sass_make_null(void) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->null.tag = SASS_NULL; return v; } union Sass_Value* sass_make_error(const char* msg) { Sass_Value* v = (Sass_Value*) calloc(1, sizeof(Sass_Value)); if (v == 0) return 0; v->error.tag = SASS_ERROR; v->error.message = strdup(msg); if (v->error.message == 0) { free(v); return 0; } return v; } // will free all associated sass values void sass_delete_value(union Sass_Value* val) { size_t i; if (val == 0) return; switch(val->unknown.tag) { case SASS_NULL: { } break; case SASS_BOOLEAN: { } break; case SASS_NUMBER: { free(val->number.unit); } break; case SASS_COLOR: { } break; case SASS_STRING: { free(val->string.value); } break; case SASS_LIST: { for (i=0; i<val->list.length; i++) { sass_delete_value(val->list.values[i]); } free(val->list.values); } break; case SASS_MAP: { for (i=0; i<val->map.length; i++) { sass_delete_value(val->map.pairs[i].key); sass_delete_value(val->map.pairs[i].value); } free(val->map.pairs); } break; case SASS_ERROR: { free(val->error.message); } break; } free(val); } } <file_sep>/libsass/parser.hpp #define SASS_PARSER #include <vector> #include <map> #ifndef SASS_PRELEXER #include "prelexer.hpp" #endif #ifndef SASS_TOKEN #include "token.hpp" #endif #ifndef SASS_CONTEXT #include "context.hpp" #endif #ifndef SASS_AST #include "ast.hpp" #endif #ifndef SASS_POSITION #include "position.hpp" #endif #include <iostream> struct Selector_Lookahead { const char* found; bool has_interpolants; }; namespace Sass { using std::string; using std::vector; using std::map; using namespace Prelexer; class Parser { private: void add_single_file (Import* imp, string import_path); public: class AST_Node; enum Syntactic_Context { nothing, mixin_def, function_def }; Context& ctx; vector<Syntactic_Context> stack; const char* source; const char* position; const char* end; string path; size_t column; Position source_position; Token lexed; Parser(Context& ctx, string path, Position source_position) : ctx(ctx), stack(vector<Syntactic_Context>()), source(0), position(0), end(0), path(path), column(1), source_position(source_position) { stack.push_back(nothing); } static Parser from_string(string src, Context& ctx, string path = "", Position source_position = Position()); static Parser from_c_str(const char* src, Context& ctx, string path = "", Position source_position = Position()); static Parser from_token(Token t, Context& ctx, string path = "", Position source_position = Position()); #ifdef __clang__ // lex and peak uses the template parameter to branch on the action, which // triggers clangs tautological comparison on the single-comparison // branches. This is not a bug, just a merging of behaviour into // one function #pragma clang diagnostic push #pragma clang diagnostic ignored "-Wtautological-compare" #endif template <prelexer mx> const char* peek(const char* start = 0) { if (!start) start = position; const char* after_whitespace; if (mx == block_comment) { after_whitespace = // start; zero_plus< alternatives<spaces, line_comment> >(start); } else if (/*mx == ancestor_of ||*/ mx == no_spaces) { after_whitespace = position; } else if (mx == spaces || mx == ancestor_of) { after_whitespace = mx(start); if (after_whitespace) { return after_whitespace; } else { return 0; } } else if (mx == optional_spaces) { after_whitespace = optional_spaces(start); } else if (mx == line_comment_prefix || mx == block_comment_prefix) { after_whitespace = position; } else { after_whitespace = spaces_and_comments(start); } const char* after_token = mx(after_whitespace); if (after_token) { return after_token; } else { return 0; } } template <prelexer mx> const char* lex() { const char* after_whitespace; if (mx == block_comment) { after_whitespace = // position; zero_plus< alternatives<spaces, line_comment> >(position); } else if (mx == url) { after_whitespace = position; } else if (mx == ancestor_of || mx == no_spaces) { after_whitespace = position; } else if (mx == spaces) { after_whitespace = spaces(position); if (after_whitespace) { source_position.line += count_interval<'\n'>(position, after_whitespace); lexed = Token(position, after_whitespace); return position = after_whitespace; } else { return 0; } } else if (mx == optional_spaces) { after_whitespace = optional_spaces(position); } else { after_whitespace = spaces_and_comments(position); } const char* after_token = mx(after_whitespace); if (after_token) { size_t previous_line = source_position.line; source_position.line += count_interval<'\n'>(position, after_token); size_t whitespace = 0; const char* ptr = after_whitespace - 1; while (ptr >= position) { if (*ptr == '\n') break; whitespace++; ptr--; } if (previous_line != source_position.line) { column = 1; } source_position.column = column + whitespace; column += after_token - after_whitespace + whitespace; lexed = Token(after_whitespace, after_token); return position = after_token; } else { return 0; } } #ifdef __clang__ #pragma clang diagnostic pop #endif void error(string msg, Position pos = Position()); void read_bom(); Block* parse(); Import* parse_import(); Definition* parse_definition(); Parameters* parse_parameters(); Parameter* parse_parameter(); Mixin_Call* parse_mixin_call(); Arguments* parse_arguments(); Argument* parse_argument(); Assignment* parse_assignment(); Propset* parse_propset(); Ruleset* parse_ruleset(Selector_Lookahead lookahead); Selector_Schema* parse_selector_schema(const char* end_of_selector); Selector_List* parse_selector_group(); Complex_Selector* parse_selector_combination(); Compound_Selector* parse_simple_selector_sequence(); Simple_Selector* parse_simple_selector(); Wrapped_Selector* parse_negated_selector(); Simple_Selector* parse_pseudo_selector(); Attribute_Selector* parse_attribute_selector(); Block* parse_block(); Declaration* parse_declaration(); Expression* parse_map_value(); Expression* parse_map(); Expression* parse_list(); Expression* parse_comma_list(); Expression* parse_space_list(); Expression* parse_disjunction(); Expression* parse_conjunction(); Expression* parse_relation(); Expression* parse_expression(); Expression* parse_term(); Expression* parse_factor(); Expression* parse_value(); Function_Call* parse_calc_function(); Function_Call* parse_function_call(); Function_Call_Schema* parse_function_call_schema(); String* parse_interpolated_chunk(Token); String* parse_string(); String* parse_ie_stuff(); String_Schema* parse_value_schema(); String* parse_identifier_schema(); String_Schema* parse_url_schema(); If* parse_if_directive(bool else_if = false); For* parse_for_directive(); Each* parse_each_directive(); While* parse_while_directive(); Media_Block* parse_media_block(); List* parse_media_queries(); Media_Query* parse_media_query(); Media_Query_Expression* parse_media_expression(); Feature_Block* parse_feature_block(); Feature_Query* parse_feature_queries(); Feature_Query_Condition* parse_feature_query(); Feature_Query_Condition* parse_feature_query_in_parens(); Feature_Query_Condition* parse_supports_negation(); Feature_Query_Condition* parse_supports_conjunction(); Feature_Query_Condition* parse_supports_disjunction(); Feature_Query_Condition* parse_supports_declaration(); At_Rule* parse_at_rule(); Warning* parse_warning(); Selector_Lookahead lookahead_for_selector(const char* start = 0); Selector_Lookahead lookahead_for_extension_target(const char* start = 0); Expression* fold_operands(Expression* base, vector<Expression*>& operands, Binary_Expression::Type op); Expression* fold_operands(Expression* base, vector<Expression*>& operands, vector<Binary_Expression::Type>& ops); void throw_syntax_error(string message, size_t ln = 0); void throw_read_error(string message, size_t ln = 0); }; size_t check_bom_chars(const char* src, const char *end, const unsigned char* bom, size_t len); } <file_sep>/libsass/prelexer.cpp #include <cctype> #include <cstddef> #include <iostream> #include "constants.hpp" #include "prelexer.hpp" #include "util.hpp" namespace Sass { using namespace Constants; namespace Prelexer { using std::ptrdiff_t; // Matches zero characters (always succeeds without consuming input). const char* epsilon(char *src) { return src; } // Matches the empty string. const char* empty(char *src) { return *src ? 0 : src; } // Match any single character. const char* any_char(const char* src) { return *src ? src+1 : src; } // Match a single character satisfying the ctype predicates. const char* space(const char* src) { return std::isspace(*src) ? src+1 : 0; } const char* alpha(const char* src) { return std::isalpha(*src) || !Sass::Util::isAscii(*src) ? src+1 : 0; } const char* digit(const char* src) { return std::isdigit(*src) ? src+1 : 0; } const char* xdigit(const char* src) { return std::isxdigit(*src) ? src+1 : 0; } const char* alnum(const char* src) { return std::isalnum(*src) || !Sass::Util::isAscii(*src) ? src+1 : 0; } const char* punct(const char* src) { return std::ispunct(*src) ? src+1 : 0; } // Match multiple ctype characters. const char* spaces(const char* src) { return one_plus<space>(src); } const char* alphas(const char* src) { return one_plus<alpha>(src); } const char* digits(const char* src) { return one_plus<digit>(src); } const char* xdigits(const char* src) { return one_plus<xdigit>(src); } const char* alnums(const char* src) { return one_plus<alnum>(src); } const char* puncts(const char* src) { return one_plus<punct>(src); } // Match a line comment. const char* line_comment(const char* src) { return to_endl<slash_slash>(src); } // Match a line comment prefix. const char* line_comment_prefix(const char* src) { return exactly<slash_slash>(src); } // Match a block comment. const char* block_comment(const char* src) { return sequence< optional_spaces, delimited_by<slash_star, star_slash, false> >(src); } const char* block_comment_prefix(const char* src) { return exactly<slash_star>(src); } // Match either comment. const char* comment(const char* src) { return alternatives<block_comment, line_comment>(src); } const char* newline(const char* src) { return alternatives< exactly<'\n'>, sequence< exactly<'\r'>, exactly<'\n'> >, exactly<'\r'>, exactly<'\f'> >(src); } const char* whitespace(const char* src) { return alternatives< newline, exactly<' '>, exactly<'\t'> >(src); } const char* escape(const char* src) { return sequence< exactly<'\\'>, any_char >(src); } // Match double- and single-quoted strings. const char* double_quoted_string(const char* src) { src = exactly<'"'>(src); if (!src) return 0; const char* p; while (1) { if (!*src) return 0; if((p = escape(src))) { src = p; continue; } else if((p = exactly<'"'>(src))) { return p; } else { ++src; } } return 0; } const char* single_quoted_string(const char* src) { src = exactly<'\''>(src); if (!src) return 0; const char* p; while (1) { if (!*src) return 0; if((p = escape(src))) { src = p; continue; } else if((p = exactly<'\''>(src))) { return p; } else { ++src; } } return 0; } const char* string_constant(const char* src) { return alternatives<double_quoted_string, single_quoted_string>(src); } // Match interpolants. const char* interpolant(const char* src) { return delimited_by<hash_lbrace, rbrace, false>(src); } // Whitespace handling. const char* optional_spaces(const char* src) { return optional<spaces>(src); } const char* optional_comment(const char* src) { return optional<comment>(src); } const char* spaces_and_comments(const char* src) { return zero_plus< alternatives<spaces, comment> >(src); } const char* no_spaces(const char* src) { return negate< spaces >(src); } const char* backslash_something(const char* src) { return sequence< exactly<'\\'>, any_char >(src); } // Match CSS identifiers. const char* identifier(const char* src) { return sequence< optional< exactly<'-'> >, alternatives< alpha, exactly<'_'>, backslash_something >, zero_plus< alternatives< alnum, exactly<'-'>, exactly<'_'>, backslash_something > > >(src); } // Match CSS selectors. const char* sel_ident(const char* src) { return sequence< optional< alternatives< exactly<'-'>, exactly<'|'> > >, alternatives< alpha, exactly<'_'>, backslash_something, exactly<'|'> >, zero_plus< alternatives< alnum, exactly<'-'>, exactly<'_'>, exactly<'|'>, backslash_something > > >(src); } // Match CSS css variables. const char* custom_property_name(const char* src) { return sequence< exactly<'-'>, exactly<'-'>, identifier >(src); } // Match interpolant schemas const char* identifier_schema(const char* src) { // follows this pattern: (x*ix*)+ ... well, not quite return one_plus< sequence< zero_plus< alternatives< identifier, exactly<'-'> > >, interpolant, zero_plus< alternatives< identifier, number, exactly<'-'> > > > >(src); } const char* value_schema(const char* src) { // follows this pattern: ([xyz]*i[xyz]*)+ return one_plus< sequence< zero_plus< alternatives< identifier, percentage, dimension, hex, number, string_constant > >, interpolant, zero_plus< alternatives< identifier, percentage, dimension, hex, number, string_constant > > > >(src); } const char* filename_schema(const char* src) { return one_plus< sequence< zero_plus< alternatives< identifier, number, exactly<'.'>, exactly<'/'> > >, interpolant, zero_plus< alternatives< identifier, number, exactly<'.'>, exactly<'/'> > > > >(src); } const char* filename(const char* src) { return one_plus< alternatives< identifier, number, exactly<'.'> > >(src); } // Match CSS '@' keywords. const char* at_keyword(const char* src) { return sequence<exactly<'@'>, identifier>(src); } const char* import(const char* src) { return exactly<import_kwd>(src); } const char* media(const char* src) { return exactly<media_kwd>(src); } const char* supports(const char* src) { return exactly<supports_kwd>(src); } const char* keyframes(const char* src) { return sequence< exactly<'@'>, optional< vendor_prefix >, exactly< keyframes_kwd > >(src); } const char* vendor_prefix(const char* src) { return alternatives< exactly< vendor_opera_kwd >, exactly< vendor_webkit_kwd >, exactly< vendor_mozilla_kwd >, exactly< vendor_ms_kwd >, exactly< vendor_khtml_kwd > >(src); } const char* keyf(const char* src) { return one_plus< alternatives< to, from, percentage > >(src); } const char* mixin(const char* src) { return exactly<mixin_kwd>(src); } const char* function(const char* src) { return exactly<function_kwd>(src); } const char* return_directive(const char* src) { return exactly<return_kwd>(src); } const char* include(const char* src) { return exactly<include_kwd>(src); } const char* content(const char* src) { return exactly<content_kwd>(src); } const char* extend(const char* src) { return exactly<extend_kwd>(src); } const char* if_directive(const char* src) { return exactly<if_kwd>(src); } const char* else_directive(const char* src) { return exactly<else_kwd>(src); } const char* elseif_directive(const char* src) { return sequence< else_directive, spaces_and_comments, exactly< if_after_else_kwd > >(src); } const char* for_directive(const char* src) { return exactly<for_kwd>(src); } const char* from(const char* src) { return exactly<from_kwd>(src); } const char* to(const char* src) { return exactly<to_kwd>(src); } const char* through(const char* src) { return exactly<through_kwd>(src); } const char* each_directive(const char* src) { return exactly<each_kwd>(src); } const char* in(const char* src) { return exactly<in_kwd>(src); } const char* while_directive(const char* src) { return exactly<while_kwd>(src); } const char* name(const char* src) { return one_plus< alternatives< alnum, exactly<'-'>, exactly<'_'>, exactly<'\\'> > >(src); } const char* warn(const char* src) { return exactly<warn_kwd>(src); } const char* directive(const char* src) { return sequence< exactly<'@'>, identifier >(src); } const char* null(const char* src) { return exactly<null_kwd>(src); } // Match CSS type selectors const char* namespace_prefix(const char* src) { return sequence< optional< alternatives< identifier, exactly<'*'> > >, exactly<'|'> >(src); } const char* type_selector(const char* src) { return sequence< optional<namespace_prefix>, identifier>(src); } const char* hyphens_and_identifier(const char* src) { return sequence< zero_plus< exactly< '-' > >, identifier >(src); } const char* hyphens_and_name(const char* src) { return sequence< zero_plus< exactly< '-' > >, name >(src); } const char* universal(const char* src) { return sequence< optional<namespace_prefix>, exactly<'*'> >(src); } // Match CSS id names. const char* id_name(const char* src) { return sequence<exactly<'#'>, name>(src); } // Match CSS class names. const char* class_name(const char* src) { return sequence<exactly<'.'>, identifier>(src); } // Attribute name in an attribute selector. const char* attribute_name(const char* src) { return alternatives< sequence< optional<namespace_prefix>, identifier>, identifier >(src); } // match placeholder selectors const char* placeholder(const char* src) { return sequence<exactly<'%'>, identifier>(src); } // Match CSS numeric constants. const char* sign(const char* src) { return class_char<sign_chars>(src); } const char* unsigned_number(const char* src) { return alternatives<sequence< zero_plus<digits>, exactly<'.'>, one_plus<digits> >, digits>(src); } const char* number(const char* src) { return sequence< optional<sign>, unsigned_number>(src); } const char* coefficient(const char* src) { return alternatives< sequence< optional<sign>, digits >, sign >(src); } const char* binomial(const char* src) { return sequence< optional<sign>, optional<digits>, exactly<'n'>, optional_spaces, sign, optional_spaces, digits >(src); } const char* percentage(const char* src) { return sequence< number, exactly<'%'> >(src); } const char* em(const char* src) { return sequence< number, exactly<em_kwd> >(src); } const char* dimension(const char* src) { return sequence<number, identifier>(src); } const char* hex(const char* src) { const char* p = sequence< exactly<'#'>, one_plus<xdigit> >(src); ptrdiff_t len = p - src; return (len != 4 && len != 7) ? 0 : p; } const char* rgb_prefix(const char* src) { return exactly<rgb_kwd>(src); } // Match CSS uri specifiers. const char* uri_prefix(const char* src) { return exactly<url_kwd>(src); } // TODO: rename the following two functions const char* uri(const char* src) { return sequence< exactly<url_kwd>, optional<spaces>, string_constant, optional<spaces>, exactly<')'> >(src); } const char* url_value(const char* src) { return sequence< optional< sequence< identifier, exactly<':'> > >, // optional protocol one_plus< sequence< zero_plus< exactly<'/'> >, filename > >, // one or more folders and/or trailing filename optional< exactly<'/'> > >(src); } const char* url_schema(const char* src) { return sequence< optional< sequence< identifier, exactly<':'> > >, // optional protocol filename_schema >(src); // optional trailing slash } // Match CSS "!important" keyword. const char* important(const char* src) { return sequence< exactly<'!'>, spaces_and_comments, exactly<important_kwd> >(src); } // Match CSS "!optional" keyword. const char* optional(const char* src) { return sequence< exactly<'!'>, spaces_and_comments, exactly<optional_kwd> >(src); } // Match Sass "!default" keyword. const char* default_flag(const char* src) { return sequence< exactly<'!'>, spaces_and_comments, exactly<default_kwd> >(src); } // Match Sass "!global" keyword. const char* global_flag(const char* src) { return sequence< exactly<'!'>, spaces_and_comments, exactly<global_kwd> >(src); } // Match CSS pseudo-class/element prefixes. const char* pseudo_prefix(const char* src) { return sequence< exactly<':'>, optional< exactly<':'> > >(src); } // Match CSS function call openers. const char* functional_schema(const char* src) { return sequence< identifier_schema, exactly<'('> >(src); } const char* functional(const char* src) { return sequence< identifier, exactly<'('> >(src); } // Match the CSS negation pseudo-class. const char* pseudo_not(const char* src) { return exactly< pseudo_not_kwd >(src); } // Match CSS 'odd' and 'even' keywords for functional pseudo-classes. const char* even(const char* src) { return exactly<even_kwd>(src); } const char* odd(const char* src) { return exactly<odd_kwd>(src); } // Match CSS attribute-matching operators. const char* exact_match(const char* src) { return exactly<'='>(src); } const char* class_match(const char* src) { return exactly<tilde_equal>(src); } const char* dash_match(const char* src) { return exactly<pipe_equal>(src); } const char* prefix_match(const char* src) { return exactly<caret_equal>(src); } const char* suffix_match(const char* src) { return exactly<dollar_equal>(src); } const char* substring_match(const char* src) { return exactly<star_equal>(src); } // Match CSS combinators. const char* adjacent_to(const char* src) { return sequence< optional_spaces, exactly<'+'> >(src); } const char* precedes(const char* src) { return sequence< optional_spaces, exactly<'~'> >(src); } const char* parent_of(const char* src) { return sequence< optional_spaces, exactly<'>'> >(src); } const char* ancestor_of(const char* src) { return sequence< spaces, negate< exactly<'{'> > >(src); } // Match SCSS variable names. const char* variable(const char* src) { return sequence<exactly<'$'>, identifier>(src); } // Match Sass boolean keywords. const char* true_val(const char* src) { return exactly<true_kwd>(src); } const char* false_val(const char* src) { return exactly<false_kwd>(src); } const char* and_op(const char* src) { return exactly<and_kwd>(src); } const char* or_op(const char* src) { return exactly<or_kwd>(src); } const char* not_op(const char* src) { return exactly<not_kwd>(src); } const char* eq_op(const char* src) { return exactly<eq>(src); } const char* neq_op(const char* src) { return exactly<neq>(src); } const char* gt_op(const char* src) { return exactly<gt>(src); } const char* gte_op(const char* src) { return exactly<gte>(src); } const char* lt_op(const char* src) { return exactly<lt>(src); } const char* lte_op(const char* src) { return exactly<lte>(src); } // match specific IE syntax const char* ie_progid(const char* src) { return sequence < exactly<progid_kwd>, exactly<':'>, alternatives< identifier_schema, identifier >, one_plus< sequence< exactly<'.'>, alternatives< identifier_schema, identifier > > > >(src); } const char* ie_expression(const char* src) { return exactly<expression_kwd>(src); } // match any IE syntax const char* ie_stuff(const char* src) { return sequence< alternatives < ie_expression, ie_progid >, delimited_by<'(', ';', true> >(src); } // const char* ie_args(const char* src) { // return sequence< alternatives< ie_keyword_arg, value_schema, string_constant, interpolant, number, identifier, delimited_by< '(', ')', true> >, // zero_plus< sequence< spaces_and_comments, exactly<','>, spaces_and_comments, alternatives< ie_keyword_arg, value_schema, string_constant, interpolant, number, identifier, delimited_by<'(', ')', true> > > > >(src); // } const char* ie_keyword_arg(const char* src) { return sequence< alternatives< variable, identifier_schema, identifier >, spaces_and_comments, exactly<'='>, spaces_and_comments, alternatives< variable, identifier_schema, identifier, number, hex > >(src); } // Path matching functions. const char* folder(const char* src) { return sequence< zero_plus< any_char_except<'/'> >, exactly<'/'> >(src); } const char* folders(const char* src) { return zero_plus< folder >(src); } const char* chunk(const char* src) { char inside_str = 0; const char* p = src; size_t depth = 0; while (true) { if (!*p) { return 0; } else if (!inside_str && (*p == '"' || *p == '\'')) { inside_str = *p; } else if (*p == inside_str && *(p-1) != '\\') { inside_str = 0; } else if (*p == '(' && !inside_str) { ++depth; } else if (*p == ')' && !inside_str) { if (depth == 0) return p; else --depth; } ++p; } // unreachable return 0; } // follow the CSS spec more closely and see if this helps us scan URLs correctly const char* NL(const char* src) { return alternatives< exactly<'\n'>, sequence< exactly<'\r'>, exactly<'\n'> >, exactly<'\r'>, exactly<'\f'> >(src); } const char* H(const char* src) { return std::isxdigit(*src) ? src+1 : 0; } const char* unicode(const char* src) { return sequence< exactly<'\\'>, between<H, 1, 6>, optional< class_char<url_space_chars> > >(src); } const char* ESCAPE(const char* src) { return alternatives< unicode, class_char<escape_chars> >(src); } const char* url(const char* src) { // using (more or less) the algorithm described at this url: // http://www.w3.org/TR/css3-syntax/#consume-a-url-token const char* pos = src; pos = zero_plus<spaces>(pos); if (*pos == '"' || *pos == '\'') return string_constant(pos); // let the parser handle the rparen while (*pos != ')') { if (space(pos)) { ++pos; continue; } if (*pos == '\\') { pos = ESCAPE(pos); if (!pos) return 0; // invalid escape sequence continue; } if (*pos == '"' || *pos == '\'' || *pos == '(') return 0; ++pos; } return pos; } } } <file_sep>/libsass/sass.h #ifndef SASS #define SASS #include <stddef.h> #include <stdbool.h> #include "sass_values.h" #include "sass_functions.h" #ifdef __cplusplus extern "C" { #endif // Different render styles enum Sass_Output_Style { SASS_STYLE_NESTED, SASS_STYLE_EXPANDED, SASS_STYLE_COMPACT, SASS_STYLE_COMPRESSED }; // Some convenient string helper function char* sass_string_quote (const char *str, const char quotemark); char* sass_string_unquote (const char *str); #ifdef __cplusplus } #endif #endif<file_sep>/libsass/sass_functions.h #ifndef SASS_C_FUNCTIONS #define SASS_C_FUNCTIONS #include <stddef.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif // Forward declaration struct Sass_C_Import_Descriptor; // Typedef defining the custom importer callback typedef struct Sass_C_Import_Descriptor (*Sass_C_Import_Callback); // Typedef defining the importer c function prototype typedef struct Sass_Import** (*Sass_C_Import_Fn) (const char* parentPath, const char* importedPath, void* cookie); // Creators for custom importer callback (with some additional pointer) // The pointer is mostly used to store the callback into the actual binding Sass_C_Import_Callback sass_make_importer (Sass_C_Import_Fn, void* cookie); // Getters for import function descriptors Sass_C_Import_Fn sass_import_get_function (Sass_C_Import_Callback fn); void* sass_import_get_cookie (Sass_C_Import_Callback fn); // Creator for sass custom importer return argument list struct Sass_Import** sass_make_import_list (size_t length); // Creator for a single import entry returned by the custom importer inside the list struct Sass_Import* sass_make_import_entry (const char* path, char* source, char* srcmap); // Setters to insert an entry into the import list (you may also use [] access directly) // Since we are dealing with pointers they should have a guaranteed and fixed size void sass_import_set_list_entry (struct Sass_Import** list, size_t idx, struct Sass_Import* entry); struct Sass_Import* sass_import_get_list_entry (struct Sass_Import** list, size_t idx); // Getters for import entry const char* sass_import_get_path (struct Sass_Import*); const char* sass_import_get_source (struct Sass_Import*); const char* sass_import_get_srcmap (struct Sass_Import*); // Explicit functions to take ownership of these items // The property on our struct will be reset to NULL char* sass_import_take_source (struct Sass_Import*); char* sass_import_take_srcmap (struct Sass_Import*); // Deallocator for associated memory (incl. entries) void sass_delete_import_list (struct Sass_Import**); // Forward declaration struct Sass_C_Function_Descriptor; // Typedef defining null terminated list of custom callbacks typedef struct Sass_C_Function_Descriptor* (*Sass_C_Function_List); typedef struct Sass_C_Function_Descriptor (*Sass_C_Function_Callback); // Typedef defining custom function prototype and its return value type typedef union Sass_Value*(*Sass_C_Function) (union Sass_Value*, void *cookie); // Creators for sass function list and function descriptors Sass_C_Function_List sass_make_function_list (size_t length); Sass_C_Function_Callback sass_make_function (const char* signature, Sass_C_Function fn, void* cookie); // Getters for custom function descriptors const char* sass_function_get_signature (Sass_C_Function_Callback fn); Sass_C_Function sass_function_get_function (Sass_C_Function_Callback fn); void* sass_function_get_cookie (Sass_C_Function_Callback fn); #ifdef __cplusplus } #endif #endif <file_sep>/libsass/Makefile CC ?= cc CXX ?= g++ RM ?= rm -f MKDIR ?= mkdir -p CFLAGS = -Wall -fPIC -g $(EXTRA_CFLAGS) CXXFLAGS = -std=c++0x -Wall -fPIC -g $(EXTRA_CXXFLAGS) LDFLAGS = -fPIC $(EXTRA_LDFLAGS) ifneq (,$(findstring /cygdrive/,$(PATH))) UNAME := Cygwin else ifneq (,$(findstring WINDOWS,$(PATH))) UNAME := Windows else UNAME := $(shell uname -s) endif endif ifeq ($(UNAME),Darwin) CFLAGS += -stdlib=libc++ CXXFLAGS += -stdlib=libc++ endif ifeq (,$(PREFIX)) ifeq (,$(TRAVIS_BUILD_DIR)) PREFIX = /usr/local else PREFIX = $(TRAVIS_BUILD_DIR) endif endif SASS_SASSC_PATH ?= sassc SASS_SPEC_PATH ?= sass-spec SASS_SPEC_SPEC_DIR ?= spec SASSC_BIN = $(SASS_SASSC_PATH)/bin/sassc RUBY_BIN = ruby SOURCES = \ ast.cpp \ base64vlq.cpp \ bind.cpp \ constants.cpp \ context.cpp \ contextualize.cpp \ copy_c_str.cpp \ error_handling.cpp \ eval.cpp \ expand.cpp \ extend.cpp \ file.cpp \ functions.cpp \ inspect.cpp \ node.cpp \ json.cpp \ output_compressed.cpp \ output_nested.cpp \ parser.cpp \ prelexer.cpp \ remove_placeholders.cpp \ sass.cpp \ sass_util.cpp \ sass_values.cpp \ sass_context.cpp \ sass_functions.cpp \ sass_interface.cpp \ sass2scss.cpp \ source_map.cpp \ to_c.cpp \ to_string.cpp \ units.cpp \ utf8_string.cpp \ util.cpp CSOURCES = cencode.c OBJECTS = $(SOURCES:.cpp=.o) COBJECTS = $(CSOURCES:.c=.o) DEBUG_LVL ?= NONE ifneq ($(BUILD), shared) BUILD = static endif all: $(BUILD) debug: $(BUILD) debug-static: LDFLAGS := -g debug-static: CFLAGS := -g -DDEBUG -DDEBUG_LVL="$(DEBUG_LVL)" $(filter-out -O2,$(CFLAGS)) debug-static: CXXFLAGS := -g -DDEBUG -DDEBUG_LVL="$(DEBUG_LVL)" $(filter-out -O2,$(CXXFLAGS)) debug-static: static debug-shared: LDFLAGS := -g debug-shared: CFLAGS := -g -DDEBUG -DDEBUG_LVL="$(DEBUG_LVL)" $(filter-out -O2,$(CFLAGS)) debug-shared: CXXFLAGS := -g -DDEBUG -DDEBUG_LVL="$(DEBUG_LVL)" $(filter-out -O2,$(CXXFLAGS)) debug-shared: shared static: lib/libsass.a shared: lib/libsass.so lib/libsass.a: $(COBJECTS) $(OBJECTS) $(MKDIR) lib $(AR) rvs $@ $(COBJECTS) $(OBJECTS) lib/libsass.so: $(COBJECTS) $(OBJECTS) $(MKDIR) lib $(CXX) -shared $(LDFLAGS) -o $@ $(COBJECTS) $(OBJECTS) %.o: %.c $(CC) $(CFLAGS) -c -o $@ $< %.o: %.cpp $(CXX) $(CXXFLAGS) -c -o $@ $< %: %.o static $(CXX) $(CXXFLAGS) -o $@ $+ $(LDFLAGS) install: install-$(BUILD) install-static: lib/libsass.a $(MKDIR) $(DESTDIR)$(PREFIX)\/lib/ install -pm0755 $< $(DESTDIR)$(PREFIX)/$< install-shared: lib/libsass.so $(MKDIR) $(DESTDIR)$(PREFIX)\/lib/ install -pm0755 $< $(DESTDIR)$(PREFIX)/$< $(SASSC_BIN): $(BUILD) cd $(SASS_SASSC_PATH) && $(MAKE) test: $(SASSC_BIN) $(RUBY_BIN) $(SASS_SPEC_PATH)/sass-spec.rb -c $(SASSC_BIN) -s $(LOG_FLAGS) $(SASS_SPEC_PATH)/$(SASS_SPEC_SPEC_DIR) test_build: $(SASSC_BIN) $(RUBY_BIN) $(SASS_SPEC_PATH)/sass-spec.rb -c $(SASSC_BIN) -s --ignore-todo $(LOG_FLAGS) $(SASS_SPEC_PATH)/$(SASS_SPEC_SPEC_DIR) test_issues: $(SASSC_BIN) $(RUBY_BIN) $(SASS_SPEC_PATH)/sass-spec.rb -c $(SASSC_BIN) $(LOG_FLAGS) $(SASS_SPEC_PATH)/spec/issues clean: $(RM) $(COBJECTS) $(OBJECTS) lib/*.a lib/*.la lib/*.so .PHONY: all debug debug-static debug-shared static shared install install-static install-shared clean <file_sep>/spec/lib/sass_spec/test.rb require 'minitest' def run_spec_test(test_case, options = {}) if options[:skip_todo] && test_case.todo? skip "Skipped todo" end assert test_case.input_path.readable?, "Input #{test_case.input_path} file does not exist" assert test_case.expected_path.readable?, "Expected #{test_case.expected_path} file does not exist" output, error, status = test_case.output if status != 0 msg = "Command `#{options[:sass_executable]}` did not complete:\n\n#{error}" if options[:skip] raise msg end puts msg exit 4 end if options[:unexpected_pass] && test_case.todo? && (test_case.expected == output) raise "#{test_case.input_path} passed a test we expected it to fail" end assert_equal test_case.expected, output, "Expected did not match output" end # Holder to put and run test cases class SassSpec::Test < Minitest::Test parallelize_me! def self.create_tests(test_cases, options = {}) test_cases[0..options[:limit]].each do |test_case| define_method('test__' << test_case.name) do run_spec_test(test_case, options) end end end end
aa811186f3bbbe306220139918b73988f299fcb3
[ "Ruby", "Makefile", "C", "Go", "C++" ]
23
C++
ry/scss.go
5eba8c06d13d6f4c6005f7e4175955fda12165e4
d1d894ebdbea1118ee4086e267a9db846504eacf
refs/heads/master
<repo_name>joeljosephjin/lamaml-l2l<file_sep>/run_cuda.sh #!/bin/bash # IMGNET='--data_path data/tiny-imagenet-200/ --log_every 100 --dataset tinyimagenet --cuda --log_dir logs/' # cuda-ed IMGNET='--data_path data/tiny-imagenet-200/ --log_every 100 --dataset tinyimagenet --log_dir logs/ --cuda' SEED=0 ##### La-MAML ##### TinyImageNet Dataset Single-Pass python3 main.py $IMGNET --model lamaml_cifar --expt_name lamaml --memories 400 --batch_size 10 --replay_batch_size 10 --n_epochs 1 \ --opt_lr 0.4 --alpha_init 0.1 --opt_wt 0.1 --glances 2 --loader class_incremental_loader --increment 5 \ --arch "pc_cnn" --cifar_batches 5 --learn_lr --log_every 3125 --second_order --class_order random \ --seed $SEED --grad_clip_norm 1.0 --calc_test_accuracy --validation 0.003 <file_sep>/run_mnist.sh # ROT="--n_layers 2 --n_hiddens 100 --data_path data/ --log_every 100 --samples_per_task 1000 --dataset mnist_rotations --cuda --log_dir logs/" ROT="--n_layers 2 --n_hiddens 100 --data_path data/ --log_every 100 --samples_per_task 1000 --dataset mnist_rotations --log_dir logs/" SEED=0 #lamaml ROTATION MNIST DATASETS python3 main.py $ROT --model lamaml --memories 200 --batch_size 10 --replay_batch_size 10 --n_epochs 1 --glances 5 --opt_lr 0.3 \ --alpha_init 0.15 --learn_lr --use_old_task_memory --seed $SEED<file_sep>/README.md # lamaml-l2l Trying to implement La-MAML in Learn2Learn library framework. ``` Set seed 0 /usr/local/lib/python3.6/dist-packages/torch/nn/modules/container.py:434: UserWarning: Setting attributes on ParameterList is not supported. warnings.warn("Setting attributes on ParameterList is not supported.") Task: 0 | Epoch: 1/1 | Iter: 4 | Loss: 2.043 | Acc: Total: 0.10325 Current Task: 0.1072 : 100% 5/5 [00:01<00:00, 2.64it/s] Task: 1 | Epoch: 1/1 | Iter: 4 | Loss: 1.464 | Acc: Total: 0.18083 Current Task: 0.3208 : 100% 5/5 [00:01<00:00, 2.63it/s] Task: 2 | Epoch: 1/1 | Iter: 4 | Loss: 1.886 | Acc: Total: 0.22473 Current Task: 0.5368 : 100% 5/5 [00:01<00:00, 2.62it/s] Task: 3 | Epoch: 1/1 | Iter: 4 | Loss: 1.294 | Acc: Total: 0.23533 Current Task: 0.4319 : 100% 5/5 [00:01<00:00, 2.56it/s] Task: 4 | Epoch: 1/1 | Iter: 4 | Loss: 1.007 | Acc: Total: 0.28168 Current Task: 0.4289 : 100% 5/5 [00:01<00:00, 2.58it/s] Task: 5 | Epoch: 1/1 | Iter: 4 | Loss: 1.02 | Acc: Total: 0.31133 Current Task: 0.4567 : 100% 5/5 [00:01<00:00, 2.58it/s] Task: 6 | Epoch: 1/1 | Iter: 4 | Loss: 1.244 | Acc: Total: 0.34235 Current Task: 0.441 : 100% 5/5 [00:01<00:00, 2.60it/s] Task: 7 | Epoch: 1/1 | Iter: 4 | Loss: 0.96 | Acc: Total: 0.35949 Current Task: 0.4456 : 100% 5/5 [00:01<00:00, 2.54it/s] Task: 8 | Epoch: 1/1 | Iter: 4 | Loss: 1.025 | Acc: Total: 0.37889 Current Task: 0.3512 : 100% 5/5 [00:01<00:00, 2.58it/s] Task: 9 | Epoch: 1/1 | Iter: 4 | Loss: 1.346 | Acc: Total: 0.40422 Current Task: 0.3211 : 100% 5/5 [00:01<00:00, 2.58it/s] Task: 10 | Epoch: 1/1 | Iter: 4 | Loss: 1.0 | Acc: Total: 0.43811 Current Task: 0.3904 : 100% 5/5 [00:01<00:00, 2.59it/s] Task: 11 | Epoch: 1/1 | Iter: 4 | Loss: 0.824 | Acc: Total: 0.46452 Current Task: 0.3172 : 100% 5/5 [00:01<00:00, 2.54it/s] Task: 12 | Epoch: 1/1 | Iter: 4 | Loss: 0.625 | Acc: Total: 0.48317 Current Task: 0.3543 : 100% 5/5 [00:01<00:00, 2.58it/s] Task: 13 | Epoch: 1/1 | Iter: 4 | Loss: 0.826 | Acc: Total: 0.5113 Current Task: 0.3383 : 100% 5/5 [00:01<00:00, 2.57it/s] Task: 14 | Epoch: 1/1 | Iter: 4 | Loss: 0.687 | Acc: Total: 0.53477 Current Task: 0.3236 : 100% 5/5 [00:01<00:00, 2.57it/s] Task: 15 | Epoch: 1/1 | Iter: 4 | Loss: 1.28 | Acc: Total: 0.55233 Current Task: 0.2568 : 100% 5/5 [00:01<00:00, 2.54it/s] Task: 16 | Epoch: 1/1 | Iter: 4 | Loss: 0.798 | Acc: Total: 0.57987 Current Task: 0.298 : 100% 5/5 [00:01<00:00, 2.57it/s] Task: 17 | Epoch: 1/1 | Iter: 4 | Loss: 1.025 | Acc: Total: 0.59714 Current Task: 0.3817 : 100% 5/5 [00:01<00:00, 2.57it/s] Task: 18 | Epoch: 1/1 | Iter: 4 | Loss: 0.982 | Acc: Total: 0.63528 Current Task: 0.3947 : 100% 5/5 [00:01<00:00, 2.54it/s] Task: 19 | Epoch: 1/1 | Iter: 4 | Loss: 1.141 | Acc: Total: 0.64562 Current Task: 0.3527 : 100% 5/5 [00:01<00:00, 2.54it/s] ####Final Validation Accuracy#### Final Results:- Total Accuracy: 0.6604299545288086 Individual Accuracy: [tensor(0.6190), tensor(0.6631), tensor(0.6915), tensor(0.7214), tensor(0.7241), tensor(0.7297), tensor(0.7309), tensor(0.7206), tensor(0.7257), tensor(0.7163), tensor(0.7133), tensor(0.6859), tensor(0.6777), tensor(0.6678), tensor(0.6570), tensor(0.6263), tensor(0.6082), tensor(0.5797), tensor(0.5336), tensor(0.4168)] logs//lamaml/test_lamaml-2020-12-28_13-51-14-6383/0/results: {'expt_name': 'test_lamaml', 'model': 'lamaml', 'arch': 'linear', 'n_hiddens': 100, 'n_layers': 2, 'xav_init': False, 'glances': 5, 'n_epochs': 1, 'batch_size': 10, 'replay_batch_size': 10.0, 'memories': 200, 'lr': 0.001, 'cuda': False, 'seed': 0, 'log_every': 100, 'log_dir': 'logs//lamaml/test_lamaml-2020-12-28_13-51-14-6383/0', 'tf_dir': 'logs//lamaml/test_lamaml-2020-12-28_13-51-14-6383/0/tfdir', 'calc_test_accuracy': False, 'data_path': 'data/', 'loader': 'task_incremental_loader', 'samples_per_task': 50, 'shuffle_tasks': False, 'classes_per_it': 4, 'iterations': 5000, 'dataset': 'mnist_rotations', 'workers': 3, 'validation': 0.0, 'class_order': 'old', 'increment': 5, 'test_batch_size': 100000, 'opt_lr': 0.3, 'opt_wt': 0.1, 'alpha_init': 0.15, 'learn_lr': True, 'sync_update': False, 'grad_clip_norm': 2.0, 'cifar_batches': 3, 'use_old_task_memory': True, 'second_order': False, 'n_memories': 0, 'memory_strength': 0, 'steps_per_sample': 1, 'gamma': 1.0, 'beta': 1.0, 's': 1, 'batches_per_example': 1, 'bgd_optimizer': 'bgd', 'optimizer_params': '{}', 'train_mc_iters': 5, 'std_init': 0.05, 'mean_eta': 1, 'fisher_gamma': 0.95} # val: 0.455 0.660 0.205 0.259 # 55.097007274627686 ```
4242cf2fb216e9cfb58cdfae3b7b12bf660849ae
[ "Markdown", "Shell" ]
3
Shell
joeljosephjin/lamaml-l2l
121d0e9887f12236c75e57f68d089c29779f470f
2240ec5f23c3abbce94f438185bf99cf4d99695d
refs/heads/master
<repo_name>ajaichemmanam/react-flask-socketio<file_sep>/socketapp/src/socketDashboard.js import React from "react"; import io from 'socket.io-client'; class Dashboard extends React.Component { state = { socketData: "", socketStatus:"On" } componentWillUnmount() { this.socket.close() console.log("component unmounted") } componentDidMount() { var sensorEndpoint = "http://localhost:5000" this.socket = io.connect(sensorEndpoint, { reconnection: true, // transports: ['websocket'] }); console.log("component mounted") this.socket.on("responseMessage", message => { this.setState({'socketData': message.temperature}) console.log("responseMessage", message) }) } handleEmit=()=>{ if(this.state.socketStatus==="On"){ this.socket.emit("message", {'data':'Stop Sending', 'status':'Off'}) this.setState({'socketStatus':"Off"}) } else{ this.socket.emit("message", {'data':'Start Sending', 'status':'On'}) this.setState({'socketStatus':"On"}) } console.log("Emit Clicked") } render() { return ( <React.Fragment> <div>Data: {this.state.socketData}</div> <div>Status: {this.state.socketStatus}</div> <div onClick={this.handleEmit}> Start/Stop</div> </React.Fragment> ) } } export default Dashboard;<file_sep>/README.md # react-flask-socketio This is a base code for testing websocket connection between python flask with socketio as Server and react Webapp as client Run server.py (localhost:5000) <br /> Go to socketapp, Open CMD and type "npm start" <br /> The data sent from python server is being displayed in the browser <br /> Click on "Start/Stop" to start or stop sending data from the server <br /> <br /> <br /> ## Requirements Requires Python 3+ <br /> npm i socket.io-client <br /> pip install Flask-SocketIO <br /> pip install gevent-websocket<file_sep>/server.py from flask_socketio import SocketIO, emit from flask import Flask from flask_cors import CORS from random import random from threading import Thread, Event from time import sleep from gevent.pywsgi import WSGIServer from geventwebsocket.handler import WebSocketHandler app = Flask(__name__) app.config['SECRET_KEY'] = 'secret!' socketio = SocketIO(app) CORS(app) # Server functionality for receiving and storing data from elsewhere, not related to the websocket #Data Generator Thread thread = Thread() thread_stop_event = Event() class DataThread(Thread): def __init__(self): self.delay = 0.5 super(DataThread, self).__init__() def dataGenerator(self): print("Initialising") try: while not thread_stop_event.isSet(): socketio.emit('responseMessage', {'temperature': round(random()*10, 3)}) sleep(self.delay) except KeyboardInterrupt: # kill() print("Keyboard Interrupt") def run(self): self.dataGenerator() # Handle the webapp connecting to the websocket @socketio.on('connect') def test_connect(): print('someone connected to websocket') emit('responseMessage', {'data': 'Connected! ayy'}) # need visibility of the global thread object global thread if not thread.isAlive(): print("Starting Thread") thread = DataThread() thread.start() # Handle the webapp connecting to the websocket, including namespace for testing @socketio.on('connect', namespace='/devices') def test_connect2(): print('someone connected to websocket!') emit('responseMessage', {'data': 'Connected devices! ayy'}) # Handle the webapp sending a message to the websocket @socketio.on('message') def handle_message(message): # print('someone sent to the websocket', message) print('Data', message["data"]) print('Status', message["status"]) global thread global thread_stop_event if (message["status"]=="Off"): if thread.isAlive(): thread_stop_event.set() else: print("Thread not alive") elif (message["status"]=="On"): if not thread.isAlive(): thread_stop_event.clear() print("Starting Thread") thread = DataThread() thread.start() else: print("Unknown command") # Handle the webapp sending a message to the websocket, including namespace for testing @socketio.on('message', namespace='/devices') def handle_message2(): print('someone sent to the websocket!') @socketio.on_error_default # handles all namespaces without an explicit error handler def default_error_handler(e): print('An error occured:') print(e) if __name__ == '__main__': # socketio.run(app, debug=False, host='0.0.0.0') http_server = WSGIServer(('',5000), app, handler_class=WebSocketHandler) http_server.serve_forever()
47fd1c10e6e30c52bc894c94c74947324da6cb42
[ "JavaScript", "Python", "Markdown" ]
3
JavaScript
ajaichemmanam/react-flask-socketio
b4d568d501c85a36d7c91bdaf5e8e4b18bda7d75
87a3ac098dc9b33b21d0b9b8631e3f61f744657a
refs/heads/main
<repo_name>kgweisman/dreams_mind_spirit<file_sep>/scripts_general/data_load.R # LOADING DATASETS FOR ALL STUDIES # study 1 ----- d1_scored <- read_csv("../data/sense_spirit_study1.csv") %>% mutate(country = factor(country, levels = levels_country), site = factor(site, levels = levels_site), religion = factor(religion, levels = levels_religion), researcher = factor(researcher, levels = levels_researcher)) contrasts(d1_scored$country) <- contrasts_country contrasts(d1_scored$site) <- contrasts_site contrasts(d1_scored$religion) <- contrasts_religion d1 <- read_csv("../data_byquestion/study1_byquestion.csv") %>% mutate(country = factor(country, levels = levels_country), site = factor(site, levels = levels_site), religion = factor(religion, levels = levels_religion), researcher = factor(researcher, levels = levels_researcher)) %>% filter(subject_id %in% d1_scored$subject_id) contrasts(d1$country) <- contrasts_country contrasts(d1$site) <- contrasts_site contrasts(d1$religion) <- contrasts_religion # study 2 ----- d2_scored <- read_csv("../data/sense_spirit_study2.csv") %>% mutate(country = factor(country, levels = levels_country), religion = factor(religion, levels = c("charismatic", "general population"))) contrasts(d2_scored$country) <- contrasts_country contrasts(d2_scored$religion) <- contrasts_religion d2 <- read_csv("../data_byquestion/d_spex.csv") %>% select(-X1) %>% rename(country = epi_ctry) %>% mutate(country = factor(country, levels = levels_country)) %>% filter(epi_subj %in% d2_scored$subject_id) # study 3 ----- d3_scored <- read_csv("../data/sense_spirit_study3.csv") %>% mutate(country = factor(country, levels = levels_country)) contrasts(d3_scored$country) <- contrasts_country d3 <- read_csv("../data_byquestion/packets123_data_byquestion_long.csv") %>% filter(packet == 1) %>% rename(country = ctry) %>% mutate(country = factor(country, levels = tolower(levels_country), labels = levels_country)) %>% filter(subj %in% d3_scored$subject_id) contrasts(d3$country) <- contrasts_country # study 4 ----- d4_scored <- read_csv("../data/sense_spirit_study4.csv") %>% mutate(country = factor(country, levels = levels_country)) contrasts(d4_scored$country) <- contrasts_country d4 <- read_csv("../data_byquestion/study4_byquestion.csv") %>% select(-X1) %>% rename(country = p7_ctry) %>% mutate(country = factor(country, levels = levels_country)) %>% filter(p7_subj %in% d4_scored$subject_id) contrasts(d4$country) <- contrasts_country <file_sep>/README.md # Dreams Authors: **<NAME>**, <NAME>, [<NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>, <NAME>], <NAME>. This repo includes analyses of the data related to dreams from the [Mind and Spirit Project](https://themindandspiritproject.stanford.edu/#Home). **Datasets** for each of the four studies are available [here](https://github.com/kgweisman/dreams_mind_spirit/tree/master/data). **Analysis scripts** are availalbe [here](https://github.com/kgweisman/dreams_mind_spirit/tree/master/analyses). To view the results of an analysis in an HTML file, download the R Notebook (extension: .nb.html) to a folder on your computer and re-open it (from that folder) in a web browser -- or use the [htmlpreview.github.com](htmlpreview.github.com) links provided below. To view and manipulate the code, download the R Markdown file (extension: .Rmd) and open it in RStudio. In Study 1, adults with strong religious commitments and faith practices were interviewed in depth about their spiritual experiences and their understanding of the mind by experienced ethnographers. In Study 2, adults from the general population, as well as a smaller sample of charismatic evangelical Christians, were interviewed briefly about their spiritual experiences and their understanding of the mind. In Study 3, college undergraduates completed a survey consisting of one measure of absorption and two measures of spiritual experience (a “Spiritual Events” inventory based on Studies 1 and 2; and a modified version of the Daily Spiritual Experiences scale [Underwood & Teresi, 2002]). In Study 4, college undergraduates completed a survey consisting of nine measures, including two indices of spiritual experience (Spiritual Events, based on Studies 1-3; and the Daily Spiritual Experiences scale [Underwood & Teresi, 2002]). <file_sep>/analyses/dreams_analyses.Rmd --- title: "Dreams in the Mind & Spirit Project" subtitle: <NAME>, <NAME>, ... & <NAME> output: html_notebook: code_folding: hide toc: yes toc_float: yes pdf_document: toc: yes --- ```{r setup, include = F} knitr::opts_chunk$set(message = F, warning = FALSE, include = F) ``` ```{r, message = F} source("../scripts_general/dependencies.R") source("../scripts_general/custom_funs.R") source("../scripts_general/var_recode_contrast.R") source("../scripts_general/data_load.R") ``` # Study 1 In Study 1, adults with strong religious commitments and faith practices were interviewed in depth about their spiritual experiences and their understanding of the mind by experienced ethnographers. The "Spiritual Curiosity" interview included one question about experiencing God* through dreams (`godviadreams`) and one question about experiencing sleep paralysis (`sleepparalysis`). ```{r, fig.width = 8, fig.asp = 1} d1 %>% select(study, researcher, country, site, religion, subject_id, godviapeople:seethingscornereye) %>% distinct() %>% gather(question, response, c(godviapeople:seethingscornereye)) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_wrap(~ question) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.2, 0.4, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 1 (Spiritual Curiosity Interview)", x = "Country", y = "Percent of participants") ``` ```{r} d1 %>% select(study, researcher, country, site, religion, subject_id, godviapeople:seethingscornereye) %>% distinct() %>% gather(question, response, c(godviapeople:seethingscornereye)) %>% group_by(country, question) %>% summarise(mean = mean(response, na.rm = T)) %>% ungroup() %>% mutate(question_cat = recode_factor(question, "godviadreams" = "dreams", "sleepparalysis" = "sleep paralysis", .default = "other")) %>% ggplot(aes(x = country, y = mean, color = question_cat, size = question_cat)) + geom_pointrange(data = . %>% filter(question_cat == "other") %>% group_by(country) %>% multi_boot_standard(col = "mean") %>% ungroup(), aes(ymin = ci_lower, ymax = ci_upper, y = mean, color = NULL, size = NULL)) + geom_line(aes(group = question)) + geom_point(data = . %>% filter(question_cat != "other"), size = 3) + scale_y_continuous(labels = scales::label_percent()) + scale_color_manual(values = c("red", "orange", "black")) + scale_size_manual(values = c(1, 1, 0.1)) + theme_minimal() + guides(color = guide_legend(override.aes = list(size = 0.5))) + labs(title = "Study 1 (Spiritual Curiosity Interview)", x = "Country", y = "Percent of participants", color = "Question", size = "Question") ``` ```{r, include = T} d1 %>% distinct(study, researcher, country, site, religion, subject_id, godviadreams, sleepparalysis) %>% gather(question, response, c(godviadreams, sleepparalysis)) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "godviadreams" = "dreams", "sleepparalysis" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.2, 0.4, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 1 (Spiritual Curiosity Interview)", x = "Country", y = "Percent of participants") ``` ```{r, fig.width = 4, fig.asp = 1.2, include = T} d1 %>% distinct(study, researcher, country, site, religion, subject_id, godviadreams, sleepparalysis) %>% gather(question, response, c(godviadreams, sleepparalysis)) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(interaction(site, religion, sep = " ") ~ recode_factor(question, "godviadreams" = "dreams", "sleepparalysis" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% filter(!is.na(response)) %>% count(country, site, religion, question), aes(label = paste0("n=", n), y = 1.1, alpha = NULL, fill = NULL), color = "black", size = 3, show.legend = F) + geom_text(data = . %>% count(country, site, religion, question, response) %>% complete(response, nesting(country, site, religion, question), fill = list(n = 0)) %>% group_by(country, site, religion, question) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, site, religion, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent(), breaks = seq(0, 1, 0.25)) + scale_alpha_manual(values = c(0, 0.2, 0.4, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 1 (Spiritual Curiosity Interview)", x = "Country", y = "Percent of participants") ``` ```{r} r1_godviadreams <- glm(godviadreams ~ country, d1 %>% distinct(study, researcher, country, site, religion, subject_id, godviadreams) %>% mutate(godviadreams = case_when(godviadreams > 0 ~ 1, TRUE ~ godviadreams)), family = "binomial") parameters(r1_godviadreams) ``` ```{r} r1_sleepparalysis <- glm(sleepparalysis ~ country, d1 %>% distinct(study, researcher, country, site, religion, subject_id, sleepparalysis) %>% mutate(sleepparalysis = case_when(sleepparalysis > 0 ~ 1, TRUE ~ sleepparalysis)), family = "binomial") parameters(r1_sleepparalysis) ``` \newpage # Study 2 In Study 2, adults from the general population, as well as a smaller sample of charismatic evangelical Christians, were interviewed briefly about their spiritual experiences and their understanding of the mind. As part of the "Spiritual Events" scale, these interviews included 1 question about dreams ("Some people say that the divine or supernatural sends them dreams. Has that happened to you?, `epi_2_02`) and 1 question about sleep paralysis ("Some people have had the experience of waking up but being unable to move [this is sometimes called sleep paralysis]. Has this ever happened to you?", `epi_2_20`). ```{r} d2 %>% filter(question %in% c("epi_2_01", "epi_2_02", "epi_2_03", "epi_2_04", "epi_2_05", "epi_2_06", "epi_2_07", "epi_2_08", "epi_2_09", "epi_2_10", "epi_2_11", "epi_2_12", "epi_2_13", "epi_2_14", "epi_2_15", "epi_2_16", "epi_2_17", "epi_2_18", "epi_2_19", "epi_2_20", "epi_2_21", "epi_2_22", "epi_2_23")) %>% group_by(country, question) %>% summarise(mean = mean(response, na.rm = T)) %>% ungroup() %>% mutate(question_cat = recode_factor(question, "epi_2_02" = "dreams", "epi_2_20" = "sleep paralysis", .default = "other")) %>% ggplot(aes(x = country, y = mean, color = question_cat, size = question_cat)) + geom_pointrange(data = . %>% filter(question_cat == "other") %>% group_by(country) %>% multi_boot_standard(col = "mean", na.rm = T) %>% ungroup(), aes(ymin = ci_lower, ymax = ci_upper, y = mean, color = NULL, size = NULL)) + geom_line(aes(group = question)) + geom_point(data = . %>% filter(question_cat != "other"), size = 3) + scale_y_continuous(labels = scales::label_percent()) + scale_color_manual(values = c("red", "orange", "black")) + scale_size_manual(values = c(1, 1, 0.1)) + theme_minimal() + guides(color = guide_legend(override.aes = list(size = 0.5))) + labs(title = "Study 2 (Spiritual Epidemiology)", x = "Country", y = "Percent of participants", color = "Question", size = "Question") ``` ```{r, include = T} d2 %>% distinct(country, epi_subj, question, response, question_text) %>% filter(question %in% c("epi_2_02", "epi_2_20")) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "epi_2_02" = "dreams", "epi_2_20" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% count(country, question, question_text, response) %>% complete(response, nesting(country, question, question_text), fill = list(n = 0)) %>% group_by(country, question, question_text) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, question, question_text, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.2, 0.4, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 2 (Spiritual Epidemiology)", x = "Country", y = "Percent of participants") ``` ```{r, fig.width = 4, fig.asp = 1, include = T} d2 %>% left_join(d2_scored %>% distinct(subject_id, religion) %>% rename(epi_subj = subject_id)) %>% distinct(country, religion, epi_subj, question, response, question_text) %>% filter(question %in% c("epi_2_02", "epi_2_20")) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(religion ~ recode_factor(question, "epi_2_02" = "dreams", "epi_2_20" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% filter(!is.na(response)) %>% count(country, religion, question), aes(label = paste0("n=", n), y = 1.1, alpha = NULL, fill = NULL), color = "black", size = 3, show.legend = F) + geom_text(data = . %>% count(country, religion, question, question_text, response) %>% complete(response, nesting(country, religion, question, question_text), fill = list(n = 0)) %>% group_by(country, religion, question, question_text) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, religion, question, question_text, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent(), breaks = seq(0, 1, 0.25)) + scale_alpha_manual(values = c(0, 0.2, 0.4, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 2 (Spiritual Epidemiology)", x = "Country", y = "Percent of participants") ``` ```{r} r1_epi_2_02 <- glm(response ~ country, d2 %>% filter(question == "epi_2_02") %>% distinct(country, epi_subj, response) %>% mutate(response = case_when(response > 0 ~ 1, TRUE ~ response)), family = "binomial") parameters(r1_epi_2_02) ``` ```{r} r1_epi_2_20 <- glm(response ~ country, d2 %>% filter(question == "epi_2_20") %>% distinct(country, epi_subj, response) %>% mutate(response = case_when(response > 0 ~ 1, TRUE ~ response)), family = "binomial") parameters(r1_epi_2_20) ``` \newpage # Study 3 In Study 3, college undergraduates completed a survey consisting of one measure of absorption and two measures of spiritual experience (a “Spiritual Events” inventory based on Studies 1 and 2; and a modified version of the Daily Spiritual Experiences scale). As part of the "Spiritual Events" scale, these interviews included 1 question about dreams ("Have you ever had a dream you felt was sent by God or a spirit?", `spev_09`) and 1 question about sleep paralysis ("Have you ever had the experience of being awake but unable to move?", `spev_18`). ```{r} d3 %>% filter(grepl("spev", question), !grepl("attn", question)) %>% group_by(country, question) %>% summarise(mean = mean(response, na.rm = T)) %>% ungroup() %>% mutate(question_cat = recode_factor(question, "spev_09" = "dreams", "spev_18" = "sleep paralysis", .default = "other")) %>% ggplot(aes(x = country, y = mean, color = question_cat, size = question_cat)) + geom_pointrange(data = . %>% filter(question_cat == "other") %>% group_by(country) %>% multi_boot_standard(col = "mean", na.rm = T) %>% ungroup(), aes(ymin = ci_lower, ymax = ci_upper, y = mean, color = NULL, size = NULL)) + geom_line(aes(group = question)) + geom_point(data = . %>% filter(question_cat != "other"), size = 3) + scale_y_continuous(labels = scales::label_percent()) + scale_color_manual(values = c("red", "orange", "black")) + scale_size_manual(values = c(1, 1, 0.1)) + theme_minimal() + guides(color = guide_legend(override.aes = list(size = 0.5))) + labs(title = "Study 3 (Packet 1)", x = "Country", y = "Percent of participants", color = "Question", size = "Question") ``` ```{r, include = T} d3 %>% distinct(country, subj, question, response) %>% filter(question %in% c("spev_09", "spev_18")) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 1, 2, 3, 4), labels = c("NA", "never", "once", "several times", "fairly often", "very often"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "spev_09" = "dreams", "spev_18" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% mutate(response = case_when( response %in% c("once", "several times", "fairly often", "very often") ~ 1, response == "never" ~ 0, TRUE ~ NA_real_)) %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == 1) %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.1, 0.5, 0.6, 0.7, 0.8, 0.9)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 3 (Packet 1)", x = "Country", y = "Percent of participants") ``` ```{r} r1_spev_09 <- clm(response ~ country, data = d3 %>% filter(question == "spev_09") %>% distinct(country, subj, response) %>% mutate(response = factor(response))) parameters(r1_spev_09) ``` ```{r} r1_spev_18 <- clm(response ~ country, data = d3 %>% filter(question == "spev_18") %>% distinct(country, subj, response) %>% mutate(response = factor(response))) parameters(r1_spev_18) ``` \newpage # Study 4 In Study 4, college undergraduates completed a survey consisting of nine measures, including two indices of porosity, the Absorption scale, two indices of spiritual experience, two indices of more secular extraordinary experience, and two control measures. As part of the "Spiritual Events" scale, this packet included 1 question about dreams ("Have you ever had a dream you felt was sent by God or a spirit?", `p7_se_dream.sent`) and 1 question about sleep paralysis ("Have you ever had the experience of being awake but unable to move?", `p7_se_slep.paralysis`). As part of the "Paranormal" scale, this packet also included 1 additional question about dreams ("I am completely convinced that I [have never had a/have had at least one] dream that came true and which (I believe) was not just a coincidence."; `p7_exsen_dream.true`). ```{r} d4 %>% select(p7_subj, country, starts_with("p7_se_"), p7_exsen_dream.true) %>% select(-ends_with("_cat"), -contains("check"), -contains("total")) %>% gather(question, response, -c(p7_subj, country)) %>% group_by(country, question) %>% summarise(mean = mean(response, na.rm = T)/4) %>% ungroup() %>% mutate(question_cat = recode_factor(question, "p7_se_dream.sent" = "dreams", "p7_se_slep.paralysis" = "sleep paralysis", "p7_exsen_dream.true" = "dream come true", .default = "other")) %>% ggplot(aes(x = country, y = mean, color = question_cat, size = question_cat)) + geom_pointrange(data = . %>% filter(question_cat == "other") %>% group_by(country) %>% multi_boot_standard(col = "mean", na.rm = T) %>% ungroup(), aes(ymin = ci_lower, ymax = ci_upper, y = mean, color = NULL, size = NULL)) + geom_line(aes(group = question)) + geom_point(data = . %>% filter(question_cat != "other"), size = 3) + scale_color_manual(values = c("red", "orange", "blue", "black")) + scale_size_manual(values = c(1, 1, 1, 0.1)) + theme_minimal() + guides(color = guide_legend(override.aes = list(size = 0.5))) + labs(title = "Study 4 (Packet 7)", x = "Country", y = "Average rating", color = "Question", size = "Question") ``` ```{r} d4 %>% select(p7_subj, country, starts_with("p7_se_"), p7_exsen_dream.true) %>% select(-ends_with("_cat"), -contains("check"), -contains("total")) %>% gather(question, response, -c(p7_subj, country)) %>% group_by(country, question) %>% mutate(response = ifelse(response > 0, 1, response)) %>% summarise(mean = mean(response, na.rm = T)) %>% ungroup() %>% mutate(question_cat = recode_factor(question, "p7_se_dream.sent" = "dreams", "p7_se_slep.paralysis" = "sleep paralysis", "p7_exsen_dream.true" = "dream come true", .default = "other")) %>% ggplot(aes(x = country, y = mean, color = question_cat, size = question_cat)) + geom_pointrange(data = . %>% filter(question_cat == "other") %>% group_by(country) %>% multi_boot_standard(col = "mean", na.rm = T) %>% ungroup(), aes(ymin = ci_lower, ymax = ci_upper, y = mean, color = NULL, size = NULL)) + geom_line(aes(group = question)) + geom_point(data = . %>% filter(question_cat != "other"), size = 3) + scale_y_continuous(labels = scales::label_percent()) + scale_color_manual(values = c("red", "orange", "blue", "black")) + scale_size_manual(values = c(1, 1, 1, 0.1)) + theme_minimal() + guides(color = guide_legend(override.aes = list(size = 0.5))) + labs(title = "Study 4 (Packet 7)", x = "Country", y = "Percentage of participants", color = "Question", size = "Question") ``` ```{r, include = T} d4 %>% select(country, p7_subj, p7_se_dream.sent, p7_se_slep.paralysis) %>% gather(question, response, c(p7_se_dream.sent, p7_se_slep.paralysis)) %>% distinct(country, p7_subj, question, response) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 1, 2, 3, 4), labels = c("NA", "never", "once", "several times", "fairly often", "very often"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "p7_se_dream.sent" = "dreams", "p7_se_slep.paralysis" = "sleep paralysis", "p7_exsen_dream.true" = "dream come true")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% mutate(response = case_when( response %in% c("once", "several times", "fairly often", "very often") ~ 1, response == "never" ~ 0, TRUE ~ NA_real_)) %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == 1) %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.1, 0.5, 0.6, 0.7, 0.8, 0.9)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 4 (Packet 7)", x = "Country", y = "Percent of participants") ``` ```{r, include = T} d4 %>% select(country, p7_subj, p7_exsen_dream.true) %>% gather(question, response, c(p7_exsen_dream.true)) %>% distinct(country, p7_subj, question, response) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 1), labels = c("NA", "no", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "p7_se_dream.sent" = "dreams", "p7_se_slep.paralysis" = "sleep paralysis", "p7_exsen_dream.true" = "dream come true")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.2, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 4 (Packet 7)", x = "Country", y = "Percent of participants") ``` ```{r} library(ordinal) ``` ```{r} r1_p7_se_dream.sent <- clm(p7_se_dream.sent ~ country, data = d4 %>% distinct(country, p7_subj, p7_se_dream.sent) %>% mutate(p7_se_dream.sent = factor(p7_se_dream.sent))) parameters(r1_p7_se_dream.sent) ``` ```{r} r1_p7_se_slep.paralysis <- clm(p7_se_slep.paralysis ~ country, data = d4 %>% distinct(country, p7_subj, p7_se_slep.paralysis) %>% mutate(p7_se_slep.paralysis = factor(p7_se_slep.paralysis))) parameters(r1_p7_se_slep.paralysis) ``` ```{r} r1_p7_exsen_dream.true <- glm(p7_exsen_dream.true ~ country, d4 %>% distinct(p7_subj, country, p7_exsen_dream.true), family = "binomial") parameters(r1_p7_exsen_dream.true) ``` \newpage # Studies 1-4: God* via dreams ```{r} g1 <- d1 %>% distinct(study, researcher, country, site, religion, subject_id, godviadreams) %>% gather(question, response, c(godviadreams)) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "godviadreams" = "dreams", "sleepparalysis" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.2, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 1", x = "Country", y = "Percent of participants") ``` ```{r} g2 <- d2 %>% distinct(country, epi_subj, question, response, question_text) %>% filter(question %in% c("epi_2_02")) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 0.5, 1), labels = c("NA", "no", "maybe", "yes"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "epi_2_02" = "dreams", "epi_2_20" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% count(country, question, question_text, response) %>% complete(response, nesting(country, question, question_text), fill = list(n = 0)) %>% group_by(country, question, question_text) %>% mutate(prop = n/sum(n)) %>% filter(response == "yes") %>% select(country, question, question_text, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.2, 0.4, 0.8)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 2", x = "Country", y = "Percent of participants") ``` ```{r} g3 <- d3 %>% distinct(country, subj, question, response) %>% filter(question %in% c("spev_09")) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 1, 2, 3, 4), labels = c("NA", "never", "once", "several times", "fairly often", "very often"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "spev_09" = "dreams", "spev_18" = "sleep paralysis")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% mutate(response = case_when( response %in% c("once", "several times", "fairly often", "very often") ~ 1, response == "never" ~ 0, TRUE ~ NA_real_)) %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == 1) %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.1, 0.5, 0.6, 0.7, 0.8, 0.9)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 3", x = "Country", y = "Percent of participants") ``` ```{r} g4 <- d4 %>% select(country, p7_subj, p7_se_dream.sent) %>% gather(question, response, c(p7_se_dream.sent)) %>% distinct(country, p7_subj, question, response) %>% mutate(response = factor(response, exclude = NULL, levels = c(NA, 0, 1, 2, 3, 4), labels = c("NA", "never", "once", "several times", "fairly often", "very often"))) %>% ggplot(aes(x = country, fill = country, alpha = response)) + facet_grid(~ recode_factor(question, "p7_se_dream.sent" = "dreams", "p7_se_slep.paralysis" = "sleep paralysis", "p7_exsen_dream.true" = "dream come true")) + geom_bar(stat = "count", position = "fill", color = "black", size = 0.2) + geom_text(data = . %>% mutate(response = case_when( response %in% c("once", "several times", "fairly often", "very often") ~ 1, response == "never" ~ 0, TRUE ~ NA_real_)) %>% count(country, question, response) %>% complete(response, nesting(country, question), fill = list(n = 0)) %>% group_by(country, question) %>% mutate(prop = n/sum(n)) %>% filter(response == 1) %>% select(country, question, prop), aes(label = paste0(round(prop, 2)*100, "%"), y = prop, alpha = NULL, fill = NULL), color = "black", nudge_y = -0.05, size = 3, show.legend = F) + scale_y_continuous(labels = scales::label_percent()) + scale_alpha_manual(values = c(0, 0.1, 0.5, 0.6, 0.7, 0.8, 0.9)) + scale_fill_brewer(palette = "Dark2") + theme_minimal() + guides(fill = guide_none(), alpha = guide_legend("Response")) + labs(title = "Study 4", x = "Country", y = "Percent of participants") ``` ```{r, fig.width = 6, fig.asp = 0.4, include = T} plot_grid(g1 + labs(x = NULL) + guides(alpha = guide_none()) + theme(strip.text = element_blank()), g2 + labs(x = NULL, y = NULL) + guides(alpha = guide_none()) + theme(strip.text = element_blank(), axis.text.y = element_blank()), g3 + labs(x = NULL, y = NULL) + guides(alpha = guide_none()) + theme(strip.text = element_blank(), axis.text.y = element_blank()), g4 + labs(x = NULL, y = NULL) + guides(alpha = guide_none()) + theme(strip.text = element_blank(), axis.text.y = element_blank()), nrow = 1, rel_widths = c(1, rep(0.85, 3))) ``` \newpage # Demographics ## Study 1 (Luhrmann, Weisman, et al., 2020, _PNAS_: Table S14) ```{r} d1_demo <- d1_scored %>% select(-contains("score")) %>% mutate(male = ifelse(grepl("male", tolower(subject_gender)) & !grepl("female", tolower(subject_gender)), 1, 0), female = ifelse(grepl("female", tolower(subject_gender)), 1, 0), subject_age = ifelse(subject_age > 120, NA_real_, subject_age), subject_hs = ifelse(grepl("yes", tolower(subject_hs)), 1, 0)) ``` ```{r, include = T} d1_demo %>% filter(!is.na(country), !is.na(site), !is.na(religion)) %>% mutate(site = factor(site, levels = c("urban", "rural"))) %>% group_by(country, site, religion) %>% summarise(n = n(), age_range = paste0(min(subject_age, na.rm = T), "-", max(subject_age, na.rm = T)), mean_age = mean(subject_age, na.rm = T), percent_male = mean(male, na.rm = T), percent_female = mean(female, na.rm = T), percent_hs = mean(subject_hs, na.rm = T), percent_special = mean(subject_specialrole, na.rm = T)) %>% ungroup() %>% # mutate_at(vars(starts_with("mean_")), funs(format(round(., 2), nsmall = 2))) %>% mutate_at(vars(starts_with("percent_")), funs(paste0(round(. * 100), "%"))) %>% rename(Country = country, Site = site, Religion = religion, `Age range` = age_range, `Mean age` = mean_age, `% male` = percent_male, `% female` = percent_female, `% attended high school` = percent_hs, `% serving a 'special role'` = percent_special) %>% kable(digits = 2, align = c(rep("l", 3), rep("r", 4))) %>% kable_styling(font_size = 16) # %>% # collapse_rows(1:2) ``` \newpage ## Study 2 (<NAME>, et al., 2020, _PNAS_: Table S15) ```{r} d2_demo <- d2_scored %>% select(-contains("score")) %>% mutate(male = ifelse(grepl("male", tolower(subject_gender)) & !grepl("female", tolower(subject_gender)), 1, 0), female = ifelse(grepl("female", tolower(subject_gender)), 1, 0), subject_age = ifelse(subject_age > 120, NA_real_, subject_age), # deal with subject_religion subject_religion = case_when( subject_religion %in% c("7th Day Adventist", "A little Catholicism, pray Jesus", "Apostolic", "Baptist", "Catholic", "Catholic 5 times a year, don't study bible but large part of family make up.", "Catholicism", "Christian", "Christian Baptist", "Christian, raised Catholic", "christianity", "Christianity", "Christianity - possibly Presbyterian / Catholic, Raised Pentecostal", "Christianity, nondenominational", "Christians", "Christiantity", "Church of Latter Day Saints", "Culturally LDS", "Episcopalian", "Grew up Catholic", "ICGC Cape Coast Branch, Christianity", "Jehovah Witness", "Jehovah's Witness", "LDS Latter Day Saints", "Methodist", "non denominational / Christian", "non-denominational", "Not specific type/denomination, parents bounced around, all Christian", "Orthodox Christian", "Pentecostal", "Pentecostal preacher", "Personal relationship w/ Jesus Christ", "Presbyterian", "Roman Catholic", "SDA (Christianity)", "Seventh Day Adventist Church", "True Jesus Church", "Unitarian Universalism", "United Methodist") ~ "Christian", subject_religion %in% c("Actually believe in Buddhism", "Buddhism", "Buddhism (believe)", "Buddhism / Ancestors (a little bit believe)", "Buddhism, incline to deism", "Buddhism. Practice and has been vegetarian for 20 years", "Buddhist", "Buddhist (interviewed @ church)", "Incline to Buddhism", "Studying Buddhism", "Vipassana Buddhism", "Wat <NAME>ong Kiang", "<NAME>", "<NAME>") ~ "Buddhist", # subject_religion %in% # c("Family - Orthodox Jew / Jewish", # "Judaism", "Orthodox Jewish") ~ "Jewish", subject_religion %in% c("Islam", "Islam, but not believe anything", "Islamic", "Islamic Religion", "Muslim") ~ "Muslim", # subject_religion %in% # c("Hinduism") ~ "Hindu", grepl("agnost", tolower(subject_religion)) | grepl("atheis", tolower(subject_religion)) | grepl("don't", tolower(subject_religion)) | grepl("none", tolower(subject_religion)) | tolower(subject_religion) %in% c("n/a", "no", tolower("No (ex - JW) Partner Christian - Possibly Korean Baptist"), "no religion", "no religion, finding one", "not really", tolower("Religion is a choice; I'm not interested in it.")) ~ "Agnostic/Atheist", subject_religion %in% c("missing data", "mdata", "NA") | is.na(subject_religion) ~ "Missing data", TRUE ~ "Other"), subject_urban_rural = recode(subject_urban_rural, "Urban" = 1, "Rural" = 0), religion = recode_factor(religion, "0" = "general pop.", "1" = "charismatic Chr."), agnostic_atheist = (subject_religion == "Agnostic/Atheist"), buddhist = (subject_religion == "Buddhist"), christian = (subject_religion == "Christian"), muslim = (subject_religion == "Muslim"), other = (subject_religion == "Other"), missing = (subject_religion == "Missing data")) ``` ```{r, include = T} d2_demo %>% group_by(country, religion) %>% summarise(n = n(), age_range = paste0(min(subject_age, na.rm = T), "-", max(subject_age, na.rm = T)), mean_age = mean(subject_age, na.rm = T), percent_male = mean(male, na.rm = T), percent_female = mean(female, na.rm = T), percent_urban = mean(subject_urban_rural, na.rm = T), percent_affr = mean(subject_afford, na.rm = T), mean_ses = mean(subject_ses, na.rm = T), mean_religiosity = mean(subject_religiosity, na.rm = T), percent_christian = mean(christian, na.rm = T), percent_agnostic_atheist = mean(agnostic_atheist, na.rm = T), percent_buddhist = mean(buddhist, na.rm = T), percent_muslim = mean(muslim, na.rm = T), percent_other = mean(other, na.rm = T), percent_missing = mean(missing, na.rm = T)) %>% ungroup() %>% # mutate_at(vars(starts_with("mean_")), funs(format(round(., 2), nsmall = 2))) %>% mutate_at(vars(starts_with("percent_")), funs(paste0(round(. * 100), "%"))) %>% rename(Country = country, Sample = religion, `Age range` = age_range, `Mean age` = mean_age, `% male` = percent_male, `% female` = percent_female, `% urban` = percent_urban, `% can afford` = percent_affr, `Mean SES` = mean_ses, `Mean religiosity` = mean_religiosity, `% Christian` = percent_christian, `% Agnostic/Atheist` = percent_agnostic_atheist, `% Buddhist` = percent_buddhist, `% Muslim` = percent_muslim, `% Other` = percent_other, `[% Missing data]` = percent_missing) %>% mutate(Country = factor(Country, levels = levels_country), Sample = factor(Sample, levels = c("general population", "charismatic"), labels = c("gen. pop.", "char. ev. Chr."))) %>% arrange(Country, Sample) %>% select(Country, Sample, n, `Age range`, `Mean age`, `% male`, `% female`, `Mean religiosity`, `% Christian`, `% Buddhist`, `% Muslim`, `% Other`, `% Agnostic/Atheist`, `[% Missing data]`, `% urban`, `% can afford`, `Mean SES`) %>% kable(digits = 2, align = c(rep("l", 2), rep("r", ncol(.) - 2))) %>% kable_styling(font_size = 16) # %>% # collapse_rows(1:2) ``` \newpage ## Study 3 (<NAME>, et al., 2020, _PNAS_: Table S16) ```{r} d3_demo <- d3_scored %>% select(-contains("score")) %>% mutate(male = ifelse(grepl("male", tolower(subject_gender)) & !grepl("female", tolower(subject_gender)), 1, 0), female = ifelse(grepl("female", tolower(subject_gender)), 1, 0), subject_age = ifelse(subject_age > 120, NA_real_, subject_age), subject_religion = case_when( subject_religion %in% c("christian", "(seventh day adventist) youth", "a.o.g.", "anglican", "anglicanism", "aog", "aog assemblies of god", "agos, assemblies of god", "assemblies of god", "c.m.c presbyterian", "christian - ame (google it!)", "christian: anglican", "christian: catholic", "christian: non specific", "christian: non-specific", "christian: protestant mainline", "christianity", "christianity: non specific", "church of christ", "coptic orthodox christian", "family worship ark healing ministry", "kingdom citizenship of god", "living water", "ntm", "pentecostal", "presbyterian", "presbyterian (illegible)", "protestant", "s.d.a.", "sda", "sda (seventh day adventist)", "seven day adventist", "seventh day adventist", "seventh day adventist church", "sunday keeper", "word christian fellowship") ~ "Christian", subject_religion %in% c("buddhist", "dge-lugs-pa (buddhist sect)", "sanqi buddhism", "some values of buddhism", "buddha temple", "buddha temples", "buddha temples & ancestral hall", "buddhist temples") ~ "Buddhist", # subject_religion %in% # c("Family - Orthodox Jew / Jewish", # "Judaism", "Orthodox Jewish") ~ "Jewish", subject_religion %in% c("muslim") ~ "Muslim", # subject_religion %in% # c("Hinduism") ~ "Hindu", grepl("agnost", tolower(subject_religion)) | grepl("atheis", tolower(subject_religion)) | grepl("don't", tolower(subject_religion)) | grepl("none", tolower(subject_religion)) | tolower(subject_religion) %in% c("n/a", "no", "no religion", "not really") ~ "Agnostic/Atheist", subject_religion %in% c("missing data", "mdata", "NA") | is.na(subject_religion) ~ "Missing data", TRUE ~ "Other"), agnostic_atheist = (subject_religion == "Agnostic/Atheist"), buddhist = (subject_religion == "Buddhist"), christian = (subject_religion == "Christian"), muslim = (subject_religion == "Muslim"), other = (subject_religion == "Other"), missing = (subject_religion == "Missing data")) ``` ```{r, include = T} d3_demo %>% group_by(country) %>% summarise(n = n(), age_range = paste0(min(subject_age, na.rm = T), "-", max(subject_age, na.rm = T)), mean_age = mean(subject_age, na.rm = T), percent_male = mean(male, na.rm = T), percent_female = mean(female, na.rm = T), percent_affr = mean(subject_afford, na.rm = T), mean_ses = mean(subject_ses, na.rm = T), mean_religiosity = mean(subject_religiosity, na.rm = T), percent_christian = mean(christian, na.rm = T), percent_agnostic_atheist = mean(agnostic_atheist, na.rm = T), percent_buddhist = mean(buddhist, na.rm = T), percent_muslim = mean(muslim, na.rm = T), percent_other = mean(other, na.rm = T), percent_missing = mean(missing, na.rm = T)) %>% ungroup() %>% # mutate_at(vars(starts_with("mean_")), funs(format(round(., 2), nsmall = 2))) %>% mutate_at(vars(starts_with("percent_")), funs(paste0(round(. * 100), "%"))) %>% rename(Country = country, `Age range` = age_range, `Mean age` = mean_age, `% male` = percent_male, `% female` = percent_female, `% can afford` = percent_affr, `% Christian` = percent_christian, `% Agnostic/Atheist` = percent_agnostic_atheist, `% Buddhist` = percent_buddhist, `% Muslim` = percent_muslim, `% Other` = percent_other, `[% Missing data]` = percent_missing, `Mean SES` = mean_ses, `Mean religiosity` = mean_religiosity) %>% mutate(Country = factor(Country, levels = levels_country)) %>% arrange(Country) %>% select(Country, n, `Age range`, `Mean age`, `% male`, `% female`, `Mean religiosity`, `% Christian`, `% Buddhist`, `% Muslim`, `% Other`, `% Agnostic/Atheist`, `[% Missing data]`, `% can afford`, `Mean SES`) %>% kable(digits = 2, align = c(rep("l", 2), rep("r", ncol(.) - 2))) %>% kable_styling(font_size = 16) # %>% # collapse_rows(1:2) ``` \newpage ## Study 4 (<NAME>, et al., 2020, _PNAS_: Table S17) ```{r} d4_demo <- d4_scored %>% select(-contains("score")) %>% mutate(male = ifelse(grepl("male", tolower(subject_gender)) & !grepl("female", tolower(subject_gender)), 1, 0), female = ifelse(grepl("female", tolower(subject_gender)), 1, 0), subject_age = ifelse(subject_age > 120, NA_real_, subject_age), urban = ifelse(subject_urban_rural == "urban", 1, 0), subject_religion = case_when( # deal with religion subject_religion %in% c("A.O.G.", "Anglican", "AoG", "AOG", "AOG (Assembly of God)", "Apostolic Life Ministry", "Assemblies of God", "Assemblies of God (AOG)", "Baptism", "Bible Church", "Bible Church of Vanuatu", "catholic", "Catholic", "catholicism", "Catholicism", "Catholicism / Christianism", "Chirstianity", "Christian", "Christian Mission Center", "Christian religion", "Christianianity", "christianity", "Christianity", "Church of Christ", "CMC", "CMC Church", "COC", "Living Water [Fresh waters]", "Living Wota (Freshwotas)", "Methodist", "New Governant Church of Vanuatu", "NTM", "only Christian", "Only Christian", "Only Christian!", "Pilow of Five Ministry", "Praise & Worship", "Presbyterian", "Roman Catholic", "S.D.A", "S.D.A. Youth", "Sabbath", "SDA (Saturday)", "SDA (Seventh Day Adventist)", "SDA, Seventh Day Adventist", "Seventh Day Adventist", "Sunday", "Sunday worship", "Sunday Worship", "The Church of Jesus Christ of Latter Day Saints", "United Methodist Christian") ~ "Christian", subject_religion %in% c("Buddhist", "Buddhism") ~ "Buddhist", subject_religion %in% c("Muslim", "Islam", "Islam / Mohammedanism", "Islam/Mohammedanism", "Some Islam habits") ~ "Muslim", grepl("agnost", tolower(subject_religion)) | grepl("atheis", tolower(subject_religion)) | grepl("don't", tolower(subject_religion)) | grepl("none", tolower(subject_religion)) | subject_religion == "." | is.na(subject_religion) | tolower(subject_religion) %in% c("n/a", "no", "no religion", "no religion, finding one", "not really") ~ "Agnostic/Atheist", subject_religion %in% c("missing data", "mdata", "NA") | is.na(subject_religion) ~ "Missing data", TRUE ~ "Other"), agnostic_atheist = (subject_religion == "Agnostic/Atheist"), buddhist = (subject_religion == "Buddhist"), christian = (subject_religion == "Christian"), muslim = (subject_religion == "Muslim"), other = (subject_religion == "Other"), missing = (subject_religion == "Missing data")) ``` ```{r, include = T} d4_demo %>% group_by(country) %>% summarise(n = n(), age_range = paste0(min(subject_age, na.rm = T), "-", max(subject_age, na.rm = T)), mean_age = mean(subject_age, na.rm = T), percent_male = mean(male, na.rm = T), percent_female = mean(female, na.rm = T), percent_urban = mean(urban, na.rm = T), percent_affr = mean(subject_afford, na.rm = T), mean_ses = mean(subject_ses, na.rm = T), mean_religiosity = mean(subject_religiosity, na.rm = T), percent_christian = mean(christian, na.rm = T), percent_agnostic_atheist = mean(agnostic_atheist, na.rm = T), percent_buddhist = mean(buddhist, na.rm = T), percent_muslim = mean(muslim, na.rm = T), percent_other = mean(other, na.rm = T), percent_missing = mean(missing, na.rm = T)) %>% ungroup() %>% # mutate_at(vars(starts_with("mean_")), funs(format(round(., 2), nsmall = 2))) %>% mutate_at(vars(starts_with("percent_")), funs(paste0(round(. * 100), "%"))) %>% rename(Country = country, `Age range` = age_range, `Mean age` = mean_age, `% male` = percent_male, `% female` = percent_female, `% urban` = percent_urban, `% can afford` = percent_affr, `Mean SES` = mean_ses, `Mean religiosity` = mean_religiosity, `% Christian` = percent_christian, `% Agnostic/Atheist` = percent_agnostic_atheist, `% Buddhist` = percent_buddhist, `% Muslim` = percent_muslim, `% Other` = percent_other, `[% Missing data]` = percent_missing) %>% mutate(Country = factor(Country, levels = levels_country)) %>% arrange(Country) %>% select(Country, n, `Age range`, `Mean age`, `% male`, `% female`, `Mean religiosity`, `% Christian`, `% Buddhist`, `% Muslim`, `% Other`, `% Agnostic/Atheist`, `[% Missing data]`, `% urban`, `% can afford`, `Mean SES`) %>% kable(digits = 2, align = c(rep("l", 2), rep("r", ncol(.) - 2))) %>% kable_styling(font_size = 16) # %>% # collapse_rows(1:2) ```
5ff1b4a7c7bd59523419f627481a1f5d3762427f
[ "Markdown", "R", "RMarkdown" ]
3
R
kgweisman/dreams_mind_spirit
44847bf1c0ddf2fb7207ab709cacb86d4b9119ef
f7cbd32c730c282c71a6741c1c1bffe23c91b815
refs/heads/master
<file_sep>require 'spec_helper' describe(List) do describe(".all") do it("starts off with no lists") do expect(List.all()).to(eq([])) end end describe("#name") do it("returns its name") do list = List.new({:name => "stuff", :id => nil}) expect(list.name()).to(eq("stuff")) end end describe("#id") do it("sets its id when saved") do list = List.new({:name => "stuff", :id => nil}) list.save() expect(list.id()).to(be_an_instance_of(Integer)) end end describe("#save") do it("saves list to the database") do list = List.new({:name => "stuff", :id => nil}) list.save() expect(List.all()).to(eq([list])) end end describe("#==") do it("is the same if the id and name match") do list1 = List.new({:name => "stuff", :id => nil}) list2 = List.new({:name => "stuff", :id => nil}) expect(list1).to(eq(list2)) end end describe(".find_list") do it("resturns a list by its ID") do test_list1 = List.new({:name => "<NAME>", :id => nil}) test_list1.save() test_list2 = List.new({:name => "Other stuff", :id => nil}) test_list2.save() expect(List.find_list(test_list1.id)).to(eq(test_list1)) end end describe("#tasks") do it("resturns an array of tasks for that list") do test_list = List.new({:name => "Epicodus stuff", :id => nil}) test_list.save() test_task = Task.new({:description => "Learn SQL", :list_id => test_list.id()}) test_task.save() test_task2 = Task.new({:description => "Review Ruby", :list_id => test_list.id()}) test_task2.save() expect(test_list.tasks()).to(eq([test_task, test_task2])) end end end <file_sep>require 'pry' class List attr_reader(:name, :id) def initialize(attributes) @name = attributes[:name] @id = attributes[:id] end def self.all() lists = [] rows = DB.exec("SELECT * FROM lists") rows.each do |row| name = row["name"] id = row["id"].to_i list = List.new({:name => name, :id => id}) lists.push(list) end lists end def self.find_list(list_id) found_list = nil all_lists = List.all all_lists.each do |list| if list.id == list_id found_list = list end end found_list end def save values = DB.exec("INSERT INTO lists (name) VALUES ('#{@name}') RETURNING id") @id = values.first["id"].to_i end def tasks list_tasks = [] tasks = DB.exec("SELECT * FROM tasks WHERE list_id = #{@id}") tasks.each do |task| description = task["description"] list_id = task["list_id"] list_tasks.push(Task.new({:description => description, :list_id => list_id})) end list_tasks end def ==(other) @name == other.name end end <file_sep>1. A query on a DB ("SELECT * FROM table_name") returns an array of hashes: [{:id => "1", :name, "Tom"}, {:id => "2", :name => "Dick"}, {:id => "3", :name => "Harry"}] Even if your query returns a single record, to work with it in Ruby, you must specify the array position of this search result so you can work with the has data. Won't work: result = DB.exec("SELECT * FROM table_name WHERE id = 1") result.fetch["name"] -This results in an error, since you're trying to run the ".fetch" method on an array. To get it working, first specify the array position so you can use your hash method on the result: result = DB.exec("SELECT * FROM table_name WHERE id = 1") result[0] (this accesses the hash position: {:id => "1", :name, "Tom"}) result[0].fetch["name"] (this returns the fetch result "Tom") 2. When working with Ruby Classes and a DB, Ruby will only display instances of its classes, not the direct DB SQL query. What this means is, each time you query the DB, to view the results on your Ruby page you must create instances of Ruby classes and push them to a variable or variable array in order to show them on the page. For example, if DB table names_table contains 3 records, to see those on your page, you must first create 3 instances of a Name class in Ruby Here's what this could look like: 1. Query DB for all names records: all_records = DB.exec("SELECT * FROM names_table") - This returns an array of hashes - In Ruby, you need to iterate over this array using an 'each' loop, setting whichever table hash values you wish to display temporarily as Ruby variables: all_records.each do |record| name = record.fetch["name"] end - However, our goal is not to return the result of a query, but an array of newly created Ruby objects. So, we need to go a little further here by initialized an empty array in our method to "catch" the new class instances we'll create on each loop through the query return hash: class_names = [] all_records.each do |record| name = record.fetch["name"] id = record.fetch["id"] new_name = Name.new({:name => name, :id => id}) class_names.push(new_name) end return class_names - We can eliminate a line here by omitting the 'new_name' variable definition. Instead, we can simply create the class instance right when we push it to the 'class_names' array: class.names.push(Name.new({:name => name, :id => id})) - Our final method will look like this: def Name.show_all class_names = [] all_records = DB.exec("SELECT * FROM names_table") all_records.each do |record| name = record.fetch("name") id = record.fetch("id").to_i class.names.push(Name.new({:name => name, :id => id})) end class_names end <file_sep>require("sinatra") require("sinatra/reloader") also_reload("lib/**/*.rb") require("./lib/task") require("./lib/list") require("pg") DB = PG.connect({:dbname => "to_do"}) get("/") do @lists = List.all (erb :index) end post("/") do if (params[:list_entry] == "") redirect "/" else list_entry = params[:list_entry].capitalize new_list = List.new(:name => list_entry) new_list.save @lists = List.all redirect "/" end end get("/tasks/:id") do @list_id = params[:id].to_i @list = List.find_list(@list_id) @tasks = @list.tasks (erb :tasks) end post("/tasks/:id") do list_id = params[:id] task_description = params[:task_entry] if (task_description == "") redirect "/tasks/#{list_id}" else task = Task.new(:description => task_description, :list_id => list_id) task.save redirect "/tasks/#{list_id}" end end
64794b12e1f424edb01e7dd916d64c58d26ada5b
[ "Text", "Ruby" ]
4
Ruby
JaredReando/todo
f0af71428c18d8e0f8e0ba228db97eef9443b943
0de7eec414e52a7073190497588a6f93561cc1f9
refs/heads/master
<file_sep> # This programs loops through all feature classes in the "input" geodatabase and buffers them by 100 meters. # It then creates a new output GDB and exports the result of a dissolve and clip of Missouri's highways. # Import necessary modules, set path and environment settings import arcpy import os #path = r"C:\Users\austi\OneDrive - Washington University in St. Louis\Desktop\Assignment02" path = r"D:\GIS_Courses\GIS_Programming\SP2019\Assignments\Assignment02" arcpy.env.workspace = path arcpy.env.overwriteOutput = True input_GDB = "Assign02_Inputs.gdb" output_GDB = "Assign02_Output.gdb" # set workspace to be the input GDB arcpy.env.workspace = os.path.join(path,input_GDB) # Create a list of all feature classes in the GDB. fc_list = arcpy.ListFeatureClasses() # Loop through each feature class in the GDB. for fc in fc_list: # Run the buffer tool on each feature class. arcpy.Buffer_analysis(fc, arcpy.Describe(fc).baseName + "_Buf100m", "100 Meters") arcpy.env.workspace = path # This if statement only executes if the GDB does not exist. if not arcpy.Exists("Assign02_Output.gdb"): arcpy.CreateFileGDB_management(path, "Assign02_Output.gdb") # Run clip tool with specified inputs. stl_highways = arcpy.Clip_analysis(os.path.join(input_GDB,"MO_Highways"),os.path.join(input_GDB,"STL_CITY_Tracts_2010"),os.path.join(output_GDB,"STL_Highways")) # Use the output of the clip tool in the disolve tool with the specified inputs. arcpy.Dissolve_management(stl_highways,os.path.join(output_GDB,"STL_Highways_ByType"), "TYPE") <file_sep># This program selects and zooms to each school district inside the "StlCounty_SchoolDistricts.mxd" map document # and then exports a map of the school district as a png. # Import necessary modules and modules, set path, mxd and workspace: import arcpy import os path = r"C:\Users\austin.tolani\Desktop\Assignment03" arcpy.env.workspace = path arcpy.env.overwriteOutput = True mxd = arcpy.mapping.MapDocument(os.path.join(path,"StlCounty_SchoolDistricts.mxd")) targetLayer = arcpy.mapping.ListLayers(mxd, "StlCounty_SchoolDistricts")[0] # Create search cursor cursor = arcpy.da.SearchCursor(targetLayer,["SCHOOL_DIS"]) # create "PNG" Directory if not os.path.exists(os.path.join(path, "PNG")): os.makedirs(os.path.join(path,"PNG")) targetDirectory = os.path.join(path,"PNG") # Iterate through rows, create search query, zoom to selection, clear selection and export png for row in cursor: query = '"SCHOOL_DIS" = ' + "'" + row[0] + "'" arcpy.SelectLayerByAttribute_management(targetLayer, "", query) arcpy.mapping.ListDataFrames(mxd)[0].zoomToSelectedFeatures() arcpy.SelectLayerByAttribute_management(targetLayer, "CLEAR_SELECTION") fileName = "DistrictMap_" + row[0] + ".png" arcpy.mapping.ExportToPNG(mxd,os.path.join(targetDirectory,fileName)) <file_sep># ArcPy This repo contains two of my assignments from a GIS Programming class and demonstrate my understanding of the ArcPy library in Python. `PDFExport.py` contains a script that selects and zooms to each feature (in this case school districts) inside a map document and then exports a map of the school district as a png. `BufferExport.py` loops through all feature classes in an input geodatabase and buffers them by 100 meters. It then creates a new output GDB and exports the result of a dissolve and clip of Missouri's highways.
18d4b724aa309cd5dc04c6e9eb1b491844b7cd6f
[ "Markdown", "Python" ]
3
Python
austintolani/ArcPy
7dad4b725b1e334056f7a7328370156a0153da54
d6421624a09a249e8bda5f06f3d58817305d1c19
refs/heads/master
<file_sep>import { rem, transparentize } from 'polished'; import styled, { css } from 'styled-components'; import { remFloat } from '../helpers'; import { colors, mixins, Theme, variables } from '../themes'; const { black, grey87, grey93, primary, white } = colors; const { component } = mixins; const { border, borderWidth } = variables; const width = rem('44px'); const height = rem('24px'); const offset = (props: { theme: Theme }) => `${Math.max(remFloat('2px') - remFloat(borderWidth(props) as string), 0)}rem`; const toggleSize = css`calc(${height} - (${offset} + ${borderWidth}) * 2)`; export const Input = styled.span` border: ${border} ${grey93}; border-radius: calc(${height} / 2); background-color: ${grey93}; box-sizing: border-box; content: ''; height: 100%; position: absolute; top: 0; left: 0; width: 100%; transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; text-align: center; display: flex; align-items: center; &::after { content: ' '; display: block; background-color: ${white}; border-radius: 100%; margin-left: ${offset}; width: ${toggleSize}; height: ${toggleSize}; transition: margin-left 0.15s ease-in-out; } `; export const SwitchContainer = styled.div` ${component}; position: relative; width: ${width}; height: ${height}; display: inline-block; input { height: 100%; left: 0; opacity: 0; position: absolute; top: 0; width: 100%; z-index: 1; margin: 0; appearance: none; &:checked + ${Input}::after { margin-left: calc(100% - ${toggleSize} - ${offset}); } &:disabled + ${Input}::after { background-color: ${grey87}; } &:not(:disabled) { & + ${Input}::after { box-shadow: 0 ${rem('3px')} ${rem('1px')} 0 ${(props) => transparentize(0.95, black(props))}, 0 ${rem('2px')} ${rem('2px')} 0 ${(props) => transparentize(0.9, black(props))}, 0 ${rem('3px')} ${rem('3px')} 0 ${(props) => transparentize(0.95, black(props))}; } &:checked + ${Input} { background-color: ${primary}; border-color: ${primary}; } &:focus + ${Input} { box-shadow: 0 0 ${rem('4px')} 0 ${(props) => transparentize(0.5, black(props))}; } } } `; <file_sep>--- name: Getting Started route: / --- # Getting Started ## Installation ```bash yarn add @josselinbuils/components npm install @josselinbuils/components --save ``` ## Usage ```jsx import { Alert } from '@josselinbuils/components/Alert'; <Alert level="info">This is an info alert</Alert> ``` Not to create unnecessary big bundles, the lib is provided with esnext syntax and has to be transpiled using Babel or any similar tool to become compatible with older browsers. <file_sep>export { ThemeProvider } from 'styled-components'; export { defaultTheme } from './defaultTheme'; export { colors } from './colors'; export { mixins } from './mixins'; export * from './Theme'; export { variables } from './variables'; <file_sep>import commonjs from '@rollup/plugin-commonjs'; import nodeResolve from '@rollup/plugin-node-resolve'; import typescript from '@rollup/plugin-typescript'; import multiInput from 'rollup-plugin-multi-input'; import { dependencies, peerDependencies } from './package.json'; export default { input: ['src/**/index.ts', '!src/doc'], output: { dir: 'dist', format: 'esm', }, external: [...Object.keys(dependencies), ...Object.keys(peerDependencies)], plugins: [ multiInput({ relative: 'src' }), nodeResolve({ extensions: ['.js', '.ts', '.tsx'] }), commonjs({ namedExports: { 'prop-types': ['elementType'], 'react-is': ['ForwardRef', 'Memo'], }, }), typescript({ rootDir: './src' }), ], }; <file_sep>--- name: Alert menu: Components --- import { Playground, Props } from 'docz' import { Alert } from './Alert' # Alert ## Properties <Props of={Alert} /> ## Usage ```js import { Alert } from '@josselinbuils/components/Alert'; ``` <Playground> <Alert level="error">This is an error alert</Alert> <Alert level="warning" style={{ marginTop: '1rem' }}>This is a warning alert</Alert> <Alert level="info" style={{ marginTop: '1rem' }}>This is an info alert</Alert> <Alert level="success" style={{ marginTop: '1rem' }}>This is a success alert</Alert> </Playground> <file_sep>--- name: Switch menu: Components --- import { Playground, Props } from 'docz' import { Switch } from './Switch' # Switch ## Properties There is no specific property to this component, just use it the same way you would use an HTML checkbox input. ## Usage ```js import { Switch } from '@josselinbuils/components/Switch'; ``` <Playground> <Switch /> <Switch defaultChecked style={{ marginLeft: '1rem' }} /> <Switch disabled style={{ marginLeft: '1rem' }} /> <Switch defaultChecked disabled style={{ marginLeft: '1rem' }} /> </Playground> <file_sep>import { rem, transparentize } from 'polished'; import styled from 'styled-components'; import { Icon } from '../Icon'; import { colors, mixins, variables } from '../themes'; const { black, grey74, grey87, grey93, primary, white } = colors; const { component } = mixins; const { border, borderRadius, fontSizeXL } = variables; const size = rem('24px'); export const Input = styled.span` border: ${border} ${grey87}; border-radius: ${borderRadius}; box-sizing: border-box; content: ''; height: 100%; left: 0; position: absolute; top: 0; width: 100%; background-color: ${white}; transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; text-align: center; `; export const StyledIcon = styled(Icon)` color: ${white}; opacity: 0; transition: opacity 0.15s ease-in-out; font-size: ${fontSizeXL}; line-height: 1em; `; export const CheckboxContainer = styled.div` ${component}; position: relative; width: ${size}; height: ${size}; display: inline-block; input { height: 100%; left: 0; opacity: 0; position: absolute; top: 0; width: 100%; z-index: 1; margin: 0; appearance: none; &:checked + ${Input} > ${StyledIcon} { opacity: 1; } &:disabled + ${Input} { border-color: ${grey93}; background-color: ${grey93}; ${StyledIcon} { color: ${grey74}; } } &:not(:disabled) { &:checked + ${Input} { border-color: ${primary}; background-color: ${primary}; } &:focus + ${Input} { border-color: ${primary}; box-shadow: 0 0 ${rem('4px')} 0 ${(props) => transparentize(0.5, black(props))}; } &:hover + ${Input} { border-color: ${primary}; } } } `; <file_sep>import { defaultTheme } from './defaultTheme'; import { Theme, ThemeColors } from './Theme'; export const colors = {} as { [key in keyof ThemeColors]: ({ theme }: { theme: Theme }) => string; }; Object.keys(defaultTheme.colors).forEach( (color) => (colors[color as keyof ThemeColors] = ({ theme }: { theme: Theme }) => (theme.colors || defaultTheme.colors)[color as keyof ThemeColors]) ); <file_sep>import { FlattenSimpleInterpolation } from 'styled-components'; import { defaultTheme } from './defaultTheme'; import { Theme, ThemeMixins } from './Theme'; export const mixins = {} as { [key in keyof ThemeMixins]: ({ theme, }: { theme: Theme; }) => FlattenSimpleInterpolation; }; Object.keys(defaultTheme.mixins).forEach( (mixin) => (mixins[mixin as keyof ThemeMixins] = ({ theme }: { theme: Theme }) => (theme.mixins || defaultTheme.mixins)[mixin as keyof ThemeMixins]) ); <file_sep>import { SvgIcon } from '@material-ui/core'; export type MaterialIcon = typeof SvgIcon; <file_sep># Components Library of React components. ## Installation ```bash yarn add @josselinbuils/components npm install @josselinbuils/components --save ``` ## Usage ```jsx import { Alert } from '@josselinbuils/components/Alert'; <Alert level="info">This is an info alert</Alert> ``` Not to create unnecessary big bundles, the lib is provided with esnext syntax and has to be transpiled using Babel or any similar tool to become compatible with older browsers. ## Documentation [Documentation](https://josselinbuils.me/components) <file_sep>import { darken, lighten } from 'polished'; import styled, { css } from 'styled-components'; import { Icon } from '../Icon'; import { colors, mixins, ThemeColors, variables } from '../themes'; const { error } = colors; const { component } = mixins; const { border, borderRadius, fontSizeM, fontSizeXXL, halfSpace, lineHeight, space, } = variables; const alert = (color: string) => css` color: ${darken(0.2, color)}; border-color: ${color}; background-color: ${lighten(0.4, color)}; svg { color: ${color}; } `; export const AlertContainer = styled.div<{ level: string }>` ${component}; font-size: ${fontSizeM}; display: flex; flex-flow: row nowrap; margin: 0; padding: ${halfSpace} ${space}; border: ${border}; border-radius: ${borderRadius}; height: calc(${fontSizeM} * ${lineHeight} + ${halfSpace} * 2); ${({ level, ...props }) => alert(colors[level as keyof ThemeColors](props) || error(props))}; `; export const Message = styled.div` padding: ${halfSpace} 0; `; export const StyledIcon = styled(Icon)` font-size: ${fontSizeXXL}; flex-grow: 0; margin-right: ${space}; `; <file_sep>--- name: Button menu: Components --- import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline'; import { Playground, Props } from 'docz' import { Icon } from '../Icon' import { Button } from './Button' # Button ## Properties <Props of={Button} /> ## Usage ```js import { Button } from '@josselinbuils/components/Button'; ``` <Playground> <Button>Button</Button> </Playground> <br /> ## Variants <Playground> <div> <Button variant="primary">Primary</Button> <Button style={{ marginLeft: '1rem' }} variant="secondary" > Secondary </Button> <Button style={{ marginLeft: '1rem' }} variant="ghost">Ghost</Button> <Button style={{ marginLeft: '1rem' }} variant="light">Light</Button> </div> <div style={{ marginTop: '1rem' }}> <Button disabled variant="primary">Primary</Button> <Button disabled style={{ marginLeft: '1rem' }} variant="secondary" > Secondary </Button> <Button disabled style={{ marginLeft: '1rem' }} variant="ghost" > Ghost </Button> <Button disabled style={{ marginLeft: '1rem' }} variant="light" > Light </Button> </div> </Playground> <br /> ## Sizes <Playground> <Button size="large">Large</Button> <Button size="medium" style={{ marginLeft: '1rem' }}>Medium</Button> <Button size="small" style={{ marginLeft: '1rem' }}>Small</Button> <Button size="extraSmall" style={{ marginLeft: '1rem' }}>Extra small</Button> </Playground> <br /> ## With icon <Playground> <Button icon={CheckCircleOutlineIcon} size="large">With icon</Button> <Button icon={CheckCircleOutlineIcon} size="large" style={{ marginLeft: '1rem' }} /> <Button icon={CheckCircleOutlineIcon} size="medium" style={{ marginLeft: '1rem' }} > With icon </Button> <Button icon={CheckCircleOutlineIcon} size="medium" style={{ marginLeft: '1rem' }} /> <Button icon={CheckCircleOutlineIcon} size="small" style={{ marginLeft: '1rem' }} > With icon </Button> <Button icon={CheckCircleOutlineIcon} size="small" style={{ marginLeft: '1rem' }} /> <Button icon={CheckCircleOutlineIcon} size="extraSmall" style={{ marginLeft: '1rem' }} > With icon </Button> <Button icon={CheckCircleOutlineIcon} size="extraSmall" style={{ marginLeft: '1rem' }} /> </Playground> <file_sep>import { rem } from 'polished'; /** * Provides px/rem input value as rem number. * * @param value Value in px or rem. */ export function remFloat(value: string): number { return parseFloat(value.endsWith('px') ? rem(value) : value); } <file_sep>import { rem } from 'polished'; import { css } from 'styled-components'; import { Theme, ThemeColors, ThemeMixins, ThemeVariables } from './Theme'; const colors = { // Main primary: '#007ad8', secondary: '#12a500', // Error levels success: '#3cb34c', info: '#15b1ce', warning: '#ff8a00', error: '#df3f2e', // Grey shades grey12: '#212121', grey25: '#424242', grey38: '#616161', grey45: '#757575', grey61: '#9e9e9e', grey74: '#bdbdbd', grey87: '#e0e0e0', grey93: '#eeeeee', grey96: '#f5f5f5', grey98: '#fafafa', // Not colors black: '#000000', white: '#ffffff', } as ThemeColors; const borderWidth = rem('1px'); const variables = { // Borders border: `${borderWidth} solid`, borderRadius: rem('3px'), borderWidth, // Font fontFamily: 'Open Sans, arial, sans-serif', fontWeight: 400, fontSizeXXL: rem('22px'), fontSizeXL: rem('20px'), fontSizeL: rem('18px'), fontSize: rem('16px'), fontSizeM: rem('14px'), fontSizeS: rem('12px'), fontSizeXS: rem('10px'), lineHeight: 1.5, // Spaces doubleSpace: rem('32px'), space: rem('16px'), halfSpace: rem('8px'), quarterSpace: rem('4px'), } as ThemeVariables; const mixins = { component: css` font-family: ${variables.fontFamily}; font-size: ${variables.fontSize}; font-weight: ${variables.fontWeight}; line-height: ${variables.lineHeight}; `, } as ThemeMixins; export const defaultTheme = { colors, mixins, variables } as Theme; <file_sep>--- name: Colors route: /colors --- import { ColorCard, FlexContainer } from './components' # Colors ## Main <FlexContainer offsetLeft={-45} offsetTop={-15}> <ColorCard color="#12b900" title="primary" /> <ColorCard color="#007ad8" title="secondary" /> </FlexContainer> <br /> ## Error levels <FlexContainer offsetLeft={-45} offsetTop={-15}> <ColorCard color="#3cb34c" title="success" /> <ColorCard color="#15b1ce" title="info" /> <ColorCard color="#ff8a00" title="warning" /> <ColorCard color="#df3f2e" title="error" /> </FlexContainer> <br /> ## Grey shades <FlexContainer offsetLeft={-45} offsetTop={-15}> <ColorCard color="#212121" title="grey12" /> <ColorCard color="#424242" title="grey25" /> <ColorCard color="#616161" title="grey38" /> <ColorCard color="#757575" title="grey45" /> <ColorCard color="#9e9e9e" title="grey61" /> <ColorCard color="#bdbdbd" title="grey74" /> <ColorCard color="#e0e0e0" title="grey87" /> <ColorCard color="#eeeeee" title="grey93" /> <ColorCard color="#f5f5f5" title="grey96" /> <ColorCard color="#fafafa" title="grey98" /> </FlexContainer> <file_sep>import styled from 'styled-components'; export const IconContainer = styled.figure` display: flex; align-items: center; justify-content: center; height: 100%; margin: 0; svg { font-size: inherit; } `; <file_sep>--- name: Icon menu: Components --- import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline'; import { Playground, Props } from 'docz' import { FlexContainer, IconCard } from '../../docz/components' import { Icon } from './Icon' # Icon Makes material icons being sized by parent font size and being vertically aligned. ## Properties <Props isToggle of={Icon} /> ## Usage ```js import { Icon } from '@josselinbuils/components/Icon'; import CheckCircleOutlineIcon from '@material-ui/icons/CheckCircleOutline'; ``` <Playground> <Icon icon={CheckCircleOutlineIcon} /> </Playground> <file_sep>import { rem, transparentize } from 'polished'; import styled from 'styled-components'; import { colors, mixins, variables } from '../themes'; const { black, grey87, grey93, primary, white } = colors; const { component } = mixins; const { border, borderWidth } = variables; export const Input = styled.span` border: ${border} ${grey87}; border-radius: 100%; box-sizing: border-box; content: ''; height: 100%; left: 0; position: absolute; top: 0; width: 100%; background-color: ${white}; transition: background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; text-align: center; display: flex; align-items: center; justify-content: center; `; export const RadioContainer = styled.div` ${component}; position: relative; width: ${rem('24px')}; height: ${rem('24px')}; display: inline-block; input { height: 100%; left: 0; opacity: 0; position: absolute; top: 0; width: 100%; z-index: 1; margin: 0; appearance: none; &:disabled + ${Input} { border-color: ${grey93}; background-color: ${grey93}; } &:not(:disabled) { &:checked + ${Input} { border-color: ${primary}; &::before { content: ' '; position: absolute; display: block; background-color: ${primary}; border-radius: 100%; width: calc( 100% - ${(props) => `max(${borderWidth(props)}, ${rem('2px')})`} * 2 ); height: calc( 100% - ${(props) => `max(${borderWidth(props)}, ${rem('2px')})`} * 2 ); } } &:focus + ${Input} { border-color: ${primary}; box-shadow: 0 0 ${rem('4px')} 0 ${(props) => transparentize(0.5, black(props))}; } &:hover + ${Input} { border-color: ${primary}; } } } `; <file_sep>export * from './Card'; export * from './ColorCard'; export * from './FlexContainer'; export * from './IconCard'; <file_sep>--- name: ButtonGroup menu: Components --- import { Playground, Props } from 'docz' import { Button } from '../Button' import { ButtonGroup } from './ButtonGroup' # ButtonGroup ## Properties <Props of={ButtonGroup} /> ## Usage ```js import { Button } from '@josselinbuils/components/Button'; import { ButtonGroup } from '@josselinbuils/components/ButtonGroup'; ``` <Playground> <ButtonGroup> <Button>1</Button> <Button>2</Button> <Button>3</Button> </ButtonGroup> </Playground> <br /> ## Variants and Sizes To avoid having to set the color and the size properties on every Button, you can provide them directly to the ButtonGroup. <Playground> <ButtonGroup variant="primary"> <Button>1</Button> <Button>2</Button> <Button>3</Button> </ButtonGroup> <ButtonGroup size="small" style={{ marginLeft: '1rem' }}> <Button>1</Button> <Button>2</Button> <Button>3</Button> </ButtonGroup> </Playground> <br /> ## Orientations <Playground> <ButtonGroup orientation="horizontal"> <Button>1</Button> <Button>2</Button> <Button>3</Button> </ButtonGroup> <ButtonGroup orientation="vertical" style={{ marginLeft: '1rem' }}> <Button>4</Button> <Button>5</Button> <Button>6</Button> </ButtonGroup> </Playground> <file_sep>import styled, { css, FlattenSimpleInterpolation } from 'styled-components'; import { variables } from '../themes'; const { borderWidth } = variables; const orientations = { horizontal: css` button:not(:last-child) { border-top-right-radius: 0; border-bottom-right-radius: 0; } button + button { border-top-left-radius: 0; border-bottom-left-radius: 0; margin-left: -${borderWidth}; } `, vertical: css` flex-direction: column; button:not(:last-child) { border-bottom-left-radius: 0; border-bottom-right-radius: 0; } button + button { border-top-left-radius: 0; border-top-right-radius: 0; margin-top: -${borderWidth}; } `, } as { [orientation: string]: FlattenSimpleInterpolation }; export const ButtonContainer = styled.div<{ orientation: string }>` position: relative; display: inline-flex; ${({ orientation }) => orientations[orientation]}; button:active, button:focus { position: relative; z-index: 1; } `; <file_sep>import { darken, lighten, rem } from 'polished'; import styled, { css, FlattenSimpleInterpolation } from 'styled-components'; import { Icon } from '../Icon'; import { colors, mixins, variables } from '../themes'; const { grey74, grey87, grey93, primary, secondary, white } = colors; const { component } = mixins; const { border, borderRadius, borderWidth, fontSize, fontSizeXXL, halfSpace, quarterSpace, space, } = variables; const variants = { ghost: css` border-color: ${primary}; background-color: ${white}; color: ${primary}; &:active { border-color: transparent; box-shadow: 0 0 0 ${borderWidth} ${primary}; } &:not(:active) { &:focus, &:hover { background-color: ${primary}; color: ${white}; } } `, light: css` border-color: ${grey87}; background-color: ${white}; color: ${(props) => darken(0.3, primary(props))}; &:active { border-color: transparent; box-shadow: 0 0 0 ${borderWidth} ${grey87}; } &:not(:active) { &:focus, &:hover { background-color: ${grey93}; } } `, primary: css` background-color: ${primary}; color: ${white}; &:active { box-shadow: 0 0 0 ${borderWidth} ${primary}; } &:not(:active) { &:focus, &:hover { background-color: ${(props) => lighten(0.1, primary(props))}; } } `, secondary: css` background-color: ${secondary}; color: ${white}; &:active { box-shadow: 0 0 0 ${borderWidth} ${secondary}; } &:not(:active) { &:focus, &:hover { background-color: ${(props) => lighten(0.1, secondary(props))}; } } `, } as { [variant: string]: FlattenSimpleInterpolation }; const sizes = { large: css` padding: ${rem('12px')} ${rem('20px')}; height: ${rem('58px')}; min-width: ${rem('58px')}; `, medium: css` padding: ${halfSpace} ${space}; height: ${rem('50px')}; min-width: ${rem('50px')}; `, small: css` padding: ${quarterSpace} calc(${halfSpace} + ${quarterSpace}); height: ${rem('42px')}; min-width: ${rem('42px')}; `, extraSmall: css` padding: 0 ${halfSpace}; height: ${rem('34px')}; min-width: ${rem('34px')}; `, } as { [size: string]: FlattenSimpleInterpolation }; export const Content = styled.span`{ padding: ${quarterSpace} 0; display: inline-block; `; export const StyledButton = styled.button<{ size: string; variant: string }>` ${component}; border: ${border} transparent; border-radius: ${borderRadius}; transition: color 0.15s ease-in-out, background-color 0.15s ease-in-out, border-color 0.15s ease-in-out, box-shadow 0.15s ease-in-out; text-align: center; font-size: ${fontSize}; outline: none; display: inline-flex; align-items: center; justify-content: center; margin: 0; box-sizing: border-box; ${({ size }) => sizes[size]}; &:disabled { color: ${grey74}; background-color: ${grey93}; border-color: transparent; } &:not(:disabled) { cursor: pointer; ${({ variant }) => variants[variant]}; } `; export const StyledIcon = styled(Icon)` font-size: ${fontSizeXXL}; &:not(:last-child) { margin-right: ${halfSpace}; } `; <file_sep>--- name: Checkbox menu: Components --- import { Playground, Props } from 'docz' import { Checkbox } from './Checkbox' # Checkbox ## Properties There is no specific property to this component, just use it the same way you would use an HTML checkbox input. ## Usage ```js import { Checkbox } from '@josselinbuils/components/Checkbox'; ``` <Playground> <Checkbox /> <Checkbox defaultChecked style={{ marginLeft: '1rem' }} /> <Checkbox disabled style={{ marginLeft: '1rem' }} /> <Checkbox defaultChecked disabled style={{ marginLeft: '1rem' }} /> </Playground> <file_sep>export { remFloat } from './remFloat'; <file_sep>import { defaultTheme } from './defaultTheme'; import { Theme, ThemeVariables } from './Theme'; export const variables = {} as { [key in keyof ThemeVariables]: ({ theme, }: { theme: Theme; }) => number | string; }; Object.keys(defaultTheme.variables).forEach( (variable) => (variables[variable as keyof ThemeVariables] = ({ theme, }: { theme: Theme; }) => (theme.variables || defaultTheme.variables)[ variable as keyof ThemeVariables ]) ); <file_sep>import { FlattenSimpleInterpolation } from 'styled-components'; export interface ThemeColors { // Main primary: string; secondary: string; // Error levels success: string; info: string; warning: string; error: string; // Grey shades grey12: string; grey25: string; grey38: string; grey45: string; grey61: string; grey74: string; grey87: string; grey93: string; grey96: string; grey98: string; // Not colors black: string; white: string; } export interface ThemeMixins { component: FlattenSimpleInterpolation; } export interface ThemeVariables { // Borders border: string; borderRadius: string; borderWidth: string; // Font fontFamily: string; fontWeight: number; fontSizeXXL: string; fontSizeXL: string; fontSizeL: string; fontSize: string; fontSizeM: string; fontSizeS: string; fontSizeXS: string; lineHeight: number; // Spaces doubleSpace: string; space: string; halfSpace: string; quarterSpace: string; } export interface Theme { colors: ThemeColors; mixins: ThemeMixins; variables: ThemeVariables; } <file_sep>FROM node:12 COPY . components WORKDIR components RUN yarn install --frozen-lockfile && \ yarn build:doc CMD ["yarn", "start:doc"] <file_sep>--- name: Radio menu: Components --- import { Playground, Props } from 'docz' import { Radio } from './Radio' # Radio ## Properties There is no specific property to this component, just use it the same way you would use an HTML radio input. ## Usage ```js import { Radio } from '@josselinbuils/components/Radio'; ``` <Playground> <Radio name="example" /> <Radio defaultChecked name="example" style={{ marginLeft: '1rem' }} /> <Radio disabled name="example" style={{ marginLeft: '1rem' }} /> </Playground>
4462ed0c14c3e83e689889f1388cddc9d58fac66
[ "Markdown", "TypeScript", "JavaScript", "Dockerfile" ]
29
TypeScript
josselinbuils/components
5fe65d8246473a71323dcbc265edb5c49193769a
44af6de716a4920e19a0e10d47a6ad67cb149229
refs/heads/master
<file_sep>// v3.1.0 //Docs at http://simpleweatherjs.com function GetIndiceTemps() { var indice = 0.0; // return 1.0; $(document).ready(function() { $.simpleWeather({ location: 'Bordeaux, FR', woeid: '', unit: 'f', success: function(weather) { //on transform weather.code en indice var arrayStorm = [0,1,2,3,4,23,37,38,39,45,47]; var arrayRainyH = [5,7,10,11,12,13,14,15,16,17,18,40,41,42,43,46]; var arrayRainy = [6,8,9,24,25,35]; var arrayCloudy = [19,20,21,26,27,28,29,30,44]; var arraySunny = [31,32,33,34,36,32000]; weatherCode = weather.code; weatherIndice = 0.0; for(var i = 0; i<arrayStorm.length; i++){ if (arrayStorm[i] == weatherCode){ weatherIndice = 0.0; } } for(var i = 0; i<arrayRainyH.length; i++){ if (arrayRainyH[i] == weatherCode){ weatherIndice = 0.25; } } for(var i = 0; i<arrayRainy.length; i++){ if (arrayRainy[i] == weatherCode){ weatherIndice = 0.5; } } for(var i = 0; i<arrayCloudy.length; i++){ if (arrayCloudy[i] == weatherCode){ weatherIndice = 0.75; } } for(var i = 0; i<arraySunny.length; i++){ if (arraySunny[i] == weatherCode){ weatherIndice = 1.0; } } wind = weather.wind.speed * 1.6; windIndice = (100.0 - wind)/100.0; if (weatherIndice>windIndice) { indice = weatherIndice; } else { indice = windIndice; } //Indice -> 0 storm 1 sunny console.log("indice : " + indice); return indice; }, error: function(error) { $("#weather").html('<p>'+error+'</p>'); } }); }); return indice; return 0.0; // au cas ou }<file_sep>/** * Compiles SASS files into CSS. * * --------------------------------------------------------------- * * This allows you to control the ordering yourself, i.e. import your * dependencies, mixins, variables, resets, etc. before other stylesheets) * */ module.exports = function(gulp, plugins, growl) { var sass = require('gulp-sass'); gulp.task('sass:dev', function() { return gulp.src('assets/styles/importer.scss') .pipe(sass().on('error', sass.logError)) .pipe(gulp.dest('.tmp/public/styles/')) .pipe(plugins.if(growl, plugins.notify({ message: 'less dev task complete' }))); }); }; <file_sep>/** * Run predefined tasks whenever watched file patterns are added, changed or deleted. * * --------------------------------------------------------------- * * Watch for changes on * - files in the `assets` folder * - the `tasks/pipeline.js` file * and re-run the appropriate tasks. * * */ module.exports = function(gulp, plugins, growl) { var livereload = require('gulp-livereload'); gulp.task('watch:api', function() { // Watch Style files livereload.listen(); return gulp.watch('api/**/*', ['syncAssets']) .on('change',function(){setTimeout(function(){livereload.reload();},1000)}); }); gulp.task('watch:assets', function() { // Watch assets livereload.listen(); return gulp.watch(['assets/**/*', 'tasks/pipeline.js'], ['syncAssets']) .on('change',function(){setTimeout(function(){livereload.reload();},1000)}); }); gulp.task('watch:views', function() { // Watch assets livereload.listen(); return gulp.watch('views/*.ejs', ['']) .on('change',function(){setTimeout(function(){livereload.reload();},1000)}); }); }; <file_sep>/** * ## Passport * * Logic for authentificating user lies here. */ 'use strict'; /** Loading Passport */ var passport = require('passport'), LocalStrategy = require('passport-local').Strategy, FacebookStrategy = require('passport-facebook').Strategy, bcrypt = require('bcrypt'); /** After passport serializes the object, return the id */ passport.serializeUser(function(user, done) { done(null, user.id); }); /** Passport deserializes the user by id and returns the full user object. */ passport.deserializeUser(function(id, done) { Personne.findOne({ id: id } , function (err, user) { done(err, user); }); }); /** * This is the holy grail of the strategy. When a request comes in * we try and find the user by email and see if their passport * is correct. */ var verifyHandler = function(req ,mail, password, done) { process.nextTick(function() { Personne.findOne({ email: mail }).exec(function(err, user) { if (err || !user) { return done(err); } bcrypt.compare(password, user.password, function(err, res) { if (!res) { return done(null, false, {message: 'Mot de passe incorrect'}); } else { /** The user's password is correct, so log them in. */ req.logIn(user, function(err) { if (err) { return done(null, false, {message: err}); } return done(null, user, {message: 'Connecté avec succès'}); }); } }); }); }); }; var verifyHandlerAssoc = function(req ,mail, password, done) { process.nextTick(function() { Association.findOne({ name: mail }).exec(function(err, user) { if (err || !user) { return done(err); } bcrypt.compare(password, user.password, function(err, res) { if (!res) { return done(null, false, {message: 'Mot de passe incorrect'}); } else { /** The user's password is correct, so log them in. */ req.logIn(user, function(err) { if (err) { return done(null, false, {message: err}); } return done(null, user, {message: 'Connecté avec succès'}); }); } }); }); }); }; /** Register the LocalStrategy with Passport. */ passport.use('local', new LocalStrategy({ usernameField: 'email', passwordField: '<PASSWORD>', passReqToCallback: true }, verifyHandler)); passport.use('localassoc', new LocalStrategy({ usernameField: 'name', passwordField: '<PASSWORD>', passReqToCallback: true }, verifyHandlerAssoc)); passport.use('facebook',new FacebookStrategy({ clientID: "1025320690924678", clientSecret: "<KEY>", callbackURL: "http://localhost:1337/facebook-callback" }, function(accessToken, refreshToken, profile, cb) { User.findOrCreate({ facebookId: profile.id }, function (err, user) { return cb(err, user); }); } )); <file_sep>/** * ## Angular Application * * Creates the Angular application called ***App*** for the whole website * */ 'use strict'; /** Creation of the app and adding all dependencies for the used modules. */ var app = angular.module('App', ['ngRoute', 'ui-notification','ngDialog']) /** Default config for the Notification service to display on-screen notification easily*/ .config(function(NotificationProvider) { NotificationProvider.setOptions({ delay: 2000, startTop: 20, startRight: 10, verticalSpacing: 20, horizontalSpacing: 20, positionX: 'right', positionY: 'bottom' }); }); <file_sep># Sails Gulp ## Installation ### Prérequis - [Node.js](https://nodejs.org/) à installer en version 5 (suivre les instructions selon votre OS). - Gulp/Sails/Bower installé sur le système. Si ce n'est pas le cas, lancer : `npm i -g sails gulp bower` - Quelques connaissances sur Sails et Angular sont préférables. - Avoir installé un compilateur C++ (cf ici pour chaque OS : https://github.com/nodejs/node-gyp) ### Sous Windows : L'utilisation de [Cmder](http://cmder.net/) en guise de terminal est fortement recommandée. TODO : écrire les instructions windows ### Sous Linux/MacOSX : ```bash npm i -g sails gulp bower npm i bower i sails lift ```<file_sep>/** * AssociationController * * @description :: Server-side logic for managing Associations * @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers */ var http = require('http'); var escape = require('escape-html'); var async = require('async'); var _ = require('lodash'); module.exports = { getassocs: function (req,res,next) { if (!req.body.lat || req.body.lat=="" || req.body.lat==null) return res.send({error: "no lat"}); if (!req.body.lon || req.body.lon=="" || req.body.lon==null) return res.send({error: "no lon"}); if (!req.body.action || req.body.action=="" || req.body.action==null) return res.send({error: "no action"}); function calculateDistance(lat1, long1, lat2, long2) { //radians lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0; long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0; lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0; long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0; // use to different earth axis length var a = 6378137.0; // Earth Major Axis (WGS84) var b = 6356752.3142; // Minor Axis var f = (a-b) / a; // "Flattening" var e = 2.0*f - f*f; // "Eccentricity" var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 ))); var cos = Math.cos( lat1 ); var x = beta * cos * Math.cos( long1 ); var y = beta * cos * Math.sin( long1 ); var z = beta * ( 1 - e ) * Math.sin( lat1 ); beta = ( a / Math.sqrt( 1.0 - e * Math.sin( lat2 ) * Math.sin( lat2 ))); cos = Math.cos( lat2 ); x -= (beta * cos * Math.cos( long2 )); y -= (beta * cos * Math.sin( long2 )); z -= (beta * (1 - e) * Math.sin( lat2 )); return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000); }; Association.find().exec(function(err,result){ console.log(result); if(err) return res.send(err); var restmp=[]; async.forEach(result,function(association, callback){ if( _.find(association.ressources, {action:req.body.action}) && _.find(association.ressources, {action:req.body.action}).status){ var km = calculateDistance(req.body.lat,req.body.lon,association.lat,association.lon); restmp.push({name:association.name,dist:km}); } callback(); }, function(err){ if(err){throw err;} restmp.sort(function(a, b) { return parseFloat(a.km) - parseFloat(b.km); }); res.send({data:restmp}); }); }); }, getassochelper: function (req,res,next) { if (!req.body.lat || req.body.lat=="" || req.body.lat==null) return res.send({error: "no lat"}); if (!req.body.lon || req.body.lon=="" || req.body.lon==null) return res.send({error: "no lon"}); if (!req.body.action || req.body.action=="" || req.body.action==null) return res.send({error: "no action"}); function calculateDistance(lat1, long1, lat2, long2) { //radians lat1 = (lat1 * 2.0 * Math.PI) / 60.0 / 360.0; long1 = (long1 * 2.0 * Math.PI) / 60.0 / 360.0; lat2 = (lat2 * 2.0 * Math.PI) / 60.0 / 360.0; long2 = (long2 * 2.0 * Math.PI) / 60.0 / 360.0; // use to different earth axis length var a = 6378137.0; // Earth Major Axis (WGS84) var b = 6356752.3142; // Minor Axis var f = (a-b) / a; // "Flattening" var e = 2.0*f - f*f; // "Eccentricity" var beta = (a / Math.sqrt( 1.0 - e * Math.sin( lat1 ) * Math.sin( lat1 ))); var cos = Math.cos( lat1 ); var x = beta * cos * Math.cos( long1 ); var y = beta * cos * Math.sin( long1 ); var z = beta * ( 1 - e ) * Math.sin( lat1 ); beta = ( a / Math.sqrt( 1.0 - e * Math.sin( lat2 ) * Math.sin( lat2 ))); cos = Math.cos( lat2 ); x -= (beta * cos * Math.cos( long2 )); y -= (beta * cos * Math.sin( long2 )); z -= (beta * (1 - e) * Math.sin( lat2 )); return (Math.sqrt( (x*x) + (y*y) + (z*z) )/1000); }; Association.find().exec(function(err,result){ console.log(result); if(err) return res.send(err); var restmp=[]; async.forEach(result,function(association, callback){ if( _.find(association.ressources, {action:req.body.action})){ var km = calculateDistance(req.body.lat,req.body.lon,association.lat,association.lon); restmp.push({name:association.name,dist:km}); } callback(); }, function(err){ if(err){throw err;} restmp.sort(function(a, b) {return parseFloat(a.km) - parseFloat(b.km);}); res.send({data:restmp}); }); }); } };<file_sep>app.controller('InsideDialogCtrl', function ($scope, $http, ngDialog,$location, $window) { $scope.openHelperDialog = function () { ngDialog.open({ template: 'HelperDialog', controller: 'InsideDialogCtrl', className: 'ngdialog-theme-default' }); } $scope.openAssoDialog = function () { ngDialog.open({ template: 'AssoDialog', controller: 'InsideDialogCtrl', className: 'ngdialog-theme-default' }); } $scope.connectRefugee = function () { $http.post("/auth-local", $scope.user) .then(function(response) { if (response.data){ $window.location.href = '/'; } }, function(response) { alert(response.error); }); } $scope.connectDonor = function () { $http.post("/auth-local", $scope.helper) .then(function(response) { if (response.data){ $window.location.href = '/'; } }, function(response) { alert(response.error); }); } $scope.connectAsso = function () { $http.post("/auth-local-assoc", $scope.asso) .then(function(response) { if (response.data){ $window.location.href = '/'; } }, function(response) { alert(response.error); }); } $scope.createRefugee = function () { $scope.user.situation="refugee"; $http({ method: 'POST', url: "/personnes", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); }, data: { first_name:$scope.user.first_name.toString(), last_name:$scope.user.last_name.toString(), password:$<PASSWORD>(), birthdate:$scope.user.birthdate, email:$scope.user.email.toString(), gender:$scope.user.gender.toString(), situation:$scope.user.situation.toString() } }).success(function () {$window.location.href = '/';}) .error(function(error){console.log(error)}); } $scope.createDonor = function () { $scope.helper.situation="donor"; $http({ method: 'POST', url: "/personnes", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); }, data: { first_name:$scope.helper.first_name.toString(), last_name:$scope.helper.last_name.toString(), password:$<PASSWORD>(), birthdate:$scope.helper.birthdate, email:$scope.helper.email.toString(), gender:$scope.helper.gender.toString(), situation:$scope.helper.situation.toString() } }).success(function () {$window.location.href = '/';}) .error(function(error){console.log(error)}); } $scope.createAsso = function () { $http.get( "http://nominatim.openstreetmap.org/?format=json&addressdetails=1&format=json&limit=1&q="+$scope.asso.address.toString()) .success(function(response) { console.log(response); $http({ method: 'POST', url: "/associations", headers: {'Content-Type': 'application/x-www-form-urlencoded'}, transformRequest: function(obj) { var str = []; for(var p in obj) str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); return str.join("&"); }, data: { name:$scope.asso.name.toString(), password:$<PASSWORD>(), address:$scope.asso.address.toString(), email:$scope.asso.email.toString(), lat:response[0].lat, lon:response[0].lon } }).success(function () {$window.location.href = '/';}) .error(function(error){console.log(error)}); }) .error(function(error){console.log(error)}); } });
5bcb6122e535f7b368016ce790ab1a6f868184c1
[ "JavaScript", "Markdown" ]
8
JavaScript
farfeduc/Sails-gulp2
83b7141761a13267381a55e58c729d4ef217ce29
66889aaa4f1b17929a5602a001228394a937f7de
refs/heads/master
<file_sep>/* Copyright (c) 2018, <NAME> */ /* * In the railfence cipher (A.K.A. zigzag cipher), the plain text is written * downwards and diagnoally on successive "rails" on an imaginary fence, then * moving up when the bottom rail is reached. When the top rail is rached, the * message is written downwards again until the whole plaintext is written out. * Then message is read off in rows as ciphertext. * * Refer to: https://en.wikipedia.org/wiki/Rail_fence_cipher */ #include <assert.h> #include <stdio.h> // for printf #include <stdlib.h> #include <string.h> #include "railfence.h" #include "utils.h" typedef enum { UP=0, DOWN, } Move_Direction; /* Get the rail of plaintext data */ static int RailfenceGetNextRail(int preRail, // IN int rails, // IN Move_Direction *md) // IN/OUT { int rail = preRail; //printf("DEBUG RailfenceGetNextRail: preRail %d, rails %d, md:%s ", // preRail, rails, (*md==DOWN ? "DOWN" : "UP")); if (*md == DOWN) { rail++; if (rail == rails) { rail = rails-2; *md = UP; } } else { rail--; if (rail == -1) { rail = 1; *md = DOWN; } } return rail; } /* Given length of plain/cipher text 'inputLen' and number of rails 'rails', get the number of data in each rail. */ static CryptoUtil_ErrorCode RailfenceGetNumberOfRails(uint64 inputLen, // IN uint64 *numOfRails, // OUT uint64 rails) // IN { if (numOfRails == NULL || rails > inputLen) { return CryptoUtil_Error_InvalidParam; } int rail; int preRail=-1; Move_Direction md=DOWN; memset(numOfRails, 0, rails * sizeof(uint64)); for (uint64 i=0; i<inputLen; i++) { rail = RailfenceGetNextRail(preRail, rails, &md); assert(rail>=0 && rail<rails); numOfRails[rail]++; preRail = rail; } return CryptoUtil_Error_Success; } /* Given the length of plain/cipher text 'inputLen' and number of data in each rail 'numOfRails', get the position of the first data of each rail in ciphertext. Note: numOfRails and railsBasePos may share same memory address. */ static CryptoUtil_ErrorCode RailfenceGetRailBasePosInCt(uint64 inputLen, // IN const uint64 *numOfRails, // IN uint64 rails, // IN uint64 *railBasePos) // OUT { if (numOfRails == NULL || railBasePos == NULL || rails > inputLen) { return CryptoUtil_Error_InvalidParam; } int i = rails-1; railBasePos[i] = inputLen - numOfRails[i]; while (--i >= 0) { railBasePos[i] = railBasePos[i+1] - numOfRails[i]; } return CryptoUtil_Error_Success; } /* Encryption */ CryptoUtil_ErrorCode Railfence_Encrypt(const char *pt, // In uint64 ptLen, // In uint64 key, // In char *ct, // Out uint64 ctLen) // In { if (pt == NULL || ct == NULL \ || ptLen == 0 || ctLen != ptLen || key >= ptLen) { return CryptoUtil_Error_InvalidParam; } if (key == 1) { memcpy(ct, pt, ptLen); return CryptoUtil_Error_Success; } int i=0; int rail=0; int preRail=-1; uint64 rails=key; Move_Direction md=DOWN; uint64 *baseOfRails; uint64 *posOfRails; CryptoUtil_ErrorCode rc; /* * Compute the number of data in each rail. */ baseOfRails = malloc(rails * sizeof(uint64)); if (baseOfRails == NULL) { return CryptoUtil_Error_OutOfMem; } rc = RailfenceGetNumberOfRails(ptLen, baseOfRails, key); assert(rc == CryptoUtil_Error_Success); /* * Compute position of each rail's 1st data in ciphertext. */ rc = RailfenceGetRailBasePosInCt(ptLen, baseOfRails, key, baseOfRails); assert(rc == CryptoUtil_Error_Success); /* * Compute ciphertext of different rails in parallel. */ preRail = -1; md = DOWN; posOfRails = malloc(sizeof(uint64) * rails); if (posOfRails == NULL) { return CryptoUtil_Error_OutOfMem; } memset(posOfRails, 0, sizeof(uint64) * key); for (i=0; i<ptLen; i++) { rail = RailfenceGetNextRail(preRail, rails, &md); int ctPos = baseOfRails[rail] + posOfRails[rail]; ct[ctPos] = pt[i]; posOfRails[rail]++; preRail = rail; } free(posOfRails); free(baseOfRails); return CryptoUtil_Error_Success; } /* Decryption */ CryptoUtil_ErrorCode Railfence_Decrypt(const char *ct, // In uint64 ctLen, // In uint64 key, // In char *pt, // Out uint64 ptLen) // In { if (pt == NULL || ct == NULL \ || ptLen == 0 || ctLen != ptLen) { return CryptoUtil_Error_InvalidParam; } if (key == 1) { memcpy(pt, ct, ctLen); return CryptoUtil_Error_Success; } /* * Compute the number of elements for each rail. */ CryptoUtil_ErrorCode rc; uint64 *baseOfRails; baseOfRails = malloc(key * sizeof(uint64)); if (baseOfRails == NULL) { return CryptoUtil_Error_OutOfMem; } rc = RailfenceGetNumberOfRails(ptLen, baseOfRails, key); assert(rc == CryptoUtil_Error_Success); /* * Compute position of each rail's 1st data in ciphertext. */ rc = RailfenceGetRailBasePosInCt(ptLen, baseOfRails, key, baseOfRails); assert(rc == CryptoUtil_Error_Success); /* * Decrypt the ciphertext. */ uint64 ptPos = 0; uint64 rails = key; int rail; int preRail = -1; uint64 *posOfRails; Move_Direction md=DOWN; uint64 ctPos; posOfRails = malloc(sizeof(uint64) * rails); if (posOfRails == NULL) { return CryptoUtil_Error_OutOfMem; } memset(posOfRails, 0, sizeof(uint64) * rails); while(ptPos < ptLen) { rail = RailfenceGetNextRail(preRail, rails, &md); assert(rail < rails); preRail = rail; ctPos = baseOfRails[rail] + posOfRails[rail]; assert(ctPos < ctLen); pt[ptPos++] = ct[ctPos]; posOfRails[rail]++; } free(posOfRails); free(baseOfRails); return CryptoUtil_Error_Success; } <file_sep>/* Copyright (c) 2018, <NAME> */ #include <stdio.h> #include <string.h> #include "caesar.h" #include "cryptoUtil_types.h" CryptoUtil_ErrorCode CompareStr(const char *actStr, const char *expStr, int len) { if (strncmp(actStr, expStr, len) != 0) { printf("Expect: %s, actual: %s\n", expStr, actStr); return CryptoUtil_Error_Failure; } return CryptoUtil_Error_Success; } CryptoUtil_ErrorCode testEncryption(const char *pt, int ptLen, int key, const char *expCt) { CryptoUtil_ErrorCode rc=0; char buf[256]; rc = Caesar_Encrypt(pt, ptLen, key, buf, ptLen); if (rc != CryptoUtil_Error_Success) { printf(" **Error** PT <%s>, key <%d>, Encryption: %d (%s)\n", pt, key, rc, CryptoUtil_ErrorDesc(rc)); return rc; } buf[ptLen] = '\0'; rc = CompareStr(buf, expCt, ptLen); return rc; } CryptoUtil_ErrorCode testDecryption(const char *ct, int ctLen, int key, const char *expPt) { CryptoUtil_ErrorCode rc=0; char buf[256]; rc = Caesar_Decrypt(ct, ctLen, key, buf, ctLen); if (rc != CryptoUtil_Error_Success) { printf(" **Error** Decryption: CT <%s>, Key <%d>, %d (%s)\n", ct, key, rc, CryptoUtil_ErrorDesc(rc)); return rc; } buf[ctLen] = '\0'; rc = CompareStr(buf, expPt, ctLen); return rc; } CryptoUtil_ErrorCode testCaesarCipher() { char *pt = NULL; char *ct = NULL; char *expCt = NULL; char *expPt = NULL; int len; int key; CryptoUtil_ErrorCode rc; printf("Case testCaesarCipher() started\n"); /* * Case 1: Encrypt/Decrypt text only containing lower alphatetic characters. */ pt = "abcdewxz"; len = strlen(pt); expCt = "defghzac"; key = 3; if (testEncryption(pt, len, key, expCt) != CryptoUtil_Error_Success) { goto Error; } ct = expCt; expPt = pt; if (testDecryption(ct, len, key, expPt) != CryptoUtil_Error_Success) { goto Error; } /* * Case 2: Encrypt text only containing upper alphatetic characters. */ pt = "ABCXYZ"; len = strlen(ct); expCt= "EFGBCD"; key = 4; if ((rc=testEncryption(pt, len, key, expCt)) != CryptoUtil_Error_Success) { goto Error; } ct = expCt; expPt = pt; if ((rc=testDecryption(ct, len, key, expPt)) != CryptoUtil_Error_Success) { goto Error; } /* * Case 3: Encrypt/Decrypt text containing both digits and alphatbeic characters. */ pt = "78ABCXYZ01"; len = strlen(pt); expCt = "78EFGBCD01"; key = 4; if ((rc=testEncryption(pt, len, key, expCt)) != CryptoUtil_Error_Success) { goto Error; } ct = expCt; expPt = pt; if ((rc=testDecryption(ct, len, key, expPt)) != CryptoUtil_Error_Success) { goto Error; } printf("Case testCaesarCipher() passed\n\n"); return rc; Error: printf("Case testCaesarCipher() failed\n\n"); return rc; } int main(void) { int result = 0; result += testCaesarCipher(); return result; } <file_sep>#ifndef _CRYPTOUTIL_TYPES_H_ #define _CRYPTOUTIL_TYPES_H_ #include <stdint.h> #define uint8 uint8_t #define uint64 uint64_t typedef enum {false, true} bool; #endif <file_sep>/* Copyright (c) 2018, <NAME> */ #include <stdio.h> #include <string.h> #include "utils.h" #include "cryptoUtil_types.h" typedef struct { char oriCh; char expCh; int shift; } ShiftVec; int testShiftAlpha() { printf("Case testShiftAlpha() started\n"); ShiftVec testVectors[5] = { {'a', 'b', 1}, {'b', 'd', 2}, {'Y', 'B', 3}, {'a', 'z', -1}, {'a', 'y', -2}}; for (int i=0; i < sizeof testVectors/sizeof(ShiftVec); i++) { ShiftVec vec = testVectors[i]; char actCh = ShiftAlpha(vec.oriCh, vec.shift); if (actCh != vec.expCh) { printf("**Error** CaesarShift(%c, %d), expect %c, actual %c\n", vec.oriCh, vec.shift, vec.expCh, actCh); printf("Case testShiftAlpha() failed\n\n"); return 1; } } printf("Case testShiftAlpha() passed\n\n"); return 0; } int main(void) { int result = 0; result += testShiftAlpha(); return result; } <file_sep>/* Copyright (c) 2018, <NAME> */ #include <ctype.h> /* * Shift an alphabet character 'ch' by 'abs(steps)' places. If steps > 0, do * right shift; left shift, otherwise, E.g. * ch='a', steps=1, return 'b' * ch='b', steps=2, return 'd' * ch='Y', steps=3, return 'B' * ch='a', steps=-1, return 'z' * ch='A', steps=-2, return 'Y' * ch='2', steps=-2, return '2' * * Note: This is a no-op if 'ch' is non English charcter. */ char ShiftAlpha(char ch, int steps) { char result = ch; char base = 0; //printf("%s shift <%c> %d positions\n", (steps > 0 ? "Right" : "Left"), ch, steps); if (!isalpha(ch)) { return ch; } else if (islower(ch)) { base = 'a'; } else if (isupper(ch)) { base = 'A'; } if (base != 0) { if (steps < 0) { //left shift steps *= -1; while (steps > 0) { result--; steps --; if (result < base) { result = base + 25; } } } else { // right shift while (steps > 0) { result++; steps--; if (result > base + 25) { result = base; } } } } return result; } <file_sep>/* Copyright (c) 2018, <NAME> */ #ifndef _CAESAR_H_ #define _CAESAR_H_ #include "cryptoUtil_errors.h" #include "cryptoUtil_types.h" CryptoUtil_ErrorCode Caesar_Encrypt(const char *pt, uint64 ptLen, uint8 key, \ char *ct, uint64 ctLen); CryptoUtil_ErrorCode Caesar_Decrypt(const char *ct, uint64 ctLen, uint8 key, \ char *pt, uint64 ptLen); #endif <file_sep>/* Copyright (c) 2018, <NAME> */ #include <stdio.h> #include <string.h> #include "cryptoUtil_types.h" #include "common.h" CryptoUtil_ErrorCode CompareStr(const char *actStr, const char *expStr, int len) { if (strncmp(actStr, expStr, len) != 0) { printf("Expect: %s, actual: %s\n", expStr, actStr); return CryptoUtil_Error_Failure; } return CryptoUtil_Error_Success; } <file_sep>/* Copyright (c) 2018, <NAME> */ #include <stdio.h> #include <string.h> #include "cryptoUtil_types.h" #include "common.h" #include "railfence.h" static CryptoUtil_ErrorCode testEncryption(const char *pt, int ptLen, int key, const char *expCt) { CryptoUtil_ErrorCode rc=0; char buf[256]; rc = Railfence_Encrypt(pt, ptLen, key, buf, ptLen); if (rc != CryptoUtil_Error_Success) { printf(" **Error** Encryption: PT <%s>, Key <%d>, %d (%s)\n", pt, key, rc, CryptoUtil_ErrorDesc(rc)); return rc; } buf[ptLen] = '\0'; rc = CompareStr(buf, expCt, ptLen); return rc; } static CryptoUtil_ErrorCode testDecryption(const char *ct, int ctLen, int key, const char *expPt) { CryptoUtil_ErrorCode rc=0; char buf[256]; rc = Railfence_Decrypt(ct, ctLen, key, buf, ctLen); if (rc != CryptoUtil_Error_Success) { goto ErrorOut; } buf[ctLen] = '\0'; rc = CompareStr(buf, expPt, ctLen); if (rc != CryptoUtil_Error_Success) { goto ErrorOut; } return rc; ErrorOut: printf(" **Error** Decryption: CT <%s>, Key <%d>, %d (%s)\n", ct, key, rc, CryptoUtil_ErrorDesc(rc)); return rc; } int testRailfenceCipher() { char *pt = NULL; char *expCt = NULL; int len; int key; int rc=0; printf("Case testRaifenceCipher started\n"); /* case 1 */ pt = "meetmelater"; len = strlen(pt); expCt = "meetmelater"; key = 1; if ((rc=testEncryption(pt, len, key, expCt)) != CryptoUtil_Error_Success) { rc = 1; goto Error; } if ((rc=testDecryption(expCt, len, key, pt)) != CryptoUtil_Error_Success) { rc = 1; goto Error; } /* case 2 */ pt = "meetmelater"; len = strlen(pt); expCt = "memltreteae"; key = 2; if ((rc=testEncryption(pt, len, key, expCt)) != CryptoUtil_Error_Success) { rc = 1; goto Error; } if ((rc=testDecryption(expCt, len, key, pt)) != CryptoUtil_Error_Success) { rc = 1; goto Error; } /* case 3 */ pt = "meetmelater"; len = strlen(pt); expCt = "mmteteaeelr"; key = 3; if ((rc=testEncryption(pt, len, key, expCt)) != CryptoUtil_Error_Success) { rc = 1; goto Error; } if ((rc=testDecryption(expCt, len, key, pt)) != CryptoUtil_Error_Success) { rc = 1; goto Error; } printf("Case testRaifenceCipher passed\n\n"); return rc; Error: printf("Case testRailfenceCipher() failed\n\n"); return rc; } int main(void) { int result = 0; result += testRailfenceCipher(); return result; } <file_sep>CC=gcc CFLAGS= -Wall -g MAKE=make MKDIR=mkdir RM=rm CRYPTOUTIL_DIR=$(shell pwd) export SUBDIRS=src test .PHONY: $(SUBDIRS) all clean all: $(SUBDIRS) $(SUBDIRS): $(MAKE) -C $@ clean: for dir in ${SUBDIRS}; do \ $(MAKE) -C $$dir clean;\ done <file_sep>/* Copyright (c) 2018, <NAME> */ /* The Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code or Caesar shift, is one of the simplest and most widely known encryption techniques. It is a type of substitution cipher in which each letter in the plaintext is replaced by a letter some fixed number of positions down the alphabet. For more introductions, refere to https://en.wikipedia.org/wiki/Caesar_cipher */ #include "stdio.h" #include "string.h" #include "caesar.h" #include "utils.h" /* * Encrypt plaintext by right shifting each alphabetic character 'key' places. */ CryptoUtil_ErrorCode Caesar_Encrypt(const char *pt, // IN uint64 ptLen, // IN uint8 key, // IN char *ct, // IN uint64 ctLen) // IN { if (pt == NULL || ct == NULL || ptLen <=0 || ptLen != ctLen) { return CryptoUtil_Error_InvalidParam; } for (int i = 0; i < ptLen; i++) { ct[i] = ShiftAlpha(pt[i], key); } return CryptoUtil_Error_Success; } /* * Decrypt ciphertext by left shifting each alphabetic character 'key' places. */ CryptoUtil_ErrorCode Caesar_Decrypt(const char *ct, // IN uint64 ctLen, // IN uint8 key, // IN char *pt, // OUT uint64 ptLen) // IN { if (pt == NULL || ct == NULL || ptLen <=0 || ptLen != ctLen) { return CryptoUtil_Error_InvalidParam; } for (int i = 0; i < ptLen; i++) { pt[i] = ShiftAlpha(ct[i], -key); } return CryptoUtil_Error_Success; } <file_sep>/* Copyright (c) 2018, <NAME> */ #ifndef _RAILFENCE_H_ #define _RAILFENCE_H_ #include "cryptoUtil_errors.h" #include "cryptoUtil_types.h" CryptoUtil_ErrorCode Railfence_Encrypt(const char *pt, uint64 ptLen, uint64 key, char *ct, uint64 ctLen); CryptoUtil_ErrorCode Railfence_Decrypt(const char *ct, uint64 ctLen, uint64 key, char *pt, uint64 ptLen); #endif <file_sep>/* Copyright (c) 2018, <NAME> */ #ifndef _VIGENERE_H_ #define _VIGENERE_H_ #include "cryptoUtil_errors.h" #include "cryptoUtil_types.h" CryptoUtil_ErrorCode Vigenere_Encrypt(const char *pt, uint64 ptLen, const char *key, uint8 keyLen, char *ct, uint64 ctLen); CryptoUtil_ErrorCode Vigenere_Decrypt(const char *ct, uint64 ctLen, const char *key, uint8 keyLen, char *pt, uint64 ptLen); #endif <file_sep>C = gcc CFLAGS ?= -Wall -g CRYPTOUTIL_DIR ?= $(shell pwd)/.. RM ?= rm .PHONY: all clean all: libcryptoUtil.so libcryptoUtil.so: caesar.c vigenere.c railfence.c utils.c @if [ ! -d ${CRYPTOUTIL_DIR}/build ]; then mkdir ${CRYPTOUTIL_DIR}/build/; fi @rm -rf ${CRYPTOUTIL_DIR}/build/* ${CC} ${CFLAGS} -fPIC -shared -I${CRYPTOUTIL_DIR}/inc $^ -o ${CRYPTOUTIL_DIR}/build/$@ clean: ${RM} -rf *.o <file_sep># cryptoUtil # Currently, caesar/vigenere/railfence cipher are supported. # <file_sep>/* Copyright (c) 2018, <NAME> */ #ifndef _COMMON_H_ #define _COMMON_H_ #include "cryptoUtil_errors.h" CryptoUtil_ErrorCode CompareStr(const char *actStr, const char *expStr, int len); #endif <file_sep>#ifndef _CRYPTOUTIL_ERRORS_H_ #define _CRYPTOUTIL_ERRORS_H_ typedef enum CryptoUtil_ErrorCode CryptoUtil_ErrorCode; #define CryptoUtil_Error_Defs \ def(CryptoUtil_Error_Success, "Success", 0) , \ def(CryptoUtil_Error_InvalidParam, "Invalid Parameter", 1), \ def(CryptoUtil_Error_OutOfMem, "Out of Memory", 2), \ def(CryptoUtil_Error_Failure, "Unknown failure", 3) enum CryptoUtil_ErrorCode { #define def(code, desc, val) code = val CryptoUtil_Error_Defs #undef def }; #define def(code, desc, val) desc #define Err_Strs ((char *[]) {CryptoUtil_Error_Defs}) #define CryptoUtil_ErrorDesc(errCode) \ Err_Strs[errCode - CryptoUtil_Error_Success] #endif <file_sep>/* Copyright (c) 2018, <NAME> */ #include <stdio.h> #include <string.h> #include "vigenere.h" #include "cryptoUtil_types.h" CryptoUtil_ErrorCode CompareStr(const char *actStr, const char *expStr, int len) { if (strncmp(actStr, expStr, len) != 0) { printf(" Expect: %s, actual: %s\n", expStr, actStr); return CryptoUtil_Error_Failure; } return CryptoUtil_Error_Success; } CryptoUtil_ErrorCode testEncryption(const char *pt, int ptLen, char *key, const char *expCt) { CryptoUtil_ErrorCode rc=0; char buf[256]; rc = Vigenere_Encrypt(pt, ptLen, key, strlen(key), buf, ptLen); if (rc != CryptoUtil_Error_Success) { printf(" **Error** Encryption: PT <%s>, Key <%s>, %d (%s)\n", pt, key, rc, CryptoUtil_ErrorDesc(rc)); return rc; } buf[ptLen] = '\0'; rc = CompareStr(buf, expCt, ptLen); return rc; } CryptoUtil_ErrorCode testDecryption(const char *ct, int ctLen, char *key, const char *expPt) { CryptoUtil_ErrorCode rc=0; char buf[256]; rc = Vigenere_Decrypt(ct, ctLen, key, strlen(key), buf, ctLen); if (rc != CryptoUtil_Error_Success) { printf(" **Error** Decryption: CT <%s>, key <%s>, %d (%s)\n", ct, key, rc, CryptoUtil_ErrorDesc(rc)); return rc; } buf[ctLen] = '\0'; rc = CompareStr(buf, expPt, ctLen); return rc; } CryptoUtil_ErrorCode testVigenereCipher() { char *pt = NULL; char *ct = NULL; char *expCt = NULL; char *expPt = NULL; char *key = NULL; int len; CryptoUtil_ErrorCode rc; printf("Case testVigenereCipher started\n"); /* * Case 1: Encrypt/Decrypt text only containing lower alphatetic characters. */ pt = "abcd"; len = strlen(pt); expCt = "bcee"; key = "aab"; if (testEncryption(pt, len, key, expCt) != CryptoUtil_Error_Success) { goto Error; } ct = expCt; expPt = pt; if (testDecryption(ct, len, key, expPt) != CryptoUtil_Error_Success) { goto Error; } /* * Case 2: Encrypt text only containing upper alphatetic characters. */ pt = "abc12"; len = strlen(ct); expCt= "ceg12"; key = "bcdee"; if ((rc=testEncryption(pt, len, key, expCt)) != CryptoUtil_Error_Success) { goto Error; } ct = expCt; expPt = pt; if ((rc=testDecryption(ct, len, key, expPt)) != CryptoUtil_Error_Success) { goto Error; } printf("Case testVigenereCipher passed\n\n"); return rc; Error: printf("Case testVigenereCipher() failed\n\n"); return rc; } int main(void) { int result = 0; result += testVigenereCipher(); return result; } <file_sep>CC=gcc CFLAGS?=-Wall -g CRYPTOUTIL_DIR?=$(shell pwd)/.. LD_LIBRARY_PATH=${CRYPTOUTIL_DIR}/build export LD_LIBRARY_PATH RM?=rm MKDIR?=mkdir .PHONY: all clean runTest all: clean testUtils testCaesar testVigenere testRailfence runTest testUtils: testUtils.c ${CC} ${CFLAGS} -I${CRYPTOUTIL_DIR}/inc $< -L${CRYPTOUTIL_DIR}/build -lcryptoUtil -o build/$@ testCaesar: testCaesar.c ${CC} ${CFLAGS} -I${CRYPTOUTIL_DIR}/inc $< -L${CRYPTOUTIL_DIR}/build -lcryptoUtil -o build/$@ testVigenere: testVigenere.c ${CC} ${CFLAGS} -I${CRYPTOUTIL_DIR}/inc $< -L${CRYPTOUTIL_DIR}/build -lcryptoUtil -o build/$@ testRailfence: testRailfence.c common.c ${CC} ${CFLAGS} -I${CRYPTOUTIL_DIR}/inc $^ -L${CRYPTOUTIL_DIR}/build -lcryptoUtil -o build/$@ clean: ${RM} -rf *.o build/ ${MKDIR} build runTest: testCaesar @echo "\n*** Run tests ***" @build/testUtils @build/testCaesar @build/testVigenere @build/testRailfence @echo "*** All tests passed ***\n" <file_sep>/* Copyright (c) 2018, <NAME> */ /* * The Vigenère cipher is a method of encrypting alphabetic text by using a * series of interwoven Caesar ciphers, based on the letters of a keyword. * * For more introductions, please refer to: * https://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher */ #include <stdio.h> #include <ctype.h> #include "vigenere.h" #include "utils.h" /* Check and return if the key for Vigenere Cipher is valid */ bool Vigenere_ValidKey(const char *key, // IN uint8 keyLen) // IN { if (key == NULL || keyLen == 0) { return false; } int i=0; while (i < keyLen) { if (!isalpha(key[i++])) { return false; } } return true; } /* Vigenere encryption */ CryptoUtil_ErrorCode Vigenere_Encrypt(const char *pt, // In uint64 ptLen, // In const char *key, // In uint8 keyLen, // In char *ct, // Out uint64 ctLen) // In { if (pt == NULL || ct == NULL \ || ptLen == 0 || ctLen != ptLen) { return CryptoUtil_Error_InvalidParam; } if (!Vigenere_ValidKey(key, keyLen)) { return CryptoUtil_Error_InvalidParam; } for (int i=0; i < ptLen; i++) { if (isalpha(pt[i])) { int pos = i % keyLen; ct[i] = ShiftAlpha(pt[i], tolower(key[pos])-'a'+1); } else { ct[i] = pt[i]; } } return CryptoUtil_Error_Success; } /* Vigenere decryption */ CryptoUtil_ErrorCode Vigenere_Decrypt(const char *ct, // In uint64 ctLen, // In const char *key, // In uint8 keyLen, // In char *pt, // Out uint64 ptLen) // In { if (pt == NULL || ct == NULL \ || ptLen == 0 || ctLen != ptLen) { return CryptoUtil_Error_InvalidParam; } if (! Vigenere_ValidKey(key, keyLen)) { return CryptoUtil_Error_InvalidParam; } for (int i=0; i < ptLen; i++) { if (isalpha(ct[i])) { int pos = i % keyLen; pt[i] = ShiftAlpha(ct[i], -(tolower(key[pos])-'a'+1)); } else { pt[i] = ct[i]; } } return CryptoUtil_Error_Success; } <file_sep>/* Copyright (c) 2018, <NAME> */ #ifndef _UTILS_H_ #define _UTILS_H_ char ShiftAlpha(char ch, int steps); #endif
32c66f20880fc286161a0679eeed694d840f1210
[ "Markdown", "C", "Makefile" ]
20
C
stephen-wang/cryptoUtil
34121b198a42740d7f9eb8668e628729bf22ee38
bfe8686f55cc905ce7e040b7c042a72d7bcd803f
refs/heads/master
<file_sep>const mySiema = new Siema({ duration: 300, onInit: changeCarouselInfo, onChange: changeCarouselInfo }); function changeCarouselInfo() { if(this.currentSlide <= 1){ document.querySelector('.info').innerHTML = 'Solving a school management problem, the SALAS software help faculties manage professors and classrooms.'; document.querySelector('.tech-info').innerHTML = 'Working with Java and MySQL'; } else if (this.currentSlide <= 3) { document.querySelector('.info').innerHTML = 'The MeuColetivo app help public transportation users be heard.'; document.querySelector('.tech-info').innerHTML = 'Working with Web development and Bootstrap'; } else { document.querySelector('.info').innerHTML = 'In my spare time, i make some css replications. Mostly from Dribbble.'; document.querySelector('.tech-info').innerHTML = 'Working with HTML, CSS'; } } document.querySelector('.prev').addEventListener('click', () => mySiema.prev()); document.querySelector('.next').addEventListener('click', () => mySiema.next());
50281030b01861f0af0deefe224fc1422086bf3d
[ "JavaScript" ]
1
JavaScript
JonatasFAlves/jonatasfalves.github.io
e8fae368ed8f9bfad91a88a382121e5269dd8b1c
6772f89efa797a44a0f6624e0a9cdcb9507ef488
refs/heads/main
<file_sep>// define sample function to randomly return an item in an array function sample(array) { let randomIndex = Math.floor(Math.random() * array.length) return array[randomIndex] } // define generatePassword function function generatePassword(options) { // define things user might want const lowerCaseLetters = 'abcdefghijklmnopqrstuvwxyz' const upperCaseLetters = lowerCaseLetters.toUpperCase() const numbers = '1234567890' const symbols = '`~!@$%^&*()-_+={}[]|;:"<>,.?/' // create a collection to store things user picked up let collection = [] if (options.lowercase === 'on') { collection = collection.concat(...lowerCaseLetters) } if (options.uppercase === 'on') { collection = collection.concat(...upperCaseLetters) } if (options.numbers === 'on') { collection = collection.concat(...numbers) } if (options.symbols === 'on') { collection = collection.concat(...symbols) } // remove things user do not need if (options.excludeCharacters) { collection = collection.filter( char => !options.excludeCharacters.includes(char) ) } // return error notice if collection is empty if (collection.length === 0) { return 'There is no valid character in your selection.' } // start generating password let password = '' for (let i = 0; i < options.length; i++) { password += sample(collection) } // return the generated password return password } // invoke generatePassword function module.exports = generatePassword
516d4a765746a05d18b4d62ece5a0f0af14999ef
[ "JavaScript" ]
1
JavaScript
Demilululu/Random-Password-Generator
2099ff178401c7c1340e1bf8c844d524022e2b91
9172070c7717f27a3a4981d17e1cacf0c1c769ec
refs/heads/main
<repo_name>JRavi2/Huffman-Coding-Algorithm<file_sep>/main.cpp /* Data Structures Mini Project * Huffman Coding Algorithm for Text Compression */ #include <bits/stdc++.h> using namespace std; #define MAX_TREE_HT 50 // Some global definitions map<char, string> code; int current_bit = 0, padding = 0; char bit_buffer; string bit_string = ""; struct Node { unsigned freq; char item; struct Node *left, *right; }; struct MinHeap { unsigned size; unsigned capacity; struct Node **array; }; // Create new Huffman tree node struct Node *newNode(char item, unsigned freq) { struct Node *temp = (struct Node *)malloc(sizeof(struct Node)); temp->left = temp->right = NULL; temp->item = item; temp->freq = freq; return temp; } // Create min heap using given capacity struct MinHeap *createMinHeap(unsigned capacity) { struct MinHeap *minHeap = (struct MinHeap *)malloc(sizeof(struct MinHeap)); minHeap->size = 0; minHeap->capacity = capacity; minHeap->array = (struct Node **)malloc(minHeap->capacity * sizeof(struct Node *)); return minHeap; } // Swap function to heapify void swap(struct Node **a, struct Node **b) { struct Node *t = *a; *a = *b; *b = t; } // Minimum Heapify void minHeapify(struct MinHeap *minHeap, int idx) { int smallest = idx; int left = 2 * idx + 1; int right = 2 * idx + 2; if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) smallest = left; if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) smallest = right; if (smallest != idx) { swap(&minHeap->array[smallest], &minHeap->array[idx]); minHeapify(minHeap, smallest); } } // Check if size of minheap is 1 int checkSizeOne(struct MinHeap *minHeap) { return (minHeap->size == 1); } // Getting the min frequency node from minheap struct Node *getMin(struct MinHeap *minHeap) { struct Node *temp = minHeap->array[0]; minHeap->array[0] = minHeap->array[minHeap->size - 1]; --minHeap->size; minHeapify(minHeap, 0); return temp; } // Inserting of new node made from 2 minimum frequency nodes in heap void insertHeapNode(struct MinHeap *minHeap, struct Node *minHeapNode) { ++minHeap->size; int i = minHeap->size - 1; while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { minHeap->array[i] = minHeap->array[(i - 1) / 2]; i = (i - 1) / 2; } minHeap->array[i] = minHeapNode; } // Building min heap void buildHeap(struct MinHeap *minHeap) { int n = minHeap->size - 1; int i; for (i = (n - 1) / 2; i >= 0; --i) minHeapify(minHeap, i); } // Checking if the node is a leaf node int isLeaf(struct Node *root) { return !(root->left) && !(root->right); } struct MinHeap *constructHeap(map<char, int> freq, int size) { map<char, int>::iterator itr; struct MinHeap *minHeap = createMinHeap(size); int i = 0; for (itr = freq.begin(); itr != freq.end(); ++itr) { minHeap->array[i] = newNode(itr->first, itr->second); i++; } minHeap->size = size; buildHeap(minHeap); return minHeap; } // Building Huffman Tree struct Node *buildHfTree(map<char, int> freq, int size) { struct Node *left, *right, *top; struct MinHeap *minHeap = constructHeap(freq, size); while (!checkSizeOne(minHeap)) { left = getMin(minHeap); right = getMin(minHeap); top = newNode('#', left->freq + right->freq); top->left = left; top->right = right; insertHeapNode(minHeap, top); } return getMin(minHeap); } // Mapping the codes void mapCodes(int arr[], int n, char ch) { int i; string bit; for (i = 0; i < n; ++i) { bit += to_string(arr[i]); } cout << bit; code.insert({ch, bit}); cout << "\n"; } // Get codes for each character void getCodes(struct Node *root, int arr[], int top) { if (root->left) { arr[top] = 0; getCodes(root->left, arr, top + 1); } if (root->right) { arr[top] = 1; getCodes(root->right, arr, top + 1); } if (isLeaf(root)) { cout << "\t" << root->item << " | "; mapCodes(arr, top, root->item); } } // Encoding the given file Node *encode(map<char, int> freq, int size) { struct Node *root = buildHfTree(freq, size); int arr[MAX_TREE_HT], top = 0; getCodes(root, arr, top); return root; } // Reading the file map<char, int> readFile(string filename) { ifstream file; map<char, int> freq; string line; file.open(filename); if (!file) { cout << "No such file"; } else { while (getline(file, line, '\0')) { for (char ch : line) { if (freq.find(ch) != freq.end()) freq[ch]++; else freq.insert({ch, 1}); } } } file.close(); return freq; } // Converting into bits void writeBit(ofstream &file2, int bit) { if (bit) bit_buffer |= (1 << current_bit); current_bit++; if (current_bit == 8) { bit_string += bit_buffer; current_bit = 0; bit_buffer = 0; } } // Deleting the buffer space void flushBits(ofstream &file) { while (current_bit) { writeBit(file, 0); padding++; } } // Writing the compressed file string writeFile(string filename, int should_add_header) { ifstream file1; string line; file1.open(filename); string out; ofstream file2; file2.open("compressed.txt"); while (getline(file1, line)) { line += '\n'; for (char ch : line) { bitset<sizeof(unsigned long) * 8> bits(code[ch]); string bin_code = code[ch]; int bit; for (int i = 0; i < bin_code.length(); i++) { bit = bin_code[i] == '1' ? 1 : 0; writeBit(file2, bit); out += bin_code[i]; } } } flushBits(file2); if (should_add_header) { int size = code.size(); file2.write((char *)&padding, sizeof(int)); file2.write((char *)&size, sizeof(int)); for (map<char, string>::iterator i = code.begin(); i != code.end(); i++) { file2.write((char *)&i->first, 1); int len = i->second.size(); file2.write((char *)&len, sizeof(int)); file2.write((char *)i->second.c_str(), i->second.size()); } } file2.write((char *)bit_string.c_str(), bit_string.size()); return out; } // Convert binary data into bit-string string convert_to_string(string name, int should_get_header, int &padding, map<char, string> &codes) { ifstream fin(name); char c; string res; if (should_get_header) { int size; fin.read((char *)&padding, sizeof(int)); fin.read((char *)&size, sizeof(int)); for (int i = 0; i < size; i++) { int sz; char a; string s; fin.read((char *)&a, sizeof(char)); fin.read((char *)&sz, sizeof(int)); char *value = (char *)malloc(sz + 1); fin.read(value, sz); value[sz] = '\0'; codes[a] = value; } } while (fin.get(c)) { for (int i = 0; i < 8; i++) res += char((((c >> i) & 1)) + 48); } return res; } // Decoding function to show maximum potential of the algorithm void decodeMax(string in, ofstream &fout, Node *root, int &index) { if (root == NULL) return; if (root->left == NULL && root->right == NULL) { fout << root->item; return; } index++; if (in[index] == '0') decodeMax(in, fout, root->left, index); else decodeMax(in, fout, root->right, index); } // Decoding function to show real world scenario void decodeRealWorld(string in, ofstream &fout, map<char, string> codes, int padding) { string bit = ""; map<string, char> reversecodes; string buffer; for (map<char, string>::iterator i = codes.begin(); i != codes.end(); i++) { reversecodes[i->second] = i->first; } for (int i = 0; i < in.size() - padding; i++) { bit += string(1, in[i]); if (reversecodes.find(bit) != reversecodes.end()) { buffer += (reversecodes[bit]); bit = ""; } } fout << buffer; } // Driver Function int main() { string name; map<char, int> freq; int choice; cout << "Choose an operation: " << endl; cout << "1. Compress a file" << endl; cout << "2. Decompress a file" << endl; cout << "3. Compress and Decompress a file" << endl; cin >> choice; switch (choice) { case 1: { cout << "Enter the file name: "; cin >> name; freq = readFile(name); int size = freq.size(); encode(freq, size); string out = writeFile(name, 1); break; } case 2: { map<char, string> m; int padding = 0; cout << "Enter the file name: "; cin >> name; string in = convert_to_string(name, 1, padding, m); ofstream fout("decompressed.txt"); decodeRealWorld(in, fout, m, padding); break; } case 3: { cout << "Enter the file name: "; cin >> name; freq = readFile(name); int size = freq.size(); Node *root = encode(freq, size); string out = writeFile(name, 0); map<char, string> m; int padding_placeholder = 0; string in = convert_to_string("compressed.txt", 0, padding_placeholder, m); ofstream fout("decompressed.txt"); for (int i = -1; i < (int)in.size() - padding - 2;) { decodeMax(in, fout, root, i); } break; } } } <file_sep>/README.md # Huffman Coding Algorithm for Text Compression ## Description This is a mini project I recently worked on. It is a simple text compression program based on Huffman Coding Algorithm. When ran, you are provided with 3 options: 1. Compress a file 2. Decompress a file 3. Compress and Decompress a file The first and second choices show a more real world scenario where the code map is stored along with the compressed file. The third choice just shows the maximum potential of the algorithm, by compressing and decompressing a file is succession while maintaing the code map in memory. ## How to run ``` gcc main.cpp -o main ./main ```
f2998b18929b53f184a32bbc3a285aeec3c7d636
[ "Markdown", "C++" ]
2
C++
JRavi2/Huffman-Coding-Algorithm
28f4a200b104084f5a188cbcddf83f0a8b84f1ac
1bfa5aa68ee59f9a483f2331969689ff53739453
refs/heads/master
<repo_name>slavonic-suomi/fs-simple-server<file_sep>/src/test/java/com/itsm/pub/courses/firsts_steps/server/dto/SimpleResponseSerializationTest.java package com.itsm.pub.courses.firsts_steps.server.dto; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import org.junit.runners.JUnit4; import java.io.IOException; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @RunWith(JUnit4.class) public class SimpleResponseSerializationTest { private static ObjectMapper objectMapper; @BeforeClass public static void init() { objectMapper = new ObjectMapper(); } @Test public void testSerialize() throws JsonProcessingException { SimpleResponse request = new SimpleResponse("testMessage"); String responseString = objectMapper.writeValueAsString(request); assertEquals("{\"message\":\"testMessage\"}", responseString); } @Test public void testDeserialize() throws IOException { String responseString = "{\"message\":\"testMessage\"}"; SimpleResponse response = objectMapper.readValue(responseString, SimpleResponse.class); assertNotNull(response); assertEquals("testMessage", response.getMessage()); } } <file_sep>/src/main/java/com/itsm/pub/courses/firsts_steps/server/core/processor/BaseRequestProcessor.java package com.itsm.pub.courses.firsts_steps.server.core.processor; import com.itsm.pub.courses.firsts_steps.server.core.BeanSleeper; import com.itsm.pub.courses.firsts_steps.server.core.RequestProcessor; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleRequest; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.context.annotation.Lazy; import org.springframework.context.annotation.Scope; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.support.TransactionSynchronizationManager; import static com.itsm.pub.courses.firsts_steps.server.core.processor.BaseRequestProcessor.BEAN_NAME; @Component @Scope("prototype") @Qualifier(BEAN_NAME) @Order(1) public class BaseRequestProcessor implements RequestProcessor { public static final String BEAN_NAME = "baseRequestProcessor"; private final BeanSleeper sleeper; private final RequestProcessor proxy; private final Runnable customRunnable; @Autowired public BaseRequestProcessor( BeanSleeper sleeper, @Lazy @Qualifier(BEAN_NAME) RequestProcessor proxy, @Qualifier("customRunnable")Runnable customRunnable) { this.sleeper = sleeper; this.proxy = proxy; this.customRunnable = customRunnable; } @Override public boolean accept(SimpleRequest request) { return proxy.process(request) != null; } @Override @Transactional public SimpleResponse process(SimpleRequest request) { System.out.println( TransactionSynchronizationManager.getCurrentTransactionName() ); try { customRunnable.run(); } catch (RuntimeException e) { System.out.println(e.getMessage()); } System.out.println( TransactionSynchronizationManager.getCurrentTransactionName() ); String message = request.getMessage(); String name = request.getName(); System.out.println(String.format("message from: %s, content: %s", name, message)); return new SimpleResponse("Hello, " + name); } } <file_sep>/src/test/java/com/itsm/pub/courses/firsts_steps/server/core/baseRequestProcessorTest.java package com.itsm.pub.courses.firsts_steps.server.core; import com.itsm.pub.courses.firsts_steps.server.core.processor.BaseRequestProcessor; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleRequest; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleResponse; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.test.context.ActiveProfiles; import static org.junit.Assert.*; import static org.mockito.ArgumentMatchers.anyLong; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @RunWith(MockitoJUnitRunner.class) @ActiveProfiles("test") public class baseRequestProcessorTest { @Mock private BeanSleeper sleeper; @InjectMocks private BaseRequestProcessor testee; @Before public void init() { when(sleeper.sleep(anyLong())).thenReturn("asd"); } @Test public void process() { SimpleResponse response = testee.process(new SimpleRequest("someName", "message")); assertNotNull(response); assertEquals("Hello, someName", response.getMessage()); verify(sleeper, times(2)) .sleep(anyLong()); } }<file_sep>/src/main/java/com/itsm/pub/courses/firsts_steps/server/core/processor/SuperMooProcessor.java package com.itsm.pub.courses.firsts_steps.server.core.processor; import com.itsm.pub.courses.firsts_steps.server.core.RequestProcessor; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleRequest; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleResponse; import com.itsm.pub.courses.firsts_steps.server.util.MooProfile; import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Profile; import org.springframework.core.annotation.Order; import org.springframework.stereotype.Component; @Component @Order(0) @MooProfile public class SuperMooProcessor implements RequestProcessor { @Value("${server.moo.superpower}") private Boolean hasSuperpower; @Override public SimpleResponse process(SimpleRequest request) { return new SimpleResponse( " (__) \n" + " (oo) \n" + " /------\\/ \n" + " / | || \n" + " * /\\---/\\ \n" + " ~~ ~~ \n" + "....\"Have you moo today?" ); } @Override public boolean accept(SimpleRequest request) { return hasSuperpower && request != null && "moo".equalsIgnoreCase(request.getMessage()); } } <file_sep>/src/main/java/com/itsm/pub/courses/firsts_steps/server/core/SomeDBService.java package com.itsm.pub.courses.firsts_steps.server.core; import com.itsm.pub.courses.firsts_steps.server.ServerConfig; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.core.RowMapper; import org.springframework.stereotype.Component; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.TransactionStatus; import org.springframework.transaction.support.DefaultTransactionDefinition; import org.springframework.transaction.support.TransactionCallback; import org.springframework.transaction.support.TransactionTemplate; import java.sql.Connection; import java.util.List; //@Component public class SomeDBService { private final JdbcTemplate jdbcTemplate; private final RowMapper<ServerConfig.AllergyRemap> allergyMapper; private final PlatformTransactionManager txManager; @Autowired public SomeDBService(JdbcTemplate jdbcTemplate, RowMapper<ServerConfig.AllergyRemap> allergyMapper, PlatformTransactionManager txManager) { this.jdbcTemplate = jdbcTemplate; this.allergyMapper = allergyMapper; this.txManager = txManager; } public void run() { // Connection connection = jdbcTemplate.getDataSource().getConnection(); // connection.commit(); TransactionTemplate template = new TransactionTemplate(txManager); template.execute(new TransactionCallback<Object>() { @Override public Object doInTransaction(TransactionStatus status) { List<ServerConfig.AllergyRemap> allergy = jdbcTemplate.query("select * from alr_master_remap", allergyMapper); System.out.println(allergy); return null; } }); // TransactionStatus tx = // txManager.getTransaction(new DefaultTransactionDefinition()); //tx.tx } } <file_sep>/src/main/resources/server.properties server.moo.superpower = true server.port = 8081 server.thread.count = 4 spring.profiles.active = dev,moo server.driver = com.mysql.cj.jdbc.Driver server.url = jdbc:mysql://localhost/gp_stg server.user = root server.password = <PASSWORD> <file_sep>/src/main/java/com/itsm/pub/courses/firsts_steps/server/core/RequestProcessor.java package com.itsm.pub.courses.firsts_steps.server.core; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleRequest; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleResponse; public interface RequestProcessor { SimpleResponse process(SimpleRequest request); boolean accept(SimpleRequest request); } <file_sep>/src/main/java/com/itsm/pub/courses/firsts_steps/server/core/BeanSleeper.java package com.itsm.pub.courses.firsts_steps.server.core; public interface BeanSleeper { String sleep(long ms); } <file_sep>/src/main/java/com/itsm/pub/courses/firsts_steps/server/core/processor/AnotherOneRequestProcessor.java package com.itsm.pub.courses.firsts_steps.server.core.processor; import com.itsm.pub.courses.firsts_steps.server.core.RequestProcessor; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleRequest; import com.itsm.pub.courses.firsts_steps.server.dto.SimpleResponse; import org.springframework.beans.factory.BeanNameAware; import org.springframework.context.annotation.Primary; import org.springframework.stereotype.Component; @Component public class AnotherOneRequestProcessor implements RequestProcessor { @Override public SimpleResponse process(SimpleRequest request) { return null; } @Override public boolean accept(SimpleRequest request) { return false; } }
2d1b56277c26fffd50ca3b386f0d2adeceafe548
[ "Java", "INI" ]
9
Java
slavonic-suomi/fs-simple-server
ccb1542eecc21ed6a11962aca68a28d268b4d06d
532d4c01caceb1df8aeb05b3ec0e908f81f1c70b
refs/heads/master
<file_sep># tea-reading A site to display tea readings <file_sep> //flashlight effect let map = document.querySelector(".map"); let moveLight = (event) => { // console.log(event.target); var light = document.querySelector(".reveal"); light.style.clipPath = `circle(80px at ${event.offsetX}px ${event.offsetY}px)`; } map.addEventListener("mousemove", function(event){ moveLight(event); }); //setup the mp3 to play on click on the pin var music = new Audio(); function playMusic(file) { music.pause(); music = new Audio(file); music.volume = 0.7; music.play(); } //pin click -> show tea modal let teaModal = document.querySelector(".tea-container-modal"); let pins = document.querySelectorAll(".pin"); pins.forEach(pin => { pin.addEventListener("click", function(){ playMusic("magic-chime.mp3"); teaModal.style.display = "block"; setTimeout(function(){ teaModal.style.opacity = 1; }, 100); }) }) //exit out of tea modal let close = document.querySelector(".close"); close.addEventListener("click", function(){ teaModal.style.opacity = 0; setTimeout(function(){ teaModal.style.display = "none"; }, 200); })
fac9c50e58754ed650fb396cc51572fb532dbab9
[ "Markdown", "JavaScript" ]
2
Markdown
Ceciceciceci/tea-reading
2b93ae0b63cc34fabfaab2b906cdd9d617094167
75f77e8d3d73aed19c1be6bf687493baed9f414f
refs/heads/master
<file_sep>Wordpress Docker Starter ======================== Includes ------------ * wordpress * mariadb * phpmyadmin Usage ------------ Command to start the containers: ```bash $ docker-compose up -d ``` Command to save the database dump ```bash $ scripts/database-save.sh ``` Command to restore the database dump, will override unsaved changes! ```bash $ scripts/database-restore.sh ```<file_sep>#!/bin/sh docker exec db /usr/bin/mysqldump -u root --password=<PASSWORD> wordpress > ./data/dump.sql
0c014fd8898547d0bdbd945892b51f9c8d2d7fe6
[ "Markdown", "Shell" ]
2
Markdown
leonhusmann/docker-wordpress-starter
0cfb2c79a6b39c03381ef7d33246f24d12542e7e
73f9f115cc07a3a2b0baeffae65474dfac5d495c
refs/heads/master
<file_sep>#pragma once #include<string> #include<map> #include<vector> #include <memory> #include<iostream> enum allowed_types : int{ string, integer, floating_point }; class AbstractColumn { public: std::string name; virtual std::string get_at_as_string(size_t index) = 0; virtual void add(std::string value) = 0; }; class StringColumn : public AbstractColumn { std::vector<std::string> column; public: StringColumn(std::string name_) { column = std::vector<std::string>(); name = name_; } virtual std::string get_at_as_string(size_t index) { return column[index]; } virtual void add(std::string value) { column.push_back(value); } }; class IntegerColumn : public AbstractColumn { std::vector<int> column; public: IntegerColumn(std::string name_){ name = name_; column = std::vector<int>(); } virtual std::string get_at_as_string(size_t index) { return std::to_string(column[index]); } virtual void add(std::string value) { column.push_back(std::stoi(value)); } }; class DoubleColumn : public AbstractColumn { std::vector<double> column; public: DoubleColumn(std::string name_){ column = std::vector<double>(); name = name_; } virtual std::string get_at_as_string(size_t index) { return std::to_string(column[index]); } virtual void add(std::string value) { column.push_back(std::stod(value)); } }; class Database { public: Database() { columns = std::map<std::string, std::unique_ptr<AbstractColumn>>(); }; void InsertColumn(const std::string &name, const allowed_types &type) { switch (type) { case string: columns[name] = std::make_unique<StringColumn>(name); break; case integer: columns[name] = std::make_unique<IntegerColumn>(name); break; case floating_point: columns[name] = std::make_unique<DoubleColumn>(name); break; } }; void AddRow(const std::string &row); void Print(); private: std::map<std::string, std::unique_ptr<AbstractColumn>> columns; int number_of_rows; }; <file_sep> #include "stdafx.h" #include "Database.h" std::vector<std::string> split(const std::string& str, const std::string& delim) { std::vector<std::string> tokens; size_t prev = 0, pos = 0; do { pos = str.find(delim, prev); if (pos == std::string::npos) pos = str.length(); std::string token = str.substr(prev, pos - prev); if (!token.empty()) tokens.push_back(token); prev = pos + delim.length(); } while (pos < str.length() && prev < str.length()); return tokens; } void Database::AddRow(const std::string &row) { std::vector<std::string> tokens = split(row, ","); for (size_t i = 0; i != tokens.size(); i++) { std::vector<std::string> key_value = split(tokens[i], ":"); columns[key_value[0]]->add(key_value[1]); } number_of_rows++; } void Database::Print() { for (size_t i = 0; i < number_of_rows; i++) { for (std::map<std::string, std::unique_ptr<AbstractColumn>>::iterator it = columns.begin(); it != columns.end(); ++it) { std::cout << columns[it->first]->get_at_as_string(i) << " "; } std::cout << std::endl; } } int main(){ Database d = Database(); d.InsertColumn("name", string); d.InsertColumn("age", integer); d.AddRow("name:Alex,age:7"); d.AddRow("name:Kate,age:23"); d.Print(); } <file_sep>#pragma once #include <vector> class Board { std::vector<std::vector<char> > board; public: size_t size; explicit Board(size_t size); Board(); void make_play(int x, int y, char symbol); const void print(); const bool check_for_winner(int limit); bool is_valid_move(int x, int y); private: const bool check_for_winner_row(bool rows, int limit); }; class Game { int turn = 0; char p1_symbol = 'X'; char p2_symbol = 'O'; Board board; public: void play(); Game(); private: void play_turn(); };
d2211a0e72c1579aae6277db2c7ea2b8dff9c26a
[ "C++" ]
3
C++
Alobal123/CvikaCpp
7fcd95a7ba606e4f965ba8d018cd78c7f307b295
ae07d272705ea0f8d3c0462feb3ef9fb920643ef
refs/heads/master
<repo_name>EvanPalmer/TpbContextSearch<file_sep>/contentscript_imdb.js //debugger; (function($, undefined){ window.onload = function(){ //debugger; var thisIsImdb = window.location.href.indexOf('//www.imdb.com/') > 0; if(thisIsImdb){ // debugger; // add bootstrap JS from CDN $.getScript("//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/js/bootstrap.min.js", function(){ var thisIsAMoviePage = window.location.href.indexOf('/title/') > 0; if(thisIsAMoviePage){ var container = $('#prometer_container'); debugger; var searchTerm = $('h1.header').text(); if(container == undefined || container.length === 0){ // this is if it's a TV series. container = $('#warplink').parent(); container.css('float', 'right'); searchTerm = $('h1.header .itemprop').text(); } // make room for the new DDL container.css('left', '-10px').children().remove(); container.tpbSearch({'searchTerm' : searchTerm }); } var thisIsPersonPage = window.location.href.indexOf('/name/') > 0; if(thisIsPersonPage){ var container = $('#prometer_container'); // make room for the new DDL container.css('left', '-10px').children().remove(); var header = $('h1.header').clone(); header.find('span').remove() container.tpbSearch({'searchTerm' : header.text() }); } var thisIsAListPage = window.location.href.indexOf('/list/') > 0; if(thisIsAListPage){ $('.list.detail .list_item .info b').each(function (i, e){ var currentElement = $(e); var container = $('<span>').attr('class', 'list_container').css('float','right'); currentElement.append(container); // make room for the new DDL //container.css('left', '-10px').children().remove(); var header = $('h1.header').clone(); header.find('span').remove() container.tpbSearch({'searchTerm' : currentElement.text() }); }); } }); }; }; }(jQuery)); (function($) { $.fn.extend({ tpbSearch : function(options){ var defaults = { searchTerm: ''}; var options = $.extend(defaults, options); return this.each(function(){ doSearch($(this), options.searchTerm); }) } }); // private functions function doSearch(container, searchTerm){ // here we should iterate over the container selector, becuase it's possible multiple items will be selected. var sanitizedSearchTerm = sanitizeSearchTerm(searchTerm); // set the default logo var logo = $('<img id="tpb-logo" src="http://thepiratebay.se/static/downloads/preview-cassette.gif">').css('width', '50px').css('height', '50px'); var searchUrl = 'http://thepiratebay.se/search/' + encodeURIComponent(sanitizedSearchTerm) + '/0/7/0' $.get(searchUrl, function(data){ var resultTds = $(data).find('a[title="Download this torrent using magnet"]:lt(5)').closest('td'); // Handle no results from TPB if(resultTds.length === 0) { container.append(logo).attr('title', 'Sorry, no results on TPB for this one...') .fadeIn('slow'); return; } // Sweet! We have some results! logo.attr('src', 'http://thepiratebay.se/static/downloads/preview-tpb-logo.gif'); buildDropdownList(container, resultTds, sanitizedSearchTerm, logo); container.fadeIn('slow'); }); } function sanitizeSearchTerm(searchTerm){ return searchTerm.replace(/(\d+ tv series)/ig, '') // get rid of the word TV Series, because most torrents don't have that string in there .replace(/(\d+ documentary)/ig, '') // get rid of the word Documentary, because most torrents don't have that string in there .replace(/[^\s\w\d]+/ig, '') // get rid of weird-ass characters .replace(/\s+/g, ' ') // get rid of excessive spaces .trim(); // keep that shit trim, motherfucker } function buildDropdownList(container, items, searchTerm, logo){ // build the bones of the DDL container.append($('<ul class="nav nav-pills">') .append($('<li class="dropdown">') .append($('<a class="dropdown-toggle" data-toggle="dropdown" href="#">').append(logo)) .append($('<ul class="dropdown-menu">') .append($('<li>').append('<a target="_blank" href="http://thepiratebay.se/search/' + encodeURIComponent(searchTerm) + '/0/7/0">Search TPB for "' + searchTerm + '"</a>')) .append($('<li class="divider">'))))); // add all the links for the top 5 magent links items.each(function(i, e) { var description = $(e).find('font.detDesc').text(); var sizeExtractionRegex = /.+Size (.+?),.+/i; var size = sizeExtractionRegex.exec(description)[1]; var linkName = $(e).find('a.detLink').text(); var contextMenuTitle = '(' + size + ') ' + linkName; var magnetUrl = $(e).find('a[title="Download this torrent using magnet"]').attr('href'); container.find('.dropdown-menu').append($('<li>').append($('<a>').attr('href', magnetUrl).append(contextMenuTitle))); }); } }(jQuery)); // (function($) { // $.fn.tpbSearcher = function(element, options){ // debugger; // console.log(element); // this.options = {}; // element.data('tpbSearcher', this); // this.init = function(element,options){ // this.options = $.extend({}, $.tpbSearcher.defaultOptions, options); // debugger; // // do the search on init // } // // public function // this.doSearch = function(container, searchTerm){ // // here we should iterate over the container selector, becuase it's possible multiple items will be selected. // var sanitizedSearchTerm = sanitizeSearchTerm(searchTerm); // // set the default logo // var logo = $('<img id="tpb-logo" src="http://thepiratebay.se/static/downloads/preview-cassette.gif">').css('width', '50px').css('height', '50px'); // var searchUrl = 'http://thepiratebay.se/search/' + encodeURIComponent(sanitizedSearchTerm) + '/0/7/0' // $.get(searchUrl, function(data){ // var resultTds = $(data).find('a[title="Download this torrent using magnet"]:lt(5)').closest('td'); // // Handle no results from TPB // if(resultTds.length === 0) { // container.append(logo).attr('title', 'Sorry, no results on TPB for this one...') // .fadeIn('slow'); // return; // } // // Sweet! We have some results! // logo.attr('src', 'http://thepiratebay.se/static/downloads/preview-tpb-logo.gif'); // buildDropdownList(container, resultTds, sanitizedSearchTerm, logo); // container.fadeIn('slow'); // }); // } // // call initialise when instatiated // this.init(element, options); // } // // private functions // function sanitizeSearchTerm(searchTerm){ // return searchTerm.replace(/(\d+ tv series)/ig, '') // get rid of the word TV Series, because most torrents don't have that string in there // .replace(/[^\s\w\d]+/ig, '') // get rid of weird-ass characters // .replace(/\s+/g, ' ') // get rid of excessive spaces // .trim(); // keep that shit trim, motherfucker // } // function buildDropdownList(container, items, searchTerm, logo){ // // build the bones of the DDL // container.append($('<ul class="nav nav-pills">') // .append($('<li class="dropdown">') // .append($('<a class="dropdown-toggle" data-toggle="dropdown" href="#">').append(logo)) // .append($('<ul class="dropdown-menu">') // .append($('<li>').append('<a target="_blank" href="http://thepiratebay.se/search/' + encodeURIComponent(searchTerm) + '/0/7/0">Search TPB for "' + searchTerm + '"</a>')) // .append($('<li class="divider">'))))); // // add all the links for the top 5 magent links // items.each(function(i, e) { // var description = $(e).find('font.detDesc').text(); // var sizeExtractionRegex = /.+Size (.+?),.+/i; // var size = sizeExtractionRegex.exec(description)[1]; // var linkName = $(e).find('a.detLink').text(); // var contextMenuTitle = '(' + size + ') ' + linkName; // var magnetUrl = $(e).find('a[title="Download this torrent using magnet"]').attr('href'); // container.find('.dropdown-menu').append($('<li>').append($('<a>').attr('href', magnetUrl).append(contextMenuTitle))); // }); // } // // set default options // $.fn.tpbSearcher.defaultOptions = { // class: 'tpbSearcher', // searchTerm: '' // } // }(jQuery)); <file_sep>/contentscript.js (function(){ // debugger ; window.onmouseup = function(e){ // debugger ; var x = window.getSelection().toString(); chrome.extension.sendMessage({directive: "page-clicked", selectedText: x}, function(response) { }); }; }()); <file_sep>/doTheWork.js // TODO: // WATCH THESE VIDEOS // http://www.youtube.com/watch?v=B4M_a7xejYI&list=ECCA101D6A85FE9D4B // should make the search a jQuery plug in. // add <NAME> and Wikipedia // Could use Url Filter to do something to IMDB http://developer.chrome.com/extensions/events.html#type-UrlFilter (parse when the dom is loaded) // Clean up folder structure, and remove unused files // Sometimes it stops working - the search term doesn't update and the onclick on the" Search TBP for XXX" does nothing // What happens when you don't have uTorrent installed? // How to add preferences?? Like, prefer HQ, prefer most recent, exclude XXX, // It would be cool if I could rename it, so it downloaded with the name of the movie and the year etc // add an options page - so we can remove XXX content // Convert background page to event page // in manifest: background persistent = false // http://developer.chrome.com/extensions/event_pages.html function genericOnClick(searchText) { var searchUrl = 'http://thepiratebay.se/search/' + encodeURIComponent(searchText) + '/0/7/0' chrome.tabs.create({'url': searchUrl}, function(tab) { // Tab opened. }); } function loadMagnetLink(magnetLink){ chrome.tabs.create({'url': magnetLink}, function(tab) { // must be a better way of doing this window.setTimeout(function(){chrome.tabs.remove(tab.id)},1000) }); } var parentId = 0; var lastSearchTerm = ''; var loadingId = 0; chrome.extension.onMessage.addListener( function(request, sender, sendResponse) { switch (request.directive) { case 'page-clicked': // execute the content script //console.log(request.selectedText); if((request.selectedText.length <= 0)||(lastSearchTerm === request.selectedText)){ // don't bother doing anything if they didn't select nothing special return; } lastSearchTerm = request.selectedText; var searchUrl = 'http://thepiratebay.se/search/' + encodeURIComponent(request.selectedText) + '/0/7/0' var xhr = new XMLHttpRequest(); xhr.open('GET', searchUrl, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { // Get rid of the menu item claiming we're loading (because we have a response now) chrome.contextMenus.remove(loadingId); var resultTds = $(xhr.responseText).find('a[title="Download this torrent using magnet"]:lt(5)').closest('td'); // Handle no results from TPB if(resultTds.length === 0) { chrome.contextMenus.create({'title': "TPB a'int got nothing.", 'parentId': parentId, 'contexts':['selection'], 'onclick': $.noop}); return; } // Sweet! We have some results! resultTds.each(function(i, e) { var description = $(e).find('font.detDesc').text(); var sizeExtractionRegex = /.+Size (.+?),.+/i; var size = sizeExtractionRegex.exec(description)[1]; var linkName = $(e).find('a.detLink').text(); var contextMenuTitle = '(' + size + ') ' + linkName; var magnetUrl = $(e).find('a[title="Download this torrent using magnet"]').attr('href'); chrome.contextMenus.create({'title': contextMenuTitle, 'parentId': parentId, 'contexts':['selection'], 'onclick': function() { loadMagnetLink(magnetUrl); }}); }); } } xhr.send(); sendResponse({}); // sending back empty response to sender var title = "Search TPB for '" + request.selectedText + "'"; chrome.contextMenus.removeAll(function(){}); parentId = chrome.contextMenus.create({"title": title, "contexts":["selection"], "onclick": function() { genericOnClick(request.selectedText); }}); loadingId = chrome.contextMenus.create({'title': 'Loading... try again.', 'parentId': parentId, 'contexts':['selection'], 'onclick': function() { alert("TPB haven't told me what they have yet. Try giving it another click.... NOW!"); }}); break; default: // helps debug when request directive doesn't match alert("Unmatched request of '" + request + "' from script to background.js from " + sender); } } ); debugger; chrome.tabs.onUpdated.addListener(function(tab) { chrome.tabs.executeScript(tab.id, { // defaults to the current tab file: 'contentscript_imdb.js', // script to inject into page and run in sandbox allFrames: false // When true, this injects script into iframes in the page and doesn't work before 4.0.266.0. We actually don't want this here. // url: [{hostSuffix: 'google.com'}, // {hostSuffix: 'google.com.au'}]} }); }); chrome.tabs.onCreated.addListener(function(tab) { chrome.tabs.executeScript(tab.id, { file: 'contentscript_imdb.js', allFrames: false }); }); // // IMPORTANT!!! // // THIS IS HOW WE CAN PROGRAMMATICALLY ADD CONTENT SCRIPTS TO PAGES // // WILL NEED TO DO THIS FOR IMDB ETC // // add a listener for every site. This will send the select script back to the context menu // chrome.tabs.onUpdated.addListener(function(tab) { // // if (tab.url.indexOf("chrome-devtools://") == -1) { // chrome.tabs.executeScript(tab.id, { // defaults to the current tab // file: 'jquery-1.9.1.min.js', // script to inject into page and run in sandbox // allFrames: false // When true, this injects script into iframes in the page and doesn't work before 4.0.266.0. We actually don't want this here. // }); // chrome.tabs.executeScript(tab.id, { // defaults to the current tab // file: 'contentscript.js', // script to inject into page and run in sandbox // allFrames: false // When true, this injects script into iframes in the page and doesn't work before 4.0.266.0. We actually don't want this here. // }); // // } // }); // // // add a listener for IMDB. This will add jQuery and set up the DDL // // chrome.tabs.onUpdated.addListener(function(tab) { // // // put jquery on the IMDB page // // chrome.tabs.executeScript(tab.id, { // defaults to the current tab // // file: 'contentscript_imdb.js', // script to inject into page and run in sandbox // // allFrames: false // When true, this injects script into iframes in the page and doesn't work before 4.0.266.0. We actually don't want this here. // // }); // // }, { // // url: [{hostContains: 'imdb.com'}, // // {hostContains: 'imdb.com.au'}] // // });
956c399e28a66ab4e91b2c8703a777a3c83e8583
[ "JavaScript" ]
3
JavaScript
EvanPalmer/TpbContextSearch
12b8743fe8fcb1a03f6a93e6ef983c52b0e726d6
54f0327771927d754eec708f72d5e1e29027492c
refs/heads/master
<file_sep>package Window; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintWriter; import java.util.ArrayList; public class History { private PrintWriter outputStream = null; private boolean rep = false; private String name,report; private int numOfOperation,numOfData; private boolean[] valid = new boolean[8]; private ArrayList<Edition> editionList = new ArrayList<Edition>(); private Law l; private boolean[] done = new boolean[8]; private String[] comments = new String[8]; public History(){ for(int i = 0 ; i < 8 ; i++){ comments[i] = "NONE"; } } public String getName(){ return name; } public int getNumOfOperation(){ return numOfOperation; } public int getNumOfData(){ return numOfData; } public void setName(String name){ this.name = name; } public void setNumOfOperation(int numOfOperation){ this.numOfOperation = numOfOperation; } public void setNumOfData(int numOfData){ this.numOfData = numOfData; } public boolean check(){ for(int i=0;i<8;i++){ if(done[i] == false){ return false; } } return true; } public boolean getValid(int position){ return valid[position]; } public void setValid(int position, boolean value){ this.valid[position] = value; } public boolean initEdition(String line){ Edition e = new Edition(); String[] words; words = line.split(";"); try{ Integer.parseInt(words[0]); }catch(NumberFormatException e1){ return false; } int temp = Integer.parseInt(words[0]); e.setId(temp); String [] words2 = words[1].split("/"); try{ Integer.parseInt(words2[0]); }catch(NumberFormatException e1){ return false; } try{ Integer.parseInt(words2[1]); }catch(NumberFormatException e1){ return false; } try{ Integer.parseInt(words2[2]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words2[0]); int temp1 = Integer.parseInt(words2[1]); int temp2 = Integer.parseInt(words2[2]); e.setDate(temp2,temp1,temp); try{ Integer.parseInt(words[2]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words[2]); e.setOpAdded(temp); try{ Integer.parseInt(words[3]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words[3]); e.setOpDeleted(temp); try{ Integer.parseInt(words[4]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words[4]); e.setOpUpdated(temp); try{ Integer.parseInt(words[5]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words[5]); e.setDataAdded(temp); try{ Integer.parseInt(words[6]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words[6]); e.setDataDeleted(temp); try{ Integer.parseInt(words[7]); }catch(NumberFormatException e1){ return false; } temp = Integer.parseInt(words[7]); e.setDataUpdated(temp); editionList.add(e); return true; } public String getReport(){ return report; } public void setReport(String report){ this.report = report; rep = true; } public void setComment(String com, int pos){ comments[pos] = com; } public String getComment(int pos){ return comments[pos]; } public void initLaw(int num){ if(num == 9){ if(check() == false){ reportError re = new reportError(); re.setVisible(true); return; } else{ if(rep == true){ alreadyReport ar = new alreadyReport(this); ar.setVisible(true); return; } report rep = new report(this); rep.setVisible(true); return; } } if(done[num - 1] == true){ if(valid[num - 1] == true){ alreadyEvaluated v = new alreadyEvaluated("valid", this, num); v.setVisible(true); return; } else{ alreadyEvaluated v = new alreadyEvaluated("invalid", this, num); v.setVisible(true); return; } } if(num == 7){ if(done[1] == false || done[5] == false){ seventhLawError el = new seventhLawError(); el.setVisible(true); return; } else{ if(valid[1] == true && valid[5] == true){ valid[6] = true; l = new LawSeven(); l.setTwoAndSix(true); l.valueLaw(this); done[6] = true; return; } else{ valid[6] = false; l = new LawSeven(); l.setTwoAndSix(false); l.valueLaw(this); done[6] = true; return; } } } if(num == 1){ l = new LawOne(); l.valueLaw(this); } else if(num == 2){ l = new LawTwo(); l.valueLaw(this); } else if(num == 3){ l = new LawThree(); l.valueLaw(this); } else if(num == 4){ l = new LawFour(); l.valueLaw(this); } else if(num == 5){ l = new LawFive(); l.valueLaw(this); } else if(num == 6){ l = new LawSix(); l.valueLaw(this); } else if(num == 8){ l = new LawEight(); l.valueLaw(this); } done[num - 1] = true; } public void undone(int pos){ done[pos - 1] = false; comments[pos - 1] = "NONE"; } public int getListSize(){ return(editionList.size()); } public Edition getEdition(int pos){ return(editionList.get(pos)); } public void saveReport(String r){ String n = name + " - Report.txt"; try { outputStream = new PrintWriter(new FileOutputStream(n)); } catch(FileNotFoundException e) { System.out.printf("Problem opening files!!!\n"); System.exit(0); } outputStream.println(r); outputStream.close(); } } <file_sep>package Window; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.border.EmptyBorder; import javax.swing.JTextArea; import javax.swing.JFormattedTextField; import java.awt.Color; import java.awt.SystemColor; import javax.swing.UIManager; import javax.swing.JTextPane; import java.awt.Font; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class seventhLaw extends JFrame { public seventhLaw(){} public seventhLaw(History h) { setTitle("Seventh Law"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 815, 411); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel txtrLawSevenIs = new JLabel("Law seven is valid, because law two and law six were also valid."); txtrLawSevenIs.setFont(new Font("Times New Roman", Font.BOLD, 20)); txtrLawSevenIs.setBackground(UIManager.getColor("Button.background")); txtrLawSevenIs.setBounds(126, 97, 564, 94); contentPane.add(txtrLawSevenIs); JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { dispose(); }}); btnOk.setBounds(171, 306, 120, 31); contentPane.add(btnOk); JButton btnComment = new JButton("Comments"); btnComment.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { comment c = new comment(h, 6); c.setVisible(true); }}); btnComment.setBounds(445, 306, 120, 31); contentPane.add(btnComment); } } <file_sep>package Window; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.lang.model.element.Element; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import javax.swing.text.Document; import javax.swing.JTextPane; import javax.swing.UIManager; import java.awt.Font; import javax.swing.JTextField; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; public class viewComments extends JFrame { public viewComments(){} public viewComments(History h) { setTitle("List of Comments"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 807, 412); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); String temp = ""; JTextArea textField = new JTextArea(); for (int i = 0 ; i < 8 ; i++){ if(h.getValid(i) == false){ temp = temp + "VALUE OF LAW " + (i + 1) + ": INVALID - COMMENT OF LAW " + (i + 1) + ": " + h.getComment(i) + "\r\n"; } else{ temp = temp + "VALUE OF LAW " + (i + 1) + ": VALID - COMMENT OF LAW " + (i + 1) + ": " + h.getComment(i) + "\r\n"; } } textField.setText(temp); textField.setBounds(10, 41, 754, 235); contentPane.add(textField); textField.setColumns(10); } public viewComments(History h, int num) { setTitle("Comment of LAW " + (num + 1)); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 807, 412); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JTextArea textField = new JTextArea(); textField.setText("COMMENT OF LAW " + (num + 1) + ": " + h.getComment(num)); textField.setBounds(10, 41, 754, 235); contentPane.add(textField); textField.setColumns(10); } } <file_sep>package Window; import java.awt.BorderLayout; import java.awt.FlowLayout; import java.awt.GridLayout; import javax.swing.ImageIcon; import javax.swing.JCheckBox; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JButton; import java.awt.event.ActionListener; import java.awt.event.ActionEvent; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.plot.PlotOrientation; import org.jfree.data.category.CategoryDataset; import org.jfree.data.category.DefaultCategoryDataset; public class firstLaw extends JFrame { private JCheckBox btnValid, btnNotValid; public firstLaw(int [] numOfOperation, int [] numOfData, int [] counter, int min, int max, History h) { setTitle("First Law"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setLayout(new BorderLayout()); //Charts JPanel charts = new JPanel(); charts.setLayout(new GridLayout(1, 3)); //Buttons JPanel buttons = new JPanel(); buttons.setLayout(new FlowLayout()); //create charts JFreeChart barChart1 = ChartFactory.createBarChart("Operation Changes", "Version ID", "Number of Changes", createDataset1(numOfOperation),PlotOrientation.VERTICAL, false, true, false); JFreeChart barChart2 = ChartFactory.createBarChart("Data Structure Changes", "Version ID", "Number of Changes", createDataset1(numOfData),PlotOrientation.VERTICAL, false, true, false); JFreeChart barChart3 = ChartFactory.createBarChart("Versions per Year", "Year", "Number of Versions", createDataset(counter, max, min),PlotOrientation.VERTICAL, false, true, false); ChartPanel chartPanel = new ChartPanel(barChart1); ChartPanel chartPanel2 = new ChartPanel(barChart2); ChartPanel chartPanel3 = new ChartPanel(barChart3); chartPanel.setPreferredSize(new java.awt.Dimension(350, 350)); chartPanel2.setPreferredSize(new java.awt.Dimension(350, 350)); chartPanel3.setPreferredSize(new java.awt.Dimension(350, 350)); // add to contentPane charts.add(chartPanel); charts.add(chartPanel2); charts.add(chartPanel3); add(charts, BorderLayout.CENTER); JButton btnComment = new JButton("Comments"); btnComment.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { comment c = new comment(h, 0); c.setVisible(true); }}); btnNotValid = new JCheckBox("Not Valid"); btnNotValid.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { h.setValid(0, false); btnValid.setSelected(false); }}); btnValid = new JCheckBox("Valid"); btnValid.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { h.setValid(0, true); btnNotValid.setSelected(false); }}); buttons.add(btnValid); buttons.add(btnNotValid); buttons.add(btnComment); add(buttons, BorderLayout.SOUTH); } private CategoryDataset createDataset1(int [] temp) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); for(int i = 0 ; i < temp.length ; i++){ dataset.addValue(temp[i], "1", String.valueOf(i + 1)); } return dataset; } private CategoryDataset createDataset(int [] temp, int max, int min) { DefaultCategoryDataset dataset = new DefaultCategoryDataset(); int x = min; for(int i = 0 ; i < temp.length ; i++){ dataset.addValue(temp[i], "1", String.valueOf(x)); x++; } return dataset; } }<file_sep>package Window; import java.awt.BorderLayout; import java.awt.EventQueue; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextArea; import javax.swing.border.EmptyBorder; import javax.swing.JTextPane; import javax.swing.JTextField; import java.awt.SystemColor; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; public class comment extends JFrame { public comment(){} public comment(History h, int pos) { setTitle("Comment"); setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE); setBounds(100, 100, 814, 443); JPanel contentPane = new JPanel(); contentPane.setBorder(new EmptyBorder(5, 5, 5, 5)); setContentPane(contentPane); contentPane.setLayout(null); JLabel txtpnWriteAComment = new JLabel("Write a comment..."); txtpnWriteAComment.setFont(new Font("Tahoma", Font.PLAIN, 13)); txtpnWriteAComment.setBackground(SystemColor.menu); txtpnWriteAComment.setBounds(74, 46, 148, 26); contentPane.add(txtpnWriteAComment); JTextArea textField = new JTextArea(); textField.setColumns(10); textField.setBounds(75, 83, 657, 235); contentPane.add(textField); JButton btnCancel = new JButton("Cancel"); btnCancel.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { dispose(); }}); btnCancel.setBounds(208, 368, 120, 31); contentPane.add(btnCancel); JButton btnOk = new JButton("OK"); btnOk.addActionListener(new ActionListener(){public void actionPerformed(ActionEvent e) { if(!textField.getText().equals("")){ String com = textField.getText(); h.setComment(com, pos); dispose(); } }}); btnOk.setBounds(75, 368, 120, 31); contentPane.add(btnOk); } }<file_sep>package Window; public class LawSeven extends Law{ private boolean choice; public void valueLaw(History h){ if(choice == true){ seventhLaw l = new seventhLaw(h); l.setVisible(true); } else{ seventhLawNotValid l = new seventhLawNotValid(h); l.setVisible(true); } } public void setTwoAndSix(boolean choice){ this.choice = choice; } }
b117225b72ecd8744a49ff1e716b6c9b3fde53f6
[ "Java" ]
6
Java
athanasiouan/Tool-implementation-for-monitoring-software-evolution
bd8d3af824dd7eaa87e2e11d3e26efadde217188
d675ae66517ccc45eb277708bade787e5c9ec917
refs/heads/master
<file_sep>js识别canvas画布上绘制的图形 ================================== ## 多边形识别 * 选取特征点, * 根据数学边角关系计算 * 匹配和绘制。 特点: * 准确度高,支持判断canvas画布上绘制出来的图形是否是三角形,矩形,横线,竖线,对勾等。 * 对复杂图形的匹配,计算上很麻烦。 ## 复杂图形识别 * 图形进行学习, * 获得学习到的模版。 * 进行图形相似度匹配, * 绘制。 特点: * 支持图形学习,实现简单。 * 样例图形间相似度高时,匹配不准确。 ## $1 Unistroke Recognize使用方法: ```markdown <script> //将绘制心形的所有的点points传入AddGesture方法中。 //统一图形可以支持传入多份点的数据。 Recognizer.AddGesture('心形',points) //识别图形 //可以得到图形检测name和score的返回信息。 var mes = Recognizer.Recognize(points,true) </script> ``` ## 实践: * 根据给出的图形,涂鸦图形的闯关益智小游戏。 * 微信好友之间,涂鸦相似度评比等。 <file_sep> (function(){ var canvasWidth = 300; var canvasHeight = 300; var ctx; var canvasOffset = $("#back").offset(); console.log(canvasOffset.top) console.log(canvasOffset.left) var game = { //游戏状态绘制中 drawing: false, //初始坐标 origin:{} } function Point(x, y) // constructor { this.X = x; this.Y = y; } function create() { var canvas = document.getElementById("back"); if (canvas.getContext) { ctx = canvas.getContext("2d"); } } create() function getAngle(angle){ if(angle>Math.PI/2){ return Math.PI/2-angle }else{ return angle } } function vector(x, y){ return { X:x, Y:y, } } function delta(a, b){ return vector(a.X - b.X, a.Y - b.Y) } function angle(d){ return Math.atan((1.0*d.Y)/d.X) } function angle_between(a, b){ return Math.acos((a.X*b.X + a.Y*b.Y)/(len(a)*len(b))) } function unit(c){ var l=len(c) return vector(c.X/len(c), c.Y/len(c)) } function len(v){ return Math.sqrt(v.X*v.X + v.Y*v.Y) } function scale(c, f){ return vector(c.X*f, c.Y*f) } function add(a, b){ return vector(a.X+b.X, a.Y+b.Y) } function rotate(v, a){ return vector( v.X*Math.cos(a) - v.Y*Math.sin(a), v.X*Math.sin(a) + v.Y*Math.cos(a)) } function average(l){ var x=0 var y=0 for (var i=0; i<l.length; i++){x+=l[i].X; y+=l[i].Y} return vector(x/l.length, y/l.length) } function getPos(e){ var curX; if(e.pageX){ curX = e.pageX, curY = e.pageY; }else{ curX = e.changedTouches[0].pageX, curY = e.changedTouches[0].pageY; } return new Point ( curX-canvasOffset.left, curY-canvasOffset.top ) } //绘制点集 var line; function getCorner(line){ var n=0 var t=0 var lastCorner=line[0] var corners= [line[0]] for (var i=1; i<line.length-2; i++){ var pt=line[i+1] var d=delta(lastCorner, line[i-1]) if (len(d)>20 && n>2){ ac=delta(line[i-1], pt) if (Math.abs(angle_between(ac, d)) > Math.PI/4){ pt.index=i corners.push(pt) lastCorner=pt n=0 t=0 } } n++ } return corners; } function calculate(corners){ console.log(corners) if (len(delta(line[line.length-1], line[0]))<45){ corners.push(line[0]) ctx.fillStyle='rgba(0, 0, 255, 0.3)' if (corners.length==5){ $(".info2").text('矩形') var p1=corners[0] var p2=corners[1] var p3=corners[2] var p4=corners[3] var p1p2=delta(p1, p2) var p2p3=delta(p2, p3) var p3p4=delta(p3, p4) var p4p1=delta(p4, p1) if ((Math.abs(angle_between(p1p2, p2p3)-Math.PI/2))<Math.PI/6 && (Math.abs(angle_between(p2p3, p3p4)-Math.PI/2))<Math.PI/6 && (Math.abs(angle_between(p3p4, p4p1)-Math.PI/2))<Math.PI/6 && (Math.abs(angle_between(p4p1, p1p2)-Math.PI/2))<Math.PI/6){ ctx.fillStyle='red' var p1p3=delta(p1, p3) var p2p4=delta(p2, p4) var diag=(len(p1p3)+len(p2p4))/4.0 var tocenter1=scale(unit(p1p3), -diag) var tocenter2=scale(unit(p2p4), -diag) var center=average([p1, p2, p3, p4]) var angle=angle_between(p1p3, p2p4) corners=[add(center, tocenter1), add(center, tocenter2), add(center, scale(tocenter1, -1)), add(center, scale(tocenter2, -1)), add(center, tocenter1)] } } if (corners.length==4){ //check for 三角形 $(".info2").text('三角形') var p1=corners[0] var p2=corners[1] var p3=corners[2] var p1p2=delta(p1, p2) var p2p3=delta(p2, p3) var p3p1=delta(p3, p1) var angle1 = getAngle(Math.abs(angle_between(p1p2, p2p3))); var angle2 = getAngle(Math.abs(angle_between(p2p3, p3p1))); var angle3 = getAngle(Math.abs(angle_between(p3p1, p1p2))); if (angle1+angle2 +angle3 -Math.PI<Math.PI/6){ ctx.fillStyle='yellow' } } ctx.beginPath() ctx.moveTo(corners[0].X, corners[0].Y) for (var i=1; i<corners.length; i++){ ctx.lineTo(corners[i].X, corners[i].Y) } ctx.fill() }else{ corners.push(line[line.length-1]) } if(corners.length==3){ $(".info2").text('对勾') var p1=corners[0] var p2=corners[1] var p3=corners[2] if(p2.Y-p1.Y>20 && p2.Y-p3.Y>20){ ctx.strokeStyle='green' }else if(p2.Y-p1.Y<-20 && p2.Y-p3.Y<-20){ ctx.strokeStyle='orange' (".info2").text('尖对勾') }else{ ctx.strokeStyle='rgba(0, 0, 255, 0.5)' } }else if(corners.length==2){ var p1=corners[0] var p2=corners[1] var p3 = { X:p1.X+40, Y:p1.Y } var p4 = { X:p2.X, X:p2.X+40 } // Math.abs(angle_between(p1p2, )) //console.log(p1p2) var p1p2=delta(p1,p2) var p1p3=delta(p1,p3) var p2p4=delta(p2,p4) if(Math.abs(angle_between(p1p2,p1p3))<Math.PI/6){ ctx.strokeStyle='pink' $(".info2").text('横') }else if(Math.abs(angle_between(p1p2,p2p4))<Math.PI/6){ //竖 $(".info2").text('竖') ctx.strokeStyle='purple' } }else{ ctx.strokeStyle='rgba(0, 0, 255, 0.5)' } //绘制点 ctx.beginPath() ctx.moveTo(corners[0].X, corners[0].Y) for (var i=1; i<corners.length; i++){ ctx.lineTo(corners[i].X, corners[i].Y) } ctx.stroke() ctx.fillStyle='rgba(255, 0, 0, 0.5)' //绘制几何图形 for (var i=0; i<corners.length; i++){ ctx.beginPath() ctx.arc(corners[i].X, corners[i].Y, 4, 0, 2*Math.PI, false) ctx.fill() } ctx.strokeStyle="rgba(0,0,0,0.2)" } function drawStart(e){ ctx.clearRect(0,0,canvasWidth,canvasHeight); $(".info2").text('') var pos = getPos(e); var curX = pos.X, curY = pos.Y; ctx.lineWidth = '20px'; ctx.strokeStyle = 'rgba(0,0,0,0.2)' game.origin.x = pos.x; game.origin.y = pos.y; ctx.beginPath(); game.drawing = true; line = [pos] } function drawing(e){ var pos = getPos(e); var curX = pos.X, curY = pos.Y; if(game.drawing){ ctx.strokeStyle="rgba(0,0,0,0.2)" ctx.moveTo(game.origin.x,game.origin.y); ctx.lineTo(curX,curY); ctx.stroke(); game.origin.x = curX; game.origin.y = curY; line.push(pos); } } function drawEnd(e){ var pos = getPos(e); var curX = pos.X, curY = pos.Y; ctx.closePath(); line.push(pos); calculate(getCorner(line)); //ctx.clearRect(0,0,canvasWidth,canvasHeight); game.drawing = false; } $("#back").on('mousedown',function(e){ drawStart(e) }); $("#back").on('mousemove',function(e){ drawing(e) }); $("#back").on('mouseup',function(e){ drawEnd(e); }); $("#back").on("touchstart", function(e) { e.preventDefault(); drawStart(e) }); $("#back").on("touchmove", function(e) { e.preventDefault(); drawing(e) }); $("#back").on("touchend", function(e) { e.preventDefault(); drawEnd(e); }); })()<file_sep> (function(){ var canvasWidth = 300; var canvasHeight = 300; var ctx; var canvasOffset = $("canvas").offset(); var game = { //游戏状态绘制中 drawing: false, //初始坐标 origin:{} } function create() { var canvas = document.getElementById("front"); if (canvas.getContext) { ctx = canvas.getContext("2d"); } } create() function vector(x, y){ return { X:x, Y:y, } } function delta(a, b){ return vector(a.X - b.X, a.Y - b.Y) } function angle_between(a, b){ return Math.acos((a.X*b.X + a.Y*b.Y)/(len(a)*len(b))) } function len(v){ return Math.sqrt(v.X*v.X + v.Y*v.Y) } function getPos(e){ var curX; if(e.pageX){ curX = e.pageX, curY = e.pageY; }else{ curX = e.changedTouches[0].pageX, curY = e.changedTouches[0].pageY; } return new Point ( curX-canvasOffset.left, curY-canvasOffset.top ) } var line; var Recognizer = new DollarRecognizer(); function drawStart(e){ var pos = getPos(e); var curX = pos.X, curY = pos.Y; ctx.lineWidth = '20px'; ctx.strokeStyle = 'rgba(0,0,0,0.2)' game.origin.x = pos.x; game.origin.y = pos.y; ctx.beginPath(); game.drawing = true; line = [pos] } function drawing(e){ var pos = getPos(e); var curX = pos.X, curY = pos.Y; if(game.drawing){ ctx.strokeStyle="rgba(0,0,0,0.2)" ctx.moveTo(game.origin.x,game.origin.y); ctx.lineTo(curX,curY); ctx.stroke(); game.origin.x = curX; game.origin.y = curY; line.push(pos); } } //输出学习到的图形信息 function getNew(){ var resObj = Recognizer.Unistrokes; var points = resObj[16].Points; var str = "" for(var i=0;i<points.length;i++){ console.log(points[i].X) str+= 'new Point('+ Math.floor(points[i].X)+','+Math.floor(points[i].Y)+'),'; } console.log(str) } function drawEnd(e){ var pos = getPos(e); var curX = pos.X, curY = pos.Y; ctx.closePath(); line.push(pos); var result = Recognizer.Recognize(line,true) $(".info").text(result.Name); $(".score").text(result.Score) //alert("这是个"+result.Name+"score:"+result.Score); //手动增加一个可识别图形 //Recognizer.AddGesture('心',line) //getNew(); //fill(); game.drawing = false; ctx.clearRect(0,0,canvasWidth,canvasHeight); } function fill(){ ctx.fillStyle='rgba(255, 0, 0, 0.5)'; //绘制几何图形 ctx.beginPath() ctx.moveTo(line[0].X, line[0].Y) for (var i=1; i<line.length; i++){ ctx.lineTo(line[i].X, line[i].Y) } ctx.lineTo(line[0].X, line[0].Y) ctx.fill() ctx.fillStyle='rgba(255, 255, 0, 0.5)' //绘制几何图形边 for (var i=0; i<line.length; i++){ ctx.beginPath() ctx.arc(line[i].X, line[i].Y, 4, 0, 2*Math.PI, false) ctx.fill() } ctx.strokeStyle="rgba(0,0,0,0.2)" } $("#front").on('mousedown',function(e){ drawStart(e) }); $("#front").on('mousemove',function(e){ drawing(e) }); $("#front").on('mouseup',function(e){ drawEnd(e); }); $("#front").on("touchstart", function(e) { e.preventDefault(); drawStart(e) }); $("#front").on("touchmove", function(e) { e.preventDefault(); drawing(e) }); $("#front").on("touchend", function(e) { e.preventDefault(); drawEnd(e); }); })()
f3903535e6dc936516380a715e84c71ca6294ba8
[ "Markdown", "JavaScript" ]
3
Markdown
cnluderson/imageReconizer
f1dfb0b8276144436fc49579dbaedbb41918f937
dab539f36a1f2df5021ecedde23dc713f8587db5
refs/heads/master
<file_sep>Identity кодера - строка, которая должна быть одинаковой у кодеров, работающих с одними и теми же данными (совместимые кодеры должны иметь одинаковую identity) Предлагается брать за identity строковое представление кодируемого типа в Котлине Например: - Для кодера для интов identity будет "Int" - Для кодера даблов "Double" - Для кодера списка строк "List<String>" - Для кодера списка списков строк "List<List<String>>" Для кодера композитного объекта предлагается делать identity вида "Object<A, B, C, D>" Для пользовательского кодера пользователь сам определяет его identity как хочет<file_sep> Примитивные типы (инты, даблы и т.д.) кодируются средствами kotlinx-io Для строк первые 4 байта занимает длина строки (кодируется так же как и инт), затем идет сама строка в UTF-8 Для списков первые 4 байта занимает длина списка, затем элементы списка кодируются один за другим без разделителей Пары элементов кодируются без разделителей Map кодируется как список пар Композитный объект кодируется без разделителей и без длины, просто как конкатенация закодированных свойств Пользовательский объект кодируется кастомным кодером как длина получившегося байт-массива (4 байта) и затем сам байт-массив<file_sep>import org.jetbrains.dokka.gradle.DokkaPlugin import org.jetbrains.dokka.gradle.DokkaTask import java.net.URL plugins { id("org.jetbrains.dokka") kotlin("multiplatform") apply false } allprojects { group = "space.kscience" version = "0.0.1" repositories { jcenter() mavenCentral() mavenLocal() } } subprojects { val p = this@subprojects if (p.name != "demo") apply<DokkaPlugin>() tasks.withType<DokkaTask> { dokkaSourceSets.configureEach { val readmeFile = File(this@subprojects.projectDir, "./README.md") if (readmeFile.exists()) includes.setFrom(includes + readmeFile.absolutePath) sourceLink { localDirectory.set(file("${p.name}/src/main/kotlin")) remoteUrl.set( URL("https://github.com/mipt-npm/${rootProject.name}/tree/master/${p.name}/src/main/kotlin/") ) } } } } <file_sep>rootProject.name = "communicator" pluginManagement { val dokkaVersion: String by settings val kotlinVersion: String by settings plugins { id("org.jetbrains.dokka") version dokkaVersion kotlin("multiplatform") version kotlinVersion } } include( ":communicator-api", ":communicator-zmq", ":demo" ) <file_sep>dokkaVersion=1.4.30 jeromqVersion=0.5.2 junitVersion=5.7.1 kotlin.code.style=official kotlin.mpp.enableGranularSourceSetsMetadata=true kotlin.mpp.stability.nowarn=true kotlin.native.enableDependencyPropagation=false kotlinLoggingVersion=2.0.4 kotlinVersion=1.4.32 ktorVersion=1.5.1 org.gradle.jvmargs=-XX:MaxMetaspaceSize=1G org.gradle.parallel=true slf4jVersion=1.7.30 statelyIsoVersion=1.1.6-a1
96d5c90c70972b311e7a3d79ffd6763495db303f
[ "Markdown", "Kotlin", "INI" ]
5
Markdown
cybernetics/communicator
2753edbf46a44d7e9fb5c479f3b11f4596f2246b
3a60d5dc58eb24fc8e76dd8e8234cd46fae3f5ac
refs/heads/master
<repo_name>PosAula/PHP<file_sep>/acao_grupo.php <?php session_start(); include_once 'conexao.php'; $acao = $_GET['acao']; $id = filter_input(INPUT_GET, 'id_grupo', FILTER_SANITIZE_NUMBER_INT); /*$id = $_GET['id_grupo']; echo $acao; echo $id;*/ switch ($acao) { case 'sair': $sql_sair_grupo = "DELETE FROM `usuario_grupo` WHERE `usuario_grupo`.`id_usuario_grupo` = '$id'"; $query_sair_grupo = $conn->query($sql_sair_grupo); if ($query_sair_grupo->rowCount() > 0) { header('Location: grupos.php'); //echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/grupos.php'>"; } break; case 'entrar': $id_usuario = $_SESSION['id_usuario']; $sql_entar_grupo = "insert into usuario_grupo (id_grupo , id_usuario) values ('$id' , '$id_usuario')"; $query_entar_grupo = $conn->query($sql_entar_grupo); if ($query_entar_grupo->rowCount() > 0) { header('Location: grupos.php'); //echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/grupos.php'>"; } break; default: break; }<file_sep>/index.php <?php session_start(); include_once 'header.html'; include_once 'menu.html'; ?> <h1>Logado</h1> <?php if(!isset($_SESSION['id_usuario'])){ echo 'Não autenticado'; } include_once 'mecanismo_listar.php'; include_once 'footer.html'; ?><file_sep>/cadastro.php <?php include_once 'header.html'; ?> <form method="post" action=""> Nome: <input type="text" name="nome"><br> Login: <input type="text" name="login"><br> Senha: <input type="<PASSWORD>" name="senha"><br> Sexo: <select name="sexo"> <option value="m">Masculino</option> <option value="f">Feminino</option> </select><br> Email: <input type="email" name="email"><br> <input type="submit" value="Cadastrar" name="btn-cadastrar"> </form><a href="login.php">Fazer login</a> <?php include_once 'conexao.php'; if (isset($_POST['btn-cadastrar'])) { $nome = filter_input(INPUT_POST, 'nome', FILTER_SANITIZE_SPECIAL_CHARS); $login = filter_input(INPUT_POST, 'login', FILTER_SANITIZE_SPECIAL_CHARS); $senha = filter_input(INPUT_POST, 'senha', FILTER_SANITIZE_SPECIAL_CHARS); $sexo = filter_input(INPUT_POST, 'sexo', FILTER_SANITIZE_SPECIAL_CHARS); $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); //var_dump($_POST); if ($sexo === 'm') { $url_imagem = 'img/user-m.png'; } else { $url_imagem = 'img/user-f.png'; } $sql_cad = "insert into usuarios (login , senha , nome , url_imagem, email) values ('$login' , '$senha' , '$nome' , '$url_imagem' , '$email')"; $query_cad = $conn->query($sql_cad); if ($query_cad->rowCount() > 0) { echo " <META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/login.php'> <script type=\"text/javascript\"> alert('Cadastrado com sucesso !'); </script> "; } } include_once 'footer.html'; ?> <file_sep>/mecanismo_listar.php <?php include_once 'conexao.php'; $id_usuario = $_SESSION['id_usuario']; $sql_dentro = "SELECT usuario_grupo.id_grupo , nome_grupo FROM usuario_grupo INNER JOIN grupos ON usuario_grupo.id_grupo = grupos.id_grupo WHERE usuario_grupo.id_usuario = '$id_usuario'"; $query_dentro = $conn->query($sql_dentro); $grupos_dentro = $query_dentro->fetchAll(PDO::FETCH_ASSOC); $a = 0; if ($query_dentro->rowCount() > 0) { while ($a < $query_dentro->rowCount()) { $id_dentro = $grupos_dentro[$a]['id_grupo']; $nome_grupo = $grupos_dentro[$a]['nome_grupo']; echo "<h1>Comentarios sobre $nome_grupo</h1>"; echo '<div>'; $sql = "select * from comentarios where id_grupo = $id_dentro order by id_comentario desc"; $query = $conn->query($sql); $comentarios = $query->fetchAll(PDO::FETCH_ASSOC); $i = 0; while ($i < $query->rowCount()) { // echo "<h2>Comentario</h2> <br>"; $imagem_c = $comentarios[$i]['url_imagem']; echo "<img src='$imagem_c' alt='' id='perfil'/>"; echo $comentarios[$i]['nome_usuario'] . ' comentou:'; //echo'<br>'; //echo $comentarios[$i]['url_imagem']; echo'<br><br>'; echo $comentarios[$i]['comentario']; echo'<br><br>'; echo "Na data: " . $comentarios[$i]['data']; $id = $comentarios[$i]['id_comentario']; echo'<br>'; //Começou as respostas $sql_resposta = "select * from respostas where id_comentario = '$id' order by id_resposta asc"; $query_resposta = $conn->query($sql_resposta); $respostas = $query_resposta->fetchAll(PDO::FETCH_ASSOC); $j = 0; while ($j < $query_resposta->rowCount()) { $imagem_r = $respostas[$j]['url_imagem']; echo "<div id='respostas'>"; echo "<h3>Respostas</h3>"; echo "<img src='$imagem_r' alt='' id='perfil'/>"; echo $respostas[$j]['nome_usuario'] . ' respondeu o comentário de ' . $comentarios[$i]['nome_usuario'] . ' com: '; //echo'<br>'; // echo $respostas[$j]['url_imagem']; echo'<br>'; echo $respostas[$j]['resposta']; echo'<br><br>'; echo 'Na data: ' . $respostas[$j]['data']; echo'<br>'; echo '<br>'; $j++; echo '</div>'; } //Acabou as respostas echo "<form method='post' action='responder.php'> Resposta: <input type='text' name='resposta' required> <input type='hidden' name='valor'"; echo " value='$id'> <input type='submit' value='Responder'> </form>"; echo '<hr><br>'; $i++; } echo '</div>'; //------------------ $a++; } } ?><file_sep>/criar_grupo.php <?php session_start(); include_once 'header.html'; include_once 'menu.html'; ?> <h3>Digite o nome do seu grupo</h3> <form method="post" action=""> <input type="text" name="nome_grupo" required><br> <h3>Descrição do grupo</h3> <textarea name="descricao_grupo" required></textarea><br> <input type="submit" value="Criar" name="btn-criar"> </form> <?php include_once 'conexao.php'; if (isset($_POST['btn-criar'])) { $nome_grupo = filter_input(INPUT_POST, 'nome_grupo', FILTER_SANITIZE_SPECIAL_CHARS); $descricao_grupo = filter_input(INPUT_POST, 'descricao_grupo', FILTER_SANITIZE_SPECIAL_CHARS); $id_usuario = $_SESSION['id_usuario']; $sql_criar = "insert into grupos (nome_grupo , desc_grupo , id_usuario) values ('$nome_grupo' , '$descricao_grupo' , '$id_usuario')"; $query_criar = $conn->query($sql_criar); if($query_criar->rowCount() > 0){ header('Location: todos_grupos.php'); } } ?><file_sep>/comentar_grupos.php <?php session_start(); include_once 'header.html'; include_once 'menu.html'; include_once 'conexao.php'; //$cod = $_GET['id_comentar']; $cod = filter_input(INPUT_GET, 'id_comentar', FILTER_SANITIZE_NUMBER_INT); $sql_comentar = "select * from grupos where id_grupo='$cod'"; $query_comentar = $conn->query($sql_comentar); $grupo_comentar = $query_comentar->fetchAll(PDO::FETCH_ASSOC); /* switch ($cod) { case '1': header('Location: comentar_matematica.php'); break; case '2': header('Location: comentar_portugues.php'); break; case '3': header('Location: comentar_biologia.php'); break; default: break; } */ ?> <form method='post' action=''> Faça seu comentário sobre <?php echo $grupo_comentar[0]['nome_grupo']; ?>:<br><textarea name="comentario" required></textarea> <input type="hidden" name="cod_materia" value="<?php echo $cod; ?>"><br> <input type='submit' value='Comentar' name="btn-comentar"> </form> <?php //echo $cod; if (isset($_POST['btn-comentar'])) { $nome = $_SESSION['nome']; $url_imagem = $_SESSION['url_imagem']; $data = 'NOW()'; $comentario = filter_input(INPUT_POST, 'comentario', FILTER_SANITIZE_SPECIAL_CHARS); //$comentario = $_GET['comentario']; $id_grupo = $cod; $id_usuario = $_SESSION['id_usuario']; $sql = "insert into comentarios (nome_usuario , url_imagem , data , comentario , id_grupo, id_usuario) values ('$nome' , '$url_imagem' , $data , '$comentario' , '$id_grupo' , '$id_usuario')"; $query = $conn->query($sql); if ($query->rowCount() > 0) { header('Location: index.php'); //echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/index.php'>"; } } include_once 'footer.html'; ?> <file_sep>/todos_grupos.php <?php session_start(); include_once 'header.html'; include_once 'menu.html'; ?> <h2>Todos os grupos</h2> <?php //Todos os grupos include_once 'conexao.php'; //session_start(); //$sql2 = "SELECT nome_grupo FROM usuario_grupo INNER JOIN grupos ON usuario_grupo.id_grupo = grupos.id_grupo"; $sql_grupos = "SELECT * from grupos"; $query_grupos = $conn->query($sql_grupos); $todos_grupos = $query_grupos->fetchAll(PDO::FETCH_ASSOC); /* $sql_dentro = "SELECT usuario_grupo.id_grupo FROM usuario_grupo INNER JOIN grupos ON usuario_grupo.id_grupo = grupos.id_grupo WHERE usuario_grupo.id_usuario = '15';"; $query_dentro = $conn->query($sql_dentro); $grupos_dentro = $query_dentro->fetchAll(PDO::FETCH_ASSOC); var_dump($todos_grupos); echo'<hr>'; var_dump($grupos_dentro); echo'<hr>'; //in_array($grupos_dentro[0]['id_grupo'], $todos_grupos[0]['id_grupo']); var_dump(in_array($grupos_dentro[1], $todos_grupos)); $a=0; $b=0; while ($a < $query_grupos->rowCount()){ while ($b < $query_dentro->rowCount()) { $valor = $grupos_dentro[$b]; var_dump(in_array($valor, $todos_grupos)); $b++; } //$valor = $grupos_dentro[$a]['id_grupo']; //echo $valor; //echo in_array($valor, $todos_grupos); $b=0; $a++; }*/ $j = 0; while ($j < $query_grupos->rowCount()) { $id_entrar_grupo = $todos_grupos[$j]['id_grupo']; echo $todos_grupos[$j]['nome_grupo'] . ' ' . "<a href = 'acao_grupo.php?acao=entrar&id_grupo=$id_entrar_grupo'>Entrar</a>" . '<br>'; $j++; }?> <file_sep>/grupos.php <?php session_start(); include_once 'header.html'; include_once 'menu.html'; include_once 'conexao.php'; $id_usuario = $_SESSION['id_usuario']; $sql_grupo = "SELECT nome_grupo, id_usuario_grupo FROM usuario_grupo INNER JOIN grupos ON usuario_grupo.id_grupo = grupos.id_grupo WHERE usuario_grupo.id_usuario = '$id_usuario'"; $query_grupo = $conn->query($sql_grupo); $grupo = $query_grupo->fetchAll(PDO::FETCH_ASSOC); $sql_comentar = "SELECT * from usuario_grupo where id_usuario = '$id_usuario'"; $query_comentar = $conn->query($sql_comentar); $comentar = $query_comentar->fetchAll(PDO::FETCH_ASSOC); $i = 0; echo "<h2>Meus grupos</h2>"; while ($i < $query_grupo->rowCount()) { $id_sair_grupo = $grupo[$i]['id_usuario_grupo']; $id_comentar = $comentar[$i]['id_grupo']; ?> <?php echo $grupo[$i]['nome_grupo']; ?> <a href="comentar_grupos.php?id_comentar=<?php echo $id_comentar; ?>">Comentar</a> <a href="acao_grupo.php?acao=sair&id_grupo=<?php echo $id_sair_grupo;?>">Sair</a><br> </form> <?php //echo $grupo[$i]['nome_grupo'].' '."<a href = 'comentar_grupos.php?id_comentar=$id_comentar'>Comentar</a>" . ' ' . "<a href = 'sair_grupo.php?id_grupo=$id_sair_grupo'>Sair</a>" . '<br>'; $i++; } //Todos os grupos <file_sep>/login.php <?php include_once 'header.html'; ?> <form method="post" action=""> Login:<input type="text" name="login"><br> Senha:<input type="<PASSWORD>" name="senha"><br> <input type="submit" value="Entrar" name="btn-logar"> </form> <a href="cadastro.php">Cadastre-se</a> <a href="recuperar_senha.php">Recuperar senha</a> <?php include_once 'conexao.php'; if(isset($_POST['btn-logar'])){ $login = filter_input(INPUT_POST, 'login', FILTER_SANITIZE_SPECIAL_CHARS); $senha = filter_input(INPUT_POST, 'senha', FILTER_SANITIZE_SPECIAL_CHARS); //valida o usuario $sql_login = "select * from usuarios where login = '$login' && senha = '$senha' limit 1"; $query_login = $conn->query($sql_login); //$usuario = $query_login->fetchAll(PDO::FETCH_ASSOC); if($query_login->rowCount() > 0){ //Cria um sessao e armazena os dados do usuario session_start(); $usuario = $query_login->fetchAll(PDO::FETCH_ASSOC); $_SESSION['nome'] = $usuario[0]['nome']; $_SESSION['url_imagem'] = $usuario[0]['url_imagem']; $_SESSION['id_usuario'] = $usuario[0]['id_usuario']; $_SESSION['email'] = $usuario[0]['email']; header('Location: index.php'); }else{ header('Location: login.php'); } } include_once 'footer.html'; ?> <file_sep>/recuperar_senha.php <?php include_once 'header.html'; ?> <div> <h3>Digite seu email cadastrado no site</h3> <form action="" method="post"> Email: <input type="email" name="email"> <input type="submit" value="Enviar" name="btn-recuperar"><br> <a href="login.php">Fazer login</a> </form> </div> <?php include_once 'conexao.php'; if (isset($_POST['btn-recuperar'])) { $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL); $sql_rec = "select * from usuarios where email = '$email' limit 1"; $query_rec = $conn->query($sql_rec); if ($query_rec->rowCount() > 0) { //se for verdadeiro $recuperar = $query_rec->fetchAll(PDO::FETCH_ASSOC); //resgata a senha $senha = $recuperar[0]['senha']; $destinatario = $email; //envia o email $assunto = 'Recuperar senha !'; $corpo = "Sua senha é: $senha"; if (mail("$destinatario", $assunto, $corpo, 'From: <EMAIL>')) { echo "<script>alert('Sua senha foi enviada para $destinatario');</script>"; echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/login.php'>"; } else { echo 'Erro ao enviar email'; } } else { echo 'Esse email não está cadastrado'; } } include_once 'footer.html'; ?><file_sep>/perfil.php <?php session_start(); include_once 'header.html'; include_once 'menu.html'; include_once 'conexao.php'; ?> <center> <div id='info'> <img src='<?php echo $_SESSION['url_imagem']; ?>'><br> <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="arquivo"><br> <input type="submit" value="Enviar" name="btn-upload"> </form> <span>Nome: <?php echo $_SESSION['nome']; ?></span><br> <span>Email: <?php echo $_SESSION['email']; ?></span><br> <span>Cidade: Barueri</span> </div> </center> <?php if (isset($_POST['btn-upload'])) { $formatos = array("jpg", "jpeg", "png"); $extensao = pathinfo($_FILES['arquivo']['name'], PATHINFO_EXTENSION); if (in_array($extensao, $formatos)) { $pasta = 'img/'; $temporario = $_FILES['arquivo']['tmp_name']; $novo_nome = uniqid() . ".$extensao"; if (move_uploaded_file($temporario, $pasta . $novo_nome)) { $id_usuario = $_SESSION['id_usuario']; $nome_sql = $pasta . $novo_nome; $sql_img = "UPDATE usuarios SET url_imagem = '$nome_sql' WHERE id_usuario = '$id_usuario'"; $query_img = $conn->query($sql_img); if ($query_img->rowCount() > 0) { $_SESSION['url_imagem'] = $nome_sql; $sql_all1 = "UPDATE usuarios SET url_imagem = '$nome_sql' WHERE id_usuario = '$id_usuario'"; $sql_all = "UPDATE usuarios SET url_imagem = '$nome_sql' WHERE id_usuario = '$id_usuario'; UPDATE comentarios SET url_imagem = '$nome_sql' WHERE id_usuario = '$id_usuario'; UPDATE respostas SET url_imagem = '$nome_sql' WHERE id_usuario = '$id_usuario';"; $query_all = $conn->query($sql_all); echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/perfil.php'>"; } } else { echo 'Falha no upload'; } } else { echo 'Extensão inválida'; } } ?><file_sep>/responder.php <?php include_once 'conexao.php'; session_start();/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ //$id_comentario = $_POST['valor']; //$resposta = $_GET['resposta']; //echo $valor; $id_comentario = filter_input(INPUT_POST, 'valor', FILTER_SANITIZE_NUMBER_INT); $nome = $_SESSION['nome']; $url_imagem = $_SESSION['url_imagem']; $data = 'NOW()'; $resposta = filter_input(INPUT_POST, 'resposta', FILTER_SANITIZE_SPECIAL_CHARS); //$comentario = $_GET['resposta']; $id_usuario = $_SESSION['id_usuario']; $sql = "insert into respostas (nome_usuario , url_imagem , data , resposta , id_comentario , id_usuario) values ('$nome' , '$url_imagem' , $data , '$resposta' , '$id_comentario' , '$id_usuario')"; $query = $conn->query($sql); if($query->rowCount() > 0){ header('Location: index.php'); //echo "<META HTTP-EQUIV=REFRESH CONTENT = '0;URL=http://localhost/Projetos_novos/pos_aula/index.php'>"; } //$query = $conn->query($sql); //$return = $query->fetchAll(PDO::FETCH_ASSOC); //echo $return[0]['url_imagem'];<file_sep>/conexao.php <?php $host = 'localhost'; $dbname = 'posaula'; $user = 'root'; $password = ''; //Faz a conexão com o banco de dados $conn = new PDO ("mysql:host=$host; dbname=$dbname; charset=utf8",$user,$password); //Consulta Padrão /* $sql = "select * from user"; $query = $conn->query($sql); $return = $query->fetchAll(PDO::FETCH_ASSOC); echo $return[0]['url_imagem']; $query->rowCount(); $sql2 = "SELECT nome_grupo FROM usuario_grupo INNER JOIN grupos ON usuario_grupo.id_grupo = grupos.id_grupo"; */
a7d54c8bf10f69d7cd4c28dd64f9812863c3ba53
[ "PHP" ]
13
PHP
PosAula/PHP
0ad3c10f3b7ee0c3d2ad31f20d2bebd8d948283c
f5aa3a951dfa31c377221786c6ec174413a2555d
refs/heads/master
<repo_name>BrentFarris/SDL_GUI<file_sep>/SDL_GUI/GUI_Element.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This is the mian parent class for all of // // GUI elements to be made. // // // ///////////////////////////////////////////////// #ifndef SDL_GUI_ELEMENT_H #define SDL_GUI_ELEMENT_H #endif #pragma once #include "SDL.h" #include "Rectangle.h" #include "InputManager.h" using namespace std; namespace SDL_GUI { class GUI_Element { private: bool mouseIsOver; bool performingClick; protected: void (*onMouseUp)(void); // The mouse up callback void (*onMouseDown)(void); // The mouse down callback void (*onMouseOver)(void); // The mouse over callback void (*onMouseOut)(void); // The mouse out callback void (*onClick)(void); // The click callback Uint32 backgroundColor; public: Rectangle rect; InputManager* inputManager; GUI_Element(); GUI_Element(SDL_Surface* screen, InputManager* passedInputManager); void SetOnClick(void (*callback)(void)) { onClick = callback; } void SetMouseUp(void (*callback)(void)) { onMouseUp = callback; } void SetMouseDown(void (*callback)(void)) { onMouseDown = callback; } void SetMouseOver(void (*callback)(void)) { onMouseOver = callback; } void SetMouseOut(void (*callback)(void)) { onMouseOut = callback; } virtual void Update(); virtual void Draw(SDL_Surface* screen); ~GUI_Element() { } }; }<file_sep>/SDL_GUI/Main.cpp #include "SDL.h" #include "SDL_TTF.h" #include <string> #include "ImageManager.h" #include "InputManager.h" #include "SDL_GUI.h" // The attributes of the screen const int SCREEN_WIDTH = 1280; const int SCREEN_HEIGHT = 720; const int SCREEN_BPP = 32; // The images SDL_Surface* screen = NULL; // Functions to test the button events void ChangeName(string txt); void MouseOver(); void MouseOut(); void MouseDown(); void MouseUp(); void MouseClick(); TTF_Font *font = NULL; int main(int argc, char* args[]) { ImageManager imageManager = ImageManager(); InputManager inputManager = InputManager(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP); SDL_GUI::GUI_Element_Manager elementManager = SDL_GUI::GUI_Element_Manager(); // Make sure that the program waits for quit bool quit = false; // Start SDL if (SDL_Init(SDL_INIT_EVERYTHING) == -1) return 1; // Set up screen screen = SDL_SetVideoMode(SCREEN_WIDTH, SCREEN_HEIGHT, SCREEN_BPP, SDL_SWSURFACE | SDL_RESIZABLE); if (screen == NULL) return 1; if(TTF_Init() == -1) return 1; SDL_WM_SetCaption("SDL_GUI", NULL); // Open the font font = TTF_OpenFont("Fonts/PTC55F.ttf", 18); if (font == NULL) return 1; // Load the images if (imageManager.AddImage("hello", "BeardedManStudios.bmp")) { Image* tmp = imageManager.GetBaseImage("hello"); tmp->rect.x = (inputManager.GetScreenWidth() * 0.5f) - (tmp->image->w * 0.5f); tmp->rect.y = (inputManager.GetScreenHeight() * 0.5f) - (tmp->image->h * 0.5f); } // Create a button and its events SDL_GUI::Button button = SDL_GUI::Button(screen, &inputManager, font, "Button!"); button.rect = Rectangle(15, 15, 150, 50); button.SetMouseOver(&MouseOver); button.SetMouseOut(&MouseOut); button.SetMouseDown(&MouseDown); button.SetMouseUp(&MouseUp); button.SetOnClick(&MouseClick); elementManager.AddElement(&button); SDL_GUI::TextBlock textBlock = SDL_GUI::TextBlock(screen, &inputManager, font, "The quick brown fox jumps over the lazy dog"); textBlock.rect = Rectangle(300, 25, 15, 15); elementManager.AddElement(&textBlock); while (!quit) { inputManager.Update(screen, &quit); elementManager.UpdateElements(); SDL_FillRect(screen, &screen->clip_rect, SDL_MapRGB(screen->format, 0xFF, 0xFF, 0xFF)); Image* tmpHello = imageManager.GetBaseImage("hello"); tmpHello->rect.x = (inputManager.GetScreenWidth() * 0.5f) - (tmpHello->image->w * 0.5f); tmpHello->rect.y = (inputManager.GetScreenHeight() * 0.5f) - (tmpHello->image->h * 0.5f); imageManager.DrawAllImages(screen); elementManager.DrawElements(screen); if (SDL_Flip(screen) == -1) return 1; } // Quit TTF TTF_CloseFont(font); TTF_Quit(); // Quit SDL SDL_Quit(); return 0; } // These are tests to make sure that the button events are working. void ChangeName(string txt) { SDL_WM_SetCaption((string("SDL_GUI: ") + txt).c_str(), NULL); } void MouseOver() { ChangeName("Mouse Over"); } void MouseOut() { ChangeName("Mouse Out"); } void MouseDown() { ChangeName("Mouse Down"); } void MouseUp() { ChangeName("Mouse Up"); } void MouseClick() { ChangeName("Mouse Click"); }<file_sep>/SDL_GUI/Button.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This is a simple button class mainly using // // a rectangle to keep track of all events. // // // ///////////////////////////////////////////////// #ifndef SDL_GUI_BUTTON_H #define SDL_GUI_BUTTON_H #endif #pragma once #include "GUI_Element.h" #include "TextBlock.h" #include <string> namespace SDL_GUI { class Button : public GUI_Element { protected: TextBlock textBlock; string text; // Will be used to have text on button Rectangle lastRect; public: Button(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont); // Initializes button with text as "button" Button(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont, string txt); // Initialize the button with text void Update(); void Draw(SDL_Surface* screen); ~Button() { } }; }<file_sep>/SDL_GUI/Button.cpp #include "Button.h" SDL_GUI::Button::Button(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont) : SDL_GUI::GUI_Element(screen, passedInputManager) { text = "Button"; textBlock = TextBlock(screen, passedInputManager, pfont, text); textBlock.SetColor(175); lastRect = rect; } SDL_GUI::Button::Button(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont, string txt) : SDL_GUI::GUI_Element(screen, passedInputManager) { text = txt; textBlock = TextBlock(screen, passedInputManager, pfont, text); textBlock.SetColor(175); lastRect = rect; } void SDL_GUI::Button::Update() { SDL_GUI::GUI_Element::Update(); if (lastRect != rect) textBlock.rect.Center(rect); lastRect = rect; textBlock.Update(); } void SDL_GUI::Button::Draw(SDL_Surface* screen) { SDL_FillRect(screen, &rect.SDL_Format(), backgroundColor); textBlock.Draw(screen); }<file_sep>/SDL_GUI/ImageManager.cpp #include "ImageManager.h" ImageManager::ImageManager() { } bool ImageManager::AddImage(string imageKey, string imagePath) { SDL_Surface* tmpImg = LoadImage(imagePath); if (tmpImg != NULL) { images[imageKey].image = tmpImg; return true; } return false; } bool ImageManager::AddImage(string imageKey, SDL_Surface* img) { if (img != NULL) { images[imageKey].image = img; return true; } return false; } SDL_Surface* ImageManager::LoadImage(string filename) { // Temporary storage for the image that's loaded SDL_Surface* loadedImage = NULL; //The optimized image that will be used SDL_Surface* optimizedImage = NULL; // Load image loadedImage = IMG_Load(filename.c_str()); //If nothing went wrong in loading the image if (loadedImage != NULL) { // Create an optimized image optimizedImage = SDL_DisplayFormat(loadedImage); // Free the old image SDL_FreeSurface(loadedImage); if (optimizedImage != NULL) { // Map the color key Uint32 colorKey = SDL_MapRGB(optimizedImage->format, 0, 0xFF, 0xFF); // Set all pixels of color R 0, G 0xFF, B 0xFF to be transparent SDL_SetColorKey(optimizedImage, SDL_SRCCOLORKEY, colorKey); } } return optimizedImage; } void ImageManager::DrawImage(string imageKey, SDL_Surface* destination) { // Blit the surface SDL_BlitSurface(images[imageKey].image, NULL, destination, &images[imageKey].rect.SDL_Format()); } void ImageManager::DrawAllImages(SDL_Surface* destination) { for (map<string, Image>::iterator image = images.begin(); image != images.end(); ++image) DrawImage((*image).first, destination); }<file_sep>/SDL_GUI/InputManager.cpp #include "InputManager.h" InputManager::InputManager(int screenSizeX, int screenSizeY, int bppScreen) { mousePosition = Vector2(0, 0); mouseInitialClick = false; mouseInitialRelease = false; screenWidth = screenSizeX; screenHeight = screenSizeY; screenBPP = bppScreen; } void InputManager::Update(SDL_Surface* screen, bool* quit) { mouseInitialClick = false; mouseInitialRelease = false; while(SDL_PollEvent(&event)) { switch(event.type) { //If a key was pressed case SDL_KEYDOWN: switch(event.key.keysym.sym) { case SDLK_UP: break; case SDLK_DOWN: break; case SDLK_LEFT: break; case SDLK_RIGHT: break; } break; case SDL_MOUSEMOTION: // If the mouse was moved // Get the mouse offsets mousePosition.x = event.motion.x; mousePosition.y = event.motion.y; break; case SDL_MOUSEBUTTONDOWN: // If the mouse button was clicked // If it was the left mouse button if (event.button.button == SDL_BUTTON_LEFT) { mouseInitialClick = true; mousePosition.x = event.button.x; mousePosition.y = event.button.y; } break; case SDL_MOUSEBUTTONUP: // If the mouse button was released // If it was the left mouse button if (event.button.button == SDL_BUTTON_LEFT) { mouseInitialRelease = true; mousePosition.x = event.button.x; mousePosition.y = event.button.y; } break; case SDL_VIDEORESIZE: screenWidth = event.resize.w; screenHeight = event.resize.h; screen = SDL_SetVideoMode(screenWidth, screenHeight, screenBPP, SDL_SWSURFACE | SDL_RESIZABLE); // Create new window break; case SDL_QUIT: *quit = true; break; } } }<file_sep>/SDL_GUI/Rectangle.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This is the main rectangle class for the // // library. It should have all the needed // // functionality to keep track of position, // // collision, contains, etc. // // // ///////////////////////////////////////////////// #ifndef IMAGE_MANAGER_H #define IMAGE_MANAGER_H #endif #pragma once #include "SDL.h" #include "Vector2.h" class Rectangle { public: int x; // The x position of the rectangle int y; // The y position of the rectangle int width; // The width of the rectangle int height; // The height of the rectangle Rectangle(); // Initialize the rectangle to have 0 in the x, y, widht, and height Rectangle(int px, int py, int pw, int ph); // Initialize x to px, y to py, width to pw and height to ph bool Contains(int x, int y); // Checks to see if the passed in x and y are within the rectangle bool Contains(Vector2 position); // Breaks the vector2 down to x and y and passes it into the other Contains function bool Intersects(Rectangle inRect); // Checks to see if another rectangle is intersecting this one SDL_Rect SDL_Format(); // Turns this rect into a SDL format rect void Center(Rectangle inRect); // Center this rectangle on another rectangle bool operator==(const Rectangle& other); bool operator!=(const Rectangle& other); ~Rectangle() { } };<file_sep>/SDL_GUI/GUI_Element_Manager.cpp #include "GUI_Element_Manager.h" SDL_GUI::GUI_Element_Manager::GUI_Element_Manager() { } void SDL_GUI::GUI_Element_Manager::AddElement(GUI_Element* element) { elements.push_back(element); } void SDL_GUI::GUI_Element_Manager::UpdateElements() { for (vector<GUI_Element*>::iterator elm = elements.begin(); elm != elements.end(); ++elm) (*elm)->Update(); } void SDL_GUI::GUI_Element_Manager::DrawElements(SDL_Surface* screen) { for (vector<GUI_Element*>::iterator elm = elements.begin(); elm != elements.end(); ++elm) (*elm)->Draw(screen); }<file_sep>/SDL_GUI/TextBlock.h #ifndef TEXTBLOCK_H #define TEXTBLOCK_H #endif #pragma once #include "GUI_Element.h" #include "SDL_TTF.h" #include <string> namespace SDL_GUI { class TextBlock : public GUI_Element { private: SDL_Color fontColor; SDL_Surface* message; void RenderText(); public: string text; TTF_Font* font; TextBlock(); // Requires default constructor for Button class to use it TextBlock(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont); TextBlock(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont, string txt); void Draw(SDL_Surface* screen); void ChangeText(string newText); // This allows for the text to be changed and updated void SetColor(int r, int g, int b); void SetColor(int grayscale); ~TextBlock() { } }; }<file_sep>/SDL_GUI/Vector2.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This is a simple vector class that holds an // // x and y. It's common purpose is to keep // // track of screen coordinates. // // // ///////////////////////////////////////////////// #ifndef VECTOR2_H #define VECTOR2_H #endif #pragma once class Vector2 { public: int x; // The x coordinate int y; // The y coordinate Vector2(); // Construct the vector and set x and y to 0 Vector2(int xy); // Construct the vector and set x and y to xy Vector2(int px, int py); // Construct the vector and set x to pX and y to pY Vector2 GetNormalized(); // Return a vector that is normalized void Normalize(); // Normalize this vector Vector2 operator+(const Vector2& other); // Add this x to the incoming x and add this y to the incoming y Vector2 operator-(const Vector2& other); // Subtract this x to the incoming x and subtract this y to the incoming y Vector2 operator*(const Vector2& other); // Multiply this x to the incoming x and multiply this y to the incoming y Vector2 operator/(const Vector2& other); // Divide this x to the incoming x and divide this y to the incoming y bool operator==(const Vector2& other); bool operator!=(const Vector2& other); ~Vector2() { } };<file_sep>/SDL_GUI/InputManager.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This is just a simple image manager to // // prototype out general functionality for // // the library. // // // ///////////////////////////////////////////////// #ifndef IMAGE_MANAGER_H #define IMAGE_MANAGER_H #endif #pragma once #include "SDL.h" #include "Vector2.h" class InputManager { private: Vector2 mousePosition; // The current mouse position bool mouseInitialClick; // The initial click of the mouse (reset next update) bool mouseInitialRelease; // The initial release of the mouse (reset next update) int screenWidth; // The width of the window (adjustable) int screenHeight; // The height of the window (adjustable) int screenBPP; // Usually set to 32 (bit) public: SDL_Event event; // The main SDL event InputManager(int screenSizeX, int screenSizeY, int bppScreen); // These inputs are used for refreshing the SDL_SetVideoMode void Update(SDL_Surface* screen, bool* quit); // Up the event loop Vector2 GetMousePosition() { return mousePosition; } int GetScreenWidth() { return screenWidth; } int GetScreenHeight() { return screenHeight; } bool MouseDown() { return mouseInitialClick; } bool MouseUp() { return mouseInitialRelease; } ~InputManager() { } };<file_sep>/SDL_GUI/GUI_Element_Manager.h #ifndef GUI_ELEMENT_MANAGER_H #define GUI_ELEMENT_MANAGER_H #endif #pragma once #include "GUI_Element.h" #include <vector> namespace SDL_GUI { class GUI_Element_Manager { public: vector<GUI_Element*> elements; GUI_Element_Manager(); void AddElement(GUI_Element* element); void UpdateElements(); void DrawElements(SDL_Surface* screen); ~GUI_Element_Manager() { } }; }<file_sep>/SDL_GUI/SDL_GUI.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This is the main include point for the // // GUI elements. // // // ///////////////////////////////////////////////// #ifndef SDL_GUI_H #define SDL_GUI_H #endif #pragma once #include "Button.h" #include "TextBlock.h" #include "GUI_Element_Manager.h"<file_sep>/SDL_GUI/TextBlock.cpp #include "TextBlock.h" SDL_GUI::TextBlock::TextBlock() { message = NULL; } SDL_GUI::TextBlock::TextBlock(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont) : SDL_GUI::GUI_Element(screen, passedInputManager) { fontColor = SDL_Color(); font = pfont; text = ""; message = NULL; RenderText(); } SDL_GUI::TextBlock::TextBlock(SDL_Surface* screen, InputManager* passedInputManager, TTF_Font* pfont, string txt) : SDL_GUI::GUI_Element(screen, passedInputManager) { fontColor = SDL_Color(); font = pfont; text = txt; message = NULL; RenderText(); } void SDL_GUI::TextBlock::ChangeText(string newText) { text = newText; RenderText(); } void SDL_GUI::TextBlock::RenderText() { if (message != NULL) SDL_FreeSurface(message); message = TTF_RenderText_Solid(font, text.c_str(), fontColor); rect.width = message->w; rect.height = message->h; } void SDL_GUI::TextBlock::Draw(SDL_Surface* screen) { SDL_BlitSurface(message, NULL, screen, &rect.SDL_Format()); } void SDL_GUI::TextBlock::SetColor(int r, int g, int b) { fontColor.r = r; fontColor.g = g; fontColor.b = b; RenderText(); } void SDL_GUI::TextBlock::SetColor(int grayscale) { fontColor.r = grayscale; fontColor.g = grayscale; fontColor.b = grayscale; RenderText(); }<file_sep>/SDL_GUI/GUI_Element.cpp #include "GUI_Element.h" SDL_GUI::GUI_Element::GUI_Element() { } SDL_GUI::GUI_Element::GUI_Element(SDL_Surface* screen, InputManager* passedInputManager) { mouseIsOver = false; performingClick = false; backgroundColor = SDL_MapRGB(screen->format, 0, 0, 0); onMouseUp = NULL; onMouseDown = NULL; onMouseOver = NULL; onMouseOut = NULL; onClick = NULL; inputManager = passedInputManager; } void SDL_GUI::GUI_Element::Update() { bool inRect = rect.Contains(inputManager->GetMousePosition()); if (!mouseIsOver && inRect) { mouseIsOver = true; if (onMouseOver != NULL) onMouseOver(); } else if (mouseIsOver && !inRect) { mouseIsOver = false; performingClick = false; if (onMouseOut != NULL) onMouseOut(); } if (inRect) { if (inputManager->MouseDown()) { performingClick = true; if (onMouseDown != NULL) onMouseDown(); } else if (inputManager->MouseUp()) { if (onMouseUp != NULL) onMouseUp(); if (performingClick) { performingClick = false; if (onClick != NULL) onClick(); } } } } void SDL_GUI::GUI_Element::Draw(SDL_Surface* screen) { }<file_sep>/SDL_GUI/ImageManager.h ///////////////////////////////////////////////// // // // <NAME>, Bearded Man Studios, Inc. // // https://www.beardedmangames.com/ // // // ///////////////////////////////////////////////// // // // This input manager is used to keep track // // of the input events and should be expanded // // to support any range of inputs. // // // ///////////////////////////////////////////////// #ifndef IMAGE_MANAGER_H #define IMAGE_MANAGER_H #endif #pragma once #include "SDL.h" #include "SDL_image.h" #include "Rectangle.h" #include <map> #include <string> using namespace std; class Image { public: Image() { } Rectangle rect; SDL_Surface* image; }; class ImageManager { private: map<string, Image> images; // A key value map to get images by key name public: ImageManager(); bool AddImage(string imageKey, string imagePath); bool AddImage(string imageKey, SDL_Surface* img); Image* GetBaseImage(string imageKey) { return &images[imageKey]; } SDL_Surface* GetImage(string imageKey) { return images[imageKey].image; } SDL_Surface* LoadImage(std::string filename); void DrawImage(string imageKey, SDL_Surface* destination); void DrawAllImages(SDL_Surface* destination); // Free the images from the map ~ImageManager() { for (map<string, Image>::iterator image = images.begin(); image != images.end(); ++image) SDL_FreeSurface((*image).second.image); } };<file_sep>/SDL_GUI/Rectangle.cpp #include "Rectangle.h" Rectangle::Rectangle() { x = 0; y = 0; width = 0; height = 0; } Rectangle::Rectangle(int px, int py, int pw, int ph) { x = px; y = py; width = pw; height = ph; } bool Rectangle::Contains(int x, int y) { if (x >= this->x && x <= this->x + this->width && y >= this->y && y <= this->y + this->height) return true; else return false; } bool Rectangle::Contains(Vector2 position) { return Contains(position.x, position.y); } bool Rectangle::Intersects(Rectangle inRect) { if (this->Contains(inRect.x, inRect.y) || this->Contains(inRect.x + inRect.width, inRect.y) || this->Contains(inRect.x, inRect.y + inRect.height) || this->Contains(inRect.x + inRect.width, inRect.y + inRect.height)) { return true; } else if (inRect.Contains(this->x, this->y) || inRect.Contains(this->x + this->width, this->y) || inRect.Contains(this->x, this->y + this->height) || inRect.Contains(this->x + this->width, this->y + this->height)) { return true; } return false; } SDL_Rect Rectangle::SDL_Format() { SDL_Rect tmp; tmp.x = x; tmp.y = y; tmp.w = width; tmp.h = height; return tmp; } void Rectangle::Center(Rectangle inRect) { x = (inRect.x + (inRect.width * 0.5f)) - (width * 0.5f); y = (inRect.y + (inRect.height * 0.5f)) - (height * 0.5f); } bool Rectangle::operator==(const Rectangle& other) { return this->x == other.x && this->y == other.y && this->width == other.width && this->height == other.height; } bool Rectangle::operator!=(const Rectangle& other) { return this->x != other.x && this->y != other.y && this->width != other.width && this->height != other.height; }<file_sep>/SDL_GUI/Vector2.cpp #include "Vector2.h" #include <cmath> Vector2::Vector2() { x = 0; y = 0; } Vector2::Vector2(int xy) { x = xy; y = xy; } Vector2::Vector2(int px, int py) { x = px; y = py; } Vector2 Vector2::GetNormalized() { Vector2 tmp = Vector2(this->x, this->y); float mag = std::sqrt((tmp.x * tmp.x) + (tmp.y * tmp.y)); tmp.x = tmp.x / mag; tmp.y = tmp.y / mag; return tmp; } void Vector2::Normalize() { float mag = std::sqrt((x * x) + (y * y)); x = x / mag; y = y / mag; } Vector2 Vector2::operator+(const Vector2& other) { return Vector2(this->x + other.x, this->y + other.y); } Vector2 Vector2::operator-(const Vector2& other) { return Vector2(this->x - other.x, this->y - other.y); } Vector2 Vector2::operator*(const Vector2& other) { return Vector2(this->x * other.x, this->y * other.y); } Vector2 Vector2::operator/(const Vector2& other) { return Vector2(this->x / other.x, this->y / other.y); } bool Vector2::operator==(const Vector2& other) { return this->x == other.x && this->y == other.y; } bool Vector2::operator!=(const Vector2& other) { return this->x != other.x && this->y != other.y; }<file_sep>/README.md SDL_GUI ======= This is going to be a GUI library for SDL. That being said its original intent is to be a learning tool. This library originates from <NAME> and possibly other members of the Bearded Man Studios: https://www.beardedmangames.com/ If you are not familiar with SDL check out this link: http://lazyfoo.net/SDL_tutorials/index.php
3cac0d9428bbaa96f9e2806bc23532f1086da58c
[ "Markdown", "C", "C++" ]
19
C++
BrentFarris/SDL_GUI
3adff7749c89d52b30cf5dd3a45152870bbb89fa
7a6b1ad7bffb40d65de22e1d20291a43a4f8bee3
refs/heads/master
<repo_name>ecsalunga/July2017<file_sep>/src/environments/environment.prod.ts export const environment = { production: true, firebase: { apiKey: "<KEY>", authDomain: "temp-system.firebaseapp.com", databaseURL: "https://temp-system.firebaseio.com", storageBucket: "temp-system.appspot.com", messagingSenderId: "1098645781584" } };
c76bfa63b0ad3b5e6116cb08d4a11a2a6fcf278d
[ "TypeScript" ]
1
TypeScript
ecsalunga/July2017
b9a171e28dbad2cfda61be0fb5b32f728c713d64
67ca77f0bb92705614293ddee3528994c0836413
refs/heads/master
<file_sep>package com.fmu.myapplication; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { ListView list; String[] Marcas = {"Fiat", "Ford", "GM", "Honda", "Kia", "Toyota"}; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); list = (ListView) findViewById(R.id.ListMarcas); ArrayAdapter<String> mAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, Marcas); list.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { TextView tmp = (TextView) view; String Value = list.getItemAtPosition(i).toString(); Toast.makeText(getApplicationContext(), Value, Toast.LENGTH_SHORT).show(); } }); list.setAdapter(mAdapter); } }
11c142362bc73f75810066e0050589675bf47e19
[ "Java" ]
1
Java
cesarboy/ListView_TOAST
cf52a908d240b8293c610568c8882168189d50cb
7698a08b5871fe6a835c264b93b65e7dbf6271e2
refs/heads/master
<file_sep>import { resolve } from "path"; import * as TJS from "typescript-json-schema"; import fs from "fs/promises"; import rimraf from "rimraf"; /** * File that reads *IRoute types from types/ * and generates schemas for it */ const BASE_PATH = "./src/types"; (async () => { // Read all files on base_path, there should be only router files let allTypeFiles = await fs.readdir(BASE_PATH); allTypeFiles = allTypeFiles.filter((file) => file.endsWith(".ts")); // Create a runner and a generator for transforming .ts into json schemas // pass, all .ts files into it const TJSProgram = TJS.getProgramFromFiles( allTypeFiles.map((fileName) => resolve(`${BASE_PATH}/${fileName}`)), //typescript compiler flags so we can traverse any module { resolveJsonModule: true, esModuleInterop: true, lib: ["ES2020"], target: "ES2020", } ); const TJSGenerator = TJS.buildGenerator( TJSProgram, {} ) as TJS.JsonSchemaGenerator; // Get all the symbols and filter them to only generate schemas // from Route symbols let TJSSymbols = TJSGenerator.getUserSymbols(); let symbolsFiltered = TJSSymbols.filter((s) => s.endsWith("IRoute")); // Temporary folder for schemas await fs.mkdir("./src/schemas_temp"); let schemaNames: string[] = []; // Generate all the schemas await Promise.all( symbolsFiltered.map(async (s) => { let schema = TJSGenerator.getSchemaForSymbol(s); let schemaName = s.replace("IRoute", ""); if (["e.", ""].includes(schemaName)) return; console.log(`Generated ${schemaName}.json`); schemaNames.push(schemaName); await fs.writeFile( `./src/schemas_temp/${schemaName}.json`, JSON.stringify(schema) ); }) ); console.log("Generated schemas import map"); // At last, generate an index that exports all schemas so it's imported from a Schemas.{SchemaName} manner await fs.writeFile( `./src/schemas_temp/GeneratedSchemas.ts`, schemaNames .map((s) => `import ${s}Schema from "./${s}.json"\n` + `export { ${s}Schema }\n`) .join("\n") ); /** * For fastify-swagger we need to put definitions on the initialization, that's why we merge all * types and inject them in a .json to be used in the initialization of the service. * * In that way, referencing types from $ref work nicely! */ let allSchemas = TJSGenerator.getSchemaForSymbols(symbolsFiltered); await fs.writeFile( `./src/schemas_temp/definitions.json`, JSON.stringify(allSchemas) ); // Delete all schemas and move temporary folder as main folder await new Promise((res) => rimraf("./src/schemas", res)); await fs.rename("./src/schemas_temp", "./src/schemas"); })(); <file_sep>import ExampleBodySchema from "./ExampleBody.json" export { ExampleBodySchema } <file_sep>import swagger from "fastify-swagger"; import { FastifyApp } from "../types/common"; import * as fastify from "fastify"; // Compiled definitions import definitionsSchema from "../schemas/definitions.json"; export function initDocumentation(app: FastifyApp, version: string) { app.register(swagger, { routePrefix: "/docs", swagger: { info: { title: "Auth API", description: "Documentation for the Auth API", version, }, // host: "localhost", schemes: ["http", "https"], consumes: ["application/json"], produces: ["application/json"], /** * Inject compiled definitions here! */ definitions: { ...(definitionsSchema.definitions as { [definitionsName: string]: fastify.FastifySchema; }), }, securityDefinitions: { apiKey: { type: "apiKey", name: "apiKey", in: "header", }, }, }, exposeRoute: true, }); console.log(`Documentation started at /docs!`); } <file_sep>import { FastifyLoggerInstance } from "fastify"; import { FastifyInstance } from "fastify/types/instance"; import { Server, IncomingMessage, ServerResponse } from "http"; // Helper for fastify, much more compact export type FastifyApp = FastifyInstance< Server, IncomingMessage, ServerResponse, FastifyLoggerInstance >; // Helper for Route, considering services export interface Route { init: (app: FastifyApp, services: Services) => void; prefix: string; } // Handy interface for Services that return a Promise export type Awaited<T> = T extends PromiseLike<infer U> ? Awaited<U> : T; export interface Services { // Something as: // db: ReturnType<typeof initMongoDB>; // db: Awaited<ReturnType<typeof initMongoDB>>; } <file_sep>/** * For constructing schemas, check: * @see https://github.com/YousefED/typescript-json-schema/blob/master/api.md */ /** * This Example interface can be anywhere in your project */ export interface Example { exampleParam: string; } export interface ExampleBodyIRoute { example: Example; arr: string[]; } <file_sep>import { FastifyApp, Services } from "../types/common"; import { ExampleBodyIRoute } from "../types/ExampleTypes"; import { ExampleBodySchema } from "../schemas/GeneratedSchemas"; export function initExampleRoutes(app: FastifyApp, {}: Services) { app.post<{ //Querystring: LoginRoute //Headers: LoginRoute Body: ExampleBodyIRoute; }>( "/route", { schema: { body: ExampleBodySchema, }, }, async (req, res) => { let { example, arr } = req.body; return res.send({ echo: { example, arr }, }); } ); } <file_sep># node-ts-fastify-boilerplate Boilerplate for starting node.js and typescript servers already with yarn. _Current Node version targeted, v14+._ ## Why? I really hate boilerplates that throw a lot of stuff that you need to learn in, I like boilerplates that just stay out of the way and organize only what's really a pain in the ass. I hope this to be it. ## What's in the package! - fastify 🚀 - fastify-swagger 📚 - **(NEW!)** Auto-documentation generated from typescript types! `generateSchemasFromTS.ts` 🤯 - `yarn gen:schema` ## Installing `npx degit pedropalhari/node-ts-fastify-boilerplate project_name` ## Commands - `yarn start`: runs the distributed copy on `dist/index.js` - `yarn dev`: starts the typescript compiler on watch mode (`tsc -w`) - in `tsconfig.json` you can set the properties on `outDir` and `rootDir` - `yarn build`: builds the code, incrementally - `yarn gen:schema`: generates JSON schema to be used for validation. ## How to use it! To use this boilerplate fully, there's only a few rules to abide by: ### Creating a new **route**! - Create a new file in `routes/`. ```ts // routes/Example.ts import { FastifyApp } from "../types/common"; export function initExampleRoutes(app: FastifyApp, service: {}) { app.post("/route", async (req, res) => { return res.send({ echo: "not yet", }); }); } ``` - Add it to `index.ts` to the `Router` with the prefix you want. ```ts // index.ts /** * Route array with prefixes */ const Routes: Route[] = [ { init: initExampleRoutes, prefix: "/example", }, ]; ``` ### Creating validation for this route! - Create a type in the `types/` folder. **The type must end in `IRoute`!** - I'm using [typescript-json-schema](https://github.com/YousefED/typescript-json-schema), that is a little bit heavy on generating JSON schemas. ```ts // types/ExampleTypes.d.ts export interface Example { exampleParam: string; } export interface ExampleBodyIRoute { example: Example; arr: string[]; } ``` - Run `yarn gen:schema` - For each `IRoute` type it will create a `.json` file on `schemas/` - It also compiles all schemas into `schemas/definitions.json` so we can use any types from the project, not any from the `types/` folder. - And for the last part it adds a nice import map so you can do `{type}Schema` and autocomplete. - Add the type and generated schema to the route: ```ts // routes/Example.ts import { FastifyApp } from "../types/common"; import { ExampleBodyIRoute } from "../types/ExampleTypes"; // <-- Here! import { ExampleBodySchema } from "../schemas/GeneratedSchemas"; export function initExampleRoutes(app: FastifyApp, {}: Services) { app.post<{ Body: ExampleBodyIRoute; // <-- Here! }>( "/route", { schema: { body: ExampleBodySchema, // <-- Here! }, }, async (req, res) => { let { example, arr } = req.body; return res.send({ echo: { example, arr }, }); } ); } ``` ### **Tã dã!** ## Useful `services` ### MongoDB ```ts // services/Mongo.ts import { Collection, MongoClient } from "mongodb"; // Connection URL const URL = "mongodb://localhost:27017"; // Database Name const dbName = "myproject"; interface User { username: string; password: string; } interface Email { recipient: string; delay: number; } export interface DBCollections { user: Collection<User>; emails: Collection<Email>; } export async function initMongoDB(): Promise<DBCollections> { // Create a new MongoClient const client = new MongoClient(URL); await client.connect(); const db = client.db(dbName); return { user: db.collection("user"), emails: db.collection("email"), }; } ``` Then on `types/common.d.ts`, `index.ts` and the `routes/*.ts` ```ts //types/common.d.ts export interface Services { db: DBCollections; } //index.ts async function main() { initDocumentation(app, API_VERSION); let db = await initMongoDB(); // <-- Here! //... // Initialize all the routes in the array, passing the db for // operations and the app for creating handlers Routes.forEach((route) => { app.register((app, opts, done) => { route.init(app, { db }); // <-- Here! //... }); }); } // routes/*.ts export function initExampleRoutes(app: FastifyApp, { db }: Services) { //... let queryResult = await db.user.findOne({}); } ``` ## Credits _Made by me, for me, so I can build services faster. Feel free to use, expand and contact me!_ <file_sep>import fastify from "fastify"; import { initExampleRoutes } from "./routes/Example"; import { initDocumentation } from "./services/Documentation"; import fastifyCors from "fastify-cors"; import { Route } from "./types/common"; /** * Main server: * * Initialize the services, pass it to the routes and initialize * the routes. */ const app = fastify(); app.register(fastifyCors); const API_VERSION = "v0.1.0"; async function main() { initDocumentation(app, API_VERSION); /** * Route array with prefixes */ const Routes: Route[] = [ { init: initExampleRoutes, prefix: "/example", }, ]; // Initialize all the routes in the array, passing the db for // operations and the app for creating handlers Routes.forEach((route) => { app.register( (app, opts, done) => { route.init(app, {}); console.log(`Initialized ${route.prefix}!`); done(); }, { prefix: route.prefix, } ); }); await app.ready(); app.swagger(); let listeningResult = await app.listen(6680, "0.0.0.0"); console.log(`Fastify initialized at ${listeningResult}`); } main();
52035cb6d5751aaed50b17de2350a4d321ee7cfd
[ "Markdown", "TypeScript" ]
8
TypeScript
pedropalhari/node-ts-fastify-boilerplate
1e6b4ea4222d0b47170608c09fb93dea37b967d3
5c660a25bef10762b7987bdf721c6e9e6aa0f972
refs/heads/master
<file_sep># Instagram-mini A simple version of [Instagram](https://www.instagram.com/), where you can create an account, publish photos, comment and like posts of other users. ### Getting started Before installing the application, you must install `meteor`. For `osx/linux` type on your terminal `curl https://install.meteor.com/ | sh` For `windows` go to https://www.meteor.com/install, download and run Meteor installer. ### Installing You can clone this repository. Open terminal and type: ``` git clone https://github.com/DmytroTohan/final-task.git ``` or download ZIP. After that, go to the app folder `../final-task` and type: ``` npm run build ``` after that, type: ``` meteor ``` Open your web browser and go to http://localhost:3000 to see the app running. ## Deployment App was deployed on [Heroku](http://www.heroku.com) Link: [https://instagram-mini.heroku.com](https://myinstagram.heroku.com) ## Built With * [Meteor](https://www.meteor.com/) - is a full-stack JavaScript platform, which is suitable for writing real-time application. * [MongoDB](https://www.mongodb.com/) - all data is stored in the mongo collections. For the photos storage used [GridFS](https://docs.mongodb.com/manual/core/gridfs/) * [Bootstrap](http://getbootstrap.com/getting-started/) - framework for client side. <file_sep>Template.postSubmit.events({ 'submit form': function(e) { e.preventDefault(); var imageURL = $('span.image-url').text(); if (!imageURL) { return throwError('Please, choose a photo for the new post!'); } var post = { imageURL: $('span.image-url').text(), userImageURL: Meteor.user().profile.image }; Meteor.call('postInsert', post, function(error, result) { Router.go('postPage', { _id: result._id }); }); }, 'click #cancel-btn': function() { Router.go('home'); }, 'change #imgInp': function(e) { FS.Utility.eachFile(e, function(file) { Images.insert(file, function(err, fileObj) { if (err) { // handle error } else { var imagePath = '/cfs/files/images/' + fileObj._id; $('span.image-url').text(imagePath); $('input[type=submit]').removeClass('disabled'); setTimeout(function() { $('#imageupload').get(0).src = imagePath; }, 500); } }); }); } }); <file_sep>Posts = new Mongo.Collection('posts'); var imageStore = new FS.Store.GridFS('images'); Images = new FS.Collection('images', { stores: [imageStore] }); Posts.allow({ update: function(userId, post) { return ownsDocument(userId, post); }, remove: function(userId, post) { return ownsDocument(userId, post); } }); Images.deny({ insert: function() { return false; }, update: function() { return false; }, remove: function() { return false; }, download: function() { return false; } }); Images.allow({ insert: function() { return true; }, update: function() { return true; }, remove: function() { return true; }, download: function() { return true; } }); Meteor.methods({ postInsert: function(postAttributes) { var user = Meteor.user(); var post = _.extend({ userId: user._id, author: user.username, imageURL: postAttributes.imageURL, userImage: postAttributes.userImageURL, submitted: new Date(), commentsCount: 0, upvoters: [], votes: 0 }); var postId = Posts.insert(post); return { _id: postId }; }, upvote: function(postId) { var affected = Posts.update({ _id: postId, upvoters: { $ne: this.userId } }, { $addToSet: { upvoters: this.userId }, $inc: { votes: 1 } }); if (!affected) throw new Meteor.Error('invalid', "You weren't able to upvote that post"); } }); Meteor.users.allow({ update: function (userId, doc, fields, modifier) { return true; } }); <file_sep>$(window).scroll(function() { var $menu = $('nav.navbar'); var top = $(this).scrollTop(); $('body').css('margin-top', top > 0 ? '5px' : '0px'); $('ul.navbar-right').css('margin-right', top > 0 ? '15px' : '0px'); if (top > 0) { $menu.addClass('navbar-fixed-top'); } else if (top < 50) { $menu.removeClass('navbar-fixed-top'); } });
a170b86392943208f6ca39af6b39c9c8b7c2d765
[ "Markdown", "JavaScript" ]
4
Markdown
DmytroTohan/final-task
46eda6faa97c28529e05a86e4ffcf629b72876b3
1a76e5b091f4cbbcc8b92e35697cb251ad0b2916
refs/heads/master
<repo_name>grape31417/Learning-Android<file_sep>/IntentCarryData/app/src/main/java/com/example/user/IntentCarryData/MainActivity.java package com.example.user.IntentCarryData; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; public class MainActivity extends AppCompatActivity { private TextView mTxtResult; private ImageButton mSicssors,mStone,mPaper; private ImageView mTxtComplay; private Button mBtnShowResult, mBtnSaveResult, mBtnLoadResult, mBtnClearResult; private int miCountSet = 0, miCountPlayerWin = 0, miCountComWin = 0, miCountDraw = 0; private final static int NOTI_ID = 100; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTxtComplay=(ImageView) findViewById(R.id.imgViewComPlay); mTxtResult=(TextView)findViewById(R.id.txtResult); mSicssors=(ImageButton)findViewById(R.id.imgBtnScissors); mPaper=(ImageButton)findViewById(R.id.imgBtnPaper); mStone=(ImageButton)findViewById(R.id.imgBtnStone); mBtnShowResult=(Button)findViewById(R.id.btnShowResult) ; mSicssors.setOnClickListener(btnSicssors); mStone.setOnClickListener(btnStone); mPaper.setOnClickListener(btnPaper); mBtnShowResult.setOnClickListener(btnShowResult); mBtnSaveResult = (Button)findViewById(R.id.btnSaveResult); mBtnLoadResult = (Button)findViewById(R.id.btnLoadResult); mBtnClearResult = (Button)findViewById(R.id.btnClearResult); mBtnSaveResult.setOnClickListener(btnSaveResultOnClick); mBtnLoadResult.setOnClickListener(btnLoadResultOnClick); mBtnClearResult.setOnClickListener(btnClearResultOnClick); } @Override protected void onDestroy() { ((NotificationManager)getSystemService(NOTIFICATION_SERVICE)).cancel(NOTI_ID); super.onDestroy(); } private View.OnClickListener btnSicssors =new View.OnClickListener() { @Override public void onClick(View v) { int iComPlay =(int)(Math.random()*3+1);//1:剪刀 2:石頭 3:布 miCountSet++; if(iComPlay==1) { miCountDraw++; mTxtComplay.setImageResource(R.drawable.scissors); mTxtResult.setText(getString(R.string.result)+getString(R.string.draw)); showNotification("平手"+Integer.toString(miCountDraw)+"局"); } else if(iComPlay==2) { miCountComWin++; mTxtComplay.setImageResource(R.drawable.stone); mTxtResult.setText(getString(R.string.result)+getString(R.string.you_lose)); showNotification("你輸了"+Integer.toString(miCountComWin)+"局"); } else { miCountPlayerWin++; mTxtComplay.setImageResource(R.drawable.paper); mTxtResult.setText(getString(R.string.result)+getString(R.string.you_win)); showNotification("你贏了"+Integer.toString(miCountPlayerWin)+"局"); } } }; private View.OnClickListener btnStone =new View.OnClickListener() { @Override public void onClick(View v) { int iComPlay =(int)(Math.random()*3+1);//1:剪刀 2:石頭 3:布 miCountSet++; if(iComPlay==1) { mTxtComplay.setImageResource(R.drawable.scissors); mTxtResult.setText(getString(R.string.result)+getString(R.string.you_win)); miCountPlayerWin++; showNotification("你贏了"+Integer.toString(miCountPlayerWin)+"局"); } else if(iComPlay==2) { mTxtComplay.setImageResource(R.drawable.stone); mTxtResult.setText(getString(R.string.result)+getString(R.string.draw)); miCountDraw++; showNotification("平手"+Integer.toString(miCountDraw)+"局"); } else { miCountComWin++; mTxtComplay.setImageResource(R.drawable.paper); mTxtResult.setText(getString(R.string.result)+getString(R.string.you_lose)); showNotification("你輸了"+Integer.toString(miCountComWin)+"局"); } } }; private View.OnClickListener btnPaper =new View.OnClickListener() { @Override public void onClick(View v) { int iComPlay =(int)(Math.random()*3+1);//1:剪刀 2:石頭 3:布 miCountSet++; if(iComPlay==1) { miCountComWin++; mTxtComplay.setImageResource(R.drawable.scissors); mTxtResult.setText(getString(R.string.result)+getString(R.string.you_lose)); showNotification("你輸了"+Integer.toString(miCountComWin)+"局"); } else if(iComPlay==2) { miCountPlayerWin++; mTxtComplay.setImageResource(R.drawable.stone); mTxtResult.setText(getString(R.string.result)+getString(R.string.you_win)); showNotification("你贏了"+Integer.toString(miCountPlayerWin)+"局"); } else { miCountDraw++; mTxtComplay.setImageResource(R.drawable.paper); mTxtResult.setText(getString(R.string.result)+getString(R.string.draw)); showNotification("平手"+Integer.toString(miCountDraw)+"局"); } } }; private View.OnClickListener btnShowResult = new View.OnClickListener() { @Override public void onClick(View v) { Intent it = new Intent(); it.setClass(MainActivity.this,gameResult.class); Bundle bundle =new Bundle(); bundle.putInt("KEY_COUNT_SET", miCountSet); bundle.putInt("KEY_COUNT_PLAYER_WIN", miCountPlayerWin); bundle.putInt("KEY_COUNT_COM_WIN", miCountComWin); bundle.putInt("KEY_COUNT_DRAW", miCountDraw); it.putExtras(bundle); startActivity(it); } }; private void showNotification (String sMsg) { Intent stbar =new Intent(getApplicationContext(),gameResult.class); stbar.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Bundle bundle =new Bundle(); bundle.putInt("KEY_COUNT_SET",miCountSet); bundle.putInt("KEY_COUNT_PLAYER_WIN",miCountPlayerWin); bundle.putInt("KEY_COUNT_COM_SET",miCountComWin); bundle.putInt("KEY_COUNT_DRAW",miCountDraw); stbar.putExtras(bundle); PendingIntent penit =PendingIntent.getActivities(getApplicationContext(),0, new Intent[]{stbar},PendingIntent.FLAG_CANCEL_CURRENT); Notification noti =new Notification.Builder(this) .setSmallIcon(android.R.drawable.btn_star_big_on) .setTicker(sMsg) .setContentTitle(getString(R.string.app_name)) .setContentText(sMsg) .setContentIntent(penit) .build(); NotificationManager notiMgr =(NotificationManager)getSystemService(NOTIFICATION_SERVICE); notiMgr.notify(NOTI_ID,noti); } private View.OnClickListener btnSaveResultOnClick = new View.OnClickListener() { public void onClick(View v) { SharedPreferences gameResultData = getSharedPreferences("GAME_RESULT", 0); gameResultData.edit() .putInt("COUNT_SET", miCountSet) .putInt("COUNT_PLAYER_WIN", miCountPlayerWin) .putInt("COUNT_COM_WIN", miCountComWin) .putInt("COUNT_DRAW", miCountDraw) .commit(); Toast.makeText(MainActivity.this, "儲存完成", Toast.LENGTH_LONG) .show(); } }; private View.OnClickListener btnLoadResultOnClick = new View.OnClickListener() { public void onClick(View v) { SharedPreferences gameResultData = getSharedPreferences("GAME_RESULT", 0); miCountSet = gameResultData.getInt("COUNT_SET", 0); miCountPlayerWin = gameResultData.getInt("COUNT_PLAYER_WIN", 0); miCountComWin = gameResultData.getInt("COUNT_COM_WIN", 0); miCountDraw = gameResultData.getInt("COUNT_DRAW", 0); Toast.makeText(MainActivity.this, "載入完成", Toast.LENGTH_LONG) .show(); } }; private View.OnClickListener btnClearResultOnClick = new View.OnClickListener() { public void onClick(View v) { SharedPreferences gameResultData = getSharedPreferences("GAME_RESULT", 0); gameResultData.edit() .clear() .commit(); Toast.makeText(MainActivity.this, "清除完成", Toast.LENGTH_LONG) .show(); } }; } <file_sep>/myfirstapp/app/src/main/java/com/example/bluedream/myfirstapp/MainActivity.java package com.example.bluedream.myfirstapp; import android.support.annotation.IdRes; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.AdapterView; import android.widget.Button; import android.widget.EditText; import android.widget.RadioButton; import android.widget.RadioGroup; import android.widget.Spinner; import android.widget.TextView; public class MainActivity extends AppCompatActivity { EditText mEdtSex,mEdtAge; TextView mTxtR; Button mBtnok; private RadioGroup mRadGrpSex,mRadGrpAge; private RadioButton mRadBtnAgeRange1,mRadBtnAgeRange2,mRadBtnAgeRange3; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnok=(Button)findViewById(R.id.btnOK); mTxtR=(TextView)findViewById(R.id.txtR); mRadGrpAge=(RadioGroup)findViewById(R.id.radGrpAge) ; mRadGrpSex=(RadioGroup)findViewById(R.id.radGrpSex) ; mRadBtnAgeRange1=(RadioButton) findViewById(R.id.radBtnAgeRange1); mRadBtnAgeRange2=(RadioButton) findViewById(R.id.radBtnAgeRange2); mRadBtnAgeRange3=(RadioButton) findViewById(R.id.radBtnAgeRange3); mRadGrpSex.setOnCheckedChangeListener(radGrpSexOnCheckChange); mBtnok.setOnClickListener(btnOKOnClick); } private View.OnClickListener btnOKOnClick=new View.OnClickListener() { @Override public void onClick(View v) { String strSug =getString(R.string.suggestion); switch (mRadGrpAge.getCheckedRadioButtonId()) { case R.id.radBtnAgeRange1: strSug+=getString(R.string.sug_not_hurry); break; case R.id.radBtnAgeRange2: strSug+=getString(R.string.sug_find_couple); break; case R.id.radBtnAgeRange3: strSug+=getString(R.string.sug_get_married); break; } mTxtR.setText(strSug); } }; private RadioGroup.OnCheckedChangeListener radGrpSexOnCheckChange =new RadioGroup.OnCheckedChangeListener() { @Override public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) { if (checkedId==R.id.radBtnMale) { mRadBtnAgeRange1.setText(getString(R.string.male_age_range1)); mRadBtnAgeRange2.setText(getString(R.string.male_age_range2)); mRadBtnAgeRange3.setText(getString(R.string.male_age_range3)); } else { mRadBtnAgeRange1.setText(getString(R.string.female_age_range1)); mRadBtnAgeRange2.setText(getString(R.string.female_age_range2)); mRadBtnAgeRange3.setText(getString(R.string.female_age_range3)); } } }; } <file_sep>/Intent/app/src/main/java/com/example/user/intent/MainActivity.java package com.example.user.intent; import android.content.Intent; import android.net.Uri; import android.os.Environment; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import java.io.File; public class MainActivity extends AppCompatActivity { private Button mBtnBrowseWWW, mBtnEditImg,mBtnViewImg; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnBrowseWWW=(Button)findViewById(R.id.btnBrowseWWW); mBtnEditImg =(Button)findViewById(R.id.btnPlayMP3); mBtnViewImg=(Button)findViewById(R.id.btnViewImg); mBtnViewImg.setOnClickListener(ViewImageOnClick); mBtnEditImg.setOnClickListener(EditImgOnClick); mBtnBrowseWWW.setOnClickListener(BrowseWWWOnClick); } private View.OnClickListener ViewImageOnClick =new View.OnClickListener() { @Override public void onClick(View v) { Intent it= new Intent(Intent.ACTION_VIEW); // String sImgFile = Environment.getExternalStorageDirectory().getPath()+ File.separator+"image.png"; File file =new File("/sdcard/image.png"); it.setDataAndType(Uri.fromFile(file),"image/*"); startActivity(it); } }; private View.OnClickListener EditImgOnClick =new View.OnClickListener() { @Override public void onClick(View v) { Intent it =new Intent(Intent.ACTION_EDIT); File file = new File("/sdcard/image.png"); it.setDataAndType(Uri.fromFile(file),"image/*"); startActivity(it); } }; /*private View.OnClickListener PlayMp3OnClick = new View.OnClickListener() { @Override public void onClick(View v) { Intent it= new Intent(Intent.ACTION_VIEW); String sMp3File = Environment.getExternalStorageDirectory().getPath()+ File.separator+"song.mp3"; File file =new File(sMp3File); boolean b=file.exists(); it.setDataAndType(Uri.fromFile(file),"audio/*"); startActivity(it); } };*/ private View.OnClickListener BrowseWWWOnClick =new View.OnClickListener() { @Override public void onClick(View v) { Uri uri =Uri.parse("https://www.google.com.tw/"); Intent it =new Intent(Intent.ACTION_VIEW,uri); startActivity(it); } }; } <file_sep>/BroadCast/app/src/main/java/com/example/user/broadcast/MainActivity.java package com.example.user.broadcast; import android.content.Intent; import android.content.IntentFilter; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { private Button mBtnRegReceiver, mBtnUnregReceiver, mBtnSendBroadcast1, mBtnSendBroadcast2; MyBroadcastReceiver2 mMyRecever2; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnRegReceiver = (Button)findViewById(R.id.btnRegReceiver); mBtnUnregReceiver = (Button)findViewById(R.id.btnUnregReceiver); mBtnSendBroadcast1 = (Button)findViewById(R.id.btnSendBroadcast1); mBtnSendBroadcast2 = (Button)findViewById(R.id.btnSendBroadcast2); mBtnRegReceiver.setOnClickListener(btnRegReceiverOnClick); mBtnUnregReceiver.setOnClickListener(btnUnregReceiverOnClick); mBtnSendBroadcast1.setOnClickListener(btnSendBroadcast1OnClick); mBtnSendBroadcast2.setOnClickListener(btnSendBroadcast2OnClick); } private View.OnClickListener btnRegReceiverOnClick = new View.OnClickListener() { @Override public void onClick(View v) { IntentFilter itFilter =new IntentFilter("com.android.MY_BROADCAST2"); mMyRecever2= new MyBroadcastReceiver2(); registerReceiver(mMyRecever2,itFilter); } }; private View.OnClickListener btnUnregReceiverOnClick=new View.OnClickListener() { @Override public void onClick(View v) { unregisterReceiver(mMyRecever2); } }; private View.OnClickListener btnSendBroadcast1OnClick =new View.OnClickListener() { @Override public void onClick(View v) { Intent it =new Intent("com.android.MY_BROADCAST1"); it.putExtra("semder_name","MainActivity"); sendBroadcast(it); } }; private View.OnClickListener btnSendBroadcast2OnClick =new View.OnClickListener() { @Override public void onClick(View v) { Intent it =new Intent("com.android.MY_BROADCAST2"); it.putExtra("semder_name","MainActivity"); sendBroadcast(it); } }; } <file_sep>/trywebapi/app/src/main/java/com/bluedream/user/trywebapi/json.java package com.bluedream.user.trywebapi; /** * Created by USER on 2017/12/28. */ public class json { String message; public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } } <file_sep>/googlemap/app/src/main/java/com/example/user/googlemap/MapsActivity.java package com.example.user.googlemap; import android.content.DialogInterface; import android.content.pm.PackageManager; import android.graphics.Color; import android.location.Location; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.v4.app.ActivityCompat; import android.support.v4.app.FragmentActivity; import android.support.v4.content.ContextCompat; import android.support.v7.app.AlertDialog; import android.view.View; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import com.google.android.gms.maps.CameraUpdateFactory; import com.google.android.gms.maps.GoogleMap; import com.google.android.gms.maps.LocationSource; import com.google.android.gms.maps.OnMapReadyCallback; import com.google.android.gms.maps.SupportMapFragment; import com.google.android.gms.maps.model.LatLng; import com.google.android.gms.maps.model.Marker; import com.google.android.gms.maps.model.Polyline; import com.google.android.gms.maps.model.PolylineOptions; import java.util.ArrayList; public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, LocationSource, android.location.LocationListener { protected static GoogleMap mMap; protected static Spinner mSpnLocation, spnMapType; protected static Button mbtn3dMap; protected static String[][] mLocation = { {"台北101", "25.0336110,121.5650000"}, {"中國長城", "40.0000350,119.7672800"}, {"紐約自由女神像", "40.6892490,-74.0445000"}, {"巴黎鐵塔", "48.8582220,2.2945000"}}; private SupportMapFragment mSupportMapFragment; protected static boolean mbIsZoomFirst = true; protected static Marker mMarker1, mMarker2, mMarker3, mMarker4; protected static Polyline mPolylineRoute; private final int REQUEST_PERMISSION_FOR_ACCESS_FINE_LOCATION = 100; private LocationManager mLocationMgr; private OnLocationChangedListener mLocationChangedListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_maps); mSpnLocation = (Spinner) findViewById(R.id.spnLocation); ArrayAdapter<String> arrAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item); for (int i = 0; i < mLocation.length; i++) { arrAdapter.add(mLocation[i][0]); } arrAdapter.setDropDownViewResource(android.R.layout.simple_spinner_item); mSpnLocation.setAdapter(arrAdapter); mSpnLocation.setOnItemSelectedListener(new AdapterOnitemSelect(arrAdapter.getContext())); spnMapType = (Spinner) findViewById(R.id.spnMapType); spnMapType.setOnItemSelectedListener(new adapterOnITEMClick(spnMapType.getContext())); mbtn3dMap = (Button) findViewById(R.id.btn3DMap); mbtn3dMap.setOnClickListener(new com.example.user.googlemap.Button(mbtn3dMap.getContext(), "3dmap")); mSupportMapFragment = new SupportMapFragment(); mSupportMapFragment.getMapAsync(this); getSupportFragmentManager().beginTransaction() .add(R.id.frameLayMapContainer, mSupportMapFragment) .commit(); mLocationMgr = (LocationManager) getSystemService(LOCATION_SERVICE); Button btnAddMarker = (Button) findViewById(R.id.btnAddMarker); btnAddMarker.setOnClickListener(new com.example.user.googlemap.Button(mbtn3dMap.getContext(), "btnAddMarkerOnClick")); Button btnRemoveMarker = (Button) findViewById(R.id.btnRemoveMarker); btnRemoveMarker.setOnClickListener(new com.example.user.googlemap.Button(mbtn3dMap.getContext(), "btnRemoveMarkerOnClick")); Button btnShowRoute = (Button) findViewById(R.id.btnShowRoute); btnShowRoute.setOnClickListener(new com.example.user.googlemap.Button(mbtn3dMap.getContext(), "btnShowRouteOnClick")); Button btnHideRoute = (Button) findViewById(R.id.btnHideRoute); btnHideRoute.setOnClickListener(new com.example.user.googlemap.Button(mbtn3dMap.getContext(), "btnHideRouteOnClick")); } @Override protected void onStart() { super.onStart(); // App從背景切換到前景執行,啟動定位功能。 if (mMap != null) checkLocationPermissionAndEnableLocationUpdate(true); } @Override protected void onStop() { super.onStop(); // 停止定位功能。 checkLocationPermissionAndEnableLocationUpdate(false); } @Override public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) { // 檢查收到的權限要求編號是否和我們送出的相同 if (requestCode == REQUEST_PERMISSION_FOR_ACCESS_FINE_LOCATION) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { // 再檢查一次,就會進入同意的狀態,並且順利啟動。 checkLocationPermissionAndEnableLocationUpdate(true); return; } } super.onRequestPermissionsResult(requestCode, permissions, grantResults); } private void checkLocationPermissionAndEnableLocationUpdate(boolean on) { if (ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) { // 這項功能尚未取得使用者的同意 // 開始執行徵詢使用者的流程 if (ActivityCompat.shouldShowRequestPermissionRationale( MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION)) { AlertDialog.Builder altDlgBuilder = new AlertDialog.Builder(MapsActivity.this); altDlgBuilder.setTitle("提示"); altDlgBuilder.setMessage("App需要啟動定位功能。"); altDlgBuilder.setIcon(android.R.drawable.ic_dialog_info); altDlgBuilder.setCancelable(false); altDlgBuilder.setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialogInterface, int i) { // 顯示詢問使用者是否同意功能權限的對話盒 // 使用者答覆後會執行callback方法onRequestPermissionsResult() ActivityCompat.requestPermissions(MapsActivity.this, new String[]{ android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_FOR_ACCESS_FINE_LOCATION); } }); altDlgBuilder.show(); return; } else { // 顯示詢問使用者是否同意功能權限的對話盒 // 使用者答覆後會執行callback方法onRequestPermissionsResult() ActivityCompat.requestPermissions(MapsActivity.this, new String[]{ android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_PERMISSION_FOR_ACCESS_FINE_LOCATION); return; } } // 這項功能之前已經取得使用者的同意 // 根據on參數的值,啟動或關閉定位功能 if (on) { // 如果GPS功能有開啟,優先使用GPS定位,否則使用網路定位。 if (mLocationMgr.isProviderEnabled(LocationManager.GPS_PROVIDER)) { mLocationMgr.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, (android.location.LocationListener) this); Toast.makeText(MapsActivity.this, "使用GPS定位", Toast.LENGTH_LONG) .show(); } else if (mLocationMgr.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) { mLocationMgr.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 5000, 5, (android.location.LocationListener) this); Toast.makeText(MapsActivity.this, "使用網路定位", Toast.LENGTH_LONG) .show(); } } else { mLocationMgr.removeUpdates((android.location.LocationListener) this); Toast.makeText(MapsActivity.this, "定位功能已經停用", Toast.LENGTH_LONG) .show(); } } /** * Manipulates the map once available. * This callback is triggered when the map is ready to be used. * This is where we can add markers or lines, add listeners or move the camera. In this case, * we just add a marker near Sydney, Australia. * If Google Play services is not installed on the device, the user will be prompted to install * it inside the SupportMapFragment. This method will only be triggered once the user has * installed Google Play services and returned to the app. */ @Override public void onMapReady(GoogleMap googleMap) { mMap = googleMap; mMap.setMyLocationEnabled(true); // 如果在模擬器執行,要加上這行程式碼 mMap.setLocationSource(this); // 取得上一次定位資料。 if (ContextCompat.checkSelfPermission(MapsActivity.this, android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) { Location location = mLocationMgr.getLastKnownLocation(LocationManager.GPS_PROVIDER); if (location == null) location = mLocationMgr.getLastKnownLocation(LocationManager.NETWORK_PROVIDER); if (location != null) { Toast.makeText(MapsActivity.this, "成功取得上一次定位", Toast.LENGTH_LONG).show(); onLocationChanged(location); // 更新地圖的定位。 } else Toast.makeText(MapsActivity.this, "沒有上一次定位的資料", Toast.LENGTH_LONG).show(); } // 設定Google Map的Info Window。 mMap.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() { @Override public View getInfoWindow(Marker marker) { View v = getLayoutInflater() .inflate(R.layout.map_info_window, null); TextView txtTitle = (TextView) v.findViewById(R.id.txtTitle); txtTitle.setText(marker.getTitle()); TextView txtSnippet = (TextView) v.findViewById(R.id.txtSnippet); txtSnippet.setText(marker.getSnippet()); return v; } @Override public View getInfoContents(Marker marker) { return null; } }); // 設定Info Window的OnClickListener。 mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() { @Override public void onInfoWindowClick(Marker marker) { // TODO Auto-generated method stub marker.hideInfoWindow(); } }); // 建立Polyline,並且先將它隱藏。 PolylineOptions polylineOpt = new PolylineOptions() .width(15) .color(Color.BLUE); ArrayList<LatLng> listLatLng = new ArrayList<LatLng>(); listLatLng.add(new LatLng(25.0336110, 121.5650000)); listLatLng.add(new LatLng(25.037, 121.5650000)); listLatLng.add(new LatLng(25.037, 121.5630000)); polylineOpt.addAll(listLatLng); mPolylineRoute = mMap.addPolyline(polylineOpt); mPolylineRoute.setVisible(false); } @Override public void onLocationChanged(Location location) { // 把新位置傳給Google Map的my-location layer。 if (mLocationChangedListener != null) mLocationChangedListener.onLocationChanged(location); // 移動地圖到新位置。 mMap.animateCamera(CameraUpdateFactory.newLatLng( new LatLng(location.getLatitude(), location.getLongitude()))); } @Override public void onStatusChanged(String provider, int status, Bundle extras) { String str = provider; switch (status) { case LocationProvider.OUT_OF_SERVICE: str += "定位功能無法使用"; break; case LocationProvider.TEMPORARILY_UNAVAILABLE: str += "暫時無法定位"; // GPS正在定位中時會傳入這個值。 break; } Toast.makeText(MapsActivity.this, str, Toast.LENGTH_LONG) .show(); } @Override public void onProviderEnabled(String provider) { Toast.makeText(MapsActivity.this, provider + "定位功能開啟", Toast.LENGTH_LONG).show(); checkLocationPermissionAndEnableLocationUpdate(true); } @Override public void onProviderDisabled(String provider) { Toast.makeText(MapsActivity.this, provider + "定位功能已經被關閉", Toast.LENGTH_LONG).show(); checkLocationPermissionAndEnableLocationUpdate(false); } @Override public void activate(OnLocationChangedListener onLocationChangedListener) { mLocationChangedListener = onLocationChangedListener; checkLocationPermissionAndEnableLocationUpdate(true); Toast.makeText(MapsActivity.this, "地圖的my-location layer已經啟用", Toast.LENGTH_LONG).show(); } @Override public void deactivate() { mLocationChangedListener = null; checkLocationPermissionAndEnableLocationUpdate(false); Toast.makeText(MapsActivity.this, "地圖的my-location layer已經關閉", Toast.LENGTH_LONG).show(); } } <file_sep>/DialogEdit/app/src/main/java/com/example/user/dialogedit/MainActivity.java package com.example.user.dialogedit; import android.app.Dialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Button mBtnLoginDlg; private TextView mTxtResult; private Dialog mDialogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mBtnLoginDlg=(Button)findViewById(R.id.btnLoginDlg); mTxtResult=(TextView)findViewById(R.id.txtResult); mBtnLoginDlg.setOnClickListener(btnLoginDlgOnClick); } private View.OnClickListener btnLoginDlgOnClick =new View.OnClickListener() { @Override public void onClick(View v) { mTxtResult.setText(""); mDialogin =new Dialog(MainActivity.this); mDialogin.setCancelable(false); mDialogin.setContentView(R.layout.mydlg); Button loginbtnOK =(Button)mDialogin.findViewById(R.id.btnOK); Button loginbtnCancle =(Button)mDialogin.findViewById(R.id.btnCancel); loginbtnCancle.setOnClickListener(loginDlgBtnCancelOnClick); loginbtnOK.setOnClickListener(loginDlgBtnOKOnClick); mDialogin.show(); } }; private View.OnClickListener loginDlgBtnOKOnClick = new View.OnClickListener() { public void onClick(View v) { EditText edtUserName = (EditText) mDialogin.findViewById(R.id.edtUserName); EditText edtPassword = (EditText) mDialogin.findViewById(R.id.edtPassword); mTxtResult.setText("你輸入的使用者名稱:" + edtUserName.getText().toString() + "密碼:" + edtPassword.getText().toString()); mDialogin.cancel(); } }; private View.OnClickListener loginDlgBtnCancelOnClick = new View.OnClickListener() { public void onClick(View v) { mTxtResult.setText("你按下\"取消\"按鈕"); mDialogin.cancel(); } }; } <file_sep>/Character/app/src/main/java/com/bluedream/user/character/wepon/KnifeBehavior.java package com.bluedream.user.character.wepon; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class KnifeBehavior implements WeponBehavior{ TextView textView; @Override public void usewupon(TextView textView) { textView.append("使用刀子"); } } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/quackBehavior/Quack.java package com.bluedream.user.simduck.quackBehavior; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class Quack implements quackBehavior { @Override public void quack(TextView textView) { TextView test =textView; test.append("\n Quack!"); } } <file_sep>/Character/app/src/main/java/com/bluedream/user/character/person/Knight.java package com.bluedream.user.character.person; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class Knight extends Character { public Knight(TextView textView) { super(textView); } public void display() { textView.append("\n騎士"); } } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/quackBehavior/Squack.java package com.bluedream.user.simduck.quackBehavior; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class Squack implements quackBehavior{ @Override public void quack(TextView textView) { TextView test =textView; test.append("\n Suack!"); } } <file_sep>/OptionMenu2/app/src/main/java/com/example/bluedream/optionmenu/MainActivity.java package com.example.bluedream.optionmenu; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; public class MainActivity extends AppCompatActivity { private static final int Menu_MUSIC=Menu.FIRST, Menu_Play_MUSIC=Menu.FIRST+1, Menu_Stop_Playmusc=Menu.FIRST+2, Menu_About=Menu.FIRST+3, Menu_Exit=Menu.FIRST+4; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override public boolean onCreateOptionsMenu(Menu menu) { SubMenu subMenu = menu.addSubMenu(0,Menu_MUSIC,0,"背景音樂"); subMenu.setIcon(android.R.drawable.ic_media_ff); subMenu.add(0,Menu_Play_MUSIC,0,"播放背景音樂"); subMenu.add(0,Menu_Stop_Playmusc,1,"停止播放背景音樂"); menu.add(0,Menu_About,1,"關於").setIcon(android.R.drawable.ic_dialog_info); menu.add(0,Menu_Exit,2,"結束").setIcon(android.R.drawable.ic_menu_close_clear_cancel); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case Menu_Play_MUSIC: Intent it =new Intent(MainActivity.this,MwdiaPlayService.class); startService(it); return true; case Menu_Stop_Playmusc: it =new Intent(MainActivity.this,MwdiaPlayService.class); stopService(it); return true; case Menu_About: new AlertDialog.Builder(MainActivity.this). setTitle("關於這個程式").setMessage("Example").setIcon(android.R.drawable.star_big_on).setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; case Menu_Exit: finish(); return true; } return super.onOptionsItemSelected(item); } } <file_sep>/Choosehobby/app/src/main/java/com/example/user/choosehobby/MainActivity.java package com.example.user.choosehobby; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.CheckBox; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private CheckBox music,sing,dance,travel,reading,writing,climbing,swim,exercise,fitness,photo,eating,painting; private Button mbtnok; private TextView mTxtHobby; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); music=(CheckBox)findViewById(R.id.checkBoxMusic); sing=(CheckBox)findViewById(R.id.checkBoxSing); dance=(CheckBox)findViewById(R.id.checkBoxDance); travel=(CheckBox)findViewById(R.id.checkBoxTravel); reading=(CheckBox)findViewById(R.id.checkBoxReadding); writing=(CheckBox)findViewById(R.id.checkBoxWriting); climbing=(CheckBox)findViewById(R.id.checkBoxClimb); swim=(CheckBox)findViewById(R.id.checkBoxSwim); exercise=(CheckBox)findViewById(R.id.checkBoxExcise); fitness=(CheckBox)findViewById(R.id.checkBoxFitness); photo=(CheckBox)findViewById(R.id.checkBoxPhoto); eating=(CheckBox)findViewById(R.id.checkBoxEat); painting=(CheckBox)findViewById(R.id.checkBoxPanting); mbtnok=(Button)findViewById(R.id.btnOK); mTxtHobby=(TextView)findViewById(R.id.textHobby); mbtnok.setOnClickListener(btnOKOnClick); } private View.OnClickListener btnOKOnClick = new View.OnClickListener() { @Override public void onClick(View v) { String s= getString(R.string.your_hobby); if(music.isChecked())s+=music.getText().toString(); if(sing.isChecked())s+=sing.getText().toString(); if(dance.isChecked())s+=dance.getText().toString(); if(travel.isChecked())s+=travel.getText().toString(); if(reading.isChecked())s+=reading.getText().toString(); if(writing.isChecked())s+=writing.getText().toString(); if(climbing.isChecked())s+=climbing.getText().toString(); if(swim.isChecked())s+=swim.getText().toString(); if(exercise.isChecked())s+=exercise.getText().toString(); if(fitness.isChecked())s+=fitness.getText().toString(); if(photo.isChecked())s+=photo.getText().toString(); if(eating.isChecked())s+=eating.getText().toString(); if(painting.isChecked())s+=painting.getText().toString(); mTxtHobby.setText(s); } }; } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/MainActivity.java package com.bluedream.user.simduck; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.TextView; import com.bluedream.user.simduck.fjyBehavior.FlyRocket; import com.bluedream.user.simduck.quackBehavior.Squack; public class MainActivity extends AppCompatActivity { TextView text; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); text=(TextView)findViewById(R.id.textview); Duck Mallard =new MallardDuck(text); Mallard.display(); Mallard.PerformFly(); Mallard.PerformQuack(); Duck ModelWithRocket =new ModeDuck(text); ModelWithRocket.display(); ModelWithRocket.setFlyBehavior(new FlyRocket()); ModelWithRocket.PerformFly(); DuckCall DuckCall =new DuckCall(text); DuckCall.display(); DuckCall.setquackBehavior(new Squack()) ; DuckCall.PerformQuack(); } } <file_sep>/trivalshow/app/src/main/java/com/bluedream/user/trivalshow/intro.java package com.bluedream.user.trivalshow; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.TextView; import com.google.android.gms.maps.GoogleMap; import butterknife.BindView; import butterknife.ButterKnife; import butterknife.OnClick; public class intro extends AppCompatActivity { @BindView(R.id.titleName) TextView titleName; @BindView(R.id.address) TextView Address; @BindView(R.id.opentime) TextView opentime; @BindView(R.id.intro) TextView Intro; @BindView(R.id.back) Button back; @BindView(R.id.Mapbutton) Button Mapbutton; private GoogleMap map; String name; String intro; String address; String openTime; Double longitude; Double latitude; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_intro); ButterKnife.bind(this); getbundle(); setText(); } private void getbundle() { Bundle bundle = getIntent().getExtras(); name = bundle.getString("name"); intro = bundle.getString("Intro"); address = bundle.getString("Address"); openTime = bundle.getString("OpenTime"); longitude = Double.valueOf(bundle.getString("Longitude")); latitude = Double.valueOf(bundle.getString("Latitude")); } private void setText() { titleName.setText(name); Address.append(address); opentime.append("\n"+openTime); Intro.append("\n"+intro); } @OnClick(R.id.back) public void onbackViewClicked() { finish(); } @OnClick(R.id.Mapbutton) public void MapbuttononViewClicked() { Intent it=new Intent(); it.setClass(intro.this,MapsActivity.class); Bundle bundle=new Bundle(); bundle.putDouble("longitude",longitude); bundle.putDouble("latitude",latitude); bundle.putString("name",name); it.putExtras(bundle); startActivity(it); } } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/fjyBehavior/FlyRocket.java package com.bluedream.user.simduck.fjyBehavior; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class FlyRocket implements flyBehavior { @Override public void fly(TextView textView) { textView.append("\n裝備火箭推進器!"); } } <file_sep>/GITHUBAPI/app/src/main/java/com/bluedream/user/githubapi/MainActivity.java package com.bluedream.user.githubapi; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.TextView; import java.io.IOException; import okhttp3.Call; import okhttp3.Callback; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; public class MainActivity extends AppCompatActivity { TextView AAA; String SSS; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AAA=(TextView) findViewById(R.id.ssss); OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .url("http://2016.cec.gov.tw/opendata/api/proofreadercanrpt/json") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { } @Override public void onResponse(Call call, Response response) throws IOException { SSS=response.body().string(); runOnUiThread(new Runnable() { @Override public void run() { AAA.setText(SSS); } }); } }); } } <file_sep>/trivalshow/app/src/main/java/com/bluedream/user/trivalshow/MainActivity.java package com.bluedream.user.trivalshow; import android.content.Intent; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.Spinner; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import butterknife.BindView; import butterknife.ButterKnife; import okhttp3.Call; import okhttp3.Callback; import okhttp3.MediaType; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.Response; @SuppressWarnings("Since15") public class MainActivity extends AppCompatActivity { @BindView(R.id.listview) ListView listview; public static final MediaType JSON = MediaType.parse("application/json; charset=utf-8"); String ResultJson = null; JSONObject responseJSON; ArrayList<museum> museumclass = new ArrayList<museum>(); ArrayList<museum> querymuseumclass = new ArrayList<museum>(); ArrayList<String> name = new ArrayList<String>(); ArrayList<String> queryname = new ArrayList<String>(); Set<String> Setcityname = new HashSet<String>(); ArrayList<String> ACname = new ArrayList<String>(); @BindView(R.id.spinner) Spinner spinner; ArrayAdapter<String> spinerAdapter; ArrayAdapter<String> arrayAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); ButterKnife.bind(this); OKhttp(); listviewclick(); spinerselect(); } private void OKhttp() { OkHttpClient client = new OkHttpClient(); final Request request = new Request.Builder() .url("https://cloud.culture.tw/frontsite/trans/emapOpenDataAction.do?method=exportEmapJsonByMainType&mainType=10") .build(); Call call = client.newCall(request); call.enqueue(new Callback() { @Override public void onFailure(Call call, IOException e) { Toast.makeText(MainActivity.this, "網路下載失敗", Toast.LENGTH_LONG).show(); } @Override public void onResponse(Call call, final Response response) throws IOException { ResultJson = response.body().string(); try { JSONArray array = new JSONArray(ResultJson); for (int i = 0; i < array.length(); i++) { JSONObject obj = array.getJSONObject(i); String name = obj.getString("name"); String intro = obj.getString("intro"); String address = obj.getString("address"); String openTime = obj.getString("openTime"); String longitude = obj.getString("longitude"); String latitude = obj.getString("latitude"); String cityname = obj.getString("cityName"); museum m = new museum(name, intro, address, openTime, longitude, latitude, cityname); museumclass.add(m); } } catch (JSONException e) { e.printStackTrace(); } update(); } }); } private void update() { runOnUiThread(new Runnable() { @Override public void run() { for (int i = 0; i < museumclass.size(); i++) { Setcityname.add(museumclass.get(i).getCityName()); } ACname.addAll(Setcityname); spinerAdapter = new ArrayAdapter<String>( MainActivity.this, android.R.layout.simple_spinner_item, ACname); spinner.setAdapter(spinerAdapter); } }); } private void updatequery() { runOnUiThread(new Runnable() { @Override public void run() { queryname.clear(); for (int i = 0; i < querymuseumclass.size(); i++) { queryname.add(querymuseumclass.get(i).getName()); } arrayAdapter = new ArrayAdapter<String>( MainActivity.this, android.R.layout.simple_list_item_1, queryname); listview.setAdapter(arrayAdapter); } }); } private void listviewclick() { listview.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Intent it = new Intent(); it.setClass(MainActivity.this, intro.class); Bundle bundle = new Bundle(); bundle.putString("name", querymuseumclass.get(position).getName()); bundle.putString("Intro", querymuseumclass.get(position).getIntro()); bundle.putString("Address", querymuseumclass.get(position).getAddress()); bundle.putString("OpenTime", querymuseumclass.get(position).getOpenTime()); bundle.putString("Latitude", querymuseumclass.get(position).getLatitude()); bundle.putString("Longitude", querymuseumclass.get(position).getLongitude()); it.putExtras(bundle); startActivity(it); } }); } protected void spinerselect() { spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { querymuseumclass.clear(); String CN =spinerAdapter.getItem(position).toString(); for(int i=0;i<museumclass.size();i++) { if(museumclass.get(i).getCityName().equals(CN)) { querymuseumclass.add(museumclass.get(i)); } } updatequery(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }); } }<file_sep>/ContentMenu/app/src/main/java/com/example/bluedream/contentmenu/MwdiaPlayService.java package com.example.bluedream.contentmenu; import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.IBinder; import android.support.annotation.Nullable; /** * Created by BlueDream on 2017/11/13. */ public class MwdiaPlayService extends Service { private MediaPlayer player; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int onStartCommand(Intent intent, int flags, int startId) { //Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory().getPath()+"/song.mp3")); String Path = "android.resource://"+getPackageName()+"/"+R.raw.song; Uri uri = Uri.parse(Path); player=MediaPlayer.create(this,uri); player.start(); return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); player.stop(); } }<file_sep>/Character/app/src/main/java/com/bluedream/user/character/wepon/AxeBehavior.java package com.bluedream.user.character.wepon; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class AxeBehavior implements WeponBehavior { TextView textView; @Override public void usewupon(TextView textView) { textView.append("使用斧"); } } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/DuckCall.java package com.bluedream.user.simduck; import android.widget.TextView; import com.bluedream.user.simduck.quackBehavior.MuteQuack; import com.bluedream.user.simduck.quackBehavior.quackBehavior; /** * Created by USER on 2018/1/8. */ public class DuckCall { TextView textView; quackBehavior quackBehavior; public DuckCall(TextView textView) { this.textView = textView; quackBehavior =new MuteQuack(); } public void setquackBehavior(quackBehavior qb) { quackBehavior = qb; } public void PerformQuack () { quackBehavior.quack(textView); } public void display () { textView.append("\n 這是個鴨鳴器 不是鴨子"); } } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/fjyBehavior/FlyWithWing.java package com.bluedream.user.simduck.fjyBehavior; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public class FlyWithWing implements flyBehavior { @Override public void fly(TextView textView) { TextView test = textView; test.append("\nI Am Fly"); } } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/quackBehavior/quackBehavior.java package com.bluedream.user.simduck.quackBehavior; import android.widget.TextView; /** * Created by USER on 2018/1/8. */ public interface quackBehavior { public void quack (TextView textView); } <file_sep>/actionbar/app/src/main/java/com/example/bluedream/actionbar/MainActivity.java package com.example.bluedream.actionbar; import android.content.res.Configuration; import android.graphics.drawable.ColorDrawable; import android.support.annotation.Nullable; import android.support.v4.widget.DrawerLayout; import android.support.v7.app.ActionBar; import android.support.v7.app.ActionBarDrawerToggle; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.content.DialogInterface; import android.content.Intent; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.ContextMenu; import android.view.Menu; import android.view.MenuItem; import android.view.SubMenu; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.SearchView; import android.widget.Spinner; import android.widget.TextView; import android.widget.Toast; import java.util.List; public class MainActivity extends AppCompatActivity { private RelativeLayout mRelativeLayout; private TextView mTxtView; private DrawerLayout mDrawerLayout; private ActionBarDrawerToggle mActionBarDrawerToggle; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mRelativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout); registerForContextMenu(mRelativeLayout); mTxtView = (TextView) findViewById(R.id.txtView); registerForContextMenu(mTxtView); //actionBar ActionBar actBar = getSupportActionBar(); actBar.setDisplayShowTitleEnabled(false); actBar.setLogo(R.drawable.app_logo); actBar.setDisplayUseLogoEnabled(true); actBar.setDisplayShowHomeEnabled(true); actBar.setBackgroundDrawable(new ColorDrawable(0xFF505050)); actBar.setDisplayHomeAsUpEnabled(true); actBar.setHomeButtonEnabled(true); //drawlayout mDrawerLayout =(DrawerLayout)findViewById(R.id.DrawerLayout); mActionBarDrawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,R.string.app_name,R.string.app_name); mActionBarDrawerToggle.setDrawerIndicatorEnabled(true); mDrawerLayout.addDrawerListener(mActionBarDrawerToggle); ListView mlistView=(ListView)findViewById(R.id.listview); ListView mlistView2=(ListView)findViewById(R.id.listview2); ArrayAdapter<CharSequence>adaapRegionList=ArrayAdapter.createFromResource(this,R.array.spnRegionList,android.R.layout.simple_list_item_1); mlistView.setAdapter(adaapRegionList); mlistView2.setAdapter(adaapRegionList); mlistView.setOnItemClickListener(listViewOnItemClick); mlistView2.setOnItemClickListener(listViewOnItemClick); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.menu_main,menu); Spinner spnRegion =(Spinner)menu.findItem(R.id.menuItemRegion).getActionView().findViewById(R.id.spnRegion); ArrayAdapter<CharSequence>adaapRegionList=ArrayAdapter.createFromResource(this,R.array.spnRegionList,android.R.layout.simple_spinner_item); spnRegion.setAdapter(adaapRegionList); spnRegion.setOnItemSelectedListener(spnRegionOnItemSelected); SearchView searchView = (SearchView) menu.findItem(R.id.menuItemSearch).getActionView(); searchView.setOnQueryTextListener(searchViewOnQueryTextLis); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case R.id.menuItemPlayBackgroundMusic: Intent it =new Intent(MainActivity.this,MwdiaPlayService.class); startService(it); return true; case R.id.menuItemStopBackgroundMusic: it =new Intent(MainActivity.this,MwdiaPlayService.class); stopService(it); return true; case R.id.menuItemAbout: new AlertDialog.Builder(MainActivity.this). setTitle("關於這個程式").setMessage("Example").setIcon(android.R.drawable.star_big_on).setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }).show(); return true; case R.id.menuItemExit: finish(); return true; case R.id.menuItemRegion: new AlertDialog.Builder(MainActivity.this) .setTitle("選擇地區") .setMessage("這是選擇地區對話盒") .setCancelable(false) .setIcon(android.R.drawable.star_big_on) .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); return true; case R.id.menuItemSearch: new AlertDialog.Builder(MainActivity.this) .setTitle("搜尋") .setMessage("這是搜尋對話盒") .setCancelable(false) .setIcon(android.R.drawable.star_big_on) .setPositiveButton("確定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .show(); return true; } if(mActionBarDrawerToggle.onOptionsItemSelected(item)) { return true; } return super.onOptionsItemSelected(item); } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(v==mRelativeLayout) { if (menu.size() == 0) { getMenuInflater().inflate(R.menu.menu_main,menu); } } } @Override public boolean onContextItemSelected(MenuItem item) { onOptionsItemSelected(item); return super.onContextItemSelected(item); } private Spinner.OnItemSelectedListener spnRegionOnItemSelected= new Spinner.OnItemSelectedListener() { @Override public void onItemSelected(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this,parent.getSelectedItem().toString(),Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView<?> parent) { } }; private SearchView.OnQueryTextListener searchViewOnQueryTextLis = new SearchView.OnQueryTextListener() { @Override public boolean onQueryTextChange(String newText) { return false; } @Override public boolean onQueryTextSubmit(String query) { Toast.makeText(MainActivity.this, query, Toast.LENGTH_LONG).show(); return true; } }; @Override protected void onPostCreate(@Nullable Bundle savedInstanceState) { super.onPostCreate(savedInstanceState); mActionBarDrawerToggle.syncState(); } @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); mActionBarDrawerToggle.onConfigurationChanged(newConfig); } private AdapterView.OnItemClickListener listViewOnItemClick =new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Toast.makeText(MainActivity.this,((TextView)view).getText(),Toast.LENGTH_SHORT).show(); mDrawerLayout.closeDrawers(); } }; } <file_sep>/SimDuck/app/src/main/java/com/bluedream/user/simduck/ModeDuck.java package com.bluedream.user.simduck; import android.widget.TextView; import com.bluedream.user.simduck.fjyBehavior.FlyNoWay; import com.bluedream.user.simduck.quackBehavior.Quack; /** * Created by USER on 2018/1/8. */ public class ModeDuck extends Duck { public ModeDuck(TextView textView) { super(textView); flyBehavior =new FlyNoWay(); quackBehavior =new Quack(); } @Override public void display() { textView.append("\n模型鴨子"); } }
87694e2aa26f8d88e25284c72bf5ff7e9b2efa3c
[ "Java" ]
25
Java
grape31417/Learning-Android
3448414b0f9657e9ce2640a5372195f3acdacaa5
278101f8e190d26cfcd329e0cba0785e35dc108e
refs/heads/master
<file_sep>运行环境:Win10 - Visual Studio 2017 <br /> 【如果使用DEVC++运行该代码, 请将第33行的system("puase")删去。】 <br /> If you use DevC++, please delete 'system("pause")' in the 33th line. <file_sep>#include <iostream> #include <time.h> #include <stdlib.h> #define MAX 100 int main() { int n = 0, m = 0; srand((unsigned)time(NULL)); std::cout << "总人数:"; std::cin >> n; std::cout << "筛选人数:"; std::cin >> m; int a[MAX]; int a_length = 0; for (int i = 0; i < m; i++) { int found = 0; int temp = (rand() % n) + 1; for (int j = 0; j < a_length; j++) if (a[j] == temp) { i--; found = 1; break; } if (found == 1) continue; a[a_length++] = temp; } for (int i = 0; i < a_length; i++) std::cout << a[i] << " "; system("pause"); //in DevC++, you should delete this line return 0; }
c59de1a4883870aa01832c3232be5ccfbafabf1c
[ "Markdown", "C++" ]
2
Markdown
qw2002q/Pseudo-random-number
98c6ab82e6621878262087f1e860dc416d887762
de295340cc9f9b36f791050e1f93c2aed9e23491
refs/heads/master
<repo_name>ZinkNotTheMetal/AngularAspCore<file_sep>/AngularWithCars.Api/src/AngularWithCars.Api/Responses/Manufacturer.cs using System; namespace AngularWithCars.Api.Responses { public class Manufacturer { public int Id { get; set; } public string Name { get; set; } public DateTime DateFounded { get; set; } public string NyseStockSymbol { get; set; } public bool IsSubsidiary { get; set; } } }<file_sep>/AngularWithCars.Angular/src/AngularWithCars.Angular/Startup.cs using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; namespace AngularWithCars.Angular { public class Startup { private readonly IHostingEnvironment _environment; private IConfigurationRoot _config; public Startup(IHostingEnvironment environment) { _environment = environment; var configBuilder = new ConfigurationBuilder() .SetBasePath(_environment.ContentRootPath) .AddJsonFile("config.json") .AddEnvironmentVariables(); _config = configBuilder.Build(); } // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //due to constructor you now can do //if (_environment.IsDevelopment()) { } //For similar to Structure Map //services.AddTransient<IMailService, IDebugMailService>(); //Reuse the IMail service where possible but only within a single request //services.AddScoped<IMailService, IDebugMailService>(); services.AddSingleton(_config); services.AddMvc(); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, ILoggerFactory logger) { if (_environment.IsDevelopment()) { app.UseDeveloperExceptionPage(); logger.AddDebug(LogLevel.Information); } else { logger.AddDebug(LogLevel.Warning); } app.UseMvc(config => { config.MapRoute( name: "Default", template: "{controller}/{action}/{id?}", defaults: new {controller = "Home", action = "Index"}); }); app.UseStaticFiles(); } } }<file_sep>/AngularWithCars.Api/src/AngularWithCars.Api/Controllers/ModelsController.cs using System.Collections.Generic; using System.Linq; using AngularWithCars.Api.Responses; using Microsoft.AspNetCore.Mvc; namespace AngularWithCars.Api.Controllers { [Route("api/[controller]")] public class ModelsController : Controller { private readonly List<Model> _models = new List<Model> { new Model { Id = 1000, ManufacturerId = 1, Name = "Civic" }, new Model { Id = 1001, ManufacturerId = 1, Name = "Accord" }, new Model { Id = 1002, ManufacturerId = 2, Name = "F-Type" }, new Model { Id = 1003, ManufacturerId = 2, Name = "XJ" }, new Model { Id = 1004, ManufacturerId = 2, Name = "XE" }, new Model { Id = 1005, ManufacturerId = 3, Name = "428i" }, new Model { Id = 1006, ManufacturerId = 3, Name = "435i" }, new Model { Id = 1007, ManufacturerId = 3, Name = "M4" } }; [HttpGet] [Produces(typeof(List<Model>))] public IActionResult Get() { return Ok(_models); } [HttpGet("{manufacturerId:int}")] public IActionResult GetByManufacturerId(int manufacturerId) { var result = _models.Where(m => m.ManufacturerId == manufacturerId); return result.Any() ? (IActionResult)Ok(result) : NotFound(); } } }<file_sep>/AngularWithCars.Angular/src/AngularWithCars.Angular/Controllers/HomeController.cs using AngularWithCars.Angular.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Logging; namespace AngularWithCars.Angular.Controllers { public class HomeController : Controller { private readonly IConfigurationRoot _config; private readonly ILogger<HomeController> _logger; public HomeController(IConfigurationRoot config, ILogger<HomeController> logger) { _config = config; _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Contact() { return View(); } [HttpPost] public IActionResult Contact(ContactModel model) { var test = _config["MailSettings:ToAddress"]; if (ModelState.IsValid) { ModelState.Clear(); return View(); } _logger.LogInformation("Failed to pass in valid data"); return View(); } } } <file_sep>/README.md # AngularAspCore Angular App with Asp.Net Core Web Api <file_sep>/AngularWithCars.Angular/src/AngularWithCars.Angular/wwwroot/js/app-home.js //app-home.js (function () { "use strict"; //[] - dependencies, currently we don't have any //Creating the module angular.module("app-home", []); })();<file_sep>/AngularWithCars.Api/src/AngularWithCars.Api/Controllers/ManufacturersController.cs using System; using System.Collections.Generic; using System.Linq; using AngularWithCars.Api.Responses; using Microsoft.AspNetCore.Mvc; namespace AngularWithCars.Api.Controllers { [Route("api/[controller]")] public class ManufacturersController : Controller { private readonly List<Manufacturer> _manfacturers = new List<Manufacturer> { new Manufacturer { Id = 1, Name = "Honda", DateFounded = DateTime.Parse("10/01/1946"), NyseStockSymbol = "HMC", IsSubsidiary = false }, new Manufacturer { Id = 2, Name = "Jaguar", DateFounded = DateTime.Parse("09/02/1922"), NyseStockSymbol = "TTM", IsSubsidiary = true }, new Manufacturer { Id = 3, Name = "BMW", DateFounded = DateTime.Parse("03/07/1916"), NyseStockSymbol = null, IsSubsidiary = false } }; [HttpGet] [Produces(typeof(List<Manufacturer>))] public IActionResult Get() { return Ok(_manfacturers); } [HttpGet("{id}")] public IActionResult Get(int id) { var result = _manfacturers.FirstOrDefault(m => m.Id == id); return result != null ? (IActionResult)Ok(result) : NotFound(); } } }
6596c9cdcff6191f2d27004c167308cfaf946a8d
[ "Markdown", "C#", "JavaScript" ]
7
C#
ZinkNotTheMetal/AngularAspCore
25d0106f622111322a9a8420bf0b5eb6f9a52582
af15a4222ce9bc41617c2a0e5624074d428ad149
refs/heads/master
<file_sep>Javascript-eval widget for Jupyter. Security considerations ----------------------- Don't use this in an environment with untrusted notebooks. This means that this widget probably should not be made available in public Jupyter deployments. Jupyterlab generally does not encourage sending arbitrary javascript to widgets in order to prevent adversarial notebooks from arbitrarily manipulating the browser. Use cases --------- This package can be, in general, be used to instantiate widgets where the render code is generated in the notebook itself. I personally use this widget in order to instantiate arbitrary Elm widgets from notebooks in a trusted environment (an internal deployment of Jupyterlab). Package Install --------------- This package is not published and not generally maintained. Thus, installation is from source. If anyone would like to properly maintain the package, feel free to fork it. **Prerequisites** - [node](http://nodejs.org/) ```bash npm install --save jupyter-javascript-eval-widget ``` <file_sep>var widgets = require('@jupyter-widgets/base'); var _ = require('lodash'); var JavascriptEvalModel = widgets.DOMWidgetModel.extend({ defaults: _.extend(widgets.DOMWidgetModel.prototype.defaults(), { _model_name : 'JavascriptEvalModel', _view_name : 'JavascriptEvalView', _model_module : 'jupyter-javascript-eval-widget', _view_module : 'jupyter-javascript-eval-widget', _model_module_version : '0.1.0', _view_module_version : '0.1.0', javascript_code : 'alert("No javascript code present"); return { error: "No javascript code present" }' }), initialize: function(attributes, options) { 'use strict'; JavascriptEvalModel.__super__.initialize.apply(this, arguments); this.eval_result = (new Function('model', this.get('javascript_code')))(this); } }); var JavascriptEvalView = widgets.DOMWidgetView.extend({ render: function() { if (this.model.eval_result instanceof Node) { this.el.appendChild(this.model.eval_result); }; } }); module.exports = { JavascriptEvalModel : JavascriptEvalModel, JavascriptEvalView : JavascriptEvalView };
6981568acd52e165ca06678db42c4f0436d4e0a3
[ "Markdown", "JavaScript" ]
2
Markdown
rehno-lindeque/jupyter-javascript-eval-widget
fd1c152042f8f89acbb02efa6b8babb5ecb21b96
f8a751ac3d8759192b391ff17da899bf10747cbe
refs/heads/master
<repo_name>goazman/MovieKidia<file_sep>/components/Homepage.js import React from 'react' import { StyleSheet, View, TouchableOpacity, ImageBackground, SafeAreaView } from 'react-native'; import { Text } from 'react-native-elements'; import { LinearGradient } from 'expo-linear-gradient'; export default function HomePage({navigation}) { return ( <SafeAreaView style={{flex:1}}> <ImageBackground style={styles.main_container} resizeMode= "stretch" source={require("../assets/homepage.jpg")}> <TouchableOpacity onPress={() => navigation.navigate("Search")}> <View style={styles.HomeTitle}> <LinearGradient style={styles.button} colors={['#057ea8',"#0fbcf9",'#057ea8']} locations={[0.8, 0.5, 0.8]}> <Text h2 h2Style={{color:"#fff7d9", textAlign:"center"}}>Entrance</Text> </LinearGradient> </View> </TouchableOpacity> </ImageBackground> </SafeAreaView> ) } const styles = StyleSheet.create({ main_container: { flex:1, alignItems: 'center', justifyContent: 'center', backgroundColor: "#ffdd59" }, HomeTitle: { alignItems: "center", justifyContent: "center", marginTop: 180, shadowColor: "#3c40c6", shadowOpacity: 0.7, shadowRadius: 12, shadowOffset : { width: 2, height: 6} }, button: { borderRadius: 15, width: 160, height: 55, textAlign: "center", padding: 3 } }) <file_sep>/components/filmDetails.js import React, {useState, useEffect} from 'react'; import { useRoute } from '@react-navigation/native'; import { StyleSheet, View, ActivityIndicator, ScrollView, Image, Text, TouchableOpacity } from 'react-native'; import moment from 'moment'; import numeral from 'numeral'; import { FontAwesome } from '@expo/vector-icons'; import { getFilmsDetailsFromApi, getImageFromApi } from "../API/TMDBApi"; import { connect } from 'react-redux'; function FilmDetails(props) { //From Search.js Navigation Route to API call const route = useRoute(); const filmId = route.params.idFilm; const [isLoading, setIsLoading] = useState(true); const [dataDetailsFilm, setDataDetailsFilm] = useState(); useEffect ( () => { async function loadDetails() { var result = await getFilmsDetailsFromApi(filmId).then(data =>{ setDataDetailsFilm(data); setIsLoading(false); }); } loadDetails() },[]); // console.log(props.favoritesFilm); // Icone d'indication de chargement de la liste var displayLoading = () => { if(isLoading) { return ( <View style={styles.loading_container}> <ActivityIndicator size="large" color="#3c40c6" /> </View> ) } } // Ajout ou suppression des favoris = mapDispatchToProps var toggleFavorite = () => { const action = { type: "TOGGLE_FAVORITE", value: dataDetailsFilm }; props.dispatch(action) // console.log(action); } // Modification état Icone favoris var displayFavoriteIcon = () =>{ var favoritesFilm = props.favoritesFilm; var favIcon = <FontAwesome name="heart-o" size={32} color="#0fbcf9"/>; if (favoritesFilm.findIndex(item => item.id === dataDetailsFilm.id)!== -1) { favIcon = <FontAwesome name="heart" size={32} color="#0fbcf9"/>; } return (favIcon) } // UI design view var displayFilms = () => { if(dataDetailsFilm != undefined) { return( <ScrollView style={styles.scroll_container}> <Image style={styles.image} source={{uri: getImageFromApi(dataDetailsFilm.backdrop_path)}} /> <Text style={styles.title}>{dataDetailsFilm.title}</Text> <TouchableOpacity style={styles.heartIcon} onPress={() => toggleFavorite()}> {displayFavoriteIcon()} </TouchableOpacity> <Text style={styles.overview}>{dataDetailsFilm.overview}</Text> <Text style={styles.details}>Sorti le : {moment(dataDetailsFilm.release_date).format("DD/MM/YYYY")}</Text> <Text style={styles.details}>Note : {dataDetailsFilm.vote_average} /10</Text> <Text style={styles.details}>Nombre de votes : {dataDetailsFilm.vote_count}</Text> <Text style={styles.details}>Budget : {numeral(dataDetailsFilm.budget).format("0,0[.]00 $")}</Text> <Text style={styles.details}>Genres : {dataDetailsFilm.genres.map(function(genre){return genre.name;}).join(" / ")}</Text> <Text style={styles.details}>Distribution : {dataDetailsFilm.production_companies.map(function(brand){return brand.name;}).join(" / ")}</Text> </ScrollView> ) } } // Render view // console.log(props); return( <View style={styles.main_container}> {displayLoading()} {displayFilms()} </View> ) } const styles = StyleSheet.create({ main_container: { flex: 1 }, loading_container: { position: 'absolute', left: 0, right: 0, top: 0, bottom: 0, alignItems: 'center', justifyContent: 'center' }, scroll_container: { flex: 1, width: "100%" }, title: { flex: 1, fontWeight: "bold", fontSize: 35, color: "#3c40c6", textAlign: "center", margin: 10 }, image: { height: 200, margin: 5 }, overview: { flex: 1, fontSize: 16, textAlign:"justify", lineHeight: 25, marginLeft: 10, marginRight: 10, marginBottom: 20 }, details: { flex: 1, fontSize: 14, fontStyle: "italic", marginTop: 10, marginLeft: 10, marginRight: 10 }, heartIcon: { flex: 1, alignItems: "center", marginBottom: 5 } }) // Parametre state = state global donc dans Props de Filmdetails => accès au state de l'application et donc aux films favoris function mapStateToProps(state) { return { favoritesFilm: state.favoritesFilm } } export default connect(mapStateToProps)(FilmDetails);<file_sep>/Navigation/Navigation.js import React from 'react'; import { createStackNavigator } from '@react-navigation/stack'; import { createBottomTabNavigator } from '@react-navigation/bottom-tabs'; import HomePage from "../components/Homepage"; import Search from "../components/Search"; import FilmDetails from "../components/filmDetails"; import Favorites from "../components/favorites"; import { FontAwesome } from '@expo/vector-icons'; const Stack = createStackNavigator(); function HomeStack() { return( <Stack.Navigator headerMode="screen" initialRouteName="HomePage" screenOptions={{ headerTintColor: '#3c40c6', headerStyle: { backgroundColor: '#0fbcf9', height:100} }} > <Stack.Screen name="HomePage" component={HomePage} options={{title: "Accueil", headerShown: false}}/> <Stack.Screen name="Search" component={Search} options={{title: "Rechercher des films"}}/> <Stack.Screen name="FilmDetails" component={FilmDetails} options={{title: "Détail du film"}}/> </Stack.Navigator> ); } function NavStack() { return( <Stack.Navigator headerMode="screen" screenOptions={{ headerTintColor: '#3c40c6', headerStyle: { backgroundColor: '#0fbcf9', height:100}, }} > <Stack.Screen name="Favoris" component={Favorites} options={{title: "Mes favoris"}}/> <Stack.Screen name="FilmDetails" component={FilmDetails} options={{title: "Détail du film"}}/> </Stack.Navigator> ); } const Tab = createBottomTabNavigator(); function NavBottomTab() { return ( <Tab.Navigator tabBarOptions={{ activeTintColor: 'white', inactiveTintColor: 'black', activeBackgroundColor: "#0fbcf9", inactiveBackgroundColor: "white", showLabel: true, showIcon: true, labelStyle: { fontSize: 15 } }} > <Tab.Screen name="Search" component={HomeStack} options={{ tabBarIcon: ({ color, size }) => (<FontAwesome name="search" color="#3c40c6" size={21}/>), }}/> <Tab.Screen name="Favoris" component={NavStack} options={{ tabBarIcon: ({ color, size }) => (<FontAwesome name="heart" color="#3c40c6" size={21}/>), tabBarBadge: 3 }}/> </Tab.Navigator> ); } export default NavBottomTab;
6a220baef947739de12e028798578e3c3f862ea5
[ "JavaScript" ]
3
JavaScript
goazman/MovieKidia
2f8213e7d55fd9c400e87093d9e3684740cca6c5
b27887bfbae4fa806861a0b04618240bba8c168c
refs/heads/master
<repo_name>bdsoftpro/kamailio-setup<file_sep>/setup-rtpengine #!/bin/bash # find text from all file in directory # grep -rnw '/path/to/somewhere/' -e 'pattern' set -e SRCPATH="$PWD" KAMBASE=/usr/local RTPBASE=/usr mkdir -p script cd script apt-get -y update # apt-get -y install gcc flex bison libunistring-dev libssl-dev libcurl4-openssl-dev libxml2-dev libpcre3-dev build-essential debhelper default-libmysqlclient-dev gperf iptables-dev libavcodec-dev libavfilter-dev libavformat-dev libavutil-dev libbencode-perl libcrypt-openssl-rsa-perl libcrypt-rijndael-perl libhiredis-dev libio-multiplex-perl libio-socket-inet6-perl libjson-glib-dev libdigest-crc-perl libdigest-hmac-perl libnet-interface-perl libnet-interface-perl libssl-dev libsystemd-dev libxmlrpc-core-c3-dev libcurl4-openssl-dev libevent-dev libpcap0.8-dev markdown unzip nfs-common dkms libspandsp-dev apt-get -y install gcc flex bison libunistring-dev libssl-dev libcurl4-openssl-dev libxml2-dev libpcre3-dev build-essential debhelper default-libmysqlclient-dev gperf iptables-dev libavcodec-dev libavfilter-dev libavformat-dev libavutil-dev libjson-glib-dev libssl-dev libsystemd-dev libxmlrpc-core-c3-dev libcurl4-openssl-dev libevent-dev libpcap0.8-dev markdown unzip nfs-common dkms libspandsp-dev libgeoip-dev libcryptsetup-dev libjansson-dev libjson-c-dev libjsoncpp-dev libexpat1-dev if [ ! -f /etc/init.d/mysql* ]; then apt-get -y install mysql-server libmysqlclient-dev systemctl start mysql systemctl enable mysql else systemctl restart mysql fi if [ ! -d WEBRTC ]; then git clone https://github.com/havfo/WEBRTC-to-SIP.git WEBRTC cd WEBRTC echo "=====================================================" echo echo " Please Fillup Right Information" echo echo "=====================================================" echo read -p "Sip IP (IPv4) : " ipv4 read -p "Sip IP (IPv6) : " ipv6 read -p "Domain Name : " dname echo find . -type f -print0 | xargs -0 sed -i "s/XXXXXX-XXXXXX/${ipv6}/g" find . -type f -print0 | xargs -0 sed -i "s/XXXXX-XXXXX/${ipv4}/g" find . -type f -print0 | xargs -0 sed -i "s/XXXX-XXXX/${dname}/g" cd ../ fi if [ ! -f /etc/init.d/ngcp-rtpengine-daemon ]; then wget -c https://github.com/sipwise/rtpengine/archive/mr6.5.7.4.tar.gz -O - | tar -xz cd rtpengine* VER=1.0.4 curl https://codeload.github.com/BelledonneCommunications/bcg729/tar.gz/$VER >bcg729_$VER.orig.tar.gz tar zxf bcg729_$VER.orig.tar.gz cd bcg729-$VER git clone https://github.com/ossobv/bcg729-deb.git debian dpkg-buildpackage -us -uc -sa cd ../ dpkg -i libbcg729-*.deb dpkg-buildpackage cd ../ dpkg -i ngcp-rtpengine-daemon_*.deb ngcp-rtpengine-iptables_*.deb ngcp-rtpengine-kernel-dkms_*.deb cat >/etc/default/ngcp-rtpengine-daemon <<EOF RUN_RTPENGINE=yes CONFIG_FILE=/etc/rtpengine/rtpengine.conf # CONFIG_SECTION=rtpengine PIDFILE=/run/ngcp-rtpengine-daemon.pid MANAGE_IPTABLES=yes TABLE=0 #SET_USER=root #SET_GROUP=root # GROUP only needs to be set if USER is not set or if the user isn't in the group EOF read -p "Press enter to continue" echo "$PWD" cp WEBRTC/etc/rtpengine/rtpengine.conf /etc/rtpengine/ read -p "Press enter to continue" /etc/init.d/ngcp-rtpengine-daemon restart fi if [ ! -f /etc/init.d/kamailio* ]; then wget -c https://github.com/kamailio/kamailio/archive/5.3.2.tar.gz -O - | tar -xz cd kamailio* make include_modules="acc_json auth_ephemeral auth_identity cdp cdp_avp cnxcc cplc crypto db_mysql dialplan geoip gzcompress http_async_client http_client ims_auth ims_charging ims_dialog ims_diameter_server ims_icscf ims_isc ims_ocs ims_qos ims_registrar_pcscf ims_registrar_scscf ims_usrloc_pcscf json jansson janssonrpcc jsonrpcc lcr log_systemd lost memcached outbound presence presence_conference presence_dialoginfo presence_mwi presence_profile presence_reginfo presence_xml regex rls tls utils websocket xcap_client xcap_server xhttp_pi xmlops xmlrpc xmpp" cfg make Q=0 all make install echo "=====================================================" echo echo " Kamailio Mysql Information " echo echo "=====================================================" echo read -p "Sip Domain : " sipdomain read -p "Database User : " dbuser read -p "Database Name : " dbname read -s -p "Database Password : " dbpasswd echo sed -i "/^# SIP_DOMAIN=.*\|^#SIP_DOMAIN=.*/c SIP_DOMAIN=${sipdomain}" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# DBENGINE=MYSQL.*\|^#DBENGINE=MYSQL.*/c DBENGINE=MYSQL" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# DBHOST=.*\|^#DBHOST=.*/c DBHOST=localhost" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# DBPORT=.*\|^#DBPORT=.*/c DBPORT=3306" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# DBNAME=.*\|^#DBNAME=.*/c DBNAME=${dbname}" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# DBRWUSER=.*\|^#DBRWUSER=.*/c DBRWUSER=\"${dbuser}\"" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# DBRWPW=.*\|^#DBRWPW=.*/c DBRWPW=\"${dbpasswd}\"" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# CHARSET=.*\|^#CHARSET=.*/c CHARSET=\"latin1\"" $KAMBASE/etc/kamailio/kamctlrc sed -i "/^# ALIASES_TYPE=.*\|^#ALIASES_TYPE=.*/c ALIASES_TYPE=\"DB\"" $KAMBASE/etc/kamailio/kamctlrc echo "=====================================================" echo echo " Kamailio DB Passwd Enter to Create Data Table" echo echo "=====================================================" echo $KAMBASE/sbin/kamdbctl create cd ../ rm -f $KAMBASE/etc/kamailio/kamailio.cfg cp WEBRTC/etc/kamailio/kamailio-old.cfg $KAMBASE/etc/kamailio/kamailio.cfg sed -i "/^#!define DBURL \"mysql:\/\/.*/c #!define DBURL \"mysql://${dbuser}:${dbpasswd}@localhost/${dbname}\"" $KAMBASE/etc/kamailio/kamailio.cfg cat >/etc/default/kamailio <<EOF # # Kamailio startup options # # Set to yes to enable kamailio, once configured properly. RUN_KAMAILIO=yes # User to run as USER=kamailio # Group to run as GROUP=kamailio # Amount of shared and private memory to allocate # for the running Kamailio server (in Mb) #SHM_MEMORY=64 #PKG_MEMORY=8 # Config file CFGFILE=$KAMBASE/etc/kamailio/kamailio.cfg # Enable the server to leave a core file when it crashes. # Set this to 'yes' to enable Kamailio to leave a core file when it crashes # or 'no' to disable this feature. This option is case sensitive and only # accepts 'yes' and 'no' and only in lowercase letters. # On some systems it is necessary to specify a directory for the core files # to get a dump. Look into the kamailio init file for an example configuration. #DUMP_CORE=yes EOF cp $SRCPATH/kamailio.init /etc/init.d/kamailio systemctl daemon-reload systemctl start kamailio.service systemctl enable kamailio.service fi apt-get -y install nginx cp WEBRTC/etc/nginx/nginx.conf /etc/nginx/ cp WEBRTC/etc/nginx/conf.d/default.conf /etc/nginx/conf.d/ cp -r WEBRTC/client/* /var/www/html/ service nginx restart apt-get -y install coturn cp WEBRTC/etc/default/coturn /etc/default/ cp WEBRTC/etc/turnserver.conf /etc/ service coturn restart
e1e8c726518ea1c16dc5c996617237910099368d
[ "Shell" ]
1
Shell
bdsoftpro/kamailio-setup
118f8fbc02ffb7855d8e0cb35c19c1ec1a6eac04
5f9436f9e3a8dac149861f59577b62cee938b4ff
refs/heads/master
<file_sep>package model; /** * Class that handles the generation of queues, servers, customers and the interaction between them for the simlulation of a multi queue system * @author <NAME> * @author <NAME> */ import java.util.ArrayList; public class MultiQueueControlSystem implements QueueControlSystem { private ServerCollection servers; private QueueCollection queues; private PersonFactory personFactory; private static MultiQueueControlSystem instance = null; private MultiQueueControlSystem() { servers = new ServerCollection(); queues = new QueueCollection(); personFactory = new PersonFactory(); } public static MultiQueueControlSystem getInstance() { if(instance == null) { instance = new MultiQueueControlSystem(); } return instance; } public void generateQueuesAndServers(int numServers) { for (int i = 0; i < numServers; i++) { Server server = new HumanServer(); servers.addServer(server); Queue queue = new PersonQueue(); queues.addQueue(queue); server.setAllocatedQueue(queue); } } //If a customer is generated, add it to the shortest queue public void customerArrival() { Person newPerson = personFactory.generatePerson(); if (newPerson != null) { Queue shortestQueue = queues.showShortestQueue(); shortestQueue.addPerson(newPerson); Stats.CUSTOMERS_GENERATED++; } } //Allocates a customer to an available server from their allocated queues public void allocateCustomersToServers() { if (servers.showAvailableServers().size() > 0) { for (Server server : servers.showAvailableServers()) { if (server.getAllocatedQueue().getLength() > 0) { server.setCurrentCustomer(server.getAllocatedQueue().getHeadOfQueue()); server.getAllocatedQueue().removeHeadOfQueue(); server.setFree(false); } } } } //Removes customers from the servers if their serve time has been met or exceeded public void serveAndFinishWithCustomers() { servers.serveCustomers(); servers.finishWithCustomers(); } public ServerCollection getServerCollection() { return this.servers; } public ArrayList<Queue> getQueues() { return queues.getQueues(); } } <file_sep>package model; import java.util.ArrayList; /** * Represents a collection of many different queues. * @author <NAME> * */ public class QueueCollection { /** * The queues contained in this collection */ private ArrayList<Queue> queues; public QueueCollection() { queues = new ArrayList<Queue>(); } public ArrayList<Queue> getQueues() { return queues; } /** * Returns the shortest queue. * @return the shortest queue */ public Queue showShortestQueue() { //TODO: Implement error handling for when the collection is empty Queue shortestQueue = queues.get(0); if (shortestQueue != null) { int shortestQueueLength = shortestQueue.getLength(); for(Queue currentQueue : queues) { if(currentQueue.getLength() < shortestQueueLength) { shortestQueue = currentQueue; } } } return shortestQueue; } public void addQueue(model.Queue queue) { queues.add(queue); } } <file_sep>package model; import java.util.ArrayList; /** * Interface that models a queueing system * Controls the generation of Queues and Servers for the simulation, and * the flow of customers between them * @author <NAME> * */ public interface QueueControlSystem { //Generates the queues and servers for the simulation public void generateQueuesAndServers(int numServers); /** * Calls the PersonFactory generatePerson() method * If a Person is generated, this method adds them to the shortest queue */ public void customerArrival(); //Allocates customers to free servers until there are no more free servers or no more customers public void allocateCustomersToServers(); //Increments time served. When serving time has been reached, removes customers from servers and sets the servers' availability to free public void serveAndFinishWithCustomers(); //Returns all of the queues in the system public ArrayList<Queue> getQueues(); public ServerCollection getServerCollection(); } <file_sep>package model; /** * Class that handles the generation of customers based on * their probability of being generated * @author <NAME> */ import java.util.Random; public final class PersonFactory { public PersonFactory() {} private int generateRandomNumber() { Random rand = new Random(42); return rand.nextInt(101); } /** * Generates a new person if the probability matches their likelihood of appearing * ComplainingCustomer has a 0.07 probability of being generated * Customer has a 0.07 probability of being generated * ShortOfTime has a 0.05 probability of being generated * @return a Person object if generated */ public Person generatePerson() { int probability = generateRandomNumber(); Person person = null; if (probability <= 7) { person = new ComplainingCustomer(); } else if (probability > 7 && probability <= 14) { person = new Customer(); } else if (probability > 14 && probability < 20) { person = new ShortOfTimeCustomer(); } return person; } }<file_sep>package model; /** * Interface modelling any kind of person that could join a queue i.e. customer, inspector or colleague * @author <NAME> */ public interface Person { public void initialiseServeTime(); public int getServeTime(); } <file_sep>package model; import java.util.LinkedList; /** * Represents a queue of people. * @author <NAME> * */ public class PersonQueue implements Queue { /** * Holds all the different people in the queue. */ private LinkedList<Person> queue; public PersonQueue() { queue = new LinkedList<Person>(); } @Override public void addPerson(Person person) { if(queue != null) { queue.add(person); } } public LinkedList<Person> getQueue() { return queue; } public void removePerson(Person person) { queue.remove(person); } @Override public int getLength() { return queue.size(); } @Override public boolean removeHeadOfQueue() { if(queue.isEmpty()) { return false; } queue.removeFirst(); return true; } public Person getHeadOfQueue() { return queue.getFirst(); } } <file_sep>package model; import java.util.LinkedList; /** * An interface to represent queues. * @author <NAME> * */ public interface Queue { /** * Adds a person to the queue. * @param person the person to add * @return whether the operation is successful */ public void addPerson(Person person); /** * Gets the length of the queue. * @return the length of the queue. */ public int getLength(); /** * Removes the element at the head (top) of the queue. * @return whether the operation is successful */ public boolean removeHeadOfQueue(); public Person getHeadOfQueue(); public LinkedList<Person> getQueue(); public void removePerson (Person person); } <file_sep>package model; /** * Class that models a customer who takes twice as long * to serve if they're kept waiting for more than 8 minutes * @author <NAME> */ public class ComplainingCustomer extends UnhappyCustomer { //Time spent waiting in the queue, measured in ticks private int timeSpentQueueing; //The cutoff point where the customer takes twice as long to serve private static final int PATIENCE_LIMIT = 48; public ComplainingCustomer() { initialiseServeTime(); } //Increases time spent queueing by one tick public void incrementTimeSpentQueueing() { this.timeSpentQueueing++; Stats.TOTAL_WAITING_TIME++; } //Returns the time spent queueing public int getTimeSpentQueueing() { return this.timeSpentQueueing; } //If the time spent queueing is greater than the patience limit, double serving time public boolean queuedForTooLong() { boolean unhappy = false; if (timeSpentQueueing >= PATIENCE_LIMIT) { unhappy = true; } return unhappy; } public void doubleServeTime() { if (this.timeSpentQueueing >= PATIENCE_LIMIT) { int serveTimeDoubled = getServeTime() * 2; setServeTime(serveTimeDoubled); } } public int getPatienceLimit() { return PATIENCE_LIMIT; } }
3c74c7f1123e4f63909a83320ec7933a03bb3835
[ "Java" ]
8
Java
ungtony/QueueSim
6514608a913de3b09c6d92ec72198849976ad0ae
b258ed9807bad20dfc48bb68ebbd8a0b84177d75
refs/heads/master
<file_sep>// react redux's connect function import { connect } from "react-redux"; // import in the Tasks component import Tasks from "../components/Tasks"; import { postTask, getTasks } from "../data/actions/api"; // We're taking the tasks array from the global state and assigning it to a taks property which will be passed to the tasks component through maps state to props. const mapStateToProps = state => { return { tasks: state.tasks, }; }; const mapDispatchToProps = dispatch => { return { // onSubmit is a function which dispatches an api action "postTask" //taking the data (the value of the input) and passing it into posttaks action onSubmit: data => dispatch(postTask(data)), onLoad: () => dispatch(getTasks()), //dispatching get tasks api action }; }; // connect up mapStateToProps with the Tasks component // Tasks' props are now controlled by this file export default connect(mapStateToProps,mapDispatchToProps)(Tasks); <file_sep>import axios from "../axios"; import { addTask, setTasks, editTask, removeTask, completeTask } from "./state"; export const postTask = (task) => dispatch => { axios.post("/tasks", { // send the submitted data from the input form task: task, // task: is what the database is expecting to receive }).then(({ data }) => { //returns a json object with a data object inside const task = data.data; //getting the data object inside and assigning it to task dispatch(addTask(task)); // sending that object to our state action }); }; export const getTasks = () => dispatch => { axios.get("/tasks").then(({ data }) => { const tasks = data; //getting the data object inside and assigning it to task dispatch(setTasks(tasks)); // sending that object to our state action }); }; export const patchTask = (data, id) => dispatch => { axios.patch(`/tasks/${id}`, { task: data }).then(({ data }) => { const task = data.data; //getting the data object inside and assigning it to task dispatch(editTask(task)); // sending that object to our state action }); }; export const deleteTask = (id) => dispatch => { axios.delete(`/tasks/${id}`).then(() => { dispatch(removeTask(id)); // sending that object to our state action }); }; export const patchTaskComplete = (status, id) => dispatch => { axios.patch(`/tasks/${id}/complete`, { completed: status }).then(({ data }) => { let task = data.data dispatch(completeTask(task)); // sending that object to our state action }); }; //these are all API actions, that we name. they take argument and then are dispatched. //Axios is the middlewear we use to talk to our db from our app. //We pass it what it needs to know in order to do what it needs to do (arguments) // <file_sep>// react redux's connect function import { connect } from "react-redux"; // import in the Task component import Task from "../components/Task"; import { patchTask, patchTaskComplete, deleteTask } from "../data/actions/api"; const mapDispatchToProps = (dispatch, {task}) => { return { // onUpdate is a function which dispatches an api action "patchTask" onUpdate: data => dispatch(patchTask(data, task.id)), onDelete: () => dispatch(deleteTask(task.id)), onComplete: status => dispatch(patchTaskComplete(status, task.id)), }; }; // connect up mapStateToProps with the Task component // Tasks' props are now controlled by this file export default connect(null, mapDispatchToProps)(Task); <file_sep>const initial = { tasks: [], } export default initial; // { // "id": 2, // "task": "Eat cookies!", // "completed": 0, // "created_at": "2018-06-27 11:44:32", // "updated_at": "2018-06-27 11:44:32" // }, // { // "id": 3, // "task": "Play pingpong", // "completed": 0, // "created_at": "2018-06-27 11:44:45", // "updated_at": "2018-06-27 11:44:45" // }, // { // "id": 4, // "task": "Read your to-do list", // "completed": 1, // "created_at": "2018-06-27 11:46:05", // "updated_at": "2018-06-27 11:49:00" // } <file_sep>//this is where we create our functings that as passed into the switch statment const addTask = (state, {task}) => { return { ...state, tasks: state.tasks.concat(task) }; }; //they take state and whatever information we've passed into state action //sometimes take a copy of state and ALWAYS returns something with the state changed in some way const setTasks = (state, {tasks}) => { return { ...state, tasks: tasks }; }; // const editTask = (state, {id, task}) => { let list = state.tasks.slice() let newTasks = list.map(listItem => { if (listItem.id === task.id) { return task } else { return listItem } }) return { ...state, tasks: newTasks }; }; const removeTask = (state, { id }) => { let list = state.tasks.slice() let newTasks = list.filter(listItem => listItem.id !== id) return { ...state, tasks: newTasks }; }; const completeTask = (state, {id, task, completed}) => { let list = state.tasks.slice() let newTasks = list.map(listItem => { if (listItem.id === task.id) { return task } else { return listItem } }) return { ...state, tasks: newTasks }; }; const reducer = (state, action) => { switch (action.type) { case "addTask": return addTask(state, action); case "setTasks": return setTasks(state, action); case "editTask": return editTask(state, action); case "removeTask": return removeTask(state, action); case "completeTask": return completeTask(state, action); default: return state; } }; export default reducer <file_sep>import React from "react"; // import { // Route, // Switch, // } from "react-router-dom"; import Tasks from "./containers/Tasks"; //import FourOhFour from "./components/FourOhFour"; const App = () => ( <React.Fragment> { /* header should show on all pages */ } <header><h1 style={{ textAlign: "center" }} className="jumbotron">To Do List</h1></header> <Tasks/> </React.Fragment> ); export default App; <file_sep>import React, { Component } from "react"; class Task extends Component { constructor(props) { super(props) this.state = { editing: false, value: this.props.task.task, completed: this.props.task.completed } //is taking props from tasks component and setting it to value this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.handleDelete = this.handleDelete.bind(this); this.handleEdit = this.handleEdit.bind(this); this.handleComplete = this.handleComplete.bind(this); } handleEdit() { this.setState({ editing: true, }) } handleChange(e) { let input = e.target.value this.setState({ value: input }) }//looks at hat the user types and saves it as value handleDelete(e) { this.props.onDelete(); } //these methods are doing soem logic and then passing through our methods from the container. handleSubmit(e) { e.preventDefault(); //taking whatever the user has typed and set it to data. let data = this.state.value; this.setState({ editing: false }) this.props.onUpdate(data); } handleComplete(e) { let complete = !this.state.completed //toggles between the two options for completed and not completed and sets to state. setting complete to the opposite of what it is equal to in state. this.setState({ completed: complete //assigning the value to the opposite of what it was before }) this.props.onComplete(complete);//taking that value and passing it into the oncomplate method } render() { const { task } = this.props;// anytime we access something from props, we can do destructuring to not have to type this.props lll the time const { editing, value, completed } = this.state;//same same let colour = completed ? "lightgrey" : "black"; return ( <React.Fragment> <input style={{ display: "inline-block" }} onChange={ this.handleComplete } type="checkbox" checked={ completed }></input> { editing ? <form style={{ display: "inline-block" }} onSubmit={ this.handleSubmit }> <input id="task" onChange={ this.handleChange } value={ value }></input> <button style={{ margin: "2px" }} className="btn btn-outline-info">Update</button> </form> : <p style={{color: colour, display: "inline-block", marginLeft: "5px", marginRight: "10px" }}>{ task.task }</p> } <button onClick={ this.handleEdit } style={{ margin: "4px" }} className="btn btn-outline-warning" disabled={ completed }>Edit</button> <button onClick={ this.handleDelete } style={{ margin: "4px" }} className="btn btn-outline-danger">Delete</button> </React.Fragment> ) //if we're in editing mode display the value in the form, if not display the value in the p tag and disable the edit button. } } export default Task;
8b865566c00b16060985a76bc60332a7e679cca5
[ "JavaScript" ]
7
JavaScript
floorford/todoreact-app
0b4c974233c21b53a3d5c290094b0f5325bf63ee
541a2a7f1bcdfd0a3c39f2b363bb24d0c260793f
refs/heads/master
<repo_name>dbcolber/si364final<file_sep>/templates/index.html <body style="background-color:LightGoldenrodYellow;"> {% if current_user.is_authenticated %} <a href="{{ url_for('logout') }}">Sign Out {{current_user.username}}</a> <br> <h2> Welcome to your virtual cookbook! </h2> <div class="page-header"> <h1><p><a href="{{ url_for('see_all') }}">See all my recipes</a></p></h1> </div> <form method="POST"> {{ form.hidden_tag() }} {{ form.searchword.label }} {{ form.searchword() }} {{ form.submit() }} </form> {% else %} <h2> Welcome to your virtual cookbook! </h2> <a href="{{ url_for('login') }}">Sign In</a> {% endif %} <div> {% for message in get_flashed_messages() %} {{ message }} {% endfor %} </div> </body><file_sep>/food2fork.py __author__ = "<NAME>" import requests import json import unittest # from app import create_app, db # from app.models import User, Role import os from flask import Flask, render_template, session, redirect, request, url_for, flash from flask_script import Manager, Shell from flask_wtf import FlaskForm from wtforms import StringField, SubmitField, FileField, PasswordField, BooleanField, SelectMultipleField, ValidationError from wtforms.validators import Required, Length, Email, Regexp, EqualTo from sqlalchemy.ext.declarative import declarative_base from flask_sqlalchemy import SQLAlchemy from flask_migrate import Migrate, MigrateCommand from flask_mail import Mail, Message from threading import Thread from werkzeug import secure_filename from flask_login import LoginManager, login_required, logout_user, login_user, UserMixin, current_user from werkzeug.security import generate_password_hash, check_password_hash Base = declarative_base() # Configuring basedir of app basedir = os.path.abspath(os.path.dirname(__file__)) # Configuring app app = Flask(__name__) app.static_folder = 'static' app.config['SECRET_KEY'] = 'hardtoguessstring' app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get('DATABASE_URL') or "postgresql://localhost/new_data_flask" app.config['SQLALCHEMY_COMMIT_ON_TEARDOWN'] = True app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['MAIL_SERVER'] = 'smtp.googlemail.com' app.config['MAIL_PORT'] = 587 #default app.config['MAIL_USE_TLS'] = True app.config['MAIL_USERNAME'] = os.environ.get('MAIL_USERNAME') app.config['MAIL_PASSWORD'] = os.environ.get('MAIL_PASSWORD') app.config['MAIL_SUBJECT_PREFIX'] = '[My Virtual Cookbook]' app.config['MAIL_SENDER'] = 'Admin <<EMAIL>>' # TODO fill in app.config['ADMIN'] = 'Admin <<EMAIL>>' mail = Mail(app) manager = Manager(app) db = SQLAlchemy(app) # For database use migrate = Migrate(app, db) # For database use/updating manager.add_command('db', MigrateCommand) # Creating a log manager // configuring login setup login_manager = LoginManager() login_manager.session_protection = 'strong' login_manager.login_view = 'login' login_manager.init_app(app) def send_asyncronous_email(app, msg): with app.app_context(): mail.send(msg) def send_email(to, subject, template, **kwargs): msg = Message(app.config['MAIL_SUBJECT_PREFIX'] + ' ' + subject, sender=app.config['MAIL_SENDER'], recipients=[to]) msg.body = render_template(template + '.txt', **kwargs) msg.html = render_template(template + '.html', **kwargs) thr = Thread(target=send_asyncronous_email, args=[app, msg]) thr.start() # SETTING UP MODELS ---------------------------------------------------------- # Setting up association tables # user_recipes = db.Table('user_recipes',db.Column('user_id', db.Integer, db.ForeignKey('users.id')), db.Column('recipes_id', db.Integer, db.ForeignKey('recipes.id'))) search_recipes = db.Table('search_recipes', db.Column('recipes_id', db.Integer, db.ForeignKey('recipes.id')), db.Column('searchword_id',db.Integer, db.ForeignKey('searchwords.id'), primary_key=True)) # User Model ----------------------------------------------------------------- class User(UserMixin, db.Model): __tablename__ = "users" id = db.Column(db.Integer, primary_key=True) username = db.Column(db.String(255), unique=True, index=True) email = db.Column(db.String(64), unique=True, index=True) password_hash = db.Column(db.String(128)) @property def password(self): raise AttributeError('password is not a readable attribute') @password.setter def password(self, password): self.password_hash = generate_password_hash(password) def verify_password(self, password): return check_password_hash(self.password_hash, password) @login_manager.user_loader def load_user(user_id): return User.query.get(int(user_id)) # Other models ----------------------------------------------------------------- class Searchword(db.Model): __tablename__ = "searchwords" id = db.Column(db.Integer, primary_key=True) word = db.Column(db.String(300)) # recipes = db.Column(db.Integer, db.ForeignKey("recipes.id")) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) recipes = db.relationship("Recipes", secondary = search_recipes, backref=db.backref('searchwords', lazy='dynamic'), lazy='dynamic') # print('from Searchword class: ', recipes) class Recipes(db.Model): __tablename__ = "recipes" id = db.Column(db.Integer, primary_key=True) name = db.Column(db.String(300)) searchword_id = db.Column(db.Integer, db.ForeignKey("searchwords.id")) publisher = db.Column(db.String(300)) url = db.Column(db.String(600)) image_url = db.Column(db.String(600)) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) # Setting up Forms ------------------------------------------------------------- class UserForm(FlaskForm): email=StringField('Enter Email: ', validators=[Required(), Email(), Length(1,64)]) username=StringField('Enter Username: ', validators=[Required(), Length(1,64), Regexp('^[A-Za-z][A-Za-z0-9]*$', 0, 'Usernames can only have numbers and letters!')]) password=PasswordField('Enter Password: ', validators=[Required(), EqualTo('password2', message="These passwords must match!")]) password2=PasswordField('Confirm Password: ', validators=[Required()]) submit=SubmitField('Register') def validate_email(self,field): if User.query.filter_by(email=field.data).first(): raise ValidationError('Sorry! This email is already registered.') def validate_username(self,field): if User.query.filter_by(username=field.data).first(): raise ValidationError('Username already taken') class LoginForm(FlaskForm): email = StringField('Email', validators=[Required(), Length(1,64), Email()]) password = PasswordField('Password', validators=[Required()]) remember_me = BooleanField('Keep me logged in') submit = SubmitField('Log In') class RecipeForm(FlaskForm): searchword = StringField("Search for a Recipe: ", validators=[Required()]) submit = SubmitField('Search') # Helper functions ----------------------------------------------------------------- def get_or_create_searchword(db_session, searchword, user_id): print(searchword) searchword1 = db_session.query(Searchword).filter_by(word=searchword).first() if searchword1: print("Found recipe...") return searchword1 else: print("Finding recipe for: ", searchword) searchword = Searchword(word=searchword, user_id=user_id) db_session.add(searchword) db_session.commit() return searchword def get_or_create_recipes(db_session, title, publisher, url, image_url, user_id, searchword): recipe = db_session.query(Recipes).filter_by(name="title").first() if recipe: return recipe else: recipe_searchword = get_or_create_searchword(db_session, searchword, user_id) # search = recipe_searchword.id # recipe.searchword_id = search print('recipe searchword: ', recipe_searchword) recipe = Recipes(name=title, publisher=publisher, url=url, image_url=image_url, user_id=user_id) print("Recipe: ", recipe) db_session.add(recipe) db_session.commit() return recipe ## ROUTES ------------------------------------------------------------------- @app.errorhandler(404) def pagenotfound(e): return render_template('404.html'), 404 @app.errorhandler(404) def pagenotfound(e): return render_template('500.html'), 500 #VIEW FUNCTION 1 @app.route('/login', methods=["GET", "POST"]) def login(): form = LoginForm() if form.validate_on_submit(): user = User.query.filter_by(email=form.email.data).first() if user is not None and user.verify_password(form.password.data): login_user(user, form.remember_me.data) return redirect(request.args.get('next') or url_for('index')) flash('Uh-oh! That username and/or password is invalid. Please try again!') return render_template('login.html',form=form) #VIEW FUNCTION 2 @app.route('/logout') @login_required def logout(): logout_user() flash('You have been logged out') return redirect(url_for('index')) #VIEW FUNCTION 3 @app.route('/register',methods=["GET","POST"]) def register(): form = UserForm() if form.validate_on_submit(): user = User(email=form.email.data,username=form.username.data,password=form.password.data) mess = "Thank you for joining Virtual Cookbook!" send_email(form.email.data, "New Virtual Cookbook Account", "mail/register") db.session.add(user) db.session.commit() flash('You can now log in!') return redirect(url_for('login')) return render_template('register.html',form=form) #VIEW FUNCTION 4 @app.route('/', methods=['GET', 'POST']) def index(): recipes = Recipes.query.all() form = RecipeForm() if form.validate_on_submit(): base = 'http://food2fork.com/api/search' r = requests.get(base, params={'key':'<KEY>', 'q':form.searchword.data}) r_dic = r.json() recipe1 = r_dic['recipes'][0] print(recipe1) print(r_dic) #user = User.query.filter_by(user_id=current_user.id).all() get_or_create_recipes(db.session, recipe1["title"], recipe1["publisher"], recipe1["source_url"], recipe1["image_url"], current_user.id, form.searchword.data) return redirect(url_for('see_all')) return render_template('index.html', form=form) #VIEW FUNCTION 5 @app.route('/cookbook') def see_all(methods=["GET","POST"]): rec = Recipes.query.all() all_recipes = [] for r in rec: if r.user_id == current_user.id: all_recipes.append((r.name, r.url, r.image_url)) return render_template('all_recipes.html', all_recipes=all_recipes) if __name__ == '__main__': db.create_all() manager.run() # class FlaskClientTestCase(unittest.TestCase): # # testing the addition of a new recipe to the database # def test_recipes(self): # # adding a new recipe # new_recipe = get_or_create_recipes(db.session, 'Paleo Pancakes', 'Cooking by Danielle', 'www.test123.com', 'www.test123.com/images', 4) # db.session.add(new_recipe) # db.session.commit() # # testing to see if user is in db # rec = Recipes.query.filter_by(name='Paleo Pancakes').first() # self.assertEqual(rec.name, 'Paleo Pancakes') # if __name__ == '__main__': # unittest.main() <file_sep>/test.py import requests import json import unittest from food2fork import get_or_create_recipes, db, app, mail, get_or_create_searchword import os ## Test Suite def getting_recipe_api(food): base = 'http://food2fork.com/api/search' r = requests.get(base, params={'key':'<KEY>', 'q':food}) r_dic = r.json() recipe1 = r_dic['recipes'][0] return recipe1 # print(getting_recipe_api('pasta')) class TestCase(unittest.TestCase): def test_api_1(self): pasta = getting_recipe_api('pasta') self.assertEqual(type(pasta["title"]), type(""), "Testing that the Food2Fork API returns a string for the title of the recipe") def test_api_2(self): pasta = getting_recipe_api('pasta') self.assertEqual(pasta['source_url'], 'http://thepioneerwoman.com/cooking/2011/06/pasta-with-pesto-cream-sauce/', "Testing that the top rated pasta recipe matches this soruce url") def test_api_3(self): searchword = "pineapple pizza" pizza = getting_recipe_api(searchword) self.assertEqual(type(pizza), type({}), "Testing that the API returns a dictionary that can later be parsed in my code for when I put the data into my database") def test_api_4(self): searchword = "pineapple pizza" pizza = getting_recipe_api(searchword) self.assertEqual(len(pizza), 8, "Testing that the Food2Fork API returns a dictionary with 8 keys") def setUp(self): app.config["TESTING"] = True app.config["WTF_CSRF_ENABLED"] = False app.config["DEBUG"] = False app.config["SQLALCHEMY_DATABASE_URI"] = os.environ.get('DATABASE_URL') or "postgresql://localhost/testdb" self.app = app.test_client() db.drop_all() db.create_all() # executed after each test def tearDown(self): pass def test_app_routes(self): resp = self.app.get('/', follow_redirects=True) self.assertEqual(resp.status_code, 200, "Testing that the status code is 200 when the user goes to the index") def test_app_routes_2(self): resp = self.app.get('/jdfksla;js', follow_redirects=True) self.assertEqual(resp.status_code, 500, "Testing that this nonsense string returns a 505 error") def test_app_routes_3(self): resp = self.app.get('/cookbook', follow_redirects=True) self.assertEqual(resp.status_code, 200, "Testing that the status code is 200 when the user goes to the /cookbook route") # testing the addition of a new recipe to the database def test_recipes(self): pasta = getting_recipe_api('pasta') all_keys = [] counter = 0 for item in pasta: counter += 1 print(counter, item) all_keys.append(item) self.assertEqual(len(all_keys), 8, "Testing the number of keys in a recipe request") if __name__ == '__main__': unittest.main() <file_sep>/README.md Virutal Cookbook by <NAME> In this project, I created an application where users register an account so that they can save recipes to their virtual cookbook. To run this application, please create a database called 'new_data_flask'. To run the project, make sure you have the following modules and requirements downloaded: requests, json, unittest, os, flask, flask_script, flask_wtf, wtforms, sqhalchemy, flask_sqlalchemy, flask_migrate, flask_mail, threading, werkzeug, and flask_login. Once you have all the requirements installed, you can run the application by typing 'python food2fork.py runserver' in terminal. Please go to localhost:5000/ to sign in. Once you click sign in, you are taken to a login in screen where you can register a new account. An email will be sent when registation is complete. After logging in, you can search for recipes to add to your virtual cookbook. To run the tests, type 'python test.py' in terminal. Enjoy! ----------------- Recipe API Used: https://food2fork.com/about/api
a3f6535ce29d80b5aee0872c3db4d9590b5803d0
[ "Markdown", "Python", "HTML" ]
4
HTML
dbcolber/si364final
834cf325e109ed72cf0943e60e3b5ce8ffa69daa
18ea60859f022ccf0e29dd425f02a92ba51577af
refs/heads/master
<file_sep>(function(){ var getChartData = function(){ //retrieve food item data var week1 = localStorage.getItem("itemValue"), week2 = localStorage.getItem("itemValue2"); //if we have something on local storage place that if(week1) { $("#foodweek1").append(week1) } if(week2) { $("#foodweek2").append(week2) } } //food items data for progress page table from local storage window.addEventListener("load", getChartData); })();
a69126d01d72449b05e4a74fbd9b3cfd64ce9ae8
[ "JavaScript" ]
1
JavaScript
geethapai/aux_bootcamp_challenge
1668f94c2eec8b9f82a89da96d5732c405ccfcbd
bbb124672cdb0629de80afb6b36bd8e7ac0e4e4c
refs/heads/master
<file_sep>/** * Created by <NAME> on 19/5/2017. */ public interface Actionator<T> { void run(T obj); } <file_sep>import java.util.Iterator; public class Queue<Item> implements Iterable<Item> { private Item[] arr; private int size; private int first; private int last; public Queue() { arr = (Item[]) new Object[1]; } public void enqueue(Item item) { if(isFull()) { resize(arr.length * 2); } if(++last == arr.length) { last = 0; } arr[last] = item; size++; } public Item dequeue() { if(isEmpty()) { return null; } Item item = arr[first]; arr[first] = null; size--; if(++first == arr.length) { first = 0; } if(size > 0 && size == arr.length / 4) { resize(arr.length / 4); } return item; } public boolean isEmpty() { return size == 0; } public boolean isFull() { return size == arr.length; } public Iterator<Item> iterator() { return new QueueIterator(); } private class QueueIterator implements Iterator<Item> { private int index = 0; public boolean hasNext() { return index < size; } public Item next() { return arr[ (first + index++) % arr.length]; } public void remove() { } } private void resize(int newSize) { Item[] newArr = (Item[]) new Object[newSize]; for(int i = first,ctr = 0; i <= last; i++) { if(i == arr.length) { i = 0; } newArr[ctr++] = arr[i]; } arr = newArr; first = 0; last = size - 1; } } <file_sep># Stack With Linked List ## Public methods public void push(Item item) public Item pop() public int size() public boolean isEmpty()<file_sep># Union ## Public methods public void union(int p,int q) public boolean connected(int p,int q) public String toString()<file_sep># Resizing Array Stack <file_sep># Binary Search Tree ## Public methods void add(Item item) Adds a Item in the binary search tree. boolean isEmpty() Check whether the bst has no elements. void levelOrder(Actionator<Item> action) Traverse the binary search tree in levelorder boolean remove(Item item) Removes a specified Item from the binary search tree. int size() Retuns the number of elements in the binary search tree. ## TO-DO I have to add more methods for traversing the collection. <file_sep># DataStructures Most common data structures with my implementation. <file_sep># Sorted Double Linked List ## Public methods void add(Item item) int indexOf(Item item) int indexOf(Item item, java.util.Comparator<Item> comp) boolean isEmpty() java.util.Iterator<Item> iterator() boolean remove(int index) boolean remove(Item item) int size() void traverse(Actionator<Item> action)
30ef4fab92f91d941dd0ff958ef6a48d9f5ad5f8
[ "Markdown", "Java" ]
8
Java
Tiltorito/DataStructures
153f7baacf8fedb3c381c2f40c177c0f2f4b491b
2f39a108bff35027c8b5cb87ac54f553f179c403
refs/heads/master
<file_sep># import libraries import pandas as pd import numpy as np from time import time from IPython.display import display import matplotlib.pyplot as plt from pandas.plotting import scatter_matrix from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler from sklearn.pipeline import Pipeline from sklearn.model_selection import train_test_split from sklearn.model_selection import GridSearchCV import pickle def load_data(file_path): """ Load the data set df will be the returned dataframe """ df = pd.read_csv(file_path) return df def clean_data(df): """ clean dataframe by dropping all the the null and duplicate rows. and returend a clean df """ # Dropping yog and yog_weight as they are not collerated with exam df.drop(["yog", "yog_weight"], axis=1, inplace=True) # Drop rows wtih missing values df.dropna(inplace=True) # check if there ar a duplicated values in the exmeinor id # some students apply for admission the following term df["idno"].duplicated().sum() # remove duplicated rows with the same idno and get the final cleaned rows df.drop_duplicates(subset=["idno"], keep=False) # if the value of the exam 0 that's mean student did not take the test # so dropp it df = df[df.exam != 0] return df def build_model(df): """ Building a model after clean the data the scatter matrix show that there are 4 feauters are collerated with exam """ # set the features and mark as an output mark = df["exam"] features = df.drop(["exam", "idno", "rank"], axis=1) # The studnet will be accepted if the mark is above 50 # So if its above 50 the mark will be 1 otherwise is 0 mark_numeric = lambda i: 0 if i < 50 else 1 # apply the lambda on mark mark = mark.apply(mark_numeric) # Building a model with pipeline definig the steps and scale the data steps = [("scaler", StandardScaler()), ("SVM", SVC())] # define the pipeline object. pipeline = Pipeline(steps) # Split the data to train and test sets X_train, X_test, y_train, y_test = train_test_split( features, mark, test_size=0.2, random_state=30 ) # fit the model using pipeline pipeline.fit(X_train, y_train) # Predict by using the model y_pred = pipeline.predict(X_test) # print thr accuracy of the model print(f"The accuracy of the model :{pipeline.score(X_test,y_test)}") # Improve the model using grid search # Parameters options parameteres = { "SVM__C": [0.001, 0.1, 10, 100, 10000, 100000], "SVM__gamma": [0.1, 0.01], } # creat Grid search object grid = GridSearchCV(pipeline, param_grid=parameteres, cv=5) # fit the improved model grid.fit(X_train, y_train) # print thr accuracy of the model after the gird search improvement print(f"The accuracy of the model :{grid.score(X_test, y_test)}") # save the model pickle.dump(pipeline, open("app/model.pk1", "wb")) if __name__ == "__main__": # load the data and assing it to sdf df = load_data("dataset.csv") # clean the data and returned clean df df = clean_data(df) # build the mode build_model(df) <file_sep>import pandas as pd from sklearn.externals import joblib from flask import Flask, url_for, render_template, request, flash app = Flask(__name__) app.config["SECRET_KEY"] = "udacity" @app.route("/", methods=["post", "get"]) def main_page(): if request.method == "POST": print(request.form) try: gp = request.form["gp"] qiyas = request.form["qiyas"] gpqiyas = request.form["gpqiyas"] balanced = request.form["balanced"] new_features = pd.DataFrame( { "gp": [gp], "qiyas": [qiyas], "gpqiyas": [gpqiyas], "balanced": [balanced], } ) model = joblib.load("../model.pk1") pred = model.predict(new_features)[0] print("dd") except Exception as e: flash("Error, Please try again") pred = "" return render_template("main.html", pred=pred) print("dd") return render_template("main.html") if __name__ == "__main__": app.run(debug=True) <file_sep># Capstone # Overview Samtah college of technology locate in Saudi Arabia accept studnets two times a year. And they facing a drop from school after one year. And one of reasons is that at foundation term the students struglle with some courses. So, for the past year all students must take an exam to check if the students got the basic knolwdge fot Math,English and Computing. if the results of the exam is above 50, they should be accepted. # Disclamer : #### The dataset was exported from the Admission exam system of Samtah College of Technology. #### The administration Kindly provided me the dataset. #### The dataset is used for this project only and any attemped to use this dataset is not allowed #### unless an approval is given from the Administration. # Three steps will be taken in this procject ## Dataset Description The dataset contain 9 columns and 1453 entries as shown below : idno : The Identification number of the student (encrypted for privacy) rank : the rank of the students among all applicance in TVTC gp : HighSchool Degree qiyas : result of qiyas exam (Saudi Arabia only). qpgiyas : combined of 40% qiyas and 60% of gp yog : year of the students graduation from High School yog_weight : The weight of yog e.g : current year 100 , last year : 90 etc.. balanced : a balnced mark for all the features. exam : the exam results taken ( will be our predection ) ![Image of dfinfo](https://github.com/mbahhari/Capstone/blob/master/images/dfinfo.png?raw=true) ## Step 1 : Data Cleaninig After importing the data from csv file ''dataset.csv'' the following steps peroformed ### get general information from the dataset There are missing values in yog and yog_weight and the amount of missing values are significant Hence, this will affect our dataset scatter plot performed to see if there any collerations for these two features and colleration found. Thus, removing these two features. ![Image of yog](https://github.com/mbahhari/Capstone/blob/master/images/yog_col.png?raw=true) ```df.drop(['yog','yog_weight'],axis=1,inplace=True) ``` ### Null values check for null values and drop all row with missing values ### Remove duplicates remove duplicated rows with the same idno and get the final cleaned rows ## Step 2: Data preprocessing: check the density of the features ``` plt.figure()df.loc[:, df.columns != 'idno'].plot(kind='density', figsize=(5,6),subplots=True ,sharex=False) plt.show() ``` ![Image of density](https://github.com/mbahhari/Capstone/blob/master/images/density.png?raw=true) check the colleration between columns to determine which column to use as features ![Image of scatter](https://github.com/mbahhari/Capstone/blob/master/images/scatter_matrix.png?raw=true) creat features and output and drop unnecessary features ``` mark= df['exam'] features = df.drop(['exam','idno','rank'], axis = 1) ``` ### StandardScaler data preprocessing method with Pipeline The use of pipeline will help to automate the workflow of the machine learning process, by performing a sequece of data processing one of the step to perform a pre-processing in the pipeline is StandardScaler. StandardScaler preprocessing parameters will be implemented as it will Standardize features by removing the mean and scaling to unit variance. ## Step 3: Build Model as mentioned Pipeline will be used to build our model the model will be impelented using pipeline is Support Vector Machines SVM : SVC as this model will provide highu accuracy comapred to other modules used in machine learning. ``` from sklearn.svm import SVC from sklearn.preprocessing import StandardScaler ``` convert the output to two values 0 if below 50 and 1 if its 50 or greater. ``` mark_numeric=lambda i: 0 if i<50 else 1 mark = mark.apply(mark_numeric) ``` Build the model ``` steps = [('scaler', StandardScaler()), ('SVM', SVC())] from sklearn.pipeline import Pipeline pipeline = Pipeline(steps) # define the pipeline object. ``` Split the data : ``` from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(features,mark,test_size=0.2, random_state=30) ``` fit the model predict and get the accuracy ``` pipeline.fit(X_train,y_train) y_pred=pipeline.predict(X_test) pipeline.score(X_test,y_test) 0.8049792531120332 ``` ## step 4 : Improve model using grid search create a list of params ``` parameteres = {'SVM__C':[0.001,0.1,10,100,10000,100000], 'SVM__gamma':[0.1,0.01]} ``` Creata a grid object ``` grid = GridSearchCV(pipeline, param_grid=parameteres, cv=5) ``` fit the gird ``` grid.fit(X_train, y_train) ``` ## Metrics : The metrics in the model wiht pipeline methods score which is to measure the accuracy Apply transforms, and score with the final estimator. and this will help us by using a gridsearch and get the most dersire score we can require ## Step 5: save the model to use it in web application using pickle ``` import pickle file='app/model.pk1' pickle.dump(grid,open(file,'wb')) ``` the file will exported to app directory to be ready to run the application ## Step 6 : web Application using Flask an application was build using flask to predict the result based on the data entered ![Image of web](https://github.com/mbahhari/Capstone/blob/master/images/web%20application.png?raw=true) ### Instruction to run the application: You can run the application from app directory ``` #python run.py ``` please check if model.pk1 file is located in app directory if its run succefully just open internet brower and type http://127.0.0.1:5000 in addresss bar Please do not hesitate to contact me for information or give me a feedback of this application the application in app folder # Conclusion ## Reflection At the end in this project i performed a from the beging data cleaning which was an important step since the dataset have null and duplicated cells in feature. After cleaning the dataset I visualize the density and the colleration between the features and the output to see which feature will help when bulding a model. finally building a model using pipeline which combined data pre processing and bulding a model in few steps. And using grid search to improve the score. one of the issue needed to be considered is the data cleaning. Because at the begining when bulding a model with all features the accuracy of the model in the range of 32%. ## Improvement an Improvement can be applied in regarding of using multiple models in gridsearch to compare what is best model for this problem. Also, the dataset was gathered for last year and in my opinion we need to have more entries to get with the best result for this problem
04acc69263768d8d3eecb3c1541349143c3e6449
[ "Markdown", "Python" ]
3
Python
mbahhari/Capstone
dbfbf83c6f9c8bc9b9f87f5b1b0336705eb8903e
1412dfd047a8b244e7c4aa39919962dc8e1e8b0c
refs/heads/master
<repo_name>arzuyildirim/project<file_sep>/preprocessing_for_gephi.R install.packages("RJSONIO") #the package to export data written in java to R library("RJSONIO") resultt <- fromJSON("starwars-episode-7-interactions-allCharacters.json", simplify = T) #firstly I wanted to extract edges data which is named as "links" in the dataset json_data_frame <- as.data.frame(resultt["links"], stringsAsFactors = F) json_data_frame json_data_frame <- t(json_data_frame) class (json_data_frame) json_data_frame <- unlist(json_data_frame) class(json_data_frame) dim(json_data_frame) #rename the variables. Specially value will be replace by weight to see if gephi reads it like that colnames(json_data_frame) colnames(json_data_frame)[colnames(json_data_frame) == "source"] <- "Source" colnames(json_data_frame)[colnames(json_data_frame) == "target"] <- "Target" colnames(json_data_frame)[colnames(json_data_frame) == "value"] <- "Weight" # Export the Edges data frame to excel install.packages("writexl") library(writexl) json_data_frame<-as.data.frame(json_data_frame) write_xlsx(json_data_frame,"Edgess.xlsx") # Nodes matrix. Here we have to give them and ID thats the same from the edges matrix(to make them matched in gephi) json_data_frame_nodes <- as.data.frame(resultt["nodes"], stringsAsFactors = F) json_data_frame_nodes json_data_frame_nodes <- t(json_data_frame_nodes) class (json_data_frame_nodes) json_data_frame_nodes <-as.data.frame(json_data_frame_nodes) class(json_data_frame_nodes) dim(json_data_frame_nodes) #here I valued nodes till 26 which is the number of nodes within the edges dataset and because numbers from 0 to 26 were the names in the edges data,this code will make them matched #it is important to assign each node with the numbers in the edge data json_data_frame_nodes$ID=0 json_data_frame_nodes$ID<-0:26 col_order_nodes <- c("ID", "value", "name", "colour") json_data_frame_nodes <- json_data_frame_nodes[,col_order_nodes] #rename the variables colnames(json_data_frame_nodes) colnames(json_data_frame_nodes)[colnames(json_data_frame_nodes) == "value"] <- "Value" colnames(json_data_frame_nodes)[colnames(json_data_frame_nodes) == "name"] <- "Label" colnames(json_data_frame_nodes)[colnames(json_data_frame_nodes) == "colour"] <- "Colour" # Export the nodes data frame to excel #wanted to make sure that organized data is data.frame which makes write_xl function work properly json_data_frame_nodes<-as.data.frame(json_data_frame_nodes) write_xlsx(json_data_frame_nodes,"Nodess.xlsx") <file_sep>/sentiment_analysis_codes.R rey <- read.csv("rey_tweets.csv", encoding="UTF-8") rey library(stringr) #I used tidytext package for sentiment analysis library(tidytext) library("dplyr") #I created tibble from given data to make proper data frame library(tibble) tibblerey<-as_tibble(rey) tibblerey<-as.character(tibblerey$content) tibblerey d <- tibble(txt = tibblerey) d #I separated words and put each of them in one line by using unnest_tokens function dat <- d %>% unnest_tokens(word, txt) dat #there are many words I am not interested in.To be able to extract what I need I used anti_join function from dplyr package unnested <- dat %>% anti_join(stop_words) # count function to take a look at what we have in tiddle count(unnested, word, sort=TRUE) #I used get_sentiment function to get specific sentiments with one row per word. rey_counts <- dat %>% inner_join(get_sentiments("bing")) %>% count(word, sentiment, sort = TRUE) %>% ungroup() #checked the first 20 adjectives head(rey_counts,20) #used ggplot2 package to create good looking graph library(ggplot2) rey_counts %>% group_by(sentiment) %>% top_n(5) %>% ungroup() %>% mutate(word = reorder(word, n)) %>% ggplot(aes(word, n, fill = sentiment)) + geom_col(show.legend = FALSE) + facet_wrap(~sentiment, scales = "free_y") + labs(y = "Contribution to sentiment", x = NULL) + coord_flip() #used for datawrangling using acast() function library(reshape2) #created wordcloud to visualize better with wordcloud package library(wordcloud) dat %>% inner_join(get_sentiments("bing")) %>% count(word, sentiment, sort = TRUE) %>% acast(word ~ sentiment, value.var = "n", fill = 0) %>% comparison.cloud(colors = c("red", "blue"), max.words = 100) library(ggplot2) library(tidyr) #I created polarity graph to see overall distribution of positive to negative words rey_counts %>% group_by(sentiment) %>% spread(sentiment, n, fill = 0) %>% mutate(polarity = positive - negative) %>% filter(abs(polarity)<10) %>% ggplot(aes(polarity)) + geom_density(alpha = 0.3) + geom_vline(xintercept=0, linetype="dashed", color = "red")+ ggtitle("Polarity of Rey Comments'") #Same codes for other characters "Finn" & "Poe" finn <- read.csv("finn_tweets.csv", encoding="UTF-8") tibblefinn<-as_tibble(finn) tibblefinn<-as.character(tibblefinn$content) tibblefinn tibblecontent d2<- tibble(txt = tibblefinn) d2 dat2 <- d2 %>% unnest_tokens(word, txt) dat2 unnested2 <- dat2 %>% anti_join(stop_words) count(unnested2, word, sort=TRUE) finn_counts <- dat2 %>% inner_join(get_sentiments("bing")) %>% count(word, sentiment, sort = TRUE) %>% ungroup() head(finn_counts,20) library(ggplot2) finn_counts %>% group_by(sentiment) %>% top_n(5) %>% ungroup() %>% mutate(word = reorder(word, n)) %>% ggplot(aes(word, n, fill = sentiment)) + geom_col(show.legend = FALSE) + facet_wrap(~sentiment, scales = "free_y") + labs(y = "Contribution to sentiment", x = NULL) + coord_flip() dat2 %>% inner_join(get_sentiments("bing")) %>% count(word, sentiment, sort = TRUE) %>% acast(word ~ sentiment, value.var = "n", fill = 0) %>% comparison.cloud(colors = c("blue", "red"), max.words = 100) finn_counts %>% group_by(sentiment) %>% spread(sentiment, n, fill = 0) %>% mutate(polarity = positive - negative) %>% filter(abs(polarity)<10) %>% ggplot(aes(polarity)) + geom_density(alpha = 0.3) + geom_vline(xintercept=0, linetype="dashed", color = "red")+ ggtitle("Polarity of 'Finn Comments'") #CODES FOR POE poe <- read.csv("poe_tweets_new.csv", encoding="UTF-8") tibblepoe<-as_tibble(poe) tibblepoe<-as.character(tibblepoe$content) tibblepoe d3 <- tibble(txt = tibblepoe) d3 dat3 <- d3 %>% unnest_tokens(word, txt) dat3 unnested3 <- dat3 %>% anti_join(stop_words) count(unnested, word, sort=TRUE) poe_counts <- dat3 %>% inner_join(get_sentiments("bing")) %>% count(word, sentiment, sort = TRUE) %>% ungroup() head(poe_counts,20) poe_counts %>% group_by(sentiment) %>% top_n(5) %>% ungroup() %>% mutate(word = reorder(word, n)) %>% ggplot(aes(word, n, fill = sentiment)) + geom_col(show.legend = FALSE) + facet_wrap(~sentiment, scales = "free_y") + labs(y = "Contribution to sentiment", x = NULL) + coord_flip() library(reshape2)#used for datawrangling using acast() function library(wordcloud) dat3 %>% inner_join(get_sentiments("bing")) %>% count(word, sentiment, sort = TRUE) %>% acast(word ~ sentiment, value.var = "n", fill = 0) %>% comparison.cloud(colors = c("red", "blue"), max.words = 100) poe_counts %>% group_by(sentiment) %>% spread(sentiment, n, fill = 0) %>% mutate(polarity = positive - negative) %>% filter(abs(polarity)<10) %>% ggplot(aes(polarity)) + geom_density(alpha = 0.3) + geom_vline(xintercept=0, linetype="dashed", color = "red")+ ggtitle("Polarity of 'Poe Comments'") <file_sep>/README.md Programming Project Summary Welcome to <NAME>'s project! In this repository, you will find an exciting exploration of network analysis using data related to the hashtag #theforceawakens from Twitter. The project consists of three files that contribute to the overall analysis. Preprocessing Codes (R File): This file contains the essential preprocessing codes in R, specifically designed to make the Java dataset compatible with gephi. By leveraging these preprocessing techniques, the dataset is refined and prepared for further analysis. Sentiment Analysis Codes (R File): Dive into the realm of sentiment analysis with this R file. It encapsulates the code snippets and methodologies employed to perform sentiment analysis on the collected Twitter data. Uncover the underlying sentiment patterns and gain valuable insights from this analysis. Graphs and Findings (PDF File): Explore the captivating visual representations and intriguing findings derived from the analysis. This PDF file provides an engaging summary of the graphs generated and the key discoveries made throughout the project. To initiate this project, a dataset related to network analysis was obtained from https://zenodo.org/record/1411479#.XshUABMzZ0v. Additionally, Twitter data under the hashtag #theforceawakens was collected using an API key, offering a rich and dynamic dataset to work with. Feel free to delve into the code, analyze the sentiment, and uncover the intricate network structures within the data. This project promises to provide a captivating journey through the world of network analysis and sentiment exploration. Enjoy the exploration, and may the force be with you!
2fb850e54b384295d61eeb7f6a918eb7f3c995a0
[ "Markdown", "R" ]
3
R
arzuyildirim/project
92196cd2ff4d63977dd6184c69b9c8ff7f17d5e0
f667cb3cc62069d335e1c28b2a1f60fe37e9c056
refs/heads/master
<repo_name>Bri997/grpc-go<file_sep>/go.mod module github.com/bri997/grpc-go-course/greet/hands-on go 1.12 require golang.org/x/tools/gopls v0.2.2 // indirect <file_sep>/calculator/calculator_client/client.go package main import ( "context" "fmt" "io" "log" "github.com/bri997/grpc-go-course/greet/hands-on/calculator/calculatorpb" "google.golang.org/grpc" ) func main() { fmt.Println("Hi cal client") cc, err := grpc.Dial("localhost:50051", grpc.WithInsecure()) if err != nil { log.Fatalf("could not connect: %v", err) } defer cc.Close() c := calculatorpb.NewCalculateServiceClient(cc) //doUnary(c) //doStreming(c) doClientStreaming(c) } func doUnary(c calculatorpb.CalculateServiceClient) { fmt.Println("starting to do a Unary RPC...") req := &calculatorpb.SumRequest{ Num1: 5, Num2: 10, } res, err := c.Sum(context.Background(), req) if err != nil { println("req =", req) log.Fatalf("error while calling Sum RPC: %v", err) } log.Printf("Response from Sum: %v", res.Result) } func doStreming(c calculatorpb.CalculateServiceClient) { fmt.Println("Starting the server Prime stream...") req := &calculatorpb.CalcPrimeRequest{ Number: 156546512, } stream, err := c.CalcPrime(context.Background(), req) if err != nil { log.Fatalf("Error while calling CalcPrime", err) } for { res, err := stream.Recv() if err == io.EOF { break } if err != nil { log.Fatalf("Problem for loop", err) } fmt.Println(res.GetPrimeFactor()) } } func doClientStreaming(c calculatorpb.CalculateServiceClient) { fmt.Println("Starting the Client Avg server Prime stream...") stream, err := c.CalcAverage(context.Background()) if err != nil { log.Fatalf("Err while opening stream ", err) } numbers := []int32{3, 5, 9, 54, 23} for _, number := range numbers { stream.Send(&calculatorpb.CalcAvgRequest{ Number: number, }) } res, err := stream.CloseAndRecv() if err != nil { log.Fatalf("Error while receiving response:..", err) } fmt.Printf("The average is: %v\n", res.GetAveResult()) } <file_sep>/calculator/calculator_server/server.go package main import ( "context" "fmt" "io" "log" "net" "github.com/bri997/grpc-go-course/greet/hands-on/calculator/calculatorpb" "google.golang.org/grpc" ) type server struct{} func (*server) Sum(ctx context.Context, req *calculatorpb.SumRequest) (*calculatorpb.SumResponse, error) { fmt.Printf("Cal function was invoked with %v\n", req) number1 := req.Num1 number2 := req.Num2 sum := number1 + number2 res := &calculatorpb.SumResponse{ Result: sum, } return res, nil } func (*server) CalcPrime(req *calculatorpb.CalcPrimeRequest, stream calculatorpb.CalculateService_CalcPrimeServer) error { fmt.Println("Cal-Prime server running", req) number := req.GetNumber() divisor := int32(2) for number > 1 { if number%divisor == 0 { stream.Send(&calculatorpb.CalcPrimeResponse{ PrimeFactor: divisor, }) number = number / divisor } else { divisor++ fmt.Println("Divisor has increased to \n", divisor) } } return nil } func (*server) CalcAverage(stream calculatorpb.CalculateService_CalcAverageServer) error { fmt.Printf("Calc Avergage was invoked with %v \n") sum := int32(0) count := 0 for { req, err := stream.Recv() if err == io.EOF { //Finished the average number stream aveResult := float64(sum) / float64(count) return stream.SendAndClose(&calculatorpb.CalcAvgResponse{ AveResult: aveResult, }) } if err != nil { log.Fatalf("Err while reading stream ", err) } sum += req.GetNumber() count++ } } func main() { fmt.Println("hi Cal") lis, err := net.Listen("tcp", "0.0.0.0:50051") if err != nil { log.Fatalf("fail %v", err) } s := grpc.NewServer() calculatorpb.RegisterCalculateServiceServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to server %v:", err) } calculatorpb.RegisterCalculateServiceServer(s, &server{}) if err := s.Serve(lis); err != nil { log.Fatalf("failed to server %v", err) } }
42b4642081d5183e524ed6490f03b0648f13cd10
[ "Go", "Go Module" ]
3
Go Module
Bri997/grpc-go
d8166aab2c350a09db950bf4d21a3a493dd8d942
232dc4d5ae45a6de25893d7223d7a4b5a66ca9a6
refs/heads/master
<repo_name>jamesninja/lab-express-basic-site<file_sep>/app.js const express = require("express"); // We create our own server named app // Express server will be handling requests and responses const app = express(); // our first Route // Make everything inside of public/ available app.use(express.static("public")); // our first Route: app.get("/home", (request, response, next) => response.sendFile(__dirname + "/views/home.html") ); // about route: app.get("/about", (request, response, next) => response.sendFile(__dirname + "/views/about.html") ); // work route: app.get("/work", (request, response, next) => response.sendFile(__dirname + "/views/work.html") ); // work route: app.get("/gallery", (request, response, next) => response.sendFile(__dirname + "/views/gallery.html") ); // ... the previously added code // Server Started app.listen(3000);
5d4dbb1bf52f2c45d9342aa771168d515d8ec405
[ "JavaScript" ]
1
JavaScript
jamesninja/lab-express-basic-site
43ef79af97a4f5e1b254632b824dcf2c18296787
63d3748428a1807f6f7fc7aac51434e2f8168eba
refs/heads/master
<file_sep>const { __ } = wp.i18n; const { registerBlockType, Editable, // I'm not using the InspectorControls or BlockControl but you can see the docs here https://wordpress.org/gutenberg/handbook/blocks/block-controls-toolbars-and-inspector/ BlockDescription, // and the BlockDescription source: { meta // I'm just using meta here, this only stores meta } } = wp.blocks; registerBlockType( 'grueziblock/faqmeta', { title: __( 'Hello faq meta!' ), // this is what shows in the blocks list icon: 'book', // you can pick different icons. there must be a list somewhere. this one is a book. category: 'common', // where do you want this to show up? this will be under "common" in the blocks attributes: { // so let's store a meta so people can add some text, maybe a url or whatever to the post someText: { type: 'string', // This is going to be a string. I think using this, you are limited to what register_meta can handle. source: 'meta', // This is going to come from postmeta meta: 'grueziblock_sometext', // this is the metakey registered in grueziblock.php } }, useOnce: true, // you can only add this once, soz // this is responsible for the editor side of things in wp-admin when you're making a post edit: props => { // focus on the someText bit as default const focusedEditable = props.focus ? props.focus.editable || null : null; const attributes = props.attributes; // the function which handles what happens when someText is changed const onChangeSomeText = value => { props.setAttributes( { someText: value } ); }; // the function which handles what happens when focus is on something const onFocusSomeText = focus => { props.setFocus( _.extend( {}, focus, { editable: 'someText' } ) ); }; // This is the bit that handles rendering in the editor // In the Gutenberg plugin, they return an array but I'm going to do it like the Gutenberg examples plugin and wrap it all in a div to return one node // // The Editable component's docs are here: https://wordpress.org/gutenberg/handbook/blocks/introducing-attributes-and-editable-fields/ // but you see that I'm putting "someText" in a p tag. It will fill the paragraph with whatever is the grueziblock_sometext meta value. // return ( <div> <div className={ props.className } key="editor-meta"> <p className="gruezi-info">Below is the Hello faq meta block. This bit won't save, it's just here fyi. I put a border around this block just for fun.</p> <Editable tagName="p" placeholder={ __( 'Please add some text, maybe a link to your blog or a note about why you are awesome.' ) } value={ attributes.someText } onChange={ onChangeSomeText } focus={ focusedEditable === 'someText' } onFocus={ onFocusSomeText } /> </div> </div> ); }, // This has a console log so you can see when it's running. save: props => { // This is so you can see when it runs. :) console.log( 'Hey! The save function in registerBlockType in the postmeta block just ran :) '); // This is returning nothing because registerBlockType handles saving the meta for you and you don't want to add anything to post_content return null; } } );<file_sep><?php /** * Recipes plugin for Health Lab Online. * * @author <NAME> <<EMAIL>> * @license MIT * @link https://tharshetests.wordpress.com * @copyright 2017 <NAME> * * Plugin Name: Hello Gutenberg! * Description: Cheap and cheerful examples of postmeta as I understand it. * Version: 0.1.0 * Author: <NAME> * License: MIT * License URI: https://opensource.org/licenses/MIT */ // this is the action you use to add scripts and styles to the editor. It doesn't add to the front end, just the editor. add_action( 'enqueue_block_editor_assets', 'grueziblock_scripts_and_styles' ); function grueziblock_scripts_and_styles() { wp_enqueue_script( 'grueziblock-content-block-js', plugin_dir_url( __FILE__ ) . 'blocks/postcontent-block.js', array( 'wp-blocks', 'wp-element' ), filemtime( plugin_dir_path( __FILE__ ) . 'blocks/postcontent-block.js' ) ); wp_enqueue_script( 'grueziblock-meta-block-js', plugin_dir_url( __FILE__ ) . 'blocks/postmeta-block.js', array( 'wp-blocks', 'wp-element' ), filemtime( plugin_dir_path( __FILE__ ) . 'blocks/postmeta-block.js' ) ); wp_enqueue_script( 'grueziblock-metafromregisterrestfield-block-js', plugin_dir_url( __FILE__ ) . 'blocks/metafromregisterrestfield-block.js', array( 'wp-blocks', 'wp-element', 'jquery', 'wp-api' ), filemtime( plugin_dir_path( __FILE__ ) . 'blocks/metafromregisterrestfield-block.js' ) ); wp_enqueue_style( 'grueziblock-css', plugin_dir_url( __FILE__ ) . 'grueziblock-editor.css', filemtime( plugin_dir_path( __FILE__ ) . 'grueziblock-editor.css' ) ); } // to use the source: meta in registerBlockType, the meta needs to be registered via register_meta which puts it in the meta object in the post json add_action( 'init', 'grueziblock_register_the_meta' ); function grueziblock_register_the_meta() { // this is for the grueziblock/faqmeta block in postmeta-block.jsx which uses source: 'meta' // and hey, this cannot be single => 'true' because Editable REALLY wants an array register_meta( 'post', // this is the object type so for cpts, it's still 'post' 'grueziblock_sometext', // metakey array( 'show_in_rest' => true, ) ); // the next bit, culminating in register_rest_field, is for the grueziblock/faqrestfield block in metafromregisterrestfield-block.jsx // but I've commented out register_block_type because I don't want it on the front end. it still works $schema = array( 'required' => false, 'description' => 'The place where the faq is applicable', // I don't know, whatever 'type' => 'string', ); $args = array( 'object' => 'post', // the object type 'attribute' => 'grueziblock_somewhere', // the meta key 'args' => array( // yeah yeah $args['args'] 'get_callback' => 'grueziblock_somewhere_get', // populate the field 'update_callback' => 'grueziblock_somewhere_update', // update the field 'schema' => $schema ) ); register_rest_field( $args['object'], $args['attribute'], $args['args'] ); // for use withAPIData // This determines what is saved to post_content and therefore shown on the front end. // In this case, I don't want it to save to post_content so I am commenting it out. // register_block_type( 'grueziblock/faqrestfield', array( // 'render_callback' => 'grueziblock_faqrestfield_render', // ) ); } // Again this can't be single => true because Editable only likes arrays function grueziblock_somewhere_get( $post_array ){ $metakey = 'grueziblock_somewhere'; $somewhere = get_post_meta( $post_array['id'], $metakey, true ); return strip_tags( $somewhere ); } function grueziblock_somewhere_update( $value, $post_object ){ $metakey = 'grueziblock_somewhere'; $somewhere = update_post_meta( $post_object->ID, $metakey, $value ); return $somewhere; // returns meta ID if the key didn't exist, true on successful update, false on failure } function grueziblock_faqrestfield_render( $attributes ) { return 'the server side render can be completely different to the editor'; } <file_sep>const { __ } = wp.i18n; const { registerBlockType, Editable } = wp.blocks; const{ Component } = wp.element; const { withAPIData } = wp.components; // What I'm trying to do here (because it is *not* obvious, I know): // Add a block which allows an entry in postmeta and registered via register_rest_field (rather than register_meta) to be shown and edited. // In this version, it does not save anything to post_content, I'm not using register_block_type in grueziblock.php (well it's there, just commented out) // It saves when save() runs and there's something in the field. Thus far this is only when I press the update button which is fine but might not be if someone relies on revisions? registerBlockType( 'grueziblock/faqrestfield', { title: __( 'Hello faq rest field :)' ), // this is what shows in the blocks list icon: 'dashicons-admin-home', // It's a house. https://developer.wordpress.org/resource/dashicons/#admin-home category: 'common', // This will be in the "common" tab in the blocks lists. attributes: { somewhere: {} // declaring the attribute here seems to make everything work a bit better, I mean, thinking about it this makes total sense doesn't it? }, useOnce: true, // You can only use this once, soz babe // this is responsible for the editor side of things in wp-admin when you're making a post // I'm using withAPIData https://github.com/WordPress/gutenberg/blob/master/docs/blocks-dynamic.md // better docs: https://github.com/WordPress/gutenberg/blob/master/components/higher-order/with-api-data/README.md edit: withAPIData( ( props ) => { let postId = _wpGutenbergPost.id; // I am picking this up from _wpGutenbergPost because it's there, wheeeeeeee. return { post: '/wp/v2/posts/' + postId + '/' // get the post we're editing }; } ) ( ( props ) => { // If there's no data yet, let people know if( ! props.post.data ) { return "loading (if you see this for too long, the endpoint is probably wrong)"; } // If there's no post, then tell someone! See something say something! if( props.post.data.length === 0 ){ return "no post!" } // what happens when we change the field? Well let's reset the attributes. const onChangeFaqField = value => { // why can't I use props.setAttributes here? I have it, it's right there. It's just not working. // why does this work? props.setAttributes({ somewhere: value.toString() }); // Editable and register_rest_field do *not* play nicely together } // It seems that it's entirely possible there's a race condition here with the Editable attribute trying to mount but props.attributes.somewhere hasn't been set // so let's check to make sure it's defined (empty is ok!), can we do it like this -- I mean this is working but I thought it was more complicated if( props.attributes.somewhere !== undefined ){ // the value is an array because of Editable and just it just is ok, leave me alone. I need to make it a string SHUT UP let theValue = ( props.attributes.somewhere ) ? [props.attributes.somewhere] : []; // jiggery pokery so the placeholder works return( <Editable tagName="p" className={ props.className } placeholder={ __( 'wait for it' ) } value={ theValue } onChange={ onChangeFaqField } /> ); } // Ok so tell me why props.setAttributes works here? Because it does! Weird. // TODO: revisit this because I might be doing something stupid if( props.attributes.somewhere === undefined ){ props.setAttributes({ somewhere: props.post.data.grueziblock_somewhere }); } // so if there's no props.attributes.somewhere then we're here return "how did we get here then?"; } ), save: ( props ) => { // this returns null! I'm using it to save the value without everything freaking out. return ( <GrueziblockSomewhereSave attributes = { props.attributes } /> ); } } ); class GrueziblockSomewhereSave extends Component { constructor( props ) { super( props ); } // I know I know but there's no component to mount! Maybe this should be in the constructor? componentWillMount () { let attributes = this.props.attributes; // console.log( 'ok try to save the value which is this: ' + attributes.somewhere ); let postId = _wpGutenbergPost.id; // I think if I had the revision id then I could save this too? // but this doesn't seem to be running for revisions? Which is ok I think because they are disabled on the host I think? I need to test this. // This is the published post (or the post id it will have it's published) // oh hey look! There's a revisions object in post data with count and last_id. // something to keep in mind console.log( attributes.somewhere ); let somewhere = ( attributes.somewhere ) ? attributes.somewhere : null; // the first time this is loaded, it's null // I need to check exactly when this is running because it doesn't seem to be running on autosave which makes sense? does it make sense? if( somewhere ){ let body = { grueziblock_somewhere: somewhere }; console.log( somewhere ); // props.post.patch(); // I'm so so so so so sorry, I'm skipping figuring out how the function above works, I am using jQuery just to move on. jQuery.ajax({ method: 'PATCH', url: '/wp-json/wp/v2/posts/' + postId + '/', data: body, beforeSend: function ( xhr ) { xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce ); }, }) .done( function ( data ){ console.log( 'phew, done' ); }) .fail( function( data ){ console.log( 'fail :(' ); console.log( data.responseJSON.message ); }); } } render() { // nothing to see here return ( null ); } } <file_sep># grueziblock This makes two WordPress Gutenberg blocks: "Hello faq" and "Hello faq meta!". There are a lot of comments which aim to show how to save and use postmeta in a block. The normal block which saves to post_content is in blocks/jsx/postcontent-block.jsx. The block which uses and saves to postmeta is in blocks/jsx/postmeta-block.jsx I think I've done it so that you can just use the plugin; copy it to your plugins folder and you're good to go. If you want to edit the blocks, edit the jsx files. These use [the Editable component](https://wordpress.org/gutenberg/handbook/blocks/introducing-attributes-and-editable-fields/). To play around with it: * clone the repo * run "npm install" * build using "grunt" * watch the jsx files with "grunt watch" Current issues relevant to meta: * [Deleting a block with meta attribute does not delete value in database](https://github.com/WordPress/gutenberg/issues/4054) * [Meta boxes: server side validation fails](https://github.com/WordPress/gutenberg/issues/3964)
c1185a1f0da59b7dd124ebc2db4c9650e78df496
[ "JavaScript", "Markdown", "PHP" ]
4
JavaScript
tharsheblows/grueziblock
7f2ae7cb6a519c86078ef0737edf239eb7bfbc8a
8b28d6ac214e698d0e6b2a33e4049b2d364a453a
refs/heads/master
<repo_name>allisonjulioo/WebRTCWithRecorderAudio<file_sep>/server_ssl.js // Load required modules const https = require("https"); const fs = require("fs"); const express = require("express"); const io = require("socket.io"); const bodyParser = require("body-parser"); const axios = require("axios"); const easyrtc = require("./lib/easyrtc_server"); // Setup and configure Express http server. Expect a subfolder called "static" to be the web root. const httpApp = express(); httpApp.use( bodyParser.json({ limit: "50mb", }) ); httpApp.use(express.static(__dirname + "/static/")); // Start Express https server on port 8443 const webServer = https.createServer( { key: fs.readFileSync(__dirname + "/certs/localhost.key"), cert: fs.readFileSync(__dirname + "/certs/localhost.crt"), }, httpApp ); // Start Socket.io so it attaches itself to Express server const socketServer = io.listen(webServer, { "log level": 1 }); // Start EasyRTC server easyrtc.events.on( "easyrtcAuth", (socket, easyrtcid, msg, socketCallback, callback) => { easyrtc.events.defaultListeners.easyrtcAuth( socket, easyrtcid, msg, socketCallback, (err, connectionObj) => { if (err || !msg.msgData || !msg.msgData.credential || !connectionObj) { callback(err, connectionObj); return; } connectionObj.setField("credential", msg.msgData.credential, { isShared: false, }); console.log( "[" + easyrtcid + "] Credential saved!", connectionObj.getFieldValueSync("credential") ); callback(err, connectionObj); } ); } ); // To test, lets print the credential to the console for every room join! easyrtc.events.on( "roomJoin", (connectionObj, roomName, roomParameter, callback) => { console.log( "[" + connectionObj.getEasyrtcid() + "] Credential retrieved!", connectionObj.getFieldValueSync("credential") ); easyrtc.events.defaultListeners.roomJoin( connectionObj, roomName, roomParameter, callback ); } ); const rtc = easyrtc.listen(httpApp, socketServer, null, (err, rtcRef) => { console.log("Initiated"); rtcRef.events.on( "roomCreate", (appObj, creatorConnectionObj, roomName, roomOptions, callback) => { console.log("roomCreate fired! Trying to create: " + roomName); appObj.events.defaultListeners.roomCreate( appObj, creatorConnectionObj, roomName, roomOptions, callback ); } ); }); httpApp.post("/recordings", async (req, res) => { if (!req.body) { return res.status(400).json({ error: "No req.body.message" }); } const { authorization } = req.headers; const { office_id, transaction_id, self, caller } = req.body; axios .post( `http://127.0.0.1:3333/api/office/post-office-recordings/`, { office_id, transaction_id, self, caller, }, { params: { transaction_id, office_id, }, headers: { Authorization: authorization, }, } ) .then(() => { res.status(200).json({ message: "Audio gravado com sucesso" }); }) .catch((error) => res.status(500).json({ message: "Algo deu errado", error }) ); }); // Listen on port 8443 webServer.listen(8443, "0.0.0.0", () => { console.log("listening on http://localhost:8443"); }); <file_sep>/README.md # How to run Instale as dependências com: `yarn` ou `npm install` Se quiser usar com dispositivos diferentes será necessário rodar com os certificados: `yarn server_ssl` ou `npm run server_ssl`. Se quiser usar com sem os certificados e apenas para teste, use: `yarn server` ou `npm run server`. ## Dicas Para habilitar os botões de gravação é necessário colocar o parametro id na url exemplo: [https://localhost:8443/?id=teste](https://localhost:8443/?id=teste), sem o parametro os botões não aparecem <file_sep>/static/index.js let selfEasyrtcid = ""; const supportsRecording = easyrtc.supportsRecording(); const url = new URL(window.location); const transaction_id = url.searchParams.get("transaction_id"); const office_id = url.searchParams.get("office_id"); const token = url.searchParams.get("token"); let audiosArr = []; const baseAudiosArr = []; let buttonStopRecording; let statusCall; let timerElement; let selfRecorder = null; let callerRecorder = null; let timmerRecording; let totalSeconds = 0; function connect() { easyrtc.enableVideo(false); easyrtc.enableVideoReceive(false); buttonStopRecording = document.getElementById("stopRecording"); timerElement = document.getElementById("timer"); statusCall = document.getElementById("inCall"); easyrtc.setRoomOccupantListener(getListUsersRoom); easyrtc.easyApp( "easyrtc.audioSimple", "selfVideo", ["callerVideo"], loginSuccess, loginFailure ); conenecteds(); } function loggedInListener(type, connections, conn) { if (!!Object.keys(connections).length) { startRecording(); } else { endRecording(); } checkPermissionMicrophone(); } function checkPermissionMicrophone() { navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia; if (navigator.getUserMedia) { navigator.getUserMedia( { audio: true, video: { width: 1280, height: 720 } }, function (stream) { console.log("Accessed the Microphone"); }, function (err) { console.log("The following error occured: " + err.name); } ); } else { console.log("getUserMedia not supported"); } } function performCall(otherEasyrtcid) { easyrtc.hangupAll(); var successCB = function () {}; var failureCB = function () {}; easyrtc.call(otherEasyrtcid, successCB, failureCB); } function getListUsersRoom(roomName, data, isPrimary) { for (var easyrtcid in data) { performCall(easyrtcid); } loggedInListener(roomName, data, isPrimary); } function conenecteds() { if (!office_id) { document.getElementById("action-buttons").remove(); } } function loginSuccess(easyrtcid) { selfEasyrtcid = easyrtcid; if (office_id) { document.getElementById("iam1").innerHTML = "Você"; } else { document.getElementById("iam2").innerHTML = "Operador"; } performCall(easyrtcid); } function loginFailure(errorCode, message) { easyrtc.showError(errorCode, message); } function startRecording() { selfRecorder = recordToFile(easyrtc.getLocalStream()); statusCall.classList.remove("ended"); document .querySelectorAll(".avatar") .forEach((avatar) => (avatar.style.backgroundColor = "#1e7e34")); statusCall.innerHTML = "Gravando"; statusCall.classList.add("active"); buttonStopRecording.classList.add("show"); if (easyrtc.getIthCaller(0)) { callerRecorder = recordToFile( easyrtc.getRemoteStream(easyrtc.getIthCaller(0), null) ); } else { callerRecorder = null; setTimeout(() => { clearInterval(timmerRecording); startRecording(); }, 2000); } timerElement.innerHTML = "Em chamada"; } function recordToFile(mediaStream) { function blobCallback(blob) { const videoURL = window.URL.createObjectURL(blob); getAudiosByBlobUrl(videoURL); } const mediaRecorder = easyrtc.recordToBlob(mediaStream, blobCallback); return mediaRecorder; } function getAudiosByBlobUrl(videoURL) { audiosArr.push(videoURL); if (audiosArr.length === 2) { audiosArr.map(async (blobUrl) => { let file = await fetch(blobUrl) .then((res) => res.blob()) .then( (blobFile) => new File([blobFile], `fileName`, { type: "audio/mp3", }) ); sendAudioFile(file); }); } } async function sendAudioFile(blob) { const reader = new window.FileReader(); reader.readAsDataURL(blob); reader.onloadend = () => saveAudios(reader.result); } function saveAudios(base64AudioMessage) { baseAudiosArr.push(base64AudioMessage); if (baseAudiosArr.length === 2 && office_id) { timer.innerHTML = "Salvando..."; statusCall.innerHTML = "Salvando gravação, não feche essa aba!"; fetch(`/recordings`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `JWT ${token}`, }, body: JSON.stringify({ self: baseAudiosArr[0], caller: baseAudiosArr[1], transaction_id, office_id, }), }) .then((res) => { console.log("Validate status saving audio message: " + res.status); window.close(); }) .catch((error) => { console.log("Invalid status saving audio message: " + error); window.close(); }); } } async function endRecording() { statusCall.classList.remove("active"); statusCall.innerHTML = " "; timer.innerHTML = "Estabelecendo conexão"; buttonStopRecording.classList.remove("show"); document.querySelectorAll(".avatar").forEach((avatar) => (avatar.style = "")); clearInterval(timmerRecording); totalSeconds = 0; const buttonError = document.querySelector(".easyrtcErrorDialog_okayButton"); if (buttonError) { setTimeout(() => buttonError.click(), 2000); console.log(buttonError); } if (selfRecorder) { selfRecorder.stop(); } if (callerRecorder) { callerRecorder.stop(); } }
3457c256994958eb68a48265ffea37227c08e6f1
[ "JavaScript", "Markdown" ]
3
JavaScript
allisonjulioo/WebRTCWithRecorderAudio
6a091be7a464d733df97689c53160080d5dad4a3
f259436f116e69e18e970ee8057826f4868072bf
refs/heads/master
<repo_name>jgalazm/Nami<file_sep>/examples/ModifyEarthquakeOnKeyPress/main.js let data = { bathymetry: [[1,1,1],[1,1,1],[1,1,1]] , earthquake: [{ L: 5, W: 3, depth: 2, slip: 1.0, strike: 30.0, dip: 70.0, rake: -45.0, U3: 1.0, cn: 0, ce: 0, reference: 'center' }], coordinates: 'cartesian', waveWidth: 512, waveHeight: 512, xmin: -10, xmax: 10, ymin: -10, ymax: 10 } let output = { stopTime: 10, displayWidth: 512, displayHeight: 512, }; let recordedBlobs = []; lifeCycle = { dataWasLoaded: (model) => { document.body.appendChild(model.canvas); }, modelStepDidFinish: (model, controller) => { console.log(model.discretization.stepNumber, model.currentTime); return false; } } let thisApp = new NAMI.app(data, output, lifeCycle); window.onkeydown = (ev)=>{ if(ev.key === 'ArrowUp' || ev.key === 'ArrowDown' ){ const sign = ev.key === 'ArrowUp'? +1: -1; const currentDepth = thisApp.model.earthquake[0].depth; const newDepth = Math.max(currentDepth + sign,1); const newSubfault = Object.assign(thisApp.model.earthquake[0], {depth: newDepth}); const newEarthquake = [newSubfault]; thisApp.model.earthquake = newEarthquake; const depthElement = document.getElementById('depth'); depthElement.innerHTML = `Current depth: ${newDepth} (m)`; console.log(depthElement.textContext); return; } console.log(ev.key); };<file_sep>/README.md # Installing dependencies After installing node.js just run ``` npm install ``` # Bundle build After running ``` npm run build ``` the bundle should be located at `build/nami.js`<file_sep>/examples/OffscreenCanvas/main.js let offscreen = new OffscreenCanvas(100,100); let data = { bathymetry: [[1,1,1],[1,1,1],[1,1,1]] , earthquake: [{ L: 5, W: 3, depth: 2, slip: 1.0, strike: 30.0, dip: 70.0, rake: -45.0, U3: 1.0, cn: 0, ce: 0, reference: 'center' }], coordinates: 'cartesian', waveWidth: 100, waveHeight: 100, xmin: -10, xmax: 10, ymin: -10, ymax: 10, canvas: offscreen } let output = { stopTime: 10, displayWidth: 512, displayHeight: 512, }; let recordedBlobs = []; lifeCycle = { dataWasLoaded: (model) => { console.log(offscreen); // offscreen.convertToBlob().then(function(blob) { // let video = document.getElementById('video'); // var superBuffer = new Blob(recordedBlobs, {type: 'video/webm'}); // video.src = window.URL.createObjectURL(superBuffer); // console.log(blob); // }); }, modelStepDidFinish: (model, controller) => { console.log(model.discretization.stepNumber); return false; } } let thismodel = new NAMI.app(data, output, lifeCycle); <file_sep>/src/__tests__/Reader.test.js import Reader from '../Reader'; 'Loads bathymetry from a javascript array' 'Loads bathymetry from a csv file' 'Loads bathymetry from a binary file' // it('Loads bathymetry from a javascript array', () => { // const data = { // bathymetry: [[1,1],[1,1]] // }; // const reader = new Reader(data); // expect(reader.bathymetry).toEqual(data.bathymetry); // });<file_sep>/examples/OffscreenCanvas/main2.js let canvas = document.getElementById('canvas'); var offscreen = canvas.transferControlToOffscreen(); var worker = new Worker("offscreen.js"); worker.postMessage({canvas: offscreen}, [offscreen]);<file_sep>/examples/slabs/main.js let w = 501; let h = 501; let slab = { 'x': [-7.5, 7.5], 'y': [0,0], 'depth': [22,-40], 'dip': [13, 13], 'strike': [-45, 45] } let data = { xmin : -15, xmax : 15, ymin : -15, ymax : 15, waveWidth: w, waveHeight: h, coordinates: 'spherical', bathymetry: [[1000,1000],[1000,1000]], earthquake: [{ depth: 22900, strike: 17, dip: 13.0, rake: 108.0, U3: 0.0, cn: 0, //centroid N coordinate, e ce: -5, Mw: 9.5, reference: 'mid bottom' }], slab: slab } let output = { displayWidth: w, displayHeight: h, stopTime: 60*60*15, displayOption: 'heights', }; let expectedOutput = 300; let lifeCycle = { dataWasLoaded: (model)=>{ document.body.appendChild(model.canvas); }, modelStepDidFinish: (model, controller) =>{ if(model.discretization.stepNumber % 10 === 0){ console.log(model.discretization.stepNumber); } if(model.discretization.stepNumber>800){ const ce = -model.earthquake[0].ce; model.earthquake = [{ depth: 22900, rake: 108.0, U3: 0.0, cn: 0, //centroid N coordinate, e ce: ce, Mw: 9.5, reference: 'mid bottom' }] } if(model.discretization.stepNumber % 10 !== 0){ return true; } return false; }, } let thisApp = new NAMI.app(data, output, lifeCycle); <file_sep>/examples/leaflet/main-leaflet.js var map = L.map('map').setView([37.8, -96], 4); L.tileLayer('https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?access_token={accessToken}', { attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>', maxZoom: 18, id: 'mapbox.streets', accessToken: '<KEY>' }).addTo(map); var bounds = L.latLngBounds([[32, -130], [13, -100]]); var videoElement = document.getElementById('videoTarget'); var videoOverlay = L.videoOverlay(videoElement, bounds, { opacity: 1.0 }).addTo(map); <file_sep>/src/Nami.js import {Controller} from './Controller'; import {Model} from './Model'; import Reader from './Reader'; let Nami = function(data, output, lifeCycle){ let model, controller; let init = () => { this.model = new Model(data, output); if (lifeCycle.dataWasLoaded !== undefined){ lifeCycle.dataWasLoaded(this.model); } this.controller = new Controller(this.model, output, lifeCycle); this.controller.animate(); } const reader = new Reader(data, init); } export default Nami; <file_sep>/examples/leaflet/simulation.js let data = { bathymetry: [[1,1,1],[1,1,1],[1,1,1]] , earthquake: [{ L: 5, W: 3, depth: 2, slip: 1.0, strike: 30.0, dip: 70.0, rake: -45.0, U3: 1.0, cn: 0, ce: 0, reference: 'center' }], coordinates: 'cartesian', waveWidth: 100, waveHeight: 100, xmin: -10, xmax: 10, ymin: -10, ymax: 10 } let output = { stopTime: 50, displayWidth: 512, displayHeight: 512, }; lifeCycle = { dataWasLoaded: (model) => { document.body.appendChild(model.canvas); model.canvas.style = 'position:absolute;left:-512px;'; video1 = document.getElementById('videoTarget'); var stream = model.canvas.captureStream(); video1.srcObject = stream; } } setTimeout(function(){ let thismodel = new NAMI.app(data, output, lifeCycle); }, 2000);<file_sep>/src/__tests__/Model.test.js "It loads a bathymetry array into a texture with a difference of less than 1%" "It loads an initial surface array into a texture to the shader with a difference of less than 1%" "It renders Okada initial condition properly, according to validation cases described in the paper" "It renders asteroid initial condition properly"
4010f3f0c11c6bcee83fc1da170d70ecfb7aefff
[ "JavaScript", "Markdown" ]
10
JavaScript
jgalazm/Nami
1ecfcdca9a0ee507bfdf4bec80ca65c02ebb2ead
3154c22950a1670312f09c298f30b924196f5380
refs/heads/master
<file_sep>import apiCall from '../utils/apiCall'; import { apiToken, baseUrl } from '../config'; import { IGiphyListResponse } from '../types/Giphy'; /** * Returns GIFs by 'trending' label * @param {Object} info Url information * @param {number} info.offset Starting position of the results * @param {Object} options Request options */ const getGiphyTrendings = async ( { offset }: { offset?:number }, options: RequestInit ): Promise<IGiphyListResponse> => { const response = await apiCall<IGiphyListResponse>(`${baseUrl}/trending?api_key=${apiToken}&offset=${offset}`, options); return response; }; export default getGiphyTrendings; <file_sep>const webpack = require('webpack'); const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const TerserPlugin = require('terser-webpack-plugin'); const sourcePath = path.join(__dirname, './src'); const distPath = path.join(__dirname, './dist'); module.exports = (env = {}) => { const isProduction = env.production === true; const environment = isProduction ? 'production' : 'development'; const publicPath = env.public_path || ''; return { // context: sourcePath, entry: { app: path.join(__dirname, './src/index.tsx'), }, output: { chunkFilename: isProduction ? '[name].[chunkhash].js' : '[name].js', filename: isProduction ? '[name].[chunkhash].js' : '[name].js', publicPath, path: distPath, }, optimization: { minimizer: [ new TerserPlugin({ cache: true, parallel: true, sourceMap: true, // set to true if you want JS source maps }), ], splitChunks: { cacheGroups: { // Split vendor code to its own chunk(s) vendors: { test: /[\\/]node_modules[\\/]/i, chunks: 'all', }, }, }, // The runtime should be in its own chunk runtimeChunk: { name: 'runtime', }, }, resolve: { extensions: ['.js', '.ts', '.tsx'], }, plugins: [ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: JSON.stringify(environment), APP_NAME: JSON.stringify(process.env.npm_package_config_appName), }, }), new HtmlWebpackPlugin({ template: path.join(__dirname, 'src/index.html'), filename: 'index.html', inject: 'body', }), ], module: { rules: [ { test: /\.(js|ts)x?$/, exclude: /(node_modules)/, use: [{ loader: 'babel-loader', }], }, { test: /\.(png|svg|jpg|jpeg|gif)$/, use: [{ loader: 'file-loader', options: { name: 'images/[name].[hash:8].[ext]' }, }], }, { test: /\.(woff|woff2|eot|ttf|otf)$/, use: [ 'file-loader', ], }, ], }, devtool: (() => { if (isProduction) return 'hidden-source-map'; return 'cheap-module-eval-source-map'; })(), devServer: { contentBase: path.join(__dirname, 'dist'), compress: true, port: 8769, hot: true, host: '0.0.0.0', liveReload: false, }, }; }; <file_sep>import apiCall from '../utils/apiCall'; import { apiToken, baseUrl } from '../config'; import { IGiphyListResponse } from '../types/Giphy'; /** * Returns metadata of multiple GIFs based on the GIF IDs specified * @param {Object} info Url information * @param {string} info.ids Specified gif IDs, separated by commas * @param {Object} options Request options */ const getGiphyByIds = async ( { ids }: { ids: string }, options: RequestInit ): Promise<IGiphyListResponse> => { const response = await apiCall<IGiphyListResponse>(`${baseUrl}?api_key=${apiToken}&ids=${ids}`, options); return response; }; export default getGiphyByIds; <file_sep>import { useState, useEffect } from 'react'; import getGiphyTrendings from '../api/getGiphyTrendings'; import getGiphySearch from '../api/getGiphySearch'; import getGiphyByIds from '../api/getGiphyByIds'; import { IGiphyItem, IGiphyPagination, IGiphyListResponse } from '../types/Giphy'; interface IUseGiphyList { error: boolean; isLoading: boolean; list: IGiphyItem[]; pagination: IGiphyPagination | null; } const useGiphyList = (type?: string, query?: string, offset?: number):IUseGiphyList => { const [isLoading, setLoading] = useState(true); const [error, setError] = useState(false); const [list, setList] = useState<IGiphyItem[]>([]); const [pagination, setPagination] = useState<IGiphyPagination | null>(null); useEffect(() => { const controller = new AbortController(); const fetchOptions = { signal: controller.signal }; const fetchData = async () => { try { let response: IGiphyListResponse; if (type === 'search' && query) { response = await getGiphySearch({ query, offset }, fetchOptions); } else if (type === 'ids' && query) { response = await getGiphyByIds({ ids: query }, fetchOptions); } else { response = await getGiphyTrendings({ offset }, fetchOptions); } setList(response.data); setPagination(response.pagination); setLoading(false); } catch(e) { setError(true); setLoading(false); } }; fetchData(); return () => controller.abort() }, [type, query, offset]); return { error, list, isLoading, pagination, }; }; export default useGiphyList; <file_sep>import {renderHook} from '@testing-library/react-hooks'; import { mocked } from 'ts-jest/utils'; import useGiphyList from './useGiphyList'; // import apiCall from '../utils/apiCall'; import getGiphyTrendings from '../api/getGiphyTrendings'; import getGiphySearch from '../api/getGiphySearch'; jest.mock('../api/getGiphyTrendings'); jest.mock('../api/getGiphySearch'); // jest.mock('../utils/apiCall'); const response = { data: [{ images: { fixed_width_downsampled: { webp: 'string', url: 'string', }, original: { webp: 'string', url: 'string', } }, id: '12345', title: 'string', source: 'string', user: { avatar_url: 'string', display_name: 'string', username: 'string', }, }], pagination: { count: 50, offset: 0, total_count: 100, }, }; describe('useGiphyList custom hook', () => { afterEach(() => { jest.clearAllMocks(); }); it('should update the state when api call is rejected', async () => { mocked(getGiphyTrendings).mockImplementationOnce(() => Promise.reject(new Error('error'))); const { result, waitForNextUpdate } = renderHook(() => useGiphyList()); await waitForNextUpdate(); expect(result.current).toEqual({ error: true, list: [], pagination: null, isLoading: false }); }); it('should make the api call to `trending` to fetch the default value and set it in the state', async () => { // mocked(apiCall).mockImplementationOnce(() => Promise.resolve([])); mocked(getGiphyTrendings).mockImplementationOnce(() => Promise.resolve(response)); const { result, waitForNextUpdate } = renderHook(() => useGiphyList()); expect(getGiphyTrendings).toHaveBeenCalled(); expect(result.current).toEqual({ error: false, list: [], pagination: null, isLoading: true }); await waitForNextUpdate(); }); it('should make the api call to `search` fetch the default value and set it in the state', async () => { // mocked(apiCall).mockImplementationOnce(() => Promise.resolve([])); mocked(getGiphySearch).mockImplementationOnce(() => Promise.resolve(response)); mocked(getGiphyTrendings).mockImplementationOnce(() => Promise.resolve(response)); const { result, waitForNextUpdate } = renderHook(() => useGiphyList('search', 'happy')); expect(getGiphySearch).toHaveBeenCalled(); // expect(getGiphyTrendings).not.toHaveBeenCalled(); expect(result.current).toEqual({ error: false, list: [], pagination: null, isLoading: true }); await waitForNextUpdate(); }); it('should update the state when api call is resolved', async () => { mocked(getGiphyTrendings).mockImplementationOnce(() => Promise.resolve(response)); const { result, waitForNextUpdate } = renderHook(() => useGiphyList()); await waitForNextUpdate(); expect(result.current).toEqual({ error: false, list: response.data, pagination: response.pagination, isLoading: false }); }); });<file_sep>import { useState, useEffect } from 'react'; import getGiphyDetails from '../api/getGiphyDetails'; import { IGiphyItem, IGiphyDetailsResponse } from '../types/Giphy'; interface IUseGiphyDetails { error: boolean; isLoading: boolean; item: IGiphyItem | null; } const useGiphyDetails = (id:string):IUseGiphyDetails => { const [isLoading, setLoading] = useState(true); const [error, setError] = useState(false); const [item, setItem] = useState<IGiphyItem | null>(null); useEffect(() => { const fetchData = async () => { try { const response: IGiphyDetailsResponse = await getGiphyDetails(id); setItem(response?.data); setLoading(false); } catch(e) { setError(true); setLoading(false); } }; fetchData(); }, [id]); return { error, item, isLoading, }; }; export default useGiphyDetails; <file_sep>import apiCall from './apiCall'; import fetchMock from 'fetch-mock-jest'; describe('apiCall test', () => { afterEach(() => { fetchMock.restore(); }); it('apiCall returns valid json', async () => { fetchMock.mock('validUrl', { status: 200, body: { message: 'hello world' }, }); const data = await apiCall('validUrl'); expect(data).toEqual({ message: 'hello world' }); }); it('apiCall throws error when gets not valid json', async () => { fetchMock.mock('validUrl', { status: 200, body: 'hello world', }); try { await apiCall('validUrl'); } catch (error) { expect(error instanceof Error).toEqual(true); expect(error.toString()).toMatch(/apiCall failed/) } }); it('apiCall throws error when response is not success', async () => { fetchMock.get('validUrl', { status: 404, }); try { await apiCall('validUrl'); } catch (error) { expect(error instanceof Error).toEqual(true); expect(error.toString()).toMatch(/apiCall failed with HTTP status 404/) } }); });<file_sep>export const apiToken = '<KEY>'; export const baseUrl = 'http://api.giphy.com/v1/gifs';<file_sep>export interface IGiphyItem { images: { fixed_width_downsampled: { webp: string, url: string, }, original: { webp: string, url: string, } }; id: string; title: string; source: string; user?: { avatar_url: string; display_name: string; username: string; }; } export interface IGiphyPagination { count: number; offset: number; total_count: number; } export interface IGiphyDetailsResponse { data: IGiphyItem; } export interface IGiphyListResponse { data: IGiphyItem[]; pagination: IGiphyPagination; } <file_sep>import apiCall from '../utils/apiCall'; import { apiToken, baseUrl } from '../config'; import { IGiphyDetailsResponse } from '../types/Giphy'; /** * Returns a GIF’s metadata based on the GIF ID specified * @param {Object} info Url information * @param {string} info.ids ID of the GIF you want details for * @param {Object} options Request options */ const getGiphyDetails = async (id?: string): Promise<IGiphyDetailsResponse> => { const response = await apiCall<IGiphyDetailsResponse>(`${baseUrl}/${id}?api_key=${apiToken}`); return response; }; export default getGiphyDetails; <file_sep>/** * Utilty function that makes a request to the enpoint and returns the response body * @param input Url of the resource * @param init Options for HTTP requests */ const apiCall = async<T>(input: RequestInfo, init?: RequestInit): Promise<T> => { try { const response: Response = await fetch(input, init); if (!response.ok) { throw new Error(`apiCall failed with HTTP status ${response.status}`); } const data = await response.json(); return data; } catch(error) { throw new Error(`apiCall failed: ${error}`); } } export default apiCall;<file_sep>import apiCall from '../utils/apiCall'; import { apiToken, baseUrl } from '../config'; import { IGiphyListResponse } from '../types/Giphy'; /** * Returns GIFs by term or phrase * @param {Object} info Url information * @param {number} info.query Search query term or phrase * @param {string} info.offset Starting position of the results * @param {Object} options Request options */ const getGiphySearch = async ( { query, offset }: { query?: string, offset?: number }, options: RequestInit ): Promise<IGiphyListResponse> => { const response = await apiCall<IGiphyListResponse>(`${baseUrl}/search?api_key=${apiToken}&q=${query}&offset=${offset}`, options); return response; }; export default getGiphySearch; <file_sep>const storageKey = 'favourites'; /** * Gets favourites list */ export const getFavourites = ():string => window.localStorage.getItem(storageKey) || ''; /** * Adds specified GIF to favourites * @param {string} id Id of GIF that have to added to favourites */ export const addToFavourites = (id: string):void => { const currentValue = getFavourites(); const currentArray = currentValue.split(','); const modifiedArray = [...currentArray, id]; const modifiedValue = modifiedArray.join(','); window.localStorage.setItem(storageKey, modifiedValue); }; /** * Removes specified GIF from favourites * @param {string} id Id of GIF that have to removed from favourites */ export const removeFromFavourites = (id: string):void => { const currentValue = getFavourites(); const currentArray = currentValue.split(','); const modifiedArray = currentArray.filter((item) => item !== id); const modifiedValue = modifiedArray.join(','); window.localStorage.setItem(storageKey, modifiedValue); }; /** * Check if specified GIF is added to favourites * @param {string} id Id of GIF that have to be checked */ export const checkIfFavourite = (id: string):boolean => { const currentValue = getFavourites(); const currentArray = currentValue.split(','); return currentArray.includes(id); };<file_sep># GIPHYBrowse A new UI for [GIPHY](https://giphy.com) (a service for finding GIFs) written in `react` and `typescript`. Key points 🤗 - Fetching data using react custom hooks. - Using `AbortController` react is able to abort `fetch` requests when the component unmounts, as well as before re-running the effect due to a subsequent render. - Search form and navigation is made with accessibility in mind. - Gallery made using css `grid`. - `<picture>` element used to show `WebP` whenever browers support it and fall back to legacy formats for clients that don't. - Clicking image in a gallery opens a modal on top of the gallery screen and the URL changes so the user can share URL and open details in new window too. Trade-offs 🧐 Due to lack of time some features are missing or could be improved. - Pagination could be improved with infinite scroll using `Intersection Observer`. - Not enough tests - only some of the components and services have basic tests written. - Favourites functionality is synchronous due to `localStorage` nature. For sure it would need to be rewriten to support async api calls. ## Installation In the project directory use `npm install` to install it on local machine. ## Available Scripts In the project directory, you can run: ### `npm start` Runs the app in the development mode. Open [http://localhost:8769](http://localhost:8769) to view it in the browser. The page will reload if you make edits. You will also see any code errors in the console. ### `npm run build` Builds the app for production to the `dist` folder. It correctly bundles React in production mode and optimizes the build for the best performance. ### `npm run lint` Launches code linting. - `npm run lint:js` using [ESLint](http://eslint.org) and [airbnb](https://github.com/airbnb/javascript) JS Style Guide. ### `npm test` Launches code testing.
19701fe230e75620099cf87d5a2b21d9b16459cb
[ "JavaScript", "TypeScript", "Markdown" ]
14
TypeScript
dpobozniak/giphy-browse
cb6987c5e072c33eb910fc2f6a6b801a17c50180
3b32e032e871c5d0346ba6eb0bf765f7063d0238
refs/heads/master
<file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Text.RegularExpressions; namespace zene { //------------------------------------- public class Track { private int _rad; private int _sec; private int _min; private string _name; public int Rad { get { return this._rad; } set { this._rad = value; } } public int Sec { get { return this._sec; } set { this._sec = value; } } public int Min { get { return this._min; } set { this._min = value; } } public string Name { get { return this._name; } set { this._name = value; } } public Track(int rad, int min, int sec, string name) { this._rad = rad; this._min = min; this._sec = sec; this._name = name; } } //----------------------- public class Repo { public List<Track> TrackList { get; set; } //1 public void ReadList(string readText) { string[] lines = System.IO.File.ReadAllLines(readText); lines = lines.Skip(1).ToArray(); TrackList = new List<Track>(); try { foreach (string line in lines) { string[] trackData = new string[4]; char[] sep = { ' ' }; trackData = line.Split(sep, 4); int Rad = Convert.ToInt32(trackData[0]); int Min = Convert.ToInt32(trackData[1]); int Sec = Convert.ToInt32(trackData[2]); string Name = trackData[3]; Track t = new Track(Rad, Min, Sec, Name); TrackList.Add(t); } } catch (Exception e) { Console.WriteLine("{0} error:", e); } Console.WriteLine("Sikeres beolvasas: '{0}'", readText); } //2. public void GroupByRadio() { for (int i = 1; i <= 3; i++) { Console.WriteLine("{0}. Ado : {1} szam", i, TrackList.Where(x => x.Rad == i).Count()); } } //3 public void ClaptonTime(string ec) { List<Track> listRadioOne = TrackList.FindAll(x => x.Rad == 1); var firstClapton = listRadioOne.Find (x => x.Name.Contains(ec)); var lastClapton = listRadioOne.FindLast(x => x.Name.Contains(ec)); var firstClaptonIndex = listRadioOne.FindIndex (i => i.Name == firstClapton.Name); var lastClaptonIndex = listRadioOne.FindIndex (i => i.Name == lastClapton.Name); var range = listRadioOne.GetRange(firstClaptonIndex, lastClaptonIndex - firstClaptonIndex); var time = 0; foreach (Track t in range) { time += t.Min * 60 + t.Sec; } time += lastClapton.Min * 60 + lastClapton.Sec; Console.WriteLine("Elso es utolso Clapton szam kozti ido 1. Adon:\n{0}", TimeConvert(time)); } //4 public void Omega(string omegaName) { var omegaObj = TrackList.Find(o => o.Name == omegaName); var omegaRadio = TrackList.Contains(omegaObj); Console.WriteLine("A(z) '{0}' szam a(z) {1}. adon volt hallhato", omegaName, omegaObj.Rad); List<Track> listRadioOne = TrackList.FindAll(x => x.Rad == 1); List<Track> listRadioTwo = TrackList.FindAll(x => x.Rad == 2); List<Track> listRadioThree = TrackList.FindAll(x => x.Rad == 3); var omegaIndex = listRadioThree.IndexOf(omegaObj); var omegaListRange = listRadioThree.GetRange(0, omegaIndex); int omegaTime = (TimePassed(omegaListRange)); string omegaTimeString = TimeConvert(omegaTime); Track elementOne = ListTime(listRadioOne, omegaTime); Track elementTwo = ListTime(listRadioTwo, omegaTime); Console.WriteLine(elementOne != null ? "1. adon hallhato szam: " + elementOne.Name : "1. adon nincs talalat"); Console.WriteLine(elementTwo != null ? "2. adon hallhato szam: " + elementTwo.Name : "2. adon nincs talalat"); } //5 public void SearchSms(string smsInput) { List<Track> searchList = TrackList.FindAll(s => s.Name.ToLower().Contains(smsInput)); string textFile = "keres.txt"; if (!File.Exists(textFile)) { string createText = smsInput + Environment.NewLine; File.WriteAllText(textFile, createText); } string minta = ".*"; for (int i = 0; i < smsInput.Length; i++) { minta = minta + Convert.ToString(smsInput[i]).ToLower() + ".*"; } Regex mint = new Regex(minta); foreach (Track t in TrackList) { if (mint.IsMatch(t.Name.ToLower())) { string appendText = t.Name + Environment.NewLine; File.AppendAllText(textFile, appendText); } } using (StreamReader sr = File.OpenText(textFile)) { string s = ""; Console.WriteLine("A(z) '{0}' allomany tartalma:", textFile); while ((s = sr.ReadLine()) != null) { Console.WriteLine(s); } } } //6 public void Change() { List<Track> listRadioOne = TrackList.FindAll(x => x.Rad == 1); int newTime = 180; int breakList = 3420; foreach (Track t in listRadioOne) { if (breakList < (t.Min * 60 + t.Sec + 60)) { newTime += breakList + 180; breakList = 3420; } newTime += t.Min * 60 + t.Sec + 60; breakList -= t.Min * 60 + t.Sec + 60; } string newList = TimeConvert(newTime); Console.WriteLine("Adas vege: {0}", newList); } //helper methods private int TimePassed(List<Track> list) { int listTime = 0; foreach (Track t in list) { int trackTime = 0; trackTime = t.Min * 60 + t.Sec; listTime += trackTime; } return listTime; } private string TimeConvert(int seconds) { TimeSpan time = TimeSpan.FromSeconds(seconds); string str = time.ToString(@"hh\:mm\:ss"); return str; } private Track ListTime(List<Track> searchedList, int searchedTime) { Track tmp = null; int listTime = 0; foreach (Track t in searchedList) { int trackTime = 0; trackTime = t.Min * 60 + t.Sec; listTime += trackTime; if (listTime > searchedTime) { tmp = t; break; } } return tmp; } } //-------------------------------------- class Program { static void Main(string[] args) { Repo repo = new Repo(); //1. Console.WriteLine("1. feladat:"); repo.ReadList("musor.txt"); //2. Console.WriteLine("2. feladat:"); repo.GroupByRadio(); //3 Console.WriteLine("3. feladat:"); repo.ClaptonTime("<NAME>"); //4 Console.WriteLine("4. feladat:"); repo.Omega("Omega:Legenda"); //5 Console.WriteLine("5. feladat:"); Console.Write("Irja be a keresett szoveget: "); string sms = Console.ReadLine(); repo.SearchSms(sms); //6 Console.WriteLine("6. feladat:"); repo.Change(); } } }
094f3078176e04c02b909ede26baad8849b66aa3
[ "C#" ]
1
C#
m4rt0n/zene
e6eba415022700c045f3a4daec085de69b158c8a
6d8c74b7de833b97cb8003b6dfa2599fc09d37ec
refs/heads/master
<file_sep>from __future__ import absolute_import, division, print_function, with_statement import socket from tornado.netutil import Resolver from tornado.testing import AsyncTestCase from tornado.test.util import unittest try: from concurrent import futures except ImportError: futures = None class _ResolverTestMixin(object): def test_localhost(self): self.resolver.getaddrinfo('localhost', 80, socket.AF_UNSPEC, socket.SOCK_STREAM, callback=self.stop) future = self.wait() self.assertIn( (socket.AF_INET, socket.SOCK_STREAM, socket.IPPROTO_TCP, '', ('127.0.0.1', 80)), future.result()) class SyncResolverTest(AsyncTestCase, _ResolverTestMixin): def setUp(self): super(SyncResolverTest, self).setUp() self.resolver = Resolver(self.io_loop) @unittest.skipIf(futures is None, "futures module not present") class ThreadedResolverTest(AsyncTestCase, _ResolverTestMixin): def setUp(self): super(ThreadedResolverTest, self).setUp() from concurrent.futures import ThreadPoolExecutor self.executor = ThreadPoolExecutor(2) self.resolver = Resolver(self.io_loop, self.executor) def tearDown(self): self.executor.shutdown() super(ThreadedResolverTest, self).tearDown()
2df09f09e46c6243b9d67762354f3ee03149e5ec
[ "Python" ]
1
Python
1stvamp/tornado
443c7f34b8eb5b77b82a04eb9b8575ad57744427
99b5f6378b994147b1fd74e87a6d9fa430a23681
refs/heads/master
<file_sep>import string import shutil alphabet = string.lowercase alphabet = list(alphabet) [shutil.rmtree(letter) for letter in alphabet]<file_sep>import string import os import shutil alphabet = string.lowercase alphabet = list(alphabet) #os.mkdir("test") [os.mkdir(letter) for letter in alphabet] #shutil.move("original_files/aexwin.txt", "a") for fn in os.listdir("original_files"): first_letter = fn[0] #print os.getcwd() sourcefile = "original_files/"+fn shutil.move(sourcefile, first_letter)
f2b2b79386c1ec747ee0f577bff919fe5d49efba
[ "Python" ]
2
Python
torypayne/Week1Project
ffa045ec3b9e97dfc9016e09d94762787b2aad52
faf9b14d3689fd6d016539591453f821e70f7a2e
refs/heads/master
<repo_name>challaruthvik/Playground<file_sep>/Hop n Hop/Main.java #include<iostream> using namespace std; int main() { int x,y,res1,res2; std::cin>>x>>y; res1=x-3; res2=y-4; if(res1>res2) std::cout<<res1; else std::cout<<res2; return 0; }<file_sep>/Car mileage/Main.java #include<iostream> using namespace std; int main() { float m,mm; int p,d; cin>>m>>p>>d; mm=m*p; if(mm>=d) cout<<"Can reach"; else cout<<"Cannot reach"; }<file_sep>/Harry Potter/Main.java #include<iostream> using namespace std; int main() { int n; cin>>n; int count=0;int r,x,y; while(n!=0) { r=n%10; n=n/10; if(count==0) { x=r; } count++; if(count==4) y=r; else y=0; } cout<<x+y; }<file_sep>/Dept Repay/Main.java #include<iostream> int main() { int p,t,r; float ff,fin,dis,in; std::cin>>p>>t>>r; in=(p*t*r)/100; ff=in+p; dis=in*2/100; fin=ff-dis; std::cout<<in<<"\n"; std::cout<<ff<<"\n"; std::cout<<dis<<"\n"; std::cout<<fin; return 0; }<file_sep>/Cricket/Main.java #include<iostream> #include<cmath> #include <iomanip> using namespace std; int main() { int tb,tr,rs,bb; float to,of,cr,trr; cin>>tb>>tr>>rs>>bb; to=tb/6; of=bb/6+(bb%6)/10.0; cr=(float)rs/of; trr=(float)tr/50; cout<<to<<"\n"; cout<<of<<"\n"; if(cr>10) cout<<setprecision(3)<<cr<<"\n"; else cout<<setprecision(2)<<cr<<"\n"; cout<<setprecision(2)<<trr<<"\n"; if(trr<cr) cout<<"Eligible to Win"; else cout<<"Not Eligible to Win"; }<file_sep>/Mango tree - I/Main.java #include<iostream> using namespace std; int main() { int row,col,tn; cin>>row>>col>>tn; if(tn<=row) cout<<"Yes"; else if (tn == 8) cout<<"No"; else if(tn==(row+1) || tn==(row+5) || tn==(row+6) || tn==(row+10) || tn==(row+11)) cout<<"Yes"; else cout<<"No"; }
5d97b636498c47b831a596bb7b97292c93af1271
[ "Java" ]
6
Java
challaruthvik/Playground
649ed7f3956fab7c06f04751abdf15e2c834748f
f4074d0586414c12333d0ede97fa7b1620637caf
refs/heads/master
<file_sep>package com.demo.plp.service; import com.demo.plp.dao.UserDao; import com.demo.plp.entity.Person; import com.demo.plp.model.PersonModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public Boolean login(PersonModel p) { return userDao.login(p); } public Boolean register(PersonModel p, Errors errors) { Boolean bool=userDao.register(p,errors); return bool; } public PersonModel editProfile(PersonModel person) { return userDao.editProfile(person); } public PersonModel getPerson(String emailId) { return userDao.getPerson(emailId); } } <file_sep>package com.demo.plp.model; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; import java.util.Date; import java.util.Set; @Entity @Table(name = "Flights") public class Flights { @Id @Column(name="flightNo") private int flightNo; @Column(name="source") private String source; @Column(name="destination") private String destination; @Column(name="time") private String time; @Column(name="duration") private float duration; @DateTimeFormat(pattern = "yyyy-MM-dd") @Column(name = "date") private Date date; public String getSource() { return source; } public void setSource(String source) { this.source = source; } public int getFlightNo() { return flightNo; } public void setFlightNo(int flightNo) { this.flightNo = flightNo; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } public Date getDate() { return date; } public void setDate(Date date) { this.date = date; } } <file_sep>package com.demo.plp.service; import com.demo.plp.entity.Bookings; import com.demo.plp.entity.Flights; import com.demo.plp.model.BookingsModel; import com.demo.plp.model.FlightsModel; import org.springframework.web.servlet.ModelAndView; public interface BookingService { ModelAndView bookingHistory(String email); ModelAndView book(BookingsModel bookings, FlightsModel flightsModel); ModelAndView cancelTicket(BookingsModel bookings); void deleteTicket(Integer ticketNo); } <file_sep>package com.demo.plp.web; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import com.demo.plp.entity.Bookings; import com.demo.plp.entity.Flights; import com.demo.plp.model.BookingsModel; import com.demo.plp.model.FlightsModel; import com.demo.plp.model.PersonModel; import com.demo.plp.service.BookingService; import com.demo.plp.service.FlightService; import com.demo.plp.service.UserService; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.ui.Model; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @Controller public class PersonController { @Autowired private SessionFactory sessionFactory; @Autowired private UserService userService; @Autowired private BookingService bookingService; @Autowired private FlightService flightService; public static final String LOGGED_IN_USER = "loggedInUser"; //TO REGISTER A NEW USER @RequestMapping(value="/addPerson.htm", method=RequestMethod.POST) public ModelAndView addPerson(PersonModel p, Errors errors) { Boolean bool = userService.register(p, errors); ModelAndView mav=new ModelAndView("addPerson"); if (bool == true) { //mav.setViewName("login"); mav.addObject("err", "false"); return mav; } mav.addObject("err", "true"); return mav; } @RequestMapping(value="/addPerson.htm") public ModelAndView addPerson(HttpServletRequest request) { ModelAndView mav = new ModelAndView("addPerson"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { return profile(request); } return mav; } //TO LOGIN A REGISTERED USER @RequestMapping(value="/login.htm", method=RequestMethod.POST) public ModelAndView login(HttpServletRequest request, PersonModel personToLogIn) { Boolean isLoginSuccess = userService.login(personToLogIn); PersonModel personModel = null; ModelAndView mav = new ModelAndView("login"); if (isLoginSuccess == true) { personModel = userService.getPerson(personToLogIn.getEmailId()); request.getSession().setAttribute("loggedInUser", personModel); mav.setViewName("profile"); mav.addObject("person", personModel); } return mav; } @RequestMapping(value="/login.htm",method = RequestMethod.GET) public ModelAndView login(HttpServletRequest request) { HttpSession session = request.getSession(); Object object = session.getAttribute(LOGGED_IN_USER); ModelAndView mav = new ModelAndView("login"); if (object != null && object instanceof PersonModel) { return profile(request); } return mav; } //TO LOGOUT A USER @RequestMapping(value="/logout.htm",method = RequestMethod.GET) public String logout(HttpServletRequest request) { request.getSession().invalidate(); return "login"; } //TO VIEW PROFILE OF A USER AFTER LOGIN @RequestMapping(value="/profile.htm") public ModelAndView profile(HttpServletRequest request) { ModelAndView mav = new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { mav.setViewName("profile"); mav.addObject("person", object); return mav; } return mav; } //TO VIEW AVAILABLE FLIGHTS @Transactional @RequestMapping("/flights.htm") public ModelAndView flights(HttpServletRequest request) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { PersonModel loggedInUser = (PersonModel)object; mav=new ModelAndView("flights"); } //List<Flights> flights=sessionFactory.getCurrentSession().createQuery("From Flights").list(); //mav.addObject("flights",flights); return mav; } //TO BOOK A FLIGHT FOR SOMEONE ELSE @RequestMapping(value = "/other.htm", method = RequestMethod.POST) public ModelAndView book(HttpServletRequest request, BookingsModel bookings, FlightsModel flights) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { PersonModel loggedInUser = (PersonModel)object; String email =loggedInUser.getEmailId(); bookings.setEmailId(email); bookingService.book(bookings,flights); mav=bookingService.bookingHistory(email); } return mav; } //TO BOOK A FLIGHT FOR SOMEONE ELSE @RequestMapping(value = "/self.htm", method = RequestMethod.POST) public ModelAndView bookForSelf(HttpServletRequest request, BookingsModel bookings, FlightsModel flightsModel) { String error="Booking failed"; Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { PersonModel loggedInUser = (PersonModel)object; String email =loggedInUser.getEmailId(); bookings.setEmailId(email); bookings.setName(loggedInUser.getName()); bookings.setAge(loggedInUser.getAge()); bookingService.book(bookings,flightsModel); ModelAndView mav=bookingService.bookingHistory(email); return mav; } ModelAndView mav=new ModelAndView("flights"); return mav.addObject("error",error); } //TO VIEW THE FLIGHT BOOKING HISTORY @RequestMapping(value = "/bookingHistory.htm", method = RequestMethod.GET) public ModelAndView bookingHistory(HttpServletRequest request) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { PersonModel loggedInUser = (PersonModel)object; String email =loggedInUser.getEmailId(); mav=bookingService.bookingHistory(email); } return mav; } @RequestMapping(value = "/bookingHistory.htm", method = RequestMethod.POST) public ModelAndView bookingHistoryCancel(HttpServletRequest request,BookingsModel bookings) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { PersonModel loggedInUser = (PersonModel) object; String email = loggedInUser.getEmailId(); bookingService.cancelTicket(bookings); mav = bookingService.bookingHistory(email); } return mav; } //TO DELETE A PARTICULAR TICKET FOR A PARTICULAR DETAILS @RequestMapping(value = "/delete.htm", method = RequestMethod.POST) public ModelAndView deleteTicket(HttpServletRequest request,Integer ticketNo) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { PersonModel loggedInUser = (PersonModel) object; String email = loggedInUser.getEmailId(); bookingService.deleteTicket(ticketNo); mav = bookingService.bookingHistory(email); } //mav.addObject("bookings",bookings ); return mav; } //TO SEARCH FLIGHTS FOR A PARTICULAR DATE , SOuRCE, DESTINATION @RequestMapping("/searchFlights.htm") public ModelAndView searchFlights(HttpServletRequest request) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { mav = flightService.searchFlights(); return mav; } return mav; } @RequestMapping(value = "/searchFlights.htm",method = RequestMethod.POST) public ModelAndView searchFlights(HttpServletRequest request,FlightsModel flights) { /*SimpleDateFormat f = new SimpleDateFormat("dd-MMM-yyyy"); Date d= null; try { d = f.parse(String.valueOf(flights.getDate())); } catch (ParseException e) { e.printStackTrace(); } long milliseconds = d.getTime(); flights.setDate(milliseconds);*/ ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof PersonModel) { mav = flightService.flights(flights); } return mav; } //TO EDIT USERS PROFILE TO ADD ADDRESS DETAILS @RequestMapping(value = "/editProfile.htm", method=RequestMethod.GET) public ModelAndView editProfile (HttpServletRequest request) { String error="NO_USER_IN_SESSION"; Object object = request.getSession().getAttribute(LOGGED_IN_USER); ModelAndView mav = new ModelAndView("login"); if (object != null && object instanceof PersonModel) { mav.setViewName("editProfile"); PersonModel person = (PersonModel) object; String emailId=person.getEmailId(); return mav.addObject("person", userService.getPerson(emailId)); } mav.addObject(error); return mav; } @RequestMapping(value = "/editProfile.htm", method=RequestMethod.POST) public ModelAndView editProfile (HttpServletRequest request,PersonModel person) { ModelAndView mav = new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object instanceof PersonModel) { mav.setViewName("editProfile"); PersonModel loggedInUser = (PersonModel) object; String email = loggedInUser.getEmailId(); person.setEmailId(email); mav.addObject("person", userService.editProfile(person)); } return mav; } /*@RequestMapping(value="/passengerDetails.htm",method = RequestMethod.GET) public String passengerDetails() { final ModelAndView view = getFlights(); return "passengerDetails"; }*/ /*@RequestMapping(value="/other.htm",method = RequestMethod.POST) public ModelAndView passengerDetailsOther(Bookings person) { ModelAndView mav=userService.passengerDetailsOther(person); return mav; }*/ } /* @RequestMapping("/allPersons.htm") public ModelAndView allPersons() { List<PersonModel> persons = sessionFactory.getCurrentSession(). createQuery("FROM PersonModel").list(); ModelAndView mav = new ModelAndView("allPersons"); mav.addObject("persons", persons); return mav; }*/ <file_sep>package com.demo.plp.entity; import com.demo.plp.model.BookingsModel; import javax.persistence.*; @Entity @Table(name = "Bookings") public class Bookings { @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name = "ticketNo") private int ticketNo; @Column(name = "emailId") private String emailId; // @Column(name = "flightNo", insertable = false,updatable = false) // private int flightNo; @Column(name = "status") private int status; @Column(name = "name") private String name; @Column(name = "age") private int age; @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = "flightNo") private Flights flights; public Flights getFlights() { return flights; } public void setFlights(Flights flights) { this.flights = flights; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getTicketNo() { return ticketNo; } public void setTicketNo(int ticketNo) { this.ticketNo = ticketNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } /* public int getFlightNo() { return flightNo; } public void setFlightNo(int flightNo) { this.flightNo = flightNo; }*/ public Bookings() { } public Bookings(BookingsModel bookingsModel){ this.age=bookingsModel.getAge(); this.emailId=bookingsModel.getEmailId(); this.name=bookingsModel.getName(); this.status=bookingsModel.getStatus(); this.ticketNo=bookingsModel.getTicketNo(); this.flights=new Flights(bookingsModel.getFlights()); } } <file_sep>jdbc.databaseName=FlightBooking jdbc.connectionUrl=jdbc:postgresql://localhost:5433/${jdbc.databaseName} jdbc.username=postgres jdbc.password=<PASSWORD><file_sep>package com.flightdetails.a8113.springbootflight; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication(scanBasePackages = {"com.flightdetails.a8113.springbootflight"}) public class SpringBootFlightApplication { public static void main(String[] args) { SpringApplication.run(SpringBootFlightApplication.class, args); } } <file_sep>package com.demo.plp.service; import com.demo.plp.dao.UserDao; import com.demo.plp.model.Bookings; import com.demo.plp.model.Flights; import com.demo.plp.model.Person; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import java.security.Principal; @Service @Transactional public class UserServiceImpl implements UserService { @Autowired private UserDao userDao; public ModelAndView login(Person p){ ModelAndView mav=userDao.login(p); return mav; } public ModelAndView register(Person p, Errors errors) { ModelAndView mav=userDao.register(p,errors); return mav; } public ModelAndView editProfile(Person person) { return userDao.editProfile(person); } public ModelAndView getPerson(String emailId) { return userDao.getPerson(emailId); } } <file_sep>package com.demo.plp.model; import com.demo.plp.entity.Person; public class PersonModel { private String emailId; private String name; private int age; private String password; private PersonDetailsModel personDetailsModel; public PersonModel () { } public PersonModel (Person person) { this.emailId = person.getEmailId(); this.name = person.getName(); this.age = person.getAge(); this.password = person.getPassword(); this.personDetailsModel = new PersonDetailsModel(person.getPersonDetails()); } public PersonDetailsModel getPersonDetailsModel() { return personDetailsModel; } public void setPersonDetailsModel(PersonDetailsModel personDetailsModel) { this.personDetailsModel = personDetailsModel; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } public String getPassword() { return password; } public void setPassword(String password) { this.password = <PASSWORD>; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } } <file_sep>package com.demo.plp.dao; import com.demo.plp.entity.Flights; import com.demo.plp.model.FlightsModel; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; import java.util.List; @Repository @Transactional public class FlightDaoImpl implements FlightDao{ @Autowired SessionFactory sessionFactory; public ModelAndView searchFlights() { List<Flights> flights = sessionFactory.getCurrentSession(). createQuery("select distinct source,destination FROM Flights").list(); ModelAndView mav=new ModelAndView("searchFlights"); mav.addObject("flights",flights); return mav; } public ModelAndView flights(FlightsModel flightsModel) { // String source=flights.getSource(); // String destination=flights.getDestination(); // //SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd-mm-yyyy"); // // // String dateString= flights.getDate().toString(); // long date=flights.getDate(); Flights flights = new Flights(flightsModel); //flights.setDate(date); List<Flights> flightsList=(ArrayList)new ArrayList<Flights>(); List<FlightsModel> flightsModelList=new ArrayList<>(); Query query=sessionFactory.getCurrentSession().createQuery("FROM Flights where source=:source and destination=:destination and date=:date"); query.setParameter("source",flights.getSource()); query.setParameter("destination",flights.getDestination()); query.setParameter("date",flights.getDate()); flightsList = query.list(); for(Flights item:flightsList){ FlightsModel flightsModel1=new FlightsModel(item); flightsModelList.add(flightsModel1); } // List<FlightsModel> flightsModelList=new ArrayList(flightsList); //flightsModelList.add((FlightsModel) flightsList); ModelAndView mav = new ModelAndView("flights"); mav.addObject("flights",flightsModelList ); return mav; } } <file_sep>package com.demo.plp.service; import com.demo.plp.model.Bookings; import com.demo.plp.model.Flights; import com.demo.plp.model.Person; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import java.security.Principal; import java.util.List; public interface UserService { ModelAndView login(Person p); ModelAndView register(Person p, Errors errors); ModelAndView editProfile(Person person); ModelAndView getPerson(String emailid); } <file_sep>package com.demo.plp.service; import com.demo.plp.dao.FlightDao; import com.demo.plp.model.Flights; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.ModelAndView; @Service @Transactional public class FlightServiceImpl implements FlightService { @Autowired FlightDao flightDao; public ModelAndView searchFlights() { ModelAndView mav=flightDao.searchFlights(); return mav; } public ModelAndView flights(Flights flights) { ModelAndView mav=flightDao.flights(flights); return mav; } } <file_sep>package com.demo.plp.model; import com.demo.plp.entity.Bookings; import javax.persistence.*; public class BookingsModel { private int ticketNo; private String emailId; private int status; private String name; private int age; private FlightsModel flights; public BookingsModel(){ } public BookingsModel(Bookings bookings){ this.age=bookings.getAge(); this.emailId=bookings.getEmailId(); this.name=bookings.getName(); this.status=bookings.getStatus(); this.ticketNo=bookings.getTicketNo(); this.flights=new FlightsModel(bookings.getFlights()); } public FlightsModel getFlights() { return flights; } public void setFlights(FlightsModel flights) { this.flights = flights; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getStatus() { return status; } public void setStatus(int status) { this.status = status; } public int getTicketNo() { return ticketNo; } public void setTicketNo(int ticketNo) { this.ticketNo = ticketNo; } public String getEmailId() { return emailId; } public void setEmailId(String emailId) { this.emailId = emailId; } /* public int getFlightNo() { return flightNo; } public void setFlightNo(int flightNo) { this.flightNo = flightNo; }*/ } <file_sep>package com.demo.plp.dao; import com.demo.plp.entity.Bookings; import com.demo.plp.entity.Flights; import com.demo.plp.model.BookingsModel; import com.demo.plp.model.FlightsModel; import org.hibernate.Criteria; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.criterion.Restrictions; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.ModelAndView; import java.util.ArrayList; import java.util.List; @Repository @Transactional public class BookingDaoImpl implements BookingDao{ @Autowired SessionFactory sessionFactory; public ModelAndView bookingHistory(String email) { //Query query=sessionFactory.getCurrentSession(). /*Query query =sessionFactory.getCurrentSession().createQuery("FROM Bookings bks where bks.emailId=:email"); //createQuery("FROM Bookings INNER JOIN Flights ON Bookings.flightNo=Flights.flightNo where Bookings.emailId='<EMAIL>' and Bookings.status=1"); List<?> bookings=query.list(); query.setParameter("email",email);*/ ModelAndView mav = new ModelAndView("bookingHistory"); Criteria bookingCriteria = sessionFactory.getCurrentSession().createCriteria(Bookings.class); bookingCriteria.add(Restrictions.eq("emailId", email)); List<Bookings> bookingList = bookingCriteria.list(); List<BookingsModel> bookingsModelsList=new ArrayList<>(); for(Bookings item:bookingList){ BookingsModel bookingsModel=new BookingsModel(item); bookingsModelsList.add(bookingsModel); } /* for(Bookings bookings:bookingList){ bookings.getFlights().toString(); }*/ if (bookingCriteria != null) { mav.addObject("bookings", bookingsModelsList); } return mav; } public ModelAndView book(BookingsModel bookingsModel, FlightsModel flightsModel) { int status=1; Flights flights = new Flights(flightsModel); Flights flightFromDB = (Flights) sessionFactory.getCurrentSession().get(Flights.class, flights.getFlightNo()); bookingsModel.setFlights(new FlightsModel(flightFromDB)); bookingsModel.setStatus(status); sessionFactory.getCurrentSession().save(new Bookings(bookingsModel)); ModelAndView mav = null; return mav; } public ModelAndView cancelTicket(BookingsModel bookings) { int ticketNo=bookings.getTicketNo(); Query query= sessionFactory.getCurrentSession().createQuery("update Bookings set status=0 where ticketNo=:ticketNo"); query.setParameter("ticketNo",ticketNo); query.executeUpdate(); ModelAndView mav = new ModelAndView("bookingHistory"); mav.addObject("bookings",bookings ); return mav; } public void deleteTicket(Integer ticketNo) { Query query= sessionFactory.getCurrentSession().createQuery("delete from Bookings where ticketNo=:ticketNo"); query.setParameter("ticketNo",ticketNo); query.executeUpdate(); } } <file_sep>package com.demo.plp.web; import java.util.List; import com.demo.plp.dao.UserDao; import com.demo.plp.model.Bookings; import com.demo.plp.model.Flights; import com.demo.plp.model.PersonDetails; import com.demo.plp.service.BookingService; import com.demo.plp.service.FlightService; import com.demo.plp.service.UserService; import com.sun.org.apache.xpath.internal.operations.Mod; import org.hibernate.Query; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.SessionAttributes; import org.springframework.web.servlet.ModelAndView; import com.demo.plp.model.Person; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; @Controller public class PersonController { @Autowired private SessionFactory sessionFactory; @Autowired private UserService userService; @Autowired private BookingService bookingService; @Autowired private FlightService flightService; public static final String LOGGED_IN_USER = "loggedInUser"; //TO REGISTER A NEW USER @RequestMapping(value="/addPerson.htm", method=RequestMethod.POST) public ModelAndView addPerson(Person p, Errors errors) { ModelAndView mav=userService.register(p,errors); return mav; } @RequestMapping(value="/addPerson.htm") public ModelAndView addPerson(HttpServletRequest request) { ModelAndView mav = new ModelAndView("addPerson"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { return profile(request); } return mav; } //TO LOGIN A REGISTERED USER @RequestMapping(value="/login.htm", method=RequestMethod.POST) public ModelAndView login(HttpServletRequest request, Person p) { ModelAndView mav = userService.login(p); ModelAndView mavPerson=userService.getPerson(p.getEmailId()); // Saving logged in user to session p = (Person) mavPerson.getModel().get("person"); if (p != null) { request.getSession().setAttribute("loggedInUser", p); } else { mav.setViewName("login"); } return mav; } @RequestMapping(value="/login.htm",method = RequestMethod.GET) public ModelAndView login(HttpServletRequest request) { HttpSession session = request.getSession(); Object object = session.getAttribute(LOGGED_IN_USER); ModelAndView mav = new ModelAndView("login"); if (object != null && object instanceof Person) { return profile(request); } return mav; } //TO LOGOUT A USER @RequestMapping(value="/logout.htm",method = RequestMethod.GET) public String logout(HttpServletRequest request) { request.getSession().invalidate(); return "login"; } //TO VIEW PROFILE OF A USER AFTER LOGIN @RequestMapping(value="/profile.htm") public ModelAndView profile(HttpServletRequest request) { ModelAndView mav = new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { mav.setViewName("profile"); mav.addObject("person", object); return mav; } return mav; } //TO VIEW AVAILABLE FLIGHTS @Transactional @RequestMapping("/flights.htm") public ModelAndView flights(HttpServletRequest request) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person)object; mav=new ModelAndView("flights"); } //List<Flights> flights=sessionFactory.getCurrentSession().createQuery("From Flights").list(); //mav.addObject("flights",flights); return mav; } //TO BOOK A FLIGHT FOR SOMEONE ELSE @RequestMapping(value = "/other.htm", method = RequestMethod.POST) public ModelAndView book(HttpServletRequest request,Bookings bookings, Flights flights) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person)object; String email =loggedInUser.getEmailId(); bookings.setEmailId(email); bookingService.book(bookings,flights); mav=bookingService.bookingHistory(email); } return mav; } //TO BOOK A FLIGHT FOR SOMEONE ELSE @RequestMapping(value = "/self.htm", method = RequestMethod.POST) public ModelAndView bookForSelf(HttpServletRequest request, Bookings bookings, Flights flights) { String error="Booking failed"; Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person)object; String email =loggedInUser.getEmailId(); bookings.setEmailId(email); bookings.setName(loggedInUser.getName()); bookings.setAge(loggedInUser.getAge()); bookingService.book(bookings,flights); ModelAndView mav=bookingService.bookingHistory(email); return mav; } ModelAndView mav=new ModelAndView("flights"); return mav.addObject("error",error); } //TO VIEW THE FLIGHT BOOKING HISTORY @RequestMapping(value = "/bookingHistory.htm", method = RequestMethod.GET) public ModelAndView bookingHistory(HttpServletRequest request) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person)object; String email =loggedInUser.getEmailId(); mav=bookingService.bookingHistory(email); } return mav; } @RequestMapping(value = "/bookingHistory.htm", method = RequestMethod.POST) public ModelAndView bookingHistoryCancel(HttpServletRequest request,Bookings bookings) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person) object; String email = loggedInUser.getEmailId(); bookingService.cancelTicket(bookings); mav = bookingService.bookingHistory(email); } return mav; } //TO DELETE A PARTICULAR TICKET FOR A PARTICULAR DETAILS @RequestMapping(value = "/delete.htm", method = RequestMethod.POST) public ModelAndView deleteTicket(HttpServletRequest request,Integer ticketNo) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person) object; String email = loggedInUser.getEmailId(); bookingService.deleteTicket(ticketNo); mav = bookingService.bookingHistory(email); } //mav.addObject("bookings",bookings ); return mav; } //TO SEARCH FLIGHTS FOR A PARTICULAR DATE , SOuRCE, DESTINATION @RequestMapping("/searchFlights.htm") public ModelAndView searchFlights(HttpServletRequest request) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { mav = flightService.searchFlights(); return mav; } return mav; } @RequestMapping(value = "/searchFlights.htm",method = RequestMethod.POST) public ModelAndView searchFlights(HttpServletRequest request,Flights flights) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { mav = flightService.flights(flights); } return mav; } //TO EDIT USERS PROFILE TO ADD ADDRESS DETAILS @RequestMapping(value = "/editProfile.htm", method=RequestMethod.GET) public ModelAndView editProfile (HttpServletRequest request) { String error="NO_USER_IN_SESSION"; Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person person = (Person) object; String emailId=person.getEmailId(); return userService.getPerson(emailId); } ModelAndView mav=new ModelAndView("login"); mav.addObject(error); return mav; } @RequestMapping(value = "/editProfile.htm", method=RequestMethod.POST) public ModelAndView editProfile (HttpServletRequest request,Person person) { ModelAndView mav=new ModelAndView("login"); Object object = request.getSession().getAttribute(LOGGED_IN_USER); if (object != null && object instanceof Person) { Person loggedInUser = (Person) object; String email = loggedInUser.getEmailId(); person.setEmailId(email); mav = userService.editProfile(person); } return mav; } /*@RequestMapping(value="/passengerDetails.htm",method = RequestMethod.GET) public String passengerDetails() { final ModelAndView view = getFlights(); return "passengerDetails"; }*/ /*@RequestMapping(value="/other.htm",method = RequestMethod.POST) public ModelAndView passengerDetailsOther(Bookings person) { ModelAndView mav=userService.passengerDetailsOther(person); return mav; }*/ } /* @RequestMapping("/allPersons.htm") public ModelAndView allPersons() { List<Person> persons = sessionFactory.getCurrentSession(). createQuery("FROM Person").list(); ModelAndView mav = new ModelAndView("allPersons"); mav.addObject("persons", persons); return mav; }*/ <file_sep>package com.demo.plp.dao; import com.demo.plp.model.Bookings; import com.demo.plp.model.Flights; import com.demo.plp.model.Person; import com.demo.plp.model.PersonDetails; import org.hibernate.Query; import org.hibernate.SessionFactory; import org.hibernate.exception.ConstraintViolationException; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import org.springframework.validation.Errors; import org.springframework.web.servlet.ModelAndView; import java.sql.SQLException; import java.util.ArrayList; import java.util.Date; import java.util.List; @Repository @Transactional public class UserDaoImpl implements UserDao{ @Autowired private SessionFactory sessionFactory; public ModelAndView login(Person p){ String errorInvalid="INVALID_USER"; String email=p.getEmailId(); String password=p.<PASSWORD>(); ModelAndView mav = new ModelAndView("profile"); // ModelAndView mavError=new ModelAndView("login"); // List<Person> personList=new ArrayList<Person>(); try { /* Query query = sessionFactory.getCurrentSession().createQuery("FROM Person where emailId=:email and password=:password"); query.setParameter("email", email); query.setParameter("password", password); personList = query.list();*/ Person person = (Person) sessionFactory.getCurrentSession().get(Person.class, email); if (person != null && person.getPassword().equals(password)) { mav.addObject("person", person); } else { mav.setViewName("login"); mav.addObject("errorInvalid", errorInvalid); } } catch (Exception ex) { ex.printStackTrace(); } finally { return mav; } } public ModelAndView register(Person p, Errors errors) { ModelAndView mav = new ModelAndView("addPerson"); try { sessionFactory.getCurrentSession().save(p); sessionFactory.getCurrentSession().flush(); mav.addObject("err", "false"); } catch (ConstraintViolationException sql){ mav.addObject("err", "true"); return mav; } return mav; } public ModelAndView editProfile(Person newPerson) { /* To fetch a row from table without using HQL Google kar lena */ String primaryKey = newPerson.getEmailId(); Person personFromDB = (Person)sessionFactory.getCurrentSession().get(Person.class, primaryKey); //p.setPersonDetails(person.getPersonDetails()); PersonDetails personDetails = personFromDB.getPersonDetails(); if (null != personDetails) { personDetails.setAddress(newPerson.getPersonDetails().getAddress()); } else { personFromDB.setPersonDetails(newPerson.getPersonDetails()); } /** * https://www.baeldung.com/hibernate-save-persist-update-merge-saveorupdate */ sessionFactory.getCurrentSession().update(personFromDB); ModelAndView mav = new ModelAndView("editProfile"); mav.addObject("person", personFromDB); return mav; } public ModelAndView getPerson(String emailId) { ModelAndView mav = new ModelAndView("editProfile"); Query query= sessionFactory.getCurrentSession().createQuery("from Person where emailId =:emailId"); query.setParameter("emailId",emailId); List<Person> personList = query.list(); Person person = new Person(); if (personList != null && personList.size() > 0) { person = personList.get(0); } mav.addObject("person",person); return mav; } } <file_sep>package com.demo.plp.service; import com.demo.plp.dao.FlightDao; import com.demo.plp.entity.Flights; import com.demo.plp.model.FlightsModel; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.ModelAndView; @Service @Transactional public class FlightServiceImpl implements FlightService { @Autowired FlightDao flightDao; public ModelAndView searchFlights() { ModelAndView mav=flightDao.searchFlights(); return mav; } public ModelAndView flights(FlightsModel flightsModel) { ModelAndView mav=flightDao.flights(flightsModel); return mav; } } <file_sep>package com.demo.plp.entity; import com.demo.plp.model.FlightsModel; import org.springframework.format.annotation.DateTimeFormat; import javax.persistence.*; @Entity @Table(name = "Flights") public class Flights { @Id @Column(name="flightNo") private int flightNo; @Column(name="source") private String source; @Column(name="destination") private String destination; @Column(name="time") private String time; @Column(name="duration") private float duration; /* @Column(name="price") private float price;*/ @DateTimeFormat(pattern = "yyyy-MM-dd") @Column(name = "date") private long date; public long getDate() { return date; } public void setDate(long date) { this.date = date; } /* public String getDate() { return date; } public void setDate(String date) { this.date = date; }*/ /* public float getPrice() { return price; } public void setPrice(float price) { this.price = price; }*/ public String getSource() { return source; } public void setSource(String source) { this.source = source; } public int getFlightNo() { return flightNo; } public void setFlightNo(int flightNo) { this.flightNo = flightNo; } public String getDestination() { return destination; } public void setDestination(String destination) { this.destination = destination; } public String getTime() { return time; } public void setTime(String time) { this.time = time; } public float getDuration() { return duration; } public void setDuration(float duration) { this.duration = duration; } /* public Date getDate() { return date; } public void setDate(Date date) { this.date = date; }*/ public Flights(FlightsModel flightsModel ) { this.flightNo = flightsModel.getFlightNo(); this.source = flightsModel.getSource(); this.destination = flightsModel.getDestination(); this.duration = flightsModel.getDuration(); if (null != flightsModel.getDate()) { this.date = flightsModel.getDate().getTime(); } } public Flights() { } } <file_sep>package com.demo.plp.service; import com.demo.plp.model.Flights; import org.springframework.web.servlet.ModelAndView; public interface FlightService { ModelAndView searchFlights(); ModelAndView flights(Flights flights); } <file_sep>package com.demo.plp.service; import com.demo.plp.entity.Flights; import com.demo.plp.model.FlightsModel; import org.springframework.web.servlet.ModelAndView; public interface FlightService { ModelAndView searchFlights(); ModelAndView flights(FlightsModel flightsModel); }
1b2975f66f6a8ab1a3b473673a34e1f721fe81b6
[ "Java", "INI" ]
20
Java
apurvadas95/PLP-projects
0198020429a181c111809a1c8e1bfc75d46b637b
bf8aa7c8647a9cc86c03a78f2e762270de31af25
refs/heads/master
<file_sep>package com.expedia.sol.util; import java.util.Comparator; import com.expedia.sol.domain.Activity; public class ActivityComparator implements Comparator<Activity> { @Override public int compare(Activity arg0, Activity arg1) { return arg0.getName().compareTo(arg1.getName()); } } <file_sep>package com.expedia.sol.validator; import org.springframework.validation.Errors; import org.springframework.validation.Validator; import com.expedia.sol.domain.Activity; import com.mysql.jdbc.StringUtils; public class ActivityValidator implements Validator { @Override public boolean supports(Class<?> clazz) { return Activity.class.isAssignableFrom(clazz); } @Override public void validate(Object target, Errors errors) { Activity activity = (Activity)target; if (StringUtils.isNullOrEmpty(activity.getName())) { errors.rejectValue("name", "name.empty"); } } } <file_sep>package com.expedia.sol.dao; import java.util.List; public interface IDBAccessor<T, R extends DBRequest> { boolean save(T type); boolean update(T type); boolean delete(R request); T getById(R request); List<T> get(R request); } <file_sep>names.list=<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME>,<NAME> time.values=0.25,0.5,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5,8 report.week=10 db.dblocation=/Users/neyma/Projects/STS_Workplace/timeTracker/timetracker.db<file_sep>package com.expedia.sol.dao.request; import com.expedia.sol.dao.DBRequest; import com.expedia.sol.domain.Person; public class PersonDbRequest implements DBRequest<Person> { private final String name; public PersonDbRequest(String name) { this.name = name; } public PersonDbRequest() { this.name = ""; } public String getName() { return name; } @Override public Person createEntity() { Person person = new Person(); person.setName(this.name); return person; } } <file_sep>package com.expedia.sol.controller; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/listTeam") public class ListTeamController extends ListController { @Override protected String getRedirectString() { return "listTeam"; } } <file_sep>package com.expedia.sol.domain; public class Report { private String name; private int week; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getWeek() { return week; } public void setWeek(int week) { this.week = week; } @Override public String toString() { return "Report [name=" + name + ", week=" + week + "]"; } } <file_sep>package com.expedia.sol.controller.admin; import java.util.List; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.validation.BindingResult; import org.springframework.validation.Validator; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import com.expedia.sol.dao.IDBAccessor; import com.expedia.sol.dao.request.ActivityDbRequest; import com.expedia.sol.dao.request.PersonDbRequest; import com.expedia.sol.domain.Activity; import com.expedia.sol.domain.Person; import com.expedia.sol.util.POJOToStringConverter; @Controller @RequestMapping("/admin") public class AdminController { @Resource(name = "activityValidator") private Validator activityValidator; @Resource(name = "personValidator") private Validator personValidator; @Resource(name = "activityHibernateDBAccessor") private IDBAccessor<Activity, ActivityDbRequest> activityAccessor; @Resource(name = "personHibernateDbAccessor") private IDBAccessor<Person, PersonDbRequest> personAccessor; @RequestMapping(value = "/addActivity", method = RequestMethod.GET) public String getAddActivity(Model model) { model.addAttribute("activity", new Activity()); return "addActivity"; } @RequestMapping(value = "/addActivity", method = RequestMethod.POST) public String postAddActivity(@ModelAttribute("activity") Activity activity, Model model, BindingResult result) { activityValidator.validate(activity, result); if (result.hasErrors()) { model.addAttribute("validationError", true); return "addActivity"; } List<String> activities = POJOToStringConverter.getTasks(activityAccessor.get(new ActivityDbRequest())); if (activities.contains(activity.getName())) { model.addAttribute("validationError", true); return "addActivity"; } boolean success = activityAccessor.save(activity); model.addAttribute("success", success); return "addActivity"; } @RequestMapping(value = "/deleteActivity", method = RequestMethod.GET) public String getDeleteActivity(Model model) { model.addAttribute("activities", POJOToStringConverter.getTasks(activityAccessor.get(new ActivityDbRequest()))); return "deleteActivity"; } @RequestMapping(value = "/deleteActivity", method = RequestMethod.POST) public String postDeleteActivity(@RequestParam("name") String name, Model model) { activityAccessor.delete(new ActivityDbRequest(name)); model.addAttribute("activities", POJOToStringConverter.getTasks(activityAccessor.get(new ActivityDbRequest()))); return "deleteActivity"; } @RequestMapping(value = "/addPerson", method = RequestMethod.GET) public String getAddPerson(Model model) { model.addAttribute("person", new Person()); return "addPerson"; } @RequestMapping(value = "/addPerson", method = RequestMethod.POST) public String postAddPerson(@ModelAttribute("person") Person person, Model model, BindingResult result) { personValidator.validate(person, result); if (result.hasErrors()) { model.addAttribute("validationError", true); return "addPerson"; } List<String> persons = POJOToStringConverter.getPersons((personAccessor.get(new PersonDbRequest()))); if (persons.contains(person.getName())) { model.addAttribute("validationError", true); return "addPerson"; } boolean success = personAccessor.save(person); model.addAttribute("success", success); return "addPerson"; } @RequestMapping(value = "/deletePerson", method = RequestMethod.GET) public String getDeletePerson(Model model) { model.addAttribute("persons", POJOToStringConverter.getPersons((personAccessor.get(new PersonDbRequest())))); return "deletePerson"; } @RequestMapping(value = "/deletePerson", method = RequestMethod.POST) public String postDeletePErson(@RequestParam("name") String name, Model model) { personAccessor.delete(new PersonDbRequest(name)); model.addAttribute("persons", POJOToStringConverter.getPersons((personAccessor.get(new PersonDbRequest())))); return "deletePerson"; } }
172d0b21c84631285b1f667b31bd4dd3d3c2edd8
[ "Java", "INI" ]
8
Java
neyma6/timeTracker
0d0599e81dbe279c38235020bcee88edd7ca8cd7
1a99966707cfe482c4185ef5e19fb2291364ff6a
refs/heads/master
<file_sep># User Colors [Github Link](html/user_colors_github.html "include") The User Colors library allows you to assign a unique color to each users in a [Room](../javascript_api/rooms/index.md), ensuring that there are no conflicts with the colors assigned to other users in the Room. By default, the library will choose from a default set of 20 colors supplied by GoInstant, but you can supply your own set of custom colors if desired. [User Colors](html/user_colors_demo_iframe.html "include") ## Table of Contents 1. [Code Example](#code-example) 1. [Constructor](#constructor) 1. [UserColors#choose](#usercolors#choose) ## Code Example ### 1. Include our CDN assets: #### Note on Versioning Specific version of widgets can be found on our [CDN](https://cdn.goinstant.net/). ```html <script type="text/javascript" src="https://cdn.goinstant.net/v1/platform.min.js"></script> <script type="text/javascript" src="https://cdn.goinstant.net/widgets/user-colors/latest/user-colors.min.js"></script> ``` ```js // Connect URL var url = 'https://goinstant.net/YOURACCOUNT/YOURAPP'; // Connect to GoInstant goinstant.connect(url, function (err, platformObj, roomObj) { if (err) { throw err; } // Create a new instance of the UserColors widget var userColors = new goinstant.widgets.UserColors({ room: roomObj }); // Choose a color for the current user. If the user already has a color // assigned from a prior use of 'choose' then that existing color will be // returned. userColors.choose(function(err, color) { if (err) { throw err; } console.log('The chosen color is ' + color); }); }); ``` ## Constructor Creates the UserColors instance with customizable options. ### Methods - ###### **new UserColors(options)** ### Parameters | options | |:---| | Type: [Object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object) | | An object with the following options: | | - `room` is a [GoInstant Room](https://developers.goinstant.net/v1/rooms/index.html) that you have previously joined | | - `colors` is an optional array containing a set of colors each in form of a hexadecimal color-code string (e.g. "#aaa"). Color names (e.g. "blue") are not supported. These will be used to override the default colors. | ### Example ```js var mainRoom = platform.room('mainRoom'); mainRoom.join(function(err) { // Note that your set of custom colors should be at least as large as the // maximum room size of your application, or some users may receive the // default '#aaa' color. var customColors = [ '#ff0000', '#222222', '#00FF00', '#00FFFF' ]; var options = { room: mainRoom, colors: customColors }; var userColors = new UserColors(options); }); ``` ## UserColors#choose ### Methods - ###### **userColors.choose(callback(errorObject, color))** ### Parameters | callback(errorObject, color) | |:---| | Called once a color has been [assigned to the local user](./guides/colors.md). | | - `errorObject` will be `null` unless an error has occured. | | - `color` is a hexidecimal representation of the colors (e.g. "#FF003B") associated with the local user. | ### Example ```js // Return or generate a color for the current user userColors.choose(function(err, color) { // Returned color is #FF0C3B }); ``` <file_sep># User Colors Changelog ### v1.0.1 - Added examples - Explicit component versions - Fixed deprecated interfaces. ### v1.0.0 - The beginning of time. <file_sep>/*jshint browser:true, node: false*/ /*global require, describe, it, beforeEach*/ 'use strict'; window.goinstant = { errors: { CollisionError: function(msg){ this.message = msg; } } }; describe('User Colors Component', function() { var UserColors = require('user-colors'); var userColors; var USER_PROPERTY = UserColors.USER_PROPERTY; var DEFAULT_COLORS = UserColors.DEFAULT_COLORS; var assert = window.assert; var sinon = window.sinon; var fakeRoom; var fakeUser; var fakeUserKey; var fakeUsers; // TODO: Not needed var fakeUsersKey; var fakeUserKeys; var fakeLockedKey; var lockedMap; var goinstant = window.goinstant; var TAKEN_BY_USERS = [ UserColors.DEFAULT_COLORS[0], UserColors.DEFAULT_COLORS[1] ]; function createFakeKey(name) { return { name: name, get: sinon.stub().yields(), set: sinon.stub().yields(), key: createFakeKey, remove: sinon.stub().yields() }; } beforeEach(function() { fakeRoom = {}; fakeRoom._platform = {}; fakeUser = { displayName: 'Guest', id: '1234', }; fakeUser[USER_PROPERTY] = TAKEN_BY_USERS[0]; fakeUserKey = createFakeKey('guest1'); fakeUserKey.get = sinon.stub().yields(null, fakeUser, {}); fakeRoom.self = sinon.stub().returns(fakeUserKey); fakeRoom._platform._user = fakeUser; fakeUsers = [ { displayName: 'Guest', id: '1234', get: function(cb) { return cb(null, fakeUsers[0]); }, set: function(value, opts, cb) { return cb(null, value); }, key: function() { return fakeUsers[0]; } }, { displayName: 'Guest', id: '5678', get: function(cb) { return cb(null, fakeUsers[1]); }, set: function(value, opts, cb) { return cb(null, value); }, key: function() { return fakeUsers[1]; } } ]; fakeUsers[0][USER_PROPERTY] = TAKEN_BY_USERS[0]; fakeUsers[1][USER_PROPERTY] = TAKEN_BY_USERS[1]; fakeUserKeys = [ createFakeKey(), createFakeKey() ]; fakeUsersKey = createFakeKey('/.users'); fakeLockedKey = createFakeKey('locked'); var fakeContext = {}; lockedMap = {}; lockedMap[UserColors.DEFAULT_COLORS[5].substring(1)] = 'fake id'; lockedMap[UserColors.DEFAULT_COLORS[11].substring(1)] = 'another fake id'; fakeLockedKey.get = sinon.stub().yields(null, lockedMap, fakeContext); fakeRoom.key = sinon.stub(); fakeRoom.key.returns(createFakeKey()); fakeRoom.key.withArgs('/.users/' + fakeUsers[0].id).returns(fakeUsers[0]); fakeRoom.key.withArgs(UserColors.KEY_NAMESPACE).returns(fakeLockedKey); }); describe('constructor', function() { it('returns a new instance of UserColors', function() { var options = { room: fakeRoom }; userColors = new UserColors(options); assert.isObject(userColors); }); describe('errors', function() { it('throws if not passed options argument', function() { assert.exception(function() { userColors = new UserColors(); }, 'UserColors: Options was not found or invalid'); }); it('throws if options passed is not an object', function() { assert.exception(function() { var options = 'options'; userColors = new UserColors(options); }, 'UserColors: Options was not found or invalid'); }); it('throws if passed a invalid arugment', function() { assert.exception(function() { var options = { room: fakeRoom, foo: 'bar' }; userColors = new UserColors(options); }, 'UserColors: Invalid argument passed'); }); it('throws if not passed a room', function() { assert.exception(function() { userColors = new UserColors({}); }, 'UserColors: Room was not found or invalid'); }); it('throws if passed room is not an object', function() { assert.exception(function() { var options = { room: 'room' }; userColors = new UserColors(options); }, 'UserColors: Room was not found or invalid'); }); it('throws error if optional colors aren\'t passed as array', function() { assert.exception(function() { var options = { room: fakeRoom, colors: {} }; userColors = new UserColors(options); }, 'UserColors: Colors must be passed as an array'); }); it('throws error if colors in array aren\'t strings', function() { assert.exception(function() { var options = { room: fakeRoom, colors: ['red', 'green', 'blue', true] }; userColors = new UserColors(options); }, 'UserColors: A color must be passed as a string'); }); }); }); describe('choose', function() { beforeEach(function() { var options = { room: fakeRoom }; userColors = new UserColors(options); userColors.room.key.withArgs(USER_PROPERTY + '/locks').returns( fakeLockedKey); }); it('returns an existing color for the current user', function(done) { lockedMap[TAKEN_BY_USERS[0].substr(1)] = fakeUsers[0].id; userColors.choose(function(err, color) { assert.ifError(err); assert.equal(color, TAKEN_BY_USERS[0]); // Assert did not re-assigned the color to the user or try to lock a // color. sinon.assert.notCalled(fakeUserKey.set); sinon.assert.notCalled(fakeLockedKey.set); done(); }); }); it('returns a new color for the current user', function(done) { // Remove the mocked color on the current user, // Update another user to have their original color so it is taken. fakeUsers[0][USER_PROPERTY] = null; lockedMap[TAKEN_BY_USERS[0].substr(1)] = fakeUsers[1].id; userColors.choose(function(err, color) { assert.ifError(err); assert.notEqual(color, TAKEN_BY_USERS[0]); assert.include(DEFAULT_COLORS, color); done(); }); }); it('returns default color when all others are taken', function(done) { // Remove the mocked color on the current user fakeUsers[0][USER_PROPERTY] = null; // Overwrite the locked map and fill it so we can't get a "free" color for(var i = 0; i < DEFAULT_COLORS.length; i++) { var color = DEFAULT_COLORS[i]; lockedMap[color.substr(1)] = 'taken'; } userColors.choose(function(err, color) { assert.ifError(err); assert.equal(UserColors.DEFAULT_COLOR, color); done(); }); }); it('gets new color when first attempt is taken', function(done) { fakeUsers[0][USER_PROPERTY] = null; var fakeColorKey = createFakeKey(); var collisionError = new goinstant.errors.CollisionError(); fakeColorKey.set = sinon.stub().yields(collisionError); sinon.stub(fakeLockedKey, 'key', function() { if (fakeLockedKey.key.callCount === 1) { // On first call return the key that will cause a collision error return fakeColorKey; } else { // Any other time return mock key as usual return createFakeKey(); } }); userColors.choose(function(err, color) { assert.ifError(err); assert.equal(fakeLockedKey.key.callCount, 2); assert.notEqual(color, DEFAULT_COLORS[0]); assert.include(DEFAULT_COLORS, color); done(); }); }); it('re-fetches the locks if all colors are exhausted', function(done) { var collisionError = new goinstant.errors.CollisionError(); var collisionKey = { set: sinon.stub().yields(collisionError) }; sinon.stub(fakeLockedKey, 'key').returns(collisionKey); fakeLockedKey.get = sinon.spy(function(cb) { // On the second call return the filled lock map to simulate that all // the colors have been taken in the meantime. if (fakeLockedKey.get.callCount === 2) { for (var i = 0; i < DEFAULT_COLORS.length; ++i) { lockedMap[DEFAULT_COLORS[i].substr(1)] = 'taken'; } } cb(null, lockedMap); }); userColors.choose(function(err, color) { assert.ifError(err); // All colors were taken, so should have returned the default color. assert.equal(color, UserColors.DEFAULT_COLOR); // Should have fetched the locks twice: once initially (returned lockMap // with available locks) and once after failing to acquire any of the // locks (returns a full map) sinon.assert.callCount(fakeLockedKey.get, 2); done(); }); }); describe('errors', function() { it('throws an error if no arguments are passed', function() { assert.exception(function() { userColors.choose(); }, 'choose: Callback was not found or invalid'); }); it('throws an error if an non-function is passed', function() { assert.exception(function() { userColors.choose('1234'); }, 'choose: Callback was not found or invalid'); }); it('returns an error when failing to retrieve user', function(done) { fakeUserKey.get = sinon.stub().yields(new Error()); userColors.choose(function(err, color) { assert.isDefined(err); assert.isUndefined(color); done(); }); }); it('returns an error when failing to retrieve locks', function(done) { fakeLockedKey.get = sinon.stub().yields(new Error()); userColors.choose(function(err, color) { assert.isDefined(err); assert.isUndefined(color); done(); }); }); it('returns an error when failing to set color in user', function(done) { var badKey = { set: sinon.stub().yields(new Error()) }; fakeUserKey.key = sinon.stub().returns(badKey); userColors.choose(function(err, color) { assert.isDefined(err); assert.isUndefined(color); done(); }); }); it('returns an error when failing to set lock', function(done) { var firstColorKeyName = DEFAULT_COLORS[0].substring(1); var failingKey = createFakeKey(); failingKey.set = sinon.stub().yields(new Error()); fakeLockedKey.key = sinon.stub(); fakeLockedKey.key.withArgs(firstColorKeyName) .returns(failingKey); userColors.choose(function(err, color) { assert.isDefined(err); assert.isUndefined(color); done(); }); }); }); describe('optional color override', function() { var colors; beforeEach(function() { colors = [ 'red', 'green', 'blue', 'yellow' ]; var options = { room: fakeRoom, colors: colors }; userColors = new UserColors(options); }); it('Assigns from the custom colors', function(done) { fakeUser[USER_PROPERTY] = null; fakeUsers[0][USER_PROPERTY] = null; userColors.choose(function(err, color) { assert.ifError(err); assert.equal(color, colors[0]); done(); }); }); }); }); }); <file_sep>/*jshint browser:true, node:false*/ /*global module, require*/ 'use strict'; /** * @fileoverview * @module goinstant/components/user-colors * @exports userColorsComponent */ /** * Module Dependencies */ var goinstant = window.goinstant; var async = require('async'); var _ = require('lodash'); var colors = require('colors-common'); var errors = require('./lib/errors'); /** * Constants */ var KEY_NAMESPACE = 'goinstant/widgets/color'; /** * Validation */ var VALID_OPTIONS = ['room', 'colors']; var DEFAULT_OPTIONS = { colors: colors.DEFAULTS }; module.exports = UserColors; /** * @constructor */ function UserColors(opts) { if (!opts || !_.isPlainObject(opts)) { throw errors.create('UserColors', 'INVALID_OPTIONS'); } var optionsPassed = _.keys(opts); var optionsDifference = _.difference(optionsPassed, VALID_OPTIONS); if (optionsDifference.length) { throw errors.create('UserColors', 'INVALID_ARGUMENT'); } if (!opts.room || !_.isObject(opts.room)) { throw errors.create('UserColors', 'INVALID_ROOM'); } if (opts.colors && !_.isArray(opts.colors)) { throw errors.create('UserColors', 'INVALID_COLORS'); } else if (opts.colors) { _.each(opts.colors, function(color) { if (!_.isString(color)) { throw errors.create('UserColors', 'INVALID_COLOR'); } }); } opts = _.defaults(opts, DEFAULT_OPTIONS); this.room = opts.room; this.colors = opts.colors; _.bindAll(this, '_choose', '_getUserData', '_getLockedColors', '_setColor', '_acquireColor'); } /** * Globally exposed constants */ UserColors.USER_PROPERTY = colors.USER_PROPERTY; UserColors.KEY_NAMESPACE = KEY_NAMESPACE; UserColors.DEFAULT_COLORS = colors.DEFAULTS; UserColors.DEFAULT_COLOR = colors.DEFAULT; /** * Choose a color from among the supplied list or the default colors. This * routine is idempotent unless it returns the default color, in which case * it may choose a different color if one has become available in the meantime. * This routine is NOT reentrant, and will have undefined behaviour if called * multiple times concurrently. * @param {function(err, color)} cb The function to call with the chosen color, * or an error if a platform error occurs. */ UserColors.prototype.choose = function(cb) { if (!_.isFunction(cb)) { throw errors.create('choose', 'INVALID_CALLBACK'); } var tasks = { user: this._getUserData, locked: this._getLockedColors }; async.parallel(tasks, _.partialRight(this._choose, cb)); }; /** * Internal implementation of the choose function. Checks to see if a color * is already available and, if not, starts the color acquisition algorithm. * @param {Error} err The error that occurred fetching the user or locked color * set, if any. * @param {object} results The results of the platform requests to fetch the * user and locked color set. * @param {function(err, color)} cb The function to call with the chosen color * or if an error occurs. * @private */ UserColors.prototype._choose = function(err, results, cb) { if (err) { return cb(err); } // results.user == [userData, context] this.user = results.user[0]; // results.locked == [locks, context] this.locked = results.locked[0]; // First argument is the value. var self = this; // The color that is currently locked in to the user, or undefined if no // color is locked. var lockedToUser = _.findKey(this.locked, function(id) { return id === self.user.id; }); // The locks don't have the hashmark because it's invalid in platform. if (lockedToUser) { lockedToUser = '#' + lockedToUser; } var userColor = self.user[colors.USER_PROPERTY]; if (userColor && lockedToUser === userColor && _.contains(this.colors, userColor)) { // Valid color is already assigned to the user and locked to prevent other // users from choosing it. Nothing else to do. return cb(null, userColor); } if (lockedToUser && _.contains(this.colors, lockedToUser)) { // Valid color is assigned, but doesn't exist in the user object. Save it // in the user and we're done. return this._setColor(lockedToUser, cb); } var tasks = []; if (lockedToUser) { // User currently has a color locked, but it is not a valid color. Release // the lock because we're going to be selecting a different color instead. var lockKey = this._keyFor(lockedToUser); tasks.push(function(next) { // Drop any other values returned from remove so they're not passed to // acquireColor. lockKey.remove(function(err) { next(err); }); }); } tasks.push(this._acquireColor); tasks.push(this._setColor); async.waterfall(tasks, cb); }; /** * Returns the updated set of locked colors. * @param {function(err, value, context)} cb The callback to call with the * results. Takes an error object, the set of locked colors, and a * context object. * @private */ UserColors.prototype._getLockedColors = function(cb) { this.room.key(KEY_NAMESPACE).get(cb); }; /** * Returns the up-to-date user object for the local user. * */ UserColors.prototype._getUserData = function(cb) { this.room.self().get(cb); }; /** * Saves the color in the user object. This is the last step of acquiring a * color and is what triggers other components to update their UI. * @private */ UserColors.prototype._setColor = function(color, cb) { var key = this.room.self().key(colors.USER_PROPERTY); key.set(color, function(err) { if (err) { return cb(err); } cb(null, color); }); }; /** * */ UserColors.prototype._acquireColor = function(cb) { // The locks don't have a hashmark, so add that now. var lockedColors = _.keys(this.locked); lockedColors = _.map(lockedColors, function(color) { return '#' + color; }); var availableColors = _.difference(this.colors, lockedColors); if (availableColors.length <= 0) { // There are no colors available at all. Assign the default color. return cb(null, colors.DEFAULT); } var acquiredColor = null; var self = this; // Loop conditional. Returns true if we've acquire a color or we've exhausted // all the available colors. function acquiredOrExhausted() { return !!acquiredColor || availableColors.length <= 0; } // Loop iterator. Attempts to acquire the next available color. function tryNextColor(next) { var color = availableColors.shift(); var key = self._keyFor(color); // Do not overwrite the lock if another user just acquired it. If we do // acquire the lock, remove it when the user leaves the room. var options = { overwrite: false, cascade: self.room.self() }; key.set(self.user.id, options, function(err) { if (err instanceof goinstant.errors.CollisionError) { // Someone else just claimed that color. Move to the next iteration to // try a different color. return next(); } else if (err) { return next(err); } // We've locked the color for the local user. acquiredColor = color; next(); }); } function done(err) { if (err) { return cb(err); } if (acquiredColor) { // Got a color, we're all done. return cb(null, acquiredColor); } // Did not get a color. This should only happen in race conditions using a // custom color list with less than the maximum room size number of colors, // or in a very unlikely race condition with the default color set involving // multiple users joining and leaving the room simultaneously. Refetch the // list of locks and run the algorithm again; this will most likely assign // the default color, but may succeed in the second case described above. self._getLockedColors(function(err, locks) { if (err) { return cb(err); } self.locked = locks; self._acquireColor(cb); }); } async.until(acquiredOrExhausted, tryNextColor, done); }; /** * */ UserColors.prototype._keyFor = function(color) { // Drop the hashmark when making a key. return this.room.key(KEY_NAMESPACE).key(color.substr(1)); }; <file_sep>prod: grunt build:prod build: prod echo "Built the User Colors widget for Production"
118d33f18b2acda2d4efe151c72035db891667a0
[ "Markdown", "JavaScript", "Makefile" ]
5
Markdown
goinstant/user-colors
1e8d15e88309f61e30fbd28a3f9eb0a2a784fb6e
629959a9af15cc45880a4756ec58d0faf32ccb1e
refs/heads/master
<repo_name>jayden-lee/hello-csharp<file_sep>/BigQueryExample/Program.cs using System; using Google.Apis.Auth.OAuth2; using Google.Cloud.BigQuery.V2; namespace BigQueryExample { class Program { static void Main(string[] args) { string jsonPath = "/Users/jayden-lee/Dev/Google/QueryPie DB Test-7d2bc445f64d.json"; string projectId = "querypie-db-test"; BigQueryClient client = BigQueryClient.Create(projectId, CreateCredential(jsonPath)); string query = @"SELECT CONCAT( 'https://stackoverflow.com/questions/', CAST(id as STRING)) as url, view_count FROM `bigquery-public-data.stackoverflow.posts_questions` WHERE tags like '%google-bigquery%' ORDER BY view_count DESC LIMIT 10"; var result = client.ExecuteQuery(query, parameters: null); Console.Write("\nQuery Results:\n------------\n"); foreach (var row in result) { Console.WriteLine($"{row["url"]}: {row["view_count"]} views"); } } #region Create Credential // Explicitly use service account credentials by specifying the private key file. private static GoogleCredential CreateCredential(string jsonPath) { return GoogleCredential.FromFile(jsonPath); } #endregion } }
afdafa95a042ebb692c5ba69a68c6986809d1028
[ "C#" ]
1
C#
jayden-lee/hello-csharp
99ec99ce73d6ab9a45437b6eebe321d05cf48bed
d40233ff632ef801f4705178750122d9d4ccde3f
refs/heads/master
<repo_name>phiyan/dotfiles<file_sep>/create_symlinks.sh #!/bin/bash dotfiles=( bash_profile bash_profile_includes gitconfig gitignore gituserconfig ) source=$(pwd) for dotfile in "${dotfiles[@]}"; do mv "${HOME}/.${dotfile}" "${HOME}/${dotfile}.bak" echo "linking ${source}/${dotfile} to ${HOME}/.${dotfile}" ln -s "${source}/${dotfile}" "${HOME}/.${dotfile}" done <file_sep>/bash_profile_includes/general.sh #!/bin/bash export CLICOLOR=1 eval "$(pyenv init -)" eval "$(rbenv init -)" export NVM_DIR="$HOME/.nvm" [ -s "$NVM_DIR/nvm.sh" ] && \. "$NVM_DIR/nvm.sh" # This loads nvm [ -s "$NVM_DIR/bash_completion" ] && \. "$NVM_DIR/bash_completion" # This loads nvm bash_completion [[ -r "/usr/local/etc/profile.d/bash_completion.sh" ]] && . "/usr/local/etc/profile.d/bash_completion.sh" # rvm [[ -s "$HOME/.rvm/scripts/rvm" ]] && . "$HOME/.rvm/scripts/rvm" # Load RVM function <file_sep>/bash_profile_includes/aliases.sh #!/bin/bash alias o='open' alias ll="ls -lAh" alias untar="tar -xvf" alias ag="ag -i" <file_sep>/bash_profile #!/bin/bash # Additions to bash should be placed into ~/.bash_profile_includes with a .sh extension for file in ~/.bash_profile_includes/*.sh; do [[ -r $file ]] && source $file; done
d068b94a70ed09529ddc279b358f310eb8ad6ab0
[ "Shell" ]
4
Shell
phiyan/dotfiles
8336cdc007240cde3071e87f948d0903a8f61731
44dd73fbea769dfe1dd802daa76643c413e4208c
refs/heads/master
<file_sep>package com.example.david.twistthemobile; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.LinearLayout; import android.widget.TextView; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; /** * Created by David on 4/07/2017. */ public class TimerActivity extends AppCompatActivity { private static final String TAG = "TimerActivity"; private TextView mTextView; //Firebase Parameters private DatabaseReference mDatabase; //User Stopwatch Parameters final int MSG_START_TIMER = 0; final int MSG_STOP_TIMER = 1; final int MSG_UPDATE_TIMER = 2; final int REFRESH_RATE = 50; StopWatch timer = new StopWatch(); boolean hasStarted = false; //using handler to interact with ui thread to update timer Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { super.handleMessage(msg); switch (msg.what) { case MSG_START_TIMER: timer.startTimer(); //start timer mHandler.sendEmptyMessage(MSG_UPDATE_TIMER); break; case MSG_UPDATE_TIMER: String elapsedTime = String.valueOf(timer.getElapsedTime()); if(elapsedTime.length() < 3) { elapsedTime = "0:" + elapsedTime.substring(0, elapsedTime.length()); } else { elapsedTime = elapsedTime.substring(0, elapsedTime.length() - 3) + ":" + elapsedTime.substring(elapsedTime.length() - 3, elapsedTime.length()); } mTextView.setText(""+ elapsedTime); mHandler.sendEmptyMessageDelayed(MSG_UPDATE_TIMER,REFRESH_RATE); //text view is updated every second, break; //though the timer is still running case MSG_STOP_TIMER: mHandler.removeMessages(MSG_UPDATE_TIMER); // no more updates. timer.stopTimer();//stop timer elapsedTime = String.valueOf(timer.getElapsedTime()); if(elapsedTime.length() < 3) { elapsedTime = "0:" + elapsedTime.substring(0, elapsedTime.length()); } else { elapsedTime = elapsedTime.substring(0, elapsedTime.length() - 3) + ":" + elapsedTime.substring(elapsedTime.length() - 3, elapsedTime.length()); } mTextView.setText(""+ elapsedTime); mDatabase.child("times").child("one").child("David").setValue(timer.getElapsedTime()); break; default: break; } } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_timer); FirebaseDatabase database = FirebaseDatabase.getInstance(); mDatabase = database.getReference(); mTextView = (TextView) findViewById(R.id.TimerText); LinearLayout layout = (LinearLayout) findViewById(R.id.rootlayout); layout.setOnClickListener(mStartListener); } View.OnClickListener mStartListener = new View.OnClickListener() { @Override public void onClick(View view) { if(hasStarted) { mHandler.sendEmptyMessage(MSG_STOP_TIMER); hasStarted = false; } else { mHandler.sendEmptyMessage(MSG_START_TIMER); mDatabase.child("times").child("one").child("David").setValue("Start"); hasStarted = true; } } }; // View.OnClickListener mStopListener = new View.OnClickListener() { // @Override // public void onClick(View view) { // mHandler.sendEmptyMessage(MSG_STOP_TIMER); // } // }; }
528f66b03d3b304032c8d88fdc04229e29e29c08
[ "Java" ]
1
Java
DavidChao99/TTWMobile
7cf213f01dc44bfa463c6533b51a06d39b42630f
6d6af8a46de17a100d7c4707bf50238dc043f499
refs/heads/master
<file_sep>import java.io.*; import java.util.Map; import java.util.Set; import java.util.TreeMap; public class Main { // -------------------------------------------------------------------------- public static final String LANGUAGE_CODE = "PL"; // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- // -------------------------------------------------------------------------- public static void main(String[] args) throws IOException { System.out.println("Start!"); String lettersSmall = "abcdefghijklmnopqrstuvwxyz"; String inputFileName = "input_" + LANGUAGE_CODE + ".txt"; TreeMap<String, String> treeMap = new TreeMap<>(); BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(inputFileName), "UTF8")); PrintWriter writer = null; for (int i = 0; i < lettersSmall.length(); i++) { File file = new File("output_" + LANGUAGE_CODE + "_" + lettersSmall.charAt(i) + ".txt"); file.createNewFile(); } String line; while ((line = reader.readLine()) != null) { System.out.println(line); String tKey = line.substring(0, line.indexOf(" [ ")); String tValue = line.substring(line.indexOf(" [ ")) .replace(" ", "") .replace("=", " ") .replace("[", "(") .replace("]", ")") .replace("(przymiotnik)", "(p.)") .replace("(rzeczownik)", "(rz.)") .replace("(czasownik)", "(cz.)") .replace("(przyimek)", "(p-im.)") .replace("(przysłówek)", "(p-sł.)"); if (!treeMap.containsKey(tKey)) { treeMap.put(tKey, tValue); } else { treeMap.replace(tKey, treeMap.get(tKey) + "; " + tValue); } } Set<Map.Entry<String, String>> entrySet = treeMap.entrySet(); for (Map.Entry<String, String> entry : entrySet) { String rawKey = entry.getKey() .toLowerCase() .replace("ą", "a") .replace("ć", "c") .replace("ę", "e") .replace("ł", "l") .replace("ń", "n") .replace("ó", "o") .replace("ś", "s") .replace("ź", "z") .replace("ż", "z"); String tLine = "[" + rawKey + "]" + entry.getKey() + " (" + LANGUAGE_CODE + ") : " + entry.getValue(); System.out.println(tLine); writer = new PrintWriter(new BufferedWriter(new FileWriter("output_" + LANGUAGE_CODE + "_" + rawKey.charAt(0) + ".txt", true))); writer.println(tLine); writer.close(); } System.out.println("Koniec!"); } }
805e56962e6f4e9ae0ff613015af72e113f3d50b
[ "Java" ]
1
Java
maciejprogramuje/DictionaryConverter
493e688fb651aecccac53aa013d1d9be222901b1
8e62de1b0a1549e8b1c96e4360368273c6757fc1