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/main
|
<repo_name>Chintan-collab/Student-Record-Management-System-SRMS<file_sep>/README.md
# Student Record Management System in PHP
**LOGIN DETAILS*
Username : admin
Password : <PASSWORD>
**Thanks to <NAME>**
DON'T FORGET TO CREATE A DATABASE NAMING "model" AND IMPORT THE DATBASE SQL FILE (model.sql)
WITHOUT THE DATABASE THE PROJECT WON'T RUN.
>> THE DATABASE FILE IS INSIDE "DATABASE" FOLDER!!
***** IF YOU FIND ANY ERRORS OR ANY PROBLEMS RELATED THIS PROGRAM, FEEL FREE TO CONTACT US *****
***** LEAVE A COMMENT IF YOU LOVED OUR WORK *****
***** EMAIL:<EMAIL> *****
#THANK YOU FOR DOWNLOADING
<file_sep>/main/savenotice.php
<?php
session_start();
include('../connect.php');
$a = $_POST['notice_title'];
$b = $_POST['notice_desc'];
if(isset($_POST['active']))
{
$c = 1;
}
else{
$c = 0;
}
// query
//do your write to the database filename and other details
$sql = "INSERT INTO notices (notice_title,notice_desc,active,date_time) VALUES (:a,:b,:c, now());";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':b'=>$b,':c'=>$c));
header("location: addnotices.php");
?><file_sep>/main/saveeditnotices.php
<?php
// configuration
include('../connect.php');
// new data
$id = $_POST['id'];
$a = $_POST['notice_title'];
$b = $_POST['notice_desc'];
if(isset($_POST['active']))
{
$c = 1;
}
else{
$c = 0;
}
$d = $_POST['date_time'];
// query
$sql = "UPDATE notices
SET notice_title=?,notice_desc=?, active=?, date_time=?
WHERE id=?";
$q = $db->prepare($sql);
$q->execute(array($a,$b,$c,$d,$id));
header("location: managenotices.php");
?><file_sep>/main/navfixed.php
<link href="style.css" rel="stylesheet" type="text/css" />
<div class="navbar navbar-inverse navbar-fixed-top">
<div class="navbar-inner">
<div class="container-fluid" style="
/* height: 82px; */
margin: 0px;
padding: 8px;
background-color: rgb(230 145 83);
/* background-image: linear-gradient(to bottom, rgb(234 64 166), rgb(234 64 166)); */
background-repeat: repeat-x;
border: 1px solid rgb(230 145 83);
">
<a class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</a>
<a class="brand" href="#" style="
color: black;
font-family: monospace;
"><b>Student Record Management System </b></a>
<div class="nav-collapse collapse">
<ul class="nav pull-right">
<li><a style="
color: black;
font-family: monospace;
font-size: 21px;
background-image: linear-gradient(to bottom, rgb(230 145 83),rgb(230 145 83));
"><i class="icon-user icon-large"></i> Welcome:<strong> <?php echo $_SESSION['SESS_FIRST_NAME'];?></strong></a></li>
<li><a style="
color: black;
font-family: monospace;
background-image: linear-gradient(to bottom, rgb(230 145 83), rgb(230 145 83));
"> <i class="icon-calendar icon-large"></i>
<?php
$Today = date('y:m:d',mktime(0,0,0));
$new = date('l, F d, Y', strtotime($Today));
echo $new;
?>
</a></li>
<li>
<a href="../index.php" style="
color: black;
padding: 5px 0px 0px 0px;
font-family: monospace;
font-size: 16px;
background-image: linear-gradient(to bottom, rgb(230 145 83),rgb(230 145 83));
"> <font color="black"><i class="icon-off icon-2x"></i></font><br></a>
</li>
<!-- <li><a href="../index.php"><font color="red"><i class="icon-off icon-large"></i></font> Log Out</a></li> -->
</ul>
</div><!--/.nav-collapse -->
</div>
</div>
</div>
<file_sep>/main/morenotices.php
<?php
$link = mysqli_connect("localhost","root","");
$notice_count = $_SESSION['NOTICE_COUNT'];
if(!$link) {
die('Failed to connect to server: ' . mysql_error());
}
else{
}
//Select database
$db = mysqli_select_db( $link,'model');
if(!$db) {
die("Unable to select database");
}
$qry="SELECT notice_title, notice_desc From notices where DATE_ADD(NOW(), INTERVAL -36 HOUR) < date_time and ACTIVE = 1 ORDER BY id";
$result=mysqli_query($link, $qry);
$info['Header'] = '';
$info['Body'] = '';
$info['Footer'] = '';
//Check whether the query was successful or not
if($result) {
if(mysqli_num_rows($result) > $notice_count) {
mysqli_data_seek($result, $notice_count);
$notices = mysqli_fetch_row($result);
$info['Header'] = $notices[0];
$info['Body'] = $notices[1];
$info['Footer'] = '';
}
}
$notice_count = $notice_count + 1;
$_SESSION['NOTICE_COUNT'] = $notice_count;
?>
<file_sep>/DATABASE/model.sql
-- phpMyAdmin SQL Dump
-- version 5.0.4
-- https://www.phpmyadmin.net/
--
-- Host: 127.0.0.1
-- Generation Time: Apr 27, 2021 at 06:10 PM
-- Server version: 10.4.17-MariaDB
-- PHP Version: 8.0.2
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
START TRANSACTION;
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `model`
--
-- --------------------------------------------------------
--
-- Table structure for table `documents`
--
CREATE TABLE `documents` (
`id` int(11) NOT NULL,
`doc_title` varchar(2000) NOT NULL,
`doc_desc` varchar(8000) NOT NULL,
`doc_file` varchar(2000) NOT NULL,
`doc_standard` varchar(2000) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `documents`
--
INSERT INTO `documents` (`id`, `doc_title`, `doc_desc`, `doc_file`, `doc_standard`) VALUES
(1, 'C Language', 'C Language is a programming language and basic language for Computer Science And Engineering.', 'document_6ece97e7790d34db230ddc8c3164332e.pdf', 'B.Tech 1st year'),
(2, 'Python Practical List', 'Python Programming Language', 'document_2c367692a8d78e71dde9658575c6025b.pdf', 'B.Tech 2nd year'),
(3, 'MPCO ', 'MPCO Practical List', 'document_2faffe0f19475f5cc967bb86788711ce.doc', 'B.Tech 3rd year'),
(4, 'DBMS', 'DBMS Practical List', 'document_38e0d1d06883572972a9984d2c8e01e8.pdf', 'B.Tech 4th year'),
(5, 'Profile Photo', 'My Profile photo', 'document_c94e9496da61c28a4eec07713bec716d.jpg', 'B.Tech 3rd year'),
(6, 'C Language', 'Practical File', 'document_730f9e0e7bcd5b1cf54294a5d36a7334.pdf', 'B.Tech 1st year');
-- --------------------------------------------------------
--
-- Table structure for table `notices`
--
CREATE TABLE `notices` (
`id` int(11) NOT NULL,
`notice_title` varchar(1000) NOT NULL,
`notice_desc` varchar(8000) NOT NULL,
`Active` tinyint(1) NOT NULL DEFAULT 1,
`date_time` datetime NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
--
-- Dumping data for table `notices`
--
INSERT INTO `notices` (`id`, `notice_title`, `notice_desc`, `Active`, `date_time`) VALUES
(2, 'covid - 19', ' hello my name is omiii', 1, '2021-04-09 21:38:41'),
(3, 'Regarding Annual Fees', 'As the new semester have been started, you all need to pay your fees from 01-01-2021 to 15-06-2021. If you are not able to pay the fees or get delayed for paying the fees then strict action would be taken against you.. Kindly note of it.', 1, '2021-04-14 18:34:54'),
(5, 'new notice from akash', 'work from home for OM TANK', 1, '2021-04-11 13:39:46'),
(7, 'testing new covid rules', 'OM Does not have to watch F1 today as there is a lot of pending work to be done, need to complete this work without fail.', 1, '2021-04-18 16:43:14'),
(8, 'About Internship', ' All Students need to do summer internship as it is compulsory.', 1, '2021-04-24 08:00:01');
-- --------------------------------------------------------
--
-- Table structure for table `parent`
--
CREATE TABLE `parent` (
`id` int(11) NOT NULL,
`name` varchar(255) NOT NULL,
`address` varchar(450) NOT NULL,
`phone` varchar(150) NOT NULL,
`email` varchar(55) NOT NULL,
`note` varchar(200) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
-- --------------------------------------------------------
--
-- Table structure for table `student`
--
CREATE TABLE `student` (
`id` int(11) NOT NULL,
`student_id` varchar(220) NOT NULL,
`name` varchar(45) NOT NULL,
`last_name` varchar(45) NOT NULL,
`report` varchar(2000) NOT NULL,
`year` varchar(100) NOT NULL,
`yoa` varchar(45) NOT NULL,
`parent` varchar(200) NOT NULL,
`dob` date NOT NULL,
`gender` varchar(7) NOT NULL,
`file` varchar(400) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `student`
--
INSERT INTO `student` (`id`, `student_id`, `name`, `last_name`, `report`, `year`, `yoa`, `parent`, `dob`, `gender`, `file`) VALUES
(13, 'MS17-def1', 'Chintan', 'Vekariya', 'Need to improve... ', 'B.Tech 2nd year', '2012', '6353245768', '2001-08-08', 'Male', 'your_site_name_bace602f28aa688ab653d901b7db7e9d.jpg'),
(14, 'MS17-a3b7', 'Ruchi', 'Tank', 'Very good in her work...', 'B.Tech 3rd year', '2016', '9316249815', '2001-03-27', 'Female', 'your_site_name_61684600542da2ec1c24b7cbf41bef53.jpg'),
(15, 'MS17-9488', 'Om', 'Tank', 'Good..', 'B.Tech 1st year', '2009', '9428340654', '2001-03-20', 'Male', 'your_site_name_1c0dba546f1716d035f318e981e804dd.jpg'),
(16, 'MS17-5412', 'Nihar', 'Zatakiya', 'Excellent....', 'B.Tech 2nd year', '2009', '9823476512', '2001-01-01', 'Male', 'your_site_name_025b68b91af7bb2c25b586a38284cbbc.jpeg'),
(17, 'MS17-583c', 'Akash', 'Shah', 'Superb....', 'B.Tech 4th year', '2009', '9316249815', '1996-10-10', 'Male', 'your_site_name_bc794cdf3b52424abfbc37e536a25adc.jpg'),
(19, 'MS17-32b2', 'Raj', 'Patel', 'Overall Good but can improve. ', 'B.Tech 4th year', '2011', '9456873216', '2001-10-14', 'Male', 'your_site_name_7b014c2716fa791b17ff5df7b7646413.jpg'),
(20, 'MS17-8195', 'Rahul', 'B.Tech 1st year', 'good ', 'B.Tech 1st year', '2009', '9321234567', '2001-02-20', 'Male', 'your_site_name_bbf64509385f74c69317a7f2d652b5ed.jpg');
-- --------------------------------------------------------
--
-- Table structure for table `user`
--
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(55) NOT NULL,
`position` varchar(55) NOT NULL,
`username` varchar(55) NOT NULL,
`password` varchar(55) NOT NULL,
`student_id` int(11) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `user`
--
INSERT INTO `user` (`id`, `name`, `position`, `username`, `password`, `student_id`) VALUES
(1, 'Om Tank', 'admin', 'admin', '<PASSWORD>', 0),
(2, 'Apurv Tank', 'admin', 'apurv', 'apurv', 0),
(4, 'Rahul', 'admin', 'rahul', 'rahul', 0),
(10, 'Chintan', 'student', 'Chintan', 'Chintan', 13),
(11, 'Ruchi', 'student', 'Ruchi', 'Ruchi', 14),
(12, 'Om', 'student', 'Om', 'Om', 15),
(13, 'Nihar', 'student', 'Nihar', 'Nihar', 16),
(14, 'Akash', 'student', 'Akash', 'Akash', 17),
(16, 'Raj', 'student', 'Raj', 'Raj', 19),
(17, 'Rahul', 'student', 'Rahul', 'Rahul', 20);
--
-- Indexes for dumped tables
--
--
-- Indexes for table `documents`
--
ALTER TABLE `documents`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `notices`
--
ALTER TABLE `notices`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `parent`
--
ALTER TABLE `parent`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `student`
--
ALTER TABLE `student`
ADD PRIMARY KEY (`id`);
--
-- Indexes for table `user`
--
ALTER TABLE `user`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `documents`
--
ALTER TABLE `documents`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=7;
--
-- AUTO_INCREMENT for table `notices`
--
ALTER TABLE `notices`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=9;
--
-- AUTO_INCREMENT for table `parent`
--
ALTER TABLE `parent`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT;
--
-- AUTO_INCREMENT for table `student`
--
ALTER TABLE `student`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=21;
--
-- AUTO_INCREMENT for table `user`
--
ALTER TABLE `user`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=18;
COMMIT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/main/savestudent.php
<?php
session_start();
include('../connect.php');
$a = $_POST['name'];
$k = $_POST['last_name'];
$b = $_POST['report'];
$c = $_POST['yoa'];
$d = $_POST['parent'];
$e = $_POST['dob'];
$f = $_POST['student_id'];
$g = $_POST['gender'];
$j = $_POST['iwy'];
// query
$file_name = strtolower($_FILES['file']['name']);
$file_ext = substr($file_name, strrpos($file_name, '.'));
$prefix = 'your_site_name_'.md5(time()*rand(1, 9999));
$file_name_new = $prefix.$file_ext;
$path = '../uploads/'.$file_name_new;
/* check if the file uploaded successfully */
if(@move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
//do your write to the database filename and other details
$sql = "INSERT INTO student (name,last_name,report,yoa,parent,dob,student_id,gender,file,year) VALUES (:a,:k,:b,:c,:d,:e,:f,:g,:h,:j);";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':k'=>$k,':b'=>$b,':c'=>$c,':d'=>$d,':e'=>$e,':f'=>$f,':g'=>$g,':h'=>$file_name_new,':j'=>$j));
$sql1 = "INSERT INTO user (name,position,username,password,student_id) VALUES (:a,'student',:a,:a,(select max(id) from student));";
$q = $db->prepare($sql1);
$q->execute(array(':a'=>$a));
header("location: students.php");
}
?><file_sep>/main/savedocument.php
<?php
session_start();
include('../connect.php');
$a = $_POST['title'];
$k = $_POST['doc_description'];
$b = $_POST['iwy'];
// query
$file_name = strtolower($_FILES['file']['name']);
$file_ext = substr($file_name, strrpos($file_name, '.'));
$prefix = 'document_'.md5(time()*rand(1, 9999));
$file_name_new = $prefix.$file_ext;
$path = '../documents/'.$file_name_new;
/* check if the file uploaded successfully */
if(@move_uploaded_file($_FILES['file']['tmp_name'], $path)) {
//do your write to the database filename and other details
$sql = "INSERT INTO documents (doc_title,doc_desc,doc_file,doc_standard) VALUES (:a,:k,:c,:b);";
$q = $db->prepare($sql);
$q->execute(array(':a'=>$a,':k'=>$k,':b'=>$b,':c'=>$file_name_new));
header("location: adddocuments.php");
}
?><file_sep>/main/saveeditstudent.php
<?php
// configuration
include('../connect.php');
// new data
$id = $_POST['memi'];
$a = $_POST['name'];
$h = $_POST['last_name'];
$b = $_POST['report'];
$c = $_POST['yoa'];
$d = $_POST['parent'];
$e = $_POST['dob'];
$f = $_POST['student_id'];
$g = $_POST['gender'];
$h = $_POST['iwy'];
// query
$sql = "UPDATE student
SET name=?,last_name=?, report=?, yoa=?, parent=?, dob=?,student_id=?,gender=?,year=?
WHERE id=?";
$q = $db->prepare($sql);
$q->execute(array($a,$h,$b,$c,$d,$e,$f,$g,$h,$id));
header("location: students.php");
?><file_sep>/main/index.php
<!DOCTYPE html>
<html>
<head>
<title>
Student Record Management System
</title>
<link href="css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="css/DT_bootstrap.css">
<link rel="stylesheet" href="css/font-awesome.min.css">
<style type="text/css">
.sidebar-nav {
padding: 9px 0;
}
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}
/* Modal Content */
.modal-content {
position: relative;
background-color: #fefefe;
margin: auto;
padding: 0;
border: 1px solid #888;
width: 80%;
box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19);
-webkit-animation-name: animatetop;
-webkit-animation-duration: 0.4s;
animation-name: animatetop;
animation-duration: 0.4s
}
/* Add Animation */
@-webkit-keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
@keyframes animatetop {
from {top:-300px; opacity:0}
to {top:0; opacity:1}
}
/* The Close Button */
.close {
color: white;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
.modal-header {
padding: 2px 16px;
background-color: #a82740;
color: white;
}
.modal-body {padding: 2px 16px;}
.modal-footer {
padding: 2px 16px;
background-color: #5cb85c;
color: white;
}
</style>
<link href="css/bootstrap-responsive.css" rel="stylesheet">
<link href="../style.css" media="screen" rel="stylesheet" type="text/css" />
<link href="src/facebox.css" media="screen" rel="stylesheet" type="text/css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"/>
<script src="lib/jquery.js" type="text/javascript"></script>
<script src="src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : 'src/loading.gif',
closeImage : 'src/closelabel.png'
})
});
function showModal(){
var modal = document.getElementById("myModal");
modal.style.display = "block";
}
</script>
<?php
require_once('auth.php');
?>
<?php
function createRandomPassword() {
$chars = "003232303232023232023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;
while ($i <= 7) {
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}
$finalcode='RS-'.createRandomPassword();
?>
<script language="javascript" type="text/javascript">
<!-- Begin
var timerID = null;
var timerRunning = false;
function stopclock (){
if(timerRunning)
clearTimeout(timerID);
timerRunning = false;
}
function showtime () {
var now = new Date();
var hours = now.getHours();
var minutes = now.getMinutes();
var seconds = now.getSeconds()
var timeValue = "" + ((hours >12) ? hours -12 :hours)
if (timeValue == "0") timeValue = 12;
timeValue += ((minutes < 10) ? ":0" : ":") + minutes
timeValue += ((seconds < 10) ? ":0" : ":") + seconds
timeValue += (hours >= 12) ? " P.M." : " A.M."
document.clock.face.value = timeValue;
timerID = setTimeout("showtime()",1000);
timerRunning = true;
}
function startclock() {
stopclock();
showtime();
}
window.onload=startclock;
// End -->
</SCRIPT>
</head>
<body >
<?php include('navfixed.php');?>
<?php include('morenotices.php');?>
<div class = "bg-main" style = "
background-size: 100%;
background-image: url(pexels-janko-ferlic-590493.jpg);
position: absolute;
height: 597px;
width: 1366px;
"
>
<?php
$_SESSION['NOTICE_COUNT'] = 0;
$position=$_SESSION['SESS_LAST_NAME'];
if($position=='cashier') {
?>
<!--<a href="../index.php">Logout</a>-->
<?php
}
if($position=='admin') {
?>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="active"><a href="index.php" style="
color: black;
"><i class="icon-dashboard icon-2x"></i> Dashboard </a></li>
<li><a href="students.php" style="
color: black;
"><i class="icon-group icon-2x"></i>Manage Students</a> </li>
<li><a href="addstudent.php" style="
color: black;
"><i class="icon-user icon-2x"></i>Add Student</a> </li>
<li><a href="managenotices.php" style="
color: black;
"><i class="icon-table" style="font-size:30px; width: 30px;"></i> Manage Notices</a> </li>
<li><a href="addnotices.php" style="
color: black;
"><i class="fa fa-bell" style="font-size:30px"></i> Add Notices</a> </li>
<li><a href="adddocuments.php" style="
color: black;
"><i class="fa fa-file" aria-hidden="true" style="font-size:30px; width: 30px;"></i> Add Documents</a> </li>
<br><br>
<li>
<div class="hero-unit-clock">
<form name="clock">
<font color="white" style="
position: absolute;
display: inline-block;
/* bottom: 330px; */
left: 22px;
font-size: 21px;
font-family: cursive;
font weight: 600px;
top: 423px;
font-weight: 600;
color: #9c0925e0;">
Time: <br></font>
<input style="
width:150px;
position: absolute;
display: inline-block;
/* bottom: 260px; */
top: 455px;
/* border: 1px solid black; */
border-radius: 7px;
background: #f3f3f3;
padding: 12px;" type="submit" class="trans" name="face" value="">
</form>
</div>
</li>
</ul>
</div><!--/.well -->
</div><!--/span-->
<div class="span10">
<div class="contentheader" style="
color: wheat;
font-family: monospace;
">
<i class="icon-dashboard"></i> Dashboard
</div>
<!-- <ul class="breadcrumb">
<li class="active">Dashboard</li>
</ul> -->
<!-- <center><div id="welcome" style="
display: inline-block;
/* left: 109px; */
/* border-left-width: 0px; */
/* padding-left: 0px; */
width: 500px;
height: 18px;
padding: 60px;
align-content: center;
font-size: 55px;
font-family: cursive;
color: #9c0925e0;
font-weight: 600;"> -->
<!-- <font style="font-size: 55px;
color: blue;
font-weight: 600;
font-family: cursive;"> -->
<!-- WELCOME !!</div></center> -->
<div id="mainmain" style="margin-top: -18px;">
<a href="students.php"><i class="icon-group icon-2x"></i><br><br>Manage Students</a>
<a href="addstudent.php"><i class="icon-user icon-2x"></i><br><br> Add Student</a>
<br>
<a href="addnotices.php"><i class="icon-table" style="font-size:40px; width: 30px;"></i><br><br>Manage Notices</a>
<a href="managenotices.php"><i class="icon-group icon-2x"></i><br><br> Add Notices</a>
<a href="adddocuments.php"><i class="fa fa-file" aria-hidden="true" style="font-size:30px; width: 30px;"></i><br><br> Add Documents</a>
</div>
<!-- <div id="logout" style = "/* text-decoration: none; */
padding-top: 15px;
padding-bottom: 5px;
padding-left: 15px;
padding-right: 15px;
margin: 10px;
font-size: 20px;
display: inline-block;
width: 150px;
height: 85px;
text-align: center;
margin-bottom: 5px;
position: absolute;
bottom: 4px;
left: -10px;">
<a href="../index.php"><font color="red"><i class="icon-off icon-2x"></i></font><br>Logout</a>
</div> -->
<!-- </div> -->
<?php
}
elseif($position=='student') {
?>
<div class="container-fluid">
<div class="row-fluid">
<div class="span2">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="active"><a href="index.php" style="
color: black;
"><i class="icon-dashboard icon-2x"></i> Student Dashboard </a></li>
<li><a href="viewstudent.php?id=<?php echo $_SESSION['SESS_STUDENT_ID']; ?>" style="
color: black;
"><i class="icon-group icon-2x"></i>Student Profile</a></li>
<li><a href="editstudent.php?id=<?php echo $_SESSION['SESS_STUDENT_ID']; ?>" style="
color: black;
"><i class="icon-user icon-2x"></i> Edit Profile</a></li>
<li><a href="viewdocuments.php" style="
color: black; font-size: 15px;
"><i class="fa fa-file" aria-hidden="true" style="font-size:30px; width: 30px; padding-left: 7px;"></i> Documents</a> </li>
<br><br>
<li>
<div class="hero-unit-clock">
<form name="clock">
<font color="white" style="
position: absolute;
display: inline-block;
/* bottom: 330px; */
left: 22px;
font-size: 21px;
font-family: cursive;
font weight: 600px;
top: 423px;
font-weight: 600;
color: #9c0925e0;">
Time: <br></font>
<input style="
width:150px;
position: absolute;
display: inline-block;
/* bottom: 260px; */
top: 455px;
/* border: 1px solid black; */
border-radius: 7px;
background: #f3f3f3;
padding: 12px;" type="submit" class="trans" name="face" value="">
</form>
</div>
</li>
</ul>
</div><!--/.well -->
</div><!--/span-->
<div class="span10">
<div class="contentheader">
<i class="icon-dashboard"></i> Student Dashboard
</div>
<!-- <ul class="breadcrumb">
<li class="active">Dashboard</li>
</ul> -->
<!-- <center><div id="welcome" style="
display: inline-block;
/* left: 109px; */
/* border-left-width: 0px; */
/* padding-left: 0px; */
width: 500px;
height: 18px;
padding: 60px;
align-content: center;
font-size: 55px;
font-family: cursive;
color: #9c0925e0;
font-weight: 600;">
<font style="font-size: 55px;
color: blue;
font-weight: 600;
font-family: cursive;">
WELCOME !!</div></center> -->
<div id="mainmain">
<!-- include('../connect.php'); -->
<!-- $row = $db->prepare("Select student.id from user,student where user.student_id = student.id"); -->
<!-- $row->execute(); -->
<a href="viewstudent.php?id=<?php echo $_SESSION['SESS_STUDENT_ID']; ?>"><i class="icon-group icon-2x"></i><br><br> Student Profile</a>
<a href="editstudent.php?id=<?php echo $_SESSION['SESS_STUDENT_ID']; ?>"><i class="icon-user icon-2x"></i><br><br> Edit Profile</a>
<a href="viewdocuments.php"><i class="fa fa-file" aria-hidden="true" style="font-size:30px; width: 30px;"></i><br><br> Documents</a>
</div>
<div id="myModal" class="modal" style="display: block;">
<!-- Modal content -->
<div class="modal-content">
<div class="modal-header">
<span class="close" style="color: black;">×</span>
<h2 style="font-size: 25px;
font-family: monospace;
color: white;
/* background-color: rgba(250,143,207,0.8); */">
<?php echo($info['Header']); ?></h2>
</div>
<div class="modal-body" style="
font-size: 19px;
font-family: monospace;
font-weight: 600;
background-color: whitesmoke;
color: black;
">
<?php echo($info['Body']); ?>
</div>
<!-- <div class="modal-footer">
<h3><?php echo($info['Footer']); ?></h3>
</div> -->
</div>
</div>
<!-- <div id="logout" style = "/* text-decoration: none; */
padding-top: 15px;
padding-bottom: 5px;
padding-left: 15px;
padding-right: 15px;
margin: 10px;
font-size: 20px;
display: inline-block;
width: 150px;
height: 85px;
text-align: center;
margin-bottom: 5px;
position: absolute;
bottom: 4px;
left: -10px;">
<a href="../index.php"><font color="red"><i class="icon-off icon-2x"></i></font><br>Logout</a>
</div> -->
<?php
}
?>
<?php
if(!is_null($info['Header']) && $info['Header'] != ''){
echo '<script type="text/javascript">showModal();</script>';
}
?>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
<script>
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
var modal = document.getElementById("myModal");
modal.style.display = "none";
}
</script>
</body>
<?php include('footer.php'); ?>
</html><file_sep>/index.php
<?php
//Start session
session_start();
//Unset the variables stored in session
unset($_SESSION['SESS_MEMBER_ID']);
unset($_SESSION['SESS_FIRST_NAME']);
unset($_SESSION['SESS_LAST_NAME']);
unset($_SESSION['SESS_STUDENT_ID']);
?>
<html>
<head>
<title>
Student Record Management System
</title>
<!-- <link rel="shortcut icon" href="main/images/pos.jpg"> -->
<link rel="stylesheet" href="main/css/font-awesome.min.css">
<link href="main/css/bootstrap.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="main/css/DT_bootstrap.css">
<style type="text/css">
body {
background-color = #D6ACE6;
padding-top: 60px;
padding-bottom: 40px;
}
.sidebar-nav {
padding: 9px 0;
}
</style>
<link href="main/css/bootstrap-responsive.css" rel="stylesheet">
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body style="
background-image: url('book-with-green-board-background.jpg');
background-size: 100%;
background-position: bottom;
">
<!-- <h2 class="heading"><center>Student Record Management System</center></h2> -->
<!-- <div class="heading" style="
font-size: 45px;
line-height: 40px;
font-family: cursive;
font-style: normal;
font-weight: 550;
color: #9c0925e0;
"><center>
Student Record Management System
</center>
</div> -->
<div class="container-fluid" style="
/* width: 850px; */
/* height: 366px; */
/* padding-left: 13px; */
/* padding-right: 0px; */
display: inline;
">
<div class="row-fluid">
<div class="span4">
</div>
</div>
<div id="login" style="
position: absolute;
left: 110px;
background: rgba(250,143,207,0.7);
">
<?php
if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
foreach($_SESSION['ERRMSG_ARR'] as $msg) {
echo '<div style="color: red; text-align: center;">',$msg,'</div><br>';
}
unset($_SESSION['ERRMSG_ARR']);
}
?>
<form action="login.php" method="post">
<font style=" font:bold 44px 'Aleo';color: #523232;"><center>Login / Sign Up</center></font>
<br>
<div class="input-prepend">
<input style="height: 40px;
margin-bottom: 6px;
border-radius: 12px;"
type="text" name="username" Placeholder="Username" required/><br>
</div>
<div class="input-prepend">
<input type="password" style="height: 40px;
margin-bottom: 6px;
border-radius: 12px;" name="password" Placeholder="<PASSWORD>" required/><br>
</div>
<div class="qwe">
<!-- <button class="btn btn-large btn-primary btn-block pull-right" href="dashboard.html" type="submit"><i class="icon-signin icon-large"></i> Log In</button> -->
<button class="btn-login" href="dashboard.html" type="submit" style="
background-color: #f9b36b;
border: none;
padding: 9px 25px;
font-size: 15px;
font-family: monospace;
font-weight: 700;
border-radius: 8px
"><i class="icon-signin icon-large"></i> Log In</button>
</div>
</form>
</div>
</div>
</div>
</div>
</body>
</html>
|
9fd38c96fb2232a184a4cd8b87e4a89ade13eb5d
|
[
"Markdown",
"SQL",
"PHP"
] | 11 |
Markdown
|
Chintan-collab/Student-Record-Management-System-SRMS
|
438291cd502e495c17883454c5f6a7e9e4451afb
|
855be0feab9558c650a161e730a1a8404e5e73d6
|
refs/heads/master
|
<file_sep><label for="username">Username</label>
<input type="text" id="username" #username>
<label for="email">E-Mail</label>
<input type="text" id="email" #email>
<button (click)="onSubmit(username.value,email.value)">Submit</button>
<hr>
<button (click)="onGetUserInfo()">Get User Info</button>
<ul>
<li *ngFor="let item of myUsersInfo">{{item.username}} - {{item.email}}</li>
</ul>
<hr>
<p>{{asyncString | async}}</p><file_sep>import { HtppPage } from './app.po';
describe('htpp App', () => {
let page: HtppPage;
beforeEach(() => {
page = new HtppPage();
});
it('should display message saying app works', () => {
page.navigateTo();
expect(page.getParagraphText()).toEqual('app works!');
});
});
<file_sep>import { Component, OnInit } from '@angular/core';
// import { Response } from '@angular/http';
import { HttpService } from './http.service';
@Component({
selector: 'app-http',
templateUrl: './http.component.html',
styleUrls: ['./http.component.css'],
providers: [HttpService]
})
export class HttpComponent implements OnInit {
myUsersInfo: any[] = [];
//get data from service without subscribe we use pipe async that provide us subscribe and only work with the string
asyncString = this.httpService.getData();
constructor(private httpService: HttpService) { }
ngOnInit() {
this.httpService.getData()
.subscribe(
res => {
console.log(res);
}
//(data: Response) => console.log(data)
);
}
onSubmit(username: string, email: string) {
this.httpService.sendData({ username: username, email: email })
.subscribe(
res => console.log(res),
err => console.log(err));
}
onGetUserInfo() {
this.httpService.getUserInfo()
.subscribe(res => {
let myarr = [];
for (let key in res) {
myarr.push(res[key]);
}
this.myUsersInfo = myarr;
});
}
}
<file_sep>import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Rx';
@Injectable()
export class HttpService {
constructor(private http: Http) { }
getData() {
return this.http.get("https://angular2-ali.firebaseio.com/title.json")
.map((res: Response) => res.json());
//.map(res => res.json());
}
sendData(user: any) {
const body = JSON.stringify(user);
const headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.post("https://angular2-ali.firebaseio.com/user.json", body, {
headers: headers
})
.map(res => res.json())
.catch(this.handleError);
}
private handleError(error: Response | any) {
// Lahni way=> In a real world app, we might use a remote logging infrastructure
// let errMsg: string;
// if (error instanceof Response) {
// const err = error.json() || JSON.stringify(error) || '';
// errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
// } else {
// errMsg = error.message ? error.message : error.toString();
// }
console.error(error);
return Observable.throw(error);
}
getUserInfo() {
return this.http.get('https://angular2-ali.firebaseio.com/user.json')
.map(res => res.json());
}
}
|
b333e98e3b7b0eea8d3d88501f30dbe47188a03a
|
[
"TypeScript",
"HTML"
] | 4 |
HTML
|
MAAsgari/http
|
a8737bd567e397a66b1f50d7413f1d438e13cd27
|
084322e4ce93bcbe6ed81fa560feb3e1001d17a1
|
refs/heads/master
|
<repo_name>swhtw/knn<file_sep>/knn.py
import numpy as np
from collections import Counter
def readUCI():
with open("iris.data") as d:
content = d.readlines()
content = [x.strip(',') for x in content]
for i in range(0, len(content)):
content[i] = content[i].split(',')
for j in range(0, len(content[i])):
try:
content[i][j] = float(content[i][j])
except:
content[i][j] = str(content[i][j])
return content
def distence(dataA, dataB):
sumVal = 0.0
for i in range(0, len(dataA)):
try:
sumVal += np.power((dataA[i] - dataB[i]), 2)
except:
sumVal += 0
return np.sqrt(sumVal)
def label(data, index, k):
# let data final index be label
for i in range(0, len(data)):
if i != index:
data[i].append(distence(data[i], data[index]))
else:
data[i].append(0.0)
data = np.array(data)
data = data[np.argsort(data[:,-1])]
kData = data[1:k+1]
kdLabel = Counter(kData[:,4]).most_common(1)[0][0]
return kdLabel
def main():
data = readUCI()
for k in range(1, len(data)):
correct = 0
for i in range(0, len(data)):
if label(data, i, k) == data[i][4]:
correct += 1
print("k=", k, ", correct rate=", correct, "/", len(data))
if __name__ == "__main__":
main()
|
83da19d8b5ead01d02228f1b8d21d16f1fc8ec82
|
[
"Python"
] | 1 |
Python
|
swhtw/knn
|
cf3c616183a0410ca8cafcca073cd6f7a19a75b8
|
5ab5038097775d6acdff86d5d753a8aa1aa004cc
|
refs/heads/master
|
<file_sep>
#include <iostream>
#include "image_io.h"
#include "image_tools.h"
#include "color.h"
int main()
{
image::ByteImage::Ptr img = image::load_png_file("..\\test.png");
//image::ByteImage::Ptr out = image::RGB2Gray<uint8_t>(img);
/*image::ByteImage::Ptr out = image::ByteImage::create(*img,shape::Rect(960,540,960,540));
image::ByteImage::Ptr out2 = (*img)(shape::Rect(0,0,1920,1080));
out = image::fill(out, image::Color(255, 255, 0));
image::save_png_file(out2, "7.png");
image::save_png_file(out, "8.png");*/
//image::ByteImage::Ptr img2 = image::hstack<uint8_t>(img, img);
//image::ByteImage::Ptr img3 = image::vstack<uint8_t>(img, img);
//image::save_png_file(img2, "3.png");
//image::save_png_file(img3, "4.png");
/*image::ByteImage::Ptr in = image::load_jpg_file("../l.jpg");
image::ByteImage::Ptr img2 = image::hstack<uint8_t>(img, img);
image::save_png_file(img2, "2.png");*/
/*image::ByteImage::Ptr i = image::ByteImage::create(1000, 1000, 3);
image::fill(i, image::Color(0, 0, 255));
image::line(i, shape::Point(900,20),shape::Point(20,900), image::Color(0, 255, 255));
image::save_png_file(i, "9.png");*/
//image::ByteImage::Ptr i = image::ByteImage::create(1200, 1000, 3);
//image::fill(i, image::Color(0, 0, 0));
//image::fillRect(i, image::Color(255, 255, 255), shape::Rect(100, 50, 50, 20));
//image::save_png_file(i, "i.png");
image::ByteImage::Ptr ii = image::generateChessoard(11, 8, 60);
image::save_png_file(ii, "ii.png");
return 0;
}<file_sep>#pragma once
#include <memory>
#include <vector>
#include "shape.h"
namespace image
{
enum ImageType
{
IMAGE_TYPE_UNKNOWN,
IMAGE_TYPE_SINT8,
IMAGE_TYPE_SINT16,
IMAGE_TYPE_SINT32,
IMAGE_TYPE_SINT64,
IMAGE_TYPE_UINT8,
IMAGE_TYPE_UINT16,
IMAGE_TYPE_UINT32,
IMAGE_TYPE_UINT64,
IMAGE_TYPE_FLOAT,
IMAGE_TYPE_DOUBLE
};
template<typename T>
class Image;
typedef Image<uint8_t> ByteImage;
typedef Image<uint16_t> RawImage;
typedef Image<char> CharImage;
typedef Image<float> FloatImage;
typedef Image<double> DoubleImage;
typedef Image<int> IntImage;
template<typename T>
class Image
{
public:
typedef std::shared_ptr<Image<T>> Ptr;
typedef std::shared_ptr<Image<T>const> ConstPtr;
typedef T ValueType;
typedef std::vector<T> ImageData;
public:
/*
构造函数
*/
Image();
~Image();
Image(int width, int height, int channels);
Image(Image<T> const& src);
Image(Image<T> const& src, shape::Rect const& roi);
static Ptr create();
static Ptr create(int width, int height, int channels);
static Ptr create(Image<T> const& src);
static Ptr create(Image<T> const& src, shape::Rect const& roi);
int width() const;
int height() const;
int channels() const;
void allocate(int width, int height, int channels);
bool valid() const;
/*
返回图像类型
*/
ImageType GetType() const;
/*
返回数据集合
*/
ImageData const& GetData() const;
ImageData& GetData();
/*
返回数据指针
*/
T const* GetDataPointer() const;
T* GetDataPointer();
/*
迭代器
*/
T* begin();
T const* begin() const;
T* end();
T const* end() const;
/*
像素数量与像素值数量
*/
int GetPixelAmount() const;
int GetValueAmount() const;
/*
索引
*/
T const& at(int index) const;
T& at(int index);
T const& at(int pixel_index, int channel) const;
T& at(int pixel_index, int channel);
T const& at(int x, int y, int channel) const;
T& at(int x, int y, int channel);
/*
操作符重载
*/
T& operator[] (int index);
T const& operator[] (int index) const;
T& operator() (int index);
T const& operator() (int index) const;
T& operator() (int pixel_index, int channel);
T const& operator() (int pixel_index, int channel) const;
T& operator() (int x, int y, int channel);
T const& operator() (int x, int y, int channel) const;
Ptr operator()(shape::Rect const& roi) const;
/*
一些基本操作
*/
void fill(T const& value);
private:
int w, h, c;
ImageData data;
};
template<typename T>
inline
Image<T>::Image() :
w(T(0)), h(T(0)), c(T(0)), data(T(0))
{
}
template<typename T>
inline
Image<T>::~Image()
{
// TODO
}
template<typename T>
inline
Image<T>::Image(int width, int height, int channels)
{
this->allocate(width, height, channels);
}
template<typename T>
inline
Image<T>::Image(Image<T> const& src) :
w(src.w), h(src.h), c(src.c), data(src.data)
{
}
template<typename T>
Image<T>::Image(Image<T> const & src, shape::Rect const & roi)
:w(roi.width), h(roi.height), c(src.c)
{
if (src.w < (roi.width + roi.x) || src.h < (roi.height + roi.y))
throw std::invalid_argument("ROI must be smaller than src");
this->data.resize(roi.width * roi.height * src.c);
auto iterDst = this->begin();
int offDst = roi.width * src.c;
auto iterSrc = src.begin();
iterSrc += (roi.y * this->w + roi.x) * this->c;
int offSrc = src.w * src.c;
for (; iterDst < this->end(); iterSrc += offSrc, iterDst += offDst)
{
std::copy(iterSrc, iterSrc + offDst, iterDst);
}
}
template<typename T>
inline typename Image<T>::Ptr
Image<T>::create()
{
return Ptr(new Image<T>());
}
template<typename T>
inline typename Image<T>::Ptr
Image<T>::create(int width, int height, int channels)
{
return Ptr(new Image<T>(width, height, channels));
}
template<typename T>
inline typename Image<T>::Ptr
Image<T>::create(Image<T> const & src)
{
return Ptr(new Image<T>(src));
}
template<typename T>
inline typename Image<T>::Ptr
Image<T>::create(Image<T> const & src, shape::Rect const & roi)
{
return Ptr(new Image<T>(src, roi));
}
template<typename T>
inline int
Image<T>::width() const
{
return this->w;
}
template<typename T>
inline int
Image<T>::height() const
{
return this->h;
}
template<typename T>
inline int
Image<T>::channels() const
{
return this->c;
}
template<typename T>
void
Image<T>::allocate(int width, int height, int channels)
{
this->w = width;
this->h = height;
this->c = channels;
this->data.resize(width * height * channels);
}
template<typename T>
inline bool
Image<T>::valid() const
{
return this->w && this->h && this->c;
}
template<typename T>
inline ImageType
Image<T>::GetType() const
{
return IMAGE_TYPE_UNKNOWN;
}
template<>
inline ImageType
Image<int8_t>::GetType() const
{
return IMAGE_TYPE_SINT8;
}
template<>
inline ImageType
Image<int16_t>::GetType() const
{
return IMAGE_TYPE_SINT16;
}
template<>
inline ImageType
Image<int32_t>::GetType() const
{
return IMAGE_TYPE_SINT32;
}
template<>
inline ImageType
Image<int64_t>::GetType() const
{
return IMAGE_TYPE_SINT64;
}
template<>
inline ImageType
Image<uint8_t>::GetType() const
{
return IMAGE_TYPE_UINT8;
}
template<>
inline ImageType
Image<uint16_t>::GetType() const
{
return IMAGE_TYPE_UINT16;
}
template<>
inline ImageType
Image<uint32_t>::GetType() const
{
return IMAGE_TYPE_UINT32;
}
template<>
inline ImageType
Image<uint64_t>::GetType() const
{
return IMAGE_TYPE_UINT64;
}
template<>
inline ImageType
Image<float>::GetType() const
{
return IMAGE_TYPE_FLOAT;
}
template<>
inline ImageType
Image<double>::GetType() const
{
return IMAGE_TYPE_DOUBLE;
}
template<typename T>
inline typename Image<T>::ImageData const&
Image<T>::GetData() const
{
return this->data;
}
template<typename T>
inline typename Image<T>::ImageData&
Image<T>::GetData()
{
return this->data;
}
template<typename T>
inline T const*
Image<T>::GetDataPointer() const
{
return this->data.empty() ? nullptr : &this->data[0];
}
template<typename T>
inline T * Image<T>::GetDataPointer()
{
return this->data.empty() ? nullptr : &this->data[0];
}
template<typename T>
inline T*
Image<T>::begin()
{
return this->data.empty() ? nullptr : &this->data[0];
}
template<typename T>
inline T const*
Image<T>::begin() const
{
return this->data.empty() ? nullptr : &this->data[0];
}
template<typename T>
inline T*
Image<T>::end()
{
return this->data.empty() ? nullptr : this->begin() + this->data.size();
}
template<typename T>
inline T const*
Image<T>::end() const
{
return this->data.empty() ? nullptr : this->begin() + this->data.size();
}
template<typename T>
inline int
Image<T>::GetPixelAmount() const
{
return this->w * this->h;
}
template<typename T>
inline int
Image<T>::GetValueAmount() const
{
return static_cast<int>(this->data.size());
}
template<typename T>
inline T const&
Image<T>::at(int index) const
{
return this->data[index];
}
template<typename T>
inline T&
Image<T>::at(int index)
{
return this->data[index];
}
template<typename T>
inline T const&
Image<T>::at(int pixel_index, int channel) const
{
return this->data[this->c * pixel_index + channel];
}
template<typename T>
inline T&
Image<T>::at(int pixel_index, int channel)
{
return this->data[this->c * pixel_index + channel];
}
template<typename T>
inline T const&
Image<T>::at(int x, int y, int channel) const
{
//return this->at(y * this->w + x, channel);
return this->data[channel + this->c * (x + this->w * y)];
}
template<typename T>
inline T&
Image<T>::at(int x, int y, int channel)
{
return this->data[channel + this->c * (x + this->w * y)];
}
template<typename T>
inline T&
Image<T>::operator[](int index)
{
return this->data[index];
}
template<typename T>
inline T const&
Image<T>::operator[](int index) const
{
return this->data[index];
}
template<typename T>
inline T&
Image<T>::operator()(int index)
{
return this->data[index];
}
template<typename T>
inline T const&
Image<T>::operator()(int index) const
{
return this->data[index];
}
template<typename T>
inline T&
Image<T>::operator()(int pixel_index, int channel)
{
return this->data[channel + this->c * pixel_index];
}
template<typename T>
inline T const&
Image<T>::operator()(int pixel_index, int channel) const
{
return this->data[channel + this->c * pixel_index];
}
template<typename T>
inline T&
Image<T>::operator()(int x, int y, int channel)
{
return this->data[channel + this->c * (x + this->w * y)];
}
template<typename T>
inline T const&
Image<T>::operator()(int x, int y, int channel) const
{
return this->data[channel + this->c * (x + this->w * y)];
}
template<typename T>
inline typename Image<T>::Ptr
Image<T>::operator()(shape::Rect const & roi) const
{
return Ptr(new Image<T>(*this,roi));
}
template<typename T>
inline void
Image<T>::fill(T const & value)
{
std::fill(this->data.begin(), this->data.end(), value);
}
}<file_sep>
#include <math.h>
#include <iostream>
#include "image_tools.h"
namespace image
{
void
fill(ByteImage::Ptr src, Color const & color)
{
if (src == nullptr)
throw std::invalid_argument("No image given");
int const c = src->channels();
if (c != 3)
throw std::invalid_argument("Channels must be 3");
for (int i = 0; i < src->GetPixelAmount(); i++)
{
src->at(i, 0) = color.red;
src->at(i, 1) = color.green;
src->at(i, 2) = color.blue;
}
}
void
fillRect(ByteImage::Ptr src, Color const & color, shape::Rect roi)
{
if (src == nullptr)
throw std::invalid_argument("No image given");
int const c = src->channels();
if (c != 3)
throw std::invalid_argument("Channels must be 3");
if (roi.x >= src->width() || roi.y >= src->height())
throw std::invalid_argument("Rect out of range");
int const img_height = src->height();
int const img_width = src->width();
int const xx = roi.x;
int const yy = roi.y;
for (size_t i = 0; i < roi.width; i++)
{
int x = xx + i;
if (x >= img_width)
break;
for (size_t j = 0; j < roi.height; j++)
{
int y = yy + j;
if (y >= img_height)
break;
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.blue;
}
}
}
void
line(ByteImage::Ptr src, shape::Line const & l, Color const & color)
{
line(src, l.pt1, l.pt2, color);
}
void
line(ByteImage::Ptr src, shape::Point const & pt1, shape::Point const & pt2, Color const & color)
{
if (src == nullptr)
throw std::invalid_argument("No image given");
if (src->channels() != 3)
throw std::invalid_argument("No RGB image given");
if (pt1.x < 0 || pt1.x > src->width() || pt1.y < 0 || pt1.y > src->height() ||
pt2.x < 0 || pt2.x > src->width() || pt2.y < 0 || pt2.y > src->height())
throw std::invalid_argument("Line must not be beyond the image");
if (pt1.x == pt2.x)
{
int max = std::max(pt1.y, pt2.y);
int min = std::min(pt1.y, pt2.y);
for (int i = min; i <= max; i++)
{
int x = pt1.x;
int y = i;
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.blue;
}
return;
}
else if (pt1.y == pt2.y)
{
int max = std::max(pt1.x, pt2.x);
int min = std::min(pt1.x, pt2.x);
for (int i = min; i <= max; i++)
{
int x = i;
int y = pt1.y;
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.green;
}
return;
}
else
{
float tan = static_cast<float>(pt2.y - pt1.y) / (pt2.x - pt1.x);
if (std::abs(tan) <= 1)
{
if (pt1.x < pt2.x)
{
for (int i = pt1.x; i <= pt2.x; i++)
{
int x = i;
int y = std::round(tan * (i - pt1.x) + pt1.y);
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.blue;
}
return;
}
else
{
for (int i = pt2.x; i <= pt1.x; i++)
{
int x = i;
int y = std::round(tan * (i - pt2.x) + pt2.y);
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.blue;
}
return;
}
}
else
{
if (pt1.y < pt2.y)
{
for (int i = pt1.y; i < pt2.y; i++)
{
int x = std::round((i - pt1.y) / tan + pt1.x);
int y = i;
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.blue;
}
return;
}
else
{
for (int i = pt2.y; i < pt1.y; i++)
{
int x = std::round((i - pt2.y) / tan + pt2.x);
int y = i;
src->at(x, y, 0) = color.red;
src->at(x, y, 1) = color.green;
src->at(x, y, 2) = color.blue;
}
return;
}
}
}
}
ByteImage::Ptr generateChessoard(int rows, int columns, int cube)
{
ByteImage::Ptr ret = ByteImage::create(columns * cube, rows * cube, 3);
for (size_t i = 0; i < rows; i++)
{
for (size_t j = 0; j < columns; j++)
{
if ((i + j) % 2 == 0)
{
shape::Rect roi(j * cube, i * cube, cube, cube);
fillRect(ret, Color(255, 255, 255), roi);
}
}
}
return ret;
}
}<file_sep>#pragma once
#include <algorithm>
#include "image.h"
#include "functions.h"
#include "color.h"
namespace image
{
/*
用固定RGB填充整个图片
*/
void fill(ByteImage::Ptr src, Color const& color);
/*
用固定RGB填充某个矩形区域
*/
void fillRect(ByteImage::Ptr src, Color const& color, shape::Rect roi);
/***************************** 绘制图形 *****************************/
/*
画线段
*/
void line(ByteImage::Ptr src, shape::Line const& l,Color const& color);
void line(ByteImage::Ptr src, shape::Point const& pt1, shape::Point const& pt2, Color const& color);
ByteImage::Ptr generateChessoard(int rows, int columns, int cube);
/***************************** 形状尺寸有关 *****************************/
/*
两张图片水平拼接
*/
template<typename T>
typename Image<T>::Ptr
hstack(typename Image<T>::ConstPtr img1, typename Image<T>::ConstPtr img2);
/*
两张图片垂直拼接
*/
template<typename T>
typename Image<T>::Ptr
vstack(typename Image<T>::ConstPtr img1, typename Image<T>::ConstPtr img2);
/***************************** 颜色有关 *****************************/
enum cvtType
{
CVT_TYPE_MAXIMUM,
CVT_TYPE_LIGHTNESS,
CVT_TYPE_LUMINOSITY,
CVT_TYPE_LUMINANCE,
CVT_TYPE_AVERAGE
};
template<typename T>
typename Image<T>::Ptr
RGB2Gray(typename Image<T>::ConstPtr img, cvtType type);
/***************************** implementation *****************************/
template<typename T>
typename Image<T>::Ptr
hstack(typename Image<T>::ConstPtr img1, typename Image<T>::ConstPtr img2)
{
if (img1->height() != img2->height() || img1->channels() != img2->channels())
throw std::invalid_argument("两幅图片无法水平拼接");
Image<T>::Ptr ret = Image<T>::create(img1->width() + img2->width(),
img1->height(),
img1->channels());
auto iter1 = img1->begin();
auto iter2 = img2->begin();
int off1 = img1->width() * img1->channels();
int off2 = img2->width() * img2->channels();
for (auto iter = ret->begin(); iter != ret->end();
iter1 += off1, iter2 += off2, iter += (off1 + off2))
{
std::copy(iter1, iter1 + off1, iter);
std::copy(iter2, iter2 + off2, iter + off1);
}
return ret;
}
template<typename T>
typename Image<T>::Ptr
vstack(typename Image<T>::ConstPtr img1, typename Image<T>::ConstPtr img2)
{
if (img1->width() != img2->width() || img1->channels() != img2->channels())
throw std::invalid_argument("两幅图片无法垂直拼接");
Image<T>::Ptr ret = Image<T>::create(img1->width(),
img1->height() + img2->height(),
img1->channels());
std::copy(img1->begin(), img1->end(), ret->begin());
std::copy(img2->begin(), img2->end(), ret->begin() + img1->GetValueAmount());
return ret;
}
template<typename T>
inline T
RGB2Gray_maximum(T const* v)
{
return *std::max_element(v, v + 3);
}
template<typename T>
inline T
RGB2Gray_lightness(T const* v)
{
T const* max = std::max_element(v, v + 3);
T const* min = std::min_element(v, v + 3);
return math::interpolate(*max, *min, 0.5f, 0.5f);
}
template<typename T>
inline T
RGB2Gray_luminosity(T const* v)
{
return math::interpolate(v[0], v[1], v[2], 0.21f, 0.72f, 0.07f);
}
template<typename T>
inline T
RGB2Gray_luminance(T const* v)
{
return math::interpolate(v[0], v[1], v[2], 0.30f, 0.59f, 0.11f);
}
template<typename T>
inline T
RGB2Gray_average(T const* v)
{
float third(1.0f / 3.0f);
return math::interpolate(v[0], v[1], v[2], third, third, third);
}
template<typename T>
typename Image<T>::Ptr
RGB2Gray(typename Image<T>::ConstPtr img, cvtType type = CVT_TYPE_AVERAGE)
{
if (img == nullptr)
throw std::invalid_argument("Null image given");
int channels = img->channels();
if (channels != 3 && channels != 4)
throw std::invalid_argument("Image must be RGB or RGBA");
bool has_alpha = (channels == 4);
typename Image<T>::Ptr out(Image<T>::create());
out->allocate(img->width(), img->height(), 1 + has_alpha);
typedef T(*RGB2GrayFunc)(T const*);
RGB2GrayFunc func;
switch (type)
{
case CVT_TYPE_MAXIMUM:
func = RGB2Gray_maximum<T>;
break;
case CVT_TYPE_LIGHTNESS:
func = RGB2Gray_lightness;
break;
case CVT_TYPE_LUMINOSITY:
func = RGB2Gray_luminosity;
break;
case CVT_TYPE_LUMINANCE:
func = RGB2Gray_luminance;
break;
case CVT_TYPE_AVERAGE:
func = RGB2Gray_average;
break;
default:
throw std::invalid_argument("Invalid conversion type");
break;
}
int outpos = 0;
int inpos = 0;
int pixels = img->GetPixelAmount();
for (int i = 0; i < pixels; i++)
{
T const* v = &img->at(inpos);
//每个像素插值
out->at(outpos) = func(v);
if (has_alpha)
out->at(outpos + 1) = img->at(inpos + 3);
outpos += 1 + has_alpha;
inpos += 3 + has_alpha;
}
return out;
}
}<file_sep>#pragma once
namespace math
{
template<typename T>
inline T
interpolate(T const& v1, T const& v2, float w1, float w2)
{
return v1 * w1 + v2 * w2;
}
template<>
inline unsigned char
interpolate(unsigned char const& v1, unsigned char const& v2,
float w1, float w2)
{
return (unsigned char)((float)v1 * w1 + (float)v2 * w2 + 0.5f);
}
template<typename T>
inline T
interpolate(T const& v1, T const& v2, T const& v3,
float w1, float w2, float w3)
{
return v1 * w1 + v2 * w2 + v3 * w3;
}
template<>
inline unsigned char
interpolate(unsigned char const& v1, unsigned char const& v2, unsigned char const& v3,
float w1, float w2, float w3)
{
return (unsigned char)((float)v1 * w1 + (float)v2 * w2 + (float)v3 * w3 + 0.5f);
}
}<file_sep>#pragma once
namespace shape
{
/*
二维点
*/
template<typename T>
struct Point2_
{
T x;
T y;
Point2_() :x(T(0)), y(T(0)) {}
Point2_(T _x, T _y) :x(_x), y(_y) {}
Point2_(Point2_ const& src) :x(src.x), y(src.y) {}
void swap(Point2_& other)
{
Point2_ temp(other);
other = this;
this = temp;
}
};
typedef Point2_<int> Point2i;
typedef Point2_<float> Point2f;
typedef Point2_<double> Point2d;
typedef Point2i Point;
/*
三维点
*/
template<typename T>
struct Point3_
{
T x;
T y;
T z;
Point3_() :x(T(0)), y(T(0)), z(T(0)) {}
Point3_(T _x, T _y, T _z) :x(_x), y(_y), z(_z) {}
Point3_(Point3_ const& src) :x(src.x), y(src.y), z(src.z) {}
};
typedef Point3_<int> Point3i;
typedef Point3_<float> Point3f;
typedef Point3_<double> Point3d;
/*
线段
*/
struct Line
{
Point pt1;
Point pt2;
Line() :pt1(Point()), pt2(Point()) {}
Line(Point const& _pt1, Point const& _pt2) :pt1(_pt1), pt2(_pt2) {}
Line(int _x1, int _y1, int _x2, int _y2) :pt1(_x1, _y1), pt2(_x2, _y2) {}
};
/*
矩形
*/
template<typename T>
struct Rect_
{
T x, y;
T width, height;
Rect_() :x(T(0)), y(T(0)), width(T(0)), height(T(0)) {}
Rect_(T _x, T _y, T _width, T _height) :x(_x), y(_y), width(_width), height(_height)
{
if (_width <= 0 || _height <= 0 || _x < 0 || _y < 0)
throw std::invalid_argument("Invaild parameter");
};
Rect_(Rect_ const& src) :x(src.x), y(src.y), width(src.width), height(src.height) {};
};
typedef Rect_<int> Rect2i;
typedef Rect_<float> Rect2f;
typedef Rect_<double> Rect2d;
typedef Rect2i Rect;
/*
圆
*/
struct Circle
{
Point center;
float radius;
Circle() :center(Point()), radius(0.0f) {}
Circle(Point _pt, float _radius) :center(_pt), radius(_radius) {}
Circle(int _x, int _y, float _radius) :center(Point(_x, _y)), radius(_radius) {}
Circle(Circle const& src) :center(src.center), radius(src.radius) {}
};
}<file_sep>#pragma once
#include <stdint.h>
namespace image
{
struct Color
{
uint8_t red;
uint8_t green;
uint8_t blue;
Color() :red(0), green(0), blue(0) {}
Color(uint8_t _red, uint8_t _green, uint8_t _blue) :
red(_red), green(_green), blue(_blue) {}
Color(Color const& src) :red(src.red), green(src.green), blue(src.blue) {}
};
}
|
ab4c42981854e3e6e03f45d84701fe75bc7a46f9
|
[
"C++"
] | 7 |
C++
|
MicroYY/LibImage
|
554b92d199888ac386d757284d81fc9a78992702
|
c582aab01ac684c7204779dcdab49dc39f98c223
|
refs/heads/master
|
<file_sep># Requisites
python3
trackopy: install via pip
# Running
Change the username and password in coin.py to the desired user/pass and then run.
# Sample Output
$ ./coin.py
Pirate Warrior
Coin rate: 0.0% (1)
Win rate: 100.0% (1)
Win rate (1st): 100.0% (1)
Aggro Shaman
Coin rate: 36.4% (11)
Win rate: 81.8% (11)
Win rate (1st): 85.7% (7)
Win rate (coin): 75.0% (4)
<file_sep>#!/usr/bin/env python3
import trackopy
from collections import defaultdict
# change the next line to your username/password
user = {'username': 'foo', 'password': 'bar'}
trackobot = trackopy.Trackobot(user['username'], user['password'])
coin_wins = defaultdict(lambda: 0)
coin_losses = defaultdict(lambda: 0)
nocoin_wins = defaultdict(lambda: 0)
nocoin_losses = defaultdict(lambda: 0)
deck_names = set()
history = trackobot.history()
total_pages = history['meta']['total_pages']
for page_number in range(1, total_pages+1):
history = trackobot.history(page_number)
for game in history['history']:
hero = game['hero'] if game['hero'] is not None else "Unknown"
hero_deck = game['hero_deck'] if game['hero_deck'] is not None else "Unknown"
deck_name = hero_deck + " " + hero
deck_names.add(deck_name)
if game['coin']:
if game['result'] == "win":
coin_wins[deck_name] += 1
elif game['result'] == "loss":
coin_losses[deck_name] += 1
else:
raise Exception("Unexpected 'result'")
else:
if game['result'] == "win":
nocoin_wins[deck_name] += 1
elif game['result'] == "loss":
nocoin_losses[deck_name] += 1
else:
raise Exception("Unexpected 'result'")
break
for deck_name in deck_names:
coin_total = coin_wins[deck_name] + coin_losses[deck_name]
nocoin_total = nocoin_wins[deck_name] + nocoin_losses[deck_name]
win_total = coin_wins[deck_name] + nocoin_wins[deck_name]
games_total = coin_total + nocoin_total
if games_total + coin_total + nocoin_total == 0:
continue
print(deck_name)
if games_total != 0:
print("Coin rate: {:>5.1f}% ({})".format(100 * coin_total/games_total, games_total))
print("Win rate: {:>5.1f}% ({})".format(100 * win_total/games_total, games_total))
if nocoin_total != 0:
print("Win rate (1st): {:>5.1f}% ({})".format(100 * nocoin_wins[deck_name]/nocoin_total, nocoin_total))
if coin_total != 0:
print("Win rate (coin): {:>5.1f}% ({})".format(100 * coin_wins[deck_name]/coin_total, coin_total))
print("")
|
308c9b707b1c7712e6bf42d93c4c38052111e011
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
theanine/coin-counter
|
290a9aa4a20ec01151762da328bc7b5778a47b48
|
ff4810c5c10f7ee9905c3c9bc7883209b2de8d89
|
refs/heads/master
|
<file_sep><?php
require('pokemon.php');
//Pokemon feuille//
$Marisson = new Pokemon("Marisson",'60','Niveau Base','Fouet lianes 10','Canon graine 20');
$Marisson -> stats();
$Boguerisse = new Pokemon("Boguerisse", '90', 'Niveau 1', 'Vampigraine 20', 'Poing Dard 50');
$Boguerisse -> stats();
$Blindepique = new Pokemon('Blindepique', '150', 'Niveau 2', 'Poing Dard 50', 'Attaque trebuchante 80+');
$Blindepique -> stats();
//Pokemon eau//
$Grenousse = new Pokemon('Grenousse', '60', 'Niveau Base', 'Ecras face 10', 'Goutte à goutte 20');
$Grenousse -> stats();
$Croaporal = new Pokemon('Croaporal', '80', 'Niveau 1', 'Goutte à goutte 20', 'Aqua-vague 40+' );
$Croaporal -> stats();
//Pokemon feu//
$Feunnec = new Pokemon('Feunnec', '60', 'Niveau Base', 'Griffe 10', 'Charbon mutant 20' );
$Feunnec -> stats();
$Roussil = new Pokemon('Roussil', '80', 'Niveau 1', 'Souffle-feu 20+', 'Queue de flammes 60');
$Roussil -> stats();
$Goupelin = new Pokemon('Goupelin', '140', 'Niveau 2', 'Feu follet 30', 'Deflagration 120');
$Goupelin -> stats();
$pokemons = [$Boguerisse, $Blindepique, $Grenousse, $Croaporal, $Feunnec, $Roussil, $Goupelin];
?>
<file_sep><?php
class pokemon{
private $name;
private $pv;
private $lvl;
private $attack1;
private $attack2;
function __construct($name, $pv, $lvl, $attack1, $attack2){
$this->name = $name;
$this->pv = $pv;
$this->lvl = $lvl;
$this->attack1 = $attack1;
$this->attack2 = $attack2;
}
public function getName(){
return $this->name;
}
public function setName(){
$this->name = $name;
}
public function getPv(){
return $this->pv;
}
public function setPv(){
$this->pv = $pv;
}
public function getLvl(){
return $this->lvl;
}
public function setLvl(){
$this->lvl = $lvl;
}
public function getAttack1(){
return $this->attack1;
}
public function setAttack1(){
$this->attack1 = $attack1;
}
public function getAttack2(){
return $this->attack2;
}
public function setAttack2(){
$this->attack2 = $attack2;
}
public function stats(){
(array(
'name'=> $this->getName(),
'pv' => $this->getPv(),
'lvl' => $this->getLvl(),
'attack1' => $this->getAttack1(),
'attack2' => $this->getAttack2(),
));
}
}
?>
<file_sep><!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.99.0/css/materialize.min.css">
<meta charset="utf-8">
<title>Pokemon</title>
</head>
<body>
<div class="container">
<table>
<thead>
<th>Nom Pokemon</th>
<th>PV</th>
<th>Level</th>
<th>Attaque 1</th>
<th>Attaque 2</th>
</thead>
<tbody>
<h1 class="center-align">Tableau Pokemon</h1>
<?php
require_once 'test.php';
foreach ( $pokemons as $pokemon){
echo '<tr><td>' .$pokemon->getName().'</td><td>' .$pokemon->getPv().'</td><td>' .$pokemon->getLvl().'</td><td>'.$pokemon->getAttack1().'</td><td>'.$pokemon->getAttack2().'</tr>';
}
?>
</tbody>
</table>
<table>
</body>
</html>
|
e75cd3f93d437c506dfd6a7550847cb87e3e9237
|
[
"PHP"
] | 3 |
PHP
|
Romain32190/class-POO
|
711ad2e7aa4db441278f5b8676810c8d83fde043
|
9cbcc3c4c68895898f5938cdb9e5fc8da7e5bee9
|
refs/heads/main
|
<file_sep>include ':app'
rootProject.name='AppClienteVipV5'
<file_sep>package com.gcstudios.entities;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import com.gcstudios.main.Game;
public class Explosion extends Entity{
private int frames = 0;
private int targetFrames = 10;
private int mexAnimation = 4;
private int curAnimation = 0;
public BufferedImage[] explosionSprite = new BufferedImage[4];
public Explosion(double x, double y, int width, int height, double speed, BufferedImage sprite) {
super(x, y, width, height, speed, sprite);
explosionSprite[0] = Game.spritesheet.getSprite(48,0,16,16);
explosionSprite[1] = Game.spritesheet.getSprite(64,0,16,16);
explosionSprite[2] = Game.spritesheet.getSprite(80,0,16,16);
explosionSprite[3] = Game.spritesheet.getSprite(96,0,16,16);
}
public void tick() {
frames++;
if(frames == targetFrames) {
frames = 0;
curAnimation++;
if(curAnimation == mexAnimation) {
Game.entities.remove(this);
}
}
}
public void render(Graphics g) {
g.drawImage(explosionSprite[curAnimation], this.getX(),this.getY(),null);
}
}
<file_sep>package com.gcstudios.main;
import com.gcstudios.entities.Enemy;
import com.gcstudios.entities.Entity;
public class EnemySpawn {
private int targetTime = 60*2;
private int curTime = 0;
public void tick() {
curTime++;
if(curTime == targetTime) {
curTime = 0;
targetTime = Entity.rand.nextInt(100);
int yy = 0;
int xx = Entity.rand.nextInt(Game.WIDTH-16);
int spawn = Entity.rand.nextInt(2);
if(spawn == 0) {
Enemy enemy1 = new Enemy(xx,yy,16,16,Entity.rand.nextInt(3-1)+1,Game.spritesheet.getSprite(16, 0, 16, 16));
Game.entities.add(enemy1);
}
if(spawn == 1) {
Enemy enemy2 = new Enemy(xx,yy,16,16,Entity.rand.nextInt(3-1)+1,Game.spritesheet.getSprite(32, 0, 16, 16));
Game.entities.add(enemy2);
}
}
}
}
<file_sep>package app.daazi.v5.appclientevip.view;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.shashank.sony.fancydialoglib.FancyAlertDialog;
import com.shashank.sony.fancydialoglib.FancyAlertDialogListener;
import com.shashank.sony.fancydialoglib.Icon;
import com.squareup.picasso.Picasso;
import app.daazi.v5.appclientevip.R;
import app.daazi.v5.appclientevip.api.AppUtil;
import app.daazi.v5.appclientevip.controller.ClienteController;
import app.daazi.v5.appclientevip.model.Cliente;
public class LoginActivity extends AppCompatActivity {
// Declarar Objetos
Cliente cliente;
private SharedPreferences preferences;
// 1º passo a partir do Layout
TextView txtRecuperarSenha, txtLerPolitica, btnSejaVip;
EditText editEmail, editSenha;
CheckBox chLembrar;
Button btnAcessar;
ImageView imgBackground, imgLogo;
boolean isFormularioOK, isLembrarSenha;
ClienteController controller;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login_novo);
initFormulario();
loadImagens();
btnAcessar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFormularioOK = validarFormulario()) {
if (validarDadosDoUsuario()) {
salvarSharedPreferences();
Intent intent =
new Intent(LoginActivity.this,
MainActivity.class);
startActivity(intent);
finish();
return;
} else {
String senhaDigitada = editSenha.getText().toString();
String emeilDigitado = editEmail.getText().toString();
if(!cliente.getEmail().equals(emeilDigitado)) {
editEmail.setError("*");
}
if(!cliente.getSenha().equals(AppUtil.gerarMD5Hash(senhaDigitada))){
editSenha.setError("*");
}
}
}
}
});
btnSejaVip.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent =
new Intent(LoginActivity.this,
ClienteVipActivity.class);
startActivity(intent);
finish();
return;
}
});
txtRecuperarSenha.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(),
"Carregando tela de recuperação de Senha...",
Toast.LENGTH_LONG).show();
;
}
});
txtLerPolitica.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new FancyAlertDialog.Builder(LoginActivity.this)
.setTitle("Política de Privacidade & Termos de Uso")
.setBackgroundColor(Color.parseColor("#303F9F"))
.setMessage("texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto texto")
.setNegativeBtnText("Discordo")
.setNegativeBtnBackground(Color.parseColor("#FF4081"))
.setPositiveBtnText("Concordo")
.setPositiveBtnBackground(Color.parseColor("#4ECA25"))
.isCancellable(true)
.setIcon(R.mipmap.ic_launcher_round, Icon.Visible)
.OnPositiveClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), "Obrigado, seja bem vindo e conclua o seu cadastro para usar o aplicativo...", Toast.LENGTH_SHORT).show();
}
})
.OnNegativeClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), "Lamentamos, mas é necessário concordar com a política de privacidade e termos de uso para se cadastrar no aplicativo...", Toast.LENGTH_SHORT).show();
finish();
return;
}
})
.build();
}
});
}
private boolean validarFormulario() {
boolean retorno = true;
if (TextUtils.isEmpty(editEmail.getText().toString())) {
editEmail.setError("*");
editEmail.requestFocus();
retorno = false;
}
if (TextUtils.isEmpty(editSenha.getText().toString())) {
editSenha.setError("*");
editSenha.requestFocus();
retorno = false;
}
return retorno;
}
private void initFormulario() {
txtRecuperarSenha = findViewById(R.id.txtRecurarSenha);
txtLerPolitica = findViewById(R.id.txtLerPolitica);
editEmail = findViewById(R.id.editEmail);
editSenha = findViewById(R.id.editSenha);
chLembrar = findViewById(R.id.ckLembrar);
btnAcessar = findViewById(R.id.btnAcessar);
btnSejaVip = findViewById(R.id.btnSejaVip);
imgBackground = findViewById(R.id.imgBackground);
imgLogo = findViewById(R.id.imgLogo);
isFormularioOK = false;
controller = new ClienteController(getApplicationContext());
cliente = new Cliente();
cliente.setId(20);
//cliente.setPrimeiroNome("Nome "+i);
//cliente.setSobreNome("Sobre nome "+i);
//cliente.setEmail(i+"<EMAIL>");
//cliente.setSenha(i+"_<PASSWORD>");
//cliente.setPessoaFisica(false);
// controller.incluir(cliente);
// controller.alterar(cliente);
controller.deletar(cliente);
// List<Cliente> clientes = controller.listar();
restaurarSharedPreferences();
}
private void loadImagens(){
Picasso.with(this)
.load(AppUtil.URL_IMG_BACKGROUD)
.into(imgBackground);
Picasso.with(this).load(AppUtil.URL_IMG_LOGO).into(imgLogo);
}
public void lembrarSenha(View view) {
isLembrarSenha = chLembrar.isChecked();
}
public boolean validarDadosDoUsuario() {
boolean retorno = false;
String senhaDigitada = editSenha.getText().toString();
String senhaMD5 = cliente.getSenha();
String emeilDigitado = editEmail.getText().toString();
String emeilBanco = cliente.getEmail();
return senhaMD5.equals(AppUtil.gerarMD5Hash(senhaDigitada)) & emeilBanco.equals(emeilDigitado);
}
private void salvarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
SharedPreferences.Editor dados = preferences.edit();
dados.putBoolean("loginAutomatico", isLembrarSenha);
dados.putString("emailCliente", editEmail.getText().toString());
dados.apply();
}
private void restaurarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
cliente.setEmail(preferences.getString("email", "<EMAIL>"));
cliente.setSenha(preferences.getString("senha", "<PASSWORD>"));
cliente.setPrimeiroNome(preferences.getString("primeiroNome", "Cliente"));
cliente.setSobreNome(preferences.getString("sobreNome", "Fake"));
cliente.setPessoaFisica(preferences.getBoolean("pessoaFisica", true));
isLembrarSenha = preferences.getBoolean("loginAutomatico", false);
}
}
<file_sep>package app.daazi.v5.appclientevip.controller;
import android.content.ContentValues;
import android.content.Context;
import androidx.annotation.Nullable;
import java.util.List;
import app.daazi.v5.appclientevip.api.AppDataBase;
import app.daazi.v5.appclientevip.datamodel.ClientePFDataModel;
import app.daazi.v5.appclientevip.model.ClientePF;
public class ClientePFController extends AppDataBase {
private static final String TABELA = ClientePFDataModel.TABELA;
private ContentValues dados;
public ClientePFController(@Nullable Context context) {
super(context);
}
public boolean incluir(ClientePF obj){
dados = new ContentValues();
dados.put(ClientePFDataModel.FK, obj.getClienteID());
dados.put(ClientePFDataModel.NOME_COMPLETO, obj.getNomeCompleto());
dados.put(ClientePFDataModel.CPF, obj.getCpf());
return insert(TABELA, dados);
}
public boolean alterar(ClientePF obj){
dados = new ContentValues();
dados.put(ClientePFDataModel.ID, obj.getId());
dados.put(ClientePFDataModel.NOME_COMPLETO, obj.getNomeCompleto());
dados.put(ClientePFDataModel.CPF, obj.getCpf());
return update(TABELA, dados);
}
public boolean deletar(ClientePF obj){
return delete(TABELA, obj.getId());
}
public List<ClientePF> listar(){
return listClientesPessoaFisica(TABELA);
}
public int getUltimoID(){
return getLastPK(TABELA);
}
public ClientePF getClientePFByFK(int idFK){
// idPK é a chave primária da tabela Cliente (id)
return getClientePFByFK(ClientePFDataModel.TABELA, idFK);
}
}
<file_sep>package com.gcstudios.entities;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import com.gcstudios.main.Game;
import com.gcstudios.world.AStar;
import com.gcstudios.world.Vector2i;
import com.gcstudios.world.World;
public class Enemy extends Entity{
public boolean right = true,left = false;
public double vida = 30;
public Enemy(double x, double y, int width, int height, double speed, BufferedImage sprite) {
super(x, y, width, height, speed, sprite);
path = AStar.findPath(Game.world,new Vector2i(World.xINITIAL,World.yINITIAL),new Vector2i(World.xFINAL,World.yFINAL));
}
public void tick() {
followPath(path);
if(x >= Game.WIDTH) {
//Perdemos vida aqui!
Game.life-=Entity.rand.nextDouble();
Game.entities.remove(this);
return;
}
if(vida <= 0)
{
Game.entities.remove(this);
Game.money+=10;
return;
}
}
public void render(Graphics g) {
super.render(g);
g.setColor(Color.red);
g.fillRect((int)x,(int) (y-5),30,6);
g.setColor(Color.green);
g.fillRect((int)x,(int) (y-5),(int)((vida/30) *30),6);
}
}
<file_sep>package app.daazi.v5.appclientevip.view;
import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.util.ArrayList;
import java.util.List;
import app.daazi.v5.appclientevip.R;
import app.daazi.v5.appclientevip.api.AppUtil;
public class SplashActivity extends AppCompatActivity {
private SharedPreferences preferences;
boolean isLembrarSenha = false;
// Use qualquer número
public static final int APP_PERMISSOES = 2020;
// Array String com a lista de permissões necessárias
String[] permissoesRequeridas = new String[]{
Manifest.permission.CAMERA,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CONTACTS,
Manifest.permission.SEND_SMS};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
salvarSharedPreferences();
restaurarSharedPreferences();
iniciarAplicativo();
// Verificar as permissões
if (validarPermissoes()){
iniciarAplicativo();
}else{
Toast.makeText(this, "Por favor, verifique as permissões.", Toast.LENGTH_SHORT).show();
}
}
private void iniciarAplicativo() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent;
if (isLembrarSenha) {
intent = new Intent(
SplashActivity.this,
MainActivity.class
);
} else {
intent
= new Intent(
SplashActivity.this,
LoginActivity.class
);
}
startActivity(intent);
finish();
return;
}
}, AppUtil.TIME_SPLASH);
}
private void salvarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
SharedPreferences.Editor dados = preferences.edit();
}
private void restaurarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
isLembrarSenha = preferences.getBoolean("loginAutomatico", false);
}
//Método para ativar permissões
private boolean validarPermissoes() {
int result;
// Array para verificar se as premissões forão autorizados
List<String> permissoesRequeridas = new ArrayList<>();
//Adicionar as permissões que o app necessita
for(String permissoes: this.permissoesRequeridas){
result = ContextCompat.checkSelfPermission(SplashActivity.this, permissoes);
if(result != PackageManager.PERMISSION_GRANTED){
permissoesRequeridas.add(permissoes);
}
}
//Caso o Array não esteja vazio. significa que tem permissões para serem autorizadas
if(!permissoesRequeridas.isEmpty()){
ActivityCompat.requestPermissions(this, permissoesRequeridas.toArray(new String[permissoesRequeridas.size()]), APP_PERMISSOES);
return false;
}
return true;
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode){
case APP_PERMISSOES:{
if (grantResults.length > 0){
String permissoesNegadasPeloUsuario = "";
for (String permissao : permissoesRequeridas){
if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
permissoesNegadasPeloUsuario += "\n" + permissao;
}
}
if (permissoesNegadasPeloUsuario.length()>0){
Toast.makeText(SplashActivity.this, "Permissões negadas pelo usuário", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(SplashActivity.this, "Todas as permissões autorizadas pelo usuário", Toast.LENGTH_LONG).show();
iniciarAplicativo();
}
return;
}
return;
}
}
}
}
<file_sep>package app.daazi.v5.appclientevip.datamodel;
// MOR - Modelo Objeto Relacional - SQLserver, Oracle, Postgress
public class ClientePFDataModel {
/**
* private int fk;
* private String cpf;
* private String nomeCompleto;
*/
public static final String TABELA = "clientePF";
public static final String ID = "id";
public static final String FK = "clienteID";
public static final String CPF = "cpf";
public static final String NOME_COMPLETO = "nomeCompleto";
private static final String DATA_INC = "datainc";
private static final String DATA_ALT = "dataalt";
private static String query;
/**
* CREATE TABLE clientePF (
* id INTEGER PRIMARY KEY AUTOINCREMENT,
* clienteID INTEGER,
* cpf TEXT,
* nomeCompleto TEXT,
* datainc TEXT,
* dataalt TEXT,
* FOREIGN KEY (
* clienteID
* )
* REFERENCES cliente (id)
* );
* @return
*/
public static String gerarTabela(){
query = "CREATE TABLE "+TABELA+" ( ";
query += ID+" INTEGER PRIMARY KEY AUTOINCREMENT, ";
query += FK+" INTEGER, ";
query += CPF+" TEXT, ";
query += NOME_COMPLETO+" TEXT, ";
query += DATA_INC+" datetime default current_timestamp, ";
query += DATA_ALT+" datetime default current_timestamp, ";
query += "FOREIGN KEY("+FK+") REFERENCES cliente(id) ";
query += ")";
return query;
}
}
<file_sep>package app.daazi.v5.appclientevip.view;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.shashank.sony.fancydialoglib.FancyAlertDialog;
import com.shashank.sony.fancydialoglib.FancyAlertDialogListener;
import com.shashank.sony.fancydialoglib.Icon;
import app.daazi.v5.appclientevip.R;
import app.daazi.v5.appclientevip.api.AppUtil;
import app.daazi.v5.appclientevip.controller.ClienteController;
import app.daazi.v5.appclientevip.model.Cliente;
public class ClienteVipActivity extends AppCompatActivity {
// Declarar Objetos
Cliente novoVip;
ClienteController controller;
private SharedPreferences preferences;
// 1º passo a partir do Layout
EditText editPrimeiroNome, editSobreNome;
CheckBox chPessoaFisica;
Button btnSalvarContinuar, btnCancelar;
boolean isFormularioOK, isPessoaFisica;
int ultimoID;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cliente_vip_card);
initFormulario();
btnSalvarContinuar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (isFormularioOK = validarFormulario()) {
novoVip.setPrimeiroNome(editPrimeiroNome.getText().toString());
novoVip.setSobreNome(editSobreNome.getText().toString());
novoVip.setPessoaFisica(isPessoaFisica);
controller.incluir(novoVip);
ultimoID = controller.getUltimoID();
salvarSharedPreferences();
Intent intent = new Intent(ClienteVipActivity.this,
ClientePessoaFisicaActivity.class);
startActivity(intent);
}
}
});
btnCancelar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new FancyAlertDialog.Builder(ClienteVipActivity.this)
.setTitle("Confirme o Cancelamento")
.setBackgroundColor(Color.parseColor("#303F9F"))
.setMessage("Deseja realmente Cancelar?")
.setNegativeBtnText("NÃO")
.setNegativeBtnBackground(Color.parseColor("#FF4081"))
.setPositiveBtnText("SIM")
.setPositiveBtnBackground(Color.parseColor("#4ECA25"))
.isCancellable(true)
.setIcon(R.mipmap.ic_launcher_round, Icon.Visible)
.OnPositiveClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), "Cancelado com sucesso....", Toast.LENGTH_SHORT).show();
}
})
.OnNegativeClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), "Continue seu cadastro...", Toast.LENGTH_SHORT).show();
}
})
.build();
}
});
}
private void initFormulario() {
editPrimeiroNome = findViewById(R.id.editPrimeiroNome);
editSobreNome = findViewById(R.id.editSobreNome);
chPessoaFisica = findViewById(R.id.chPessoaFisica);
btnSalvarContinuar = findViewById(R.id.btnSalvarContinuar);
btnCancelar = findViewById(R.id.btnCancelar);
isFormularioOK = false;
novoVip = new Cliente();
controller = new ClienteController(this);
restaurarSharedPreferences();
}
private boolean validarFormulario() {
boolean retorno = true;
if (TextUtils.isEmpty(editPrimeiroNome.getText().toString())) {
editPrimeiroNome.setError("*");
editPrimeiroNome.requestFocus();
retorno = false;
}
if (TextUtils.isEmpty(editSobreNome.getText().toString())) {
editSobreNome.setError("*");
editSobreNome.requestFocus();
retorno = false;
}
return retorno;
}
public void pessoaFisica(View view) {
isPessoaFisica = chPessoaFisica.isChecked();
}
private void salvarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
SharedPreferences.Editor dados = preferences.edit();
dados.putString("primeiroNome", novoVip.getPrimeiroNome());
dados.putString("sobreNome", novoVip.getSobreNome());
dados.putBoolean("pessoaFisica", novoVip.isPessoaFisica());
dados.putInt("clienteID", ultimoID);
dados.apply();
}
private void restaurarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
}
}
<file_sep>package app.daazi.v5.appclientevip.view;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.Toast;
import com.shashank.sony.fancydialoglib.FancyAlertDialog;
import com.shashank.sony.fancydialoglib.FancyAlertDialogListener;
import com.shashank.sony.fancydialoglib.Icon;
import app.daazi.v5.appclientevip.R;
import app.daazi.v5.appclientevip.api.AppUtil;
import app.daazi.v5.appclientevip.controller.ClienteController;
import app.daazi.v5.appclientevip.controller.ClientePFController;
import app.daazi.v5.appclientevip.controller.ClientePJController;
import app.daazi.v5.appclientevip.model.Cliente;
public class AtualizarMeusDadosActivity extends AppCompatActivity {
// Card Cliente
EditText editPrimeiroNome, editSobreNome;
CheckBox chPessoaFisica;
Button btnEditarCardCliente, btnSalvarCardCliente;
// Card ClientePF
EditText editCPF, editNomeCompleto;
Button btnEditarCardPF, btnSalvarCardPF;
// Card ClientePJ
EditText editCNPJ, editRazaoSocial, editDataAberturaPJ;
CheckBox chSimplesNacional, chMEI;
Button btnEditarCardPJ, btnSalvarCardPJ;
// Card Credenciais
EditText editEmail, editSenhaA;
Button btnEditarCardCredenciais, btnSalvarCardCredenciais;
Button btnVoltar;
Cliente cliente;
ClienteController controller;
ClientePFController controllerPF;
ClientePJController controllerPJ;
SharedPreferences preferences;
int clienteID;
boolean isPessoaFisica;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_atualizar_meus_dados);
restaurarSharedPreferences();
initFormulario();
polularFormulario();
}
private void polularFormulario() {
if (clienteID >= 1) {
cliente = controller.getClienteByID(cliente);
cliente.setClientePF(controllerPF.getClientePFByFK(cliente.getId()));
if (!cliente.isPessoaFisica())
cliente.setClientePJ(controllerPJ.getClientePJByFK(cliente.getClientePF().getId()));
// Dados Obj Cliente
editPrimeiroNome.setText(cliente.getPrimeiroNome());
editSobreNome.setText(cliente.getSobreNome());
editEmail.setText(cliente.getEmail());
editSenhaA.setText(cliente.getSenha());
chPessoaFisica.setChecked(cliente.isPessoaFisica());
// Dados Pessoa Física Obj Cliente
editCPF.setText(cliente.getClientePF().getCpf());
editNomeCompleto.setText(cliente.getClientePF().getNomeCompleto());
// Dados Pessoa Júridica Obj Cliente
if (!cliente.isPessoaFisica()) {
editCNPJ.setText(cliente.getClientePJ().getCnpj());
editRazaoSocial.setText(cliente.getClientePJ().getRazaoSocial());
editDataAberturaPJ.setText(cliente.getClientePJ().getDataAbertura());
chSimplesNacional.setChecked(cliente.getClientePJ().isSimplesNacional());
chMEI.setChecked(cliente.getClientePJ().isMei());
}
} else {
new FancyAlertDialog.Builder(AtualizarMeusDadosActivity.this)
.setTitle("ATENÇÃO")
.setBackgroundColor(Color.parseColor("#303F9F"))
.setMessage("Não foi possível, recuperar os dados do cliente?")
.setNegativeBtnText("RETORNAR")
.setNegativeBtnBackground(Color.parseColor("#FF4081"))
.isCancellable(true)
.setIcon(R.mipmap.ic_launcher_round, Icon.Visible)
.OnNegativeClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Intent intent = new Intent(AtualizarMeusDadosActivity.this, MainActivity.class);
startActivity(intent);
}
})
.build();
}
}
private void initFormulario() {
// Card Cliente
editPrimeiroNome = findViewById(R.id.editPrimeiroNome);
editSobreNome = findViewById(R.id.editSobreNome);
chPessoaFisica = findViewById(R.id.chPessoaFisica);
btnEditarCardCliente = findViewById(R.id.btnEditarCardCliente);
btnSalvarCardCliente = findViewById(R.id.btnSalvarCardCliente);
// Card ClientePF
editCPF = findViewById(R.id.editCPF);
editNomeCompleto = findViewById(R.id.editNomeCompleto);
btnEditarCardPF = findViewById(R.id.btnEditarCardPF);
btnSalvarCardPF = findViewById(R.id.btnSalvarCardPF);
// Card ClientePJ
editCNPJ = findViewById(R.id.editCNPJ);
editRazaoSocial = findViewById(R.id.editRazaoSocial);
editDataAberturaPJ = findViewById(R.id.editDataAberturaPJ);
btnSalvarCardPJ = findViewById(R.id.btnSalvarCardPJ);
btnEditarCardPJ = findViewById(R.id.btnEditarCardPJ);
chSimplesNacional = findViewById(R.id.chSimplesNacional);
chMEI = findViewById(R.id.chMEI);
// Card Credenciais
editEmail = findViewById(R.id.editEmail);
editSenhaA = findViewById(R.id.editSenhaA);
btnEditarCardCredenciais = findViewById(R.id.btnEditarCardCredenciais);
btnSalvarCardCredenciais = findViewById(R.id.btnSalvarCardCredenciais);
cliente = new Cliente();
cliente.setId(clienteID);
controller = new ClienteController(this);
controllerPF = new ClientePFController(this);
controllerPJ = new ClientePJController(this);
if (!cliente.isPessoaFisica()) {
// busco os dados
}
}
public void vontar(View view) {
Intent intent = new Intent(AtualizarMeusDadosActivity.this, MainActivity.class);
startActivity(intent);
}
public void editarCardCliente(View view) {
btnEditarCardCliente.setEnabled(false);
btnSalvarCardCliente.setEnabled(true);
editPrimeiroNome.setEnabled(true);
editSobreNome.setEnabled(true);
}
public void salvarCardCliente(View view) {
if(validarFormularioCardCliente()){
}
}
public void editarCardPF(View view) {
btnEditarCardPF.setEnabled(false);
btnSalvarCardPF.setEnabled(true);
editCPF.setEnabled(true);
editNomeCompleto.setEnabled(true);
}
public void salvarCardPF(View view) {
if(validarFormularioCardPF()){
}
}
public void editarCardPJ(View view) {
btnEditarCardPJ.setEnabled(false);
btnSalvarCardPJ.setEnabled(true);
editCNPJ.setEnabled(true);
editRazaoSocial.setEnabled(true);
editDataAberturaPJ.setEnabled(true);
}
public void salvarCardPJ(View view) {
if(validarFormularioCardPJ()){
}
}
public void editarCardCredenciais(View view) {
btnEditarCardCredenciais.setEnabled(false);
btnSalvarCardCredenciais.setEnabled(true);
editEmail.setEnabled(true);
editSenhaA.setEnabled(true);
}
public void salvarCardCredenciais(View view) {
}
private boolean validarFormularioCardCliente() {
boolean retorno = true;
if (TextUtils.isEmpty(editPrimeiroNome.getText().toString())) {
editPrimeiroNome.setError("*");
editPrimeiroNome.requestFocus();
retorno = false;
}
if (TextUtils.isEmpty(editSobreNome.getText().toString())) {
editSobreNome.setError("*");
editSobreNome.requestFocus();
retorno = false;
}
return retorno;
}
private boolean validarFormularioCardPF() {
boolean retorno = true;
String cpf = editCPF.getText().toString();
if (TextUtils.isEmpty(cpf)) {
editCPF.setError("*");
editCPF.requestFocus();
retorno = false;
}
if(!AppUtil.isCPF(cpf)){
editCPF.setError("*");
editCPF.requestFocus();
retorno = false;
Toast.makeText(this,"CPF Inválido, tente novamente...",Toast.LENGTH_LONG).show();
}else{
editCPF.setText(AppUtil.mascaraCPF(editCPF.getText().toString()));
}
if (TextUtils.isEmpty(editNomeCompleto.getText().toString())) {
editNomeCompleto.setError("*");
editNomeCompleto.requestFocus();
retorno = false;
}
return retorno;
}
private boolean validarFormularioCardPJ() {
boolean retorno = true;
if(TextUtils.isEmpty(editCNPJ.getText().toString())){
editCNPJ.setError("*");
editCNPJ.requestFocus();
retorno = false;
}
if(!AppUtil.isCNPJ(editCNPJ.getText().toString())){
editCNPJ.setError("*");
editCNPJ.requestFocus();
retorno = false;
Toast.makeText(this,"CNPJ Inválido, tente novamente...",Toast.LENGTH_LONG).show();
}else{
editCNPJ.setText(AppUtil.mascaraCNPJ(editCNPJ.getText().toString()));
}
if(TextUtils.isEmpty(editRazaoSocial.getText().toString())){
editRazaoSocial.setError("*");
editRazaoSocial.requestFocus();
retorno = false;
}
if(TextUtils.isEmpty(editDataAberturaPJ.getText().toString())){
editDataAberturaPJ.setError("*");
editDataAberturaPJ.requestFocus();
retorno = false;
}
return retorno;
}
private void restaurarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
isPessoaFisica = preferences.getBoolean("pessoaFisica", true);
clienteID = preferences.getInt("clienteID", -1);
}
}<file_sep>package app.daazi.v5.appclientevip.controller;
import android.content.ContentValues;
import android.content.Context;
import androidx.annotation.Nullable;
import java.util.List;
import app.daazi.v5.appclientevip.api.AppDataBase;
import app.daazi.v5.appclientevip.datamodel.ClientePFDataModel;
import app.daazi.v5.appclientevip.datamodel.ClientePJDataModel;
import app.daazi.v5.appclientevip.model.ClientePF;
import app.daazi.v5.appclientevip.model.ClientePJ;
public class ClientePJController extends AppDataBase {
private static final String TABELA = ClientePJDataModel.TABELA;
private ContentValues dados;
public ClientePJController(@Nullable Context context) {
super(context);
}
public boolean incluir(ClientePJ obj){
dados = new ContentValues();
dados.put(ClientePJDataModel.FK, obj.getClientePFID());
dados.put(ClientePJDataModel.CNPJ, obj.getCnpj());
dados.put(ClientePJDataModel.RAZAO_SOCIAL, obj.getRazaoSocial());
dados.put(ClientePJDataModel.DATA_ABERTURA, obj.getDataAbertura());
dados.put(ClientePJDataModel.SIMPLES_NACIONAL, obj.isSimplesNacional());
dados.put(ClientePJDataModel.MEI, obj.isMei());
return insert(TABELA, dados);
}
public boolean alterar(ClientePJ obj){
dados = new ContentValues();
dados.put(ClientePJDataModel.ID, obj.getId());
dados.put(ClientePJDataModel.FK, obj.getClienteID());
dados.put(ClientePJDataModel.RAZAO_SOCIAL, obj.getRazaoSocial());
dados.put(ClientePJDataModel.DATA_ABERTURA, obj.getDataAbertura());
dados.put(ClientePJDataModel.SIMPLES_NACIONAL, obj.isSimplesNacional());
dados.put(ClientePJDataModel.MEI, obj.isMei());
return update(TABELA, dados);
}
public boolean deletar(ClientePJ obj){
return delete(TABELA, obj.getId());
}
public List<ClientePJ> listar(){
return listClientesPessoaJuridica(TABELA);
}
public int getUltimoID(){
return getLastPK(TABELA);
}
public ClientePJ getClientePJByFK(int idFK){
// idPK é a chave primária da tabela Cliente (id)
return getClientePJByFK(ClientePJDataModel.TABELA, idFK);
}
}
<file_sep><h1>Projetos<h1>
Aqui tem projetos que foi feito no meus estudos em programação
<file_sep>package app.daazi.v5.appclientevip.datamodel;
// MOR - Modelo Objeto Relacional - SQLserver, Oracle, Postgress
public class ClientePJDataModel {
/**
* private int fk;
* private String cnpj;
* private String razaoSocial;
* private String dataAbertura;
* private boolean simplesNacional;
* private boolean mei;
*/
public static final String TABELA = "clientePJ";
public static final String ID = "id";
public static final String FK = "clientePFID";
public static final String CNPJ = "cnpj";
public static final String RAZAO_SOCIAL = "razao_social";
public static final String DATA_ABERTURA = "dataAbertura";
public static final String SIMPLES_NACIONAL = "simplesNacional";
public static final String MEI = "mei";
private static final String DATA_INC = "datainc";
private static final String DATA_ALT = "dataalt";
private static String query;
/**
* CREATE TABLE clientePJ (
* id INTEGER PRIMARY KEY AUTOINCREMENT,
* clientePFID INTEGER,
* cnpj TEXT,
* razao_social TEXT,
* dataAbertura TEXT,
* simplesNacional INTEGER,
* mei INTEGER,
* datainc TEXT,
* dataalt TEXT,
* FOREIGN KEY (
* clientePFID
* )
* REFERENCES clientePF (id)
* );
* @return
*/
public static String gerarTabela(){
query = "CREATE TABLE "+TABELA+" ( ";
query += ID+" INTEGER PRIMARY KEY AUTOINCREMENT, ";
query += FK+" INTEGER, ";
query += CNPJ+" TEXT, ";
query += RAZAO_SOCIAL+" TEXT, ";
query += DATA_ABERTURA+" TEXT, ";
query += SIMPLES_NACIONAL+" INTEGER, ";
query += MEI+" INTEGER, ";
query += DATA_INC+" datetime default current_timestamp, ";
query += DATA_ALT+" datetime default current_timestamp, ";
query += "FOREIGN KEY("+FK+") REFERENCES clientePF(id) ";
query += ")";
return query;
}
}
<file_sep>package app.daazi.v5.appclientevip.view;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import com.shashank.sony.fancydialoglib.FancyAlertDialog;
import com.shashank.sony.fancydialoglib.FancyAlertDialogListener;
import com.shashank.sony.fancydialoglib.Icon;
import java.util.ArrayList;
import java.util.List;
import app.daazi.v5.appclientevip.R;
import app.daazi.v5.appclientevip.api.AppUtil;
import app.daazi.v5.appclientevip.controller.ClienteController;
import app.daazi.v5.appclientevip.controller.ClientePFController;
import app.daazi.v5.appclientevip.controller.ClientePJController;
import app.daazi.v5.appclientevip.model.Cliente;
import app.daazi.v5.appclientevip.model.ClientePF;
import app.daazi.v5.appclientevip.model.ClientePJ;
public class MainActivity extends AppCompatActivity {
Cliente cliente;
ClienteController controller;
ClientePFController controllerPF;
ClientePJController controllerPJ;
TextView txtNomeCliente;
private SharedPreferences preferences;
List<Cliente> clientes;
List<String> cidades;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initFormulario();
}
private void buscarListaDeClientes() {
cidades = new ArrayList<>();
clientes = new ArrayList<>();
cidades.add("Brasília");
cidades.add("Campo Grande");
cidades.add("São Paulo");
cidades.add("Curitiba");
for (int i = 0; i < 10; i++) {
cliente = new Cliente();
cliente.setPrimeiroNome("Cliente nº "+i);
clientes.add(cliente);
}
for (String obj: cidades) {
Log.i(AppUtil.LOG_APP,"Obj: "+obj);
}
}
private void initFormulario() {
cliente = new Cliente();
controllerPF = new ClientePFController(this);
controller = new ClienteController(this);
controllerPJ = new ClientePJController(this);
txtNomeCliente = findViewById(R.id.txtNomeCliente);
restaurarSharedPreferences();
txtNomeCliente.setText("Bem vindo, "+ cliente.getPrimeiroNome());
}
private void salvarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
SharedPreferences.Editor dados = preferences.edit();
}
public void meusDados(View view) {
Intent intent = new Intent(MainActivity.this, MeusDadosActivity.class);
startActivity(intent);
}
public void atualizarMeusDados(View view) {
Intent intent = new Intent(MainActivity.this, AtualizarMeusDadosActivity.class);
startActivity(intent);
}
public void excluirMinhaConta(View view) {
new FancyAlertDialog.Builder(MainActivity.this)
.setTitle("EXCLUIR SUA CONTA")
.setBackgroundColor(Color.parseColor("#303F9F"))
.setMessage("Confirma EXCLUSÃO definitiva da sua conta do aplicativo?")
.setNegativeBtnText("RETORNAR")
.setNegativeBtnBackground(Color.parseColor("#FF4081"))
.setPositiveBtnText("SIM")
.setPositiveBtnBackground(Color.parseColor("#4ECA25"))
.isCancellable(true)
.setIcon(R.mipmap.ic_launcher_round, Icon.Visible)
.OnPositiveClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
cliente.setClientePF(controllerPF.getClientePFByFK(cliente.getId()));
if(!cliente.isPessoaFisica()) {
cliente.setClientePJ(controllerPJ.getClientePJByFK(cliente.getClientePF().getId()));
controllerPJ.deletar(cliente.getClientePJ());
}
controllerPF.deletar(cliente.getClientePF());
controller.deletar(cliente);
Toast.makeText(getApplicationContext(), cliente.getPrimeiroNome() + ", sua conta foi excluída, esperamos que retorne em breve...", Toast.LENGTH_SHORT).show();
finish();
return;
}
})
.OnNegativeClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), cliente.getPrimeiroNome() + ", divirta-se com as opções do aplicativo...", Toast.LENGTH_SHORT).show();
}
})
.build();
}
public void consultarClientesVip(View view) {
Intent intent = new Intent(MainActivity.this, ConsultarClientesActivity.class);
startActivity(intent);
}
public void sairDoAplicativo(View view) {
new FancyAlertDialog.Builder(MainActivity.this)
.setTitle("SAIR DO APLICATIVO")
.setBackgroundColor(Color.parseColor("#303F9F"))
.setMessage("Confirma sua saída do aplicativo?")
.setNegativeBtnText("RETORNAR")
.setNegativeBtnBackground(Color.parseColor("#FF4081"))
.setPositiveBtnText("SIM")
.setPositiveBtnBackground(Color.parseColor("#4ECA25"))
.isCancellable(true)
.setIcon(R.mipmap.ic_launcher_round, Icon.Visible)
.OnPositiveClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), cliente.getPrimeiroNome() + ", volte sempre e obrigado...", Toast.LENGTH_SHORT).show();
finish();
return;
}
})
.OnNegativeClicked(new FancyAlertDialogListener() {
@Override
public void OnClick() {
Toast.makeText(getApplicationContext(), cliente.getPrimeiroNome() + ", divirta-se com as opções do aplicativo...", Toast.LENGTH_SHORT).show();
}
})
.build();
}
private void restaurarSharedPreferences() {
preferences = getSharedPreferences(AppUtil.PREF_APP, MODE_PRIVATE);
cliente.setPrimeiroNome(preferences.getString("primeiroNome", "Maddo"));
cliente.setSobreNome(preferences.getString("sobreNome", "NULO"));
cliente.setEmail(preferences.getString("email", "NULO"));
cliente.setSenha(preferences.getString("senha", "<PASSWORD>"));
cliente.setPessoaFisica(preferences.getBoolean("pessoaFisica", true));
cliente.setId(preferences.getInt("clienteID", -1));
}
}
<file_sep>package app.daazi.v5.appclientevip.api;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Calendar;
import java.util.InputMismatchException;
/**
* Classe de apoio contendo métodos que podem
* ser reutilizados de códigos, classes, métodos no projeto
* <p>
* Criada por <NAME> - 01/2020
* <p>
* Versão v2
*/
public class AppUtil {
public static final int TIME_SPLASH = 5 * 1000;
public static final String PREF_APP = "app_cliente_vip_pref";
public static final String LOG_APP = "CLIENTE_LOG";
public static final String URL_IMG_BACKGROUD = "http://bit.ly/daaziImgBackground";
public static final String URL_IMG_LOGO = "http://bit.ly/daaziImgLogo";
/**
* @return devolve a data atual
*/
public static String getDataAtual() {
String dia, mes, ano;
String dataAtual = "00/00/0000";
try {
Calendar calendar = Calendar.getInstance();
dia = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
mes = String.valueOf(calendar.get(Calendar.MONTH) + 1);
ano = String.valueOf(calendar.get(Calendar.YEAR));
// p1 : p2 : p2
dia = (Calendar.DAY_OF_MONTH < 10) ? "0" + dia : dia;
dia = (dia.length() > 2) ? dia.substring(1, 3) : dia;
int mesAtual = (Calendar.MONTH) + 1;
mes = (mesAtual <= 9) ? "0" + mes : mes;
mes = (mes.length() > 2) ? mes.substring(1, 3) : mes;
dataAtual = dia + "/" + mes + "/" + ano;
return dataAtual;
} catch (Exception e) {
}
return dataAtual;
}
/**
* @return devolve a hora atual
*/
public static String getHoraAtual() {
String horaAtual = "00:00:00";
String hora, minuto, segudo;
try {
Calendar calendar = Calendar.getInstance();
int iHora = calendar.get(Calendar.HOUR_OF_DAY);
int iMinuto = calendar.get(Calendar.MINUTE);
int iSegundo = calendar.get(Calendar.SECOND);
hora = (iHora <= 9) ? "0" + iHora : Integer.toString(iHora);
minuto = (iMinuto <= 9) ? "0" + iMinuto : Integer.toString(iMinuto);
segudo = (iSegundo <= 9) ? "0" + iSegundo : Integer.toString(iSegundo);
horaAtual = hora + ":" + minuto + ":" + segudo;
return horaAtual;
} catch (Exception e) {
}
return horaAtual;
}
/**
* Validar CNPJ
* @param CNPJ
* @return
*/
public static boolean isCNPJ(String CNPJ) {
// considera-se erro CNPJ's formados por uma sequencia de numeros iguais
if (CNPJ.equals("00000000000000") || CNPJ.equals("11111111111111") ||
CNPJ.equals("22222222222222") || CNPJ.equals("33333333333333") ||
CNPJ.equals("44444444444444") || CNPJ.equals("55555555555555") ||
CNPJ.equals("66666666666666") || CNPJ.equals("77777777777777") ||
CNPJ.equals("88888888888888") || CNPJ.equals("99999999999999") ||
(CNPJ.length() != 14))
return (false);
char dig13, dig14;
int sm, i, r, num, peso;
try {
sm = 0;
peso = 2;
for (i = 11; i >= 0; i--) {
num = (int) (CNPJ.charAt(i) - 48);
sm = sm + (num * peso);
peso = peso + 1;
if (peso == 10)
peso = 2;
}
r = sm % 11;
if ((r == 0) || (r == 1))
dig13 = '0';
else dig13 = (char) ((11 - r) + 48);
sm = 0;
peso = 2;
for (i = 12; i >= 0; i--) {
num = (int) (CNPJ.charAt(i) - 48);
sm = sm + (num * peso);
peso = peso + 1;
if (peso == 10)
peso = 2;
}
r = sm % 11;
if ((r == 0) || (r == 1))
dig14 = '0';
else dig14 = (char) ((11 - r) + 48);
if ((dig13 == CNPJ.charAt(12)) && (dig14 == CNPJ.charAt(13)))
return (true);
else return (false);
} catch (InputMismatchException erro) {
return (false);
}
}
/**
* Validar CPF
* @param CPF
* @return
*/
public static boolean isCPF(String CPF) {
if (CPF.equals("00000000000") ||
CPF.equals("11111111111") ||
CPF.equals("22222222222") || CPF.equals("33333333333") ||
CPF.equals("44444444444") || CPF.equals("55555555555") ||
CPF.equals("66666666666") || CPF.equals("77777777777") ||
CPF.equals("88888888888") || CPF.equals("99999999999") ||
(CPF.length() != 11))
return (false);
char dig10, dig11;
int sm, i, r, num, peso;
try {
sm = 0;
peso = 10;
for (i = 0; i < 9; i++) {
num = (int) (CPF.charAt(i) - 48);
sm = sm + (num * peso);
peso = peso - 1;
}
r = 11 - (sm % 11);
if ((r == 10) || (r == 11))
dig10 = '0';
else dig10 = (char) (r + 48);
sm = 0;
peso = 11;
for (i = 0; i < 10; i++) {
num = (int) (CPF.charAt(i) - 48);
sm = sm + (num * peso);
peso = peso - 1;
}
r = 11 - (sm % 11);
if ((r == 10) || (r == 11))
dig11 = '0';
else dig11 = (char) (r + 48);
if ((dig10 == CPF.charAt(9)) && (dig11 == CPF.charAt(10)))
return (true);
else return (false);
} catch (InputMismatchException erro) {
return (false);
}
}
/**
* Adicionar mascára para CNPJ
* @param CNPJ
* @return
*/
public static String mascaraCNPJ(String CNPJ) {
String retorno;
retorno =(CNPJ.substring(0, 2) + "." + CNPJ.substring(2, 5) + "." +
CNPJ.substring(5, 8) + "." + CNPJ.substring(8, 12) + "-" +
CNPJ.substring(12, 14));
return retorno;
}
/**
* Adicionar mascára para CPF
* @param CPF
* @return
*/
public static String mascaraCPF(String CPF) {
return (CPF.substring(0, 3) + "." + CPF.substring(3, 6) + "." +
CPF.substring(6, 9) + "-" + CPF.substring(9, 11));
}
/**
* Gerar senha criptografada com MD5.
* @param password
* @return
*/
public static String gerarMD5Hash(String password) {
String retorno = "";
if(!password.isEmpty()) {
retorno = "falhou";
try {
// Create MD5 Hash
MessageDigest digest = MessageDigest.getInstance("MD5");
digest.update(password.getBytes());
byte messageDigest[] = digest.digest();
StringBuffer MD5Hash = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
String h = Integer.toHexString(0xFF & messageDigest[i]);
while (h.length() < 2)
h = "0" + h;
MD5Hash.append(h);
}
return MD5Hash.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
return retorno;
}
}
|
0a67616182a14b24bdff9368effbd8e5f3fd80da
|
[
"Markdown",
"Java",
"Gradle"
] | 15 |
Gradle
|
LeandroFerraro/Projetos
|
ccfca3292d9681ba8130e94733406bb1c0455f45
|
c9faadf7e46dc352eaffd5cefe50dfa2a1d4ccb0
|
refs/heads/master
|
<repo_name>ben-x9/twicas<file_sep>/app/components/comment.ts
import { div, img, h, VNode, newlineStrToBr } from 'core/html';
import { style } from 'typestyle';
import { horizontal, horizontallySpaced, vertical, verticallySpaced, center, padding, width, height } from 'csstips';
import { Action as GlobalAction } from 'actions';
import { percent } from 'csx';
import * as colors from 'colors';
import { Comment } from 'store/comment';
import { Update, set } from 'core/common';
export interface Store {
comment: Comment;
explanation?: ReadonlyArray<VNode>;
};
export const initialState = {
showExplanation: false,
};
export type State = Readonly<typeof initialState>;
interface ToggleExplanation {
type: 'TOGGLE_EXPLANATION';
}
export type Action = GlobalAction | ToggleExplanation;
export function update(action: Action, store: Store, state: State): [State, GlobalAction|null] {
switch (action.type) {
case 'TOGGLE_EXPLANATION': return [
set(state, {
showExplanation: !state.showExplanation,
}),
store.explanation ? null : {
type: 'GET_COMMENT_EXPLANATION',
commentId: store.comment.id,
}];
default: return [state, action];
}
}
export const view = (store: Store, state: State, update: Update<Action>) =>
div(
style(
padding(5),
width(percent(100)),
horizontal,
horizontallySpaced(10),
),
{key: store.comment.id},
[
img(style(
width(40),
height(40),
{borderRadius: 5},
), {attrs: {src: store.comment.fromUser.image}}),
div(style(vertical, verticallySpaced(10)), [
div(style({
color: colors.darkGray,
fontWeight: 'bold',
fontSize: 14,
}), store.comment.fromUser.name),
div(
style(padding(10), {
backgroundColor: colors.lightGray,
borderRadius: 5,
cursor: 'pointer',
}), {
on: {
click: () => update({type: 'TOGGLE_EXPLANATION'}),
},
},
newlineStrToBr(store.comment.message),
),
state.showExplanation ?
div(style(padding(10), {
backgroundColor: colors.yellow,
borderRadius: 5,
cursor: 'pointer',
fontSize: 14,
lineHeight: '16px',
}), {
on: {
click: () => update({type: 'TOGGLE_EXPLANATION'}),
},
},
store.explanation ?
store.explanation as VNode[] :
div('loading...')) :
'',
]),
],
);<file_sep>/types/urlencode.d.ts
declare module 'urlencode' {
function urlencode(string: string): string;
namespace urlencode {}
export = urlencode;
}<file_sep>/app/pages/loading.ts
import { div } from 'core/html';
import { style } from 'typestyle';
import { vertical, center, padding } from 'csstips';
export default () =>
div(style(padding(10), vertical, center), [
div('loading...'),
]);<file_sep>/app/core/actions.ts
export interface Goto {
type: 'GOTO';
path: string;
}
// Goto without storing the previous path in the browser history
export interface GotoSilently {
type: 'GOTO_SILENTLY';
path: string;
}
export interface Redirect {
type: 'REDIRECT';
url: string;
}
export interface RefreshView {
type: 'REFRESH_VIEW';
}
export type Action = Goto | GotoSilently | Redirect | RefreshView;<file_sep>/app/core/api.ts
import { Store, State } from 'root';
interface Global extends Window {
// ensure callbacks always access the latest data
store: Store;
state: State;
}
export const global = window as Global;
export type Callback<T> = (error: Error|null, data: T) => void;
export type ActionCallback<T> = (error: Error|null, store: Store, state: State, data: T) => void;
export function action<T>(callback: ActionCallback<T>, err: Error | null, data: T) {
callback(err, global.store, global.state, data);
};
<file_sep>/app/api/twicas.ts
import * as xhr from 'xhr';
import { map, snakeCase, camelCase, mapKeys, mapValues } from 'lodash';
import { User } from 'store/user';
import { Comment } from 'store/comment';
import { Callback, ActionCallback, action } from 'core/api';
const baseUrl = 'https://v20ki0pxd7.execute-api.us-west-2.amazonaws.com/supercast/';
const unproxiedBaseUrl = 'https://apiv2.twitcasting.tv/';
const clientId = '<KEY>';
const clientSecret = require('../../twicas-secret.json');
const redirectUri = 'https://twicas-17f39.firebaseapp.com/twicas_auth';
interface Global extends Window {
accessToken: string;
}
const global = window as Global;
type Data = {[key: string]: primitive};
const queryString = (vals: Data) =>
map(vals, (val, param) => `${snakeCase(param)}=${val}`).join('&');
const camelizeKeys = (object: ByKey<any>) =>
mapKeys(object, (value, key) => camelCase(key));
const camelizeKeysDeep = (data: any): any =>
Array.isArray(data) ?
data.map(camelizeKeysDeep) :
typeof data === 'object' ?
mapValues(camelizeKeys(data), (value) => camelizeKeysDeep(value)) :
data;
const url = (path: string, queryVals?: {[param: string]: string}) =>
baseUrl + path + (queryVals ? ('?' + queryString(queryVals)) : '');
const authUrl = unproxiedBaseUrl + 'oauth2/authorize?' + queryString({
clientId,
responseType: 'code',
});
export const fetchAccessToken = (code: string, callback: () => void) => {
post('oauth2/access_token', {
code,
grantType: 'authorization_code',
clientId,
clientSecret,
redirectUri,
}, (err, data) => {
const token = data['accessToken'] as string;
localStorage.setItem('accessToken', token);
global.accessToken = token;
callback();
});
};
const post = (uri: string, args: Data, callback: Callback<any>) =>
xhr.post({
url: url(uri),
headers: {'Content-type': 'application/x-www-form-urlencoded'},
body: queryString(args),
responseType: 'json',
}, (err, resp) => callback(err, camelizeKeysDeep(resp.body)));
const get = (uri: string, args: Data, callback: Callback<any>) => {
if (!global.accessToken) {
const token = localStorage.getItem('accessToken');
if (token) {
global.accessToken = token;
} else {
localStorage.setItem('returnToPath', location.pathname);
window.location.replace(authUrl);
return;
}
}
const query = queryString(args);
xhr.get({
url: url(uri) + (query ? '?' + query : ''),
headers: {
'Accept': 'application/json',
'X-Api-Version': '2.0',
'Authorization': `Bearer ${global.accessToken}`,
},
responseType: 'json',
}, (err, resp) => {
if (err) throw err;
callback(err, camelizeKeysDeep(resp.body));
});
};
export function getUser(id: string, callback: ActionCallback<User>) {
get(`users/${id}`, {}, (err: Error, data: any) =>
data.error ?
action(callback, new Error('no such user'), data) :
action(callback, null, data.user));
}
export function getComments(movieId: string, callback: ActionCallback<ReadonlyArray<Comment>>) {
get(`movies/${movieId}/comments?offset=0&limit=10`, {},
(err: Error, data: any) => !err && action(callback, null, data.comments),
);
}
export function getCurrentLiveId(userId: string, callback: ActionCallback<string>) {
get(`users/${userId}/current_live`, {}, (err: Error, data: any) =>
data.error ?
action(callback, new Error('this user is not live'), '') :
action(callback, null, data.movie.id));
}
export function getCurrentUser(callback: ActionCallback<User>) {
get(`verify_credentials`, {}, (err: Error, data: any) =>
action(callback, err, data.user as User));
}<file_sep>/README.md
# Twitcasting Dictionary
1. Find a live stream in Japanese
2. Get the username of the live streamer and enter it into the app
3. Click on a comment to show a Japanese to English dictionary entry for that comment
https://twicas-17f39.firebaseapp.com/<file_sep>/types/xhr.d.ts
type anyObject = {[key: string]: any};
declare module 'xhr' {
interface Response {
body: anyObject | string,
statusCode: number,
method: string,
headers: anyObject,
url: string,
rawRequest: any
}
interface RequestOptions {
useXDR?: boolean,
sync?: boolean,
uri?: string,
url?: string,
method?: string,
timeout?: number,
headers?: anyObject,
body?: string | anyObject,
json?: boolean | anyObject,
username?: string,
password?: String,
withCredentials?: boolean,
responseType?: string,
beforeSend?: () => void,
}
type CallbackType = (error: Error, response: Response, body: XMLHttpRequest) => void;
function xhr(options: string | RequestOptions, callback: CallbackType): void;
namespace xhr {
function post(options: string | RequestOptions, callback: Callback): void;
function get(options: string | RequestOptions, callback: Callback): void;
type Callback = CallbackType;
}
export = xhr;
}<file_sep>/app/pages/user.ts
import { div, img } from 'core/html';
import { style } from 'typestyle';
import { vertical, verticallySpaced, center, padding } from 'csstips';
import { User } from 'store/user';
import loading from 'pages/loading';
import { Action } from 'actions';
import { Update } from 'core/common';
export const view = (user: User|null, update: Update<Action>) =>
user ?
div(style(padding(10), vertical, verticallySpaced(10), center), [
div(user.name),
div(user.profile),
img({attrs: {src: user.image}}),
]) :
(update({type: 'GET_CURRENT_USER'}), loading());<file_sep>/app/store/comment.ts
import { User } from 'store/user';
export interface Comment {
id: string;
message: string;
fromUser: User;
created: number;
}<file_sep>/app/store/user.ts
export const newUser = {
id: '',
screenId: '',
name: '',
profile: '',
image: '',
};
export type User = Readonly<typeof newUser>;<file_sep>/app/root.ts
import { path, match, reset, readParam, Path } from 'core/router';
import { Action as GlobalAction } from 'actions';
import { Update, set } from 'core/common';
import * as NotFound from 'pages/not-found';
import * as HomePage from 'pages/home';
import * as UserPage from 'pages/user';
import * as CommentsPage from 'pages/comments';
import { User } from 'store/user';
import { Comment } from 'store/comment';
import loading from 'pages/loading';
import * as twicas from 'api/twicas';
import { VNode } from 'core/html';
if (module.hot) module.hot.dispose(() => {
reset();
});
// MODEL
export const initialStore = {
user: null as User | null,
comments: [] as ReadonlyArray<Comment>,
explanations: {} as ByKey<ReadonlyArray<VNode>>,
};
export type Store = Readonly<typeof initialStore>;
export const initialErrors = {
user: '',
comments: '',
};
export const initialState = {
errors: initialErrors,
homePage: HomePage.initialState,
commentsPage: CommentsPage.initialState,
};
export type State = Readonly<typeof initialState>;
export type Errors = Readonly<typeof initialErrors>;
// UPDATE
export interface HomePageAction {
type: 'HOME_PAGE';
action: HomePage.Action;
}
export interface CommentsPageAction {
type: 'COMMENTS_PAGE';
action: CommentsPage.Action;
}
export type Action = GlobalAction | HomePageAction | CommentsPageAction;
export function update(action: Action, store: Store, state: State): [Store, State, GlobalAction|null] {
let newStore = store;
let newState = state;
let reaction = null as null|GlobalAction;
switch (action.type) {
case 'HOME_PAGE':
let newHomePageState: HomePage.State;
[newHomePageState, reaction] = HomePage.update(action.action, state.homePage);
newState = set(state, {homePage: newHomePageState});
break;
case 'COMMENTS_PAGE':
let newCommentsPageState: CommentsPage.State;
[newCommentsPageState, reaction] = CommentsPage.update(action.action, store, state.commentsPage);
newState = set(state, {commentsPage: newCommentsPageState});
break;
default:
reaction = action;
break;
}
if (reaction && reaction.type === 'GOTO') {
newStore = initialStore;
newState = set(newState, {errors: initialErrors});
}
return [newStore, newState, reaction];
};
// VIEW
export const homePage = path('/', 'HOME');
export const twitAuthPath = path('/twicas_auth', 'TWICAS_AUTH');
export const userPage = path('/user', 'USER');
export const commentsPage: Path<{userId: string}> =
path('/:userId', 'COMMENTS');
export function view(store: Store, state: State, path: string, update: Update<Action>) {
const route = match(path);
switch (route.key) {
case 'HOME':
return HomePage.view(state.homePage, (action: HomePage.Action) =>
update({type: 'HOME_PAGE', action}));
case 'TWICAS_AUTH':
const code = readParam('code');
twicas.fetchAccessToken(code, () => update({
type: 'GOTO_SILENTLY',
path: localStorage.getItem('returnToPath') as string,
}));
return loading();
case 'USER':
return UserPage.view(store.user, update);
case 'COMMENTS':
return CommentsPage.view(route.args[0], store, state.commentsPage, (action: CommentsPage.Action) => update({type: 'COMMENTS_PAGE', action}), state.errors);
default: return NotFound.view();
}
}<file_sep>/app/pages/home.ts
import { div, input, VNode } from 'core/html';
import { Update, set } from 'core/common';
import { Action as GlobalAction } from 'core/actions';
import { style } from 'typestyle';
import { vertical, verticallySpaced, center, content, padding } from 'csstips';
import button from 'components/button';
import { commentsPage } from 'root';
import * as colors from 'colors';
export const initialState = {
input: '',
};
export type State = Readonly<typeof initialState>;
export interface SetInput {
type: 'SET_INPUT';
value: string;
}
export type Action = SetInput | GlobalAction;
export function update(action: Action, state: State): [State, GlobalAction|null] {
switch (action.type) {
case 'SET_INPUT': return [set(state, {input: action.value}), null];
default: return [state, action];
}
}
export const view = (state: State, update: Update<Action>) => {
document.body.style.backgroundColor = colors.lightGray;
const gotoComments = () => update({
type: 'GOTO',
path: commentsPage({userId: state.input}),
});
return div(style(padding(10), vertical, verticallySpaced(10), center), [
div(style(content), 'enter user id'),
input(style({textAlign: 'center'}), {
props: {type: 'text', value: state.input},
on: {
input: (e: Event) => update({
type: 'SET_INPUT',
value: (e.target as HTMLInputElement).value,
}),
keypress: (e: KeyboardEvent) => e.keyCode === 13 && gotoComments(),
},
hook: {
insert: (vnode: VNode) => (vnode.elm as HTMLElement).focus(),
update: (vnode: VNode) => (vnode.elm as HTMLElement).focus(),
},
}),
button('OK', () => gotoComments()),
]);
};<file_sep>/test/core/html.ts
import { tag, newlineToBr, br } from 'core/html';
import { assert } from 'chai';
describe('tag', () => {
it('should set css class to the name arg when present', () => {
const vnode = tag('div')({name: 'hello'}, 'hello world!');
assert.strictEqual(vnode.sel, 'div.hello');
});
it('should not set a css class when name arg is missing', () => {
const vnode = tag('div')('hello world!');
assert.strictEqual(vnode.sel, 'div');
});
});
describe('newlineToBr', () => {
it('should convert newline chars to br tags', () => {
assert.deepEqual(
newlineToBr('hello\nworld'),
['hello', br, 'world'],
);
assert.deepEqual(
newlineToBr('hello\nworld\n\nhave a nice day'),
['hello', br, 'world', br, '', br, 'have a nice day'],
);
});
});<file_sep>/app/pages/comments.ts
import { div, img } from 'core/html';
import { style } from 'typestyle';
import { vertical, verticallySpaced, center, padding, width, margin } from 'csstips';
import { Action as GlobalAction } from 'actions';
import { Update, set } from 'core/common';
import { Store, Errors } from 'root';
import * as colors from 'colors';
import * as CommentComponent from 'components/comment';
import { Comment } from 'store/comment';
export const initialState = {
comments: {} as ByKey<CommentComponent.State>,
};
export type State = Readonly<typeof initialState>;
export interface CommentComponentAction {
type: 'COMMENT_COMPONENT';
id: string;
action: CommentComponent.Action;
}
export type Action = GlobalAction | CommentComponentAction;
export function update(action: Action, store: Store, state: State): [State, GlobalAction|null] {
let newState = state;
let reaction = null as null|GlobalAction;
switch (action.type) {
case 'COMMENT_COMPONENT':
const comment =
store.comments.find(comment => comment.id === action.id) as Comment;
let newCommentState: CommentComponent.State;
[newCommentState, reaction] = CommentComponent.update(action.action, {
comment, explanation: store.explanations[action.id],
}, state.comments[action.id] || CommentComponent.initialState);
newState = set(state, {
comments: set(state.comments, {[action.id]: newCommentState}),
});
break;
default:
reaction = action;
break;
}
return [newState, reaction];
}
export const view = (userId: string, store: Store, state: State, update: Update<Action>, errors: Errors) =>
div(
style(padding(10), vertical, verticallySpaced(15), center),
{
key: 'comments',
hook: {
create: () => {
document.body.style.backgroundColor = colors.white;
update({type: 'SUBSCRIBE_COMMENTS', userId});
},
destroy: () => update({type: 'UNSUBSCRIBE_COMMENTS', userId}),
},
},
errors.user ?
div(errors.user) :
!store.user ?
div('loading...') :
[
div(style(padding(10), vertical, verticallySpaced(10), center, {maxWidth: 500, textAlign: 'center'}), [
img(style({borderRadius: 5}), {attrs: {src: store.user.image}}),
div(style({
color: colors.darkGray,
fontWeight: 'bold',
}), store.user.name),
div(store.user.profile),
]),
div(
style(vertical, verticallySpaced(10), padding(20), {maxWidth: 460}, center),
errors.comments ?
[div(errors.comments)] :
store.comments.length === 0 ?
[div('loading comments...')] :
store.comments.map(comment =>
CommentComponent.view(
{comment, explanation: store.explanations[comment.id]},
state.comments[comment.id] || CommentComponent.initialState,
(action: CommentComponent.Action) => update({
type: 'COMMENT_COMPONENT',
id: comment.id,
action,
}),
)),
),
],
);<file_sep>/app/api/jdic.ts
import * as xhr from 'xhr';
import { ActionCallback, action } from 'core/api';
import virtualize from 'snabbdom-virtualize';
import { VNode } from 'snabbdom/vnode';
export function getExplanation(text: string, callback: ActionCallback<VNode[]>) {
const cleanText = text
.replace(/[\ud800-\udfff]/g, '')
.replace('_', ' ')
.replace('\n', ' ');
xhr.get({
url: `https://xes56jrq8b.execute-api.us-west-2.amazonaws.com/wwwjdic/wwwjdic/cgi-data/wwwjdic?9ZIG${cleanText}`,
responseType: 'document',
}, (err, resp) => {
if (err) throw err;
const doc = resp.body as Document;
action(callback, err, Array.prototype.map.call(
doc.body.childNodes, (node: Node) => virtualize(node),
));
});
}<file_sep>/types/snabbdom-virtualize.d.ts
declare module 'snabbdom-virtualize' {
import { VNode } from 'snabbdom/vnode';
export default function virtualize(node: Node): VNode;
}<file_sep>/app/core/index.ts
import { init, h } from 'snabbdom';
import { VNode } from 'snabbdom/VNode';
import snabbClass from 'snabbdom/modules/class';
import snabbProps from 'snabbdom/modules/props';
import snabbStyle from 'snabbdom/modules/style';
import snabbEvent from 'snabbdom/modules/eventlisteners';
import snabbAttrs from 'snabbdom/modules/attributes';
const patch = init([ // init patch function with choosen modules
snabbClass, // makes it easy to toggle classes
snabbProps, // for setting properties on DOM elements
snabbStyle, // handles styling on elements with support for animations
snabbEvent, // attaches event listeners
snabbAttrs, // for setting attr on DOM elements
]);
let unlisten: () => void;
// enable webpack hot module replacement
if (module.hot) {
module.hot.accept();
module.hot.dispose(() => {
unlisten();
});
}
import * as Root from 'root';
import { defer, debounce } from 'lodash';
import * as Actions from 'actions';
import { omit } from 'lodash';
interface Global extends Window {
// expose the model and state globally so we can view in the console
store: Root.Store;
state: Root.State;
// make view a global because cannot `x = x || y` when x is a local
view: VNode | HTMLElement;
loaded: Boolean;
scrollTop: ByKey<number>;
}
const global = window as Global;
global.view = global.view || document.getElementById('root') as HTMLElement;
global.scrollTop = global.scrollTop || {};
import * as csstips from 'csstips';
csstips.normalize();
csstips.setupPage('#root');
import createHistory from 'history/createBrowserHistory';
const history = createHistory();
interface GoBack {
type: 'POP';
path: string;
state: Root.State;
}
type Action = Root.Action | GoBack;
import { create } from 'jsondiffpatch';
const json = create();
if (!global.store) global.store = Root.initialStore;
if (!global.state) global.state = Root.initialState;
function update(action: Action) {
const [newData, newState, reaction] =
action.type === 'POP' ?
[ global.store,
/*json.diff(state, action.state) ? action.state :*/ global.state,
null] :
Root.update(action, global.store, global.state);
applyUpdate(action, newData, newState, reaction);
}
function applyUpdate(action: Action, newStore: Root.Store, newState: Root.State, reaction?: Actions.Action|null) {
if (process.env.NODE_ENV === 'development')
logAction(action, newStore, newState, reaction);
const shouldRefresh = newStore !== global.store || newState !== global.state;
if (action.type !== 'POP' && newState !== global.state)
history.replace(history.location.pathname, newState);
global.store = newStore;
global.state = newState;
if (reaction) {
perform(reaction);
} else if (shouldRefresh || action.type === 'POP') {
refreshView();
}
}
function perform(action: Actions.Action) {
if (!action) return;
switch (action.type) {
case 'GOTO':
history.push(action.path, global.state);
refreshView();
break;
case 'GOTO_SILENTLY':
history.replace(action.path, global.state);
refreshView();
break;
case 'REDIRECT':
window.location.replace(action.url);
break;
case 'REFRESH_VIEW':
refreshView();
break;
default:
if (Actions.perform(action, global.store, global.state,
(newData, newState, nextAction) =>
applyUpdate(action, newData, newState, nextAction)))
refreshView();
break;
}
}
function logAction(action: Action, store: Root.Store, state: Root.State, reaction?: Actions.Action|null) {
let actionPath = action.type;
let actualAction: any = action;
while (actualAction.action) {
actualAction = actualAction.action;
actionPath += ' / ' + actualAction.type;
}
actionPath += ' ' + JSON.stringify(omit(actualAction, 'type'));
let msg = actionPath;
if (store !== global.store)
msg += '\n-> store ' +
(JSON.stringify(json.diff(global.store, store)) || '(unchanged)');
if (state !== global.state)
msg += '\n-> state ' + JSON.stringify(json.diff(global.state, state));
if (reaction)
msg += '\n-> reaction ' + JSON.stringify(reaction);
console.log(msg);
}
defer(refreshView);
unlisten = history.listen((location, action) => {
if (action === 'POP') {
update({
type: 'POP',
path: location.pathname,
state: <Root.State>(location.state || global.state),
});
}
});
import { set } from 'core/common';
import { match } from 'core/router';
function refreshView() {
let view = Root.view(
global.store,
global.state,
history.location.pathname,
update,
);
const key = match(history.location.pathname).key as string;
view = set(view, {
data: set(view.data || {}, {
hook: set((view.data || {}).hook || {}, {
insert: () => {
window.scrollTo(0, global.scrollTop[key] || 0);
window.onscroll = debounce(() =>
global.scrollTop[key] = window.scrollY, 100);
},
update: () =>
defer(() => window.scrollTo(0, global.scrollTop[key] || 0)),
}),
}),
});
global.view = patch(global.view, h('div#root', view));
}<file_sep>/app/actions.ts
import { Action as CoreAction } from 'core/actions';
import * as twicas from 'api/twicas';
import * as jdic from 'api/jdic';
import { Store, State } from 'root';
import { set, stop } from 'core/common';
import * as lo from 'lodash';
import { Comment } from 'store/comment';
export interface GetCurrentUser {
type: 'GET_CURRENT_USER';
}
export interface SubscribeComments {
type: 'SUBSCRIBE_COMMENTS';
userId: string;
}
export interface UnsubscribeComments {
type: 'UNSUBSCRIBE_COMMENTS';
userId: string;
}
export interface GetCommentExplanation {
type: 'GET_COMMENT_EXPLANATION';
commentId: string;
}
export type Action = CoreAction | GetCurrentUser | SubscribeComments | UnsubscribeComments | GetCommentExplanation;
let timerId: number | null = null;
export function perform(action: Action, store: Store, state: State, callback: (store: Store, state: State, action?: Action|null) => void) {
switch (action.type) {
case 'GET_CURRENT_USER':
twicas.getCurrentUser((err, store, state, user) =>
callback(set(store, {user}), state, null));
return false;
case 'SUBSCRIBE_COMMENTS':
if (timerId !== null) clearInterval(timerId);
twicas.getUser(action.userId, (err, store, state, user) =>
err ?
callback(store, set(state, {
errors: set(state.errors, {user: err.message}),
})) :
callback(set(store, {user}), state));
twicas.getCurrentLiveId(action.userId, (err, store, state, liveId) => {
if (err) {
callback(store, set(state, {
errors: set(state.errors, {comments: err.message}),
}));
} else {
const getComments = () =>
twicas.getComments(liveId, (err, store, state, comments) =>
callback(set(store, {
comments: lo(comments.concat(store.comments))
.sortBy('id')
.sortedUniqBy('id')
.value()
.reverse(),
}), state));
getComments();
timerId = setInterval(() => getComments(), 3000);
}
});
return false;
case 'UNSUBSCRIBE_COMMENTS':
if (timerId !== null) clearInterval(timerId);
return false;
case 'GET_COMMENT_EXPLANATION':
jdic.getExplanation(
(store.comments.find(c =>
c.id === action.commentId) as Comment).message,
(err, store, state, result) =>
callback(set(store, {explanations: set(
store.explanations, {[action.commentId]: result},
)}), state),
);
break;
}
return true;
};
|
7c639ff9b039bb6370594f4d8692ccd3dc911c94
|
[
"Markdown",
"TypeScript"
] | 19 |
TypeScript
|
ben-x9/twicas
|
1ba7c2d38eb39e8025b95aa5b433711a5c60cb19
|
68ca1f7b028b100c8a979c5c08fbaeb29d86367f
|
refs/heads/master
|
<file_sep># Copyright 2020 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import requests
import json
from .engine import VaultEngine
class Vault(object):
def __init__(self, addr, approle_path, role_id, secret_id, namespace=None):
self._addr = addr
self._api_url = "{0}/v1".format(addr)
self._approle_path = approle_path
self._role_id = role_id
self._secret_id = secret_id
self._namespace = namespace
self._token = self._authenticate_approle()
# TODO - this should be abstracted into an authentication method class
def _authenticate_approle(self):
auth_data = json.dumps({
"role_id": self._role_id,
"secret_id": self._secret_id,
})
auth_url = self.url_for_path(
"auth/{0}/login".format(self._approle_path)
)
headers = {}
self._add_namespace(headers)
r = requests.post(auth_url, data=auth_data, headers=headers)
r.raise_for_status()
# TODO - this needs error handling
return r.json()["auth"]["client_token"]
def _add_namespace(self, headers):
if self._namespace:
headers["X-Vault-Namespace"] = self._namespace
def _add_token(self, headers):
headers["X-Vault-Token"] = self._token
def url_for_path(self, path):
return "{0}/{1}".format(self._api_url, path)
def engine(self, engine_type, engine_path):
return VaultEngine.engine_at_path(self, engine_type, engine_path)
def _get(self, path, params={}):
url = self.url_for_path(path)
headers = {}
self._add_namespace(headers)
self._add_token(headers)
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
return response.json()["data"]
<file_sep># Hashicorp Vault Synchronization
Synchronize secrets from Hashicorp Vault to Splunk's Credential Store.
## Configuration
### inputs.conf
#### [vault_sync_kv_credential] - Vault Synchronize KV Credential
Synchronize secrets from Hashicorp Vault's KV Engine to Splunk's Credential Store.
[vault_sync_kv_credential://<name>]
* Create an input per-credential you wish to synchronize
* Use a meaningful value for <name> to differentiate your configured inputs
interval = <integer>
* How often, in seconds, to check Hashicorp Vault for an updated secret
* Required
vault_url = <string>
* Hashicorp Vault URL
* Required
vault_namespace = <string>
* The namespace in vault containing your secret
* Optional
vault_approle_auth_path = <string>
* Path at which your AppRole authentication method is enabled, with no leading or trailing slash
* https://www.vaultproject.io/api-docs/system/auth#path
* Defaults to "approle"
vault_approle_role_id = <string>
* The role_id of an AppRole that has read access to your secret
* This will be encrypted into Splunk's Credential Store any time the input runs and detects a plaintext value
* Required
vault_approle_secret_id = <string>
* A secret_id granting access to your role_id
* This will be encrypted into Splunk's Credential Store any time the input runs and detects a plaintext value
* Vault allows using only a role_id, without a secret_id along with it, but this Add-on requires a secret_id
* Required
vault_engine_path = <string>
* The path to the KV Engine containing your secret
* Required
vault_secret_path = <string>
* The path, relative from vault_engine_path, of your secret
* Required
vault_username_key = <string>
* The key in your KV secret containing the username to synchronize
* Required
vault_secret_key = <string>
* The key in your KV secret containing the key to synchronize
* Required
remove_old_versions = <integer>
* How many old versions of your KV secret should be removed from your passwords.conf
* Needed for Add-ons like the AWS TA, which programmatically fetches the username from a credential defined in a specific realm
* Defaults to 0
credential_app = <string>
* The app context to use for the created/updated credential
* Optional
credential_realm = <string>
* The realm of the created/updated credential
* Optional
### vault_sync_kv_credential.conf
#### [logging] - Configure logging for the input
[logging]
rotate_max_bytes = <integer>
* Rotate log files after rotate_max_bytes bytes.
* Default is 1000000
rotate_backup_count = <integer>
* Keep rotate_backup_count rotated (inactive) log files
* Default is 5
log_level = [CRITICAL|ERROR|WARNING|INFO|DEBUG|NOTSET]
* Set the log level. Valid values are shown above.
* Default is INFO
<file_sep># Copyright 2020 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# VaultEngine is an abstract class and should not be used directly
# it should make use of ABCMeta to ensure it is not attempted
class VaultEngine(object):
_engine_classes = { }
def __init__(self, vault, engine_path):
self._vault = vault
self._engine_path = engine_path
@classmethod
def _add_engine_class(cls, engine_type, engine_class):
cls._engine_classes[engine_type] = engine_class
@classmethod
def _engine_class_for_type(cls, engine_type):
if not engine_type in cls._engine_classes:
raise Exception('Unknown engine type: {0}'.format(engine_type))
return cls._engine_classes[engine_type]
@classmethod
def engine_at_path(cls, vault, engine_type, engine_path):
engine_class = cls._engine_class_for_type(engine_type)
return engine_class(vault, engine_path)
def _get(self, path, params={}):
path_with_engine = "{0}/{1}".format(self._engine_path, path)
return self._vault._get(path_with_engine, params=params)
# decorator that tells VaultEngine we exist
class ConfiguredEngine(object):
def __init__(self, engine_type):
self._engine_type = engine_type
def __call__(self, configured_class):
VaultEngine._add_engine_class(self._engine_type, configured_class)
<file_sep># Copyright 2020 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
import splunklib.client as client
from splunklib.binding import UrlEncoded
class SecretEncryption(object):
_masked_secret = '**********'
def __init__(self, input_stanza, service, realm_prefix=None, required_on_edit_fields=[]):
self._service = service
self._input_type, self._input_name = input_stanza.split('://')
self._required_on_edit_fields = required_on_edit_fields
# use specified realm_prefix, or the input type if none was given
self._realm_prefix = realm_prefix
if not self._realm_prefix:
self._realm_prefix = self._input_type
def encrypt_and_get_secret(self, secret, field):
# If the secret is not masked, encrypt then mask it.
if secret != self._masked_secret:
self.encrypt_secret(secret, field)
self.mask_secret(field)
return self.get_secret(field)
def _credential_realm(self):
return "{0}-{1}".format(self._realm_prefix, self._input_name)
def encrypt_secret(self, secret, field):
# If the credential already exists, update it.
found_secret = self.credential_for_field(field)
if found_secret:
found_secret.update(password=secret)
else:
# Create the credential.
self._service.storage_passwords.create(secret, field, self._credential_realm())
def mask_secret(self, field):
inputs_kind_path = self._service.inputs.kindpath(self._input_type)
inputs_path_for_kind = "{0}/{1}".format("data/inputs", inputs_kind_path)
input_path = "{0}/{1}".format(inputs_path_for_kind, UrlEncoded(self._input_name, encode_slash=True))
input = self._service.input(input_path)
# the change we are explicitly making
input_changes = {
field: self._masked_secret,
}
# add fields that are required on edit
for field_name in self._required_on_edit_fields:
if not field_name in input_changes:
input_changes[field_name] = input.content[field_name]
# this causes the input config to refresh, resulting in this input instance ending and being started again
input.update(**input_changes)
def get_secret(self, field):
found_credential = self.credential_for_field(field)
if found_credential:
return found_credential.content.clear_password
raise Exception("No credential found for {0} in realm {1}".format(field, self._credential_realm()))
def credential_for_field(self, field):
password_name = "{0}:{1}:".format(self._credential_realm(), field)
if password_name in self._service.storage_passwords:
return self._service.storage_passwords[password_name]
return None
<file_sep># Copyright 2020 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from __future__ import absolute_import
from splunklib.modularinput import *
from splunklib import client
import sys
import os
import traceback
import logging
import logging.handlers
import json
from splunk_utils import secret_encryption
from vault_utils import vault_interface
class VaultSyncKVCredentialScript(Script):
_script_name = "vault_sync_kv_credential"
_arguments = {
"vault_url": {
"title": "Hashicorp Vault URL",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"vault_namespace": {
"title": "The namespace in vault containing your secret",
"data_type": Argument.data_type_string,
"required_on_create": False,
},
"vault_approle_auth_path": {
"title": "Path to the AppRole authentication method",
"data_type": Argument.data_type_string,
"required_on_create": False,
},
"vault_approle_role_id": {
"title": "AppRole role_id with read access to your secret",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"vault_approle_secret_id": {
"title": "AppRole secret_id for your role_id",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"vault_engine_path": {
"title": "The path to the KV Engine containing your secret",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"vault_secret_path": {
"title": "The path, relative from vault_engine_path, of your secret",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"vault_username_key": {
"title": "The key in your KV secret containing the username to synchronize",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"vault_password_key": {
"title": "The key in your KV secret containing the password to synchronize. If credential_store_json=true, this can be a comma-delimited list of keys to synchronize as JSON.",
"data_type": Argument.data_type_string,
"required_on_create": True,
},
"credential_store_json": {
"title": "Set to true to synchronize the vault_password_key(s) as a JSON document",
"data_type": Argument.data_type_boolean,
"required_on_create": False,
},
"credential_app": {
"title": "The app context to use for the created/updated credential",
"data_type": Argument.data_type_string,
"required_on_create": False,
},
"credential_realm": {
"title": "The realm of the created/updated credential",
"data_type": Argument.data_type_string,
"required_on_create": False,
},
"remove_old_versions": {
"title": "How many old versions of this secret should be forcibly removed from passwords.conf",
"data_type": Argument.data_type_number,
"required_on_create": False,
},
}
_encrypted_arguments = [ 'vault_approle_role_id', 'vault_approle_secret_id' ]
def configure_logging(self):
# get this script's configuration
script_config = self.service.confs[self._script_name]
# set logging specific variables from config
logging_config = script_config["logging"]
max_bytes = int(logging_config["rotate_max_bytes"])
backup_count = int(logging_config["rotate_backup_count"])
log_level = getattr(logging, logging_config["log_level"])
# configure our logger
self._logger = logging.getLogger(self._script_name)
self._logger.setLevel(log_level)
self._logger.propagate = False
# configure our log handler
log_dir = os.path.expandvars(os.path.join("$SPLUNK_HOME", "var", "log", "splunk"))
log_file = os.path.join(log_dir, "{0}.log".format(self._script_name))
log_handler = logging.handlers.RotatingFileHandler(log_file, maxBytes=max_bytes, backupCount=backup_count)
log_formatter = logging.Formatter('%(asctime)s - [%(levelname)s] - %(message)s')
log_handler.setFormatter(log_formatter)
# add our handler to our logger
self._logger.addHandler(log_handler)
def get_scheme(self):
scheme = Scheme("Vault Synchronize KV Credential")
scheme.use_single_instance = False
for argument_name, argument_config in self._arguments.items():
scheme_argument = Argument(argument_name, **argument_config)
scheme.add_argument(scheme_argument)
return scheme
def stream_events(self, inputs, ew):
# logging can't be configured until this point
# there is no session key available during __init__ (or get_scheme), and we need it to get the running config
self.configure_logging()
self._logger.debug("stream_events")
try:
self._stream_events(inputs, ew)
except Exception as e:
self._logger.critical("unhandled exception: {0}".format(traceback.format_exc()))
exit(-1)
def _stream_events(self, inputs, ew):
for input_name, input_config in inputs.inputs.items():
self._logger.debug("input_name: {0}".format(input_name))
for argument_name in self._arguments:
if argument_name not in input_config:
if self._arguments[argument_name].get('required_on_create'):
self._logger.critical("{0} Missing required field {1}, quitting".format(input_name, argument_name))
sys.exit(-1)
argument_value = input_config.get(argument_name)
if self._arguments[argument_name].get('data_type') == Argument.data_type_boolean:
argument_value = True if argument_value.lower() in ["true", "yes", "t", "y", "1"] else False
# use .get(argument_name) to use the default of None if missing
setattr(self, argument_name, argument_value)
self._logger.debug("{0}: fetched argument {1}".format(input_name, argument_name))
required_on_edit_field_names = filter(lambda argument_name: self._arguments[argument_name].get("required_on_edit", False), self._arguments)
encryption = secret_encryption.SecretEncryption(input_stanza=input_name, service=self.service, required_on_edit_fields=required_on_edit_field_names)
for argument_name in self._encrypted_arguments:
# all encrypted arguments in this input are required, so the checking above should be sufficient
setattr(self, argument_name, encryption.encrypt_and_get_secret(getattr(self, argument_name), argument_name))
self._logger.debug("{0}: handled encrypted argument {1}".format(input_name, argument_name))
vault = vault_interface.Vault(addr=self.vault_url, namespace=self.vault_namespace, approle_path=self.vault_approle_auth_path, role_id=self.vault_approle_role_id, secret_id=self.vault_approle_secret_id)
vault_kv_engine = vault.engine("kv", self.vault_engine_path)
vault_kv_secret = vault_kv_engine.secret(self.vault_secret_path)
fetched_secret_version = vault_kv_secret.version()
self._logger.debug("{0}: latest KV secret version: {1}".format(input_name, fetched_secret_version))
fetched_vault_username = vault_kv_secret.key(self.vault_username_key)
fetched_vault_password = vault_kv_secret.key(self.vault_password_key)
if self.credential_store_json:
vault_password_keys = self.vault_password_key.split(",")
vault_password_data = {key: vault_kv_secret.key(key) for key in vault_password_keys}
fetched_vault_password = json.dumps(vault_password_data)
credential_session = self.service
# switch app context if one was specified
if self.credential_app:
credential_session = client.connect(app=self.credential_app, token=self.service.token)
# default realm to empty string
credential_title = "{0}:{1}:".format(self.credential_realm or "", fetched_vault_username)
self._logger.debug("{0}: working with credential: {1}".format(input_name, credential_title))
if credential_title in credential_session.storage_passwords:
self._logger.debug("{0}: found existing credential".format(input_name))
found_credential = credential_session.storage_passwords[credential_title]
found_clear_password = None
try:
found_clear_password = found_credential.content.clear_password
except AttributeError:
self._logger.debug("{0}: credential entry has no clear password".format(input_name))
if found_clear_password != fetched_vault_password:
self._logger.debug("{0}: stored credential is out of date, updating".format(input_name))
found_credential.update(password=f<PASSWORD>)
else:
self._logger.debug("{0}: stored credential is up to date, doing nothing".format(input_name))
else:
self._logger.info("{0}: no existing credential found, creating".format(input_name))
credential_session.storage_passwords.create(fetched_vault_password, fetched_vault_username, self.credential_realm)
self._logger.debug("{0}: credential created".format(input_name))
if self.remove_old_versions:
# TODO - do type conversions when fetching arguments
oldest_removeable_version = vault_kv_secret.version() - int(self.remove_old_versions)
self._logger.info("{0}: removeable versions".format(input_name))
for previous_version in vault_kv_secret.previous_versions():
if previous_version.version() < oldest_removeable_version:
break
self._logger.info(" {0}: previous version: {1}".format(input_name, previous_version.version()))
previous_version_vault_username = previous_version.key(self.vault_username_key)
# we only need to look for differing usernames, because differing passwords with the same username will have already been updated
if previous_version_vault_username != fetched_vault_username:
self._logger.debug(" {0}: version {1} is stale".format(input_name, previous_version.version()))
credential_title = "{0}:{1}:".format(self.credential_realm or "", previous_version_vault_username)
if credential_title in credential_session.storage_passwords:
self._logger.info(" {0}: version {1}'s username has an old entry in passwords.conf, removing".format(input_name, previous_version.version()))
credential_session.storage_passwords[credential_title].delete()
else:
self._logger.info(" {0}: version {1} is identical to latest".format(input_name, previous_version.version()))
if __name__ == "__main__":
sys.exit(VaultSyncKVCredentialScript().run(sys.argv))
<file_sep># Copyright 2020 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
[vault_sync_kv_credential://<name>]
python.version = python3
vault_url = <string>
vault_namespace = <string>
vault_approle_auth_path = <string>
vault_approle_role_id = <string>
vault_approle_secret_id = <string>
vault_engine_path = <string>
vault_secret_path = <string>
vault_username_key = <string>
vault_password_key = <string>
credential_store_json = <bool>
credential_app = <string>
credential_realm = <string>
remove_old_versions = <integer>
<file_sep># Copyright 2020 Splunk, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from .engine import ConfiguredEngine, VaultEngine
from .secret import VaultSecret
@ConfiguredEngine("kv")
class VaultKVEngine(VaultEngine):
def secret(self, path):
return VaultKVSecret(self, path)
class VaultKVSecret(VaultSecret):
def __init__(self, vault_engine, path, version=None):
super(VaultKVSecret, self).__init__(vault_engine, path)
# explicit version defined
self._version = version
# attempt to use a requested "version 0"
if self._version is None:
# if explicitly defined version was, well, not defined, ask for and use the latest
self._version = self.version()
def _get(self):
if self._version is not None:
return super(VaultKVSecret, self)._get(params={'version': self._version})
return super(VaultKVSecret, self)._get()
def version(self):
return self._get()["metadata"]["version"]
def key(self, key):
return self._get()["data"][key]
def previous_version_number(self):
return self._version - 1
def previous_version(self):
if self.previous_version_number() == 0:
return None
previous_version = VaultKVSecret(self._vault_engine, self._path, self._version - 1)
try:
previous_version.version()
except:
return None
return previous_version
def previous_versions(self):
my_previous_version = self.previous_version()
while my_previous_version:
yield my_previous_version
my_previous_version = my_previous_version.previous_version()
|
76e992f8e2bd7431fcf71a6d3f1fa64366b74ed2
|
[
"Markdown",
"Python"
] | 7 |
Python
|
splunk/TA-VaultSync
|
4012c31adf12467dcb940d6dea43050c22670c11
|
b5abcb1e34ead944ed7e7b7734b254c4965ff63e
|
refs/heads/master
|
<repo_name>trice-imaging/trice-docker-app-base<file_sep>/Dockerfile
FROM triceio/trice-docker-base:latest
MAINTAINER <NAME> <<EMAIL>>
ENV DEBIAN_FRONTEND noninteractive
ADD bootstrap.sh /root/bootstrap.sh
RUN chmod +x /root/bootstrap.sh && /root/bootstrap.sh && rm /root/bootstrap.sh
EXPOSE 80
CMD ["/usr/sbin/runsvdir-start"]
<file_sep>/bootstrap.sh
#!/bin/bash
## compile imagemagick with q8
apt-get install --force-yes -y -q devscripts imagemagick libgraphviz-dev libcdt4 libcgraph5 libgd3 libgraph4 libgvc5 libgvpr1 libpathplan4 libvpx1 libxdot4 libxpm4
cd /tmp
mkdir -p source/imagemagick
cd source/imagemagick
apt-get source --force-yes -y -q imagemagick
apt-get build-dep --force-yes -y -q imagemagick
cd imagemagick*
sed -i 's/\t\-\-x\-libraries\=\/usr\/lib\/X11/\t\-\-x\-libraries\=\/usr\/lib\/X11 \\\n\t--with-quantum-depth=8 \\\n\t--disable-openmp/' debian/rules
perl -pi -e 's/modules-Q16/modules-Q8/g' debian/libmagickcore5-extra.install
perl -pi -e 's/modules-Q16/modules-Q8/g' debian/libmagickcore5.install
dch -l local "$(basename `pwd`-q8)"
debuild -us -uc
apt-get remove --force-yes -y -q imagemagick
dpkg -i ../*.deb
cd /
rm -rf /tmp/*
## end imagemagick
## mongodb 10gen key
apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv 7F0CEB10
echo 'deb http://downloads-distro.mongodb.org/repo/ubuntu-upstart dist 10gen' | sudo tee /etc/apt/sources.list.d/mongodb.list
add-apt-repository ppa:jon-severinsson/ffmpeg -y
add-apt-repository ppa:nginx/development -y # for latest nginx, this is the mainline version which IS a stable version suitable for production according to nginx devs
apt-get update
apt-get install --force-yes -y -q ffmpeg nodejs nginx whois runit libgdcm-tools dcmtk phantomjs mongodb-10gen
## clean up so we use less space
apt-get clean
|
89d942e44f3e6c8addf412edbe8a62414d1c758f
|
[
"Dockerfile",
"Shell"
] | 2 |
Dockerfile
|
trice-imaging/trice-docker-app-base
|
4944a33f44bba9597352786236d45a513c05f07f
|
5452d31c137fc90b7a94c5035452694ea2161514
|
refs/heads/main
|
<repo_name>ldcapt/BTVN_Luvina-LA-Course<file_sep>/Day 4 - Data Struct/19_NguyenHoangAnh_Bai34/src/com/luvina/Student.java
/**
* @Project_Name 19_NguyenHoangAnh_Bai34
*/
package com.luvina;
/**
* @author <NAME>
* @since 15 thg 3, 2021
* @version 1.0
*/
public class Student implements Comparable<Student> {
String name;
String score;
int age;
public Student() {
this.name = null;
this.score = null;
this.age = 0;
}
public Student(String name, String score, int age) {
this.name = name;
this.score = score;
this.age = age;
}
@Override
public String toString() {
return "Tên : " + this.name + "\n"
+ "Điểm : " + this.score + "\n"
+ "Tuổi : " + this.age + "\n";
}
@Override
public boolean equals(Object other) {
return this.name.equals( ((Student) other).getName() );
}
@Override
public int compareTo(Student o) {
return this.age - o.age;
}
// ---------------------- GETTER ----------------------
public String getName() {
return name;
}
public String getScore() {
return score;
}
public int getAge() {
return age;
}
}
<file_sep>/Day 1 - Overview/BTVN/BTVN1_19_NguyenHoangAnh_Bai4/src/com/luvina/bai4/BinaryTree.java
/**
* @Project_Name BTVN1_19_NguyenHoangAnh_Bai4
*/
package com.luvina.bai4;
/**
* @author <NAME>
* @since 25 thg 2, 2021
* @version 1.0
*/
public class BinaryTree {
Node root;
/**
*
*/
public BinaryTree() {
root = null;
}
public Node insertRec(Node newNode, int value) {
if(root == null) {
root = new Node(value);
return root;
}
if(value < root.value)
root.left = insertRec(root.left, value);
else if(value > root.value)
root.right = insertRec(root.right, value);
return root;
}
public void inorderRec(Node root) {
if(root != null) {
inorderRec(root.left);
System.out.println(root.value);
inorderRec(root.right);
}
}
public Node search(Node root, int value) {
// Trường hợp gốc : nếu node null hoặc là node root
if(root == null || root.value == value) {
return root;
}
// Giá trị lớn hơn giá trị code node root
if(root.value > value) {
return search(root.left, value);
}
// giá trị bé hơn giá trị của node root
return search(root.right, value);
}
}
<file_sep>/Day 4 - Data Struct/cautrucDLJava/TestPriorityQueueBook.java
package Luvina.Lec5.generic.priorityQueue;
import java.util.Comparator;
import java.util.*;
import java.util.PriorityQueue;
/**
*
* @author ManhHung
*/
public class TestPriorityQueueBook {
public static void main(String[] a) {
// Queue<String> q= new LinkedList<String>();
// q.add("S1");
// q.add("S2");
// q.add("S3");
// q.add("S4");
// while (!q.isEmpty()) {
// System.out.println("=="+ q.remove().toString());
// }
PriorityQueue<Book> pQ = new PriorityQueue<Book>();
// Theo tac gia
pQ.add(new Book("Tutorial Java 1.1", "C1", 1990));
pQ.add(new Book("Tutorial Java 1.2","A1", 1995));
pQ.add(new Book("Tutorial C", "D1", 1985));
pQ.add(new Book("Tutorial Pascal","A1", 1980));
// theo tac gia
while (!pQ.isEmpty()) {
System.out.println(pQ.remove().toString());
}
// Theo nam
PriorityQueue<Book> pQ1 = new PriorityQueue<Book> (100, new Comparator<Book>() {
public int compare(Book o1, Book o2) {
return o1.getYear().compareTo(o2.getYear());
}
});
pQ1.add(new Book("D Tutorial Java 1.1","C", 1990));
pQ1.add(new Book("A Tutorial Java 1.2", "A", 1995));
pQ1.add(new Book("C Tutorial C", "B", 1985));
pQ1.add(new Book("B Tutorial Pascal","A", 1980));
pQ1.addAll(pQ);
// Theo nam
while (!pQ1.isEmpty()) {
System.out.println("=="+ pQ1.remove());
}
}
}
<file_sep>/README.md
# Bài tập về nhà khóa LA
### Tác giả [<NAME>](https://www.facebook.com/ldcapt/)
Các project bài tập về nhà của khóa học LA
<file_sep>/Day 4 - Data Struct/cautrucDLJava/Student.java
package Luvina.Lec5.generic.arrayList;
/**
*
* @author ManhHung
*/
class Student implements Comparable<Student> // cai lại method compareTo
{ private String code;
private String name;
private Integer score;
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public void setScore(Integer score) {
this.score = score;
}
public Student(String code, String name, Integer score) {
this.code = code;
this.score = score;
this.name = name;
}
public Integer getScore() {
return score;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public String toString() {
return "(" + code + "," + score + ")";
}
// public int compareTo(Object other)
// {
// Student otherStu = (Student) other;
// return code.compareTo(otherStu.code);
// }
public int compareTo(Student other) {
return this.name.compareTo(other.name);
// int i1= code.compareTo(other.code);
// if (i1!=0) return i1;
// // =0
// int i2=name.compareTo(other.name);
// if (i2!=0) return i2;
// int i3=score.compareTo(other.score);
// return i3;
// code, name, score
// if (this.score.equals(other.score))
// return 0;
// else
// if (this.score>other.score)
// return 1;
// else
// return -1;
}
}
<file_sep>/Day 5 - Thread/README.md
# Buổi 5 - Thread
> ## Bài 1
Tạo một lớp NguoiGuiTien (Ma, Hoten, Diachi, Sodienthoai,Ngaysinh), so sánh được theo Ma.
### Yêu cầu
1.1. Tạo dữ liệu (5 người) và lưu vào `TreeMap<NguoiGuiTen, Double>;`
1.2. Nhập vào một người nào đó và tìm kiếm:
- Nếu người đó chưa có trong `TreeMap` thì thêm vào với số tiền gửi là 100;
- Nếu đã có người đó trong `TreeMap` thì tiến hành tăng số tiền trong tài khoản lên 100.
> ## Bài 2
### 2.a) Xây dựng các lớp sau
a.1. Tạo lớp Order gồm các thuộc tính sau - HOÁ ĐƠN
```java
int IdOrder; // mã hoá đơn
Date OrdDate; // ngày hoá đơn
String CustomerID; // mã khách hàng
// Ví dụ
or1 = new Order (1,"06/8/2020", "Cus01");
or2 = new Order (2,"06/8/2020", "Cus02");
```
a.2. Tạo lớp OrderDetail gồm các thuộc tính sau - CHI TIẾT HOÁ ĐƠN
```java
int IdOrder; // mã hoá đơn
int IdDetail; // mã hoá đơn chi tiết
int ItemID; // mã hàng
int Amount; // số lượng hàng
float Price; // đơn giá
// Ví dụ
orDetail1 = new OrderDetail (1, 1, 1, 10, 100);
orDetail2 = new OrderDetail (1, 2, 5, 7 , 20 );
orDetail3 = new OrderDetail (2, 3, 3, 10, 100);
orDetail4 = new OrderDetail (2, 4, 7, 7 , 20 );
```
a.3. Tạo lớp Purchase gồm các thuộc tính sau - NHẬP HÀNG
```java
int IdPurchase ; // mã đơn nhập hàng
Date purDate ; // ngày nhập hàng
String SupplierID; // mã nhà cung cấp
```
a.4. Tạo lớp PurchaseDetail gồm các thuộc tính sau
```java
int IdPurchase;
int IdDetail ;
int ItemID ;
int Amount ;
float Price ;
```
a.5.Tạo lớp Supplier gồm các thuộc tính sau
```java
String IdSup ; // mã nhà cung cấp
String Name ;
String Address;
String Tel ;
```
a.6. Tạo lớp Customer gồm:
```java
String IdCus ; // mã nhà cung cấp
String Name ;
String Address;
String Tel ;
```
### 2.b) Yêu cầu:
*b.1. Hãy xây dựng và chèn các hoá đơn vào các cấu trúc dữ liệu sau:*
1. `TreeMap <Order, ArrayList<OrderDetail>>`
2. `TreeMap <Customer, ArrayList<Order>>`
- Thực hành tìm kiếm danh sách hoá đơn theo mã khách hàng
- Thực hành tìm kiếm chi tiết hoá đơn theo mã hoá đơn
*b.2. Hãy xây dựng và chèn đơn nhập hàng vào các cấu trúc dữ liệu sau:*
- `HashMap <Supplier, TreeMap<Purchase, ArrayList<PurchaseDetail>>>`
- Thực hành tìm kiếm các đơn nhập hàng theo mã nhà cung cấp
> ## Bài 3
Thực hành Funtional Interfaces, Lambda Expressions, Method References, Stream Filter
> ## Bài 4
Thực hành các thao tác với CSDL
> ## Bài 5
Thực hành JavaBeans: PropertyChangeSupport, PropertyChangeListener
> ### Chú ý
1) Ôn tập thuật toán
2) Ôn tập kỹ các cấu trúc dữ liệu
---
# Bài tập phần Thead
> ## Bài 1
Cho int[] arr = { 11, 6, 7, 8, 9, 10 };
- Dùng `DataOutputStream` ghi các giá trị của mảng A ra file `Bai1-1.txt`;
- Dùng `DataInputStream` đọc dữ liệu từ file `Bai1-1.txt`, sắp xếp các giá trị đọc được theo thứ tự tăng dần sau đó ghi ra file `Bai1-2.txt`;
> ## Bài 2
Cho int[] arr = { 1, 7, 9, 14 } tăng dần và giá trị `x = 5`
- Dùng `RandomAccessFile` ghi mảng `arr` ra file `Bai2.txt`
- Đọc file `Bai2.txt` và chèn x vào để nội dung của file gồm các giá trị liên tiếp tăng dần.
> ## Bài 3
- Dùng notepad soạn 1 file text `Bai3-1.txt` gồm các câu.
- Dùng `FileReader` đọc và sửa lỗi soạn thảo
(sau dấu chấm phải viết hoa, sau dấu chấm, phảy phải có chỉ 1 dấu cách) và dùng `FileWriter` để ghi ra file `Bai3-2.txt`
> ## Bài 4
- Luyên tập try/catch/finally;
- Luyện tập các lớp streams khác
> ## Bài 5
Tính giá trị định thức của một ma trận vuông theo phương pháp biến đổi thành ma trận tam giác. (3 vòng lặp)
> ### Bài 6
Tham khảo `ObjectInputStream` và `ObjectOutputStream`
[Xem ví dụ](https://www.boraji.com/java-objectinputstream-and-objectoutputstream-example)
<file_sep>/Day 4 - Data Struct/cautrucDLJava/ListBinarySearch.java
package Luvina.Lec5.generic.arrayList;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
public class ListBinarySearch {
public static void main(String[] args)
{ List<Student> lst = new ArrayList<Student>();// sx theo ten
lst.add(new Student("A05726","AA", 8));
lst.add(new Student("A06338","AB", 7));
lst.add(new Student("A05379", "AC",5));
lst.add(new Student("A06338","AB1", 7));
lst.add(new Student("A06178", "AD",9));
System.out.println(lst);
//1 Menu
Collections.sort(lst);// Sort by name
Student st1=new Student("......","AC", 12);//Nhap SV can tim kiem (thay)
int i= Collections.binarySearch(lst, st1);// Search by name
System.out.println("index="+i);
if (i>=0) {
System.out.println("Found by name");
System.out.println(lst.get(i));
}
// 2 Sap xep theo Score de chuan bi cho tim kiem nhi phan theo Score
Collections.sort(lst, new Comparator <Student>(){
public int compare(Student a, Student b){
return a.getScore().compareTo(b.getScore());
}
} );
System.out.println(lst);
st1=new Student("......","A..C", 7);//Nhap SV can tim kiem
// 3 Tim kiem nhi phan theo Score
i= Collections.binarySearch(lst, st1, new Comparator<Student> (){ @Override
public int compare(Student a, Student b) {
return a.getScore().compareTo(b.getScore());
} });// tim theo score
System.out.println("index="+i);
if (i>=0) {
System.out.println("Found by score:");
int j=i;
while (j<lst.size() && lst.get(j).getScore()==7){
System.out.println(lst.get(j));
j++;
};
j=i-1;
while (j>=0 && lst.get(j).getScore()==7){
System.out.println(lst.get(j));
j--;
};
}
}
}
<file_sep>/Day 4 - Data Struct/cautrucDLJava/treeMap/treeMap1.java
package Luvina.Lec5.generic.treeMap;
import java.util.TreeMap;
import java.util.Set;
import java.util.Iterator;
import java.util.Map;
/**
* @author maychu
*/
public class treeMap1 {
public static void main(String args[]) {
// K, V
TreeMap<Integer, Book> tmap = new TreeMap<Integer, Book>();
tmap.put( 1, new Book("Tutorial Java 1.1", "C1", 1990,1));
tmap.put( 23, new Book("Tutorial Java 1.1", "C1", 1990,12));
tmap.put( 70, new Book("Tutorial Java 1.1", "C1", 1990,12));
tmap.put( 4, new Book("Tutorial Java 1.1", "C1", 1990,12));
tmap.put( 2, new Book("Tutorial Java 1.1", "C1", 1990,12));
boolean kt = tmap.containsKey(23);// tim kiem nhi phan nhu tren cay NPTK
if (kt) {System.out.println("The TreeMap containc key: 23");}
else {System.out.println("The TreeMap not containc key: 23");}
Book b=tmap.get(new Integer(4));
if (b!=null ) System.out.println(b);
else
System.out.println("The TreeMap not containc key: 23");
Iterator<Integer> iterator = tmap.keySet().iterator();
while(iterator.hasNext()) {
Integer key=iterator.next();
System.out.print("key is: "+ key + " & Value is: ");
System.out.println(tmap.get(key));
}
}
}<file_sep>/Day 4 - Data Struct/cautrucDLJava/TreeSet/Student.java
package Luvina.Lec5.generic.pTreeSet;
class Student implements Comparable<Student>
{
public String code;
private String name;
public Integer score;
public void setCode(String code) {
this.code = code;
}
public void setName(String name) {
this.name = name;
}
public void setScore(Integer score) {
this.score = score;
}
public Student(String code, String name, Integer score) {
this.code = code;
this.score = score;
this.name = name;
}
public Integer getScore() {
return score;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public String toString() {
return "(Ma SV: " + code + ", Ho ten:" + name + ", Diem TBL " + score + ")";
}
// public int compareTo(Object other)
// {
// Student otherStu = (Student) other;
// return code.compareTo(otherStu.code);
// }
public int compareTo(Student other) {
return code.compareTo(other.code);
}
}
<file_sep>/Day 2 - String/BTVN/README.md
# Buổi 2 : String
### 1. Cho int x = 9, kiểm tra x có phải là số nguyên tố hay ko?
### 2. Cho `int [] A = {1, 3, 4, 5, 6, 8}`
2.1. Kiểm tra xem mảng A có tạo thành dãy tăng dần ko?
2.2. Kiểm tra xem mảng A có tạo thành dãy đan dấu ko?
```
Ví dụ :
A = {1, -3, 4, -5, 6, -8}
```
### 3. Lập trình 03 thuật toán sx như trong file excel (`SX1-AM01`, `SX2-AM01`, `SX3-AM01`)
### 4. Sắp xếp các số lẻ tăng dần nhưng giá trị khác giữ nguyên vị trí
### 5. Sắp xếp các số dương tăng dần, các số âm giữ nguyên vị trí
### 6. Sắp xếp các số dương tăng dần, các số âm giảm dần.
<file_sep>/Day 4 - Data Struct/cautrucDLJava/HashSet/Book.java
package Luvina.Lec5.hashSet;
import java.util.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class Book {
private String title;
private String author;
private Integer year;
public Book(String title, String author, Integer year) {
this.title = title;
this.year = year;
this.author = author;
}
public String getTitle() {
return title;
}
public Integer getYear() {
return year;
}
public void setTitle(String title) {
this.title = title;
}
public void setYear(Integer year) {
this.year = year;
}
@Override
public String toString() {
return author + "," + title + "," + year.toString();
}
@Override
public int hashCode(){
int hash = (int) (author.charAt(0)+author.charAt(1));
System.out.println("hashCode of key: " + author + " = " + hash);
return hash;
}
@Override
public boolean equals(Object obj){
return author.equals(((Book) obj).author);
// boolean t1=title.equals(((Book)obj).title);
// if (!t1) return t1;
// boolean t2=author.equals(((Book)obj).author);
// if (!t2) return t2;
// return year.equals(((Book)obj).year);
}
}
class comparatorTitle implements Comparator<Book> {
@Override
public int compare(Book o1, Book o2) {
return o1.getTitle().compareTo(o2.getTitle());
}
}
class comparatorYear implements Comparator<Book> {
@Override
public int compare(Book o1, Book o2) {
return o1.getYear().compareTo(o2.getYear());
}
}
<file_sep>/Day 4 - Data Struct/19_NguyenHoangAnh_Bai1/src/com/luvina/linklist/Node.java
/**
* @Project_Name 19_NguyenHoangAnh_Bai1
*/
package com.luvina.linklist;
/**
* @author <NAME>
* @since 11 thg 3, 2021
* @version 1.0
*/
public class Node<Type> {
Type value;
Node<?> next;
public Node(Type value) {
this(value, null);
}
public Node(Type value, Node<?> next) {
this.value = value;
this.next = next;
}
public Type getValue() {
return value;
}
public Node<?> getNext() {
return next;
}
@Override
public boolean equals(Object other) {
if (other instanceof Node<?>)
if ( ((Node<?>) other).value.equals(value) )
return true;
return false;
}
}
<file_sep>/Day 1 - Overview/BTVN/BTVN1_19_NguyenHoangAnh_Bai3/src/com/luvina/bai3/BTVN1_19_NguyenHoangAnh_Bai3.java
/**
* @Project_Name BTVN1_19_NguyenHoangAnh_Bai3
*/
package com.luvina.bai3;
import java.util.Arrays;
/**
* @author <NAME>
* @since 25 thg 2, 2021
* @version 1.0
*/
public class BTVN1_19_NguyenHoangAnh_Bai3 {
/**
* @param args
*/
public static void main(String[] args) {
int[] arr = {4, 6, 9, 10, 17, 22};
insertNumber(arr, 15);
System.out.println(Arrays.toString(arr));
}
public static void insertNumber(int[] arr, int number) {
arr[arr.length - 1] = number;
for (int i = arr.length - 1; i > 0; i--) {
if(arr[i] < arr[i - 1]) {
arr[i] = arr[i - 1];
arr[i - 1] = number;
} else break;
}
}
}
<file_sep>/Day 1 - Overview/BTVN/README.md
# Buổi 1 : Java Overview
> ### 1. Mảng int [] A ={.....}; // Vòng while, for
Tìm, in ra giá trị LN và tất cả các ví trị xuất hiện của nó theo các trường hợp sau
Trường hợp 1: chí có 1 giá trị là LN thì in ra: Max=...
Trường hợp 2: có nhiều 1 hơn 1 phần tử của mảng có giá trị bằng LN thì in ra như sau:
Max=...; Soluong=...; cac vi tri= vt1, vt2, ....vtcuoi.
(Dùng mảng khác để lưu vị trí)
> ### 2. Cho mảng int [] A ={8, 6, 7, 3, 5, 6, 8, 9, 1, 4, 6, 7, 8}; // Vòng while, for
1. Xác định đoạn dài nhất chứa các phần tử liên tiếp tạo thành một dãy tăng dần, in ra màn hình vị trí đầu, vị trí cuối của đoạn đó.
2. Xác định tất cả các đoạn dài nhất chứa các phần tử liên tiếp tạo thành một dãy tăng dần, in ra màn hình các đoạn đó theo các trương hợp sau:
- Trường hợp 1: Chỉ có một đoạn thì in ra: Độ dài của đoạn =...; [đầu:..., cuối=...]
- Trường hợp 2: Có nhiều hơn một đoạn thì in ra: Số đoạn:=....; Độ dài của đoạn =...; {[đầu:..., cuối=...]; [đầu:..., cuối=...]; ....[đầu:..., cuối=...]}
> ### 3. Cho một giá trị int x=7 và một mảng int [] A ={ 4, 6, 9, 10, 17, 22}; gồm các phần tử tạo thành 1 dãy tăng dần.
Hãy bỏ phần tử cuối cùng của mảng A và chèn x vào mảng A để dãy kết quả nhận được là một dãy tăng dần.
A = { 4, 6, 9, 10, 17, 7};
A = { 4, 6, 7, 9, 10, 17};
> ### 4. Cho một giá trị int x và một mảng gồm các phần tử tạo thành 1 dãy tăng dần
```
int [] A = { 1, 4, 5, 6, 7, 7, 7, 7, 8, 9, 10};
```
Thực hiện tìm kiếm nhị phân phần tử x trong mảng A và in ra các vị trí xuất hiện của x.
> ### 5. Biến đổi mảng bằng cách thay giá trị max = giá trị min và ngược lại (tất cả)
> ### 6. Xâu kí tự
1. Cho một xâu kí tự chứa họ đệm tên, có thể thừa một số dấu cách. Viết chương trình loại bỏ các dấu cách thừa.
Ví dụ: `" Nguyễn Văn A ".`
2. Cho một xâu kí tự họ đệm tên. Viết chương trình tách riêng phần họ, đệm và tên.
3. Cho xâu kí tự. Viết chương trình tìm tất cả các từ dài nhất trong xâu (các từ cách nhau bởi dấu cách).
4. Cho một mảng chứa N phần tử là họ đệm tên của sinh viên. Viết chương trình đếm xem có bao nhiêu sinh viên tên Bình.
5. Cho một mảng chứa N phần tử là họ đệm tên của sinh viên. Hãy viết chương trình sắp xếp lại mảng theo thứ tự bảng chữ cái của tên họ đệm.
> ### 7. Luyện thêm các thuật toán sắp xếp
<file_sep>/Day 4 - Data Struct/README.md
# Buổi 4 - Data Struct
### 0.1) Tự xây dựng các cấu trúc:
- Danh sách liên kết, ngăn xếp, hàng đợi (kế thừa từ danh sách liên kết)
### 0.2) Cây nhị phân tìm kiếm:
- Viết phương thức chèn khử đệ quy;
- Viết 2 phương thức xoá: đệ quy và không đệ quy.
### 1) LinkedList
Thực hiện các phương thức của `LinkedList` với đối tượng thuộc kiểu cơ bản: `Integer`, `String`, `Double`, `Float`,...
### 2) LinkedList
Thực hiện các phương thức của `LinkedList` với đối tượng thuộc kiểu tự xây dựng: `Student`, `Book`, ....
### 3) ArrayList
Thực hiện các phương thức **(Chú ý: sắp xếp, tìm kiếm)** của `ArrayList` với đối tượng thuộc kiểu cơ bản: `Integer`, `String`, `Double`, `Float`,...
### 4) ArrayList
Thực hiện các phương thức **(Chú ý: sắp xếp, tìm kiếm)** của `ArrayList` với đối tượng thuộc kiểu tự xây dựng: `Student`, `Book`, ....
### 5) PriorityQueue
Thực hiện các phương thức **(Chú ý: điều kiện ưu tiên)** của `PriorityQueue` với đối tượng thuộc kiểu tự xây dựng: `Student`, `Book`, ....
### 6) HashSet
Thực hiện các phương thức của `HashSet` với đối tượng thuộc kiểu cơ bản: `Integer`, `String`, `Double`, Float,...
### 7) HashSet
Thực hiện các phương thức **(Chú ý: hashCode, equals)** của `HashSet` với đối tượng thuộc kiểu tự xây dựng: `Student`, `Book`, ....
### 8) TreeSet
Thực hiện các phương thức **(Chú ý: get, contains)** của `TreeSet` đối tượng thuộc kiểu cơ bản: `Integer`, `String`, `Double`, `Float`,...
### 9) TreeSet
Thực hiện các phương thức **(Chú ý: get, contains)** của `TreeSet` với đối tượng thuộc kiểu tự xây dựng: `Student`, `Book`, ....
|
c2a6af60256d9cdfbd2c9492c446473532679782
|
[
"Markdown",
"Java"
] | 15 |
Java
|
ldcapt/BTVN_Luvina-LA-Course
|
4a4874a6ea3a2b5325c24d2fff95b54b9b8602f7
|
e4f19c42eded0b8c631b29251be7cf6aa69a6a79
|
refs/heads/master
|
<repo_name>ajdelgados/callback-to-promise<file_sep>/index.js
async function execute () {
const request = require('request');
const options = {
method: 'GET',
url: 'https://aws.random.cat/meow'
};
request(options, (error, response, body) => {
if(error) console.log("Error form callback", error);
else console.log("Data from callback", body);
});
console.log("Done!");
const getData = () => {
return new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if(error) reject(error);
else resolve(body);
});
});
};
const data = await getData();
console.log("Data from function async/await", data);
console.log("Finished!")
}
execute();
<file_sep>/README.md
# De callback a async
Los callbacks, promise y async/await causa confusión cuando un desarrollador se encuentra aprendiendo JavaScript, con este post trataré de explicar los conceptos básicos y un ejemplo de como se puede transformar un callback en promesa para usarse dentro de una función async.
#### Conceptos básicos para la explicación
Callback es una función en JavaScript para ser ejecutada por otra función la cual se pasa como argumento y la declaración async en una función permite que esta opere asincrónamente a través de eventos usando promesas para devolver sus resultados. Una promesa es un objeto que devuelve el resultado de una operación asincrona (callback).
#### Iniciemos con callback
Un callback se puede hacer con el módulo request, para hacer una llamada a un API y poder ver el efecto del callback.
```javascript
const request = require('request');
const options = {
method: 'GET',
url: 'https://aws.random.cat/meow'
};
request(options, (error, response, body) => {
if(error) console.log("Error form callback", error);
else console.log("Data from callback", body);
});
console.log("Finished script!");
```
Con el código anterior, vemos que se ejecuta el script principal completamente y luego el resultado de la llamada al API.
#### Transformando un callback en promesa
En la sintaxis de un objeto promesa es importante los argumentos resolve y reject de la función que se indica para iniciarla, donde en resolve se ejecuta la resolución exitosa del callback y en reject el error.
```javascript
let promiseResponse = new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if(error) reject(error);
else resolve(body);
});
});
```
En el ejemplo, creamos promiseResponse como una promesa e indicamos que nos debe devolver en el caso de éxito o fallo con resolve y reject.
#### Esperando la resolución de la promesa con async/await
La espera de la ejecución de la promesa se debe hacer con el operador await, para usarlo debe ser dentro de una función async.
```javascript
const request = require('request');
const options = {
method: 'GET',
url: 'https://aws.random.cat/meow'
};
request(options, (error, response, body) => {
if(error) console.log("Error form callback", error);
else console.log("Data from callback", body);
});
async function execute() {
let promiseResponse = new Promise((resolve, reject) => {
request(options, (error, response, body) => {
if(error) reject(error);
else resolve(body);
});
});
console.log("Promise response", await promiseResponse);
console.log("Finished script!");
}
execute();
```
Al ejecutar el script, se podrá notar la diferencia entre hacer un callback y la espera de la respuesta de la promesa con el async/await. En diferentes ejecuciones la impresión del callback puede ser antes de finalizar el script o luego, mientras la respuesta de la promesa siempre se ejecuta antes de la ejecución de todo el script.
#### Referencias
* [Callback function](https://developer.mozilla.org/en-US/docs/Glossary/Callback_function)
* [Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
* [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function)
|
6eb07c3fd3d3212e4ec7a5afc316176f06b66143
|
[
"JavaScript",
"Markdown"
] | 2 |
JavaScript
|
ajdelgados/callback-to-promise
|
d9643bfe83960af3fcd0ceba044717f35c872c75
|
47579e967317dc0829ff44d2ebcab258dd353011
|
refs/heads/master
|
<repo_name>szintPisti/widget-service<file_sep>/src/main/java/com/miro/widgetservice/controller/WidgetController.java
package com.miro.widgetservice.controller;
import com.miro.widgetservice.model.Widget;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.apache.log4j.Logger;
import org.springframework.web.bind.annotation.*;
import java.awt.*;
@RestController
@RequestMapping("/widget-service")
@Api(value="widgetservice", description="Operations for managing widgets in the system")
public class WidgetController {
private final static Logger log = Logger.getLogger(WidgetController.class);
@PostMapping(value = "/create", produces = "application/json")
@ApiOperation(value = "Creates a single widget")
@ApiResponses(value = {
@ApiResponse(code = 201, message = "Widget has been successfully created"),
@ApiResponse(code = 400, message = "The provided parameter is invalid"),
@ApiResponse(code = 401, message = "You are not authorized to create widgets"),
@ApiResponse(code = 403, message = "Accessing the resource you were trying to reach is forbidden")})
public Widget create(@RequestParam int x,
@RequestParam int y,
@RequestParam int width,
@RequestParam int height,
@RequestParam(required = false, defaultValue = "0") int z) {
Widget newWidget = new Widget(new Point(x, y), width, height, z);
log.info(newWidget);
return newWidget;
}
}
<file_sep>/src/main/java/com/miro/widgetservice/WidgetServiceApp.java
package com.miro.widgetservice;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class WidgetServiceApp {
public static void main(String[] args) {
SpringApplication.run(WidgetServiceApp.class, args);
}
}
<file_sep>/README.md
# widget-service
Responsible for widget related CRUD operations.
|
341acf237a1619625fc549ec38c791f97edc8b09
|
[
"Markdown",
"Java"
] | 3 |
Java
|
szintPisti/widget-service
|
e05ed648eadac0dbdd361c7f77a61e665740d534
|
5ab1badb7d5576ef3f7f9eb8b1f2217c6165af2a
|
refs/heads/master
|
<repo_name>shuixi2013/xposed-art-dump-dex<file_sep>/app/src/main/java/cn/zaratustra/dumpdex/adapter/AppData.kt
package cn.zaratustra.dumpdex.adapter
import android.graphics.drawable.Drawable
/**
* Created by zaratustra on 2017/12/6.
*/
data class AppData(var packageName: String) {
var appName: String = ""
var icon: Drawable? = null
var isSelected: Boolean = false
}<file_sep>/app/src/main/java/cn/zaratustra/dumpdex/view/MainActivity.kt
package cn.zaratustra.dumpdex.view
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import android.view.View
import android.widget.EditText
import cn.zaratustra.dumpdex.R
import cn.zaratustra.dumpdex.adapter.AppData
import cn.zaratustra.dumpdex.adapter.AppListAdapter
import cn.zaratustra.dumpdex.core.AppInfoCenter
import cn.zaratustra.dumpdex.core.DumpDexNative
class MainActivity : AppCompatActivity() {
val mRvAppList: RecyclerView by lazy {
findViewById<RecyclerView>(R.id.rv_app_list)
}
val mEtSearch: EditText by lazy {
findViewById<EditText>(R.id.et_search)
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
DumpDexNative.chmodSoExecutable()
mRvAppList.layoutManager = LinearLayoutManager(this)
(mRvAppList.layoutManager as? LinearLayoutManager)?.orientation = LinearLayoutManager.VERTICAL
mEtSearch.visibility = View.GONE
AppInfoCenter.getAppList(object : AppInfoCenter.Callback {
override fun onFinish(appList: ArrayList<AppData>) {
mRvAppList.adapter = AppListAdapter(this@MainActivity, appList)
mRvAppList.adapter.notifyDataSetChanged()
mEtSearch.visibility = View.VISIBLE
}
})
mEtSearch.addTextChangedListener(object : TextWatcher {
override fun afterTextChanged(s: Editable?) {
if (!s.isNullOrEmpty() && !s.isNullOrBlank()) {
val mapKey = ArrayList<Int>()
val appList = AppInfoCenter.getAppListSync()
(0 until appList.size step 1).filterTo(mapKey) { appList[it].appName.contains(s.toString()) }
for (index in 0 until mapKey.size step 1) {
val value = mapKey[index]
(mRvAppList.adapter as AppListAdapter).swapData(index, value)
mRvAppList.scrollToPosition(0)
}
}
}
override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
}
override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
}
})
}
}
<file_sep>/app/src/main/cpp/dex_dump/DexDumper.h
//
// Created by RoseJames on 2017/12/6.
//
#ifndef XPOSED_ART_DUMP_DEX_DEXDUMPER_H
#define XPOSED_ART_DUMP_DEX_DEXDUMPER_H
#include <string>
using namespace std;
class DexDumper {
public:
bool StartDump(string pkgName);
static void LOG(const char *fmt, ...);
static void WriteToFile(uint8_t *string, size_t size);
private:
bool IsArt();
static string createFileName(size_t size);
};
typedef uint8_t byte;
namespace art {
class OatFile;
class DexFile;
class OatDexFile;
class MemMap;
}
#endif //XPOSED_ART_DUMP_DEX_DEXDUMPER_H
<file_sep>/app/src/main/java/cn/zaratustra/dumpdex/core/DumpDexNative.java
package cn.zaratustra.dumpdex.core;
import java.io.File;
/**
* Created by zaratustra on 2017/12/6.
*/
public class DumpDexNative {
private static final String SO_PATH = "/data/data/cn.zaratustra.dumpdex/lib/libdump-dex.so";
public static void chmodSoExecutable() {
File file = new File(SO_PATH);
file.setWritable(true, false);
file.setReadable(true, false);
file.setExecutable(true, false);
}
public static void loadSO() {
System.load(SO_PATH);
}
public static native void dumpDexNative(String pkgName);
}
<file_sep>/app/src/main/java/cn/zaratustra/dumpdex/core/AppInfoCenter.kt
package cn.zaratustra.dumpdex.core
import cn.zaratustra.dumpdex.adapter.AppData
import cn.zaratustra.dumpdex.utils.ContextFinder
import cn.zaratustra.dumpdex.utils.FileUtils
import org.jetbrains.anko.doAsync
import org.jetbrains.anko.uiThread
import org.json.JSONArray
import java.io.File
/**
* Created by zaratustra on 2017/12/6.
*/
object AppInfoCenter {
private val SELECTED_APP_FILE = "/sdcard/cn.zaratustra.dumpdex/selected.list"
private val mAllApp: HashMap<String, AppData> = HashMap()
private val mAppList = ArrayList<AppData>()
fun getAppList(callback: Callback) {
if (!File(SELECTED_APP_FILE).parentFile.exists()) {
File(SELECTED_APP_FILE).parentFile.mkdirs()
}
doAsync {
mAppList.clear()
mAllApp.clear()
var selectedApp = getSelectedApp()
var pkgManager = ContextFinder.getApplication().packageManager
var packages = pkgManager.getInstalledPackages(0)
for (it in packages) {
var appData = AppData(it.packageName)
appData.icon = it.applicationInfo.loadIcon(pkgManager)
appData.appName = it.applicationInfo.loadLabel(pkgManager).toString()
appData.isSelected = selectedApp.contains(appData.packageName)
mAppList.add(appData)
mAllApp[appData.packageName] = appData
}
uiThread {
callback.onFinish(mAppList)
}
}
}
fun getAppListSync(): ArrayList<AppData> {
return mAppList
}
interface Callback {
fun onFinish(appList: ArrayList<AppData>)
}
@Synchronized
fun selectedToBlock(appData: AppData, isSelected: Boolean) {
var appData = mAllApp[appData.packageName]
appData?.isSelected = isSelected
doAsync {
saveSelectedApp()
}
}
private fun saveSelectedApp() {
val selectedApp = mAllApp.filter { it.value.isSelected }
val jsonArray = JSONArray()
for (it in selectedApp.values) {
jsonArray.put(it.packageName)
}
FileUtils.saveContent(jsonArray.toString(), File(SELECTED_APP_FILE), "utf-8")
}
@Synchronized
fun getSelectedApp(): ArrayList<String> {
val result = ArrayList<String>()
try {
val jsonArrayStr = FileUtils.readFile(File(SELECTED_APP_FILE), "utf-8")
val jsonArray = JSONArray(jsonArrayStr)
(0 until jsonArray.length() step 1).mapTo(result) { it -> jsonArray[it].toString() }
} catch (e: Exception) {
e.printStackTrace()
}
return result
}
fun swapData(i: Int, k: Int) {
var appData = mAppList.removeAt(k)
mAppList.add(i, appData)
}
}<file_sep>/app/src/main/java/cn/zaratustra/dumpdex/adapter/AppListAdapter.kt
package cn.zaratustra.dumpdex.adapter
import android.content.Context
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.CheckBox
import android.widget.TextView
import cn.zaratustra.dumpdex.R
import cn.zaratustra.dumpdex.core.AppInfoCenter
/**
* Created by zaratustra on 2017/12/5.
*/
class AppListAdapter(private var mContext: Context, private var mAppList: ArrayList<AppData>)
: RecyclerView.Adapter<AppListItem>() {
var mLayoutInflater: LayoutInflater = LayoutInflater.from(mContext)
override fun onBindViewHolder(holder: AppListItem?, position: Int) {
holder?.let { holder.updateData(mAppList[position]) }
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): AppListItem {
return AppListItem(mLayoutInflater.inflate(R.layout.item_app, parent, false))
}
override fun getItemCount(): Int {
return mAppList.size
}
fun swapData(i: Int, k: Int) {
AppInfoCenter.swapData(i, k)
notifyItemMoved(k, i)
}
}
class AppListItem(itemView: View) : RecyclerView.ViewHolder(itemView) {
private var mAppIcon = itemView.findViewById<View>(R.id.app_icon)
private var mAppName = itemView.findViewById<TextView>(R.id.app_name)
private var mAppPkgName = itemView.findViewById<TextView>(R.id.app_pkg_name)
private var mCheckbox = itemView.findViewById<CheckBox>(R.id.check_box)
fun updateData(appData: AppData) {
mAppIcon.background = appData.icon
mAppName.text = appData.appName
mAppPkgName.text = appData.packageName
mCheckbox.isChecked = appData.isSelected
itemView.setOnClickListener {
appData.isSelected = !mCheckbox.isChecked
mCheckbox.isChecked = !mCheckbox.isChecked
AppInfoCenter.selectedToBlock(appData, appData.isSelected)
}
}
}<file_sep>/app/src/main/java/cn/zaratustra/dumpdex/core/HookMain.java
package cn.zaratustra.dumpdex.core;
import android.content.Context;
import android.os.Process;
import java.lang.reflect.Method;
import cn.zaratustra.dumpdex.utils.FileUtils;
import dalvik.system.PathClassLoader;
import de.robv.android.xposed.IXposedHookLoadPackage;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import de.robv.android.xposed.callbacks.XC_LoadPackage;
/**
* Created by zaratustra on 2017/12/5.
*/
public class HookMain implements IXposedHookLoadPackage {
public static String packageName = "cn.zaratustra.dumpdex";
public static String[] paths = new String[]{
String.format("/data/app/%s-%s.apk", packageName, 1),
String.format("/data/app/%s-%s.apk", packageName, 2),
String.format("/data/app/%s-%s/base.apk", packageName, 1),
String.format("/data/app/%s-%s/base.apk", packageName, 2)
};
@Override
public void handleLoadPackage(XC_LoadPackage.LoadPackageParam loadPackageParam) throws Throwable {
String filePath = "";
for (int i = 0; i < paths.length; i++) {
filePath = paths[i];
if (FileUtils.isExitsAndNotDir(filePath)) {
break;
}
}
try {
PathClassLoader pathClassLoader = new PathClassLoader(filePath, ClassLoader.getSystemClassLoader());
Class aClass = Class.forName(HookMain.class.getCanonicalName(), true, pathClassLoader);
Method aClassMethod = aClass.getMethod("hook", XC_LoadPackage.LoadPackageParam.class);
aClassMethod.setAccessible(true);
aClassMethod.invoke(aClass.newInstance(), loadPackageParam);
} catch (Exception e) {
e.printStackTrace();
}
}
public void hook(final XC_LoadPackage.LoadPackageParam loadPackageParam) {
if (AppInfoCenter.INSTANCE.getSelectedApp().contains(loadPackageParam.packageName)) {
XposedBridge.log("选择了APP,开始拦截:" + loadPackageParam.packageName);
DumpDexNative.loadSO();
XposedHelpers.findAndHookMethod("android.app.Application", loadPackageParam.classLoader, "attach",
Context.class, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
super.beforeHookedMethod(param);
XposedBridge.log(String.format("[%d]Hook %s Application attach method",
Process.myPid(), loadPackageParam.packageName));
DumpDexNative.dumpDexNative(loadPackageParam.packageName);
}
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
super.afterHookedMethod(param);
}
});
} else {
XposedBridge.log("未在列表中找到该APP:" + loadPackageParam.packageName);
}
}
}
<file_sep>/app/src/main/cpp/dex_dump/DexDumper.cc
//
// Created by RoseJames on 2017/12/6.
//
extern "C" {
#include "inline_hook/inlineHook.h"
}
#include "DexDumper.h"
#include <sys/system_properties.h>
#include <unistd.h>
#include <stdlib.h>
#include <android/log.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <time.h>
#include <string>
#include <string.h>
#define LOG_TAG "DexDumper"
using namespace std;
static string mPkgName;
art::DexFile *(*old_openmemory)(const byte *base, size_t size, const std::string &location,
uint32_t location_checksum, art::MemMap *mem_map,
const art::OatDexFile *oat_dex_file, std::string *error_msg) = NULL;
art::DexFile *new_openmemory(const byte *base, size_t size, const std::string &location,
uint32_t location_checksum, art::MemMap *mem_map,
const art::OatDexFile *oat_dex_file, std::string *error_msg) {
DexDumper::LOG("art::DexFile::OpenMemory is called");
DexDumper::WriteToFile((uint8_t *) base, size);
// 调用原art::DexFile::OpenMemory函数
return (*old_openmemory)(base, size, location, location_checksum, mem_map, oat_dex_file,
error_msg);
}
bool DexDumper::StartDump(string pkgName) {
if (IsArt()) {
mPkgName = pkgName;
void *handle = dlopen("libart.so", RTLD_GLOBAL | RTLD_LAZY);
if (handle == NULL) {
LOG("Error: unable to find libart.so");
return false;
}
void *address = dlsym(handle,
"_ZN3art7DexFile10OpenMemoryEPKhjRKNSt3__112basic_stringIcNS3_11char_traitsIcEENS3_9allocatorIcEEEEjPNS_6MemMapEPKNS_10OatDexFileEPS9_");
if (address == NULL) {
LOG("Error: unable to find openMemory method");
return false;
}
if (registerInlineHook((uint32_t) address, (uint32_t) new_openmemory,
(uint32_t **) &old_openmemory) != ELE7EN_OK) {
LOG("ERROR: Register inline hook failed");
return false;
}
if (inlineHook((uint32_t) address) != ELE7EN_OK) {
LOG("Error: inline hook failed");
return false;
}
LOG("Inline hook Success");
return true;
} else {
return false;
}
}
bool DexDumper::IsArt() {
char version[10];
__system_property_get("ro.build.version.sdk", version);
int sdk = atoi(version);
LOG("version:%d", sdk);
if (sdk >= 21) {
return true;
} else {
return false;
}
}
void DexDumper::LOG(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
__android_log_vprint(ANDROID_LOG_INFO, LOG_TAG, fmt, args);
va_end(args);
}
void DexDumper::WriteToFile(uint8_t *data, size_t size) {
string pathName = DexDumper::createFileName(size);
LOG("Dump dex file name is %s", pathName.c_str());
LOG("Start dump");
int dex = open(pathName.c_str(), O_CREAT | O_WRONLY, 0644);
if (dex < 0) {
LOG("Open or create file error");
return;
}
int ret = write(dex, data, size);
if (ret < 0) {
LOG("Write file error");
} else {
LOG("Dump dex file success: %s", pathName.c_str());
}
close(dex);
}
string DexDumper::createFileName(size_t size) {
char result[1024];
time_t now;
struct tm *timenow;
time(&now);
timenow = localtime(&now);
memset(result, 0, 1024);
sprintf(result, "/data/data/%s/dump_size_%u_time_%d_%d_%d_%d_%d_%d.dex", mPkgName.c_str(),
size,
timenow->tm_year + 1900,
timenow->tm_mon + 1,
timenow->tm_mday,
timenow->tm_hour,
timenow->tm_min,
timenow->tm_sec);
return string(result);
}
<file_sep>/README.md
# xposed-art-dump-dex
A Dex dumper for art with xposed framework
<file_sep>/app/CMakeLists.txt
cmake_minimum_required(VERSION 3.4.1)
include_directories(src/main/cpp/inline_hook
src/main/cpp/dex_dump
src/main/cpp/)
aux_source_directory(src/main/cpp/inline_hook SRC_PATH)
aux_source_directory(src/main/cpp/dex_dump SRC_PATH)
aux_source_directory(src/main/cpp SRC_PATH)
add_library(dump-dex SHARED ${SRC_PATH})
find_library(log-lib log)
target_link_libraries(dump-dex ${log-lib})<file_sep>/app/src/main/cpp/jni_bridge.cpp
#include <jni.h>
#include <string>
#include <string.h>
#include "dex_dump/DexDumper.h"
using namespace std;
extern "C"
JNIEXPORT void JNICALL
Java_cn_zaratustra_dumpdex_core_DumpDexNative_dumpDexNative(JNIEnv *env, jclass type,
jstring pkgName) {
const char *c_str = env->GetStringUTFChars(pkgName, JNI_FALSE);
string result = "";
if (c_str != NULL) {
result = string(c_str, strlen(c_str));
}
DexDumper *dexDumper = new DexDumper();
dexDumper->StartDump(result);
env->DeleteLocalRef(pkgName);
delete dexDumper;
}
|
9bd891863ca77412fee495299b3b3d6d65ea7097
|
[
"CMake",
"Markdown",
"Java",
"C++",
"Kotlin"
] | 11 |
Kotlin
|
shuixi2013/xposed-art-dump-dex
|
a3da7bd54361c4dd089d26e55d68c9492c6a33e5
|
eed0180d624b4933fae6098a9eb728f1a4270e65
|
refs/heads/main
|
<repo_name>Hunt-C/Laravel_practice<file_sep>/README.md
# Laravel_practice
following: https://github.com/chasewwy/laravel_tutorial https://dometi.com.tw/blog/category/%e7%b6%b2%e9%a0%81%e5%be%8c%e7%ab%af%e6%95%99%e5%ad%b8/laravel%e6%95%99%e5%ad%b8/
|
fee17e2a67815474bd4100ad714b0891775b1ae2
|
[
"Markdown"
] | 1 |
Markdown
|
Hunt-C/Laravel_practice
|
ffd860587f017532dfd0d3df7c52200a4803c50d
|
9d7ffc0f6328431af60afe979fb44fb57d35f234
|
refs/heads/master
|
<file_sep>
$(document).ready(function() {
$('#btnLogin').click(function(){
loginUtil.login();
});
});
var loginUtil = (function () {
return {
login: function () {
var id = $("#userId").val();
var pwd = $("#userPwd").val();
if(true){
alert("로그인 성공");
window.location.href = "dashboard";
}
else{
//todo 추후 이 코드로 수정
$.ajax({
url: 'login/doLogin'
,async: false //비동기 요청여부
,data:{
userId : id, userPwd: pwd
}
,dataType: 'json'
,type: 'GET'
,beforeSend: function(jqXHR){ //서버 요청 전 호출 함수, return false일 경우 요청 중단
if(!loginUtil.checkVal(id, pwd)){
return false;
}
}
,success: function(jqXHR){ //요청 성공시 호출
alert(jqXHR.resultCode);
}
,error: function(jqXHR){ // 요청 실패시 호출
alert("요청 실패");
}
// ,complete: function (jqXHR) {} //요청 여부 상관없이 호출
});
}
},
checkVal: function (id, pwd) {
if(id==null || id==""){
alert("ID를 입력하세요.");
return false;
}
if(pwd==null || pwd==""){
alert("비밀번호를 입력하세요.")
return false;
}
else{
return true;
}
}
}
}());
|
edd4ccb3e0e7d11ee7f670ae0de13e66ba60fd08
|
[
"JavaScript"
] | 1 |
JavaScript
|
2rules/boot-spring-boot
|
b4cf2f1ab0cc3c29af7baad471b7aa38b63c8dfe
|
a4f88e922542712c103edbeff1c621fcecf233f9
|
refs/heads/master
|
<file_sep>import {GET_PHOTOS_REQUEST,
GET_PHOTOS_SUCCESS, SET_MARK, SET_MODEL, SET_YEAR, SET_COST, SET_VALUTA, SET_TRANSMISSION, SET_TYPE, SET_MILEAGE, SET_AMOUNT, CLEAR,GET_CARS,SET_SEARCH } from '../constants/Search'
export function setMark(event,data) {
return {
type: SET_MARK,
mark: data.value
}
}
export function setModel(event,data) {
return {
type: SET_MODEL,
model: data.value
}
}
export function setYear(event,newValue) {
return {
type: SET_YEAR,
year: newValue
}
}
export function setCost(event,newValue) {
return {
type: SET_COST,
cost: newValue
}
}
export function setValuta(event,data) {
return {
type: SET_VALUTA,
valuta: data.value
}
}
export function setTransmission(event,data) {
return {
type: SET_TRANSMISSION,
transmission : data.checked?"Автоматика":"Ручное"
}
}
export function setType(event,data) {
return {
type: SET_TYPE,
enginesType: data.value
}
}
export function setAmount(event,data) {
return {
type: SET_AMOUNT,
amount: data.value
}
}
export function setMileage(event,data) {
return {
type: SET_MILEAGE,
mileage: data.value
}
}
export function setClear() {
return {
type: CLEAR,
mark:"",
model:"",
cost:0,
year:1950,
amount:0,
mileage:0,
enginesType:false,
transmission:"",
valuta:""
}
}
export function setSearch(obj) {
return {
type: SET_SEARCH,
mark:obj.mark,
model:obj.model,
cost:obj.cost,
year:obj.year,
amount:obj.amount,
mileage:obj.mileage,
enginesType:obj.enginesType,
transmission:obj.transmission
}
}
export function getPhotos() {
return (dispatch) => {
dispatch({
type: GET_PHOTOS_REQUEST,
year: 1999
})
setTimeout(() => {
dispatch({
type: GET_PHOTOS_SUCCESS,
photos: [1,2,3,4,5]
})
}, 1000)
}
}
export function getCars() {
return (dispatch) => {
fetch('http://localhost:3000/api/cars')
.then(function(response) {
return response.json();
})
.then(function(data) {
dispatch({
type: GET_CARS,
cars: data
})
})
}
}<file_sep>import {GET_POPULAR_CARS_SUCCESS,GET_POPULAR_CARS_REQUEST,SET_CAR,GET_CAR ,SET_MARK,SET_MODEL, SET_YEAR, SET_COST, SET_TRANSMISSION, SET_TYPE, SET_MILEAGE, SET_AMOUNT,SET_PHOTO} from '../constants/Main'
const initialState = {
cars: [
],
fetching:false,
car:{},
mark:"",
model:"",
year:1950,
cost:0,
transmission:"",
enginesType:"",
mileage:0,
amount:0,
marks: [ { key: 'Лифан', value: 'Лифан', text: 'Лифан' },{ key: 'Нисан', value: 'Нисан', text: 'Нисан' }],
models: {
"Лифан": [ { key: 'ЛифаноНовая', value: 'ЛифаноНовая', text: 'ЛифаноНовая' },{ key: 'ЛифанСтарая', value: 'ЛифанСтарая', text: 'ЛифанСтарая' }],
"Нисан":[ { key: 'НисанНовая', value: 'НисанНовая', text: 'НисанНовая' },{ key: 'НисанСтарая', value: 'НисанСтарая', text: 'НисанСтарая' }]} ,
currentModels: [],
photo:"",
watch:0
}
export default function main(state = initialState, action) {
switch (action.type) {
case GET_POPULAR_CARS_REQUEST:
return { ...state, fetching: true }
case GET_POPULAR_CARS_SUCCESS:
return { ...state, cars:action.cars, fetching: false }
case SET_CAR:
return { ...state, car:action.car }
case GET_CAR:
return { ...state, car:action.car, mark:action.mark,model:action.model ,currentModels: state.models[action.mark],cost:action.cost, year:action.year, transmission:action.transmission, enginesType:action.enginesType, mileage:action.mileage, amount:action.amount,photo:action.photo,watch:action.watch}
case SET_MARK:
return { ...state, mark:action.mark ,currentModels: state.models[action.mark]}
case SET_MODEL:
return { ...state, model:action.model }
case SET_COST:
return { ...state, cost: action.cost }
case SET_YEAR:
return { ...state, year: action.year}
case SET_TRANSMISSION:
return { ...state, transmission: action.transmission }
case SET_TYPE:
return { ...state, enginesType: action.enginesType }
case SET_MILEAGE:
return { ...state, mileage: action.mileage }
case SET_AMOUNT:
return { ...state, amount: action.amount }
case SET_PHOTO:
return { ...state, photo: action.photo }
default:
return state;
}
}<file_sep>export const GET_POPULAR_CARS_REQUEST = 'GET_POPULAR_CARS_REQUEST'
export const GET_POPULAR_CARS_SUCCESS = 'GET_POPULAR_CARS_SUCCESS'
export const SET_CAR = 'SET_CAR'
export const GET_CAR = 'GET_CAR'
export const SET_MARK = 'SET_MARK'
export const SET_MODEL = 'SET_MODEL'
export const SET_YEAR = 'SET_YEAR';
export const SET_COST = 'SET_COST';
export const SET_TRANSMISSION = 'SET_TRANSMISSION';
export const SET_TYPE = 'SET_TYPE';
export const SET_MILEAGE = 'SET_MILEAGE';
export const SET_AMOUNT = 'SET_AMOUNT';
export const SET_PHOTO = 'SET_PHOTO';<file_sep>import React from 'react'
import Cars from './Cars'
import Form from './Form'
import HeaderUser from './HeaderUser'
import {Grid,Row,Col} from 'react-bootstrap/lib/';
class Search extends React.Component {
constructor(props){
super(props);
this.query = this.query.bind(this);
}
componentDidMount(){
this.props.SearchActions.getCars();
}
query(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
componentDidMount(){
this.props.SearchActions.getCars();
var obj = {
mark:this.query('mark'),
model:this.query('model'),
year:this.query('year')?this.query('year'):1950,
cost:this.query('cost')?this.query('cost'):0,
transmission:this.query('transmission'),
enginesType:this.query('enginesType'),
mileage:this.query('mileage')?this.query('mileage'):0,
amount:this.query('amount')?this.query('amount'):0
};
this.props.SearchActions.setSearch(obj);
}
render () {
return <div>
<HeaderUser/>
<Grid>
<Row className="show-grid">
<Col xs={12} md={8}><Cars info={this.props.search} /></Col>
<Col xs={6} md={4}><Form handles={this.props.SearchActions} info={this.props.search} /></Col>
</Row>
</Grid>
</div>
}
}
export default Search;<file_sep>import React from 'react';
import HeaderUser from './HeaderUser'
import { Grid, Image } from 'semantic-ui-react'
import {Row,Col} from 'react-bootstrap/lib/';
class Car extends React.Component {
componentDidMount(){
this.props.MainActions.getCar(this.props.id.substring(1));
}
render () {
return <Grid.Column className="carCars">
<div onClick={this.showCar}>
<Row className="show-grid">
<Col xs={12} md={8}><Image src={this.props.car.photo} /></Col>
<Col xs={6} md={4}> <p>Марка: {this.props.car.id}</p>
<p>Марка: {this.props.car.mark}</p>
<p>Модель: {this.props.car.model}</p>
<p>Год: {this.props.car.year}</p>
<p>Цена: {this.props.car.cost}</p>
<p>Трансмиссия: {this.props.car.transmission}</p>
<p>Тип двигателя: {this.props.car.enginesType}</p>
<p>Пробег: {this.props.car.mileage}</p>
<p>Объём двигателя: {this.props.car.amount}</p>
<p>Просмотры: {this.props.car.watch}</p></Col>
{console.log(this.props.car.photo)}
</Row>
</div>
</Grid.Column>
}
}
export default Car;<file_sep>export const SET_MARK = 'SET_MARK';
export const SET_MODEL = 'SET_MODEL';
export const SET_YEAR = 'SET_YEAR';
export const SET_COST = 'SET_COST';
export const SET_VALUTA = 'SET_VALUTA';
export const SET_TRANSMISSION = 'SET_TRANSMISSION';
export const SET_TYPE = 'SET_TYPE';
export const SET_MILEAGE = 'SET_MILEAGE';
export const SET_AMOUNT = 'SET_AMOUNT';
export const CLEAR = 'CLEAR';
export const GET_PHOTOS_REQUEST = 'GET_PHOTOS_REQUEST'
export const GET_PHOTOS_SUCCESS = 'GET_PHOTOS_SUCCESS'
export const GET_CARS = 'GET_CARS'
export const SET_SEARCH = 'SET_SEARCH'<file_sep>{
"name": "laba3",
"version": "1.0.0",
"description": "",
"main": "server.js",
"scripts": {
"start": "node server.js"
},
"repository": {
"type": "git",
"url": "git+https://github.com/CHUKIN/laba3.git"
},
"author": "",
"license": "ISC",
"bugs": {
"url": "https://github.com/CHUKIN/laba3/issues"
},
"homepage": "https://github.com/CHUKIN/laba3#readme",
"dependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.0.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-es2017": "^6.24.1",
"babel-preset-react": "^6.24.1",
"babel-preset-react-hmre": "^1.1.1",
"babel-preset-stage-0": "^6.24.1",
"babel-preset-stage-1": "^6.24.1",
"body-parser": "^1.17.2",
"css-loader": "^0.28.4",
"express": "^4.15.3",
"express-fileupload": "^0.1.3",
"file-loader": "^0.11.2",
"history": "^4.6.2",
"material-ui": "^0.18.3",
"opn": "^5.1.0",
"react": "^15.6.1",
"react-bootstrap": "^0.31.0",
"react-dom": "^15.6.1",
"react-file-base64": "^1.0.2",
"react-redux": "^5.0.5",
"react-router": "^4.1.1",
"react-router-dom": "^4.1.1",
"react-router-redux": "^4.0.8",
"react-tap-event-plugin": "^2.0.1",
"redux": "^3.7.0",
"redux-thunk": "^2.2.0",
"semantic-ui-css": "^2.2.10",
"semantic-ui-react": "^0.68.5",
"style-loader": "^0.18.2",
"webpack": "^2.6.1",
"webpack-dev-middleware": "^1.10.2",
"webpack-hot-middleware": "^2.18.0"
}
}
<file_sep>import React from 'react';
import {Link, HashRouter,Switch,Route, BrowserRouter} from 'react-router-dom'
import {Navbar,Nav,NavItem,NavDropdown, MenuItem} from 'react-bootstrap/lib/';
class HeaderAdmin extends React.Component {
render () {
return <div>
<Navbar inverse collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<Link to="/admin">Главная страница админа</Link>
</Navbar.Brand>
<Navbar.Brand>
<Link to="/add">Добавление новой машины</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
</Navbar>
</div>
}
}
export default HeaderAdmin;<file_sep>import React, { Component } from 'react'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import Cars from '../components/Cars';
import Form from '../components/Form';
import Main from '../components/Main';
import Search from '../components/Search';
import Admin from '../components/Admin';
import AddCar from '../components/AddCar';
import Car from '../components/Car';
import ChangeCar from '../components/ChangeCar';
import DeleteCar from '../components/DeleteCar';
import './App.css';
import * as SearchActions from '../actions/SearchActions'
import * as MainActions from '../actions/MainActions'
import { Router, IndexRoute, browserHistory, Redirect } from 'react-router'
import createHistory from 'history/createBrowserHistory'
import {Link, HashRouter,Switch,Route, BrowserRouter} from 'react-router-dom'
const history = createHistory()
class App extends Component {
render () {
return <BrowserRouter browserHistory={history}>
<div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css"/>
<Route exact path="/" render={()=><Main {...this.props}/>} />
<Route path="/search" render={()=><Search {...this.props}/>}/>
<Route path="/admin" render={()=><Admin {...this.props}/>}/>
<Route path="/add" render={()=><AddCar {...this.props}/>}/>
<Route path="/car:id" render={({match})=><Car {...this.props} id={match.params.id} car={this.props.main.car}/>}/>
<Route path="/change:id" render={({match})=><ChangeCar {...this.props} id={match.params.id}/>}/>
<Route path="/delete:id" render={({match})=><DeleteCar {...this.props} id={match.params.id}/>}/>
</div>
</BrowserRouter>
}
}
function mapStateToProps(state) {
return {
search: state.search,
main: state.main
}
}
function mapDispatchToProps(dispatch) {
return {
SearchActions: bindActionCreators(SearchActions,dispatch),
MainActions: bindActionCreators(MainActions,dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(App)
<file_sep>import React from 'react';
import './Cars.css';
import { Grid, Image } from 'semantic-ui-react'
import CarCars from './CarCars'
class Cars extends React.Component {
render () {
const listCars = this.props.info.filteredCars.map((car) =><Grid.Row key={car.id.toString()}> <CarCars car={car}/> </Grid.Row>);
return <div className="cars">
<p>Найдено: {this.props.info.filteredCars.length}</p>
<Grid columns={1} divided>
{listCars}
</Grid>
</div>
}
}
export default Cars;<file_sep>import { combineReducers } from 'redux'
import search from './search'
import main from './main'
export default combineReducers({
main,
search
})<file_sep>var webpack = require('webpack');
module.exports = {
entry: [
'webpack-hot-middleware/client',
"./src/index.js",
],
output: {
path:'/public',
filename: "js/build.js",
publicPath: '/'
},
plugins : [
new webpack.optimize.OccurrenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin()
],
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015','es2017', 'react', 'stage-0', 'stage-1', 'react-hmre']
}
},
{ test: /\.css$/, loader: "style-loader!css-loader" },
{
test: /\.woff2?$|\.ttf$|\.eot$|\.svg$|\.png|\.jpe?g|\.gif$/,
loader: 'file-loader'
}
]
},
};<file_sep>import React from 'react';
import MostPopularCars from './MostPopularCars'
import HeaderUser from './HeaderUser'
import 'semantic-ui-css/semantic.min.css';
class Main extends React.Component {
componentDidMount(){
this.props.MainActions.getPopularCars();
}
render () {
return <div>
<HeaderUser/>
<div className="ui grid">
<MostPopularCars cars={this.props.main.cars} MainActions={this.props.MainActions} main={this.props.main} />
</div>
</div>
}
}
export default Main;<file_sep>import {GET_POPULAR_CARS_SUCCESS,GET_POPULAR_CARS_REQUEST,SET_CAR,GET_CAR ,SET_MARK,SET_MODEL, SET_YEAR, SET_COST, SET_TRANSMISSION, SET_TYPE, SET_MILEAGE, SET_AMOUNT,SET_PHOTO} from '../constants/Main'
export function setCar(car) {
return {
type: SET_CAR,
car: car
}
}
export function setMark(event,data) {
return {
type: SET_MARK,
mark: data.value
}
}
export function setModel(event,data) {
return {
type: SET_MODEL,
model: data.value
}
}
export function setYear(event,newValue) {
return {
type: SET_YEAR,
year: newValue
}
}
export function setCost(event,newValue) {
return {
type: SET_COST,
cost: newValue
}
}
export function setTransmission(event,data) {
return {
type: SET_TRANSMISSION,
transmission : data.checked?"Автоматика":"Ручное"
}
}
export function setType(event,data) {
return {
type: SET_TYPE,
enginesType: data.value
}
}
export function setAmount(event,data) {
return {
type: SET_AMOUNT,
amount: data.value
}
}
export function setMileage(event,data) {
return {
type: SET_MILEAGE,
mileage: data.value
}
}
export function setPhoto(data) {
return {
type: SET_PHOTO,
photo: data.target.src
}
}
export function getPopularCars() {
return (dispatch) => {
dispatch({
type: GET_POPULAR_CARS_REQUEST,
})
fetch('http://localhost:3000/api/mostpopularcars')
.then(function(response) {
return response.json();
})
.then(function(data) {
dispatch({
type: GET_POPULAR_CARS_SUCCESS,
cars: data
})
})
}
}
export function getCar(id) {
return (dispatch) => {
fetch('http://localhost:3000/api/car?id='+id)
.then(function(response) {
return response.json();
})
.then(function(data) {
dispatch({
type: GET_CAR,
car: data,
mark:data.mark,
model:data.model,
year: data.year,
cost:data.cost,
transmission:data.transmission,
enginesType:data.enginesType,
amount:data.amount,
mileage:data.mileage,
photo:data.photo,
watch:data.watch
})
})
}
}
export function deleteCar(id) {
return (dispatch) => {
fetch('http://localhost:3000/api/deletecar?id='+id)
.then(function(response) {
})
.then(function(data) {
})
}
}
export function changeCar(car) {
return (dispatch) => {
fetch(`http://localhost:3000/api/changecar?id=${car.id}&mark=${car.mark}&model=${car.model}&year=${car.year}&cost=${car.cost}&watch=${car.watch}&mileage=${car.mileage}&amount=${car.amount}&transmission=${car.transmission}&enginesType=${car.enginesType}`,{
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: `photo=${car.photo}`
})
.then(function(response) {
})
.then(function(data) {
})
}
}
export function addCar(car) {
return (dispatch) => {
fetch(`http://localhost:3000/api/addcar?mark=${car.mark}&model=${car.model}&year=${car.year}&cost=${car.cost}&watch=${car.watch}&mileage=${car.mileage}&amount=${car.amount}&transmission=${car.transmission}&enginesType=${car.enginesType}`,{
method: 'post',
headers: {
"Content-type": "application/x-www-form-urlencoded; charset=UTF-8"
},
body: `photo=${car.photo}`
})
.then(function(response) {
})
.then(function(data) {
})
}
}<file_sep># laba3
cd laba3
npm install
npm start
<file_sep>var express = require('express');
var app = express();
var opn = require('opn');
var config = require('./webpack.config.js');
var webpack = require('webpack');
var webpackDevMiddleware = require('webpack-dev-middleware');
var webpackHotMiddleware = require('webpack-hot-middleware');
var bodyParser = require('body-parser');
var compiler = webpack(config);
app.use(webpackDevMiddleware(compiler, {noInfo:true, publicPath: config.output.publicPath}));
app.use(webpackHotMiddleware(compiler))
app.use(express.static('public'));
let cars= [
{id:1,mark:"Лифан",model:"ЛифаноНовая",watch:101,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:2,mark:"Нисан",model:"НисанНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'http://ona-znaet.ru/statii/4/26/2.jpg'},
{id:3,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:2000,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'http://ona-znaet.ru/statii/4/26/2.jpg'},
{id:4,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:2000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://i.ytimg.com/vi/cFmFACENiGs/maxresdefault.jpg'},
{id:5,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Ручное",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:6,mark:"Лифан",model:"ЛифаноНовая",watch:105,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Дизель",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:7,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:30000,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:8,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:5,photo:'https://i.ytimg.com/vi/cFmFACENiGs/maxresdefault.jpg'},
{id:9,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:10,mark:"Нисан",model:"НисанНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://i.ytimg.com/vi/cFmFACENiGs/maxresdefault.jpg'},
{id:11,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:2000,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:12,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:2000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://i.ytimg.com/vi/cFmFACENiGs/maxresdefault.jpg'},
{id:13,mark:"Лифан",model:"ЛифаноНовая",watch:110,year:1950,cost:1000,transmission:"Ручное",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:14,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Дизель",mileage:100,amount:1,photo:'http://ona-znaet.ru/statii/4/26/2.jpg'},
{id:15,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:30000,amount:1,photo:'http://ona-znaet.ru/statii/4/26/2.jpg'},
{id:16,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:5,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:17,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'http://ona-znaet.ru/statii/4/26/2.jpg'},
{id:18,mark:"Нисан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:19,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:2000,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://i.ytimg.com/vi/cFmFACENiGs/maxresdefault.jpg'},
{id:20,mark:"Лифан",model:"ЛифаноНовая",watch:120,year:1950,cost:2000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:21,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Ручное",enginesType:"Бензин",mileage:100,amount:1,photo:'http://ona-znaet.ru/statii/4/26/2.jpg'},
{id:22,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Дизель",mileage:100,amount:1,photo:'https://look.com.ua/pic/201209/1600x900/look.com.ua-19447.jpg'},
{id:23,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:30000,amount:1,photo:'https://a.d-cd.net/409306u-960.jpg'},
{id:24,mark:"Лифан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:5,photo:'https://a.d-cd.net/409306u-960.jpg'},
{id:25,mark:"Нисан",model:"НисанНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://a.d-cd.net/409306u-960.jpg'},
{id:26,mark:"Нисан",model:"НисанНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:30000,amount:1,photo:'https://a.d-cd.net/409306u-960.jpg'},
{id:27,mark:"Нисан",model:"ЛифаноНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:5,photo:'https://a.d-cd.net/409306u-960.jpg'},
{id:28,mark:"Нисан",model:"НисанНовая",watch:100,year:1950,cost:1000,transmission:"Автоматика",enginesType:"Бензин",mileage:100,amount:1,photo:'https://a.d-cd.net/409306u-960.jpg'},
];
app.get('/api/cars',function (req, res) {
res.send(cars);
})
// app.use(bodyParser.json());
var urlencodedParser = bodyParser.urlencoded({limit: '500mb', extended: true})
app.post('/api/changecar', urlencodedParser, function (request, response) {
for(let i =0;i<cars.length;i++){
if(cars[i].id==request.query.id){
cars[i].mark=request.query.mark;
cars[i].model=request.query.model;
cars[i].year=request.query.year;
cars[i].cost=request.query.cost;
cars[i].transmission=request.query.transmission;
cars[i].enginesType=request.query.enginesType;
cars[i].amount=request.query.amount;
cars[i].mileage=request.query.mileage;
cars[i].watch=request.query.watch;
cars[i].photo=request.body.photo;
//var decodedFile = new Buffer(request.body.photo, 'base64');
break;
}
}
response.send(cars);
});
app.post('/api/addcar', urlencodedParser, function (request, response) {
let id =0;
for(let i=0;i<cars.length;i++){
if(id<cars[i].id){
id=cars[i].id;
}
car = {
id: id+1,
mark: request.query.mark,
model: request.query.model,
year: request.query.year,
cost: request.query.cost,
transmission: request.query.transmission,
enginesType: request.query.enginesType,
amount: request.query.amount,
mileage: request.query.mileage,
watch: request.query.watch,
photo: request.body.photo,
}
}
cars.push(car);
response.send(cars);
});
app.get('/api/deletecar', function (request, response) {
let newCars=[];
for(let i =0;i<cars.length;i++){
if(cars[i].id!=request.query.id){
newCars.push(cars[i]);
}
}
cars=newCars;
response.send(newCars);
});
app.get('/api/mostpopularcars', function (req, res) {
cars.sort(function(a,b){
return b.watch-a.watch;
})
let popularCars = [];
for(let i=0;i<25;i++){
popularCars.push(cars[i]);
}
res.send(popularCars);
});
function findCar(id) {
let car;
for(let i = 0 ; i<cars.length;i++){
if (cars[i].id==id){
car=cars[i];
break;
}
}
return car;
}
app.get('/api/car' , function(req, res) {
const id = req.query.id;
const car = findCar(id);
res.send(car);
});
app.get('*', function (req, res) {
res.sendFile("./public/index.html", { root: __dirname });
});
app.listen(3000, function () {
console.log('Example app listening on port 3000!');
opn('http://localhost:3000');
});<file_sep>import React from 'react';
import HeaderAdmin from './HeaderAdmin'
class DeleteCar extends React.Component {
componentDidMount(){
this.props.MainActions.deleteCar(this.props.id.substring(1));
}
render () {
return <div>
<HeaderAdmin/>
<h1>Машина удалена!</h1>
</div>
}
}
export default DeleteCar;
|
6260fc7d426b8c84b2436faa64782304b2fede66
|
[
"JavaScript",
"JSON",
"Markdown"
] | 17 |
JavaScript
|
CHUKIN/laba3
|
6bbcc675852ccce60f95e2373fe8115dfb08ea52
|
f6157e4a9338327c594885c2bd06a3c60487b42f
|
refs/heads/master
|
<file_sep>let formCheckboxes = document.querySelector('.form-checkboxes'),
formSubmit = document.querySelector('.input-email-wrapper'),
submitButtonMobile = document.querySelector('.input-submit.mobile');
formSubmit.addEventListener('click', () => {
formCheckboxes.classList.toggle('form-active');
formSubmit.classList.toggle('form-active');
submitButtonMobile.classList.toggle('form-active');
});
|
bd22d6c0bb39c0ef7a9d4270683a3e55cea2c4d0
|
[
"JavaScript"
] | 1 |
JavaScript
|
pawbie/CSW
|
53e1e89151ebee6fa7bf9d4995b0126f9f11edb8
|
6a8ff4ad4ae8b8e84fdd275bd60103de37baa1ba
|
refs/heads/master
|
<file_sep>Hooks:PostHook(BlackMarketTweakData, "_init_projectiles", "M202Incen_BlackMarketTweakData_init_projectiles", function(self, tweak_data)
self.projectiles.rocket_ray_frag_incen = deep_clone(self.projectiles.rocket_ray_frag)
self.projectiles.rocket_ray_frag_incen.unit = "units/mods/weapons/wpn_third_ray_fired_rocket/wpn_third_ray_fired_incen_rocket"
if not table.contains(self._projectiles_index, 'rocket_ray_frag_incen') then
table.insert(self._projectiles_index, 'rocket_ray_frag_incen')
end
local free_dlcs = tweak_data:free_dlc_list()
for _, data in pairs(self.projectiles) do
if free_dlcs[data.dlc] then
data.dlc = nil
end
end
self:_add_desc_from_name_macro(self.projectiles)
end)<file_sep>_G.HeavySecurity = _G.HeavySecurity or {}
if Network:is_client() then
return
end
if not HeavySecurity then
return
end
Hooks:Add("NetworkManagerOnPeerAdded", "NetworkManagerOnPeerAdded_ModAnnounce", function(peer, peer_id)
if Network:is_server() then
DelayedCalls:Add("DelayedModAnnounces_HeavySecurity_" .. tostring(peer_id), 5, function()
local peer2 = managers.network:session() and managers.network:session():peer(peer_id)
if peer2 then
peer2:send("send_chat_message", ChatManager.GAME, "This lobby is running Heavy Security MOD.")
end
end)
end
end)<file_sep>function FragGrenade:_spawn_environment_fire(normal, unit)
local grenade_entry = self._tweak_projectile_entry or "frag"
local tweak_entry = tweak_data.projectiles[grenade_entry]
if tweak_entry.incendiary_fire_arbiter then
local position = self._unit:position()
local rotation = self._unit:rotation()
local data = tweak_entry.incendiary_fire_arbiter
EnvironmentFire.spawn(position, rotation, data, normal, self._thrower_unit, 0, 1)
if unit:base()._fake_fire then
local _fire = World:spawn_unit(Idstring("units/pd2_dlc_bbq/weapons/molotov_cocktail/wpn_molotov_third"), unit:position(), unit:rotation())
_fire:base():_detonate(normal)
end
end
end
function FragGrenade:_detonate(tag, unit, body, other_unit, other_body, position, normal, collision_velocity, velocity, other_velocity, new_velocity, direction, damage, ...)
local pos = self._unit:position()
local normal = math.UP
local range = self._range
local slot_mask = managers.slot:get_mask("explosion_targets")
managers.explosion:give_local_player_dmg(pos, range, self._player_damage)
managers.explosion:play_sound_and_effects(pos, normal, range, self._custom_params)
local hit_units, splinters = managers.explosion:detect_and_give_dmg({
player_damage = 0,
hit_pos = pos,
range = range,
collision_slotmask = slot_mask,
curve_pow = self._curve_pow,
damage = self._damage,
ignore_unit = self._unit,
alert_radius = self._alert_radius,
user = self:thrower_unit() or self._unit,
owner = self._unit
})
self:_spawn_environment_fire(normal, unit)
managers.network:session():send_to_peers_synched("sync_unit_event_id_16", self._unit, "base", GrenadeBase.EVENT_IDS.detonate)
self._unit:set_slot(0)
end<file_sep># PingCap
http://downloads.lastbullet.net/15236
<file_sep>ProjectileBase = ProjectileBase or class(UnitBase)
function ProjectileBase.throw_projectile(projectile_type, pos, dir, owner_peer_id)
local projectile_entry = tweak_data.blackmarket:get_projectile_name_from_index(projectile_type)
if not ProjectileBase.check_time_cheat(projectile_type, owner_peer_id) then
return
end
local tweak_entry = tweak_data.blackmarket.projectiles[projectile_entry]
local unit_name = Idstring(not Network:is_server() and tweak_entry.local_unit or tweak_entry.unit)
local unit = World:spawn_unit(unit_name, pos, Rotation(dir, math.UP))
if owner_peer_id and managers.network:session() then
local peer = managers.network:session():peer(owner_peer_id)
local thrower_unit = peer and peer:unit()
if alive(thrower_unit) then
unit:base():set_thrower_unit(thrower_unit)
if not tweak_entry.throwable and thrower_unit:movement() and thrower_unit:movement():current_state() then
unit:base():set_weapon_unit(thrower_unit:movement():current_state()._equipped_unit)
end
end
end
unit:base():throw({
dir = dir,
projectile_entry = projectile_entry
})
if unit:base().set_owner_peer_id then
unit:base():set_owner_peer_id(owner_peer_id)
end
if projectile_entry == 'rocket_ray_frag_incen' then
projectile_entry = 'rocket_ray_frag'
projectile_type = tweak_data.blackmarket:get_index_from_projectile_id(projectile_entry)
unit:base()._fake_fire = true
end
managers.network:session():send_to_peers_synched("sync_throw_projectile", unit:id() ~= -1 and unit or nil, pos, dir, projectile_type, owner_peer_id or 0)
if tweak_data.blackmarket.projectiles[projectile_entry].impact_detonation then
unit:damage():add_body_collision_callback(callback(unit:base(), unit:base(), "clbk_impact"))
unit:base():create_sweep_data()
end
return unit
end<file_sep>http://downloads.lastbullet.net/16274
|
49f3744b6ae2d9669dc359f2dfb98693d234dcd2
|
[
"Markdown",
"Lua"
] | 6 |
Lua
|
ax6842/Mess
|
6f307db1af368685948088ee2bb0bd1987b5d197
|
57a13edb03c8f18f257cf20c98f256350c64059b
|
refs/heads/master
|
<repo_name>kowalsking/generative_art<file_sep>/index.js
/*
TILED LINES
*/
// function tiledLines() {
// const canvas = document.querySelector('canvas');
// const text = document.querySelector('#rgb-text');
// const ctx = canvas.getContext('2d');
//
// const size = 400;
// // window.innerWidth/2;
// const dpr = window.devicePixelRatio;
//
// canvas.width = size * dpr;
// canvas.height = size * dpr;
//
// ctx.scale(dpr, dpr);
// ctx.lineWidth = 2;
//
// let step = 15;
// let clr = randRGB();
//
// for (let x = 0; x < size; x += step) {
// for (let y = 0; y < size; y += step) {
// ctx.fillRect(0,0, size, size);
// ctx.fillStyle = clr;
// draw(x, y, step, step);
// }
// }
//
// function draw(x, y, width, height, color) {
// let leftToRight = Math.random() >= 0.5;
// if (leftToRight) {
// ctx.moveTo(x, y);
// ctx.lineTo(x + width, y + height);
// } else {
// ctx.moveTo(x + width, y);
// ctx.lineTo(x, y + height);
// }
// ctx.stroke();
// }
//
// function randRGB() {
// let r,g,b,rgb;
// r = Math.floor(Math.random()*256);
// g = Math.floor(Math.random()*256);
// b = Math.floor(Math.random()*256);
// rgb = `rgb(${r},${g},${b})`;
// text.textContent = rgb;
// return rgb;
// }
// }
/*
JOY DIVISION
*/
// function joyDivision() {
// const canvas = document.querySelector('canvas');
// const text = document.querySelector('#rgb-text');
// const ctx = canvas.getContext('2d');
//
// const size = 400;
// // window.innerWidth/2;
// const dpr = window.devicePixelRatio;
//
// canvas.width = size * dpr;
// canvas.height = size * dpr;
//
// const step = 10;
// const lines = [];
//
// createLines();
// draw();
//
// // create the lines
// function createLines() {
// for (let i = step; i <= size - step; i += step) {
// const line = [];
// for (let j = step; j <= size - step; j += step) {
// let distanceToCenter = Math.abs(j - size / 2);
// let variance = Math.max(size / 2 - 50 - distanceToCenter, 0);
// let random = Math.random() * variance / 2 * -1;
// let point = {x: j, y: i + random};
// line.push(point);
// }
// lines.push(line);
// }
// }
//
// // do the drawing
// function draw() {
// for (let i = 5; i < lines.length-4; i++) {
// ctx.beginPath();
// ctx.moveTo(lines[i][0].x, lines[i][0].y);
//
// for (var j = 0; j < lines[i].length - 2; j++) {
// var xc = (lines[i][j].x + lines[i][j + 1].x) / 2;
// var yc = (lines[i][j].y + lines[i][j + 1].y) / 2;
// ctx.quadraticCurveTo(lines[i][j].x, lines[i][j].y, xc, yc);
// }
//
// ctx.quadraticCurveTo(lines[i][j].x, lines[i][j].y, lines[i][j + 1].x, lines[i][j + 1].y);
// ctx.save();
// ctx.globalCompositeOperation = 'destination-out';
// ctx.fill();
// ctx.restore();
// ctx.stroke();
// }
// }
// }
/*
CUBIC DISARRAY
*/
// function cubicDisarray() {
// const canvas = document.querySelector('canvas');
// const text = document.querySelector('#rgb-text');
// const ctx = canvas.getContext('2d');
//
// const size = 320;
// // window.innerWidth/2;
// const dpr = window.devicePixelRatio;
//
// canvas.width = size * dpr;
// canvas.height = size * dpr;
//
// ctx.lineWidth = 2;
// ctx.scale(dpr, dpr);
//
// let squareSize = 30;
// let randomDisplacement = 15;
// let rotateMultiplier = 20;
// let offset = 10;
//
// function draw(width, height) {
// ctx.beginPath();
// ctx.rect(-width/2, -height/2, width, height);
// ctx.fillStyle = randRGB();
// ctx.fillRect(-width/2, -height/2, width, height);
// ctx.stroke();
// }
//
// function randRGB() {
// let r, g, b, rgb;
// r = Math.floor(Math.random()*256);
// g = Math.floor(Math.random()*256);
// b = Math.floor(Math.random()*256);
// rgb = `rgb(${r},${g},${b})`;
// // text.textContent = rgb;
// return rgb;
// }
//
// for (let i = squareSize; i <= size - squareSize ; i+=squareSize) {
// for (let j = 10; j <= size - squareSize; j+=squareSize) {
// let plusOrMinus = Math.random() < 0.5 ? -1 : 1;
// let rotateAmt = j / size * Math.PI / 180 * plusOrMinus * Math.random() * rotateMultiplier;
// plusOrMinus = Math.random() < 0.5 ? -1 : 1;
// let translateAmt = j / size * plusOrMinus * Math.random() * randomDisplacement;
//
// ctx.save();
// ctx.translate(i + translateAmt + offset, j + offset);
// ctx.rotate(rotateAmt);
// draw(squareSize, squareSize);
// ctx.restore();
// }
// }
// }
/*
TRINGULAR MESH
*/
function tringularMesh() {
const canvas = document.querySelector('canvas');
const text = document.querySelector('#rgb-text');
const ctx = canvas.getContext('2d');
const size = 320;
const dpr = window.devicePixelRatio;
canvas.width = size * dpr;
canvas.height = size * dpr;
ctx.lineWidth = 2;
ctx.scale(dpr, dpr);
ctx.lineJoin = 'bevel';
let line, dot, odd = false,
lines = [],
gap = size / 8;
for (let y = gap / 2; y <= size ; y += gap) {
odd = !odd;
line = [];
for (let x = gap / 4; x <= size; x += gap) {
dot = {x: x + (odd ? gap/2 : 0), y: y};
line.push({
x: x + (Math.random()*.8 - .4) * gap + (odd ? gap / 2 : 0),
y: y + (Math.random()*.8 - .4) * gap
});
ctx.fill();
}
lines.push(line);
}
function drawTriangle(pointA, pointB, pointC) {
ctx.beginPath();
ctx.moveTo(pointA.x, pointA.y);
ctx.lineTo(pointB.x, pointB.y);
ctx.lineTo(pointC.x, pointC.y);
ctx.lineTo(pointA.x, pointA.y);
ctx.closePath();
let gray = Math.floor(Math.random() * 16).toString(16);
ctx.fillStyle = '#' + gray + gray + gray;
ctx.fill();
ctx.stroke();
}
let dotLine;
odd = true;
for(let y = 0; y < lines.length -1; y++) {
odd = !odd;
dotLine = [];
for (let i = 0; i < lines[y].length; i++) {
dotLine.push(odd ? lines[y][i] : lines[y+1][i]);
dotLine.push(odd ? lines[y+1][i] : lines[y][i]);
}
for (let i = 0; i < dotLine.length - 2; i++) {
drawTriangle(dotLine[i], dotLine[i+1], dotLine[i+2]);
}
}
}
document.addEventListener('DOMContentLoaded', tringularMesh);
|
5dbbd952382aeabf9ab47c4042bf258a7d177c88
|
[
"JavaScript"
] | 1 |
JavaScript
|
kowalsking/generative_art
|
3a5c5d903b180fe782973500b1733dcab80a1b4c
|
3ea2d459008e89789abf317e5aa18bdd468edf45
|
refs/heads/master
|
<repo_name>mjzhou/6vspider<file_sep>/README.md
6vspider
========
Get seed information on bt.neu6.edu.cn
<file_sep>/spider.py
#!/usr/bin/python
# -*- coding: utf-8 -*-
from multiprocessing import Process,Pool
import urllib,urllib2,cookielib,sys,os,types,re,threading,MySQLdb
class torrent:
def __init__(self):
self.username='yourusername'
self.password='<PASSWORD>'
self.opener = self.cookie()
self.page_6v = {'movie': 13,'tv':14,'music':15,'ent':16,'pe':17,'file':18,'soft':19,'other':20,'game':21,'avg':44,'record':127,'hdmovie':45,'hdtv':48,'hdrecord':49,'hdmv':50,'hdmusic':91}
def cookie(self):
auth_url = 'http://bt.neu6.edu.cn/member.php?mod=logging&action=login&loginsubmit=yes&infloat=yes&lssubmit=yes&inajax=1'
data={"username":self.username,"password":self.<PASSWORD>,"quickforward":"yes","hamdlekey":"ls"}
post_data=urllib.urlencode(data)
cookieJar=cookielib.CookieJar()
opener=urllib2.build_opener(urllib2.HTTPCookieProcessor(cookieJar))
req=urllib2.Request(auth_url,post_data)
result = opener.open(req)
return opener
def pagesum(self,page):
rs = re.findall(r'\.{3}\d+',page)
return rs[0][3:]
def pagelist(self):
for board in self.page_6v.values():
p = Process(target=self.page, args=(board,))
p.start()
def content(self,url):
f = self.opener.open(url)
str = f.read()
html = str.decode('gbk', 'ignore').encode('utf-8')
html = html.replace(' ','')
html = html.replace('\r\n','')
return html
f.close()
def page(self,board):
url = 'http://bt.neu6.edu.cn/forum-'+str(board)+'-1.html'
html = self.content(url)
pagemax = int(self.pagesum(html))+1
for pnum in range(1,pagemax):
pid=str(board)+'-'+str(pnum)
turl = 'http://bt.neu6.edu.cn/forum-'+pid+'.html'
t = threading.Thread(target=self.seedinfo,args=(turl,))
t.start()
t.join()
def seedinfo(self,url):
html = self.content(url)
rs = re.findall(r'id="normal.*?</tbody>',html)
sql="INSERT INTO `file` (`id`, `name`, `dir` , `size` ,`author` , `date`) VALUES "
for list in rs:
try:
surl = 'http://bt.neu6.edu.cn/'+re.findall(r'thread-.*?html',list)[0]
size = re.findall(r'\d*\.\d*\wB|\d{1,3}[K|M|G|T]B|\d*Bytes',list)[0]
title = re.findall(r'xst">.*?</a>',list)[0][5:-4]
author = re.findall(r'>.{1,50}</a></cite>',list)[0][1:-11].replace("'","\\'")
date = re.findall(r'\d{4}-\d{1,2}-\d{3,4}:\d{2}',list)[0]+':00'
time=date[:-8]+' '+date[-8:]
stitle = title.replace("'","\\'")
sql=sql+"(NULL, '"+stitle+"', '"+surl+"', '"+size+"', '"+author+"', '"+time+"'),"
except:
surl = 'http://bt.neu6.edu.cn/'+re.findall(r'thread-.*?html',list)[0]
size = re.findall(r'\d*\.\d*\wB|\d{1,3}[K|M|G|T]B|\d*Bytes',list)[0]
if(size=='0Bytes'):
break
title = re.findall(r'xst">.*?</a><img',list)[0][5:-8]
author = re.findall(r'<cite>.{1,50}</cite>',list)[0][6:-7].replace("'","\\'")
date = re.findall(r'\d{4}-\d{1,2}-\d{3,4}:\d{2}',list)[0]+':00'
time=date[:-8]+' '+date[-8:]
stitle = title.replace("'","\\'")
sql=sql+"(NULL, '"+title+"', '"+surl+"', '"+size+"', '"+author+"', '"+time+"'),"
try:
self.insert(sql[0:-1])
except:
print url
print sys.exc_info()
def insert(self,sql):
conn = MySQLdb.Connect(user='root', passwd='', db='ftp', host='192.168.96.243',charset='utf8')
cur=conn.cursor(cursorclass = MySQLdb.cursors.DictCursor)
cur.execute(sql)
conn.commit()
cur.close()
conn.close()
down = torrent()
down.pagelist()
|
9b24d4497961f863ef1fc0dddd69008d788ff6b1
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
mjzhou/6vspider
|
34df035228e034cfe6fa183b06e961a4f7626953
|
d9f5355222daec0de74fd25739d0cc420f23ba2c
|
refs/heads/master
|
<repo_name>vjuhnder/UhQAMailer<file_sep>/report.py
#!/usr/bin/env python
# START_SOFTWARE_LICENSE_NOTICE
# -------------------------------------------------------------------------------------------------------------------
# Copyright (C) 2016-2017 Uhnder, Inc. All rights reserved.
# This Software is the property of Uhnder, Inc. (Uhnder) and is Proprietary and Confidential. It has been provided
# under license for solely use in evaluating and/or developing code for Uhnder products. Any use of the Software to
# develop code for a product not manufactured by or for Uhnder is prohibited. Unauthorized use of this Software is
# strictly prohibited.
# Restricted Rights Legend: Use, Duplication, or Disclosure by the Government is Subject to Restrictions as Set
# Forth in Paragraph (c)(1)(ii) of the Rights in Technical Data and Computer Software Clause at DFARS 252.227-7013.
# THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE UHNDER END-USER LICENSE AGREEMENT (EULA). THE PROGRAM MAY ONLY
# BE USED IN A MANNER EXPLICITLY SPECIFIED IN THE EULA, WHICH INCLUDES LIMITATIONS ON COPYING, MODIFYING,
# REDISTRIBUTION AND WARRANTIES. PROVIDING AFFIRMATIVE CLICK-THROUGH CONSENT TO THE EULA IS A REQUIRED PRECONDITION
# TO YOUR USE OF THE PROGRAM. YOU MAY OBTAIN A COPY OF THE EULA FROM WWW.UHNDER.COM. UNAUTHORIZED USE OF THIS
# PROGRAM IS STRICTLY PROHIBITED.
# THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES ARE GIVEN, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING
# WARRANTIES OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT AND TITLE. RECIPIENT SHALL HAVE
# THE SOLE RESPONSIBILITY FOR THE ADEQUATE PROTECTION AND BACK-UP OF ITS DATA USED IN CONNECTION WITH THIS SOFTWARE.
# IN NO EVENT WILL UHNDER BE LIABLE FOR ANY CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING LOSS OF DATA OR USE, LOST
# PROFITS OR ANY INCIDENTAL OR SPECIAL DAMAGES, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE, WHETHER IN ACTION OF CONTRACT OR TORT, INCLUDING NEGLIGENCE. UHNDER FURTHER DISCLAIMS ANY LIABILITY
# WHATSOEVER FOR INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS OF ANY THIRD PARTY.
# -------------------------------------------------------------------------------------------------------------------
# END_SOFTWARE_LICENSE_NOTICE
<file_sep>/email_util.py
#!/usr/bin/env python
# START_SOFTWARE_LICENSE_NOTICE
# -------------------------------------------------------------------------------------------------------------------
# Copyright (C) 2016-2017 Uhnder, Inc. All rights reserved.
# This Software is the property of Uhnder, Inc. (Uhnder) and is Proprietary and Confidential. It has been provided
# under license for solely use in evaluating and/or developing code for Uhnder products. Any use of the Software to
# develop code for a product not manufactured by or for Uhnder is prohibited. Unauthorized use of this Software is
# strictly prohibited.
# Restricted Rights Legend: Use, Duplication, or Disclosure by the Government is Subject to Restrictions as Set
# Forth in Paragraph (c)(1)(ii) of the Rights in Technical Data and Computer Software Clause at DFARS 252.227-7013.
# THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE UHNDER END-USER LICENSE AGREEMENT (EULA). THE PROGRAM MAY ONLY
# BE USED IN A MANNER EXPLICITLY SPECIFIED IN THE EULA, WHICH INCLUDES LIMITATIONS ON COPYING, MODIFYING,
# REDISTRIBUTION AND WARRANTIES. PROVIDING AFFIRMATIVE CLICK-THROUGH CONSENT TO THE EULA IS A REQUIRED PRECONDITION
# TO YOUR USE OF THE PROGRAM. YOU MAY OBTAIN A COPY OF THE EULA FROM WWW.UHNDER.COM. UNAUTHORIZED USE OF THIS
# PROGRAM IS STRICTLY PROHIBITED.
# THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES ARE GIVEN, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING
# WARRANTIES OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT AND TITLE. RECIPIENT SHALL HAVE
# THE SOLE RESPONSIBILITY FOR THE ADEQUATE PROTECTION AND BACK-UP OF ITS DATA USED IN CONNECTION WITH THIS SOFTWARE.
# IN NO EVENT WILL UHNDER BE LIABLE FOR ANY CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING LOSS OF DATA OR USE, LOST
# PROFITS OR ANY INCIDENTAL OR SPECIAL DAMAGES, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE, WHETHER IN ACTION OF CONTRACT OR TORT, INCLUDING NEGLIGENCE. UHNDER FURTHER DISCLAIMS ANY LIABILITY
# WHATSOEVER FOR INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS OF ANY THIRD PARTY.
# -------------------------------------------------------------------------------------------------------------------
# END_SOFTWARE_LICENSE_NOTICE
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from email.mime.application import MIMEApplication
import report
def send_email(job_names, job_url, html_table):
addressto = "All"
changeset = "abcdefgh"
commit_msg = "This is commit message"
# TODO: Get addressto
# TODO: Get Changeset
# TODO: Get commit message
message = 'Hi ' \
+ addressto + ','
message += '<br><br> Your commit with <b>changeset: ' \
+ changeset \
+ '</b>, with changes (<b>' \
+ commit_msg \
+ '</b>) is breaking the build.<br><br>'
message += '<br><br> <b>Panic Board Summary<b><br><br>' \
+ html_table \
+ '<br><br><br>Thanks & Regards, <br> <b>UhDC QA Team</b>'
msg = MIMEMultipart()
msg['From'] = '<EMAIL>'
# TODO: Get names to send email
msg['To'] = '<EMAIL>'
msg['Subject'] = "DO NOT REPLY***PANIC***NOTIFICATION "
msg.attach(MIMEText(message, 'html'))
# TODO: attach log file
server = smtplib.SMTP('smtp.office365.com', 587)
server.ehlo()
server.starttls()
server.ehlo()
# TODO: Store password in a file or get from a file
server.login('<EMAIL>', "fcnsslpffwpchlkq")
text = msg.as_string()
server.sendmail('<EMAIL>', "<EMAIL>", text)
server.quit()
print("Sending Email.....")
<file_sep>/jenkins.py
#!/usr/bin/env python
# START_SOFTWARE_LICENSE_NOTICE
# -------------------------------------------------------------------------------------------------------------------
# Copyright (C) 2016-2017 Uhnder, Inc. All rights reserved.
# This Software is the property of Uhnder, Inc. (Uhnder) and is Proprietary and Confidential. It has been provided
# under license for solely use in evaluating and/or developing code for Uhnder products. Any use of the Software to
# develop code for a product not manufactured by or for Uhnder is prohibited. Unauthorized use of this Software is
# strictly prohibited.
# Restricted Rights Legend: Use, Duplication, or Disclosure by the Government is Subject to Restrictions as Set
# Forth in Paragraph (c)(1)(ii) of the Rights in Technical Data and Computer Software Clause at DFARS 252.227-7013.
# THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE UHNDER END-USER LICENSE AGREEMENT (EULA). THE PROGRAM MAY ONLY
# BE USED IN A MANNER EXPLICITLY SPECIFIED IN THE EULA, WHICH INCLUDES LIMITATIONS ON COPYING, MODIFYING,
# REDISTRIBUTION AND WARRANTIES. PROVIDING AFFIRMATIVE CLICK-THROUGH CONSENT TO THE EULA IS A REQUIRED PRECONDITION
# TO YOUR USE OF THE PROGRAM. YOU MAY OBTAIN A COPY OF THE EULA FROM WWW.UHNDER.COM. UNAUTHORIZED USE OF THIS
# PROGRAM IS STRICTLY PROHIBITED.
# THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES ARE GIVEN, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING
# WARRANTIES OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT AND TITLE. RECIPIENT SHALL HAVE
# THE SOLE RESPONSIBILITY FOR THE ADEQUATE PROTECTION AND BACK-UP OF ITS DATA USED IN CONNECTION WITH THIS SOFTWARE.
# IN NO EVENT WILL UHNDER BE LIABLE FOR ANY CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING LOSS OF DATA OR USE, LOST
# PROFITS OR ANY INCIDENTAL OR SPECIAL DAMAGES, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE, WHETHER IN ACTION OF CONTRACT OR TORT, INCLUDING NEGLIGENCE. UHNDER FURTHER DISCLAIMS ANY LIABILITY
# WHATSOEVER FOR INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS OF ANY THIRD PARTY.
# -------------------------------------------------------------------------------------------------------------------
# END_SOFTWARE_LICENSE_NOTICE
import json
import urllib
JENKINS_PORT = "8080"
PANIC_MONITOR = "Panic%20Monitor"
class PanicMonitor:
def __init__(self, server_ip):
self.job_names = []
self.failed_jobs = []
self.succeed_jobs = []
self.failed_progress_job = []
self.succeed_progress_job = []
self.server_ip = server_ip
self.job_count = 0
self.job_url = []
self.sno = []
self.job_status = {}
def get_url_json(self, get_url):
get_url += '/api/json'
json_response = urllib.urlopen(get_url)
json_data = json.loads(json_response.read())
json_response.close()
return json_data
def get_jobs_details(self):
get_url = 'http://' + self.server_ip + ':' + JENKINS_PORT + '/view/' + PANIC_MONITOR
json_data = self.get_url_json(get_url)
monitor_jobs = json_data['jobs']
self.job_count = 0
# parse the jobs array
for each_job in monitor_jobs:
self.job_count += 1
self.sno.append(self.job_count)
job_name = each_job['name']
self.job_names.append(job_name)
self.job_url.append(each_job['url'])
status = each_job['color']
if status == 'blue' or status == 'blue_anime':
self.succeed_jobs.append(job_name)
self.job_status[job_name] = "SUCCESS"
elif status == 'red':
self.failed_jobs.append(job_name)
self.job_status[job_name] = "FAILED"
elif status == "red_anime":
self.failed_progress_job(job_name)
self.job_status[job_name] = "FAILED"
def get_last_build(self, job_url):
json_data = self.get_url_json(job_url)
last_build_url = json_data['lastBuild']['url']
return last_build_url
def get_jenkins_server_uri(self):
jenkins_url = 'http://' + self.server_ip + ':' + JENKINS_PORT
print("Jenkins server url..." + jenkins_url)
def create_table(self):
# TODO: Get last build url, console log attachment
html_table = '<style>table {font-family: arial, sans-serif;border-collapse: collapse;width: 100%;}td, ' \
'th {border: 1px solid #dddddd;text-align: left;padding: 8px;}</style><table><tr><th>S. No</th>' \
'<th>Job Name</th><th>Build Status</th><th>Jenkins URL</th></tr>'
index = 0
print (self.job_status)
for each_job in self.job_names:
if self.job_status[each_job] == "SUCCESS":
color = "green"
else:
color = "red"
html_table += '<tr style="color: %s;"><td>' %(color) \
+ str(self.sno[index]) \
+ '</td><td>' \
+ each_job \
+ '</td><td>%s</td><td><a href="%s"> Jenkins URL </a></tr>' \
% (self.job_status[each_job], self.get_last_build(self.job_url[index]) + "console")
index += 1
html_table += '</table>'
return html_table
<file_sep>/generate_email.py
#!/usr/bin/env python
# START_SOFTWARE_LICENSE_NOTICE
# -------------------------------------------------------------------------------------------------------------------
# Copyright (C) 2016-2017 Uhnder, Inc. All rights reserved.
# This Software is the property of Uhnder, Inc. (Uhnder) and is Proprietary and Confidential. It has been provided
# under license for solely use in evaluating and/or developing code for Uhnder products. Any use of the Software to
# develop code for a product not manufactured by or for Uhnder is prohibited. Unauthorized use of this Software is
# strictly prohibited.
# Restricted Rights Legend: Use, Duplication, or Disclosure by the Government is Subject to Restrictions as Set
# Forth in Paragraph (c)(1)(ii) of theRights in Technical Data and Computer Software Clause at DFARS 252.227-7013.
# THIS PROGRAM IS PROVIDED UNDER THE TERMS OF THE UHNDER END-USER LICENSE AGREEMENT (EULA). THE PROGRAM MAY ONLY
# BE USED IN A MANNER EXPLICITLY SPECIFIED IN THE EULA, WHICH INCLUDES LIMITATIONS ON COPYING, MODIFYING,
# REDISTRIBUTION AND WARRANTIES. PROVIDING AFFIRMATIVE CLICK-THROUGH CONSENT TO THE EULA IS A REQUIRED PRECONDITION
# TO YOUR USE OF THE PROGRAM. YOU MAY OBTAIN A COPY OF THE EULA FROM WWW.UHNDER.COM. UNAUTHORIZED USE OF THIS
# PROGRAM IS STRICTLY PROHIBITED.
# THIS SOFTWARE IS PROVIDED "AS IS". NO WARRANTIES ARE GIVEN, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING
# WARRANTIES OR MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, NONINFRINGEMENT AND TITLE. RECIPIENT SHALL HAVE
# THE SOLE RESPONSIBILITY FOR THE ADEQUATE PROTECTION AND BACK-UP OF ITS DATA USED IN CONNECTION WITH THIS SOFTWARE.
# IN NO EVENT WILL UHNDER BE LIABLE FOR ANY CONSEQUENTIAL DAMAGES WHATSOEVER, INCLUDING LOSS OF DATA OR USE, LOST
# PROFITS OR ANY INCIDENTAL OR SPECIAL DAMAGES, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
# SOFTWARE, WHETHER IN ACTION OF CONTRACT OR TORT, INCLUDING NEGLIGENCE. UHNDER FURTHER DISCLAIMS ANY LIABILITY
# WHATSOEVER FOR INFRINGEMENT OF ANY INTELLECTUAL PROPERTY RIGHTS OF ANY THIRD PARTY.
# -------------------------------------------------------------------------------------------------------------------
# END_SOFTWARE_LICENSE_NOTICE
# Work in progress
import jenkins
import email_util
import argparse
def main():
# TODO: parse arguments
parser = argparse.ArgumentParser(
description='This script polls for bad_commit.txt in various jobs, and create a one generic e-mail')
parser.add_argument('--workspace', type=str, default=None, help='workspace for the script')
parser.add_argument('--jenkins-ip', type=str, default=None, help='IP of jenkins')
args = parser.parse_args()
jenkins_ip = args.jenkins_ip
panic_view = jenkins.PanicMonitor(jenkins_ip)
panic_view.get_jenkins_server_uri()
panic_view.get_jobs_details()
# print(panic_view.job_names)
# print(panic_view.failed_jobs)
# print(panic_view.succeed_jobs)
email_util.send_email(panic_view.job_names, panic_view.job_url, panic_view.create_table())
print("Ends fine")
if __name__ == "__main__":
main()
<file_sep>/README.md
# UhQAMailer
Scripts to send email from QA infra
|
a0b3212ad3de90d18024bba6f17bf2fc96454720
|
[
"Markdown",
"Python"
] | 5 |
Python
|
vjuhnder/UhQAMailer
|
3ed6f26129e0142acb85a9730eb44d8e1d629678
|
45e67a0eab360f202b0102771426c4e1aae49833
|
refs/heads/master
|
<repo_name>yanjiangdi/Design-algorithms-to-solve-problems<file_sep>/成绩排序(需要使用到稳定排序).cpp
#include <iostream>
#include <algorithm>
using namespace std;
struct Student
{
string name;
int score ;
}s[10000] ;
bool cmp_0(Student s1,Student s2)
{
return s1.score>s2.score;
}
bool cmp_1(Student s1,Student s2)
{
return s1.score<s2.score;
}
int main()
{
int num,de;
while(cin>>num)
{
cin>>de;
for(int i=0;i<num;i++)
{
cin>>s[i].name>>s[i].score;
}
if(de==0)
{
stable_sort(s,s+num,cmp_0);
for(int i=0;i<num;i++)
{
cout<<s[i].name<<" "<<s[i].score<<endl;
}
}
else if(de==1)
{
stable_sort(s,s+num,cmp_1);
for(int i=0;i<num;i++)
{
cout<<s[i].name<<" "<<s[i].score<<endl;
}
}
}
return 0;
}
<file_sep>/哈夫曼树.cpp
#include <iostream>
#include <queue>
using namespace std;
struct cmp {
bool operator() (const int & a, const int & b) {
return a > b;
}
};
int main() {
//freopen("t.txt", "r", stdin);
int n;
while(cin>>n) {
priority_queue<int, vector<int>, cmp> pq;
for(int i = 0; i<n; i++) {
int t;
cin>>t;
pq.push(t);
}
int res = 0;
while(pq.size() > 1) {
int a = pq.top(); pq.pop();
int b = pq.top(); pq.pop();
int c = a + b;
res += c;
pq.push(c);
}
cout<<res<<endl;
}
return 0;
}
<file_sep>/首字母大写.cpp
#include <iostream>
using namespace std;
int main() {
string str;
while (getline(cin,str))
{
cout<<(char)toupper(str[0]);
for(int i=1;i<str.length();i++)
{
if(str[i]=='\t' ||str[i]=='\r' || str[i]==' ' || str[i]=='\n')
{
str[i+1]=(char)toupper(str[i+1]);
}
cout<<str[i];
}
cout<<endl;
}
return 0;
}<file_sep>/数组排序.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int num[n];
int num2[n];
for(int i=0;i<n;i++)
{
cin>>num[i];
num2[i]=num[i];
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(num2[j]>num2[j+1])
{
int temp=num2[j];
num2[j]=num2[j+1];
num2[j+1]=temp;
}
}
}
for(int i=0;i<n;i++)
{
int index=0,index1=0;
for(int j=0;j<n;j++)
{
index1=j;
if(num2[j]<num[i])
{
if(num2[j]==num2[j+1])
{
index++;
}
}
else
{
break;
}
}
if(i!=n-1)
{
cout<<index1+1-index<<" ";
}
else
{
cout<<index1+1-index<<endl;
}
}
}
return 0;
}
<file_sep>/互换最大数和最小数.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>20)
{
cin>>n;
}
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int max=0,index1=0,min=arr[0],index2=0;
for(int i=0;i<n;i++)
{
if(max<arr[i])
{
max=arr[i];
index1=i;
}
if(min>arr[i])
{
min=arr[i];
index2=i;
}
}
arr[index1]=min;
arr[index2]=max;
for(int i=0;i<n-1;i++)
{
cout<<arr[i]<<" ";
}
cout<<arr[n-1]<<endl;
}
return 0;
}
<file_sep>/输入n, 求y1=1!+3!+...m!(m是小于等于n的最大奇数) y2=2!+4!+...p!(p是小于等于n的最大偶数)。 .cpp
#include <iostream>
using namespace std;
int jc(int number);
void y(int number);
int main()
{
int number;
while(cin>>number)
{
y(number);
}
return 0;
}
int jc(int number)
{
if(number==1)
{
return 1;
}
if(number>1)
{
return number*jc(number-1);
}
return 0;
}
void y(int number)
{
int y1=0,y2=0;
if(number%2==0)
{
for(int i=1;i<=number-1;i+=2)
{
y1+=jc(i);
}
for(int i=2;i<=number;i+=2)
{
y2+=jc(i);
}
}
else
{
for(int i=1;i<=number;i+=2)
{
y1+=jc(i);
}
for(int i=2;i<=number-1;i+=2)
{
y2+=jc(i);
}
}
cout<<y1<<" "<<y2<<endl;
}
<file_sep>/矩阵最大值---把每行总和放入每行最大值的位置,如果有多个最大值,取下标值最小的那一个作为最大值。 最后将结果矩阵输出。 .java
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
int m=sc.nextInt();
int n=sc.nextInt();
int[][] max = new int[100][100];
while(m<1 || m>100 ||n<1 || n>100)
{
System.out.println("输入有误:请输入1-100之间的整数");
m=sc.nextInt();
n=sc.nextInt();
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
max[i][j]=sc.nextInt();
}
}
for(int i=0;i<m;i++)
{
int po=0,ls=0,ma=0;
for(int j=0;j<n;j++)
{
if(ma<max[i][j])
{
ma=max[i][j];
po=j;
}
ls+=max[i][j];
}
max[i][po]=ls;
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(j<n-1)
{
System.out.print(max[i][j]+" ");
}
else
{
System.out.print(max[i][j]);
}
}
System.out.println();
}
}
}
public static boolean isD(int [][] max,int number)
{
for(int i=0;i<number;i++)
{
for(int j=0;j<=i;j++)
{
if(max[i][j]!=max[j][i])
{
return false;
}
}
}
return true;
}
}<file_sep>/Digital Root.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext())
{
long num=scanner.nextInt();
if(num==0)
{
break;
}
else
{
if(num>=1 && num<=9)
{
System.out.println(num);
}
else
{
//int n_t=0;
while(num>9)
{
String n=num+"";
num=0;
for(int i=0;i<n.length();i++)
{
num+=Integer.parseInt(n.substring(i, i+1));
}
}
System.out.println(num);
}
}
}
}
}
<file_sep>/abc+bcc==532.cpp
#include <iostream>
using namespace std;
int main()
{
for(int i=1;i<=9;i++)
{
for(int j=1;j<=9;j++)
{
for(int k=0;k<=9;k++)
{
int abc=i*100+j*10+k;
int bcc=j*100+k*10+k;
if(abc+bcc==532)
{
cout<<i<<" "<<j<<" "<<k<<endl;
}
}
}
}
return 0;
}
<file_sep>/特殊的乘法.cpp
#include <iostream>
#include <sstream>
#include <string>
#include <stdlib.h>
using namespace std;
int main()
{
string a,b;
while(cin>>a>>b)
{
long long sum=0;
for(int i=0;i<a.length();i++)
{
string str;
stringstream stream;
stream << a[i];
str = stream.str();
int t=atoi(str.c_str());
for(int j=0;j<b.length();j++)
{
string str;
stringstream stream;
stream << b[j];
str = stream.str();
int t1=atoi(str.c_str());
sum+=t*t1;
}
}
cout<<sum<<endl;
}
return 0;
}
<file_sep>/字符串去特定字符.cpp
#include <iostream>
using namespace std;
int main()
{
string str;
string c;
while(cin>>str>>c)
{
string s="";
for(int i=0;i<str.length();i++)
{
if(str.substr(i,1)==c)
{
continue;
}
else
{
s+=str.substr(i,1);
}
}
cout<<s<<endl;
}
return 0;
}
<file_sep>/素数判定.cpp
#include <iostream>
using namespace std;
bool isS(int num)
{
for(int i=1;i<=num;i++)
{
if(num%i==0 && i!=1 && i!=num)
{
return false;
}
}
return true;
}
int main()
{
int num;
while(cin>>num)
{
if(num<=1)
{
cout<<"no"<<endl;
}
else
{
if(isS(num))
{
cout<<"yes"<<endl;
}
else
{
cout<<"no"<<endl;
}
}
}
return 0;
}
<file_sep>/查找数组中未出现的最小正整数.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findArrayMex(vector<int> A, int n) {
// write code here
sort(A.begin(),A.end());
int r=1;
for(int i=0;i<n;i++)
{
if(A[i]==r)
{
r++;
i=0;
}
}
return r;
}
int main()
{
int n;
while(cin>>n)
{
vector<int> v;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
v.push_back(t);
}
cout<<findArrayMex(v, n)<<endl;
}
return 0;
}
<file_sep>/鸡兔同笼问题求最多最少数.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int m;
for(int i=0;i<n;i++)
{
cin>>m;
if(m%2!=0)
{
cout<<0<<" "<<0<<endl;
}
else
{
if(m%4==0)
{
cout<<m/4<<" "<<m/2<<endl;
}
else
{
cout<<(m-2)/4+1<<" "<<m/2<<endl;
}
}
}
}
return 0;
}
<file_sep>/字符串的全排列(使用STL).cpp
#include <bits/stdc++.h>
using namespace std;
int main(){
for(string s;cin>>s;cout<<endl){
sort(s.begin(),s.end());
for(cout<<s<<endl;next_permutation(s.begin(),s.end());cout<<s<<endl);
}
return 0;
}
<file_sep>/查找学生信息.cpp
#include <iostream>
#include <cstring>
using namespace std;
struct Student
{
string sid;
string name;
string sex;
string age;
};
int main()
{
int n,m;
Student s[1000];
while(cin>>n)
{
for(int i=0;i<n;i++)
{
cin>>s[i].sid>>s[i].name>>s[i].sex>>s[i].age;
}
cin>>m;
for(int j=0;j<m;j++ )
{
string str;
cin>>str;
string ss="";
for(int i=0;i<n;i++)
{
if(s[i].sid==str)
{
ss=s[i].sid+" "+s[i].name+" "+s[i].sex+" "+s[i].age;
}
}
if(ss=="")
{
cout<<"No Answer!"<<endl;
}
else
{
cout<<ss<<endl;
}
}
}
return 0;
}
<file_sep>/字符串的反码.cpp
#include <iostream>
using namespace std;
void re(string str)
{
for(int i=0;i<str.length();i++)
{
if(str[i]>='a' &&str[i]<='z')
{
int d=str[i]-'a';
cout<<(char)('z'-d);
}
else if(str[i]>='A' &&str[i]<='Z')
{
int d=str[i]-'A';
cout<<(char)('Z'-d);
}
else
{
cout<<str[i];
}
}
cout<<endl;
}
int main()
{
string str;
while(cin>>str && str!="!")
{
while(str.length()>80 || str.length()<1)
{
cin>>str;
}
re(str);
}
return 0;
}
<file_sep>/排列(转换为二进制后求末尾0个数).cpp
#include<iostream>
using namespace std;
int main()
{
int m,n;
while(cin>>n>>m && n )
{
int sum=0;
for(int i=n;i>(n-m);--i)
{
int wei=0,t=i;
while(t!=0)
{
if(t%2!=0)
break;
++wei;
t/=2;
}
sum+=wei;
}
cout<<sum<<endl;
}
return 0;
}
<file_sep>/最大上升子序列和(yjd).cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int num[n];
int cMax[n];
for(int i=0;i<n;i++)
{
cin>>num[i];
}
int sum=num[0];
for(int i=0;i<n;i++)
{
cMax[i]=num[i];
for(int j=0;j<i;j++)
{
if(num[j]<num[i] && cMax[j]+num[i]>cMax[i])
{
cMax[i]=cMax[j]+num[i];
}
}
if(sum<cMax[i])
{
sum=cMax[i];
}
}
cout<<sum<<endl;
}
return 0;
}
<file_sep>/百万富翁问题.cpp
#include <iostream>
#include <cmath>
using namespace std;
int main()
{
int m=0;
int n=10*30;
for(int i=1;i<=30;i++)
{
m+=(int)pow(2,i-1);
}
cout<<n<<" "<<m<<endl;
return 0;
}
<file_sep>/统计同成绩学生人数.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main(){
int n;
while(cin>>n && n){
int sc;
while(n>1000)
{
cin>>n;
}
int s[n];
for(int i=0;i<n;i++)
{
cin>>s[i];
}
cin>>sc;
int count=0;
for(int i=0;i<n;i++)
{
if(s[i]==sc)
{
count++;
}
}
cout<<count<<endl;
}
return 0;
}
<file_sep>/小白鼠排队.cpp
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
struct xbs
{
int weight;
string color;
};
bool cmp(xbs b1,xbs b2)
{
return b1.weight>b2.weight;
}
int main()
{
int n;
while (cin>>n)
{
xbs b[100]={0};
for(int i=0;i<n;i++)
{
cin>>b[i].weight>>b[i].color;
}
sort(b,b+n,cmp);
for(int i=0;i<n;i++)
{
cout<<b[i].color<<endl;
}
}
return 0;
}
<file_sep>/最短排序.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int findShortest(vector<int> A, int n) {
// write code here
int t[n],res = 0;
for(int i = 0; i < n; ++i) t[i] = A[i];
sort(A.begin(),A.end());
int Left = -1,Right = -1 ;
for(int i = n - 1; i >= 0; --i){
if(t[i] != A[i]){
Right = i;
break;
}
}
for(int i = 0; i < n;++i){
if(t[i] != A[i]){
Left = i;
break;
}
}
if(Left == Right && Left == -1) return 0;
else return Right - Left + 1;
}
int main()
{
int n;
while(cin>>n)
{
vector<int> A;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
A.push_back(t);
}
cout<<findShortest(A,n)<<endl;
}
return 0;
}
<file_sep>/毕业bg.cpp
#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;
struct node
{
int d,l,e;
}bg[31];
bool com(node a,node b)
{
return a.e<b.e;
}
int main()
{
int n;
while(cin>>n && n>=0)
{
int mmax,i,j;
int ans[60];
mmax=0;
memset(ans,0,sizeof(ans));
for(i=1;i<=n;i++)
{
cin>>bg[i].d>>bg[i].l>>bg[i].e;
}
sort(bg+1,bg+1+n,com);
mmax=bg[n].e;
for(i=1;i<=n;i++)
{
for(j=mmax;j>=bg[i].l;j--)
if(ans[j]<(ans[j-bg[i].l]+bg[i].d))
ans[j]=(ans[j-bg[i].l])+bg[i].d;
for(j=bg[i].e+1;j<=mmax;j++)
ans[j]=ans[bg[i].e];
}
cout<<ans[mmax]<<endl;
}
return 0;
}
<file_sep>/构造MAXTree.cpp
#include <iostream>
#include <vector>
#include <stack>
using namespace std;
class MaxTree {
public:
vector<int> buildMaxTree(vector<int> A, int n) {
// write code here
stack<int> s; //用栈存储数组下标,栈内顺序保证自栈顶向下递增
vector<int> result(n, -1);
s.push(0);
for(int i = 1; i < n; ++i)
{
//当前元素小于栈顶对应元素则入栈(递增顺序)
//大于则出栈并与之后的栈顶比较,此时找到了左右首个大于当前元素的位置
if(A[i] < A[s.top()])
s.push(i);
else
{
int index = s.top(); //记录确定父节点的子节点下标
s.pop();
if(s.empty()) //栈空则左边无大值,当前位置即父节点
{
result[index] = i;
s.push(i); //当前位置入栈,后续寻找其父节点
}
else //不空则比较左右
{
if(A[i] < A[s.top()]) //右小于左则右是父节点,右入栈
{
result[index] = i;
s.push(i);
}
else //左小于右则左是父节点,再寻找左的父节点,i自减,当前节点继续与左(栈顶)比较
{
result[index] = s.top();
--i;
}
}
}
}
//栈中剩余元素递增,下面是上面的父节点
while(!s.empty())
{
int index = s.top();
s.pop();
if(s.empty()) //最大的,找到根节点
result[index] = -1;
else
result[index] = s.top();
}
return result;
}
};
<file_sep>/A-Z字母统计.cpp
#include <iostream>
using namespace std;
struct word{
char c;
int count=0;
};
int main()
{
word w[26];
for(int i=0;i<26;i++)
{
w[i].c=65+i;
}
string str;
while(cin>>str)
{
for(int i=0;i<26;i++)
{
for(int j=0;j<str.length();j++)
{
if(str[j]==w[i].c)
{
w[i].count++;
}
}
}
for(int i=0;i<26;i++)
{
cout<<w[i].c<<":"<<w[i].count<<endl;
w[i].count=0;
}
}
return 0;
}
<file_sep>/火星A+B.cpp
#include <stdio.h>
#include <string.h>
int pivot[26] = {
2,3,5,7,11,
13,17,19,23,29,
31,37,41,43,47,
53,59,61,67,71,
73,79,83,89,97,
};
int str2num(char* str, int* array)
{
char *p = NULL, *q = NULL;
char tmp[5];
int k = 0;
for (p = str, q = tmp; *p != '\0'; ++p)
{
if (*p == ',')
{
*q = '\0';
q = tmp;
sscanf(tmp, "%d", &array[k++]);
continue;
}
else
*q++ = *p;
}
*q = '\0';
sscanf(tmp, "%d", &array[k++]);
return k;
}
void printSum(int *a, int m, int * b, int n)
{
int sum[26] = {0};
int k = m > n ? m : n;
m--; n--; k--;
int flag = 0, i = 0, j = k;
while (m >= 0 && n >= 0)
{
flag += a[m--] + b[n--];
sum[j--] = flag % pivot[i];
flag /= pivot[i++];
}
while (m >= 0)
{
flag += a[m--];
sum[j--] = flag % pivot[i];
flag /= pivot[i++];
}
while (n >= 0)
{
flag += b[n--];
sum[j--] = flag % pivot[i];
flag /= pivot[i++];
}
if (flag)
{
printf("%d,", flag);
}
for (i = 0; i < k; ++i)
{
printf("%d,", sum[i]);
}
printf("%d\n", sum[k]);
}
void printArray(int* a, int n)
{
int i = 0;
for (i = 0; i < n; i++)
{
printf("%d ", a[i]);
}
printf("\n");
}
int main(void)
{
int a[26], b[26];
int m, n;
char str1[53], str2[53];
while (1)
{
scanf("%s%s", str1, str2);
m = str2num(str1, a);
n = str2num(str2, b);
if (strcmp(str1, "0") == 0 && strcmp(str2, "0") == 0)
break;
printSum(a, m, b, n);
}
return 0;
}
<file_sep>/建立链表--升序链表---.遍历输出链表.cpp
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
typedef struct LNode{
int data;
struct LNode* next;
}LNode;
/* 尾插法创建 带头节点单链表 */
LNode * CreateList(LNode *L,int n){
int x;
L=(LNode*)malloc(sizeof(LNode)); //建立头结点
LNode *s,*r=L; //r为表尾指针
for(int i=0;i<n;i++){
scanf("%d",&x);
s = (LNode*)malloc(sizeof(LNode));
s->data = x;
r->next = s;
r = s; // r 指向新的表尾节点
}
r->next=NULL; //千万不要忘了,最后把尾指针指向NULL
return L;
}
/* 将单链表按升序重排 */
LNode* InSort(LNode *L){
LNode *p = L->next;
LNode *pre = NULL;
LNode *r = p->next; //r保持p的后继节点指针,以保证不断链
p->next = NULL; //构造只含一个数据的有序表
p = r;
while(p!=NULL){
r = p->next; //保持p的后继节点指针
pre = L;
while(pre->next!=NULL && pre->next->data < p->data){
pre = pre->next; //在有序表中查找插入 *p 的前驱节点 *pre
}
p->next = pre->next; //将 *p 头插法插入 *pre之后
pre->next = p;
p = r; //扫描原单链表中剩下的结点
}
return L;
}
/* 打印单链表 */
void Print(LNode *L){
LNode *p = L->next;
while(p->next != NULL){
printf("%d ",p->data);
p = p->next;
}
printf("%d",p->data);
}
int main(){
int n;
LNode *L=NULL;
while(scanf("%d",&n) != EOF){
L = CreateList(L,n);
L = InSort(L);
Print(L);
printf("\n");
}
return 0;
}
<file_sep>/矩阵最大值---把每行总和放入每行最大值的位置,如果有多个最大值,取下标值最小的那一个作为最大值。 最后将结果矩阵输出。 .cpp
#include <iostream>
using namespace std;
int main()
{
int m,n;
int max[100][100];
while(cin>>m>>n)
{
while(m<1 || n<1 || m>100 || n>100)
{
cin>>m>>n;
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
cin>>max[i][j];
}
}
for(int i=0;i<m;i++)
{
int lmax=0,po=0,lineSum=0;
for(int j=0;j<n;j++)
{
lineSum+=max[i][j];
if(lmax<max[i][j])
{
po=j;
lmax=max[i][j];
}
}
max[i][po]=lineSum;
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(j<n-1)
{
cout<<max[i][j]<<" ";
}
else
{
cout<<max[i][j];
}
}
cout<<endl;
}
}
}
<file_sep>/A+B(找末尾相同位数).cpp
#include <iostream>
using namespace std;
int main()
{
int A,B,k;
while(cin>>A>>B>>k &&A && B)
{
int sum=A+B;
if(A%10!=B%10)
{
cout<<sum<<endl;
}
else
{
int count=1;
A/=10;
B/=10;
while(A%10==B%10)
{
count++;
A/=10;
B/=10;
}
if(count==k)
{
cout<<-1<<endl;
}
else
{
cout<<sum<<endl;
}
}
}
return 0;
}
<file_sep>/字符串的内排序.cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(char a,char b)
{
return ((int)(a))<((int)(b));
}
int main()
{
string str;
while(cin>>str)
{
char ch[str.length()];
strcpy(ch, str.c_str());
sort(ch,ch+str.length(),cmp);
cout<<ch;
cout<<endl;
}
return 0;
}
<file_sep>/求解数组中的最大素数.cpp
#include<iostream>
using namespace std;
bool isS(int n)
{
int count=0;
for(int i=1;i<=n;i++)
{
if(n%i==0)
{
count++;
}
}
if(count==2)
{
return true;
}
return false;
}
int max_s(int n[],int num)
{
int max=0;
for(int i=0;i<num;i++)
{
if(isS(n[i]))
{
if(max<n[i])
{
max=n[i];
}
}
}
return max;
}
int main(){
int n;
cout<<"请输入数组个数:";
cin>>n;
int a[n];
cout<<"请输入"<<n<<"个数组元素:";
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cout<<"数组中的最大素数:"<<max_s(a,n)<<endl;
return 0;
}
<file_sep>/杨辉三角(递归).java
import java.util.Scanner;
?
public class Main{
????public static void main(String[] args){
????????Scanner input = new Scanner(System.in);
????????while(input.hasNext()){
????????????int n=input.nextInt();
????????????find2(n);?????
????????}
????????input.close();
????}
?????
????public static int find(int n,int i)
????{
????????if(i==0)
????????????return 0;
????????if(i==n+1)
????????????return 0;
????????if(n==1)
????????????return 1;
????????int t = find(n-1,i-1)+find(n-1,i);
????????return t;
????}
?????
????public static void find2(int n)
????{
????????for(int j=2;j<=n;j++)
????????{
????????????for(int i=1;i<j;i++)
????????????{
????????????????System.out.print(find(j,i)+" ");
????????????}
????????????System.out.println(find(j,j));
????????}
????}
}<file_sep>/求平均分(小数点后两位).cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>100)
{
cin>>n;
}
double sum=0;
for(int i=0;i<n;i++)
{
int score;
cin>>score;
sum+=score;
}
cout<<setprecision(2)<<fixed<<sum/n<<endl;
}
return 0;
}
<file_sep>/根据前序和中序遍历构建二叉树.cpp
#include <iostream>
#include <vector>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class tree{
public:
TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
size_t size1 = pre.size();
int size2 = vin.size();
if(size1 == 0 && size2 == 0) return NULL;
if(size1 > size2 || size1 < size2) return NULL;
vector<int> pre_left,pre_right,vin_left,vin_right;
TreeNode* root = new TreeNode(pre[0]);
int pos = 0;
for(int i = 0;i < size2;i++)
{
if(vin[i] == pre[0])
{
pos = i;
break;
}
}
for(int i = 0;i < pos;i++)
{
pre_left.push_back(pre[i+1]);
vin_left.push_back(vin[i]);
}
for(int i = pos + 1;i < size2;i++)
{
pre_right.push_back(pre[i]);
vin_right.push_back(vin[i]);
}
root->left = reConstructBinaryTree(pre_left,vin_left);
root->right = reConstructBinaryTree(pre_right,vin_right);
return root;
}
};
int main()
{
return 0;
}
<file_sep>/二叉树的序列化.cpp
#include <iostream>
#include <cstring>
using namespace std;
struct TreeNode {
int val;
struct TreeNode *left;
struct TreeNode *right;
};
string toSequence(TreeNode* root) {
// write code here
TreeNode*p=new TreeNode;
p=root;
string str;
if(root!=NULL)
{
str+="(";
str+=toSequence(root->left);
str+=toSequence(root->right);
str+=")";
}
else
str="";
delete p;
return str;
}
<file_sep>/A+B(用字母代替数字).java
import java.math.BigInteger;
import java.util.Scanner;
enum num{zero,one,two,three,four,five,six,seven,eight,line};
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(input.hasNext()){
String str=input.nextLine();
String[] stru=str.split("\\=");
String strup=stru[0];
String[] strN=strup.split("\\+");
int sum=0;
for(int i=0;i<strN.length;i++)
{
String [] s=strN[i].split(" ");
int t1=0;
for(int j=0;j<s.length;j++)
{
if(s[j]=="=")
{
continue;
}
else
{
int t2 = 0;
//System.out.println(s[j]);
switch(s[j])
{
case "zero":
t2=0;
break;
case "one":
t2=1;
break;
case "two":
t2=2;
break;
case "three":
t2=3;
break;
case "four":
t2=4;
break;
case "five":
t2=5;
break;
case "six":
t2=6;
break;
case "seven":
t2=7;
break;
case "eight":
t2=8;
break;
case "nine":
t2=9;
break;
}
t1+=(int)t2*Math.pow(10, s.length-1-j);
}
}
sum+=t1;
}
if(sum==0)
{
break;
}else
{
System.out.println(sum);
}
}
}
}
<file_sep>/A+B(找全0行和全0列个数).cpp
#include <iostream>
using namespace std;
int main()
{
int n,m;
while(cin>>n && n)
{
cin>>m;
while(n<1 || n>10 || m<1 || m>10)
{
cin>>n>>m;
}
int A[n][m];
int B[n][m];
int sum[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>A[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>B[i][j];
sum[i][j]=A[i][j]+B[i][j];
}
}
int s=0,in1=0,in2=0;
for(int i=0;i<n;i++)
{
int index=0;
for(int j=0;j<m;j++)
{
if(sum[i][j]!=0)
{
break;
}
else
{
index++;
}
}
if(index==m)
{
in1++;
}
}
for(int i=0;i<m;i++)
{
int index=0;
for(int j=0;j<n;j++)
{
if(sum[j][i]!=0)
{
break;
}else
{
index++;
}
}
if(index==n)
{
in2++;
}
}
s=in1+in2;
cout<<s<<endl;
}
return 0;
}
<file_sep>/Old Bill.cpp
#include<iostream>
using namespace std;
int main()
{
int num;
while(cin>>num)
{
int x,y,z;
bool isFind=false;
cin>>x>>y>>z;
int mid=x*1000+y*100+z*10;
for(int i=9;i>0;--i)
{
for(int j=9;j>=0;--j)
{
int temp=i*10000+mid+j;
if(temp % num==0)
{
isFind=true;
cout<<i<<' '<<j<<' '<<temp/num<<endl;
break;
}
}
if(isFind)
break;
}
if(!isFind)
cout<<0<<endl;
}
return 0;
}
<file_sep>/字符串排序.cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct stru
{
string data;
int length;
};
bool cmp(stru s1,stru s2)
{
return s1.length<s2.length;
}
int main()
{
int n;
while(cin>>n)
{
getchar();
stru *strs=new stru[n];
int count=0;
for(int i=0;i<n;i++)
{
string str_in;
getline(cin,str_in);
if(str_in=="stop")
{
break;
}
else
{
strs[i].data=str_in;
strs[i].length=str_in.length();
count++;
}
}
sort(strs,strs+count,cmp);
for(int i=0;i<count;i++)
{
cout<<strs[i].data<<endl;
}
}
return 0;
}
<file_sep>/小于数字a的和.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
int num[5];
while(cin>>n>>num[0]>>num[1]>>num[2]>>num[3]>>num[4])
{
int sum=0;
for(int i=0;i<5;i++)
{
if(num[i]<n)
{
sum+=num[i];
}
}
cout<<sum<<endl;
}
return 0;
}
<file_sep>/最短路径.cpp
#include <iostream>
#include <vector>
using namespace std;
int root[100]={-1};
int dis[100][100]={-1};
int findRoot(int a) {
if (root[a]==-1) return a;
else return root[a]=findRoot(root[a]);
}
void join(int a,int b) {
int rootA=findRoot(a), rootB=findRoot(b);
if (rootA==rootB) return;
root[rootA]=rootB;
}
int pow(int base,int k) {
int ans=1;
while (k--) ans=ans*base%100000;
return ans;
}
int main(int argc, const char * argv[]) {
int n,m,a,b;
cin>>n>>m;
fill(root, root+m, -1);
for (int i=0; i<n; ++i) {
fill(dis[i], dis[i]+n, -1);
dis[i][i]=0;
}
for (int i=0; i<m; ++i) {
cin>>a>>b;
int A=findRoot(a),B=findRoot(b);
if (A==B) continue;
int currentDis=pow(2, i);
for (int i=0; i<n; ++i) {
if (A!=findRoot(i)) continue;
for (int j=0; j<n; ++j) {
if (B!=findRoot(j)) continue;
dis[i][j]=dis[j][i]=(dis[i][a]+dis[b][j]+currentDis)%100000;
}
}
join(a, b);
}
int finalRoot=findRoot(0);
for (int i=1;i<n;++i) {
if (findRoot(i)!=finalRoot) cout<<-1<<endl;
else cout<<dis[0][i]<<endl;
}
}
<file_sep>/密码翻译.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
getchar();
for(int i=0;i<n;i++)
{
string str;
getline(cin,str);
for(int i=0;i<str.length();i++)
{
if(str[i]=='z')
{
str[i]='a';
}
else if(str[i]=='Z')
{
str[i]='A';
}
else if((str[i]>='a' && str[i]<='y') || (str[i]>='A' && str[i]<='Y'))
{
str[i]=str[i]+1;
}
cout<<str[i];
}
cout<<endl;
}
}
return 0;
}
<file_sep>/HelloWorld For U.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
while(str.length()<5)
{
cin>>str;
}
//if(str.length()%2==0)
// {
for(int i=0;i<(str.length()+2)/3-1;i++)
{
//cout<<i<<endl;
cout<<str.substr(i,1);
for(int j=0;j<str.length()-((str.length()+2)/3-1)*2-2;j++)
{
cout<<" ";
}
cout<<str.substr(str.length()-1-i,1)<<endl;
}
cout<<str.substr((str.length()+2)/3-1,str.length()-((str.length()+2)/3-1)*2)<<endl;
//}
}
return 0;
}
<file_sep>/A+B(转成m进制数).cpp
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
void toN(long long m,long long num)
{
if(num==0) cout << 0<<endl;
else
{
string str="";
while(num!=0)
{
stringstream ss;
ss<<(num%m);
str=ss.str()+str;
num/=m;
}
cout<<str<<endl;
}
}
int main(){
long long m,A,B;
while(cin>>m && m)
{
cin>>A>>B;
long long sum=A+B;
toN(m,sum);
}
return 0;
}
<file_sep>/无向图的连通图(示例).cpp
#include <stdio.h>
#define N 1000
int Tree[N];
int findRoot(int x)
{
if (Tree[x] == -1) return x;
else
{
int res = findRoot(Tree[x]);
Tree[x] = res;
return res;
}
}
int main ()
{
int n, m;
while (scanf("%d %d", &n, &m) != EOF)
{
if (!n) break;
for (int i = 1; i <= n; i++)https://www.nowcoder.com/ta/jlu-kaoyan/question-ranking?tpId=65&tqId=29622&uuid=569e89823a5141fe8a11ab7d4da21edf&rp=6
{
Tree[i] = -1;
}
while (m-- != 0)
{
int a, b;
scanf("%d %d", &a, &b);
a = findRoot(a);
b = findRoot(b);
if (a != b) Tree[a] = b;
}
int ans = 0;
for (int i = 1; i <= n; i++)
{
if (Tree[i] == -1)
{
ans++;
}
}
if (ans == 1)
{
printf("YES\n");
}
else
printf("NO\n");
}
}<file_sep>/奇偶校验-输入一个字符串,然后对每个字符进行奇校验,最后输出校验后的二进制数(如'3’,输出:10110011)。 .java
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String str=sc.next();
while(str.length()<1 || str.length()>1000)
{
System.out.println("输入有误:请输入1-1000长度的字符串");
str=sc.next();
}
char[] ch=str.toCharArray();
for(char cha:ch)
{
String str2=Integer.toBinaryString((int)(cha));
int count=0;
for(int i=0;i<str2.length();i++)
{
if(str2.substring(i,i+1).equals("1"))
{
count++;
}
}
if(count%2==0)
{
if(str2.length()<8)
{
System.out.print("1");
for(int i=0;i<8-str2.length()-1;i++)
{
System.out.print("0");
}
System.out.println(str2);
}
}
else
{
if(str2.length()<8)
{
for(int i=0;i<8-str2.length();i++)
{
System.out.print("0");
}
System.out.println(str2);
}
}
}
}
}
}<file_sep>/堆栈的使用.cpp
#include <iostream>
#include <string>
#include <stack>
#include <sstream>
#include <stdlib.h>
using namespace std;
int main()
{
int n;
while(cin>>n && n)
{
stack<double> s;
for(int i=0;i<n;i++)
{
string str1="";
cin>>str1;
if(str1=="P")
{
string str2;
cin>>str2;
double num=(double)atoi(str2.c_str());
s.push(num);
}
else if(str1=="A")
{
if(s.empty())
{
cout<<"E"<<endl;
}
else
{
double nu=s.top();
cout<<nu<<endl;
}
}
else if(str1=="O")
{
if(!s.empty())
{
s.pop();
}
}
if(i==n-1)
{
cout<<endl;
}
}
}
return 0;
}
<file_sep>/位操作练习(示例).cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int a,b;
cin>>a>>b;
int n=1;
int temp=0;
for(int j = 0;j < 16;j ++)
{
temp = ((a << j) | (a >> (16 - j))) & 65535;
if(temp == b)
{
cout<<"YES"<<endl;
break;
}
else if(j==15 && temp!=b)
{
cout<<"NO"<<endl;
}
}
}
}
return 0;
}
<file_sep>/Coincidence.cpp
#include <iostream>
#include <stdio.h>
#include <string.h>
int d[101][101];
using namespace std;
int main(int argc, const char * argv[]) {
char s1[101];
char s2[101];
while(scanf("%s\n%s",s1,s2)!=EOF)
{
long int l1=strlen(s1);
long int l2=strlen(s2);
int i,j;
for(i=0;i<=l1;i++)
d[i][0]=0;
for(i=0;i<=l2;i++)
d[0][i]=0;
for(i=1;i<=l1;i++)
{
for(j=1;j<=l2;j++)
{
if(s1[i-1]==s2[j-1])
d[i][j]=d[i-1][j-1]+1;
else
d[i][j]=max(d[i-1][j],d[i][j-1]);
}
}
cout<<d[l1][l2]<<endl;
}
return 0;
}
<file_sep>/最大公约数.cpp
#include <iostream>
using namespace std;
int main()
{
int m,n;
while(cin>>m>>n)
{
if(m>n)
{
for(int i=n;i>=1;i--)
{
if(m%i==0 && n%i==0)
{
cout<<i<<endl;
break;
}
}
}
else
{
for(int i=m;i>=1;i--)
{
if(m%i==0 && n%i==0)
{
cout<<i<<endl;
break;
}
}
}
}
return 0;
}<file_sep>/合并字符串.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str1,str2;
while(cin>>str1>>str2)
{
while(str1.length()!=str2.length())
{
cin>>str1>>str2;
}
string strS="";
for(int i=0;i<str1.length();i++)
{
strS=strS+str1[i]+str2[str1.length()-i-1];
}
cout<<strS<<endl;
}
return 0;
}
<file_sep>/MBank.cpp
#include <iostream>
using namespace std;
int main()
{
string f,t;
int m;
char type;
double sum=0;
while(cin>>f)
{
if(f=="0")
{
cout<<(int)(sum+0.5)<<endl;
sum=0;
}
else if(f=="#")
{
break;
}
else
{
cin>>t>>m>>type;
if(type=='F')
{
sum+=2*m;
}
else if(type=='B')
{
sum+=1.5*m;
}
else if(type=='Y')
{
if(m>=1 && m<=500)
{
sum+=500;
}
else
{
sum+=m;
}
}
}
}
return 0;
}
<file_sep>/位操作练习(yjd).cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int a,b;
cin>>a>>b;
int n=1;
int temp=a;
while(temp<b)
{
temp=((a<<n) | (a >> (16 - n)) ) & 65535;
n++;
}
if(temp==b)
{
cout<<"YES"<<endl;
}
else
{
cout<<"NO"<<endl;
}
}
}
return 0;
}
<file_sep>/二叉排序树.cpp
#include<iostream>
#include<stdlib.h>
using namespace std;
//-----------二叉树的存储结构-----------
typedef struct BiTNode{
int data;
struct BiTNode *lchild,*rchild;
}* BiTree;
//-------------基本操作--------
bool LT(int a,int b) {
if(a<b)
{
return true;
}
else{
return false;
}
}
/*
//查找二叉树中是否存在一个值和data相等,相等则返回true,否则返回false
在根指针root所指向的二叉排序树中递归地查找其关键字等于data的数据元素,
若查找成功,则指针p指向该数据元素结点,并返回true,
否则指针p指向查找路径上访问的最后一个结点并返回false指针,指针f指向root的双亲,其初始调用值NULL
*/
int SearchBST(BiTree root,int data,BiTree f,BiTree &p);
//inline void InsertBST(BiTree &root,int data)
//root为传引用指针
void InsertBST(BiTree &root,int data)
{
BiTree p,s;
if(-1==SearchBST(root,data,NULL,p)) //查找不成功
{
s=(struct BiTNode *)malloc(sizeof(BiTNode));
s->data=data;
s->lchild=s->rchild=NULL;
if(p==NULL) //二叉排序树为空的时候,被插入结点*s为新的根结点
root=s;
else if(LT(data,p->data)) //被插结点*s为左孩子
p->lchild=s;
else //被插结点*s为右孩子
p->rchild=s;
}
return ;
}
//--------------------三种遍历方法
void PreOrderTraverse(BiTree root){
if(root){
printf("%d ",root->data);
PreOrderTraverse(root->lchild);
PreOrderTraverse(root->rchild);
}
}
void InOrderTraverse(BiTree root) //中序遍历
{
if(root)
{
InOrderTraverse(root->lchild);
printf("%d ",root->data);
InOrderTraverse(root->rchild);
}
}
void PostOrderTraverse(BiTree root){
if(root){
PostOrderTraverse(root->lchild);
PostOrderTraverse(root->rchild);
printf("%d ",root->data);
}
}
int main()
{
BiTree T;
int num[101];
int n;
while(scanf("%d",&n)!=EOF){
int i;
T=NULL;
//-------------循环构造二叉树------------
for(i=1;i<=n;++i) {
scanf("%d",&num[i]);
InsertBST(T,num[i]);
}
//printf("\n");
PreOrderTraverse(T);
printf("\n");
InOrderTraverse(T);
printf("\n");
PostOrderTraverse(T);
printf("\n");
}
return 0;
}
int SearchBST(BiTree root,int data,BiTree f,BiTree &p)
{
if(!root){ //如果树为空 ,则指向f
p=f;
return -1;
}
else if(data==root->data) { //树不空
p=root;
return 1;
}
else if(data<root->data)
return SearchBST(root->lchild,data,root,p);
else if(data>root->data){
return SearchBST(root->rchild,data,root,p);
}
return 0;
}
<file_sep>/数组的单调和.cpp
#include <iostream>
#include <vector>
#include <cstring>
using namespace std;
int calcMonoSum(vector<int> A, int n) {
// write code here
int sum=0;
for(int i=1;i<n;i++)
{
int s=0;
for(int j=0;j<i;j++)
{
if(A[j]<=A[i])
{
s+=A[j];
}
}
sum+=s;
}
return sum;
}
int main()
{
int n;
string s;
while(cin>>n)
{
vector<int> v;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
v.push_back(t);
}
cout<<calcMonoSum(v,n)<<endl;
}
return 0;
}
<file_sep>/单词替换(yjd).cpp
#include <iostream>
using namespace std;
int main() {
string str;
while(getline(cin,str))
{
string r1,r2;
cin>>r1>>r2;
while(str.find(r1)!=str.npos)
{
str= str.replace(str.find(r1), r1.length(), r2);
}
cout<<str<<endl;
}
return 0;
}<file_sep>/Fill or Not Fill.cpp
#include<stdio.h>
#include<math.h>
#include<algorithm>
using namespace std;
struct node{
double p;
double dis;
}sta[510];
bool cmp(const node a,const node b)
{
return a.dis<b.dis;
}
int main()
{
int cmax,d,davg,n,i,j,k;
double tmp,ans,mdis,rest;
while(~scanf("%d%d%d%d",&cmax,&d,&davg,&n))
{
for(i=0;i<n;i++)
scanf("%lf%lf",&sta[i].p,&sta[i].dis);
sta[n].dis=d;
sta[n].p=9999999;
sort(sta,sta+n,cmp);
if(sta[0].dis>0)
printf("The maximum travel distance = 0.00\n");
else{
ans=rest=0;
mdis=cmax*davg;
for(i=0;i<n;i++)
{
k=i+1;
if(i!=0)
rest-=(double)(sta[i].dis-sta[i-1].dis)/davg;
for(;k<n&&sta[k].p>=sta[i].p;k++);
if(sta[k].dis-sta[i].dis>mdis)
{
ans+=(cmax-rest)*sta[i].p;
rest=cmax;
}
else
{
tmp=(double)(sta[k].dis-sta[i].dis)/davg-rest;
if(tmp>0&&fabs(tmp)>1e-5)
{
ans+=tmp*sta[i].p;
rest=(double)(sta[k].dis-sta[i].dis)/davg;
}
}
if(sta[i+1].dis-sta[i].dis>mdis)
{
printf("The maximum travel distance = %.2f\n",sta[i].dis+mdis);
break;
}
}
if(i==n)
printf("%.2f\n",ans);
}
}
return 0;
}
<file_sep>/二叉搜索树.cpp
#include<stdio.h>
#include<string.h>
struct node{
node* lchild;
node* rchild;
int c;
}Tree[15];
int loc;
node* creat(){
Tree[loc].lchild=Tree[loc].rchild=NULL;
return &Tree[loc++];
}
node* insert(node* T,int x){
if(T==NULL){
T=creat();
T->c=x;
return T;
}
else if(x<T->c){
T->lchild=insert(T->lchild,x);
}
else if(x>T->c){
T->rchild=insert(T->rchild,x);
}
return T;
}
int len;
void preorder(node* T,int seq[]){
seq[len++]=T->c;
if(T->lchild!=NULL)
preorder(T->lchild,seq);
if(T->rchild!=NULL)
preorder(T->rchild,seq);
}
int main(){
int n;
char str[12];
while(scanf("%d",&n)!=EOF&&n!=0){
node* T=NULL;
scanf("%s",str);
int Len=strlen(str);
loc=0;
for(int i=0;i<Len;i++){
int x=str[i]-'0';
T=insert(T,x);
}
int seq[12];
len=0;
preorder(T,seq);
while(n--){
scanf("%s",str);
T=NULL;
loc=0;
for(int j=0;j<Len;j++){
int x=str[j]-'0';
T=insert(T,x);
}
int seqn[12];
len=0;
preorder(T,seqn);
int k;
for(k=0;k<Len;k++){
if(seq[k]!=seqn[k])
break;
}
if(k==Len)
printf("YES\n");
else
printf("NO\n");
}
}
return 0;
}
<file_sep>/第几周.cpp
#include <iostream>
using namespace std;
int jt(int year,int month,int day)
{
int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int sum=0;
if((year%4==0 && year%100!=0 ) || year%400==0)
{
days[1]=29;
}
else
{
days[1]=28;
}
for(int i=0;i<month-1;i++)
{
sum+=days[i];
}
sum=sum+day;
return sum;
}
int main()
{
int day, year, m;
string month;
while(cin>>day>>month>>year)
{
if(month=="January") m=1;
else if(month=="February") m=2;
else if(month=="March") m=3;
else if(month=="April") m=4;
else if(month=="May") m=5;
else if(month=="June") m=6;
else if(month=="July") m=7;
else if(month=="August") m=8;
else if(month=="September") m=9;
else if(month=="October") m=10;
else if(month=="November") m=11;
else if(month=="December") m=12;
int sum_day=jt(year,m,day);
int da=sum_day;
for(int i=1;i<year;i++)
{
if((i%4==0 && i%100!=0 ) || i%400==0)
{
da+=366;
}
else
{
da+=365;
}
}
int d=da%7;
string week;
switch(d)
{
case 0:
week="Sunday";
break;
case 1:
week="Monday";
break;
case 2:
week="Tuesday";
break;
case 3:
week="Wednesday";
break;
case 4:
week="Thursday";
break;
case 5:
week="Friday";
break;
case 6:
week="Saturday";
break;
default:
week="";
break;
}
cout<<week<<endl;
}
return 0;
}
<file_sep>/sortK.cpp
#include<iostream>
#include <algorithm>
#include<string.h>
using namespace std;
const int N=5;
struct Book {
string isbn;
string name;
double price;
int stock;
};
bool cmp(Book b1,Book b2)
{
return b1.stock>b2.stock;
}
void display(Book bk[],int len);
int main(){
Book book1[N]={ {"23924-1","计算机导论",26.5,120},
{"13956-3","高等数学",31,195},
{"87623-8","线性代数",28,267},
{"56721-2","普通物理",42,102},
{"34781-9","数据结构",22.5,298}
};
sort(book1,book1+N,cmp);
display(book1,N);
return 0;
}
void display(Book bk[],int len){
cout<<"书号\t书名\t\t单价\t库存量"<<endl;
for(int i=0;i<len;++i){
cout<<bk[i].isbn<<"\t"<<bk[i].name<<"\t";
cout<<bk[i].price<<"\t"<<bk[i].stock<<endl;
}
}<file_sep>/Carray Operations.cpp
#include <iostream>
#include <cstdio>
using namespace std;
int main(){
int m, n, carry, ans;
while (cin>>m>>n && m && n){
ans = carry = 0;
while (m || n || carry){
carry = (carry+m%10+n%10)/10;
if (carry) ans++;
m/=10, n/=10;
}
if (!ans) cout<<"NO carry operation."<<endl;
else if (ans==1) cout<<ans<<" carry operation."<<endl;
else cout<<ans<<" carry operations."<<endl;
}
return 0;
}
<file_sep>/二叉树.cpp
#include<iostream>
using namespace std;
int main() {
int n, m, base, res, b, e;
while (cin >> m >> n) {
if (n == 0 & m == 0)break;
base = 1;
b = e = m;
res = 1;
while (n > 2 * e + 1) {
e = 2 * e + 1;
b = 2 * b;
base *= 2;
res += base;
m = 2 * m + 1;
}
if (n >= 2*b) {
res += n - 2*b + 1;
}
cout << res << endl;
}
}
<file_sep>/字符串的旋转.cpp
#include <iostream>
#include <cstring>
using namespace std;
string rotateString(string A, int n, int p)
{
// write code here
return A.substr(p+1,n-p-1)+A.substr(0,p+1);
}
int main()
{
string str;
int n,p;
while( cin>>str>>n>>p)
{
cout<<rotateString(str, n, p)<<endl;
}
return 0;
}
<file_sep>/寻找直系亲属.cpp
#include <iostream>
#include <string.h>
using namespace std;
int re[26];
void findre(int a,int b){
int count=0;
int tmp1=a,tmp2=b;
while(re[a]!=b && a!=re[a]){
count++;
a=re[a];
}
count++;
if(re[a]==b){
int i;
if(count>=3){
for(i=count;i>2;i--){
cout<<"great-";
}
cout<<"grandparent"<<endl;
}else if(count==2)
cout<<"grandparent"<<endl;
else if(count==1)
cout<<"parent"<<endl;
}else{
count=0;
a=tmp2;
b=tmp1;
while(re[a]!=b && a!=re[a]){
count++;
a=re[a];
}
count++;
if(re[a]==b){
int i;
if(count>=3){
for(i=count;i>2;i--){
cout<<"great-";
}
cout<<"grandchild"<<endl;
}else if(count==2)
cout<<"grandchild"<<endl;
else if(count==1)
cout<<"child"<<endl;
}else
cout<<"-"<<endl;
}
}
int main(){
int i,j;
char tmp[4]={"\0"};
int n,m;
while(cin>>n>>m &&m!=0 && n!=0){
for(i=0;i<26;i++)
re[i]=i;
for(i=0;i<n;i++){
cin>>tmp;
for(j=1;j<strlen(tmp);j++){
if(tmp[j]!='-'){
re[tmp[j]-'A']=tmp[0]-'A';
}
}
memset(tmp,'\0',4);
}
for(i=0;i<m;i++){
cin>>tmp;
findre(tmp[0]-'A',tmp[1]-'A');
memset(tmp,'\0',4);
}
}
return 0;
}
<file_sep>/最小花费(示例).java
import java.util.Arrays;
import java.util.Scanner;
public class Main{
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
while(in.hasNext()){
int l1 = in.nextInt();
int l2 = in.nextInt();
int l3 = in.nextInt();
int c1 = in.nextInt();
int c2 = in.nextInt();
int c3 = in.nextInt();
int a = in.nextInt();
int b = in.nextInt();
int n = in.nextInt();
int n1 = b-a+1;
int len[] = new int[n1];
int dp[] = new int[n1];
Arrays.fill(dp,Integer.MAX_VALUE);
dp[0]=0;
for(int k=2;k<=n;k++){
if(k>=a&&k<=b) len[k-a]=in.nextInt();
else in.nextInt();
}
for (int i=0; i<n1-1; i++) {
for (int j=i+1,cum=0; j<n1; j++) {
cum=len[j]-len[i];
if(cum<=l1){
dp[j] = Math.min(c1+dp[i],dp[j]);
}else if(cum<=l2){
dp[j] = Math.min(c2+dp[i],dp[j]);
}if(cum<=l3){
dp[j] = Math.min(c3+dp[i],dp[j]);
}else break;
}
}
System.out.println(dp[n1-1]);
}
}
} <file_sep>/最小长方形.cpp
#include<iostream>
#include<vector>
#include<limits.h>
using namespace std;
int main()
{
while(true)
{
int a,b;
int count = 0;
int xmax = INT_MIN;
int xmin = INT_MAX;
int ymax =INT_MIN;
int ymin = INT_MAX;
while(cin>>a>>b,a!=0||b!=0)
{
xmax = max(xmax,a);
xmin = min(xmin,a);
ymax = max(ymax,b);
ymin = min(ymin,b);
count++;
}
if(count == 0)
break;
else
{
cout<<xmin<<' '<<ymin<<' '<<xmax<<' '<<ymax<<endl;
}
}
return 0;
}
<file_sep>/二叉树求解m子树的子节点数目.cpp
#include<iostream>
#include <cmath>
using namespace std;
int main() {
int n, m, base, res, b, e;
while (cin >> m >> n) {
if (n == 0 & m == 0)break;
int h1=(int)(log(m)/log(2));
int h2=(int)(log(n)/log(2));
int sum=0;
int t1=pow(2,h2-h1)*m;
int t2=m;
for(int i=0;i<h2-h1;i++)
{
t2=2*t2+1;
}
if(n<t1)
{
for(int i=0;i<h2-h1;i++)
{
sum+=pow(2,i);
}
}
if(n>t2)
{
for(int i=0;i<=h2-h1;i++)
{
sum+=pow(2,i);
}
}
if(n>=t1 && n<=t2)
{
for(int i=0;i<h2-h1;i++)
{
sum+=pow(2,i);
}
sum+=n-pow(2,h2-h1)*m+1;
}
cout<<sum<<endl;
}
}
<file_sep>/点菜问题(既是 0-1背包问题).cpp
#include <iostream>
#include <vector>
using namespace std;
void knapsack(int m, int t, vector<int>& price_array, vector<int>& score_array, vector< vector<int> >& result)
{
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= t; ++j)
{
if (price_array[i] > j)
{
result[i][j] = result[i - 1][j];
}
else
{
int score1 = result[i - 1][j - price_array[i]] + score_array[i];
int score2 = result[i - 1][j];
if (score1 > score2)
{
result[i][j] = score1;
}
else
{
result[i][j] = score2;
}
}
}
}
}
int main()
{
int t,m;
while(cin>>t>>m)
{
vector<int> price_array(1, 0);
vector<int> score_array(1, 0);
for(int i=0;i<m;i++)
{
int price,score;
cin>>price>>score;
price_array.push_back(price);
score_array.push_back(score);
}
vector< vector<int> > result(m + 1, vector<int>(t + 1, 0)); // 结果数组
knapsack(m, t, price_array, score_array, result); // 调用动态规划算法
cout <<result[m][t] << endl;
}
return 0;
}
<file_sep>/Sharing.cpp
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int next[99999];
char node[99999];
int add1,add2,pt,len,len1,len2,a,c,add,flag;
char b;
while(~scanf("%d%d%d",&add1,&add2,&pt))
{
len1=len2=1;
while(pt--)
{
scanf("%d %c %d",&a,&b,&c);
next[a]=c;
node[a]=b;
}
a=add1;
while(next[a]!=-1)
{
a=next[a];
len1++;
}
a=add2;
while(next[a]!=-1)
{
a=next[a];
len2++;
}
if(len1>=len2)
{
a=len1-len2;
while(a--) add1=next[add1];
}
else
{
a=len2-len1;
while(a--) add2=next[add2];
}
add=-1;
flag=0;
len=min(len1,len2);
while(len--)
{
if(node[add1]==node[add2])
{
if(flag==0)
{
add=add1;
flag=1;
}
add1=next[add1];
add2=next[add2];
}
else
{
flag=0;
add=-1;
add1=next[add1];
add2=next[add2];
}
}
if(add==-1)
printf("-1\n");
else
printf("%05d\n",add);
}
return 0;
}
<file_sep>/根据无向图的边邻接矩阵求任意一点到其他所有点之间的最短路径.cpp
#include <iostream>
#include <cmath>
using namespace std;
#define INFINITY 1000000000 //存储无向图中无边两点之间的距离
#define MAX 100 //存储该无向图最多的点数为500
long long arr[MAX][MAX];
void ShortestPath_DIJ(int n,int v0, int p[MAX][MAX], int D[MAX],long long arr[MAX][MAX]) { //计算v0到其他所有点之间的最短路径。
int v, w, i, j, min;
bool final[MAX];
for(v=0; v<n; v++) {
final[v]=false;
D[v]=arr[v0][v];
for(w=0; w<n; w++)
p[v][w]=-1;
if(D[v]<INFINITY) {
p[v][0]=v0;
p[v][1]=v;
}
}
D[v0]=0;
final[v0]=true;
for(i=1; i<n; i++) {
min=INFINITY;
for(w=0; w<n; w++)
if(!final[w] && D[w]<min) {
v=w;
min=D[w];
}
final[v]=true;
for(w=0; w<n; w++) {
if(!final[w] && min<INFINITY && arr[v][w]<INFINITY
&& (min+arr[v][w]<D[w])) {
D[w]=min+arr[v][w];
for(j=0; j<n; j++) {
p[w][j]=p[v][j];
if(p[w][j]==-1) {
p[w][j]=w;
break;
}
}
}
}
}
for(int i=0;i<n;i++) //输出v0到其他所有点之间的最短路径
{
if(i!=v0)
{
cout<<v0<<"------>"<<i<<": "<<D[i]<<endl;
}
else
{
continue;
}
}
}
int main()
{
int n,k;
while(true)
{
cout<<"请输入点数和边数:";
cin>>n>>k;
for(int m=0;m<n;m++)
{
for(int r=0;r<n;r++)
{
if(m==r)
{
arr[m][r]=0;
}
else
{
arr[m][r]=INFINITY;
}
}
}
cout<<"请输入每条边的邻接点及所在边的距离:"<<endl;
for(int m=0;m<k;m++)
{
int i,j,d;
cin>>i>>j>>d;
arr[i][j]=d;
arr[j][i]=arr[i][j];
}
int p[MAX][MAX];
int D[MAX];
int v0;
cout<<"请输入起始点:";
cin>>v0;
cout<<v0<<"点到其他各个点之间的最短距离为:"<<endl ;
ShortestPath_DIJ(n,v0,p,D,arr);
}
return 0;
}
<file_sep>/Sum of Factorial.cpp
#include<iostream>
using namespace std;
int main()
{
int factorial[10];
int i;
factorial[0]=1;
for(i=1;i<10;i++)
{
factorial[i]=factorial[i-1]*i;
}
int n;
while(cin>>n)
{
for(int k=9;k>=0;k--)
{
if(n>=factorial[k])
n-=factorial[k];
if(n==0)
break;
}
if(n==0)
cout<<"YES"<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
<file_sep>/将输入的整数转换为八进制数.cpp
#include <iostream>
#include <math.h>
using namespace std;
int tran(int number);
int main()
{
int n;
int sum=0;
int i=0;
while(cin>>n)
{
cout<<tran(n)<<endl;
}
return 0;
}
int tran(int number)
{
int sum=0;
int i=0;
while(number)
{
sum+=pow(10,i++)*(number%8);
number/=8;
}
return sum;
}
<file_sep>/完数和盈数.cpp
#include <iostream>
using namespace std;
bool isw(int n)
{
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(sum==n)
{
return true;
}
return false;
}
bool isy(int n)
{
int sum=0;
for(int i=1;i<n;i++)
{
if(n%i==0)
{
sum+=i;
}
}
if(sum>n)
{
return true;
}
return false;
}
int main()
{
cout<<"E: ";
int count=0;
for(int i=2;i<=60;i++)
{
if(isw(i))
{
count++;
if(count==1)
{
cout<<i;
}
else
{
cout<<" "<<i;
}
}
}
cout<<endl;
cout<<"G: ";
int c=0;
for(int i=2;i<=60;i++)
{
if(isy(i))
{
c++;
if(c==1)
{
cout<<i;
}
else
{
cout<<" "<<i;
}
}
}
cout<<endl;
return 0;
}
<file_sep>/四则运算_示例.cpp
#include<iostream>
using namespace std;
int main()
{
int a,c;
char b;
while(cin>>a>>b)
{
if(b=='+')
{cin>>c;
cout<<a+c<<endl;}
if(b=='-')
{ cin>>c;
cout<<a-c<<endl;}
if(b=='*')
{cin>>c;
cout<<a*c<<endl;}
if(b=='/')
{
cin>>c;
if(c==0)
cout<<"error"<<endl;
else
cout<<a/c<<endl;
}
if(b=='%')
{
cin>>c;
if(c==0)
cout<<"error"<<endl;
else
cout<<a%c<<endl;
}
if(b=='!')
{
int i,sum=1;
for(i=1;i<=a;i++)
sum=sum*i;
cout<<sum<<endl;
}
}
return 0;
}
<file_sep>/矩阵转置.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
int maxt[100][100];
while(cin>>n)
{
while(n<1||n>100)
{
cin>>n;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>maxt[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j!=n-1)
{
cout<<maxt[j][i]<<" ";
}
else
{
cout<<maxt[j][i];
}
}
cout<<endl;
}
}
return 0;
}
<file_sep>/数值的整数次方.cpp
#include <iostream>
#include <cmath>
using namespace std;
double Power(double base, int exponent) {
return pow(base,exponent);
}
double Power2(double base, int exp) {
int ex=abs(exp);
double res=1.0;
double cur=base;
while(ex!=0){
if(ex&1)
res*=cur;
cur*=cur;
ex>>=1;
}
return exp>0?res:1/res;
}
int main()
{
double base;
int ex;
while(cin>>base>>ex)
{
cout<<Power(base,ex)<<" "<<Power(base,ex)<<endl;
}
return 0;
}
<file_sep>/计算n个年龄的平均值.cpp
#include<iostream.h>
#include<vector>
using namespace std;
int main(){
int n,sumAge,aveAge;
cout<<"请输入年龄的个数:";
cin>>n;
vector<int>age(n);
cout<<endl<<"请输入"<<n<<"个年龄:";
for(int i=0;i<n;++i)
cin>>age[i];
sumAge=0;
for(i=0;i<n;++i)
sumAge+=age[i];
aveAge=sumAge/n;
cout<<"平均年龄:"<<aveAge<<endl;
return 0;
}
<file_sep>/求最大值.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int num[10];
while(cin>>num[0]>>num[1]>>num[2]>>num[3]>>num[4]>>num[5]>>num[6]>>num[7]>>num[8]>>num[9])
{
sort(num,num+10);
cout<<"max="<<num[9]<<endl;
}
return 0;
}
<file_sep>/众数.cpp
#include <iostream>
#include <algorithm>
using namespace std;
struct zs
{
int data,num;
};
bool cmp(zs z1,zs z2)
{
if(z1.num!=z2.num)
{
return z1.num>z2.num;
}
return z1.data<z2.data;
}
int main()
{
zs z[10];
int n[20];
while(cin>>n[0]>>n[1]>>n[2]>>n[3]>>n[4]>>n[5]>>n[6]>>n[7]>>n[8]>>n[9]>>n[10]>>n[11]>>n[12]>>n[13]>>n[14]>>n[15]>>n[16]>>n[17]>>n[18]>>n[19])
{
for(int i=1;i<=10;i++)
{
z[i-1].num=0;
z[i-1].data=i;
for(int j=0;j<20;j++)
{
if(n[j]==i)
{
z[i-1].num++;
}
}
}
sort(z,z+10,cmp);
cout<<z[0].data<<endl;
}
return 0;
}
<file_sep>/判断三角形类型.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr[3];
while(cin>>arr[0]>>arr[1]>>arr[2])
{
sort(arr,arr+3);
int value=arr[0]*arr[0]+arr[1]*arr[1]-arr[2]*arr[2];
if(value>0)
{
cout<<"锐角三角形"<<endl;
}
else if(value==0)
{
cout<<"直角三角形"<<endl;
}
else
{
cout<<"钝角三角形"<<endl;
}
}
return 0;
}
<file_sep>/字符串匹配---高效率(数目).cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str1,str2;
while(cin >> str1>>str2)
{
int count=0;
int startpos = 0;
int pos=str1.find(str2, startpos);
while(pos!=string::npos)
{
count++;
pos=str1.find(str2, pos+1);
}
cout << count<< endl;
}
return 0;
}
<file_sep>/拦截导弹.cpp
#include <iostream>
using namespace std;
/**
动态规划: dp[]数组记录后面比他小的数字的个数
*/
int main()
{
int k = 0;
int a[50] = {0};
while(cin>>k)
{
for(int i = k-1;i>=0;i--)
cin>>a[i];
int dp[50] = {0};
dp[0] = 1;
int maxx = 0;
for(int i = 0;i<k;i++)
{
for(int j = 0;j<i;j++)
{
if(a[i]>=a[j]) dp[i] = max(dp[j]+1,dp[i]);
}
if(dp[i]==0) dp[i] = 1;
}
for(int i = 0;i<k;i++) maxx = max(maxx,dp[i]);
cout<<maxx<<endl;
}
return 0;
}
<file_sep>/递推数列(迭代法).cpp
#include <iostream>
using namespace std;
int main()
{
int a,b,p,q,k;
while(cin>>a>>b>>p>>q>>k)
{
long long num[k+1];
num[0]=a;
num[1]=b;
for(int i=2;i<=k;i++)
{
num[i]=(p*num[i-1]+q*num[i-2])%10000;
}
cout<<num[k]<<endl;
}
return 0;
}
<file_sep>/成绩排序.cpp
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
struct Student
{
string name;
int age;
int score;
}myStudent[1000];
bool cmp(Student s1,Student s2);
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>1000)
{
cin>>n;
}
for(int i=0;i<n;i++)
{
cin>>myStudent[i].name>>myStudent[i].age>>myStudent[i].score;
}
sort(myStudent,myStudent+n,cmp);
for(int i=0;i<n;i++)
{
cout<<myStudent[i].name<<" "<<myStudent[i].age<<" "<<myStudent[i].score<<endl;
}
}
return 0;
}
bool cmp(Student s1,Student s2)
{
if(s1.score!=s2.score)
{
return s1.score<s2.score;
}
if(s1.name!=s2.name)
{
return s1.name<s2.name;
}
else return s1.age<s2.age;
}
<file_sep>/开门人和闭门人.cpp
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
struct record
{
string numebr;
string time_in;
string time_out;
};
bool cmp_in(record r1,record r2)
{
int n1,n2;
if(r1.time_in.substr(0,2)!=r2.time_in.substr(0,2))
{
stringstream ss1(r1.time_in.substr(0,2));
ss1>>n1;
stringstream ss2(r2.time_in.substr(0,2));
ss2>>n2;
return n1<n2;
}
else if(r1.time_in.substr(3,2)!=r2.time_in.substr(3,2))
{
stringstream ss1(r1.time_in.substr(3,2));
ss1>>n1;
stringstream ss2(r2.time_in.substr(3,2));
ss2>>n2;
return n1<n2;
}
else
{
stringstream ss1(r1.time_in.substr(6,2));
ss1>>n1;
stringstream ss2(r2.time_in.substr(6,2));
ss2>>n2;
return n1<n2;
}
}
bool cmp_out(record r1,record r2)
{
int n1,n2;
if(r1.time_out.substr(0,2)!=r2.time_out.substr(0,2))
{
stringstream ss1(r1.time_out.substr(0,2));
ss1>>n1;
stringstream ss2(r2.time_out.substr(0,2));
ss2>>n2;
return n1<n2;
}
else if(r1.time_out.substr(3,2)!=r2.time_out.substr(3,2))
{
stringstream ss1(r1.time_out.substr(3,2));
ss1>>n1;
stringstream ss2(r2.time_out.substr(3,2));
ss2>>n2;
return n1<n2;
}
else
{
stringstream ss1(r1.time_out.substr(6,2));
ss1>>n1;
stringstream ss2(r2.time_out.substr(6,2));
ss2>>n2;
return n1<n2;
}
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int m;
cin>>m;
record r[m];
for(int j=0;j<m;j++)
{
cin>>r[j].numebr>>r[j].time_in>>r[j].time_out;
}
sort(r,r+m,cmp_in);
cout<<r[0].numebr<<" ";
sort(r,r+m,cmp_out);
cout<<r[m-1].numebr<<endl;
}
}
return 0;
}
<file_sep>/正常排序.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
int num[100];
while(cin>>n)
{
while(n<1 || n>100)
{
cin>>n;
}
for(int i=0;i<n;i++)
{
cin>>num[i];
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(num[j]>num[j+1])
{
int temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
for(int i=0;i<n;i++)
{
cout<<num[i]<<" ";
}
cout<<endl;
}
return 0;
}
<file_sep>/最小邮票数.cpp
#include <iostream>
using namespace std;
int main() {
int sum;
while (cin >> sum){
int n;
cin >> n;
int stamps[n];
int mins[sum+1];
for (int i = 0; i < sum+1; ++i) {
mins[i] = 20;
}
mins[0] = 0;
for (int i = 0; i < n; ++i) {
cin >> stamps[i];
}
for (int i = 0; i < n; ++i) {
for (int j = sum; j >= stamps[i]; --j) {
if (mins[j - stamps[i]] != 20){
mins[j] = (mins[j] < mins[j - stamps[i]] + 1)? mins[j]: mins[j - stamps[i]] + 1;
}
}
}
if (mins[sum] != 20){
cout << mins[sum] << endl;
} else {
cout << 0 << endl;
}
}
return 0;
}
<file_sep>/对称矩阵.cpp
#include <iostream>
using namespace std;
int main()
{
l:
int n;
int max[100][100];
while(cin>>n)
{
while(n<1 || n>100)
{
cout<<"输入有误,请输入1-100之间的整数:"<<endl;
cin>>n;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>max[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<=i;j++)
{
if(max[i][j]!=max[j][i])
{
cout<<"No!"<<endl;
goto l;
}
}
}
cout<<"Yes!"<<endl;
}
return 0;
}
<file_sep>/复数集合.cpp
#include <iostream>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;
struct COMPLEX{
int a, b;
};
COMPLEX c[1000];
int StringToNum( string s ){
int i, len, r;
len = s.length();
for( i=0; i<len; i++ ){
if( i==0 )
r = s[i]-48;
else r = r*10 + s[i]-48;
}
return r;
};
int module( COMPLEX x ){
return x.a*x.a+x.b*x.b;
};
bool cmp( COMPLEX x, COMPLEX y ){
int xm = module(x), ym = module(y);
if( xm==ym )
return x.a < y.a;
return xm < ym;
};
int main()
{
int i, j, k, n, m;
int len, size;
string t, s, temp, aS, bS; //t=命令
while( cin >> n ){
size = 0;
for( i=0; i<n; i++ ){
cin >> t;
if( t == "Pop" ){
//cout << "i=" << i << " ";//
if( size == 0 )
cout << "empty\n";
else{
sort(c,c+size,cmp);
cout << c[size-1].a << "+i" << c[size-1].b << endl;
size--;
cout << "SIZE = " << size << endl;
}
}
else{ //Insert命令
cin >> s;
len = s.length();
for( j=0; j<len; j++ )
if( s[j]=='+' )
break;
aS = s.substr(0,j);
bS = s.substr(j+2); //不给出长度就默认到结尾
c[size].a = StringToNum(aS);
c[size].b = StringToNum(bS);
size++;
cout << "SIZE = " << size << endl;
}
}// for
}
return 0;
}
<file_sep>/杨辉三角(非递归做法).cpp
#include <iostream>
using namespace std;
int main()
{
int n;
//int matrix[10000][10000];
while(cin>>n)
{
while(n<2)
{
cin>>n;
}
int matrix[n-1][n];
for(int i=0;i<n-1;i++)
{
matrix[i][0]=matrix[i][i+1]=1;
for(int j=1;j<(i+1);j++)
{
matrix[i][j]=matrix[i-1][j-1]+matrix[i-1][j];
}
}
for(int i=0;i<n-1;i++)
{
for(int j=0;j<i+2;j++)
{
cout<<matrix[i][j]<<" ";
}
cout<<endl;
}
}
return 0;
}
<file_sep>/采药(0-1背包问题).cpp
#include <iostream>
#include <vector>
using namespace std;
void knapsack(int m, int t, vector<int>& time_array, vector<int>& value_array, vector< vector<int> >& result)
{
for (int i = 1; i <= m; ++i)
{
for (int j = 1; j <= t; ++j)
{
if (time_array[i] > j) // 当前药品的价值 j 放不下第 i 位药品时
{
result[i][j] = result[i - 1][j]; // 放弃第 i 件药品,拿第 i - 1 件药品
}
else
{
int value1 = result[i - 1][j - time_array[i]] + value_array[i]; // 拿走第 i - 1件药品
int value2 = result[i - 1][j]; // 不拿走第 i - 1 件药品
if (value1 > value2)
{
result[i][j] = value1;
}
else
{
result[i][j] = value2;
}
}
}
}
}
int main()
{
int t,m;
while(cin>>t>>m)
{
vector<int> time_array(1, 0);
vector<int> value_array(1, 0);
for(int i=0;i<m;i++)
{
int time,value;
cin>>time>>value;
time_array.push_back(time);
value_array.push_back(value);
}
vector< vector<int> > result(m + 1, vector<int>(t + 1, 0)); // 结果数组
knapsack(m, t, time_array, value_array, result); // 调用动态规划算法
cout <<result[m][t] << endl;
}
return 0;
}
<file_sep>/String Matching.cpp
#include<iostream>
#include<cstring>
using namespace std;
int main() {
string str1,str2;
while(cin>>str1>>str2)
{
int length=str2.length();
int count=0;
for(int i=0;i<=str1.length()-length;i++)
{
if(str1.substr(i,length)==str2)
{
count++;
}
}
cout<<count<<endl;
}
return 0;
}
<file_sep>/调整方阵---输入一个N(N=10)阶方阵,按照如下方式调整方阵: 1.将第一列中最大数所在的行与第一行对调。 2.将第二列中从第二行到第N行最大数所在的行与第二行对调。 依此类推... N-1.将第N-1列中从第N-1行到第N行最大数所在的行与第N-1行对调。 N.输出这个方阵 .cpp
#include <iostream>
using namespace std;
int main()
{
int n;
int maxt[10][10];
while(cin>>n)
{
while(n<1 || n>10)
{
cin>>n;
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>maxt[i][j];
}
}
for(int i=0;i<n;i++)
{
int max=0,index;
for(int j=i;j<n;j++)
{
if(max<maxt[j][i])
{
max=maxt[j][i];
index=j;
}
}
for(int j=0;j<n;j++)
{
int t=maxt[i][j];
maxt[i][j]=maxt[index][j];
maxt[index][j]=t;
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(j!=n-1)
{
cout<<maxt[i][j]<<" ";
}
else
{
cout<<maxt[i][j];
}
}
cout<<endl;
}
}
return 0;
}
<file_sep>/最后一个字符--示例.cpp
#include<iostream>
#include<string.h>
using namespace std;
const int MAX = 1000000;
void findChar(char* s)
{
if(s==NULL)
return;
int hash[256], len = strlen(s);
memset(hash,0,sizeof(hash));
int i;
for(i=0;i<len;i++)
hash[s[i]]++;
for(i=0;i<len;i++)
{
if(hash[s[i]]==1)
{
printf("%c\n",s[i]);
break;
}
}
if(i==len)
return;
}
int main( )
{
char s[MAX];
int num;
cin>>num;
while(num--)
{
scanf("%s",s);
findChar(s);
}
return 0;
}
<file_sep>/数组逆序(字符串).cpp
#include <iostream>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
while(str.length()>200)
{
cin>>str;
}
string s(str.rbegin(),str.rend());
cout<<s<<endl;
}
return 0;
}
<file_sep>/奇数偶数排序.cpp
#include <iostream>
#include <map>
using namespace std;
int main()
{
int num[10];
while(cin>>num[0]>>num[1]>>num[2]>>num[3]>>num[4]>>num[5]>>num[6]>>num[7]>>num[8]>>num[9])
{
int ji[10];
int ou[10];
int i_j=0,j_ou=0;
for(int i=0;i<10;i++)
{
if(num[i]%2==0)
{
ou[j_ou]=num[i];
j_ou++;
}
else
{
ji[i_j]=num[i];
i_j++;
}
}
for(int i=0;i<i_j;i++)
{
for(int j=0;j<i_j-1-i;j++)
{
if(ji[j]<ji[j+1])
{
int temp=ji[j];
ji[j]=ji[j+1];
ji[j+1]=temp;
}
}
}
for(int i=0;i<j_ou;i++)
{
for(int j=0;j<j_ou-1-i;j++)
{
if(ou[j]>ou[j+1])
{
int temp=ou[j];
ou[j]=ou[j+1];
ou[j+1]=temp;
}
}
}
for(int i=0;i<i_j;i++)
{
cout<<ji[i]<<" ";
}
for(int i=0;i<j_ou-1;i++)
{
cout<<ou[i]<<" ";
}
cout<<ou[j_ou-1]<<endl;
}
return 0;
}
<file_sep>/count the string---yjd.cpp
#include <iostream>
#include <stdio.h>
using namespace std;
int count_subString(string str1,string str2)
{
int count=0;
int startpos = 0;
int pos=str1.find(str2, startpos);
while(pos!=string::npos)
{
count++;
pos=str1.find(str2, pos+1);
}
return count;
}
int main()
{
int n;
while(cin >> n)
{
for(int i=0;i<n;i++)
{
int sum=0;
int l;
string str1;
cin>>l;
cin>>str1;
for(int i=1;i<=str1.length();i++)
{
string str2=str1.substr(0,i);
sum+=count_subString(str1,str2);
}
cout<<sum<<endl;
}
}
return 0;
}
<file_sep>/字符串匹配(数目).cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string T,P;
int cnt;
while(cin >> T)
{
cnt=0;
cin >> P;
int startpos = 0;
int pos=T.find(P, startpos);
while(pos!=string::npos)
{
cnt++;
pos=T.find(P, pos+1);
}
cout << cnt << endl;
}
return 0;
}
<file_sep>/输入n, 求y1=1!+3!+...m!(m是小于等于n的最大奇数) y2=2!+4!+...p!(p是小于等于n的最大偶数)。 .java
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
String input=null;
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext())
{
input=scanner.next();
while(!isNumeric(input) )
{
System.out.println("ÇëÊäÈëÕûÊý");
input=scanner.next();
}
jc(input);
}
}
public static boolean isNumeric(String str){
for ( int i=str.length();--i>=0;){
int chr=str.charAt(i);
if(chr<48 || chr>57)
return false ;
}
return true ;
}
public static void jc(String number)
{
int n=Integer.parseInt(number);
int y1 = 0,y2=0;
if(n%2==0)
{
for(int i=1;i<=n-1;i+=2)
{
y1+=jiec(i);
}
for(int i=2;i<=n;i+=2)
{
y2+=jiec(i);
}
}
else
{
for(int i=1;i<=n;i+=2)
{
y1+=jiec(i);
}
for(int i=2;i<=n-1;i+=2)
{
y2+=jiec(i);
}
}
System.out.println(y1+" "+y2);
}
public static int jiec(int number)
{
if(number==1)
{
return 1;
}
if(number>1)
{
return number*jiec(number-1);
}
return 0;
}
}
<file_sep>/哈利波特---魔咒_yjd.cpp
#include <iostream>
#include <string>
using namespace std;
struct mz
{
string name;
string fun;
}mzS[100000];
int isExistName(string str,mz mzS[],int k)
{
for(int i=0;i<k;i++)
{
if(mzS[i].name==str)
{
return i;
}
}
return -1;
}
int isExistFun(string str,mz mzS[],int k)
{
for(int i=0;i<k;i++)
{
if(mzS[i].fun==str)
{
return i;
}
}
return -1;
}
int main()
{
string str;
int n;
int k=0;
while(getline(cin,str)&& str!="@END@")
{
int index=0;
for(int i=0;i<str.length();i++)
{
if(str.substr(i,1)==" ")
{
index=i;
break;
}
}
mzS[k].name=str.substr(0,index);
mzS[k].fun=str.substr(index+1);
k++;
}
cin>>n;
getchar();
for(int j=0;j<n;j++)
{
string str1;
getline(cin,str1);
if(str1.substr(0,1)!="[")
{
if(isExistFun(str1,mzS,k)!=-1)
{
cout<<mzS[isExistFun(str1,mzS,k)].name<<endl;
}
else
{
cout<<"what?"<<endl;
}
}
else
{
if(isExistName(str1,mzS,k)!=-1)
{
cout<<mzS[isExistName(str1,mzS,k)].fun<<endl;
}
else
{
cout<<"what?"<<endl;
}
}
}
return 0;
}
<file_sep>/立方根的迭代求法.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double x;
int n;
while(cin>>x>>n)
{
double value=x;
for(int i=0;i<n;i++)
{
value=(value*2/3)+(x/(3*value*value));
}
cout<<setiosflags(ios::fixed)<<setprecision(6)<<value<<endl;
}
return 0;
}
<file_sep>/最大报销额.cpp
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
using namespace std;
double all;
void find(double f,double q,double mm[],int k,int n)
{
if(k<n)
{
if(f+mm[k]<=q)
{
if(f+mm[k]>all)
all=f+mm[k];
find(f+mm[k],q,mm,k+1,n);
}
find(f,q,mm,k+1,n);
}
}
int main()
{
double q,num,price,pa,pb,pc,mm[35];
char type,ss[100];
int n,m,flag,i,k;
while(scanf("%lf%d",&q,&n) && n)
{
all=0;
for(i=0,k=0;i<n;i++)
{
num=0;
flag=0;
scanf("%d",&m);
pa=pb=pc=0;
while(m--)
{
getchar();
type=getchar();
getchar();
scanf("%lf",&price);
if(type!='A' && type!='B' && type!='C')
flag=1;
else if(type == 'A')
pa+=price;
else if(type == 'B')
pb+=price;
else if(type == 'C')
pc+=price;
}
getchar();
num=pa+pb+pc;
if(num>1000 || pa>600 || pb>600 || pc>600 || flag==1)
{
continue;
}
mm[k++]=num;
}
find(0,q,mm,0,k);
printf("%.2f\n",all);
}
return 0;
}<file_sep>/二叉树遍历.cpp
#include <cstring>
#include <iostream>
#include <stdlib.h>
#define StringMax 100
using namespace std;
typedef struct BinaryTree {
char data;
BinaryTree *lchild;
BinaryTree *rchild;
} BinaryTree;
void RebuildTree(BinaryTree *&Tree, char *PreOrder, char *InOrder, int len) {
Tree = (BinaryTree *)malloc(sizeof(BinaryTree));
if (Tree != NULL) {
if (len <= 0) {
Tree = NULL;
return;
} else {
int index = 0;
while (index < len && *(PreOrder) != *(InOrder + index))
index++;
Tree->data = *(PreOrder);
RebuildTree(Tree->lchild, PreOrder + 1, InOrder, index);
RebuildTree(Tree->rchild, PreOrder + 1 + index, InOrder + 1 + index, len - (index + 1));
}
}
return;
}
void PostOrderTravese(BinaryTree *Tree) {
if (Tree == NULL)
return;
else {
PostOrderTravese(Tree->lchild);
PostOrderTravese(Tree->rchild);
cout << Tree->data;
}
}
int main() {
char PreOrder[StringMax], InOrder[StringMax];
while (cin >> PreOrder >> InOrder) {
BinaryTree *tree;
int length = strlen(PreOrder);
RebuildTree(tree, PreOrder, InOrder, length);
PostOrderTravese(tree);
cout << endl;
}
return 0;
}
<file_sep>/矮个子中的高个子和高个子中的矮个子.java
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class Work1 {
public static void readTxtFile(String filePath){
try {
String encoding="GBK";
int [][] ma=new int[10][20];
File file=new File(filePath);
if(file.isFile() && file.exists()){ //判断文件是否存在
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);//考虑到编码格式
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
int i=0;
while((lineTxt = bufferedReader.readLine()) != null){
String [] line=lineTxt.split(" ");
for(int j=0;j<20;j++)
{
ma[i][j]=Integer.parseInt(line[j]);
}
i++;
}
int[] row=new int[10];
int[] col=new int[20];
for(int m=0;m<10;m++)
{
int h=0;
for(int n=0;n<20;n++)
{
if(ma[m][n]>h)
{
h=ma[m][n];
}
}
row[m]=h;
}
for(int m=0;m<20;m++)
{
int s=100000;
for(int n=0;n<10;n++)
{
if(ma[n][m]<s)
{
s=ma[n][m];
}
}
col[m]=s;
}
int short_of_height=row[0];
for(int i1=1;i1<10;i1++)
{
if(short_of_height>row[i1])
{
short_of_height=row[i1];
}
}
int height_of_short=row[0];
for(int i1=1;i1<20;i1++)
{
if(height_of_short<col[i1])
{
height_of_short=col[i1];
}
}
System.out.println("<矮人中的高个子>身高为:"+height_of_short);
System.out.println("<高个子中的矮人>身高为:"+short_of_height);
if(height_of_short>short_of_height)
{
System.out.println("<矮人中的高个子>高于<高个子中的矮人>");
}
if(height_of_short==short_of_height)
{
System.out.println("<矮人中的高个子>等于<高个子中的矮人>");
}
if(height_of_short<short_of_height)
{
System.out.println("<矮人中的高个子>低于<高个子中的矮人>");
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
}
public static void main(String argv[]){
String filePath = "D:\\1.txt";
// "res/";
readTxtFile(filePath);
}
}<file_sep>/子串计算.cpp
#include<iostream>
#include<string>
#include<map>
using namespace std;
int main()
{
string str;
while (cin >> str)
{
map<string, int>my;
for (int i = 0; i < str.length();i++)
for (int j = 1; j <= str.length()-i; j++)
my[str.substr(i, j)]++;
for (map<string, int>::iterator it = my.begin(); it != my.end(); it++)
{
if (it->second>1)
cout << it->first << " " << it->second << endl;
}
}
return 0;
}
<file_sep>/查找(翻转和替换).cpp
#include <iostream>
#include <cstring>
#include <sstream>
#include <algorithm>
using namespace std;
int main()
{
string str;
string s[100];
int n;
while(cin>>str>>n)
{
int k=0;
for(int i=0;i<n;i++)
{
string str1;
cin>>str1;
if(str1.substr(0,1)=="0")
{
int num1,num2;
stringstream ss(str1.substr(1,1));
ss>>num1;
stringstream ss1(str1.substr(2,str1.length()-2));
ss1>>num2;
string str2=str.substr(num1,num2);
reverse(str2.begin(),str2.end());
str=str.substr(0,num1)+str2+str.substr(num1+num2,str.length()-num1-num2);
s[k]=str;
k++;
}
else if(str1.substr(0,1)=="1")
{
int index=0;
for(int i=0;i<str1.length();i++)
{
if(!isdigit(str1.at(i)))
{
index=i;
break;
}
}
int num1,num2;
stringstream ss(str1.substr(1,1));
ss>>num1;
stringstream ss1(str1.substr(2,index-1));
ss1>>num2;
string str2=str1.substr(index,str1.length()-index);
str=str.substr(0,num1)+str2+str.substr(num1+num2,str.length()-num1-num2);
s[k]=str;
k++;
}
}
for(int i=0;i<n;i++)
{
cout<<s[i]<<endl;
}
}
return 0;
}
<file_sep>/Reapter.cpp
#include <iostream>
using namespace std;
char mat[3001][3001];
char init[6][6];
int n;
void paint(int x,int y,int n_size,int size) {
if(n_size == 1) {
for(int i = 0;i < n;i++)
for(int j = 0;j < n;j++)
mat[x+i][y+j] = init[i][j];
return;
}else {
for(int i = 0;i < n;i++) {
for(int j = 0;j < n;j++) {
if(init[i][j]!=' ')
paint(x+i*size/n,y+j*size/n,n_size-1,size/n);
}
}
}
}
int main(void) {
while(cin >> n) {
if(n==0) break;
getchar();
for(int i = 0;i < n;i++) {
for(int j = 0;j < n;j++) {
init[i][j] = getchar();
}
getchar();
}
int n_size;
cin >> n_size;
int size = 1;
for(int i = 1;i <= n_size;i++)
size*=n;
for(int i = 0;i < size;i++)
for(int j = 0;j < size;j++)
mat[i][j] = ' ';
paint(0,0,n_size,size);
for(int i = 0;i < size;i++) {
for(int j = 0;j < size;j++) {
cout << mat[i][j];
}
cout << endl;
}
}
return 0;
}
<file_sep>/无需数组中最小的k个数.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
vector<int> findKthNumbers(vector<int> A, int n, int k) {
// write code here
vector<int> A_copy;
for(int i=0;i<n;i++)
{
A_copy.push_back(A[i]);
}
sort(A.begin(),A.end());
vector<int> v;
for(int i=0;i<k;i++)
{
v.push_back(A[i]);
}
vector<int> v2;
for(int i=0;i<n;i++)
{
for(int j=0;j<k;j++)
{
if(A_copy[i]==v[j])
{
v2.push_back(v[j]);
break;
}
}
}
return v2;
}
int main()
{
int n,k;
while(cin>>n>>k)
{
vector<int> A;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
A.push_back(t);
}
vector<int> v2=findKthNumbers(A,n,k);
for(int i=0;i<k-1;i++)
{
cout<<v2[i]<<" ";
}
cout<<v2[k-1]<<endl;
}
return 0;
}
<file_sep>/找X.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>200)
{
cin>>n;
}
int arr[n];
for(int i=0;i<n;i++)
{
cin>>arr[i];
}
int x;
cin>>x;
int index=-1;
for(int i=0;i<n;i++)
{
if(x==arr[i])
{
index=i;
break;
}
}
cout<<index<<endl;
}
return 0;
}
<file_sep>/最简真分数.cpp
#include <iostream>
using namespace std;
bool is(int m,int n)
{
int count=0;
int min=m>n?n:m;
for(int i=2;i<=min;i++)
{
if(m%i==0 &&n%i==0 )
{
count++;
}
}
return count>=1?false:true;
}
int main()
{
int n;
while(cin>>n && n)
{
int num[n];
int count=0;
for(int i=0;i<n;i++)
{
cin>>num[i];
}
for(int i=0;i<n-1;i++)
{
for(int j=i+1;j<n;j++)
{
if(is(num[i],num[j]))
{
count++;
}
}
}
cout<<count<<endl;
}
return 0;
}
<file_sep>/Biorhythms.cpp
#include <iostream>
using namespace std;
int main() {
int p, e, i, d;
int j = 0;
while (cin >> p >> e >> i >> d) {
j++;
if (d == -1) {
break;
}
for (int n = 0;; n++) {
int m = n * 23;
if(((m + p - e) % 28 == 0) && ((m + p - i) % 33 == 0)){
if (m + p > d) {
cout << "Case " << j << ": the next triple peak occurs in " << m + p - d << " days." << endl;
break;
} else {
cout << "Case " << j << ": the next triple peak occurs in " << m + p - d + 21252 << " days." << endl;
break;
}
}
}
}
return 0;
}
<file_sep>/Integer inqury.cpp
#include<iostream>
#include<cstring>
using namespace std;
int main() {
char c[111];
int tmp[111];
int d[111];
memset(tmp, 0, sizeof(tmp));
while (cin >> c) {
if (strlen(c)==1 && c[0] == '0')
break;
memset(d, 0, sizeof(d));
d[0] = strlen(c);
for (int i = 0; i < d[0]; i++) {
d[d[0] - i] = c[i] - 48;
}
while (d[d[0]] == 0)
d[0]--;
int carry = 0;
tmp[0] = tmp[0] > d[0] ? tmp[0] : d[0];
for (int i = 1; i <= tmp[0]; i++) {
int tt = (d[i] + tmp[i] + carry) % 10;
carry = (d[i] + tmp[i] + carry) / 10;
tmp[i] = tt;
}
if (carry > 0) {
tmp[++tmp[0]] = carry;
}
}
for (int i = tmp[0]; i >= 1; i--) {
cout << tmp[i];
}
cout << endl;
return 0;
}
<file_sep>/比较奇偶个数.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>1000)
{
cin>>n;
}
int num;
int ou=0;
for(int i=0;i<n;i++)
{
cin>>num;
if(num%2==0)
{
ou++;
}
}
string str=ou>(n-ou)?"NO":"YES";
cout<<str<<endl;
}
return 0;
}
<file_sep>/学分绩点.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
double s[n];
int xf[n];
int xfSum=0;
double sum=0;
for(int i=0;i<n;i++)
{
cin>>xf[i];
xfSum+=xf[i];
}
for(int i=0;i<n;i++)
{
cin>>s[i];
if(s[i]>=90 && s[i]<=100)
{
sum+=xf[i]*4.0;
}
else if(s[i]>=85 && s[i]<=89)
{
sum+=xf[i]*3.7;
}else if(s[i]>=82 && s[i]<=84)
{
sum+=xf[i]*3.3;
}else if(s[i]>=78 && s[i]<=81)
{
sum+=xf[i]*3.0;
}
else if(s[i]>=75 && s[i]<=77)
{
sum+=xf[i]*2.7;
}
else if(s[i]>=72 && s[i]<=74)
{
sum+=xf[i]*2.3;
}else if(s[i]>=68 && s[i]<=71)
{
sum+=xf[i]*2.0;
}else if(s[i]>=64 && s[i]<=67)
{
sum+=xf[i]*1.5;
}else if(s[i]>=60 && s[i]<=63)
{
sum+=xf[i]*1.0;
}
else
{
sum+=xf[i]*0;
}
}
cout<<setprecision(2)<<fixed<<sum/xfSum<<endl;
}
return 0;
}
<file_sep>/串的模式匹配(找出第一次出现的位置).cpp
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
int findAppearance(string A, int lena, string B, int lenb) {
// write code here
int index=0;
int j=0;
for(int i=0;i<=lena-lenb;i++)
{
if(A.substr(i,lenb)==B)
{
index=1;
j=i;
break;
}
}
if(index==0)
{
return -1;
}
else
{
return j;
}
}
int main()
{
string str1,str2;
while(cin>>str1>>str2)
{
cout<<findAppearance(str1,str1.length(),str2,str2.length())<<endl;
}
}
<file_sep>/素数.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main{
public static ArrayList<Integer> arr =new ArrayList<Integer>();
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(input.hasNext()){
int n = input.nextInt();
if(match(n))
{
for(int i=0;i<arr.size()-1;i++)
{
System.out.print(arr.get(i)+" ");
}
System.out.println(arr.get(arr.size()-1));
arr.clear();
}else
{
System.out.println(-1);
}
//System.out.println();
}
}
public static boolean isSu(int num)
{
int count=0;
for(int i=1;i<=num;i++)
{
if(num%i==0)
{
count++;
}
}
if(count==2)
{
return true;
}
return false;
}
public static boolean match(int num)
{
for(int i=1;i<num;i++)
{
if(isSu(i) && (""+i).endsWith("1"))
{
arr.add(i);
}
}
if(arr.size()>0)
{
return true;
}
return false;
}
}<file_sep>/字符串排序(按照ascii).cpp
#include <iostream>
#include <algorithm>
#include <cstring>
using namespace std;
bool cmp(char c1,char c2)
{
return (int(c1) )< (int(c2));
}
int main()
{
string str;
while(cin>>str)
{
char ch[str.length()];
strcpy(ch, str.c_str());
sort(ch,ch+str.length(),cmp);
cout<<ch<<endl;
}
return 0;
}
<file_sep>/m个苹果放在n个盘子里面(动态规划).cpp
#include <iostream>
using namespace std;
int s(int m ,int n)
{
if(m==0||n==1){
return 1;
}
if(m<n)
{
return s(m,m);
}
if(m>=n) {
return s(m, n - 1) + s(m - n, n);
}
return 0;
}
int main() {
int m,n;
while(cin>>m>>n)
{
cout<<s(m,n)<<endl;
}
return 0;
}
<file_sep>/打印极值点坐标.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
int c;
cin>>c;
int num[c];
for(int i=0;i<c;i++)
{
cin>>num[i];
}
int count=0;
int p[c];
for(int i=0;i<c;i++)
{
if((i==0 && num[i]!=num[i+1])|| (i==c-1 && num[i]!=num[i-1]))
{
p[count]=i;
count++;
}else
{
if((num[i]>num[i-1] && num[i]>num[i+1]) ||(num[i]<num[i-1] && num[i]<num[i+1]) )
{
p[count]=i;
count++;
}
}
}
for(int i=0;i<count-1;i++)
{
cout<<p[i]<<" ";
}
cout<<p[count-1]<<endl;
}
}
return 0;
}
<file_sep>/畅通工程.cpp
#include "iostream"
#include <stdio.h>
#include <string.h>
#include <cstring>
#include <vector>
#include <algorithm>
#pragma warning (disable:4996);
using namespace std;
#define MAX_TREE 1001
int findRoot(int tree[MAX_TREE],int i)
{
if (tree[i] == -1) return i;
return findRoot(tree,tree[i]);
}
int main() {
int tree[MAX_TREE],town,roadnum;
while (1)
{
scanf("%d",&town);
if (!town) break;
scanf("%d",&roadnum);
memset(tree,-1,sizeof(tree));
int town1, town2,root1,root2;
for (int i = 0; i < roadnum; i++)
{
scanf("%d %d", &town1, &town2);
root1 = findRoot(tree,town1);
root2 = findRoot(tree, town2);
if (root1 != root2)
tree[root1] = root2;
}
int rootnum = 0;
for (int i = 1; i <= town; i++)
{
if (tree[i] == -1) rootnum++;
}
printf("%d\n",(rootnum-1));
}
return 0;
}
<file_sep>/二维数组中判断有没有某个整数(二维数组每列递减).cpp
#include <iostream>
#include <vector>
using namespace std;
bool Find(int target, vector<vector<int> > array) {
for(int i=0;i<array.size();i++)
{
for(int j=0;j<array[i].size();j++)
{
if(array[i][j]==target)
{
return true;
}
}
}
return false;
}
int main()
{
vector<vector<int> > array(4);
for(int i=0;i <4;i++)
array[i].resize(4);//设置数组的大小3X3
for(int i=0;i<array.size();i++)
{
for(int j=0;j<array[i].size();j++)
{
cin>>array[j][i];
}
}
for(int i=0;i<array.size();i++)
{
for(int j=0;j<array[i].size();j++)
{
cout<<array[i][j]<<" ";
}
cout<<endl;
}
int n;
cin>>n;
cout<<Find(n,array)<<endl;
return 0;
}
<file_sep>/16进制转换为10进制数.cpp
#include <iostream>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <sstream>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
long n=0;
for(int i=2;i<str.length();i++)
{
if(str[i]>='A' && str[i]<='F')
{
int t=(((int)str[i])-55);
n+=t*pow(16,str.length()-1-i);
}
else
{
n+=(int(str[i]-'0'))*pow(16,str.length()-1-i);
}
}
cout<<n<<endl;
}
return 0;
}
<file_sep>/无括号表达式求值.cpp
#include <iostream>
#include <vector>
#include <string>
#include<algorithm>
using namespace std;
int main()
{
string s;
while (cin >> s)
{
vector<double> num, resnum;
vector<char> sym, ressym;
for (int i = 0; i < s.length();)
if (s[i] >= '0'&&s[i] <= '9')
{
double sum = 0;
while (i < s.length() && s[i] >= '0'&&s[i] <= '9')
{
int n = s[i] - '0';
sum = sum * 10 + n;
i++;
}
num.push_back(sum);
}
else
sym.push_back(s[i++]);
for (int i = 0; i < sym.size(); i++)
{
if (sym[i] == '/')
{
num[i + 1] = num[i] / num[i + 1];
num[i] = 0;
sym[i] = '+';
}
else if (sym[i] == '*')
{
num[i + 1] = num[i] * num[i + 1];
num[i] = 0;
sym[i] = '+';
}
else
continue;
}
for (int i = 0; i < num.size(); i++)
if (num[i] != 0)
{
resnum.push_back(num[i]);
if (i != num.size() - 1)
ressym.push_back(sym[i]);
}
double sum = resnum[0];
for (int i = 0; i < ressym.size(); i++)
{
if (ressym[i] == '+')
sum += resnum[i + 1];
else
sum -= resnum[i + 1];
}
printf("%.0f\n", sum);
}
return 0;
}
<file_sep>/找最小数(x,y).cpp
#include <algorithm>
#include <iostream>
using namespace std;
struct NUMBER{
int x, y;
};
NUMBER a[1000];
bool cmp( NUMBER a, NUMBER b ){
if( a.x == b.x )
return a.y < b.y;
else return a.x < b.x;
};
int main()
{
int i,n;
while( (cin >> n)!=NULL ){
for( i=0; i<n; i++ )
cin >> a[i].x >> a[i].y;
sort(a,a+n,cmp);
cout << a[0].x << " " << a[0].y << endl;
}
return 0;
}
<file_sep>/求n个成绩的最大值及其最大值个数.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n,num=0;
cout<<"请输入成绩个数:";
cin>>n;
int score[n];
cout<<"请输入"<<n<<"个成绩:"<<endl;
for(int i=0;i<n;i++)
{
cin>>score[i];
}
sort(score,score+n);
for(int i=0;i<=n;i++)
{
if(score[i]==score[n-1])
{
num++;
}
}
cout<<"最大数为:"<<score[n-1]<<endl
<<"最大数个数为:"<<num<<endl;
return 0;
}
<file_sep>/约数个数.cpp
#include <iostream>
#include <cmath>
using namespace std;
int count_ys(int n)
{
int num=0;
if (n == 1) num = 1;
else {
num = 2;
for (int i = 2; i<sqrt(n); i++) {
if (n%i == 0) num += 2;
}
int n1 = (int)sqrt(n);
if (n%n1 == 0 && n1*n1 == n) num ++;
}
return num;
}
int main()
{
int num;
while(cin>>num)
{
int n[num];
for(int i=0;i<num;i++)
{
cin>>n[i];
cout<<count_ys(n[i])<<endl;
}
}
return 0;
}
<file_sep>/数组中的最大值和最小值.cpp
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int num[n];
int max=0,min=100000000;
for(int i=0;i<n;i++)
{
cin>>num[i];
}
sort(num,num+n);
cout<<num[n-1]<<" "<<num[0]<<endl;
}
return 0;
}
<file_sep>/最大上升子序列之和.cpp
#include<iostream>
using namespace std;
int main() {
int N;
int d[1001], dp[1001], sum[1001];
while (cin >> N) {
for (int i = 0; i < N; i++) {
cin >> d[i];
}
int max = 0;
for (int i = 0; i < N; i++) {
sum[i] = d[i];
for (int j = 0; j < i; j++) {
if (d[j] < d[i]) {
sum[i] = sum[j] + d[i] > sum[i] ? sum[j] + d[i] : sum[i];
}
}
if (sum[i] > max)
max = sum[i];
}
cout << max << endl;
}
return 0;
}<file_sep>/哈利波特---魔咒_示例.cpp
#include <iostream>
#include <map>
#include <string>
#include <stdio.h>
using namespace std;
int main(void) {
string str;
while(getline(cin,str)){
map<string,string> word1;
map<string,string> word2;
do{
if(str == "@END@") break;
int t1 = str.find("[",0);
int t2 = str.find("]",0);
string key = str.substr(t1+1,t2-1);
string value = str.substr(t2+2);
word1[key] = value;
word2[value] = key;
}while(getline(cin,str));
int m;
cin >> m;
getchar();
for(int i = 0;i < m;i++) {
getline(cin,str);
string result;
if(str[0]=='[') {
string s = str.substr(1,str.find(']',0)-1);
result = word1[s];
}else {
result = word2[str];
}
if(result.empty()){
cout << "what?" << endl;
}else{
cout << result << endl;
}
}
}
return 0;
}<file_sep>/二叉树寻找公共父节点.cpp
#include <iostream>
#include <math.h>
using namespace std;
int pub(int m,int n)
{
while (m>=1) {
int r1 = (int) (log(n) / log(2));
int r2 = (int) (log(m) / log(2));
int l = m * pow(2, r1 - r2);
int r = m;
for (int i = 0; i < r1 - r2; i++) {
r = r * 2 + 1;
}
if (n >= l && n <= r) {
return m;
} else {
m/= 2;
}
}
return 0;
}
int main() {
int m,n;
while(cin>>m>>n)
{
if(m<n)
{
cout<<pub(m,n)<<endl;
}
else if(m==n)
{
cout<<m<<endl;
}
else
{
cout<<pub(n,m)<<endl;
}
}
return 0;
}<file_sep>/学生成绩排序.cpp
#include <iostream>
#include <algorithm>
using namespace std;
struct Student
{
int sid;
int score;
}stu[100];
bool cmp(Student s1,Student s2)
{
if(s1.score!=s2.score)
{
return s1.score<s2.score;
}
return s1.sid<s2.sid;
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
cin>>stu[i].sid>>stu[i].score;
}
sort(stu,stu+n,cmp);
for(int i=0;i<n;i++)
{
cout<<stu[i].sid<<" "<<stu[i].score<<endl;
}
}
return 0;
}
<file_sep>/整数拆分.cpp
#include <iostream>
#define MaxSize 1000000
using namespace std;
int main() {
int a[MaxSize + 1], N;
a[0] = a[1] = 1;
for (int i = 2; i <= MaxSize; i++)
if (i % 2 == 0)
a[i] = (a[i - 1] + a[i / 2]) % 1000000000;
else
a[i] = a[i - 1];
while (cin >> N)
cout << a[N] << endl;
return 0;
}
<file_sep>/简单密码.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
string str1,str2,str3;
while(cin>>str1 && str1!="ENDOFINPUT")
{
getchar();
getline(cin,str2);
cin>>str3;
for(int i=0;i<str2.length();i++)
{
if(str2[i]>='A' && str2[i]<='E')
{
cout<<char(((int)str2[i])+21 );
}
else if(str2[i]>='F' && str2[i]<='Z')
{
cout<<char(str2[i]-5);
}
else
{
cout<<str2[i];
}
}
cout<<endl;
}
return 0;
}
<file_sep>/游船出租.cpp
#include <cstdio>
#include <cstring>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
const int maxn = 101;
const int inf = 0x3f3f3f3f;
int ship[maxn];
int main() {
int ship_index;
int total_time = 0, rent_time = 0;
bool exi = false;
char flag;
int hours, mins;
while (1) {
exi = false;
total_time = rent_time = 0;
memset(ship, 0x3f, sizeof ship);
while (scanf("%d", &ship_index)) {
getchar();
if (!ship_index) {
scanf("%c %d:%d", &flag, &hours, &mins);
printf("%d %d\n", rent_time,
rent_time ? (int)((float)total_time / rent_time + 0.5f) : 0);
break;
} else if (ship_index == -1) {
exi = true;
break;
}
scanf("%c %d:%d", &flag, &hours, &mins);
if (flag == 'S')
ship[ship_index] = hours * 60 + mins;
else if (ship[ship_index] != inf) {
total_time += hours * 60 + mins - ship[ship_index];
++rent_time;
// ship[ship_index] = inf;
}
}
if (exi)
break;
}
return 0;
}
<file_sep>/二进制数中的1的个数---负数用补码表示.java
import java.util.*;
public class Main {
public static int NumberOf1(int n) {
return Integer.toBinaryString(n).replaceAll("0","").length(); }
public static void main(String[] args)
{
int n;
Scanner in=new Scanner(System.in);
n=in.nextInt();
Main s=new Main();
System.out.println(NumberOf1(n));
}
}<file_sep>/ZOJ问题.cpp
#include"stdio.h"
#include"string.h"
int main(){
char d[1001];
int index_z,index_j,a,b,c;
while(~scanf("%s",d)){
index_z=-1;
int i;
index_j=-1;
for(i=0;i<strlen(d);i++){
if(d[i]=='z')
index_z=i;
if(d[i]=='j')
index_j=i;
}
if(index_z==-1||index_j==-1)
printf("Wrong Answer\n");
else{
a=index_z;
b=index_j-index_z-1;
c=i-index_j-1;
if (b==0)
{
printf("Wrong Answer\n");
}
else if (a*b == c)
{
printf("Accepted\n");
}
else
{
printf("Wrong Answer\n");
}
}
}
}
<file_sep>/H6.java
import java.security.KeyStore.Entry;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
public class H6 {
public static void main(String[] args) {
// TODO Auto-generated method stub
String[] s={"A","B","C","D","E","F","G"};
int [] w={7,5,3,2,6,1,4,9};
int n=5;
String [] ss=topN(s,w,5);
for(int j=0;j<ss.length;j++)
{
System.out.print(ss[j]+" ");
}
}
public static String[] topN(String[] s,int[] w,int n)
{
Map<String,Integer>m=new LinkedHashMap<String,Integer>();
for(int i=0;i<s.length;i++)
{
int score=w[i]+i+1;
m.put(s[i], score);
}
Map mu=new LinkedHashMap<String,Integer>();
mu=sortMap(m);
String [] str=new String[n];
int k=0;
Iterator it = mu.entrySet().iterator();
while(it.hasNext() && k<=n-1){
Map.Entry e = (Map.Entry) it.next();
str[k]=(String) e.getKey();
k++;}
return str;
}
private static void printMap(Map map){
System.out.println("===================mapStart==================");
Iterator it = map.entrySet().iterator();
while(it.hasNext()){
Map.Entry entry = (Map.Entry) it.next();
System.out.println(entry.getKey() + ":" + entry.getValue());
}
System.out.println("===================mapEnd==================");
}
public static Map sortMap(Map oldMap) {
ArrayList<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(oldMap.entrySet());
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(java.util.Map.Entry<String, Integer> arg0,
java.util.Map.Entry<String, Integer> arg1) {
return arg0.getValue() - arg1.getValue(); }
});
Map newMap = new LinkedHashMap();
for (int i = 0; i < list.size(); i++) {
newMap.put(list.get(i).getKey(), list.get(i).getValue());
}
return newMap;
}
}
<file_sep>/字符串反序输出.cpp
#include <iostream>
using namespace std;
int main()
{
string str;
while(cin>>str)
{
for(int i=str.length()-1;i>=0;i--)
{
cout<<str[i];
}
cout<<endl;
}
return 0;
}
<file_sep>/回文数.cpp
#include <iostream>
#include <string>
using namespace std;
int main()
{
l:
string str;
while(cin>>str)
{
while(str.length()>1000)
{
cout<<"ÇëÊäÈë0-1000³¤¶ÈµÄ×Ö·û´®£¡"<<endl;
}
for(int i=0;i<str.length()/2;i++)
{
if(str[i]!=str[str.length()-1-i])
{
cout<<"No!"<<endl;
goto l;
}
}
cout<<"Yes!"<<endl;
}
return 0;
}
<file_sep>/Skew.cpp
#include <iostream>
#include <math.h>
using namespace std;
int main() {
string str;
while(cin>>str && str!="0")
{
int sum=0;
int m=1;
for(int i=str.length()-1;i>=0;i--)
{
sum+=(str[i]-'0')*(long)(pow(2,m)-1);
m++;
}
cout<<sum<<endl;
}
return 0;
}<file_sep>/旋转矩阵.cpp
#include<stdio.h>
#include<iostream>
using namespace std;
int main()
{
int n;
int mat1[10][10];
int mat2[10][10];
while((cin>>n)!=0)
{
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin>>mat1[i][j];
for(int i=0; i<n; i++)
for(int j=0; j<n; j++)
cin>>mat2[i][j];
int flag=4;
int f[4]= {0};
for(int i=0; i<n; i++)
{
for(int j=0; j<n; j++)
{
if(mat2[i][j]==mat1[i][j])
f[0]++;
if(mat2[j][n-i-1]==mat1[i][j])
f[1]++;
if(mat2[n-i-1][n-j-1]==mat1[i][j])
f[2]++;
if(mat2[n-j-1][i]==mat1[i][j])
f[3]++;
}
}
int pro=n*n;
for(int i=0; i<4; i++)
{
if(f[i]==pro)
{
flag=i;
break;
}
}
if(flag==0)
printf("0\n");
else if(flag==1)
printf("90\n");
else if(flag==2)
printf("180\n");
else if(flag==3)
printf("270\n");
else
printf("-1\n");
}
return 0;
}
<file_sep>/H9.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
public class H9 {
public static void main(String[] args) {
// TODO Auto-generated method stub
System.out.println(Test("C"));
}
public static String Test(String str)
{
String [] keys={"A","B","C","D","E","F","G","H","I"};
Map<String ,String[]> m=new LinkedHashMap<String ,String[]>();
String[] sa={"B","C","D","E","F","G","H","I"};
m.put("A", sa);
String[] sb={"E"};
m.put("B", sb);
String[] sc={"F","G","H"};
m.put("C", sc);
String[] sd={"I"};
m.put("D", sd);
String ss="";
for (Map.Entry<String ,String[]> e : m.entrySet()) {
//System.out.println(e.getKey());
if(e.getKey().equals(str))
{
//System.out.println(e.getKey());
for(int i=0;i<9;i++)
{
for(int j=0;j<e.getValue().length;j++)
{
if(keys[i].equals(e.getValue()[j]))
{
keys[i]="0";
}
}
if(keys[i].equals(e.getKey()))
{
keys[i]="0";
}
}
for(int i=0;i<9;i++)
{
//System.out.print(keys[i]+" ");
if(!keys[i].equals("0"))
{
ss=ss+keys[i];
}
}
break;
}
}
return ss;
}
}
<file_sep>/平方因子.cpp
#include<iostream>
using namespace std;
int main()
{
int n;
while(cin>>n && n)
{
int i=2;
int count=0;
while((i*i)<=n)
{
if(n%(i*i)==0)
{
count++;
}
i++;
}
if(count>0)
{
cout<<"Yes"<<endl;
}
else
{
cout<<"No"<<endl;
}
}
return 0;
}
<file_sep>/WERTYU.cpp
#include<iostream>
#include<string>
#include<cctype>
#include<cstring>
using namespace std;
int main() {
char s[] = "`1234567890-=QWERTYUIOP[]\\ASDFGHJKL;'ZXCVBNM,./";
string str;
while (getline(cin,str)) {
for (int i = 0; i < str.length(); i++) {
if (isspace(str[i])) {
cout << str[i];
continue;
}
int j;
for (j = 1; j < strlen(s); j++)
if (s[j] == str[i])
break;
cout << s[j - 1];
}
cout << endl;
}
return 0;
}
<file_sep>/第k个质数.cpp
#include <iostream>
#include <cmath>
using namespace std;
bool isPrime(int k)
{
if(k==1) return false;
if( k == 2)
return true;
for(int i = 2;i<=sqrt(k);i++){
if(k%i == 0)
return false;
}
return true;
}
int main()
{
int n;
while(cin>>n)
{
int count=0;
int i=1;
while(count<n)
{
if(isPrime(i))
{
count++;
}
i++;
}
cout<<i-1<<endl;
}
return 0;
}
<file_sep>/最大相邻差值.cpp
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int findMaxDivision(vector<int> A, int n) {
sort(A.begin(),A.end());
int diff[n-1];
for(int i=1;i<n;i++)
{
diff[i-1]=A[i]-A[i-1];
}
sort(diff,diff+(n-1));
return diff[n-2];
}
int main()
{
int n;
while(cin>>n)
{
vector<int> num;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
num.push_back(t);
}
cout<<findMaxDivision(num,n)<<endl;
}
return 0;
}
<file_sep>/最大子矩阵.cpp
#include <iostream>
using namespace std;
int f(int B[], int N) {
int i, max = B[0], sum = 0;
for (i = 0; i < N; i++) {
sum += B[i];
if (sum < B[i])
sum = B[i];
if (sum > max)
max = sum;
}
return max;
}
int main() {
int N, A[100][100];
while (cin >> N) {
for (int i = 0; i < N; i++)
for (int j = 0; j < N; j++)
cin >> A[i][j];
int B[100] = { 0 }, max = 0, sum = 0;
for (int i = 0; i < N; i++) { //起始行
for (int j = i; j < N; j++) { //终止行
for (int k = 0; k < N; k++) //列相加
B[k] += A[j][k];
sum = f(B, N);
if (sum > max)
max = sum;
}
for (int k = 0; k < N; k++)
B[k] = 0;
}
cout << max << endl;
}
}
<file_sep>/Freckle.cpp
#include<iostream>
#include <iomanip>
#include<string>
#include <string.h>
#include<math.h>
#include<vector>
#include<sstream>
#include<algorithm>
#include<stack>
#include<queue>
#include<functional>
using namespace std;
int Tree[101];
int findRoot(int x)
{
if (Tree[x]==-1)
{
return x;
}
int tmp = findRoot(Tree[x]);
Tree[x] = tmp;
return tmp;
}
struct point
{
double x;
double y;
double getDistance(point A)
{
double ans = (x - A.x)*(x - A.x) + (y - A.y)*(y - A.y);
return sqrt(ans);
}
}Points[101];
struct edge
{
int a;
int b;
double length;
bool operator <(const edge &E) const{
return length < E.length;
}
}Edges[6000];
int main()
{
int n;
while(~scanf("%d",&n))
{
for (int i = 1; i <= n;i++)
{
scanf("%lf%lf", &Points[i].x, &Points[i].y);
Tree[i] = -1;
}
int size = 0;
for (int i = 1; i <= n;i++)
{
for (int j = i+1; j <= n;j++)
{
Edges[size].a =i;
Edges[size].b = j;
Edges[size].length = Points[i].getDistance(Points[j]);
size++;
}
}
sort(Edges, Edges + size-1);
double ans = 0;
for (int i = 0; i < size;i++)
{
int a = findRoot(Edges[i].a);
int b = findRoot(Edges[i].b);
if (a!=b)
{
Tree[a] = b;
ans += Edges[i].length;
}
}
printf("%.2lf\n", ans);
}
return 0;
}
<file_sep>/Graduate Admission.cpp
#include <iostream>
#include <vector>
#include <cstdio>
#include <algorithm>
#include <functional>
using namespace std;
int choice;
struct Node{
int id;
int rank;
int sco1;
int sco2;
vector<int> will;
Node()
{
rank = 0;
will.resize(choice);
}
bool operator>(const Node &n) const
{
if(sco1+sco2!=n.sco1+n.sco2) return sco1+sco2>n.sco1+n.sco2;
else return sco1>n.sco1;
}
};
int main()
{
//freopen("t.txt", "r", stdin);
int Num, school;
scanf("%d %d %d", &Num, &school, &choice);
vector<int> Full(school);
for(int i=0; i<school;i++) cin>>Full[i];
vector<Node> Stu;
Stu.resize(Num);
vector<int> luqu[100];//学校最多100个
vector<int> maxrank;
maxrank.resize(school);
for(int i=0; i<Num; i++)
{
scanf("%d %d",&Stu[i].sco1, &Stu[i].sco2);
for(int j=0; j<choice; j++) scanf("%d", &Stu[i].will[j]);
Stu[i].id = i;
}
sort(Stu.begin(), Stu.end(), greater<Node>());
int nowrank = 1, nowsc = Stu[0].sco1+Stu[0].sco2, nowsc1=Stu[0].sco1, tmp = 0;
for(int i=0; i<Stu.size(); i++)
{
if(Stu[i].sco1+Stu[i].sco2==nowsc)
{
if(Stu[i].sco1==nowsc1)
{
Stu[i].rank = nowrank;
tmp++;
}
else
{
nowsc1 = Stu[i].sco1;
Stu[i].rank = nowrank + tmp;
nowrank += tmp;
tmp = 1;
}
}
else//小于
{
Stu[i].rank = nowrank + tmp;
nowsc = Stu[i].sco1+Stu[i].sco2;
nowsc1 = Stu[i].sco1;
nowrank += tmp;
tmp = 1;
}
}
for(int i=0; i<Stu.size(); i++)//对每一个学生
{
for(int j = 0; j<choice; j++)//想报哪个学校
{
if(Full[Stu[i].will[j]]>0)//还有名额
{
luqu[Stu[i].will[j]].push_back(Stu[i].id);
maxrank[Stu[i].will[j]] = Stu[i].rank;
Full[Stu[i].will[j]]--;
break;
}
else if(maxrank[Stu[i].will[j]] == Stu[i].rank)
{
luqu[Stu[i].will[j]].push_back(Stu[i].id);
break;
}
}
}
for(int i=0; i<school; i++)
sort(luqu[i].begin(), luqu[i].end(), less<int>());
for(int i=0; i<school; i++)
{
for(int j=0; j<luqu[i].size(); j++)
{
printf("%d", luqu[i][j]);
if(j!=luqu[i].size()-1) printf(" ");
}
cout<<endl;
}
return 0;
}
<file_sep>/输出字符串的全排列_yjd.cpp
#include<iostream>
#include <cstring>
using namespace std;
#include<assert.h>
void Permutation(char* pStr, char* pBegin)
{
assert(pStr && pBegin);
if(*pBegin == '\0')
printf("%s\n",pStr);
else
{
for(char* pCh = pBegin; *pCh != '\0'; pCh++)
{
swap(*pBegin,*pCh);
Permutation(pStr, pBegin+1);
swap(*pBegin,*pCh);
}
}
}
int main() {
string str;
while (cin>>str)
{
char *ch=new char(str.length()+1);
strcpy(ch,str.c_str());
Permutation(ch,ch);
}
return 0;
}
<file_sep>/左右最值最大值.cpp
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
using namespace std;
int findMaxGap(vector<int> A, int n) {
// write code here
vector<int> v;
for(int k=0;k<=n-2;k++)
{
vector<int> left;
for(int j=0;j<=k;j++)
{
left.push_back(A[j]);
}
vector<int> right;
for(int m=k+1;m<=n-1;m++)
{
right.push_back(A[m]);
}
sort(left.begin(),left.end());
sort(right.begin(),right.end());
v.push_back(abs(left[left.size()-1]-right[right.size()-1]));
}
sort(v.begin(),v.end());
return v[v.size()-1];
}
int main()
{
int n;
while(cin>>n)
{
vector<int> A;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
A.push_back(t);
}
cout<<findMaxGap(A,n)<<endl;
}
return 0;
}
<file_sep>/无向图的连通图(yjd).cpp
#include <iostream>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m && n)
{
int ma[n][n];
int arr[n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
ma[i][j]=0;
}
}
for(int i=0;i<m;i++)
{
int i1,j1;
cin>>i1>>j1;
ma[i1-1][j1-1]=1;
ma[j1-1][i1-1]=ma[i1-1][j1-1];
}/*
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<ma[i][j]<<" ";
}
cout<<endl;
}*/
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
if(ma[i][j]==1 && i!=j)
{
arr[j]=1;
}
}
}
int count=0;
for(int i=0;i<n;i++)
{
if(arr[i]==1)
{
count++;
}
}
if(count!=n)
{
cout<<"NO"<<endl;
}
else
{
cout<<"YES"<<endl;
}
}
return 0;
}
<file_sep>/变态跳台阶---一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法.cpp
#include <iostream>
using namespace std;
int jumpFloorII(int number) {
int method = 0;
if(number==0)return 1;
for(int i=1;i<=number;i++){
method += jumpFloorII(number-i);
}
return method;
}
int main()
{
int n;
while(cin>>n)
{
cout<<jumpFloorII(n)<<endl;
}
return 0;
}
<file_sep>/Digital Root.cpp
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
long num;
while(cin>>num && num)
{
if(num>=1 && num<=9)
{
cout<<num<<endl;
}
else
{
while(num>9)
{
ostringstream s1;
s1 << num << endl;
string s2 = s1.str();
num=0;
for(int i=0;i<s2.length();i++)
{
int t=0;
istringstream ss(s2.substr(i,1));
ss>>t;
num+=t;
}
}
cout<<num<<endl;
}
}
return 0;
}
<file_sep>/ZOJ.cpp
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
using namespace std;
bool cmp(char a, char b){
return a > b;
}
int main()
{
char zoj[101], *z, *o, *j;
while(gets(zoj) && zoj[0] != 'E'){
sort(zoj, zoj + strlen(zoj), cmp);
z = zoj;
while(*z != 'Z' && *z != '\0')
z ++;
o = zoj;
while(*o != 'O' && *o != '\0')
o ++;
j = zoj;
while(*j != 'J' && *j != '\0')
j ++;
while(*z == 'Z' || *o == 'O' || *j == 'J'){
if(*z == 'Z'){
cout << 'Z';
z ++;
}
if(*o == 'O'){
cout << 'O';
o ++;
}
if(*j == 'J'){
cout << 'J';
j ++;
}
}
cout << endl;
}
return 0;
}
<file_sep>/字符串拼接.cpp
#include <iostream>
#include <cstring>
using namespace std;
int main()
{
int n;
string s1,s2;
while(cin>>s1>>s2)
{
while(s1.length()<1 ||s1.length()>100 ||s2.length()<1 || s2.length()>100)
{
cin>>s1>>s2;
}
cout<<s1+s2<<endl;
}
return 0;
}
<file_sep>/树查找.cpp
#include<iostream>
#include<vector>
#include<string>
using namespace std;
int deepandcount(int x)
{
int res;
if (x == 1)
res = 1;
else
{
int sum = 1;
for (int i = 1; i < x; i++)
sum = sum * 2;
res = sum;
}
return res;
}
int main()
{
int length, num, deep;
while (cin >> length)
{
vector<int> data;
for (int i = 0; i < length; i++)
{
cin >> num;
data.push_back(num);
}
cin >> deep;
if (deepandcount(deep) > length)
{
cout << "EMPTY" << endl;
continue;
}
for (int i = deepandcount(deep) - 1; i < length && i < deepandcount(deep + 1) - 1; i++)
{
cout << data[i];
if (i == deepandcount(deep + 1) - 2 || i == length - 1)
break;
else
cout << " ";
}
cout << endl;
}
return 0;
}<file_sep>/字符串的匹配.java
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
class result
{
public result(int i, String string) {
// TODO Auto-generated constructor stub
this.line=i;
this.value=string;
}
public int line;
public String value;
}
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(input.hasNext()){
int n = input.nextInt();
String []str = new String[n];
for(int i = 0;i<n;i++)
str[i] = input.next();
String str2=input.next();
match(str,str2);
}
}
public static void match(String[] str,String str2)
{
//Map<String,Integer> printstr=new LinkedHashMap<String,Integer>();
ArrayList<result> printstr=new ArrayList<result>();
if(str2.contains("["))
{
String [] str2_up=new String[1000];
int b = 0,e = 0;
for(int i=0;i<str2.length();i++)
{
if(str2.substring(i,i+1).equals("["))
{
b=i;
}
if(str2.substring(i,i+1).equals("]"))
{
e=i;
}
}
int m=0;
for(int i=b+1;i<=e-1;i++)
{
str2_up[m]=str2.substring(0,b)+str2.substring(i,i+1)+str2.substring(e+1);
m++;
}
int k=0;
for(int i=0;i<m;i++)
{
for(int j=0;j<str.length;j++)
{
if(str2_up[i].toLowerCase().equals(str[j].toLowerCase()))
{
printstr.add(new result(j+1,str[j]));
}
}
}
for(int i=0;i<printstr.size();i++)
{
System.out.println(printstr.get(i).line+" "+printstr.get(i).value);
}
}
else
{
for(int i=0;i<str.length;i++)
{
if(str[i].toLowerCase().equals(str2.toLowerCase()))
{
System.out.println((i+1)+" "+str[i]);
}
}
}
}
}<file_sep>/(A+B)给定两个整数A和B,其表示形式是:从个位开始,每三位数用逗号,隔开。 现在请计算A+B的结果,并以正常形式输出。 .java
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
String num1=sc.next();
String num2=sc.next();
String[] a1=num1.split(",");
String[] a2=num2.split(",");
int n1=0;
int n2=0;
if(!num1.startsWith("-"))
{
for(int i=a1.length-1;i>=0;i--)
{
n1+=Integer.parseInt(a1[i])*Math.pow(10, (a1.length-1-i)*3);
}
if(!num2.startsWith("-"))
{
for(int i=a2.length-1;i>=0;i--)
{
n2+=Integer.parseInt(a2[i])*Math.pow(10, (a2.length-1-i)*3);
}
}
else
{
for(int i=a2.length-1;i>=0;i--)
{
n2+=Math.abs(Integer.parseInt(a2[i]))*Math.pow(10, (a2.length-1-i)*3);
}
n2*=-1;
}
}
else
{
for(int i=a1.length-1;i>=0;i--)
{
n1+=Math.abs(Integer.parseInt(a1[i]))*Math.pow(10, (a1.length-1-i)*3);
}
n1*=-1;
if(!num2.startsWith("-"))
{
for(int i=a2.length-1;i>=0;i--)
{
n2+=Integer.parseInt(a2[i])*Math.pow(10, (a2.length-1-i)*3);
}
}
else
{
for(int i=a2.length-1;i>=0;i--)
{
n2+=Math.abs(Integer.parseInt(a2[i]))*Math.pow(10, (a2.length-1-i)*3);
}
n2*=-1;
}
}
System.out.println(n1+n2);
}
}
}<file_sep>/今天是第几天.cpp
#include <iostream>
using namespace std;
int main()
{
int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int year,month,day;
int sum=0;
while(cin>>year>>month>>day)
{
if((year%4==0 && year%100!=0 ) || year%400==0)
{
days[1]=29;
}
else
{
days[1]=28;
}
for(int i=0;i<month-1;i++)
{
sum+=days[i];
}
sum=sum+day;
cout<<sum<<endl;
sum=0;
}
return 0;
}
<file_sep>/字符串中的字符数.cpp
#include <iostream>
using namespace std;
int main()
{
string str;
while(getline(cin,str) && str!="#")
{
string str1;
getline(cin,str1);
for(int i=0;i<str.length();i++)
{
int count=0;
for(int j=0;j<str1.length();j++)
{
if(str.substr(i,1)==str1.substr(j,1))
{
count++;
}
}
cout<<str.substr(i,1)<<" "<<count<<endl;
}
}
return 0;
}
<file_sep>/递推数列.java
import java.math.BigInteger;
import java.util.Scanner;
/**
* Created by 22291_000 on 2017/6/16.
*/
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
BigInteger a,b,p,q;
int k;
while(in.hasNext())
{
a=in.nextBigInteger();
b=in.nextBigInteger();
p=in.nextBigInteger();
q=in.nextBigInteger();
k=in.nextInt();
BigInteger [] n=new BigInteger[k+1];
n[0]=a;
n[1]=b;
for(int i=2;i<=k;i++)
{
n[i]=p.multiply(n[i-1]).add(q.multiply(n[i-2]));
}
System.out.println(n[k].mod(BigInteger.valueOf(10000)));
}
}
}
<file_sep>/N阶楼梯上楼问题:一次可以走两阶或一阶,问有多少种上楼方式。(要求采用非递归).cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>90)
{
cin>>n;
}
if(n==1)
{
cout<<1<<endl;
}
if(n==2)
{
cout<<2<<endl;
}
if(n>2)
{
long long f1=1;
long long f2=2;
for(int i=3;i<=n;++i)
{
f2+=f1;
f1=f2-f1;
}
cout<<f2<<endl;
}
}
return 0;
}
<file_sep>/二叉排序树 (2).cpp
#include <iostream>
typedef struct node
{
int key;
node* lchild;
node* rchild;
}*Node;
class BinarySortTree
{
private:
Node root;
void _insert(Node &root,int key)
{
if(!root)
{
Node n = new node;
n->key = key;
n->lchild = n->rchild = NULL;
root = n;
}
else if(root->key>key)
{
insertParentNode = root;
_insert(root->lchild,key);
}
else
{
insertParentNode = root;
_insert(root->rchild,key);
}
}
void destory(Node &root)
{
if(root)
{
destory(root->lchild);
destory(root->rchild);
delete root;
}
}
public:
Node insertParentNode;
BinarySortTree(){ root = NULL; insertParentNode = NULL;}
~BinarySortTree() { destory(root);}
void insert(int key)
{
_insert(root,key);
}
};
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int t;
BinarySortTree *bst = new BinarySortTree();
while(n--)
{
cin>>t;
bst->insert(t);
if(bst->insertParentNode==NULL)
{
cout<<"-1"<<"\n";
}else
cout<<bst->insertParentNode->key<<"\n";
}
delete bst;
}
}
<file_sep>/判断链表的回文结构.cpp
struct ListNode {
int val;
ListNode *next;
} ;
bool chkPalindrome(ListNode* A) {
// write code here
int data[10000];
int i=0;
ListNode* p=A;
while(p)
{
data[i++]=p->val;
p=p->next;
}
int k=0;
for (int j=i-1;j>=i/2;j--)
{
if (data[j]==data[k++])
continue;
else
return false;
}
return true;
}
<file_sep>/日期差值.cpp
#include <iostream>
#include <sstream>
#include <algorithm>
using namespace std;
struct ymdays
{
int year;
int month;
int day;
}days[2];
bool cmp(ymdays y1,ymdays y2)
{
if(y1.year!=y2.year)
{
return y1.year<y2.year;
}
else if(y1.month!=y2.month)
{
return y1.month<y2.month;
}
else
{
return y1.day<y2.day;
}
}
int jt(int year,int month,int day)
{
int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};
int sum=0;
if((year%4==0 && year%100!=0 ) || year%400==0)
{
days[1]=29;
}
else
{
days[1]=28;
}
for(int i=0;i<month-1;i++)
{
sum+=days[i];
}
sum=sum+day;
return sum;
}
int main()
{
string y1,y2;
while(cin>>y1>>y2)
{
istringstream s(y1.substr(0,4));
int y1_year;
s>>y1_year;
istringstream ss(y1.substr(4,2));
int y1_month;
ss>>y1_month;
istringstream sss(y1.substr(6,2));
int y1_day;
sss>>y1_day;
days[0].year=y1_year;
days[0].month=y1_month;
days[0].day=y1_day;
istringstream s2(y2.substr(0,4));
int y2_year;
s2>>y2_year;
istringstream ss2(y2.substr(4,2));
int y2_month;
ss2>>y2_month;
istringstream sss2(y2.substr(6,2));
int y2_day;
sss2>>y2_day;
days[1].year=y2_year;
days[1].month=y2_month;
days[1].day=y2_day;
sort(days,days+2,cmp);
int sum_min=jt(days[0].year,days[0].month,days[0].day);
int sum_max=jt(days[1].year,days[1].month,days[1].day);
int t=days[1].year-days[0].year;
if(t==0)
{
cout<<sum_max-sum_min+1<<endl;
}
else
{
int s=0;
for(int i=1;i<=t;i++)
{
if(((days[0].year+i-1)%4==0 && (days[0].year+i-1)%100!=0 ) || (days[0].year+i-1)%400==0)
{
s+=366;
}
else
{
s+=365;
}
}
s+=sum_max;
cout<<s-sum_min+1<<endl;
}
}
return 0;
}
<file_sep>/最短路径问题.cpp
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
#define N 1001
#define INF 0x3f3f3f3f
int n,m,adj[N][N],cost[N][N],visit[N],lowdis[N],lowcos[N];
void dijkstra(int s, int t)
{
memset(visit,0,sizeof(visit));
visit[s] = 1;
lowdis[s] = lowcos[s] = 0;
for(int i=1;i<=n;i++)
if(i != s)
{
lowdis[i] = adj[s][i];
lowcos[i] = cost[s][i];
}
int pos = s;
for(int i=1;i<n;i++)
{
int mindis = INF;
for(int j=1;j<=n;j++)
if(!visit[j] && lowdis[j] < mindis)
{
mindis = lowdis[j];
pos = j;
}
if(mindis == INF)
break;
visit[pos] = 1;
for(int j=1;j<=n;j++)
if(adj[pos][j] != INF && cost[pos][j] != INF && (lowdis[j] >= lowdis[pos] + adj[pos][j]))
{
if((lowdis[j] == lowdis[pos] + adj[pos][j] && lowcos[j] > lowcos[pos] + cost[pos][j]) || (lowdis[j] > lowdis[pos] + adj[pos][j]))
lowcos[j] = lowcos[pos] + cost[pos][j];
lowdis[j] = lowdis[pos] + adj[pos][j];
}
}
printf("%d %d\n",lowdis[t],lowcos[t]);
}
int main()
{
while(scanf("%d %d",&n,&m) != EOF)
{
if(n == 0 && m == 0)
break;
for(int i=1;i<=n;i++)
for(int j=1;j<=n;j++)
adj[i][j] = cost[i][j] = INF;
while(m--)
{
int a,b,d,p;
scanf("%d %d %d %d",&a,&b,&d,&p);
if(d < adj[a][b])
{
adj[a][b] = adj[b][a] = d;
cost[a][b] = cost[b][a] = p;
}
else if(d == adj[a][b] && p < cost[a][b])
cost[a][b] = cost[b][a] = p;
}
int s,t;
scanf("%d %d",&s,&t);
dijkstra(s,t);
}
return 0;
}<file_sep>/最小面积子矩阵.cpp
#include <iostream>
#include <cstring>
using namespace std;
int matrix[110][110];
int num[110];
int N,M;
int K;
void my_merge(int i,int j)
{
for(int p = 0;p<N;p++)
{
for(int q = i;q <= j; q++)
num[p] += matrix[p][q];
}
}
int findShort()
{
int start = 0,e = 0;
int sum = 0;
int len = N;
int ans = len+1;
bool flag = false;
while(e < len)
{
if(sum < K) sum += num[e];
while(sum >= K)
{
flag = true;
ans = min(ans,e-start+1);
sum -= num[start++];
}
e++;
}
if(flag) return ans;
else return N*M;
}
int main()
{
while(cin>>N>>M>>K)
{
int sum = 0;
for(int i = 0;i<N;i++)
{
for(int j = 0;j<M;j++)
{
cin>>matrix[i][j];
sum += matrix[i][j];
}
}
if(sum < K) cout<<-1<<endl;
else
{
int minn = N*M;
for(int i = 0;i<M;i++)
{
for(int j = i;j<M;j++)
{
memset(num,0,sizeof(num));
my_merge(i,j);
int tmp = findShort();
tmp = (j-i+1)*tmp;
if(minn > tmp) minn = tmp;
}
}
cout<<minn<<endl;
}
}
return 0;
}
<file_sep>/特殊排序(输入一系列整数,将其中最大的数挑出,并将剩下的数进行排序。 ).cpp
#include <iostream>
using namespace std;
int main()
{
int n;
int num[1000];
while(cin>>n)
{
while(n<1 || n>1000)
{
cin>>n;
}
for(int i=0;i<n;i++)
{
cin>>num[i];
}
if(n==1)
{
cout<<num[0]<<endl<<-1<<endl;
}
else
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(num[j] > num[j + 1])
{
int temp = num[j];
num[j] = num[j + 1];
num[j + 1] = temp;
}
}
}
cout<<num[n-1]<<endl;
for(int i=0;i<n-1;i++)
{
if(i!=n-2)
{
cout<<num[i]<<" ";
}
else
{
cout<<num[i]<<endl;
}
}
}
}
return 0;
}
<file_sep>/排列(转换为二进制后求末尾0个数).java
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main{
public static void main(String[] args){
Scanner input = new Scanner(System.in);
while(input.hasNext()){
int n = input.nextInt();
int m=input.nextInt();
if(n==0)
{
break;
}
else
{
BigInteger bigInt = BigInteger.valueOf(1);
for(int i=0;i<m;i++)
{
bigInt=bigInt.multiply(BigInteger.valueOf(n-i));
}
String str=change(bigInt.toString(),10,2);
int count=0;
for(int i=str.length()-1;i>=0;i--)
{
if(str.charAt(i)=='0'){
count++;
}
else
{
break;
}
}
System.out.println(count);
}
}
}
private static String change(String num,int from, int to){
return new java.math.BigInteger(num, from).toString(to);
}
}
<file_sep>/数字反转.cpp
#include<iostream>
using namespace std;
int reverse(int num)
{
int res=0;
while(num)
{
int lei=num%10;
res=res*10+lei;
num/=10;
}
return res;
}
int main()
{
int n;
cin>>n;
while(n--)
{
int a,b;
cin>>a>>b;
int a1=reverse(a);
int b1=reverse(b);
int c1=reverse(a+b);
if(a1+b1==c1)
cout<<a+b<<endl;
else
cout<<"NO"<<endl;
}
return 0;
}
<file_sep>/怪异的洗牌(示例).cpp
#include <iostream>
#include <algorithm>
using namespace std;
int n;
int buff[1001];
void shift(int x) {
reverse(buff+1,buff+x+1);
reverse(buff+x+1,buff+n+1);
reverse(buff+1,buff+n+1);
}
void flip() {
int s = (n%2==0)?n/2:(n-1)/2;
reverse(buff+1,buff+s+1);
}
int main(void) {
while(cin >> n) {
if(n==0) break;
for(int i = 1;i <= n;i++) buff[i] = i;
int k,x;
cin >> k;
while(k--) {
cin >> x;
shift(x);
flip();
}
for(int i = 1;i <= n;i++) cout << buff[i] << " ";
cout << endl;
}
return 0;
}
<file_sep>/输入一个链表,返回从尾到头每个节点的值组成的集合。.cpp
#include <iostream>
#include <cstring>
#include <vector>
using namespace std;
struct ListNode {
int val;
struct ListNode *next;
ListNode(int x) :
val(x), next(NULL) {
}
};
vector<int> printListFromTailToHead(ListNode* head) {
vector<int> v;
vector<int> v2;
ListNode *node=head;
while(node)
{
v.push_back(node->val);
node=node->next;
}
for(int i=v.size()-1;i>=0;i--)
{
v2.push_back(v[i]);
}
return v2;
}
int main()
{
ListNode *n1=new ListNode(1);
ListNode *n2=new ListNode(2);
ListNode *n3=new ListNode(3);
n1->next=n2;
n2->next=n3;
vector<int> v=printListFromTailToHead(n1);
for(int i=0;i<v.size();i++ )
{
cout<<v[i]<<" ";
}
return 0;
}
<file_sep>/倒序输出整数序列.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int num[n];
for(int i=0;i<n;i++)
{
cin>>num[i];
}
cout<<num[n-1];
for(int i=n-2;i>=0;i--)
{
cout<<" "<<num[i];
}
cout<<endl;
}
return 0;
}
<file_sep>/输入年份和天数来判断是几月几号.java
package c;
import java.util.Scanner;
import io.netty.handler.codec.spdy.SpdyStreamFrame;
public class P1 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner in =new Scanner(System.in);
int months[]={31,28,31,30,31,30,31,31,30,31,30,31};
while(in.hasNext())
{
int year=in.nextInt();
int days=in.nextInt();
if(isR(year))
{
months[1]=29;
}
else
{
months[1]=28;
}
int sum=0;
int m=0;
for(int i=0;i<12;i++)
{
sum+=months[i];
if(sum>=days)
{
m=i+1;
break;
}
}
System.out.println(m+"月"+(days-(sum-months[m-1]))+"日");
}
}
public static boolean isR(int year)
{
if((year%4==0 && year%100!=0) || year%400==0)
{
return true;
}
return false;
}
}
<file_sep>/后缀字符串比较.cpp
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool cmp(string s1,string s2)
{
return s1<s2;
}
int main()
{
string str;
while(cin>>str)
{
string s[100000];
for(int i=0;i<str.length();i++)
{
s[i]=str.substr(i,str.length()-i);
}
sort(s,s+str.length(),cmp);
for(int i=0;i<str.length();i++)
{
cout<<s[i]<<endl;
}
}
return 0;
}
<file_sep>/代理服务器.cpp
#include<iostream>
#include<cstring>
#include <stdlib.h>
using namespace std;
int find(char agent[1000][40],char server[5000][40],int n,int m);
int main(){
int n,m;
char agent[1000][40],server[5000][40];
while( cin>>n){
for(int i=0;i<n;i++)
cin>>agent[i];
cin>>m;
for(int j=0; j<m; j++)
cin>>server[j];
cout<<find(agent,server,n,m)<<endl;
}
return 0;
}
int find(char agent[1000][40],char server[5000][40],int n,int m){
int cur = 0; //当前服务器÷
int maxFar = 0; //从当前位置所有代理中能访问的最大服务器数
int num = 0; //切换次数
int cfar = 0; //当前代理服务器能按顺序访问的服务器数+当前的服务器顺序
while(cur<m){
for(int i=0;i<n;i++){
cfar = cur; //当前代理服务器能按顺序访问的服务器数+当前的服务器顺序
//当前代理能访问到的最远处
while( strcmp( agent[i],server[cfar] ) !=0 ){
cfar++;
}
if(cfar>maxFar)
maxFar = cfar;
}
//例如只有一个代理且碰到了ip相同的服务器
if(maxFar==0)
return -1;
cur = maxFar;
num++;
}
return num-1;
}
<file_sep>/百鸡问题.cpp
#include<iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
for(int x=0;x<=100;x++)
for(int y=0;y<=100-x;y++)
{
int z=100-x-y;
if(z+y*3*3+x*3*5<=3*n)
cout<<"x="<<x<<","<<"y="<<y<<","<<"z="<<z<<endl;
}
}
return 0;
}
<file_sep>/球的半径和体积.cpp
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
int main()
{
int a,b,c,x,y,z;
while(cin>>a>>b>>c>>x>>y>>z)
{
double r=sqrt(pow(x-a,2)+pow(y-b,2)+pow(z-c,2));
double v=4*acos(-1)*pow(r,3)/3;
cout<<setprecision(3)<<fixed<<r<<" "<<v<<endl;
}
return 0;
}
<file_sep>/剩下的树.cpp
#include <iostream>
using namespace std;
int main()
{
int l,m;
while(cin>>l>>m)
{
int num[l+1];
for(int i=0;i<=l;i++)
{
num[i]=i;
}
int count=0;
for(int i=0;i<m;i++)
{
int left,right;
cin>>left>>right;
for(int j=0;j<=l;j++)
{
if(num[j]>=left && num[j]<=right)
{
num[j]=100000;
}
}
}
for(int i=0;i<=l;i++)
{
if(num[i]!=100000)
{
count++;
}
}
cout<<count<<endl;
}
return 0;
}
<file_sep>/旋转数组的最小值.cpp
#include <iostream>
#include <vector>
using namespace std;
int minNumberInRotateArray(vector<int> rotateArray)
{
if(rotateArray.size()==0)
{
return 0;
}
int min;
for(int i=0;i<rotateArray.size()-1;i++)
{
if(rotateArray[i]>rotateArray[i+1])
{
min=rotateArray[i+1]<rotateArray[0]?rotateArray[i+1]:rotateArray[0];
}
}
return min;
}
int main()
{
vector<int> v;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
int t;
cin>>t;
v.push_back(t);
}
cout<<minNumberInRotateArray(v)<<endl;
return 0;
}
<file_sep>/Median for two sequence.cpp
#include <iostream>
using namespace std;
int num1[1000000],num2[1000000];
int main()
{
int n,m;
while(cin>>n)
{
//int num1[n];
for(int i=0;i<n;i++)
{
cin>>num1[i];
}
cin>>m;
// int num2[m];
for(int i=0;i<m;i++)
{
cin>>num2[i];
}
int count=(m+n-1)/2;
int i=0,j=0;
for(int k=0;k<count;k++)
{
if(num1[i]<num2[j])
{
i++;
}
else
{
j++;
}
}
if(num1[i]<num2[j])
{
cout<<num1[i]<<endl;
}
else
{
cout<<num2[j]<<endl;
}
}
return 0;
}
<file_sep>/斐波那契数列迭代实现.cpp
#include <iostream>
using namespace std;
int Fibonacci(int n) {
if(n==1 || n==2)
{
return 1;
}
int a=1,b=1;
int sum=0;
for(int i=3;i<=n;i++)
{
sum=a+b;
a=b;
b=sum;
}
return sum;
}
int main()
{
int n;
while(cin>>n)
{
cout<<Fibonacci(n)<<endl;
}
return 0;
}
<file_sep>/之字形打印矩阵.cpp
#include <vector>
using namespace std;
class Printer {
public:
vector<int> printMatrix(vector<vector<int> > mat, int n, int m) {
// write code here
bool flag=true;
vector<int> martix;
for(int i=0;i<n;i++){
if(flag==true){
for(int j=0;j<m;j++)
martix.push_back(mat[i][j]);
}
else{
for(int j=m-1;j>=0;j--)
martix.push_back(mat[i][j]);
}
flag=!flag;
}
return martix;
}
};
<file_sep>/玛雅人的密码.cpp
#include <iostream>
#include <stdio.h>
#include <queue>
using namespace std;
struct MaYaString{
char maya[14];
int level;
int exc; //exchange
};
bool isSame(char *a,char *b,int n);
bool isHave2012(char *a,int n);
bool isAble(char *a,int n);
int main(){
int N,i,j,answer;
char cc;
queue<MaYaString *> Que;
bool has2012;
while(scanf("%d",&N)!=EOF){
answer=0;
has2012=false;
MaYaString *Node1=new MaYaString;
MaYaString *Node2;
Node1->level=0;
Node1->exc=-1;
scanf("%s",Node1->maya);
if(isHave2012(Node1->maya,N)){
if(!isAble(Node1->maya,N)){ //!!!!!!!!
printf("-1\n");
}
else
printf("0\n");
delete Node1;
}
else{
Que.push(Node1);
while(!Que.empty()){
Node1=Que.front();
Que.pop();
for(i=0;i<N-1;i++){
if(Node1->exc==i) //剪枝
continue;
Node2=new MaYaString;
Node2->exc=i;
Node2->level=(Node1->level)+1;
for(j=0;j<N;j++){
Node2->maya[j]=Node1->maya[j];
}
cc=Node2->maya[i];
Node2->maya[i]=Node2->maya[i+1];
Node2->maya[i+1]=cc;
if(isSame(Node1->maya,Node2->maya,N)){
delete Node2;
continue;
}
if(isHave2012(Node2->maya,N)){ //有2012了
has2012=true;
answer=Node2->level;
//释放所有空间
delete Node2;
while(!Que.empty()){
Node2=Que.front();
Que.pop();
delete Node2;
}
break;
}
else{ //还没有2012,入队
Que.push(Node2);
}
}
delete Node1;
if(has2012){ //有2012了
printf("%d\n",answer);
}
}
}
}
return 0;
}
bool isSame(char *a,char *b,int n){
int i;
bool boo=true;
for(i=0;i<n;i++){
if(a[i]!=b[i]){
boo=false;
break;
}
}
return boo;
}
bool isHave2012(char *a,int n){
int i;
bool boo=false;
if(n<4){
return false;
}
else{
for(i=0;i<=(n-4);i++){
if((a[i]=='2' && a[i+1]=='0') && (a[i+2]=='1' && a[i+3]=='2')){ //!!!!!&&能连用
boo=true;
break;
}
}
}
return boo;
}
bool isAble(char *a,int n){
int i,n0=0,n1=0,n2=0;
if(n<4)
return false;
else{
for(i=0;i<n;i++){
switch(a[i]){
case '0':n0++;break;
case '1':n1++;break;
case '2':n2++;
}
}
if(n0>=1 && n1>=1 && n2>=2)
return true;
else
return false;
}
}<file_sep>/a+b(大整数).java
import java.math.BigInteger;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
while(sc.hasNext()){
BigInteger a=sc.nextBigInteger();
BigInteger b=sc.nextBigInteger();
while((a+" ").length()<2 || (a+" ").length()>1001 ||(b+" ").length()<2||(b+" ").length()>1001)
{
System.out.println("输入有误:请输入1-1000长度的整数");
a=sc.nextBigInteger();
b=sc.nextBigInteger();
}
System.out.println(a.add(b));
}
}
}<file_sep>/打印路径.cpp
#include <iostream>
#include <vector>
#include <string>
#include <cstdio>
#include <algorithm>
using namespace std;
void func()
{
int n;
string str;
vector<string> v;
while(cin>>n){
if(n==0)break;
v.resize(0);
while(n--){
cin>>str;
if(str[str.length()-1]=='\\'){
str.erase(str.length()-1,str.length());
}
if(find(v.begin(),v.end(),str)==v.end()){
v.push_back(str);
}
while(str.find('\\')!=string::npos){
str.erase(str.find_last_of('\\'),str.length());
if(find(v.begin(),v.end(),str)==v.end()){
v.push_back(str);
}
}
}
sort(v.begin(),v.end());
for(int i=0;i<v.size();i++){
if(v[i].find('\\')==string::npos){
cout<<v[i]<<endl;
}
else{
for(int j=0;j<v[i].find_last_of('\\');j++){
cout<<" ";
}
cout<<" ";
cout<<v[i].substr(v[i].find_last_of('\\')+1,v[i].length());
cout<<endl;
}
}
cout<<endl;
}
}
int main(int argc, char *argv[])
{
func();
return 0;
}
<file_sep>/最大两个数_yjd.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
int maxt[4][5];
int f[5];
int f1[5];
int s[5];
int s1[5];
cin>>n;
while(n--)
{
for(int i=0;i<4;i++)
{
for(int j=0;j<5;j++)
{
cin>>maxt[i][j];
}
}
for(int i=0;i<5;i++)
{
int max=0,index;
for(int j=0;j<4;j++)
{
if(max<maxt[j][i])
{
max=maxt[j][i];
f1[i]=j;
index=j;
}
}
f[i]=max;
maxt[index][i]=0;
}
for(int i=0;i<5;i++)
{
int max=0;
for(int j=0;j<4;j++)
{
if(max<maxt[j][i])
{
max=maxt[j][i];
s1[i]=j;
}
}
s[i]=max;
}
for(int i=0;i<5;i++)
{
if(f1[i]<s1[i])
{
cout<<f[i]<<" ";
}
else
{
cout<<s[i]<<" ";
}
}
cout<<endl;
for(int i=0;i<5;i++)
{
if(f1[i]>s1[i])
{
cout<<f[i]<<" ";
}
else
{
cout<<s[i]<<" ";
}
}
cout<<endl;
}
return 0;
}
<file_sep>/数字之和.cpp
#include <iostream>
using namespace std;
int Count(int n)
{
int sum=0;
while(n!=0)
{
sum+=n%10;
n/=10;
}
return sum;
}
int main()
{
int n;
while(cin>>n && n)
{
cout<<Count(n)<<" "<<Count(n*n)<<endl;
}
}
<file_sep>/长整型数每三位增加分隔符.java
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext())
{
long a;
a=scanner.nextLong();
String string=String.valueOf(a);
int length=string.length();
int count=length/3;
System.out.print(string.substring(0, length-3*count));
int l=length-3*count;
if(l==0)
{
for(int i=0;i<count;i++)
{
if(i!=count-1)
{
System.out.print(string.substring(l,l+3)+",");
}
else
{
System.out.print(string.substring(l,l+3));
}
l+=3;
}
}
else
{
for(int i=0;i<count;i++)
{
System.out.print(","+string.substring(l,l+3));
l+=3;
}
}
System.out.println();
}
}
}
<file_sep>/Root(N,k)_yjd .java
import java.math.BigInteger;
import java.util.Scanner;
/**
* Created by 22291_000 on 2017/6/16.
*/
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
BigInteger x;
int y,k;
while(in.hasNext())
{
x=in.nextBigInteger();
y=in.nextInt();
k=in.nextInt();
BigInteger r=x.pow(y);
while(r.compareTo(BigInteger.valueOf(k))!=-1)
{
String str=new BigInteger(r.toString(),10).toString(k);
int t=0;
for(int i=0;i<str.length();i++)
{
if(str.charAt(i)>'a' && str.charAt(i)<='z')
{
t+=str.charAt(i)-87;
}
else
{
t+=Integer.parseInt(str.substring(i,i+1));
}
}
String s=Integer.toString(t);
r=new BigInteger(s);
}
System.out.println(r);
}
}
}
<file_sep>/查找.cpp
#include <iostream>
using namespace std;
int main()
{
l:
int m,n;
while(cin>>n)
{
while(n<1 || n>100)
{
cin>>n;
}
int a[n];
for(int i=0;i<n;i++)
{
cin>>a[i];
}
cin>>m;
while(m<1 || m>100)
{
cin>>m;
}
int b[n];
for(int i=0;i<m;i++)
{
cin>>b[i];
}
for(int i=0;i<m;i++)
{
for(int j=0;j<n;j++)
{
if(b[i]==a[j])
{
cout<<"YES"<<endl;
break;
}
else
{
if(b[i]!=a[j] && j==n-1)
{
cout<<"NO"<<endl;
break;
}
}
}
}
}
return 0;
}
<file_sep>/进制转换(a进制转换为b进制).cpp
#include <iostream>
#include <math.h>
#include <sstream>
using namespace std;
int main() {
string str;
int a,b;
while (cin>>a>>str>>b)
{
for(int i=0;i<str.length();i++)
{
str[i]=(char)toupper(str[i]);
}
double num=0;
for(int i=0;i<str.length();i++)
{
if(str[i]>='0' && str[i]<='9')
{
num+=(str[i]-'0')*pow(a,str.length()-i-1);
}
else if(str[i]>='A' && str[i]<='F')
{
num+=(str[i]-'0'-7)*pow(a,str.length()-i-1);
}
}
int n=(int)num;
string str_trans="";
while(n>0)
{
int num_y=n%b;
if(num_y>=0 && num_y<=9)
{
ostringstream ss;
ss<<num_y;
str_trans=ss.str()+str_trans;
}
else
{
str_trans=((char)(num_y+55))+str_trans;
}
n/=b;
}
cout<<str_trans<<endl;
}
return 0;
}<file_sep>/合唱团.cpp
#include <iostream>
#include <vector>
#include <cstdio>
using namespace std;
int max(int a, int b){
return a > b ? a : b;
}
int min(int a, int b){
return a < b ? a : b;
}
int main(int argc, char *argv[]){
int n;
while(std::cin >> n){
int peer[101];
for(int i = 1; i <= n; ++i){
std::cin >> peer[i];
}
int dp_f[101], dp_b[101];
int team_mem = 1;
for(int i = 1; i <= n; ++i){
dp_f[i] = 1;
dp_b[i] = 1;
for(int j = 1; j < i; ++j)
if(peer[i] > peer[j])
dp_f[i] = max(dp_f[i], dp_f[j] + 1);
for(int j = n; j > n - i + 1; --j)
if(peer[n - i + 1] > peer[j])
dp_b[i] = max(dp_b[i], dp_b[n - j + 1] + 1);
}
for(int i = 1; i <= n; ++i)
team_mem = max(team_mem, dp_f[i] + dp_b[n - i + 1] - 1);
cout<< n - team_mem<<endl;
}
return 0;
}
<file_sep>/质因数的个数.cpp
#include<iostream>
#include<math.h>
using namespace std;
bool isZ(long n)
{
if(n==2)return true;
for(int i=2;i<=sqrt(n);i++)
if(n%i==0)return false;
return true;
}
int main()
{
long n;
while(cin>>n)
{
int count=0;
if(isZ(n))
{
cout<<1<<endl;
}
else
{
while(!isZ(n))
{
for(int i=2;i<=sqrt(n);i++)
{
if(n%i==0 && isZ(i))
{
count++;
n=n/i;
break;
}
}
}
cout<<count+1<<endl;
}
}
return 0;
}
<file_sep>/求中间值.cpp
#include <iostream>
#include<algorithm>
using namespace std;
int main()
{
int num;
while(cin>>num)
{
for(int i=0;i<num;i++)
{
int m,n;
cin>>m>>n;
int n1[m],n2[n];
for(int j=0;j<m;j++)
{
cin>>n1[i];
}
for(int j=0;j<n;j++)
{
cin>>n2[j];
}
int a,b,c,d;
cin>>a>>b>>c>>d;
int temp[b+d-a-c+2];
int k=0;
for(int j=a-1;j<b;j++)
{
temp[k]=n1[j];
k++;
}
for(int j=c-1;j<d;j++)
{
temp[k]=n2[j];
k++;
}
if((b+d-a-c+2)%2==0)
{
cout<<temp[(b+d-a-c+2)/2-1]<<endl;
}
else
{
cout<<temp[(b+d-a-c+2)/2]<<endl;
}
}
}
return 0;
}
<file_sep>/数字阶梯求和(示例).cpp
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define N 100
char s[N];
int main() {
int i, l, f, tmp, idx, a, n;
while (scanf("%d %d", &a, &n) != EOF) {
l = 0;
idx = 0;
for (i = 0; i < n; ++i) {
tmp = (n - i) * a + l;
f = tmp % 10;
l = tmp / 10;
s[idx++] = f + '0';
}
if (l > 0)
s[idx++] = l + '0';
for (i = idx - 1; i >= 0; --i) {
printf("%c", s[i]);
}
printf("\n");
}
return 0;
}
<file_sep>/特殊排序---C语言.c
#include <stdio.h>
#include <stdlib.h>
#define maxn 1000+10
int arr[maxn];
int main()
{
int n, i, temp, j;
while(scanf("%d", &n) == 1) {
for(i=0; i<n; i++) {
scanf("%d", &arr[i]);
}
if(n==1)
{
printf("%d \n",arr[0]);
printf("%d\n",-1);
}
else
{
for(i=0; i<n; i++) {
for(j=0; j<n-i-1; j++) {
if(arr[j]>arr[j+1]) {
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
}
}
}
printf("%d\n", arr[n-1]);
int flag = 0;
for(i=0; i<n-1; i++) {
printf("%d ", arr[i]);
flag = 1;
}
if(flag){
printf("\n");
}
}
}
system("pause");
return 0;
}
<file_sep>/Person类和Dog类继承animal类.java
package hw;
abstract class animal{
abstract public void sleep();
}
class Person extends animal{
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("人睡觉");
}
}
class Dog extends animal
{
@Override
public void sleep() {
// TODO Auto-generated method stub
System.out.println("狗睡觉");
}
}
public class h4 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Person person=new Person();
person.sleep();
Dog dog=new Dog();
dog.sleep();
}
}
<file_sep>/找重复字符位置.java
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static Map<Character, Integer> counts = new LinkedHashMap<Character, Integer>();
public static void main(String[] args) {
// TODO Auto-generated method stub
String input=null;
@SuppressWarnings("resource")
Scanner scanner=new Scanner(System.in);
while(scanner.hasNext())
{
input=scanner.next();
while(!is(input))
{
System.out.println("请输入0-100长度仅含有整数和字母的字符串");
input=scanner.next();
}
wc(input);
counts.clear();
}
}
public static void wc(String words)
{
for(Character w:words.toCharArray())
{
Integer count = counts.get(w);
if (count == null)
count = 0;
count++;
counts.put(w, count);
}
for (Map.Entry<Character, Integer> m :counts.entrySet()) {
if (m.getValue() > 1)
{
lo(words,m.getKey());
//System.out.println(m.getKey());
}
}
}
public static void lo(String words,char word)
{
char[] ch=words.toCharArray();
int j=0;
for(int i=0;i<ch.length;i++)
{
if(ch[i]==word)
{
j++;
if(j<counts.get(ch[i]))
{
System.out.print(word+":"+i+",");
}
else
{
System.out.print(word+":"+i);
}
}
}
System.out.println();
}
public static boolean is(String str)
{
return str.matches("^[a-zA-Z0-9]{0,100}$");
}
}
<file_sep>/Head of Gang.cpp
#include<iostream>
#include<vector>
#include<queue>
#include<map>
#include<string>
#include<algorithm>
using namespace std;
struct relation{
string start;
string end;
int val;
};
bool cmp(relation temp1, relation temp2)
{
return temp1.start < temp2.start;
}
int main()
{
int N, K;
while (cin >> N >> K)
{
vector<relation> infor;
map<string, int> weight;
for (int j = 0; j < N; j++)
{
string temp1, temp2;
int temp_val;
bool flag = false;
cin >> temp1 >> temp2 >> temp_val;
weight[temp1] += temp_val; //更新每个人的weight
weight[temp2] += temp_val;
//更新infor数组
for (int i = 0; i < infor.size(); i++)
{
if (infor[i].start == temp1 && infor[i].end == temp2)
{
infor[i].val += temp_val;
flag = true;
}
if (infor[i].start == temp2 && infor[i].end == temp1)
{
infor[i].val += temp_val;
}
}
if (flag == false) //该关系不在infor中
{
relation temp;
temp.start = temp1;
temp.end = temp2;
temp.val = temp_val;
infor.push_back(temp);
swap(temp.start, temp.end);
infor.push_back(temp);
}
}///信息输入完毕
sort(infor.begin(), infor.end(), cmp);
/* cout << "---------------------------------" << endl;
for (int i = 0; i < infor.size(); i++)
{
cout << infor[i].start << " " << infor[i].end << " " << infor[i].val << endl;
}
for (map<string, int>::iterator it = weight.begin(); it != weight.end(); it++)
cout << it->first << " " << it->second << endl;
*/
//////---------------------------------------------------------------------------------------------
int num_gang=0;
map<string,int> headofgang;
while (!infor.empty())
{
vector<string> visit;
queue<string> cur_gang; ///该次查找的团体
cur_gang.push(infor[0].start);
visit.push_back(infor[0].start);
while (!cur_gang.empty())
{
string temp = cur_gang.front();
cur_gang.pop();
for (int i = 0; i < infor.size(); i++)
{
if (infor[i].start == temp)
{
int j;
for (j = 0; j < visit.size() && visit[j] != infor[i].end; j++);
if (j == visit.size()) ///不在visit之列,则加入cur_gang
{
cur_gang.push(infor[i].end);
visit.push_back(infor[i].end);
}
}
}
}////该团体查找完毕
string headof_cur = visit[0];
int total_weight = 0;
for (int i = 0; i < visit.size(); i++)
{
total_weight += weight[visit[i]];
if (weight[visit[i]]>weight[headof_cur])
headof_cur = visit[i];
int start_pos, end_pos;
for (start_pos = 0; start_pos < infor.size() && infor[start_pos].start != visit[i]; start_pos++);
for (end_pos = start_pos; end_pos < infor.size() && infor[end_pos].start == visit[i]; end_pos++);
infor.erase(infor.begin() + start_pos, infor.begin() + end_pos);
}
if (visit.size()>2 && total_weight>2*K)
{
num_gang++;
headofgang[headof_cur]=visit.size();
}
}////结束
cout << num_gang << endl;
for (map<string, int>::iterator it = headofgang.begin(); it != headofgang.end();it++)
cout << it->first<<" "<<it->second<< endl;
}
return 0;
}
<file_sep>/最大连续子列.cpp
#include <stdio.h>
int main(void)
{
int n;
long a[10000];
int i;
long best, bestTmp;
long bestL, bestR, bestTmpL, bestTmpR;
while (scanf("%d", &n) != EOF)
{
if (n == 0)
break;
for (i=0; i<n; i++)
scanf("%lld", &a[i]);
best = bestL = bestR = a[0];
bestTmp = bestTmpL = bestTmpR = a[0];
for (i=1; i<n; i++)
{
if (bestTmp < 0)
bestTmp = bestTmpL = bestTmpR = a[i];
else
{
bestTmp += a[i];
bestTmpR = a[i];
}
if (bestTmp > best)
{
best = bestTmp;
bestL = bestTmpL;
bestR = bestTmpR;
}
}
if(best==bestL && best == bestR && best<0)
{
best=0;
bestL=a[0];
bestR=a[n-1];
}
printf("%lld %lld %lld\n", best, bestL, bestR);
}
return 0;
}
<file_sep>/矩形覆盖问题---如果用1m的方块覆盖mn区域,递推关系式为f(n) = f(n-1) + f(n-m),(n m).cpp
#include <iostream>
using namespace std;
int rectCover(int number) {
if(number==0)
return 0;
if(number==1)
return 1;
int prevalue=1;
int preprevalue=1;
int value;
for(int i=2;i<=number;i++)
{
value=prevalue+preprevalue;
preprevalue=prevalue;
prevalue=value;
}
return value;
}
int main()
{
int m;
while(cin>>m)
{
int n;
cin>>n;
cout<<rectCover(n)<<endl;
}
return 0;
}
<file_sep>/四则运算_yjd.cpp
#include <iostream>
using namespace std;
int jc(int n)
{
if(n==1) return 1;
else
{
return n*jc(n-1);
}
}
int main()
{
int n,n2;
char str;
while(cin>>n>>str)
{
switch(str)
{
case '+':
cin>>n2;
cout<<n+n2<<endl;
break;
case '-':
cin>>n2;
cout<<n-n2<<endl;
break;
case '*':
cin>>n2;
cout<<n*n2<<endl;
break;
case '/':
cin>>n2;
if(n2==0)
{
cout<<"error"<<endl;
}
else
{
cout<<n/n2<<endl;
}
break;
case '%':
cin>>n2;
if(n2==0)
{
cout<<"error"<<endl;
}
else
{
cout<<n%n2<<endl;
}
break;
case '!':
cout<<jc(n)<<endl;
break;
}
}
return 0;
}
<file_sep>/最后一个字符.cpp
#include <iostream>
#include <map>
using namespace std;
int main()
{
int n;
string str;
cin>>n;
for(int i=0;i<n;i++)
{
map<char, int> mymap;
string str;
cin>>str;
for(int j=0;j<str.length();j++)
{
mymap[str[j]]++;
if(mymap[str[j]]>1)
{
mymap.erase(str[j]);
}
}
int ii=100000000;
for(map<char, int>::iterator it= mymap.begin();it!=mymap.end();++it)
{
int find=str.find(it->first);
if(ii>find)
{
ii=find;
}
}
cout<<str[ii]<<endl;
}
return 0;
}
<file_sep>/Simple Sort.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
int num[n];
int count=0;
for(int i=0;i<n;i++)
{
cin>>num[i];
if(i>=1 && num[i]!=num[i-1])
{
count++;
}
}
sort(num,num+n);
int nu[count];
int k=0;
for(int i=0;i<n;i++)
{
if(num[i]!=num[i+1])
{
nu[k]=num[i];
k++;
}
}
for(int i=0;i<k-1;i++)
{
cout<<nu[i]<<" ";
}
cout<<nu[k-1]<<endl;
}
return 0;
}
<file_sep>/最大两个数_示例.cpp
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include <limits.h>
typedef struct Matrixs{
int value;//数值
int row;//行数
}Matrixs;
int main()
{
int i,j,n,k,first;
Matrixs Matrix[4][5];
Matrixs Matrix2[2][5];
while(scanf("%d",&n) != EOF){
for(k = 0;k < n;k++){
//输入数据
for(i = 0;i < 4;i ++){
for(j = 0;j < 5;j++){
scanf("%d",&Matrix[i][j].value);
Matrix[i][j].row = i;
}
}
//最大的两个数放在前两位
Matrixs temp;
for(j = 0;j < 5;j++){
//初始化最小值
Matrix2[0][j].value = INT_MIN;
Matrix2[1][j].value = INT_MIN;
//每列最大的两个数
for(i = 0;i < 4;i++){
if(Matrix[i][j].value > Matrix2[0][j].value){
Matrix2[0][j] = Matrix[i][j];
}
}
for(i = 0;i < 4;i++){
if(Matrix2[0][j].row != Matrix[i][j].row && Matrix[i][j].value > Matrix2[1][j].value){
Matrix2[1][j] = Matrix[i][j];
}
}
}
//保留原矩阵的行列顺序
for(j = 0;j < 5;j++){
if(Matrix2[0][j].row > Matrix2[1][j].row){
temp = Matrix2[0][j];
Matrix2[0][j] = Matrix2[1][j];
Matrix2[1][j] = temp;
}
}
//输出
for(i = 0;i < 2;i++){
for(j = 0;j < 5;j++){
printf("%d ",Matrix2[i][j].value);
}
printf("\n");
}
}
}
return 0;
}
<file_sep>/判断IP.java
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
String a=sc.nextLine();
while(sc.hasNext()){
String str=sc.nextLine();
String[] ch=str.split("\\.");
if(isIp(ch))
{
System.out.println("Yes!");
}
else
{
System.out.println("No!");
}
}
}
public static boolean isIp(String[] ch)
{
if(ch.length!=4)
{
return false;
}
else
{
for(int i=0;i<ch.length;i++)
{
if(Integer.parseInt(ch[i])>255 || Integer.parseInt(ch[i])<0)
{
return false;
}
}
}
return true;
}
}<file_sep>/买房子.cpp
#include <iostream>
#include <math.h>
using namespace std;
int main() {
int n,k;
while(cin>>n>>k)
{
int count=1;
double sum=200;
double l=(double)k/100;
while((count*n)<sum)
{
sum=200*pow((1+l),count);
count++;
if(count>21)
{
cout<<"Impossible"<<endl;
break;
}
}
if(count<=21)
{
cout << count << endl;
}
}
return 0;
}<file_sep>/排名.cpp
#include <iostream>
#include <algorithm>
using namespace std;
struct ks
{
string numid;
int ts;
int sum;
};
bool cmp(ks k1,ks k2)
{
if(k1.sum!=k2.sum)
{
return k1.sum>k2.sum;
}
return k1.numid<k2.numid;
}
int main()
{
int num_p,num_t,sline;
while(cin>>num_p && num_p)
{
cin>>num_t>>sline ;
int t[num_t];
for(int i=0;i<num_t;i++)
{
cin>>t[i];
}
ks k[1000];
ks k_th[1000];
int count=0;
for(int i=0;i<num_p;i++)
{
cin>>k[i].numid;
cin>>k[i].ts;
int sumS=0;
for(int j=0;j<k[i].ts;j++)
{
int s=0;
cin>>s;
sumS+=t[s-1];
}
k[i].sum=sumS;
if(k[i].sum>=sline)
{
k_th[count].numid=k[i].numid;
k_th[count].ts=k[i].ts;
k_th[count].sum=k[i].sum;
count++;
}
}
sort(k_th,k_th+count,cmp);
cout<<count<<endl;
for(int i=0;i<count;i++)
{
cout<<k_th[i].numid<<" "<<k_th[i].sum<<endl;
}
}
return 0;
}
<file_sep>/完数.cpp
#include <iostream>
using namespace std;
bool isw(int num)
{
int sum=0;
for(int i=1;i<=num;i++)
{
if(num%i==0 && i!=num)
{
sum+=i;
}
}
if(sum==num)
{
return true;
}
return false;
}
int main()
{
int n;
while(cin>>n)
{
int count=0;
for(int i=1;i<=n;i++)
{
if(isw(i))
{
count++;
}
}
int m=0;
for(int i=1;i<=n;i++)
{
if(isw(i))
{
m++;
if(m<count)
{
cout<<i<<" ";
}
else
{
cout<<i;
}
}
}
cout<<endl;
}
return 0;
}
<file_sep>/CPU调度.cpp
#include<iostream>
#include<string>
using namespace std;
class Process
{
public:
string ProcessName; // 进程名字
int Time; // 进程需要时间
int leval; // 进程优先级
int LeftTime; // 进程运行一段时间后还需要的时间
};
void Copy ( Process proc1, Process proc2); // 把proc2赋值给proc1
void Sort( Process pr[], int size) ; // 此排序后按优先级从大到小排列
void sort1(Process pr[], int size) ; // 此排序后按需要的cpu时间从小到大排列
void Fcfs( Process pr[], int num, int Timepice); // 先来先服务算法
void TimeTurn( Process process[], int num, int Timepice); // 时间片轮转算法
void Priority( Process process[], int num, int Timepice); // 优先级算法
int main()
{
int a;
cout<<endl;
cout<<" 选择调度算法:"<<endl;
cout<<" 1: FCFS 2: 时间片轮换 3: 优先级调度 4: 最短作业优先 5: 最短剩余时间优先"<<endl;
cin>>a;
const int Size =30;
Process process[Size] ;
int num;
int TimePice;
cout<<" 输入进程个数:"<<endl;
cin>>num;
cout<<" 输入此进程时间片大小: "<<endl;
cin>>TimePice;
for( int i=0; i< num; i++)
{
string name;
int CpuTime;
int Leval;
cout<<" 输入第"<< i+1<<" 个进程的名字、cpu时间和优先级:"<<endl;
cin>>name;
cin>> CpuTime>>Leval;
process[i].ProcessName =name;
process[i].Time =CpuTime;
process[i].leval =Leval;
cout<<endl;
}
for ( int k=0;k<num;k++)
process[k].LeftTime=process[k].Time ;//对进程剩余时间初始化
cout<<" ( 说明: 在本程序所列进程信息中,优先级一项是指进程运行后的优先级!! )";
cout<<endl; cout<<endl;
cout<<"进程名字"<<"共需占用CPU时间 "<<" 还需要占用时间 "<<" 优先级"<<" 状态"<<endl;
if(a==1)
Fcfs(process,num,TimePice);
else if(a==2)
TimeTurn( process, num, TimePice);
else if(a==3)
{
Sort( process, num);
Priority( process , num, TimePice);
}
else // 最短作业算法,先按时间从小到大排序,再调用Fcfs算法即可
{
sort1(process,num);
Fcfs(process,num,TimePice);
}
return 0;
}
void Copy ( Process proc1, Process proc2)
{
proc1.leval =proc2.leval ;
proc1.ProcessName =proc2.ProcessName ;
proc1.Time =proc2.Time ;
}
void Sort( Process pr[], int size) //以进程优先级高低排序
{// 直接插入排序
for( int i=1;i<size;i++)
{
Process temp;
temp = pr[i];
int j=i;
while(j>0 && temp.leval<pr[j-1].leval)
{
pr[j] = pr[j-1];
j--;
}
pr[j] = temp;
} // 直接插入排序后进程按优先级从小到大排列
for( int d=size-1;d>size/2;d--)
{
Process temp;
temp=pr [d];
pr [d] = pr [size-d-1];
pr [size-d-1]=temp;
} // 此排序后按优先级从大到小排列
}
/* 最短作业优先算法的实现*/
void sort1 ( Process pr[], int size) // 以进程时间从低到高排序
{// 直接插入排序
for( int i=1;i<size;i++)
{
Process temp;
temp = pr[i];
int j=i;
while(j>0 && temp.Time < pr[j-1].Time )
{
pr[j] = pr[j-1];
j--;
}
pr[j] = temp;
}
}
/* 先来先服务算法的实现*/
void Fcfs( Process process[], int num, int Timepice)
{ // process[] 是输入的进程,num是进程的数目,Timepice是时间片大小
while(true)
{
if(num==0)
{
cout<<" 所有进程都已经执行完毕!"<<endl;
exit(1);
}
if(process[0].LeftTime==0)
{
cout<<" 进程"<<process[0].ProcessName<< " 已经执行完毕!"<<endl;
for (int i=0;i<num;i++)
process[i]=process[i+1];
num--;
}
else if(process[num-1].LeftTime==0)
{
cout<<" 进程"<<process[num-1].ProcessName<< " 已经执行完毕!"<<endl;
num--;
}
else
{
cout<<endl; //输出正在运行的进程
process[0].LeftTime=process[0].LeftTime- Timepice;
process[0].leval =process[0].leval-1;
cout<<" "<<process[0].ProcessName <<" "<<process[0].Time <<" ";
cout<<process[0].LeftTime <<" "<<process[0].leval<<" 运行";
cout<<endl;
for(int s=1;s<num;s++)
{
cout<<" "<<process[s].ProcessName <<" "<<process[s].Time <<" ";
cout<<process[s].LeftTime <<" "<<process[s].leval<<" 等待"<<endl; ;
}
} // else
cout<<endl;
system(" pause");
cout<<endl;
} // while
}
/* 时间片轮转调度算法实现*/
void TimeTurn( Process process[], int num, int Timepice)
{
while(true)
{
if(num==0)
{
cout<<" 所有进程都已经执行完毕!"<<endl;
exit(1);
}
if(process[0].LeftTime==0)
{
cout<<" 进程"<<process[0].ProcessName<< " 已经执行完毕!"<<endl;
for (int i=0;i<num;i++)
process[i]=process[i+1];
num--;
}
if( process[num-1].LeftTime ==0 )
{
cout<<" 进程" << process[num-1].ProcessName <<" 已经执行完毕! "<<endl;
num--;
}
else if(process[0].LeftTime > 0)
{
cout<<endl; //输出正在运行的进程
process[0].LeftTime=process[0].LeftTime- Timepice;
process[0].leval =process[0].leval-1;
cout<<" "<<process[0].ProcessName <<" "<<process[0].Time <<" ";
cout<<process[0].LeftTime <<" "<<process[0].leval<<" 运行";
cout<<endl;
for(int s=1;s<num;s++)
{
cout<<" "<<process[s].ProcessName <<" "<<process[s].Time <<" ";
cout<<process[s].LeftTime <<" "<<process[s].leval;
if(s==1)
cout<<" 就绪"<<endl;
else
cout<<" 等待"<<endl;
}
Process temp;
temp = process[0];
for( int j=0;j<num;j++)
process[j] = process[j+1];
process[num-1] = temp;
} // else
cout<<endl;
system(" pause");
cout<<endl;
} // while
}
/* 优先级调度算法的实现*/
void Priority( Process process[], int num, int Timepice)
{
while( true)
{
if(num==0)
{
cout<< "所有进程都已经执行完毕!"<<endl;
exit(1);
}
if(process[0].LeftTime==0)
{
cout<<" 进程" << process[0].ProcessName <<" 已经执行完毕! "<<endl;
for( int m=0;m<num;m++)
process[m] = process[m+1]; //一个进程执行完毕后从数组中删除
num--; // 此时进程数目减少一个
}
if( num!=1 && process[num-1].LeftTime ==0 )
{
cout<<" 进程" << process[num-1].ProcessName <<" 已经执行完毕! "<<endl;
num--;
}
if(process[0].LeftTime > 0)
{
cout<<endl; //输出正在运行的进程
process[0].LeftTime=process[0].LeftTime- Timepice;
process[0].leval =process[0].leval-1;
cout<<" "<<process[0].ProcessName <<" "<<process[0].Time <<" ";
cout<<process[0].LeftTime <<" "<<process[0].leval<<" 运行";
cout<<endl; // 输出其他进程
for(int s=1;s<num;s++)
{
cout<<" "<<process[s].ProcessName <<" "<<process[s].Time <<" ";
cout<<process[s].LeftTime <<" "<<process[s].leval ;
if(s==1)
cout<<" 就绪"<<endl;
else
cout<<" 等待 "<<endl;
}
} // else
Sort(process, num);
cout<<endl;
system(" pause");
cout<<endl;
} // while
}
<file_sep>/与7无关的数.cpp
#include <iostream>
using namespace std;
bool isSeven(int n)
{
if(n%7==0 || n%10==7 || (n/10)%10==7)
{
return true;
}
return false;
}
int main() {
int n;
while(cin>>n)
{
int sum=0;
for(int i=1;i<=n;i++)
{
if(!isSeven(i))
{
sum+=i*i;
}
}
cout<<sum<<endl;
}
return 0;
}<file_sep>/Financial ManageMent.cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double num[12]={0};
while(cin>>num[0]>>num[1]>>num[2]>>num[3]>>num[4]>>num[5]>>num[6]>>num[7]>>num[8]>>num[9]>>num[10]>>num[11])
{
double sum=0;
for(int i=0;i<12;i++)
{
sum+=num[i];
}
cout<<"$";
cout<<setprecision(2)<<fixed<<sum/12<<endl;
}
return 0;
}
<file_sep>/谁是你的潜在朋友.cpp
#include <iostream>
using namespace std;
int main()
{
int n,m;
while(cin>>n>>m)
{
int num[n];
for(int i=0;i<n;i++)
{
cin>>num[i];
}
for(int i=0;i<n;i++)
{
int count=0;
for(int j=0;j<n;j++)
{
if(j==i)
{
continue;
}
else
{
if(num[i]==num[j])
{
count++;
}
}
}
if(count>0)
{
cout<<count<<endl;
}
else
{
cout<<"BeiJu"<<endl;
}
}
}
return 0;
}
<file_sep>/八皇后第n串.cpp
#include <iostream>
#include <cmath>
using namespace std;
int num = 8;
int x[9] = {0};
int a[92][9] = {0};
int pos = 0;
bool place(int k)
{
for(int j = 1;j<k;j++)
if(abs(x[k] - x[j]) == abs(k-j)||x[j] == x[k])
return false;
return true;
}
void backtrack(int t)
{
if(t>num) //num为皇后的数目
{
for(int m = 1;m<=num;m++)
{
a[pos][m] = x[m];//这一行用输出当递归到叶节点的时候,一个可行解
}
pos++;
}
else
for(int i = 1;i<=num;i++)
{
x[t] = i;
if(place(t)) backtrack(t+1);//此处的place函数用来进行我们上面所说的条件的判断,如果成立,进入下一级递归
}
}
int main()
{
for(int i= 0;i<=num;i++)
x[i] = 0;
backtrack(1);
/* for(int i = 0;i<92;i++)
{
for(int j = 1;j<=8;j++)
cout<<a[i][j];
cout<<endl;
}*/
int n = 0;
while(cin>>n)
{
int indes = 0;
for(int i = 0;i<n;i++)
{
cin>>indes;
indes--;
for(int j = 1;j<9;j++) cout<<a[indes][j];
cout<<endl;
}
}
return 0;
}
<file_sep>/一只青蛙一次可以跳上1级台阶,也可以跳上2级。求该青蛙跳上一个n级的台阶总共有多少种跳法.cpp
#include <iostream>
using namespace std;
int jumpFloor(int number) {
if(number==1)
{
return 1;
}
if(number==2)
{
return 2;
}
long long f1=1;
long long f2=2;
if(number>2)
{
for(int i=3;i<=number;++i)
{
f2+=f1;
f1=f2-f1;
}
}
return f2;
}
int main()
{
int n;
while(cin>>n)
{
cout<<jumpFloor(n)<<endl;
}
return 0;
}
<file_sep>/字符串的查找删除.cpp
#include<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int main()
{
string str1, str2;
cin >> str1;
getchar(); //这一步很重要
while (getline(cin,str2))
{
int i = 0, j = 0;
for (;i+j < str2.size();)
{
if ((str2[i + j]|32) == (str1[j]|32))
j++;
else
{
i++;
j = 0;
}
if (j == str1.size())
{
for (int z = i;z < i + str1.size();++z)
str2[z] = ' ';
i = i + str1.size();
j = 0;
}
}
for (int i = 0;i < str2.size();++i)
if (str2[i] == ' ')
continue;
else
cout << str2[i];
cout << endl;
}
return 0;
}<file_sep>/吃糖果.cpp
#include <iostream>
using namespace std;
int s(int n)
{
if(n==1 || n==2){
return n;
}
else
{
return s(n-1)+s(n-2);
}
}
int main() {
int n;
while(cin>>n)
{
cout<<s(n)<<endl;
}
return 0;
}<file_sep>/查找第K小数.cpp
#include <iostream>
using namespace std;
int main()
{
int n;
while(cin>>n)
{
while(n<1 || n>100)
{
cin>>n;
}
int num[n];
for(int i=0;i<n;i++)
{
cin>>num[i];
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n-i-1;j++)
{
if(num[j]>num[j+1])
{
int temp=num[j];
num[j]=num[j+1];
num[j+1]=temp;
}
}
}
int k;
cin>>k;
int m=0;
for(int i=0;i<n;i++)
{
if(num[i]!=num[i+1])
{
m++;
if(m==k)
{
cout<<num[i]<<endl;
}
}
}
}
return 0;
}
<file_sep>/从n个物品中挑总重量为m的组合数.cpp
#include<iostream>
#include<cstdio>
using namespace std;
const int maxn = 21;
int v[maxn]; // 存储每个物品体积
int bite[maxn]; // 用于标记这个物品是否出现在最后的队列中
int count = 0; // 计数器
int total = 0; // 物品总数量
void solve(int num, int n)
{
if(n == 0)
{
// 没有剩余容积则是一种方法
++count;
return ;
}
if(num == total)
{
// 放到最后也没有结束
return ;
}
bite[num] = 1;
solve(num+1, n-v[num]);
bite[num] = 0;
solve(num+1, n);
}
int main()
{
cin >> total;
for(int i = 0; i < total; ++i)
{
cin >> v[i];
}
solve(0, 40);
cout << count <<endl;
return 0;
}<file_sep>/Financial ManageMent(求12个月的平均值--保留小数点后两位).cpp
#include <iostream>
#include <iomanip>
using namespace std;
int main(){
double money[12]={0};
while(cin>>money[0]>>money[1]>>money[2]>>money[3]>>money[4]>>money[5]>>money[6]>>money[7]>>money[8]>>money[9]>>money[10]>>money[11])
{
double sum=0;
for(int i=0;i<12;i++)
{
sum+=money[i];
}
cout<<"$";
cout<<setprecision(2)<<fixed<<sum/12<<endl;
}
return 0;
}
<file_sep>/顺时针旋转90度矩阵.cpp
#include <iostream>
using namespace std;
#define MAX 500
int matrix[MAX][MAX];
void sx(int mat[][MAX] ,int n)
{
int temp[n][n];
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
temp[j][n-1-i]=mat[i][j];
}
}
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cout<<temp[i][j]<<" ";
}
cout<<endl;
}
}
int main()
{
int n;
while(cin>>n)
{
for(int i=0;i<n;i++)
{
for(int j=0;j<n;j++)
{
cin>>matrix[i][j];
}
}
sx(matrix,n);
}
return 0;
}
<file_sep>/字符串通配.cpp
#include <iostream>
#include <cstring>
using namespace std;
class WildMatch {
public:
bool chkWildMatch(string A, int lena, string B, int lenb) {
// write code here
int i=lena-1;
int j=lenb-1;
while(i>=0&&j>=0){
if(A[i]==B[j]||B[j]=='.'){
i--;
j--;
}
else if(B[j]=='*'){
lenb=j;
j--;
}
else {
i=i-j+lenb-2;
j=lenb-1;
}
}
if(j<0)
return 1;
else
return 0;
}
};
<file_sep>/进制转换(30位大整型转换为2进制).java
import java.math.BigInteger;
import java.util.Scanner;
/**
* Created by 22291_000 on 2017/6/16.
*/
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
BigInteger b;
while(in.hasNext())
{
b=in.nextBigInteger();
String str = new BigInteger(b.toString(),10).toString(2);
System.out.println(str);
}
}
}
<file_sep>/两个栈实现一个队列.cpp
#include <stack>
#include <iostream>
using namespace std;
class Solution
{
public:
void push(int node) {
while(!stack2.empty())
{
int temp=stack2.top();
stack1.push(temp);
stack2.pop();
}
stack2.push(node);
while(!stack1.empty())
{
int t=stack1.top();
stack2.push(t);
stack1.pop();
}
}
int pop() {
int temp=stack2.top();
stack2.pop();
return temp;
}
private:
stack<int> stack1;
stack<int> stack2;
};
int main()
{
Solution s;
s.push(1);
s.push(2);
s.push(3);
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
cout<<s.pop()<<endl;
return 0;
}
<file_sep>/简单计算器.cpp
#include <iostream>
#include <cstdio>
using namespace std;
inline int Cmp(const char & c){
if(c == '+' || c == '-'){
return 1;
}
return 2;
}
inline double Count(const double & a, const double & b, const char & c){
switch(c){
case '+' :{
return a + b;
}
case '-' :{
return a - b;
}
case '*' :{
return a * b;
}
case '/' :{
if(!b){
throw 0;
}
return a / b;
}
}
return 0;
}
inline double Calculate(const char *str){
int len = 0, numIndex = -1, chIndex = -1;
double narrNum[8], num = 0, result;
char ch[8];
while(str[len]){
if(str[len] >= '0' && str[len] <= '9'){
do{
num = num * 10 + str[len] - '0';
}while(str[++len] >= '0' && str[len] <= '9');
narrNum[++numIndex] = num;
num = 0;
}else if(str[len] == '+' || str[len] == '-' || str[len] == '*' || str[len] == '/'){
while(chIndex >= 0 && Cmp(ch[chIndex]) >= Cmp(str[len])){
result = Count(narrNum[numIndex - 1], narrNum[numIndex], ch[chIndex]);
narrNum[--numIndex] = result;
--chIndex;
}
ch[++chIndex] = str[len++];
}else{
++len;
}
}
while(chIndex >= 0){
result = Count(narrNum[numIndex - 1], narrNum[numIndex], ch[chIndex]);
narrNum[--numIndex] = result;
--chIndex;
}
return result;
}
int main(void){
char str[200];
while(gets(str) && (str[0] != '0'))
try{
printf("%.2f\n", Calculate(str));
}catch(int){
printf("error\n");
}
return 0;
}
<file_sep>/字符数组拼接.cpp
#include <iostream>
#include <cstring>
using namespace std;
void MyStrcat(char dstStr[],char srcStr[])
{
cout<<string(dstStr)+string(srcStr)<<endl;
}
int main()
{
string str1,str2;
while(cin>>str1>>str2)
{
char ch1[str1.length()];
char ch2[str2.length()];
strcpy(ch1, str1.c_str());
strcpy(ch2, str2.c_str());
MyStrcat(ch1,ch2);
}
return 0;
}
<file_sep>/寻找大富翁.cpp
#include <iostream>
#include <algorithm>
using namespace std;
bool cmp(int a,int b)
{
return a>b;
}
int main()
{
int n,m;
while(cin>>n>>m && n && m)
{
int num[n];
for(int i=0;i<n;i++)
{
cin>>num[i];
}
sort(num,num+n,cmp);
if(n<=m)
{
for(int i=0;i<n-1;i++)
{
cout<<num[i]<<" ";
}
cout<<num[n-1]<<endl;
}
else
{
for(int i=0;i<m-1;i++)
{
cout<<num[i]<<" ";
}
cout<<num[m-1]<<endl;
}
}
return 0;
}
<file_sep>/最后一个字符.java
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Scanner;
/**
* Created by 22291_000 on 2017/6/16.
*/
public class Main {
public static void main(String[] args)
{
Scanner in=new Scanner(System.in);
int n;
n=in.nextInt();
for(int i=0;i<n;i++)
{
Map<String,Integer> map=new LinkedHashMap<String ,Integer>();
String str;
str=in.next();
for(int i1=0;i1<str.length();i1++)
{
if(map.get(str.substring(i1,i1+1))==null)
{
map.put(str.substring(i1,i1+1), 1);
}
else
{
int count=map.get(str.substring(i1,i1+1))+1;
map.put(str.substring(i1,i1+1), count);
}
}
for(String key:map.keySet())
{
if(map.get(key)==1)
{
System.out.println(key);
break;
}
}
}
}
}
<file_sep>/Excel排序.cpp
#include <iostream>
#include <algorithm>
using namespace std;
struct student{
string snum;
string name;
int score;
};
bool cmp1(const student &s1,const student &s2)
{
return s1.snum<s2.snum;
}
bool cmp2(const student &s1,const student &s2)
{
if(s1.name!=s2.name)
{
return s1.name<s2.name;
}
else return s1.snum<s2.snum;
}
bool cmp3(const student &s1,const student &s2)
{
if(s1.score!=s2.score)
{
return s1.score<s2.score;
}
else return s1.snum<s2.snum;
}
int main()
{
int n,c;
int testCase=1;
while(cin>>n>>c && n)
{
student s[n];
for(int i=0;i<n;i++)
{
cin>>s[i].snum>>s[i].name>>s[i].score;
}
if(c==1) sort(s,s+n,cmp1);
else if(c==2) sort(s,s+n,cmp2);
else sort(s,s+n,cmp3);
cout<<"Case "<<testCase<<":"<<endl;
for(int i=0;i<n;i++)
{
cout<<s[i].snum<<" "<<s[i].name<<" "<<s[i].score<<endl;
}
testCase++;
}
return 0;
}
|
683171fab8a901224b29caadc7202958d7bb15c5
|
[
"Java",
"C",
"C++"
] | 232 |
C++
|
yanjiangdi/Design-algorithms-to-solve-problems
|
1f48cad39982843621696d95fb9ed446291b1169
|
145e1ccb000bbd50309b0cfb8ca459ddc2f4df34
|
refs/heads/master
|
<file_sep>package qpay
import (
"bytes"
"encoding/json"
"github.com/pkg/errors"
"io/ioutil"
"net/http"
"os"
"time"
)
type AuthResponse struct {
TokenType string `json:"token_type"`
RefreshExpiresIn int `json:"refresh_expires_in"`
RefreshToken string `json:"refresh_token"`
AccessToken string `json:"access_token"`
ExpiresIn int `json:"expires_in"`
Scope string `json:"scope"`
NotBeforePolicy string `json:"not-before-policy"`
SessionState string `json:"session_state"`
}
func Authenticate() (*AuthResponse, error) {
clientVal, found := cacheInstance.Get("client")
if !found {
return nil, errors.New("No client information has found")
}
requestBody, err := json.Marshal(clientVal)
if err != nil {
return nil, err
}
response, err := http.Post(os.Getenv("QPAY_URL")+"/auth/token", "application/json", bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
//fmt.Println(string(body), os.Getenv("QPAY_URL") + "/auth/token")
var data AuthResponse
if err := json.Unmarshal(body, &data); err != nil {
return nil, err
}
cacheInstance.Set("auth_response", data, time.Minute*30)
cacheInstance.Set("token", data.AccessToken, time.Minute*30)
return &data, nil
}
<file_sep>module "github.com/felagund18/qpay/v4"
go 1.17
require (
github.com/patrickmn/go-cache v2.1.0+incompatible
github.com/pkg/errors v0.9.1
)
<file_sep>package qpay
import (
"fmt"
"log"
"os"
"testing"
)
func TestSchema(t *testing.T) {
err := os.Setenv("QPAY_URL", "https://sandbox.qpay.mn/v1")
if err != nil {
panic(err)
}
InitQPay("qpay_test", "1234")
bill, err := CreateBill(Bill{
TemplateID: "TEST_INVOICE",
MerchantID: "TEST_MERCHANT",
BranchID: "1",
PosID: "1",
Receiver: Receiver{
ID: "1",
RegisterNo: "1",
Name: "<NAME>",
Email: "<EMAIL>",
PhoneNumber: "1",
Note: "1",
},
BillNumber: "2020-02-02-02",
Date: "2020-03-03",
Description: "Hello World",
Amount: 1000,
BtukCode: "",
VatFlag: "0",
})
if err != nil {
log.Println(err)
}
fmt.Println(bill)
//
//checkStatus, err := qpay.Check("2020-02-02-02")
//if err != nil {
// log.Println(err)
//}
//fmt.Println(checkStatus.PaymentInfo.PaymentStatus)
}<file_sep>package qpay
import (
"fmt"
"github.com/patrickmn/go-cache"
"log"
"time"
)
var cacheInstance *cache.Cache
type client struct {
ClientID string `json:"client_id"`
ClientSecret string `json:"client_secret"`
GrantType string `json:"grant_type"`
RefreshToken string `json:"refresh_token"`
}
func InitQPay(clientID string, clientSecret string) {
cacheInstance = cache.New(864000*time.Second, 1*time.Hour)
cacheInstance.Set("client", client{
ClientID: clientID,
ClientSecret: clientSecret,
GrantType: "client",
RefreshToken: "",
}, cache.NoExpiration)
_, err := GetToken()
if err != nil {
fmt.Println(err)
}
}
func GetToken() (string, error) {
token, found := cacheInstance.Get("token")
if !found {
log.Println("Token has not found")
if _, err := Authenticate(); err != nil {
log.Println(err)
}
}
return fmt.Sprintf("%v", token), nil
}
<file_sep>package qpay
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
)
type Bill struct {
TemplateID string `json:"template_id"`
MerchantID string `json:"merchant_id"`
BranchID string `json:"branch_id"`
PosID string `json:"pos_id"`
Receiver Receiver `json:"receiver"`
BillNumber string `json:"bill_no"`
Date string `json:"date"`
Description string `json:"description"`
Amount int `json:"amount"`
BtukCode string `json:"btuk_code"`
VatFlag string `json:"vat_flag"`
}
type Receiver struct {
ID string `json:"id"`
RegisterNo string `json:"register_no"`
Name string `json:"name"`
Email string `json:"email"`
PhoneNumber string `json:"phone_number"`
Note string `json:"note"`
}
type BillResponse struct {
PaymentID int64 `json:"payment_id"`
QPayCode string `json:"qPay_QRcode"`
QPayImage string `json:"qPay_QRimage"`
QPayURL string `json:"qPay_url"`
QPayShortURL string `json:"qPay_shortUrl"`
QPayDeepLink []struct {
Name string `json:"name"`
Link string `json:"link"`
} `json:"qPay_deeplink"`
}
func CreateBill(bill Bill) (*BillResponse, error) {
requestBody, err := json.Marshal(bill)
if err != nil {
log.Println(err)
return nil, err
}
token, err := GetToken()
if err != nil {
log.Println(err)
return nil, err
}
req, err := http.NewRequest("POST", os.Getenv("QPAY_URL")+"/bill/create", bytes.NewBuffer(requestBody))
if err != nil {
log.Println(err)
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
var data *BillResponse
if err := json.Unmarshal(body, &data); err != nil {
return nil, err
}
return data, nil
}
<file_sep>package qpay
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"os"
)
type CheckResponse struct {
ID int64 `json:"id"`
TemplateID string `json:"template_id"`
MerchantID string `json:"merchant_id"`
BranchInfo struct {
ID string `json:"id"`
Email string `json:"email"`
Name string `json:"name"`
Phone interface{} `json:"phone"`
Address interface{} `json:"address"`
} `json:"branch_info"`
StaffInfo interface{} `json:"staff_info"`
MerchantCustomerInfo struct {
ID string `json:"id"`
RegisterNo string `json:"register_no"`
Name string `json:"name"`
Email string `json:"email"`
PhoneNumber string `json:"phone_number"`
Note string `json:"note"`
} `json:"merchant_customer_info"`
BillNo string `json:"bill_no"`
AllowPartialPayment bool `json:"allow_partial_payment"`
AllowTip bool `json:"allow_tip"`
CurrencyType string `json:"currency_type"`
GoodsDetail []struct {
ID interface{} `json:"id"`
Name string `json:"name"`
BarCode interface{} `json:"bar_code"`
Quantity int `json:"quantity"`
UnitPrice int `json:"unit_price"`
TaxInfo []interface{} `json:"tax_info"`
} `json:"goods_detail"`
Surcharge struct {
} `json:"surcharge"`
Discount struct {
} `json:"discount"`
Note interface{} `json:"note"`
Attach interface{} `json:"attach"`
PaymentMethod string `json:"payment_method"`
CustomerQr interface{} `json:"customer_qr"`
VatInfo struct {
IsAutoGenerate bool `json:"is_auto_generate"`
Vats []interface{} `json:"vats"`
} `json:"vat_info"`
PaymentInfo struct {
PaymentStatus string `json:"payment_status"`
TransactionID interface{} `json:"transaction_id"`
LastPaymentDate interface{} `json:"last_payment_date"`
Transactions []interface{} `json:"transactions"`
} `json:"payment_info"`
}
func Check(billNumber string) (*CheckResponse, error) {
requestBody, err := json.Marshal(map[string]string{
"merchant_id": os.Getenv("QPAY_MERCHANT_ID"),
"bill_no": billNumber,
})
if err != nil {
return nil, err
}
token, err := GetToken()
if err != nil {
return nil, err
}
req, err := http.NewRequest("POST", os.Getenv("QPAY_URL")+"/bill/check", bytes.NewBuffer(requestBody))
if err != nil {
return nil, err
}
req.Header.Set("Authorization", fmt.Sprintf("Bearer %v", token))
req.Header.Set("Content-Type", "application/json")
client := &http.Client{}
response, err := client.Do(req)
if err != nil {
return nil, err
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
if err != nil {
return nil, err
}
if response.StatusCode != 200 {
return nil, errors.New(string(body))
}
var data *CheckResponse
if err := json.Unmarshal(body, &data); err != nil {
return nil, err
}
return data, nil
}
func CheckPaymentID(paymentID string) {
}
|
699f7b2023713607c83b33846ebe8d7be1f79bad
|
[
"Go Module",
"Go"
] | 6 |
Go
|
felagund18/qpay
|
13a2be3f90f322a041af37e624e2e14bc91edc40
|
27128d93f9bd0e5c25b476536ecd89b10d8bed00
|
refs/heads/master
|
<repo_name>Karagul/datascience-olympics_RMD<file_sep>/src/script.R
jforny <- "~/rstudio/OlympicsPrediction/"
dgribel <- "~/PUC-MSc/datascience/olympics/"
path <- dgribel
source_medals <- paste(path, "dataset/medals.tsv", sep = "")
medals <- read.table(source_medals, header = T, sep = "\t", fill = TRUE, stringsAsFactors = FALSE)
# remove last row
medals <- medals[ -nrow(medals), ]
# replace NA by 0
medals[is.na(medals)] <- 0
hosts <- c("Spain", "United.States", "Australia", "Greece", "China", "Great.Britain")
hosts_acronym <- c("SPA", "USA", "AUS", "GRE", "CHI", "GBR")
years <- c()
last_n_games <- 6
j <- 1
for(i in (last_n_games-1):0) {
years[j] <- 2012 - 4*i
j <- j+1
}
# define colors for total medals chart
total_colors <- rep("#ADCFFF", times = last_n_games*last_n_games)
j <- 1
for (i in 1:last_n_games-1) {
total_colors[j] <- "#388BFF"
j <- j+last_n_games+1
}
home_factor <- c()
mean_away_factor <- c()
total_medals <- c()
for(i in(1:length(hosts))) {
k <- hosts[i]
host_pos <- which(medals$Year==years[i])
host_pos_tail <- last_n_games - (nrow(medals)-host_pos)
key_gold <- paste(k, "Gold", sep="..")
key_silver <- paste(k, "Silver", sep="..")
key_bronze <- paste(k, "Bronze", sep="..")
mean_away_factor <- cbind(mean_away_factor, mean(3*tail(medals[[key_gold]], last_n_games)[-host_pos_tail] +
2*tail(medals[[key_silver]], last_n_games)[-host_pos_tail] +
tail(medals[[key_bronze]], last_n_games)[-host_pos_tail]))
home_factor <- cbind(home_factor, 3*medals[[key_gold]][host_pos] +
2*medals[[key_silver]][host_pos] +
medals[[key_bronze]][host_pos])
total_medals <- cbind(total_medals, tail(medals[[key_gold]], last_n_games) +
tail(medals[[key_silver]], last_n_games) +
tail(medals[[key_bronze]], last_n_games))
}
y_lim_total <- c(0, 1.2*max(total_medals))
y_lim_score <- c(0, 1.2*max(home_factor))
bra_score <- 3*tail(medals$Brazil..Gold, last_n_games) +
2*tail(medals$Brazil..Silver, last_n_games) +
tail(medals$Brazil..Bronze, last_n_games)
bra_gold_totals <- sum(tail(medals$Brazil..Gold, last_n_games))
bra_silver_totals <- sum(tail(medals$Brazil..Silver, last_n_games))
bra_bronze_totals <- sum(tail(medals$Brazil..Bronze, last_n_games))
sum_bra_medals <- bra_gold_totals + bra_silver_totals + bra_bronze_totals
bra_gold_perc <- bra_gold_totals/sum_bra_medals
bra_silver_perc <- bra_silver_totals/sum_bra_medals
bra_bronze_perc <- bra_bronze_totals/sum_bra_medals
# ratio: mean between home factor and mean away factor
r <- mean(home_factor/mean_away_factor)
# predicting BRA score
pred_bra_score <- mean(bra_score) * r
# predicting BRA medals distribution
p <- pred_bra_score/3 + pred_bra_score/6 + pred_bra_score/9
pred_bra_gold <- round(bra_gold_perc*p)
pred_bra_silver <- round(bra_silver_perc*p)
pred_bra_bronze <- round(bra_bronze_perc*p)
pred_bra <- cbind(pred_bra_gold, pred_bra_silver, pred_bra_bronze)
# medals ratio, year by year (1992--2012)
country_medals_ratio <- function(country) {
y <- years[1]
medals_ratio <- c()
for(i in(1:length(years))) {
medals_ratio <- rbind(medals_ratio,
(3*medals[[paste(country, "Gold", sep="..")]][which(medals$Year==y)]+
2*medals[[paste(country, "Silver", sep="..")]][which(medals$Year==y)]+
medals[[paste(country, "Bronze", sep="..")]][which(medals$Year==y)])/
(3*medals[[paste(country, "Gold", sep="..")]][which(medals$Year==y-4)]+
2*medals[[paste(country, "Silver", sep="..")]][which(medals$Year==y-4)]+
medals[[paste(country, "Bronze", sep="..")]][which(medals$Year==y-4)]))
y <- y+4
}
rownames(medals_ratio) <- years
return(medals_ratio)
}
# Fuction to compute medals score, year by year (1992--2012)
country_medals_score <- function(country) {
y <- years[1]
medals_score <- c()
for(i in(1:length(years))) {
medals_score <- rbind(medals_score,
(3*medals[[paste(country, "Gold", sep="..")]][which(medals$Year==y)]+
2*medals[[paste(country, "Silver", sep="..")]][which(medals$Year==y)]+
medals[[paste(country, "Bronze", sep="..")]][which(medals$Year==y)]))
y <- y+4
}
rownames(medals_score) <- years
return(medals_score)
}
#Function to convert factor to numeric
as.numeric.factor <- function(x) {as.numeric(levels(x)[x])}
# Loading indicator script
cor_gdp <- c()
source(paste(path, "src/indicator.R", sep = ""))
more_countries <- c("Spain", "United.States", "Australia", "Greece", "China", "Great.Britain",
"France", "Canada", "Italy", "Japan", "Sweden", "Brazil", "Norway", "Finland",
"Netherlands", "Switzerland", "Austria", "Romania", "Bulgaria", "Denmark",
"Belgium", "South.Korea")
# Medals x gdp correlation for hosts -- removing year which country was the host (host factor influences)
groupeddata <- data.frame("Country" = character(), "Year" = character(), "GGF" = character(), "MGR" = character(), "Gold" = character(), "Silver" = character(), "Bronze" = character(), "Medals Score" = character())
for(c in more_countries) {
if(c %in% hosts) {
pos <- match(c, hosts)
cor_gdp <- cbind(cor_gdp, cor(country_medals_ratio(c)[-pos], ind_factor[c,][-pos]))
} else {
cor_gdp <- cbind(cor_gdp, cor(country_medals_ratio(c), ind_factor[c,]))
}
#Grouping data
for(year in years) {
gold <- medals[[paste(c, "Gold", sep="..")]][which(medals$Year==year)]
silver <- medals[[paste(c, "Silver", sep="..")]][which(medals$Year==year)]
bronze <- medals[[paste(c, "Bronze", sep="..")]][which(medals$Year==year)]
medalsscore <- country_medals_score(c)[toString(year),]
ggf <- ind_factor[c,toString(year)]
mgr <- country_medals_ratio(c)[toString(year),]
groupeddata <- as.data.frame(rbind(as.matrix(groupeddata), c(c, year, ggf, mgr, gold, silver, bronze, medalsscore)))
}
}
colnames(cor_gdp) <- more_countries
#Order by year
groupeddata <- groupeddata[order(groupeddata$Year),]
#Removing hosts data
# for(i in (1:length(hosts))) {
# groupeddata <- groupeddata[!(groupeddata$Country == hosts[i] & groupeddata$Year == years[i]),]
# }
#Linear model for previous hosts
hostLM <- function(host) {
hostIndex <- which(hosts==host)
hostData <- groupeddata[!(groupeddata$Country != hosts[hostIndex]),]
hostGGF <- as.numeric(as.character(hostData[(hostData$Country == hosts[hostIndex] & hostData$Year == years[hostIndex]),"GGF"]))
hostData$Year <- as.numeric.factor(hostData$Year)
hostData <- hostData[(hostData$Year < as.numeric(years[hostIndex])),]
# Converting dependent and independent properties (factor to numeric)
hostData$MGR <- as.numeric.factor(hostData$MGR)
hostData$GGF <- as.numeric.factor(hostData$GGF)
hostModel <- lm(hostData$MGR ~ hostData$GGF)
plot(hostData$MGR, hostData$GGF, xlab = paste(hosts[hostIndex], "GGF"), ylab = paste(hosts[hostIndex], "MGR"))
return(hostModel)
}
brazil2016LM <- function() {
hostData <- groupeddata[!(groupeddata$Country != "Brazil"),]
# hostData <- groupeddata
hostData$Year <- as.numeric.factor(hostData$Year)
# Converting dependent and independent properties (factor to numeric)
hostData$MGR <- as.numeric.factor(hostData$MGR)
hostData$GGF <- as.numeric.factor(hostData$GGF)
hostModel <- lm(hostData$MGR ~ hostData$GGF)
# plot(hostData$GGF, hostData$MGR, xlab = "Brazil GGF", ylab = "Brazil MGR", xlim=c(0, 2), ylim=c(0,3.5))
# abline(hostModel)
# text(hostData$GGF, hostData$MGR, labels=hostData$Year, cex= 0.6, pos=3)
brazilGDPGrowth12to15 = as.numeric(c(tail(ind[,"Brazil"], 2), c("0.14500", "-1.02600")))
worldGDPGrowth12to15 = as.numeric(c(rowMeans(ind[which(ind$Time >= "2012" & ind$Time <= "2013"),][-c(1)],na.rm=TRUE), c("3.38900", "3.45100")))
brazil2016GGF = mean(brazilGDPGrowth12to15)/mean(worldGDPGrowth12to15)
# predict(hostModel, brazil2016GGF, interval="confidence")
brazil2016MGR = coefficients(hostModel)[1] + coefficients(hostModel)[2] * brazil2016GGF
# points(hostData$GGF, fitted.values(hostModel), col = "red")
# points(brazil2016GGF, brazil2016MGR, col = "blue")
return(hostModel)
}
brazilLM = brazil2016LM()
# summary(brazilLM)
# layout(matrix(1:4,2,2))
# plot(brazilLM)
# layout(matrix(1:1))
brazilGDPGrowth12to15 = as.numeric(c(tail(ind[,"Brazil"], 2), c("0.14500", "-1.02600")))
worldGDPGrowth12to15 = as.numeric(c(rowMeans(ind[which(ind$Time >= "2012" & ind$Time <= "2013"),][-c(1)],na.rm=TRUE), c("3.38900", "3.45100")))
brazil2016GGF = mean(brazilGDPGrowth12to15)/mean(worldGDPGrowth12to15)
brazil2016MGR = coefficients(brazilLM)[1] + coefficients(brazilLM)[2] * brazil2016GGF
gdp_pred_bra_score <- pred_bra_score * brazil2016MGR
gdp_p <- gdp_pred_bra_score/3 + gdp_pred_bra_score/6 + gdp_pred_bra_score/9
gdp_pred_bra_gold <- round(bra_gold_perc*gdp_p)
gdp_pred_bra_silver <- round(bra_silver_perc*gdp_p)
gdp_pred_bra_bronze <- round(bra_bronze_perc*gdp_p)
gdp_pred_bra <- cbind(gdp_pred_bra_gold, gdp_pred_bra_silver, gdp_pred_bra_bronze)
# CORRELATION THROUGH YEARS CONSIDERING ONLY 1 COUNTRY
#country <- "China"
#ggf <- ind_factor[country,][-match(country, hosts)]
#mgr <- country_medals_ratio(country)[-match(country, hosts)]
#plot(cbind(mgr,ggf))
#country_model <- lm(mgr ~ ggf)
# CORRELATION FOR 2012, CONSIDERING MANY COUNTRIES
# all <- c("Spain",
# "United.States",
# "Australia",
# "Greece",
# "Great.Britain",
# "China",
# "Russia",
# "Germany",
# "France",
# "Finland",
# "Romania",
# "Canada",
# "Poland",
# "Netherlands",
# "South.Korea",
# "Bulgaria",
# "Cuba",
# "Switzerland",
# "Denmark",
# "Norway",
# "Belgium",
# "Ukraine",
# "Brazil",
# "New.Zealand",
# "Turkey",
# "Austria",
# "Kenya",
# "Belarus",
# "Argentina",
# "Jamaica",
# "Mexico")
#
# ggf <- ind_factor[all, match(2012, years)]
# mgr <- c()
# i <- 1
# for(c in all) {
# mgr[i] <- country_medals_ratio(c)[match(2012, years)]
# i <- i+1
# }
#plot(cbind(mgr,ggf), col="blue", pch = 19, cex = 0.8)<file_sep>/presentation/olympics.Rmd
---
title: "Olympic games medals prediction"
author: "<NAME> and <NAME>"
date: \today
output:
beamer_presentation:
colortheme: default
fonttheme: default
theme: default
subtitle: Predicting host country performance
---
## Model
- Medals history
- \textcolor{red}{80's problem: USSR, East/West Germany}
- Hosting factor
- GDP (total, per capita and growth rate) and economic freedom
- \textcolor{blue}{Sports investment}
- \textcolor{blue}{Performance analysis on recent competitions}
- \textcolor{red}{Population (total and growth rate)}
## Possible achievements
- Predict medals table for the host country
+ How many medals will Brazil win in Rio'2016?
+ What about medals distribution (gold, silver, bronze)?
+ Is it possible to extend such analysis in order to discriminate predictions for specific sports?
- Investigate hosting factor
+ How does hosting factor effectively contributes for performance improvement?
- Explore visualization mechanisms that may bring some insights
## Validation
- Compare prediction results with past olympic games (2012, 2008, 2004, ...), by shifting datasets in time
## Datasets
### Medals history
- Data Market
- https://datamarket.com/data/set/24b1/medals-won-at-the-summer-olympic-games
- The Guardian Sport Datablog (~30K medals entries)
- http://www.theguardian.com/sport/datablog/2012/jun/25/olympic-medal-winner-list-data
- Sports Reference
- http://www.sports-reference.com/olympics/
### Country indicators
- The World Bank
- http://data.worldbank.org
## Total of medals (1992 -- 2012)
```{r echo=FALSE}
source("~/PUC-MSc/datascience/olympics/src/script.R")
```
```{r eval=FALSE}
# total of medals for last 6 games
total_medals <- cbind(total_medals,
tail(medals[[key_gold]], 6) +
tail(medals[[key_silver]], 6) +
tail(medals[[key_bronze]], 6))
```
```{r echo=FALSE}
rownames(total_medals) <- paste(years, hosts_acronym)
colnames(total_medals) <- hosts_acronym
total_medals
```
## Total of medals (1992 -- 2012)
```{r, echo=FALSE}
bp_totals <- barplot(total_medals, main="Total of medals (1992, 1996, 2000, 2004, 2008, 2012)",
ylab = "# Medals",
beside = TRUE,
col = total_colors,
border = NA,
space = c(0.1,0.8),
ylim = y_lim_total,
las = 1)
legend("topleft", legend = c("Performance being host", "Performance being visitor"),
fill = c("#388BFF", "#ADCFFF"),
bty = "n",
inset = 0.03)
text(x = bp_totals, y = array(total_medals), label = array(total_medals), pos = 3,
cex = 0.8, col = "#444444")
```
## Hosting factor
### Mean away score
```{r eval=FALSE}
# mean away score for last 6 games
mean_away_factor <- cbind(mean_away_factor,
mean(
3*tail(medals[[key_gold]], 6)[-host_pos_tail] +
2*tail(medals[[key_silver]], 6)[-host_pos_tail] +
tail(medals[[key_bronze]], 6)[-host_pos_tail]
))
```
```{r echo=FALSE}
colnames(mean_away_factor) <- hosts_acronym
mean_away_factor
```
## Hosting factor
### Home score
```{r eval=FALSE}
# home score for last 6 games
home_factor <- cbind(home_factor,
3*medals[[key_gold]][host_pos] +
2*medals[[key_silver]][host_pos] +
medals[[key_bronze]][host_pos])
```
```{r echo=FALSE}
#colnames(home_factor) <- hosts_acronym
home_factor
```
## Hosting factor
```{r, echo=FALSE}
colors <- c("#DD4200", "#FF9155")
bp_scores <- barplot(rbind(home_factor, mean_away_factor),
main="Scores (Home x Away)",
ylab = "Score",
beside = TRUE,
col = colors,
border = NA,
space = c(0.1,1),
ylim = y_lim_score,
las = 1)
legend("topleft", legend = c("Home score", "Away score (mean)"), fill = colors, bty = "n",inset = 0.03)
text(x = bp_scores, y = array(rbind(home_factor, mean_away_factor)), label = array(rbind(home_factor, mean_away_factor)), pos = 3, cex = 0.8, col = "#444444")
```
## Hosting factor
```{r eval=FALSE}
home_factor/mean_away_factor
```
```{r echo=FALSE}
round(home_factor/mean_away_factor, 4)
```
```{r}
mean(home_factor/mean_away_factor)
```
## Brazil's performance
```{r, echo=FALSE}
medals_bra <- read.table("../dataset/bra-medals.csv", header = T, sep="\t")
color_medals <- c("#E0D910", "#C8C8C8", "#C7872E")
medals_header <- c("gold", "silver", "bronze")
ylim <- c(0, 1.1*max(medals_bra$gold + medals_bra$silver + medals_bra$bronze))
bp2 <- barplot(t(as.matrix(medals_bra[, medals_header])), main = "Brazil medals distribution (1920 - 2012)", ylab = "# Medals", beside = FALSE, col = color_medals, border = NA, space = 0.2, names.arg = medals_bra$year, las = 2, ylim = ylim)
legend("topleft", legend = medals_header, fill = color_medals, bty = "n", inset = 0.03)
text(x = bp2, y = medals_bra$gold + medals_bra$silver + medals_bra$bronze, label = medals_bra$gold + medals_bra$silver + medals_bra$bronze, pos = 3, cex = 0.8, col = "#666666")
```
## Our first prediction for Brazil medals distribution...
```{r, eval=FALSE}
bra_score <-
3*tail(medals$Brazil..Gold, 6) +
2*tail(medals$Brazil..Silver, 6) +
tail(medals$Brazil..Bronze, 6)
# ratio: mean between home factor and mean away factor
r <- mean(home_factor/mean_away_factor)
# predicting BRA score
pred_bra_score <- mean(bra_score) * r
# predicting BRA medals distribution
p <- pred_bra_score/3 + pred_bra_score/6 + pred_bra_score/9
pred_bra_gold <- round(bra_gold_perc*p)
pred_bra_silver <- round(bra_silver_perc*p)
pred_bra_bronze <- round(bra_bronze_perc*p)
```
## Our first prediction for Brazil medals distribution...
```{r, echo=FALSE}
ylim_pred <- c(0, 1.2*max(pred_bra))
bp_pred <- barplot(array(pred_bra), col = color_medals, border = NA, ylim = ylim_pred, axes=FALSE)
legend("topleft", legend = medals_header, fill = color_medals, bty = "n", inset = 0.03)
text(x = bp_pred, y = array(pred_bra), label = array(pred_bra), pos = 3, cex = 3.5, col = "#999999")
```
\* HFP: Hosting factor prediction
## GDP
- Analyze correlation between GDP growth and medals growth $\Rightarrow$ fit in a regression model
\begin{center}
$ggf_{c(y)} = \frac{\bar{G}_{c(y-4,y)}}{\bar{G}_{w(y-4,y)}}$
\end{center}
\begin{center}
\center$mgr_{c(y)} = \frac{S_{c(y)}}{S_{c(y-4)}}$
\end{center}
where $\bar{G}_{c(y,y-4)}$ is the average GDP growth on period $[y-4, y[$ for country $c$, $\bar{G}_{w(y,y-4)}$ is the world average GDP growth on period $[y-4, y[$ and $S_{c(y)}$ is the medal score for country $c$ on year $y$.
## Correlation: Medals score x GDP
**Correlation coefficient** of two variables: their covariance divided by the product of their individual standard deviations. It is a normalized measurement of how the two are linearly related.
1: variables are positively linearly related
-1: variables are negatively linearly related
```{r echo=FALSE}
cor_gdp_hosts <- round(subset(cor_gdp, select = hosts), 4)
cor_gdp_bra <- round(cor(country_medals_ratio("Brazil"), ind_factor["Brazil",]), 4)
colnames(cor_gdp_hosts) <- hosts_acronym
colnames(cor_gdp_bra) <- "BRA"
```
```{r}
cor_gdp_hosts
```
```{r}
cor_gdp_bra
```
## Correlation: Medals score x GDP (2012)
```{r, echo=FALSE}
all <- c(hosts, c("Russia", "Germany", "France"))
ggf <- ind_factor[all, match(2012, years)]
mgr <- c()
i <- 1
for(c in all) {
mgr[i] <- country_medals_ratio(c)[match(2012, years)]
i <- i+1
}
plot(cbind(mgr,ggf), col=ifelse(rownames(cbind(mgr,ggf))%in% c("China","Great.Britain"), "red", "blue"), pch = 19, cex = 1, ylab = "GDP growth factor", xlab = "Medals growth factor")
text(mgr, ggf, labels=rownames(cbind(mgr,ggf)), cex= 0.7, pos=3)
```
## Projecting GDP: 2016 analysis
```{r, echo=FALSE}
yr <- c(1992:2013)
world <- rowMeans(ind[which(ind$Time %in% yr),][-c(1, which(colnames(ind)=="Brazil"))],na.rm=TRUE)
world <- c(world, c(3.38900, 3.45100))
bra <- tail(ind$Brazil, length(yr))
bra <- c(bra, c(0.14500, -1.02600))
yr <- c(yr, c(2014, 2015))
g_range <- range(0, world, bra)
plot(world, type="o", col="blue", axes=FALSE, ann=TRUE, ylim=g_range, ylab = "GDP", xlab = "Years")
lines(bra, type="o", pch=22, lty=1, col="red")
axis(1, at=1:length(yr), lab=yr)
axis(2, at=-5:10, las=1)
title(main = "World mean GDP x Brazil GDP")
legend("topleft", g_range[2], c("World mean GDP","Brazil GDP"), cex=0.8, col=c("blue","red"), pch=21:22, lty=1:2)
addTrans <- function(color,trans) {
if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))
num2hex <- function(x)
{
hex <- unlist(strsplit("0123456789ABCDEF",split=""))
return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
}
rgb <- rbind(col2rgb(color),trans)
res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""), sep="")
return(res)
}
lim <- par("usr")
rect(length(yr)-3, lim[3]-1, length(yr), lim[4]+1, border=NA, col=addTrans("red", 50))
box()
```
\tiny{* 2014 and 2015: forecasts}
\tiny{Source: IMF World Economic Outlook (WEO), April 2015}
## Brazil MGR x GGF
```{r, echo=FALSE}
hostData <- groupeddata[!(groupeddata$Country != "Brazil"),]
hostData$Year <- as.numeric.factor(hostData$Year)
# Converting dependent and independent properties (factor to numeric)
hostData$MGR <- as.numeric.factor(hostData$MGR)
hostData$GGF <- as.numeric.factor(hostData$GGF)
plot(hostData$GGF, hostData$MGR, xlab = "Brazil GGF", ylab = "Brazil MGR", xlim=c(0, 2), ylim=c(0,3.5))
abline(brazilLM)
text(hostData$GGF, hostData$MGR, labels=hostData$Year, cex= 0.6, pos=3)
points(hostData$GGF, fitted.values(brazilLM), col = "red")
points(brazil2016GGF, brazil2016MGR, col = "blue")
```
## Linear Regression Model for Brazil
```{r, echo=TRUE}
summary(brazil2016LM())
```
## Using predicted MGR to improve 2016 prediction
```{r, echo=TRUE}
intercept = as.numeric(coefficients(brazilLM)[1])
slope = as.numeric(coefficients(brazilLM)[2])
brazil2016MGR = intercept + slope * brazil2016GGF
gdp_pred_bra_score <- pred_bra_score * brazil2016MGR
```
## Our second prediction for Brazil medals distribution...
```{r, echo=FALSE}
ylim_pred <- c(0, 1.2*max(gdp_pred_bra))
bp_pred <- barplot(array(gdp_pred_bra), col = color_medals, border = NA, ylim = ylim_pred, axes=FALSE)
legend("topleft", legend = medals_header, fill = color_medals, bty = "n", inset = 0.03)
text(x = bp_pred, y = array(gdp_pred_bra), label = array(gdp_pred_bra), pos = 3, cex = 3.5, col = "#999999")
```
## Sports investment
Brazil:
```{r eval=FALSE}
> sports_investment_bra
year budget population budget_pp
1 2010 1.50 195.2 7.68
2 2011 2.50 196.9 12.69
3 2012 3.44 198.6 17.32
4 2013 3.38 200.3 16.87
5 2014 3.39 202.7 16.72
6 2015 3.01 204.4 14.72
```
## Sports investment
```{r eval=FALSE}
budget_pp_2016 <- mean(budget_pp[which(year >= 2012)])
> budget_pp_2016
[1] 16.4075
budget_pp_2012 <- mean(budget_pp[which(year < 2012)])
> budget_pp_2012
[1] 10.185
bra_score_2012 <-
3*tail(medals$Brazil..Gold, 1) +
2*tail(medals$Brazil..Silver, 1) +
tail(medals$Brazil..Bronze, 1)
x <- (bra_score_2016*bra_score_2012)/bra_score_2012
> x
[1] 45.10653
```
## Sports investment
Great Britain:
```{r eval=FALSE}
> sports_investment_gbr
year budget population budget_pp medals_score
1 2000 0.19 58.9 3.22 60
2 2012 0.84 63.7 13.18 140
```
```{r eval=FALSE}
ratio_budget_medals <-
sports_investment_gbr$budget_pp/sports_investment_gbr$medals_score
> ratio_budget_medals[2]/ratio_budget_medals[1]
[1] 1.754215
```
## Sports investment
```{r eval=FALSE}
sports_inv <- (x-pred_bra_score)/1.754215
> sports_inv
[1] 3.36705
> bra_gold_perc*sports_inv
[1] 0.7488889
> bra_silver_perc*sports_inv
[1] 0.9829167
> bra_bronze_perc*sports_inv
[1] 1.638194
```
Rounding, we have +0 gold medal, +1 silver medal and +2 bronze medals relative to HFP.
## Recent competitions<file_sep>/report/report.Rmd
---
title: 'Olympic games medals prediction: Predicting host country performance'
author: "<NAME> and <NAME>"
output: pdf_document
---
```{r echo=FALSE}
#source("~/PUC-MSc/datascience/olympics/src/script.R")
```
## Introdução
Nesse relatório, serão apresentados a metodologia e os principais resultados para um modelo preditivo aplicado ao contexto dos jogos olímpicos de 2016. Nesse trabalho, o foco será dado especialmente para o quadro de medalhas a ser alcançado pelo Brasil, país sede da competição.
Os principais objetivos do trabalho são: prever o quadro de medalhas para o Brasil (quantidade de medalhas e distribuição destas em ouro, prata e bronze) e investigar o fator sede, determinando o quanto esse fator efetivamente contribui para a melhoria de performance de um país.
Para atingir esses objetivos, adotamos uma estratégia que consiste em coletar algumas séries históricas que permitam evidenciar possíveis variáveis que interferem no desempenho de um país nos jogos olímpicos (dados econômicos, dados de competições recentes, e dados sobre investimento em esportes). Além disso, a proposta apresentada faz uso de mecanismos de visualização que trazem *insights* ao problema analisado.
## Modelo de dados
O modelo de dados foi criado a partir de séries históricas que compreendem: resultados de competições recentes, histórico de medalhas em olimpíadas passadas, desenvolvimento econômico (taxa de crescimento do PIB) e investimento em esportes. Além da coleta dessas séries, investigamos o fator sede (*hosting factor*), que mede o quanto um país melhora a sua performance pelo fato de sediar uma competição olímpica.
O projeto desenvolvido fornece um *framework* genérico que possibilita apresentar possíveis co-relações entre variáveis do modelo (como taxa de crescimento do PIB) e o ganho de medalhas.
## Datasets
No projeto foram usados basicamente 2 datasets. O primeiro, obtido pelo website do [Data Market](https://datamarket.com/data/set/24b1/medals-won-at-the-summer-olympic-games), disponibiliza o total de medalhas (discrimininando por ouro, prata e bronze) conquistado por cada país no período compreendido entre 1896 e 2012. O segundo dataset, obtido pelo portal do [Banco Mundial](http://data.worldbank.org), traz dados referentes aos indicadores dos países, como a taxa de crescimento (PIB) ao longo do tempo.
## Modelo preditivo
### Fator sede (*hosting factor*)
O principal objetivo deste trabalho é prever o número de medalhas que o Brasil ganhará em 2016. Para esta finalidade, analisaremos a performance de outros países que já sediaram alguma olimpíada, em especial as mais recentes. Nesta etapa, concentraremos nossa análise no período entre 1992 e 2012. A figura abaixo mostra o total de medalhas obtido quando cada país foi sede dos jogos, nos anos de 1992, 1996, 2000, 2004, 2008 e 2012. Como podemos observar, o número de medalhas obtidas por um país sede é, de modo geral, maior que o número de medalhas obtidos quando o país é visitante (no caso dos EUA, isso não acontece, mas veremos mais adiante o que isso significa).
Porém, não estamos interessados no total de medalhas exatamente. Esse é um indicador importante, mas devemos considerar que medalhas de ouro valem mais que medalhas de prata e medalhas de prata valem mais que as de bronze. Portanto, definimos o *score* de medalhas como sendo uma ponderação, que deve nos dar uma previsão melhor. Para nossa análise, iremos considerar:
\begin{center}
1 medalha de ouro = 3 medalhas de bronze
1 medalha de prata = 2 medalhas de bronze
\end{center}
Assim, o *score* de medalhas para um país $c$ em um ano $y$ é definido como:
\begin{center}
$S_{c(y)} = 3g_{c(y)} + 2s_{c(y)} + b_{c(y)}$
\end{center}
onde $g_{c(y)}$ corresponde ao total de medalhas de ouro ganho pelo país $c$ no ano $y$, $s_{c(y)}$ ao total de medalhas de prata e $b_{c(y)}$ ao total de medalhas de bronze. Agora, podemos fazer um levantamento sobre o fator sede considerando o *score* de medalhas ao invés do total de medalhas. Nesse novo resultado, podemos observar que o EUA teve um desempenho melhor sendo sede do que sendo visitante (pois aumentou sua proporção de ouro quando foi sede), nos trazendo evidências mais compatíveis com a realidade do que o gráfico mostrando o total de medalhas. A figura abaixo compara o *score* de medalhas do país sendo sede, com a média dos *scores* de medalhas quando o país foi visitante:
```{r, echo=FALSE}
#colors <- c("#DD4200", "#FF9155")
#colnames(mean_away_factor) <- hosts_acronym
#bp_scores <- barplot(rbind(home_factor, mean_away_factor),
# main="",
# ylab = "Score",
# beside = TRUE,
# col = colors,
# border = NA,
# space = c(0.1,1),
# ylim = y_lim_score,
# las = 1, cex.axis=0.7, cex.names=0.7)
#
#legend("topleft", legend = c("Home score", "Away score (mean)"), fill = colors, bty = "n",inset = 0.01, cex=0.6)
#text(x = bp_scores, y = array(rbind(home_factor, mean_away_factor)), label = array(rbind(home_factor, mean_away_factor)), pos = 3, cex = 0.6, col = "#444444")
```
A partir desses dados, conseguimos obter a média para o fator sede (*hosting factor*):
```{r eval=FALSE}
> home_factor/mean_away_factor
SPA USA AUS GRE CHI GBR
[1,] 1.708075 1.038534 1.545699 2.786885 1.646972 2.564103
> mean(home_factor/mean_away_factor)
[1] 1.881711
```
o que significa que em média um país sede aumenta em 1.88x o seu *score*. Portanto, nesse ponto já temos condições de fazer uma primeira previsão (ainda grosseira) para o Brasil. Primeiramente, obtemos o desempenho do país nas últimas 6 olímpiadas:
```{r eval=FALSE}
bra_score <- 3*tail(medals$Brazil..Gold, 6) +
2*tail(medals$Brazil..Silver, 6) +
tail(medals$Brazil..Bronze, 6)
```
Em seguida, calculamos $r$, a razão média entre o desempenho em casa e o desempenho como visitante:
```{r eval=FALSE}
# ratio: mean between home factor and mean away factor
r <- mean(home_factor/mean_away_factor)
```
E então fazemos a predição do *score* para o Brasil em 2016:
```{r eval=FALSE}
# predicting BRA score
pred_bra_score <- mean(bra_score) * r
```
Como estamos interessados na quantidade de medalhas de ouro, prata e bronze, devemos agora fazer o movimento reverso, convertendo o *score* para o número de medalhas. Para isso, tomamos a proporção de ouro, prata e bronze para o Brasil na série história:
```{r eval=FALSE}
# predicting BRA medals distribution
p <- pred_bra_score/3 + pred_bra_score/6 + pred_bra_score/9
bra_gold_totals <- sum(tail(medals$Brazil..Gold, 6))
bra_silver_totals <- sum(tail(medals$Brazil..Silver, 6))
bra_bronze_totals <- sum(tail(medals$Brazil..Bronze, 6))
sum_bra_medals <- bra_gold_totals + bra_silver_totals + bra_bronze_totals
bra_gold_perc <- bra_gold_totals/sum_bra_medals
bra_silver_perc <- bra_silver_totals/sum_bra_medals
bra_bronze_perc <- bra_bronze_totals/sum_bra_medals
pred_bra_gold <- round(bra_gold_perc*p)
pred_bra_silver <- round(bra_silver_perc*p)
pred_bra_bronze <- round(bra_bronze_perc*p)
```
E o resultado final dessa primeira previsão é o seguinte:
```{r eval=FALSE}
> pred_bra_gold
[1] 5
> pred_bra_silver
[1] 7
> pred_bra_bronze
[1] 12
```
5 medalhas de ouro, 7 de prata e 12 de bronze. Chamaremos essa primeira previsão de **Hosting factor prediction (HFP)**, que será uma base para as análises seguintes.
### Crescimento econômico
Para analisar a co-relação entre o crescimento do PIB e o crescimento de medalhas, usamos as seguintes métricas:
\begin{center}
$ggf_{c(y)} = \frac{\bar{G}_{c(y-4,y)}}{\bar{G}_{w(y-4,y)}}$
\end{center}
\begin{center}
\center$mgr_{c(y)} = \frac{S_{c(y)}}{S_{c(y-4)}}$
\end{center}
onde $\bar{G}_{c(y,y-4)}$ é o crescimento médio do PIB do país $c$ no período $[y-4, y[$, $\bar{G}_{w(y,y-4)}$ é o crescimento médio do PIB mundial no período $[y-4, y[$ e $S_{c(y)}$ é o *score* de medalhas para o país $c$ no ano $y$.
### Co-relação: *Score* de medalhas x PIB
O coeficiente de co-relação entre duas variáveis corresponde às suas covariâncias dividido
pelo produto de seus desvios padrões individuais. É uma medida normalizada que captura o quanto duas variáveis estão linearmente relacionadas. O valor de um coeficiente de co-relação varia entre -1 (variáveis negativamente relacionadas linearmente) e 1 (variáveis positivamente relacionadas linearmente).
### Investimentos em esporte
Para analisar o impacto do investimento em esportes no número de medalhas, consideramos o orçamento do Ministério dos Esportes, disponibilizado através da Lei Orçamentária Anual (LOA), elaborada ano a ano pelo poder executivo federal. A LOA é uma lei que estabelece despesas e receitas que serão realizadas no próximo ano. Desta maneira, foram coletados os orçamentos dos últimos 6 anos (2010 -- 2015), a fim de se comparar o ganho de medalhas em 2012 com o possível ganho a ser obtido em 2016. A tabela a seguir mostra os dados de investimento:
```{r eval=FALSE}
> sports_investment_bra
year budget population budget_pp
1 2010 1.50 195.2 7.68
2 2011 2.50 196.9 12.69
3 2012 3.44 198.6 17.32
4 2013 3.38 200.3 16.87
5 2014 3.39 202.7 16.72
6 2015 3.01 204.4 14.72
```
Os dados nos mostram que a média anual de investimento nos anos anteriores à olimpíada de 2012 foi de 10.18 milhões de reais per capita. Nos anos anteriores à 2016 (2012 -- 2015), a média anual de investimento foi de 16.40 milhões de reais per capita. Se considerarmos uma relação direta, chegaríamos à um score de medalhas de 45.10, como mostra a regra de três abaixo:
```{r eval=FALSE}
budget_pp_2016 <- mean(budget_pp[which(year >= 2012)])
> budget_pp_2016
[1] 16.4075
budget_pp_2012 <- mean(budget_pp[which(year < 2012)])
> budget_pp_2012
[1] 10.185
bra_score_2012 <- 3*tail(medals$Brazil..Gold, 1) + 2*tail(medals$Brazil..Silver, 1) +
tail(medals$Brazil..Bronze, 1)
x <- (bra_score_2016*bra_score_2012)/bra_score_2012
> x
[1] 45.10653
```
Com este valor, se fizermos a diferença do novo score pelo HFP ja calculado, temos: 45.10 - 39.2 = 5.91. No entanto, vamos considerar também os dados de investimento feito pelo Reino Unido (sede das Olimpíadas de 2012), a fim de se realizar uma comparação mais assertiva. Nos anos anteriores à Olimpíada de 2000, o Reino Unido investiu em média cerca de 3.22 milhões de reais per capita em esportes. Para 2012, foi investido cerca de 13.18 milhões de reais nos anos anteriores. Isso corresponde a um aumento de cerca de 4.09x. Se analisarmos o mesmo período, em 2000 o score de medalhas para o Reino Unido foi de 60. Em 2012 foi de 140. Isso corresponde a um aumento de cerca de 2.33x.
```{r eval=FALSE}
> sports_investment_gbr
year budget population budget_pp medals_score
1 2000 0.19 58.9 3.22 60
2 2012 0.84 63.7 13.18 140
```
Portanto, conseguimos observar que a relação investimento em esportes x ganho de medalhas não é direta (1 para 1). A razão que encontramos para o caso do Reino Unido é 4.09/2.33 ~ 1.75.
```{r eval=FALSE}
ratio_budget_medals <- sports_investment_gbr$budget_pp/sports_investment_gbr$medals_score
> ratio_budget_medals[2]/ratio_budget_medals[1]
[1] 1.754215
```
Portanto, devemos atualizar nossa previsão para o Brasil, considerando o ganho no score como:
```{r eval=FALSE}
sports_inv <- (x-pred_bra_score)/1.754215
> sports_inv
[1] 3.36705
```
Ao considerar o aumento de investimentos em esporte, o acréscimo no score do Brasil é de aproximadamente 3.37. Convertendo para medalhas temos:
```{r eval=FALSE}
p2 <- sports_inv/3 + sports_inv/6 + sports_inv/9
> bra_gold_perc*p2
[1] 0.4572537
> bra_silver_perc*p2
[1] 0.6001455
> bra_bronze_perc*p2
[1] 1.000242
```
Arredondando, temos +0 medalha de ouro, +1 medalha de prata e +1 medalha de bronze em relação ao HFP.
### Competições recentes
Nessa seção, analisaremos o desempenho do Brasil nas competições mundiais mais recentes. Importante notar que para cada modalidade o ano da última competição mundial pode ser diferente. Esse levantamento permite indicar a performance atual do Brasil em modalidades que o país costuma receber medalhas. Para esta finalidade, analisaremos especialmente as modalidades em que o Brasil tradicionalmente tem melhor desempenho nas olimpíadas, como vôlei, vôlei de praia, judô e futebol.
A metodologia para essa parte é simples: para cada uma dessas modalidades, coletamos a posição do Brasil na respectiva competição mundial anterior a 2012 e comparamos com a posição do país (nessa mesma modalidade) na olimpíada de 2012. Em seguida, coletamos a posição do Brasil na respectiva competição mundial anterior a 2016 (e posterior a 2012) e fazemos uma projeção para 2016. Por exemplo, para o vôlei masculino temos o seguinte cenário:
Posição na última competição mundial antes de 2012: 1º
Posição na olimpíada de 2012: 2º
Posição na última competição mundial antes de 2016: 2º
Previsão para a olimpíada de 2016: ?
Neste caso, consideramos a projeção como sendo uma relação direta, e estimamos que o Brasil ganhará uma medalha de bronze (3ª posição) em 2016 no vôlei masculino. Por fim, aplicamos essa metodologia para cada uma das modalidades coletadas: vôlei masculino, vôlei feminino, vôlei de praia masculino, vôlei de praia feminino e futebol masculino. E também introduzimos uma projeção para o polo-aquático masculino e o handball feminino, que tiveram desempenho baixo ao longo das séries históricas, mas que em 2015 ganharam medalha de bronze e ouro (respectivamente) na última competição mundial, sendo portanto, modalidades promissoras para 2016.
Computando o somatório total da projeção de cada modalidade, obtemos um resultado de +0 medalha de ouro, -1 medalha de prata e +2 medalhas de bronze em relação ao HFP.
## Conclusões
De acordo com nossa metodologia, cujo modelo é definido basicamente por 4 dimensões -- fator sede (conjuntamente com o histórico de medalhas), crescimento econômico, investimento em esportes e competições recentes -- podemos concluir que o Brasil terá em 2016 um desempenho superior ao alcançado em 2012. No entanto, o crescimento de medalhas será pequeno, com +1 ouro, -1 prata e +2 bronze. Esse crescimento tímido se deve por conta da projeção de crescimento econômico, dimensão que vem trazendo a predição para baixo.
Como trabalho futuro, pretendemos investigar uma abordagem capaz de determinar pesos para cada uma das dimensões levadas em consideração para a construção do modelo. No atual trabalho, cada dimensão contribui com o mesmo peso para as predições. Além disso, pretendemos aprimorar a análise feita para as competições recentes, coletando mais modalidades e integrando às outras dimensões do modelo para que tenhamos predições mais assertivas.<file_sep>/src/gdp.R
jforny <- "~/rstudio/OlympicsPrediction/"
dgribel <- "~/PUC-MSc/datascience/olympics/"
path <- dgribel
source_ gdp <- paste(path, "dataset/ny.gdp.mktp.kd.zg_Indicator_en_csv_v2/ny.gdp.mktp.kd.zg_Indicator_en_csv_v2.csv", sep = "")
gdp <- read.table(source_ gdp,
header = T,
skip = 1,
sep = ",",
fill = TRUE,
stringsAsFactors = FALSE)
# hosts <- c("Spain", "United.States", "Australia", "Greece", "China", "United Kingdom")
# metadata <- gdp[, head(names(gdp), 4)]
# observations <- gdp[, !names(gdp) %in% head(names(gdp), 4)]
# Data cleaning based on hosts and years
# gdp[gdp$Country.Name %in% hosts, names(gdp) %in% c("Country.Name", years)]
years <- c("X1992", "X1996", "X2000", "X2004", "X2008", "X2012")
nrows = nrow(gdp)
ggfconsolidated = data.frame(yearcountry = character(), country = character(), year4 = numeric(), year3 = numeric(), year2 = numeric(),
year1 = numeric(), average = numeric(), globalaverage = numeric(), ggf = numeric())
for(year in years) {
worldgdpmean = mean(gdp[,year], na.rm=TRUE)
for(i in 1:nrows) {
yearpos = which(colnames(gdp)==year)
pastgdpmean = rowMeans(gdp[i, (yearpos - 4):(yearpos - 1)])
ggf = pastgdpmean/worldgdpmean
country = gdp[i, 1]
yearcountry = paste(year, country, sep='_')
# tuple = c(yearcountry, country, gdp[i, yearpos-4], gdp[i, yearpos-3], gdp[i, yearpos-2], gdp[i, yearpos-1], pastgdpmean, worldgdpmean, ggf)
ggfconsolidated <- as.data.frame(rbind(as.matrix(ggfconsolidated), c(yearcountry, country, gdp[i, yearpos-4], gdp[i, yearpos-3], gdp[i, yearpos-2], gdp[i, yearpos-1], pastgdpmean, worldgdpmean, ggf)))
# ggfconsolidated = rbind(ggfconsolidated, tuple)
print(tuple)
}
}
#write.csv(ggfconsolidated, file = "MyData.csv")
# print(ggfconsolidated)
<file_sep>/README.md
# datascience-olympics
Predictive model applied to the 2016 Olympic Games. The focus is on the medal table to be achieved by Brazil, the host country of the competition. We analyze historical series from economic indicators, recent competitions, and data on investment in sports.
<file_sep>/src/indicator.R
# edit this source to change indicator dataset
jforny <- "~/rstudio/OlympicsPrediction/"
dgribel <- "~/PUC-MSc/datascience/olympics/"
path <- dgribel
source_gdp_growth <- paste(path, "dataset/gdp_growth.csv", sep = "")
ind <- read.csv(source_gdp_growth, header = T, sep = ",", fill = TRUE, stringsAsFactors = FALSE)
# removing unnecessary columns
if("X...Series.Name" %in% colnames(ind)) {
ind <- subset(ind, select = -X...Series.Name)
}
if("Series.Name" %in% colnames(ind)) {
ind <- subset(ind, select = -Series.Name)
}
ind <- subset(ind, select = -Series.Code)
ind <- subset(ind, select = -Time.Code)
# removing 1960 -- everything is blank
ind <- ind[-1, ]
# removing last rows -- blank or not important
ind <- head(ind, -6)
years <- c()
# filling years with last K games
last_n_games <- 6
j <- 1
for(i in (last_n_games-1):0) {
years[j] <- 2012 - 4*i
j <- j+1
}
# renaming country names
colnames(ind)[-1] <- gsub("\\.\\.\\.", ".", colnames(ind)[-1])
colnames(ind)[-1] <- gsub("\\.\\.", ".", colnames(ind)[-1])
colnames(ind)[-1] <- substr(colnames(ind)[-1], 1, nchar(colnames(ind)[-1])-5)
colnames(ind)[which(colnames(ind)=="United.Kingdom")] <- "Great.Britain"
colnames(ind)[which(colnames(ind)=="Korea.Rep")] <- "South.Korea"
colnames(ind)[which(colnames(ind)=="Russian.Federation")] <- "Russia"
# calculate world mean indicator (except for country in question) considering past 4 years for each year in period
world_ind_growth <- function(years, country) {
world_mean_ind <- c()
for(j in(1:last_n_games)) {
world_mean_ind <- rbind(world_mean_ind,
rowMeans(ind[which(ind$Time >= (years[j]-4) & ind$Time <= years[j]-1),][-c(1, which(colnames(ind)==country))],
na.rm=TRUE))
}
return(world_mean_ind)
}
# calculate indicator for a country considering past 4 years for each year in period
country_ind_growth <- function(years, country) {
country_ind <- c()
for(i in(1:last_n_games)) {
country_ind <- rbind(country_ind,
rowMeans(ind[which(ind$Time >= (years[i]-4) & ind$Time <= years[i]-1),][which(colnames(ind)==country)],
na.rm=TRUE))
}
return(country_ind)
}
# calculate indicator factor -- ratio between country mean indicator and global mean for each year in period
ind_factor <- c()
for(ct in colnames(ind)[-1]) {
ind_factor <- rbind(ind_factor, rowMeans(country_ind_growth(years, ct))/rowMeans(world_ind_growth(years, ct)))
}
colnames(ind_factor) <- years
rownames(ind_factor) <- colnames(ind)[-1]
|
b8c3c1e68aa9fd51f1a383dc6eb4642db863962d
|
[
"Markdown",
"R",
"RMarkdown"
] | 6 |
R
|
Karagul/datascience-olympics_RMD
|
7562f0161689ec150183a290200e284a3f997082
|
f2de7ea41f57c7d3e8b4b4bc1266c6ca450e8796
|
refs/heads/master
|
<repo_name>CaptGillespie/Dojo-Survey<file_sep>/Survey/Controllers/HomeController.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Survey.Models;
namespace Survey.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost("result")]
public IActionResult Result(string name, string location, string language, string textarea)
{
ViewBag.name = name;
ViewBag.location = location;
ViewBag.language = language;
ViewBag.textarea = textarea;
return View();
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}
}
|
e7fe8851246bb4d354dc2f1fc6be9df98462bf8d
|
[
"C#"
] | 1 |
C#
|
CaptGillespie/Dojo-Survey
|
f938cb894ae4d020a846d9be9c9afa47a2cd3246
|
d5ed1874938781103d31d2cc62575cbe4d87bd32
|
refs/heads/master
|
<file_sep>from odoo import http
class BusTest(http.Controller):
@http.route('/bus_test/test', type='http', auth='none')
def test(self):
http.request.env['bus.bus'].sendone('bus_test', {'message':'This is test',
'title': 'Test'})
return 'ok'
<file_sep>odoo.define("bus_test.notification", function (require) {
"use strict"
var WebClient = require('web.WebClient')
var session = require('web.session')
var channel = 'bus_test'
WebClient.include({
start: function() {
this._super()
this.call('bus_service', 'addChannel', channel);
this.call('bus_service', 'onNotification', this, this.on_agent_test_notification)
console.log('Listening on ', channel)
},
on_agent_test_notification: function (notification) {
for (var i = 0; i < notification.length; i++) {
var ch = notification[i][0]
var msg = notification[i][1]
if (ch == channel) {
try {
this.handle_agent_test_message(msg)
}
catch(err) {console.log(err)}
}
}
},
handle_agent_test_message: function(msg) {
console.log(msg)
if (typeof msg == 'string')
var message = JSON.parse(msg)
else
var message = msg
if (message.warning == true)
this.do_warn(message.title, message.message, message.sticky)
else
this.do_notify(message.title, message.message, message.sticky)
},
})
})
<file_sep># -*- encoding: utf-8 -*-
{
'name': 'Odoo bus test',
'version': '192.168.127.12',
'author': 'Odooist',
'maintainer': 'Odooist',
'support': '<EMAIL>',
'license': 'LGPL-3',
'category': 'Tools',
'summary': 'Test odoo bus responsiveness',
'description': "",
'depends': ['bus'],
'data': [
'views/resources.xml',
],
'demo': [
],
'installable': True,
'application': False,
'auto_install': False,
'images': [],
}
|
a887cbf5b20887d0daa64fe08e29d7f4ae3c129f
|
[
"JavaScript",
"Python"
] | 3 |
Python
|
fah-odoo/12
|
b0eb65f6af6002eab4e48f6cbb5e7d749ae77411
|
9cf8f99ef424f45b96bcfbad03630b88f494a29f
|
refs/heads/master
|
<file_sep><?php
require_once("include/head.php");
$sql = "SELECT * FROM `states`";
$state = $conn->query($sql);
if(isset($_GET['id']))
{
if(isset($_GET['delete'])){
$sql = "DELETE FROM `states` WHERE id ='".$_GET['id']."'";
$delete = $conn->query($sql);
header("Location:state.php");
}
$sql = "SELECT * FROM `states` WHERE id = ".$_GET['id'];
$result = $conn->query($sql);
$state_row = $result->fetch_assoc();
}
?>
<form method="POST">
<h1 align="center">Add New State :</h1>
<table align="center" cellspacing="0px" cellpadding="10px" width="90%">
<tr>
<td align="right">
<label style="font-size:30px">Add State:</label>
</td>
<td>
<input type="text" name="new_state" style="width:100%" autofocus="true" value="<?php echo isset($state_row['state_name'])?$state_row['state_name']:'' ?>">
</td>
<td align="left">
<button type="submit" name="add_state" class="blue">Add</button>
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['add_state']))
{
if(isset($_POST['add_state'])&&!empty($_POST['new_state']))
{
if(isset($_GET['id']))
{
$sql = "SELECT * FROM `states` WHERE state_name = '".$_POST['new_state']."'";
$compare = $conn->query($sql);
if(mysqli_num_rows($compare)>0){
echo "<h1 align='center' style='color:red'> Allready Exist..</h1>";
}
else{
$sql = "UPDATE `states` SET `state_name` = '".$_POST['new_state']."'";
$update = $conn->query($sql);
header("Location:state.php");
}
}
else{
$sql = "SELECT * FROM `states` WHERE state_name = '".$_POST['new_state']."'";
$compare = $conn->query($sql);
if(mysqli_num_rows($compare)>0)
{
echo "<h1 align='center' style='color:red'> Allready Exist..</h1>";
}
else{
$sql = "INSERT INTO `states`(`state_name`)"."VALUES('".$_POST['new_state']."')";
$add = $conn->query($sql);
header("Location:state.php");
}
}
}
else
{
echo "<h1 align='center' style='color:red'> Please Enter State Name..</h1>";
}
}
?>
<fieldset>
<legend>
<h1 align="center">State List:</h1>
</legend>
<form method="POST">
<table align="center" cellspacing="0px" cellpadding="10px" width="90%" bgcolor="white">
<tr>
<thead>
<th>
Sr.no
</th>
<th>
State Name
</th>
<th>
Actions
</th>
</thead>
</tr>
<tbody>
<tr>
<?php
$count=0;
while($row = $state->fetch_assoc())
{
$count++;
echo "<tr>";
echo "<td align='center'>".$count."</td>";
echo "<td align='center'>".ucwords($row['state_name'])."</td>";
echo "<td align='center'>
<a href='state.php?id=".$row['id']."'><button type='button' name='edit_city' class='yellow'>Edit</button></a>
<a href='state.php?delete=1&id=".$row['id']."'><button type='button' name='delete_city' class='red'>Delete</button></a>
</td>";
}
?>
</tr>
</tbody>
</table>
</form>
</fieldset><file_sep> <?php
require_once("include/head.php");
$sql ="SELECT ct.cityname,st.state_name,country.country_name,u.* FROM users AS u INNER JOIN cities AS ct ON u.city_id = ct.id INNER JOIN states AS st ON u.state_id = st.id
INNER JOIN countries AS country ON u.country_id = country.id WHERE u.id='".$_GET['id']."'";
echo $sql;
$joindata = $conn->query($sql);
$row = $joindata->fetch_assoc();
print_r($row);
// print_r($row['photo']);
?>
<fieldset>
<legend>
<?php echo "<img src='./uploads/photo/".$row['photo']."' width='150px' height='150px'>";?>
</legend>
<table cellpadding="10px" cellspacing="0px" border="0" width="90%" align="center">
<tr>
<?php
echo "<tr>";
echo "<td align='center'><span class='white'><b>Name :</b>".ucwords($row['first_name']." ".$row['last_name'])."</span></td>";
echo "<td align='center'><span class='white'><b>Email :</b>".$row['email']."</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center'><span class='white'><b>Address :</b>".$row['address']."</span></td>";
echo "<td align='center'><span class='white'><b>Date of Birth :</b>".$row['dob']."</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center'><span class='white'><b>Phone no :</b>".$row['phone_no']."</span></td>";
echo "<td align='center'><span class='white'><b>Hobbies :</b>".$row['hobby_id']."</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center'><span class='white'><b>City name :</b>".$row['cityname']."</span></td>";
echo "<td align='center'><span class='white'><b>State :</b>".$row['state_name']."</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center'><span class='white'><b>Country name :</b>".$row['country_name']."</span></td>";
echo "</tr>";
echo "<tr>";
echo "<td align='center' colspan='2'><a href='edit.php?id=".base64_encode($row['id'])."'><button type='button' class='yellow'><span >Edit</span></button>
<a href='index.php'><button type='button' class='blue'><span >Cancel</span></button>
</td>";
echo "</tr>";
?>
</tr>
</tbody>
</table>
</fieldset><file_sep><?php
if(isset($_GET['id'])){
//Call Config File
require_once("includes/config.php");
$id = base64_decode($_GET['id']);
$data = mysqli_query($conn, "select users.*, cities.id as cityid, cities.cityname from cities inner join users on users.city_id=cities.id where users.id='".$id."'");
if(mysqli_num_rows($data))
{
$row = mysqli_fetch_assoc($data);
}
else
{
echo "Your Data is not available against request";
}
}
else
{
header("location:index.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<link href="css/style.css" rel="stylesheet"/>
</head>
<body>
<table cellpadding="10px" cellspacing="0px" border="1" align="center" width="600px">
<tr>
<td><label>Name : </label></td>
<td><?php echo $row['name'];?></td>
</tr>
<tr>
<td><label>Address : </label></td>
<td><?php echo $row['address'];?></td>
</tr>
<tr>
<td><label>Gender : </label></td>
<td><?php echo $row['gender'];?></td>
</tr>
<tr>
<td><label>Hobbies : </label></td>
<td>
<?php
$hobbies = explode(", ",$row['hobby_id']);
foreach($hobbies as $hobrow=>$value){
$hobbytitle = mysqli_fetch_assoc(mysqli_query($conn,"Select id,title from hobbies where id='".$value."'"));
echo $hobbytitle['title']. ", ";
}
?>
</td>
</tr>
<tr>
<td><label>City : </label></td>
<td><?php echo $row['cityname'];?></td>
</tr>
<tr>
<td><label>Photo : </label></td>
<td><img width="50px" src="uploads/photo/<?php echo $row['photo'];?>" alt="Photo"/></td>
</tr>
<tr>
<td colspan="2">
<button type="button" onclick="window.location='index.php'">Cancel</button>
</td>
</tr>
</table>
</body>
</html>
<file_sep><?php
require_once("include/head.php");
$sql = "SELECT * FROM `cities`";
$cities = $conn->query($sql);
if(isset($_GET['id']))
{
if(isset($_GET['delete'])){
$sql = "DELETE FROM `cities` WHERE id ='".$_GET['id']."'";
$delete = $conn->query($sql);
header("Location:city.php");
}
$sql = "SELECT * FROM `cities` WHERE id = ".$_GET['id'];
$result = $conn->query($sql);
$city_row = $result->fetch_assoc();
}
?>
<form method="POST">
<h1 align="center">Add New City:</h1>
<table align="center" cellspacing="0px" cellpadding="10px" width="90%">
<tr>
<td align="right">
<label style="font-size:30px">Add City:</label>
</td>
<td>
<input type="text" name="new_city" style="width:100%" autofocus="true" value="<?php echo isset($city_row['cityname'])?$city_row['cityname']:'' ?>">
</td>
<td align="left">
<button type="submit" name="add_city" class="blue">Add</button>
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['add_city']))
{
if(isset($_POST['add_city'])&&!empty($_POST['new_city']))
{
if(isset($_GET['id']))
{
$sql = "SELECT * FROM `cities` WHERE cityname = '".$_POST['new_city']."'";
$compare = $conn->query($sql);
if(mysqli_num_rows($compare)>0){
echo "<h1 align='center' style='color:red'> Allready Exist..</h1>";
}
else{
$sql = "UPDATE `cities` SET `cityname` = '".$_POST['new_city']."'";
$update = $conn->query($sql);
header("Location:city.php");
}
}
else{
$sql = "SELECT * FROM `cities` WHERE cityname = '".$_POST['new_city']."'";
$compare = $conn->query($sql);
if(mysqli_num_rows($compare)>0)
{
echo "<h1 align='center' style='color:red'> Allready Exist..</h1>";
}
else{
$sql = "INSERT INTO `cities`(`cityname`)"."VALUES('".$_POST['new_city']."')";
$add = $conn->query($sql);
header("Location:city.php");
}
}
}
else
{
echo "<h1 align='center' style='color:red'> Please Enter City Name..</h1>";
}
}
?>
<fieldset>
<legend>
<h1 align="center">City List:</h1>
</legend>
<form method="POST">
<table align="center" cellspacing="0px" cellpadding="10px" width="90%" bgcolor="white">
<tr>
<thead>
<th>
Sr.no
</th>
<th>
City Name
</th>
<th>
Actions
</th>
</thead>
</tr>
<tbody>
<tr>
<?php
$count=0;
while($row = $cities->fetch_assoc())
{
$count++;
echo "<tr>";
echo "<td align='center'>".$count."</td>";
echo "<td align='center'>".ucwords($row['cityname'])."</td>";
echo "<td align='center'>
<a href='city.php?id=".$row['id']."'><button type='button' name='edit_city' class='yellow'>Edit</button></a>
<a href='city.php?delete=1&id=".$row['id']."'><button type='button' name='delete_city' class='red'>Delete</button></a>
</td>";
}
?>
</tr>
</tbody>
</table>
</form>
</fieldset><file_sep><?php
require_once("include/head.php");
// exit();
$sql = "SELECT * FROM cities";
$city = $conn->query($sql);
$sql = "SELECT * FROM `users` WHERE id ='".base64_decode($_GET['id'])."'";
$userdata = $conn->query($sql);
// $row = $userdata->fetch_assoc();
// $citydata = $city->fetch_assoc();
echo $citydata['id'];
print_r($citydata);
echo $row['city'];
print_r($row);
$sql = "SELECT * FROM states";
$state = $conn->query($sql);
$sql = "SELECT * FROM countries";
$country = $conn->query($sql);
$sql = "SELECT * FROM hobbies";
$hobby = $conn->query($sql);
?>
<h1 align="center">Edit Your Details:</h1>
<form method ="POST" action="#" enctype="multipart/form-data">
<table cellpadding="10px" cellspacing="10px" align="center" width="75%" bgcolor="white">
<tr>
<td colspan="4"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Full Name:</span></label></td>
<td align=""><input type="text" name="first_name" value="<?php echo isset($row['first_name'])?$row['first_name']:'';?>"><br> First Name</td>
<td align="left"><input type="text" name="last_name" value="<?php echo isset($row['last_name'])?$row['last_name']:'';?>"><br> Last Name</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Email</span></label></td>
<td colspan="2"><input type="text" name="email" value="<?php echo isset($row['email'])?$row['email']:'';?>"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Address</span></label></td>
<td colspan="2"><textarea name="address" rows="8" cols="100"><?php echo isset($row['address'])?$row['address']:'';?></textarea></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Date of Birth</span></label></td>
<td colspan="2"><input type="date" name="dob" value="<?php echo isset($row['dob'])?$row['dob']:'';?>"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Phone Number</span></label></td>
<td colspan="2"><input type="number" name="phone_no" value="<?php echo isset($row['phone_no'])?$row['phone_no']:'';?>"></td>
</tr>
<tr>
<tr>
<td align="center"><label><span class="bold">City</span></label></td>
<td colspan="2">
<select name="city">
<option>Select</option>
<?php while($citydata = $city->fetch_assoc()){?>
<option value = "<?php echo $citydata['id'];?>" <?php echo(isset($row['city'])&&$row['city']==$citydata['id']?'selected':'');?>> <?php echo $citydata['cityname'];?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">State</span></label></td>
<td colspan="2">
<select name="state">
<option>Select</option>
<?php
while($row = $state->fetch_assoc())
{
echo "<option value = ".$row['id'].">".$row['state_name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Country</span></label></td>
<td colspan="2">
<select name="country">
<option>Select</option>
<?php
while($row = $country->fetch_assoc())
{
echo "<option value = ".$row['id'].">".$row['country_name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Hobbies</span></label></td>
<td colspan="2">
<?php
while($row = $hobby->fetch_assoc())
{
echo "<div class='mydiv'><input type='checkbox' name='hobby_id[]' value=".$row['id'].">".$row['hobby_name']."</div>";
}
?>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Photo</span></label></td>
<td colspan="2"><input type="file" name="photo"/></td>
</td>
</tr>
<tr>
<td colspan="3" align="center">
<button type="submit" name="save">Save</button>
<span class="cancel_btn"><a href="index.php"><button type="button" name="cancel">Back</button></a></span>
</td>
</tr>
</table>
</form>
</body>
</html><file_sep><?php
require_once("include/head.php");
if(isset($_POST['delete_user']))
{
$sql = "DELETE FROM users WHERE id = ".base64_decode($_GET['id']);
$delete = $conn->query($sql);
header("Location:index.php");
echo $sql;
}
?>
<h1 align="center">Are You Sure You Want To Delete The Records?</h1>
<form method="POST">
<div id="delete_page">
<button type="submit" name="delete_user" class="red">Delete</button>
<a href="index.php" ><button type="button" class="green">Cancel</button></a>
</div>
</form><file_sep> <?php
require_once("include/head.php");
$sql = "SELECT * FROM users";
$userdata = $conn->query($sql);
?>
<fieldset>
<legend>
<h1 align="center">Users List:</h1>
</legend>
<div style="float:right"><a href="add.php" align="right"><button type="button" class="blue" align="right"><span>Add User</span></button></a></div>
<table cellpadding="10px" cellspacing="0px" border="0" width="90%" align="center" bgcolor="white">
<thead>
<tr>
<th align="center">
Sr.no
</th>
<th align="center">
Photo
</th>
<th align="center">
Name
</th>
<th align="center">
Actions
</th>
</tr>
</thead>
<tbody>
<tr>
<?php
$count=0;
while($row = $userdata->fetch_assoc())
{
$count++;
echo "<tr>";
echo "<td align='center'>".$count."</td>";
echo "<td align='center'><img src='./uploads/photo/".$row['photo']."' width='50px' height='50px'</td>";
echo "<td align='center'>".ucwords($row['first_name']." ".$row['last_name'])."</td>";
echo "<td align='center'><a href='view.php?id=".$row['id']."'><button>View</button></a>";
echo "<a href='delete.php?id=".base64_encode($row['id'])."'><button type='button' class='red'>Delete</button></a></td>";
}
?>
</tr>
</tbody>
</table>
</fieldset><file_sep><?php
// Connection with Server
$conn = mysqli_connect("localhost","root","") or die("Unable to connect with server. please check credentials");
// Selection of Database
mysqli_select_db($conn,"batch_62_phpbasics") or die("Unable to select Database. Please contact Database Admin");
?><file_sep><!DOCTYPE html>
<html>
<head>
<link href="css/style.css" type="text/css" rel="stylesheet">
</head>
<body id="grad1">
<?php
$server = "localhost";
$username ="root";
$password ="";
$dbname ="mytasktbs";
$conn = mysqli_connect($server,$username,$password,$dbname);
if(!$conn){
die("Unable to connect with server. please check credentials" .mysqli_connect_error());
}else{
// echo " Connection Successfull";
}
?>
<div class="nav">
<ul>
<li>
<a href="index.php">Users</a>
</li>
<li>
<a href="city.php">City</a>
</li>
<li>
<a href="state.php">State</a>
</li>
<li>
<a href="country.php">Country</a>
</li>
<li>
<a href="hobbies.php">Hobbies</a>
</li>
</ul>
</div><file_sep><?php
require_once("include/head.php");
$sql = "SELECT * FROM `hobbies`";
$hobby = $conn->query($sql);
if(isset($_GET['id']))
{
if(isset($_GET['delete'])){
$sql = "DELETE FROM `hobbies` WHERE id ='".$_GET['id']."'";
$delete = $conn->query($sql);
header("Location:hobbies.php");
}
$sql = "SELECT * FROM `hobbies` WHERE id = ".$_GET['id'];
$result = $conn->query($sql);
$hobby_row = $result->fetch_assoc();
}
?>
<form method="POST">
<h1 align="center">Add New Hobby :</h1>
<table align="center" cellspacing="0px" cellpadding="10px" width="90%">
<tr>
<td align="right">
<label style="font-size:30px">Add Hobby:</label>
</td>
<td>
<input type="text" name="new_hobby" style="width:100%" autofocus="true" value="<?php echo isset($hobby_row['hobby_name'])?$hobby_row['hobby_name']:'' ?>">
</td>
<td align="left">
<button type="submit" name="add_hobby" class="blue">Add</button>
</td>
</tr>
</table>
</form>
<?php
if(isset($_POST['add_hobby']))
{
if(isset($_POST['add_hobby'])&&!empty($_POST['new_hobby']))
{
if(isset($_GET['id']))
{
$sql = "SELECT * FROM `hobbies` WHERE hobby_name = '".$_POST['new_hobby']."'";
$compare = $conn->query($sql);
if(mysqli_num_rows($compare)>0){
echo "<h1 align='center' style='color:red'> Allready Exist..</h1>";
}
else{
$sql = "UPDATE `hobbies` SET `hobby_name` = '".$_POST['new_hobby']."'";
$update = $conn->query($sql);
header("Location:hobbies.php");
}
}
else{
$sql = "SELECT * FROM `hobbies` WHERE hobby_name = '".$_POST['new_hobby']."'";
$compare = $conn->query($sql);
if(mysqli_num_rows($compare)>0)
{
echo "<h1 align='center' style='color:red'> Allready Exist..</h1>";
}
else{
$sql = "INSERT INTO `hobbies`(`hobby_name`)"."VALUES('".$_POST['new_hobby']."')";
$add = $conn->query($sql);
header("Location:hobbies.php");
}
}
}
else
{
echo "<h1 align='center' style='color:red'> Please Enter State Name..</h1>";
}
}
?>
<fieldset>
<legend>
<h1 align="center">Hobby List:</h1>
</legend>
<form method="POST">
<table align="center" cellspacing="0px" cellpadding="10px" width="90%" bgcolor="white">
<tr>
<thead>
<th>
Sr.no
</th>
<th>
Hobby Name
</th>
<th>
Actions
</th>
</thead>
</tr>
<tbody>
<tr>
<?php
$count=0;
while($row = $hobby->fetch_assoc())
{
$count++;
echo "<tr>";
echo "<td align='center'>".$count."</td>";
echo "<td align='center'>".ucwords($row['hobby_name'])."</td>";
echo "<td align='center'>
<a href='hobbies.php?id=".$row['id']."'><button type='button' name='edit_city' class='yellow'>Edit</button></a>
<a href='hobbies.php?delete=1&id=".$row['id']."'><button type='button' name='delete_city' class='red'>Delete</button></a>
</td>";
}
?>
</tr>
</tbody>
</table>
</form>
</fieldset><file_sep><?php
function validate_form()
{
$errors = array();
if(isset($_POST['name']) && empty(trim($_POST['name'])))
{
$errors['name'] = "Please Enter Your Name";
}
if(isset($_POST['email_address']) && empty(trim($_POST['email_address'])))
{
$errors['email_address'] = "Please Enter Your Email Address";
}
if(isset($_POST['password']) && empty(trim($_POST['password'])))
{
$errors['password'] = "Please Enter Password";
}
if(empty($_POST['intersts']))
{
$errors['intersts'] = "Please select intersts";
}
return $errors;
}
?><file_sep><?php
//Call Config File
require_once("includes/config.php");
//Get All Active cities from table
$getallcities =mysqli_query($conn,"select id,cityname from cities where status='Active' order by cityname");
//Get All Active Hobbies from table
$getallhobbies =mysqli_query($conn,"select id,title from hobbies where status='Active' order by title");
// Check button Click or Not
if(isset($_POST['save']))
{
if($_FILES['photo']['error']==0)
{
$filename = time().$_FILES['photo']['name'];
$src=$_FILES['photo']['tmp_name']; //Find Source
$dest="uploads/photo/".$filename; //Set Destination
if(move_uploaded_file($src,$dest))
{
$_POST['photo'] = $filename;
// Fire insert query
$insetuser = "INSERT INTO users SET
name='".ucwords($_POST['name'])."',
password='".md5($_POST['<PASSWORD>'])."',
address='".$_POST['address']."',
gender='".$_POST['gender']."',
city_id='".$_POST['city_id']."',
hobby_id='".implode(", ",$_POST['hobby_id'])."',
photo='".$_POST['photo']."',
created=now()";
if(mysqli_query($conn,$insetuser))
{
//echo "User has been registered Successfully";
unset($_POST);
header("location: index.php");
}
else
{
echo "Unable to Register Please try again";
}
}
else
{
echo "Unable to Upload file";
}
}
else
{
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Form</title>
<link href="css/style.css" rel="stylesheet"/>
</head>
<body>
<form method="post" action="#" enctype="multipart/form-data">
<table cellpadding="10px" cellspacing="0px" border="1" align="center" width="600px">
<tr>
<td>
<label>Name : </label><br/>
<input type="text" name="name" value="<?php echo isset($_POST['name'])?ucwords($_POST['name']):'';?>"/>
</td>
</tr>
<tr>
<td>
<label>Password : </label><br/>
<input type="<PASSWORD>" name="password"/>
</td>
</tr>
<tr>
<td>
<label>Address : </label><br/>
<textarea rows="5" col="30" name="address"></textarea>
</td>
</tr>
<tr>
<td>
<label>Gender : </label><br/>
<input type="radio" name="gender" value="Male"/> Male
<input type="radio" name="gender" value="Female"/> Female
<input type="radio" name="gender" value="Other"/> Other
</td>
</tr>
<tr>
<td>
<label>Hobbies : </label><br/>
<?php while($hobbyrow = mysqli_fetch_array($getallhobbies)){?>
<input type="checkbox" name="hobby_id[]" value="<?php echo $hobbyrow['id'];?>" <?php echo (isset($_POST['hobby_id']) && in_array($hobbyrow['title'],$_POST['hobby_id']))?'checked':'';?> /><?php echo $hobbyrow['title'];?>
<?php } ?>
</td>
</tr>
<tr>
<td>
<label>City : </label><br/>
<select name="city_id">
<option>-- Select City--</option>
<?php while($cityrow = mysqli_fetch_array($getallcities)){?>
<option value="<?php echo $cityrow['id'];?>"><?php echo $cityrow['cityname'];?></option>
<?php } ?>
</select>
</td>
</tr>
<tr>
<td>
<label>Photo : </label><br/>
<input type="file" name="photo"/>
</td>
</tr>
<tr>
<td>
<button type="submit" name="save">Submit</button>
<button type="button" onclick="window.location='index.php'">Cancel</button>
</td>
</tr>
</table>
</form>
</body>
</html>
<file_sep><?php
//Call Config File
if(isset($_GET['id'])){
require_once("includes/config.php");
// Get name of photo against id
$getphoto = mysqli_fetch_assoc(mysqli_query($conn,"select photo from users where id='".base64_decode($_GET['id'])."'"));
//print_r($getphoto['photo']);exit;
// fire delete query & Execute query
$deletedata = "delete from users where id='".base64_decode($_GET['id'])."'";
if(mysqli_query($conn,$deletedata)){
// if query get execute then only remove file from folder
unlink("uploads/photo/".$getphoto['photo']);
header("location:index.php");
}
else
{
header("location:index.php");
}
}
else
{
header("location:index.php");
}
?><file_sep><?php
require_once("include/head.php");
$sql = "SELECT * FROM cities";
$city = $conn->query($sql);
$sql = "SELECT * FROM states";
$state = $conn->query($sql);
$sql = "SELECT * FROM countries";
$country = $conn->query($sql);
$sql = "SELECT * FROM hobbies";
$hobby = $conn->query($sql);
// print_r($_POST);
if(isset($_POST['save']))
{
print_r($_FILES);
print_r($_POST);
if($_FILES['photo']['error']==0)
{
$filename = time().$_FILES['photo']['name'];
$src=$_FILES['photo']['tmp_name'];
$dest="uploads/photo/".$filename;
if(move_uploaded_file($src,$dest))
{
$_POST['photo'] = $filename;
}
}
$sql = "INSERT INTO `users`(`first_name`,`last_name`,`email`,`password`,`address`,`dob`,`phone_no`,`city_id`,`state_id`,`country_id`,`hobby_id`,`photo`)"
."VALUES('".$_POST['first_name']."','".$_POST['last_name']."','".$_POST['email']."','".$_POST['password']."','".$_POST['address']."','".$_POST['dob']."','".$_POST['phone_no']."',
'".$_POST['city']."','".$_POST['state']."','".$_POST['country']."','".implode(", ",$_POST['hobby_id'])."','".$_POST['photo']."')";
echo $sql;
if($conn->query($sql)==TRUE)
{
echo "New Record Created Successfully";
header ("Location:index.php");
}
else{
echo "Error :" .$sql ."<br>" .$conn->error;
}
}
?>
<h1 align="center">Please Fill Your Details:</h1>
<form method ="POST" action="#" enctype="multipart/form-data">
<table cellpadding="10px" cellspacing="10px" align="center" width="75%" bgcolor="white">
<tr>
<td colspan="4"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Full Name:</span></label></td>
<td align=""><input type="text" name="first_name"><br> First Name</td>
<td align="left"><input type="text" name="last_name"><br> Last Name</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Email</span></label></td>
<td colspan="2"><input type="text" name="email"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Password</span></label></td>
<td colspan="2"><input type="password" name="password"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Address</span></label></td>
<td colspan="2"><textarea name="address" rows="8" cols="100"></textarea></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Date of Birth</span></label></td>
<td colspan="2"><input type="date" name="dob"></td>
</tr>
<tr>
<td align="center"><label><span class="bold">Phone Number</span></label></td>
<td colspan="2"><input type="number" name="phone_no"></td>
</tr>
<tr>
<tr>
<td align="center"><label><span class="bold">City</span></label></td>
<td colspan="2">
<select name="city">
<option>Select</option>
<?php
while($row = $city->fetch_assoc())
{
echo "<option value = ".$row['id'].">".$row['cityname']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">State</span></label></td>
<td colspan="2">
<select name="state">
<option>Select</option>
<?php
while($row = $state->fetch_assoc())
{
echo "<option value = ".$row['id'].">".$row['state_name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Country</span></label></td>
<td colspan="2">
<select name="country">
<option>Select</option>
<?php
while($row = $country->fetch_assoc())
{
echo "<option value = ".$row['id'].">".$row['country_name']."</option>";
}
?>
</select>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Hobbies</span></label></td>
<td colspan="2">
<?php
while($row = $hobby->fetch_assoc())
{
echo "<div class='mydiv'><input type='checkbox' name='hobby_id[]' value=".$row['id'].">".$row['hobby_name']."</div>";
}
?>
</td>
</tr>
<tr>
<td align="center"><label><span class="bold">Photo</span></label></td>
<td colspan="2"><input type="file" name="photo"/></td>
</td>
</tr>
<tr>
<td colspan="3" align="center">
<button type="submit" name="save">Submit</button>
<span class="cancel_btn"><a href="index.php"><button type="button" name="cancel">Cancel</button></a></span>
</td>
</tr>
</table>
</form>
</body>
</html><file_sep><?php
//Call Config File
if(iseet($_GET['id'])){
require_once("includes/config.php");
// Get name of photo against id
// fire delete query & Execute query
// if query get execute then only remove file from folder
}
else
{
header("location:index.php");
}
?><file_sep><?php
//Call Config File
require_once("includes/config.php");
$getallusers = mysqli_query($conn, "SELECT id, name,gender,photo,created FROM users where status='Active' order by name");
?>
<!DOCTYPE html>
<html>
<head>
<title>Manage / List of Users</title>
<link href="css/style.css" rel="stylesheet"/>
</head>
<body>
<table cellpadding="10px" cellspacing="0px" border="1" align="center" width="90%">
<tr>
<td><button type="button" onclick="window.location='create_user.php'">CREATE USER</button></td>
</tr>
</table>
<table cellpadding="10px" cellspacing="0px" border="1" align="center" width="90%">
<tr>
<th>Sr</th>
<th>Name</th>
<th>Gender</th>
<th>Photo</th>
<th>Reg. On</th>
<th>Action</th>
</tr>
<?php $sr = 1; while($userrow = mysqli_fetch_array($getallusers)){?>
<tr>
<td><?php echo $sr;?></td>
<td><?php echo $userrow['name'];?></td>
<td><?php echo $userrow['gender'];?></td>
<td><img width="50px" src="uploads/photo/<?php echo $userrow['photo'];?>" alt="<?php echo $userrow['name'];?>"/></td>
<td><?php echo date("d M Y", strtotime($userrow['created']));?></td>
<td>
<a href="show_user.php?id=<?php echo base64_encode($userrow['id']);?>">Show</a> |
<a href="update_user.php?id=<?php echo base64_encode($userrow['id']);?>">Edit</a> |
<a href="delete_user.php?id=<?php echo base64_encode($userrow['id']);?>" onclick="return confirm('Do you really want to remove this record?')">Delete</a></td>
</tr>
<?php $sr++;} ?>
</table>
</body>
</html>
|
d60e0eddb8ffff02e92506bb54f6c3deb8458b4f
|
[
"PHP"
] | 16 |
PHP
|
shubhamsharma3097/mytasktbs
|
ae86ad1b30ac0088d2f4f3e23631f3e06fb34785
|
6a7d18819c87b2e422fe2fe223df49595d9d5617
|
refs/heads/master
|
<repo_name>Kirthana-S/kirthana.s<file_sep>/counting 1.c
#include <stdio.h>
int main()
{
int a,b;
scanf("%d %d",&a,&b);
int count=0;
for(int i=a;i<=b;i++){
int j=i%10;
if(j==1){
count++;
}
if(i==10 || i==100 || i==1000 || i==10000){
count++;
}
}
printf("%d",count);
return 0;
}
<file_sep>/number of characters.c
#include <stdio.h>
#include<string.h>
int main()
{
char str[]="A Global Innovation Company";
int count=0;
for(int i=0;i<strlen(str);i++){
if(str[i]!=' '){
count++;
}
}
printf("Number of Characters : %d",count);
}
<file_sep>/10th public mark.c
#include <stdio.h>
#include<string.h>
int main()
{
int n,a,b,c,d,e,a1,b1,c1,d1,e1;
printf("Enter the number of students:");
scanf("%d",&n);
printf("Enter the 1st student Quarterly marks:\n");
printf("English-");
scanf("%d\n",&a);
printf("Tamil-");
scanf("%d\n",&b);
printf("Math-");
scanf("%d\n",&c);
printf("Science-");
scanf("%d\n",&d);
printf("Social Science-");
scanf("%d\n",&e);
printf("Enter the 1st student Half yearly marks:\n");
printf("English-");
scanf("%d\n",&a1);
printf("Tamil-");
scanf("%d\n",&b1);
printf("Math-");
scanf("%d\n",&c1);
printf("Science-");
scanf("%d\n",&d1);
printf("Social Science-");
scanf("%d\n",&e1);
printf("Average of i student:\n");
printf("English-%d",(a+a1)/2);
printf("Tamil-%d",(b+b1)/2);
printf("Math-%d",(c+c1)/2);
printf("Science-%d",(d+d1)/2);
printf("Social Science-%d",(e+e1)/2);
}
|
6291fa05ce14c4e5b21daa3d00c301b12c9516c0
|
[
"C"
] | 3 |
C
|
Kirthana-S/kirthana.s
|
521f81e45ad65661e693fbe7d7b3684ad8b44cae
|
5010d72a386202c90a47ba08de30c16625fd3ece
|
refs/heads/main
|
<file_sep>// notes array will hold all the notes
let notes = [];
// grab any data from local storage and saved in a 'notes' key
let stored = JSON.parse(localStorage.getItem('notes'));
// if there is any data, spread the data into the notes array
if (stored !== null) {
notes = [...stored];
// this prevents the localStorage from being overwritten and reinitialized as an empty array if the page reloads, which would thereby virtually clear the data in localStorage.
};
// Select HTML items
const form = document.querySelector('form');
const autoResizeElements = document.querySelectorAll('.auto-resize');
const noteBoard = document.querySelector('#note-board');
// -----------------------------
// FUNCTIONALITY
// -----------------------------
// Here we create the note data by grabbing whatever information is in the form at the time of submission and saving it as an object called noteData.
// This function gets called in the saveNote()
const createNoteData = () => {
const noteData = {
id: Date.now(),
title: document.querySelector('#new-note-title').value,
content: document.querySelector('#new-note-content').value
}
return noteData;
};
// Logic for rendering notes that are saved
// This function gets called in saveNote()
const renderNote = (note) => {
// Create the dom elements needed for every note
const formWrapper = document.createElement("div");
formWrapper.classList.add("form-wrapper");
const newForm = document.createElement("form");
const title = document.createElement("input");
newForm.appendChild(title);
title.value = note.title;
const textArea = document.createElement("textarea");
newForm.appendChild(textArea);
textArea.value = note.content;
formWrapper.appendChild(newForm);
noteBoard.appendChild(formWrapper);
};
// Here we send the noteData object to the notes array and to local storage
// Therefore, saveNote() does not need to receive the form data but rather call createNoteData()
// Thus, we can use it to create eventListeners that don't need the form data passed to it, since the data gets created AFTER the event trigger.
const saveNote = (event) => {
// prevent page refresh on form submit
event.preventDefault();
// save noteData to note variable
const note = createNoteData();
// add note to notes array and localstorage
notes.push(note);
localStorage.setItem( 'notes', JSON.stringify(notes) );
// NOTE: rendering should probably not happen inside this function
renderNote(note);
// clear the form for new entries
form.reset();
};
//
if (notes) {
for (let note of notes) {
renderNote(note)
}
};
// -----------------------------
// EVENT LISTENERS
// -----------------------------
// run saveNote() whenever form is submitted
// form submissions can happen by clicking the Save button or through keyboard shortcut
form.addEventListener('submit', saveNote);
// Submit form with keyboard shortcut: metaKey + enter
document.addEventListener('keydown', (event) => {
if ( event.ctrlKey && event.key === 'Enter' ) {
document.querySelector('#save-note-btn').click()
}
});
// -----------------------------
// UX details
// -----------------------------
// This allows the textarea to automatically resize instead of remaining the same height with a scroll bar
autoResizeElements.forEach(element => {
element.addEventListener('input', (element) => autoResizeInput(element, '50px'))
});
function autoResizeInput(element, defaultHeight) {
if (element) {
// if an element has been passed in, this ternary operator will check if it was created by a dom event or if the element was already in the dom, and either way create a target variable
const target = element.target ? element.target : element;
// default height is set in case user deletes content
target.style.height = defaultHeight;
// height is changed dynamically to match however much content is in the input
target.style.height = `${target.scrollHeight}px`;
}
};
// -----------------------------
|
41ae9a056ca9ee6128cab99e8c8d918ac3cd7107
|
[
"JavaScript"
] | 1 |
JavaScript
|
dan-ville/blocknote-js
|
c75139d8448c7e8d486257d54a90b4f3daacd40f
|
c93af682ae121a858becbbf9b09d8216438f47dc
|
refs/heads/master
|
<file_sep>import React, {useState} from 'react'
import MovieCard from './MovieCard'
const SearchMovies=()=>{
const [query,setQuery]=useState("")
const [movies,setMovies]=useState([])
const searchMovie = async(e)=>{
e.preventDefault()
const url =`https://api.themoviedb.org/3/search/movie?api_key=<KEY>&language=en-US
&query=${query}&page=1&include_adult=false`;
try {
const res = await fetch(url);
const data = await res.json();
setMovies(data.results);
}catch(err){
console.error(err);
}
}
return(
<>
<form className="form" onSubmit={searchMovie}>
<label htmlFor="query" className="label">Movie Name</label>
<input type="text" placeholder=" i.e. Avengers Endgame" value={query}
onChange={(e) => setQuery(e.target.value)}
className="input"/>
<button type="submit" className="btn">Search</button>
</form>
<MovieCard movies={movies}/>
</>
)
}
export default SearchMovies
|
5a583e73374c5c6c9dd950946dacbe437a5fe2e7
|
[
"JavaScript"
] | 1 |
JavaScript
|
abhi3899/movie-search-app
|
17ebc6b06aee9ffff05fc0fea85d9dedeb398e8f
|
6637912502d22c7e5fdcc929c9fb7f5a9cc68ae2
|
refs/heads/master
|
<file_sep>module.exports = {
siteMetadata: {
title: 'This Awesome Site',
},
plugins: ['gatsby-plugin-react-helmet'],
}
|
2cd611ea509ca8027cc82e5d3fb4dd3053f9761f
|
[
"JavaScript"
] | 1 |
JavaScript
|
jasonmarkbeaton/Gatsby-tryouts
|
bac153e1b51d2782bb26b60e67231abad3e57415
|
0fb9a24aa75e4639cf9382b54f2161a4a1bf958a
|
refs/heads/master
|
<file_sep>// import firebase from 'firebase/app';
import firebase from "firebase/compat/app";
// import 'firebase/auth';
import "firebase/compat/auth";
export const auth = firebase.initializeApp( {
apiKey: "<KEY>",
authDomain: "chatplanet-8e5ce.firebaseapp.com",
projectId: "chatplanet-8e5ce",
storageBucket: "chatplanet-8e5ce.appspot.com",
messagingSenderId: "452105934238",
appId: "1:452105934238:web:96f50a2666c35e7596b28f",
}).auth();
|
322ec00e76590fc92eef695189427bd4332d29e1
|
[
"JavaScript"
] | 1 |
JavaScript
|
mrBondD1/ChatPlanet
|
f1882ac1f548e698df6fa944b02794fcd81faf36
|
2e6450f0415d15bee25320dca1316c5a2b7ec235
|
refs/heads/master
|
<file_sep>from django.shortcuts import render, redirect
from .models import Inventory
# Create your views here.
def inventory_list(request):
inventories = Inventory.objects.all()
query = request.GET.get('q')
if query:
inventories = inventories.filter(
Q(name__icontains=query)|
Q(store__name__icontains=query)
).distinct()
# favorite_list = []
# if request.user.is_authenticated:
# favorite_list = request.user.favoriterestaurant_set.all().values_list('restaurant', flat=True)
context = {
"inventories": inventories,
# "favorite_list": favorite_list
}
return render(request, 'list.html', context)
|
3cb10fa877837b8f637ed54b7408a10375da477c
|
[
"Python"
] | 1 |
Python
|
khm56/django_advanced_01
|
b2ffda06609f1486329122cc8a327c4b1b2a051b
|
a48eea637d5d9c3d2653fc8f27426650fd44969d
|
refs/heads/master
|
<file_sep>#!/bin/bash
cat <<EOF
################################################################################
Welcome to the ghcr.io/servercontainers/rsync
################################################################################
You'll find this container sourcecode here:
https://github.com/ServerContainers/rsync
The container repository will be updated regularly.
################################################################################
EOF
INITALIZED="/.initialized"
if [ ! -f "$INITALIZED" ]; then
echo ">> CONTAINER: starting initialisation"
##
# rsyncd secrets ENVs
##
for I_CONF in "$(env | grep '^RSYNC_SECRET_')"
do
ACCOUNT_NAME=$(echo "$I_CONF" | cut -d'=' -f1 | sed 's/HTACCESS_ACCOUNT_//g' | tr '[:upper:]' '[:lower:]')
CONF_CONF_VALUE=$(echo "$I_CONF" | sed 's/^[^=]*=//g')
echo ">> RSYNC SECRETS: adding account: $ACCOUNT_NAME"
echo "$CONF_CONF_VALUE" >> /etc/rsyncd.secrets
unset $(echo "$I_CONF" | cut -d'=' -f1)
done
##
# rsyncd Global Config ENVs
##
for I_CONF in "$(env | grep '^RSYNC_GLOBAL_CONFIG_')"
do
CONF_CONF_VALUE=$(echo "$I_CONF" | sed 's/^[^=]*=//g')
echo "$CONF_CONF_VALUE" >> /etc/rsyncd.conf
done
echo "" >> /etc/rsyncd.conf
##
# rsyncd Volume Config ENVs
##
for I_CONF in "$(env | grep '^RSYNC_VOLUME_CONFIG_')"
do
CONF_CONF_VALUE=$(echo "$I_CONF" | sed 's/^[^=]*=//g')
echo "$CONF_CONF_VALUE" | sed 's/;/\n/g' >> /etc/rsyncd.conf
echo "" >> /etc/rsyncd.conf
done
touch "$INITALIZED"
else
echo ">> CONTAINER: already initialized - direct start of rsync"
fi
##
# CMD
##
echo ">> CMD: exec docker CMD"
echo "$@"
exec "$@"
<file_sep># rsync - (ghcr.io/servercontainers/) [x86 + arm]
rsync - freshly complied from official stable releases on `alpine`
# Source Code
Check the following link for a new version: https://www.samba.org/ftp/rsync/src/
## Build & Versions
You can specify `DOCKER_REGISTRY` environment variable (for example `my.registry.tld`)
and use the build script to build the main container and it's variants for _x86_64, arm64 and arm_
You'll find all images tagged like `a3.15.0-r3.2.7` which means `a<alpine version>-r<rsync version>`.
This way you can pin your installation/configuration to a certian version. or easily roll back if you experience any problems
(don't forget to open a issue in that case ;D).
To build a `latest` tag run `./build.sh release`
## Changelogs
* 2023-03-20
* complete upgrade
* rsync upgrade to `3.2.7`
* github action to build container
* implemented ghcr.io as new registry
* 2021-05-28
* fixed build by switched to `alpine`
* 2020-11-05
* multiarch build
* rsync version update to `3.2.3`
## Environment variables and defaults
### default /etc/rsyncd.conf
log file = /dev/stdout
use chroot = yes
list = yes
uid = nobody
gid = nogroup
transfer logging = no
timeout = 600
ignore errors = no
refuse options = checksum dry-run
dont compress = *.gz *.tgz *.zip *.z *.rpm *.deb *.iso *.bz2 *.tbz
### rsync
* __RSYNC\_SECRET\_mysecretname__
* adds a new secret to /etc/rsyncd.secrets
* multiple secrets possible by adding unique name to RSYNC_SECRET_
* examples
* "rsyncclient:passWord"
* "alice:PassWord"
to enable authentication add the following to your volume config (inside or outside the location tag):
auth users = alice;
* __RSYNC\_VOLUME\_CONFIG\_myconfigname__
* adds a new rsyncd volume configuration
* multiple variables/confgurations possible by adding unique configname to RSYNC_VOLUME_CONFIG_
* examples
* "[alice]; path = /shares/alice; comment = alices public files; read only = yes"
* "[timemachine]; path = /shares/timemachine; comment = timemachine files; ignore errors = yes"
* __RSYNC\_GLOBAL\_CONFIG\_optionname__
* adds a new rsyncd option to configuration file
* multiple options possible by adding unique optionname to RSYNC_GLOBAL_CONFIG_
* examples
* "max connections = 0"
* "read only = no"
# Usage
rsync servername::volume # lists files in volume
rsync alice@servername::volume # lists files in volume with user alice
# Links
* https://linux.die.net/man/5/rsyncd.conf
* http://www.jveweb.net/en/archives/2011/01/running-rsync-as-a-daemon.html
<file_sep>version: '3'
services:
rsync:
build: .
image: ghcr.io/servercontainers/rsync
restart: always
environment:
RSYNC_SECRET_alice: "alice:<PASSWORD>"
RSYNC_GLOBAL_CONFIG_maxcon: "max connections = 0"
RSYNC_VOLUME_CONFIG_alice: "[alice]; path = /shares/alice; auth users = alice; comment = alices public files; read only = yes"
RSYNC_VOLUME_CONFIG_bob: "[timemachine]; path = /shares/timemachine; comment = timemachine files;"
volumes:
- ./shares/alice:/shares/alice
- ./shares/timemachine:/shares/timemachine
ports:
- 873:873
networks:
- rsync
networks:
rsync:
driver: bridge
<file_sep>#!/bin/bash
export IMG=$(docker build -q --pull --no-cache -t 'get-version' .)
#export RSYNC_VERSION=$(cat Dockerfile | tr ' ' '\n' | grep "rsync_version=" | cut -d"=" -f2)
# auto update rsync
export RSYNC_VERSION=$(curl https://rsync.samba.org/ 2>/dev/null | grep h3 | grep Rsync | grep released | head -n1 | tr ' ' '\n' | grep '[0-9]\.[0-9]')
export FOOBAR=$(sed -i.bak 's/rsync_version=3.2.7/rsync_version='"$RSYNC_VERSION"'/g' Dockerfile; rm Dockerfile.bak)
export ALPINE_VERSION=$(docker run --rm -t get-version cat /etc/alpine-release | tail -n1 | tr -d '\r')
[ -z "$ALPINE_VERSION" ] && exit 1
export IMGTAG=$(echo "$1""a$ALPINE_VERSION-r$RSYNC_VERSION")
export IMAGE_EXISTS=$(docker pull "$IMGTAG" 2>/dev/null >/dev/null; echo $?)
# return latest, if container is already available :)
if [ "$IMAGE_EXISTS" -eq 0 ]; then
echo "$1""latest"
else
echo "$IMGTAG"
fi<file_sep>FROM alpine
ENV PATH="/container/scripts:${PATH}"
RUN export rsync_version=3.2.7 \
\
&& apk add --no-cache alpine-sdk \
bash \
openssl-dev \
lz4-dev \
zstd-dev \
xxhash-dev \
\
&& wget https://download.samba.org/pub/rsync/src/rsync-${rsync_version}.tar.gz \
&& tar xvf rsync-${rsync_version}.tar.gz \
&& rm rsync-${rsync_version}.tar.gz \
&& cd rsync-${rsync_version} \
\
&& ./configure --prefix=/ \
&& make \
&& make install \
\
&& cd - \
&& rm -rf rsync-${rsync_version} \
\
&& apk del alpine-sdk \
\
&& touch /etc/rsyncd.secrets \
&& chmod 600 /etc/rsyncd.secrets
VOLUME ["/shares"]
EXPOSE 873
COPY . /container/
RUN cp /container/config/rsyncd.conf /etc/rsyncd.conf
HEALTHCHECK CMD ["docker-healthcheck.sh"]
ENTRYPOINT ["entrypoint.sh"]
CMD [ "rsync", "--no-detach", "--daemon", "--config", "/etc/rsyncd.conf" ]
|
3287d58fe1eaa2e4e8937478c5c5d75bba780cf9
|
[
"Markdown",
"YAML",
"Dockerfile",
"Shell"
] | 5 |
Shell
|
ServerContainers/rsync
|
c315f927a8d63ee7907c08c851eb138b04e1f319
|
85c9a4aeef23b405487ad7d27a98605a5c058fa8
|
refs/heads/master
|
<file_sep>var gameBox = document.getElementById('box'), playerIndex = 1, players = ['O', 'X'], resultValues = [],
winningCombinations = [[0, 1, 2], [3, 4, 5], [6, 7, 8], [0, 3, 6], [1, 4, 7], [2, 5, 8], [0, 4, 8], [2, 4, 6]];
var numberOfX = 0;
var numberOfO = 0;
var n = 0;
function onClick(s) {
n++;
if (n % 2 == 1) {
s.style.backgroundColor = "cadetblue";
} else {
s.style.backgroundColor = "aquamarine";
}
s.disabled = "disabled";
s.value = players[playerIndex];
playerIndex == 1 ? playerIndex-- : playerIndex++;
resetIfWinnerFound();
}
function resetIfWinnerFound() {
var inputs = gameBox.getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
resultValues[i] = inputs[i].value;
}
for (let i = 0; i < players.length; i++) {
if (isWinning(players[i])) {
var end = 'The winner is ' + players[i] + '!' + " " + scores();
document.getElementById('final').innerText = (end);
reset();
} else {
var k = 0;
for (let j = 0; j < resultValues.length; j++) {
if (resultValues[j] == "") {
break;
} else {
k++;
}
}
if (k == 9) {
var noOne = "No one is winning!";
document.getElementById('final').innerText = (noOne);
reset();
break;
}
}
}
return;
}
function isWinning(value) {
var combination;
var j;
for (let i = 0; i < winningCombinations.length; i++) {
combination = winningCombinations[i];
for (j = 0; j < combination.length; j++) {
if (resultValues[combination[j]] != value) break;
}
if (j == 3) {
return true;
}
}
return false;
}
function reset() {
var inputs = gameBox.getElementsByTagName('input');
for (let i = 0; i < inputs.length; i++) {
inputs[i].disabled = '';
inputs[i].value = '';
inputs[i].style.backgroundColor = "tan";
}
numberOfO = 0;
numberOfX = 0;
playerIndex = 1;
n = 0;
resultValues = [];
}
function scores() {
for (let i = 0; i < resultValues.length; i++) {
if (resultValues[i] == "X") {
numberOfX++;
}
if (resultValues[i] == "O") {
numberOfO++;
}
}
var theScore = "Score: X-" + numberOfX + " O-" + numberOfO;
return theScore;
}
function newGame() {
document.getElementById('final').innerText = ("");
}
|
026b3729521089e14ae18e07875a05f5984363de
|
[
"JavaScript"
] | 1 |
JavaScript
|
zakoyangayane/TicTacToe
|
e260305992cbad6440bfbeeb4e2f7ec6967fc43f
|
90c9a69dd93d13e387eb50a83c4e525d7815ee0c
|
refs/heads/master
|
<repo_name>armandomj/FamilyGame<file_sep>/Assets/Scripts/EventsManager.cs
using UnityEngine;
using System.Collections;
public class EventsManager : MonoBehaviour {
public delegate void GameObjectDelegate(GameObject obj);
public static event GameObjectDelegate OnTouchEvent;
public static void RaiseOnTouchEvent(GameObject obj) {
if (OnTouchEvent != null) {
OnTouchEvent(obj);
}
}
public static event GameObjectDelegate PlantIsFreeEvent;
public static void RaisePlantIsFreeEvent(GameObject plant) {
if (PlantIsFreeEvent != null) {
PlantIsFreeEvent(plant);
}
}
//public static event GameObjectDelegate ImSelectedCellEvent;
//public static void RaiseImSelectedCell(GameObject obj) {
// if (ImSelectedCellEvent != null) {
// ImSelectedCellEvent(obj);
// }
//}
}
<file_sep>/Assets/Scripts/followFinger.cs
using UnityEngine;
using System.Collections;
public class followFinger : MonoBehaviour {
void Update () {
if (Input.touchCount > 0) {
// No queremos que reaccione al resto de pulsaciones
if (Input.GetTouch(0).fingerId == 0) {
if (Input.GetTouch(0).phase.Equals(TouchPhase.Stationary)) {
Vector3 pos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
// Se dibuja lo más cerca de la camára posible
transform.position = new Vector3(pos.x, pos.y, Camera.main.transform.position.z + Camera.main.nearClipPlane);
}
else if (Input.GetTouch(0).phase.Equals(TouchPhase.Ended)) {
EventsManager.RaisePlantIsFreeEvent(gameObject);
}
}
}
}
}
<file_sep>/Assets/Scripts/SelectGround.cs
using UnityEngine;
using System.Collections;
public class SelectGround : MonoBehaviour {
private bool m_ImSelected = false;
void OnEnable() {
EventsManager.OnTouchEvent += this.OnTouchEvent;
EventsManager.PlantIsFreeEvent += this.PlantIsFreeEvent;
}
void OnDisable() {
EventsManager.OnTouchEvent -= this.OnTouchEvent;
EventsManager.PlantIsFreeEvent -= this.PlantIsFreeEvent;
}
void OnTouchEvent(GameObject obj) {
if (obj == gameObject) {
m_ImSelected = true;
}
else {
m_ImSelected = false;
}
}
void PlantIsFreeEvent(GameObject plant) {
if (m_ImSelected) {
Destroy(plant);
}
}
}
<file_sep>/Assets/Scripts/InputManager.cs
using System.Collections;
using UnityEngine;
public class InputManager : MonoBehaviour {
private bool m_OnButton = false;
void Update () {
if (Input.touchCount > 0) {
// Intentamos que sea monotactil
if (Input.GetTouch(0).fingerId == 0) {//&& (Input.GetTouch(0).phase.Equals(TouchPhase.Began))){
// No ignora la interfaz
//if (!UnityEngine.EventSystems.EventSystem.current.IsPointerOverGameObject(Input.GetTouch(0).fingerId)) {
if (!m_OnButton) {
Vector2 pos = Camera.main.ScreenToWorldPoint(Input.GetTouch(0).position);
RaycastHit2D hit = Physics2D.Raycast(pos, Vector2.zero);
if (hit) {
EventsManager.RaiseOnTouchEvent(hit.transform.gameObject);
}
else {
EventsManager.RaiseOnTouchEvent(null);
}
}
else {
// Si el rayo colisiona con un elemento UI consideramos que no choca con nada
EventsManager.RaiseOnTouchEvent(null);
}
}
}
}
public void SetOnButton() {
m_OnButton = true;
}
public void ReleaseOnButton() {
m_OnButton = false;
}
}
<file_sep>/Assets/Scripts/selectCell.cs
using UnityEngine;
using System.Collections;
public class selectCell : MonoBehaviour {
private bool m_ImSelected = false;
private bool m_IHavePlant = false;
void OnEnable() {
EventsManager.OnTouchEvent += this.OnTouchEvent;
EventsManager.PlantIsFreeEvent += this.PlantIsFreeEvent;
}
void OnDisable() {
EventsManager.OnTouchEvent -= this.OnTouchEvent;
EventsManager.PlantIsFreeEvent -= this.PlantIsFreeEvent;
}
void OnTouchEvent(GameObject obj) {
if (obj == gameObject) {
m_ImSelected = true;
}
else {
m_ImSelected = false;
}
}
void PlantIsFreeEvent(GameObject plant) {
if (m_ImSelected && !m_IHavePlant) {
plant.transform.position = transform.position;
plant.GetComponent<followFinger>().enabled = false;
m_IHavePlant = true;
}
else if (m_ImSelected && m_IHavePlant) {
Destroy(plant);
}
}
}
|
81201f03c66e17093a9c3f091a9efaa7334337fc
|
[
"C#"
] | 5 |
C#
|
armandomj/FamilyGame
|
448988c700988f5ab356dacae47d1f76da15fcdc
|
d1dd855f235bc31e56adf1fbff9f1ec8712d4b85
|
refs/heads/master
|
<repo_name>blings0611/Finding-New-Location-of-Wheel-Chair-Charging-Station<file_sep>/2. CLUSTERING/BARRIER_FREE_FINAL.py
#!/usr/bin/env python
# coding: utf-8
# # Wheelchair Charging Stations for the Disabled in Seoul
# ## Import libraries
# In[2]:
# For data manipulation and analysis
import pandas as pd
from pandas import Series, DataFrame
# For scientific computing
import numpy as np
# For clustering algorithm (K-Means)
from sklearn.preprocessing import StandardScaler, RobustScaler, MinMaxScaler, MaxAbsScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
from scipy.spatial import distance
from scipy.spatial.distance import cdist, pdist
from sklearn.metrics import euclidean_distances
from sklearn.metrics import silhouette_score
# For visulization
import matplotlib.pyplot as plt
import matplotlib
from math import sqrt
from mpl_toolkits.mplot3d import Axes3D
# ## Load csv data
# In[3]:
import os
os.getcwd() # Get my working directory (current working directory)
# In[4]:
df=pd.read_csv('DATASET.csv', index_col='ID')
df.head()
# ## Data scaling (MinMaxScaler)
# In[5]:
# Scaler: StandardScaler, RobustScaler, MinMaxScaler, MaxAbsScaler
scaled = MinMaxScaler().fit_transform(df)
features = ['DISALBED', 'SHOPPING MALL', 'TAXI', 'EMPLOYEE','WELFARE CENTER','CARD']
pd.DataFrame(scaled, columns=features)
# ## Principal Component Analysis
# In[6]:
pca = PCA(n_components=3) # n=3, 0.835 (83.5%) (Explained variance ratio should be at least 0.8)
values_pca = pca.fit_transform(scaled)
principalDf = pd.DataFrame(data=values_pca, columns = ['PC-1', 'PC-2','PC-3'])
print('Explained variance ratio :', pca.explained_variance_ratio_)
# In[7]:
principalDf
# ## Elbow method
# In[9]:
# Using the elbow method to determine the optimal number of clusters for k-means clustering
def elbow_method(data):
K = range(2,6)
KM = [KMeans(n_clusters=k).fit(data) for k in K]
centroids = [k.cluster_centers_ for k in KM]
D_k = [cdist(data, cent, 'euclidean') for cent in centroids]
cIdx = [np.argmin(D,axis=1) for D in D_k]
dist = [np.min(D,axis=1) for D in D_k]
avgWithinSS = [sum(d)/data.shape[0] for d in dist]
# Total with-in sum of square
wcss = [sum(d**2) for d in dist]
tss = sum(pdist(data)**2)/data.shape[0]
bss = tss-wcss
# Elbow curve
fig = plt.figure()
ax = fig.add_subplot(111)
kIdx = 1
ax.plot(K, avgWithinSS, 'b*-')
ax.plot(K[kIdx], avgWithinSS[kIdx], marker='o', markersize=15,
markeredgewidth=2, markeredgecolor='r', markerfacecolor='None')
kIdx = 2
ax.plot(K, avgWithinSS, 'b*-')
ax.plot(K[kIdx], avgWithinSS[kIdx], marker='o', markersize=10,
markeredgewidth=2, markeredgecolor='b', markerfacecolor='None')
plt.grid(True)
plt.xlabel('Number of clusters')
plt.ylabel('Average within-cluster sum of squares')
plt.title('Elbow for K-Means clustering')
# In[10]:
elbow_method(values_pca) # Optimal K for K-Means = 3
# ## K-Means Clustering
# In[13]:
# K-Means Clustering
fig = plt.figure(1, figsize=(9, 7))
ax = Axes3D(fig, elev=-150, azim=230)
kmeans = KMeans(init='k-means++', n_clusters=3, n_init=5) # Opitmal K = 3
kmeans.fit(values_pca)
ax.scatter(values_pca[:, 0], values_pca[:, 1], values_pca[:, 2],
c=kmeans.labels_.astype(np.float), s=300
)
cntr = kmeans.cluster_centers_
ax.scatter(cntr[0][0],cntr[0][2],cntr[0][1],c = 'red',marker="x",s=1000)
ax.scatter(cntr[1][0],cntr[1][2],cntr[1][1],c = 'red',marker="x",s=1000)
ax.scatter(cntr[2][0],cntr[2][2],cntr[2][1],c = 'red',marker="x",s=1000)
# For visualization
ax.set_title('K-Means clustering (PCA-reduced data)\n'
'Centroids are marked with red cross')
ax.set_xlabel("Principal Component 1")
ax.w_xaxis.set_ticklabels([])
ax.set_ylabel("Principal Component 2")
ax.w_yaxis.set_ticklabels([])
ax.set_zlabel("Principal Component 3")
ax.w_zaxis.set_ticklabels([])
# In[14]:
#Labeling
df['CLUSTERING RESULT']=kmeans.labels_
# In[15]:
df.head()
# In[16]:
df.to_excel('BARRIER_FREE.xlsx')
|
f9e1175798bdba00d8015c5a54bf16b63ebf73e2
|
[
"Python"
] | 1 |
Python
|
blings0611/Finding-New-Location-of-Wheel-Chair-Charging-Station
|
5a5b3fee7c4c3769f0f848b6ca2a9a516087047d
|
9d9d9562e72673eb7ece962f464ca816a25f3c6b
|
refs/heads/master
|
<file_sep>package cast
import (
"testing"
)
func TestOutputs(t *testing.T) {
// where our values come from
producer := make(chan []byte)
// output channels
outputs := make([]chan []byte, 0)
for i := 0; i < 5; i++ {
outputs = append(outputs, make(chan []byte, 1))
}
// init relay, add channels
relay := New(producer)
for _, ch := range outputs {
relay.Add(ch)
}
relay.Start()
// value added to producer
producer <- []byte("Hello World")
for i, ch := range outputs {
val := <-ch
if string(val) != "Hello World" {
t.Errorf("Channel %d not recieving value", i)
}
}
}
func TestAdding(t *testing.T) {
// adding before or after calling Start should not change behavior
producer := make(chan []byte)
output1 := make(chan []byte, 1)
output2 := make(chan []byte, 1)
relay := New(producer)
relay.Add(output1)
relay.Start()
relay.Add(output2)
producer <- []byte("Testing")
val1 := <-output1
if string(val1) != "Testing" {
t.Error("Output channel added before start not recieving value")
}
val2 := <-output2
if string(val2) != "Testing" {
t.Error("Output channel after Start not recieving value")
}
}
<file_sep># Cast
An interface to satisfy a one to many message passing pattern (fan out). This problem arose when I wanted mulitple one-to-many messaging patterns in a backend server. Cast allows for an input channel to fan-out to multiple output channels with each output channel recieving the same value. For example, this can be used as a dispatcher to relay messages from a process in a server to multiple clients.
## Example usage
```golang
package main
import "github.com/andresoro/cast"
func main() {
// where our values come from
producer := make(chan []byte)
// output channels
outputs := make([]chan []byte, 0)
for i := 0; i < 5; i++ {
outputs = append(outputs, make(chan []byte, 1))
}
// init relay, add channels
relay := cast.New(producer)
for _, ch := range outputs {
relay.Add(ch)
}
// start relay, now listening to producer channel
relay.Start()
// value added to producer will be sent to every output channel
producer <- []byte("Hello World")
}
```
### Disclaimer
Wrote this up quickly in an effort to avoid writing something like this multiple times for my webserver. Better tests and more features will probably be added later.
<file_sep>package cast
import "sync"
// Relay implements an interface for a fan out pattern
// the goal is to have one input source pass data to multiple output recievers
// with each reciever getting the same data
type Relay interface {
Start()
Close()
Add(chan []byte)
}
type cast struct {
input <-chan []byte
outputs []chan<- []byte
end chan struct{}
add chan chan []byte
running bool
mu sync.Mutex
}
// New returns a broacast interface from an input channel
func New(input <-chan []byte) Relay {
return &cast{
input: input,
outputs: make([]chan<- []byte, 0),
end: make(chan struct{}),
add: make(chan chan []byte),
}
}
func (c *cast) Start() {
c.running = true
go func() {
for {
select {
// handle incoming data
case data := <-c.input:
for _, ch := range c.outputs {
ch <- data
}
case ch := <-c.add:
c.outputs = append(c.outputs, ch)
// handle end signal
case <-c.end:
for _, ch := range c.outputs {
close(ch)
}
c.running = false
return
}
}
}()
}
func (c *cast) Add(ch chan []byte) {
if c.running {
c.add <- ch
} else {
c.outputs = append(c.outputs, ch)
}
}
func (c *cast) Close() {
c.end <- struct{}{}
}
|
54efde6df86b7c38c97cf81606721b92d6d1d9cf
|
[
"Markdown",
"Go"
] | 3 |
Go
|
ProfessorMc/cast
|
79863a0070ee029af410b2d9c88811b348f57554
|
a66608673239ab3f0671a9c8a821a2ab4b71a6c0
|
refs/heads/master
|
<repo_name>koolventure/Test-Repo<file_sep>/beta.py
import math
option1 = ('Option 1. Inside Angle Calculator')
option2 = ('Option 2. Midpoint Calculator')
option3 = ('Option 3. Distance Calculator')
print (option1)
print(option2)
print(option3)
insert_option = int(input( 'Please input an option number. '))
if insert_option == 1:
pass
y = input ("Please insert a value.")
z = float(y)
x = float(3)
a = int(x)
while x <= z:
(n) = float (180 - 360/x)
print(a,".", n)
x = x + 1
a = int(x)
elif insert_option == 2:
pass
xx = input("Please insert X 2 value.")
xx = int(xx)
x = input("Please insert X 1 value.")
x = int(x)
firstPoint = ((xx+x)/2)
n = (firstPoint)
print ("Your first point is...", n)
yy = input("Please insert Y 2 value.")
yy = int(yy)
y = input("Please insert Y 1 value.")
y = int(y)
secondPoint = ((yy+y)/2)
nn = (secondPoint)
print ("Your second point is...", nn)
print("The midpoint of your line is...")
print ("(",nn,",",n,")")
elif insert_option == 3:
pass
xx = input("Please insert X 2 value.")
xx = int(xx)
x = input("Please insert X 1 value.")
x = int(x)
yy = input("Please insert Y 2 value.")
yy = int(yy)
y = input("Please insert Y 1 value.")
y = int(y)
(n) = math.sqrt((xx-x)**2 + (yy-y)**2)
print(n)
else:
pass
print ('There is no option for the number you have typed')
<file_sep>/funmath.py
import math
tau = (2*math.pi)
def chudnovsky(n):
pi = Decimal(0)
k = 0
while k < n:
pi += (Decimal(-1)**k)*(Decimal(factorial(6*k))/((factorial(k)**3)*(factorial(3*k)))* (13591409+545140134*k)/(640320**(3*k)))
k += 1
pi = pi * Decimal(10005).sqrt()/4270934400
pi = pi**(-1)
return pi
print (tau)<file_sep>/trig.py
import math
import cmath
x = math.radians(32)
step = math.cos(x)
print (step)
<file_sep>/temp.py
x = input('Farenheit, Celsius, or Kelvin?')
farenheit= 'farenheit'
celsius = 'celsius'
kelvin='kelvin' or 'k'
if x.lower()==farenheit:
ftemp=float(input('Please insert your temperature in degrees Celsius. '))
c=(9/5*ftemp) + 32
print (c)
elif x.lower()== celsius:
ctemp=float(input('Please insert your temperature in degrees Farenheit. '))
f=5/9*(ctemp - 32)
print(f)
elif x.lower()==kelvin:
answer = input('Would you like to convert Farenheit to Kelvin or Celsius to Kelvin')
answer1='farenheit' or 'f'
answer2='celsius'
if answer.lower()==answer1:
ktemp =float(input('Please insert your temperature in degrees Farenheit. '))
ct = 5/9*(ktemp-32)
final = ct+273.15
print(final)
<file_sep>/inside angle Calc.py
import math
y = input ("Please insert a value.")
z = float(y)
x = float(3)
a = int(x)
while x <= z:
(n) = float (180 - 360/x)
print(a,".", n)
x = x + 1
a = int(x)
<file_sep>/tempcalc.py
x = input('Farenheit or Celsius?')
if x==Farenheit or x==farenheit:
ftemp=float(input('Please insert your temperature.'))
c=x*2+30
print (c)
else:
print ('No conversion yet.')
<file_sep>/world_pop_calc.py
import math
pop_0 = int(input('Please insert the current population.'))
print()
year2 = int(input('Insert your desired year past the current year.'))
e = math.e
year = year2 - 2013
final_population = (pop_0 * e)
final_pop = (year * 0.0114)
final = final_population ** final_pop
print (final)
|
deeccccdf7da4e74c05116502a86d177fa0e3677
|
[
"Python"
] | 7 |
Python
|
koolventure/Test-Repo
|
a60a8590c8c977198812e3408ce7e3c4d3c6a426
|
a15d3b0915c5e41f4b2457b53efa53a4f2990b90
|
refs/heads/main
|
<repo_name>igorpoguliai/todo-list<file_sep>/js/script.js
const input = document.getElementById('input-value');
const list = document.getElementById('list');
const form = document.getElementById('form');
const buttonDelete = document.getElementById('button-delete');
const buttonMakeDone = document.getElementById('button-make-done');
const buttonSortDate = document.getElementById('button-sort-date');
const buttonSortAlphabet = document.getElementById('button-sort-alphabet');
let notes = [];
appInit();
form.addEventListener('submit', event => {
event.preventDefault();
const newNote = {
note: input.value,
checked: false,
id: Math.random(),
addetDate: new Date().toLocaleString().slice(0, -3),
}
input.value = '';
notes.push(newNote);
drawNotes();
})
function drawNotes() {
let message = '';
notes.forEach((item) => {
message += `
<li class="list__item ${item.checked ? 'list__item--checked' : ''}" onclick='toggleIsChecked(${item.id})'>
<div class="list__item-checkbox">
<svg width="9" height="8" viewBox="0 0 9 8" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M2.71866 5.71866L1.75 4.75C1.61193 4.61193 1.38807 4.61193 1.25 4.75C1.11193 4.88807 1.11193 5.11193 1.25 5.25L2.72569 6.72569C3.1415 7.1415 3.82457 7.11051 4.20102 6.65877L8.29517 1.7458C8.41118 1.60659 8.40189 1.40189 8.27376 1.27376C8.12718 1.12718 7.8861 1.13921 7.75484 1.29964L4.19972 5.64479C3.82508 6.10268 3.137 6.137 2.71866 5.71866Z" stroke="white"/>
</svg>
</div>
<div class="list__item-text">
${item.note}
</div>
<div class="list__item-date">
${item.addetDate}
</div>
<button class="list__item-remove" onclick='clickedItemRemove(${item.id})'>
<svg viewBox="0 0 14 14" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M7.77343 7.00003L13.8398 0.933604C14.0534 0.720022 14.0534 0.373741 13.8398 0.160186C13.6262 -0.0533682 13.28 -0.0533955 13.0664 0.160186L6.99999 6.22661L0.933602 0.160186C0.72002 -0.0533955 0.37374 -0.0533955 0.160186 0.160186C-0.053368 0.373768 -0.0533953 0.720049 0.160186 0.933604L6.22657 7L0.160186 13.0664C-0.0533953 13.28 -0.0533953 13.6263 0.160186 13.8398C0.266963 13.9466 0.406935 14 0.546908 14C0.68688 14 0.826825 13.9466 0.933629 13.8398L6.99999 7.77345L13.0664 13.8398C13.1731 13.9466 13.3131 14 13.4531 14C13.5931 14 13.733 13.9466 13.8398 13.8398C14.0534 13.6263 14.0534 13.28 13.8398 13.0664L7.77343 7.00003Z" fill="#4F4F4F"/>
</svg>
</button>
</li>
`;
})
list.innerHTML = message;
localStorage.setItem('todo-list', JSON.stringify(notes));
}
function appInit() {
if (localStorage.getItem('todo-list')) {
notes = JSON.parse(localStorage.getItem('todo-list'));
drawNotes();
}
}
function toggleIsChecked(clickedItemId) {
notes = notes.map(item => {
const {checked, id,} = item;
if (id === clickedItemId) {
return {...item, checked: !checked,}
} else {
return item;
}
})
drawNotes();
}
function clickedItemRemove(itemRemoveId) {
notes = notes.filter(item => item.id !== itemRemoveId);
drawNotes();
}
buttonDelete.addEventListener('click', function() {
notes = notes.filter(item => !item.checked);
drawNotes();
})
buttonMakeDone.addEventListener('click', function() {
const isEveryChecked = notes.every(item => item.checked === true);
notes = notes.map(item => {
return {...item, checked: isEveryChecked ? false : true};
})
drawNotes();
})
buttonSortDate.addEventListener('click', function() {
notes = notes.sort((a, b) => new Date(b.addetDate) - new Date(a.addetDate));
drawNotes();
})
buttonSortAlphabet.addEventListener('click', function() {
notes = notes.sort((a, b) => a.note.localeCompare(b.note));
drawNotes();
})
|
812c09af148d9d802f2afe08ad8e938f3c9741fc
|
[
"JavaScript"
] | 1 |
JavaScript
|
igorpoguliai/todo-list
|
dc8b93fcdf477043c10c2fc790a0da9b415cfaa1
|
7aa3a06bd738101fc208d1dcb502de905e89028d
|
refs/heads/master
|
<repo_name>Jeckman03/AdventureGameC-<file_sep>/main.cs
using System;
namespace Adventure
{
class MainClass {
public static void Main (string[] args) {
GameTitle();
string characterName = NameCharacter();
Console.ReadLine();
}
private static void GameTitle()
{
Console.WriteLine("-------------------------");
Console.WriteLine("\tAdventure Game!");
Console.WriteLine("-------------------------");
Console.WriteLine();
Console.WriteLine("Shall we go on an adventure!");
Console.WriteLine();
}
private static string NameCharacter()
{
string output;
Console.Write("What is your name aventure: ");
output = Console.ReadLine();
Console.WriteLine();
Console.WriteLine($"I wish you the best of luck during your journey { output }");
return output;
}
private static void Dialog(string message)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(message);
Console.ResetColor();
}
private static void Choice()
{
string input = "";
Console.Write("Which will you choose? A or B: ");
input = Console.ReadLine();
}
}
}
|
fffe93923c71325a03077ddacee22df76aa8a314
|
[
"C#"
] | 1 |
C#
|
Jeckman03/AdventureGameC-
|
4dff30135805bca594730a3a9327ea0d1306787b
|
6a260124f6d8f6c91571f32b3272711e7977fd65
|
refs/heads/master
|
<repo_name>HelenMoskovskaya/572193-mishka<file_sep>/source/js/script.js
var nav = document.querySelector (".navigation");
var navToggle = document.querySelector (".navigation__toggle");
nav.classList.remove ("navigation--nojs");
navToggle.addEventListener ("click", function()
{
if (nav.classList.contains ("navigation--closed")) {
nav.classList.remove ("navigation--closed");
nav.classList.add ("navigation--opened");
} else {
nav.classList.add ("navigation--closed");
nav.classList.remove ("navigation--opened");
}
});
|
8a641fcda6d2b8cdb9e4c69f3114c3a9b0cff0c2
|
[
"JavaScript"
] | 1 |
JavaScript
|
HelenMoskovskaya/572193-mishka
|
1713db266f53f567c069d0f8389a9802814098ec
|
d2e7677b077632861321fd6b10c12f560515d21d
|
refs/heads/master
|
<repo_name>DxrosAnys/backend-server<file_sep>/app.js
// Requires
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const cors = require('cors');
var rawBodyHandler = function (req, res, buf, encoding) {
if (buf && buf.length) {
req.rawBody = buf.toString(encoding || 'utf8');
console.log('Raw body: ' + req.rawBody);
}
}
//Inicializando variables
var app= express();
//CORS
app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "POST, GET, PUT, DELETE, OPTIONS");
next();
});
// app.use(cors({origin:"http://localhost:4200"}));
//app.options('*', cors());
//BodyParser
// parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
//app.use(bodyParser.json());
//app.use(cors());
//Importar rutas
var appRoutes = require('./routes/app');
var loginRoutes = require('./routes/login');
var appUsuario = require('./routes/usuario');
var appHospital = require('./routes/hospital');
var appMedico = require('./routes/medicos');
var busquedaRoutes = require('./routes/busquedas');
var uploadRoutes = require('./routes/upload');
var imagenesRoutes = require('./routes/imagenes');
//Conexion a la base de datos
mongoose.connection.openUri('mongodb://localhost:27017/hospitalDB', { useNewUrlParser: true },
(err, res)=> {
if(err) throw err;
console.log('Conexión correcta a la base de datos: \x1b[32m%s\x1b[0m', 'OK');
});
//Server index config
//var serveIndex = require('serve-index');
//app.use(express.static(__dirname + '/'))
//app.use('/upload', serveIndex(__dirname + '/upload'));
//Rutas
app.use( '/hospital',appHospital);
app.use('/medico', appMedico);
app.use('/usuario',appUsuario);
app.use('/login',loginRoutes);
app.use('/busqueda', busquedaRoutes);
//app.use('/coleccion', busquedaRoutes);
app.use('/upload', uploadRoutes);
app.use('/img', imagenesRoutes);
app.use('/',appRoutes);
//Escuchar peticiones
app.listen(3000, () =>{
console.log('Express server puerto 3000: \x1b[32m%s\x1b[0m', 'online');
});
<file_sep>/routes/medicos.js
// Requires
var express = require('express');
var bcrypt = require('bcryptjs');
var mdAutenticacion = require('../middleware/autenticacion');
const app = express();
const Medico = require('../models/medicos');
//=========================================
// Obtener todos los medicos
//=========================================
app.get('/', (req, res, next) => {
var desde = req.query.desde || 0;
desde = Number(desde);
Medico.find({}, 'nombre img usuario hospital')
.populate('usuario', 'nombre email')
.populate('hospital')
.skip(desde)
.limit(5)
.exec((err, medicos) => {
if (err) {
res.status(500).json({
ok: true,
mensaje: 'Error cargando medicos',
errors: err
});
}
Medico.count({}, (err, count) => {
res.status(200).json({
ok: true,
mensaje: 'Se obtuvo medicos',
medicos: medicos,
total: count
});
});
});
});
//=========================================
// Obtener un medico
// =========================================
app.get('/:id', (req,res) =>{
var id = req.params.id;
Medico.findById(id)
.populate('usuario', 'nombre email img')
.populate('hospital')
.exec((err, medico) =>{
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar medico',
errors: err
});
}
if (!medico) {
return res.status(400).json({
ok: false,
mensaje: 'El usuario con el id ' + id + 'no existe',
errors: {message: 'No existe un hospital con ese ID'}
});
}
return res.status(200).json({
ok: true,
medico: medico
});
})
});
//=========================================
// Actualizar un medico
// =========================================
app.put('/:id', mdAutenticacion.verificaToken, (req, res) => {
const id = req.params.id;
const body = req.body;
Medico.findById(id, (err, medico) => {
if (err) {
return res.status(500).json({
ok: false,
mensaje: 'Error al buscar medico',
errors: err
});
}
if (!medico) {
return res.status(400).json({
ok: false,
mensaje: 'El usuario con el id ' + id + 'no existe',
errors: {message: 'No existe un hospital con ese ID'}
});
}
console.log(body);
medico.nombre = body.nombre;
medico.email = body.email;
medico.img = body.img;
medico.usuario = body.usuario;
medico.hospital = body.hospital;
medico.save((err, medicoGuardado) => {
if (err) {
return res.status(400).json({
ok: false,
mensaje: 'Error al actualizar el medico',
errors: err
});
}
res.status(200).json({
ok: true,
medico: medicoGuardado
});
});
});
});
//=========================================
// Crear nuevo registro de medico
//=========================================
var debug = require('debug');
app.post('/', mdAutenticacion.verificaToken, (req, res) => {
var body = req.body;
var medico = new Medico({
nombre: body.nombre,
img: body.img,
usuario: req.usuario._id,
hospital: body.hospital
});
console.log(req);
medico.save((err, medicoGuardado) => {
if (err) {
res.status(400).json({
ok: true,
mensaje: 'Error al crear medico',
errors: err
});
}
res.status(201).json({
ok: true,
medico: medicoGuardado
});
});
});
//=========================================
// Eliminar un medico
//=========================================
app.delete('/:id', mdAutenticacion.verificaToken, (req, res) => {
var id = req.params.id;
Medico.findByIdAndDelete(id, (err, medicoBorrado) => {
if (err) {
res.status(500).json({
ok: true,
mensaje: 'Error al borrar medico',
errors: err
});
}
if (!medicoBorrado) {
res.status(400).json({
ok: true,
mensaje: 'Error al borrar medico',
errors: {message: 'No existe ningun medico con ese ID'}
});
}
res.status(200).json({
ok: true,
medico: medicoBorrado
});
});
});
module.exports = app;
<file_sep>/routes/upload.js
// Requires
var express = require('express');
const fileUpload = require('express-fileupload');
var fs = require('fs');
var app = express();
// default options
app.use(fileUpload());
var Usuario = require('../models/usuario');
var Medicos = require('../models/medicos');
var Hospital = require('../models/hospital');
// Rutas
app.put('/:tipo/:id', function(req, res) {
var tipo = req.params.tipo;
var id = req.params.id;
//tipos de colección
var tiposValidos = ['hospitales','medicos','usuarios'];
if(tiposValidos.indexOf(tipo) < 0){
return res.status(400).json({
ok: false,
mensaje: 'Tipo de colección no es válida',
errors: { message: 'Tipo de colección no es válida'}
});
}
if(!req.files){
return res.status(400).json({
ok: false,
mensaje: 'No selecciono nada',
errors: { message: 'Debe de seleccionar una imagen'}
});
}
//Obtener nombre del archivo
var archivo = req.files.imagen;
var nombreCortado = archivo.name.split('.');
var extensionArchivo = nombreCortado[nombreCortado.length-1];
//Extensiones de archivos permitidas
const extensionesValidas = ['png','jpg','gif','jpeg'];
if(extensionesValidas.indexOf(extensionArchivo) < 0){
return res.status(400).json({
ok: false,
mensaje: 'Extension no valida',
errors: { message: 'Las extensiones validas son: '+ extensionesValidas.join(', ')}
});
}
//Nombre de archivo personalizado
var nombreArchivo = `${id}-${new Date().getMilliseconds()}.${extensionArchivo}`;
var path = `./upload/${tipo}/${nombreArchivo}`;
archivo.mv(path, err =>{
if(err){
return res.status(500).json({
ok: false,
mensaje: 'Extension al mover archivo',
errors: err
});
}
subirPorTipo(tipo, id, nombreArchivo, res);
/*res.status(200).json({
ok: true,
mensaje: 'Archivo movido',
nombreCortado:nombreCortado
});*/
});
});
function subirPorTipo(tipo, id, nombreArchivo, res){
if(tipo === 'usuarios'){
Usuario.findById(id, (err,usuario)=>{
if(!usuario){
return res.status(400).json({
ok: false,
mensaje: 'Usuario no existe',
errors: { message: 'Usuario no existente'}
});
}
var pathViejo = '../upload/usuarios/'+ usuario.img;
//Si existe, elimina la imagen anterior
if(fs.existsSync(pathViejo)){
fs.unlink(pathViejo);
}
usuario.img = nombreArchivo;
usuario.save( (err, UsuarioActualizado) =>{
return res.status(200).json({
ok: true,
mensaje: 'Imagen de usuario actualizada',
usuario: UsuarioActualizado
});
});
});
}
if(tipo === 'medicos'){
Medicos.findById(id, (err,medico)=>{
if(!medico){
return res.status(400).json({
ok: false,
mensaje: 'Medico no existe',
errors: { message: 'Medico no existente'}
});
}
var pathViejo = '../upload/medicos/'+ medico.img;
//Si existe, elimina la imagen anterior
if(fs.existsSync(pathViejo)){
fs.unlink(pathViejo);
}
medico.img = nombreArchivo;
medico.save( (err, MedicoActualizado) =>{
return res.status(200).json({
ok: true,
mensaje: 'Imagen de medico actualizada',
medico: MedicoActualizado
});
});
});
}
if(tipo === 'hospitales'){
Hospital.findById(id, (err,hospital)=>{
if(!hospital){
return res.status(400).json({
ok: false,
mensaje: 'Hospital no existe',
errors: { message: 'Hospital no existente'}
});
}
var pathViejo = '../upload/hospitales/'+ hospital.img;
//Si existe, elimina la imagen anterior
if(fs.existsSync(pathViejo)){
fs.unlink(pathViejo);
}
hospital.img = nombreArchivo;
hospital.save( (err, HospitalActualizado) =>{
return res.status(200).json({
ok: true,
mensaje: 'Imagen de hospital actualizada',
hospital: HospitalActualizado
});
});
});
}
}
module.exports= app;
<file_sep>/routes/busquedas.js
// Requires
var express = require('express');
var app = express();
var Hospital = require('../models/hospital');
var Medico = require('../models/medicos');
var Usuario = require('../models/usuario');
//=============================
// Busqueda por colección
//=============================
app.get('/coleccion/:tabla/:busqueda', (req, res )=>{
const tabla = req.params.tabla;
const busqueda = req.params.busqueda;
const regex = new RegExp(busqueda, 'i');
var promesa;
switch (tabla){
case 'Usuario':
promesa = buscarUsuarios(busqueda, regex);
break;
case 'Hospital':
promesa = buscarHospitales(busqueda, regex);
break;
case 'Medico':
promesa = buscarMedicos(busqueda, regex);
break;
default:
return res.status(400).json({
ok: false,
mensaje: 'Los tipos de busqueda son usuarios, hospitales y medicos',
error: {message:'Tipo de tabla/coleccion no valida'}
});
}
promesa.then( data => {
res.status(200).json({
ok: true,
[tabla]: data
});
});
});
//=============================
// Busqueda general
//=============================
// Rutas
app.get('/todo/:busqueda', (req, res, next) => {
var busqueda=req.params.busqueda;
var regex = new RegExp(busqueda, 'i');
Promise.all([
buscarHospitales(busqueda,regex),
buscarMedicos(busqueda, regex),
buscarUsuarios(busqueda, regex)
]).then(respuesta =>{
res.status(200).json({
ok: true,
hospitales: respuesta[0],
medicos: respuesta[1],
usuarios: respuesta[2]
});
});
});
function buscarHospitales(busqueda, regex){
return new Promise((resolve, reject) =>{
Hospital.find({nombre : regex})
.populate('usuario', 'nombre email img')
.exec((err,hospitales)=>{
if(err){
reject('Error al cargar hospitales',err);
} else {
resolve(hospitales);
}
});
});
}
function buscarUsuarios(busqueda, regex){
return new Promise((resolve, reject) =>{
Usuario.find({}, 'nombre email rol img')
.or([{'nombre': regex}, {'email': regex}])
.exec((err,usuario) =>{
if(err){
reject('Error al cargar usuarios', err);
} else{
resolve(usuario);
}
});
});
}
function buscarMedicos(busqueda, regex){
return new Promise((resolve, reject) =>{
Medico.find({nombre : regex})
.populate( 'usuario', 'nombre email img')
.populate('hospital')
.exec((err,medicos)=>{
if(err){
reject('Error al cargar hospitales',err);
} else {
resolve(medicos);
}
});
});
}
module.exports= app;
<file_sep>/config/config.js
module.exports.SEED = '@este-es@-un-seed';
//Google
module.exports.GOOGLE_CLIENT_ID='588911111713-abg4dp5hvs2tbf0kb2i5tabthvrtavdt.apps.googleusercontent.com';
module.exports.GOOGLE_SECRET = '<KEY>';
|
d1ac99da59eba5d11f76112fb258de817c6cc098
|
[
"JavaScript"
] | 5 |
JavaScript
|
DxrosAnys/backend-server
|
a2e1619020b7ba5340add4382c247c13552bb080
|
f375f5cbfdad46e559adeb877f392f26d44e65db
|
refs/heads/master
|
<file_sep><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<!-- NewPage -->
<html lang="en">
<head>
<!-- Generated by javadoc (1.8.0_45) on Sun Aug 16 17:47:03 EDT 2015 -->
<title>Index</title>
<meta name="date" content="2015-08-16">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">
<script type="text/javascript" src="script.js"></script>
</head>
<body>
<script type="text/javascript"><!--
try {
if (location.href.indexOf('is-external=true') == -1) {
parent.document.title="Index";
}
}
catch(err) {
}
//-->
</script>
<noscript>
<div>JavaScript is disabled on your browser.</div>
</noscript>
<!-- ========= START OF TOP NAVBAR ======= -->
<div class="topNav"><a name="navbar.top">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.top" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.top.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?index-all.html" target="_top">Frames</a></li>
<li><a href="index-all.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_top">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_top");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.top">
<!-- -->
</a></div>
<!-- ========= END OF TOP NAVBAR ========= -->
<div class="contentContainer"><a href="#I:A">A</a> <a href="#I:C">C</a> <a href="#I:D">D</a> <a href="#I:E">E</a> <a href="#I:G">G</a> <a href="#I:I">I</a> <a href="#I:M">M</a> <a href="#I:R">R</a> <a href="#I:S">S</a> <a href="#I:T">T</a> <a name="I:A">
<!-- -->
</a>
<h2 class="title">A</h2>
<dl>
<dt><a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">AutomatedDisplay</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class implements the IDisplay interface for testing with Main and Core.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#AutomatedDisplay-int-int-">AutomatedDisplay(int, int)</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><a href="edu/oakland/classProject/test/AutomatedTest.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">AutomatedTest</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class tests the robustness of the entire program by simulating how a user would play the game.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedTest.html#AutomatedTest--">AutomatedTest()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedTest.html" title="class in edu.oakland.classProject.test">AutomatedTest</a></dt>
<dd> </dd>
</dl>
<a name="I:C">
<!-- -->
</a>
<h2 class="title">C</h2>
<dl>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#computeGuess--">computeGuess()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">Uses the value set by setGuessFeedbackSelection to calcuate
the value of the system's next guess</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#computeGuess--">computeGuess()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">Has core compute the next guess based on class variables</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#computeGuess--">computeGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production"><span class="typeNameLink">Core</span></a> - Class in <a href="edu/oakland/classProject/production/package-summary.html">edu.oakland.classProject.production</a></dt>
<dd>
<div class="block">This class holds all of the core functionality of TheGuessingGame backend.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#Core--">Core()</a></span> - Constructor for class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#Core-boolean-int-int-int-int-int-int-java.lang.String-">Core(boolean, int, int, int, int, int, int, String)</a></span> - Constructor for class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd> </dd>
<dt><a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">CoreTest</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class holds all of the JUnit test cases for testing the Core class.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#CoreTest--">CoreTest()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd> </dd>
</dl>
<a name="I:D">
<!-- -->
</a>
<h2 class="title">D</h2>
<dl>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/IDisplay.html#displayGuessInfo-int-int-">displayGuessInfo(int, int)</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production">IDisplay</a></dt>
<dd>
<div class="block">Displays the current guess and the current guess iteration</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#displayGuessInfo-int-int-">displayGuessInfo(int, int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#displayGuessInfo-int-int-">displayGuessInfo(int, int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">DisplayHelperTest</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class holds all of the JUnit test cases for testing the DisplayHelper class.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/DisplayHelperTest.html#DisplayHelperTest--">DisplayHelperTest()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test">DisplayHelperTest</a></dt>
<dd> </dd>
</dl>
<a name="I:E">
<!-- -->
</a>
<h2 class="title">E</h2>
<dl>
<dt><a href="edu/oakland/classProject/production/package-summary.html">edu.oakland.classProject.production</a> - package edu.oakland.classProject.production</dt>
<dd> </dd>
<dt><a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a> - package edu.oakland.classProject.test</dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Main.html#endGame--">endGame()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production">Main</a></dt>
<dd>
<div class="block">Calls display to show the game end screen</div>
</dd>
<dt><a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">EndToEndTest</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class tests functionality of Main working with a real instance of Core and a mock Display.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#EndToEndTest--">EndToEndTest()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd> </dd>
</dl>
<a name="I:G">
<!-- -->
</a>
<h2 class="title">G</h2>
<dl>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getCurrentGuess--">getCurrentGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getCurrentGuessIteration--">getCurrentGuessIteration()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/IDisplay.html#getEndGameConfirmation-int-int-">getEndGameConfirmation(int, int)</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production">IDisplay</a></dt>
<dd>
<div class="block">Displays the end game UI</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#getEndGameConfirmation-int-int-">getEndGameConfirmation(int, int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getEndGameConfirmation-int-int-">getEndGameConfirmation(int, int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#getEndGuess--">getEndGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getEndGuess--">getEndGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getEndGuessIteration--">getEndGuessIteration()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#getGuess--">getGuess()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">Returns the numberGuessed value</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#getGuess--">getGuess()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">A getter for the current guess</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getGuess--">getGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/IDisplay.html#getGuessFeedback--">getGuessFeedback()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production">IDisplay</a></dt>
<dd>
<div class="block">A getter for the current user feedback (higher or lower)</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#getGuessFeedback--">getGuessFeedback()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getGuessFeedback--">getGuessFeedback()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getGuessFeedbackSelection--">getGuessFeedbackSelection()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#getGuessIteration--">getGuessIteration()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">Returns value stored in the guess counter.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#getGuessIteration--">getGuessIteration()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">A getter for the current guess iteration</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getGuessIteration--">getGuessIteration()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#getHasGameEnded--">getHasGameEnded()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">This boolean method tests to see if the game actually ended and returns the result.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#getHasGameEnded--">getHasGameEnded()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">A getter for the end status of the current game session</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getHasGameEnded--">getHasGameEnded()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#getMaxNumOfGuesses--">getMaxNumOfGuesses()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">Returns the maximum number of guesses the System is
allowed to make.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#getMaxNumOfGuesses--">getMaxNumOfGuesses()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">A getter for the max number of guesses</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getMaxNumOfGuesses--">getMaxNumOfGuesses()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getMaxNumOfGuesses--">getMaxNumOfGuesses()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/IDisplay.html#getPlaySelection--">getPlaySelection()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production">IDisplay</a></dt>
<dd>
<div class="block">Getter for the simple or advanced game session options</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#getPlaySelection--">getPlaySelection()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getPlaySelection--">getPlaySelection()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#getUpperBoundComputed--">getUpperBoundComputed()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">This method calls for the requested Upper Bound and returns the computed uppper bound.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#getUpperBoundComputed--">getUpperBoundComputed()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">A getter for the upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getUpperBoundComputed--">getUpperBoundComputed()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getUpperBoundComputed--">getUpperBoundComputed()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#getUpperBoundInput--">getUpperBoundInput()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/IDisplay.html#getUpperBoundSelection--">getUpperBoundSelection()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production">IDisplay</a></dt>
<dd>
<div class="block">Getter for the upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#getUpperBoundSelection--">getUpperBoundSelection()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getUpperBoundSelection--">getUpperBoundSelection()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/IDisplay.html#getUserConfirmation-int-int-">getUserConfirmation(int, int)</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production">IDisplay</a></dt>
<dd>
<div class="block">Shows the user the upper bound and max number of guesses for the current game session</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedDisplay.html#getUserConfirmation-int-int-">getUserConfirmation(int, int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedDisplay.html" title="class in edu.oakland.classProject.test">AutomatedDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#getUserConfirmation-int-int-">getUserConfirmation(int, int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Main.html#giveFeedback--">giveFeedback()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production">Main</a></dt>
<dd>
<div class="block">Calls display to get feedback from the user based on the guess displayed</div>
</dd>
</dl>
<a name="I:I">
<!-- -->
</a>
<h2 class="title">I</h2>
<dl>
<dt><a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production"><span class="typeNameLink">ICore</span></a> - Interface in <a href="edu/oakland/classProject/production/package-summary.html">edu.oakland.classProject.production</a></dt>
<dd>
<div class="block">ICore class represents the interface that Core must implement
The two classes that depend on this class are Core and MockCore
Core actually computes these functions based on the SLRq while
MockCore uses db style getters and setters to ensure the MainTest
passes the JUnit tests</div>
</dd>
<dt><a href="edu/oakland/classProject/production/IDisplay.html" title="interface in edu.oakland.classProject.production"><span class="typeNameLink">IDisplay</span></a> - Interface in <a href="edu/oakland/classProject/production/package-summary.html">edu.oakland.classProject.production</a></dt>
<dd>
<div class="block">IDisplay represents the interface that the UI must implement.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#isReinitialized--">isReinitialized()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
</dl>
<a name="I:M">
<!-- -->
</a>
<h2 class="title">M</h2>
<dl>
<dt><a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production"><span class="typeNameLink">Main</span></a> - Class in <a href="edu/oakland/classProject/production/package-summary.html">edu.oakland.classProject.production</a></dt>
<dd>
<div class="block">This class defines the logic for the program flow of TheGuessingGame.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Main.html#Main-edu.oakland.classProject.production.IDisplay-">Main(IDisplay)</a></span> - Constructor for class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production">Main</a></dt>
<dd>
<div class="block">Default constuctor for use in production</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Main.html#Main-edu.oakland.classProject.production.IDisplay-edu.oakland.classProject.production.ICore-">Main(IDisplay, ICore)</a></span> - Constructor for class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production">Main</a></dt>
<dd>
<div class="block">Overloaded constructor used for testing</div>
</dd>
<dt><a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">MainTest</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class holds all of the JUnit test cases for testing the Main class using mock Display and Core classes.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#MainTest--">MainTest()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Main.html#makeGuess--">makeGuess()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production">Main</a></dt>
<dd>
<div class="block">Defines the logic for making a guess using input from the user</div>
</dd>
<dt><a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">MockCore</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class implements the ICore interface for use in testing with Main</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#MockCore--">MockCore()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test"><span class="typeNameLink">MockDisplay</span></a> - Class in <a href="edu/oakland/classProject/test/package-summary.html">edu.oakland.classProject.test</a></dt>
<dd>
<div class="block">This class implements the IDisplay interface for testing with Main and Core.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#MockDisplay--">MockDisplay()</a></span> - Constructor for class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
</dl>
<a name="I:R">
<!-- -->
</a>
<h2 class="title">R</h2>
<dl>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#reinitialize--">reinitialize()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">Resets all the values of the core object</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#reinitialize--">reinitialize()</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">Resets the current game session</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#reinitialize--">reinitialize()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
</dl>
<a name="I:S">
<!-- -->
</a>
<h2 class="title">S</h2>
<dl>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setGuess-int-">setGuess(int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#setGuessFeedback-java.lang.String-">setGuessFeedback(String)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#setGuessFeedbackSelection-java.lang.String-">setGuessFeedbackSelection(String)</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">This method sets the feedbackSelection as a String reference
which will calculate feedselection as selection</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#setGuessFeedbackSelection-java.lang.String-">setGuessFeedbackSelection(String)</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">A setter for the current user feedback</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setGuessFeedbackSelection-java.lang.String-">setGuessFeedbackSelection(String)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setGuessIteration-int-">setGuessIteration(int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setHasGameEnded-boolean-">setHasGameEnded(boolean)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setMaxNumOfGuesses-int-">setMaxNumOfGuesses(int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#setPlaySelection-char-">setPlaySelection(char)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setUpperBoundComputed-int-">setUpperBoundComputed(int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Core.html#setUpperBoundInput-int-">setUpperBoundInput(int)</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Core.html" title="class in edu.oakland.classProject.production">Core</a></dt>
<dd>
<div class="block">Calculates the upper bound based on the user's input.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/ICore.html#setUpperBoundInput-int-">setUpperBoundInput(int)</a></span> - Method in interface edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/ICore.html" title="interface in edu.oakland.classProject.production">ICore</a></dt>
<dd>
<div class="block">Sets the upper bound for the current session</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockCore.html#setUpperBoundInput-int-">setUpperBoundInput(int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockCore.html" title="class in edu.oakland.classProject.test">MockCore</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MockDisplay.html#setUpperBoundSelection-int-">setUpperBoundSelection(int)</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MockDisplay.html" title="class in edu.oakland.classProject.test">MockDisplay</a></dt>
<dd> </dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/production/Main.html#startGame--">startGame()</a></span> - Method in class edu.oakland.classProject.production.<a href="edu/oakland/classProject/production/Main.html" title="class in edu.oakland.classProject.production">Main</a></dt>
<dd>
<div class="block">Defines the logic for starting the game</div>
</dd>
</dl>
<a name="I:T">
<!-- -->
</a>
<h2 class="title">T</h2>
<dl>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testComputeInitialGuess--">testComputeInitialGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if the initial guess is calcuated as expected</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testComputeMaxNumOfGuessesAdvanced--">testComputeMaxNumOfGuessesAdvanced()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if getMaxNumOfGuesses() returns the correct number of guesses given a user defined upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testComputeMaxNumOfGuessesBasic--">testComputeMaxNumOfGuessesBasic()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if getMaxNumOfGuesses() returns the correct default number of guesses</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testComputeSubsequentGuess_Higher--">testComputeSubsequentGuess_Higher()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if the subsequent guess given a user input of higher is calculated as expected</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testComputeSubsequentGuess_Lower--">testComputeSubsequentGuess_Lower()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if the subsequent guess given a user input of lower is calculated as expected</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testEndGame--">testEndGame()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if endGame() displays the correct values for the end guess and end guess iteration</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testEndGame--">testEndGame()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if endGame() displays the correct end guess and end guess iteration values when the game has ended</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedTest.html#testGameAll--">testGameAll()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedTest.html" title="class in edu.oakland.classProject.test">AutomatedTest</a></dt>
<dd>
<div class="block">Tests the game functionality for every userNumber within a specified upperBound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedTest.html#testGameFail--">testGameFail()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedTest.html" title="class in edu.oakland.classProject.test">AutomatedTest</a></dt>
<dd>
<div class="block">Tests the game for a userNumber that is outside the upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/AutomatedTest.html#testGameSingle--">testGameSingle()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/AutomatedTest.html" title="class in edu.oakland.classProject.test">AutomatedTest</a></dt>
<dd>
<div class="block">Tests the game functionality with one specific userNumber and upperBound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/DisplayHelperTest.html#testGenerateUpperBoundOptions_d1--">testGenerateUpperBoundOptions_d1()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test">DisplayHelperTest</a></dt>
<dd>
<div class="block">Tests if generateUpperBoundOptions helper returns the correct upper bound options by default</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/DisplayHelperTest.html#testGenerateUpperBoundOptions_d1_overloaded--">testGenerateUpperBoundOptions_d1_overloaded()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test">DisplayHelperTest</a></dt>
<dd>
<div class="block">Tests if generateUpperBoundOptions returns the correct upper bound options with a set max upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/DisplayHelperTest.html#testGenerateUpperBoundOptions_d2--">testGenerateUpperBoundOptions_d2()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test">DisplayHelperTest</a></dt>
<dd>
<div class="block">Tests if generateUpperBoundOptions returns the correct upper bound options paired with option numbers</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/DisplayHelperTest.html#testGenerateUpperBoundOptions_d2_overloaded--">testGenerateUpperBoundOptions_d2_overloaded()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test">DisplayHelperTest</a></dt>
<dd>
<div class="block">Tests if generateUpperBoundOptions returns the currect upper bound options paired with option numbers with a set max upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testGetUpperBoundComputed--">testGetUpperBoundComputed()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if getUpperBoundComputed() returns the expected computed upper bound</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testGiveFeedback--">testGiveFeedback()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if giveFeedback() gets the correct user input from Display</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testGuessIteration--">testGuessIteration()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if the guessIteration is properly iterated after computing a guess</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testHasGameEnded_Equal--">testHasGameEnded_Equal()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if getHasGameEnded() returns true if the user gives a feeback selection of equal</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testHasGameEnded_False--">testHasGameEnded_False()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if getHasGameEnded() returns false when the game has not ended</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/CoreTest.html#testHasGameEnded_MaxNumOfGuessesExceeded--">testHasGameEnded_MaxNumOfGuessesExceeded()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/CoreTest.html" title="class in edu.oakland.classProject.test">CoreTest</a></dt>
<dd>
<div class="block">Tests if getHasGameEnded() returns true if the max number of guesses has been reached</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/DisplayHelperTest.html#testIntArrayToIntegerArray--">testIntArrayToIntegerArray()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/DisplayHelperTest.html" title="class in edu.oakland.classProject.test">DisplayHelperTest</a></dt>
<dd>
<div class="block">Tests if intArrayToIntergerArray converts as expected</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testMakeGuess_GuessNotMade--">testMakeGuess_GuessNotMade()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if makeGuess() returns false when a guess should not be made</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testMakeGuess_GuessNotMade--">testMakeGuess_GuessNotMade()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if makeGuess() returns false when a guess should not be made</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testMakeGuess_InitialGuess--">testMakeGuess_InitialGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if makeGuess() gets correct values for the current guess and current guess iteration when making an initial guess and returns true.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testMakeGuess_InitialGuess--">testMakeGuess_InitialGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if makeGuess() calculates the correct values for the initial guess and initial guess iteration and returns false</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testMakeGuess_SubsequentGuess--">testMakeGuess_SubsequentGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if makeGuess() gets correct values for the current guess and current guess iteration when making a subsequent guess and returns true.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testMakeGuess_SubsequentGuess--">testMakeGuess_SubsequentGuess()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if makeGuess() is able to properly make subsequent guesses</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testQuit--">testQuit()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if startGame() with a user input of quit returns false.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testQuit--">testQuit()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if startGame() returns false when given a user input of quit.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testStartGame_Advanced--">testStartGame_Advanced()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if startGame() with a user input of advanced gets correct values for the upper bound and max number of guesses and returns true.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testStartGame_Advanced--">testStartGame_Advanced()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if startGame() with a user input of advanced properly initializes values in core, and computes the upper range and max number of guesses.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/EndToEndTest.html#testStartGame_Simple--">testStartGame_Simple()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/EndToEndTest.html" title="class in edu.oakland.classProject.test">EndToEndTest</a></dt>
<dd>
<div class="block">Tests if startGame() with a user input of simple gets correct values for the upper bound and max number of guesses and returns true.</div>
</dd>
<dt><span class="memberNameLink"><a href="edu/oakland/classProject/test/MainTest.html#testStartGame_Simple--">testStartGame_Simple()</a></span> - Method in class edu.oakland.classProject.test.<a href="edu/oakland/classProject/test/MainTest.html" title="class in edu.oakland.classProject.test">MainTest</a></dt>
<dd>
<div class="block">Tests if startGame() with a user input of simple properly initializes values in core, and computes the upper range and max number of guesses.</div>
</dd>
</dl>
<a href="#I:A">A</a> <a href="#I:C">C</a> <a href="#I:D">D</a> <a href="#I:E">E</a> <a href="#I:G">G</a> <a href="#I:I">I</a> <a href="#I:M">M</a> <a href="#I:R">R</a> <a href="#I:S">S</a> <a href="#I:T">T</a> </div>
<!-- ======= START OF BOTTOM NAVBAR ====== -->
<div class="bottomNav"><a name="navbar.bottom">
<!-- -->
</a>
<div class="skipNav"><a href="#skip.navbar.bottom" title="Skip navigation links">Skip navigation links</a></div>
<a name="navbar.bottom.firstrow">
<!-- -->
</a>
<ul class="navList" title="Navigation">
<li><a href="overview-summary.html">Overview</a></li>
<li>Package</li>
<li>Class</li>
<li><a href="overview-tree.html">Tree</a></li>
<li><a href="deprecated-list.html">Deprecated</a></li>
<li class="navBarCell1Rev">Index</li>
<li><a href="help-doc.html">Help</a></li>
</ul>
</div>
<div class="subNav">
<ul class="navList">
<li>Prev</li>
<li>Next</li>
</ul>
<ul class="navList">
<li><a href="index.html?index-all.html" target="_top">Frames</a></li>
<li><a href="index-all.html" target="_top">No Frames</a></li>
</ul>
<ul class="navList" id="allclasses_navbar_bottom">
<li><a href="allclasses-noframe.html">All Classes</a></li>
</ul>
<div>
<script type="text/javascript"><!--
allClassesLink = document.getElementById("allclasses_navbar_bottom");
if(window==top) {
allClassesLink.style.display = "block";
}
else {
allClassesLink.style.display = "none";
}
//-->
</script>
</div>
<a name="skip.navbar.bottom">
<!-- -->
</a></div>
<!-- ======== END OF BOTTOM NAVBAR ======= -->
</body>
</html>
<file_sep>package edu.oakland.classProject.test;
import edu.oakland.classProject.production.Core;
import junit.framework.*;
/**
* This class holds all of the JUnit test cases for testing the Core class.
* CoreTest.java
* @version: v1.0 20150815
*/
public class CoreTest extends TestCase{
/*
This JUnit test package creates an instance of the game and then provides
simulated user input. The following 3 tests are used to show that the user
number entered and the final correct guess are pulled from different places,
that the number was guessed correctly in the maximum allowed amount of
guesses or less, and that the program is calculating the right number of
guesses based on the upperBound variable.
*/
private final int testMaxNumOfGuessesBasic = 10;
private final int testMaxNumOfGuessesAdvanced = 7;
private final int testGuessIterations = 3;
private final int testMaxNumOfGuessesHasGameEnded = 10;
private final int testCurrentGuessHasGameEnded = 10;
private final int testInitialGuess = 512;
private final int testSubsequentGuess_Higher = 768;
private final int testSubsequentGuess_Lower = 256;
private final int testUpperBoundInput = 10;
private final int testUpperBoundComputed = 1023;
/**
* Tests if getMaxNumOfGuesses() returns the correct default number of guesses
*/
public void testComputeMaxNumOfGuessesBasic(){
Core core = new Core();
assertEquals(testMaxNumOfGuessesBasic,core.getMaxNumOfGuesses());
}
/**
* Tests if getMaxNumOfGuesses() returns the correct number of guesses given a user defined upper bound
*/
public void testComputeMaxNumOfGuessesAdvanced(){
Core core = new Core();
core.setUpperBoundInput(testMaxNumOfGuessesAdvanced);
int maxNumOfGuesses = core.getMaxNumOfGuesses();
assertEquals(testMaxNumOfGuessesAdvanced,maxNumOfGuesses);
}
/**
* Tests if the initial guess is calcuated as expected
*/
public void testComputeInitialGuess(){
Core core = new Core();
core.computeGuess();
int numberGuessed = core.getGuess();
assertEquals(testInitialGuess,numberGuessed);
}
/**
* Tests if the subsequent guess given a user input of higher is calculated as expected
*/
public void testComputeSubsequentGuess_Higher(){
Core core = new Core();
core.computeGuess();
core.setGuessFeedbackSelection("higher");
core.computeGuess();
int numberGuessed = core.getGuess();
assertEquals(testSubsequentGuess_Higher,numberGuessed);
}
/**
* Tests if the subsequent guess given a user input of lower is calculated as expected
*/
public void testComputeSubsequentGuess_Lower(){
Core core = new Core();
core.computeGuess();
core.setGuessFeedbackSelection("lower");
core.computeGuess();
int numberGuessed = core.getGuess();
assertEquals(testSubsequentGuess_Lower,numberGuessed);
}
/**
* Tests if the guessIteration is properly iterated after computing a guess
*/
public void testGuessIteration(){
Core core = new Core();
for (int i=0; i < testGuessIterations; i++){
core.computeGuess();
}
int guessIteration = core.getGuessIteration();
assertEquals(testGuessIterations,guessIteration);
}
/**
* Tests if getHasGameEnded() returns false when the game has not ended
*/
public void testHasGameEnded_False(){
Core core = new Core();
core.computeGuess();
boolean hasGameEnded = core.getHasGameEnded();
assertFalse(hasGameEnded);
}
/**
* Tests if getHasGameEnded() returns true if the user gives a feeback selection of equal
*/
public void testHasGameEnded_Equal(){
Core core = new Core();
core.computeGuess();
core.setGuessFeedbackSelection("equal");
boolean hasGameEnded = core.getHasGameEnded();
assertTrue(hasGameEnded);
}
/**
* Tests if getHasGameEnded() returns true if the max number of guesses has been reached
*/
public void testHasGameEnded_MaxNumOfGuessesExceeded(){
Core core = new Core();
core.setUpperBoundInput(1);
core.getMaxNumOfGuesses();
core.computeGuess();
core.setGuessFeedbackSelection("equal");
boolean hasGameEnded = core.getHasGameEnded();
assertTrue(hasGameEnded);
}
/**
* Tests if getUpperBoundComputed() returns the expected computed upper bound
*/
public void testGetUpperBoundComputed(){
Core core = new Core();
core.setUpperBoundInput(testUpperBoundInput);
int upperBoundComputed = core.getUpperBoundComputed();
assertEquals(testUpperBoundComputed, upperBoundComputed);
}
}
<file_sep>/**
* Output requirements for display team
* @created DD_150728_1530
* @edited DD_150728_1700
*/
Welcome to The Guessing Game!
----------------------------------------
Select an option:
[P]: Play
[Q]: Quit
>* P
----------------------------------------
Enter the upper bound integer (inclusive). [1-upperBound]
upperBound: >* 1023
----------------------------------------
The device will find the correct number in {maxNumOfGuesses} guesses or less.
Select a number between 1 and {upperBound}.
DO NOT COMMUNICATE THE NUMBER CHOSEN TO THE DEVICE IN ANY WAY.
Press the enter key once you have selected a number between 1 and {upperBound}.
>* [ENTER]
----------------------------------------
Guess #{currentGuessIteration}
The system has guessed {currentGuess}.
Select an option:
[+]: My number is higher
[-]: My number is lower
[=]: My number is equal
>* +
----------------------------------------
Guess #{currentGuessIteration}
The system has guessed {currentGuess}.
Select an option:
[+]: My number is higher
[-]: My number is lower
[=]: My number is equal
>* =
----------------------------------------
The system has guessed your number, which is {currentGuess}.
The device found the correct number in {currentGuessIteration} guesses.
Select an option:
[P]: Play
[Q]: Quit
>* Q
----------------------------------------<file_sep>This program shall open when lauched by the user.
The program shall display options to either play or quit to the user.
If the program is selected to play, the user shall be prompted for an upper bound.
If the program is selected to quit, the program shall exit.
When provided with an upper bound, the program shall determine the number of guesses required and make its first guess.
The program shall prompt the user as to whether the guess if lower, higher, or equal to the user's selected number.
If the user selects higher or lower, the program shall make a new guess and prompt the user about the new guess.
If the user selects equals, the program shall display the user's number and display the opening message again.
The program shall continue to make guesses and prompt the user until the user either selects equals or the program runs out of guesses.
If the program runs out of guesses, the program shall display the last guess as the user's selected number.
<file_sep>package edu.oakland.classProject.test;
import junit.framework.TestCase;
import edu.oakland.classProject.production.Main;
/**
* This class tests the robustness of the entire program by simulating how a user would play the game.
*@author
*@version 1.0 150816
*@since 1.0 150816
*/
public class AutomatedTest extends TestCase{
/**
* Tests the game functionality with one specific userNumber and upperBound
*/
public void testGameSingle(){
int userNumber = 1000;
int upperBoundInput = 10;
AutomatedDisplay display = new AutomatedDisplay(userNumber, upperBoundInput);
Main main = new Main(display);
while(main.startGame()){
while(main.makeGuess()){
main.giveFeedback();
}
main.endGame();
}
assertEquals(display.getEndGuess(), userNumber);
}
/**
* Tests the game functionality for every userNumber within a specified upperBound
*/
public void testGameAll(){
int userNumber = 1;
int upperBoundInput = 16;
int upperBound = 65536;
AutomatedDisplay display;
Main main;
while(userNumber < upperBound) {
display = new AutomatedDisplay(userNumber, upperBoundInput);
main = new Main(display);
while(main.startGame()){
while(main.makeGuess()){
main.giveFeedback();
}
main.endGame();
}
assertEquals(display.getEndGuess(), userNumber);
userNumber++;
}
}
/**
* Tests the game for a userNumber that is outside the upper bound
*/
public void testGameFail(){
int userNumber = 1050;
int upperBoundInput = 10;
AutomatedDisplay display = new AutomatedDisplay(userNumber, upperBoundInput);
Main main = new Main(display);
while(main.startGame()){
while(main.makeGuess()){
main.giveFeedback();
}
main.endGame();
}
assertFalse(userNumber == display.getEndGuess());
}
}
<file_sep>package edu.oakland.classProject.production;
/** ICore class represents the interface that Core must implement
The two classes that depend on this class are Core and MockCore
Core actually computes these functions based on the SLRq while
MockCore uses db style getters and setters to ensure the MainTest
passes the JUnit tests
*/
public interface ICore {
/**
* Resets the current game session
*/
public void reinitialize();
/**
* Sets the upper bound for the current session
* @param upperBoundInput the upper bound
*/
public void setUpperBoundInput(int upperBoundInput);
/**
* A getter for the upper bound
* @return the upper bound
*/
public int getUpperBoundComputed();
/**
* A getter for the max number of guesses
* @return the max number of guesses needed by the app for the selected upper bound
*/
public int getMaxNumOfGuesses();
/**
* A getter for the end status of the current game session
* @return Returns whether the game has ended
*/
public boolean getHasGameEnded();
/**
* Has core compute the next guess based on class variables
*/
public void computeGuess();
/**
* A getter for the current guess
* @return the current guess made by the app
*/
public int getGuess();
/**
* A getter for the current guess iteration
* @return the current guess iteration
*/
public int getGuessIteration();
/**
* A setter for the current user feedback
* @param guessFeedbackSelection the feedback given by the display telling Core wheter the user said their guess was higher or lower
*/
public void setGuessFeedbackSelection(String guessFeedbackSelection);
}
<file_sep>package edu.oakland.classProject.cmdLine;
import java.util.*;
import edu.oakland.classProject.production.IDisplay;
import edu.oakland.classProject.helper.DisplayHelper;
/**
*This class holds the methods involved with displaying the command line interface.
*@version "version 0.0.2" "150803"
*/
public class Display implements IDisplay {
/**
* The local variables that determines the min and max that a user
* can select from.
* @param int MIN_UPPERBOUND_OPTION is the lowwest number possible.
* @param int MAX_UPPERBOUND_OPTION is the hightest number possible.
*/
int MIN_UPPERBOUND_OPTION = 1;
int MAX_UPPERBOUND_OPTION = 16;
/*
*TODO: make sure to define each method's functionality
*/
private String[] playOptions = new String[]{
"[S]: Simple play",
"[A]: Advanced play",
"[Q]: Quit"
};
private String[] guessOptions = new String[]{
"[+]: My number is higher",
"[-]: My number is lower",
"[=]: My number is equal"
};
private char[] playSelections = optionsToSelections(playOptions);
private char[] guessSelections = optionsToSelections(guessOptions);
/**
*This method displays the displaystart screen to the user.
* User must select an option.
* @param diplayWelcomeMessage
* @param diplayOptions
* @return char This returns the selection entered by user
* which should be redirected to the Play Selection.
*/
public char getPlaySelection(){
displayWelcomeMessage();
displayOptions(playOptions);
return requestEnterSelection(playSelections);
}
/**
* Displays the UpperBound selection.
* @return the display of the requested UpperBound that was entered.
*/
public int getUpperBoundSelection(){
displayRequestUpperBoundSelection();
return requestEnterUpperBoundSelection();
}
public void getUserConfirmation(int upperBoundComputed, int maxNumOfGuesses){
displayRange(upperBoundComputed);
displayReminder();
displayNumOfGuesses(maxNumOfGuesses, false);
displayRequestReturnKey();
requestReturnKey();
}
public void displayGuessInfo(int currentGuess, int currentGuessIteration){
String lineToPrint = String.format("Guess #%d\nThe system has guessed %d.", currentGuessIteration, currentGuess);
System.out.println(lineToPrint);
}
public String getGuessFeedback(){
return formatGuessFeedback(requestEnterGuessFeedback());
}
public String formatGuessFeedback(char guessFeedback){
String formattedGuessFeedback = new String();
switch (guessFeedback){
case '+': //"My number is higher"
formattedGuessFeedback = "higher";
break;
case '-': //"My number is lower"
formattedGuessFeedback = "lower";
break;
case '=': //"My number is equal"
formattedGuessFeedback = "equal";
break;
}
return formattedGuessFeedback;
}
public void getEndGameConfirmation(int guess, int guessIteration){
System.out.println(String.format("The system has guessed your number, which is %d.", guess));
displayNumOfGuesses(guessIteration, true);
displayRequestReturnKey();
requestReturnKey();
}
private char requestEnterGuessFeedback(){
displayOptions(guessOptions);
return requestEnterSelection(guessSelections);
}
/**
* Displays Welcome Message.
* Welcome title diplayed at the beginning of the game.
*/
private void displayWelcomeMessage() {
System.out.println("Welcome to The Guessing Game!");
System.out.println();
}
/**
* Instructions user to choose a number between 1 and UpperBound.
* Will diplay for user to chose a number.
* @see upperBoundComputed
*/
private void displayRange(int upperBoundComputed){
String lineToPrint = String.format("Please think of a number between 1 and %d.", upperBoundComputed);
System.out.println(lineToPrint);
System.out.println();
}
/**
* Diplays warning message to user.
* Warns user of the rules of the game.
*/
private void displayReminder(){
System.out.println("Make sure you remember your number,");
System.out.println("and do not change it during the game.");
System.out.println();
}
private void displayNumOfGuesses(int numOfGuesses, boolean gameEnded){
String verbTense = new String();
String plurality = new String();
if (gameEnded)
verbTense = "successfully guessed";
else
verbTense = "will guess";
if (numOfGuesses > 1){
plurality = "es";
if (!gameEnded)
plurality += " or fewer";
}
else
plurality = "";
String lineToPrint = String.format("The system %s your number in %d guess%s.", verbTense, numOfGuesses, plurality);
System.out.println(lineToPrint);
System.out.println();
}
/**
* Prints for user to enter an option for upper bound
*
*
*/
private void displayRequestUpperBoundSelection(){
System.out.println("Please enter an option for your desired upper bound.");
DisplayHelper displayHelper = new DisplayHelper(MIN_UPPERBOUND_OPTION, MAX_UPPERBOUND_OPTION);
int[][] upperBoundOptions = (int[][])displayHelper.generateUpperBoundOptions(2);
for (int[] option : upperBoundOptions){
int maxNumOfGuesses = option[0];
int upperBound = option[1];
System.out.println(String.format("[%d]: %d", maxNumOfGuesses, upperBound));
}
}
/**
* This method checks to see if the integer is a valid entry
* If the selection is incorrect, the System will throw an error message
* saying Invalid Input.
* Creates a Scanner class to be able to print multiple lines.
* @param userInput the userInput is the input stored by the user
* @return the request for upper bound selected
*
*/
private int requestEnterUpperBoundSelection(){
System.out.print(">");
Scanner input = new Scanner(System.in);
String userInput = input.next();
while (!isInteger(userInput)){
System.out.println("Invalid input! Please enter a valid integer.");
return requestEnterUpperBoundSelection();
}
int intInput = Integer.parseInt(userInput);
while(intInput < MIN_UPPERBOUND_OPTION || intInput > MAX_UPPERBOUND_OPTION){
System.out.println(String.format("Invalid input! Please enter a valid selection."));
return requestEnterUpperBoundSelection();
}
return intInput;
}
private char requestEnterSelection(char[] selections){
System.out.print(">");
Scanner input = new Scanner(System.in);
String userInput = input.next();
while (userInput.length() != 1){
System.out.println("Invalid selection! Please enter a 1 character selection.");
return requestEnterSelection(selections);
}
char selectionChar = userInput.toUpperCase().charAt(0);
while(!contains(selectionChar, selections)){
System.out.println("Invalid selection! Please enter a valid selection.");
return requestEnterSelection(selections);
}
return selectionChar;
}
/**
* Diplay for the user to press the return (enter)
* button to continue the game.
*/
private void displayRequestReturnKey(){
System.out.println("Press the return key to continue.");
}
/**
* The method checks for the user pressing the enter key.
* @param input looks for the user to press the enter key.
* @return the enter key
*/
private void requestReturnKey(){
System.out.print(">");
Scanner input = new Scanner(System.in);
input.nextLine();
return;
}
private void displayOptions(String[] options){
System.out.println("Select an option:");
for (String option : options) {
System.out.println(option);
}
}
private char[] optionsToSelections(String[] options){
int selection = 0;
char[] selections = new char[options.length];
for (String option : options) {
selections[selection] = option.charAt(1);
selection++;
}
return selections;
}
private boolean contains(char c, char[] array) {
for (char x : array) {
if (x == c) {
return true;
}
}
return false;
}
/**
* String utility class to determine if a given string is a number (Integer).
* Using method try, catch to only accept numbers.
* <p>
* This method always returns immediately, whether or not the
* number exists. When this user attempts to place a letter on
* the screen, the data will throw an exception.
*
* @param name the location of the image, relative to the url argument
* @return true
*/
private static boolean isInteger(String s) {
try {
Integer.parseInt(s);
} catch(NumberFormatException e) {
return false;
} catch(NullPointerException e) {
return false;
}
return true;
}
}
<file_sep>package edu.oakland.classProject.test;
import edu.oakland.classProject.production.IDisplay;
/**
* This class implements the IDisplay interface for testing with Main and Core.
*@author
*@version 1.0 150816
*@since 1.0 150816
*/
public class MockDisplay implements IDisplay {
private char playSelection;
private int upperBoundSelection;
private int upperBoundComputed;
private int maxNumOfGuesses;
private int currentGuess;
private int currentGuessIteration;
private String guessFeedback;
private int endGuess;
private int endGuessIteration;
public void setPlaySelection(char _playSelection){
playSelection = _playSelection;
}
public char getPlaySelection(){
return playSelection;
}
public void setUpperBoundSelection(int _upperBoundSelection){
upperBoundSelection = _upperBoundSelection;
}
public int getUpperBoundSelection(){
return upperBoundSelection;
}
public void getUserConfirmation(int _upperBoundComputed, int _maxNumOfGuesses){
upperBoundComputed = _upperBoundComputed;
maxNumOfGuesses = _maxNumOfGuesses;
}
public int getUpperBoundComputed(){
return upperBoundComputed;
}
public int getMaxNumOfGuesses(){
return maxNumOfGuesses;
}
public void displayGuessInfo(int _currentGuess, int _currentGuessIteration){
currentGuess = _currentGuess;
currentGuessIteration = _currentGuessIteration;
}
public int getCurrentGuess(){
return currentGuess;
}
public int getCurrentGuessIteration(){
return currentGuessIteration;
}
public void setGuessFeedback(String _guessFeedback){
guessFeedback = _guessFeedback;
}
public String getGuessFeedback(){
return guessFeedback;
}
public void getEndGameConfirmation(int _guess, int _guessIteration){
endGuess = _guess;
endGuessIteration = _guessIteration;
}
public int getEndGuess(){
return endGuess;
}
public int getEndGuessIteration(){
return endGuessIteration;
}
}
<file_sep>package edu.oakland.classProject.production.android;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.content.Intent;
import edu.oakland.classProject.production.IDisplay;
import edu.oakland.classProject.production.Main;
import edu.oakland.classProject.helper.DisplayHelper;
public class MainActivity extends Activity implements IDisplay {
// INSTANCE VARIABLE - Create instance of Main class, and that instance will be loaded for the entire game
Main main;
private TextView tvGameOver;
private TextView tvGuessIteration;
private TextView tvGuess;
private Button btnHigher;
private Button btnEquals;
private Button btnLower;
private Spinner sprAdvanced;
private RadioGroup rbsPlayOptions;
private RadioButton rbBasic;
private RadioButton rbAdvanced;
private TextView tvBasic;
private TextView tvAdvanced;
private TextView tvMaxNumOfGuesses;
private Button btnGuess;
private Button btnNumChosen;
int MIN_UPPERBOUND_OPTION = 3;
int MAX_UPPERBOUND_OPTION = 16;
DisplayHelper displayHelper = new DisplayHelper(MIN_UPPERBOUND_OPTION, MAX_UPPERBOUND_OPTION);
private int[] upperBoundSelection_int = (int[])displayHelper.generateUpperBoundOptions(1);
private Integer[] upperBoundSelection = DisplayHelper.intArrayToIntegerArray(upperBoundSelection_int);
private Button currentFeedbackButton;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.displaystart);
main = new Main(MainActivity.this);
rbsPlayOptions = (RadioGroup) findViewById(R.id.rbsPlayOptions);
rbBasic = (RadioButton) findViewById(R.id.rbBasic);
rbAdvanced = (RadioButton) findViewById(R.id.rbAdvanced);
tvBasic = (TextView) findViewById(R.id.tvBasic);
tvAdvanced = (TextView) findViewById(R.id.tvAdvanced);
sprAdvanced = (Spinner) findViewById(R.id.sprAdvanced);
btnGuess = (Button) findViewById(R.id.btnGuess);
tvMaxNumOfGuesses = (TextView) findViewById(R.id.tvMaxNumOfGuesses);
btnNumChosen = (Button) findViewById(R.id.btnNumChosen);
ArrayAdapter<Integer> dataAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, upperBoundSelection);
dataAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
sprAdvanced.setAdapter(dataAdapter);
}
/**
* Disables radio buttons and dropdown menu,
* displays textview saying how many guesses the system gets, and
* displays the button to start the game
* @param view Takes the button that is pressed of type View*/
public void btnNumberChosen_OnClick(View view){
main.startGame();
//Disable other radio button and Spinner
rbBasic.setEnabled(false);
rbAdvanced.setEnabled(false);
sprAdvanced.setEnabled(false);
btnNumChosen.setEnabled(false);
btnGuess.setVisibility(View.VISIBLE);
tvMaxNumOfGuesses.setVisibility(View.VISIBLE);
}
/**
* Displays the Game Screen, calls btnFeedback_OnClick method
* @param view Takes the button that is pressed of type View
* */
public void btnGuess_OnClick(View view){
setContentView(R.layout.displayguess);
tvGuessIteration = (TextView) findViewById(R.id.tvGuessIteration);
tvGuess = (TextView) findViewById(R.id.tvGuess);
tvGameOver = (TextView) findViewById(R.id.tvGameOver);
btnHigher = (Button) findViewById(R.id.btnHigher);
btnEquals = (Button) findViewById(R.id.btnEquals);
btnLower = (Button) findViewById(R.id.btnLower);
btnFeedback_OnClick(view);
}
/**
* Gets whether Basic or Advanced is selected
* @return Returns a variable of type char that resembles the user's game type selected
* */
public char getPlaySelection() {
int rbId = rbsPlayOptions.getCheckedRadioButtonId();
RadioButton rb = (RadioButton) findViewById(rbId);
String result = rb.getText().toString();
if (result.equals("Basic")) {
return 'S';
} else {
return 'A';
}
}
/**
* Gets the upper bound that's selected
* @return The upper bound selected of type int
* */
public int getUpperBoundSelection(){
return sprAdvanced.getSelectedItemPosition() + MIN_UPPERBOUND_OPTION;
}
/**
* Displays how many guesses the system has to guess the user's number
* @param upperBoundComputed The upper bound selected
* @param maxNumOfGuesses The number of guesses the system has, given the upper bound
* */
public void getUserConfirmation(int upperBoundComputed, int maxNumOfGuesses) {
String strFormat = getResources().getString(R.string.max_num_of_guesses);
String strMessage = String.format(strFormat, maxNumOfGuesses);
tvMaxNumOfGuesses.setText(strMessage);
}
/**
* Displays the currentGuess and currentGuessIteration to the user
*@param currentGuess The system's current guess of type "int"
*@param currentGuessIteration The system's current guess number of type "int"
*/
public void displayGuessInfo(int currentGuess, int currentGuessIteration){
String strCurrentGuessFormat = getResources().getString(R.string.current_guess);
String strCurrentGuessMessage = String.format(strCurrentGuessFormat, currentGuess);
String strGuessIterationFormat = getResources().getString(R.string.guess_iteration);
String strGuessIterationMessage = String.format(strGuessIterationFormat, currentGuessIteration);
tvGuess.setText(strCurrentGuessMessage);
tvGuessIteration.setText(strGuessIterationMessage);
}
/**
* Gets the status of the feedback button and returns it
* @return the value of "currentFeedbackButton.getTag().toString()" of type String
*/
public String getGuessFeedback(){
return currentFeedbackButton.getTag().toString();
}
/**
* Displays the end game screen to the user with the end guess and guessIteration
* @param guess The system's current guess of type "int"
* @param guessIteration The system's current guess number of type "int"
*/
public void getEndGameConfirmation(int guess, int guessIteration){
// tvGameOver.setVisibility(View.VISIBLE);
String strCurrentGuessFormat = getResources().getString(R.string.final_guess);
String strCurrentGuessMessage = String.format(strCurrentGuessFormat, guess);
String strGuessIterationFormat = getResources().getString(R.string.guess_iteration);
String strGuessIterationMessage = String.format(strGuessIterationFormat, guessIteration);
tvGuess.setText(strCurrentGuessMessage);
tvGuessIteration.setText(strGuessIterationMessage);
btnHigher.setVisibility(View.GONE);
btnLower.setVisibility(View.GONE);
btnEquals.setVisibility(View.GONE);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
// Do something after 5s = 5000ms
Intent intent = getIntent();
finish();
startActivity(intent);
}
}, 2500);
}
/**
* Handles the click events on the radio buttons showing the basic and advanced game type selections
* @param view The radio button that was clicked of type "View"
*/
public void rbOption_OnClick(View view){
if (rbBasic.isChecked()){
tvBasic.setVisibility(View.VISIBLE);
tvAdvanced.setVisibility(View.GONE);
sprAdvanced.setVisibility(View.GONE);
}
else{ //if (rbAdvanced.isChecked())
tvBasic.setVisibility(View.GONE);
tvAdvanced.setVisibility(View.VISIBLE);
sprAdvanced.setVisibility(View.VISIBLE);
}
btnNumChosen.setEnabled(true);
}
/**
* Called when the user gives their feedback on a guess
* Handles logic for when to call giveFeedback() and endGame() in Main
* @param view The button that was pressed of type "View"
*/
public void btnFeedback_OnClick(View view){
currentFeedbackButton = (Button)view;
// if this is not the initial guess
if (currentFeedbackButton.getId() != R.id.btnGuess)
main.giveFeedback();
if (!main.makeGuess())
main.endGame();
}
}
<file_sep># TheGuessingGame
The Guessing Game allows the user to think of a number 1 through 1023, and the app will guess the user’s number in 10 guesses or fewer, given the correct guess feedback arguments.
# System-Level Requirements
- The system shall provide a means for the user to start the game.
- The system shall provide a means for the user to quit the game.
- The upper bound shall be 1024.
- The system shall display the guessable range (1 – 1023)
- The system shall provide a means for User to inform the device that he/she has selected a number between 1 and 1,023.
- The system shall be able to find the number in 10 guesses or less
- The system shall have a way to determine what guess it is on.
- The system shall be able to receive feedback from the user:
- The guess is correct.
- The guess is too high
- The guess is too low.
- The system shall be able to determine the next number to guess.
- The system shall be able to store the last number that it guessed.
- The system shall be able to display the number guessed
- The system shall have a way to end the game once either the guessed number is correct or the maximum guess count is reached.
Extra Credit:
- A means for the user to set the upper bound
- Use binomial theorem to log base 2 to determine number of guesses, round up to whole number if log is a decimal
# Javadocs
http://cit-cse-337-summer-2015.github.io/TheGuessingGame/
# Presentation
[Click here to view the presentation](https://docs.google.com/a/oakland.edu/presentation/d/1g8itabDIH__EbUkqzAHWQnEOrx0TsDYNr29Bfaakx50/edit?usp=sharing)
|
8f1f979621b666b54e6f28a955b52b5992450ae7
|
[
"Markdown",
"Java",
"Text",
"HTML"
] | 10 |
HTML
|
CIT-CSE-337-Summer-2015/TheGuessingGame
|
acb1a6440399f2221284aa57b0e0094660206d32
|
22633cc3674632b961eca4373977b9ace369d82f
|
refs/heads/master
|
<file_sep># Lifeguards-
<file_sep>/*
* first lets remove every interval lies in another interval and subtract the number of removed intervals from k
* now lets sort the intervals ( notice that both the li & ri are in increasing order )
* lets fill dp [N][K][2] , dp[i][j][z] is the maximum amount of time covered by the the first i cows and we have fired j cows and z = 0 the i'th cow is fired z = 1 otherwise
* it is easy to fill the dp[i][j][0] part -> dp [i][j][0] = max ( dp [i-1][j-1][0] , dp [i-1][j-1][1] )
* so we are remaining with the part of not firing the i'th cow , notice that between all of the id that achieve r[id] > l[i]
* the optimal solution is to take the minimum id ( the minimum intersection ) , let J = max ( 0 , j - ( i - id - 1 ) ) then ->
* dp [i][j][1] = ( max dp [id][J][0] firing all the cows that intersect with the i'th cow
* dp [id][J][1] - overlap ( id , i ) firing all the cows the intersect with the i'th cow expect the cow with the minimum intersection )
* + the size of the i'th interval ( dont forget to subtract the overlap between the i'th cow and the id cow when trying not to fire it )
*/
#define fast ios_base::sync_with_stdio(0),cin.tie(0),cout.tie(0)
#include <bits/stdc++.h>
using namespace std;
#define sqr 547
#define mp make_pair
#define mid (l+r)/2
#define pb push_back
#define ppb pop_back
#define fi first
#define se second
#define lb lower_bound
#define ub upper_bound
#define ins insert
#define era erase
#define C continue
#define mem(dp,i) memset(dp,i,sizeof(dp))
#define mset multiset
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef short int si;
typedef long double ld;
typedef pair<int,int> pi;
typedef pair<ll,ll> pll;
typedef vector<int> vi;
typedef vector<ll> vll;
typedef vector<pi> vpi;
typedef vector<pll> vpll;
const ll inf=1e18;
const ll mod=1e9+7;
const ld pai=acos(-1);
int N , n , k ;
int done [100009] ;
vpi ord ;
pi a [100009] , ret [100009] ;
int dp [100009][109][2] ;
int sz ( int l , int r ) {
return r - l ;
}
int overlap ( int i , int j ) {
return max ( 0 , a [i].se - a [j].fi ) ;
}
int find ( int l , int r ) {
int id = lb ( ord.begin() , ord.end() , mp ( l , -1 ) ) - ord.begin() ;
if ( ord [id] .fi == r ) id -- ;
return id ;
}
int main () {
freopen("lifeguards.in", "r", stdin);
freopen("lifeguards.out", "w", stdout);
cin >> n >> k ;
for ( int i = 0 ; i < n ; i ++ ) {
cin >> ret [i] .fi >> ret [i] .se ;
}
sort ( ret , ret + n ) ;
int Mx = 0 ;
for ( int i = 0 ; i < n ; i ++ ) {
done [i] = ( Mx > ret [i] .se ) ;
Mx = max ( Mx , ret[i] .se ) ;
}
a [0] = { 0 , 0 } ;
ord .pb (a[0]) ;
for ( int i = 0 ; i < n ; i ++ ) {
if ( done [i] ) C ;
a [ ++N ] = ret [i] ;
ord .pb ( { ret [i].se , ret [i].fi } ) ;
}
k -= ( n - N ) ;
k = max ( k , 0 ) ;
for ( int i = 1 ; i <= N ; i ++ ) {
int id = find ( a[i] .fi , a[i] .se ) ;
for ( int j = 0 ; j <= min ( k , i ) ; j ++ ) {
if ( j ) dp [i][j][0] = max ( dp [i-1][j-1][0] , dp [i-1][j-1][1] ) ;
if ( j == i ) break ;
int J = max ( 0 , j - ( i - id - 1 ) ) ;
dp [i][j][1] = max ( dp [id][J][0] , dp [id][J][1] - overlap ( id , i ) ) + sz ( a[i] .fi , a[i] .se ) ;
}
}
cout << max ( dp [N][k][0] , dp [N][k][1] ) << endl ;
}
|
e632bde53fa6636aad599cc98c41748128ec5b20
|
[
"Markdown",
"C++"
] | 2 |
Markdown
|
besherislambouley/Lifeguards-
|
4cde6e1d58f0d871ae149700f833330b4c7d0a79
|
6bec31fbd86428907d801ffa93995f45cbb688e2
|
refs/heads/master
|
<file_sep>namespace :db do
desc "Fill database with sample data"
task populate: :environment do
make_users
make_microposts
make_relationships
end
end
def make_users
User.create!(name: "<NAME>",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>",
admin: true)
User.create!(name: "<NAME>",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>",
admin: false)
User.create!(name: "<NAME>",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>",
admin: false)
User.create!(name: "<NAME>",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>",
admin: false)
User.create!(name: "<NAME>",
email: "<EMAIL>",
password: "<PASSWORD>",
password_confirmation: "<PASSWORD>",
admin: false)
99.times do |n|
name = Faker::Name.name
email = "<EMAIL>"
password = "<PASSWORD>"
User.create!(name: name,
email: email,
password: <PASSWORD>,
password_confirmation: <PASSWORD>)
end
end
def make_microposts
users = User.all(limit: 6)
50.times do
content = Faker::Lorem.sentence(5)
users.each { |user| user.microposts.create!(content: content) }
end
end
def make_relationships
users = User.all
user = users.first
followed_users = users[2..50]
followers = users[3..40]
followed_users.each { |followed| user.follow!(followed) }
followers.each { |follower| follower.follow!(user) }
end
|
5b06044e125e5ee41f4bb4ae14ae0ad5a89e716a
|
[
"Ruby"
] | 1 |
Ruby
|
JC103/sample_app
|
69483a0451a8b8de255ea9cb3c1ecd3a80287389
|
b4003cf6c7ead31313a3e7316988bae9d5d4b346
|
refs/heads/main
|
<repo_name>mi-v/img1b<file_sep>/png/reader_test.go
// Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2020 <NAME>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package png
import (
"bufio"
"bytes"
"fmt"
"github.com/mi-v/img1b"
"image/color"
gopng "image/png"
"io"
"io/ioutil"
"os"
"reflect"
"strings"
"testing"
)
var filenames = []string{
"basn0g01",
"basn0g01-30",
"basn3p01",
"ftbbn0g01",
}
var filenamesPaletted = []string{
"basn3p01",
}
func readPNG(filename string) (*img1b.Image, error) {
f, err := os.Open(filename)
if err != nil {
return nil, err
}
defer f.Close()
return Decode(f)
}
// An approximation of the sng command-line tool.
func sng(w io.WriteCloser, filename string, png *img1b.Image) {
defer w.Close()
bounds := png.Bounds()
// Write the filename and IHDR.
io.WriteString(w, "#SNG: from "+filename+".png\nIHDR {\n")
fmt.Fprintf(w, " width: %d; height: %d; bitdepth: 1;\n", bounds.Dx(), bounds.Dy())
io.WriteString(w, " using color palette;\n")
io.WriteString(w, "}\n")
// Write the PLTE and tRNS (if applicable).
lastAlpha := -1
io.WriteString(w, "PLTE {\n")
for i, c := range png.Palette {
var r, g, b, a uint8
switch c := c.(type) {
case color.RGBA:
r, g, b, a = c.R, c.G, c.B, 0xff
case color.NRGBA:
r, g, b, a = c.R, c.G, c.B, c.A
default:
panic("unknown palette color type")
}
if a != 0xff {
lastAlpha = i
}
fmt.Fprintf(w, " (%3d,%3d,%3d) # rgb = (0x%02x,0x%02x,0x%02x)\n", r, g, b, r, g, b)
}
io.WriteString(w, "}\n")
if lastAlpha != -1 {
io.WriteString(w, "tRNS {\n")
for i := 0; i <= lastAlpha; i++ {
_, _, _, a := png.Palette[i].RGBA()
a >>= 8
fmt.Fprintf(w, " %d", a)
}
io.WriteString(w, "}\n")
}
// Write the IMAGE.
io.WriteString(w, "IMAGE {\n pixels base64\n")
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
for x := bounds.Min.X; x < bounds.Max.X; x++ {
fmt.Fprintf(w, "%d", png.ColorIndexAt(x, y))
}
io.WriteString(w, "\n")
}
io.WriteString(w, "}\n")
}
func TestReader(t *testing.T) {
names := filenames
for _, fn := range names {
// Read the .png file.
img, err := readPNG("testdata/pngsuite/" + fn + ".png")
if err != nil {
t.Error(fn, err)
continue
}
piper, pipew := io.Pipe()
pb := bufio.NewScanner(piper)
go sng(pipew, fn, img)
defer piper.Close()
// Read the .sng file.
sf, err := os.Open("testdata/pngsuite/" + fn + ".sng")
if err != nil {
t.Error(fn, err)
continue
}
defer sf.Close()
sb := bufio.NewScanner(sf)
// Compare the two, in SNG format, line by line.
for {
pdone := !pb.Scan()
sdone := !sb.Scan()
if pdone && sdone {
break
}
if pdone || sdone {
t.Errorf("%s: Different sizes", fn)
break
}
ps := pb.Text()
ss := sb.Text()
// Newer versions of the sng command line tool append an optional
// color name to the RGB tuple. For example:
// # rgb = (0xff,0xff,0xff) grey100
// # rgb = (0x00,0x00,0xff) blue1
// instead of the older version's plainer:
// # rgb = (0xff,0xff,0xff)
// # rgb = (0x00,0x00,0xff)
// We strip any such name.
if strings.Contains(ss, "# rgb = (") && !strings.HasSuffix(ss, ")") {
if i := strings.LastIndex(ss, ") "); i >= 0 {
ss = ss[:i+1]
}
}
if ps != ss {
t.Errorf("%s: Mismatch\n%s\nversus\n%s\n", fn, ps, ss)
break
}
}
if pb.Err() != nil {
t.Error(fn, pb.Err())
}
if sb.Err() != nil {
t.Error(fn, sb.Err())
}
}
}
var readerErrors = []struct {
file string
err string
}{
{"invalid-zlib.png", "zlib: invalid checksum"},
{"invalid-crc32.png", "invalid checksum"},
{"invalid-noend.png", "unexpected EOF"},
{"invalid-trunc.png", "unexpected EOF"},
}
func TestReaderError(t *testing.T) {
for _, tt := range readerErrors {
img, err := readPNG("testdata/" + tt.file)
if err == nil {
t.Errorf("decoding %s: missing error", tt.file)
continue
}
if !strings.Contains(err.Error(), tt.err) {
t.Errorf("decoding %s: %s, want %s", tt.file, err, tt.err)
}
if img != nil {
t.Errorf("decoding %s: have image + error", tt.file)
}
}
}
func TestPalettedDecodeConfig(t *testing.T) {
for _, fn := range filenamesPaletted {
f, err := os.Open("testdata/pngsuite/" + fn + ".png")
if err != nil {
t.Errorf("%s: open failed: %v", fn, err)
continue
}
defer f.Close()
cfg, err := DecodeConfig(f)
if err != nil {
t.Errorf("%s: %v", fn, err)
continue
}
pal, ok := cfg.ColorModel.(color.Palette)
if !ok {
t.Errorf("%s: expected paletted color model", fn)
continue
}
if pal == nil {
t.Errorf("%s: palette not initialized", fn)
continue
}
}
}
func TestInterlaced(t *testing.T) {
a, err := readPNG("testdata/gradient.png")
if err != nil {
t.Fatal(err)
}
b, err := readPNG("testdata/gradient.interlaced.png")
if err != nil {
t.Fatal(err)
}
if !reflect.DeepEqual(a, b) {
t.Fatalf("decodings differ:\nnon-interlaced:\n%#v\ninterlaced:\n%#v", a, b)
}
}
func TestIncompleteIDATOnRowBoundary(t *testing.T) {
// The following is an invalid 1x2 grayscale PNG image. The header is OK,
// but the zlib-compressed IDAT payload contains two bytes "\x02\x00",
// which is only one row of data (the leading "\x02" is a row filter).
const (
ihdr = "\x00\x00\x00\x0dIHDR\x00\x00\x00\x01\x00\x00\x00\x02\x01\x00\x00\x00\x00\xb1\xfa\x8b\x8a"
idat = "\x00\x00\x00\x0eIDAT\x78\x9c\x62\x62\x00\x04\x00\x00\xff\xff\x00\x06\x00\x03\xfa\xd0\x59\xae"
iend = "\x00\x00\x00\x00IEND\xae\x42\x60\x82"
)
_, err := Decode(strings.NewReader(pngHeader + ihdr + idat + iend))
if err == nil {
t.Fatal("got nil error, want non-nil")
}
}
func TestTrailingIDATChunks(t *testing.T) {
// The following is a valid 1x1 PNG image containing color.Gray{255} and
// a trailing zero-length IDAT chunk (see PNG specification section 12.9):
const (
ihdr = "\x00\x00\x00\x0dIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x01\x00\x00\x00\x00\x37\x6e\xf9\x24"
idatWhite = "\x00\x00\x00\x0eIDAT\x78\x9c\x62\xfa\x0f\x08\x00\x00\xff\xff\x01\x05\x01\x02\x5a\xdd\x39\xcd"
idatZero = "\x00\x00\x00\x00IDAT\x35\xaf\x06\x1e"
iend = "\x00\x00\x00\x00IEND\xae\x42\x60\x82"
)
_, err := Decode(strings.NewReader(pngHeader + ihdr + idatWhite + idatZero + iend))
if err != nil {
t.Fatalf("decoding valid image: %v", err)
}
// Non-zero-length trailing IDAT chunks should be ignored (recoverable error).
// The following chunk contains a single pixel with color.Gray{0}.
const idatBlack = "\x00\x00\x00\x0eIDAT\x78\x9c\x62\x62\x00\x04\x00\x00\xff\xff\x00\x06\x00\x03\xfa\xd0\x59\xae"
img, err := Decode(strings.NewReader(pngHeader + ihdr + idatWhite + idatBlack + iend))
if err != nil {
t.Fatalf("trailing IDAT not ignored: %v", err)
}
if img.At(0, 0) == (color.Gray{0}) {
t.Fatal("decoded image from trailing IDAT chunk")
}
}
func TestMultipletRNSChunks(t *testing.T) {
/*
The following is a valid 1x1 paletted PNG image with a 1-element palette
containing color.NRGBA{0xff, 0x00, 0x00, 0x7f}:
0000000: 8950 4e47 0d0a 1a0a 0000 000d 4948 4452 .PNG........IHDR
0000010: 0000 0001 0000 0001 0103 0000 0025 db56 .............%.V
0000020: ca00 0000 0350 4c54 45ff 0000 19e2 0937 .....PLTE......7
0000030: 0000 0001 7452 4e53 7f80 5cb4 cb00 0000 ....tRNS..\.....
0000040: 0e49 4441 5478 9c62 6200 0400 00ff ff00 .IDATx.bb.......
0000050: 0600 03fa d059 ae00 0000 0049 454e 44ae .....Y.....IEND.
0000060: 4260 82 B`.
Dropping the tRNS chunk makes that color's alpha 0xff instead of 0x7f.
*/
const (
ihdr = "\x00\x00\x00\x0dIHDR\x00\x00\x00\x01\x00\x00\x00\x01\x01\x03\x00\x00\x00\x25\xdb\x56\xca"
plte = "\x00\x00\x00\x03PLTE\xff\x00\x00\x19\xe2\x09\x37"
trns = "\x00\x00\x00\x01tRNS\x7f\x80\x5c\xb4\xcb"
idat = "\x00\x00\x00\x0aIDAT\x78\x5e\x63\x62\x00\x00\x00\x06\x00\x03\xa0\x06\x57\x66"
iend = "\x00\x00\x00\x00IEND\xae\x42\x60\x82"
)
for i := 0; i < 4; i++ {
var b []byte
b = append(b, pngHeader...)
b = append(b, ihdr...)
b = append(b, plte...)
for j := 0; j < i; j++ {
b = append(b, trns...)
}
b = append(b, idat...)
b = append(b, iend...)
var want color.Color
m, err := Decode(bytes.NewReader(b))
switch i {
case 0:
if err != nil {
t.Errorf("%d tRNS chunks: %v", i, err)
continue
}
want = color.RGBA{0xff, 0x00, 0x00, 0xff}
case 1:
if err != nil {
t.Errorf("%d tRNS chunks: %v", i, err)
continue
}
want = color.NRGBA{0xff, 0x00, 0x00, 0x7f}
default:
if err == nil {
t.Errorf("%d tRNS chunks: got nil error, want non-nil", i)
}
continue
}
if got := m.At(0, 0); got != want {
t.Errorf("%d tRNS chunks: got %T %v, want %T %v", i, got, got, want, want)
}
}
}
func TestUnknownChunkLengthUnderflow(t *testing.T) {
data := []byte{0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0xff, 0xff,
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x06, 0xf4, 0x7c, 0x55, 0x04, 0x1a,
0xd3, 0x11, 0x9a, 0x73, 0x00, 0x00, 0xf8, 0x1e, 0xf3, 0x2e, 0x00, 0x00,
0x01, 0x00, 0xff, 0xff, 0xff, 0xff, 0x07, 0xf4, 0x7c, 0x55, 0x04, 0x1a,
0xd3}
_, err := Decode(bytes.NewReader(data))
if err == nil {
t.Errorf("Didn't fail reading an unknown chunk with length 0xffffffff")
}
}
func TestOutOfPalettePixel(t *testing.T) {
// IDAT contains a reference to a palette index that does not exist in the file.
data := []byte{
// png header
0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a,
// IHDR
0x00, 0x00, 0x00, 0x0d, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00,
0x00, 0x00, 0x01, 0x01, 0x03, 0x00, 0x00, 0x00, 0x25, 0xdb, 0x56, 0xca,
// PLTE
0x00, 0x00, 0x00, 0x03, 0x50, 0x4c, 0x54, 0x45, 0xff, 0x00, 0x00, 0x19, 0xe2,
0x09, 0x37,
// IDAT
0x00, 0x00, 0x00, 0x0a, 0x49, 0x44, 0x41, 0x54, 0x78, 0x5e, 0x63, 0x6a, 0x00,
0x00, 0x00, 0x86, 0x00, 0x83, 0x9f, 0x64, 0x81, 0xa1,
// IEND
0x00, 0x00, 0x00, 0x00, 0x49, 0x45, 0x4e, 0x44, 0xae, 0x42, 0x60, 0x82,
}
img, err := Decode(bytes.NewReader(data))
if err != nil {
t.Errorf("decoding invalid palette png: unexpected error %v", err)
return
}
// Expect that the palette is extended with opaque black.
want := color.RGBA{0x00, 0x00, 0x00, 0xff}
if got := img.At(0, 0); got != want {
t.Errorf("got %T %v, expected %T %v", got, got, want, want)
}
}
func BenchmarkDecode(b *testing.B) {
data, err := ioutil.ReadFile("testdata/benchBW.png")
if err != nil {
b.Fatal(err)
}
cfg, err := DecodeConfig(bytes.NewReader(data))
if err != nil {
b.Fatal(err)
}
b.SetBytes(int64(cfg.Width * cfg.Height / 8))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
Decode(bytes.NewReader(data))
}
}
func BenchmarkDecodeStock(b *testing.B) {
data, err := ioutil.ReadFile("testdata/benchBW.png")
if err != nil {
b.Fatal(err)
}
cfg, err := DecodeConfig(bytes.NewReader(data))
if err != nil {
b.Fatal(err)
}
b.SetBytes(int64(cfg.Width * cfg.Height))
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
gopng.Decode(bytes.NewReader(data))
}
}
<file_sep>/go.mod
module github.com/mi-v/img1b
go 1.15
<file_sep>/image_test.go
// Copyright 2011 The Go Authors. All rights reserved.
// Copyright 2020 <NAME>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package img1b
import (
"image"
"image/color"
"testing"
)
func cmp(cm color.Model, c0, c1 color.Color) bool {
r0, g0, b0, a0 := cm.Convert(c0).RGBA()
r1, g1, b1, a1 := cm.Convert(c1).RGBA()
return r0 == r1 && g0 == g1 && b0 == b1 && a0 == a1
}
func TestImage(t *testing.T) {
m := New(image.Rect(0, 0, 14, 14), color.Palette{
color.Transparent,
color.Opaque,
})
// Check for right initial conditions.
if !image.Rect(0, 0, 14, 14).Eq(m.Bounds()) {
t.Errorf("%T: want bounds %v, got %v", m, image.Rect(0, 0, 14, 14), m.Bounds())
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(7, 3)) {
t.Errorf("%T: at (7, 3), want a zero color, got %v", m, m.At(7, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(8, 3)) {
t.Errorf("%T: at (8, 3), want a zero color, got %v", m, m.At(8, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(9, 3)) {
t.Errorf("%T: at (9, 3), want a zero color, got %v", m, m.At(9, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(10, 3)) {
t.Errorf("%T: at (10, 3), want a zero color, got %v", m, m.At(10, 3))
return
}
// Check that SetColorIndex works both ways and does not spill into adjacent pixels.
m.SetColorIndex(8, 3, 1)
if !cmp(m.ColorModel(), color.Transparent, m.At(7, 3)) {
t.Errorf("%T: at (7, 3), want a zero color, got %v", m, m.At(7, 3))
return
}
if !cmp(m.ColorModel(), color.Opaque, m.At(8, 3)) {
t.Errorf("%T: at (8, 3), want a non-zero color, got %v", m, m.At(8, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(9, 3)) {
t.Errorf("%T: at (9, 3), want a zero color, got %v", m, m.At(9, 3))
return
}
m.SetColorIndex(9, 3, 1)
if !cmp(m.ColorModel(), color.Opaque, m.At(8, 3)) {
t.Errorf("%T: at (8, 3), want a non-zero color, got %v", m, m.At(8, 3))
return
}
if !cmp(m.ColorModel(), color.Opaque, m.At(9, 3)) {
t.Errorf("%T: at (9, 3), want a non-zero color, got %v", m, m.At(9, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(10, 3)) {
t.Errorf("%T: at (10, 3), want a zero color, got %v", m, m.At(10, 3))
return
}
m.SetColorIndex(9, 3, 0)
if !cmp(m.ColorModel(), color.Opaque, m.At(8, 3)) {
t.Errorf("%T: at (8, 3), want a non-zero color, got %v", m, m.At(8, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(9, 3)) {
t.Errorf("%T: at (9, 3), want a zero color, got %v", m, m.At(9, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(10, 3)) {
t.Errorf("%T: at (10, 3), want a zero color, got %v", m, m.At(10, 3))
return
}
// SubImage tests.
m.SetColorIndex(8, 3, 1)
if !m.SubImage(image.Rect(8, 3, 9, 4)).Opaque() {
t.Errorf("%T: at (8, 3) was not opaque", m)
return
}
m = m.SubImage(image.Rect(8, 2, 13, 8))
if !image.Rect(8, 2, 13, 8).Eq(m.Bounds()) {
t.Errorf("%T: sub-image want bounds %v, got %v", m, image.Rect(8, 2, 13, 8), m.Bounds())
return
}
if !cmp(m.ColorModel(), color.Opaque, m.At(8, 3)) {
t.Errorf("%T: sub-image at (8, 3), want a non-zero color, got %v", m, m.At(8, 3))
return
}
if !cmp(m.ColorModel(), color.Transparent, m.At(8, 4)) {
t.Errorf("%T: sub-image at (8, 4), want a zero color, got %v", m, m.At(8, 4))
return
}
m.SetColorIndex(8, 4, 1)
if !cmp(m.ColorModel(), color.Opaque, m.At(8, 4)) {
t.Errorf("%T: sub-image at (8, 4), want a non-zero color, got %v", m, m.At(8, 4))
return
}
// Test that taking an empty sub-image starting at a corner does not panic.
m.SubImage(image.Rect(0, 0, 0, 0))
m.SubImage(image.Rect(14, 0, 14, 0))
m.SubImage(image.Rect(0, 10, 0, 14))
m.SubImage(image.Rect(14, 10, 14, 14))
}
func TestNewBadRectangle(t *testing.T) {
// call calls f(r) and reports whether it ran without panicking.
call := func(f func(image.Rectangle), r image.Rectangle) (ok bool) {
defer func() {
if recover() != nil {
ok = false
}
}()
f(r)
return true
}
// Calling New(r) should fail (panic, since New doesn't return an error)
// unless r's width and height are both non-negative.
f := func(r image.Rectangle) { New(r, color.Palette{color.Black, color.White}) }
for _, negDx := range []bool{false, true} {
for _, negDy := range []bool{false, true} {
r := image.Rectangle{
Min: image.Point{15, 28},
Max: image.Point{16, 29},
}
if negDx {
r.Max.X = 14
}
if negDy {
r.Max.Y = 27
}
got := call(f, r)
want := !negDx && !negDy
if got != want {
t.Errorf("New: negDx=%t, negDy=%t: got %t, want %t",
negDx, negDy, got, want)
}
}
}
// Passing a Rectangle whose width and height is MaxInt should also fail
// (panic), due to overflow.
{
zeroAsUint := uint(0)
maxUint := zeroAsUint - 1
maxInt := int(maxUint / 2)
got := call(f, image.Rectangle{
Min: image.Point{0, 0},
Max: image.Point{maxInt, maxInt},
})
if got {
t.Error("New: overflow: got ok, want !ok")
}
}
}
func TestSubimageBadRectangle(t *testing.T) {
// call calls f(r) and reports whether it ran without panicking.
call := func(f func(image.Rectangle), r image.Rectangle) (ok bool) {
defer func() {
if recover() != nil {
ok = false
}
}()
f(r)
return true
}
m := New(image.Rect(0, 0, 14, 14), color.Palette{
color.Transparent,
color.Opaque,
})
// Calling SubImage(r) should fail (panic, since SubImage doesn't return
// an error) unless r.Min.X is byte aligned.
f := func(r image.Rectangle) { m.SubImage(r) }
{
r := image.Rectangle{
Min: image.Point{8, 3},
Max: image.Point{12, 6},
}
got := call(f, r)
want := true
if got != want {
t.Errorf("SubImage: r=%v: got %t, want %t",
r, got, want)
}
}
{
r := image.Rectangle{
Min: image.Point{9, 3},
Max: image.Point{12, 6},
}
got := call(f, r)
want := false
if got != want {
t.Errorf("SubImage: r=%v: got %t, want %t",
r, got, want)
}
}
}
func BenchmarkAt(b *testing.B) {
m := New(image.Rect(0, 0, 10, 10), color.Palette{
color.Transparent,
color.Opaque,
})
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
m.At(4, 5)
}
}
func BenchmarkSet(b *testing.B) {
m := New(image.Rect(0, 0, 10, 10), color.Palette{
color.Transparent,
color.Opaque,
})
b.ReportAllocs()
b.ResetTimer()
for i := 0; i < b.N; i++ {
m.SetColorIndex(4, 5, 1)
}
}
<file_sep>/png/writer.go
// Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2020 <NAME>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package png
import (
"bufio"
"compress/zlib"
"encoding/binary"
"github.com/mi-v/img1b"
"hash/crc32"
"image/color"
"io"
"strconv"
)
// Encoder configures encoding PNG images.
type Encoder struct {
CompressionLevel CompressionLevel
// BufferPool optionally specifies a buffer pool to get temporary
// EncoderBuffers when encoding an image.
BufferPool EncoderBufferPool
}
// EncoderBufferPool is an interface for getting and returning temporary
// instances of the EncoderBuffer struct. This can be used to reuse buffers
// when encoding multiple images.
type EncoderBufferPool interface {
Get() *EncoderBuffer
Put(*EncoderBuffer)
}
// EncoderBuffer holds the buffers used for encoding PNG images.
type EncoderBuffer encoder
type encoder struct {
enc *Encoder
w io.Writer
m *img1b.Image
cb int
err error
header [8]byte
footer [4]byte
tmp [4 * 256]byte
cr []byte
zw *zlib.Writer
zwLevel int
bw *bufio.Writer
}
type CompressionLevel int
const (
DefaultCompression CompressionLevel = 0
NoCompression CompressionLevel = -1
BestSpeed CompressionLevel = -2
BestCompression CompressionLevel = -3
// Positive CompressionLevel values are reserved to mean a numeric zlib
// compression level, although that is not implemented yet.
)
func (e *encoder) writeChunk(b []byte, name string) {
if e.err != nil {
return
}
n := uint32(len(b))
if int(n) != len(b) {
e.err = UnsupportedError(name + " chunk is too large: " + strconv.Itoa(len(b)))
return
}
binary.BigEndian.PutUint32(e.header[:4], n)
e.header[4] = name[0]
e.header[5] = name[1]
e.header[6] = name[2]
e.header[7] = name[3]
crc := crc32.NewIEEE()
crc.Write(e.header[4:8])
crc.Write(b)
binary.BigEndian.PutUint32(e.footer[:4], crc.Sum32())
_, e.err = e.w.Write(e.header[:8])
if e.err != nil {
return
}
_, e.err = e.w.Write(b)
if e.err != nil {
return
}
_, e.err = e.w.Write(e.footer[:4])
}
func (e *encoder) writeIHDR() {
b := e.m.Bounds()
binary.BigEndian.PutUint32(e.tmp[0:4], uint32(b.Dx()))
binary.BigEndian.PutUint32(e.tmp[4:8], uint32(b.Dy()))
// Set bit depth and color type.
switch e.cb {
case cbG1:
e.tmp[8] = 1
e.tmp[9] = ctGrayscale
case cbP1:
e.tmp[8] = 1
e.tmp[9] = ctPaletted
}
e.tmp[10] = 0 // default compression method
e.tmp[11] = 0 // default filter method
e.tmp[12] = 0 // non-interlaced
e.writeChunk(e.tmp[:13], "IHDR")
}
func (e *encoder) writePLTEAndTRNS(p color.Palette) {
if len(p) < 1 || len(p) > 2 {
e.err = FormatError("bad palette length: " + strconv.Itoa(len(p)))
return
}
last := -1
for i, c := range p {
c1 := color.NRGBAModel.Convert(c).(color.NRGBA)
e.tmp[3*i+0] = c1.R
e.tmp[3*i+1] = c1.G
e.tmp[3*i+2] = c1.B
if c1.A != 0xff {
last = i
}
e.tmp[3*256+i] = c1.A
}
e.writeChunk(e.tmp[:3*len(p)], "PLTE")
if last != -1 {
e.writeChunk(e.tmp[3*256:3*256+1+last], "tRNS")
}
}
// An encoder is an io.Writer that satisfies writes by writing PNG IDAT chunks,
// including an 8-byte header and 4-byte CRC checksum per Write call. Such calls
// should be relatively infrequent, since writeIDATs uses a bufio.Writer.
//
// This method should only be called from writeIDATs (via writeImage).
// No other code should treat an encoder as an io.Writer.
func (e *encoder) Write(b []byte) (int, error) {
e.writeChunk(b, "IDAT")
if e.err != nil {
return 0, e.err
}
return len(b), nil
}
func (e *encoder) writeImage(w io.Writer, m *img1b.Image, cb int, level int) error {
if e.zw == nil || e.zwLevel != level {
zw, err := zlib.NewWriterLevel(w, level)
if err != nil {
return err
}
e.zw = zw
e.zwLevel = level
} else {
e.zw.Reset(w)
}
defer e.zw.Close()
b := m.Bounds()
sz := 1 + (b.Dx()+7)/8
if cap(e.cr) < sz {
e.cr = make([]byte, sz)
} else {
e.cr = e.cr[:sz]
}
cr := e.cr
// Mask to blank out of bounds bits.
tm := byte(uint16(0xff00) >> ((b.Dx()-1)%8 + 1))
lb := tm &^ (tm << 1)
for y := b.Min.Y; y < b.Max.Y; y++ {
offset := (y - b.Min.Y) * m.Stride
copy(cr[1:], m.Pix[offset:offset+(b.Dx()+7)/8])
// Extend the row last pixel till the end of the byte.
// It seems to result in slightly better compression than just zeroing.
if cr[sz-1]&lb == 0 {
cr[sz-1] &= tm
} else {
cr[sz-1] |= ^tm
}
// Write the compressed bytes.
if _, err := e.zw.Write(cr); err != nil {
return err
}
}
return nil
}
// Write the actual image data to one or more IDAT chunks.
func (e *encoder) writeIDATs() {
if e.err != nil {
return
}
if e.bw == nil {
e.bw = bufio.NewWriterSize(e, 1<<15)
} else {
e.bw.Reset(e)
}
e.err = e.writeImage(e.bw, e.m, e.cb, levelToZlib(e.enc.CompressionLevel))
if e.err != nil {
return
}
e.err = e.bw.Flush()
}
// This function is required because we want the zero value of
// Encoder.CompressionLevel to map to zlib.DefaultCompression.
func levelToZlib(l CompressionLevel) int {
switch l {
case DefaultCompression:
return zlib.DefaultCompression
case NoCompression:
return zlib.NoCompression
case BestSpeed:
return zlib.BestSpeed
case BestCompression:
return zlib.BestCompression
default:
return zlib.DefaultCompression
}
}
func (e *encoder) writeIEND() { e.writeChunk(nil, "IEND") }
func isBlackWhite(pal color.Palette) bool {
return len(pal) > 1 &&
color.RGBAModel.Convert(pal[0]) == color.RGBAModel.Convert(color.Black) &&
color.RGBAModel.Convert(pal[1]) == color.RGBAModel.Convert(color.White)
}
// Encode writes the Image m to w in PNG format.
func Encode(w io.Writer, m *img1b.Image) error {
var e Encoder
return e.Encode(w, m)
}
// Encode writes the Image m to w in PNG format.
func (enc *Encoder) Encode(w io.Writer, m *img1b.Image) error {
// Obviously, negative widths and heights are invalid. Furthermore, the PNG
// spec section 11.2.2 says that zero is invalid. Excessively large images are
// also rejected.
mw, mh := int64(m.Bounds().Dx()), int64(m.Bounds().Dy())
if mw <= 0 || mh <= 0 || mw >= 1<<32 || mh >= 1<<32 {
return FormatError("invalid image size: " + strconv.FormatInt(mw, 10) + "x" + strconv.FormatInt(mh, 10))
}
var e *encoder
if enc.BufferPool != nil {
buffer := enc.BufferPool.Get()
e = (*encoder)(buffer)
}
if e == nil {
e = &encoder{}
}
if enc.BufferPool != nil {
defer enc.BufferPool.Put((*EncoderBuffer)(e))
}
e.enc = enc
e.w = w
e.m = m
e.cb = cbP1
pal := m.Palette
if isBlackWhite(pal) {
e.cb = cbG1
pal = nil
}
_, e.err = io.WriteString(w, pngHeader)
e.writeIHDR()
if pal != nil {
e.writePLTEAndTRNS(pal)
}
e.writeIDATs()
e.writeIEND()
return e.err
}
<file_sep>/README.md
# img1b
Package img1b is a fork of the standard Go image package modified for 1-bit images.
Images are kept packed so they take up to 8 times less memory and may be processed
faster.
It provides an Image type that is in most aspects very similar to image.Paletted with
palette limited to two colors.
img1b.Image implements image.PalettedImage and can be encoded with image/png and
probably other encoders but that is not very efficient due to all the bit shuffling
involved. Subpackage img1b/png is a modified png codec that processes whole rows
which is several times faster.
<file_sep>/image.go
// Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2020 <NAME>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package img1b is a fork of the standard Go image package modified for 1-bit images.
// Images are kept packed so they take up to 8 times less memory and may be processed
// faster.
//
// There is currently no img1b.Decode. To read a PNG file use Decode from img1b/png.
package img1b
import (
"bytes"
"image"
"image/color"
"math/bits"
)
// Image implements the image.PalettedImage interface and is mostly analogous to
// image.Paletted except that Pix is a bitmap, so only color indices 0 and 1 can be used.
type Image struct {
// Pix is a bitmap of image pixels. Bytes represent up to 8 horizontally adjacent
// pixels (there may be unused bits in the last byte of a row) with the most
// significant bit corresponding to leftmost pixel.
Pix []byte
// Stride is the Pix stride (in bytes) between vertically adjacent pixels.
Stride int
// Rect is the image's bounds.
Rect image.Rectangle
// Palette is the image's palette.
Palette color.Palette
}
// At returns the color of the pixel at (x, y).
func (p *Image) At(x, y int) color.Color {
if len(p.Palette) == 0 {
return nil
}
if !(image.Point{x, y}.In(p.Rect)) {
return p.Palette[0]
}
i, b := p.PixBitOffset(x, y)
return p.Palette[(p.Pix[i]>>b)&1]
}
// PixBitOffset returns the index of the byte of Pix that corresponds to
// the pixel at (x, y) and bit offset (7 for MSB) in that byte.
func (p *Image) PixBitOffset(x, y int) (ofs, bit int) {
ofs = (y-p.Rect.Min.Y)*p.Stride + (x-p.Rect.Min.X)/8
bit = 7 - (x-p.Rect.Min.X)%8
return
}
// Bounds returns the domain for which At can return non-zero color.
// The bounds do not necessarily contain the point (0, 0).
func (p *Image) Bounds() image.Rectangle { return p.Rect }
// ColorModel returns the Image's color model.
func (p *Image) ColorModel() color.Model { return p.Palette }
// ColorIndexAt returns the palette index of the pixel at (x, y).
func (p *Image) ColorIndexAt(x, y int) uint8 {
if !(image.Point{x, y}.In(p.Rect)) {
return 0
}
i, b := p.PixBitOffset(x, y)
return (p.Pix[i] >> b) & 1
}
// SetColorIndex sets color index for the pixel at (x, y). Index should be 0 or 1.
func (p *Image) SetColorIndex(x, y int, index uint8) {
if !(image.Point{x, y}.In(p.Rect)) {
return
}
i, b := p.PixBitOffset(x, y)
if index == 0 {
p.Pix[i] &^= 1 << b
} else {
p.Pix[i] |= 1 << b
}
}
// mul2NonNeg returns (x * y), unless at least one argument is negative or
// if the computation overflows the int type, in which case it returns -1.
func mul2NonNeg(x int, y int) int {
if (x < 0) || (y < 0) {
return -1
}
hi, lo := bits.Mul64(uint64(x), uint64(y))
if hi != 0 {
return -1
}
a := int(lo)
if (a < 0) || (uint64(a) != lo) {
return -1
}
return a
}
// New returns a new Image with given dimensions and palette.
func New(r image.Rectangle, p color.Palette) *Image {
w, h := r.Dx(), r.Dy()
stride := (w + 7) / 8
bytes := mul2NonNeg(h, stride)
if w < 0 || bytes < 0 {
panic("img1b.New: Rectangle has huge or negative dimensions")
}
pix := make([]byte, bytes)
return &Image{pix, stride, r, p}
}
// SubImage returns an image representing the portion of the image p visible
// through r. The returned value shares pixels with the original image. Left edge
// has to be byte aligned.
func (p *Image) SubImage(r image.Rectangle) *Image {
r = r.Intersect(p.Rect)
// If r1 and r2 are Rectangles, r1.Intersect(r2) is not guaranteed to be inside
// either r1 or r2 if the intersection is empty. Without explicitly checking for
// this, the Pix[i:] expression below can panic.
if r.Empty() {
return &Image{
Palette: p.Palette,
}
}
i, b := p.PixBitOffset(r.Min.X, r.Min.Y)
if b != 7 {
panic("img1b.SubImage: left edge is not byte aligned")
}
return &Image{
Pix: p.Pix[i:],
Stride: p.Stride,
Rect: r,
Palette: p.Palette,
}
}
// Opaque scans the entire image and reports whether it is fully opaque.
func (p *Image) Opaque() bool {
ts := 0 // transparent indices+1 sum
for i, c := range p.Palette {
if i > 1 {
// skip inaccessible colors
break
}
_, _, _, a := c.RGBA()
if a != 0xffff {
ts += i + 1
}
}
var ob byte // opaque byte
switch ts {
case 0:
return true // no transparent colors
case 1:
ob = 0xff
case 2:
ob = 0
case 3:
return false // both colors are transparent
}
i0, i1 := 0, p.Rect.Dx()/8 // whole byte indices
bc := i1 - i0
tm := byte(0xff) << (8 - p.Rect.Dx()%8) // tail mask
for y := p.Rect.Min.Y; y < p.Rect.Max.Y; y++ {
if bytes.Count(p.Pix[i0:i1], []byte{ob}) != bc {
return false
}
if tm != 0 && p.Pix[i1]&tm != ob&tm {
return false
}
i0 += p.Stride
i1 += p.Stride
}
return true
}
<file_sep>/png/reader.go
// Copyright 2009 The Go Authors. All rights reserved.
// Copyright 2020 <NAME>
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package png implements a PNG image decoder and encoder. Only 1-bit images can
// be decoded (grayscale or paletted).
//
// The PNG specification is at https://www.w3.org/TR/PNG/.
package png
import (
"compress/zlib"
"encoding/binary"
"fmt"
"github.com/mi-v/img1b"
"hash"
"hash/crc32"
"image"
"image/color"
"io"
)
// Color type, as per the PNG spec.
const (
ctGrayscale = 0
ctTrueColor = 2
ctPaletted = 3
ctGrayscaleAlpha = 4
ctTrueColorAlpha = 6
)
// A cb is a combination of color type and bit depth.
const (
cbInvalid = iota
cbG1
cbG2
cbG4
cbG8
cbGA8
cbTC8
cbP1
cbP2
cbP4
cbP8
cbTCA8
cbG16
cbGA16
cbTC16
cbTCA16
)
func cbPaletted(cb int) bool {
return cbP1 <= cb && cb <= cbP8
}
// Filter type, as per the PNG spec.
const (
ftNone = 0
ftSub = 1
ftUp = 2
ftAverage = 3
ftPaeth = 4
nFilter = 5
)
// Interlace type.
const (
itNone = 0
itAdam7 = 1
)
// interlaceScan defines the placement and size of a pass for Adam7 interlacing.
type interlaceScan struct {
xFactor, yFactor, xOffset, yOffset int
}
// interlacing defines Adam7 interlacing, with 7 passes of reduced images.
// See https://www.w3.org/TR/PNG/#8Interlace
var interlacing = []interlaceScan{
{8, 8, 0, 0},
{8, 8, 4, 0},
{4, 8, 0, 4},
{4, 4, 2, 0},
{2, 4, 0, 2},
{2, 2, 1, 0},
{1, 2, 0, 1},
}
// Decoding stage.
// The PNG specification says that the IHDR, PLTE (if present), tRNS (if
// present), IDAT and IEND chunks must appear in that order. There may be
// multiple IDAT chunks, and IDAT chunks must be sequential (i.e. they may not
// have any other chunks between them).
// https://www.w3.org/TR/PNG/#5ChunkOrdering
const (
dsStart = iota
dsSeenIHDR
dsSeenPLTE
dsSeentRNS
dsSeenIDAT
dsSeenIEND
)
const pngHeader = "\x89PNG\r\n\x1a\n"
type decoder struct {
r io.Reader
img *img1b.Image
crc hash.Hash32
width, height int
depth int
palette color.Palette
cb int
stage int
idatLength uint32
tmp [3 * 256]byte
interlace int
}
// A FormatError reports that the input is not a valid PNG.
type FormatError string
func (e FormatError) Error() string { return "png: invalid format: " + string(e) }
var chunkOrderError = FormatError("chunk out of order")
// An UnsupportedError reports that the input uses a valid but unimplemented PNG feature.
type UnsupportedError string
func (e UnsupportedError) Error() string { return "png: unsupported feature: " + string(e) }
func min(a, b int) int {
if a < b {
return a
}
return b
}
func (d *decoder) parseIHDR(length uint32) error {
if length != 13 {
return FormatError("bad IHDR length")
}
if _, err := io.ReadFull(d.r, d.tmp[:13]); err != nil {
return err
}
d.crc.Write(d.tmp[:13])
if d.tmp[10] != 0 {
return UnsupportedError("compression method")
}
if d.tmp[11] != 0 {
return UnsupportedError("filter method")
}
if d.tmp[12] != itNone && d.tmp[12] != itAdam7 {
return FormatError("invalid interlace method")
}
d.interlace = int(d.tmp[12])
w := int32(binary.BigEndian.Uint32(d.tmp[0:4]))
h := int32(binary.BigEndian.Uint32(d.tmp[4:8]))
if w <= 0 || h <= 0 {
return FormatError("non-positive dimension")
}
nPixels := int64(w) * int64(h)
if nPixels != int64(int(nPixels)) {
return UnsupportedError("dimension overflow")
}
d.cb = cbInvalid
d.depth = int(d.tmp[8])
if d.depth == 1 {
switch d.tmp[9] {
case ctGrayscale:
d.cb = cbG1
case ctPaletted:
d.cb = cbP1
}
}
if d.cb == cbInvalid {
return UnsupportedError(fmt.Sprintf("bit depth %d, color type %d", d.tmp[8], d.tmp[9]))
}
d.width, d.height = int(w), int(h)
return d.verifyChecksum()
}
func (d *decoder) parsePLTE(length uint32) error {
np := int(length / 3) // The number of palette entries.
if length%3 != 0 || np < 1 || np > 2 {
return FormatError("bad PLTE length")
}
n, err := io.ReadFull(d.r, d.tmp[:3*np])
if err != nil {
return err
}
d.crc.Write(d.tmp[:n])
if d.cb != cbP1 {
return FormatError("PLTE, color type mismatch")
}
d.palette[0] = color.RGBA{d.tmp[0], d.tmp[1], d.tmp[2], 0xff}
if np == 2 {
d.palette[1] = color.RGBA{d.tmp[3], d.tmp[4], d.tmp[5], 0xff}
} else {
d.palette[1] = color.RGBA{0x00, 0x00, 0x00, 0xff}
}
return d.verifyChecksum()
}
func (d *decoder) parsetRNS(length uint32) error {
switch d.cb {
case cbG1:
if length != 2 {
return FormatError("bad tRNS length")
}
n, err := io.ReadFull(d.r, d.tmp[:length])
if err != nil {
return err
}
d.crc.Write(d.tmp[:n])
rgba := d.palette[d.tmp[1]&1].(color.RGBA)
d.palette[d.tmp[1]&1] = color.NRGBA{rgba.R, rgba.G, rgba.B, 0}
case cbP1:
if length > 2 {
return FormatError("bad tRNS length")
}
n, err := io.ReadFull(d.r, d.tmp[:length])
if err != nil {
return err
}
d.crc.Write(d.tmp[:n])
if len(d.palette) < n {
d.palette = d.palette[:n]
}
for i := 0; i < n; i++ {
rgba := d.palette[i].(color.RGBA)
d.palette[i] = color.NRGBA{rgba.R, rgba.G, rgba.B, d.tmp[i]}
}
default:
return FormatError("tRNS, color type mismatch")
}
return d.verifyChecksum()
}
// Read presents one or more IDAT chunks as one continuous stream (minus the
// intermediate chunk headers and footers). If the PNG data looked like:
// ... len0 IDAT xxx crc0 len1 IDAT yy crc1 len2 IEND crc2
// then this reader presents xxxyy. For well-formed PNG data, the decoder state
// immediately before the first Read call is that d.r is positioned between the
// first IDAT and xxx, and the decoder state immediately after the last Read
// call is that d.r is positioned between yy and crc1.
func (d *decoder) Read(p []byte) (int, error) {
if len(p) == 0 {
return 0, nil
}
for d.idatLength == 0 {
// We have exhausted an IDAT chunk. Verify the checksum of that chunk.
if err := d.verifyChecksum(); err != nil {
return 0, err
}
// Read the length and chunk type of the next chunk, and check that
// it is an IDAT chunk.
if _, err := io.ReadFull(d.r, d.tmp[:8]); err != nil {
return 0, err
}
d.idatLength = binary.BigEndian.Uint32(d.tmp[:4])
if string(d.tmp[4:8]) != "IDAT" {
return 0, FormatError("not enough pixel data")
}
d.crc.Reset()
d.crc.Write(d.tmp[4:8])
}
if int(d.idatLength) < 0 {
return 0, UnsupportedError("IDAT chunk length overflow")
}
n, err := d.r.Read(p[:min(len(p), int(d.idatLength))])
d.crc.Write(p[:n])
d.idatLength -= uint32(n)
return n, err
}
// decode decodes the IDAT data into an image.
func (d *decoder) decode() (*img1b.Image, error) {
r, err := zlib.NewReader(d)
if err != nil {
return nil, err
}
defer r.Close()
var img *img1b.Image
if d.interlace == itNone {
img, err = d.readImagePass(r, 0, false)
if err != nil {
return nil, err
}
} else if d.interlace == itAdam7 {
// Allocate a blank image of the full size.
img, err = d.readImagePass(nil, 0, true)
if err != nil {
return nil, err
}
for pass := 0; pass < 7; pass++ {
imagePass, err := d.readImagePass(r, pass, false)
if err != nil {
return nil, err
}
if imagePass != nil {
d.mergePassInto(img, imagePass, pass)
}
}
}
// Check for EOF, to verify the zlib checksum.
n := 0
for i := 0; n == 0 && err == nil; i++ {
if i == 100 {
return nil, io.ErrNoProgress
}
n, err = r.Read(d.tmp[:1])
}
if err != nil && err != io.EOF {
return nil, FormatError(err.Error())
}
if n != 0 || d.idatLength != 0 {
return nil, FormatError("too much pixel data")
}
return img, nil
}
// readImagePass reads a single image pass, sized according to the pass number.
func (d *decoder) readImagePass(r io.Reader, pass int, allocateOnly bool) (*img1b.Image, error) {
pixOffset := 0
var img *img1b.Image
width, height := d.width, d.height
if d.interlace == itAdam7 && !allocateOnly {
p := interlacing[pass]
// Add the multiplication factor and subtract one, effectively rounding up.
width = (width - p.xOffset + p.xFactor - 1) / p.xFactor
height = (height - p.yOffset + p.yFactor - 1) / p.yFactor
// A PNG image can't have zero width or height, but for an interlaced
// image, an individual pass might have zero width or height. If so, we
// shouldn't even read a per-row filter type byte, so return early.
if width == 0 || height == 0 {
return nil, nil
}
}
img = img1b.New(image.Rect(0, 0, width, height), d.palette)
if allocateOnly {
return img, nil
}
// The +1 is for the per-row filter type, which is at cr[0].
rowSize := 1 + (width+7)/8
// cr and pr are the bytes for the current and previous row.
cr := make([]uint8, rowSize)
pr := make([]uint8, rowSize)
for y := 0; y < height; y++ {
// Read the decompressed bytes.
_, err := io.ReadFull(r, cr)
if err != nil {
if err == io.EOF || err == io.ErrUnexpectedEOF {
return nil, FormatError("not enough pixel data")
}
return nil, err
}
// Apply the filter.
cdat := cr[1:]
pdat := pr[1:]
switch cr[0] {
case ftNone:
// No-op.
case ftSub:
for i := 1; i < len(cdat); i++ {
cdat[i] += cdat[i-1]
}
case ftUp:
for i, p := range pdat {
cdat[i] += p
}
case ftAverage:
// The first column has no column to the left of it, so it is a
// special case. We know that the first column exists because we
// check above that width != 0, and so len(cdat) != 0.
cdat[0] += pdat[0] / 2
for i := 1; i < len(cdat); i++ {
cdat[i] += uint8((int(cdat[i-1]) + int(pdat[i])) / 2)
}
case ftPaeth:
filterPaeth(cdat, pdat, 1)
default:
return nil, FormatError("bad filter type")
}
copy(img.Pix[pixOffset:], cdat)
pixOffset += img.Stride
// The current row for y is the previous row for y+1.
pr, cr = cr, pr
}
return img, nil
}
// mergePassInto merges a single pass into a full sized image.
func (d *decoder) mergePassInto(dst *img1b.Image, src *img1b.Image, pass int) {
p := interlacing[pass]
var (
rect image.Rectangle
)
rect = dst.Rect
bounds := src.Bounds()
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
dstY := y*p.yFactor + p.yOffset - rect.Min.Y
for x := bounds.Min.X; x < bounds.Max.X; x++ {
dstX := x*p.xFactor + p.xOffset - rect.Min.X
dst.SetColorIndex(dstX, dstY, src.ColorIndexAt(x, y))
}
}
}
func (d *decoder) parseIDAT(length uint32) (err error) {
d.idatLength = length
d.img, err = d.decode()
if err != nil {
return err
}
return d.verifyChecksum()
}
func (d *decoder) parseIEND(length uint32) error {
if length != 0 {
return FormatError("bad IEND length")
}
return d.verifyChecksum()
}
func (d *decoder) parseChunk() error {
// Read the length and chunk type.
_, err := io.ReadFull(d.r, d.tmp[:8])
if err != nil {
return err
}
length := binary.BigEndian.Uint32(d.tmp[:4])
d.crc.Reset()
d.crc.Write(d.tmp[4:8])
// Read the chunk data.
switch string(d.tmp[4:8]) {
case "IHDR":
if d.stage != dsStart {
return chunkOrderError
}
d.stage = dsSeenIHDR
return d.parseIHDR(length)
case "PLTE":
if d.stage != dsSeenIHDR {
return chunkOrderError
}
d.stage = dsSeenPLTE
return d.parsePLTE(length)
case "tRNS":
if cbPaletted(d.cb) {
if d.stage != dsSeenPLTE {
return chunkOrderError
}
} else if d.stage != dsSeenIHDR {
return chunkOrderError
}
d.stage = dsSeentRNS
return d.parsetRNS(length)
case "IDAT":
if d.stage < dsSeenIHDR || d.stage > dsSeenIDAT || (d.stage == dsSeenIHDR && cbPaletted(d.cb)) {
return chunkOrderError
} else if d.stage == dsSeenIDAT {
// Ignore trailing zero-length or garbage IDAT chunks.
//
// This does not affect valid PNG images that contain multiple IDAT
// chunks, since the first call to parseIDAT below will consume all
// consecutive IDAT chunks required for decoding the image.
break
}
d.stage = dsSeenIDAT
return d.parseIDAT(length)
case "IEND":
if d.stage != dsSeenIDAT {
return chunkOrderError
}
d.stage = dsSeenIEND
return d.parseIEND(length)
}
if length > 0x7fffffff {
return FormatError(fmt.Sprintf("Bad chunk length: %d", length))
}
// Ignore this chunk (of a known length).
var ignored [4096]byte
for length > 0 {
n, err := io.ReadFull(d.r, ignored[:min(len(ignored), int(length))])
if err != nil {
return err
}
d.crc.Write(ignored[:n])
length -= uint32(n)
}
return d.verifyChecksum()
}
func (d *decoder) verifyChecksum() error {
if _, err := io.ReadFull(d.r, d.tmp[:4]); err != nil {
return err
}
if binary.BigEndian.Uint32(d.tmp[:4]) != d.crc.Sum32() {
return FormatError("invalid checksum")
}
return nil
}
func (d *decoder) checkHeader() error {
_, err := io.ReadFull(d.r, d.tmp[:len(pngHeader)])
if err != nil {
return err
}
if string(d.tmp[:len(pngHeader)]) != pngHeader {
return FormatError("not a PNG file")
}
return nil
}
// Decode reads a PNG image from r and returns it as an img1b.Image.
func Decode(r io.Reader) (*img1b.Image, error) {
d := &decoder{
r: r,
crc: crc32.NewIEEE(),
palette: color.Palette{
color.RGBAModel.Convert(color.Black),
color.RGBAModel.Convert(color.White),
},
}
if err := d.checkHeader(); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
for d.stage != dsSeenIEND {
if err := d.parseChunk(); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return nil, err
}
}
return d.img, nil
}
// DecodeConfig returns the color model and dimensions of a PNG image without
// decoding the entire image.
func DecodeConfig(r io.Reader) (image.Config, error) {
d := &decoder{
r: r,
crc: crc32.NewIEEE(),
palette: color.Palette{
color.RGBAModel.Convert(color.Black),
color.RGBAModel.Convert(color.White),
},
}
if err := d.checkHeader(); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return image.Config{}, err
}
for {
if err := d.parseChunk(); err != nil {
if err == io.EOF {
err = io.ErrUnexpectedEOF
}
return image.Config{}, err
}
paletted := cbPaletted(d.cb)
if d.stage == dsSeenIHDR && !paletted {
break
}
if d.stage == dsSeenPLTE && paletted {
break
}
}
return image.Config{
ColorModel: d.palette,
Width: d.width,
Height: d.height,
}, nil
}
|
6d68c52e62d23f29d19d2fb2dd238cc45d00709b
|
[
"Markdown",
"Go Module",
"Go"
] | 7 |
Go
|
mi-v/img1b
|
220dfd967c790a55cfb09b2f5fe44561687e502d
|
4a2562b597cf754a7640b10bf18147cb7ef55274
|
refs/heads/master
|
<file_sep>#include <pthread.h>
struct station {
int count,toset,set;
pthread_mutex_t trainWait;
pthread_cond_t trainArrive;
pthread_cond_t seated;
};
void station_init(struct station *station);
void station_load_train(struct station *station, int count);
void station_wait_for_train(struct station *station);
void station_on_board(struct station *station);
<file_sep>#include <pthread.h>
#include "caltrain.h"
/*
used to initialize station using station pointer.
*/
void station_init(struct station *station)
{
(*station).count=0;
pthread_mutex_init(&((*station).trainWait), NULL);
pthread_cond_init(&((*station).trainArrive), NULL);
pthread_cond_init(&((*station).seated), NULL);
}
/*
used when train arrives the station and calls out for passengers.
*/
void station_load_train(struct station *station, int count)
{
if (count ==0 || (*station).count==0)
return;
pthread_mutex_lock(&((*station).trainWait));
(*station).toset=(*station).set=(count <(*station).count ) ? count : (*station).count;
pthread_cond_broadcast(&((*station).trainArrive));
pthread_cond_wait(&((*station).seated), &((*station).trainWait));
pthread_mutex_unlock(&((*station).trainWait));
}
/*
used when a passengers arrives the station and waits a train.
*/
void station_wait_for_train(struct station *station)
{
pthread_mutex_lock(&((*station).trainWait));
(*station).count++;
while(1)
{
pthread_cond_wait(&((*station).trainArrive), &((*station).trainWait));
if((*station).count>0&&(*station).toset>0)
{
(*station).toset--;
(*station).count--;
break;
}
}
pthread_mutex_unlock(&((*station).trainWait));
}
/*
used to make sure that a passenger is in his seat just like air plans first class tickets.
*/
void station_on_board(struct station *station)
{
(*station).set--;
if((*station).set<=0)
{
pthread_cond_signal(&((*station).seated));
}
}
|
bb7c737ba11ef50a3c20aae03c55788b1b608e9e
|
[
"C"
] | 2 |
C
|
mohab567/caltrain-threads
|
187d0741d48aac014575333f7bdd2dae4648a1ce
|
658ce210a8f4060dd5a35f785794f1f0436735bf
|
refs/heads/master
|
<file_sep><?php
namespace Hellpers;
use Exception;
class Pather
{
/**
* @var array Массив запрещенных имен в ОС windows
*/
private static $antiNames = [
'CON',
'NUL',
'AUX',
'PRN',
'COM1',
'COM2',
'COM3',
'COM4',
'COM5',
'COM6',
'COM7',
'COM8',
'COM9',
'LPT1',
'LPT2',
'LPT3',
'LPT4',
'LPT5',
'LPT6',
'LPT7',
'LPT8',
'LPT9',
];
/**
* @var array Массив запрещенных символов в ОС windows
*/
private static $antiSymbols = [
'\\', ':', '*', '?', '"', '<', '>', '|'
];
/**
* Определяем какой метод необходимо вызвать
* @param string $name Имя вызываемого метода
* @param array $arguments Параметры переданный в метод
* @return mixed Результат работы метода
* @throws Exception
*/
public static function __callStatic(string $name, array $arguments)
{
switch ($name) {
case $name == 'strim':
unset($name);
return self::preplace($arguments[0], ['/^\//ui', '/\/$/ui']);
case $name == 'lstrim':
unset($name);
return self::preplace($arguments[0], ['/^\//ui']);
case $name == 'rstrim':
unset($name);
return self::preplace($arguments[0], ['/\/$/ui']);
case $name == 'quote':
unset($name);
return self::preplace($arguments[0], ['/(.)/ui'], ['\\\$1']);
case $name == 'upath':
unset($name);
if (stristr(strtolower(php_uname('s')), 'win') !== false) {
$replacement = ['/([^\\]|^)\\([^\\]|$)/ui'];
} else {
$replacement = ['/([^\\\]|^)\\\([^\\\]|$)/ui'];
}
return self::preplace($arguments[0], $replacement, ['$1/$2']);
case $name == 'sone':
unset($name);
return self::preplace($arguments[0], ['/\/{2,}/ui'], ['/']);
default:
throw new Exception(
"Отсутствует метод " . __CLASS__ . "::$name()"
);
}
}
/**
* Обертка над preg_replace
* @param string $string Строка, которую необходимо отформатировать
* @param array $replacement Массив строк для замены
* @param array $subject Массив строк на которые менять
* @return string Отформатированная строка
*/
private static function preplace(
string $string, array $replacement, array $subject = ['']
): string
{
$string = preg_replace($replacement, $subject, $string);
unset($replacement);
unset($subject);
return $string;
}
/**
* Вырезаем из имени файла/паки запрещенные символы/слова
* @param string $string Имя
* @param string $symbol Символ, которым запрещенные символы будут заменены
* @return string Откорректированное имя
*/
public static function name(string $name, string $symbol = '_'): string
{
$name = str_replace('/', $symbol, $name);
if (stristr(strtolower(php_uname('s')), 'win') !== false) {
$name = str_replace(self::$antiSymbols, $symbol, $name);
if (in_array(strtoupper($name), self::$antiNames)) {
$name .= $symbol;
}
}
unset($symbol);
return trim($name);
}
/**
* Развернуть путь ОС
* @param string $path Путь к ресурсу
* @param array $mode Параметры:
*
* bool $mode['upath'] - Разделители в unix стиле (default)
*
* bool $mode['sone'] - Исключить дублирование слеша (default)
*
* bool $mode['rstrim'] - Без разделителя в конце
*
* bool $mode['trim'] - Применить к строке trim() (default)
*
* @return string Развернутый путь к ресурсу
* @throws Exception
*/
public static function expath(string $path, array $mode = []): string
{
$mode = [
'upath' => (bool)($mode['upath'] ?? true),
'sone' => (bool)($mode['sone'] ?? true),
'rstrim' => (bool)($mode['rstrim'] ?? false),
'trim' => (bool)($mode['trim'] ?? true),
];
if ($mode['trim']) {
$path = trim($path);
}
if ($mode['upath']) {
$path = self::upath($path);
}
if ($mode['sone']) {
$path = self::sone($path);
}
if ($mode['rstrim']) {
$path = self::rstrim($path);
}
unset($mode);
$parts = explode('/', $path);
$npath = [];
foreach ($parts as $part) {
if ($part == '.') {
unset($part);
continue;
} elseif ($part == '..') {
if (count($npath) < 2) {
throw new Exception("Некорректный путь: $path");
} else {
array_pop($npath);
unset($part);
continue;
}
} else {
$npath[] = $part;
}
unset($part);
}
unset($path, $parts);
$npath = implode('/', $npath);
return $npath;
}
}
<file_sep>{
"name": "hellpers/pather",
"description": "Обработка и форматирование путей, ссылок, имен файлов/папок",
"minimum-stability": "dev",
"keywords": [
"adikalon",
"hellpers",
"pather"
],
"type": "library",
"homepage": "https://bitbucket.org/adikaion/pather",
"license": "MIT",
"authors": [
{
"name": "adikalon",
"homepage": "https://bitbucket.org/adikalon/",
"role": "Developer"
}
],
"autoload": {
"psr-4": {
"Hellpers\\": "src/"
}
}
}
<file_sep># Pather
**hellpers/pather** - Обработка и форматирование путей, ссылок, имен файлов/папок.
## Установка:
composer require hellpers/pather
## Пример:
```php
<?php
use Hellpers\Pather;
// Экранировать все символы
$string = 'Hello, World!';
echo Pather::quote($string) . PHP_EOL;
// Вырезаем из имени файла/паки запрещенные символы/слова
$string = 'File <Name>?';
echo Pather::name($string) . PHP_EOL;
// Обрезать слеш в конце
$string = '/path/to/folder/';
echo Pather::rstrim($string) . PHP_EOL;
// Обрезать слеш в начале
$string = '/path/to/folder/';
echo Pather::lstrim($string) . PHP_EOL;
// Обрезать слеш с обеих сторон
$string = '/path/to/folder/';
echo Pather::strim($string) . PHP_EOL;
// Заменить тип разделителя пути с windows на unix
$string = '\path\to\folder';
echo Pather::upath($string) . PHP_EOL;
// Исключить дублирование слеша
$string = '/path//to///folder';
echo Pather::sone($string) . PHP_EOL;
// Развертывание пути
$string = 'C:\path\to\..\folder';
$params = [
'upath' => true, // Разделители в unix стиле (default)
'sone' => true, // Исключить дублирование слеша (default)
'rstrim' => false, // Без разделителя в конце
'trim' => true, // Применить к строке trim() (default)
];
echo Pather::expath($string, $params) . PHP_EOL;
```<file_sep><?php
require_once(__DIR__ . '/../vendor/autoload.php');
use Hellpers\Pather;
// Экранировать все символы
$string = 'Hello, World!';
echo Pather::quote($string) . PHP_EOL;
// Вырезаем из имени файла/паки запрещенные символы/слова
$string = 'File <Name>?';
echo Pather::name($string) . PHP_EOL;
// Обрезать слеш в конце
$string = '/path/to/folder/';
echo Pather::rstrim($string) . PHP_EOL;
// Обрезать слеш в начале
$string = '/path/to/folder/';
echo Pather::lstrim($string) . PHP_EOL;
// Обрезать слеш с обеих сторон
$string = '/path/to/folder/';
echo Pather::strim($string) . PHP_EOL;
// Заменить тип разделителя пути с windows на unix
$string = '\path\to\folder';
echo Pather::upath($string) . PHP_EOL;
// Исключить дублирование слеша
$string = '/path//to///folder';
echo Pather::sone($string) . PHP_EOL;
// Развертывание пути
$string = 'C:\path\to\..\folder';
$params = [
'upath' => true, // Разделители в unix стиле (default)
'sone' => true, // Исключить дублирование слеша (default)
'rstrim' => false, // Без разделителя в конце
'trim' => true, // Применить к строке trim() (default)
];
echo Pather::expath($string, $params) . PHP_EOL;
|
7ebf40a78cc9a6b0053ebf6171df9b7875b4a584
|
[
"Markdown",
"JSON",
"PHP"
] | 4 |
PHP
|
adikalon/pather
|
525ae07d508dc479204b371e6be760442277d0e3
|
4cefeabc242b8265c06de648ca10c9368b4c8252
|
refs/heads/master
|
<file_sep>angular
.module("noteApp")
.controller("homeController", function ($scope, $sce) {
})<file_sep>var app = angular.module("noteApp", ["ui.router","chart.js"])
app.config(function($stateProvider, $urlRouterProvider) {
$urlRouterProvider.otherwise("/") //needs to match "home" url
$stateProvider
.state("home", {
url: "/",
templateUrl: "./views/home.html",
controller: "homeController"
})
.state("notes", {
url: "/notes",
templateUrl: "./views/notes.html", //the name on the address bar
controller: "noteController"
})
.state("deck", {
url: "/deck",
templateUrl: "./views/deck.html",
controller: "deckController"
})
.state("quiz", {
url: "/quiz",
templateUrl: "./views/quiz.html",
controller: "quizController"
})
.state("data", {
url: "/data",
templateUrl: "./views/data.html",
controller: "dataController"
})
.state("newUser", {
url: "/newUser",
templateUrl: "./views/newUser.html",
controller: "noteController"
})
});
<file_sep>var users = [];
var userId = 0;
// function randomInRange(min, max) {
// return Math.floor(Math.random() * (max - min + 1)) + min;
// }
function User(id, firstName, lastName, schoolName, email) {
var postId = 0
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.schoolName = schoolName;
this.email = email;
this.notes = [];
this.postDate = function () {
var day = new Date().getUTCDate();
var month = (1 + new Date().getMonth()) + "/";
var year = "/" + new Date().getUTCFullYear();
var hour = new Date().getHours() - 12
var minutes = new Date().getMinutes()
var concat = hour + ":" + minutes + " PM " + month + day + year;
return concat;
}
this.pushNote = function (input) {
this.notes.push({ postId: postId++, postedBy: this.firstName + " " + this.lastName, postedOn: this.postDate(), note: input });
}
}
users.push(new User(userId++, "Ron", "Weasley", "Red Wood", "<EMAIL>"));
users.push(new User(userId++, "Sirius", "Black", "Red Wood", "<EMAIL>"));
users.push(new User(userId++, "Severus", "Snape", "Red Wood", "<EMAIL>"));
users[0].pushNote("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores omnis rerum atque vitae Prize Picture explicabo recusandae unde, excepturi doloribus officiis, odio ratione animi. Magnam expedita fuga deserunt illo optio!");
users[0].pushNote("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores omnis rerum atque vitae Winner Winner facilis explicabo recusandae unde, excepturi doloribus officiis, odio ratione animi. Magnam expedita fuga deserunt illo optio!");
users[0].pushNote("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores omnis rerum atque Chicken Dinner facilis explicabo recusandae unde, excepturi doloribus officiis, odio ratione animi. Magnam expedita fuga deserunt illo optio!");
users[0].pushNote("Lorem ipsum dolor sit amet, consectetur adipisicing elit. Dolores omnis rerum atque vitae saepe facilis explicabo recusandae unde, excepturi doloribus officiis, odio ratione animi. Magnam expedita fuga deserunt illo optio!");
//GET
function index(req, res, next) {
res.json({ users: users });
}
//POST
function create(req, res, next) {
var tempUser = new User(userId++, req.body.firstName, req.body.lastName, req.body.schoolName, req.body.email);
users.push(tempUser);
res.json({ user: tempUser });
}
//GET
function show(req, res, next) {
for (var i = 0; i < users.length; i++) {
if (users[i].id == req.params.id) {
res.json({ user: users[i] });
}
}
res.json({ error: "Sorry that user does not exist." });
}
//PUT
function update(req, res, next) {
for (var i = 0; i < users.length; i++) {
if (users[i].id == req.params.id) {
users.splice(i, 1, new User(parseInt(req.params.id), req.body.firstName, req.body.lastName, req.body.schoolName, req.body.email, req.body.email));
res.json({ user: users[i] });
}
}
}
//DELETE
function destroy(req, res, next) {
for (var i = 0; i < users.length; i++) {
if (users[i].id == req.params.id) {
users.splice(i, 1);
res.json({ user: users });
}
}
res.json({ error: "Sorry that user didn't exist." });
}
module.exports = {
users: users,
index: index,
create: create,
show: show,
update: update,
destroy: destroy
}<file_sep>var notes = [];
var noteID = null;
var keywordID = null;
function Note(id, firstName, lastName, note, deckName) {
this.postId = id;
this.postedBy = firstName + " " + lastName;
this.postedDate = this.postDate();
this.postedTime = this.postTime();
this.note = note;
this.deckName = deckName || "Deck " + "#" + (this.postId + 1);
this.keywords = [];
}
function Keyword(id, keyword, definition) {
this.id = id;
this.keyword = keyword;
this.definition = definition|| " ";
}
Note.prototype.postTime = function () {
function z(n) { return (n < 10 ? "0" : "") + n; }
var hour = new Date().getHours();
var minutes = new Date().getMinutes();
if (hour >= 12) {
hour -= 12;
}
return z(hour) + ":" + z(minutes);
}
Note.prototype.postDate = function () {
var month = (1 + new Date().getMonth()) + "/";
var day = new Date().getUTCDate() + "/";
var year = new Date().getUTCFullYear();
var concat = day + month + year;
return concat
}
Note.prototype.updateNote = function(note){
this.note = note;
}
Note.prototype.addKeyword = function (id, keyword, definition) {
this.keywords.push(new Keyword(id, keyword, definition));
}
Keyword.prototype.updateKeywordDefinition = function (input) {
this.definition = input;
}
//creating a note
notes.push(new Note(noteID++, "Roger", "Chavez", "This is a test."));
notes.push(new Note(noteID++, "John", "Bianco", "A biome is a community or large ecological area on the earth's surface with plants and animals that have common characteristics for the environment with specific climatic conditions to suit the flora and fauna, they exist in and can be found over a range of continents. Biomes are distinct biological communities that have formed in response to a shared physical climate. 'Biome' is a broader term than 'habitat'; any biome can comprise a variety of habitats.", "biome"));
//creating a keyword
notes[0].addKeyword(keywordID++, "keyword 0", "Definition of the keyword 0.");
notes[0].addKeyword(keywordID++, "keyword 1", "Definition of the keyword 1.");
notes[0].addKeyword(keywordID++, "keyword 2", "Definition of the keyword 2.");
notes[0].addKeyword(keywordID++, "keyword 3", "Definition of the keyword 3.");
notes[0].addKeyword(keywordID++, "keyword 4", "Definition of the keyword 4.");
notes[0].addKeyword(keywordID++, "keyword 5", "Definition of the keyword 5.");
notes[1].addKeyword(keywordID++, "Tundra", "tree growth is hindered by low temperatures and short growing seasons.");
notes[1].addKeyword(keywordID++, "Taiga", " coniferous forests consisting mostly of pines, spruces and larches.");
notes[1].addKeyword(keywordID++, "Deciduous Forest", "dominated by trees that lose their leaves each year. They are found in areas with warm moist summers and mild winters.");
notes[1].addKeyword(keywordID++, "Grasslands", " areas where the vegetation is dominated by grasses.");
notes[1].addKeyword(keywordID++, "Desert", "barren area of landscape where little precipitation occurs and consequently living conditions are hostile for plant and animal life.");
notes[1].addKeyword(keywordID++, "Chaparral", "shrubland or heathland plant community found primarily in the U.S. state of California and in the northern portion of the Baja California Peninsula, Mexico");
//GET
function index(req, res, next) {
res.json({ usersNotes: notes });
}
//POST
function create(req, res, next) {
var tempUserNote = req.body.note;
notes.push(new Note(noteID++, req.body.firstName, req.body.lastName, req.body.note, req.body.deckName));
res.json({ note: notes });
}
function update(req, res, next) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].postId == req.params.id) {
notes[i].updateNote(req.body.note);
res.json({ note: notes });
}
}
}
//GET
function show(req, res, next) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].postId == req.params.id) {
res.json({ notes: notes[i] })
}
}
res.json({ error: "Sorry notes for that user do not exist." });
}
//PUT
function updateKeywords(req, res, next) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].postId == req.params.id) {
notes[i].addKeyword(keywordID++, req.body.keyword, req.body.definition);
res.json({ keywords: notes[i].keywords });
}
}
res.json({ error: "Sorry those notes do not exist." });
}
// PUT
function updateKeywordDefinition(req, res, next) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].postId == req.params.id) {
for (var j = 0; j < notes[i].keywords.length; j++) {
if (notes[i].keywords[j].id == req.params.id2) {
notes[i].keywords[j].updateKeywordDefinition(req.body.definition);
res.json({ keywords: notes[i].keywords });
}
}
}
}
res.json({ error: "Sorry those notes do not exist." });
}
//DELETE NOTES
function destroy(req, res, next) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].postId == req.params.id) {
notes.splice(i, 1);
res.json({ user: notes });
}
}
res.json({ error: "Sorry those notes don't exist." });
}
//DELETE KEYWORDS
function destroyKeyword(req, res, next) {
for (var i = 0; i < notes.length; i++) {
if (notes[i].postId == req.params.id) {
for (var j = 0; j < notes[i].keywords.length; j++) {
if (notes[i].keywords[j].id == req.params.id2) {
notes[i].keywords.splice(j, 1);
res.json({ keywords: notes[i].keywords });
}
}
}
}
res.json({ error: "Sorry there was an error, please check your notes id and your keyword id." });
}
module.exports = {
index: index,
create: create,
show: show,
update: update,
destroy: destroy,
destroyKeyword: destroyKeyword,
updateKeywords: updateKeywords,
updateKeywordDefinition: updateKeywordDefinition
}<file_sep>angular
.module('noteApp')
.controller('deckController', function ($scope, noteService) {
$scope.singleSelect = "";
noteService.getUserNotes()
.then(function (response) {
$scope.notes = response.data.usersNotes;
console.log($scope.notes)
});
$scope.$watch('singleSelect', function () {
console.log("this is running")
if ($scope.singleSelect != "") {
for (var i = 0; i < $scope.notes.length; i++) {
if ($scope.notes[i].postId == $scope.singleSelect) {
$scope.theseNotes = $scope.notes[i];
$scope.currentID = $scope.notes[i].postId
}
}
}
else {
$scope.currentID = "";
$scope.theseNotes = "";
}
})
})<file_sep>angular
.module('noteApp')
.controller('quizController', function ($scope, $timeout, $http, noteService, dataService) {
// below is the code for my timer
$scope.counter = 0;
$scope.onTimeout = function () {
$scope.counter++;
mytimeout = $timeout($scope.onTimeout, 1000);
}
var mytimeout = $timeout($scope.onTimeout, 1000);
$scope.stopTimeout = function () {
$timeout.cancel(mytimeout);
}
$scope.stopTimeout();
// this displays the select header bar and hides it after a deck is chosen
$scope.display = "display:inherit";
// key that displays a bar that displays which deck is currently being studied
$scope.studyOn = "display:none";
// This is the value of my select select element, it will change to whichever option I choose
$scope.singleSelect = "";
// This will be set to true when someone starts a study session
$scope.continueStudy = false;
// variable used to keep track of which deck to reset the cards into
var thisIndex = null;
// variable hold the id of the question, the function that checks if the answers are correct accesses this
var questionID = null;
// temporary container for cards
var tempCardCont = [];
//This array contains all the id's for the given deck, this insures the cards are tested randomly, but that the whole deck is studied complely before repeating cards.
var wholeDeckIDs = [];
//variable that displaysthat displays deck length
$scope.deckSize = 0;
// This variable stores the total amount of questions that have been asked,
$scope.questionTotal = 0;
// this variable stores the total amount of correct answers
$scope.answerCorrect = 0;
// this variable stores the total amount of wrong answers
$scope.answerWrong = 0;
// this variable stores card name on the global scope
$scope.cardName = [];
// represents the array of cards that will be tested and are being prepopulated at the start of the test into the backend
$scope.prePop = [];
// this scope will be able to tell if a person got a question wrong
$scope.notWrong = true;
// These variables will trigger animation when set to true
$scope.wrong = false;
// this is where the deck object is retrieved from the noteService, which get's it from my nodeserver
noteService.getUserNotes()
.then(function (response) {
$scope.notes = response.data.usersNotes;
console.log($scope.notes);
$scope.startStudy = function () {
// hide/show display
$scope.display = "display:none";
$scope.studyOn = "display:inherit";
// This for loops goes throught the data called and finds the right deck by key, which is attained from the select menu on my quiz screen
for (var i = 0; i < $scope.notes.length; i++) {
if ($scope.notes[i].postId == $scope.singleSelect) {
// fill the wholeDeckIDs only when it's completly empty, on deck completion or when starting up a study session
if (wholeDeckIDs.length == 0) {
for (var n = 0; n < $scope.notes[i].keywords.length; n++) {
wholeDeckIDs.push($scope.notes[i].keywords[n].id);
}
}
function prePopulateResults(arr) {
var tempArr = [];
for (var a = 0; a < arr.length; a++) {
if (arr[a] == $scope.notes[i].keywords[a].id) {
tempArr.push({ id: $scope.notes[i].keywords[a].id, keyword: $scope.notes[i].keywords[a].keyword, correct: 0, wrong: 0 })
}
}
$scope.prePop = tempArr;
console.log(tempArr)
}
if ($scope.questionTotal == 0) {
$scope.postSession($scope.notes[i].postId, $scope.notes[i].deckName);
prePopulateResults(wholeDeckIDs);
console.log(wholeDeckIDs)
}
//sets current notes index to variable accessible to global scope
thisIndex = i;
//sets the variable equal to the name of the deck
$scope.deckName = $scope.notes[i].deckName;
//set's variable to the length of the deck
$scope.deckSize = $scope.notes[i].keywords.length + " cards";
// get's a random number between 0 and the length of an inputted array
var randomNumber = function (arr) {
return Math.floor(Math.random() * (arr.length));
}
// shuffles items in an array
var shuffleArray = function (arr) {
for (var j = 0; j < 30; j++) {
var temp = arr[0];
var newNumber = randomNumber(arr);
if (arr[0] != arr[newNumber]) {
arr.splice(0, 1, arr[newNumber]);
arr.splice(newNumber, 1, temp);
}
}
}
shuffleArray(wholeDeckIDs);
// This represents the id that will be displayed as a question and is referece that that the program could find the complimentary answer and makes sure to display it in the answer selectioins
questionID = wholeDeckIDs.splice(0, 1);
// console.log("This is the answer and question ID:" + questionID);
// array of keywords will plugged into the function and will be shuffled
var shuffleKeywords = function (input) {
rightAnswer = "";
// this for loop splices out the right answer and stores it into a temporary variable
for (var k = 0; k < input.length; k++) {
if (input[k].id == questionID) {
rightAnswer = input.splice(k, 1);
}
}
shuffleArray(input);
// this for loop will shorten the answer selection to 3
while (input.length > 3) {
var temp = input.pop();
tempCardCont.push(temp);
}
if ($scope.cardName.length > 1) {
$scope.cardName.shift();
}
$scope.cardName.push(rightAnswer[0].keyword);
input.splice(randomNumber(input), 0, rightAnswer[0]);
}
shuffleKeywords($scope.notes[i].keywords);
// The question (keyword definition) that is being displayed on the quiz screen
for (var l = 0; l < $scope.notes[i].keywords.length; l++) {
if ($scope.notes[i].keywords[l].id == questionID) {
$scope.definition = $scope.notes[i].keywords[l].definition;
}
}
// The keywords array that is displaying below the quiz screen
$scope.keyWords = $scope.notes[i].keywords;
}
}
}
function countFilter(input) {
function z(n) { return (n < 10 ? '0' : '') + n; }
var seconds = input % 60;
var minutes = Math.floor((input / 60) % 60);
var hours = Math.floor((input / 60) / 60);
return (z(hours) + ':' + z(minutes) + ':' + z(seconds));
};
$scope.endStudy = function () {
// stop timeout timer
$scope.stopTimeout();
console.log(countFilter($scope.counter));
dataService.updateDuration($scope.tempID, countFilter($scope.counter))
// ejects out of the while loop to stop the study session
$scope.continueStudy = false;
// this displays the select header bar and hides it after a deck is chosen
$scope.display = "display:inherit";
// key that displays a bar that displays which deck is currently being studied
$scope.studyOn = "display:none";
// resets the select optioins menu back to a blank option
$scope.singleSelect = "";
// resets the array of ids used to select id's at random
wholeDeckIDs = [];
// resets the quiz screen to a blank screen
$scope.definition = "";
//resets the keyword buttons below the quiz screen
$scope.keyWords = "";
//pushes all the cards back in the appropriate deck
for (var i = 0; i < tempCardCont.length; i++) {
$scope.notes[thisIndex].keywords.push(tempCardCont[i]);
}
// resets string that displays deck length
$scope.deckSize = 0;
// This variable stores the total amount of questions that have been asked,
$scope.questionTotal = 0;
// this variable stores the total amount of correct answers
$scope.answerCorrect = 0;
// this variable stores the total amount of wrong answers
$scope.answerWrong = 0;
//empty the temporary container
tempCardCont = [];
// reset temp index
thisIndex = null;
//resets timer to 0
$scope.counter = 0;
}
$scope.checkAnswer = function (id) {
if (id == questionID) {
if ($scope.notWrong == true) {
$scope.answerCorrect++;
dataService.updateAnswer($scope.tempID, id, $scope.notWrong);
}
else {
$scope.answerWrong++;
dataService.updateAnswer($scope.tempID, id, $scope.notWrong);
}
$scope.questionTotal = $scope.answerCorrect + $scope.answerWrong;
resetStudy();
$scope.startStudy();
$scope.wrong = false;
}
else {
$scope.notWrong = false;
$scope.wrong = true;
}
}
function resetStudy() {
// resets the quiz screen to a blank screen
$scope.definition = "";
//resets the keyword buttons below the quiz screen
$scope.keyWords = "";
//pushes all the cards back in the appropriate deck
for (var i = 0; i < tempCardCont.length; i++) {
$scope.notes[thisIndex].keywords.push(tempCardCont[i]);
}
//empty the temporary container
tempCardCont = [];
// reset temp index
thisIndex = null;
$scope.notWrong = true;
$scope.wrong = false;
}
});
// POST make an instance of a session
$scope.postSession = function (deckId, deckName) {
$http.post("/session", { deckId: deckId, deckName: deckName })
.then(function (response) {
$scope.tempID = response.data.sessionID.id;
console.log('This is my new instance of session and its id');
console.log(response.data.sessionID.id);
})
}
$scope.updateResults = function (arr) {
for (var i = 0; i < arr.length; i++) {
dataService.updateResults($scope.tempID, arr[i].id, arr[i].keyword, arr[i].correct, arr[i].wrong);
}
}
$scope.$watch('tempID', function () {
console.log("This is the id.")
console.log($scope.tempID)
if ($scope.tempID > 0) {
$scope.updateResults($scope.prePop);
console.log($scope.prePop)
}
});
})
<file_sep>angular
.module("noteApp")
.service("dataService", function ($http) {
// stores id of current session so that I can update name of session and update test results in realtime
var postID = "";
//Get
this.getSessionData = function () {
return $http.get("/session");
}
// POST make an instance of a session
this.postSession = function (deckId, deckName, name) {
$http.post("/session", { deckId: deckId, deckName: deckName, name: name })
.then(function (response) {
console.log('This is my new instance of session and its id');
console.log(response.data.sessionID.id);
return response.data.sessionID.id;
})
}
//PUT Finishing up a Session. Setting the duration length.
this.updateDuration = function (thisDeckId, duration) {
$http.put("/session/duration/" + thisDeckId, { duration: duration })
.then(function (response) {
console.log('This is my duration update path');
console.log(response.data);
})
}
this.postID = function () {
return postID;
}
//PUT uploading Results
this.updateResults = function (thisPostId, id, keyword, correct, wrong) {
$http.put("/session/" + thisPostId, { id: id, keyword: keyword, correct: correct, wrong: wrong })
// .then(function (response) {
// console.log('This is my update results path');
// console.log(response.data);
// })
}
// PUT ANSWERS
this.updateAnswer = function (thisPostId, id, input) {
console.log("logging: " + thisPostId)
console.log("logging: " + id)
console.log("logging: " + input)
$http.put("session/" + thisPostId + "/answer/" + id, { rightOrWrong: input })
.then(function (response) {
console.log('This is my update results path');
console.log(response.data);
})
}
// DELETE
this.deleteSession = function (id) {
console.log("In the delete function")
$http.delete("/session/" + id)
.then(function (response) {
console.log('This is my destroy path');
console.log(response.data);
})
}
})<file_sep>$('.input-field').on('input', function () {
if ($(this).val().length > 0) {
$(this).parent('.input').addClass('has-input');
} else {
$(this).parent('.input').removeClass('has-input');
}
});<file_sep>angular
.module('noteApp')
.service('noteService', function ($http) {
//** Get
this.getUserNotes = function () {
return $http.get('/notes');
}
})<file_sep>var express = require('express');
var router = express.Router();
var notesController = require('../controllers/notes-controller');
/* GET users listing. */
router.get('/', notesController.index);
//POST
router.post('/', notesController.create);
//GET
router.get('/:id', notesController.show);
//PUT
router.put('/:id/keyword', notesController.updateKeywords);
//PUT
router.put('/:id/definition/:id2', notesController.updateKeywordDefinition);
//PUT
router.put('/:id', notesController.update);
//DELETE
router.delete('/:id', notesController.destroy);
//DELETE KEYWORD
router.delete('/:id/keyword/:id2', notesController.destroyKeyword);
module.exports = router;
<file_sep>angular
.module('noteApp')
.controller('dataController', function ($scope, dataService) {
$scope.displayOnGraph = "";
// POST scopes
$scope.deckId = "";
$scope.deckName = "";
$scope.name = "";
// PUT scopes
$scope.thisDeckId = null;
$scope.id = null;
$scope.duration = dataService.postID();
$scope.correct = 0
$scope.wrong = 0;
dataService.getSessionData()
.then(function (response) {
$scope.sessions = response.data.sessions;
console.log($scope.sessions)
function grabPropertyPerc(arr, prop, newloc) {
var tempArr = [];
for (var i = 0; i < arr.length; i++) {
tempArr.push(arr[i][prop])
}
$scope[newloc].push(tempArr);
}
function grabPropertyData(id, arr, prop, newloc) {
console.log("this is my function id "+id)
for (var i = 0; i < arr.length; i++) {
if (arr[i].id == id) {
console.log("makes it here")
$scope[newloc].push(arr[i][prop]);
}
}
}
$scope.currentDeck = null;
$scope.showThis = function (id) {
$scope.currentSession = id;
}
$scope.$watch('currentSession', function () {
grabPropertyData($scope.currentSession, $scope.sessions, "name", "series");
grabPropertyData($scope.currentSession, $scope.sessions[0].results, "keyword", "labels");
for (var i = 0; i < $scope.sessions.length; i++) {
if ($scope.sessions[i].id == $scope.currentSession) {
$scope.currentDeck = $scope.sessions[i].deckIDTested;
grabPropertyPerc($scope.sessions[i].results, "percentage", "data");
}
}
})
$scope.$watch('displayOnGraph', function () {
console.log($scope.displayOnGraph);
})
});
$scope.postSession = function () {
dataService.postSession($scope.deckId, $scope.deckName, $scope.name);
}
$scope.updateDuration = function () {
dataService.updateDuration($scope.thisDeckId, $scope.duration);
}
$scope.updateResults = function () {
dataService.updateResults($scope.thisDeckId, $scope.id, $scope.keyword, $scope.correct, $scope.wrong);
}
$scope.deleteSessions = function () {
console.log("inside my delete function")
dataService.deleteSession($scope.id);
}
$scope.clearGraph = function () {
$scope.currentSession = null;
$scope.labels = [];
$scope.series = [];
$scope.data = [];
}
$scope.currentSession = null;
$scope.labels = [];
$scope.series = [];
$scope.data = [];
console.log($scope.labels)
console.log($scope.series)
console.log($scope.data)
})<file_sep>sessions = [];
sessionID = null;
// write a similar incrementing if statement as the front end, only use the prototype to push if the id doesn't already exist (or push all the cards in the the rests array at some point and increment right and wrong answers as you go), increment by boolean like front end;
function Session(id, deckId, deckName, name) {
this.id = id;
this.deckIDTested = deckId;
this.deckName = deckName;
this.postDate = this.postDate();
this.localTime = this.localTime();
this.duration = null;
this.name = name || "Session #" + (this.id + 1);
this.results = [];
}
function Result(id, keyword, correct, wrong) {
this.cardID = id;
this.keyword = keyword;
this.correct = correct;
this.wrong = wrong;
this.total = this.correct + this.wrong;
this.getPercentage = function () {
return Math.round(this.correct / this.total * 100);
}
this.percentage = this.getPercentage();
}
Session.prototype.newName = function (name) {
this.name = name;
}
Session.prototype.setDuration = function (time) {
this.duration = time;
}
Session.prototype.newResult = function (id, keyword, correct, wrong) {
this.results.push(new Result(id, keyword, correct, wrong));
}
Session.prototype.localTime = function () {
function z(n) { return (n < 10 ? '0' : '') + n; }
var hour = new Date().getHours()
var minutes = new Date().getMinutes()
if (hour >= 12) {
hour -= 12;
}
return z(hour) + ":" + z(minutes);
}
Result.prototype.updateAnswer = function (input) {
if (input == true) {
this.correct++
this.total = this.correct + this.wrong;
this.percentage = this.getPercentage();
}
else {
this.wrong++
this.total = this.correct + this.wrong;
this.percentage = this.getPercentage();
}
}
Session.prototype.postDate = function () {
var month = (1 + new Date().getMonth()) + "/";
var day = new Date().getUTCDate() + "/";
var year = new Date().getUTCFullYear();
var concat = day + month + year;
return concat
}
// seeding my database
sessions.push(new Session(sessionID++, 0, "Deck #1"));
sessions.push(new Session(sessionID++, 0, "Deck #1"));
sessions.push(new Session(sessionID++, 0, "Deck #1"));
// sessions.push(new Session(sessionID++, 0, "Deck #1", "Third session"));
// sessions.push(new Session(sessionID++, 0, "Deck #1", "Fourth session"));
// sessions.push(new Session(sessionID++, 0, "Deck #1", "Fifth session"));
sessions[0].newResult(0, "keyword", 5, 6);
sessions[0].newResult(1, "keyword 1", 4, 7);
sessions[0].newResult(2, "keyword 2", 8, 3);
sessions[0].newResult(3, "keyword 3", 9, 2);
sessions[0].newResult(4, "keyword 4", 2, 9);
sessions[0].newResult(5, "keyword 5", 6, 5);
sessions[0].newResult(6, "keyword 6", 11, 0);
sessions[0].newResult(7, "keyword 7", 5, 6);
sessions[0].newResult(8, "keyword 8", 4, 7);
sessions[0].setDuration("867:53:09");
sessions[1].newResult(0, "keyword", 6, 6);
sessions[1].newResult(1, "keyword 1", 5, 7);
sessions[1].newResult(2, "keyword 2", 9, 3);
sessions[1].newResult(3, "keyword 3", 10, 2);
sessions[1].newResult(4, "keyword 4", 3, 9);
sessions[1].newResult(5, "keyword 5", 7, 5);
sessions[1].newResult(6, "keyword 6", 12, 0);
sessions[1].newResult(7, "keyword 7", 6, 6);
sessions[1].newResult(8, "keyword 8", 5, 7);
sessions[1].setDuration("00:19:84");
sessions[2].newResult(0, "keyword", 8, 4);
sessions[2].newResult(1, "keyword 1", 7, 5);
sessions[2].newResult(2, "keyword 2", 11, 3);
sessions[2].newResult(3, "keyword 3", 12, 2);
sessions[2].newResult(4, "keyword 4", 9, 5);
sessions[2].newResult(5, "keyword 5", 9, 3);
sessions[2].newResult(6, "keyword 6", 14, 0);
sessions[2].newResult(7, "keyword 7", 8, 4);
sessions[2].newResult(8, "keyword 8", 7, 5);
sessions[2].setDuration("00:17:38");
//GET
function index(req, res, next) {
res.json({ sessions: sessions });
}
//POST
function create(req, res, next) {
console.log("this create path got hit")
sessions.push(new Session(sessionID++, req.body.deckId, req.body.deckName, req.body.name));
res.json({ sessionID: sessions[sessions.length - 1] });
}
//GET
function show(req, res, next) {
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].id == req.params.id) {
res.json({ Session: sessions[i] });
}
}
res.json({ error: "Sorry that session does not exist." });
}
//PUT session name
function updateName(req, res, next) {
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].id == req.params.id) {
sessions[i].newName(req.body.name);
res.json({ Session: sessions[i] });
}
}
res.json({ error: "error, please double check your input." });
}
//PUT Results Prepopulate
function update(req, res, next) {
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].id == req.params.id) {
sessions[i].newResult(req.body.id, req.body.keyword, req.body.correct, req.body.wrong);
res.json({ Session: sessions });
}
}
res.json({ error: "error, please double check your input." });
}
// PUT update right and wrong answer by boolean
function updateAnswer(req, res, next) {
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].id == req.params.id) {
for (var j = 0; j < sessions[i].results.length; j++) {
if (sessions[i].results[j].cardID == req.params.id2) {
console.log(req.body.rightOrWrong)
sessions[i].results[j].updateAnswer(req.body.rightOrWrong);
res.json({ SessionAnswer: sessions[i] });
}
}
}
}
res.json({ error: "error, please double check your input." });
}
// PUT FINISHED SESSION - Duration
function updateDuration(req, res, next) {
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].id == req.params.id) {
sessions[i].setDuration(req.body.duration);
res.json({ Session: sessions[i] });
}
}
res.json({ error: "error, please double check your input." });
}
//DELETE
function destroy(req, res, next) {
for (var i = 0; i < sessions.length; i++) {
if (sessions[i].id == req.params.id) {
sessions.splice(i, 1);
res.json({ Session: sessions });
}
}
res.json({ error: "Sorry that session does not exist." });
}
module.exports = {
index: index,
create: create,
show: show,
updateName: updateName,
updateAnswer: updateAnswer,
updateDuration: updateDuration,
update: update,
destroy: destroy
}<file_sep>
# Description
SmartNotes is a web app that allows users to optimize their study time by combining note taking and flash cards. As you take notes you can easily mark keywords and either define them right then or define them later. You can then review and/or quiz yourself on these keywords and the app will also keep track of your quiz data and will display your data upon clicking on the session in the data page. Another convenient aspect of the app is that they're saved online, meaning if you have access to internet you can access them anywhere.
<br>
## Technologies
| Technology | Deployment |
| ----------- | ------------|
| Angular JS | [heroku](https://smart-notes.herokuapp.com/#/) |
| node.js ||
| express.js ||
| chart.js ||
| angular-chart.js||
| HTML ||
| CSS ||
| JavaScript ||
<br>

<br>
## Deck Model
| Parameters | Value | Description | Example |
| ----------- | ---------- | ------------ | ------- |
| Deck name | String | If this isn't named it will be set to a default name. | "Deck #1" |
| Posted by | String | Takes in the first and last name of the user. | "<NAME>"
| Posted Date| Date | Automatically get's the date, on creation. | 07/03/2017 |
| Posted Time | Date | Get's the current time, on creation. | 17:38 |
| Keywords | array | Stores keyword objects. | Object example below |
```
{
id: 777,
keyword:"Newton's Third Law ",
definition: "For every action, there is an equal and opposite reaction."
}
```
## Keyword Model
|Parameters| Value| Description| Example|
|----------|------|------------|--------|
| Id| Number| Easily distinguishes one card from the next.| 777|
| Keyword | String| This can be a vocabulary word or key concept.| Newton's Third Law |
| Definition| string| This is the statement that gives meaning to the keyword.| "For every action, there is an equal and opposite reaction."
## Session model
|Parameters| Value| Description| Example|
|----------|------|------------|--------|
| Deck id tested | Number| Displays the id for the deck used in a given study session.| 0 |
| Deck Name | String|Displays the name for the deck used in a given study session.| "Deck #1" |
| Posted Date| Date | Automatically get's the date, on creation. | 07/07/2017 |
| Posted Time | Date | Get's the current time, on creation. | 12:34 |
| Duration | Date | Displays total time spend studying. | 12:34 |
| Session name | sting | Allows a user to easily distinguish sessions when looking at their study data. | "MidTerm practice quiz #3" |
| results | array | Stores result objects. | Object example below|
```
{
cardID: 0,
keyword: "Constellation",
correct: 9,
wrong: 2,
total: 11,
percentage: 82
}
```
## Result model
|Parameters| Value| Description| Example|
|----------|------|------------|--------|
| Card id | Number| Stores the id of the keyword in a given study session.| 0 |
| Keyword | String| Stores the name of the keyword used in a given study session.| "Constellation" |
| Correct| number | Displays the number of times a student answered correctly. | 9|
| Wrong | number | Displays the number of times a student answered wrong. | 2|
| Total | number | Displays the total number of times a student answered. | 11|
| Percentage | number | Displays a percentage, rounded to the nearest whole number, for the correct answers. | 82|
<br>
## Planning and Approach
We came into this project having a good idea of what we wanted to do. From the get go we were both interested in solving different problems for app. We entrusted each other to work on the areas of the app we were interested in and kept communicating what changes we had successfully made, what we were currently working on and our stretch goals if we had sufficient time. We started in the backend trying to think through all the ways we needed to be able to use a note and keyword, and we adjusted the model accordingly.
## Challenges
- Manipulating API to get correct information needed for functionality of the App.
- Comming up with a way to parse through notes and pick out the keywords.
- Comming up with a way to make a quiz using the keyword object and storing the quiz study session data.
|
c9cf01f4081ae93f2771b7173f0c2d99ff92894d
|
[
"JavaScript",
"Markdown"
] | 13 |
JavaScript
|
Roger-Chavez/SmartNotes
|
9c73a32b0ab9e409c902bf345bb77c25f2b666e5
|
88bbdb35e5731a99e9035e1c65649442a2100a58
|
refs/heads/master
|
<file_sep>class CommentsController < ApplicationController
before_action :find_comment,except: [:create]
before_action :authenticate_user!
def create
@article = Article.find(params[:article_id])
@comment = @article.comments.create(comment_params)
if @comment.save
flash[:success] = "Comment successfully created !"
redirect_to article_path(@article)
else
flash[:danger] = "Comment failed to create !"
render '_form'
end
end
def edit
end
def update
if @comment.update(comment_params)
flash[:success] = "Comment successfully updated !"
redirect_to article_path(@article)
else
flash[:danger] = "Comment failed to update !"
render 'edit'
end
end
def destroy
@comment.delete
redirect_to article_path(@article)
flash[:danger] = "Comment successfully deleted !"
end
private
def find_comment
@article = Article.find(params[:article_id])
@comment = @article.comments.find(params[:id])
end
def comment_params
params.require(:comment).permit(:body)
end
end
<file_sep>Rails.application.routes.draw do
devise_for :users
resources :articles do
resources :comments
end
get '/users-listing', to: 'users#index'
root 'articles#index'
end
<file_sep>class Comment < ActiveRecord::Base
belongs_to :article
belongs_to :user
validates :body, presence: true, length: { minimum: 2}
end
<file_sep>class Article < ActiveRecord::Base
has_many :comments, dependent: :destroy
belongs_to :user
validates :title, presence: true, length: { minimum: 4 }
validates :content, presence: true, length: { minimum: 30}
# Needed for carrierwave
mount_uploader :image, ImageUploader
end
|
755b04917462f67f50a1c5bd42ec58ed18205c11
|
[
"Ruby"
] | 4 |
Ruby
|
aminesirati/HameldBlog
|
9dc698a38d5b00a1aed63285819e0375060c8b98
|
5182407e8417d086cc7d4c24da96eaa9a44ce467
|
refs/heads/master
|
<file_sep>'use strict';
const uuidv4 = require('uuid/v4');
let path = require('path');
let config = require('../../server/config.json');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
let generatePassword = require('<PASSWORD>');
let senderAddress = '<EMAIL>'; // Replace this address with your actual address
module.exports = function(Relations) {
// Add extension code here
let date = new Date().toLocaleString();
let modifier;
// send password reset link when password reset requested
Relations.on('resetPasswordRequest', function(info) {
var url = 'http://' + config.resetHost + ':' + config.resetPort + '/desktop/reset-password';
var html = 'Click <a href="' + url + '?access_token=' +
info.accessToken.id + '">here</a> to reset your password';
// 'here' in above html is linked to : 'http://<host:port>/reset-password?access_token=<short-lived/temporary access token>'
Relations.app.models.Email.send({
to: info.email,
from: info.email,
subject: 'Password reset',
html: html,
}, function(err) {
if (err) return console.log('> error sending password reset email');
// console.log('>>>>> sending password reset email to:', info.email);
});
});
Relations.beforeRemote('deleteById', function(context, unused, next) {
console.log('>>>>>', context.args.id);
console.log('>>>>> afterRemote', context.method.name);
console.log('>>>>> afterRemote', context.args.data);
console.log('>>>>> afterRemote', context.args.filter);
const relationsId = context.args.id;
function deleteRelatedLocation() {
let query = 'delete from locations where id<>1 and id= ' +
'(select locations_id from relations where id=' + relationsId + ')';
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
} else {
console.log('>>>>> Deleted records from locations');
}
deleteFromRelatedTables();
});
}
function deleteFromRelatedTables() {
let tables = ['relations_with_teams', 'relations_with_roles',
'relations_with_tasks', 'debts',
'transactions'];
for (let i = 0; i < tables.length; i++) {
let table = tables[i];
let query = 'delete from ' + table + ' where relations_id=' +
relationsId;
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
} else {
console.log('>>>>> Deleted records from ' + table);
}
});
}
}
deleteRelatedLocation();
next();
});
Relations.beforeRemote('create', function(context, unused, next) {
if (context.args.data.debt &&
(isNaN(parseFloat(context.args.data.debt)) ||
parseFloat(context.args.data.debt) < 0)) {
let error = new Error();
error.status = 500;
error.message = 'Debt must be a positive number';
error.code = 'NUMBER_REQUIRED';
next(error);
} else if (context.args.data.rolesId &&
(isNaN(parseInt(context.args.data.rolesId)) ||
parseFloat(context.args.data.rolesId) < 0)) {
let error = new Error();
error.status = 500;
error.message = 'rolesId must be a positive number';
error.code = 'NUMBER_REQUIRED';
next(error);
} else {
modifier = context.req.connection.remoteAddress;
context.args.data.locationsId = 1; // placeholder, will be updated with actual location
context.args.data.uuid = uuidv4();
context.args.data.creationdate = date;
context.args.data.createdby = modifier;
context.args.data.modificationdate = date;
context.args.data.modifiedby = modifier;
context.args.data.password = <PASSWORD>(12, false);
next();
}
});
// send verification email after registration
Relations.afterRemote('create', function(context, user, next) {
let statements = 0;
function doNext(err) {
if (err) {
next(err);
}
statements += 1;
if (statements === 6) {
// console.log('>>>>> statements: ', statements);
next();
}
}
// add debt for participant
if (context.args.data.debt) {
let debt = parseFloat(context.args.data.debt);
if (!isNaN(debt) && debt > 0) {
let query = 'insert into debts (\n' +
'uuid, \n' +
'relations_id, \n' +
'debtDate, \n' +
'debt_lc, \n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + uuidv4() + '\',\n' +
'\'' + user.id + '\',\n' +
'\'' + date + '\',\n' +
'\'' + debt + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
doNext(err);
} else {
// console.log('>>>>> query:', query);
// console.log('>>>>> commit:', data);
context.result = data;
doNext();
}
});
}
}
// create role. default role is participant
if (context.args.data.rolesId) {
let query = 'insert into relations_with_roles (\n' +
'relations_id, \n' +
'roles_id,\n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + user.id + '\',\n' +
'\'' + context.args.data.rolesId + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
ds.connector.execute(query, [], function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
doNext(err);
} else {
// console.log('>>>>> query:', query);
// console.log('>>>>> commit:', data);
context.result = data;
doNext();
}
});
}
// create team if teamsId is set
if (context.args.data.teamsId) {
let query = 'insert into relations_with_teams (\n' +
'relations_id, \n' +
'teams_id,\n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + user.id + '\',\n' +
'\'' + context.args.data.teamsId + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
doNext(err);
} else {
context.result = data;
// console.log('>>>>> query:', query);
// console.log('>>>>> commit:', data);
doNext();
}
});
}
function updateRelation(locationsId) {
let query = 'update relations set locations_id = ' +
locationsId + ', modifiedBy=\'tester\' where id = ' + user.id;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
doNext(err);
} else {
// console.log('>>>>> query:', query);
// console.log('>>>>> data:', data);
context.result = data;
doNext();
}
});
}
function setDefaultValues(key) {
let value = '';
if (context.args.data.location &&
context.args.data.location[key] !== undefined &&
context.args.data.location[key] !== null) {
value = context.args.data.location[key];
}
return value;
}
// create locations record
let streetname = setDefaultValues('streetname');
let housenumber = setDefaultValues('housenumber');
let postalcode = setDefaultValues('postalcode');
let city = setDefaultValues('city');
let query = 'insert into locations (\n' +
'uuid, \n' +
'streetname, \n' +
'housenumber, \n' +
'postalcode, \n' +
'city, \n' +
'description, \n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + uuidv4() + '\',\n' +
'\'' + streetname + '\',\n' +
'\'' + housenumber + '\',\n' +
'\'' + postalcode + '\',\n' +
'\'' + city + '\',\n' +
'\'created with relation\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'now(),\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
doNext(err);
} else {
context.result = data;
let locationsId = data.insertId;
// console.log('>>>>> query:', query);
// console.log('>>>>> data:', data);
// create relations record
updateRelation(data.insertId);
doNext();
}
});
let options = {
type: 'email',
to: user.email,
from: senderAddress,
subject: 'Thanks for registering.',
template: path.resolve(__dirname, '../../server/views/verify.ejs'),
redirect: '/verified',
user: user,
};
user.verify(options, function(err, response) {
if (err) {
Relations.deleteById(user.id);
return next(err);
}
context.res.render('response', {
title: 'Signed up successfully',
content: 'Please check your email and click on the verification link ' +
'before logging in.',
redirectTo: '/',
redirectToLinkText: 'Log in',
});
doNext();
});
});
// Method to render
Relations.afterRemote('prototype.verify', function(context, user, next) {
context.res.render('response', {
title: 'A Link to reverify your identity has been sent ' +
'to your email successfully',
content: 'Please check your email and click on the verification link ' +
'before logging in',
redirectTo: '/',
redirectToLinkText: 'Log in',
});
});
// render UI page after password change
Relations.afterRemote('changePassword', function(context, user, next) {
context.res.render('response', {
title: 'Password changed successfully',
content: 'Please login again with new password',
redirectTo: '/',
redirectToLinkText: 'Log in',
});
});
// render UI page after password reset
Relations.afterRemote('setPassword', function(context, user, next) {
context.res.render('response', {
title: 'Password reset success',
content: 'Your password has been reset successfully',
redirectTo: '/',
redirectToLinkText: 'Log in',
});
});
Relations.afterRemote('findById', function(context, user, next) {
console.log('>>>>>', context.args.id);
console.log('>>>>> afterRemote', context.method.name);
console.log('>>>>> afterRemote', context.args.data);
console.log('>>>>> afterRemote', context.args.filter);
function getTeams() {
if (context.args.filter && context.args.filter.teams) {
let query = 'select *\n' +
'from teams t\n' +
'where t.id in (select teams_id from relations_with_teams ' +
'where relations_id=' + context.args.id + ')';
console.log('>>>>> query: ', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
} else {
context.result.teams = data;
getRoles();
}
});
} else {
getRoles();
}
}
function getRoles() {
if (context.args.filter && context.args.filter.roles) {
let query = 'select roles.* from \n' +
'relations r\n' +
'left join relations_with_roles rwr on r.id=rwr.relations_id\n' +
'left join roles on roles.id=rwr.roles_id\n' +
'where r.id=' + context.args.id;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
} else {
context.result.roles = data;
getTasks();
}
});
} else {
getTasks();
}
}
function getTasks() {
if (context.args.filter && context.args.filter.tasks) {
let query = 'select tasks.* from \n' +
'relations r\n' +
'left join relations_with_tasks rwr on r.id=rwr.relations_id\n' +
'left join tasks on tasks.id=rwr.tasks_id\n' +
'where r.id=' + context.args.id;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> query: ', query);
console.log(err);
} else {
context.result.tasks = data;
next();
}
});
} else {
console.log('>>>>> context.result: ', context.result);
next();
}
}
getTeams();
});
// Disabled remote methods
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
// 'deleteById',
'exists',
// 'find',
// 'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
// 'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
// Relations.disableRemoteMethodByName(methods[i]);
}
}
;
<file_sep>'use strict';
let _ = require('lodash');
let fs = require('fs');
let outputPath = './common/models';
let loopback = require('loopback');
let config = require('../datasources.json').socialcoinDb;
let ds = loopback.createDataSource('mysql', config);
ds.discoverModelDefinitions({schema: 'socialcoin'}, function(err, models) {
let count = models.length;
_.each(models, function(model) {
ds.discoverSchema(model.name, {associations: false}, function(err, schema) { // instead of model.name just mention your table name
let outputName = outputPath + '/' + schema.name + '.json';
// With the next line, we assume that an id is auto generated. However this value is required, it will be generated by the database.
schema.properties.id.required = false;
fs.writeFile(outputName, JSON.stringify(schema, null, 2), function(err) {
if (err) {
console.log(err);
} else {
console.log('JSON saved to ' + outputName);
}
});
let str = '\'use strict\';\n' +
'\n' +
'module.exports = function(' + schema.name + ') {\n' +
' // Add extension code here\n' +
'};';
fs.writeFile(outputPath + '/' + schema.name + '.js', str, function(err) {
if (err) throw err;
console.log('Created ' + schema.name + '.json file');
});
count = count - 1;
if (count === 0) {
console.log('DONE!', count);
ds.disconnect();
return;
}
});
});
});
<file_sep>'use strict';
module.exports = {
config: {
headers: {
'Accept': 'application/json',
'Accept-Language': 'en-US',
},
auth: {
url: '/api/Relations/login',
},
error: err => {
console.error(err);
},
},
adminUser: {
email: '<EMAIL>',
password: '<PASSWORD>',
},
};
<file_sep>'use strict';
const uuidv4 = require('uuid/v4');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(Actions) {
let modifier = '';
// Add extension code here
Actions.beforeRemote('**', function(context, unused, next) {
modifier = context.req.connection.remoteAddress;
next();
});
Actions.job = function(body, cb) {
let result = {response: 'ok'};
let query = 'insert into actions (';
let columns = [];
let values = [];
columns.push('uuid');
values.push('\'' + uuidv4() + '\'');
if (body.description) {
columns.push('description');
values.push('\'' + (body.description || '') + '\'');
} else {
columns.push('description');
values.push('\'.\'');
}
if (body.effort) {
columns.push('effort');
values.push('\'' + body.effort + '\'');
}
if (body.json) {
columns.push('json');
values.push('\'' + JSON.stringify(body.json) + '\'');
}
columns.push('startDate');
values.push('now()');
columns.push('creationDate');
values.push('now()');
columns.push('createdBy');
values.push('\'' + modifier + '\'');
columns.push('modificationDate');
values.push('now()');
columns.push('modifiedBy');
values.push('\'' + modifier + '\'');
query += columns.join(',') + ')\n values (' +
values.join(',') + ')';
let params = [];
console.log('>>>>> query\n', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
cb(null, err);
return;
} else {
let actionId = data.insertId;
let query = 'insert into tasks_with_actions (' +
'tasks_id, actions_id, creationDate, createdBy, ' +
'modificationDate, modifiedBy) \nvalues (' +
body.taskId + ', ' + actionId +
', now(), \'' + modifier + '\'' +
', now(), \'' + modifier + '\')';
console.log('>>>>> query\n', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
cb(null, err);
return;
} else {
if (body.statusId) {
let query = 'update tasks_with_status set ' +
'status_id=' + body.statusId + ',\n' +
'modificationDate=now(),\n' +
'modifiedBy=\'' + modifier + '\'\n' +
'where tasks_id=' + body.taskId;
console.log('>>>>> query\n', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
cb(null, err);
return;
} else {
console.log('>>>>> data', data);
cb(null, data);
}
});
} else {
cb(null, data);
}
}
});
}
});
};
Actions.remoteMethod(
'job', {
http: {
path: '/',
verb: 'post',
},
returns: [
{arg: 'taskId', type: 'number', required: true},
{arg: 'description', type: 'string', required: true},
{arg: 'startDate', type: 'string', required: true},
{arg: 'endDate', type: 'string', required: true},
{arg: 'effort', type: 'number'},
{arg: 'json', type: 'object'},
{arg: 'creationDate', type: 'string'},
{arg: 'createdBy', type: 'string'},
{arg: 'modificationDate', type: 'string'},
{arg: 'modifiedBy', type: 'string'},
],
accepts: [
{
arg: 'body',
type:
'object',
http: {
source: 'body',
},
required: true,
description:
'Pass an object from the example value.',
},
],
description:
'Creates Action model for Task from Participant.',
})
;
// Disabled remote methods
let methods = [
'confirm',
'count',
'create',
'createChangeStream',
'deleteById',
'exists',
'find',
'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
Actions.disableRemoteMethodByName(methods[i]);
}
}
;
<file_sep>'use strict';
const uuidv4 = require('uuid/v4');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
let generatePassword = require('<PASSWORD>-<PASSWORD>');
let senderAddress = '<EMAIL>'; // Replace this address with your actual address
module.exports = function(Teams) {
// Add extension code here
Teams.beforeRemote('create', function(context, unused, next) {
context.args.data.uuid = uuidv4();
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = context.req.connection.remoteAddress;
if (context.args.data.json) {
context.args.data.json = JSON.stringify(context.args.data.json);
}
next();
});
// add data into related tables
Teams.afterRemote('create', function(context, team, next) {
let dataAr = [context.result.data];
let modifier = context.req.connection.remoteAddress;
let teamsId = team.id;
let relationsId;
let date = new Date().toISOString().slice(0, 19).replace('T', ' ');
function createRelationsWithTeams(relationsId) {
let query = 'insert into relations_with_teams (\n' +
'relations_id, \n' +
'teams_id, \n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + relationsId + '\',\n' +
'\'' + teamsId + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
// console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
dataAr.push(data);
// create relations_with_locations record
console.log('Done with team creation. ' +
'Created records in relations, locations, ' +
'teams and relations_with_teams');
context.result.relationsId = relationsId;
next();
}
});
}
function createRelation(locationsId) {
let password = generatePassword(12, false);
let description = context.args.data.relation.description ||
'Created with team';
let json = '{}';
if (context.args.data.relation && context.args.data.relation.json !==
undefined && context.args.data.relation.json !== null) {
json = JSON.stringify(context.args.data.relation.json);
}
let username = context.args.data.relation.username ||
context.args.data.relation.email;
let query = 'insert into relations (\n' +
'uuid, \n' +
'locations_id, \n' +
'firstname, \n' +
'prefix, \n' +
'lastname, \n' +
'phonenumber, \n' +
'email, \n' +
'username, \n' +
'password, \n' +
'description, \n' +
'json, \n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + uuidv4() + '\',\n' +
'\'' + locationsId + '\',\n' +
'\'' + context.args.data.relation.firstname + '\',\n' +
'\'' + context.args.data.relation.prefix + '\',\n' +
'\'' + context.args.data.relation.lastname + '\',\n' +
'\'' + context.args.data.relation.phonenumber + '\',\n' +
'\'' + context.args.data.relation.email + '\',\n' +
'\'' + username + '\',\n' +
'\'' + password + password + '\',\n' +
'\'' + description + '\',\n' +
'\'' + json + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
// console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
dataAr.push(data);
relationsId = data.insertId;
context.result.locationsId = locationsId;
// create relations_with_locations record
createRelationsWithTeams(relationsId);
}
});
}
// create locations record
let query = 'insert into locations (\n' +
'uuid, \n' +
'streetname, \n' +
'housenumber, \n' +
'postalcode, \n' +
'city, \n' +
'description, \n' +
'creationDate, \n' +
'createdBy, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
'\'' + uuidv4() + '\',\n' +
'\'' + context.args.data.location.streetname + '\',\n' +
'\'' + context.args.data.location.housenumber + '\',\n' +
'\'' + context.args.data.location.postalcode + '\',\n' +
'\'' + context.args.data.location.city + '\',\n' +
'\'created with team\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\',\n' +
'\'' + date + '\',\n' +
'\'' + modifier + '\'\n' +
');';
let params = [1];
// console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
dataAr.push(data);
let locationsId = data.insertId;
// create relations record
createRelation(locationsId);
}
});
});
function getQuery(id) {
return 'select r.id,\n' +
'r.uuid,\n' +
'r.firstname,\n' +
'r.prefix,\n' +
'r.lastname,\n' +
'concat(r.firstname, \' \', r.prefix, \' \',' +
' r.lastname) relationsName,\n' +
'r.phonenumber,\n' +
'r.email,\n' +
'r.description,\n' +
'r.json,\n' +
'l.id locationsId,\n' +
'l.streetname,\n' +
'l.housenumber,\n' +
'l.housenumber_suffix,\n' +
'l.postalcode,\n' +
'l.city\n' +
'from relations r\n' +
', locations l\n' +
', teams t\n' +
', relations_with_teams rwt\n' +
'where t.id = ' + id + '\n' +
'and l.id=r.locations_id\n' +
'and t.id=rwt.teams_id\n' +
'and r.id=rwt.relations_id';
}
// add data into related tables
Teams.afterRemote('find', function(context, team, next) {
let newResult = JSON.parse(JSON.stringify(context.result));
function getRelationsWithTeam(i, teams) {
if (i + 1 > teams.length || teams.length === 0) {
context.result = newResult;
next();
} else {
let id = teams[i].id;
let query = getQuery(id);
// console.log('>>>>>', query)
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
newResult[i].relations = data;
// console.log('>>>>> i', i);
// console.log('>>>>> data', data);
// console.log('>>>>> newResult', newResult[i]);
i = i + 1;
getRelationsWithTeam(i, team);
}
});
}
}
getRelationsWithTeam(0, newResult);
});
function getTasksWithTeam(context, next) {
let teamId = context.args.id;
let query = 'select ta.*\n' +
'from teams t\n' +
', relations_with_teams rwt\n' +
', relations r\n' +
', relations_with_tasks rwta\n' +
', tasks ta\n' +
'where t.id=rwt.teams_id\n' +
'and r.id=rwta.relations_id\n' +
'and ta.id=rwta.tasks_id\n' +
'and t.id=' + teamId + '\n' +
'group by ta.id';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
next(err);
} else {
context.result.tasks = data;
next();
}
});
}
// add data into related tables // replaceById
Teams.afterRemote('findById', function(context, team, next) {
console.log('>>>>> context.method.name', context.method.name);
console.log('>>>>>', context.args);
console.log('>>>>>', context.args.filter);
console.log('>>>>> context.result', context.result);
let query = getQuery(context.args.id);
// console.log('>>>>> query: ', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
next(err);
} else {
if (context.args.filter && context.args.filter.tasks) {
if (context.args.filter.relations !== undefined &&
context.args.filter.relations === false) {
context.result.relation = null;
} else {
context.result.relation = data;
}
getTasksWithTeam(context, next);
} else {
next();
}
}
});
});
Teams.beforeRemote('replaceById', function(context, team, next) {
// console.log('>>>>> context.method.name', context.method.name);
// console.log('>>>>> context.args.data', context.args.data);
// console.log('>>>>> context.result', context.result);
//
if (context.args.data.json !== undefined &&
context.args.data.json !== null) {
context.args.data.json = JSON.stringify(context.args.data.json);
}
function buildQuery(i, key, trailer) {
let clause = '';
if (context.args.data.relation[i][key] !== undefined &&
context.args.data.relation[i][key] !== null &&
key !== 'uuid') {
if (key === 'json') {
clause = key + ' = \'' +
JSON.stringify(context.args.data.relation[i][key]) + '\'' + trailer;
} else {
clause = key + ' = \'' +
context.args.data.relation[i][key] + '\'' + trailer;
}
} else {
clause = '';
}
return clause;
}
function updateLocation() {
if (context.args.data !== undefined &&
context.args.data.relation !== undefined) {
// console.log('xxxxx');
for (let i = 0; i < context.args.data.relation.length; i++) {
// console.log('iiiii', i);
let query = 'update locations set \n';
query += buildQuery(i, 'streetname', ',\n');
query += buildQuery(i, 'housenumber', ',\n');
query += buildQuery(i, 'housenumber_suffix', ',\n');
query += buildQuery(i, 'postalcode', ',\n');
query += buildQuery(i, 'city', ',\n');
query += 'modificationDate = \'' +
(new Date().toISOString().slice(0, 19).replace('T', ' ')) + '\',\n';
query += 'modifiedBy = \'' +
context.req.connection.remoteAddress + '\'\n';
query += 'where id = ' + context.args.data.relation[i].locationsId;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
}
});
next();
}
}
}
function updateRelation() {
if (context.args.data !== undefined &&
context.args.data.relation !== undefined) {
// console.log('xxxxx');
for (let i = 0; i < context.args.data.relation.length; i++) {
// console.log('iiiii', i);
let query = 'update relations set \n';
query += buildQuery(i, 'firstname', ',\n');
query += buildQuery(i, 'prefix', ',\n');
query += buildQuery(i, 'lastname', ',\n');
query += buildQuery(i, 'phonenumber', ',\n');
query += buildQuery(i, 'email', ',\n');
query += buildQuery(i, 'description', ',\n');
query += buildQuery(i, 'json', ',\n');
query += 'modificationDate = \'' +
(new Date().toISOString().slice(0, 19).replace('T', ' ')) + '\',\n';
query += 'modifiedBy = \'' +
context.req.connection.remoteAddress + '\'\n';
query += 'where id = ' + context.args.data.relation[i].id;
// console.log('>>>>> query: ', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
}
});
}
updateLocation();
}
}
updateRelation();
});
Teams.remoteMethod(
'create', {
http: {
path: '/',
verb: 'post',
},
returns: [
{arg: 'id', type: 'string'},
{arg: 'name', type: 'string'},
{arg: 'description', type: 'string'},
{arg: 'json', type: 'object'},
{
arg: 'relation', type: 'object', default: {
firstname: 'string',
prefix: 'string',
lastname: 'string',
phonenumber: 'string',
email: 'string',
description: 'string',
json: 'object',
},
},
{
arg: 'location', type: 'object', default: {
'streetname': 'string',
'housenumber': 'string',
'housenumberSuffix': 'string',
'postalcode': 'string',
'city': 'string',
},
},
],
accepts: [
{
arg: 'body',
type:
'object',
http: {
source: 'body',
},
required: true,
description:
'Pass an object from the example value.',
},
],
description:
'Creates Team model with Relation and Location Model.',
})
;
Teams.remoteMethod(
'replaceById', {
http: {
path: '/:id',
verb: 'put',
},
returns: [
{arg: 'id', type: 'string'},
{arg: 'uuid', type: 'string'},
{arg: 'name', type: 'string'},
{arg: 'description', type: 'string'},
{arg: 'json', type: 'object'},
{
arg: 'relation', type: 'object', default: [{
id: 'string',
uuid: 'string',
firstname: 'string',
prefix: 'string',
lastname: 'string',
phonenumber: 'string',
email: 'string',
description: 'string',
json: 'object',
locationsId: 'string',
streetname: 'string',
housenumber: 'string',
housenumberSuffix: 'string',
postalcode: 'string',
city: 'string',
},
],
},
],
accepts: [
{
arg: 'id',
type: 'string',
http: {source: 'path'},
required: true,
description:
'Model id',
},
{
arg: 'body',
type:
'object',
http: {
source: 'body',
},
required: true,
description:
'Pass an object from the example value.',
},
],
description:
'Updates Team model with Relation and Location Model.',
})
;
// Disabled remote methods
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
'delete',
'deleteById',
'exists',
// 'find',
// 'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
// 'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
Teams.disableRemoteMethodByName(methods[i]);
}
}
;
<file_sep>'use strict';
module.exports = function(StatusFlows) {
// Add extension code here
};
<file_sep>'use strict';
/**
* For anyone else having that problem with loopback 3 and Postman that on POST,
* the connection hangs (or returns ERR_EMPTY_RESPONSE) (seen in some comments here)...
* The problem in this scenario is, that Postman uses as
* Content-Type "application/x-www-form-urlencoded"!
* Please remove that header and add "Accept" = "multipart/form-data".
* I've already filed a bug at loopback for this behavior
* @see https://stackoverflow.com/questions/28885282/how-to-store-files-with-meta-data-in-loopback
*/
const uuidv4 = require('uuid/v4');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(Transactions) {
let modifier = '';
// Add extension code here
Transactions.beforeRemote('create', function(context, unused, next) {
context.args.data.uuid = uuidv4();
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
modifier = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
if (context.args.data.amountEuro == undefined ||
context.args.data.amountEuro == null) {
context.args.data.amountEuro = 0;
}
if (context.args.data.amountSc == undefined ||
context.args.data.amountSc == null) {
context.args.data.amountSc = 0;
}
context.args.data.modifiedby = context.req.connection.remoteAddress;
next();
});
Transactions.afterRemote('create', function(context, unused, next) {
let query = 'select count(1) cnt\nfrom relations_with_tasks\n' +
'where relations_id=' + context.result.relationsId + '\nand ' +
'tasks_id=' + context.result.tasksId;
// console.log('>>>>> afterRemote', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
// console.log('>>>>> data', data[0].cnt);
if (data[0].cnt == 0) {
// console.log('>>>>> data', data);
// console.log('>>>>> err', err);
query = 'insert into relations_with_tasks (\n' +
' relations_id, tasks_id, creationDate, createdBy, ' +
' modificationDate, modifiedBy) values (\n' +
context.result.relationsId + ', ' + context.result.tasksId + ', ' +
'now(), \'' + modifier + '\',' +
'now(), \'' + modifier + '\');';
// console.log('>>>>> afterRemote', query);
// console.log('>>>>> afterRemote context', context.result);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
context.result = data;
next();
}
});
} else {
next();
}
}
});
});
Transactions.afterRemote('find', function(context, unused, next) {
let filter = context.args.filter;
let clause = '';
if (filter) {
if (filter.where && filter.where.relationId) {
clause = ' r.id = ' + filter.where.relationId + '\nand ';
}
}
let query = 'select r.id relationId,\n' +
'r.firstname relationFirstname,\n' +
'r.prefix relationPrefix,\n' +
'r.lastname relationLastname,\n' +
'concat(r.firstname, \' \', r.prefix, \' \', r.lastname) ' +
'relationName,\n' +
'r.phonenumber relationPhonenumber,\n' +
'r.email relationEmail,\n' +
'r.description relationDescription,\n' +
'r.json relationJson,\n' +
'l.streetname locationStreetname,\n' +
'l.housenumber locationHousenumber,\n' +
'l.housenumber_suffix locationHousenumberSuffix,\n' +
'l.postalcode locationPostalcode,\n' +
'l.city locationCity,\n' +
't.id taskId,\n' +
't.name taskName,\n' +
't.description taskDescription,\n' +
't.json taskJson,\n' +
'tr.amount_euro transactionAmountLc,\n' +
'tr.amount_sc transactionAmountSc,\n' +
'tr.description transactionDescription,\n' +
'tr.json transactionJson\n' +
'from tasks t,\n' +
'relations r,\n' +
'transactions tr,\n' +
'locations l\n' +
'where ' + clause + 'r.id=tr.relations_id\n' +
'and t.id=tr.tasks_id\n' +
'and l.id=r.locations_id';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
context.result = data;
next();
}
});
});
// Disabled remote methods
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
'deleteById',
'exists',
// 'find',
// 'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
// 'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
Transactions.disableRemoteMethodByName(methods[i]);
}
};
<file_sep>'use strict';
const uuidv4 = require('uuid/v4');
let path = require('path');
let config = require('../../server/config.json');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
let generatePassword = require('<PASSWORD>');
let senderAddress = '<EMAIL>'; // Replace this address with your actual address
module.exports = function(Participants) {
Participants.beforeRemote('**', function(context, unused, next) {
console.log('>>>>>', context.method.name);
next();
});
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
Participants.disableRemoteMethodByName('update');
Participants.disableRemoteMethodByName('create');
Participants.disableRemoteMethodByName('patchOrCreate');
Participants.disableRemoteMethodByName('replaceOrCreate');
Participants.disableRemoteMethodByName('upsertWithWhere');
Participants.disableRemoteMethodByName('deleteById');
Participants.disableRemoteMethodByName('exists');
Participants.disableRemoteMethodByName('replaceById');
Participants.disableRemoteMethodByName('count');
Participants.disableRemoteMethodByName('findOne');
Participants.disableRemoteMethodByName('createChangeStream');
Participants.disableRemoteMethodByName('findById');
};
<file_sep>'use strict';
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(TasksWithStatus) {
// Add extension code here
TasksWithStatus.beforeRemote('create', function(context, unused, next) {
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = context.req.connection.remoteAddress;
next();
});
TasksWithStatus.beforeRemote('**', function(context, unused, next) {
console.log('>>>>> afterRemote TasksWithStatus', context.method.name);
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = context.req.connection.remoteAddress;
next();
});
//
TasksWithStatus.afterRemote('__get__statuses',
function(context, unused, next) {
let query = 'select s1.id fromId, s1.name fromName, ' +
's2.id toId, s2.name toName\n' +
'from status s1, status s2, socialcoin.status_flows sf\n' +
'where s1.uuid=sf.status_uuid\n' +
'and s2.uuid=sf.status_uuid1\n' +
// 'and s1.id>$1\n' +
'order by s1.displayOrder';
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
console.log('>>>>>', data);
}
});
console.log('>>>>> afterRemote TasksWithStatus', context.method.name);
next();
});
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
TasksWithStatus.disableRemoteMethodByName('deleteById');
};
<file_sep>'use strict';
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(RelationsWithTeams) {
// Add extension code here
RelationsWithTeams.beforeRemote('create', function(context, unused, next) {
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = context.req.connection.remoteAddress;
next();
});
RelationsWithTeams.afterRemote('find', function(context, unused, next) {
console.log('>>>>> context.args.filter', context.args.filter);
let clause = [];
if (context.args.filter) {
if (context.args.filter.where.relationsId) {
clause.push('relations_id = ' + context.args.filter.where.relationsId);
}
if (context.args.filter.where.teamsId) {
clause.push('teams_id = ' + context.args.filter.where.teamsId);
}
}
clause = clause.join(' and\n ');
if (clause !== '') {
clause += ' and\n';
}
let query = 'select r.id relationsId,\n' +
'r.uuid relationsUuid,\n' +
'r. locations_id relationLocationsId,\n' +
'r.firstname relationsFirstname,\n' +
'r.prefix relationsPrefix,\n' +
'r.lastname relationLastname,\n' +
'concat(' +
'r.firstname, \' \', r.prefix, \' \', r.lastname) relationsName,\n' +
'r.date_of_birth relationsDateOfBirth,\n' +
'r.phonenumber relationsPhonenumber,\n' +
'r.email relationsEmail,\n' +
'r.description relationsDescription,\n' +
'r.username relationsUsername,\n' +
'r.json relationsJson,\n' +
't.id teamsId,\n' +
't.name teamsName,\n' +
't.uuid teamsUuid,\n' +
't.description teamsDescription,\n' +
't.json teamsJson\n' +
'from relations_with_teams rwt\n' +
', relations r\n' +
', teams t\n' +
'where ' + clause + ' r.id=rwt.relations_id\n' +
'and t.id=rwt.teams_id';
console.log('>>>>>', query);
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
context.result = data;
}
next();
});
});
RelationsWithTeams.delete = function(body, cb) {
let relationsId = body.relationsId;
let teamsId = body.teamsId;
let query = 'delete from relations_with_teams \n' +
'where relations_id = ' + relationsId + '\n' +
'and teams_id = ' + teamsId;
let params = [];
console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(error, data) {
if (error) {
console.log(error);
cb(error);
} else {
console.log('>>>>> data', data);
cb(null, {'response': 'ok'});
}
});
};
RelationsWithTeams.remoteMethod(
'delete', {
http: {
path: '/',
verb: 'delete',
},
returns: [{
arg: 'relationsId',
type: 'Number',
}, {
arg: 'teamsId',
type: 'Number',
}],
accepts: {
arg: 'body',
type: 'object',
http: {source: 'body'},
required: true,
description: 'Pass an object from the example value.',
},
description: 'Delete a Relation with Role ' +
'from the RelationsWithTeams model.',
});
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
// RelationsWithTeams.disableRemoteMethodByName('deleteById');
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
'deleteById',
'exists',
// 'find',
// 'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
RelationsWithTeams.disableRemoteMethodByName(methods[i]);
}
};
<file_sep>'use strict';
const CONTAINERS_URL = '/api/containers/';
const uuidv4 = require('uuid/v4');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
const fs = require('fs');
const path = require('path');
module.exports = function(Files) {
let modifier = '';
Files.beforeRemote('**', function(context, unused, next) {
modifier = context.req.connection.remoteAddress;
next();
});
Files.upload = function(ctx, options, cb) {
function createActionRecord(fileObj, obj) {
// console.log('>>>> fileObj', fileObj, obj);
let query = 'insert into actions (uuid, description, ' +
'files_id, startDate, endDate, ' +
'duration, json, creationDate, createdBy, ' +
'modificationDate, modifiedBy) \nvalues (' +
'\'' + uuidv4() + '\', ' +
'\'' + fileObj.fields.description[0] + '\', ' +
'\'' + obj.id + '\', ' +
'now(), ' +
'now(), ' +
'\'' + fileObj.fields.effort[0] + '\',' +
'\'' + fileObj.fields.json[0] + '\',' +
'now(), ' +
'\'' + modifier + '\', ' +
'now(), ' +
'\'' + modifier + '\')';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
cb(null, err);
} else {
let actionId = data.insertId;
obj.actionId = actionId;
let query = 'insert into tasks_with_actions (' +
'tasks_id, actions_id, ' +
'creationDate, createdBy, ' +
'modificationDate, modifiedBy) \nvalues (' +
'\'' + fileObj.fields.taskId[0] + '\', ' +
'\'' + actionId + '\', ' +
'now(), ' +
'\'' + modifier + '\', ' +
'now(), ' +
'\'' + modifier + '\')';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
cb(null, err);
} else {
cb(null, obj);
}
});
}
});
}
if (!options) options = {};
ctx.req.params.container = 'tmp';
let newPath = 'common';
Files.app.models.container.upload(
ctx.req,
ctx.result,
options,
function(err, fileObj) {
if (err || !fileObj) {
cb(err);
} else {
var fileInfo = fileObj.files.file[0];
let oldFilename = fileInfo.name;
let extension = path.extname(oldFilename);
let newFilename = uuidv4() + extension;
fs.rename('./storage/tmp/' + oldFilename,
'./storage/' + newPath + '/' + newFilename,
function() {
Files.create({
name: fileInfo.name,
type: fileInfo.type,
container: fileInfo.container,
url: CONTAINERS_URL + 'common' +
'/download/' + newFilename,
}, function(err, obj) {
if (err !== null) {
cb(err);
} else {
obj.newFilename = newFilename;
obj.newPath = newPath;
createActionRecord(fileObj, obj);
}
});
});
}
});
};
Files.remoteMethod(
'upload',
{
description: 'Uploads a file',
accepts: [
{arg: 'ctx', type: 'object', http: {source: 'context'}},
{arg: 'options', type: 'object', http: {source: 'query'}},
],
returns: {
arg: 'fileObject', type: 'object', root: true,
},
http: {verb: 'post'},
});
};
<file_sep>'use strict';
const uuidv4 = require('uuid/v4');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(Debts) {
// Add extension code here
Debts.beforeRemote('create', function(context, unused, next) {
context.args.data.uuid = uuidv4();
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = context.req.connection.remoteAddress;
next();
});
Debts.afterRemote('find', function(context, unused, next) {
// filter example: {"where":{"and":[{"relationId":57},{"or":[{"statusId":0},{"statusId":34}]}]}}
let where = context.args.filter.where;
let and = where.and;
let relationId = 0;
let statusIds = [];
let clause = '';
for (let i = 0; i < and.length; i++) {
let arg = and[i];
if (arg.relationId !== undefined) {
relationId = arg.relationId;
}
if (arg.or) {
let or = arg.or;
for (let j = 0; j < or.length; j++) {
if (or[j].statusId) {
statusIds.push(or[j].statusId);
}
}
}
}
let statusId = statusIds.join(', ');
if (statusIds.length > 0) {
clause = ' and s.id in (' + statusId + ')\n';
}
let debts = {};
let query = 'select sum(debt_lc) debtsLc\n' +
'from debts d\n' +
'where relations_id = ' + relationId;
// console.log('>>>>>', query)
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
debts = data;
context.result = {};
context.result.debts = debts;
// let query = 'select sum(tr.amount_euro) amountLc,\n' +
// 'sum(tr.amount_sc) amountSc \n' +
// ', s.id statusId\n' +
// ', s.name statusName\n' +
// 'from transactions tr, \n' +
// 'tasks t,\n' +
// 'tasks_with_status swt,\n' +
// 'status s\n' +
// 'where \n' +
// 't.relations_id=' + relationId + '\n' + clause +
// 'and t.id=tr.tasks_id\n' +
// 'and t.id=swt.tasks_id\n' +
// 'and s.id=swt.status_id\n' +
// 'group by s.id;';
let query = 'select 0 amountLc,\n' +
'sum(t.value_sc) amountSc \n' +
', s.id statusId\n' +
', s.name statusName\n' +
'from tasks t,\n' +
'tasks_with_status swt,\n' +
'relations_with_tasks rwt,\n' +
'status s\n' +
'where \n' +
'rwt.relations_id=' + relationId + '\n' + clause +
'and t.id=swt.tasks_id\n' +
'and s.id=swt.status_id\n' +
'and t.id=rwt.tasks_id\n' +
'group by s.id;';
console.log('>>>>>', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
let payedOffLc = 0;
let payedOffSc = 0;
for (let i = 0; i < data.length; i++) {
if (data[i].statusId === 34) {
payedOffLc = data[i].amountLc;
payedOffSc = data[i].amountSc;
}
}
let balanceLc = null;
if (context.result.debts[0].debtsLc) {
balanceLc = context.result.debts[0].debtsLc - payedOffLc;
}
context.result.balanceLc = balanceLc;
context.result.payedOffLc = payedOffLc;
context.result.payedOffSc = payedOffSc;
context.result.transactions = data;
console.log('>>>>>', context.result);
next();
}
});
}
});
});
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
// Disabled remote methods
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
'deleteById',
'exists',
// 'find',
'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
Debts.disableRemoteMethodByName(methods[i]);
}
};
<file_sep>// Copyright IBM Corp. 2014,2015. All Rights Reserved.
// Node module: loopback-example-user-management
// This file is licensed under the MIT License.
// License text available at https://opensource.org/licenses/MIT
'use strict';
let dsConfig = require('../datasources.json');
let path = require('path');
let server = require('../server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(app) {
let User = app.models.user;
let Relations = app.models.Relations;
// login page
app.get('/', function(req, res) {
let credentials = dsConfig.emailDs.transports[0].auth;
res.render('login', {
email: credentials.user,
password: <PASSWORD>,
});
});
// verified
app.get('/verified', function(req, res) {
res.render('verified');
});
// log a user in
app.post('/login', function(req, res) {
Relations.login({
email: req.body.email,
password: <PASSWORD>,
}, 'user', function(err, token) {
if (err) {
if (err.details && err.code === 'LOGIN_FAILED_EMAIL_NOT_VERIFIED') {
res.render('reponseToTriggerEmail', {
title: 'Login failed',
content: err,
redirectToEmail: '/api/relations/' + err.details.userId + '/verify',
redirectTo: '/',
redirectToLinkText: 'Click here',
userId: err.details.userId,
});
} else {
res.render('response', {
title: 'Login failed. Wrong username or password',
content: err,
redirectTo: '/',
redirectToLinkText: 'Please login again',
});
}
return;
}
res.render('home', {
email: req.body.email,
accessToken: token.id,
redirectUrl: '/api/relations/change-password?access_token=' + token.id,
});
});
});
// log a user out
app.get('/logout', function(req, res, next) {
if (!req.accessToken) return res.sendStatus(401);
User.logout(req.accessToken.id, function(err) {
if (err) return next(err);
res.redirect('/');
});
});
// send an email with instructions to reset an existing user's password
app.post('/request-password-reset', function(req, res, next) {
Relations.resetPassword({
email: req.body.email,
}, function(err) {
if (err) return res.status(401).send(err);
res.render('response', {
title: 'Password reset requested',
content: 'Check your email for further instructions',
redirectTo: '/',
redirectToLinkText: 'Log in',
});
});
});
// show password reset form
app.get('/reset-password', function(req, res, next) {
if (!req.accessToken) return res.sendStatus(401);
res.render('password-reset', {
redirectUrl: '/api/relations/reset-password?access_token=' +
req.accessToken.id,
});
});
// test shit
app.get('/ping', function(req, res) {
res.send('pongaroo');
});
app.get('/participantsxxxxx', function(req, res) {
if (!req.accessToken || !req.accessToken.id) {
res.send({
'error': {
'statusCode': 401,
'name': 'Error',
'message': 'Authorization Required',
'code': 'AUTHORIZATION_REQUIRED',
},
});
} else {
let query = 'select r.id,\n' +
'r.locations_id,\n' +
'r.firstname,\n' +
'r.prefix,\n' +
'r.lastname,\n' +
'r.date_of_birth,\n' +
'r.phonenumber,\n' +
'r.email,\n' +
'r.description,\n' +
'r.username,\n' +
'r.creationDate,\n' +
'r.createdBy,\n' +
'r.modificationDate,\n' +
'r.modifiedBy,\n' +
't.id teamId,\n' +
't.name teamName\n' +
', (select sum(debt_lc) from debts where relations_id=r.id) debt\n' +
'from (relations r, \n' +
'relations_with_roles rwr)\n' +
'left join relations_with_teams rwt on r.id=rwt.relations_id \n' +
'left join teams t on t.id=rwt.teams_id\n' +
'where r.id=rwr.relations_id\n' +
'and rwr.roles_id=12';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
res.send(data);
}
});
}
});
};
<file_sep>'use strict';
module.exports = function(Audit) {
// Add extension code here
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
Audit.disableRemoteMethodByName('deleteById');
};
<file_sep># Requirements
## Installation
Additional to provisioning.
- Requirements
- `sudo apt install build-essential`
- MySQL
- `sudo apt install -y mysql-server`
- `sudo mysql_secure_installation`
- Node en npm
- Install node & npm. First check version numbers on https://github.com/creationix/nvm
- `curl -sL https://raw.githubusercontent.com/creationix/nvm/v0.33.11/install.sh -o install_nvm.sh`
- `. ./install_nvm.sh`
- `source ~/.profile`
- `nvm ls-remote|grep -i lts # To retrieve LTS versions`
- `nvm install 8.11.4`
- Loopback
- `npm install -g loopback-cli`
## Tunneling
MySQL `ssh -L 3308:socialcoin.tezzt.nl:3306 -f <EMAIL> -N`
Command to kill tunnels (on Mac) ```kill -9 `lsof|grep localhost|grep ssh|awk {'print $2'}` ```
# Configuration
Copy `server/datasources.json.default` to `server/datasources.json`.
Replace the default values that start with `MY-...` with applicable values.
# Import data
- Create user
- `mysql -u root -p`
- `create user 'socialcoin'@'%' identified by 'MY-PASSWORD';`
- `grant all privileges on *.* to 'socialcoin'@'%' identified by 'MY-PASSWORD';`
- From the project root directory, run `mysql -u root -p < database/dump.sql`
# Discovery
- From the root of the project folder, run `node server/bin/discovery-and-build.js`
- Modify `server/model-config.json` and add all the models. This is a manual step.
- Restart node with `pm2 restart server/server.js`
# Running
From the root of the project folder, run `node .`
# Generate Swagger documentation
`lb export-api-def --o /var/www/html/api.yml.txt`
Make sure the first three lines are:
```
swagger: '2.0'
host: '172.16.31.10:3000'
schemes: ['http']
```
# Copy to remote dir
- `rm -fr node_modules && scp -r * <EMAIL>:/home/theotheu/socialcoin-api
&& npm i && npm audit fix`
- Change port numbers to `3306` with `vi server/datasources.json server/bin/discovery-and-build.js`
- Change ip address of host `172.16.31.10` with `vi server/config.json`
# ACL
- From the root of the project folder, run `lb acl`
- Select options:
- `? Select the model to apply the ACL entry to: (all existing models)`
- `? Select the ACL scope: All methods and properties`
- `? Select the access type: All (match all types)`
- `? Select the role All users`
- `? Select the permission to apply Explicitly deny access`
- @see https://loopback.io/doc/en/lb3/ACL-generator.html
<file_sep>'use strict';
const should = require('should');
const supertest = require('supertest');
const uuidv4 = require('uuid/v4');
const server = require('../server/server');
let config = require('../server/config');
let localConfig = require('./config.json');
let ds = server.dataSources.socialcoinDb;
describe('API Routing for CRUD operations on Relations', function() {
let relationId = 0;
let uuid = uuidv4();
let token = '';
let verificationToken = '';
const request = supertest(localConfig.scheme + '://' +
config.host + ':' +
config.port +
config.restApiRoot);
let email = 'theo.theunissen+' + uuid + '@gmail.com';
before(function(done) {
this.enableTimeouts(false);
request
.post('/Relations/login')
.send(localConfig.credentials)
.end(function(err, response) {
if (err || !response) {
done(err);
} else {
let json = JSON.parse(response.text);
let id = json.id;
token = id;
console.log('>>>>> Set up for Relations completed.');
done();
}
});
});
// Tear down
after(function(done) {
this.enableTimeouts(false);
let query = 'delete from relations where email = \'' + email + '\'';
let params = [1];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
console.log('>>>>> Tear down completed.');
}
done();
});
});
describe.skip('UN-Authenticaed access for Relations', function() {
it('Should NOT GET /Relations', function(done) {
request
.get('/Relations')
.expect(401) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(401);
done();
});
});
it('Should NOT DELETE /Relations', function(done) {
request
.get('/Relations/' + email)
.expect(401) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
// console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(401);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
});
describe('AUTHENTICATED access for Relations', function() {
let body = {
'firstname': 'John',
'prefix': '',
'lastname': 'Doe',
'dateOfBirth': '1970-01-01',
'phonenumber': '06-12345678',
'description': 'Master of socialcoin',
'username': 'johndoe',
'email': email,
'debt': '999',
'rolesId': config.testRoleId,
'teamsId': config.teamId,
'location': {
'streetname': 'My Streetnamess',
'housenumber': '123',
'postalcode': '1234AB',
'city': 'MyCity',
},
};
body.firstname = 'Test - ' + uuid;
body.username = 'Test - ' + uuid;
it('Should CREATE /Relations', function(done) {
this.enableTimeouts(false);
request
.post('/Relations?access_token=' + token)
.send(body)
.expect(200) // supertest
.expect('Content-Type', 'text/html; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('text/html');
res.charset.should.be.exactly('utf-8');
let query = 'select * ' +
'from relations where email = \'' + email + '\'';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
done(err);
} else {
verificationToken = data[0].verificationToken;
relationId = data[0].id;
// console.log('>>>>> data', data);
// console.log('>>>>> verificationToken', verificationToken);
// console.log('>>>>> relationId', relationId);
// console.log('>>>>> token', token);
done();
}
});
});
});
it('Should validate registration of /Relations', function(done) {
let url = '/Relations/confirm?uid=' + relationId +
'&redirect=%2Fverified&token=' + verificationToken;
request
.get(url)
.expect(302) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
done();
});
});
it('Should GET /Relations', function(done) {
request
.get('/Relations?access_token=' + token)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
// console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should GET /Relations/{id}', function(done) {
let url = '/Relations/' + relationId + '?access_token=' + token;
request
.get('/Relations/' + relationId + '/?access_token=' + token)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
// console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should GET /Relations/{id} with roles', function(done) {
let url = '/Relations/' + relationId +
'?filter=%7B%22roles%22%3Atrue%7D&access_token=' + token;
request
.get(url)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should NOT DELETE /Relations', function(done) {
request
.delete('/Relations/' + relationId + '?access_token=' + token)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
// console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Log out from /Relations', function(done) {
request
.post('/Relations/logout?access_token=' + token)
.expect(204) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(204);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
});
});
<file_sep>'use strict';
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(RelationsWithRoles) {
// Add extension code here
RelationsWithRoles.beforeRemote('create', function(context, unused, next) {
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = context.req.connection.remoteAddress;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = context.req.connection.remoteAddress;
next();
});
// get relations with roles if filter is applied
// @see https://loopback.io/doc/en/lb3/Where-filter.html
RelationsWithRoles.afterRemote('find', function(context, team, next) {
// console.log('>>>>> afterRemote, context.method.name: ', context.method.name);
// console.log('>>>>> afterRemote, context.args.data: ', context.args.data);
// console.log('>>>>> afterRemote, context.args.filter: ', context.args.filter);
let whereClause = '';
if (!context.args.filter && !context.args.filter.rolesId) {
let error = new Error();
error.status = 500;
error.message = 'rolesId must be a positive integer';
error.code = 'NUMBER_REQUIRED';
next(error);
} else {
whereClause = 'rwr.roles_id=' + context.args.filter.rolesId + ' and ';
let query = 'select r.id relationsId,\n' +
'concat(r.firstname, \' \', r.prefix, \' \',' +
' r.lastname) relationsName,\n' +
'r.email,\n' +
'r.phonenumber\n' +
'from relations r\n' +
', relations_with_roles rwr \n' +
', roles ro\n' +
'where ' + whereClause + ' r.id=rwr.relations_id\n' +
'and ro.id=rwr.roles_id \n' +
'group by r.id order by r.lastname, r.firstname;\n';
// console.log('Get relations with teams, if filter is applied');
// console.log(context.args.filter);
let params = [];
// console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(error, data) {
if (error) {
console.log(error);
next(error);
} else {
context.result = data;
next();
}
});
}
});
RelationsWithRoles.create = function(body, cb) {
let relationsId = body.relationsId;
let rolesId = body.rolesId;
let query = 'insert into relations_with_roles (\n' +
'relations_id, \n' +
'roles_id, \n' +
'createdBy, \n' +
'creationDate, \n' +
'modificationDate, \n' +
'modifiedBy) values (\n' +
relationsId + ', \n' +
rolesId + ', \n' +
rolesId + ', \n' +
'\'' + new Date().toISOString() + '\', \n' +
'\'' + context.req.connection.remoteAddress + '\', \n' +
'\'' + new Date().toISOString() + '\', \n' +
'\'' + context.req.connection.remoteAddress + '\')\n';
let params = [];
console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(error, data) {
if (error) {
console.log(error);
cb(error);
} else {
cb(null, {'response': 'ok'});
}
});
};
RelationsWithRoles.delete = function(body, cb) {
let relationsId = body.relationsId;
let rolesId = body.rolesId;
let query = 'delete from relations_with_roles \n' +
'where relations_id = ' + relationsId + '\n' +
'and roles_id = ' + rolesId;
let params = [];
// console.log('>>>>> query: ', query);
ds.connector.execute(query, params, function(error, data) {
if (error) {
console.log(error);
cb(error);
} else {
cb(null, {'response': 'ok'});
}
});
};
RelationsWithRoles.remoteMethod(
'delete', {
http: {
path: '/',
verb: 'delete',
},
returns: [{
arg: 'relationsId',
type: 'Number',
}, {
arg: 'rolesId',
type: 'Number',
}],
accepts: {
arg: 'body',
type: 'object',
http: {source: 'body'},
required: true,
description: 'Pass an object from the example value.',
},
description: 'Delete a Relation with Role ' +
'from the RelationsWithRoles model.',
});
RelationsWithRoles.remoteMethod(
'create', {
http: {
path: '/',
verb: 'post',
},
returns: [{
arg: 'relationsId',
type: 'Number',
}, {
arg: 'rolesId',
type: 'Number',
}],
accepts: {
arg: 'body',
type: 'object',
http: {source: 'body'},
required: true,
description: 'Pass an object from the example value.',
},
description: 'Creates a Relation with Role ' +
'from the RelationsWithRoles model.',
});
// The deleteById() operation and the corresponding REST endpoint will not be publicly available
// RelationsWithRoles.disableRemoteMethodByName('deleteById');
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
'deleteById',
'exists',
// 'find',
'findById',
'findOne',
'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
RelationsWithRoles.disableRemoteMethodByName(methods[i]);
}
};
<file_sep>'use strict';
const should = require('should');
const supertest = require('supertest');
const uuidv4 = require('uuid/v4');
const server = require('../server/server');
let config = require('../server/config');
let localConfig = require('./config.json');
let ds = server.dataSources.socialcoinDb;
describe('API Routing for CRUD operations on Tasks', function() {
const request = supertest(localConfig.scheme + '://' +
config.host + ':' +
config.port +
config.restApiRoot);
let uuid = uuidv4();
let taskId = 0;
let token = null;
let verificationToken = '';
let relationsId = 0;
let locationsId = 0;
let username = 'tasks.test.js.' + uuid;
let email = username + '@example.com';
let body = {};
before(function(done) {
this.enableTimeouts(false);
request
.post('/Relations/login')
.send(localConfig.credentials)
.end(function(err, response) {
if (err) {
console.log(err);
done(err);
}
let json = JSON.parse(response.text);
let id = json.id;
token = id;
let body = {
'firstname': 'John',
'prefix': '',
'lastname': 'Doe',
'dateOfBirth': '1970-01-01',
'phonenumber': '06-12345678',
'description': 'Created in test for Tasks',
'username': username,
'email': email,
'debt': '999',
'teamsId': config.testTeamId,
'rolesId': config.testRoleId,
'location': {
'streetname': 'My Streetnames',
'housenumber': '123',
'postalcode': '1234AB',
'city': 'MyCity',
},
};
body.firstname = 'TasksTest-' + uuid;
body.username = email;
request
.post('/Relations?access_token=' + token)
.send(body)
.expect(200) // supertest
.expect('Content-Type', 'text/html; charset=utf-8') // supertest
.end(function(err, res) {
console.log('>>>>> res', res.body);
if (err) {
throw err;
}
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('text/html');
res.charset.should.be.exactly('utf-8');
let query = 'select * ' +
'from relations where email = \'' + email + '\'';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log('>>>>> err', err);
done(err);
} else {
verificationToken = data[0].verificationToken;
relationsId = data[0].id;
done();
}
});
});
});
})
;
// Tear down
after(function(done) {
this.enableTimeouts(false);
let query = 'delete from tasks_with_status where tasks_id = ' + taskId;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
query = 'delete from tasks where id=' + taskId;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
}
query = 'delete from relations where email = \'' + email + '\'';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
query = 'delete from relations_with_tasks where ' +
'tasks_id=' + taskId;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
console.log('>>>>> Tear down completed.');
}
done();
});
}
});
});
}
});
});
describe.skip('UN-Authenticaed access for Tasks', function() {
it('Should NOT GET /Tasks', function(done) {
request
.get('/Tasks')
.expect(401) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(401);
done();
});
});
it('Should NOT DELETE /Tasks', function(done) {
request
.get('/Tasks/' + taskId)
.expect(401) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
// console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(401);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
});
describe('AUTHENTICATED access for Tasks', function() {
it('Should have created a USER for this test session', function(done) {
request
.get('/Relations/' + relationsId + '?access_token=' + token)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should CREATE /Tasks', function(done) {
body = {
'relationsId': relationsId,
'name': 'Test - ' + uuid,
'description': 'string',
'valueSc': 0,
'locationdescription': 'string',
'startdate': '2018-08-11T10:33:57.565Z',
'enddate': '2018-08-11T10:33:57.565Z',
'location': {
'streetname': 'string',
'housenumber': 'string',
'city': 'string',
'housenumber_suffix': 'string',
'postalcode': 'string',
'description': 'string',
'latitude': 'string',
'longitude': 'string',
'json': {},
},
};
request
.post('/Tasks?access_token=' + token)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.send(body)
.end(function(err, res) {
if (err) {
throw err;
}
let json = JSON.parse(res.text);
taskId = json.id;
locationsId = json.location.id;
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should PATCH /Tasks (minimal updates)', function(done) {
let body = {};
request
.patch('/Tasks/' + taskId + '?access_token=' + token)
.expect(200) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.send(body)
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(200);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should GET /Tasks/{id} (verify minimal update)', function(done) {
let statusCode = 200;
request
.get('/Tasks/' + taskId + '?access_token=' + token)
.expect(statusCode)
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(statusCode);
let json = JSON.parse(res.text);
let taskObj = json[0];
json.length.should.be.exactly(1);
let keys = [
{name: 'taskId', value: '', type: 'number'},
{name: 'taskUuid', value: '', type: 'string'},
{name: 'taskName', value: '', type: 'string'},
{name: 'taskDescription', value: '', type: 'string'},
{name: 'taskValueSc', value: '', type: 'number'},
{name: 'taskPhonenumber', value: '', type: 'string'},
{name: 'taskEmail', value: '', type: 'string'},
{name: 'taskStartDate', value: '', type: 'string'},
{name: 'taskEndDate', value: '', type: 'string'},
{name: 'taskEffort', value: '', type: 'number'},
{name: 'taskCreationDate', value: '', type: 'string'},
{name: 'taskCreatedBy', value: null, type: ''},
{name: 'taskModificationDate', value: '', type: 'string'},
{name: 'taskModifiedBy', value: '', type: 'string'},
{name: 'taskLocationDescription', value: '', type: 'string'},
{name: 'taskLocationId', value: '', type: 'number'},
{name: 'statusId', value: '', type: 'number'},
{name: 'locationStreetname', value: '', type: 'string'},
{name: 'locationHousenumber', value: '', type: 'string'},
{name: 'locationHousenumberSuffix', value: '', type: 'string'},
{name: 'taskLocationPostalcode', value: '', type: 'string'},
{name: 'taskLocationCity', value: '', type: 'string'},
{name: 'taskLocationLatitude', value: '', type: 'string'},
{name: 'taskLocationLongitude', value: '', type: 'string'},
{name: 'taskLocationDescription', value: '', type: 'string'},
{name: 'taskLocationJson', value: '', type: 'string'},
{name: 'statusId', value: '', type: 'number'},
{name: 'statusUuid', value: '', type: 'string'},
{name: 'statusName', value: '', type: 'string'},
{name: 'statusDescription', value: null, type: 'string'},
{name: 'statusJson', value: null, type: 'string'},
{name: 'relations', value: '', type: 'object'},
{name: 'actions', value: '', type: 'object'},
];
for (let i = 0; i < keys.length; i++) {
let keyName = keys[i].name;
// Test for keys
taskObj.should.have.key(keyName);
// Test for null values
if (keys[i].value === null) {
if (taskObj[keyName] !== null) {
let err = new Error(keyName + ' should be null.');
console.log(err);
}
should.not.exist(taskObj[keyName]);
} else {
if (taskObj[keyName] === null) {
let err = new Error(keyName + ' should not be null.');
console.log(err);
}
should.exist(taskObj[keyName]);
}
// Test for types
if (keys[i].type !== '' && taskObj[keyName] !== null) {
let obj = taskObj[keyName];
let type = keys[i].type;
if (!(typeof obj === type)) {
let err = new Error(keyName + ' should be of type ' +
keys[i].type) + '. It is ' + (taskObj[keyName].constructor);
console.log(err);
}
taskObj[keyName].should.be.type(keys[i].type);
}
}
done();
});
});
it('Should PATCH /Tasks (full updates)', function(done) {
let body = {
'uuid': 'b0eb00b8-2aea-4790-b34c-55f9c509131d',
'name': 'Updated Daycare (TESTING)',
'description': 'Updated Lorem ipsum',
'valueSc': 40,
'phonenumber': 'Updated 0123456789',
'email': '<EMAIL>',
'startDate': null,
'endDate': null,
'effort': 0,
'relation': {
'id': relationsId,
'uuid': '1',
'firstname': 'updated John',
'prefix': 'updated ',
'lastname': 'updated Doe',
'dateOfBirth': '1964-11-02',
'phonenumber': 'updated 06-28617829',
'email': email,
'description': 'updated',
'json': {'a': 'updated '},
},
'location': {
'id': locationsId,
'description': 'updated participant',
'streetname': 'Updated Valkstraat',
'housenumber': 'Updated 6',
'housenumberSuffix': null,
'postalcode': 'Updated 6611KW',
'city': 'Updated Overasselt',
'latitude': null,
'longitude': null,
'json': {'a': 'updated '},
},
'role': {
'roleId': 12,
'roleUuid': '716a38bd-96fe-11e8-99ba-8e9c42f3e967',
'roleName': 'Participant',
},
'status': {
'id': 33,
'uuid': 'bd612f02-96fe-11e8-99ba-8e9c42f3e967',
'statusName': 'Pending for approval',
'description': null,
'json': {'a': 1},
},
};
let statusCode = 200;
request
.patch('/Tasks/' + taskId + '?access_token=' + token)
// .set('Accept', 'application/json;')
// .set('Content-Type', 'application/json;')
// .set('Accept-Encoding', 'gzip, deflate, br;')
// .set('Content-length', JSON.stringify(body).length)
// .set('Content-Type', 'application/x-www-form-urlencoded')
.send(body)
.expect(statusCode) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
// console.log('??????', res.text)
if (err) {
throw err;
}
res.statusCode.should.be.exactly(statusCode);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
let json = JSON.parse(res.text);
done();
});
});
it('Should GET /Tasks/{id} (verify full update)', function(done) {
let statusCode = 200;
request
.get('/Tasks/' + taskId + '?access_token=' + token)
.expect(statusCode)
.end(function(err, res) {
if (err) {
throw err;
}
res.statusCode.should.be.exactly(statusCode);
let json = JSON.parse(res.text);
let taskObj = json[0];
json.length.should.be.exactly(1);
let keys = [{name: 'taskName', value: '', type: 'string'},
{name: 'taskId', value: '', type: 'number'},
{name: 'taskUuid', value: '', type: 'string'},
{name: 'taskName', value: '', type: 'string'},
{name: 'taskDescription', value: '', type: 'string'},
{name: 'taskValueSc', value: '', type: 'number'},
{name: 'taskPhonenumber', value: '', type: 'string'},
{name: 'taskEmail', value: '', type: 'string'},
{name: 'taskStartDate', value: '', type: 'string'},
{name: 'taskEndDate', value: '', type: 'string'},
{name: 'taskEffort', value: '', type: 'number'},
{name: 'taskCreationDate', value: '', type: 'string'},
{name: 'taskCreatedBy', value: null, type: ''},
{name: 'taskModificationDate', value: '', type: 'string'},
{name: 'taskModifiedBy', value: '', type: 'string'},
{name: 'taskLocationDescription', value: '', type: 'string'},
{name: 'taskLocationId', value: '', type: 'number'},
{name: 'statusId', value: '', type: 'number'},
{name: 'locationStreetname', value: '', type: 'string'},
{name: 'locationHousenumber', value: '', type: 'string'},
{name: 'locationHousenumberSuffix', value: '', type: 'string'},
{name: 'taskLocationPostalcode', value: '', type: 'string'},
{name: 'taskLocationCity', value: '', type: 'string'},
{name: 'taskLocationLatitude', value: '', type: 'string'},
{name: 'taskLocationLongitude', value: '', type: 'string'},
{name: 'taskLocationDescription', value: '', type: 'string'},
{name: 'taskLocationJson', value: '', type: 'string'},
{name: 'statusId', value: '', type: 'number'},
{name: 'statusUuid', value: '', type: 'string'},
{name: 'statusName', value: '', type: 'string'},
{name: 'statusDescription', value: null, type: 'string'},
{name: 'statusJson', value: null, type: 'string'},
{name: 'relations', value: '', type: 'object'},
{name: 'actions', value: '', type: 'object'},
];
for (let i = 0; i < keys.length; i++) {
let keyName = keys[i].name;
// Test for keys
taskObj.should.have.key(keyName);
// Test for null values
if (keys[i].value === null) {
if (taskObj[keyName] !== null) {
let err = new Error(keyName + ' should be null.');
console.log(err);
}
should.not.exist(taskObj[keyName]);
} else {
if (taskObj[keyName] === null) {
let err = new Error(keyName + ' should not be null.');
console.log(err);
}
should.exist(taskObj[keyName]);
}
// Test for types
if (keys[i].type !== '' && taskObj[keyName] !== null) {
let obj = taskObj[keyName];
let type = keys[i].type;
if (!(typeof obj === type)) {
let err = new Error(keyName + ' should be of type ' +
keys[i].type) + '. It is ' + (taskObj[keyName].constructor);
console.log(err);
}
taskObj[keyName].should.be.type(keys[i].type);
}
}
done();
});
});
let fields = ['taskId', 'taskUuid', 'taskName', 'taskDescription',
'taskValueSc', 'taskPhonenumber', 'taskEmail', 'taskStartDate',
'taskEndDate', 'taskEffort', 'taskCreationDate', 'taskCreatedBy',
'taskModificationDate', 'taskModifiedBy',
'taskLocationId', 'locationStreetname', 'locationHousenumber',
'locationHousenumberSuffix', 'taskLocationPostalcode',
'taskLocationCity', 'taskLocationLatitude', 'taskLocationLongitude',
'taskLocationDescription', 'taskLocationJson',
'statusId', 'statusUuid', 'statusName',
];
it('Should GET /Tasks', function(done) {
let statusCode = 200;
request
.get('/Tasks?access_token=' + token)
.expect(statusCode) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
let json = JSON.parse(res.text);
let obj = {};
if (json.length > 0) {
obj = json[0];
}
let presentFieldCounter = 0;
for (let i = 0; i < fields.length; i++) {
if (obj[fields[i]] !== undefined) {
presentFieldCounter++;
}
}
if (presentFieldCounter !== fields.length) {
let err = new Error('There should be ' + fields.length +
' fields.' +
'The actual number of fields is ' + presentFieldCounter + '.');
console.log(err);
}
presentFieldCounter.should.be.exactly(fields.length);
res.statusCode.should.be.exactly(statusCode);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should GET /Tasks with filter applied', function(done) {
let filter = {'where': {'and': [{'roleId': 12}, {'taskId': 65}]}};
let filterEncoded = encodeURI(filter);
let statusCode = 200;
request
.get('/Tasks?' + filterEncoded + '&access_token=' + token)
.expect(statusCode) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
let json = JSON.parse(res.text);
console.log(json);
let obj = {};
if (json.length > 0) {
obj = json[0];
}
let presentFieldCounter = 0;
for (let i = 0; i < fields.length; i++) {
if (obj[fields[i]] !== undefined) {
presentFieldCounter++;
}
}
if (presentFieldCounter !== fields.length) {
let err = new Error('There should be ' + fields.length +
' fields.' +
'The actual number of fields is ' + presentFieldCounter + '.');
console.log(err);
}
presentFieldCounter.should.be.exactly(fields.length);
json.length.should.be.above(0);
res.statusCode.should.be.exactly(statusCode);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
it('Should NOT DELETE /Tasks', function(done) {
request
.delete('/Tasks/' + taskId + '?access_token=' + token)
.expect(404) // supertest
.expect('Content-Type', 'application/json; charset=utf-8') // supertest
.end(function(err, res) {
if (err) {
throw err;
}
// console.log('>>>>>', res.text);
res.statusCode.should.be.exactly(404);
res.type.should.be.exactly('application/json');
res.charset.should.be.exactly('utf-8');
done();
});
});
});
});
<file_sep>'use strict';
const uuidv4 = require('uuid/v4');
let server = require('../../server/server.js');
let ds = server.dataSources.socialcoinDb;
module.exports = function(Tasks) {
let ctx = '';
let modifier = '';
// Add extension code here]
Tasks.beforeRemote('**', function(context, unused, next) {
ctx = context;
// console.log('>>>>> ctx', ctx.args);
modifier = context.req.connection.remoteAddress;
if (context && context.args && context.args.data) {
context.args.data.uuid = uuidv4();
context.args.data.locationsId = 1;
context.args.data.creationdate = new Date().toISOString();
context.args.data.createdby = modifier;
context.args.data.modificationdate = new Date().toISOString();
context.args.data.modifiedby = modifier;
context.args.data.phonenumber = context.args.data.phonenumber || '.';
context.args.data.email = context.args.data.email || '.';
}
next();
});
Tasks.afterRemote('create', function(context, unused, next) {
let taskId = context.result.id;
let locationId = 0;
let query = 'insert into tasks_with_status (' +
'tasks_id, status_id, creationDate, createdBy, ' +
'modificationDate, modifiedBy) \nvalues (' +
taskId + ', ' + 30 +
', now(), \'' + modifier + '\'' +
', now(), \'' + modifier + '\')';
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
// console.log('>>>>> context: ', context.args);
let uuid = uuidv4();
let relationsId = context.args.data.relationsId || 0;
let streetname = context.args.data.location.streetname || '';
let housenumber = context.args.data.location.housenumber || '';
let housenumberSuffix = context.args.data.location.housenumberSuffix ||
'';
let postalcode = context.args.data.location.postalcode || '';
let city = context.args.data.location.city || '';
let description = context.args.data.location.description || '';
let latitude = context.args.data.location.latitude || '';
let longitude = context.args.data.location.longitude || '';
let json = JSON.stringify(context.args.data.location.longitude || {});
let creationDate = 'now()';
let createdBy = modifier;
let modificationDate = 'now()';
let modifiedBy = modifier;
query = 'insert into locations (\n' +
'uuid, streetname, housenumber, housenumber_suffix, postalcode, ' +
'city, description, latitude, longitude, json, creationDate, ' +
'createdBy, modificationDate, modifiedBy)\nvalues (' +
'\'' + uuid + '\', ' +
'\'' + streetname + '\', ' +
'\'' + housenumber + '\', ' +
'\'' + housenumberSuffix + '\', ' +
'\'' + postalcode + '\', ' +
'\'' + city + '\', ' +
'\'' + description + '\', ' +
'\'' + latitude + '\', ' +
'\'' + longitude + '\', ' +
'\'' + json + '\', ' +
creationDate + ', ' +
'\'' + createdBy + '\', ' +
modificationDate + ', ' +
'\'' + modifiedBy + '\')';
// console.log('>>>>> query: ', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
locationId = data.insertId;
// console.log('>>>>> data: ', data);
let query = 'update tasks set locations_id=' + data.insertId +
'\nwhere id=' + taskId;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
// console.log('>>>>> context: ', context.args);
// console.log('>>>>> data: ', data);
let query = 'select count(1) cnt from relations_with_tasks\n' +
'where relations_id=' + relationsId +
'\nand tasks_id= ' + taskId;
let params = [];
// console.log('>>>>>qyert', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
if (data[0].cnt === 0) {
// console.log('>>>>> data: ', data);
let query = 'insert into relations_with_tasks\n(' +
'relations_id, tasks_id, creationDate, createdBy, ' +
'modificationDate, modifiedBy) values\n(' +
relationsId + ', ' + taskId + ', ' +
'now(), \'' + modifier + '\', ' +
'now(), \'' + modifier + '\');';
let params = [];
// console.log('>>>>>qyert', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
// console.log('>>>>> context: ', context.args);
data.locationId = locationId;
context.result.locationsId = locationId;
context.result.location.id = locationId;
next();
}
});
}
}
});
}
});
}
});
}
});
});
//
Tasks.beforeRemote('__updateById__statuses', function(context,
unused, next) {
// console.log('>>>>> afterRemote', context.method.name);
// console.log('>>>>> afterRemote', context.args.data);
});
//
Tasks.afterRemote('findById', function(context, unused, next) {
let filter = '';
if (context.args && context.args.filter) {
filter = context.args.filter;
}
let transactionsClause = '';
let tasks = [];
function getActions() {
let i = 0;
for (i = 0; i < tasks.length; i++) {
let task = tasks[i];
_getActions(i, task.taskId);
}
}
function _getActions(i, taskId) {
let query = 'select a.*, f.url\n' +
'from (actions a,\n' +
'tasks_with_actions twa)\n' +
'left join files f on f.id=a.files_id\n' +
'where twa.tasks_id=' + taskId + '\n' +
'and a.id=twa.actions_id\n';
let params = [];
// console.log('>>>>>', query)
ds.connector.execute(query, params, function(err, data) {
if (err) {
next(err);
return 'sssi';
} else {
tasks[i].actions = data;
}
if (i + 1 === tasks.length) {
context.result = tasks;
next();
}
});
}
function getRelations() {
let i = 0;
for (i = 0; i < tasks.length; i++) {
let task = tasks[i];
_getRelations(i, task.taskId);
}
}
function _getRelations(i, taskId) {
let clauses = [];
if (filter !== undefined && filter !== null &&
filter.where !== undefined && filter.where !== null) {
if (filter.where.and) {
for (let i = 0; i < filter.where.and.length; i++) {
if (filter.where.and[i].roleId !== undefined &&
filter.where.and[i].roleId !== null) {
clauses.push(' ro.id = ' + filter.where.and[i].roleId);
}
if (filter.where.and[i].relationId !== undefined &&
filter.where.and[i].relationId !== null) {
clauses.push(' r.id = ' + filter.where.and[i].relationId);
}
}
}
if (filter.where.roleId !== undefined && filter.where.roleId !== null) {
clauses.push(' ro.id = ' + filter.where.roleId);
}
if (filter.where.relationId !== undefined &&
filter.where.relationId !== null) {
clauses.push(' r.id = ' + filter.where.relationId);
}
}
let clausStr = '';
if (clauses.length > 0) {
clausStr = clauses.join(' and ') + ' and ';
}
let query = 'select r.id relationId,\n' +
'r.uuid relationUuid,\n' +
'r.firstname relationFirstname,\n' +
'r.prefix relationPrefix,\n' +
'r.lastname relationLastname,\n' +
'r.date_of_birth relationDateOfBirth,\n' +
'r.phonenumber relationPhonenumber,\n' +
'r.email relationEmail,\n' +
'r.json relationJson,\n' +
'r.description relationDescriptrion,\n' +
'l.id taskLocationId,\n' +
'l.streetname locationStreetname,\n' +
'l.housenumber locationHousenumber,\n' +
'l.housenumber_suffix locationHousenumberSuffix,\n' +
'l.postalcode taskLocationPostalcode,\n' +
'l.city taskLocationCity,\n' +
'l.latitude taskLocationLatitude,\n' +
'l.longitude taskLocationLongitude,\n' +
'l.description taskLocationDescription,\n' +
'l.json taskLocationJson,\n' +
'ro.id roleId,\n' +
'ro.uuid roleUuid,\n' +
'ro.name roleName\n' +
'from (relations r,\n' +
'locations l,\n' +
'relations_with_roles rwr,\n' +
'roles ro,\n' +
'relations_with_tasks rwt\n' +
')\n' +
'where ' + taskId + '=rwt.tasks_id and ' + clausStr + '\n' +
'l.id=r.locations_id\n' +
'and r.id=rwr.relations_id\n' +
'and ro.id=rwr.roles_id\n' +
'and r.id=rwt.relations_id';
// console.log('>>>>> quwey: ', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
// console.log('........', err);
console.log(err);
next(err);
} else {
tasks[i].relations = data;
}
// console.log('>>>>> i, tasks.length', i, tasks.length)
if (i + 1 === tasks.length) {
getActions();
}
});
}
function getTasks() {
let clauses = [];
let relationClause = '';
if (filter !== undefined && filter !== null &&
filter.where !== undefined && filter.where !== null) {
if (filter.where.and) {
for (let i = 0; i < filter.where.and.length; i++) {
if (filter.where.and[i].taskId !== undefined &&
filter.where.and[i].taskId !== null) {
clauses.push(' t.id = ' + filter.where.and[i].taskId);
}
if (filter.where.and[i].statusId !== undefined &&
filter.where.and[i].statusId !== null) {
clauses.push(' s.id = ' + filter.where.and[i].statusId);
}
if (filter.where.and[i].relationId !== undefined &&
filter.where.and[i].relationId !== null) {
relationClause = '\nand t.id in ' +
'(select tasks_id from relations_with_tasks ' +
'where relations_id=' + filter.where.and[i].relationId + ')';
}
}
}
if (filter.where.taskId !== undefined && filter.where.taskId !== null) {
clauses.push(' t.id = ' + filter.where.taskId);
}
if (filter.where.statusId !== undefined &&
filter.where.statusId !== null) {
clauses.push(' s.id = ' + filter.where.statusId);
}
if (filter.where.relationId !== undefined &&
filter.where.relationId !== null) {
relationClause = '\nand t.id in ' +
'(select tasks_id from relations_with_tasks ' +
'where relations_id=' + filter.where.relationId + ')';
}
}
let clausStr = '';
if (clauses.length > 0) {
clausStr = clauses.join(' and ');
}
let query = ' select t.id taskId,\n' +
't.uuid taskUuid,\n' +
't.name taskName,\n' +
't.description taskDescription,\n' +
't.value_sc taskValueSc,\n' +
't.phonenumber taskPhonenumber,\n' +
't.email taskEmail,\n' +
't.startDate taskStartDate,\n' +
't.endDate taskEndDate,\n' +
't.effort taskEffort,\n' +
't.creationDate taskCreationDate,\n' +
't.createdBy taskCreatedBy,\n' +
't.modificationDate taskModificationDate,\n' +
't.modifiedBy taskModifiedBy,\n' +
'l.id taskLocationId,\n' +
'l.streetname locationStreetname,\n' +
'l.housenumber locationHousenumber,\n' +
'l.housenumber_suffix locationHousenumberSuffix,\n' +
'l.postalcode taskLocationPostalcode,\n' +
'l.city taskLocationCity,\n' +
'l.latitude taskLocationLatitude,\n' +
'l.longitude taskLocationLongitude,\n' +
'l.description taskLocationDescription,\n' +
'l.json taskLocationJson,\n' +
's.id statusId,\n' +
's.uuid statusUuid,\n' +
's.name statusName,\n' +
's.description statusDescription,\n' +
's.json statusJson\n' +
'from (tasks t,\n' +
'locations l\n' +
')\n' +
'left join tasks_with_status swt on t.id=swt.tasks_id\n' +
'left join status s on s.id=swt.status_id \n' +
'where t.id=' + context.args.id + clausStr +
' and l.id=t.locations_id\n' +
relationClause;
// console.log('>>>>> quwey: ', query);
let params = [];
// console.log('>>>>> query:', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
next(err);
} else {
tasks = data;
getRelations();
}
});
}
getTasks();
});
//
Tasks.afterRemote('find', function(context, unused, next) {
let filter = '';
if (context.args && context.args.filter) {
filter = context.args.filter;
}
let transactionsClause = '';
let tasks = [];
function getActions() {
let i = 0;
for (i = 0; i < tasks.length; i++) {
let task = tasks[i];
_getActions(i, task.taskId);
}
}
function _getActions(i, taskId) {
let query = 'select a.*, f.url\n' +
'from (actions a,\n' +
'tasks_with_actions twa)\n' +
'left join files f on f.id=a.files_id\n' +
'where twa.tasks_id=' + taskId + '\n' +
'and a.id=twa.actions_id\n';
let params = [];
// console.log('>>>>>', query)
ds.connector.execute(query, params, function(err, data) {
if (err) {
next(err);
return 'sssi';
} else {
tasks[i].actions = data;
}
if (i + 1 === tasks.length) {
context.result = tasks;
next();
}
});
}
function getRelations() {
let i = 0;
for (i = 0; i < tasks.length; i++) {
let task = tasks[i];
_getRelations(i, task.taskId);
}
}
function _getRelations(i, taskId) {
let clauses = [];
if (filter !== undefined && filter !== null &&
filter.where !== undefined && filter.where !== null) {
if (filter.where.and) {
for (let i = 0; i < filter.where.and.length; i++) {
if (filter.where.and[i].roleId !== undefined &&
filter.where.and[i].roleId !== null) {
clauses.push(' ro.id = ' + filter.where.and[i].roleId);
}
if (filter.where.and[i].relationId !== undefined &&
filter.where.and[i].relationId !== null) {
clauses.push(' r.id = ' + filter.where.and[i].relationId);
}
}
}
if (filter.where.roleId !== undefined && filter.where.roleId !== null) {
clauses.push(' ro.id = ' + filter.where.roleId);
}
if (filter.where.relationId !== undefined &&
filter.where.relationId !== null) {
clauses.push(' r.id = ' + filter.where.relationId);
}
}
let clausStr = '';
if (clauses.length > 0) {
clausStr = clauses.join(' and ') + ' and ';
}
let query = 'select r.id relationId,\n' +
'r.uuid relationUuid,\n' +
'r.firstname relationFirstname,\n' +
'r.prefix relationPrefix,\n' +
'r.lastname relationLastname,\n' +
'r.date_of_birth relationDateOfBirth,\n' +
'r.phonenumber relationPhonenumber,\n' +
'r.email relationEmail,\n' +
'r.json relationJson,\n' +
'r.description relationDescriptrion,\n' +
'l.id taskLocationId,\n' +
'l.streetname locationStreetname,\n' +
'l.housenumber locationHousenumber,\n' +
'l.housenumber_suffix locationHousenumberSuffix,\n' +
'l.postalcode taskLocationPostalcode,\n' +
'l.city taskLocationCity,\n' +
'l.latitude taskLocationLatitude,\n' +
'l.longitude taskLocationLongitude,\n' +
'l.description taskLocationDescription,\n' +
'l.json taskLocationJson,\n' +
'ro.id roleId,\n' +
'ro.uuid roleUuid,\n' +
'ro.name roleName\n' +
'from (relations r,\n' +
'locations l,\n' +
'relations_with_roles rwr,\n' +
'roles ro,\n' +
'relations_with_tasks rwt\n' +
')\n' +
'where ' + taskId + '=rwt.tasks_id and ' + clausStr + '\n' +
'l.id=r.locations_id\n' +
'and r.id=rwr.relations_id\n' +
'and ro.id=rwr.roles_id\n' +
'and r.id=rwt.relations_id';
console.log('>>>>> quwey: ', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
// console.log('........', err);
console.log(err);
next(err);
} else {
tasks[i].relations = data;
}
console.log('>>>>>i + 1, tasks.length', i + 1, tasks.length);
if (i + 1 === tasks.length) {
getActions();
}
});
}
function getTasks() {
let clauses = [];
let relationClause = '';
if (filter !== undefined && filter !== null &&
filter.where !== undefined && filter.where !== null) {
if (filter.where.and) {
for (let i = 0; i < filter.where.and.length; i++) {
if (filter.where.and[i].taskId !== undefined &&
filter.where.and[i].taskId !== null) {
clauses.push(' t.id = ' + filter.where.and[i].taskId);
}
if (filter.where.and[i].statusId !== undefined &&
filter.where.and[i].statusId !== null) {
clauses.push(' s.id = ' + filter.where.and[i].statusId);
}
if (filter.where.and[i].relationId !== undefined &&
filter.where.and[i].relationId !== null) {
relationClause = '\nand t.id in ' +
'(select tasks_id from relations_with_tasks ' +
'where relations_id=' + filter.where.and[i].relationId + ')';
}
}
}
if (filter.where.taskId !== undefined && filter.where.taskId !== null) {
clauses.push(' t.id = ' + filter.where.taskId);
}
if (filter.where.statusId !== undefined &&
filter.where.statusId !== null) {
clauses.push(' s.id = ' + filter.where.statusId);
}
if (filter.where.relationId !== undefined &&
filter.where.relationId !== null) {
relationClause = '\nand t.id in ' +
'(select tasks_id from relations_with_tasks ' +
'where relations_id=' + filter.where.relationId + ')';
}
}
let clausStr = '';
if (clauses.length > 0) {
clausStr = clauses.join(' and ') + ' and ';
}
let query = ' select t.id taskId,\n' +
't.uuid taskUuid,\n' +
't.name taskName,\n' +
't.description taskDescription,\n' +
't.value_sc taskValueSc,\n' +
't.phonenumber taskPhonenumber,\n' +
't.email taskEmail,\n' +
't.startDate taskStartDate,\n' +
't.endDate taskEndDate,\n' +
't.effort taskEffort,\n' +
't.creationDate taskCreationDate,\n' +
't.createdBy taskCreatedBy,\n' +
't.modificationDate taskModificationDate,\n' +
't.modifiedBy taskModifiedBy,\n' +
'l.id taskLocationId,\n' +
'l.streetname locationStreetname,\n' +
'l.housenumber locationHousenumber,\n' +
'l.housenumber_suffix locationHousenumberSuffix,\n' +
'l.postalcode taskLocationPostalcode,\n' +
'l.city taskLocationCity,\n' +
'l.latitude taskLocationLatitude,\n' +
'l.longitude taskLocationLongitude,\n' +
'l.description taskLocationDescription,\n' +
'l.json taskLocationJson,\n' +
's.id statusId,\n' +
's.uuid statusUuid,\n' +
's.name statusName,\n' +
's.description statusDescription,\n' +
's.json statusJson\n' +
'from (tasks t,\n' +
'locations l\n' +
')\n' +
'left join tasks_with_status swt on t.id=swt.tasks_id\n' +
'left join status s on s.id=swt.status_id \n' +
'where ' + clausStr + ' l.id=t.locations_id\n' +
relationClause;
// console.log('>>>>> quwey: ', query);
let params = [];
// console.log('>>>>> query:', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
next(err);
} else {
tasks = data;
if (tasks.length > 0) {
getRelations();
} else {
context.result = tasks;
next();
}
}
});
}
getTasks();
});
Tasks.patchAttributes = function(taskId, body, cb) {
// console.log('>>>>> taskId', taskId);
// console.log('>>>>> body', body);
// console.log('>>>>> ctx', ctx.args);
let result = {};
function buildClause(obj, key, fieldname) {
let retVal = null;
// console.log('>>>>> obj, key', obj, key)
if (obj && key && (obj[key] !== undefined && obj[key] !== null &&
obj[key] !== 'null') || fieldname === '') {
if (key === 'json') {
retVal = fieldname + '=\'' + JSON.stringify(obj[key]) + '\'';
} else {
retVal = fieldname + '=\'' + obj[key] + '\'';
}
}
return retVal;
}
// update task
function updateTask() {
let clauseAr = [];
clauseAr.push(buildClause(body, 'name', 'name'));
clauseAr.push(buildClause(body, 'description', 'description'));
clauseAr.push(buildClause(body, 'phonenumber', 'phonenumber'));
clauseAr.push(buildClause(body, 'email', 'email'));
clauseAr.push(buildClause(body, 'valueSc', 'value_sc'));
clauseAr.push(buildClause(body, 'json', 'json'));
clauseAr.push(buildClause(body, 'startDate', 'startDate'));
clauseAr.push(buildClause(body, 'endDate', 'endDate'));
clauseAr.push(buildClause(body, 'effort', 'effort'));
clauseAr.push('modificationDate=now()');
clauseAr.push('modifiedBy=\'' + modifier + '\'');
let temp = [];
for (let i of clauseAr) {
i && temp.push(i); // copy each non-empty value to the 'temp' array
}
clauseAr = temp;
let clauses = clauseAr.join(',\n');
let query = 'update tasks set\n' + clauses + '\nwhere id = ' + taskId;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
result.task = data;
updateRelation();
}
});
}
// update relation
function updateRelation() {
if (body && body.relation) {
let relation = body.relation;
// console.log('>>>>> relation', body.relation, '<<<<<')
let clauseAr = [];
clauseAr.push(buildClause(relation, 'firstname', 'firstname'));
clauseAr.push(buildClause(relation, 'prefix', 'prefix'));
clauseAr.push(buildClause(relation, 'lastname', 'lastname'));
clauseAr.push(buildClause(relation, 'dateOfBirth', 'date_of_birth'));
clauseAr.push(buildClause(relation, 'phonenumber', 'phonenumber'));
clauseAr.push(buildClause(relation, 'email', 'email'));
clauseAr.push(buildClause(relation, 'description', 'description'));
clauseAr.push(buildClause(relation, 'json', 'json'));
clauseAr.push('modificationDate=now()');
clauseAr.push('modifiedBy=\'' + modifier + '\'');
let temp = [];
for (let i of clauseAr) {
i && temp.push(i); // copy each non-empty value to the 'temp' array
}
clauseAr = temp;
let clauses = clauseAr.join(',\n');
let query = 'update relations set\n' + clauses +
'\nwhere id = ' + relation.id;
let params = [];
// console.log('>>>>> updateRelation query:', query);
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
result.relation = data;
}
updateLocation();
});
} else {
updateLocation();
}
}
// update location
function updateLocation() {
if (body && body.location) {
let location = body.location;
let clauseAr = [];
clauseAr.push(buildClause(location, 'streetname', 'streetname'));
clauseAr.push(buildClause(location, 'housenumber', 'housenumber'));
clauseAr.push(buildClause(location, 'housenumberSuffix',
'housenumber_suffix'));
clauseAr.push(buildClause(location, 'postalcode', 'postalcode'));
clauseAr.push(buildClause(location, 'city', 'city'));
clauseAr.push(buildClause(location, 'latitude', 'latitude'));
clauseAr.push(buildClause(location, 'longitude', 'longitude'));
clauseAr.push(buildClause(location, 'description', 'description'));
clauseAr.push(buildClause(location, 'json', 'json'));
clauseAr.push('modificationDate=now()');
clauseAr.push('modifiedBy=\'' + modifier + '\'');
let temp = [];
for (let i of clauseAr) {
i && temp.push(i); // copy each non-empty value to the 'temp' array
}
clauseAr = temp;
let clauses = clauseAr.join(',\n');
let query = 'update locations set\n' + clauses +
'\nwhere id = ' + location.id;
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
result.location = data;
}
updateStatus();
});
// console.log('>>>>> query:', query);
} else {
updateStatus();
}
}
// update role
function updateStatus() {
let statusId = 0;
if (body.status && body.status.id) {
statusId = body.status.id;
let query = 'select id from tasks_with_status where tasks_id=' +
taskId;
// console.log('>>>>> query:', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
} else {
if (data.length === 0) {
query = 'insert into tasks_with_status (' +
'tasks_id, status_id, creationDate, createdBy, ' +
'modificationDate, modifiedBy) values (\n' +
taskId + ', ' + statusId + ',' +
'now(), ' +
'\'' + modifier + '\', ' +
'now(), ' +
'\'' + modifier + '\')';
} else {
query = 'update tasks_with_status set ' +
'status_id=' + statusId + ',\n' +
'modificationDate=now(),\n' +
'modifiedBy=\'' + modifier + '\' ' +
'where id = ' + data[0].id;
}
// console.log('>>>>> query:', query);
let params = [];
ds.connector.execute(query, params, function(err, data) {
if (err) {
console.log(err);
}
cb(null, result);
});
}
});
} else {
cb(null, result);
}
}
updateTask();
};
Tasks.remoteMethod(
'patchAttributes', {
http: {
path: '/:id',
verb: 'patch',
},
returns: [
{arg: 'tasksId', type: 'string'},
{arg: 'uuid', type: 'string'},
{arg: 'name', type: 'string'},
{arg: 'valueSc', type: 'Number'},
{arg: 'phonenumber', type: 'string'},
{arg: 'email;', type: 'string'},
{arg: 'startDate', type: 'string'},
{arg: 'endDate', type: 'string'},
{arg: 'effort', type: 'string'},
{arg: 'description', type: 'string'},
{arg: 'json', type: 'object'},
{
arg: 'relation', type: 'object', default: {
id: 'string',
uuid: 'string',
firstname: 'string',
prefix: 'string',
lastname: 'string',
phonenumber: 'string',
email: 'string',
description: 'string',
json: 'object',
locationsId: 'string',
streetname: 'string',
housenumber: 'string',
housenumberSuffix: 'string',
postalcode: 'string',
city: 'string',
latitude: 'string',
longitude: 'string',
},
},
// {
// arg: 'role', type: 'object', default: {
// id: 'string',
// uuid: 'string',
// name: 'string',
// },
// },
{
arg: 'status', type: 'object', default: {
id: 'string',
// uuid: 'string',
// name: 'string',
description: 'string',
json: 'object',
},
},
],
accepts: [
{
arg: 'id',
type: 'string',
http: {source: 'path'},
required: true,
description:
'Model id',
},
{
arg: 'body',
type:
'object',
http: {
source: 'body',
},
required: true,
description:
'Pass an object from the example value.',
},
],
description:
'Updates Team model with Relation and Location Model.',
})
;
// Disabled remote methods
let methods = [
'confirm',
'count',
// 'create',
'createChangeStream',
'deleteById',
'exists',
// 'find',
// 'findById',
'findOne',
// 'patchAttributes',
'patchOrCreate',
'prototype.__count__accessTokens',
'prototype.__create__accessTokens',
'prototype.__delete__accessTokens',
'prototype.__destroyById__accessTokens',
'prototype.__findById__accessTokens',
'prototype.__get__accessTokens',
'prototype.__updateById__accessTokens',
'prototype.updateAttributes',
// 'replaceById',
'replaceOrCreate',
'resetPassword',
'updateAll',
'upsert',
'upsertWithWhere',
];
for (let i = 0; i < methods.length; i++) {
Tasks.disableRemoteMethodByName(methods[i]);
}
};
<file_sep>'use strict';
module.exports = function(Privileges) {
// Add extension code here
};
|
5992f5216b222525469636dfa5b4daa3b325cc09
|
[
"JavaScript",
"Markdown"
] | 20 |
JavaScript
|
boschpeter/socialcoin-api
|
d6899e3555b82aabd5b154c7961c0f866f570cfa
|
aac25907ce642017d563802fea6940d76b620daa
|
refs/heads/master
|
<repo_name>bkopplin/quackathon<file_sep>/Quackathon2020/Assets/Scripts/PlayerController.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerController : MonoBehaviour
{
float verticalInput = 0;
float horizontalInput = 0;
float jumpForce = 5;
[SerializeField]
float speedHorizontal = 15;
float boundLeft = -20;
float boundRight = 20;
bool isOnGround = true;
Rigidbody rigidbody;
GameManager gameManager;
// Start is called before the first frame update
void Start()
{
rigidbody = GetComponent<Rigidbody>();
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update()
{
if (gameManager.isGameActive)
{
horizontalInput = Input.GetAxis("Horizontal");
transform.Translate(Vector3.right * horizontalInput * speedHorizontal * Time.deltaTime);
if (Input.GetKeyDown(KeyCode.Space) && isOnGround)
{
rigidbody.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
isOnGround = false;
}
if (transform.position.y < -20)
{
gameManager.GameOver();
}
}
}
private void OnCollisionEnter(Collision collision)
{
if (collision.gameObject.CompareTag("Ground"))
{
isOnGround = true;
}
}
void OnTriggerEnter(Collider other)
{
if (other.gameObject.CompareTag("Pick Up"))
{
other.gameObject.SetActive(false);
gameManager.UpdateScore(1);
}
if (other.gameObject.CompareTag("Speed Up"))
{
other.gameObject.SetActive(false);
StartCoroutine(SpeedUp());
}
if (other.gameObject.CompareTag("Duck"))
{
other.gameObject.SetActive(false);
gameManager.UpdateScore(-1);
}
}
private IEnumerator SpeedUp()
{
Time.timeScale = .5f;
yield return new WaitForSeconds(3);
Time.timeScale = 1.0f;
}
}
<file_sep>/Quackathon2020/Assets/Scripts/DuckMove.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using UnityEngine.UI;
public class DuckMove : MonoBehaviour
{
public int radius;
public float speed;
System.Random rand;
private int[] numbers = new int[2] { -1, 1 };
private float period = 0.3f;
private float nextActionTime = 0.1f;
// Start is called before the first frame update
void Start()
{
rand = new System.Random((int)DateTime.Now.Ticks);
}
// Update is called once per frame
void Update()
{
//if (Time.time > nextActionTime)
{
//nextActionTime += period;
// execute block of code here
int moveHorizontal = rand.Next(2);
Vector3 movement = new Vector3(numbers[moveHorizontal], 0.0f, 0.0f);
if ((transform.position + movement).x < (-2+radius) &&
(transform.position + movement).x > (+2-radius))
{
//transform.position = transform.position + movement;
transform.Translate(movement * Time.deltaTime * speed);
}
}
}
}
<file_sep>/Quackathon2020/Assets/Scripts/GameManager.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class GameManager : MonoBehaviour
{
public TextMeshProUGUI scoreText;
public TextMeshProUGUI DistanceText;
public GameObject titleScreen;
public TextMeshProUGUI gameOverText;
public Button restartButton;
private float score;
private float distance;
public bool isGameActive;
[SerializeField] GameObject [] assets;
public float horizontalBound = 3.0f;
float spawnRateMin = 1;
float spawnRateMax = 2;
float weightEnemy = 40;
float weightPowerup = 10;
float weightPoint = 10;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
IEnumerator SpawnObjects()
{
while (isGameActive)
{
yield return new WaitForSeconds(Random.Range(spawnRateMin, spawnRateMax));
int index = (int)RandomRange.Range(
new FloatRange(0f, 1f, weightEnemy),
new FloatRange(1f, 2f, weightPowerup),
new FloatRange(2f, 3f, weightPoint)
);
Instantiate(assets[index], RandomStartPos(), assets[index].transform.rotation);
Debug.Log("Spawn enemy");
}
}
IEnumerator DistanceUpdate()
{
while (isGameActive)
{
yield return new WaitForSeconds(1);
UpdateDistance(1);
}
}
Vector3 RandomStartPos()
{
float randomX = Random.Range(-horizontalBound, horizontalBound);
Debug.Log(randomX);
return new Vector3(randomX, 1, 30);
}
public void UpdateScore(int scoreToAdd)
{
score += scoreToAdd;
scoreText.text = "Score: " + score;
}
public void UpdateDistance(int distanceToAdd)
{
distance += distanceToAdd;
DistanceText.text = "Distance: " + distance + " km";
}
public void GameOver()
{
restartButton.gameObject.SetActive(true);
gameOverText.gameObject.SetActive(true);
isGameActive = false;
}
public void RestartGame()
{
SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
public void StartGame()
{
isGameActive = true;
score = 0;
distance = 0;
UpdateScore(0);
UpdateDistance(0);
StartCoroutine(SpawnObjects());
StartCoroutine(DistanceUpdate());
titleScreen.SetActive(false);
}
}
<file_sep>/Quackathon2020/Assets/Scripts/RandomRange.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public struct FloatRange
{
public float Min;
public float Max;
public float Weight;
public FloatRange(float min, float max, float weight)
{
Min = min;
Max = max;
Weight = weight;
}
}
public static class RandomRange
{
public static float Range(params FloatRange[] ranges)
{
if (ranges.Length == 0) { throw new System.ArgumentException("need more arguments"); }
if (ranges.Length == 1) { return Random.Range(ranges[0].Max, ranges[0].Min); }
float total = 0f;
for (int i = 0; i < ranges.Length; i++) { total += ranges[i].Weight; }
float randomNumber = Random.value;
float s = 0;
int count = ranges.Length - 1;
for (int i = 0; i < count; i++)
{
s += ranges[i].Weight / total;
// choose wheather or not to pick this range
if (s > randomNumber)
{
// return a random number from that range
return Random.Range(ranges[i].Max, ranges[i].Min);
}
}
return Random.Range(ranges[count].Max, ranges[count].Min);
}
}
<file_sep>/Quackathon2020/Assets/Scripts/MoveForward.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveForward : MonoBehaviour
{
[SerializeField] float speed = 10;
GameManager gameManager;
// Start is called before the first frame update
void Start()
{
gameManager = GameObject.Find("GameManager").GetComponent<GameManager>();
}
// Update is called once per frame
void Update()
{
if (gameManager.isGameActive)
{
gameObject.transform.Translate(Vector3.back * Time.deltaTime * speed);
}
}
}
|
07e98b5eb6ed1c059b9a9f6c36c16c3d11e0c364
|
[
"C#"
] | 5 |
C#
|
bkopplin/quackathon
|
ceaef66ccadaa859cfb59d8529cd52aa462c95e9
|
91858abf56d5f4517b3c515cf9679a0c82fdfc43
|
refs/heads/master
|
<repo_name>sam-lev/GraphSAGE<file_sep>/eval_scripts/test_eval.py
from __future__ import print_function
import json
from networkx.readwrite import json_graph
import numpy as np
import networkx as nx
from argparse import ArgumentParser
''' To evaluate the embeddings, we run a logistic regression.
Run this script after running unsupervised training.
Baseline of using features-only can be run by setting data_dir as 'feat'
Example:
python eval_scripts/ppi_eval.py ../data/ppi unsup-ppi/n2v_big_0.000010 test
python eval_scripts/ppi_eval.py (dataset_dir) ../example_data (embed_dir) ../unsup-example_data/graphsage_mean_small_0.000010 (setting) test
python eval_scripts/ppi_eval.py example_data unsup-example_data/graphsage_mean_small_0.000010 test
python eval_scripts/ppi_eval.py (dataset_dir) ../json_graphs (embed_dir) /Users/multivax/Documents/PhD/Research/topologicalComputing-Pascucci/TopoML/graphSage/GraphSAGE/unsup-json_graphs/graphsage_mean_small_0.000010 (setting) test
python eval_scripts/ppi_eval.py ../json_graphs /Users/multivax/Documents/PhD/Research/topologicalComputing-Pascucci/TopoML/graphSage/GraphSAGE/unsup-json_graphs/graphsage_mean_small_0.000010 test
'''
import os
def run_regression(train_embeds, train_labels, test_embeds, test_labels, test_node_ids = None, test_graph = None):
np.random.seed(1)
from sklearn.linear_model import SGDClassifier
from sklearn.dummy import DummyClassifier
from sklearn.metrics import f1_score
from sklearn.multioutput import MultiOutputClassifier
dummy = MultiOutputClassifier(DummyClassifier())
dummy.fit(train_embeds, train_labels)
log = MultiOutputClassifier(SGDClassifier(loss="log"), n_jobs=10)
log.fit(train_embeds, train_labels)
prediction = log.predict(test_embeds)
f1 = 0
for i in range(test_labels.shape[1]):
print("F1 score", f1_score(test_labels[:,i], prediction[:,i], average="binary"))
for i in range(test_labels.shape[1]):
print("Random baseline F1 score", f1_score(test_labels[:,i], dummy.predict(test_embeds)[:,i], average="micro"))
if test_graph:
prediction_prob={}
for id, pred in zip(range(len(test_node_ids)), prediction):
prediction_prob[id] = {'prediction':pred}#, 'prob_predict':prob_predict[id]}
nx.set_node_attributes(test_graph, prediction_prob)
print(test_graph.nodes[2])
if not os.path.exists( 'predicted_graph-G.json'):
open( 'predicted_graph-G.json', 'w').close()
with open( 'predicted_graph-G.json', 'w') as graph_file:
write_form = json_graph.node_link_data(test_graph)
json.dump(write_form, graph_file)
if __name__ == '__main__':
parser = ArgumentParser("Run evaluation on TEST data.")
parser.add_argument("dataset_dir", help="Path to directory containing the dataset.")
parser.add_argument("dataset_dir_test", help="Path to directory containing the dataset.")
parser.add_argument("embed_dir", help="Path to directory containing the learned node embeddings. Set to 'feat' for raw features.")
parser.add_argument("graph_set", help="Either val or test.")
parser.add_argument("graph_set_test", help="Either val or test.")
parser.add_argument("label_node_predictions", default=False, help="Either val or test.")
parser.add_argument("setting", help="Either val or test.")
args = parser.parse_args()
dataset_dir = os.path.join(os.getcwd(),args.dataset_dir)
dataset_dir_test = os.path.join(os.getcwd(),args.dataset_dir_test)
data_dir = os.path.join(os.getcwd(),args.embed_dir)
graph_set = args.graph_set
graph_set_test = args.graph_set_test
label_node_predictions = args.label_node_predictions
setting = args.setting
print("Loading data...")
G = json_graph.node_link_graph(json.load(open(dataset_dir + "/"+graph_set+"-G.json")))
G_test = json_graph.node_link_graph(json.load(open(dataset_dir_test + "/"+graph_set_test+"-G.json")))
labels = json.load(open(dataset_dir + "/"+graph_set+"-class_map.json"))
labels = {int(i):l for i, l in labels.items()}#iteritems()} #for python3
labels_test = json.load(open(dataset_dir_test + "/"+graph_set_test+"-class_map.json"))
labels_test = {int(i):l for i, l in labels_test.items()}#iteritems()} #for python3
train_ids = [n for n in G.nodes() if not G.node[n]['val'] and not G.node[n]['test']]
test_ids = [n for n in G_test.nodes() if G_test.node[n][setting]] #changed here!
train_labels = np.array([labels[i] for i in train_ids])
if train_labels.ndim == 1:
train_labels = np.expand_dims(train_labels, 1)
test_labels = np.array([labels_test[i] for i in test_ids])
print("running\n", data_dir)
if data_dir == "feat":
print("\n", "Using only features..","\n")
feats = np.load(dataset_dir + "/"+graph_set+"-feats.npy")
feats_test = np.load(dataset_dir_test + "/"+graph_set_test+"-feats.npy")
## Logistic gets thrown off by big counts, so log transform num comments and score
feats[:,0] = np.log(feats[:,0]+1.0)
feats[:,1] = np.log(feats[:,1]-min(np.min(feats[:,1]), -1))
feat_id_map = json.load(open(dataset_dir + "/"+graph_set+"-id_map.json"))
feat_id_map = {int(id):val for id,val in feat_id_map.items()}#iteritems()}
train_feats = feats[[feat_id_map[id] for id in train_ids]]
feats_test[:,0] = np.log(feats_test[:,0]+1.0)
feats_test[:,1] = np.log(feats_test[:,1]-min(np.min(feats_test[:,1]), -1))
feat_id_map_test = json.load(open(dataset_dir_test + "/"+graph_set_test+"-id_map.json"))
feat_id_map_test = {int(id):val for id,val in feat_id_map_test.items()}#iteritems()}
test_feats_test = feats_test[[feat_id_map_test[id] for id in test_ids_test]]
print("\n","Running regression..","\n")
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
scaler.fit(train_feats)
train_feats = scaler.transform(train_feats)
test_feats = scaler.transform(test_feats_test)
if not label_node_predictions:
run_regression(train_feats, train_labels, test_feats, test_labels)
else:
run_regression(train_feats, train_labels, test_feats, test_labels, test_ids, G_test)
else:
embeds = np.load(data_dir + "/val.npy")
id_map = {}
with open(data_dir + "/val.txt") as fp:
for i, line in enumerate(fp):
id_map[int(line.strip())] = i
train_embeds = embeds[[id_map[id] for id in train_ids]]
test_embeds = embeds[[id_map[id] for id in test_ids]]
print("Running regression..")
if not label_node_predictions:
run_regression(train_embeds, train_labels, test_embeds, test_labels)
else:
run_regression(train_embeds, train_labels, test_embeds, test_labels, test_ids, G_test)
<file_sep>/view_graph.py
import networkx
import networkx as nx
import json
from networkx.readwrite import json_graph
import matplotlib.pyplot as plt
G_data = json.load(open('./json_graphs/right_test_thro/right_test-G.json'))
G = json_graph.node_link_graph(G_data)
nx.draw_networkx(G, node_size=5,with_labels=False)
plt.draw()
plt.show()
|
be034fca86b52a4b8f65e6cb323875e54e58cf91
|
[
"Python"
] | 2 |
Python
|
sam-lev/GraphSAGE
|
79ffb0d2f88e6e375a5e241a95c48ad98b96ebae
|
ac629154ce500a091919c56e0d3c0dfef62506ff
|
refs/heads/master
|
<repo_name>kyle-copeland/unity-ui-example<file_sep>/Assets/Scripts/ScrollingText.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class ScrollingText : MonoBehaviour {
public CharacterSettings characterSettings;
public string sentence = "My body's ready!";
public float scrollSpeed;
private Text dialogueBox;
private char[] letters;
void Awake() {
dialogueBox = GetComponent<Text> ();
}
void Start () {
var dialogue = characterSettings.characterName + ": " + sentence;
letters = dialogue.ToCharArray();
StartCoroutine (GenerateText());
}
IEnumerator GenerateText() {
for (int i = 0; i < letters.Length; i++) {
dialogueBox.text += letters [i];
yield return new WaitForSeconds(scrollSpeed);
}
}
}
<file_sep>/Assets/ScriptableObjects/CharacterSettings.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
[CreateAssetMenu(menuName="Settings/Character")]
public class CharacterSettings : ScriptableObject {
public string characterName;
}
<file_sep>/Assets/Scripts/PlayerHealth.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PlayerHealth : MonoBehaviour {
public Transform healthPanel;
public void RemoveHealth() {
Destroy(healthPanel.GetChild (healthPanel.childCount - 1).gameObject);
}
}
<file_sep>/Assets/Scripts/Gun.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour {
public Transform bullet;
public float fireRate;
private void Start() {
InvokeRepeating ("Fire", fireRate, fireRate);
}
private void Fire() {
Instantiate (bullet);
}
}
<file_sep>/Assets/Scripts/HitPlayer.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Events;
public class HitPlayer : MonoBehaviour {
public UnityEvent onBulletHit;
private Animator anim;
private bool isVulnerable = true;
// Utilizing C# properties to manage vulnerability state
private bool Vulnerable {
get {
return isVulnerable;
}
set {
isVulnerable = value;
anim.SetBool ("isVulnerable", isVulnerable);
}
}
private void Awake() {
anim = GetComponent<Animator> ();
Vulnerable = true;
onBulletHit.AddListener (() => {
MakeInvulnerable();
});
}
private void OnTriggerEnter(Collider other) {
if(other.gameObject.CompareTag("Bullet")) {
Destroy (other.gameObject);
if (Vulnerable) {
onBulletHit.Invoke ();
}
}
}
private void MakeVulnerable() {
Vulnerable = true;
}
private void MakeInvulnerable() {
Vulnerable = false;
Invoke ("MakeVulnerable", 2.0f);
}
}<file_sep>/Assets/Scripts/CharacterDropdown.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class CharacterDropdown : MonoBehaviour {
public CharacterSettings characterSettings;
private Dropdown characterDropdown;
public void Awake() {
characterDropdown = GetComponent<Dropdown> ();
}
public void SetCharacterName(int optionSelected) {
characterSettings.characterName = characterDropdown.options[optionSelected].text;
}
}
|
76ac4506f155cad3c924007278011904eb667584
|
[
"C#"
] | 6 |
C#
|
kyle-copeland/unity-ui-example
|
5c3784fc07166c084b44dd6c54eb82df50c1eab9
|
ea98492356f4660e199ca67f3c1c444b92d4bcf6
|
refs/heads/master
|
<file_sep>// LABA7.cpp: определяет точку входа для консольного приложения.
//
#include "stdafx.h"
#include <iostream>
#include <thread>
#include <mutex>
#include <chrono>
#include <Windows.h>
#include <condition_variable>
using namespace std;
mutex f1,f2,f;
condition_variable cv;
bool ready = false;
void VivoB(mutex& m1, mutex& m2)
{
lock_guard <mutex> l1(m1);
this_thread::sleep_for(chrono::milliseconds(100));
lock_guard <mutex> l2(m2);
cout << "Hello1" << endl;
}
void VivoA(mutex& m1, mutex& m2)
{
lock_guard <mutex> l2(m2);
this_thread::sleep_for(chrono::milliseconds(100));
lock_guard <mutex> l1(m1);
cout << "Hello2" << endl;
}
void VivodB()
{
unique_lock<mutex> lck(f);
for (int i = 0; i < 10; i++)
{
this_thread::sleep_for(chrono::milliseconds(10));
cout << "bbbbb";
}
ready = true;
lck.unlock();
cv.notify_one();
for (int j = 0; j < 5; j++)
{
this_thread::sleep_for(chrono::milliseconds(10));
cout << "bbbbb";
}
}
void VivodA()
{
unique_lock<mutex> lck(f);
cv.wait(lck, [] {return ready; });
for (int i = 0; i < 5; i++)
{
this_thread::sleep_for(chrono::milliseconds(10));
cout << "aaaaa";
}
}
int main()
{
thread thr1(VivodB);
thread thr2(VivodA);
thread thr3(VivoB, f1, f2);
thread thr4(VivoA, f1, f2);
thr1.join();
thr2.join();
thr3.join();
thr4.join();
system("pause");
return 0;
}
|
a97571609b4a031ae635e705f279ca36955c3f2a
|
[
"C++"
] | 1 |
C++
|
3gpak/Lab-LP
|
4972c6c96c89503a5b93442780dcdcef991c3314
|
4b0243fef5a69be85e886c8c4e7cc51e6b4652ee
|
refs/heads/master
|
<file_sep>#ifndef _FCBF_
#define _FCBF_
#include <unordered_map>
#include <vector>
#include <string>
#include <list>
#include "ReadCsv.h"
#define MISSING_PROB -1
#define LOG2(X) (std::log(X)/std::log(2))
// TODO refactor into structs
#define PROB_HASH std::unordered_map<std::string, std::unordered_map<std::string, double>>
#define PROB_GIVEN_HASH std::unordered_map<std::string, std::unordered_map<std::string, std::unordered_map<std::string, std::unordered_map<std::string, double>>>>
double GetProb(std::string feature, std::string value, PROB_HASH & hash);
double GetGivenProb(std::string feature, std::string value, std::string given_feature, std::string given_value, PROB_GIVEN_HASH & hash);
int CalculateProbabilities(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string y_col_name);
int CalculateGivenProbabilities(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string column, std::string given_column);
double H(PROB_HASH & prob, std::string feature);
double H(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string feature, std::string given_feature);
double IG(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string feature, std::string given_feature);
double SU(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string feature, std::string given_feature);
int FCBF(DATA_SET & data, double min_threshold, std::string class_column, std::vector<std::string> & features);
bool TupleCompare(const std::pair<std::string, double> & x1, const std::pair<std::string, double> & x2);
#endif
<file_sep>#include "ReadCsv.h"
#include <iostream>
#include <fstream>
#include <sstream>
int GetKeys(const DATA_SET & data, std::vector<std::string> & keys)
{
keys.reserve(data.size());
for(auto it = data.begin(); it != data.end(); ++it)
{
keys.push_back(it->first);
}
return 0;
}
int ReadCsv(std::string fileName, DATA_SET & map, bool hasHeaders)
{
int numTokens, i;
std::vector<std::string> names;
std::ifstream input(fileName);
std::vector<std::string> headers;
if(hasHeaders)
{
ReadLine(input, headers);
}
int j = 1;
if(headers.empty())
{
std::stringstream convert;
std::string key;
while(input.good())
{
std::vector<std::string> row;
ReadLine(input, row);
numTokens = row.size();
for(i = 0; i < numTokens; i++)
{
map[convert.str()].push_back(row[i]);
convert.str("");
}
}
j++;
}
else
{
while(input.good())
{
std::vector<std::string> row;
ReadLine(input, row);
numTokens = row.size();
for(i = 0; i < numTokens; i++)
{
map[headers[i]].push_back(row[i]);
}
j++;
}
}
return 0;
}
int ReadLine(std::istream & input, std::vector<std::string> & row)
{
int returnCode = 0;
std::string rowString;
std::string token;
if(input.good())
{
std::getline(input, rowString);
std::stringstream stream(rowString);
if(!rowString.empty())
{
while(stream.good())
{
std::getline(stream, token, ',');
row.push_back(token);
}
}
}
else
{
returnCode = 1;
}
return returnCode;
}
<file_sep>require('rpart')
createFolds <- function(data, nfolds=10) {
folds <- list()
indexes <- split(sample(1:nrow(data)), 1:nfolds)
for(i in 1:length(indexes)) {
folds[[i]] <- data[indexes[[i]],]
}
return(folds)
}
tenFold <- function(folds, features, class_col='class') {
count_match <- numeric()
count_total <- numeric()
for(i in 1:10) {
test <- folds[[i]]
training <- NULL
for(j in 1:10) {
if(i != j) {
if(is.null(training)) {
training <- folds[[j]]
} else {
training <- rbind(training, folds[[j]])
}
}
}
model <- rpart(as.formula(paste(class_col, " ~ ", paste(features, collapse='+'), sep="")), training)
results <- predict(model, test, type="class")
count_total <- c(count_total, nrow(test))
temp_match <- 0
for(j in 1:nrow(test)) {
if(results[j] == test[j, class_col]) {
temp_match <- temp_match + 1
}
}
count_match <- c(count_match, temp_match)
}
return(data.frame(matches=count_match, total=count_total))
}
averageAccuracy <- function(result) {
percent <- function(x) {
x[['matches']] / x[['total']] * 100
}
return(mean(apply(result, 1, percent)))
}
car <- read.csv('car.csv')
car_folds <- createFolds(car)
writeLines('Car - All')
result <- tenFold(car_folds, setdiff(names(car), c("class")))
writeLines(paste(averageAccuracy(result), "%", sep=""))
writeLines('Car - FCBF')
result <- tenFold(car_folds, c('safety', 'persons'))
writeLines(paste(averageAccuracy(result), "%", sep=""))
writeLines('Car - MVM')
result <- tenFold(car_folds, c('doors', 'lug_boot', 'maint', 'buying'))
writeLines(paste(averageAccuracy(result), "%", sep=""))
mushroom <- read.csv('mushroom.csv')
mushroom_folds <- createFolds(mushroom)
writeLines('Mushroom - All')
result <- tenFold(mushroom_folds, setdiff(names(mushroom), c("class")))
writeLines(paste(averageAccuracy(result), "%", sep=""))
writeLines('Mushroom - FCBF')
result <- tenFold(mushroom_folds, c('odor', 'Spore.print.color', 'Stalk.surface.above.ring', 'Gill.size'))
writeLines(paste(averageAccuracy(result), "%", sep=""))
writeLines('Mushroom - MVM')
result <- tenFold(mushroom_folds, c('Veil.type', 'Stalk.shape', 'Gill.attachment', 'Veil.color'))
writeLines(paste(averageAccuracy(result), "%", sep=""))<file_sep>#include "ReadCsv.h"
#include "FCBF.h"
#include "MVM.h"
#include <iostream>
#include <vector>
#include <string>
#include <ctime>
#define FCBF_TYPE 0
#define MVM_TYPE 1
int RunTest(std::string file_name, int type, double threshold);
int RunTestSet(std::string set_name, std::string csv_file, double fcbf_threshold, double mvm_threshold);
int main(void)
{
//RunTestSet("Car", "car.csv", 0.2, 0.05);
//RunTestSet("Mushroom", "mushroom.csv", 0.2, 0.0475);
//RunTestSet("Soybean", "soybean-large.csv", 0.2, 0.0335);
//RunTestSet("Connect-4", "connect-4.csv", 0.01, 0.007);
RunTestSet("Car", "car.csv", 0, 1);
RunTestSet("Mushroom", "mushroom.csv", 0, 1);
RunTestSet("Soybean", "soybean-large.csv", 0, 1);
RunTestSet("Connect-4", "connect-4.csv", 0, 1);
return 0;
}
int RunTest(std::string file_name, int type, double threshold)
{
std::clock_t start;
double duration;
DATA_SET data;
std::vector<std::string> best_features;
ReadCsv(file_name, data);
start = std::clock();
if(type == FCBF_TYPE)
{
FCBF(data, threshold, "class", best_features);
}
else if(type == MVM_TYPE)
{
MVM(data, threshold, "class", best_features);
}
duration = ( std::clock() - start ) / (double) CLOCKS_PER_SEC;
std::cout << "Selected Features:" << std::endl;
for(auto it = best_features.begin(); it != best_features.end(); ++it)
{
std::cout << " " << *it << std::endl;
}
std::cout<<"Duration: "<< duration << " s" << std::endl;
return 0;
}
int RunTestSet(std::string set_name, std::string csv_file, double fcbf_threshold, double mvm_threshold) {
std::cout << set_name << " - FCBF" << std::endl;
RunTest(csv_file, FCBF_TYPE, fcbf_threshold);
std::cout << std::endl;
std::cout << set_name << " - MVM" << std::endl;
RunTest(csv_file, MVM_TYPE, mvm_threshold);
std::cout << std::endl;
return 0;
}
<file_sep>#include <cmath>
#include <utility>
#include <algorithm>
#include "FCBF.h"
double GetProb(std::string feature, std::string value, PROB_HASH & hash)
{
double probability = MISSING_PROB;
if(hash.count(feature) && hash[feature].count(value))
{
probability = hash[feature][value];
}
return probability;
}
double GetGivenProb(std::string feature, std::string value, std::string given_feature, std::string given_value, PROB_GIVEN_HASH & hash)
{
double probability = MISSING_PROB;
if(hash.count(feature) && hash[feature].count(value) && hash[feature][value].count(given_feature) && hash[feature][value][given_feature][given_value])
{
probability = hash[feature][value][given_feature][given_value];
}
return probability;
}
int CalculateProbabilities(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string y_col_name)
{
std::vector<std::string> keys;
if(GetKeys(data, keys))
{
// ERROR
}
else
{
// Calculate probabilities
for(auto it = keys.begin(); it != keys.end(); ++it)
{
std::string col_name = *it;
const std::vector<std::string> & column = data[col_name];
// Count Occurrences
for(auto col_it = column.begin(); col_it != column.end(); ++col_it)
{
std::string value = *col_it;
if(prob.count(col_name) && prob[col_name].count(value))
{
prob[col_name][value] += 1;
}
else
{
prob[col_name][value] = 1;
}
}
// Divide by total
int size = column.size();
std::unordered_map<std::string, double> & col_probs = prob[col_name];
for(auto val_it = col_probs.begin(); val_it != col_probs.end(); ++val_it)
{
col_probs[val_it->first] = val_it->second / size;
}
}
// Calculate given probabilities for the y column to every other column
const std::vector<std::string> & y_column = data[y_col_name];
int size = y_column.size();
for(auto it = keys.begin(); it != keys.end(); ++it)
{
std::string given_col_name = *it;
if(given_col_name != y_col_name)
{
const std::vector<std::string> & given_column = data[given_col_name];
// Count occurrences
for(int i = 0; i < size; i++)
{
std::string y_value = y_column[i];
std::string given_value = given_column[i];
if(given_prob.count(y_col_name) && given_prob[y_col_name].count(given_col_name) && given_prob[y_col_name][given_col_name].count(given_value) && given_prob[y_col_name][given_col_name][given_value].count(y_value))
{
given_prob[y_col_name][given_col_name][given_value][y_value] += 1;
}
else
{
given_prob[y_col_name][given_col_name][given_value][y_value] = 1;
}
}
// Divide by total
auto & column_probs = given_prob[y_col_name][given_col_name];
for(auto y_it = column_probs.begin(); y_it != column_probs.end(); ++y_it)
{
std::string given_value = y_it->first;
auto & given_column_probs = y_it->second;
int count_match = 0;
for(auto given_it = given_column_probs.begin(); given_it != given_column_probs.end(); ++given_it)
{
count_match += given_it->second;
}
for(auto given_it = given_column_probs.begin(); given_it != given_column_probs.end(); ++given_it)
{
std::string column_value = given_it->first;
given_prob[y_col_name][given_col_name][given_value][column_value] = given_it->second / count_match;
}
}
}
}
}
return 0;
}
int CalculateGivenProbabilities(DATA_SET data, PROB_GIVEN_HASH & given_prob, std::string column_name, std::string given_column_name)
{
const std::vector<std::string> & column = data[column_name];
int size = column.size();
const std::vector<std::string> & given_column = data[given_column_name];
// Count occurrences
for(int i = 0; i < size; i++)
{
std::string column_value = column[i];
std::string given_value = given_column[i];
if(given_prob.count(column_name) && given_prob[column_name].count(given_column_name) && given_prob[column_name][given_column_name].count(given_value) && given_prob[column_name][given_column_name][given_value].count(column_value))
{
given_prob[column_name][given_column_name][given_value][column_value] += 1;
}
else
{
given_prob[column_name][given_column_name][given_value][column_value] = 1;
}
}
// Divide by total
auto & column_probs = given_prob[column_name][given_column_name];
for(auto column_it = column_probs.begin(); column_it != column_probs.end(); ++column_it)
{
std::string given_value = column_it->first;
auto & given_value_probs = column_it->second;
int count_match = 0;
for(auto given_it = given_value_probs.begin(); given_it != given_value_probs.end(); ++given_it)
{
count_match += given_it->second;
}
for(auto given_it = given_value_probs.begin(); given_it != given_value_probs.end(); ++given_it)
{
std::string column_value = given_it->first;
given_prob[column_name][given_column_name][given_value][column_value] = given_it->second / count_match;
}
}
return 0;
}
double H(PROB_HASH & prob, std::string feature)
{
double sum = 0;
std::unordered_map<std::string, double> & feature_prob = prob[feature];
for(auto it = feature_prob.begin(); it != feature_prob.end(); ++it)
{
sum += it->second * LOG2(it->second);
}
return -sum;
}
double H(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string feature, std::string given_feature)
{
if(!given_prob.count(feature) || !given_prob[feature].count(given_feature))
{
CalculateGivenProbabilities(data, given_prob, feature, given_feature);
}
double sum = 0;
auto & given_value_probs = given_prob[feature][given_feature];
auto & given_feature_probs = prob[given_feature];
for(auto it = given_value_probs.begin(); it != given_value_probs.end(); ++it)
{
std::string given_value = it->first;
std::unordered_map<std::string, double> & value_probs = it->second;
double given_value_prob = given_feature_probs[given_value];
double temp_sum = 0;
for(auto value_it = value_probs.begin(); value_it != value_probs.end(); ++value_it)
{
temp_sum += value_it->second * LOG2(value_it->second);
}
sum += temp_sum * given_value_prob;
}
return -sum;
}
double IG(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string feature, std::string given_feature)
{
return H(prob, feature) - H(data, prob, given_prob, feature, given_feature);
}
double SU(DATA_SET & data, PROB_HASH & prob, PROB_GIVEN_HASH & given_prob, std::string feature, std::string given_feature)
{
return 2 * (IG(data, prob, given_prob, feature, given_feature) / (H(prob, feature) + H(data, prob, given_prob, feature, given_feature)));
}
bool TupleCompare(const std::pair<std::string, double> & x1, const std::pair<std::string, double> & x2)
{
return (x1.second > x2.second);
}
int FCBF(DATA_SET & data, double min_threshold, std::string class_column, std::vector<std::string> & best_features)
{
PROB_HASH probs;
PROB_GIVEN_HASH given_probs;
std::vector<std::string> feature_names;
std::list<std::pair<std::string, double>> list;
GetKeys(data, feature_names);
CalculateProbabilities(data, probs, given_probs, class_column);
for(auto it = feature_names.begin(); it != feature_names.end(); ++it)
{
if(*it != class_column)
{
std::pair<std::string, double> tuple;
tuple.first = *it;
tuple.second = SU(data, probs, given_probs, class_column, *it);
if(tuple.second > min_threshold)
{
list.push_back(tuple);
}
}
}
list.sort(TupleCompare);
auto F_j = list.begin();
while (F_j != list.end())
{
auto F_i = F_j;
++F_i;
while (F_i != list.end())
{
double su_ij = SU(data, probs, given_probs, F_j->first, F_i->first);
if(su_ij >= F_i->second)
{
F_i = list.erase(F_i);
}
else
{
++F_i;
}
}
++F_j;
}
best_features.clear();
best_features.reserve(list.size());
for(auto it = list.begin(); it != list.end(); ++it)
{
best_features.push_back(it->first);
}
return 0;
}
<file_sep>#ifndef _READ_CSV_
#define _READ_CSV_
#include <unordered_map>
#include <vector>
#include <string>
#define DATA_SET std::unordered_map<std::string, std::vector<std::string>>
int GetKeys(const DATA_SET & data, std::vector<std::string> & keys);
int ReadCsv(std::string fileName, DATA_SET & map, bool hasHeaders = true);
int ReadLine(std::istream & input, std::vector<std::string> & row);
#endif
<file_sep>#include "MVM.h"
EquivalenceClass::EquivalenceClass()
{
this->_totalCount = 0;
}
bool EquivalenceClass::Included(int index)
{
bool result = false;
if(this->_inclusionMap.count(index))
{
result = true;
}
return result;
}
int EquivalenceClass::Add(int index, std::string class_value)
{
this->_inclusionMap[index] = true;
if(this->_classCounts.count(class_value))
{
this->_classCounts[class_value]++;
}
else
{
this->_classCounts[class_value] = 1;
}
this->_totalCount++;
return 0;
}
double EquivalenceClass::Ap(std::string class_value)
{
return (this->_classCounts.count(class_value) ? this->_classCounts[class_value] : 0)/ ((double) this->_totalCount);
}
int GetAttributes(DATA_SET & data, std::list<std::string> & attributes, std::string class_col)
{
for(auto it = data.begin(); it != data.end(); ++it)
{
if(it->first != class_col)
{
attributes.push_back(it->first);
}
}
return 0;
}
int FindClasses(DATA_SET & data, std::string class_column, std::vector<std::string> & classes)
{
std::unordered_map<std::string, bool> discovered;
int numrows = data[class_column].size();
int i = 0;
for(; i < numrows; i++)
{
std::string value = data[class_column][i];
if(!discovered.count(value))
{
classes.push_back(value);
discovered[value] = true;
}
}
return 0;
}
int FindEquivalences(DATA_SET & data, std::vector<std::pair<std::string, EquivalenceClass *>> & equivalence_assoc, std::unordered_map<std::string, EquivalenceClass> & equivalences, std::string class_column, std::vector<std::string> & attributes)
{
int numrows = data[class_column].size();
int i;
std::pair<std::string, EquivalenceClass *> dummy;
if(!attributes.empty())
{
for(i = 0; i < numrows; i++)
{
std::string class_value = data[class_column][i];
std::string attribute_string;
for(auto it = attributes.begin(); it != attributes.end(); ++it)
{
attribute_string += data[*it][i];
}
EquivalenceClass & ec = equivalences[attribute_string];
ec.Add(i, class_value);
dummy.first = class_value;
dummy.second = &ec;
equivalence_assoc.push_back(dummy);
}
}
return 0;
}
double Sigma_p(DATA_SET & data, std::vector<std::pair<std::string, EquivalenceClass *>> & equivalences, std::string class_value, int num_classes)
{
int i = 0;
double sum_same = 0;
double sum_different = 0;
for(auto it = equivalences.begin(); it != equivalences.end(); ++it)
{
std::string & current_class = it->first;
EquivalenceClass & ec = *(it->second);
if(current_class == class_value)
{
sum_same += SQUARE(1 - ec.Ap(class_value));
}
else
{
sum_different += SQUARE(ec.Ap(class_value));
}
}
return(sqrt((sum_same + sum_different) / equivalences.size()));
}
double Sigma(DATA_SET & data, std::vector<std::pair<std::string, EquivalenceClass *>> & equivalences, std::vector<std::string> classes)
{
int num_classes = classes.size();
double sum = 0;
for(auto it = classes.begin(); it != classes.end(); ++it)
{
sum += Sigma_p(data, equivalences, *it, num_classes);
}
return(sum / num_classes);
}
int MVM(DATA_SET & data, double max_threshold, std::string class_column, std::vector<std::string> & best_features)
{
std::list<std::string> attributes;
std::vector<std::string> red_copy;
std::vector<std::pair<std::string, EquivalenceClass *>> equivalence_assoc;
std::unordered_map<std::string, EquivalenceClass> equivalences;
std::vector<std::string> classes;
std::vector<double> sigmas;
GetAttributes(data, attributes, class_column);
FindClasses(data, class_column, classes);
equivalence_assoc.reserve(data[class_column].size());
while(!attributes.empty())
{
double min_value = std::numeric_limits<double>::infinity();
std::string min_col;
for(auto attr_it = attributes.begin(); attr_it != attributes.end(); ++attr_it)
{
red_copy.push_back(*attr_it);
double sigma_new;
double sigma_old;
if(best_features.empty())
{
sigma_old = 0;
}
else
{
sigma_old = sigmas.back();
}
FindEquivalences(data, equivalence_assoc, equivalences, class_column, red_copy);
sigma_new = Sigma(data, equivalence_assoc, classes);
double result = sigma_new - sigma_old;
if(result < min_value)
{
min_value = result;
min_col = *attr_it;
}
equivalence_assoc.clear();
equivalences.clear();
red_copy.pop_back();
}
if(best_features.empty() || std::abs(min_value) < max_threshold)
{
sigmas.push_back(min_value + (sigmas.empty() ? 0 : sigmas.back()));
best_features.push_back(min_col);
red_copy.push_back(min_col);
attributes.remove(min_col);
}
else {
break;
}
}
return 0;
}
<file_sep>#ifndef _MVM_
#define _MVM_
#include <vector>
#include <unordered_map>
#include <string>
#include <list>
#include <limits>
#include "ReadCsv.h"
#define SQUARE(X) ((X) * (X))
class EquivalenceClass
{
public:
EquivalenceClass();
bool Included(int index);
int Add(int index, std::string class_value);
double Ap(std::string class_value);
private:
std::unordered_map<int, bool> _inclusionMap;
int _totalCount;
std::unordered_map<std::string, int> _classCounts;
};
int MVM(DATA_SET & data, double max_threshold, std::string class_column, std::vector<std::string> & best_features) ;
#endif
|
3e09163d09b0bef6a8564ea32a0a2dae2f7fa9c3
|
[
"R",
"C++"
] | 8 |
C++
|
christophertfoo/FeatureSelection
|
cc6daaf82ed6ed1a728282a6af77c3f7558c59e4
|
05d574c3268a3180acd4d4ee6f81595256def011
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyChanged
{
class Person2
{
public event EventHandler PropertyChanged;
private int id;
public int Id
{
get { return id; }
set
{
OnPropertyChangedEventHandler("Id");
id = value;
}
}
private int name;
public int Name
{
get { return name; }
set
{
OnPropertyChangedEventHandler("Name");
name = value;
}
}
private void OnPropertyChangedEventHandler(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyChanged
{
//delegate void PropertyChangedEventHandler(object sender, PropertyChangedEventArgs e);
class Person3
{
//public event PropertyChangedEventHandler PropertyChanged;
public event EventHandler<PropertyChangedEventArgs> PropertyChanged;
private int id;
public int Id
{
get { return id; }
set
{
OnPropertyChangedEventHandler("id");
id = value;
}
}
private int name;
public int Name
{
get { return name; }
set
{
OnPropertyChangedEventHandler("name");
name = value;
}
}
private void OnPropertyChangedEventHandler(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(name));
}
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyChanged
{
class PropertyChangedEventArgs : EventArgs
{
public string PropertyName { get; set; }
public PropertyChangedEventArgs(string propertyName)
{
this.PropertyName = propertyName;
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyChanged
{
class Person1
{
public event EventHandler PropertyChanged;
private int id;
public int Id
{
get => this.id;
set
{
this.OnPropertyChangedEventHandler();
this.id = value;
}
}
private int name;
public int Name
{
get => this.name;
set
{
this.OnPropertyChangedEventHandler();
this.name = value;
}
}
private void OnPropertyChangedEventHandler() => PropertyChanged?.Invoke(this, new EventArgs());
}
}
<file_sep># Opgave i C#: PropertyChanged
Her en lille simpel opgave i brugen af hændelser/delegates, som samtidig kan bruges som inspiration ved design af klasser. Opgaven er i sig selv simpel – sørg at et objekt smider en hændelse når en egenskab tilrettes. Det kan bruges til mange ting som eksempelvis log, fejlhåndtering og databinding på brugerflader.
Start med at skabe en konsol app og tilføj en simpel Person-klasse som eksempelvis:

Klassen består af et antal private felter og tilhørende egenskaber (get/set). Du skal nu tilføje en hændelse (event) til klassen kaldet PropertyChanged.

I første omgang kan du bruge den indbyggede EventHandler-delegate, navngive denne PropertyChanged, og blot kalde den med en ny instans af EventArgs hver gang en af egenskaberne ændre sig. Du bør placere kaldet til hændelsen i en privat metode (måske navngivet OnPropertyChangedEventHandler), og så blot kalde den i egenskabernes Set. Test koden i Main som eksempelvis:
```csharp
Person1 p1 = new Person1();
p1.PropertyChanged += (s, e) => Console.WriteLine("Egenskab rettet");
p1.Id = 1; // skulle gerne resulterer i "Egenskab rettet" på consol
```
Men den indbyggede EventArgs giver ikke mulighed for at oplyse hvilken egenskab der er rettet. Så næste skridt er at skabe en klasse der arver fra EventArgs, og som giver mulighed for at oplyse navnet på egenskaben der er rettet. Det vil kræve en tilretning af OnPropertyChangedEventHandler så der kan angives et navn på egenskaben der tilrettes. Men så bliver følgende kode mulig:
```csharp
Person2 p2 = new Person2();
p2.PropertyChanged += (s, e) => Console.WriteLine("Egenskab " +
((PropertyChangedEventArgs)e).PropertyName + " rettet");
p2.Id = 1; // skulle gerne resulterer i "Egenskab Id rettet" på consol
```
Det er dog lidt træls at skulle typecaste EventArgs til PropertyChangedEventArgs så sidste skridt må være at skabe sin egen delegate så den kan kaldes med en sender (Object) og den rigtige event (PropertyChangedEventArgs). Så bliver følgende muligt:
```csharp
Person3 p3 = new Person3();
p3.PropertyChanged += (s, e) => Console.WriteLine("Egenskab " +
e.PropertyName + " rettet");
p3.Id = 1; // skulle gerne resulterer i "Egenskab Id rettet" på consol
```
Start med at skabe din helt egen PropertyChangedEventHandler, og herefter i stedet bruge den anbefalede og indbyggede EventHandler<> (se evt. [løsning](https://github.com/devcronberg/os-cs-propchanged/tree/master/PropertyChanged)).
> Bemærk, at [løsningen](https://github.com/devcronberg/os-cs-propchanged/tree/master/PropertyChanged) er et .NET Framework 4.6.1 projekt, men du kan blot bruge .NET Core.
Når du har fået det hele til at spille kan du se på Microsofts forslag til en ”best-practice” – nemlig implementation af INotifyPropertyChanged (fra System.ComponentModel). Dette interface benyttes blandt andet til databinding i WinForm og WPF applikationer.
I øvrigt er der en del forslag på nettet til en ”PropertyChange” feature – se eksempelvis https://goo.gl/uEPdw.
<file_sep>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PropertyChanged
{
class Program
{
static void Main(string[] args)
{
Person1 p1 = new Person1();
p1.PropertyChanged += (s, e) => Console.WriteLine("Egenskab rettet");
p1.Id = 1; // skulle gerne resulterer i "Egenskab rettet" på consol
Person2 p2 = new Person2();
p2.PropertyChanged += (s, e) => Console.WriteLine("Egenskab " +
((PropertyChangedEventArgs)e).PropertyName + " rettet");
p2.Id = 1; // skulle gerne resulterer i "Egenskab Id rettet" på consol
Person3 p3 = new Person3();
p3.PropertyChanged += (s, e) => Console.WriteLine("Egenskab " +
e.PropertyName + " rettet");
p3.Id = 1; // skulle gerne resulterer i "Egenskab Id rettet" på consol
Person4 p4 = new Person4();
p4.PropertyChanged += (s, e) => Console.WriteLine("Egenskab " +
e.PropertyName + " rettet");
p4.Id = 1; // skulle gerne resulterer i "Egenskab Id rettet" på consol
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace PropertyChanged
{
class Person4 : INotifyPropertyChanged
{
public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
private int id;
public int Id
{
get { return id; }
set
{
OnPropertyChangedEventHandler("id");
id = value;
}
}
private int name;
public int Name
{
get { return name; }
set
{
OnPropertyChangedEventHandler("name");
name = value;
}
}
private void OnPropertyChangedEventHandler(string name)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(name));
}
}
}
}
|
4e9ea93db10c2580146f44d947627f40209834d3
|
[
"Markdown",
"C#"
] | 7 |
C#
|
devcronberg/os-cs-propchanged
|
c5e7899d7ffe7d6ce90f84590fb06d9dc393ed4d
|
9c587191e871849afac3ac7a22d349f9966d11dc
|
refs/heads/master
|
<repo_name>Jonatthanlopez23/Computacion-en-java<file_sep>/README.md
# Computacion-en-java
Evidencia 1
• Instalación y configuración.
• Uso del programa.
• Créditos.
• Licencia.
<file_sep>/src/clinica/Cita.java
package clinica;
import javax.swing.JOptionPane;
public final class Cita {
private String id;
private String fecha;
private String hora;
private String motivo;
private Doctor doctor;
private Paciente paciente;
public String generaLineaCSV() {
return String.format("%s,%s,%s,%s,%s,%s\n", id, fecha, hora, motivo, doctor, paciente);
}
public Cita(String id, String fecha, String hora, String motivo) {
this.id = id;
this.fecha = fecha;
this.hora = hora;
this.motivo = motivo;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getFecha() {
return fecha;
}
public void setFecha(String fecha) {
this.fecha = fecha;
}
public String getHora() {
return hora;
}
public void setHora(String hora) {
this.hora = hora;
}
public String getMotivo() {
return motivo;
}
public void setMotivo(String motivo) {
this.motivo = motivo;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
public Paciente getPaciente() {
return paciente;
}
public void setPaciente(Paciente paciente) {
this.paciente = paciente;
}
/**
* Muestra por panel todos los datos de la cita
*/
public void mostrar() {
String mensaje = "\nid cita: " + id + "\nFecha: " + fecha
+ "\nHora: " + hora + "\nMotivo: " + motivo;
JOptionPane.showMessageDialog(null, mensaje, "Mostrar Cita", JOptionPane.INFORMATION_MESSAGE);
}
}
|
d32a502006143ee24930ec82ebd6730b7612ff30
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
Jonatthanlopez23/Computacion-en-java
|
edf6d117b02a2c93127a995675cf4616fc4d66c7
|
d7642feb62b9e808fa2b25aba2f462db517c8321
|
refs/heads/master
|
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SurfboardBrokerScrape
{
class xyz
{
public static string local { get; set; } = "mongodb://localhost:27017";
public static string MLab { get; set; } = "mongodb://wyatt123:<EMAIL>:19055/surfengine";
}
}
<file_sep>using AngleSharp;
using MongoDB.Driver;
using System;
using System.Linq;
using System.Text.RegularExpressions;
namespace SurfboardBrokerScrape
{
class Program
{
static void Main(string[] args)
{
try
{
var connectionString = xyz.MLab;
var client = new MongoClient(connectionString);
var db = client.GetDatabase("surfengine");
var collection = db.GetCollection<ScrapedBoard>("Surfboard");
collection.DeleteMany(Builders<ScrapedBoard>.Filter.Eq("Source", "SurfboardBroker"));
int? ParseLength(string input)
{
var match = Regex.Match(input, @"(\d{1,2})\s*’\s*(\d{1,2})?"); // swaped ' for ’
if (!match.Success)
return null;
var inches = match.Groups[2].Value;
if (inches.Length == 0)
inches = "0";
var Answer = int.Parse(match.Groups[1].Value) * 12 + int.Parse(inches);
if (Answer >= 180)
{
return null;
}
return Answer;
}
var context = BrowsingContext.New(AngleSharp.Configuration.Default.WithDefaultLoader());
for (var i = 1; i < 34; i++)
{
var doc = context.OpenAsync("https://surfboardbroker.com/collections/surfboard-count?page=" + i).Result;
doc = doc;
var nodes =
doc.QuerySelectorAll(".grid-view-item")
.Select(x =>
new
{
Title =
x
.QuerySelector(".grid-view-item__title")
.TextContent
.Trim(),
Price =
x
.QuerySelector(".product-price__price")
?.TextContent // this checks for null reference error
.Trim(),
Image =
x
.QuerySelector(".grid-view-item__image")
?.Attributes["src"]
.Value,
Link =
x
.QuerySelector(".grid-view-item__link")
?.Attributes["href"]
?.Value,
});
nodes = nodes;
foreach (var node in nodes)
{
var mySurfboard = new ScrapedBoard();
mySurfboard.Name = node.Title;
mySurfboard.Brand = node.Title;
//price
var FormattedPrice = node.Price.Replace(",", "");
var blah = FormattedPrice.Split('$', '.');
mySurfboard.Price = Convert.ToInt32(blah[1]);
//height
//if (node.Title.IndexOf("\’") > -1)
//{
mySurfboard.Height = ParseLength(node.Title);
//}
//Image
mySurfboard.Image = node.Image;
//Link
mySurfboard.Link = "surfboardbroker.com" + node.Link;
//Date created
mySurfboard.Created = DateTime.UtcNow.Date;
mySurfboard = mySurfboard;
Console.WriteLine(mySurfboard.Name);
collection.InsertOne(mySurfboard);
}
}
}
catch (Exception e)
{
throw;
}
Console.ReadKey();
}
}
}
<file_sep>using System;
using System.Collections.Generic;
using System.Text;
namespace SurfboardBrokerScrape
{
class ScrapedBoard
{
public string Name { get; set; }
public string Brand { get; set; }
public int? Height { get; set; }
public int Price { get; set; }
public string Image { get; set; }
public string Link { get; set; }
public string Source { get; set; } = "SurfboardBroker";
public bool FromInternalUser { get; set; } = false;
public DateTime Created { get; set; }
public int Zip { get; set; } = 92010;
public string City { get; set; } = "San Diego";
}
}
|
b2b1c1db05b11e54e85ca5356ca65d02caf566f6
|
[
"C#"
] | 3 |
C#
|
wyattwade/SurfboardBrokerScrape
|
f822d07266281fd276813b92aae2b2b8a64f41f1
|
402367eba38ec57e5b3e937905931804eeaf1eb6
|
refs/heads/master
|
<repo_name>JakoboNazarGuevara/Parking_evaluation<file_sep>/Path/HP/Evaluacion.hp.js
/*this imports my functions from './../Tool/datauto' to be used in this file.*/
const Tools = require('./../Tool/datauto');
/*array and matrix of data to be evaluated by the program 7 cases each*/
var Tparkeo =["Valet","Short","Economy","Long-Garage","Long-Surface"];
var Sdate =["2","3","4","5","6","9","17"];
var Ldate =["2","3","4","5","8","16","26"];
var Dmsg =["0","0","0","0","2","7","9"];
var Hmsg =["0","2","6","7","0","0","0"];
var Mmsg =["40","0","0","30","0","0","0"];
var Stime =["08:00","09:00","07:00","07:00","07:00","07:00","07:00"];
var Ltime =["08:40","11:00","01:00","02:30","07:00","07:00","07:00"];
var SAMPM =["AM","AM","AM","AM","AM","AM","AM"];
var LAMPM =["AM","AM","PM","PM","AM","AM","AM"];
var Total =[
["12.00","12.00","18.00","18.00","36.00","126.00","162.00"],
["2.00","4.00","12.00","15.00","48.00","168.00","216.00"],
["2.00","4.00","9.00","9.00","18.00","54.00","72.00"],
["2.00","4.00","12.00","12.00","24.00","72.00","96.00"],
["2.00","4.00","10.00","10.00","20.00","60.00","80.00"]
];
var Month =["January","February","March","April","May","Jun","July","August","September","October","November","December"];
var MonthS = 8;
var Year = 2020;
var ci= 0;
var h=0;
var TparkeoL = Tparkeo.length;
var SdateL = Sdate.length;
/*this for is meant to loop betwen the diferent tipe of Parking
to evaluate:
Valet Parking = set i=0;i<1
short term = set i=1;i<2
Economy = set i=2;i<3
long-term Garage = set i=3;i<4
long-term surface = set i=4;i<5
all =
*/
for(i=0;i<1;){
let ci=i
/*this for is meant to loop betwen the diferent cases given
to evaluate
case 1 = set hi=0;hi<1
case 2 = set hi=1;hi<2
case 3 = set hi=2;hi<3
case 4 = set hi=3;hi<4
case 5 = set hi=4;hi<5
case 6 = set hi=5;hi<6
case 7 = set hi=6;hi<7
all = set hi=0;hi<7
*/
for(hi=2;hi<4;){
let h=hi;
describe('Evaluating: '+Tparkeo[ci]+' Case :'+hi+' ',()=>{
/*Go to shino parking calculator*/
it('Open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
browser.pause(2000);
});
it('Set and check Parking tipe to "'+Tparkeo[ci]+' Parking"',()=>{
$("select#ParkingLot").selectByIndex(ci);
const $parking = browser.$('select[id="ParkingLot"]');
expect($parking).toHaveValue(Tparkeo[ci]);
});
/*call ESetDate() to feed the form with information from Array*/
Tools.ESetDate(Sdate[h],Ldate[h],MonthS,Stime[h],Ltime[h],SAMPM[h],LAMPM[h]);
/**/
it('Click on calculate bottom: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
/*call ECheckDate() to veriry nformation in form is correct*/
Tools.ECheckDate(((MonthS+1)+'/'+Sdate[h]+'/'+Year),((MonthS+1)+'/'+Ldate[h]+'/'+Year),Stime[h],Ltime[h],SAMPM[h],LAMPM[h],Total[ci][h],Dmsg[h],Hmsg[h],Mmsg[h]);
});
/*case counter +1*/
hi++;
}
/*Parkng tipe counter +1*/
i++;
}
<file_sep>/Path/SP/Evaluacion.sp.js
const Tools = require('./../Tool/datauto');
/*just click on calculate to verfy warning and error elements*/
describe('just click on calculate to verify warning and error elements',()=>{
it('Open Browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
it('Set and check Parking tipe value to "Valet Parking"',()=>{
const $parking = browser.$('select[id="ParkingLot"]');
expect($parking).toHaveValue('Valet');
});
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.Warnings(1,1,1);
});
/*Entry date after Leaving date sould throw error message*/
describe('Entry date after Leaving date should throw error message',()=>{
it('Open Browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
Tools.ESetDate(12,11,11,null,null,null,null);
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.Warnings(null,null,1);
});
/*Entry information Without changing Entry date should throw error and warning message*/
describe('Entry information Without changing Entry date should throw error and warning message',()=>{
it('Open Browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
Tools.ESetDate(null,12,11,null,null,null,null);
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.Warnings(1,1,1);
});
/**/
describe('Entry information With blank Entry date should throw error and warning message',()=>{
it('Open Browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
it('Set and Check Entry date value to " "', () => {
const $Sdate = $('#startingDate');
$Sdate.setValue(" ");
expect($Sdate).toHaveValue(" ");
});
Tools.ESetDate(null,11,11,null,null,null,null);
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.Warnings(1,1,1);
});
/*Enter the same Entry and leaving date and same entry and leaving time, total should be "0"*/
describe('Enter Same date and Same time',()=>{
it('Open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
Tools.ESetDate(12,12,11,"10:00","10:00",null,null);
it('click on calculate',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
it('Total value to be equal: $ 0', () => {
const $total = $('span[class=SubHead]');
expect($total).toHaveText('$ 0');
});
it('Day message value to be equal to : (0 Days, 0 Hours, 0 Minutes)', () => {
const $diamessage = $('span[class=BodyCopy]');
expect($diamessage).toHaveTextContaining('(0 Days, 0 Hours, 0 Minutes)');
});
});
/*Enter text instead of date*/
describe('Enter Text instead of date',()=>{
it('Open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
/*inputs text directly to date box*/
it('Set and Check Entry date value to "abcd"', () => {
const $Sdate = $('#startingDate');
$Sdate.setValue('abcd');
expect($Sdate).toHaveValue('abcd');
});
/*inputs text directly to date box*/
it('Set and Check Leving date value to "abcd"', () => {
const $Ldate = $('#LeavingDate');
$Ldate.setValue('abcd');
expect($Ldate).toHaveValue('abcd');
});
it('Click on calculate',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.Warnings(1,1,1);
});
/*Set Time to PM should be PM after click*/
describe('Set Time to PM should be PM after click',()=>{
it('open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
Tools.ESetDate(16,18,11,'08:00','08:00','PM','PM');
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.ECheckDate(null,null,null,null,"PM","PM","36.00",2,null,null);
});
/**/
describe('Click calculate then enter date and click calculate again',()=>{
it('Open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.Warnings(1,1,1);
Tools.ESetDate(12,14,11,'08:00','08:00','AM','PM');
it('Click on calculate: ',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.ECheckDate("12/12/2020","12/14/2020",'08:00','08:00','AM','PM',"54.00",2,12,0);
});
/*should throw Erro message if month bigger than 12 */
describe('Input date month number value bigger than 12 = December should throw Error message',()=>{
it('Open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
it('Set and Check Entry date value to "14/12/2020"', () => {
const $Sdate = $('#startingDate');
$Sdate.setValue('14/12/2020');
expect($Sdate).toHaveValue('14/12/2020');
});
it('Set and Check Leaving date value to "14/14/2020"', () => {
const $Sdate = $('#leavingDate');
$Sdate.setValue('14/14/2020');
expect($Sdate).toHaveValue('14/14/2020');
});
Tools.Warnings(1,1,1)
});
/**/
describe('Entry and Leaving time PM twice',()=>{
it('Open browser',()=>{
browser.url('http://www.shino.de/parkcalc');
});
Tools.ESetDate(12,14,11,"08:00","08:00","PM","PM");
it('click on Calculate',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.ECheckDate("12/12/2020","12/14/2020","08:00","08:00","PM","PM","36.00",2,null,null);
Tools.ESetDate(null,null,null,null,null,"PM","PM");
it('click on Calculate',()=>{
const $buttom = $('input[type=Submit]');
$buttom.click();
});
Tools.ECheckDate("12/12/2020","12/14/2020","08:00","08:00","PM","PM","36.00",2,null,null);
});
<file_sep>/Path/Tool/datauto.js
module.exports={
/*Looks for the warning elements to show:
1. mktime warning message, 2.gmmktime warning message and 3. Error message in Total box
in case a field s not needed replace value with: null eje:Warnings(null,null,ErroMsg)*/
Warnings : function Warnings(mktime,gmmktime,ErroMsg){
if(mktime!=null){
it('Expect warning "mktime" to be displayed',()=>{
const $Wmsg = $('body*=mktime()');
expect($Wmsg).toBeDisplayed();
});
};
if(gmmktime!=null){
it('Expect warning "gmmktime" to be displayed',()=>{
const $Wmsg = $('body*=gmmktime()');
expect($Wmsg).toBeDisplayed();
});
};
if(ErroMsg!=null){
it('Expect total to have ERROR message Displayed',()=>{
const $Error = $('td[class=SubHead]');
expect($Error).toHaveTextContaining('ERROR');
});
};
},
/*sets information needed in the app.
Sday=Entry day number in calendar, Lday=leaving day numbe in calendar, Month= Month numbe in calendar -1, 0=January, 11=December,
Stime= Entry time "09:00", Ltime= Leaving time "10:30", SAMPM= Entry "AM"or"PM" time, LAMPM= Leaving "AM"or"PM" time.
in case a field s not needed replace value with: null eje:ESetDate(Sday,Lday,Month,Stime,Ltime,null,null)*/
ESetDate : function ESetDate(Sday,Lday,Month,Stime,Ltime,SAMPM,LAMPM){
var Imonth=["January","February","March","April","May","Jun","July","August","September","October","November","December"];
if(Sday!=null){
it('Click on enter Entry date Calendar palette',()=>{
const $callendar = $('a[href*=StartingDate]');
$callendar.click();
});
it('Window should change to "Pick a Date"',()=>{
browser.switchWindow('Pick a Date');
expect(browser).toHaveTitle('Pick a Date');
});
if(Month!=null){
it('Select '+Month+'on month',()=>{
$("select[name=MonthSelector]").selectByIndex((Month));
browser.pause(1000);
const $mes = $('b*='+Imonth[(Month)]+'');
expect($mes).toHaveText(''+Imonth[(Month)]+' 2020');
});
};
it('Click on Entry date '+Sday+'',()=>{
const $dia=$('a='+Sday+'');
$dia.click();
});
it('Window should change to "Parking Cost Calculator"',()=>{
browser.switchWindow('Parking Cost Calculator');
expect(browser).toHaveTitle('Parking Cost Calculator');
});
};
if(Stime!=null){
it('Set and Check Entry Time value to '+Stime+'', () => {
const $Stime = $('#startingTime');
$Stime.setValue(Stime);
expect($Stime).toHaveValue(Stime);
});
};
if(SAMPM!=null){
it('Click and Check Entry time "'+SAMPM+'" bottom', () => {
$("input[name=StartingTimeAMPM][value="+SAMPM+"]").click();
const $AMPM = $('input[name=StartingTimeAMPM]:checked');
expect($AMPM).toHaveValue(SAMPM);
});
};
if(Lday!=null){
it('Click on enter leaving date Calendar palette',()=>{
const $callendar = $('a[href*=LeavingDate]');
$callendar.click();
});
it('Window should change to "Pick a Date"',()=>{
browser.switchWindow('Pick a Date');
expect(browser).toHaveTitle('Pick a Date');
});
if (Month!=null){
it('Select December on month',()=>{
$("select[name=MonthSelector]").selectByIndex((Month));
browser.pause(1000);
const $mes = $('b*='+Imonth[(Month)]+'');
expect($mes).toHaveText(''+Imonth[(Month)]+' 2020');
});
};
it('Click on leaving day '+Lday+'',()=>{
const $dia=$('a='+Lday+'');
$dia.click();
});
it('Window should change to "Parking Cost Calculator"',()=>{
browser.switchWindow('Parking Cost Calculator');
expect(browser).toHaveTitle('Parking Cost Calculator');
});
};
if(Ltime!=null){
it('Set and Check Leaving value Time to '+Ltime+'', () => {
const $Ltime = $('#leavingTime');
$Ltime.setValue(Ltime);
expect($Ltime).toHaveValue(Ltime);
});
};
if(LAMPM!=null){
it('Click and Check Leaving "'+LAMPM+'" bottom', () => {
$("input[name=LeavingTimeAMPM][value="+LAMPM+"]").click();
const $AMPM = $('input[name=LeavingTimeAMPM]:checked');
expect($AMPM).toHaveValue(LAMPM);
});
};
},
/*Check if the infomrmation n the form is correct.
Sdate=Entry date MM/DD/YYYY, Ldate= Leaving date MM/DD/YYYY, Stime= Entry time "09:00", Ltime= Leaving time "10:30",
SAMPM= Entry "AM"or"PM" time, LAMPM= Leaving "AM"or"PM" time, Total= number+2 decimals"36.00" if none then "0",Ndias=number of days,
Nhoras= number of hours and Nminutos= number of minutes expected to be in the app.
in case a field is not needed replace value with: null eje:ECheckDate(Sdate,Ldate,Stime,Ltime,null,null,total,Ndias,null,null)*/
ECheckDate : function ECheckDate(Sdate,Ldate,Stime,Ltime,SAMPM,LAMPM,total,Ndias,Nhoras,Nminutos){
var Imonth=["January","February","March","April","May","Jun","July","August","September","October","November","December"];
if(Sdate!=null){
it('Entry date value after click should be "'+Sdate+'"', () => {
const $Sdate = $('#startingDate');
expect($Sdate).toHaveValue(Sdate);
});
};
if(Ldate!=null){
it('Leaving date value after click should be "'+Ldate+'"', () => {
const $Ldate = $('#LeavingDate');
expect($Ldate).toHaveValue(Ldate);
});
};
if(Stime!=null){
if(SAMPM=='PM'){
it('Check Entry Time value after click should be "'+(Number(Stime.slice(0,2))+12)+':'+(Stime.slice(3,5))+'"', () => {
const $Stime = $('#startingTime');
expect($Stime).toHaveValue((Number(Stime.slice(0,2))+12)+':'+(Stime.slice(3,5)));
});
}else{
it('Check Entry Time value after click should be "'+Stime+'"', () => {
const $Stime = $('#startingTime');
expect($Stime).toHaveValue(Stime);
});
};
};
if(SAMPM!=null){
it('Entry time AM PM value after click should be "'+SAMPM+'"', () => {
const $AMPM = $('input[name=StartingTimeAMPM]:checked');
expect($AMPM).toHaveValue(SAMPM);
});
};
if(Ltime!=null){
if(LAMPM=='PM'){
it('Check Leaving Time value after click should be "'+(Number(Ltime.slice(0,2))+12)+':'+(Ltime.slice(3,5))+'', () => {
const $Stime = $('#LeavingTime');
expect($Stime).toHaveValue((Number(Ltime.slice(0,2))+12)+':'+(Ltime.slice(3,5)));
});
}else{
it('Check Leaving Time value after click should be "'+Ltime+'"', () => {
const $Stime = $('#LeavingTime');
expect($Stime).toHaveValue(Ltime);
});
};
};
if(LAMPM!=null){
it('Leaving time AM PM value after click should be "'+LAMPM+'"', () => {
const $AMPM = $('input[name=LeavingTimeAMPM]:checked');
expect($AMPM).toHaveValue(LAMPM);
});
};
if(total!=null){
it('Total value after click should be equal to: $ '+total+'', () => {
const $total = $('span[class=SubHead]');
expect($total).toHaveText('$ '+total);
});
};
if(Ndias==null){
Ndias=0;
};
if(Nhoras==null){
Nhoras=0;
};
if(Nminutos==null){
Nminutos=0;
};
if(Ndias!=null && Nhoras!=null && Nminutos!=null){
it('Day message to be equal to : ('+Ndias+' Days, '+Nhoras+' Hours, '+Nminutos+' Minutes)', () => {
const $diamessage = $('span[class=BodyCopy]');
expect($diamessage).toHaveTextContaining('('+Ndias+' Days, '+Nhoras+' Hours, '+Nminutos+' Minutes)');
});
};
}
};
|
5f1d461a5b3311a9e411c1b257276fa6a3eb201e
|
[
"JavaScript"
] | 3 |
JavaScript
|
JakoboNazarGuevara/Parking_evaluation
|
c782788458a8b83660e16c9955a6c35b712818bc
|
77c75575d39e40792412d2d8585ce3c9c3102296
|
refs/heads/master
|
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class doigun : MonoBehaviour
{
private GameObject player;
public int zoom;
public int normal = 60;
public float smooth = 8;
private bool zoomedIn = false;
int nn = 0;
// Use this for initialization
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
fire2();
}
public void fire2()
{
if (Input.GetButtonDown("Fire2"))
{
zoomedIn = !zoomedIn;
}
if (zoomedIn == true)
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, zoom, Time.deltaTime * smooth);
seclectGun(1);
}
else
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, normal, Time.deltaTime * smooth);
seclectGun(nn);
}
}
void seclectGun(int _gun)
{
for (int i = 0; i < transform.childCount; i++)
{
if (i == _gun)
{
transform.GetChild(i).gameObject.SetActive(true);
}
else
{
transform.GetChild(i).gameObject.SetActive(false);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Help : MonoBehaviour {
private GameObject player;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
void Update()
{
transform.Rotate(new Vector3(0, 0, Time.deltaTime * 50));
}
void OnTriggerEnter(Collider Collider) {
if (Collider.tag =="Player") {
// player.GetComponent<gunPlayer>().bulletgame = 500;
float bullet2 = player.GetComponent<gunPlayer>().bulletgame=500;
player.GetComponent<gunPlayer>().bulletpoint.text = "|" + bullet2.ToString();
Debug.Log("1000");
Destroy(gameObject,0.5f);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class demogun2 : MonoBehaviour {
private Animation animation;
// Use this for initialization
void Start () {
animation = GetComponent<Animation>();
}
// Update is called once per frame
void Update () {
if (Input.GetButton("Fire1"))
{
animation.CrossFade("Fire2");
}
/* if (Input.GetKey(KeyCode.R)) {
animation.CrossFade("Reload");
}*/
}
}
<file_sep>var target : Transform;
var moveSpeed = 3;
var rotationSpeed = 3;
var myTransform : Transform;
var ragdoll : GameObject;
var agent : UnityEngine.AI.NavMeshAgent;
var isNotDead : boolean = true;
var health : float = 100;
var damageMin : float = 10;
function Awake()
{
myTransform = transform;
}
function Start()
{
target = GameObject.FindWithTag("Player").transform;
agent = GetComponent.<UnityEngine.AI.NavMeshAgent>();
}
function Update () {
target = GameObject.FindWithTag("Player").transform;
if(health < 1){
isNotDead = false;
Instantiate(ragdoll, myTransform.position, myTransform.rotation);
}
if(isNotDead){
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed*Time.deltaTime);
var distance = Vector3.Distance(target.position, myTransform.position);
if (distance < 2.0f) {
GetComponent.<Animation>().Play("Attack");
}
else{
agent.SetDestination(target.position);
GetComponent.<Animation>().Play("Run");
}
}
}
function OnTriggerEnter(collider : Collider)
{
if(collider.tag == "impact")
{
health -= 20;
}
}
function ApplyDamage(dmg : float){
health -= 20;
}<file_sep>using UnityEngine;
using System.Collections;
using UltraReal.Utilities;
using UltraReal.WeaponSystem;
using UnityEngine.UI;
public class BasicInputExample : UltraRealMonobehaviorBase {
private UltraRealLauncherBase launcher;
private Animation anim;
private GameObject player;
protected override void OnStart ()
{
anim = GetComponent<Animation>();
base.OnStart ();
launcher = GetComponent<UltraRealLauncherBase> ();
}
public AudioClip otherClip;
protected override void OnUpdate ()
{
base.OnUpdate ();
if (Input.GetButton ("Fire1") && launcher != null) {
launcher.Fire ();
// anim.CrossFade ("Fire");
}
if (Input.GetKeyDown (KeyCode.R)) {
AudioSource audio = GetComponent<AudioSource>();
audio.clip = otherClip;
audio.Play();
// anim.CrossFade ("Reload");
launcher.Reload ();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class enemytudong : MonoBehaviour
{
public GameObject Zombie;
GameObject[] SpawnPoint1;
public float minspawn = 2f;
public float maxspawn = 4f;
private float lastspawntime = 0;
private float spawntime = 0;
// Use this for initialization
void Start()
{
Updatespawntime();
SpawnPoint1 = GameObject.FindGameObjectsWithTag("spawn");
// Zombie = GameObject.FindGameObjectWithTag("Enemy");
}
void Updatespawntime()
{
lastspawntime = Time.time;
spawntime = Random.Range(minspawn, maxspawn);
}
void Zom()
{
int Point = Random.Range(0, SpawnPoint1.Length);
Instantiate(Zombie,SpawnPoint1[Point].transform.position, Quaternion.identity);
Updatespawntime();
}
// Update is called once per frame
void Update()
{
if (Time.time >= lastspawntime + spawntime)
{
Zom();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Boss : MonoBehaviour {
UnityEngine.AI.NavMeshAgent agent;
private Transform target;
public bool isNotDead = true;
public Transform myTransform;
float rotationSpeed = 3;
// private Animator anim;
// Use this for initialization
void Start()
{
target = GameObject.FindWithTag("Player").transform;
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
// anim = GetComponent<Animator>();
// anim.SetBool("Run",true);
// anim.SetBool("Attack", false);
}
// Update is called once per frame
void Update () {
// if (isNotDead)
// {
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
var distance = Vector3.Distance(target.transform.position, myTransform.transform.position);
if (distance == 2.0f)
{
GetComponent<Animation>().Play("attk2");
// player.GetComponent<gunPlayer>().heathpanel.SetActive(true);
// anim.SetBool("Attack",true);
}
else
{
// anim.SetBool("Attack", false);
agent.SetDestination(target.position);
// anim.SetBool("Run", true);
// GetComponent<Animation>().Play("run");
// player.GetComponent<gunPlayer>().heathpanel.SetActive(false);
// player.gameObject.GetComponent<gunPlayer>().heathpanel.SetActive(false);
}
// }
}
}
<file_sep>using UnityEngine;
using System.Collections;
public class PlayerUnit : Unit
{
float cameraRotaX = 0f;
public float maxCamera = 45f;
// Use this for initialization
public override void Start ()
{
base.Start ();
}
// Update is called once per frame
public override void Update ()
{
//print (Mathf.Clamp (-10, 1, 3));
//rotation
gameObject.transform.Rotate(0f, Input.GetAxis("Mouse X") * turnSpeed * Time.deltaTime, 0f);
//lay goc tao y
cameraRotaX -= Input.GetAxis("Mouse Y");
//print (Input.GetAxis ("Mouse Y") + "---");
//4 9 = -5
//print ("cameraRotaX:" + cameraRotaX);
cameraRotaX = Mathf.Clamp(cameraRotaX, -maxCamera, maxCamera);
Camera.main.transform.forward = transform.forward;
Camera.main.transform.Rotate(cameraRotaX, -45f, 1f);
//movement
move = new Vector3 (Input.GetAxis ("Horizontal"), 0f, Input.GetAxis ("Vertical"));
move.Normalize ();//xac dinh huong can di chuyen
move = transform.TransformDirection(move);//dich chuyen theo huong move
if (Input.GetKey(KeyCode.Space) && control.isGrounded)
{
jump = true;
}
running = Input.GetKey(KeyCode.LeftShift) || Input.GetKey(KeyCode.RightShift);
base.Update ();//truyxuat lop ke thua update cua script unit
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class raycastenemy : MonoBehaviour
{
GameObject Followter;
// Use this for initialization
void Start()
{
Vector3 FollowterPosition = gameObject.transform.position;
FollowterPosition.y += 10;
Followter = new GameObject("Followter");
Followter.transform.position = FollowterPosition;
}
// Update is called once per frame
void Update()
{
RaycastHit hit;
if (Physics.Raycast(Followter.transform.position, Vector3.down, out hit, 30, 1 << 1))
{
gameObject.transform.position = hit.point;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Stopladder : MonoBehaviour {
private GameObject ladder;
private GameObject player;
float speed = 1;
// Use this for initialization
void Start () {
ladder=GameObject.FindGameObjectWithTag("Ladder");
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter(Collider Collider)
{
if (Collider.tag == "Player")
{
// canClimb = true;
ladder.GetComponent<Ladder>().canClimb=false;
float h = Input.GetAxis("Vertical") * speed;
Debug.Log("ladder");
player.transform.Translate (new Vector3(0,0,h));
// player.GetComponent<Rigidbody>().velocity = new Vector3(0,0,0)*1;
//player.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"))*1;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraZoom2 : MonoBehaviour {
int zoom=35;
int normal=60;
float smooth = 8;
private bool zoomedIn = false;
public GameObject gun1;
public GameObject gun2;
private Vector3 olposition;
// Use this for initialization
void Start () {
gun1.SetActive(true);
gun2.SetActive(false);
}
// Update is called once per frame
void Update () {
if (Input.GetButtonDown("Fire2"))
{
zoomedIn = !zoomedIn;
}
if (zoomedIn == true)
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, zoom, Time.deltaTime * smooth);
gun2.SetActive(true);
gun1.SetActive(false);
}
else
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, normal, Time.deltaTime * smooth);
gun1.SetActive(true);
gun2.SetActive(false);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UltraReal.Utilities;
using UltraReal.WeaponSystem;
public class Gun1 : MonoBehaviour {
public int damge ;
int damgebullet = 1;
int damge2 = 35;
public float firetime ;
public float lastFireTime = 0;
public GameObject SmokeOuthit;
public float bullet2 = 30;
public GameObject lightbullet;
private Animator anim;
public AudioClip otherClip;
public AudioClip stopbullet;
private Animation animation;
private GameObject player;
private GameObject gun;
//public GameObject Gethit;
public GameObject par;
public int zoom;
public int normal = 60;
public float smooth = 8;
private bool zoomedIn = false;
public GameObject canvas;
// Use this for initialization
void Start () {
UpdateFireTime();
anim = GetComponent<Animator>();
player = GameObject.FindGameObjectWithTag("Player");
canvas.SetActive(false);
}
void UpdateFireTime()
{
lastFireTime = Time.time;
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1"))
{
Fire();
}
if (Input.GetButton("Fire2"))
{
firegun2();
}
}
public void Fire()
{
if (Time.time >= lastFireTime + firetime)
{
AudioSource audio = GetComponent<AudioSource>();
// yield return new WaitForSeconds(audio.clip.length);
audio.clip = otherClip;
audio.Play();
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// Ray ray = new Ray(transform.position, transform.forward);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.Log("hit");
bullet2 -= damgebullet;
player.GetComponent<gunPlayer>().GetBulletgun2(1);
if (bullet2 == 0)
{
gameObject.GetComponent<Gun1>().enabled = false;
}
if (bullet2 > 1)
{
gameObject.GetComponent<Gun1>().enabled = true;
}
GameObject ab = Instantiate(SmokeOuthit, hit.point, Quaternion.identity);
// Instantiate(smoke,transform.position,Quaternion.identity);
if (hit.transform.tag.Equals("Enemy"))
{
Instantiate(lightbullet, transform.position, Quaternion.identity);
// GameObject bc= Instantiate(par,hit.transform.position,Quaternion.identity);
GameObject bc = Instantiate(par, hit.point, Quaternion.identity);
hit.transform.gameObject.GetComponent<Enemy>().GetHit(damge);
// hit.transform.gameObject.GetComponent<boss>().GetHit(damge);
Debug.Log("hitenemy");
Destroy(ab);
}
if (hit.transform.tag.Equals("Boss"))
{
GameObject a = Instantiate(par, hit.point, Quaternion.identity);
// GameObject bc = Instantiate(par, parboss.transform.position, Quaternion.identity);
hit.transform.gameObject.GetComponent<boss>().GetHit(damge);
Debug.Log("hitenemy");
Destroy(ab);
}
if (hit.transform.tag.Equals("Bos"))
{
//GameObject bccb = Instantiate(par, hit.transform.position, Quaternion.identity);
GameObject bccb = Instantiate(par, hit.point, Quaternion.identity);
// GameObject bc = Instantiate(par, parboss2.transform.position, Quaternion.identity);
hit.transform.gameObject.GetComponent<Bos>().GetHit(damge);
Debug.Log("hitenemy");
Destroy(ab);
}
}
UpdateFireTime();
}
}
public GameObject panelgun2;
public GameObject gun2;
public GameObject bulletgun2;
public GameObject scores;
// public GameObject mimap;
public void firegun2() {
if (Input.GetButtonDown("Fire2"))
{
zoomedIn = !zoomedIn;
}
if (zoomedIn == true)
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, zoom, Time.deltaTime * smooth);
panelgun2.SetActive(true);
canvas.SetActive(false);
gun2.SetActive(false);
bulletgun2.SetActive(false);
scores.SetActive(false);
// mimap.SetActive(false);
}
else
{
Camera.main.fieldOfView = Mathf.Lerp(Camera.main.fieldOfView, normal, Time.deltaTime * smooth);
panelgun2.SetActive(false);
gun2.SetActive(true);
bulletgun2.SetActive(true);
scores.SetActive(true);
// mimap.SetActive(false);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Reloadfire : MonoBehaviour
{
private Animation animation;
public GameObject play;
private GameObject player;
public Text point2;
float bullet = 500;
int damge2 = 35;
void Awake() {
animation = GetComponent<Animation>();
}
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
// Update is called once per frame
void Update()
{
if (Input.GetButton("Fire1"))
{
animation.CrossFade("Fire");
}
else if (Input.GetKeyDown(KeyCode.R))
{
play.GetComponent<Gun>().enabled = false;
int GameBullet = player.GetComponent<gunPlayer>().GameBullet;
float bullet2 = play.GetComponent<Gun>().bullet2 = 35;
player.GetComponent<gunPlayer>().PointBullet.text = "Bullet:" + bullet2.ToString();
// player.GetComponent<gunPlayer>().PointBullet.text = "Bullet:" + bull.ToString();
if (bullet2 > 0)
{
play.GetComponent<Gun>().enabled = true;
}
/* if (bullet==0) {
// gameObject.GetComponent<Reloadfire>().enabled=false;
play.GetComponent<Gun>().enabled = true;
}*/
animation.CrossFade("Reload");
player.GetComponent<gunPlayer>().GetBullet2(35 - GameBullet);
player.GetComponent<gunPlayer>().GameBullet = 35;
/* AudioSource audio = GetComponent<AudioSource>();
audio.clip = au;
audio.Play();*/
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
public class gunPlayer : MonoBehaviour {
public int GameBullet = 35;
public int GameBulletgun2 = 30;
public int bulletgame =500;
public Text PointBullet;
public Text PointBulletgun2;
public Text bulletpoint;
int heathplayer=100;
public GameObject heathpanel;
public Slider HeathBar;
public float currentheath = 100;
public Text heath;
int hea=100;
public Text point;
int pointspider ;
public Transform deadReplacement;
private GameObject player;
public float speed = 5;
public GameObject panelboss;
public GameObject panelguide;
public GameObject canvaspoint;
public GameObject win;
public GameObject gameover;
// Use this for initialization
void Start () {
player = GameObject.FindGameObjectWithTag("Player");
player.SetActive(true);
HeathBar.maxValue = heathplayer;//=mau mac dinh
HeathBar.value = currentheath;//mau hien tai
HeathBar.minValue = 0;
heathpanel.SetActive(false);
panelboss.SetActive(false);
panelguide.SetActive(false);
canvaspoint.SetActive(true);
win.SetActive(false);
gameover.SetActive(false);
}
// Update is called once per frame
void Update() {
if (Input.GetKey(KeyCode.Alpha3))
{
panelboss.SetActive(true);
canvaspoint.SetActive(false);
}
else {
panelboss.SetActive(false);
canvaspoint.SetActive(true);
}
if (Input.GetKey(KeyCode.Alpha4))
{
panelguide.SetActive(true);
canvaspoint.SetActive(false);
}
else
{
panelguide.SetActive(false);
canvaspoint.SetActive(true);
}
}
public void GetBullet(int bullet2)
{
GameBullet--;
PointBullet.text = "Bullet:" + GameBullet.ToString();
}
public void GetBullet2(int bullet)
{
bulletgame-=bullet;
bulletpoint.text = "|" + bulletgame.ToString();
if (bulletgame <= 0)
{
bulletgame = 0;
bulletpoint.text = "|" + bulletgame.ToString();
}
}
public void GetBulletgun2(int bullet2)
{
GameBulletgun2--;
PointBulletgun2.text = "Bullet:" + GameBulletgun2.ToString();
}
public void Gethitplayer(int damge) {
currentheath -= damge;
HeathBar.value = currentheath;
// heathpanel.SetActive(true);
// hea -= damge;
heath.text = "" + currentheath.ToString();
if (currentheath <=0) {
currentheath = 0;
heath.text = "" + currentheath.ToString();
// Instantiate(deadReplacement, transform.position, transform.rotation);
Instantiate(deadReplacement,transform.position,Quaternion.identity);
Invoke("Engame",3);
Invoke("Restartsgame",3);
player.SetActive(false);
}
}
void Restartsgame() {
gameover.SetActive(true);
Cursor.lockState = CursorLockMode.None;
Cursor.visible = true;
canvaspoint.SetActive(false);
}
public void Engame() {
Time.timeScale = 0;
}
public void GetPoint()
{
pointspider+=10;
point.text = "Scores:" + pointspider.ToString();
}
public Text pointbosscurrent;
int damgeboss = 0;
int damgecurrentboss = 6;
public Text restboss;
public void mission(int current)
{
damgecurrentboss -= current;
pointbosscurrent.text = "" + damgecurrentboss.ToString();
damgeboss += current;
restboss.text = "" + damgeboss.ToString();
if (damgeboss>=6) {
win.SetActive(true);
canvaspoint.SetActive(false);
// Invoke("LoadScene",2);
}
}
public void LoadScene() {
Application.LoadLevel("testscene");
Time.timeScale = 1;
}
}
<file_sep>using UnityEngine;
using System.Collections;
using UltraReal.Utilities;
using UltraReal.WeaponSystem;
using UnityEngine.UI;
public class BasicLauncher : UltraRealLauncherBase {
float _nextShotTime;
int _ammoCount;
[SerializeField]
private float _shotDelay = 0.1f;
[SerializeField]
private float _reloadDelay = 1f;
[SerializeField]
private int _magazineSize = 35;
[SerializeField]
private Transform _ejectorTransform = null;
[SerializeField]
private Transform _muzzleTransform = null;
[SerializeField]
private AudioClip _reloadSound = null;
[SerializeField]
private AudioClip _missfireSound = null;
[SerializeField]
protected float _ejectorForce = 100f;
[SerializeField]
protected float _ejectorTorque = 100f;
[SerializeField]
protected AudioSource _audioSource = null;
[SerializeField]
protected Animator _animator = null;
[SerializeField]
protected string _fireAnimTriggerName = "Fire";
[SerializeField]
protected string _reloadAnimTriggerName = "Reload";
protected override void OnStart ()
{
base.OnStart ();
_nextShotTime = Time.time;
_ammoCount = _magazineSize;
if (_audioSource == null)
_audioSource = gameObject.AddComponent<AudioSource>();
}
public Text bullet;
int bull;
public override void Fire ()
{
if (_nextShotTime <= Time.time){
if (_ammoCount > 0 && _ammo != null) {
if(_muzzleTransform != null)
_ammo.SpawnAmmo(_muzzleTransform, _ejectorTransform, _ejectorForce, _ejectorTorque, 2f, _audioSource);
_ammoCount--;
if (_animator != null)
_animator.SetTrigger(_fireAnimTriggerName);
// fire();
base.Fire ();
}
else
MissFire();
_nextShotTime = Time.time + _shotDelay;
}
}
public override void MissFire()
{
base.MissFire ();
if (_missfireSound != null && _audioSource != null)
_audioSource.PlayOneShot (_missfireSound);
}
public override void Reload ()
{
/* base.Reload ();
if (_reloadSound != null && _audioSource != null)
_audioSource.PlayOneShot (_reloadSound);
if (_animator != null)
_animator.SetTrigger(_reloadAnimTriggerName);
_nextShotTime = Time.time + _reloadDelay;
_ammoCount = _magazineSize;
*/
}
/* void fire() {
_magazineSize--;
bullet.text = "Bullet:" + _magazineSize.ToString();
}
*/
}
<file_sep>using UnityEngine;
using System.Collections;
public class Rotation : MonoBehaviour
{
/*public Vector3 RotationAxis;
void Start ()
{
}
void Update ()
{
this.transform.Rotate (RotationAxis * Time.deltaTime);
}*/
void Update()
{
transform.Rotate(new Vector3(0,0,Time.deltaTime * 10));
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class camgun : MonoBehaviour {
public GameObject gun1bullet;
public GameObject gun2bullet;
public GameObject panelgun2;
public GameObject mimap;
public GameObject canvangun1;
// Use this for initialization
void Start () {
gun1bullet.SetActive(true);
gun2bullet.SetActive(false);
}
// Update is called once per frame
void Update()
{
if (Input.GetKey(KeyCode.Alpha1))
{
seclectGun(0);
gun1bullet.SetActive(true);
gun2bullet.SetActive(false);
panelgun2.SetActive(false);
mimap.SetActive(true);
canvangun1.SetActive(true);
}
if (Input.GetKey(KeyCode.Alpha2))
{
seclectGun(1);
gun1bullet.SetActive(false);
gun2bullet.SetActive(true);
mimap.SetActive(true);
canvangun1.SetActive(false);
}
}
void seclectGun(int _gun)
{
for (int i = 0; i < transform.childCount; i++)
{
if (i == _gun)
{
transform.GetChild(i).gameObject.SetActive(true);
}
else
{
transform.GetChild(i).gameObject.SetActive(false);
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Enemy : MonoBehaviour {
private Transform target;
public float moveSpeed = 3;
float rotationSpeed = 3;
public Transform myTransform;
public GameObject ragdoll;
UnityEngine.AI.NavMeshAgent agent;
public bool isNotDead= true;
int health = 5;
float damageMin = 5;
int damge = 5;
private GameObject player;
public Slider sliderenemy;
public float currentheath = 5;
int heathenemy = 5;
// Use this for initialization
void Awake() {
target = GameObject.FindWithTag("Player").transform;
agent = GetComponent<UnityEngine.AI.NavMeshAgent>();
player = GameObject.FindGameObjectWithTag("Player");
}
void Start () {
// sliderenemy.maxValue = heathenemy;//=mau mac dinh
sliderenemy.value = currentheath;//mau hien tai
sliderenemy.minValue = 0;
}
// Update is called once per frame
void Update () {
target = GameObject.FindWithTag("Player").transform;
if (isNotDead)
{
myTransform.rotation = Quaternion.Slerp(myTransform.rotation,
Quaternion.LookRotation(target.position - myTransform.position), rotationSpeed * Time.deltaTime);
var distance = Vector3.Distance(target.position, myTransform.position);
if (distance < 2.0f)
{
GetComponent< Animation > ().Play("Attack");
// player.GetComponent<gunPlayer>().heathpanel.SetActive(true);
}
else
{
agent.SetDestination(target.position);
GetComponent< Animation > ().Play("Run");
// player.GetComponent<gunPlayer>().heathpanel.SetActive(false);
// player.gameObject.GetComponent<gunPlayer>().heathpanel.SetActive(false);
}
}
}
void OnTriggerEnter(Collider Collider)
{
if (Collider.tag == "Player")
{
// health -= 20;
// gameObject.GetComponent<gunPlayer>().Gethitplayer(damge);
player.GetComponent<gunPlayer>().Gethitplayer(damge);
Debug.Log("hit");
player.GetComponent<gunPlayer>().heathpanel.SetActive(true);
Invoke("outpanel", 1);
}
}
public void outpanel() {
player.gameObject.GetComponent<gunPlayer>().heathpanel.SetActive(false);
}
public void GetHit(int damge) {
currentheath -= damge;
sliderenemy.value = currentheath;
if (currentheath <= 0)
{
// currentheath = 0;
Destroy(gameObject);
GameObject a = Instantiate(ragdoll, transform.position, Quaternion.identity);
Destroy(a, 1.5f);
// GetPoint();
player.GetComponent<gunPlayer>().GetPoint();
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Ladder : MonoBehaviour {
public GameObject player;
float speed = 0.2f;
public bool canClimb = false;
private Vector3 moveDirection;
void Start () {
}
void OnTriggerEnter(Collider Collider)
{
if (Collider.tag == "Player")
{
canClimb = true;
}
}
void OnTriggerExit(Collider coll2) {
if (coll2.tag == "Player")
{
canClimb = false;
player.GetComponent<Rigidbody>().velocity = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
}
}
void Update()
{
if (canClimb)
{
float x = Input.GetAxis("Horizontal") * speed;
float h = Input.GetAxis("Vertical") * speed;
if (Input.GetAxis("Vertical") > 0 || Input.GetAxis("Horizontal") > 0)
{
// player.transform.Translate (new Vector3(0,h,0));
player.GetComponent<Rigidbody>().velocity = new Vector3(-x, h, 0) * 20;
}
else {
player.GetComponent<Rigidbody>().velocity = Vector3.zero;
}
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityStandardAssets.Characters.FirstPerson;
public class starts : MonoBehaviour {
// public MouseLook mouseLook;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
// mouseLook.m_cursorIsLocked = false;
// mouseLook.lockCursor = true;
}
public void star() {
// SceneManager.LoadScene("testscene", LoadSceneMode.Additive);
// SceneManager.LoadScene("testscene", LoadSceneMode.Single);
Application.LoadLevel("testscene");
}
public void OnLevelWasLoaded(int level)
{
#if UNITY_EDITOR && (UNITY_5_0 || UNITY_5_1 || UNITY_5_2_0)
if (UnityEditor.Lightmapping.giWorkflowMode == UnityEditor.Lightmapping.GIWorkflowMode.Iterative) {
DynamicGI.UpdateEnvironment();
Application.LoadLevel("testscene");
}
#endif
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
public class playerdie : MonoBehaviour {
public float secBeforeFade = 3;
public float fadeTime;
public Texture fadeTexture;
bool fadeIn = false;
private float tempTime;
float time = 0.0f;
public AudioClip die;
// Use this for initialization
void Start() {
AudioSource.PlayClipAtPoint(die, transform.position);
// yield WaitForSeconds(secBeforeFade);(javascripts)
StartCoroutine(Example());
fadeIn = true;
}
IEnumerator Example()
{
yield return new WaitForSeconds(secBeforeFade);
}
// Update is called once per frame
void Update() {
if (fadeIn)
{
if (time < fadeTime) time += Time.deltaTime;
tempTime = Mathf.InverseLerp(0, fadeTime, time);
}
// if (tempTime >= 1.0) SceneManager.LoadScene(0, LoadSceneMode.Single);
}
void OnGUI()
{
if (fadeIn)
{
GUI.color = new Color() { a = tempTime };
/* GUI.color = new Color()
{
a = 0.5f
};*/
// GUI.color.a = tempTime;
GUI.DrawTexture(new Rect(0, 0, Screen.width, Screen.height), fadeTexture);
}
}
}
<file_sep>using UnityEngine;
using System.Collections;
//using System.IO.Ports;
[RequireComponent(typeof(CharacterController))]
public class Unit : MonoBehaviour {
protected CharacterController control;
protected Vector3 move = Vector3.zero;
protected Vector3 gravity = Vector3.zero;
public float walkSpeed= 1f;
public float runSpeed= 5f;
public float turnSpeed= 90f;
public float jumpSpeed=5f;
protected bool jump;
protected bool running;
// Use this for initialization
public virtual void Start () {
control = GetComponent<CharacterController> ();
if (!control) {
print ("ok");
enabled = false;
}
}
// Update is called once per frame
public virtual void Update () {
// dich chuyen theo toc do
if (running)
move *= runSpeed;
else
move *= walkSpeed;
if (!control.isGrounded) {// contrl khong cham dat
gravity +=Physics.gravity * Time.deltaTime;//keo control cham dat
} else {
gravity = Vector3.zero;
if(jump)
{
gravity.y=jumpSpeed;
jump=false;
}
}
move += gravity;
//control.SimpleMove (move * moveSpeed);
control.Move (move * Time.deltaTime);
}
}
|
adb72873eb1d97f7849f85f7b41a5af8f2dd82b0
|
[
"JavaScript",
"C#"
] | 22 |
C#
|
dienanh2210/demofps1234
|
2f33f6b18bac25491dc2c38be49da757f10283b9
|
696eb73175161d17100c91da5ea20c26f9a6cbdd
|
refs/heads/master
|
<repo_name>Suraj0019/Library_System<file_sep>/member.py
class Member:
def __init__(self, member_id, member_name, book_issued):
self.member_id = member_id
self.member_name = member_name
self.book_issued = book_issued
<file_sep>/application.py
import random
session_name = ''
session_id = ''
members = {
'007': 'admin',
}
members_record = {
'007': 'settled'
}
books = {
'1': 'Da Vinci Code',
'2': 'Angels and Demons',
'3': 'Fifty Shades of Grey'
}
books_status = {
'1': 'available',
'2': 'available',
'3': 'available',
}
def id_issue():
Id = random.randint(1001, 1999)
if Id in members:
id_issue()
else:
return Id
def to_borrow_a_book():
print('List of Books with their S.no')
print(books)
book_no = input('Enter the S.no of the book which you want to borrow:')
if book_no in books:
if books_status[book_no] == 'available':
if members_record[session_id] == 'settled':
books_status[book_no] = 'unavailable'
members_record[session_id] = 'pending'
print('Book Issued')
else:
print("We can't issue you a book sir. You already have one book to return.")
else:
print('Sorry Sir! The book is currently unavailable')
else:
print('WRONG S.No')
def to_return_a_book():
print('List of Books with their S.no')
print(books)
book_no = input('Which book do you want to return?')
if book_no in books:
if books_status[book_no] == 'unavailable':
if members_record[session_id] == 'pending':
books_status[book_no] = 'available'
members_record[session_id] = 'settled'
print('Book Returned')
else:
print("You must have mistaken sir. All your accounts are settled")
else:
print("There is some mistake. Please check the book's serial number again")
else:
print('WRONG S.No')
def to_entry_a_new_book():
if session_id == '007' and session_name == 'admin':
print('Howdy, ' + session_name)
book_no = input('Enter the S.no of the Book:')
book_name = input('Enter the name of the Book:')
if book_no in books:
print('This serial no is already available and can not be assigned to any other book')
else:
books[book_no] = book_name
books_status[book_no] = 'available'
else:
print("You don't have access to this area")
print('Welcome to "World of Wisdom"')
user_status = input('Do you have your membership card?(yes/no)')
choice = '0'
if user_status == 'yes':
mem_id = input('Enter your member id:')
mem_name = input('Enter your name:')
if mem_id in members:
if mem_name == members[mem_id]:
print('Welcome ' + mem_name)
session_id = mem_id
session_name = mem_name
else:
print('Wrong Username')
choice = '4'
else:
print('Wrong ID or username')
choice = '4'
elif user_status == 'no':
print('We need some details to issue you a membership card.')
name = input('Tell me your name:')
Id = str(id_issue())
members[Id] = name
members_record[Id] = 'settled'
print('Your card is issued with ' + name + ' as your name and ' + Id + ' as your Id.')
session_name = name
session_id = Id
else:
print('Wrong Input')
choice = '4'
while choice != '4':
print('So, what do you want to do now?')
print('Press "1" to BORROW a book')
print('Press "2" to RETURN a book')
print('Press "3" to ENTER a new book')
print('Press "4" to LEAVE the "World of Wisdom"')
choice = input()
if choice == '1':
to_borrow_a_book()
elif choice == '2':
to_return_a_book()
elif choice == '3':
to_entry_a_new_book()
elif choice == '4':
print('Goodbye, ' + session_name)
else:
print('WRONG INPUT. Try again!')
<file_sep>/README.md
# Library_System
This is a very simple and straight forward Python Project on Library System.
<file_sep>/book.py
class Book:
def __init__(self, book_id, book_name):
self.book_id = book_id
self.book_name = book_name
|
ce407ae46230c4155794f5796dab0310183c400a
|
[
"Markdown",
"Python"
] | 4 |
Python
|
Suraj0019/Library_System
|
2fe1c5938011299ffbe9385f912b00276c1329fc
|
68a3c741d639c762a94c1178cdde7379b0014b9b
|
refs/heads/master
|
<repo_name>youyoutech/test_partners_capital<file_sep>/src/helpers/dataAnalysis.ts
import { Survey, MODE_OF_TRANSPORT, SurveyTotalsByMode, SurveyTotals, CostPerKilometerByMode } from "../types";
export function getTotalJourneysByMode(completedSurveys: Survey[]): Record<MODE_OF_TRANSPORT, number> {
return completedSurveys.reduce((totalJourneysByMode:Record<string, number>, survey:Survey) => {
totalJourneysByMode[survey.modeOfTransport] = (totalJourneysByMode[survey.modeOfTransport] || 0) + 1
return totalJourneysByMode
}, {})
}
export function getAverageSpeedByMode(totalsByMode: SurveyTotalsByMode, journeysByMode: Record<MODE_OF_TRANSPORT, number>): Record<MODE_OF_TRANSPORT, number> {
let averageSpeedByMode: Record<MODE_OF_TRANSPORT, number> = {} as Record<MODE_OF_TRANSPORT, number>
Object.values(MODE_OF_TRANSPORT).forEach((mode: string) => {
averageSpeedByMode[mode as MODE_OF_TRANSPORT] =
totalsByMode[mode].distance / (totalsByMode[mode].time / 60)
})
return averageSpeedByMode
}
export function getAverageCostPerJourney(totalsByMode: SurveyTotalsByMode, totalJourneysByMode: Record<MODE_OF_TRANSPORT, number>): Record<MODE_OF_TRANSPORT, number> {
let averageCostPerJourney: Record<MODE_OF_TRANSPORT, number> = {} as Record<MODE_OF_TRANSPORT, number>
Object.values(MODE_OF_TRANSPORT).forEach((mode: string) => {
averageCostPerJourney[mode as MODE_OF_TRANSPORT] =
totalsByMode[mode].cost / totalJourneysByMode[mode as MODE_OF_TRANSPORT]
})
return averageCostPerJourney
}
export function getAverageDistanceCovered(totalsByMode: SurveyTotalsByMode, totalJourneysByMode: Record<MODE_OF_TRANSPORT, number>): Record<MODE_OF_TRANSPORT, number> {
let averageDistanceCovered: Record<MODE_OF_TRANSPORT, number> = {} as Record<MODE_OF_TRANSPORT, number>
Object.values(MODE_OF_TRANSPORT).forEach((mode: string) => {
averageDistanceCovered[mode as MODE_OF_TRANSPORT] =
totalsByMode[mode].distance / totalJourneysByMode[mode as MODE_OF_TRANSPORT]
})
return averageDistanceCovered
}
export function getAverageTimeTaken(totalsByMode: SurveyTotalsByMode, totalJourneysByMode: Record<MODE_OF_TRANSPORT, number>): Record<MODE_OF_TRANSPORT, number> {
let averageTimeTaken: Record<MODE_OF_TRANSPORT, number> = {} as Record<MODE_OF_TRANSPORT, number>
Object.values(MODE_OF_TRANSPORT).forEach((mode: string) => {
averageTimeTaken[mode as MODE_OF_TRANSPORT] =
totalsByMode[mode].time / totalJourneysByMode[mode as MODE_OF_TRANSPORT]
})
return averageTimeTaken
}
export function getCostPerKilometerByMode(totalsByMode: SurveyTotalsByMode): CostPerKilometerByMode {
let costPerKilometerByMode: CostPerKilometerByMode = {} as CostPerKilometerByMode
Object.values(MODE_OF_TRANSPORT).forEach((mode: string) => {
costPerKilometerByMode[mode as MODE_OF_TRANSPORT] =
totalsByMode[mode].cost / totalsByMode[mode].distance
})
return costPerKilometerByMode
}
export function sumByMode(completedSurveys: Survey[]): SurveyTotalsByMode {
let totalsByMode: SurveyTotalsByMode = {} as SurveyTotalsByMode
Object.values(MODE_OF_TRANSPORT).forEach((mode: string) => {
totalsByMode[mode] =
{ distance: 0, cost: 0, time: 0 } as SurveyTotals
})
return completedSurveys.reduce((totalByMode: SurveyTotalsByMode, survey: Survey) => {
totalByMode[survey.modeOfTransport] = {
cost: totalByMode[survey.modeOfTransport].cost + survey.cost,
time: totalByMode[survey.modeOfTransport].time + survey.time,
distance: totalByMode[survey.modeOfTransport].distance + survey.distance,
}
return totalByMode
}, totalsByMode)
} <file_sep>/src/mockData.ts
export const mockSurveyResults = [
{
username: '<NAME>',
modeOfTransport: 'Train',
distance: 15,
time: 45,
cost: 12
},
{
username: '<NAME>',
modeOfTransport: 'Bus',
distance: 5,
time: 105,
cost: 6
},
{
username: '<NAME>',
modeOfTransport: 'Walk',
distance: 2,
time: 20,
cost: 0
}
, {
username: '<NAME>',
modeOfTransport: 'Train',
distance: 25,
time: 35,
cost: 22
}
, {
username: '<NAME>',
modeOfTransport: 'Bike',
distance: 11,
time: 48,
cost: 0
}
, {
username: '<NAME>',
modeOfTransport: 'Bus',
distance: 4,
time: 19,
cost: 3.50
}
, {
username: '<NAME>',
modeOfTransport: 'Bike',
distance: 8,
time: 35,
cost: 0
}
, {
username: '<NAME>',
modeOfTransport: 'Train',
distance: 30,
time: 45,
cost: 12
}
, {
username: '<NAME>',
modeOfTransport: 'Car',
distance: 45,
time: 120,
cost: 26.5
}
, {
username: '<NAME>',
modeOfTransport: 'Underground',
distance: 12,
time: 65,
cost: 5.6
}
, {
username: '<NAME>',
modeOfTransport: 'Underground',
distance: 5,
time: 25,
cost: 3.4
}
, {
username: '<NAME>',
modeOfTransport: 'Underground',
distance: 11,
time: 55,
cost: 6.5
}
, {
username: '<NAME>',
modeOfTransport: 'Car',
distance: 5,
time: 20,
cost: 4
}
]<file_sep>/src/types.ts
export interface Survey {
username: string
modeOfTransport: string
distance: number
time: number
cost: number
}
export interface SurveyAppState {
completedSurveys: Survey[]
totalsByMode: SurveyTotalsByMode
journeysByMode: Record<MODE_OF_TRANSPORT, number>
showResults: boolean
}
export enum MODE_OF_TRANSPORT {
BIKE = 'Bike',
CAR = 'Car',
WALK = 'Walk',
TRAIN = 'Train',
UNDERGROUND = 'Underground',
BUS = 'Bus'
}
export interface SurveyTotals {
distance: number
time: number
cost: number
}
export type SurveyTotalsByMode = Record<string, SurveyTotals>
export type CostPerKilometerByMode = Record<string, number>
export interface AddSurveyAction {
type: string
payload: Survey
}<file_sep>/src/reducers/index.ts
import { SurveyAppState, AddSurveyAction } from '../types'
import { mockSurveyResults } from '../mockData'
import {sumByMode, getTotalJourneysByMode} from '../helpers/dataAnalysis'
const initialState: SurveyAppState = {
completedSurveys: mockSurveyResults,
totalsByMode: sumByMode(mockSurveyResults),
journeysByMode: getTotalJourneysByMode(mockSurveyResults),
showResults: false
}
export default (state: SurveyAppState = initialState, action: AddSurveyAction): SurveyAppState => {
switch (action.type) {
case 'SHOW_RESULTS':
return {
...state,
showResults: true,
}
case 'SHOW_SURVEY':
return {
...state,
showResults: false,
}
case 'ADD_SURVEY':
return {
completedSurveys: [...state.completedSurveys, action.payload],
totalsByMode: sumByMode([...state.completedSurveys, action.payload]),
journeysByMode: getTotalJourneysByMode([...state.completedSurveys, action.payload]),
showResults: false
}
default:
return state
}
}<file_sep>/src/helpers/dataAnalysis.test.ts
import { getTotalJourneysByMode, getCostPerKilometerByMode, getAverageSpeedByMode, sumByMode, getAverageDistanceCovered, getAverageCostPerJourney, getAverageTimeTaken } from "./dataAnalysis"
import { mockSurveyResults } from "../mockData"
import { MODE_OF_TRANSPORT } from "../types"
describe('getTotalJourneysByMode', () => {
let totalJourneys: Record<MODE_OF_TRANSPORT, number>
beforeEach(() => {
totalJourneys = getTotalJourneysByMode(mockSurveyResults)
})
it('returns expected sum for Walk journeys', () => {
expect(totalJourneys.Walk).toBe(1)
})
it('returns expected sum for Bike journeys', () => {
expect(totalJourneys.Bike).toBe(2)
})
it('returns expected sum for Car journeys', () => {
expect(totalJourneys.Car).toBe(2)
})
it('returns expected sum for Bus journeys', () => {
expect(totalJourneys.Bus).toBe(2)
})
it('returns expected sum for Train journeys', () => {
expect(totalJourneys.Train).toBe(3)
})
it('returns expected sum for Underground journeys', () => {
expect(totalJourneys.Underground).toBe(3)
})
})
describe('getCostPerKilometerByMode', () => {
let costPerKilometerByMode: Record<MODE_OF_TRANSPORT, number>
beforeEach(() => {
costPerKilometerByMode = getCostPerKilometerByMode(sumByMode(mockSurveyResults))
})
it('returns expected cost/km for Walk journeys', () => {
expect(costPerKilometerByMode.Walk).toBe(0)
})
it('returns expected cost/km for Bike journeys', () => {
expect(costPerKilometerByMode.Bike).toBe(0)
})
it('returns expected cost/km for Car journeys', () => {
expect(costPerKilometerByMode.Car).toBe(0.61)
})
it('returns expected cost/km for Bus journeys', () => {
expect(costPerKilometerByMode.Bus).toBe(1.0555555555555556)
})
it('returns expected cost/km for Train journeys', () => {
expect(costPerKilometerByMode.Train).toBe(0.6571428571428571)
})
it('returns expected cost/km for Underground journeys', () => {
expect(costPerKilometerByMode.Underground).toBe(0.5535714285714286)
})
})
describe('getAverageSpeedByMode', () => {
let averageSpeedByMode: Record<MODE_OF_TRANSPORT, number>
beforeEach(() => {
averageSpeedByMode = getAverageSpeedByMode(sumByMode(mockSurveyResults), getTotalJourneysByMode(mockSurveyResults))
})
it('returns expected average speed in km/h for Walk journeys', () => {
expect(averageSpeedByMode.Walk).toBe(6)
})
it('returns expected average speed in km/h for Bike journeys', () => {
expect(averageSpeedByMode.Bike).toBe(13.734939759036145)
})
it('returns expected average speed in km/h for Car journeys', () => {
expect(averageSpeedByMode.Car).toBe(21.428571428571427)
})
it('returns expected average speed in km/h for Bus journeys', () => {
expect(averageSpeedByMode.Bus).toBe(4.354838709677419)
})
it('returns expected average speed in km/h for Train journeys', () => {
expect(averageSpeedByMode.Train).toBe(33.599999999999994)
})
it('returns expected average speed in km/h for Underground journeys', () => {
expect(averageSpeedByMode.Underground).toBe(11.586206896551724)
})
})
describe('getAverageCostPerJourney', () => {
let averageCostPerJourney: Record<MODE_OF_TRANSPORT, number>
beforeEach(() => {
averageCostPerJourney = getAverageCostPerJourney(sumByMode(mockSurveyResults), getTotalJourneysByMode(mockSurveyResults))
})
it('returns expected cost/journey for Walk journeys', () => {
expect(averageCostPerJourney.Walk).toBe(0)
})
it('returns expected cost/journey for Bike journeys', () => {
expect(averageCostPerJourney.Bike).toBe(0)
})
it('returns expected cost/journey for Car journeys', () => {
expect(averageCostPerJourney.Car).toBe(15.25)
})
it('returns expected cost/journey for Bus journeys', () => {
expect(averageCostPerJourney.Bus).toBe(4.75)
})
it('returns expected cost/journey for Train journeys', () => {
expect(averageCostPerJourney.Train).toBe(15.333333333333334)
})
it('returns expected cost/journey for Underground journeys', () => {
expect(averageCostPerJourney.Underground).toBe(5.166666666666667)
})
})
describe('getAverageDistanceCovered', () => {
let averageDistanceCovered: Record<MODE_OF_TRANSPORT, number>
beforeEach(() => {
averageDistanceCovered = getAverageDistanceCovered(sumByMode(mockSurveyResults), getTotalJourneysByMode(mockSurveyResults))
})
it('returns expected average distance covered for Walk journeys', () => {
expect(averageDistanceCovered.Walk).toBe(2)
})
it('returns expected average distance covered for Bike journeys', () => {
expect(averageDistanceCovered.Bike).toBe(9.5)
})
it('returns expected average distance covered for Car journeys', () => {
expect(averageDistanceCovered.Car).toBe(25)
})
it('returns expected average distance covered for Bus journeys', () => {
expect(averageDistanceCovered.Bus).toBe(4.5)
})
it('returns expected average distance covered for Train journeys', () => {
expect(averageDistanceCovered.Train).toBe(23.333333333333332)
})
it('returns expected average distance covered for Underground journeys', () => {
expect(averageDistanceCovered.Underground).toBe(9.333333333333334)
})
})
describe('getAverageTimeTaken', () => {
let averageTimeTaken: Record<MODE_OF_TRANSPORT, number>
beforeEach(() => {
averageTimeTaken = getAverageTimeTaken(sumByMode(mockSurveyResults), getTotalJourneysByMode(mockSurveyResults))
})
it('returns expected average time taken for Walk journeys', () => {
expect(averageTimeTaken.Walk).toBe(20)
})
it('returns expected average time taken for Bike journeys', () => {
expect(averageTimeTaken.Bike).toBe(41.5)
})
it('returns expected average time taken for Car journeys', () => {
expect(averageTimeTaken.Car).toBe(70)
})
it('returns expected average time taken for Bus journeys', () => {
expect(averageTimeTaken.Bus).toBe(62)
})
it('returns expected average time taken for Train journeys', () => {
expect(averageTimeTaken.Train).toBe(41.666666666666664)
})
it('returns expected average time taken for Underground journeys', () => {
expect(averageTimeTaken.Underground).toBe(48.333333333333336)
})
})
|
cd364dd1023d7c74262bf2911e8daf6fc41caaff
|
[
"TypeScript"
] | 5 |
TypeScript
|
youyoutech/test_partners_capital
|
afcd9ccdf259ab1395294bd8cee880dc746dde83
|
22e2c96158ff2b90c9b0815c8b3850abaa3536f4
|
refs/heads/master
|
<repo_name>tysmitty94/pokemongobarrhaven<file_sep>/ProjectMeowth/Scripts/homepage.js
jQuery(document).ready(function ($) {
var theme = localStorage.getItem('theme');
var themeName = '';
/*
if (localStorage.getItem('theme') === null) {
localStorage.setItem('theme', 'default');
}
*/
switch (theme) {
case "valor":
themeName = 'valor-bg';
setBackground(themeName);
break;
case "instinct":
themeName = 'instinct-bg';
setBackground(themeName);
break;
case "mystic":
themeName = 'mystic-bg';
setBackground(themeName);
break;
case "none":
themeName = 'blank-bg';
setBackground(themeName);
break;
//case "default":
default:
themeName = 'trio-bg2';
setBackground(themeName);
break;
}
$('#valorBtn').click(function (e) {
e.preventDefault();
localStorage.setItem('theme', 'valor');
themeName = 'valor-bg';
setBackground(themeName);
});
$('#mysticBtn').click(function (e) {
e.preventDefault();
localStorage.setItem('theme', 'mystic');
themeName = 'mystic-bg';
setBackground(themeName);
});
$('#instinctBtn').click(function (e) {
e.preventDefault();
localStorage.setItem('theme', 'instinct');
themeName = 'instinct-bg';
setBackground(themeName);
});
$('#btnBlankBackground').click(function (e) {
e.preventDefault();
localStorage.setItem('theme', 'none');
themeName = 'blank-bg';
setBackground(themeName);
});
$('#defaultBtn').click(function (e) {
e.preventDefault();
localStorage.setItem('theme', 'default');
themeName = 'trio-bg2';
setBackground(themeName);
});
function setBackground(themeName) {
if (themeName == 'blank-bg') {
$('body').css('background', '#B4E1D9');
} else {
$('body').css('background-image', 'linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)), url("/Content/Images/' + themeName + '.png")');
}
}
});<file_sep>/ProjectMeowth/Migrations/201904170529542_PlayerName.cs
namespace ProjectMeowth.Migrations
{
using System;
using System.Data.Entity.Migrations;
public partial class PlayerName : DbMigration
{
public override void Up()
{
AddColumn("dbo.AspNetUsers", "PlayerName", c => c.String());
AddColumn("dbo.AspNetUsers", "Team", c => c.String());
AddColumn("dbo.AspNetUsers", "GameExperience", c => c.Int(nullable: false));
}
public override void Down()
{
DropColumn("dbo.AspNetUsers", "GameExperience");
DropColumn("dbo.AspNetUsers", "Team");
DropColumn("dbo.AspNetUsers", "PlayerName");
}
}
}
<file_sep>/ProjectMeowth/Trades.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace ProjectMeowth
{
public partial class Trades : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
HtmlImage img = new HtmlImage();
img.Attributes.Add("class", "pokemonImage");
img.Src = "/Content/img/Loading Pokeball-xs.gif";
tmpPanel.Controls.Add(img);
tmpPanel.Attributes.Add("class", "text-center");
}
}
}<file_sep>/ProjectMeowth/Models/PokemonModel.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace ProjectMeowth.Models
{
public class PokemonModel
{
public PokemonModel(string Name, int SpeciesID, int Generation, string PokemonType)
{
this.Name = Name;
this.SpeciesID = SpeciesID;
this.Generation = Generation;
this.PokemonType = PokemonType;
}
public string Name { get; }
public int SpeciesID { get; }
public int Generation { get; }
public string PokemonType { get; }
}
}<file_sep>/ProjectMeowth/MyProfile.aspx.cs
using Microsoft.AspNet.Identity.Owin;
using ProjectMeowth.Helpers;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace ProjectMeowth
{
public partial class MyProfile : System.Web.UI.Page
{
public string PlayerName { get; private set; }
public string TeamName { get; private set; }
public int GameExperience { get; private set; }
public int Level { get; private set; }
protected void Page_Load(object sender, EventArgs e)
{
PlayerName = User.Identity.GetPlayerName();
TeamName = User.Identity.GetTeamName();
GameExperience = User.Identity.GetGameExperience();
Level = AccountHelper.ConvertExpToLevel(GameExperience);
}
}
}<file_sep>/ProjectMeowth/Startup.cs
using Microsoft.Owin;
using Owin;
[assembly: OwinStartupAttribute(typeof(ProjectMeowth.Startup))]
namespace ProjectMeowth
{
public partial class Startup {
public void Configuration(IAppBuilder app) {
ConfigureAuth(app);
}
}
}
<file_sep>/ProjectMeowth/Account/Register.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Owin;
using ProjectMeowth.Models;
namespace ProjectMeowth.Account
{
public partial class Register : Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void CreateUser_Click(object sender, EventArgs e)
{
var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
var signInManager = Context.GetOwinContext().Get<ApplicationSignInManager>();
int parsedExp = -1;
int.TryParse(Experience.Text, out parsedExp);
var user = new ApplicationUser() {
UserName = Email.Text,
Email = Email.Text,
PlayerName = TrainerName.Text,
Team = TeamDropdown.SelectedItem.Text,
GameExperience = parsedExp
};
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
//string code = manager.GenerateEmailConfirmationToken(user.Id);
//string callbackUrl = IdentityHelper.GetUserConfirmationRedirectUrl(code, user.Id, Request);
//manager.SendEmail(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>.");
signInManager.SignIn(user, isPersistent: false, rememberBrowser: false);
IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
}
/*
ErrorMessage.Visible = false;
SuccessMessage.Visible = false;
try
{
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
var sql = "INSERT INTO reg (name, email, team, exp, password) VALUES (@name, @email, @team, @exp, @password)";
using (var cmd = new SqlCommand(sql, connection))
{
cmd.Parameters.AddWithValue("@name", TrainerName.Text);
cmd.Parameters.AddWithValue("@email", Email.Text);
cmd.Parameters.AddWithValue("@team", TeamDropdown.SelectedItem.Value);
cmd.Parameters.AddWithValue("@exp", Experience.Text);
cmd.Parameters.AddWithValue("@password", Password.Text);
cmd.ExecuteNonQuery();
ErrorMessage.Visible = false;
SuccessMessage.Visible = true;
SuccessMessage.Text = "Registration Successful!";
}
}
}
catch (Exception ex)
*/
else
{
ErrorMessage.Text = result.Errors.FirstOrDefault();
/*
SuccessMessage.Visible = false;
ErrorMessage.Visible = true;
ErrorMessage.Text = ex.Message;
*/
}
}
}
}<file_sep>/ProjectMeowth/Pokedex.aspx.cs
using ProjectMeowth.Helpers;
using ProjectMeowth.Models;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
namespace ProjectMeowth
{
public partial class Pokedex : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{
}
PokedexFakeGenerator generator = new PokedexFakeGenerator();
List<PokemonModel> lstPokemon = generator.GetFakePokedex();
HtmlGenericControl bootStrapRow = new HtmlGenericControl("div");
bootStrapRow.Attributes.Add("class", "row align-items-center");
PokedexGrid.Controls.Add(bootStrapRow);
lstPokemon.ForEach(x =>
//lstPokemon.Take(20).ToList<PokemonModel>().ForEach(x =>
{
string customClass = "Generation-" + x.Generation.ToString() + " " + x.PokemonType;
HtmlGenericControl cardWrapper = new HtmlGenericControl("div");
cardWrapper.Attributes.Add("class", "card border-info col-sm-3 col-md-4 col-lg-2 grid-item " + customClass);
// Due to jQuery.imgCheckbox, cards are getting overlapped on each other, so we need to add margin-bottom for the label.
cardWrapper.Attributes.Add("style", "margin-bottom: 3%; min-height: 110px;");
HtmlGenericControl cardContents = new HtmlGenericControl("div");
cardContents.Attributes.Add("class", "pokemonCard");
HtmlGenericControl cardBody = new HtmlGenericControl("div");
cardBody.Attributes.Add("class", "card-body");
HtmlGenericControl cardImage = new HtmlGenericControl("div");
cardImage.Attributes.Add("class", "card-img-top mx-auto");
cardImage.Attributes.Add("data-speciesid", "SpeciesID-" + x.SpeciesID);
HtmlImage img = new HtmlImage();
img.Attributes.Add("class", "pokemonImage");
//img.Src = "/Content/img/Loading Pokeball-xs.gif";
String imageURL = "/Content/img/pokemon/" + x.SpeciesID + ".png";
if (File.Exists(Server.MapPath(imageURL)))
{
img.Attributes.Add("data-src", imageURL);
img.Attributes.Add("height", "100px");
}
cardImage.Controls.Add(img);
HtmlGenericControl cardTitle = new HtmlGenericControl();
cardTitle.Attributes.Add("class", "card-title");
cardTitle.InnerText = x.Name;
cardBody.Controls.Add(cardTitle);
cardContents.Controls.Add(cardImage);
cardContents.Controls.Add(cardBody);
cardWrapper.Controls.Add(cardContents);
bootStrapRow.Controls.Add(cardWrapper);
});
}
protected void btnSave_Click(object sender, EventArgs e)
{
return;
//
//foo[0].querySelector("[data-speciesID]").getAttribute("data-speciesID")
List<HtmlGenericControl> foo = PokedexGrid.FindDescendants<HtmlGenericControl>().ToList();
foo = foo.Where(x => x.Attributes["imgChked"] != null).ToList();
Panel pnlTest = (Panel)vwSavedSelection.FindControl("pnlTest");
foo.ForEach(x => pnlTest.Controls.Add(x));
}
}
}<file_sep>/ProjectMeowth/Helpers/AccountHelper.cs
using Microsoft.AspNet.Identity;
using ProjectMeowth.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Security.Principal;
using System.Web;
using System.Web.Security;
namespace ProjectMeowth.Helpers
{
public static class AccountHelper
{
public static bool IsLoggedIn()
{
bool val1 = (System.Web.HttpContext.Current.User != null) && System.Web.HttpContext.Current.User.Identity.IsAuthenticated;
return val1;
}
public static String GetUsername()
{
string userName = string.Empty;
if (System.Web.HttpContext.Current != null &&
System.Web.HttpContext.Current.User.Identity.IsAuthenticated)
{
var usr = HttpContext.Current.User.Identity;
if (usr != null)
{
userName = usr.Name;
}
}
return userName;
}
public static string GetPlayerName(this IIdentity identity)
{
if(identity == null)
{
throw new ArgumentException("Identity is null!");
}
var ci = identity as ClaimsIdentity;
if(ci != null)
{
return ci.FindFirstValue("PlayerName");
}
return "Anonymous PlayerName";
}
public static string GetTeamName(this IIdentity identity)
{
if (identity == null)
{
throw new ArgumentException("Identity is null!");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
return ci.FindFirstValue("TeamName");
}
return "Team Rocket?";
}
public static int GetGameExperience(this IIdentity identity)
{
int exp = -1;
if (identity == null)
{
throw new ArgumentException("Identity is null!");
}
var ci = identity as ClaimsIdentity;
if (ci != null)
{
string result = ci.FindFirstValue("Exp");
int.TryParse(result, out exp);
return exp;
}
return -2;
}
public static int ConvertExpToLevel(int exp)
{
int output = 42;
switch(exp)
{
case int n when (n >= 20000000): output = 40; break;
case int n when (n >= 15000000): output = 39; break;
case int n when (n >= 12000000): output = 38; break;
case int n when (n >= 9500000): output = 37; break;
case int n when (n >= 7500000): output = 36; break;
case int n when (n >= 6000000): output = 35; break;
case int n when (n >= 4750000): output = 34; break;
case int n when (n >= 3750000): output = 33; break;
case int n when (n >= 3000000): output = 32; break;
case int n when (n >= 2500000): output = 31; break;
case int n when (n >= 2000000): output = 30; break;
case int n when (n >= 1650000): output = 29; break;
case int n when (n >= 1350000): output = 28; break;
case int n when (n >= 1100000): output = 27; break;
case int n when (n >= 900000): output = 26; break;
case int n when (n >= 710000): output = 25; break;
case int n when (n >= 560000): output = 24; break;
case int n when (n >= 435000): output = 23; break;
case int n when (n >= 335000): output = 22; break;
case int n when (n >= 260000): output = 21; break;
case int n when (n >= 210000): output = 20; break;
case int n when (n >= 185000): output = 19; break;
case int n when (n >= 160000): output = 18; break;
case int n when (n >= 140000): output = 17; break;
case int n when (n >= 120000): output = 16; break;
case int n when (n >= 100000): output = 15; break;
case int n when (n >= 85000): output = 14; break;
case int n when (n >= 75000): output = 13; break;
case int n when (n >= 65000): output = 12; break;
case int n when (n >= 55000): output = 11; break;
case int n when (n >= 45000): output = 10; break;
case int n when (n >= 36000): output = 9; break;
case int n when (n >= 28000): output = 8; break;
case int n when (n >= 21000): output = 7; break;
case int n when (n >= 15000): output = 6; break;
case int n when (n >= 10000): output = 5; break;
case int n when (n >= 6000): output = 4; break;
case int n when (n >= 3000): output = 3; break;
case int n when (n >= 1000): output = 2; break;
case int n when (n >= 0): output = 1; break;
default: output = 43; break;
}
return output;
}
}
}
|
60c2c812a1d37678ab983a72b6d3ab99afc88f4a
|
[
"JavaScript",
"C#"
] | 9 |
JavaScript
|
tysmitty94/pokemongobarrhaven
|
4dd8752d41436c26861d3a1c5b8eeaf28daf58f9
|
ff4419b5a8dc7c1e214fb45902dbab1bdeeae29b
|
refs/heads/master
|
<repo_name>Hakuna-Matata-/TestChat<file_sep>/src/main/java/xellos/aka/atan/Collections/testMap.java
package xellos.aka.atan.Collections;
import java.util.Map;
import java.util.WeakHashMap;
public class TestMap {
public static void main(String[] args) {
// Map<Integer, String> map = new LinkedHashMap<Integer, String>(5, 1, true);
// map.put(5, "a");
// map.put(4, "b");
// map.put(3, "c");
// map.put(2, "d");
// map.put(1, "e");
// map.get(3);
// map.get(5);
// map.get(1);
// Map<Integer, String> map = new SimpleLRUCache(2);
// map.put(3, "c");
// map.put(2, "d");
// map.put(1, "e");
// map.get(2);
// map.put(9, "q");
// System.out.println(map);
Map<Integer, String> map = new WeakHashMap<Integer, String>();
Integer data = new Integer(1);
map.put(data, "information");
data = null;
System.gc();
for (int i = 1; i < 10000; i++) {
if (map.isEmpty()) {
System.out.println(i + " Empty!");
break;
}
}
}
}<file_sep>/README.md
TestChat
========
This is my first tentative project for learning Java.
I planing to make simple Chat step by step and complicate it after some time.
<file_sep>/src/main/java/xellos/aka/atan/server/ThreadedEchoHandler.java
package xellos.aka.atan.server;
import xellos.aka.atan.server.Storage.Message;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;
class ThreadedEchoHandler implements Runnable {
private Socket incoming;
private PrintWriter out;
public ThreadedEchoHandler(Socket socket) {
incoming = socket;
}
public boolean sendMessage(Message message) {
boolean success = false;
out.println(message);
return success;
}
public boolean sendMessage(String message) {
boolean success = false;
out.println("\n" + message);
return success;
}
public Message createMessage(String text) {
Message message = new Message("\n" + text);
return message;
}
@Override
public void run() {
try {
try {
boolean done = false;
InputStream inStream = incoming.getInputStream();
OutputStream outputStream = incoming.getOutputStream();
Scanner in = new Scanner(inStream);
out = new PrintWriter(outputStream, true);
out.println("Enter \"BYE\" to exit...");
while (!done && in.hasNextLine()) {
String line = in.nextLine();
System.out.println(line);
sendMessage("Echo: " + line);
//sendMessage(createMessage("Echo: " + line));
if (line.trim().equals("BYE")) {
done = true;
ChatServer.connectionCount--;
}
if (line.trim().equals("shutdown")) { // TODO fix shutdown (it doesn't work immediately)
done = true;
ChatServer.process = false;
ChatServer.connectionCount--;
incoming.close();
break;
}
}
} catch (Exception e) {System.out.println(e);}
finally {
incoming.close();
}
} catch (Exception e) {System.out.println(e);}
}
}
<file_sep>/src/test/java/xellos/aka/atan/examples/WorldTimeServer.java
package xellos.aka.atan.examples;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.Scanner;
public class WorldTimeServer {
public static void main(String[] arg) throws IOException {
String server = "time-A.timefreq.bldrdoc.gov"; // time-A.timefreq.bldrdoc.gov
try {
Socket s = new Socket();
s.connect(new InetSocketAddress(server, 8080));
InputStream inStream = s.getInputStream();
Scanner in = new Scanner(inStream);
while (in.hasNextLine()) {
String line = in.nextLine();
System.out.println(line);
}
} catch (Exception e) { System.out.println(e);}
}
}
<file_sep>/src/main/java/xellos/aka/atan/Collections/TestQueue.java
package xellos.aka.atan.Collections;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
public class TestQueue {
static class Comp implements Comparator<Integer> {
@Override
public int compare(Integer o1, Integer o2) {
if ((o1 / 2) > (o2 / 2))
return -1;
else
if ((o1 / 2) < (o2 / 2))
return 1;
else
return 0;
}
}
public static void main(String[] args) {
// Comparator c = new Comparator() {
// @Override
// public int compare(Object o1, Object o2) {
// if (((Integer)o1 / 2) > ((Integer)o2 / 2))
// return -1;
// else
// if (((Integer)o1 / 2) < ((Integer)o2 / 2))
// return 1;
// else
// return 0;
// }
// };
Comparator c = new Comp();
Queue pq = new PriorityQueue<Integer>();
pq.add(5);
pq.add(2);
pq.add(1);
pq.add(4);
while (!pq.isEmpty()) {
System.out.println(pq.poll());
}
// Queue<Integer> q = new LinkedList<>();
// q.add(5);
// q.add(4);
// q.add(3);
// q.add(2);
// q.add(1);
// while (!q.isEmpty()) {
// System.out.println(q.poll());
// }
}
}
<file_sep>/src/main/java/xellos/aka/atan/Collections/TestSet.java
package xellos.aka.atan.Collections;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;
public class TestSet {
public static void main(String[] args) {
System.out.println("Start");
NavigableSet<Integer> sortedSet = new TreeSet<Integer>();
for (int i = 1; i < 11; i++) {
sortedSet.add(i);
}
// System.out.println(sortedSet);
for (Iterator<Integer> k = sortedSet.iterator(); k.hasNext();) {
Integer elem = k.next();
if (elem == 5) {
k.remove();
continue;
}
System.out.println(elem);
}
}
Integer getNextElem(Integer elem) {
Integer nextElem = null;
return nextElem;
}
// Set<Integer> set = new TreeSet<>(new Comparator<Integer>() {
// @Override
// public int compare(Integer o1, Integer o2) {
// return 0;
// }
// });
//
// set.add(1);
// set.add(2);
// set.add(1);
// System.out.println(set);
}
<file_sep>/src/main/java/xellos/aka/atan/client/ChatClient.java
package xellos.aka.atan.client;
import java.io.*;
import java.net.Socket;
import static xellos.aka.atan.server.ChatServer.CHARSET;
public class ChatClient {
private Socket socket;
private String nickName;
private BufferedWriter writer;
private BufferedReader userInput;
public ChatClient(String host, int port) throws IOException {
String userAnswer;
userInput = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter server IP adress or hit Enter for default host");
userAnswer = userInput.readLine();
if (userAnswer.length() != 0) {
host = userAnswer;
}
System.out.println("Enter server port or hit Enter for default port");
userAnswer = userInput.readLine();
if (userAnswer.length() != 0) {
int newPort = Integer.parseInt(userAnswer);
if (newPort > 1024 && newPort < 65535) {
port = newPort;
}
}
System.out.println("Trying connect to " + host + ":" + port + "...");
socket = new Socket(host, port);
writer = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(), CHARSET));
}
public void run() throws IOException {
final ClientReader clientReader = new ClientReader(socket);
new Thread(clientReader, "Clientreader").start();
String s;
while(!(s = userInput.readLine()).equals("")) {
writeString(s);
}
}
public static void main(String[] args) throws IOException {
System.out.println("*** Client is running *** ");
}
public void writeString(String s) throws IOException {
writer.write(s);
writer.write("/n");
writer.flush();
}
public void close() {
if (socket != null && !socket.isClosed()) {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
@Override
public void finalize() throws Throwable {
super.finalize();
close();
}
public String getNickName() {
return nickName;
}
}
|
57cc88086a5edd645f574d0602b39487036f9568
|
[
"Markdown",
"Java"
] | 7 |
Java
|
Hakuna-Matata-/TestChat
|
9aef4ad84c7c1ffcd30b4876c291a2a6a39bd6c3
|
1cd835410a75aac9b6c612e3fee9a8902cdc8958
|
refs/heads/main
|
<repo_name>piyush-hack/takeNoteApp<file_sep>/README.md
# CrudsOnMongodb
# open master branch for files related project
### visit live example at
### http://crudsmongodb.herokuapp.com/#freshpage
|
3a3f2b9fea1e3e751e15bb4db3921cd0803f0f01
|
[
"Markdown"
] | 1 |
Markdown
|
piyush-hack/takeNoteApp
|
a27fa459d725b268149e89401be2d4e1f515badb
|
10d8a43f4d7fdad4629358c82f9b0dd5e9daed38
|
refs/heads/master
|
<repo_name>eabell94/eabell94.github.io<file_sep>/README.md
# eabell94.github.io
<file_sep>/multest.rs
[#test]
fn is_this_correct(){
assert_eq!(Some(6), eval(&[Token::Operand(2),
Token::Operand(3),
Token::Operator(Operator::Mul)]));
}<file_sep>/index.md
## About Me
My name is <NAME> and I am an undergraduate student at the University of California, Davis majoring in Applied Statistics with an emphasis in Managerial Economics. I am proficient with R and have experience with C, Rust, and Python. In addition I also have experience using SQL through the R and Python languages and limited familiarity in SAS. In Python I have used the numpy, pandas, seaborn, basemap, sqlite3, and matplotlib packages to visualize and analyze data from a variety of sources. I have worked for two years in Operations and Guest Services for the UC Davis Bookstore, with one data-related duty being the providing of insight with regards to purchasing trends in the store in an effort to improve sales. My goal is to reach proficiency and eventual mastery of stastistcal computing packages through extensive experience in an effort to attain a data analyst position. My interests stem from a intrigue in the identification and visualization of trends within data sets to answer a wide range of questions. In particular, I am interested in data that relate to the following:
* Development of Technology
* Social Trends and Behavior relating to the popularity of tech brands and features
* Sports, specifically the analysis of individual player efficiency, impactfulness, and skillset improvement
* Business, specifically visualization and prediction of profit trajectory
* Finance, consultation on and the analysis and optimization of personal finances and business expenses
* Population behavior in metropolitan areas
* Any subject relating to my native state of California
* Demographic shifts and population densities within the city of Los Angeles
* * *
## Coursework Completed
#### Statistics
* STA 108 - Regression Analysis
* STA 106 - Analysis of Variance
* STA 104 - Nonparametric Statistics
* STA 145 - Bayesian Statistal Inference
* STA 141 - Statistical Computing
* STA 137 - Applied Time Series Analysis
* STA 138 - Analysis of Categorical Data
* STA 141B - Data & Web Technologies for Data Analysis
#### Economics
* ARE 100A - Intermediate Microeconomics
* ARE 100B - Intermediate Macroeconomics
* ARE 106 - Econometrics
* ARE 142 - Personal Finance
* ARE 155 - Operation Resources and Management Science
* * *
## Statistical Projects
[UFOs and Disasters Project](https://eabell94.github.io/EAB%2BSecond%2BAnalysis.html)
<b>Description:</b> The objective was to answer a series of questions regarding a UFO sightings data set and a natural disasters data set, both focused on the United States. My portion of questions focused on identifying the most reported UFO sightings and top disasters; and potential correlations between state counties that had either the most reported disasters; the most reported UFO sightings; or the county with the longest declared disaster.
<b>Project completed in collaboration with:</b> [<NAME>](https://nicholas-alonzo.github.io/), [<NAME>](https://zora2028.github.io/) and [<NAME>](https://mmadet.github.io/)
[Repository](https://nicholas-alonzo.github.io/Projects/UCD%20Projects/Data%20and%20Web%20Technologies/datawebtech.html)
* * *
[Fruits and Vegetables: .CSV and JSON Familiarization](https://eabell94.github.io/assignment4.html)
<b>Description:</b> In this individual assignment the purpose was to gain experience querying a website API to acquire data on a specified search query in a JSON format and perform an analysis of it.
* * *
[Project 3](link3)
* * *
[Project 4](link4)
##### *To be updated with older work
|
68e56796fd0184239042f1406fd868c0e9853a74
|
[
"Markdown",
"Rust"
] | 3 |
Markdown
|
eabell94/eabell94.github.io
|
47024f7651b97d0ef713c6ec7771cb0f9967eccd
|
e3a3c0203586e7edfd62e13edf3bfc75b11c3f8d
|
refs/heads/main
|
<repo_name>mdabdulbari/posts<file_sep>/src/views/PostDetails/index.js
import { Button, Card, withStyles } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import PrimaryHeader from "../../components/Header/PrimaryHeader";
import Post from "../../components/Post";
import { getCall } from "../../utils/helpers";
import styles from "./styles";
const PostDetails = ({ classes, history, match }) => {
const emptyPost = {
title: "",
description: "",
};
const [postDetails, setPostDetails] = useState(emptyPost);
const fetchPost = () => {
const { postId } = match.params;
getCall(`/${postId}`).then((res) => {
const post = res.data;
setPostDetails(post);
});
};
useEffect(fetchPost, emptyPost);
return (
<div>
<PrimaryHeader history={history} />
<div className={classes.postContainer}>
{postDetails.title !== "" ? (
<Post postDetails={postDetails} allowActions={false} />
) : (
"Loading..."
)}
</div>
</div>
);
};
export default withStyles(styles)(PostDetails);
<file_sep>/src/views/Home/index.js
import { Fab, withStyles } from "@material-ui/core";
import React, { useEffect, useState } from "react";
import DeleteIcon from "@material-ui/icons/Delete";
import Header from "../../components/Header";
import PostModal from "../../components/PostModal";
import Post from "../../components/Post";
import { deleteCall, getCall, postCall, putCall } from "../../utils/helpers";
import styles from "./styles";
const Home = ({ classes, history }) => {
const [posts, setPosts] = useState([]);
const [isNewPostModalOpen, setIsNewPostModalOpen] = useState(false);
const [postDetails, setPostDetails] = useState({
title: "",
description: "",
});
const [type, setType] = useState("new");
const [postsSelected, setPostsSelected] = useState([]);
const fetchPosts = () => {
getCall("/").then((res) => {
const posts = res.data;
setPosts(posts);
});
};
const toggleModal = () => {
setIsNewPostModalOpen(!isNewPostModalOpen);
};
const onSubmit = (title, text) => {
if (type === "edit") {
putCall(`/${postDetails.id}`, {
...postDetails,
title: title,
text: text,
}).then(() => {
setIsNewPostModalOpen(false);
fetchPosts();
});
} else {
postCall("/posts", { title, text }).then(() => {
setIsNewPostModalOpen(false);
fetchPosts();
});
}
};
const onNewPostClick = () => {
setPostDetails({ title: "", description: "" });
setType("new");
setIsNewPostModalOpen(true);
};
const handleEdit = (post) => {
setPostDetails(post);
setType("edit");
setIsNewPostModalOpen(true);
};
const deletePost = (id) => {
deleteCall(`/${id}`).then(fetchPosts);
};
const handleCheckboxClick = (id) => {
const index = postsSelected.indexOf(id);
if (index === -1) {
setPostsSelected([...postsSelected, id]);
} else {
let currentPostsSelected = [...postsSelected];
currentPostsSelected.splice(index, 1);
setPostsSelected(currentPostsSelected);
}
};
const onBulkDelete = () => {
const ids = postsSelected
.reduce((id, sum) => sum + "," + id, "")
.slice(0, -1);
deleteCall(`/bulkDelete?ids=${ids}`).then(() => {
setPostsSelected([]);
fetchPosts();
});
};
useEffect(fetchPosts, []);
return (
<div>
<Header toggleModal={onNewPostClick} history={history} />
<div className={classes.postsContainer}>
{postsSelected.length !== 0 && (
<Fab
color="primary"
aria-label="delete"
className={classes.deleteIcon}
onClick={onBulkDelete}
>
<DeleteIcon />
</Fab>
)}
{posts.map((post) => (
<Post
key={post.id}
postDetails={post}
handleEdit={handleEdit}
showActions={true}
deletePost={deletePost}
handleCheckboxClick={handleCheckboxClick}
checked={postsSelected.includes(post.id)}
/>
))}
</div>
{isNewPostModalOpen && (
<PostModal
onClose={toggleModal}
initialPostDetails={postDetails}
onSubmit={onSubmit}
/>
)}
</div>
);
};
export default withStyles(styles)(Home);
<file_sep>/src/utils/helpers.js
import axios from "axios";
import { API_BASE_URL } from "../apiConfig";
import postData from "../data/posts";
export const getCall = (path) => {
// Commented as the API is down
// let URL = API_BASE_URL + path;
// return axios.get(URL);
if (path === "/") {
return Promise.resolve({ data: [...postData] });
}
const postId = Number(path.split("/")[1]);
return Promise.resolve({ data: postData[postId - 1] });
};
export const postCall = (path, data) => {
// Commented as the API is down
// let URL = API_BASE_URL + path;
// return axios.post(URL, data);
const newPost = {
...data,
id: postData[postData.length - 1].id + 1,
timestamp: new Date().toISOString(),
};
postData.push(newPost);
return Promise.resolve();
};
export const putCall = (path, data) => {
// Commented as the API is down
// let URL = API_BASE_URL + path;
// return axios.put(URL, data);
const id = path.split("/")[1];
const postToEdit = postData.find((post) => post.id === Number(id));
postToEdit.title = data.title;
postToEdit.text = data.text;
return Promise.resolve();
};
export const deleteCall = (path) => {
// Commented as the API is down
// let URL = API_BASE_URL + path;
// return axios.delete(URL);
if (path.includes("bulkDelete")) {
const ids = path.split("=")[1].split(",");
ids.forEach((id) => {
const postToDelete = postData.find((post) => post.id === Number(id));
const indexToDelete = postData.indexOf(postToDelete);
postData.splice(indexToDelete, 1);
});
return Promise.resolve();
} else {
const id = path.split("/")[1];
const postToDelete = postData.find((post) => post.id === Number(id));
const indexToDelete = postData.indexOf(postToDelete);
postData.splice(indexToDelete, 1);
return Promise.resolve();
}
};
<file_sep>/src/components/PostModal/styles.js
const styles = (theme) => ({
paper: {
// height: 400,
// width: 400,
background: "#FCFBFE",
padding: 40,
},
modal: {
display: "flex",
alignItems: "center",
justifyContent: "center",
fontFamily: ['"Mukta"', "sans-serif"],
},
textField: {
margin: "15px 0px",
width: "100%",
},
});
export default styles;
<file_sep>/src/App.js
import { createMuiTheme, MuiThemeProvider } from "@material-ui/core/styles";
import { BrowserRouter, Switch, Route } from "react-router-dom";
import "./App.css";
import Post from "./views/PostDetails";
import Home from "./views/Home";
const theme = createMuiTheme({
typography: {
fontFamily: ['"Noto Sans TC"', "sans-serif"],
useNextVariants: true,
fontWeight: "bold",
color: "#264052",
},
palette: {
primary: {
main: "#f86152",
},
},
textColor: "#264052",
secondaryText: "#cad1d6",
});
function App() {
return (
<MuiThemeProvider theme={theme}>
<div className="App">
<BrowserRouter>
<Route path="/" component={Home} exact />
<Route path="/post/:postId" component={Post} />
</BrowserRouter>
</div>
</MuiThemeProvider>
);
}
export default App;
<file_sep>/src/components/Header/PrimaryHeader/index.js
import {
AppBar,
Button,
Grid,
Typography,
withStyles,
} from "@material-ui/core";
import { Link } from "react-router-dom";
import React from "react";
import styles from "./styles";
const PrimaryHeader = ({ classes, toggleModal, history }) => (
<AppBar position="fixed" className={classes.primaryHeader}>
<Grid container>
<Grid xs={6}>
<Typography>
<Link to="/" className={classes.logo}>
MALANA
</Link>
</Typography>
</Grid>
<Grid xs={6} style={{ textAlign: "right" }}>
{history.location.pathname === "/" && (
<Button
variant="contained"
color="default"
className={classes.newPostButton}
onClick={toggleModal}
>
New Post
</Button>
)}
</Grid>
</Grid>
</AppBar>
);
export default withStyles(styles)(PrimaryHeader);
<file_sep>/src/apiConfig.js
export const API_BASE_URL = "https://salesforce-blogs.herokuapp.com/blogs/api";
<file_sep>/src/components/PostModal/index.js
import { Button, Card, Modal, TextField, withStyles } from "@material-ui/core";
import React, { useState } from "react";
import styles from "./styles";
const PostModal = ({ classes, onClose, initialPostDetails, onSubmit }) => {
const [title, setTitle] = useState(initialPostDetails.title);
const [description, setDescription] = useState(initialPostDetails.text);
return (
<Modal className={classes.modal} open={true} onClose={onClose}>
<form
onSubmit={(e) => {
e.preventDefault();
onSubmit(title, description);
}}
>
<Card className={classes.paper}>
<h3>What's on your mind?</h3>
<TextField
multiline
className={classes.textField}
placeholder="Title"
value={title}
onChange={(e) => setTitle(e.target.value)}
/>
<TextField
multiline
className={classes.textField}
placeholder="Description"
value={description}
onChange={(e) => setDescription(e.target.value)}
/>
<Button variant="contained" color="primary" type="submit">
Submit
</Button>
</Card>
</form>
</Modal>
);
};
export default withStyles(styles)(PostModal);
<file_sep>/src/views/Home/styles.js
const styles = (theme) => ({
postsContainer: {
paddingTop: 50,
},
deleteIcon: {
position: "fixed",
bottom: 20,
right: 20,
},
});
export default styles;
<file_sep>/src/views/PostDetails/styles.js
const styles = (theme) => ({
postContainer: {
width: "60%",
margin: "auto",
paddingTop: 100,
[theme.breakpoints.down("md")]: {
width: "70%",
},
[theme.breakpoints.down("sm")]: {
width: "80%",
},
[theme.breakpoints.down("xs")]: {
width: "90%",
},
},
});
export default styles;
|
fdb0ba83435b9d49ac647306ca51840258f4c96b
|
[
"JavaScript"
] | 10 |
JavaScript
|
mdabdulbari/posts
|
dafe48acf9f96c59e8a0dc1bba9afb38bd993d60
|
8a1806a9f798d21986f56bbb3f959b0bcea7a5c7
|
refs/heads/master
|
<file_sep>package grifts
import (
"encoding/csv"
"io"
"log"
"net/http"
"snow_watch/models"
"strconv"
"time"
"github.com/markbates/grift/grift"
)
var _ = grift.Namespace("reports", func() {
grift.Desc("seed", "Seeds a database")
grift.Add("seed", func(c *grift.Context) error {
stations := models.Stations{}
models.DB.All(&stations)
fUrl := "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/daily/"
eUrl := ":ID:SNTL%7Cid=%22%22%7Cname/-7,0/SNWD::value,SNWD::delta"
for _, s := range stations {
sId := strconv.Itoa(s.StationID)
url := fUrl + sId + eUrl
resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
records := readCsv(resp.Body)
if len(records) > 0 {
for _, r := range records[1:] {
dr := &models.DailyReport{}
date, err := time.Parse("2006-01-02", r[0])
if err != nil {
log.Fatalln(err)
}
dr.Date = date
dr.StationID = s.ID
depth, _ := strconv.ParseFloat(r[1], 64)
dr.SnowDepth = depth
change, _ := strconv.ParseFloat(r[2], 64)
dr.SnowChange = change
models.DB.Create(dr)
}
}
}
return nil
})
grift.Add("stations", func(c *grift.Context) error {
models.DB.TruncateAll()
url := "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customMultipleStationReport/daily/start_of_period/state=%22ID%22%20AND%20network=%22SNTLT%22,%22SNTL%22%20AND%20element=%22SNWD%22%20AND%20outServiceDate=%222100-01-01%22%7Cname/0,0/name,stationId,elevation,latitude,longitude,state.code?fitToScreen=false"
resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
records := readCsv(resp.Body)
for _, r := range records[1:] {
s := &models.Station{}
s.Name = r[0]
id, err := strconv.Atoi(r[1])
if err != nil {
log.Fatalln(err)
}
s.StationID = id
el, err := strconv.Atoi(r[2])
if err != nil {
log.Fatalln(err)
}
s.Elevation = el
la, err := strconv.ParseFloat(r[3], 64)
s.Lat = la
lo, err := strconv.ParseFloat(r[4], 64)
s.Long = lo
s.State = r[5]
models.DB.Save(s)
}
return nil
})
})
func readCsv(csv_file io.Reader) [][]string {
r := csv.NewReader(csv_file)
r.Comment = '#'
records, err := r.ReadAll()
if err != nil {
log.Fatalln(err)
}
return records
}
<file_sep>package actions
import (
"github.com/gobuffalo/buffalo/render"
"github.com/gobuffalo/packr/v2"
"snow_watch/models"
"time"
)
var r *render.Engine
var assetsBox = packr.New("app:assets", "../public")
func init() {
r = render.New(render.Options{
// HTML layout to be used for all HTML requests:
HTMLLayout: "application.plush.html",
// Box containing all of the templates:
TemplatesBox: packr.New("app:templates", "../templates"),
AssetsBox: assetsBox,
// Add template helpers here:
Helpers: render.Helpers{
// for non-bootstrap form helpers uncomment the lines
// below and import "github.com/gobuffalo/helpers/forms"
// forms.FormKey: forms.Form,
// forms.FormForKey: forms.FormFor,
"timeFix": timeFix,
"lastReport": lastReport,
"reverseOrder": reverseOrder,
},
})
}
func timeFix(d time.Time) string {
return d.Format("January 02, 2006")
}
func lastReport(reports []models.DailyReport) models.DailyReport {
if len(reports) > 0 {
return reports[len(reports)-1]
}
return models.DailyReport{}
}
func reverseOrder(a []models.DailyReport) []models.DailyReport {
for i := len(a)/2 - 1; i >= 0; i-- {
opp := len(a) - 1 - i
a[i], a[opp] = a[opp], a[i]
}
return a
}
<file_sep>--
-- PostgreSQL database dump
--
-- Dumped from database version 12.1
-- Dumped by pg_dump version 12.1
SET statement_timeout = 0;
SET lock_timeout = 0;
SET idle_in_transaction_session_timeout = 0;
SET client_encoding = 'UTF8';
SET standard_conforming_strings = on;
SELECT pg_catalog.set_config('search_path', '', false);
SET check_function_bodies = false;
SET xmloption = content;
SET client_min_messages = warning;
SET row_security = off;
SET default_tablespace = '';
SET default_table_access_method = heap;
--
-- Name: daily_reports; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.daily_reports (
id uuid NOT NULL,
date timestamp without time zone NOT NULL,
station_id uuid NOT NULL,
snow_depth numeric NOT NULL,
snow_change numeric NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE public.daily_reports OWNER TO postgres;
--
-- Name: schema_migration; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.schema_migration (
version character varying(14) NOT NULL
);
ALTER TABLE public.schema_migration OWNER TO postgres;
--
-- Name: stations; Type: TABLE; Schema: public; Owner: postgres
--
CREATE TABLE public.stations (
id uuid NOT NULL,
station_id integer NOT NULL,
name character varying(255) NOT NULL,
state character varying(255) NOT NULL,
elevation integer NOT NULL,
lat numeric NOT NULL,
long numeric NOT NULL,
created_at timestamp without time zone NOT NULL,
updated_at timestamp without time zone NOT NULL
);
ALTER TABLE public.stations OWNER TO postgres;
--
-- Name: daily_reports daily_reports_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.daily_reports
ADD CONSTRAINT daily_reports_pkey PRIMARY KEY (id);
--
-- Name: stations stations_pkey; Type: CONSTRAINT; Schema: public; Owner: postgres
--
ALTER TABLE ONLY public.stations
ADD CONSTRAINT stations_pkey PRIMARY KEY (id);
--
-- Name: schema_migration_version_idx; Type: INDEX; Schema: public; Owner: postgres
--
CREATE UNIQUE INDEX schema_migration_version_idx ON public.schema_migration USING btree (version);
--
-- PostgreSQL database dump complete
--
<file_sep>module snow_watch
go 1.13
require (
github.com/gobuffalo/buffalo v0.15.3
github.com/gobuffalo/buffalo-pop v1.23.1
github.com/gobuffalo/envy v1.8.1
github.com/gobuffalo/mw-csrf v0.0.0-20190129204204-25460a055517
github.com/gobuffalo/mw-forcessl v0.0.0-20180802152810-73921ae7a130
github.com/gobuffalo/mw-i18n v0.0.0-20190129204410-552713a3ebb4
github.com/gobuffalo/mw-paramlogger v0.0.0-20190129202837-395da1998525
github.com/gobuffalo/packr/v2 v2.7.1
github.com/gobuffalo/pop v4.13.0+incompatible
github.com/gobuffalo/suite v2.8.2+incompatible
github.com/gobuffalo/validate v2.0.3+incompatible
github.com/gofrs/uuid v3.2.0+incompatible
github.com/markbates/grift v1.5.0
github.com/stretchr/testify v1.4.0
github.com/unrolled/secure v0.0.0-20190103195806-76e6d4e9b90c
)
<file_sep>package actions
import (
"encoding/csv"
"fmt"
"io"
"log"
"net/http"
"snow_watch/models"
"strconv"
"sync"
"time"
"github.com/gobuffalo/buffalo"
"github.com/gobuffalo/pop"
)
// HomeHandler is a default handler to serve up
// a home page.
func HomeHandler(c buffalo.Context) error {
tx, ok := c.Value("tx").(*pop.Connection)
if !ok {
return fmt.Errorf("no transaction found")
}
report := models.DailyReport{}
models.DB.Order("Date Desc").First(&report)
if timeFix(report.Date) != timeFix(time.Now()) {
getDailyReport(tx)
}
stations := &models.Stations{}
// Paginate results. Params "page" and "per_page" control pagination.
// Default values are "page=1" and "per_page=20".
//q := tx.PaginateFromParams(c.Params())
// Retrieve all DailyReports from the DB
if err := tx.Eager().All(stations); err != nil {
return err
}
c.Set("stations", stations)
return c.Render(200, r.HTML("index.html"))
}
func getDailyReport(tx *pop.Connection) {
models.DB.RawQuery("TRUNCATE daily_reports").Exec()
stations := models.Stations{}
tx.All(&stations)
var wg sync.WaitGroup
for _, s := range stations {
wg.Add(1)
go stationReports(s, tx, &wg)
}
wg.Wait()
}
func stationReports(s models.Station, tx *pop.Connection, wg *sync.WaitGroup) {
fUrl := "https://wcc.sc.egov.usda.gov/reportGenerator/view_csv/customSingleStationReport/daily/"
eUrl := ":ID:SNTL%7Cid=%22%22%7Cname/-7,0/SNWD::value,SNWD::delta"
sId := strconv.Itoa(s.StationID)
url := fUrl + sId + eUrl
resp, err := http.Get(url)
if err != nil {
log.Fatalln(err)
}
records := readCsv(resp.Body)
if len(records) > 0 {
for _, r := range records[1:] {
saveRecords(s, r, tx)
}
}
wg.Done()
}
func saveRecords(s models.Station, r []string, tx *pop.Connection) {
dr := &models.DailyReport{}
date, err := time.Parse("2006-01-02", r[0])
if err != nil {
log.Fatalln(err)
}
dr.Date = date
dr.StationID = s.ID
depth, _ := strconv.ParseFloat(r[1], 64)
dr.SnowDepth = depth
change, _ := strconv.ParseFloat(r[2], 64)
dr.SnowChange = change
tx.Create(dr)
}
func readCsv(csv_file io.Reader) [][]string {
r := csv.NewReader(csv_file)
r.Comment = '#'
records, err := r.ReadAll()
if err != nil {
log.Fatalln(err)
}
return records
}
<file_sep>package models
import (
"encoding/json"
"time"
"github.com/gobuffalo/pop"
"github.com/gobuffalo/validate"
"github.com/gofrs/uuid"
)
// Station is used by pop to map your .model.Name.Proper.Pluralize.Underscore database table to your go code.
type Station struct {
ID uuid.UUID `json:"id" db:"id"`
StationID int `json:"station_id" db:"station_id"`
Name string `json:"name" db:"name"`
State string `json:"state" db:"state"`
Elevation int `json:"elevation" db:"elevation"`
Lat float64 `json:"lat" db:"lat"`
Long float64 `json:"long" db:"long"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
DailyReports []DailyReport `json:"daily_reports,omitempty" has_many:"daily_reports"`
}
// String is not required by pop and may be deleted
func (s Station) String() string {
js, _ := json.Marshal(s)
return string(js)
}
// Stations is not required by pop and may be deleted
type Stations []Station
// String is not required by pop and may be deleted
func (s Stations) String() string {
js, _ := json.Marshal(s)
return string(js)
}
// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method.
// This method is not required and may be deleted.
func (s *Station) Validate(tx *pop.Connection) (*validate.Errors, error) {
return validate.NewErrors(), nil
}
// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method.
// This method is not required and may be deleted.
func (s *Station) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) {
return validate.NewErrors(), nil
}
// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method.
// This method is not required and may be deleted.
func (s *Station) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
return validate.NewErrors(), nil
}
<file_sep>package models
import (
"encoding/json"
"time"
"github.com/gobuffalo/pop"
"github.com/gobuffalo/validate"
"github.com/gofrs/uuid"
)
// DailyReport is used by pop to map your .model.Name.Proper.Pluralize.Underscore database table to your go code.
type DailyReport struct {
ID uuid.UUID `json:"id" db:"id"`
Date time.Time `json:"date" db:"date"`
StationID uuid.UUID `json:"station_id" db:"station_id"`
SnowDepth float64 `json:"snow_depth" db:"snow_depth"`
SnowChange float64 `json:"snow_change" db:"snow_change"`
CreatedAt time.Time `json:"created_at" db:"created_at"`
UpdatedAt time.Time `json:"updated_at" db:"updated_at"`
Station *Station `json:"station,omitempty" belongs_to:"station"`
}
// String is not required by pop and may be deleted
func (d DailyReport) String() string {
jd, _ := json.Marshal(d)
return string(jd)
}
// DailyReports is not required by pop and may be deleted
type DailyReports []DailyReport
// String is not required by pop and may be deleted
func (d DailyReports) String() string {
jd, _ := json.Marshal(d)
return string(jd)
}
// Validate gets run every time you call a "pop.Validate*" (pop.ValidateAndSave, pop.ValidateAndCreate, pop.ValidateAndUpdate) method.
// This method is not required and may be deleted.
func (d *DailyReport) Validate(tx *pop.Connection) (*validate.Errors, error) {
return validate.Validate(), nil
}
// ValidateCreate gets run every time you call "pop.ValidateAndCreate" method.
// This method is not required and may be deleted.
func (d *DailyReport) ValidateCreate(tx *pop.Connection) (*validate.Errors, error) {
return validate.NewErrors(), nil
}
// ValidateUpdate gets run every time you call "pop.ValidateAndUpdate" method.
// This method is not required and may be deleted.
func (d *DailyReport) ValidateUpdate(tx *pop.Connection) (*validate.Errors, error) {
return validate.NewErrors(), nil
}
|
3e764d1a0fb9ba5aadf5c9d30c9e3f83c5b5da4a
|
[
"SQL",
"Go Module",
"Go"
] | 7 |
Go
|
jwoods1/snow_reporter
|
cf7eb231e9351038692649c1b65f9042e98213e1
|
a0104e0fc04593fc9091f89351665f11fc518dcf
|
refs/heads/master
|
<file_sep>import { expect } from 'chai';
import sinon from 'sinon';
import { mount } from '@vue/test-utils';
// import Vue from 'vue';
// import Vuex from 'vuex';
// import bButton from 'bootstrap-vue/es/components/button/button';
import store from '@/store';
import LoginForm from '@/components/LoginForm.vue';
// import account from '@/store/account';
describe('LoginForm.vue', function() {
describe('data()', function() {
it('sets the correct default data', function() {
expect(typeof LoginForm.data).to.equal('function');
const defaultData = LoginForm.data();
expect(defaultData.form).to.have.property('login', '');
expect(defaultData.form).to.have.property('password', '');
});
});
describe('onSubmit()', function() {
let stub;
beforeEach(function() {
stub = sinon.stub(store, 'dispatch');
});
afterEach(function() {
stub.restore();
});
it('triggers the account/authenticate() action when submit button is clicked', function() {
const wrapper = mount(LoginForm, { store });
const formWrapper = wrapper.find({ref: 'loginForm'});
formWrapper.trigger('submit');
expect(stub.calledOnce).to.equal(true);
expect(stub.calledWith('account/authenticate')).to.equal(true);
});
});
});
<file_sep>import { expect } from 'chai';
import { omit, cloneDeep } from 'lodash';
import {
REMOTE_REQUEST, SUBJECTS_SUCCESS, DATA_TYPES_SUCCESS,
DATA_TYPE_SUCCESS, REMOTE_ERROR
} from '@/store/mutation-types';
import records, { defaultDataType } from '@/store/records';
import dataTypes from '../fixtures/dataTypes/dataTypeList';
import subjects from '../fixtures/subjects/subjectList';
import dataType from '../fixtures/dataTypes/dataType';
import * as recordsApi from '@/api/records-api';
const testState = {
isPending: false,
dataTypes: [],
dataType: defaultDataType,
subjects: subjects,
samples: [],
data: [],
paginationInfo: {
currentPage: 0
},
error: null
};
const resHeaders = {
'x-current-page': '0',
'x-page-size': '30',
'x-total-count': '1604',
'x-total-pages': '54',
link: '<http://localhost:1337/subject?limit=30&skip=30>; rel=next, <http://localhost:1337/subject?limit=30&skip=1590>; rel=last'
};
const dtHeaders = {
'x-current-page': '0',
'x-page-size': '30',
'x-total-count': '45',
'x-total-pages': '2',
link: '<http://localhost:1337/dataType?limit=30&skip=30>; rel=next, <http://localhost:1337/dataType?limit=30&skip=30>; rel=last'
};
describe('records', function() {
describe('getters', function() {
describe('subjects', function() {
it('gets the \'subjects\' property of the state', function() {
expect(records.getters.subjects(testState)).to.eql(subjects);
});
});
describe('paginationInfo', function() {
it('gets the \'paginationInfo\' property of the state', function() {
expect(records.getters.paginationInfo(testState)).to.eql(testState.paginationInfo);
});
});
describe('dataType', function() {
it('gets the \'dataType\' property of the state', function() {
expect(records.getters.dataType(testState)).to.eql(defaultDataType);
});
});
});
describe('actions', function() {
let commit, getRecordStub, correctPayload, malformedPayload, state;
describe('getDataTypes', function() {
beforeEach(function() {
commit = sinon.stub();
getRecordStub = sinon.stub(recordsApi, 'getDataTypes');
malformedPayload = { '': 'this is malformed' };
getRecordStub.withArgs(correctPayload).returns({
data: dataTypes,
headers: dtHeaders
});
getRecordStub.withArgs(malformedPayload).throws();
state = cloneDeep(testState);
});
afterEach(function() {
getRecordStub.restore();
});
it('commits a REMOTE_REQUEST event', function(done) {
records.actions.getDataTypes({commit, state}, correctPayload)
.then(() => {
expect(commit.calledWithExactly(REMOTE_REQUEST)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('commits a DATA_TYPE_SUCCESS event with headers and dataTypes as properties of the second argument', function(done) {
records.actions.getDataTypes({commit, state}, correctPayload)
.then(() => {
const secondArg = {
dataTypes,
headers: dtHeaders
};
expect(commit.calledWithExactly(DATA_TYPES_SUCCESS, secondArg)).to.be.true;
done();
}).catch(done);
});
it('commits a REMOTE_ERROR event if an error is throw by recordsApi.getDataTypes()', function(done) {
records.actions.getDataTypes({commit, state}, malformedPayload)
.then(() => {
expect(commit.calledWith(REMOTE_ERROR)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
});
describe('getDataTypeForEdit', function() {
let getDataTypesStub, getSuperTypeMetaStub;
beforeEach(function() {
commit = sinon.stub();
correctPayload = { id: 7 };
malformedPayload = { id: 'this is malformed' };
getRecordStub = sinon.stub(recordsApi, 'getDataType');
getRecordStub.throws();
getRecordStub.withArgs(correctPayload).returns({
data: dataType
});
getRecordStub.withArgs(malformedPayload).throws();
getDataTypesStub = sinon.stub(recordsApi, 'getDataTypes').returns({
data: dataTypes
});
console.log(`SuperType ID is: ${JSON.stringify(dataType.superType.id)}`);
getSuperTypeMetaStub = sinon.stub(recordsApi, 'getSuperTypeMeta').returns({
data: {
isMultiProject: false
}
});
getSuperTypeMetaStub.withArgs(dataType.superType.id).returns({
data: {
isMultiProject: true
}
});
state = cloneDeep(testState);
});
afterEach(function() {
getRecordStub.restore();
getDataTypesStub.restore();
getSuperTypeMetaStub.restore();
});
it('correctly commits a DATA_TYPE_SUCCESS event with the expected payload', function(done) {
records.actions.getDataTypeForEdit({commit, state}, { id: 7 })
.then(res => {
const meta = { isMultiProject: true };
const args = [DATA_TYPE_SUCCESS, {
dataType,
dataTypes,
meta
}];
expect(commit.calledWithExactly(...args)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
});
describe('getSubjects', function() {
beforeEach(function() {
commit = sinon.stub();
getRecordStub = sinon.stub(recordsApi, 'getSubjects');
correctPayload = {};
malformedPayload = { '': 'this is malformed' };
getRecordStub.withArgs(correctPayload).returns({
data: subjects,
headers: resHeaders
});
getRecordStub.withArgs(malformedPayload).throws();
state = cloneDeep(testState);
});
afterEach(function() {
getRecordStub.restore();
});
it('commits a REMOTE_REQUEST event', function(done) {
records.actions.getSubjects({commit, state}, correctPayload)
.then(() => {
expect(commit.calledWithExactly(REMOTE_REQUEST)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('commits a SUBJECTS_SUCCESS event with headers and subjects as properties of the second argument', function(done) {
records.actions.getSubjects({commit, state}, correctPayload)
.then(() => {
const arg1 = {
subjects,
headers: resHeaders
};
expect(commit.calledWithExactly(SUBJECTS_SUCCESS, arg1)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('triggers a call of the api.getSubjects() method with correct \'payload\' argument', function(done) {
records.actions.getSubjects({commit, state}, correctPayload)
.then(() => {
expect(getRecordStub.calledWithExactly(correctPayload)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('commits a REMOTE_ERROR event if an error is throw by recordsApi.getSubjects()', function(done) {
records.actions.getSubjects({commit, state}, malformedPayload)
.then(() => {
expect(commit.calledWith(REMOTE_ERROR)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
});
});
describe('mutations', function() {
describe('REMOTE_REQUEST', function() {
it('sets the isPending property of the state to true', function() {
records.mutations[REMOTE_REQUEST](testState);
expect(testState.isPending).to.be.true;
});
});
describe('SUBJECTS_SUCCESS', function() {
it('sets isPending to false', function() {
records.mutations[SUBJECTS_SUCCESS](testState, {
subjects,
headers: resHeaders
});
expect(testState.isPending).to.be.false;
});
it('sets subjects to the value provided in the corrispondent payload property', function() {
records.mutations[SUBJECTS_SUCCESS](testState, {
subjects,
headers: resHeaders
});
expect(testState.subjects).to.eql(subjects);
});
it('sets the Pagination Info as read from the header', function() {
records.mutations[SUBJECTS_SUCCESS](testState, {
subjects,
headers: resHeaders
});
expect(testState.paginationInfo).to.have.property('currentPage', Number.parseInt(resHeaders['x-current-page']));
expect(testState.paginationInfo).to.have.property('pageSize', Number.parseInt(resHeaders['x-page-size']));
expect(testState.paginationInfo).to.have.property('totalItems', Number.parseInt(resHeaders['x-total-count']));
expect(testState.paginationInfo).to.have.property('totalPages', Number.parseInt(resHeaders['x-total-pages']));
console.log(testState.paginationInfo);
expect(testState.paginationInfo).to.have.nested.property('links.next', 'http://localhost:1337/subject?limit=30&skip=30');
expect(testState.paginationInfo).to.have.nested.property('links.last', 'http://localhost:1337/subject?limit=30&skip=1590');
});
});
describe('DATA_TYPE_SUCCESS', function() {
beforeEach(function() {
const meta = { isMultiProject: true };
records.mutations[DATA_TYPE_SUCCESS](testState, {
dataType,
dataTypes,
meta
});
});
it('sets isPending to false', function() {
expect(testState.isPending).to.be.false;
});
it('sets isMultiProject to false within dataType.superType', function() {
expect(testState).to.have.nested.property('dataType.superType.isMultiProject', true);
});
it('sets dataType and dataTypes correctly', function() {
expect(testState).to.have.property('dataTypes', dataTypes);
expect(omit(testState.dataType, 'superType')).to.eql(omit(dataType, 'superType'));
expect(omit(testState.dataType.superType, 'isMultiProject')).to.eql(dataType.superType);
});
});
describe('REMOTE_ERROR', function() {
it('sets the isPending property of the state to false and sets the errorResponse', function() {
const errorResponse = {
message: 'This is a bl00dy error'
};
records.mutations[REMOTE_ERROR](testState, errorResponse);
expect(testState.error).to.eql(errorResponse);
});
});
});
});
<file_sep>// import { find } from 'lodash';
import {
REMOTE_REQUEST, SUBJECTS_SUCCESS, REMOTE_ERROR, DATA_TYPES_SUCCESS,
DATA_TYPE_SUCCESS
} from '@/store/mutation-types';
import * as api from '@/api/records-api';
import { parseLinkHeader } from '@/utils/funcs';
export const defaultDataType = {
superType: {
schema: {
header: {
// fileUpload: false
},
body: []
}
}
};
const state = {
isPending: false,
dataTypes: [],
dataType: defaultDataType,
subjects: [],
samples: [],
data: [],
currentDataTypeId: 0,
isMultiProject: false,
paginationInfo: {
currentPage: 0
},
error: null
};
const getters = {
// lists
dataTypes: state => state.dataTypes,
subjects: state => state.subjects,
// single instances/records
dataType: state => state.dataType,
paginationInfo: state => state.paginationInfo
};
const actions = {
async getDataTypes({commit, state}, payload) {
commit(REMOTE_REQUEST);
try {
const res = await api.getDataTypes(payload);
commit(DATA_TYPES_SUCCESS, {
dataTypes: res.data,
headers: res.headers
});
} catch (err) {
const { response } = err;
commit(REMOTE_ERROR, response);
}
},
async getSubjects({commit, state}, payload) {
commit(REMOTE_REQUEST);
try {
const res = await api.getSubjects(payload);
commit(SUBJECTS_SUCCESS, {
subjects: res.data,
headers: res.headers
});
} catch (err) {
const { response } = err;
commit(REMOTE_ERROR, response);
}
},
async getDataTypeForEdit({commit, state}, payload) {
try {
commit(REMOTE_REQUEST);
const dataTypeRes = await api.getDataType({id: payload.id});
const dataType = dataTypeRes.data;
const dataTypesRes = await api.getDataTypes();
const metaRes = await api.getSuperTypeMeta(dataType.superType.id);
const commitParams = {
dataType,
dataTypes: dataTypesRes.data,
meta: metaRes.data
};
commit(DATA_TYPE_SUCCESS, commitParams);
return 'success';
} catch (err) {
const { response } = err;
commit(REMOTE_ERROR, response);
return 'failure';
}
}
};
const mutations = {
[REMOTE_REQUEST](state) {
state.isPending = true;
},
[DATA_TYPES_SUCCESS](state, {dataTypes = [], headers = {}}) {
state.isPending = false;
state.dataTypes = dataTypes;
state.paginationInfo = {
currentPage: Number.parseInt(headers['x-current-page']),
pageSize: Number.parseInt(headers['x-page-size']),
totalItems: Number.parseInt(headers['x-total-count']),
totalPages: Number.parseInt(headers['x-total-pages']),
links: parseLinkHeader(headers['link'])
};
},
[SUBJECTS_SUCCESS](state, {subjects = [], headers = {}}) {
// console.log(headers);
state.isPending = false;
state.subjects = subjects;
state.paginationInfo = {
currentPage: Number.parseInt(headers['x-current-page']),
pageSize: Number.parseInt(headers['x-page-size']),
totalItems: Number.parseInt(headers['x-total-count']),
totalPages: Number.parseInt(headers['x-total-pages']),
links: parseLinkHeader(headers['link'])
};
},
[DATA_TYPE_SUCCESS](state, {
dataType = defaultDataType,
dataTypes = [],
meta: {
isMultiProject = false
} = {}
}) {
state.isPending = false;
state.dataType = {
...dataType,
superType: {
...dataType.superType,
isMultiProject
}
};
state.dataTypes = dataTypes;
state.paginationInfo = {};
},
[REMOTE_ERROR](state, errorResponse) {
state.isPending = false;
state.error = errorResponse;
}
};
export default {
namespaced: true,
state,
getters,
actions,
mutations
};
<file_sep>import axios from 'axios';
import { DEFAULT_SORTING_CRITERION } from '@/utils/constants';
export async function getProjects() {
const response = await axios.get('/api/project', {
params: {
// sort: 'id ASC',
sort: DEFAULT_SORTING_CRITERION,
populate: 'groups'
}
});
return response;
}
<file_sep>import { expect } from 'chai';
import superUser from '../fixtures/users/superUser.json';
import projects from '../fixtures/projects/projectList.json';
import { ALL_PROJECTS } from '@/utils/constants';
import {
LOGIN_REQUEST, LOGIN_SUCCESS, GET_PROJECTS_SUCCESS, LOGIN_ERROR, RESET, CHANGE_ACTIVE_PROJECT
} from '@/store/mutation-types';
import account, { initialState } from '@/store/account';
import * as authApi from '@/api/auth-api';
import * as projApi from '@/api/project-api';
// const projects = [];
describe('account', function() {
const testCorrectCredentials = {
identifier: 'Geeno',
password: '<PASSWORD>'
};
const testWrongCredentials = {
identifier: 'Geeno',
password: '<PASSWORD>'
};
const testToken = <PASSWORD>';
const loginApiResponse = {
data: {
user: superUser,
token: testToken
}
};
const testError = {};
describe('getters', function() {
describe('userInfo', function() {
it('returns the user and token as properties object', function() {
const state = {
user: superUser,
token: '<PASSWORD>'
};
expect(account.getters.userInfo(state)).to.eql(state);
});
});
describe('isAuthenticated', function() {
it('returns true if user is not null', function() {
const state = {
user: superUser
};
expect(account.getters.isAuthenticated(state)).to.be.true;
});
it('returns false if user is null', function() {
const state = {
user: null
};
expect(account.getters.isAuthenticated(state)).to.be.false;
});
});
describe('hasToken', function() {
it('returns true if the token is not null', function() {
const state = {
user: superUser,
token: testToken
};
expect(account.getters.hasToken(state)).to.be.true;
});
it('returns false if token is null', function() {
const state = {
user: superUser,
token: null
};
expect(account.getters.hasToken(state)).to.be.false;
});
});
describe('error', function() {
it('returns the error property', function() {
const state = {
user: superUser,
token: testToken,
error: testError
};
expect(account.getters.error(state)).to.eql(testError);
});
});
describe('isWheel', function() {
it('returns false if user is empty', function() {
const state = {
user: {},
token: null
};
expect(account.getters.isWheel(state)).to.be.false;
});
it('returns true if user is superuser', function() {
const state = {
user: superUser,
token: null
};
expect(account.getters.isWheel(state)).to.be.true;
});
});
describe('isAdmin', function() {
it('returns false if user is empty', function() {
const state = {
user: {},
token: null
};
expect(account.getters.isAdmin(state)).to.be.false;
});
it('returns true if user is superuser', function() {
const state = {
user: superUser,
token: null
};
expect(account.getters.isAdmin(state)).to.be.true;
});
});
describe('adminProjects', function() {
it('returns an empty array if user is empty', function() {
const state = {
user: {},
token: null
};
expect(account.getters.adminProjects(state)).to.eql([]);
});
it('returns the list of projects IDs of the SuperAdmin group', function() {
const state = {
user: superUser,
token: null
};
expect(account.getters.adminProjects(state)).to.eql(superUser.groups[0].projects.map(proj => proj.id));
});
});
describe('canAccessPersonalData', function() {
it('returns false if user is empty', function() {
const state = {
user: {},
token: null
};
expect(account.getters.canAccessPersonalData(state)).to.be.false;
});
it('returns true if user is superuser', function() {
const state = {
user: superUser,
token: null
};
expect(account.getters.canAccessPersonalData(state)).to.be.true;
});
});
describe('canAccessSensitiveData', function() {
it('returns false if user is empty', function() {
const state = {
user: {},
token: null
};
expect(account.getters.canAccessSensitiveData(state)).to.be.false;
});
it('returns true if user is superuser', function() {
const state = {
user: superUser,
token: null
};
expect(account.getters.canAccessSensitiveData(state)).to.be.true;
});
});
describe('projects', function() {
it('returns the projects property of the state', function() {
const state = {
user: {},
token: null,
projects: [],
activeProject: {}
};
expect(account.getters.projects(state)).to.eql(state.projects);
});
});
describe('activeProject', function() {
it('returns the activeProject property of the state', function() {
const state = {
user: {},
token: null,
projects: [],
activeProject: {}
};
expect(account.getters.activeProject(state)).to.eql(state.activeProject);
});
});
});
describe('mutations', function() {
describe('LOGIN_REQUEST', function() {
it('sets the isPending property of the state to true', function() {
const state = {};
account.mutations[LOGIN_REQUEST](state);
expect(state.isPending).to.be.true;
});
});
describe('LOGIN_SUCCESS', function() {
it('sets the user and token property of the state', function() {
const state = {};
account.mutations[LOGIN_SUCCESS](state, {
user: superUser,
token: testToken
});
expect(state.user).to.eql(superUser);
expect(state.token).to.equal(testToken);
});
it('sets the error to null and isPending to false', function() {
const state = {};
account.mutations[LOGIN_SUCCESS](state, {
user: superUser,
token: testToken
});
expect(state.error).to.be.null;
expect(state.isPending).to.be.false;
});
});
describe('GET_PROJECTS_SUCCESS', function() {
it('writes into the state the projects object and sets isPending to false', function() {
const state = {
user: superUser,
token: testToken,
isPending: true,
error: null
};
account.mutations[GET_PROJECTS_SUCCESS](state, projects);
expect(state.isPending).to.be.false;
expect(state.projects).to.eql(projects);
});
});
describe('LOGIN_ERROR', function() {
it('writes the error object and sets isPending to false', function() {
const state = {
user: superUser,
token: testToken,
isPending: true,
error: null
};
const ERROR_STATUS = 500;
account.mutations[LOGIN_ERROR](state, {
status: ERROR_STATUS
});
expect(state.user).to.be.null;
expect(state.token).to.be.null;
expect(state.error).to.eql({
status: ERROR_STATUS
});
expect(state.isPending).to.be.false;
});
});
describe('RESET', function() {
it('resets the state to the initial value', function() {
const state = {
...initialState,
user: superUser,
token: testToken
};
account.mutations[RESET](state);
console.log(state);
expect(state).to.eql(initialState);
});
});
describe('CHANGE_ACTIVE_PROJECT', function() {
it('changes the project to the correct one', function() {
const newProject = projects[0].name;
const state = {
...initialState,
projects,
user: superUser,
token: testToken
};
account.mutations[CHANGE_ACTIVE_PROJECT](state, newProject);
expect(state.activeProject).to.equal(newProject);
});
it('changes the project to ALL_PROJECTS', function() {
const state = {
...initialState,
projects,
activeProject: projects[0].name
};
account.mutations[CHANGE_ACTIVE_PROJECT](state, ALL_PROJECTS);
expect(state.activeProject).to.equal(ALL_PROJECTS);
});
});
});
describe('actions', function() {
describe('authenticate()', function() {
let commit, logInFnc, getProjectsFnc, payload, state;
beforeEach(function() {
commit = sinon.stub();
logInFnc = sinon.stub(authApi, 'logIn');
getProjectsFnc = sinon.stub(projApi, 'getProjects').returns({
data: projects
});
logInFnc.withArgs(testCorrectCredentials).returns(loginApiResponse);
logInFnc.withArgs(testWrongCredentials).throws();
payload = {};
state = {};
});
afterEach(function() {
logInFnc.restore();
getProjectsFnc.restore();
});
it('commits a LOGIN_REQUEST mutation', function(done) {
account.actions.authenticate({
commit,
state
}, payload).then(() => {
expect(commit.calledWithExactly(LOGIN_REQUEST)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('commits a LOGIN_SUCCESS mutation', function(done) {
account.actions.authenticate({
commit,
state
}, testCorrectCredentials).then(() => {
expect(commit.calledWithExactly(LOGIN_SUCCESS, loginApiResponse.data)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('commits a GET_PROJECTS_SUCCESS event', function(done) {
account.actions.authenticate({
commit,
state
}, testCorrectCredentials).then(() => {
expect(commit.calledWithExactly(GET_PROJECTS_SUCCESS, projects)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
it('commits a LOGIN_ERROR mutation if an error occurs on auth', function(done) {
account.actions.authenticate({
commit,
state
}, testWrongCredentials).then(() => {
expect(commit.calledWith(LOGIN_ERROR)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
});
describe('storeUserInfo()', function() {
let commit, state, userInfo, getProjectsFnc;
beforeEach(function() {
commit = sinon.stub();
getProjectsFnc = sinon.stub(projApi, 'getProjects').returns({
data: projects
});
userInfo = {
user: {},
token: 'bäø'
};
state = {};
});
afterEach(function() {
getProjectsFnc.restore();
});
it('commits a LOGIN_SUCCESS mutation', function() {
account.actions.storeUserInfo({
commit,
state
}, userInfo);
expect(commit.calledWithExactly(LOGIN_SUCCESS, userInfo)).to.be.true;
});
it('commits a GET_PROJECTS_SUCCESS event', function(done) {
account.actions.storeUserInfo({
commit,
state
}, userInfo).then(() => {
expect(getProjectsFnc.calledOnce).to.be.true;
expect(commit.calledWithExactly(GET_PROJECTS_SUCCESS, projects)).to.be.true;
done();
}).catch(err => {
done(err);
});
});
});
describe('logout()', function() {
let commit, state;
beforeEach(function() {
commit = sinon.stub();
state = {};
});
it('commits a RESET mutation', function() {
account.actions.signOut({
commit,
state
});
expect(commit.calledWithExactly(RESET)).to.be.true;
});
});
describe('changeActiveProject()', function() {
let commit, state;
beforeEach(function() {
commit = sinon.stub();
state = {};
});
it('commits a CHANGE_ACTIVE_PROJECT mutation', function() {
const newProject = 'New Project';
account.actions.changeActiveProject({
commit,
state
}, newProject);
expect(commit.calledWithExactly(CHANGE_ACTIVE_PROJECT, newProject)).to.be.true;
});
});
});
});
<file_sep>// PRIVILEGE LEVELS
export const WHEEL = 'wheel';
export const ADMIN = 'admin';
export const STANDARD = 'standard';
export const ALL_PROJECTS = 'all';
export const DEFAULT_LIMIT = 10;
export const DEFAULT_SORTING_CRITERION = 'created_at DESC';
export const DATA_TYPE_MODELS = [ 'Data', 'Sample', 'Subject' ];
<file_sep>import axios from 'axios';
import { DEFAULT_LIMIT, DEFAULT_SORTING_CRITERION } from '@/utils/constants';
/**
* @method
* @name getSubjects
* @param{Object/Integer} payload.activeProject - the id of the current active project or the project object
* @param{Integer} payload.limit - integer
* @param{Integer} payload.skip - integer
* @param{String} payload.sort - must be a meaningful sorting criterion for the underlying database
*/
export async function getSubjects({
activeProject,
limit = DEFAULT_LIMIT,
skip = 0,
sort = DEFAULT_SORTING_CRITERION
} = {}) {
const response = await axios.get('/api/subject', {
params: {
project: activeProject ? activeProject.id : undefined,
populate: 'type',
limit,
skip,
sort
}
});
return response;
}
/**
* @method
* @name getDataTypes
* @param{Object/Integer} payload.activeProject
* @param{Integer} payload.limit - integer
* @param{Integer} payload.skip - integer
* @param{String} payload.sort - must be a meaningful sorting criterion for the underlying database
*/
export async function getDataTypes({
activeProject,
limit = undefined,
skip = 0,
sort = DEFAULT_SORTING_CRITERION
} = {}) {
const response = await axios.get('/api/dataType', {
params: {
project: activeProject ? activeProject.id : undefined,
populate: ['parents', 'project'],
limit,
skip,
sort
}
});
return response;
}
/**
* @method
* @name getDataType
* @param{Integer} id - the id/primary key of the dataType
*/
export async function getDataType({
id,
populate = ['parents', 'project', 'superType']
}) {
const response = await axios.get(`/api/dataType/${id}`, {
params: {
populate
}
});
return response;
}
/**
* @method
* @name getSuperTypeMeta
* @param{Integer} id - the id/primary key of the superType
*/
export async function getSuperTypeMeta(id) {
const response = await axios.get(`/api/superType/meta/${id}`);
return response;
}
<file_sep>const credentials = require('../secrets').testUserCredentials;
module.exports = {
'login test with page refresh': function(browser) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/login`).waitForElementVisible('#app', 500);
browser.expect.element('h1').text.to.equal('Account Login:');
browser.expect.element('#login').to.be.present;
browser.expect.element('#password').to.be.present;
browser.setValue('#login', credentials.login);
browser.setValue('#password', <PASSWORD>);
browser.submitForm('form');
browser.waitForElementNotPresent('#login', 5000).waitForElementVisible('#main', 10000);
browser.assert.urlEquals(`${devServer}/subjects`);
browser.refresh();
browser.waitForElementVisible('#main', 10000);
// after refresh we should still be logged in
browser.assert.urlEquals(`${devServer}/subjects`);
browser.expect.element('#navbarUsername').text.to.equal(credentials.login);
browser.end();
},
'login and logout': function(browser) {
const devServer = browser.globals.devServerURL;
browser.url(`${devServer}/login`).waitForElementVisible('#app', 500);
browser.setValue('#login', credentials.login);
browser.setValue('#password', <PASSWORD>);
browser.submitForm('form');
browser.waitForElementNotPresent('#login', 5000).waitForElementVisible('#navbarUsername', 10000);
browser.assert.urlEquals(`${devServer}/subjects`);
browser.click('#navbarUsername').waitForElementVisible('#navbarSignOut', 5000);
browser.click('#navbarSignOut').waitForElementNotPresent('#main', 5000);
browser.assert.urlEquals(`${devServer}/login`);
browser.end();
}
};
<file_sep>import axios from 'axios';
export async function logIn(credentials) {
const { login, password } = credentials;
const response = await axios.post('/api/login', {
identifier: login,
password: <PASSWORD>
});
return response;
}
<file_sep>import { expect } from 'chai';
import sinon from 'sinon';
import { shallowMount, mount } from '@vue/test-utils';
import store from '@/store';
import ProjectSelector from '@/components/subcomponents/ProjectSelector';
import projects from '../../fixtures/projects/projectList';
describe('ProjectSelector.vue', function() {
describe('overall behaviour', function() {
let wrapper;
beforeEach(function() {
// dstub = sinon.stub(store, 'dispatch');
wrapper = mount(ProjectSelector, {
propsData: {
projects
}// ,
// store
});
});
// afterEach(function() {
// dstub.restore();
// });
it('does not contain the project selector if the checkbox is not ticked', function() {
expect(wrapper.contains('#activeProjectSelect')).to.be.false;
});
it.only('contains the project selector if the checkbox is ticked', function() {
console.log(wrapper.html());
wrapper.setData({ changeEnabled: true });
wrapper.vm.$forceUpdate(); // it does not seem to update automatically
// const checkboxRef = wrapper.find({ ref: 'changeEnabledCheckbox' });
// checkboxRef.trigger('click');
console.log(wrapper.html());
expect(wrapper.contains('#activeProjectSelect')).to.be.true;
});
});
describe('methods', function() {
describe('activeProjectOnChange()', function() {
let wrapper, dstub;
beforeEach(function() {
dstub = sinon.stub(store, 'dispatch');
wrapper = shallowMount(ProjectSelector, {
propsData: {
projects
},
store
});
});
afterEach(function() {
dstub.restore();
});
it('dispatches the changeActiveProject action', function() {
const nextProject = wrapper.vm.$props.projects[0].name;
wrapper.setData({
selectedProject: nextProject
});
wrapper.vm.changeActiveProject();
expect(dstub.calledWithExactly('account/changeActiveProject', nextProject)).to.be.true;
});
it('closes the modal', function() {
const spy = sinon.spy(wrapper.vm.$root, '$emit');
wrapper.vm.changeActiveProject();
expect(spy.calledWithExactly('bv::hide::modal', 'activeProjectSelectorModal'));
});
/*
it('dispatches the changeActiveProject action', function() {
// TODO
wrapper.find({ref: 'changeEnabledCheckbox'}).trigger('click');
expect(wrapper.contains('#activeProjectSelect')).to.be.true;
const selectWrapper = wrapper.find('#activeProjectSelect');
selectWrapper.vm.value = selectWrapper.vm.options[0].value;
selectWrapper.trigger('change');
expect(dstub.calledOnce).to.be.true;
expect(dstub.calledWith('account/changeActiveProject'));
}); */
});
describe('openModal()', function() {
it('opens the modal', function() {
const wrapper = shallowMount(ProjectSelector, {
propsData: {
projects
}
});
const spy = sinon.spy(wrapper.vm.$root, '$emit');
wrapper.vm.openModal();
expect(spy.calledWithExactly('bv::show::modal', 'activeProjectSelectorModal'));
});
});
});
});
<file_sep>import { expect } from 'chai';
import sinon from 'sinon';
import { mount, createLocalVue } from '@vue/test-utils';
import BootstrapVue from 'bootstrap-vue';
import Vuex from 'vuex';
import store from '@/store';
import router from '@/router';
import AppNavbar from '@/components/subcomponents/AppNavbar';
const appNavbarProps = {
login: 'Pippo',
userId: 1,
isAuthenticated: true
};
describe('AppNavbar.vue', function() {
let localVue, dstub, pstub;
beforeEach(function() {
localVue = createLocalVue();
localVue.use(Vuex);
localVue.use(BootstrapVue);
dstub = sinon.stub(store, 'dispatch');
pstub = sinon.stub(router, 'push');
});
afterEach(function() {
dstub.restore();
pstub.restore();
});
it('renders the user name in the appropriate <em> tag', function() {
const wrapper = mount(AppNavbar, {
// localVue,
propsData: appNavbarProps
});
// const htmlString = wrapper.html();
expect(wrapper.find('#navbarUsername').text()).to.equal(appNavbarProps.login);
});
it('renders the user profile dropdown if client not authenticated', function() {
const wrapper = mount(AppNavbar, {
// localVue,
propsData: appNavbarProps
});
expect(wrapper.find('#navbarUserProfileDropdown').exists()).to.be.true;
});
it('does not render the user profile dropdown if client not authenticated', function() {
const wrapper = mount(AppNavbar, {
// localVue
});
expect(wrapper.find('#navbarUserProfileDropdown').exists()).to.be.false;
});
describe('methods', function() {
describe('signOut', function() {
let wrapper;
beforeEach(function() {
wrapper = mount(AppNavbar, {
// localVue,
propsData: appNavbarProps,
store,
router
});
});
it('dispatches an account/signOut event', function() {
wrapper.find('#navbarSignOut').trigger('click');
expect(dstub.calledOnce).to.be.true;
expect(dstub.calledWithExactly('account/signOut')).to.equal(true);
});
it('redirects the client to the /login address', function() {
wrapper.find('#navbarSignOut').trigger('click');
expect(pstub.calledOnce).to.be.true;
expect(pstub.calledWithExactly('login')).to.equal(true);
});
});
});
});
|
e30531393ac4fe23293cd60552908dbda0a19905
|
[
"JavaScript"
] | 11 |
JavaScript
|
xtens-suite/xtens-client
|
67e08fd54368c964368ec80c990fe6a5e5455234
|
08999e4e363248ee02a997ac2e7baeb75cdbe19a
|
refs/heads/master
|
<file_sep>// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
namespace NLU.DevOps.ModelPerformance
{
using System.Collections.Generic;
using Models;
/// <summary>
/// Labeled utterance with confidence score.
/// </summary>
public class CompareLabeledUtterance : LabeledUtterance
{
/// <summary>
/// Initializes a new instance of the <see cref="CompareLabeledUtterance"/> class.
/// </summary>
/// <param name="utteranceId">Utterance ID.</param>
/// <param name="text">Text of the utterance.</param>
/// <param name="intent">Intent of the utterance.</param>
/// <param name="entities">Entities referenced in the utterance.</param>
public CompareLabeledUtterance(string utteranceId, string text, string intent, IReadOnlyList<Entity> entities)
: base(text, intent, entities)
{
this.UtteranceId = utteranceId;
}
/// <summary>
/// Gets the utterance ID.
/// </summary>
public string UtteranceId { get; }
}
}
|
a602833c71c7341cbe4c5a9a847395985f6b52a6
|
[
"C#"
] | 1 |
C#
|
ponarunkumar/NLU.DevOps
|
55921b937b3bc6b71313057304bb740a918fbab3
|
6f4f30694ffd9e46ceb4cd812ac6936e583848dd
|
refs/heads/master
|
<file_sep>#Mon Nov 30 17:08:40 EST 2015
org.eclipse.core.runtime=2
org.eclipse.platform=4.4.0.v20140925-0400
<file_sep>/*
* IMUData.h
*
* Created on: Sep 23, 2015
* Author: suyashkumar
*/
#ifndef IMUDATA_H_
#define IMUDATA_H_
class IMUData {
public:
IMUData();
virtual ~IMUData();
};
#endif /* IMUDATA_H_ */
<file_sep>////////////////////////////////////////////////////////////////////////////
//
// This file is part of RTIMULib
//
// Copyright (c) 2014-2015, richards-tech, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
// Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#include "RTIMULib/RTIMULib.h"
#include "stdio.h"
#include "mraa.h"
#include "mraa.hpp"
#include <unistd.h>
#include <iostream>
#include <exception>
int main()
{
int sampleCount = 0;
int sampleRate = 0;
uint64_t rateTimer;
uint64_t displayTimer;
uint64_t now;
// Set up PWM
mraa::Pwm* pwm;
pwm = new mraa::Pwm(0);
if (pwm == NULL) {
return MRAA_ERROR_UNSPECIFIED;
}
if (pwm->enable(true) != MRAA_SUCCESS) {
std::cerr << "Cannot enable PWM on mraa::PWM object, exiting" << std::endl;
return MRAA_ERROR_UNSPECIFIED;
}
float duty_cycle=0.0;
// Using RTIMULib here allows it to use the .ini file generated by RTIMULibDemo.
// Or, you can create the .ini in some other directory by using:
// RTIMUSettings *settings = new RTIMUSettings("<directory path>", "RTIMULib");
// where <directory path> is the path to where the .ini file is to be loaded/saved
RTIMUSettings *settings = new RTIMUSettings("RTIMULib");
RTIMU *imu = RTIMU::createIMU(settings);
if ((imu == NULL) || (imu->IMUType() == RTIMU_TYPE_NULL)) {
printf("No IMU found\n");
exit(1);
}
// This is an opportunity to manually override any settings before the call IMUInit
// set up IMU
imu->IMUInit();
// this is a convenient place to change fusion parameters
imu->setSlerpPower(0.02);
imu->setGyroEnable(true);
imu->setAccelEnable(true);
imu->setCompassEnable(true);
// Set up serial out UART ports
mraa_uart_context uart;
//uart = mraa_uart_init(0);
uart=mraa_uart_init_raw("/dev/ttyGS0");
mraa_uart_set_baudrate(uart, 9600);
if (uart == NULL) {
fprintf(stderr, "UART failed to setup\n");
return 0;
}
char buffer[20]={}; // To hold output
while (1) {
while (imu->IMURead()) {
RTIMU_DATA imuData = imu->getIMUData();
//sleep(1);
printf("%s\r", RTMath::displayDegrees("Gyro", imuData.fusionPose) );
//printf("\nx %f ",imuData.gyro.x()*(180.0/3.14));
//printf("\ny %f ",imuData.gyro.y()*(180.0/3.14));
//printf("\nz %f\n",imuData.gyro.z()*(180.0/3.14));
float current_reading=imuData.fusionPose.x()*(180.0/3.14);
sprintf(buffer,"%4f\n",imuData.fusionPose.x()*(180.0/3.14));
//mraa_uart_write(uart, buffer, sizeof(buffer));
duty_cycle=current_reading/90;
pwm->config_percent(1,duty_cycle); // Write 50% duty cycle period of 1ms
printf("\n\n");
//imuData.
fflush(stdout);
//displayTimer = now;
}
}
mraa_uart_stop(uart);
mraa_deinit();
}
<file_sep># BME464_Tremor
<file_sep>#include <iostream>
#include <string.h>
#include <time.h>
#include <mraa.hpp>
int main() {
mraa::Pwm* pwm;
pwm = new mraa::Pwm(0);
clock_t t;
if (pwm == NULL) {
return MRAA_ERROR_UNSPECIFIED;
}
if (pwm->enable(true) != MRAA_SUCCESS) {
std::cerr << "Cannot enable PWM on mraa::PWM object, exiting" << std::endl;
return MRAA_ERROR_UNSPECIFIED;
}
char buffer[20];
float duty_cycle=0.5;
for (;;) {
pwm->config_percent(20,(0.8*0.05)+0.05);
usleep(50000);
pwm->config_percent(20,0.05+0.05);
//pwm->period_us(500);
usleep(50000);
}
delete pwm;
return 0;
}
<file_sep>#include "RTIMULib/RTIMULib.h"
#include "stdio.h"
#include "mraa.h"
#include "mraa.hpp"
#include <unistd.h>
#include <iostream>
#include <exception>
#include <fstream>
#include <ctime>
#include <string>
#include <queue>
#include <sys/time.h>
// Forward function declarations:
mraa::Pwm* initPwm(int pin);
RTIMU* initImu();
float calculateDutyCycle(float deflection);
void motorControl(RTIMU_DATA imuData, mraa::Pwm* pwm);
void writeToCSV(float current_reading);
long long current_timestamp();
float runningDeflectionAverage(float sample);
float limit(float current_reading);
long long oldTime; // last time stamp recorded in file.
long long firstTime;
float saveSamplePeriod=1; // in ms
char buffer[20]={}; // for logging
long long counter=0; // Current number of sample
char saveName[50]={};
std::clock_t a = std::clock();
float currentAverage=0;
std::queue <float> prevSamples;
int samplesSeen=1;
int runningAvgSamples=50;
int main()
{
// Parameter declaration, initiation:
int sampleCount = 0;
int sampleRate = 0;
long long currentTime=current_timestamp();
sprintf(saveName,"static/data/%lld.csv",currentTime); // CSV file name
prevSamples.push(0.0);
mraa::Pwm* pwm = initPwm(0); // Initialize PWM Object
RTIMU *imu = initImu(); // Initialize IMU Object
//printf("How many avg samples? ");
//std::cin >> runningAvgSamples;
oldTime=current_timestamp(); // Set first time stamp for csv recording
firstTime=oldTime;
// Main loop:
while (1) {
while (imu->IMURead()) {
RTIMU_DATA imuData = imu->getIMUData();
motorControl(imuData,pwm); // Update motor position
}
}
mraa_deinit();
}
/*
* initPwm()
* Initiates a PWM object on the supplied pin.
* @param pin an integer representing the pin to initiate PWM on.
* @returns pwm a mraa::Pwm* pointer
*/
mraa::Pwm* initPwm(int pin){
mraa::Pwm* pwm;
pwm=new mraa::Pwm(pin);
if (pwm == NULL) { // Look for null case
//return MRAA_ERROR_UNSPECIFIED;
std::cerr << "PWM object was returned as null...exiting" << std::endl;
exit(1);
}
if (pwm->enable(true) != MRAA_SUCCESS) { // enable and check status of enable
std::cerr << "Cannot enable PWM on mraa::PWM object, exiting" << std::endl;
//return MRAA_ERROR_UNSPECIFIED;
exit(1);
}
return pwm;
}
/*
*
*/
RTIMU* initImu(){
RTIMUSettings *settings = new RTIMUSettings("RTIMULib");
RTIMU *imu = RTIMU::createIMU(settings);
if ((imu == NULL) || (imu->IMUType() == RTIMU_TYPE_NULL)) {
printf("No IMU found\n");
exit(1);
}
// IMU Init:
imu->IMUInit();
imu->setSlerpPower(0.02);
imu->setGyroEnable(true);
return imu;
}
/*
* calculateDutyCycle()
* Calculates the duty cycle needed to move our servo to the provided deflection.
* @param deflection the input angular deflection
* @returns duty_cycle the duty cycle to send to the motor
*/
float calculateDutyCycle(float deflection){
return ((0.317*deflection)+52.464)/100;
}
/*
* motorControl()
* Inspects last read set of data from IMU and calculates a restoring displacement that is
* then translated to a duty cycle that is then sent to the motor. Any smoothing tasks occur
* in this function.
* @param imuData the RTIMU_DATA object that holds the last read set of data.
* @param pwm the PWM control object that writes the motor control signal.
*/
void motorControl(RTIMU_DATA imuData, mraa::Pwm* pwm){
//printf("%s\r", RTMath::displayDegrees("Gyro", imuData.fusionPose));
RTMath::displayDegrees("Gyro", imuData.fusionPose);
float current_reading=imuData.fusionPose.x()*(180.0/3.14); // get roll measurement
float currentRunningAvg=runningDeflectionAverage(current_reading);
writeToCSV(current_reading);
float duty_cycle=calculateDutyCycle(limit(current_reading)-currentRunningAvg);
pwm->config_percent(3,duty_cycle); // Write duty_cycle with period of 1ms
//printf("\n\n");
//printf("\nRunning Average %f",currentRunningAvg);
fflush(stdout);
}
/*
* writeToCSV()
* Writes the current
*/
void writeToCSV(float current_reading){
long long currTime=current_timestamp();
if (currTime-oldTime>=saveSamplePeriod){
std::ofstream logfile (saveName,std::ios::app);
sprintf(buffer,"%lli,%f\n",currTime,current_reading);
logfile << buffer;
logfile.close();
oldTime=currTime;
//printf("timestamp: %lli",currTime);
}
}
float limit(float current_reading){
if (abs(current_reading) > 20){
return ( (current_reading > 0) - (current_reading<0) )*20; //return pos or neg 20 based on the sign of current reading
}
return current_reading;
}
float runningDeflectionAverage(float sample){
if (samplesSeen>runningAvgSamples){
// do normal stuff
float oldestSample=0;
oldestSample=(float)prevSamples.front();
prevSamples.pop();
currentAverage=currentAverage-(oldestSample/runningAvgSamples);
currentAverage=currentAverage+(sample/runningAvgSamples);
prevSamples.push(sample); // add sample to queue
return currentAverage;
}
else{
prevSamples.push(sample); // add to queue
samplesSeen++;
currentAverage=(currentAverage+sample)/samplesSeen;
return 0;
}
}
long long current_timestamp() {
struct timeval te;
gettimeofday(&te, NULL); // get current time
long long milliseconds = te.tv_sec*1000LL + te.tv_usec/1000; // caculate milliseconds
//printf("milliseconds: %lld\n", milliseconds);
return milliseconds;
}
<file_sep>var myApp = angular.module('mainapp', []);
myApp.controller("mainController", function($scope,$http){
var dataList;
$http.get("/datalist").success(
function(data){
$scope.fileList=data.files;
dataList=data.files;
console.log(data.files[0]);
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"data/"+data.files[0], // path to CSV file
{ylabel:'Deflection Angle',
xlabel:'Sample Number',
animatedZooms:true} // options
);
}
);
$scope.switchGraph=function(index){
console.log(index);
g2 = new Dygraph(
document.getElementById("graphdiv2"),
"data/"+$scope.fileList[index], // path to CSV file
{ylabel:'Deflection Angle',
xlabel:'Sample Number',
animatedZooms:true} // options
);
}
});
<file_sep>#include <iostream>
#include <string.h>
#include <time.h>
#include <mraa.hpp>
int main() {
mraa::Pwm* pwm;
pwm = new mraa::Pwm(0);
clock_t t;
if (pwm == NULL) {
return MRAA_ERROR_UNSPECIFIED;
}
if (pwm->enable(true) != MRAA_SUCCESS) {
std::cerr << "Cannot enable PWM on mraa::PWM object, exiting" << std::endl;
return MRAA_ERROR_UNSPECIFIED;
}
char buffer[20];
float duty_cycle=0.5;
for (;;) {
std::cout << "Type new duty cycle: ";
std::cin >> buffer;
duty_cycle=atof(buffer);
t = clock();
pwm->config_percent(1,duty_cycle); // Write 50% duty cycle period of 1ms
t = clock() - t;
double time_taken = ((double)t)/CLOCKS_PER_SEC; // in seconds
printf("Time taken to write: %f seconds\n", time_taken);
//pwm->period_us(500);
usleep(1000);
}
delete pwm;
return 0;
}
|
b3a29b96b4a7f0b8795bd970f63c7ed136ca22f4
|
[
"Markdown",
"JavaScript",
"C++",
"INI"
] | 8 |
INI
|
suyashkumar/BME464_Tremor
|
86d236631b54427f849866b83723c7a960074f86
|
c64174828f4463539fb2d60a7df2c04b91ff6805
|
refs/heads/master
|
<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Soundboard FIPA</title>
<!-- Bootstrap core CSS -->
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/heroic-features.css" rel="stylesheet">
</head>
<body>
<!-- Navigation -->
<nav class="navbar navbar-expand-lg navbar-dark bg-dark fixed-top">
<div class="container">
<a class="navbar-brand" href="#">Soundboard FIPA</a>
</div>
</nav>
<!-- Page Content -->
<div class="container">
<!-- Page Features -->
<div class="row text-center">
<?php
$files = scandir('audio/');
foreach($files as $file) {
if ($file == '.' || $file == '..')
continue;
echo('
<div class="col-lg-4">
<div class="card">
<div class="card-body">
<h5 class="card-title">'.$file.'</h5>
</div>
<div class="card-footer">
<audio controls src="audio/'.$file.'"/>
</div>
</div>
</div>');
}
?>
</div>
<!-- /.row -->
</div>
<!-- /.container -->
<!-- Bootstrap core JavaScript -->
<script src="vendor/jquery/jquery.min.js"></script>
<script src="vendor/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>
|
36998af668c771234814c94b88133d9e314c02d7
|
[
"PHP"
] | 1 |
PHP
|
Superjajaman75/soundbox
|
7868dddd7e038200053b4e137266507408a019d2
|
6dd77d19e573856a2f932435c07c03e1dde4f550
|
refs/heads/master
|
<repo_name>SwagWarrior/armory-hardened<file_sep>/hardened/src/bitcoin.c
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "bitcoin.h"
void hash256(const uint8_t *data, size_t len, uint8_t *digest)
{
sha256_Raw(data, len, digest);
sha256_Raw(digest, SHA256_DIGEST_LENGTH, digest);
}
void hash160(const uint8_t *data, size_t len, uint8_t *digest)
{
uint8_t hash[SHA256_DIGEST_LENGTH];
sha256_Raw(data, len, hash);
ripemd160(hash, SHA256_DIGEST_LENGTH, digest);
}
void compute_checksum(const uint8_t *data, size_t len, uint8_t checksum[4])
{
uint8_t hash[SHA256_DIGEST_LENGTH];
hash256(data, len, hash);
memcpy(checksum, hash, 4);
}
uint8_t verify_checksum(const uint8_t *data, const size_t len, const uint8_t checksum[4])
{
uint8_t cs[4];
compute_checksum(data, len, cs);
return (cs[0] == checksum[0] && \
cs[1] == checksum[1] && \
cs[2] == checksum[2] && \
cs[3] == checksum[3]) ? 1 : 0;
}
uint8_t fix_verify_checksum(uint8_t *data, const size_t len, uint8_t checksum[4])
{
uint16_t i, c;
size_t pos = 0;
if(!verify_checksum(data, len, checksum)) {
// search data for error:
while(pos < len) {
c = data[pos];
while(!verify_checksum(data, len, checksum) && i <= 0xFF) {
data[pos] = i++;
}
if(verify_checksum(data, len, checksum)) return 2; // fixed successfully
data[pos++] = c;
i = 0;
}
// search checksum for error:
pos = 0;
while(pos < 4) {
c = checksum[pos];
while(!verify_checksum(data, len, checksum) && i <= 0xFF) {
checksum[pos] = i++;
}
if(verify_checksum(data, len, checksum)) return 2; // fixed successfully
checksum[pos++] = c;
i = 0;
}
} else return 1; // checksum fine
return 0; // not fixed
}
void privkey_to_pubkey_compressed(uint8_t *privkey, uint8_t *pubkey)
{
EccPoint R;
ecc_make_key(&R, privkey);
vli_swap(R.x,R.x);
pubkey[0] = 0x02 | (R.y[0] & 0x01);
memcpy(pubkey + 1, &R.x, 32);
}
void privkey_to_pubkey(uint8_t *privkey, uint8_t *pubkey)
{
EccPoint R;
vli_swap(privkey,privkey); // we store all bitcoin data big endian, but do calcs with little endian
ecc_make_key(&R, privkey);
vli_swap(privkey,privkey); // swap back from le to be
vli_swap(R.x,R.x);
vli_swap(R.y,R.y);
pubkey[0] = 0x04;
memcpy(pubkey + 1, &R.x, 32);
memcpy(pubkey + 33, &R.y, 32);
}
void pubkey_to_pubkeyhash(const uint8_t *pubkey, uint8_t *pubkeyhash)
{
if (pubkey[0] == 0x04) { // uncompressed format
hash160(pubkey, 65, pubkeyhash);
} else if (pubkey[0] == 0x00) {
hash160(pubkey, 1, pubkeyhash); // point at infinity
} else {
hash160(pubkey, 33, pubkeyhash); // expecting compressed format
}
}
void pubkeyhash_to_addr(const uint8_t *pubkeyhash, const uint8_t version, char *addr)
{
uint8_t rawaddr[25];
rawaddr[0] = version;
memcpy(rawaddr + 1, pubkeyhash, 20);
compute_checksum(rawaddr, 21, rawaddr + 21);
base58_encode(rawaddr, 25, addr);
}
void pubkey_to_addr(const uint8_t *pubkey, const uint8_t version, char *addr)
{
uint8_t pubkeyhash[20];
pubkey_to_pubkeyhash(pubkey, pubkeyhash);
pubkeyhash_to_addr(pubkeyhash, version, addr);
}
void privkey_to_pubkeyhash(uint8_t *privkey, uint8_t *pubkeyhash)
{
uint8_t temp[65];
privkey_to_pubkey(privkey,temp);
pubkey_to_pubkeyhash(temp,pubkeyhash);
}
void pubkey_to_p2pkhscript(uint8_t *pubkey, uint8_t *pkscript)
{
uint8_t hash[20];
pubkey_to_pubkeyhash(pubkey,hash);
pkscript[0] = 0x76; // OP_DUP
pkscript[1] = 0xa9; // OP_HASH160
pkscript[2] = 0x14; // PUSHDATA 20 bytes
memcpy(&pkscript[3], hash, 20);
pkscript[23] = 0x88; // OP_EQUALVERIFY
pkscript[24] = 0xac; // OP_CHECKSIG
}
void pkscript_to_addr(const uint8_t *pkscript, const size_t len, char *addr)
{
if(len == 0x19 &&
pkscript[0] == 0x76 && // OP_DUP
pkscript[1] == 0xa9 && // OP_HASH160
pkscript[2] == 0x14 && // PUSHDATA 20 bytes
pkscript[23] == 0x88 && // OP_EQUALVERIFY
pkscript[24] == 0xac) { // OP_CHECKSIG
pubkeyhash_to_addr(&pkscript[3], 0x00, addr); // is P2PKH
} else if(len == 0x17 &&
pkscript[0] == 0xa9 && // OP_HASH160
pkscript[1] == 0x14 && // PUSHDATA 20 bytes
pkscript[22] == 0x87) { // OP_EQUAL
pubkeyhash_to_addr(&pkscript[2], 0x05, addr); // is P2SH
} else {
strcpy(addr, "unknown"); // Multisig, P2PK, OP_RETURN not supported
}
}
void pkscript_to_pubkeyhash(const uint8_t *pkscript, const size_t len, uint8_t *pubkeyhash)
{
if(len == 0x19 &&
pkscript[0] == 0x76 && // OP_DUP
pkscript[1] == 0xa9 && // OP_HASH160
pkscript[2] == 0x14 && // PUSHDATA 20 bytes
pkscript[23] == 0x88 && // OP_EQUALVERIFY
pkscript[24] == 0xac) { // OP_CHECKSIG
memcpy(pubkeyhash, &pkscript[3], 20); // is P2PKH
} else if(len == 0x17 &&
pkscript[0] == 0xa9 && // OP_HASH160
pkscript[1] == 0x14 && // PUSHDATA 20 bytes
pkscript[22] == 0x87) { // OP_EQUAL
memcpy(pubkeyhash, &pkscript[2], 20); // is P2PKH
} else {
memset(pubkeyhash, 0, 20); // Multisig, P2PK, OP_RETURN not supported
}
}<file_sep>/hardened/src/utils.c
/*
* utils.c
*
*/
#include "utils.h"
static bool usb_cdc_open = false;
const char easy16chars[] = "asdfghjkwertuion";
//const char easy16chars_obf[] = "ASDFGHJKWERTUION";
size_t binary_to_easyType16(const uint8_t *src, const size_t len, char *dest)
{
size_t pos = 0, destpos = 0;
while(pos < len) {
dest[destpos++] = easy16chars[(src[pos] >> 4)];
dest[destpos++] = easy16chars[(src[pos++] & 0x0F)];
if(!(pos % 2) && pos < len) {
dest[destpos++] = ' ';
}
}
dest[destpos] = '\0';
return destpos;
}
size_t easyType16_to_binary(const char *src, uint8_t *dest, const size_t destlen)
{
uint8_t i, ii;
size_t pos = 0, destpos = 0;
while(src[pos] != '\0' && destpos < destlen) {
if(src[pos] != ' ' && src[pos] != '\r' && src[pos] != '\n') {
for(i = 0; i < 16; i++) {
if(src[pos] == easy16chars[i]) {
pos++;
for(ii = 0; ii < 16; ii++) {
if(src[pos] == easy16chars[ii]) {
dest[destpos++] = (i << 4) | ii;
break;
}
}
break;
}
}
}
pos++;
}
return pos;
}
void makeSixteenBytesEasy(const uint8_t *src, char *dest)
{
uint8_t cs[4];
compute_checksum(src, 16, cs);
binary_to_easyType16(src, 16, dest);
*(dest + 39) = ' ';
binary_to_easyType16(cs, 2, dest + 40);
}
size_t readSixteenEasyBytes(const char *src, uint8_t *dest)
{
uint8_t cs[4], bin[18];
size_t srcpos = easyType16_to_binary(src, bin, 18);
compute_checksum(bin, 16, cs);
if(cs[0] == bin[16] && cs[1] == bin[17]) {
memcpy(dest, bin, 16);
return srcpos;
}
return 0;
}
uint8_t securely_erase_file(const char *filename)
{
FIL fp;
char c[2];
if(!f_open(&fp, filename, FA_WRITE | FA_READ)) {
while(!f_eof(&fp)) {
f_putc('-', &fp);
}
f_lseek(&fp, 0);
while(!f_eof(&fp)) {
if(!f_gets(c, 2, &fp) || c[0] != '-') return 0;
}
f_close(&fp);
if(f_unlink(filename)) return 0;
return 1;
}
return 0;
}
uint8_t scan_for_file(const char *s1, const char *s2, char *filename)
{
uint32_t fdatetime_latest = 0;
uint32_t fdatetime_current = 0;
//uint16_t fdate = 0;
//char fname[_MAX_LFN + 1] = "\0";
FRESULT res;
FILINFO fno;
DIR dir;
// int i;
char *fn;
*filename = '\0';
static char lfn[_MAX_LFN + 1]; /// Buffer to store the LFN
fno.lfname = lfn;
fno.lfsize = sizeof lfn;
res = f_opendir(&dir, "/"); // Open the directory
if (res == FR_OK) {
//i = strlen(path);
for (;;) {
res = f_readdir(&dir, &fno); // Read a directory item
if (res != FR_OK || fno.fname[0] == 0) break; // Break on error or end of dir
if (fno.fname[0] == '.') continue; // Ignore dot entry
fn = *fno.lfname ? fno.lfname : fno.fname;
if((strstr(fn, s1) && strlen(s2) && strstr(fn, s2)) || (!strlen(s2) && strstr(fn, s1))) {
fdatetime_current = ((uint32_t) fno.fdate << 16) | fno.ftime;
if(fdatetime_current > fdatetime_latest) {
fdatetime_latest = fdatetime_current;
strcpy(filename, fn);
}
}
}
if(*filename != '\0') {
return 1;
}
}
return 0;
}
void usb_cdc_set_dtr(bool b_enable)
{
usb_cdc_open = b_enable;
}
bool usb_cdc_is_open(void)
{
return usb_cdc_open;
}<file_sep>/hardened/src/bytestream.h
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BYTESTREAM_H_
#define BYTESTREAM_H_
#include <asf.h>
#include "string.h"
typedef struct bytestream {
uint8_t *bs; // pointer to buffer
uint16_t res, size, bptr; // reserved buffer space, current content size, cursor pos
size_t srclen, snklen;
size_t vofs;
size_t (*inh)(void *bp, size_t ofs);
size_t (*outh)(void *bp);
void *inh_ctx;
void *outh_ctx;
} BYT;
void b_open(BYT *bp, uint8_t *bytestrm, size_t reserved);
uint8_t *b_addr(BYT *bp);
uint8_t *b_posaddr(BYT *bp);
//size_t b_tell(BYT *bp);
size_t b_size(BYT *bp);
size_t b_ressize(BYT *bp);
size_t b_srcsize(BYT *bp);
size_t b_snksize(BYT *bp);
size_t b_srcsize(BYT *bp);
size_t b_snksize(BYT *bp);
//size_t b_seek(BYT *bp, size_t ofs);
//size_t b_setrewofs(BYT *bp);
//size_t b_unsetrewofs(BYT *bp);
//void b_rewind(BYT *bp);
size_t b_truncate(BYT *bp);
size_t b_reopen(BYT *bp);
//size_t b_read(BYT *bp, uint8_t *buff, size_t btr);
//size_t b_write(BYT *bp, const uint8_t *buff, size_t btw);
size_t b_copy(BYT *bp_from, BYT *bp_to, size_t btc);
size_t b_putc(BYT *bp, char chr);
char b_getc(BYT *bp);
size_t b_putvint(BYT *bp, uint32_t vint);
uint32_t b_getvint(BYT *bp);
size_t b_read(BYT *bp, uint8_t *buff, size_t btr);
//void b_open2(BYT *bp, uint8_t *buff, size_t limit, void *in_handler, void *out_handler);
size_t b_setpos(BYT *bp, size_t ofs);
size_t b_write(BYT *bp, const uint8_t *buff, size_t btw);
void b_flush(BYT *bp);
size_t b_seek(BYT *bp, size_t ofs);
size_t b_tell(BYT *bp);
void b_rewind(BYT *bp);
void b_setbufin(BYT *bp, void *inh, void *ctx);
void b_setbufout(BYT *bp, void *outh, void *ctx);
#endif /* BYTESTREAM_H_ */<file_sep>/hardened/src/utils.h
/*
* utils.h
*
*/
#ifndef UTILS_H_
#define UTILS_H_
#include <string.h>
#include <avr/io.h>
#include <asf.h>
#include "bitcoin.h"
#include "sha2.h"
#include "hmac.h"
#include "ecc.h"
#include "bytestream.h"
size_t binary_to_easyType16(const uint8_t *src, const size_t len, char *dest);
size_t easyType16_to_binary(const char *src, uint8_t *dest, const size_t destlen);
void makeSixteenBytesEasy(const uint8_t *src, char *dest);
size_t readSixteenEasyBytes(const char *src, uint8_t *dest);
uint8_t securely_erase_file(const char *filename);
uint8_t scan_for_file(const char *s1, const char *s2, char *filename);
bool usb_cdc_is_open(void);
void usb_cdc_set_dtr(bool b_enable);
#endif /* UTILS_H_ */<file_sep>/hardened/src/main.c
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <asf.h>
#include <string.h>
#include <avr/eeprom.h>
#include <stddef.h>
#include <avr/io.h>
#include "ui.h"
#include "bitcoin.h"
#include "base64.h"
#include "base58.h"
#include "ecc.h"
#include "sha2.h"
#include "rand.h"
#include "utils.h"
#include "bytestream.h"
#include "transaction.h"
uint8_t check_sdcard(void);
extern WLT ui_wallet;
uint8_t check_sdcard(void)
{
Ctrl_status status = sd_mmc_test_unit_ready(0);
if (status != CTRL_GOOD) {
udc_stop();
_ui_clear();
gfx_mono_draw_string("ARMORY HARDENED", 19, 5, &sysfont);
gfx_mono_draw_filled_rect(0, 25, 128, 7, 0);
if(status == CTRL_NO_PRESENT){
gfx_mono_draw_string("Insert SD card!", 0, 25, &sysfont);
} else {
gfx_mono_draw_string("SD card failure!", 0, 25, &sysfont);
}
while(sd_mmc_test_unit_ready(0) != CTRL_GOOD);
gfx_mono_draw_filled_rect(0, 25, 128, 7, 0);
gfx_mono_draw_string("Loading", 40, 25, &sysfont);
return 1; // remounted card
}
return 0; // card is fine
}
/*! \brief Main function. Execution starts here.
*/
int main(void)
{
FATFS fs;
irq_initialize_vectors();
cpu_irq_enable();
/* Initialize ASF services */
//sleepmgr_init();
sysclk_init();
board_init();
sd_mmc_init();
rtc_init();
sysclk_enable_module(SYSCLK_PORT_A, SYSCLK_ADC);
adc_rand_init();
_ui_clear();
gfx_mono_draw_string("ARMORY HARDENED", 19, 5, &sysfont);
//gfx_mono_draw_horizontal_line(0, 11, 128, 1);
gfx_mono_draw_filled_rect(0, 25, 128, 7, 0);
gfx_mono_draw_string("Loading", 40, 25, &sysfont);
check_sdcard();
// gfx_mono_draw_string("Loading", 40, 25, &sysfont);
memset(&fs, 0, sizeof(FATFS));
f_mount(LUN_ID_SD_MMC_0_MEM, &fs);
stdio_usb_init();
//udc_start();
_ui_init();
while(true) {
if(check_sdcard()) {
udc_start();
ui_screen_home();
}
while(udi_msc_process_trans());
_ui_scan_buttons();
//usb_check_rx();
}
}<file_sep>/hardened/src/wallet.h
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#define EEP_VERSION (void *) 0
#define EEP_WLTNUM (void *) 1
#define EEP_ACTWLT (void *) 2
#define armwlt_get_eep_walletpos(i) (void *) (3 + (i-1) * sizeof(WLT_EEP))
#define armwlt_get_eep_privkeypos(i) (void *) (3 + (i-1) * sizeof(WLT_EEP) + 7)
#define EEP_WLTNUMMAX 80
#include <string.h>
#include <avr/io.h>
#include <asf.h>
#include "utils.h"
#include "bitcoin.h"
#include "sha2.h"
#include "hmac.h"
#include "ecc.h"
#include "bytestream.h"
#ifndef ARMORY_H_
#define ARMORY_H_
/*
typedef struct armoryReducedAddr1 {
uint8_t hash160[20];
uint8_t hash160_chksum[4];
uint8_t privkey[32];
uint8_t privkey_chksum[4];
uint8_t pubkey[65];
uint8_t pubkey_chksum[4];
} WLT_ADDR;
typedef struct armoryReducedWallet2 {
uint8_t version[4];
uint8_t magicBytes[4];
uint8_t WltFlags[8];
uint8_t createDate[8];
uint8_t uniqueid[6];
uint8_t labelName[32];
uint32_t highestUsedChainIndex;
//WLT_ADDR rootaddr;
} WLT_FIL;*/
typedef struct EEPROMWalletData {
uint8_t set; // 0xAF = set
uint8_t flags;
uint8_t uniqueid[6];
//uint8_t uniqueid_cs[4];
uint8_t privkey[32];
uint8_t privkey_cs[4];
} WLT_EEP;
typedef struct ArmoryWalletInstance2 {
uint16_t id;
uint8_t uniqueid[6];
uint8_t rootkey[32];
uint8_t chaincode[32];
uint8_t rootpubkey[65];
uint8_t rootpubkeyhash[20];
uint8_t addrprivkey[32];
uint8_t addrpubkey[65];
uint8_t addrpubkeyhash[20];
} WLT;
#define WLT_EEP_SETBYTE 0xAF
#define WLT_COMPUTE_UNIQUEID 1
#define WLT_COMPUTE_FIRST_ADDR (1 << 1)
#define WLT_DELETE_ROOTKEY (1 << 2)
#define WLT_DELETE_ADDRPRIVKEY (1 << 3)
void compute_chained_privkey(const uint8_t *privkey, const uint8_t *chaincode, const uint8_t *pubkey, uint8_t *next_privkey);
uint8_t armwlt_get_privkey_from_pubkey(const WLT *wallet, /*FIL *fp*/const char *wltfn, const uint8_t *pubkey, uint8_t *privkey);
uint8_t safe_extend_privkey(uint8_t *privkey, uint8_t *chaincode, uint8_t *pubkey, uint8_t *next_privkey, uint8_t *next_privkey_checksum);
uint8_t safe_extend_pubkey(uint8_t *privkey, uint8_t *pubkey, uint8_t *pubkey_checksum, uint8_t *pubkeyhash, uint8_t *pubkeyhash_checksum);
void derive_chaincode_from_rootkey(uint8_t *privkey, uint8_t *chaincode);
//uint8_t create_wallet_from_rootkey(uint8_t rootkey[32], uint8_t checksum[4], armory_wallet *wallet, armory_addr *addrlist);
uint8_t get_wallet_mapblock(FIL *fp, uint16_t blockstart, uint32_t *ci_map);
//uint8_t armwlt_create_instance(uint16_t walletid, WLT *wallet);
//uint8_t ui_set_active_wallet(WLT *wallet);
uint8_t armwlt_create_instance(WLT *wallet, const uint8_t options);
//uint8_t safe_extend_addrlist(armory_wallet *wallet, armory_addr *addrlist, const uint8_t num);
uint8_t armwlt_read_rootkey_file(const char *filename, uint8_t *rootkey);
uint8_t armwlt_read_shuffrootkey_file(const char *filename, const char *code, uint8_t *rootkey);
uint8_t armwlt_read_wallet_file(const char *filename, uint8_t *rootkey);
uint8_t armwlt_build_rootpubkey_file(const WLT *wallet);
void armwlt_make_rootkey_file(const uint8_t *rootkey);
//uint16_t armwlt_eep_get_first_free_slot(void);
uint8_t armwlt_eep_get_next_free_wltid(uint8_t wltid);
uint8_t armwlt_eep_get_next_wltid(uint8_t wltid);
uint8_t armwlt_eep_get_prev_slot(uint8_t slot);
uint8_t armwlt_eep_read_wallet(WLT *wallet);
uint8_t armwlt_eep_create_wallet(const uint8_t *rootkey, const uint8_t *uniqueid, const uint8_t setact);
uint8_t armwlt_eep_erase_wallet(const uint8_t wltid);
uint8_t armwlt_eep_get_actwlt(void);
uint8_t armwlt_eep_get_wltnum(void);
//uint8_t armwlt_lookup_pubkeyhash(WLT *wallet, uint8_t *pubkeyhash);
#endif /* ARMORY_H_ */<file_sep>/hardened/src/rand.c
/*
* rand.c
*
* Created: 05.01.2015 17:52:51
* Author: Mo
*/
#include "rand.h"
void byteshuffle(const uint8_t *src, const size_t len, uint8_t *dest)
{
size_t i, j = 0;
for(i = 0; i < len; i++) {
if(j != i) {
dest[i] = dest[j];
}
dest[j] = src[i];
j = (size_t) rand32() % (i+1);
}
}
uint32_t rand32(void)
{
uint32_t t;
adc_rand((uint8_t *) &t, 4);
return t;
}
void adc_rand(uint8_t *dest, size_t len)
{
size_t pos = 0;
uint8_t i;
memset(dest, 0, len);
while(pos < len) {
for(i = 0; i < 8; i++) {
ADCA.CH0.CTRL |= ADC_CH_START_bm; // start ADCB channel 0
while(!ADCA.CH0.INTFLAGS); // wait for ADC ready flag
ADCA.CH0.INTFLAGS = ADC_CH_CHIF_bm; // clear flag (cleared by writing 1)
dest[pos] |= ((ADCA.CH0.RES & 0x01) ^ ((ADCA.CH0.RES & 0x02) >> 1)) << i; // XOR lsb and lsb+1 and feed current seed byte
}
pos++;
}
}
void adc_rand_init(void)
{
ADCA.CTRLA = ADC_ENABLE_bm; // enable
ADCA.CTRLB = ADC_CONMODE_bm; // no currlim, signed, no freerun, 12 bit
ADCA.REFCTRL = ADC_REFSEL_INTVCC_gc;
ADCA.PRESCALER = ADC_PRESCALER_DIV256_gc;
ADCA.CH0.CTRL = ADC_CH_INPUTMODE_DIFF_gc;
ADCA.CH0.MUXCTRL = ADC_CH_MUXPOS_PIN6_gc | ADC_CH_MUXNEG_PIN2_gc;
}<file_sep>/hardened/src/ui.c
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "ui.h"
WLT ui_wallet;
WLT ui_wallet_tmp;
char ui_fname[100];
BYT ui_armtx_bp;
uint8_t ui_armtx[5120];
char ui_armtx_uniqueid[9];
extern const char easy16chars[];
extern const char easy16chars_obf[];
char ui_shuff16chars[16];
void (*_ui_sw0_ptr)(void);
void (*_ui_sw1_ptr)(void);
void (*_ui_sw0_lastptr)(void);
void (*_ui_sw1_lastptr)(void);
void (*_ui_qtb_ptr)(uint8_t i);
uint8_t _ui_qtb_i = 0;
uint8_t _ui_qtb_i_max = 0;
void _ui_init(void)
{
gfx_mono_init();
app_touch_init();
tc_enable(&TCC1);
tc_set_direction(&TCC1, TC_UP);
tc_write_count(&TCC1, 0);
if(armwlt_eep_get_wltnum()) {
ui_wallet.id = armwlt_eep_get_actwlt();
armwlt_eep_read_wallet(&ui_wallet);
armwlt_create_instance(&ui_wallet, WLT_DELETE_ROOTKEY);
}
byteshuffle((uint8_t *) &easy16chars, 16, (uint8_t *) &ui_shuff16chars);
ui_screen_home();
}
void _ui_scan_buttons(void)
{
static bool accept_input = true;
static bool qtb0_last_state = false;
static bool qtb1_last_state = false;
bool qtb_state;
if( (tc_read_count(&TCC1) > 12000 || tc_is_overflow(&TCC1))) {
tc_write_clock_source(&TCC1, TC_CLKSEL_OFF_gc); /* 24MHz / 1024 */
tc_clear_overflow(&TCC1);
tc_write_count(&TCC1, 0);
accept_input = true;
}
if(accept_input) {
if(ioport_pin_is_low(GPIO_PUSH_BUTTON_0) && _ui_sw0_ptr) {
accept_input = false;
tc_write_clock_source(&TCC1, TC_CLKSEL_DIV1024_gc); /* 24MHz / 1024 */
//printf ("0");
udi_cdc_putc('0');
_ui_sw0_ptr();
} else if(ioport_pin_is_low(GPIO_PUSH_BUTTON_1) && _ui_sw1_ptr) {
accept_input = false;
tc_write_clock_source(&TCC1, TC_CLKSEL_DIV1024_gc); /* 24MHz / 1024 */
//printf("\x0CSensor data logs:\r\n");
udi_cdc_putc('1');
_ui_sw1_ptr();
}
/* Manage frequency sample through QTouch buttons */
qtb_state = app_touch_check_key_pressed(0);
if (qtb_state != qtb0_last_state) {
/* QTouch button have changed */
qtb0_last_state = qtb_state;
if (!qtb_state) {
/* It is a press */
//printf("QTB\r\n");
udi_cdc_putc('A');
accept_input = false;
tc_write_clock_source(&TCC1, TC_CLKSEL_DIV1024_gc); /* 24MHz / 1024 */
_ui_qtb_action(0);
}
}
qtb_state = app_touch_check_key_pressed(1);
if (qtb_state != qtb1_last_state) {
/* QTouch button have changed */
qtb1_last_state = qtb_state;
if (!qtb_state) {
/* It is a press */
udi_cdc_putc('V');
accept_input = false;
tc_write_clock_source(&TCC1, TC_CLKSEL_DIV1024_gc); /* 24MHz / 1024 */
_ui_qtb_action(1);
}
}
}
app_touch_task();
}
void _ui_clear(void)
{
gfx_mono_init();
_ui_set_qtb(NULL, 0);
_ui_set_sw0(NULL, 0);
_ui_set_sw1(NULL, 0);
}
void _ui_set_qtb(void *dest, uint8_t i_max)
{
_ui_qtb_ptr = dest;
_ui_qtb_i = 0;
_ui_qtb_i_max = i_max;
if(_ui_qtb_ptr) {
gfx_mono_draw_string(" QTB>", 48, 25, &sysfont);
_ui_qtb_ptr(0);
}
}
void _ui_qtb_action(uint8_t dir)
{
if(_ui_qtb_ptr) {
if(dir && _ui_qtb_i < _ui_qtb_i_max) {
_ui_qtb_ptr(++_ui_qtb_i);
} else if(!dir && _ui_qtb_i > 0) {
_ui_qtb_ptr(--_ui_qtb_i);
}
if(_ui_qtb_i == 0) {
gfx_mono_draw_string(" QTB>", 48, 25, &sysfont);
} else if(_ui_qtb_i == _ui_qtb_i_max) {
gfx_mono_draw_string("<QTB ", 48, 25, &sysfont);
} else {
gfx_mono_draw_string("<QTB>", 48, 25, &sysfont);
}
}
}
void _ui_set_sw0(void *dest, char label)
{
_ui_sw0_lastptr = _ui_sw0_ptr;
_ui_sw0_ptr = dest;
if(dest && label) {
gfx_mono_draw_string("SW0:", 0, 25, &sysfont);
gfx_mono_draw_char(label, 24, 25, &sysfont);
}
}
void _ui_set_sw1(void *dest, char label)
{
_ui_sw1_lastptr = _ui_sw1_ptr;
_ui_sw1_ptr = dest;
if(dest && label) {
gfx_mono_draw_string("SW1:", 96, 25, &sysfont);
gfx_mono_draw_char(label, 120, 25, &sysfont);
}
}
void ui_screen_menu(void)
{
_ui_clear();
gfx_mono_draw_string("SELECT MENU ITEM:", 0, 0, &sysfont);
_ui_set_qtb(&ui_screen_menu_list, 5);
_ui_set_sw0(&ui_screen_home,'B');
}
void ui_screen_menu_list(uint8_t i)
{
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
if(i == 0) {
gfx_mono_draw_string("> Select wallet", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_selectwlt,'S');
} else if(i == 1) {
gfx_mono_draw_string("> Show shuffle code", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_shuffcode,'S');
} else if(i == 2) {
gfx_mono_draw_string("> Export wallet", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_exportwlt,'S');
} else if(i == 3) {
gfx_mono_draw_string("> Erase wallet", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_erasewlt,'S');
} else if(i == 4) {
gfx_mono_draw_string("> Set up wallet", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt,'S');
} else if(i == 5) {
gfx_mono_draw_string("> Change PIN", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_changepin,'S');
}
}
void ui_screen_menu_shuffcode(void)
{
_ui_clear();
gfx_mono_draw_string("SHUFFLE CODE:", 0, 0, &sysfont);
_ui_set_qtb(&ui_screen_menu_shuffcode_list, 3);
_ui_set_sw0(&ui_screen_home,'B');
_ui_set_sw1(&ui_screen_menu_shuffcode_refresh,'R');
}
void ui_screen_menu_shuffcode_refresh(void)
{
byteshuffle((uint8_t *) &easy16chars, 16, (uint8_t *) &ui_shuff16chars);
ui_screen_menu_shuffcode();
}
void ui_screen_menu_shuffcode_list(uint8_t i)
{
char q[21];
sprintf(q, "%c=%X %c=%X %c=%X %c=%X", ui_shuff16chars[i*4], i*4, ui_shuff16chars[1+i*4], 1+i*4, ui_shuff16chars[2+i*4], 2+i*4, ui_shuff16chars[3+i*4], 3+i*4);
gfx_mono_draw_string(q, 0, 11, &sysfont);
}
void ui_screen_menu_erasewlt(void)
{
char b58uniqueid[10], q[21];
_ui_clear();
gfx_mono_draw_string("ERASE WALLET:", 0, 0, &sysfont);
base58_encode((const uint8_t *) &ui_wallet.uniqueid, 6, b58uniqueid);
sprintf(q, "Erase %s?", b58uniqueid);
gfx_mono_draw_string(q, 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu,'N');
_ui_set_sw1(&ui_screen_menu_erasewlt_erase,'Y');
}
void ui_screen_menu_erasewlt_erase(void)
{
char b58uniqueid[10], q[21];
_ui_set_sw1(NULL, 0);
_ui_set_sw0(NULL, 0);
gfx_mono_draw_filled_rect(0, 11, 128, 21, 0);
gfx_mono_draw_string("Erasing wallet...", 0, 11, &sysfont);
if(armwlt_eep_erase_wallet(ui_wallet.id)) {
base58_encode((const uint8_t *) &ui_wallet.uniqueid, 6, b58uniqueid);
if((ui_wallet.id = armwlt_eep_get_actwlt())) {
gfx_mono_draw_string("Switching wallet...", 0, 11, &sysfont);
armwlt_eep_read_wallet(&ui_wallet);
armwlt_create_instance(&ui_wallet, WLT_DELETE_ROOTKEY);
} else {
memset(&ui_wallet, 0, sizeof(WLT));
}
sprintf(q, "Erased %s.", b58uniqueid);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string(q, 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_home,'B');
return;
}
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string("Erasing failed.", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu,'B');
}
void ui_screen_menu_setupwlt(void)
{
_ui_clear();
gfx_mono_draw_string("WALLET SETUP:", 0, 0, &sysfont);
_ui_set_qtb(&ui_screen_menu_setupwlt_list, 3);
if(eeprom_read_byte(EEP_WLTNUM)) {
_ui_set_sw0(&ui_screen_menu,'B');
} else {
_ui_set_sw0(&ui_screen_home,'B');
}
}
void ui_screen_menu_setupwlt_list(uint8_t i)
{
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
if(i == 0) {
gfx_mono_draw_string("> Create on-chip", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_createonchip,'S');
} else if(i == 1) {
gfx_mono_draw_string("> Plain wallet file", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_wltfile,'S');
} else if(i == 2) {
gfx_mono_draw_string("> Plain rootkey file", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_rootkeyfile,'S');
} else if(i == 3) {
gfx_mono_draw_string("> Shuff. rootkey file", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_shuffrootkeyfile,'S');
}
}
void ui_screen_menu_setupwlt_createonchip(void)
{
_ui_clear();
gfx_mono_draw_string("CREATE WALLET:", 0, 0, &sysfont);
gfx_mono_draw_string("Seeding wallet...", 0, 11, &sysfont);
adc_rand(ui_wallet_tmp.rootkey, 32);
hash256(ui_wallet_tmp.rootkey, 32, ui_wallet_tmp.rootkey);
gfx_mono_draw_string("Computing wallet...", 0, 11, &sysfont);
armwlt_create_instance(&ui_wallet_tmp, WLT_COMPUTE_UNIQUEID);
ui_screen_menu_setupwlt_import();
}
void ui_screen_menu_setupwlt_wltfile(void)
{
char b58uniqueid[10], q[21];
_ui_clear();
udc_stop();
gfx_mono_draw_string("WALLET FILE IMPORT:", 0, 0, &sysfont);
if(!scan_for_file("decrypt.wallet", "", ui_fname) || !armwlt_read_wallet_file(ui_fname, ui_wallet_tmp.rootkey)) {
gfx_mono_draw_string("No valid data found.", 0, 11, &sysfont);
udc_start();
_ui_set_sw0(&ui_screen_menu_setupwlt,'B');
return;
}
gfx_mono_draw_string("Computing wallet...", 0, 11, &sysfont);
armwlt_create_instance(&ui_wallet_tmp, WLT_COMPUTE_UNIQUEID);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
base58_encode((const uint8_t *) &ui_wallet_tmp.uniqueid, 6, b58uniqueid);
sprintf(q, "Import %s?", b58uniqueid);
gfx_mono_draw_string(q, 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_import,'Y');
_ui_set_sw0(&ui_screen_menu_setupwlt_erase,'N');
}
void ui_screen_menu_setupwlt_rootkeyfile(void)
{
char b58uniqueid[10], q[21];
_ui_clear();
udc_stop();
gfx_mono_draw_string("ROOTKEY FILE IMPORT:", 0, 0, &sysfont);
if(!scan_for_file("rootkey", "", ui_fname) || !armwlt_read_rootkey_file(ui_fname, ui_wallet_tmp.rootkey)) {
gfx_mono_draw_string("No valid data found.", 0, 11, &sysfont);
udc_start();
_ui_set_sw0(&ui_screen_menu_setupwlt,'B');
return;
}
gfx_mono_draw_string("Computing wallet...", 0, 11, &sysfont);
armwlt_create_instance(&ui_wallet_tmp, WLT_COMPUTE_UNIQUEID);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
base58_encode((const uint8_t *) &ui_wallet_tmp.uniqueid, 6, b58uniqueid);
sprintf(q, "Import %s?", b58uniqueid);
gfx_mono_draw_string(q, 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_import,'Y');
_ui_set_sw0(&ui_screen_menu_setupwlt_erase,'N');
}
void ui_screen_menu_setupwlt_shuffrootkeyfile(void)
{
char b58uniqueid[10], q[21];
_ui_clear();
udc_stop();
gfx_mono_draw_string("SHUFF RK FILE IMPORT:", 0, 0, &sysfont);
if(!scan_for_file("rootkey", "", ui_fname) || !armwlt_read_shuffrootkey_file(ui_fname, ui_shuff16chars, ui_wallet_tmp.rootkey)) {
gfx_mono_draw_string("No valid data found.", 0, 11, &sysfont);
udc_start();
_ui_set_sw0(&ui_screen_menu_setupwlt,'B');
return;
}
gfx_mono_draw_string("Computing wallet...", 0, 11, &sysfont);
armwlt_create_instance(&ui_wallet_tmp, WLT_COMPUTE_UNIQUEID);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
base58_encode((const uint8_t *) &ui_wallet_tmp.uniqueid, 6, b58uniqueid);
sprintf(q, "Import %s?", b58uniqueid);
gfx_mono_draw_string(q, 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_setupwlt_import,'Y');
_ui_set_sw0(&ui_screen_menu_setupwlt_erase,'N');
}
void ui_screen_menu_setupwlt_import(void)
{
char b58uniqueid[10], q[21];
_ui_set_sw1(NULL, 0);
_ui_set_sw0(NULL, 0);
gfx_mono_draw_filled_rect(0, 11, 128, 21, 0);
gfx_mono_draw_string("Importing wallet...", 0, 11, &sysfont);
if((ui_wallet_tmp.id = armwlt_eep_create_wallet(ui_wallet_tmp.rootkey, ui_wallet_tmp.uniqueid, 1))) {
base58_encode((const uint8_t *) &ui_wallet_tmp.uniqueid, 6, b58uniqueid);
sprintf(q, "Set up %s.", b58uniqueid);
memcpy(&ui_wallet, &ui_wallet_tmp, sizeof(WLT));
//eeprom_write_word(EEP_ACTWLT, ui_wallet.id);
//ui_wallet.id = armwlt_eep_get_actwlt();
memset(ui_wallet.rootkey, 0, 32);
memset(ui_wallet.addrprivkey, 0, 32);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string(q, 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu_setupwlt_erase,'B');
} else {
memset(&ui_wallet_tmp, 0, sizeof(WLT));
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string("Setup failed.", 0, 11, &sysfont);
udc_start();
_ui_set_sw0(&ui_screen_menu_setupwlt,'B');
}
}
void ui_screen_menu_setupwlt_erase(void)
{
_ui_set_sw1(NULL, 0);
_ui_set_sw0(NULL, 0);
gfx_mono_draw_filled_rect(0, 11, 128, 21, 0);
gfx_mono_draw_string("Erasing data...", 0, 11, &sysfont);
if(!strlen(ui_fname) || securely_erase_file(ui_fname)) {
udc_start();
if(ui_wallet_tmp.id) {
ui_screen_home();
} else {
ui_screen_menu_setupwlt();
}
memset(&ui_wallet_tmp, 0, sizeof(WLT));
return;
}
memset(&ui_wallet_tmp, 0, sizeof(WLT));
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string("Could not erase file.", 0, 11, &sysfont);
udc_start();
_ui_set_sw0(&ui_screen_menu_setupwlt,'B');
}
void ui_screen_menu_exportwlt(void)
{
_ui_clear();
gfx_mono_draw_string("WALLET EXPORT:", 0, 0, &sysfont);
_ui_set_qtb(&ui_screen_menu_exportwlt_list, 2);
_ui_set_sw0(&ui_screen_menu,'B');
}
void ui_screen_menu_exportwlt_list(uint8_t i)
{
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
if(i == 0) {
gfx_mono_draw_string("> Watchonly data file", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_exportwlt_watchonly,'S');
} else if(i == 1) {
gfx_mono_draw_string("> Rootkey file", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_exportwlt_rootkeyfile,'S');
} else if(i == 2) {
gfx_mono_draw_string("> Show rootkey", 0, 11, &sysfont);
_ui_set_sw1(&ui_screen_menu_exportwlt_showrootkey,'S');
}
}
void ui_screen_menu_exportwlt_rootkeyfile(void)
{
_ui_clear();
gfx_mono_draw_string("MAKE ROOTKEY FILE:", 0, 0, &sysfont);
gfx_mono_draw_string("Disabled.", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu_exportwlt,'B');
}
void ui_screen_menu_exportwlt_watchonly(void)
{
char q[21], b58uniqueid[10];
_ui_clear();
gfx_mono_draw_string("MAKE WATCHONLY FILE:", 0, 0, &sysfont);
_ui_set_sw0(&ui_screen_menu_exportwlt_erase,'B');
if(!armwlt_eep_read_wallet(&ui_wallet)) {
gfx_mono_draw_string("Memory corrupted.", 0, 11, &sysfont);
return;
}
udc_stop();
armwlt_build_rootpubkey_file(&ui_wallet);
udc_start();
base58_encode(ui_wallet.uniqueid, 6, b58uniqueid);
sprintf(q, "%s exported.", b58uniqueid);
gfx_mono_draw_string(q, 0, 11, &sysfont);
}
void ui_screen_menu_exportwlt_showrootkey(void)
{
_ui_clear();
/*gfx_mono_draw_string("SHOW WALLET ROOTKEY:", 0, 0, &sysfont);
gfx_mono_draw_string("Disabled.", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu_exportwlt,'B');
return;*/
gfx_mono_draw_string("SHOW WALLET ROOTKEY:", 0, 0, &sysfont);
_ui_set_sw0(&ui_screen_menu_exportwlt_erase,'B');
if(!armwlt_eep_read_wallet(&ui_wallet)) {
gfx_mono_draw_string("Memory corrupted.", 0, 11, &sysfont);
return;
}
_ui_set_qtb(&ui_screen_menu_exportwlt_showrootkey_list, 6);
}
void ui_screen_menu_exportwlt_erase(void)
{
memset(ui_wallet.rootkey, 0, 32);
ui_screen_menu_exportwlt();
}
void ui_screen_menu_exportwlt_showrootkey_list(uint8_t i)
{
char easy16buff[100], disp[15], q[21];
if(i > 0 && i < 4) {
makeSixteenBytesEasy(ui_wallet.rootkey, easy16buff);
memcpy(disp, easy16buff + (i-1)*15, 15);
} else if(i > 0){
makeSixteenBytesEasy(ui_wallet.rootkey + 16, easy16buff);
memcpy(disp, easy16buff + (i-4)*15, 15);
}
disp[14] = '\0';
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
if(i == 0) {
gfx_mono_draw_string("QTB1: Reveal it!", 0, 11, &sysfont);
} else {
sprintf(q, "%u/6: %s", i, disp);
gfx_mono_draw_string(q, 0, 11, &sysfont);
}
}
void ui_screen_menu_browsetxs(void)
{
_ui_clear();
gfx_mono_draw_string("BROWSE TX'S:", 0, 0, &sysfont);
gfx_mono_draw_string("Not yet supported.", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu,'B');
}
void ui_screen_menu_selectwlt(void)
{
_ui_clear();
gfx_mono_draw_string("SELECT WALLET:", 0, 0, &sysfont);
//gfx_mono_draw_string("Not yet supported.", 0, 11, &sysfont);
//if(!ui_wallet_tmp.id) {
//ui_wallet_tmp.id = armwlt_eep_get_next_wltid(1);
ui_wallet_tmp.id = 0;
ui_wallet_tmp.chaincode[0] = 0;
//}
_ui_set_sw0(&ui_screen_menu,'B');
_ui_set_sw1(&ui_screen_menu_selectwlt_setact,'S');
_ui_set_qtb(&ui_screen_menu_selectwlt_list, armwlt_eep_get_wltnum()-1);
}
void ui_screen_menu_selectwlt_setact(void)
{
_ui_clear();
gfx_mono_draw_string("SELECT WALLET:", 0, 0, &sysfont);
gfx_mono_draw_string("Switching wallet...", 0, 11, &sysfont);
memcpy(&ui_wallet, &ui_wallet_tmp, sizeof(WLT));
armwlt_create_instance(&ui_wallet, WLT_DELETE_ROOTKEY);
eeprom_update_byte(EEP_ACTWLT, ui_wallet.id);
ui_screen_home();
}
void ui_screen_menu_selectwlt_list(uint8_t i)
{
//gfx_mono_draw_filled_rect(0, 0, 128, 18, 0);
char q[21];
//WLT eepwlt;
if(i >= ui_wallet_tmp.chaincode[0]) {
ui_wallet_tmp.id = armwlt_eep_get_next_wltid(ui_wallet_tmp.id+1);
} else if(i < ui_wallet_tmp.chaincode[0]) {
ui_wallet_tmp.id = armwlt_eep_get_prev_slot(ui_wallet_tmp.id-1);
}
armwlt_eep_read_wallet(&ui_wallet_tmp);
//memset(ui_wallet_tmp.rootkey, 0, 32);
ui_wallet_tmp.chaincode[0] = i;
base58_encode(ui_wallet_tmp.uniqueid, 6, q);
gfx_mono_draw_string(q, 0, 11, &sysfont);
}
void ui_screen_menu_changepin(void)
{
_ui_clear();
gfx_mono_draw_string("CHANGE PIN:", 0, 0, &sysfont);
gfx_mono_draw_string("Not yet supported.", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_menu,'B');
}
void ui_screen_opentx_list(uint8_t i)
{
gfx_mono_draw_filled_rect(0, 0, 128, 18, 0);
char q[21];
char amount[10];
uint16_t txout;
uint8_t script[100];
char addr[35];
if(i == 0) {
sprintf(q, "SIGN TX %s:", ui_armtx_uniqueid);
gfx_mono_draw_string(q, 0, 0, &sysfont);
gfx_mono_draw_string("QTB1: Show details", 0, 11, &sysfont);
} else if(i == 1) {
_ui_format_amount(armtx_get_total_inputvalue(&ui_armtx_bp), amount);
sprintf(q, "TxIn#: %u (%s)", armtx_get_txin_cnt(&ui_armtx_bp), amount);
gfx_mono_draw_string(q, 0, 0, &sysfont);
_ui_format_amount(armtx_get_fee(&ui_armtx_bp), amount);
sprintf(q, "Fee: %s", amount);
gfx_mono_draw_string(q, 0, 11, &sysfont);
} /*else if(i == 2) {
_ui_format_amount(armtx_get_fee(&ui_armtx_bp), amount);
sprintf(q, "Fee: %s", amount);
gfx_mono_draw_string(q, 0, 11, &sysfont);
} */else if(i >= 2) {
txout = _ui_qtb_i_max - i;
_ui_format_amount(armtx_get_txout_value(&ui_armtx_bp, txout), amount);
pkscript_to_addr(script, armtx_get_txout_script(&ui_armtx_bp, txout, script), addr);
addr[18] = '\0';
sprintf(q, "TxOut %u/%u: %s to", i-1, armtx_get_txout_cnt(&ui_armtx_bp), amount);
gfx_mono_draw_string(q, 0, 0, &sysfont);
sprintf(q, "%s...", addr);
gfx_mono_draw_string(q, 0, 11, &sysfont);
}
}
void _ui_format_amount(const uint64_t input, char *output)
{
uint64_t rem, val = input;
if(val < 100000) { // < 1 milliBTC, using µB notation
rem = val % 100;
if(rem >= 50) val += 100;
val /= 100;
sprintf(output, "%uuB", (uint16_t) val);
} else if(val < 100000000) { // < 1 BTC, using mB notation
rem = val % 100000;
if(rem >= 50000) val += 100000;
val /= 100000;
sprintf(output, "%umB", (uint16_t) val);
} else { // >= 1 BTC, using B notation
rem = val % 100000000;
if(rem >= 50000000) val += 100000000;
sprintf(output, "%uB", (uint16_t) val);
}
}
/*
size_t rebuff(BYT *bp, size_t ofs)
{
//zu füllen: bp->res
//
size_t rem = ui_armtx_bp.size - ofs;
if(bp->res > rem) {
memcpy(bp->bs, ui_armtx_bp.bs + ofs, rem);
return rem;
}
memcpy(bp->bs, ui_armtx_bp.bs + ofs, bp->res);
return bp->res;
}
size_t flushbuff(BYT *bp)
{
memcpy(ui_test, b_addr(bp), bp->size);
return 0;
}
*/
void ui_screen_opentx(void)
{
//if(!b_size(&ui_test_bp)) {
udc_stop();
_ui_clear();
//if(!(*ui_fname)) {
// armtx_get_latest_unsigned_file(ui_fname);
//}
//armtx_fetch_unsigned_file(ui_fname, ui_armtx_uniqueid, &ui_test_bp);
if((!(*ui_fname) && !scan_for_file(".unsigned.tx", "", ui_fname)) || !txfile_fetch_unsigned_file(ui_fname, ui_armtx_uniqueid, &ui_armtx_bp)) {
gfx_mono_draw_string("No valid file found.", 0, 11, &sysfont);
udc_start();
_ui_set_sw0(&ui_screen_home,'B');
return;
}
//}
_ui_set_sw0(&ui_screen_home,'N');
_ui_set_sw1(&ui_screen_signtx,'Y');
_ui_set_qtb(&ui_screen_opentx_list, armtx_get_txout_cnt(&ui_armtx_bp)+1);
}
void ui_screen_signtx(void)
{
_ui_clear();
char q[21], b58uniqueid[10];
char wlt_filename[100];
sprintf(q, "BUILDING TX %s:", ui_armtx_uniqueid);
gfx_mono_draw_string(q, 0, 10 * 0, &sysfont);
base58_encode(ui_wallet.uniqueid, 6, b58uniqueid);
if(!scan_for_file(".watchonly.wallet", b58uniqueid, wlt_filename)) {
gfx_mono_draw_string("Wallet file missing!", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_home,'B');
return;
}
//eeprom_busy_wait();
//eeprom_read_block(ui_wallet.rootkey, armwlt_get_eep_privkeypos(ui_wallet.id), 32);
armwlt_eep_read_wallet(&ui_wallet);
//armtx_fetch_unsigned_file("armory.unsigned.tx", uniqueid, &armtx_bp);
if(!txfile_build_signed_file(&ui_armtx_bp)) {
memset(ui_wallet.rootkey, 0, 32);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string("Key not found!", 0, 11, &sysfont);
_ui_set_sw0(&ui_screen_home,'B');
return;
}
memset(ui_wallet.rootkey, 0, 32);
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
gfx_mono_draw_string("Signing done!", 0, 11, &sysfont);
//f_unlink((TCHAR *) ui_fname);
//*ui_fname = '\0';
b_reopen(&ui_armtx_bp);
udc_start();
_ui_set_sw0(&ui_screen_home,'B');
}
void ui_screen_home(void)
{
char walletid[10];
_ui_clear();
*ui_fname = '\0';
memset(&ui_wallet_tmp, 0, sizeof(WLT));
f_unlink("workspace.bin.temp");
b_open(&ui_armtx_bp, ui_armtx, sizeof(ui_armtx));
//b_open(&ui_test_bp, ui_test, sizeof(ui_test));
//udc_start();
if(armwlt_eep_get_wltnum()) {
base58_encode(ui_wallet.uniqueid, 6, walletid);
gfx_mono_draw_string("Wallet:", 0, 0, &sysfont);//PaV7rsYj
gfx_mono_draw_string(walletid, 48, 0, &sysfont);
//gfx_mono_draw_string("ARMORY HARDENED",
//19, 10 * 0, &sysfont);
gfx_mono_draw_horizontal_line(0, 11, 128, 1);
gfx_mono_draw_string("SW0: Open latest Tx",
0, 16, &sysfont);
gfx_mono_draw_string("SW1: Menu",
0, 25, &sysfont);
_ui_set_sw1(&ui_screen_menu, 0);
_ui_set_sw0(&ui_screen_opentx, 0);
//_ui_set_qtb(&ui_screen_menu_selectwlt, 0);
} else {
gfx_mono_draw_string("Wallet: None", 0, 0, &sysfont);//PaV7rsYj
gfx_mono_draw_horizontal_line(0, 11, 128, 1);
gfx_mono_draw_string("SW0: Shuffle code", 0, 16, &sysfont);
gfx_mono_draw_string("SW1: Set up wallet", 0, 25, &sysfont);
_ui_set_sw0(&ui_screen_menu_shuffcode, 0);
_ui_set_sw1(&ui_screen_menu_setupwlt, 0);
}
}<file_sep>/hardened/Debug/makedep.mk
################################################################################
# Automatically-generated file. Do not edit or delete the file
################################################################################
src\base58.c
src\rand.c
src\ripemd160.c
src\sha2.c
src\transaction.c
src\ui.c
src\utils.c
src\wallet.c
src\app_touch.c
src\ASF\common\components\display\ssd1306\font.c
src\ASF\common\components\display\ssd1306\ssd1306.c
src\ASF\common\components\memory\sd_mmc\sd_mmc.c
src\ASF\common\components\memory\sd_mmc\sd_mmc_mem.c
src\ASF\common\components\memory\sd_mmc\sd_mmc_spi.c
src\ASF\common\services\calendar\calendar.c
src\ASF\common\services\clock\xmega\sysclk.c
src\ASF\common\services\gfx_mono\gfx_mono_framebuffer.c
src\ASF\common\services\gfx_mono\gfx_mono_generic.c
src\ASF\common\services\gfx_mono\gfx_mono_text.c
src\ASF\common\services\gfx_mono\gfx_mono_ug_2832hsweg04.c
src\ASF\common\services\gfx_mono\sysfont.c
src\ASF\common\services\ioport\xmega\ioport_compat.c
src\ASF\common\services\sleepmgr\xmega\sleepmgr.c
src\ASF\common\services\spi\xmega_usart_spi\usart_spi.c
src\ASF\common\services\storage\ctrl_access\ctrl_access.c
src\ASF\common\services\usb\class\cdc\device\udi_cdc.c
src\ASF\common\services\usb\class\composite\device\udi_composite_desc.c
src\ASF\common\services\usb\class\msc\device\udi_msc.c
src\ASF\common\services\usb\udc\udc.c
src\ASF\common\utils\stdio\read.c
src\ASF\common\utils\stdio\stdio_usb\stdio_usb.c
src\ASF\common\utils\stdio\write.c
src\ASF\thirdparty\fatfs\fatfs-port-r0.09\diskio.c
src\ASF\thirdparty\fatfs\fatfs-port-r0.09\xmega\fattime.c
src\ASF\thirdparty\fatfs\fatfs-r0.09\src\ff.c
src\ASF\thirdparty\fatfs\fatfs-r0.09\src\option\ccsbcs.c
src\ASF\thirdparty\qtouch\generic\avr8\qtouch\common\qt_asm_xmega.S
src\ASF\xmega\boards\xmega_c3_xplained\init.c
src\ASF\xmega\drivers\cpu\ccp.s
src\ASF\xmega\drivers\nvm\nvm.c
src\ASF\xmega\drivers\nvm\nvm_asm.s
src\ASF\xmega\drivers\rtc\rtc.c
src\ASF\xmega\drivers\tc\tc.c
src\ASF\xmega\drivers\usart\usart.c
src\ASF\xmega\drivers\usb\usb_device.c
src\base64.c
src\bitcoin.c
src\bytestream.c
src\ecc.c
src\hmac.c
src\main.c
<file_sep>/hardened/src/ecc.c
/*
* Copyright (c) 2013, <NAME>
* Copyright (c) 2014, <NAME>
* Based on micro-ecc, Copyright (c) 2013, <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:
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* * 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 THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
* ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include "ecc.h"
#include <string.h>
#include <stdlib.h>
typedef unsigned int uint;
#define CONCAT1(a, b) a##b
#define CONCAT(a, b) CONCAT1(a, b)
#define Curve_P_32 {0x2F, 0xFC, 0xFF, 0xFF, \
0xFE, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0xFF }
#define Curve_B_32 { \
7, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0, \
0, 0, 0, 0 }
/*#define Curve_G_32 { \
{0x96, 0xC2, 0x98, 0xD8, 0x45, 0x39, 0xA1, 0xF4, 0xA0, 0x33, 0xEB, 0x2D, \
0x81, 0x7D, 0x03, 0x77, 0xF2, 0x40, 0xA4, 0x63, 0xE5, 0xE6, 0xBC, \
0xF8, 0x47, 0x42, 0x2C, 0xE1, 0xF2, 0xD1, 0x17, 0x6B}, \
{0xF5, 0x51, 0xBF, 0x37, 0x68, 0x40, 0xB6, 0xCB, 0xCE, 0x5E, 0x31, 0x6B, \
0x57, 0x33, 0xCE, 0x2B, 0x16, 0x9E, 0x0F, 0x7C, 0x4A, 0xEB, 0xE7, \
0x8E, 0x9B, 0x7F, 0x1A, 0xFE, 0xE2, 0x42, 0xE3, 0x4F}}*/
#define Curve_G_32 { \
{0x98, 0x17, 0xF8, 0x16, \
0x5B, 0x81, 0xF2, 0x59, \
0xD9, 0x28, 0xCE, 0x2D, \
0xDB, 0xFC, 0x9B, 0x02, \
0x07, 0x0B, 0x87, 0xCE, \
0x95, 0x62, 0xA0, 0x55, \
0xAC, 0xBB, 0xDC, 0xF9, \
0x7E, 0x66, 0xBE, 0x79}, \
{0xB8, 0xD4, 0x10, 0xFB, \
0x8F, 0xD0, 0x47, 0x9C, \
0x19, 0x54, 0x85, 0xA6, \
0x48, 0xB4, 0x17, 0xFD, \
0xA8, 0x08, 0x11, 0x0E, \
0xFC, 0xFB, 0xA4, 0x5D, \
0x65, 0xC4, 0xA3, 0x26, \
0x77, 0xDA, 0x3A, 0x48 }}
/* g.x = 79 BE 66 7E F9 DC BB AC 55 A0 62 95 CE 87 0B 07 02 9B FC DB 2D CE 28 D9 59 F2 81 5B 16 F8 17 98
g.y = 48 3A DA 77 26 A3 C4 65 5D A4 FB FC 0E 11 08 A8 FD 17 B4 48 A6 85 54 19 9C 47 D0 8F FB 10 D4 B8 */
#define Curve_G_48 { \
{0xB7, 0x0A, 0x76, 0x72, 0x38, 0x5E, 0x54, 0x3A, 0x6C, 0x29, 0x55, 0xBF, \
0x5D, 0xF2, 0x02, 0x55, 0x38, 0x2A, 0x54, 0x82, 0xE0, 0x41, 0xF7, \
0x59, 0x98, 0x9B, 0xA7, 0x8B, 0x62, 0x3B, 0x1D, 0x6E, 0x74, 0xAD, \
0x20, 0xF3, 0x1E, 0xC7, 0xB1, 0x8E, 0x37, 0x05, 0x8B, 0xBE, 0x22, \
0xCA, 0x87, 0xAA}, \
{0x5F, 0x0E, 0xEA, 0x90, 0x7C, 0x1D, 0x43, 0x7A, 0x9D, 0x81, 0x7E, 0x1D, \
0xCE, 0xB1, 0x60, 0x0A, 0xC0, 0xB8, 0xF0, 0xB5, 0x13, 0x31, 0xDA, \
0xE9, 0x7C, 0x14, 0x9A, 0x28, 0xBD, 0x1D, 0xF4, 0xF8, 0x29, 0xDC, \
0x92, 0x92, 0xBF, 0x98, 0x9E, 0x5D, 0x6F, 0x2C, 0x26, 0x96, 0x4A, \
0xDE, 0x17, 0x36}}
/*#define Curve_N_32 { 0x51, 0x25, 0x63, 0xFC, 0xC2, 0xCA, 0xB9, 0xF3, 0x84, \
0x9E, 0x17, 0xA7, 0xAD, 0xFA, 0xE6, 0xBC, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF }*/
#define Curve_N_32 { 0x41, 0x41, 0x36, 0xD0, 0x8C, 0x5E, 0xD2, 0xBF, 0x3B, 0xA0, 0x48, 0xAF, 0xE6, 0xDC, 0xAE, 0xBA, 0xFE, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
/* FFFFFFFF FFFFFFFF FFFFFFFF FFFFFFFE BA AE DC E6 AF 48 A0 3B BF D2 5E 8C D0 36 41 41 */
static uint8_t curve_p[NUM_ECC_DIGITS] = CONCAT(Curve_P_, ECC_CURVE);
static uint8_t curve_b[NUM_ECC_DIGITS] = CONCAT(Curve_B_, ECC_CURVE);
static EccPoint curve_G = CONCAT(Curve_G_, ECC_CURVE);
uint8_t curve_n[NUM_ECC_DIGITS] = CONCAT(Curve_N_, ECC_CURVE);
static void vli_clear(uint8_t *p_vli)
{
uint i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
p_vli[i] = 0;
}
}
/* Returns 1 if p_vli == 0, 0 otherwise. */
static int vli_isZero(uint8_t *p_vli)
{
uint i;
for(i = 0; i < NUM_ECC_DIGITS; ++i)
{
if(p_vli[i])
{
return 0;
}
}
return 1;
}
/* Returns nonzero if bit p_bit of p_vli is set. */
static uint8_t vli_testBit(uint8_t *p_vli, uint p_bit)
{
return (p_vli[p_bit/8] & (1 << (p_bit % 8)));
}
/* Counts the number of 8-bit "digits" in p_vli. */
static uint vli_numDigits(uint8_t *p_vli)
{
int i;
/* Search from the end until we find a non-zero digit.
We do it in reverse because we expect that most digits will be nonzero. */
for(i = NUM_ECC_DIGITS - 1; i >= 0 && p_vli[i] == 0; --i)
{
}
return (i + 1);
}
/* Counts the number of bits required for p_vli. */
static uint vli_numBits(uint8_t *p_vli)
{
uint i;
uint8_t l_digit;
uint l_numDigits = vli_numDigits(p_vli);
if(l_numDigits == 0)
{
return 0;
}
l_digit = p_vli[l_numDigits - 1];
for(i=0; l_digit; ++i)
{
l_digit >>= 1;
}
return ((l_numDigits - 1) * 8 + i);
}
/* Sets p_dest = p_src. */
static void vli_set(uint8_t *p_dest, uint8_t *p_src)
{
uint i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
p_dest[i] = p_src[i];
}
}
/* Returns sign of p_left - p_right. */
static int vli_cmp(uint8_t *p_left, uint8_t *p_right)
{
int i;
for(i = NUM_ECC_DIGITS-1; i >= 0; --i)
{
if(p_left[i] > p_right[i])
{
return 1;
}
else if(p_left[i] < p_right[i])
{
return -1;
}
}
return 0;
}
/* Computes p_result = p_in << c, returning carry. Can modify in place (if p_result == p_in). 0 < p_shift < 8. */
static uint8_t vli_lshift(uint8_t *p_result, uint8_t *p_in, uint p_shift)
{
uint8_t l_carry = 0;
uint i;
for(i = 0; i < NUM_ECC_DIGITS; ++i)
{
uint8_t l_temp = p_in[i];
p_result[i] = (l_temp << p_shift) | l_carry;
l_carry = l_temp >> (8 - p_shift);
}
return l_carry;
}
/* Computes p_vli = p_vli >> 1. */
static void vli_rshift1(uint8_t *p_vli)
{
uint8_t *l_end = p_vli;
uint8_t l_carry = 0;
p_vli += NUM_ECC_DIGITS;
while(p_vli-- > l_end)
{
uint8_t l_temp = *p_vli;
*p_vli = (l_temp >> 1) | l_carry;
l_carry = l_temp << 7;
}
}
/* Computes p_result = p_left + p_right, returning carry. Can modify in place. */
uint8_t vli_add(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
{
uint8_t l_carry = 0;
uint i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
uint8_t l_sum = p_left[i] + p_right[i] + l_carry;
if(l_sum != p_left[i])
{
l_carry = (l_sum < p_left[i]);
}
p_result[i] = l_sum;
}
return l_carry;
}
/* Computes p_result = p_left - p_right, returning borrow. Can modify in place. */
static uint8_t vli_sub(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
{
uint8_t l_borrow = 0;
uint i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
uint8_t l_diff = p_left[i] - p_right[i] - l_borrow;
if(l_diff != p_left[i])
{
l_borrow = (l_diff > p_left[i]);
}
p_result[i] = l_diff;
}
return l_borrow;
}
/* Computes p_result = p_left * p_right. */
void vli_mult(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
{
uint16_t r01 = 0;
uint8_t r2 = 0;
uint i, k;
/* Compute each digit of p_result in sequence, maintaining the carries. */
for(k=0; k < NUM_ECC_DIGITS*2 - 1; ++k)
{
uint l_min = (k < NUM_ECC_DIGITS ? 0 : (k + 1) - NUM_ECC_DIGITS);
for(i=l_min; i<=k && i<NUM_ECC_DIGITS; ++i)
{
uint16_t l_product = (uint16_t)p_left[i] * p_right[k-i];
r01 += l_product;
r2 += (r01 < l_product);
}
p_result[k] = (uint8_t)r01;
r01 = (r01 >> 8) | (((uint16_t)r2) << 8);
r2 = 0;
}
p_result[NUM_ECC_DIGITS*2 - 1] = (uint8_t)r01;
}
/* Computes p_result = (p_left + p_right) % p_mod.
Assumes that p_left < p_mod and p_right < p_mod, p_result != p_mod. */
void vli_modAdd(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right, uint8_t *p_mod)
{
uint8_t l_carry = vli_add(p_result, p_left, p_right);
if(l_carry || vli_cmp(p_result, p_mod) >= 0)
{ /* p_result > p_mod (p_result = p_mod + remainder), so subtract p_mod to get remainder. */
vli_sub(p_result, p_result, p_mod);
}
}
/* Computes p_result = (p_left - p_right) % p_mod.
Assumes that p_left < p_mod and p_right < p_mod, p_result != p_mod. */
static void vli_modSub(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right, uint8_t *p_mod)
{
uint8_t l_borrow = vli_sub(p_result, p_left, p_right);
if(l_borrow)
{ /* In this case, p_result == -diff == (max int) - diff.
Since -x % d == d - x, we can get the correct result from p_result + p_mod (with overflow). */
vli_add(p_result, p_result, p_mod);
}
}
#if ECC_CURVE == secp128r1
/* Computes p_result = p_product % curve_p.
See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf */
static void vli_mmod_fast(uint8_t *p_result, uint8_t *p_product)
{
uint8_t l_tmp[NUM_ECC_DIGITS];
int l_carry;
vli_set(p_result, p_product);
l_tmp[0] = p_product[16];
l_tmp[1] = p_product[17];
l_tmp[2] = p_product[18];
l_tmp[3] = p_product[19];
l_tmp[4] = p_product[20];
l_tmp[5] = p_product[21];
l_tmp[6] = p_product[22];
l_tmp[7] = p_product[23];
l_tmp[8] = p_product[24];
l_tmp[9] = p_product[25];
l_tmp[10] = p_product[26];
l_tmp[11] = p_product[27];
l_tmp[12] = (p_product[28] & 1) | (p_product[16] << 1);
l_tmp[13] = (p_product[16] >> 7) | (p_product[17] << 1);
l_tmp[14] = (p_product[17] >> 7) | (p_product[18] << 1);
l_tmp[15] = (p_product[18] >> 7) | (p_product[19] << 1);
l_carry = vli_add(p_result, p_result, l_tmp);
l_tmp[0] = (p_product[19] >> 7) | (p_product[20] << 1);
l_tmp[1] = (p_product[20] >> 7) | (p_product[21] << 1);
l_tmp[2] = (p_product[21] >> 7) | (p_product[22] << 1);
l_tmp[3] = (p_product[22] >> 7) | (p_product[23] << 1);
l_tmp[4] = (p_product[23] >> 7) | (p_product[24] << 1);
l_tmp[5] = (p_product[24] >> 7) | (p_product[25] << 1);
l_tmp[6] = (p_product[25] >> 7) | (p_product[26] << 1);
l_tmp[7] = (p_product[26] >> 7) | (p_product[27] << 1);
l_tmp[8] = (p_product[27] >> 7) | (p_product[28] << 1);
l_tmp[9] = (p_product[28] >> 7) | (p_product[29] << 1);
l_tmp[10] = (p_product[29] >> 7) | (p_product[30] << 1);
l_tmp[11] = (p_product[30] >> 7) | (p_product[31] << 1);
l_tmp[12] = (p_product[31] >> 7) | ((p_product[19] & 0x80) >> 6) | (p_product[20] << 2);
l_tmp[13] = (p_product[20] >> 6) | (p_product[21] << 2);
l_tmp[14] = (p_product[21] >> 6) | (p_product[22] << 2);
l_tmp[15] = (p_product[22] >> 6) | (p_product[23] << 2);
l_carry += vli_add(p_result, p_result, l_tmp);
l_tmp[0] = (p_product[23] >> 6) | (p_product[24] << 2);
l_tmp[1] = (p_product[24] >> 6) | (p_product[25] << 2);
l_tmp[2] = (p_product[25] >> 6) | (p_product[26] << 2);
l_tmp[3] = (p_product[26] >> 6) | (p_product[27] << 2);
l_tmp[4] = (p_product[27] >> 6) | (p_product[28] << 2);
l_tmp[5] = (p_product[28] >> 6) | (p_product[29] << 2);
l_tmp[6] = (p_product[29] >> 6) | (p_product[30] << 2);
l_tmp[7] = (p_product[30] >> 6) | (p_product[31] << 2);
l_tmp[8] = (p_product[31] >> 6);
l_tmp[9] = 0;
l_tmp[10] = 0;
l_tmp[11] = 0;
l_tmp[12] = ((p_product[23] & 0xC0) >> 5) | (p_product[24] << 3);
l_tmp[13] = (p_product[24] >> 5) | (p_product[25] << 3);
l_tmp[14] = (p_product[25] >> 5) | (p_product[26] << 3);
l_tmp[15] = (p_product[26] >> 5) | (p_product[27] << 3);
l_carry += vli_add(p_result, p_result, l_tmp);
l_tmp[0] = (p_product[27] >> 5) | (p_product[28] << 3);
l_tmp[1] = (p_product[28] >> 5) | (p_product[29] << 3);
l_tmp[2] = (p_product[29] >> 5) | (p_product[30] << 3);
l_tmp[3] = (p_product[30] >> 5) | (p_product[31] << 3);
l_tmp[4] = (p_product[31] >> 5);
l_tmp[5] = 0;
l_tmp[6] = 0;
l_tmp[7] = 0;
l_tmp[8] = 0;
l_tmp[9] = 0;
l_tmp[10] = 0;
l_tmp[11] = 0;
l_tmp[12] = ((p_product[27] & 0xE0) >> 4) | (p_product[28] << 4);
l_tmp[13] = (p_product[28] >> 4) | (p_product[29] << 4);
l_tmp[14] = (p_product[29] >> 4) | (p_product[30] << 4);
l_tmp[15] = (p_product[30] >> 4) | (p_product[31] << 4);
l_carry += vli_add(p_result, p_result, l_tmp);
l_tmp[0] = (p_product[31] >> 4);
l_tmp[1] = 0;
l_tmp[2] = 0;
l_tmp[3] = 0;
l_tmp[4] = 0;
l_tmp[5] = 0;
l_tmp[6] = 0;
l_tmp[7] = 0;
l_tmp[8] = 0;
l_tmp[9] = 0;
l_tmp[10] = 0;
l_tmp[11] = 0;
l_tmp[12] = (p_product[28] & 0xFE);
l_tmp[13] = p_product[29];
l_tmp[14] = p_product[30];
l_tmp[15] = p_product[31];
l_carry += vli_add(p_result, p_result, l_tmp);
l_tmp[0] = 0;
l_tmp[1] = 0;
l_tmp[2] = 0;
l_tmp[3] = 0;
l_tmp[4] = 0;
l_tmp[5] = 0;
l_tmp[6] = 0;
l_tmp[7] = 0;
l_tmp[8] = 0;
l_tmp[9] = 0;
l_tmp[10] = 0;
l_tmp[11] = 0;
l_tmp[12] = ((p_product[31] & 0xF0) >> 3);
l_tmp[13] = 0;
l_tmp[14] = 0;
l_tmp[15] = 0;
l_carry += vli_add(p_result, p_result, l_tmp);
while(l_carry || vli_cmp(curve_p, p_result) != 1)
{
l_carry -= vli_sub(p_result, p_result, curve_p);
}
}
#elif ECC_CURVE == secp192r1
/* Computes p_result = p_product % curve_p.
See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf */
static void vli_mmod_fast(uint8_t *p_result, uint8_t *p_product)
{
uint8_t l_tmp[NUM_ECC_DIGITS];
int l_carry;
vli_set(p_result, p_product);
vli_set(l_tmp, &p_product[NUM_ECC_DIGITS]); // the top 192 bits of result
l_carry = vli_add(p_result, p_result, l_tmp);
l_tmp[0] = l_tmp[1] = l_tmp[2] = l_tmp[3] = 0;
l_tmp[4] = l_tmp[5] = l_tmp[6] = l_tmp[7] = 0;
l_tmp[8] = p_product[24];
l_tmp[9] = p_product[25];
l_tmp[10] = p_product[26];
l_tmp[11] = p_product[27];
l_tmp[12] = p_product[28];
l_tmp[13] = p_product[29];
l_tmp[14] = p_product[30];
l_tmp[15] = p_product[31];
l_tmp[16] = p_product[32];
l_tmp[17] = p_product[33];
l_tmp[18] = p_product[34];
l_tmp[19] = p_product[35];
l_tmp[20] = p_product[36];
l_tmp[21] = p_product[37];
l_tmp[22] = p_product[38];
l_tmp[23] = p_product[39];
l_carry += vli_add(p_result, p_result, l_tmp);
l_tmp[0] = l_tmp[8] = p_product[40];
l_tmp[1] = l_tmp[9] = p_product[41];
l_tmp[2] = l_tmp[10] = p_product[42];
l_tmp[3] = l_tmp[11] = p_product[43];
l_tmp[4] = l_tmp[12] = p_product[44];
l_tmp[5] = l_tmp[13] = p_product[45];
l_tmp[6] = l_tmp[14] = p_product[46];
l_tmp[7] = l_tmp[15] = p_product[47];
l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
l_carry += vli_add(p_result, p_result, l_tmp);
while(l_carry || vli_cmp(curve_p, p_result) != 1)
{
l_carry -= vli_sub(p_result, p_result, curve_p);
}
}
#elif (ECC_CURVE == secp256k1)
/* omega_mult() is defined farther below for the different curves / word sizes */
static void omega_mult(uint8_t *p_result, uint8_t *p_right);
static void muladd(uint8_t a, uint8_t b, uint8_t *r0, uint8_t *r1, uint8_t *r2)
{
uint16_t p = (uint16_t)a * b;
uint16_t r01 = ((uint16_t)(*r1) << 8) | *r0;
r01 += p;
*r2 += (r01 < p);
*r1 = r01 >> 8;
*r0 = (uint8_t)r01;
}
/* Computes p_result = p_product % curve_p
see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354
Note that this only works if log2(omega) < log2(p)/2 */
static void vli_mmod_fast(uint8_t *p_result, uint8_t *p_product)
{
uint8_t l_tmp[2*NUM_ECC_DIGITS];
int l_carry;
vli_clear(l_tmp);
vli_clear(l_tmp + NUM_ECC_DIGITS);
omega_mult(l_tmp, p_product + NUM_ECC_DIGITS); /* (Rq, q) = q * c */
l_carry = vli_add(p_result, p_product, l_tmp); /* (C, r) = r + q */
vli_clear(p_product);
omega_mult(p_product, l_tmp + NUM_ECC_DIGITS); /* Rq*c */
l_carry += vli_add(p_result, p_result, p_product); /* (C1, r) = r + Rq*c */
while(l_carry > 0)
{
--l_carry;
vli_sub(p_result, p_result, curve_p);
}
if(vli_cmp(p_result, curve_p) > 0)
{
vli_sub(p_result, p_result, curve_p);
}
}
static void omega_mult(uint8_t *p_result, uint8_t *p_right)
{
/* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
uint8_t r0 = 0;
uint8_t r1 = 0;
uint8_t r2 = 0;
uint8_t k;
/* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */
muladd(0xD1, p_right[0], &r0, &r1, &r2);
p_result[0] = r0;
r0 = r1;
r1 = r2;
/* r2 is still 0 */
for(k = 1; k < NUM_ECC_DIGITS; ++k)
{
muladd(0x03, p_right[k-1], &r0, &r1, &r2);
muladd(0xD1, p_right[k], &r0, &r1, &r2);
p_result[k] = r0;
r0 = r1;
r1 = r2;
r2 = 0;
}
muladd(0x03, p_right[NUM_ECC_DIGITS-1], &r0, &r1, &r2);
p_result[NUM_ECC_DIGITS] = r0;
p_result[NUM_ECC_DIGITS + 1] = r1;
p_result[4 + NUM_ECC_DIGITS] = vli_add(p_result + 4, p_result + 4, p_right); /* add the 2^32 multiple */
}
#elif ECC_CURVE == secp256k1 +1
/* Computes p_result = p_product % curve_p
from http://www.nsa.gov/ia/_files/nist-routines.pdf */
static void vli_mmod_fast(uint8_t *p_result, uint8_t *p_product)
{
uint8_t l_tmp[NUM_ECC_DIGITS];
int l_carry;
/* t */
vli_set(p_result, p_product);
/* s1 */
l_tmp[0] = l_tmp[1] = l_tmp[2] = l_tmp[3] = 0;
l_tmp[4] = l_tmp[5] = l_tmp[6] = l_tmp[7] = 0;
l_tmp[8] = l_tmp[9] = l_tmp[10] = l_tmp[11] = 0;
l_tmp[12] = p_product[44];
l_tmp[13] = p_product[45];
l_tmp[14] = p_product[46];
l_tmp[15] = p_product[47];
l_tmp[16] = p_product[48];
l_tmp[17] = p_product[49];
l_tmp[18] = p_product[50];
l_tmp[19] = p_product[51];
l_tmp[20] = p_product[52];
l_tmp[21] = p_product[53];
l_tmp[22] = p_product[54];
l_tmp[23] = p_product[55];
l_tmp[24] = p_product[56];
l_tmp[25] = p_product[57];
l_tmp[26] = p_product[58];
l_tmp[27] = p_product[59];
l_tmp[28] = p_product[60];
l_tmp[29] = p_product[61];
l_tmp[30] = p_product[62];
l_tmp[31] = p_product[63];
l_carry = vli_lshift(l_tmp, l_tmp, 1);
l_carry += vli_add(p_result, p_result, l_tmp);
/* s2 */
l_tmp[12] = p_product[48];
l_tmp[13] = p_product[49];
l_tmp[14] = p_product[50];
l_tmp[15] = p_product[51];
l_tmp[16] = p_product[52];
l_tmp[17] = p_product[53];
l_tmp[18] = p_product[54];
l_tmp[19] = p_product[55];
l_tmp[20] = p_product[56];
l_tmp[21] = p_product[57];
l_tmp[22] = p_product[58];
l_tmp[23] = p_product[59];
l_tmp[24] = p_product[60];
l_tmp[25] = p_product[61];
l_tmp[26] = p_product[62];
l_tmp[27] = p_product[63];
l_tmp[28] = 0;
l_tmp[29] = 0;
l_tmp[30] = 0;
l_tmp[31] = 0;
l_carry += vli_lshift(l_tmp, l_tmp, 1);
l_carry += vli_add(p_result, p_result, l_tmp);
/* s3 */
l_tmp[0] = p_product[32];
l_tmp[1] = p_product[33];
l_tmp[2] = p_product[34];
l_tmp[3] = p_product[35];
l_tmp[4] = p_product[36];
l_tmp[5] = p_product[37];
l_tmp[6] = p_product[38];
l_tmp[7] = p_product[39];
l_tmp[8] = p_product[40];
l_tmp[9] = p_product[41];
l_tmp[10] = p_product[42];
l_tmp[11] = p_product[43];
l_tmp[12] = l_tmp[13] = l_tmp[14] = l_tmp[15] = 0;
l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
l_tmp[24] = p_product[56];
l_tmp[25] = p_product[57];
l_tmp[26] = p_product[58];
l_tmp[27] = p_product[59];
l_tmp[28] = p_product[60];
l_tmp[29] = p_product[61];
l_tmp[30] = p_product[62];
l_tmp[31] = p_product[63];
l_carry += vli_add(p_result, p_result, l_tmp);
/* s4 */
l_tmp[0] = p_product[36];
l_tmp[1] = p_product[37];
l_tmp[2] = p_product[38];
l_tmp[3] = p_product[39];
l_tmp[4] = p_product[40];
l_tmp[5] = p_product[41];
l_tmp[6] = p_product[42];
l_tmp[7] = p_product[43];
l_tmp[8] = p_product[44];
l_tmp[9] = p_product[45];
l_tmp[10] = p_product[46];
l_tmp[11] = p_product[47];
l_tmp[12] = p_product[52];
l_tmp[13] = p_product[53];
l_tmp[14] = p_product[54];
l_tmp[15] = p_product[55];
l_tmp[16] = p_product[56];
l_tmp[17] = p_product[57];
l_tmp[18] = p_product[58];
l_tmp[19] = p_product[59];
l_tmp[20] = p_product[60];
l_tmp[21] = p_product[61];
l_tmp[22] = p_product[62];
l_tmp[23] = p_product[63];
l_tmp[24] = p_product[52];
l_tmp[25] = p_product[53];
l_tmp[26] = p_product[54];
l_tmp[27] = p_product[55];
l_tmp[28] = p_product[32];
l_tmp[29] = p_product[33];
l_tmp[30] = p_product[34];
l_tmp[31] = p_product[35];
l_carry += vli_add(p_result, p_result, l_tmp);
/* d1 */
l_tmp[0] = p_product[44];
l_tmp[1] = p_product[45];
l_tmp[2] = p_product[46];
l_tmp[3] = p_product[47];
l_tmp[4] = p_product[48];
l_tmp[5] = p_product[49];
l_tmp[6] = p_product[50];
l_tmp[7] = p_product[51];
l_tmp[8] = p_product[52];
l_tmp[9] = p_product[53];
l_tmp[10] = p_product[54];
l_tmp[11] = p_product[55];
l_tmp[12] = l_tmp[13] = l_tmp[14] = l_tmp[15] = 0;
l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
l_tmp[24] = p_product[32];
l_tmp[25] = p_product[33];
l_tmp[26] = p_product[34];
l_tmp[27] = p_product[35];
l_tmp[28] = p_product[40];
l_tmp[29] = p_product[41];
l_tmp[30] = p_product[42];
l_tmp[31] = p_product[43];
l_carry -= vli_sub(p_result, p_result, l_tmp);
/* d2 */
l_tmp[0] = p_product[48];
l_tmp[1] = p_product[49];
l_tmp[2] = p_product[50];
l_tmp[3] = p_product[51];
l_tmp[4] = p_product[52];
l_tmp[5] = p_product[53];
l_tmp[6] = p_product[54];
l_tmp[7] = p_product[55];
l_tmp[8] = p_product[56];
l_tmp[9] = p_product[57];
l_tmp[10] = p_product[58];
l_tmp[11] = p_product[59];
l_tmp[12] = p_product[60];
l_tmp[13] = p_product[61];
l_tmp[14] = p_product[62];
l_tmp[15] = p_product[63];
l_tmp[16] = l_tmp[17] = l_tmp[18] = l_tmp[19] = 0;
l_tmp[20] = l_tmp[21] = l_tmp[22] = l_tmp[23] = 0;
l_tmp[24] = p_product[36];
l_tmp[25] = p_product[37];
l_tmp[26] = p_product[38];
l_tmp[27] = p_product[39];
l_tmp[28] = p_product[44];
l_tmp[29] = p_product[45];
l_tmp[30] = p_product[46];
l_tmp[31] = p_product[47];
l_carry -= vli_sub(p_result, p_result, l_tmp);
/* d3 */
l_tmp[0] = p_product[52];
l_tmp[1] = p_product[53];
l_tmp[2] = p_product[54];
l_tmp[3] = p_product[55];
l_tmp[4] = p_product[56];
l_tmp[5] = p_product[57];
l_tmp[6] = p_product[58];
l_tmp[7] = p_product[59];
l_tmp[8] = p_product[60];
l_tmp[9] = p_product[61];
l_tmp[10] = p_product[62];
l_tmp[11] = p_product[63];
l_tmp[12] = p_product[32];
l_tmp[13] = p_product[33];
l_tmp[14] = p_product[34];
l_tmp[15] = p_product[35];
l_tmp[16] = p_product[36];
l_tmp[17] = p_product[37];
l_tmp[18] = p_product[38];
l_tmp[19] = p_product[39];
l_tmp[20] = p_product[40];
l_tmp[21] = p_product[41];
l_tmp[22] = p_product[42];
l_tmp[23] = p_product[43];
l_tmp[24] = l_tmp[25] = l_tmp[26] = l_tmp[27] = 0;
l_tmp[28] = p_product[48];
l_tmp[29] = p_product[49];
l_tmp[30] = p_product[50];
l_tmp[31] = p_product[51];
l_carry -= vli_sub(p_result, p_result, l_tmp);
/* d4 */
l_tmp[0] = p_product[56];
l_tmp[1] = p_product[57];
l_tmp[2] = p_product[58];
l_tmp[3] = p_product[59];
l_tmp[4] = p_product[60];
l_tmp[5] = p_product[61];
l_tmp[6] = p_product[62];
l_tmp[7] = p_product[63];
l_tmp[8] = l_tmp[9] = l_tmp[10] = l_tmp[11] = 0;
l_tmp[12] = p_product[36];
l_tmp[13] = p_product[37];
l_tmp[14] = p_product[38];
l_tmp[15] = p_product[39];
l_tmp[16] = p_product[40];
l_tmp[17] = p_product[41];
l_tmp[18] = p_product[42];
l_tmp[19] = p_product[43];
l_tmp[20] = p_product[44];
l_tmp[21] = p_product[45];
l_tmp[22] = p_product[46];
l_tmp[23] = p_product[47];
l_tmp[24] = l_tmp[25] = l_tmp[26] = l_tmp[27] = 0;
l_tmp[28] = p_product[52];
l_tmp[29] = p_product[53];
l_tmp[30] = p_product[54];
l_tmp[31] = p_product[55];
l_carry -= vli_sub(p_result, p_result, l_tmp);
if(l_carry < 0)
{
do
{
l_carry += vli_add(p_result, p_result, curve_p);
} while(l_carry < 0);
}
else
{
while(l_carry || vli_cmp(curve_p, p_result) != 1)
{
l_carry -= vli_sub(p_result, p_result, curve_p);
}
}
}
#elif ECC_CURVE == secp384r1
static void omega_mult(uint8_t *p_result, uint8_t *p_right)
{
/* Multiply by (2^128 + 2^96 - 2^32 + 1). */
vli_set(p_result, p_right); /* 1 */
p_result[16 + NUM_ECC_DIGITS] = vli_add(p_result + 12, p_result + 12, p_right); /* 2^96 + 1 */
p_result[17 + NUM_ECC_DIGITS] = 0;
p_result[18 + NUM_ECC_DIGITS] = 0;
p_result[19 + NUM_ECC_DIGITS] = 0;
p_result[20 + NUM_ECC_DIGITS] = vli_add(p_result + 16, p_result + 16, p_right); /* 2^128 + 2^96 + 1 */
p_result[21 + NUM_ECC_DIGITS] = 0;
p_result[22 + NUM_ECC_DIGITS] = 0;
p_result[23 + NUM_ECC_DIGITS] = 0;
if(vli_sub(p_result + 4, p_result + 4, p_right)) /* 2^128 + 2^96 - 2^32 + 1 */
{ /* Propagate borrow if necessary. */
uint i;
for(i = 4 + NUM_ECC_DIGITS; ; ++i)
{
--p_result[i];
if(p_result[i] != 0xff)
{
break;
}
}
}
}
/* Computes p_result = p_product % curve_p
see PDF "Comparing Elliptic Curve Cryptography and RSA on 8-bit CPUs"
section "Curve-Specific Optimizations" */
static void vli_mmod_fast(uint8_t *p_result, uint8_t *p_product)
{
uint8_t l_tmp[2*NUM_ECC_DIGITS];
while(!vli_isZero(p_product + NUM_ECC_DIGITS)) /* While c1 != 0 */
{
uint8_t l_carry = 0;
uint i;
vli_clear(l_tmp);
vli_clear(l_tmp + NUM_ECC_DIGITS);
omega_mult(l_tmp, p_product + NUM_ECC_DIGITS); /* tmp = w * c1 */
vli_clear(p_product + NUM_ECC_DIGITS); /* p = c0 */
/* (c1, c0) = c0 + w * c1 */
for(i=0; i<NUM_ECC_DIGITS+20; ++i)
{
uint8_t l_sum = p_product[i] + l_tmp[i] + l_carry;
if(l_sum != p_product[i])
{
l_carry = (l_sum < p_product[i]);
}
p_product[i] = l_sum;
}
}
while(vli_cmp(p_product, curve_p) > 0)
{
vli_sub(p_product, p_product, curve_p);
}
vli_set(p_result, p_product);
}
#endif
/* Computes p_result = (p_left * p_right) % curve_p. */
void vli_modMult_fast(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right)
{
uint8_t l_product[2 * NUM_ECC_DIGITS];
vli_mult(l_product, p_left, p_right);
vli_mmod_fast(p_result, l_product);
//vli_modMult(p_result, p_left, p_right, curve_n);
}
#if ECC_SQUARE_FUNC
/* Computes p_result = p_left^2. */
static void vli_square(uint8_t *p_result, uint8_t *p_left)
{
uint16_t r01 = 0;
uint8_t r2 = 0;
uint i, k;
for(k=0; k < NUM_ECC_DIGITS*2 - 1; ++k)
{
uint l_min = (k < NUM_ECC_DIGITS ? 0 : (k + 1) - NUM_ECC_DIGITS);
for(i=l_min; i<=k && i<=k-i; ++i)
{
uint16_t l_product = (uint16_t)p_left[i] * p_left[k-i];
if(i < k-i)
{
r2 += l_product >> 15;
l_product *= 2;
}
r01 += l_product;
r2 += (r01 < l_product);
}
p_result[k] = (uint8_t)r01;
r01 = (r01 >> 8) | (((uint16_t)r2) << 8);
r2 = 0;
}
p_result[NUM_ECC_DIGITS*2 - 1] = (uint8_t)r01;
}
/* Computes p_result = p_left^2 % curve_p. */
static void vli_modSquare_fast(uint8_t *p_result, uint8_t *p_left)
{
uint8_t l_product[2 * NUM_ECC_DIGITS];
vli_square(l_product, p_left);
vli_mmod_fast(p_result, l_product);
}
#else /* ECC_SQUARE_FUNC */
#define vli_square(result, left, size) vli_mult((result), (left), (left), (size))
#define vli_modSquare_fast(result, left) vli_modMult_fast((result), (left), (left))
#endif /* ECC_SQUARE_FUNC */
#define EVEN(vli) (!(vli[0] & 1))
/* Computes p_result = (1 / p_input) % p_mod. All VLIs are the same size.
See "From Euclid's GCD to Montgomery Multiplication to the Great Divide"
https://labs.oracle.com/techrep/2001/smli_tr-2001-95.pdf */
static void vli_modInv(uint8_t *p_result, uint8_t *p_input, uint8_t *p_mod)
{
uint8_t a[NUM_ECC_DIGITS], b[NUM_ECC_DIGITS], u[NUM_ECC_DIGITS], v[NUM_ECC_DIGITS];
uint8_t l_carry;
vli_set(a, p_input);
vli_set(b, p_mod);
vli_clear(u);
u[0] = 1;
vli_clear(v);
int l_cmpResult;
while((l_cmpResult = vli_cmp(a, b)) != 0)
{
l_carry = 0;
if(EVEN(a))
{
vli_rshift1(a);
if(!EVEN(u))
{
l_carry = vli_add(u, u, p_mod);
}
vli_rshift1(u);
if(l_carry)
{
u[NUM_ECC_DIGITS-1] |= 0x80;
}
}
else if(EVEN(b))
{
vli_rshift1(b);
if(!EVEN(v))
{
l_carry = vli_add(v, v, p_mod);
}
vli_rshift1(v);
if(l_carry)
{
v[NUM_ECC_DIGITS-1] |= 0x80;
}
}
else if(l_cmpResult > 0)
{
vli_sub(a, a, b);
vli_rshift1(a);
if(vli_cmp(u, v) < 0)
{
vli_add(u, u, p_mod);
}
vli_sub(u, u, v);
if(!EVEN(u))
{
l_carry = vli_add(u, u, p_mod);
}
vli_rshift1(u);
if(l_carry)
{
u[NUM_ECC_DIGITS-1] |= 0x80;
}
}
else
{
vli_sub(b, b, a);
vli_rshift1(b);
if(vli_cmp(v, u) < 0)
{
vli_add(v, v, p_mod);
}
vli_sub(v, v, u);
if(!EVEN(v))
{
l_carry = vli_add(v, v, p_mod);
}
vli_rshift1(v);
if(l_carry)
{
v[NUM_ECC_DIGITS-1] |= 0x80;
}
}
}
vli_set(p_result, u);
}
/* ------ Point operations ------ */
/* Returns 1 if p_point is the point at infinity, 0 otherwise. */
static int EccPoint_isZero(EccPoint *p_point)
{
return (vli_isZero(p_point->x) && vli_isZero(p_point->y));
}
/* Point multiplication algorithm using Montgomery's ladder with co-Z coordinates.
From http://eprint.iacr.org/2011/338.pdf
*/
/* Double in place */
static void EccPoint_double_jacobian(uint8_t *X1, uint8_t *Y1, uint8_t *Z1)
{
/* t1 = X, t2 = Y, t3 = Z */
uint8_t t4[NUM_ECC_DIGITS];
uint8_t t5[NUM_ECC_DIGITS];
if(vli_isZero(Z1))
{
return;
}
vli_modSquare_fast(t5, Y1); /* t5 = y1^2 */
vli_modMult_fast(t4, X1, t5); /* t4 = x1*y1^2 = A */
vli_modSquare_fast(X1, X1); /* t1 = x1^2 */
vli_modSquare_fast(t5, t5); /* t5 = y1^4 */
vli_modMult_fast(Z1, Y1, Z1); /* t3 = y1*z1 = z3 */
vli_modAdd(Y1, X1, X1, curve_p); /* t2 = 2*x1^2 */
vli_modAdd(Y1, Y1, X1, curve_p); /* t2 = 3*x1^2 */
if(vli_testBit(Y1, 0))
{
uint8_t l_carry = vli_add(Y1, Y1, curve_p);
vli_rshift1(Y1);
Y1[NUM_ECC_DIGITS-1] |= l_carry << (8 - 1);
}
else
{
vli_rshift1(Y1);
}
/* t2 = 3/2*(x1^2) = B */
vli_modSquare_fast(X1, Y1); /* t1 = B^2 */
vli_modSub(X1, X1, t4, curve_p); /* t1 = B^2 - A */
vli_modSub(X1, X1, t4, curve_p); /* t1 = B^2 - 2A = x3 */
vli_modSub(t4, t4, X1, curve_p); /* t4 = A - x3 */
vli_modMult_fast(Y1, Y1, t4); /* t2 = B * (A - x3) */
vli_modSub(Y1, Y1, t5, curve_p); /* t2 = B * (A - x3) - y1^4 = y3 */
//vli_modSquare_fast(t4, Y1); /* t4 = y1^2 */
//vli_modMult_fast(t5, X1, t4); /* t5 = x1*y1^2 = A */
//vli_modSquare_fast(t4, t4); /* t4 = y1^4 */
//vli_modMult_fast(Y1, Y1, Z1); /* t2 = y1*z1 = z3 */
//vli_modSquare_fast(Z1, Z1); /* t3 = z1^2 */
//vli_modAdd(X1, X1, Z1, curve_p); /* t1 = x1 + z1^2 */
//vli_modAdd(Z1, Z1, Z1, curve_p); /* t3 = 2*z1^2 */
//vli_modSub(Z1, X1, Z1, curve_p); /* t3 = x1 - z1^2 */
//vli_modMult_fast(X1, X1, Z1); /* t1 = x1^2 - z1^4 */
//vli_modAdd(Z1, X1, X1, curve_p); /* t3 = 2*(x1^2 - z1^4) */
//vli_modAdd(X1, X1, Z1, curve_p); /* t1 = 3*(x1^2 - z1^4) */
//if(vli_testBit(X1, 0))
//{
// uint8_t l_carry = vli_add(X1, X1, curve_p);
// vli_rshift1(X1);
// X1[NUM_ECC_DIGITS-1] |= l_carry << 7;
//}
//else
//{
// vli_rshift1(X1);
//}
/* t1 = 3/2*(x1^2 - z1^4) = B */
//vli_modSquare_fast(Z1, X1); /* t3 = B^2 */
//vli_modSub(Z1, Z1, t5, curve_p); /* t3 = B^2 - A */
//vli_modSub(Z1, Z1, t5, curve_p); /* t3 = B^2 - 2A = x3 */
//vli_modSub(t5, t5, Z1, curve_p); /* t5 = A - x3 */
//vli_modMult_fast(X1, X1, t5); /* t1 = B * (A - x3) */
//vli_modSub(t4, X1, t4, curve_p); /* t4 = B * (A - x3) - y1^4 = y3 */
//vli_set(X1, Z1);
//vli_set(Z1, Y1);
//vli_set(Y1, t4);*/
}
/* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */
static void apply_z(uint8_t *X1, uint8_t *Y1, uint8_t *Z)
{
uint8_t t1[NUM_ECC_DIGITS];
vli_modSquare_fast(t1, Z); /* z^2 */
vli_modMult_fast(X1, X1, t1); /* x1 * z^2 */
vli_modMult_fast(t1, t1, Z); /* z^3 */
vli_modMult_fast(Y1, Y1, t1); /* y1 * z^3 */
}
/* P = (x1, y1) => 2P, (x2, y2) => P' */
static void XYcZ_initial_double(uint8_t *X1, uint8_t *Y1, uint8_t *X2, uint8_t *Y2, uint8_t *p_initialZ)
{
uint8_t z[NUM_ECC_DIGITS];
vli_set(X2, X1);
vli_set(Y2, Y1);
vli_clear(z);
z[0] = 1;
if(p_initialZ)
{
vli_set(z, p_initialZ);
}
apply_z(X1, Y1, z);
EccPoint_double_jacobian(X1, Y1, z);
apply_z(X2, Y2, z);
}
/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3)
or P => P', Q => P + Q
*/
static void XYcZ_add(uint8_t *X1, uint8_t *Y1, uint8_t *X2, uint8_t *Y2)
{
/* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
uint8_t t5[NUM_ECC_DIGITS];
vli_modSub(t5, X2, X1, curve_p); /* t5 = x2 - x1 */
vli_modSquare_fast(t5, t5); /* t5 = (x2 - x1)^2 = A */
vli_modMult_fast(X1, X1, t5); /* t1 = x1*A = B */
vli_modMult_fast(X2, X2, t5); /* t3 = x2*A = C */
vli_modSub(Y2, Y2, Y1, curve_p); /* t4 = y2 - y1 */
vli_modSquare_fast(t5, Y2); /* t5 = (y2 - y1)^2 = D */
vli_modSub(t5, t5, X1, curve_p); /* t5 = D - B */
vli_modSub(t5, t5, X2, curve_p); /* t5 = D - B - C = x3 */
vli_modSub(X2, X2, X1, curve_p); /* t3 = C - B */
vli_modMult_fast(Y1, Y1, X2); /* t2 = y1*(C - B) */
vli_modSub(X2, X1, t5, curve_p); /* t3 = B - x3 */
vli_modMult_fast(Y2, Y2, X2); /* t4 = (y2 - y1)*(B - x3) */
vli_modSub(Y2, Y2, Y1, curve_p); /* t4 = y3 */
vli_set(X2, t5);
}
/* Input P = (x1, y1, Z), Q = (x2, y2, Z)
Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3)
or P => P - Q, Q => P + Q
*/
static void XYcZ_addC(uint8_t *X1, uint8_t *Y1, uint8_t *X2, uint8_t *Y2)
{
/* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */
uint8_t t5[NUM_ECC_DIGITS];
uint8_t t6[NUM_ECC_DIGITS];
uint8_t t7[NUM_ECC_DIGITS];
vli_modSub(t5, X2, X1, curve_p); /* t5 = x2 - x1 */
vli_modSquare_fast(t5, t5); /* t5 = (x2 - x1)^2 = A */
vli_modMult_fast(X1, X1, t5); /* t1 = x1*A = B */
vli_modMult_fast(X2, X2, t5); /* t3 = x2*A = C */
vli_modAdd(t5, Y2, Y1, curve_p); /* t4 = y2 + y1 */
vli_modSub(Y2, Y2, Y1, curve_p); /* t4 = y2 - y1 */
vli_modSub(t6, X2, X1, curve_p); /* t6 = C - B */
vli_modMult_fast(Y1, Y1, t6); /* t2 = y1 * (C - B) */
vli_modAdd(t6, X1, X2, curve_p); /* t6 = B + C */
vli_modSquare_fast(X2, Y2); /* t3 = (y2 - y1)^2 */
vli_modSub(X2, X2, t6, curve_p); /* t3 = x3 */
vli_modSub(t7, X1, X2, curve_p); /* t7 = B - x3 */
vli_modMult_fast(Y2, Y2, t7); /* t4 = (y2 - y1)*(B - x3) */
vli_modSub(Y2, Y2, Y1, curve_p); /* t4 = y3 */
vli_modSquare_fast(t7, t5); /* t7 = (y2 + y1)^2 = F */
vli_modSub(t7, t7, t6, curve_p); /* t7 = x3' */
vli_modSub(t6, t7, X1, curve_p); /* t6 = x3' - B */
vli_modMult_fast(t6, t6, t5); /* t6 = (y2 + y1)*(x3' - B) */
vli_modSub(Y1, t6, Y1, curve_p); /* t2 = y3' */
vli_set(X1, t7);
}
void EccPoint_mult(EccPoint *p_result, EccPoint *p_point, uint8_t *p_scalar, uint8_t *p_initialZ)
{
/* R0 and R1 */
uint8_t Rx[2][NUM_ECC_DIGITS];
uint8_t Ry[2][NUM_ECC_DIGITS];
uint8_t z[NUM_ECC_DIGITS];
uint i, nb;
vli_set(Rx[1], p_point->x);
vli_set(Ry[1], p_point->y);
XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], p_initialZ);
for(i = vli_numBits(p_scalar) - 2; i > 0; --i)
{
nb = !vli_testBit(p_scalar, i);
XYcZ_addC(Rx[1-nb], Ry[1-nb], Rx[nb], Ry[nb]);
XYcZ_add(Rx[nb], Ry[nb], Rx[1-nb], Ry[1-nb]);
}
nb = !vli_testBit(p_scalar, 0);
XYcZ_addC(Rx[1-nb], Ry[1-nb], Rx[nb], Ry[nb]);
/* Find final 1/Z value. */
vli_modSub(z, Rx[1], Rx[0], curve_p); /* X1 - X0 */
vli_modMult_fast(z, z, Ry[1-nb]); /* Yb * (X1 - X0) */
vli_modMult_fast(z, z, p_point->x); /* xP * Yb * (X1 - X0) */
vli_modInv(z, z, curve_p); /* 1 / (xP * Yb * (X1 - X0)) */
vli_modMult_fast(z, z, p_point->y); /* yP / (xP * Yb * (X1 - X0)) */
vli_modMult_fast(z, z, Rx[1-nb]); /* Xb * yP / (xP * Yb * (X1 - X0)) */
/* End 1/Z calculation */
XYcZ_add(Rx[nb], Ry[nb], Rx[1-nb], Ry[1-nb]);
apply_z(Rx[0], Ry[0], z);
vli_set(p_result->x, Rx[0]);
vli_set(p_result->y, Ry[0]);
}
int ecc_make_key(EccPoint *p_publicKey, uint8_t p_privateKey[NUM_ECC_DIGITS])//, uint8_t p_random[NUM_ECC_DIGITS])
{
/* Make sure the private key is in the range [1, n-1].
For the supported curves, n is always large enough that we only need to subtract once at most. */
//vli_set(p_privateKey, p_random);
if(vli_cmp(curve_n, p_privateKey) != 1)
{
vli_sub(p_privateKey, p_privateKey, curve_n);
}
if(vli_isZero(p_privateKey))
{
return 0; /* The private key cannot be 0 (mod p). */
}
EccPoint_mult(p_publicKey, &curve_G, p_privateKey, NULL);
return 1;
}
int ecc_valid_public_key(EccPoint *p_publicKey)
{
uint8_t na[NUM_ECC_DIGITS] = {3}; /* -a = 3 */
uint8_t l_tmp1[NUM_ECC_DIGITS];
uint8_t l_tmp2[NUM_ECC_DIGITS];
if(EccPoint_isZero(p_publicKey))
{
return 0;
}
if(vli_cmp(curve_p, p_publicKey->x) != 1 || vli_cmp(curve_p, p_publicKey->y) != 1)
{
return 0;
}
vli_modSquare_fast(l_tmp1, p_publicKey->y); /* tmp1 = y^2 */
vli_modSquare_fast(l_tmp2, p_publicKey->x); /* tmp2 = x^2 */
vli_modSub(l_tmp2, l_tmp2, na, curve_p); /* tmp2 = x^2 + a = x^2 - 3 */
vli_modMult_fast(l_tmp2, l_tmp2, p_publicKey->x); /* tmp2 = x^3 + ax */
vli_modAdd(l_tmp2, l_tmp2, curve_b, curve_p); /* tmp2 = x^3 + ax + b */
/* Make sure that y^2 == x^3 + ax + b */
if(vli_cmp(l_tmp1, l_tmp2) != 0)
{
return 0;
}
return 1;
}
int ecdh_shared_secret(uint8_t p_secret[NUM_ECC_DIGITS], EccPoint *p_publicKey, uint8_t p_privateKey[NUM_ECC_DIGITS], uint8_t p_random[NUM_ECC_DIGITS])
{
EccPoint l_product;
EccPoint_mult(&l_product, p_publicKey, p_privateKey, p_random);
if(EccPoint_isZero(&l_product))
{
return 0;
}
vli_set(p_secret, l_product.x);
return 1;
}
#if ECC_ECDSA
/* -------- ECDSA code -------- */
/* Computes p_result = (p_left * p_right) % p_mod. */
void vli_modMult(uint8_t *p_result, uint8_t *p_left, uint8_t *p_right, uint8_t *p_mod)
{
uint8_t l_product[2 * NUM_ECC_DIGITS];
uint8_t l_modMultiple[2 * NUM_ECC_DIGITS];
uint l_digitShift, l_bitShift;
uint l_productBits;
uint l_modBits = vli_numBits(p_mod);
vli_mult(l_product, p_left, p_right);
l_productBits = vli_numBits(l_product + NUM_ECC_DIGITS);
if(l_productBits)
{
l_productBits += NUM_ECC_DIGITS * 8;
}
else
{
l_productBits = vli_numBits(l_product);
}
if(l_productBits < l_modBits)
{ /* l_product < p_mod. */
vli_set(p_result, l_product);
return;
}
/* Shift p_mod by (l_leftBits - l_modBits). This multiplies p_mod by the largest
power of two possible while still resulting in a number less than p_left. */
vli_clear(l_modMultiple);
vli_clear(l_modMultiple + NUM_ECC_DIGITS);
l_digitShift = (l_productBits - l_modBits) / 8;
l_bitShift = (l_productBits - l_modBits) % 8;
if(l_bitShift)
{
l_modMultiple[l_digitShift + NUM_ECC_DIGITS] = vli_lshift(l_modMultiple + l_digitShift, p_mod, l_bitShift);
}
else
{
vli_set(l_modMultiple + l_digitShift, p_mod);
}
/* Subtract all multiples of p_mod to get the remainder. */
vli_clear(p_result);
p_result[0] = 1; /* Use p_result as a temp var to store 1 (for subtraction) */
while(l_productBits > NUM_ECC_DIGITS * 8 || vli_cmp(l_modMultiple, p_mod) >= 0)
{
int l_cmp = vli_cmp(l_modMultiple + NUM_ECC_DIGITS, l_product + NUM_ECC_DIGITS);
if(l_cmp < 0 || (l_cmp == 0 && vli_cmp(l_modMultiple, l_product) <= 0))
{
if(vli_sub(l_product, l_product, l_modMultiple))
{ /* borrow */
vli_sub(l_product + NUM_ECC_DIGITS, l_product + NUM_ECC_DIGITS, p_result);
}
vli_sub(l_product + NUM_ECC_DIGITS, l_product + NUM_ECC_DIGITS, l_modMultiple + NUM_ECC_DIGITS);
}
uint8_t l_carry = (l_modMultiple[NUM_ECC_DIGITS] & 0x01) << 7;
vli_rshift1(l_modMultiple + NUM_ECC_DIGITS);
vli_rshift1(l_modMultiple);
l_modMultiple[NUM_ECC_DIGITS-1] |= l_carry;
--l_productBits;
}
vli_set(p_result, l_product);
}
static uint max(uint a, uint b)
{
return (a > b ? a : b);
}
int ecdsa_sign(uint8_t r[NUM_ECC_DIGITS], uint8_t s[NUM_ECC_DIGITS], uint8_t p_privateKey[NUM_ECC_DIGITS],
uint8_t p_random[NUM_ECC_DIGITS], uint8_t p_hash[NUM_ECC_DIGITS])
{
uint8_t k[NUM_ECC_DIGITS];
EccPoint p;
if(vli_isZero(p_random))
{ /* The random number must not be 0. */
return 0;
}
vli_set(k, p_random);
if(vli_cmp(curve_n, k) != 1)
{
vli_sub(k, k, curve_n);
}
/* tmp = k * G */
EccPoint_mult(&p, &curve_G, k, NULL);
/* r = x1 (mod n) */
vli_set(r, p.x);
if(vli_cmp(curve_n, r) != 1)
{
vli_sub(r, r, curve_n);
}
if(vli_isZero(r))
{ /* If r == 0, fail (need a different random number). */
return 0;
}
vli_modMult(s, r, p_privateKey, curve_n); /* s = r*d */
vli_modAdd(s, p_hash, s, curve_n); /* s = e + r*d */
vli_modInv(k, k, curve_n); /* k = 1 / k */
vli_modMult(s, s, k, curve_n); /* s = (e + r*d) / k */
return 1;
}
int ecdsa_verify(EccPoint *p_publicKey, uint8_t p_hash[NUM_ECC_DIGITS], uint8_t r[NUM_ECC_DIGITS], uint8_t s[NUM_ECC_DIGITS])
{
uint8_t u1[NUM_ECC_DIGITS], u2[NUM_ECC_DIGITS];
uint8_t z[NUM_ECC_DIGITS];
EccPoint l_sum;
uint8_t rx[NUM_ECC_DIGITS];
uint8_t ry[NUM_ECC_DIGITS];
uint8_t tx[NUM_ECC_DIGITS];
uint8_t ty[NUM_ECC_DIGITS];
uint8_t tz[NUM_ECC_DIGITS];
if(vli_isZero(r) || vli_isZero(s))
{ /* r, s must not be 0. */
return 0;
}
if(vli_cmp(curve_n, r) != 1 || vli_cmp(curve_n, s) != 1)
{ /* r, s must be < n. */
return 0;
}
/* Calculate u1 and u2. */
vli_modInv(z, s, curve_n); /* Z = s^-1 */
vli_modMult(u1, p_hash, z, curve_n); /* u1 = e/s */
vli_modMult(u2, r, z, curve_n); /* u2 = r/s */
/* Calculate l_sum = G + Q. */
vli_set(l_sum.x, p_publicKey->x);
vli_set(l_sum.y, p_publicKey->y);
vli_set(tx, curve_G.x);
vli_set(ty, curve_G.y);
vli_modSub(z, l_sum.x, tx, curve_p); /* Z = x2 - x1 */
XYcZ_add(tx, ty, l_sum.x, l_sum.y);
vli_modInv(z, z, curve_p); /* Z = 1/Z */
apply_z(l_sum.x, l_sum.y, z);
/* Use Shamir's trick to calculate u1*G + u2*Q */
EccPoint *l_points[4] = {NULL, &curve_G, p_publicKey, &l_sum};
uint l_numBits = max(vli_numBits(u1), vli_numBits(u2));
EccPoint *l_point = l_points[(!!vli_testBit(u1, l_numBits-1)) | ((!!vli_testBit(u2, l_numBits-1)) << 1)];
vli_set(rx, l_point->x);
vli_set(ry, l_point->y);
vli_clear(z);
z[0] = 1;
int i;
for(i = l_numBits - 2; i >= 0; --i)
{
EccPoint_double_jacobian(rx, ry, z);
int l_index = (!!vli_testBit(u1, i)) | ((!!vli_testBit(u2, i)) << 1);
EccPoint *l_point = l_points[l_index];
if(l_point)
{
vli_set(tx, l_point->x);
vli_set(ty, l_point->y);
apply_z(tx, ty, z);
vli_modSub(tz, rx, tx, curve_p); /* Z = x2 - x1 */
XYcZ_add(tx, ty, rx, ry);
vli_modMult_fast(z, z, tz);
}
}
vli_modInv(z, z, curve_p); /* Z = 1/Z */
apply_z(rx, ry, z);
/* v = x1 (mod n) */
if(vli_cmp(curve_n, rx) != 1)
{
vli_sub(rx, rx, curve_n);
}
/* Accept only if v == r. */
return (vli_cmp(rx, r) == 0);
}
#endif /* ECC_ECDSA */
void ecc_bytes2native(uint8_t p_native[NUM_ECC_DIGITS], uint8_t p_bytes[NUM_ECC_DIGITS*4])
{
unsigned i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
p_native[i] = p_bytes[NUM_ECC_DIGITS-i-1];
}
}
void ecc_native2bytes(uint8_t p_bytes[NUM_ECC_DIGITS*4], uint8_t p_native[NUM_ECC_DIGITS])
{
unsigned i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
p_bytes[NUM_ECC_DIGITS-i-1] = p_native[i];
}
}
void vli_swap(const uint8_t *src, uint8_t *dest)
{
uint8_t temp[NUM_ECC_DIGITS];
unsigned i;
for(i=0; i<NUM_ECC_DIGITS; ++i)
{
temp[i] = src[NUM_ECC_DIGITS-i-1];
}
memcpy(dest, &temp, NUM_ECC_DIGITS);
}
// generate deterministic k according to -http://tools.ietf.org/html/rfc6979
int ecdsa_derive_k(const uint8_t p_privateKey[NUM_ECC_DIGITS], uint8_t p_hash[NUM_ECC_DIGITS], uint8_t k[NUM_ECC_DIGITS])//bignum256 *secret, const uint8_t *priv_key, const uint8_t *hash)
{
uint8_t v[NUM_ECC_DIGITS], msg[3*NUM_ECC_DIGITS+1], x_h1[2*NUM_ECC_DIGITS], t[NUM_ECC_DIGITS], z2[NUM_ECC_DIGITS];
// 2.3.4:
if(vli_cmp(p_hash, curve_n) >= 0) {
vli_sub(z2, p_hash, curve_n);
} else {
memcpy(z2, p_hash, 32);
}
vli_swap(z2, z2);
// prep for d, f:
memcpy(x_h1, p_privateKey, 32);
memcpy(x_h1 + 32, z2, 32);
memset(v, 0x01, 32); // b
memset(k, 0x00, 32); // c
// d:
memcpy(msg, v, 32);
msg[32] = 0x00;
memcpy(msg + 32 + 1, x_h1, 64);
hmac_sha256(k, 32, msg, 97, k);
hmac_sha256(k, 32, v, 32, v); // e
// f:
memcpy(msg, v, 32);
msg[32] = 0x01;
memcpy(msg + 32 + 1, x_h1, 64);
hmac_sha256(k, 32, msg, 97, k);
hmac_sha256(k, 32, v, 32, v); // g
// h:
while(1) {
hmac_sha256(k, 32, v, 32, t); // h.2. (tlen always equals qlen)
vli_swap(t, t);
// h.3.:
if(!vli_isZero(t) && vli_cmp(curve_n, t) > 0) { // (0<t<q)
memcpy(k, t, 32);
return 1;
}
// else
memcpy(msg, v, 32);
msg[32] = 0x00;
hmac_sha256(k, 32, msg, 97, k);
hmac_sha256(k, 32, v, 32, v);
}
return 0;
}<file_sep>/hardened/src/transaction.c
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <asf.h>
#include <string.h>
#include "wallet.h"
#include "bitcoin.h"
#include "base64.h"
#include "ecc.h"
#include "bytestream.h"
#include "transaction.h"
/*
*
* Functions to read Armory compliant decoded transactions:
*
*/
void armtx_get_uniqueid(BYT *armtx_bp, char *uniqueid)
{
uint8_t txhash[32];
char b58txhash[45];
armtx_build_unsigned_txhash(armtx_bp, 0xFFFF, txhash); // build hash of tx with all sigscripts empty
base58_encode(txhash, 32, b58txhash);
memcpy(uniqueid, b58txhash, 8); // trim to 8 chars
*(uniqueid + 8) = '\0'; // terminate id string
}
uint16_t armtx_get_txin_cnt(BYT *armtx_bp)
{
b_seek(armtx_bp, 4 + 4 + 4); // start at 0, skip version, mbyte, locktime
return b_getvint(armtx_bp);
}
size_t armtx_get_txin_pos(BYT *armtx_bp, const uint16_t txin)
{
if(txin >= armtx_get_txin_cnt(armtx_bp)) return 0; // verify txin while moving over txin_cnt
for(uint16_t i = 0; i < txin; i++) {
b_seek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp));
}
return b_tell(armtx_bp);
}
size_t armtx_get_txin_len(BYT *armtx_bp, const uint16_t txin)
{
armtx_get_txin_pos(armtx_bp, txin);
return b_getvint(armtx_bp);
}
size_t armtx_get_txin_data_pos(BYT *armtx_bp, const uint16_t txin)
{
armtx_get_txin_len(armtx_bp, txin); // move over txin len varint
return b_tell(armtx_bp);
}
uint32_t armtx_get_txin_previndex(BYT *armtx_bp, const uint16_t txin)
{
uint32_t index;
armtx_get_txin_data_pos(armtx_bp, txin);
b_seek(armtx_bp, b_tell(armtx_bp) + 4 + 4 + 32); // skip version, mbyte, hash
b_read(armtx_bp, (uint8_t *) &index, 4); // copy index (is little endian)
return index;
}
size_t armtx_get_txin_supptx_pos(BYT *armtx_bp, const uint16_t txin)
{
armtx_get_txin_data_pos(armtx_bp, txin);
b_seek(armtx_bp, b_tell(armtx_bp) + 4 + 4 + 32 + 4); // skip version, mbyte, hash, index
return b_tell(armtx_bp);
}
size_t armtx_get_txin_supptx_len(BYT *armtx_bp, const uint16_t txin)
{
armtx_get_txin_supptx_pos(armtx_bp, txin);
return b_getvint(armtx_bp);
}
static size_t armtx_get_txin_inputvalue_rebuff(BYT *bp, size_t ofs)
{
typedef struct {
BYT *armtx_bp;
uint16_t txin;
} ctx;
ctx *supptx_ctx;
supptx_ctx = (*bp).inh_ctx;
size_t len = armtx_get_txin_supptx_len(supptx_ctx->armtx_bp, supptx_ctx->txin);
size_t btc = len - ofs < bp->res ? len - ofs : bp->res;
b_seek( supptx_ctx->armtx_bp, b_tell(supptx_ctx->armtx_bp) + ofs);
//b_rewind(bp);
//b_copy(supptx_ctx->armtx_bp, bp, btc);
b_read(supptx_ctx->armtx_bp, b_addr(bp), btc);
return btc;
}
uint64_t armtx_get_txin_inputvalue(BYT *armtx_bp, const uint16_t txin)
{
uint64_t val;
uint32_t i = armtx_get_txin_previndex(armtx_bp, txin);
BYT supptx_bp;
uint8_t supptx[400];
//void *supptx_addr;
struct {
BYT *armtx_bp;
uint16_t txin;
} supptx_ctx = {armtx_bp, txin};
//armtx_get_txin_supptx_len(armtx_bp, txin); // goto supptx (moves over the len varint)
//supptx_ctx.txin = txin;//b_tell(armtx_bp);
//supptx_ctx.armtx_bp = armtx_bp;
//ctx.armtx_bp = armtx_bp;
//ctx.ofs =
b_open(&supptx_bp, supptx, sizeof(supptx));
b_setbufin(&supptx_bp, &armtx_get_txin_inputvalue_rebuff, &supptx_ctx);
//armtx_get_txin_supptx_len(armtx_bp, txin); // goto supptx (moves over the len varint)
//b_setrewofs(armtx_bp); // limit the workspace for the tx handlers
//val = tx_get_txout_value(armtx_bp, i);
val = tx_get_txout_value(&supptx_bp, i);
//b_unsetrewofs(armtx_bp); // get back full workspace for following ops
return val;
}
size_t armtx_get_txin_sequence_pos(BYT *armtx_bp, const uint16_t txin)
{
b_seek(armtx_bp, armtx_get_txin_supptx_len(armtx_bp, txin) + b_tell(armtx_bp)); // skip supptx
b_seek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp)); // skip p2shScr
b_seek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp)); // skip contrib
b_seek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp)); // skip contribLbl
return b_tell(armtx_bp);
}
size_t armtx_get_txin_pubkey_pos(BYT *armtx_bp, const uint16_t txin)
{
armtx_get_txin_sequence_pos(armtx_bp, txin);
b_seek(armtx_bp, b_tell(armtx_bp) + 4 + 1); // skip sequence, nEntry
return b_tell(armtx_bp);
}
size_t armtx_get_txin_pubkey(BYT *armtx_bp, const uint16_t txin, uint8_t *pubkey)
{
armtx_get_txin_pubkey_pos(armtx_bp, txin); // goto txin pubkey
b_read(armtx_bp, pubkey, b_getvint(armtx_bp)); // copy pubkey to destination
return b_tell(armtx_bp); // return pointer to byte after pubkey (=siglist varint)
}
/*uint32_t armtx_get_txin_siglist_pos(BYT *armtx_bp, uint16_t txin)
{
armtx_get_txin_pubkey_pos(armtx_bp, txin); // goto txin pubkey
b_lseek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp)); // skip pubkey
return b_tell(armtx_bp);
}*/
size_t armtx_get_txout_cnt_pos(BYT *armtx_bp)
{
uint16_t last_txin = armtx_get_txin_cnt(armtx_bp) - 1; // search last txin
armtx_get_txin_data_pos(armtx_bp, last_txin); // goto last txin
b_seek(armtx_bp, b_tell(armtx_bp) + armtx_get_txin_len(armtx_bp, last_txin)); // move over last txin
return b_tell(armtx_bp);
}
uint16_t armtx_get_txout_cnt(BYT *armtx_bp)
{
armtx_get_txout_cnt_pos(armtx_bp);
return b_getvint(armtx_bp);
}
size_t armtx_get_txout_pos(BYT *armtx_bp, const uint16_t txout)
{
if(txout >= armtx_get_txout_cnt(armtx_bp)) return 0; // verify txout while moving over txout_cnt
for(uint16_t i = 0; i < txout; i++) {
b_seek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp));
}
return b_tell(armtx_bp);
}
size_t armtx_get_txout_len(BYT *armtx_bp, const uint16_t txout)
{
armtx_get_txout_pos(armtx_bp, txout);
return b_getvint(armtx_bp);
}
size_t armtx_get_txout_data_pos(BYT *armtx_bp, const uint16_t txout)
{
armtx_get_txout_len(armtx_bp, txout);
return b_tell(armtx_bp);
}
size_t armtx_get_txout_script_pos(BYT *armtx_bp, const uint16_t txout)
{
armtx_get_txout_data_pos(armtx_bp, txout);
b_seek(armtx_bp, b_tell(armtx_bp) + 4 + 4); // skip version, mbyte
return b_tell(armtx_bp);
}
size_t armtx_get_txout_script_len(BYT *armtx_bp, const uint16_t txout)
{
armtx_get_txout_script_pos(armtx_bp, txout);
return b_getvint(armtx_bp);
}
size_t armtx_get_txout_script(BYT *armtx_bp, const uint16_t txout, uint8_t *script)
{
size_t len = armtx_get_txout_script_len(armtx_bp, txout);
b_read(armtx_bp, script, len); // copy script to destination
return len;
}
size_t armtx_get_txout_value_pos(BYT *armtx_bp, const uint16_t txout)
{
armtx_get_txout_script_pos(armtx_bp, txout);
b_seek(armtx_bp, b_getvint(armtx_bp) + b_tell(armtx_bp)); // skip script
return b_tell(armtx_bp);
}
uint64_t armtx_get_txout_value(BYT *armtx_bp, const uint16_t txout)
{
uint64_t val;
armtx_get_txout_value_pos(armtx_bp, txout);
b_read(armtx_bp, (uint8_t *) &val, 8);
return val;
}
uint64_t armtx_get_total_inputvalue(BYT *armtx_bp)
{
uint64_t val = 0;
uint16_t txin_cnt = armtx_get_txin_cnt(armtx_bp);
for(uint16_t i = 0; i < txin_cnt; i++) {
val += armtx_get_txin_inputvalue(armtx_bp, i);
}
return val;
}
uint64_t armtx_get_total_outputvalue(BYT *armtx_bp)
{
uint64_t val = 0;
uint16_t txout_cnt = armtx_get_txout_cnt(armtx_bp);
for(uint16_t i = 0; i < txout_cnt; i++) {
val += armtx_get_txout_value(armtx_bp, i);
}
return val;
}
uint64_t armtx_get_fee(BYT *armtx_bp)
{
return
armtx_get_total_inputvalue(armtx_bp) -
armtx_get_total_outputvalue(armtx_bp);
}
/*
*
*Functions to read Bitcoin compliant transactions:
*
*/
uint16_t tx_get_txin_cnt(BYT *tx_bp)
{
b_seek(tx_bp, 4); // start at 0, skip ver
return b_getvint(tx_bp);
}
size_t tx_get_txin_pos(BYT *tx_bp, const uint16_t txin)
{
if(txin >= tx_get_txin_cnt(tx_bp)) return 0; // verify txin while moving over txin_cnt
for(uint16_t i = 0; i < txin; i++) {
b_seek(tx_bp, b_tell(tx_bp) + 32 + 4); // skip hash, index
b_seek(tx_bp, b_getvint(tx_bp) + b_tell(tx_bp) + 4); // skip sigscript, sequence
}
return b_tell(tx_bp);
}
size_t tx_get_txout_cnt_pos(BYT *tx_bp)
{
uint16_t last_txin = tx_get_txin_cnt(tx_bp) - 1;
tx_get_txin_pos(tx_bp, last_txin); // go to last tx_in
b_seek(tx_bp, b_tell(tx_bp) + 32 + 4); // skip hash, index
b_seek(tx_bp, b_getvint(tx_bp) + b_tell(tx_bp) + 4); // skip sigscript, sequence
return b_tell(tx_bp);
}
uint16_t tx_get_txout_cnt(BYT *tx_bp)
{
tx_get_txout_cnt_pos(tx_bp);
return b_getvint(tx_bp);
}
size_t tx_get_txout_pos(BYT *tx_bp, const uint16_t txout)
{
if(txout >= tx_get_txout_cnt(tx_bp)) return 0; // verify txout while moving over txout_cnt
for(uint16_t i = 0; i < txout; i++) {
b_seek(tx_bp, b_tell(tx_bp) + 8); // skip value
b_seek(tx_bp, b_getvint(tx_bp) + b_tell(tx_bp)); // skip pkscript
}
return b_tell(tx_bp);
}
size_t tx_get_txout_script_pos(BYT *tx_bp, const uint16_t txout)
{
tx_get_txout_pos(tx_bp, txout); // goto txout
b_seek(tx_bp, b_tell(tx_bp) + 8); // skip value
return b_tell(tx_bp);
}
uint64_t tx_get_txout_value(BYT *tx_bp, const uint16_t txout)
{
uint64_t val;
tx_get_txout_pos(tx_bp, txout); // goto txout
b_read(tx_bp, (uint8_t *) &val, 8); // copy value (is little endian)
return val;
}
/*
*
* Tx signing and support functions:
*
*/
void armtx_build_unsigned_txhash(BYT *armtx_bp, const uint16_t txin, uint8_t *txhash)
{
uint8_t buf[70];
uint8_t pubkey[65];
uint8_t script[25];
volatile static uint16_t cnt, scriptlen;
SHA256_CTX ctx;
sha256_Init(&ctx); // we push the tx data block-wise to the sha buffer to allow an unlimited tx size
BYT rawtx_bp;
b_open(&rawtx_bp, buf, sizeof(buf));
b_rewind(armtx_bp);
b_copy(armtx_bp, &rawtx_bp, 4); // copy version
cnt = armtx_get_txin_cnt(armtx_bp);
b_putvint(&rawtx_bp, cnt);
sha256_Update(&ctx, b_addr(&rawtx_bp), b_reopen(&rawtx_bp)); // push 5-13 bytes
for(uint16_t i = 0; i < cnt; i++) {
b_seek(armtx_bp, armtx_get_txin_data_pos(armtx_bp, i) + 8); // goto prev hash
b_copy(armtx_bp, &rawtx_bp, 32+4); // copy prev hash and index
if(i == txin) {
armtx_get_txin_pubkey(armtx_bp, i, pubkey);
pubkey_to_p2pkhscript(pubkey, script); // make temp sigscript for signing
b_putc(&rawtx_bp, 0x19); // write script len
b_write(&rawtx_bp, script, 25); // write temp sigscript
} else {
b_putc(&rawtx_bp, 0x00); // if this is not the input to sign, set empty sigscript
}
armtx_get_txin_sequence_pos(armtx_bp, i);
b_copy(armtx_bp, &rawtx_bp, 4);
sha256_Update(&ctx, b_addr(&rawtx_bp), b_reopen(&rawtx_bp)); // push 41-66 bytes
}
cnt = armtx_get_txout_cnt(armtx_bp);
b_putvint(&rawtx_bp, cnt);
sha256_Update(&ctx, b_addr(&rawtx_bp), b_reopen(&rawtx_bp)); // push 1-9 bytes
for(uint32_t i = 0; i < cnt; i++) {
armtx_get_txout_value_pos(armtx_bp, i);
b_copy(armtx_bp, &rawtx_bp, 8);
armtx_get_txout_script_pos(armtx_bp, i);
scriptlen = b_getvint(armtx_bp);
b_putvint(&rawtx_bp, scriptlen);
b_copy(armtx_bp, &rawtx_bp, scriptlen);
sha256_Update(&ctx, b_addr(&rawtx_bp), b_reopen(&rawtx_bp)); // push 32-34 bytes if P2SH or P2PKH
}
b_seek(armtx_bp, 8);
b_copy(armtx_bp, &rawtx_bp, 4); // write locktime
// append hash code type (SIGHASH_ALL) if this hash is built for signing:
if(txin < 0xFFFF) {
b_putc(&rawtx_bp, 0x01);
b_putc(&rawtx_bp, 0x00);
b_putc(&rawtx_bp, 0x00);
b_putc(&rawtx_bp, 0x00);
}
sha256_Update(&ctx, b_addr(&rawtx_bp), b_reopen(&rawtx_bp)); // push 4-8 bytes
sha256_Final(txhash, &ctx); // finalize
sha256_Raw(txhash, 32, txhash); // 2nd sha round because we need hash256() as output
}
uint8_t armtx_build_txin_sig(BYT *armtx_bp, const uint16_t txin, const /*WLT *wallet*/uint8_t *privkey, BYT *sig_bp)
{
uint8_t len, /*pubkey[65], privkey[32],*/ hashtosign[32];
armtx_build_unsigned_txhash(armtx_bp, txin, hashtosign);
//armtx_get_txin_pubkey(armtx_bp, txin, pubkey);
//armwl_get_privkey_from_pubkey(wallet, pubkey, privkey);
b_reopen(sig_bp);
len = build_DER_sig(hashtosign, privkey, sig_bp);
//memset(privkey, 0, 32); // clear private key memory
b_putc(sig_bp, 0x01); // SIGHASH_ALL
return ++len; // +1 because of hashtype byte; actually a varint, but p2pkh sigs will not exceed 0x49 bytes max
}
uint8_t build_DER_sig(const uint8_t *hashtosign, const uint8_t *privkey, BYT *sig_bp)
{
uint8_t h[32], p[32], k[32], r[32], s[32];
uint8_t len = 0x44; // min sequence length
//static volatile uint8_t veri = 0;
vli_swap(hashtosign, h); // need hash to sign as little endian for vli arithmetics
vli_swap(privkey, p); // same with private key
ecdsa_derive_k(privkey, h, k); // hash to sign used as vli, private key not
ecdsa_sign(r, s, p, k, h);
//veri = ecdsa_verify(&pubkey, h, r, s);
memset(p, 0, 32); // clear private key memory
vli_swap(r, r); // r and s need to be represented..
vli_swap(s, s); // ..as big endian in the sig
if(r[0] & 0x80) len++; // most left bit == 1
if(s[0] & 0x80) len++; // most left bit == 1
b_putc(sig_bp, 0x30); // sequence identifier
b_putc(sig_bp, len); // sequence length
b_putc(sig_bp, 0x02); // int identifier
if(r[0] & 0x80) { // most left bit == 1
b_putc(sig_bp, 0x21); // r length
b_putc(sig_bp, 0x00);
} else {
b_putc(sig_bp, 0x20); // r length
}
b_write(sig_bp, (const uint8_t *) &r, 32); // write r
b_putc(sig_bp, 0x02); // int identifier
if(s[0] & 0x80) { // most left bit == 1
b_putc(sig_bp, 0x21); // s length
b_putc(sig_bp, 0x00);
} else {
b_putc(sig_bp, 0x20); // s length
}
b_write(sig_bp, (const uint8_t *) &s, 32); // write s
return len + 2; // +2 to include sequence byte (0x30) and the length byte itself
}
uint8_t armtx_insert_sigs(BYT *u_armtx_bp, BYT *s_armtx_bp, void *pub2privkey_wrp)
{
size_t txin_cnt;
uint8_t pubkey[65], privkey[32];
char q[21];
uint8_t (*pub2privkey_wrp_ptr)(const uint8_t *pubkey, uint8_t *privkey);
pub2privkey_wrp_ptr = pub2privkey_wrp;
BYT sig_bp;
uint8_t sigdata[0x49]; // max. P2PKH sig len is 73 (0x49) bytes
b_open(&sig_bp, sigdata, sizeof(sigdata)); // open sigdata buffer
// copy first 12 bytes:
b_rewind(u_armtx_bp);
b_copy(u_armtx_bp, s_armtx_bp, 12);
txin_cnt = armtx_get_txin_cnt(u_armtx_bp);
b_putvint(s_armtx_bp, txin_cnt); // push txin cnt vint to file
for(uint16_t i = 0; i < txin_cnt; i++) {
#ifdef CONF_SSD1306_H_INCLUDED
gfx_mono_draw_filled_rect(0, 11, 128, 7, 0);
sprintf(q, "Signing TxIn %u/%u...", i+1, txin_cnt);
gfx_mono_draw_string(q, 0, 11, &sysfont);
#endif
// get the corresponding pubkey for txin and compute privkey; stop if unsuccessful:
armtx_get_txin_pubkey(u_armtx_bp, i, pubkey);
if(!pub2privkey_wrp_ptr(pubkey, privkey)) {
memset(privkey, 0, 32);
return 0;
}
// create vint with new length of txin (old len + sig len) and push to file.
// This works without extra bytes because the siglen byte is set as 0x00 before and max 0x49 after.
// The sig itself is meanwhile built and kept in sig_bp
b_putvint(s_armtx_bp, armtx_get_txin_len(u_armtx_bp, i) + armtx_build_txin_sig(u_armtx_bp, i, privkey, &sig_bp));
memset(privkey, 0, 32); // erase privkey
// copy txin data from version to pubkey. we cheat a bit here and expect just 2 more bytes to follow (2*0x00 for siglist len and loclist len).
// by getting the txin length as an arg for b_copy we also set the pointer of armtx_bp to the beginning of the txin data for the copying process
b_copy(u_armtx_bp, s_armtx_bp, armtx_get_txin_len(u_armtx_bp, i) - 2);
b_putvint(s_armtx_bp, b_size(&sig_bp)); // make vint from sig len and push to file
b_write(s_armtx_bp, b_addr(&sig_bp), b_size(&sig_bp)); // push sig to file
b_putvint(s_armtx_bp, 0x00); // make loclist and push to file
}
// copy outputs:
b_copy(u_armtx_bp, s_armtx_bp, b_srcsize(u_armtx_bp) - armtx_get_txout_cnt_pos(u_armtx_bp)); // trick like with txin data above
b_flush(s_armtx_bp); // push what's left to the file
return 1;
}
/*
*
* Tx file operation functions:
*
*/
void txfile_build_signed_file_snkwrp(BYT *bp)
{
char buff_b64[64+1];
size_t s = bp->size;
b_rewind(bp);
while(s > 48) {
base64enc(buff_b64, b_posaddr(bp), 48);
f_puts(buff_b64, bp->outh_ctx);
f_puts("\r\n", bp->outh_ctx);
b_seek(bp, b_tell(bp) + 48);
s -= 48;
}
base64enc(buff_b64, b_posaddr(bp), s);
f_puts(buff_b64, bp->outh_ctx);
f_puts("\r\n", bp->outh_ctx);
}
uint8_t txfile_build_signed_file_pub2privkeywrp(const uint8_t *pubkey, uint8_t *privkey)
{
char b58uniqueid[10];
char wlt_filename[100];
extern WLT ui_wallet;
base58_encode(ui_wallet.uniqueid, 6, b58uniqueid);
if(!scan_for_file(".watchonly.wallet", b58uniqueid, wlt_filename)) return 0;
if(!armwlt_get_privkey_from_pubkey(&ui_wallet, wlt_filename, pubkey, privkey)) return 0;
return 1;
}
uint8_t txfile_build_signed_file(BYT *u_armtx_bp)
{
FIL fp_tx;
char fn[100], uniqueid[9];
BYT s_armtx_bp;
uint8_t s_armtx_buff[48*4]; // must be multiple of 3 (for base64) and should be multiple of 48 because of line break in Armory tx files after 64 bytes
// open signed tx buffer with outgoing handler:
b_open(&s_armtx_bp, s_armtx_buff, sizeof(s_armtx_buff));
b_setbufout(&s_armtx_bp, &txfile_build_signed_file_snkwrp, &fp_tx);
// compute Armory's unique tx id:
armtx_get_uniqueid(u_armtx_bp, uniqueid);
sprintf(fn, "armory_%s.hardened.SIGNED.tx", uniqueid);
f_open(&fp_tx, fn, FA_READ | FA_WRITE | FA_CREATE_ALWAYS); // create signed tx file
// signed tx file header:
f_puts("=====TXSIGCOLLECT-", &fp_tx);
f_puts(uniqueid, &fp_tx);
f_puts("======================================\r\n", &fp_tx);
if(!armtx_insert_sigs(u_armtx_bp, &s_armtx_bp, &txfile_build_signed_file_pub2privkeywrp)){
f_close(&fp_tx);
f_unlink(fn);
return 0;
}
f_puts("================================================================\r\n", &fp_tx); // tx file footer
f_close(&fp_tx);
return 1;
}
size_t txfile_fetch_unsigned_file_srcwrp(BYT *bp, size_t ofs)
{
FIL fp;
UINT br;
//memcpy(bp->bs, bp->inh_ctx + ofs, bp->res);
//size_t len = armtx_get_txin_supptx_len(supptx_ctx->armtx_bp, supptx_ctx->txin);
size_t btc = bp->srclen - ofs < bp->res ? bp->srclen - ofs : bp->res;
f_open(&fp, "workspace.bin.temp", FA_READ);
f_lseek(&fp, ofs);
f_read(&fp, b_addr(bp), (UINT) btc, &br);
//size_t rem = ui_test_bp.size - ofs;
//bp->srclen = ui_test_bp.size;
//if(bp->res > rem) {
// memcpy(bp->bs, ui_test_bp.bs + ofs, rem);
// return rem;
//}
//memcpy(bp->bs, ui_test_bp.bs + ofs, bp->res);
//return bp->res;
f_close(&fp);
return (size_t) br;
}
uint8_t txfile_fetch_unsigned_file(char *fn, char *uniqueid, BYT *armtx_bp)
{
uint8_t oversize = 0;
UINT br;
FIL fp_b64, fp_bin;
//char fn_bin[100];
char armtx_rawbuff[100];//[67];
uint8_t armtx_binbuff[100];//[46];
b_reopen(armtx_bp);
f_open(&fp_b64, fn, FA_READ);
if(f_size(&fp_b64)*3/4-2 > b_ressize(armtx_bp)) { // taking whole file size to safely avoid buffer overflow
oversize = 1;
//sprintf(fn_bin, "%s.bin.temp", fn);
//strcpy(fn, fn_bin);
f_open(&fp_bin, "workspace.bin.temp", FA_READ | FA_WRITE | FA_CREATE_ALWAYS);
}
f_gets((TCHAR *) armtx_rawbuff, 67, &fp_b64);
//memset(uniqueid, 0, 9);
//memcpy(uniqueid, armtx_rawbuff + 18, 8);
while(!f_eof(&fp_b64)) {
f_gets((TCHAR *) armtx_rawbuff, 67, &fp_b64);
if(armtx_rawbuff[0] != '=') {
base64dec(armtx_binbuff, armtx_rawbuff, 0);
if(oversize) {
f_write(&fp_bin, armtx_binbuff, base64_binlength(armtx_rawbuff, 0), &br);
} else {
b_write(armtx_bp, armtx_binbuff, base64_binlength(armtx_rawbuff, 0));
}
}
}
f_close(&fp_b64);
if(oversize) {
armtx_bp->srclen = f_size(&fp_bin);
f_close(&fp_bin);
b_setbufin(armtx_bp, &txfile_fetch_unsigned_file_srcwrp, NULL);
}
armtx_get_uniqueid(armtx_bp, uniqueid);
return 1;
}<file_sep>/README-Usage.md
# armory-hardened
Armory DIY Hardware Wallet - User Guide (usage; installation to follow)
## Warning
* Keep in mind this thing is totally beta.
* The device is only tested under Windows (8.1) and with Armory 0.92.3
* The device is not yet access-restrictable. Keep itas physically secure as a paper wallet.
* Always keep a backup of the root keys as before. The device is meant to make your keys secure against the internet, but not yet safe against physical theft/damage/weird beta behavior.
But: The device can do nothing wrong with your money or transactions. The random number k needed for signing is generated securely and deterministically according to RFC6979. The worst thing to happen is the signing to fail due to a whatever bug, but then the transaction is just invalid and will not be accepted by Armory. It will not reveal your keys.
##Interface
The device features 4 buttons:
* 2 mechanical buttons labeled SW0 and SW1
* 2 capacitive “Q-Touch” buttons labeled QTB0 and QTB1
The QTB buttons are used for browsing menus and info (up/down). The display shows “QTB” in the center bottom if available, with “<” and/or “>” to indicate whether you can scroll up with QTB0 and down with QTB1.
The SW buttons are used for confirmation/canceling actions or to go back and forth in menu structures. The current function will be shown in the right and/or left bottom as “SW0:” and “SW1:” with a character following, indicating the assigned action:
* S: Select
* B: Back
* Y: Yes
* N: No
* R: Refresh
##Start up
Be sure to insert an SD card. Connect to the computer and make sure it gets acknowledged as a removable drive. Make sure the card is formatted with FAT (FAT16).
The device starts up with no wallet set up, thus telling you “Wallet: None”.
With SW1 you go to the wallet setup menu to proceed with setting up the first wallet.
If you have at least one wallet set up, the home screen will show you the currently active wallet and the option to open the latest unsigned tx file (SW0) as well as to go to the main menu (SW1).
##Wallet setup
In the main menu, go to “Set up wallet” by scrolling down with QTB1 and select it with SW1:S. If there is no wallet set up yet, just press SW1 on the home screen.
There are four options yet:
###1. Create on-chip
The device will create a new wallet with root key data gathered from two floating ADC pins. For 256 samples the LSB and L+1SB of every sample are XOR’ed and put together as a key. True randomness is not proven in any way!
If you use this feature, it is advised to write down the root key (see “Wallet export”) as a backup and test its integrity via “Shuffled root key file”.
###2. Plain wallet file
Using this function, the device will search for the file ending with “.decrypt.wallet” on the SD card with the most recent modification date.
The file has to be a standard decrypted Armory wallet file, from which the root key will be extracted.
###3. Plain root key file
The device will search for the file containing the string “rootkey” anywhere in its name (e.g. just rootkey.txt) on the SD card with the most recent modification date.
The file has to be an ASCII text file and must contain the 2 times 9 words from a normal Armory paper backup. The device will ignore all spaces and line breaks (\r and \n).
###4. Shuffled root key file
Works the same way as with a plain root key file, but with obfuscated characters. Use “Show shuffle code” in the main menu (or on the home screen if there is no wallet yet).
The available Armory conform charset (asdfghjkwertuion) will be randomly replaced with the hex charset (0123456789ABCDEF, uppercase!) in ASCII.
Example: If your first backup word is “krfh” and the device displays k=6, r=8, f=7, h=C among the 16 characters, type in “687C” as the first word in your text file. The device will swap that back internally according to the current shuffle map, but no malware on your computer will get to know your plain key.
After every successful import, the code will be automatically re-shuffled. You can always trigger that yourself with pressing SW1:R in the “Shuffle code” display.
###Import confirmation
After finding a valid file, the device will compute and show the corresponding Armory wallet ID and ask you whether you want to import or not. Confirm with SW1:Y or abort with SW0:N.
A freshly set up wallet will automatically be set as the active one. Look at “Transaction signing” how to switch between multiple wallets.
###Note for imports via files
After a successful import, the file on the card will be completely overwritten with “-” (ASCII 0x2D) and then dropped from FAT. You will get an error message on the screen if secure erasing is unsuccessful. If the import fails itself (e.g. invalid file content), the file will persist and needs to be deleted manually.
###Finishing the setup
If the imported wallet is not already existing in Armory on the computer, you can use for example the watching-only data file export function (see “Wallet Export”).
After the wallet was set up in Armory itself, you have to permanently provide a watching-only wallet file on the SD card for the device to look up public keys. Do this by opening the wallet in Armory and click “Export Watching-Only Copy” -> “Export Watching-Only Wallet File” and save the file to the device’s SD card. It has to contain the wallet ID as well as the ending “.watchonly.wallet” in the filename.
Now you are set to use this wallet with Armory and Armory Hardened!
##Wallet Erasing
You have to select the wallet via “Select Wallet” first before you can erase it.
Go to “Erase wallet” in the main menu and select it with SW1:S. The device will show you the Armory wallet ID of the wallet going to be erased and ask for your confirmation. Confirm with SW1:Y or abort with SW0:N.
After erasing, the remaining wallet with the lowest internal slot number will be set as active. If there is no other wallet left, you will end with the “Wallet: None” home screen.
##Wallet Export
You have to select the wallet via “Select Wallet” first before you can export its data.
To make backups and to conveniently import watch-only wallets into Armory, the device offers few export modes:
###Watchonly data file
This will write an Armory-compatible watching-only wallet file named “armory_{walletid}.hardened.rootpubkey” to the SD card. This file does not contain any security-sensitive data.
You can import it to Armory via “Import or Restore Wallet” -> “Import watching-only wallet data” -> “Continue” -> “Load From Text File”.
###Rootkey file
This will write an ASCII text file named “armory_{walletid}.decryt.rootkey.txt” to the SD card. It contains the full, plain wallet seed as if you made a single-sheet paper backup in Armory.
You can import it to Armory via “Import or Restore Wallet” -> “Single-Sheet Backup (printed)” -> “Continue” and copy the file content into the shown input fields.
Be careful using that function on an unsecure computer!
###Show rootkey
Shows the plain wallet seed on the screen instead of writing it to a file. Use QTB0/1 to scroll through the 6 pages needed to display it.
##Transaction signing
Before you can sign a transaction, you have to set the wallet this tx is coming from as active on the device.
If it is not already, do so by going to the main menu and select “Select wallet”. This will show you all set-up wallet IDs ordered by the internal storage order, scrollable with QTB0/1. Select the desired wallet with SW1:S and wait for the wallet parameters to be computed from the root key on-the-fly.
You will then be brought back to the home screen, displaying the newly selected wallet. This selection is stored permanently, so unplugging the device will not reset it.
Pressing SW0 on the home screen will search the SD card for the file with the most recent modification date containing “.unsigned.tx” in the filename.
You will see the Armory transaction ID, which you should compare to the one shown by Armory to be sure the file was not modified in between.
Use QTB0 to scroll down and see the number of inputs and total input value, the fee, and all outputs with amount and recipient address (well, the first 18 characters due to space restrictions on the screen).
All amounts get rounded to the next micro-BTC, milli-BTC or BTC depending on the order of magnitude the amount is in.
You then can abort with SW0:N or confirm with SW1:Y. After confirmation, the screen will show you the progress as the number of inputs already signed.
The signed transaction is written to the SD card as a new file named “armory_{txID}.hardened.SIGNED.tx”. Load it with Armory and broadcast.
The old, unsigned file gets deleted but not erased.
<file_sep>/hardened/src/base64.c
/* base64_dec.c */
/*
* This file is part of the AVR-Crypto-Lib.
* Copyright (C) 2006, 2007, 2008 <NAME> (<EMAIL>)
*
* 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 3 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, see <http://www.gnu.org/licenses/>.
*/
/**
* base64 decoder (RFC3548)
* Author: <NAME>
* License: GPLv3
*
*
*/
#include <stdint.h>
#include "base64.h"
//#include "cli.h"
#if 1
#include <avr/pgmspace.h>
const char base64_alphabet[64] PROGMEM = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P',
'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X',
'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f',
'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u', 'v',
'w', 'x', 'y', 'z', '0', '1', '2', '3',
'4', '5', '6', '7', '8', '9', '+', '/' };
static
char bit6toAscii(uint8_t a){
a &= (uint8_t)0x3F;
return pgm_read_byte(base64_alphabet+a);
}
#else
static
char bit6toAscii(uint8_t a){
a &= (uint8_t)0x3F;
if(a<=25){
return a+'A';
} else {
if(a<=51){
return a-26+'a';
} else {
if(a<=61){
return a-52+'0';
} else {
if(a==62){
return '+';
} else {
return '/'; /* a == 63 */
}
}
}
}
}
#endif
void base64enc(char *dest,const void *src, uint16_t length){
uint16_t i,j;
uint8_t a[4];
for(i=0; i<length/3; ++i){
a[0]= (((uint8_t*)src)[i*3+0])>>2;
a[1]= (((((uint8_t*)src)[i*3+0])<<4) | ((((uint8_t*)src)[i*3+1])>>4)) & 0x3F;
a[2]= (((((uint8_t*)src)[i*3+1])<<2) | ((((uint8_t*)src)[i*3+2])>>6)) & 0x3F;
a[3]= (((uint8_t*)src)[i*3+2]) & 0x3F;
for(j=0; j<4; ++j){
*dest++=bit6toAscii(a[j]);
}
}
/* now we do the rest */
switch(length%3){
case 0:
break;
case 1:
a[0]=(((uint8_t*)src)[i*3+0])>>2;
a[1]=((((uint8_t*)src)[i*3+0])<<4)&0x3F;
*dest++ = bit6toAscii(a[0]);
*dest++ = bit6toAscii(a[1]);
*dest++ = '=';
*dest++ = '=';
break;
case 2:
a[0]= (((uint8_t*)src)[i*3+0])>>2;
a[1]= (((((uint8_t*)src)[i*3+0])<<4) | ((((uint8_t*)src)[i*3+1])>>4)) & 0x3F;
a[2]= ((((uint8_t*)src)[i*3+1])<<2) & 0x3F;
*dest++ = bit6toAscii(a[0]);
*dest++ = bit6toAscii(a[1]);
*dest++ = bit6toAscii(a[2]);
*dest++ = '=';
break;
default: /* this will not happen! */
break;
}
/* finalize: */
*dest='\0';
}
/*
#define USE_GCC_EXTENSION
*/
#if 1
#ifdef USE_GCC_EXTENSION
static
int ascii2bit6(char a){
switch(a){
case 'A'...'Z':
return a-'A';
case 'a'...'z':
return a-'a'+26;
case '0'...'9':
return a-'0'+52;
case '+':
case '-':
return 62;
case '/':
case '_':
return 63;
default:
return -1;
}
}
#else
static
uint8_t ascii2bit6(char a){
int r;
switch(a>>4){
case 0x5:
case 0x4:
r=a-'A';
if(r<0 || r>25){
return -1;
} else {
return r;
}
case 0x7:
case 0x6:
r=a-'a';
if(r<0 || r>25){
return -1;
} else {
return r+26;
}
break;
case 0x3:
if(a>'9')
return -1;
return a-'0'+52;
default:
break;
}
switch (a){
case '+':
case '-':
return 62;
case '/':
case '_':
return 63;
default:
return 0xff;
}
}
#endif
#else
static
uint8_t ascii2bit6(uint8_t a){
if(a>='A' && a<='Z'){
return a-'A';
} else {
if(a>='a' && a<= 'z'){
return a-'a'+26;
} else {
if(a>='0' && a<='9'){
return a-'0'+52;
} else {
if(a=='+' || a=='-'){
return 62;
} else {
if(a=='/' || a=='_'){
return 63;
} else {
return 0xff;
}
}
}
}
}
}
#endif
int base64_binlength(char *str, uint8_t strict){
int l=0;
uint8_t term=0;
for(;;){
if(*str=='\0')
break;
if(*str=='\n' || *str=='\r'){
str++;
continue;
}
if(*str=='='){
term++;
str++;
if(term==2){
break;
}
continue;
}
if(term)
return -1;
if(ascii2bit6(*str)==-1){
if(strict)
return -1;
} else {
l++;
}
str++;
}
switch(term){
case 0:
if(l%4!=0)
return -1;
return l/4*3;
case 1:
if(l%4!=3)
return -1;
return (l+1)/4*3-1;
case 2:
if(l%4!=2)
return -1;
return (l+2)/4*3-2;
default:
return -1;
}
}
/*
|543210543210543210543210|
|765432107654321076543210|
. . . .
|54321054|32105432|10543210|
|76543210|76543210|76543210|
*/
int base64dec(void *dest, const char *b64str, uint8_t strict){
uint8_t buffer[4];
uint8_t idx=0;
uint8_t term=0;
for(;;){
// cli_putstr_P(PSTR("\r\n DBG: got 0x"));
// cli_hexdump(b64str, 1);
buffer[idx]= ascii2bit6(*b64str);
// cli_putstr_P(PSTR(" --> 0x"));
// cli_hexdump(buffer+idx, 1);
if(buffer[idx]==0xFF){
if(*b64str=='='){
term++;
b64str++;
if(term==2)
goto finalize; /* definitly the end */
}else{
if(*b64str == '\0'){
goto finalize; /* definitly the end */
}else{
if(*b64str == '\r' || *b64str == '\n' || !(strict)){
b64str++; /* charcters that we simply ignore */
}else{
return -1;
}
}
}
}else{
if(term)
return -1; /* this happens if we get a '=' in the stream */
idx++;
b64str++;
}
if(idx==4){
((uint8_t*)dest)[0] = buffer[0]<<2 | buffer[1]>>4;
((uint8_t*)dest)[1] = buffer[1]<<4 | buffer[2]>>2;
((uint8_t*)dest)[2] = buffer[2]<<6 | buffer[3];
dest = (uint8_t*)dest +3;
idx=0;
}
}
finalize:
/* the final touch */
if(idx==0)
return 0;
if(term==1){
((uint8_t*)dest)[0] = buffer[0]<<2 | buffer[1]>>4;
((uint8_t*)dest)[1] = buffer[1]<<4 | buffer[2]>>2;
return 0;
}
if(term==2){
((uint8_t*)dest)[0] = buffer[0]<<2 | buffer[1]>>4;
return 0;
}
return -1;
}
<file_sep>/hardened/src/base58.h
// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Port 2014 by <NAME>
#ifndef BASE58_H_
#define BASE58_H_
#include <string.h>
#include <stdint.h>
void base58_encode(const uint8_t *src, const uint16_t len, char *dest);
#endif /* BASE58_H_ */<file_sep>/hardened/src/bitcoin.h
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef BITCOIN_H_
#define BITCOIN_H_
#include <stdint.h>
#include <string.h>
#include "ecc.h"
#include "sha2.h"
#include "ripemd160.h"
#include "base58.h"
void hex_init(const char *str, uint8_t *dest);
void hash256(const uint8_t* data, size_t len, uint8_t *digest);
void hash160(const uint8_t *data, size_t len, uint8_t *digest);
void compute_checksum(const uint8_t *data, size_t len, uint8_t checksum[4]);
uint8_t verify_checksum(const uint8_t *data, size_t len, const uint8_t checksum[4]);
uint8_t fix_verify_checksum(uint8_t *data, const size_t len, uint8_t checksum[4]);
void privkey_to_pubkey(uint8_t *, uint8_t *);
void privkey_to_pubkey_compressed(uint8_t *, uint8_t *);
void pubkey_to_pubkeyhash(const uint8_t *pubkey, uint8_t *pubkeyhash);
void privkey_to_pubkeyhash(uint8_t *privkey, uint8_t *pubkeyhash);
void pubkeyhash_to_addr(const uint8_t *pubkeyhash, const uint8_t version, char *addr);
void pubkey_to_addr(const uint8_t *pubkey, const uint8_t version, char *addr);
void pkscript_to_addr(const uint8_t *pkscript, const size_t len, char *addr);
void pkscript_to_pubkeyhash(const uint8_t *pkscript, const size_t len, uint8_t *pubkeyhash);
void pubkey_to_p2pkhscript(uint8_t *pubkey, uint8_t *pkscript);
#endif /* BITCOIN_H_ */<file_sep>/hardened/src/wallet.c
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include <avr/eeprom.h>
#include "wallet.h"
void armwlt_make_rootkey_file(const uint8_t *rootkey)
{
return;
FIL fp;
char easy16buff[45];
//sprintf(filename, "armory_.decryt.rootkey.txt", b58uniqueid);
f_open(&fp, "armory_.decryt.rootkey.txt", FA_WRITE | FA_CREATE_ALWAYS);
makeSixteenBytesEasy(rootkey, easy16buff);
f_puts(easy16buff, &fp);
f_puts("\r\n", &fp);
makeSixteenBytesEasy(rootkey + 16, easy16buff);
f_puts(easy16buff, &fp);
f_close(&fp);
}
uint8_t armwlt_build_rootpubkey_file(const WLT *wallet)
{
char b58uniqueid[10];
char filename[50];
FIL fp;
uint8_t rootid[20];
char easy16buff[45];
// Wallet public data backup rootid is non-compatible to normal 16 easy bytes, so we do it manually:
rootid[0] = 0x01; // version
rootid[0] |= (wallet->rootpubkey[64] & 0x01) ? 0x80 : 0x00; // pubkey y-coord sign encoding
memcpy(&rootid[1], wallet->uniqueid, 6); // wallet uniqueid
compute_checksum(rootid, 7, rootid + 7); // checksum of first byte and uniqueid
binary_to_easyType16(rootid, 9, easy16buff); // make 9 easy bytes rootid
base58_encode(wallet->uniqueid, 6, b58uniqueid);
sprintf(filename, "armory_%s.hardened.rootpubkey", b58uniqueid);
f_open(&fp, filename, FA_WRITE | FA_CREATE_ALWAYS); // always create new
// push "1" (Armory wants this) and rootid:
f_puts("1\n", &fp);
f_puts(easy16buff, &fp);
f_puts("\n", &fp);
// push pubkey x-coord:
makeSixteenBytesEasy(wallet->rootpubkey + 1, easy16buff);
f_puts(easy16buff, &fp);
f_puts("\n", &fp);
makeSixteenBytesEasy(wallet->rootpubkey + 17, easy16buff);
f_puts(easy16buff, &fp);
f_puts("\n", &fp);
// push chaincode:
makeSixteenBytesEasy(wallet->chaincode, easy16buff);
f_puts(easy16buff, &fp);
f_puts("\n", &fp);
makeSixteenBytesEasy(wallet->chaincode + 16, easy16buff);
f_puts(easy16buff, &fp);
f_close(&fp);
return 1;
}
uint8_t armwlt_eep_get_actwlt(void)
{
uint8_t actwlt = eeprom_read_byte(EEP_ACTWLT);
if(actwlt == 0xFF) return 0;
return actwlt;
}
uint8_t armwlt_eep_get_wltnum(void)
{
uint8_t wltnum = eeprom_read_byte(EEP_WLTNUM);
if(wltnum == 0xFF) return 0;
return wltnum;
}
uint8_t armwlt_eep_get_next_wltid(uint8_t wltid)
{
//uint16_t i = 0;
//uint16_t wltid = 0;
WLT_EEP eepwlt;
//uint8_t wltnum = eeprom_read_byte(EEP_WLTNUM);
if(!wltid || wltid > EEP_WLTNUMMAX || !armwlt_eep_get_wltnum()) return 0;
do
{
eeprom_read_block(&eepwlt, armwlt_get_eep_walletpos(wltid), sizeof(WLT_EEP));
if(eepwlt.set == WLT_EEP_SETBYTE) return wltid;
} while (++wltid < EEP_WLTNUMMAX);
return armwlt_eep_get_next_wltid(1);
}
uint8_t armwlt_eep_get_prev_slot(uint8_t slot)
{
//uint16_t i = 0;
//uint16_t wltid = 0;
WLT_EEP eepwlt;
//uint8_t wltnum = eeprom_read_byte(EEP_WLTNUM);
if(!slot || slot > EEP_WLTNUMMAX || !armwlt_eep_get_wltnum()) return 0;
do
{
eeprom_read_block(&eepwlt, armwlt_get_eep_walletpos(slot), sizeof(WLT_EEP));
if(eepwlt.set == WLT_EEP_SETBYTE) return slot;
} while (--slot < EEP_WLTNUMMAX);
return 0;//armwlt_eep_get_next_wltid(1);
}
uint8_t armwlt_eep_get_next_free_wltid(uint8_t wltid)
{
//uint16_t i = 0;
//uint16_t wltid = 0;
WLT_EEP eepwlt;
//uint16_t wltcnt = eeprom_read_byte(EEP_WLTNUM);
if(!wltid || wltid >= EEP_WLTNUMMAX || armwlt_eep_get_wltnum() >= EEP_WLTNUMMAX) return 0;
do
{
eeprom_read_block(&eepwlt, armwlt_get_eep_walletpos(wltid), sizeof(WLT_EEP));
if(eepwlt.set != WLT_EEP_SETBYTE) return wltid;
} while (++wltid < EEP_WLTNUMMAX);
return armwlt_eep_get_next_free_wltid(1);
}
uint8_t armwlt_eep_create_wallet(const uint8_t *rootkey, const uint8_t *uniqueid, const uint8_t setact)
{
WLT_EEP eepwlt, eepwlt_chk;
uint8_t wltid = armwlt_eep_get_next_free_wltid(1);
uint8_t wltnum = armwlt_eep_get_wltnum();
if(wltnum >= EEP_WLTNUMMAX) return 0;
compute_checksum(rootkey, 32, eepwlt.privkey_cs);
//compute_checksum(uniqueid, 6, eepwlt.uniqueid_cs);
memcpy(eepwlt.privkey, rootkey, 32);
memcpy(eepwlt.uniqueid, uniqueid, 6);
eepwlt.set = WLT_EEP_SETBYTE;
eepwlt.flags = 0;
eeprom_update_block(&eepwlt, armwlt_get_eep_walletpos(wltid), sizeof(WLT_EEP));
eeprom_read_block(&eepwlt_chk, armwlt_get_eep_walletpos(wltid), sizeof(WLT_EEP));
// we do not do more verifying than checking eeprom content against data prepared to store before;
// as long as we did not create the rootkey on-chip (not supported yet), previous corruption will not affect safety
if(memcmp(&eepwlt, &eepwlt_chk, sizeof(WLT_EEP))) {
memset(&eepwlt, 0, sizeof(WLT_EEP));
memset(&eepwlt_chk, 0, sizeof(WLT_EEP));
return 0; // eeprom corrupted
}
eeprom_update_byte(EEP_WLTNUM, wltnum+1);
if(setact) {
eeprom_update_byte(EEP_ACTWLT, wltid);
}
memset(&eepwlt, 0, sizeof(WLT_EEP));
memset(&eepwlt_chk, 0, sizeof(WLT_EEP));
return wltid;
}
uint8_t armwlt_eep_erase_wallet(const uint8_t wltid)
{
WLT_EEP eepwlt, eepwlt_chk;
if(!wltid) return 0;
memset(&eepwlt, 0xFF, sizeof(WLT_EEP));
eeprom_update_block(&eepwlt, armwlt_get_eep_walletpos(wltid), sizeof(WLT_EEP));
eeprom_read_block(&eepwlt_chk, armwlt_get_eep_walletpos(wltid), sizeof(WLT_EEP));
if(memcmp(&eepwlt, &eepwlt_chk, sizeof(WLT_EEP))) {
memset(&eepwlt_chk, 0, sizeof(WLT_EEP));
return 0; // eeprom corrupted
}
eeprom_update_byte(EEP_WLTNUM, armwlt_eep_get_wltnum()-1);
eeprom_update_byte(EEP_ACTWLT, armwlt_eep_get_next_wltid(wltid));
return 1;
}
uint8_t armwlt_eep_read_wallet(WLT *wallet)
{
WLT_EEP eepwlt;
uint8_t cs_verify;
eeprom_busy_wait();
eeprom_read_block(&eepwlt, armwlt_get_eep_walletpos(wallet->id), sizeof(WLT_EEP));
//if(!(cs_verify = fix_verify_checksum(eepwlt.uniqueid, 6, eepwlt.uniqueid_cs))) return 0;
//if(cs_verify == 2) {
// eeprom_busy_wait();
// eeprom_update_block(&eepwlt, armwlt_get_eep_walletpos(wallet->id), sizeof(WLT_EEP));
//}
if(!(cs_verify = fix_verify_checksum(eepwlt.privkey, 32, eepwlt.privkey_cs))) return 0;
if(cs_verify == 2) {
eeprom_busy_wait();
eeprom_update_block(&eepwlt, armwlt_get_eep_walletpos(wallet->id), sizeof(WLT_EEP));
}
memcpy(wallet->uniqueid, eepwlt.uniqueid, 6);
memcpy(wallet->rootkey, eepwlt.privkey, 32);
memset(&eepwlt, 0, sizeof(WLT_EEP));
return 1;
}
uint8_t armwlt_create_instance(WLT *wallet, const uint8_t options)
{
derive_chaincode_from_rootkey(wallet->rootkey, wallet->chaincode);
privkey_to_pubkey(wallet->rootkey, wallet->rootpubkey);
pubkey_to_pubkeyhash(wallet->rootpubkey, wallet->rootpubkeyhash);
if(options & (WLT_COMPUTE_FIRST_ADDR | WLT_COMPUTE_UNIQUEID)) {
compute_chained_privkey(wallet->rootkey, wallet->chaincode, wallet->rootpubkey, wallet->addrprivkey);
privkey_to_pubkey(wallet->addrprivkey, wallet->addrpubkey);
pubkey_to_pubkeyhash(wallet->addrpubkey, wallet->addrpubkeyhash);
if(options & WLT_COMPUTE_UNIQUEID) {
wallet->uniqueid[0] = wallet->addrpubkeyhash[4];
wallet->uniqueid[1] = wallet->addrpubkeyhash[3];
wallet->uniqueid[2] = wallet->addrpubkeyhash[2];
wallet->uniqueid[3] = wallet->addrpubkeyhash[1];
wallet->uniqueid[4] = wallet->addrpubkeyhash[0];
wallet->uniqueid[5] = 0x00;
}
if(options & WLT_DELETE_ADDRPRIVKEY) {
memset(wallet->addrprivkey, 0, 32);
}
}
if(options & WLT_DELETE_ROOTKEY) {
memset(wallet->rootkey, 0, 32);
}
return 1;
}
uint8_t armwlt_read_wallet_file(const char *filename, uint8_t *rootkey)
{
FIL fp;
uint8_t buff[36];
UINT br;
if(f_open(&fp, filename, FA_READ)) return 0;
f_lseek(&fp, 954);
if(f_read(&fp, buff, 36, &br)) return 0;
f_close(&fp);
if(!verify_checksum(buff, 32, buff + 32)) {
memset(buff, 0, 36);
return 0;
}
memcpy(rootkey, buff, 32);
memset(buff, 0, 36);
return 1;
}
uint8_t armwlt_read_rootkey_file(const char *filename, uint8_t *rootkey)
{
FIL fp;
char easy16buff[100];
UINT br;
if(f_open(&fp, filename, FA_READ)) return 0;
if(f_read(&fp, easy16buff, 100, &br)) return 0;
f_close(&fp);
easy16buff[br] = '\0';
if(!readSixteenEasyBytes(easy16buff + readSixteenEasyBytes(easy16buff, rootkey), rootkey + 16)) {
memset(easy16buff, 0, sizeof(easy16buff));
memset(rootkey, 0, 32);
return 0;
}
memset(easy16buff, 0, sizeof(easy16buff));
return 1;
}
uint8_t armwlt_read_shuffrootkey_file(const char *filename, const char *code, uint8_t *rootkey)
{
FIL fp;
char easy16buff[100];
UINT br;
static volatile uint8_t i, j;
if(f_open(&fp, filename, FA_READ)) return 0;
if(f_read(&fp, easy16buff, 100, &br)) return 0;
f_close(&fp);
easy16buff[br] = '\0';
const char transl[] = "0123456789ABCDEF";
for(i = 0; i < br; i++) {
for(j = 0; j < 16; j++) {
if(easy16buff[i] == transl[j]) {
easy16buff[i] = code[j];
}
}
}
if(!readSixteenEasyBytes(easy16buff + readSixteenEasyBytes(easy16buff, rootkey), rootkey + 16)) {
memset(easy16buff, 0, sizeof(easy16buff));
memset(rootkey, 0, 32);
return 0;
}
memset(easy16buff, 0, sizeof(easy16buff));
return 1;
}
uint8_t armwlt_get_privkey_from_pubkey(const WLT *wallet, /*FIL *fp*/const char *wltfn, const uint8_t *pubkey, uint8_t *privkey)
{
uint8_t pubkeyhash[20], pubkeyhash_buf[20], pubkey_buf[65];
uint32_t ci_map[50];
uint16_t ci_map_offset = 0;
//uint8_t chaincode[32];
//FRESULT fr;
FIL fp;
//char filename[100];
uint32_t br;
pubkey_to_pubkeyhash(pubkey, pubkeyhash);
//eeprom_busy_wait();
//eeprom_read_block(wallet->rootkey, armwlt_get_eep_privkeypos(wallet->id), 32);
//derive_chaincode_from_rootkey(wallet->privk, chaincode);
compute_chained_privkey(wallet->rootkey, wallet->chaincode, wallet->rootpubkey, privkey);
//memset(wallet->rootkey, 0, 32);
f_open(&fp, wltfn, FA_READ);
uint8_t eom;
do {
eom = get_wallet_mapblock(&fp, ci_map_offset, ci_map);
for(uint8_t i = 0; i < eom; i++) {
f_lseek (&fp, ci_map[i]);
f_read(&fp, (void *) pubkeyhash_buf, 20, (UINT*) &br);
if(memcmp(pubkeyhash, pubkeyhash_buf, 20) == 0) {
return 1;
} else {
f_lseek (&fp, (DWORD) f_tell(&fp) + 144);
f_read(&fp, (void *) pubkey_buf, 65, (UINT*) &br);
compute_chained_privkey(privkey, wallet->chaincode, pubkey_buf, privkey);
}
}
if(memcmp(pubkeyhash, pubkeyhash_buf, 20) == 0) {
return 1;
}
ci_map_offset += 50;
} while (eom != 0 && !f_eof(&fp));
f_close(&fp);
return 0;
}
uint8_t get_wallet_mapblock(FIL *fp, uint16_t blockstart, uint32_t *ci_map)
{
uint8_t entrytype, i;
static volatile uint16_t ci, N;
uint32_t pos, br;
f_lseek(fp, 2107);
i = 0;
while(i < 50 && /*f_tell(fp) < f_size(fp)*/!f_eof(fp)) {
f_read(fp, (void *) &entrytype, 1, (UINT*) &br);
if(entrytype == 0x00) {
pos = f_tell(fp);
f_lseek (fp, (DWORD) pos + 92);
f_read(fp, (void *) &ci, 2, (UINT*) &br);
if(ci >= blockstart && ci < blockstart + 50) {
ci_map[ci - blockstart] = pos;
i++;
}
f_lseek (fp, (DWORD) f_tell(fp) + 163);
} else if(entrytype == 0x01) {
f_lseek (fp, (DWORD) f_tell(fp) + 20);
f_read(fp, (void *) &N, 2, (UINT*) &br);
f_lseek (fp, (DWORD) f_tell(fp) + N);
} else if(entrytype == 0x02) {
f_lseek (fp, (DWORD) f_tell(fp) + 32);
f_read(fp, (void *) &N, 2, (UINT*) &br);
f_lseek (fp, (DWORD) f_tell(fp) + N);
} else if(entrytype == 0x04) {
f_read(fp, (void *) &N, 2, (UINT*) &br);
f_lseek (fp, (DWORD) f_tell(fp) + N);
} else {
break;
}
}
return i;
}
void compute_chained_privkey(const uint8_t *privkey, const uint8_t *chaincode, const uint8_t *pubkey, uint8_t *next_privkey)
{
extern uint8_t curve_n[32];
uint8_t chainMod[32], chainXor[32], temp[32], temp2[32];
hash256(pubkey, 65, chainMod);
for(uint8_t i = 0; i <= sizeof(chainXor); i++) {
chainXor[i] = chaincode[i] ^ chainMod[i];
}
vli_swap(chainXor, chainXor);
vli_swap(privkey, temp2);
vli_modMult(temp, chainXor, temp2, curve_n);
vli_swap(temp, temp);
memcpy(next_privkey, temp, 32);
}
void derive_chaincode_from_rootkey(uint8_t *rootkey, uint8_t *chaincode)
{
const char msg[] = "Derive Chaincode from Root Key"; // 0x44657269766520436861696E636F64652066726F6D20526F6F74204B6579
static uint8_t m[30];
memcpy(m,msg,strlen(msg));
uint8_t hash[32];
hash256(rootkey, 32, hash);
//vli_swap(hash,hash);
//_NOP();
hmac_sha256_armory_workaround(hash, 32, m, strlen(msg), chaincode);
}
/*
uint8_t create_wallet_from_rootkey(uint8_t rootkey[32], uint8_t checksum[4], armory_wallet *wallet, armory_addr *addrlist)
{
uint8_t i = 0;
armory_wallet tempw;
armory_addr tempa;
do {
memcpy(tempw.rootaddr.privkey, rootkey, 32); // copy rootkey
memcpy(tempw.rootaddr.privkey_chksum, checksum, 4); // copy rootkey checksum
} while (!verify_checksum(tempw.rootaddr.privkey, 32, tempw.rootaddr.privkey_chksum) && i++ < MAX_WRITE_ITER);
if(i > MAX_WRITE_ITER) { // copied rootkey and checksum still valid?
memset(&tempw, 0x00, sizeof(armory_wallet));
return 0;
}
i = 0;
uint8_t cc_mirror[32];
do {
derive_chaincode_from_rootkey(rootkey, tempw.chaincode);
derive_chaincode_from_rootkey(rootkey, cc_mirror); // derive chaincode 2x to detect bit errors
} while (memcmp(tempw.chaincode, cc_mirror, 32) != 0 && i++ < MAX_WRITE_ITER);
if(i > MAX_WRITE_ITER) { // copied chaincode and checksum still valid?
memset(&tempw, 0x00, sizeof(armory_wallet));
return 0;
}
compute_checksum(tempw.chaincode, 32, tempw.chaincode_chksum); // get cc checksum
if(!safe_extend_pubkey(rootkey, tempw.rootaddr.pubkey, tempw.rootaddr.pubkey_chksum, tempw.rootaddr.hash160, tempw.rootaddr.hash160_chksum)) {
memset(&tempw, 0x00, sizeof(armory_wallet));
return 0;
}
derive first actual privkey/pubkeyhash:
if(!safe_extend_privkey(tempw.rootaddr.privkey, tempw.chaincode, tempw.rootaddr.pubkey, tempa.privkey, tempa.privkey_chksum)) {
return 0;
}
if(!safe_extend_pubkey(tempa.privkey, tempa.pubkey, tempa.pubkey_chksum, tempa.hash160, tempa.hash160_chksum)) {
return 0;
}
now set wallet idstr from pubkeyhash of first usable addr:
pubkeyhash_to_wallet_idstr(tempa.hash160, tempw.idstr);
no errors so far, push wallet data to target space:
memcpy(tempw.sname, WALLET_CREATE_NAME, strlen(WALLET_CREATE_NAME)); // copy name
i = 0;
do {
memcpy(wallet, &tempw, sizeof(armory_wallet)); // copy whole local wallet struct to global wallet
} while (memcmp(wallet, &tempw, sizeof(armory_wallet)) != 0 && i++ < MAX_WRITE_ITER);
memcpy(&addrlist[0], &tempa, sizeof(armory_addr)); // copy first actual keypair to global address list
// create the first WALLET_CREATE_ADDRNUM - 1 keypairs of this wallet (one already exists from above)
uint8_t created = safe_extend_addrlist(wallet, addrlist, WALLET_CREATE_ADDRNUM - 1); // returns number of successfully created keypairs
// WRITE TO FLASH!!!
return 1;
}
*/
/*
uint8_t safe_extend_addrlist(armory_wallet *wallet, armory_addr *addrlist, const uint8_t num)
{
armory_addr tempa;
uint32_t ci = wallet->chainindex; // chainindex
uint8_t i = 0;
for( ; i <= num; i++) {
if(!safe_extend_privkey(addrlist[ci].privkey, wallet->chaincode, addrlist[ci].pubkey, tempa.privkey, tempa.privkey_chksum) ||
!safe_extend_pubkey(tempa.privkey, tempa.pubkey, tempa.pubkey_chksum, tempa.hash160, tempa.hash160_chksum)) {
break;
}
memcpy(&addrlist[++ci], &tempa, sizeof(armory_addr));
}
wallet->chainindex = ci;
return i;
}
uint8_t safe_extend_privkey(uint8_t *privkey, uint8_t *chaincode, uint8_t *pubkey, uint8_t *next_privkey, uint8_t *next_privkey_checksum)
{
uint8_t i = 0;
uint8_t k_mirror[32];
do {
compute_chained_privkey(privkey, chaincode, pubkey, next_privkey);
compute_chained_privkey(privkey, chaincode, pubkey, k_mirror);
} while (memcmp(next_privkey, k_mirror, 32) != 0 && i++ < MAX_WRITE_ITER);
if(i > MAX_WRITE_ITER) { return 0; }
compute_checksum(next_privkey, 32, next_privkey_checksum);
return 1;
}
uint8_t safe_extend_pubkey(uint8_t *privkey, uint8_t *pubkey, uint8_t *pubkey_checksum, uint8_t *pubkeyhash, uint8_t *pubkeyhash_checksum)
{
uint8_t i = 0;
uint8_t k_mirror[65], h_mirror[20];
do {
privkey_to_pubkey(privkey, pubkey);
privkey_to_pubkey(privkey, k_mirror);
} while (memcmp(pubkey, k_mirror, 65) != 0 && i++ < MAX_WRITE_ITER);
if(i > MAX_WRITE_ITER) { return 0; }
compute_checksum(pubkey, 65, pubkey_checksum);
i = 0;
do {
pubkey_to_pubkeyhash(pubkey, pubkeyhash);
pubkey_to_pubkeyhash(pubkey, h_mirror);
} while (memcmp(pubkeyhash, h_mirror, 20) != 0 && i++ < MAX_WRITE_ITER);
if(i > MAX_WRITE_ITER) { return 0; }
compute_checksum(pubkeyhash, 20, pubkeyhash_checksum);
return 1;
}
*/<file_sep>/hardened/src/transaction.h
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef TRANSACTION_H_
#define TRANSACTION_H_
#include <asf.h>
#include <string.h>
#include "bitcoin.h"
#include "base64.h"
#include "ecc.h"
#include "bytestream.h"
#include "transaction.h"
#include "wallet.h"
/*typedef struct _B64_CTX {
BYT buff_bp;
uint8_t buff[48];
FIL fp;
} B64_CTX;*/
//uint8_t armtx_fetch_unsigned_file(const char *filename, char *uniqueid, BYT *armtx_bp);
//uint8_t armtx_build_signed_file(BYT *armtx_bp, const char *uniqueid, const WLT *wallet, const char *wlt_filename);
//uint8_t armtx_get_latest_unsigned_file(char *filename);
//void armtx_push_base64blocks_to_file_init(B64_CTX *ctx, const char *filename, const char *uniqueid);
//void armtx_push_base64blocks_to_file_update(B64_CTX *ctx, const uint8_t *src, const uint16_t len);
//void armtx_push_base64blocks_to_file_final(B64_CTX *ctx);
void armtx_get_uniqueid(BYT *armtx_bp, char *uniqueid);
uint16_t armtx_get_txin_cnt(BYT *armtx_bp);
size_t armtx_get_txin_pos(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txin_len(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txin_data_pos(BYT *armtx_bp, const uint16_t txin);
uint32_t armtx_get_txin_previndex(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txin_supptx_pos(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txin_supptx_len(BYT *armtx_bp, const uint16_t txin);
uint64_t armtx_get_txin_inputvalue(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txin_pubkey_pos(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txin_pubkey(BYT *armtx_bp, const uint16_t txin, uint8_t *pubkey);
size_t armtx_get_txin_sequence_pos(BYT *armtx_bp, const uint16_t txin);
size_t armtx_get_txout_cnt_pos(BYT *armtx_bp);
uint16_t armtx_get_txout_cnt(BYT *armtx_bp);
size_t armtx_get_txout_pos(BYT *armtx_bp, const uint16_t txout);
size_t armtx_get_txout_len(BYT *armtx_bp, const uint16_t txout);
size_t armtx_get_txout_data_pos(BYT *armtx_bp, const uint16_t txout);
size_t armtx_get_txout_script_pos(BYT *armtx_bp, const uint16_t txout);
size_t armtx_get_txout_script_len(BYT *armtx_bp, const uint16_t txout);
size_t armtx_get_txout_script(BYT *armtx_bp, const uint16_t txout, uint8_t *script);
size_t armtx_get_txout_value_pos(BYT *armtx_bp, const uint16_t txout);
uint64_t armtx_get_txout_value(BYT *armtx_bp, const uint16_t txout);
uint64_t armtx_get_total_inputvalue(BYT *armtx_bp);
uint64_t armtx_get_total_outputvalue(BYT *armtx_bp);
uint64_t armtx_get_fee(BYT *armtx_bp);
//void armtx_build_unsigned_txhash_limbuffer(BYT *armtx_bp, const uint16_t txin, uint8_t *txhash);
void armtx_build_unsigned_txhash(BYT *armtx_bp, const uint16_t txin, uint8_t *txhash);
uint8_t armtx_build_txin_sig(BYT *armtx_bp, const uint16_t txin, const /*WLT *wallet*/uint8_t *privkey, BYT *sig_bp);
uint8_t build_DER_sig(const uint8_t *hashtosign, const uint8_t *privkey, BYT *sig_bp);
uint16_t tx_get_txin_cnt(BYT *tx_bp);
size_t tx_get_txin_pos(BYT *tx_bp, const uint16_t txin);
size_t tx_get_txin_sig_pos(BYT *tx_bp, const uint16_t txin);
size_t tx_get_txin_sig_len(BYT *tx_bp, const uint16_t txin);
size_t tx_get_txout_cnt_pos(BYT *tx_bp);
uint16_t tx_get_txout_cnt(BYT *tx_bp);
size_t tx_get_txout_pos(BYT *tx_bp, const uint16_t txout);
size_t tx_get_txout_script_pos(BYT *tx_bp, const uint16_t txout);
size_t tx_get_txout_value_pos(BYT *tx_bp, const uint16_t txout);
uint64_t tx_get_txout_value(BYT *tx_bp, const uint16_t txout);
uint8_t armtx_insert_sigs(BYT *u_armtx_bp, BYT *s_armtx_bp, void *pub2privkey_wrp);
//uint8_t armtx_build_signed_file2(BYT *armtx_bp, const char *uniqueid, const WLT *wallet, const char *wlt_filename);
void txfile_build_signed_file_snkwrp(BYT *bp);
uint8_t txfile_build_signed_file_pub2privkeywrp(const uint8_t *pubkey, uint8_t *privkey);
uint8_t txfile_build_signed_file(BYT *u_armtx_bp);
uint8_t txfile_fetch_unsigned_file(char *fn, char *uniqueid, BYT *armtx_bp);
size_t txfile_fetch_unsigned_file_srcwrp(BYT *bp, size_t ofs);
#endif /* TRANSACTION_H_ */<file_sep>/hardened/src/base58.c
// Copyright (c) 2014 The Bitcoin developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Port 2014 by <NAME>
#include "base58.h"
const char pszBase58[] = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
void base58_encode(const uint8_t *src, const uint16_t len, char *dest)
{
uint8_t pos = 0;
uint8_t destpos = 0;
uint32_t carry = 0;
uint8_t b58[50];
int8_t b58pos = 0;
uint8_t b58len = len * 138 / 100 + 1; // log(256) / log(58), rounded up.
memset(b58, 0, sizeof(b58));
while (pos < len && !src[pos]) {
destpos++;
pos++;
}
while (pos < len) {
carry = src[pos];
for (b58pos = b58len - 1; b58pos >= 0; b58pos--) {
carry += 256 * b58[b58pos];
b58[b58pos] = carry % 58;
carry /= 58;
}
pos++;
}
// Skip leading zeroes in base58 result.
b58pos = 0;
while (b58pos != b58len && b58[b58pos] == 0) {
b58pos++;
}
// Translate the result into a string.
memset(dest, '1', destpos);
while (b58pos != b58len) {
dest[destpos++] = pszBase58[b58[b58pos++]];
}
dest[destpos] = '\0';
}<file_sep>/hardened/src/bytestream.c
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#include "bytestream.h"
void b_open(BYT *bp, uint8_t *bytestrm, size_t reserved)
{
bp->bs = bytestrm;
bp->res = reserved;
bp->bptr = 0;
bp->size = 0;
bp->inh = 0;
bp->outh = 0;
bp->vofs = 0;
}
void b_setbufin(BYT *bp, void *inh, void *ctx)
{
bp->inh = inh;
bp->inh_ctx = ctx;
b_setpos(bp, 0);
}
void b_setbufout(BYT *bp, void *outh, void *ctx)
{
bp->outh = outh;
bp->outh_ctx = ctx;
}
uint8_t *b_addr(BYT *bp)
{
return bp->bs;
}
uint8_t *b_posaddr(BYT *bp)
{
return bp->bs + bp->bptr;
}
size_t b_tell(BYT *bp)
{
return bp->vofs + bp->bptr;
}
size_t b_size(BYT *bp)
{
return bp->size;
}
size_t b_ressize(BYT *bp)
{
return bp->res;
}
size_t b_srcsize(BYT *bp)
{
if(!bp->srclen) return bp->size;
return bp->srclen;
}
size_t b_snksize(BYT *bp)
{
if(!bp->snklen) return bp->size;
return bp->snklen;
}
size_t b_seek(BYT *bp, size_t ofs)
{
//if(bp->ofs + ofs > bp->size) {
// ofs = bp->size - bp->ofs;
//}
if(ofs < bp->vofs || ofs > bp->vofs+bp->res) {
if(bp->inh) {
b_setpos(bp, ofs);
} else if(bp->outh) {
if(ofs < bp->vofs) {
ofs = bp->vofs;
} else if(ofs > bp->vofs+bp->res) {
ofs = bp->vofs+bp->res;
}
}
}
return bp->bptr = ofs - bp->vofs;
}
void b_rewind(BYT *bp)
{
b_seek(bp, 0);
}
size_t b_truncate(BYT *bp)
{
return bp->size = bp->bptr;
}
size_t b_reopen(BYT *bp)
{
uint16_t size = b_size(bp);
b_rewind(bp);
b_truncate(bp);
return size; // return number of bytes discarded
}
size_t b_setpos(BYT *bp, size_t ofs)
{
if((bp->inh)) {
bp->size = bp->inh(bp, ofs);
bp->vofs = ofs;
bp->bptr = 0;
}
return 0;
}
size_t b_read(BYT *bp, uint8_t *buff, size_t btr)
{
size_t chunk, br = 0;
while((bp->inh) && btr > (chunk = bp->size - bp->bptr)) {
memcpy(buff + br, bp->bs + bp->bptr, chunk);
br += chunk;
btr -= chunk;
b_setpos(bp, bp->vofs + bp->bptr + br);
}
memcpy(buff + br, bp->bs + bp->bptr, btr);
bp->bptr = br ? btr : bp->bptr + btr;
br += btr;
return br;
}
size_t b_write(BYT *bp, const uint8_t *buff, size_t btw)
{
size_t chunk, bw = 0;
while((bp->outh) && btw > (chunk = bp->res - bp->bptr)) {
memcpy(bp->bs + bp->bptr, buff, chunk);
bw += chunk;
btw -= chunk;
bp->bptr = bp->res;
bp->size = bp->res;
b_flush(bp);
}
if(btw > (chunk = bp->res - bp->bptr)) btw = chunk;
memcpy(bp->bs + bp->bptr, buff + bw, btw);
bp->bptr += btw;
bw += btw;
if(bp->bptr > bp->size) bp->size = bp->bptr;
return bw;
}
void b_flush(BYT *bp)
{
if((bp->outh)) {
bp->outh(bp);
bp->vofs += bp->size;
bp->bptr = 0;
bp->size = 0;
}
//return 0;
}
size_t b_copy(BYT *bp_from, BYT *bp_to, size_t btc)
{
uint8_t buff[32];
if(btc <= sizeof(buff)) {
b_read(bp_from, buff, btc);
b_write(bp_to, buff, btc);
} else {
uint8_t rem = btc % sizeof(buff);
uint16_t s = 0;
while(s + rem < btc) {
b_read(bp_from, buff, sizeof(buff));
b_write(bp_to, buff, sizeof(buff));
s += sizeof(buff);
}
if(rem > 0) {
b_read(bp_from, buff, rem);
b_write(bp_to, buff, rem);
}
}
return btc;
}
size_t b_putc(BYT *bp, char chr)
{
return b_write(bp, (uint8_t *) &chr, 1);
}
char b_getc(BYT *bp)
{
char chr;
b_read(bp, (uint8_t *) &chr, 1);
return chr;
}
size_t b_putvint(BYT *bp, uint32_t vint)
{
uint8_t fb;
if(vint < 0xfd) { // vint length 1
b_write(bp, (uint8_t *) &vint, 1);
return 1;
} else if(vint < 0xffff){ // vint length 3
fb = 0xfd;
b_write(bp, &fb, 1);
b_write(bp, (uint8_t *) &vint, 2);
return 3;
} else if(vint < 0xffffffff) { // vint length 5
fb = 0xfe;
b_write(bp, &fb, 1);
b_write(bp, (uint8_t *) &vint, 4);
return 5;
} else { // not expecting 64 bit integers in a tx
return 0;
}
}
uint32_t b_getvint(BYT *bp)
{
uint8_t fb;
uint32_t b;
b_read(bp, &fb, 1);
if(fb < 0xfd) { // vint length 1
return fb;
} else if(fb < 0xfe) { // vint length 3
b_read(bp, (uint8_t *) &b, 2);
return b;
} else if(fb < 0xff) { // vint length 5
b_read(bp, (uint8_t *) &b, 4);
return b;
} else { // assuming we never get 64 bit integers in a tx
return 0;
}
}<file_sep>/hardened/src/rand.h
/*
* rand.h
*
* Created: 05.01.2015 17:52:36
* Author: Mo
*/
#ifndef RAND_H_
#define RAND_H_
#include <asf.h>
#include <string.h>
#include <avr/eeprom.h>
#include <stddef.h>
#include <avr/io.h>
void adc_rand_init(void);
void adc_rand(uint8_t *dest, size_t len);
uint32_t rand32(void);
void byteshuffle(const uint8_t *src, const size_t len, uint8_t *dest);
#endif /* RAND_H_ */<file_sep>/hardened/src/ui.h
/**
* Copyright (c) 2014 <NAME>
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
#ifndef UI_H_
#define UI_H_
#include <asf.h>
#include <string.h>
#include <avr/eeprom.h>
#include "utils.h"
#include "app_touch.h"
#include "bitcoin.h"
#include "base64.h"
#include "base58.h"
#include "ecc.h"
#include "sha2.h"
#include "bytestream.h"
#include "transaction.h"
#include "rand.h"
void _ui_clear(void);
void _ui_qtb_action(uint8_t dir);
void _ui_set_sw0(void *dest, char label);
void _ui_set_sw1(void *dest, char label);
void _ui_set_qtb(void *dest, uint8_t i_max);
void _ui_init(void);
void _ui_scan_buttons(void);
void _ui_format_amount(const uint64_t val, char *output);
void ui_screen_home(void);
void ui_screen_menu(void);
void ui_screen_menu_list(uint8_t i);
void ui_screen_menu_shuffcode(void);
void ui_screen_menu_shuffcode_list(uint8_t i);
void ui_screen_menu_shuffcode_refresh(void);
void ui_screen_menu_browsetxs(void);
void ui_screen_opentx(void);
void ui_screen_opentx_list(uint8_t i);
void ui_screen_signtx(void);
void ui_screen_menu_exportwlt(void);
void ui_screen_menu_exportwlt_list(uint8_t i);
void ui_screen_menu_exportwlt_erase(void);
void ui_screen_menu_exportwlt_watchonly(void);
void ui_screen_menu_exportwlt_rootkeyfile(void);
void ui_screen_menu_exportwlt_showrootkey(void);
void ui_screen_menu_exportwlt_showrootkey_list(uint8_t i);
void ui_screen_menu_setupwlt(void);
void ui_screen_menu_setupwlt_list(uint8_t i);
void ui_screen_menu_setupwlt_rootkeyfile(void);
void ui_screen_menu_setupwlt_shuffrootkeyfile(void);
void ui_screen_menu_setupwlt_wltfile(void);
void ui_screen_menu_setupwlt_createonchip(void);
void ui_screen_menu_setupwlt_import(void);
void ui_screen_menu_setupwlt_erase(void);
void ui_screen_menu_selectwlt(void);
void ui_screen_menu_selectwlt_list(uint8_t i);
void ui_screen_menu_selectwlt_setact(void);
void ui_screen_menu_changepin(void);
void ui_screen_menu_erasewlt(void);
void ui_screen_menu_erasewlt_erase(void);
#endif /* UI_H_ */
|
fb2514291424ce800f1b234f26f2e59c5d28f5e0
|
[
"Markdown",
"C",
"Makefile"
] | 21 |
C
|
SwagWarrior/armory-hardened
|
7fb464c85d22a4bf1b0ad0a8c335ebdd47aa0ed3
|
ce03f5573373fcf420d61ca04c9775b4de308b0d
|
refs/heads/main
|
<file_sep>#include <shmem.h>
#include <stdio.h>
#include <stdlib.h>
#define NUM_POINTS 10000
long long inside = 0, total = 0; //long long is double the size of long
int main(int argc, char **argv){
int me, myshmem_n_pes;
shmem_init();
myshmem_n_pes = shmem_n_pes();
me = shmem_my_pe();
srand(1+me); //sets the seed
//each PE calaculates NUM_POINTS times
for(total = 0; total < NUM_POINTS; ++total) {
double x,y;
//coordinates between 0 and 1
x = rand()/(double)RAND_MAX;
y = rand()/(double)RAND_MAX;
//inside the circle
if(x*x + y*y < 1) {
++inside;
}
}
shmem_barrier_all();
if(me == 0) {
for(int i = 1; i < myshmem_n_pes; ++i) {
long long remoteInside,remoteTotal;
shmem_longlong_get(&remoteInside,&inside,1,i);
shmem_longlong_get(&remoteTotal,&total,1,i);
//get inside and total of every PE
total += remoteTotal;
inside += remoteInside;
}
//ratio of the quarters of the circle and square is sure to be pi/4
double approx_pi = 4.0*inside/(double)total;
printf("Pi from %llu points on %d PEs: %lf\n", total, myshmem_n_pes, approx_pi);
}
shmem_finalize();
return 0;
}
<file_sep>#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#include <pthread.h>
#include <omp.h>
#define width 1920 //width of the image
#define height 1080 //height of the image
int32_t array_a[width*height]; //original image
int32_t array_b[width*height]; //blurred image
//Return a specified pixel in the image
int32_t apply(int x, int y, int32_t data[]) {
return data[y * width + x];
}
//Update a specified pixel in the image
void update(int x, int y, int32_t c, int32_t data[]) {
data[y * width + x] = c;
}
//Get the red component
int32_t red(int32_t c) {
return (0xFF000000 & c) >> 24;
}
//Get the green component
int32_t green(int32_t c) {
return (0x00FF0000 & c) >> 16;
}
//Get the blue component
int32_t blue(int32_t c) {
return (0x0000FF00 & c) >> 8;
}
//Get the alpha component
int32_t alpha(int32_t c) {
return (0x000000FF & c) >> 0;
}
//Create RGBA from separate components
int32_t rgba(int32_t r, int32_t g, int32_t b, int32_t a) {
return (r << 24) | (g << 16) | (b << 8) | (a << 0);
}
//Restricts the integer into the specified range
int clamp(int v, int min, int max) {
if (v < min)
return min;
else if (v > max)
return max;
else
return v;
}
//Computes the blurred RGBA of a pixel
int32_t boxBlurKernel(int32_t data[], int x, int y, int radius) {
int32_t r = 0;
int32_t g = 0;
int32_t b = 0;
int32_t a = 0;
int32_t num = 0;
for (int i = clamp(y - radius, 0, height - 1); i <= clamp(y + radius, 0, height - 1); i ++){
for(int j = clamp(x - radius, 0, width - 1); j <= clamp(x + radius, 0, width - 1); j ++)
{
r += red(apply(j, i, data));
g += green(apply(j, i, data));
b += blue(apply(j, i, data));
a += alpha(apply(j, i, data));
num += 1;
}
}
return rgba(r / num, g / num, b / num, a / num);
}
//Blurs the row of src into dst going from left to right
void blur(int32_t src[], int32_t dst[], int from, int end, int radius) {
for (int i = from; i <= end; i ++){
int y = i / width;
int x = i - y * width;
update(x, y, boxBlurKernel(src, x, y, radius), dst);
}
}
int main(int argc, char **argv) {
int size = omp_get_max_threads();
int task_length = (height*width) / size;
for (int j = 0; j < height*width; j ++){
array_a[j] = j;
}
#pragma omp parallel
{
int start = omp_get_thread_num()*task_length;
int end = start + task_length - 1;
if (end > width*height - 1)
end = width*height - 1;
blur(array_a, array_b, start, end, 3);
}
/*for (int i = 0; i < width*height; i ++)
printf("src[%d] = %d to dst[%d] = %d\n", i, array_a[i], i, array_b[i]);*/
}
<file_sep>#include <stdio.h>
#include <shmem.h>
// Forked from the tutorial
int main (int argc, char **argv) {
int me, npes;
shmem_init (); //Library Initialization
me = shmem_my_pe ();
npes = shmem_n_pes ();
printf ("Hello World from PE %4d of %4d\n", me, npes);
shmem_finalize();
return 0;
}
<file_sep># openshmem-coding
parallel programming practice
<file_sep>CC=oshcc
CFLAGS=-Wall -Wextra -Werror -Wno-unused -Wno-unused-parameter -Wno-format-overflow -g3 -O3 -msse4.2
all: hello_world array broadcast
hello_world: hello_world.c
$(CC) -o $@ $<
array: array.c
$(CC) -o $@ $<
broadcast: broadcast.c
$(CC) -o $@ $<
team: team.c
$(CC) -o $@ $<
monte_carlo_pi: monte_carlo_pi.c
$(CC) -o $@ $<
box_blur: box_blur.c
$(CC) -o $@ $<
<file_sep>//Written by <NAME>
#include <stdlib.h>
#include <stdio.h>
#include <shmem.h>
#include <shmemx.h>
#define MAXPROC 2112
int a[MAXPROC];
int main(int argc, char **argv) {
int rank, size;
static int local;
shmem_init();
rank = shmem_my_pe();
size = shmem_n_pes();
if (rank == 0) {
for (int i=0; i<MAXPROC; i++)
a[i] = 0;
}
shmem_barrier_all();
local = shmem_g(&a[rank], 0);
local += rank;
shmem_barrier_all();
shmem_p(&a[rank], local, 0);
shmem_barrier_all();
if (rank == 0) {
for (int i=0; i<size; i++)
printf("a[%d] = %d\n", i, a[i]);
}
shmem_finalize();
}
<file_sep>#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
#include <string.h>
#include <shmem.h>
#include <shmemx.h>
#include <math.h>
int rank;
long long q_length;
long long elem_length;
double min;
double max;
double data[1048576];
#define N 67108864
#define MIN(X, Y) (((X) < (Y)) ? (X) : (Y))
#define MAX(X, Y) (((X) > (Y)) ? (X) : (Y))
static long long tsk_q[N];
void steal(int from, long long index, long long size){
clock_t t = clock();
shmem_get(&tsk_q[index], &tsk_q[index], size, from);
t = clock() - t;
double time_taken = ((double)t/CLOCKS_PER_SEC)*1000000;
data[index/size] = time_taken;
max = MAX(max, time_taken);
min = MIN(min, time_taken);
}
void communicate(void (*method)(), long long tsk_size, long long msg_iter){
if (rank == 0)
for (long long i = 0; i < q_length; i += elem_length)
(*method)(1, i, elem_length);
}
void printtable(long long tsk_size, long long msg_iter, double time_taken){
printf("============ RESULTS ================\n");
printf("Message size: %ld \n", tsk_size);
printf("Message count: %ld \n", msg_iter);
printf("Total duration: %.3f %s\n", time_taken, "ms");
double average = time_taken*1000/msg_iter;
printf("Average duration: %.3f %s\n", average, "us");
printf("Minimum duration: %.3f %s\n", min, "us");
printf("Maximum duration: %.3f %s\n", max, "us");
double sum = 0;
for (int i = 0; i < msg_iter; i ++)
sum += (data[i] - average) * (data[i] - average);
sum /= (msg_iter - 1);
sum = sqrt(sum);
printf("Standard deviation: %.3f %s\n", sum, "us");
printf("Message rate: %.3f %s\n", msg_iter/(time_taken/1000), "msg/s");
printf("=====================================\n");
}
void createqueue(long long tsk_size, long long msg_iter){
elem_length = tsk_size / sizeof(long long);
q_length = msg_iter * elem_length;
for (int64_t i = 0; i < q_length; i ++)
tsk_q[i] = i;
}
int main(int argc, char *argv[]){
shmem_init();
long long msg_iter = 1048576;
long long tsk_size = 512;
rank = shmem_my_pe();
if (argc > 1){
msg_iter = atoi(argv[1]);
if (argc > 2)
tsk_size = atoi(argv[2]);
}
shmem_barrier_all();
createqueue(tsk_size, msg_iter);
clock_t t;
if (rank == 0)
t = clock();
communicate(&steal, tsk_size, msg_iter);
shmem_barrier_all();
if (rank == 0)
printtable(tsk_size, msg_iter, ((double)(clock()-t)/CLOCKS_PER_SEC)*1000);
shmem_finalize();
}
<file_sep>//Skeleton written by <NAME>. Modified by <NAME>.
#include <stdlib.h>
#include <stdio.h>
#include <stdbool.h>
#include <shmem.h>
#include <shmemx.h>
#define MAXPROC 2112
int rank, size;
uint64_t parent_sent, left_sent, right_sent; // signal flag values
int64_t myval,leftval, rightval; // local places to send/recv messages
void broadcast(int64_t *val) {
int left = rank*2 + 1;
if (left < size)
shmem_putmem_signal(&myval, val, sizeof(int64_t), &parent_sent, 1, SHMEM_SIGNAL_SET, left);
if (left + 1 < size)
shmem_putmem_signal(&myval, val, sizeof(int64_t), &parent_sent, 1, SHMEM_SIGNAL_SET, left+1);
}
void reduce(int64_t *local, int64_t *result) {
int parent = (rank + 1) / 2 - 1;
//*result = *local + leftval + rightval;
*result = *local * 10;
if (parent >= 0 && rank % 2 != 0) {
shmem_putmem_signal(&leftval, result, sizeof(int64_t), &left_sent, 1, SHMEM_SIGNAL_SET, parent);
} else if (parent >= 0 && rank % 2 == 0) {
shmem_putmem_signal(&rightval, result, sizeof(int64_t), &right_sent, 1, SHMEM_SIGNAL_SET, parent);
}
}
int main(int argc, char **argv) {
int64_t reduceval = 0;
setbuf(stdout, NULL);
shmem_init();
rank = shmem_my_pe();
size = shmem_n_pes();
if (rank == 0) {
myval = size;
}
parent_sent = left_sent = right_sent = 0;
leftval = rightval = 0;
shmem_barrier_all();
if (rank != 0){
shmem_wait_until(&parent_sent, SHMEM_CMP_EQ, 1);
}
broadcast(&myval);
shmem_barrier_all();
for (int i = 0; i < size; i ++){
if (i == rank)
printf("rank %d received %ld\n", rank, myval);
shmem_barrier_all();
}
shmem_barrier_all();
int left = rank*2 + 1;
if (left < size){
shmem_wait_until(&left_sent, SHMEM_CMP_EQ, 1);
}
if (left + 1 < size){
shmem_wait_until(&right_sent, SHMEM_CMP_EQ, 1);
}
reduce(&myval, &reduceval);
shmem_barrier_all();
if (rank == 0)
printf("reduced value is: %ld\n", reduceval);
shmem_finalize();
}
|
388fd27977e4cff6b7bd2fd38b66b82ed374d8c4
|
[
"Markdown",
"C",
"Makefile"
] | 8 |
C
|
ledd-23/openshmem-code-snippets
|
b2abcd0211c599f20d5d5ec3753b934b740d99f8
|
558ba45e8129a4384b13cccf02ab7fc996572493
|
refs/heads/master
|
<file_sep># keras_unet
unet
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import os
os.environ["CUDA_VISIBLE_DEVICES"] = "0"
from unet_def import *
import cv2
import keras
from keras.optimizers import *
def transform_predict_to_image(predict, save_name):
predict = predict[:, :, 0]
result = np.zeros_like(predict, dtype=np.uint8)
result[np.where(predict > 0.5)] = 255
cv2.imwrite(save_name, result)
def get_test_images(image_dir, target_size=(256, 256)):
images = []
image_list = [os.path.join(image_dir, item) for item in os.listdir(image_dir)]
for img_path in image_list:
image = cv2.imread(img_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, target_size)
image = image.astype(np.float32)
image /= 256.0
image = image[np.newaxis, :, :, np.newaxis]
images.append(image)
images = np.concatenate(images)
return images, image_list
def get_train_images_masks(image_dir, mask_dir, target_size=(256, 256)):
images = []
masks = []
image_list = [os.path.join(image_dir, item) for item in os.listdir(image_dir)]
mask_list = [os.path.join(mask_dir, item) for item in os.listdir(mask_dir)]
assert(len(image_list) == len(mask_list))
for img_path, mask_path in zip(image_list, mask_list):
assert(img_path.split('/')[-1][:-3] == mask_path.split('/')[-1][:-3])
image = cv2.imread(img_path)
mask = cv2.imread(mask_path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
mask = cv2.cvtColor(mask, cv2.COLOR_BGR2GRAY)
image = cv2.resize(image, target_size)
mask = cv2.resize(mask, target_size)
image = image.astype(np.float32)
mask = mask.astype(np.float32)
image /= 256.0
mask /= 256.0
image = image[np.newaxis, :, :, np.newaxis]
mask[mask > 0.5] = 1.0
mask[mask <= 0.5] = 0.0
mask = mask[np.newaxis, :, :, np.newaxis]
images.append(image)
masks.append(mask)
images = np.concatenate(images)
masks = np.concatenate(masks)
return (images, masks)
def make_train_generator(images, masks, batch_size=2):
seed = 1
data_augment_args = dict(rotation_range=60, width_shift_range=0.05,
height_shift_range=0.05, shear_range=0.05,
zoom_range=0.05, vertical_flip=True,
horizontal_flip=True, fill_mode='nearest')
image_generator = keras.preprocessing.image.ImageDataGenerator(**data_augment_args)
mask_generator = keras.preprocessing.image.ImageDataGenerator(**data_augment_args)
image_generator = image_generator.flow(images, batch_size=batch_size, seed=seed)
mask_generator = mask_generator.flow(masks, batch_size=batch_size, seed=seed)
return zip(image_generator, mask_generator)
def get_callbacks():
mcp = keras.callbacks.ModelCheckpoint(filepath='./weights/{val_loss:.5f}.hdf5',
monitor='val_loss', save_best_only=False,period=10)
tb = keras.callbacks.TensorBoard(log_dir='./logs', batch_size=2, write_grads=True, write_images=True)
return [mcp, tb]
if __name__ == "__main__":
train_images, train_masks = get_train_images_masks('data/membrane/train/image', 'data/membrane/train/label')
test_images, test_image_names = get_test_images('data/membrane/test')
valid_images, valid_masks = train_images[24:], train_masks[24:]
train_images, train_masks = train_images[:24], train_masks[:24]
print "train images shape : ", train_images.shape
print "train masks shape : ", train_masks.shape
print "valid images shape : ", valid_images.shape
print "valid masks shape : ", valid_masks.shape
print "test image shape : ", test_images.shape
train_generator = make_train_generator(train_images, train_masks)
model = unet()
model.summary()
# model.load_weights('./weights/best_model.hdf5')
model.compile(optimizer=adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])
model.fit_generator(train_generator, steps_per_epoch=30, epochs=50,
validation_data = (valid_images, valid_masks), callbacks=get_callbacks())
# test
predict_result = model.predict(test_images, batch_size=len(test_images) / 5)
for index, item in enumerate(predict_result):
save_name = 'results/' + test_image_names[index].split('/')[-1]
transform_predict_to_image(item, save_name)
|
da232d3e09f3d4d0eb5319fe8610a9d870d18a57
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
zzdxfei/keras_unet
|
d450d044a4889aa459ead39db8724009935124b0
|
6f9e340af3032ef9f04b32d759a3a03cb65bfcb9
|
refs/heads/master
|
<file_sep>print("Hola Mundo del GitHub")
<file_sep>#Esto lo hice en la net,como lo veo en internet
<file_sep>aca van todos los codigos
vamos a ver si puedo pullear el cambio de nombre y es texo desde mi net: pude hacerlo con >> git pull https://github.com/NickTrossa/repoPrimero.git master
vamos a ver si puedo pushear esto para que se vea online
<file_sep>print("Este archivo lo cree en una subcarpeta. Como lo veo en la net?")
|
e3b6dbc40ee449536384cde904c8ec3ac39c9bca
|
[
"Python",
"Text"
] | 4 |
Python
|
NickTrossa/repoPrimero
|
5e7cd7672157b0dfa60dfe56bffb5d8ea209409a
|
f9c396dd09bf07748378c85f6fec91626f8ecd0d
|
refs/heads/master
|
<repo_name>augustapop/WentToursPOM<file_sep>/WentToursPOM/LoginPage.cs
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace WentToursPOM
{
class LoginPage
{
public IWebDriver driver;
public LoginPage(IWebDriver driver)
{
this.driver = driver;
}
public FindFlightPage Do(string UserName, string Password)
{
driver.FindElement(By.Name("userName")).SendKeys(UserName);
driver.FindElement(By.Name("password")).SendKeys(Password);
driver.FindElement(By.Name("login")).Click();
return new FindFlightPage(driver);
}
}
}
<file_sep>/WentToursPOM/FindFlightPage.cs
using OpenQA.Selenium;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace WentToursPOM
{
class FindFlightPage
{
private IWebDriver driver;
public FindFlightPage(IWebDriver driver)
{
this.driver = driver;
}
public void Do()
{
driver.FindElement(By.CssSelector("input[name=tripType][value=oneway]")).Click();
driver.FindElement(By.Name("passCount")).FindElement(By.CssSelector("option[value='3']")).Click();
driver.FindElement(By.Name("fromPort")).FindElement(By.CssSelector("option[value='Paris']")).Click();
driver.Manage().Window.Maximize();
driver.FindElement(By.CssSelector("input[name=servClass][value=Business]")).Click();
driver.FindElement(By.Name("findFlights")).Click();
driver.FindElement(By.CssSelector("input[name=outFlight][value='Blue Skies Airlines$361$271$7:10']")).Click();
//Thread.Sleep(1000);
driver.FindElement(By.Name("reserveFlights")).Click();
//driver.Manage().Window.Maximize();
driver.FindElement(By.Name("passFirst0")).SendKeys("Ioana");
driver.FindElement(By.Name("passLast0")).SendKeys("Pop");
driver.FindElement(By.Name("pass.0.meal")).FindElement(By.CssSelector("option[value='BLML']")).Click();
driver.FindElement(By.Name("creditnumber")).SendKeys("1234565789365426");
IWebElement element = driver.FindElement(By.Name("cc_exp_dt_mn"));
IList<IWebElement> AllDropDownList = element.FindElements(By.XPath("//option"));
int DpListCount = AllDropDownList.Count;
for (int i = 0; i < DpListCount; i++)
{
if (AllDropDownList[i].Text == "02")
{
AllDropDownList[i].Click();
}
}
//driver.FindElement(By.Name("cc_exp_dt_mn")).FindElement(By.PartialLinkText("01")).Click();
driver.FindElement(By.Name("cc_exp_dt_yr")).FindElement(By.CssSelector("option[value='2010']")).Click();
driver.FindElement(By.Name("ticketLess")).Click();
driver.FindElement(By.Name("buyFlights")).Click();
}
public LoginPage Logout()
{
driver.Navigate().GoToUrl("http://newtours.demoaut.com/");
return new LoginPage(driver);
}
}
}
<file_sep>/WentToursPOM/WentToursPOM.cs
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using OpenQA.Selenium.Firefox;
using OpenQA.Selenium;
using System.Threading;
namespace WentToursPOM
{
[TestClass]
public class WentToursPOM
{
private string baseURL = "http://newtours.demoaut.com/";
private int Timeout = 30;
IWebDriver driver = new FirefoxDriver();
[TestMethod]
public void TestLogin()
{
driver.Navigate().GoToUrl(baseURL);
LoginPage Login = new LoginPage(driver);
FindFlightPage FindFlight = Login.Do("<EMAIL>","Abigail_muresan1980");
if (FindFlight != null)
{
FindFlight.Do();
Thread.Sleep(2000);
Login = FindFlight.Logout();
}
}
}
}
<file_sep>/README.md
# WentToursPOM Reservation
Page Object Model is a design pattern to create Object Repository for web UI elements.
Under this model, for each web page in the application there should be corresponding page class.
This Page class will find the WebElements of that web page and also contains Page methods which perform operations on those WebElements.
Here we have one POM for LoginPage and another for FindFlightPage which are calling in TestPage.
Ready Scenarios:
1)TestLogin
Steps:
1)Navigate to Page
2)Login Page
3)FindFlight
4)Logout using LoginPage
Run the tests:
1)TestLogin
Download Zip and run https://github.com/augustapop/WentToursPOM/blob/master/WentToursPOM/WentToursPOM.cs
|
a28380c7e569887fb3341628dbc0552bc7ae6688
|
[
"Markdown",
"C#"
] | 4 |
C#
|
augustapop/WentToursPOM
|
10bfd654c1faca8d2f2ef8663f38a63d373cefc4
|
7781c782eebb84f6671a6fd75e9a75a41b6321ef
|
refs/heads/master
|
<file_sep># ODU17
有妖气app
<file_sep>platform :ios, '8.0'
target 'ODU17' do
use_frameworks!
inhibit_all_warnings!
pod 'SnapKit'
pod 'Moya'
pod 'Kingfisher'
pod 'MJRefresh'
pod 'IQKeyboardManagerSwift'
pod 'HandyJSON'
end
|
b0e9da9de706f6f6f14b8d10cb0121b35737e54e
|
[
"Markdown",
"Ruby"
] | 2 |
Markdown
|
Leungwn/ODU17
|
52c9533975fdcf8553deb2d88acf16a4b0daccb8
|
6b2d24fdd86269bc0f52dec9f0be90d05c1ab323
|
refs/heads/master
|
<repo_name>kien2929/ci-begin-master-Session-6<file_sep>/src/base/enemy/Enemy.java
package base.enemy;
import base.FrameCounter;
import base.GameObject;
import base.game.GameCanvas;
import base.physics.BoxCollider;
import base.physics.Physics;
import base.renderer.AnimationRenderer;
import base.renderer.SingleImageRenderer;
import tklibs.SpriteUtils;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
public class Enemy extends GameObject implements Physics {
FrameCounter fireCounter;
BoxCollider boxCollider;
public Enemy() {
super();
this.position.set(50,50);
this.velocity.set(0, 3);
this.createRenderer();
this.fireCounter = new FrameCounter(20);
this.boxCollider = new BoxCollider(this.position, 28, 28);
}
private void createRenderer() {
ArrayList<BufferedImage> images = SpriteUtils.loadImages(
"assets/images/enemies/level0/pink/0.png",
"assets/images/enemies/level0/pink/1.png",
"assets/images/enemies/level0/pink/2.png",
"assets/images/enemies/level0/pink/3.png"
);
this.renderer = new AnimationRenderer(images);
}
@Override
public void run() {
super.run();
if(this.position.y >= 300) {
this.velocity.set(0, 0);
}
this.fire();
}
//TODO: replace frameCounter
private void fire() {
if (this.fireCounter.run()) {
EnemyBullet enemyBullet = GameObject.recycle(EnemyBullet.class);
enemyBullet.position.set(this.position);
this.fireCounter.reset();
}
}
@Override
public void destroy() {
super.destroy();
EnemyExplosion explosion = GameObject.recycle(EnemyExplosion.class);
explosion.position.set(this.position);
}
@Override
public BoxCollider getBoxCollider() {
return this.boxCollider;
}
}
|
6d09b01e5e8a2b63962794d67ca04229b100f1ef
|
[
"Java"
] | 1 |
Java
|
kien2929/ci-begin-master-Session-6
|
77a7632f3f0943ebbdac3bbbe7ac838d04655c7b
|
bfa4963d5fcc7d3edfef56d38251f99c5d88effd
|
refs/heads/master
|
<repo_name>NarimanAB/atomikos<file_sep>/src/main/java/com/example/atomikos/AtomikosApplication.java
package com.example.atomikos;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.support.TransactionTemplate;
@SpringBootApplication
public class AtomikosApplication {
public static void main(String[] args) {
SpringApplication.run(AtomikosApplication.class, args);
}
@Bean
public TransactionTemplate transactionTemplate(PlatformTransactionManager transactionManager) {
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
return transactionTemplate;
}
}
<file_sep>/src/main/resources/application.properties
spring.jta.atomikos.datasource.max-pool-size=20
spring.jta.atomikos.datasource.min-pool-size=10
spring.jta.atomikos.datasource.test-query=select 1
spring.jta.atomikos.properties.default-jta-timeout=900s
spring.datasource.url=jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
<file_sep>/src/test/java/com/example/atomikos/AtomikosApplicationTests.java
package com.example.atomikos;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CancellationException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import javax.persistence.EntityManager;
import javax.transaction.Transactional;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.transaction.support.TransactionTemplate;
@SpringBootTest
@Transactional
@Slf4j
class AtomikosApplicationTests {
@Autowired
private TransactionTemplate transactionTemplate;
@Autowired
private EntityManager entityManager;
@Test
void testJTA() {
ExecutorService executorService = null;
executorService = Executors.newFixedThreadPool(1);
try {
List<BatchItem> batchItems = new ArrayList<>();
batchItems.add(() -> {
entityManager.createNativeQuery("select 1").getResultList().get(0);
try {
Thread.sleep(10000);
}
catch (InterruptedException e) {
log.debug("", e);
//restore thread interrupt state / emulate not responding DB query
Thread.currentThread().interrupt();
}
return true;
});
batchItems.add(() -> {
entityManager.createNativeQuery("select 1").getResultList().get(0);
return true;
});
batchItems.add(() -> {
entityManager.createNativeQuery("select 2").getResultList().get(0);
return true;
});
batchItems.add(() -> {
entityManager.createNativeQuery("select 3").getResultList().get(0);
return true;
});
List<Future<FutureResult<Boolean>>> futures = new ArrayList<>();
for (BatchItem batchEntry : batchItems) {
futures.add(
executorService.submit(() -> {
List<Throwable> exceptions = new ArrayList<>();
Boolean result = null;
try {
log.info("processing batch entry {}", batchEntry);
result = transactionTemplate.execute(status -> batchEntry.run());
log.info("batch successfully processed");
}
catch (RuntimeException e) {
exceptions.add(e);
log.error("unexpected error: ", e);
}
FutureResult<Boolean> futureResult = new FutureResult<>();
futureResult.exceptions = exceptions;
futureResult.result = result;
return futureResult;
})
);
}
List<Throwable> exceptions = new ArrayList<>();
for (Future<FutureResult<Boolean>> future : futures) {
try {
FutureResult<Boolean> futureResult;
futureResult = future.get(1, TimeUnit.SECONDS);
exceptions.addAll(futureResult.exceptions);
}
catch (InterruptedException e) {
log.error("Thread was interrupted", e);
exceptions.add(e);
// Restore interrupted state...
Thread.currentThread().interrupt();
}
catch (TimeoutException e) {
log.error("Exception while waiting for the batch job future task completion", e);
exceptions.add(e);
// cancel the task and flag its thread as interrupted
future.cancel(true);
}
catch (ExecutionException e) {
log.error("Exception while the batch job future task execution", e);
exceptions.add(e);
}
catch (CancellationException e) {
log.error("The task was canceled", e);
exceptions.add(e);
}
}
if (exceptions.isEmpty()) {
log.info("successfully processed batch with {}", batchItems);
}
else {
log.error("batch processing finished with {} exceptions", exceptions.size());
}
Assertions.assertEquals(1, exceptions.size());
}
finally {
shutDownExecutorService(executorService);
}
}
/**
* Shuts down an ExecutorService in two phases
*/
private void shutDownExecutorService(ExecutorService executorService) {
if (executorService == null) {
return;
}
executorService.shutdown();
try {
if (!executorService.awaitTermination(5, TimeUnit.SECONDS)) {
executorService.shutdownNow();
}
}
catch (InterruptedException e) {
executorService.shutdownNow();
// Restore interrupted state...
Thread.currentThread().interrupt();
}
}
@FunctionalInterface
interface BatchItem {
Boolean run();
}
private static class FutureResult<Boolean> {
private List<Throwable> exceptions = new ArrayList<>();
private Boolean result;
}
}
|
2e55b7642404d1cc26e3e6ce3f7f54239775c2f1
|
[
"Java",
"INI"
] | 3 |
Java
|
NarimanAB/atomikos
|
18ae7e6ac53b749294b0b80457650aea8e6877bd
|
a5630818956330a7a6561a5c4cf62b0dba3e424d
|
refs/heads/master
|
<file_sep>package com.eluctari.sample.graph;
import java.util.*;
import net.jcip.annotations.Immutable;
@Immutable
public final class Graph {
private final Map<Node, Set<Node>> edges;
private final Set<Node> nodes;
public Graph(Set<Node> n, Map<Node, Set<Node>> e) {
// FIXME Is this defensive copy necessary?
HashMap<Node, Set<Node>> edges2 = new HashMap<Node, Set<Node>>();
for (Node n1 : e.keySet()) {
edges2.put(n1, Collections.unmodifiableSet(new HashSet<Node>(e.get(n1))));
}
edges = Collections.unmodifiableMap(edges2);
nodes = Collections.unmodifiableSet(new HashSet<Node>(n));
}
public Set<Node> getNodes() {
return nodes;
}
public Set<Node> getTargets(Node n) {
return edges.get(n);
}
public int size() {
return nodes.size();
}
}
<file_sep>package com.eluctari.sample.graph;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;
import org.junit.*;
import com.eluctari.sample.graph.Graph;
import com.eluctari.sample.graph.GraphFactory;
import com.eluctari.sample.graph.Node;
import java.util.*;
public class GraphTest {
/**
* Attack Graph immutability via the getNodes() method.
*/
@Test public void testImmutable1() {
GraphFactory gf = new GraphFactory();
gf.addNode(new Node("1"));
Graph g = gf.newInstance();
Set<Node> nodeSet = g.getNodes();
try {
nodeSet.add(new Node("2"));
} catch(java.lang.UnsupportedOperationException e) {
return; // Success!
}
fail("Supposedly immutable node set was modified without error.");
}
/**
* Attack Graph immutability via the getTargets() method.
*/
@Test public void testImmutable2() {
GraphFactory gf = new GraphFactory();
Node n1 = new Node("1");
Node n2 = new Node("2");
gf.connectBidirectional(n1, n2);
Graph g = gf.newInstance();
try {
g.getTargets(n1).add(new Node("3"));
} catch(java.lang.UnsupportedOperationException e1) {
try {
g.getTargets(n2).add(new Node("4"));
} catch(java.lang.UnsupportedOperationException e2) {
return; // Success!
}
}
fail("Supposedly immutable node set was modified without error.");
}
/**
* Attack Graph immutability via the GraphFactory. Changing the
* GraphFactory object after it creates a Graph object should not
* change the (immutable) Graph object.
*/
@Test public void testImmutable3() {
GraphFactory gf = new GraphFactory();
Node n1 = new Node("1");
Node n2 = new Node("2");
gf.connectBidirectional(n1, n2);
Graph g = gf.newInstance();
gf.addNode(new Node("3"));
assertThat(g.size(), is(2));
gf.connectUnidirectional(n1, new Node("4"));
assertThat(g.getTargets(n1).size(), is(1));
}
}
<file_sep>/**
*
*/
package com.eluctari.sample.graph;
/**
* @author software
*
*/
import java.util.*;
import net.jcip.annotations.*;
@ThreadSafe
public class GraphFactory {
private Map<Node, Set<Node>> edges;
private Set<Node> nodes;
public GraphFactory() {
edges = new HashMap<Node, Set<Node>>();
nodes = new HashSet<Node>();
}
/**
* This method is only necessary for adding nodes that are not
* connected to other nodes. Otherwise, connectUnidirectional
* and connectBidirectional already adds the nodes to the node
* list.
* @param n the node to be added
*/
@GuardedBy("itself")
public synchronized void addNode(Node n) {
nodes.add(n);
}
@GuardedBy("itself")
public synchronized void connectUnidirectional(Node n1, Node n2) {
nodes.add(n1);
nodes.add(n2);
if (!edges.containsKey(n1)) {
edges.put(n1, new HashSet<Node>());
}
edges.get(n1).add(n2);
}
@GuardedBy("itself")
public synchronized void connectBidirectional(Node n1, Node n2) {
connectUnidirectional(n1, n2);
connectUnidirectional(n2, n1);
}
@GuardedBy("itself")
public synchronized Graph newInstance() {
return new Graph(nodes, edges);
}
}
<file_sep>/**
*
*/
package com.eluctari.sample.graph;
import net.jcip.annotations.Immutable;
/**
* @author software
*
*/
@Immutable
public final class Node {
private final String text;
public Node(String x) {
text = x;
}
@Override
public String toString() {
return text;
}
}
|
42cb47656668f85e684e53f8a1b81e9f161946a1
|
[
"Java"
] | 4 |
Java
|
EluctariLLC/simple-graph
|
049e33cbe3d38a724d17c46f0fb86b93267f867c
|
de252da1859ba8d774b1019af7034a28fea7e235
|
refs/heads/master
|
<repo_name>kuvamdazeus/simple_http_server<file_sep>/server.py
#! /usr/bin/env python3
"""Note: This server uses 8080 as default port"""
import http.server, sys, socketserver, socket, re
args = sys.argv
args.pop(0)
args = " ".join(args)
port_pattern, address_pattern = r"([0-9]+)", r"(^[a-zA-Z][0-9a-zA-Z\.\-_]+)"
# searching for patterns in args (argv) list
server_address = re.search(address_pattern, args)
port = re.search(port_pattern, args)
# default values
default_port = 8080
address = ""
# change values if needed
if server_address != None:
address = server_address.group(1)
if port != None:
default_port = int(port.group(1).strip())
print("Listening on port", default_port)
# defining a simple HTTP request handler, handles requests over HTTP
handler = http.server.SimpleHTTPRequestHandler
try:
tcp_server = socketserver.TCPServer((address, default_port), handler, bind_and_activate=True) # deploying server
except Exception as error:
message = str(error)
if "already in use" in message:
print("\nServer failed to start, please ensure that the website is not opened on your machine or any other, if so, close the tabs and try again")
print("you can fix this problem either by given explanation or by changing the port number by passing the specified as CLI argument")
print("Like this: ./server.py <your-port-number> or ./server.py 7000 <-- example")
else:
print("Error message:", message)
sys.exit(1)
def get_ip_address():
ip = socket.gethostbyname(socket.gethostname())
return ip
def main(): # main function does all required things to bring our new tcp_server on track and running
print("Website: http://{}:{}/".format(get_ip_address(), default_port))
print("Server active")
serve_forever = tcp_server.serve_forever() # runs the server
print(serve_forever)
if __name__ == "__main__":
try:
main()
except KeyboardInterrupt: # saves screen from filling with a long stderr message due to pressing of ctrl-c
print("\nServer closed\n")
<file_sep>/README.md
#### Quick instructions: just give executable permissions to it and type ./server.py in your CLI --have-fun
---------------------
# simple_http_server
-----------------------
## Note: this program uses 8080 as default port for listening on HTTP
## You can change this by using `python server.py <your-specified-port-number>`
### Example: `python server.py 7000` (you've to pass it as a CLI argument)
Steps to setup your own:
1. open CLI (Command Line Interface) of your machine and type cd into cloned git repository "simple_http_server"
2. type "sudo chmod +x server.py", you may have to enter your machine's login password, enter it then press enter
3. now you are ready, type "./server.py" in the CLI whenever you want to start your server
4. to stop the server, go to the running CLI and press "ctrl-c" or "^C" and the message will appear that the server has stopped
---------------------------
to run the website on other machine (other than the deployed TCP server), you ca simply access the website from your machine on
which server is deployed, you can simply type:
the port 8080 will only work if you didn't changed it, if it was changed, you have to enter that port instead of 8080
localhost:8080/
or
127.0.0.1:8080/
Note: you can modify the index.html file and add more files in the same directory
|
6993ae36b0fe0cd5dde313f446fc0f6199c58077
|
[
"Markdown",
"Python"
] | 2 |
Python
|
kuvamdazeus/simple_http_server
|
bfff903329684e872ce95144876cb5ceb1a8351d
|
39a41c5b1a2c1d1ea1adba8d59b6c1c66f236f74
|
refs/heads/master
|
<repo_name>smcrowley8/esu-GameJam<file_sep>/audio_mod.py
from moviepy.video.io.ffmpeg_tools import ffmpeg_extract_subclip
ffmpeg_extract_subclip("shorter_music.mp3", 4, 40, targetname="background.mp3")
'''
for converting .mp3 to .wav in terminal:
ffmpeg -i background.mp3 -ab 160k -ac 2 -ar 44100 -vn audio.wav
'''<file_sep>/setup.py
from cx_Freeze import setup, Executable
import sys
files={"packages":["pygame"],
"include_files":[
"audio.wav",
"enemyDown1.png",
"enemyDown2.png",
"enemyUp1.png",
"enemyUp2.png",
"enemyRight1.png",
"enemyRight2.png",
"enemyLeft1.png",
"enemyLeft2.png",
"playerDown1.png",
"playerDown2.png",
"playerUp1.png",
"playerUp2.png",
"playerRight1.png",
"playerRight2.png",
"playerLeft1.png",
"playerLeft2.png",
"playerAttackDown1.png",
"playerAttackDown2.png",
"playerAttackUp1.png",
"playerAttackUp2.png",
"playerAttackRight1.png",
"playerAttackRight2.png",
"playerAttackLeft1.png",
"playerAttackLeft2.png",
"highScore.txt"
]}
executable=Executable("main.py", base="Win32GUI", targetName="sampleGame.exe")
setup(
name="Only One Action",
version="0.1",
author="<NAME>",
description="ESU GameJam game",
options={"build_exe": files},
executables=[executable]
)<file_sep>/test.py
import pygame
screen=pygame.display.set_mode([720, 720])
screen.fill([255, 255, 255])
red=255
blue=0
green=0
left=50
top=50
width=80
height=80
filled=0
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
def drawBoard():
pygame.draw.rect(screen, white, [0,0,720,720],0)
for i in range(9):
for j in range(9):
pygame.draw.rect(screen, black, [i*80, j*80, width, height], 1)
#pygame.draw.rect(screen, red, [30,50,200,500], 0)
front1Img = pygame.image.load('playerUp1.png')
drawBoard()
pygame.display.flip()
running=True
while running:
for event in pygame.event.get():
if event.type==pygame.QUIT:
running=False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
pygame.draw.rect(screen, red, [30,50,200,500], 0)
if event.key == pygame.K_RIGHT:
drawBoard()
if event.key == pygame.K_UP:
screen.blit(front1Img, (4 * 80, 4 * 80))
pygame.display.flip()
pygame.quit()<file_sep>/build/playGame.sh
#!/bin/bash
cd exe.linux-x86_64-3.6
sh ./sampleGame
<file_sep>/main.py
import pygame
import random
import time
pygame.init()
'''
*********************************** game variables ***********************************
'''
'''
the window is 720 by 720 and divided into a 9x9 board
each sqare is 80x80
square i,j starts at (i*80, j*80)
character x and y correlates to that square
the upper left square is (0,0), the bottom right is (8,8)\
board represents the game board. 9 on the board is an enemy, 1 is the player, 0 is empty
'''
display_width = 1000
display_height = 720
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green=(0,255,0)
purple = (148, 0, 211)
img_width=80
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('only one move at a time')
clock = pygame.time.Clock()
##music stuff
playlist=list()
music='audio.wav'
pygame.mixer.music.load(music)
pygame.mixer.music.queue(music)
class Character:
def __init__(self, x=0, y=0, player=False):
self.attacking=False
if player:
self.back1Img = pygame.image.load('playerDown1.png')
self.back2Img = pygame.image.load('playerDown2.png')
self.front1Img = pygame.image.load('playerUp1.png')
self.front2Img = pygame.image.load('playerUp2.png')
self.left1Img = pygame.image.load('playerLeft1.png')
self.left2Img = pygame.image.load('playerLeft2.png')
self.right1Img = pygame.image.load('playerRight1.png')
self.right2Img = pygame.image.load('playerRight2.png')
self.attackUp1= pygame.image.load('playerAttackUp1.png')
self.attackUp2= pygame.image.load('playerAttackUp2.png')
self.attackDown1= pygame.image.load('playerAttackDown1.png')
self.attackDown2= pygame.image.load('playerAttackDown2.png')
self.attackLeft1= pygame.image.load('playerAttackLeft1.png')
self.attackLeft2= pygame.image.load('playerAttackLeft2.png')
self.attackRight1= pygame.image.load('playerAttackRight1.png')
self.attackRight2= pygame.image.load('playerAttackRight2.png')
else:
self.back1Img = pygame.image.load('enemyDown1.png')
self.back2Img = pygame.image.load('enemyDown2.png')
self.front1Img = pygame.image.load('enemyUp1.png')
self.front2Img = pygame.image.load('enemyUp2.png')
self.left1Img = pygame.image.load('enemyLeft1.png')
self.left2Img = pygame.image.load('enemyLeft2.png')
self.right1Img = pygame.image.load('enemyRight1.png')
self.right2Img = pygame.image.load('enemyRight2.png')
self.direction="up"
self.attacking=False
self.whatImg=0
self.x=x
self.player=player
self.y=y
if player==True:
self.hp=100
else:
self.hp=5
self.dmg=5
def drawSelf(self):
if self.attacking==True: #only true for players
if self.direction=="up":
if self.whatImg==0:
gameDisplay.blit(self.attackUp1, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.attackUp2, (self.x * 80, self.y * 80))
if self.direction=="left":
if self.whatImg==0:
gameDisplay.blit(self.attackLeft1, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.attackLeft2, (self.x * 80, self.y * 80))
if self.direction=="right":
if self.whatImg==0:
gameDisplay.blit(self.attackRight1, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.attackRight2, (self.x * 80, self.y * 80))
if self.direction=="down":
if self.whatImg==0:
gameDisplay.blit(self.attackDown1, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.attackDown2, (self.x * 80, self.y * 80))
else:
if self.direction=="up":
if self.whatImg==0:
gameDisplay.blit(self.front1Img, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.front2Img, (self.x * 80, self.y * 80))
if self.direction=="left":
if self.whatImg==0:
gameDisplay.blit(self.left1Img, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.left2Img, (self.x * 80, self.y * 80))
if self.direction=="right":
if self.whatImg==0:
gameDisplay.blit(self.right1Img, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.right2Img, (self.x * 80, self.y * 80))
if self.direction=="down":
if self.whatImg==0:
gameDisplay.blit(self.back1Img, (self.x * 80, self.y * 80))
else:
gameDisplay.blit(self.back2Img, (self.x * 80, self.y * 80))
#now draw the hp bar
pygame.draw.rect(gameDisplay, black, [self.x*80, self.y*80, 80, 10], 1)
#outline
hpX=80
if self.player==True:
color=green
hpX=int(4*self.hp/5)
else:
color=red
hpx=80
pygame.draw.rect(gameDisplay, color, [self.x*80, self.y*80, hpX, 10], 0)
def getSelf(self, x, y):
if self.x == x and self.y==y:
return self
else:
return None
def isHere(self, x, y):
if self.x == x and self.y == y:
return True
else:
return False
def attack(self, obj):
obj.hp=obj.hp-self.dmg
board=[[0]*9 for _ in range(9)] #10 x 10 board that will be our playable area
player=Character(4,4,player=True)
board[4][4]=1
enemies=[]
numEnemies=3 #will always be 5, when one dies another is made
original_positions=[]
SCORE=0
HIGHSCORE=0
scoreInc=10
killInc=100
pause=False
pauseMsg="PAUSED"
with open('highScore.txt') as f:
lines=f.readlines()
HIGHSCORE=int(lines[0])
#waitCT is used to tell how long its been since the palyer moved
#if player waits too long then enemies start to move anyway
'''
*********************************** game functions ***********************************
'''
def makeEnemies():
x=0
y=0
while len(enemies)<numEnemies:
x=random.randint(0,8)
y=random.randint(0,8)
if (board[x][y]==0) and (abs(x-player.x)>2 and abs(y-player.y)>2):
original_positions.append((x,y))
board[x][y]=9
#break
enemy=Character(x,y)
enemies.append(enemy)
def removeDeadEnemy():
#enemies=[enemy for enemy in enemies if enemy.hp >0]
x=-1
y=-1
for i in range(len(enemies)):
if enemies[i].hp==0:
x=enemies[i].x
y=enemies[i].y
enemies.pop(i)
break
if x>=0 and y>=0:
board[x][y]=0
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text, x, y, size):
largeText = pygame.font.Font('freesansbold.ttf',size)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = (x,y)
gameDisplay.blit(TextSurf, TextRect)
#time.sleep(2)
#game_loop()
def drawBoard():
#draw each inner rectangle
for i in range(9):
for j in range(9):
pygame.draw.rect(gameDisplay, black, [i*80, j*80, 80, 80], 1)
def drawEnemies():
for enemy in enemies:
enemy.drawSelf()
def drawRules():
r1='RULES: '
r2='you and the enemies take turns moving'
r3='you can only do one move per turn'
r4='you can move up, down, left, or right'
r5='move and attack by using arrow keys'
r6='if an enemy is to your left, and you hit left,'
r7='you will attack the enemy'
message_display(r1, 860, 150, 40)
message_display(r2, 860, 180, 10)
message_display(r3, 860, 210, 10)
message_display(r4, 860, 240, 10)
message_display(r5, 860, 270, 10)
message_display(r6, 860, 300, 10)
message_display(r7, 860, 330, 10)
def drawScore():
message_display("SCORE: ", 860, 40, 60)
message_display(str(SCORE), 860, 100, 60)
message_display("High Score: ", 860, 600, 40)
message_display(str(HIGHSCORE), 860, 650, 30)
def drawState():
gameDisplay.fill(white)
drawBoard()
drawEnemies()
player.drawSelf()
drawRules()
drawScore()
if pause==True:
if pauseMsg=="PAUSED":
message_display(pauseMsg, (display_width/2), (display_height/2), 115)
else:
msgs=pauseMsg.split('\n')
h=100
for msg in msgs:
message_display(msg, (display_width/2), h, 60)
h+=100
def updateImgs():
for enemy in enemies:
if enemy.whatImg==1:
enemy.whatImg=0
else:
enemy.whatImg=1
if player.whatImg==1:
player.whatImg=0
else:
player.whatImg=1
def make_enemy_turn():
for enemy in enemies:
xdiff=enemy.x-player.x
ydiff=enemy.y - player.y
if (abs(xdiff)==1 and abs(ydiff)==0) or (abs(xdiff)==0 and abs(ydiff)==1):
enemy.attack(player)
else:
nextX=int(enemy.x)
nextY=int(enemy.y)
if abs(xdiff)==0:
if ydiff<0:
nextY+=1
else:
nextY-=1
elif abs(ydiff)==0:
if xdiff<0:
nextX+=1
else:
nextX-=1
elif abs(xdiff) > abs(ydiff):
if xdiff<0:
nextX+=1
else:
nextX-=1
else:
if ydiff<0:
nextY+=1
else:
nextY-=1
if board[nextX][nextY]==0:
#unoccupioed so move there
if nextX>enemy.x:
enemy.direction="right"
elif nextX<enemy.x:
enemy.direction="left"
elif nextY>enemy.y:
enemy.direction="down"
elif nextY<enemy.y:
enemy.direction="up"
board[enemy.x][enemy.y]=0
enemy.x=nextX
enemy.y=nextY
board[enemy.x][enemy.y]=9
#if not 0 then occupied and cant move there
'''
*********************************** game itself ***********************************
'''
def game_loop():
gameExit = False
player_turn=True
waitCT=0
global pause
global enemies
global SCORE
global HIGHSCORE
global numEnemies
global pauseMsg
global scoreInc
global killInc
makeEnemies()
pause=True #this is for selecting difficulty at the start
pauseMsg="press E for easy\n M for medium\n and H for hard"
pygame.mixer.music.play(-1)
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
with open('highScore.txt', 'w') as f:
f.write(str(HIGHSCORE))
pygame.quit()
quit()
if pause==False:
if player_turn:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.direction="right"
if player.x<8:
#if the spot youre moving too has an enemy, attack
if board[player.x+1][player.y]==9:
for enemy in enemies:
if enemy.isHere(player.x+1, player.y)==True:
player.attack(enemy)
SCORE+=killInc
removeDeadEnemy()
player.attacking=True
else:
player.x+=1
player.attacking=False
player_turn=False
''' used to be this
if waitCT%2==0:
waitCT=0
else:
waitCT=-1
'''
waitCT=abs(waitCT-30)
SCORE+=scoreInc
if event.key == pygame.K_LEFT:
player.direction="left"
if player.x>0:
if board[player.x-1][player.y]==9:
for enemy in enemies:
if enemy.isHere(player.x-1, player.y)==True:
player.attack(enemy)
SCORE+=killInc
removeDeadEnemy()
player.attacking=True
else:
player.x-=1
player.attacking=False
player_turn=False
waitCT=abs(waitCT-30)
SCORE+=scoreInc
if event.key == pygame.K_DOWN:
player.direction="down"
if player.y<8:
if board[player.x][player.y+1]==9:
for enemy in enemies:
if enemy.isHere(player.x, player.y+1)==True:
player.attack(enemy)
SCORE+=killInc
removeDeadEnemy()
player.attacking=True
else:
player.y+=1
player.attacking=False
player_turn=False
waitCT=abs(waitCT-30)
SCORE+=scoreInc
if event.key == pygame.K_UP:
player.direction="up"
if player.y>0:
if board[player.x][player.y-1]==9:
for enemy in enemies:
if enemy.isHere(player.x, player.y-1)==True:
player.attack(enemy)
SCORE+=killInc
removeDeadEnemy()
player.attacking=True
else:
player.y-=1
player.attacking=False
player_turn=False
waitCT=abs(waitCT-30)
SCORE+=scoreInc
if event.type == pygame.KEYDOWN:
if pauseMsg=="PAUSED":
if event.key == pygame.K_p:
pause=not pause
else:
if event.key==pygame.K_e:#easy
scoreInc=10
killInc=100
numEnemies=3
pauseMsg="PAUSED"
pause=False
if event.key==pygame.K_m:#medium
scoreInc=15
killInc=125
numEnemies=5
pauseMsg="PAUSED"
pause=False
if event.key==pygame.K_h:#hard
scoreInc=20
killInc=150
numEnemies=7
pauseMsg="PAUSED"
pause=False
if pause==False:
#do other checks for game related functions
if player_turn==False:
#make the enemies move towards player. if they are adjacent, attack
if waitCT%30==0:
make_enemy_turn()
if player.hp<=0:
gameExit=True
SCORE+=10
if len(enemies)<numEnemies:
makeEnemies()
player_turn=True
if waitCT>600:
#once youve gone 5 sec without moving, enemies will move anyway
waitCT=0
player_turn=False
#after all game related inputs have been read, we update
if waitCT%30==0:
updateImgs()
if HIGHSCORE<SCORE:
HIGHSCORE=int(SCORE)
#print(waitCT)
#re print everything in the game
drawState()
#add final check for boundaries
#
waitCT=waitCT+1
pygame.display.update()
clock.tick(50)#we want 2 frames per second so that the game is a slow turn base
#game is over, replay?
message_display("game over", (display_width/2), (display_height/2), 115)
pygame.display.update()
with open('highScore.txt', 'w') as f:
f.write(str(HIGHSCORE))
time.sleep(2)
game_loop()
pygame.quit()
quit()<file_sep>/flip_images.py
from PIL import Image, ImageDraw
# Load image:
input_image = Image.open("enemyRight2.png")
input_pixels = input_image.load()
# Create output image
output_image = Image.new("RGB", input_image.size)
draw = ImageDraw.Draw(output_image)
# Copy pixels
for x in range(output_image.width):
for y in range(output_image.height):
xp = input_image.width - x - 1
#forhorizontal flip
#yp=input_image.height - y -1
#for virtical flip
draw.point((x, y), input_pixels[xp, y]) #for hor
#draw.point((x,y), input_pixels[x,yp])#for vir
output_image.save("enemyLeft2.png")<file_sep>/scale_image.py
from PIL import Image, ImageDraw
from math import floor
path='playerAttackDown1.png'
'''
first we scale
'''
inImg=Image.open(path)
inPxls=inImg.load()
newSize=(80,80)
outImg=Image.new("RGB", newSize)
draw=ImageDraw.Draw(outImg)
x_scale=inImg.width / outImg.width
y_scale=inImg.height / outImg.height
for x in range(outImg.width):
for y in range(outImg.height):
xp, yp = floor(x*x_scale), floor(y*y_scale)
draw.point((x,y), inPxls[xp,yp])
outImg.save(path)
<file_sep>/make_white_pxl_transluscent.py
from PIL import Image, ImageDraw
from math import floor
path='playerAttackDown1.png'
img=Image.open(path)
img=img.convert("RGBA")
datas=img.getdata()
newData=[]
for item in datas:
if item[0] == 255 and item[1] == 255 and item[2]==255:
newData.append((0,0,0,0))
else:
newData.append(item)
img.putdata(newData)
img.save(path)<file_sep>/replace_pxl_value.py
from PIL import Image, ImageDraw
from math import floor
path='enemyUp2.png'
img=Image.open(path)
img=img.convert("RGBA")
datas=img.getdata()
newData=[]
for item in datas:
if item[0] > 0:
newData.append((0,item[1],item[2],item[3]))
else:
newData.append(item)
img.putdata(newData)
img.save(path)<file_sep>/change_some_pxls.py
from PIL import Image, ImageDraw
from math import floor
import numpy as np
path='playerUp1.png'
img=Image.open(path)
img=img.convert("RGBA")
datas=img.getdata()
print(np.shape(datas))
'''
newData=[]
for i in range(len(datas)):
for j in range(len(datas[i])):
if (i >= 80 and i < len(datas[i][j])) and (j>=40 and j<60):
newData.append((255,255,255))
else:
newData.append(datas[i][j])
img.putdata(newData)
img.save('test.png')
'''
|
fe60ba67ff4f670945f09435e2718aa60f03cb05
|
[
"Python",
"Shell"
] | 10 |
Python
|
smcrowley8/esu-GameJam
|
10792f1619ce8d24b90e0dedd65e7fb61f7e51e3
|
d749391e3678e4ded159c741d85f4ea7fbaac853
|
refs/heads/master
|
<repo_name>achiara311/Lab-2---Room-Calculator<file_sep>/Program.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace RoomCalculator
{
class Program
{
static void Main(string[] args)
{
//input
//1. Prompt
Console.WriteLine("Welcome, please enter the length.");
string lengthOfSnug = Console.ReadLine();
double lengthNumber1 = double.Parse(lengthOfSnug);
Console.WriteLine("Please enter width");
string widthOfSnug = Console.ReadLine();
double widthNumber2 = double.Parse(widthOfSnug);
Console.WriteLine("Please enter height.");
string heightOfSnug = Console.ReadLine();
double heightOfNumber1 = double.Parse(heightOfSnug);
//2. Receive
//Processing
double areaOfSnug = lengthNumber1 * widthNumber2;
double perimeterOfSnug = 2 * (lengthNumber1 + widthNumber2);
double volumeOfSnug = lengthNumber1 * widthNumber2 * heightOfNumber1;
//Output
Console.WriteLine("The Area of the Snug is = {0} in, the perimeter is = {1} in, and the volume is = {2} in.", areaOfSnug, perimeterOfSnug, volumeOfSnug);
Console.WriteLine("Continue? (Y/N)");
string yes = Console.ReadLine();
if (yes == "Y" || yes == "y")
{
Console.WriteLine("Enter the length of the Penthouse.");
string lengthOfPenthouse = Console.ReadLine();
double lengthNumber2 = double.Parse(lengthOfPenthouse);
Console.WriteLine("Please enter width of Penthouse.");
string widthOfPenthouse = Console.ReadLine();
double widthOfNumber2 = double.Parse(widthOfPenthouse);
Console.WriteLine("Please enter the height of the Penthouse.");
string heightOfPenthouse = Console.ReadLine();
double heightOfNumber2 = double.Parse(heightOfPenthouse);
double areaOfPenthouse = lengthNumber2 * widthOfNumber2;
double perimeterOfPenthouse = 2 * (lengthNumber2 + widthOfNumber2);
double volumeOfPenthouse = lengthNumber2 * widthOfNumber2 * heightOfNumber2;
Console.WriteLine("The Area of the Penthouse is = {0} in, the perimeter is = {1} in, and the volume is = {2} in.", areaOfPenthouse, perimeterOfPenthouse, volumeOfPenthouse);
}
else
{
Console.WriteLine("Ok, goodbye.");
}
Console.ReadKey();
}
}
}
|
a1f28c32174e65b69ffc0a3ff86c0e9feb0447d8
|
[
"C#"
] | 1 |
C#
|
achiara311/Lab-2---Room-Calculator
|
d1b3469523d076addc936f7227133fe484429ca4
|
1ea3f354e70c02d28fd5df55e3cb65c0c2f1d67f
|
refs/heads/master
|
<file_sep>
import paho.mqtt.client as mqtt
from subprocess import call
import webbrowser
import os
import signal
import subprocess
def callZoom():
openlink()
call(["node", "index.js"])
def disConnect():
print("stop")
call("exit 1",shell=True)
def openlink():
url = 'http://localhost:3000/'
chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s'
webbrowser.get(chrome_path).open(url)
def on_connect(client, userdata, flags, rc):
print("Connected with Code : " + str(rc))
print("MQTT Connected.")
client.subscribe("demo1")
def on_message(client, userdata, msg):
messageCome = str(msg.payload.decode("utf-8"))
if(messageCome == "start"):
callZoom()
elif(messageCome == "stop"):
disConnect()
else:
print("command not found! ")
if __name__ == '__main__':
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("soldier.cloudmqtt.com", 14222, 60)
client.username_pw_set("obpkkwdc", "1lUnSF15XpWM")
# client.connect("smart-teacher.cloudmqtt.com",1883,60)
# client.username_pw_set("ekrwnxjf","x9OU_vaUyZQJ")
client.loop_forever()
<file_sep># API for create zoom_id and open zoomApp on desktop windows
>
## Getting Started
### Install
Clone the repo using git clone.
` git clone https://github.com/thapakorn613/remoteLab-zoomApi.git`
Install the dependent node modules.
1. ` npm install
2. ` npm install windows-edge
### Config
In the config.js file, input your client API Key & Secret credentials.
```
const config = {
production:{
APIKey : 'Your environment API Key',
APISecret : 'Your environment API Secret'
}
};
```
> Start the node app.
Type node index.js
> Enter your email and view the API's response.
After you submit an email address, Zoom API call and you will be redirected to localhost:3000/userinfo page that displays the API response
### Run Project
-> open cmd
-> "node index.js"
|
06eedbcffd13cadd62002d0630d16aeba9418f8d
|
[
"Markdown",
"Python"
] | 2 |
Python
|
thapakorn613/remoteLab-zoomApi
|
71f31e19df74aff0e29f3c89aaaff2b834c0eaba
|
0bed0868eaa88cf54d7f4ce8b8225ede9d3f6c63
|
refs/heads/master
|
<file_sep># Sparse Matrix with Python 2.7
Create sparse matrix with non-zero elements in it's diagonal.
<file_sep>import random
import numpy as np
size = 5
ub = 7
def ranz():
return [random.randint(1,100) for i in range(0,size)]
def zero():
return [0]*size
c = ranz()+zero()+zero()+zero()+ranz()
outer = []
counter = 0
for j in range(0,ub*size):
inner = []
if j%size == 0:
pola = [0,ub-1]
pola.append(counter)
counter += 1
for i in range(0,ub):
if i in pola:
inner += ranz()
else:
inner += zero()
outer.append(inner)
for i in range(0,len(outer)):
outer[i][i] = -1 * outer[i][i]
outer = np.array(outer)
sparsity = 1.0 - float(np.count_nonzero(outer))/outer.size
print sparsity
print outer
|
7d87b906f4a768f068e4d9de112c59f299cb6aba
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
herukurniawan/sparsematrix
|
21cd092d1eabd7c1afa669eeb3412ed28eb42f0d
|
82fd84393752fce0d79d488470ad18398f4fde94
|
refs/heads/master
|
<file_sep>require 'parser/ruby24'
def traverse(node, visitor)
visitor.__send__(:"on_#{node.type}", node)
node.children.each do |child|
traverse(child, visitor) if child.is_a?(Parser::AST::Node)
end
end
class Visitor
def on_if(node)
cond = node.children.first
if cond.type == :int
warn "Do not use an int literal in condition!!! (#{cond.loc.line}:#{cond.loc.column})"
end
end
def method_missing(name, *args)
if name.to_s.start_with?('on_')
# nothing
else
super
end
end
end
ast = Parser::Ruby24.parse_file(ARGV.first)
traverse(ast, Visitor.new)
<file_sep>if 1
p 'Hello'
end
|
9abb42366c2f94b32e92ad14191fa9e651145221
|
[
"Ruby"
] | 2 |
Ruby
|
pocke/rubykaigi2017
|
ddec55e4bbddc3b8e6766d05d396af6320cae275
|
206a574870e3d184ef2b79dcb77b7b05da0b883e
|
refs/heads/master
|
<file_sep># Mean Value Adjuster
A python class to adjust the mean(average) value of a dataset by weighing each
value based on its z - score. Values closer to the mean are considered "better"
and so are given more weight.
# In ranking systems
Adjusted mean be used to give toll votes less weight.
# Example
```python
import mva
vote_values = [100, 70, 88, 91, 85, 60, 99, 2]
adjuster = mva.Adjuster(vote_values)
adjuster.get_true_mean()
adjuster.get_adjusted_mean()
```
# License
Released under MIT license
<file_sep>"""
Mean Value Adjuster
===================
A python class to adjust the mean (average) value of a dataset by weighing each
value based on its z-score. Values closer to the mean are considered "better"
and so are given more weight.
Usage
-----
Very useful for giving less weight to "troll votes" in rating systems.
Example
-------
>>> values = [100,70,88,91,85,60,99,2]
>>> adjuster = Adjuster(values)
>>> adjuster.get_true_mean()
74.375
>>> adjuster.get_adjusted_mean()
83.54110999572508
"""
from math import cos
from statistics import mean, stdev
class Adjuster:
def __init__(self, ls=[0]):
self.votes = ls
def _apply_weight(self):
mn = mean(self.votes)
sd = stdev(self.votes)
weights = []
for x in self.votes:
z_score = (x - mn) / sd if sd is not 0 else 0
weight = cos(z_score)
if weight < 0:
weight = 0
weights.append({'value': x, 'weight': weight})
return weights
def get_true_mean(self):
return mean(self.votes)
def get_adjusted_mean(self):
weights = self._apply_weight()
sum_value = 0
sum_weight = 0
for item in weights:
sum_value += item['value'] * item['weight']
sum_weight += item['weight']
return sum_value / sum_weight
def main():
import doctest
doctest.testmod()
if __name__ == '__main__':
main()
|
315d84b166ec0adca646fb57ae59c427ca8ee0c9
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
Rayraegah/mean-value-adjuster
|
04cb005998b47770209985d615543235efd82007
|
44264f2ecbe7be6db1929747e18bc864bc34bb63
|
refs/heads/main
|
<repo_name>Jehyeop-Yu/PEGweb<file_sep>/javascript/GameDi_test_list.js
var list1 = ['메인','액션','스포츠','레이싱','인디','시뮬레이션']
var list2 = ['main','Action','Sports','Racing','Indi','Simulation']
var MenuBarList = function(){
for(var i=0; i<list1.length; i++){
document.write('<li onclick="Select(this)" id="'+list2[i]+'">'+list1[i]+'</li>');
// document.write('<li onclick="'+list2[i]+'()">'+list1[i]+'</li>');
}
}
var Select = function(self){
for(var i=0; i<list2.length; i++){
var GET = document.getElementById(self.getAttribute('id')).getAttribute('id');
if(GET==='Action'){
document.querySelector('div.Game-'+list2[0]).style.display="none";
document.querySelector('div.Game-'+list2[1]).style.display="block";
}
else{document.querySelector('div.Game-'+list2[1]).style.display="none";}
if(GET==='Sports'){
document.querySelector('div.Game-'+list2[0]).style.display="none";
document.querySelector('div.Game-'+list2[2]).style.display="block";
}
else{document.querySelector('div.Game-'+list2[2]).style.display="none";}
if(GET==='Racing'){
document.querySelector('div.Game-'+list2[0]).style.display="none";
document.querySelector('div.Game-'+list2[3]).style.display="block";
}
else{document.querySelector('div.Game-'+list2[3]).style.display="none";}
if(GET==='Indi'){
document.querySelector('div.Game-'+list2[0]).style.display="none";
document.querySelector('div.Game-'+list2[4]).style.display="block";
}
else{document.querySelector('div.Game-'+list2[4]).style.display="none";}
if(GET==='Simulation'){
document.querySelector('div.Game-'+list2[0]).style.display="none";
document.querySelector('div.Game-'+list2[5]).style.display="block";
}
else{document.querySelector('div.Game-'+list2[5]).style.display="none";
}
}
}
// var list3=['div.Game-main','div.Game-Action','div.Game-Racing','div.Game-Indi','div.Game-Simulation']
// var clk = document.querySelector(list3[i]).style.display="block";
// for(var i=0; i<list3.length; i++){
// document.write(clk);
// }
// var List = function(self){
// var list3=['div.Game-main','div.Game-Action','div.Game-Sports','div.Game-Racing','div.Game-Indi','div.Game-Simulation']
// for(var i=0; i<list3.length; i++){
// document.querySelector(list3[i]).style.display="block";
// }
// // document.querySelector().style.display="none";
// }
// var Select = function(self){
// var GET = document.getElementById(self.getAttribute('id')).getAttribute('id');
// if(GET==='Action'){
// document.querySelector('div.Game-Action').style.display="block";
// }
// else if(GET==='Sports'){
// document.querySelector('div.Game-Sports').style.display="block";
// }
// else if(GET==='Racing'){
// document.querySelector('div.Game-Racing').style.display="block";
// }
// else if(GET==='Indi'){
// document.querySelector('div.Game-Indi').style.display="block";
// }
// else if(GET==='Simulation'){
// document.querySelector('div.Game-Simulation').style.display="block";
// }
// else{document.querySelector('div.Game-main').style.display="block";
// }
// console.log(GET);
// }
// var Action = function(){
// document.querySelector('div.Game-main').style.display="none";
// document.querySelector('div.Game-Action').style.display="block";
// document.querySelector('div.Game-Sports').style.display="none";
// document.querySelector('div.Game-Racing').style.display="none";
// document.querySelector('div.Game-Indi').style.display="none";
// document.querySelector('div.Game-Simulation').style.display="none";
// }
// var Sports = function(){
// document.querySelector('div.Game-main').style.display="none";
// document.querySelector('div.Game-Action').style.display="none";
// document.querySelector('div.Game-Sports').style.display="block";
// document.querySelector('div.Game-Racing').style.display="none";
// document.querySelector('div.Game-Indi').style.display="none";
// document.querySelector('div.Game-Simulation').style.display="none";
// }
// var Racing = function(){
// document.querySelector('div.Game-main').style.display="none";
// document.querySelector('div.Game-Action').style.display="none";
// document.querySelector('div.Game-Sports').style.display="none";
// document.querySelector('div.Game-Racing').style.display="block";
// document.querySelector('div.Game-Indi').style.display="none";
// document.querySelector('div.Game-Simulation').style.display="none";
// }
// var Indi = function(){
// document.querySelector('div.Game-main').style.display="none";
// document.querySelector('div.Game-Action').style.display="none";
// document.querySelector('div.Game-Sports').style.display="none";
// document.querySelector('div.Game-Racing').style.display="none";
// document.querySelector('div.Game-Indi').style.display="block";
// document.querySelector('div.Game-Simulation').style.display="none";
// }
// var Simulation = function(){
// document.querySelector('div.Game-main').style.display="none";
// document.querySelector('div.Game-Action').style.display="none";
// document.querySelector('div.Game-Sports').style.display="none";
// document.querySelector('div.Game-Racing').style.display="none";
// document.querySelector('div.Game-Indi').style.display="none";
// document.querySelector('div.Game-Simulation').style.display="block";
// }
// var Select = function(){
// var list2 = ['Action','Sport','Racing','Indi','Simulation']
// var list3 = ['Game-main','Game-Action']
// var slt = document.getElementById("Action");
// var cnts = document.querySelector(list3[i]);
// for(var i=0; i<list2.length; i++){
// cnts.style.display="block";
// console.log(i)
// if(slt.clicked == true){
// }
// }
// }
<file_sep>/javascript/연습장.js
var func = function(){
var chb = document.getElementsByTagName('input');
if(document.getElementsByTagName('input')[0].checked){
document.getElementById('MenuList').style.color = "blue";
}else{
document.getElementById('MenuList').style.color = "black";
}
}<file_sep>/javascript/메모장.js
var add = function () {
document.querySelector('#sports').textContent;
}
|
d9dcab5393e3fe564bbe9dbd40d6914f799281e4
|
[
"JavaScript"
] | 3 |
JavaScript
|
Jehyeop-Yu/PEGweb
|
22c8cb53b1b4b3a3df0061ea24dd293a660417b1
|
728af223b5b74826a058bd67e598288fb5a1a0e0
|
refs/heads/master
|
<repo_name>TimRlm/letai<file_sep>/app/src/main/java/timerlan/letai/Osnova/BdTat.java
package timerlan.letai.Osnova;
import java.io.BufferedReader;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashSet;
import java.util.List;
import android.content.ComponentName;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.graphics.Color;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.FrameLayout;
public class BdTat {
private DBHelper mD;
private String TABLE_NAME = "Acount";
private String TABLE_NAME2 = "Aboniment";
private String TABLE_NAME3 = "TarifServices";
private String TABLE_NAME4 = "Map";
private String TABLE_SALE = "Sale";
private String TABLE_Auto = "Auto";
private String LOG_TAG="BDTat";
private SQLiteDatabase db1;
private class DBHelper extends SQLiteOpenHelper {
final static int DB_VER = 8;
final static String DB_NAME = "tattelecom.db";
final String CREATE_TABLE = "CREATE TABLE "+TABLE_NAME+
"( _id INTEGER PRIMARY KEY , IDD INTEGER, Balance VAR CHAR(255),AccountType VAR CHAR(255))";
final String DROP_TABLE = "DROP TABLE IF EXISTS "+TABLE_NAME;
final String CREATE_TABLE2 = "CREATE TABLE "+TABLE_NAME2+
"( _id INTEGER PRIMARY KEY ,AbonName VAR CHAR(255), AbonId INTEGER, Status VAR CHAR(255), Tarif VAR CHAR(255), TarifId INTEGER, Adres VAR CHAR(255), Tel VAR CHAR(50), IDD INTEGER,TogetherAccount VAR CHAR(255))";
final String DROP_TABLE2 = "DROP TABLE IF EXISTS "+TABLE_NAME2;
final String CREATE_TABLE3 = "CREATE TABLE "+TABLE_NAME3+
"( _id INTEGER PRIMARY KEY ,ServiceId INTEGER,ServiceName VAR CHAR(255),ServicePrice INTEGER, ServiceType INTEGER, orderId INTEGER, AbonId INTEGER)";
final String DROP_TABLE3 = "DROP TABLE IF EXISTS "+TABLE_NAME3;
final String CREATE_TABLE4 = "CREATE TABLE "+TABLE_NAME4+
"( _id INTEGER PRIMARY KEY ,address VAR CHAR(4000),monsun VAR CHAR(7000),latitude VAR CHAR(255),longitude VAR CHAR(255))";
final String DROP_TABLE4 = "DROP TABLE IF EXISTS "+TABLE_NAME4;
final String CREATE_Auto = "CREATE TABLE "+TABLE_Auto+
"( _id INTEGER PRIMARY KEY,Log VAR CHAR(255),Pass VAR CHAR(255),SapId VAR CHAR(255))";
final String DROP_Auto = "DROP TABLE IF EXISTS "+TABLE_Auto;
final String CREATE_SALE = "CREATE TABLE "+TABLE_SALE+
"( _id INTEGER PRIMARY KEY ,title VAR CHAR(1000),descrip VAR CHAR(4000),date VAR CHAR(1000),image VAR CHAR(1000),vers VAR CHAR(100))";
final String DROP_SALE = "DROP TABLE IF EXISTS "+TABLE_SALE;
Context mContext;
public DBHelper(Context context) {
super(context, DB_NAME, null, DB_VER);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db)
{
db.execSQL(CREATE_TABLE);
Log.d(LOG_TAG, "Create "+TABLE_NAME);
db.execSQL(CREATE_TABLE2);
Log.d(LOG_TAG, "Create "+TABLE_NAME2);
db.execSQL(CREATE_TABLE3);
Log.d(LOG_TAG, "Create "+TABLE_NAME3);
db.execSQL(CREATE_TABLE4);
Log.d(LOG_TAG, "Create "+TABLE_NAME4);
db.execSQL(CREATE_Auto);
Log.d(LOG_TAG, "Create "+TABLE_Auto);
db.execSQL(CREATE_SALE);
Log.d(LOG_TAG, "Create "+TABLE_SALE);
ContentValues values = new ContentValues();
values.put("Login","none");
values.put("Pass","<PASSWORD>");
db.insert(TABLE_Auto, null, values);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
{
db.execSQL(DROP_TABLE);
Log.d(LOG_TAG, "DROP "+TABLE_NAME);
db.execSQL(DROP_TABLE2);
Log.d(LOG_TAG, "DROP "+TABLE_NAME2);
db.execSQL(DROP_TABLE3);
Log.d(LOG_TAG, "DROP "+TABLE_NAME3);
db.execSQL(DROP_TABLE4);
Log.d(LOG_TAG, "DROP "+TABLE_NAME4);
db.execSQL(DROP_Auto);
Log.d(LOG_TAG, "DROP "+TABLE_Auto);
db.execSQL(DROP_SALE);
Log.d(LOG_TAG, "DROP "+TABLE_SALE);
onCreate(db);
}
}
private void SetTabel2String(Context context,String AbonName,int AbonId,String Status,String Tarif, int TarifId,String Adres,String Tel,int IDD,String TogetherAccount)
{
ContentValues values = new ContentValues();
values.put("AbonName",AbonName);
values.put("AbonId",AbonId);
values.put("Status",Status);
values.put("Tarif",Tarif);
values.put("TarifId",TarifId);
values.put("Adres",Adres);
values.put("Tel",Tel);
values.put("IDD",IDD);
values.put("TogetherAccount",TogetherAccount);
long rowID = db1.insert(TABLE_NAME2, null, values);
Log.d(LOG_TAG, "Inst " + rowID+' '+ AbonName +' '+ AbonId+ " "+Status+' '+Tarif+' '+TarifId+' '+Adres+' '+Tel+' '+IDD);
}
public void SetAuto(Context context,String Login,String Pass,String SapId)
{
Start(context);
db1.delete(TABLE_Auto, null, null);
ContentValues values = new ContentValues();
values.put("Log",Login);
values.put("Pass",Pass);
values.put("SapId",SapId);
long rowID=db1.insert(TABLE_Auto, null, values);
Log.d("LOG", "Inst " + rowID+' '+ Login +' '+ Pass);
End(context);
}
public String[] GetAuto(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_Auto, null, null, null, null, null, null);
String[] s=new String[2];
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("Log");
int balanceColIndex = c.getColumnIndex("Pass");
s[0]=String.valueOf(c.getString(idColIndex));
s[1]=String.valueOf(c.getString(balanceColIndex));
} else
{
s[0]="none";
s[1]="none";
}
Log.d("LOG",s[0]+" "+s[1]);
c.close();
End(context);
return s;
}
public String GetSapId(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_Auto, null, null, null, null, null, null);
String s="";
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("SapId");
s=String.valueOf(c.getString(idColIndex));
}
c.close();
End(context);
return s;
}
private void SetTabel1String(Context context,int dat1,String dat2,String dat3)
{
ContentValues values = new ContentValues();
values.put("IDD", dat1);
values.put("Balance", dat2);
values.put("AccountType", dat3);
long rowID = db1.insert(TABLE_NAME, null, values);
Log.d(LOG_TAG, "Inst " + rowID+' '+ dat1+" "+dat2+" "+dat3);
}
private void SetTabel3String(Context context,int ServiceId, String ServiceName, int ServicePrice, int ServiceType, int orderId,int AbonId)
{
ContentValues values = new ContentValues();
values.put("ServiceId",ServiceId);
values.put("ServiceName",ServiceName);
values.put("ServicePrice",ServicePrice);
values.put("ServiceType",ServiceType);
values.put("orderId",orderId);
values.put("AbonId",AbonId);
long rowID = db1.insert(TABLE_NAME3, null, values);
Log.d(LOG_TAG, "Inst " + rowID+' '+ ServiceId +' '+ ServiceName+ " "+ServicePrice+' '+ServiceType+' '+orderId+' '+AbonId);
}
public String XML(String s,String xml)
{
String s1="</"+s+">";
s="<"+s+">";
String it="null";
if (xml.indexOf(s)>-1) {
Integer a = xml.indexOf(s) + s.length();
Integer a1 = xml.indexOf(s1);
a1 = a1 - a;
it = new String(xml.toCharArray(), a, a1);
if (s.equals("<Balance>")) {
if (it.indexOf(",")>-1) {
try {
it = new String(it.toCharArray(), 0, it.indexOf(",") + 3);
} catch (Exception e) {
it = new String(xml.toCharArray(), a, a1);
}
}
else
if (it.indexOf(".")>-1) {
try {
it = new String(it.toCharArray(), 0, it.indexOf(".") + 3);
} catch (Exception e) {
it = new String(xml.toCharArray(), a, a1);
}
}
}
if (s.equals("<Reason>"))
{
if (it.indexOf("ORA")>-1) {
Integer aa = it.indexOf("*-") + 2;
Integer aa1 = it.indexOf("-*");
aa1 = aa1 - aa;
it = new String(it.toCharArray(), aa, aa1);
}
}
}
return it;
}
private String XMLDel(String s,String xml)
{
Integer a=xml.indexOf(s);
Integer a1=xml.indexOf(s)+s.length();
String it=new String(xml.toCharArray(),0,a);
it=it+new String(xml.toCharArray(),a1,xml.length()-a1);
return it;
}
private void Start(Context context)
{
mD = new DBHelper(context);
db1 = mD.getWritableDatabase();
}
private void Del()
{
db1.delete(TABLE_NAME, null, null);
db1.delete(TABLE_NAME2, null, null);
db1.delete(TABLE_NAME3, null, null);
}
public void Del2(Context context)
{
Start(context);
db1.delete(TABLE_NAME, null, null);
db1.delete(TABLE_NAME2, null, null);
db1.delete(TABLE_NAME3, null, null);
db1.delete(TABLE_Auto, null, null);
End(context);
}
private void Del(int AbonId)
{
int delCount = db1.delete(TABLE_NAME3, null, null);
Log.d(LOG_TAG, "deleted rows count = " + delCount);
}
private void End(Context context)
{
db1.close();
mD.close();
}
public void SetTabel1Date(Context context,String xml) {
String[] Auto=GetAuto(context);
SetAuto(context,Auto[0],Auto[1],XML("SapId",xml));
Start(context);
Del();
String abon=null;
String acount=null;
Log.d(LOG_TAG,"0");
acount = XML("accounts",xml);
while (XML("item",acount)!="null")
{
abon = XML("Abonements",acount);
acount=XMLDel("<Abonements>"+abon+"</Abonements>",acount);
Log.d(LOG_TAG,"1");
int id=0;
try
{
id = Integer.parseInt(XML("AccountId",acount));
}
catch(Exception e)
{
id=0;
}
String bal = XML("Balance",acount).toString();
String AccountType=XML("AccountType",acount).toString();
SetTabel1String(context,id,bal,AccountType);
Log.d(LOG_TAG,"2");
acount=XMLDel("<item>"+XML("item",acount)+"</item>",acount);
while (XML("item",abon)!="null")
{
Log.d(LOG_TAG,"2");
String item=XML("item",abon);
String AbonName=XML("AbonementTypeName",item).toString();
if (AbonName.equals("Мобильная телефония"))
AbonName="Мобильная телефония";
else
if (AbonName.equals("Интернет"))
AbonName="Интернет";
else
if (AbonName.toLowerCase().indexOf("телефония")>-1)
AbonName="Телефония";
else
if (AbonName.toLowerCase().indexOf("телевидение")>-1)
AbonName="Телевидение";
else AbonName="Пакеты услуг";
int AbonId;
try
{
AbonId=Integer.parseInt(XML("AbonnementNumber",item));
}
catch(Exception e)
{
AbonId=0;
}
String Status=XML("Status",item).toString();
String Tarif=XML("TarifPlan",item).toString();
int TarifId;
try
{
TarifId=Integer.parseInt(XML("TarifPlanId",item));
}
catch(Exception e)
{
TarifId=0;
}
String Adres=XML("ConnectionAddress",item).toString();
String Tel=XML("PhoneNumber",item).toString();
String TogetherAccount=XML("TogetherAccount",item).toString();
SetTabel2String(context,AbonName,AbonId,Status,Tarif,TarifId,Adres,Tel,id,TogetherAccount);
abon=XMLDel("<item>"+item+"</item>",abon);
}
}
End(context);
}
public ArrayList<String[]> GetTable2(Context context, String IDD,String AbonName)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, "IDD="+IDD, null, null, null, null);
ArrayList<String[]> l=new ArrayList<String[]> ();
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("IDD");
int AbonNameColIndex = c.getColumnIndex("AbonName");
int AbonIdColIndex = c.getColumnIndex("AbonId");
int StatusColIndex = c.getColumnIndex("Status");
int TarifColIndex = c.getColumnIndex("Tarif");
int TarifIdColIndex = c.getColumnIndex("TarifId");
int AdresColIndex = c.getColumnIndex("Adres");
int TelColIndex = c.getColumnIndex("Tel");
int _id = c.getColumnIndex("_id");
do {
String[] s=new String[9];
s[0]=String.valueOf(c.getInt(idColIndex));
s[1]=String.valueOf(c.getString(AbonNameColIndex));
s[2]=String.valueOf(c.getInt(AbonIdColIndex));
s[3]=String.valueOf(c.getString(StatusColIndex));
s[4]=String.valueOf(c.getString(TarifColIndex));
s[5]=String.valueOf(c.getInt(TarifIdColIndex));
s[6]=String.valueOf(c.getString(AdresColIndex));
s[7]=String.valueOf(c.getString(TelColIndex));
s[8]=String.valueOf(c.getInt(_id));
if (s[1].equals(AbonName)) l.add(s);
} while (c.moveToNext());
} else
Log.d(LOG_TAG, "0 rows");
c.close();
return l;
}
public String Balance(Context context, String IDD)
{
String bal="";
Start(context);
Cursor c = db1.query(TABLE_NAME, null, "IDD="+IDD, null, null, null, null);
if (c.moveToFirst()) {
int BalanceIndex = c.getColumnIndex("Balance");
bal=String.valueOf(c.getString(BalanceIndex));
}
c.close();
return bal;
}
public ArrayList<String[]> GetTable2(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, null, null, null, null, null);
ArrayList<String[]> l=new ArrayList<String[]> ();
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("IDD");
int AbonNameColIndex = c.getColumnIndex("AbonName");
int AbonIdColIndex = c.getColumnIndex("AbonId");
int StatusColIndex = c.getColumnIndex("Status");
int TarifColIndex = c.getColumnIndex("Tarif");
int TarifIdColIndex = c.getColumnIndex("TarifId");
int AdresColIndex = c.getColumnIndex("Adres");
int TelColIndex = c.getColumnIndex("Tel");
int _id = c.getColumnIndex("_id");
do {
String[] s=new String[9];
s[0]=String.valueOf(c.getInt(idColIndex));
s[1]=String.valueOf(c.getString(AbonNameColIndex));
s[2]=String.valueOf(c.getInt(AbonIdColIndex));
s[3]=String.valueOf(c.getString(StatusColIndex));
s[4]=String.valueOf(c.getString(TarifColIndex));
s[5]=String.valueOf(c.getInt(TarifIdColIndex));
s[6]=String.valueOf(c.getString(AdresColIndex));
s[7]=String.valueOf(c.getString(TelColIndex));
s[8]=String.valueOf(c.getInt(_id));
l.add(s);
} while (c.moveToNext());
} else
Log.d(LOG_TAG, "0 rows");
c.close();
return l;
}
public ArrayList<String> GetAbonNameHash(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, null, null, "AbonName", null, null);
ArrayList<String> l = new ArrayList<String>();
l.add("Мобильная телефония");
if (c.moveToFirst()) {
int AbonNameColIndex = c.getColumnIndex("AbonName");
do {
String s=String.valueOf(c.getString(AbonNameColIndex));
if (l.contains(s)==false) l.add(s);
} while (c.moveToNext());
}
c.close();
End(context);
return l;
}
public ArrayList<String> GetAbonNameHash(Context context,String AbonId)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, null, null, null, null, null);
ArrayList<String> l = new ArrayList<String>();
int AbonNameColIndex = c.getColumnIndex("AbonName");
int AbonIdColIndex = c.getColumnIndex("IDD");
while (c.moveToNext()) {
if (String.valueOf(c.getString(AbonIdColIndex)).equals(AbonId))
{
String s=String.valueOf(c.getString(AbonNameColIndex));
if (l.contains(s)==false) l.add(s);
}
}
if (l.contains("Мобильная телефония"))
{
l.set(l.indexOf("Мобильная телефония"), l.get(0));
l.set(0, "Мобильная телефония");
}
c.close();
End(context);
return l;
}
public ArrayList<String[]> GetTable1(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_NAME, null, null, null, null, null, null);
ArrayList<String[]> l=new ArrayList<String[]> ();
if (c.moveToFirst()) {
int idColIndex = c.getColumnIndex("IDD");
int balanceColIndex = c.getColumnIndex("Balance");
int AccountTypeColIndex = c.getColumnIndex("AccountType");
do {
String[] s=new String[3];
s[0]=String.valueOf(c.getInt(idColIndex));
s[1]=String.valueOf(c.getString(balanceColIndex));
s[2]=String.valueOf(c.getString(AccountTypeColIndex));
l.add(s);
} while (c.moveToNext());
} else
Log.d(LOG_TAG, "0 rows");
c.close();
End(context);
return l;
}
public ArrayList<String[]> GetTable3(Context context,String abonid)
{
Start(context);
Cursor c = db1.query(TABLE_NAME3, null, null, null, null, null, "orderId DESC");
ArrayList<String[]> l=new ArrayList<String[]> ();
if (c.moveToFirst()) {
int ServiceIdColIndex = c.getColumnIndex("ServiceId");
int ServiceNameColIndex = c.getColumnIndex("ServiceName");
int ServicePriceColIndex = c.getColumnIndex("ServicePrice");
int ServiceTypeColIndex = c.getColumnIndex("ServiceType");
int orderIdColIndex = c.getColumnIndex("orderId");
int AbonIdColIndex = c.getColumnIndex("AbonId");
int _id = c.getColumnIndex("_id");
do {
Log.d(LOG_TAG,abonid+ " " + c.getInt(AbonIdColIndex));
if (c.getInt(AbonIdColIndex)==Integer.parseInt(abonid))
{
String[] s=new String[7];
s[0]=String.valueOf(c.getInt(ServiceIdColIndex));
s[1]=String.valueOf(c.getString(ServiceNameColIndex));
s[2]=String.valueOf(c.getInt(ServicePriceColIndex));
s[3]=String.valueOf(c.getInt(ServiceTypeColIndex));
s[4]=String.valueOf(c.getInt(orderIdColIndex));
s[5]=String.valueOf(c.getInt(AbonIdColIndex));
s[6]=String.valueOf(c.getInt(_id));
l.add(s);
Log.d(LOG_TAG, s[1]+" "+ abonid+ " " + s[2]);
}
} while (c.moveToNext());
}
else
c.close();
End(context);
return l;
}
public ArrayList<String> HashTable3(Context context,String abonid)
{
Start(context);
Cursor c = db1.query(TABLE_NAME3, null, null, null, null, null, null);
ArrayList<String> l=new ArrayList<String> ();
int ServiceTypeColIndex = c.getColumnIndex("ServiceType");
int AbonIdColIndex = c.getColumnIndex("AbonId");
while (c.moveToNext())
{
if (c.getInt(AbonIdColIndex)==Integer.parseInt(abonid))
{
if (l.contains(String.valueOf(c.getInt(ServiceTypeColIndex)))==false)
l.add(String.valueOf(c.getInt(ServiceTypeColIndex)));
Log.d("LOGG", String.valueOf(c.getInt(ServiceTypeColIndex)));
}
}
c.close();
End(context);
return l;
}
public void SetTabel3Date(Context context,String xml,int AbonId)
{
Start(context);
Del(AbonId);
String tarif=XML("TarifServices",xml);
while (XML("item",tarif)!="null")
{
String item=XML("item",tarif);
int ServiceId;
try
{
ServiceId=Integer.parseInt(XML("ServiceId",item));
}
catch(Exception e)
{
ServiceId=0;
}
String ServiceName=XML("ServiceName",item).toString();
int ServicePrice;
try
{
ServicePrice=Integer.parseInt(XML("ServicePrice",item));
}
catch(Exception e)
{
ServicePrice=0;
}
int ServiceType;
try
{
ServiceType=Integer.parseInt(XML("ServiceType",item));
}
catch(Exception e)
{
ServiceType=0;
}
int orderId;
try
{
orderId=Integer.parseInt(XML("orderId",item));
}
catch(Exception e)
{
orderId=0;
}
SetTabel3String(context,ServiceId, ServiceName, ServicePrice, ServiceType, orderId, AbonId);
tarif=XMLDel("<item>"+item+"</item>",tarif);
}
End(context);
}
public void UpdateTabel3(Context context,String ServiceId,int orderid)
{
Start(context);
ContentValues cv = new ContentValues();
cv.put("orderId", orderid);
String s[]=new String[1];
s[0]=ServiceId;
int updCount = db1.update(TABLE_NAME3, cv, "ServiceId = ?", s);
Log.d(LOG_TAG, "updated rows count = " + updCount);
End(context);
}
public String Tel(Context context, String IDD)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, "IDD="+IDD, null, null, null, null);
int TelColIndex = c.getColumnIndex("Tel");
String s="null";
while (c.moveToNext())
{
if (String.valueOf(c.getString(TelColIndex)).indexOf("null")==-1) s=String.valueOf(c.getString(TelColIndex));
}
c.close();
return s;
}
public String Adres(Context context, String IDD)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, "AbonId="+IDD, null, null, null, null);
int AdresColIndex = c.getColumnIndex("Adres");
String s="null";
while (c.moveToNext())
{
if (String.valueOf(c.getString(AdresColIndex)).indexOf("null")==-1) s=String.valueOf(c.getString(AdresColIndex));
}
c.close();
return s;
}
public String Adres(Context context, String IDD,String q)
{
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, "IDD="+IDD, null, null, null, null);
int AdresColIndex = c.getColumnIndex("Adres");
String s="null";
while (c.moveToNext())
{
if (String.valueOf(c.getString(AdresColIndex)).indexOf("null")==-1) s=String.valueOf(c.getString(AdresColIndex));
if (s.indexOf("г.")>-1) break;
}
c.close();
return s;
}
public String[] GetData3(Context context,String ServiceId) {
Start(context);
Cursor c = db1.query(TABLE_NAME3, null,"ServiceId="+ServiceId, null, null, null, null);
String[] s=new String[7];
if (c.moveToFirst()) {
int ServiceIdColIndex = c.getColumnIndex("ServiceId");
int ServiceNameColIndex = c.getColumnIndex("ServiceName");
int ServicePriceColIndex = c.getColumnIndex("ServicePrice");
int ServiceTypeColIndex = c.getColumnIndex("ServiceType");
int orderIdColIndex = c.getColumnIndex("orderId");
int AbonIdColIndex = c.getColumnIndex("AbonId");
int _id = c.getColumnIndex("_id");
s[0]=String.valueOf(c.getInt(ServiceIdColIndex));
s[1]=String.valueOf(c.getString(ServiceNameColIndex));
s[2]=String.valueOf(c.getInt(ServicePriceColIndex));
s[3]=String.valueOf(c.getInt(ServiceTypeColIndex));
s[4]=String.valueOf(c.getInt(orderIdColIndex));
s[5]=String.valueOf(c.getInt(AbonIdColIndex));
s[6]=String.valueOf(c.getInt(_id));
Log.d(LOG_TAG, s[1]+" "+ ServiceId + " " + s[2]);
}
c.close();
End(context);
return s;
}
public void SetTabel4Date(Context context,String xml)
{
Start(context);
db1.delete(TABLE_NAME4, null, null);
String ttk=xml;
while (XML("salesoffices",ttk)!="null")
{
String item=XML("salesoffices",ttk);
String address=XML("address",item);
String monsun="Часы работы:\nБудни: "+XML("monfri",item)+";\nСуббота: "+XML("sat",item)+";\nВоскресенье: "+XML("sun",item)+".";
String latitude=XML("latitude",item);;
String longitude=XML("longitude",item);;
SetTabel4String(context,address, monsun,latitude, longitude);
ttk=XMLDel("<salesoffices>"+item+"</salesoffices>",ttk);
}
while (XML("mobileoffice",ttk)!="null")
{
String item=XML("mobileoffice",ttk);
String address=XML("address",item);
String monsun="Часы работы:\nБудни: "+XML("routine",item)+";\nСуббота: "+XML("routine",item)+";\nВоскресенье: "+XML("routine",item)+".";
String latitude=XML("lat",item);;
String longitude=XML("lng",item);;
SetTabel4String(context,address, monsun,latitude, longitude);
ttk=XMLDel("<mobileoffice>"+item+"</mobileoffice>",ttk);
}
End(context);
}
private void SetTabel4String(Context context,String address,String monsun,String latitude,String longitude)
{
ContentValues values = new ContentValues();
values.put("address",address);
values.put("monsun",monsun);
values.put("latitude",latitude);
values.put("longitude",longitude);
long rowID = db1.insert(TABLE_NAME4, null, values);
Log.d(LOG_TAG, "Inst " + rowID+' '+ address+' '+monsun+' '+latitude+' '+longitude);
}
public ArrayList<String[]> GetTable4(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_NAME4, null, null, null, null, null, null);
ArrayList<String[]> l=new ArrayList<String[]> ();
int addressColIndex = c.getColumnIndex("address");
int monsunColIndex = c.getColumnIndex("monsun");
int latitudeColIndex = c.getColumnIndex("latitude");
int longitudeColIndex = c.getColumnIndex("longitude");
while (c.moveToNext()) {
String[] s=new String[4];
s[0]=c.getString(addressColIndex);
s[1]=c.getString(monsunColIndex);
s[2]=c.getString(latitudeColIndex);
s[3]=c.getString(longitudeColIndex);
l.add(s);
}
c.close();
return l;
}
public ArrayList<String[]> GetInfTar(Context context,String xml)
{
ArrayList<String[]> inf = new ArrayList<String[]>();
String[] infS = new String[5];
String currentTariff = XML("currentTariff", xml);
infS[0] = XML("irbisCode", currentTariff);
infS[1] = XML("title", currentTariff);
infS[2] = XML("shortDescription", currentTariff);
infS[3] = XML("newPrice", currentTariff);
infS[4] = XML("sizing", currentTariff);
String Mes="";
if (XML("changeCost", currentTariff).equals("0")==false)
Mes="Смена тарифного плана стоит 150 рублей, так как после предыдушей смены тарифного плана прошло менее 30 дней!";
inf.add(infS);
if (XML("request", xml) != "null") {
String xml2 = xml;
String request = XML("request", xml);
while (XML("availableTariff", xml2) != "null") {
String availableTariff = XML("availableTariff", xml2);
if (XML("title", availableTariff).equals(XML("title", request))) {
infS = new String[7];
infS[0] = XML("irbisCode", availableTariff);
infS[1] = XML("title", availableTariff);
infS[2] = XML("shortDescription", availableTariff);
infS[3] = XML("newPrice", availableTariff);
infS[4] = XML("sizing", availableTariff);
infS[5] = XML("date", request);
infS[6] = XML("id", request);
inf.add(infS);
xml = XMLDel("<availableTariff>" + availableTariff + "</availableTariff>", xml);
}
xml2 = XMLDel("<availableTariff>" + availableTariff + "</availableTariff>", xml2);
}
} else {
inf.add(new String[0]);
}
while (XML("availableTariff", xml) != "null") {
String availableTariff = XML("availableTariff", xml);
infS = new String[6];
infS[0] = XML("irbisCode", availableTariff);
infS[1] = XML("title", availableTariff);
infS[2] = XML("shortDescription", availableTariff);
infS[3] = XML("newPrice", availableTariff);
infS[4] = XML("sizing", availableTariff);
infS[5] = Mes;
inf.add(infS);
xml = XMLDel("<availableTariff>" + availableTariff + "</availableTariff>", xml);
}
return inf;
}
private String OstatocParser(String ost){
String[] ostSplit=ost.split(" ");
try {
return ostSplit[0] + " "+ostSplit[3];
}
catch (Exception e)
{return ostSplit[0];}
}
public ArrayList<String> GetOstat(String xml) {
ArrayList<String> inf=new ArrayList<String>();
String currentTariff=xml;
if ((XML("minutes",currentTariff)=="null") && (XML("traffic",currentTariff)=="null") && (XML("sms",currentTariff)=="null") && (XML("mms",currentTariff)=="null"))
inf.add("0");
else
{
if (XML("minutes",currentTariff)=="null") inf.add("0 0"); else inf.add(OstatocParser(XML("minutes",currentTariff)));
if (XML("traffic",currentTariff)=="null") inf.add("0 0"); else inf.add(OstatocParser(XML("traffic",currentTariff)));
if (XML("sms",currentTariff)=="null") inf.add("0 0"); else inf.add(OstatocParser(XML("sms",currentTariff)));
if (XML("mms",currentTariff)=="null") inf.add("0 0"); else inf.add(OstatocParser(XML("mms",currentTariff)));
}
return inf;
}
public void UpdBalance(Context context,String xml){
Start(context);
while (XML("Account",xml)!="null")
{
String acount=XML("Account",xml);
String id= XML("AccountId",acount);
String bal = XML("Balance",acount);
ContentValues cv = new ContentValues();
cv.put("Balance",bal);
db1.update(TABLE_NAME, cv, "IDD = ?",new String[] { id });
xml=XMLDel("<Account>"+acount+"</Account>",xml);
}
End(context);
}
public String[] GetVmesteAbonId(Context context, String LicId ) {
String[] vmeste=new String[2];
Start(context);
Cursor c = db1.query(TABLE_NAME2, null, "IDD="+LicId , null, null, null, null);
if (c.moveToFirst()) {
int AbonIdColIndex = c.getColumnIndex("AbonId");
int TogColIndex = c.getColumnIndex("TogetherAccount");
vmeste[0]=String.valueOf(c.getInt(AbonIdColIndex));
vmeste[1]=String.valueOf(c.getString(TogColIndex));
}
c.close();
End(context);
return vmeste;
}
public void UpdVmeste(Context context,String AbonId, String LicId){
Start(context);
ContentValues cv = new ContentValues();
cv.put("TogetherAccount",LicId);
db1.update(TABLE_NAME2, cv, "AbonId = ?",new String[] { AbonId });
End(context);
}
public String TelPars(String Tel) {
try {
return "+7 " + Tel.substring(0, 3) + " " + Tel.substring(3, 6) + " " + Tel.substring(6, 8) + " " + Tel.substring(8, 10);
}
catch (Exception e)
{
return Tel;
}
}
public void EnabledAllView(FrameLayout myLayout,boolean bool) {
for (int i = 0; i < myLayout.getChildCount(); i++) {
myLayout.getChildAt(i).setBackgroundColor(Color.BLUE);
}
}
public boolean AsynkTask(Context context){
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(context);
String save = sPref.getString("AsynkTask","0");
if (save.equals("1")) return false;
else return true;
}
public void AsynkTask(Context context,String k) {
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(context);
SharedPreferences.Editor ed = sPref.edit();
ed.putString("AsynkTask", k);
ed.putString("AsynkTask2", k);
ed.commit();
}
public boolean AsynkTask2(Context context){
SharedPreferences sPref = PreferenceManager.getDefaultSharedPreferences(context);
String save = sPref.getString("AsynkTask2","0");
if (save.equals("1")) return true;
else return false;
}
public String OrderString(Context context, String AbonId)
{
Start(context);
Cursor c = db1.query(TABLE_NAME3, null, "AbonId="+AbonId+" and orderId>0", null, null, null, null);
int orderIdColIndex = c.getColumnIndex("orderId");
String s="0;";
while (c.moveToNext())
{
if (s.equals("0;")) s="";
s+=String.valueOf(c.getInt(orderIdColIndex))+";";
}
c.close();
return s;
}
public void KeyBoard_Hide(MainActivity Main){
InputMethodManager imm = (InputMethodManager) Main.getSystemService(Main.getApplicationContext().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(Main.headerView.getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);
}
public void SetTabel_SALE(Context context,String xml)
{
Start(context);
db1.delete(TABLE_SALE, null, null);
String ttk=xml;
while (XML("offer",ttk)!="null")
{
String item=XML("offer",ttk);
String title=XML("title",item);
String date="Срок действия акции: с "+XML("startDate",item)+" до "+XML("endDate",item);
String shortDescription=XML("shortDescription",item);;
String image=XML("image",item);;
SetTabel_SALE_String(context,title, shortDescription,date, image);
ttk=XMLDel("<offer>"+item+"</offer>",ttk);
}
End(context);
}
private void SetTabel_SALE_String(Context context,String title,String shortDescription,String date,String image)
{
ContentValues values = new ContentValues();
values.put("title",title);
values.put("descrip",shortDescription);
values.put("date",date);
image="http://letai.ru" + XMLDel("http://192.168.100.192:7003",image);
values.put("image",image);
Calendar c = Calendar.getInstance();
String vers=String.valueOf(c.get(Calendar.DATE))+"."+String.valueOf(c.get(Calendar.MONTH))+"."+String.valueOf(c.get(Calendar.YEAR));
values.put("vers",vers);
long rowID = db1.insert(TABLE_SALE, null, values);
Log.d(LOG_TAG, "Inst " + rowID+' '+ title+' '+shortDescription+' '+date+' '+image+" "+vers);
}
public boolean SALE_vers(Context context)
{
boolean bol=false;
Start(context);
Cursor c = db1.query(TABLE_SALE, null, null, null, null, null, null);
int vers_ColIndex = c.getColumnIndex("vers");
Calendar cal = Calendar.getInstance();
String vers=String.valueOf(cal.get(Calendar.DATE))+"."+String.valueOf(cal.get(Calendar.MONTH))+"."+String.valueOf(cal.get(Calendar.YEAR));
if (c.moveToNext())
{
if (vers.equals(String.valueOf(c.getString(vers_ColIndex)))) bol=true;
}
c.close();
return bol;
}
public ArrayList<String[]> Get_SALE(Context context)
{
Start(context);
Cursor c = db1.query(TABLE_SALE, null, null, null, null, null, null);
ArrayList<String[]> l=new ArrayList<String[]> ();
int title_ColIndex = c.getColumnIndex("title");
int descrip_ColIndex = c.getColumnIndex("descrip");
int date_ColIndex = c.getColumnIndex("date");
int image_ColIndex = c.getColumnIndex("image");
while (c.moveToNext()) {
String[] s=new String[4];
s[0]=c.getString(title_ColIndex);
s[1]=c.getString(descrip_ColIndex);
s[2]=c.getString(date_ColIndex);
s[3]=c.getString(image_ColIndex);
l.add(s);
}
c.close();
return l;
}
}
<file_sep>/app/src/main/java/timerlan/letai/Usl/UslFrag.java
package timerlan.letai.Usl;
import java.util.ArrayList;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.LinearLayout;
import timerlan.letai.Licefie.LicFrag;
import timerlan.letai.Osnova.BdTat;
import timerlan.letai.R;
import timerlan.letai.Tarif.TarifFrag;
public class UslFrag extends Fragment {
String Login,LicId,AbonId;
View rootView;
BdTat bd=new BdTat();
ArrayList<String> hash;
ArrayList<String[]> T3;
LinearLayout t1,t2,t3,t4,t5,t6,t7;
LinearLayout l1,l2,l3,l4,l5,l6,l7;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragusl, container, false);
Bundle b = getArguments();
Login = b.getString("Login");
LicId = b.getString("LicId");
AbonId = b.getString("AbonId");
t1=(LinearLayout) rootView.findViewById(R.id.bezTab);
t2=(LinearLayout) rootView.findViewById(R.id.antTab);
t3=(LinearLayout) rootView.findViewById(R.id.uscTab);
t4=(LinearLayout) rootView.findViewById(R.id.sipTab);
t5=(LinearLayout) rootView.findViewById(R.id.ipTab);
t6=(LinearLayout) rootView.findViewById(R.id.mobTab);
t7=(LinearLayout) rootView.findViewById(R.id.drTab);
l1=(LinearLayout) rootView.findViewById(R.id.t1);
l2=(LinearLayout) rootView.findViewById(R.id.t2);
l3=(LinearLayout) rootView.findViewById(R.id.t3);
l4=(LinearLayout) rootView.findViewById(R.id.t4);
l5=(LinearLayout) rootView.findViewById(R.id.t5);
l6=(LinearLayout) rootView.findViewById(R.id.t6);
l7=(LinearLayout) rootView.findViewById(R.id.t7);
ArrayList<LinearLayout> KL=new ArrayList<LinearLayout>();
KL.add(l7);KL.add(l1);KL.add(l2);KL.add(l3);KL.add(l4);KL.add(l5);KL.add(l6);
t1.setOnClickListener(lis);
t2.setOnClickListener(lis);
t3.setOnClickListener(lis);
t4.setOnClickListener(lis);
t5.setOnClickListener(lis);
t6.setOnClickListener(lis);
t7.setOnClickListener(lis);
hash=bd.HashTable3(rootView.getContext(), AbonId);
hash.remove("0");
if (hash.contains(String.valueOf(1))) t1.setVisibility(View.VISIBLE);
if (hash.contains(String.valueOf(2))) t2.setVisibility(View.VISIBLE);
if (hash.contains(String.valueOf(3))) t3.setVisibility(View.VISIBLE);
if (hash.contains(String.valueOf(4))) t4.setVisibility(View.VISIBLE);
if (hash.contains(String.valueOf(5))) t5.setVisibility(View.VISIBLE);
if (hash.contains(String.valueOf(6))) t6.setVisibility(View.VISIBLE);
//if (hash.contains(String.valueOf(0))) t7.setVisibility(View.VISIBLE);
T3=bd.GetTable3(rootView.getContext(), AbonId);
LinearLayout.LayoutParams p2=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,Conv(10));
KL.get(Integer.parseInt(hash.get(0))).setLayoutParams(p2);
fragm(Integer.parseInt(hash.get(0)));
return rootView;
}
public void onBackPressed(){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
TarifFrag Fragment = new TarifFrag();
Bundle bundle = new Bundle();
bundle.putString("Login", Login);
bundle.putString("LicId", LicId);
Fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.frgmCont, Fragment,"TarifFrag");
fragmentTransaction.commit();
}
OnClickListener lis=new OnClickListener(){
@Override
public void onClick(View v) {
LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,Conv(10));
p.topMargin=Conv(5);
LinearLayout.LayoutParams p2=new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,Conv(10));
l1.setLayoutParams(p);
l2.setLayoutParams(p);
l3.setLayoutParams(p);
l4.setLayoutParams(p);
l5.setLayoutParams(p);
l6.setLayoutParams(p);
l7.setLayoutParams(p);
switch(v.getId())
{
case R.id.bezTab:
{
l1.setLayoutParams(p2);
fragm(1);
break;
}
case R.id.antTab:
{
l2.setLayoutParams(p2);
fragm(2);
break;
}
case R.id.uscTab:
{
l3.setLayoutParams(p2);
fragm(3);
break;
}
case R.id.sipTab:
{
l4.setLayoutParams(p2);
fragm(4);
break;
}
case R.id.ipTab:
{
l5.setLayoutParams(p2);
fragm(5);
break;
}
case R.id.mobTab:
{
l6.setLayoutParams(p2);
fragm(6);
break;
}
case R.id.drTab:
{
l7.setLayoutParams(p2);
fragm(0);
break;
}
}
}};
public int Conv(int px)
{
return Math.round(px* rootView.getResources().getDisplayMetrics().density);
}
public void fragm(int k)
{
LinearLayout l=(LinearLayout) rootView.findViewById(R.id.UslCont);
l.removeAllViews();
for(int i=0;i<T3.size();i++)
{
if(Integer.parseInt(T3.get(i)[3])==k)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
UslEx Fragment = new UslEx();
Bundle bundle = new Bundle();
bundle.putString("Login", Login);
bundle.putString("ServiceId", T3.get(i)[0]);
bundle.putString("AbonId",AbonId);
Fragment.setArguments(bundle);
fragmentTransaction.add(R.id.UslCont, Fragment,"UslCont");
fragmentTransaction.commit();
}
}
}
}
<file_sep>/app/src/main/java/timerlan/letai/Map/Map_Two.java
package timerlan.letai.Map;
import android.app.Fragment;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import timerlan.letai.Osnova.BdTat;
import timerlan.letai.Osnova.MainActivity;
import timerlan.letai.R;
public class Map_Two extends Fragment {
private static View rootview;
LinearLayout l;
private static GoogleMap mMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootview = (FrameLayout) inflater.inflate(R.layout.map_two, container, false);
return rootview;
}
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
mMap = ((SupportMapFragment) MainActivity.mapFragmentManager.findFragmentById(R.id.location_map)).getMap();
if (mMap != null) {
mMap.setMyLocationEnabled(true);
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(55.78874, 49.12214), 12));
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Toast toast = Toast.makeText(rootview.getContext(),
marker.getTitle() + "\n" + XMLDel("Чтобы узнать часы работы нажмите на блок\n", marker.getSnippet()), Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
});
BdTat bd = new BdTat();
if (bd.GetTable4(view.getContext()).size() == 0)
{
LinearLayout l = (LinearLayout) getActivity().findViewById(R.id.ll);
l.setVisibility(View.VISIBLE);
MyTask mt=new MyTask();
mt.execute("");
}
else setUpMap();
}
}
@Override
public void onDestroyView() {
super.onDestroyView();
try {
if (mMap != null) {
MainActivity.mapFragmentManager.beginTransaction()
.remove(MainActivity.mapFragmentManager.findFragmentById(R.id.location_map)).commit();
mMap = null;
}
} catch (Exception e) {
}
}
private static void setUpMap() {
BdTat bd = new BdTat();
ArrayList<String[]> point = bd.GetTable4(rootview.getContext());
for (int i = 0; i < point.size(); i++) {
Double latitude = Double.valueOf(point.get(i)[2]);
Double longitude = Double.valueOf(point.get(i)[3]);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(point.get(i)[0])
.snippet("Чтобы узнать часы работы нажмите на блок\n" + point.get(i)[1])
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
}
}
public String XMLDel(String s, String xml) {
Integer a = xml.indexOf(s);
Integer a1 = xml.indexOf(s) + s.length();
String it = new String(xml.toCharArray(), 0, a);
it = it + new String(xml.toCharArray(), a1, xml.length() - a1);
return it;
}
class MyTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params)
{
XXX();
return "";
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
YYY();
}
}
void XXX(){
AssetManager assetManager = rootview.getResources().getAssets();
InputStream input;
String text = "";
try {
input = assetManager.open("Map.txt");
int size = input.available();
byte[] buffer = new byte[size]; input.read(buffer); input.close();
text = new String(buffer);
Log.d("Exx",text+"3");
} catch (Exception e) {
Log.d("Exx",e.getMessage());
}
BdTat bd=new BdTat();
bd.SetTabel4Date(rootview.getContext(),text);
}
void YYY(){
Map f=(Map) MainActivity.fragmentManager.findFragmentByTag("Map");
if (f != null && f.isVisible()) {
LinearLayout l = (LinearLayout) getActivity().findViewById(R.id.ll);
l.setVisibility(View.GONE);
setUpMap();
}
}
}<file_sep>/.gradle/2.14.1/taskArtifacts/cache.properties
#Tue Aug 16 08:08:48 GMT+03:00 2016
<file_sep>/app/src/main/java/timerlan/letai/Tarif/TarifExFrag.java
package timerlan.letai.Tarif;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import timerlan.letai.Osnova.BdTat;
import timerlan.letai.R;
import timerlan.letai.Usl.UslFrag;
public class TarifExFrag extends Fragment {
String Login,LicId,Tarif;
TextView balance,tarifname;
View rootView;
BdTat bd=new BdTat();
public int Conv(int px)
{
return Math.round(px* rootView.getResources().getDisplayMetrics().density);
}
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.fragtarifex, container, false);
Bundle b = getArguments();
Login = b.getString("Login");
LicId = b.getString("LicId");
Tarif = b.getString("Tarif");
String Tel=bd.Tel(rootView.getContext(), LicId);
String Adres=bd.Adres(rootView.getContext(), LicId);
TextView abonid=(TextView) rootView.findViewById(R.id.AbonId);
abonid.setText("№ "+LicId);
TextView tel=(TextView) rootView.findViewById(R.id.Tel);
if (Tel.equals("null")) tel.setVisibility(View.GONE);
tel.setText("Номер телефона: "+ "\n" +bd.TelPars(Tel));
TextView adres=(TextView) rootView.findViewById(R.id.Adres);
if (Adres.equals("null")) adres.setVisibility(View.GONE);
adres.setText("Адрес: "+Adres);
tarifname=(TextView) rootView.findViewById(R.id.tarifnameee);
tarifname.setText(Tarif);
if (Tarif.equals("Мобильная телефония"))
{
tarifname.setTextColor(getResources().getColor(R.color.Mobile));
Button vmeste=(Button) rootView.findViewById(R.id.vmeste);
vmeste.setVisibility(View.VISIBLE);
vmeste.setOnClickListener(lis);
MyTask mt=new MyTask();
mt.execute("https://newlk.letai.ru:8443/portal/BalanceInfo?login="+Login+"&phone="+Tel);
}
else
if (Tarif.equals("Интернет"))
tarifname.setTextColor(getResources().getColor(R.color.Enternet));
else
if (Tarif.equals("Телефония"))
tarifname.setTextColor(getResources().getColor(R.color.Phone));
else
if (Tarif.equals("Телевидение"))
tarifname.setTextColor(getResources().getColor(R.color.TV));
else
if (Tarif.equals("Пакеты услуг"))
tarifname.setTextColor(getResources().getColor(R.color.Pacets));
ArrayList<String[]> T2=bd.GetTable2(rootView.getContext(), LicId, Tarif);
for(int i=0;i<T2.size();i++)
{
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
TarifEx2Frag Fragment = new TarifEx2Frag();
Bundle bundle = new Bundle();
bundle.putString("Login", Login);
bundle.putString("LicId", LicId);
bundle.putString("Tarif",Tarif);
bundle.putString("TP", T2.get(i)[4]);
bundle.putString("TPId", T2.get(i)[5]);
bundle.putString("AbonId", T2.get(i)[2]);
bundle.putString("Status", T2.get(i)[3]);
Fragment.setArguments(bundle);
fragmentTransaction.add(R.id.tarifex, Fragment);
fragmentTransaction.commit();
}
return rootView;
}
View.OnClickListener lis= new View.OnClickListener(){
@Override
public void onClick(View v) {
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
VmesteVig Fragment = new VmesteVig();
Bundle bundle = new Bundle();
bundle.putString("Login", Login);
bundle.putString("LicId", LicId);
bundle.putString("Tarif",Tarif);
Fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.tarifex, Fragment,"VmesteVig");
fragmentTransaction.commit();
tarifname.setText("Вместе выгодно");
}
};
class MyTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params)
{
String inputLine="";
String s=params[0];
try
{
String otvet="";
URL url = new URL(s);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(15000);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((otvet=in.readLine()) != null) {
inputLine+=otvet;
}
in.close();
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputLine;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String xml=result;
BdTat bd=new BdTat();
ArrayList<String> ost=bd.GetOstat(xml);
if (ost.size()==4) {
ProgressBar pmin=(ProgressBar) rootView.findViewById(R.id.progressMin);
pmin.setMax(Integer.parseInt(ost.get(0).split(" ")[1]));
pmin.setProgress(Integer.parseInt(ost.get(0).split(" ")[0]));
TextView min=(TextView) rootView.findViewById(R.id.min);
min.setText(ost.get(0).split(" ")[0]+"/"+ost.get(0).split(" ")[1]+" мин");
if (min.getText().toString().indexOf("0/0")>-1) min.setText("0 мин");
ProgressBar pmb=(ProgressBar) rootView.findViewById(R.id.progressMb);
pmb.setMax(Integer.parseInt(ost.get(1).split(" ")[1]));
pmb.setProgress(Integer.parseInt(ost.get(1).split(" ")[0]));
TextView mb=(TextView) rootView.findViewById(R.id.mb);
mb.setText(ost.get(1).split(" ")[0]+"/"+ost.get(1).split(" ")[1]+" мб");
if (mb.getText().toString().indexOf("0/0")>-1) mb.setText("трафик по тарифу");
ProgressBar psms=(ProgressBar) rootView.findViewById(R.id.progressSms);
psms.setMax(Integer.parseInt(ost.get(2).split(" ")[1]));
psms.setProgress(Integer.parseInt(ost.get(2).split(" ")[0]));
TextView sms=(TextView) rootView.findViewById(R.id.sms);
sms.setText(ost.get(2).split(" ")[0]+"/"+ost.get(2).split(" ")[1]+" смс");
if (sms.getText().toString().indexOf("0/0")>-1) sms.setText("смс по тарифу");
ProgressBar pmms=(ProgressBar) rootView.findViewById(R.id.progressMms);
pmms.setMax(Integer.parseInt(ost.get(3).split(" ")[1]));
pmms.setProgress(Integer.parseInt(ost.get(3).split(" ")[0]));
TextView mms=(TextView) rootView.findViewById(R.id.mms);
mms.setText(ost.get(3).split(" ")[0]+"/"+ost.get(3).split(" ")[1]+" ммс");
if (mms.getText().toString().indexOf("0/0")>-1) mms.setText("ммс по тарифу");
LinearLayout ostatoc=(LinearLayout) rootView.findViewById(R.id.ostatoc);
ostatoc.setVisibility(View.VISIBLE);
}
}
}
}
<file_sep>/app/src/main/java/timerlan/letai/Tarif/VmesteVig.java
package timerlan.letai.Tarif;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import timerlan.letai.Osnova.BdTat;
import timerlan.letai.R;
public class VmesteVig extends Fragment {
String Login,LicId;
View rootView;
String AbonId;
EditText schet;
Button bt;
BdTat bd=new BdTat();
TextView vmestelic;
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container,
@Nullable Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.vmestevig, container, false);
Bundle b = getArguments();
Login = b.getString("Login");
LicId = b.getString("LicId");
String[] vm=bd.GetVmesteAbonId(rootView.getContext(),LicId);
AbonId=vm[0];
bt=(Button) rootView.findViewById(R.id.button2);
bt.setOnClickListener(lis);
schet=(EditText) rootView.findViewById(R.id.editText);
vmestelic=(TextView) rootView.findViewById(R.id.vmestelic);
String vmeste=vm[1];
if (vmeste.length()>4) vmestelic.setText("Вместе выгодно подключен на лицевой счет № "+vmeste);
return rootView;
}
public void onBackPressed(){
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager
.beginTransaction();
TarifFrag Fragment = new TarifFrag();
Bundle bundle = new Bundle();
bundle.putString("Login", Login);
bundle.putString("LicId", LicId);
Fragment.setArguments(bundle);
fragmentTransaction.replace(R.id.frgmCont, Fragment,"TarifFrag");
fragmentTransaction.commit();
}
class MyTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... params) {
String inputLine = "";
String s = params[0];
try {
String otvet = "";
URL url = new URL(s);
URLConnection conn = url.openConnection();
conn.setConnectTimeout(15000);
BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((otvet = in.readLine()) != null) {
inputLine += otvet;
}
in.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return inputLine;
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
String xml = result;
LinearLayout l = (LinearLayout) getActivity().findViewById(R.id.ll);
l.setVisibility(View.GONE);
bt.setEnabled(true);
schet.setEnabled(true);
if ( bd.XML("ResultCode",xml).equals("0")) {
Mes("Вы успешно подключили услугу Вместе выгодно.");
vmestelic.setText("Вместе выгодно подключен на лицевой счет № "+schet.getText());
bd.UpdVmeste(rootView.getContext(),AbonId,schet.getText().toString());
}else
Mes(bd.XML("Reason", xml));
schet.setText("");
}
}
View.OnClickListener lis=new View.OnClickListener(){
@Override
public void onClick(View v) {
AlertDialog.Builder builder = new AlertDialog.Builder(rootView.getContext());
builder.setTitle("Подтверждение операции?")
.setMessage("Вы точно хотите подключить услугу?")
.setCancelable(false)
.setPositiveButton("Да", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int idd) {
LinearLayout l = (LinearLayout) getActivity().findViewById(R.id.ll);
l.setVisibility(View.VISIBLE);
bt.setEnabled(false);
schet.setEnabled(false);
MyTask mt=new MyTask();
mt.execute("https://newlk.letai.ru:8443/portal/TogetherAccount?login="+Login+"&paccount_num="+schet.getText()+"&abonement="+AbonId+"&switch_=on");
}
})
.setNegativeButton("Нет",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int idd) { dialog.cancel();}
});
AlertDialog alert = builder.create();
alert.show();
}};
public void Mes(String m)
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("Результат действий")
.setMessage(m)
.setCancelable(false)
.setPositiveButton("Хорошо", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int idd) { dialog.cancel(); } });
AlertDialog alert = builder.create();
alert.show();
}
}
<file_sep>/app/src/main/java/timerlan/letai/Map/Map.java
package timerlan.letai.Map;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.content.Intent;
import android.content.res.AssetManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.MapFragment;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Time;
import java.util.ArrayList;
import timerlan.letai.Osnova.BdTat;
import timerlan.letai.Osnova.MainActivity;
import timerlan.letai.R;
public class Map extends Fragment implements OnMapReadyCallback {
private static View view;
LinearLayout l;
private static GoogleMap mMap;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
view = (FrameLayout) inflater.inflate(R.layout.map, container, false);
MapFragment mapFragment = new MapFragment();
FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
transaction.add(R.id.map, mapFragment).commit();
mapFragment.getMapAsync(this);
return view;
}
@Override
public void onMapReady(GoogleMap googleMap) {
BdTat bd = new BdTat();
mMap = googleMap;
mMap.setMyLocationEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(55.78874, 49.12214 )));
mMap.animateCamera(CameraUpdateFactory.zoomTo(12), 2000, null);
mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
@Override
public void onInfoWindowClick(Marker marker) {
Toast toast = Toast.makeText(view.getContext(),
marker.getTitle()+"\n"+XMLDel("Чтобы узнать часы работы нажмите на блок\n", marker.getSnippet()),Toast.LENGTH_LONG);
toast.setGravity(Gravity.BOTTOM, 0, 0);
toast.show();
}
});
if (bd.GetTable4(view.getContext()).size() == 0)
{
LinearLayout l = (LinearLayout) getActivity().findViewById(R.id.ll);
l.setVisibility(View.VISIBLE);
MyTask mt=new MyTask();
mt.execute("");
}
else setUpMap();
}
private static void setUpMap() {
BdTat bd = new BdTat();
ArrayList<String[]> point=bd.GetTable4(view.getContext());
for(int i=0;i<point.size();i++) {
Double latitude = Double.valueOf(point.get(i)[2]);
Double longitude = Double.valueOf(point.get(i)[3]);
mMap.addMarker(new MarkerOptions()
.position(new LatLng(latitude, longitude))
.title(point.get(i)[0])
.snippet("Чтобы узнать часы работы нажмите на блок\n"+point.get(i)[1])
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_VIOLET)));
}
}
public String XMLDel(String s,String xml) {
Integer a=xml.indexOf(s);
Integer a1=xml.indexOf(s)+s.length();
String it=new String(xml.toCharArray(),0,a);
it=it+new String(xml.toCharArray(),a1,xml.length()-a1);
return it;
}
class MyTask extends AsyncTask<String, Void, String>
{
@Override
protected String doInBackground(String... params)
{
XXX();
return "";
}
@Override
protected void onPostExecute(String result)
{
super.onPostExecute(result);
YYY();
}
}
void XXX(){
AssetManager assetManager = view.getResources().getAssets();
InputStream input;
String text = "";
try {
input = assetManager.open("Map.txt");
int size = input.available();
byte[] buffer = new byte[size]; input.read(buffer); input.close();
text = new String(buffer);
Log.d("Exx",text+"3");
} catch (Exception e) {
Log.d("Exx",e.getMessage());
}
BdTat bd=new BdTat();
bd.SetTabel4Date(view.getContext(),text);
}
void YYY(){
Map f=(Map) MainActivity.fragmentManager.findFragmentByTag("Map");
if (f != null && f.isVisible()) {
LinearLayout l = (LinearLayout) getActivity().findViewById(R.id.ll);
l.setVisibility(View.GONE);
setUpMap();
}
}
}
|
010e5862d88ac34c135062e26b4dfc24d131c353
|
[
"Java",
"INI"
] | 7 |
Java
|
TimRlm/letai
|
9c74b0ae59708b1f38e44fa6fb624994c25ea1d3
|
d7a254126329a15f9be1fcc766d3a709deb4e3b9
|
refs/heads/master
|
<file_sep>import React, { useContext, useEffect, useLayoutEffect } from 'react'
import Navbar from './components/Navbar/Navbar'
import Cart from './components/Cart/Cart'
import { BrowserRouter as Router, Switch, Route } from 'react-router-dom'
import DetailProduct from './components/DetailProduct/DetailProduct'
import Checkout from './components/CheckoutForm/Checkout/Checkout'
import Home from './screens/Home/Home'
import { ContextCart } from './context/Cart/StateCart'
const App = () => {
const { fetchCard } = useContext(ContextCart)
useLayoutEffect(() => {
fetchCard()
}, [])
return (
<Router>
<div>
<Navbar />
<Switch>
<Route exact path="/">
<Home />
</Route>
<Route exact path="/cart">
<Cart />
</Route>
<Route exact path="/checkout">
<Checkout />
</Route>
<Route exact path="/product/:id">
<DetailProduct />
</Route>
</Switch>
</div>
</Router>
)
}
export default App<file_sep>import { InputLabel, Select, MenuItem, Button, Grid, Typography } from '@material-ui/core'
import { useEffect, useState } from 'react'
import { useForm, FormProvider } from 'react-hook-form'
import InputForm from './CustomTextField'
import { Link } from 'react-router-dom'
import useFormAddress from '../../hooks/useFormAddress'
const AddressForm = ({ checkoutToken, next }) => {
const methods = useForm()
const {
fetchShippingCountries,
fetchSubdivisions,
fetchShippingOptions,
setShippingCountry,
setShippingOpcion,
setShippingSubdivision,
shippingCountries,
shippingOpcion,
shippingCountry,
shippingSubdivision,
options,
subdivisions,
} = useFormAddress()
useEffect(() => {
fetchShippingCountries(checkoutToken?.id)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
useEffect(() => {
if (shippingCountry) fetchSubdivisions(shippingCountry)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shippingCountry])
useEffect(() => {
if (shippingSubdivision) fetchShippingOptions(checkoutToken?.id, shippingCountry, shippingSubdivision)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [shippingSubdivision])
const handleFormSubmit = (data) => {
next({ ...data, shippingCountry, shippingSubdivision, shippingOpcion })
}
return (
<>
<Typography variant="h6" gutterBottom >Dirección de Envío</Typography>
<FormProvider {...methods} >
<form onSubmit={methods.handleSubmit(data => handleFormSubmit(data))} >
<Grid container spacing={3}>
<InputForm name="firstName" label="Nombres" required />
<InputForm name="lastName" label="Apellidos" required />
<InputForm name="address1" label="Dirección" required />
<InputForm name="email" label="Correo electronico" required />
<InputForm name="city" label="Ciudad" required />
<InputForm name="ZIP" label="Codigo postal" required />
<Grid item xs={12} sm={6}>
<InputLabel>Pais</InputLabel>
<Select value={shippingCountry} fullWidth onChange={(e) => setShippingCountry(e.target.value)}>
{Object.entries(shippingCountries).map(([code, name]) => (
<MenuItem key={code} value={code}>
{name}
</MenuItem>
))}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Departamento</InputLabel>
<Select value={shippingSubdivision} fullWidth onChange={(e) => setShippingSubdivision(e.target.value)}>
{
subdivisions.map(sub => (
<MenuItem key={sub.code} value={sub.code}>
{sub.name}
</MenuItem>
))
}
</Select>
</Grid>
<Grid item xs={12} sm={6}>
<InputLabel>Precio de envio</InputLabel>
<Select value={shippingOpcion} fullWidth onChange={(e) => setShippingOpcion(e.target.value)} >
{
options.map(opt => (
<MenuItem key={opt.id} value={opt.id}>
{`${opt?.description} - ${opt?.price}`}
</MenuItem>
))
}
</Select>
</Grid>
</Grid>
<br />
<div style={{ display: 'flex', justifyContent: 'space-between', marginTop: '1rem' }} >
<Button
component={Link}
to="/cart"
variant="outlined"
color="secondary"
>Volver al carrito</Button>
<Button
variant="contained"
color="primary"
type="submit"
>Siguiente</Button>
</div>
</form>
</FormProvider>
</>
)
}
export default AddressForm
<file_sep>import { Typography, Button, CircularProgress } from "@material-ui/core"
import { useContext, useEffect, useState } from "react"
import { useParams, useHistory } from 'react-router-dom'
import { makeStyles } from '@material-ui/core/styles'
import styled from 'styled-components'
import { ContextProduct } from "../../context/Product/StateProduct"
import { ContextCart } from "../../context/Cart/StateCart"
const useStyles = makeStyles((theme) => ({
root: {
display: 'flex',
'& > * + *': {
marginLeft: theme.spacing(2),
},
justifyContent: 'center',
alignItems: 'center',
height: '70vh'
},
}));
const DetailProduct = () => {
const classes = useStyles();
const [product, setProduct] = useState(null)
const params = useParams()
const history = useHistory()
const { getProductById } = useContext(ContextProduct)
const { handleAddToCart } = useContext(ContextCart)
const getProduct = async () => {
try {
const response = await getProductById(params.id)
setProduct(response)
} catch (error) {
history.push('/')
}
}
useEffect(() => {
getProduct()
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
if (!product) {
return (
<div className={classes.root}>
<Loading color="secondary" />
</div>
)
}
return (
<Container>
<ImgProduct src={product?.media?.source} alt="" />
<Description>
<Typography>{product?.name}</Typography>
<Typography dangerouslySetInnerHTML={{ __html: product?.description }} variant="body2" color="textSecondary" component="p" />
</Description>
<OpcionsProduct>
<Button
type="button"
variant="contained"
size="small"
color="secondary"
onClick={() => handleAddToCart(product?.id, 1)}
>
Add to list
</Button>
</OpcionsProduct>
</Container>
)
}
export default DetailProduct
const Container = styled.div`
padding: 100px 70px;
display: grid;
grid-template-columns: 1fr 2fr 0.8fr;
@media (max-width: 890px) {
padding: 100px 0px;
grid-auto-flow: dense;
grid-template-columns: 1fr ;
}
`
const Loading = styled(CircularProgress)`
margin-top: 4.5rem;
`
const Description = styled.div`
padding-left: 1.5rem;
@media (max-width: 500px) {
padding-left: 0;
grid-row: 3;
}
`
const OpcionsProduct = styled.div`
direction: rtl;
@media (max-width: 890px) {
grid-row: 2;
padding: 1rem 0 1rem 0;
margin: auto;
}
`
const ImgProduct = styled.img`
height: 350px;
object-fit: cover;
@media (max-width: 890px) {
grid-row: 1;
height: 300px;
margin: auto;
}
`
<file_sep>import { Typography, Button, Card, CardActions, CardContent, CardMedia } from '@material-ui/core'
import { useContext } from 'react'
import { useHistory } from 'react-router-dom'
import styled from 'styled-components'
import { ContextCart } from '../../../context/Cart/StateCart'
import useStyles from './styles'
const CartItem = ({ cart: item }) => {
const history = useHistory()
const classes = useStyles()
const { handleRemoveFromCart, handleUpdateCartQty } = useContext(ContextCart)
const showDetailProduct = () => {
history.push(`/product/${item.product_id}`)
}
return (
<Card className={classes.card} >
<ImageCard
image={item?.media?.source}
className={classes.media}
alt={item.name}
onClick={showDetailProduct}
/>
<CardContent
className={classes.cardContent}
>
<Typography variant="subtitle2">{item?.name}</Typography>
<Typography variant="h6" color="primary" >{item?.line_total?.formatted_with_symbol}</Typography>
</CardContent>
<CardActions
className={classes.cartActions}
>
<div className={classes.buttons}>
<Button type="button" size="small" onClick={() => handleUpdateCartQty(item.id, item?.quantity - 1)} >-</Button>
<Typography>{item?.quantity}</Typography>
<Button type="button" size="small" onClick={() => handleUpdateCartQty(item.id, item?.quantity + 1)} >+</Button>
</div>
<Button
type="button"
variant="contained"
size="small"
color="secondary"
onClick={() => handleRemoveFromCart(item.id)}
>
Eliminar
</Button>
</CardActions>
</Card>
)
}
export default CartItem
const ImageCard = styled(CardMedia)`
cursor: pointer;
`<file_sep>import React, { createContext, useReducer } from 'react'
import { commerce } from '../../lib/commerce'
import { productTypes } from '../../typesContext/product'
import { ReducerProduct } from './ReducerProduct'
export const ContextProduct = createContext()
export const StateProduct = (props) => {
const initialState = {
products: null,
lastProducts: null,
error: null
}
const [state, dispatch] = useReducer(ReducerProduct, initialState)
const getProducts = async () => {
try {
const { data } = await commerce.products.list()
dispatch({
type: productTypes.getProducts,
payload: data
})
} catch (error) {
console.log(error);
}
}
const getProductById = async (productId) => {
if (!productId) return null
const response = await commerce.products.retrieve(productId)
return response
}
const getLastProduct = async (limit = 3) => {
const url = new URL(
"https://api.chec.io/v1/products"
);
let params = {
"limit": limit.toString(),
};
Object.keys(params)
.forEach(key => url?.searchParams?.append(key, params[key]));
let headers = {
"X-Authorization": process.env.REACT_APP_CHEC_PUBLIC_KEY,
"Accept": "application/json",
"Content-Type": "application/json",
};
const reponse = await fetch(url, {
method: "GET",
headers: headers,
})
const { data } = await reponse.json()
dispatch({
type: productTypes.getProductsLastProducts,
payload: data
})
}
return (
<ContextProduct.Provider
value={{
state,
getProducts,
getLastProduct,
getProductById
}}
>
{props.children}
</ContextProduct.Provider>
)
}
<file_sep>import { useState } from "react"
import { commerce } from '../lib/commerce'
const useFormAddress = () => {
const [shippingCountries, setShippingCountries] = useState([])
const [shippingCountry, setShippingCountry] = useState('')
const [shippingSubdivisions, setShippingSubdivisions] = useState([])
const [shippingSubdivision, setShippingSubdivision] = useState('')
const [shippingOpcions, setShippingOpcions] = useState([])
const [shippingOpcion, setShippingOpcion] = useState('')
const subdivisions = Object.entries(shippingSubdivisions).map((city) => ({ code: city[0], name: city[1] }))
const options = shippingOpcions.map((option) => ({
id: option?.id,
description: option?.description,
price: option?.price?.formatted_with_symbol
}))
const fetchShippingCountries = async (checkoutTokenId) => {
const { countries } = await commerce.services.localeListShippingCountries(checkoutTokenId)
setShippingCountries(countries)
setShippingCountry(Object.keys(countries)[0])
}
const fetchSubdivisions = async (countryCode) => {
if (!countryCode) return
const { subdivisions } = await commerce.services.localeListSubdivisions(countryCode)
setShippingSubdivisions(subdivisions)
setShippingSubdivision(Object.keys(subdivisions)[0])
}
const fetchShippingOptions = async (checkoutToken, country, region = null) => {
const options = await commerce.checkout.getShippingOptions(checkoutToken, { country, region })
setShippingOpcions(options)
setShippingOpcion(options[0]?.id)
}
return {
fetchShippingCountries,
fetchSubdivisions,
fetchShippingOptions,
setShippingCountry,
setShippingOpcion,
setShippingSubdivision,
shippingCountries,
shippingOpcion,
shippingCountry,
shippingSubdivision,
options,
subdivisions,
}
}
export default useFormAddress
<file_sep>import { Paper, Stepper, Step, StepLabel, Typography, CircularProgress, Divider, Button } from '@material-ui/core'
import { useContext, useEffect, useState } from 'react'
import { ContextCart } from '../../../context/Cart/StateCart'
import { commerce } from '../../../lib/commerce'
import AddressForm from '../AddressForm'
import PaymentForm from '../PaymentForm'
import useStyles from './styles'
const steps = ['Dirección de envío', 'Detalles de pago']
const Checkout = () => {
const classes = useStyles()
// recorrido de llena informacion
const [activeStep, setActiveStep] = useState(0)
const [data, setData] = useState(null)
const [checkoutToken, setCheckoutToken] = useState(null)
const { state: { cart } } = useContext(ContextCart)
// generar token para las comprar del carrito
useEffect(() => {
const generateToken = async () => {
try {
const token = await commerce.checkout.generateToken(cart?.id, {
type: 'cart'
})
setCheckoutToken(token)
} catch (error) {
}
}
// si carrito esta disponible
if (cart) generateToken()
}, [cart])
const nextStep = () => setActiveStep(activeStep + 1)
const backStep = () => setActiveStep(activeStep - 1)
const next = (data) => {
setData(data)
nextStep()
}
const Form = () => activeStep === 0
? <AddressForm checkoutToken={checkoutToken} next={next} />
: <PaymentForm checkoutToken={checkoutToken} backStep={backStep} nextStep={nextStep} data={data} />
const Confirmation = () => (
<div>
confirmation
</div>
)
return (
<>
<div className={classes.toolbar} />
<main className={classes.layout}>
<Paper className={classes.paper}>
<Typography variant="h5" align="center" >Checkout</Typography>
<Stepper activeStep={activeStep} className={classes.stepper}>
{
steps.map(step => (
<Step key={step}>
<StepLabel>{step}</StepLabel>
</Step>
))
}
</Stepper>
{activeStep === steps.length ? <Confirmation /> : checkoutToken && <Form />}
</Paper>
</main>
</>
)
}
export default Checkout
<file_sep>import { productTypes } from "../../typesContext/product";
export const ReducerProduct = (state, action) => {
switch (action.type) {
case productTypes.getProducts:
return {
...state,
products: action?.payload
}
case productTypes.getProductsLastProducts:
return {
...state,
lastProducts: action?.payload
}
default:
break;
}
}
// const initialState = {
// products: null,
// lastProducts: null,
// error: null
// }<file_sep>import { Card, CardMedia, CardContent, CardActions, Typography, IconButton } from '@material-ui/core'
import { AddShoppingCart } from '@material-ui/icons'
import { useHistory } from 'react-router-dom'
import useStyles from './styles'
import styled from 'styled-components'
import { useContext } from 'react'
import { ContextCart } from '../../../context/Cart/StateCart'
const Product = ({ product }) => {
const history = useHistory()
const classes = useStyles()
const { handleAddToCart } = useContext(ContextCart)
const showDetailProduct = () => {
history.push(`/product/${product.id}`)
}
return (
<Card className={classes.root}
>
<ImageCard
onClick={showDetailProduct}
image={product.media.source}
title={product.name}
/>
<CardContent>
<div className={classes.cardContent} >
<NameProduct variant="subtitle1" gutterBottom >
{product.name}
</NameProduct>
<Typography variant="subtitle1" color="primary" >
{product.price.formatted_with_symbol}
</Typography>
</div>
</CardContent>
<CardActions disableSpacing className={classes.cardActions}>
<IconButton
color="primary"
aria-label="Add to Card"
onClick={() => {
handleAddToCart(product.id, 1)
}}
>
<AddShoppingCart />
</IconButton>
</CardActions>
</Card>
)
}
export default Product
const ImageCard = styled(CardMedia)`
height: 190px;
cursor: pointer;
margin-top: 5px;
background-size: contain;
`
const NameProduct = styled(Typography)`
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-box;
-webkit-line-clamp: 1;
-webkit-box-orient: vertical;
margin-bottom: 10px;
`
<file_sep>import { useContext, useEffect, useState } from 'react'
import { Container, Typography, Button, Grid } from '@material-ui/core'
import { Link } from 'react-router-dom'
import CartItem from './CardItem/CartItem'
import useStyles from './styles'
import { ContextCart } from '../../context/Cart/StateCart'
import styled from 'styled-components'
const Cart = () => {
const classes = useStyles()
const { state: { cart, totalItems }, handleEmptyCart } = useContext(ContextCart)
const [isEmptyCart, setIsEmptyCart] = useState(true)
useEffect(() => {
if (totalItems > 0) {
setIsEmptyCart(false)
} else {
setIsEmptyCart(true)
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [totalItems])
const EmptyCart = () => {
return (
<Typography variant="subtitle1">
No tiene artículos en tu carrito de compras,{' '}
<Link to="/" className={classes.link} >empieza agregando uno.</Link>
</Typography>
)
}
const FilledCart = () => {
return (
<>
<div className={classes.cardDetails} >
<Typography
variant="h5"
>
SubTotal: {cart?.subtotal?.formatted_with_symbol}
</Typography>
<div>
<Button
className={classes.emptyButton}
size="large"
type="button"
variant="contained"
color="secondary"
onClick={handleEmptyCart}
>
Vaciar Carrito
</Button>
<Button
className={classes.checkoutButton}
size="large"
type="button"
variant="contained"
color="primary"
component={Link} to="/checkout"
>
Efectuar Pago
</Button>
</div>
</div>
<Grid container spacing={3}>
{
cart?.line_items?.map(item => (
<Grid item xs={12} sm={4} key={item.id}>
<CartItem
cart={item}
/>
</Grid>
))
}
</Grid>
</>
)
}
return (
<ContainerCart>
<div className={classes.toolbar} />
<Typography className={classes.title} gutterBottom variant="h4">Tus Productos</Typography>
{ isEmptyCart ? <EmptyCart /> : <FilledCart />}
</ContainerCart>
)
}
export default Cart
const ContainerCart = styled(Container)`
margin-bottom: 3rem;
`<file_sep>import { cartTypes } from "../../typesContext/cart";
export const ReducerCart = (state, action) => {
switch (action.type) {
case cartTypes.getProductsOfCart:
return {
...state,
cart: action?.payload,
totalItems: action?.payload?.total_items
}
case cartTypes.placeOrder:
return {
...state,
order: action.payload
}
case cartTypes.EmptyCart:
return {
...state,
cart: action.payload,
}
default:
return state;
}
}
// const initialState = {
// cart: null,
// totalItems: null,
// itemsOnCart: null,
// }<file_sep>import { Typography } from '@material-ui/core'
import { useContext, useEffect } from 'react'
import styled from 'styled-components'
import banner from '../../assets/banner.png'
import Products from '../../components/Products/Products'
import { ContextCart } from '../../context/Cart/StateCart'
import { ContextProduct } from '../../context/Product/StateProduct'
const Home = () => {
const { state: { lastProducts }, getLastProduct } = useContext(ContextProduct)
useEffect(() => {
getLastProduct(3)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [])
return (
<Container>
<BannerImg src={banner} />
<Typography
variant="h4"
>
Productos Nuevos
</Typography>
<Products
products={lastProducts}
/>
</Container>
)
}
export default Home
const BannerImg = styled.img`
width: 90%;
margin-bottom: 2rem;
@media (max-width: 500px){
width: 100%;
height: 160px;
object-fit: cover;
}
`
const Container = styled.div`
margin-top: 90px;
padding: 0 10px 0 10px;
text-align: center;
@media (max-width: 500px){
margin-top: 70px;
}
`<file_sep>export const productTypes = {
getProducts: '[product] get products',
getProductsLastProducts: '[product] get last products',
}
|
98638de37562b6a2fbabb8968f06fd2a901092f2
|
[
"JavaScript"
] | 13 |
JavaScript
|
cuadros-code/react_e-commerce
|
96979d1ca60ec33c023f9602476a2788a210eab3
|
ec011617203376e0ccb6168ac2a36601f9383d85
|
refs/heads/master
|
<repo_name>jwwinship/CS2301_HW3<file_sep>/src/BingoCard.c
//
// Created by John on 11/28/2020.
//
#include <stdio.h>
#include <string.h>
#include "BingoCard.h"
#include "marker.h"
//A list of markers in the space
LLNode* markerList;
//TODO: add functionality for a second type of linked list, which will keep track of all called balls.
bool initBingoCard(bingoBall** corner, int howManyRows)
{
//bingoBall cardlist[400];
bool ok = true;
bingoBall* tempSpaceP;
for(int row = 0; row< 20; row++)
{
for(int col = 0; col < 20; col++)
{
tempSpaceP = malloc(sizeof(bingoBall));
//Sets letter to random letter from A to Z
tempSpaceP->letter = rand()%26 + 65;
//Sets number from 0-9
tempSpaceP->number = rand()%10; //Testing should pass
*(corner+row*howManyRows + col) = tempSpaceP;
if (tempSpaceP->letter > 90 || tempSpaceP->letter < 65 || tempSpaceP->number < 0 || tempSpaceP->number > 9)
{
ok = false;
}
}
}
//Also initializing the Linked List
markerList = makeEmptyLinkedList();
return ok;
}
bool displayBingoCard(bingoBall** corner, int howManyRows)
{
bool ok = true;
for(int row = 0; row< 20; row++)
{
for(int col = 0; col < 20; col++)
{
bingoBall tempSpace = **(corner + row * howManyRows + col);
printf("|%c%d",tempSpace.letter, tempSpace.number);
}
printf("|\n");
}
return ok;
}
//This method calls the checkCardForMatch method, so needs the necessary parameters for bingo card.
bingoBall* callBingoBall(bingoBall** corner, int howManyRows)
{
//TODO: Find a way to incorporate row and column into the calls for a bingo ball, so we can tell where it is.
puts("\nCalling new Bingo Ball......");
bingoBall* ballCalledP;
ballCalledP = malloc(sizeof(bingoBall));
//Sets letter to random letter from A to Z
ballCalledP->letter = rand()%26 + 65;
//Sets number from 0-9
ballCalledP->number = rand()%10;
printf("%c%d!\n\n", ballCalledP->letter, ballCalledP->number);
ballCalledP = checkCardForMatch(corner, howManyRows, ballCalledP); //See if the currently called ball is on the bingo card anywhere
if(ballCalledP->matchFound)
{
Marker* ballMarkerP = malloc(sizeof(Marker));
ballMarkerP->letter = ballCalledP->letter;
ballMarkerP->number = ballCalledP->number;
ballMarkerP->row = ballCalledP->rowFound;
ballMarkerP->col = ballCalledP->colFound;
ballMarkerP->matchFound = true;
savePayload(markerList, ballMarkerP);
}
printList(markerList); //Used for test purposes. Uncomment in order to test functionality of method
return ballCalledP;
}
bingoBall* checkCardForMatch(bingoBall** corner, int howManyRows, bingoBall* ballToCheck)
{
bingoBall* tempBallP = ballToCheck;
for(int row = 0; row< 20; row++)
{
for(int col = 0; col < 20; col++)
{
tempBallP = *(corner + row * howManyRows + col);
if (tempBallP->number == ballToCheck->number && tempBallP->letter == ballToCheck->letter)
{
tempBallP->colFound = col;
tempBallP->rowFound = row;
tempBallP->matchFound = true;
return tempBallP;
}
else
{
tempBallP = ballToCheck;
}
}
}
return tempBallP;
}
void printHistoryList()
{
//prints out the entirety of the marker history list
printList(markerList);
}<file_sep>/cmake-build-debug/CMakeFiles/2020HW3starter.dir/DependInfo.cmake
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"C"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_C
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/2020HW3starter.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/2020HW3starter.dir/src/2020HW3starter.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/AdjMat.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/2020HW3starter.dir/src/AdjMat.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/LinkedList.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/2020HW3starter.dir/src/LinkedList.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/production.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/2020HW3starter.dir/src/production.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/tests.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/2020HW3starter.dir/src/tests.c.obj"
)
set(CMAKE_C_COMPILER_ID "MSVC")
# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
"../src"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
<file_sep>/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"CMakeFiles/CS2301_HW3.dir/src/BingoCard.c.obj"
"CMakeFiles/CS2301_HW3.dir/src/CS2301_HW3.c.obj"
"CMakeFiles/CS2301_HW3.dir/src/LinkedList.c.obj"
"CMakeFiles/CS2301_HW3.dir/src/marker.c.obj"
"CMakeFiles/CS2301_HW3.dir/src/production.c.obj"
"CMakeFiles/CS2301_HW3.dir/src/tests.c.obj"
"CS2301_HW3.exe"
"CS2301_HW3.exe.manifest"
"CS2301_HW3.lib"
"CS2301_HW3.pdb"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/CS2301_HW3.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
<file_sep>/CMakeLists.txt
cmake_minimum_required(VERSION 3.17)
project(CS2301_HW3 C)
set(CMAKE_C_STANDARD 11)
include_directories(src)
add_executable(CS2301_HW3
src/CS2301_HW3.c
src/LinkedList.c
src/LinkedList.h
src/production.c
src/production.h
src/tests.c
src/tests.h
src/TMSName.h src/BingoCard.c src/BingoCard.h src/marker.c src/marker.h)
<file_sep>/src/marker.c
//
// Created by John on 11/28/2020.
//
#include "marker.h"
#include "BingoCard.h"
#include "LinkedList.h"
Marker* placeMarker(int r, int c, int number, char letter, bool matchFound)
{
Marker* mP = (Marker*) malloc(sizeof(Marker));
//TODO what do we do?
mP->row = r;
mP->col = c;
mP->letter = letter;
mP->number = number;
mP->matchFound = matchFound;
return mP;
}
<file_sep>/src/tests.c
/*
* tests.c
*
* Created on: Jul 4, 2019
* Author: Therese
*/
#include "tests.h"
#include "production.h"
#include "LinkedList.h"
#include "BingoCard.h"
bool tests()
{
bool answer = false;
bool ok1 = testInitBingoCard();
bool ok2 = testPrintList();
bool ok3 = testCallBall();
//bool ok3 = testMakeLList();
//bool ok4 = testEnqueue();
//bool ok5 = testRemoveFromList();
//bool ok6 = testPrintHistory();
answer = ok1 && ok2 && ok3;
return answer;
}
bool testGotAdjacencyMatrix()
{
bool ans = true;
return ans;
}
bool testMakeLList()
{
bool ok = true;
puts("starting testMakeLList");fflush(stdout);
//what are the criteria for success for make LList?
//should be able to make one, add data to it, get the data back
//test case 1:
LLNode* theListP = makeEmptyLinkedList();
bool rightAnswer = true;
bool answer = isEmpty(theListP);
if(answer!=rightAnswer)
{
ok = false;
}
//test case 2:
//TODO more test cases here
else
{
puts("test make LList did not pass.");
}
return ok;
}
bool testPrintHistory()
{
bool ok = true;
return ok;
}
//This will simultaneously test the initialization and display of the card, since they are pretty tied together.
bool testInitBingoCard()
{
bool ok = false;
bingoBall** theSpaceP = malloc(20 * 20 * sizeof(bingoBall));
ok = initBingoCard(theSpaceP,20);
displayBingoCard(theSpaceP, 20); //Visual test. If the console prints out a randomized bingo card, then the test is a success.
if (ok)
{
puts("Test InitBingoCard passed\n");
}
else
{
puts("Test InitBingoCard failed\n");
}
return ok;
}
bool testPrintList()
//This is another visual test. If the test prints out a list of Bingo ball markers, then the test is successful.
{
bool ok = true;
LLNode* markerList = makeEmptyLinkedList();
for (int i = 0; i<5; i++)
{
bingoBall* testBingoBallP = malloc(sizeof(bingoBall));
//Sets letter to random letter from A to Z
testBingoBallP->letter = rand()%26 + 65;
//Sets number from 0-9
testBingoBallP->number = rand()%10;
Marker* testMarker = malloc(sizeof(Marker));
testMarker->row = rand()%20;
testMarker->col = rand()%20;
testMarker->letter = testBingoBallP->letter;
testMarker->number = testBingoBallP->number;
savePayload(markerList, testMarker); //List should be populated, test should pass
}
if (isEmpty(markerList))
{
ok = false;
}
printf("\nTesting Ability to print the contents of a list\n");
printList(markerList);
if (ok)
{
puts("Test PrintList passed\n");
}
else
{
puts("Test PrintList failed\n");
}
return ok;
}
//A double test again.
bool testCallBall()
{
bool ok = true;
bingoBall** theSpaceP = malloc(20 * 20 * sizeof(bingoBall));
bingoBall* tempBallP;
ok = initBingoCard(theSpaceP,20);
displayBingoCard(theSpaceP, 20); //Visual test. If the console prints out a randomized bingo card, then the test can continue
for (int i = 0; i<10; i++)
{
tempBallP = callBingoBall(theSpaceP, 20); //this should call a bunch of bingo balls, and add matches to the list.
if (tempBallP->letter > 90 || tempBallP->letter < 65 || tempBallP->number < 0 || tempBallP->number > 9)
{
ok = false;
}
}
//printHistoryList();
if (ok)
{
puts("Test CallBall passed\n");
}
else
{
puts("Test CallBall failed\n");
}
return ok;
}<file_sep>/src/BingoCard.h
//
// Created by John on 11/28/2020.
//
#ifndef CS2301_HW3_BINGOCARD_H
#define CS2301_HW3_BINGOCARD_H
#include <stdbool.h>
#include "marker.h"
typedef struct
{
int number;
char letter;
int rowFound;
int colFound;
bool matchFound;
}bingoBall;
bool initBingoCard(bingoBall**, int);
bool displayBingoCard(bingoBall**, int);
bingoBall* callBingoBall();
bingoBall* checkCardForMatch(bingoBall**, int, bingoBall*);
void printHistoryList();
#endif //CS2301_HW3_BINGOCARD_H
<file_sep>/src/marker.h
//
// Created by John on 11/28/2020.
//
#ifndef CS2301_HW3_MARKER_H
#define CS2301_HW3_MARKER_H
#include "BingoCard.h"
typedef struct
{
int row;
int col;
int number;
char letter;
// We create a marker for every ball called, for simplicity's sake.
// Because of this, we have a field that tells us if a marker actually has a match on the board
bool matchFound;
}Marker;
#include <stdbool.h>
#include <stdlib.h>
#include <LinkedList.h>
Marker* placeMarker(int, int, int,char, bool matchFound);
#endif //CS2301_HW3_MARKER_H
<file_sep>/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/DependInfo.cmake
# The set of languages for which implicit dependencies are needed:
set(CMAKE_DEPENDS_LANGUAGES
"C"
)
# The set of files for implicit dependencies of each language:
set(CMAKE_DEPENDS_CHECK_C
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/BingoCard.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/src/BingoCard.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/CS2301_HW3.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/src/CS2301_HW3.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/LinkedList.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/src/LinkedList.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/marker.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/src/marker.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/production.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/src/production.c.obj"
"C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/src/tests.c" "C:/Users/John/Desktop/ECE Resources/CS2301/Code and Labs/2020HW3starter/cmake-build-debug/CMakeFiles/CS2301_HW3.dir/src/tests.c.obj"
)
set(CMAKE_C_COMPILER_ID "MSVC")
# The include file search paths:
set(CMAKE_C_TARGET_INCLUDE_PATH
"../src"
)
# Targets to which this target links.
set(CMAKE_TARGET_LINKED_INFO_FILES
)
# Fortran module output directory.
set(CMAKE_Fortran_TARGET_MODULE_DIR "")
<file_sep>/src/LinkedList.h
/*
* LinkedList.h
*
* Created on: Nov 4, 2019
* Author: Therese
*/
#ifndef LINKEDLIST_H_
#define LINKEDLIST_H_
#include <stdbool.h>
#include "marker.h"
typedef Marker Payload;
//struct LLNode;
typedef struct
{
struct LLNode* next;
struct LLNode* prev;
Payload* payP;
}LLNode;
typedef struct
{
Payload* mp;
LLNode* newQHead;
}backFromDQFIFO;
LLNode* makeEmptyLinkedList();
LLNode* removeFromList(LLNode* hp, Payload* pP);
void savePayload(LLNode* lp, Payload* mp);
bool isEmpty(LLNode* lp);
Payload* dequeueLIFO(LLNode* lp);
backFromDQFIFO* dequeueFIFO(LLNode* lp);
//These functions added by <NAME>, to expand functionality of the lists.
void printList(LLNode* lp);
#endif /* LINKEDLIST_H_ */
<file_sep>/src/production.c
/*
* production.c
*
* Created on: Jul 4, 2019
* Author: Therese
*/
#include "production.h"
#include "LinkedList.h"
//TODO: modify production to accept argument
bool production(int argc, char* argv[])
{
bool answer = false;
if(argc <=1) //no interesting information
{
puts("Didn't find any arguments.");
fflush(stdout);
answer = false;
}
else //there is interesting information
{
printf("Found %d interesting arguments.\n", argc-1);
fflush(stdout);
char* eptr=(char*) malloc(sizeof(char*));
long aL=-1L;
for(int i = 1; i<argc; i++) //don't want to read argv[0]
{//argv[i] is a string
switch(i)
{
case 1:
aL = strtol(argv[i], &eptr, 10);
int ballsToCall = (int) aL;
printf("Number of balls to call: %d\n", ballsToCall);
bingoBall** theSpaceP = malloc(20 * 20 * sizeof(bingoBall));
answer = initBingoCard(theSpaceP,20);
displayBingoCard(theSpaceP, 20); //Visual test. If the console prints out a randomized bingo card, then the test can continue
for (int j = 0; j<ballsToCall; j++)
{
callBingoBall(theSpaceP, 20); //this should call a bunch of bingo balls, and add matches to the list.
}
break;
default:
puts("Unexpected argument count."); fflush(stdout);
answer = false;
break;
}//end of switch
}//end of for loop on argument count
}//end of else we have good arguments
return answer;
}
<file_sep>/cmake-build-debug/CMakeFiles/2020HW3starter.dir/cmake_clean.cmake
file(REMOVE_RECURSE
"2020HW3starter.exe"
"2020HW3starter.exe.manifest"
"2020HW3starter.lib"
"2020HW3starter.pdb"
"CMakeFiles/2020HW3starter.dir/src/2020HW3starter.c.obj"
"CMakeFiles/2020HW3starter.dir/src/AdjMat.c.obj"
"CMakeFiles/2020HW3starter.dir/src/LinkedList.c.obj"
"CMakeFiles/2020HW3starter.dir/src/production.c.obj"
"CMakeFiles/2020HW3starter.dir/src/tests.c.obj"
)
# Per-language clean rules from dependency scanning.
foreach(lang C)
include(CMakeFiles/2020HW3starter.dir/cmake_clean_${lang}.cmake OPTIONAL)
endforeach()
|
5489975a074f9d03aa9afc1bdc176ef1df915e73
|
[
"C",
"CMake"
] | 12 |
C
|
jwwinship/CS2301_HW3
|
bce62b76691b25b128bddaec559dabfa87d066e7
|
b3d95f0d424f39d30cdb78ceebb63a01196fc444
|
refs/heads/master
|
<repo_name>fmca/PlaceChat<file_sep>/src/com/fuzuapp/model/resultados/IRedeSociaisAdapter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fuzuapp.model.resultados;
import com.fuzuapp.model.resultados.entidades.GeoPoint;
import com.fuzuapp.model.resultados.entidades.Resultado;
import java.util.List;
/**
*
* @author Filipe_2
*/
interface IRedeSociaisAdapter {
List<Resultado> getResultados(GeoPoint ponto, double raio);
}
<file_sep>/src/com/fuzuapp/controller/LoginServlet.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fuzuapp.controller;
import com.fuzuapp.model.Fachada;
import com.fuzuapp.model.usuario.entidades.Login;
import com.fuzuapp.model.usuario.entidades.Senha;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Filipe_2
*/
public class LoginServlet extends HttpServlet {
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("TelaLogin.jsp");
dispatcher.forward(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* @param request servlet request
* @param response servlet response
* @throws ServletException if a servlet-specific error occurs
* @throws IOException if an I/O error occurs
*/
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logar(request, response);
}
/**
* Returns a short description of the servlet.
*
* @return a String containing servlet description
*/
@Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
private void logar(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
boolean logado = false;
boolean credenciais = false;
try{
Login login = new Login(request.getParameter("login"));
Senha senha = new Senha(request.getParameter("senha"));
credenciais = true;
Fachada fachada = Fachada.getInstance();
fachada.logar(login, senha);
logado = true;
request.getSession().setAttribute("login", login);
request.getSession().setAttribute("senha", senha);
}catch(Exception e){
request.setAttribute("erro", e.getMessage());
}
if(logado){
String url = (String) request.getSession().getAttribute("caller");
url = url == null ? "resultados" : url;
response.sendRedirect(url);
}else{
RequestDispatcher dispatcher = request.getRequestDispatcher("TelaLogin.jsp");
dispatcher.forward(request, response);
}
}
}
<file_sep>/src/com/fuzuapp/model/favoritos/RepositorioFavoritosHibernate.java
package com.fuzuapp.model.favoritos;
import com.fuzuapp.util.HibernateUtil;
import com.fuzuapp.model.favoritos.entidades.Favorito;
import com.fuzuapp.model.resultados.entidades.Resultado;
import com.fuzuapp.model.usuario.entidades.Usuario;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import java.util.ArrayList;
import java.util.List;
/**
* Created by filipe on 27/07/14.
*/
public class RepositorioFavoritosHibernate implements IRepositorioFavoritos {
SessionFactory sessFact = HibernateUtil.getSessionFactory();
Session session;
@Override
public void inserir(Resultado favorito, Usuario usuario) {
session = sessFact.openSession();
org.hibernate.Transaction tr = session.beginTransaction();
session.save(new Favorito(favorito,usuario));
tr.commit();
session.close();
}
@Override
public void remover(Resultado favorito, Usuario usuario) {
}
@Override
public List<Resultado> getTodos(Usuario usuario) {
session = sessFact.openSession();
org.hibernate.Transaction tr = session.beginTransaction();
Favorito favorito = new Favorito();
favorito.setUsuario(usuario);
Example example = Example.create(favorito);
Criteria criteria = session.createCriteria(Favorito.class).add(example);
List<Favorito> favs = criteria.list();
List<Resultado> resp = new ArrayList<Resultado>();
for(Favorito fav : favs){
resp.add(fav.getResultado());
}
tr.commit();
session.close();
return resp;
}
}
<file_sep>/src/com/fuzuapp/model/resultados/FlickrAdapter.java
package com.fuzuapp.model.resultados;
import com.fuzuapp.model.resultados.entidades.GeoPoint;
import com.fuzuapp.model.resultados.entidades.Resultado;
import com.flickr4java.flickr.Flickr;
import com.flickr4java.flickr.FlickrException;
import com.flickr4java.flickr.REST;
import com.flickr4java.flickr.photos.Photo;
import com.flickr4java.flickr.photos.PhotoList;
import com.flickr4java.flickr.photos.SearchParameters;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
/**
* Created by filipe on 28/07/14.
*/
public class FlickrAdapter implements IRedeSociaisAdapter {
public static void main(String[] args) throws FlickrException {
GeoPoint g = new GeoPoint();
g.setLatitude(-8.08);
g.setLongitude(-34.94);
for (Resultado r : new FlickrAdapter().getResultados(g, 2)){
System.out.println(r);
}
}
@Override
public List<Resultado> getResultados(GeoPoint ponto, double raio) {
String apikey = "af10cdd6ab2eda09f4a832ed791aaade";
String secret = "68a23ba8834f93ae";
Flickr flickr = new Flickr(apikey, secret, new REST());
SearchParameters searchParameters = new SearchParameters();
searchParameters.setLatitude(ponto.getLatitude().toString());
searchParameters.setLongitude(ponto.getLongitude().toString());
searchParameters.setRadius(raio>0 ? (int) raio : 1);
PhotoList<Photo> list = new PhotoList<>();
try {
list = flickr.getPhotosInterface().search(searchParameters, 20, 0);
} catch (FlickrException e) {
e.printStackTrace();
}
List<Resultado> resultados = new ArrayList<>();
List<String> urls = new ArrayList<String>();
for(Photo photo: list){
try {
Resultado r = new Resultado();
r.setTipo(Resultado.IMAGEM);
//r.setHorario(new SimpleDateFormat("dd/MM HH:mm").format(photo.));
r.setNomeUsuario(photo.getOwner().getId());
r.setUrl(photo.getUrl());
r.setDescricao(photo.getTitle() + " - " + photo.getDescription());
r.setFotoUrl(photo.getMedium640Url());
resultados.add(r);
}catch (Exception e){
e.printStackTrace();
}
}
return resultados;
}
}
<file_sep>/src/com/fuzuapp/model/favoritos/IRepositorioFavoritos.java
package com.fuzuapp.model.favoritos;
import com.fuzuapp.model.resultados.entidades.Resultado;
import com.fuzuapp.model.usuario.entidades.Usuario;
import java.util.List;
/**
* Created by filipe on 27/07/14.
*/
public interface IRepositorioFavoritos {
public void inserir(Resultado favorito, Usuario usuario);
public void remover(Resultado favorito, Usuario usuario);
public List<Resultado> getTodos(Usuario usuario);
}
<file_sep>/src/com/fuzuapp/model/favoritos/exceptions/FavoritoNaoEncontrado.java
package com.fuzuapp.model.favoritos.exceptions;
/**
* Created by filipe on 27/07/14.
*/
public class FavoritoNaoEncontrado extends Exception {
public FavoritoNaoEncontrado (){
super("Favorito não existe");
}
}
<file_sep>/src/com/fuzuapp/model/usuario/CadastroUsuario.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fuzuapp.model.usuario;
import com.fuzuapp.model.usuario.entidades.Login;
import com.fuzuapp.model.usuario.entidades.Senha;
import com.fuzuapp.model.usuario.entidades.Usuario;
import com.fuzuapp.model.usuario.exceptions.AutenticacaoInvalida;
import com.fuzuapp.model.usuario.exceptions.UsuarioJaExisteException;
/**
*
* @author Filipe_2
*/
public class CadastroUsuario {
private IRepositorioUsuario repositorioUsuario;
public CadastroUsuario(IRepositorioUsuario repositorioUsuario){
this.repositorioUsuario = repositorioUsuario;
}
public Usuario getUsuario(Login login){
return repositorioUsuario.get(login);
}
public void autenticar (Login login, Senha senha) throws AutenticacaoInvalida{
Usuario u = getUsuario(login);
if (u == null){
throw new AutenticacaoInvalida("Usuário não existe");
}
if(senha == null || ! u.validar(senha.toString())){
throw new AutenticacaoInvalida("Senha inválida");
}
}
public void inserirUsuario(Usuario usuario) throws UsuarioJaExisteException {
Usuario u = getUsuario(usuario.getLogin());
if(u == null){
this.repositorioUsuario.inserir(usuario);
}else{
throw new UsuarioJaExisteException();
}
}
public void remover(Usuario usuario){
this.repositorioUsuario.remover(usuario);
}
}
<file_sep>/src/com/fuzuapp/model/resultados/TwitterAdapter.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fuzuapp.model.resultados;
import com.fuzuapp.model.resultados.entidades.GeoPoint;
import com.fuzuapp.model.resultados.entidades.Resultado;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import twitter4j.GeoLocation;
import twitter4j.Query;
import twitter4j.QueryResult;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.conf.ConfigurationBuilder;
/**
*
* @author Filipe_2
*/
public class TwitterAdapter implements IRedeSociaisAdapter{
Twitter twitter;
public TwitterAdapter(){
inicializar();
}
@Override
public List<Resultado> getResultados(GeoPoint ponto, double raio) {
List<Resultado> resultados = new ArrayList();
try {
Query query = new Query("");
GeoLocation geo = new GeoLocation(ponto.getLatitude(), ponto.getLongitude());
query.setGeoCode(geo, raio, Query.KILOMETERS);
query.resultType(Query.RECENT);
query.setCount(20);
QueryResult result = twitter.search(query);
for (Status status : result.getTweets()) {
Resultado r = new Resultado();
r.setDescricao(status.getText());
r.setUrl("http://twitter.com/statuses/"+String.valueOf(status.getId()));
r.setNomeUsuario(status.getUser().getName());
r.setHorario(new SimpleDateFormat("dd/MM HH:mm").format(status.getCreatedAt()));
r.setFotoUrl(status.getUser().getProfileImageURL());
//r.setLocal(new GeoPoint(status.getGeoLocation().getLatitude(), status.getGeoLocation().getLongitude()));
r.setTipo(Resultado.TEXTO);
resultados.add(r);
}
} catch (TwitterException ex) {
Logger.getLogger(TwitterAdapter.class.getName()).log(Level.SEVERE, null, ex);
}
return resultados;
}
private void inicializar() {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey("56dJMai5O3H1MUjUl607LPgOh")
.setOAuthConsumerSecret("<KEY>")
.setOAuthAccessToken("<KEY>")
.setOAuthAccessTokenSecret("<KEY>");
TwitterFactory tf = new TwitterFactory(cb.build());
twitter = tf.getInstance();
}
}
<file_sep>/src/com/fuzuapp/util/Prop.java
package com.fuzuapp.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Created by filipe on 27/07/14.
*/
public class Prop {
public static final String TYPE_LIST = "list";
public static final String TYPE_HIBERNATE = "hibernate";
public static final String TYPE = "type";
public String getPropriedade(String nome) {
Properties prop = new Properties();
InputStream input = null;
String resp = null;
try {
prop.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("repo.properties"));
resp = prop.getProperty(nome);
} catch (IOException ex) {
ex.printStackTrace();
}
return resp;
}
}
<file_sep>/README.md
PlaceChat
=========
Como instalar
====
O projeto foi desenvolvido na IDE IntelliJ Ultimate. Para executar, deve-se ter uma instalação do Tomcat 8.0+
Inicialmente o projeto executa sem persistência, mas ela pode ser facilmente habilitada no arquivo [repo.properties](https://github.com/fmca/PlaceChat/blob/master/web/WEB-INF/classes/repo.properties).
Caso deseje trocar para persistência Hibernate, deve-se executar o script [mysql](https://github.com/fmca/PlaceChat/blob/master/src/conf/mysql_script.sql).
O servidor MySQL deve executar na porta 3306
<file_sep>/src/com/fuzuapp/model/usuario/ControladorUsuario.java
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.fuzuapp.model.usuario;
import com.fuzuapp.model.usuario.entidades.Login;
import com.fuzuapp.model.usuario.entidades.Senha;
import com.fuzuapp.model.usuario.entidades.Usuario;
import com.fuzuapp.model.usuario.exceptions.AutenticacaoInvalida;
import com.fuzuapp.model.usuario.exceptions.UsuarioJaExisteException;
/**
*
* @author Filipe_2
*/
public class ControladorUsuario {
private CadastroUsuario cadastroUsuario;
public ControladorUsuario(IRepositorioUsuario repUsuario){
this.cadastroUsuario = new CadastroUsuario(repUsuario);
}
public void cadastrar (Usuario usuario) throws UsuarioJaExisteException {
this.cadastroUsuario.inserirUsuario(usuario);
}
public void autenticar (Login login, Senha senha) throws AutenticacaoInvalida{
cadastroUsuario.autenticar(login, senha);
}
public Usuario buscarUsuario(Login login){
return cadastroUsuario.getUsuario(login);
}
}
<file_sep>/src/conf/mysql_script.sql
create database fuzuapp;
use fuzuapp;
create table Usuario (id INT, Email VARCHAR(20), Nome VARCHAR(100), Senha VARCHAR(20), Login VARCHAR(20));
alter table Usuario add primary key (id);
ALTER TABLE Usuario MODIFY COLUMN id INT auto_increment;
create table Favorito (id INT, descricao VARCHAR(500), foto_url VARCHAR(200), nome_usuario VARCHAR(150), tipo VARCHAR(30), url VARCHAR(200), horario VARCHAR(100), latitude DOUBLE, longitude DOUBLE);
alter table Favorito add primary key (id);
ALTER TABLE Favorito MODIFY COLUMN id INT auto_increment;
|
926e36a0f290e45151013ce336311aa81f759ad9
|
[
"Markdown",
"Java",
"SQL"
] | 12 |
Java
|
fmca/PlaceChat
|
d74fefaf5ed33e56b96859fb33a3bfe9452c0d9d
|
979cbbee8fe5cd1b36af9e285f8637eedc3f2336
|
refs/heads/master
|
<repo_name>Nirob143/Nirob143-Droow-Creative-Showcase<file_sep>/assets/js/main.js
// Carousel Slier
$(".carousel-active").owlCarousel({
items:3,
margin:0,
loop:true,
autoplay:true,
autoplayTimeout:3000,
responsive: {
0: {
items: 1
},
600: {
items: 3
},
800: {
items: 3
},
1000: {
items: 3
}
}
});
$(".carousel-blog").owlCarousel({
items:3,
margin:0,
loop:true,
autoplay:true,
autoplayTimeout:3000,
responsive: {
0: {
items: 1
},
600: {
items: 1
},
800: {
items: 2
},
1000: {
items: 3
}
}
});
$(".carousel-client").owlCarousel({
items:1,
margin:0,
loop:true,
autoplay:true,
autoplayTimeout:3000,
responsive: {
0: {
items: 1
},
600: {
items: 1
},
600: {
items: 1
},
1000: {
items:1
}
}
});
// counterUp
$('.counter').counterUp({
delay : 10,
time: 3000,
});
$('.counter2').counterUp({
delay : 10,
time: 10000,
});
// wow
new WOW().init();
//one pagenave js
$('#nav').onePageNav({
filter: ':not(.external)'
});
// init Isotope
var $grid = $('.portfolio-iteams').isotope({
// options
});
// filter items on button click
$('.portfolio-menu').on( 'click', 'li', function() {
var filterValue = $(this).attr('data-filter');
$grid.isotope({ filter: filterValue });
});
// filter items on button active
$('.portfolio-menu').on( 'click', 'li', function() {
$(this).activeclass('active').siblings.removeClass('active');
});
$(function(){
$('#menu').slicknav();
});
jQuery(window).load(function () {
/* Sticky Header */
$(window).on('scroll', function () {
if ($(this).scrollTop() > 20) {
$('.header-fixed').addClass("sticky");
} else {
$('.header-fixed').removeClass("sticky");
}
});
/* Preloader */
$(".preloader").fadeOut()
});
|
409d8b6922997bf9f4cf7d4bbe7336c45447eef7
|
[
"JavaScript"
] | 1 |
JavaScript
|
Nirob143/Nirob143-Droow-Creative-Showcase
|
ecf5c4f7323f803079310c51ac34d4db9262f014
|
411e536841bc28bb03bcddecc3bea55a307ecd92
|
refs/heads/master
|
<repo_name>OneWang/FlowLayout<file_sep>/Example/Podfile
use_frameworks!
platform :ios, '8.0'
target 'OWWaterFallLayout_Example' do
pod 'OWWaterFallLayout', :path => '../'
pod 'MJExtension'
pod 'MJRefresh'
pod 'SDWebImage'
target 'OWWaterFallLayout_Tests' do
inherit! :search_paths
end
end
|
3bb21c49e0688dc31c01558b37f4b887a84db861
|
[
"Ruby"
] | 1 |
Ruby
|
OneWang/FlowLayout
|
6946235f77234fe4da3e1183b2fc7519bce4f186
|
0accf2424398ceb5978608143082ef9ae850d25c
|
refs/heads/master
|
<repo_name>ProfReynolds/KnowledgeSystems<file_sep>/src/CognitiveServices.VisionLibrary.Tests/ComputerVisionApiTests.cs
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
using CognitiveServices.VisionLibrary;
using CognitiveServices.VisionLibrary.ComputerVision;
using NUnit.Framework;
using Shouldly;
#pragma warning disable 1998 // suppresses warning about the async
namespace Knowledge.CognitiveServicesVision.Tests
{
[TestFixture]
public class ComputerVisionApiTests
{
class AbstractClassTestInstance : ComputerVisionApi
{
public override async Task<GetVisualFeaturesStringResponse> GetVisualFeatures(CognitiveServicesRequest request)
{
throw new System.NotImplementedException();
}
public override async Task<GetThumbnailResponse> GetThumbnail(GetThumbnailRequest request)
{
throw new System.NotImplementedException();
}
public override async Task<PerformOcrStringResponse> PerformOcr(CognitiveServicesRequest request)
{
throw new System.NotImplementedException();
}
}
private AbstractClassTestInstance _abstractClassTestInstance;
[OneTimeSetUp]
public void TestInitializer()
{
_abstractClassTestInstance = new AbstractClassTestInstance();
}
[Test]
public void TestMethod1()
{
_abstractClassTestInstance.ShouldNotBeNull();
}
}
}
<file_sep>/src/Knowledge.Accord.Housing/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Knowledge.Accord.Housing
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private ModelImplementation _modelImplemention;
private void MainForm_Loaded(object sender, RoutedEventArgs e)
{
TxtboxTrainingDataSource.Text = ModelSettings.TrainingData;
TxtboxTestingDataSource.Text = ModelSettings.TestingData;
_modelImplemention = new ModelImplementation();
}
private void BtnLoadTrainingAndTextData_Click(object sender, RoutedEventArgs e)
{
if (!_modelImplemention.Ready) return;
TxtblockLoadInformation.Text = string.Empty;
CanvasLoadData.Background= new SolidColorBrush(Colors.LightCoral);
_modelImplemention.LoadTrainingDataFromFile(
trainingDataAbsolutePath: ModelSettings.TrainingData,
trainingDataHasHeaders: ModelSettings.TrainingDataHasHeaders);
if (_modelImplemention.Ready)
{
ShowMessageAlert(_modelImplemention.FailureInformation);
TxtblockLoadInformation.Text = _modelImplemention.FailureInformation;
}
}
private void ShowMessageAlert(string modelImplementionFailureInformation)
{
MessageBox.Show(
messageBoxText: modelImplementionFailureInformation,
caption: @"Model Demonstrator Failure",
button: MessageBoxButton.OK,
icon: MessageBoxImage.Error);
}
}
}
<file_sep>/src/Knowledge.Accord.Housing/ModelImplementation.cs
using System;
using System.Data;
using System.Diagnostics;
using System.IO;
using Accord.IO;
namespace Knowledge.Accord.Housing
{
internal class ModelImplementation
{
public bool Ready { get; private set; }
public bool ErrorHasOccured { get; private set; } = false;
public string FailureInformation { get; private set; }
public ModelImplementation()
{
Ready = true;
}
public void LoadTrainingDataFromFile(string trainingDataAbsolutePath, bool trainingDataHasHeaders)
{
if (ErrorHasOccured) return;
try
{
using (StreamReader sr = new StreamReader(trainingDataAbsolutePath))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();
DataTable table = CsvReader.FromText(line, trainingDataHasHeaders).ToTable();
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
ErrorHasOccured = true;
FailureInformation = ex.Message;
return;
}
}
}
}<file_sep>/README.md
# KnowledgeSystems
User Group Demonstrator for Machine Learning
## Machine Learning for the Developer – Part 1 (in the slides folder)
Slides: Azure Machine Learning.pptx
Overview: Azure Machine Learning is a cloud predictive analytics service that makes it possible to quickly create and deploy predictive models as analytics solutions. Getting started is easy. The first working prototype is an easy evening project. But Azure Machine Learning will grow to extremely complex projects. This session will demonstrate initial projects utilizing multiple data science principals.
## Machine Learning for the Developer – Part 2
Slides: Machine Learning for the Developer.pptx (in the slides folder)
Source Code: in the src folder
Application of the Microsoft Toolkits, SDKs, and APIs will be surveyed and demonstrated in VS 2019. Particular attention will be given to Azure Cognitive Services, ML.NET, and Microsoft Cognitive Toolkit. How-to examples will include for Classification, Clustering, Regression, Neural Nets, and Vision.
<file_sep>/src/CognitiveServices.VisionLibrary/CognitiveServicesApi.cs
using System.IO;
namespace CognitiveServices.VisionLibrary
{
public class CognitiveServicesRequest
{
public string EndPointKey1 { get; set; }
public string EndPoint { get; set; }
public Stream ImageStream { get; set; }
public string EndPointExtension { get; set; }
public string RestRequestParameters { get; set; }
}
public class CognitiveServicesStringResponse :
CommonFramework.Library.ContractsBaseResponseClass
{
public string RestResponse { get; set; }
}
public class CognitiveServicesStreamResponse :
CommonFramework.Library.ContractsBaseResponseClass
{
public Stream RestResponse { get; set; }
}
}<file_sep>/src/CognitiveServices.VisionLibrary/ComputerVision/ComputerVisionHttpClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Threading.Tasks;
/*
* ProfReynolds
* Computer Vision Quick Start Tutorial
* https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/
*/
namespace CognitiveServices.VisionLibrary.ComputerVision
{
public class ComputerVisionHttpClient : ComputerVisionApi
{
public override async Task<GetVisualFeaturesStringResponse> GetVisualFeatures(CognitiveServicesRequest request)
{
var cognitiveServicesRestHttpClient = new CognitiveServicesRestHttpClient();
var restHttpResponse = await cognitiveServicesRestHttpClient.GetRestHttpStringResponse(request);
var getVisualFeaturesResponse = new GetVisualFeaturesStringResponse
{
Success = restHttpResponse.Success,
ImplementedInModule = restHttpResponse.ImplementedInModule,
FailureInformation = restHttpResponse.FailureInformation,
VisualFeatures =
CommonFramework.Library.Helpers.JsonHelpers.JsonPrettyPrint(restHttpResponse.RestResponse),
};
return getVisualFeaturesResponse;
}
public override async Task<PerformOcrStringResponse> PerformOcr(CognitiveServicesRequest request)
{
var cognitiveServicesRestHttpClient = new CognitiveServicesRestHttpClient();
var restHttpResponse = await cognitiveServicesRestHttpClient.GetRestHttpStringResponse(request);
var performOcrResponse = new PerformOcrStringResponse
{
Success = restHttpResponse.Success,
ImplementedInModule = restHttpResponse.ImplementedInModule,
FailureInformation = restHttpResponse.FailureInformation,
// LinesFound = new List<string>(),
// WordsFound = new List<PerformOcrWordInstance>(),
};
performOcrResponse.LinesFound.Add(CommonFramework.Library.Helpers.JsonHelpers.JsonPrettyPrint(restHttpResponse.RestResponse));
return performOcrResponse;
}
public override async Task<GetThumbnailResponse> GetThumbnail(GetThumbnailRequest request)
{
var cognitiveServicesRestHttpClient = new CognitiveServicesRestHttpClient();
var restHttpResponse = await cognitiveServicesRestHttpClient.GetRestHttpStreamResponse(request);
var servicesStreamResponseApi = new GetThumbnailResponse
{
Success = restHttpResponse.Success,
ImplementedInModule = restHttpResponse.ImplementedInModule,
FailureInformation = restHttpResponse.FailureInformation,
Thumbnail = restHttpResponse.RestResponse,
};
return servicesStreamResponseApi;
}
}
}
<file_sep>/src/CognitiveServices.Demonstrator/CognitiveServicesVisionDemo.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using CommonFramework.Library;
using CognitiveServices.VisionLibrary;
using CognitiveServices.VisionLibrary.ComputerVision;
using Microsoft.Win32;
namespace Knowledge.Demonstrator
{
/// <summary>
/// Interaction logic for CognitiveServicesVisionDemo.xaml
/// </summary>
public partial class CognitiveServicesVisionDemo : Window
{
public CognitiveServicesVisionDemo()
{
InitializeComponent();
}
private string _validatedImageFileLocation = string.Empty;
private ComputerVisionApi _computerVisionApi;
private void Window_Loaded(object sender, RoutedEventArgs e)
{
_validatedImageFileLocation = Properties.Settings.Default.PreviousImagePath;
LblImageFileLocation.Content = _validatedImageFileLocation;
}
private void BtnSelectImage_Click(object sender, RoutedEventArgs e)
{
var openFileDialog1 = new OpenFileDialog
{
Filter =
"All Images Files (*.png;*.jpeg;*.gif;*.jpg;*.bmp;*.tiff;*.tif)|*.png;*.jpeg;*.gif;*.jpg;*.bmp;*.tiff;*.tif" +
"|PNG Portable Network Graphics (*.png)|*.png" +
"|JPEG File Interchange Format (*.jpg *.jpeg *jfif)|*.jpg;*.jpeg;*.jfif" +
"|BMP Windows Bitmap (*.bmp)|*.bmp" +
"|TIF Tagged Imaged File Format (*.tif *.tiff)|*.tif;*.tiff" +
"|GIF Graphics Interchange Format (*.gif)|*.gif",
Title = "Select Image to Utilize",
//FileName = Properties.Settings.Default.PreviousImagePath
};
// Notice: if DialogResult is not OK, the process is short-circuited
if (openFileDialog1.ShowDialog() != true) return;
_validatedImageFileLocation = openFileDialog1.FileName;
this.LblImageFileLocation.Content = _validatedImageFileLocation;
Properties.Settings.Default.PreviousImagePath = _validatedImageFileLocation;
Properties.Settings.Default.Save();
}
private void RadioInterface_Checked(object sender, RoutedEventArgs e)
{
void UiEnabledStatus(bool setAllEnabled)
{
BtnGetVisualFeatures.IsEnabled = setAllEnabled;
BtnRunOcr.IsEnabled = setAllEnabled;
BtnGetThumbnail.IsEnabled = setAllEnabled;
}
UiEnabledStatus(false);
if (!(sender is RadioButton azureInterface)) return;
if (!(azureInterface?.IsChecked ?? false)) return;
switch (azureInterface.Name)
{
case "RadioAzureSdk":
_computerVisionApi = new ComputerVisionAzureSdk();
UiEnabledStatus(true);
break;
case "RadioHttpClient":
_computerVisionApi = new ComputerVisionHttpClient();
UiEnabledStatus(true);
break;
case "RadioProjectOxford":
_computerVisionApi = null;
UiEnabledStatus(false);
break;
default:
_computerVisionApi = null;
break;
}
}
private async void BtnGetVisualFeatures_Click(object sender, RoutedEventArgs e)
{
TxtCognitiveServicesAnalysisResponse.Text = string.Empty;
if (!System.IO.File.Exists(_validatedImageFileLocation)) return;
if (_computerVisionApi == null) return;
var imageStream = CommonFramework.Library.Helpers.ImagesHelpers.GetImagesAsStream(_validatedImageFileLocation);
var request = new CognitiveServicesRequest
{
EndPointKey1 = Properties.Settings.Default.EndPointKey1,
EndPoint = Properties.Settings.Default.EndPoint,
ImageStream = imageStream,
EndPointExtension = "/vision/v2.0/analyze",
RestRequestParameters = "visualFeatures=Categories,Tags,Description,Faces,ImageType,Color,Adult&details=Celebrities,Landmarks&language=en",
};
var response = await _computerVisionApi.GetVisualFeatures(request);
TxtCognitiveServicesAnalysisResponse.Text = response.Success
? response.VisualFeatures
: response.FailureInformation;
}
private async void BtnRunOcr_Click(object sender, RoutedEventArgs e)
{
TxtCognitiveServicesAnalysisResponse.Text = string.Empty;
if (!System.IO.File.Exists(_validatedImageFileLocation)) return;
if (_computerVisionApi == null) return;
var imageStream = CommonFramework.Library.Helpers.ImagesHelpers.GetImagesAsStream(_validatedImageFileLocation);
var request = new CognitiveServicesRequest
{
EndPointKey1 = Properties.Settings.Default.EndPointKey1,
EndPoint = Properties.Settings.Default.EndPoint,
ImageStream = imageStream,
EndPointExtension = "/vision/v2.0/ocr",
RestRequestParameters = "language=unk&detectOrientation=true",
};
var response = await _computerVisionApi.PerformOcr(request);
if (response.Success)
{
var output = new StringBuilder();
foreach (var word in response.WordsFound)
{
output.AppendLine($"{word.Word} --- {word.Instances}");
}
output.AppendLine();
output.AppendLine("=============================================");
output.AppendLine();
output.AppendLine(string.Join("\n", response.LinesFound));
TxtCognitiveServicesAnalysisResponse.Text = output.ToString();
}
else
{
TxtCognitiveServicesAnalysisResponse.Text = response.FailureInformation;
}
}
private async void BtnGetFacialFeatures_Click(object sender, RoutedEventArgs e)
{
TxtCognitiveServicesAnalysisResponse.Text = string.Empty;
if (!System.IO.File.Exists(_validatedImageFileLocation)) return;
var httpClient = new CognitiveServicesRestHttpClient();
var imageStream = CommonFramework.Library.Helpers.ImagesHelpers.GetImagesAsStream(_validatedImageFileLocation);
var request = new CognitiveServicesRequest
{
EndPointKey1 = Properties.Settings.Default.EndPointKey1,
EndPoint = Properties.Settings.Default.EndPoint,
ImageStream = imageStream,
EndPointExtension = "/face/v1.0/detect",
RestRequestParameters = "returnFaceId=true&returnFaceLandmarks=false" +
"&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
"emotion,hair,makeup,occlusion,accessories,blur,exposure,noise",
};
// ReSharper disable once PossibleNullReferenceException
var response = await httpClient.GetRestHttpStringResponse(request);
var visualFeatures = CommonFramework.Library.Helpers.JsonHelpers.JsonPrettyPrint(response.RestResponse);
TxtCognitiveServicesAnalysisResponse.Text = response.Success
? visualFeatures
: response.FailureInformation;
}
private async void BtnGetThumbnail_Click(object sender, RoutedEventArgs e)
{
if (!System.IO.File.Exists(_validatedImageFileLocation)) return;
if (_computerVisionApi == null) return;
var imageStream = CommonFramework.Library.Helpers.ImagesHelpers.GetImagesAsStream(_validatedImageFileLocation);
var width = TxtWidth.Text.ToInt();
var height = TxtHeight.Text.ToInt();
var request = new GetThumbnailRequest()
{
EndPointKey1 = Properties.Settings.Default.EndPointKey1,
EndPoint = Properties.Settings.Default.EndPoint,
ImageStream = imageStream,
EndPointExtension = "/vision/v2.0/generateThumbnail",
RestRequestParameters =
$"width={width}&height={height}&smartCropping={CheckSmartCropping.IsChecked ?? false}",
ThumbnailSize = (Width: width, Height: height, SmartCropping: CheckSmartCropping.IsChecked ?? false),
};
var response = await _computerVisionApi.GetThumbnail(request);
var imageSource = new BitmapImage();
imageSource.BeginInit();
imageSource.StreamSource = response.Thumbnail;
imageSource.EndInit();
ImageThumbnail.Source = response.Success
? imageSource
: null;
}
}
}
<file_sep>/src/Knowledge.ML_NET.Demonstrator/MainWindow.xaml.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Knowledge.ML_NET.Demonstrator.Digits;
namespace Knowledge.ML_NET.Demonstrator
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
InitialControlOccurance.BorderThickness = new Thickness(10);
var demoControl = new DemoControl
{
Width = 100,
Height = MyCanvas.ActualHeight,
BorderThickness = new Thickness(4),
BorderBrush = new SolidColorBrush(Color.FromRgb(255, 0, 0)),
Background = new SolidColorBrush(Color.FromRgb(0, 255, 0)),
Margin = new Thickness(0,0,0,0)
};
MyCanvas.Children.Add(demoControl);
}
}
}
<file_sep>/src/CognitiveServices.VisionLibrary/ComputerVision/ComputerVisionApi.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;
namespace CognitiveServices.VisionLibrary.ComputerVision
{
public class GetVisualFeaturesStringResponse : CognitiveServicesStringResponse
{
public string VisualFeatures { get; set; }
}
public class GetThumbnailRequest : CognitiveServicesRequest
{
public (int Width, int Height, bool SmartCropping) ThumbnailSize { get; set; }
}
public class GetThumbnailResponse : CognitiveServicesStringResponse
{
public Stream Thumbnail = null;
}
public class PerformOcrWordInstance
{
public string Word { get; set; }
public int Instances { get; set; }
}
public class PerformOcrStringResponse : CognitiveServicesStringResponse
{
public IList<string> LinesFound { get; set; } = new List<string>();
public IList<PerformOcrWordInstance> WordsFound { get; set; } = new List<PerformOcrWordInstance>();
}
public abstract class ComputerVisionApi
{
public abstract Task<GetVisualFeaturesStringResponse> GetVisualFeatures(CognitiveServicesRequest request);
public abstract Task<PerformOcrStringResponse> PerformOcr(CognitiveServicesRequest request);
public abstract Task<GetThumbnailResponse> GetThumbnail(GetThumbnailRequest request);
}
}
<file_sep>/src/Knowledge.Accord.Housing/ModelSettings.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Knowledge.Accord.Housing
{
class ModelSettings
{
public static string TrainingData { get; private set; } = System.IO.Path.GetFullPath(@"../../../../Datasets/housing_train.csv");
public static bool TrainingDataHasHeaders { get; } = true;
public static string TestingData { get; private set; } = System.IO.Path.GetFullPath(@"../../../../Datasets/housing_test.csv");
public static bool TestingDataHasHeaders { get; } = true;
}
}
<file_sep>/src/CognitiveServices.VisionLibrary/ComputerVision/ComputerVisionAzureSdk.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision;
using Microsoft.Azure.CognitiveServices.Vision.ComputerVision.Models;
/*
* ProfReynolds
* Computer Vision Quick Start Tutorial
* https://docs.microsoft.com/en-us/azure/cognitive-services/computer-vision/
*/
namespace CognitiveServices.VisionLibrary.ComputerVision
{
public class ComputerVisionAzureSdk : ComputerVisionApi
{
public override async Task<GetVisualFeaturesStringResponse> GetVisualFeatures(CognitiveServicesRequest request)
{
var response = new GetVisualFeaturesStringResponse();
try
{
var apiKeyServiceClientCredentials = new ApiKeyServiceClientCredentials(request.EndPointKey1);
var delegatingHandlers = new System.Net.Http.DelegatingHandler[] { };
IComputerVisionClient computerVision = new ComputerVisionClient(
credentials: apiKeyServiceClientCredentials,
handlers: delegatingHandlers)
{
Endpoint = request.EndPoint
};
IList<VisualFeatureTypes> features = new List<VisualFeatureTypes>()
{
VisualFeatureTypes.ImageType,
VisualFeatureTypes.Faces,
VisualFeatureTypes.Adult,
VisualFeatureTypes.Categories,
VisualFeatureTypes.Color,
VisualFeatureTypes.Tags,
VisualFeatureTypes.Description,
VisualFeatureTypes.Objects,
};
var imageAnalysis = await computerVision.AnalyzeImageInStreamAsync(
image: request.ImageStream,
visualFeatures: features);
var visualFeaturesTemp = new StringBuilder();
visualFeaturesTemp.AppendLine("Description - Captions");
foreach (var item in imageAnalysis.Description.Captions)
{
visualFeaturesTemp.AppendLine($"{item.Text} ({item.Confidence})");
}
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Description - Tags");
visualFeaturesTemp.AppendLine(string.Join(", ", imageAnalysis.Description.Tags));
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Adult / Racy Content");
visualFeaturesTemp.AppendLine($"({imageAnalysis.Adult.AdultScore}) , ({imageAnalysis.Adult.RacyScore})");
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Categories - name, score, detail");
foreach (var item in imageAnalysis.Categories)
{
visualFeaturesTemp.AppendLine($"{item.Name} ({item.Score})");
visualFeaturesTemp.AppendLine($"{item.Detail}");
}
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Color");
visualFeaturesTemp.AppendLine($"{imageAnalysis.Color}");
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Faces - Age, Gender");
foreach (var item in imageAnalysis.Faces)
{
visualFeaturesTemp.AppendLine($"{item.Age} {item.Gender}");
}
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Image Type - ClipArtType, LineDrawingType");
visualFeaturesTemp.AppendLine($"{imageAnalysis.ImageType.ClipArtType} {imageAnalysis.ImageType.LineDrawingType}");
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Objects");
foreach (var item in imageAnalysis.Objects)
{
visualFeaturesTemp.AppendLine($"{item.ObjectProperty} ({item.Confidence})");
}
visualFeaturesTemp.AppendLine("");
visualFeaturesTemp.AppendLine("Tags - Name, Confidence, Hint");
foreach (var item in imageAnalysis.Tags)
{
visualFeaturesTemp.AppendLine($"{item.Name} ({item.Confidence})");
visualFeaturesTemp.AppendLine($"{item.Hint}");
}
response.VisualFeatures = visualFeaturesTemp.ToString();
response.Success = true;
}
catch (Exception e)
{
response.FailureInformation = e.Message;
}
return response;
}
public override async Task<PerformOcrStringResponse> PerformOcr(CognitiveServicesRequest request)
{
var response = new PerformOcrStringResponse();
try
{
var apiKeyServiceClientCredentials = new ApiKeyServiceClientCredentials(request.EndPointKey1);
var delegatingHandlers = new System.Net.Http.DelegatingHandler[] { };
IComputerVisionClient computerVision = new ComputerVisionClient(
credentials: apiKeyServiceClientCredentials,
handlers: delegatingHandlers)
{
Endpoint = request.EndPoint
};
var contentString = await computerVision.RecognizePrintedTextInStreamAsync(
image: request.ImageStream,
detectOrientation: false,
language: OcrLanguages.En,
cancellationToken: CancellationToken.None);
var resultsLinesFound = new List<string>();
var resultsWordsFound = new List<string>();
foreach (OcrRegion region in contentString.Regions)
foreach (OcrLine line in region.Lines)
{
var words = line.Words.Select(word => word.Text).ToList();
resultsWordsFound.AddRange(words);
if (words.Count > 0)
resultsLinesFound.Add(string.Join<string>(" ", words));
}
var wordGrouping =
from word in resultsWordsFound
group word by word
into g
select new { InstanceFound = g.Key, Word = g };
var groupedWordsFound = wordGrouping
.Select(item => new PerformOcrWordInstance
{
Word = item.Word.Key,
Instances = item.Word.Count()
});
response.LinesFound = resultsLinesFound;
response.WordsFound = groupedWordsFound.ToList();
response.Success = true;
}
catch (Exception e)
{
response.FailureInformation = e.Message;
}
return response;
}
public override async Task<GetThumbnailResponse> GetThumbnail(GetThumbnailRequest request)
{
var response = new GetThumbnailResponse();
try
{
var apiKeyServiceClientCredentials = new ApiKeyServiceClientCredentials(request.EndPointKey1);
var delegatingHandlers = new System.Net.Http.DelegatingHandler[] { };
IComputerVisionClient computerVision = new ComputerVisionClient(
credentials: apiKeyServiceClientCredentials,
handlers: delegatingHandlers)
{
Endpoint = request.EndPoint
};
response.Thumbnail = await computerVision.GenerateThumbnailInStreamAsync(
image: request.ImageStream,
width: request.ThumbnailSize.Width,
height: request.ThumbnailSize.Height,
smartCropping: request.ThumbnailSize.SmartCropping);
response.Success = true;
}
catch (Exception e)
{
response.FailureInformation = e.Message;
}
return response;
}
}
}
<file_sep>/src/CognitiveServices.VisionLibrary/CognitiveServicesRestHttpClient.cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using CognitiveServices.VisionLibrary.ComputerVision;
namespace CognitiveServices.VisionLibrary
{
public class CognitiveServicesRestHttpClient
{
public async Task<CognitiveServicesStringResponse> GetRestHttpStringResponse(CognitiveServicesRequest request)
{
var response = new CognitiveServicesStringResponse();
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", request.EndPointKey1);
// Assemble the URI for the REST API method.
var uri = request.EndPoint + request.EndPointExtension + "?" + request.RestRequestParameters;
// Read the contents of the specified local image into a byte array.
byte[] photoBytes = new byte[request.ImageStream.Length];
request.ImageStream.Read(photoBytes, 0, photoBytes.Length);
// Add the byte array as an octet stream to the request body.
using (var byteArrayContent = new ByteArrayContent(photoBytes))
{
// This example uses the "application/octet-stream" content type.
// The other content types you can use are "application/json"
// and "multipart/form-data".
byteArrayContent.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
// Asynchronously call the REST API method.
var responseMessage = await httpClient.PostAsync(uri, byteArrayContent);
response.RestResponse = await responseMessage.Content.ReadAsStringAsync();
response.Success = true;
}
}
catch (Exception e)
{
response.FailureInformation = e.Message;
}
return response;
}
public async Task<CognitiveServicesStreamResponse> GetRestHttpStreamResponse(CognitiveServicesRequest request)
{
var response = new CognitiveServicesStreamResponse();
try
{
var httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", request.EndPointKey1);
var uri = request.EndPoint + request.EndPointExtension + "?" + request.RestRequestParameters;
byte[] photoBytes = new byte[request.ImageStream.Length];
request.ImageStream.Read(photoBytes, 0, photoBytes.Length);
using (var byteArrayContent = new ByteArrayContent(photoBytes))
{
byteArrayContent.Headers.ContentType =
new System.Net.Http.Headers.MediaTypeHeaderValue("application/octet-stream");
var responseMessage = await httpClient.PostAsync(uri, byteArrayContent);
var readAsByteArrayAsync = await responseMessage.Content.ReadAsByteArrayAsync();
response.RestResponse = new MemoryStream(readAsByteArrayAsync);
response.Success = true;
}
}
catch (Exception e)
{
response.FailureInformation = e.Message;
}
return response;
}
}
}
|
13004c98e706d6f1488663f1c92ebc5956be7940
|
[
"Markdown",
"C#"
] | 12 |
C#
|
ProfReynolds/KnowledgeSystems
|
a318ac6b9eefae998cf4c0127ffb9d52ad142d69
|
ff979c07b0dee9049e78a5c9581b38a3d454de84
|
refs/heads/master
|
<file_sep>module sequoia-backend-assignment
go 1.14
require (
github.com/0xAX/notificator v0.0.0-20191016112426-3962a5ea8da1 // indirect
github.com/codegangsta/envy v0.0.0-20141216192214-4b78388c8ce4 // indirect
github.com/codegangsta/gin v0.0.0-20171026143024-cafe2ce98974 // indirect
github.com/go-redis/redis v6.15.8+incompatible
github.com/jinzhu/gorm v1.9.15
github.com/labstack/echo/v4 v4.1.16
github.com/mattn/go-shellwords v1.0.10 // indirect
github.com/sirupsen/logrus v1.6.0
gopkg.in/urfave/cli.v1 v1.20.0 // indirect
)
<file_sep>package cfg
/*-------------------------------------------------------------------------------------*/
type User struct {
ID int `json:"user_id" gorm:"column:id;PRIMARY_KEY;AUTO_INCREMENT"`
Email string `json:"email" gorm:"column:email;unique;not null"`
RoleID *int `json:"role_id" gorm:"column:role_id"`
}
func (User) TableName() string {
return "user"
}
/*-------------------------------------------------------------------------------------*/
<file_sep>package cfg
import (
"net/http"
"github.com/labstack/echo/v4"
)
func rootPingHandler(c echo.Context) error {
return c.String(http.StatusOK, `rtw service is running under route route => /rtw-backend`)
}
func rtwEntryPingHandler(c echo.Context) error {
return c.String(http.StatusOK, `rtw service is running`)
}
<file_sep># Learning new language challenges
### How to setup routes or project structure ?
<file_sep>Go live server:
https://github.com/codegangsta/gin
Data types in Golang:
Structs:
Mind the names start with capital letter
type Doctor struct {
Number int
CctorName string
Companions []string
}
aDoctor:= Doctor{
Number: 3
ActorName: “David,
Companions []string {
“<NAME>”,
“Anil”
},
}
//////
Anonymous struct declaration and definition
aDoctor : struct{name string} {name: “Anil”}
Structs are value type
anotherDoctor:= aDoctor
anotherDoctor.name = “sunil”
Result will be
aDoctor.name = “Anil”
anotherDoctor.name = “sunil”
Embedding model with structs:
type Animal struct {
Name string
Origin string
}
type Bird Struct {
Animal
CanFly bool
}
//////// First way
B: = Bird{}
B.Name = “Emu”
B.Origin = “Australia”
B.CanFly= 48
///// Second way:
B:= Bird {
Animal: Animal{Name: “Emu”, “Origin”: “Austraila”},
CanFly: false
}
Tags
type struct {
Name string `required max: “100”`
Origin string `required max: “50”`
}
Import “reflect”
T:= reflect.TypeOf(Animal{})
field, \_ := t.FieldByName(“Name”)
fmt.Println(field.Tag)
Maps:
v := make([string]int)
v = map[string]int{
“A”: 1,
“B”: 2
}
Access v[“A”]
Update v[“B”] = 8
delete(v, “A”)
If v[A] is not there, then it will give 0
Return order of map is not guaranteed
\_, ok := v[A]
if(!ok) {
fmt.Println(“not there”, ok)
}
len(v) for length for the map
These are passed by reference.
Queries
package main
import "fmt"
type CoffeeMachine struct {
NumberOfCoffeeBeans int
}
func NewCoffeeMachine() \*CoffeeMachine {
return &CoffeeMachine{}
}
func (cm \*CoffeeMachine) SetNumberOfCoffeeBeans(n int) {
cm.NumberOfCoffeeBeans = n
}
func main() {
cm := NewCoffeeMachine()
fmt.Println(cm)
cm.SetNumberOfCoffeeBeans(100)
fmt.Printf("The coffee machine has %d beans\n", cm.NumberOfCoffeeBeans)
}
If Statement
If pop, ok := simecheck(); ok {
fmt.Println(pop)
Pop variable is only accessible inside it, not outside
}
fmt.Println(pop) // it will be error
Switch Statement
Switch with tag here 2 is the tag which will be checked in switch.
Switch 2 {
case 1:
fmt.Println(“one”)
case 2:
fmt.Println(“two”)
default :
fmt.Println()
}
// two will get printed out
case 1, 5, 10:
fmt.Println(“It will check 1, 5 10”)
/////
switch i:= 2 + r; i {
Case 1,5,10
}
///////
Switch without tag
Without tags, first pass will run only
It has implicit breaks
i:=10
Switch {
Case i <=10:
Dada
saasdad
Case i <=20:
sdadsds
}
Fallthrough
i:=10
Switch {
Case i <=10:
Dada
saasdad
fallthrough
Case i <=20:
sdadsds
}
Both the condition when i < 10 and also i <=20
var i interface {} = 1
Switch i.(type) {
case int:
Sadsds
case float64:
Asdsads
case string:
Sdadsad
default:
fmt.Print
}
You can aslo make use of break keyword to coume out of switch
For loop
i is scoped to only for loop
for i:=0; i<5;i++ {
}
for i, j:=0, 0; i<5;i, j = i + 1, j+ 1 {
}
i:=0
for ; i<5;i++ {
}
i is scoped to main function above in this specific case
For range loop
s:= []int{1,2,3}
for k, v: range s {
fmt.Println(k, v)
}
This way you can also loop map
Ansn also string
s:= “sdadad”
for k, v: range s {
fmt.Println(k, string(v))
}
DE
Defer, Panic and Recover
Defer
It executes the statement after the last statement is excited in wrapped function and then call the defer statement before returning
Defer follow stack order
Defer dad /// 1
Defer sdadc // 2
Defer sddcsd //3
3/2/1
/////
a:= “start”
defer fmt.Println(a) // start
a = “end”
Panic
a, b = 1, 0
ans:= a/b
fmt.Println(ans)
Will throw error
panic(“something bad happened”)
Panic always run after the defer statements
defer func() {
}()
Recover read more about it, but it like catch statement in javascript
Pointer
Pointer arithmetic is not allowed in golang directly
Pointers arithmetic is available in ‘unsafe’ package
package main
import "fmt"
type A struct {
B int
E string
}
func main() {
c:= A{2, "anil"}
d:= &c
fmt.Println(d)
}
// output &{2 anil}
Just a representation telling it is a pointer holding on two this value
Var ms \* mystruct
Ms = new(mystruct)
Ms.foo = 42
fmt.Println(ms.foo)
Var ms * mystruct
Ms = new(mystruct)
(*ms).foo = 42
fmt.Println((\*ms).foo)
Slice and Array
In slices changes the original array
But in case of array we change the copy.
Slices and maps are like object passed around
But arrays are passed by deep immutable new structure
// Pending new operator
Functions
Variadic parameters
func sum(msg string,values ...int) {
Result : =0
for \_, v:=range values {
result +=v
}
fmt.Println()
}
Panic means application cannot continue
This is also valid
var f func() = func() {
}
f()
Var divide func(float64 , float64) (float64, error)
divide = func(afloat64 , bfloat64) (float64, error) {
}
Type greeter struct {
greeting string
name string
}
// Copy example
Value reciever
func (g greeter) greet() {
fmt.Println(g)
}
Pointer reciever
func (g greeter) greet() {
fmt.Println(g)
}
Using pointer receiver is good in case , when you need to change the original object.
Interfaces
They describe behaviour not data
Import “fmt”
type Writer interface {
Write([]byte) (int, error)
}
In go we implicitly implement interfaces, there is not keyword like implements
type ConsoleWriter struct {}
func (cw ConsoleWriter) Write(data []byte) (int, error) {
n, err = fmt.Println(string(data))
Return n, error
}
In Main method
Var w Writer = ConsoleWriter{}
w.Write([]byte(“Hello Go!”))
Append er to interface names
Anything ending with er is mostly interface
We can compose two or more interface and declare a new interface
Var myObj interface{} = NewBufferWriterCloser()
For empty interface , you need to use type case or type conversion
myObj.(WriterCLoser)
…….
Interface type conversion
Bwc, ok := wc.(\*BufferWriterCOloser)
The object with having implementation based on a same interface can be converted interchangeably
The method receiver also need to be same when doing the conversion
Var myObj interface{} = NewBufferedWWriteCloser()
Types switches
Var i interface{} = 0
Switch i.(type) {
Case int:
asSSD
CASE STRING:
SASADsadasdd
default :
csacadad
}
https://youtu.be/YS4e4q9oBaU?t=19241 for specidal behaviour of interface amd methods
Types methods each one of methods regardless of receiver types
Implement interface with concrete value :
Method set of value, any method set with value as a receiver. And it makes method set is incomplete.
If I am implementing an interface, if i am using a value type, the method that implements the interface have to have the value receivers
If I am implementing an interface, if i am using a pointertype, the method can be there regardless of receiver types
io.Writer, io.Reader, interface{}
GoRoutines:
func main() {
go sayHello()
}
func sayHello() {
fmt.Println(“sdasd”)
}
Green thread
Above code will not print the
func main() {
go sayHello()
time.Sleep(100\* time.Millisecond)
}
func sayHello() {
fmt.Println(“sdasd”)
}
Above is one of the hack
func main() {
go func() {
fmt.Println(“sdasd”)
}()
time.Sleep(100\* time.Millisecond)
}
func main() {
Var msg = “hello”
go func() {
fmt.Println(msg)
}()
msg = “opjo”
time.Sleep(100\* time.Millisecond)
}
Opjo will get printed
////////
Var wg = sync.WaitGroup{}
func main() {
Var msg = “hello”
wg.Add(1)
go func() {
fmt.Println(msg)
wg.Done()
}()
msg = “opjo”
wg.Wait()
}
Mutex
Var m = sync.RWMutex{}
Import “runtime”
runtime.Gomaxprocs(100)
Best practices:
Donot create go routines for library
Know how it will end
Let the consumer of the library set the no of threads
Debugiging
go run -race pathtofile.go
Channels
Var wg = sync.WaitGroup()
Func main() {
ch: make(chan, int)
wg.Add(2)
Go func() {
i:= <- ch
fmt.Println(i)
wg.Done()
}()
Go func() {
i:= 42
Ch <- i
fmt.Println(i)
wg.Done()
}()
}
wg.Wait()
Concept of receiver anf sender goroutine
Send only and receive only channel
Buffered channel
ch: make(chan int, 50)
ch:= make(chan int, 50)
wg.Add(2)
// Receive only channel
go func(ch <- chan int) {
i:= <-ch
fmt.Println(i)
wg.Done()
}(ch)
// Send only channel
go func(ch chan<- int) {
Ch <-42
Ch <-27
fmt.Println(i)
wg.Done()
}(ch)
wg.Wait()
// Make use of for looping strategy
// Receive only channel
go func(ch <- chan int) {
i:= <-ch
for i:= range ch{
fmt.Println
}
wg.Done()
}(ch)
// Send only channel
go func(ch chan<- int) {
Ch <-42
Ch <-27
fmt.Println(i)
wg.Done()
}(ch)
wg.Wait()
In case of channel range the first
for i:= range ch{
fmt.Println
}
I is the value itself
You can close the channel with
close(ch)
You cannot send a message to a closed channel
/// on receiver side
for {
If i, ok := <-ch;ok {
fmt.Println(i)
} else {
break
}
<file_sep>package cfg
import (
"fmt"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql"
)
func IntializeDatabase() (*gorm.DB, error) {
db, err := gorm.Open("mysql", "root:Stack@123@/trello_app?charset=utf8&parseTime=True&loc=Local")
if err != nil {
fmt.Println("err is ", err)
} else {
fmt.Println("Database connection successfull")
}
// v := db.Ping()
// if v != nil {
// panic(v.Error()) // proper error handling instead of panic in your app
// }
// defer db.Close()
return db, err
}
<file_sep>package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
"sequoia-backend-assignment/packages/trelloboard/cfg"
"github.com/jinzhu/gorm"
)
var db *gorm.DB
var err error
func createUser(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Not valid route !", 404)
}
defer r.Body.Close()
// body, err := ioutil.ReadAll(r.Body)
// fmt.Println(body)
var result *cfg.User
json.NewDecoder(r.Body).Decode(&result)
fmt.Println("result decoded", result)
result.RoleID = nil
db.Create(result)
if err != nil {
http.Error(w, "Not able to read he body !", 404)
}
fmt.Println("Reached the post handle")
}
func getUsers(w http.ResponseWriter, r *http.Request) {
if r.Method != "GET" {
http.Error(w, "Not valid route !", 404)
}
defer r.Body.Close()
// body, err := ioutil.ReadAll(r.Body)
// fmt.Println(body)
var result []cfg.User
errDb := db.Raw(`
SELECT *
FROM user
`).Scan(&result).Error
if errDb != nil {
http.Error(w, "Not able to get the results !", 404)
}
json.NewEncoder(w).Encode(result)
fmt.Println("Reached the get handle")
}
func pingHandler(w http.ResponseWriter, r *http.Request) {
if r.URL.Path != "/hello" {
http.Error(w, "404 not found.", http.StatusNotFound)
}
if r.Method != "GET" {
http.Error(w, "Method is not supported.", http.StatusNotFound)
return
}
fmt.Fprintf(w, "Success")
}
func main() {
t := "Hello World"
fmt.Println("t is", t)
db, err = cfg.IntializeDatabase()
defer db.Close()
fmt.Println(db, err)
// Handle the /hello request get request
// func(w http.ResponseWriter, r *http.Request) {
// fmt.Fprintf(w, "Hello!")
// }
http.HandleFunc("/ping", pingHandler)
http.HandleFunc("/create-user", createUser)
http.HandleFunc("/get-users", getUsers)
fmt.Printf("Starting server at port 8080\n")
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
}
}
|
4fff2bb99304c47fc023f8dfbac0cdde495a1f60
|
[
"Go",
"Go Module",
"Markdown"
] | 7 |
Go Module
|
simbathesailor/golang-learn
|
9649ac4c584aaa9eb88c44d1ca793dbd52b70c16
|
a524360655be5229988ad0e44939f311bc9fc66d
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.